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