5 #include "packager/media/formats/mp4/mp4_media_parser.h"
9 #include "packager/base/callback.h"
10 #include "packager/base/callback_helpers.h"
11 #include "packager/base/logging.h"
12 #include "packager/base/memory/ref_counted.h"
13 #include "packager/base/strings/string_number_conversions.h"
14 #include "packager/media/base/audio_stream_info.h"
15 #include "packager/media/base/buffer_reader.h"
16 #include "packager/media/base/decrypt_config.h"
17 #include "packager/media/base/key_source.h"
18 #include "packager/media/base/macros.h"
19 #include "packager/media/base/media_sample.h"
20 #include "packager/media/base/rcheck.h"
21 #include "packager/media/base/video_stream_info.h"
22 #include "packager/media/codecs/avc_decoder_configuration_record.h"
23 #include "packager/media/codecs/es_descriptor.h"
24 #include "packager/media/codecs/hevc_decoder_configuration_record.h"
25 #include "packager/media/codecs/vp_codec_configuration_record.h"
26 #include "packager/media/file/file.h"
27 #include "packager/media/file/file_closer.h"
28 #include "packager/media/formats/mp4/box_definitions.h"
29 #include "packager/media/formats/mp4/box_reader.h"
30 #include "packager/media/formats/mp4/track_run_iterator.h"
37 uint64_t Rescale(uint64_t time_in_old_scale,
40 return (static_cast<double>(time_in_old_scale) / old_scale) * new_scale;
43 VideoCodec FourCCToVideoCodec(FourCC fourcc) {
58 return kUnknownVideoCodec;
62 AudioCodec FourCCToAudioCodec(FourCC fourcc) {
83 return kUnknownAudioCodec;
88 const uint8_t kDtsAudioNumChannels = 6;
89 const uint64_t kNanosecondsPerSecond = 1000000000ull;
93 MP4MediaParser::MP4MediaParser()
94 : state_(kWaitingForInit),
95 decryption_key_source_(NULL),
99 MP4MediaParser::~MP4MediaParser() {}
102 const NewSampleCB& new_sample_cb,
104 DCHECK_EQ(state_, kWaitingForInit);
105 DCHECK(init_cb_.is_null());
106 DCHECK(!init_cb.is_null());
107 DCHECK(!new_sample_cb.is_null());
109 ChangeState(kParsingBoxes);
111 new_sample_cb_ = new_sample_cb;
112 decryption_key_source_ = decryption_key_source;
113 if (decryption_key_source)
117 void MP4MediaParser::Reset() {
125 DCHECK_NE(state_, kWaitingForInit);
127 ChangeState(kParsingBoxes);
132 DCHECK_NE(state_, kWaitingForInit);
134 if (state_ == kError)
137 queue_.Push(buf, size);
139 bool result, err =
false;
142 if (state_ == kParsingBoxes) {
143 result = ParseBox(&err);
145 DCHECK_EQ(kEmittingSamples, state_);
146 result = EnqueueSample(&err);
148 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
149 err = !ReadAndDiscardMDATsUntil(max_clear);
152 }
while (result && !err);
155 DLOG(ERROR) <<
"Error while parsing MP4";
166 scoped_ptr<File, FileCloser> file(
169 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
172 if (!file->Seek(0)) {
173 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
178 uint64_t file_position(0);
179 bool mdat_seen(
false);
181 const uint32_t kBoxHeaderReadSize(16);
182 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
183 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
184 if (bytes_read == 0) {
185 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
188 if (bytes_read < kBoxHeaderReadSize) {
189 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
197 LOG(ERROR) <<
"Could not start top level box from file '" << file_path
201 if (box_type == FOURCC_mdat) {
203 }
else if (box_type == FOURCC_moov) {
209 if (!
Parse(&buffer[0], bytes_read)) {
210 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
213 uint64_t bytes_to_read = box_size - bytes_read;
214 buffer.resize(bytes_to_read);
215 while (bytes_to_read > 0) {
216 bytes_read = file->Read(&buffer[0], bytes_to_read);
217 if (bytes_read <= 0) {
218 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
222 if (!
Parse(&buffer[0], bytes_read)) {
223 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
226 bytes_to_read -= bytes_read;
232 file_position += box_size;
233 if (!file->Seek(file_position)) {
234 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
241 bool MP4MediaParser::ParseBox(
bool* err) {
244 queue_.Peek(&buf, &size);
249 if (reader.get() == NULL)
252 if (reader->type() == FOURCC_mdat) {
256 NOTIMPLEMENTED() <<
" Files with MDAT before MOOV is not supported yet.";
262 mdat_tail_ = queue_.
head() + reader->size();
264 if (reader->type() == FOURCC_moov) {
265 *err = !ParseMoov(reader.get());
266 }
else if (reader->type() == FOURCC_moof) {
267 moof_head_ = queue_.
head();
268 *err = !ParseMoof(reader.get());
276 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
279 queue_.Pop(reader->size());
283 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
287 moov_.reset(
new Movie);
288 RCHECK(moov_->Parse(reader));
291 std::vector<scoped_refptr<StreamInfo> > streams;
293 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
294 track != moov_->tracks.end(); ++track) {
295 const uint32_t timescale = track->media.header.timescale;
298 uint64_t duration = 0;
299 if (track->media.header.duration > 0) {
300 duration = track->media.header.duration;
301 }
else if (moov_->extends.header.fragment_duration > 0) {
302 DCHECK(moov_->header.timescale != 0);
303 duration = Rescale(moov_->extends.header.fragment_duration,
304 moov_->header.timescale,
306 }
else if (moov_->header.duration > 0 &&
307 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
308 DCHECK(moov_->header.timescale != 0);
310 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
313 const SampleDescription& samp_descr =
314 track->media.information.sample_table.description;
320 if (moov_->extends.tracks.size() > 0) {
321 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
322 const TrackExtends& trex = moov_->extends.tracks[t];
323 if (trex.track_id == track->header.track_id) {
324 desc_idx = trex.default_sample_description_index;
329 const std::vector<ChunkInfo>& chunk_info =
330 track->media.information.sample_table.sample_to_chunk.chunk_info;
331 RCHECK(chunk_info.size() > 0);
332 desc_idx = chunk_info[0].sample_description_index;
334 RCHECK(desc_idx > 0);
337 if (samp_descr.type == kAudio) {
338 RCHECK(!samp_descr.audio_entries.empty());
342 if (desc_idx >= samp_descr.audio_entries.size())
345 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
346 const FourCC actual_format = entry.GetActualFormat();
347 AudioCodec codec = FourCCToAudioCodec(actual_format);
348 uint8_t num_channels = 0;
349 uint32_t sampling_frequency = 0;
350 uint64_t codec_delay_ns = 0;
351 uint8_t audio_object_type = 0;
352 uint32_t max_bitrate = 0;
353 uint32_t avg_bitrate = 0;
354 std::vector<uint8_t> extra_data;
356 switch (actual_format) {
360 if (entry.esds.es_descriptor.IsAAC()) {
362 const AACAudioSpecificConfig& aac_audio_specific_config =
363 entry.esds.aac_audio_specific_config;
364 num_channels = aac_audio_specific_config.num_channels();
365 sampling_frequency = aac_audio_specific_config.frequency();
366 audio_object_type = aac_audio_specific_config.audio_object_type();
367 extra_data = entry.esds.es_descriptor.decoder_specific_info();
369 }
else if (entry.esds.es_descriptor.IsDTS()) {
370 ObjectType audio_type = entry.esds.es_descriptor.object_type();
371 switch (audio_type) {
385 LOG(ERROR) <<
"Unsupported audio type " << audio_type
389 num_channels = entry.esds.aac_audio_specific_config.num_channels();
392 if (num_channels != kDtsAudioNumChannels) {
393 LOG(ERROR) <<
"Unsupported channel count " << num_channels
394 <<
" for audio type " << audio_type <<
".";
397 sampling_frequency = entry.samplerate;
398 max_bitrate = entry.esds.es_descriptor.max_bitrate();
399 avg_bitrate = entry.esds.es_descriptor.avg_bitrate();
401 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
402 << actual_format <<
" in stsd box.";
407 FALLTHROUGH_INTENDED;
409 FALLTHROUGH_INTENDED;
411 FALLTHROUGH_INTENDED;
413 FALLTHROUGH_INTENDED;
415 extra_data = entry.ddts.extra_data;
416 max_bitrate = entry.ddts.max_bitrate;
417 avg_bitrate = entry.ddts.avg_bitrate;
418 num_channels = entry.channelcount;
419 sampling_frequency = entry.samplerate;
422 extra_data = entry.dac3.data;
423 num_channels = entry.channelcount;
424 sampling_frequency = entry.samplerate;
427 extra_data = entry.dec3.data;
428 num_channels = entry.channelcount;
429 sampling_frequency = entry.samplerate;
432 extra_data = entry.dops.opus_identification_header;
433 num_channels = entry.channelcount;
434 sampling_frequency = entry.samplerate;
435 RCHECK(sampling_frequency != 0);
437 entry.dops.preskip * kNanosecondsPerSecond / sampling_frequency;
440 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
441 << actual_format <<
" in stsd box.";
446 uint64_t seek_preroll_ns = 0;
447 for (
const auto& sample_group_description :
448 track->media.information.sample_table.sample_group_descriptions) {
449 if (sample_group_description.grouping_type != FOURCC_roll)
451 const auto& audio_roll_recovery_entries =
452 sample_group_description.audio_roll_recovery_entries;
453 if (audio_roll_recovery_entries.size() != 1) {
454 LOG(WARNING) <<
"Unexpected number of entries in "
455 "SampleGroupDescription table with grouping type "
459 const int16_t roll_distance_in_samples =
460 audio_roll_recovery_entries[0].roll_distance;
461 if (roll_distance_in_samples < 0) {
462 RCHECK(sampling_frequency != 0);
463 seek_preroll_ns = kNanosecondsPerSecond *
464 (-roll_distance_in_samples) / sampling_frequency;
467 <<
"Roll distance is supposed to be negative, but seeing "
468 << roll_distance_in_samples;
473 const bool is_encrypted =
474 entry.sinf.info.track_encryption.default_is_protected == 1;
475 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
476 streams.push_back(
new AudioStreamInfo(
477 track->header.track_id,
482 track->media.header.language.code,
495 if (samp_descr.type == kVideo) {
496 RCHECK(!samp_descr.video_entries.empty());
497 if (desc_idx >= samp_descr.video_entries.size())
499 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
501 uint32_t coded_width = entry.width;
502 uint32_t coded_height = entry.height;
503 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
504 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
505 if (pixel_width == 0 && pixel_height == 0) {
509 std::string codec_string;
510 uint8_t nalu_length_size = 0;
512 const FourCC actual_format = entry.GetActualFormat();
513 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
514 switch (actual_format) {
516 AVCDecoderConfigurationRecord avc_config;
517 if (!avc_config.Parse(entry.codec_configuration.data)) {
518 LOG(ERROR) <<
"Failed to parse avcc.";
521 codec_string = avc_config.GetCodecString();
522 nalu_length_size = avc_config.nalu_length_size();
524 if (coded_width != avc_config.coded_width() ||
525 coded_height != avc_config.coded_height()) {
526 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
527 <<
"," << coded_height
528 <<
") does not match with resolution in "
529 "AVCDecoderConfigurationRecord ("
530 << avc_config.coded_width() <<
","
531 << avc_config.coded_height()
532 <<
"). Use AVCDecoderConfigurationRecord.";
533 coded_width = avc_config.coded_width();
534 coded_height = avc_config.coded_height();
537 if (pixel_width != avc_config.pixel_width() ||
538 pixel_height != avc_config.pixel_height()) {
539 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
540 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
542 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
544 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
545 <<
"). Use AVCDecoderConfigurationRecord.";
546 pixel_width = avc_config.pixel_width();
547 pixel_height = avc_config.pixel_height();
553 HEVCDecoderConfigurationRecord hevc_config;
554 if (!hevc_config.Parse(entry.codec_configuration.data)) {
555 LOG(ERROR) <<
"Failed to parse hevc.";
558 codec_string = hevc_config.GetCodecString(video_codec);
559 nalu_length_size = hevc_config.nalu_length_size();
565 VPCodecConfigurationRecord vp_config;
566 if (!vp_config.Parse(entry.codec_configuration.data)) {
567 LOG(ERROR) <<
"Failed to parse vpcc.";
570 codec_string = vp_config.GetCodecString(video_codec);
574 LOG(ERROR) <<
"Unsupported video format "
575 << FourCCToString(actual_format) <<
" in stsd box.";
579 const bool is_encrypted =
580 entry.sinf.info.track_encryption.default_is_protected == 1;
581 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
582 streams.push_back(
new VideoStreamInfo(
583 track->header.track_id, timescale, duration, video_codec,
584 codec_string, track->media.header.language.code, coded_width,
585 coded_height, pixel_width, pixel_height,
587 nalu_length_size, entry.codec_configuration.data.data(),
588 entry.codec_configuration.data.size(), is_encrypted));
592 init_cb_.Run(streams);
593 if (!FetchKeysIfNecessary(moov_->pssh))
595 runs_.reset(
new TrackRunIterator(moov_.get()));
596 RCHECK(runs_->Init());
597 ChangeState(kEmittingSamples);
601 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
605 RCHECK(moof.Parse(reader));
607 runs_.reset(
new TrackRunIterator(moov_.get()));
608 RCHECK(runs_->Init(moof));
609 if (!FetchKeysIfNecessary(moof.pssh))
611 ChangeState(kEmittingSamples);
615 bool MP4MediaParser::FetchKeysIfNecessary(
616 const std::vector<ProtectionSystemSpecificHeader>& headers) {
621 if (!decryption_key_source_)
625 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
626 headers.begin(); iter != headers.end(); ++iter) {
627 status = decryption_key_source_->
FetchKeys(iter->raw_box);
631 VLOG(1) <<
"Unable to fetch decryption keys: " << status
632 <<
", trying the next PSSH box";
639 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
643 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
647 bool MP4MediaParser::EnqueueSample(
bool* err) {
648 if (!runs_->IsRunValid()) {
651 if (!queue_.
Trim(mdat_tail_))
654 ChangeState(kParsingBoxes);
658 if (!runs_->IsSampleValid()) {
667 queue_.Peek(&buf, &buf_size);
672 if (!runs_->is_audio() && !runs_->is_video())
682 if (runs_->AuxInfoNeedsToBeCached()) {
683 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
684 if (buf_size < runs_->aux_info_size())
686 *err = !runs_->CacheAuxInfo(buf, buf_size);
690 int64_t sample_offset = runs_->sample_offset() + moof_head_;
691 queue_.
PeekAt(sample_offset, &buf, &buf_size);
692 if (buf_size < runs_->sample_size()) {
693 if (sample_offset < queue_.
head()) {
694 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
695 <<
" < " << queue_.
head();
702 buf, runs_->sample_size(), runs_->is_keyframe()));
703 if (runs_->is_encrypted()) {
704 if (!decryptor_source_) {
706 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
711 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
712 if (!decrypt_config ||
713 !decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
714 stream_sample->writable_data(),
715 stream_sample->data_size())) {
717 LOG(ERROR) <<
"Cannot decrypt samples.";
722 stream_sample->set_dts(runs_->dts());
723 stream_sample->set_pts(runs_->cts());
724 stream_sample->set_duration(runs_->duration());
726 DVLOG(3) <<
"Pushing frame: "
727 <<
", key=" << runs_->is_keyframe()
728 <<
", dur=" << runs_->duration()
729 <<
", dts=" << runs_->dts()
730 <<
", cts=" << runs_->cts()
731 <<
", size=" << runs_->sample_size();
733 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
735 LOG(ERROR) <<
"Failed to process the sample.";
739 runs_->AdvanceSample();
743 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
745 while (mdat_tail_ < offset) {
748 queue_.
PeekAt(mdat_tail_, &buf, &size);
755 mdat_tail_ += box_sz;
757 queue_.
Trim(std::min(mdat_tail_, offset));
761 void MP4MediaParser::ChangeState(State new_state) {
762 DVLOG(2) <<
"Changing state: " << new_state;