7 #include "packager/media/formats/mp4/segmenter.h"
11 #include "packager/base/logging.h"
12 #include "packager/media/base/aes_cryptor.h"
13 #include "packager/media/base/buffer_writer.h"
14 #include "packager/media/base/key_source.h"
15 #include "packager/media/base/media_sample.h"
16 #include "packager/media/base/muxer_options.h"
17 #include "packager/media/base/muxer_util.h"
18 #include "packager/media/base/video_stream_info.h"
19 #include "packager/media/event/muxer_listener.h"
20 #include "packager/media/event/progress_listener.h"
21 #include "packager/media/formats/mp4/box_definitions.h"
22 #include "packager/media/formats/mp4/key_rotation_fragmenter.h"
23 #include "packager/version/version.h"
30 const size_t kCencKeyIdSize = 16u;
33 const int kCencSchemeVersion = 0x00010000;
36 const uint8_t kKeyRotationDefaultKeyId[] = {
37 0, 0, 0, 0, 0, 0, 0, 0,
38 0, 0, 0, 0, 0, 0, 0, 0
42 struct ProtectionPattern {
43 uint8_t crypt_byte_block;
44 uint8_t skip_byte_block;
47 static_assert(arraysize(kKeyRotationDefaultKeyId) == kCencKeyIdSize,
48 "cenc_key_id_must_be_size_16");
50 uint64_t Rescale(uint64_t time_in_old_scale,
53 return static_cast<double>(time_in_old_scale) / old_scale * new_scale;
56 ProtectionPattern GetProtectionPattern(FourCC protection_scheme,
57 TrackType track_type) {
58 ProtectionPattern pattern;
59 if (protection_scheme != FOURCC_cbcs && protection_scheme != FOURCC_cens) {
61 pattern.crypt_byte_block = 0u;
62 pattern.skip_byte_block = 0u;
63 }
else if (track_type != kVideo) {
71 pattern.crypt_byte_block = 1u;
72 pattern.skip_byte_block = 0u;
75 const uint8_t kCryptByteBlock = 1u;
76 const uint8_t kSkipByteBlock = 9u;
77 pattern.crypt_byte_block = kCryptByteBlock;
78 pattern.skip_byte_block = kSkipByteBlock;
83 void GenerateSinf(
const EncryptionKey& encryption_key,
85 FourCC protection_scheme,
86 ProtectionPattern pattern,
87 ProtectionSchemeInfo* sinf) {
88 sinf->format.format = old_type;
90 DCHECK_NE(protection_scheme, FOURCC_NULL);
91 sinf->type.type = protection_scheme;
92 sinf->type.version = kCencSchemeVersion;
94 auto& track_encryption = sinf->info.track_encryption;
95 track_encryption.default_is_protected = 1;
96 DCHECK(!encryption_key.iv.empty());
97 if (protection_scheme == FOURCC_cbcs) {
100 track_encryption.default_per_sample_iv_size = 0;
101 track_encryption.default_constant_iv = encryption_key.iv;
103 track_encryption.default_per_sample_iv_size =
104 static_cast<uint8_t
>(encryption_key.iv.size());
106 track_encryption.default_crypt_byte_block = pattern.crypt_byte_block;
107 track_encryption.default_skip_byte_block = pattern.skip_byte_block;
108 track_encryption.default_kid = encryption_key.key_id;
111 void GenerateEncryptedSampleEntry(
const EncryptionKey& encryption_key,
112 double clear_lead_in_seconds,
113 FourCC protection_scheme,
114 ProtectionPattern pattern,
115 SampleDescription* description) {
117 if (description->type == kVideo) {
118 DCHECK_EQ(1u, description->video_entries.size());
121 if (clear_lead_in_seconds > 0)
122 description->video_entries.push_back(description->video_entries[0]);
125 VideoSampleEntry& entry = description->video_entries[0];
126 GenerateSinf(encryption_key, entry.format, protection_scheme, pattern,
128 entry.format = FOURCC_encv;
130 DCHECK_EQ(kAudio, description->type);
131 DCHECK_EQ(1u, description->audio_entries.size());
134 if (clear_lead_in_seconds > 0)
135 description->audio_entries.push_back(description->audio_entries[0]);
138 AudioSampleEntry& entry = description->audio_entries[0];
139 GenerateSinf(encryption_key, entry.format, protection_scheme, pattern,
141 entry.format = FOURCC_enca;
147 Segmenter::Segmenter(
const MuxerOptions& options,
148 std::unique_ptr<FileType> ftyp,
149 std::unique_ptr<Movie> moov)
151 ftyp_(std::move(ftyp)),
152 moov_(std::move(moov)),
153 moof_(new MovieFragment()),
154 fragment_buffer_(new BufferWriter()),
155 sidx_(new SegmentIndex()),
156 muxer_listener_(NULL),
157 progress_listener_(NULL),
159 accumulated_progress_(0),
160 sample_duration_(0u) {}
162 Segmenter::~Segmenter() {}
165 const std::vector<std::shared_ptr<StreamInfo>>& streams,
169 uint32_t max_sd_pixels,
170 uint32_t max_hd_pixels,
171 uint32_t max_uhd1_pixels,
172 double clear_lead_in_seconds,
173 double crypto_period_duration_in_seconds,
174 FourCC protection_scheme) {
175 DCHECK_LT(0u, streams.size());
176 muxer_listener_ = muxer_listener;
177 progress_listener_ = progress_listener;
178 moof_->header.sequence_number = 0;
180 moof_->tracks.resize(streams.size());
181 segment_durations_.resize(streams.size());
182 fragmenters_.resize(streams.size());
183 const bool key_rotation_enabled = crypto_period_duration_in_seconds != 0;
184 const bool kInitialEncryptionInfo =
true;
186 for (uint32_t i = 0; i < streams.size(); ++i) {
187 moof_->tracks[i].header.track_id = i + 1;
188 if (streams[i]->stream_type() == kStreamVideo) {
190 if (sidx_->reference_id == 0)
191 sidx_->reference_id = i + 1;
193 if (!encryption_key_source) {
194 fragmenters_[i].reset(
new Fragmenter(streams[i], &moof_->tracks[i]));
198 KeySource::TrackType track_type = GetTrackTypeForEncryption(
199 *streams[i], max_sd_pixels, max_hd_pixels, max_uhd1_pixels);
201 moov_->tracks[i].media.information.sample_table.description;
202 ProtectionPattern pattern =
203 GetProtectionPattern(protection_scheme, description.type);
205 if (key_rotation_enabled) {
208 encryption_key.key_id.assign(
209 kKeyRotationDefaultKeyId,
210 kKeyRotationDefaultKeyId + arraysize(kKeyRotationDefaultKeyId));
212 &encryption_key.iv)) {
213 return Status(error::INTERNAL_ERROR,
"Failed to generate random iv.");
215 GenerateEncryptedSampleEntry(encryption_key, clear_lead_in_seconds,
216 protection_scheme, pattern, &description);
217 if (muxer_listener_) {
218 muxer_listener_->OnEncryptionInfoReady(
219 kInitialEncryptionInfo, protection_scheme, encryption_key.key_id,
220 encryption_key.iv, encryption_key.key_system_info);
224 moof_.get(), streams[i], &moof_->tracks[i], encryption_key_source,
226 crypto_period_duration_in_seconds * streams[i]->time_scale(),
227 clear_lead_in_seconds * streams[i]->time_scale(), protection_scheme,
228 pattern.crypt_byte_block, pattern.skip_byte_block, muxer_listener_));
232 std::unique_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
234 encryption_key_source->
GetKey(track_type, encryption_key.get());
237 if (encryption_key->iv.empty()) {
239 &encryption_key->iv)) {
240 return Status(error::INTERNAL_ERROR,
"Failed to generate random iv.");
244 GenerateEncryptedSampleEntry(*encryption_key, clear_lead_in_seconds,
245 protection_scheme, pattern, &description);
247 if (moov_->pssh.empty()) {
248 moov_->pssh.resize(encryption_key->key_system_info.size());
249 for (
size_t i = 0; i < encryption_key->key_system_info.size(); i++) {
250 moov_->pssh[i].raw_box = encryption_key->key_system_info[i].CreateBox();
253 if (muxer_listener_) {
254 muxer_listener_->OnEncryptionInfoReady(
255 kInitialEncryptionInfo, protection_scheme, encryption_key->key_id,
256 encryption_key->iv, encryption_key->key_system_info);
261 streams[i], &moof_->tracks[i], std::move(encryption_key),
262 clear_lead_in_seconds * streams[i]->time_scale(), protection_scheme,
263 pattern.crypt_byte_block, pattern.skip_byte_block, muxer_listener_));
267 for (uint32_t i = 0; i < streams.size(); ++i)
268 fragmenters_[i]->set_use_decoding_timestamp_in_timeline(
true);
272 if (sidx_->reference_id == 0)
273 sidx_->reference_id = 1;
274 sidx_->timescale = streams[GetReferenceStreamId()]->time_scale();
277 progress_target_ = streams[GetReferenceStreamId()]->duration();
280 moov_->header.timescale = sidx_->timescale;
281 moof_->header.sequence_number = 1;
284 const std::string version = GetPackagerVersion();
285 if (!version.empty()) {
286 moov_->metadata.handler.handler_type = FOURCC_ID32;
287 moov_->metadata.id3v2.language.code =
"eng";
288 moov_->metadata.id3v2.private_frame.owner = GetPackagerProjectUrl();
289 moov_->metadata.id3v2.private_frame.value = version;
291 return DoInitialize();
295 for (
const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_) {
296 Status status = FinalizeFragment(
true, fragmenter.get());
304 for (std::vector<Track>::iterator track = moov_->tracks.begin();
305 track != moov_->tracks.end();
307 track->header.duration = Rescale(track->media.header.duration,
308 track->media.header.timescale,
309 moov_->header.timescale);
310 if (track->header.duration > moov_->header.duration)
311 moov_->header.duration = track->header.duration;
313 moov_->extends.header.fragment_duration = moov_->header.duration;
319 std::shared_ptr<MediaSample> sample) {
321 const uint32_t stream_id = 0;
322 Fragmenter* fragmenter = fragmenters_[stream_id].get();
325 if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
326 moov_->extends.tracks[stream_id].default_sample_duration =
330 if (fragmenter->fragment_finalized()) {
331 return Status(error::FRAGMENT_FINALIZED,
332 "Current fragment is finalized already.");
335 bool finalize_fragment =
false;
336 if (fragmenter->fragment_duration() >=
339 finalize_fragment =
true;
342 bool finalize_segment =
false;
343 if (segment_durations_[stream_id] >=
346 finalize_segment =
true;
347 finalize_fragment =
true;
352 if (finalize_fragment) {
353 status = FinalizeFragment(finalize_segment, fragmenter);
362 if (sample_duration_ == 0)
363 sample_duration_ = sample->duration();
364 moov_->tracks[stream_id].media.header.duration += sample->duration();
365 segment_durations_[stream_id] += sample->duration();
366 DCHECK_GE(segment_durations_[stream_id], fragmenter->fragment_duration());
370 uint32_t Segmenter::GetReferenceTimeScale()
const {
371 return moov_->header.timescale;
375 if (moov_->header.timescale == 0) {
380 return static_cast<double>(moov_->header.duration) / moov_->header.timescale;
384 accumulated_progress_ += progress;
386 if (!progress_listener_)
return;
387 if (progress_target_ == 0)
return;
391 if (accumulated_progress_ >= progress_target_) {
394 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
399 void Segmenter::SetComplete() {
400 if (!progress_listener_)
return;
404 Status Segmenter::FinalizeSegment() {
405 Status status = DoFinalizeSegment();
408 sidx_->references.clear();
409 std::vector<uint64_t>::iterator it = segment_durations_.begin();
410 for (; it != segment_durations_.end(); ++it)
416 uint32_t Segmenter::GetReferenceStreamId() {
418 return sidx_->reference_id - 1;
421 Status Segmenter::FinalizeFragment(
bool finalize_segment,
422 Fragmenter* fragmenter) {
423 fragmenter->FinalizeFragment();
426 for (
const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_) {
427 if (!fragmenter->fragment_finalized())
434 uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
436 uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
437 for (
size_t i = 0; i < moof_->tracks.size(); ++i) {
438 TrackFragment& traf = moof_->tracks[i];
439 if (traf.auxiliary_offset.offsets.size() > 0) {
440 DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
441 DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
443 next_traf_position += traf.box_size();
446 traf.auxiliary_offset.offsets[0] =
447 next_traf_position - traf.sample_encryption.box_size() +
448 traf.sample_encryption.HeaderSize() +
451 traf.runs[0].data_offset = data_offset + mdat.data_size;
452 mdat.data_size +=
static_cast<uint32_t
>(fragmenters_[i]->data()->Size());
456 sidx_->references.resize(sidx_->references.size() + 1);
457 fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
458 &sidx_->references[sidx_->references.size() - 1]);
459 sidx_->references[sidx_->references.size() - 1].referenced_size =
460 data_offset + mdat.data_size;
463 moof_->Write(fragment_buffer_.get());
464 mdat.WriteHeader(fragment_buffer_.get());
465 for (
const std::unique_ptr<Fragmenter>& fragmenter : fragmenters_)
466 fragment_buffer_->AppendBuffer(*fragmenter->data());
469 ++moof_->header.sequence_number;
471 if (finalize_segment)
472 return FinalizeSegment();