7 #include <packager/media/formats/mp4/mp4_muxer.h>
12 #include <absl/log/check.h>
13 #include <absl/strings/escaping.h>
14 #include <absl/strings/numbers.h>
16 #include <packager/file.h>
17 #include <packager/macros/logging.h>
18 #include <packager/macros/status.h>
19 #include <packager/media/base/aes_encryptor.h>
20 #include <packager/media/base/audio_stream_info.h>
21 #include <packager/media/base/fourccs.h>
22 #include <packager/media/base/key_source.h>
23 #include <packager/media/base/media_sample.h>
24 #include <packager/media/base/text_stream_info.h>
25 #include <packager/media/base/video_stream_info.h>
26 #include <packager/media/codecs/es_descriptor.h>
27 #include <packager/media/event/muxer_listener.h>
28 #include <packager/media/formats/mp4/box_definitions.h>
29 #include <packager/media/formats/mp4/low_latency_segment_segmenter.h>
30 #include <packager/media/formats/mp4/multi_segment_segmenter.h>
31 #include <packager/media/formats/mp4/single_segment_segmenter.h>
32 #include <packager/media/formats/ttml/ttml_generator.h>
42 void SetStartAndEndFromOffsetAndSize(
size_t offset,
46 range->start =
static_cast<uint32_t
>(offset);
48 range->end = range->start +
static_cast<uint32_t
>(size) - 1;
51 FourCC CodecToFourCC(Codec codec, H26xStreamFormat h26x_stream_format) {
56 return h26x_stream_format ==
57 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
61 return h26x_stream_format ==
62 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
65 case kCodecH265DolbyVision:
66 return h26x_stream_format ==
67 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
112 void GenerateSinf(FourCC old_type,
113 const EncryptionConfig& encryption_config,
114 ProtectionSchemeInfo* sinf) {
115 sinf->format.format = old_type;
117 DCHECK_NE(encryption_config.protection_scheme, FOURCC_NULL);
118 sinf->type.type = encryption_config.protection_scheme;
121 const int kCencSchemeVersion = 0x00010000;
122 sinf->type.version = kCencSchemeVersion;
124 auto& track_encryption = sinf->info.track_encryption;
125 track_encryption.default_is_protected = 1;
127 track_encryption.default_crypt_byte_block =
128 encryption_config.crypt_byte_block;
129 track_encryption.default_skip_byte_block = encryption_config.skip_byte_block;
130 switch (encryption_config.protection_scheme) {
133 DCHECK_EQ(track_encryption.default_crypt_byte_block, 0u);
134 DCHECK_EQ(track_encryption.default_skip_byte_block, 0u);
137 track_encryption.version = 0;
144 track_encryption.version = 1;
147 NOTIMPLEMENTED() <<
"Unexpected protection scheme "
148 << encryption_config.protection_scheme;
151 track_encryption.default_per_sample_iv_size =
152 encryption_config.per_sample_iv_size;
153 track_encryption.default_constant_iv = encryption_config.constant_iv;
154 track_encryption.default_kid = encryption_config.key_id;
159 int16_t GetRollDistance(uint64_t seek_preroll_ns, uint32_t sampling_frequency) {
160 const double kNanosecondsPerSecond = 1000000000;
161 const double preroll_in_samples =
162 seek_preroll_ns / kNanosecondsPerSecond * sampling_frequency;
164 return -
static_cast<int16_t
>(preroll_in_samples + 0.5);
170 MP4Muxer::~MP4Muxer() {}
172 Status MP4Muxer::InitializeMuxer() {
174 to_be_initialized_ =
true;
178 Status MP4Muxer::Finalize() {
183 DCHECK(to_be_initialized_);
185 <<
"' which does not contain any sample.";
189 Status segmenter_finalized = segmenter_->Finalize();
191 if (!segmenter_finalized.ok())
192 return segmenter_finalized;
194 FireOnMediaEndEvent();
199 Status MP4Muxer::AddMediaSample(
size_t stream_id,
const MediaSample& sample) {
200 if (to_be_initialized_) {
201 RETURN_IF_ERROR(UpdateEditListOffsetFromSample(sample));
202 RETURN_IF_ERROR(DelayInitializeMuxer());
203 to_be_initialized_ =
false;
206 return segmenter_->AddSample(stream_id, sample);
209 Status MP4Muxer::FinalizeSegment(
size_t stream_id,
210 const SegmentInfo& segment_info) {
212 VLOG(3) <<
"Finalizing " << (segment_info.is_subsegment ?
"sub" :
"")
213 <<
"segment " << segment_info.start_timestamp <<
" duration "
214 << segment_info.duration <<
" segment number "
215 << segment_info.segment_number;
216 return segmenter_->FinalizeSegment(stream_id, segment_info);
219 Status MP4Muxer::DelayInitializeMuxer() {
220 DCHECK(!streams().empty());
222 std::unique_ptr<FileType> ftyp(
new FileType);
223 std::unique_ptr<Movie> moov(
new Movie);
225 ftyp->major_brand = FOURCC_mp41;
226 ftyp->compatible_brands.push_back(FOURCC_iso8);
227 ftyp->compatible_brands.push_back(FOURCC_isom);
228 ftyp->compatible_brands.push_back(FOURCC_mp41);
229 ftyp->compatible_brands.push_back(FOURCC_dash);
231 if (streams().size() == 1) {
232 FourCC codec_fourcc = FOURCC_NULL;
233 if (streams()[0]->stream_type() == kStreamVideo) {
235 CodecToFourCC(streams()[0]->codec(),
236 static_cast<const VideoStreamInfo*
>(streams()[0].get())
237 ->h26x_stream_format());
238 if (codec_fourcc != FOURCC_NULL)
239 ftyp->compatible_brands.push_back(codec_fourcc);
242 std::string codec_string =
243 static_cast<const VideoStreamInfo*
>(streams()[0].get())
245 std::string supplemental_codec_string =
246 static_cast<const VideoStreamInfo*
>(streams()[0].get())
247 ->supplemental_codec();
248 if (codec_string.find(
"dvh") != std::string::npos ||
249 supplemental_codec_string.find(
"dvh") != std::string::npos ||
250 codec_string.find(
"dav1") != std::string::npos ||
251 supplemental_codec_string.find(
"dav1") != std::string::npos)
252 ftyp->compatible_brands.push_back(FOURCC_dby1);
254 static_cast<const VideoStreamInfo*
>(streams()[0].get())
255 ->compatible_brand();
256 if (extra_brand != FOURCC_NULL)
257 ftyp->compatible_brands.push_back(extra_brand);
263 if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
264 ftyp->compatible_brands.push_back(FOURCC_cmfc);
266 if (streams()[0]->stream_type() == kStreamAudio) {
268 CodecToFourCC(streams()[0]->codec(), H26xStreamFormat::kUnSpecified);
269 if (codec_fourcc == FOURCC_iamf)
270 ftyp->compatible_brands.push_back(FOURCC_iamf);
274 moov->header.creation_time = IsoTimeNow();
275 moov->header.modification_time = IsoTimeNow();
276 moov->header.next_track_id =
static_cast<uint32_t
>(streams().size()) + 1;
278 moov->tracks.resize(streams().size());
279 moov->extends.tracks.resize(streams().size());
282 for (uint32_t i = 0; i < streams().size(); ++i) {
283 const StreamInfo* stream = streams()[i].get();
284 Track& trak = moov->tracks[i];
285 trak.header.track_id = i + 1;
287 TrackExtends& trex = moov->extends.tracks[i];
288 trex.track_id = trak.header.track_id;
289 trex.default_sample_description_index = 1;
291 bool generate_trak_result =
false;
292 switch (stream->stream_type()) {
294 generate_trak_result = GenerateVideoTrak(
295 static_cast<const VideoStreamInfo*
>(stream), &trak);
298 generate_trak_result = GenerateAudioTrak(
299 static_cast<const AudioStreamInfo*
>(stream), &trak);
302 generate_trak_result = GenerateTextTrak(
303 static_cast<const TextStreamInfo*
>(stream), &trak);
306 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
307 << stream->stream_type();
309 if (!generate_trak_result)
310 return Status(error::MUXER_FAILURE,
"Failed to generate trak.");
314 if (edit_list_offset_.value() > 0) {
316 entry.media_time = edit_list_offset_.value();
317 entry.media_rate_integer = 1;
318 trak.edit.list.edits.push_back(entry);
321 if (stream->is_encrypted() && options().mp4_params.include_pssh_in_stream) {
323 const auto& key_system_info = stream->encryption_config().key_system_info;
324 for (
const ProtectionSystemSpecificInfo& system : key_system_info) {
325 if (system.psshs.empty())
327 ProtectionSystemSpecificHeader pssh;
328 pssh.raw_box = system.psshs;
329 moov->pssh.push_back(pssh);
334 if (options().segment_template.empty()) {
335 segmenter_.reset(
new SingleSegmentSegmenter(options(), std::move(ftyp),
337 }
else if (options().mp4_params.low_latency_dash_mode) {
338 segmenter_.reset(
new LowLatencySegmentSegmenter(options(), std::move(ftyp),
342 new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
345 const Status segmenter_initialized =
346 segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
347 if (!segmenter_initialized.ok())
348 return segmenter_initialized;
350 FireOnMediaStartEvent();
354 Status MP4Muxer::UpdateEditListOffsetFromSample(
const MediaSample& sample) {
355 if (edit_list_offset_)
358 const int64_t pts = sample.pts();
359 const int64_t dts = sample.dts();
391 const int64_t pts_dts_offset = pts - dts;
392 if (pts_dts_offset > 0) {
394 LOG(ERROR) <<
"Negative presentation timestamp (" << pts
395 <<
") is not supported when there is an offset between "
396 "presentation timestamp and decoding timestamp ("
398 return Status(error::MUXER_FAILURE,
399 "Unsupported negative pts when there is an offset between "
402 edit_list_offset_ = pts_dts_offset;
405 if (pts_dts_offset < 0) {
406 LOG(ERROR) <<
"presentation timestamp (" << pts
407 <<
") is not supposed to be greater than decoding timestamp ("
409 return Status(error::MUXER_FAILURE,
"Not expecting pts < dts.");
411 edit_list_offset_ = std::max(-sample.pts(),
static_cast<int64_t
>(0));
415 void MP4Muxer::InitializeTrak(
const StreamInfo* info, Track* trak) {
416 int64_t now = IsoTimeNow();
417 trak->header.creation_time = now;
418 trak->header.modification_time = now;
419 trak->header.duration = 0;
420 trak->media.header.creation_time = now;
421 trak->media.header.modification_time = now;
422 trak->media.header.timescale = info->time_scale();
423 trak->media.header.duration = 0;
424 if (!info->language().empty()) {
426 std::string main_language = info->language();
427 size_t dash = main_language.find(
'-');
428 if (dash != std::string::npos) {
429 main_language.erase(dash);
433 if (main_language.size() != 3) {
434 LOG(WARNING) <<
"'" << main_language <<
"' is not a valid ISO-639-2 "
435 <<
"language code, ignoring.";
437 trak->media.header.language.code = main_language;
442 bool MP4Muxer::GenerateVideoTrak(
const VideoStreamInfo* video_info,
444 InitializeTrak(video_info, trak);
448 uint32_t pixel_width = video_info->pixel_width();
449 uint32_t pixel_height = video_info->pixel_height();
450 if (pixel_width == 0 || pixel_height == 0) {
451 LOG(WARNING) <<
"pixel width/height are not set. Assuming 1:1.";
455 const double sample_aspect_ratio =
456 static_cast<double>(pixel_width) / pixel_height;
457 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
458 trak->header.height = video_info->height() * 0x10000;
460 VideoSampleEntry video;
462 CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
463 video.width = video_info->width();
464 video.height = video_info->height();
465 video.colr.raw_box = video_info->colr_data();
466 video.codec_configuration.data = video_info->codec_config();
467 if (!video.ParseExtraCodecConfigsVector(video_info->extra_config())) {
468 LOG(ERROR) <<
"Malformed extra codec configs: "
469 << absl::BytesToHexString(
470 absl::string_view(
reinterpret_cast<const char*
>(
471 video_info->extra_config().data()),
472 video_info->extra_config().size()));
475 if (pixel_width != 1 || pixel_height != 1) {
476 video.pixel_aspect.h_spacing = pixel_width;
477 video.pixel_aspect.v_spacing = pixel_height;
480 SampleDescription& sample_description =
481 trak->media.information.sample_table.description;
482 sample_description.type = kVideo;
483 sample_description.video_entries.push_back(video);
485 if (video_info->is_encrypted()) {
486 if (video_info->has_clear_lead()) {
488 sample_description.video_entries.push_back(video);
491 VideoSampleEntry& entry = sample_description.video_entries[0];
492 GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
493 entry.format = FOURCC_encv;
498 bool MP4Muxer::GenerateAudioTrak(
const AudioStreamInfo* audio_info,
500 InitializeTrak(audio_info, trak);
502 trak->header.volume = 0x100;
504 AudioSampleEntry audio;
506 CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
507 switch(audio_info->codec()){
509 DecoderConfigDescriptor* decoder_config =
510 audio.esds.es_descriptor.mutable_decoder_config_descriptor();
511 decoder_config->set_object_type(ObjectType::kISO_14496_3);
512 decoder_config->set_max_bitrate(audio_info->max_bitrate());
513 decoder_config->set_avg_bitrate(audio_info->avg_bitrate());
514 decoder_config->mutable_decoder_specific_info_descriptor()->set_data(
515 audio_info->codec_config());
523 audio.ddts.extra_data = audio_info->codec_config();
524 audio.ddts.max_bitrate = audio_info->max_bitrate();
525 audio.ddts.avg_bitrate = audio_info->avg_bitrate();
526 audio.ddts.sampling_frequency = audio_info->sampling_frequency();
527 audio.ddts.pcm_sample_depth = audio_info->sample_bits();
530 audio.udts.data = audio_info->codec_config();
533 audio.dac3.data = audio_info->codec_config();
536 audio.dec3.data = audio_info->codec_config();
539 audio.dac4.data = audio_info->codec_config();
542 audio.alac.data = audio_info->codec_config();
545 audio.dfla.data = audio_info->codec_config();
548 DecoderConfigDescriptor* decoder_config =
549 audio.esds.es_descriptor.mutable_decoder_config_descriptor();
550 uint32_t samplerate = audio_info->sampling_frequency();
551 if (samplerate < 32000)
552 decoder_config->set_object_type(ObjectType::kISO_13818_3_MPEG1);
554 decoder_config->set_object_type(ObjectType::kISO_11172_3_MPEG1);
555 decoder_config->set_max_bitrate(audio_info->max_bitrate());
556 decoder_config->set_avg_bitrate(audio_info->avg_bitrate());
566 audio.dops.opus_identification_header = audio_info->codec_config();
569 audio.iacb.data = audio_info->codec_config();
573 audio.mhac.data = audio_info->codec_config();
576 NOTIMPLEMENTED() <<
" Unsupported audio codec " << audio_info->codec();
580 if (audio_info->codec() == kCodecAC3 || audio_info->codec() == kCodecEAC3) {
583 audio.channelcount = 2;
584 audio.samplesize = 16;
585 }
else if (audio_info->codec() == kCodecAC4) {
588 audio.channelcount = audio_info->num_channels();
590 audio.samplesize = 16;
591 }
else if (audio_info->codec() == kCodecIAMF) {
594 audio.channelcount = 0;
596 audio.channelcount = audio_info->num_channels();
597 audio.samplesize = audio_info->sample_bits();
603 audio_info->codec() == kCodecIAMF ? 0 : audio_info->sampling_frequency();
605 SampleTable& sample_table = trak->media.information.sample_table;
606 SampleDescription& sample_description = sample_table.description;
607 sample_description.type = kAudio;
608 sample_description.audio_entries.push_back(audio);
610 if (audio_info->is_encrypted()) {
611 if (audio_info->has_clear_lead()) {
613 sample_description.audio_entries.push_back(audio);
616 AudioSampleEntry& entry = sample_description.audio_entries[0];
617 GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
618 entry.format = FOURCC_enca;
621 if (audio_info->seek_preroll_ns() > 0) {
622 sample_table.sample_group_descriptions.resize(1);
623 SampleGroupDescription& sample_group_description =
624 sample_table.sample_group_descriptions.back();
625 sample_group_description.grouping_type = FOURCC_roll;
626 sample_group_description.audio_roll_recovery_entries.resize(1);
627 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
628 GetRollDistance(audio_info->seek_preroll_ns(), audio.samplerate);
635 bool MP4Muxer::GenerateTextTrak(
const TextStreamInfo* text_info,
637 InitializeTrak(text_info, trak);
639 if (text_info->codec_string() ==
"wvtt") {
641 TextSampleEntry webvtt;
642 webvtt.format = FOURCC_wvtt;
648 webvtt.config.config =
"WEBVTT";
651 if (!text_info->regions().empty() || !text_info->css_styles().empty()) {
652 LOG(INFO) <<
"Skipping possible style / region configuration as the spec "
653 "does not define a way to carry them inside ISO-BMFF files.";
659 webvtt.label.source_label =
"source_label";
660 SampleDescription& sample_description =
661 trak->media.information.sample_table.description;
662 sample_description.type = kText;
663 sample_description.text_entries.push_back(webvtt);
665 }
else if (text_info->codec_string() ==
"ttml") {
667 TextSampleEntry ttml;
668 ttml.format = FOURCC_stpp;
669 ttml.namespace_ = ttml::TtmlGenerator::kTtNamespace;
671 SampleDescription& sample_description =
672 trak->media.information.sample_table.description;
673 sample_description.type = kSubtitle;
674 sample_description.text_entries.push_back(ttml);
677 NOTIMPLEMENTED() << text_info->codec_string()
678 <<
" handling not implemented yet.";
682 std::optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
683 size_t range_offset = 0;
684 size_t range_size = 0;
685 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
691 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
695 std::optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
696 size_t range_offset = 0;
697 size_t range_size = 0;
698 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
704 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
708 void MP4Muxer::FireOnMediaStartEvent() {
709 if (!muxer_listener())
712 if (streams().size() > 1) {
713 LOG(ERROR) <<
"MuxerListener cannot take more than 1 stream.";
716 DCHECK(!streams().empty()) <<
"Media started without a stream.";
718 const int32_t timescale = segmenter_->GetReferenceTimeScale();
719 muxer_listener()->
OnMediaStart(options(), *streams().front(), timescale,
720 MuxerListener::kContainerMp4);
723 void MP4Muxer::FireOnMediaEndEvent() {
724 if (!muxer_listener())
727 MuxerListener::MediaRanges media_range;
728 media_range.init_range = GetInitRangeStartAndEnd();
729 media_range.index_range = GetIndexRangeStartAndEnd();
730 media_range.subsegment_ranges = segmenter_->GetSegmentRanges();
732 const float duration_seconds =
static_cast<float>(segmenter_->GetDuration());
733 muxer_listener()->
OnMediaEnd(media_range, duration_seconds);
736 uint64_t MP4Muxer::IsoTimeNow() {
738 const uint64_t kIsomTimeOffset = 2082844800l;
741 std::int64_t secondsSince1970 = Now();
744 return secondsSince1970 + kIsomTimeOffset;
All the methods that are virtual are virtual for mocking.