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  audio.format = FOURCC_MP4A;
229  audio.channelcount = audio_info->num_channels();
230  audio.samplesize = audio_info->sample_bits();
231  audio.samplerate = audio_info->sampling_frequency();
232 
233  if (kCodecAAC) {
234  audio.esds.es_descriptor.set_object_type(kISO_14496_3); // MPEG4 AAC.
235  } else {
236  // Do we need to support other types?
237  NOTIMPLEMENTED();
238  }
239  audio.esds.es_descriptor.set_esid(track_id);
240  audio.esds.es_descriptor.set_decoder_specific_info(audio_info->extra_data());
241 
242  SampleDescription& sample_description =
243  trak->media.information.sample_table.description;
244  sample_description.type = kAudio;
245  sample_description.audio_entries.push_back(audio);
246 }
247 
248 bool MP4Muxer::GetInitRangeStartAndEnd(uint32_t* start, uint32_t* end) {
249  DCHECK(start && end);
250  size_t range_offset = 0;
251  size_t range_size = 0;
252  const bool has_range = segmenter_->GetInitRange(&range_offset, &range_size);
253 
254  if (!has_range)
255  return false;
256 
257  SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
258  return true;
259 }
260 
261 bool MP4Muxer::GetIndexRangeStartAndEnd(uint32_t* start, uint32_t* end) {
262  DCHECK(start && end);
263  size_t range_offset = 0;
264  size_t range_size = 0;
265  const bool has_range = segmenter_->GetIndexRange(&range_offset, &range_size);
266 
267  if (!has_range)
268  return false;
269 
270  SetStartAndEndFromOffsetAndSize(range_offset, range_size, start, end);
271  return true;
272 }
273 
274 void MP4Muxer::FireOnMediaStartEvent() {
275  if (!muxer_listener())
276  return;
277 
278  if (streams().size() > 1) {
279  LOG(ERROR) << "MuxerListener cannot take more than 1 stream.";
280  return;
281  }
282  DCHECK(!streams().empty()) << "Media started without a stream.";
283 
284  const uint32_t timescale = segmenter_->GetReferenceTimeScale();
285  muxer_listener()->OnMediaStart(options(),
286  *streams().front()->info(),
287  timescale,
288  MuxerListener::kContainerMp4);
289 }
290 
291 void MP4Muxer::FireOnMediaEndEvent() {
292  if (!muxer_listener())
293  return;
294 
295  uint32_t init_range_start = 0;
296  uint32_t init_range_end = 0;
297  const bool has_init_range =
298  GetInitRangeStartAndEnd(&init_range_start, &init_range_end);
299 
300  uint32_t index_range_start = 0;
301  uint32_t index_range_end = 0;
302  const bool has_index_range =
303  GetIndexRangeStartAndEnd(&index_range_start, &index_range_end);
304 
305  const float duration_seconds = static_cast<float>(segmenter_->GetDuration());
306 
307  const int64_t file_size =
308  File::GetFileSize(options().output_file_name.c_str());
309  if (file_size <= 0) {
310  LOG(ERROR) << "Invalid file size: " << file_size;
311  return;
312  }
313 
314  muxer_listener()->OnMediaEnd(has_init_range,
315  init_range_start,
316  init_range_end,
317  has_index_range,
318  index_range_start,
319  index_range_end,
320  duration_seconds,
321  file_size);
322 }
323 
324 uint64_t MP4Muxer::IsoTimeNow() {
325  // Time in seconds from Jan. 1, 1904 to epoch time, i.e. Jan. 1, 1970.
326  const uint64_t kIsomTimeOffset = 2082844800l;
327  return kIsomTimeOffset +
328  (clock() ? clock()->Now() : base::Time::Now()).ToDoubleT();
329 }
330 
331 } // namespace mp4
332 } // namespace media
333 } // 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:151