Shaka Packager SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
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/logging.h"
12 #include "packager/media/base/buffer_writer.h"
13 #include "packager/media/base/media_sample.h"
14 #include "packager/media/base/muxer_options.h"
15 #include "packager/media/base/muxer_util.h"
16 #include "packager/media/base/stream_info.h"
17 #include "packager/media/chunking/chunking_handler.h"
18 #include "packager/media/event/progress_listener.h"
19 #include "packager/media/formats/mp4/box_definitions.h"
20 #include "packager/media/formats/mp4/fragmenter.h"
21 #include "packager/version/version.h"
22 
23 namespace shaka {
24 namespace media {
25 namespace mp4 {
26 
27 namespace {
28 
29 uint64_t Rescale(uint64_t time_in_old_scale,
30  uint32_t old_scale,
31  uint32_t new_scale) {
32  return static_cast<double>(time_in_old_scale) / old_scale * new_scale;
33 }
34 
35 } // namespace
36 
37 Segmenter::Segmenter(const MuxerOptions& options,
38  std::unique_ptr<FileType> ftyp,
39  std::unique_ptr<Movie> moov)
40  : options_(options),
41  ftyp_(std::move(ftyp)),
42  moov_(std::move(moov)),
43  moof_(new MovieFragment()),
44  fragment_buffer_(new BufferWriter()),
45  sidx_(new SegmentIndex()) {}
46 
47 Segmenter::~Segmenter() {}
48 
50  const std::vector<std::shared_ptr<const StreamInfo>>& streams,
51  MuxerListener* muxer_listener,
52  ProgressListener* progress_listener) {
53  DCHECK_LT(0u, streams.size());
54  muxer_listener_ = muxer_listener;
55  progress_listener_ = progress_listener;
56  moof_->header.sequence_number = 0;
57 
58  moof_->tracks.resize(streams.size());
59  fragmenters_.resize(streams.size());
60  stream_durations_.resize(streams.size());
61 
62  for (uint32_t i = 0; i < streams.size(); ++i) {
63  moof_->tracks[i].header.track_id = i + 1;
64  if (streams[i]->stream_type() == kStreamVideo) {
65  // Use the first video stream as the reference stream (which is 1-based).
66  if (sidx_->reference_id == 0)
67  sidx_->reference_id = i + 1;
68  }
69  fragmenters_[i].reset(new Fragmenter(streams[i], &moof_->tracks[i]));
70  }
71 
73  for (uint32_t i = 0; i < streams.size(); ++i)
74  fragmenters_[i]->set_use_decoding_timestamp_in_timeline(true);
75  }
76 
77  // Choose the first stream if there is no VIDEO.
78  if (sidx_->reference_id == 0)
79  sidx_->reference_id = 1;
80  sidx_->timescale = streams[GetReferenceStreamId()]->time_scale();
81 
82  // Use media duration as progress target.
83  progress_target_ = streams[GetReferenceStreamId()]->duration();
84 
85  // Use the reference stream's time scale as movie time scale.
86  moov_->header.timescale = sidx_->timescale;
87  moof_->header.sequence_number = 1;
88 
89  // Fill in version information.
90  const std::string version = GetPackagerVersion();
91  if (!version.empty()) {
92  moov_->metadata.handler.handler_type = FOURCC_ID32;
93  moov_->metadata.id3v2.language.code = "eng";
94  moov_->metadata.id3v2.private_frame.owner = GetPackagerProjectUrl();
95  moov_->metadata.id3v2.private_frame.value = version;
96  }
97  return DoInitialize();
98 }
99 
101  // Set movie duration. Note that the duration in mvhd, tkhd, mdhd should not
102  // be touched, i.e. kept at 0. The updated moov box will be written to output
103  // file for VOD case only.
104  moov_->extends.header.fragment_duration = 0;
105  for (size_t i = 0; i < stream_durations_.size(); ++i) {
106  uint64_t duration =
107  Rescale(stream_durations_[i], moov_->tracks[i].media.header.timescale,
108  moov_->header.timescale);
109  if (duration > moov_->extends.header.fragment_duration)
110  moov_->extends.header.fragment_duration = duration;
111  }
112  return DoFinalize();
113 }
114 
115 Status Segmenter::AddSample(size_t stream_id, const MediaSample& sample) {
116  // Set default sample duration if it has not been set yet.
117  if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
118  moov_->extends.tracks[stream_id].default_sample_duration =
119  sample.duration();
120  }
121 
122  DCHECK_LT(stream_id, fragmenters_.size());
123  Fragmenter* fragmenter = fragmenters_[stream_id].get();
124  if (fragmenter->fragment_finalized()) {
125  return Status(error::FRAGMENT_FINALIZED,
126  "Current fragment is finalized already.");
127  }
128 
129  Status status = fragmenter->AddSample(sample);
130  if (!status.ok())
131  return status;
132 
133  if (sample_duration_ == 0)
134  sample_duration_ = sample.duration();
135  stream_durations_[stream_id] += sample.duration();
136  return Status::OK;
137 }
138 
140  const SegmentInfo& segment_info) {
141  if (segment_info.key_rotation_encryption_config) {
142  FinalizeFragmentForKeyRotation(
143  stream_id, segment_info.is_encrypted,
144  *segment_info.key_rotation_encryption_config);
145  }
146 
147  DCHECK_LT(stream_id, fragmenters_.size());
148  Fragmenter* fragmenter = fragmenters_[stream_id].get();
149  DCHECK(fragmenter);
150  Status status = fragmenter->FinalizeFragment();
151  if (!status.ok())
152  return status;
153 
154  // Check if all tracks are ready for fragmentation.
155  for (const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_) {
156  if (!fragmenter->fragment_finalized())
157  return Status::OK;
158  }
159 
160  MediaData mdat;
161  // Data offset relative to 'moof': moof size + mdat header size.
162  // The code will also update box sizes for moof_ and its child boxes.
163  uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
164  // 'traf' should follow 'mfhd' moof header box.
165  uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
166  for (size_t i = 0; i < moof_->tracks.size(); ++i) {
167  TrackFragment& traf = moof_->tracks[i];
168  if (traf.auxiliary_offset.offsets.size() > 0) {
169  DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
170  DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
171 
172  next_traf_position += traf.box_size();
173  // SampleEncryption 'senc' box should be the last box in 'traf'.
174  // |auxiliary_offset| should point to the data of SampleEncryption.
175  traf.auxiliary_offset.offsets[0] =
176  next_traf_position - traf.sample_encryption.box_size() +
177  traf.sample_encryption.HeaderSize() +
178  sizeof(uint32_t); // for sample count field in 'senc'
179  }
180  traf.runs[0].data_offset = data_offset + mdat.data_size;
181  mdat.data_size += static_cast<uint32_t>(fragmenters_[i]->data()->Size());
182  }
183 
184  // Generate segment reference.
185  sidx_->references.resize(sidx_->references.size() + 1);
186  fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
187  &sidx_->references[sidx_->references.size() - 1]);
188  sidx_->references[sidx_->references.size() - 1].referenced_size =
189  data_offset + mdat.data_size;
190 
191  // Write the fragment to buffer.
192  moof_->Write(fragment_buffer_.get());
193  mdat.WriteHeader(fragment_buffer_.get());
194  for (const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_)
195  fragment_buffer_->AppendBuffer(*fragmenter->data());
196 
197  // Increase sequence_number for next fragment.
198  ++moof_->header.sequence_number;
199 
200  for (std::unique_ptr<Fragmenter>& fragmenter : fragmenters_)
201  fragmenter->ClearFragmentFinalized();
202  if (!segment_info.is_subsegment) {
203  Status status = DoFinalizeSegment();
204  // Reset segment information to initial state.
205  sidx_->references.clear();
206  return status;
207  }
208  return Status::OK;
209 }
210 
211 uint32_t Segmenter::GetReferenceTimeScale() const {
212  return moov_->header.timescale;
213 }
214 
215 double Segmenter::GetDuration() const {
216  uint64_t duration = moov_->extends.header.fragment_duration;
217  if (duration == 0) {
218  // Handling the case where this is not properly initialized.
219  return 0.0;
220  }
221  return static_cast<double>(duration) / moov_->header.timescale;
222 }
223 
224 void Segmenter::UpdateProgress(uint64_t progress) {
225  accumulated_progress_ += progress;
226 
227  if (!progress_listener_) return;
228  if (progress_target_ == 0) return;
229  // It might happen that accumulated progress exceeds progress_target due to
230  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
231  // progress.
232  if (accumulated_progress_ >= progress_target_) {
233  progress_listener_->OnProgress(1.0);
234  } else {
235  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
236  progress_target_);
237  }
238 }
239 
240 void Segmenter::SetComplete() {
241  if (!progress_listener_) return;
242  progress_listener_->OnProgress(1.0);
243 }
244 
245 uint32_t Segmenter::GetReferenceStreamId() {
246  DCHECK(sidx_);
247  return sidx_->reference_id - 1;
248 }
249 
250 void Segmenter::FinalizeFragmentForKeyRotation(
251  size_t stream_id,
252  bool fragment_encrypted,
253  const EncryptionConfig& encryption_config) {
254  if (options_.mp4_params.include_pssh_in_stream) {
255  const std::vector<ProtectionSystemSpecificInfo>& system_info =
256  encryption_config.key_system_info;
257  moof_->pssh.resize(system_info.size());
258  for (size_t i = 0; i < system_info.size(); i++)
259  moof_->pssh[i].raw_box = system_info[i].CreateBox();
260  } else {
261  LOG(WARNING)
262  << "Key rotation and no pssh in stream may not work well together.";
263  }
264 
265  // Skip the following steps if the current fragment is not going to be
266  // encrypted. 'pssh' box needs to be included in the fragment, which is
267  // performed above, regardless of whether the fragment is encrypted. This is
268  // necessary for two reasons: 1) Requesting keys before reaching encrypted
269  // content avoids playback delay due to license requests; 2) In Chrome, CDM
270  // must be initialized before starting the playback and CDM can only be
271  // initialized with a valid 'pssh'.
272  if (!fragment_encrypted)
273  return;
274 
275  DCHECK_LT(stream_id, moof_->tracks.size());
276  TrackFragment& traf = moof_->tracks[stream_id];
277  traf.sample_group_descriptions.resize(traf.sample_group_descriptions.size() +
278  1);
279  SampleGroupDescription& sample_group_description =
280  traf.sample_group_descriptions.back();
281  sample_group_description.grouping_type = FOURCC_seig;
282 
283  sample_group_description.cenc_sample_encryption_info_entries.resize(1);
284  CencSampleEncryptionInfoEntry& sample_group_entry =
285  sample_group_description.cenc_sample_encryption_info_entries.back();
286  sample_group_entry.is_protected = 1;
287  sample_group_entry.per_sample_iv_size = encryption_config.per_sample_iv_size;
288  sample_group_entry.constant_iv = encryption_config.constant_iv;
289  sample_group_entry.crypt_byte_block = encryption_config.crypt_byte_block;
290  sample_group_entry.skip_byte_block = encryption_config.skip_byte_block;
291  sample_group_entry.key_id = encryption_config.key_id;
292 }
293 
294 } // namespace mp4
295 } // namespace media
296 } // namespace shaka
uint32_t HeaderSize() const final
Definition: box.cc:75
Status AddSample(const MediaSample &sample)
Definition: segmenter.cc:159
virtual Status FinalizeSegment(uint64_t start_timestamp, uint64_t duration_timestamp, bool is_subsegment)=0
Finalize the (sub)segment.
Definition: segmenter.cc:195
uint32_t ComputeSize()
Definition: box.cc:50
Mp4OutputParams mp4_params
MP4 (ISO-BMFF) specific parameters.
Definition: muxer_options.h:25
This class listens to progress updates events.
Status Initialize(const StreamInfo &info, ProgressListener *progress_listener, MuxerListener *muxer_listener)
Definition: segmenter.cc:78
uint32_t box_size()
Definition: box.h:55
virtual uint32_t HeaderSize() const
Definition: box.cc:55
Class to hold a media sample.
Definition: media_sample.h:22
virtual void OnProgress(double progress)=0
void UpdateProgress(uint64_t progress)
Update segmentation progress using ProgressListener.
Definition: segmenter.cc:270
void WriteHeader(BufferWriter *writer)
Definition: box.cc:38