7 #include "packager/media/formats/mp4/segmenter.h"
11 #include "packager/base/logging.h"
12 #include "packager/base/stl_util.h"
13 #include "packager/media/base/aes_cryptor.h"
14 #include "packager/media/base/buffer_writer.h"
15 #include "packager/media/base/key_source.h"
16 #include "packager/media/base/media_sample.h"
17 #include "packager/media/base/media_stream.h"
18 #include "packager/media/base/muxer_options.h"
19 #include "packager/media/base/muxer_util.h"
20 #include "packager/media/base/video_stream_info.h"
21 #include "packager/media/event/muxer_listener.h"
22 #include "packager/media/event/progress_listener.h"
23 #include "packager/media/formats/mp4/box_definitions.h"
24 #include "packager/media/formats/mp4/key_rotation_fragmenter.h"
31 const size_t kCencKeyIdSize = 16u;
34 const int kCencSchemeVersion = 0x00010000;
37 const uint8_t kKeyRotationDefaultKeyId[] = {
38 0, 0, 0, 0, 0, 0, 0, 0,
39 0, 0, 0, 0, 0, 0, 0, 0
43 struct ProtectionPattern {
44 uint8_t crypt_byte_block;
45 uint8_t skip_byte_block;
48 COMPILE_ASSERT(arraysize(kKeyRotationDefaultKeyId) == kCencKeyIdSize,
49 cenc_key_id_must_be_size_16);
51 uint64_t Rescale(uint64_t time_in_old_scale,
54 return static_cast<double>(time_in_old_scale) / old_scale * new_scale;
57 ProtectionPattern GetProtectionPattern(FourCC protection_scheme,
58 TrackType track_type) {
59 ProtectionPattern pattern;
60 if (protection_scheme != FOURCC_cbcs && protection_scheme != FOURCC_cens) {
62 pattern.crypt_byte_block = 0u;
63 pattern.skip_byte_block = 0u;
64 }
else if (track_type != kVideo) {
72 pattern.crypt_byte_block = 1u;
73 pattern.skip_byte_block = 0u;
76 const uint8_t kCryptByteBlock = 1u;
77 const uint8_t kSkipByteBlock = 9u;
78 pattern.crypt_byte_block = kCryptByteBlock;
79 pattern.skip_byte_block = kSkipByteBlock;
84 void GenerateSinf(
const EncryptionKey& encryption_key,
86 FourCC protection_scheme,
87 ProtectionPattern pattern,
88 ProtectionSchemeInfo* sinf) {
89 sinf->format.format = old_type;
91 DCHECK_NE(protection_scheme, FOURCC_NULL);
92 sinf->type.type = protection_scheme;
93 sinf->type.version = kCencSchemeVersion;
95 auto& track_encryption = sinf->info.track_encryption;
96 track_encryption.default_is_protected = 1;
97 DCHECK(!encryption_key.iv.empty());
98 if (protection_scheme == FOURCC_cbcs) {
101 track_encryption.default_per_sample_iv_size = 0;
102 track_encryption.default_constant_iv = encryption_key.iv;
104 track_encryption.default_per_sample_iv_size = 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 scoped_ptr<FileType> ftyp,
149 scoped_ptr<Movie> 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() { STLDeleteElements(&fragmenters_); }
168 uint32_t max_sd_pixels,
169 double clear_lead_in_seconds,
170 double crypto_period_duration_in_seconds,
171 FourCC protection_scheme) {
172 DCHECK_LT(0u, streams.size());
173 muxer_listener_ = muxer_listener;
174 progress_listener_ = progress_listener;
175 moof_->header.sequence_number = 0;
177 moof_->tracks.resize(streams.size());
178 segment_durations_.resize(streams.size());
179 fragmenters_.resize(streams.size());
180 const bool key_rotation_enabled = crypto_period_duration_in_seconds != 0;
181 const bool kInitialEncryptionInfo =
true;
183 for (uint32_t i = 0; i < streams.size(); ++i) {
184 stream_map_[streams[i]] = i;
185 moof_->tracks[i].header.track_id = i + 1;
186 if (streams[i]->info()->stream_type() == kStreamVideo) {
188 if (sidx_->reference_id == 0)
189 sidx_->reference_id = i + 1;
191 if (!encryption_key_source) {
192 fragmenters_[i] =
new Fragmenter(streams[i]->info(), &moof_->tracks[i]);
196 KeySource::TrackType track_type =
197 GetTrackTypeForEncryption(*streams[i]->info(), max_sd_pixels);
199 moov_->tracks[i].media.information.sample_table.description;
200 ProtectionPattern pattern =
201 GetProtectionPattern(protection_scheme, description.type);
203 if (key_rotation_enabled) {
206 encryption_key.key_id.assign(
207 kKeyRotationDefaultKeyId,
208 kKeyRotationDefaultKeyId + arraysize(kKeyRotationDefaultKeyId));
210 &encryption_key.iv)) {
211 return Status(error::INTERNAL_ERROR,
"Failed to generate random iv.");
213 GenerateEncryptedSampleEntry(encryption_key, clear_lead_in_seconds,
214 protection_scheme, pattern, &description);
215 if (muxer_listener_) {
216 muxer_listener_->OnEncryptionInfoReady(
217 kInitialEncryptionInfo, protection_scheme, encryption_key.key_id,
218 encryption_key.iv, encryption_key.key_system_info);
222 moof_.get(), streams[i]->info(), &moof_->tracks[i],
223 encryption_key_source, track_type,
224 crypto_period_duration_in_seconds * streams[i]->info()->time_scale(),
225 clear_lead_in_seconds * streams[i]->info()->time_scale(),
226 protection_scheme, pattern.crypt_byte_block, pattern.skip_byte_block,
231 scoped_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
233 encryption_key_source->
GetKey(track_type, encryption_key.get());
236 if (encryption_key->iv.empty()) {
238 &encryption_key->iv)) {
239 return Status(error::INTERNAL_ERROR,
"Failed to generate random iv.");
243 GenerateEncryptedSampleEntry(*encryption_key, clear_lead_in_seconds,
244 protection_scheme, pattern, &description);
246 if (moov_->pssh.empty()) {
247 moov_->pssh.resize(encryption_key->key_system_info.size());
248 for (
size_t i = 0; i < encryption_key->key_system_info.size(); i++) {
249 moov_->pssh[i].raw_box = encryption_key->key_system_info[i].CreateBox();
252 if (muxer_listener_) {
253 muxer_listener_->OnEncryptionInfoReady(
254 kInitialEncryptionInfo, protection_scheme, encryption_key->key_id,
255 encryption_key->iv, encryption_key->key_system_info);
260 streams[i]->info(), &moof_->tracks[i], encryption_key.Pass(),
261 clear_lead_in_seconds * streams[i]->info()->time_scale(),
262 protection_scheme, pattern.crypt_byte_block, pattern.skip_byte_block,
267 if (sidx_->reference_id == 0)
268 sidx_->reference_id = 1;
269 sidx_->timescale = streams[GetReferenceStreamId()]->info()->time_scale();
272 progress_target_ = streams[GetReferenceStreamId()]->info()->duration();
275 moov_->header.timescale = sidx_->timescale;
276 moof_->header.sequence_number = 1;
279 moov_->metadata.handler.handler_type = FOURCC_ID32;
280 moov_->metadata.id3v2.language.code =
"eng";
281 moov_->metadata.id3v2.private_frame.owner =
282 "https://github.com/google/shaka-packager";
284 return DoInitialize();
288 for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
289 it != fragmenters_.end();
291 Status status = FinalizeFragment(
true, *it);
299 for (std::vector<Track>::iterator track = moov_->tracks.begin();
300 track != moov_->tracks.end();
302 track->header.duration = Rescale(track->media.header.duration,
303 track->media.header.timescale,
304 moov_->header.timescale);
305 if (track->header.duration > moov_->header.duration)
306 moov_->header.duration = track->header.duration;
308 moov_->extends.header.fragment_duration = moov_->header.duration;
314 scoped_refptr<MediaSample> sample) {
317 DCHECK(stream_map_.find(stream) != stream_map_.end());
318 uint32_t stream_id = stream_map_[stream];
319 Fragmenter* fragmenter = fragmenters_[stream_id];
322 if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
323 moov_->extends.tracks[stream_id].default_sample_duration =
327 if (fragmenter->fragment_finalized()) {
328 return Status(error::FRAGMENT_FINALIZED,
329 "Current fragment is finalized already.");
332 bool finalize_fragment =
false;
333 if (fragmenter->fragment_duration() >=
336 finalize_fragment =
true;
339 bool finalize_segment =
false;
340 if (segment_durations_[stream_id] >=
343 finalize_segment =
true;
344 finalize_fragment =
true;
349 if (finalize_fragment) {
350 status = FinalizeFragment(finalize_segment, fragmenter);
359 if (sample_duration_ == 0)
360 sample_duration_ = sample->duration();
361 moov_->tracks[stream_id].media.header.duration += sample->duration();
362 segment_durations_[stream_id] += sample->duration();
363 DCHECK_GE(segment_durations_[stream_id], fragmenter->fragment_duration());
367 uint32_t Segmenter::GetReferenceTimeScale()
const {
368 return moov_->header.timescale;
372 if (moov_->header.timescale == 0) {
377 return static_cast<double>(moov_->header.duration) / moov_->header.timescale;
381 accumulated_progress_ += progress;
383 if (!progress_listener_)
return;
384 if (progress_target_ == 0)
return;
388 if (accumulated_progress_ >= progress_target_) {
391 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
396 void Segmenter::SetComplete() {
397 if (!progress_listener_)
return;
401 Status Segmenter::FinalizeSegment() {
402 Status status = DoFinalizeSegment();
405 sidx_->references.clear();
406 std::vector<uint64_t>::iterator it = segment_durations_.begin();
407 for (; it != segment_durations_.end(); ++it)
413 uint32_t Segmenter::GetReferenceStreamId() {
415 return sidx_->reference_id - 1;
418 Status Segmenter::FinalizeFragment(
bool finalize_segment,
419 Fragmenter* fragmenter) {
420 fragmenter->FinalizeFragment();
423 for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
424 it != fragmenters_.end();
426 if (!(*it)->fragment_finalized())
433 uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
435 uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
436 for (
size_t i = 0; i < moof_->tracks.size(); ++i) {
437 TrackFragment& traf = moof_->tracks[i];
438 if (traf.auxiliary_offset.offsets.size() > 0) {
439 DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
440 DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
442 next_traf_position += traf.box_size();
445 traf.auxiliary_offset.offsets[0] =
446 next_traf_position - traf.sample_encryption.box_size() +
447 traf.sample_encryption.HeaderSize() +
450 traf.runs[0].data_offset = data_offset + mdat.data_size;
451 mdat.data_size += fragmenters_[i]->data()->Size();
455 sidx_->references.resize(sidx_->references.size() + 1);
456 fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
457 &sidx_->references[sidx_->references.size() - 1]);
458 sidx_->references[sidx_->references.size() - 1].referenced_size =
459 data_offset + mdat.data_size;
462 moof_->Write(fragment_buffer_.get());
463 mdat.WriteHeader(fragment_buffer_.get());
464 for (Fragmenter* fragmenter : fragmenters_)
465 fragment_buffer_->AppendBuffer(*fragmenter->data());
468 ++moof_->header.sequence_number;
470 if (finalize_segment)
471 return FinalizeSegment();