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