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_sec_(0),
46 segment_length_sec_(0),
49 Segmenter::~Segmenter() {}
56 uint32_t max_sd_pixels,
57 double clear_lead_in_seconds) {
58 muxer_listener_ = muxer_listener;
60 clear_lead_ = clear_lead_in_seconds;
63 progress_target_ = info_->duration();
64 progress_listener_ = progress_listener;
67 segment_info_.set_timecode_scale(kTimecodeScale);
69 const std::string version = GetPackagerVersion();
70 if (!version.empty()) {
71 segment_info_.set_writing_app(
72 (GetPackagerProjectUrl() +
" version " + version).c_str());
75 if (options().single_segment) {
79 segment_info_.set_duration(1);
83 if (encryption_key_source) {
84 status = InitializeEncryptor(encryption_key_source,
91 switch (info_->stream_type()) {
93 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
96 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
99 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
100 << info_->stream_type();
101 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
106 return DoInitialize(std::move(writer));
110 Status status = WriteFrame(
true );
115 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
116 segment_info_.set_duration(FromBMFFTimescale(duration));
121 if (sample_duration_ == 0) {
122 first_timestamp_ = sample->pts();
123 sample_duration_ = sample->duration();
137 bool wrote_frame =
false;
139 status = NewSegment(sample->pts());
144 status = WriteFrame(
true );
145 status.Update(NewSegment(sample->pts()));
146 segment_length_sec_ = 0;
147 cluster_length_sec_ = 0;
150 if (encryptor_ && !enable_encryption_) {
151 if (sample->pts() - first_timestamp_ >=
152 clear_lead_ * info_->time_scale()) {
153 enable_encryption_ =
true;
161 status = WriteFrame(
true );
162 status.Update(NewSubsegment(sample->pts()));
163 cluster_length_sec_ = 0;
168 status = WriteFrame(
false );
175 status = encryptor_->EncryptFrame(sample, enable_encryption_);
177 LOG(ERROR) <<
"Error encrypting frame.";
185 const double duration_sec =
186 static_cast<double>(sample->duration()) / info_->time_scale();
187 cluster_length_sec_ += duration_sec;
188 segment_length_sec_ += duration_sec;
190 prev_sample_ = sample;
195 return static_cast<float>(segment_info_.duration()) *
196 segment_info_.timecode_scale() / kSecondsToNs;
199 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
201 const int64_t time_ns =
202 kSecondsToNs * time_timescale / info_->time_scale();
203 return time_ns / segment_info_.timecode_scale();
206 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
208 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
209 return time_ns * info_->time_scale() / kSecondsToNs;
213 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
215 if (!WriteEbmlHeader(writer))
218 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
221 const uint64_t segment_size_size = 8;
222 segment_payload_pos_ = writer->
Position() + segment_size_size;
225 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
226 segment_size_size) != 0)
228 if (!seek_head_.Write(writer))
231 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
235 if (!seek_head_.WriteVoid(writer))
239 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
240 if (!segment_info_.Write(writer))
243 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
244 if (!tracks_.Write(writer))
250 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
253 const uint64_t scale = segment_info_.timecode_scale();
254 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
255 cluster_->Init(writer);
260 accumulated_progress_ += progress;
261 if (!progress_listener_ || progress_target_ == 0)
266 if (accumulated_progress_ >= progress_target_) {
269 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
276 unsigned int seed = 0;
277 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
279 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
281 if (info->codec() == kCodecVP8) {
282 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
283 }
else if (info->codec() == kCodecVP9) {
284 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
289 if (!vp_config.
ParseMP4(info->codec_config())) {
290 return Status(error::INTERNAL_ERROR,
291 "Unable to parse VP9 codec configuration");
294 std::vector<uint8_t> codec_config;
296 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
297 return Status(error::INTERNAL_ERROR,
298 "Private codec data required for VP9 streams");
301 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
302 return Status(error::UNIMPLEMENTED,
303 "Only VP8 and VP9 video codecs are supported.");
306 track->set_uid(info->track_id());
307 if (!info->language().empty())
308 track->set_language(info->language().c_str());
309 track->set_type(mkvmuxer::Tracks::kVideo);
310 track->set_width(info->width());
311 track->set_height(info->height());
312 track->set_display_height(info->height());
313 track->set_display_width(info->width() * info->
pixel_width() /
317 encryptor_->AddTrackInfo(track);
319 tracks_.AddTrack(track, info->track_id());
320 track_id_ = track->number();
324 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
326 unsigned int seed = 0;
327 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
329 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
331 if (info->codec() == kCodecOpus) {
332 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
333 }
else if (info->codec() == kCodecVorbis) {
334 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
336 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
337 return Status(error::UNIMPLEMENTED,
338 "Only Vorbis and Opus audio codecs are supported.");
340 if (!track->SetCodecPrivate(info->codec_config().data(),
341 info->codec_config().size())) {
342 return Status(error::INTERNAL_ERROR,
343 "Private codec data required for audio streams");
346 track->set_uid(info->track_id());
347 if (!info->language().empty())
348 track->set_language(info->language().c_str());
349 track->set_type(mkvmuxer::Tracks::kAudio);
350 track->set_sample_rate(info->sampling_frequency());
351 track->set_channels(info->num_channels());
352 track->set_seek_pre_roll(info->seek_preroll_ns());
353 track->set_codec_delay(info->codec_delay_ns());
356 encryptor_->AddTrackInfo(track);
358 tracks_.AddTrack(track, info->track_id());
359 track_id_ = track->number();
363 Status Segmenter::InitializeEncryptor(KeySource* key_source,
364 uint32_t max_sd_pixels) {
365 encryptor_.reset(
new Encryptor());
366 const KeySource::TrackType track_type =
367 GetTrackTypeForEncryption(*info_, max_sd_pixels);
368 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
370 return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
371 key_source, options_.webm_subsample_encryption);
374 Status Segmenter::WriteFrame(
bool write_duration) {
378 mkvmuxer::Frame frame;
380 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
381 return Status(error::MUXER_FAILURE,
382 "Error adding sample to segment: Frame::Init failed");
385 if (write_duration) {
386 const uint64_t duration_ns =
387 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
388 frame.set_duration(duration_ns);
390 frame.set_is_key(prev_sample_->is_key_frame());
391 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
392 frame.set_track_number(track_id_);
394 if (prev_sample_->side_data_size() > 0) {
395 uint64_t block_add_id;
398 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
399 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
400 if (!frame.AddAdditionalData(
401 prev_sample_->side_data() +
sizeof(block_add_id),
402 prev_sample_->side_data_size() -
sizeof(block_add_id),
405 error::MUXER_FAILURE,
406 "Error adding sample to segment: Frame::AddAditionalData Failed");
410 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
411 const int64_t timestamp_ns =
412 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
413 frame.set_reference_block_timestamp(timestamp_ns);
418 if (cluster_->GetRelativeTimecode(frame.timestamp() /
419 cluster_->timecode_scale()) < 0) {
420 const double segment_duration =
421 static_cast<double>(frame.timestamp()) / kSecondsToNs;
422 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
423 << segment_duration <<
" seconds.";
424 return Status(error::MUXER_FAILURE,
425 "Error adding sample to segment: segment too large");
428 if (!cluster_->AddFrame(&frame)) {
429 return Status(error::MUXER_FAILURE,
430 "Error adding sample to segment: Cluster::AddFrame failed");
436 reference_frame_timestamp_ = prev_sample_->pts();