DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
encrypting_fragmenter.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/encrypting_fragmenter.h"
8 
9 #include <limits>
10 
11 #include "packager/media/base/aes_encryptor.h"
12 #include "packager/media/base/aes_pattern_cryptor.h"
13 #include "packager/media/base/buffer_reader.h"
14 #include "packager/media/base/key_source.h"
15 #include "packager/media/base/media_sample.h"
16 #include "packager/media/codecs/nalu_reader.h"
17 #include "packager/media/codecs/vp8_parser.h"
18 #include "packager/media/codecs/vp9_parser.h"
19 #include "packager/media/formats/mp4/box_definitions.h"
20 
21 namespace shaka {
22 namespace media {
23 namespace mp4 {
24 
25 namespace {
26 const size_t kCencBlockSize = 16u;
27 
28 // Adds one or more subsamples to |*subsamples|. This may add more than one
29 // if one of the values overflows the integer in the subsample.
30 void AddSubsamples(uint64_t clear_bytes,
31  uint64_t cipher_bytes,
32  std::vector<SubsampleEntry>* subsamples) {
33  CHECK_LT(cipher_bytes, std::numeric_limits<uint32_t>::max());
34  const uint64_t kUInt16Max = std::numeric_limits<uint16_t>::max();
35  while (clear_bytes > kUInt16Max) {
36  subsamples->push_back(SubsampleEntry(kUInt16Max, 0));
37  clear_bytes -= kUInt16Max;
38  }
39 
40  if (clear_bytes > 0 || cipher_bytes > 0)
41  subsamples->push_back(SubsampleEntry(clear_bytes, cipher_bytes));
42 }
43 
44 Codec GetCodec(const StreamInfo& stream_info) {
45  if (stream_info.stream_type() != kStreamVideo) return kUnknownCodec;
46  const VideoStreamInfo& video_stream_info =
47  static_cast<const VideoStreamInfo&>(stream_info);
48  return video_stream_info.codec();
49 }
50 
51 uint8_t GetNaluLengthSize(const StreamInfo& stream_info) {
52  if (stream_info.stream_type() != kStreamVideo)
53  return 0;
54 
55  const VideoStreamInfo& video_stream_info =
56  static_cast<const VideoStreamInfo&>(stream_info);
57  return video_stream_info.nalu_length_size();
58 }
59 } // namespace
60 
62  scoped_refptr<StreamInfo> info, TrackFragment* traf,
63  scoped_ptr<EncryptionKey> encryption_key, int64_t clear_time,
64  FourCC protection_scheme, uint8_t crypt_byte_block, uint8_t skip_byte_block,
65  MuxerListener* listener)
66  : Fragmenter(info, traf),
67  info_(info),
68  encryption_key_(encryption_key.Pass()),
69  nalu_length_size_(GetNaluLengthSize(*info)),
70  video_codec_(GetCodec(*info)),
71  clear_time_(clear_time),
72  protection_scheme_(protection_scheme),
73  crypt_byte_block_(crypt_byte_block),
74  skip_byte_block_(skip_byte_block),
75  listener_(listener) {
76  DCHECK(encryption_key_);
77  switch (video_codec_) {
78  case kCodecVP8:
79  vpx_parser_.reset(new VP8Parser);
80  break;
81  case kCodecVP9:
82  vpx_parser_.reset(new VP9Parser);
83  break;
84  case kCodecH264:
85  header_parser_.reset(new H264VideoSliceHeaderParser);
86  break;
87  case kCodecHVC1:
88  FALLTHROUGH_INTENDED;
89  case kCodecHEV1:
90  header_parser_.reset(new H265VideoSliceHeaderParser);
91  break;
92  default:
93  if (nalu_length_size_ > 0) {
94  LOG(WARNING) << "Unknown video codec '" << video_codec_
95  << "', whole subsamples will be encrypted.";
96  }
97  }
98 }
99 
100 EncryptingFragmenter::~EncryptingFragmenter() {}
101 
102 Status EncryptingFragmenter::AddSample(scoped_refptr<MediaSample> sample) {
103  DCHECK(sample);
104  if (!fragment_initialized()) {
105  Status status = InitializeFragment(sample->dts());
106  if (!status.ok())
107  return status;
108  }
109  if (encryptor_) {
110  Status status = EncryptSample(sample);
111  if (!status.ok())
112  return status;
113  }
114  return Fragmenter::AddSample(sample);
115 }
116 
118  Status status = Fragmenter::InitializeFragment(first_sample_dts);
119  if (!status.ok())
120  return status;
121 
122  if (header_parser_ && !header_parser_->Initialize(info_->codec_config()))
123  return Status(error::MUXER_FAILURE, "Fail to read SPS and PPS data.");
124 
125  traf()->auxiliary_size.sample_info_sizes.clear();
126  traf()->auxiliary_offset.offsets.clear();
127  if (IsSubsampleEncryptionRequired()) {
128  traf()->sample_encryption.flags |=
129  SampleEncryption::kUseSubsampleEncryption;
130  }
131  traf()->sample_encryption.sample_encryption_entries.clear();
132 
133  const bool enable_encryption = clear_time_ <= 0;
134  if (!enable_encryption) {
135  // This fragment should be in clear text.
136  // At most two sample description entries, an encrypted entry and a clear
137  // entry, are generated. The 1-based clear entry index is always 2.
138  const uint32_t kClearSampleDescriptionIndex = 2;
139 
140  traf()->header.flags |=
141  TrackFragmentHeader::kSampleDescriptionIndexPresentMask;
142  traf()->header.sample_description_index = kClearSampleDescriptionIndex;
143  } else {
144  if (listener_)
145  listener_->OnEncryptionStart();
146  }
147  return PrepareFragmentForEncryption(enable_encryption);
148 }
149 
151  if (encryptor_) {
152  DCHECK_LE(clear_time_, 0);
154  } else {
155  DCHECK_GT(clear_time_, 0);
156  clear_time_ -= fragment_duration();
157  }
159 }
160 
162  bool enable_encryption) {
163  return (!enable_encryption || encryptor_) ? Status::OK : CreateEncryptor();
164 }
165 
167  // The offset will be adjusted in Segmenter after knowing moof size.
168  traf()->auxiliary_offset.offsets.push_back(0);
169 
170  // For 'cbcs' scheme, Constant IVs SHALL be used.
171  const uint8_t per_sample_iv_size =
172  (protection_scheme_ == FOURCC_cbcs) ? 0 :
173  static_cast<uint8_t>(encryptor_->iv().size());
174  traf()->sample_encryption.iv_size = per_sample_iv_size;
175 
176  // Optimize saiz box.
177  SampleAuxiliaryInformationSize& saiz = traf()->auxiliary_size;
178  saiz.sample_count = traf()->runs[0].sample_sizes.size();
179  if (!saiz.sample_info_sizes.empty()) {
180  if (!OptimizeSampleEntries(&saiz.sample_info_sizes,
181  &saiz.default_sample_info_size)) {
182  saiz.default_sample_info_size = 0;
183  }
184  } else {
185  // |sample_info_sizes| table is filled in only for subsample encryption,
186  // otherwise |sample_info_size| is just the IV size.
187  DCHECK(!IsSubsampleEncryptionRequired());
188  saiz.default_sample_info_size = static_cast<uint8_t>(per_sample_iv_size);
189  }
190 
191  // It should only happen with full sample encryption + constant iv, i.e.
192  // 'cbcs' applying to audio.
193  if (saiz.default_sample_info_size == 0 && saiz.sample_info_sizes.empty()) {
194  DCHECK_EQ(protection_scheme_, FOURCC_cbcs);
195  DCHECK(!IsSubsampleEncryptionRequired());
196  // ISO/IEC 23001-7:2016(E) The sample auxiliary information would then be
197  // empty and should be emitted. Clear saiz and saio boxes so they are not
198  // written.
199  saiz.sample_count = 0;
200  traf()->auxiliary_offset.offsets.clear();
201  }
202 }
203 
205  DCHECK(encryption_key_);
206  scoped_ptr<AesCryptor> encryptor;
207  switch (protection_scheme_) {
208  case FOURCC_cenc:
209  encryptor.reset(new AesCtrEncryptor);
210  break;
211  case FOURCC_cbc1:
212  encryptor.reset(new AesCbcEncryptor(kNoPadding));
213  break;
214  case FOURCC_cens:
215  encryptor.reset(new AesPatternCryptor(
216  crypt_byte_block(), skip_byte_block(),
218  AesCryptor::kDontUseConstantIv,
219  scoped_ptr<AesCryptor>(new AesCtrEncryptor())));
220  break;
221  case FOURCC_cbcs:
222  encryptor.reset(new AesPatternCryptor(
223  crypt_byte_block(), skip_byte_block(),
225  AesCryptor::kUseConstantIv,
226  scoped_ptr<AesCryptor>(new AesCbcEncryptor(kNoPadding))));
227  break;
228  default:
229  return Status(error::MUXER_FAILURE, "Unsupported protection scheme.");
230  }
231 
232  DCHECK(!encryption_key_->iv.empty());
233  const bool initialized =
234  encryptor->InitializeWithIv(encryption_key_->key, encryption_key_->iv);
235  if (!initialized)
236  return Status(error::MUXER_FAILURE, "Failed to create the encryptor.");
237  encryptor_ = encryptor.Pass();
238  return Status::OK;
239 }
240 
241 void EncryptingFragmenter::EncryptBytes(uint8_t* data, uint32_t size) {
242  DCHECK(encryptor_);
243  CHECK(encryptor_->Crypt(data, size, data));
244 }
245 
246 Status EncryptingFragmenter::EncryptSample(scoped_refptr<MediaSample> sample) {
247  DCHECK(encryptor_);
248 
249  SampleEncryptionEntry sample_encryption_entry;
250  // For 'cbcs' scheme, Constant IVs SHALL be used.
251  if (protection_scheme_ != FOURCC_cbcs)
252  sample_encryption_entry.initialization_vector = encryptor_->iv();
253  uint8_t* data = sample->writable_data();
254  if (IsSubsampleEncryptionRequired()) {
255  if (vpx_parser_) {
256  std::vector<VPxFrameInfo> vpx_frames;
257  if (!vpx_parser_->Parse(sample->data(), sample->data_size(),
258  &vpx_frames)) {
259  return Status(error::MUXER_FAILURE, "Failed to parse vpx frame.");
260  }
261 
262  const bool is_superframe = vpx_frames.size() > 1;
263  for (const VPxFrameInfo& frame : vpx_frames) {
264  SubsampleEntry subsample;
265  subsample.clear_bytes =
266  static_cast<uint16_t>(frame.uncompressed_header_size);
267  subsample.cipher_bytes =
268  frame.frame_size - frame.uncompressed_header_size;
269 
270  // "VP Codec ISO Media File Format Binding" document requires that the
271  // encrypted bytes of each frame within the superframe must be block
272  // aligned so that the counter state can be computed for each frame
273  // within the superframe.
274  // ISO/IEC 23001-7:2016 10.2 'cbc1' 10.3 'cens'
275  // The BytesOfProtectedData size SHALL be a multiple of 16 bytes to
276  // avoid partial blocks in Subsamples.
277  if (is_superframe || protection_scheme_ == FOURCC_cbc1 ||
278  protection_scheme_ == FOURCC_cens) {
279  const uint16_t misalign_bytes =
280  subsample.cipher_bytes % kCencBlockSize;
281  subsample.clear_bytes += misalign_bytes;
282  subsample.cipher_bytes -= misalign_bytes;
283  }
284 
285  sample_encryption_entry.subsamples.push_back(subsample);
286  if (subsample.cipher_bytes > 0)
287  EncryptBytes(data + subsample.clear_bytes, subsample.cipher_bytes);
288  data += frame.frame_size;
289  }
290  // Add subsample for the superframe index if exists.
291  if (is_superframe) {
292  size_t index_size = sample->data() + sample->data_size() - data;
293  DCHECK_LE(index_size, 2 + vpx_frames.size() * 4);
294  DCHECK_GE(index_size, 2 + vpx_frames.size() * 1);
295  SubsampleEntry subsample;
296  subsample.clear_bytes = static_cast<uint16_t>(index_size);
297  subsample.cipher_bytes = 0;
298  sample_encryption_entry.subsamples.push_back(subsample);
299  }
300  } else {
301  const Nalu::CodecType nalu_type =
302  (video_codec_ == kCodecHVC1 || video_codec_ == kCodecHEV1)
303  ? Nalu::kH265
304  : Nalu::kH264;
305  NaluReader reader(nalu_type, nalu_length_size_, data,
306  sample->data_size());
307 
308  // Store the current length of clear data. This is used to squash
309  // multiple unencrypted NAL units into fewer subsample entries.
310  uint64_t accumulated_clear_bytes = 0;
311 
312  Nalu nalu;
313  NaluReader::Result result;
314  while ((result = reader.Advance(&nalu)) == NaluReader::kOk) {
315  if (nalu.is_video_slice()) {
316  // For video-slice NAL units, encrypt the video slice. This skips
317  // the frame header. If this is an unrecognized codec (e.g. H.265),
318  // the whole NAL unit will be encrypted.
319  const int64_t video_slice_header_size =
320  header_parser_ ? header_parser_->GetHeaderSize(nalu) : 0;
321  if (video_slice_header_size < 0)
322  return Status(error::MUXER_FAILURE, "Failed to read slice header.");
323 
324  uint64_t current_clear_bytes =
325  nalu.header_size() + video_slice_header_size;
326  uint64_t cipher_bytes = nalu.payload_size() - video_slice_header_size;
327 
328  // ISO/IEC 23001-7:2016 10.2 'cbc1' 10.3 'cens'
329  // The BytesOfProtectedData size SHALL be a multiple of 16 bytes to
330  // avoid partial blocks in Subsamples.
331  if (protection_scheme_ == FOURCC_cbc1 ||
332  protection_scheme_ == FOURCC_cens) {
333  const uint16_t misalign_bytes = cipher_bytes % kCencBlockSize;
334  current_clear_bytes += misalign_bytes;
335  cipher_bytes -= misalign_bytes;
336  }
337 
338  const uint8_t* nalu_data = nalu.data() + current_clear_bytes;
339  EncryptBytes(const_cast<uint8_t*>(nalu_data), cipher_bytes);
340 
341  AddSubsamples(
342  accumulated_clear_bytes + nalu_length_size_ + current_clear_bytes,
343  cipher_bytes, &sample_encryption_entry.subsamples);
344  accumulated_clear_bytes = 0;
345  } else {
346  // For non-video-slice NAL units, don't encrypt.
347  accumulated_clear_bytes +=
348  nalu_length_size_ + nalu.header_size() + nalu.payload_size();
349  }
350  }
351  if (result != NaluReader::kEOStream)
352  return Status(error::MUXER_FAILURE, "Failed to parse NAL units.");
353  AddSubsamples(accumulated_clear_bytes, 0,
354  &sample_encryption_entry.subsamples);
355  }
356  DCHECK_EQ(sample_encryption_entry.GetTotalSizeOfSubsamples(),
357  sample->data_size());
358 
359  // The length of per-sample auxiliary datum, defined in CENC ch. 7.
360  traf()->auxiliary_size.sample_info_sizes.push_back(
361  sample_encryption_entry.ComputeSize());
362  } else {
363  DCHECK_LE(crypt_byte_block(), 1u);
364  DCHECK_EQ(skip_byte_block(), 0u);
365  EncryptBytes(data, sample->data_size());
366  }
367 
368  traf()->sample_encryption.sample_encryption_entries.push_back(
369  sample_encryption_entry);
370  encryptor_->UpdateIv();
371  return Status::OK;
372 }
373 
374 bool EncryptingFragmenter::IsSubsampleEncryptionRequired() {
375  return vpx_parser_ || nalu_length_size_ != 0;
376 }
377 
378 } // namespace mp4
379 } // namespace media
380 } // namespace shaka
Status AddSample(scoped_refptr< MediaSample > sample) override
Status InitializeFragment(int64_t first_sample_dts) override
EncryptingFragmenter(scoped_refptr< StreamInfo > info, TrackFragment *traf, scoped_ptr< EncryptionKey > encryption_key, int64_t clear_time, FourCC protection_scheme, uint8_t crypt_byte_block, uint8_t skip_byte_block, MuxerListener *listener)
virtual Status AddSample(scoped_refptr< MediaSample > sample)
Definition: fragmenter.cc:47
virtual void OnEncryptionStart()=0
void FinalizeFragment() override
Finalize and optimize the fragment.
virtual Status InitializeFragment(int64_t first_sample_dts)
Definition: fragmenter.cc:92
virtual void FinalizeFragment()
Finalize and optimize the fragment.
Definition: fragmenter.cc:111
virtual void FinalizeFragmentForEncryption()
Finalize current fragment for encryption.
Class to parse a vp9 bit stream.
Definition: vp9_parser.h:20
Implements pattern-based encryption/decryption.
virtual Status PrepareFragmentForEncryption(bool enable_encryption)
bool OptimizeSampleEntries(std::vector< T > *entries, T *default_value)
Definition: fragmenter.h:102