-
Notifications
You must be signed in to change notification settings - Fork 9
/
AudioPlayer.m
2177 lines (1720 loc) · 66.4 KB
/
AudioPlayer.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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* $Id$
*
* Copyright (C) 2006 - 2007 Stephen F. Booth <me@sbooth.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#import "AudioPlayer.h"
#import "AudioScheduler.h"
#import "ScheduledAudioRegion.h"
#import "AudioLibrary.h"
#import "AudioStream.h"
#include <CoreServices/CoreServices.h>
#include <CoreAudio/CoreAudio.h>
// ========================================
// Utility functions
// ========================================
static BOOL
channelLayoutsAreEqual(AudioChannelLayout *layoutA,
AudioChannelLayout *layoutB)
{
// First check if the tags are equal
if(layoutA->mChannelLayoutTag != layoutB->mChannelLayoutTag)
return NO;
// If the tags are equal, check for special values
if(kAudioChannelLayoutTag_UseChannelBitmap == layoutA->mChannelLayoutTag)
return (layoutA->mChannelBitmap == layoutB->mChannelBitmap);
if(kAudioChannelLayoutTag_UseChannelDescriptions == layoutA->mChannelLayoutTag) {
if(layoutA->mNumberChannelDescriptions != layoutB->mNumberChannelDescriptions)
return NO;
unsigned bytesToCompare = layoutA->mNumberChannelDescriptions * sizeof(AudioChannelDescription);
return (0 == memcmp(&layoutA->mChannelDescriptions, &layoutB->mChannelDescriptions, bytesToCompare));
}
return YES;
}
// ========================================
// Constants
// ========================================
NSString * const AUTypeKey = @"componentType";
NSString * const AUSubTypeKey = @"componentSubType";
NSString * const AUManufacturerKey = @"componentManufacturer";
NSString * const AUNameStringKey = @"name";
NSString * const AUManufacturerStringKey = @"manufacturer";
NSString * const AUNameAndManufacturerStringKey = @"nameAndManufacturer";
NSString * const AUInformationStringKey = @"information";
NSString * const AUIconKey = @"icon";
NSString * const AUClassDataKey = @"classData";
NSString * const AUNodeKey = @"AUNode";
NSString *const AudioPlayerErrorDomain = @"org.sbooth.Play.ErrorDomain.AudioPlayer";
// ========================================
// AUGraph manipulation
// ========================================
@interface AudioPlayer (AUGraphMethods)
- (AUGraph) auGraph;
- (OSStatus) setupAUGraph;
- (OSStatus) teardownAUGraph;
- (OSStatus) resetAUGraph;
- (OSStatus) startAUGraph;
- (OSStatus) stopAUGraph;
- (OSStatus) getAUGraphLatency:(Float64 *)graphLatency;
- (OSStatus) getAUGraphTailTime:(Float64 *)graphTailTime;
- (OSStatus) setAUGraphFormat:(AudioStreamBasicDescription)format;
- (OSStatus) setAUGraphChannelLayout:(AudioChannelLayout)channelLayout;
- (OSStatus) setPropertyOnAUGraphNodes:(AudioUnitPropertyID)propertyID data:(const void *)propertyData dataSize:(UInt32)propertyDataSize;
- (AUNode) limiterNode;
- (AUNode) outputNode;
- (void) saveEffectsToDefaults;
- (void) restoreEffectsFromDefaults;
@end
// ========================================
// Private methods
// ========================================
@interface AudioPlayer (Private)
- (AudioScheduler *) scheduler;
- (BOOL) canPlay;
- (void) uiTimerFireMethod:(NSTimer *)theTimer;
- (NSRunLoop *) runLoop;
- (void) setPlaying:(BOOL)playing;
// Accessor is public
- (void) setTotalFrames:(SInt64)totalFrames;
- (SInt64) startingFrame;
- (void) setStartingFrame:(SInt64)startingFrame;
- (SInt64) playingFrame;
- (void) setPlayingFrame:(SInt64)playingFrame;
- (void) setOutputDeviceUID:(NSString *)deviceUID;
- (OSStatus) setOutputDeviceSampleRate:(Float64)sampleRate;
- (BOOL) outputDeviceIsHogged;
- (OSStatus) startHoggingOutputDevice;
- (OSStatus) stopHoggingOutputDevice;
- (OSStatus) startListeningForSampleRateChangesOnOutputDevice;
- (OSStatus) stopListeningForSampleRateChangesOnOutputDevice;
- (void) outputDeviceSampleRateChanged;
- (void) setHasReplayGain:(BOOL)hasReplayGain;
- (void) setReplayGain:(float)replayGain;
- (void) prepareToPlayStream:(AudioStream *)stream;
- (NSNumber *) setReplayGainForStream:(AudioStream *)stream;
- (void) setFormat:(AudioStreamBasicDescription)format;
- (void) setChannelLayout:(AudioChannelLayout)channelLayout;
@end
// ========================================
// AUEventListener callbacks
// ========================================
static void
myAUEventListenerProc(void *inCallbackRefCon,
void *inObject,
const AudioUnitEvent *inEvent,
UInt64 inEventHostTime,
Float32 inParameterValue)
{
// AudioPlayer *myself = (AudioPlayer *)inCallbackRefCon;
if(kAudioUnitEvent_ParameterValueChange == inEvent->mEventType) {
}
}
// ========================================
// AudioDevicePropertyListener callbacks
// ========================================
static OSStatus
myAudioDevicePropertyListenerProc( AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
void* inClientData)
{
AudioPlayer *myself = (AudioPlayer *)inClientData;
if(kAudioDevicePropertyNominalSampleRate == inPropertyID)
[myself outputDeviceSampleRateChanged];
return noErr;
}
@implementation AudioPlayer
+ (void) initialize
{
[self exposeBinding:@"volume"];
[self exposeBinding:@"currentFrame"];
[self exposeBinding:@"totalFrames"];
[self exposeBinding:@"hasValidStream"];
[self exposeBinding:@"streamSupportsSeeking"];
[self setKeys:[NSArray arrayWithObject:@"hasValidStream"] triggerChangeNotificationsForDependentKey:@"streamSupportsSeeking"];
[self setKeys:[NSArray arrayWithObject:@"hasValidStream"] triggerChangeNotificationsForDependentKey:@"currentFrame"];
[self setKeys:[NSArray arrayWithObject:@"hasValidStream"] triggerChangeNotificationsForDependentKey:@"totalFrames"];
[self setKeys:[NSArray arrayWithObject:@"currentFrame"] triggerChangeNotificationsForDependentKey:@"currentSecond"];
[self setKeys:[NSArray arrayWithObject:@"currentFrame"] triggerChangeNotificationsForDependentKey:@"secondsRemaining"];
[self setKeys:[NSArray arrayWithObject:@"totalFrames"] triggerChangeNotificationsForDependentKey:@"totalSeconds"];
}
- (id) init
{
if((self = [super init])) {
_runLoop = [[NSRunLoop currentRunLoop] retain];
OSStatus err = AUEventListenerCreate(myAUEventListenerProc, self,
CFRunLoopGetCurrent(), kCFRunLoopDefaultMode,
0.1, 0.1,
&_auEventListener);
if(noErr != err) {
[self release];
return nil;
}
[self setupAUGraph];
_scheduler = [[AudioScheduler alloc] init];
[_scheduler setAudioUnit:_generatorUnit];
[_scheduler setDelegate:self];
// Set up a timer to update the UI 4 times per second
_timer = [NSTimer timerWithTimeInterval:0.25 target:self selector:@selector(uiTimerFireMethod:) userInfo:nil repeats:YES];
// Add to all three run loop modes to ensure playback progress is always displayed
[_runLoop addTimer:_timer forMode:NSDefaultRunLoopMode];
[_runLoop addTimer:_timer forMode:NSModalPanelRunLoopMode];
// [_runLoop addTimer:_timer forMode:NSEventTrackingRunLoopMode];
// Set the output device
[self setOutputDeviceUID:[[NSUserDefaults standardUserDefaults] objectForKey:@"outputAudioDeviceUID"]];
// Listen for changes to the output device
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self
forKeyPath:@"values.outputAudioDeviceUID"
options:0
context:NULL];
}
return self;
}
- (void) dealloc
{
[_timer invalidate], _timer = nil;
if([self outputDeviceIsHogged])
[self stopHoggingOutputDevice];
OSStatus err = AUListenerDispose(_auEventListener);
if(noErr != err)
NSLog(@"AudioPlayer: AUListenerDispose failed: %i", err);
[[self scheduler] stopScheduling];
[self teardownAUGraph];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self
forKeyPath:@"values.outputAudioDeviceUID"];
[_runLoop release], _runLoop = nil;
[_scheduler release], _scheduler = nil;
[super dealloc];
}
- (AudioLibrary *) owner { return [[_owner retain] autorelease]; }
- (void) setOwner:(AudioLibrary *)owner { [_owner release], _owner = [owner retain]; }
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if(object == [NSUserDefaultsController sharedUserDefaultsController] && [keyPath isEqualToString:@"values.outputAudioDeviceUID"])
[self setOutputDeviceUID:[[NSUserDefaults standardUserDefaults] objectForKey:@"outputAudioDeviceUID"]];
}
#pragma mark Stream Management
- (BOOL) setStream:(AudioStream *)stream error:(NSError **)error
{
NSParameterAssert(nil != stream);
[[self scheduler] stopScheduling];
[[self scheduler] clear];
[self stopAUGraph];
[self setPlaying:NO];
_regionStartingFrame = 0;
OSStatus err = [self resetAUGraph];
if(noErr != err)
NSLog(@"AudioPlayer error: Unable to reset AUGraph AudioUnits: %i", err);
id <AudioDecoderMethods> decoder = [stream decoder:error];
if(nil == decoder)
return NO;
AudioStreamBasicDescription format = [self format];
AudioStreamBasicDescription newFormat = [decoder format];
AudioChannelLayout channelLayout = [self channelLayout];
AudioChannelLayout newChannelLayout = [decoder channelLayout];
// If the sample rate or number of channels changed, change the AU formats
if(newFormat.mSampleRate != format.mSampleRate || newFormat.mChannelsPerFrame != format.mChannelsPerFrame) {
OSStatus err = [self setAUGraphFormat:newFormat];
if(noErr == err) {
[self setFormat:newFormat];
if([[NSUserDefaults standardUserDefaults] boolForKey:@"automaticallySetOutputDeviceSampleRate"])
[self setOutputDeviceSampleRate:newFormat.mSampleRate];
}
else {
if(nil != error) {
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
NSString *path = [[stream valueForKey:StreamURLKey] path];
[errorDictionary setObject:[NSString stringWithFormat:NSLocalizedStringFromTable(@"The format of the file \"%@\" is not supported.", @"Errors", @""), [[NSFileManager defaultManager] displayNameAtPath:path]] forKey:NSLocalizedDescriptionKey];
[errorDictionary setObject:NSLocalizedStringFromTable(@"File Format Not Supported", @"Errors", @"") forKey:NSLocalizedFailureReasonErrorKey];
[errorDictionary setObject:NSLocalizedStringFromTable(@"The current DSP effects may not support this track's sample rate or channel layout.", @"Errors", @"") forKey:NSLocalizedRecoverySuggestionErrorKey];
*error = [NSError errorWithDomain:AudioPlayerErrorDomain
code:AudioPlayerInternalError
userInfo:errorDictionary];
}
return NO;
}
}
// Update the AUGraph
if(NO == channelLayoutsAreEqual(&newChannelLayout, &channelLayout)) {
OSStatus err = [self setAUGraphChannelLayout:newChannelLayout];
if(noErr == err)
[self setChannelLayout:newChannelLayout];
else {
if(nil != error) {
NSMutableDictionary *errorDictionary = [NSMutableDictionary dictionary];
NSString *path = [[stream valueForKey:StreamURLKey] path];
[errorDictionary setObject:[NSString stringWithFormat:NSLocalizedStringFromTable(@"The format of the file \"%@\" is not supported.", @"Errors", @""), [[NSFileManager defaultManager] displayNameAtPath:path]] forKey:NSLocalizedDescriptionKey];
[errorDictionary setObject:NSLocalizedStringFromTable(@"File Format Not Supported", @"Errors", @"") forKey:NSLocalizedFailureReasonErrorKey];
[errorDictionary setObject:NSLocalizedStringFromTable(@"The current DSP effects may not support this track's sample rate or channel layout.", @"Errors", @"") forKey:NSLocalizedRecoverySuggestionErrorKey];
*error = [NSError errorWithDomain:AudioPlayerErrorDomain
code:AudioPlayerInternalError
userInfo:errorDictionary];
}
return NO;
}
}
// Schedule the region for playback, and start scheduling audio slices
[[self scheduler] scheduleAudioRegion:[ScheduledAudioRegion scheduledAudioRegionWithDecoder:decoder]];
[[self scheduler] startScheduling];
[self prepareToPlayStream:stream];
return YES;
}
- (BOOL) setNextStream:(AudioStream *)stream error:(NSError **)error
{
NSParameterAssert(nil != stream);
if(NO == [self isPlaying] || NO == [[self scheduler] isScheduling])
return NO;
id <AudioDecoderMethods> decoder = [stream decoder:error];
if(nil == decoder)
return NO;
AudioStreamBasicDescription format = [self format];
AudioStreamBasicDescription nextFormat = [decoder format];
AudioChannelLayout channelLayout = [self channelLayout];
AudioChannelLayout nextChannelLayout = [decoder channelLayout];
BOOL formatsMatch = (nextFormat.mSampleRate == format.mSampleRate && nextFormat.mChannelsPerFrame == format.mChannelsPerFrame);
BOOL channelLayoutsMatch = channelLayoutsAreEqual(&nextChannelLayout, &channelLayout);
// The two files can be joined only if they have the same formats and channel layouts
if(NO == formatsMatch || NO == channelLayoutsMatch)
return NO;
// The formats and channel layouts match, so schedule the region for playback
[[self scheduler] scheduleAudioRegion:[ScheduledAudioRegion scheduledAudioRegionWithDecoder:decoder]];
return YES;
}
- (void) reset
{
[self willChangeValueForKey:@"hasValidStream"];
[[self scheduler] stopScheduling];
[[self scheduler] clear];
[self didChangeValueForKey:@"hasValidStream"];
[self willChangeValueForKey:@"totalFrames"];
[self setTotalFrames:0];
[self didChangeValueForKey:@"totalFrames"];
[self willChangeValueForKey:@"currentFrame"];
[self setStartingFrame:0];
[self setPlayingFrame:0];
[self didChangeValueForKey:@"currentFrame"];
_regionStartingFrame = 0;
}
- (BOOL) hasValidStream
{
return (nil != [[self scheduler] regionBeingScheduled] || nil != [[self scheduler] regionBeingRendered]);
}
- (BOOL) streamSupportsSeeking
{
return ([self hasValidStream] && [[[[self scheduler] regionBeingRendered] decoder] supportsSeeking]);
}
#pragma mark Playback Control
- (void) play
{
if(NO == [self canPlay] || [self isPlaying])
return;
if(NO == [[self scheduler] isScheduling])
[[self scheduler] startScheduling];
// Start playback of the ScheduledSoundPlayer unit by setting its start time
AudioTimeStamp timeStamp = { 0 };
timeStamp.mFlags = kAudioTimeStampSampleTimeValid;
timeStamp.mSampleTime = -1;
OSStatus err = AudioUnitSetProperty(_generatorUnit,
kAudioUnitProperty_ScheduleStartTimeStamp,
kAudioUnitScope_Global,
0,
&timeStamp,
sizeof(timeStamp));
if(noErr != err)
NSLog(@"AudioPlayer error: Unable to start AUScheduledSoundPlayer: %i", err);
/* UInt32 dataSize = sizeof(timeStamp);
err = AudioUnitGetProperty(_generatorUnit, kAudioUnitProperty_ScheduleStartTimeStamp, kAudioUnitScope_Global, 0, &timeStamp, &dataSize);
if(noErr == err)
NSLog(@"started at time: %f", timeStamp.mSampleTime);*/
[self startAUGraph];
[self setPlaying:YES];
}
- (void) playPause
{
if([self isPlaying])
[self stop];
else
[self play];
}
- (void) pause
{
if([self isPlaying])
[self stop];
}
- (void) stop
{
if(NO == [self isPlaying])
return;
// Don't schedule any further slices for playback
[[self scheduler] stopScheduling];
// Determine the last sample that was rendered and update our internal state
AudioTimeStamp timeStamp = [[self scheduler] currentPlayTime];
if(kAudioTimeStampSampleTimeValid & timeStamp.mFlags) {
SInt64 lastRenderedFrame = [self startingFrame] + timeStamp.mSampleTime - _regionStartingFrame;
[self setStartingFrame:[[[[self scheduler] regionBeingScheduled] decoder] seekToFrame:lastRenderedFrame]];
[self setPlayingFrame:0];
}
// Reset the scheduler to remove any scheduled slices
[[self scheduler] reset];
_regionStartingFrame = 0;
[self stopAUGraph];
[self setPlaying:NO];
}
- (void) skipForward
{
[self skipForward:3];
}
- (void) skipBackward
{
[self skipBackward:3];
}
- (void) skipForward:(UInt32)seconds
{
ScheduledAudioRegion *currentRegion = [[self scheduler] regionBeingScheduled];
if(nil != currentRegion && [[currentRegion decoder] supportsSeeking]) {
SInt64 totalFrames = [[currentRegion decoder] totalFrames];
SInt64 currentFrame = [[currentRegion decoder] currentFrame];
SInt64 desiredFrame = currentFrame + (SInt64)(seconds * [[currentRegion decoder] format].mSampleRate);
if(totalFrames < desiredFrame)
desiredFrame = totalFrames;
[self setCurrentFrame:desiredFrame];
}
}
- (void) skipBackward:(UInt32)seconds
{
ScheduledAudioRegion *currentRegion = [[self scheduler] regionBeingScheduled];
if(nil != currentRegion && [[currentRegion decoder] supportsSeeking]) {
SInt64 currentFrame = [[currentRegion decoder] currentFrame];
SInt64 desiredFrame = currentFrame - (SInt64)(seconds * [[currentRegion decoder] format].mSampleRate);
if(0 > desiredFrame)
desiredFrame = 0;
[self setCurrentFrame:desiredFrame];
}
}
- (void) skipToEnd
{
ScheduledAudioRegion *currentRegion = [[self scheduler] regionBeingScheduled];
if(nil != currentRegion && [[currentRegion decoder] supportsSeeking]) {
SInt64 totalFrames = [[currentRegion decoder] totalFrames];
[self setCurrentFrame:totalFrames - 1];
}
}
- (void) skipToBeginning
{
ScheduledAudioRegion *currentRegion = [[self scheduler] regionBeingScheduled];
if(nil != currentRegion && [[currentRegion decoder] supportsSeeking])
[self setCurrentFrame:0];
}
- (BOOL) isPlaying
{
return _playing;
}
#pragma mark Bindings
- (Float32) volume
{
Float32 volume = -1;
ComponentResult result = AudioUnitGetParameter(_outputUnit,
kHALOutputParam_Volume,
kAudioUnitScope_Global,
0,
&volume);
if(noErr != result)
NSLog(@"Unable to determine volume");
return volume;
}
- (void) setVolume:(Float32)volume
{
NSParameterAssert(0 <= volume && volume <= 1);
ComponentResult result = AudioUnitSetParameter(_outputUnit,
kHALOutputParam_Volume,
kAudioUnitScope_Global,
0,
volume,
0);
if(noErr != result)
NSLog(@"Unable to set volume");
}
- (BOOL) hasReplayGain { return _hasReplayGain; }
- (float) replayGain { return _replayGain; }
- (float) preAmplification { return _preAmplification; }
- (void) setPreAmplification:(float)preAmplification
{
NSParameterAssert(-15.0 <= preAmplification && preAmplification <= 15.0);
_preAmplification = preAmplification;
}
- (AudioStreamBasicDescription) format { return _format; }
- (AudioChannelLayout) channelLayout { return _channelLayout; }
- (void) saveStateToDefaults
{
[[NSUserDefaults standardUserDefaults] setFloat:[self volume] forKey:@"playerVolume"];
[self saveEffectsToDefaults];
}
- (void) restoreStateFromDefaults
{
[self setVolume:[[NSUserDefaults standardUserDefaults] floatForKey:@"playerVolume"]];
[self restoreEffectsFromDefaults];
}
- (SInt64) totalFrames { return _totalFrames; }
- (SInt64) currentFrame
{
return [self startingFrame] + [self playingFrame] - _regionStartingFrame;
}
- (void) setCurrentFrame:(SInt64)currentFrame
{
// NSParameterAssert(0 <= currentFrame && currentFrame < [self totalFrames]);
/* if(0 > currentFrame)
currentFrame = 0;
else if([self totalFrames] <= currentFrame)
currentFrame = [self totalFrames ] - 1;*/
BOOL resume = NO;
[[self scheduler] stopScheduling];
[[self scheduler] reset];
if([self isPlaying]) {
[self setPlaying:NO];
_regionStartingFrame = 0;
resume = YES;
}
OSStatus err = [self resetAUGraph];
if(noErr != err)
NSLog(@"AudioPlayer error: Unable to reset AUGraph AudioUnits: %i", err);
Float64 graphLatency;
err = [self getAUGraphLatency:&graphLatency];
if(noErr != err)
NSLog(@"AudioPlayer error: Unable to determine AUGraph latency: %i", err);
UInt32 graphLatencyFrames = graphLatency * [self format].mSampleRate;
currentFrame -= graphLatencyFrames;
if(0 > currentFrame)
currentFrame = 0;
else if([self totalFrames] <= currentFrame)
currentFrame = [self totalFrames ] - 1;
[self setStartingFrame:[[[[self scheduler] regionBeingScheduled] decoder] seekToFrame:currentFrame + _regionStartingFrame]];
[self setPlayingFrame:0];
AudioTimeStamp timeStamp = [[self scheduler] scheduledStartTime];
timeStamp.mSampleTime -= graphLatencyFrames;
[[self scheduler] setScheduledStartTime:timeStamp];
#if DEBUG
if([self startingFrame] != currentFrame)
NSLog(@"Seek failed: requested frame %qi, got %qi", currentFrame, [self startingFrame]);
#endif
[[self scheduler] startScheduling];
if(resume)
[self play];
}
- (SInt64) framesRemaining
{
return [self totalFrames] - [self currentFrame];
}
- (NSTimeInterval) totalSeconds
{
return (NSTimeInterval)([self totalFrames] / [self format].mSampleRate);
}
- (NSTimeInterval) currentSecond
{
return (NSTimeInterval)([self currentFrame] / [self format].mSampleRate);
}
- (NSTimeInterval) secondsRemaining
{
return (NSTimeInterval)([self framesRemaining] / [self format].mSampleRate);
}
#pragma mark AudioSchedulerMethods
- (void) audioSchedulerFinishedSchedulingRegion:(NSDictionary *)schedulerAndRegion
{
NSParameterAssert(nil != schedulerAndRegion);
#if DEBUG
ScheduledAudioRegion *region = [schedulerAndRegion valueForKey:ScheduledAudioRegionObjectKey];
NSLog(@"-audioSchedulerFinishedSchedulingRegion: %@", region);
#endif
// Request the next stream from the library, to keep playback going
[_owner requestNextStream];
}
- (void) audioSchedulerStartedRenderingRegion:(NSDictionary *)schedulerAndRegion
{
NSParameterAssert(nil != schedulerAndRegion);
ScheduledAudioRegion *region = [schedulerAndRegion valueForKey:ScheduledAudioRegionObjectKey];
#if DEBUG
NSLog(@"-audioSchedulerStartedRenderingRegion: %@", region);
#endif
[self setTotalFrames:[[region decoder] totalFrames]];
[self willChangeValueForKey:@"hasValidStream"];
[self didChangeValueForKey:@"hasValidStream"];
[self willChangeValueForKey:@"currentFrame"];
[self setStartingFrame:0];
[self setPlayingFrame:0];
[self didChangeValueForKey:@"currentFrame"];
// If the owner successfully sent the next stream request, signal the end of the current stream
// and beginning of the next one
if([_owner sentNextStreamRequest])
[_owner streamPlaybackDidStart];
}
- (void) audioSchedulerFinishedRenderingRegion:(NSDictionary *)schedulerAndRegion
{
NSParameterAssert(nil != schedulerAndRegion);
ScheduledAudioRegion *region = [schedulerAndRegion valueForKey:ScheduledAudioRegionObjectKey];
#if DEBUG
NSLog(@"-audioSchedulerFinishedRenderingRegion: %@", region);
#endif
// If nothing is coming up right away, stop ourselves from playing
if(nil == [[self scheduler] regionBeingScheduled]) {
[self stopAUGraph];
[self setPlaying:NO];
_regionStartingFrame = 0;
[self willChangeValueForKey:@"hasValidStream"];
[self didChangeValueForKey:@"hasValidStream"];
// Reset play position
[self willChangeValueForKey:@"currentFrame"];
[self setStartingFrame:0];
[self setPlayingFrame:0];
[self didChangeValueForKey:@"currentFrame"];
}
// Otherwise set up for the next stream
else {
_regionStartingFrame += [region framesRendered];
[self prepareToPlayStream:[_owner nextStream]];
}
// If the owner did not successfully send the next stream request, signal the end of the current stream
if(NO == [_owner sentNextStreamRequest])
[_owner streamPlaybackDidComplete];
}
@end
@implementation AudioPlayer (AUGraphMethods)
- (AUGraph) auGraph
{
return _auGraph;
}
- (OSStatus) setupAUGraph
{
// Set up the AUGraph
OSStatus err = NewAUGraph(&_auGraph);
if(noErr != err)
return err;
// The graph will look like:
// Generator -> Peak Limiter -> Effects -> Output
ComponentDescription desc;
// Set up the generator node
desc.componentType = kAudioUnitType_Generator;
desc.componentSubType = kAudioUnitSubType_ScheduledSoundPlayer;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
err = AUGraphAddNode([self auGraph], &desc, &_generatorNode);
if(noErr != err)
return err;
// Set up the peak limiter node
desc.componentType = kAudioUnitType_Effect;
desc.componentSubType = kAudioUnitSubType_PeakLimiter;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
err = AUGraphAddNode([self auGraph], &desc, &_limiterNode);
if(noErr != err)
return err;
// Set up the output node
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
err = AUGraphAddNode([self auGraph], &desc, &_outputNode);
if(noErr != err)
return err;
// Connect the nodes
err = AUGraphConnectNodeInput([self auGraph], _generatorNode, 0, _limiterNode, 0);
if(noErr != err)
return err;
err = AUGraphConnectNodeInput([self auGraph], _limiterNode, 0, _outputNode, 0);
if(noErr != err)
return err;
// Open the graph
err = AUGraphOpen([self auGraph]);
if(noErr != err)
return err;
// Initialize the graph
err = AUGraphInitialize([self auGraph]);
if(noErr != err)
return err;
// Store the audio units for later use
err = AUGraphNodeInfo([self auGraph], _generatorNode, NULL, &_generatorUnit);
if(noErr != err)
return err;
err = AUGraphNodeInfo([self auGraph], _limiterNode, NULL, &_limiterUnit);
if(noErr != err)
return err;
err = AUGraphNodeInfo([self auGraph], _outputNode, NULL, &_outputUnit);
if(noErr != err)
return err;
return noErr;
}
- (OSStatus) teardownAUGraph
{
Boolean graphIsRunning = NO;
OSStatus err = AUGraphIsRunning([self auGraph], &graphIsRunning);
if(noErr != err)
return err;
if(graphIsRunning) {
err = AUGraphStop([self auGraph]);
if(noErr != err)
return err;
}
Boolean graphIsInitialized = NO;
err = AUGraphIsInitialized([self auGraph], &graphIsInitialized);
if(noErr != err)
return err;
if(graphIsInitialized) {
err = AUGraphUninitialize([self auGraph]);
if(noErr != err)
return err;
}
err = AUGraphClose([self auGraph]);
if(noErr != err)
return err;
err = DisposeAUGraph([self auGraph]);
if(noErr != err)
return err;
_auGraph = NULL;
_generatorUnit = NULL;
_limiterUnit = NULL;
_outputUnit = NULL;
return noErr;
}
- (OSStatus) resetAUGraph
{
UInt32 nodeCount;
OSStatus err = AUGraphGetNodeCount([self auGraph], &nodeCount);
if(noErr != err)
return err;
UInt32 i;
for(i = 0; i < nodeCount; ++i) {
AUNode node;
err = AUGraphGetIndNode([self auGraph], i, &node);
if(noErr != err)
return err;
AudioUnit au;
err = AUGraphNodeInfo([self auGraph], node, NULL, &au);
if(noErr != err)
return err;
err = AudioUnitReset(au, kAudioUnitScope_Global, 0);
if(noErr != err)
return err;
}
return noErr;
}
- (OSStatus) startAUGraph
{
// Don't attempt to start an already running graph
Boolean graphIsRunning = NO;
OSStatus err = AUGraphIsRunning([self auGraph], &graphIsRunning);
if(noErr == err && !graphIsRunning)
err = AUGraphStart([self auGraph]);
return err;
}
- (OSStatus) stopAUGraph
{
Boolean graphIsRunning = NO;
OSStatus err = AUGraphIsRunning([self auGraph], &graphIsRunning);
if(noErr == err && graphIsRunning)
err = AUGraphStop([self auGraph]);
return err;
}
- (OSStatus) getAUGraphLatency:(Float64 *)graphLatency
{
NSParameterAssert(NULL != graphLatency);
*graphLatency = 0;
UInt32 nodeCount;
OSStatus err = AUGraphGetNodeCount([self auGraph], &nodeCount);
if(noErr != err)
return err;
UInt32 i;
for(i = 0; i < nodeCount; ++i) {
AUNode node;
err = AUGraphGetIndNode([self auGraph], i, &node);
if(noErr != err)
return err;
AudioUnit au;
err = AUGraphNodeInfo([self auGraph], node, NULL, &au);
if(noErr != err)
return err;
Float64 latency;
UInt32 dataSize = sizeof(latency);
err = AudioUnitGetProperty(au, kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0, &latency, &dataSize);
if(noErr != err)
return err;
*graphLatency += latency;
}
return noErr;
}
- (OSStatus) getAUGraphTailTime:(Float64 *)graphTailTime
{
NSParameterAssert(NULL != graphTailTime);
*graphTailTime = 0;
UInt32 nodeCount;
OSStatus err = AUGraphGetNodeCount([self auGraph], &nodeCount);
if(noErr != err)
return err;
UInt32 i;
for(i = 0; i < nodeCount; ++i) {
AUNode node;
err = AUGraphGetIndNode([self auGraph], i, &node);
if(noErr != err)
return err;
AudioUnit au;
err = AUGraphNodeInfo([self auGraph], node, NULL, &au);
if(noErr != err)
return err;
Float64 tailTime;