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/stream_info.h"
15 #include "packager/media/base/video_stream_info.h"
16 #include "packager/media/event/muxer_listener.h"
17 #include "packager/media/event/progress_listener.h"
18 #include "packager/third_party/libwebm/src/mkvmuxerutil.hpp"
19 #include "packager/third_party/libwebm/src/webmids.hpp"
21 namespace edash_packager {
25 int64_t kTimecodeScale = 1000000;
26 int64_t kSecondsToNs = 1000000000L;
29 Segmenter::Segmenter(
const MuxerOptions& options)
30 : reference_frame_timestamp_(0),
33 muxer_listener_(NULL),
34 progress_listener_(NULL),
36 accumulated_progress_(0),
39 segment_payload_pos_(0),
40 cluster_length_sec_(0),
41 segment_length_sec_(0),
44 Segmenter::~Segmenter() {}
51 uint32_t max_sd_pixels,
52 double clear_lead_in_seconds) {
53 muxer_listener_ = muxer_listener;
55 clear_lead_ = clear_lead_in_seconds;
58 progress_target_ = info_->duration();
59 progress_listener_ = progress_listener;
61 const std::string version_string =
62 "https://github.com/google/edash-packager version " +
66 segment_info_.set_timecode_scale(kTimecodeScale);
67 segment_info_.set_writing_app(version_string.c_str());
72 segment_info_.set_duration(1);
76 if (encryption_key_source) {
77 status = InitializeEncryptor(encryption_key_source, max_sd_pixels);
83 switch (info_->stream_type()) {
85 status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
88 status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
91 NOTIMPLEMENTED() <<
"Not implemented for stream type: "
92 << info_->stream_type();
93 status =
Status(error::UNIMPLEMENTED,
"Not implemented for stream type");
98 return DoInitialize(writer.Pass());
102 Status status = WriteFrame(
true );
107 prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
108 segment_info_.set_duration(FromBMFFTimescale(duration));
113 if (sample_duration_ == 0) {
114 first_timestamp_ = sample->pts();
115 sample_duration_ = sample->duration();
129 bool wrote_frame =
false;
131 status = NewSegment(sample->pts());
136 status = WriteFrame(
true );
137 status.Update(NewSegment(sample->pts()));
138 segment_length_sec_ = 0;
139 cluster_length_sec_ = 0;
144 status = WriteFrame(
true );
145 status.Update(NewSubsegment(sample->pts()));
146 cluster_length_sec_ = 0;
151 status = WriteFrame(
false );
158 const bool encrypt_frame =
159 static_cast<double>(sample->pts() - first_timestamp_) /
160 info_->time_scale() >=
162 status = encryptor_->EncryptFrame(sample, encrypt_frame);
164 LOG(ERROR) <<
"Error encrypting frame.";
173 const double duration_sec =
174 static_cast<double>(sample->duration()) / info_->time_scale();
175 cluster_length_sec_ += duration_sec;
176 segment_length_sec_ += duration_sec;
178 prev_sample_ = sample;
183 return static_cast<float>(segment_info_.duration()) *
184 segment_info_.timecode_scale() / kSecondsToNs;
187 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
189 const int64_t time_ns =
190 kSecondsToNs * time_timescale / info_->time_scale();
191 return time_ns / segment_info_.timecode_scale();
194 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
196 const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
197 return time_ns * info_->time_scale() / kSecondsToNs;
201 Status error_status(error::FILE_FAILURE,
"Error writing segment header.");
203 if (!WriteEbmlHeader(writer))
206 if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
209 const uint64_t segment_size_size = 8;
210 segment_payload_pos_ = writer->
Position() + segment_size_size;
213 if (WriteUIntSize(writer, file_size - segment_payload_pos_,
214 segment_size_size) != 0)
216 if (!seek_head_.Write(writer))
219 if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
223 if (!seek_head_.WriteVoid(writer))
227 seek_head_.set_info_pos(writer->
Position() - segment_payload_pos_);
228 if (!segment_info_.Write(writer))
231 seek_head_.set_tracks_pos(writer->
Position() - segment_payload_pos_);
232 if (!tracks_.Write(writer))
238 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
241 const uint64_t scale = segment_info_.timecode_scale();
242 cluster_.reset(
new mkvmuxer::Cluster(start_webm_timecode, position, scale));
243 cluster_->Init(writer);
248 accumulated_progress_ += progress;
249 if (!progress_listener_ || progress_target_ == 0)
254 if (accumulated_progress_ >= progress_target_) {
257 progress_listener_->
OnProgress(static_cast<double>(accumulated_progress_) /
264 unsigned int seed = 0;
265 mkvmuxer::VideoTrack* track =
new mkvmuxer::VideoTrack(&seed);
267 return Status(error::INTERNAL_ERROR,
"Failed to create video track.");
269 if (info->codec() == kCodecVP8) {
270 track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
271 }
else if (info->codec() == kCodecVP9) {
272 track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
274 LOG(ERROR) <<
"Only VP8 and VP9 video codec is supported.";
275 return Status(error::UNIMPLEMENTED,
276 "Only VP8 and VP9 video codecs are supported.");
279 track->set_uid(info->track_id());
280 if (!info->language().empty())
281 track->set_language(info->language().c_str());
282 track->set_type(mkvmuxer::Tracks::kVideo);
283 track->set_width(info->width());
284 track->set_height(info->height());
285 track->set_display_height(info->height());
286 track->set_display_width(info->width() * info->
pixel_width() /
290 encryptor_->AddTrackInfo(track);
292 tracks_.AddTrack(track, info->track_id());
293 track_id_ = track->number();
297 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
299 unsigned int seed = 0;
300 mkvmuxer::AudioTrack* track =
new mkvmuxer::AudioTrack(&seed);
302 return Status(error::INTERNAL_ERROR,
"Failed to create audio track.");
304 if (info->codec() == kCodecOpus) {
305 track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
306 }
else if (info->codec() == kCodecVorbis) {
307 track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
309 LOG(ERROR) <<
"Only Vorbis and Opus audio codec is supported.";
310 return Status(error::UNIMPLEMENTED,
311 "Only Vorbis and Opus audio codecs are supported.");
313 if (!track->SetCodecPrivate(info->extra_data().data(),
314 info->extra_data().size())) {
315 return Status(error::INTERNAL_ERROR,
316 "Private codec data required for audio streams");
319 track->set_uid(info->track_id());
320 if (!info->language().empty())
321 track->set_language(info->language().c_str());
322 track->set_type(mkvmuxer::Tracks::kAudio);
323 track->set_sample_rate(info->sampling_frequency());
324 track->set_channels(info->num_channels());
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 encryptor_.reset(
new Encryptor());
337 switch (info_->stream_type()) {
339 VideoStreamInfo* video_info =
static_cast<VideoStreamInfo*
>(info_);
340 uint32_t pixels = video_info->width() * video_info->height();
341 KeySource::TrackType type = (pixels > max_sd_pixels)
342 ? KeySource::TRACK_TYPE_HD
343 : KeySource::TRACK_TYPE_SD;
344 return encryptor_->Initialize(muxer_listener_, type, key_source);
347 return encryptor_->Initialize(
348 muxer_listener_, KeySource::TrackType::TRACK_TYPE_AUDIO, key_source);
355 Status Segmenter::WriteFrame(
bool write_duration) {
359 mkvmuxer::Frame frame;
361 if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
362 return Status(error::MUXER_FAILURE,
363 "Error adding sample to segment: Frame::Init failed");
366 if (write_duration) {
367 const uint64_t duration_ns =
368 prev_sample_->duration() * kSecondsToNs / info_->time_scale();
369 frame.set_duration(duration_ns);
371 frame.set_is_key(prev_sample_->is_key_frame());
372 frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
373 frame.set_track_number(track_id_);
375 if (prev_sample_->side_data_size() > 0) {
376 uint64_t block_add_id;
379 CHECK_GT(prev_sample_->side_data_size(),
sizeof(block_add_id));
380 memcpy(&block_add_id, prev_sample_->side_data(),
sizeof(block_add_id));
381 if (!frame.AddAdditionalData(
382 prev_sample_->side_data() +
sizeof(block_add_id),
383 prev_sample_->side_data_size() -
sizeof(block_add_id),
386 error::MUXER_FAILURE,
387 "Error adding sample to segment: Frame::AddAditionalData Failed");
391 if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
392 const int64_t timestamp_ns =
393 reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
394 frame.set_reference_block_timestamp(timestamp_ns);
399 if (cluster_->GetRelativeTimecode(frame.timestamp() /
400 cluster_->timecode_scale()) < 0) {
401 const double segment_duration =
402 static_cast<double>(frame.timestamp()) / kSecondsToNs;
403 LOG(ERROR) <<
"Error adding sample to segment: segment too large, "
404 << segment_duration <<
" seconds.";
405 return Status(error::MUXER_FAILURE,
406 "Error adding sample to segment: segment too large");
409 if (!cluster_->AddFrame(&frame)) {
410 return Status(error::MUXER_FAILURE,
411 "Error adding sample to segment: Cluster::AddFrame failed");
417 reference_frame_timestamp_ = prev_sample_->pts();