DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
segmenter.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/segmenter.h"
8 
9 #include <algorithm>
10 
11 #include "packager/base/stl_util.h"
12 #include "packager/media/base/buffer_writer.h"
13 #include "packager/media/base/key_source.h"
14 #include "packager/media/base/media_sample.h"
15 #include "packager/media/base/media_stream.h"
16 #include "packager/media/base/muxer_options.h"
17 #include "packager/media/base/video_stream_info.h"
18 #include "packager/media/event/muxer_listener.h"
19 #include "packager/media/event/progress_listener.h"
20 #include "packager/media/formats/mp4/box_definitions.h"
21 #include "packager/media/formats/mp4/key_rotation_fragmenter.h"
22 
23 namespace edash_packager {
24 namespace media {
25 namespace mp4 {
26 
27 namespace {
28 
29 // Generate 64bit IV by default.
30 const size_t kDefaultIvSize = 8u;
31 const size_t kCencKeyIdSize = 16u;
32 
33 // The version of cenc implemented here. CENC 4.
34 const int kCencSchemeVersion = 0x00010000;
35 
36 // The default KID for key rotation is all 0s.
37 const uint8_t kKeyRotationDefaultKeyId[] = {
38  0, 0, 0, 0, 0, 0, 0, 0,
39  0, 0, 0, 0, 0, 0, 0, 0
40 };
41 COMPILE_ASSERT(arraysize(kKeyRotationDefaultKeyId) == kCencKeyIdSize,
42  cenc_key_id_must_be_size_16);
43 
44 uint64_t Rescale(uint64_t time_in_old_scale,
45  uint32_t old_scale,
46  uint32_t new_scale) {
47  return static_cast<double>(time_in_old_scale) / old_scale * new_scale;
48 }
49 
50 void GenerateSinf(const EncryptionKey& encryption_key,
51  FourCC old_type,
52  ProtectionSchemeInfo* sinf) {
53  sinf->format.format = old_type;
54  sinf->type.type = FOURCC_CENC;
55  sinf->type.version = kCencSchemeVersion;
56  sinf->info.track_encryption.is_encrypted = true;
57  sinf->info.track_encryption.default_iv_size =
58  encryption_key.iv.empty() ? kDefaultIvSize : encryption_key.iv.size();
59  sinf->info.track_encryption.default_kid = encryption_key.key_id;
60 }
61 
62 void GenerateEncryptedSampleEntry(const EncryptionKey& encryption_key,
63  double clear_lead_in_seconds,
64  SampleDescription* description) {
65  DCHECK(description);
66  if (description->type == kVideo) {
67  DCHECK_EQ(1u, description->video_entries.size());
68 
69  // Add a second entry for clear content if needed.
70  if (clear_lead_in_seconds > 0)
71  description->video_entries.push_back(description->video_entries[0]);
72 
73  // Convert the first entry to an encrypted entry.
74  VideoSampleEntry& entry = description->video_entries[0];
75  GenerateSinf(encryption_key, entry.format, &entry.sinf);
76  entry.format = FOURCC_ENCV;
77  } else {
78  DCHECK_EQ(kAudio, description->type);
79  DCHECK_EQ(1u, description->audio_entries.size());
80 
81  // Add a second entry for clear content if needed.
82  if (clear_lead_in_seconds > 0)
83  description->audio_entries.push_back(description->audio_entries[0]);
84 
85  // Convert the first entry to an encrypted entry.
86  AudioSampleEntry& entry = description->audio_entries[0];
87  GenerateSinf(encryption_key, entry.format, &entry.sinf);
88  entry.format = FOURCC_ENCA;
89  }
90 }
91 
92 KeySource::TrackType GetTrackTypeForEncryption(const StreamInfo& stream_info,
93  uint32_t max_sd_pixels) {
94  if (stream_info.stream_type() == kStreamAudio)
95  return KeySource::TRACK_TYPE_AUDIO;
96 
97  DCHECK_EQ(kStreamVideo, stream_info.stream_type());
98  const VideoStreamInfo& video_stream_info =
99  static_cast<const VideoStreamInfo&>(stream_info);
100  uint32_t pixels = video_stream_info.width() * video_stream_info.height();
101  return (pixels > max_sd_pixels) ? KeySource::TRACK_TYPE_HD
102  : KeySource::TRACK_TYPE_SD;
103 }
104 
105 } // namespace
106 
107 Segmenter::Segmenter(const MuxerOptions& options,
108  scoped_ptr<FileType> ftyp,
109  scoped_ptr<Movie> moov)
110  : options_(options),
111  ftyp_(ftyp.Pass()),
112  moov_(moov.Pass()),
113  moof_(new MovieFragment()),
114  fragment_buffer_(new BufferWriter()),
115  sidx_(new SegmentIndex()),
116  muxer_listener_(NULL),
117  progress_listener_(NULL),
118  progress_target_(0),
119  accumulated_progress_(0),
120  sample_duration_(0u) {}
121 
122 Segmenter::~Segmenter() { STLDeleteElements(&fragmenters_); }
123 
124 Status Segmenter::Initialize(const std::vector<MediaStream*>& streams,
125  MuxerListener* muxer_listener,
126  ProgressListener* progress_listener,
127  KeySource* encryption_key_source,
128  uint32_t max_sd_pixels,
129  double clear_lead_in_seconds,
130  double crypto_period_duration_in_seconds) {
131  DCHECK_LT(0u, streams.size());
132  muxer_listener_ = muxer_listener;
133  progress_listener_ = progress_listener;
134  moof_->header.sequence_number = 0;
135 
136  moof_->tracks.resize(streams.size());
137  segment_durations_.resize(streams.size());
138  fragmenters_.resize(streams.size());
139  const bool key_rotation_enabled = crypto_period_duration_in_seconds != 0;
140  const bool kInitialEncryptionInfo = true;
141 
142  for (uint32_t i = 0; i < streams.size(); ++i) {
143  stream_map_[streams[i]] = i;
144  moof_->tracks[i].header.track_id = i + 1;
145  if (streams[i]->info()->stream_type() == kStreamVideo) {
146  // Use the first video stream as the reference stream (which is 1-based).
147  if (sidx_->reference_id == 0)
148  sidx_->reference_id = i + 1;
149  }
150  if (!encryption_key_source) {
151  fragmenters_[i] = new Fragmenter(&moof_->tracks[i]);
152  continue;
153  }
154 
155  KeySource::TrackType track_type =
156  GetTrackTypeForEncryption(*streams[i]->info(), max_sd_pixels);
157  SampleDescription& description =
158  moov_->tracks[i].media.information.sample_table.description;
159 
160  if (key_rotation_enabled) {
161  // Fill encrypted sample entry with default key.
162  EncryptionKey encryption_key;
163  encryption_key.key_id.assign(
164  kKeyRotationDefaultKeyId,
165  kKeyRotationDefaultKeyId + arraysize(kKeyRotationDefaultKeyId));
166  GenerateEncryptedSampleEntry(encryption_key, clear_lead_in_seconds,
167  &description);
168 
169  if (muxer_listener_) {
170  muxer_listener_->OnEncryptionInfoReady(
171  kInitialEncryptionInfo, encryption_key.key_id,
172  encryption_key.key_system_info);
173  }
174 
175  fragmenters_[i] = new KeyRotationFragmenter(
176  moof_.get(), streams[i]->info(), &moof_->tracks[i],
177  encryption_key_source, track_type,
178  crypto_period_duration_in_seconds * streams[i]->info()->time_scale(),
179  clear_lead_in_seconds * streams[i]->info()->time_scale(),
180  muxer_listener_);
181  continue;
182  }
183 
184  scoped_ptr<EncryptionKey> encryption_key(new EncryptionKey());
185  Status status =
186  encryption_key_source->GetKey(track_type, encryption_key.get());
187  if (!status.ok())
188  return status;
189 
190  GenerateEncryptedSampleEntry(*encryption_key, clear_lead_in_seconds,
191  &description);
192 
193  if (moov_->pssh.empty()) {
194  moov_->pssh.resize(encryption_key->key_system_info.size());
195  for (size_t i = 0; i < encryption_key->key_system_info.size(); i++) {
196  moov_->pssh[i].raw_box = encryption_key->key_system_info[i].CreateBox();
197  }
198 
199  if (muxer_listener_) {
200  muxer_listener_->OnEncryptionInfoReady(kInitialEncryptionInfo,
201  encryption_key->key_id,
202  encryption_key->key_system_info);
203  }
204  }
205 
206  fragmenters_[i] = new EncryptingFragmenter(
207  streams[i]->info(), &moof_->tracks[i], encryption_key.Pass(),
208  clear_lead_in_seconds * streams[i]->info()->time_scale());
209  }
210 
211  // Choose the first stream if there is no VIDEO.
212  if (sidx_->reference_id == 0)
213  sidx_->reference_id = 1;
214  sidx_->timescale = streams[GetReferenceStreamId()]->info()->time_scale();
215 
216  // Use media duration as progress target.
217  progress_target_ = streams[GetReferenceStreamId()]->info()->duration();
218 
219  // Use the reference stream's time scale as movie time scale.
220  moov_->header.timescale = sidx_->timescale;
221  moof_->header.sequence_number = 1;
222 
223  // Fill in version information.
224  moov_->metadata.handler.handler_type = FOURCC_ID32;
225  moov_->metadata.id3v2.language.code = "eng";
226  moov_->metadata.id3v2.private_frame.owner =
227  "https://github.com/google/edash-packager";
228  moov_->metadata.id3v2.private_frame.value = options_.packager_version_string;
229  return DoInitialize();
230 }
231 
233  for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
234  it != fragmenters_.end();
235  ++it) {
236  Status status = FinalizeFragment(true, *it);
237  if (!status.ok())
238  return status;
239  }
240 
241  // Set tracks and moov durations.
242  // Note that the updated moov box will be written to output file for VOD case
243  // only.
244  for (std::vector<Track>::iterator track = moov_->tracks.begin();
245  track != moov_->tracks.end();
246  ++track) {
247  track->header.duration = Rescale(track->media.header.duration,
248  track->media.header.timescale,
249  moov_->header.timescale);
250  if (track->header.duration > moov_->header.duration)
251  moov_->header.duration = track->header.duration;
252  }
253  moov_->extends.header.fragment_duration = moov_->header.duration;
254 
255  return DoFinalize();
256 }
257 
259  scoped_refptr<MediaSample> sample) {
260  // Find the fragmenter for this stream.
261  DCHECK(stream);
262  DCHECK(stream_map_.find(stream) != stream_map_.end());
263  uint32_t stream_id = stream_map_[stream];
264  Fragmenter* fragmenter = fragmenters_[stream_id];
265 
266  // Set default sample duration if it has not been set yet.
267  if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
268  moov_->extends.tracks[stream_id].default_sample_duration =
269  sample->duration();
270  }
271 
272  if (fragmenter->fragment_finalized()) {
273  return Status(error::FRAGMENT_FINALIZED,
274  "Current fragment is finalized already.");
275  }
276 
277  bool finalize_fragment = false;
278  if (fragmenter->fragment_duration() >=
279  options_.fragment_duration * stream->info()->time_scale()) {
280  if (sample->is_key_frame() || !options_.fragment_sap_aligned) {
281  finalize_fragment = true;
282  }
283  }
284  bool finalize_segment = false;
285  if (segment_durations_[stream_id] >=
286  options_.segment_duration * stream->info()->time_scale()) {
287  if (sample->is_key_frame() || !options_.segment_sap_aligned) {
288  finalize_segment = true;
289  finalize_fragment = true;
290  }
291  }
292 
293  Status status;
294  if (finalize_fragment) {
295  status = FinalizeFragment(finalize_segment, fragmenter);
296  if (!status.ok())
297  return status;
298  }
299 
300  status = fragmenter->AddSample(sample);
301  if (!status.ok())
302  return status;
303 
304  if (sample_duration_ == 0)
305  sample_duration_ = sample->duration();
306  moov_->tracks[stream_id].media.header.duration += sample->duration();
307  segment_durations_[stream_id] += sample->duration();
308  DCHECK_GE(segment_durations_[stream_id], fragmenter->fragment_duration());
309  return Status::OK;
310 }
311 
312 uint32_t Segmenter::GetReferenceTimeScale() const {
313  return moov_->header.timescale;
314 }
315 
316 double Segmenter::GetDuration() const {
317  if (moov_->header.timescale == 0) {
318  // Handling the case where this is not properly initialized.
319  return 0.0;
320  }
321 
322  return static_cast<double>(moov_->header.duration) / moov_->header.timescale;
323 }
324 
325 void Segmenter::UpdateProgress(uint64_t progress) {
326  accumulated_progress_ += progress;
327 
328  if (!progress_listener_) return;
329  if (progress_target_ == 0) return;
330  // It might happen that accumulated progress exceeds progress_target due to
331  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
332  // progress.
333  if (accumulated_progress_ >= progress_target_) {
334  progress_listener_->OnProgress(1.0);
335  } else {
336  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
337  progress_target_);
338  }
339 }
340 
341 void Segmenter::SetComplete() {
342  if (!progress_listener_) return;
343  progress_listener_->OnProgress(1.0);
344 }
345 
346 Status Segmenter::FinalizeSegment() {
347  Status status = DoFinalizeSegment();
348 
349  // Reset segment information to initial state.
350  sidx_->references.clear();
351  std::vector<uint64_t>::iterator it = segment_durations_.begin();
352  for (; it != segment_durations_.end(); ++it)
353  *it = 0;
354 
355  return status;
356 }
357 
358 uint32_t Segmenter::GetReferenceStreamId() {
359  DCHECK(sidx_);
360  return sidx_->reference_id - 1;
361 }
362 
363 Status Segmenter::FinalizeFragment(bool finalize_segment,
364  Fragmenter* fragmenter) {
365  fragmenter->FinalizeFragment();
366 
367  // Check if all tracks are ready for fragmentation.
368  for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
369  it != fragmenters_.end();
370  ++it) {
371  if (!(*it)->fragment_finalized())
372  return Status::OK;
373  }
374 
375  MediaData mdat;
376  // Data offset relative to 'moof': moof size + mdat header size.
377  // The code will also update box sizes for moof_ and its child boxes.
378  uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
379  // 'traf' should follow 'mfhd' moof header box.
380  uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
381  for (size_t i = 0; i < moof_->tracks.size(); ++i) {
382  TrackFragment& traf = moof_->tracks[i];
383  if (traf.auxiliary_offset.offsets.size() > 0) {
384  DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
385  DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
386 
387  next_traf_position += traf.box_size();
388  // SampleEncryption 'senc' box should be the last box in 'traf'.
389  // |auxiliary_offset| should point to the data of SampleEncryption.
390  traf.auxiliary_offset.offsets[0] =
391  next_traf_position - traf.sample_encryption.box_size() +
392  traf.sample_encryption.HeaderSize() +
393  sizeof(uint32_t); // for sample count field in 'senc'
394  }
395  traf.runs[0].data_offset = data_offset + mdat.data_size;
396  mdat.data_size += fragmenters_[i]->data()->Size();
397  }
398 
399  // Generate segment reference.
400  sidx_->references.resize(sidx_->references.size() + 1);
401  fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
402  &sidx_->references[sidx_->references.size() - 1]);
403  sidx_->references[sidx_->references.size() - 1].referenced_size =
404  data_offset + mdat.data_size;
405 
406  // Write the fragment to buffer.
407  moof_->Write(fragment_buffer_.get());
408  mdat.WriteHeader(fragment_buffer_.get());
409  for (Fragmenter* fragmenter : fragmenters_)
410  fragment_buffer_->AppendBuffer(*fragmenter->data());
411 
412  // Increase sequence_number for next fragment.
413  ++moof_->header.sequence_number;
414 
415  if (finalize_segment)
416  return FinalizeSegment();
417 
418  return Status::OK;
419 }
420 
421 } // namespace mp4
422 } // namespace media
423 } // namespace edash_packager
virtual Status GetKey(TrackType track_type, EncryptionKey *key)
Definition: key_source.cc:42
Status Initialize(scoped_ptr< MkvWriter > writer, StreamInfo *info, ProgressListener *progress_listener, MuxerListener *muxer_listener, KeySource *encryption_key_source, uint32_t max_sd_pixels, double clear_lead_in_seconds)
Definition: segmenter.cc:46
std::string packager_version_string
Specify the version string to be embedded in the output files.
Definition: muxer_options.h:71
This class listens to progress updates events.
EncryptingFragmenter generates MP4 fragments with sample encrypted.
virtual Status AddSample(scoped_refptr< MediaSample > sample)
Definition: fragmenter.cc:36
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:35
virtual void OnProgress(double progress)=0
void UpdateProgress(uint64_t progress)
Update segmentation progress using ProgressListener.
Definition: segmenter.cc:245
Status AddSample(scoped_refptr< MediaSample > sample)
Definition: segmenter.cc:112