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/media_stream.h"
17 #include "packager/media/base/muxer_options.h"
18 #include "packager/media/base/muxer_util.h"
19 #include "packager/media/base/video_stream_info.h"
20 #include "packager/media/event/muxer_listener.h"
21 #include "packager/media/event/progress_listener.h"
22 #include "packager/media/formats/mp4/box_definitions.h"
23 #include "packager/media/formats/mp4/key_rotation_fragmenter.h"
24 #include "packager/version/version.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 static_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 =
105  static_cast<uint8_t>(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  std::unique_ptr<FileType> ftyp,
150  std::unique_ptr<Movie> moov)
151  : options_(options),
152  ftyp_(std::move(ftyp)),
153  moov_(std::move(moov)),
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() {}
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].reset(
194  new Fragmenter(streams[i]->info(), &moof_->tracks[i]));
195  continue;
196  }
197 
198  KeySource::TrackType track_type =
199  GetTrackTypeForEncryption(*streams[i]->info(), max_sd_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]->info(), &moof_->tracks[i],
225  encryption_key_source, track_type,
226  crypto_period_duration_in_seconds * streams[i]->info()->time_scale(),
227  clear_lead_in_seconds * streams[i]->info()->time_scale(),
228  protection_scheme, pattern.crypt_byte_block, pattern.skip_byte_block,
229  muxer_listener_));
230  continue;
231  }
232 
233  std::unique_ptr<EncryptionKey> encryption_key(new EncryptionKey());
234  Status status =
235  encryption_key_source->GetKey(track_type, encryption_key.get());
236  if (!status.ok())
237  return status;
238  if (encryption_key->iv.empty()) {
239  if (!AesCryptor::GenerateRandomIv(protection_scheme,
240  &encryption_key->iv)) {
241  return Status(error::INTERNAL_ERROR, "Failed to generate random iv.");
242  }
243  }
244 
245  GenerateEncryptedSampleEntry(*encryption_key, clear_lead_in_seconds,
246  protection_scheme, pattern, &description);
247 
248  if (moov_->pssh.empty()) {
249  moov_->pssh.resize(encryption_key->key_system_info.size());
250  for (size_t i = 0; i < encryption_key->key_system_info.size(); i++) {
251  moov_->pssh[i].raw_box = encryption_key->key_system_info[i].CreateBox();
252  }
253 
254  if (muxer_listener_) {
255  muxer_listener_->OnEncryptionInfoReady(
256  kInitialEncryptionInfo, protection_scheme, encryption_key->key_id,
257  encryption_key->iv, encryption_key->key_system_info);
258  }
259  }
260 
261  fragmenters_[i].reset(new EncryptingFragmenter(
262  streams[i]->info(), &moof_->tracks[i], std::move(encryption_key),
263  clear_lead_in_seconds * streams[i]->info()->time_scale(),
264  protection_scheme, pattern.crypt_byte_block, pattern.skip_byte_block,
265  muxer_listener_));
266  }
267 
269  for (uint32_t i = 0; i < streams.size(); ++i)
270  fragmenters_[i]->set_use_decoding_timestamp_in_timeline(true);
271  }
272 
273  // Choose the first stream if there is no VIDEO.
274  if (sidx_->reference_id == 0)
275  sidx_->reference_id = 1;
276  sidx_->timescale = streams[GetReferenceStreamId()]->info()->time_scale();
277 
278  // Use media duration as progress target.
279  progress_target_ = streams[GetReferenceStreamId()]->info()->duration();
280 
281  // Use the reference stream's time scale as movie time scale.
282  moov_->header.timescale = sidx_->timescale;
283  moof_->header.sequence_number = 1;
284 
285  // Fill in version information.
286  const std::string version = GetPackagerVersion();
287  if (!version.empty()) {
288  moov_->metadata.handler.handler_type = FOURCC_ID32;
289  moov_->metadata.id3v2.language.code = "eng";
290  moov_->metadata.id3v2.private_frame.owner = GetPackagerProjectUrl();
291  moov_->metadata.id3v2.private_frame.value = version;
292  }
293  return DoInitialize();
294 }
295 
297  for (const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_) {
298  Status status = FinalizeFragment(true, fragmenter.get());
299  if (!status.ok())
300  return status;
301  }
302 
303  // Set tracks and moov durations.
304  // Note that the updated moov box will be written to output file for VOD case
305  // only.
306  for (std::vector<Track>::iterator track = moov_->tracks.begin();
307  track != moov_->tracks.end();
308  ++track) {
309  track->header.duration = Rescale(track->media.header.duration,
310  track->media.header.timescale,
311  moov_->header.timescale);
312  if (track->header.duration > moov_->header.duration)
313  moov_->header.duration = track->header.duration;
314  }
315  moov_->extends.header.fragment_duration = moov_->header.duration;
316 
317  return DoFinalize();
318 }
319 
321  scoped_refptr<MediaSample> sample) {
322  // Find the fragmenter for this stream.
323  DCHECK(stream);
324  DCHECK(stream_map_.find(stream) != stream_map_.end());
325  uint32_t stream_id = stream_map_[stream];
326  Fragmenter* fragmenter = fragmenters_[stream_id].get();
327 
328  // Set default sample duration if it has not been set yet.
329  if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
330  moov_->extends.tracks[stream_id].default_sample_duration =
331  sample->duration();
332  }
333 
334  if (fragmenter->fragment_finalized()) {
335  return Status(error::FRAGMENT_FINALIZED,
336  "Current fragment is finalized already.");
337  }
338 
339  bool finalize_fragment = false;
340  if (fragmenter->fragment_duration() >=
341  options_.fragment_duration * stream->info()->time_scale()) {
342  if (sample->is_key_frame() || !options_.fragment_sap_aligned) {
343  finalize_fragment = true;
344  }
345  }
346  bool finalize_segment = false;
347  if (segment_durations_[stream_id] >=
348  options_.segment_duration * stream->info()->time_scale()) {
349  if (sample->is_key_frame() || !options_.segment_sap_aligned) {
350  finalize_segment = true;
351  finalize_fragment = true;
352  }
353  }
354 
355  Status status;
356  if (finalize_fragment) {
357  status = FinalizeFragment(finalize_segment, fragmenter);
358  if (!status.ok())
359  return status;
360  }
361 
362  status = fragmenter->AddSample(sample);
363  if (!status.ok())
364  return status;
365 
366  if (sample_duration_ == 0)
367  sample_duration_ = sample->duration();
368  moov_->tracks[stream_id].media.header.duration += sample->duration();
369  segment_durations_[stream_id] += sample->duration();
370  DCHECK_GE(segment_durations_[stream_id], fragmenter->fragment_duration());
371  return Status::OK;
372 }
373 
374 uint32_t Segmenter::GetReferenceTimeScale() const {
375  return moov_->header.timescale;
376 }
377 
378 double Segmenter::GetDuration() const {
379  if (moov_->header.timescale == 0) {
380  // Handling the case where this is not properly initialized.
381  return 0.0;
382  }
383 
384  return static_cast<double>(moov_->header.duration) / moov_->header.timescale;
385 }
386 
387 void Segmenter::UpdateProgress(uint64_t progress) {
388  accumulated_progress_ += progress;
389 
390  if (!progress_listener_) return;
391  if (progress_target_ == 0) return;
392  // It might happen that accumulated progress exceeds progress_target due to
393  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
394  // progress.
395  if (accumulated_progress_ >= progress_target_) {
396  progress_listener_->OnProgress(1.0);
397  } else {
398  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
399  progress_target_);
400  }
401 }
402 
403 void Segmenter::SetComplete() {
404  if (!progress_listener_) return;
405  progress_listener_->OnProgress(1.0);
406 }
407 
408 Status Segmenter::FinalizeSegment() {
409  Status status = DoFinalizeSegment();
410 
411  // Reset segment information to initial state.
412  sidx_->references.clear();
413  std::vector<uint64_t>::iterator it = segment_durations_.begin();
414  for (; it != segment_durations_.end(); ++it)
415  *it = 0;
416 
417  return status;
418 }
419 
420 uint32_t Segmenter::GetReferenceStreamId() {
421  DCHECK(sidx_);
422  return sidx_->reference_id - 1;
423 }
424 
425 Status Segmenter::FinalizeFragment(bool finalize_segment,
426  Fragmenter* fragmenter) {
427  fragmenter->FinalizeFragment();
428 
429  // Check if all tracks are ready for fragmentation.
430  for (const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_) {
431  if (!fragmenter->fragment_finalized())
432  return Status::OK;
433  }
434 
435  MediaData mdat;
436  // Data offset relative to 'moof': moof size + mdat header size.
437  // The code will also update box sizes for moof_ and its child boxes.
438  uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
439  // 'traf' should follow 'mfhd' moof header box.
440  uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
441  for (size_t i = 0; i < moof_->tracks.size(); ++i) {
442  TrackFragment& traf = moof_->tracks[i];
443  if (traf.auxiliary_offset.offsets.size() > 0) {
444  DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
445  DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
446 
447  next_traf_position += traf.box_size();
448  // SampleEncryption 'senc' box should be the last box in 'traf'.
449  // |auxiliary_offset| should point to the data of SampleEncryption.
450  traf.auxiliary_offset.offsets[0] =
451  next_traf_position - traf.sample_encryption.box_size() +
452  traf.sample_encryption.HeaderSize() +
453  sizeof(uint32_t); // for sample count field in 'senc'
454  }
455  traf.runs[0].data_offset = data_offset + mdat.data_size;
456  mdat.data_size += fragmenters_[i]->data()->Size();
457  }
458 
459  // Generate segment reference.
460  sidx_->references.resize(sidx_->references.size() + 1);
461  fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
462  &sidx_->references[sidx_->references.size() - 1]);
463  sidx_->references[sidx_->references.size() - 1].referenced_size =
464  data_offset + mdat.data_size;
465 
466  // Write the fragment to buffer.
467  moof_->Write(fragment_buffer_.get());
468  mdat.WriteHeader(fragment_buffer_.get());
469  for (const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_)
470  fragment_buffer_->AppendBuffer(*fragmenter->data());
471 
472  // Increase sequence_number for next fragment.
473  ++moof_->header.sequence_number;
474 
475  if (finalize_segment)
476  return FinalizeSegment();
477 
478  return Status::OK;
479 }
480 
481 } // namespace mp4
482 } // namespace media
483 } // namespace shaka
Status AddSample(scoped_refptr< MediaSample > sample)
Definition: segmenter.cc:120
virtual Status AddSample(scoped_refptr< MediaSample > sample)
Definition: fragmenter.cc:46
virtual Status GetKey(TrackType track_type, EncryptionKey *key)=0
This class listens to progress updates events.
static bool GenerateRandomIv(FourCC protection_scheme, std::vector< uint8_t > *iv)
Definition: aes_cryptor.cc:107
Status Initialize(std::unique_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:51
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:259