DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
segmenter.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/segmenter.h"
8 
9 #include <algorithm>
10 
11 #include "packager/base/stl_util.h"
12 #include "packager/media/base/buffer_writer.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/muxer_options.h"
17 #include "packager/media/base/video_stream_info.h"
18 #include "packager/media/event/muxer_listener.h"
19 #include "packager/media/event/progress_listener.h"
20 #include "packager/media/formats/mp4/box_definitions.h"
21 #include "packager/media/formats/mp4/key_rotation_fragmenter.h"
22 
23 namespace edash_packager {
24 namespace media {
25 namespace mp4 {
26 
27 namespace {
28 
29 // Generate 64bit IV by default.
30 const size_t kDefaultIvSize = 8u;
31 const size_t kCencKeyIdSize = 16u;
32 
33 // The version of cenc implemented here. CENC 4.
34 const int kCencSchemeVersion = 0x00010000;
35 
36 // The default KID for key rotation is all 0s.
37 const uint8_t kKeyRotationDefaultKeyId[] = {
38  0, 0, 0, 0, 0, 0, 0, 0,
39  0, 0, 0, 0, 0, 0, 0, 0
40 };
41 COMPILE_ASSERT(arraysize(kKeyRotationDefaultKeyId) == kCencKeyIdSize,
42  cenc_key_id_must_be_size_16);
43 
44 uint64_t Rescale(uint64_t time_in_old_scale,
45  uint32_t old_scale,
46  uint32_t new_scale) {
47  return static_cast<double>(time_in_old_scale) / old_scale * new_scale;
48 }
49 
50 void GenerateSinf(const EncryptionKey& encryption_key,
51  FourCC old_type,
52  ProtectionSchemeInfo* sinf) {
53  sinf->format.format = old_type;
54  sinf->type.type = FOURCC_CENC;
55  sinf->type.version = kCencSchemeVersion;
56  sinf->info.track_encryption.is_encrypted = true;
57  sinf->info.track_encryption.default_iv_size =
58  encryption_key.iv.empty() ? kDefaultIvSize : encryption_key.iv.size();
59  sinf->info.track_encryption.default_kid = encryption_key.key_id;
60 }
61 
62 void GenerateEncryptedSampleEntry(const EncryptionKey& encryption_key,
63  double clear_lead_in_seconds,
64  SampleDescription* description) {
65  DCHECK(description);
66  if (description->type == kVideo) {
67  DCHECK_EQ(1u, description->video_entries.size());
68 
69  // Add a second entry for clear content if needed.
70  if (clear_lead_in_seconds > 0)
71  description->video_entries.push_back(description->video_entries[0]);
72 
73  // Convert the first entry to an encrypted entry.
74  VideoSampleEntry& entry = description->video_entries[0];
75  GenerateSinf(encryption_key, entry.format, &entry.sinf);
76  entry.format = FOURCC_ENCV;
77  } else {
78  DCHECK_EQ(kAudio, description->type);
79  DCHECK_EQ(1u, description->audio_entries.size());
80 
81  // Add a second entry for clear content if needed.
82  if (clear_lead_in_seconds > 0)
83  description->audio_entries.push_back(description->audio_entries[0]);
84 
85  // Convert the first entry to an encrypted entry.
86  AudioSampleEntry& entry = description->audio_entries[0];
87  GenerateSinf(encryption_key, entry.format, &entry.sinf);
88  entry.format = FOURCC_ENCA;
89  }
90 }
91 
92 VideoCodec GetVideoCodec(const StreamInfo& stream_info) {
93  if (stream_info.stream_type() != kStreamVideo)
94  return kUnknownVideoCodec;
95  const VideoStreamInfo& video_stream_info =
96  static_cast<const VideoStreamInfo&>(stream_info);
97  return video_stream_info.codec();
98 }
99 
100 uint8_t GetNaluLengthSize(const StreamInfo& stream_info) {
101  if (stream_info.stream_type() != kStreamVideo)
102  return 0;
103  const VideoStreamInfo& video_stream_info =
104  static_cast<const VideoStreamInfo&>(stream_info);
105  return video_stream_info.nalu_length_size();
106 }
107 
108 KeySource::TrackType GetTrackTypeForEncryption(const StreamInfo& stream_info,
109  uint32_t max_sd_pixels) {
110  if (stream_info.stream_type() == kStreamAudio)
111  return KeySource::TRACK_TYPE_AUDIO;
112 
113  DCHECK_EQ(kStreamVideo, stream_info.stream_type());
114  const VideoStreamInfo& video_stream_info =
115  static_cast<const VideoStreamInfo&>(stream_info);
116  uint32_t pixels = video_stream_info.width() * video_stream_info.height();
117  return (pixels > max_sd_pixels) ? KeySource::TRACK_TYPE_HD
118  : KeySource::TRACK_TYPE_SD;
119 }
120 
121 } // namespace
122 
123 Segmenter::Segmenter(const MuxerOptions& options,
124  scoped_ptr<FileType> ftyp,
125  scoped_ptr<Movie> moov)
126  : options_(options),
127  ftyp_(ftyp.Pass()),
128  moov_(moov.Pass()),
129  moof_(new MovieFragment()),
130  fragment_buffer_(new BufferWriter()),
131  sidx_(new SegmentIndex()),
132  muxer_listener_(NULL),
133  progress_listener_(NULL),
134  progress_target_(0),
135  accumulated_progress_(0),
136  sample_duration_(0u) {}
137 
138 Segmenter::~Segmenter() { STLDeleteElements(&fragmenters_); }
139 
140 Status Segmenter::Initialize(const std::vector<MediaStream*>& streams,
141  MuxerListener* muxer_listener,
142  ProgressListener* progress_listener,
143  KeySource* encryption_key_source,
144  uint32_t max_sd_pixels,
145  double clear_lead_in_seconds,
146  double crypto_period_duration_in_seconds) {
147  DCHECK_LT(0u, streams.size());
148  muxer_listener_ = muxer_listener;
149  progress_listener_ = progress_listener;
150  moof_->header.sequence_number = 0;
151 
152  moof_->tracks.resize(streams.size());
153  segment_durations_.resize(streams.size());
154  fragmenters_.resize(streams.size());
155  const bool key_rotation_enabled = crypto_period_duration_in_seconds != 0;
156  const bool kInitialEncryptionInfo = true;
157 
158  for (uint32_t i = 0; i < streams.size(); ++i) {
159  stream_map_[streams[i]] = i;
160  moof_->tracks[i].header.track_id = i + 1;
161  if (streams[i]->info()->stream_type() == kStreamVideo) {
162  // Use the first video stream as the reference stream (which is 1-based).
163  if (sidx_->reference_id == 0)
164  sidx_->reference_id = i + 1;
165  }
166  if (!encryption_key_source) {
167  fragmenters_[i] = new Fragmenter(&moof_->tracks[i]);
168  continue;
169  }
170 
171  VideoCodec video_codec = GetVideoCodec(*streams[i]->info());
172  uint8_t nalu_length_size = GetNaluLengthSize(*streams[i]->info());
173  KeySource::TrackType track_type =
174  GetTrackTypeForEncryption(*streams[i]->info(), max_sd_pixels);
175  SampleDescription& description =
176  moov_->tracks[i].media.information.sample_table.description;
177 
178  if (key_rotation_enabled) {
179  // Fill encrypted sample entry with default key.
180  EncryptionKey encryption_key;
181  encryption_key.key_id.assign(
182  kKeyRotationDefaultKeyId,
183  kKeyRotationDefaultKeyId + arraysize(kKeyRotationDefaultKeyId));
184  GenerateEncryptedSampleEntry(encryption_key, clear_lead_in_seconds,
185  &description);
186  if (muxer_listener_) {
187  muxer_listener_->OnEncryptionInfoReady(
188  kInitialEncryptionInfo, encryption_key_source->UUID(),
189  encryption_key_source->SystemName(), encryption_key.key_id,
190  std::vector<uint8_t>());
191  }
192 
193  fragmenters_[i] = new KeyRotationFragmenter(
194  moof_.get(), &moof_->tracks[i], encryption_key_source, track_type,
195  crypto_period_duration_in_seconds * streams[i]->info()->time_scale(),
196  clear_lead_in_seconds * streams[i]->info()->time_scale(), video_codec,
197  nalu_length_size, muxer_listener_);
198  continue;
199  }
200 
201  scoped_ptr<EncryptionKey> encryption_key(new EncryptionKey());
202  Status status =
203  encryption_key_source->GetKey(track_type, encryption_key.get());
204  if (!status.ok())
205  return status;
206 
207  GenerateEncryptedSampleEntry(*encryption_key, clear_lead_in_seconds,
208  &description);
209 
210  // One and only one pssh box is needed.
211  if (moov_->pssh.empty()) {
212  moov_->pssh.resize(1);
213  moov_->pssh[0].raw_box = encryption_key->pssh;
214 
215  // Also only one default key id.
216  if (muxer_listener_) {
217  muxer_listener_->OnEncryptionInfoReady(
218  kInitialEncryptionInfo,
219  encryption_key_source->UUID(), encryption_key_source->SystemName(),
220  encryption_key->key_id, encryption_key->pssh);
221  }
222  }
223 
224  fragmenters_[i] = new EncryptingFragmenter(
225  &moof_->tracks[i], encryption_key.Pass(),
226  clear_lead_in_seconds * streams[i]->info()->time_scale(), video_codec,
227  nalu_length_size);
228  }
229 
230  // Choose the first stream if there is no VIDEO.
231  if (sidx_->reference_id == 0)
232  sidx_->reference_id = 1;
233  sidx_->timescale = streams[GetReferenceStreamId()]->info()->time_scale();
234 
235  // Use media duration as progress target.
236  progress_target_ = streams[GetReferenceStreamId()]->info()->duration();
237 
238  // Use the reference stream's time scale as movie time scale.
239  moov_->header.timescale = sidx_->timescale;
240  moof_->header.sequence_number = 1;
241 
242  // Fill in version information.
243  moov_->metadata.handler.handler_type = FOURCC_ID32;
244  moov_->metadata.id3v2.language.code = "eng";
245  moov_->metadata.id3v2.private_frame.owner =
246  "https://github.com/google/edash-packager";
247  moov_->metadata.id3v2.private_frame.value = options_.packager_version_string;
248  return DoInitialize();
249 }
250 
252  for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
253  it != fragmenters_.end();
254  ++it) {
255  Status status = FinalizeFragment(true, *it);
256  if (!status.ok())
257  return status;
258  }
259 
260  // Set tracks and moov durations.
261  // Note that the updated moov box will be written to output file for VOD case
262  // only.
263  for (std::vector<Track>::iterator track = moov_->tracks.begin();
264  track != moov_->tracks.end();
265  ++track) {
266  track->header.duration = Rescale(track->media.header.duration,
267  track->media.header.timescale,
268  moov_->header.timescale);
269  if (track->header.duration > moov_->header.duration)
270  moov_->header.duration = track->header.duration;
271  }
272  moov_->extends.header.fragment_duration = moov_->header.duration;
273 
274  return DoFinalize();
275 }
276 
278  scoped_refptr<MediaSample> sample) {
279  // Find the fragmenter for this stream.
280  DCHECK(stream);
281  DCHECK(stream_map_.find(stream) != stream_map_.end());
282  uint32_t stream_id = stream_map_[stream];
283  Fragmenter* fragmenter = fragmenters_[stream_id];
284 
285  // Set default sample duration if it has not been set yet.
286  if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
287  moov_->extends.tracks[stream_id].default_sample_duration =
288  sample->duration();
289  }
290 
291  if (fragmenter->fragment_finalized()) {
292  return Status(error::FRAGMENT_FINALIZED,
293  "Current fragment is finalized already.");
294  }
295 
296  bool finalize_fragment = false;
297  if (fragmenter->fragment_duration() >=
298  options_.fragment_duration * stream->info()->time_scale()) {
299  if (sample->is_key_frame() || !options_.fragment_sap_aligned) {
300  finalize_fragment = true;
301  }
302  }
303  bool finalize_segment = false;
304  if (segment_durations_[stream_id] >=
305  options_.segment_duration * stream->info()->time_scale()) {
306  if (sample->is_key_frame() || !options_.segment_sap_aligned) {
307  finalize_segment = true;
308  finalize_fragment = true;
309  }
310  }
311 
312  Status status;
313  if (finalize_fragment) {
314  status = FinalizeFragment(finalize_segment, fragmenter);
315  if (!status.ok())
316  return status;
317  }
318 
319  status = fragmenter->AddSample(sample);
320  if (!status.ok())
321  return status;
322 
323  if (sample_duration_ == 0)
324  sample_duration_ = sample->duration();
325  moov_->tracks[stream_id].media.header.duration += sample->duration();
326  segment_durations_[stream_id] += sample->duration();
327  DCHECK_GE(segment_durations_[stream_id], fragmenter->fragment_duration());
328  return Status::OK;
329 }
330 
331 uint32_t Segmenter::GetReferenceTimeScale() const {
332  return moov_->header.timescale;
333 }
334 
335 double Segmenter::GetDuration() const {
336  if (moov_->header.timescale == 0) {
337  // Handling the case where this is not properly initialized.
338  return 0.0;
339  }
340 
341  return static_cast<double>(moov_->header.duration) / moov_->header.timescale;
342 }
343 
344 void Segmenter::UpdateProgress(uint64_t progress) {
345  accumulated_progress_ += progress;
346 
347  if (!progress_listener_) return;
348  if (progress_target_ == 0) return;
349  // It might happen that accumulated progress exceeds progress_target due to
350  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
351  // progress.
352  if (accumulated_progress_ >= progress_target_) {
353  progress_listener_->OnProgress(1.0);
354  } else {
355  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
356  progress_target_);
357  }
358 }
359 
360 void Segmenter::SetComplete() {
361  if (!progress_listener_) return;
362  progress_listener_->OnProgress(1.0);
363 }
364 
365 Status Segmenter::FinalizeSegment() {
366  Status status = DoFinalizeSegment();
367 
368  // Reset segment information to initial state.
369  sidx_->references.clear();
370  std::vector<uint64_t>::iterator it = segment_durations_.begin();
371  for (; it != segment_durations_.end(); ++it)
372  *it = 0;
373 
374  return status;
375 }
376 
377 uint32_t Segmenter::GetReferenceStreamId() {
378  DCHECK(sidx_);
379  return sidx_->reference_id - 1;
380 }
381 
382 Status Segmenter::FinalizeFragment(bool finalize_segment,
383  Fragmenter* fragmenter) {
384  fragmenter->FinalizeFragment();
385 
386  // Check if all tracks are ready for fragmentation.
387  for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
388  it != fragmenters_.end();
389  ++it) {
390  if (!(*it)->fragment_finalized())
391  return Status::OK;
392  }
393 
394  MediaData mdat;
395  // Data offset relative to 'moof': moof size + mdat header size.
396  // The code will also update box sizes for moof_ and its child boxes.
397  uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
398  // 'traf' should follow 'mfhd' moof header box.
399  uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
400  for (size_t i = 0; i < moof_->tracks.size(); ++i) {
401  TrackFragment& traf = moof_->tracks[i];
402  if (traf.auxiliary_offset.offsets.size() > 0) {
403  DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
404  DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
405 
406  next_traf_position += traf.box_size();
407  // SampleEncryption 'senc' box should be the last box in 'traf'.
408  // |auxiliary_offset| should point to the data of SampleEncryption.
409  traf.auxiliary_offset.offsets[0] =
410  next_traf_position - traf.sample_encryption.box_size() +
411  traf.sample_encryption.HeaderSize() +
412  sizeof(uint32_t); // for sample count field in 'senc'
413  }
414  traf.runs[0].data_offset = data_offset + mdat.data_size;
415  mdat.data_size += fragmenters_[i]->data()->Size();
416  }
417 
418  // Generate segment reference.
419  sidx_->references.resize(sidx_->references.size() + 1);
420  fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
421  &sidx_->references[sidx_->references.size() - 1]);
422  sidx_->references[sidx_->references.size() - 1].referenced_size =
423  data_offset + mdat.data_size;
424 
425  // Write the fragment to buffer.
426  moof_->Write(fragment_buffer_.get());
427  mdat.WriteHeader(fragment_buffer_.get());
428  for (Fragmenter* fragmenter : fragmenters_)
429  fragment_buffer_->AppendBuffer(*fragmenter->data());
430 
431  // Increase sequence_number for next fragment.
432  ++moof_->header.sequence_number;
433 
434  if (finalize_segment)
435  return FinalizeSegment();
436 
437  return Status::OK;
438 }
439 
440 } // namespace mp4
441 } // namespace media
442 } // namespace edash_packager
virtual Status GetKey(TrackType track_type, EncryptionKey *key)
Definition: key_source.cc:46
Status Initialize(scoped_ptr< MkvWriter > writer, StreamInfo *info, ProgressListener *progress_listener, MuxerListener *muxer_listener, KeySource *encryption_key_source, uint32_t max_sd_pixels, double clear_lead_in_seconds)
Definition: segmenter.cc:45
std::string packager_version_string
Specify the version string to be embedded in the output files.
Definition: muxer_options.h:71
This class listens to progress updates events.
EncryptingFragmenter generates MP4 fragments with sample encrypted.
virtual Status AddSample(scoped_refptr< MediaSample > sample)
Definition: fragmenter.cc:36
virtual std::string UUID()
Definition: key_source.cc:92
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:29
virtual void OnProgress(double progress)=0
void UpdateProgress(uint64_t progress)
Update segmentation progress using ProgressListener.
Definition: segmenter.cc:240
virtual std::string SystemName()
Definition: key_source.cc:96
Status AddSample(scoped_refptr< MediaSample > sample)
Definition: segmenter.cc:104