Shaka Packager SDK
subsample_generator.cc
1 // Copyright 2018 Google LLC. 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/subsample_generator.h"
8 
9 #include <algorithm>
10 #include <limits>
11 
12 #include "packager/media/base/decrypt_config.h"
13 #include "packager/media/base/video_stream_info.h"
14 #include "packager/media/codecs/av1_parser.h"
15 #include "packager/media/codecs/video_slice_header_parser.h"
16 #include "packager/media/codecs/vp8_parser.h"
17 #include "packager/media/codecs/vp9_parser.h"
18 
19 namespace shaka {
20 namespace media {
21 namespace {
22 
23 const size_t kAesBlockSize = 16u;
24 
25 uint8_t GetNaluLengthSize(const StreamInfo& stream_info) {
26  if (stream_info.stream_type() != kStreamVideo)
27  return 0;
28 
29  const VideoStreamInfo& video_stream_info =
30  static_cast<const VideoStreamInfo&>(stream_info);
31  return video_stream_info.nalu_length_size();
32 }
33 
34 bool ShouldAlignProtectedData(Codec codec,
35  FourCC protection_scheme,
36  bool vp9_subsample_encryption) {
37  switch (codec) {
38  case kCodecAV1:
39  // Per AV1 in ISO-BMFF spec [1], BytesOfProtectedData SHALL be a multiple
40  // of 16 bytes.
41  // [1] https://aomediacodec.github.io/av1-isobmff/#subsample-encryption
42  return true;
43  case kCodecVP9:
44  // "VP Codec ISO Media File Format Binding" document requires that the
45  // encrypted bytes of each frame within the superframe must be block
46  // aligned so that the counter state can be computed for each frame
47  // within the superframe.
48  // ISO/IEC 23001-7:2016 10.2 'cbc1' 10.3 'cens'
49  // The BytesOfProtectedData size SHALL be a multiple of 16 bytes to
50  // avoid partial blocks in Subsamples.
51  // For consistency, apply block alignment to all frames when VP9 subsample
52  // encryption is enabled.
53  return vp9_subsample_encryption;
54  default:
55  // ISO/IEC 23001-7:2016 10.2 'cbc1' 10.3 'cens'
56  // The BytesOfProtectedData size SHALL be a multiple of 16 bytes to avoid
57  // partial blocks in Subsamples.
58  // CMAF requires 'cenc' scheme BytesOfProtectedData SHALL be a multiple of
59  // 16 bytes; while 'cbcs' scheme BytesOfProtectedData SHALL start on the
60  // first byte of video data following the slice header.
61  return protection_scheme == FOURCC_cbc1 ||
62  protection_scheme == FOURCC_cens ||
63  protection_scheme == FOURCC_cenc;
64  }
65 }
66 
67 // A convenient util class to organize subsamples, e.g. combine consecutive
68 // subsamples with only clear bytes, split subsamples if the clear bytes exceeds
69 // 2^16 etc.
70 class SubsampleOrganizer {
71  public:
72  SubsampleOrganizer(bool align_protected_data,
73  std::vector<SubsampleEntry>* subsamples)
74  : align_protected_data_(align_protected_data), subsamples_(subsamples) {}
75 
76  ~SubsampleOrganizer() {
77  if (accumulated_clear_bytes_ > 0) {
78  PushSubsample(accumulated_clear_bytes_, 0);
79  accumulated_clear_bytes_ = 0;
80  }
81  }
82 
83  void AddSubsample(size_t clear_bytes, size_t cipher_bytes) {
84  DCHECK_LT(clear_bytes, std::numeric_limits<uint32_t>::max());
85  DCHECK_LT(cipher_bytes, std::numeric_limits<uint32_t>::max());
86 
87  if (align_protected_data_ && cipher_bytes != 0) {
88  const size_t misalign_bytes = cipher_bytes % kAesBlockSize;
89  clear_bytes += misalign_bytes;
90  cipher_bytes -= misalign_bytes;
91  }
92 
93  accumulated_clear_bytes_ += clear_bytes;
94  // Accumulated clear bytes are handled later.
95  if (cipher_bytes == 0)
96  return;
97 
98  PushSubsample(accumulated_clear_bytes_, cipher_bytes);
99  accumulated_clear_bytes_ = 0;
100  }
101 
102  private:
103  SubsampleOrganizer(const SubsampleOrganizer&) = delete;
104  SubsampleOrganizer& operator=(const SubsampleOrganizer&) = delete;
105 
106  void PushSubsample(size_t clear_bytes, size_t cipher_bytes) {
107  const uint16_t kUInt16Max = std::numeric_limits<uint16_t>::max();
108  while (clear_bytes > kUInt16Max) {
109  subsamples_->emplace_back(kUInt16Max, 0);
110  clear_bytes -= kUInt16Max;
111  }
112  subsamples_->emplace_back(static_cast<uint16_t>(clear_bytes),
113  static_cast<uint32_t>(cipher_bytes));
114  }
115 
116  const bool align_protected_data_ = false;
117  std::vector<SubsampleEntry>* const subsamples_ = nullptr;
118  size_t accumulated_clear_bytes_ = 0;
119 };
120 
121 } // namespace
122 
123 SubsampleGenerator::SubsampleGenerator(bool vp9_subsample_encryption)
124  : vp9_subsample_encryption_(vp9_subsample_encryption) {}
125 
126 SubsampleGenerator::~SubsampleGenerator() {}
127 
128 Status SubsampleGenerator::Initialize(FourCC protection_scheme,
129  const StreamInfo& stream_info) {
130  codec_ = stream_info.codec();
131  nalu_length_size_ = GetNaluLengthSize(stream_info);
132 
133  switch (codec_) {
134  case kCodecAV1:
135  av1_parser_.reset(new AV1Parser);
136  break;
137  case kCodecVP9:
138  if (vp9_subsample_encryption_)
139  vpx_parser_.reset(new VP9Parser);
140  break;
141  case kCodecH264:
142  header_parser_.reset(new H264VideoSliceHeaderParser);
143  break;
144  case kCodecH265:
145  header_parser_.reset(new H265VideoSliceHeaderParser);
146  break;
147  default:
148  // Other codecs should have nalu length size == 0.
149  if (nalu_length_size_ > 0) {
150  LOG(WARNING) << "Unknown video codec '" << codec_ << "'";
151  return Status(error::ENCRYPTION_FAILURE, "Unknown video codec.");
152  }
153  }
154  if (av1_parser_) {
155  // Parse configOBUs in AV1CodecConfigurationRecord if exists.
156  // https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax.
157  const size_t kConfigOBUsOffset = 4;
158  const bool has_config_obus =
159  stream_info.codec_config().size() > kConfigOBUsOffset;
160  std::vector<AV1Parser::Tile> tiles;
161  if (has_config_obus &&
162  !av1_parser_->Parse(
163  &stream_info.codec_config()[kConfigOBUsOffset],
164  stream_info.codec_config().size() - kConfigOBUsOffset, &tiles)) {
165  return Status(
166  error::ENCRYPTION_FAILURE,
167  "Failed to parse configOBUs in AV1CodecConfigurationRecord.");
168  }
169  DCHECK(tiles.empty());
170  }
171  if (header_parser_) {
172  CHECK_NE(nalu_length_size_, 0u) << "AnnexB stream is not supported yet";
173  if (!header_parser_->Initialize(stream_info.codec_config())) {
174  return Status(error::ENCRYPTION_FAILURE,
175  "Failed to read SPS and PPS data.");
176  }
177  }
178 
179  align_protected_data_ = ShouldAlignProtectedData(codec_, protection_scheme,
180  vp9_subsample_encryption_);
181 
182  if (protection_scheme == kAppleSampleAesProtectionScheme) {
183  const size_t kH264LeadingClearBytesSize = 32u;
184  const size_t kAudioLeadingClearBytesSize = 16u;
185  switch (codec_) {
186  case kCodecH264:
187  leading_clear_bytes_size_ = kH264LeadingClearBytesSize;
188  min_protected_data_size_ =
189  leading_clear_bytes_size_ + kAesBlockSize + 1u;
190  break;
191  case kCodecAAC:
192  FALLTHROUGH_INTENDED;
193  case kCodecAC3:
194  leading_clear_bytes_size_ = kAudioLeadingClearBytesSize;
195  min_protected_data_size_ = leading_clear_bytes_size_ + kAesBlockSize;
196  break;
197  case kCodecEAC3:
198  // E-AC3 encryption is handled by SampleAesEc3Cryptor, which also
199  // manages leading clear bytes.
200  leading_clear_bytes_size_ = 0;
201  min_protected_data_size_ = leading_clear_bytes_size_ + kAesBlockSize;
202  break;
203  default:
204  LOG(ERROR) << "Unexpected codec for SAMPLE-AES " << codec_;
205  return Status(error::ENCRYPTION_FAILURE,
206  "Unexpected codec for SAMPLE-AES.");
207  }
208  }
209  return Status::OK;
210 }
211 
213  const uint8_t* frame,
214  size_t frame_size,
215  std::vector<SubsampleEntry>* subsamples) {
216  subsamples->clear();
217  switch (codec_) {
218  case kCodecAV1:
219  return GenerateSubsamplesFromAV1Frame(frame, frame_size, subsamples);
220  case kCodecH264:
221  FALLTHROUGH_INTENDED;
222  case kCodecH265:
223  return GenerateSubsamplesFromH26xFrame(frame, frame_size, subsamples);
224  case kCodecVP9:
225  if (vp9_subsample_encryption_)
226  return GenerateSubsamplesFromVPxFrame(frame, frame_size, subsamples);
227  // Full sample encrypted so no subsamples.
228  break;
229  default:
230  // Other codecs are full sample encrypted unless there are clear leading
231  // bytes.
232  if (leading_clear_bytes_size_ > 0) {
233  SubsampleOrganizer subsample_organizer(align_protected_data_,
234  subsamples);
235  const size_t clear_bytes =
236  std::min(frame_size, leading_clear_bytes_size_);
237  const size_t cipher_bytes = frame_size - clear_bytes;
238  subsample_organizer.AddSubsample(clear_bytes, cipher_bytes);
239  } else {
240  // Full sample encrypted so no subsamples.
241  }
242  break;
243  }
244  return Status::OK;
245 }
246 
247 void SubsampleGenerator::InjectVpxParserForTesting(
248  std::unique_ptr<VPxParser> vpx_parser) {
249  vpx_parser_ = std::move(vpx_parser);
250 }
251 
252 void SubsampleGenerator::InjectVideoSliceHeaderParserForTesting(
253  std::unique_ptr<VideoSliceHeaderParser> header_parser) {
254  header_parser_ = std::move(header_parser);
255 }
256 
257 void SubsampleGenerator::InjectAV1ParserForTesting(
258  std::unique_ptr<AV1Parser> av1_parser) {
259  av1_parser_ = std::move(av1_parser);
260 }
261 
262 Status SubsampleGenerator::GenerateSubsamplesFromVPxFrame(
263  const uint8_t* frame,
264  size_t frame_size,
265  std::vector<SubsampleEntry>* subsamples) {
266  DCHECK(vpx_parser_);
267  std::vector<VPxFrameInfo> vpx_frames;
268  if (!vpx_parser_->Parse(frame, frame_size, &vpx_frames))
269  return Status(error::ENCRYPTION_FAILURE, "Failed to parse vpx frame.");
270 
271  SubsampleOrganizer subsample_organizer(align_protected_data_, subsamples);
272 
273  size_t total_size = 0;
274  for (const VPxFrameInfo& frame : vpx_frames) {
275  subsample_organizer.AddSubsample(
276  frame.uncompressed_header_size,
277  frame.frame_size - frame.uncompressed_header_size);
278  total_size += frame.frame_size;
279  }
280  // Add subsample for the superframe index if exists.
281  const bool is_superframe = vpx_frames.size() > 1;
282  if (is_superframe) {
283  const size_t index_size = frame_size - total_size;
284  DCHECK_LE(index_size, 2 + vpx_frames.size() * 4);
285  DCHECK_GE(index_size, 2 + vpx_frames.size() * 1);
286  subsample_organizer.AddSubsample(index_size, 0);
287  } else {
288  DCHECK_EQ(total_size, frame_size);
289  }
290  return Status::OK;
291 }
292 
293 Status SubsampleGenerator::GenerateSubsamplesFromH26xFrame(
294  const uint8_t* frame,
295  size_t frame_size,
296  std::vector<SubsampleEntry>* subsamples) {
297  DCHECK_NE(nalu_length_size_, 0u);
298  DCHECK(header_parser_);
299 
300  SubsampleOrganizer subsample_organizer(align_protected_data_, subsamples);
301 
302  const Nalu::CodecType nalu_type =
303  (codec_ == kCodecH265) ? Nalu::kH265 : Nalu::kH264;
304  NaluReader reader(nalu_type, nalu_length_size_, frame, frame_size);
305 
306  Nalu nalu;
307  NaluReader::Result result;
308  while ((result = reader.Advance(&nalu)) == NaluReader::kOk) {
309  const size_t nalu_total_size = nalu.header_size() + nalu.payload_size();
310  size_t clear_bytes = 0;
311  if (nalu.is_video_slice() && nalu_total_size >= min_protected_data_size_) {
312  clear_bytes = leading_clear_bytes_size_;
313  if (clear_bytes == 0) {
314  // For video-slice NAL units, encrypt the video slice. This skips
315  // the frame header.
316  const int64_t video_slice_header_size =
317  header_parser_->GetHeaderSize(nalu);
318  if (video_slice_header_size < 0) {
319  LOG(ERROR) << "Failed to read slice header.";
320  return Status(error::ENCRYPTION_FAILURE,
321  "Failed to read slice header.");
322  }
323  clear_bytes = nalu.header_size() + video_slice_header_size;
324  }
325  } else {
326  // For non-video-slice or small NAL units, don't encrypt.
327  clear_bytes = nalu_total_size;
328  }
329  const size_t cipher_bytes = nalu_total_size - clear_bytes;
330  subsample_organizer.AddSubsample(nalu_length_size_ + clear_bytes,
331  cipher_bytes);
332  }
333  if (result != NaluReader::kEOStream) {
334  LOG(ERROR) << "Failed to parse NAL units.";
335  return Status(error::ENCRYPTION_FAILURE, "Failed to parse NAL units.");
336  }
337  return Status::OK;
338 }
339 
340 Status SubsampleGenerator::GenerateSubsamplesFromAV1Frame(
341  const uint8_t* frame,
342  size_t frame_size,
343  std::vector<SubsampleEntry>* subsamples) {
344  DCHECK(av1_parser_);
345  std::vector<AV1Parser::Tile> av1_tiles;
346  if (!av1_parser_->Parse(frame, frame_size, &av1_tiles))
347  return Status(error::ENCRYPTION_FAILURE, "Failed to parse AV1 frame.");
348 
349  SubsampleOrganizer subsample_organizer(align_protected_data_, subsamples);
350 
351  size_t last_tile_end_offset = 0;
352  for (const AV1Parser::Tile& tile : av1_tiles) {
353  DCHECK_LE(last_tile_end_offset, tile.start_offset_in_bytes);
354  // Per AV1 in ISO-BMFF spec [1], only decode_tile is encrypted.
355  // [1] https://aomediacodec.github.io/av1-isobmff/#subsample-encryption
356  subsample_organizer.AddSubsample(
357  tile.start_offset_in_bytes - last_tile_end_offset, tile.size_in_bytes);
358  last_tile_end_offset = tile.start_offset_in_bytes + tile.size_in_bytes;
359  }
360  DCHECK_LE(last_tile_end_offset, frame_size);
361  if (last_tile_end_offset < frame_size)
362  subsample_organizer.AddSubsample(frame_size - last_tile_end_offset, 0);
363  return Status::OK;
364 }
365 
366 } // namespace media
367 } // namespace shaka
Abstract class holds stream information.
Definition: stream_info.h:61
bool is_video_slice() const
Slice data partition NALs are not considered as slice NALs.
Definition: nalu_reader.h:117
All the methods that are virtual are virtual for mocking.
uint64_t header_size() const
The size of the header, e.g. 1 for H.264.
Definition: nalu_reader.h:100
virtual Status GenerateSubsamples(const uint8_t *frame, size_t frame_size, std::vector< SubsampleEntry > *subsamples)
Result Advance(Nalu *nalu)
Definition: nalu_reader.cc:239
Class to parse a vp9 bit stream.
Definition: vp9_parser.h:20
SubsampleGenerator(bool vp9_subsample_encryption)
virtual Status Initialize(FourCC protection_scheme, const StreamInfo &stream_info)
uint64_t payload_size() const
Size of this Nalu minus header_size().
Definition: nalu_reader.h:102