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,
89 switch (info_->stream_type()) {
91 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
94 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
97 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
98 << info_->stream_type();
99 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
104 return DoInitialize(writer.Pass());
108 Status status = WriteFrame(
true );
113 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
114 segment_info_.set_duration(FromBMFFTimescale(duration));
119 if (sample_duration_ == 0) {
120 first_timestamp_ = sample->pts();
121 sample_duration_ = sample->duration();
135 bool wrote_frame =
false;
137 status = NewSegment(sample->pts());
142 status = WriteFrame(
true );
143 status.Update(NewSegment(sample->pts()));
144 segment_length_sec_ = 0;
145 cluster_length_sec_ = 0;
150 status = WriteFrame(
true );
151 status.Update(NewSubsegment(sample->pts()));
152 cluster_length_sec_ = 0;
157 status = WriteFrame(
false );
164 const bool encrypt_frame =
165 static_cast<double>(sample->pts() - first_timestamp_) /
166 info_->time_scale() >=
168 status = encryptor_->EncryptFrame(sample, encrypt_frame);
170 LOG(ERROR) <<
"Error encrypting frame.";
173 if (encrypt_frame && muxer_listener_)
181 const double duration_sec =
182 static_cast<double>(sample->duration()) / info_->time_scale();
183 cluster_length_sec_ += duration_sec;
184 segment_length_sec_ += duration_sec;
186 prev_sample_ = sample;
191 return static_cast<float>(segment_info_.duration()) *
192 segment_info_.timecode_scale() / kSecondsToNs;
195 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
197 const int64_t time_ns =
198 kSecondsToNs * time_timescale / info_->time_scale();
199 return time_ns / segment_info_.timecode_scale();
202 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
204 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
205 return time_ns * info_->time_scale() / kSecondsToNs;
209 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
211 if (!WriteEbmlHeader(writer))
214 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
217 const uint64_t segment_size_size = 8;
218 segment_payload_pos_ = writer->
Position() + segment_size_size;
221 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
222 segment_size_size) != 0)
224 if (!seek_head_.Write(writer))
227 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
231 if (!seek_head_.WriteVoid(writer))
235 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
236 if (!segment_info_.Write(writer))
239 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
240 if (!tracks_.Write(writer))
246 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
249 const uint64_t scale = segment_info_.timecode_scale();
250 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
251 cluster_->Init(writer);
256 accumulated_progress_ += progress;
257 if (!progress_listener_ || progress_target_ == 0)
262 if (accumulated_progress_ >= progress_target_) {
265 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
272 unsigned int seed = 0;
273 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
275 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
277 if (info->codec() == kCodecVP8) {
278 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
279 }
else if (info->codec() == kCodecVP9) {
280 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
285 if (!vp_config.
ParseMP4(info->codec_config())) {
286 return Status(error::INTERNAL_ERROR,
287 "Unable to parse VP9 codec configuration");
290 std::vector<uint8_t> codec_config;
292 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
293 return Status(error::INTERNAL_ERROR,
294 "Private codec data required for VP9 streams");
297 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
298 return Status(error::UNIMPLEMENTED,
299 "Only VP8 and VP9 video codecs are supported.");
302 track->set_uid(info->track_id());
303 if (!info->language().empty())
304 track->set_language(info->language().c_str());
305 track->set_type(mkvmuxer::Tracks::kVideo);
306 track->set_width(info->width());
307 track->set_height(info->height());
308 track->set_display_height(info->height());
309 track->set_display_width(info->width() * info->
pixel_width() /
313 encryptor_->AddTrackInfo(track);
315 tracks_.AddTrack(track, info->track_id());
316 track_id_ = track->number();
320 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
322 unsigned int seed = 0;
323 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
325 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
327 if (info->codec() == kCodecOpus) {
328 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
329 }
else if (info->codec() == kCodecVorbis) {
330 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
332 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
333 return Status(error::UNIMPLEMENTED,
334 "Only Vorbis and Opus audio codecs are supported.");
336 if (!track->SetCodecPrivate(info->codec_config().data(),
337 info->codec_config().size())) {
338 return Status(error::INTERNAL_ERROR,
339 "Private codec data required for audio streams");
342 track->set_uid(info->track_id());
343 if (!info->language().empty())
344 track->set_language(info->language().c_str());
345 track->set_type(mkvmuxer::Tracks::kAudio);
346 track->set_sample_rate(info->sampling_frequency());
347 track->set_channels(info->num_channels());
348 track->set_seek_pre_roll(info->seek_preroll_ns());
349 track->set_codec_delay(info->codec_delay_ns());
352 encryptor_->AddTrackInfo(track);
354 tracks_.AddTrack(track, info->track_id());
355 track_id_ = track->number();
359 Status Segmenter::InitializeEncryptor(KeySource* key_source,
360 uint32_t max_sd_pixels) {
361 encryptor_.reset(
new Encryptor());
362 const KeySource::TrackType track_type =
363 GetTrackTypeForEncryption(*info_, max_sd_pixels);
364 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
366 return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
367 key_source, options_.webm_subsample_encryption);
370 Status Segmenter::WriteFrame(
bool write_duration) {
374 mkvmuxer::Frame frame;
376 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
377 return Status(error::MUXER_FAILURE,
378 "Error adding sample to segment: Frame::Init failed");
381 if (write_duration) {
382 const uint64_t duration_ns =
383 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
384 frame.set_duration(duration_ns);
386 frame.set_is_key(prev_sample_->is_key_frame());
387 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
388 frame.set_track_number(track_id_);
390 if (prev_sample_->side_data_size() > 0) {
391 uint64_t block_add_id;
394 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
395 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
396 if (!frame.AddAdditionalData(
397 prev_sample_->side_data() +
sizeof(block_add_id),
398 prev_sample_->side_data_size() -
sizeof(block_add_id),
401 error::MUXER_FAILURE,
402 "Error adding sample to segment: Frame::AddAditionalData Failed");
406 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
407 const int64_t timestamp_ns =
408 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
409 frame.set_reference_block_timestamp(timestamp_ns);
414 if (cluster_->GetRelativeTimecode(frame.timestamp() /
415 cluster_->timecode_scale()) < 0) {
416 const double segment_duration =
417 static_cast<double>(frame.timestamp()) / kSecondsToNs;
418 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
419 << segment_duration <<
" seconds.";
420 return Status(error::MUXER_FAILURE,
421 "Error adding sample to segment: segment too large");
424 if (!cluster_->AddFrame(&frame)) {
425 return Status(error::MUXER_FAILURE,
426 "Error adding sample to segment: Cluster::AddFrame failed");
432 reference_frame_timestamp_ = prev_sample_->pts();