Shaka Packager SDK
Loading...
Searching...
No Matches
mp4_muxer.cc
1// Copyright 2014 Google LLC. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd
6
7#include <packager/media/formats/mp4/mp4_muxer.h>
8
9#include <algorithm>
10#include <chrono>
11
12#include <absl/log/check.h>
13#include <absl/strings/escaping.h>
14#include <absl/strings/numbers.h>
15
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>
33
34namespace shaka {
35namespace media {
36namespace mp4 {
37
38namespace {
39
40// Sets the range start and end value from offset and size.
41// |start| and |end| are for byte-range-spec specified in RFC2616.
42void SetStartAndEndFromOffsetAndSize(size_t offset, size_t size, Range* range) {
43 DCHECK(range);
44 range->start = static_cast<uint32_t>(offset);
45 // Note that ranges are inclusive. So we need - 1.
46 range->end = range->start + static_cast<uint32_t>(size) - 1;
47}
48
49FourCC CodecToFourCC(Codec codec, H26xStreamFormat h26x_stream_format) {
50 switch (codec) {
51 case kCodecAV1:
52 return FOURCC_av01;
53 case kCodecH264:
54 return h26x_stream_format ==
55 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
56 ? FOURCC_avc3
57 : FOURCC_avc1;
58 case kCodecH265:
59 return h26x_stream_format ==
60 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
61 ? FOURCC_hev1
62 : FOURCC_hvc1;
63 case kCodecH265DolbyVision:
64 return h26x_stream_format ==
65 H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
66 ? FOURCC_dvhe
67 : FOURCC_dvh1;
68 case kCodecVP8:
69 return FOURCC_vp08;
70 case kCodecVP9:
71 return FOURCC_vp09;
72 case kCodecAAC:
73 case kCodecMP3:
74 return FOURCC_mp4a;
75 case kCodecAC3:
76 return FOURCC_ac_3;
77 case kCodecALAC:
78 return FOURCC_alac;
79 case kCodecDTSC:
80 return FOURCC_dtsc;
81 case kCodecDTSH:
82 return FOURCC_dtsh;
83 case kCodecDTSL:
84 return FOURCC_dtsl;
85 case kCodecDTSE:
86 return FOURCC_dtse;
87 case kCodecDTSM:
88 return FOURCC_dtsm;
89 case kCodecDTSX:
90 return FOURCC_dtsx;
91 case kCodecEAC3:
92 return FOURCC_ec_3;
93 case kCodecAC4:
94 return FOURCC_ac_4;
95 case kCodecFlac:
96 return FOURCC_fLaC;
97 case kCodecOpus:
98 return FOURCC_Opus;
99 case kCodecIAMF:
100 return FOURCC_iamf;
101 case kCodecMha1:
102 return FOURCC_mha1;
103 case kCodecMhm1:
104 return FOURCC_mhm1;
105 default:
106 return FOURCC_NULL;
107 }
108}
109
110void GenerateSinf(FourCC old_type,
111 const EncryptionConfig& encryption_config,
112 ProtectionSchemeInfo* sinf) {
113 sinf->format.format = old_type;
114
115 DCHECK_NE(encryption_config.protection_scheme, FOURCC_NULL);
116 sinf->type.type = encryption_config.protection_scheme;
117
118 // The version of cenc implemented here. CENC 4.
119 const int kCencSchemeVersion = 0x00010000;
120 sinf->type.version = kCencSchemeVersion;
121
122 auto& track_encryption = sinf->info.track_encryption;
123 track_encryption.default_is_protected = 1;
124
125 track_encryption.default_crypt_byte_block =
126 encryption_config.crypt_byte_block;
127 track_encryption.default_skip_byte_block = encryption_config.skip_byte_block;
128 switch (encryption_config.protection_scheme) {
129 case FOURCC_cenc:
130 case FOURCC_cbc1:
131 DCHECK_EQ(track_encryption.default_crypt_byte_block, 0u);
132 DCHECK_EQ(track_encryption.default_skip_byte_block, 0u);
133 // CENCv3 10.1 ‘cenc’ AES-CTR scheme and 10.2 ‘cbc1’ AES-CBC scheme:
134 // The version of the Track Encryption Box (‘tenc’) SHALL be 0.
135 track_encryption.version = 0;
136 break;
137 case FOURCC_cbcs:
138 case FOURCC_cens:
139 // CENCv3 10.3 ‘cens’ AES-CTR subsample pattern encryption scheme and
140 // 10.4 ‘cbcs’ AES-CBC subsample pattern encryption scheme:
141 // The version of the Track Encryption Box (‘tenc’) SHALL be 1.
142 track_encryption.version = 1;
143 break;
144 default:
145 NOTIMPLEMENTED() << "Unexpected protection scheme "
146 << encryption_config.protection_scheme;
147 }
148
149 track_encryption.default_per_sample_iv_size =
150 encryption_config.per_sample_iv_size;
151 track_encryption.default_constant_iv = encryption_config.constant_iv;
152 track_encryption.default_kid = encryption_config.key_id;
153}
154
155// The roll distance is expressed in sample units and always takes negative
156// values.
157int16_t GetRollDistance(uint64_t seek_preroll_ns, uint32_t sampling_frequency) {
158 const double kNanosecondsPerSecond = 1000000000;
159 const double preroll_in_samples =
160 seek_preroll_ns / kNanosecondsPerSecond * sampling_frequency;
161 // Round to closest integer.
162 return -static_cast<int16_t>(preroll_in_samples + 0.5);
163}
164
165} // namespace
166
167MP4Muxer::MP4Muxer(const MuxerOptions& options) : Muxer(options) {}
168MP4Muxer::~MP4Muxer() {}
169
170Status MP4Muxer::InitializeMuxer() {
171 // Muxer will be delay-initialized after seeing the first sample.
172 to_be_initialized_ = true;
173 return Status::OK;
174}
175
176Status MP4Muxer::Finalize() {
177 // This happens on streams that are not initialized, i.e. not going through
178 // DelayInitializeMuxer, which can only happen if there are no samples from
179 // the stream.
180 if (!segmenter_) {
181 DCHECK(to_be_initialized_);
182 LOG(INFO) << "Skip stream '" << options().output_file_name
183 << "' which does not contain any sample.";
184 return Status::OK;
185 }
186
187 Status segmenter_finalized = segmenter_->Finalize();
188
189 if (!segmenter_finalized.ok())
190 return segmenter_finalized;
191
192 FireOnMediaEndEvent();
193 LOG(INFO) << "MP4 file '" << options().output_file_name << "' finalized.";
194 return Status::OK;
195}
196
197Status MP4Muxer::AddMediaSample(size_t stream_id, const MediaSample& sample) {
198 if (to_be_initialized_) {
199 RETURN_IF_ERROR(UpdateEditListOffsetFromSample(sample));
200 RETURN_IF_ERROR(DelayInitializeMuxer());
201 to_be_initialized_ = false;
202 }
203 DCHECK(segmenter_);
204 return segmenter_->AddSample(stream_id, sample);
205}
206
207Status MP4Muxer::FinalizeSegment(size_t stream_id,
208 const SegmentInfo& segment_info) {
209 DCHECK(segmenter_);
210 VLOG(3) << "Finalizing " << (segment_info.is_subsegment ? "sub" : "")
211 << "segment " << segment_info.start_timestamp << " duration "
212 << segment_info.duration << " segment number "
213 << segment_info.segment_number;
214 return segmenter_->FinalizeSegment(stream_id, segment_info);
215}
216
217Status MP4Muxer::DelayInitializeMuxer() {
218 DCHECK(!streams().empty());
219
220 std::unique_ptr<FileType> ftyp(new FileType);
221 std::unique_ptr<Movie> moov(new Movie);
222
223 ftyp->major_brand = FOURCC_mp41;
224 ftyp->compatible_brands.push_back(FOURCC_iso8);
225 ftyp->compatible_brands.push_back(FOURCC_isom);
226 ftyp->compatible_brands.push_back(FOURCC_mp41);
227 ftyp->compatible_brands.push_back(FOURCC_dash);
228
229 if (streams().size() == 1) {
230 FourCC codec_fourcc = FOURCC_NULL;
231 if (streams()[0]->stream_type() == kStreamVideo) {
232 codec_fourcc =
233 CodecToFourCC(streams()[0]->codec(),
234 static_cast<const VideoStreamInfo*>(streams()[0].get())
235 ->h26x_stream_format());
236 if (codec_fourcc != FOURCC_NULL)
237 ftyp->compatible_brands.push_back(codec_fourcc);
238
239 // https://professional.dolby.com/siteassets/content-creation/dolby-vision-for-content-creators/dolby_vision_bitstreams_within_the_iso_base_media_file_format_dec2017.pdf
240 std::string codec_string =
241 static_cast<const VideoStreamInfo*>(streams()[0].get())
242 ->codec_string();
243 std::string supplemental_codec_string =
244 static_cast<const VideoStreamInfo*>(streams()[0].get())
245 ->supplemental_codec();
246 if (codec_string.find("dvh") != std::string::npos ||
247 supplemental_codec_string.find("dvh") != std::string::npos ||
248 codec_string.find("dav1") != std::string::npos ||
249 supplemental_codec_string.find("dav1") != std::string::npos)
250 ftyp->compatible_brands.push_back(FOURCC_dby1);
251 FourCC extra_brand =
252 static_cast<const VideoStreamInfo*>(streams()[0].get())
253 ->compatible_brand();
254 if (extra_brand != FOURCC_NULL)
255 ftyp->compatible_brands.push_back(extra_brand);
256 }
257
258 // CMAF allows only one track/stream per file.
259 // CMAF requires single initialization switching for AVC3/HEV1, which is not
260 // supported yet.
261 if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
262 ftyp->compatible_brands.push_back(FOURCC_cmfc);
263
264 if (streams()[0]->stream_type() == kStreamAudio) {
265 codec_fourcc =
266 CodecToFourCC(streams()[0]->codec(), H26xStreamFormat::kUnSpecified);
267 if (codec_fourcc == FOURCC_iamf)
268 ftyp->compatible_brands.push_back(FOURCC_iamf);
269 }
270 }
271
272 moov->header.creation_time = IsoTimeNow();
273 moov->header.modification_time = IsoTimeNow();
274 moov->header.next_track_id = static_cast<uint32_t>(streams().size()) + 1;
275
276 moov->tracks.resize(streams().size());
277 moov->extends.tracks.resize(streams().size());
278
279 // Initialize tracks.
280 for (uint32_t i = 0; i < streams().size(); ++i) {
281 const StreamInfo* stream = streams()[i].get();
282 Track& trak = moov->tracks[i];
283 trak.header.track_id = i + 1;
284
285 TrackExtends& trex = moov->extends.tracks[i];
286 trex.track_id = trak.header.track_id;
287 trex.default_sample_description_index = 1;
288
289 bool generate_trak_result = false;
290 switch (stream->stream_type()) {
291 case kStreamVideo:
292 generate_trak_result = GenerateVideoTrak(
293 static_cast<const VideoStreamInfo*>(stream), &trak);
294 break;
295 case kStreamAudio:
296 generate_trak_result = GenerateAudioTrak(
297 static_cast<const AudioStreamInfo*>(stream), &trak);
298 break;
299 case kStreamText:
300 generate_trak_result =
301 GenerateTextTrak(static_cast<const TextStreamInfo*>(stream), &trak);
302 break;
303 default:
304 NOTIMPLEMENTED() << "Not implemented for stream type: "
305 << stream->stream_type();
306 }
307 if (!generate_trak_result)
308 return Status(error::MUXER_FAILURE, "Failed to generate trak.");
309
310 // Generate EditList if needed. See UpdateEditListOffsetFromSample() for
311 // more information.
312 if (edit_list_offset_.value() > 0) {
313 EditListEntry entry;
314 entry.media_time = edit_list_offset_.value();
315 entry.media_rate_integer = 1;
316 trak.edit.list.edits.push_back(entry);
317 }
318
319 if (stream->is_encrypted() && options().mp4_params.include_pssh_in_stream) {
320 // AES-128 has no DRM system; skip pssh.
321 if (stream->encryption_config().protection_scheme !=
322 kAes128ProtectionScheme) {
323 moov->pssh.clear();
324 const auto& key_system_info =
325 stream->encryption_config().key_system_info;
326 for (const ProtectionSystemSpecificInfo& system : key_system_info) {
327 if (system.psshs.empty())
328 continue;
329 ProtectionSystemSpecificHeader pssh;
330 pssh.raw_box = system.psshs;
331 moov->pssh.push_back(pssh);
332 }
333 }
334 }
335 }
336
337 if (options().segment_template.empty()) {
338 segmenter_.reset(new SingleSegmentSegmenter(options(), std::move(ftyp),
339 std::move(moov)));
340 } else if (options().mp4_params.low_latency_dash_mode) {
341 segmenter_.reset(new LowLatencySegmentSegmenter(options(), std::move(ftyp),
342 std::move(moov)));
343 } else {
344 segmenter_.reset(
345 new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
346 }
347
348 const Status segmenter_initialized =
349 segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
350 if (!segmenter_initialized.ok())
351 return segmenter_initialized;
352
353 // For AES-128, pass the encryption config to the segmenter for
354 // whole-segment encryption.
355 for (const auto& stream : streams()) {
356 if (stream->is_encrypted() &&
357 stream->encryption_config().protection_scheme ==
358 kAes128ProtectionScheme) {
359 segmenter_->SetAes128EncryptionConfig(stream->encryption_config());
360 break;
361 }
362 }
363
364 FireOnMediaStartEvent();
365 return Status::OK;
366}
367
368Status MP4Muxer::UpdateEditListOffsetFromSample(const MediaSample& sample) {
369 if (edit_list_offset_)
370 return Status::OK;
371
372 const int64_t pts = sample.pts();
373 const int64_t dts = sample.dts();
374 // An EditList entry is inserted if one of the below conditions occur [4]:
375 // (1) pts > dts for the first sample. Due to Chrome's dts bug [1], dts is
376 // used in buffered range API, while pts is used elsewhere (players,
377 // manifests, and Chrome's own appendWindow check etc.), this
378 // inconsistency creates various problems, including possible stalls
379 // during playback. Since Chrome adjusts pts only when seeing EditList
380 // [2], we can insert an EditList with the time equal to difference of pts
381 // and dts to make aligned buffered ranges using pts and dts. This
382 // effectively workarounds the dts bug. It is also recommended by ISO-BMFF
383 // specification [3].
384 // (2) pts == dts and with pts < 0. This happens for some audio codecs where a
385 // negative presentation timestamp signals that the sample is not supposed
386 // to be shown, i.e. for audio priming. EditList is needed to encode
387 // negative timestamps.
388 // [1] https://crbug.com/718641, fixed but behind MseBufferByPts, still not
389 // enabled as of M67.
390 // [2] This is actually a bug, see https://crbug.com/354518. It looks like
391 // Chrome is planning to enable the fix for [1] before addressing this
392 // bug, so we are safe.
393 // [3] ISO 14496-12:2015 8.6.6.1
394 // It is recommended that such an edit be used to establish a presentation
395 // time of 0 for the first presented sample, when composition offsets are
396 // used.
397 // [4] ISO 23009-19:2018 7.5.13
398 // In two cases, an EditBox containing a single EditListBox with the
399 // following constraints may be present in the CMAF header of a CMAF track
400 // to adjust the presentation time of all media samples in the CMAF track.
401 // a) The first case is a video CMAF track file using v0 TrackRunBoxes
402 // with positive composition offsets to reorder video media samples.
403 // b) The second case is an audio CMAF track where each media sample's
404 // presentation time does not equal its composition time.
405 const int64_t pts_dts_offset = pts - dts;
406 if (pts_dts_offset > 0) {
407 if (pts < 0) {
408 LOG(ERROR) << "Negative presentation timestamp (" << pts
409 << ") is not supported when there is an offset between "
410 "presentation timestamp and decoding timestamp ("
411 << dts << ").";
412 return Status(error::MUXER_FAILURE,
413 "Unsupported negative pts when there is an offset between "
414 "pts and dts.");
415 }
416 edit_list_offset_ = pts_dts_offset;
417 return Status::OK;
418 }
419 if (pts_dts_offset < 0) {
420 LOG(ERROR) << "presentation timestamp (" << pts
421 << ") is not supposed to be greater than decoding timestamp ("
422 << dts << ").";
423 return Status(error::MUXER_FAILURE, "Not expecting pts < dts.");
424 }
425 edit_list_offset_ = std::max(-sample.pts(), static_cast<int64_t>(0));
426 return Status::OK;
427}
428
429void MP4Muxer::InitializeTrak(const StreamInfo* info, Track* trak) {
430 int64_t now = IsoTimeNow();
431 trak->header.creation_time = now;
432 trak->header.modification_time = now;
433 trak->header.duration = 0;
434 trak->media.header.creation_time = now;
435 trak->media.header.modification_time = now;
436 trak->media.header.timescale = info->time_scale();
437 trak->media.header.duration = 0;
438 if (!info->language().empty()) {
439 // Strip off the subtag, if any.
440 std::string main_language = info->language();
441 size_t dash = main_language.find('-');
442 if (dash != std::string::npos) {
443 main_language.erase(dash);
444 }
445
446 // ISO-639-2/T main language code should be 3 characters.
447 if (main_language.size() != 3) {
448 LOG(WARNING) << "'" << main_language << "' is not a valid ISO-639-2 "
449 << "language code, ignoring.";
450 } else {
451 trak->media.header.language.code = main_language;
452 }
453 }
454}
455
456bool MP4Muxer::GenerateVideoTrak(const VideoStreamInfo* video_info,
457 Track* trak) {
458 InitializeTrak(video_info, trak);
459
460 // width and height specify the track's visual presentation size as
461 // fixed-point 16.16 values.
462 uint32_t pixel_width = video_info->pixel_width();
463 uint32_t pixel_height = video_info->pixel_height();
464 if (pixel_width == 0 || pixel_height == 0) {
465 LOG(WARNING) << "pixel width/height are not set. Assuming 1:1.";
466 pixel_width = 1;
467 pixel_height = 1;
468 }
469 const double sample_aspect_ratio =
470 static_cast<double>(pixel_width) / pixel_height;
471 trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
472 trak->header.height = video_info->height() * 0x10000;
473
474 VideoSampleEntry video;
475 video.format =
476 CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
477 video.width = video_info->width();
478 video.height = video_info->height();
479 video.colr.raw_box = video_info->colr_data();
480 video.codec_configuration.data = video_info->codec_config();
481 if (!video.ParseExtraCodecConfigsVector(video_info->extra_config())) {
482 LOG(ERROR) << "Malformed extra codec configs: "
483 << absl::BytesToHexString(
484 absl::string_view(reinterpret_cast<const char*>(
485 video_info->extra_config().data()),
486 video_info->extra_config().size()));
487 return false;
488 }
489 if (pixel_width != 1 || pixel_height != 1) {
490 video.pixel_aspect.h_spacing = pixel_width;
491 video.pixel_aspect.v_spacing = pixel_height;
492 }
493
494 SampleDescription& sample_description =
495 trak->media.information.sample_table.description;
496 sample_description.type = kVideo;
497 sample_description.video_entries.push_back(video);
498
499 if (video_info->is_encrypted()) {
500 // AES-128 encrypts at the segment level; no encv/sinf box needed.
501 if (video_info->encryption_config().protection_scheme !=
502 kAes128ProtectionScheme) {
503 if (video_info->has_clear_lead()) {
504 // Add a second entry for clear content.
505 sample_description.video_entries.push_back(video);
506 }
507 // Convert the first entry to an encrypted entry.
508 VideoSampleEntry& entry = sample_description.video_entries[0];
509 GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
510 entry.format = FOURCC_encv;
511 }
512 }
513 return true;
514}
515
516bool MP4Muxer::GenerateAudioTrak(const AudioStreamInfo* audio_info,
517 Track* trak) {
518 InitializeTrak(audio_info, trak);
519
520 trak->header.volume = 0x100;
521
522 AudioSampleEntry audio;
523 audio.format =
524 CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
525 switch (audio_info->codec()) {
526 case kCodecAAC: {
527 DecoderConfigDescriptor* decoder_config =
528 audio.esds.es_descriptor.mutable_decoder_config_descriptor();
529 decoder_config->set_object_type(ObjectType::kISO_14496_3); // MPEG4 AAC.
530 decoder_config->set_max_bitrate(audio_info->max_bitrate());
531 decoder_config->set_avg_bitrate(audio_info->avg_bitrate());
532 decoder_config->mutable_decoder_specific_info_descriptor()->set_data(
533 audio_info->codec_config());
534 break;
535 }
536 case kCodecDTSC:
537 case kCodecDTSH:
538 case kCodecDTSL:
539 case kCodecDTSE:
540 case kCodecDTSM:
541 audio.ddts.extra_data = audio_info->codec_config();
542 audio.ddts.max_bitrate = audio_info->max_bitrate();
543 audio.ddts.avg_bitrate = audio_info->avg_bitrate();
544 audio.ddts.sampling_frequency = audio_info->sampling_frequency();
545 audio.ddts.pcm_sample_depth = audio_info->sample_bits();
546 break;
547 case kCodecDTSX:
548 audio.udts.data = audio_info->codec_config();
549 break;
550 case kCodecAC3:
551 audio.dac3.data = audio_info->codec_config();
552 break;
553 case kCodecEAC3:
554 audio.dec3.data = audio_info->codec_config();
555 break;
556 case kCodecAC4:
557 audio.dac4.data = audio_info->codec_config();
558 break;
559 case kCodecALAC:
560 audio.alac.data = audio_info->codec_config();
561 break;
562 case kCodecFlac:
563 audio.dfla.data = audio_info->codec_config();
564 break;
565 case kCodecMP3: {
566 DecoderConfigDescriptor* decoder_config =
567 audio.esds.es_descriptor.mutable_decoder_config_descriptor();
568 uint32_t samplerate = audio_info->sampling_frequency();
569 if (samplerate < 32000)
570 decoder_config->set_object_type(ObjectType::kISO_13818_3_MPEG1);
571 else
572 decoder_config->set_object_type(ObjectType::kISO_11172_3_MPEG1);
573 decoder_config->set_max_bitrate(audio_info->max_bitrate());
574 decoder_config->set_avg_bitrate(audio_info->avg_bitrate());
575
576 // For values of DecoderConfigDescriptor.objectTypeIndication
577 // that refer to streams complying with ISO/IEC 11172-3 or
578 // ISO/IEC 13818-3 the decoder specific information is empty
579 // since all necessary data is contained in the bitstream frames
580 // itself.
581 break;
582 }
583 case kCodecOpus:
584 audio.dops.opus_identification_header = audio_info->codec_config();
585 break;
586 case kCodecIAMF:
587 audio.iacb.data = audio_info->codec_config();
588 break;
589 case kCodecMha1:
590 case kCodecMhm1:
591 audio.mhac.data = audio_info->codec_config();
592 break;
593 default:
594 NOTIMPLEMENTED() << " Unsupported audio codec " << audio_info->codec();
595 return false;
596 }
597
598 if (audio_info->codec() == kCodecAC3 || audio_info->codec() == kCodecEAC3) {
599 // AC3 and EC3 does not fill in actual channel count and sample size in
600 // sample description entry. Instead, two constants are used.
601 audio.channelcount = 2;
602 audio.samplesize = 16;
603 } else if (audio_info->codec() == kCodecAC4) {
604 // ETSI TS 103 190-2, E.4.5 channelcount should be set to the total number
605 // of audio outputchannels of the default audio presentation of that track
606 audio.channelcount = audio_info->num_channels();
607 // ETSI TS 103 190-2, E.4.6 samplesize shall be set to 16.
608 audio.samplesize = 16;
609 } else if (audio_info->codec() == kCodecIAMF) {
610 // IAMF sets channelcount to 0
611 // https://aomediacodec.github.io/iamf/#iasampleentry-section
612 audio.channelcount = 0;
613 } else {
614 audio.channelcount = audio_info->num_channels();
615 audio.samplesize = audio_info->sample_bits();
616 }
617
618 // IAMF sets samplerate to 0
619 // https://aomediacodec.github.io/iamf/#iasampleentry-section
620 audio.samplerate =
621 audio_info->codec() == kCodecIAMF ? 0 : audio_info->sampling_frequency();
622
623 SampleTable& sample_table = trak->media.information.sample_table;
624 SampleDescription& sample_description = sample_table.description;
625 sample_description.type = kAudio;
626 sample_description.audio_entries.push_back(audio);
627
628 if (audio_info->is_encrypted()) {
629 // AES-128 encrypts at the segment level; no enca/sinf box needed.
630 if (audio_info->encryption_config().protection_scheme !=
631 kAes128ProtectionScheme) {
632 if (audio_info->has_clear_lead()) {
633 // Add a second entry for clear content.
634 sample_description.audio_entries.push_back(audio);
635 }
636 // Convert the first entry to an encrypted entry.
637 AudioSampleEntry& entry = sample_description.audio_entries[0];
638 GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
639 entry.format = FOURCC_enca;
640 }
641 }
642
643 if (audio_info->seek_preroll_ns() > 0) {
644 sample_table.sample_group_descriptions.resize(1);
645 SampleGroupDescription& sample_group_description =
646 sample_table.sample_group_descriptions.back();
647 sample_group_description.grouping_type = FOURCC_roll;
648 sample_group_description.audio_roll_recovery_entries.resize(1);
649 sample_group_description.audio_roll_recovery_entries[0].roll_distance =
650 GetRollDistance(audio_info->seek_preroll_ns(), audio.samplerate);
651 // sample to group box is not allowed in the init segment per CMAF
652 // specification. It is put in the fragment instead.
653 }
654 return true;
655}
656
657bool MP4Muxer::GenerateTextTrak(const TextStreamInfo* text_info, Track* trak) {
658 InitializeTrak(text_info, trak);
659
660 if (text_info->codec_string() == "wvtt") {
661 // Handle WebVTT.
662 TextSampleEntry webvtt;
663 webvtt.format = FOURCC_wvtt;
664
665 // 14496-30:2014 7.5 Web Video Text Tracks Sample entry format.
666 // In the sample entry, a WebVTT configuration box must occur, carrying
667 // exactly the lines of the WebVTT file header, i.e. all text lines up to
668 // but excluding the 'two or more line terminators' that end the header.
669 webvtt.config.config = "WEBVTT";
670 // The spec does not define a way to carry STYLE and REGION information in
671 // the mp4 container.
672 if (!text_info->regions().empty() || !text_info->css_styles().empty()) {
673 LOG(INFO) << "Skipping possible style / region configuration as the spec "
674 "does not define a way to carry them inside ISO-BMFF files.";
675 }
676
677 // TODO(rkuroiwa): This should be the source file URI(s). Putting bogus
678 // string for now so that the box will be there for samples with overlapping
679 // cues.
680 webvtt.label.source_label = "source_label";
681 SampleDescription& sample_description =
682 trak->media.information.sample_table.description;
683 sample_description.type = kText;
684 sample_description.text_entries.push_back(webvtt);
685 return true;
686 } else if (text_info->codec_string() == "ttml") {
687 // Handle TTML.
688 TextSampleEntry ttml;
689 ttml.format = FOURCC_stpp;
690 ttml.namespace_ = ttml::TtmlGenerator::kTtNamespace;
691
692 SampleDescription& sample_description =
693 trak->media.information.sample_table.description;
694 sample_description.type = kSubtitle;
695 sample_description.text_entries.push_back(ttml);
696 return true;
697 }
698 NOTIMPLEMENTED() << text_info->codec_string()
699 << " handling not implemented yet.";
700 return false;
701}
702
703std::optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
704 size_t range_offset = 0;
705 size_t range_size = 0;
706 const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
707
708 if (!has_range)
709 return std::nullopt;
710
711 Range range;
712 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
713 return range;
714}
715
716std::optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
717 size_t range_offset = 0;
718 size_t range_size = 0;
719 const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
720
721 if (!has_range)
722 return std::nullopt;
723
724 Range range;
725 SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
726 return range;
727}
728
729void MP4Muxer::FireOnMediaStartEvent() {
730 if (!muxer_listener())
731 return;
732
733 if (streams().size() > 1) {
734 LOG(ERROR) << "MuxerListener cannot take more than 1 stream.";
735 return;
736 }
737 DCHECK(!streams().empty()) << "Media started without a stream.";
738
739 const int32_t timescale = segmenter_->GetReferenceTimeScale();
740 muxer_listener()->OnMediaStart(options(), *streams().front(), timescale,
741 MuxerListener::kContainerMp4);
742}
743
744void MP4Muxer::FireOnMediaEndEvent() {
745 if (!muxer_listener())
746 return;
747
748 MuxerListener::MediaRanges media_range;
749 media_range.init_range = GetInitRangeStartAndEnd();
750 media_range.index_range = GetIndexRangeStartAndEnd();
751 media_range.subsegment_ranges = segmenter_->GetSegmentRanges();
752
753 const float duration_seconds = static_cast<float>(segmenter_->GetDuration());
754 muxer_listener()->OnMediaEnd(media_range, duration_seconds);
755}
756
757uint64_t MP4Muxer::IsoTimeNow() {
758 // Time in seconds from Jan. 1, 1904 to epoch time, i.e. Jan. 1, 1970.
759 const uint64_t kIsomTimeOffset = 2082844800l;
760
761 // Get the current system time since January 1, 1970, in seconds.
762 std::int64_t secondsSince1970 = Now();
763
764 // Add the offset of seconds between January 1, 1970, and January 1, 1904.
765 return secondsSince1970 + kIsomTimeOffset;
766}
767
768} // namespace mp4
769} // namespace media
770} // namespace shaka
virtual void OnMediaEnd(const MediaRanges &media_ranges, float duration_seconds)=0
virtual void OnMediaStart(const MuxerOptions &muxer_options, const StreamInfo &stream_info, int32_t time_scale, ContainerType container_type)=0
MP4Muxer(const MuxerOptions &options)
Create a MP4Muxer object from MuxerOptions.
Definition mp4_muxer.cc:167
All the methods that are virtual are virtual for mocking.
This structure contains the list of configuration options for Muxer.