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/codecs/vp8_parser.h"
14 #include "packager/media/codecs/vp9_parser.h"
15 #include "packager/media/codecs/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"
24 const int64_t kMicrosecondsPerMillisecond = 1000;
30 bool IsKeyframe(
bool is_video,
45 NOTIMPLEMENTED() <<
"Unsupported codec " << codec;
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,
65 : timecode_multiplier_(timecode_scale / 1000.0),
66 audio_stream_info_(audio_stream_info),
67 video_stream_info_(video_stream_info),
68 ignored_tracks_(ignored_tracks),
69 audio_encryption_key_id_(audio_encryption_key_id),
70 video_encryption_key_id_(video_encryption_key_id),
71 parser_(kWebMIdCluster, this),
74 cluster_start_time_(kNoTimestamp),
75 audio_(audio_stream_info ? audio_stream_info->track_id() : -1,
77 audio_default_duration,
79 video_(video_stream_info ? video_stream_info->track_id() : -1,
81 video_default_duration,
83 if (decryption_key_source)
85 for (WebMTracksParser::TextTracks::const_iterator it = text_tracks.begin();
86 it != text_tracks.end();
88 text_track_map_.insert(std::make_pair(
89 it->first, Track(it->first,
false, kNoTimestamp, new_sample_cb)));
93 WebMClusterParser::~WebMClusterParser() {}
96 last_block_timecode_ = -1;
97 cluster_timecode_ = -1;
98 cluster_start_time_ = kNoTimestamp;
99 cluster_ended_ =
false;
108 bool audio_result = audio_.ApplyDurationEstimateIfNeeded();
109 bool video_result = video_.ApplyDurationEstimateIfNeeded();
111 return audio_result && video_result;
115 int result = parser_.
Parse(buf, size);
118 cluster_ended_ =
false;
123 if (cluster_ended_) {
126 if (cluster_start_time_ == kNoTimestamp) {
129 if (cluster_timecode_ < 0)
132 cluster_start_time_ = cluster_timecode_ * timecode_multiplier_;
140 last_block_timecode_ = -1;
141 cluster_timecode_ = -1;
148 if (
id == kWebMIdCluster) {
149 cluster_timecode_ = -1;
150 cluster_start_time_ = kNoTimestamp;
151 }
else if (
id == kWebMIdBlockGroup) {
153 block_data_size_ = -1;
154 block_duration_ = -1;
155 discard_padding_ = -1;
156 discard_padding_set_ =
false;
157 }
else if (
id == kWebMIdBlockAdditions) {
159 block_additional_data_.reset();
160 block_additional_data_size_ = 0;
166 bool WebMClusterParser::OnListEnd(
int id) {
167 if (
id != kWebMIdBlockGroup)
171 if (block_data_size_ == -1) {
172 LOG(ERROR) <<
"Block missing from BlockGroup.";
176 bool result = ParseBlock(
false, block_data_.get(), block_data_size_,
177 block_additional_data_.get(),
178 block_additional_data_size_, block_duration_,
179 discard_padding_set_ ? discard_padding_ : 0);
181 block_data_size_ = -1;
182 block_duration_ = -1;
184 block_additional_data_.reset();
185 block_additional_data_size_ = 0;
186 discard_padding_ = -1;
187 discard_padding_set_ =
false;
191 bool WebMClusterParser::OnUInt(
int id, int64_t val) {
194 case kWebMIdTimecode:
195 dst = &cluster_timecode_;
197 case kWebMIdBlockDuration:
198 dst = &block_duration_;
200 case kWebMIdBlockAddID:
201 dst = &block_add_id_;
212 bool WebMClusterParser::ParseBlock(
bool is_simple_block,
215 const uint8_t* additional,
218 int64_t discard_padding) {
224 if (!(buf[0] & 0x80)) {
225 LOG(ERROR) <<
"TrackNumber over 127 not supported";
229 int track_num = buf[0] & 0x7f;
230 int timecode = buf[1] << 8 | buf[2];
231 int flags = buf[3] & 0xff;
232 int lacing = (flags >> 1) & 0x3;
235 LOG(ERROR) <<
"Lacing " << lacing <<
" is not supported yet.";
240 if (timecode & 0x8000)
243 const uint8_t* frame_data = buf + 4;
244 int frame_size = size - (frame_data - buf);
245 return OnBlock(is_simple_block, track_num, timecode, duration, flags,
246 frame_data, frame_size, additional, additional_size,
250 bool WebMClusterParser::OnBinary(
int id,
const uint8_t* data,
int size) {
252 case kWebMIdSimpleBlock:
253 return ParseBlock(
true, data, size, NULL, 0, -1, 0);
257 LOG(ERROR) <<
"More than 1 Block in a BlockGroup is not "
261 block_data_.reset(
new uint8_t[size]);
262 memcpy(block_data_.get(), data, size);
263 block_data_size_ = size;
266 case kWebMIdBlockAdditional: {
267 uint64_t block_add_id = base::HostToNet64(block_add_id_);
268 if (block_additional_data_) {
273 LOG(ERROR) <<
"More than 1 BlockAdditional in a "
274 "BlockGroup is not supported.";
280 block_additional_data_size_ = size +
sizeof(block_add_id);
281 block_additional_data_.reset(
new uint8_t[block_additional_data_size_]);
282 memcpy(block_additional_data_.get(), &block_add_id,
283 sizeof(block_add_id));
284 memcpy(block_additional_data_.get() + 8, data, size);
287 case kWebMIdDiscardPadding: {
288 if (discard_padding_set_ || size <= 0 || size > 8)
290 discard_padding_set_ =
true;
293 discard_padding_ =
static_cast<int8_t
>(data[0]);
294 for (
int i = 1; i < size; ++i)
295 discard_padding_ = (discard_padding_ << 8) | data[i];
304 bool WebMClusterParser::OnBlock(
bool is_simple_block,
311 const uint8_t* additional,
313 int64_t discard_padding) {
315 if (cluster_timecode_ == -1) {
316 LOG(ERROR) <<
"Got a block before cluster timecode.";
323 LOG(ERROR) <<
"Got a block with negative timecode offset " << timecode;
327 if (last_block_timecode_ != -1 && timecode < last_block_timecode_) {
328 LOG(ERROR) <<
"Got a block with a timecode before the previous block.";
333 StreamType stream_type = kStreamUnknown;
334 std::string encryption_key_id;
335 if (track_num == audio_.track_num()) {
337 encryption_key_id = audio_encryption_key_id_;
338 stream_type = kStreamAudio;
339 }
else if (track_num == video_.track_num()) {
341 encryption_key_id = video_encryption_key_id_;
342 stream_type = kStreamVideo;
343 }
else if (ignored_tracks_.find(track_num) != ignored_tracks_.end()) {
345 }
else if (Track*
const text_track = FindTextTrack(track_num)) {
348 if (block_duration < 0)
351 stream_type = kStreamText;
353 LOG(ERROR) <<
"Unexpected track number " << track_num;
356 DCHECK_NE(stream_type, kStreamUnknown);
358 last_block_timecode_ = timecode;
360 int64_t timestamp = (cluster_timecode_ + timecode) * timecode_multiplier_;
362 scoped_refptr<MediaSample> buffer;
363 if (stream_type != kStreamText) {
370 ? (flags & 0x80) != 0
371 : IsKeyframe(stream_type == kStreamVideo,
372 video_stream_info_ ? video_stream_info_->codec()
373 : kUnknownVideoCodec,
379 scoped_ptr<DecryptConfig> decrypt_config;
381 if (!encryption_key_id.empty() &&
382 !WebMCreateDecryptConfig(
384 reinterpret_cast<const uint8_t*>(encryption_key_id.data()),
385 encryption_key_id.size(),
386 &decrypt_config, &data_offset)) {
391 additional, additional_size, is_keyframe);
394 if (decrypt_config && !decrypt_config->iv().empty()) {
395 if (!decryptor_source_) {
396 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is "
400 if (!decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
401 buffer->writable_data(),
402 buffer->data_size())) {
403 LOG(ERROR) <<
"Cannot decrypt samples";
408 std::string id, settings, content;
411 std::vector<uint8_t> side_data;
412 MakeSideData(
id.begin(),
id.end(),
413 settings.begin(), settings.end(),
417 reinterpret_cast<const uint8_t*>(content.data()), content.length(),
418 &side_data[0], side_data.size(),
true);
421 buffer->set_dts(timestamp);
422 buffer->set_pts(timestamp);
423 if (cluster_start_time_ == kNoTimestamp)
424 cluster_start_time_ = timestamp;
425 buffer->set_duration(block_duration > 0
426 ? (block_duration * timecode_multiplier_)
429 if (!init_cb_.is_null() && !initialized_) {
430 std::vector<scoped_refptr<StreamInfo>> streams;
431 if (audio_stream_info_)
432 streams.push_back(audio_stream_info_);
433 if (video_stream_info_) {
434 if (stream_type == kStreamVideo) {
435 scoped_ptr<VPxParser> vpx_parser;
436 switch (video_stream_info_->codec()) {
438 vpx_parser.reset(
new VP8Parser);
441 vpx_parser.reset(
new VP9Parser);
444 NOTIMPLEMENTED() <<
"Unsupported codec "
445 << video_stream_info_->codec();
448 std::vector<VPxFrameInfo> vpx_frames;
449 if (!vpx_parser->Parse(buffer->data(), buffer->data_size(),
451 LOG(ERROR) <<
"Failed to parse vpx frame.";
454 if (vpx_frames.size() != 1u || !vpx_frames[0].is_keyframe) {
455 LOG(ERROR) <<
"The first frame should be a key frame.";
459 VPCodecConfigurationRecord codec_config;
460 if (!video_stream_info_->codec_config().empty())
461 codec_config.ParseMP4(video_stream_info_->codec_config());
462 codec_config.MergeFrom(vpx_parser->codec_config());
464 video_stream_info_->set_codec_string(
465 codec_config.GetCodecString(video_stream_info_->codec()));
466 std::vector<uint8_t> config_serialized;
467 codec_config.WriteMP4(&config_serialized);
468 video_stream_info_->set_codec_config(config_serialized);
469 streams.push_back(video_stream_info_);
470 init_cb_.Run(streams);
474 init_cb_.Run(streams);
479 return track->EmitBuffer(buffer);
482 WebMClusterParser::Track::Track(
int track_num,
484 int64_t default_duration,
486 : track_num_(track_num),
488 default_duration_(default_duration),
489 estimated_next_frame_duration_(kNoTimestamp),
490 new_sample_cb_(new_sample_cb) {
491 DCHECK(default_duration_ == kNoTimestamp || default_duration_ > 0);
494 WebMClusterParser::Track::~Track() {}
496 bool WebMClusterParser::Track::EmitBuffer(
497 const scoped_refptr<MediaSample>& buffer) {
498 DVLOG(2) <<
"EmitBuffer() : " << track_num_
499 <<
" ts " << buffer->pts()
500 <<
" dur " << buffer->duration()
501 <<
" kf " << buffer->is_key_frame()
502 <<
" size " << buffer->data_size();
504 if (last_added_buffer_missing_duration_.get()) {
505 int64_t derived_duration =
506 buffer->pts() - last_added_buffer_missing_duration_->pts();
507 last_added_buffer_missing_duration_->set_duration(derived_duration);
509 DVLOG(2) <<
"EmitBuffer() : applied derived duration to held-back buffer : "
511 << last_added_buffer_missing_duration_->pts()
513 << last_added_buffer_missing_duration_->duration()
514 <<
" kf " << last_added_buffer_missing_duration_->is_key_frame()
515 <<
" size " << last_added_buffer_missing_duration_->data_size();
516 scoped_refptr<MediaSample> updated_buffer =
517 last_added_buffer_missing_duration_;
518 last_added_buffer_missing_duration_ = NULL;
519 if (!EmitBufferHelp(updated_buffer))
523 if (buffer->duration() == kNoTimestamp) {
524 last_added_buffer_missing_duration_ = buffer;
525 DVLOG(2) <<
"EmitBuffer() : holding back buffer that is missing duration";
529 return EmitBufferHelp(buffer);
532 bool WebMClusterParser::Track::ApplyDurationEstimateIfNeeded() {
533 if (!last_added_buffer_missing_duration_.get())
536 int64_t estimated_duration = GetDurationEstimate();
537 last_added_buffer_missing_duration_->set_duration(estimated_duration);
539 VLOG(1) <<
"Track " << track_num_ <<
": Estimating WebM block duration to be "
540 << estimated_duration / 1000
541 <<
"ms for the last (Simple)Block in the Cluster for this Track. Use "
542 "BlockGroups with BlockDurations at the end of each Track in a "
543 "Cluster to avoid estimation.";
545 DVLOG(2) <<
" new dur : ts " << last_added_buffer_missing_duration_->pts()
546 <<
" dur " << last_added_buffer_missing_duration_->duration()
547 <<
" kf " << last_added_buffer_missing_duration_->is_key_frame()
548 <<
" size " << last_added_buffer_missing_duration_->data_size();
552 if (!new_sample_cb_.Run(track_num_, last_added_buffer_missing_duration_))
554 last_added_buffer_missing_duration_ = NULL;
558 void WebMClusterParser::Track::Reset() {
559 last_added_buffer_missing_duration_ = NULL;
562 bool WebMClusterParser::Track::EmitBufferHelp(
563 const scoped_refptr<MediaSample>& buffer) {
564 DCHECK(!last_added_buffer_missing_duration_.get());
566 int64_t duration = buffer->duration();
567 if (duration < 0 || duration == kNoTimestamp) {
568 LOG(ERROR) <<
"Invalid buffer duration: " << duration;
575 int64_t orig_duration_estimate = estimated_next_frame_duration_;
576 if (estimated_next_frame_duration_ == kNoTimestamp) {
577 estimated_next_frame_duration_ = duration;
579 estimated_next_frame_duration_ =
580 std::max(duration, estimated_next_frame_duration_);
583 if (orig_duration_estimate != estimated_next_frame_duration_) {
584 DVLOG(3) <<
"Updated duration estimate:"
585 << orig_duration_estimate
587 << estimated_next_frame_duration_
593 return new_sample_cb_.Run(track_num_, buffer);
596 int64_t WebMClusterParser::Track::GetDurationEstimate() {
597 int64_t duration = kNoTimestamp;
598 if (default_duration_ != kNoTimestamp) {
599 duration = default_duration_;
600 DVLOG(3) << __FUNCTION__ <<
" : using track default duration " << duration;
601 }
else if (estimated_next_frame_duration_ != kNoTimestamp) {
602 duration = estimated_next_frame_duration_;
603 DVLOG(3) << __FUNCTION__ <<
" : using estimated duration " << duration;
606 duration = kDefaultVideoBufferDurationInMs * kMicrosecondsPerMillisecond;
608 duration = kDefaultAudioBufferDurationInMs * kMicrosecondsPerMillisecond;
610 DVLOG(3) << __FUNCTION__ <<
" : using hardcoded default duration "
614 DCHECK_GT(duration, 0);
615 DCHECK_NE(duration, kNoTimestamp);
619 void WebMClusterParser::ResetTextTracks() {
620 for (TextTrackMap::iterator it = text_track_map_.begin();
621 it != text_track_map_.end();
627 WebMClusterParser::Track*
628 WebMClusterParser::FindTextTrack(
int track_num) {
629 const TextTrackMap::iterator it = text_track_map_.find(track_num);
631 if (it == text_track_map_.end())