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/video_stream_info.h"
21 #include "packager/media/file/file.h"
22 #include "packager/media/file/file_closer.h"
23 #include "packager/media/filters/avc_decoder_configuration.h"
24 #include "packager/media/filters/hevc_decoder_configuration.h"
25 #include "packager/media/filters/vp_codec_configuration.h"
26 #include "packager/media/formats/mp4/box_definitions.h"
27 #include "packager/media/formats/mp4/box_reader.h"
28 #include "packager/media/formats/mp4/es_descriptor.h"
29 #include "packager/media/formats/mp4/rcheck.h"
30 #include "packager/media/formats/mp4/track_run_iterator.h"
32 namespace edash_packager {
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) {
81 return kUnknownAudioCodec;
85 const char kWidevineKeySystemId[] =
"edef8ba979d64acea3c827dcd51d21ed";
87 const uint8_t kDtsAudioNumChannels = 6;
91 MP4MediaParser::MP4MediaParser()
92 : state_(kWaitingForInit),
93 decryption_key_source_(NULL),
97 MP4MediaParser::~MP4MediaParser() {}
100 const NewSampleCB& new_sample_cb,
102 DCHECK_EQ(state_, kWaitingForInit);
103 DCHECK(init_cb_.is_null());
104 DCHECK(!init_cb.is_null());
105 DCHECK(!new_sample_cb.is_null());
107 ChangeState(kParsingBoxes);
109 new_sample_cb_ = new_sample_cb;
110 decryption_key_source_ = decryption_key_source;
111 if (decryption_key_source)
115 void MP4MediaParser::Reset() {
123 DCHECK_NE(state_, kWaitingForInit);
125 ChangeState(kParsingBoxes);
130 DCHECK_NE(state_, kWaitingForInit);
132 if (state_ == kError)
135 queue_.Push(buf, size);
137 bool result, err =
false;
140 if (state_ == kParsingBoxes) {
141 result = ParseBox(&err);
143 DCHECK_EQ(kEmittingSamples, state_);
144 result = EnqueueSample(&err);
146 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
147 err = !ReadAndDiscardMDATsUntil(max_clear);
150 }
while (result && !err);
153 DLOG(ERROR) <<
"Error while parsing MP4";
164 scoped_ptr<File, FileCloser> file(
167 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
170 if (!file->Seek(0)) {
171 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
176 uint64_t file_position(0);
177 bool mdat_seen(
false);
179 const uint32_t kBoxHeaderReadSize(16);
180 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
181 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
182 if (bytes_read == 0) {
183 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
186 if (bytes_read < kBoxHeaderReadSize) {
187 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
195 LOG(ERROR) <<
"Could not start top level box from file '" << file_path
199 if (box_type == FOURCC_MDAT) {
201 }
else if (box_type == FOURCC_MOOV) {
207 if (!
Parse(&buffer[0], bytes_read)) {
208 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
211 uint64_t bytes_to_read = box_size - bytes_read;
212 buffer.resize(bytes_to_read);
213 while (bytes_to_read > 0) {
214 bytes_read = file->Read(&buffer[0], bytes_to_read);
215 if (bytes_read <= 0) {
216 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
220 if (!
Parse(&buffer[0], bytes_read)) {
221 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
224 bytes_to_read -= bytes_read;
230 file_position += box_size;
231 if (!file->Seek(file_position)) {
232 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
239 bool MP4MediaParser::ParseBox(
bool* err) {
242 queue_.Peek(&buf, &size);
247 if (reader.get() == NULL)
250 if (reader->type() == FOURCC_MDAT) {
254 NOTIMPLEMENTED() <<
" Files with MDAT before MOOV is not supported yet.";
260 mdat_tail_ = queue_.
head() + reader->size();
262 if (reader->type() == FOURCC_MOOV) {
263 *err = !ParseMoov(reader.get());
264 }
else if (reader->type() == FOURCC_MOOF) {
265 moof_head_ = queue_.
head();
266 *err = !ParseMoof(reader.get());
274 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
277 queue_.Pop(reader->size());
281 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
285 moov_.reset(
new Movie);
286 RCHECK(moov_->Parse(reader));
289 std::vector<scoped_refptr<StreamInfo> > streams;
291 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
292 track != moov_->tracks.end(); ++track) {
293 const uint32_t timescale = track->media.header.timescale;
296 uint64_t duration = 0;
297 if (track->media.header.duration > 0) {
298 duration = track->media.header.duration;
299 }
else if (moov_->extends.header.fragment_duration > 0) {
300 DCHECK(moov_->header.timescale != 0);
301 duration = Rescale(moov_->extends.header.fragment_duration,
302 moov_->header.timescale,
304 }
else if (moov_->header.duration > 0 &&
305 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
306 DCHECK(moov_->header.timescale != 0);
308 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
311 const SampleDescription& samp_descr =
312 track->media.information.sample_table.description;
318 if (moov_->extends.tracks.size() > 0) {
319 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
320 const TrackExtends& trex = moov_->extends.tracks[t];
321 if (trex.track_id == track->header.track_id) {
322 desc_idx = trex.default_sample_description_index;
327 const std::vector<ChunkInfo>& chunk_info =
328 track->media.information.sample_table.sample_to_chunk.chunk_info;
329 RCHECK(chunk_info.size() > 0);
330 desc_idx = chunk_info[0].sample_description_index;
332 RCHECK(desc_idx > 0);
335 if (samp_descr.type == kAudio) {
336 RCHECK(!samp_descr.audio_entries.empty());
340 if (desc_idx >= samp_descr.audio_entries.size())
343 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
344 const FourCC actual_format = entry.GetActualFormat();
345 AudioCodec codec = FourCCToAudioCodec(actual_format);
346 uint8_t num_channels = 0;
347 uint32_t sampling_frequency = 0;
348 uint8_t audio_object_type = 0;
349 uint32_t max_bitrate = 0;
350 uint32_t avg_bitrate = 0;
351 std::vector<uint8_t> extra_data;
353 switch (actual_format) {
357 if (entry.esds.es_descriptor.IsAAC()) {
359 const AACAudioSpecificConfig& aac_audio_specific_config =
360 entry.esds.aac_audio_specific_config;
361 num_channels = aac_audio_specific_config.num_channels();
362 sampling_frequency = aac_audio_specific_config.frequency();
363 audio_object_type = aac_audio_specific_config.audio_object_type();
364 extra_data = entry.esds.es_descriptor.decoder_specific_info();
366 }
else if (entry.esds.es_descriptor.IsDTS()) {
367 ObjectType audio_type = entry.esds.es_descriptor.object_type();
368 switch (audio_type) {
382 LOG(ERROR) <<
"Unsupported audio type " << audio_type
386 num_channels = entry.esds.aac_audio_specific_config.num_channels();
389 if (num_channels != kDtsAudioNumChannels) {
390 LOG(ERROR) <<
"Unsupported channel count " << num_channels
391 <<
" for audio type " << audio_type <<
".";
394 sampling_frequency = entry.samplerate;
395 max_bitrate = entry.esds.es_descriptor.max_bitrate();
396 avg_bitrate = entry.esds.es_descriptor.avg_bitrate();
398 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
399 << actual_format <<
" in stsd box.";
404 FALLTHROUGH_INTENDED;
406 FALLTHROUGH_INTENDED;
408 FALLTHROUGH_INTENDED;
410 FALLTHROUGH_INTENDED;
412 extra_data = entry.ddts.extra_data;
413 max_bitrate = entry.ddts.max_bitrate;
414 avg_bitrate = entry.ddts.avg_bitrate;
415 num_channels = entry.channelcount;
416 sampling_frequency = entry.samplerate;
419 extra_data = entry.dac3.data;
420 num_channels = entry.channelcount;
421 sampling_frequency = entry.samplerate;
424 extra_data = entry.dec3.data;
425 num_channels = entry.channelcount;
426 sampling_frequency = entry.samplerate;
429 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
430 << actual_format <<
" in stsd box.";
434 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
435 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
436 streams.push_back(
new AudioStreamInfo(
437 track->header.track_id,
442 track->media.header.language.code,
453 if (samp_descr.type == kVideo) {
454 RCHECK(!samp_descr.video_entries.empty());
455 if (desc_idx >= samp_descr.video_entries.size())
457 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
459 uint32_t coded_width = entry.width;
460 uint32_t coded_height = entry.height;
461 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
462 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
463 if (pixel_width == 0 && pixel_height == 0) {
467 std::string codec_string;
468 uint8_t nalu_length_size = 0;
470 const FourCC actual_format = entry.GetActualFormat();
471 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
472 switch (actual_format) {
474 AVCDecoderConfiguration avc_config;
475 if (!avc_config.Parse(entry.codec_config_record.data)) {
476 LOG(ERROR) <<
"Failed to parse avcc.";
479 codec_string = avc_config.GetCodecString();
480 nalu_length_size = avc_config.length_size();
482 if (coded_width != avc_config.coded_width() ||
483 coded_height != avc_config.coded_height()) {
484 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
485 <<
"," << coded_height
486 <<
") does not match with resolution in "
487 "AVCDecoderConfigurationRecord ("
488 << avc_config.coded_width() <<
","
489 << avc_config.coded_height()
490 <<
"). Use AVCDecoderConfigurationRecord.";
491 coded_width = avc_config.coded_width();
492 coded_height = avc_config.coded_height();
495 if (pixel_width != avc_config.pixel_width() ||
496 pixel_height != avc_config.pixel_height()) {
497 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
498 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
500 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
502 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
503 <<
"). Use AVCDecoderConfigurationRecord.";
504 pixel_width = avc_config.pixel_width();
505 pixel_height = avc_config.pixel_height();
511 HEVCDecoderConfiguration hevc_config;
512 if (!hevc_config.Parse(entry.codec_config_record.data)) {
513 LOG(ERROR) <<
"Failed to parse hevc.";
516 codec_string = hevc_config.GetCodecString(video_codec);
517 nalu_length_size = hevc_config.length_size();
523 VPCodecConfiguration vp_config;
524 if (!vp_config.Parse(entry.codec_config_record.data)) {
525 LOG(ERROR) <<
"Failed to parse vpcc.";
528 codec_string = vp_config.GetCodecString(video_codec);
532 LOG(ERROR) <<
"Unsupported video format "
533 << FourCCToString(actual_format) <<
" in stsd box.";
537 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
538 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
539 streams.push_back(
new VideoStreamInfo(
540 track->header.track_id, timescale, duration, video_codec,
541 codec_string, track->media.header.language.code, coded_width,
542 coded_height, pixel_width, pixel_height,
544 nalu_length_size, entry.codec_config_record.data.data(),
545 entry.codec_config_record.data.size(), is_encrypted));
549 init_cb_.Run(streams);
550 if (!FetchKeysIfNecessary(moov_->pssh))
552 runs_.reset(
new TrackRunIterator(moov_.get()));
553 RCHECK(runs_->Init());
554 ChangeState(kEmittingSamples);
558 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
562 RCHECK(moof.Parse(reader));
564 runs_.reset(
new TrackRunIterator(moov_.get()));
565 RCHECK(runs_->Init(moof));
566 if (!FetchKeysIfNecessary(moof.pssh))
568 ChangeState(kEmittingSamples);
572 bool MP4MediaParser::FetchKeysIfNecessary(
573 const std::vector<ProtectionSystemSpecificHeader>& headers) {
578 if (!decryption_key_source_)
583 std::vector<uint8_t> widevine_system_id;
584 base::HexStringToBytes(kWidevineKeySystemId, &widevine_system_id);
585 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
586 headers.begin(); iter != headers.end(); ++iter) {
587 if (iter->system_id == widevine_system_id) {
588 Status status = decryption_key_source_->
FetchKeys(iter->data);
590 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
597 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
601 bool MP4MediaParser::EnqueueSample(
bool* err) {
602 if (!runs_->IsRunValid()) {
605 if (!queue_.
Trim(mdat_tail_))
608 ChangeState(kParsingBoxes);
612 if (!runs_->IsSampleValid()) {
621 queue_.Peek(&buf, &buf_size);
626 if (!runs_->is_audio() && !runs_->is_video())
636 if (runs_->AuxInfoNeedsToBeCached()) {
637 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
638 if (buf_size < runs_->aux_info_size())
640 *err = !runs_->CacheAuxInfo(buf, buf_size);
644 int64_t sample_offset = runs_->sample_offset() + moof_head_;
645 queue_.
PeekAt(sample_offset, &buf, &buf_size);
646 if (buf_size < runs_->sample_size()) {
647 if (sample_offset < queue_.
head()) {
648 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
649 <<
" < " << queue_.
head();
656 buf, runs_->sample_size(), runs_->is_keyframe()));
657 if (runs_->is_encrypted()) {
658 if (!decryptor_source_) {
660 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
665 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
666 if (!decrypt_config ||
667 !decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
668 stream_sample->writable_data(),
669 stream_sample->data_size())) {
671 LOG(ERROR) <<
"Cannot decrypt samples.";
676 stream_sample->set_dts(runs_->dts());
677 stream_sample->set_pts(runs_->cts());
678 stream_sample->set_duration(runs_->duration());
680 DVLOG(3) <<
"Pushing frame: "
681 <<
", key=" << runs_->is_keyframe()
682 <<
", dur=" << runs_->duration()
683 <<
", dts=" << runs_->dts()
684 <<
", cts=" << runs_->cts()
685 <<
", size=" << runs_->sample_size();
687 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
689 LOG(ERROR) <<
"Failed to process the sample.";
693 runs_->AdvanceSample();
697 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
699 while (mdat_tail_ < offset) {
702 queue_.
PeekAt(mdat_tail_, &buf, &size);
709 mdat_tail_ += box_sz;
711 queue_.
Trim(std::min(mdat_tail_, offset));
715 void MP4MediaParser::ChangeState(State new_state) {
716 DVLOG(2) <<
"Changing state: " << new_state;