Shaka Packager SDK
mp4_muxer.cc
1 // Copyright 2014 Google Inc. 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 "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"
24 
25 namespace shaka {
26 namespace media {
27 namespace mp4 {
28 
29 namespace {
30 
31 // Sets the range start and end value from offset and size.
32 // |start| and |end| are for byte-range-spec specified in RFC2616.
33 void SetStartAndEndFromOffsetAndSize(size_t offset,
34  size_t size,
35  Range* range) {
36  DCHECK(range);
37  range->start = static_cast<uint32_t>(offset);
38  // Note that ranges are inclusive. So we need - 1.
39  range->end = range->start + static_cast<uint32_t>(size) - 1;
40 }
41 
42 FourCC CodecToFourCC(Codec codec, H26xStreamFormat h26x_stream_format) {
43  switch (codec) {
44  case kCodecH264:
45  return h26x_stream_format ==
46  H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
47  ? FOURCC_avc3
48  : FOURCC_avc1;
49  case kCodecH265:
50  return h26x_stream_format ==
51  H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
52  ? FOURCC_hev1
53  : FOURCC_hvc1;
54  case kCodecVP8:
55  return FOURCC_vp08;
56  case kCodecVP9:
57  return FOURCC_vp09;
58  case kCodecVP10:
59  return FOURCC_vp10;
60  case kCodecAAC:
61  return FOURCC_mp4a;
62  case kCodecAC3:
63  return FOURCC_ac_3;
64  case kCodecDTSC:
65  return FOURCC_dtsc;
66  case kCodecDTSH:
67  return FOURCC_dtsh;
68  case kCodecDTSL:
69  return FOURCC_dtsl;
70  case kCodecDTSE:
71  return FOURCC_dtse;
72  case kCodecDTSM:
73  return FOURCC_dtsm;
74  case kCodecEAC3:
75  return FOURCC_ec_3;
76  case kCodecOpus:
77  return FOURCC_Opus;
78  default:
79  return FOURCC_NULL;
80  }
81 }
82 
83 void GenerateSinf(FourCC old_type,
84  const EncryptionConfig& encryption_config,
85  ProtectionSchemeInfo* sinf) {
86  sinf->format.format = old_type;
87 
88  DCHECK_NE(encryption_config.protection_scheme, FOURCC_NULL);
89  sinf->type.type = encryption_config.protection_scheme;
90 
91  // The version of cenc implemented here. CENC 4.
92  const int kCencSchemeVersion = 0x00010000;
93  sinf->type.version = kCencSchemeVersion;
94 
95  auto& track_encryption = sinf->info.track_encryption;
96  track_encryption.default_is_protected = 1;
97 
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  switch (encryption_config.protection_scheme) {
102  case FOURCC_cenc:
103  case FOURCC_cbc1:
104  DCHECK_EQ(track_encryption.default_crypt_byte_block, 0u);
105  DCHECK_EQ(track_encryption.default_skip_byte_block, 0u);
106  // CENCv3 10.1 ‘cenc’ AES-CTR scheme and 10.2 ‘cbc1’ AES-CBC scheme:
107  // The version of the Track Encryption Box (‘tenc’) SHALL be 0.
108  track_encryption.version = 0;
109  break;
110  case FOURCC_cbcs:
111  case FOURCC_cens:
112  if (track_encryption.default_skip_byte_block == 0) {
113  // Some clients, e.g. Safari v11.0.3 does not like having
114  // crypt_byte_block as a non-zero value when skip_byte_block is zero.
115  track_encryption.default_crypt_byte_block = 0;
116  }
117  // CENCv3 10.3 ‘cens’ AES-CTR subsample pattern encryption scheme and
118  // 10.4 ‘cbcs’ AES-CBC subsample pattern encryption scheme:
119  // The version of the Track Encryption Box (‘tenc’) SHALL be 1.
120  track_encryption.version = 1;
121  break;
122  default:
123  NOTREACHED() << "Unexpected protection scheme "
124  << encryption_config.protection_scheme;
125  }
126 
127  track_encryption.default_per_sample_iv_size =
128  encryption_config.per_sample_iv_size;
129  track_encryption.default_constant_iv = encryption_config.constant_iv;
130  track_encryption.default_kid = encryption_config.key_id;
131 }
132 
133 } // namespace
134 
135 MP4Muxer::MP4Muxer(const MuxerOptions& options) : Muxer(options) {}
136 MP4Muxer::~MP4Muxer() {}
137 
138 Status MP4Muxer::InitializeMuxer() {
139  DCHECK(!streams().empty());
140 
141  std::unique_ptr<FileType> ftyp(new FileType);
142  std::unique_ptr<Movie> moov(new Movie);
143 
144  ftyp->major_brand = FOURCC_isom;
145  ftyp->compatible_brands.push_back(FOURCC_iso8);
146  ftyp->compatible_brands.push_back(FOURCC_mp41);
147  ftyp->compatible_brands.push_back(FOURCC_dash);
148 
149  if (streams().size() == 1) {
150  FourCC codec_fourcc = FOURCC_NULL;
151  if (streams()[0]->stream_type() == kStreamVideo) {
152  codec_fourcc =
153  CodecToFourCC(streams()[0]->codec(),
154  static_cast<const VideoStreamInfo*>(streams()[0].get())
155  ->h26x_stream_format());
156  if (codec_fourcc != FOURCC_NULL)
157  ftyp->compatible_brands.push_back(codec_fourcc);
158  }
159 
160  // CMAF allows only one track/stream per file.
161  // CMAF requires single initialization switching for AVC3/HEV1, which is not
162  // supported yet.
163  if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
164  ftyp->compatible_brands.push_back(FOURCC_cmfc);
165  }
166 
167  moov->header.creation_time = IsoTimeNow();
168  moov->header.modification_time = IsoTimeNow();
169  moov->header.next_track_id = static_cast<uint32_t>(streams().size()) + 1;
170 
171  moov->tracks.resize(streams().size());
172  moov->extends.tracks.resize(streams().size());
173 
174  // Initialize tracks.
175  for (uint32_t i = 0; i < streams().size(); ++i) {
176  Track& trak = moov->tracks[i];
177  trak.header.track_id = i + 1;
178 
179  TrackExtends& trex = moov->extends.tracks[i];
180  trex.track_id = trak.header.track_id;
181  trex.default_sample_description_index = 1;
182 
183  switch (streams()[i]->stream_type()) {
184  case kStreamVideo:
185  GenerateVideoTrak(
186  static_cast<const VideoStreamInfo*>(streams()[i].get()),
187  &trak,
188  i + 1);
189  break;
190  case kStreamAudio:
191  GenerateAudioTrak(
192  static_cast<const AudioStreamInfo*>(streams()[i].get()),
193  &trak,
194  i + 1);
195  break;
196  case kStreamText:
197  GenerateTextTrak(
198  static_cast<const TextStreamInfo*>(streams()[i].get()),
199  &trak,
200  i + 1);
201  break;
202  default:
203  NOTIMPLEMENTED() << "Not implemented for stream type: "
204  << streams()[i]->stream_type();
205  }
206 
207  if (streams()[i]->is_encrypted() &&
208  options().mp4_params.include_pssh_in_stream) {
209  const auto& key_system_info =
210  streams()[i]->encryption_config().key_system_info;
211  moov->pssh.resize(key_system_info.size());
212  for (size_t j = 0; j < key_system_info.size(); j++)
213  moov->pssh[j].raw_box = key_system_info[j].CreateBox();
214  }
215  }
216 
217  if (options().segment_template.empty()) {
218  segmenter_.reset(new SingleSegmentSegmenter(options(), std::move(ftyp),
219  std::move(moov)));
220  } else {
221  segmenter_.reset(
222  new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
223  }
224 
225  const Status segmenter_initialized =
226  segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
227  if (!segmenter_initialized.ok())
228  return segmenter_initialized;
229 
230  FireOnMediaStartEvent();
231  return Status::OK;
232 }
233 
234 Status MP4Muxer::Finalize() {
235  DCHECK(segmenter_);
236  Status segmenter_finalized = segmenter_->Finalize();
237 
238  if (!segmenter_finalized.ok())
239  return segmenter_finalized;
240 
241  FireOnMediaEndEvent();
242  LOG(INFO) << "MP4 file '" << options().output_file_name << "' finalized.";
243  return Status::OK;
244 }
245 
246 Status MP4Muxer::AddSample(size_t stream_id, const MediaSample& sample) {
247  DCHECK(segmenter_);
248  return segmenter_->AddSample(stream_id, sample);
249 }
250 
251 Status MP4Muxer::FinalizeSegment(size_t stream_id,
252  const SegmentInfo& segment_info) {
253  DCHECK(segmenter_);
254  VLOG(3) << "Finalize " << (segment_info.is_subsegment ? "sub" : "")
255  << "segment " << segment_info.start_timestamp << " duration "
256  << segment_info.duration;
257  return segmenter_->FinalizeSegment(stream_id, segment_info);
258 }
259 
260 void MP4Muxer::InitializeTrak(const StreamInfo* info, Track* trak) {
261  int64_t now = IsoTimeNow();
262  trak->header.creation_time = now;
263  trak->header.modification_time = now;
264  trak->header.duration = 0;
265  trak->media.header.creation_time = now;
266  trak->media.header.modification_time = now;
267  trak->media.header.timescale = info->time_scale();
268  trak->media.header.duration = 0;
269  if (!info->language().empty()) {
270  // Strip off the subtag, if any.
271  std::string main_language = info->language();
272  size_t dash = main_language.find('-');
273  if (dash != std::string::npos) {
274  main_language.erase(dash);
275  }
276 
277  // ISO-639-2/T main language code should be 3 characters.
278  if (main_language.size() != 3) {
279  LOG(WARNING) << "'" << main_language << "' is not a valid ISO-639-2 "
280  << "language code, ignoring.";
281  } else {
282  trak->media.header.language.code = main_language;
283  }
284  }
285 }
286 
287 void MP4Muxer::GenerateVideoTrak(const VideoStreamInfo* video_info,
288  Track* trak,
289  uint32_t track_id) {
290  InitializeTrak(video_info, trak);
291 
292  // width and height specify the track's visual presentation size as
293  // fixed-point 16.16 values.
294  uint32_t pixel_width = video_info->pixel_width();
295  uint32_t pixel_height = video_info->pixel_height();
296  if (pixel_width == 0 || pixel_height == 0) {
297  LOG(WARNING) << "pixel width/height are not set. Assuming 1:1.";
298  pixel_width = 1;
299  pixel_height = 1;
300  }
301  const double sample_aspect_ratio =
302  static_cast<double>(pixel_width) / pixel_height;
303  trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
304  trak->header.height = video_info->height() * 0x10000;
305 
306  VideoSampleEntry video;
307  video.format =
308  CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
309  video.width = video_info->width();
310  video.height = video_info->height();
311  video.codec_configuration.data = video_info->codec_config();
312  if (pixel_width != 1 || pixel_height != 1) {
313  video.pixel_aspect.h_spacing = pixel_width;
314  video.pixel_aspect.v_spacing = pixel_height;
315  }
316 
317  SampleDescription& sample_description =
318  trak->media.information.sample_table.description;
319  sample_description.type = kVideo;
320  sample_description.video_entries.push_back(video);
321 
322  if (video_info->is_encrypted()) {
323  if (video_info->has_clear_lead()) {
324  // Add a second entry for clear content.
325  sample_description.video_entries.push_back(video);
326  }
327  // Convert the first entry to an encrypted entry.
328  VideoSampleEntry& entry = sample_description.video_entries[0];
329  GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
330  entry.format = FOURCC_encv;
331  }
332 }
333 
334 void MP4Muxer::GenerateAudioTrak(const AudioStreamInfo* audio_info,
335  Track* trak,
336  uint32_t track_id) {
337  InitializeTrak(audio_info, trak);
338 
339  trak->header.volume = 0x100;
340 
341  AudioSampleEntry audio;
342  audio.format =
343  CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
344  switch(audio_info->codec()){
345  case kCodecAAC:
346  audio.esds.es_descriptor.set_object_type(kISO_14496_3); // MPEG4 AAC.
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());
352  break;
353  case kCodecDTSC:
354  case kCodecDTSH:
355  case kCodecDTSL:
356  case kCodecDTSE:
357  case kCodecDTSM:
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();
363  break;
364  case kCodecAC3:
365  audio.dac3.data = audio_info->codec_config();
366  break;
367  case kCodecEAC3:
368  audio.dec3.data = audio_info->codec_config();
369  break;
370  case kCodecOpus:
371  audio.dops.opus_identification_header = audio_info->codec_config();
372  break;
373  default:
374  NOTIMPLEMENTED();
375  break;
376  }
377 
378  if (audio_info->codec() == kCodecAC3 || audio_info->codec() == kCodecEAC3) {
379  // AC3 and EC3 does not fill in actual channel count and sample size in
380  // sample description entry. Instead, two constants are used.
381  audio.channelcount = 2;
382  audio.samplesize = 16;
383  } else {
384  audio.channelcount = audio_info->num_channels();
385  audio.samplesize = audio_info->sample_bits();
386  }
387  audio.samplerate = audio_info->sampling_frequency();
388  SampleTable& sample_table = trak->media.information.sample_table;
389  SampleDescription& sample_description = sample_table.description;
390  sample_description.type = kAudio;
391  sample_description.audio_entries.push_back(audio);
392 
393  if (audio_info->is_encrypted()) {
394  if (audio_info->has_clear_lead()) {
395  // Add a second entry for clear content.
396  sample_description.audio_entries.push_back(audio);
397  }
398  // Convert the first entry to an encrypted entry.
399  AudioSampleEntry& entry = sample_description.audio_entries[0];
400  GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
401  entry.format = FOURCC_enca;
402  }
403 
404  // Opus requires at least one sample group description box and at least one
405  // sample to group box with grouping type 'roll' within sample table box.
406  if (audio_info->codec() == kCodecOpus) {
407  sample_table.sample_group_descriptions.resize(1);
408  SampleGroupDescription& sample_group_description =
409  sample_table.sample_group_descriptions.back();
410  sample_group_description.grouping_type = FOURCC_roll;
411  sample_group_description.audio_roll_recovery_entries.resize(1);
412  // The roll distance is expressed in sample units and always takes negative
413  // values.
414  const uint64_t kNanosecondsPerSecond = 1000000000ull;
415  sample_group_description.audio_roll_recovery_entries[0].roll_distance =
416  (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
417  kNanosecondsPerSecond / 2)) /
418  kNanosecondsPerSecond;
419 
420  sample_table.sample_to_groups.resize(1);
421  SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
422  sample_to_group.grouping_type = FOURCC_roll;
423 
424  sample_to_group.entries.resize(1);
425  SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
426  // All samples are in track fragments.
427  sample_to_group_entry.sample_count = 0;
428  sample_to_group_entry.group_description_index =
429  SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
430  } else if (audio_info->seek_preroll_ns() != 0) {
431  LOG(WARNING) << "Unexpected seek preroll for codec " << audio_info->codec();
432  return;
433  }
434 }
435 
436 void MP4Muxer::GenerateTextTrak(const TextStreamInfo* text_info,
437  Track* trak,
438  uint32_t track_id) {
439  InitializeTrak(text_info, trak);
440 
441  if (text_info->codec_string() == "wvtt") {
442  // Handle WebVTT.
443  TextSampleEntry webvtt;
444  webvtt.format = FOURCC_wvtt;
445  webvtt.config.config.assign(text_info->codec_config().begin(),
446  text_info->codec_config().end());
447  // TODO(rkuroiwa): This should be the source file URI(s). Putting bogus
448  // string for now so that the box will be there for samples with overlapping
449  // cues.
450  webvtt.label.source_label = "source_label";
451  SampleDescription& sample_description =
452  trak->media.information.sample_table.description;
453  sample_description.type = kText;
454  sample_description.text_entries.push_back(webvtt);
455  return;
456  }
457  NOTIMPLEMENTED() << text_info->codec_string()
458  << " handling not implemented yet.";
459 }
460 
461 base::Optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
462  size_t range_offset = 0;
463  size_t range_size = 0;
464  const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
465 
466  if (!has_range)
467  return base::nullopt;
468 
469  Range range;
470  SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
471  return range;
472 }
473 
474 base::Optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
475  size_t range_offset = 0;
476  size_t range_size = 0;
477  const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
478 
479  if (!has_range)
480  return base::nullopt;
481 
482  Range range;
483  SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
484  return range;
485 }
486 
487 void MP4Muxer::FireOnMediaStartEvent() {
488  if (!muxer_listener())
489  return;
490 
491  if (streams().size() > 1) {
492  LOG(ERROR) << "MuxerListener cannot take more than 1 stream.";
493  return;
494  }
495  DCHECK(!streams().empty()) << "Media started without a stream.";
496 
497  const uint32_t timescale = segmenter_->GetReferenceTimeScale();
498  muxer_listener()->OnMediaStart(options(), *streams().front(), timescale,
499  MuxerListener::kContainerMp4);
500 }
501 
502 void MP4Muxer::FireOnMediaEndEvent() {
503  if (!muxer_listener())
504  return;
505 
506  MuxerListener::MediaRanges media_range;
507  media_range.init_range = GetInitRangeStartAndEnd();
508  media_range.index_range = GetIndexRangeStartAndEnd();
509  media_range.subsegment_ranges = segmenter_->GetSegmentRanges();
510 
511  const float duration_seconds = static_cast<float>(segmenter_->GetDuration());
512  muxer_listener()->OnMediaEnd(media_range, duration_seconds);
513 }
514 
515 uint64_t MP4Muxer::IsoTimeNow() {
516  // Time in seconds from Jan. 1, 1904 to epoch time, i.e. Jan. 1, 1970.
517  const uint64_t kIsomTimeOffset = 2082844800l;
518  return kIsomTimeOffset +
519  (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();
520 }
521 
522 } // namespace mp4
523 } // namespace media
524 } // namespace shaka
base::Optional< Range > init_range
Range of the initialization section of a segment.
Abstract class holds stream information.
Definition: stream_info.h:58
base::Optional< Range > index_range
Range of the index section of a segment.
MP4Muxer(const MuxerOptions &options)
Create a MP4Muxer object from MuxerOptions.
Definition: mp4_muxer.cc:135
All the methods that are virtual are virtual for mocking.
This structure contains the list of configuration options for Muxer.
Definition: muxer_options.h:20
virtual void OnMediaEnd(const MediaRanges &media_ranges, float duration_seconds)=0
Class to hold a media sample.
Definition: media_sample.h:22
virtual void OnMediaStart(const MuxerOptions &muxer_options, const StreamInfo &stream_info, uint32_t time_scale, ContainerType container_type)=0
Holds video stream information.
Holds audio stream information.