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_handler.h"
12 #include "packager/media/base/media_sample.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) : options_(options) {}
34 Segmenter::~Segmenter() {}
40 uint32_t max_sd_pixels,
41 uint32_t max_hd_pixels,
42 uint32_t max_uhd1_pixels,
43 double clear_lead_in_seconds) {
44 muxer_listener_ = muxer_listener;
46 clear_lead_ = clear_lead_in_seconds;
49 progress_target_ = info_->duration();
50 progress_listener_ = progress_listener;
53 segment_info_.set_timecode_scale(kTimecodeScale);
55 const std::string version = GetPackagerVersion();
56 if (!version.empty()) {
57 segment_info_.set_writing_app(
58 (GetPackagerProjectUrl() +
" version " + version).c_str());
61 if (options().segment_template.empty()) {
65 segment_info_.set_duration(1);
69 if (encryption_key_source) {
70 status = InitializeEncryptor(encryption_key_source,
79 switch (info_->stream_type()) {
81 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
84 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
87 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
88 << info_->stream_type();
89 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
94 return DoInitialize();
99 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
100 segment_info_.set_duration(FromBMFFTimescale(duration));
105 if (sample_duration_ == 0) {
106 first_timestamp_ = sample->pts();
107 sample_duration_ = sample->duration();
121 if (new_segment_ || new_subsegment_) {
122 status = NewSegment(sample->pts(), new_subsegment_);
124 status = WriteFrame(
false );
133 if (new_segment_ && !enable_encryption_) {
134 if (sample->pts() - first_timestamp_ >=
135 clear_lead_ * info_->time_scale()) {
136 enable_encryption_ =
true;
142 status = encryptor_->EncryptFrame(sample, enable_encryption_);
144 LOG(ERROR) <<
"Error encrypting frame.";
149 new_subsegment_ =
false;
150 new_segment_ =
false;
151 prev_sample_ = sample;
156 uint64_t duration_timescale,
157 bool is_subsegment) {
159 new_subsegment_ =
true;
162 return WriteFrame(
true );
166 return static_cast<float>(segment_info_.duration()) *
167 segment_info_.timecode_scale() / kSecondsToNs;
170 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
172 const int64_t time_ns =
173 kSecondsToNs * time_timescale / info_->time_scale();
174 return time_ns / segment_info_.timecode_scale();
177 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
179 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
180 return time_ns * info_->time_scale() / kSecondsToNs;
184 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
186 if (!WriteEbmlHeader(writer))
189 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
192 const uint64_t segment_size_size = 8;
193 segment_payload_pos_ = writer->
Position() + segment_size_size;
196 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
197 segment_size_size) != 0)
199 if (!seek_head_.Write(writer))
202 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
206 if (!seek_head_.WriteVoid(writer))
210 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
211 if (!segment_info_.Write(writer))
214 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
215 if (!tracks_.Write(writer))
221 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
224 const uint64_t scale = segment_info_.timecode_scale();
225 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
226 cluster_->Init(writer);
231 accumulated_progress_ += progress;
232 if (!progress_listener_ || progress_target_ == 0)
237 if (accumulated_progress_ >= progress_target_) {
240 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
247 unsigned int seed = 0;
248 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
250 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
252 if (info->codec() == kCodecVP8) {
253 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
254 }
else if (info->codec() == kCodecVP9) {
255 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
260 if (!vp_config.
ParseMP4(info->codec_config())) {
261 return Status(error::INTERNAL_ERROR,
262 "Unable to parse VP9 codec configuration");
265 std::vector<uint8_t> codec_config;
267 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
268 return Status(error::INTERNAL_ERROR,
269 "Private codec data required for VP9 streams");
272 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
273 return Status(error::UNIMPLEMENTED,
274 "Only VP8 and VP9 video codecs are supported.");
277 track->set_uid(info->track_id());
278 if (!info->language().empty())
279 track->set_language(info->language().c_str());
280 track->set_type(mkvmuxer::Tracks::kVideo);
281 track->set_width(info->width());
282 track->set_height(info->height());
283 track->set_display_height(info->height());
284 track->set_display_width(info->width() * info->
pixel_width() /
288 encryptor_->AddTrackInfo(track);
290 tracks_.AddTrack(track, info->track_id());
291 track_id_ = track->number();
295 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
297 unsigned int seed = 0;
298 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
300 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
302 if (info->codec() == kCodecOpus) {
303 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
304 }
else if (info->codec() == kCodecVorbis) {
305 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
307 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
308 return Status(error::UNIMPLEMENTED,
309 "Only Vorbis and Opus audio codecs are supported.");
311 if (!track->SetCodecPrivate(info->codec_config().data(),
312 info->codec_config().size())) {
313 return Status(error::INTERNAL_ERROR,
314 "Private codec data required for audio streams");
317 track->set_uid(info->track_id());
318 if (!info->language().empty())
319 track->set_language(info->language().c_str());
320 track->set_type(mkvmuxer::Tracks::kAudio);
321 track->set_sample_rate(info->sampling_frequency());
322 track->set_channels(info->num_channels());
323 track->set_seek_pre_roll(info->seek_preroll_ns());
324 track->set_codec_delay(info->codec_delay_ns());
327 encryptor_->AddTrackInfo(track);
329 tracks_.AddTrack(track, info->track_id());
330 track_id_ = track->number();
334 Status Segmenter::InitializeEncryptor(KeySource* key_source,
335 uint32_t max_sd_pixels,
336 uint32_t max_hd_pixels,
337 uint32_t max_uhd1_pixels) {
338 encryptor_.reset(
new Encryptor());
339 const KeySource::TrackType track_type =
340 GetTrackTypeForEncryption(*info_, max_sd_pixels, max_hd_pixels,
342 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
344 return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
345 key_source, options_.webm_subsample_encryption);
348 Status Segmenter::WriteFrame(
bool write_duration) {
352 mkvmuxer::Frame frame;
354 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
355 return Status(error::MUXER_FAILURE,
356 "Error adding sample to segment: Frame::Init failed");
359 if (write_duration) {
360 const uint64_t duration_ns =
361 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
362 frame.set_duration(duration_ns);
364 frame.set_is_key(prev_sample_->is_key_frame());
365 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
366 frame.set_track_number(track_id_);
368 if (prev_sample_->side_data_size() > 0) {
369 uint64_t block_add_id;
372 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
373 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
374 if (!frame.AddAdditionalData(
375 prev_sample_->side_data() +
sizeof(block_add_id),
376 prev_sample_->side_data_size() -
sizeof(block_add_id),
379 error::MUXER_FAILURE,
380 "Error adding sample to segment: Frame::AddAditionalData Failed");
384 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
385 const int64_t timestamp_ns =
386 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
387 frame.set_reference_block_timestamp(timestamp_ns);
392 if (cluster_->GetRelativeTimecode(frame.timestamp() /
393 cluster_->timecode_scale()) < 0) {
394 const double segment_duration =
395 static_cast<double>(frame.timestamp()) / kSecondsToNs;
396 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
397 << segment_duration <<
" seconds.";
398 return Status(error::MUXER_FAILURE,
399 "Error adding sample to segment: segment too large");
402 if (!cluster_->AddFrame(&frame)) {
403 return Status(error::MUXER_FAILURE,
404 "Error adding sample to segment: Cluster::AddFrame failed");
410 reference_frame_timestamp_ = prev_sample_->pts();