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