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 (track->media.handler.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 num_channels = entry.channelcount;
415 sampling_frequency = entry.samplerate;
418 LOG(ERROR) <<
"Unsupported audio format 0x" << std::hex
419 << actual_format <<
" in stsd box.";
423 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
424 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
425 streams.push_back(
new AudioStreamInfo(
426 track->header.track_id,
431 track->media.header.language,
437 vector_as_array(&extra_data),
442 if (track->media.handler.type == kVideo) {
443 RCHECK(!samp_descr.video_entries.empty());
444 if (desc_idx >= samp_descr.video_entries.size())
446 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
448 uint32_t coded_width = entry.width;
449 uint32_t coded_height = entry.height;
450 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
451 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
452 if (pixel_width == 0 && pixel_height == 0) {
456 std::string codec_string;
457 uint8_t nalu_length_size = 0;
459 const FourCC actual_format = entry.GetActualFormat();
460 const VideoCodec video_codec = FourCCToVideoCodec(actual_format);
461 switch (actual_format) {
463 AVCDecoderConfiguration avc_config;
464 if (!avc_config.Parse(entry.codec_config_record.data)) {
465 LOG(ERROR) <<
"Failed to parse avcc.";
468 codec_string = avc_config.GetCodecString();
469 nalu_length_size = avc_config.length_size();
471 if (coded_width != avc_config.coded_width() ||
472 coded_height != avc_config.coded_height()) {
473 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
474 <<
"," << coded_height
475 <<
") does not match with resolution in "
476 "AVCDecoderConfigurationRecord ("
477 << avc_config.coded_width() <<
","
478 << avc_config.coded_height()
479 <<
"). Use AVCDecoderConfigurationRecord.";
480 coded_width = avc_config.coded_width();
481 coded_height = avc_config.coded_height();
484 if (pixel_width != avc_config.pixel_width() ||
485 pixel_height != avc_config.pixel_height()) {
486 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
487 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
489 <<
") does not match with SAR in AVCDecoderConfigurationRecord "
491 << avc_config.pixel_width() <<
"," << avc_config.pixel_height()
492 <<
"). Use AVCDecoderConfigurationRecord.";
493 pixel_width = avc_config.pixel_width();
494 pixel_height = avc_config.pixel_height();
500 HEVCDecoderConfiguration hevc_config;
501 if (!hevc_config.Parse(entry.codec_config_record.data)) {
502 LOG(ERROR) <<
"Failed to parse hevc.";
505 codec_string = hevc_config.GetCodecString(video_codec);
506 nalu_length_size = hevc_config.length_size();
512 VPCodecConfiguration vp_config;
513 if (!vp_config.Parse(entry.codec_config_record.data)) {
514 LOG(ERROR) <<
"Failed to parse vpcc.";
517 codec_string = vp_config.GetCodecString(video_codec);
521 LOG(ERROR) <<
"Unsupported video format "
522 << FourCCToString(actual_format) <<
" in stsd box.";
526 bool is_encrypted = entry.sinf.info.track_encryption.is_encrypted;
527 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
528 streams.push_back(
new VideoStreamInfo(
529 track->header.track_id, timescale, duration, video_codec,
530 codec_string, track->media.header.language, coded_width, coded_height,
531 pixel_width, pixel_height,
533 nalu_length_size, vector_as_array(&entry.codec_config_record.data),
534 entry.codec_config_record.data.size(), is_encrypted));
538 init_cb_.Run(streams);
539 if (!FetchKeysIfNecessary(moov_->pssh))
541 runs_.reset(
new TrackRunIterator(moov_.get()));
542 RCHECK(runs_->Init());
543 ChangeState(kEmittingSamples);
547 bool MP4MediaParser::ParseMoof(BoxReader* reader) {
551 RCHECK(moof.Parse(reader));
553 runs_.reset(
new TrackRunIterator(moov_.get()));
554 RCHECK(runs_->Init(moof));
555 if (!FetchKeysIfNecessary(moof.pssh))
557 ChangeState(kEmittingSamples);
561 bool MP4MediaParser::FetchKeysIfNecessary(
562 const std::vector<ProtectionSystemSpecificHeader>& headers) {
567 if (!decryption_key_source_)
572 std::vector<uint8_t> widevine_system_id;
573 base::HexStringToBytes(kWidevineKeySystemId, &widevine_system_id);
574 for (std::vector<ProtectionSystemSpecificHeader>::const_iterator iter =
575 headers.begin(); iter != headers.end(); ++iter) {
576 if (iter->system_id == widevine_system_id) {
577 Status status = decryption_key_source_->
FetchKeys(iter->data);
579 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
586 LOG(ERROR) <<
"No viable 'pssh' box found for content decryption.";
590 bool MP4MediaParser::EnqueueSample(
bool* err) {
591 if (!runs_->IsRunValid()) {
594 if (!queue_.
Trim(mdat_tail_))
597 ChangeState(kParsingBoxes);
601 if (!runs_->IsSampleValid()) {
610 queue_.Peek(&buf, &buf_size);
615 if (!runs_->is_audio() && !runs_->is_video())
625 if (runs_->AuxInfoNeedsToBeCached()) {
626 queue_.
PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
627 if (buf_size < runs_->aux_info_size())
629 *err = !runs_->CacheAuxInfo(buf, buf_size);
633 int64_t sample_offset = runs_->sample_offset() + moof_head_;
634 queue_.
PeekAt(sample_offset, &buf, &buf_size);
635 if (buf_size < runs_->sample_size()) {
636 if (sample_offset < queue_.
head()) {
637 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset
638 <<
" < " << queue_.
head();
645 buf, runs_->sample_size(), runs_->is_keyframe()));
646 if (runs_->is_encrypted()) {
647 scoped_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
648 if (!decrypt_config ||
649 !DecryptSampleBuffer(decrypt_config.get(),
650 stream_sample->writable_data(),
651 stream_sample->data_size())) {
653 LOG(ERROR) <<
"Cannot decrypt samples.";
658 stream_sample->set_dts(runs_->dts());
659 stream_sample->set_pts(runs_->cts());
660 stream_sample->set_duration(runs_->duration());
662 DVLOG(3) <<
"Pushing frame: "
663 <<
", key=" << runs_->is_keyframe()
664 <<
", dur=" << runs_->duration()
665 <<
", dts=" << runs_->dts()
666 <<
", cts=" << runs_->cts()
667 <<
", size=" << runs_->sample_size();
669 if (!new_sample_cb_.Run(runs_->track_id(), stream_sample)) {
671 LOG(ERROR) <<
"Failed to process the sample.";
675 runs_->AdvanceSample();
679 bool MP4MediaParser::DecryptSampleBuffer(
const DecryptConfig* decrypt_config,
681 size_t buffer_size) {
682 DCHECK(decrypt_config);
685 if (!decryption_key_source_) {
686 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is not "
692 AesCtrEncryptor* encryptor;
693 DecryptorMap::iterator found = decryptor_map_.find(decrypt_config->key_id());
694 if (found == decryptor_map_.end()) {
697 Status status(decryption_key_source_->
GetKey(decrypt_config->key_id(),
700 LOG(ERROR) <<
"Error retrieving decryption key: " << status;
703 scoped_ptr<AesCtrEncryptor> new_encryptor(
new AesCtrEncryptor);
704 if (!new_encryptor->InitializeWithIv(key.key, decrypt_config->iv())) {
705 LOG(ERROR) <<
"Failed to initialize AesCtrEncryptor for decryption.";
708 encryptor = new_encryptor.release();
709 decryptor_map_[decrypt_config->key_id()] = encryptor;
711 encryptor = found->second;
713 if (!encryptor->SetIv(decrypt_config->iv())) {
714 LOG(ERROR) <<
"Invalid initialization vector.";
718 if (decrypt_config->subsamples().empty()) {
720 if (!encryptor->Decrypt(buffer, buffer_size, buffer)) {
721 LOG(ERROR) <<
"Error during bulk sample decryption.";
728 const std::vector<SubsampleEntry>& subsamples = decrypt_config->subsamples();
729 uint8_t* current_ptr = buffer;
730 const uint8_t* buffer_end = buffer + buffer_size;
731 current_ptr += decrypt_config->data_offset();
732 if (current_ptr > buffer_end) {
733 LOG(ERROR) <<
"Subsample data_offset too large.";
736 for (std::vector<SubsampleEntry>::const_iterator iter = subsamples.begin();
737 iter != subsamples.end();
739 if ((current_ptr + iter->clear_bytes + iter->cipher_bytes) > buffer_end) {
740 LOG(ERROR) <<
"Subsamples overflow sample buffer.";
743 current_ptr += iter->clear_bytes;
744 if (!encryptor->Decrypt(current_ptr, iter->cipher_bytes, current_ptr)) {
745 LOG(ERROR) <<
"Error decrypting subsample buffer.";
748 current_ptr += iter->cipher_bytes;
753 bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
755 while (mdat_tail_ < offset) {
758 queue_.
PeekAt(mdat_tail_, &buf, &size);
765 mdat_tail_ += box_sz;
767 queue_.
Trim(std::min(mdat_tail_, offset));
771 void MP4MediaParser::ChangeState(State new_state) {
772 DVLOG(2) <<
"Changing state: " << new_state;