-
Notifications
You must be signed in to change notification settings - Fork 282
/
mp4.coffee
2233 lines (1946 loc) · 67 KB
/
mp4.coffee
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
Bits = require './bits'
EventEmitterModule = require './event_emitter'
Sequent = require 'sequent'
fs = require 'fs'
logger = require './logger'
h264 = require './h264'
formatDate = (date) ->
date.toISOString()
# copyright sign + 'too' (we should not use literal '\xa9'
# since it expands to [0xc2, 0xa9])
TAG_CTOO = new Buffer([0xa9, 0x74, 0x6f, 0x6f]).toString 'utf8'
MIN_TIME_DIFF = 0.01 # seconds
READ_BUFFER_TIME = 3.0
QUEUE_BUFFER_TIME = 1.5
DEBUG = false
# If true, outgoing audio/video packets will be printed
DEBUG_OUTGOING_MP4_DATA = false
getCurrentTime = ->
time = process.hrtime()
return time[0] + time[1] / 1e9
class MP4File extends EventEmitterModule
constructor: (filename) ->
super()
if filename?
@open filename
@isStopped = false
clearBuffers: ->
@consumedAudioChunks = 0
@consumedVideoChunks = 0
@bufferedAudioTime = 0
@bufferedVideoTime = 0
@queuedAudioTime = 0
@queuedVideoTime = 0
@bufferedAudioSamples = []
@queuedAudioSampleIndex = 0
@bufferedVideoSamples = []
@queuedVideoSampleIndex = 0
@isAudioEOF = false
@isVideoEOF = false
@sessionId++
open: (filename) ->
@filename = filename
if DEBUG
startTime = process.hrtime()
@fileBuf = fs.readFileSync filename # up to 1GB
@bits = new Bits @fileBuf
if DEBUG
diffTime = process.hrtime startTime
logger.debug "[mp4] took #{(diffTime[0] * 1e9 + diffTime[1]) / 1000000} ms to read #{filename}"
@consumedAudioSamples = 0
@consumedVideoSamples = 0
@clearBuffers()
@currentPlayTime = 0
@playStartTime = null
# sessionId will change when buffer is cleared
@sessionId = 0
close: ->
logger.debug "[mp4:#{@filename}] close"
if not @isStopped
@stop()
@bits = null
@fileBuf = null
@boxes = null
@moovBox = null
@mdatBox = null
@audioTrakBox = null
@videoTrakBox = null
return
parse: ->
if DEBUG
startTime = process.hrtime()
@boxes = []
while @bits.has_more_data()
box = Box.parse @bits, null # null == root box
if box instanceof MovieBox
@moovBox = box
else if box instanceof MediaDataBox
@mdatBox = box
@boxes.push box
if DEBUG
diffTime = process.hrtime startTime
logger.debug "[mp4] took #{(diffTime[0] * 1e9 + diffTime[1]) / 1000000} ms to parse #{@filename}"
for child in @moovBox.children
if child instanceof TrackBox # trak
tkhdBox = child.find 'tkhd'
if tkhdBox.isAudioTrack
@audioTrakBox = child
else
@videoTrakBox = child
@numVideoSamples = @getNumVideoSamples()
@numAudioSamples = @getNumAudioSamples()
return
getTree: ->
if not @boxes?
throw new Error "parse() must be called before dump"
tree = { root: [] }
for box in @boxes
tree.root.push box.getTree()
return tree
dump: ->
if not @boxes?
throw new Error "parse() must be called before dump"
for box in @boxes
process.stdout.write box.dump 0, 2
return
hasVideo: ->
return @videoTrakBox?
hasAudio: ->
return @audioTrakBox?
getSPS: ->
avcCBox = @videoTrakBox.find 'avcC'
return avcCBox.sequenceParameterSets[0]
getPPS: ->
avcCBox = @videoTrakBox.find 'avcC'
return avcCBox.pictureParameterSets[0]
getAudioSpecificConfig: ->
esdsBox = @audioTrakBox.find 'esds'
return esdsBox.decoderConfigDescriptor.decoderSpecificInfo.specificInfo
stop: ->
@isStopped = true
isPaused: ->
return @isStopped
pause: ->
if not @isStopped
@isStopped = true
logger.debug "[mp4:#{@filename}] paused at #{@currentPlayTime} (server mp4 head time)"
else
logger.debug "[mp4:#{@filename}] already paused"
sendVideoPacketsSinceLastKeyFrame: (endSeconds, callback) ->
if not @videoTrakBox? # video trak does not exist
callback? null
return
# Get next sample number
stblBox = @videoTrakBox.child('mdia').child('minf').child('stbl')
sttsBox = stblBox.child('stts') # TimeToSampleBox
videoSample = sttsBox.getSampleAfterSeconds endSeconds
if videoSample?
videoSampleNumber = videoSample.sampleNumber
else
videoSampleNumber = @numVideoSamples + 1
samples = []
isFirstSample = true
loop
rawSample = @getSample videoSampleNumber, @videoTrakBox
isKeyFrameFound = false
if rawSample?
nalUnits = @parseH264Sample rawSample.data
for nalUnit in nalUnits
if (nalUnit[0] & 0x1f) is h264.NAL_UNIT_TYPE_IDR_PICTURE
isKeyFrameFound = true
break
if not isFirstSample
samples.unshift
pts: rawSample.pts
dts: rawSample.dts
time: rawSample.time
data: nalUnits
if isFirstSample
isFirstSample = false
if isKeyFrameFound
break
videoSampleNumber--
if videoSampleNumber <= 0
break
for sample in samples
@emit 'video_data', sample.data, sample.pts, sample.dts
callback? null
resume: ->
@play()
isAudioEOFReached: ->
return (@bufferedAudioSamples.length is 0) and
(@consumedAudioSamples is @numAudioSamples)
isVideoEOFReached: ->
return (@bufferedVideoSamples.length is 0) and
(@consumedVideoSamples is @numVideoSamples)
fillBuffer: (callback) ->
seq = new Sequent
@bufferAudio =>
# audio samples has been buffered
seq.done()
@bufferVideo =>
# video samples has been buffered
seq.done()
seq.wait 2, callback
seek: (seekSeconds=0) ->
logger.debug "[mp4:#{@filename}] seek: seconds=#{seekSeconds}"
@clearBuffers()
if @videoTrakBox?
# Seek video sample
stblBox = @videoTrakBox.child('mdia').child('minf').child('stbl')
sttsBox = stblBox.child('stts') # TimeToSampleBox
videoSample = sttsBox.getSampleAfterSeconds seekSeconds
if videoSample?
logger.debug "video sample >= #{seekSeconds} is #{JSON.stringify videoSample}"
videoSampleSeconds = videoSample.seconds
@currentPlayTime = videoSampleSeconds
videoSampleNumber = videoSample.sampleNumber
else
# No video sample left
logger.debug "video sample >= #{seekSeconds} does not exist"
@isVideoEOF = true
@currentPlayTime = @getDurationSeconds()
videoSampleNumber = @numVideoSamples + 1
videoSampleSeconds = @currentPlayTime
else
videoSampleNumber = null
videoSampleSeconds = null
if @audioTrakBox?
# Seek audio sample
stblBox = @audioTrakBox.child('mdia').child('minf').child('stbl')
sttsBox = stblBox.child('stts') # TimeToSampleBox
audioSample = sttsBox.getSampleAfterSeconds seekSeconds
if audioSample?
logger.debug "audio sample >= #{seekSeconds} is #{JSON.stringify audioSample}"
audioSampleNumber = audioSample.sampleNumber
if videoSampleSeconds? and (videoSampleSeconds <= audioSample.seconds)
minTime = videoSampleSeconds
else
minTime = audioSample.seconds
if @currentPlayTime isnt minTime
@currentPlayTime = minTime
else
# No audio sample left
logger.debug "audio sample >= #{seekSeconds} does not exist"
audioSampleNumber = @numAudioSamples + 1
@isAudioEOF = true
else
audioSampleNumber = null
if audioSampleNumber?
@consumedAudioSamples = audioSampleNumber - 1
if videoSampleNumber?
@consumedVideoSamples = videoSampleNumber - 1
logger.debug "[mp4:#{@filename}] set current play time to #{@currentPlayTime}"
return @currentPlayTime
play: ->
logger.debug "[mp4:#{@filename}] start playing from #{@currentPlayTime} (server mp4 head time)"
@fillBuffer =>
@isStopped = false
@playStartTime = getCurrentTime() - @currentPlayTime
if @isAudioEOFReached()
@isAudioEOF = true
if @isVideoEOFReached()
@isVideoEOF = true
if @checkEOF()
# EOF reached
return false
else
@queueBufferedSamples()
return true
checkAudioBuffer: ->
timeDiff = @bufferedAudioTime - @currentPlayTime
if timeDiff < READ_BUFFER_TIME
# Fill audio buffer
if @readNextAudioChunk()
# Audio EOF not reached
@queueBufferedSamples()
else
@queueBufferedSamples()
return
checkVideoBuffer: ->
timeDiff = @bufferedVideoTime - @currentPlayTime
if timeDiff < READ_BUFFER_TIME
# Fill video buffer
if @readNextVideoChunk()
# Video EOF not reached
@queueBufferedSamples()
else
@queueBufferedSamples()
return
startStreaming: ->
@queueBufferedSamples()
updateCurrentPlayTime: ->
@currentPlayTime = getCurrentTime() - @playStartTime
queueBufferedAudioSamples: ->
audioSample = @bufferedAudioSamples[@queuedAudioSampleIndex]
if not audioSample? # @bufferedAudioSamples is empty
return
timeDiff = audioSample.time - @currentPlayTime
if timeDiff <= MIN_TIME_DIFF
@bufferedAudioSamples.shift()
@queuedAudioSampleIndex--
if DEBUG_OUTGOING_MP4_DATA
logger.info "emit audio_data pts=#{audioSample.pts}"
@emit 'audio_data', audioSample.data, audioSample.pts
@updateCurrentPlayTime()
if (@queuedAudioSampleIndex is 0) and (@consumedAudioSamples is @numAudioSamples)
# No audio sample left
@isAudioEOF = true
@checkEOF()
else
if not @isStopped
sessionId = @sessionId
setTimeout =>
if (not @isStopped) and (@sessionId is sessionId)
@bufferedAudioSamples.shift()
@queuedAudioSampleIndex--
if DEBUG_OUTGOING_MP4_DATA
logger.info "emit timed audio_data pts=#{audioSample.pts}"
@emit 'audio_data', audioSample.data, audioSample.pts
@updateCurrentPlayTime()
if (@queuedAudioSampleIndex is 0) and (@consumedAudioSamples is @numAudioSamples)
# No audio sample left
@isAudioEOF = true
@checkEOF()
else
@checkAudioBuffer()
, timeDiff * 1000
@queuedAudioSampleIndex++
@queuedAudioTime = audioSample.time
if @queuedAudioTime - @currentPlayTime < QUEUE_BUFFER_TIME
@queueBufferedSamples()
queueBufferedVideoSamples: ->
if @isStopped
return
videoSample = @bufferedVideoSamples[@queuedVideoSampleIndex]
if not videoSample? # @bufferedVideoSamples is empty
return
timeDiff = videoSample.time - @currentPlayTime
if timeDiff <= MIN_TIME_DIFF
@bufferedVideoSamples.shift()
@queuedVideoSampleIndex--
if DEBUG_OUTGOING_MP4_DATA
totalBytes = 0
for nalUnit in videoSample.data
totalBytes += nalUnit.length
logger.info "emit video_data pts=#{videoSample.pts} dts=#{videoSample.dts} bytes=#{totalBytes}"
@emit 'video_data', videoSample.data, videoSample.pts, videoSample.dts
@updateCurrentPlayTime()
if (@queuedVideoSampleIndex is 0) and (@consumedVideoSamples is @numVideoSamples)
# No video sample left
@isVideoEOF = true
@checkEOF()
else
sessionId = @sessionId
setTimeout =>
if (not @isStopped) and (@sessionId is sessionId)
@bufferedVideoSamples.shift()
@queuedVideoSampleIndex--
if DEBUG_OUTGOING_MP4_DATA
totalBytes = 0
for nalUnit in videoSample.data
totalBytes += nalUnit.length
logger.info "emit timed video_data pts=#{videoSample.pts} dts=#{videoSample.dts} bytes=#{totalBytes}"
@emit 'video_data', videoSample.data, videoSample.pts, videoSample.dts
@updateCurrentPlayTime()
if (@queuedVideoSampleIndex is 0) and (@consumedVideoSamples is @numVideoSamples)
# No video sample left
@isVideoEOF = true
@checkEOF()
else
@checkVideoBuffer()
, timeDiff * 1000
@queuedVideoSampleIndex++
@queuedVideoTime = videoSample.time
if @queuedVideoTime - @currentPlayTime < QUEUE_BUFFER_TIME
@queueBufferedSamples()
queueBufferedSamples: ->
if @isStopped
return
# Determine which of audio or video should be sent first
firstAudioTime = @bufferedAudioSamples[@queuedAudioSampleIndex]?.time
firstVideoTime = @bufferedVideoSamples[@queuedVideoSampleIndex]?.time
if firstAudioTime? and firstVideoTime?
if firstVideoTime <= firstAudioTime
@queueBufferedVideoSamples()
@queueBufferedAudioSamples()
else
@queueBufferedAudioSamples()
@queueBufferedVideoSamples()
else
@queueBufferedAudioSamples()
@queueBufferedVideoSamples()
checkEOF: ->
if @isAudioEOF and @isVideoEOF
@stop()
@emit 'eof'
return true
return false
bufferAudio: (callback) ->
# TODO: Use async
while @bufferedAudioTime < @currentPlayTime + READ_BUFFER_TIME
if not @readNextAudioChunk()
# No audio sample left
break
callback?()
bufferVideo: (callback) ->
# TODO: Use async
while @bufferedVideoTime < @currentPlayTime + READ_BUFFER_TIME
if not @readNextVideoChunk()
# No video sample left
break
callback?()
getNumVideoSamples: ->
if @videoTrakBox?
sttsBox = @videoTrakBox.find 'stts'
return sttsBox.getTotalSamples()
else
return 0
getNumAudioSamples: ->
if @audioTrakBox?
sttsBox = @audioTrakBox.find 'stts'
return sttsBox.getTotalSamples()
else
return 0
# Returns the timestamp of the last sample in the file
getLastTimestamp: ->
if @videoTrakBox?
numVideoSamples = @getNumVideoSamples()
sttsBox = @videoTrakBox.find 'stts'
videoLastTimestamp = sttsBox.getDecodingTime(numVideoSamples).seconds
else
videoLastTimestamp = 0
if @audioTrakBox?
numAudioSamples = @getNumAudioSamples()
sttsBox = @audioTrakBox.find 'stts'
audioLastTimestamp = sttsBox.getDecodingTime(numAudioSamples).seconds
else
audioLastTimestamp = 0
if audioLastTimestamp > videoLastTimestamp
return audioLastTimestamp
else
return videoLastTimestamp
getDurationSeconds: ->
mvhdBox = @moovBox.child('mvhd')
return mvhdBox.durationSeconds
parseH264Sample: (buf) ->
# The format is defined in ISO 14496-15 5.2.3
# <length><NAL unit> <length><NAL unit> ...
avcCBox = @videoTrakBox.find 'avcC'
lengthSize = avcCBox.lengthSizeMinusOne + 1
bits = new Bits buf
nalUnits = []
while bits.has_more_data()
length = bits.read_bits lengthSize * 8
nalUnits.push bits.read_bytes(length)
if bits.get_remaining_bits() isnt 0
throw new Error "number of remaining bits is not zero: #{bits.get_remaining_bits()}"
return nalUnits
getSample: (sampleNumber, trakBox) ->
stblBox = trakBox.child('mdia').child('minf').child('stbl')
sttsBox = stblBox.child 'stts'
stscBox = stblBox.child 'stsc'
chunkNumber = stscBox.findChunk sampleNumber
# Get chunk offset in the file
stcoBox = stblBox.child 'stco'
chunkOffset = stcoBox.getChunkOffset chunkNumber
firstSampleNumberInChunk = stscBox.getFirstSampleNumberInChunk chunkNumber
# Get an array of sample sizes in this chunk
stszBox = stblBox.child 'stsz'
sampleSizes = stszBox.getSampleSizes firstSampleNumberInChunk,
sampleNumber - firstSampleNumberInChunk + 1
cttsBox = stblBox.child 'ctts'
samples = []
sampleOffset = 0
mdhdBox = trakBox.child('mdia').child('mdhd')
for sampleSize, i in sampleSizes
if firstSampleNumberInChunk + i is sampleNumber
compositionTimeOffset = 0
if cttsBox?
compositionTimeOffset = cttsBox.getCompositionTimeOffset sampleNumber
sampleTime = sttsBox.getDecodingTime sampleNumber
compositionTime = sampleTime.time + compositionTimeOffset
if mdhdBox.timescale isnt 90000
pts = Math.floor(compositionTime * 90000 / mdhdBox.timescale)
dts = Math.floor(sampleTime.time * 90000 / mdhdBox.timescale)
else
pts = compositionTime
dts = sampleTime.time
return {
pts: pts
dts: dts
time: sampleTime.seconds
data: @fileBuf[chunkOffset+sampleOffset...chunkOffset+sampleOffset+sampleSize]
}
sampleOffset += sampleSize
return null
readChunk: (chunkNumber, fromSampleNumber, trakBox) ->
stblBox = trakBox.child('mdia').child('minf').child('stbl')
sttsBox = stblBox.child 'stts'
stscBox = stblBox.child 'stsc'
numSamplesInChunk = stscBox.getNumSamplesInChunk chunkNumber
# Get chunk offset in the file
stcoBox = stblBox.child 'stco'
chunkOffset = stcoBox.getChunkOffset chunkNumber
firstSampleNumberInChunk = stscBox.getFirstSampleNumberInChunk chunkNumber
# Get an array of sample sizes in this chunk
stszBox = stblBox.child 'stsz'
sampleSizes = stszBox.getSampleSizes firstSampleNumberInChunk, numSamplesInChunk
cttsBox = stblBox.child 'ctts'
samples = []
sampleOffset = 0
mdhdBox = trakBox.child('mdia').child('mdhd')
for sampleSize, i in sampleSizes
if firstSampleNumberInChunk + i >= fromSampleNumber
compositionTimeOffset = 0
if cttsBox?
compositionTimeOffset = cttsBox.getCompositionTimeOffset firstSampleNumberInChunk + i
sampleTime = sttsBox.getDecodingTime firstSampleNumberInChunk + i
compositionTime = sampleTime.time + compositionTimeOffset
if mdhdBox.timescale isnt 90000
pts = Math.floor(compositionTime * 90000 / mdhdBox.timescale)
dts = Math.floor(sampleTime.time * 90000 / mdhdBox.timescale)
else
pts = compositionTime
dts = sampleTime.time
samples.push {
pts: pts
dts: dts
time: sampleTime.seconds
data: @fileBuf[chunkOffset+sampleOffset...chunkOffset+sampleOffset+sampleSize]
}
sampleOffset += sampleSize
return samples
readNextVideoChunk: ->
if @consumedVideoSamples >= @numVideoSamples
return false
if @consumedVideoChunks is 0 and @consumedVideoSamples isnt 0 # seeked
stscBox = @videoTrakBox.find 'stsc'
chunkNumber = stscBox.findChunk @consumedVideoSamples + 1
samples = @readChunk chunkNumber, @consumedVideoSamples + 1, @videoTrakBox
@consumedVideoChunks = chunkNumber
else
samples = @readChunk @consumedVideoChunks + 1, @consumedVideoSamples + 1, @videoTrakBox
@consumedVideoChunks++
for sample in samples
nalUnits = @parseH264Sample sample.data
sample.data = nalUnits
numSamples = samples.length
@consumedVideoSamples += numSamples
@bufferedVideoTime = samples[numSamples - 1].time
@bufferedVideoSamples = @bufferedVideoSamples.concat samples
return true
parseAACSample: (buf) ->
# nop
readNextAudioChunk: ->
if @consumedAudioSamples >= @numAudioSamples
return false
if @consumedAudioChunks is 0 and @consumedAudioSamples isnt 0 # seeked
stscBox = @audioTrakBox.find 'stsc'
chunkNumber = stscBox.findChunk @consumedAudioSamples + 1
samples = @readChunk chunkNumber, @consumedAudioSamples + 1, @audioTrakBox
@consumedAudioChunks = chunkNumber
else
samples = @readChunk @consumedAudioChunks + 1, @consumedAudioSamples + 1, @audioTrakBox
@consumedAudioChunks++
# for sample in samples
# @parseAACSample sample.data
@consumedAudioSamples += samples.length
@bufferedAudioTime = samples[samples.length-1].time
@bufferedAudioSamples = @bufferedAudioSamples.concat samples
return true
class Box
# time: seconds since midnight, Jan. 1, 1904 UTC
@mp4TimeToDate: (time) ->
return new Date(new Date('1904-01-01 00:00:00+0000').getTime() + time * 1000)
getTree: ->
obj =
type: @typeStr
if @children?
obj.children = []
for child in @children
obj.children.push child.getTree()
return obj
dump: (depth=0, detailLevel=0) ->
str = ''
for i in [0...depth]
str += ' '
str += "#{@typeStr}"
if detailLevel > 0
detailString = @getDetails detailLevel
if detailString?
str += " (#{detailString})"
str += "\n"
if @children?
for child in @children
str += child.dump depth+1, detailLevel
return str
getDetails: (detailLevel) ->
return null
constructor: (info) ->
for name, value of info
@[name] = value
if @data?
@read @data
readFullBoxHeader: (bits) ->
@version = bits.read_byte()
@flags = bits.read_bits 24
return
findParent: (typeStr) ->
if @parent?
if @parent.typeStr is typeStr
return @parent
else
return @parent.findParent typeStr
else
return null
child: (typeStr) ->
if @typeStr is typeStr
return this
else
if @children?
for child in @children
if child.typeStr is typeStr
return child
return null
find: (typeStr) ->
if @typeStr is typeStr
return this
else
if @children?
for child in @children
box = child.find typeStr
if box?
return box
return null
read: (buf) ->
@readHeader: (bits, destObj) ->
destObj.size = bits.read_uint32()
destObj.type = bits.read_bytes 4
destObj.typeStr = destObj.type.toString 'utf8'
headerLen = 8
if destObj.size is 1
destObj.size = bits.read_bits 64 # TODO: might lose some precision
headerLen += 8
if destObj.typeStr is 'uuid'
destObj.usertype = bits.read_bytes 16
headerLen += 16
if destObj.size > 0
destObj.data = bits.read_bytes(destObj.size - headerLen)
else
destObj.data = bits.remaining_buffer()
destObj.size = headerLen + destObj.data.length
return
@readLanguageCode: (bits) ->
return Box.readASCII(bits) + Box.readASCII(bits) + Box.readASCII(bits)
@readASCII: (bits) ->
diff = bits.read_bits 5
return String.fromCharCode 0x60 + diff
@parse: (bits, parent=null, cls) ->
info = {}
info.parent = parent
@readHeader bits, info
switch info.typeStr
when 'ftyp'
return new FileTypeBox info
when 'moov'
return new MovieBox info
when 'mvhd'
return new MovieHeaderBox info
when 'mdat'
return new MediaDataBox info
when 'trak'
return new TrackBox info
when 'tkhd'
return new TrackHeaderBox info
when 'edts'
return new EditBox info
when 'elst'
return new EditListBox info
when 'mdia'
return new MediaBox info
when 'iods'
return new ObjectDescriptorBox info
when 'mdhd'
return new MediaHeaderBox info
when 'hdlr'
return new HandlerBox info
when 'minf'
return new MediaInformationBox info
when 'vmhd'
return new VideoMediaHeaderBox info
when 'dinf'
return new DataInformationBox info
when 'dref'
return new DataReferenceBox info
when 'url '
return new DataEntryUrlBox info
when 'urn '
return new DataEntryUrnBox info
when 'stbl'
return new SampleTableBox info
when 'stsd'
return new SampleDescriptionBox info
when 'stts'
return new TimeToSampleBox info
when 'stss'
return new SyncSampleBox info
when 'stsc'
return new SampleToChunkBox info
when 'stsz'
return new SampleSizeBox info
when 'stco'
return new ChunkOffsetBox info
when 'smhd'
return new SoundMediaHeaderBox info
when 'meta'
return new MetaBox info
when 'pitm'
return new PrimaryItemBox info
when 'iloc'
return new ItemLocationBox info
when 'ipro'
return new ItemProtectionBox info
when 'infe'
return new ItemInfoEntry info
when 'iinf'
return new ItemInfoBox info
when 'ilst'
return new MetadataItemListBox info
when 'gsst'
return new GoogleGSSTBox info
when 'gstd'
return new GoogleGSTDBox info
when 'gssd'
return new GoogleGSSDBox info
when 'gspu'
return new GoogleGSPUBox info
when 'gspm'
return new GoogleGSPMBox info
when 'gshh'
return new GoogleGSHHBox info
when 'udta'
return new UserDataBox info
when 'avc1'
return new AVCSampleEntry info
when 'avcC'
return new AVCConfigurationBox info
when 'btrt'
return new MPEG4BitRateBox info
when 'm4ds'
return new MPEG4ExtensionDescriptorsBox info
when 'mp4a'
return new MP4AudioSampleEntry info
when 'esds'
return new ESDBox info
when 'free'
return new FreeSpaceBox info
when 'ctts'
return new CompositionOffsetBox info
when TAG_CTOO
return new CTOOBox info
else
if cls?
return new cls info
else
logger.warn "[mp4] warning: skipping unknown (not implemented) box type: #{info.typeStr} (0x#{info.type.toString('hex')})"
return new Box info
class Container extends Box
read: (buf) ->
bits = new Bits buf
@children = []
while bits.has_more_data()
box = Box.parse bits, this
@children.push box
return
# getDetails: (detailLevel) ->
# "Container"
# moov
class MovieBox extends Container
# stbl
class SampleTableBox extends Container
# dinf
class DataInformationBox extends Container
# udta
class UserDataBox extends Container
# minf
class MediaInformationBox extends Container
# mdia
class MediaBox extends Container
# edts
class EditBox extends Container
# trak
class TrackBox extends Container
# ftyp
class FileTypeBox extends Box
read: (buf) ->
bits = new Bits buf
@majorBrand = bits.read_uint32()
@majorBrandStr = Bits.uintToString @majorBrand, 4
@minorVersion = bits.read_uint32()
@compatibleBrands = []
while bits.has_more_data()
brand = bits.read_bytes 4
brandStr = brand.toString 'utf8'
@compatibleBrands.push
brand: brand
brandStr: brandStr
return
getDetails: (detailLevel) ->
"brand=#{@majorBrandStr} version=#{@minorVersion}"
getTree: ->
obj = new Box
obj.brand = @majorBrandStr
obj.version = @minorVersion
return obj
# mvhd
class MovieHeaderBox extends Box
read: (buf) ->
bits = new Bits buf
@readFullBoxHeader bits
if @version is 1
@creationTime = bits.read_bits 64 # TODO: loses precision
@creationDate = Box.mp4TimeToDate @creationTime
@modificationTime = bits.read_bits 64 # TODO: loses precision
@modificationDate = Box.mp4TimeToDate @modificationTime
@timescale = bits.read_uint32()
@duration = bits.read_bits 64 # TODO: loses precision
@durationSeconds = @duration / @timescale
else # @version is 0
@creationTime = bits.read_bits 32 # TODO: loses precision
@creationDate = Box.mp4TimeToDate @creationTime
@modificationTime = bits.read_bits 32 # TODO: loses precision
@modificationDate = Box.mp4TimeToDate @modificationTime
@timescale = bits.read_uint32()
@duration = bits.read_bits 32 # TODO: loses precision
@durationSeconds = @duration / @timescale
@rate = bits.read_int 32
if @rate isnt 0x00010000 # 1.0
logger.warn "[mp4] warning: Irregular rate found in mvhd box: #{@rate}"
@volume = bits.read_int 16
if @volume isnt 0x0100 # full volume
logger.warn "[mp4] warning: Irregular volume found in mvhd box: #{@volume}"
reserved = bits.read_bits 16
if reserved isnt 0
throw new Error "reserved bits are not all zero: #{reserved}"
reservedInt1 = bits.read_int 32
if reservedInt1 isnt 0
throw new Error "reserved int(32) (1) is not zero: #{reservedInt1}"
reservedInt2 = bits.read_int 32
if reservedInt2 isnt 0
throw new Error "reserved int(32) (2) is not zero: #{reservedInt2}"
bits.skip_bytes 4 * 9 # Unity matrix
bits.skip_bytes 4 * 6 # pre_defined
@nextTrackID = bits.read_uint32()
if bits.has_more_data()
throw new Error "mvhd box has more data"
getDetails: (detailLevel) ->
"created=#{formatDate @creationDate} modified=#{formatDate @modificationDate} timescale=#{@timescale} durationSeconds=#{@durationSeconds}"
getTree: ->
obj = new Box
obj.creationDate = @creationDate
obj.modificationDate = @modificationDate
obj.timescale = @timescale
obj.duration = @duration
obj.durationSeconds = @durationSeconds
return obj
# Object Descriptor Box: contains an Object Descriptor or an Initial Object Descriptor
# (iods)
# Defined in ISO 14496-14
class ObjectDescriptorBox extends Box
read: (buf) ->
bits = new Bits buf
@readFullBoxHeader bits
return
# Track header box: specifies the characteristics of a single track (tkhd)
class TrackHeaderBox extends Box
read: (buf) ->
bits = new Bits buf
@readFullBoxHeader bits
if @version is 1
@creationTime = bits.read_bits 64 # TODO: loses precision
@creationDate = Box.mp4TimeToDate @creationTime
@modificationTime = bits.read_bits 64 # TODO: loses precision
@modificationDate = Box.mp4TimeToDate @modificationTime
@trackID = bits.read_uint32()
reserved = bits.read_uint32()
if reserved isnt 0
throw new Error "tkhd: reserved bits are not zero: #{reserved}"
@duration = bits.read_bits 64 # TODO: loses precision