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 muxer_listener_(NULL),
37 progress_listener_(NULL),
39 accumulated_progress_(0),
42 segment_payload_pos_(0),
43 cluster_length_sec_(0),
44 segment_length_sec_(0),
47 Segmenter::~Segmenter() {}
54 uint32_t max_sd_pixels,
55 double clear_lead_in_seconds) {
56 muxer_listener_ = muxer_listener;
58 clear_lead_ = clear_lead_in_seconds;
61 progress_target_ = info_->duration();
62 progress_listener_ = progress_listener;
65 segment_info_.set_timecode_scale(kTimecodeScale);
67 const std::string version = GetPackagerVersion();
68 if (!version.empty()) {
69 segment_info_.set_writing_app(
70 (GetPackagerProjectUrl() +
" version " + version).c_str());
73 if (options().single_segment) {
77 segment_info_.set_duration(1);
81 if (encryption_key_source) {
82 status = InitializeEncryptor(encryption_key_source, max_sd_pixels);
88 switch (info_->stream_type()) {
90 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
93 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
96 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
97 << info_->stream_type();
98 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
103 return DoInitialize(writer.Pass());
107 Status status = WriteFrame(
true );
112 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
113 segment_info_.set_duration(FromBMFFTimescale(duration));
118 if (sample_duration_ == 0) {
119 first_timestamp_ = sample->pts();
120 sample_duration_ = sample->duration();
134 bool wrote_frame =
false;
136 status = NewSegment(sample->pts());
141 status = WriteFrame(
true );
142 status.Update(NewSegment(sample->pts()));
143 segment_length_sec_ = 0;
144 cluster_length_sec_ = 0;
149 status = WriteFrame(
true );
150 status.Update(NewSubsegment(sample->pts()));
151 cluster_length_sec_ = 0;
156 status = WriteFrame(
false );
163 const bool encrypt_frame =
164 static_cast<double>(sample->pts() - first_timestamp_) /
165 info_->time_scale() >=
167 status = encryptor_->EncryptFrame(sample, encrypt_frame);
169 LOG(ERROR) <<
"Error encrypting frame.";
172 if (encrypt_frame && muxer_listener_)
180 const double duration_sec =
181 static_cast<double>(sample->duration()) / info_->time_scale();
182 cluster_length_sec_ += duration_sec;
183 segment_length_sec_ += duration_sec;
185 prev_sample_ = sample;
190 return static_cast<float>(segment_info_.duration()) *
191 segment_info_.timecode_scale() / kSecondsToNs;
194 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
196 const int64_t time_ns =
197 kSecondsToNs * time_timescale / info_->time_scale();
198 return time_ns / segment_info_.timecode_scale();
201 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
203 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
204 return time_ns * info_->time_scale() / kSecondsToNs;
208 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
210 if (!WriteEbmlHeader(writer))
213 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
216 const uint64_t segment_size_size = 8;
217 segment_payload_pos_ = writer->
Position() + segment_size_size;
220 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
221 segment_size_size) != 0)
223 if (!seek_head_.Write(writer))
226 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
230 if (!seek_head_.WriteVoid(writer))
234 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
235 if (!segment_info_.Write(writer))
238 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
239 if (!tracks_.Write(writer))
245 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
248 const uint64_t scale = segment_info_.timecode_scale();
249 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
250 cluster_->Init(writer);
255 accumulated_progress_ += progress;
256 if (!progress_listener_ || progress_target_ == 0)
261 if (accumulated_progress_ >= progress_target_) {
264 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
271 unsigned int seed = 0;
272 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
274 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
276 if (info->codec() == kCodecVP8) {
277 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
278 }
else if (info->codec() == kCodecVP9) {
279 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
284 if (!vp_config.
ParseMP4(info->codec_config())) {
285 return Status(error::INTERNAL_ERROR,
286 "Unable to parse VP9 codec configuration");
289 std::vector<uint8_t> codec_config;
291 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
292 return Status(error::INTERNAL_ERROR,
293 "Private codec data required for VP9 streams");
296 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
297 return Status(error::UNIMPLEMENTED,
298 "Only VP8 and VP9 video codecs are supported.");
301 track->set_uid(info->track_id());
302 if (!info->language().empty())
303 track->set_language(info->language().c_str());
304 track->set_type(mkvmuxer::Tracks::kVideo);
305 track->set_width(info->width());
306 track->set_height(info->height());
307 track->set_display_height(info->height());
308 track->set_display_width(info->width() * info->
pixel_width() /
312 encryptor_->AddTrackInfo(track);
314 tracks_.AddTrack(track, info->track_id());
315 track_id_ = track->number();
319 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
321 unsigned int seed = 0;
322 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
324 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
326 if (info->codec() == kCodecOpus) {
327 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
328 }
else if (info->codec() == kCodecVorbis) {
329 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
331 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
332 return Status(error::UNIMPLEMENTED,
333 "Only Vorbis and Opus audio codecs are supported.");
335 if (!track->SetCodecPrivate(info->codec_config().data(),
336 info->codec_config().size())) {
337 return Status(error::INTERNAL_ERROR,
338 "Private codec data required for audio streams");
341 track->set_uid(info->track_id());
342 if (!info->language().empty())
343 track->set_language(info->language().c_str());
344 track->set_type(mkvmuxer::Tracks::kAudio);
345 track->set_sample_rate(info->sampling_frequency());
346 track->set_channels(info->num_channels());
347 track->set_seek_pre_roll(info->seek_preroll_ns());
348 track->set_codec_delay(info->codec_delay_ns());
351 encryptor_->AddTrackInfo(track);
353 tracks_.AddTrack(track, info->track_id());
354 track_id_ = track->number();
358 Status Segmenter::InitializeEncryptor(KeySource* key_source,
359 uint32_t max_sd_pixels) {
360 encryptor_.reset(
new Encryptor());
361 const KeySource::TrackType track_type =
362 GetTrackTypeForEncryption(*info_, max_sd_pixels);
363 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
365 return encryptor_->Initialize(muxer_listener_, track_type, key_source);
368 Status Segmenter::WriteFrame(
bool write_duration) {
372 mkvmuxer::Frame frame;
374 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
375 return Status(error::MUXER_FAILURE,
376 "Error adding sample to segment: Frame::Init failed");
379 if (write_duration) {
380 const uint64_t duration_ns =
381 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
382 frame.set_duration(duration_ns);
384 frame.set_is_key(prev_sample_->is_key_frame());
385 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
386 frame.set_track_number(track_id_);
388 if (prev_sample_->side_data_size() > 0) {
389 uint64_t block_add_id;
392 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
393 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
394 if (!frame.AddAdditionalData(
395 prev_sample_->side_data() +
sizeof(block_add_id),
396 prev_sample_->side_data_size() -
sizeof(block_add_id),
399 error::MUXER_FAILURE,
400 "Error adding sample to segment: Frame::AddAditionalData Failed");
404 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
405 const int64_t timestamp_ns =
406 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
407 frame.set_reference_block_timestamp(timestamp_ns);
412 if (cluster_->GetRelativeTimecode(frame.timestamp() /
413 cluster_->timecode_scale()) < 0) {
414 const double segment_duration =
415 static_cast<double>(frame.timestamp()) / kSecondsToNs;
416 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
417 << segment_duration <<
" seconds.";
418 return Status(error::MUXER_FAILURE,
419 "Error adding sample to segment: segment too large");
422 if (!cluster_->AddFrame(&frame)) {
423 return Status(error::MUXER_FAILURE,
424 "Error adding sample to segment: Cluster::AddFrame failed");
430 reference_frame_timestamp_ = prev_sample_->pts();