-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAudioStreamer.m
1947 lines (1770 loc) · 48.3 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
//
// AudioStreamer.m
// StreamingAudioPlayer
//
// Created by Matt Gallagher on 27/09/08.
// Copyright 2008 Matt Gallagher. All rights reserved.
//
// Permission is given to use this source code file, free of charge, in any
// project, commercial or otherwise, entirely at your risk, with the condition
// that any redistribution (in part or whole) of source code must retain
// this copyright and permission notice. Attribution in compiled projects is
// appreciated but not required.
//
#import "AudioStreamer.h"
#if TARGET_OS_IPHONE
#import <CFNetwork/CFNetwork.h>
#endif
#define BitRateEstimationMaxPackets 5000
#define BitRateEstimationMinPackets 50
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 kAQDefaultBufSize.";
extern void ASReadStreamCallBack(CFReadStreamRef aStream, CFStreamEventType eventType, void* inClientInfo); //private, avoid warning
@interface AudioStreamer ()
@property (readwrite, nonatomic) AudioStreamerState state;
- (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;
#if TARGET_OS_IPHONE
- (void)handleInterruptionChangeToState:(AudioQueuePropertyID)inInterruptionState;
#endif
- (void)internalSeekToTime:(double)newSeekTime;
- (void)enqueueBuffer;
- (void)handleReadFromStream:(CFReadStreamRef)aStream
eventType:(CFStreamEventType)eventType;
@end
#pragma mark Audio Callback Function Prototypes
void MyAudioQueueOutputCallback(void* inClientData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer);
void MyAudioQueueIsRunningCallback(void *inUserData, AudioQueueRef inAQ, AudioQueuePropertyID inID);
void MyPropertyListenerProc( void * inClientData,
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 * ioFlags);
void MyPacketsProc( void * inClientData,
UInt32 inNumberBytes,
UInt32 inNumberPackets,
const void * inInputData,
AudioStreamPacketDescription *inPacketDescriptions);
OSStatus MyEnqueueBuffer(AudioStreamer* myData);
#if 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 MyPropertyListenerProc( void * inClientData,
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 * ioFlags)
{
// 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 MyPacketsProc( void * inClientData,
UInt32 inNumberBytes,
UInt32 inNumberPackets,
const void * inInputData,
AudioStreamPacketDescription *inPacketDescriptions)
{
// 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];
}
//
// 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];
}
#if TARGET_OS_IPHONE
//
// MyAudioSessionInterruptionListener
//
// Invoked if the audio session is interrupted (like when the phone rings)
//
void MyAudioSessionInterruptionListener(void *inClientData, UInt32 inInterruptionState)
{
AudioStreamer* streamer = (AudioStreamer *)inClientData;
[streamer handleInterruptionChangeToState:inInterruptionState];
}
#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 state;
@synthesize bitRate;
@synthesize httpHeaders;
//
// initWithURL
//
// Init method for the object.
//
- (id)initWithURL:(NSURL *)aURL
{
self = [super init];
if (self != nil)
{
url = [aURL retain];
}
return self;
}
//
// dealloc
//
// Releases instance memory.
//
- (void)dealloc
{
[self stop];
[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))
{
return YES;
}
}
return NO;
}
//
// 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;
default:
return AS_AUDIO_STREAMER_FAILED_STRING;
}
return AS_AUDIO_STREAMER_FAILED_STRING;
}
//
// presentAlertWithTitle:message:
//
// Common code for presenting error dialogs
//
// Parameters:
// title - title for the dialog
// message - main test for the dialog
//
- (void)presentAlertWithTitle:(NSString*)title message:(NSString*)message
{
return;
#if TARGET_OS_IPHONE
UIAlertView *alert = [
[[UIAlertView alloc]
initWithTitle:title
message:message
delegate:self
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles: nil]
autorelease];
[alert
performSelector:@selector(show)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
#else
NSAlert *alert =
[NSAlert
alertWithMessageText:title
defaultButton:NSLocalizedString(@"OK", @"")
alternateButton:nil
otherButton:nil
informativeTextWithFormat:message];
[alert
performSelector:@selector(runModal)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
#endif
}
//
// 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);
}
[self presentAlertWithTitle:NSLocalizedStringFromTable(@"File Error", @"Errors", nil)
message:NSLocalizedStringFromTable(@"Unable to configure network read stream.", @"Errors", nil)];
}
}
//
// mainThreadStateNotification
//
// Method invoked on main thread to send notifications to the main thread's
// notification center.
//
- (void)mainThreadStateNotification
{
NSNotification *notification =
[NSNotification
notificationWithName:ASStatusChangedNotification
object:self];
[[NSNotificationCenter defaultCenter]
postNotification:notification];
}
//
// 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;
if ([[NSThread currentThread] isEqual:[NSThread mainThread]])
{
[self mainThreadStateNotification];
}
else
{
[self
performSelectorOnMainThread:@selector(mainThreadStateNotification)
withObject:nil
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;
}
//
// hintForFileExtension:
//
// Generates a first guess for the file type based on the file's extension
//
// Parameters:
// fileExtension - the file extension
//
// returns a file type hint that can be passed to the AudioFileStream
//
+ (AudioFileTypeID)hintForFileExtension:(NSString *)fileExtension
{
AudioFileTypeID fileTypeHint = kAudioFileMP3Type;
if ([fileExtension isEqual:@"mp3"])
{
fileTypeHint = kAudioFileMP3Type;
}
else if ([fileExtension isEqual:@"wav"])
{
fileTypeHint = kAudioFileWAVEType;
}
else if ([fileExtension isEqual:@"aifc"])
{
fileTypeHint = kAudioFileAIFCType;
}
else if ([fileExtension isEqual:@"aiff"])
{
fileTypeHint = kAudioFileAIFFType;
}
else if ([fileExtension isEqual:@"m4a"])
{
fileTypeHint = kAudioFileM4AType;
}
else if ([fileExtension isEqual:@"mp4"])
{
fileTypeHint = kAudioFileMPEG4Type;
}
else if ([fileExtension isEqual:@"caf"])
{
fileTypeHint = kAudioFileCAFType;
}
else if ([fileExtension isEqual:@"aac"])
{
fileTypeHint = kAudioFileAAC_ADTSType;
}
return fileTypeHint;
}
//
// openReadStream
//
// Open the audioFileStream to parse data and the fileHandle as the data
// source.
//
- (BOOL)openReadStream
{
@synchronized(self)
{
NSAssert([[NSThread currentThread] isEqual:internalThread],
@"File stream download must be started on the internalThread");
NSAssert(stream == nil, @"Download stream already initialized");
//
// Create the HTTP GET request
//
CFHTTPMessageRef message= CFHTTPMessageCreateRequest(NULL, (CFStringRef)@"GET", (CFURLRef)url, kCFHTTPVersion1_1);
//
// If we are creating this request to seek to a location, set the
// requested byte range in the headers.
//
if (fileLength > 0 && seekByteOffset > 0)
{
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Range"),
(CFStringRef)[NSString stringWithFormat:@"bytes=%ld-%ld", seekByteOffset, fileLength]);
discontinuous = YES;
}
//
// Create the read stream that will receive data from the HTTP request
//
stream = CFReadStreamCreateForHTTPRequest(NULL, message);
CFRelease(message);
//
// Enable stream redirection
//
if (CFReadStreamSetProperty(
stream,
kCFStreamPropertyHTTPShouldAutoredirect,
kCFBooleanTrue) == false)
{
[self presentAlertWithTitle:NSLocalizedStringFromTable(@"File Error", @"Errors", nil)
message:NSLocalizedStringFromTable(@"Unable to configure network read stream.", @"Errors", nil)];
return NO;
}
//
// Handle SSL connections
//
if( [[url absoluteString] rangeOfString:@"https"].location != NSNotFound )
{
NSDictionary *sslSettings =
[NSDictionary dictionaryWithObjectsAndKeys:
(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamSSLLevel,
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredRoots,
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
[NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
[NSNull null], kCFStreamSSLPeerName,
nil];
CFReadStreamSetProperty(stream, kCFStreamPropertySSLSettings, sslSettings);
}
//
// We're now ready to receive data
//
self.state = AS_WAITING_FOR_DATA;
//
// Open the stream
//
if (!CFReadStreamOpen(stream))
{
CFRelease(stream);
[self presentAlertWithTitle:NSLocalizedStringFromTable(@"File Error", @"Errors", nil)
message:NSLocalizedStringFromTable(@"Unable to configure network read stream.", @"Errors", nil)];
return NO;
}
//
// Set our callback function to receive the data
//
CFStreamClientContext context = {0, self, NULL, NULL, NULL};
CFReadStreamSetClient(
stream,
kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
ASReadStreamCallBack,
&context);
CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
return YES;
}
//
// startInternal
//
// This is the start method for the AudioStream thread. This thread is created
// because it will be blocked when there are no audio buffers idle (and ready
// to receive audio data).
//
// Activity in this thread:
// - Creation and cleanup of all AudioFileStream and AudioQueue objects
// - Receives data from the CFReadStream
// - AudioFileStream processing
// - Copying of data from AudioFileStream into audio buffers
// - Stopping of the thread because of end-of-file
// - Stopping due to error or failure
//
// Activity *not* in this thread:
// - AudioQueue playback and notifications (happens in AudioQueue thread)
// - Actual download of NSURLConnection data (NSURLConnection's thread)
// - Creation of the AudioStreamer (other, likely "main" thread)
// - Invocation of -start method (other, likely "main" thread)
// - User/manual invocation of -stop (other, likely "main" thread)
//
// This method contains bits of the "main" function from Apple's example in
// AudioFileStreamExample.
//
- (void)startInternal
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@synchronized(self)
{
if (state != AS_STARTING_FILE_THREAD)
{
if (state != AS_STOPPING &&
state != AS_STOPPED)
{
NSLog(@"### Not starting audio thread. State code is: %u", state);
}
self.state = AS_INITIALIZED;
[pool release];
return;
}
#if TARGET_OS_IPHONE
//
// Set the audio session category so that we continue to play if the
// iPhone/iPod auto-locks.
//
AudioSessionInitialize (
NULL, // 'NULL' to use the default (main) run loop
NULL, // 'NULL' to use the default run loop mode
MyAudioSessionInterruptionListener, // a reference to your interruption callback
self // data to pass to your interruption listener callback
);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (
kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory
);
AudioSessionSetActive(true);
#endif
// initialize a mutex and condition so that we can block on buffers in use.
pthread_mutex_init(&queueBuffersMutex, NULL);
pthread_cond_init(&queueBufferReadyCondition, NULL);
if (![self openReadStream])
{
goto cleanup;
}
}
//
// Process the run loop until playback is finished or failed.
//
BOOL isRunning = YES;
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
do
{
//NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
isRunning = [theRL
runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
if (seekWasRequested) {
@synchronized(self) {
[self internalSeekToTime:requestedSeekTime];
seekWasRequested = NO;
}
}
//
// If there are no queued buffers, we need to check here since the
// handleBufferCompleteForQueue:buffer: should not change the state
// (may not enter the synchronized section).
//
if (buffersUsed == 0 && self.state == AS_PLAYING)
{
err = AudioQueuePause(audioQueue);
if (err)
{
[self failWithErrorCode:AS_AUDIO_QUEUE_PAUSE_FAILED];
return;
}
self.state = AS_BUFFERING;
}
//[pool2 release];
} while (isRunning && ![self runLoopShouldExit]);
cleanup:
@synchronized(self)
{
//
// Cleanup the read stream if it is still open
//
if (stream)
{
CFReadStreamClose(stream);
CFRelease(stream);
stream = nil;
}
//
// Close the audio file strea,
//
if (audioFileStream)
{
err = AudioFileStreamClose(audioFileStream);
audioFileStream = nil;
if (err)
{
[self failWithErrorCode:AS_FILE_STREAM_CLOSE_FAILED];
}
}
//
// Dispose of the Audio Queue
//
if (audioQueue)
{
err = AudioQueueDispose(audioQueue, true);
audioQueue = nil;
if (err)
{
[self failWithErrorCode:AS_AUDIO_QUEUE_DISPOSE_FAILED];
}
}
pthread_mutex_destroy(&queueBuffersMutex);
pthread_cond_destroy(&queueBufferReadyCondition);
#if TARGET_OS_IPHONE
AudioSessionSetActive(false);
#endif
[httpHeaders release];
httpHeaders = nil;
bytesFilled = 0;
packetsFilled = 0;
seekByteOffset = 0;
packetBufferSize = 0;
self.state = AS_INITIALIZED;
[internalThread release];
internalThread = nil;
}
[pool release];
}
//
// start
//
// Calls startInternal in a new thread.
//
- (void)start
{
@synchronized (self)
{
if (state == AS_PAUSED)
{
[self pause];
}
else if (state == AS_INITIALIZED)
{
NSAssert([[NSThread currentThread] isEqual:[NSThread mainThread]],
@"Playback can only be started from the main thread.");
notificationCenter =
[[NSNotificationCenter defaultCenter] retain];
self.state = AS_STARTING_FILE_THREAD;
internalThread =
[[NSThread alloc]
initWithTarget:self
selector:@selector(startInternal)
object:nil];
[internalThread start];
}
}
}
// internalSeekToTime:
//
// Called from our internal runloop to reopen the stream at a seeked location
//
- (void)internalSeekToTime:(double)newSeekTime
{
if ([self calculatedBitRate] == 0.0 || fileLength <= 0)
{
return;
}
//
// Calculate the byte offset for seeking
//
seekByteOffset = dataOffset +
(newSeekTime / self.duration) * (fileLength - dataOffset);
//
// Attempt to leave 1 useful packet at the end of the file (although in
// reality, this may still seek too far if the file has a long trailer).
//
if (seekByteOffset > fileLength - 2 * packetBufferSize)
{
seekByteOffset = fileLength - 2 * packetBufferSize;
}
//
// Store the old time from the audio queue and the time that we're seeking
// to so that we'll know the correct time progress after seeking.
//
seekTime = newSeekTime;
//
// Attempt to align the seek with a packet boundary
//
double calculatedBitRate = [self calculatedBitRate];
if (packetDuration > 0 &&
calculatedBitRate > 0)
{
UInt32 ioFlags = 0;
SInt64 packetAlignedByteOffset;
SInt64 seekPacket = floor(newSeekTime / packetDuration);
err = AudioFileStreamSeek(audioFileStream, seekPacket, &packetAlignedByteOffset, &ioFlags);
if (!err && !(ioFlags & kAudioFileStreamSeekFlag_OffsetIsEstimated))
{
seekTime -= ((seekByteOffset - dataOffset) - packetAlignedByteOffset) * 8.0 / calculatedBitRate;
seekByteOffset = packetAlignedByteOffset + dataOffset;
}
}
//
// Close the current read straem
//
if (stream)
{
CFReadStreamClose(stream);
CFRelease(stream);
stream = nil;
}
//
// Stop the audio queue
//
self.state = AS_STOPPING;
stopReason = AS_STOPPING_TEMPORARILY;
err = AudioQueueStop(audioQueue, true);
if (err)
{
[self failWithErrorCode:AS_AUDIO_QUEUE_STOP_FAILED];
return;
}
//
// Re-open the file stream. It will request a byte-range starting at
// seekByteOffset.
//
[self openReadStream];
}
//
// seekToTime:
//
// Attempts to seek to the new time. Will be ignored if the bitrate or fileLength
// are unknown.
//
// Parameters:
// newTime - the time to seek to
//
- (void)seekToTime:(double)newSeekTime
{
@synchronized(self)