DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
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  track_encryption.default_crypt_byte_block =
98  encryption_config.crypt_byte_block;
99  track_encryption.default_skip_byte_block = encryption_config.skip_byte_block;
100  track_encryption.default_per_sample_iv_size =
101  encryption_config.per_sample_iv_size;
102  track_encryption.default_constant_iv = encryption_config.constant_iv;
103  track_encryption.default_kid = encryption_config.key_id;
104 }
105 
106 } // namespace
107 
108 MP4Muxer::MP4Muxer(const MuxerOptions& options) : Muxer(options) {}
109 MP4Muxer::~MP4Muxer() {}
110 
111 Status MP4Muxer::InitializeMuxer() {
112  DCHECK(!streams().empty());
113 
114  std::unique_ptr<FileType> ftyp(new FileType);
115  std::unique_ptr<Movie> moov(new Movie);
116 
117  ftyp->major_brand = FOURCC_isom;
118  ftyp->compatible_brands.push_back(FOURCC_iso8);
119  ftyp->compatible_brands.push_back(FOURCC_mp41);
120  ftyp->compatible_brands.push_back(FOURCC_dash);
121 
122  if (streams().size() == 1) {
123  FourCC codec_fourcc = FOURCC_NULL;
124  if (streams()[0]->stream_type() == kStreamVideo) {
125  codec_fourcc =
126  CodecToFourCC(streams()[0]->codec(),
127  static_cast<VideoStreamInfo*>(streams()[0].get())
128  ->h26x_stream_format());
129  if (codec_fourcc != FOURCC_NULL)
130  ftyp->compatible_brands.push_back(codec_fourcc);
131  }
132 
133  // CMAF allows only one track/stream per file.
134  // CMAF requires single initialization switching for AVC3/HEV1, which is not
135  // supported yet.
136  if (codec_fourcc != FOURCC_avc3 && codec_fourcc != FOURCC_hev1)
137  ftyp->compatible_brands.push_back(FOURCC_cmfc);
138  }
139 
140  moov->header.creation_time = IsoTimeNow();
141  moov->header.modification_time = IsoTimeNow();
142  moov->header.next_track_id = static_cast<uint32_t>(streams().size()) + 1;
143 
144  moov->tracks.resize(streams().size());
145  moov->extends.tracks.resize(streams().size());
146 
147  // Initialize tracks.
148  for (uint32_t i = 0; i < streams().size(); ++i) {
149  Track& trak = moov->tracks[i];
150  trak.header.track_id = i + 1;
151 
152  TrackExtends& trex = moov->extends.tracks[i];
153  trex.track_id = trak.header.track_id;
154  trex.default_sample_description_index = 1;
155 
156  switch (streams()[i]->stream_type()) {
157  case kStreamVideo:
158  GenerateVideoTrak(static_cast<VideoStreamInfo*>(streams()[i].get()),
159  &trak, i + 1);
160  break;
161  case kStreamAudio:
162  GenerateAudioTrak(static_cast<AudioStreamInfo*>(streams()[i].get()),
163  &trak, i + 1);
164  break;
165  case kStreamText:
166  GenerateTextTrak(static_cast<TextStreamInfo*>(streams()[i].get()),
167  &trak, i + 1);
168  break;
169  default:
170  NOTIMPLEMENTED() << "Not implemented for stream type: "
171  << streams()[i]->stream_type();
172  }
173 
174  if (streams()[i]->is_encrypted() && options().mp4_include_pssh_in_stream) {
175  const auto& key_system_info =
176  streams()[i]->encryption_config().key_system_info;
177  moov->pssh.resize(key_system_info.size());
178  for (size_t j = 0; j < key_system_info.size(); j++)
179  moov->pssh[j].raw_box = key_system_info[j].CreateBox();
180  }
181  }
182 
183  if (options().segment_template.empty()) {
184  segmenter_.reset(new SingleSegmentSegmenter(options(), std::move(ftyp),
185  std::move(moov)));
186  } else {
187  segmenter_.reset(
188  new MultiSegmentSegmenter(options(), std::move(ftyp), std::move(moov)));
189  }
190 
191  const Status segmenter_initialized =
192  segmenter_->Initialize(streams(), muxer_listener(), progress_listener());
193  if (!segmenter_initialized.ok())
194  return segmenter_initialized;
195 
196  FireOnMediaStartEvent();
197  return Status::OK;
198 }
199 
200 Status MP4Muxer::Finalize() {
201  DCHECK(segmenter_);
202  Status segmenter_finalized = segmenter_->Finalize();
203 
204  if (!segmenter_finalized.ok())
205  return segmenter_finalized;
206 
207  FireOnMediaEndEvent();
208  LOG(INFO) << "MP4 file '" << options().output_file_name << "' finalized.";
209  return Status::OK;
210 }
211 
212 Status MP4Muxer::AddSample(size_t stream_id,
213  std::shared_ptr<MediaSample> sample) {
214  DCHECK(segmenter_);
215  return segmenter_->AddSample(stream_id, sample);
216 }
217 
218 Status MP4Muxer::FinalizeSegment(size_t stream_id,
219  std::shared_ptr<SegmentInfo> segment_info) {
220  DCHECK(segmenter_);
221  VLOG(3) << "Finalize " << (segment_info->is_subsegment ? "sub" : "")
222  << "segment " << segment_info->start_timestamp << " duration "
223  << segment_info->duration;
224  return segmenter_->FinalizeSegment(stream_id, std::move(segment_info));
225 }
226 
227 void MP4Muxer::InitializeTrak(const StreamInfo* info, Track* trak) {
228  int64_t now = IsoTimeNow();
229  trak->header.creation_time = now;
230  trak->header.modification_time = now;
231  trak->header.duration = 0;
232  trak->media.header.creation_time = now;
233  trak->media.header.modification_time = now;
234  trak->media.header.timescale = info->time_scale();
235  trak->media.header.duration = 0;
236  if (!info->language().empty()) {
237  // Strip off the subtag, if any.
238  std::string main_language = info->language();
239  size_t dash = main_language.find('-');
240  if (dash != std::string::npos) {
241  main_language.erase(dash);
242  }
243 
244  // ISO-639-2/T main language code should be 3 characters.
245  if (main_language.size() != 3) {
246  LOG(WARNING) << "'" << main_language << "' is not a valid ISO-639-2 "
247  << "language code, ignoring.";
248  } else {
249  trak->media.header.language.code = main_language;
250  }
251  }
252 }
253 
254 void MP4Muxer::GenerateVideoTrak(const VideoStreamInfo* video_info,
255  Track* trak,
256  uint32_t track_id) {
257  InitializeTrak(video_info, trak);
258 
259  // width and height specify the track's visual presentation size as
260  // fixed-point 16.16 values.
261  uint32_t pixel_width = video_info->pixel_width();
262  uint32_t pixel_height = video_info->pixel_height();
263  if (pixel_width == 0 || pixel_height == 0) {
264  LOG(WARNING) << "pixel width/height are not set. Assuming 1:1.";
265  pixel_width = 1;
266  pixel_height = 1;
267  }
268  const double sample_aspect_ratio =
269  static_cast<double>(pixel_width) / pixel_height;
270  trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
271  trak->header.height = video_info->height() * 0x10000;
272 
273  VideoSampleEntry video;
274  video.format =
275  CodecToFourCC(video_info->codec(), video_info->h26x_stream_format());
276  video.width = video_info->width();
277  video.height = video_info->height();
278  video.codec_configuration.data = video_info->codec_config();
279  if (pixel_width != 1 || pixel_height != 1) {
280  video.pixel_aspect.h_spacing = pixel_width;
281  video.pixel_aspect.v_spacing = pixel_height;
282  }
283 
284  SampleDescription& sample_description =
285  trak->media.information.sample_table.description;
286  sample_description.type = kVideo;
287  sample_description.video_entries.push_back(video);
288 
289  if (video_info->is_encrypted()) {
290  if (video_info->has_clear_lead()) {
291  // Add a second entry for clear content.
292  sample_description.video_entries.push_back(video);
293  }
294  // Convert the first entry to an encrypted entry.
295  VideoSampleEntry& entry = sample_description.video_entries[0];
296  GenerateSinf(entry.format, video_info->encryption_config(), &entry.sinf);
297  entry.format = FOURCC_encv;
298  }
299 }
300 
301 void MP4Muxer::GenerateAudioTrak(const AudioStreamInfo* audio_info,
302  Track* trak,
303  uint32_t track_id) {
304  InitializeTrak(audio_info, trak);
305 
306  trak->header.volume = 0x100;
307 
308  AudioSampleEntry audio;
309  audio.format =
310  CodecToFourCC(audio_info->codec(), H26xStreamFormat::kUnSpecified);
311  switch(audio_info->codec()){
312  case kCodecAAC:
313  audio.esds.es_descriptor.set_object_type(kISO_14496_3); // MPEG4 AAC.
314  audio.esds.es_descriptor.set_esid(track_id);
315  audio.esds.es_descriptor.set_decoder_specific_info(
316  audio_info->codec_config());
317  audio.esds.es_descriptor.set_max_bitrate(audio_info->max_bitrate());
318  audio.esds.es_descriptor.set_avg_bitrate(audio_info->avg_bitrate());
319  break;
320  case kCodecDTSC:
321  case kCodecDTSH:
322  case kCodecDTSL:
323  case kCodecDTSE:
324  case kCodecDTSM:
325  audio.ddts.extra_data = audio_info->codec_config();
326  audio.ddts.max_bitrate = audio_info->max_bitrate();
327  audio.ddts.avg_bitrate = audio_info->avg_bitrate();
328  audio.ddts.sampling_frequency = audio_info->sampling_frequency();
329  audio.ddts.pcm_sample_depth = audio_info->sample_bits();
330  break;
331  case kCodecAC3:
332  audio.dac3.data = audio_info->codec_config();
333  break;
334  case kCodecEAC3:
335  audio.dec3.data = audio_info->codec_config();
336  break;
337  case kCodecOpus:
338  audio.dops.opus_identification_header = audio_info->codec_config();
339  break;
340  default:
341  NOTIMPLEMENTED();
342  break;
343  }
344 
345  audio.channelcount = audio_info->num_channels();
346  audio.samplesize = audio_info->sample_bits();
347  audio.samplerate = audio_info->sampling_frequency();
348  SampleTable& sample_table = trak->media.information.sample_table;
349  SampleDescription& sample_description = sample_table.description;
350  sample_description.type = kAudio;
351  sample_description.audio_entries.push_back(audio);
352 
353  if (audio_info->is_encrypted()) {
354  if (audio_info->has_clear_lead()) {
355  // Add a second entry for clear content.
356  sample_description.audio_entries.push_back(audio);
357  }
358  // Convert the first entry to an encrypted entry.
359  AudioSampleEntry& entry = sample_description.audio_entries[0];
360  GenerateSinf(entry.format, audio_info->encryption_config(), &entry.sinf);
361  entry.format = FOURCC_enca;
362  }
363 
364  // Opus requires at least one sample group description box and at least one
365  // sample to group box with grouping type 'roll' within sample table box.
366  if (audio_info->codec() == kCodecOpus) {
367  sample_table.sample_group_descriptions.resize(1);
368  SampleGroupDescription& sample_group_description =
369  sample_table.sample_group_descriptions.back();
370  sample_group_description.grouping_type = FOURCC_roll;
371  sample_group_description.audio_roll_recovery_entries.resize(1);
372  // The roll distance is expressed in sample units and always takes negative
373  // values.
374  const uint64_t kNanosecondsPerSecond = 1000000000ull;
375  sample_group_description.audio_roll_recovery_entries[0].roll_distance =
376  (0 - (audio_info->seek_preroll_ns() * audio.samplerate +
377  kNanosecondsPerSecond / 2)) /
378  kNanosecondsPerSecond;
379 
380  sample_table.sample_to_groups.resize(1);
381  SampleToGroup& sample_to_group = sample_table.sample_to_groups.back();
382  sample_to_group.grouping_type = FOURCC_roll;
383 
384  sample_to_group.entries.resize(1);
385  SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
386  // All samples are in track fragments.
387  sample_to_group_entry.sample_count = 0;
388  sample_to_group_entry.group_description_index =
389  SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
390  } else if (audio_info->seek_preroll_ns() != 0) {
391  LOG(WARNING) << "Unexpected seek preroll for codec " << audio_info->codec();
392  return;
393  }
394 }
395 
396 void MP4Muxer::GenerateTextTrak(const TextStreamInfo* text_info,
397  Track* trak,
398  uint32_t track_id) {
399  InitializeTrak(text_info, trak);
400 
401  if (text_info->codec_string() == "wvtt") {
402  // Handle WebVTT.
403  TextSampleEntry webvtt;
404  webvtt.format = FOURCC_wvtt;
405  webvtt.config.config.assign(text_info->codec_config().begin(),
406  text_info->codec_config().end());
407  // TODO(rkuroiwa): This should be the source file URI(s). Putting bogus
408  // string for now so that the box will be there for samples with overlapping
409  // cues.
410  webvtt.label.source_label = "source_label";
411  SampleDescription& sample_description =
412  trak->media.information.sample_table.description;
413  sample_description.type = kText;
414  sample_description.text_entries.push_back(webvtt);
415  return;
416  }
417  NOTIMPLEMENTED() << text_info->codec_string()
418  << " handling not implemented yet.";
419 }
420 
421 base::Optional<Range> MP4Muxer::GetInitRangeStartAndEnd() {
422  size_t range_offset = 0;
423  size_t range_size = 0;
424  const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
425 
426  if (!has_range)
427  return base::nullopt;
428 
429  Range range;
430  SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
431  return range;
432 }
433 
434 base::Optional<Range> MP4Muxer::GetIndexRangeStartAndEnd() {
435  size_t range_offset = 0;
436  size_t range_size = 0;
437  const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
438 
439  if (!has_range)
440  return base::nullopt;
441 
442  Range range;
443  SetStartAndEndFromOffsetAndSize(range_offset, range_size, &range);
444  return range;
445 }
446 
447 void MP4Muxer::FireOnMediaStartEvent() {
448  if (!muxer_listener())
449  return;
450 
451  if (streams().size() > 1) {
452  LOG(ERROR) << "MuxerListener cannot take more than 1 stream.";
453  return;
454  }
455  DCHECK(!streams().empty()) << "Media started without a stream.";
456 
457  const uint32_t timescale = segmenter_->GetReferenceTimeScale();
458  muxer_listener()->OnMediaStart(options(), *streams().front(), timescale,
459  MuxerListener::kContainerMp4);
460 }
461 
462 void MP4Muxer::FireOnMediaEndEvent() {
463  if (!muxer_listener())
464  return;
465 
466  MuxerListener::MediaRanges media_range;
467  media_range.init_range = GetInitRangeStartAndEnd();
468  media_range.index_range = GetIndexRangeStartAndEnd();
469  media_range.subsegment_ranges = segmenter_->GetSegmentRanges();
470 
471  const float duration_seconds = static_cast<float>(segmenter_->GetDuration());
472 
473  const int64_t file_size =
474  File::GetFileSize(options().output_file_name.c_str());
475  if (file_size <= 0) {
476  LOG(ERROR) << "Invalid file size: " << file_size;
477  return;
478  }
479 
480  muxer_listener()->OnMediaEnd(media_range, duration_seconds, file_size);
481 }
482 
483 uint64_t MP4Muxer::IsoTimeNow() {
484  // Time in seconds from Jan. 1, 1904 to epoch time, i.e. Jan. 1, 1970.
485  const uint64_t kIsomTimeOffset = 2082844800l;
486  return kIsomTimeOffset +
487  (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();
488 }
489 
490 } // namespace mp4
491 } // namespace media
492 } // namespace shaka
MP4Muxer(const MuxerOptions &options)
Create a MP4Muxer object from MuxerOptions.
Definition: mp4_muxer.cc:108
This structure contains the list of configuration options for Muxer.
Definition: muxer_options.h:18
virtual void OnMediaStart(const MuxerOptions &muxer_options, const StreamInfo &stream_info, uint32_t time_scale, ContainerType container_type)=0
virtual void OnMediaEnd(const MediaRanges &media_ranges, float duration_seconds, uint64_t file_size)=0