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/protection_system_specific_info.h"
21 #include "packager/media/base/video_stream_info.h"
22 #include "packager/media/file/file.h"
23 #include "packager/media/file/file_closer.h"
24 #include "packager/media/filters/avc_decoder_configuration.h"
25 #include "packager/media/filters/hevc_decoder_configuration.h"
26 #include "packager/media/filters/vp_codec_configuration.h"
27 #include "packager/media/formats/mp4/box_definitions.h"
28 #include "packager/media/formats/mp4/box_reader.h"
29 #include "packager/media/formats/mp4/es_descriptor.h"
30 #include "packager/media/formats/mp4/rcheck.h"
31 #include "packager/media/formats/mp4/track_run_iterator.h"
33 namespace edash_packager {
38 uint64_t Rescale(uint64_t time_in_old_scale,
41 return (static_cast<double>(time_in_old_scale) / old_scale) * new_scale;
44 VideoCodec FourCCToVideoCodec(FourCC fourcc) {
59 return kUnknownVideoCodec;
63 AudioCodec FourCCToAudioCodec(FourCC fourcc) {
82 return kUnknownAudioCodec;
86 const char kWidevineKeySystemId[] =
"edef8ba979d64acea3c827dcd51d21ed";
88 const uint8_t kDtsAudioNumChannels = 6;
92 MP4MediaParser::MP4MediaParser()
93 : state_(kWaitingForInit),
94 decryption_key_source_(NULL),
98 MP4MediaParser::~MP4MediaParser() {}
101 const NewSampleCB& new_sample_cb,
103 DCHECK_EQ(state_, kWaitingForInit);
104 DCHECK(init_cb_.is_null());
105 DCHECK(!init_cb.is_null());
106 DCHECK(!new_sample_cb.is_null());
108 ChangeState(kParsingBoxes);
110 new_sample_cb_ = new_sample_cb;
111 decryption_key_source_ = decryption_key_source;
112 if (decryption_key_source)
116 void MP4MediaParser::Reset() {
124 DCHECK_NE(state_, kWaitingForInit);
126 ChangeState(kParsingBoxes);
131 DCHECK_NE(state_, kWaitingForInit);
133 if (state_ == kError)
136 queue_.Push(buf, size);
138 bool result, err =
false;
141 if (state_ == kParsingBoxes) {
142 result = ParseBox(&err);
144 DCHECK_EQ(kEmittingSamples, state_);
145 result = EnqueueSample(&err);
147 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
148 err = !ReadAndDiscardMDATsUntil(max_clear);
151 }
while (result && !err);
154 DLOG(ERROR) <<
"Error while parsing MP4";
165 scoped_ptr<File, FileCloser> file(
168 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
171 if (!file->Seek(0)) {
172 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
177 uint64_t file_position(0);
178 bool mdat_seen(
false);
180 const uint32_t kBoxHeaderReadSize(16);
181 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
182 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
183 if (bytes_read == 0) {
184 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
187 if (bytes_read < kBoxHeaderReadSize) {
188 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
196 LOG(ERROR) <<
"Could not start top level box from file '" << file_path
200 if (box_type == FOURCC_MDAT) {
202 }
else if (box_type == FOURCC_MOOV) {
208 if (!
Parse(&buffer[0], bytes_read)) {
209 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
212 uint64_t bytes_to_read = box_size - bytes_read;
213 buffer.resize(bytes_to_read);
214 while (bytes_to_read > 0) {
215 bytes_read = file->Read(&buffer[0], bytes_to_read);
216 if (bytes_read <= 0) {
217 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
221 if (!
Parse(&buffer[0], bytes_read)) {
222 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
225 bytes_to_read -= bytes_read;
231 file_position += box_size;
232 if (!file->Seek(file_position)) {
233 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
240 bool MP4MediaParser::ParseBox(
bool* err) {
243 queue_.Peek(&buf, &size);
248 if (reader.get() == NULL)
251 if (reader->type() == FOURCC_MDAT) {
255 NOTIMPLEMENTED() <<
" Files with MDAT before MOOV is not supported yet.";
261 mdat_tail_ = queue_.
head() + reader->size();
263 if (reader->type() == FOURCC_MOOV) {
264 *err = !ParseMoov(reader.get());
265 }
else if (reader->type() == FOURCC_MOOF) {
266 moof_head_ = queue_.
head();
267 *err = !ParseMoof(reader.get());
275 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
278 queue_.Pop(reader->size());
282 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
286 moov_.reset(
new Movie);
287 RCHECK(moov_->Parse(reader));
290 std::vector<scoped_refptr<StreamInfo> > streams;
292 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
293 track != moov_->tracks.end(); ++track) {
294 const uint32_t timescale = track->media.header.timescale;
297 uint64_t duration = 0;
298 if (track->media.header.duration > 0) {
299 duration = track->media.header.duration;
300 }
else if (moov_->extends.header.fragment_duration > 0) {
301 DCHECK(moov_->header.timescale != 0);
302 duration = Rescale(moov_->extends.header.fragment_duration,
303 moov_->header.timescale,
305 }
else if (moov_->header.duration > 0 &&
306 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
307 DCHECK(moov_->header.timescale != 0);
309 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
312 const SampleDescription& samp_descr =
313 track->media.information.sample_table.description;
319 if (moov_->extends.tracks.size() > 0) {
320 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
321 const TrackExtends& trex = moov_->extends.tracks[t];
322 if (trex.track_id == track->header.track_id) {
323 desc_idx = trex.default_sample_description_index;
328 const std::vector<ChunkInfo>& chunk_info =
329 track->media.information.sample_table.sample_to_chunk.chunk_info;
330 RCHECK(chunk_info.size() > 0);
331 desc_idx = chunk_info[0].sample_description_index;
333 RCHECK(desc_idx > 0);
336 if (samp_descr.type == kAudio) {
337 RCHECK(!samp_descr.audio_entries.empty());
341 if (desc_idx >= samp_descr.audio_entries.size())
344 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
345 const FourCC actual_format = entry.GetActualFormat();
346 AudioCodec codec = FourCCToAudioCodec(actual_format);
347 uint8_t num_channels = 0;
348 uint32_t sampling_frequency = 0;
349 uint8_t audio_object_type = 0;
350 uint32_t max_bitrate = 0;
351 uint32_t avg_bitrate = 0;
352 std::vector<uint8_t> extra_data;
354 switch (actual_format) {
358 if (entry.esds.es_descriptor.IsAAC()) {
360 const AACAudioSpecificConfig& aac_audio_specific_config =
361 entry.esds.aac_audio_specific_config;
362 num_channels = aac_audio_specific_config.num_channels();
363 sampling_frequency = aac_audio_specific_config.frequency();
364 audio_object_type = aac_audio_specific_config.audio_object_type();
365 extra_data = entry.esds.es_descriptor.decoder_specific_info();
367 }
else if (entry.esds.es_descriptor.IsDTS()) {
368 ObjectType audio_type = entry.esds.es_descriptor.object_type();
369 switch (audio_type) {
383 LOG(ERROR) <<
"Unsupported audio type " << audio_type
387 num_channels = entry.esds.aac_audio_specific_config.num_channels();
390 if (num_channels != kDtsAudioNumChannels) {
391 LOG(ERROR) <<
"Unsupported channel count " << num_channels
392 <<
" for audio type " << audio_type <<
".";
395 sampling_frequency = entry.samplerate;
396 max_bitrate = entry.esds.es_descriptor.max_bitrate();
397 avg_bitrate = entry.esds.es_descriptor.avg_bitrate();
399 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
400 << actual_format <<
" in stsd box.";
405 FALLTHROUGH_INTENDED;
407 FALLTHROUGH_INTENDED;
409 FALLTHROUGH_INTENDED;
411 FALLTHROUGH_INTENDED;
413 extra_data = entry.ddts.extra_data;
414 max_bitrate = entry.ddts.max_bitrate;
415 avg_bitrate = entry.ddts.avg_bitrate;
416 num_channels = entry.channelcount;
417 sampling_frequency = entry.samplerate;
420 extra_data = entry.dac3.data;
421 num_channels = entry.channelcount;
422 sampling_frequency = entry.samplerate;
425 extra_data = entry.dec3.data;
426 num_channels = entry.channelcount;
427 sampling_frequency = entry.samplerate;
430 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
431 << actual_format <<
" in stsd box.";
435 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
436 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
437 streams.push_back(
new AudioStreamInfo(
438 track->header.track_id,
443 track->media.header.language.code,
454 if (samp_descr.type == kVideo) {
455 RCHECK(!samp_descr.video_entries.empty());
456 if (desc_idx >= samp_descr.video_entries.size())
458 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
460 uint32_t coded_width = entry.width;
461 uint32_t coded_height = entry.height;
462 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
463 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
464 if (pixel_width == 0 && pixel_height == 0) {
468 std::string codec_string;
469 uint8_t nalu_length_size = 0;
471 const FourCC actual_format = entry.GetActualFormat();
472 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
473 switch (actual_format) {
475 AVCDecoderConfiguration avc_config;
476 if (!avc_config.Parse(entry.codec_config_record.data)) {
477 LOG(ERROR) <<
"Failed to parse avcc.";
480 codec_string = avc_config.GetCodecString();
481 nalu_length_size = avc_config.nalu_length_size();
483 if (coded_width != avc_config.coded_width() ||
484 coded_height != avc_config.coded_height()) {
485 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
486 <<
"," << coded_height
487 <<
") does not match with resolution in "
488 "AVCDecoderConfigurationRecord ("
489 << avc_config.coded_width() <<
","
490 << avc_config.coded_height()
491 <<
"). Use AVCDecoderConfigurationRecord.";
492 coded_width = avc_config.coded_width();
493 coded_height = avc_config.coded_height();
496 if (pixel_width != avc_config.pixel_width() ||
497 pixel_height != avc_config.pixel_height()) {
498 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
499 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
501 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
503 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
504 <<
"). Use AVCDecoderConfigurationRecord.";
505 pixel_width = avc_config.pixel_width();
506 pixel_height = avc_config.pixel_height();
512 HEVCDecoderConfiguration hevc_config;
513 if (!hevc_config.Parse(entry.codec_config_record.data)) {
514 LOG(ERROR) <<
"Failed to parse hevc.";
517 codec_string = hevc_config.GetCodecString(video_codec);
518 nalu_length_size = hevc_config.nalu_length_size();
524 VPCodecConfiguration vp_config;
525 if (!vp_config.Parse(entry.codec_config_record.data)) {
526 LOG(ERROR) <<
"Failed to parse vpcc.";
529 codec_string = vp_config.GetCodecString(video_codec);
533 LOG(ERROR) <<
"Unsupported video format "
534 << FourCCToString(actual_format) <<
" in stsd box.";
538 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
539 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
540 streams.push_back(
new VideoStreamInfo(
541 track->header.track_id, timescale, duration, video_codec,
542 codec_string, track->media.header.language.code, coded_width,
543 coded_height, pixel_width, pixel_height,
545 nalu_length_size, entry.codec_config_record.data.data(),
546 entry.codec_config_record.data.size(), is_encrypted));
550 init_cb_.Run(streams);
551 if (!FetchKeysIfNecessary(moov_->pssh))
553 runs_.reset(
new TrackRunIterator(moov_.get()));
554 RCHECK(runs_->Init());
555 ChangeState(kEmittingSamples);
559 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
563 RCHECK(moof.Parse(reader));
565 runs_.reset(
new TrackRunIterator(moov_.get()));
566 RCHECK(runs_->Init(moof));
567 if (!FetchKeysIfNecessary(moof.pssh))
569 ChangeState(kEmittingSamples);
573 bool MP4MediaParser::FetchKeysIfNecessary(
574 const std::vector<ProtectionSystemSpecificHeader>& headers) {
579 if (!decryption_key_source_)
584 std::vector<uint8_t> widevine_system_id;
585 base::HexStringToBytes(kWidevineKeySystemId, &widevine_system_id);
586 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
587 headers.begin(); iter != headers.end(); ++iter) {
588 ProtectionSystemSpecificInfo info;
589 RCHECK(info.Parse(iter->raw_box.data(), iter->raw_box.size()));
590 if (info.system_id() == widevine_system_id) {
591 Status status = decryption_key_source_->
FetchKeys(info.pssh_data());
593 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
600 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
604 bool MP4MediaParser::EnqueueSample(
bool* err) {
605 if (!runs_->IsRunValid()) {
608 if (!queue_.
Trim(mdat_tail_))
611 ChangeState(kParsingBoxes);
615 if (!runs_->IsSampleValid()) {
624 queue_.Peek(&buf, &buf_size);
629 if (!runs_->is_audio() && !runs_->is_video())
639 if (runs_->AuxInfoNeedsToBeCached()) {
640 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
641 if (buf_size < runs_->aux_info_size())
643 *err = !runs_->CacheAuxInfo(buf, buf_size);
647 int64_t sample_offset = runs_->sample_offset() + moof_head_;
648 queue_.
PeekAt(sample_offset, &buf, &buf_size);
649 if (buf_size < runs_->sample_size()) {
650 if (sample_offset < queue_.
head()) {
651 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
652 <<
" < " << queue_.
head();
659 buf, runs_->sample_size(), runs_->is_keyframe()));
660 if (runs_->is_encrypted()) {
661 if (!decryptor_source_) {
663 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
668 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
669 if (!decrypt_config ||
670 !decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
671 stream_sample->writable_data(),
672 stream_sample->data_size())) {
674 LOG(ERROR) <<
"Cannot decrypt samples.";
679 stream_sample->set_dts(runs_->dts());
680 stream_sample->set_pts(runs_->cts());
681 stream_sample->set_duration(runs_->duration());
683 DVLOG(3) <<
"Pushing frame: "
684 <<
", key=" << runs_->is_keyframe()
685 <<
", dur=" << runs_->duration()
686 <<
", dts=" << runs_->dts()
687 <<
", cts=" << runs_->cts()
688 <<
", size=" << runs_->sample_size();
690 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
692 LOG(ERROR) <<
"Failed to process the sample.";
696 runs_->AdvanceSample();
700 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
702 while (mdat_tail_ < offset) {
705 queue_.
PeekAt(mdat_tail_, &buf, &size);
712 mdat_tail_ += box_sz;
714 queue_.
Trim(std::min(mdat_tail_, offset));
718 void MP4MediaParser::ChangeState(State new_state) {
719 DVLOG(2) <<
"Changing state: " << new_state;