5#include <packager/media/formats/mp4/mp4_media_parser.h>
17#include <absl/flags/flag.h>
18#include <absl/log/check.h>
19#include <absl/log/log.h>
21#include <packager/file.h>
22#include <packager/file/file_closer.h>
23#include <packager/macros/compiler.h>
24#include <packager/macros/logging.h>
25#include <packager/media/base/audio_stream_info.h>
26#include <packager/media/base/decrypt_config.h>
27#include <packager/media/base/decryptor_source.h>
28#include <packager/media/base/fourccs.h>
29#include <packager/media/base/key_source.h>
30#include <packager/media/base/media_sample.h>
31#include <packager/media/base/rcheck.h>
32#include <packager/media/base/stream_info.h>
33#include <packager/media/base/video_stream_info.h>
34#include <packager/media/base/video_util.h>
35#include <packager/media/codecs/aac_audio_specific_config.h>
36#include <packager/media/codecs/ac3_audio_util.h>
37#include <packager/media/codecs/ac4_audio_util.h>
38#include <packager/media/codecs/av1_codec_configuration_record.h>
39#include <packager/media/codecs/avc_decoder_configuration_record.h>
40#include <packager/media/codecs/dovi_decoder_configuration_record.h>
41#include <packager/media/codecs/ec3_audio_util.h>
42#include <packager/media/codecs/es_descriptor.h>
43#include <packager/media/codecs/hevc_decoder_configuration_record.h>
44#include <packager/media/codecs/iamf_audio_util.h>
45#include <packager/media/codecs/vp_codec_configuration_record.h>
46#include <packager/media/formats/mp4/box_definitions.h>
47#include <packager/media/formats/mp4/box_reader.h>
48#include <packager/media/formats/mp4/track_run_iterator.h>
49#include <packager/status.h>
52 use_dovi_supplemental_codecs,
54 "Set to true to signal DolbyVision using the modern supplemental "
55 "codecs approach instead of the legacy "
56 "duplicate representations approach");
63int64_t Rescale(int64_t time_in_old_scale,
66 return (
static_cast<double>(time_in_old_scale) / old_scale) * new_scale;
69H26xStreamFormat GetH26xStreamFormat(FourCC fourcc) {
74 return H26xStreamFormat::kNalUnitStreamWithoutParameterSetNalus;
78 return H26xStreamFormat::kNalUnitStreamWithParameterSetNalus;
80 return H26xStreamFormat::kUnSpecified;
84Codec FourCCToCodec(FourCC fourcc) {
93 return kCodecH265DolbyVision;
136 return kUnknownCodec;
140Codec ObjectTypeToCodec(ObjectType object_type) {
141 switch (object_type) {
142 case ObjectType::kISO_14496_3:
143 case ObjectType::kISO_13818_7_AAC_LC:
145 case ObjectType::kDTSC:
147 case ObjectType::kDTSE:
149 case ObjectType::kDTSH:
151 case ObjectType::kDTSL:
154 return kUnknownCodec;
158std::vector<uint8_t> GetDOVIDecoderConfig(
159 const std::vector<CodecConfiguration>& configs) {
160 for (
const CodecConfiguration& config : configs) {
161 if (config.box_type == FOURCC_dvcC || config.box_type == FOURCC_dvvC) {
165 return std::vector<uint8_t>();
168std::vector<uint8_t> GetLHEVCDecoderConfig(
169 const std::vector<CodecConfiguration>& configs) {
170 for (
const CodecConfiguration& config : configs) {
171 if (config.box_type == FOURCC_lhvC) {
175 return std::vector<uint8_t>();
178bool UpdateCodecStringForDolbyVision(
179 FourCC actual_format,
180 const std::vector<CodecConfiguration>& configs,
181 std::string* codec_string) {
182 DOVIDecoderConfigurationRecord dovi_config;
183 if (!dovi_config.Parse(GetDOVIDecoderConfig(configs))) {
184 LOG(ERROR) <<
"Failed to parse Dolby Vision decoder "
185 "configuration record.";
188 switch (actual_format) {
194 *codec_string = dovi_config.GetCodecString(actual_format);
199 *codec_string +=
";" + dovi_config.GetCodecString(FOURCC_dvhe);
203 *codec_string +=
";" + dovi_config.GetCodecString(FOURCC_dvh1);
206 *codec_string +=
";" + dovi_config.GetCodecString(FOURCC_dav1);
209 LOG(ERROR) <<
"Unsupported format with extra codec "
210 << FourCCToString(actual_format);
216bool UpdateDolbyVisionInfo(FourCC actual_format,
217 const std::vector<CodecConfiguration>& configs,
218 uint8_t transfer_characteristics,
219 std::string* codec_string,
220 std::string* dovi_supplemental_codec_string,
221 FourCC* dovi_compatible_brand) {
222 DOVIDecoderConfigurationRecord dovi_config;
223 if (!dovi_config.Parse(GetDOVIDecoderConfig(configs))) {
224 LOG(ERROR) <<
"Failed to parse Dolby Vision decoder "
225 "configuration record.";
228 switch (actual_format) {
234 *codec_string = dovi_config.GetCodecString(actual_format);
239 *dovi_supplemental_codec_string = dovi_config.GetCodecString(FOURCC_dvhe);
243 *dovi_supplemental_codec_string = dovi_config.GetCodecString(FOURCC_dvh1);
246 *dovi_supplemental_codec_string = dovi_config.GetCodecString(FOURCC_dav1);
249 LOG(ERROR) <<
"Unsupported format with extra codec "
250 << FourCCToString(actual_format);
253 *dovi_compatible_brand =
254 dovi_config.GetDoViCompatibleBrand(transfer_characteristics);
258bool UpdateLHEVCInfo(FourCC actual_format,
259 HEVCDecoderConfigurationRecord& hevc_config,
260 const std::vector<CodecConfiguration>& configs,
261 std::string* codec_string) {
262 if (!hevc_config.ParseLHEVCConfig(GetLHEVCDecoderConfig(configs))) {
263 LOG(ERROR) <<
"Failed to parse L-HEVC decoder "
264 "configuration record.";
267 *codec_string = hevc_config.GetCodecString(actual_format);
271const uint64_t kNanosecondsPerSecond = 1000000000ull;
275MP4MediaParser::MP4MediaParser()
276 : state_(kWaitingForInit),
277 decryption_key_source_(NULL),
281MP4MediaParser::~MP4MediaParser() {}
283void MP4MediaParser::Init(
const InitCB& init_cb,
287 DCHECK_EQ(state_, kWaitingForInit);
288 DCHECK(init_cb_ ==
nullptr);
289 DCHECK(init_cb !=
nullptr);
290 DCHECK(new_media_sample_cb !=
nullptr);
292 ChangeState(kParsingBoxes);
294 new_sample_cb_ = new_media_sample_cb;
295 decryption_key_source_ = decryption_key_source;
296 if (decryption_key_source)
300void MP4MediaParser::Reset() {
307bool MP4MediaParser::Flush() {
308 DCHECK_NE(state_, kWaitingForInit);
310 ChangeState(kParsingBoxes);
314bool MP4MediaParser::Parse(
const uint8_t* buf,
int size) {
315 DCHECK_NE(state_, kWaitingForInit);
317 if (state_ == kError)
320 queue_.Push(buf, size);
322 bool result, err =
false;
325 if (state_ == kParsingBoxes) {
326 result = ParseBox(&err);
328 DCHECK_EQ(kEmittingSamples, state_);
329 result = EnqueueSample(&err);
331 int64_t max_clear = runs_->GetMaxClearOffset() + moof_head_;
332 err = !ReadAndDiscardMDATsUntil(max_clear);
335 }
while (result && !err);
338 DLOG(ERROR) <<
"Error while parsing MP4";
348bool MP4MediaParser::LoadMoov(
const std::string& file_path) {
349 std::unique_ptr<File, FileCloser> file(
350 File::OpenWithNoBuffering(file_path.c_str(),
"r"));
352 LOG(ERROR) <<
"Unable to open media file '" << file_path <<
"'";
355 if (!file->Seek(0)) {
356 LOG(WARNING) <<
"Filesystem does not support seeking on file '" << file_path
361 uint64_t file_position(0);
362 bool mdat_seen(
false);
364 const uint32_t kBoxHeaderReadSize(16);
365 std::vector<uint8_t> buffer(kBoxHeaderReadSize);
366 int64_t bytes_read = file->Read(&buffer[0], kBoxHeaderReadSize);
367 if (bytes_read == 0) {
368 LOG(ERROR) <<
"Could not find 'moov' box in file '" << file_path <<
"'";
371 if (bytes_read < kBoxHeaderReadSize) {
372 LOG(ERROR) <<
"Error reading media file '" << file_path <<
"'";
378 if (!BoxReader::StartBox(&buffer[0], kBoxHeaderReadSize, &box_type,
380 LOG(ERROR) <<
"Could not start box from file '" << file_path <<
"'";
383 if (box_type == FOURCC_mdat) {
385 }
else if (box_type == FOURCC_moov) {
391 if (!Parse(&buffer[0], bytes_read)) {
392 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
395 uint64_t bytes_to_read = box_size - bytes_read;
396 buffer.resize(bytes_to_read);
397 while (bytes_to_read > 0) {
398 bytes_read = file->Read(&buffer[0], bytes_to_read);
399 if (bytes_read <= 0) {
400 LOG(ERROR) <<
"Error reading 'moov' contents from file '" << file_path
404 if (!Parse(&buffer[0], bytes_read)) {
405 LOG(ERROR) <<
"Error parsing mp4 file '" << file_path <<
"'";
408 bytes_to_read -= bytes_read;
414 file_position += box_size;
415 if (!file->Seek(file_position)) {
416 LOG(ERROR) <<
"Error skipping box in mp4 file '" << file_path <<
"'";
423bool MP4MediaParser::ParseBox(
bool* err) {
426 queue_.Peek(&buf, &size);
430 std::unique_ptr<BoxReader> reader(BoxReader::ReadBox(buf, size, err));
431 if (reader.get() == NULL)
434 if (reader->type() == FOURCC_mdat) {
440 NOTIMPLEMENTED() <<
" Non-seekable Files with 'mdat' box before 'moov' "
441 "box is not supported.";
448 <<
"Ignore unused 'mdat' box - this could be as a result of extra "
449 "not usable 'mdat' or 'mdat' associated with unrecognized track.";
454 mdat_tail_ = queue_.head() + reader->size();
456 if (reader->type() == FOURCC_moov) {
457 *err = !ParseMoov(reader.get());
458 }
else if (reader->type() == FOURCC_moof) {
459 moof_head_ = queue_.head();
460 *err = !ParseMoof(reader.get());
468 VLOG(2) <<
"Skipping top-level box: " << FourCCToString(reader->type());
471 queue_.Pop(
static_cast<int>(reader->size()));
475bool MP4MediaParser::ParseMoov(BoxReader* reader) {
479 moov_.reset(
new Movie);
480 RCHECK(moov_->Parse(reader));
483 std::vector<std::shared_ptr<StreamInfo>> streams;
485 bool use_dovi_supplemental =
486 absl::GetFlag(FLAGS_use_dovi_supplemental_codecs);
488 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
489 track != moov_->tracks.end(); ++track) {
490 const int32_t timescale = track->media.header.timescale;
493 int64_t duration = 0;
494 if (track->media.header.duration > 0) {
495 duration = track->media.header.duration;
496 }
else if (moov_->extends.header.fragment_duration > 0) {
497 DCHECK(moov_->header.timescale != 0);
498 duration = Rescale(moov_->extends.header.fragment_duration,
499 moov_->header.timescale, timescale);
500 }
else if (moov_->header.duration > 0 &&
501 moov_->header.duration != std::numeric_limits<uint64_t>::max()) {
502 DCHECK(moov_->header.timescale != 0);
504 Rescale(moov_->header.duration, moov_->header.timescale, timescale);
507 const SampleDescription& samp_descr =
508 track->media.information.sample_table.description;
514 if (moov_->extends.tracks.size() > 0) {
515 for (
size_t t = 0; t < moov_->extends.tracks.size(); t++) {
516 const TrackExtends& trex = moov_->extends.tracks[t];
517 if (trex.track_id == track->header.track_id) {
518 desc_idx = trex.default_sample_description_index;
523 const std::vector<ChunkInfo>& chunk_info =
524 track->media.information.sample_table.sample_to_chunk.chunk_info;
525 RCHECK(chunk_info.size() > 0);
526 desc_idx = chunk_info[0].sample_description_index;
528 RCHECK(desc_idx > 0);
531 if (samp_descr.type == kAudio) {
532 RCHECK(!samp_descr.audio_entries.empty());
536 if (desc_idx >= samp_descr.audio_entries.size())
539 const AudioSampleEntry& entry = samp_descr.audio_entries[desc_idx];
540 const FourCC actual_format = entry.GetActualFormat();
541 Codec codec = FourCCToCodec(actual_format);
542 uint8_t num_channels = entry.channelcount;
543 uint32_t sampling_frequency = entry.samplerate;
544 uint64_t codec_delay_ns = 0;
545 uint8_t audio_object_type = 0;
546 uint32_t max_bitrate = 0;
547 uint32_t avg_bitrate = 0;
548 std::vector<uint8_t> codec_config;
550 switch (actual_format) {
552 const DecoderConfigDescriptor& decoder_config =
553 entry.esds.es_descriptor.decoder_config_descriptor();
554 max_bitrate = decoder_config.max_bitrate();
555 avg_bitrate = decoder_config.avg_bitrate();
557 codec = ObjectTypeToCodec(decoder_config.object_type());
558 if (codec == kCodecAAC) {
559 const AACAudioSpecificConfig& aac_audio_specific_config =
560 entry.esds.aac_audio_specific_config;
561 num_channels = aac_audio_specific_config.GetNumChannels();
563 aac_audio_specific_config.GetSamplesPerSecond();
564 audio_object_type = aac_audio_specific_config.GetAudioObjectType();
566 decoder_config.decoder_specific_info_descriptor().data();
567 }
else if (codec == kUnknownCodec) {
572 LOG(WARNING) <<
"Unsupported audio object type "
573 <<
static_cast<int>(decoder_config.object_type())
574 <<
" in stsd.es_desriptor.";
579 FALLTHROUGH_INTENDED;
581 FALLTHROUGH_INTENDED;
583 FALLTHROUGH_INTENDED;
585 FALLTHROUGH_INTENDED;
587 codec_config = entry.ddts.extra_data;
588 max_bitrate = entry.ddts.max_bitrate;
589 avg_bitrate = entry.ddts.avg_bitrate;
592 codec_config = entry.udts.data;
595 codec_config = entry.dac3.data;
596 num_channels =
static_cast<uint8_t
>(GetAc3NumChannels(codec_config));
599 codec_config = entry.dec3.data;
600 num_channels =
static_cast<uint8_t
>(GetEc3NumChannels(codec_config));
603 codec_config = entry.dac4.data;
607 if (!GetAc4CodecInfo(codec_config, &audio_object_type)) {
608 LOG(ERROR) <<
"Failed to parse dac4.";
613 codec_config = entry.alac.data;
616 codec_config = entry.dfla.data;
619 codec_config = entry.dops.opus_identification_header;
621 entry.dops.preskip * kNanosecondsPerSecond / sampling_frequency;
624 codec_config = entry.iacb.data;
625 if (!GetIamfCodecStringInfo(codec_config, audio_object_type)) {
626 LOG(ERROR) <<
"Failed to parse iamf.";
632 codec_config = entry.mhac.data;
633 audio_object_type = entry.mhac.mpeg_h_3da_profile_level_indication;
641 LOG(WARNING) <<
"Unsupported audio format '"
642 << FourCCToString(actual_format) <<
"' in stsd box.";
647 uint64_t seek_preroll_ns = 0;
648 for (
const auto& sample_group_description :
649 track->media.information.sample_table.sample_group_descriptions) {
650 if (sample_group_description.grouping_type != FOURCC_roll)
652 const auto& audio_roll_recovery_entries =
653 sample_group_description.audio_roll_recovery_entries;
654 if (audio_roll_recovery_entries.size() != 1) {
655 LOG(WARNING) <<
"Unexpected number of entries in "
656 "SampleGroupDescription table with grouping type "
660 const int16_t roll_distance_in_samples =
661 audio_roll_recovery_entries[0].roll_distance;
662 if (roll_distance_in_samples < 0) {
665 if (actual_format == FOURCC_iamf)
668 RCHECK((sampling_frequency != 0));
669 seek_preroll_ns = kNanosecondsPerSecond *
670 (-roll_distance_in_samples) / sampling_frequency;
673 <<
"Roll distance is supposed to be negative, but seeing "
674 << roll_distance_in_samples;
680 const bool is_encrypted =
683 : entry.sinf.info.track_encryption.default_is_protected == 1;
684 DVLOG(1) <<
"is_audio_track_encrypted_: " << is_encrypted;
685 streams.emplace_back(
new AudioStreamInfo(
686 track->header.track_id, timescale, duration, codec,
687 AudioStreamInfo::GetCodecString(codec, audio_object_type),
688 codec_config.data(), codec_config.size(), entry.samplesize,
689 num_channels, sampling_frequency, seek_preroll_ns, codec_delay_ns,
690 max_bitrate, avg_bitrate, track->media.header.language.code,
694 if (samp_descr.type == kVideo) {
695 RCHECK(!samp_descr.video_entries.empty());
696 if (desc_idx >= samp_descr.video_entries.size())
698 const VideoSampleEntry& entry = samp_descr.video_entries[desc_idx];
699 std::vector<uint8_t> codec_configuration_data =
700 entry.codec_configuration.data;
702 uint32_t coded_width = entry.width;
703 uint32_t coded_height = entry.height;
704 uint32_t pixel_width = entry.pixel_aspect.h_spacing;
705 uint32_t pixel_height = entry.pixel_aspect.v_spacing;
706 if (pixel_width == 0 && pixel_height == 0) {
707 DerivePixelWidthHeight(coded_width, coded_height, track->header.width,
708 track->header.height, &pixel_width,
711 std::string codec_string;
712 std::string dovi_supplemental_codec_string(
"");
713 FourCC dovi_compatible_brand = FOURCC_NULL;
714 uint8_t nalu_length_size = 0;
715 uint8_t transfer_characteristics = 0;
716 uint8_t color_primaries = 0;
717 uint8_t matrix_coefficients = 0;
719 const FourCC actual_format = entry.GetActualFormat();
720 const Codec video_codec = FourCCToCodec(actual_format);
721 switch (actual_format) {
723 AV1CodecConfigurationRecord av1_config;
724 if (!av1_config.Parse(codec_configuration_data)) {
725 LOG(ERROR) <<
"Failed to parse av1c.";
729 if (entry.colr.color_parameter_type != FOURCC_NULL) {
730 transfer_characteristics = entry.colr.transfer_characteristics;
731 color_primaries = entry.colr.color_primaries;
732 matrix_coefficients = entry.colr.matrix_coefficients;
733 codec_string = av1_config.GetCodecString(
734 color_primaries, transfer_characteristics, matrix_coefficients,
735 entry.colr.video_full_range_flag);
737 codec_string = av1_config.GetCodecString();
740 if (!entry.extra_codec_configs.empty()) {
742 if (use_dovi_supplemental) {
743 if (!UpdateDolbyVisionInfo(
744 actual_format, entry.extra_codec_configs,
745 transfer_characteristics, &codec_string,
746 &dovi_supplemental_codec_string,
747 &dovi_compatible_brand)) {
751 if (!UpdateCodecStringForDolbyVision(actual_format,
752 entry.extra_codec_configs,
762 AVCDecoderConfigurationRecord avc_config;
763 if (!avc_config.Parse(codec_configuration_data)) {
764 LOG(ERROR) <<
"Failed to parse avcc.";
767 codec_string = avc_config.GetCodecString(actual_format);
768 nalu_length_size = avc_config.nalu_length_size();
769 transfer_characteristics = avc_config.transfer_characteristics();
770 color_primaries = avc_config.color_primaries();
771 matrix_coefficients = avc_config.matrix_coefficients();
774 if (avc_config.coded_width() != 0) {
775 DCHECK_NE(avc_config.coded_height(), 0u);
776 if (coded_width != avc_config.coded_width() ||
777 coded_height != avc_config.coded_height()) {
778 LOG(WARNING) <<
"Resolution in VisualSampleEntry (" << coded_width
779 <<
"," << coded_height
780 <<
") does not match with resolution in "
781 "AVCDecoderConfigurationRecord ("
782 << avc_config.coded_width() <<
","
783 << avc_config.coded_height()
784 <<
"). Use AVCDecoderConfigurationRecord.";
785 coded_width = avc_config.coded_width();
786 coded_height = avc_config.coded_height();
789 DCHECK_NE(avc_config.pixel_width(), 0u);
790 DCHECK_NE(avc_config.pixel_height(), 0u);
791 if (pixel_width != avc_config.pixel_width() ||
792 pixel_height != avc_config.pixel_height()) {
793 LOG_IF(WARNING, pixel_width != 1 || pixel_height != 1)
794 <<
"Pixel aspect ratio in PASP box (" << pixel_width <<
","
796 <<
") does not match with SAR in "
797 "AVCDecoderConfigurationRecord "
799 << avc_config.pixel_width() <<
","
800 << avc_config.pixel_height()
801 <<
"). Use AVCDecoderConfigurationRecord.";
802 pixel_width = avc_config.pixel_width();
803 pixel_height = avc_config.pixel_height();
812 HEVCDecoderConfigurationRecord hevc_config;
813 if (!hevc_config.Parse(codec_configuration_data)) {
814 LOG(ERROR) <<
"Failed to parse hevc.";
817 codec_string = hevc_config.GetCodecString(actual_format);
818 nalu_length_size = hevc_config.nalu_length_size();
819 transfer_characteristics = hevc_config.transfer_characteristics();
820 color_primaries = hevc_config.color_primaries();
821 matrix_coefficients = hevc_config.matrix_coefficients();
823 if (!entry.extra_codec_configs.empty()) {
826 if (entry.HaveDolbyVisionConfig()) {
827 if (use_dovi_supplemental) {
828 if (!UpdateDolbyVisionInfo(
829 actual_format, entry.extra_codec_configs,
830 transfer_characteristics, &codec_string,
831 &dovi_supplemental_codec_string,
832 &dovi_compatible_brand)) {
836 if (!UpdateCodecStringForDolbyVision(actual_format,
837 entry.extra_codec_configs,
843 if (entry.HaveLHEVCConfig()) {
844 if (!UpdateLHEVCInfo(actual_format, hevc_config,
845 entry.extra_codec_configs, &codec_string)) {
854 VPCodecConfigurationRecord vp_config;
855 if (!vp_config.ParseMP4(codec_configuration_data)) {
856 LOG(ERROR) <<
"Failed to parse vpcc.";
859 if (actual_format == FOURCC_vp09 &&
860 (!vp_config.is_level_set() || vp_config.level() == 0)) {
861 const double kUnknownSampleDuration = 0.0;
862 vp_config.SetVP9Level(coded_width, coded_height,
863 kUnknownSampleDuration);
864 vp_config.WriteMP4(&codec_configuration_data);
866 codec_string = vp_config.GetCodecString(video_codec);
875 LOG(WARNING) <<
"Unsupported video format '"
876 << FourCCToString(actual_format) <<
"' in stsd box.";
881 const bool is_encrypted =
884 : entry.sinf.info.track_encryption.default_is_protected == 1;
885 DVLOG(1) <<
"is_video_track_encrypted_: " << is_encrypted;
886 std::shared_ptr<VideoStreamInfo> video_stream_info(
new VideoStreamInfo(
887 track->header.track_id, timescale, duration, video_codec,
888 GetH26xStreamFormat(actual_format), codec_string,
889 codec_configuration_data.data(), codec_configuration_data.size(),
890 coded_width, coded_height, pixel_width, pixel_height, color_primaries,
891 matrix_coefficients, transfer_characteristics,
893 nalu_length_size, track->media.header.language.code, is_encrypted));
895 if (use_dovi_supplemental) {
896 video_stream_info->set_supplemental_codec(
897 dovi_supplemental_codec_string);
898 video_stream_info->set_compatible_brand(dovi_compatible_brand);
900 video_stream_info->set_layered_codec_config(
901 GetLHEVCDecoderConfig(entry.extra_codec_configs));
902 video_stream_info->set_extra_config(entry.ExtraCodecConfigsAsVector());
903 video_stream_info->set_colr_data((entry.colr.raw_box).data(),
904 (entry.colr.raw_box).size());
907 if (moov_->pssh.size() > 0) {
908 std::vector<uint8_t> pssh_raw_data;
909 for (
const auto& pssh : moov_->pssh) {
910 pssh_raw_data.insert(pssh_raw_data.end(), pssh.raw_box.begin(),
913 video_stream_info->set_eme_init_data(pssh_raw_data.data(),
914 pssh_raw_data.size());
917 streams.push_back(video_stream_info);
922 if (!FetchKeysIfNecessary(moov_->pssh))
924 runs_.reset(
new TrackRunIterator(moov_.get()));
925 RCHECK(runs_->Init());
926 ChangeState(kEmittingSamples);
930bool MP4MediaParser::ParseMoof(BoxReader* reader) {
934 RCHECK(moof.Parse(reader));
936 runs_.reset(
new TrackRunIterator(moov_.get()));
937 RCHECK(runs_->Init(moof));
938 if (!FetchKeysIfNecessary(moof.pssh))
940 ChangeState(kEmittingSamples);
944bool MP4MediaParser::FetchKeysIfNecessary(
945 const std::vector<ProtectionSystemSpecificHeader>& headers) {
950 if (!decryption_key_source_)
953 std::vector<uint8_t> pssh_raw_data;
954 for (
const auto& header : headers) {
955 pssh_raw_data.insert(pssh_raw_data.end(), header.raw_box.begin(),
956 header.raw_box.end());
959 decryption_key_source_->FetchKeys(EmeInitDataType::CENC, pssh_raw_data);
961 LOG(ERROR) <<
"Error fetching decryption keys: " << status;
967bool MP4MediaParser::EnqueueSample(
bool* err) {
968 if (!runs_->IsRunValid()) {
971 if (!queue_.Trim(mdat_tail_))
974 ChangeState(kParsingBoxes);
978 if (!runs_->IsSampleValid()) {
987 queue_.Peek(&buf, &buf_size);
992 if (!runs_->is_audio() && !runs_->is_video())
1002 if (runs_->AuxInfoNeedsToBeCached()) {
1003 queue_.PeekAt(runs_->aux_info_offset() + moof_head_, &buf, &buf_size);
1004 if (buf_size < runs_->aux_info_size())
1006 *err = !runs_->CacheAuxInfo(buf, buf_size);
1010 int64_t sample_offset = runs_->sample_offset() + moof_head_;
1011 queue_.PeekAt(sample_offset, &buf, &buf_size);
1012 if (buf_size < runs_->sample_size()) {
1013 if (sample_offset < queue_.head()) {
1014 LOG(ERROR) <<
"Incorrect sample offset " << sample_offset <<
" < "
1021 const uint8_t* media_data = buf;
1022 const size_t media_data_size = runs_->sample_size();
1025 const size_t kDummyDataSize = 0;
1026 std::shared_ptr<MediaSample> stream_sample(
1027 MediaSample::CopyFrom(media_data, kDummyDataSize, runs_->is_keyframe()));
1029 if (runs_->is_encrypted()) {
1030 std::shared_ptr<uint8_t> decrypted_media_data(
1031 new uint8_t[media_data_size], std::default_delete<uint8_t[]>());
1032 std::unique_ptr<DecryptConfig> decrypt_config = runs_->GetDecryptConfig();
1033 if (!decrypt_config) {
1035 LOG(ERROR) <<
"Missing decrypt config.";
1039 if (!decryptor_source_) {
1040 stream_sample->SetData(media_data, media_data_size);
1043 stream_sample->set_decrypt_config(std::move(decrypt_config));
1044 stream_sample->set_is_encrypted(
true);
1046 if (!decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
1047 media_data, media_data_size,
1048 decrypted_media_data.get())) {
1050 LOG(ERROR) <<
"Cannot decrypt samples.";
1053 stream_sample->TransferData(std::move(decrypted_media_data),
1057 stream_sample->SetData(media_data, media_data_size);
1060 stream_sample->set_dts(runs_->dts());
1061 stream_sample->set_pts(runs_->cts());
1062 stream_sample->set_duration(runs_->duration());
1064 DVLOG(3) <<
"Pushing frame: "
1065 <<
", key=" << runs_->is_keyframe() <<
", dur=" << runs_->duration()
1066 <<
", dts=" << runs_->dts() <<
", cts=" << runs_->cts()
1067 <<
", size=" << runs_->sample_size();
1069 if (!new_sample_cb_(runs_->track_id(), stream_sample)) {
1071 LOG(ERROR) <<
"Failed to process the sample.";
1075 runs_->AdvanceSample();
1079bool MP4MediaParser::ReadAndDiscardMDATsUntil(
const int64_t offset) {
1081 while (mdat_tail_ < offset) {
1084 queue_.PeekAt(mdat_tail_, &buf, &size);
1088 if (!BoxReader::StartBox(buf, size, &type, &box_sz, &err))
1091 mdat_tail_ += box_sz;
1093 queue_.Trim(std::min(mdat_tail_, offset));
1097void MP4MediaParser::ChangeState(State new_state) {
1098 DVLOG(2) <<
"Changing state: " << new_state;
All the methods that are virtual are virtual for mocking.