forked from decarbonization/PlayerKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PKAudioPlayer.cpp
828 lines (646 loc) · 21.7 KB
/
PKAudioPlayer.cpp
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
/*
* PKAudioPlayer.cpp
* PlayerKit
*
* Created by Peter MacWhinnie on 10/16/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#import "PKAudioPlayer.h"
#import "PKAudioPlayerInternal.h"
#import <libKern/OSAtomic.h>
#import "CoreAudioErrors.h"
#import "CAAudioBufferList.h"
#import "CAStreamBasicDescription.h"
#import "RBLockableObject.h"
///The singleton instance of the audio player state.
PK_VISIBILITY_HIDDEN RBLockableObject AudioPlayerStateLock;
PK_VISIBILITY_HIDDEN PKAudioPlayer AudioPlayerState = { /* Initialized in PKAudioPlayerInit */ };
PK_VISIBILITY_HIDDEN volatile int32_t AudioPlayerStateInitCount = 0;
#pragma mark Constants
PK_EXTERN CFStringRef const PKAudioPlayerDidEncounterErrorNotification = CFSTR("PKAudioPlayerDidEncounterErrorNotification");
PK_EXTERN CFStringRef const PKAudioPlayerDidFinishPlayingNotification = CFSTR("PKAudioPlayerDidFinishPlayingNotification");
PK_EXTERN CFStringRef const PKAudioPlayerDidChangeOutputDeviceNotification = CFSTR("PKAudioPlayerDidChangeOutputDeviceNotification");
PK_EXTERN CFStringRef const PKAudioPlayerDidEncounterOtherPlayerNotification = CFSTR("PKAudioPlayerDidEncounterOtherPlayerNotification");
#pragma mark -
static CFStringRef const PKAudioPlayerDidBroadcastPresenceNotification = CFSTR("com.roundabout.PKAudioPlayerDidBroadcastPresenceNotification");
static void PKAudioPlayerDidBroadcastPresence(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo);
#pragma mark -
#pragma mark Lifecycle
PK_EXTERN Boolean PKAudioPlayerInit(CFErrorRef *outError)
{
if(OSMemoryBarrier(), AudioPlayerStateInitCount > 0)
{
OSAtomicIncrement32Barrier(&AudioPlayerStateInitCount);
return true;
}
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
try
{
AudioPlayerState.engine = PKAudioPlayerEngine::New();
AudioPlayerState.engine->SetErrorHandler(^(CFErrorRef error) {
try
{
if(AudioPlayerState.engine->IsRunning())
AudioPlayerState.engine->StopGraph();
AudioPlayerState.engine->StopProcessing();
AudioPlayerState.isPaused = false;
PKAudioPlayerSetCurrentTime(0.0, NULL);
}
catch (RBException e)
{
std::cerr << "An exception was raised while resetting PKAudioPlayer's internal state after an error occurred {";
CFErrorRef tempError = e.CopyError();
CFShow(tempError);
CFRelease(tempError);
std::cerr << "}. It will be ignored." << std::endl;
}
dispatch_async(dispatch_get_main_queue(), ^{
CFDictionaryRef userInfo = CFDICT({ CFSTR("Error") }, { error });
CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(),
PKAudioPlayerDidEncounterErrorNotification,
NULL,
userInfo,
true);
CFRelease(userInfo);
CFRelease(error);
});
});
AudioPlayerState.engine->SetEndOfPlaybackHandler(^{
dispatch_async(dispatch_get_main_queue(), ^{
CFDictionaryRef userInfo = CFDICT({ CFSTR("DidFinish") }, { kCFBooleanTrue });
CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(),
PKAudioPlayerDidFinishPlayingNotification,
NULL,
userInfo,
true);
CFRelease(userInfo);
});
});
AudioPlayerState.engine->SetOutputDeviceDidChangeHandler(^{
dispatch_async(dispatch_get_main_queue(), ^{
CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(),
PKAudioPlayerDidChangeOutputDeviceNotification,
NULL,
NULL,
true);
});
});
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
CFNotificationCallback(&PKAudioPlayerDidBroadcastPresence),
PKAudioPlayerDidBroadcastPresenceNotification,
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
CFUUIDRef sessionUUID = CFUUIDCreate(kCFAllocatorDefault);
AudioPlayerState.sessionID = CFUUIDCreateString(kCFAllocatorDefault, sessionUUID);
CFRelease(sessionUUID);
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
OSAtomicIncrement32Barrier(&AudioPlayerStateInitCount);
return true;
}
PK_EXTERN Boolean PKAudioPlayerTeardown(CFErrorRef *outError)
{
if(OSMemoryBarrier(), AudioPlayerStateInitCount > 0)
{
if(OSAtomicDecrement32(&AudioPlayerStateInitCount) != 0)
return true;
}
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
try
{
if((PKAudioPlayerIsPlaying() || PKAudioPlayerIsPaused()) && !PKAudioPlayerStop(false, outError))
return false;
if(AudioPlayerState.engine)
delete AudioPlayerState.engine;
if(AudioPlayerState.decoderConverter)
{
AudioConverterDispose(AudioPlayerState.decoderConverter);
AudioPlayerState.decoderConverter = NULL;
}
if(AudioPlayerState.decoderConverterBuffers)
{
for (int index = 0; index < AudioPlayerState.decoderConverterBuffers->mNumberBuffers; index++)
{
free(AudioPlayerState.decoderConverterBuffers->mBuffers[index].mData);
}
CAAudioBufferList::Destroy(AudioPlayerState.decoderConverterBuffers);
AudioPlayerState.decoderConverterBuffers = NULL;
}
if(AudioPlayerState.decoder)
{
AudioPlayerState.decoder->Release();
AudioPlayerState.decoder = NULL;
}
if(AudioPlayerState.sessionID)
{
CFRelease(AudioPlayerState.sessionID);
AudioPlayerState.sessionID = NULL;
}
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
memset(&AudioPlayerState, 0, sizeof(AudioPlayerState));
return true;
}
#pragma mark -
#pragma mark Notifications
static void PKAudioPlayerDidBroadcastPresence(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo)
{
if(CFEqual(AudioPlayerState.sessionID, CFStringRef(object)))
return;
dispatch_async(dispatch_get_main_queue(), ^{
CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(),
PKAudioPlayerDidEncounterOtherPlayerNotification,
NULL,
NULL,
true);
});
}
#pragma mark -
#pragma mark Playback Callbacks
static UInt32 PKAudioPlayerScheduleSlice(PKAudioPlayerEngine *graph, AudioBufferList *ioBuffer, UInt32 numberOfFramesToRead, CFErrorRef *error, void *userData)
{
try
{
return AudioPlayerState.decoder->FillBuffers(ioBuffer, numberOfFramesToRead);
}
catch (RBException e)
{
if(error) *error = e.CopyError();
return 0;
}
}
struct PKAudioPlayerConverterState
{
CFErrorRef mError;
};
static OSStatus PKAudioPlayerConverterCallback(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, AudioBufferList *ioData, AudioStreamPacketDescription **outDataPacketDescription, void *inUserData)
{
PKAudioPlayerConverterState *sharedState = (PKAudioPlayerConverterState *)inUserData;
for (int index = 0; index < AudioPlayerState.decoderConverterBuffers->mNumberBuffers; index++)
ioData->mBuffers[index] = AudioPlayerState.decoderConverterBuffers->mBuffers[index];
try
{
*ioNumberDataPackets = AudioPlayerState.decoder->FillBuffers(ioData, *ioNumberDataPackets);
if(*ioNumberDataPackets == 0)
{
//This is necessary or AudioConverter will continue to call this function
//producing garbage that the user then has to hear. We don't want that to happen.
for (int index = 0; index < AudioPlayerState.decoderConverterBuffers->mNumberBuffers; index++)
ioData->mBuffers[index].mDataByteSize = 0;
}
}
catch (RBException e)
{
sharedState->mError = e.CopyError();
return CFErrorGetCode(sharedState->mError);
}
return noErr;
}
static UInt32 PKAudioPlayerScheduleSliceWithConverter(PKAudioPlayerEngine *graph, AudioBufferList *ioBuffer, UInt32 numberOfFramesToRead, CFErrorRef *error, void *userData)
{
UInt32 ioNumberOfFramesForConverter = numberOfFramesToRead;
PKAudioPlayerConverterState converterState = { mError: NULL };
OSStatus errorCode = AudioConverterFillComplexBuffer(AudioPlayerState.decoderConverter, //in audioConverter
PKAudioPlayerConverterCallback, //in inputDataProc
&converterState, //in userData
&ioNumberOfFramesForConverter, //io dataPacketSize
ioBuffer, //out outputData
NULL); //out packetDescription
if(ioNumberOfFramesForConverter == 0)
{
if(errorCode != noErr)
if(error) *error = converterState.mError;
return 0;
}
return ioNumberOfFramesForConverter;
}
#pragma mark -
#pragma mark Controlling Playback
static void __PKAudioPlayerSetupAudioConverter(CAStreamBasicDescription *sourceFormat, CAStreamBasicDescription *resultFormat) throw(RBException)
{
resultFormat->mSampleRate = kPKCanonicalSampleRate;
resultFormat->SetCanonical(2, false);
OSStatus errorCode = AudioConverterNew(sourceFormat, resultFormat, &AudioPlayerState.decoderConverter);
RBAssert((errorCode == noErr), CFSTR("AudioConverterNew failed. Error: %d."), errorCode);
UInt32 baseBufferSize = kPKCanonicalBaseBufferSize;
if(sourceFormat->IsInterleaved())
{
UInt32 bufferSize = (baseBufferSize * sourceFormat->SampleWordSize());
AudioPlayerState.decoderConverterBuffers = CAAudioBufferList::Create(1);
AudioPlayerState.decoderConverterBuffers->mBuffers[0].mData = malloc(bufferSize);
AudioPlayerState.decoderConverterBuffers->mBuffers[0].mDataByteSize = bufferSize;
AudioPlayerState.decoderConverterBuffers->mBuffers[0].mNumberChannels = bufferSize;
}
else
{
AudioPlayerState.decoderConverterBuffers = CAAudioBufferList::Create(sourceFormat->mChannelsPerFrame);
UInt32 bufferSize = (baseBufferSize * sourceFormat->mBytesPerPacket) / sourceFormat->mChannelsPerFrame;
for (int index = 0; index < AudioPlayerState.decoderConverterBuffers->mNumberBuffers; index++)
{
AudioBuffer &buffer = AudioPlayerState.decoderConverterBuffers->mBuffers[index];
buffer.mData = malloc(bufferSize);
buffer.mDataByteSize = bufferSize;
buffer.mNumberChannels = 1;
}
}
}
PK_EXTERN Boolean PKAudioPlayerSetDecoder(PKDecoder *decoder, CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
if(decoder == AudioPlayerState.decoder)
return true;
if((PKAudioPlayerIsPlaying() || PKAudioPlayerIsPaused()) && !PKAudioPlayerStop(false, outError))
return false;
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
if(AudioPlayerState.decoder)
{
AudioPlayerState.decoder->Release();
AudioPlayerState.decoder = NULL;
}
if(AudioPlayerState.decoderConverter)
{
AudioConverterDispose(AudioPlayerState.decoderConverter);
AudioPlayerState.decoderConverter = NULL;
}
if(AudioPlayerState.decoderConverterBuffers)
{
for (int index = 0; index < AudioPlayerState.decoderConverterBuffers->mNumberBuffers; index++)
{
free(AudioPlayerState.decoderConverterBuffers->mBuffers[index].mData);
}
CAAudioBufferList::Destroy(AudioPlayerState.decoderConverterBuffers);
AudioPlayerState.decoderConverterBuffers = NULL;
}
if(decoder)
{
CAStreamBasicDescription nativeFormat = decoder->GetStreamFormat();
//
// If the data being given to us is already canonical,
// we use the data as is. This is an attempt at efficiency.
//
CAStreamBasicDescription audioFormat;
if(PKStreamFormatIsCanonical(nativeFormat))
{
audioFormat = nativeFormat;
AudioPlayerState.decoderConverter = nil;
AudioPlayerState.decoderConverterBuffers = nil;
AudioPlayerState.engine->SetScheduleSliceFunctionHandler(PKAudioPlayerScheduleSlice);
}
else
{
__PKAudioPlayerSetupAudioConverter(&nativeFormat, &audioFormat);
AudioPlayerState.engine->SetScheduleSliceFunctionHandler(PKAudioPlayerScheduleSliceWithConverter);
}
AudioPlayerState.decoder = decoder;
try
{
AudioPlayerState.engine->SetStreamFormat(audioFormat);
}
catch (RBException e)
{
AudioPlayerState.decoder = NULL;
if(outError)
{
CFErrorRef underlyingError = e.CopyError();
CFDictionaryRef userInfo = CFDICT({ kCFErrorUnderlyingErrorKey }, { underlyingError });
CFRelease(underlyingError);
CFURLRef decoderLocation = decoder->CopyLocation();
*outError = PKCopyError(PKPlaybackErrorDomain,
kPKPlaybackErrorIncompatibleStreamFormat,
userInfo,
CFSTR("The stream format of the file %@ cannot be decoded."), decoderLocation);
CFRelease(decoderLocation);
CFRelease(userInfo);
}
return false;
}
}
return true;
}
PK_EXTERN PKDecoder *PKAudioPlayerGetDecoder()
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
return AudioPlayerState.decoder;
}
#pragma mark -
PK_EXTERN Boolean PKAudioPlayerSetURL(CFURLRef location, CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
try
{
if(location)
{
PKDecoder *decoder = PKDecoder::DecoderForURL(location);
RBAssert((decoder != NULL), CFSTR("Could not find decoder for {%@}."), location);
return PKAudioPlayerSetDecoder(decoder, outError);
}
else
{
return PKAudioPlayerSetDecoder(NULL, outError);
}
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
return true;
}
PK_EXTERN CFURLRef PKAudioPlayerCopyURL()
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
return AudioPlayerState.decoder->CopyLocation();
}
#pragma mark -
PK_EXTERN Boolean PKAudioPlayerPlay(CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
if(PKAudioPlayerIsPlaying())
return true;
if(PKAudioPlayerIsPaused())
return PKAudioPlayerResume(outError);
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
if(OSMemoryBarrier(), !AudioPlayerState.hasBroadcastedPresence)
{
CFNotificationCenterPostNotification(CFNotificationCenterGetDistributedCenter(),
PKAudioPlayerDidBroadcastPresenceNotification,
AudioPlayerState.sessionID,
NULL,
true);
OSAtomicCompareAndSwap32Barrier(AudioPlayerState.hasBroadcastedPresence, 1, &AudioPlayerState.hasBroadcastedPresence);
}
try
{
if(!AudioPlayerState.engine->IsRunning())
{
AudioPlayerState.engine->StartGraph();
AudioPlayerState.engine->StartProcessing();
}
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
return true;
}
PK_EXTERN Boolean PKAudioPlayerStop(Boolean postNotification, CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
if(!PKAudioPlayerIsPlaying() && !PKAudioPlayerIsPaused())
return true;
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
try
{
if(AudioPlayerState.engine->IsRunning())
AudioPlayerState.engine->StopGraph();
AudioPlayerState.engine->StopProcessing();
AudioPlayerState.isPaused = false;
PKAudioPlayerSetCurrentTime(0.0, NULL);
if(postNotification)
{
dispatch_async(dispatch_get_main_queue(), ^{
CFDictionaryRef userInfo = CFDICT({ CFSTR("DidFinish") }, { kCFBooleanFalse });
CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(),
PKAudioPlayerDidFinishPlayingNotification,
NULL,
userInfo,
true);
CFRelease(userInfo);
});
}
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
}
return true;
}
PK_EXTERN Boolean PKAudioPlayerIsPlaying()
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
return AudioPlayerState.engine->IsRunning();
}
#pragma mark -
PK_EXTERN Boolean PKAudioPlayerPause(CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
PKAudioPlayerEngine *engine = AudioPlayerState.engine;
if(OSMemoryBarrier(), AudioPlayerState.isPaused)
return true;
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
//
// If we're not playing, we do nothing. Why? Because attempting to
// resume processing when we aren't paused will cause some problems.
//
if(PKAudioPlayerIsPlaying())
{
try
{
engine->StopGraph();
engine->PauseProcessing();
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
OSAtomicCompareAndSwap32Barrier(AudioPlayerState.preserveExistingBuffersOnResume, true, &AudioPlayerState.preserveExistingBuffersOnResume);
OSAtomicCompareAndSwap32Barrier(AudioPlayerState.isPaused, true, &AudioPlayerState.isPaused);
}
return true;
}
PK_EXTERN Boolean PKAudioPlayerResume(CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
PKAudioPlayerEngine *engine = AudioPlayerState.engine;
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
if(OSMemoryBarrier(), AudioPlayerState.isPaused)
{
OSAtomicCompareAndSwap32Barrier(AudioPlayerState.isPaused, false, &AudioPlayerState.isPaused);
try
{
OSMemoryBarrier();
engine->ResumeProcessing(AudioPlayerState.preserveExistingBuffersOnResume);
engine->StartGraph();
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
}
else
{
return PKAudioPlayerPlay(outError);
}
return true;
}
PK_EXTERN Boolean PKAudioPlayerIsPaused()
{
CHECK_STATE_INITIALIZED();
return OSMemoryBarrier(), AudioPlayerState.isPaused;
}
#pragma mark -
#pragma mark Properties
PK_EXTERN Boolean PKAudioPlayerSetVolume(Float32 volume, CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
try
{
AudioPlayerState.engine->SetVolume(volume);
}
catch (RBException e)
{
if(outError) *outError = e.CopyError();
return false;
}
return true;
}
PK_EXTERN Float32 PKAudioPlayerGetVolume()
{
CHECK_STATE_INITIALIZED();
try
{
return AudioPlayerState.engine->GetVolume();
}
catch (RBException e)
{
std::cerr << "***Warning: Could not get volume for PKAudioPlayer." << std::endl;
}
return 1.0;
}
PK_EXTERN Float32 PKAudioPlayerGetAverageCPUUsage()
{
CHECK_STATE_INITIALIZED();
return AudioPlayerState.engine->GetAverageCPUUsage();
}
#pragma mark -
PK_EXTERN CFTimeInterval PKAudioPlayerGetDuration()
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
PKDecoder *decoder = AudioPlayerState.decoder;
if(decoder)
return decoder->GetTotalNumberOfFrames() / decoder->GetStreamFormat().mSampleRate;
return 0.0;
}
#pragma mark -
PK_EXTERN Boolean PKAudioPlayerSetCurrentTime(CFTimeInterval currentTime, CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
PKAudioPlayerEngine *engine = AudioPlayerState.engine;
PKDecoder *decoder = AudioPlayerState.decoder;
if(decoder && decoder->CanSeek())
{
Boolean shouldRestartGraph = PKAudioPlayerIsPlaying();
try
{
if(shouldRestartGraph)
{
engine->StopGraph();
engine->Acquire();
engine->PauseProcessing();
}
decoder->SetCurrentFrame(currentTime * decoder->GetStreamFormat().mSampleRate);
if(shouldRestartGraph)
{
engine->ResumeProcessing();
engine->Relinquish();
engine->StartGraph();
}
OSAtomicCompareAndSwap32Barrier(AudioPlayerState.preserveExistingBuffersOnResume, false, &AudioPlayerState.preserveExistingBuffersOnResume);
}
catch (RBException e)
{
//
// We prevent deadlocks here by relinquishing our exclusive access to the audio player engine.
// We only relinquish if we should be starting and stopping the graph and there are
// one or more locks active on the playback engine.
//
if(shouldRestartGraph)
engine->Relinquish();
if(outError) *outError = e.CopyError();
return false;
}
return true;
}
return false;
}
PK_EXTERN CFTimeInterval PKAudioPlayerGetCurrentTime()
{
CHECK_STATE_INITIALIZED();
RBLockableObject::Acquisitor lock(&AudioPlayerStateLock);
PKDecoder *decoder = AudioPlayerState.decoder;
if(decoder)
return decoder->GetCurrentFrame() / decoder->GetStreamFormat().mSampleRate;
return 0.0;
}
#pragma mark -
//Derived From <http://vgable.com/blog/2008/09/11/detecting-if-headphones-are-plugged-in/>
PK_EXTERN PKAudioPlayerOutputDestination PKAudioPlayerGetAudioOutputDestination(CFErrorRef *outError)
{
CHECK_STATE_INITIALIZED();
OSStatus error = noErr;
UInt32 dataSize = 0;
//Get the default output device
AudioObjectPropertyAddress outputDeviceAddress = {kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal};
AudioDeviceID outputDevice = NULL;
dataSize = sizeof(outputDevice);
error = AudioObjectGetPropertyData(/*inObjectID:*/ kAudioObjectSystemObject,
/*inAddress:*/ &outputDeviceAddress,
/*inQualifierDataSize:*/ 0,
/*inQualifierData:*/ NULL,
/*ioDataSize:*/ &dataSize,
/*outData:*/ &outputDevice);
if(error != noErr)
{
if(outError) *outError = PKCopyError(PKPlaybackErrorDomain,
error,
NULL,
CFSTR("Could not find system output device. Error %s (%d)"), CoreAudioGetErrorName(error), error);
return kPKAudioPlayerOutputDestinationUnknown;
}
//Get the data source for the output device
AudioObjectPropertyAddress dataSourceAddress = {kAudioDevicePropertyDataSource, kAudioDevicePropertyScopeOutput};
UInt32 dataSource = NULL;
dataSize = sizeof(dataSource);
error = AudioObjectGetPropertyData(/*inObjectID:*/ outputDevice,
/*inAddress:*/ &dataSourceAddress,
/*inQualifierDataSize:*/ 0,
/*inQualifierData:*/ NULL,
/*ioDataSize:*/ &dataSize,
/*outData:*/ &dataSource);
if(error != noErr)
{
if(outError) *outError = PKCopyError(PKPlaybackErrorDomain,
error,
NULL,
CFSTR("Could not copy system output device's output destination (data source). Error %s (%d)"), CoreAudioGetErrorName(error), error);
return kPKAudioPlayerOutputDestinationUnknown;
}
return PKAudioPlayerOutputDestination(dataSource);
}