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