Shaka Packager SDK
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/fragmenter.h"
8 
9 #include <algorithm>
10 #include <limits>
11 
12 #include "packager/media/base/audio_stream_info.h"
13 #include "packager/media/base/buffer_writer.h"
14 #include "packager/media/base/media_sample.h"
15 #include "packager/media/formats/mp4/box_definitions.h"
16 #include "packager/media/formats/mp4/key_frame_info.h"
17 #include "packager/status_macros.h"
18 
19 namespace shaka {
20 namespace media {
21 namespace mp4 {
22 
23 namespace {
24 const int64_t kInvalidTime = std::numeric_limits<int64_t>::max();
25 
26 int64_t GetSeekPreroll(const StreamInfo& stream_info) {
27  if (stream_info.stream_type() != kStreamAudio)
28  return 0;
29  const AudioStreamInfo& audio_stream_info =
30  static_cast<const AudioStreamInfo&>(stream_info);
31  return audio_stream_info.seek_preroll_ns();
32 }
33 
34 void NewSampleEncryptionEntry(const DecryptConfig& decrypt_config,
35  bool use_constant_iv,
36  TrackFragment* traf) {
37  SampleEncryption& sample_encryption = traf->sample_encryption;
38  SampleEncryptionEntry sample_encryption_entry;
39  if (!use_constant_iv)
40  sample_encryption_entry.initialization_vector = decrypt_config.iv();
41  sample_encryption_entry.subsamples = decrypt_config.subsamples();
42  sample_encryption.sample_encryption_entries.push_back(
43  sample_encryption_entry);
44  traf->auxiliary_size.sample_info_sizes.push_back(
45  sample_encryption_entry.ComputeSize());
46 }
47 
48 } // namespace
49 
50 Fragmenter::Fragmenter(std::shared_ptr<const StreamInfo> stream_info,
51  TrackFragment* traf,
52  int64_t edit_list_offset)
53  : stream_info_(std::move(stream_info)),
54  traf_(traf),
55  edit_list_offset_(edit_list_offset),
56  seek_preroll_(GetSeekPreroll(*stream_info_)),
57  earliest_presentation_time_(kInvalidTime),
58  first_sap_time_(kInvalidTime) {
59  DCHECK(stream_info_);
60  DCHECK(traf);
61 }
62 
63 Fragmenter::~Fragmenter() {}
64 
66  const int64_t pts = sample.pts();
67  const int64_t dts = sample.dts();
68  const int64_t duration = sample.duration();
69  if (duration == 0)
70  LOG(WARNING) << "Unexpected sample with zero duration @ dts " << dts;
71 
72  if (!fragment_initialized_)
73  RETURN_IF_ERROR(InitializeFragment(dts));
74 
75  if (sample.side_data_size() > 0)
76  LOG(WARNING) << "MP4 samples do not support side data. Side data ignored.";
77 
78  // Fill in sample parameters. It will be optimized later.
79  traf_->runs[0].sample_sizes.push_back(
80  static_cast<uint32_t>(sample.data_size()));
81  traf_->runs[0].sample_durations.push_back(duration);
82  traf_->runs[0].sample_flags.push_back(
83  sample.is_key_frame() ? 0 : TrackFragmentHeader::kNonKeySampleMask);
84 
85  if (sample.decrypt_config()) {
86  NewSampleEncryptionEntry(
87  *sample.decrypt_config(),
88  !stream_info_->encryption_config().constant_iv.empty(), traf_);
89  }
90 
91  if (stream_info_->stream_type() == StreamType::kStreamVideo &&
92  sample.is_key_frame()) {
93  key_frame_infos_.push_back(
94  {static_cast<uint64_t>(pts), data_->Size(), sample.data_size()});
95  }
96 
97  data_->AppendArray(sample.data(), sample.data_size());
98 
99  traf_->runs[0].sample_composition_time_offsets.push_back(pts - dts);
100  if (pts != dts)
101  traf_->runs[0].flags |= TrackFragmentRun::kSampleCompTimeOffsetsPresentMask;
102 
103  // Exclude the part of sample with negative pts out of duration calculation as
104  // they are not presented.
105  if (pts < 0) {
106  const int64_t end_pts = pts + duration;
107  if (end_pts > 0) {
108  // Include effective presentation duration.
109  fragment_duration_ += end_pts;
110 
111  earliest_presentation_time_ = 0;
112  if (sample.is_key_frame())
113  first_sap_time_ = 0;
114  }
115  } else {
116  fragment_duration_ += duration;
117 
118  if (earliest_presentation_time_ > pts)
119  earliest_presentation_time_ = pts;
120 
121  if (sample.is_key_frame()) {
122  if (first_sap_time_ == kInvalidTime)
123  first_sap_time_ = pts;
124  }
125  }
126  return Status::OK;
127 }
128 
129 Status Fragmenter::InitializeFragment(int64_t first_sample_dts) {
130  fragment_initialized_ = true;
131  fragment_finalized_ = false;
132 
133  // |first_sample_dts| is adjusted by the edit list offset. The offset should
134  // be un-applied in |decode_time|, so when applying the Edit List, the result
135  // dts is |first_sample_dts|.
136  const int64_t dts_before_edit = first_sample_dts + edit_list_offset_;
137  traf_->decode_time.decode_time = dts_before_edit;
138 
139  traf_->runs.clear();
140  traf_->runs.resize(1);
141  traf_->runs[0].flags = TrackFragmentRun::kDataOffsetPresentMask;
142  traf_->auxiliary_size.sample_info_sizes.clear();
143  traf_->auxiliary_offset.offsets.clear();
144  traf_->sample_encryption.sample_encryption_entries.clear();
145  traf_->sample_group_descriptions.clear();
146  traf_->sample_to_groups.clear();
147  traf_->header.sample_description_index = 1; // 1-based.
148  traf_->header.flags = TrackFragmentHeader::kDefaultBaseIsMoofMask |
149  TrackFragmentHeader::kSampleDescriptionIndexPresentMask;
150 
151  fragment_duration_ = 0;
152  earliest_presentation_time_ = kInvalidTime;
153  first_sap_time_ = kInvalidTime;
154  data_.reset(new BufferWriter());
155  key_frame_infos_.clear();
156  return Status::OK;
157 }
158 
160  if (stream_info_->is_encrypted()) {
161  Status status = FinalizeFragmentForEncryption();
162  if (!status.ok())
163  return status;
164  }
165 
166  // Optimize trun box.
167  traf_->runs[0].sample_count =
168  static_cast<uint32_t>(traf_->runs[0].sample_sizes.size());
169  if (OptimizeSampleEntries(&traf_->runs[0].sample_durations,
170  &traf_->header.default_sample_duration)) {
171  traf_->header.flags |=
172  TrackFragmentHeader::kDefaultSampleDurationPresentMask;
173  } else {
174  traf_->runs[0].flags |= TrackFragmentRun::kSampleDurationPresentMask;
175  }
176  if (OptimizeSampleEntries(&traf_->runs[0].sample_sizes,
177  &traf_->header.default_sample_size)) {
178  traf_->header.flags |= TrackFragmentHeader::kDefaultSampleSizePresentMask;
179  } else {
180  traf_->runs[0].flags |= TrackFragmentRun::kSampleSizePresentMask;
181  }
182  if (OptimizeSampleEntries(&traf_->runs[0].sample_flags,
183  &traf_->header.default_sample_flags)) {
184  traf_->header.flags |= TrackFragmentHeader::kDefaultSampleFlagsPresentMask;
185  } else {
186  traf_->runs[0].flags |= TrackFragmentRun::kSampleFlagsPresentMask;
187  }
188 
189  // Add SampleToGroup boxes. A SampleToGroup box with grouping type of 'roll'
190  // needs to be added if there is seek preroll, referencing sample group
191  // description in track level; Also need to add SampleToGroup boxes
192  // correponding to every SampleGroupDescription boxes, referencing sample
193  // group description in fragment level.
194  DCHECK_EQ(traf_->sample_to_groups.size(), 0u);
195  if (seek_preroll_ > 0) {
196  traf_->sample_to_groups.resize(traf_->sample_to_groups.size() + 1);
197  SampleToGroup& sample_to_group = traf_->sample_to_groups.back();
198  sample_to_group.grouping_type = FOURCC_roll;
199 
200  sample_to_group.entries.resize(1);
201  SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
202  sample_to_group_entry.sample_count = traf_->runs[0].sample_count;
203  sample_to_group_entry.group_description_index =
204  SampleToGroupEntry::kTrackGroupDescriptionIndexBase + 1;
205  }
206  for (const auto& sample_group_description :
207  traf_->sample_group_descriptions) {
208  traf_->sample_to_groups.resize(traf_->sample_to_groups.size() + 1);
209  SampleToGroup& sample_to_group = traf_->sample_to_groups.back();
210  sample_to_group.grouping_type = sample_group_description.grouping_type;
211 
212  sample_to_group.entries.resize(1);
213  SampleToGroupEntry& sample_to_group_entry = sample_to_group.entries.back();
214  sample_to_group_entry.sample_count = traf_->runs[0].sample_count;
215  sample_to_group_entry.group_description_index =
216  SampleToGroupEntry::kTrackFragmentGroupDescriptionIndexBase + 1;
217  }
218 
219  fragment_finalized_ = true;
220  fragment_initialized_ = false;
221  return Status::OK;
222 }
223 
225  // NOTE: Daisy chain is not supported currently.
226  reference->reference_type = false;
227  reference->subsegment_duration = fragment_duration_;
228  reference->starts_with_sap = StartsWithSAP();
229  if (kInvalidTime == first_sap_time_) {
230  reference->sap_type = SegmentReference::TypeUnknown;
231  reference->sap_delta_time = 0;
232  } else {
233  reference->sap_type = SegmentReference::Type1;
234  reference->sap_delta_time = first_sap_time_ - earliest_presentation_time_;
235  }
236  reference->earliest_presentation_time = earliest_presentation_time_;
237 }
238 
239 Status Fragmenter::FinalizeFragmentForEncryption() {
240  SampleEncryption& sample_encryption = traf_->sample_encryption;
241  if (sample_encryption.sample_encryption_entries.empty()) {
242  // This fragment is not encrypted.
243  // There are two sample description entries, an encrypted entry and a clear
244  // entry, are generated. The 1-based clear entry index is always 2.
245  const uint32_t kClearSampleDescriptionIndex = 2;
246  traf_->header.sample_description_index = kClearSampleDescriptionIndex;
247  return Status::OK;
248  }
249  if (sample_encryption.sample_encryption_entries.size() !=
250  traf_->runs[0].sample_sizes.size()) {
251  LOG(ERROR) << "Partially encrypted segment is not supported";
252  return Status(error::MUXER_FAILURE,
253  "Partially encrypted segment is not supported.");
254  }
255 
256  const SampleEncryptionEntry& sample_encryption_entry =
257  sample_encryption.sample_encryption_entries.front();
258  const bool use_subsample_encryption =
259  !sample_encryption_entry.subsamples.empty();
260  if (use_subsample_encryption)
261  traf_->sample_encryption.flags |= SampleEncryption::kUseSubsampleEncryption;
262  traf_->sample_encryption.iv_size = static_cast<uint8_t>(
263  sample_encryption_entry.initialization_vector.size());
264 
265  // The offset will be adjusted in Segmenter after knowing moof size.
266  traf_->auxiliary_offset.offsets.push_back(0);
267 
268  // Optimize saiz box.
269  SampleAuxiliaryInformationSize& saiz = traf_->auxiliary_size;
270  saiz.sample_count = static_cast<uint32_t>(saiz.sample_info_sizes.size());
271  DCHECK_EQ(saiz.sample_info_sizes.size(),
272  traf_->sample_encryption.sample_encryption_entries.size());
273  if (!OptimizeSampleEntries(&saiz.sample_info_sizes,
274  &saiz.default_sample_info_size)) {
275  saiz.default_sample_info_size = 0;
276  }
277 
278  // It should only happen with full sample encryption + constant iv, i.e.
279  // 'cbcs' applying to audio.
280  if (saiz.default_sample_info_size == 0 && saiz.sample_info_sizes.empty()) {
281  DCHECK(!use_subsample_encryption);
282  // ISO/IEC 23001-7:2016(E) The sample auxiliary information would then be
283  // empty and should be omitted. Clear saiz and saio boxes so they are not
284  // written.
285  saiz.sample_count = 0;
286  traf_->auxiliary_offset.offsets.clear();
287  }
288  return Status::OK;
289 }
290 
291 bool Fragmenter::StartsWithSAP() const {
292  DCHECK(!traf_->runs.empty());
293  uint32_t start_sample_flag;
294  if (traf_->runs[0].flags & TrackFragmentRun::kSampleFlagsPresentMask) {
295  DCHECK(!traf_->runs[0].sample_flags.empty());
296  start_sample_flag = traf_->runs[0].sample_flags[0];
297  } else {
298  DCHECK(traf_->header.flags &
299  TrackFragmentHeader::kDefaultSampleFlagsPresentMask);
300  start_sample_flag = traf_->header.default_sample_flags;
301  }
302  return (start_sample_flag & TrackFragmentHeader::kNonKeySampleMask) == 0;
303 }
304 
305 } // namespace mp4
306 } // namespace media
307 } // namespace shaka
STL namespace.
All the methods that are virtual are virtual for mocking.
Status InitializeFragment(int64_t first_sample_dts)
Definition: fragmenter.cc:129
void GenerateSegmentReference(SegmentReference *reference) const
Fill reference with current fragment information.
Definition: fragmenter.cc:224
Status AddSample(const MediaSample &sample)
Definition: fragmenter.cc:65
Fragmenter(std::shared_ptr< const StreamInfo > info, TrackFragment *traf, int64_t edit_list_offset)
Definition: fragmenter.cc:50
Class to hold a media sample.
Definition: media_sample.h:22
Status FinalizeFragment()
Finalize and optimize the fragment.
Definition: fragmenter.cc:159
bool OptimizeSampleEntries(std::vector< T > *entries, T *default_value)
Definition: fragmenter.h:105