7 #include "packager/media/formats/webm/segmenter.h"
9 #include "packager/base/time/time.h"
10 #include "packager/media/base/audio_stream_info.h"
11 #include "packager/media/base/media_sample.h"
12 #include "packager/media/base/muxer_options.h"
13 #include "packager/media/base/muxer_util.h"
14 #include "packager/media/base/stream_info.h"
15 #include "packager/media/base/video_stream_info.h"
16 #include "packager/media/codecs/vp_codec_configuration_record.h"
17 #include "packager/media/event/muxer_listener.h"
18 #include "packager/media/event/progress_listener.h"
19 #include "packager/third_party/libwebm/src/mkvmuxerutil.hpp"
20 #include "packager/third_party/libwebm/src/webmids.hpp"
21 #include "packager/version/version.h"
27 int64_t kTimecodeScale = 1000000;
28 int64_t kSecondsToNs = 1000000000L;
31 Segmenter::Segmenter(
const MuxerOptions& options)
32 : reference_frame_timestamp_(0),
35 enable_encryption_(false),
37 muxer_listener_(NULL),
38 progress_listener_(NULL),
40 accumulated_progress_(0),
43 segment_payload_pos_(0),
44 cluster_length_in_time_scale_(0),
45 segment_length_in_time_scale_(0),
48 Segmenter::~Segmenter() {}
55 uint32_t max_sd_pixels,
56 uint32_t max_hd_pixels,
57 uint32_t max_uhd1_pixels,
58 double clear_lead_in_seconds) {
59 muxer_listener_ = muxer_listener;
61 clear_lead_ = clear_lead_in_seconds;
64 progress_target_ = info_->duration();
65 progress_listener_ = progress_listener;
68 segment_info_.set_timecode_scale(kTimecodeScale);
70 const std::string version = GetPackagerVersion();
71 if (!version.empty()) {
72 segment_info_.set_writing_app(
73 (GetPackagerProjectUrl() +
" version " + version).c_str());
76 if (options().segment_template.empty()) {
80 segment_info_.set_duration(1);
84 if (encryption_key_source) {
85 status = InitializeEncryptor(encryption_key_source,
94 switch (info_->stream_type()) {
96 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
99 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
102 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
103 << info_->stream_type();
104 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
109 return DoInitialize(std::move(writer));
113 Status status = WriteFrame(
true );
118 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
119 segment_info_.set_duration(FromBMFFTimescale(duration));
124 if (sample_duration_ == 0) {
125 first_timestamp_ = sample->pts();
126 sample_duration_ = sample->duration();
140 bool wrote_frame =
false;
141 bool new_segment =
false;
143 status = NewSegment(sample->pts());
147 }
else if (segment_length_in_time_scale_ >=
150 status = WriteFrame(
true );
151 status.Update(NewSegment(sample->pts()));
153 segment_length_in_time_scale_ = 0;
154 cluster_length_in_time_scale_ = 0;
157 }
else if (cluster_length_in_time_scale_ >=
160 status = WriteFrame(
true );
161 status.Update(NewSubsegment(sample->pts()));
162 cluster_length_in_time_scale_ = 0;
167 status = WriteFrame(
false );
176 if (new_segment && !enable_encryption_) {
177 if (sample->pts() - first_timestamp_ >=
178 clear_lead_ * info_->time_scale()) {
179 enable_encryption_ =
true;
185 status = encryptor_->EncryptFrame(sample, enable_encryption_);
187 LOG(ERROR) <<
"Error encrypting frame.";
195 cluster_length_in_time_scale_ += sample->duration();
196 segment_length_in_time_scale_ += sample->duration();
198 prev_sample_ = sample;
203 return static_cast<float>(segment_info_.duration()) *
204 segment_info_.timecode_scale() / kSecondsToNs;
207 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
209 const int64_t time_ns =
210 kSecondsToNs * time_timescale / info_->time_scale();
211 return time_ns / segment_info_.timecode_scale();
214 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
216 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
217 return time_ns * info_->time_scale() / kSecondsToNs;
221 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
223 if (!WriteEbmlHeader(writer))
226 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
229 const uint64_t segment_size_size = 8;
230 segment_payload_pos_ = writer->
Position() + segment_size_size;
233 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
234 segment_size_size) != 0)
236 if (!seek_head_.Write(writer))
239 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
243 if (!seek_head_.WriteVoid(writer))
247 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
248 if (!segment_info_.Write(writer))
251 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
252 if (!tracks_.Write(writer))
258 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
261 const uint64_t scale = segment_info_.timecode_scale();
262 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
263 cluster_->Init(writer);
268 accumulated_progress_ += progress;
269 if (!progress_listener_ || progress_target_ == 0)
274 if (accumulated_progress_ >= progress_target_) {
277 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
284 unsigned int seed = 0;
285 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
287 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
289 if (info->codec() == kCodecVP8) {
290 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
291 }
else if (info->codec() == kCodecVP9) {
292 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
297 if (!vp_config.
ParseMP4(info->codec_config())) {
298 return Status(error::INTERNAL_ERROR,
299 "Unable to parse VP9 codec configuration");
302 std::vector<uint8_t> codec_config;
304 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
305 return Status(error::INTERNAL_ERROR,
306 "Private codec data required for VP9 streams");
309 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
310 return Status(error::UNIMPLEMENTED,
311 "Only VP8 and VP9 video codecs are supported.");
314 track->set_uid(info->track_id());
315 if (!info->language().empty())
316 track->set_language(info->language().c_str());
317 track->set_type(mkvmuxer::Tracks::kVideo);
318 track->set_width(info->width());
319 track->set_height(info->height());
320 track->set_display_height(info->height());
321 track->set_display_width(info->width() * info->
pixel_width() /
325 encryptor_->AddTrackInfo(track);
327 tracks_.AddTrack(track, info->track_id());
328 track_id_ = track->number();
332 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
334 unsigned int seed = 0;
335 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
337 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
339 if (info->codec() == kCodecOpus) {
340 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
341 }
else if (info->codec() == kCodecVorbis) {
342 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
344 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
345 return Status(error::UNIMPLEMENTED,
346 "Only Vorbis and Opus audio codecs are supported.");
348 if (!track->SetCodecPrivate(info->codec_config().data(),
349 info->codec_config().size())) {
350 return Status(error::INTERNAL_ERROR,
351 "Private codec data required for audio streams");
354 track->set_uid(info->track_id());
355 if (!info->language().empty())
356 track->set_language(info->language().c_str());
357 track->set_type(mkvmuxer::Tracks::kAudio);
358 track->set_sample_rate(info->sampling_frequency());
359 track->set_channels(info->num_channels());
360 track->set_seek_pre_roll(info->seek_preroll_ns());
361 track->set_codec_delay(info->codec_delay_ns());
364 encryptor_->AddTrackInfo(track);
366 tracks_.AddTrack(track, info->track_id());
367 track_id_ = track->number();
371 Status Segmenter::InitializeEncryptor(KeySource* key_source,
372 uint32_t max_sd_pixels,
373 uint32_t max_hd_pixels,
374 uint32_t max_uhd1_pixels) {
375 encryptor_.reset(
new Encryptor());
376 const KeySource::TrackType track_type =
377 GetTrackTypeForEncryption(*info_, max_sd_pixels, max_hd_pixels,
379 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
381 return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
382 key_source, options_.webm_subsample_encryption);
385 Status Segmenter::WriteFrame(
bool write_duration) {
389 mkvmuxer::Frame frame;
391 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
392 return Status(error::MUXER_FAILURE,
393 "Error adding sample to segment: Frame::Init failed");
396 if (write_duration) {
397 const uint64_t duration_ns =
398 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
399 frame.set_duration(duration_ns);
401 frame.set_is_key(prev_sample_->is_key_frame());
402 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
403 frame.set_track_number(track_id_);
405 if (prev_sample_->side_data_size() > 0) {
406 uint64_t block_add_id;
409 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
410 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
411 if (!frame.AddAdditionalData(
412 prev_sample_->side_data() +
sizeof(block_add_id),
413 prev_sample_->side_data_size() -
sizeof(block_add_id),
416 error::MUXER_FAILURE,
417 "Error adding sample to segment: Frame::AddAditionalData Failed");
421 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
422 const int64_t timestamp_ns =
423 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
424 frame.set_reference_block_timestamp(timestamp_ns);
429 if (cluster_->GetRelativeTimecode(frame.timestamp() /
430 cluster_->timecode_scale()) < 0) {
431 const double segment_duration =
432 static_cast<double>(frame.timestamp()) / kSecondsToNs;
433 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
434 << segment_duration <<
" seconds.";
435 return Status(error::MUXER_FAILURE,
436 "Error adding sample to segment: segment too large");
439 if (!cluster_->AddFrame(&frame)) {
440 return Status(error::MUXER_FAILURE,
441 "Error adding sample to segment: Cluster::AddFrame failed");
447 reference_frame_timestamp_ = prev_sample_->pts();