7 #include "packager/media/crypto/encryption_handler.h"
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"
27 const size_t kCencBlockSize = 16u;
30 const uint8_t kKeyRotationDefaultKeyId[] = {
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
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;
46 if (clear_bytes > 0 || cipher_bytes > 0)
47 decrypt_config->AddSubsample(clear_bytes, cipher_bytes);
50 uint8_t GetNaluLengthSize(
const StreamInfo& stream_info) {
51 if (stream_info.stream_type() != kStreamVideo)
54 const VideoStreamInfo& video_stream_info =
55 static_cast<const VideoStreamInfo&
>(stream_info);
56 return video_stream_info.nalu_length_size();
60 KeySource::TrackType ToTrackType(
const std::string& track_type) {
61 if (track_type ==
"SD")
62 return KeySource::TRACK_TYPE_SD;
63 if (track_type ==
"HD")
64 return KeySource::TRACK_TYPE_HD;
65 if (track_type ==
"AUDIO")
66 return KeySource::TRACK_TYPE_AUDIO;
67 return KeySource::TRACK_TYPE_SD;
70 KeySource::TrackType GetTrackTypeForEncryption(
71 const StreamInfo& stream_info,
72 const std::function<std::string(
73 const EncryptionParams::EncryptedStreamAttributes& stream_attributes)>&
75 EncryptionParams::EncryptedStreamAttributes stream_attributes;
76 if (stream_info.stream_type() == kStreamAudio) {
77 stream_attributes.stream_type =
78 EncryptionParams::EncryptedStreamAttributes::kAudio;
79 }
else if (stream_info.stream_type() == kStreamVideo) {
80 const VideoStreamInfo& video_stream_info =
81 static_cast<const VideoStreamInfo&
>(stream_info);
82 stream_attributes.stream_type =
83 EncryptionParams::EncryptedStreamAttributes::kVideo;
84 stream_attributes.oneof.video.width = video_stream_info.width();
85 stream_attributes.oneof.video.height = video_stream_info.height();
87 return ToTrackType(stream_label_func(stream_attributes));
91 EncryptionHandler::EncryptionHandler(
92 const EncryptionOptions& encryption_options,
93 KeySource* key_source)
94 : encryption_options_(encryption_options), key_source_(key_source) {}
96 EncryptionHandler::~EncryptionHandler() {}
100 return Status(error::INVALID_ARGUMENT,
"Stream label function not set.");
102 if (num_input_streams() != 1 || next_output_stream_index() != 1) {
103 return Status(error::INVALID_ARGUMENT,
104 "Expects exactly one input and output.");
111 switch (stream_data->stream_data_type) {
112 case StreamDataType::kStreamInfo:
113 status = ProcessStreamInfo(stream_data->stream_info.get());
115 case StreamDataType::kSegmentInfo: {
116 SegmentInfo* segment_info = stream_data->segment_info.get();
117 segment_info->is_encrypted = remaining_clear_lead_ <= 0;
119 const bool key_rotation_enabled = crypto_period_duration_ != 0;
120 if (key_rotation_enabled)
121 segment_info->key_rotation_encryption_config = encryption_config_;
122 if (!segment_info->is_subsegment) {
123 if (key_rotation_enabled)
124 check_new_crypto_period_ =
true;
125 if (remaining_clear_lead_ > 0)
126 remaining_clear_lead_ -= segment_info->duration;
130 case StreamDataType::kMediaSample:
131 status = ProcessMediaSample(stream_data->media_sample.get());
134 VLOG(3) <<
"Stream data type "
135 <<
static_cast<int>(stream_data->stream_data_type) <<
" ignored.";
138 return status.ok() ?
Dispatch(std::move(stream_data)) : status;
142 if (stream_info->is_encrypted()) {
143 return Status(error::INVALID_ARGUMENT,
144 "Input stream is already encrypted.");
147 remaining_clear_lead_ =
149 crypto_period_duration_ =
151 stream_info->time_scale();
152 codec_ = stream_info->codec();
153 nalu_length_size_ = GetNaluLengthSize(*stream_info);
154 track_type_ = GetTrackTypeForEncryption(
159 vpx_parser_.reset(
new VP9Parser);
162 header_parser_.reset(
new H264VideoSliceHeaderParser);
165 header_parser_.reset(
new H265VideoSliceHeaderParser);
169 if (nalu_length_size_ > 0) {
170 LOG(WARNING) <<
"Unknown video codec '" << codec_ <<
"'";
171 return Status(error::ENCRYPTION_FAILURE,
"Unknown video codec.");
174 if (header_parser_) {
175 CHECK_NE(nalu_length_size_, 0u) <<
"AnnexB stream is not supported yet";
176 if (!header_parser_->Initialize(stream_info->codec_config())) {
177 return Status(error::ENCRYPTION_FAILURE,
178 "Fail to read SPS and PPS data.");
182 Status status = SetupProtectionPattern(stream_info->stream_type());
186 EncryptionKey encryption_key;
187 const bool key_rotation_enabled = crypto_period_duration_ != 0;
188 if (key_rotation_enabled) {
189 check_new_crypto_period_ =
true;
191 encryption_key.key_id.assign(
192 kKeyRotationDefaultKeyId,
193 kKeyRotationDefaultKeyId +
sizeof(kKeyRotationDefaultKeyId));
196 encryption_key.key = encryption_key.key_id;
198 status = key_source_->
GetKey(track_type_, &encryption_key);
202 if (!CreateEncryptor(encryption_key))
203 return Status(error::ENCRYPTION_FAILURE,
"Failed to create encryptor");
205 stream_info->set_is_encrypted(
true);
208 stream_info->set_encryption_config(*encryption_config_);
212 Status EncryptionHandler::ProcessMediaSample(MediaSample* sample) {
216 std::vector<VPxFrameInfo> vpx_frames;
218 !vpx_parser_->Parse(sample->data(), sample->data_size(), &vpx_frames)) {
219 return Status(error::ENCRYPTION_FAILURE,
"Failed to parse vpx frame.");
225 if (check_new_crypto_period_) {
226 const int64_t current_crypto_period_index =
227 sample->dts() / crypto_period_duration_;
228 if (current_crypto_period_index != prev_crypto_period_index_) {
229 EncryptionKey encryption_key;
231 current_crypto_period_index, track_type_, &encryption_key);
234 if (!CreateEncryptor(encryption_key))
235 return Status(error::ENCRYPTION_FAILURE,
"Failed to create encryptor");
237 check_new_crypto_period_ =
false;
240 if (remaining_clear_lead_ > 0)
243 std::unique_ptr<DecryptConfig> decrypt_config(
new DecryptConfig(
244 encryption_config_->key_id, encryptor_->iv(),
246 crypt_byte_block_, skip_byte_block_));
249 result = EncryptVpxFrame(vpx_frames, sample, decrypt_config.get());
251 DCHECK_EQ(decrypt_config->GetTotalSizeOfSubsamples(),
252 sample->data_size());
254 }
else if (header_parser_) {
255 result = EncryptNalFrame(sample, decrypt_config.get());
257 DCHECK_EQ(decrypt_config->GetTotalSizeOfSubsamples(),
258 sample->data_size());
261 if (sample->data_size() > leading_clear_bytes_size_) {
262 EncryptBytes(sample->writable_data() + leading_clear_bytes_size_,
263 sample->data_size() - leading_clear_bytes_size_);
267 return Status(error::ENCRYPTION_FAILURE,
"Failed to encrypt samples.");
268 sample->set_is_encrypted(
true);
269 sample->set_decrypt_config(std::move(decrypt_config));
270 encryptor_->UpdateIv();
274 Status EncryptionHandler::SetupProtectionPattern(StreamType stream_type) {
276 case kAppleSampleAesProtectionScheme: {
277 const size_t kH264LeadingClearBytesSize = 32u;
278 const size_t kSmallNalUnitSize = 32u + 16u;
279 const size_t kAudioLeadingClearBytesSize = 16u;
283 crypt_byte_block_ = 1u;
284 skip_byte_block_ = 9u;
285 leading_clear_bytes_size_ = kH264LeadingClearBytesSize;
286 min_protected_data_size_ = kSmallNalUnitSize + 1u;
289 FALLTHROUGH_INTENDED;
295 crypt_byte_block_ = 0u;
296 skip_byte_block_ = 0u;
297 leading_clear_bytes_size_ = kAudioLeadingClearBytesSize;
298 min_protected_data_size_ = leading_clear_bytes_size_ + 1u;
301 return Status(error::ENCRYPTION_FAILURE,
302 "Only AAC/AC3 and H264 are supported in Sample AES.");
307 FALLTHROUGH_INTENDED;
309 if (stream_type == kStreamVideo) {
311 crypt_byte_block_ = 1u;
312 skip_byte_block_ = 9u;
322 crypt_byte_block_ = 1u;
323 skip_byte_block_ = 0u;
328 crypt_byte_block_ = 0u;
329 skip_byte_block_ = 0u;
334 bool EncryptionHandler::CreateEncryptor(
const EncryptionKey& encryption_key) {
335 std::unique_ptr<AesCryptor> encryptor;
338 encryptor.reset(
new AesCtrEncryptor);
341 encryptor.reset(
new AesCbcEncryptor(kNoPadding));
344 encryptor.reset(
new AesPatternCryptor(
345 crypt_byte_block_, skip_byte_block_,
347 AesCryptor::kDontUseConstantIv,
348 std::unique_ptr<AesCryptor>(
new AesCtrEncryptor())));
351 encryptor.reset(
new AesPatternCryptor(
352 crypt_byte_block_, skip_byte_block_,
354 AesCryptor::kUseConstantIv,
355 std::unique_ptr<AesCryptor>(
new AesCbcEncryptor(kNoPadding))));
357 case kAppleSampleAesProtectionScheme:
358 if (crypt_byte_block_ == 0 && skip_byte_block_ == 0) {
360 new AesCbcEncryptor(kNoPadding, AesCryptor::kUseConstantIv));
362 encryptor.reset(
new AesPatternCryptor(
363 crypt_byte_block_, skip_byte_block_,
365 AesCryptor::kUseConstantIv,
366 std::unique_ptr<AesCryptor>(
new AesCbcEncryptor(kNoPadding))));
370 LOG(ERROR) <<
"Unsupported protection scheme.";
374 std::vector<uint8_t> iv = encryption_key.iv;
378 LOG(ERROR) <<
"Failed to generate random iv.";
382 const bool initialized =
383 encryptor->InitializeWithIv(encryption_key.key, iv);
384 encryptor_ = std::move(encryptor);
386 encryption_config_.reset(
new EncryptionConfig);
388 encryption_config_->crypt_byte_block = crypt_byte_block_;
389 encryption_config_->skip_byte_block = skip_byte_block_;
390 if (encryptor_->use_constant_iv()) {
391 encryption_config_->per_sample_iv_size = 0;
392 encryption_config_->constant_iv = iv;
394 encryption_config_->per_sample_iv_size =
static_cast<uint8_t
>(iv.size());
396 encryption_config_->key_id = encryption_key.key_id;
397 encryption_config_->key_system_info = encryption_key.key_system_info;
401 bool EncryptionHandler::EncryptVpxFrame(
402 const std::vector<VPxFrameInfo>& vpx_frames,
404 DecryptConfig* decrypt_config) {
405 uint8_t* data = sample->writable_data();
406 for (
const VPxFrameInfo& frame : vpx_frames) {
407 uint16_t clear_bytes =
408 static_cast<uint16_t
>(frame.uncompressed_header_size);
409 uint32_t cipher_bytes =
static_cast<uint32_t
>(
410 frame.frame_size - frame.uncompressed_header_size);
420 const uint16_t misalign_bytes = cipher_bytes % kCencBlockSize;
421 clear_bytes += misalign_bytes;
422 cipher_bytes -= misalign_bytes;
424 decrypt_config->AddSubsample(clear_bytes, cipher_bytes);
425 if (cipher_bytes > 0)
426 EncryptBytes(data + clear_bytes, cipher_bytes);
427 data += frame.frame_size;
430 const bool is_superframe = vpx_frames.size() > 1;
432 size_t index_size = sample->data() + sample->data_size() - data;
433 DCHECK_LE(index_size, 2 + vpx_frames.size() * 4);
434 DCHECK_GE(index_size, 2 + vpx_frames.size() * 1);
435 uint16_t clear_bytes =
static_cast<uint16_t
>(index_size);
436 uint32_t cipher_bytes = 0;
437 decrypt_config->AddSubsample(clear_bytes, cipher_bytes);
442 bool EncryptionHandler::EncryptNalFrame(MediaSample* sample,
443 DecryptConfig* decrypt_config) {
444 DCHECK_NE(nalu_length_size_, 0u);
445 DCHECK(header_parser_);
446 const Nalu::CodecType nalu_type =
447 (codec_ == kCodecH265) ? Nalu::kH265 : Nalu::kH264;
448 NaluReader reader(nalu_type, nalu_length_size_, sample->writable_data(),
449 sample->data_size());
453 uint64_t accumulated_clear_bytes = 0;
456 NaluReader::Result result;
457 while ((result = reader.Advance(&nalu)) == NaluReader::kOk) {
458 const uint64_t nalu_total_size = nalu.header_size() + nalu.payload_size();
459 if (nalu.is_video_slice() && nalu_total_size >= min_protected_data_size_) {
460 uint64_t current_clear_bytes = leading_clear_bytes_size_;
461 if (current_clear_bytes == 0) {
464 const int64_t video_slice_header_size =
465 header_parser_->GetHeaderSize(nalu);
466 if (video_slice_header_size < 0) {
467 LOG(ERROR) <<
"Failed to read slice header.";
470 current_clear_bytes = nalu.header_size() + video_slice_header_size;
472 uint64_t cipher_bytes = nalu_total_size - current_clear_bytes;
483 const uint16_t misalign_bytes = cipher_bytes % kCencBlockSize;
484 current_clear_bytes += misalign_bytes;
485 cipher_bytes -= misalign_bytes;
488 const uint8_t* nalu_data = nalu.data() + current_clear_bytes;
489 EncryptBytes(const_cast<uint8_t*>(nalu_data), cipher_bytes);
492 accumulated_clear_bytes + nalu_length_size_ + current_clear_bytes,
493 cipher_bytes, decrypt_config);
494 accumulated_clear_bytes = 0;
497 accumulated_clear_bytes += nalu_length_size_ + nalu_total_size;
500 if (result != NaluReader::kEOStream) {
501 LOG(ERROR) <<
"Failed to parse NAL units.";
504 AddSubsample(accumulated_clear_bytes, 0, decrypt_config);
508 void EncryptionHandler::EncryptBytes(uint8_t* data,
size_t size) {
510 CHECK(encryptor_->Crypt(data, size, data));
513 void EncryptionHandler::InjectVpxParserForTesting(
514 std::unique_ptr<VPxParser> vpx_parser) {
515 vpx_parser_ = std::move(vpx_parser);
518 void EncryptionHandler::InjectVideoSliceHeaderParserForTesting(
519 std::unique_ptr<VideoSliceHeaderParser> header_parser) {
520 header_parser_ = std::move(header_parser);