7 #include "packager/media/formats/mp4/segmenter.h"
11 #include "packager/base/stl_util.h"
12 #include "packager/media/base/buffer_writer.h"
13 #include "packager/media/base/key_source.h"
14 #include "packager/media/base/media_sample.h"
15 #include "packager/media/base/media_stream.h"
16 #include "packager/media/base/muxer_options.h"
17 #include "packager/media/base/video_stream_info.h"
18 #include "packager/media/event/muxer_listener.h"
19 #include "packager/media/event/progress_listener.h"
20 #include "packager/media/formats/mp4/box_definitions.h"
21 #include "packager/media/formats/mp4/key_rotation_fragmenter.h"
23 namespace edash_packager {
30 const size_t kDefaultIvSize = 8u;
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
41 COMPILE_ASSERT(arraysize(kKeyRotationDefaultKeyId) == kCencKeyIdSize,
42 cenc_key_id_must_be_size_16);
44 uint64_t Rescale(uint64_t time_in_old_scale,
47 return static_cast<double>(time_in_old_scale) / old_scale * new_scale;
50 void GenerateSinf(
const EncryptionKey& encryption_key,
52 ProtectionSchemeInfo* sinf) {
53 sinf->format.format = old_type;
54 sinf->type.type = FOURCC_CENC;
55 sinf->type.version = kCencSchemeVersion;
56 sinf->info.track_encryption.is_encrypted =
true;
57 sinf->info.track_encryption.default_iv_size =
58 encryption_key.iv.empty() ? kDefaultIvSize : encryption_key.iv.size();
59 sinf->info.track_encryption.default_kid = encryption_key.key_id;
62 void GenerateEncryptedSampleEntry(
const EncryptionKey& encryption_key,
63 double clear_lead_in_seconds,
64 SampleDescription* description) {
66 if (description->type == kVideo) {
67 DCHECK_EQ(1u, description->video_entries.size());
70 if (clear_lead_in_seconds > 0)
71 description->video_entries.push_back(description->video_entries[0]);
74 VideoSampleEntry& entry = description->video_entries[0];
75 GenerateSinf(encryption_key, entry.format, &entry.sinf);
76 entry.format = FOURCC_ENCV;
78 DCHECK_EQ(kAudio, description->type);
79 DCHECK_EQ(1u, description->audio_entries.size());
82 if (clear_lead_in_seconds > 0)
83 description->audio_entries.push_back(description->audio_entries[0]);
86 AudioSampleEntry& entry = description->audio_entries[0];
87 GenerateSinf(encryption_key, entry.format, &entry.sinf);
88 entry.format = FOURCC_ENCA;
92 KeySource::TrackType GetTrackTypeForEncryption(
const StreamInfo& stream_info,
93 uint32_t max_sd_pixels) {
94 if (stream_info.stream_type() == kStreamAudio)
95 return KeySource::TRACK_TYPE_AUDIO;
97 DCHECK_EQ(kStreamVideo, stream_info.stream_type());
98 const VideoStreamInfo& video_stream_info =
99 static_cast<const VideoStreamInfo&
>(stream_info);
100 uint32_t pixels = video_stream_info.width() * video_stream_info.height();
101 return (pixels > max_sd_pixels) ? KeySource::TRACK_TYPE_HD
102 : KeySource::TRACK_TYPE_SD;
107 Segmenter::Segmenter(
const MuxerOptions& options,
108 scoped_ptr<FileType> ftyp,
109 scoped_ptr<Movie> moov)
113 moof_(new MovieFragment()),
114 fragment_buffer_(new BufferWriter()),
115 sidx_(new SegmentIndex()),
116 muxer_listener_(NULL),
117 progress_listener_(NULL),
119 accumulated_progress_(0),
120 sample_duration_(0u) {}
122 Segmenter::~Segmenter() { STLDeleteElements(&fragmenters_); }
128 uint32_t max_sd_pixels,
129 double clear_lead_in_seconds,
130 double crypto_period_duration_in_seconds) {
131 DCHECK_LT(0u, streams.size());
132 muxer_listener_ = muxer_listener;
133 progress_listener_ = progress_listener;
134 moof_->header.sequence_number = 0;
136 moof_->tracks.resize(streams.size());
137 segment_durations_.resize(streams.size());
138 fragmenters_.resize(streams.size());
139 const bool key_rotation_enabled = crypto_period_duration_in_seconds != 0;
140 const bool kInitialEncryptionInfo =
true;
142 for (uint32_t i = 0; i < streams.size(); ++i) {
143 stream_map_[streams[i]] = i;
144 moof_->tracks[i].header.track_id = i + 1;
145 if (streams[i]->info()->stream_type() == kStreamVideo) {
147 if (sidx_->reference_id == 0)
148 sidx_->reference_id = i + 1;
150 if (!encryption_key_source) {
151 fragmenters_[i] =
new Fragmenter(&moof_->tracks[i]);
155 KeySource::TrackType track_type =
156 GetTrackTypeForEncryption(*streams[i]->info(), max_sd_pixels);
158 moov_->tracks[i].media.information.sample_table.description;
160 if (key_rotation_enabled) {
163 encryption_key.key_id.assign(
164 kKeyRotationDefaultKeyId,
165 kKeyRotationDefaultKeyId + arraysize(kKeyRotationDefaultKeyId));
166 GenerateEncryptedSampleEntry(encryption_key, clear_lead_in_seconds,
168 if (muxer_listener_) {
169 muxer_listener_->OnEncryptionInfoReady(
170 kInitialEncryptionInfo, encryption_key_source->
UUID(),
171 encryption_key_source->
SystemName(), encryption_key.key_id,
172 std::vector<uint8_t>());
176 moof_.get(), streams[i]->info(), &moof_->tracks[i],
177 encryption_key_source, track_type,
178 crypto_period_duration_in_seconds * streams[i]->info()->time_scale(),
179 clear_lead_in_seconds * streams[i]->info()->time_scale(),
184 scoped_ptr<EncryptionKey> encryption_key(
new EncryptionKey());
186 encryption_key_source->
GetKey(track_type, encryption_key.get());
190 GenerateEncryptedSampleEntry(*encryption_key, clear_lead_in_seconds,
194 if (moov_->pssh.empty()) {
195 moov_->pssh.resize(1);
196 moov_->pssh[0].raw_box = encryption_key->pssh;
199 if (muxer_listener_) {
200 muxer_listener_->OnEncryptionInfoReady(
201 kInitialEncryptionInfo,
202 encryption_key_source->
UUID(), encryption_key_source->
SystemName(),
203 encryption_key->key_id, encryption_key->pssh);
208 streams[i]->info(), &moof_->tracks[i], encryption_key.Pass(),
209 clear_lead_in_seconds * streams[i]->info()->time_scale());
213 if (sidx_->reference_id == 0)
214 sidx_->reference_id = 1;
215 sidx_->timescale = streams[GetReferenceStreamId()]->info()->time_scale();
218 progress_target_ = streams[GetReferenceStreamId()]->info()->duration();
221 moov_->header.timescale = sidx_->timescale;
222 moof_->header.sequence_number = 1;
225 moov_->metadata.handler.handler_type = FOURCC_ID32;
226 moov_->metadata.id3v2.language.code =
"eng";
227 moov_->metadata.id3v2.private_frame.owner =
228 "https://github.com/google/edash-packager";
230 return DoInitialize();
234 for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
235 it != fragmenters_.end();
237 Status status = FinalizeFragment(
true, *it);
245 for (std::vector<Track>::iterator track = moov_->tracks.begin();
246 track != moov_->tracks.end();
248 track->header.duration = Rescale(track->media.header.duration,
249 track->media.header.timescale,
250 moov_->header.timescale);
251 if (track->header.duration > moov_->header.duration)
252 moov_->header.duration = track->header.duration;
254 moov_->extends.header.fragment_duration = moov_->header.duration;
260 scoped_refptr<MediaSample> sample) {
263 DCHECK(stream_map_.find(stream) != stream_map_.end());
264 uint32_t stream_id = stream_map_[stream];
265 Fragmenter* fragmenter = fragmenters_[stream_id];
268 if (moov_->extends.tracks[stream_id].default_sample_duration == 0) {
269 moov_->extends.tracks[stream_id].default_sample_duration =
273 if (fragmenter->fragment_finalized()) {
274 return Status(error::FRAGMENT_FINALIZED,
275 "Current fragment is finalized already.");
278 bool finalize_fragment =
false;
279 if (fragmenter->fragment_duration() >=
282 finalize_fragment =
true;
285 bool finalize_segment =
false;
286 if (segment_durations_[stream_id] >=
289 finalize_segment =
true;
290 finalize_fragment =
true;
295 if (finalize_fragment) {
296 status = FinalizeFragment(finalize_segment, fragmenter);
305 if (sample_duration_ == 0)
306 sample_duration_ = sample->duration();
307 moov_->tracks[stream_id].media.header.duration += sample->duration();
308 segment_durations_[stream_id] += sample->duration();
309 DCHECK_GE(segment_durations_[stream_id], fragmenter->fragment_duration());
313 uint32_t Segmenter::GetReferenceTimeScale()
const {
314 return moov_->header.timescale;
318 if (moov_->header.timescale == 0) {
323 return static_cast<double>(moov_->header.duration) / moov_->header.timescale;
327 accumulated_progress_ += progress;
329 if (!progress_listener_)
return;
330 if (progress_target_ == 0)
return;
334 if (accumulated_progress_ >= progress_target_) {
337 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
342 void Segmenter::SetComplete() {
343 if (!progress_listener_)
return;
347 Status Segmenter::FinalizeSegment() {
348 Status status = DoFinalizeSegment();
351 sidx_->references.clear();
352 std::vector<uint64_t>::iterator it = segment_durations_.begin();
353 for (; it != segment_durations_.end(); ++it)
359 uint32_t Segmenter::GetReferenceStreamId() {
361 return sidx_->reference_id - 1;
364 Status Segmenter::FinalizeFragment(
bool finalize_segment,
365 Fragmenter* fragmenter) {
366 fragmenter->FinalizeFragment();
369 for (std::vector<Fragmenter*>::iterator it = fragmenters_.begin();
370 it != fragmenters_.end();
372 if (!(*it)->fragment_finalized())
379 uint64_t data_offset = moof_->ComputeSize() + mdat.HeaderSize();
381 uint64_t next_traf_position = moof_->HeaderSize() + moof_->header.box_size();
382 for (
size_t i = 0; i < moof_->tracks.size(); ++i) {
383 TrackFragment& traf = moof_->tracks[i];
384 if (traf.auxiliary_offset.offsets.size() > 0) {
385 DCHECK_EQ(traf.auxiliary_offset.offsets.size(), 1u);
386 DCHECK(!traf.sample_encryption.sample_encryption_entries.empty());
388 next_traf_position += traf.box_size();
391 traf.auxiliary_offset.offsets[0] =
392 next_traf_position - traf.sample_encryption.box_size() +
393 traf.sample_encryption.HeaderSize() +
396 traf.runs[0].data_offset = data_offset + mdat.data_size;
397 mdat.data_size += fragmenters_[i]->data()->Size();
401 sidx_->references.resize(sidx_->references.size() + 1);
402 fragmenters_[GetReferenceStreamId()]->GenerateSegmentReference(
403 &sidx_->references[sidx_->references.size() - 1]);
404 sidx_->references[sidx_->references.size() - 1].referenced_size =
405 data_offset + mdat.data_size;
408 moof_->Write(fragment_buffer_.get());
409 mdat.WriteHeader(fragment_buffer_.get());
410 for (Fragmenter* fragmenter : fragmenters_)
411 fragment_buffer_->AppendBuffer(*fragmenter->data());
414 ++moof_->header.sequence_number;
416 if (finalize_segment)
417 return FinalizeSegment();