Shaka Packager SDK
mp4_media_parser.cc
1 // Copyright (c) 2012 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/formats/mp4/mp4_media_parser.h"
6 
7 #include <algorithm>
8 
9 #include "packager/base/callback.h"
10 #include "packager/base/callback_helpers.h"
11 #include "packager/base/logging.h"
12 #include "packager/base/strings/string_number_conversions.h"
13 #include "packager/file/file.h"
14 #include "packager/file/file_closer.h"
15 #include "packager/media/base/audio_stream_info.h"
16 #include "packager/media/base/buffer_reader.h"
17 #include "packager/media/base/decrypt_config.h"
18 #include "packager/media/base/key_source.h"
19 #include "packager/media/base/macros.h"
20 #include "packager/media/base/media_sample.h"
21 #include "packager/media/base/rcheck.h"
22 #include "packager/media/base/video_stream_info.h"
23 #include "packager/media/base/video_util.h"
24 #include "packager/media/codecs/ac3_audio_util.h"
25 #include "packager/media/codecs/av1_codec_configuration_record.h"
26 #include "packager/media/codecs/avc_decoder_configuration_record.h"
27 #include "packager/media/codecs/dovi_decoder_configuration_record.h"
28 #include "packager/media/codecs/ec3_audio_util.h"
29 #include "packager/media/codecs/es_descriptor.h"
30 #include "packager/media/codecs/hevc_decoder_configuration_record.h"
31 #include "packager/media/codecs/vp_codec_configuration_record.h"
32 #include "packager/media/formats/mp4/box_definitions.h"
33 #include "packager/media/formats/mp4/box_reader.h"
34 #include "packager/media/formats/mp4/track_run_iterator.h"
35 
36 namespace shaka {
37 namespace media {
38 namespace mp4 {
39 namespace {
40 
41 uint64_t Rescale(uint64_t time_in_old_scale,
42  uint32_t old_scale,
43  uint32_t new_scale) {
44  return (static_cast<double>(time_in_old_scale) / old_scale) * new_scale;
45 }
46 
47 H26xStreamFormat GetH26xStreamFormat(FourCC fourcc) {
48  switch (fourcc) {
49  case FOURCC_avc1:
50  case FOURCC_dvh1:
51  case FOURCC_hvc1:
52  return H26xStreamFormat::kNalUnitStreamWithoutParameterSetNalus;
53  case FOURCC_avc3:
54  case FOURCC_dvhe:
55  case FOURCC_hev1:
56  return H26xStreamFormat::kNalUnitStreamWithParameterSetNalus;
57  default:
58  return H26xStreamFormat::kUnSpecified;
59  }
60 }
61 
62 Codec FourCCToCodec(FourCC fourcc) {
63  switch (fourcc) {
64  case FOURCC_av01:
65  return kCodecAV1;
66  case FOURCC_avc1:
67  case FOURCC_avc3:
68  return kCodecH264;
69  case FOURCC_dvh1:
70  case FOURCC_dvhe:
71  return kCodecH265DolbyVision;
72  case FOURCC_hev1:
73  case FOURCC_hvc1:
74  return kCodecH265;
75  case FOURCC_vp08:
76  return kCodecVP8;
77  case FOURCC_vp09:
78  return kCodecVP9;
79  case FOURCC_Opus:
80  return kCodecOpus;
81  case FOURCC_dtsc:
82  return kCodecDTSC;
83  case FOURCC_dtsh:
84  return kCodecDTSH;
85  case FOURCC_dtsl:
86  return kCodecDTSL;
87  case FOURCC_dtse:
88  return kCodecDTSE;
89  case FOURCC_dtsp:
90  return kCodecDTSP;
91  case FOURCC_dtsm:
92  return kCodecDTSM;
93  case FOURCC_ac_3:
94  return kCodecAC3;
95  case FOURCC_ec_3:
96  return kCodecEAC3;
97  case FOURCC_fLaC:
98  return kCodecFlac;
99  default:
100  return kUnknownCodec;
101  }
102 }
103 
104 Codec ObjectTypeToCodec(ObjectType object_type) {
105  switch (object_type) {
106  case ObjectType::kISO_14496_3:
107  case ObjectType::kISO_13818_7_AAC_LC:
108  return kCodecAAC;
109  case ObjectType::kDTSC:
110  return kCodecDTSC;
111  case ObjectType::kDTSE:
112  return kCodecDTSE;
113  case ObjectType::kDTSH:
114  return kCodecDTSH;
115  case ObjectType::kDTSL:
116  return kCodecDTSL;
117  default:
118  return kUnknownCodec;
119  }
120 }
121 
122 std::vector<uint8_t> GetDOVIDecoderConfig(
123  const std::vector<CodecConfiguration>& configs) {
124  for (const CodecConfiguration& config : configs) {
125  if (config.box_type == FOURCC_dvcC || config.box_type == FOURCC_dvvC) {
126  return config.data;
127  }
128  }
129  return std::vector<uint8_t>();
130 }
131 
132 bool UpdateCodecStringForDolbyVision(
133  FourCC actual_format,
134  const std::vector<CodecConfiguration>& configs,
135  std::string* codec_string) {
136  DOVIDecoderConfigurationRecord dovi_config;
137  if (!dovi_config.Parse(GetDOVIDecoderConfig(configs))) {
138  LOG(ERROR) << "Failed to parse Dolby Vision decoder "
139  "configuration record.";
140  return false;
141  }
142  if (actual_format == FOURCC_dvh1 || actual_format == FOURCC_dvhe) {
143  // Non-Backward compatibility mode. Replace the code string with
144  // Dolby Vision only.
145  *codec_string = dovi_config.GetCodecString(actual_format);
146  } else {
147  // TODO(kqyang): Support backward compatible signaling.
148  }
149  return true;
150 }
151 
152 const uint64_t kNanosecondsPerSecond = 1000000000ull;
153 
154 } // namespace
155 
156 MP4MediaParser::MP4MediaParser()
157  : state_(kWaitingForInit),
158  decryption_key_source_(NULL),
159  moof_head_(0),
160  mdat_tail_(0) {}
161 
162 MP4MediaParser::~MP4MediaParser() {}
163 
164 void MP4MediaParser::Init(const InitCB& init_cb,
165  const NewSampleCB& new_sample_cb,
166  KeySource* decryption_key_source) {
167  DCHECK_EQ(state_, kWaitingForInit);
168  DCHECK(init_cb_.is_null());
169  DCHECK(!init_cb.is_null());
170  DCHECK(!new_sample_cb.is_null());
171 
172  ChangeState(kParsingBoxes);
173  init_cb_ = init_cb;
174  new_sample_cb_ = new_sample_cb;
175  decryption_key_source_ = decryption_key_source;
176  if (decryption_key_source)
177  decryptor_source_.reset(new DecryptorSource(decryption_key_source));
178 }
179 
180 void MP4MediaParser::Reset() {
181  queue_.Reset();
182  runs_.reset();
183  moof_head_ = 0;
184  mdat_tail_ = 0;
185 }
186 
188  DCHECK_NE(state_, kWaitingForInit);
189  Reset();
190  ChangeState(kParsingBoxes);
191  return true;
192 }
193 
194 bool MP4MediaParser::Parse(const uint8_t* buf, int size) {
195  DCHECK_NE(state_, kWaitingForInit);
196 
197  if (state_ == kError)
198  return false;
199 
200  queue_.Push(buf, size);
201 
202  bool result, err = false;
203 
204  do {
205  if (state_ == kParsingBoxes) {
206  result = ParseBox(&err);
207  } else {
208  DCHECK_EQ(kEmittingSamples, state_);
209  result = EnqueueSample(&err);
210  if (result) {
211  int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
212  err = !ReadAndDiscardMDATsUntil(max_clear);
213  }
214  }
215  } while (result && !err);
216 
217  if (err) {
218  DLOG(ERROR) << "Error while parsing MP4";
219  moov_.reset();
220  Reset();
221  ChangeState(kError);
222  return false;
223  }
224 
225  return true;
226 }
227 
228 bool MP4MediaParser::LoadMoov(const std::string& file_path) {
229  std::unique_ptr<File, FileCloser> file(
230  File::OpenWithNoBuffering(file_path.c_str(), "r"));
231  if (!file) {
232  LOG(ERROR) << "Unable to open media file '" << file_path << "'";
233  return false;
234  }
235  if (!file->Seek(0)) {
236  LOG(WARNING) << "Filesystem does not support seeking on file '" << file_path
237  << "'";
238  return false;
239  }
240 
241  uint64_t file_position(0);
242  bool mdat_seen(false);
243  while (true) {
244  const uint32_t kBoxHeaderReadSize(16);
245  std::vector<uint8_t> buffer(kBoxHeaderReadSize);
246  int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
247  if (bytes_read == 0) {
248  LOG(ERROR) << "Could not find 'moov' box in file '" << file_path << "'";
249  return false;
250  }
251  if (bytes_read < kBoxHeaderReadSize) {
252  LOG(ERROR) << "Error reading media file '" << file_path << "'";
253  return false;
254  }
255  uint64_t box_size;
256  FourCC box_type;
257  bool err;
258  if (!BoxReader::StartBox(&buffer[0], kBoxHeaderReadSize, &box_type,
259  &box_size, &err)) {
260  LOG(ERROR) << "Could not start box from file '" << file_path << "'";
261  return false;
262  }
263  if (box_type == FOURCC_mdat) {
264  mdat_seen = true;
265  } else if (box_type == FOURCC_moov) {
266  if (!mdat_seen) {
267  // 'moov' is before 'mdat'. Nothing to do.
268  break;
269  }
270  // 'mdat' before 'moov'. Read and parse 'moov'.
271  if (!Parse(&buffer[0], bytes_read)) {
272  LOG(ERROR) << "Error parsing mp4 file '" << file_path << "'";
273  return false;
274  }
275  uint64_t bytes_to_read = box_size - bytes_read;
276  buffer.resize(bytes_to_read);
277  while (bytes_to_read > 0) {
278  bytes_read = file->Read(&buffer[0], bytes_to_read);
279  if (bytes_read <= 0) {
280  LOG(ERROR) << "Error reading 'moov' contents from file '" << file_path
281  << "'";
282  return false;
283  }
284  if (!Parse(&buffer[0], bytes_read)) {
285  LOG(ERROR) << "Error parsing mp4 file '" << file_path << "'";
286  return false;
287  }
288  bytes_to_read -= bytes_read;
289  }
290  queue_.Reset(); // So that we don't need to adjust data offsets.
291  mdat_tail_ = 0; // So it will skip boxes until mdat.
292  break; // Done.
293  }
294  file_position += box_size;
295  if (!file->Seek(file_position)) {
296  LOG(ERROR) << "Error skipping box in mp4 file '" << file_path << "'";
297  return false;
298  }
299  }
300  return true;
301 }
302 
303 bool MP4MediaParser::ParseBox(bool* err) {
304  const uint8_t* buf;
305  int size;
306  queue_.Peek(&buf, &size);
307  if (!size)
308  return false;
309 
310  std::unique_ptr<BoxReader> reader(BoxReader::ReadBox(buf, size, err));
311  if (reader.get() == NULL)
312  return false;
313 
314  if (reader->type() == FOURCC_mdat) {
315  if (!moov_) {
316  // For seekable files, we seek to the 'moov' and load the 'moov' first
317  // then seek back (see LoadMoov function for details); we do not support
318  // having 'mdat' before 'moov' for non-seekable files. The code ends up
319  // here only if it is a non-seekable file.
320  NOTIMPLEMENTED() << " Non-seekable Files with 'mdat' box before 'moov' "
321  "box is not supported.";
322  *err = true;
323  return false;
324  } else {
325  // This can happen if there are unused 'mdat' boxes, which is unusual
326  // but allowed by the spec. Ignore the 'mdat' and proceed.
327  LOG(INFO)
328  << "Ignore unused 'mdat' box - this could be as a result of extra "
329  "not usable 'mdat' or 'mdat' associated with unrecognized track.";
330  }
331  }
332 
333  // Set up mdat offset for ReadMDATsUntil().
334  mdat_tail_ = queue_.head() + reader->size();
335 
336  if (reader->type() == FOURCC_moov) {
337  *err = !ParseMoov(reader.get());
338  } else if (reader->type() == FOURCC_moof) {
339  moof_head_ = queue_.head();
340  *err = !ParseMoof(reader.get());
341 
342  // Return early to avoid evicting 'moof' data from queue. Auxiliary info may
343  // be located anywhere in the file, including inside the 'moof' itself.
344  // (Since 'default-base-is-moof' is mandated, no data references can come
345  // before the head of the 'moof', so keeping this box around is sufficient.)
346  return !(*err);
347  } else {
348  VLOG(2) << "Skipping top-level box: " << FourCCToString(reader->type());
349  }
350 
351  queue_.Pop(static_cast<int>(reader->size()));
352  return !(*err);
353 }
354 
355 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
356  if (moov_)
357  return true; // Already parsed the 'moov' box.
358 
359  moov_.reset(new Movie);
360  RCHECK(moov_->Parse(reader));
361  runs_.reset();
362 
363  std::vector<std::shared_ptr<StreamInfo>> streams;
364 
365  for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
366  track != moov_->tracks.end(); ++track) {
367  const uint32_t timescale = track->media.header.timescale;
368 
369  // Calculate duration (based on timescale).
370  uint64_t duration = 0;
371  if (track->media.header.duration > 0) {
372  duration = track->media.header.duration;
373  } else if (moov_->extends.header.fragment_duration > 0) {
374  DCHECK(moov_->header.timescale != 0);
375  duration = Rescale(moov_->extends.header.fragment_duration,
376  moov_->header.timescale,
377  timescale);
378  } else if (moov_->header.duration > 0 &&
379  moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
380  DCHECK(moov_->header.timescale != 0);
381  duration =
382  Rescale(moov_->header.duration, moov_->header.timescale, timescale);
383  }
384 
385  const SampleDescription& samp_descr =
386  track->media.information.sample_table.description;
387 
388  size_t desc_idx = 0;
389 
390  // Read sample description index from mvex if it exists otherwise read
391  // from the first entry in Sample To Chunk box.
392  if (moov_->extends.tracks.size() > 0) {
393  for (size_t t = 0; t < moov_->extends.tracks.size(); t++) {
394  const TrackExtends& trex = moov_->extends.tracks[t];
395  if (trex.track_id == track->header.track_id) {
396  desc_idx = trex.default_sample_description_index;
397  break;
398  }
399  }
400  } else {
401  const std::vector<ChunkInfo>& chunk_info =
402  track->media.information.sample_table.sample_to_chunk.chunk_info;
403  RCHECK(chunk_info.size() > 0);
404  desc_idx = chunk_info[0].sample_description_index;
405  }
406  RCHECK(desc_idx > 0);
407  desc_idx -= 1; // BMFF descriptor index is one-based
408 
409  if (samp_descr.type == kAudio) {
410  RCHECK(!samp_descr.audio_entries.empty());
411 
412  // It is not uncommon to find otherwise-valid files with incorrect sample
413  // description indices, so we fail gracefully in that case.
414  if (desc_idx >= samp_descr.audio_entries.size())
415  desc_idx = 0;
416 
417  const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
418  const FourCC actual_format = entry.GetActualFormat();
419  Codec codec = FourCCToCodec(actual_format);
420  uint8_t num_channels = entry.channelcount;
421  uint32_t sampling_frequency = entry.samplerate;
422  uint64_t codec_delay_ns = 0;
423  uint8_t audio_object_type = 0;
424  uint32_t max_bitrate = 0;
425  uint32_t avg_bitrate = 0;
426  std::vector<uint8_t> codec_config;
427 
428  switch (actual_format) {
429  case FOURCC_mp4a: {
430  const DecoderConfigDescriptor& decoder_config =
431  entry.esds.es_descriptor.decoder_config_descriptor();
432  max_bitrate = decoder_config.max_bitrate();
433  avg_bitrate = decoder_config.avg_bitrate();
434 
435  codec = ObjectTypeToCodec(decoder_config.object_type());
436  if (codec == kCodecAAC) {
437  const AACAudioSpecificConfig& aac_audio_specific_config =
438  entry.esds.aac_audio_specific_config;
439  num_channels = aac_audio_specific_config.GetNumChannels();
440  sampling_frequency =
441  aac_audio_specific_config.GetSamplesPerSecond();
442  audio_object_type = aac_audio_specific_config.GetAudioObjectType();
443  codec_config =
444  decoder_config.decoder_specific_info_descriptor().data();
445  } else if (codec == kUnknownCodec) {
446  // Intentionally not to fail in the parser as there may be multiple
447  // streams in the source content, which allows the supported stream
448  // to be packaged. An error will be returned if the unsupported
449  // stream is passed to the muxer.
450  LOG(WARNING) << "Unsupported audio object type "
451  << static_cast<int>(decoder_config.object_type())
452  << " in stsd.es_desriptor.";
453  }
454  break;
455  }
456  case FOURCC_dtsc:
457  FALLTHROUGH_INTENDED;
458  case FOURCC_dtse:
459  FALLTHROUGH_INTENDED;
460  case FOURCC_dtsh:
461  FALLTHROUGH_INTENDED;
462  case FOURCC_dtsl:
463  FALLTHROUGH_INTENDED;
464  case FOURCC_dtsm:
465  codec_config = entry.ddts.extra_data;
466  max_bitrate = entry.ddts.max_bitrate;
467  avg_bitrate = entry.ddts.avg_bitrate;
468  break;
469  case FOURCC_ac_3:
470  codec_config = entry.dac3.data;
471  num_channels = static_cast<uint8_t>(GetAc3NumChannels(codec_config));
472  break;
473  case FOURCC_ec_3:
474  codec_config = entry.dec3.data;
475  num_channels = static_cast<uint8_t>(GetEc3NumChannels(codec_config));
476  break;
477  case FOURCC_fLaC:
478  codec_config = entry.dfla.data;
479  break;
480  case FOURCC_Opus:
481  codec_config = entry.dops.opus_identification_header;
482  codec_delay_ns =
483  entry.dops.preskip * kNanosecondsPerSecond / sampling_frequency;
484  break;
485  default:
486  // Intentionally not to fail in the parser as there may be multiple
487  // streams in the source content, which allows the supported stream to
488  // be packaged.
489  // An error will be returned if the unsupported stream is passed to
490  // the muxer.
491  LOG(WARNING) << "Unsupported audio format '"
492  << FourCCToString(actual_format) << "' in stsd box.";
493  break;
494  }
495 
496  // Extract possible seek preroll.
497  uint64_t seek_preroll_ns = 0;
498  for (const auto& sample_group_description :
499  track->media.information.sample_table.sample_group_descriptions) {
500  if (sample_group_description.grouping_type != FOURCC_roll)
501  continue;
502  const auto& audio_roll_recovery_entries =
503  sample_group_description.audio_roll_recovery_entries;
504  if (audio_roll_recovery_entries.size() != 1) {
505  LOG(WARNING) << "Unexpected number of entries in "
506  "SampleGroupDescription table with grouping type "
507  "'roll'.";
508  break;
509  }
510  const int16_t roll_distance_in_samples =
511  audio_roll_recovery_entries[0].roll_distance;
512  if (roll_distance_in_samples < 0) {
513  RCHECK(sampling_frequency != 0);
514  seek_preroll_ns = kNanosecondsPerSecond *
515  (-roll_distance_in_samples) / sampling_frequency;
516  } else {
517  LOG(WARNING)
518  << "Roll distance is supposed to be negative, but seeing "
519  << roll_distance_in_samples;
520  }
521  break;
522  }
523 
524  // The stream will be decrypted if a |decryptor_source_| is available.
525  const bool is_encrypted =
526  decryptor_source_
527  ? false
528  : entry.sinf.info.track_encryption.default_is_protected == 1;
529  DVLOG(1) << "is_audio_track_encrypted_: " << is_encrypted;
530  streams.emplace_back(new AudioStreamInfo(
531  track->header.track_id, timescale, duration, codec,
532  AudioStreamInfo::GetCodecString(codec, audio_object_type),
533  codec_config.data(), codec_config.size(), entry.samplesize,
534  num_channels, sampling_frequency, seek_preroll_ns, codec_delay_ns,
535  max_bitrate, avg_bitrate, track->media.header.language.code,
536  is_encrypted));
537  }
538 
539  if (samp_descr.type == kVideo) {
540  RCHECK(!samp_descr.video_entries.empty());
541  if (desc_idx >= samp_descr.video_entries.size())
542  desc_idx = 0;
543  const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
544  std::vector<uint8_t> codec_configuration_data =
545  entry.codec_configuration.data;
546 
547  uint32_t coded_width = entry.width;
548  uint32_t coded_height = entry.height;
549  uint32_t pixel_width = entry.pixel_aspect.h_spacing;
550  uint32_t pixel_height = entry.pixel_aspect.v_spacing;
551  if (pixel_width == 0 && pixel_height == 0) {
552  DerivePixelWidthHeight(coded_width, coded_height, track->header.width,
553  track->header.height, &pixel_width,
554  &pixel_height);
555  }
556  std::string codec_string;
557  uint8_t nalu_length_size = 0;
558  uint8_t transfer_characteristics = 0;
559 
560  const FourCC actual_format = entry.GetActualFormat();
561  const Codec video_codec = FourCCToCodec(actual_format);
562  switch (actual_format) {
563  case FOURCC_av01: {
564  AV1CodecConfigurationRecord av1_config;
565  if (!av1_config.Parse(codec_configuration_data)) {
566  LOG(ERROR) << "Failed to parse av1c.";
567  return false;
568  }
569  codec_string = av1_config.GetCodecString();
570  break;
571  }
572  case FOURCC_avc1:
573  case FOURCC_avc3: {
575  if (!avc_config.Parse(codec_configuration_data)) {
576  LOG(ERROR) << "Failed to parse avcc.";
577  return false;
578  }
579  codec_string = avc_config.GetCodecString(actual_format);
580  nalu_length_size = avc_config.nalu_length_size();
581  transfer_characteristics = avc_config.transfer_characteristics();
582 
583  // Use configurations from |avc_config| if it is valid.
584  if (avc_config.coded_width() != 0) {
585  DCHECK_NE(avc_config.coded_height(), 0u);
586  if (coded_width != avc_config.coded_width() ||
587  coded_height != avc_config.coded_height()) {
588  LOG(WARNING) << "Resolution in VisualSampleEntry (" << coded_width
589  << "," << coded_height
590  << ") does not match with resolution in "
591  "AVCDecoderConfigurationRecord ("
592  << avc_config.coded_width() << ","
593  << avc_config.coded_height()
594  << "). Use AVCDecoderConfigurationRecord.";
595  coded_width = avc_config.coded_width();
596  coded_height = avc_config.coded_height();
597  }
598 
599  DCHECK_NE(avc_config.pixel_width(), 0u);
600  DCHECK_NE(avc_config.pixel_height(), 0u);
601  if (pixel_width != avc_config.pixel_width() ||
602  pixel_height != avc_config.pixel_height()) {
603  LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
604  << "Pixel aspect ratio in PASP box (" << pixel_width << ","
605  << pixel_height
606  << ") does not match with SAR in "
607  "AVCDecoderConfigurationRecord "
608  "("
609  << avc_config.pixel_width() << ","
610  << avc_config.pixel_height()
611  << "). Use AVCDecoderConfigurationRecord.";
612  pixel_width = avc_config.pixel_width();
613  pixel_height = avc_config.pixel_height();
614  }
615  }
616  break;
617  }
618  case FOURCC_dvh1:
619  case FOURCC_dvhe:
620  case FOURCC_hev1:
621  case FOURCC_hvc1: {
622  HEVCDecoderConfigurationRecord hevc_config;
623  if (!hevc_config.Parse(codec_configuration_data)) {
624  LOG(ERROR) << "Failed to parse hevc.";
625  return false;
626  }
627  codec_string = hevc_config.GetCodecString(actual_format);
628  nalu_length_size = hevc_config.nalu_length_size();
629  transfer_characteristics = hevc_config.transfer_characteristics();
630 
631  if (!entry.extra_codec_configs.empty()) {
632  if (!UpdateCodecStringForDolbyVision(
633  actual_format, entry.extra_codec_configs, &codec_string)) {
634  return false;
635  }
636  }
637  break;
638  }
639  case FOURCC_vp08:
640  case FOURCC_vp09: {
641  VPCodecConfigurationRecord vp_config;
642  if (!vp_config.ParseMP4(codec_configuration_data)) {
643  LOG(ERROR) << "Failed to parse vpcc.";
644  return false;
645  }
646  if (actual_format == FOURCC_vp09 &&
647  (!vp_config.is_level_set() || vp_config.level() == 0)) {
648  const double kUnknownSampleDuration = 0.0;
649  vp_config.SetVP9Level(coded_width, coded_height,
650  kUnknownSampleDuration);
651  vp_config.WriteMP4(&codec_configuration_data);
652  }
653  codec_string = vp_config.GetCodecString(video_codec);
654  break;
655  }
656  default:
657  // Intentionally not to fail in the parser as there may be multiple
658  // streams in the source content, which allows the supported stream to
659  // be packaged.
660  // An error will be returned if the unsupported stream is passed to
661  // the muxer.
662  LOG(WARNING) << "Unsupported video format '"
663  << FourCCToString(actual_format) << "' in stsd box.";
664  break;
665  }
666 
667  // The stream will be decrypted if a |decryptor_source_| is available.
668  const bool is_encrypted =
669  decryptor_source_
670  ? false
671  : entry.sinf.info.track_encryption.default_is_protected == 1;
672  DVLOG(1) << "is_video_track_encrypted_: " << is_encrypted;
673  std::shared_ptr<VideoStreamInfo> video_stream_info(new VideoStreamInfo(
674  track->header.track_id, timescale, duration, video_codec,
675  GetH26xStreamFormat(actual_format), codec_string,
676  codec_configuration_data.data(), codec_configuration_data.size(),
677  coded_width, coded_height, pixel_width, pixel_height,
678  transfer_characteristics,
679  0, // trick_play_factor
680  nalu_length_size, track->media.header.language.code, is_encrypted));
681  video_stream_info->set_extra_config(entry.ExtraCodecConfigsAsVector());
682 
683  // Set pssh raw data if it has.
684  if (moov_->pssh.size() > 0) {
685  std::vector<uint8_t> pssh_raw_data;
686  for (const auto& pssh : moov_->pssh) {
687  pssh_raw_data.insert(pssh_raw_data.end(), pssh.raw_box.begin(),
688  pssh.raw_box.end());
689  }
690  video_stream_info->set_eme_init_data(pssh_raw_data.data(),
691  pssh_raw_data.size());
692  }
693 
694  streams.push_back(video_stream_info);
695  }
696  }
697 
698  init_cb_.Run(streams);
699  if (!FetchKeysIfNecessary(moov_->pssh))
700  return false;
701  runs_.reset(new TrackRunIterator(moov_.get()));
702  RCHECK(runs_->Init());
703  ChangeState(kEmittingSamples);
704  return true;
705 }
706 
707 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
708  // Must already have initialization segment.
709  RCHECK(moov_.get());
710  MovieFragment moof;
711  RCHECK(moof.Parse(reader));
712  if (!runs_)
713  runs_.reset(new TrackRunIterator(moov_.get()));
714  RCHECK(runs_->Init(moof));
715  if (!FetchKeysIfNecessary(moof.pssh))
716  return false;
717  ChangeState(kEmittingSamples);
718  return true;
719 }
720 
721 bool MP4MediaParser::FetchKeysIfNecessary(
722  const std::vector<ProtectionSystemSpecificHeader>& headers) {
723  if (headers.empty())
724  return true;
725 
726  // An error will be returned later if the samples need to be decrypted.
727  if (!decryption_key_source_)
728  return true;
729 
730  std::vector<uint8_t> pssh_raw_data;
731  for (const auto& header : headers) {
732  pssh_raw_data.insert(pssh_raw_data.end(), header.raw_box.begin(),
733  header.raw_box.end());
734  }
735  Status status =
736  decryption_key_source_->FetchKeys(EmeInitDataType::CENC, pssh_raw_data);
737  if (!status.ok()) {
738  LOG(ERROR) << "Error fetching decryption keys: " << status;
739  return false;
740  }
741  return true;
742 }
743 
744 bool MP4MediaParser::EnqueueSample(bool* err) {
745  if (!runs_->IsRunValid()) {
746  // Remain in kEnqueueingSamples state, discarding data, until the end of
747  // the current 'mdat' box has been appended to the queue.
748  if (!queue_.Trim(mdat_tail_))
749  return false;
750 
751  ChangeState(kParsingBoxes);
752  return true;
753  }
754 
755  if (!runs_->IsSampleValid()) {
756  runs_->AdvanceRun();
757  return true;
758  }
759 
760  DCHECK(!(*err));
761 
762  const uint8_t* buf;
763  int buf_size;
764  queue_.Peek(&buf, &buf_size);
765  if (!buf_size)
766  return false;
767 
768  // Skip this entire track if it is not audio nor video.
769  if (!runs_->is_audio() && !runs_->is_video())
770  runs_->AdvanceRun();
771 
772  // Attempt to cache the auxiliary information first. Aux info is usually
773  // placed in a contiguous block before the sample data, rather than being
774  // interleaved. If we didn't cache it, this would require that we retain the
775  // start of the segment buffer while reading samples. Aux info is typically
776  // quite small compared to sample data, so this pattern is useful on
777  // memory-constrained devices where the source buffer consumes a substantial
778  // portion of the total system memory.
779  if (runs_->AuxInfoNeedsToBeCached()) {
780  queue_.PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
781  if (buf_size < runs_->aux_info_size())
782  return false;
783  *err = !runs_->CacheAuxInfo(buf, buf_size);
784  return !*err;
785  }
786 
787  int64_t sample_offset = runs_->sample_offset() + moof_head_;
788  queue_.PeekAt(sample_offset, &buf, &buf_size);
789  if (buf_size < runs_->sample_size()) {
790  if (sample_offset < queue_.head()) {
791  LOG(ERROR) << "Incorrect sample offset " << sample_offset
792  << " < " << queue_.head();
793  *err = true;
794  }
795  return false;
796  }
797 
798  const uint8_t* media_data = buf;
799  const size_t media_data_size = runs_->sample_size();
800  // Use a dummy data size of 0 to avoid copying overhead.
801  // Actual media data is set later.
802  const size_t kDummyDataSize = 0;
803  std::shared_ptr<MediaSample> stream_sample(
804  MediaSample::CopyFrom(media_data, kDummyDataSize, runs_->is_keyframe()));
805 
806  if (runs_->is_encrypted()) {
807  std::shared_ptr<uint8_t> decrypted_media_data(
808  new uint8_t[media_data_size], std::default_delete<uint8_t[]>());
809  std::unique_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
810  if (!decrypt_config) {
811  *err = true;
812  LOG(ERROR) << "Missing decrypt config.";
813  return false;
814  }
815 
816  if (!decryptor_source_) {
817  stream_sample->SetData(media_data, media_data_size);
818  // If the demuxer does not have the decryptor_source_, store
819  // decrypt_config so that the demuxed sample can be decrypted later.
820  stream_sample->set_decrypt_config(std::move(decrypt_config));
821  stream_sample->set_is_encrypted(true);
822  } else {
823  if (!decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
824  media_data, media_data_size,
825  decrypted_media_data.get())) {
826  *err = true;
827  LOG(ERROR) << "Cannot decrypt samples.";
828  return false;
829  }
830  stream_sample->TransferData(std::move(decrypted_media_data),
831  media_data_size);
832  }
833  } else {
834  stream_sample->SetData(media_data, media_data_size);
835  }
836 
837  stream_sample->set_dts(runs_->dts());
838  stream_sample->set_pts(runs_->cts());
839  stream_sample->set_duration(runs_->duration());
840 
841  DVLOG(3) << "Pushing frame: "
842  << ", key=" << runs_->is_keyframe()
843  << ", dur=" << runs_->duration()
844  << ", dts=" << runs_->dts()
845  << ", cts=" << runs_->cts()
846  << ", size=" << runs_->sample_size();
847 
848  if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
849  *err = true;
850  LOG(ERROR) << "Failed to process the sample.";
851  return false;
852  }
853 
854  runs_->AdvanceSample();
855  return true;
856 }
857 
858 bool MP4MediaParser::ReadAndDiscardMDATsUntil(const int64_t offset) {
859  bool err = false;
860  while (mdat_tail_ < offset) {
861  const uint8_t* buf;
862  int size;
863  queue_.PeekAt(mdat_tail_, &buf, &size);
864 
865  FourCC type;
866  uint64_t box_sz;
867  if (!BoxReader::StartBox(buf, size, &type, &box_sz, &err))
868  break;
869 
870  mdat_tail_ += box_sz;
871  }
872  queue_.Trim(std::min(mdat_tail_, offset));
873  return !err;
874 }
875 
876 void MP4MediaParser::ChangeState(State new_state) {
877  DVLOG(2) << "Changing state: " << new_state;
878  state_ = new_state;
879 }
880 
881 } // namespace mp4
882 } // namespace media
883 } // namespace shaka
Class for parsing or writing VP codec configuration record.
bool Flush() override WARN_UNUSED_RESULT
All the methods that are virtual are virtual for mocking.
void SetVP9Level(uint16_t width, uint16_t height, double sample_duration_seconds)
Compute and set VP9 Level based on the input attributes.
bool Parse(const uint8_t *buf, int size) override WARN_UNUSED_RESULT
bool Parse(const std::vector< uint8_t > &data)
std::string GetCodecString(FourCC codec_fourcc) const
Class for reading MP4 boxes.
Definition: box_reader.h:25
bool Parse(const std::vector< uint8_t > &data)
void WriteMP4(std::vector< uint8_t > *data) const
bool ParseMP4(const std::vector< uint8_t > &data)
Class for parsing AV1 codec configuration record.
Class for parsing HEVC decoder configuration record.
static File * OpenWithNoBuffering(const char *file_name, const char *mode)
Definition: file.cc:187
static std::string GetCodecString(Codec codec, uint8_t audio_object_type)
bool LoadMoov(const std::string &file_path)
Class for parsing AVC decoder configuration record.
static std::shared_ptr< MediaSample > CopyFrom(const uint8_t *data, size_t size, bool is_key_frame)
Definition: media_sample.cc:42
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:48
void Init(const InitCB &init_cb, const NewSampleCB &new_sample_cb, KeySource *decryption_key_source) override
Holds video stream information.
Holds audio stream information.
DecryptorSource wraps KeySource and is responsible for decryptor management.
static bool StartBox(const uint8_t *buf, const size_t buf_size, FourCC *type, uint64_t *box_size, bool *err) WARN_UNUSED_RESULT
Definition: box_reader.cc:54
static BoxReader * ReadBox(const uint8_t *buf, const size_t buf_size, bool *err)
Definition: box_reader.cc:36