-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWKAudioStreamer.m
773 lines (646 loc) · 24.8 KB
/
WKAudioStreamer.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
//
// WKAudioStreamer.m
// WKAudioStreamer
//
// Created by Chenguang Wang on 11/16/12.
// Copyright (c) 2012 Chenguang Wang. All rights reserved.
//
#import "WKAudioStreamer.h"
#import <AudioToolbox/AudioToolbox.h>
#define AQBUF_N 5
#define AQBUF_DEFAULT_SIZE 0x25000 // 160kb
// WKAudioStreamer only stores the audio data part as parsed packets.
// Clients could get the original full data (including audio header, ...) with the delegate method onDataReceived:availFrom:to.
//
// WKAudioStreamer uses a two layer caching structure:
// L1: emptyQueueBuffers
// L2: parsedPackets
//
// initial values:
// BOOL audioQueuePaused = YES set to YES iff: L2.next == nil and L1.n == AQBUF_N ("no data" in L1,L2)
// or playerPlaying = NO (paused/finished)
// BOOL playerPlaying = NO
// BOOL finishedFeedingParser = NO set to YES iff: no new incoming data from HTTP connection
// BOOL streamerRunning = NO
//
// L1's callback:
// onNewEmptyQueueBufferReceived: @synchronized (self)
// push new data onto L1
// feedL1()
//
// L2's callback:
// onParsedPacketsReceived: @synchronized (self)
// push new data onto L2
// feedL1()
//
// feedL1: @synchronized (self)
// while L2.next != nil and L1.n != 0:
// buf <- L1.pop()
// if L2.next.size > buf.capacity:
// free & allocate buf
// while L2.next != nil:
// fill in buf with L2
// L2.next = L2.next.next
// enqueue buf
// if audioQueuePaused and playerPlaying:
// audioQueue.start()
// audioQueuePaused = NO
// if L2.next == nil and L1.n == AQBUF_N: // no data in L1,L2
// if !audioQueuePaused and playerPlaying: // not paused by user, audio queue still playing
// audioQueuePaused = YES
// audioQueue.pause()
// if finishedFeedingParser: // also no incoming data
// playerPlaying = NO
// set L2.current to L2.head
// send onPlayingFinished to delegate
//
// play: @synchronized (self)
// if playerPlaying: // still playing (maybe still waiting for data)
// return
// if !streamerRunning and !finishedFeedingParser:
// startStreaming
// playerPlaying = YES
// if L2.next != nil and L1.n != AQBUF_N: // previously paused by user
// audioQueue.start()
// audioQueuePaused = NO
//
// connection:didReceiveData: @synchronized (self)
// feed parser
// send onDataReceived to delegate
//
// connectionDidFinishedLoading: @synchronized (self)
// finishedFeedingParser = YES // no new incoming data
// if audioQueuePaused and playerPlaying: // no data in L1,L2; not paused by user
// playerPlaying = NO
// set L2.current to L2.head
// send onPlayerFinished to delegate
@interface WKAudioStreamer () {
@private
id<WKAudioStreamerDelegate> _delegate;
NSString *_url;
NSURLConnection *_connection;
NSUInteger _resumeStreamingFrom;
NSUInteger _playedAudioBytes;
NSUInteger _streamingStartedFrom;
AudioFileStreamID _afsID;
AudioQueueRef _aq;
AudioQueueBufferRef _aqBufs[AQBUF_N]; // FIXME: remember to call AudioQueueFreeBuffer().
NSMutableArray *_emptyQueueBuffers;
NSMutableArray *_parsedPackets;
NSMutableArray *_packetsDesc;
BOOL _audioQueuePaused;
BOOL _playerPlaying;
BOOL _finishedFeedingParser;
BOOL _streamerRunning;
BOOL _playerBlocked; // waiting for incoming data
BOOL _restartStreamingNeverCalled;
int _l2_curIdx;
int _fileSize;
BOOL _finishedParsingHeader;
AudioStreamBasicDescription *_streamDesc;
unsigned int _packetCount;
unsigned int _frameCount;
UInt32 _bitRate;
SInt64 _dataOffset;
}
- (double)audioBytesPlayedToAudioPosition;
// callbacks
- (void)onParsedPacketsReceived:(const void *)d
audioDataSize:(UInt32)d_size
numberOfPackets:(UInt32)packet_n
packetDescriptions:(AudioStreamPacketDescription *)packet_desc;
- (void)onPropertyAcquired:(AudioFilePropertyID)ppt_id
audioFileStreamID:(AudioFileStreamID)afs_id;
- (void)onNewEmptyQueueBufferReceived:(AudioQueueRef)inAQ buffer:(AudioQueueBufferRef)inBuffer;
- (void)feedL1;
// some helper methods used for seeking
- (UInt32)bitRate;
- (Float64)framesPerPacket;
- (Float64)bytesPerPacket;
- (void)sendBlocked;
- (void)sendBlockingEnded;
@end
static void afs_audio_data_cb(void *inClientData,
UInt32 inNumberBytes,
UInt32 inNumberPackets,
const void *inInputData,
AudioStreamPacketDescription *inPacketDescriptions) {
WKAudioStreamer *s = (__bridge WKAudioStreamer *)inClientData;
[s onParsedPacketsReceived:inInputData
audioDataSize:inNumberBytes
numberOfPackets:inNumberPackets
packetDescriptions:inPacketDescriptions];
}
static void afs_properties_cb(void *inClientData,
AudioFileStreamID inAudioFileStream,
AudioFileStreamPropertyID inPropertyID,
UInt32 *ioFlags) {
WKAudioStreamer *s = (__bridge WKAudioStreamer *)inClientData;
[s onPropertyAcquired:inPropertyID audioFileStreamID:inAudioFileStream];
}
static void aq_new_buffer_cb(void *inUserData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer) {
WKAudioStreamer *s = (__bridge WKAudioStreamer *)inUserData;
[s onNewEmptyQueueBufferReceived:inAQ buffer:inBuffer];
}
//
//
// actual implementation
//
//
@implementation WKAudioStreamer
+ (id)streamerWithURLString:(NSString *)url
delegate:(id<WKAudioStreamerDelegate>)delegate {
WKAudioStreamer *streamer = [WKAudioStreamer new];
streamer->_delegate = delegate;
streamer->_url = url;
return streamer;
}
- (NSString *)requestedURL {
return _url;
}
- (id)init {
self = [super init];
if (self != nil) {
// L1.
_emptyQueueBuffers = [NSMutableArray new];
_dataOffset = -1;
_audioQueuePaused = YES;
_restartStreamingNeverCalled = YES;
}
return self;
}
- (void)dealloc {
if (_aq) {
AudioQueueDispose(_aq, true);
}
if (_afsID) {
AudioFileStreamClose(_afsID);
}
if (_streamDesc) {
free(_streamDesc);
}
}
- (BOOL)play {
@synchronized(self) {
if (_playerPlaying) {
return NO;
}
if (_connection == nil && !_finishedFeedingParser) {
[self startStreaming];
}
_playerPlaying = YES;
if (_aq == NULL && _streamDesc != NULL) {
// FIXME: error checking
AudioQueueNewOutput(_streamDesc, aq_new_buffer_cb, (__bridge void *)(self), NULL, NULL, 0, &_aq);
for (int i = 0; i < AQBUF_N; i++) {
AudioQueueAllocateBuffer(_aq, AQBUF_DEFAULT_SIZE, &_aqBufs[i]);
[_emptyQueueBuffers addObject:[NSData dataWithBytes:&_aqBufs[i] length:sizeof(AudioQueueBufferRef)]];
}
}
// this should be able to handle the situation of:
// 1. previously paused
// 2. calling play after fully streamed
[self feedL1];
if (_audioQueuePaused && _aq != NULL) {
AudioQueueStart(_aq, NULL);
_audioQueuePaused = NO;
}
return YES;
}
}
- (BOOL)pause {
// pause will still work even if:
// 1. the streamer is still streaming the header; or
// 2. play is not called previously.
//
// because we check _playerPlaying first. it would not be YES if play is not called previously; and
// after play, we are 100% sure that audio queue is created; so pause _aq should have no problem at all.
@synchronized(self) {
if (_playerPlaying) {
if (!_audioQueuePaused) {
AudioQueuePause(_aq);
_audioQueuePaused = YES;
}
_playerPlaying = NO;
return YES;
} else {
return NO;
}
}
}
- (BOOL)seek:(double)targetTime {
//if (_fileSize == 0 || _dataOffset == -1) {
// return NO;
//}
//UInt32 bit_rate = [self bitRate];
//Float64 average_bytes_per_packet;
//UInt32 ppt_size = sizeof(Float64);
//// FIXME: error checking
//AudioFileStreamGetProperty(_afsID, kAudioFileStreamProperty_AverageBytesPerPacket, &ppt_size, &average_bytes_per_packet);
//
//if (average_bytes_per_packet <= 0 || bit_rate == 0) {
// return NO;
//}
//
//NSLog(@"\n-> seek requested: %f", targetTime); // DEBUG
//
//UInt32 target_byte = targetTime / 8 * bit_rate;
//if (_streamingStartedFrom <= target_byte && target_byte <= _resumeStreamingFrom) {
// // FIXME
//} else {
// // FIXME
//}
// FIXME
return NO;
}
// this method is "private".
- (double)audioBytesPlayedToAudioPosition {
UInt32 bit_rate = [self bitRate];
if (bit_rate != 0) {
return _playedAudioBytes * 1.0 / bit_rate * 8;
}
return 0.0;
}
- (double)duration {
UInt32 bit_rate = [self bitRate];
if (_fileSize != 0 && _dataOffset != -1 && bit_rate != 0) {
return (_fileSize - _dataOffset) * 1.0 / bit_rate * 8;
}
return 0.0;
}
- (int)fileSize {
return _fileSize;
}
- (void)restartStreaming {
@synchronized(self) {
if (_connection != nil) {
[self pauseStreaming];
}
_restartStreamingNeverCalled = NO;
[self sendBlocked];
if (_aq) {
AudioQueuePause(_aq);
_audioQueuePaused = YES;
_playerPlaying = NO;
// for (int i = 0; i < AQBUF_N; i++) {
// AudioQueueBufferRef aqbuf = *(AudioQueueBufferRef *)[(NSData *)[_emptyQueueBuffers objectAtIndex:i] bytes];
// AudioQueueFreeBuffer(_aq, aqbuf);
// }
AudioQueueDispose(_aq, true);
for (int i = 0; i < AQBUF_N; i++) {
// NSLog(@"%d", _aqBufs[i]->mAudioDataBytesCapacity);
AudioQueueFreeBuffer(_aq, _aqBufs[i]);
}
_aq = NULL;
}
if (!_afsID) {
// FIXME: add error checking
AudioFileStreamOpen((__bridge void *)self, afs_properties_cb, afs_audio_data_cb, 0, &_afsID);
}
// L1.
[_emptyQueueBuffers removeAllObjects];
// L2.
_parsedPackets = [NSMutableArray new];
_packetsDesc = [NSMutableArray new];
_l2_curIdx = -1;
_resumeStreamingFrom = 0;
_playedAudioBytes = 0;
_streamingStartedFrom = 0;
_finishedFeedingParser = NO;
if ([_delegate respondsToSelector:@selector(onPlayerPosChanged:pos:)]) {
[_delegate onPlayerPosChanged:self pos:0.0];
}
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
[req setValue:@"" forHTTPHeaderField:@"User-Agent"];
_connection = [NSURLConnection connectionWithRequest:req delegate:self];
}
}
- (void)pauseStreaming {
@synchronized(self) {
if (_connection == nil) {
return;
}
[_connection cancel];
_connection = nil;
}
}
- (void)startStreaming {
@synchronized(self) {
// I will just assume nobody will call resumeStreaming before startStreaming or play...
if (_connection != nil || _finishedFeedingParser) {
return;
}
if (_restartStreamingNeverCalled) {
[self restartStreaming];
return;
}
if (_l2_curIdx + 1 == [_parsedPackets count]) {
[self sendBlocked];
}
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
[req setValue:@"" forHTTPHeaderField:@"User-Agent"];
// if _resumeStreamingFrom is not zero, it means seek is already called -- which means
// _fileSize should not be zero as well.
//
// but, well, it doesn't harm...
if (_fileSize != 0 && _resumeStreamingFrom != 0) {
NSString *range = [NSString stringWithFormat:@"bytes=%ld-%d", _resumeStreamingFrom, _fileSize];
[req addValue:range forHTTPHeaderField:@"Range"];
}
_connection = [NSURLConnection connectionWithRequest:req delegate:self];
}
}
- (BOOL)streamingFinished {
return _finishedFeedingParser;
}
- (BOOL)isPlayerBlocking {
return _playerBlocked;
}
- (void)sendBlocked {
if (!_playerBlocked) {
_playerBlocked = YES;
if ([_delegate respondsToSelector:@selector(onPlayerBlocked:)]) {
[_delegate onPlayerBlocked:self];
}
}
}
- (void)sendBlockingEnded {
if (_playerBlocked) {
_playerBlocked = NO;
if ([_delegate respondsToSelector:@selector(onPlayerBlockingEnded:)]) {
[_delegate onPlayerBlockingEnded:self];
}
}
}
//
// afs callbacks
//
// L2's callback
- (void)onParsedPacketsReceived:(const void *)data
audioDataSize:(UInt32)d_size
numberOfPackets:(UInt32)packet_n
packetDescriptions:(AudioStreamPacketDescription *)packet_desc {
@autoreleasepool {
@synchronized(self) {
_packetCount += packet_n;
for (int i = 0; i < packet_n; i++) {
_frameCount += packet_desc[i].mVariableFramesInPacket;
}
// NSLog(@"\n-> bit rate: %u", [self bitRate]); // DEBUG
// push data into L2
for (int i = 0; i < packet_n; i++) {
NSData *d = [NSData dataWithBytes:data+packet_desc[i].mStartOffset
length:packet_desc[i].mDataByteSize];
[_parsedPackets addObject:d];
d = [NSData dataWithBytes:packet_desc+i
length:sizeof(AudioStreamPacketDescription)];
AudioStreamPacketDescription *ds = (AudioStreamPacketDescription *)[d bytes];
ds->mStartOffset = 0;
[_packetsDesc addObject:d];
[self sendBlockingEnded];
}
}
[self feedL1];
}
}
- (void)onPropertyAcquired:(AudioFilePropertyID)ppt_id
audioFileStreamID:(AudioFileStreamID)afs_id {
@autoreleasepool {
UInt32 ppt_size;
AudioFileStreamGetPropertyInfo(afs_id, ppt_id, &ppt_size, nil);
// I will just assume the value could be completely read at once...
void *buff = malloc(ppt_size);
UInt32 buff_size = ppt_size;
// FIXME: error checking?
AudioFileStreamGetProperty(afs_id, ppt_id, &buff_size, buff);
if (ppt_id == kAudioFileStreamProperty_ReadyToProducePackets) {
_finishedParsingHeader = YES;
NSLog(@"\n-> finished parsing header."); // DEBUG
NSLog(@"\n-> audio duration: %.2lfs", [self duration]); // DEBUG
// _playerReady = YES;
// [_delegate onPlayerReady:self];
// FIXME: if streamDesc == nil, fail
// for (int i = 0; i < AQBUF_N; i++) {
// AudioQueueAllocateBuffer(_aq, AQBUF_DEFAULT_SIZE, &_aqBufs[i]);
// NSData *d = [NSData dataWithBytes:&_aqBufs[i] length:sizeof(_aqBufs[i])];
// [_emptyQueueBuffers addObject:d];
// }
} else if (ppt_id == kAudioFileStreamProperty_DataFormat) {
_streamDesc = buff;
@synchronized(self) {
if (_playerPlaying && _aq == NULL) {
// FIXME: check error.
AudioQueueNewOutput(_streamDesc, aq_new_buffer_cb, (__bridge void *)(self), NULL, NULL, 0, &_aq);
for (int i = 0; i < AQBUF_N; i++) {
AudioQueueAllocateBuffer(_aq, AQBUF_DEFAULT_SIZE, &_aqBufs[i]);
[_emptyQueueBuffers addObject:[NSData dataWithBytes:&_aqBufs[i] length:sizeof(AudioQueueBufferRef)]];
}
NSLog(@"\n-> audio queues created in properties' callback");
}
}
return; // don't free _streamDesc!
} else if (ppt_id == kAudioFileStreamProperty_BitRate) {
_bitRate = *(UInt32 *)buff;
} else if (ppt_id == kAudioFileStreamProperty_DataOffset) {
_dataOffset = *(SInt64 *)buff;
}
// kAudioFileStreamProperty_AudioDataByteCount and
// kAudioFileStreamProperty_AudioDataPacketCount
//
// seems very helpful as well, but the document didn't specify what will
// byte count be if there's no valid data available.
// farewell!
if (buff != NULL) {
free(buff);
}
}
}
- (void)onNewEmptyQueueBufferReceived:(AudioQueueRef)inAQ buffer:(AudioQueueBufferRef)inBuffer {
@autoreleasepool {
@synchronized(self) {
NSData *d = [NSData dataWithBytes:&inBuffer length:sizeof(AudioQueueBufferRef)];
[_emptyQueueBuffers addObject:d];
}
[self feedL1];
}
}
- (void)feedL1 {
@synchronized(self) {
// NSLog(@"\n-> feedL1 called!!"); // DEBUG
while (_l2_curIdx + 1 < [_parsedPackets count] && [_emptyQueueBuffers count] > 0) {
AudioQueueBufferRef aqbuf = *(AudioQueueBufferRef *)[(NSData *)[_emptyQueueBuffers objectAtIndex:0] bytes];
[_emptyQueueBuffers removeObjectAtIndex:0];
aqbuf->mAudioDataByteSize = 0;
NSData *next_packet = [_parsedPackets objectAtIndex:(_l2_curIdx + 1)];
if (aqbuf->mAudioDataBytesCapacity < [next_packet length]) {
int cur_buf_idx = -1;
for (int i = 0; i < AQBUF_N; i++) {
if (_aqBufs[i] == aqbuf) {
cur_buf_idx = i;
break;
}
}
AudioQueueFreeBuffer(_aq, _aqBufs[cur_buf_idx]);
AudioQueueAllocateBuffer(_aq, (UInt32)[next_packet length], &aqbuf);
_aqBufs[cur_buf_idx] = aqbuf;
}
// while (next_packet != nil &&
// aqbuf->mAudioDataByteSize + [next_packet length] <= aqbuf->mAudioDataBytesCapacity) {
// memcpy(aqbuf->mAudioData + aqbuf->mAudioDataByteSize,
// [next_packet bytes], [next_packet length]);
// aqbuf->mAudioDataByteSize += [next_packet length];
//
// _l2_curIdx++;
// if (_l2_curIdx + 1 < [_parsedPackets count]) {
// next_packet = [_parsedPackets objectAtIndex:(_l2_curIdx + 1)];
// } else {
// next_packet = nil;
// }
// }
memcpy(aqbuf->mAudioData, [next_packet bytes], [next_packet length]);
aqbuf->mAudioDataByteSize = (UInt32)[next_packet length];
const AudioStreamPacketDescription *desc = [[_packetsDesc objectAtIndex:(_l2_curIdx + 1)] bytes];
AudioQueueEnqueueBuffer(_aq, aqbuf, 1, desc);
_l2_curIdx++;
_playedAudioBytes += [next_packet length];
if ([_delegate respondsToSelector:@selector(onPlayerPosChanged:pos:)]) {
[_delegate onPlayerPosChanged:self pos:[self audioBytesPlayedToAudioPosition]];
}
// NSLog(@"\n-> new audio buffer filled & enqueued"); // DEBUG
if (_playerPlaying && _audioQueuePaused) {
AudioQueueStart(_aq, NULL);
_audioQueuePaused = NO;
}
}
if (_l2_curIdx + 1 == [_parsedPackets count] && [_emptyQueueBuffers count] == AQBUF_N) {
if (_playerPlaying && !_audioQueuePaused) {
AudioQueuePause(_aq);
_audioQueuePaused = YES;
if (_finishedFeedingParser) {
_playerPlaying = NO;
_l2_curIdx = -1;
_playedAudioBytes = 0;
[_delegate onPlayingFinished:self];
[self sendBlockingEnded];
} else {
[self sendBlocked];
}
}
}
}
}
//
// helper methods for seeking
//
- (UInt32)bitRate {
if (_bitRate != 0) {
return _bitRate;
} else if (_streamDesc != nil) {
// sample rate: frames / sec
Float64 sample_rate = _streamDesc->mSampleRate;
Float64 bytes_per_frame = 0;
if (sample_rate != 0.0f) {
// (bytes/packet) / (frames/packet) = bytes/frame
Float64 bytes_per_packet = [self bytesPerPacket];
Float64 frames_per_packet = [self framesPerPacket];
if (bytes_per_packet != 0 && frames_per_packet != 0) {
bytes_per_frame = bytes_per_frame / frames_per_packet;
}
}
// (bytes/frame) * (frames/sec) * 8 = bits/sec
return bytes_per_frame * sample_rate * 8;
}
return 0;
}
- (Float64)framesPerPacket {
if (_streamDesc->mFramesPerPacket) {
return _streamDesc->mFramesPerPacket;
} else if (_packetCount != 0) {
return (Float64)_frameCount / _packetCount;
}
return 0;
}
- (Float64)bytesPerPacket {
if (_streamDesc->mBytesPerPacket) {
return _streamDesc->mBytesPerPacket;
} else {
Float64 t;
UInt32 _size = sizeof(Float64);
// FIXME: error checking
AudioFileStreamGetProperty(_afsID, kAudioFileStreamProperty_AverageBytesPerPacket, &_size, &t);
return t;
}
}
//
// NSURLConnection delegate methods
//
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
@synchronized(self) {
if (connection != _connection) {
return;
}
// FIXME: on seeking forward the last parameter has to be kAudioFileStreamParseFlag_Discontinuity.
AudioFileStreamParseBytes(_afsID, (UInt32)[data length], [data bytes], 0);
_resumeStreamingFrom += [data length];
}
[_delegate onDataReceived:self data:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
BOOL send_playing_finished = NO;
@synchronized(self) {
if (connection != _connection) {
return;
}
_finishedFeedingParser = YES;
_connection = nil;
if (_playerPlaying && _audioQueuePaused) {
_playerPlaying = NO;
_l2_curIdx = -1;
_playedAudioBytes = 0;
send_playing_finished = YES;
}
}
[_delegate onStreamingFinished:self];
if (send_playing_finished) {
[_delegate onPlayingFinished:self];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
@synchronized(self) {
if (connection != _connection) {
return;
}
_connection = nil;
}
if ([_delegate respondsToSelector:@selector(onErrorOccured:error:)]) {
[_delegate onErrorOccured:self error:error];
}
}
// get response header from the server.
// used for getting the file size.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection != _connection) {
return;
}
if (_fileSize != 0) {
return;
}
NSDictionary *d = [(NSHTTPURLResponse *)response allHeaderFields];
NSString *content_length_string = [d objectForKey:@"Content-Length"];
if (content_length_string != nil) {
_fileSize = [content_length_string intValue];
}
NSLog(@"\n-> file size: %d bytes.\n", _fileSize);
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse {
return request; // just redirect.
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil; // don't do caching on response.
}
@end