7 #include "packager/media/formats/mp4/mp4_muxer.h" 9 #include "packager/base/time/clock.h" 10 #include "packager/base/time/time.h" 11 #include "packager/file/file.h" 12 #include "packager/media/base/aes_encryptor.h" 13 #include "packager/media/base/audio_stream_info.h" 14 #include "packager/media/base/fourccs.h" 15 #include "packager/media/base/key_source.h" 16 #include "packager/media/base/media_sample.h" 17 #include "packager/media/base/text_stream_info.h" 18 #include "packager/media/base/video_stream_info.h" 19 #include "packager/media/codecs/es_descriptor.h" 20 #include "packager/media/event/muxer_listener.h" 21 #include "packager/media/formats/mp4/box_definitions.h" 22 #include "packager/media/formats/mp4/multi_segment_segmenter.h" 23 #include "packager/media/formats/mp4/single_segment_segmenter.h" 33 void SetStartAndEndFromOffsetAndSize(
size_t offset,
37 range->start =
static_cast<uint32_t
>(offset);
39 range->end = range->start +
static_cast<uint32_t
>(size) - 1;
42 FourCC CodecToFourCC(Codec codec, H26xStreamFormat h26x_stream_format) {
45 return h26x_stream_format ==
46 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
50 return h26x_stream_format ==
51 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
83 void GenerateSinf(FourCC old_type,
84 const EncryptionConfig& encryption_config,
85 ProtectionSchemeInfo* sinf) {
86 sinf->format.format = old_type;
88 DCHECK_NE(encryption_config.protection_scheme, FOURCC_NULL);
89 sinf->type.type = encryption_config.protection_scheme;
92 const int kCencSchemeVersion = 0x00010000;
93 sinf->type.version = kCencSchemeVersion;
95 auto& track_encryption = sinf->info.track_encryption;
96 track_encryption.default_is_protected = 1;
98 track_encryption.default_crypt_byte_block =
99 encryption_config.crypt_byte_block;
100 track_encryption.default_skip_byte_block = encryption_config.skip_byte_block;
101 switch (encryption_config.protection_scheme) {
104 DCHECK_EQ(track_encryption.default_crypt_byte_block, 0u);
105 DCHECK_EQ(track_encryption.default_skip_byte_block, 0u);
108 track_encryption.version = 0;
112 if (track_encryption.default_skip_byte_block == 0) {
115 track_encryption.default_crypt_byte_block = 0;
120 track_encryption.version = 1;
123 NOTREACHED() <<
"Unexpected protection scheme " 124 << encryption_config.protection_scheme;
127 track_encryption.default_per_sample_iv_size =
128 encryption_config.per_sample_iv_size;
129 track_encryption.default_constant_iv = encryption_config.constant_iv;
130 track_encryption.default_kid = encryption_config.key_id;
136 MP4Muxer::~MP4Muxer() {}
138 Status MP4Muxer::InitializeMuxer() {
139 DCHECK(!streams().empty());
141 std::unique_ptr<FileType> ftyp(
new FileType);
142 std::unique_ptr<Movie> moov(
new Movie);
144 ftyp->major_brand = FOURCC_isom;
145 ftyp->compatible_brands.push_back(FOURCC_iso8);
146 ftyp->compatible_brands.push_back(FOURCC_mp41);
147 ftyp->compatible_brands.push_back(FOURCC_dash);
149 if (streams().size() == 1) {
150 FourCC codec_fourcc = FOURCC_NULL;
151 if (streams()[0]->stream_type() == kStreamVideo) {
153 CodecToFourCC(streams()[0]->codec(),
154 static_cast<const VideoStreamInfo*>(streams()[0].
get())
155 ->h26x_stream_format());
156 if (codec_fourcc != FOURCC_NULL)
157 ftyp->compatible_brands.push_back(codec_fourcc);
163 if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
164 ftyp->compatible_brands.push_back(FOURCC_cmfc);
167 moov->header.creation_time = IsoTimeNow();
168 moov->header.modification_time = IsoTimeNow();
169 moov->header.next_track_id =
static_cast<uint32_t
>(streams().size()) + 1;
171 moov->tracks.resize(streams().size());
172 moov->extends.tracks.resize(streams().size());
175 for (uint32_t i = 0; i < streams().size(); ++i) {
176 Track& trak = moov->tracks[i];
177 trak.header.track_id = i + 1;
180 trex.track_id = trak.header.track_id;
181 trex.default_sample_description_index = 1;
183 switch (streams()[i]->stream_type()) {
186 static_cast<const VideoStreamInfo*>(streams()[i].
get()),
192 static_cast<const AudioStreamInfo*>(streams()[i].
get()),
198 static_cast<const TextStreamInfo*>(streams()[i].
get()),
203 NOTIMPLEMENTED() <<
"Not implemented for stream type: " 204 << streams()[i]->stream_type();
207 if (streams()[i]->is_encrypted() &&
208 options().mp4_params.include_pssh_in_stream) {
209 const auto& key_system_info =
210 streams()[i]->encryption_config().key_system_info;
211 moov->pssh.resize(key_system_info.size());
212 for (
size_t j = 0; j < key_system_info.size(); j++)
213 moov->pssh[j].raw_box = key_system_info[j].CreateBox();
217 if (options().segment_template.empty()) {
225 const Status segmenter_initialized =
226 segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
227 if (!segmenter_initialized.ok())
228 return segmenter_initialized;
230 FireOnMediaStartEvent();
234 Status MP4Muxer::Finalize() {
236 Status segmenter_finalized = segmenter_->Finalize();
238 if (!segmenter_finalized.ok())
239 return segmenter_finalized;
241 FireOnMediaEndEvent();
248 return segmenter_->AddSample(stream_id, sample);
251 Status MP4Muxer::FinalizeSegment(
size_t stream_id,
254 VLOG(3) <<
"Finalize " << (segment_info.is_subsegment ?
"sub" :
"")
255 <<
"segment " << segment_info.start_timestamp <<
" duration " 256 << segment_info.duration;
257 return segmenter_->FinalizeSegment(stream_id, segment_info);
261 int64_t now = IsoTimeNow();
262 trak->header.creation_time = now;
263 trak->header.modification_time = now;
264 trak->header.duration = 0;
265 trak->media.header.creation_time = now;
266 trak->media.header.modification_time = now;
267 trak->media.header.timescale = info->time_scale();
268 trak->media.header.duration = 0;
269 if (!info->language().empty()) {
271 std::string main_language = info->language();
272 size_t dash = main_language.find(
'-');
273 if (dash != std::string::npos) {
274 main_language.erase(dash);
278 if (main_language.size() != 3) {
279 LOG(WARNING) <<
"'" << main_language <<
"' is not a valid ISO-639-2 " 280 <<
"language code, ignoring.";
282 trak->media.header.language.code = main_language;
290 InitializeTrak(video_info, trak);
296 if (pixel_width == 0 || pixel_height == 0) {
297 LOG(WARNING) <<
"pixel width/height are not set. Assuming 1:1.";
301 const double sample_aspect_ratio =
302 static_cast<double>(pixel_width) / pixel_height;
303 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
304 trak->header.height = video_info->height() * 0x10000;
308 CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
309 video.width = video_info->width();
310 video.height = video_info->height();
311 video.codec_configuration.data = video_info->codec_config();
312 if (pixel_width != 1 || pixel_height != 1) {
313 video.pixel_aspect.h_spacing = pixel_width;
314 video.pixel_aspect.v_spacing = pixel_height;
318 trak->media.information.sample_table.description;
319 sample_description.type = kVideo;
320 sample_description.video_entries.push_back(video);
322 if (video_info->is_encrypted()) {
323 if (video_info->has_clear_lead()) {
325 sample_description.video_entries.push_back(video);
329 GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
330 entry.format = FOURCC_encv;
337 InitializeTrak(audio_info, trak);
339 trak->header.volume = 0x100;
343 CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
344 switch(audio_info->codec()){
346 audio.esds.es_descriptor.set_object_type(kISO_14496_3);
347 audio.esds.es_descriptor.set_esid(track_id);
348 audio.esds.es_descriptor.set_decoder_specific_info(
349 audio_info->codec_config());
350 audio.esds.es_descriptor.set_max_bitrate(audio_info->max_bitrate());
351 audio.esds.es_descriptor.set_avg_bitrate(audio_info->avg_bitrate());
358 audio.ddts.extra_data = audio_info->codec_config();
359 audio.ddts.max_bitrate = audio_info->max_bitrate();
360 audio.ddts.avg_bitrate = audio_info->avg_bitrate();
361 audio.ddts.sampling_frequency = audio_info->sampling_frequency();
362 audio.ddts.pcm_sample_depth = audio_info->sample_bits();
365 audio.dac3.data = audio_info->codec_config();
368 audio.dec3.data = audio_info->codec_config();
371 audio.dops.opus_identification_header = audio_info->codec_config();
378 if (audio_info->codec() == kCodecAC3 || audio_info->codec() == kCodecEAC3) {
381 audio.channelcount = 2;
382 audio.samplesize = 16;
384 audio.channelcount = audio_info->num_channels();
385 audio.samplesize = audio_info->sample_bits();
387 audio.samplerate = audio_info->sampling_frequency();
388 SampleTable& sample_table = trak->media.information.sample_table;
390 sample_description.type = kAudio;
391 sample_description.audio_entries.push_back(audio);
393 if (audio_info->is_encrypted()) {
394 if (audio_info->has_clear_lead()) {
396 sample_description.audio_entries.push_back(audio);
400 GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
401 entry.format = FOURCC_enca;
406 if (audio_info->codec() == kCodecOpus) {
407 sample_table.sample_group_descriptions.resize(1);
409 sample_table.sample_group_descriptions.back();
410 sample_group_description.grouping_type = FOURCC_roll;
411 sample_group_description.audio_roll_recovery_entries.resize(1);
414 const uint64_t kNanosecondsPerSecond = 1000000000ull;
415 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
416 (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
417 kNanosecondsPerSecond / 2)) /
418 kNanosecondsPerSecond;
420 sample_table.sample_to_groups.resize(1);
421 SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
422 sample_to_group.grouping_type = FOURCC_roll;
424 sample_to_group.entries.resize(1);
427 sample_to_group_entry.sample_count = 0;
428 sample_to_group_entry.group_description_index =
429 SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
430 }
else if (audio_info->seek_preroll_ns() != 0) {
431 LOG(WARNING) <<
"Unexpected seek preroll for codec " << audio_info->codec();
439 InitializeTrak(text_info, trak);
441 if (text_info->codec_string() ==
"wvtt") {
444 webvtt.format = FOURCC_wvtt;
445 webvtt.config.config.assign(text_info->codec_config().begin(),
446 text_info->codec_config().end());
450 webvtt.label.source_label =
"source_label";
452 trak->media.information.sample_table.description;
453 sample_description.type = kText;
454 sample_description.text_entries.push_back(webvtt);
457 NOTIMPLEMENTED() << text_info->codec_string()
458 <<
" handling not implemented yet.";
461 base::Optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
462 size_t range_offset = 0;
463 size_t range_size = 0;
464 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
467 return base::nullopt;
470 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
474 base::Optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
475 size_t range_offset = 0;
476 size_t range_size = 0;
477 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
480 return base::nullopt;
483 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
487 void MP4Muxer::FireOnMediaStartEvent() {
488 if (!muxer_listener())
491 if (streams().size() > 1) {
492 LOG(ERROR) <<
"MuxerListener cannot take more than 1 stream.";
495 DCHECK(!streams().empty()) <<
"Media started without a stream.";
497 const uint32_t timescale = segmenter_->GetReferenceTimeScale();
498 muxer_listener()->
OnMediaStart(options(), *streams().front(), timescale,
499 MuxerListener::kContainerMp4);
502 void MP4Muxer::FireOnMediaEndEvent() {
503 if (!muxer_listener())
507 media_range.
init_range = GetInitRangeStartAndEnd();
508 media_range.
index_range = GetIndexRangeStartAndEnd();
511 const float duration_seconds =
static_cast<float>(segmenter_->GetDuration());
512 muxer_listener()->
OnMediaEnd(media_range, duration_seconds);
515 uint64_t MP4Muxer::IsoTimeNow() {
517 const uint64_t kIsomTimeOffset = 2082844800l;
518 return kIsomTimeOffset +
519 (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();
All the methods that are virtual are virtual for mocking.