DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs 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/key_source.h"
14 #include "packager/media/base/media_sample.h"
15 #include "packager/media/base/media_stream.h"
16 #include "packager/media/base/video_stream_info.h"
17 #include "packager/media/event/muxer_listener.h"
18 #include "packager/media/file/file.h"
19 #include "packager/media/formats/mp4/box_definitions.h"
20 #include "packager/media/formats/mp4/es_descriptor.h"
21 #include "packager/media/formats/mp4/fourccs.h"
22 #include "packager/media/formats/mp4/multi_segment_segmenter.h"
23 #include "packager/media/formats/mp4/single_segment_segmenter.h"
24 
25 namespace edash_packager {
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_AC3;
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_EAC3;
80  default:
81  return FOURCC_NULL;
82  }
83 }
84 
85 } // namespace
86 
87 MP4Muxer::MP4Muxer(const MuxerOptions& options) : Muxer(options) {}
88 MP4Muxer::~MP4Muxer() {}
89 
90 Status MP4Muxer::Initialize() {
91  DCHECK(!streams().empty());
92 
93  scoped_ptr<FileType> ftyp(new FileType);
94  scoped_ptr<Movie> moov(new Movie);
95 
96  ftyp->major_brand = FOURCC_DASH;
97  ftyp->compatible_brands.push_back(FOURCC_ISO6);
98  ftyp->compatible_brands.push_back(FOURCC_MP41);
99  if (streams().size() == 1 &&
100  streams()[0]->info()->stream_type() == kStreamVideo) {
101  const FourCC codec_fourcc = VideoCodecToFourCC(
102  static_cast<VideoStreamInfo*>(streams()[0]->info().get())->codec());
103  if (codec_fourcc != FOURCC_NULL)
104  ftyp->compatible_brands.push_back(codec_fourcc);
105  }
106 
107  moov->header.creation_time = IsoTimeNow();
108  moov->header.modification_time = IsoTimeNow();
109  moov->header.next_track_id = streams().size() + 1;
110 
111  moov->tracks.resize(streams().size());
112  moov->extends.tracks.resize(streams().size());
113 
114  // Initialize tracks.
115  for (uint32_t i = 0; i < streams().size(); ++i) {
116  Track& trak = moov->tracks[i];
117  trak.header.track_id = i + 1;
118 
119  TrackExtends& trex = moov->extends.tracks[i];
120  trex.track_id = trak.header.track_id;
121  trex.default_sample_description_index = 1;
122 
123  switch (streams()[i]->info()->stream_type()) {
124  case kStreamVideo:
125  GenerateVideoTrak(
126  static_cast<VideoStreamInfo*>(streams()[i]->info().get()),
127  &trak,
128  i + 1);
129  break;
130  case kStreamAudio:
131  GenerateAudioTrak(
132  static_cast<AudioStreamInfo*>(streams()[i]->info().get()),
133  &trak,
134  i + 1);
135  break;
136  default:
137  NOTIMPLEMENTED() << "Not implemented for stream type: "
138  << streams()[i]->info()->stream_type();
139  }
140  }
141 
142  if (options().single_segment) {
143  segmenter_.reset(
144  new SingleSegmentSegmenter(options(), ftyp.Pass(), moov.Pass()));
145  } else {
146  segmenter_.reset(
147  new MultiSegmentSegmenter(options(), ftyp.Pass(), moov.Pass()));
148  }
149 
150  Status segmenter_initialized =
151  segmenter_->Initialize(streams(),
152  muxer_listener(),
153  progress_listener(),
154  encryption_key_source(),
155  max_sd_pixels(),
156  clear_lead_in_seconds(),
157  crypto_period_duration_in_seconds(),
158  encryption_mode());
159 
160  if (!segmenter_initialized.ok())
161  return segmenter_initialized;
162 
163  FireOnMediaStartEvent();
164  return Status::OK;
165 }
166 
167 Status MP4Muxer::Finalize() {
168  DCHECK(segmenter_);
169  Status segmenter_finalized = segmenter_->Finalize();
170 
171  if (!segmenter_finalized.ok())
172  return segmenter_finalized;
173 
174  FireOnMediaEndEvent();
175  LOG(INFO) << "MP4 file '" << options().output_file_name << "' finalized.";
176  return Status::OK;
177 }
178 
179 Status MP4Muxer::DoAddSample(const MediaStream* stream,
180  scoped_refptr<MediaSample> sample) {
181  DCHECK(segmenter_);
182  return segmenter_->AddSample(stream, sample);
183 }
184 
185 void MP4Muxer::InitializeTrak(const StreamInfo* info, Track* trak) {
186  int64_t now = IsoTimeNow();
187  trak->header.creation_time = now;
188  trak->header.modification_time = now;
189  trak->header.duration = 0;
190  trak->media.header.creation_time = now;
191  trak->media.header.modification_time = now;
192  trak->media.header.timescale = info->time_scale();
193  trak->media.header.duration = 0;
194  if (!info->language().empty()) {
195  // Strip off the subtag, if any.
196  std::string main_language = info->language();
197  size_t dash = main_language.find('-');
198  if (dash != std::string::npos) {
199  main_language.erase(dash);
200  }
201 
202  // ISO-639-2/T main language code should be 3 characters.
203  if (main_language.size() != 3) {
204  LOG(WARNING) << "'" << main_language << "' is not a valid ISO-639-2 "
205  << "language code, ignoring.";
206  } else {
207  trak->media.header.language.code = main_language;
208  }
209  }
210 }
211 
212 void MP4Muxer::GenerateVideoTrak(const VideoStreamInfo* video_info,
213  Track* trak,
214  uint32_t track_id) {
215  InitializeTrak(video_info, trak);
216 
217  // width and height specify the track's visual presentation size as
218  // fixed-point 16.16 values.
219  uint32_t pixel_width = video_info->pixel_width();
220  uint32_t pixel_height = video_info->pixel_height();
221  if (pixel_width == 0 || pixel_height == 0) {
222  LOG(WARNING) << "pixel width/height are not set. Assuming 1:1.";
223  pixel_width = 1;
224  pixel_height = 1;
225  }
226  const double sample_aspect_ratio =
227  static_cast<double>(pixel_width) / pixel_height;
228  trak->header.width = video_info->width() * sample_aspect_ratio * 0x10000;
229  trak->header.height = video_info->height() * 0x10000;
230 
231  VideoSampleEntry video;
232  video.format = VideoCodecToFourCC(video_info->codec());
233  video.width = video_info->width();
234  video.height = video_info->height();
235  video.codec_config_record.data = video_info->extra_data();
236  if (pixel_width != 1 || pixel_height != 1) {
237  video.pixel_aspect.h_spacing = pixel_width;
238  video.pixel_aspect.v_spacing = pixel_height;
239  }
240 
241  SampleDescription& sample_description =
242  trak->media.information.sample_table.description;
243  sample_description.type = kVideo;
244  sample_description.video_entries.push_back(video);
245 }
246 
247 void MP4Muxer::GenerateAudioTrak(const AudioStreamInfo* audio_info,
248  Track* trak,
249  uint32_t track_id) {
250  InitializeTrak(audio_info, trak);
251 
252  trak->header.volume = 0x100;
253 
254  AudioSampleEntry audio;
255  audio.format = AudioCodecToFourCC(audio_info->codec());
256  switch(audio_info->codec()){
257  case kCodecAAC:
258  audio.esds.es_descriptor.set_object_type(kISO_14496_3); // MPEG4 AAC.
259  audio.esds.es_descriptor.set_esid(track_id);
260  audio.esds.es_descriptor.set_decoder_specific_info(
261  audio_info->extra_data());
262  audio.esds.es_descriptor.set_max_bitrate(audio_info->max_bitrate());
263  audio.esds.es_descriptor.set_avg_bitrate(audio_info->avg_bitrate());
264  break;
265  case kCodecDTSC:
266  case kCodecDTSH:
267  case kCodecDTSL:
268  case kCodecDTSE:
269  case kCodecDTSM:
270  audio.ddts.extra_data = audio_info->extra_data();
271  audio.ddts.max_bitrate = audio_info->max_bitrate();
272  audio.ddts.avg_bitrate = audio_info->avg_bitrate();
273  audio.ddts.sampling_frequency = audio_info->sampling_frequency();
274  audio.ddts.pcm_sample_depth = audio_info->sample_bits();
275  break;
276  case kCodecAC3:
277  audio.dac3.data = audio_info->extra_data();
278  break;
279  case kCodecEAC3:
280  audio.dec3.data = 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  SampleDescription& sample_description =
291  trak->media.information.sample_table.description;
292  sample_description.type = kAudio;
293  sample_description.audio_entries.push_back(audio);
294 }
295 
296 bool MP4Muxer::GetInitRangeStartAndEnd(uint32_t* start, uint32_t* end) {
297  DCHECK(start && end);
298  size_t range_offset = 0;
299  size_t range_size = 0;
300  const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
301 
302  if (!has_range)
303  return false;
304 
305  SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
306  return true;
307 }
308 
309 bool MP4Muxer::GetIndexRangeStartAndEnd(uint32_t* start, uint32_t* end) {
310  DCHECK(start && end);
311  size_t range_offset = 0;
312  size_t range_size = 0;
313  const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
314 
315  if (!has_range)
316  return false;
317 
318  SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
319  return true;
320 }
321 
322 void MP4Muxer::FireOnMediaStartEvent() {
323  if (!muxer_listener())
324  return;
325 
326  if (streams().size() > 1) {
327  LOG(ERROR) << "MuxerListener cannot take more than 1 stream.";
328  return;
329  }
330  DCHECK(!streams().empty()) << "Media started without a stream.";
331 
332  const uint32_t timescale = segmenter_->GetReferenceTimeScale();
333  muxer_listener()->OnMediaStart(options(),
334  *streams().front()->info(),
335  timescale,
336  MuxerListener::kContainerMp4);
337 }
338 
339 void MP4Muxer::FireOnMediaEndEvent() {
340  if (!muxer_listener())
341  return;
342 
343  uint32_t init_range_start = 0;
344  uint32_t init_range_end = 0;
345  const bool has_init_range =
346  GetInitRangeStartAndEnd(&init_range_start, &init_range_end);
347 
348  uint32_t index_range_start = 0;
349  uint32_t index_range_end = 0;
350  const bool has_index_range =
351  GetIndexRangeStartAndEnd(&index_range_start, &index_range_end);
352 
353  const float duration_seconds = static_cast<float>(segmenter_->GetDuration());
354 
355  const int64_t file_size =
356  File::GetFileSize(options().output_file_name.c_str());
357  if (file_size <= 0) {
358  LOG(ERROR) << "Invalid file size: " << file_size;
359  return;
360  }
361 
362  muxer_listener()->OnMediaEnd(has_init_range,
363  init_range_start,
364  init_range_end,
365  has_index_range,
366  index_range_start,
367  index_range_end,
368  duration_seconds,
369  file_size);
370 }
371 
372 uint64_t MP4Muxer::IsoTimeNow() {
373  // Time in seconds from Jan. 1, 1904 to epoch time, i.e. Jan. 1, 1970.
374  const uint64_t kIsomTimeOffset = 2082844800l;
375  return kIsomTimeOffset +
376  (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();
377 }
378 
379 } // namespace mp4
380 } // namespace media
381 } // namespace edash_packager
MP4Muxer(const MuxerOptions &options)
Create a MP4Muxer object from MuxerOptions.
Definition: mp4_muxer.cc:87
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