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