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/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) {
79 return kUnknownAudioCodec;
83 const char kWidevineKeySystemId[] =
"edef8ba979d64acea3c827dcd51d21ed";
85 const uint8_t kDtsAudioNumChannels = 6;
89 MP4MediaParser::MP4MediaParser()
90 : state_(kWaitingForInit), moof_head_(0), mdat_tail_(0) {}
92 MP4MediaParser::~MP4MediaParser() {
93 STLDeleteValues(&decryptor_map_);
97 const NewSampleCB& new_sample_cb,
99 DCHECK_EQ(state_, kWaitingForInit);
100 DCHECK(init_cb_.is_null());
101 DCHECK(!init_cb.is_null());
102 DCHECK(!new_sample_cb.is_null());
104 ChangeState(kParsingBoxes);
106 new_sample_cb_ = new_sample_cb;
107 decryption_key_source_ = decryption_key_source;
110 void MP4MediaParser::Reset() {
118 DCHECK_NE(state_, kWaitingForInit);
120 ChangeState(kParsingBoxes);
124 DCHECK_NE(state_, kWaitingForInit);
126 if (state_ == kError)
129 queue_.Push(buf, size);
131 bool result, err =
false;
134 if (state_ == kParsingBoxes) {
135 result = ParseBox(&err);
137 DCHECK_EQ(kEmittingSamples, state_);
138 result = EnqueueSample(&err);
140 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
141 err = !ReadAndDiscardMDATsUntil(max_clear);
144 }
while (result && !err);
147 DLOG(ERROR) <<
"Error while parsing MP4";
158 scoped_ptr<File, FileCloser> file(
161 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
164 if (!file->Seek(0)) {
165 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
170 uint64_t file_position(0);
171 bool mdat_seen(
false);
173 const uint32_t kBoxHeaderReadSize(16);
174 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
175 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
176 if (bytes_read == 0) {
177 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
180 if (bytes_read < kBoxHeaderReadSize) {
181 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
189 LOG(ERROR) <<
"Could not start top level 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 (track->media.handler.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 AudioCodec codec = FourCCToAudioCodec(actual_format);
340 uint8_t num_channels = 0;
341 uint32_t sampling_frequency = 0;
342 uint8_t audio_object_type = 0;
343 uint32_t max_bitrate = 0;
344 uint32_t avg_bitrate = 0;
345 std::vector<uint8_t> extra_data;
347 switch (actual_format) {
351 if (entry.esds.es_descriptor.IsAAC()) {
353 const AACAudioSpecificConfig& aac_audio_specific_config =
354 entry.esds.aac_audio_specific_config;
355 num_channels = aac_audio_specific_config.num_channels();
356 sampling_frequency = aac_audio_specific_config.frequency();
357 audio_object_type = aac_audio_specific_config.audio_object_type();
358 extra_data = entry.esds.es_descriptor.decoder_specific_info();
360 }
else if (entry.esds.es_descriptor.IsDTS()) {
361 ObjectType audio_type = entry.esds.es_descriptor.object_type();
362 switch (audio_type) {
376 LOG(ERROR) <<
"Unsupported audio type " << audio_type
380 num_channels = entry.esds.aac_audio_specific_config.num_channels();
383 if (num_channels != kDtsAudioNumChannels) {
384 LOG(ERROR) <<
"Unsupported channel count " << num_channels
385 <<
" for audio type " << audio_type <<
".";
388 sampling_frequency = entry.samplerate;
389 max_bitrate = entry.esds.es_descriptor.max_bitrate();
390 avg_bitrate = entry.esds.es_descriptor.avg_bitrate();
392 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
393 << actual_format <<
" in stsd box.";
401 extra_data = entry.ddts.extra_data;
402 max_bitrate = entry.ddts.max_bitrate;
403 avg_bitrate = entry.ddts.avg_bitrate;
404 num_channels = entry.channelcount;
405 sampling_frequency = entry.samplerate;
408 num_channels = entry.channelcount;
409 sampling_frequency = entry.samplerate;
412 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
413 << actual_format <<
" in stsd box.";
417 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
418 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
419 streams.push_back(
new AudioStreamInfo(
420 track->header.track_id,
425 track->media.header.language,
431 vector_as_array(&extra_data),
436 if (track->media.handler.type == kVideo) {
437 RCHECK(!samp_descr.video_entries.empty());
438 if (desc_idx >= samp_descr.video_entries.size())
440 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
442 uint32_t coded_width = entry.width;
443 uint32_t coded_height = entry.height;
444 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
445 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
446 if (pixel_width == 0 && pixel_height == 0) {
450 std::string codec_string;
451 uint8_t nalu_length_size = 0;
453 const FourCC actual_format = entry.GetActualFormat();
454 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
455 switch (actual_format) {
457 AVCDecoderConfiguration avc_config;
458 if (!avc_config.Parse(entry.codec_config_record.data)) {
459 LOG(ERROR) <<
"Failed to parse avcc.";
462 codec_string = avc_config.GetCodecString();
463 nalu_length_size = avc_config.length_size();
465 if (coded_width != avc_config.coded_width() ||
466 coded_height != avc_config.coded_height()) {
467 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
468 <<
"," << coded_height
469 <<
") does not match with resolution in "
470 "AVCDecoderConfigurationRecord ("
471 << avc_config.coded_width() <<
","
472 << avc_config.coded_height()
473 <<
"). Use AVCDecoderConfigurationRecord.";
474 coded_width = avc_config.coded_width();
475 coded_height = avc_config.coded_height();
478 if (pixel_width != avc_config.pixel_width() ||
479 pixel_height != avc_config.pixel_height()) {
480 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
481 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
483 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
485 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
486 <<
"). Use AVCDecoderConfigurationRecord.";
487 pixel_width = avc_config.pixel_width();
488 pixel_height = avc_config.pixel_height();
494 HEVCDecoderConfiguration hevc_config;
495 if (!hevc_config.Parse(entry.codec_config_record.data)) {
496 LOG(ERROR) <<
"Failed to parse hevc.";
499 codec_string = hevc_config.GetCodecString(video_codec);
500 nalu_length_size = hevc_config.length_size();
506 VPCodecConfiguration vp_config;
507 if (!vp_config.Parse(entry.codec_config_record.data)) {
508 LOG(ERROR) <<
"Failed to parse vpcc.";
511 codec_string = vp_config.GetCodecString(video_codec);
515 LOG(ERROR) <<
"Unsupported video format "
516 << FourCCToString(actual_format) <<
" in stsd box.";
520 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
521 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
522 streams.push_back(
new VideoStreamInfo(
523 track->header.track_id, timescale, duration, video_codec,
524 codec_string, track->media.header.language, coded_width, coded_height,
525 pixel_width, pixel_height,
527 nalu_length_size, vector_as_array(&entry.codec_config_record.data),
528 entry.codec_config_record.data.size(), is_encrypted));
532 init_cb_.Run(streams);
533 if (!FetchKeysIfNecessary(moov_->pssh))
535 runs_.reset(
new TrackRunIterator(moov_.get()));
536 RCHECK(runs_->Init());
537 ChangeState(kEmittingSamples);
541 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
545 RCHECK(moof.Parse(reader));
547 runs_.reset(
new TrackRunIterator(moov_.get()));
548 RCHECK(runs_->Init(moof));
549 if (!FetchKeysIfNecessary(moof.pssh))
551 ChangeState(kEmittingSamples);
555 bool MP4MediaParser::FetchKeysIfNecessary(
556 const std::vector<ProtectionSystemSpecificHeader>& headers) {
561 if (!decryption_key_source_)
566 std::vector<uint8_t> widevine_system_id;
567 base::HexStringToBytes(kWidevineKeySystemId, &widevine_system_id);
568 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
569 headers.begin(); iter != headers.end(); ++iter) {
570 if (iter->system_id == widevine_system_id) {
571 Status status = decryption_key_source_->
FetchKeys(iter->data);
573 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
580 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
584 bool MP4MediaParser::EnqueueSample(
bool* err) {
585 if (!runs_->IsRunValid()) {
588 if (!queue_.
Trim(mdat_tail_))
591 ChangeState(kParsingBoxes);
595 if (!runs_->IsSampleValid()) {
604 queue_.Peek(&buf, &buf_size);
609 if (!runs_->is_audio() && !runs_->is_video())
619 if (runs_->AuxInfoNeedsToBeCached()) {
620 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
621 if (buf_size < runs_->aux_info_size())
623 *err = !runs_->CacheAuxInfo(buf, buf_size);
627 int64_t sample_offset = runs_->sample_offset() + moof_head_;
628 queue_.
PeekAt(sample_offset, &buf, &buf_size);
629 if (buf_size < runs_->sample_size()) {
630 if (sample_offset < queue_.
head()) {
631 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
632 <<
" < " << queue_.
head();
639 buf, runs_->sample_size(), runs_->is_keyframe()));
640 if (runs_->is_encrypted()) {
641 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
642 if (!decrypt_config ||
643 !DecryptSampleBuffer(decrypt_config.get(),
644 stream_sample->writable_data(),
645 stream_sample->data_size())) {
647 LOG(ERROR) <<
"Cannot decrypt samples.";
652 stream_sample->set_dts(runs_->dts());
653 stream_sample->set_pts(runs_->cts());
654 stream_sample->set_duration(runs_->duration());
656 DVLOG(3) <<
"Pushing frame: "
657 <<
", key=" << runs_->is_keyframe()
658 <<
", dur=" << runs_->duration()
659 <<
", dts=" << runs_->dts()
660 <<
", cts=" << runs_->cts()
661 <<
", size=" << runs_->sample_size();
663 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
665 LOG(ERROR) <<
"Failed to process the sample.";
669 runs_->AdvanceSample();
673 bool MP4MediaParser::DecryptSampleBuffer(
const DecryptConfig* decrypt_config,
675 size_t buffer_size) {
676 DCHECK(decrypt_config);
679 if (!decryption_key_source_) {
680 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
686 AesCtrEncryptor* encryptor;
687 DecryptorMap::iterator found = decryptor_map_.find(decrypt_config->key_id());
688 if (found == decryptor_map_.end()) {
691 Status status(decryption_key_source_->
GetKey(decrypt_config->key_id(),
694 LOG(ERROR) <<
"Error retrieving decryption key: " << status;
697 scoped_ptr<AesCtrEncryptor> new_encryptor(
new AesCtrEncryptor);
698 if (!new_encryptor->InitializeWithIv(key.key, decrypt_config->iv())) {
699 LOG(ERROR) <<
"Failed to initialize AesCtrEncryptor for decryption.";
702 encryptor = new_encryptor.release();
703 decryptor_map_[decrypt_config->key_id()] = encryptor;
705 encryptor = found->second;
707 if (!encryptor->SetIv(decrypt_config->iv())) {
708 LOG(ERROR) <<
"Invalid initialization vector.";
712 if (decrypt_config->subsamples().empty()) {
714 if (!encryptor->Decrypt(buffer, buffer_size, buffer)) {
715 LOG(ERROR) <<
"Error during bulk sample decryption.";
722 const std::vector<SubsampleEntry>& subsamples = decrypt_config->subsamples();
723 uint8_t* current_ptr = buffer;
724 const uint8_t* buffer_end = buffer + buffer_size;
725 current_ptr += decrypt_config->data_offset();
726 if (current_ptr > buffer_end) {
727 LOG(ERROR) <<
"Subsample data_offset too large.";
730 for (std::vector<SubsampleEntry>::const_iterator iter = subsamples.begin();
731 iter != subsamples.end();
733 if ((current_ptr + iter->clear_bytes + iter->cipher_bytes) > buffer_end) {
734 LOG(ERROR) <<
"Subsamples overflow sample buffer.";
737 current_ptr += iter->clear_bytes;
738 if (!encryptor->Decrypt(current_ptr, iter->cipher_bytes, current_ptr)) {
739 LOG(ERROR) <<
"Error decrypting subsample buffer.";
742 current_ptr += iter->cipher_bytes;
747 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
749 while (mdat_tail_ < offset) {
752 queue_.
PeekAt(mdat_tail_, &buf, &size);
759 mdat_tail_ += box_sz;
761 queue_.
Trim(std::min(mdat_tail_, offset));
765 void MP4MediaParser::ChangeState(State new_state) {
766 DVLOG(2) <<
"Changing state: " << new_state;