-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathkpr_iOS.m
734 lines (633 loc) · 21.7 KB
/
kpr_iOS.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/*
* Copyright (C) 2010-2015 Marvell International Ltd.
* Copyright (C) 2002-2010 Kinoma, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kpr.h"
#include "kprImage.h"
#include "kprMessage.h"
#include "kprShell.h"
#include "kprURL.h"
#include "kprUtilities.h"
#if TARGET_OS_IPHONE
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetExportSession.h>
#import <MediaPlayer/MediaPlayer.h>
#import "kpr_iOS.h"
#import "FskCocoaApplicationPhone.h"
#import "FskCocoaViewControllerPhone.h"
static void KprALServiceStart(KprService self, FskThread thread, xsMachine* the);
static void KprALServiceStop(KprService self);
static void KprALServiceCancel(KprService self, KprMessage message);
static void KprALServiceInvoke(KprService self, KprMessage message);
KprServiceRecord gALService = {
NULL,
kprServicesThread,
"assets-library:",
NULL,
NULL,
KprServiceAccept,
KprALServiceCancel,
KprALServiceInvoke,
KprALServiceStart,
KprALServiceStop,
NULL,
NULL,
NULL
};
typedef struct {
KprMessage message;
ALAssetsLibrary* library;
FskGrowableStorage buffer;
} KprALTargetRecord, *KprALTarget;
FskErr KprALTargetNew(KprALTarget* it, KprMessage message)
{
KprALTarget self;
FskErr err = kFskErrNone;
bailIfError(FskMemPtrNewClear(sizeof(KprALTargetRecord), it));
self = *it;
self->message = message;
self->library = [[ALAssetsLibrary alloc] init];
bailIfError(FskGrowableStorageNew(1024, &self->buffer));
bail:
return err;
}
void KprALTargetCancel(KprMessage message, void* it)
{
// KprALTarget self = it;
}
void KprALTargetDispose(void* it)
{
KprALTarget self = it;
FskGrowableStorageDispose(self->buffer);
[self->library release];
FskMemPtrDispose(self);
}
static void KprALTargetEnumerateGroupsCallback(KprALTarget target, ALAssetsGroup *group)
{
static char* s0 = "{\"name\":\"";
static char* s1 = "\",\"type\":\"directory\",\"url\":\"";
static char* s2 = "\"},";
FskErr err = kFskErrNone;
KprMessage message = target->message;
UInt32 length;
char* pointer;
char* name = NULL;
char* url = NULL;
if (group == NULL) {
bailIfError(FskGrowableStorageAppendItem(target->buffer, "]", 1));
length = FskGrowableStorageGetSize(target->buffer);
FskGrowableStorageGetPointerToItem(target->buffer, 0, (void **)&pointer);
bailIfError(FskMemPtrNew(length, &message->response.body));
FskMemCopy(message->response.body, pointer, length);
message->response.size = length;
KprMessageTransform(message, gALService.machine);
FskThreadPostCallback(KprShellGetThread(gShell), (FskThreadCallback)KprMessageComplete, message, NULL, NULL, NULL);
}
else {
NSString* _name = [group valueForProperty:ALAssetsGroupPropertyName];
const char* name = [_name UTF8String];
NSURL* _url = [group valueForProperty:ALAssetsGroupPropertyURL];
const char* url = [[_url absoluteString] UTF8String];
bailIfError(FskGrowableStorageAppendItem(target->buffer, s0, FskStrLen(s0)));
bailIfError(FskGrowableStorageAppendItem(target->buffer, name, FskStrLen(name)));
bailIfError(FskGrowableStorageAppendItem(target->buffer, s1, FskStrLen(s1)));
bailIfError(FskGrowableStorageAppendItem(target->buffer, url, FskStrLen(url)));
bailIfError(FskGrowableStorageAppendItem(target->buffer, s2, FskStrLen(s2)));
}
bail:
FskMemPtrDispose(url);
FskMemPtrDispose(name);
}
static void KprALTargetGroupForURLCallback(KprALTarget target, ALAssetsGroup *group)
{
static char* s0 = "{\"mime\":\"image/jpeg\",\"type\":\"file\",\"url\":\"";
static char* s2 = "\"},";
if (group == NULL)
return;
ALAssetsGroupEnumerationResultsBlock enumerationBlock = ^(ALAsset *asset, NSUInteger index, BOOL *stop) {
FskErr err = kFskErrNone;
if (asset == NULL) {
FskErr err = kFskErrNone;
KprMessage message = target->message;
UInt32 length;
char* pointer;
bailIfError(FskGrowableStorageAppendItem(target->buffer, "]", 1));
length = FskGrowableStorageGetSize(target->buffer);
FskGrowableStorageGetPointerToItem(target->buffer, 0, (void **)&pointer);
bailIfError(FskMemPtrNew(length, &message->response.body));
FskMemCopy(message->response.body, pointer, length);
message->response.size = length;
KprMessageTransform(message, gALService.machine);
FskThreadPostCallback(KprShellGetThread(gShell), (FskThreadCallback)KprMessageComplete, message, NULL, NULL, NULL);
}
else {
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *_url = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
const char* url = [[_url absoluteString] UTF8String];
bailIfError(FskGrowableStorageAppendItem(target->buffer, s0, FskStrLen(s0)));
bailIfError(FskGrowableStorageAppendItem(target->buffer, url, FskStrLen(url)));
bailIfError(FskGrowableStorageAppendItem(target->buffer, s2, FskStrLen(s2)));
}
bail:
return;
};
FskGrowableStorageAppendItem(target->buffer, "[", 1);
[group enumerateAssetsUsingBlock:enumerationBlock];
}
static void KprALTargetAssetForURLCallback(KprALTarget target, ALAsset *asset)
{
FskErr err = kFskErrNone;
KprMessage message = target->message;
KprImageTarget stream = (KprImageTarget)message->stream;
char* directory = NULL;
char* path = NULL;
char* url = NULL;
if (stream) {
CGImageRef imageRef;
if (stream->width && stream->height)
imageRef = [asset thumbnail];
else
imageRef = [[asset defaultRepresentation] fullScreenImage];
bailIfNULL(imageRef);
FskRectangleRecord srcRect, dstRect, tmpRect;
FskRectangleSet(&srcRect, 0, 0, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
if (stream->width && stream->height) {
FskRectangleSet(&dstRect, 0, 0, stream->width, stream->height);
if (stream->aspect & kprImageFit)
FskRectangleScaleToFit(&srcRect, &dstRect, &tmpRect);
else
FskRectangleScaleToFill(&srcRect, &dstRect, &tmpRect);
dstRect = tmpRect;
}
else
dstRect = srcRect;
bailIfError(FskBitmapNew(dstRect.width, dstRect.height, kFskBitmapFormatDefaultNoAlpha, &stream->bitmap));
FskBitmapWriteBegin(stream->bitmap, NULL, NULL, NULL);
CGContextDrawImage(FskBitmapGetNativeBitmap(stream->bitmap), CGRectMake(dstRect.x, dstRect.y, dstRect.width, dstRect.height), imageRef);
FskBitmapWriteEnd(stream->bitmap);
}
else {
FskFileInfo info;
ALAssetRepresentation *representation = [asset defaultRepresentation];
FskDirectoryGetSpecialPath(kFskDirectorySpecialTypeTemporary, true, NULL, &directory);
path = FskStrDoCat(directory, [[representation filename] UTF8String]);
url = FskStrDoCat("file://", path);
KprMessageSetResponseHeader(message, "location", url);
KprMessageSetResponseHeader(message, "content-type", "video/mp4");
if (kFskErrNone != FskFileGetFileInfo(path, &info)) {
AVURLAsset* asset = [AVURLAsset URLAssetWithURL:representation.url options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: asset presetName: AVAssetExportPresetMediumQuality];
exporter.outputURL = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]];
exporter.shouldOptimizeForNetworkUse = YES;
exporter.outputFileType = AVFileTypeMPEG4;
[exporter exportAsynchronouslyWithCompletionHandler: ^(void) {
switch ([exporter status]) {
case AVAssetExportSessionStatusFailed:
message->error = kFskErrOperationFailed;
break;
case AVAssetExportSessionStatusCancelled:
message->error = kFskErrOperationCancelled;
break;
default:
break;
}
FskThreadPostCallback(KprShellGetThread(gShell), (FskThreadCallback)KprMessageComplete, message, NULL, NULL, NULL);
}];
err = kFskErrNeedMoreTime;
}
}
bail:
FskMemPtrDispose(url);
FskMemPtrDispose(path);
FskMemPtrDispose(directory);
if (kFskErrNeedMoreTime != err)
FskThreadPostCallback(KprShellGetThread(gShell), (FskThreadCallback)KprMessageComplete, message, NULL, NULL, NULL);
}
void KprALServiceStart(KprService self, FskThread thread, xsMachine* the)
{
self->machine = the;
self->thread = thread;
}
void KprALServiceStop(KprService self UNUSED)
{
}
void KprALServiceCancel(KprService service UNUSED, KprMessage message UNUSED)
{
}
void KprALServiceInvoke(KprService service UNUSED, KprMessage message)
{
FskErr err = kFskErrNone;
KprALTarget target;
if (KprMessageContinue(message)) {
bailIfError(KprALTargetNew(&target, message));
if ((message->parts.authorityLength == 8) && (!FskStrCompareWithLength(message->parts.authority, "pictures", 8))) {
ALAssetsLibraryGroupsEnumerationResultsBlock usingBlock = ^(ALAssetsGroup *group, BOOL *stop) {
KprALTargetEnumerateGroupsCallback(target, group);
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
KprALTargetEnumerateGroupsCallback(target, NULL);
};
NSUInteger groupTypes = ALAssetsGroupAll;
bailIfError(FskGrowableStorageAppendItem(target->buffer, "[", 1));
[target->library enumerateGroupsWithTypes:groupTypes usingBlock:usingBlock failureBlock:failureBlock];
}
else if ((message->parts.authorityLength == 5) && (!FskStrCompareWithLength(message->parts.authority, "group", 5))) {
ALAssetsLibraryGroupResultBlock resultBlock = ^(ALAssetsGroup *group) {
KprALTargetGroupForURLCallback(target, group);
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
KprALTargetGroupForURLCallback(target, NULL);
};
[target->library groupForURL:[NSURL URLWithString:[NSString stringWithUTF8String:message->url]] resultBlock:resultBlock failureBlock:failureBlock];
}
else if ((message->parts.authorityLength == 5) && (!FskStrCompareWithLength(message->parts.authority, "asset", 5))) {
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *asset) {
KprALTargetAssetForURLCallback(target, asset);
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
KprALTargetAssetForURLCallback(target, NULL);
};
[target->library assetForURL:[NSURL URLWithString:[NSString stringWithUTF8String:message->url]] resultBlock:resultBlock failureBlock:failureBlock];
}
else
err = kFskErrUnimplemented;
bail:
if (err) {
message->error = err;
FskThreadPostCallback(KprShellGetThread(gShell), (FskThreadCallback)KprMessageComplete, message, NULL, NULL, NULL);
}
}
}
/*
* Metadata updater
*/
@interface KprSystemNowPlayingInfo : NSObject
+ (KprSystemNowPlayingInfo *)sharedInstance;
@property (nonatomic, readonly) BOOL idling;
@property(retain, atomic) NSDictionary *metadata;
- (void)reset;
- (void)update:(NSDictionary *)info append:(BOOL)append;
- (void)startIdling;
- (void)stopIdling;
@end
void
KprSystemNowPlayingInfoSetIdling(Boolean idling)
{
KprSystemNowPlayingInfo *updater = [KprSystemNowPlayingInfo sharedInstance];
if (idling)
{
if (!updater.idling)
{
[updater startIdling];
}
}
else
{
if (updater.idling)
{
[updater stopIdling];
}
}
}
Boolean
KprSystemNowPlayingInfoGetIdling(void)
{
return [KprSystemNowPlayingInfo sharedInstance].idling ? true : false;
}
static void
appendArtworkToInfo(NSData *data, NSMutableDictionary *info)
{
if (data != nil) {
UIImage *image = [UIImage imageWithData:data];
if (image) {
MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
info[MPMediaItemPropertyArtwork] = artwork;
[artwork release];
}
}
}
void
KprSystemNowPlayingInfoSetMetadata(KprMedia media, FskMediaPropertyValue artwork)
{
NSMutableDictionary *info;
if (media == NULL)
{
[[KprSystemNowPlayingInfo sharedInstance] update:nil append:NO];
return;
}
info = [NSMutableDictionary dictionaryWithCapacity:10];
if (media->artist) {
info[MPMediaItemPropertyArtist] = [NSString stringWithCString:media->artist encoding:NSUTF8StringEncoding];
}
if (media->album) {
info[MPMediaItemPropertyAlbumTitle] = [NSString stringWithCString:media->album encoding:NSUTF8StringEncoding];
}
if (media->title) {
info[MPMediaItemPropertyTitle] = [NSString stringWithCString:media->title encoding:NSUTF8StringEncoding];
}
if (media->duration) {
info[MPMediaItemPropertyPlaybackDuration] = @(media->duration);
}
if (media->cover && (artwork->type == kFskMediaPropertyTypeImage)) {
char* mime = (char*)artwork->value.data.data;
UInt32 mimeLen = FskStrLen(mime) + 1;
NSData *data = [NSData dataWithBytes:artwork->value.data.data + mimeLen length:artwork->value.data.dataSize - mimeLen];
appendArtworkToInfo(data, info);
}
[[KprSystemNowPlayingInfo sharedInstance] update:info append:NO];
}
void
KprSystemNowPlayingInfoSetUPnPMetadata(KprUPnPMetadata metadata)
{
NSMutableDictionary *info;
if (metadata == NULL)
{
[[KprSystemNowPlayingInfo sharedInstance] update:nil append:NO];
return;
}
info = [NSMutableDictionary dictionaryWithCapacity:10];
if (metadata->artist) {
info[MPMediaItemPropertyArtist] = [NSString stringWithCString:metadata->artist encoding:NSUTF8StringEncoding];
}
if (metadata->album) {
info[MPMediaItemPropertyAlbumTitle] = [NSString stringWithCString:metadata->album encoding:NSUTF8StringEncoding];
}
if (metadata->title) {
info[MPMediaItemPropertyTitle] = [NSString stringWithCString:metadata->title encoding:NSUTF8StringEncoding];
}
if (metadata->creator) {
info[MPMediaItemPropertyComposer] = [NSString stringWithCString:metadata->creator encoding:NSUTF8StringEncoding];
}
if (metadata->genre) {
info[MPMediaItemPropertyGenre] = [NSString stringWithCString:metadata->genre encoding:NSUTF8StringEncoding];
}
if (metadata->track) {
info[MPMediaItemPropertyAlbumTrackNumber] = @(metadata->track);
}
if (metadata->duration) {
info[MPMediaItemPropertyPlaybackDuration] = @(metadata->duration);
}
if (metadata->artworkUri) {
NSURL *url = [NSURL URLWithString:[NSString stringWithCString:metadata->artworkUri encoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:(NSURLRequest*) request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* connectionError) {
if (connectionError == nil) {
appendArtworkToInfo(data, info);
}
}];
}
[[KprSystemNowPlayingInfo sharedInstance] update:info append:NO];
}
void
KprSystemNowPlayingInfoSetNativeMetadata(void *metadataIn, Boolean append)
{
NSMutableDictionary *info = (NSMutableDictionary *)metadataIn;
[[KprSystemNowPlayingInfo sharedInstance] update:info append:append];
}
void
KprSystemNowPlayingInfoSetTime(double duration, double position)
{
NSDictionary *info = @{MPMediaItemPropertyPlaybackDuration: @(duration), MPNowPlayingInfoPropertyElapsedPlaybackTime: @(position), MPNowPlayingInfoPropertyPlaybackRate: @1.0};
[[KprSystemNowPlayingInfo sharedInstance] update:info append:YES];
}
@implementation KprSystemNowPlayingInfo {
NSTimer *_timer;
}
static KprSystemNowPlayingInfo *metadataUpdater = NULL;
+ (KprSystemNowPlayingInfo *)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
metadataUpdater = [[KprSystemNowPlayingInfo alloc] init];
});
return metadataUpdater;
}
- (id)init
{
self = [super init];
if (self) {
[self reset];
}
return self;
}
- (void)reset
{
self.metadata = @{};
}
- (void)update:(NSDictionary *)info append:(BOOL)append
{
if (append == NO) {
[self reset];
}
NSMutableDictionary *metadata = [NSMutableDictionary dictionaryWithDictionary:self.metadata];
[metadata addEntriesFromDictionary:info];
self.metadata = metadata;
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = metadata;
}
- (void)startIdling
{
if (_timer) return;
_timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(idle:) userInfo:nil repeats:YES] retain];
_idling = YES;
}
- (void)stopIdling
{
if (_timer == nil) return;
[_timer invalidate];
[_timer release];
_timer = nil;
_idling = NO;
}
- (void)idle:(NSTimer *)timer
{
FskCocoaViewController *viewController = [FskCocoaApplication sharedApplication].mainViewController;
if ([viewController isDisplayLinkActive] == NO) {
FskEvent fskEvent;
FskTimeRecord updateTime;
FskWindow win = viewController.fskWindow;
FskTimeGetNow(&updateTime);
FskErr err = FskEventNew(&fskEvent, kFskEventWindowBeforeUpdate, &updateTime, kFskEventModifierNotSet);
if (err == kFskErrNone) FskWindowEventSend(win, fskEvent);
}
}
- (void)dealloc
{
self.metadata = nil;
[self stopIdling];
[super dealloc];
}
@end
/*
* Tone Generator
*/
@interface ToneGenerator : NSObject
+ (ToneGenerator *)sharedInstance;
@property(assign) double frequency;
@property(assign) double sampleRate;
@property(assign) double amplitude;
- (BOOL)play;
- (void)stop;
- (BOOL)isPlaying;
@end
void KprToneGeneratorPlay()
{
[[ToneGenerator sharedInstance] play];
}
void KprToneGeneratorStop()
{
[[ToneGenerator sharedInstance] stop];
}
@implementation ToneGenerator {
AudioComponentInstance toneUnit;
double theta;
BOOL _playing;
}
+ (ToneGenerator *)sharedInstance
{
static ToneGenerator *shared = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
shared = [[ToneGenerator alloc] init];
shared.frequency = 220;
shared.amplitude = 0;
});
return shared;
}
- (instancetype)init
{
self = [super init];
if (self) {
_frequency = 440;
_amplitude = 0.25;
_sampleRate = 44100;
// Configure the search parameters to find the default playback output unit
// (called the kAudioUnitSubType_RemoteIO on iOS but
// kAudioUnitSubType_DefaultOutput on Mac OS X)
AudioComponentDescription defaultOutputDescription;
defaultOutputDescription.componentType = kAudioUnitType_Output;
defaultOutputDescription.componentSubType = kAudioUnitSubType_RemoteIO;
defaultOutputDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
defaultOutputDescription.componentFlags = 0;
defaultOutputDescription.componentFlagsMask = 0;
// Get the default playback output unit
AudioComponent defaultOutput = AudioComponentFindNext(NULL, &defaultOutputDescription);
NSAssert(defaultOutput, @"Can't find default output");
// Create a new unit based on this that we'll use for output
OSStatus err = AudioComponentInstanceNew(defaultOutput, &toneUnit);
NSAssert1(toneUnit, @"Error creating unit: %d", (int)err);
// Set our tone rendering function on the unit
AURenderCallbackStruct input;
input.inputProc = RenderTone;
input.inputProcRefCon = (__bridge void *)(self);
err = AudioUnitSetProperty(toneUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input,
0,
&input,
sizeof(input));
NSAssert1(err == noErr, @"Error setting callback: %d", (int)err);
// Set the format to 32 bit, single channel, floating point, linear PCM
const int four_bytes_per_float = 4;
const int eight_bits_per_byte = 8;
AudioStreamBasicDescription streamFormat;
streamFormat.mSampleRate = self.sampleRate;
streamFormat.mFormatID = kAudioFormatLinearPCM;
streamFormat.mFormatFlags =
kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
streamFormat.mBytesPerPacket = four_bytes_per_float;
streamFormat.mFramesPerPacket = 1;
streamFormat.mBytesPerFrame = four_bytes_per_float;
streamFormat.mChannelsPerFrame = 1;
streamFormat.mBitsPerChannel = four_bytes_per_float * eight_bits_per_byte;
err = AudioUnitSetProperty (toneUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&streamFormat,
sizeof(AudioStreamBasicDescription));
NSAssert1(err == noErr, @"Error setting stream format: %d", (int)err);
// Stop changing parameters on the unit
err = AudioUnitInitialize(toneUnit);
NSAssert1(err == noErr, @"Error initializing unit: %d", (int)err);
}
return self;
}
- (void)dealloc
{
if ([self isPlaying]) [self stop];
AudioUnitUninitialize(toneUnit);
AudioComponentInstanceDispose(toneUnit);
[super dealloc];
}
- (NSString *)description
{
return [NSString stringWithFormat:@"Tone %4.1f Hz x %d%%", self.frequency, (int)(self.amplitude * 100)];
}
- (BOOL)play
{
// Start playback
OSStatus err = AudioOutputUnitStart(toneUnit);
NSAssert1(err == noErr, @"Error starting unit: %d", (int)err);
_playing = (err == noErr);
return _playing;
}
- (void)stop
{
AudioOutputUnitStop(toneUnit);
_playing = NO;
}
- (BOOL)isPlaying
{
return _playing;
}
- (void)renderIntoBufferList:(AudioBufferList *)bufferList count:(UInt32)count
{
// Fixed amplitude is good enough for our purposes
const double amplitude = self.amplitude;
// This is a mono tone generator so we only need the first buffer
const int channel = 0;
Float32 *buffer = (Float32 *)bufferList->mBuffers[channel].mData;
if (amplitude > 0) {
const double theta_increment = 2.0 * M_PI * self.frequency / self.sampleRate;
// Generate the samples
for (UInt32 frame = 0; frame < count; frame++) {
buffer[frame] = sin(theta) * amplitude;
theta += theta_increment;
if (theta > 2.0 * M_PI) {
theta -= 2.0 * M_PI;
}
}
} else {
memset(buffer, 0, count);
}
}
static OSStatus RenderTone(
void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData)
{
// Get the tone parameters out of the view controller
ToneGenerator *generator = (__bridge ToneGenerator *)inRefCon;
[generator renderIntoBufferList:ioData count:inNumberFrames];
return noErr;
}
@end
#endif