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) {
80 return kUnknownAudioCodec;
84 const char kWidevineKeySystemId[] =
"edef8ba979d64acea3c827dcd51d21ed";
86 const uint8_t kDtsAudioNumChannels = 6;
90 MP4MediaParser::MP4MediaParser()
91 : state_(kWaitingForInit), moof_head_(0), mdat_tail_(0) {}
93 MP4MediaParser::~MP4MediaParser() {
94 STLDeleteValues(&decryptor_map_);
98 const NewSampleCB& new_sample_cb,
100 DCHECK_EQ(state_, kWaitingForInit);
101 DCHECK(init_cb_.is_null());
102 DCHECK(!init_cb.is_null());
103 DCHECK(!new_sample_cb.is_null());
105 ChangeState(kParsingBoxes);
107 new_sample_cb_ = new_sample_cb;
108 decryption_key_source_ = decryption_key_source;
111 void MP4MediaParser::Reset() {
119 DCHECK_NE(state_, kWaitingForInit);
121 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 top level box from file '" << file_path
194 if (box_type == FOURCC_MDAT) {
196 }
else if (box_type == FOURCC_MOOV) {
202 if (!
Parse(&buffer[0], bytes_read)) {
203 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
206 uint64_t bytes_to_read = box_size - bytes_read;
207 buffer.resize(bytes_to_read);
208 while (bytes_to_read > 0) {
209 bytes_read = file->Read(&buffer[0], bytes_to_read);
210 if (bytes_read <= 0) {
211 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
215 if (!
Parse(&buffer[0], bytes_read)) {
216 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
219 bytes_to_read -= bytes_read;
225 file_position += box_size;
226 if (!file->Seek(file_position)) {
227 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
234 bool MP4MediaParser::ParseBox(
bool* err) {
237 queue_.Peek(&buf, &size);
242 if (reader.get() == NULL)
245 if (reader->type() == FOURCC_MDAT) {
249 NOTIMPLEMENTED() <<
" Files with MDAT before MOOV is not supported yet.";
255 mdat_tail_ = queue_.
head() + reader->size();
257 if (reader->type() == FOURCC_MOOV) {
258 *err = !ParseMoov(reader.get());
259 }
else if (reader->type() == FOURCC_MOOF) {
260 moof_head_ = queue_.
head();
261 *err = !ParseMoof(reader.get());
269 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
272 queue_.Pop(reader->size());
276 bool MP4MediaParser::ParseMoov(BoxReader* reader) {
280 moov_.reset(
new Movie);
281 RCHECK(moov_->Parse(reader));
284 std::vector<scoped_refptr<StreamInfo> > streams;
286 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
287 track != moov_->tracks.end(); ++track) {
288 const uint32_t timescale = track->media.header.timescale;
291 uint64_t duration = 0;
292 if (track->media.header.duration > 0) {
293 duration = track->media.header.duration;
294 }
else if (moov_->extends.header.fragment_duration > 0) {
295 DCHECK(moov_->header.timescale != 0);
296 duration = Rescale(moov_->extends.header.fragment_duration,
297 moov_->header.timescale,
299 }
else if (moov_->header.duration > 0 &&
300 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
301 DCHECK(moov_->header.timescale != 0);
303 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
306 const SampleDescription& samp_descr =
307 track->media.information.sample_table.description;
313 if (moov_->extends.tracks.size() > 0) {
314 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
315 const TrackExtends& trex = moov_->extends.tracks[t];
316 if (trex.track_id == track->header.track_id) {
317 desc_idx = trex.default_sample_description_index;
322 const std::vector<ChunkInfo>& chunk_info =
323 track->media.information.sample_table.sample_to_chunk.chunk_info;
324 RCHECK(chunk_info.size() > 0);
325 desc_idx = chunk_info[0].sample_description_index;
327 RCHECK(desc_idx > 0);
330 if (samp_descr.type == kAudio) {
331 RCHECK(!samp_descr.audio_entries.empty());
335 if (desc_idx >= samp_descr.audio_entries.size())
338 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
339 const FourCC actual_format = entry.GetActualFormat();
340 AudioCodec codec = FourCCToAudioCodec(actual_format);
341 uint8_t num_channels = 0;
342 uint32_t sampling_frequency = 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> extra_data;
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 extra_data = 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 extra_data = 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 extra_data = entry.dac3.data;
415 num_channels = entry.channelcount;
416 sampling_frequency = entry.samplerate;
419 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
420 << actual_format <<
" in stsd box.";
424 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
425 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
426 streams.push_back(
new AudioStreamInfo(
427 track->header.track_id,
432 track->media.header.language.code,
438 vector_as_array(&extra_data),
443 if (samp_descr.type == kVideo) {
444 RCHECK(!samp_descr.video_entries.empty());
445 if (desc_idx >= samp_descr.video_entries.size())
447 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
449 uint32_t coded_width = entry.width;
450 uint32_t coded_height = entry.height;
451 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
452 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
453 if (pixel_width == 0 && pixel_height == 0) {
457 std::string codec_string;
458 uint8_t nalu_length_size = 0;
460 const FourCC actual_format = entry.GetActualFormat();
461 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
462 switch (actual_format) {
464 AVCDecoderConfiguration avc_config;
465 if (!avc_config.Parse(entry.codec_config_record.data)) {
466 LOG(ERROR) <<
"Failed to parse avcc.";
469 codec_string = avc_config.GetCodecString();
470 nalu_length_size = avc_config.length_size();
472 if (coded_width != avc_config.coded_width() ||
473 coded_height != avc_config.coded_height()) {
474 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
475 <<
"," << coded_height
476 <<
") does not match with resolution in "
477 "AVCDecoderConfigurationRecord ("
478 << avc_config.coded_width() <<
","
479 << avc_config.coded_height()
480 <<
"). Use AVCDecoderConfigurationRecord.";
481 coded_width = avc_config.coded_width();
482 coded_height = avc_config.coded_height();
485 if (pixel_width != avc_config.pixel_width() ||
486 pixel_height != avc_config.pixel_height()) {
487 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
488 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
490 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
492 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
493 <<
"). Use AVCDecoderConfigurationRecord.";
494 pixel_width = avc_config.pixel_width();
495 pixel_height = avc_config.pixel_height();
501 HEVCDecoderConfiguration hevc_config;
502 if (!hevc_config.Parse(entry.codec_config_record.data)) {
503 LOG(ERROR) <<
"Failed to parse hevc.";
506 codec_string = hevc_config.GetCodecString(video_codec);
507 nalu_length_size = hevc_config.length_size();
513 VPCodecConfiguration vp_config;
514 if (!vp_config.Parse(entry.codec_config_record.data)) {
515 LOG(ERROR) <<
"Failed to parse vpcc.";
518 codec_string = vp_config.GetCodecString(video_codec);
522 LOG(ERROR) <<
"Unsupported video format "
523 << FourCCToString(actual_format) <<
" in stsd box.";
527 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
528 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
529 streams.push_back(
new VideoStreamInfo(
530 track->header.track_id, timescale, duration, video_codec,
531 codec_string, track->media.header.language.code, coded_width,
532 coded_height, pixel_width, pixel_height,
534 nalu_length_size, vector_as_array(&entry.codec_config_record.data),
535 entry.codec_config_record.data.size(), is_encrypted));
539 init_cb_.Run(streams);
540 if (!FetchKeysIfNecessary(moov_->pssh))
542 runs_.reset(
new TrackRunIterator(moov_.get()));
543 RCHECK(runs_->Init());
544 ChangeState(kEmittingSamples);
548 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
552 RCHECK(moof.Parse(reader));
554 runs_.reset(
new TrackRunIterator(moov_.get()));
555 RCHECK(runs_->Init(moof));
556 if (!FetchKeysIfNecessary(moof.pssh))
558 ChangeState(kEmittingSamples);
562 bool MP4MediaParser::FetchKeysIfNecessary(
563 const std::vector<ProtectionSystemSpecificHeader>& headers) {
568 if (!decryption_key_source_)
573 std::vector<uint8_t> widevine_system_id;
574 base::HexStringToBytes(kWidevineKeySystemId, &widevine_system_id);
575 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
576 headers.begin(); iter != headers.end(); ++iter) {
577 if (iter->system_id == widevine_system_id) {
578 Status status = decryption_key_source_->
FetchKeys(iter->data);
580 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
587 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
591 bool MP4MediaParser::EnqueueSample(
bool* err) {
592 if (!runs_->IsRunValid()) {
595 if (!queue_.
Trim(mdat_tail_))
598 ChangeState(kParsingBoxes);
602 if (!runs_->IsSampleValid()) {
611 queue_.Peek(&buf, &buf_size);
616 if (!runs_->is_audio() && !runs_->is_video())
626 if (runs_->AuxInfoNeedsToBeCached()) {
627 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
628 if (buf_size < runs_->aux_info_size())
630 *err = !runs_->CacheAuxInfo(buf, buf_size);
634 int64_t sample_offset = runs_->sample_offset() + moof_head_;
635 queue_.
PeekAt(sample_offset, &buf, &buf_size);
636 if (buf_size < runs_->sample_size()) {
637 if (sample_offset < queue_.
head()) {
638 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
639 <<
" < " << queue_.
head();
646 buf, runs_->sample_size(), runs_->is_keyframe()));
647 if (runs_->is_encrypted()) {
648 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
649 if (!decrypt_config ||
650 !DecryptSampleBuffer(decrypt_config.get(),
651 stream_sample->writable_data(),
652 stream_sample->data_size())) {
654 LOG(ERROR) <<
"Cannot decrypt samples.";
659 stream_sample->set_dts(runs_->dts());
660 stream_sample->set_pts(runs_->cts());
661 stream_sample->set_duration(runs_->duration());
663 DVLOG(3) <<
"Pushing frame: "
664 <<
", key=" << runs_->is_keyframe()
665 <<
", dur=" << runs_->duration()
666 <<
", dts=" << runs_->dts()
667 <<
", cts=" << runs_->cts()
668 <<
", size=" << runs_->sample_size();
670 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
672 LOG(ERROR) <<
"Failed to process the sample.";
676 runs_->AdvanceSample();
680 bool MP4MediaParser::DecryptSampleBuffer(
const DecryptConfig* decrypt_config,
682 size_t buffer_size) {
683 DCHECK(decrypt_config);
686 if (!decryption_key_source_) {
687 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
693 AesCtrEncryptor* encryptor;
694 DecryptorMap::iterator found = decryptor_map_.find(decrypt_config->key_id());
695 if (found == decryptor_map_.end()) {
698 Status status(decryption_key_source_->
GetKey(decrypt_config->key_id(),
701 LOG(ERROR) <<
"Error retrieving decryption key: " << status;
704 scoped_ptr<AesCtrEncryptor> new_encryptor(
new AesCtrEncryptor);
705 if (!new_encryptor->InitializeWithIv(key.key, decrypt_config->iv())) {
706 LOG(ERROR) <<
"Failed to initialize AesCtrEncryptor for decryption.";
709 encryptor = new_encryptor.release();
710 decryptor_map_[decrypt_config->key_id()] = encryptor;
712 encryptor = found->second;
714 if (!encryptor->SetIv(decrypt_config->iv())) {
715 LOG(ERROR) <<
"Invalid initialization vector.";
719 if (decrypt_config->subsamples().empty()) {
721 if (!encryptor->Decrypt(buffer, buffer_size, buffer)) {
722 LOG(ERROR) <<
"Error during bulk sample decryption.";
729 const std::vector<SubsampleEntry>& subsamples = decrypt_config->subsamples();
730 uint8_t* current_ptr = buffer;
731 const uint8_t* buffer_end = buffer + buffer_size;
732 current_ptr += decrypt_config->data_offset();
733 if (current_ptr > buffer_end) {
734 LOG(ERROR) <<
"Subsample data_offset too large.";
737 for (std::vector<SubsampleEntry>::const_iterator iter = subsamples.begin();
738 iter != subsamples.end();
740 if ((current_ptr + iter->clear_bytes + iter->cipher_bytes) > buffer_end) {
741 LOG(ERROR) <<
"Subsamples overflow sample buffer.";
744 current_ptr += iter->clear_bytes;
745 if (!encryptor->Decrypt(current_ptr, iter->cipher_bytes, current_ptr)) {
746 LOG(ERROR) <<
"Error decrypting subsample buffer.";
749 current_ptr += iter->cipher_bytes;
754 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
756 while (mdat_tail_ < offset) {
759 queue_.
PeekAt(mdat_tail_, &buf, &size);
766 mdat_tail_ += box_sz;
768 queue_.
Trim(std::min(mdat_tail_, offset));
772 void MP4MediaParser::ChangeState(State new_state) {
773 DVLOG(2) <<
"Changing state: " << new_state;