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/event/muxer_listener.h"
18 #include "packager/media/event/progress_listener.h"
19 #include "packager/third_party/libwebm/src/mkvmuxerutil.hpp"
20 #include "packager/third_party/libwebm/src/webmids.hpp"
22 namespace edash_packager {
26 int64_t kTimecodeScale = 1000000;
27 int64_t kSecondsToNs = 1000000000L;
30 Segmenter::Segmenter(
const MuxerOptions& options)
31 : reference_frame_timestamp_(0),
34 muxer_listener_(NULL),
35 progress_listener_(NULL),
37 accumulated_progress_(0),
40 segment_payload_pos_(0),
41 cluster_length_sec_(0),
42 segment_length_sec_(0),
45 Segmenter::~Segmenter() {}
52 uint32_t max_sd_pixels,
53 double clear_lead_in_seconds) {
54 muxer_listener_ = muxer_listener;
56 clear_lead_ = clear_lead_in_seconds;
59 progress_target_ = info_->duration();
60 progress_listener_ = progress_listener;
62 const std::string version_string =
63 "https://github.com/google/edash-packager version " +
67 segment_info_.set_timecode_scale(kTimecodeScale);
68 segment_info_.set_writing_app(version_string.c_str());
73 segment_info_.set_duration(1);
77 if (encryption_key_source) {
78 status = InitializeEncryptor(encryption_key_source, max_sd_pixels);
84 switch (info_->stream_type()) {
86 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
89 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
92 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
93 << info_->stream_type();
94 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
99 return DoInitialize(writer.Pass());
103 Status status = WriteFrame(
true );
108 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
109 segment_info_.set_duration(FromBMFFTimescale(duration));
114 if (sample_duration_ == 0) {
115 first_timestamp_ = sample->pts();
116 sample_duration_ = sample->duration();
130 bool wrote_frame =
false;
132 status = NewSegment(sample->pts());
137 status = WriteFrame(
true );
138 status.Update(NewSegment(sample->pts()));
139 segment_length_sec_ = 0;
140 cluster_length_sec_ = 0;
145 status = WriteFrame(
true );
146 status.Update(NewSubsegment(sample->pts()));
147 cluster_length_sec_ = 0;
152 status = WriteFrame(
false );
159 const bool encrypt_frame =
160 static_cast<double>(sample->pts() - first_timestamp_) /
161 info_->time_scale() >=
163 status = encryptor_->EncryptFrame(sample, encrypt_frame);
165 LOG(ERROR) <<
"Error encrypting frame.";
174 const double duration_sec =
175 static_cast<double>(sample->duration()) / info_->time_scale();
176 cluster_length_sec_ += duration_sec;
177 segment_length_sec_ += duration_sec;
179 prev_sample_ = sample;
184 return static_cast<float>(segment_info_.duration()) *
185 segment_info_.timecode_scale() / kSecondsToNs;
188 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
190 const int64_t time_ns =
191 kSecondsToNs * time_timescale / info_->time_scale();
192 return time_ns / segment_info_.timecode_scale();
195 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
197 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
198 return time_ns * info_->time_scale() / kSecondsToNs;
202 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
204 if (!WriteEbmlHeader(writer))
207 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
210 const uint64_t segment_size_size = 8;
211 segment_payload_pos_ = writer->
Position() + segment_size_size;
214 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
215 segment_size_size) != 0)
217 if (!seek_head_.Write(writer))
220 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
224 if (!seek_head_.WriteVoid(writer))
228 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
229 if (!segment_info_.Write(writer))
232 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
233 if (!tracks_.Write(writer))
239 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
242 const uint64_t scale = segment_info_.timecode_scale();
243 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
244 cluster_->Init(writer);
249 accumulated_progress_ += progress;
250 if (!progress_listener_ || progress_target_ == 0)
255 if (accumulated_progress_ >= progress_target_) {
258 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
265 unsigned int seed = 0;
266 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
268 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
270 if (info->codec() == kCodecVP8) {
271 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
272 }
else if (info->codec() == kCodecVP9) {
273 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
275 LOG(ERROR) <<
"Only VP8 and VP9 video codec is supported.";
276 return Status(error::UNIMPLEMENTED,
277 "Only VP8 and VP9 video codecs are supported.");
280 track->set_uid(info->track_id());
281 if (!info->language().empty())
282 track->set_language(info->language().c_str());
283 track->set_type(mkvmuxer::Tracks::kVideo);
284 track->set_width(info->width());
285 track->set_height(info->height());
286 track->set_display_height(info->height());
287 track->set_display_width(info->width() * info->
pixel_width() /
291 encryptor_->AddTrackInfo(track);
293 tracks_.AddTrack(track, info->track_id());
294 track_id_ = track->number();
298 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
300 unsigned int seed = 0;
301 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
303 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
305 if (info->codec() == kCodecOpus) {
306 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
307 }
else if (info->codec() == kCodecVorbis) {
308 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
310 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
311 return Status(error::UNIMPLEMENTED,
312 "Only Vorbis and Opus audio codecs are supported.");
314 if (!track->SetCodecPrivate(info->extra_data().data(),
315 info->extra_data().size())) {
316 return Status(error::INTERNAL_ERROR,
317 "Private codec data required for audio streams");
320 track->set_uid(info->track_id());
321 if (!info->language().empty())
322 track->set_language(info->language().c_str());
323 track->set_type(mkvmuxer::Tracks::kAudio);
324 track->set_sample_rate(info->sampling_frequency());
325 track->set_channels(info->num_channels());
326 track->set_seek_pre_roll(info->seek_preroll_ns());
327 track->set_codec_delay(info->codec_delay_ns());
330 encryptor_->AddTrackInfo(track);
332 tracks_.AddTrack(track, info->track_id());
333 track_id_ = track->number();
337 Status Segmenter::InitializeEncryptor(KeySource* key_source,
338 uint32_t max_sd_pixels) {
339 encryptor_.reset(
new Encryptor());
340 const KeySource::TrackType track_type =
341 GetTrackTypeForEncryption(*info_, max_sd_pixels);
342 if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
344 return encryptor_->Initialize(muxer_listener_, track_type, key_source);
347 Status Segmenter::WriteFrame(
bool write_duration) {
351 mkvmuxer::Frame frame;
353 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
354 return Status(error::MUXER_FAILURE,
355 "Error adding sample to segment: Frame::Init failed");
358 if (write_duration) {
359 const uint64_t duration_ns =
360 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
361 frame.set_duration(duration_ns);
363 frame.set_is_key(prev_sample_->is_key_frame());
364 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
365 frame.set_track_number(track_id_);
367 if (prev_sample_->side_data_size() > 0) {
368 uint64_t block_add_id;
371 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
372 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
373 if (!frame.AddAdditionalData(
374 prev_sample_->side_data() +
sizeof(block_add_id),
375 prev_sample_->side_data_size() -
sizeof(block_add_id),
378 error::MUXER_FAILURE,
379 "Error adding sample to segment: Frame::AddAditionalData Failed");
383 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
384 const int64_t timestamp_ns =
385 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
386 frame.set_reference_block_timestamp(timestamp_ns);
391 if (cluster_->GetRelativeTimecode(frame.timestamp() /
392 cluster_->timecode_scale()) < 0) {
393 const double segment_duration =
394 static_cast<double>(frame.timestamp()) / kSecondsToNs;
395 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
396 << segment_duration <<
" seconds.";
397 return Status(error::MUXER_FAILURE,
398 "Error adding sample to segment: segment too large");
401 if (!cluster_->AddFrame(&frame)) {
402 return Status(error::MUXER_FAILURE,
403 "Error adding sample to segment: Cluster::AddFrame failed");
409 reference_frame_timestamp_ = prev_sample_->pts();