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