-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1375 lines (1277 loc) · 43.6 KB
/
index.js
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
/* eslint-disable camelcase,curly,no-fallthrough */
export const profileNames = {
66: 'BASELINE',
77: 'MAIN',
88: 'EXTENDED',
100: 'FREXT_HP',
110: 'FREXT_Hi10P',
122: 'FREXT_Hi422',
244: 'FREXT_Hi444',
44: 'FREXT_CAVLC444'
}
export const chromaFormatValues = {
0: 'YUV400',
1: 'YUV420',
2: 'YUV422',
3: 'YUV444'
}
export class Slice {
constructor (slice, avcc, options) {
/* we won't parse out much of this, so use subarray */
const bitstream = options?.all
? new Bitstream(slice)
: new Bitstream(slice.subarray(0, 10))
this.bitstream = bitstream
this.nalu = slice
const forbidden_zero_bit = bitstream.u_1()
if (forbidden_zero_bit) throw new Error('NALU error: invalid NALU header')
this.nal_ref_id = bitstream.u_2()
this.nal_unit_type = bitstream.u(5)
if (this.nal_unit_type !== 1 && this.nal_unit_type !== 5)
throw new Error('Slice error: not slice_layer_without_partitioning')
this.first_mb_in_slice = bitstream.ue_v()
this.slice_type = bitstream.ue_v()
this.ppsIdPtr = bitstream.ptr
this.pic_parameter_set_id = bitstream.ue_v()
this.ppsIdLen = bitstream.ptr - this.ppsIdPtr
if (avcc && avcc.ppsDecoded[this.pic_parameter_set_id]) {
const pps = avcc.ppsDecoded[this.pic_parameter_set_id]
if (pps.separate_colour_plane_flag) {
this.colour_plane_id = bitstream.u_2()
}
const seq_parameter_set_id = pps.seq_parameter_set_id
if (avcc && avcc.spsDecoded[seq_parameter_set_id]) {
const sps = avcc.spsDecoded[seq_parameter_set_id]
this.frame_num = bitstream.u(sps.log2_max_frame_num_minus4 + 4)
}
}
}
/**
* Set the pic_parameter_set_id in a slice to a desired number.
* This works around a bizarro bug in Chrome(ium)
* @returns {Uint8Array}
*/
setPPSId (ppsId = 0) {
if (this.pic_parameter_set_id === ppsId) return this.nalu
const sourceLength = this.bitstream.buffer.byteLength << 3
const target = new Bitstream(sourceLength)
target.copyBits(this.bitstream, 0, this.ppsIdPtr)
target.put_ue_v(ppsId)
target.copyBits(this.bitstream, this.ppsIdPtr + this.ppsIdLen, sourceLength - (this.ppsIdPtr + this.ppsIdLen))
return target.stream
}
}
export class SPS {
constructor (SPS) {
const bitstream = new Bitstream(SPS)
this.bitstream = bitstream
this.buffer = bitstream.buffer
const forbidden_zero_bit = bitstream.u_1()
if (forbidden_zero_bit) throw new Error('NALU error: invalid NALU header')
this.nal_ref_id = bitstream.u_2()
this.nal_unit_type = bitstream.u(5)
if (this.nal_unit_type !== 7) throw new Error('SPS error: not SPS')
this.profile_idc = bitstream.u_8()
if (profileNames[this.profile_idc]) {
this.profileName = profileNames[this.profile_idc]
} else {
throw new Error('SPS error: invalid profile_idc')
}
this.constraint_set0_flag = bitstream.u_1()
this.constraint_set1_flag = bitstream.u_1()
this.constraint_set2_flag = bitstream.u_1()
this.constraint_set3_flag = bitstream.u_1()
this.constraint_set4_flag = bitstream.u_1()
this.constraint_set5_flag = bitstream.u_1()
const reserved_zero_2bits = bitstream.u_2()
if (reserved_zero_2bits !== 0)
throw new Error('SPS error: reserved_zero_2bits must be zero')
this.level_idc = bitstream.u_8()
this.seq_parameter_set_id = bitstream.ue_v()
if (this.seq_parameter_set_id > 31)
throw new Error('SPS error: seq_parameter_set_id must be 31 or less')
this.has_no_chroma_format_idc =
(this.profile_idc === 66 || this.profile_idc === 77 || this.profile_idc === 88)
if (!this.has_no_chroma_format_idc) {
this.chroma_format_idc = bitstream.ue_v()
if (this.bit_depth_luma_minus8 > 3)
throw new Error('SPS error: chroma_format_idc must be 3 or less')
if (this.chroma_format_idc === 3) { /* 3 = YUV444 */
this.separate_colour_plane_flag = bitstream.u_1()
this.chromaArrayType = this.separate_colour_plane_flag ? 0 : this.chroma_format_idc
}
this.bit_depth_luma_minus8 = bitstream.ue_v()
if (this.bit_depth_luma_minus8 > 6)
throw new Error('SPS error: bit_depth_luma_minus8 must be 6 or less')
this.bitDepthLuma = this.bit_depth_luma_minus8 + 8
this.bit_depth_chroma_minus8 = bitstream.ue_v()
if (this.bit_depth_chroma_minus8 > 6)
throw new Error('SPS error: bit_depth_chroma_minus8 must be 6 or less')
this.lossless_qpprime_flag = bitstream.u_1()
this.bitDepthChroma = this.bit_depth_chroma_minus8 + 8
this.seq_scaling_matrix_present_flag = bitstream.u_1()
if (this.seq_scaling_matrix_present_flag) {
const n_ScalingList = (this.chroma_format_idc !== 3) ? 8 : 12
this.seq_scaling_list_present_flag = []
this.seq_scaling_list = []
for (let i = 0; i < n_ScalingList; i++) {
const seqScalingListPresentFlag = bitstream.u_1()
this.seq_scaling_list_present_flag.push(seqScalingListPresentFlag)
if (seqScalingListPresentFlag) {
const sizeOfScalingList = i < 6 ? 16 : 64
let nextScale = 8
let lastScale = 8
const delta_scale = []
for (let j = 0; j < sizeOfScalingList; j++) {
if (nextScale !== 0) {
const deltaScale = bitstream.se_v()
delta_scale.push(deltaScale)
nextScale = (lastScale + delta_scale + 256) % 256
}
lastScale = (nextScale === 0) ? lastScale : nextScale
this.seq_scaling_list.push(delta_scale)
}
}
}
}
}
this.log2_max_frame_num_minus4 = bitstream.ue_v()
if (this.log2_max_frame_num_minus4 > 12)
throw new Error('SPS error: log2_max_frame_num_minus4 must be 12 or less')
this.maxFrameNum = 1 << (this.log2_max_frame_num_minus4 + 4)
this.pic_order_cnt_type = bitstream.ue_v()
if (this.pic_order_cnt_type > 2)
throw new Error('SPS error: pic_order_cnt_type must be 2 or less')
let expectedDeltaPerPicOrderCntCycle = 0
switch (this.pic_order_cnt_type) {
case 0:
this.log2_max_pic_order_cnt_lsb_minus4 = bitstream.ue_v()
if (this.log2_max_pic_order_cnt_lsb_minus4 > 12)
throw new Error('SPS error: log2_max_pic_order_cnt_lsb_minus4 must be 12 or less')
this.maxPicOrderCntLsb = 1 << (this.log2_max_pic_order_cnt_lsb_minus4 + 4)
break
case 1:
this.delta_pic_order_always_zero_flag = bitstream.u_1()
this.offset_for_non_ref_pic = bitstream.se_v()
this.offset_for_top_to_bottom_field = bitstream.se_v()
this.num_ref_frames_in_pic_order_cnt_cycle = bitstream.ue_v()
this.offset_for_ref_frame = []
for (let i = 0; i < this.num_ref_frames_in_pic_order_cnt_cycle; i++) {
const offsetForRefFrame = bitstream.se_v()
this.offset_for_ref_frame.push(offsetForRefFrame)
// eslint-disable-next-line no-unused-vars
expectedDeltaPerPicOrderCntCycle += offsetForRefFrame
}
break
case 2:
/* there is nothing for case 2 */
break
}
this.max_num_ref_frames = bitstream.ue_v()
this.gaps_in_frame_num_value_allowed_flag = bitstream.u_1()
this.pic_width_in_mbs_minus_1 = bitstream.ue_v()
this.picWidth = (this.pic_width_in_mbs_minus_1 + 1) << 4
this.pic_height_in_map_units_minus_1 = bitstream.ue_v()
this.frame_mbs_only_flag = bitstream.u_1()
this.interlaced = !this.frame_mbs_only_flag
if (this.frame_mbs_only_flag === 0) { /* 1 if frames rather than fields (no interlacing) */
this.mb_adaptive_frame_field_flag = bitstream.u_1()
}
this.picHeight = ((2 - this.frame_mbs_only_flag) * (this.pic_height_in_map_units_minus_1 + 1)) << 4
this.direct_8x8_inference_flag = bitstream.u_1()
this.frame_cropping_flag = bitstream.u_1()
if (this.frame_cropping_flag) {
this.frame_cropping_rect_left_offset = bitstream.ue_v()
this.frame_cropping_rect_right_offset = bitstream.ue_v()
this.frame_cropping_rect_top_offset = bitstream.ue_v()
this.frame_cropping_rect_bottom_offset = bitstream.ue_v()
this.cropRect = {
x: this.frame_cropping_rect_left_offset,
y: this.frame_cropping_rect_top_offset,
width: this.picWidth - (this.frame_cropping_rect_left_offset + this.frame_cropping_rect_right_offset),
height: this.picHeight - (this.frame_cropping_rect_top_offset + this.frame_cropping_rect_bottom_offset)
}
} else {
this.cropRect = {
x: 0,
y: 0,
width: this.picWidth,
height: this.picHeight
}
}
this.vui_parameters_present_flag = bitstream.u_1()
if (this.vui_parameters_present_flag) {
this.aspect_ratio_info_present_flag = bitstream.u_1()
if (this.aspect_ratio_info_present_flag) {
this.aspect_ratio_idc = bitstream.u_8()
if (this.aspect_ratio_idc) {
this.sar_width = bitstream.u(16)
this.sar_height = bitstream.u(16)
}
}
this.overscan_info_present_flag = bitstream.u_1()
if (this.overscan_info_present_flag)
this.overscan_appropriate_flag = bitstream.u_1()
this.video_signal_type_present_flag = bitstream.u_1()
if (this.video_signal_type_present_flag) {
this.video_format = bitstream.u(3)
this.video_full_range_flag = bitstream.u_1()
this.color_description_present_flag = bitstream.u_1()
if (this.color_description_present_flag) {
this.color_primaries = bitstream.u_8()
this.transfer_characteristics = bitstream.u_8()
this.matrix_coefficients = bitstream.u_8()
}
}
this.chroma_loc_info_present_flag = bitstream.u_1()
if (this.chroma_loc_info_present_flag) {
this.chroma_sample_loc_type_top_field = bitstream.ue_v()
this.chroma_sample_loc_type_bottom_field = bitstream.ue_v()
}
this.timing_info_present_flag = bitstream.u_1()
if (this.timing_info_present_flag) {
this.num_units_in_tick = bitstream.u(32)
this.time_scale = bitstream.u(32)
this.fixed_frame_rate_flag = bitstream.u_1()
if (this.num_units_in_tick > 0) {
this.framesPerSecond = this.time_scale / this.num_units_in_tick
}
}
this.nal_hrd_parameters_present_flag = bitstream.u_1()
}
this.success = true
}
get stream () {
return this.bitstream.stream
}
get profile_compatibility () {
let v = this.constraint_set0_flag << 7
v |= this.constraint_set1_flag << 6
v |= this.constraint_set2_flag << 5
v |= this.constraint_set3_flag << 4
v |= this.constraint_set4_flag << 3
v |= this.constraint_set5_flag << 1
return v
}
/**
* getter for the MIME type encoded in this avcC
* @returns {string}
*/
get MIME () {
const f = []
f.push('avc1.')
f.push(AvcC.byte2hex(this.profile_idc).toUpperCase())
f.push(AvcC.byte2hex(this.profile_compatibility).toUpperCase())
f.push(AvcC.byte2hex(this.level_idc).toUpperCase())
return f.join('')
}
}
export class PPS {
constructor (NALU) {
const bitstream = new Bitstream(NALU)
const forbidden_zero_bit = bitstream.u_1()
if (forbidden_zero_bit) throw new Error('NALU error: invalid NALU header')
this.nal_ref_id = bitstream.u_2()
this.nal_unit_type = bitstream.u(5)
if (this.nal_unit_type !== 8) throw new Error('PPS error: not PPS')
this.pic_parameter_set_id = bitstream.ue_v()
this.seq_parameter_set_id = bitstream.ue_v()
this.entropy_coding_mode_flag = bitstream.u_1()
this.entropyCodingMode = this.entropy_coding_mode_flag ? 'CABAC' : 'CAVLC'
this.bottom_field_pic_order_in_frame_present_flag = bitstream.u_1()
this.num_slice_groups_minus1 = bitstream.ue_v()
this.numSliceGroups = this.num_slice_groups_minus1 + 1
if (this.num_slice_groups_minus1 > 0) {
this.slice_group_map_type = bitstream.ue_v()
switch (this.slice_group_map_type) {
case 0:
this.run_length_minus1 = []
for (let i = 0; i <= this.num_slice_groups_minus1; i++) {
this.run_length_minus1.push(bitstream.ue_v())
}
break
case 1: /* there is no case 1 */
break
case 2:
this.top_left = []
this.bottom_right = []
for (let i = 0; i <= this.num_slice_groups_minus1; i++) {
const topLeft = bitstream.ue_v()
const bottomRight = bitstream.ue_v()
if (topLeft > bottomRight)
throw new Error('PPS error: bottom_right less than top_left when slice_group_map is 2')
this.top_left.push(topLeft)
this.bottom_right.push(bottomRight)
}
break
case 3:
case 4:
case 5:
if (this.num_slice_groups_minus1 !== 1)
throw new Error('PPS error: num_slice_groups_minus1 must be 1 when slice_group_map is 3,4,5')
this.slice_group_change_direction_flag = bitstream.u_1()
this.slice_group_change_rate_minus1 = bitstream.ue_v()
break
case 6:
if (this.num_slice_groups_minus1 + 1 > 4) {
this.numberBitsPerSliceGroupId = 3
} else if (this.num_slice_groups_minus1 + 1 > 2) {
this.numberBitsPerSliceGroupId = 2
} else {
this.numberBitsPerSliceGroupId = 1
}
this.pic_size_in_map_units_minus1 = bitstream.ue_v()
this.slice_group_id = []
for (let i = 0; i <= this.pic_size_in_map_units_minus1; i++) {
const sliceGroupId = bitstream.u(this.numberBitsPerSliceGroupId)
if (sliceGroupId > this.num_slice_groups_minus1)
throw new Error('PPS error: slice_group_id must not be greater than num_slice_groups_minus1 when slice_group_map is 6')
this.slice_group_id.push(sliceGroupId)
}
break
}
}
this.num_ref_idx_l0_active_minus1 = bitstream.ue_v()
if (this.num_ref_idx_l0_active_minus1 > 31)
throw new Error('PPS error: num_ref_idx_l0_active_minus1 may not be greater than 31')
this.num_ref_idx_l1_active_minus1 = bitstream.ue_v()
if (this.num_ref_idx_l1_active_minus1 > 31)
throw new Error('PPS error: num_ref_idx_l1_active_minus1 may not be greater than 31')
this.weighted_pred_flag = bitstream.u_1()
this.weighted_bipred_idc = bitstream.u_2()
this.pic_init_qp_minus26 = bitstream.se_v()
if (this.pic_init_qp_minus26 > 25)
throw new Error('PPS error: pic_init_qp_minus26 may not be greater than 25')
this.pic_init_qs_minus26 = bitstream.se_v()
if (this.pic_init_qs_minus26 > 25)
throw new Error('PPS error: pic_init_qs_minus26 may not be greater than 25')
this.deblocking_filter_control_present_flag = bitstream.u_1()
this.constrained_intra_pred_flag = bitstream.u_1()
this.redundant_pic_cnt_present_flag = bitstream.u_1()
this.success = true
}
}
// noinspection DuplicatedCode
/**
* Tools for handling general bitstream issues.
*/
export class RawBitstream {
/**
* Construct a bitstream
* @param stream Buffer containing the stream, or length in bits
*/
constructor (stream) {
this.ptr = 0
if (typeof stream === 'number') {
this.buffer = new Uint8Array((stream + 7) >> 3)
this.originalByteLength = this.buffer.byteLength
this.max = stream
} else if (typeof stream === 'undefined') {
this.buffer = new Uint8Array(8192)
this.originalByteLength = this.buffer.byteLength
this.max = 8192 << 3
} else {
this.buffer = new Uint8Array(stream, 0, stream.byteLength)
this.max = (this.buffer.byteLength << 3)
this.originalByteLength = stream.byteLength
}
}
/**
* utility / debugging function to examine next 16 bits of stream
* @returns {string} Remaining unconsumed bits in the stream
* (Careful: getters cannot have side-effects like advancing a pointer)
*/
get peek16 () {
let n = 16
let p = this.ptr
if (n + p > this.remaining) n = this.remaining
const bitstrings = []
const hexstrings = []
/* nibble accumulators */
const bits = []
let nibble = 0
for (let i = 0; i < n; i++) {
const q = (p >> 3)
const o = 0x07 - (p & 0x07)
const bit = (this.buffer[q] >> o) & 0x01
nibble = (nibble << 1) | bit
bits.push(bit)
p++
if (i === n - 1 || (i % 4) === 3) {
hexstrings.push(nibble.toString(16))
let bitstring = ''
bits.forEach(bit => { bitstring += (bit === 0) ? '0' : '1' })
bitstrings.push(bitstring)
bits.length = 0
nibble = 0
}
}
return bitstrings.join(' ') + ' ' + hexstrings.join('')
}
/**
* number of bits remaining in the present stream
* @returns {number}
*/
get remaining () {
return this.max - this.ptr
}
/**
* number of bits already consumed in the present stream
* @returns {number}
*/
get consumed () {
return this.ptr
}
seek (pos = 0) {
if (pos > this.max) throw new Error('cannot seek beyond end')
this.ptr = pos
}
reallocate (size) {
if (this.ptr + size <= this.max) return
const newSize = (0xff + Math.floor((this.max + size) * 1.25)) & ~0xff
const newBuf = new Uint8Array((newSize + 7) >>> 3)
this.max = newSize
newBuf.set(this.buffer)
this.buffer = newBuf
}
/**
* copy bits from some other bitstream to this one
* @param {RawBitstream} from the source of the copy
* @param {number} ptr the starting bit position of the copy in "from"
* @param {number} count the number of bits to copy
* @param {number|undefined} to the starting bit position to receive the copy, or the current pointer
*/
copyBits (from, ptr, count, to) {
/* this is a little intricate for the sake of performance */
this.reallocate(count)
/* handle pointer saving. */
const savedFromPtr = from.ptr
const savedToPtr = this.ptr
from.ptr = ptr
if (typeof to === 'number') this.ptr = to
/* split the copy into a starting fragment of < 8 bits,
* a multiple of 8 bits,
* and an ending fragment of less than 8 bits
*/
const firstFragLen = (8 - this.ptr) & 0x07
const lastFragLen = (count - firstFragLen) & 0x07
const byteCopyLen = count - (firstFragLen + lastFragLen)
/* copy first fragment bit by bit */
for (let i = 0; i < firstFragLen; i++) {
const b = from.u_1()
this.put_u_1(b)
}
/* copy whole bytes byte-by-byte */
const thisbuf = this.buffer
const frombuf = from.buffer
let q = this.ptr >> 3
const byteLen = byteCopyLen >> 3
const lshift = from.ptr & 0x07
if (lshift === 0) {
/* byte-aligned source and dest */
let r = from.ptr >> 3
/* four-way loop unroll */
let n = byteLen & 0x03
while (n-- > 0) {
thisbuf[q++] = frombuf[r++]
}
n = byteLen >> 2
while (n-- > 0) {
thisbuf[q++] = frombuf[r++]
thisbuf[q++] = frombuf[r++]
thisbuf[q++] = frombuf[r++]
thisbuf[q++] = frombuf[r++]
}
} else {
/* unaligned source, retrieve it with masks and shifts */
const rshift = 8 - lshift
const mask = (0xff << rshift) & 0xff
let p = (from.ptr >> 3) + 1
let v1 = frombuf[p - 1]
let v2 = frombuf[p]
/* 8-way loop unroll.
* This is a hot path when changing pic_parameter_set_ids in Slices. */
let n = byteLen & 0x07
while (n-- > 0) {
thisbuf[q++] = ((v1 & ~mask) << lshift) | ((v2 & mask) >> rshift)
v1 = v2
v2 = frombuf[++p]
}
n = byteLen >> 3
while (n-- > 0) {
/* flip back and forth between v1 and v2 */
thisbuf[q++] = ((v1 & ~mask) << lshift) | ((v2 & mask) >> rshift)
v1 = frombuf[++p]
thisbuf[q++] = ((v2 & ~mask) << lshift) | ((v1 & mask) >> rshift)
v2 = frombuf[++p]
thisbuf[q++] = ((v1 & ~mask) << lshift) | ((v2 & mask) >> rshift)
v1 = frombuf[++p]
thisbuf[q++] = ((v2 & ~mask) << lshift) | ((v1 & mask) >> rshift)
v2 = frombuf[++p]
thisbuf[q++] = ((v1 & ~mask) << lshift) | ((v2 & mask) >> rshift)
v1 = frombuf[++p]
thisbuf[q++] = ((v2 & ~mask) << lshift) | ((v1 & mask) >> rshift)
v2 = frombuf[++p]
thisbuf[q++] = ((v1 & ~mask) << lshift) | ((v2 & mask) >> rshift)
v1 = frombuf[++p]
thisbuf[q++] = ((v2 & ~mask) << lshift) | ((v1 & mask) >> rshift)
v2 = frombuf[++p]
}
}
from.ptr += byteCopyLen
this.ptr += byteCopyLen
/* copy the last fragment bit by bit */
for (let i = 0; i < lastFragLen; i++) {
const b = from.u_1()
this.put_u_1(b)
}
/* restore saved pointers */
from.ptr = savedFromPtr
if (typeof to === 'number') this.ptr = savedToPtr
}
/**
* put one bit
*/
put_u_1 (b) {
if (this.ptr + 1 > this.max) throw new Error('NALUStream error: bitstream exhausted')
const p = (this.ptr >> 3)
const o = 0x07 - (this.ptr & 0x07)
const val = b << o
const mask = ~(1 << o)
this.buffer[p] = (this.buffer[p] & mask) | val
this.ptr++
return val
}
/**
* get one bit
* @returns {number}
*/
u_1 () {
if (this.ptr + 1 > this.max)
throw new Error('NALUStream error: bitstream exhausted')
const p = (this.ptr >> 3)
const o = 0x07 - (this.ptr & 0x07)
const val = (this.buffer[p] >> o) & 0x01
this.ptr++
return val
}
/**
* get two bits
* @returns {number}
*/
u_2 () {
return (this.u_1() << 1) | (this.u_1())
}
/**
* get three bits
* @returns {number}
*/
u_3 () {
return (this.u_1() << 2) | (this.u_1() << 1) | (this.u_1())
}
/**
* get n bits
* @param n
* @returns {number}
*/
u (n) {
if (n === 8) return this.u_8()
if (this.ptr + n >= this.max) throw new Error('NALUStream error: bitstream exhausted')
let val = 0
for (let i = 0; i < n; i++) {
val = (val << 1) | this.u_1()
}
return val
}
/**
* get one byte (as an unsigned number)
* @returns {number}
*/
u_8 () {
if (this.ptr + 8 > this.max) throw new Error('NALUStream error: bitstream exhausted')
const o = this.ptr & 0x07
if (o === 0) {
const val = this.buffer[(this.ptr >> 3)]
this.ptr += 8
return val
} else {
const n = 8 - o
const rmask = (0xff << n) & 0xff
const lmask = (~rmask) & 0xff
const p = this.ptr >> 3
this.ptr += 8
return ((this.buffer[p] & lmask) << o) | ((this.buffer[p + 1] & rmask) >> n)
}
}
/**
* get an unsigned H.264-style variable-bit number
* in exponential Golomb format
* @returns {number}
*/
ue_v () {
let zeros = 0
while (!this.u_1()) zeros++
let val = 1 << zeros
for (let i = zeros - 1; i >= 0; i--) {
val |= (this.u_1() << i)
}
return val - 1
}
put_u8 (val) {
this.reallocate(8)
if ((this.ptr & 0x07) === 0) {
this.buffer[this.ptr >> 3] = val
this.ptr += 8
return
}
this.put_u(val, 8)
}
put_u (val, count) {
this.reallocate(count)
if (count === 0) return
while (count > 0) {
count--
this.put_u_1((val >> count) & 0x01)
}
}
/**
* Put an exponential-Golomb coded unsigned integer into the bitstream
* https://en.wikipedia.org/wiki/Exponential-Golomb_coding
* @param {number} val to insert
* @returns {number} count of bits inserted
*/
put_ue_v (val) {
const v = val + 1
let v1 = v
let z = -1
do {
z++
v1 = v1 >> 1
} while (v1 !== 0)
this.put_u(0, z)
this.put_u(v, z + 1)
return z + z + 1
}
/**
* when done putting into a buffer, mark it complete,
* rewind it to the beginning, and shorten its contents,
* as if it had just been loaded.
* @returns {number} the number of bits in the buffer
*/
put_complete () {
const newLength = this.ptr
const newByteLength = (newLength + 7) >> 3
this.buffer = this.buffer.subarray(0, newByteLength)
this.originalByteLength = newByteLength
this.max = newLength
this.ptr = 0
return newLength
}
/**
* get a signed h.264-style variable bit number
* in exponential Golomb format
* @returns {number} (without negative zeros)
*/
se_v () {
const codeword = this.ue_v()
const result = codeword & 0x01 ? 1 + (codeword >> 1) : -(codeword >> 1)
return (result === 0) ? 0 : result
}
/**
* Put an exponential-Golomb coded signed integer into the bitstream
* https://en.wikipedia.org/wiki/Exponential-Golomb_coding#Extension_to_negative_numbers
* @param {number} val to insert
* @returns {number} count of bits inserted
*/
put_se_v (val) {
const cw = (val <= 0) ? (-val) << 1 : (val << 1) - 1
return this.put_ue_v(cw)
}
}
/**
* Tools for handling h264 bitstream issues.
*/
export class Bitstream extends RawBitstream {
/**
* Construct a bitstream
* @param stream Buffer containing the stream, or length in bits
*/
constructor (stream) {
super(stream)
if (typeof stream !== 'number' && typeof stream !== 'undefined') {
this.deemulated = this.hasEmulationPrevention(this.buffer)
this.buffer = this.deemulated ? this.deemulate(this.buffer) : this.buffer
this.max = (this.buffer.byteLength << 3)
}
}
get stream () {
return this.deemulated ? this.reemulate(this.buffer) : this.buffer
}
copyBits (from, ptr, count, to) {
this.deemulated = from.deemulated
super.copyBits(from, ptr, count, to)
}
/**
* add emulation prevention bytes
* @param {Uint8Array} buf
* @returns {Uint8Array}
*/
reemulate (buf) {
const size = Math.floor(this.originalByteLength * 1.2)
const stream = new Uint8Array(size)
const len = buf.byteLength - 1
let q = 0
let p = 0
stream[p++] = buf[q++]
stream[p++] = buf[q++]
while (q < len) {
if (buf[q - 2] === 0 && buf[q - 1] === 0 && buf[q] <= 3) {
stream[p++] = 3
stream[p++] = buf[q++]
}
stream[p++] = buf[q++]
}
stream[p++] = buf[q++]
return stream.subarray(0, p)
}
hasEmulationPrevention (stream) {
/* maybe no need to remove emulation protection? scan for 00 00 */
for (let i = 1; i < stream.byteLength; i++) {
if (stream[i - 1] === 0 && stream[i] === 0) {
return true
}
}
return false
}
/**
* remove the emulation prevention bytes
* @param {Uint8Array} stream
* @returns {Uint8Array}
*/
deemulate (stream) {
const buf = new Uint8Array(stream.byteLength)
let p = 0
let q = 0
const len = stream.byteLength - 1
buf[q++] = stream[p++]
buf[q++] = stream[p++]
/* remove emulation prevention: 00 00 03 00 means 00 00 00, 00 00 03 01 means 00 00 01 */
while (p < len) {
if (stream[p - 2] === 0 && stream[p - 1] === 0 && stream[p] === 3 && stream[p] <= 3) p++
else buf[q++] = stream[p++]
}
buf[q++] = stream[p++]
return buf.subarray(0, q)
}
}
/**
* Handle the parsing and creation of "avcC" atoms.
*/
export class AvcC {
/**
* The options here:
* options.bitstream is a bunch of NALUs, the video payload from a webm key frame.
* options.NALUStream, a bitstream in a NALUStream object, read on.
* options.sps and options.pps SPS and PPS NALUs from the H.264 bitstream.
* options.avcC. an existing avcC object.
* options.strict if true, this throws more errors on unexpected data.
* @param options
*/
constructor (options) {
/* instance props */
this.strict = true
this.sps = []
this.pps = []
this.spsDecoded = {}
this.ppsDecoded = {}
this.configurationVersion = 1
this.profileIndication = 0xff
this.profileCompatibility = 0xff
this.avcLevelIndication = 0xff
this.boxSizeMinusOne = 3
this.cacheAvcC = null
this.extradata = null
if (typeof options.strict === 'boolean') this.strict = options.strict
if (typeof options.strictLength === 'boolean') this.strictLength = options.strictLength
/* construct avcC from NALU stream */
let stream
if (options.bitstream || options.naluStream) {
stream = options.naluStream ? options.naluStream : new NALUStream(options.bitstream, options)
this.boxSizeMinusOne = stream.boxSizeMinusOne
for (const nalu of stream) {
let pps
let sps
switch (nalu[0] & 0x1f) {
case 7:
sps = this.unpackSps(nalu)
this.spsDecoded[sps.seq_parameter_set_id] = sps
this.sps.push(nalu)
break
case 8:
pps = this.unpackPps(nalu)
this.ppsDecoded[pps.pic_parameter_set_id] = pps
this.pps.push(nalu)
break
}
if (this.pps.length > 0 && this.sps.length > 0) return
}
if (this.strict) throw new Error('avcC error: bitstream must contain both SPS and PPS')
} else if (options.sps && options.pps) {
/* construct avcC from sps and pps */
const sps = this.unpackSps(options.sps)
this.sps.push(options.sps)
this.spsDecoded[sps.seq_parameter_set_id] = sps
const pps = this.unpackPps(options.pps)
this.pps.push(options.pps)
this.ppsDecoded[pps.pic_parameter_set_id] = pps
} else if (options.avcC) {
/* construct it from avcC stream */
this.cacheAvcC = options.avcC
this.parseAvcC(options.avcC)
}
if (profileNames[this.profileIndication]) {
this.profileName = profileNames[this.profileIndication]
} else {
throw new Error('avcC error: invalid profileIndication')
}
}
/**
* getter for the avcC object
* @returns {Uint8Array}
*/
get avcC () {
this.cacheAvcC = this.packAvcC()
return this.cacheAvcC
}
/**
* setter for the avcC object
* @param {Uint8Array} avcC
*/
set avcC (avcC) {
this.cacheAvcC = avcC
this.parseAvcC(this.cacheAvcC)
}
get hex () {
return NALUStream.array2hex(this.cacheAvcC)
}
/**
* getter for the MIME type encoded in this avcC
* @returns {string}
*/
get MIME () {
const f = []
f.push('avc1.')
f.push(AvcC.byte2hex(this.profileIndication).toUpperCase())
f.push(AvcC.byte2hex(this.profileCompatibility).toUpperCase())
f.push(AvcC.byte2hex(this.avcLevelIndication).toUpperCase())
return f.join('')
}
/**
* put NALU data (sps or pps) into output buffer
* @param {Uint8Array} buf buffer
* @param p {number} pointer to buf
* @param nalus {array} sps[] or pps[]
* @param mask {number} mask for setting bits in nalu-count field
* @returns {number} updated pointer.
*/
static appendNALUs (buf, p, nalus, mask) {
const setBits = ~mask
if (this.strict && (nalus.length <= 0 || nalus.length > mask))
throw new Error('avcC error: too many or not enough NALUs: ' + nalus.length)
buf[p++] = (setBits | (nalus.length & mask))
for (let nalui = 0; nalui < nalus.length; nalui++) {
const nalu = nalus[nalui]
const len = nalu.byteLength
if (this.strict && (len <= 0 || len > 0xffff))
throw new Error('avcC error: NALU has wrong length: ' + len)
buf[p++] = 0xff & (len >> 8)
buf[p++] = 0xff & len
buf.set(nalu, p)
p += len
}
return p
}
static readUInt16BE (buff, ptr) {
return ((buff[ptr] << 8) & 0xff00) | ((buff[ptr + 1]) & 0x00ff) // jshint ignore:line
}
static readUInt32BE (buff, ptr) {
let result = 0 | 0
for (let i = ptr; i < ptr + 4; i++) {
result = ((result << 8) | buff[i])
}
return result
}
static readUInt24BE (buff, ptr) {
let result = 0 | 0
for (let i = ptr; i < ptr + 3; i++) {
result = ((result << 8) | buff[i])
}
return result
}
static byte2hex (val) {
return ('00' + val.toString(16)).slice(-2)
}
parseAvcC (inbuff) {
const buf = new Uint8Array(inbuff, 0, inbuff.byteLength)
const buflen = buf.byteLength
if (buflen < 10) throw new Error('avcC error: object too short')
let ptr = 0
this.configurationVersion = buf[ptr++]
if (this.strict && this.configurationVersion !== 1)
throw new Error(`avcC error: configuration version must be 1: ${this.configurationVersion}`)
this.profileIndication = buf[ptr++]
this.profileCompatibility = buf[ptr++]
this.avcLevelIndication = buf[ptr++]