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