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, Codec codec,
const uint8_t* data,
int size) {
42 NOTIMPLEMENTED() <<
"Unsupported codec " << codec;
50 int64_t timecode_scale,
51 scoped_refptr<AudioStreamInfo> audio_stream_info,
52 scoped_refptr<VideoStreamInfo> video_stream_info,
53 int64_t audio_default_duration,
54 int64_t video_default_duration,
55 const WebMTracksParser::TextTracks& text_tracks,
56 const std::set<int64_t>& ignored_tracks,
57 const std::string& audio_encryption_key_id,
58 const std::string& video_encryption_key_id,
62 : timecode_multiplier_(timecode_scale / 1000.0),
63 audio_stream_info_(audio_stream_info),
64 video_stream_info_(video_stream_info),
65 ignored_tracks_(ignored_tracks),
66 audio_encryption_key_id_(audio_encryption_key_id),
67 video_encryption_key_id_(video_encryption_key_id),
68 parser_(kWebMIdCluster, this),
71 cluster_start_time_(kNoTimestamp),
72 audio_(audio_stream_info ? audio_stream_info->track_id() : -1,
74 audio_default_duration,
76 video_(video_stream_info ? video_stream_info->track_id() : -1,
78 video_default_duration,
80 if (decryption_key_source)
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 bool audio_result = audio_.ApplyDurationEstimateIfNeeded();
106 bool video_result = video_.ApplyDurationEstimateIfNeeded();
108 return audio_result && video_result;
112 int result = parser_.
Parse(buf, size);
115 cluster_ended_ =
false;
120 if (cluster_ended_) {
123 if (cluster_start_time_ == kNoTimestamp) {
126 if (cluster_timecode_ < 0)
129 cluster_start_time_ = cluster_timecode_ * timecode_multiplier_;
137 last_block_timecode_ = -1;
138 cluster_timecode_ = -1;
145 if (
id == kWebMIdCluster) {
146 cluster_timecode_ = -1;
147 cluster_start_time_ = kNoTimestamp;
148 }
else if (
id == kWebMIdBlockGroup) {
150 block_data_size_ = -1;
151 block_duration_ = -1;
152 discard_padding_ = -1;
153 discard_padding_set_ =
false;
154 }
else if (
id == kWebMIdBlockAdditions) {
156 block_additional_data_.reset();
157 block_additional_data_size_ = 0;
163 bool WebMClusterParser::OnListEnd(
int id) {
164 if (
id != kWebMIdBlockGroup)
168 if (block_data_size_ == -1) {
169 LOG(ERROR) <<
"Block missing from BlockGroup.";
173 bool result = ParseBlock(
false, block_data_.get(), block_data_size_,
174 block_additional_data_.get(),
175 block_additional_data_size_, block_duration_,
176 discard_padding_set_ ? discard_padding_ : 0);
178 block_data_size_ = -1;
179 block_duration_ = -1;
181 block_additional_data_.reset();
182 block_additional_data_size_ = 0;
183 discard_padding_ = -1;
184 discard_padding_set_ =
false;
188 bool WebMClusterParser::OnUInt(
int id, int64_t val) {
191 case kWebMIdTimecode:
192 dst = &cluster_timecode_;
194 case kWebMIdBlockDuration:
195 dst = &block_duration_;
197 case kWebMIdBlockAddID:
198 dst = &block_add_id_;
209 bool WebMClusterParser::ParseBlock(
bool is_simple_block,
212 const uint8_t* additional,
215 int64_t discard_padding) {
221 if (!(buf[0] & 0x80)) {
222 LOG(ERROR) <<
"TrackNumber over 127 not supported";
226 int track_num = buf[0] & 0x7f;
227 int timecode = buf[1] << 8 | buf[2];
228 int flags = buf[3] & 0xff;
229 int lacing = (flags >> 1) & 0x3;
232 LOG(ERROR) <<
"Lacing " << lacing <<
" is not supported yet.";
237 if (timecode & 0x8000)
240 const uint8_t* frame_data = buf + 4;
241 int frame_size = size - (frame_data - buf);
242 return OnBlock(is_simple_block, track_num, timecode, duration, flags,
243 frame_data, frame_size, additional, additional_size,
247 bool WebMClusterParser::OnBinary(
int id,
const uint8_t* data,
int size) {
249 case kWebMIdSimpleBlock:
250 return ParseBlock(
true, data, size, NULL, 0, -1, 0);
254 LOG(ERROR) <<
"More than 1 Block in a BlockGroup is not "
258 block_data_.reset(
new uint8_t[size]);
259 memcpy(block_data_.get(), data, size);
260 block_data_size_ = size;
263 case kWebMIdBlockAdditional: {
264 uint64_t block_add_id = base::HostToNet64(block_add_id_);
265 if (block_additional_data_) {
270 LOG(ERROR) <<
"More than 1 BlockAdditional in a "
271 "BlockGroup is not supported.";
277 block_additional_data_size_ = size +
sizeof(block_add_id);
278 block_additional_data_.reset(
new uint8_t[block_additional_data_size_]);
279 memcpy(block_additional_data_.get(), &block_add_id,
280 sizeof(block_add_id));
281 memcpy(block_additional_data_.get() + 8, data, size);
284 case kWebMIdDiscardPadding: {
285 if (discard_padding_set_ || size <= 0 || size > 8)
287 discard_padding_set_ =
true;
290 discard_padding_ =
static_cast<int8_t
>(data[0]);
291 for (
int i = 1; i < size; ++i)
292 discard_padding_ = (discard_padding_ << 8) | data[i];
301 bool WebMClusterParser::OnBlock(
bool is_simple_block,
308 const uint8_t* additional,
310 int64_t discard_padding) {
312 if (cluster_timecode_ == -1) {
313 LOG(ERROR) <<
"Got a block before cluster timecode.";
320 LOG(ERROR) <<
"Got a block with negative timecode offset " << timecode;
324 if (last_block_timecode_ != -1 && timecode < last_block_timecode_) {
325 LOG(ERROR) <<
"Got a block with a timecode before the previous block.";
330 StreamType stream_type = kStreamUnknown;
331 std::string encryption_key_id;
332 if (track_num == audio_.track_num()) {
334 encryption_key_id = audio_encryption_key_id_;
335 stream_type = kStreamAudio;
336 }
else if (track_num == video_.track_num()) {
338 encryption_key_id = video_encryption_key_id_;
339 stream_type = kStreamVideo;
340 }
else if (ignored_tracks_.find(track_num) != ignored_tracks_.end()) {
342 }
else if (Track*
const text_track = FindTextTrack(track_num)) {
345 if (block_duration < 0)
348 stream_type = kStreamText;
350 LOG(ERROR) <<
"Unexpected track number " << track_num;
353 DCHECK_NE(stream_type, kStreamUnknown);
355 last_block_timecode_ = timecode;
357 int64_t timestamp = (cluster_timecode_ + timecode) * timecode_multiplier_;
359 scoped_refptr<MediaSample> buffer;
360 if (stream_type != kStreamText) {
367 ? (flags & 0x80) != 0
368 : IsKeyframe(stream_type == kStreamVideo,
369 video_stream_info_ ? video_stream_info_->codec()
376 scoped_ptr<DecryptConfig> decrypt_config;
378 if (!encryption_key_id.empty() &&
379 !WebMCreateDecryptConfig(
381 reinterpret_cast<const uint8_t*>(encryption_key_id.data()),
382 encryption_key_id.size(),
383 &decrypt_config, &data_offset)) {
388 additional, additional_size, is_keyframe);
390 if (decrypt_config) {
391 if (!decryptor_source_) {
392 LOG(ERROR) <<
"Encrypted media sample encountered, but decryption is "
396 if (!decryptor_source_->DecryptSampleBuffer(decrypt_config.get(),
397 buffer->writable_data(),
398 buffer->data_size())) {
399 LOG(ERROR) <<
"Cannot decrypt samples";
404 std::string id, settings, content;
407 std::vector<uint8_t> side_data;
408 MakeSideData(
id.begin(),
id.end(),
409 settings.begin(), settings.end(),
413 reinterpret_cast<const uint8_t*>(content.data()), content.length(),
414 &side_data[0], side_data.size(),
true);
417 buffer->set_dts(timestamp);
418 buffer->set_pts(timestamp);
419 if (cluster_start_time_ == kNoTimestamp)
420 cluster_start_time_ = timestamp;
421 buffer->set_duration(block_duration > 0
422 ? (block_duration * timecode_multiplier_)
425 if (!init_cb_.is_null() && !initialized_) {
426 std::vector<scoped_refptr<StreamInfo>> streams;
427 if (audio_stream_info_)
428 streams.push_back(audio_stream_info_);
429 if (video_stream_info_) {
430 if (stream_type == kStreamVideo) {
431 scoped_ptr<VPxParser> vpx_parser;
432 switch (video_stream_info_->codec()) {
434 vpx_parser.reset(
new VP8Parser);
437 vpx_parser.reset(
new VP9Parser);
440 NOTIMPLEMENTED() <<
"Unsupported codec "
441 << video_stream_info_->codec();
444 std::vector<VPxFrameInfo> vpx_frames;
445 if (!vpx_parser->Parse(buffer->data(), buffer->data_size(),
447 LOG(ERROR) <<
"Failed to parse vpx frame.";
450 if (vpx_frames.size() != 1u || !vpx_frames[0].is_keyframe) {
451 LOG(ERROR) <<
"The first frame should be a key frame.";
455 VPCodecConfigurationRecord codec_config;
456 if (!video_stream_info_->codec_config().empty())
457 codec_config.ParseWebM(video_stream_info_->codec_config());
458 codec_config.MergeFrom(vpx_parser->codec_config());
460 video_stream_info_->set_codec_string(
461 codec_config.GetCodecString(video_stream_info_->codec()));
462 std::vector<uint8_t> config_serialized;
463 codec_config.WriteMP4(&config_serialized);
464 video_stream_info_->set_codec_config(config_serialized);
465 streams.push_back(video_stream_info_);
466 init_cb_.Run(streams);
470 init_cb_.Run(streams);
475 return track->EmitBuffer(buffer);
478 WebMClusterParser::Track::Track(
int track_num,
480 int64_t default_duration,
482 : track_num_(track_num),
484 default_duration_(default_duration),
485 estimated_next_frame_duration_(kNoTimestamp),
486 new_sample_cb_(new_sample_cb) {
487 DCHECK(default_duration_ == kNoTimestamp || default_duration_ > 0);
490 WebMClusterParser::Track::~Track() {}
492 bool WebMClusterParser::Track::EmitBuffer(
493 const scoped_refptr<MediaSample>& buffer) {
494 DVLOG(2) <<
"EmitBuffer() : " << track_num_
495 <<
" ts " << buffer->pts()
496 <<
" dur " << buffer->duration()
497 <<
" kf " << buffer->is_key_frame()
498 <<
" size " << buffer->data_size();
500 if (last_added_buffer_missing_duration_.get()) {
501 int64_t derived_duration =
502 buffer->pts() - last_added_buffer_missing_duration_->pts();
503 last_added_buffer_missing_duration_->set_duration(derived_duration);
505 DVLOG(2) <<
"EmitBuffer() : applied derived duration to held-back buffer : "
507 << last_added_buffer_missing_duration_->pts()
509 << last_added_buffer_missing_duration_->duration()
510 <<
" kf " << last_added_buffer_missing_duration_->is_key_frame()
511 <<
" size " << last_added_buffer_missing_duration_->data_size();
512 scoped_refptr<MediaSample> updated_buffer =
513 last_added_buffer_missing_duration_;
514 last_added_buffer_missing_duration_ = NULL;
515 if (!EmitBufferHelp(updated_buffer))
519 if (buffer->duration() == kNoTimestamp) {
520 last_added_buffer_missing_duration_ = buffer;
521 DVLOG(2) <<
"EmitBuffer() : holding back buffer that is missing duration";
525 return EmitBufferHelp(buffer);
528 bool WebMClusterParser::Track::ApplyDurationEstimateIfNeeded() {
529 if (!last_added_buffer_missing_duration_.get())
532 int64_t estimated_duration = GetDurationEstimate();
533 last_added_buffer_missing_duration_->set_duration(estimated_duration);
535 VLOG(1) <<
"Track " << track_num_ <<
": Estimating WebM block duration to be "
536 << estimated_duration / 1000
537 <<
"ms for the last (Simple)Block in the Cluster for this Track. Use "
538 "BlockGroups with BlockDurations at the end of each Track in a "
539 "Cluster to avoid estimation.";
541 DVLOG(2) <<
" new dur : ts " << last_added_buffer_missing_duration_->pts()
542 <<
" dur " << last_added_buffer_missing_duration_->duration()
543 <<
" kf " << last_added_buffer_missing_duration_->is_key_frame()
544 <<
" size " << last_added_buffer_missing_duration_->data_size();
548 if (!new_sample_cb_.Run(track_num_, last_added_buffer_missing_duration_))
550 last_added_buffer_missing_duration_ = NULL;
554 void WebMClusterParser::Track::Reset() {
555 last_added_buffer_missing_duration_ = NULL;
558 bool WebMClusterParser::Track::EmitBufferHelp(
559 const scoped_refptr<MediaSample>& buffer) {
560 DCHECK(!last_added_buffer_missing_duration_.get());
562 int64_t duration = buffer->duration();
563 if (duration < 0 || duration == kNoTimestamp) {
564 LOG(ERROR) <<
"Invalid buffer duration: " << duration;
571 int64_t orig_duration_estimate = estimated_next_frame_duration_;
572 if (estimated_next_frame_duration_ == kNoTimestamp) {
573 estimated_next_frame_duration_ = duration;
575 estimated_next_frame_duration_ =
576 std::max(duration, estimated_next_frame_duration_);
579 if (orig_duration_estimate != estimated_next_frame_duration_) {
580 DVLOG(3) <<
"Updated duration estimate:"
581 << orig_duration_estimate
583 << estimated_next_frame_duration_
589 return new_sample_cb_.Run(track_num_, buffer);
592 int64_t WebMClusterParser::Track::GetDurationEstimate() {
593 int64_t duration = kNoTimestamp;
594 if (default_duration_ != kNoTimestamp) {
595 duration = default_duration_;
596 DVLOG(3) << __FUNCTION__ <<
" : using track default duration " << duration;
597 }
else if (estimated_next_frame_duration_ != kNoTimestamp) {
598 duration = estimated_next_frame_duration_;
599 DVLOG(3) << __FUNCTION__ <<
" : using estimated duration " << duration;
602 duration = kDefaultVideoBufferDurationInMs * kMicrosecondsPerMillisecond;
604 duration = kDefaultAudioBufferDurationInMs * kMicrosecondsPerMillisecond;
606 DVLOG(3) << __FUNCTION__ <<
" : using hardcoded default duration "
610 DCHECK_GT(duration, 0);
611 DCHECK_NE(duration, kNoTimestamp);
615 void WebMClusterParser::ResetTextTracks() {
616 for (TextTrackMap::iterator it = text_track_map_.begin();
617 it != text_track_map_.end();
623 WebMClusterParser::Track*
624 WebMClusterParser::FindTextTrack(
int track_num) {
625 const TextTrackMap::iterator it = text_track_map_.find(track_num);
627 if (it == text_track_map_.end())