DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
encryption_handler.cc
1 // Copyright 2017 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/crypto/encryption_handler.h"
8 
9 #include <stddef.h>
10 #include <stdint.h>
11 
12 #include <limits>
13 
14 #include "packager/media/base/aes_encryptor.h"
15 #include "packager/media/base/aes_pattern_cryptor.h"
16 #include "packager/media/base/key_source.h"
17 #include "packager/media/base/media_sample.h"
18 #include "packager/media/base/video_stream_info.h"
19 #include "packager/media/codecs/video_slice_header_parser.h"
20 #include "packager/media/codecs/vp8_parser.h"
21 #include "packager/media/codecs/vp9_parser.h"
22 
23 namespace shaka {
24 namespace media {
25 
26 namespace {
27 const size_t kCencBlockSize = 16u;
28 
29 // The default KID for key rotation is all 0s.
30 const uint8_t kKeyRotationDefaultKeyId[] = {
31  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 };
33 
34 // Adds one or more subsamples to |*subsamples|. This may add more than one
35 // if one of the values overflows the integer in the subsample.
36 void AddSubsample(uint64_t clear_bytes,
37  uint64_t cipher_bytes,
38  DecryptConfig* decrypt_config) {
39  CHECK_LT(cipher_bytes, std::numeric_limits<uint32_t>::max());
40  const uint64_t kUInt16Max = std::numeric_limits<uint16_t>::max();
41  while (clear_bytes > kUInt16Max) {
42  decrypt_config->AddSubsample(kUInt16Max, 0);
43  clear_bytes -= kUInt16Max;
44  }
45 
46  if (clear_bytes > 0 || cipher_bytes > 0)
47  decrypt_config->AddSubsample(clear_bytes, cipher_bytes);
48 }
49 
50 uint8_t GetNaluLengthSize(const StreamInfo& stream_info) {
51  if (stream_info.stream_type() != kStreamVideo)
52  return 0;
53 
54  const VideoStreamInfo& video_stream_info =
55  static_cast<const VideoStreamInfo&>(stream_info);
56  return video_stream_info.nalu_length_size();
57 }
58 
59 std::string GetStreamLabelForEncryption(
60  const StreamInfo& stream_info,
61  const std::function<std::string(
62  const EncryptionParams::EncryptedStreamAttributes& stream_attributes)>&
63  stream_label_func) {
64  EncryptionParams::EncryptedStreamAttributes stream_attributes;
65  if (stream_info.stream_type() == kStreamAudio) {
66  stream_attributes.stream_type =
67  EncryptionParams::EncryptedStreamAttributes::kAudio;
68  } else if (stream_info.stream_type() == kStreamVideo) {
69  const VideoStreamInfo& video_stream_info =
70  static_cast<const VideoStreamInfo&>(stream_info);
71  stream_attributes.stream_type =
72  EncryptionParams::EncryptedStreamAttributes::kVideo;
73  stream_attributes.oneof.video.width = video_stream_info.width();
74  stream_attributes.oneof.video.height = video_stream_info.height();
75  }
76  return stream_label_func(stream_attributes);
77 }
78 } // namespace
79 
80 EncryptionHandler::EncryptionHandler(
81  const EncryptionOptions& encryption_options,
82  KeySource* key_source)
83  : encryption_options_(encryption_options), key_source_(key_source) {}
84 
85 EncryptionHandler::~EncryptionHandler() {}
86 
88  if (!encryption_options_.stream_label_func) {
89  return Status(error::INVALID_ARGUMENT, "Stream label function not set.");
90  }
91  if (num_input_streams() != 1 || next_output_stream_index() != 1) {
92  return Status(error::INVALID_ARGUMENT,
93  "Expects exactly one input and output.");
94  }
95  return Status::OK;
96 }
97 
98 Status EncryptionHandler::Process(std::unique_ptr<StreamData> stream_data) {
99  Status status;
100  switch (stream_data->stream_data_type) {
101  case StreamDataType::kStreamInfo:
102  status = ProcessStreamInfo(stream_data->stream_info.get());
103  break;
104  case StreamDataType::kSegmentInfo: {
105  SegmentInfo* segment_info = stream_data->segment_info.get();
106  segment_info->is_encrypted = remaining_clear_lead_ <= 0;
107 
108  const bool key_rotation_enabled = crypto_period_duration_ != 0;
109  if (key_rotation_enabled)
110  segment_info->key_rotation_encryption_config = encryption_config_;
111  if (!segment_info->is_subsegment) {
112  if (key_rotation_enabled)
113  check_new_crypto_period_ = true;
114  if (remaining_clear_lead_ > 0)
115  remaining_clear_lead_ -= segment_info->duration;
116  }
117  break;
118  }
119  case StreamDataType::kMediaSample:
120  status = ProcessMediaSample(stream_data->media_sample.get());
121  break;
122  default:
123  VLOG(3) << "Stream data type "
124  << static_cast<int>(stream_data->stream_data_type) << " ignored.";
125  break;
126  }
127  return status.ok() ? Dispatch(std::move(stream_data)) : status;
128 }
129 
130 Status EncryptionHandler::ProcessStreamInfo(StreamInfo* stream_info) {
131  if (stream_info->is_encrypted()) {
132  return Status(error::INVALID_ARGUMENT,
133  "Input stream is already encrypted.");
134  }
135 
136  remaining_clear_lead_ =
137  encryption_options_.clear_lead_in_seconds * stream_info->time_scale();
138  crypto_period_duration_ =
139  encryption_options_.crypto_period_duration_in_seconds *
140  stream_info->time_scale();
141  codec_ = stream_info->codec();
142  nalu_length_size_ = GetNaluLengthSize(*stream_info);
143  stream_label_ = GetStreamLabelForEncryption(
144  *stream_info, encryption_options_.stream_label_func);
145  switch (codec_) {
146  case kCodecVP9:
147  if (encryption_options_.vp9_subsample_encryption)
148  vpx_parser_.reset(new VP9Parser);
149  break;
150  case kCodecH264:
151  header_parser_.reset(new H264VideoSliceHeaderParser);
152  break;
153  case kCodecH265:
154  header_parser_.reset(new H265VideoSliceHeaderParser);
155  break;
156  default:
157  // Other codecs should have nalu length size == 0.
158  if (nalu_length_size_ > 0) {
159  LOG(WARNING) << "Unknown video codec '" << codec_ << "'";
160  return Status(error::ENCRYPTION_FAILURE, "Unknown video codec.");
161  }
162  }
163  if (header_parser_) {
164  CHECK_NE(nalu_length_size_, 0u) << "AnnexB stream is not supported yet";
165  if (!header_parser_->Initialize(stream_info->codec_config())) {
166  return Status(error::ENCRYPTION_FAILURE,
167  "Fail to read SPS and PPS data.");
168  }
169  }
170 
171  Status status = SetupProtectionPattern(stream_info->stream_type());
172  if (!status.ok())
173  return status;
174 
175  EncryptionKey encryption_key;
176  const bool key_rotation_enabled = crypto_period_duration_ != 0;
177  if (key_rotation_enabled) {
178  check_new_crypto_period_ = true;
179  // Setup dummy key id and key to signal encryption for key rotation.
180  encryption_key.key_id.assign(
181  kKeyRotationDefaultKeyId,
182  kKeyRotationDefaultKeyId + sizeof(kKeyRotationDefaultKeyId));
183  // The key is not really used to encrypt any data. It is there just for
184  // convenience.
185  encryption_key.key = encryption_key.key_id;
186  } else {
187  status = key_source_->GetKey(stream_label_, &encryption_key);
188  if (!status.ok())
189  return status;
190  }
191  if (!CreateEncryptor(encryption_key))
192  return Status(error::ENCRYPTION_FAILURE, "Failed to create encryptor");
193 
194  stream_info->set_is_encrypted(true);
195  stream_info->set_has_clear_lead(encryption_options_.clear_lead_in_seconds >
196  0);
197  stream_info->set_encryption_config(*encryption_config_);
198  return Status::OK;
199 }
200 
201 Status EncryptionHandler::ProcessMediaSample(MediaSample* sample) {
202  // We need to parse the frame (which also updates the vpx parser) even if the
203  // frame is not encrypted as the next (encrypted) frame may be dependent on
204  // this clear frame.
205  std::vector<VPxFrameInfo> vpx_frames;
206  if (vpx_parser_ &&
207  !vpx_parser_->Parse(sample->data(), sample->data_size(), &vpx_frames)) {
208  return Status(error::ENCRYPTION_FAILURE, "Failed to parse vpx frame.");
209  }
210 
211  // Need to setup the encryptor for new segments even if this segment does not
212  // need to be encrypted, so we can signal encryption metadata earlier to
213  // allows clients to prefetch the keys.
214  if (check_new_crypto_period_) {
215  const int64_t current_crypto_period_index =
216  sample->dts() / crypto_period_duration_;
217  if (current_crypto_period_index != prev_crypto_period_index_) {
218  EncryptionKey encryption_key;
219  Status status = key_source_->GetCryptoPeriodKey(
220  current_crypto_period_index, stream_label_, &encryption_key);
221  if (!status.ok())
222  return status;
223  if (!CreateEncryptor(encryption_key))
224  return Status(error::ENCRYPTION_FAILURE, "Failed to create encryptor");
225  }
226  check_new_crypto_period_ = false;
227  }
228 
229  if (remaining_clear_lead_ > 0)
230  return Status::OK;
231 
232  std::unique_ptr<DecryptConfig> decrypt_config(new DecryptConfig(
233  encryption_config_->key_id, encryptor_->iv(),
234  std::vector<SubsampleEntry>(), encryption_options_.protection_scheme,
235  crypt_byte_block_, skip_byte_block_));
236  bool result = true;
237  if (vpx_parser_) {
238  result = EncryptVpxFrame(vpx_frames, sample, decrypt_config.get());
239  if (result) {
240  DCHECK_EQ(decrypt_config->GetTotalSizeOfSubsamples(),
241  sample->data_size());
242  }
243  } else if (header_parser_) {
244  result = EncryptNalFrame(sample, decrypt_config.get());
245  if (result) {
246  DCHECK_EQ(decrypt_config->GetTotalSizeOfSubsamples(),
247  sample->data_size());
248  }
249  } else {
250  if (sample->data_size() > leading_clear_bytes_size_) {
251  EncryptBytes(sample->writable_data() + leading_clear_bytes_size_,
252  sample->data_size() - leading_clear_bytes_size_);
253  }
254  }
255  if (!result)
256  return Status(error::ENCRYPTION_FAILURE, "Failed to encrypt samples.");
257  sample->set_is_encrypted(true);
258  sample->set_decrypt_config(std::move(decrypt_config));
259  encryptor_->UpdateIv();
260  return Status::OK;
261 }
262 
263 Status EncryptionHandler::SetupProtectionPattern(StreamType stream_type) {
264  switch (encryption_options_.protection_scheme) {
265  case kAppleSampleAesProtectionScheme: {
266  const size_t kH264LeadingClearBytesSize = 32u;
267  const size_t kSmallNalUnitSize = 32u + 16u;
268  const size_t kAudioLeadingClearBytesSize = 16u;
269  switch (codec_) {
270  case kCodecH264:
271  // Apple Sample AES uses 1:9 pattern for video.
272  crypt_byte_block_ = 1u;
273  skip_byte_block_ = 9u;
274  leading_clear_bytes_size_ = kH264LeadingClearBytesSize;
275  min_protected_data_size_ = kSmallNalUnitSize + 1u;
276  break;
277  case kCodecAAC:
278  FALLTHROUGH_INTENDED;
279  case kCodecAC3:
280  // Audio is whole sample encrypted. We could not use a
281  // crypto_byte_block_ of 1 here as if there is one crypto block
282  // remaining, it need not be encrypted for video but it needs to be
283  // encrypted for audio.
284  crypt_byte_block_ = 0u;
285  skip_byte_block_ = 0u;
286  leading_clear_bytes_size_ = kAudioLeadingClearBytesSize;
287  min_protected_data_size_ = leading_clear_bytes_size_ + 1u;
288  break;
289  default:
290  return Status(error::ENCRYPTION_FAILURE,
291  "Only AAC/AC3 and H264 are supported in Sample AES.");
292  }
293  break;
294  }
295  case FOURCC_cbcs:
296  FALLTHROUGH_INTENDED;
297  case FOURCC_cens:
298  if (stream_type == kStreamVideo) {
299  // Use 1:9 pattern for video.
300  crypt_byte_block_ = 1u;
301  skip_byte_block_ = 9u;
302  } else {
303  // Tracks other than video are protected using whole-block full-sample
304  // encryption, which is essentially a pattern of 1:0. Note that this may
305  // not be the same as the non-pattern based encryption counterparts,
306  // e.g. in 'cens' for full sample encryption, the whole sample is
307  // encrypted up to the last 16-byte boundary, see 23001-7:2016(E) 9.7;
308  // while in 'cenc' for full sample encryption, the last partial 16-byte
309  // block is also encrypted, see 23001-7:2016(E) 9.4.2. Another
310  // difference is the use of constant iv.
311  crypt_byte_block_ = 1u;
312  skip_byte_block_ = 0u;
313  }
314  break;
315  default:
316  // Not using pattern encryption.
317  crypt_byte_block_ = 0u;
318  skip_byte_block_ = 0u;
319  }
320  return Status::OK;
321 }
322 
323 bool EncryptionHandler::CreateEncryptor(const EncryptionKey& encryption_key) {
324  std::unique_ptr<AesCryptor> encryptor;
325  switch (encryption_options_.protection_scheme) {
326  case FOURCC_cenc:
327  encryptor.reset(new AesCtrEncryptor);
328  break;
329  case FOURCC_cbc1:
330  encryptor.reset(new AesCbcEncryptor(kNoPadding));
331  break;
332  case FOURCC_cens:
333  encryptor.reset(new AesPatternCryptor(
334  crypt_byte_block_, skip_byte_block_,
336  AesCryptor::kDontUseConstantIv,
337  std::unique_ptr<AesCryptor>(new AesCtrEncryptor())));
338  break;
339  case FOURCC_cbcs:
340  encryptor.reset(new AesPatternCryptor(
341  crypt_byte_block_, skip_byte_block_,
343  AesCryptor::kUseConstantIv,
344  std::unique_ptr<AesCryptor>(new AesCbcEncryptor(kNoPadding))));
345  break;
346  case kAppleSampleAesProtectionScheme:
347  if (crypt_byte_block_ == 0 && skip_byte_block_ == 0) {
348  encryptor.reset(
349  new AesCbcEncryptor(kNoPadding, AesCryptor::kUseConstantIv));
350  } else {
351  encryptor.reset(new AesPatternCryptor(
352  crypt_byte_block_, skip_byte_block_,
354  AesCryptor::kUseConstantIv,
355  std::unique_ptr<AesCryptor>(new AesCbcEncryptor(kNoPadding))));
356  }
357  break;
358  default:
359  LOG(ERROR) << "Unsupported protection scheme.";
360  return false;
361  }
362 
363  std::vector<uint8_t> iv = encryption_key.iv;
364  if (iv.empty()) {
365  if (!AesCryptor::GenerateRandomIv(encryption_options_.protection_scheme,
366  &iv)) {
367  LOG(ERROR) << "Failed to generate random iv.";
368  return false;
369  }
370  }
371  const bool initialized =
372  encryptor->InitializeWithIv(encryption_key.key, iv);
373  encryptor_ = std::move(encryptor);
374 
375  encryption_config_.reset(new EncryptionConfig);
376  encryption_config_->protection_scheme = encryption_options_.protection_scheme;
377  encryption_config_->crypt_byte_block = crypt_byte_block_;
378  encryption_config_->skip_byte_block = skip_byte_block_;
379  if (encryptor_->use_constant_iv()) {
380  encryption_config_->per_sample_iv_size = 0;
381  encryption_config_->constant_iv = iv;
382  } else {
383  encryption_config_->per_sample_iv_size = static_cast<uint8_t>(iv.size());
384  }
385  encryption_config_->key_id = encryption_key.key_id;
386  encryption_config_->key_system_info = encryption_key.key_system_info;
387  return initialized;
388 }
389 
390 bool EncryptionHandler::EncryptVpxFrame(
391  const std::vector<VPxFrameInfo>& vpx_frames,
392  MediaSample* sample,
393  DecryptConfig* decrypt_config) {
394  uint8_t* data = sample->writable_data();
395  for (const VPxFrameInfo& frame : vpx_frames) {
396  uint16_t clear_bytes =
397  static_cast<uint16_t>(frame.uncompressed_header_size);
398  uint32_t cipher_bytes = static_cast<uint32_t>(
399  frame.frame_size - frame.uncompressed_header_size);
400 
401  // "VP Codec ISO Media File Format Binding" document requires that the
402  // encrypted bytes of each frame within the superframe must be block
403  // aligned so that the counter state can be computed for each frame
404  // within the superframe.
405  // ISO/IEC 23001-7:2016 10.2 'cbc1' 10.3 'cens'
406  // The BytesOfProtectedData size SHALL be a multiple of 16 bytes to
407  // avoid partial blocks in Subsamples.
408  // For consistency, apply block alignment to all frames.
409  const uint16_t misalign_bytes = cipher_bytes % kCencBlockSize;
410  clear_bytes += misalign_bytes;
411  cipher_bytes -= misalign_bytes;
412 
413  decrypt_config->AddSubsample(clear_bytes, cipher_bytes);
414  if (cipher_bytes > 0)
415  EncryptBytes(data + clear_bytes, cipher_bytes);
416  data += frame.frame_size;
417  }
418  // Add subsample for the superframe index if exists.
419  const bool is_superframe = vpx_frames.size() > 1;
420  if (is_superframe) {
421  size_t index_size = sample->data() + sample->data_size() - data;
422  DCHECK_LE(index_size, 2 + vpx_frames.size() * 4);
423  DCHECK_GE(index_size, 2 + vpx_frames.size() * 1);
424  uint16_t clear_bytes = static_cast<uint16_t>(index_size);
425  uint32_t cipher_bytes = 0;
426  decrypt_config->AddSubsample(clear_bytes, cipher_bytes);
427  }
428  return true;
429 }
430 
431 bool EncryptionHandler::EncryptNalFrame(MediaSample* sample,
432  DecryptConfig* decrypt_config) {
433  DCHECK_NE(nalu_length_size_, 0u);
434  DCHECK(header_parser_);
435  const Nalu::CodecType nalu_type =
436  (codec_ == kCodecH265) ? Nalu::kH265 : Nalu::kH264;
437  NaluReader reader(nalu_type, nalu_length_size_, sample->writable_data(),
438  sample->data_size());
439 
440  // Store the current length of clear data. This is used to squash
441  // multiple unencrypted NAL units into fewer subsample entries.
442  uint64_t accumulated_clear_bytes = 0;
443 
444  Nalu nalu;
445  NaluReader::Result result;
446  while ((result = reader.Advance(&nalu)) == NaluReader::kOk) {
447  const uint64_t nalu_total_size = nalu.header_size() + nalu.payload_size();
448  if (nalu.is_video_slice() && nalu_total_size >= min_protected_data_size_) {
449  uint64_t current_clear_bytes = leading_clear_bytes_size_;
450  if (current_clear_bytes == 0) {
451  // For video-slice NAL units, encrypt the video slice. This skips
452  // the frame header.
453  const int64_t video_slice_header_size =
454  header_parser_->GetHeaderSize(nalu);
455  if (video_slice_header_size < 0) {
456  LOG(ERROR) << "Failed to read slice header.";
457  return false;
458  }
459  current_clear_bytes = nalu.header_size() + video_slice_header_size;
460  }
461  uint64_t cipher_bytes = nalu_total_size - current_clear_bytes;
462 
463  // ISO/IEC 23001-7:2016 10.2 'cbc1' 10.3 'cens'
464  // The BytesOfProtectedData size SHALL be a multiple of 16 bytes to
465  // avoid partial blocks in Subsamples.
466  // CMAF requires 'cenc' scheme BytesOfProtectedData SHALL be a multiple
467  // of 16 bytes; while 'cbcs' scheme BytesOfProtectedData SHALL start on
468  // the first byte of video data following the slice header.
469  if (encryption_options_.protection_scheme == FOURCC_cbc1 ||
470  encryption_options_.protection_scheme == FOURCC_cens ||
471  encryption_options_.protection_scheme == FOURCC_cenc) {
472  const uint16_t misalign_bytes = cipher_bytes % kCencBlockSize;
473  current_clear_bytes += misalign_bytes;
474  cipher_bytes -= misalign_bytes;
475  }
476 
477  const uint8_t* nalu_data = nalu.data() + current_clear_bytes;
478  EncryptBytes(const_cast<uint8_t*>(nalu_data), cipher_bytes);
479 
480  AddSubsample(
481  accumulated_clear_bytes + nalu_length_size_ + current_clear_bytes,
482  cipher_bytes, decrypt_config);
483  accumulated_clear_bytes = 0;
484  } else {
485  // For non-video-slice or small NAL units, don't encrypt.
486  accumulated_clear_bytes += nalu_length_size_ + nalu_total_size;
487  }
488  }
489  if (result != NaluReader::kEOStream) {
490  LOG(ERROR) << "Failed to parse NAL units.";
491  return false;
492  }
493  AddSubsample(accumulated_clear_bytes, 0, decrypt_config);
494  return true;
495 }
496 
497 void EncryptionHandler::EncryptBytes(uint8_t* data, size_t size) {
498  DCHECK(encryptor_);
499  CHECK(encryptor_->Crypt(data, size, data));
500 }
501 
502 void EncryptionHandler::InjectVpxParserForTesting(
503  std::unique_ptr<VPxParser> vpx_parser) {
504  vpx_parser_ = std::move(vpx_parser);
505 }
506 
507 void EncryptionHandler::InjectVideoSliceHeaderParserForTesting(
508  std::unique_ptr<VideoSliceHeaderParser> header_parser) {
509  header_parser_ = std::move(header_parser);
510 }
511 
512 } // namespace media
513 } // namespace shaka
std::function< std::string(const EncryptionParams::EncryptedStreamAttributes &stream_attributes)> stream_label_func
Abstract class holds stream information.
Definition: stream_info.h:57
bool vp9_subsample_encryption
Enable/disable subsample encryption for VP9.
virtual Status GetCryptoPeriodKey(uint32_t crypto_period_index, const std::string &stream_label, EncryptionKey *key)=0
Status Dispatch(std::unique_ptr< StreamData > stream_data)
virtual Status GetKey(const std::string &stream_label, EncryptionKey *key)=0
Status Process(std::unique_ptr< StreamData > stream_data) override
static bool GenerateRandomIv(FourCC protection_scheme, std::vector< uint8_t > *iv)
Definition: aes_cryptor.cc:107
double clear_lead_in_seconds
Clear lead duration in seconds.
FourCC protection_scheme
The protection scheme: 'cenc', 'cens', 'cbc1', 'cbcs'.