2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
10 * This file contains the WEBRTC VP8 wrapper implementation
14 #include "webrtc/modules/video_coding/codecs/vp8/vp8_impl.h"
21 #include "vpx/vpx_encoder.h"
22 #include "vpx/vpx_decoder.h"
23 #include "vpx/vp8cx.h"
24 #include "vpx/vp8dx.h"
26 #include "webrtc/common.h"
27 #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
28 #include "webrtc/modules/interface/module_common_types.h"
29 #include "webrtc/modules/video_coding/codecs/vp8/temporal_layers.h"
30 #include "webrtc/modules/video_coding/codecs/vp8/reference_picture_selection.h"
31 #include "webrtc/system_wrappers/interface/tick_util.h"
32 #include "webrtc/system_wrappers/interface/trace_event.h"
34 enum { kVp8ErrorPropagationTh = 30 };
38 VP8EncoderImpl::VP8EncoderImpl()
40 encoded_complete_callback_(NULL),
44 feedback_mode_(false),
45 cpu_speed_(-6), // default value
46 rc_max_intra_target_(0),
47 token_partitions_(VP8_ONE_TOKENPARTITION),
48 rps_(new ReferencePictureSelection),
49 temporal_layers_(NULL),
53 memset(&codec_, 0, sizeof(codec_));
54 uint32_t seed = static_cast<uint32_t>(TickTime::MillisecondTimestamp());
58 VP8EncoderImpl::~VP8EncoderImpl() {
63 int VP8EncoderImpl::Release() {
64 if (encoded_image_._buffer != NULL) {
65 delete [] encoded_image_._buffer;
66 encoded_image_._buffer = NULL;
68 if (encoder_ != NULL) {
69 if (vpx_codec_destroy(encoder_)) {
70 return WEBRTC_VIDEO_CODEC_MEMORY;
75 if (config_ != NULL) {
83 delete temporal_layers_;
84 temporal_layers_ = NULL;
86 return WEBRTC_VIDEO_CODEC_OK;
89 int VP8EncoderImpl::SetRates(uint32_t new_bitrate_kbit,
90 uint32_t new_framerate) {
92 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
95 return WEBRTC_VIDEO_CODEC_ERROR;
97 if (new_framerate < 1) {
98 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
101 if (codec_.maxBitrate > 0 && new_bitrate_kbit > codec_.maxBitrate) {
102 new_bitrate_kbit = codec_.maxBitrate;
104 config_->rc_target_bitrate = new_bitrate_kbit; // in kbit/s
105 temporal_layers_->ConfigureBitrates(new_bitrate_kbit, codec_.maxBitrate,
106 new_framerate, config_);
107 codec_.maxFramerate = new_framerate;
109 // update encoder context
110 if (vpx_codec_enc_config_set(encoder_, config_)) {
111 return WEBRTC_VIDEO_CODEC_ERROR;
113 return WEBRTC_VIDEO_CODEC_OK;
116 int VP8EncoderImpl::InitEncode(const VideoCodec* inst,
118 uint32_t /*max_payload_size*/) {
120 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
122 if (inst->maxFramerate < 1) {
123 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
125 // allow zero to represent an unspecified maxBitRate
126 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
127 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
129 if (inst->width < 1 || inst->height < 1) {
130 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
132 if (number_of_cores < 1) {
133 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
135 feedback_mode_ = inst->codecSpecific.VP8.feedbackModeOn;
137 int retVal = Release();
141 if (encoder_ == NULL) {
142 encoder_ = new vpx_codec_ctx_t;
144 if (config_ == NULL) {
145 config_ = new vpx_codec_enc_cfg_t;
149 if (&codec_ != inst) {
153 // TODO(andresp): assert(inst->extra_options) and cleanup.
154 Config default_options;
155 const Config& options =
156 inst->extra_options ? *inst->extra_options : default_options;
158 int num_temporal_layers = inst->codecSpecific.VP8.numberOfTemporalLayers > 1 ?
159 inst->codecSpecific.VP8.numberOfTemporalLayers : 1;
160 assert(temporal_layers_ == NULL);
161 temporal_layers_ = options.Get<TemporalLayers::Factory>()
162 .Create(num_temporal_layers, rand());
163 // random start 16 bits is enough.
164 picture_id_ = static_cast<uint16_t>(rand()) & 0x7FFF;
166 // allocate memory for encoded image
167 if (encoded_image_._buffer != NULL) {
168 delete [] encoded_image_._buffer;
170 encoded_image_._size = CalcBufferSize(kI420, codec_.width, codec_.height);
171 encoded_image_._buffer = new uint8_t[encoded_image_._size];
172 encoded_image_._completeFrame = true;
174 // Creating a wrapper to the image - setting image data to NULL. Actual
175 // pointer will be set in encode. Setting align to 1, as it is meaningless
176 // (actual memory is not allocated).
177 raw_ = vpx_img_wrap(NULL, IMG_FMT_I420, codec_.width, codec_.height,
179 // populate encoder configuration with default values
180 if (vpx_codec_enc_config_default(vpx_codec_vp8_cx(), config_, 0)) {
181 return WEBRTC_VIDEO_CODEC_ERROR;
183 config_->g_w = codec_.width;
184 config_->g_h = codec_.height;
185 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
186 temporal_layers_->ConfigureBitrates(inst->startBitrate, inst->maxBitrate,
187 inst->maxFramerate, config_);
188 // setting the time base of the codec
189 config_->g_timebase.num = 1;
190 config_->g_timebase.den = 90000;
192 // Set the error resilience mode according to user settings.
193 switch (inst->codecSpecific.VP8.resilience) {
195 config_->g_error_resilient = 0;
196 if (num_temporal_layers > 1) {
197 // Must be on for temporal layers (i.e., |num_temporal_layers| > 1).
198 config_->g_error_resilient = 1;
201 case kResilientStream:
202 config_->g_error_resilient = 1; // TODO(holmer): Replace with
203 // VPX_ERROR_RESILIENT_DEFAULT when we
204 // drop support for libvpx 9.6.0.
206 case kResilientFrames:
207 #ifdef INDEPENDENT_PARTITIONS
208 config_->g_error_resilient = VPX_ERROR_RESILIENT_DEFAULT |
209 VPX_ERROR_RESILIENT_PARTITIONS;
212 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; // Not supported
215 config_->g_lag_in_frames = 0; // 0- no frame lagging
217 if (codec_.width * codec_.height > 1280 * 960 && number_of_cores >= 6) {
218 config_->g_threads = 3; // 3 threads for 1080p.
219 } else if (codec_.width * codec_.height > 640 * 480 && number_of_cores >= 3) {
220 config_->g_threads = 2; // 2 threads for qHD/HD.
222 config_->g_threads = 1; // 1 thread for VGA or less
225 // rate control settings
226 config_->rc_dropframe_thresh = inst->codecSpecific.VP8.frameDroppingOn ?
228 config_->rc_end_usage = VPX_CBR;
229 config_->g_pass = VPX_RC_ONE_PASS;
230 config_->rc_resize_allowed = inst->codecSpecific.VP8.automaticResizeOn ?
232 config_->rc_min_quantizer = 2;
233 config_->rc_max_quantizer = inst->qpMax;
234 config_->rc_undershoot_pct = 100;
235 config_->rc_overshoot_pct = 15;
236 config_->rc_buf_initial_sz = 500;
237 config_->rc_buf_optimal_sz = 600;
238 config_->rc_buf_sz = 1000;
239 // set the maximum target size of any key-frame.
240 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
242 if (feedback_mode_) {
243 // Disable periodic key frames if we get feedback from the decoder
244 // through SLI and RPSI.
245 config_->kf_mode = VPX_KF_DISABLED;
246 } else if (inst->codecSpecific.VP8.keyFrameInterval > 0) {
247 config_->kf_mode = VPX_KF_AUTO;
248 config_->kf_max_dist = inst->codecSpecific.VP8.keyFrameInterval;
250 config_->kf_mode = VPX_KF_DISABLED;
252 switch (inst->codecSpecific.VP8.complexity) {
253 case kComplexityHigh:
256 case kComplexityHigher:
266 #if defined(WEBRTC_ARCH_ARM)
267 // On mobile platform, always set to -12 to leverage between cpu usage
272 return InitAndSetControlSettings(inst);
275 int VP8EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
276 vpx_codec_flags_t flags = 0;
277 // TODO(holmer): We should make a smarter decision on the number of
278 // partitions. Eight is probably not the optimal number for low resolution
280 flags |= VPX_CODEC_USE_OUTPUT_PARTITION;
281 if (vpx_codec_enc_init(encoder_, vpx_codec_vp8_cx(), config_, flags)) {
282 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
284 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
285 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
286 vpx_codec_control(encoder_, VP8E_SET_TOKEN_PARTITIONS,
287 static_cast<vp8e_token_partitions>(token_partitions_));
288 #if !defined(WEBRTC_ARCH_ARM)
289 // TODO(fbarchard): Enable Noise reduction for ARM once optimized.
290 vpx_codec_control(encoder_, VP8E_SET_NOISE_SENSITIVITY,
291 inst->codecSpecific.VP8.denoisingOn ? 1 : 0);
293 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
294 rc_max_intra_target_);
296 return WEBRTC_VIDEO_CODEC_OK;
299 uint32_t VP8EncoderImpl::MaxIntraTarget(uint32_t optimalBuffersize) {
300 // Set max to the optimal buffer level (normalized by target BR),
301 // and scaled by a scalePar.
302 // Max target size = scalePar * optimalBufferSize * targetBR[Kbps].
303 // This values is presented in percentage of perFrameBw:
304 // perFrameBw = targetBR[Kbps] * 1000 / frameRate.
305 // The target in % is as follows:
307 float scalePar = 0.5;
308 uint32_t targetPct = optimalBuffersize * scalePar * codec_.maxFramerate / 10;
310 // Don't go below 3 times the per frame bandwidth.
311 const uint32_t minIntraTh = 300;
312 return (targetPct < minIntraTh) ? minIntraTh: targetPct;
315 int VP8EncoderImpl::Encode(const I420VideoFrame& input_image,
316 const CodecSpecificInfo* codec_specific_info,
317 const std::vector<VideoFrameType>* frame_types) {
318 TRACE_EVENT1("webrtc", "VP8::Encode", "timestamp", input_image.timestamp());
321 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
323 if (input_image.IsZeroSize()) {
324 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
326 if (encoded_complete_callback_ == NULL) {
327 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
330 VideoFrameType frame_type = kDeltaFrame;
331 // We only support one stream at the moment.
332 if (frame_types && frame_types->size() > 0) {
333 frame_type = (*frame_types)[0];
336 // Check for change in frame size.
337 if (input_image.width() != codec_.width ||
338 input_image.height() != codec_.height) {
339 int ret = UpdateCodecFrameSize(input_image);
344 // Image in vpx_image_t format.
345 // Input image is const. VP8's raw image is not defined as const.
346 raw_->planes[PLANE_Y] = const_cast<uint8_t*>(input_image.buffer(kYPlane));
347 raw_->planes[PLANE_U] = const_cast<uint8_t*>(input_image.buffer(kUPlane));
348 raw_->planes[PLANE_V] = const_cast<uint8_t*>(input_image.buffer(kVPlane));
349 // TODO(mikhal): Stride should be set in initialization.
350 raw_->stride[VPX_PLANE_Y] = input_image.stride(kYPlane);
351 raw_->stride[VPX_PLANE_U] = input_image.stride(kUPlane);
352 raw_->stride[VPX_PLANE_V] = input_image.stride(kVPlane);
354 int flags = temporal_layers_->EncodeFlags(input_image.timestamp());
356 bool send_keyframe = (frame_type == kKeyFrame);
358 // Key frame request from caller.
359 // Will update both golden and alt-ref.
360 flags = VPX_EFLAG_FORCE_KF;
361 } else if (feedback_mode_ && codec_specific_info) {
362 // Handle RPSI and SLI messages and set up the appropriate encode flags.
363 bool sendRefresh = false;
364 if (codec_specific_info->codecType == kVideoCodecVP8) {
365 if (codec_specific_info->codecSpecific.VP8.hasReceivedRPSI) {
367 codec_specific_info->codecSpecific.VP8.pictureIdRPSI);
369 if (codec_specific_info->codecSpecific.VP8.hasReceivedSLI) {
370 sendRefresh = rps_->ReceivedSLI(input_image.timestamp());
373 flags = rps_->EncodeFlags(picture_id_, sendRefresh,
374 input_image.timestamp());
377 // TODO(holmer): Ideally the duration should be the timestamp diff of this
378 // frame and the next frame to be encoded, which we don't have. Instead we
379 // would like to use the duration of the previous frame. Unfortunately the
380 // rate control seems to be off with that setup. Using the average input
381 // frame rate to calculate an average duration for now.
382 assert(codec_.maxFramerate > 0);
383 uint32_t duration = 90000 / codec_.maxFramerate;
384 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
386 return WEBRTC_VIDEO_CODEC_ERROR;
388 timestamp_ += duration;
390 return GetEncodedPartitions(input_image);
393 int VP8EncoderImpl::UpdateCodecFrameSize(const I420VideoFrame& input_image) {
394 codec_.width = input_image.width();
395 codec_.height = input_image.height();
396 raw_->w = codec_.width;
397 raw_->h = codec_.height;
398 raw_->d_w = codec_.width;
399 raw_->d_h = codec_.height;
401 raw_->stride[VPX_PLANE_Y] = input_image.stride(kYPlane);
402 raw_->stride[VPX_PLANE_U] = input_image.stride(kUPlane);
403 raw_->stride[VPX_PLANE_V] = input_image.stride(kVPlane);
404 vpx_img_set_rect(raw_, 0, 0, codec_.width, codec_.height);
406 // Update encoder context for new frame size.
407 // Change of frame size will automatically trigger a key frame.
408 config_->g_w = codec_.width;
409 config_->g_h = codec_.height;
410 if (vpx_codec_enc_config_set(encoder_, config_)) {
411 return WEBRTC_VIDEO_CODEC_ERROR;
413 return WEBRTC_VIDEO_CODEC_OK;
416 void VP8EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
417 const vpx_codec_cx_pkt& pkt,
418 uint32_t timestamp) {
419 assert(codec_specific != NULL);
420 codec_specific->codecType = kVideoCodecVP8;
421 CodecSpecificInfoVP8 *vp8Info = &(codec_specific->codecSpecific.VP8);
422 vp8Info->pictureId = picture_id_;
423 vp8Info->simulcastIdx = 0;
424 vp8Info->keyIdx = kNoKeyIdx; // TODO(hlundin) populate this
425 vp8Info->nonReference = (pkt.data.frame.flags & VPX_FRAME_IS_DROPPABLE) != 0;
426 temporal_layers_->PopulateCodecSpecific(
427 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false, vp8Info,
429 picture_id_ = (picture_id_ + 1) & 0x7FFF; // prepare next
432 int VP8EncoderImpl::GetEncodedPartitions(const I420VideoFrame& input_image) {
433 vpx_codec_iter_t iter = NULL;
435 encoded_image_._length = 0;
436 encoded_image_._frameType = kDeltaFrame;
437 RTPFragmentationHeader frag_info;
438 frag_info.VerifyAndAllocateFragmentationHeader((1 << token_partitions_) + 1);
439 CodecSpecificInfo codec_specific;
441 const vpx_codec_cx_pkt_t *pkt = NULL;
442 while ((pkt = vpx_codec_get_cx_data(encoder_, &iter)) != NULL) {
444 case VPX_CODEC_CX_FRAME_PKT: {
445 memcpy(&encoded_image_._buffer[encoded_image_._length],
448 frag_info.fragmentationOffset[part_idx] = encoded_image_._length;
449 frag_info.fragmentationLength[part_idx] = pkt->data.frame.sz;
450 frag_info.fragmentationPlType[part_idx] = 0; // not known here
451 frag_info.fragmentationTimeDiff[part_idx] = 0;
452 encoded_image_._length += pkt->data.frame.sz;
453 assert(encoded_image_._length <= encoded_image_._size);
462 if ((pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT) == 0) {
463 // check if encoded frame is a key frame
464 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
465 encoded_image_._frameType = kKeyFrame;
466 rps_->EncodedKeyFrame(picture_id_);
468 PopulateCodecSpecific(&codec_specific, *pkt, input_image.timestamp());
472 if (encoded_image_._length > 0) {
473 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
474 encoded_image_._timeStamp = input_image.timestamp();
475 encoded_image_.capture_time_ms_ = input_image.render_time_ms();
476 encoded_image_._encodedHeight = codec_.height;
477 encoded_image_._encodedWidth = codec_.width;
478 encoded_complete_callback_->Encoded(encoded_image_, &codec_specific,
481 return WEBRTC_VIDEO_CODEC_OK;
484 int VP8EncoderImpl::SetChannelParameters(uint32_t /*packet_loss*/, int rtt) {
486 return WEBRTC_VIDEO_CODEC_OK;
489 int VP8EncoderImpl::RegisterEncodeCompleteCallback(
490 EncodedImageCallback* callback) {
491 encoded_complete_callback_ = callback;
492 return WEBRTC_VIDEO_CODEC_OK;
495 VP8DecoderImpl::VP8DecoderImpl()
496 : decode_complete_callback_(NULL),
498 feedback_mode_(false),
501 image_format_(VPX_IMG_FMT_NONE),
503 propagation_cnt_(-1),
504 mfqe_enabled_(false),
505 key_frame_required_(true) {
506 memset(&codec_, 0, sizeof(codec_));
509 VP8DecoderImpl::~VP8DecoderImpl() {
510 inited_ = true; // in order to do the actual release
514 int VP8DecoderImpl::Reset() {
516 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
518 InitDecode(&codec_, 1);
519 propagation_cnt_ = -1;
520 mfqe_enabled_ = false;
521 return WEBRTC_VIDEO_CODEC_OK;
524 int VP8DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
526 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
528 int ret_val = Release();
532 if (decoder_ == NULL) {
533 decoder_ = new vpx_dec_ctx_t;
535 if (inst->codecType == kVideoCodecVP8) {
536 feedback_mode_ = inst->codecSpecific.VP8.feedbackModeOn;
538 vpx_codec_dec_cfg_t cfg;
539 // Setting number of threads to a constant value (1)
541 cfg.h = cfg.w = 0; // set after decode
543 vpx_codec_flags_t flags = 0;
544 #ifndef WEBRTC_ARCH_ARM
545 flags = VPX_CODEC_USE_POSTPROC;
546 if (inst->codecSpecific.VP8.errorConcealmentOn) {
547 flags |= VPX_CODEC_USE_ERROR_CONCEALMENT;
549 #ifdef INDEPENDENT_PARTITIONS
550 flags |= VPX_CODEC_USE_INPUT_PARTITION;
554 if (vpx_codec_dec_init(decoder_, vpx_codec_vp8_dx(), &cfg, flags)) {
555 return WEBRTC_VIDEO_CODEC_MEMORY;
558 #ifndef WEBRTC_ARCH_ARM
559 vp8_postproc_cfg_t ppcfg;
560 ppcfg.post_proc_flag = VP8_DEMACROBLOCK | VP8_DEBLOCK;
561 // Strength of deblocking filter. Valid range:[0,16]
562 ppcfg.deblocking_level = 3;
563 vpx_codec_control(decoder_, VP8_SET_POSTPROC, &ppcfg);
566 if (&codec_ != inst) {
567 // Save VideoCodec instance for later; mainly for duplicating the decoder.
571 propagation_cnt_ = -1;
575 // Always start with a complete key frame.
576 key_frame_required_ = true;
578 return WEBRTC_VIDEO_CODEC_OK;
581 int VP8DecoderImpl::Decode(const EncodedImage& input_image,
583 const RTPFragmentationHeader* fragmentation,
584 const CodecSpecificInfo* codec_specific_info,
585 int64_t /*render_time_ms*/) {
587 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
589 if (decode_complete_callback_ == NULL) {
590 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
592 if (input_image._buffer == NULL && input_image._length > 0) {
593 // Reset to avoid requesting key frames too often.
594 if (propagation_cnt_ > 0)
595 propagation_cnt_ = 0;
596 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
599 #ifdef INDEPENDENT_PARTITIONS
600 if (fragmentation == NULL) {
601 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
605 #ifndef WEBRTC_ARCH_ARM
606 if (!mfqe_enabled_ && codec_specific_info &&
607 codec_specific_info->codecSpecific.VP8.temporalIdx > 0) {
608 // Enable MFQE if we are receiving layers.
609 // temporalIdx is set in the jitter buffer according to what the RTP
611 mfqe_enabled_ = true;
612 vp8_postproc_cfg_t ppcfg;
613 ppcfg.post_proc_flag = VP8_MFQE | VP8_DEMACROBLOCK | VP8_DEBLOCK;
614 ppcfg.deblocking_level = 3;
615 vpx_codec_control(decoder_, VP8_SET_POSTPROC, &ppcfg);
620 // Always start with a complete key frame.
621 if (key_frame_required_) {
622 if (input_image._frameType != kKeyFrame)
623 return WEBRTC_VIDEO_CODEC_ERROR;
624 // We have a key frame - is it complete?
625 if (input_image._completeFrame) {
626 key_frame_required_ = false;
628 return WEBRTC_VIDEO_CODEC_ERROR;
631 // Restrict error propagation using key frame requests. Disabled when
632 // the feedback mode is enabled (RPS).
633 // Reset on a key frame refresh.
634 if (!feedback_mode_) {
635 if (input_image._frameType == kKeyFrame && input_image._completeFrame)
636 propagation_cnt_ = -1;
637 // Start count on first loss.
638 else if ((!input_image._completeFrame || missing_frames) &&
639 propagation_cnt_ == -1)
640 propagation_cnt_ = 0;
641 if (propagation_cnt_ >= 0)
645 vpx_codec_iter_t iter = NULL;
649 // Check for missing frames.
650 if (missing_frames) {
651 // Call decoder with zero data length to signal missing frames.
652 if (vpx_codec_decode(decoder_, NULL, 0, 0, VPX_DL_REALTIME)) {
653 // Reset to avoid requesting key frames too often.
654 if (propagation_cnt_ > 0)
655 propagation_cnt_ = 0;
656 return WEBRTC_VIDEO_CODEC_ERROR;
658 // We don't render this frame.
659 vpx_codec_get_frame(decoder_, &iter);
663 #ifdef INDEPENDENT_PARTITIONS
664 if (DecodePartitions(inputImage, fragmentation)) {
665 // Reset to avoid requesting key frames too often.
666 if (propagation_cnt_ > 0) {
667 propagation_cnt_ = 0;
669 return WEBRTC_VIDEO_CODEC_ERROR;
672 uint8_t* buffer = input_image._buffer;
673 if (input_image._length == 0) {
674 buffer = NULL; // Triggers full frame concealment.
676 if (vpx_codec_decode(decoder_,
681 // Reset to avoid requesting key frames too often.
682 if (propagation_cnt_ > 0)
683 propagation_cnt_ = 0;
684 return WEBRTC_VIDEO_CODEC_ERROR;
688 // Store encoded frame if key frame. (Used in Copy method.)
689 if (input_image._frameType == kKeyFrame && input_image._buffer != NULL) {
690 const uint32_t bytes_to_copy = input_image._length;
691 if (last_keyframe_._size < bytes_to_copy) {
692 delete [] last_keyframe_._buffer;
693 last_keyframe_._buffer = NULL;
694 last_keyframe_._size = 0;
697 uint8_t* temp_buffer = last_keyframe_._buffer; // Save buffer ptr.
698 uint32_t temp_size = last_keyframe_._size; // Save size.
699 last_keyframe_ = input_image; // Shallow copy.
700 last_keyframe_._buffer = temp_buffer; // Restore buffer ptr.
701 last_keyframe_._size = temp_size; // Restore buffer size.
702 if (!last_keyframe_._buffer) {
704 last_keyframe_._size = bytes_to_copy;
705 last_keyframe_._buffer = new uint8_t[last_keyframe_._size];
707 // Copy encoded frame.
708 memcpy(last_keyframe_._buffer, input_image._buffer, bytes_to_copy);
709 last_keyframe_._length = bytes_to_copy;
712 img = vpx_codec_get_frame(decoder_, &iter);
713 ret = ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_);
715 // Reset to avoid requesting key frames too often.
716 if (ret < 0 && propagation_cnt_ > 0)
717 propagation_cnt_ = 0;
720 if (feedback_mode_) {
721 // Whenever we receive an incomplete key frame all reference buffers will
722 // be corrupt. If that happens we must request new key frames until we
723 // decode a complete.
724 if (input_image._frameType == kKeyFrame && !input_image._completeFrame)
725 return WEBRTC_VIDEO_CODEC_ERROR;
727 // Check for reference updates and last reference buffer corruption and
728 // signal successful reference propagation or frame corruption to the
730 int reference_updates = 0;
731 if (vpx_codec_control(decoder_, VP8D_GET_LAST_REF_UPDATES,
732 &reference_updates)) {
733 // Reset to avoid requesting key frames too often.
734 if (propagation_cnt_ > 0)
735 propagation_cnt_ = 0;
736 return WEBRTC_VIDEO_CODEC_ERROR;
739 if (vpx_codec_control(decoder_, VP8D_GET_FRAME_CORRUPTED, &corrupted)) {
740 // Reset to avoid requesting key frames too often.
741 if (propagation_cnt_ > 0)
742 propagation_cnt_ = 0;
743 return WEBRTC_VIDEO_CODEC_ERROR;
745 int16_t picture_id = -1;
746 if (codec_specific_info) {
747 picture_id = codec_specific_info->codecSpecific.VP8.pictureId;
749 if (picture_id > -1) {
750 if (((reference_updates & VP8_GOLD_FRAME) ||
751 (reference_updates & VP8_ALTR_FRAME)) && !corrupted) {
752 decode_complete_callback_->ReceivedDecodedReferenceFrame(picture_id);
754 decode_complete_callback_->ReceivedDecodedFrame(picture_id);
757 // we can decode but with artifacts
758 return WEBRTC_VIDEO_CODEC_REQUEST_SLI;
761 // Check Vs. threshold
762 if (propagation_cnt_ > kVp8ErrorPropagationTh) {
763 // Reset to avoid requesting key frames too often.
764 propagation_cnt_ = 0;
765 return WEBRTC_VIDEO_CODEC_ERROR;
767 return WEBRTC_VIDEO_CODEC_OK;
770 int VP8DecoderImpl::DecodePartitions(
771 const EncodedImage& input_image,
772 const RTPFragmentationHeader* fragmentation) {
773 for (int i = 0; i < fragmentation->fragmentationVectorSize; ++i) {
774 const uint8_t* partition = input_image._buffer +
775 fragmentation->fragmentationOffset[i];
776 const uint32_t partition_length =
777 fragmentation->fragmentationLength[i];
778 if (vpx_codec_decode(decoder_,
783 return WEBRTC_VIDEO_CODEC_ERROR;
786 // Signal end of frame data. If there was no frame data this will trigger
787 // a full frame concealment.
788 if (vpx_codec_decode(decoder_, NULL, 0, 0, VPX_DL_REALTIME))
789 return WEBRTC_VIDEO_CODEC_ERROR;
790 return WEBRTC_VIDEO_CODEC_OK;
793 int VP8DecoderImpl::ReturnFrame(const vpx_image_t* img,
795 int64_t ntp_time_ms) {
797 // Decoder OK and NULL image => No show frame
798 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
800 int half_height = (img->d_h + 1) / 2;
801 int size_y = img->stride[VPX_PLANE_Y] * img->d_h;
802 int size_u = img->stride[VPX_PLANE_U] * half_height;
803 int size_v = img->stride[VPX_PLANE_V] * half_height;
804 // TODO(mikhal): This does a copy - need to SwapBuffers.
805 decoded_image_.CreateFrame(size_y, img->planes[VPX_PLANE_Y],
806 size_u, img->planes[VPX_PLANE_U],
807 size_v, img->planes[VPX_PLANE_V],
809 img->stride[VPX_PLANE_Y],
810 img->stride[VPX_PLANE_U],
811 img->stride[VPX_PLANE_V]);
812 decoded_image_.set_timestamp(timestamp);
813 decoded_image_.set_ntp_time_ms(ntp_time_ms);
814 int ret = decode_complete_callback_->Decoded(decoded_image_);
818 // Remember image format for later
819 image_format_ = img->fmt;
820 return WEBRTC_VIDEO_CODEC_OK;
823 int VP8DecoderImpl::RegisterDecodeCompleteCallback(
824 DecodedImageCallback* callback) {
825 decode_complete_callback_ = callback;
826 return WEBRTC_VIDEO_CODEC_OK;
829 int VP8DecoderImpl::Release() {
830 if (last_keyframe_._buffer != NULL) {
831 delete [] last_keyframe_._buffer;
832 last_keyframe_._buffer = NULL;
834 if (decoder_ != NULL) {
835 if (vpx_codec_destroy(decoder_)) {
836 return WEBRTC_VIDEO_CODEC_MEMORY;
841 if (ref_frame_ != NULL) {
842 vpx_img_free(&ref_frame_->img);
847 return WEBRTC_VIDEO_CODEC_OK;
850 VideoDecoder* VP8DecoderImpl::Copy() {
857 if (decoded_image_.IsZeroSize()) {
858 // Nothing has been decoded before; cannot clone.
861 if (last_keyframe_._buffer == NULL) {
862 // Cannot clone if we have no key frame to start with.
865 // Create a new VideoDecoder object
866 VP8DecoderImpl *copy = new VP8DecoderImpl;
868 // Initialize the new decoder
869 if (copy->InitDecode(&codec_, 1) != WEBRTC_VIDEO_CODEC_OK) {
873 // Inject last key frame into new decoder.
874 if (vpx_codec_decode(copy->decoder_, last_keyframe_._buffer,
875 last_keyframe_._length, NULL, VPX_DL_REALTIME)) {
879 // Allocate memory for reference image copy
880 assert(decoded_image_.width() > 0);
881 assert(decoded_image_.height() > 0);
882 assert(image_format_ > VPX_IMG_FMT_NONE);
883 // Check if frame format has changed.
885 (decoded_image_.width() != static_cast<int>(ref_frame_->img.d_w) ||
886 decoded_image_.height() != static_cast<int>(ref_frame_->img.d_h) ||
887 image_format_ != ref_frame_->img.fmt)) {
888 vpx_img_free(&ref_frame_->img);
895 ref_frame_ = new vpx_ref_frame_t;
897 unsigned int align = 16;
898 if (!vpx_img_alloc(&ref_frame_->img,
899 static_cast<vpx_img_fmt_t>(image_format_),
900 decoded_image_.width(), decoded_image_.height(),
907 const vpx_ref_frame_type_t type_vec[] = { VP8_LAST_FRAME, VP8_GOLD_FRAME,
909 for (uint32_t ix = 0;
910 ix < sizeof(type_vec) / sizeof(vpx_ref_frame_type_t); ++ix) {
911 ref_frame_->frame_type = type_vec[ix];
912 if (CopyReference(copy) < 0) {
917 // Copy all member variables (that are not set in initialization).
918 copy->feedback_mode_ = feedback_mode_;
919 copy->image_format_ = image_format_;
920 copy->last_keyframe_ = last_keyframe_; // Shallow copy.
921 // Allocate memory. (Discard copied _buffer pointer.)
922 copy->last_keyframe_._buffer = new uint8_t[last_keyframe_._size];
923 memcpy(copy->last_keyframe_._buffer, last_keyframe_._buffer,
924 last_keyframe_._length);
926 return static_cast<VideoDecoder*>(copy);
929 int VP8DecoderImpl::CopyReference(VP8Decoder* copyTo) {
930 // The type of frame to copy should be set in ref_frame_->frame_type
931 // before the call to this function.
932 if (vpx_codec_control(decoder_, VP8_COPY_REFERENCE, ref_frame_)
936 if (vpx_codec_control(static_cast<VP8DecoderImpl*>(copyTo)->decoder_,
937 VP8_SET_REFERENCE, ref_frame_) != VPX_CODEC_OK) {
943 } // namespace webrtc