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 "packager/media/base/aes_encryptor.h"
10 #include "packager/media/base/buffer_reader.h"
11 #include "packager/media/base/key_source.h"
12 #include "packager/media/base/media_sample.h"
13 #include "packager/media/filters/vp8_parser.h"
14 #include "packager/media/filters/vp9_parser.h"
15 #include "packager/media/formats/mp4/box_definitions.h"
16 #include "packager/media/formats/mp4/cenc.h"
17 
18 namespace {
19 // Generate 64bit IV by default.
20 const size_t kDefaultIvSize = 8u;
21 } // namespace
22 
23 namespace edash_packager {
24 namespace media {
25 namespace mp4 {
26 
28  TrackFragment* traf,
29  scoped_ptr<EncryptionKey> encryption_key,
30  int64_t clear_time,
31  VideoCodec video_codec,
32  uint8_t nalu_length_size)
33  : Fragmenter(traf),
34  encryption_key_(encryption_key.Pass()),
35  video_codec_(video_codec),
36  nalu_length_size_(nalu_length_size),
37  clear_time_(clear_time) {
38  DCHECK(encryption_key_);
39  if (video_codec == kCodecVP8) {
40  vpx_parser_.reset(new VP8Parser);
41  } else if (video_codec == kCodecVP9) {
42  vpx_parser_.reset(new VP9Parser);
43  }
44 }
45 
46 EncryptingFragmenter::~EncryptingFragmenter() {}
47 
48 Status EncryptingFragmenter::AddSample(scoped_refptr<MediaSample> sample) {
49  DCHECK(sample);
50  if (!fragment_initialized()) {
51  Status status = InitializeFragment(sample->dts());
52  if (!status.ok())
53  return status;
54  }
55  if (encryptor_) {
56  Status status = EncryptSample(sample);
57  if (!status.ok())
58  return status;
59  }
60  return Fragmenter::AddSample(sample);
61 }
62 
64  Status status = Fragmenter::InitializeFragment(first_sample_dts);
65  if (!status.ok())
66  return status;
67 
68  traf()->auxiliary_size.sample_info_sizes.clear();
69  traf()->auxiliary_offset.offsets.clear();
70 
71  const bool enable_encryption = clear_time_ <= 0;
72  if (!enable_encryption) {
73  // This fragment should be in clear text.
74  // At most two sample description entries, an encrypted entry and a clear
75  // entry, are generated. The 1-based clear entry index is always 2.
76  const uint32_t kClearSampleDescriptionIndex = 2;
77 
78  traf()->header.flags |=
79  TrackFragmentHeader::kSampleDescriptionIndexPresentMask;
80  traf()->header.sample_description_index = kClearSampleDescriptionIndex;
81  }
82  return PrepareFragmentForEncryption(enable_encryption);
83 }
84 
86  if (encryptor_) {
87  DCHECK_LE(clear_time_, 0);
89  } else {
90  DCHECK_GT(clear_time_, 0);
91  clear_time_ -= fragment_duration();
92  }
94 }
95 
97  bool enable_encryption) {
98  return (!enable_encryption || encryptor_) ? Status::OK : CreateEncryptor();
99 }
100 
102  // The offset will be adjusted in Segmenter after knowing moof size.
103  traf()->auxiliary_offset.offsets.push_back(0);
104 
105  // Optimize saiz box.
106  SampleAuxiliaryInformationSize& saiz = traf()->auxiliary_size;
107  saiz.sample_count = traf()->runs[0].sample_sizes.size();
108  if (!saiz.sample_info_sizes.empty()) {
109  if (!OptimizeSampleEntries(&saiz.sample_info_sizes,
110  &saiz.default_sample_info_size)) {
111  saiz.default_sample_info_size = 0;
112  }
113  } else {
114  // |sample_info_sizes| table is filled in only for subsample encryption,
115  // otherwise |sample_info_size| is just the IV size.
116  DCHECK(!IsSubsampleEncryptionRequired());
117  saiz.default_sample_info_size = encryptor_->iv().size();
118  }
119 }
120 
122  DCHECK(encryption_key_);
123 
124  scoped_ptr<AesCtrEncryptor> encryptor(new AesCtrEncryptor());
125  const bool initialized = encryption_key_->iv.empty()
126  ? encryptor->InitializeWithRandomIv(
127  encryption_key_->key, kDefaultIvSize)
128  : encryptor->InitializeWithIv(
129  encryption_key_->key, encryption_key_->iv);
130  if (!initialized)
131  return Status(error::MUXER_FAILURE, "Failed to create the encryptor.");
132  encryptor_ = encryptor.Pass();
133  return Status::OK;
134 }
135 
136 void EncryptingFragmenter::EncryptBytes(uint8_t* data, uint32_t size) {
137  DCHECK(encryptor_);
138  CHECK(encryptor_->Encrypt(data, size, data));
139 }
140 
141 Status EncryptingFragmenter::EncryptSample(scoped_refptr<MediaSample> sample) {
142  DCHECK(encryptor_);
143 
144  FrameCENCInfo cenc_info(encryptor_->iv());
145  uint8_t* data = sample->writable_data();
146  if (IsSubsampleEncryptionRequired()) {
147  if (vpx_parser_) {
148  std::vector<VPxFrameInfo> vpx_frames;
149  if (!vpx_parser_->Parse(sample->data(), sample->data_size(),
150  &vpx_frames)) {
151  return Status(error::MUXER_FAILURE, "Failed to parse vpx frame.");
152  }
153  for (const VPxFrameInfo& frame : vpx_frames) {
154  SubsampleEntry subsample;
155  subsample.clear_bytes = frame.uncompressed_header_size;
156  subsample.cipher_bytes =
157  frame.frame_size - frame.uncompressed_header_size;
158  cenc_info.AddSubsample(subsample);
159  if (subsample.cipher_bytes > 0)
160  EncryptBytes(data + subsample.clear_bytes, subsample.cipher_bytes);
161  data += frame.frame_size;
162  }
163  } else {
164  BufferReader reader(data, sample->data_size());
165  while (reader.HasBytes(1)) {
166  uint64_t nalu_length;
167  if (!reader.ReadNBytesInto8(&nalu_length, nalu_length_size_))
168  return Status(error::MUXER_FAILURE, "Fail to read nalu_length.");
169 
170  SubsampleEntry subsample;
171  subsample.clear_bytes = nalu_length_size_ + 1;
172  subsample.cipher_bytes = nalu_length - 1;
173  if (!reader.SkipBytes(nalu_length)) {
174  return Status(error::MUXER_FAILURE,
175  "Sample size does not match nalu_length.");
176  }
177 
178  EncryptBytes(data + subsample.clear_bytes, subsample.cipher_bytes);
179  cenc_info.AddSubsample(subsample);
180  data += nalu_length_size_ + nalu_length;
181  }
182  }
183 
184  // The length of per-sample auxiliary datum, defined in CENC ch. 7.
185  traf()->auxiliary_size.sample_info_sizes.push_back(cenc_info.ComputeSize());
186  } else {
187  EncryptBytes(data, sample->data_size());
188  }
189 
190  cenc_info.Write(aux_data());
191  encryptor_->UpdateIv();
192  return Status::OK;
193 }
194 
195 } // namespace mp4
196 } // namespace media
197 } // namespace edash_packager
EncryptingFragmenter(TrackFragment *traf, scoped_ptr< EncryptionKey > encryption_key, int64_t clear_time, VideoCodec video_codec, uint8_t nalu_length_size)
Status InitializeFragment(int64_t first_sample_dts) override
virtual Status InitializeFragment(int64_t first_sample_dts)
Definition: fragmenter.cc:73
virtual Status AddSample(scoped_refptr< MediaSample > sample)
Definition: fragmenter.cc:36
Class to parse a vp9 bit stream.
Definition: vp9_parser.h:20
bool OptimizeSampleEntries(std::vector< T > *entries, T *default_value)
Definition: fragmenter.h:91
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:91