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/media/base/aes_encryptor.h"
12 #include "packager/media/base/audio_stream_info.h"
13 #include "packager/media/base/fourccs.h"
14 #include "packager/media/base/key_source.h"
15 #include "packager/media/base/media_sample.h"
16 #include "packager/media/base/text_stream_info.h"
17 #include "packager/media/base/video_stream_info.h"
18 #include "packager/media/codecs/es_descriptor.h"
19 #include "packager/media/event/muxer_listener.h"
20 #include "packager/media/file/file.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,
38 *start =
static_cast<uint32_t
>(offset);
40 *end = *start +
static_cast<uint32_t
>(size) - 1;
43 FourCC CodecToFourCC(Codec codec, H26xStreamFormat h26x_stream_format) {
46 return h26x_stream_format ==
47 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
51 return h26x_stream_format ==
52 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
84 void GenerateSinf(FourCC old_type,
85 const EncryptionConfig& encryption_config,
86 ProtectionSchemeInfo* sinf) {
87 sinf->format.format = old_type;
89 DCHECK_NE(encryption_config.protection_scheme, FOURCC_NULL);
90 sinf->type.type = encryption_config.protection_scheme;
93 const int kCencSchemeVersion = 0x00010000;
94 sinf->type.version = kCencSchemeVersion;
96 auto& track_encryption = sinf->info.track_encryption;
97 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 track_encryption.default_per_sample_iv_size =
102 encryption_config.per_sample_iv_size;
103 track_encryption.default_constant_iv = encryption_config.constant_iv;
104 track_encryption.default_kid = encryption_config.key_id;
110 MP4Muxer::~MP4Muxer() {}
112 Status MP4Muxer::InitializeMuxer() {
113 DCHECK(!streams().empty());
115 std::unique_ptr<FileType> ftyp(
new FileType);
116 std::unique_ptr<Movie> moov(
new Movie);
118 ftyp->major_brand = FOURCC_dash;
119 ftyp->compatible_brands.push_back(FOURCC_iso6);
120 ftyp->compatible_brands.push_back(FOURCC_mp41);
121 if (streams().size() == 1 && streams()[0]->stream_type() == kStreamVideo) {
122 const FourCC codec_fourcc = CodecToFourCC(
123 streams()[0]->codec(), static_cast<VideoStreamInfo*>(streams()[0].
get())
124 ->h26x_stream_format());
125 if (codec_fourcc != FOURCC_NULL)
126 ftyp->compatible_brands.push_back(codec_fourcc);
129 moov->header.creation_time = IsoTimeNow();
130 moov->header.modification_time = IsoTimeNow();
131 moov->header.next_track_id =
static_cast<uint32_t
>(streams().size()) + 1;
133 moov->tracks.resize(streams().size());
134 moov->extends.tracks.resize(streams().size());
137 for (uint32_t i = 0; i < streams().size(); ++i) {
138 Track& trak = moov->tracks[i];
139 trak.header.track_id = i + 1;
141 TrackExtends& trex = moov->extends.tracks[i];
142 trex.track_id = trak.header.track_id;
143 trex.default_sample_description_index = 1;
145 switch (streams()[i]->stream_type()) {
147 GenerateVideoTrak(static_cast<VideoStreamInfo*>(streams()[i].
get()),
151 GenerateAudioTrak(static_cast<AudioStreamInfo*>(streams()[i].
get()),
155 GenerateTextTrak(static_cast<TextStreamInfo*>(streams()[i].
get()),
159 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
160 << streams()[i]->stream_type();
163 if (streams()[i]->is_encrypted()) {
164 const auto& key_system_info =
165 streams()[i]->encryption_config().key_system_info;
166 moov->pssh.resize(key_system_info.size());
167 for (
size_t j = 0; j < key_system_info.size(); j++)
168 moov->pssh[j].raw_box = key_system_info[j].CreateBox();
172 if (options().segment_template.empty()) {
173 segmenter_.reset(
new SingleSegmentSegmenter(options(), std::move(ftyp),
177 new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
180 const Status segmenter_initialized =
181 segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
182 if (!segmenter_initialized.ok())
183 return segmenter_initialized;
185 FireOnMediaStartEvent();
189 Status MP4Muxer::Finalize() {
191 Status segmenter_finalized = segmenter_->Finalize();
193 if (!segmenter_finalized.ok())
194 return segmenter_finalized;
196 FireOnMediaEndEvent();
201 Status MP4Muxer::AddSample(
size_t stream_id,
202 std::shared_ptr<MediaSample> sample) {
204 return segmenter_->AddSample(stream_id, sample);
207 Status MP4Muxer::FinalizeSegment(
size_t stream_id,
208 std::shared_ptr<SegmentInfo> segment_info) {
210 VLOG(3) <<
"Finalize " << (segment_info->is_subsegment ?
"sub" :
"")
211 <<
"segment " << segment_info->start_timestamp <<
" duration "
212 << segment_info->duration;
213 return segmenter_->FinalizeSegment(stream_id, std::move(segment_info));
216 void MP4Muxer::InitializeTrak(
const StreamInfo* info, Track* trak) {
217 int64_t now = IsoTimeNow();
218 trak->header.creation_time = now;
219 trak->header.modification_time = now;
220 trak->header.duration = 0;
221 trak->media.header.creation_time = now;
222 trak->media.header.modification_time = now;
223 trak->media.header.timescale = info->time_scale();
224 trak->media.header.duration = 0;
225 if (!info->language().empty()) {
227 std::string main_language = info->language();
228 size_t dash = main_language.find(
'-');
229 if (dash != std::string::npos) {
230 main_language.erase(dash);
234 if (main_language.size() != 3) {
235 LOG(WARNING) <<
"'" << main_language <<
"' is not a valid ISO-639-2 "
236 <<
"language code, ignoring.";
238 trak->media.header.language.code = main_language;
243 void MP4Muxer::GenerateVideoTrak(
const VideoStreamInfo* video_info,
246 InitializeTrak(video_info, trak);
250 uint32_t pixel_width = video_info->pixel_width();
251 uint32_t pixel_height = video_info->pixel_height();
252 if (pixel_width == 0 || pixel_height == 0) {
253 LOG(WARNING) <<
"pixel width/height are not set. Assuming 1:1.";
257 const double sample_aspect_ratio =
258 static_cast<double>(pixel_width) / pixel_height;
259 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
260 trak->header.height = video_info->height() * 0x10000;
262 VideoSampleEntry video;
264 CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
265 video.width = video_info->width();
266 video.height = video_info->height();
267 video.codec_configuration.data = video_info->codec_config();
268 if (pixel_width != 1 || pixel_height != 1) {
269 video.pixel_aspect.h_spacing = pixel_width;
270 video.pixel_aspect.v_spacing = pixel_height;
273 SampleDescription& sample_description =
274 trak->media.information.sample_table.description;
275 sample_description.type = kVideo;
276 sample_description.video_entries.push_back(video);
278 if (video_info->is_encrypted()) {
280 sample_description.video_entries.push_back(video);
282 VideoSampleEntry& entry = sample_description.video_entries[0];
283 GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
284 entry.format = FOURCC_encv;
288 void MP4Muxer::GenerateAudioTrak(
const AudioStreamInfo* audio_info,
291 InitializeTrak(audio_info, trak);
293 trak->header.volume = 0x100;
295 AudioSampleEntry audio;
297 CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
298 switch(audio_info->codec()){
300 audio.esds.es_descriptor.set_object_type(kISO_14496_3);
301 audio.esds.es_descriptor.set_esid(track_id);
302 audio.esds.es_descriptor.set_decoder_specific_info(
303 audio_info->codec_config());
304 audio.esds.es_descriptor.set_max_bitrate(audio_info->max_bitrate());
305 audio.esds.es_descriptor.set_avg_bitrate(audio_info->avg_bitrate());
312 audio.ddts.extra_data = audio_info->codec_config();
313 audio.ddts.max_bitrate = audio_info->max_bitrate();
314 audio.ddts.avg_bitrate = audio_info->avg_bitrate();
315 audio.ddts.sampling_frequency = audio_info->sampling_frequency();
316 audio.ddts.pcm_sample_depth = audio_info->sample_bits();
319 audio.dac3.data = audio_info->codec_config();
322 audio.dec3.data = audio_info->codec_config();
325 audio.dops.opus_identification_header = audio_info->codec_config();
332 audio.channelcount = audio_info->num_channels();
333 audio.samplesize = audio_info->sample_bits();
334 audio.samplerate = audio_info->sampling_frequency();
335 SampleTable& sample_table = trak->media.information.sample_table;
336 SampleDescription& sample_description = sample_table.description;
337 sample_description.type = kAudio;
338 sample_description.audio_entries.push_back(audio);
340 if (audio_info->is_encrypted()) {
342 sample_description.audio_entries.push_back(audio);
344 AudioSampleEntry& entry = sample_description.audio_entries[0];
345 GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
346 entry.format = FOURCC_enca;
351 if (audio_info->codec() == kCodecOpus) {
352 sample_table.sample_group_descriptions.resize(1);
353 SampleGroupDescription& sample_group_description =
354 sample_table.sample_group_descriptions.back();
355 sample_group_description.grouping_type = FOURCC_roll;
356 sample_group_description.audio_roll_recovery_entries.resize(1);
359 const uint64_t kNanosecondsPerSecond = 1000000000ull;
360 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
361 (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
362 kNanosecondsPerSecond / 2)) /
363 kNanosecondsPerSecond;
365 sample_table.sample_to_groups.resize(1);
366 SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
367 sample_to_group.grouping_type = FOURCC_roll;
369 sample_to_group.entries.resize(1);
370 SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
372 sample_to_group_entry.sample_count = 0;
373 sample_to_group_entry.group_description_index =
374 SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
375 }
else if (audio_info->seek_preroll_ns() != 0) {
376 LOG(WARNING) <<
"Unexpected seek preroll for codec " << audio_info->codec();
381 void MP4Muxer::GenerateTextTrak(
const TextStreamInfo* text_info,
384 InitializeTrak(text_info, trak);
386 if (text_info->codec_string() ==
"wvtt") {
388 TextSampleEntry webvtt;
389 webvtt.format = FOURCC_wvtt;
390 webvtt.config.config.assign(text_info->codec_config().begin(),
391 text_info->codec_config().end());
395 webvtt.label.source_label =
"source_label";
396 SampleDescription& sample_description =
397 trak->media.information.sample_table.description;
398 sample_description.type = kText;
399 sample_description.text_entries.push_back(webvtt);
402 NOTIMPLEMENTED() << text_info->codec_string()
403 <<
" handling not implemented yet.";
406 bool MP4Muxer::GetInitRangeStartAndEnd(uint32_t* start, uint32_t* end) {
407 DCHECK(start && end);
408 size_t range_offset = 0;
409 size_t range_size = 0;
410 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
415 SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
419 bool MP4Muxer::GetIndexRangeStartAndEnd(uint32_t* start, uint32_t* end) {
420 DCHECK(start && end);
421 size_t range_offset = 0;
422 size_t range_size = 0;
423 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
428 SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
432 void MP4Muxer::FireOnMediaStartEvent() {
433 if (!muxer_listener())
436 if (streams().size() > 1) {
437 LOG(ERROR) <<
"MuxerListener cannot take more than 1 stream.";
440 DCHECK(!streams().empty()) <<
"Media started without a stream.";
442 const uint32_t timescale = segmenter_->GetReferenceTimeScale();
443 muxer_listener()->
OnMediaStart(options(), *streams().front(), timescale,
444 MuxerListener::kContainerMp4);
447 void MP4Muxer::FireOnMediaEndEvent() {
448 if (!muxer_listener())
451 uint32_t init_range_start = 0;
452 uint32_t init_range_end = 0;
453 const bool has_init_range =
454 GetInitRangeStartAndEnd(&init_range_start, &init_range_end);
456 uint32_t index_range_start = 0;
457 uint32_t index_range_end = 0;
458 const bool has_index_range =
459 GetIndexRangeStartAndEnd(&index_range_start, &index_range_end);
461 const float duration_seconds =
static_cast<float>(segmenter_->GetDuration());
463 const int64_t file_size =
465 if (file_size <= 0) {
466 LOG(ERROR) <<
"Invalid file size: " << file_size;
480 uint64_t MP4Muxer::IsoTimeNow() {
482 const uint64_t kIsomTimeOffset = 2082844800l;
483 return kIsomTimeOffset +
484 (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();