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