5 #include "packager/media/formats/webm/webm_cluster_parser.h"
9 #include "packager/base/logging.h"
10 #include "packager/base/sys_byteorder.h"
11 #include "packager/media/base/decrypt_config.h"
12 #include "packager/media/base/timestamp.h"
13 #include "packager/media/filters/vp8_parser.h"
14 #include "packager/media/filters/vp9_parser.h"
15 #include "packager/media/filters/webvtt_util.h"
16 #include "packager/media/formats/webm/webm_constants.h"
17 #include "packager/media/formats/webm/webm_crypto_helpers.h"
18 #include "packager/media/formats/webm/webm_webvtt_parser.h"
20 namespace edash_packager {
24 const int64_t kMicrosecondsPerMillisecond = 1000;
30 bool IsKeyframe(
bool is_video,
45 NOTIMPLEMENTED() <<
"Unsupported codec " << codec;
52 WebMClusterParser::WebMClusterParser(
53 int64_t timecode_scale,
54 scoped_refptr<AudioStreamInfo> audio_stream_info,
55 scoped_refptr<VideoStreamInfo> video_stream_info,
56 int64_t audio_default_duration,
57 int64_t video_default_duration,
58 const WebMTracksParser::TextTracks& text_tracks,
59 const std::set<int64_t>& ignored_tracks,
60 const std::string& audio_encryption_key_id,
61 const std::string& video_encryption_key_id,
64 : timecode_multiplier_(timecode_scale / 1000.0),
65 audio_stream_info_(audio_stream_info),
66 video_stream_info_(video_stream_info),
67 ignored_tracks_(ignored_tracks),
68 audio_encryption_key_id_(audio_encryption_key_id),
69 video_encryption_key_id_(video_encryption_key_id),
70 parser_(kWebMIdCluster, this),
73 cluster_start_time_(kNoTimestamp),
74 audio_(audio_stream_info ? audio_stream_info->track_id() : -1,
76 audio_default_duration,
78 video_(video_stream_info ? video_stream_info->track_id() : -1,
80 video_default_duration,
82 for (WebMTracksParser::TextTracks::const_iterator it = text_tracks.begin();
83 it != text_tracks.end();
85 text_track_map_.insert(std::make_pair(
86 it->first, Track(it->first,
false, kNoTimestamp, new_sample_cb)));
90 WebMClusterParser::~WebMClusterParser() {}
93 last_block_timecode_ = -1;
94 cluster_timecode_ = -1;
95 cluster_start_time_ = kNoTimestamp;
96 cluster_ended_ =
false;
105 audio_.ApplyDurationEstimateIfNeeded();
106 video_.ApplyDurationEstimateIfNeeded();
111 int result = parser_.
Parse(buf, size);
114 cluster_ended_ =
false;
119 if (cluster_ended_) {
122 if (cluster_start_time_ == kNoTimestamp) {
125 if (cluster_timecode_ < 0)
128 cluster_start_time_ = cluster_timecode_ * timecode_multiplier_;
136 last_block_timecode_ = -1;
137 cluster_timecode_ = -1;
144 if (
id == kWebMIdCluster) {
145 cluster_timecode_ = -1;
146 cluster_start_time_ = kNoTimestamp;
147 }
else if (
id == kWebMIdBlockGroup) {
149 block_data_size_ = -1;
150 block_duration_ = -1;
151 discard_padding_ = -1;
152 discard_padding_set_ =
false;
153 }
else if (
id == kWebMIdBlockAdditions) {
155 block_additional_data_.reset();
156 block_additional_data_size_ = 0;
162 bool WebMClusterParser::OnListEnd(
int id) {
163 if (
id != kWebMIdBlockGroup)
167 if (block_data_size_ == -1) {
168 LOG(ERROR) <<
"Block missing from BlockGroup.";
172 bool result = ParseBlock(
false, block_data_.get(), block_data_size_,
173 block_additional_data_.get(),
174 block_additional_data_size_, block_duration_,
175 discard_padding_set_ ? discard_padding_ : 0);
177 block_data_size_ = -1;
178 block_duration_ = -1;
180 block_additional_data_.reset();
181 block_additional_data_size_ = 0;
182 discard_padding_ = -1;
183 discard_padding_set_ =
false;
187 bool WebMClusterParser::OnUInt(
int id, int64_t val) {
190 case kWebMIdTimecode:
191 dst = &cluster_timecode_;
193 case kWebMIdBlockDuration:
194 dst = &block_duration_;
196 case kWebMIdBlockAddID:
197 dst = &block_add_id_;
208 bool WebMClusterParser::ParseBlock(
bool is_simple_block,
211 const uint8_t* additional,
214 int64_t discard_padding) {
220 if (!(buf[0] & 0x80)) {
221 LOG(ERROR) <<
"TrackNumber over 127 not supported";
225 int track_num = buf[0] & 0x7f;
226 int timecode = buf[1] << 8 | buf[2];
227 int flags = buf[3] & 0xff;
228 int lacing = (flags >> 1) & 0x3;
231 LOG(ERROR) <<
"Lacing " << lacing <<
" is not supported yet.";
236 if (timecode & 0x8000)
239 const uint8_t* frame_data = buf + 4;
240 int frame_size = size - (frame_data - buf);
241 return OnBlock(is_simple_block, track_num, timecode, duration, flags,
242 frame_data, frame_size, additional, additional_size,
246 bool WebMClusterParser::OnBinary(
int id,
const uint8_t* data,
int size) {
248 case kWebMIdSimpleBlock:
249 return ParseBlock(
true, data, size, NULL, 0, -1, 0);
253 LOG(ERROR) <<
"More than 1 Block in a BlockGroup is not "
257 block_data_.reset(
new uint8_t[size]);
258 memcpy(block_data_.get(), data, size);
259 block_data_size_ = size;
262 case kWebMIdBlockAdditional: {
263 uint64_t block_add_id = base::HostToNet64(block_add_id_);
264 if (block_additional_data_) {
269 LOG(ERROR) <<
"More than 1 BlockAdditional in a "
270 "BlockGroup is not supported.";
276 block_additional_data_size_ = size +
sizeof(block_add_id);
277 block_additional_data_.reset(
new uint8_t[block_additional_data_size_]);
278 memcpy(block_additional_data_.get(), &block_add_id,
279 sizeof(block_add_id));
280 memcpy(block_additional_data_.get() + 8, data, size);
283 case kWebMIdDiscardPadding: {
284 if (discard_padding_set_ || size <= 0 || size > 8)
286 discard_padding_set_ =
true;
289 discard_padding_ =
static_cast<int8_t
>(data[0]);
290 for (
int i = 1; i < size; ++i)
291 discard_padding_ = (discard_padding_ << 8) | data[i];
300 bool WebMClusterParser::OnBlock(
bool is_simple_block,
307 const uint8_t* additional,
309 int64_t discard_padding) {
311 if (cluster_timecode_ == -1) {
312 LOG(ERROR) <<
"Got a block before cluster timecode.";
319 LOG(ERROR) <<
"Got a block with negative timecode offset " << timecode;
323 if (last_block_timecode_ != -1 && timecode < last_block_timecode_) {
324 LOG(ERROR) <<
"Got a block with a timecode before the previous block.";
329 StreamType stream_type = kStreamAudio;
330 std::string encryption_key_id;
331 if (track_num == audio_.track_num()) {
333 encryption_key_id = audio_encryption_key_id_;
334 }
else if (track_num == video_.track_num()) {
336 encryption_key_id = video_encryption_key_id_;
337 stream_type = kStreamVideo;
338 }
else if (ignored_tracks_.find(track_num) != ignored_tracks_.end()) {
340 }
else if (Track*
const text_track = FindTextTrack(track_num)) {
343 if (block_duration < 0)
346 stream_type = kStreamText;
348 LOG(ERROR) <<
"Unexpected track number " << track_num;
352 last_block_timecode_ = timecode;
354 int64_t timestamp = (cluster_timecode_ + timecode) * timecode_multiplier_;
356 scoped_refptr<MediaSample> buffer;
357 if (stream_type != kStreamText) {
364 ? (flags & 0x80) != 0
365 : IsKeyframe(stream_type == kStreamVideo,
366 video_stream_info_ ? video_stream_info_->codec()
367 : kUnknownVideoCodec,
373 scoped_ptr<DecryptConfig> decrypt_config;
375 if (!encryption_key_id.empty() &&
376 !WebMCreateDecryptConfig(
378 reinterpret_cast<const uint8_t*>(encryption_key_id.data()),
379 encryption_key_id.size(),
380 &decrypt_config, &data_offset)) {
385 additional, additional_size, is_keyframe);
387 if (decrypt_config) {
389 buffer->set_is_encrypted(
true);
392 std::string id, settings, content;
395 std::vector<uint8_t> side_data;
396 MakeSideData(
id.begin(),
id.end(),
397 settings.begin(), settings.end(),
401 reinterpret_cast<const uint8_t*>(content.data()), content.length(),
402 &side_data[0], side_data.size(),
true);
405 buffer->set_dts(timestamp);
406 buffer->set_pts(timestamp);
407 if (cluster_start_time_ == kNoTimestamp)
408 cluster_start_time_ = timestamp;
409 buffer->set_duration(block_duration > 0
410 ? (block_duration * timecode_multiplier_)
413 if (!init_cb_.is_null() && !initialized_) {
414 std::vector<scoped_refptr<StreamInfo>> streams;
415 if (audio_stream_info_)
416 streams.push_back(audio_stream_info_);
417 if (video_stream_info_) {
418 if (stream_type == kStreamVideo) {
419 scoped_ptr<VPxParser> vpx_parser;
420 switch (video_stream_info_->codec()) {
422 vpx_parser.reset(
new VP8Parser);
425 vpx_parser.reset(
new VP9Parser);
428 NOTIMPLEMENTED() <<
"Unsupported codec "
429 << video_stream_info_->codec();
432 std::vector<VPxFrameInfo> vpx_frames;
433 if (!vpx_parser->Parse(buffer->data(), buffer->data_size(),
435 LOG(ERROR) <<
"Failed to parse vpx frame.";
438 if (vpx_frames.size() != 1u || !vpx_frames[0].is_keyframe) {
439 LOG(ERROR) <<
"The first frame should be a key frame.";
443 const VPCodecConfiguration* codec_config = &vpx_parser->codec_config();
444 video_stream_info_->set_codec_string(
445 codec_config->GetCodecString(video_stream_info_->codec()));
446 std::vector<uint8_t> extra_data;
447 codec_config->Write(&extra_data);
448 video_stream_info_->set_extra_data(extra_data);
449 streams.push_back(video_stream_info_);
450 init_cb_.Run(streams);
454 init_cb_.Run(streams);
459 return track->EmitBuffer(buffer);
462 WebMClusterParser::Track::Track(
int track_num,
464 int64_t default_duration,
466 : track_num_(track_num),
468 default_duration_(default_duration),
469 estimated_next_frame_duration_(kNoTimestamp),
470 new_sample_cb_(new_sample_cb) {
471 DCHECK(default_duration_ == kNoTimestamp || default_duration_ > 0);
474 WebMClusterParser::Track::~Track() {}
476 bool WebMClusterParser::Track::EmitBuffer(
477 const scoped_refptr<MediaSample>& buffer) {
478 DVLOG(2) <<
"EmitBuffer() : " << track_num_
479 <<
" ts " << buffer->pts()
480 <<
" dur " << buffer->duration()
481 <<
" kf " << buffer->is_key_frame()
482 <<
" size " << buffer->data_size();
484 if (last_added_buffer_missing_duration_.get()) {
485 int64_t derived_duration =
486 buffer->pts() - last_added_buffer_missing_duration_->pts();
487 last_added_buffer_missing_duration_->set_duration(derived_duration);
489 DVLOG(2) <<
"EmitBuffer() : applied derived duration to held-back buffer : "
491 << last_added_buffer_missing_duration_->pts()
493 << last_added_buffer_missing_duration_->duration()
494 <<
" kf " << last_added_buffer_missing_duration_->is_key_frame()
495 <<
" size " << last_added_buffer_missing_duration_->data_size();
496 scoped_refptr<MediaSample> updated_buffer =
497 last_added_buffer_missing_duration_;
498 last_added_buffer_missing_duration_ = NULL;
499 if (!EmitBufferHelp(updated_buffer))
503 if (buffer->duration() == kNoTimestamp) {
504 last_added_buffer_missing_duration_ = buffer;
505 DVLOG(2) <<
"EmitBuffer() : holding back buffer that is missing duration";
509 return EmitBufferHelp(buffer);
512 void WebMClusterParser::Track::ApplyDurationEstimateIfNeeded() {
513 if (!last_added_buffer_missing_duration_.get())
516 int64_t estimated_duration = GetDurationEstimate();
517 last_added_buffer_missing_duration_->set_duration(estimated_duration);
519 VLOG(1) <<
"Track " << track_num_ <<
": Estimating WebM block duration to be "
520 << estimated_duration / 1000
521 <<
"ms for the last (Simple)Block in the Cluster for this Track. Use "
522 "BlockGroups with BlockDurations at the end of each Track in a "
523 "Cluster to avoid estimation.";
525 DVLOG(2) <<
" new dur : ts " << last_added_buffer_missing_duration_->pts()
526 <<
" dur " << last_added_buffer_missing_duration_->duration()
527 <<
" kf " << last_added_buffer_missing_duration_->is_key_frame()
528 <<
" size " << last_added_buffer_missing_duration_->data_size();
532 new_sample_cb_.Run(track_num_, last_added_buffer_missing_duration_);
533 last_added_buffer_missing_duration_ = NULL;
536 void WebMClusterParser::Track::Reset() {
537 last_added_buffer_missing_duration_ = NULL;
540 bool WebMClusterParser::Track::EmitBufferHelp(
541 const scoped_refptr<MediaSample>& buffer) {
542 DCHECK(!last_added_buffer_missing_duration_.get());
544 int64_t duration = buffer->duration();
545 if (duration < 0 || duration == kNoTimestamp) {
546 LOG(ERROR) <<
"Invalid buffer duration: " << duration;
553 int64_t orig_duration_estimate = estimated_next_frame_duration_;
554 if (estimated_next_frame_duration_ == kNoTimestamp) {
555 estimated_next_frame_duration_ = duration;
557 estimated_next_frame_duration_ =
558 std::max(duration, estimated_next_frame_duration_);
561 if (orig_duration_estimate != estimated_next_frame_duration_) {
562 DVLOG(3) <<
"Updated duration estimate:"
563 << orig_duration_estimate
565 << estimated_next_frame_duration_
571 new_sample_cb_.Run(track_num_, buffer);
575 int64_t WebMClusterParser::Track::GetDurationEstimate() {
576 int64_t duration = kNoTimestamp;
577 if (default_duration_ != kNoTimestamp) {
578 duration = default_duration_;
579 DVLOG(3) << __FUNCTION__ <<
" : using track default duration " << duration;
580 }
else if (estimated_next_frame_duration_ != kNoTimestamp) {
581 duration = estimated_next_frame_duration_;
582 DVLOG(3) << __FUNCTION__ <<
" : using estimated duration " << duration;
585 duration = kDefaultVideoBufferDurationInMs * kMicrosecondsPerMillisecond;
587 duration = kDefaultAudioBufferDurationInMs * kMicrosecondsPerMillisecond;
589 DVLOG(3) << __FUNCTION__ <<
" : using hardcoded default duration "
593 DCHECK_GT(duration, 0);
594 DCHECK_NE(duration, kNoTimestamp);
598 void WebMClusterParser::ResetTextTracks() {
599 for (TextTrackMap::iterator it = text_track_map_.begin();
600 it != text_track_map_.end();
606 WebMClusterParser::Track*
607 WebMClusterParser::FindTextTrack(
int track_num) {
608 const TextTrackMap::iterator it = text_track_map_.find(track_num);
610 if (it == text_track_map_.end())