DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs 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/buffer_reader.h"
13 #include "packager/media/base/key_source.h"
14 #include "packager/media/base/media_sample.h"
15 #include "packager/media/filters/nalu_reader.h"
16 #include "packager/media/filters/vp8_parser.h"
17 #include "packager/media/filters/vp9_parser.h"
18 #include "packager/media/formats/mp4/box_definitions.h"
19 
20 namespace edash_packager {
21 namespace media {
22 namespace mp4 {
23 
24 namespace {
25 // Generate 64bit IV by default.
26 const size_t kDefaultIvSize = 8u;
27 const size_t kCencBlockSize = 16u;
28 
29 // Adds one or more subsamples to |*subsamples|. This may add more than one
30 // if one of the values overflows the integer in the subsample.
31 void AddSubsamples(uint64_t clear_bytes,
32  uint64_t cipher_bytes,
33  std::vector<SubsampleEntry>* subsamples) {
34  CHECK_LT(cipher_bytes, std::numeric_limits<uint32_t>::max());
35  const uint64_t kUInt16Max = std::numeric_limits<uint16_t>::max();
36  while (clear_bytes > kUInt16Max) {
37  subsamples->push_back(SubsampleEntry(kUInt16Max, 0));
38  clear_bytes -= kUInt16Max;
39  }
40 
41  if (clear_bytes > 0 || cipher_bytes > 0)
42  subsamples->push_back(SubsampleEntry(clear_bytes, cipher_bytes));
43 }
44 
45 VideoCodec GetVideoCodec(const StreamInfo& stream_info) {
46  if (stream_info.stream_type() != kStreamVideo)
47  return kUnknownVideoCodec;
48  const VideoStreamInfo& video_stream_info =
49  static_cast<const VideoStreamInfo&>(stream_info);
50  return video_stream_info.codec();
51 }
52 
53 uint8_t GetNaluLengthSize(const StreamInfo& stream_info) {
54  if (stream_info.stream_type() != kStreamVideo)
55  return 0;
56 
57  const VideoStreamInfo& video_stream_info =
58  static_cast<const VideoStreamInfo&>(stream_info);
59  return video_stream_info.nalu_length_size();
60 }
61 } // namespace
62 
64  scoped_refptr<StreamInfo> info,
65  TrackFragment* traf,
66  scoped_ptr<EncryptionKey> encryption_key,
67  int64_t clear_time)
68  : Fragmenter(traf),
69  info_(info),
70  encryption_key_(encryption_key.Pass()),
71  nalu_length_size_(GetNaluLengthSize(*info)),
72  clear_time_(clear_time) {
73  DCHECK(encryption_key_);
74  VideoCodec video_codec = GetVideoCodec(*info);
75  if (video_codec == kCodecVP8) {
76  vpx_parser_.reset(new VP8Parser);
77  } else if (video_codec == kCodecVP9) {
78  vpx_parser_.reset(new VP9Parser);
79  } else if (video_codec == kCodecH264) {
80  header_parser_.reset(new H264VideoSliceHeaderParser);
81  }
82  // TODO(modmaker): Support H.265.
83 }
84 
85 EncryptingFragmenter::~EncryptingFragmenter() {}
86 
87 Status EncryptingFragmenter::AddSample(scoped_refptr<MediaSample> sample) {
88  DCHECK(sample);
89  if (!fragment_initialized()) {
90  Status status = InitializeFragment(sample->dts());
91  if (!status.ok())
92  return status;
93  }
94  if (encryptor_) {
95  Status status = EncryptSample(sample);
96  if (!status.ok())
97  return status;
98  }
99  return Fragmenter::AddSample(sample);
100 }
101 
103  Status status = Fragmenter::InitializeFragment(first_sample_dts);
104  if (!status.ok())
105  return status;
106 
107  if (header_parser_ && !header_parser_->Initialize(info_->extra_data()))
108  return Status(error::MUXER_FAILURE, "Fail to read SPS and PPS data.");
109 
110  traf()->auxiliary_size.sample_info_sizes.clear();
111  traf()->auxiliary_offset.offsets.clear();
112  if (IsSubsampleEncryptionRequired()) {
113  traf()->sample_encryption.flags |=
114  SampleEncryption::kUseSubsampleEncryption;
115  }
116  traf()->sample_encryption.sample_encryption_entries.clear();
117 
118  const bool enable_encryption = clear_time_ <= 0;
119  if (!enable_encryption) {
120  // This fragment should be in clear text.
121  // At most two sample description entries, an encrypted entry and a clear
122  // entry, are generated. The 1-based clear entry index is always 2.
123  const uint32_t kClearSampleDescriptionIndex = 2;
124 
125  traf()->header.flags |=
126  TrackFragmentHeader::kSampleDescriptionIndexPresentMask;
127  traf()->header.sample_description_index = kClearSampleDescriptionIndex;
128  }
129  return PrepareFragmentForEncryption(enable_encryption);
130 }
131 
133  if (encryptor_) {
134  DCHECK_LE(clear_time_, 0);
136  } else {
137  DCHECK_GT(clear_time_, 0);
138  clear_time_ -= fragment_duration();
139  }
141 }
142 
144  bool enable_encryption) {
145  return (!enable_encryption || encryptor_) ? Status::OK : CreateEncryptor();
146 }
147 
149  // The offset will be adjusted in Segmenter after knowing moof size.
150  traf()->auxiliary_offset.offsets.push_back(0);
151 
152  // Optimize saiz box.
153  SampleAuxiliaryInformationSize& saiz = traf()->auxiliary_size;
154  saiz.sample_count = traf()->runs[0].sample_sizes.size();
155  if (!saiz.sample_info_sizes.empty()) {
156  if (!OptimizeSampleEntries(&saiz.sample_info_sizes,
157  &saiz.default_sample_info_size)) {
158  saiz.default_sample_info_size = 0;
159  }
160  } else {
161  // |sample_info_sizes| table is filled in only for subsample encryption,
162  // otherwise |sample_info_size| is just the IV size.
163  DCHECK(!IsSubsampleEncryptionRequired());
164  saiz.default_sample_info_size = encryptor_->iv().size();
165  }
166  traf()->sample_encryption.iv_size = encryptor_->iv().size();
167 }
168 
170  DCHECK(encryption_key_);
171 
172  scoped_ptr<AesCtrEncryptor> encryptor(new AesCtrEncryptor());
173  const bool initialized = encryption_key_->iv.empty()
174  ? encryptor->InitializeWithRandomIv(
175  encryption_key_->key, kDefaultIvSize)
176  : encryptor->InitializeWithIv(
177  encryption_key_->key, encryption_key_->iv);
178  if (!initialized)
179  return Status(error::MUXER_FAILURE, "Failed to create the encryptor.");
180  encryptor_ = encryptor.Pass();
181  return Status::OK;
182 }
183 
184 void EncryptingFragmenter::EncryptBytes(uint8_t* data, uint32_t size) {
185  DCHECK(encryptor_);
186  CHECK(encryptor_->Encrypt(data, size, data));
187 }
188 
189 Status EncryptingFragmenter::EncryptSample(scoped_refptr<MediaSample> sample) {
190  DCHECK(encryptor_);
191 
192  SampleEncryptionEntry sample_encryption_entry;
193  sample_encryption_entry.initialization_vector = encryptor_->iv();
194  uint8_t* data = sample->writable_data();
195  if (IsSubsampleEncryptionRequired()) {
196  if (vpx_parser_) {
197  std::vector<VPxFrameInfo> vpx_frames;
198  if (!vpx_parser_->Parse(sample->data(), sample->data_size(),
199  &vpx_frames)) {
200  return Status(error::MUXER_FAILURE, "Failed to parse vpx frame.");
201  }
202 
203  const bool is_superframe = vpx_frames.size() > 1;
204  for (const VPxFrameInfo& frame : vpx_frames) {
205  SubsampleEntry subsample;
206  subsample.clear_bytes = frame.uncompressed_header_size;
207  subsample.cipher_bytes =
208  frame.frame_size - frame.uncompressed_header_size;
209 
210  // "VP Codec ISO Media File Format Binding" document requires that the
211  // encrypted bytes of each frame within the superframe must be block
212  // aligned so that the counter state can be computed for each frame
213  // within the superframe.
214  if (is_superframe) {
215  uint16_t misalign_bytes = subsample.cipher_bytes % kCencBlockSize;
216  subsample.clear_bytes += misalign_bytes;
217  subsample.cipher_bytes -= misalign_bytes;
218  }
219 
220  sample_encryption_entry.subsamples.push_back(subsample);
221  if (subsample.cipher_bytes > 0)
222  EncryptBytes(data + subsample.clear_bytes, subsample.cipher_bytes);
223  data += frame.frame_size;
224  }
225  } else {
226  NaluReader reader(nalu_length_size_, data, sample->data_size());
227 
228  // Store the current length of clear data. This is used to squash
229  // multiple unencrypted NAL units into fewer subsample entries.
230  uint64_t accumulated_clear_bytes = 0;
231 
232  Nalu nalu;
233  NaluReader::Result result;
234  while ((result = reader.Advance(&nalu)) == NaluReader::kOk) {
235  if (nalu.is_video_slice()) {
236  // For video-slice NAL units, encrypt the video slice. This skips
237  // the frame header. If this is an unrecognized codec (e.g. H.265),
238  // the whole NAL unit will be encrypted.
239  const int64_t video_slice_header_size =
240  header_parser_ ? header_parser_->GetHeaderSize(nalu) : 0;
241  if (video_slice_header_size < 0)
242  return Status(error::MUXER_FAILURE, "Failed to read slice header.");
243 
244  const uint64_t current_clear_bytes = nalu.header_size() +
245  video_slice_header_size;
246  const uint64_t cipher_bytes =
247  nalu.data_size() - video_slice_header_size;
248  const uint8_t* nalu_data = nalu.data() + current_clear_bytes;
249  EncryptBytes(const_cast<uint8_t*>(nalu_data), cipher_bytes);
250 
251  AddSubsamples(
252  accumulated_clear_bytes + nalu_length_size_ + current_clear_bytes,
253  cipher_bytes, &sample_encryption_entry.subsamples);
254  accumulated_clear_bytes = 0;
255  } else {
256  // For non-video-slice NAL units, don't encrypt.
257  accumulated_clear_bytes += nalu.header_size() + nalu.data_size();
258  }
259  }
260  if (result != NaluReader::kEOStream)
261  return Status(error::MUXER_FAILURE, "Failed to parse NAL units.");
262  AddSubsamples(accumulated_clear_bytes, 0,
263  &sample_encryption_entry.subsamples);
264  }
265 
266  // The length of per-sample auxiliary datum, defined in CENC ch. 7.
267  traf()->auxiliary_size.sample_info_sizes.push_back(
268  sample_encryption_entry.ComputeSize());
269  } else {
270  EncryptBytes(data, sample->data_size());
271  }
272 
273  traf()->sample_encryption.sample_encryption_entries.push_back(
274  sample_encryption_entry);
275  encryptor_->UpdateIv();
276  return Status::OK;
277 }
278 
279 bool EncryptingFragmenter::IsSubsampleEncryptionRequired() {
280  return vpx_parser_ || nalu_length_size_ != 0;
281 }
282 
283 } // namespace mp4
284 } // namespace media
285 } // namespace edash_packager
Status InitializeFragment(int64_t first_sample_dts) override
virtual Status InitializeFragment(int64_t first_sample_dts)
Definition: fragmenter.cc:76
virtual Status AddSample(scoped_refptr< MediaSample > sample)
Definition: fragmenter.cc:36
Class to parse a vp9 bit stream.
Definition: vp9_parser.h:20
EncryptingFragmenter(scoped_refptr< StreamInfo > info, TrackFragment *traf, scoped_ptr< EncryptionKey > encryption_key, int64_t clear_time)
bool OptimizeSampleEntries(std::vector< T > *entries, T *default_value)
Definition: fragmenter.h:89
Status AddSample(scoped_refptr< MediaSample > sample) override
void FinalizeFragment() override
Finalize and optimize the fragment.
virtual Status PrepareFragmentForEncryption(bool enable_encryption)
virtual void FinalizeFragmentForEncryption()
Finalize current fragment for encryption.
virtual void FinalizeFragment()
Finalize and optimize the fragment.
Definition: fragmenter.cc:93