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"
27 int64_t kTimecodeScale = 1000000;
28 int64_t kSecondsToNs = 1000000000L;
31 Segmenter::Segmenter(
const MuxerOptions& options)
32 : reference_frame_timestamp_(0),
35 muxer_listener_(NULL),
36 progress_listener_(NULL),
38 accumulated_progress_(0),
41 segment_payload_pos_(0),
42 cluster_length_sec_(0),
43 segment_length_sec_(0),
46 Segmenter::~Segmenter() {}
53 uint32_t max_sd_pixels,
54 double clear_lead_in_seconds) {
55 muxer_listener_ = muxer_listener;
57 clear_lead_ = clear_lead_in_seconds;
60 progress_target_ = info_->duration();
61 progress_listener_ = progress_listener;
63 const std::string version_string =
64 "https://github.com/google/shaka-packager version " +
68 segment_info_.set_timecode_scale(kTimecodeScale);
69 segment_info_.set_writing_app(version_string.c_str());
74 segment_info_.set_duration(1);
78 if (encryption_key_source) {
79 status = InitializeEncryptor(encryption_key_source, max_sd_pixels);
85 switch (info_->stream_type()) {
87 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
90 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
93 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
94 << info_->stream_type();
95 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
100 return DoInitialize(writer.Pass());
104 Status status = WriteFrame(
true );
109 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
110 segment_info_.set_duration(FromBMFFTimescale(duration));
115 if (sample_duration_ == 0) {
116 first_timestamp_ = sample->pts();
117 sample_duration_ = sample->duration();
131 bool wrote_frame =
false;
133 status = NewSegment(sample->pts());
138 status = WriteFrame(
true );
139 status.Update(NewSegment(sample->pts()));
140 segment_length_sec_ = 0;
141 cluster_length_sec_ = 0;
146 status = WriteFrame(
true );
147 status.Update(NewSubsegment(sample->pts()));
148 cluster_length_sec_ = 0;
153 status = WriteFrame(
false );
160 const bool encrypt_frame =
161 static_cast<double>(sample->pts() - first_timestamp_) /
162 info_->time_scale() >=
164 status = encryptor_->EncryptFrame(sample, encrypt_frame);
166 LOG(ERROR) <<
"Error encrypting frame.";
169 if (encrypt_frame && muxer_listener_)
177 const double duration_sec =
178 static_cast<double>(sample->duration()) / info_->time_scale();
179 cluster_length_sec_ += duration_sec;
180 segment_length_sec_ += duration_sec;
182 prev_sample_ = sample;
187 return static_cast<float>(segment_info_.duration()) *
188 segment_info_.timecode_scale() / kSecondsToNs;
191 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
193 const int64_t time_ns =
194 kSecondsToNs * time_timescale / info_->time_scale();
195 return time_ns / segment_info_.timecode_scale();
198 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
200 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
201 return time_ns * info_->time_scale() / kSecondsToNs;
205 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
207 if (!WriteEbmlHeader(writer))
210 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
213 const uint64_t segment_size_size = 8;
214 segment_payload_pos_ = writer->
Position() + segment_size_size;
217 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
218 segment_size_size) != 0)
220 if (!seek_head_.Write(writer))
223 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
227 if (!seek_head_.WriteVoid(writer))
231 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
232 if (!segment_info_.Write(writer))
235 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
236 if (!tracks_.Write(writer))
242 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
245 const uint64_t scale = segment_info_.timecode_scale();
246 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
247 cluster_->Init(writer);
252 accumulated_progress_ += progress;
253 if (!progress_listener_ || progress_target_ == 0)
258 if (accumulated_progress_ >= progress_target_) {
261 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
268 unsigned int seed = 0;
269 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
271 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
273 if (info->codec() == kCodecVP8) {
274 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
275 }
else if (info->codec() == kCodecVP9) {
276 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
281 if (!vp_config.
ParseMP4(info->codec_config())) {
282 return Status(error::INTERNAL_ERROR,
283 "Unable to parse VP9 codec configuration");
286 std::vector<uint8_t> codec_config;
288 if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
289 return Status(error::INTERNAL_ERROR,
290 "Private codec data required for VP9 streams");
293 LOG(ERROR) <<
"Only VP8 and VP9 video codecs are supported.";
294 return Status(error::UNIMPLEMENTED,
295 "Only VP8 and VP9 video codecs are supported.");
298 track->set_uid(info->track_id());
299 if (!info->language().empty())
300 track->set_language(info->language().c_str());
301 track->set_type(mkvmuxer::Tracks::kVideo);
302 track->set_width(info->width());
303 track->set_height(info->height());
304 track->set_display_height(info->height());
305 track->set_display_width(info->width() * info->
pixel_width() /
309 encryptor_->AddTrackInfo(track);
311 tracks_.AddTrack(track, info->track_id());
312 track_id_ = track->number();
316 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
318 unsigned int seed = 0;
319 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
321 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
323 if (info->codec() == kCodecOpus) {
324 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
325 }
else if (info->codec() == kCodecVorbis) {
326 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
328 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
329 return Status(error::UNIMPLEMENTED,
330 "Only Vorbis and Opus audio codecs are supported.");
332 if (!track->SetCodecPrivate(info->codec_config().data(),
333 info->codec_config().size())) {
334 return Status(error::INTERNAL_ERROR,
335 "Private codec data required for audio streams");
338 track->set_uid(info->track_id());
339 if (!info->language().empty())
340 track->set_language(info->language().c_str());
341 track->set_type(mkvmuxer::Tracks::kAudio);
342 track->set_sample_rate(info->sampling_frequency());
343 track->set_channels(info->num_channels());
344 track->set_seek_pre_roll(info->seek_preroll_ns());
345 track->set_codec_delay(info->codec_delay_ns());
348 encryptor_->AddTrackInfo(track);
350 tracks_.AddTrack(track, info->track_id());
351 track_id_ = track->number();
355 Status Segmenter::InitializeEncryptor(KeySource* key_source,
356 uint32_t max_sd_pixels) {
357 encryptor_.reset(
new Encryptor());
358 const KeySource::TrackType track_type =
359 GetTrackTypeForEncryption(*info_, max_sd_pixels);
360 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
362 return encryptor_->Initialize(muxer_listener_, track_type, key_source);
365 Status Segmenter::WriteFrame(
bool write_duration) {
369 mkvmuxer::Frame frame;
371 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
372 return Status(error::MUXER_FAILURE,
373 "Error adding sample to segment: Frame::Init failed");
376 if (write_duration) {
377 const uint64_t duration_ns =
378 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
379 frame.set_duration(duration_ns);
381 frame.set_is_key(prev_sample_->is_key_frame());
382 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
383 frame.set_track_number(track_id_);
385 if (prev_sample_->side_data_size() > 0) {
386 uint64_t block_add_id;
389 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
390 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
391 if (!frame.AddAdditionalData(
392 prev_sample_->side_data() +
sizeof(block_add_id),
393 prev_sample_->side_data_size() -
sizeof(block_add_id),
396 error::MUXER_FAILURE,
397 "Error adding sample to segment: Frame::AddAditionalData Failed");
401 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
402 const int64_t timestamp_ns =
403 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
404 frame.set_reference_block_timestamp(timestamp_ns);
409 if (cluster_->GetRelativeTimecode(frame.timestamp() /
410 cluster_->timecode_scale()) < 0) {
411 const double segment_duration =
412 static_cast<double>(frame.timestamp()) / kSecondsToNs;
413 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
414 << segment_duration <<
" seconds.";
415 return Status(error::MUXER_FAILURE,
416 "Error adding sample to segment: segment too large");
419 if (!cluster_->AddFrame(&frame)) {
420 return Status(error::MUXER_FAILURE,
421 "Error adding sample to segment: Cluster::AddFrame failed");
427 reference_frame_timestamp_ = prev_sample_->pts();