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