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 Codec FourCCToCodec(FourCC fourcc) {
81 const uint8_t kDtsAudioNumChannels = 6;
82 const uint64_t kNanosecondsPerSecond = 1000000000ull;
86 MP4MediaParser::MP4MediaParser()
87 : state_(kWaitingForInit),
88 decryption_key_source_(NULL),
92 MP4MediaParser::~MP4MediaParser() {}
95 const NewSampleCB& new_sample_cb,
97 DCHECK_EQ(state_, kWaitingForInit);
98 DCHECK(init_cb_.is_null());
99 DCHECK(!init_cb.is_null());
100 DCHECK(!new_sample_cb.is_null());
102 ChangeState(kParsingBoxes);
104 new_sample_cb_ = new_sample_cb;
105 decryption_key_source_ = decryption_key_source;
106 if (decryption_key_source)
110 void MP4MediaParser::Reset() {
118 DCHECK_NE(state_, kWaitingForInit);
120 ChangeState(kParsingBoxes);
125 DCHECK_NE(state_, kWaitingForInit);
127 if (state_ == kError)
130 queue_.Push(buf, size);
132 bool result, err =
false;
135 if (state_ == kParsingBoxes) {
136 result = ParseBox(&err);
138 DCHECK_EQ(kEmittingSamples, state_);
139 result = EnqueueSample(&err);
141 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
142 err = !ReadAndDiscardMDATsUntil(max_clear);
145 }
while (result && !err);
148 DLOG(ERROR) <<
"Error while parsing MP4";
159 scoped_ptr<File, FileCloser> file(
162 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
165 if (!file->Seek(0)) {
166 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
171 uint64_t file_position(0);
172 bool mdat_seen(
false);
174 const uint32_t kBoxHeaderReadSize(16);
175 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
176 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
177 if (bytes_read == 0) {
178 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
181 if (bytes_read < kBoxHeaderReadSize) {
182 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
190 LOG(ERROR) <<
"Could not start box from file '" << file_path <<
"'";
193 if (box_type == FOURCC_mdat) {
195 }
else if (box_type == FOURCC_moov) {
201 if (!
Parse(&buffer[0], bytes_read)) {
202 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
205 uint64_t bytes_to_read = box_size - bytes_read;
206 buffer.resize(bytes_to_read);
207 while (bytes_to_read > 0) {
208 bytes_read = file->Read(&buffer[0], bytes_to_read);
209 if (bytes_read <= 0) {
210 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
214 if (!
Parse(&buffer[0], bytes_read)) {
215 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
218 bytes_to_read -= bytes_read;
224 file_position += box_size;
225 if (!file->Seek(file_position)) {
226 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
233 bool MP4MediaParser::ParseBox(
bool* err) {
236 queue_.Peek(&buf, &size);
241 if (reader.get() == NULL)
244 if (reader->type() == FOURCC_mdat) {
248 NOTIMPLEMENTED() <<
" Files with MDAT before MOOV is not supported yet.";
254 mdat_tail_ = queue_.
head() + reader->size();
256 if (reader->type() == FOURCC_moov) {
257 *err = !ParseMoov(reader.get());
258 }
else if (reader->type() == FOURCC_moof) {
259 moof_head_ = queue_.
head();
260 *err = !ParseMoof(reader.get());
268 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
271 queue_.Pop(reader->size());
275 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
279 moov_.reset(
new Movie);
280 RCHECK(moov_->Parse(reader));
283 std::vector<scoped_refptr<StreamInfo> > streams;
285 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
286 track != moov_->tracks.end(); ++track) {
287 const uint32_t timescale = track->media.header.timescale;
290 uint64_t duration = 0;
291 if (track->media.header.duration > 0) {
292 duration = track->media.header.duration;
293 }
else if (moov_->extends.header.fragment_duration > 0) {
294 DCHECK(moov_->header.timescale != 0);
295 duration = Rescale(moov_->extends.header.fragment_duration,
296 moov_->header.timescale,
298 }
else if (moov_->header.duration > 0 &&
299 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
300 DCHECK(moov_->header.timescale != 0);
302 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
305 const SampleDescription& samp_descr =
306 track->media.information.sample_table.description;
312 if (moov_->extends.tracks.size() > 0) {
313 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
314 const TrackExtends& trex = moov_->extends.tracks[t];
315 if (trex.track_id == track->header.track_id) {
316 desc_idx = trex.default_sample_description_index;
321 const std::vector<ChunkInfo>& chunk_info =
322 track->media.information.sample_table.sample_to_chunk.chunk_info;
323 RCHECK(chunk_info.size() > 0);
324 desc_idx = chunk_info[0].sample_description_index;
326 RCHECK(desc_idx > 0);
329 if (samp_descr.type == kAudio) {
330 RCHECK(!samp_descr.audio_entries.empty());
334 if (desc_idx >= samp_descr.audio_entries.size())
337 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
338 const FourCC actual_format = entry.GetActualFormat();
339 Codec codec = FourCCToCodec(actual_format);
340 uint8_t num_channels = 0;
341 uint32_t sampling_frequency = 0;
342 uint64_t codec_delay_ns = 0;
343 uint8_t audio_object_type = 0;
344 uint32_t max_bitrate = 0;
345 uint32_t avg_bitrate = 0;
346 std::vector<uint8_t> codec_config;
348 switch (actual_format) {
352 if (entry.esds.es_descriptor.IsAAC()) {
354 const AACAudioSpecificConfig& aac_audio_specific_config =
355 entry.esds.aac_audio_specific_config;
356 num_channels = aac_audio_specific_config.num_channels();
357 sampling_frequency = aac_audio_specific_config.frequency();
358 audio_object_type = aac_audio_specific_config.audio_object_type();
359 codec_config = entry.esds.es_descriptor.decoder_specific_info();
361 }
else if (entry.esds.es_descriptor.IsDTS()) {
362 ObjectType audio_type = entry.esds.es_descriptor.object_type();
363 switch (audio_type) {
377 LOG(ERROR) <<
"Unsupported audio type " << audio_type
381 num_channels = entry.esds.aac_audio_specific_config.num_channels();
384 if (num_channels != kDtsAudioNumChannels) {
385 LOG(ERROR) <<
"Unsupported channel count " << num_channels
386 <<
" for audio type " << audio_type <<
".";
389 sampling_frequency = entry.samplerate;
390 max_bitrate = entry.esds.es_descriptor.max_bitrate();
391 avg_bitrate = entry.esds.es_descriptor.avg_bitrate();
393 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
394 << actual_format <<
" in stsd box.";
399 FALLTHROUGH_INTENDED;
401 FALLTHROUGH_INTENDED;
403 FALLTHROUGH_INTENDED;
405 FALLTHROUGH_INTENDED;
407 codec_config = entry.ddts.extra_data;
408 max_bitrate = entry.ddts.max_bitrate;
409 avg_bitrate = entry.ddts.avg_bitrate;
410 num_channels = entry.channelcount;
411 sampling_frequency = entry.samplerate;
414 codec_config = entry.dac3.data;
415 num_channels = entry.channelcount;
416 sampling_frequency = entry.samplerate;
419 codec_config = entry.dec3.data;
420 num_channels = entry.channelcount;
421 sampling_frequency = entry.samplerate;
424 codec_config = entry.dops.opus_identification_header;
425 num_channels = entry.channelcount;
426 sampling_frequency = entry.samplerate;
427 RCHECK(sampling_frequency != 0);
429 entry.dops.preskip * kNanosecondsPerSecond / sampling_frequency;
432 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
433 << actual_format <<
" in stsd box.";
438 uint64_t seek_preroll_ns = 0;
439 for (
const auto& sample_group_description :
440 track->media.information.sample_table.sample_group_descriptions) {
441 if (sample_group_description.grouping_type != FOURCC_roll)
443 const auto& audio_roll_recovery_entries =
444 sample_group_description.audio_roll_recovery_entries;
445 if (audio_roll_recovery_entries.size() != 1) {
446 LOG(WARNING) <<
"Unexpected number of entries in "
447 "SampleGroupDescription table with grouping type "
451 const int16_t roll_distance_in_samples =
452 audio_roll_recovery_entries[0].roll_distance;
453 if (roll_distance_in_samples < 0) {
454 RCHECK(sampling_frequency != 0);
455 seek_preroll_ns = kNanosecondsPerSecond *
456 (-roll_distance_in_samples) / sampling_frequency;
459 <<
"Roll distance is supposed to be negative, but seeing "
460 << roll_distance_in_samples;
465 const bool is_encrypted =
466 entry.sinf.info.track_encryption.default_is_protected == 1;
467 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
468 streams.push_back(
new AudioStreamInfo(
469 track->header.track_id, timescale, duration, codec,
471 codec_config.data(), codec_config.size(), entry.samplesize,
472 num_channels, sampling_frequency, seek_preroll_ns, codec_delay_ns,
473 max_bitrate, avg_bitrate, track->media.header.language.code,
477 if (samp_descr.type == kVideo) {
478 RCHECK(!samp_descr.video_entries.empty());
479 if (desc_idx >= samp_descr.video_entries.size())
481 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
483 uint32_t coded_width = entry.width;
484 uint32_t coded_height = entry.height;
485 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
486 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
487 if (pixel_width == 0 && pixel_height == 0) {
491 std::string codec_string;
492 uint8_t nalu_length_size = 0;
494 const FourCC actual_format = entry.GetActualFormat();
495 const Codec video_codec = FourCCToCodec(actual_format);
496 switch (actual_format) {
498 AVCDecoderConfigurationRecord avc_config;
499 if (!avc_config.Parse(entry.codec_configuration.data)) {
500 LOG(ERROR) <<
"Failed to parse avcc.";
503 codec_string = avc_config.GetCodecString();
504 nalu_length_size = avc_config.nalu_length_size();
506 if (coded_width != avc_config.coded_width() ||
507 coded_height != avc_config.coded_height()) {
508 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
509 <<
"," << coded_height
510 <<
") does not match with resolution in "
511 "AVCDecoderConfigurationRecord ("
512 << avc_config.coded_width() <<
","
513 << avc_config.coded_height()
514 <<
"). Use AVCDecoderConfigurationRecord.";
515 coded_width = avc_config.coded_width();
516 coded_height = avc_config.coded_height();
519 if (pixel_width != avc_config.pixel_width() ||
520 pixel_height != avc_config.pixel_height()) {
521 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
522 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
524 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
526 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
527 <<
"). Use AVCDecoderConfigurationRecord.";
528 pixel_width = avc_config.pixel_width();
529 pixel_height = avc_config.pixel_height();
535 HEVCDecoderConfigurationRecord hevc_config;
536 if (!hevc_config.Parse(entry.codec_configuration.data)) {
537 LOG(ERROR) <<
"Failed to parse hevc.";
540 codec_string = hevc_config.GetCodecString(video_codec);
541 nalu_length_size = hevc_config.nalu_length_size();
547 VPCodecConfigurationRecord vp_config;
548 if (!vp_config.ParseMP4(entry.codec_configuration.data)) {
549 LOG(ERROR) <<
"Failed to parse vpcc.";
552 codec_string = vp_config.GetCodecString(video_codec);
556 LOG(ERROR) <<
"Unsupported video format "
557 << FourCCToString(actual_format) <<
" in stsd box.";
561 const bool is_encrypted =
562 entry.sinf.info.track_encryption.default_is_protected == 1;
563 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
564 streams.push_back(
new VideoStreamInfo(
565 track->header.track_id, timescale, duration, video_codec,
566 codec_string, entry.codec_configuration.data.data(),
567 entry.codec_configuration.data.size(), coded_width, coded_height,
568 pixel_width, pixel_height,
570 nalu_length_size, track->media.header.language.code, is_encrypted));
574 init_cb_.Run(streams);
575 if (!FetchKeysIfNecessary(moov_->pssh))
577 runs_.reset(
new TrackRunIterator(moov_.get()));
578 RCHECK(runs_->Init());
579 ChangeState(kEmittingSamples);
583 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
587 RCHECK(moof.Parse(reader));
589 runs_.reset(
new TrackRunIterator(moov_.get()));
590 RCHECK(runs_->Init(moof));
591 if (!FetchKeysIfNecessary(moof.pssh))
593 ChangeState(kEmittingSamples);
597 bool MP4MediaParser::FetchKeysIfNecessary(
598 const std::vector<ProtectionSystemSpecificHeader>& headers) {
603 if (!decryption_key_source_)
607 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
608 headers.begin(); iter != headers.end(); ++iter) {
609 status = decryption_key_source_->
FetchKeys(iter->raw_box);
613 VLOG(1) <<
"Unable to fetch decryption keys: " << status
614 <<
", trying the next PSSH box";
621 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
625 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
629 bool MP4MediaParser::EnqueueSample(
bool* err) {
630 if (!runs_->IsRunValid()) {
633 if (!queue_.
Trim(mdat_tail_))
636 ChangeState(kParsingBoxes);
640 if (!runs_->IsSampleValid()) {
649 queue_.Peek(&buf, &buf_size);
654 if (!runs_->is_audio() && !runs_->is_video())
664 if (runs_->AuxInfoNeedsToBeCached()) {
665 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
666 if (buf_size < runs_->aux_info_size())
668 *err = !runs_->CacheAuxInfo(buf, buf_size);
672 int64_t sample_offset = runs_->sample_offset() + moof_head_;
673 queue_.
PeekAt(sample_offset, &buf, &buf_size);
674 if (buf_size < runs_->sample_size()) {
675 if (sample_offset < queue_.
head()) {
676 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
677 <<
" < " << queue_.
head();
684 buf, runs_->sample_size(), runs_->is_keyframe()));
685 if (runs_->is_encrypted()) {
686 if (!decryptor_source_) {
688 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
693 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
694 if (!decrypt_config ||
695 !decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
696 stream_sample->writable_data(),
697 stream_sample->data_size())) {
699 LOG(ERROR) <<
"Cannot decrypt samples.";
704 stream_sample->set_dts(runs_->dts());
705 stream_sample->set_pts(runs_->cts());
706 stream_sample->set_duration(runs_->duration());
708 DVLOG(3) <<
"Pushing frame: "
709 <<
", key=" << runs_->is_keyframe()
710 <<
", dur=" << runs_->duration()
711 <<
", dts=" << runs_->dts()
712 <<
", cts=" << runs_->cts()
713 <<
", size=" << runs_->sample_size();
715 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
717 LOG(ERROR) <<
"Failed to process the sample.";
721 runs_->AdvanceSample();
725 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
727 while (mdat_tail_ < offset) {
730 queue_.
PeekAt(mdat_tail_, &buf, &size);
737 mdat_tail_ += box_sz;
739 queue_.
Trim(std::min(mdat_tail_, offset));
743 void MP4MediaParser::ChangeState(State new_state) {
744 DVLOG(2) <<
"Changing state: " << new_state;