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