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/aes_encryptor.h"
15 #include "packager/media/base/audio_stream_info.h"
16 #include "packager/media/base/buffer_reader.h"
17 #include "packager/media/base/decrypt_config.h"
18 #include "packager/media/base/key_source.h"
19 #include "packager/media/base/macros.h"
20 #include "packager/media/base/media_sample.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), moof_head_(0), mdat_tail_(0) {}
95 MP4MediaParser::~MP4MediaParser() {
96 STLDeleteValues(&decryptor_map_);
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;
113 void MP4MediaParser::Reset() {
121 DCHECK_NE(state_, kWaitingForInit);
123 ChangeState(kParsingBoxes);
127 DCHECK_NE(state_, kWaitingForInit);
129 if (state_ == kError)
132 queue_.Push(buf, size);
134 bool result, err =
false;
137 if (state_ == kParsingBoxes) {
138 result = ParseBox(&err);
140 DCHECK_EQ(kEmittingSamples, state_);
141 result = EnqueueSample(&err);
143 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
144 err = !ReadAndDiscardMDATsUntil(max_clear);
147 }
while (result && !err);
150 DLOG(ERROR) <<
"Error while parsing MP4";
161 scoped_ptr<File, FileCloser> file(
164 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
167 if (!file->Seek(0)) {
168 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
173 uint64_t file_position(0);
174 bool mdat_seen(
false);
176 const uint32_t kBoxHeaderReadSize(16);
177 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
178 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
179 if (bytes_read == 0) {
180 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
183 if (bytes_read < kBoxHeaderReadSize) {
184 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
192 LOG(ERROR) <<
"Could not start top level box from file '" << file_path
196 if (box_type == FOURCC_MDAT) {
198 }
else if (box_type == FOURCC_MOOV) {
204 if (!
Parse(&buffer[0], bytes_read)) {
205 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
208 uint64_t bytes_to_read = box_size - bytes_read;
209 buffer.resize(bytes_to_read);
210 while (bytes_to_read > 0) {
211 bytes_read = file->Read(&buffer[0], bytes_to_read);
212 if (bytes_read <= 0) {
213 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
217 if (!
Parse(&buffer[0], bytes_read)) {
218 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
221 bytes_to_read -= bytes_read;
227 file_position += box_size;
228 if (!file->Seek(file_position)) {
229 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
236 bool MP4MediaParser::ParseBox(
bool* err) {
239 queue_.Peek(&buf, &size);
244 if (reader.get() == NULL)
247 if (reader->type() == FOURCC_MDAT) {
251 NOTIMPLEMENTED() <<
" Files with MDAT before MOOV is not supported yet.";
257 mdat_tail_ = queue_.
head() + reader->size();
259 if (reader->type() == FOURCC_MOOV) {
260 *err = !ParseMoov(reader.get());
261 }
else if (reader->type() == FOURCC_MOOF) {
262 moof_head_ = queue_.
head();
263 *err = !ParseMoof(reader.get());
271 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
274 queue_.Pop(reader->size());
278 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
282 moov_.reset(
new Movie);
283 RCHECK(moov_->Parse(reader));
286 std::vector<scoped_refptr<StreamInfo> > streams;
288 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
289 track != moov_->tracks.end(); ++track) {
290 const uint32_t timescale = track->media.header.timescale;
293 uint64_t duration = 0;
294 if (track->media.header.duration > 0) {
295 duration = track->media.header.duration;
296 }
else if (moov_->extends.header.fragment_duration > 0) {
297 DCHECK(moov_->header.timescale != 0);
298 duration = Rescale(moov_->extends.header.fragment_duration,
299 moov_->header.timescale,
301 }
else if (moov_->header.duration > 0 &&
302 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
303 DCHECK(moov_->header.timescale != 0);
305 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
308 const SampleDescription& samp_descr =
309 track->media.information.sample_table.description;
315 if (moov_->extends.tracks.size() > 0) {
316 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
317 const TrackExtends& trex = moov_->extends.tracks[t];
318 if (trex.track_id == track->header.track_id) {
319 desc_idx = trex.default_sample_description_index;
324 const std::vector<ChunkInfo>& chunk_info =
325 track->media.information.sample_table.sample_to_chunk.chunk_info;
326 RCHECK(chunk_info.size() > 0);
327 desc_idx = chunk_info[0].sample_description_index;
329 RCHECK(desc_idx > 0);
332 if (samp_descr.type == kAudio) {
333 RCHECK(!samp_descr.audio_entries.empty());
337 if (desc_idx >= samp_descr.audio_entries.size())
340 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
341 const FourCC actual_format = entry.GetActualFormat();
342 AudioCodec codec = FourCCToAudioCodec(actual_format);
343 uint8_t num_channels = 0;
344 uint32_t sampling_frequency = 0;
345 uint8_t audio_object_type = 0;
346 uint32_t max_bitrate = 0;
347 uint32_t avg_bitrate = 0;
348 std::vector<uint8_t> extra_data;
350 switch (actual_format) {
354 if (entry.esds.es_descriptor.IsAAC()) {
356 const AACAudioSpecificConfig& aac_audio_specific_config =
357 entry.esds.aac_audio_specific_config;
358 num_channels = aac_audio_specific_config.num_channels();
359 sampling_frequency = aac_audio_specific_config.frequency();
360 audio_object_type = aac_audio_specific_config.audio_object_type();
361 extra_data = entry.esds.es_descriptor.decoder_specific_info();
363 }
else if (entry.esds.es_descriptor.IsDTS()) {
364 ObjectType audio_type = entry.esds.es_descriptor.object_type();
365 switch (audio_type) {
379 LOG(ERROR) <<
"Unsupported audio type " << audio_type
383 num_channels = entry.esds.aac_audio_specific_config.num_channels();
386 if (num_channels != kDtsAudioNumChannels) {
387 LOG(ERROR) <<
"Unsupported channel count " << num_channels
388 <<
" for audio type " << audio_type <<
".";
391 sampling_frequency = entry.samplerate;
392 max_bitrate = entry.esds.es_descriptor.max_bitrate();
393 avg_bitrate = entry.esds.es_descriptor.avg_bitrate();
395 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
396 << actual_format <<
" in stsd box.";
401 FALLTHROUGH_INTENDED;
403 FALLTHROUGH_INTENDED;
405 FALLTHROUGH_INTENDED;
407 FALLTHROUGH_INTENDED;
409 extra_data = entry.ddts.extra_data;
410 max_bitrate = entry.ddts.max_bitrate;
411 avg_bitrate = entry.ddts.avg_bitrate;
412 num_channels = entry.channelcount;
413 sampling_frequency = entry.samplerate;
416 extra_data = entry.dac3.data;
417 num_channels = entry.channelcount;
418 sampling_frequency = entry.samplerate;
421 extra_data = entry.dec3.data;
422 num_channels = entry.channelcount;
423 sampling_frequency = entry.samplerate;
426 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
427 << actual_format <<
" in stsd box.";
431 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
432 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
433 streams.push_back(
new AudioStreamInfo(
434 track->header.track_id,
439 track->media.header.language.code,
445 vector_as_array(&extra_data),
450 if (samp_descr.type == kVideo) {
451 RCHECK(!samp_descr.video_entries.empty());
452 if (desc_idx >= samp_descr.video_entries.size())
454 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
456 uint32_t coded_width = entry.width;
457 uint32_t coded_height = entry.height;
458 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
459 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
460 if (pixel_width == 0 && pixel_height == 0) {
464 std::string codec_string;
465 uint8_t nalu_length_size = 0;
467 const FourCC actual_format = entry.GetActualFormat();
468 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
469 switch (actual_format) {
471 AVCDecoderConfiguration avc_config;
472 if (!avc_config.Parse(entry.codec_config_record.data)) {
473 LOG(ERROR) <<
"Failed to parse avcc.";
476 codec_string = avc_config.GetCodecString();
477 nalu_length_size = avc_config.length_size();
479 if (coded_width != avc_config.coded_width() ||
480 coded_height != avc_config.coded_height()) {
481 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
482 <<
"," << coded_height
483 <<
") does not match with resolution in "
484 "AVCDecoderConfigurationRecord ("
485 << avc_config.coded_width() <<
","
486 << avc_config.coded_height()
487 <<
"). Use AVCDecoderConfigurationRecord.";
488 coded_width = avc_config.coded_width();
489 coded_height = avc_config.coded_height();
492 if (pixel_width != avc_config.pixel_width() ||
493 pixel_height != avc_config.pixel_height()) {
494 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
495 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
497 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
499 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
500 <<
"). Use AVCDecoderConfigurationRecord.";
501 pixel_width = avc_config.pixel_width();
502 pixel_height = avc_config.pixel_height();
508 HEVCDecoderConfiguration hevc_config;
509 if (!hevc_config.Parse(entry.codec_config_record.data)) {
510 LOG(ERROR) <<
"Failed to parse hevc.";
513 codec_string = hevc_config.GetCodecString(video_codec);
514 nalu_length_size = hevc_config.length_size();
520 VPCodecConfiguration vp_config;
521 if (!vp_config.Parse(entry.codec_config_record.data)) {
522 LOG(ERROR) <<
"Failed to parse vpcc.";
525 codec_string = vp_config.GetCodecString(video_codec);
529 LOG(ERROR) <<
"Unsupported video format "
530 << FourCCToString(actual_format) <<
" in stsd box.";
534 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
535 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
536 streams.push_back(
new VideoStreamInfo(
537 track->header.track_id, timescale, duration, video_codec,
538 codec_string, track->media.header.language.code, coded_width,
539 coded_height, pixel_width, pixel_height,
541 nalu_length_size, vector_as_array(&entry.codec_config_record.data),
542 entry.codec_config_record.data.size(), is_encrypted));
546 init_cb_.Run(streams);
547 if (!FetchKeysIfNecessary(moov_->pssh))
549 runs_.reset(
new TrackRunIterator(moov_.get()));
550 RCHECK(runs_->Init());
551 ChangeState(kEmittingSamples);
555 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
559 RCHECK(moof.Parse(reader));
561 runs_.reset(
new TrackRunIterator(moov_.get()));
562 RCHECK(runs_->Init(moof));
563 if (!FetchKeysIfNecessary(moof.pssh))
565 ChangeState(kEmittingSamples);
569 bool MP4MediaParser::FetchKeysIfNecessary(
570 const std::vector<ProtectionSystemSpecificHeader>& headers) {
575 if (!decryption_key_source_)
580 std::vector<uint8_t> widevine_system_id;
581 base::HexStringToBytes(kWidevineKeySystemId, &widevine_system_id);
582 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
583 headers.begin(); iter != headers.end(); ++iter) {
584 if (iter->system_id == widevine_system_id) {
585 Status status = decryption_key_source_->
FetchKeys(iter->data);
587 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
594 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
598 bool MP4MediaParser::EnqueueSample(
bool* err) {
599 if (!runs_->IsRunValid()) {
602 if (!queue_.
Trim(mdat_tail_))
605 ChangeState(kParsingBoxes);
609 if (!runs_->IsSampleValid()) {
618 queue_.Peek(&buf, &buf_size);
623 if (!runs_->is_audio() && !runs_->is_video())
633 if (runs_->AuxInfoNeedsToBeCached()) {
634 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
635 if (buf_size < runs_->aux_info_size())
637 *err = !runs_->CacheAuxInfo(buf, buf_size);
641 int64_t sample_offset = runs_->sample_offset() + moof_head_;
642 queue_.
PeekAt(sample_offset, &buf, &buf_size);
643 if (buf_size < runs_->sample_size()) {
644 if (sample_offset < queue_.
head()) {
645 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
646 <<
" < " << queue_.
head();
653 buf, runs_->sample_size(), runs_->is_keyframe()));
654 if (runs_->is_encrypted()) {
655 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
656 if (!decrypt_config ||
657 !DecryptSampleBuffer(decrypt_config.get(),
658 stream_sample->writable_data(),
659 stream_sample->data_size())) {
661 LOG(ERROR) <<
"Cannot decrypt samples.";
666 stream_sample->set_dts(runs_->dts());
667 stream_sample->set_pts(runs_->cts());
668 stream_sample->set_duration(runs_->duration());
670 DVLOG(3) <<
"Pushing frame: "
671 <<
", key=" << runs_->is_keyframe()
672 <<
", dur=" << runs_->duration()
673 <<
", dts=" << runs_->dts()
674 <<
", cts=" << runs_->cts()
675 <<
", size=" << runs_->sample_size();
677 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
679 LOG(ERROR) <<
"Failed to process the sample.";
683 runs_->AdvanceSample();
687 bool MP4MediaParser::DecryptSampleBuffer(
const DecryptConfig* decrypt_config,
689 size_t buffer_size) {
690 DCHECK(decrypt_config);
693 if (!decryption_key_source_) {
694 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
700 AesCtrEncryptor* encryptor;
701 DecryptorMap::iterator found = decryptor_map_.find(decrypt_config->key_id());
702 if (found == decryptor_map_.end()) {
705 Status status(decryption_key_source_->
GetKey(decrypt_config->key_id(),
708 LOG(ERROR) <<
"Error retrieving decryption key: " << status;
711 scoped_ptr<AesCtrEncryptor> new_encryptor(
new AesCtrEncryptor);
712 if (!new_encryptor->InitializeWithIv(key.key, decrypt_config->iv())) {
713 LOG(ERROR) <<
"Failed to initialize AesCtrEncryptor for decryption.";
716 encryptor = new_encryptor.release();
717 decryptor_map_[decrypt_config->key_id()] = encryptor;
719 encryptor = found->second;
721 if (!encryptor->SetIv(decrypt_config->iv())) {
722 LOG(ERROR) <<
"Invalid initialization vector.";
726 if (decrypt_config->subsamples().empty()) {
728 if (!encryptor->Decrypt(buffer, buffer_size, buffer)) {
729 LOG(ERROR) <<
"Error during bulk sample decryption.";
736 const std::vector<SubsampleEntry>& subsamples = decrypt_config->subsamples();
737 uint8_t* current_ptr = buffer;
738 const uint8_t* buffer_end = buffer + buffer_size;
739 current_ptr += decrypt_config->data_offset();
740 if (current_ptr > buffer_end) {
741 LOG(ERROR) <<
"Subsample data_offset too large.";
744 for (std::vector<SubsampleEntry>::const_iterator iter = subsamples.begin();
745 iter != subsamples.end();
747 if ((current_ptr + iter->clear_bytes + iter->cipher_bytes) > buffer_end) {
748 LOG(ERROR) <<
"Subsamples overflow sample buffer.";
751 current_ptr += iter->clear_bytes;
752 if (!encryptor->Decrypt(current_ptr, iter->cipher_bytes, current_ptr)) {
753 LOG(ERROR) <<
"Error decrypting subsample buffer.";
756 current_ptr += iter->cipher_bytes;
761 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
763 while (mdat_tail_ < offset) {
766 queue_.
PeekAt(mdat_tail_, &buf, &size);
773 mdat_tail_ += box_sz;
775 queue_.
Trim(std::min(mdat_tail_, offset));
779 void MP4MediaParser::ChangeState(State new_state) {
780 DVLOG(2) <<
"Changing state: " << new_state;