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