5 #include "packager/media/formats/webm/webm_cluster_parser.h"
10 #include "packager/base/logging.h"
11 #include "packager/base/sys_byteorder.h"
12 #include "packager/media/base/decrypt_config.h"
13 #include "packager/media/base/timestamp.h"
14 #include "packager/media/codecs/vp8_parser.h"
15 #include "packager/media/codecs/vp9_parser.h"
16 #include "packager/media/codecs/webvtt_util.h"
17 #include "packager/media/formats/webm/webm_constants.h"
18 #include "packager/media/formats/webm/webm_crypto_helpers.h"
19 #include "packager/media/formats/webm/webm_webvtt_parser.h"
25 const int64_t kMicrosecondsPerMillisecond = 1000;
30 int64_t timecode_scale,
31 std::shared_ptr<AudioStreamInfo> audio_stream_info,
32 std::shared_ptr<VideoStreamInfo> video_stream_info,
33 int64_t audio_default_duration,
34 int64_t video_default_duration,
35 const WebMTracksParser::TextTracks& text_tracks,
36 const std::set<int64_t>& ignored_tracks,
37 const std::string& audio_encryption_key_id,
38 const std::string& video_encryption_key_id,
42 : timecode_multiplier_(timecode_scale / 1000.0),
43 audio_stream_info_(audio_stream_info),
44 video_stream_info_(video_stream_info),
45 ignored_tracks_(ignored_tracks),
46 audio_encryption_key_id_(audio_encryption_key_id),
47 video_encryption_key_id_(video_encryption_key_id),
48 parser_(kWebMIdCluster, this),
51 cluster_start_time_(kNoTimestamp),
52 audio_(audio_stream_info ? audio_stream_info->track_id() : -1,
54 audio_default_duration,
56 video_(video_stream_info ? video_stream_info->track_id() : -1,
58 video_default_duration,
60 if (decryption_key_source)
62 for (WebMTracksParser::TextTracks::const_iterator it = text_tracks.begin();
63 it != text_tracks.end();
65 text_track_map_.insert(std::make_pair(
66 it->first, Track(it->first,
false, kNoTimestamp, new_sample_cb)));
70 WebMClusterParser::~WebMClusterParser() {}
73 last_block_timecode_ = -1;
74 cluster_timecode_ = -1;
75 cluster_start_time_ = kNoTimestamp;
76 cluster_ended_ =
false;
85 bool audio_result = audio_.ApplyDurationEstimateIfNeeded();
86 bool video_result = video_.ApplyDurationEstimateIfNeeded();
88 return audio_result && video_result;
92 int result = parser_.
Parse(buf, size);
95 cluster_ended_ =
false;
100 if (cluster_ended_) {
103 if (cluster_start_time_ == kNoTimestamp) {
106 if (cluster_timecode_ < 0)
109 cluster_start_time_ = cluster_timecode_ * timecode_multiplier_;
117 last_block_timecode_ = -1;
118 cluster_timecode_ = -1;
125 if (
id == kWebMIdCluster) {
126 cluster_timecode_ = -1;
127 cluster_start_time_ = kNoTimestamp;
128 }
else if (
id == kWebMIdBlockGroup) {
130 block_data_size_ = -1;
131 block_duration_ = -1;
132 discard_padding_ = -1;
133 discard_padding_set_ =
false;
134 reference_block_set_ =
false;
135 }
else if (
id == kWebMIdBlockAdditions) {
137 block_additional_data_.reset();
138 block_additional_data_size_ = 0;
144 bool WebMClusterParser::OnListEnd(
int id) {
145 if (
id != kWebMIdBlockGroup)
149 if (block_data_size_ == -1) {
150 LOG(ERROR) <<
"Block missing from BlockGroup.";
154 bool result = ParseBlock(
155 false, block_data_.get(), block_data_size_, block_additional_data_.get(),
156 block_additional_data_size_, block_duration_,
157 discard_padding_set_ ? discard_padding_ : 0, reference_block_set_);
159 block_data_size_ = -1;
160 block_duration_ = -1;
162 block_additional_data_.reset();
163 block_additional_data_size_ = 0;
164 discard_padding_ = -1;
165 discard_padding_set_ =
false;
166 reference_block_set_ =
false;
170 bool WebMClusterParser::OnUInt(
int id, int64_t val) {
173 case kWebMIdTimecode:
174 dst = &cluster_timecode_;
176 case kWebMIdBlockDuration:
177 dst = &block_duration_;
179 case kWebMIdBlockAddID:
180 dst = &block_add_id_;
191 bool WebMClusterParser::ParseBlock(
bool is_simple_block,
194 const uint8_t* additional,
197 int64_t discard_padding,
198 bool reference_block_set) {
204 if (!(buf[0] & 0x80)) {
205 LOG(ERROR) <<
"TrackNumber over 127 not supported";
209 int track_num = buf[0] & 0x7f;
210 int timecode = buf[1] << 8 | buf[2];
211 int flags = buf[3] & 0xff;
212 int lacing = (flags >> 1) & 0x3;
215 LOG(ERROR) <<
"Lacing " << lacing <<
" is not supported yet.";
220 if (timecode & 0x8000)
228 is_simple_block ? (flags & 0x80) != 0 : !reference_block_set;
230 const uint8_t* frame_data = buf + 4;
231 int frame_size = size - (frame_data - buf);
232 return OnBlock(is_simple_block, track_num, timecode, duration, frame_data,
233 frame_size, additional, additional_size, discard_padding,
237 bool WebMClusterParser::OnBinary(
int id,
const uint8_t* data,
int size) {
239 case kWebMIdSimpleBlock:
240 return ParseBlock(
true, data, size, NULL, 0, -1, 0,
false);
244 LOG(ERROR) <<
"More than 1 Block in a BlockGroup is not "
248 block_data_.reset(
new uint8_t[size]);
249 memcpy(block_data_.get(), data, size);
250 block_data_size_ = size;
253 case kWebMIdBlockAdditional: {
254 uint64_t block_add_id = base::HostToNet64(block_add_id_);
255 if (block_additional_data_) {
260 LOG(ERROR) <<
"More than 1 BlockAdditional in a "
261 "BlockGroup is not supported.";
267 block_additional_data_size_ = size +
sizeof(block_add_id);
268 block_additional_data_.reset(
new uint8_t[block_additional_data_size_]);
269 memcpy(block_additional_data_.get(), &block_add_id,
270 sizeof(block_add_id));
271 memcpy(block_additional_data_.get() + 8, data, size);
274 case kWebMIdDiscardPadding: {
275 if (discard_padding_set_ || size <= 0 || size > 8)
277 discard_padding_set_ =
true;
280 discard_padding_ =
static_cast<int8_t
>(data[0]);
281 for (
int i = 1; i < size; ++i)
282 discard_padding_ = (discard_padding_ << 8) | data[i];
286 case kWebMIdReferenceBlock:
290 reference_block_set_ =
true;
297 bool WebMClusterParser::OnBlock(
bool is_simple_block,
303 const uint8_t* additional,
305 int64_t discard_padding,
308 if (cluster_timecode_ == -1) {
309 LOG(ERROR) <<
"Got a block before cluster timecode.";
316 LOG(ERROR) <<
"Got a block with negative timecode offset " << timecode;
320 if (last_block_timecode_ != -1 && timecode < last_block_timecode_) {
321 LOG(ERROR) <<
"Got a block with a timecode before the previous block.";
326 StreamType stream_type = kStreamUnknown;
327 std::string encryption_key_id;
328 if (track_num == audio_.track_num()) {
330 encryption_key_id = audio_encryption_key_id_;
331 stream_type = kStreamAudio;
332 }
else if (track_num == video_.track_num()) {
334 encryption_key_id = video_encryption_key_id_;
335 stream_type = kStreamVideo;
336 }
else if (ignored_tracks_.find(track_num) != ignored_tracks_.end()) {
338 }
else if (Track*
const text_track = FindTextTrack(track_num)) {
341 if (block_duration < 0)
344 stream_type = kStreamText;
346 LOG(ERROR) <<
"Unexpected track number " << track_num;
349 DCHECK_NE(stream_type, kStreamUnknown);
351 last_block_timecode_ = timecode;
353 int64_t timestamp = (cluster_timecode_ + timecode) * timecode_multiplier_;
355 std::shared_ptr<MediaSample> buffer;
356 if (stream_type != kStreamText) {
360 std::unique_ptr<DecryptConfig> decrypt_config;
362 if (!encryption_key_id.empty() &&
363 !WebMCreateDecryptConfig(
365 reinterpret_cast<const uint8_t*>(encryption_key_id.data()),
366 encryption_key_id.size(),
367 &decrypt_config, &data_offset)) {
372 additional, additional_size, is_key_frame);
374 if (decrypt_config) {
375 if (!decryptor_source_) {
378 buffer->set_decrypt_config(std::move(decrypt_config));
379 buffer->set_is_encrypted(
true);
380 }
else if (!decryptor_source_->DecryptSampleBuffer(
381 decrypt_config.get(), buffer->writable_data(),
382 buffer->data_size())) {
383 LOG(ERROR) <<
"Cannot decrypt samples";
388 std::string id, settings, content;
391 std::vector<uint8_t> side_data;
392 MakeSideData(
id.begin(),
id.end(),
393 settings.begin(), settings.end(),
397 reinterpret_cast<const uint8_t*>(content.data()), content.length(),
398 &side_data[0], side_data.size(),
true);
401 buffer->set_dts(timestamp);
402 buffer->set_pts(timestamp);
403 if (cluster_start_time_ == kNoTimestamp)
404 cluster_start_time_ = timestamp;
405 buffer->set_duration(block_duration > 0
406 ? (block_duration * timecode_multiplier_)
409 if (!init_cb_.is_null() && !initialized_) {
410 std::vector<std::shared_ptr<StreamInfo>> streams;
411 if (audio_stream_info_)
412 streams.push_back(audio_stream_info_);
413 if (video_stream_info_) {
414 if (stream_type == kStreamVideo) {
415 std::unique_ptr<VPxParser> vpx_parser;
416 switch (video_stream_info_->codec()) {
418 vpx_parser.reset(
new VP8Parser);
421 vpx_parser.reset(
new VP9Parser);
424 NOTIMPLEMENTED() <<
"Unsupported codec "
425 << video_stream_info_->codec();
428 std::vector<VPxFrameInfo> vpx_frames;
429 if (!vpx_parser->Parse(buffer->data(), buffer->data_size(),
431 LOG(ERROR) <<
"Failed to parse vpx frame.";
434 if (vpx_frames.size() != 1u || !vpx_frames[0].is_keyframe) {
435 LOG(ERROR) <<
"The first frame should be a key frame.";
439 VPCodecConfigurationRecord codec_config;
440 if (!video_stream_info_->codec_config().empty())
441 codec_config.ParseWebM(video_stream_info_->codec_config());
442 codec_config.MergeFrom(vpx_parser->codec_config());
444 video_stream_info_->set_codec_string(
445 codec_config.GetCodecString(video_stream_info_->codec()));
446 std::vector<uint8_t> config_serialized;
447 codec_config.WriteMP4(&config_serialized);
448 video_stream_info_->set_codec_config(config_serialized);
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 std::shared_ptr<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 std::shared_ptr<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 bool 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 if (!new_sample_cb_.Run(track_num_, last_added_buffer_missing_duration_))
534 last_added_buffer_missing_duration_ = NULL;
538 void WebMClusterParser::Track::Reset() {
539 last_added_buffer_missing_duration_ = NULL;
542 bool WebMClusterParser::Track::EmitBufferHelp(
543 const std::shared_ptr<MediaSample>& buffer) {
544 DCHECK(!last_added_buffer_missing_duration_.get());
546 int64_t duration = buffer->duration();
547 if (duration < 0 || duration == kNoTimestamp) {
548 LOG(ERROR) <<
"Invalid buffer duration: " << duration;
555 int64_t orig_duration_estimate = estimated_next_frame_duration_;
556 if (estimated_next_frame_duration_ == kNoTimestamp) {
557 estimated_next_frame_duration_ = duration;
559 estimated_next_frame_duration_ =
560 std::max(duration, estimated_next_frame_duration_);
563 if (orig_duration_estimate != estimated_next_frame_duration_) {
564 DVLOG(3) <<
"Updated duration estimate:"
565 << orig_duration_estimate
567 << estimated_next_frame_duration_
573 return new_sample_cb_.Run(track_num_, buffer);
576 int64_t WebMClusterParser::Track::GetDurationEstimate() {
577 int64_t duration = kNoTimestamp;
578 if (default_duration_ != kNoTimestamp) {
579 duration = default_duration_;
580 DVLOG(3) << __FUNCTION__ <<
" : using track default duration " << duration;
581 }
else if (estimated_next_frame_duration_ != kNoTimestamp) {
582 duration = estimated_next_frame_duration_;
583 DVLOG(3) << __FUNCTION__ <<
" : using estimated duration " << duration;
586 duration = kDefaultVideoBufferDurationInMs * kMicrosecondsPerMillisecond;
588 duration = kDefaultAudioBufferDurationInMs * kMicrosecondsPerMillisecond;
590 DVLOG(3) << __FUNCTION__ <<
" : using hardcoded default duration "
594 DCHECK_GT(duration, 0);
595 DCHECK_NE(duration, kNoTimestamp);
599 void WebMClusterParser::ResetTextTracks() {
600 for (TextTrackMap::iterator it = text_track_map_.begin();
601 it != text_track_map_.end();
607 WebMClusterParser::Track*
608 WebMClusterParser::FindTextTrack(
int track_num) {
609 const TextTrackMap::iterator it = text_track_map_.find(track_num);
611 if (it == text_track_map_.end())