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