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