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