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;
97 track_encryption.default_crypt_byte_block =
98 encryption_config.crypt_byte_block;
99 track_encryption.default_skip_byte_block = encryption_config.skip_byte_block;
100 track_encryption.default_per_sample_iv_size =
101 encryption_config.per_sample_iv_size;
102 track_encryption.default_constant_iv = encryption_config.constant_iv;
103 track_encryption.default_kid = encryption_config.key_id;
109 MP4Muxer::~MP4Muxer() {}
111 Status MP4Muxer::InitializeMuxer() {
112 DCHECK(!streams().empty());
114 std::unique_ptr<FileType> ftyp(
new FileType);
115 std::unique_ptr<Movie> moov(
new Movie);
117 ftyp->major_brand = FOURCC_isom;
118 ftyp->compatible_brands.push_back(FOURCC_iso8);
119 ftyp->compatible_brands.push_back(FOURCC_mp41);
120 ftyp->compatible_brands.push_back(FOURCC_dash);
122 if (streams().size() == 1) {
123 FourCC codec_fourcc = FOURCC_NULL;
124 if (streams()[0]->stream_type() == kStreamVideo) {
126 CodecToFourCC(streams()[0]->codec(),
127 static_cast<const VideoStreamInfo*>(streams()[0].
get())
128 ->h26x_stream_format());
129 if (codec_fourcc != FOURCC_NULL)
130 ftyp->compatible_brands.push_back(codec_fourcc);
136 if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
137 ftyp->compatible_brands.push_back(FOURCC_cmfc);
140 moov->header.creation_time = IsoTimeNow();
141 moov->header.modification_time = IsoTimeNow();
142 moov->header.next_track_id =
static_cast<uint32_t
>(streams().size()) + 1;
144 moov->tracks.resize(streams().size());
145 moov->extends.tracks.resize(streams().size());
148 for (uint32_t i = 0; i < streams().size(); ++i) {
149 Track& trak = moov->tracks[i];
150 trak.header.track_id = i + 1;
152 TrackExtends& trex = moov->extends.tracks[i];
153 trex.track_id = trak.header.track_id;
154 trex.default_sample_description_index = 1;
156 switch (streams()[i]->stream_type()) {
159 static_cast<const VideoStreamInfo*>(streams()[i].
get()),
165 static_cast<const AudioStreamInfo*>(streams()[i].
get()),
171 static_cast<const TextStreamInfo*>(streams()[i].
get()),
176 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
177 << streams()[i]->stream_type();
180 if (streams()[i]->is_encrypted() &&
181 options().mp4_params.include_pssh_in_stream) {
182 const auto& key_system_info =
183 streams()[i]->encryption_config().key_system_info;
184 moov->pssh.resize(key_system_info.size());
185 for (
size_t j = 0; j < key_system_info.size(); j++)
186 moov->pssh[j].raw_box = key_system_info[j].CreateBox();
190 if (options().segment_template.empty()) {
191 segmenter_.reset(
new SingleSegmentSegmenter(options(), std::move(ftyp),
195 new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
198 const Status segmenter_initialized =
199 segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
200 if (!segmenter_initialized.ok())
201 return segmenter_initialized;
203 FireOnMediaStartEvent();
207 Status MP4Muxer::Finalize() {
209 Status segmenter_finalized = segmenter_->Finalize();
211 if (!segmenter_finalized.ok())
212 return segmenter_finalized;
214 FireOnMediaEndEvent();
219 Status MP4Muxer::AddSample(
size_t stream_id,
const MediaSample& sample) {
221 return segmenter_->AddSample(stream_id, sample);
224 Status MP4Muxer::FinalizeSegment(
size_t stream_id,
225 const SegmentInfo& segment_info) {
227 VLOG(3) <<
"Finalize " << (segment_info.is_subsegment ?
"sub" :
"")
228 <<
"segment " << segment_info.start_timestamp <<
" duration "
229 << segment_info.duration;
230 return segmenter_->FinalizeSegment(stream_id, segment_info);
233 void MP4Muxer::InitializeTrak(
const StreamInfo* info, Track* trak) {
234 int64_t now = IsoTimeNow();
235 trak->header.creation_time = now;
236 trak->header.modification_time = now;
237 trak->header.duration = 0;
238 trak->media.header.creation_time = now;
239 trak->media.header.modification_time = now;
240 trak->media.header.timescale = info->time_scale();
241 trak->media.header.duration = 0;
242 if (!info->language().empty()) {
244 std::string main_language = info->language();
245 size_t dash = main_language.find(
'-');
246 if (dash != std::string::npos) {
247 main_language.erase(dash);
251 if (main_language.size() != 3) {
252 LOG(WARNING) <<
"'" << main_language <<
"' is not a valid ISO-639-2 "
253 <<
"language code, ignoring.";
255 trak->media.header.language.code = main_language;
260 void MP4Muxer::GenerateVideoTrak(
const VideoStreamInfo* video_info,
263 InitializeTrak(video_info, trak);
267 uint32_t pixel_width = video_info->pixel_width();
268 uint32_t pixel_height = video_info->pixel_height();
269 if (pixel_width == 0 || pixel_height == 0) {
270 LOG(WARNING) <<
"pixel width/height are not set. Assuming 1:1.";
274 const double sample_aspect_ratio =
275 static_cast<double>(pixel_width) / pixel_height;
276 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
277 trak->header.height = video_info->height() * 0x10000;
279 VideoSampleEntry video;
281 CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
282 video.width = video_info->width();
283 video.height = video_info->height();
284 video.codec_configuration.data = video_info->codec_config();
285 if (pixel_width != 1 || pixel_height != 1) {
286 video.pixel_aspect.h_spacing = pixel_width;
287 video.pixel_aspect.v_spacing = pixel_height;
290 SampleDescription& sample_description =
291 trak->media.information.sample_table.description;
292 sample_description.type = kVideo;
293 sample_description.video_entries.push_back(video);
295 if (video_info->is_encrypted()) {
296 if (video_info->has_clear_lead()) {
298 sample_description.video_entries.push_back(video);
301 VideoSampleEntry& entry = sample_description.video_entries[0];
302 GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
303 entry.format = FOURCC_encv;
307 void MP4Muxer::GenerateAudioTrak(
const AudioStreamInfo* audio_info,
310 InitializeTrak(audio_info, trak);
312 trak->header.volume = 0x100;
314 AudioSampleEntry audio;
316 CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
317 switch(audio_info->codec()){
319 audio.esds.es_descriptor.set_object_type(kISO_14496_3);
320 audio.esds.es_descriptor.set_esid(track_id);
321 audio.esds.es_descriptor.set_decoder_specific_info(
322 audio_info->codec_config());
323 audio.esds.es_descriptor.set_max_bitrate(audio_info->max_bitrate());
324 audio.esds.es_descriptor.set_avg_bitrate(audio_info->avg_bitrate());
331 audio.ddts.extra_data = audio_info->codec_config();
332 audio.ddts.max_bitrate = audio_info->max_bitrate();
333 audio.ddts.avg_bitrate = audio_info->avg_bitrate();
334 audio.ddts.sampling_frequency = audio_info->sampling_frequency();
335 audio.ddts.pcm_sample_depth = audio_info->sample_bits();
338 audio.dac3.data = audio_info->codec_config();
341 audio.dec3.data = audio_info->codec_config();
344 audio.dops.opus_identification_header = audio_info->codec_config();
351 audio.channelcount = audio_info->num_channels();
352 audio.samplesize = audio_info->sample_bits();
353 audio.samplerate = audio_info->sampling_frequency();
354 SampleTable& sample_table = trak->media.information.sample_table;
355 SampleDescription& sample_description = sample_table.description;
356 sample_description.type = kAudio;
357 sample_description.audio_entries.push_back(audio);
359 if (audio_info->is_encrypted()) {
360 if (audio_info->has_clear_lead()) {
362 sample_description.audio_entries.push_back(audio);
365 AudioSampleEntry& entry = sample_description.audio_entries[0];
366 GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
367 entry.format = FOURCC_enca;
372 if (audio_info->codec() == kCodecOpus) {
373 sample_table.sample_group_descriptions.resize(1);
374 SampleGroupDescription& sample_group_description =
375 sample_table.sample_group_descriptions.back();
376 sample_group_description.grouping_type = FOURCC_roll;
377 sample_group_description.audio_roll_recovery_entries.resize(1);
380 const uint64_t kNanosecondsPerSecond = 1000000000ull;
381 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
382 (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
383 kNanosecondsPerSecond / 2)) /
384 kNanosecondsPerSecond;
386 sample_table.sample_to_groups.resize(1);
387 SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
388 sample_to_group.grouping_type = FOURCC_roll;
390 sample_to_group.entries.resize(1);
391 SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
393 sample_to_group_entry.sample_count = 0;
394 sample_to_group_entry.group_description_index =
395 SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
396 }
else if (audio_info->seek_preroll_ns() != 0) {
397 LOG(WARNING) <<
"Unexpected seek preroll for codec " << audio_info->codec();
402 void MP4Muxer::GenerateTextTrak(
const TextStreamInfo* text_info,
405 InitializeTrak(text_info, trak);
407 if (text_info->codec_string() ==
"wvtt") {
409 TextSampleEntry webvtt;
410 webvtt.format = FOURCC_wvtt;
411 webvtt.config.config.assign(text_info->codec_config().begin(),
412 text_info->codec_config().end());
416 webvtt.label.source_label =
"source_label";
417 SampleDescription& sample_description =
418 trak->media.information.sample_table.description;
419 sample_description.type = kText;
420 sample_description.text_entries.push_back(webvtt);
423 NOTIMPLEMENTED() << text_info->codec_string()
424 <<
" handling not implemented yet.";
427 base::Optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
428 size_t range_offset = 0;
429 size_t range_size = 0;
430 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
433 return base::nullopt;
436 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
440 base::Optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
441 size_t range_offset = 0;
442 size_t range_size = 0;
443 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
446 return base::nullopt;
449 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
453 void MP4Muxer::FireOnMediaStartEvent() {
454 if (!muxer_listener())
457 if (streams().size() > 1) {
458 LOG(ERROR) <<
"MuxerListener cannot take more than 1 stream.";
461 DCHECK(!streams().empty()) <<
"Media started without a stream.";
463 const uint32_t timescale = segmenter_->GetReferenceTimeScale();
464 muxer_listener()->
OnMediaStart(options(), *streams().front(), timescale,
465 MuxerListener::kContainerMp4);
468 void MP4Muxer::FireOnMediaEndEvent() {
469 if (!muxer_listener())
472 MuxerListener::MediaRanges media_range;
473 media_range.init_range = GetInitRangeStartAndEnd();
474 media_range.index_range = GetIndexRangeStartAndEnd();
475 media_range.subsegment_ranges = segmenter_->GetSegmentRanges();
477 const float duration_seconds =
static_cast<float>(segmenter_->GetDuration());
478 muxer_listener()->
OnMediaEnd(media_range, duration_seconds);
481 uint64_t MP4Muxer::IsoTimeNow() {
483 const uint64_t kIsomTimeOffset = 2082844800l;
484 return kIsomTimeOffset +
485 (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();