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
85 void GenerateSinf(FourCC old_type,
86 const EncryptionConfig& encryption_config,
87 ProtectionSchemeInfo* sinf) {
88 sinf->format.format = old_type;
90 DCHECK_NE(encryption_config.protection_scheme, FOURCC_NULL);
91 sinf->type.type = encryption_config.protection_scheme;
94 const int kCencSchemeVersion = 0x00010000;
95 sinf->type.version = kCencSchemeVersion;
97 auto& track_encryption = sinf->info.track_encryption;
98 track_encryption.default_is_protected = 1;
100 track_encryption.default_crypt_byte_block =
101 encryption_config.crypt_byte_block;
102 track_encryption.default_skip_byte_block = encryption_config.skip_byte_block;
103 switch (encryption_config.protection_scheme) {
106 DCHECK_EQ(track_encryption.default_crypt_byte_block, 0u);
107 DCHECK_EQ(track_encryption.default_skip_byte_block, 0u);
110 track_encryption.version = 0;
114 if (track_encryption.default_skip_byte_block == 0) {
117 track_encryption.default_crypt_byte_block = 0;
122 track_encryption.version = 1;
125 NOTREACHED() <<
"Unexpected protection scheme " 126 << encryption_config.protection_scheme;
129 track_encryption.default_per_sample_iv_size =
130 encryption_config.per_sample_iv_size;
131 track_encryption.default_constant_iv = encryption_config.constant_iv;
132 track_encryption.default_kid = encryption_config.key_id;
138 MP4Muxer::~MP4Muxer() {}
140 Status MP4Muxer::InitializeMuxer() {
141 DCHECK(!streams().empty());
143 std::unique_ptr<FileType> ftyp(
new FileType);
144 std::unique_ptr<Movie> moov(
new Movie);
146 ftyp->major_brand = FOURCC_isom;
147 ftyp->compatible_brands.push_back(FOURCC_iso8);
148 ftyp->compatible_brands.push_back(FOURCC_mp41);
149 ftyp->compatible_brands.push_back(FOURCC_dash);
151 if (streams().size() == 1) {
152 FourCC codec_fourcc = FOURCC_NULL;
153 if (streams()[0]->stream_type() == kStreamVideo) {
155 CodecToFourCC(streams()[0]->codec(),
156 static_cast<const VideoStreamInfo*>(streams()[0].
get())
157 ->h26x_stream_format());
158 if (codec_fourcc != FOURCC_NULL)
159 ftyp->compatible_brands.push_back(codec_fourcc);
165 if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
166 ftyp->compatible_brands.push_back(FOURCC_cmfc);
169 moov->header.creation_time = IsoTimeNow();
170 moov->header.modification_time = IsoTimeNow();
171 moov->header.next_track_id =
static_cast<uint32_t
>(streams().size()) + 1;
173 moov->tracks.resize(streams().size());
174 moov->extends.tracks.resize(streams().size());
177 for (uint32_t i = 0; i < streams().size(); ++i) {
178 const StreamInfo* stream = streams()[i].get();
179 Track& trak = moov->tracks[i];
180 trak.header.track_id = i + 1;
183 trex.track_id = trak.header.track_id;
184 trex.default_sample_description_index = 1;
186 bool generate_trak_result =
false;
187 switch (stream->stream_type()) {
189 generate_trak_result = GenerateVideoTrak(
190 static_cast<const VideoStreamInfo*>(stream), &trak, i + 1);
193 generate_trak_result = GenerateAudioTrak(
194 static_cast<const AudioStreamInfo*>(stream), &trak, i + 1);
197 generate_trak_result = GenerateTextTrak(
198 static_cast<const TextStreamInfo*>(stream), &trak, i + 1);
201 NOTIMPLEMENTED() <<
"Not implemented for stream type: " 202 << stream->stream_type();
204 if (!generate_trak_result)
205 return Status(error::MUXER_FAILURE,
"Failed to generate trak.");
207 if (stream->is_encrypted() && options().
mp4_params.include_pssh_in_stream) {
208 const auto& key_system_info = stream->encryption_config().key_system_info;
209 moov->pssh.resize(key_system_info.size());
210 for (
size_t j = 0; j < key_system_info.size(); j++)
211 moov->pssh[j].raw_box = key_system_info[j].psshs;
223 const Status segmenter_initialized =
224 segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
225 if (!segmenter_initialized.ok())
226 return segmenter_initialized;
228 FireOnMediaStartEvent();
232 Status MP4Muxer::Finalize() {
234 Status segmenter_finalized = segmenter_->Finalize();
236 if (!segmenter_finalized.ok())
237 return segmenter_finalized;
239 FireOnMediaEndEvent();
246 return segmenter_->AddSample(stream_id, sample);
249 Status MP4Muxer::FinalizeSegment(
size_t stream_id,
252 VLOG(3) <<
"Finalize " << (segment_info.is_subsegment ?
"sub" :
"")
253 <<
"segment " << segment_info.start_timestamp <<
" duration " 254 << segment_info.duration;
255 return segmenter_->FinalizeSegment(stream_id, segment_info);
259 int64_t now = IsoTimeNow();
260 trak->header.creation_time = now;
261 trak->header.modification_time = now;
262 trak->header.duration = 0;
263 trak->media.header.creation_time = now;
264 trak->media.header.modification_time = now;
265 trak->media.header.timescale = info->time_scale();
266 trak->media.header.duration = 0;
267 if (!info->language().empty()) {
269 std::string main_language = info->language();
270 size_t dash = main_language.find(
'-');
271 if (dash != std::string::npos) {
272 main_language.erase(dash);
276 if (main_language.size() != 3) {
277 LOG(WARNING) <<
"'" << main_language <<
"' is not a valid ISO-639-2 " 278 <<
"language code, ignoring.";
280 trak->media.header.language.code = main_language;
288 InitializeTrak(video_info, trak);
294 if (pixel_width == 0 || pixel_height == 0) {
295 LOG(WARNING) <<
"pixel width/height are not set. Assuming 1:1.";
299 const double sample_aspect_ratio =
300 static_cast<double>(pixel_width) / pixel_height;
301 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
302 trak->header.height = video_info->height() * 0x10000;
306 CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
307 video.width = video_info->width();
308 video.height = video_info->height();
309 video.codec_configuration.data = video_info->codec_config();
310 if (pixel_width != 1 || pixel_height != 1) {
311 video.pixel_aspect.h_spacing = pixel_width;
312 video.pixel_aspect.v_spacing = pixel_height;
316 trak->media.information.sample_table.description;
317 sample_description.type = kVideo;
318 sample_description.video_entries.push_back(video);
320 if (video_info->is_encrypted()) {
321 if (video_info->has_clear_lead()) {
323 sample_description.video_entries.push_back(video);
327 GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
328 entry.format = FOURCC_encv;
336 InitializeTrak(audio_info, trak);
338 trak->header.volume = 0x100;
342 CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
343 switch(audio_info->codec()){
345 audio.esds.es_descriptor.set_object_type(
346 ObjectType::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.dfla.data = audio_info->codec_config();
374 audio.dops.opus_identification_header = audio_info->codec_config();
377 NOTIMPLEMENTED() <<
" Unsupported audio codec " << audio_info->codec();
381 if (audio_info->codec() == kCodecAC3 || audio_info->codec() == kCodecEAC3) {
384 audio.channelcount = 2;
385 audio.samplesize = 16;
387 audio.channelcount = audio_info->num_channels();
388 audio.samplesize = audio_info->sample_bits();
390 audio.samplerate = audio_info->sampling_frequency();
391 SampleTable& sample_table = trak->media.information.sample_table;
393 sample_description.type = kAudio;
394 sample_description.audio_entries.push_back(audio);
396 if (audio_info->is_encrypted()) {
397 if (audio_info->has_clear_lead()) {
399 sample_description.audio_entries.push_back(audio);
403 GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
404 entry.format = FOURCC_enca;
409 if (audio_info->codec() == kCodecOpus) {
410 sample_table.sample_group_descriptions.resize(1);
412 sample_table.sample_group_descriptions.back();
413 sample_group_description.grouping_type = FOURCC_roll;
414 sample_group_description.audio_roll_recovery_entries.resize(1);
417 const uint64_t kNanosecondsPerSecond = 1000000000ull;
418 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
419 (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
420 kNanosecondsPerSecond / 2)) /
421 kNanosecondsPerSecond;
423 sample_table.sample_to_groups.resize(1);
424 SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
425 sample_to_group.grouping_type = FOURCC_roll;
427 sample_to_group.entries.resize(1);
430 sample_to_group_entry.sample_count = 0;
431 sample_to_group_entry.group_description_index =
432 SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
433 }
else if (audio_info->seek_preroll_ns() != 0) {
434 LOG(WARNING) <<
"Unexpected seek preroll for codec " << audio_info->codec();
442 InitializeTrak(text_info, trak);
444 if (text_info->codec_string() ==
"wvtt") {
447 webvtt.format = FOURCC_wvtt;
448 webvtt.config.config.assign(text_info->codec_config().begin(),
449 text_info->codec_config().end());
453 webvtt.label.source_label =
"source_label";
455 trak->media.information.sample_table.description;
456 sample_description.type = kText;
457 sample_description.text_entries.push_back(webvtt);
460 NOTIMPLEMENTED() << text_info->codec_string()
461 <<
" handling not implemented yet.";
465 base::Optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
466 size_t range_offset = 0;
467 size_t range_size = 0;
468 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
471 return base::nullopt;
474 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
478 base::Optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
479 size_t range_offset = 0;
480 size_t range_size = 0;
481 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
484 return base::nullopt;
487 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
491 void MP4Muxer::FireOnMediaStartEvent() {
492 if (!muxer_listener())
495 if (streams().size() > 1) {
496 LOG(ERROR) <<
"MuxerListener cannot take more than 1 stream.";
499 DCHECK(!streams().empty()) <<
"Media started without a stream.";
501 const uint32_t timescale = segmenter_->GetReferenceTimeScale();
502 muxer_listener()->
OnMediaStart(options(), *streams().front(), timescale,
503 MuxerListener::kContainerMp4);
506 void MP4Muxer::FireOnMediaEndEvent() {
507 if (!muxer_listener())
511 media_range.
init_range = GetInitRangeStartAndEnd();
512 media_range.
index_range = GetIndexRangeStartAndEnd();
515 const float duration_seconds =
static_cast<float>(segmenter_->GetDuration());
516 muxer_listener()->
OnMediaEnd(media_range, duration_seconds);
519 uint64_t MP4Muxer::IsoTimeNow() {
521 const uint64_t kIsomTimeOffset = 2082844800l;
522 return kIsomTimeOffset +
523 (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();
All the methods that are virtual are virtual for mocking.