-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathAudioStreamer.m
executable file
·2482 lines (2107 loc) · 67.8 KB
/
AudioStreamer.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
#import "AudioStreamer.h"
#ifdef TARGET_OS_IPHONE
#import <CFNetwork/CFNetwork.h>
#endif
#import "NSData+SnapAdditions.h"
#import "PacketClientPrimed.h"
NSString * const ASStatusChangedNotification = @"ASStatusChangedNotification";
NSString * const AS_NO_ERROR_STRING = @"No error.";
NSString * const AS_FILE_STREAM_GET_PROPERTY_FAILED_STRING = @"File stream get property failed.";
NSString * const AS_FILE_STREAM_SEEK_FAILED_STRING = @"File stream seek failed.";
NSString * const AS_FILE_STREAM_PARSE_BYTES_FAILED_STRING = @"Parse bytes failed.";
NSString * const AS_FILE_STREAM_OPEN_FAILED_STRING = @"Open audio file stream failed.";
NSString * const AS_FILE_STREAM_CLOSE_FAILED_STRING = @"Close audio file stream failed.";
NSString * const AS_AUDIO_QUEUE_CREATION_FAILED_STRING = @"Audio queue creation failed.";
NSString * const AS_AUDIO_QUEUE_BUFFER_ALLOCATION_FAILED_STRING = @"Audio buffer allocation failed.";
NSString * const AS_AUDIO_QUEUE_ENQUEUE_FAILED_STRING = @"Queueing of audio buffer failed.";
NSString * const AS_AUDIO_QUEUE_ADD_LISTENER_FAILED_STRING = @"Audio queue add listener failed.";
NSString * const AS_AUDIO_QUEUE_REMOVE_LISTENER_FAILED_STRING = @"Audio queue remove listener failed.";
NSString * const AS_AUDIO_QUEUE_START_FAILED_STRING = @"Audio queue start failed.";
NSString * const AS_AUDIO_QUEUE_BUFFER_MISMATCH_STRING = @"Audio queue buffers don't match.";
NSString * const AS_AUDIO_QUEUE_DISPOSE_FAILED_STRING = @"Audio queue dispose failed.";
NSString * const AS_AUDIO_QUEUE_PAUSE_FAILED_STRING = @"Audio queue pause failed.";
NSString * const AS_AUDIO_QUEUE_STOP_FAILED_STRING = @"Audio queue stop failed.";
NSString * const AS_AUDIO_DATA_NOT_FOUND_STRING = @"No audio data found.";
NSString * const AS_AUDIO_QUEUE_FLUSH_FAILED_STRING = @"Audio queue flush failed.";
NSString * const AS_GET_AUDIO_TIME_FAILED_STRING = @"Audio queue get current time failed.";
NSString * const AS_AUDIO_STREAMER_FAILED_STRING = @"Audio playback failed";
NSString * const AS_NETWORK_CONNECTION_FAILED_STRING = @"Network connection failed";
NSString * const AS_AUDIO_BUFFER_TOO_SMALL_STRING = @"Audio packets are larger than kAQBufSize.";
NSString * const ABSD_SETUP_FAILED_STRING = @"could not set up ABSD format.";
@interface AudioStreamer ()
- (void)handlePropertyChangeForFileStream:(AudioFileStreamID)inAudioFileStream
fileStreamPropertyID:(AudioFileStreamPropertyID)inPropertyID
ioFlags:(UInt32 *)ioFlags;
- (void)handleAudioPackets:(const void *)inInputData
numberBytes:(UInt32)inNumberBytes
numberPackets:(UInt32)inNumberPackets
packetDescriptions:(AudioStreamPacketDescription *)inPacketDescriptions;
- (void)handleBufferCompleteForQueue:(AudioQueueRef)inAQ
buffer:(AudioQueueBufferRef)inBuffer;
- (void)handlePropertyChangeForQueue:(AudioQueueRef)inAQ
propertyID:(AudioQueuePropertyID)inID;
#ifdef TARGET_OS_IPHONE
- (void)handleInterruptionChangeToState:(AudioQueuePropertyID)inInterruptionState;
void interruptionListenerCallback( void *inUserData, UInt32 interruptionState );
#endif
- (void)enqueueBuffer;
- (void)handleReadFromStream:(CFReadStreamRef)aStream
eventType:(CFStreamEventType)eventType;
@end
#pragma mark Audio Callback Function Prototypes
void audioCallback( void *inUserData, AudioQueueRef inQueue, AudioQueueBufferRef inBuffer );
void MyAudioQueueOutputCallback(void* inClientData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer);
void MyAudioQueueIsRunningCallback(void *inUserData, AudioQueueRef inAQ, AudioQueuePropertyID inID);
OSStatus MyEnqueueBuffer(AudioStreamer* myData);
#ifdef TARGET_OS_IPHONE
void MyAudioSessionInterruptionListener(void *inClientData, UInt32 inInterruptionState);
#endif
#pragma mark Audio Callback Function Implementations
//
// MyPropertyListenerProc
//
// Receives notification when the AudioFileStream has audio packets to be
// played. In response, this function creates the AudioQueue, getting it
// ready to begin playback (playback won't begin until audio packets are
// sent to the queue in MyEnqueueBuffer).
//
// This function is adapted from Apple's example in AudioFileStreamExample with
// kAudioQueueProperty_IsRunning listening added.
//
void audioCallback( void *inUserData, AudioQueueRef inQueue, AudioQueueBufferRef inBuffer ) {
// //NSLog(@"audio callback");
int numBuffersToEnqueueLater;
AudioQueueBufferRef audioQueueBuffer[kNumAQBufs];
// fill it up
inBuffer->mAudioDataByteSize = inBuffer->mAudioDataBytesCapacity;
//getSoundSamples( (Uint8 *)inBuffer->mAudioData, (Uint8 *)inBuffer->mAudioDataByteSize );
OSStatus err = AudioQueueEnqueueBuffer( inQueue,
inBuffer,
0,
NULL );
if( err ) {
printf( "Error on AudioQueueEnqueueBuffer: %4s\n", (char*)&err );
audioQueueBuffer[ numBuffersToEnqueueLater ] = inBuffer;
numBuffersToEnqueueLater++;
}
}
//
// ASPropertyListenerProc
//
// Receives notification when the AudioFileStream has audio packets to be
// played. In response, this function creates the AudioQueue, getting it
// ready to begin playback (playback won't begin until audio packets are
// sent to the queue in ASEnqueueBuffer).
//
// This function is adapted from Apple's example in AudioFileStreamExample with
// kAudioQueueProperty_IsRunning listening added.
//
void ASPropertyListenerProc( void * inClientData,
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 * ioFlags)
{
//NSLog(@"STREAMER: ASPropertyListenerProc");
// this is called by audio file stream when it finds property values
AudioStreamer* streamer = (AudioStreamer *)inClientData;
[streamer
handlePropertyChangeForFileStream:inAudioFileStream
fileStreamPropertyID:inPropertyID
ioFlags:ioFlags];
}
//
// MyPacketsProc
//
// When the AudioStream has packets to be played, this function gets an
// idle audio buffer and copies the audio packets into it. The calls to
// MyEnqueueBuffer won't return until there are buffers available (or the
// playback has been stopped).
//
// This function is adapted from Apple's example in AudioFileStreamExample with
// CBR functionality added.
//
void ASPacketsProc( void * inClientData,
UInt32 inNumberBytes,
UInt32 inNumberPackets,
const void * inInputData,
AudioStreamPacketDescription *inPacketDescriptions)
{
//NSLog(@"STREAMER: ASPacketsProc");
// this is called by audio file stream when it finds packets of audio
AudioStreamer* streamer = (AudioStreamer *)inClientData;
[streamer
handleAudioPackets:inInputData
numberBytes:inNumberBytes
numberPackets:inNumberPackets
packetDescriptions:inPacketDescriptions];
}
//
// MyAudioQueueOutputCallback
//
// Called from the AudioQueue when playback of specific buffers completes. This
// function signals from the AudioQueue thread to the AudioStream thread that
// the buffer is idle and available for copying data.
//
// This function is unchanged from Apple's example in AudioFileStreamExample.
//
void MyAudioQueueOutputCallback( void* inClientData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer)
{
// this is called by the audio queue when it has finished decoding our data.
// The buffer is now free to be reused.
AudioStreamer* streamer = (AudioStreamer*)inClientData;
[streamer handleBufferCompleteForQueue:inAQ buffer:inBuffer];
}
void MyAudioQueueOutputCallback2( void* inClientData,
AudioQueueRef inAQ,
AudioQueueBufferRef inCompleteAQBuffer)
{
AudioStreamer* streamer = (AudioStreamer*)inClientData;
if (streamer.isDone) return;
}
//
// MyAudioQueueIsRunningCallback
//
// Called from the AudioQueue when playback is started or stopped. This
// information is used to toggle the observable "isPlaying" property and
// set the "finished" flag.
//
void MyAudioQueueIsRunningCallback(void *inUserData, AudioQueueRef inAQ, AudioQueuePropertyID inID)
{
AudioStreamer* streamer = (AudioStreamer *)inUserData;
[streamer handlePropertyChangeForQueue:inAQ propertyID:inID];
}
#ifdef TARGET_OS_IPHONE
//
// MyAudioSessionInterruptionListener
//
// Invoked if the audio session is interrupted (like when the phone rings)
//
void MyAudioSessionInterruptionListener(void *inClientData, UInt32 inInterruptionState)
{
// //NSLog(@"Audio session interruption");
AudioStreamer* streamer = (AudioStreamer *)inClientData;
[streamer handleInterruptionChangeToState:inInterruptionState];
}
void interruptionListenerCallback (void *inUserData, UInt32 interruptionState) {
// This callback, being outside the implementation block, needs a reference
//to the AudioPlayer object
AudioStreamer *player = (AudioStreamer *)inUserData;
if (interruptionState == kAudioSessionBeginInterruption) {
// //NSLog(@"kAudioSessionBeginInterruption");
//if ([player audioStreamer]) {
// if currently playing, pause
[player pause];
interruptedOnPlayback = YES;
//}
}// else if ((interruptionState == kAudioSessionEndInterruption) && player.interruptedOnPlayback) {
else if (interruptionState == kAudioSessionEndInterruption) {
// //NSLog(@"kAudioSessionEndInterruption");
AudioSessionSetActive( true );
// if the interruption was removed, and the app had been playing, resume playback
[player start];
interruptedOnPlayback = NO;
// player.state = AS_PAUSED;
}
}
#endif
#pragma mark CFReadStream Callback Function Implementations
//
// ReadStreamCallBack
//
// This is the callback for the CFReadStream from the network connection. This
// is where all network data is passed to the AudioFileStream.
//
// Invoked when an error occurs, the stream ends or we have data to read.
//
void ASReadStreamCallBack
(
CFReadStreamRef aStream,
CFStreamEventType eventType,
void* inClientInfo
)
{
AudioStreamer* streamer = (AudioStreamer *)inClientInfo;
[streamer handleReadFromStream:aStream eventType:eventType];
}
@implementation AudioStreamer
@synthesize errorCode;
@synthesize err;
@synthesize state;
@synthesize bytesFilled;
@synthesize byteOffset;
@synthesize bitRate;
@dynamic progress;
@synthesize audioFileStream;
@synthesize queueBuffersMutex;
@synthesize queueBufferReadyCondition;
@synthesize isDone;
@synthesize numPacketsToRead;
@synthesize packetPosition;
- (id)initStreamer
{
self = [super init];
//audioPool = [[AudioPool init] alloc];
return self;
}
//
// initWithURL
//
// Init method for the object.
//
- (id)initWithURL:(NSURL *)aURL
{
self = [super init];
if (self != nil)
{
url = [aURL retain];
}
AudioSessionInitialize( NULL,
NULL,
interruptionListenerCallback,
self );
AudioSessionSetActive( true );
return self;
}
//
// initWithURL
//
// Init method for the object.
//
- (id)initWithCFURL:(CFURLRef)aCFURL
{
self = [super init];
if (self != nil)
{
cfURL = aCFURL;
}
AudioSessionInitialize( NULL,
NULL,
interruptionListenerCallback,
self );
AudioSessionSetActive( true );
return self;
}
- (id)initWithRingBuffer:(VirtualRingBuffer *)ringBuff
bufferByteSize:(UInt32)bufferByteSize
numPacketsToRead:(UInt32)numPacketsToRead
gameObj:(Game *)game
{
self = [super init];
if (self != nil)
{
ringBuffer = ringBuff;
packetBufferSize = bufferByteSize;
_game = game;
}
AudioSessionInitialize( NULL,
NULL,
interruptionListenerCallback,
self );
AudioSessionSetActive( true );
return self;
}
//
// dealloc
//
// Releases instance memory.
//
- (void)dealloc
{
[self stop];
[notificationCenter release];
[url release];
[super dealloc];
}
//
// isFinishing
//
// returns YES if the audio has reached a stopping condition.
//
- (BOOL)isFinishing
{
@synchronized (self)
{
if ((errorCode != AS_NO_ERROR && state != AS_INITIALIZED) ||
((state == AS_STOPPING || state == AS_STOPPED) &&
stopReason != AS_STOPPING_TEMPORARILY))
{
return YES;
}
}
return NO;
}
//
// runLoopShouldExit
//
// returns YES if the run loop should exit.
//
- (BOOL)runLoopShouldExit
{
@synchronized(self)
{
if (errorCode != AS_NO_ERROR ||
(state == AS_STOPPED &&
stopReason != AS_STOPPING_TEMPORARILY) || [self hasNetworkTimedOut])
{
[self printState:state];
// NSLog(@"CLIENT: runLOOP SHOULD EXIT!!");
return YES;
} else {
// NSLog(@"CLIENT: run loop shouldn't exit!!");
}
}
return NO;
}
-(void)printState:(AudioStreamerState)state
{
switch (state) {
case AS_INITIALIZED:
NSLog(@"AudioStreamerState: AS_INITIALIZED");
break;
case AS_STARTING_FILE_THREAD:
NSLog(@"AudioStreamerState: AS_STARTING_FILE_THREAD");
break;
case AS_WAITING_FOR_DATA:
NSLog(@"AudioStreamerState: AS_WAITING_FOR_DATA");
break;
case AS_WAITING_FOR_QUEUE_TO_START:
NSLog(@"AudioStreamerState: AS_WAITING_FOR_QUEUE_TO_START");
break;
case AS_READY_TO_PLAY:
NSLog(@"AudioStreamerState: AS_READY_TO_PLAY");
break;
case AS_PLAYING:
NSLog(@"AudioStreamerState: AS_PLAYING");
break;
case AS_BUFFERING:
NSLog(@"AudioStreamerState: AS_BUFFERING");
break;
case AS_STOPPING:
NSLog(@"AudioStreamerState: AS_STOPPING");
break;
case AS_STOPPED:
NSLog(@"AudioStreamerState: AS_STOPPED");
break;
case AS_PAUSED:
NSLog(@"AudioStreamerState: AS_PAUSED");
break;
default:
break;
}
}
-(BOOL)hasNetworkTimedOut
{
if (PacketTypeEndOfSong) {
// if host reached end of song, then we don't worry about receiving any more packets
return NO;
}
double curTime = [Timer getCurTime];
double timeElapsedSinceLastPacket = [Timer getTimeDifference:_game->lastAudioPacketTimeStamp
time2:curTime];
BOOL hasNetworkTimedOut = (timeElapsedSinceLastPacket > networkTimeOutTime);
if (hasNetworkTimedOut) {
NSLog(@"network timed out! b/c cur time is %f and last packet time is %f, differnece is %f",curTime, _game->lastAudioPacketTimeStamp,timeElapsedSinceLastPacket);
} else {
NSLog(@"network DID NOT timed out! b/c cur time is %f and last packet time is %f, differnece is %f",curTime, _game->lastAudioPacketTimeStamp,timeElapsedSinceLastPacket);
}
return (hasNetworkTimedOut);
}
//
// stringForErrorCode:
//
// Converts an error code to a string that can be localized or presented
// to the user.
//
// Parameters:
// anErrorCode - the error code to convert
//
// returns the string representation of the error code
//
+ (NSString *)stringForErrorCode:(AudioStreamerErrorCode)anErrorCode
{
switch (anErrorCode)
{
case AS_NO_ERROR:
return AS_NO_ERROR_STRING;
case AS_FILE_STREAM_GET_PROPERTY_FAILED:
return AS_FILE_STREAM_GET_PROPERTY_FAILED_STRING;
case AS_FILE_STREAM_SEEK_FAILED:
return AS_FILE_STREAM_SEEK_FAILED_STRING;
case AS_FILE_STREAM_PARSE_BYTES_FAILED:
return AS_FILE_STREAM_PARSE_BYTES_FAILED_STRING;
case AS_AUDIO_QUEUE_CREATION_FAILED:
return AS_AUDIO_QUEUE_CREATION_FAILED_STRING;
case AS_AUDIO_QUEUE_BUFFER_ALLOCATION_FAILED:
return AS_AUDIO_QUEUE_BUFFER_ALLOCATION_FAILED_STRING;
case AS_AUDIO_QUEUE_ENQUEUE_FAILED:
return AS_AUDIO_QUEUE_ENQUEUE_FAILED_STRING;
case AS_AUDIO_QUEUE_ADD_LISTENER_FAILED:
return AS_AUDIO_QUEUE_ADD_LISTENER_FAILED_STRING;
case AS_AUDIO_QUEUE_REMOVE_LISTENER_FAILED:
return AS_AUDIO_QUEUE_REMOVE_LISTENER_FAILED_STRING;
case AS_AUDIO_QUEUE_START_FAILED:
return AS_AUDIO_QUEUE_START_FAILED_STRING;
case AS_AUDIO_QUEUE_BUFFER_MISMATCH:
return AS_AUDIO_QUEUE_BUFFER_MISMATCH_STRING;
case AS_FILE_STREAM_OPEN_FAILED:
return AS_FILE_STREAM_OPEN_FAILED_STRING;
case AS_FILE_STREAM_CLOSE_FAILED:
return AS_FILE_STREAM_CLOSE_FAILED_STRING;
case AS_AUDIO_QUEUE_DISPOSE_FAILED:
return AS_AUDIO_QUEUE_DISPOSE_FAILED_STRING;
case AS_AUDIO_QUEUE_PAUSE_FAILED:
return AS_AUDIO_QUEUE_DISPOSE_FAILED_STRING;
case AS_AUDIO_QUEUE_FLUSH_FAILED:
return AS_AUDIO_QUEUE_FLUSH_FAILED_STRING;
case AS_AUDIO_DATA_NOT_FOUND:
return AS_AUDIO_DATA_NOT_FOUND_STRING;
case AS_GET_AUDIO_TIME_FAILED:
return AS_GET_AUDIO_TIME_FAILED_STRING;
case AS_NETWORK_CONNECTION_FAILED:
return AS_NETWORK_CONNECTION_FAILED_STRING;
case AS_AUDIO_QUEUE_STOP_FAILED:
return AS_AUDIO_QUEUE_STOP_FAILED_STRING;
case AS_AUDIO_STREAMER_FAILED:
return AS_AUDIO_STREAMER_FAILED_STRING;
case AS_AUDIO_BUFFER_TOO_SMALL:
return AS_AUDIO_BUFFER_TOO_SMALL_STRING;
case ABSD_SETUP_FAILED:
return ABSD_SETUP_FAILED_STRING;
default:
return AS_AUDIO_STREAMER_FAILED_STRING;
}
return AS_AUDIO_STREAMER_FAILED_STRING;
}
//
// failWithErrorCode:
//
// Sets the playback state to failed and logs the error.
//
// Parameters:
// anErrorCode - the error condition
//
- (void)failWithErrorCode:(AudioStreamerErrorCode)anErrorCode
{
@synchronized(self)
{
if (errorCode != AS_NO_ERROR)
{
// Only set the error once.
return;
}
errorCode = anErrorCode;
if (err)
{
char *errChars = (char *)&err;
//NSLog(@"%@ err: %c%c%c%c %d\n",
[AudioStreamer stringForErrorCode:anErrorCode],
errChars[3], errChars[2], errChars[1], errChars[0],
(int)err;
}
else
{
// //NSLog(@"%@", [AudioStreamer stringForErrorCode:anErrorCode]);
}
if (state == AS_PLAYING ||
state == AS_PAUSED ||
state == AS_BUFFERING)
{
self.state = AS_STOPPING;
stopReason = AS_STOPPING_ERROR;
AudioQueueStop(audioQueue, true);
}
#ifdef TARGET_OS_IPHONE
UIAlertView *alert =
[[[UIAlertView alloc]
initWithTitle:NSLocalizedStringFromTable(@"Audio Error", @"Errors", nil)
message:NSLocalizedStringFromTable([AudioStreamer stringForErrorCode:self.errorCode], @"Errors", nil)
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil]
autorelease];
[alert
performSelector:@selector(show)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
#else
NSAlert *alert =
[NSAlert
alertWithMessageText:NSLocalizedString(@"Audio Error", @"")
defaultButton:NSLocalizedString(@"OK", @"")
alternateButton:nil
otherButton:nil
informativeTextWithFormat:[AudioStreamer stringForErrorCode:self.errorCode]];
[alert
performSelector:@selector(runModal)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
#endif
}
}
//
// setState:
//
// Sets the state and sends a notification that the state has changed.
//
// This method
//
// Parameters:
// anErrorCode - the error condition
//
- (void)setState:(AudioStreamerState)aStatus
{
@synchronized(self)
{
if (state != aStatus)
{
state = aStatus;
NSNotification *notification =
[NSNotification
notificationWithName:ASStatusChangedNotification
object:self];
[notificationCenter
performSelector:@selector(postNotification:)
onThread:[NSThread mainThread]
withObject:notification
waitUntilDone:NO];
}
}
}
//
// isPlaying
//
// returns YES if the audio currently playing.
//
- (BOOL)isPlaying
{
if (state == AS_PLAYING)
{
return YES;
}
return NO;
}
//
// isPaused
//
// returns YES if the audio currently playing.
//
- (BOOL)isPaused
{
if (state == AS_PAUSED)
{
return YES;
}
return NO;
}
//
// isWaiting
//
// returns YES if the AudioStreamer is waiting for a state transition of some
// kind.
//
- (BOOL)isWaiting
{
@synchronized(self)
{
if ([self isFinishing] ||
state == AS_STARTING_FILE_THREAD||
state == AS_WAITING_FOR_DATA ||
state == AS_WAITING_FOR_QUEUE_TO_START ||
state == AS_BUFFERING)
{
return YES;
}
}
return NO;
}
//
// isIdle
//
// returns YES if the AudioStream is in the AS_INITIALIZED state (i.e.
// isn't doing anything).
//
- (BOOL)isIdle
{
if (state == AS_INITIALIZED)
{
return YES;
}
return NO;
}
-(BOOL)openBTWIFIFileStream
{
@synchronized(self)
{
NSAssert(stream == nil && audioFileStream == nil,
@"audioFileStream already initialized");
// create an audio file stream parser
err = AudioFileStreamOpen(self, ASPropertyListenerProc, ASPacketsProc,
0, &audioFileStream);
if (err)
{
[self failWithErrorCode:AS_FILE_STREAM_OPEN_FAILED];
return NO;
}
}
}
-(BOOL)openLocalFileStream
{
@synchronized(self)
{
NSAssert(stream == nil && audioFileStream == nil,
@"audioFileStream already initialized");
/* // create an audio file stream parser
err = AudioFileStreamOpen(self, ASPropertyListenerProc, ASPacketsProc,
kAudioFileMPEG4Type, &audioFileStream);
if (err)
{
[self failWithErrorCode:AS_FILE_STREAM_OPEN_FAILED];
return NO;
}
*/
//
// Create the GET request
//
// //NSLog(@"opening local file with URL %@",self->cfURL);
stream = CFReadStreamCreateWithFile(NULL, self->cfURL);
//
// Open the stream
//
if (!CFReadStreamOpen(stream))
{
CFRelease(stream);
UIAlertView *alert =
[[UIAlertView alloc]
initWithTitle:NSLocalizedStringFromTable(@"File Error", @"Errors", nil)
message:NSLocalizedStringFromTable(@"Unable to configure network read stream.", @"Errors", nil)
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert
performSelector:@selector(show)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:YES];
[alert release];
return NO;
}
//
// Set our callback function to receive the data
//
CFStreamClientContext context = {0, self, NULL, NULL, NULL};
Boolean streamSupportsAsyncNot = CFReadStreamSetClient(
stream,
kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered | kCFStreamEventCanAcceptBytes | kCFStreamEventOpenCompleted | kCFStreamEventNone,
ASReadStreamCallBack,
&context);
assert(streamSupportsAsyncNot == true);
CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
return YES;
}
/*
* we read the audio data from the ring buffer as well as
* the packet descriptions (VBR data).
*/
-(BOOL)readFromRingBuffer
{
NSLog(@"READER: readFromRingBuffer, setting streamer state to AS_BUFFERING");
state = AS_BUFFERING;
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
ringBufferReaderTimer = [[NSTimer alloc] initWithFireDate:fireDate
interval:0.25
target:self
selector:@selector(readRingBufferDataBit)
userInfo:NULL
repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
NSLog(@"this is the runloops current mode %@",[runLoop currentMode]);
[runLoop addTimer:ringBufferReaderTimer forMode:NSDefaultRunLoopMode];
[ringBufferReaderTimer fire];
NSLog(@"end of readFromRingBuffer");
return YES;
}
-(void)readRingBufferDataBit
{
if (state == AS_STOPPED) {
[ringBufferReaderTimer invalidate];
return;
}
void *readPointer;
allBytesAvailable = [ringBuffer lengthAvailableToReadReturningPointer:&readPointer];
if (allBytesAvailable == 0) {
NSLog(@"READER: OOOOOPTS.. NOTHING TO READ YET.. EXIT THE READ FROM RING BUFFER");
return;
}
// we store all the bytes grabbed unto ringBufferReadData first, so that we can
// purge the ring buffer the best we can
NSData * ringBufferReadData = [NSData dataWithBytes:readPointer length:allBytesAvailable];
// NSLog(@"READER: THESE ARE THE BYTES WE ARE ABOUT TO READ FROM RING BUFFER %lu ",allBytesAvailable);
[ringBuffer didReadLength:allBytesAvailable];
UInt32 ringBufferReadDataOffset = 0;
while (ringBufferReadDataOffset < allBytesAvailable) {
NSData * packetData = [ringBufferReadData subdataWithRange:NSMakeRange(8 + ringBufferReadDataOffset, 2)];
PacketType packetType = [packetData rw_int16AtOffset:0];
packetData = [ringBufferReadData subdataWithRange:NSMakeRange(4 + ringBufferReadDataOffset, 4)];
UInt32 packNumber = [packetData rw_int32AtOffset:0];
int packetBytesFilled = [[ringBufferReadData subdataWithRange:NSMakeRange(12 + ringBufferReadDataOffset, 4)] rw_int32AtOffset:0];
int packetDescriptionsBytesFilled = [[ringBufferReadData subdataWithRange:NSMakeRange(16 + ringBufferReadDataOffset, 4)] rw_int32AtOffset:0];
int offset = AUDIO_BUFFER_PACKET_HEADER_SIZE + ringBufferReadDataOffset;
NSData* audioBufferData = [NSData dataWithBytes:(char *)([ringBufferReadData bytes] + offset) length:packetBytesFilled];
offset += packetBytesFilled ;
NSData *packetDescriptionsData = [NSData dataWithBytes:(char *)([ringBufferReadData bytes] + offset) length:packetDescriptionsBytesFilled];
UInt32 inNumberPackets = packetDescriptionsBytesFilled/AUDIO_STREAM_PACK_DESC_SIZE;
AudioStreamPacketDescription *inPacketDescriptions;
inPacketDescriptions = [self populatePacketDescriptionArray:packetDescriptionsData
packetDescriptionNumber:inNumberPackets];
if (inPacketDescriptions[0].mDataByteSize > 65536)
{
NSLog(@"packet description size is abnormally large.. soething is wrong");
}
[self handleAudioPackets:[audioBufferData bytes]
numberBytes:packetBytesFilled
numberPackets:inNumberPackets
packetDescriptions:inPacketDescriptions];
ringBufferReadDataOffset += AUDIO_BUFFER_PACKET_HEADER_SIZE + packetBytesFilled + packetDescriptionsBytesFilled;
}
}
-(AudioStreamPacketDescription *)populatePacketDescriptionArray:(NSData *)packetDescData
packetDescriptionNumber:(UInt32)packetDescNumber
{
AudioStreamPacketDescription *localPacketDescriptions = (AudioStreamPacketDescription *)
malloc(sizeof(AudioStreamPacketDescription) * packetDescNumber);
UInt32 offset = 0;
for (int i=0; i < packetDescNumber; i++) {
localPacketDescriptions[i].mStartOffset = [packetDescData rw_int32AtOffset:offset];
offset += sizeof(UInt32);
localPacketDescriptions[i].mVariableFramesInPacket = [packetDescData rw_int32AtOffset:offset];
offset += sizeof(UInt32);
localPacketDescriptions[i].mDataByteSize = [packetDescData rw_int32AtOffset:offset];
offset += sizeof(UInt32);
}
return localPacketDescriptions;
}
//
// openFileStream
//
// Open the audioFileStream to parse data and the fileHandle as the data
// source.
//
- (BOOL)openFileStream
{
@synchronized(self)
{
NSAssert(stream == nil && audioFileStream == nil,
@"audioFileStream already initialized");
//
// Attempt to guess the file type from the URL. Reading the MIME type
// from the CFReadStream would be a better approach since lots of
// URL's don't have the right extension.
//
// If you have a fixed file-type, you may want to hardcode this.
//
AudioFileTypeID fileTypeHint = kAudioFileMP3Type;
NSString *fileExtension = [[url path] pathExtension];
if ([fileExtension isEqual:@"mp3"])
{
fileTypeHint = kAudioFileMP3Type;
}
else if ([fileExtension isEqual:@"wav"])