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;
138 bool new_segment =
false;
140 status = NewSegment(sample->pts());
146 status = WriteFrame(
true );
147 status.Update(NewSegment(sample->pts()));
149 segment_length_sec_ = 0;
150 cluster_length_sec_ = 0;
155 status = WriteFrame(
true );
156 status.Update(NewSubsegment(sample->pts()));
157 cluster_length_sec_ = 0;
162 status = WriteFrame(
false );
171 if (new_segment && !enable_encryption_) {
172 if (sample->pts() - first_timestamp_ >=
173 clear_lead_ * info_->time_scale()) {
174 enable_encryption_ =
true;
180 status = encryptor_->EncryptFrame(sample, enable_encryption_);
182 LOG(ERROR) <<
"Error encrypting frame.";
190 const double duration_sec =
191 static_cast<double>(sample->duration()) / info_->time_scale();
192 cluster_length_sec_ += duration_sec;
193 segment_length_sec_ += duration_sec;
195 prev_sample_ = sample;
200 return static_cast<float>(segment_info_.duration()) *
201 segment_info_.timecode_scale() / kSecondsToNs;
204 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
206 const int64_t time_ns =
207 kSecondsToNs * time_timescale / info_->time_scale();
208 return time_ns / segment_info_.timecode_scale();
211 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
213 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
214 return time_ns * info_->time_scale() / kSecondsToNs;
218 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
220 if (!WriteEbmlHeader(writer))
223 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
226 const uint64_t segment_size_size = 8;
227 segment_payload_pos_ = writer->
Position() + segment_size_size;
230 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
231 segment_size_size) != 0)
233 if (!seek_head_.Write(writer))
236 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
240 if (!seek_head_.WriteVoid(writer))
244 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
245 if (!segment_info_.Write(writer))
248 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
249 if (!tracks_.Write(writer))
255 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
258 const uint64_t scale = segment_info_.timecode_scale();
259 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
260 cluster_->Init(writer);
265 accumulated_progress_ += progress;
266 if (!progress_listener_ || progress_target_ == 0)
271 if (accumulated_progress_ >= progress_target_) {
274 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
281 unsigned int seed = 0;
282 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
284 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
286 if (info->codec() == kCodecVP8) {
287 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
288 }
else if (info->codec() == kCodecVP9) {
289 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
294 if (!vp_config.
ParseMP4(info->codec_config())) {
295 return Status(error::INTERNAL_ERROR,
296 "Unable to parse VP9 codec configuration");
299 std::vector<uint8_t> codec_config;
301 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
302 return Status(error::INTERNAL_ERROR,
303 "Private codec data required for VP9 streams");
306 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
307 return Status(error::UNIMPLEMENTED,
308 "Only VP8 and VP9 video codecs are supported.");
311 track->set_uid(info->track_id());
312 if (!info->language().empty())
313 track->set_language(info->language().c_str());
314 track->set_type(mkvmuxer::Tracks::kVideo);
315 track->set_width(info->width());
316 track->set_height(info->height());
317 track->set_display_height(info->height());
318 track->set_display_width(info->width() * info->
pixel_width() /
322 encryptor_->AddTrackInfo(track);
324 tracks_.AddTrack(track, info->track_id());
325 track_id_ = track->number();
329 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
331 unsigned int seed = 0;
332 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
334 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
336 if (info->codec() == kCodecOpus) {
337 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
338 }
else if (info->codec() == kCodecVorbis) {
339 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
341 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
342 return Status(error::UNIMPLEMENTED,
343 "Only Vorbis and Opus audio codecs are supported.");
345 if (!track->SetCodecPrivate(info->codec_config().data(),
346 info->codec_config().size())) {
347 return Status(error::INTERNAL_ERROR,
348 "Private codec data required for audio streams");
351 track->set_uid(info->track_id());
352 if (!info->language().empty())
353 track->set_language(info->language().c_str());
354 track->set_type(mkvmuxer::Tracks::kAudio);
355 track->set_sample_rate(info->sampling_frequency());
356 track->set_channels(info->num_channels());
357 track->set_seek_pre_roll(info->seek_preroll_ns());
358 track->set_codec_delay(info->codec_delay_ns());
361 encryptor_->AddTrackInfo(track);
363 tracks_.AddTrack(track, info->track_id());
364 track_id_ = track->number();
368 Status Segmenter::InitializeEncryptor(KeySource* key_source,
369 uint32_t max_sd_pixels) {
370 encryptor_.reset(
new Encryptor());
371 const KeySource::TrackType track_type =
372 GetTrackTypeForEncryption(*info_, max_sd_pixels);
373 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
375 return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
376 key_source, options_.webm_subsample_encryption);
379 Status Segmenter::WriteFrame(
bool write_duration) {
383 mkvmuxer::Frame frame;
385 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
386 return Status(error::MUXER_FAILURE,
387 "Error adding sample to segment: Frame::Init failed");
390 if (write_duration) {
391 const uint64_t duration_ns =
392 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
393 frame.set_duration(duration_ns);
395 frame.set_is_key(prev_sample_->is_key_frame());
396 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
397 frame.set_track_number(track_id_);
399 if (prev_sample_->side_data_size() > 0) {
400 uint64_t block_add_id;
403 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
404 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
405 if (!frame.AddAdditionalData(
406 prev_sample_->side_data() +
sizeof(block_add_id),
407 prev_sample_->side_data_size() -
sizeof(block_add_id),
410 error::MUXER_FAILURE,
411 "Error adding sample to segment: Frame::AddAditionalData Failed");
415 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
416 const int64_t timestamp_ns =
417 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
418 frame.set_reference_block_timestamp(timestamp_ns);
423 if (cluster_->GetRelativeTimecode(frame.timestamp() /
424 cluster_->timecode_scale()) < 0) {
425 const double segment_duration =
426 static_cast<double>(frame.timestamp()) / kSecondsToNs;
427 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
428 << segment_duration <<
" seconds.";
429 return Status(error::MUXER_FAILURE,
430 "Error adding sample to segment: segment too large");
433 if (!cluster_->AddFrame(&frame)) {
434 return Status(error::MUXER_FAILURE,
435 "Error adding sample to segment: Cluster::AddFrame failed");
441 reference_frame_timestamp_ = prev_sample_->pts();