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