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/media_stream.h"
13 #include "packager/media/base/muxer_options.h"
14 #include "packager/media/base/muxer_util.h"
15 #include "packager/media/base/stream_info.h"
16 #include "packager/media/base/video_stream_info.h"
17 #include "packager/media/codecs/vp_codec_configuration_record.h"
18 #include "packager/media/event/muxer_listener.h"
19 #include "packager/media/event/progress_listener.h"
20 #include "packager/third_party/libwebm/src/mkvmuxerutil.hpp"
21 #include "packager/third_party/libwebm/src/webmids.hpp"
22 #include "packager/version/version.h"
28 int64_t kTimecodeScale = 1000000;
29 int64_t kSecondsToNs = 1000000000L;
32 Segmenter::Segmenter(
const MuxerOptions& options)
33 : reference_frame_timestamp_(0),
36 enable_encryption_(false),
38 muxer_listener_(NULL),
39 progress_listener_(NULL),
41 accumulated_progress_(0),
44 segment_payload_pos_(0),
45 cluster_length_in_time_scale_(0),
46 segment_length_in_time_scale_(0),
49 Segmenter::~Segmenter() {}
56 uint32_t max_sd_pixels,
57 uint32_t max_hd_pixels,
58 uint32_t max_uhd1_pixels,
59 double clear_lead_in_seconds) {
60 muxer_listener_ = muxer_listener;
62 clear_lead_ = clear_lead_in_seconds;
65 progress_target_ = info_->duration();
66 progress_listener_ = progress_listener;
69 segment_info_.set_timecode_scale(kTimecodeScale);
71 const std::string version = GetPackagerVersion();
72 if (!version.empty()) {
73 segment_info_.set_writing_app(
74 (GetPackagerProjectUrl() +
" version " + version).c_str());
77 if (options().segment_template.empty()) {
81 segment_info_.set_duration(1);
85 if (encryption_key_source) {
86 status = InitializeEncryptor(encryption_key_source,
95 switch (info_->stream_type()) {
97 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
100 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
103 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
104 << info_->stream_type();
105 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
110 return DoInitialize(std::move(writer));
114 Status status = WriteFrame(
true );
119 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
120 segment_info_.set_duration(FromBMFFTimescale(duration));
125 if (sample_duration_ == 0) {
126 first_timestamp_ = sample->pts();
127 sample_duration_ = sample->duration();
141 bool wrote_frame =
false;
142 bool new_segment =
false;
144 status = NewSegment(sample->pts());
148 }
else if (segment_length_in_time_scale_ >=
151 status = WriteFrame(
true );
152 status.Update(NewSegment(sample->pts()));
154 segment_length_in_time_scale_ = 0;
155 cluster_length_in_time_scale_ = 0;
158 }
else if (cluster_length_in_time_scale_ >=
161 status = WriteFrame(
true );
162 status.Update(NewSubsegment(sample->pts()));
163 cluster_length_in_time_scale_ = 0;
168 status = WriteFrame(
false );
177 if (new_segment && !enable_encryption_) {
178 if (sample->pts() - first_timestamp_ >=
179 clear_lead_ * info_->time_scale()) {
180 enable_encryption_ =
true;
186 status = encryptor_->EncryptFrame(sample, enable_encryption_);
188 LOG(ERROR) <<
"Error encrypting frame.";
196 cluster_length_in_time_scale_ += sample->duration();
197 segment_length_in_time_scale_ += sample->duration();
199 prev_sample_ = sample;
204 return static_cast<float>(segment_info_.duration()) *
205 segment_info_.timecode_scale() / kSecondsToNs;
208 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
210 const int64_t time_ns =
211 kSecondsToNs * time_timescale / info_->time_scale();
212 return time_ns / segment_info_.timecode_scale();
215 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
217 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
218 return time_ns * info_->time_scale() / kSecondsToNs;
222 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
224 if (!WriteEbmlHeader(writer))
227 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
230 const uint64_t segment_size_size = 8;
231 segment_payload_pos_ = writer->
Position() + segment_size_size;
234 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
235 segment_size_size) != 0)
237 if (!seek_head_.Write(writer))
240 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
244 if (!seek_head_.WriteVoid(writer))
248 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
249 if (!segment_info_.Write(writer))
252 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
253 if (!tracks_.Write(writer))
259 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
262 const uint64_t scale = segment_info_.timecode_scale();
263 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
264 cluster_->Init(writer);
269 accumulated_progress_ += progress;
270 if (!progress_listener_ || progress_target_ == 0)
275 if (accumulated_progress_ >= progress_target_) {
278 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
285 unsigned int seed = 0;
286 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
288 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
290 if (info->codec() == kCodecVP8) {
291 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
292 }
else if (info->codec() == kCodecVP9) {
293 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
298 if (!vp_config.
ParseMP4(info->codec_config())) {
299 return Status(error::INTERNAL_ERROR,
300 "Unable to parse VP9 codec configuration");
303 std::vector<uint8_t> codec_config;
305 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
306 return Status(error::INTERNAL_ERROR,
307 "Private codec data required for VP9 streams");
310 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
311 return Status(error::UNIMPLEMENTED,
312 "Only VP8 and VP9 video codecs are supported.");
315 track->set_uid(info->track_id());
316 if (!info->language().empty())
317 track->set_language(info->language().c_str());
318 track->set_type(mkvmuxer::Tracks::kVideo);
319 track->set_width(info->width());
320 track->set_height(info->height());
321 track->set_display_height(info->height());
322 track->set_display_width(info->width() * info->
pixel_width() /
326 encryptor_->AddTrackInfo(track);
328 tracks_.AddTrack(track, info->track_id());
329 track_id_ = track->number();
333 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
335 unsigned int seed = 0;
336 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
338 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
340 if (info->codec() == kCodecOpus) {
341 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
342 }
else if (info->codec() == kCodecVorbis) {
343 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
345 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
346 return Status(error::UNIMPLEMENTED,
347 "Only Vorbis and Opus audio codecs are supported.");
349 if (!track->SetCodecPrivate(info->codec_config().data(),
350 info->codec_config().size())) {
351 return Status(error::INTERNAL_ERROR,
352 "Private codec data required for audio streams");
355 track->set_uid(info->track_id());
356 if (!info->language().empty())
357 track->set_language(info->language().c_str());
358 track->set_type(mkvmuxer::Tracks::kAudio);
359 track->set_sample_rate(info->sampling_frequency());
360 track->set_channels(info->num_channels());
361 track->set_seek_pre_roll(info->seek_preroll_ns());
362 track->set_codec_delay(info->codec_delay_ns());
365 encryptor_->AddTrackInfo(track);
367 tracks_.AddTrack(track, info->track_id());
368 track_id_ = track->number();
372 Status Segmenter::InitializeEncryptor(KeySource* key_source,
373 uint32_t max_sd_pixels,
374 uint32_t max_hd_pixels,
375 uint32_t max_uhd1_pixels) {
376 encryptor_.reset(
new Encryptor());
377 const KeySource::TrackType track_type =
378 GetTrackTypeForEncryption(*info_, max_sd_pixels, max_hd_pixels,
380 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
382 return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
383 key_source, options_.webm_subsample_encryption);
386 Status Segmenter::WriteFrame(
bool write_duration) {
390 mkvmuxer::Frame frame;
392 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
393 return Status(error::MUXER_FAILURE,
394 "Error adding sample to segment: Frame::Init failed");
397 if (write_duration) {
398 const uint64_t duration_ns =
399 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
400 frame.set_duration(duration_ns);
402 frame.set_is_key(prev_sample_->is_key_frame());
403 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
404 frame.set_track_number(track_id_);
406 if (prev_sample_->side_data_size() > 0) {
407 uint64_t block_add_id;
410 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
411 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
412 if (!frame.AddAdditionalData(
413 prev_sample_->side_data() +
sizeof(block_add_id),
414 prev_sample_->side_data_size() -
sizeof(block_add_id),
417 error::MUXER_FAILURE,
418 "Error adding sample to segment: Frame::AddAditionalData Failed");
422 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
423 const int64_t timestamp_ns =
424 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
425 frame.set_reference_block_timestamp(timestamp_ns);
430 if (cluster_->GetRelativeTimecode(frame.timestamp() /
431 cluster_->timecode_scale()) < 0) {
432 const double segment_duration =
433 static_cast<double>(frame.timestamp()) / kSecondsToNs;
434 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
435 << segment_duration <<
" seconds.";
436 return Status(error::MUXER_FAILURE,
437 "Error adding sample to segment: segment too large");
440 if (!cluster_->AddFrame(&frame)) {
441 return Status(error::MUXER_FAILURE,
442 "Error adding sample to segment: Cluster::AddFrame failed");
448 reference_frame_timestamp_ = prev_sample_->pts();