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