Shaka Packager SDK
Loading...
Searching...
No Matches
container_names.cc
1// Copyright (c) 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <packager/media/base/container_names.h>
6
7#include <algorithm>
8#include <cctype>
9#include <cstddef>
10#include <cstdint>
11#include <cstring>
12#include <iterator>
13#include <string>
14
15#include <absl/log/check.h>
16#include <libxml/parser.h>
17#include <libxml/tree.h>
18
19#include <packager/media/base/bit_reader.h>
20#include <packager/mpd/base/xml/scoped_xml_ptr.h>
21
22namespace shaka {
23namespace media {
24
25#define TAG(a, b, c, d) \
26 ((static_cast<uint32_t>(static_cast<uint8_t>(a)) << 24) | \
27 (static_cast<uint8_t>(b) << 16) | (static_cast<uint8_t>(c) << 8) | \
28 (static_cast<uint8_t>(d)))
29
30#define RCHECK(x) \
31 do { \
32 if (!(x)) \
33 return false; \
34 } while (0)
35
36#define UTF8_BYTE_ORDER_MARK "\xef\xbb\xbf"
37
38// Helper function to read 2 bytes (16 bits, big endian) from a buffer.
39static int Read16(const uint8_t* p) {
40 return p[0] << 8 | p[1];
41}
42
43// Helper function to read 3 bytes (24 bits, big endian) from a buffer.
44static uint32_t Read24(const uint8_t* p) {
45 return p[0] << 16 | p[1] << 8 | p[2];
46}
47
48// Helper function to read 4 bytes (32 bits, big endian) from a buffer.
49static uint32_t Read32(const uint8_t* p) {
50 return p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
51}
52
53// Helper function to read 4 bytes (32 bits, little endian) from a buffer.
54static uint32_t Read32LE(const uint8_t* p) {
55 return p[3] << 24 | p[2] << 16 | p[1] << 8 | p[0];
56}
57
58// Helper function to do buffer comparisons with a string without going off the
59// end of the buffer.
60static bool StartsWith(const uint8_t* buffer,
61 size_t buffer_size,
62 const char* prefix) {
63 size_t prefix_size = strlen(prefix);
64 return (prefix_size <= buffer_size &&
65 memcmp(buffer, prefix, prefix_size) == 0);
66}
67
68// Helper function to do buffer comparisons with another buffer (to allow for
69// embedded \0 in the comparison) without going off the end of the buffer.
70static bool StartsWith(const uint8_t* buffer,
71 size_t buffer_size,
72 const uint8_t* prefix,
73 size_t prefix_size) {
74 return (prefix_size <= buffer_size &&
75 memcmp(buffer, prefix, prefix_size) == 0);
76}
77
78// Helper function to read up to 64 bits from a bit stream.
79static uint64_t ReadBits(BitReader* reader, int num_bits) {
80 DCHECK_GE(static_cast<int>(reader->bits_available()), num_bits);
81 DCHECK((num_bits > 0) && (num_bits <= 64));
82 uint64_t value;
83 reader->ReadBits(num_bits, &value);
84 return value;
85}
86
87const int kAc3FrameSizeTable[38][3] = {
88 {128, 138, 192}, {128, 140, 192}, {160, 174, 240},
89 {160, 176, 240}, {192, 208, 288}, {192, 210, 288},
90 {224, 242, 336}, {224, 244, 336}, {256, 278, 384},
91 {256, 280, 384}, {320, 348, 480}, {320, 350, 480},
92 {384, 416, 576}, {384, 418, 576}, {448, 486, 672},
93 {448, 488, 672}, {512, 556, 768}, {512, 558, 768},
94 {640, 696, 960}, {640, 698, 960}, {768, 834, 1152},
95 {768, 836, 1152}, {896, 974, 1344}, {896, 976, 1344},
96 {1024, 1114, 1536}, {1024, 1116, 1536}, {1280, 1392, 1920},
97 {1280, 1394, 1920}, {1536, 1670, 2304}, {1536, 1672, 2304},
98 {1792, 1950, 2688}, {1792, 1952, 2688}, {2048, 2228, 3072},
99 {2048, 2230, 3072}, {2304, 2506, 3456}, {2304, 2508, 3456},
100 {2560, 2768, 3840}, {2560, 2770, 3840}};
101
102// Checks for an ADTS AAC container.
103static bool CheckAac(const uint8_t* buffer, int buffer_size) {
104 // Audio Data Transport Stream (ADTS) header is 7 or 9 bytes
105 // (from http://wiki.multimedia.cx/index.php?title=ADTS)
106 RCHECK(buffer_size > 6);
107
108 int offset = 0;
109 while (offset + 6 < buffer_size) {
110 BitReader reader(buffer + offset, 6);
111
112 // Syncword must be 0xfff.
113 RCHECK(ReadBits(&reader, 12) == 0xfff);
114
115 // Skip MPEG version.
116 reader.SkipBits(1);
117
118 // Layer is always 0.
119 RCHECK(ReadBits(&reader, 2) == 0);
120
121 // Skip protection + profile.
122 reader.SkipBits(1 + 2);
123
124 // Check sampling frequency index.
125 RCHECK(ReadBits(&reader, 4) != 15); // Forbidden.
126
127 // Skip private stream, channel configuration, originality, home,
128 // copyrighted stream, and copyright_start.
129 reader.SkipBits(1 + 3 + 1 + 1 + 1 + 1);
130
131 // Get frame length (includes header).
132 int size = ReadBits(&reader, 13);
133 RCHECK(size > 0);
134 offset += size;
135 }
136 return true;
137}
138
139const uint16_t kAc3SyncWord = 0x0b77;
140
141// Checks for an AC3 container.
142static bool CheckAc3(const uint8_t* buffer, int buffer_size) {
143 // Reference: ATSC Standard: Digital Audio Compression (AC-3, E-AC-3)
144 // Doc. A/52:2012
145 // (http://www.atsc.org/cms/standards/A52-2012(12-17).pdf)
146
147 // AC3 container looks like syncinfo | bsi | audblk * 6 | aux | check.
148 RCHECK(buffer_size > 6);
149
150 int offset = 0;
151 while (offset + 6 < buffer_size) {
152 BitReader reader(buffer + offset, 6);
153
154 // Check syncinfo.
155 RCHECK(ReadBits(&reader, 16) == kAc3SyncWord);
156
157 // Skip crc1.
158 reader.SkipBits(16);
159
160 // Verify fscod.
161 int sample_rate_code = ReadBits(&reader, 2);
162 RCHECK(sample_rate_code != 3); // Reserved.
163
164 // Verify frmsizecod.
165 int frame_size_code = ReadBits(&reader, 6);
166 RCHECK(frame_size_code < 38); // Undefined.
167
168 // Verify bsid.
169 RCHECK(ReadBits(&reader, 5) < 10); // Normally 8 or 6, 16 used by EAC3.
170
171 offset += kAc3FrameSizeTable[frame_size_code][sample_rate_code];
172 }
173 return true;
174}
175
176// Checks for an EAC3 container (very similar to AC3)
177static bool CheckEac3(const uint8_t* buffer, int buffer_size) {
178 // Reference: ATSC Standard: Digital Audio Compression (AC-3, E-AC-3)
179 // Doc. A/52:2012
180 // (http://www.atsc.org/cms/standards/A52-2012(12-17).pdf)
181
182 // EAC3 container looks like syncinfo | bsi | audfrm | audblk* | aux | check.
183 RCHECK(buffer_size > 6);
184
185 int offset = 0;
186 while (offset + 6 < buffer_size) {
187 BitReader reader(buffer + offset, 6);
188
189 // Check syncinfo.
190 RCHECK(ReadBits(&reader, 16) == kAc3SyncWord);
191
192 // Verify strmtyp.
193 RCHECK(ReadBits(&reader, 2) != 3);
194
195 // Skip substreamid.
196 reader.SkipBits(3);
197
198 // Get frmsize. Include syncinfo size and convert to bytes.
199 int frame_size = (ReadBits(&reader, 11) + 1) * 2;
200 RCHECK(frame_size >= 7);
201
202 // Skip fscod, fscod2, acmod, and lfeon.
203 reader.SkipBits(2 + 2 + 3 + 1);
204
205 // Verify bsid.
206 int bit_stream_id = ReadBits(&reader, 5);
207 RCHECK(bit_stream_id >= 11 && bit_stream_id <= 16);
208
209 offset += frame_size;
210 }
211 return true;
212}
213
214// Additional checks for a BINK container.
215static bool CheckBink(const uint8_t* buffer, int buffer_size) {
216 // Reference: http://wiki.multimedia.cx/index.php?title=Bink_Container
217 RCHECK(buffer_size >= 44);
218
219 // Verify number of frames specified.
220 RCHECK(Read32LE(buffer + 8) > 0);
221
222 // Verify width in range.
223 int width = Read32LE(buffer + 20);
224 RCHECK(width > 0 && width <= 32767);
225
226 // Verify height in range.
227 int height = Read32LE(buffer + 24);
228 RCHECK(height > 0 && height <= 32767);
229
230 // Verify frames per second specified.
231 RCHECK(Read32LE(buffer + 28) > 0);
232
233 // Verify video frames per second specified.
234 RCHECK(Read32LE(buffer + 32) > 0);
235
236 // Number of audio tracks must be 256 or less.
237 return (Read32LE(buffer + 40) <= 256);
238}
239
240// Additional checks for a CAF container.
241static bool CheckCaf(const uint8_t* buffer, int buffer_size) {
242 // Reference: Apple Core Audio Format Specification 1.0
243 // (https://developer.apple.com/library/mac/#documentation/MusicAudio/Reference/CAFSpec/CAF_spec/CAF_spec.html)
244 RCHECK(buffer_size >= 52);
245 BitReader reader(buffer, buffer_size);
246
247 // mFileType should be "caff".
248 RCHECK(ReadBits(&reader, 32) == TAG('c', 'a', 'f', 'f'));
249
250 // mFileVersion should be 1.
251 RCHECK(ReadBits(&reader, 16) == 1);
252
253 // Skip mFileFlags.
254 reader.SkipBits(16);
255
256 // First chunk should be Audio Description chunk, size 32l.
257 RCHECK(ReadBits(&reader, 32) == TAG('d', 'e', 's', 'c'));
258 RCHECK(ReadBits(&reader, 64) == 32);
259
260 // CAFAudioFormat.mSampleRate(float64) not 0
261 RCHECK(ReadBits(&reader, 64) != 0);
262
263 // CAFAudioFormat.mFormatID not 0
264 RCHECK(ReadBits(&reader, 32) != 0);
265
266 // Skip CAFAudioFormat.mBytesPerPacket and mFramesPerPacket.
267 reader.SkipBits(32 + 32);
268
269 // CAFAudioFormat.mChannelsPerFrame not 0
270 RCHECK(ReadBits(&reader, 32) != 0);
271 return true;
272}
273
274static bool kSamplingFrequencyValid[16] = {
275 false, true, true, true, false, false, true, true,
276 true, false, false, true, true, true, false, false};
277static bool kExtAudioIdValid[8] = {true, false, true, false,
278 false, false, true, false};
279
280// Additional checks for a DTS container.
281static bool CheckDts(const uint8_t* buffer, int buffer_size) {
282 // Reference: ETSI TS 102 114 V1.3.1 (2011-08)
283 // (http://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.03.01_60/ts_102114v010301p.pdf)
284 RCHECK(buffer_size > 11);
285
286 int offset = 0;
287 while (offset + 11 < buffer_size) {
288 BitReader reader(buffer + offset, 11);
289
290 // Verify sync word.
291 RCHECK(ReadBits(&reader, 32) == 0x7ffe8001);
292
293 // Skip frame type and deficit sample count.
294 reader.SkipBits(1 + 5);
295
296 // Verify CRC present flag.
297 RCHECK(ReadBits(&reader, 1) == 0); // CPF must be 0.
298
299 // Verify number of PCM sample blocks.
300 RCHECK(ReadBits(&reader, 7) >= 5);
301
302 // Verify primary frame byte size.
303 int frame_size = ReadBits(&reader, 14);
304 RCHECK(frame_size >= 95);
305
306 // Skip audio channel arrangement.
307 reader.SkipBits(6);
308
309 // Verify core audio sampling frequency is an allowed value.
310 RCHECK(kSamplingFrequencyValid[ReadBits(&reader, 4)]);
311
312 // Verify transmission bit rate is valid.
313 RCHECK(ReadBits(&reader, 5) <= 25);
314
315 // Verify reserved field is 0.
316 RCHECK(ReadBits(&reader, 1) == 0);
317
318 // Skip dynamic range flag, time stamp flag, auxiliary data flag, and HDCD.
319 reader.SkipBits(1 + 1 + 1 + 1);
320
321 // Verify extension audio descriptor flag is an allowed value.
322 RCHECK(kExtAudioIdValid[ReadBits(&reader, 3)]);
323
324 // Skip extended coding flag and audio sync word insertion flag.
325 reader.SkipBits(1 + 1);
326
327 // Verify low frequency effects flag is an allowed value.
328 RCHECK(ReadBits(&reader, 2) != 3);
329
330 offset += frame_size + 1;
331 }
332 return true;
333}
334
335// Checks for a DV container.
336static bool CheckDV(const uint8_t* buffer, int buffer_size) {
337 // Reference: SMPTE 314M (Annex A has differences with IEC 61834).
338 // (http://standards.smpte.org/content/978-1-61482-454-1/st-314-2005/SEC1.body.pdf)
339 RCHECK(buffer_size > 11);
340
341 int offset = 0;
342 int current_sequence_number = -1;
343 int last_block_number[6];
344 while (offset + 11 < buffer_size) {
345 BitReader reader(buffer + offset, 11);
346
347 // Decode ID data. Sections 5, 6, and 7 are reserved.
348 int section = ReadBits(&reader, 3);
349 RCHECK(section < 5);
350
351 // Next bit must be 1.
352 RCHECK(ReadBits(&reader, 1) == 1);
353
354 // Skip arbitrary bits.
355 reader.SkipBits(4);
356
357 int sequence_number = ReadBits(&reader, 4);
358
359 // Skip FSC.
360 reader.SkipBits(1);
361
362 // Next 3 bits must be 1.
363 RCHECK(ReadBits(&reader, 3) == 7);
364
365 int block_number = ReadBits(&reader, 8);
366
367 if (section == 0) { // Header.
368 // Validate the reserved bits in the next 8 bytes.
369 reader.SkipBits(1);
370 RCHECK(ReadBits(&reader, 1) == 0);
371 RCHECK(ReadBits(&reader, 11) == 0x7ff);
372 reader.SkipBits(4);
373 RCHECK(ReadBits(&reader, 4) == 0xf);
374 reader.SkipBits(4);
375 RCHECK(ReadBits(&reader, 4) == 0xf);
376 reader.SkipBits(4);
377 RCHECK(ReadBits(&reader, 4) == 0xf);
378 reader.SkipBits(3);
379 RCHECK(ReadBits(&reader, 24) == 0xffffff);
380 current_sequence_number = sequence_number;
381 for (size_t i = 0; i < std::size(last_block_number); ++i)
382 last_block_number[i] = -1;
383 } else {
384 // Sequence number must match (this will also fail if no header seen).
385 RCHECK(sequence_number == current_sequence_number);
386 // Block number should be increasing.
387 RCHECK(block_number > last_block_number[section]);
388 last_block_number[section] = block_number;
389 }
390
391 // Move to next block.
392 offset += 80;
393 }
394 return true;
395}
396
397// Checks for a GSM container.
398static bool CheckGsm(const uint8_t* buffer, int buffer_size) {
399 // Reference: ETSI EN 300 961 V8.1.1
400 // (http://www.etsi.org/deliver/etsi_en/300900_300999/300961/08.01.01_60/en_300961v080101p.pdf)
401 // also http://tools.ietf.org/html/rfc3551#page-24
402 // GSM files have a 33 byte block, only first 4 bits are fixed.
403 RCHECK(buffer_size >= 1024); // Need enough data to do a decent check.
404
405 int offset = 0;
406 while (offset < buffer_size) {
407 // First 4 bits of each block are xD.
408 RCHECK((buffer[offset] & 0xf0) == 0xd0);
409 offset += 33;
410 }
411 return true;
412}
413
414// Advance to the first set of |num_bits| bits that match |start_code|. |offset|
415// is the current location in the buffer, and is updated. |bytes_needed| is the
416// number of bytes that must remain in the buffer when |start_code| is found.
417// Returns true if start_code found (and enough space in the buffer after it),
418// false otherwise.
419static bool AdvanceToStartCode(const uint8_t* buffer,
420 int buffer_size,
421 int* offset,
422 int bytes_needed,
423 int num_bits,
424 uint32_t start_code) {
425 DCHECK_GE(bytes_needed, 3);
426 DCHECK_LE(num_bits, 24); // Only supports up to 24 bits.
427
428 // Create a mask to isolate |num_bits| bits, once shifted over.
429 uint32_t bits_to_shift = 24 - num_bits;
430 uint32_t mask = (1 << num_bits) - 1;
431 while (*offset + bytes_needed < buffer_size) {
432 uint32_t next = Read24(buffer + *offset);
433 if (((next >> bits_to_shift) & mask) == start_code)
434 return true;
435 ++(*offset);
436 }
437 return false;
438}
439
440// Checks for an H.261 container.
441static bool CheckH261(const uint8_t* buffer, int buffer_size) {
442 // Reference: ITU-T Recommendation H.261 (03/1993)
443 // (http://www.itu.int/rec/T-REC-H.261-199303-I/en)
444 RCHECK(buffer_size > 16);
445
446 int offset = 0;
447 bool seen_start_code = false;
448 while (true) {
449 // Advance to picture_start_code, if there is one.
450 if (!AdvanceToStartCode(buffer, buffer_size, &offset, 4, 20, 0x10)) {
451 // No start code found (or off end of buffer), so success if
452 // there was at least one valid header.
453 return seen_start_code;
454 }
455
456 // Now verify the block. AdvanceToStartCode() made sure that there are
457 // at least 4 bytes remaining in the buffer.
458 BitReader reader(buffer + offset, buffer_size - offset);
459 RCHECK(ReadBits(&reader, 20) == 0x10);
460
461 // Skip the temporal reference and PTYPE.
462 reader.SkipBits(5 + 6);
463
464 // Skip any extra insertion information. Since this is open-ended, if we run
465 // out of bits assume that the buffer is correctly formatted.
466 int extra = ReadBits(&reader, 1);
467 while (extra == 1) {
468 if (!reader.SkipBits(8))
469 return seen_start_code;
470 if (!reader.ReadBits(1, &extra))
471 return seen_start_code;
472 }
473
474 // Next should be a Group of Blocks start code. Again, if we run out of
475 // bits, then assume that the buffer up to here is correct, and the buffer
476 // just happened to end in the middle of a header.
477 int next;
478 if (!reader.ReadBits(16, &next))
479 return seen_start_code;
480 RCHECK(next == 1);
481
482 // Move to the next block.
483 seen_start_code = true;
484 offset += 4;
485 }
486}
487
488// Checks for an H.263 container.
489static bool CheckH263(const uint8_t* buffer, int buffer_size) {
490 // Reference: ITU-T Recommendation H.263 (01/2005)
491 // (http://www.itu.int/rec/T-REC-H.263-200501-I/en)
492 // header is PSC(22b) + TR(8b) + PTYPE(8+b).
493 RCHECK(buffer_size > 16);
494
495 int offset = 0;
496 bool seen_start_code = false;
497 while (true) {
498 // Advance to picture_start_code, if there is one.
499 if (!AdvanceToStartCode(buffer, buffer_size, &offset, 9, 22, 0x20)) {
500 // No start code found (or off end of buffer), so success if
501 // there was at least one valid header.
502 return seen_start_code;
503 }
504
505 // Now verify the block. AdvanceToStartCode() made sure that there are
506 // at least 9 bytes remaining in the buffer.
507 BitReader reader(buffer + offset, 9);
508 RCHECK(ReadBits(&reader, 22) == 0x20);
509
510 // Skip the temporal reference.
511 reader.SkipBits(8);
512
513 // Verify that the first 2 bits of PTYPE are 10b.
514 RCHECK(ReadBits(&reader, 2) == 2);
515
516 // Skip the split screen indicator, document camera indicator, and full
517 // picture freeze release.
518 reader.SkipBits(1 + 1 + 1);
519
520 // Verify Source Format.
521 int format = ReadBits(&reader, 3);
522 RCHECK(format != 0 && format != 6); // Forbidden or reserved.
523
524 if (format == 7) {
525 // Verify full extended PTYPE.
526 int ufep = ReadBits(&reader, 3);
527 if (ufep == 1) {
528 // Verify the optional part of PLUSPTYPE.
529 format = ReadBits(&reader, 3);
530 RCHECK(format != 0 && format != 7); // Reserved.
531 reader.SkipBits(11);
532 // Next 4 bits should be b1000.
533 RCHECK(ReadBits(&reader, 4) == 8); // Not allowed.
534 } else {
535 RCHECK(ufep == 0); // Only 0 and 1 allowed.
536 }
537
538 // Verify picture type code is not a reserved value.
539 int picture_type_code = ReadBits(&reader, 3);
540 RCHECK(picture_type_code != 6 && picture_type_code != 7); // Reserved.
541
542 // Skip picture resampling mode, reduced resolution mode,
543 // and rounding type.
544 reader.SkipBits(1 + 1 + 1);
545
546 // Next 3 bits should be b001.
547 RCHECK(ReadBits(&reader, 3) == 1); // Not allowed.
548 }
549
550 // Move to the next block.
551 seen_start_code = true;
552 offset += 9;
553 }
554}
555
556// Checks for an H.264 container.
557static bool CheckH264(const uint8_t* buffer, int buffer_size) {
558 // Reference: ITU-T Recommendation H.264 (01/2012)
559 // (http://www.itu.int/rec/T-REC-H.264)
560 // Section B.1: Byte stream NAL unit syntax and semantics.
561 RCHECK(buffer_size > 4);
562
563 int offset = 0;
564 int parameter_count = 0;
565 while (true) {
566 // Advance to picture_start_code, if there is one.
567 if (!AdvanceToStartCode(buffer, buffer_size, &offset, 4, 24, 1)) {
568 // No start code found (or off end of buffer), so success if
569 // there was at least one valid header.
570 return parameter_count > 0;
571 }
572
573 // Now verify the block. AdvanceToStartCode() made sure that there are
574 // at least 4 bytes remaining in the buffer.
575 BitReader reader(buffer + offset, 4);
576 RCHECK(ReadBits(&reader, 24) == 1);
577
578 // Verify forbidden_zero_bit.
579 RCHECK(ReadBits(&reader, 1) == 0);
580
581 // Extract nal_ref_idc and nal_unit_type.
582 int nal_ref_idc = ReadBits(&reader, 2);
583 int nal_unit_type = ReadBits(&reader, 5);
584
585 switch (nal_unit_type) {
586 case 5: // Coded slice of an IDR picture.
587 RCHECK(nal_ref_idc != 0);
588 break;
589 case 6: // Supplemental enhancement information (SEI).
590 case 9: // Access unit delimiter.
591 case 10: // End of sequence.
592 case 11: // End of stream.
593 case 12: // Filler data.
594 RCHECK(nal_ref_idc == 0);
595 break;
596 case 7: // Sequence parameter set.
597 case 8: // Picture parameter set.
598 ++parameter_count;
599 break;
600 }
601
602 // Skip the current start_code_prefix and move to the next.
603 offset += 4;
604 }
605}
606
607static const char kHlsSignature[] = "#EXTM3U";
608static const char kHls1[] = "#EXT-X-STREAM-INF:";
609static const char kHls2[] = "#EXT-X-TARGETDURATION:";
610static const char kHls3[] = "#EXT-X-MEDIA-SEQUENCE:";
611
612// Additional checks for a HLS container.
613static bool CheckHls(const uint8_t* buffer, int buffer_size) {
614 // HLS is simply a play list used for Apple HTTP Live Streaming.
615 // Reference: Apple HTTP Live Streaming Overview
616 // (http://goo.gl/MIwxj)
617
618 if (StartsWith(buffer, buffer_size, kHlsSignature)) {
619 // Need to find "#EXT-X-STREAM-INF:", "#EXT-X-TARGETDURATION:", or
620 // "#EXT-X-MEDIA-SEQUENCE:" somewhere in the buffer. Other playlists (like
621 // WinAmp) only have additional lines with #EXTINF
622 // (http://en.wikipedia.org/wiki/M3U).
623 int offset = strlen(kHlsSignature);
624 while (offset < buffer_size) {
625 if (buffer[offset] == '#') {
626 if (StartsWith(buffer + offset, buffer_size - offset, kHls1) ||
627 StartsWith(buffer + offset, buffer_size - offset, kHls2) ||
628 StartsWith(buffer + offset, buffer_size - offset, kHls3)) {
629 return true;
630 }
631 }
632 ++offset;
633 }
634 }
635 return false;
636}
637
638// Checks for a MJPEG stream.
639static bool CheckMJpeg(const uint8_t* buffer, int buffer_size) {
640 // Reference: ISO/IEC 10918-1 : 1993(E), Annex B
641 // (http://www.w3.org/Graphics/JPEG/itu-t81.pdf)
642 RCHECK(buffer_size >= 16);
643
644 int offset = 0;
645 int last_restart = -1;
646 int num_codes = 0;
647 while (offset + 5 < buffer_size) {
648 // Marker codes are always a two byte code with the first byte xFF.
649 RCHECK(buffer[offset] == 0xff);
650 uint8_t code = buffer[offset + 1];
651 RCHECK(code >= 0xc0 || code == 1);
652
653 // Skip sequences of xFF.
654 if (code == 0xff) {
655 ++offset;
656 continue;
657 }
658
659 // Success if the next marker code is EOI (end of image)
660 if (code == 0xd9)
661 return true;
662
663 // Check remaining codes.
664 if (code == 0xd8 || code == 1) {
665 // SOI (start of image) / TEM (private use). No other data with header.
666 offset += 2;
667 } else if (code >= 0xd0 && code <= 0xd7) {
668 // RST (restart) codes must be in sequence. No other data with header.
669 int restart = code & 0x07;
670 if (last_restart >= 0)
671 RCHECK(restart == (last_restart + 1) % 8);
672 last_restart = restart;
673 offset += 2;
674 } else {
675 // All remaining marker codes are followed by a length of the header.
676 int length = Read16(buffer + offset + 2) + 2;
677
678 // Special handling of SOS (start of scan) marker since the entropy
679 // coded data follows the SOS. Any xFF byte in the data block must be
680 // followed by x00 in the data.
681 if (code == 0xda) {
682 int number_components = buffer[offset + 4];
683 RCHECK(length == 8 + 2 * number_components);
684
685 // Advance to the next marker.
686 offset += length;
687 while (offset + 2 < buffer_size) {
688 if (buffer[offset] == 0xff && buffer[offset + 1] != 0)
689 break;
690 ++offset;
691 }
692 } else {
693 // Skip over the marker data for the other marker codes.
694 offset += length;
695 }
696 }
697 ++num_codes;
698 }
699 return (num_codes > 1);
700}
701
702enum Mpeg2StartCodes { PROGRAM_END_CODE = 0xb9, PACK_START_CODE = 0xba };
703
704// Checks for a MPEG2 Program Stream.
705static bool CheckMpeg2ProgramStream(const uint8_t* buffer, int buffer_size) {
706 // Reference: ISO/IEC 13818-1 : 2000 (E) / ITU-T Rec. H.222.0 (2000 E).
707 RCHECK(buffer_size > 14);
708
709 int offset = 0;
710 while (offset + 14 < buffer_size) {
711 BitReader reader(buffer + offset, 14);
712
713 // Must start with pack_start_code.
714 RCHECK(ReadBits(&reader, 24) == 1);
715 RCHECK(ReadBits(&reader, 8) == PACK_START_CODE);
716
717 // Determine MPEG version (MPEG1 has b0010, while MPEG2 has b01).
718 int mpeg_version = ReadBits(&reader, 2);
719 if (mpeg_version == 0) {
720 // MPEG1, 10 byte header
721 // Validate rest of version code
722 RCHECK(ReadBits(&reader, 2) == 2);
723 } else {
724 RCHECK(mpeg_version == 1);
725 }
726
727 // Skip system_clock_reference_base [32..30].
728 reader.SkipBits(3);
729
730 // Verify marker bit.
731 RCHECK(ReadBits(&reader, 1) == 1);
732
733 // Skip system_clock_reference_base [29..15].
734 reader.SkipBits(15);
735
736 // Verify next marker bit.
737 RCHECK(ReadBits(&reader, 1) == 1);
738
739 // Skip system_clock_reference_base [14..0].
740 reader.SkipBits(15);
741
742 // Verify next marker bit.
743 RCHECK(ReadBits(&reader, 1) == 1);
744
745 if (mpeg_version == 0) {
746 // Verify second marker bit.
747 RCHECK(ReadBits(&reader, 1) == 1);
748
749 // Skip mux_rate.
750 reader.SkipBits(22);
751
752 // Verify next marker bit.
753 RCHECK(ReadBits(&reader, 1) == 1);
754
755 // Update offset to be after this header.
756 offset += 12;
757 } else {
758 // Must be MPEG2.
759 // Skip program_mux_rate.
760 reader.SkipBits(22);
761
762 // Verify pair of marker bits.
763 RCHECK(ReadBits(&reader, 2) == 3);
764
765 // Skip reserved.
766 reader.SkipBits(5);
767
768 // Update offset to be after this header.
769 int pack_stuffing_length = ReadBits(&reader, 3);
770 offset += 14 + pack_stuffing_length;
771 }
772
773 // Check for system headers and PES_packets.
774 while (offset + 6 < buffer_size && Read24(buffer + offset) == 1) {
775 // Next 8 bits determine stream type.
776 int stream_id = buffer[offset + 3];
777
778 // Some stream types are reserved and shouldn't occur.
779 if (mpeg_version == 0)
780 RCHECK(stream_id != 0xbc && stream_id < 0xf0);
781 else
782 RCHECK(stream_id != 0xfc && stream_id != 0xfd && stream_id != 0xfe);
783
784 // Some stream types are used for pack headers.
785 if (stream_id == PACK_START_CODE) // back to outer loop.
786 break;
787 if (stream_id == PROGRAM_END_CODE) // end of stream.
788 return true;
789
790 int pes_length = Read16(buffer + offset + 4);
791 RCHECK(pes_length > 0);
792 offset = offset + 6 + pes_length;
793 }
794 }
795 // Success as we are off the end of the buffer and liked everything
796 // in the buffer.
797 return true;
798}
799
800const uint8_t kMpeg2SyncWord = 0x47;
801
802// Checks for a MPEG2 Transport Stream.
803static bool CheckMpeg2TransportStream(const uint8_t* buffer, int buffer_size) {
804 // Spec: ISO/IEC 13818-1 : 2000 (E) / ITU-T Rec. H.222.0 (2000 E).
805 // Normal packet size is 188 bytes. However, some systems add various error
806 // correction data at the end, resulting in packet of length 192/204/208
807 // (https://en.wikipedia.org/wiki/MPEG_transport_stream). Determine the
808 // length with the first packet.
809 RCHECK(buffer_size >= 250); // Want more than 1 packet to check.
810
811 int offset = 0;
812 int packet_length = -1;
813 while (buffer[offset] != kMpeg2SyncWord && offset < 20) {
814 // Skip over any header in the first 20 bytes.
815 ++offset;
816 }
817
818 while (offset + 6 < buffer_size) {
819 BitReader reader(buffer + offset, 6);
820
821 // Must start with sync byte.
822 RCHECK(ReadBits(&reader, 8) == kMpeg2SyncWord);
823
824 // Skip transport_error_indicator, payload_unit_start_indicator, and
825 // transport_priority.
826 reader.SkipBits(1 + 1 + 1);
827
828 // Verify the pid is not a reserved value.
829 int pid = ReadBits(&reader, 13);
830 RCHECK(pid < 3 || pid > 15);
831
832 if (pid != 8191) { // More checks for non-stuffing packets
833 // Skip transport_scrambling_control.
834 reader.SkipBits(2);
835
836 // Adaptation_field_control can not be 0.
837 int adaptation_field_control = ReadBits(&reader, 2);
838 RCHECK(adaptation_field_control != 0);
839
840 // If there is an adaptation_field, verify it.
841 if (adaptation_field_control >= 2) {
842 // Skip continuity_counter.
843 reader.SkipBits(4);
844
845 // Get adaptation_field_length and verify it.
846 int adaptation_field_length = ReadBits(&reader, 8);
847 if (adaptation_field_control == 2)
848 RCHECK(adaptation_field_length == 183);
849 else
850 RCHECK(adaptation_field_length <= 182);
851 }
852 }
853
854 // Attempt to determine the packet length on the first packet.
855 if (packet_length < 0) {
856 if (buffer[offset + 188] == kMpeg2SyncWord)
857 packet_length = 188;
858 else if (buffer[offset + 192] == kMpeg2SyncWord)
859 packet_length = 192;
860 else if (buffer[offset + 204] == kMpeg2SyncWord)
861 packet_length = 204;
862 else
863 packet_length = 208;
864 }
865 offset += packet_length;
866 }
867 return true;
868}
869
870enum Mpeg4StartCodes {
871 VISUAL_OBJECT_SEQUENCE_START_CODE = 0xb0,
872 VISUAL_OBJECT_SEQUENCE_END_CODE = 0xb1,
873 VISUAL_OBJECT_START_CODE = 0xb5,
874 VOP_START_CODE = 0xb6
875};
876
877// Checks for a raw MPEG4 bitstream container.
878static bool CheckMpeg4BitStream(const uint8_t* buffer, int buffer_size) {
879 // Defined in ISO/IEC 14496-2:2001.
880 // However, no length ... simply scan for start code values.
881 // Note tags are very similar to H.264.
882 RCHECK(buffer_size > 4);
883
884 int offset = 0;
885 int sequence_start_count = 0;
886 int sequence_end_count = 0;
887 int visual_object_count = 0;
888 int vop_count = 0;
889 while (true) {
890 // Advance to start_code, if there is one.
891 if (!AdvanceToStartCode(buffer, buffer_size, &offset, 6, 24, 1)) {
892 // Not a complete sequence in memory, so return true if we've seen a
893 // visual_object_sequence_start_code and a visual_object_start_code.
894 return (sequence_start_count > 0 && visual_object_count > 0);
895 }
896
897 // Now verify the block. AdvanceToStartCode() made sure that there are
898 // at least 6 bytes remaining in the buffer.
899 BitReader reader(buffer + offset, 6);
900 RCHECK(ReadBits(&reader, 24) == 1);
901
902 int start_code = ReadBits(&reader, 8);
903 RCHECK(start_code < 0x30 || start_code > 0xaf); // 30..AF and
904 RCHECK(start_code < 0xb7 || start_code > 0xb9); // B7..B9 reserved
905
906 switch (start_code) {
907 case VISUAL_OBJECT_SEQUENCE_START_CODE: {
908 ++sequence_start_count;
909 // Verify profile in not one of many reserved values.
910 int profile = ReadBits(&reader, 8);
911 RCHECK(profile > 0);
912 RCHECK(profile < 0x04 || profile > 0x10);
913 RCHECK(profile < 0x13 || profile > 0x20);
914 RCHECK(profile < 0x23 || profile > 0x31);
915 RCHECK(profile < 0x35 || profile > 0x41);
916 RCHECK(profile < 0x43 || profile > 0x60);
917 RCHECK(profile < 0x65 || profile > 0x70);
918 RCHECK(profile < 0x73 || profile > 0x80);
919 RCHECK(profile < 0x83 || profile > 0x90);
920 RCHECK(profile < 0x95 || profile > 0xa0);
921 RCHECK(profile < 0xa4 || profile > 0xb0);
922 RCHECK(profile < 0xb5 || profile > 0xc0);
923 RCHECK(profile < 0xc3 || profile > 0xd0);
924 RCHECK(profile < 0xe4);
925 break;
926 }
927
928 case VISUAL_OBJECT_SEQUENCE_END_CODE:
929 RCHECK(++sequence_end_count == sequence_start_count);
930 break;
931
932 case VISUAL_OBJECT_START_CODE: {
933 ++visual_object_count;
934 if (ReadBits(&reader, 1) == 1) {
935 int visual_object_verid = ReadBits(&reader, 4);
936 RCHECK(visual_object_verid > 0 && visual_object_verid < 3);
937 RCHECK(ReadBits(&reader, 3) != 0);
938 }
939 int visual_object_type = ReadBits(&reader, 4);
940 RCHECK(visual_object_type > 0 && visual_object_type < 6);
941 break;
942 }
943
944 case VOP_START_CODE:
945 RCHECK(++vop_count <= visual_object_count);
946 break;
947 }
948 // Skip this block.
949 offset += 6;
950 }
951}
952
953// Additional checks for a MOV/QuickTime/MPEG4 container.
954static bool CheckMov(const uint8_t* buffer, int buffer_size) {
955 // Reference: ISO/IEC 14496-12:2005(E).
956 // (http://standards.iso.org/ittf/PubliclyAvailableStandards/c061988_ISO_IEC_14496-12_2012.zip)
957 RCHECK(buffer_size > 8);
958
959 int offset = 0;
960 int boxes_seen = 0;
961 while (offset + 8 < buffer_size) {
962 int atomsize = Read32(buffer + offset);
963 uint32_t atomtype = Read32(buffer + offset + 4);
964 // Only need to check for ones that are valid at the top level.
965 switch (atomtype) {
966 case TAG('f', 't', 'y', 'p'):
967 case TAG('p', 'd', 'i', 'n'):
968 case TAG('b', 'l', 'o', 'c'):
969 case TAG('m', 'o', 'o', 'v'):
970 case TAG('m', 'o', 'o', 'f'):
971 case TAG('m', 'f', 'r', 'a'):
972 case TAG('m', 'd', 'a', 't'):
973 case TAG('f', 'r', 'e', 'e'):
974 case TAG('s', 'k', 'i', 'p'):
975 case TAG('m', 'e', 't', 'a'):
976 case TAG('m', 'e', 'c', 'o'):
977 case TAG('s', 't', 'y', 'p'):
978 case TAG('s', 'i', 'd', 'x'):
979 case TAG('s', 's', 'i', 'x'):
980 case TAG('p', 'r', 'f', 't'):
981 case TAG('u', 'u', 'i', 'd'):
982 // Assumes that it is an iso-bmff file after seeing two known boxes.
983 // Note that it is correct only for our use cases as we support only
984 // a limited number of containers, and there is no other container
985 // has this behavior.
986 if (++boxes_seen >= 2)
987 return true;
988 break;
989 default:
990 // Ignore unrecognized box.
991 break;
992 }
993 if (atomsize == 1) {
994 // Indicates that the length is the next 64bits.
995 if (offset + 16 > buffer_size)
996 break;
997 if (Read32(buffer + offset + 8) != 0)
998 break; // Offset is way past buffer size.
999 atomsize = Read32(buffer + offset + 12);
1000 }
1001 if (atomsize <= 0)
1002 break; // Indicates the last atom or length too big.
1003 offset += atomsize;
1004 }
1005 return false;
1006}
1007
1008enum MPEGVersion { VERSION_25 = 0, VERSION_RESERVED, VERSION_2, VERSION_1 };
1009enum MPEGLayer { L_RESERVED = 0, LAYER_3, LAYER_2, LAYER_1 };
1010
1011static int kSampleRateTable[4][4] = {
1012 {11025, 12000, 8000, 0}, // v2.5
1013 {0, 0, 0, 0}, // not used
1014 {22050, 24000, 16000, 0}, // v2
1015 {44100, 48000, 32000, 0} // v1
1016};
1017
1018static int kBitRateTableV1L1[16] = {0, 32, 64, 96, 128, 160, 192, 224,
1019 256, 288, 320, 352, 384, 416, 448, 0};
1020static int kBitRateTableV1L2[16] = {0, 32, 48, 56, 64, 80, 96, 112,
1021 128, 160, 192, 224, 256, 320, 384, 0};
1022static int kBitRateTableV1L3[16] = {0, 32, 40, 48, 56, 64, 80, 96,
1023 112, 128, 160, 192, 224, 256, 320, 0};
1024static int kBitRateTableV2L1[16] = {0, 32, 48, 56, 64, 80, 96, 112,
1025 128, 144, 160, 176, 192, 224, 256, 0};
1026static int kBitRateTableV2L23[16] = {0, 8, 16, 24, 32, 40, 48, 56,
1027 64, 80, 96, 112, 128, 144, 160, 0};
1028
1029static bool ValidMpegAudioFrameHeader(const uint8_t* header,
1030 int header_size,
1031 int* framesize) {
1032 // Reference: http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm.
1033 DCHECK_GE(header_size, 4);
1034 *framesize = 0;
1035 BitReader reader(header, 4); // Header can only be 4 bytes long.
1036
1037 // Verify frame sync (11 bits) are all set.
1038 RCHECK(ReadBits(&reader, 11) == 0x7ff);
1039
1040 // Verify MPEG audio version id.
1041 int version = ReadBits(&reader, 2);
1042 RCHECK(version != 1); // Reserved.
1043
1044 // Verify layer.
1045 int layer = ReadBits(&reader, 2);
1046 RCHECK(layer != 0);
1047
1048 // Skip protection bit.
1049 reader.SkipBits(1);
1050
1051 // Verify bitrate index.
1052 int bitrate_index = ReadBits(&reader, 4);
1053 RCHECK(bitrate_index != 0xf);
1054
1055 // Verify sampling rate frequency index.
1056 int sampling_index = ReadBits(&reader, 2);
1057 RCHECK(sampling_index != 3);
1058
1059 // Get padding bit.
1060 int padding = ReadBits(&reader, 1);
1061
1062 // Frame size:
1063 // For Layer I files = (12 * BitRate / SampleRate + Padding) * 4
1064 // For others = 144 * BitRate / SampleRate + Padding
1065 // Unfortunately, BitRate and SampleRate are coded.
1066 int sampling_rate = kSampleRateTable[version][sampling_index];
1067 int bitrate;
1068 if (version == VERSION_1) {
1069 if (layer == LAYER_1)
1070 bitrate = kBitRateTableV1L1[bitrate_index];
1071 else if (layer == LAYER_2)
1072 bitrate = kBitRateTableV1L2[bitrate_index];
1073 else
1074 bitrate = kBitRateTableV1L3[bitrate_index];
1075 } else {
1076 if (layer == LAYER_1)
1077 bitrate = kBitRateTableV2L1[bitrate_index];
1078 else
1079 bitrate = kBitRateTableV2L23[bitrate_index];
1080 }
1081 if (layer == LAYER_1)
1082 *framesize = ((12000 * bitrate) / sampling_rate + padding) * 4;
1083 else
1084 *framesize = (144000 * bitrate) / sampling_rate + padding;
1085 return (bitrate > 0 && sampling_rate > 0);
1086}
1087
1088// Extract a size encoded the MP3 way.
1089static int GetMp3HeaderSize(const uint8_t* buffer, int buffer_size) {
1090 DCHECK_GE(buffer_size, 9);
1091 int size = ((buffer[6] & 0x7f) << 21) + ((buffer[7] & 0x7f) << 14) +
1092 ((buffer[8] & 0x7f) << 7) + (buffer[9] & 0x7f) + 10;
1093 if (buffer[5] & 0x10) // Footer added?
1094 size += 10;
1095 return size;
1096}
1097
1098// Additional checks for a MP3 container.
1099static bool CheckMp3(const uint8_t* buffer, int buffer_size, bool seenHeader) {
1100 RCHECK(buffer_size >= 10); // Must be enough to read the initial header.
1101
1102 int framesize;
1103 int numSeen = 0;
1104 int offset = 0;
1105 if (seenHeader) {
1106 offset = GetMp3HeaderSize(buffer, buffer_size);
1107 } else {
1108 // Skip over leading 0's.
1109 while (offset < buffer_size && buffer[offset] == 0)
1110 ++offset;
1111 }
1112
1113 while (offset + 3 < buffer_size) {
1114 RCHECK(ValidMpegAudioFrameHeader(buffer + offset, buffer_size - offset,
1115 &framesize));
1116
1117 // Have we seen enough valid headers?
1118 if (++numSeen > 10)
1119 return true;
1120 offset += framesize;
1121 }
1122 // Off the end of the buffer, return success if a few valid headers seen.
1123 return numSeen > 2;
1124}
1125
1126// Check that the next characters in |buffer| represent a number. The format
1127// accepted is optional whitespace followed by 1 or more digits. |max_digits|
1128// specifies the maximum number of digits to process. Returns true if a valid
1129// number is found, false otherwise.
1130static bool VerifyNumber(const uint8_t* buffer,
1131 int buffer_size,
1132 int* offset,
1133 int max_digits) {
1134 RCHECK(*offset < buffer_size);
1135
1136 // Skip over any leading space.
1137 while (isspace(buffer[*offset])) {
1138 ++(*offset);
1139 RCHECK(*offset < buffer_size);
1140 }
1141
1142 // Need to process up to max_digits digits.
1143 int numSeen = 0;
1144 while (--max_digits >= 0 && isdigit(buffer[*offset])) {
1145 ++numSeen;
1146 ++(*offset);
1147 if (*offset >= buffer_size)
1148 return true; // Out of space but seen a digit.
1149 }
1150
1151 // Success if at least one digit seen.
1152 return (numSeen > 0);
1153}
1154
1155// Check that the next character in |buffer| is one of |c1| or |c2|. |c2| is
1156// optional. Returns true if there is a match, false if no match or out of
1157// space.
1158static inline bool VerifyCharacters(const uint8_t* buffer,
1159 int buffer_size,
1160 int* offset,
1161 char c1,
1162 char c2) {
1163 RCHECK(*offset < buffer_size);
1164 char c = static_cast<char>(buffer[(*offset)++]);
1165 return (c == c1 || (c == c2 && c2 != 0));
1166}
1167
1168// Checks for a SRT container.
1169static bool CheckSrt(const uint8_t* buffer, int buffer_size) {
1170 // Reference: http://en.wikipedia.org/wiki/SubRip
1171 RCHECK(buffer_size > 20);
1172
1173 // First line should just be the subtitle sequence number.
1174 int offset = StartsWith(buffer, buffer_size, UTF8_BYTE_ORDER_MARK) ? 3 : 0;
1175 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 100));
1176 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, '\n', '\r'));
1177
1178 // Skip any additional \n\r.
1179 while (VerifyCharacters(buffer, buffer_size, &offset, '\n', '\r')) {
1180 }
1181 --offset; // Since VerifyCharacters() gobbled up the next non-CR/LF.
1182
1183 // Second line should look like the following:
1184 // 00:00:10,500 --> 00:00:13,000
1185 // Units separator can be , or .
1186 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 100));
1187 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ':', 0));
1188 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 2));
1189 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ':', 0));
1190 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 2));
1191 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ',', '.'));
1192 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 3));
1193 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ' ', 0));
1194 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, '-', 0));
1195 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, '-', 0));
1196 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, '>', 0));
1197 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ' ', 0));
1198 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 100));
1199 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ':', 0));
1200 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 2));
1201 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ':', 0));
1202 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 2));
1203 RCHECK(VerifyCharacters(buffer, buffer_size, &offset, ',', '.'));
1204 RCHECK(VerifyNumber(buffer, buffer_size, &offset, 3));
1205 return true;
1206}
1207
1208// Read a Matroska Element Id.
1209static int GetElementId(BitReader* reader) {
1210 // Element ID is coded with the leading zero bits (max 3) determining size.
1211 // If it is an invalid encoding or the end of the buffer is reached,
1212 // return -1 as a tag that won't be expected.
1213 if (reader->bits_available() >= 8) {
1214 int num_bits_to_read = 0;
1215 static int prefix[] = {0x80, 0x4000, 0x200000, 0x10000000};
1216 for (int i = 0; i < 4; ++i) {
1217 num_bits_to_read += 7;
1218 if (ReadBits(reader, 1) == 1) {
1219 if (static_cast<int>(reader->bits_available()) < num_bits_to_read)
1220 break;
1221 // prefix[] adds back the bits read individually.
1222 return ReadBits(reader, num_bits_to_read) | prefix[i];
1223 }
1224 }
1225 }
1226 // Invalid encoding, return something not expected.
1227 return -1;
1228}
1229
1230// Read a Matroska Unsigned Integer (VINT).
1231static uint64_t GetVint(BitReader* reader) {
1232 // Values are coded with the leading zero bits (max 7) determining size.
1233 // If it is an invalid coding or the end of the buffer is reached,
1234 // return something that will go off the end of the buffer.
1235 if (reader->bits_available() >= 8) {
1236 int num_bits_to_read = 0;
1237 for (int i = 0; i < 8; ++i) {
1238 num_bits_to_read += 7;
1239 if (ReadBits(reader, 1) == 1) {
1240 if (static_cast<int>(reader->bits_available()) < num_bits_to_read)
1241 break;
1242 return ReadBits(reader, num_bits_to_read);
1243 }
1244 }
1245 }
1246 // Incorrect format (more than 7 leading 0's) or off the end of the buffer.
1247 // Since the return value is used as a byte size, return a value that will
1248 // cause a failure when used.
1249 return (reader->bits_available() / 8) + 2;
1250}
1251
1252// Additional checks for a WEBM container.
1253static bool CheckWebm(const uint8_t* buffer, int buffer_size) {
1254 // Reference: http://www.matroska.org/technical/specs/index.html
1255 RCHECK(buffer_size > 12);
1256
1257 BitReader reader(buffer, buffer_size);
1258
1259 // Verify starting Element Id.
1260 RCHECK(GetElementId(&reader) == 0x1a45dfa3);
1261
1262 // Get the header size, and ensure there are enough bits to check.
1263 int header_size = GetVint(&reader);
1264 RCHECK(static_cast<int>(reader.bits_available()) / 8 >= header_size);
1265
1266 // Loop through the header.
1267 while (reader.bits_available() > 0) {
1268 int tag = GetElementId(&reader);
1269 int tagsize = GetVint(&reader);
1270 switch (tag) {
1271 case 0x4286: // EBMLVersion
1272 case 0x42f7: // EBMLReadVersion
1273 case 0x42f2: // EBMLMaxIdLength
1274 case 0x42f3: // EBMLMaxSizeLength
1275 case 0x4287: // DocTypeVersion
1276 case 0x4285: // DocTypeReadVersion
1277 case 0xec: // void
1278 case 0xbf: // CRC32
1279 RCHECK(reader.SkipBits(tagsize * 8));
1280 break;
1281
1282 case 0x4282: // EBMLDocType
1283 // Need to see "webm" or "matroska" next.
1284 switch (ReadBits(&reader, 32)) {
1285 case TAG('w', 'e', 'b', 'm'):
1286 return true;
1287 case TAG('m', 'a', 't', 'r'):
1288 return (ReadBits(&reader, 32) == TAG('o', 's', 'k', 'a'));
1289 }
1290 return false;
1291
1292 default: // Unrecognized tag
1293 return false;
1294 }
1295 }
1296 return false;
1297}
1298
1299enum VC1StartCodes {
1300 VC1_FRAME_START_CODE = 0x0d,
1301 VC1_ENTRY_POINT_START_CODE = 0x0e,
1302 VC1_SEQUENCE_START_CODE = 0x0f
1303};
1304
1305// Checks for a VC1 bitstream container.
1306static bool CheckVC1(const uint8_t* buffer, int buffer_size) {
1307 // Reference: SMPTE 421M
1308 // (http://standards.smpte.org/content/978-1-61482-555-5/st-421-2006/SEC1.body.pdf)
1309 // However, no length ... simply scan for start code values.
1310 // Expect to see SEQ | [ [ ENTRY ] PIC* ]*
1311 // Note tags are very similar to H.264.
1312
1313 RCHECK(buffer_size >= 24);
1314
1315 // First check for Bitstream Metadata Serialization (Annex L)
1316 if (buffer[0] == 0xc5 && Read32(buffer + 4) == 0x04 &&
1317 Read32(buffer + 20) == 0x0c) {
1318 // Verify settings in STRUCT_C and STRUCT_A
1319 BitReader reader(buffer + 8, 12);
1320
1321 int profile = ReadBits(&reader, 4);
1322 if (profile == 0 || profile == 4) { // simple or main
1323 // Skip FRMRTQ_POSTPROC, BITRTQ_POSTPROC, and LOOPFILTER.
1324 reader.SkipBits(3 + 5 + 1);
1325
1326 // Next bit must be 0.
1327 RCHECK(ReadBits(&reader, 1) == 0);
1328
1329 // Skip MULTIRES.
1330 reader.SkipBits(1);
1331
1332 // Next bit must be 1.
1333 RCHECK(ReadBits(&reader, 1) == 1);
1334
1335 // Skip FASTUVMC, EXTENDED_MV, DQUANT, and VSTRANSFORM.
1336 reader.SkipBits(1 + 1 + 2 + 1);
1337
1338 // Next bit must be 0.
1339 RCHECK(ReadBits(&reader, 1) == 0);
1340
1341 // Skip OVERLAP, SYNCMARKER, RANGERED, MAXBFRAMES, QUANTIZER, and
1342 // FINTERPFLAG.
1343 reader.SkipBits(1 + 1 + 1 + 3 + 2 + 1);
1344
1345 // Next bit must be 1.
1346 RCHECK(ReadBits(&reader, 1) == 1);
1347
1348 } else {
1349 RCHECK(profile == 12); // Other profile values not allowed.
1350 RCHECK(ReadBits(&reader, 28) == 0);
1351 }
1352
1353 // Now check HORIZ_SIZE and VERT_SIZE, which must be 8192 or less.
1354 RCHECK(ReadBits(&reader, 32) <= 8192);
1355 RCHECK(ReadBits(&reader, 32) <= 8192);
1356 return true;
1357 }
1358
1359 // Buffer isn't Bitstream Metadata, so scan for start codes.
1360 int offset = 0;
1361 int sequence_start_code = 0;
1362 int frame_start_code = 0;
1363 while (true) {
1364 // Advance to start_code, if there is one.
1365 if (!AdvanceToStartCode(buffer, buffer_size, &offset, 5, 24, 1)) {
1366 // Not a complete sequence in memory, so return true if we've seen a
1367 // sequence start and a frame start (not checking entry points since
1368 // they only occur in advanced profiles).
1369 return (sequence_start_code > 0 && frame_start_code > 0);
1370 }
1371
1372 // Now verify the block. AdvanceToStartCode() made sure that there are
1373 // at least 5 bytes remaining in the buffer.
1374 BitReader reader(buffer + offset, 5);
1375 RCHECK(ReadBits(&reader, 24) == 1);
1376
1377 // Keep track of the number of certain types received.
1378 switch (ReadBits(&reader, 8)) {
1379 case VC1_SEQUENCE_START_CODE: {
1380 ++sequence_start_code;
1381 switch (ReadBits(&reader, 2)) {
1382 case 0: // simple
1383 case 1: // main
1384 RCHECK(ReadBits(&reader, 2) == 0);
1385 break;
1386 case 2: // complex
1387 return false;
1388 case 3: // advanced
1389 RCHECK(ReadBits(&reader, 3) <= 4); // Verify level = 0..4
1390 RCHECK(ReadBits(&reader, 2) == 1); // Verify colordiff_format = 1
1391 break;
1392 }
1393 break;
1394 }
1395
1396 case VC1_ENTRY_POINT_START_CODE:
1397 // No fields in entry data to check. However, it must occur after
1398 // sequence header.
1399 RCHECK(sequence_start_code > 0);
1400 break;
1401
1402 case VC1_FRAME_START_CODE:
1403 ++frame_start_code;
1404 break;
1405 }
1406 offset += 5;
1407 }
1408}
1409
1410// For some formats the signature is a bunch of characters. They are defined
1411// below. Note that the first 4 characters of the string may be used as a TAG
1412// in LookupContainerByFirst4. For signatures that contain embedded \0, use
1413// uint8_t[].
1414static const char kAmrSignature[] = "#!AMR";
1415static const uint8_t kAsfSignature[] = {0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66,
1416 0xcf, 0x11, 0xa6, 0xd9, 0x00, 0xaa,
1417 0x00, 0x62, 0xce, 0x6c};
1418static const char kAssSignature[] = "[Script Info]";
1419static const char kAssBomSignature[] = UTF8_BYTE_ORDER_MARK "[Script Info]";
1420static const uint8_t kWtvSignature[] = {0xb7, 0xd8, 0x00, 0x20, 0x37, 0x49,
1421 0xda, 0x11, 0xa6, 0x4e, 0x00, 0x07,
1422 0xe9, 0x5e, 0xad, 0x8d};
1423
1424// Attempt to determine the container type from the buffer provided. This is
1425// a simple pass, that uses the first 4 bytes of the buffer as an index to get
1426// a rough idea of the container format.
1427static MediaContainerName LookupContainerByFirst4(const uint8_t* buffer,
1428 int buffer_size) {
1429 // Minimum size that the code expects to exist without checking size.
1430 if (buffer_size < 12)
1431 return CONTAINER_UNKNOWN;
1432
1433 uint32_t first4 = Read32(buffer);
1434 switch (first4) {
1435 case 0x1a45dfa3:
1436 if (CheckWebm(buffer, buffer_size))
1437 return CONTAINER_WEBM;
1438 break;
1439
1440 case 0x3026b275:
1441 if (StartsWith(buffer, buffer_size, kAsfSignature,
1442 sizeof(kAsfSignature))) {
1443 return CONTAINER_ASF;
1444 }
1445 break;
1446
1447 case TAG('#', '!', 'A', 'M'):
1448 if (StartsWith(buffer, buffer_size, kAmrSignature))
1449 return CONTAINER_AMR;
1450 break;
1451
1452 case TAG('#', 'E', 'X', 'T'):
1453 if (CheckHls(buffer, buffer_size))
1454 return CONTAINER_HLS;
1455 break;
1456
1457 case TAG('.', 'R', 'M', 'F'):
1458 if (buffer[4] == 0 && buffer[5] == 0)
1459 return CONTAINER_RM;
1460 break;
1461
1462 case TAG('.', 'r', 'a', '\xfd'):
1463 return CONTAINER_RM;
1464
1465 case TAG('B', 'I', 'K', 'b'):
1466 case TAG('B', 'I', 'K', 'd'):
1467 case TAG('B', 'I', 'K', 'f'):
1468 case TAG('B', 'I', 'K', 'g'):
1469 case TAG('B', 'I', 'K', 'h'):
1470 case TAG('B', 'I', 'K', 'i'):
1471 if (CheckBink(buffer, buffer_size))
1472 return CONTAINER_BINK;
1473 break;
1474
1475 case TAG('c', 'a', 'f', 'f'):
1476 if (CheckCaf(buffer, buffer_size))
1477 return CONTAINER_CAF;
1478 break;
1479
1480 case TAG('D', 'E', 'X', 'A'):
1481 if (buffer_size > 15 && Read16(buffer + 11) <= 2048 &&
1482 Read16(buffer + 13) <= 2048) {
1483 return CONTAINER_DXA;
1484 }
1485 break;
1486
1487 case TAG('D', 'T', 'S', 'H'):
1488 if (Read32(buffer + 4) == TAG('D', 'H', 'D', 'R'))
1489 return CONTAINER_DTSHD;
1490 break;
1491
1492 case 0x64a30100:
1493 case 0x64a30200:
1494 case 0x64a30300:
1495 case 0x64a30400:
1496 case 0x0001a364:
1497 case 0x0002a364:
1498 case 0x0003a364:
1499 if (Read32(buffer + 4) != 0 && Read32(buffer + 8) != 0)
1500 return CONTAINER_IRCAM;
1501 break;
1502
1503 case TAG('f', 'L', 'a', 'C'):
1504 return CONTAINER_FLAC;
1505
1506 case TAG('F', 'L', 'V', 0):
1507 case TAG('F', 'L', 'V', 1):
1508 case TAG('F', 'L', 'V', 2):
1509 case TAG('F', 'L', 'V', 3):
1510 case TAG('F', 'L', 'V', 4):
1511 if (buffer[5] == 0 && Read32(buffer + 5) > 8)
1512 return CONTAINER_FLV;
1513 break;
1514
1515 case TAG('F', 'O', 'R', 'M'):
1516 switch (Read32(buffer + 8)) {
1517 case TAG('A', 'I', 'F', 'F'):
1518 case TAG('A', 'I', 'F', 'C'):
1519 return CONTAINER_AIFF;
1520 }
1521 break;
1522
1523 case TAG('M', 'A', 'C', ' '):
1524 return CONTAINER_APE;
1525
1526 case TAG('O', 'N', '2', ' '):
1527 if (Read32(buffer + 8) == TAG('O', 'N', '2', 'f'))
1528 return CONTAINER_AVI;
1529 break;
1530
1531 case TAG('O', 'g', 'g', 'S'):
1532 if (buffer[5] <= 7)
1533 return CONTAINER_OGG;
1534 break;
1535
1536 case TAG('R', 'F', '6', '4'):
1537 if (buffer_size > 16 && Read32(buffer + 12) == TAG('d', 's', '6', '4'))
1538 return CONTAINER_WAV;
1539 break;
1540
1541 case TAG('R', 'I', 'F', 'F'):
1542 switch (Read32(buffer + 8)) {
1543 case TAG('A', 'V', 'I', ' '):
1544 case TAG('A', 'V', 'I', 'X'):
1545 case TAG('A', 'V', 'I', '\x19'):
1546 case TAG('A', 'M', 'V', ' '):
1547 return CONTAINER_AVI;
1548 case TAG('W', 'A', 'V', 'E'):
1549 return CONTAINER_WAV;
1550 }
1551 break;
1552
1553 case TAG('[', 'S', 'c', 'r'):
1554 if (StartsWith(buffer, buffer_size, kAssSignature))
1555 return CONTAINER_ASS;
1556 break;
1557
1558 case TAG('\xef', '\xbb', '\xbf', '['):
1559 if (StartsWith(buffer, buffer_size, kAssBomSignature))
1560 return CONTAINER_ASS;
1561 break;
1562
1563 case 0x7ffe8001:
1564 case 0xfe7f0180:
1565 case 0x1fffe800:
1566 case 0xff1f00e8:
1567 if (CheckDts(buffer, buffer_size))
1568 return CONTAINER_DTS;
1569 break;
1570
1571 case 0xb7d80020:
1572 if (StartsWith(buffer, buffer_size, kWtvSignature,
1573 sizeof(kWtvSignature))) {
1574 return CONTAINER_WTV;
1575 }
1576 break;
1577 case 0x000001ba:
1578 return CONTAINER_MPEG2PS;
1579 }
1580
1581 // Now try a few different ones that look at something other
1582 // than the first 4 bytes.
1583 uint32_t first3 = first4 & 0xffffff00;
1584 switch (first3) {
1585 case TAG('C', 'W', 'S', 0):
1586 case TAG('F', 'W', 'S', 0):
1587 return CONTAINER_SWF;
1588
1589 case TAG('I', 'D', '3', 0):
1590 if (CheckMp3(buffer, buffer_size, true))
1591 return CONTAINER_MP3;
1592 break;
1593 }
1594
1595 // Maybe the first 2 characters are something we can use.
1596 uint32_t first2 = Read16(buffer);
1597 switch (first2) {
1598 case kAc3SyncWord:
1599 if (CheckAc3(buffer, buffer_size))
1600 return CONTAINER_AC3;
1601 if (CheckEac3(buffer, buffer_size))
1602 return CONTAINER_EAC3;
1603 break;
1604
1605 case 0xfff0:
1606 case 0xfff1:
1607 case 0xfff8:
1608 case 0xfff9:
1609 if (CheckAac(buffer, buffer_size))
1610 return CONTAINER_AAC;
1611 break;
1612 }
1613
1614 // Check if the file is in MP3 format without the header.
1615 if (CheckMp3(buffer, buffer_size, false))
1616 return CONTAINER_MP3;
1617
1618 return CONTAINER_UNKNOWN;
1619}
1620
1621namespace {
1622const char kWebVtt[] = "WEBVTT";
1623
1624bool CheckWebVtt(const uint8_t* buffer, int buffer_size) {
1625 const int offset =
1626 StartsWith(buffer, buffer_size, UTF8_BYTE_ORDER_MARK) ? 3 : 0;
1627
1628 return StartsWith(buffer + offset, buffer_size - offset,
1629 reinterpret_cast<const uint8_t*>(kWebVtt),
1630 std::size(kWebVtt) - 1);
1631}
1632
1633bool CheckTtml(const uint8_t* buffer, int buffer_size) {
1634 // Sanity check first before reading the entire thing.
1635 if (!StartsWith(buffer, buffer_size, "<?xml"))
1636 return false;
1637
1638 // Make sure that it can be parsed so that it doesn't error later in the
1639 // process. Not doing a schema check to allow TTMLs that makes some sense but
1640 // not necessarily compliant to the schema.
1641 xml::scoped_xml_ptr<xmlDoc> doc(
1642 xmlParseMemory(reinterpret_cast<const char*>(buffer), buffer_size));
1643 if (!doc)
1644 return false;
1645
1646 xmlNodePtr root_node = xmlDocGetRootElement(doc.get());
1647 std::string root_node_name(reinterpret_cast<const char*>(root_node->name));
1648 // "tt" is supposed to be the top level element for ttml.
1649 return root_node_name == "tt";
1650}
1651
1652} // namespace
1653
1654// Attempt to determine the container name from the buffer provided.
1655MediaContainerName DetermineContainer(const uint8_t* buffer, int buffer_size) {
1656 DCHECK(buffer);
1657
1658 // Since MOV/QuickTime/MPEG4 streams are common, check for them first.
1659 if (CheckMov(buffer, buffer_size))
1660 return CONTAINER_MOV;
1661
1662 // Next attempt the simple checks, that typically look at just the
1663 // first few bytes of the file.
1664 MediaContainerName result = LookupContainerByFirst4(buffer, buffer_size);
1665 if (result != CONTAINER_UNKNOWN)
1666 return result;
1667
1668 // WebVTT check only checks for the first few bytes.
1669 if (CheckWebVtt(buffer, buffer_size))
1670 return CONTAINER_WEBVTT;
1671
1672 // Additional checks that may scan a portion of the buffer.
1673 if (CheckMpeg2ProgramStream(buffer, buffer_size))
1674 return CONTAINER_MPEG2PS;
1675 if (CheckMpeg2TransportStream(buffer, buffer_size))
1676 return CONTAINER_MPEG2TS;
1677 if (CheckMJpeg(buffer, buffer_size))
1678 return CONTAINER_MJPEG;
1679 if (CheckDV(buffer, buffer_size))
1680 return CONTAINER_DV;
1681 if (CheckH261(buffer, buffer_size))
1682 return CONTAINER_H261;
1683 if (CheckH263(buffer, buffer_size))
1684 return CONTAINER_H263;
1685 if (CheckH264(buffer, buffer_size))
1686 return CONTAINER_H264;
1687 if (CheckMpeg4BitStream(buffer, buffer_size))
1688 return CONTAINER_MPEG4BS;
1689 if (CheckVC1(buffer, buffer_size))
1690 return CONTAINER_VC1;
1691 if (CheckSrt(buffer, buffer_size))
1692 return CONTAINER_SRT;
1693 if (CheckGsm(buffer, buffer_size))
1694 return CONTAINER_GSM;
1695
1696 // AC3/EAC3 might not start at the beginning of the stream,
1697 // so scan for a start code.
1698 int offset = 1; // No need to start at byte 0 due to First4 check.
1699 if (AdvanceToStartCode(buffer, buffer_size, &offset, 4, 16, kAc3SyncWord)) {
1700 if (CheckAc3(buffer + offset, buffer_size - offset))
1701 return CONTAINER_AC3;
1702 if (CheckEac3(buffer + offset, buffer_size - offset))
1703 return CONTAINER_EAC3;
1704 }
1705
1706 // To do a TTML check, it parses the XML which requires scanning
1707 // the whole content.
1708 if (CheckTtml(buffer, buffer_size))
1709 return CONTAINER_TTML;
1710
1711 return CONTAINER_UNKNOWN;
1712}
1713
1714MediaContainerName DetermineContainerFromFormatName(
1715 const std::string& format_name) {
1716 std::string normalized_format_name = format_name;
1717 std::transform(format_name.begin(), format_name.end(),
1718 normalized_format_name.begin(), ::tolower);
1719
1720 if (normalized_format_name == "aac" || normalized_format_name == "adts") {
1721 return CONTAINER_AAC;
1722 } else if (normalized_format_name == "ac3") {
1723 return CONTAINER_AC3;
1724 } else if (normalized_format_name == "ec3" ||
1725 normalized_format_name == "eac3") {
1726 return CONTAINER_EAC3;
1727 } else if (normalized_format_name == "mp3") {
1728 return CONTAINER_MP3;
1729 } else if (normalized_format_name == "webm") {
1730 return CONTAINER_WEBM;
1731 } else if (normalized_format_name == "cmfa" ||
1732 normalized_format_name == "cmft" ||
1733 normalized_format_name == "cmfv" ||
1734 normalized_format_name == "m4a" ||
1735 normalized_format_name == "m4s" ||
1736 normalized_format_name == "m4v" ||
1737 normalized_format_name == "mov" ||
1738 normalized_format_name == "mp4" ||
1739 normalized_format_name == "ttml+mp4" ||
1740 normalized_format_name == "webvtt+mp4" ||
1741 normalized_format_name == "vtt+mp4") {
1742 return CONTAINER_MOV;
1743 } else if (normalized_format_name == "ts" ||
1744 normalized_format_name == "mpeg2ts") {
1745 return CONTAINER_MPEG2TS;
1746 } else if (normalized_format_name == "wvm") {
1747 return CONTAINER_WVM;
1748 } else if (normalized_format_name == "vtt" ||
1749 normalized_format_name == "webvtt") {
1750 return CONTAINER_WEBVTT;
1751 } else if (normalized_format_name == "ttml" ||
1752 // Treat xml as ttml.
1753 normalized_format_name == "xml") {
1754 return CONTAINER_TTML;
1755 }
1756 return CONTAINER_UNKNOWN;
1757}
1758
1759MediaContainerName DetermineContainerFromFileName(
1760 const std::string& file_name) {
1761 const size_t pos = file_name.rfind('.');
1762 if (pos == std::string::npos)
1763 return CONTAINER_UNKNOWN;
1764 const std::string& file_extension = file_name.substr(pos + 1);
1765 return DetermineContainerFromFormatName(file_extension);
1766}
1767
1768} // namespace media
1769} // namespace shaka
All the methods that are virtual are virtual for mocking.