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