/
MatroskaExtractor.java
2561 lines (2435 loc) · 103 KB
/
MatroskaExtractor.java
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
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.extractor.mkv;
import static com.google.android.exoplayer2.util.Assertions.checkArgument;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Assertions.checkState;
import static com.google.android.exoplayer2.util.Assertions.checkStateNotNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.annotation.ElementType.TYPE_USE;
import android.util.Pair;
import android.util.SparseArray;
import androidx.annotation.CallSuper;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.audio.AacUtil;
import com.google.android.exoplayer2.audio.MpegAudioUtil;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmInitData.SchemeData;
import com.google.android.exoplayer2.extractor.ChunkIndex;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.extractor.ExtractorInput;
import com.google.android.exoplayer2.extractor.ExtractorOutput;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.extractor.PositionHolder;
import com.google.android.exoplayer2.extractor.SeekMap;
import com.google.android.exoplayer2.extractor.TrackOutput;
import com.google.android.exoplayer2.extractor.TrueHdSampleRechunker;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.LongArray;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.NalUnitUtil;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.AvcConfig;
import com.google.android.exoplayer2.video.ColorInfo;
import com.google.android.exoplayer2.video.DolbyVisionConfig;
import com.google.android.exoplayer2.video.HevcConfig;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.checkerframework.checker.nullness.compatqual.NullableType;
import org.checkerframework.checker.nullness.qual.EnsuresNonNull;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
/**
* Extracts data from the Matroska and WebM container formats.
*
* @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which
* contains the same ExoPlayer code). See <a
* href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the
* migration guide</a> for more details, including a script to help with the migration.
*/
@Deprecated
public class MatroskaExtractor implements Extractor {
/** Factory for {@link MatroskaExtractor} instances. */
public static final ExtractorsFactory FACTORY = () -> new Extractor[] {new MatroskaExtractor()};
/**
* Flags controlling the behavior of the extractor. Possible flag value is {@link
* #FLAG_DISABLE_SEEK_FOR_CUES}.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(TYPE_USE)
@IntDef(
flag = true,
value = {FLAG_DISABLE_SEEK_FOR_CUES})
public @interface Flags {}
/**
* Flag to disable seeking for cues.
*
* <p>Normally (i.e. when this flag is not set) the extractor will seek to the cues element if its
* position is specified in the seek head and if it's after the first cluster. Setting this flag
* disables seeking to the cues element. If the cues element is after the first cluster then the
* media is treated as being unseekable.
*/
public static final int FLAG_DISABLE_SEEK_FOR_CUES = 1;
private static final String TAG = "MatroskaExtractor";
private static final int UNSET_ENTRY_ID = -1;
private static final int BLOCK_STATE_START = 0;
private static final int BLOCK_STATE_HEADER = 1;
private static final int BLOCK_STATE_DATA = 2;
private static final String DOC_TYPE_MATROSKA = "matroska";
private static final String DOC_TYPE_WEBM = "webm";
private static final String CODEC_ID_VP8 = "V_VP8";
private static final String CODEC_ID_VP9 = "V_VP9";
private static final String CODEC_ID_AV1 = "V_AV1";
private static final String CODEC_ID_MPEG2 = "V_MPEG2";
private static final String CODEC_ID_MPEG4_SP = "V_MPEG4/ISO/SP";
private static final String CODEC_ID_MPEG4_ASP = "V_MPEG4/ISO/ASP";
private static final String CODEC_ID_MPEG4_AP = "V_MPEG4/ISO/AP";
private static final String CODEC_ID_H264 = "V_MPEG4/ISO/AVC";
private static final String CODEC_ID_H265 = "V_MPEGH/ISO/HEVC";
private static final String CODEC_ID_FOURCC = "V_MS/VFW/FOURCC";
private static final String CODEC_ID_THEORA = "V_THEORA";
private static final String CODEC_ID_VORBIS = "A_VORBIS";
private static final String CODEC_ID_OPUS = "A_OPUS";
private static final String CODEC_ID_AAC = "A_AAC";
private static final String CODEC_ID_MP2 = "A_MPEG/L2";
private static final String CODEC_ID_MP3 = "A_MPEG/L3";
private static final String CODEC_ID_AC3 = "A_AC3";
private static final String CODEC_ID_E_AC3 = "A_EAC3";
private static final String CODEC_ID_TRUEHD = "A_TRUEHD";
private static final String CODEC_ID_DTS = "A_DTS";
private static final String CODEC_ID_DTS_EXPRESS = "A_DTS/EXPRESS";
private static final String CODEC_ID_DTS_LOSSLESS = "A_DTS/LOSSLESS";
private static final String CODEC_ID_FLAC = "A_FLAC";
private static final String CODEC_ID_ACM = "A_MS/ACM";
private static final String CODEC_ID_PCM_INT_LIT = "A_PCM/INT/LIT";
private static final String CODEC_ID_PCM_INT_BIG = "A_PCM/INT/BIG";
private static final String CODEC_ID_PCM_FLOAT = "A_PCM/FLOAT/IEEE";
private static final String CODEC_ID_SUBRIP = "S_TEXT/UTF8";
private static final String CODEC_ID_ASS = "S_TEXT/ASS";
private static final String CODEC_ID_VTT = "S_TEXT/WEBVTT";
private static final String CODEC_ID_VOBSUB = "S_VOBSUB";
private static final String CODEC_ID_PGS = "S_HDMV/PGS";
private static final String CODEC_ID_DVBSUB = "S_DVBSUB";
private static final int VORBIS_MAX_INPUT_SIZE = 8192;
private static final int OPUS_MAX_INPUT_SIZE = 5760;
private static final int ENCRYPTION_IV_SIZE = 8;
private static final int TRACK_TYPE_AUDIO = 2;
private static final int ID_EBML = 0x1A45DFA3;
private static final int ID_EBML_READ_VERSION = 0x42F7;
private static final int ID_DOC_TYPE = 0x4282;
private static final int ID_DOC_TYPE_READ_VERSION = 0x4285;
private static final int ID_SEGMENT = 0x18538067;
private static final int ID_SEGMENT_INFO = 0x1549A966;
private static final int ID_SEEK_HEAD = 0x114D9B74;
private static final int ID_SEEK = 0x4DBB;
private static final int ID_SEEK_ID = 0x53AB;
private static final int ID_SEEK_POSITION = 0x53AC;
private static final int ID_INFO = 0x1549A966;
private static final int ID_TIMECODE_SCALE = 0x2AD7B1;
private static final int ID_DURATION = 0x4489;
private static final int ID_CLUSTER = 0x1F43B675;
private static final int ID_TIME_CODE = 0xE7;
private static final int ID_SIMPLE_BLOCK = 0xA3;
private static final int ID_BLOCK_GROUP = 0xA0;
private static final int ID_BLOCK = 0xA1;
private static final int ID_BLOCK_DURATION = 0x9B;
private static final int ID_BLOCK_ADDITIONS = 0x75A1;
private static final int ID_BLOCK_MORE = 0xA6;
private static final int ID_BLOCK_ADD_ID = 0xEE;
private static final int ID_BLOCK_ADDITIONAL = 0xA5;
private static final int ID_REFERENCE_BLOCK = 0xFB;
private static final int ID_TRACKS = 0x1654AE6B;
private static final int ID_TRACK_ENTRY = 0xAE;
private static final int ID_TRACK_NUMBER = 0xD7;
private static final int ID_TRACK_TYPE = 0x83;
private static final int ID_FLAG_DEFAULT = 0x88;
private static final int ID_FLAG_FORCED = 0x55AA;
private static final int ID_DEFAULT_DURATION = 0x23E383;
private static final int ID_MAX_BLOCK_ADDITION_ID = 0x55EE;
private static final int ID_BLOCK_ADDITION_MAPPING = 0x41E4;
private static final int ID_BLOCK_ADD_ID_TYPE = 0x41E7;
private static final int ID_BLOCK_ADD_ID_EXTRA_DATA = 0x41ED;
private static final int ID_NAME = 0x536E;
private static final int ID_CODEC_ID = 0x86;
private static final int ID_CODEC_PRIVATE = 0x63A2;
private static final int ID_CODEC_DELAY = 0x56AA;
private static final int ID_SEEK_PRE_ROLL = 0x56BB;
private static final int ID_DISCARD_PADDING = 0x75A2;
private static final int ID_VIDEO = 0xE0;
private static final int ID_PIXEL_WIDTH = 0xB0;
private static final int ID_PIXEL_HEIGHT = 0xBA;
private static final int ID_DISPLAY_WIDTH = 0x54B0;
private static final int ID_DISPLAY_HEIGHT = 0x54BA;
private static final int ID_DISPLAY_UNIT = 0x54B2;
private static final int ID_AUDIO = 0xE1;
private static final int ID_CHANNELS = 0x9F;
private static final int ID_AUDIO_BIT_DEPTH = 0x6264;
private static final int ID_SAMPLING_FREQUENCY = 0xB5;
private static final int ID_CONTENT_ENCODINGS = 0x6D80;
private static final int ID_CONTENT_ENCODING = 0x6240;
private static final int ID_CONTENT_ENCODING_ORDER = 0x5031;
private static final int ID_CONTENT_ENCODING_SCOPE = 0x5032;
private static final int ID_CONTENT_COMPRESSION = 0x5034;
private static final int ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254;
private static final int ID_CONTENT_COMPRESSION_SETTINGS = 0x4255;
private static final int ID_CONTENT_ENCRYPTION = 0x5035;
private static final int ID_CONTENT_ENCRYPTION_ALGORITHM = 0x47E1;
private static final int ID_CONTENT_ENCRYPTION_KEY_ID = 0x47E2;
private static final int ID_CONTENT_ENCRYPTION_AES_SETTINGS = 0x47E7;
private static final int ID_CONTENT_ENCRYPTION_AES_SETTINGS_CIPHER_MODE = 0x47E8;
private static final int ID_CUES = 0x1C53BB6B;
private static final int ID_CUE_POINT = 0xBB;
private static final int ID_CUE_TIME = 0xB3;
private static final int ID_CUE_TRACK_POSITIONS = 0xB7;
private static final int ID_CUE_CLUSTER_POSITION = 0xF1;
private static final int ID_LANGUAGE = 0x22B59C;
private static final int ID_PROJECTION = 0x7670;
private static final int ID_PROJECTION_TYPE = 0x7671;
private static final int ID_PROJECTION_PRIVATE = 0x7672;
private static final int ID_PROJECTION_POSE_YAW = 0x7673;
private static final int ID_PROJECTION_POSE_PITCH = 0x7674;
private static final int ID_PROJECTION_POSE_ROLL = 0x7675;
private static final int ID_STEREO_MODE = 0x53B8;
private static final int ID_COLOUR = 0x55B0;
private static final int ID_COLOUR_RANGE = 0x55B9;
private static final int ID_COLOUR_TRANSFER = 0x55BA;
private static final int ID_COLOUR_PRIMARIES = 0x55BB;
private static final int ID_MAX_CLL = 0x55BC;
private static final int ID_MAX_FALL = 0x55BD;
private static final int ID_MASTERING_METADATA = 0x55D0;
private static final int ID_PRIMARY_R_CHROMATICITY_X = 0x55D1;
private static final int ID_PRIMARY_R_CHROMATICITY_Y = 0x55D2;
private static final int ID_PRIMARY_G_CHROMATICITY_X = 0x55D3;
private static final int ID_PRIMARY_G_CHROMATICITY_Y = 0x55D4;
private static final int ID_PRIMARY_B_CHROMATICITY_X = 0x55D5;
private static final int ID_PRIMARY_B_CHROMATICITY_Y = 0x55D6;
private static final int ID_WHITE_POINT_CHROMATICITY_X = 0x55D7;
private static final int ID_WHITE_POINT_CHROMATICITY_Y = 0x55D8;
private static final int ID_LUMNINANCE_MAX = 0x55D9;
private static final int ID_LUMNINANCE_MIN = 0x55DA;
/**
* BlockAddID value for ITU T.35 metadata in a VP9 track. See also
* https://www.webmproject.org/docs/container/.
*/
private static final int BLOCK_ADDITIONAL_ID_VP9_ITU_T_35 = 4;
/**
* BlockAddIdType value for Dolby Vision configuration with profile <= 7. See also
* https://www.matroska.org/technical/codec_specs.html.
*/
private static final int BLOCK_ADD_ID_TYPE_DVCC = 0x64766343;
/**
* BlockAddIdType value for Dolby Vision configuration with profile > 7. See also
* https://www.matroska.org/technical/codec_specs.html.
*/
private static final int BLOCK_ADD_ID_TYPE_DVVC = 0x64767643;
private static final int LACING_NONE = 0;
private static final int LACING_XIPH = 1;
private static final int LACING_FIXED_SIZE = 2;
private static final int LACING_EBML = 3;
private static final int FOURCC_COMPRESSION_DIVX = 0x58564944;
private static final int FOURCC_COMPRESSION_H263 = 0x33363248;
private static final int FOURCC_COMPRESSION_VC1 = 0x31435657;
/**
* A template for the prefix that must be added to each subrip sample.
*
* <p>The display time of each subtitle is passed as {@code timeUs} to {@link
* TrackOutput#sampleMetadata}. The start and end timecodes in this template are relative to
* {@code timeUs}. Hence the start timecode is always zero. The 12 byte end timecode starting at
* {@link #SUBRIP_PREFIX_END_TIMECODE_OFFSET} is set to a placeholder value, and must be replaced
* with the duration of the subtitle.
*
* <p>Equivalent to the UTF-8 string: "1\n00:00:00,000 --> 00:00:00,000\n".
*/
private static final byte[] SUBRIP_PREFIX =
new byte[] {
49, 10, 48, 48, 58, 48, 48, 58, 48, 48, 44, 48, 48, 48, 32, 45, 45, 62, 32, 48, 48, 58, 48,
48, 58, 48, 48, 44, 48, 48, 48, 10
};
/** The byte offset of the end timecode in {@link #SUBRIP_PREFIX}. */
private static final int SUBRIP_PREFIX_END_TIMECODE_OFFSET = 19;
/**
* The value by which to divide a time in microseconds to convert it to the unit of the last value
* in a subrip timecode (milliseconds).
*/
private static final long SUBRIP_TIMECODE_LAST_VALUE_SCALING_FACTOR = 1000;
/** The format of a subrip timecode. */
private static final String SUBRIP_TIMECODE_FORMAT = "%02d:%02d:%02d,%03d";
/** Matroska specific format line for SSA subtitles. */
private static final byte[] SSA_DIALOGUE_FORMAT =
Util.getUtf8Bytes(
"Format: Start, End, "
+ "ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text");
/**
* A template for the prefix that must be added to each SSA sample.
*
* <p>The display time of each subtitle is passed as {@code timeUs} to {@link
* TrackOutput#sampleMetadata}. The start and end timecodes in this template are relative to
* {@code timeUs}. Hence the start timecode is always zero. The 12 byte end timecode starting at
* {@link #SUBRIP_PREFIX_END_TIMECODE_OFFSET} is set to a placeholder value, and must be replaced
* with the duration of the subtitle.
*
* <p>Equivalent to the UTF-8 string: "Dialogue: 0:00:00:00,0:00:00:00,".
*/
private static final byte[] SSA_PREFIX =
new byte[] {
68, 105, 97, 108, 111, 103, 117, 101, 58, 32, 48, 58, 48, 48, 58, 48, 48, 58, 48, 48, 44,
48, 58, 48, 48, 58, 48, 48, 58, 48, 48, 44
};
/** The byte offset of the end timecode in {@link #SSA_PREFIX}. */
private static final int SSA_PREFIX_END_TIMECODE_OFFSET = 21;
/**
* The value by which to divide a time in microseconds to convert it to the unit of the last value
* in an SSA timecode (1/100ths of a second).
*/
private static final long SSA_TIMECODE_LAST_VALUE_SCALING_FACTOR = 10_000;
/** The format of an SSA timecode. */
private static final String SSA_TIMECODE_FORMAT = "%01d:%02d:%02d:%02d";
/**
* A template for the prefix that must be added to each VTT sample.
*
* <p>The display time of each subtitle is passed as {@code timeUs} to {@link
* TrackOutput#sampleMetadata}. The start and end timecodes in this template are relative to
* {@code timeUs}. Hence the start timecode is always zero. The 12 byte end timecode starting at
* {@link #VTT_PREFIX_END_TIMECODE_OFFSET} is set to a placeholder value, and must be replaced
* with the duration of the subtitle.
*
* <p>Equivalent to the UTF-8 string: "WEBVTT\n\n00:00:00.000 --> 00:00:00.000\n".
*/
private static final byte[] VTT_PREFIX =
new byte[] {
87, 69, 66, 86, 84, 84, 10, 10, 48, 48, 58, 48, 48, 58, 48, 48, 46, 48, 48, 48, 32, 45, 45,
62, 32, 48, 48, 58, 48, 48, 58, 48, 48, 46, 48, 48, 48, 10
};
/** The byte offset of the end timecode in {@link #VTT_PREFIX}. */
private static final int VTT_PREFIX_END_TIMECODE_OFFSET = 25;
/**
* The value by which to divide a time in microseconds to convert it to the unit of the last value
* in a VTT timecode (milliseconds).
*/
private static final long VTT_TIMECODE_LAST_VALUE_SCALING_FACTOR = 1000;
/** The format of a VTT timecode. */
private static final String VTT_TIMECODE_FORMAT = "%02d:%02d:%02d.%03d";
/** The length in bytes of a WAVEFORMATEX structure. */
private static final int WAVE_FORMAT_SIZE = 18;
/** Format tag indicating a WAVEFORMATEXTENSIBLE structure. */
private static final int WAVE_FORMAT_EXTENSIBLE = 0xFFFE;
/** Format tag for PCM. */
private static final int WAVE_FORMAT_PCM = 1;
/** Sub format for PCM. */
private static final UUID WAVE_SUBFORMAT_PCM = new UUID(0x0100000000001000L, 0x800000AA00389B71L);
/** Some HTC devices signal rotation in track names. */
private static final Map<String, Integer> TRACK_NAME_TO_ROTATION_DEGREES;
static {
Map<String, Integer> trackNameToRotationDegrees = new HashMap<>();
trackNameToRotationDegrees.put("htc_video_rotA-000", 0);
trackNameToRotationDegrees.put("htc_video_rotA-090", 90);
trackNameToRotationDegrees.put("htc_video_rotA-180", 180);
trackNameToRotationDegrees.put("htc_video_rotA-270", 270);
TRACK_NAME_TO_ROTATION_DEGREES = Collections.unmodifiableMap(trackNameToRotationDegrees);
}
private final EbmlReader reader;
private final VarintReader varintReader;
private final SparseArray<Track> tracks;
private final boolean seekForCuesEnabled;
// Temporary arrays.
private final ParsableByteArray nalStartCode;
private final ParsableByteArray nalLength;
private final ParsableByteArray scratch;
private final ParsableByteArray vorbisNumPageSamples;
private final ParsableByteArray seekEntryIdBytes;
private final ParsableByteArray sampleStrippedBytes;
private final ParsableByteArray subtitleSample;
private final ParsableByteArray encryptionInitializationVector;
private final ParsableByteArray encryptionSubsampleData;
private final ParsableByteArray supplementalData;
private @MonotonicNonNull ByteBuffer encryptionSubsampleDataBuffer;
private long segmentContentSize;
private long segmentContentPosition = C.INDEX_UNSET;
private long timecodeScale = C.TIME_UNSET;
private long durationTimecode = C.TIME_UNSET;
private long durationUs = C.TIME_UNSET;
// The track corresponding to the current TrackEntry element, or null.
@Nullable private Track currentTrack;
// Whether a seek map has been sent to the output.
private boolean sentSeekMap;
// Master seek entry related elements.
private int seekEntryId;
private long seekEntryPosition;
// Cue related elements.
private boolean seekForCues;
private long cuesContentPosition = C.INDEX_UNSET;
private long seekPositionAfterBuildingCues = C.INDEX_UNSET;
private long clusterTimecodeUs = C.TIME_UNSET;
@Nullable private LongArray cueTimesUs;
@Nullable private LongArray cueClusterPositions;
private boolean seenClusterPositionForCurrentCuePoint;
// Reading state.
private boolean haveOutputSample;
// Block reading state.
private int blockState;
private long blockTimeUs;
private long blockDurationUs;
private int blockSampleIndex;
private int blockSampleCount;
private int[] blockSampleSizes;
private int blockTrackNumber;
private int blockTrackNumberLength;
private @C.BufferFlags int blockFlags;
private int blockAdditionalId;
private boolean blockHasReferenceBlock;
private long blockGroupDiscardPaddingNs;
// Sample writing state.
private int sampleBytesRead;
private int sampleBytesWritten;
private int sampleCurrentNalBytesRemaining;
private boolean sampleEncodingHandled;
private boolean sampleSignalByteRead;
private boolean samplePartitionCountRead;
private int samplePartitionCount;
private byte sampleSignalByte;
private boolean sampleInitializationVectorRead;
// Extractor outputs.
private @MonotonicNonNull ExtractorOutput extractorOutput;
public MatroskaExtractor() {
this(0);
}
public MatroskaExtractor(@Flags int flags) {
this(new DefaultEbmlReader(), flags);
}
/* package */ MatroskaExtractor(EbmlReader reader, @Flags int flags) {
this.reader = reader;
this.reader.init(new InnerEbmlProcessor());
seekForCuesEnabled = (flags & FLAG_DISABLE_SEEK_FOR_CUES) == 0;
varintReader = new VarintReader();
tracks = new SparseArray<>();
scratch = new ParsableByteArray(4);
vorbisNumPageSamples = new ParsableByteArray(ByteBuffer.allocate(4).putInt(-1).array());
seekEntryIdBytes = new ParsableByteArray(4);
nalStartCode = new ParsableByteArray(NalUnitUtil.NAL_START_CODE);
nalLength = new ParsableByteArray(4);
sampleStrippedBytes = new ParsableByteArray();
subtitleSample = new ParsableByteArray();
encryptionInitializationVector = new ParsableByteArray(ENCRYPTION_IV_SIZE);
encryptionSubsampleData = new ParsableByteArray();
supplementalData = new ParsableByteArray();
blockSampleSizes = new int[1];
}
@Override
public final boolean sniff(ExtractorInput input) throws IOException {
return new Sniffer().sniff(input);
}
@Override
public final void init(ExtractorOutput output) {
extractorOutput = output;
}
@CallSuper
@Override
public void seek(long position, long timeUs) {
clusterTimecodeUs = C.TIME_UNSET;
blockState = BLOCK_STATE_START;
reader.reset();
varintReader.reset();
resetWriteSampleData();
for (int i = 0; i < tracks.size(); i++) {
tracks.valueAt(i).reset();
}
}
@Override
public final void release() {
// Do nothing
}
@Override
public final int read(ExtractorInput input, PositionHolder seekPosition) throws IOException {
haveOutputSample = false;
boolean continueReading = true;
while (continueReading && !haveOutputSample) {
continueReading = reader.read(input);
if (continueReading && maybeSeekForCues(seekPosition, input.getPosition())) {
return Extractor.RESULT_SEEK;
}
}
if (!continueReading) {
for (int i = 0; i < tracks.size(); i++) {
Track track = tracks.valueAt(i);
track.assertOutputInitialized();
track.outputPendingSampleMetadata();
}
return Extractor.RESULT_END_OF_INPUT;
}
return Extractor.RESULT_CONTINUE;
}
/**
* Maps an element ID to a corresponding type.
*
* @see EbmlProcessor#getElementType(int)
*/
@CallSuper
protected @EbmlProcessor.ElementType int getElementType(int id) {
switch (id) {
case ID_EBML:
case ID_SEGMENT:
case ID_SEEK_HEAD:
case ID_SEEK:
case ID_INFO:
case ID_CLUSTER:
case ID_TRACKS:
case ID_TRACK_ENTRY:
case ID_BLOCK_ADDITION_MAPPING:
case ID_AUDIO:
case ID_VIDEO:
case ID_CONTENT_ENCODINGS:
case ID_CONTENT_ENCODING:
case ID_CONTENT_COMPRESSION:
case ID_CONTENT_ENCRYPTION:
case ID_CONTENT_ENCRYPTION_AES_SETTINGS:
case ID_CUES:
case ID_CUE_POINT:
case ID_CUE_TRACK_POSITIONS:
case ID_BLOCK_GROUP:
case ID_BLOCK_ADDITIONS:
case ID_BLOCK_MORE:
case ID_PROJECTION:
case ID_COLOUR:
case ID_MASTERING_METADATA:
return EbmlProcessor.ELEMENT_TYPE_MASTER;
case ID_EBML_READ_VERSION:
case ID_DOC_TYPE_READ_VERSION:
case ID_SEEK_POSITION:
case ID_TIMECODE_SCALE:
case ID_TIME_CODE:
case ID_BLOCK_DURATION:
case ID_PIXEL_WIDTH:
case ID_PIXEL_HEIGHT:
case ID_DISPLAY_WIDTH:
case ID_DISPLAY_HEIGHT:
case ID_DISPLAY_UNIT:
case ID_TRACK_NUMBER:
case ID_TRACK_TYPE:
case ID_FLAG_DEFAULT:
case ID_FLAG_FORCED:
case ID_DEFAULT_DURATION:
case ID_MAX_BLOCK_ADDITION_ID:
case ID_BLOCK_ADD_ID_TYPE:
case ID_CODEC_DELAY:
case ID_SEEK_PRE_ROLL:
case ID_DISCARD_PADDING:
case ID_CHANNELS:
case ID_AUDIO_BIT_DEPTH:
case ID_CONTENT_ENCODING_ORDER:
case ID_CONTENT_ENCODING_SCOPE:
case ID_CONTENT_COMPRESSION_ALGORITHM:
case ID_CONTENT_ENCRYPTION_ALGORITHM:
case ID_CONTENT_ENCRYPTION_AES_SETTINGS_CIPHER_MODE:
case ID_CUE_TIME:
case ID_CUE_CLUSTER_POSITION:
case ID_REFERENCE_BLOCK:
case ID_STEREO_MODE:
case ID_COLOUR_RANGE:
case ID_COLOUR_TRANSFER:
case ID_COLOUR_PRIMARIES:
case ID_MAX_CLL:
case ID_MAX_FALL:
case ID_PROJECTION_TYPE:
case ID_BLOCK_ADD_ID:
return EbmlProcessor.ELEMENT_TYPE_UNSIGNED_INT;
case ID_DOC_TYPE:
case ID_NAME:
case ID_CODEC_ID:
case ID_LANGUAGE:
return EbmlProcessor.ELEMENT_TYPE_STRING;
case ID_SEEK_ID:
case ID_BLOCK_ADD_ID_EXTRA_DATA:
case ID_CONTENT_COMPRESSION_SETTINGS:
case ID_CONTENT_ENCRYPTION_KEY_ID:
case ID_SIMPLE_BLOCK:
case ID_BLOCK:
case ID_CODEC_PRIVATE:
case ID_PROJECTION_PRIVATE:
case ID_BLOCK_ADDITIONAL:
return EbmlProcessor.ELEMENT_TYPE_BINARY;
case ID_DURATION:
case ID_SAMPLING_FREQUENCY:
case ID_PRIMARY_R_CHROMATICITY_X:
case ID_PRIMARY_R_CHROMATICITY_Y:
case ID_PRIMARY_G_CHROMATICITY_X:
case ID_PRIMARY_G_CHROMATICITY_Y:
case ID_PRIMARY_B_CHROMATICITY_X:
case ID_PRIMARY_B_CHROMATICITY_Y:
case ID_WHITE_POINT_CHROMATICITY_X:
case ID_WHITE_POINT_CHROMATICITY_Y:
case ID_LUMNINANCE_MAX:
case ID_LUMNINANCE_MIN:
case ID_PROJECTION_POSE_YAW:
case ID_PROJECTION_POSE_PITCH:
case ID_PROJECTION_POSE_ROLL:
return EbmlProcessor.ELEMENT_TYPE_FLOAT;
default:
return EbmlProcessor.ELEMENT_TYPE_UNKNOWN;
}
}
/**
* Checks if the given id is that of a level 1 element.
*
* @see EbmlProcessor#isLevel1Element(int)
*/
@CallSuper
protected boolean isLevel1Element(int id) {
return id == ID_SEGMENT_INFO || id == ID_CLUSTER || id == ID_CUES || id == ID_TRACKS;
}
/**
* Called when the start of a master element is encountered.
*
* @see EbmlProcessor#startMasterElement(int, long, long)
*/
@CallSuper
protected void startMasterElement(int id, long contentPosition, long contentSize)
throws ParserException {
assertInitialized();
switch (id) {
case ID_SEGMENT:
if (segmentContentPosition != C.INDEX_UNSET && segmentContentPosition != contentPosition) {
throw ParserException.createForMalformedContainer(
"Multiple Segment elements not supported", /* cause= */ null);
}
segmentContentPosition = contentPosition;
segmentContentSize = contentSize;
break;
case ID_SEEK:
seekEntryId = UNSET_ENTRY_ID;
seekEntryPosition = C.INDEX_UNSET;
break;
case ID_CUES:
cueTimesUs = new LongArray();
cueClusterPositions = new LongArray();
break;
case ID_CUE_POINT:
seenClusterPositionForCurrentCuePoint = false;
break;
case ID_CLUSTER:
if (!sentSeekMap) {
// We need to build cues before parsing the cluster.
if (seekForCuesEnabled && cuesContentPosition != C.INDEX_UNSET) {
// We know where the Cues element is located. Seek to request it.
seekForCues = true;
} else {
// We don't know where the Cues element is located. It's most likely omitted. Allow
// playback, but disable seeking.
extractorOutput.seekMap(new SeekMap.Unseekable(durationUs));
sentSeekMap = true;
}
}
break;
case ID_BLOCK_GROUP:
blockHasReferenceBlock = false;
blockGroupDiscardPaddingNs = 0L;
break;
case ID_CONTENT_ENCODING:
// TODO: check and fail if more than one content encoding is present.
break;
case ID_CONTENT_ENCRYPTION:
getCurrentTrack(id).hasContentEncryption = true;
break;
case ID_TRACK_ENTRY:
currentTrack = new Track();
break;
case ID_MASTERING_METADATA:
getCurrentTrack(id).hasColorInfo = true;
break;
default:
break;
}
}
/**
* Called when the end of a master element is encountered.
*
* @see EbmlProcessor#endMasterElement(int)
*/
@CallSuper
protected void endMasterElement(int id) throws ParserException {
assertInitialized();
switch (id) {
case ID_SEGMENT_INFO:
if (timecodeScale == C.TIME_UNSET) {
// timecodeScale was omitted. Use the default value.
timecodeScale = 1000000;
}
if (durationTimecode != C.TIME_UNSET) {
durationUs = scaleTimecodeToUs(durationTimecode);
}
break;
case ID_SEEK:
if (seekEntryId == UNSET_ENTRY_ID || seekEntryPosition == C.INDEX_UNSET) {
throw ParserException.createForMalformedContainer(
"Mandatory element SeekID or SeekPosition not found", /* cause= */ null);
}
if (seekEntryId == ID_CUES) {
cuesContentPosition = seekEntryPosition;
}
break;
case ID_CUES:
if (!sentSeekMap) {
extractorOutput.seekMap(buildSeekMap(cueTimesUs, cueClusterPositions));
sentSeekMap = true;
} else {
// We have already built the cues. Ignore.
}
this.cueTimesUs = null;
this.cueClusterPositions = null;
break;
case ID_BLOCK_GROUP:
if (blockState != BLOCK_STATE_DATA) {
// We've skipped this block (due to incompatible track number).
return;
}
Track track = tracks.get(blockTrackNumber);
track.assertOutputInitialized();
if (blockGroupDiscardPaddingNs > 0L && CODEC_ID_OPUS.equals(track.codecId)) {
// For Opus, attach DiscardPadding to the block group samples as supplemental data.
supplementalData.reset(
ByteBuffer.allocate(8)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(blockGroupDiscardPaddingNs)
.array());
}
// Commit sample metadata.
int sampleOffset = 0;
for (int i = 0; i < blockSampleCount; i++) {
sampleOffset += blockSampleSizes[i];
}
for (int i = 0; i < blockSampleCount; i++) {
long sampleTimeUs = blockTimeUs + (i * track.defaultSampleDurationNs) / 1000;
int sampleFlags = blockFlags;
if (i == 0 && !blockHasReferenceBlock) {
// If the ReferenceBlock element was not found in this block, then the first frame is a
// keyframe.
sampleFlags |= C.BUFFER_FLAG_KEY_FRAME;
}
int sampleSize = blockSampleSizes[i];
sampleOffset -= sampleSize; // The offset is to the end of the sample.
commitSampleToOutput(track, sampleTimeUs, sampleFlags, sampleSize, sampleOffset);
}
blockState = BLOCK_STATE_START;
break;
case ID_CONTENT_ENCODING:
assertInTrackEntry(id);
if (currentTrack.hasContentEncryption) {
if (currentTrack.cryptoData == null) {
throw ParserException.createForMalformedContainer(
"Encrypted Track found but ContentEncKeyID was not found", /* cause= */ null);
}
currentTrack.drmInitData =
new DrmInitData(
new SchemeData(
C.UUID_NIL, MimeTypes.VIDEO_WEBM, currentTrack.cryptoData.encryptionKey));
}
break;
case ID_CONTENT_ENCODINGS:
assertInTrackEntry(id);
if (currentTrack.hasContentEncryption && currentTrack.sampleStrippedBytes != null) {
throw ParserException.createForMalformedContainer(
"Combining encryption and compression is not supported", /* cause= */ null);
}
break;
case ID_TRACK_ENTRY:
Track currentTrack = checkStateNotNull(this.currentTrack);
if (currentTrack.codecId == null) {
throw ParserException.createForMalformedContainer(
"CodecId is missing in TrackEntry element", /* cause= */ null);
} else {
if (isCodecSupported(currentTrack.codecId)) {
currentTrack.initializeOutput(extractorOutput, currentTrack.number);
tracks.put(currentTrack.number, currentTrack);
}
}
this.currentTrack = null;
break;
case ID_TRACKS:
if (tracks.size() == 0) {
throw ParserException.createForMalformedContainer(
"No valid tracks were found", /* cause= */ null);
}
extractorOutput.endTracks();
break;
default:
break;
}
}
/**
* Called when an integer element is encountered.
*
* @see EbmlProcessor#integerElement(int, long)
*/
@CallSuper
protected void integerElement(int id, long value) throws ParserException {
switch (id) {
case ID_EBML_READ_VERSION:
// Validate that EBMLReadVersion is supported. This extractor only supports v1.
if (value != 1) {
throw ParserException.createForMalformedContainer(
"EBMLReadVersion " + value + " not supported", /* cause= */ null);
}
break;
case ID_DOC_TYPE_READ_VERSION:
// Validate that DocTypeReadVersion is supported. This extractor only supports up to v2.
if (value < 1 || value > 2) {
throw ParserException.createForMalformedContainer(
"DocTypeReadVersion " + value + " not supported", /* cause= */ null);
}
break;
case ID_SEEK_POSITION:
// Seek Position is the relative offset beginning from the Segment. So to get absolute
// offset from the beginning of the file, we need to add segmentContentPosition to it.
seekEntryPosition = value + segmentContentPosition;
break;
case ID_TIMECODE_SCALE:
timecodeScale = value;
break;
case ID_PIXEL_WIDTH:
getCurrentTrack(id).width = (int) value;
break;
case ID_PIXEL_HEIGHT:
getCurrentTrack(id).height = (int) value;
break;
case ID_DISPLAY_WIDTH:
getCurrentTrack(id).displayWidth = (int) value;
break;
case ID_DISPLAY_HEIGHT:
getCurrentTrack(id).displayHeight = (int) value;
break;
case ID_DISPLAY_UNIT:
getCurrentTrack(id).displayUnit = (int) value;
break;
case ID_TRACK_NUMBER:
getCurrentTrack(id).number = (int) value;
break;
case ID_FLAG_DEFAULT:
getCurrentTrack(id).flagDefault = value == 1;
break;
case ID_FLAG_FORCED:
getCurrentTrack(id).flagForced = value == 1;
break;
case ID_TRACK_TYPE:
getCurrentTrack(id).type = (int) value;
break;
case ID_DEFAULT_DURATION:
getCurrentTrack(id).defaultSampleDurationNs = (int) value;
break;
case ID_MAX_BLOCK_ADDITION_ID:
getCurrentTrack(id).maxBlockAdditionId = (int) value;
break;
case ID_BLOCK_ADD_ID_TYPE:
getCurrentTrack(id).blockAddIdType = (int) value;
break;
case ID_CODEC_DELAY:
getCurrentTrack(id).codecDelayNs = value;
break;
case ID_SEEK_PRE_ROLL:
getCurrentTrack(id).seekPreRollNs = value;
break;
case ID_DISCARD_PADDING:
blockGroupDiscardPaddingNs = value;
break;
case ID_CHANNELS:
getCurrentTrack(id).channelCount = (int) value;
break;
case ID_AUDIO_BIT_DEPTH:
getCurrentTrack(id).audioBitDepth = (int) value;
break;
case ID_REFERENCE_BLOCK:
blockHasReferenceBlock = true;
break;
case ID_CONTENT_ENCODING_ORDER:
// This extractor only supports one ContentEncoding element and hence the order has to be 0.
if (value != 0) {
throw ParserException.createForMalformedContainer(
"ContentEncodingOrder " + value + " not supported", /* cause= */ null);
}
break;
case ID_CONTENT_ENCODING_SCOPE:
// This extractor only supports the scope of all frames.
if (value != 1) {
throw ParserException.createForMalformedContainer(
"ContentEncodingScope " + value + " not supported", /* cause= */ null);
}
break;
case ID_CONTENT_COMPRESSION_ALGORITHM:
// This extractor only supports header stripping.
if (value != 3) {
throw ParserException.createForMalformedContainer(
"ContentCompAlgo " + value + " not supported", /* cause= */ null);
}
break;
case ID_CONTENT_ENCRYPTION_ALGORITHM:
// Only the value 5 (AES) is allowed according to the WebM specification.
if (value != 5) {
throw ParserException.createForMalformedContainer(
"ContentEncAlgo " + value + " not supported", /* cause= */ null);
}
break;
case ID_CONTENT_ENCRYPTION_AES_SETTINGS_CIPHER_MODE:
// Only the value 1 is allowed according to the WebM specification.
if (value != 1) {
throw ParserException.createForMalformedContainer(
"AESSettingsCipherMode " + value + " not supported", /* cause= */ null);
}
break;
case ID_CUE_TIME:
assertInCues(id);
cueTimesUs.add(scaleTimecodeToUs(value));
break;
case ID_CUE_CLUSTER_POSITION:
if (!seenClusterPositionForCurrentCuePoint) {
assertInCues(id);
// If there's more than one video/audio track, then there could be more than one
// CueTrackPositions within a single CuePoint. In such a case, ignore all but the first
// one (since the cluster position will be quite close for all the tracks).
cueClusterPositions.add(value);
seenClusterPositionForCurrentCuePoint = true;
}
break;
case ID_TIME_CODE:
clusterTimecodeUs = scaleTimecodeToUs(value);
break;
case ID_BLOCK_DURATION:
blockDurationUs = scaleTimecodeToUs(value);
break;
case ID_STEREO_MODE:
int layout = (int) value;
assertInTrackEntry(id);
switch (layout) {
case 0:
currentTrack.stereoMode = C.STEREO_MODE_MONO;
break;
case 1:
currentTrack.stereoMode = C.STEREO_MODE_LEFT_RIGHT;
break;
case 3:
currentTrack.stereoMode = C.STEREO_MODE_TOP_BOTTOM;
break;
case 15:
currentTrack.stereoMode = C.STEREO_MODE_STEREO_MESH;
break;
default:
break;
}
break;
case ID_COLOUR_PRIMARIES:
assertInTrackEntry(id);
currentTrack.hasColorInfo = true;
int colorSpace = ColorInfo.isoColorPrimariesToColorSpace((int) value);
if (colorSpace != Format.NO_VALUE) {