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