Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / modules / video_coding / codecs / vp8 / vp8_impl.cc
1 /*
2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3  *
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.
9  *
10  * This file contains the WEBRTC VP8 wrapper implementation
11  *
12  */
13
14 #include "webrtc/modules/video_coding/codecs/vp8/vp8_impl.h"
15
16 #include <stdlib.h>
17 #include <string.h>
18 #include <time.h>
19 #include <vector>
20
21 #include "vpx/vpx_encoder.h"
22 #include "vpx/vpx_decoder.h"
23 #include "vpx/vp8cx.h"
24 #include "vpx/vp8dx.h"
25
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"
33
34 enum { kVp8ErrorPropagationTh = 30 };
35
36 namespace webrtc {
37
38 VP8EncoderImpl::VP8EncoderImpl()
39     : encoded_image_(),
40       encoded_complete_callback_(NULL),
41       inited_(false),
42       timestamp_(0),
43       picture_id_(0),
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),
50       encoder_(NULL),
51       config_(NULL),
52       raw_(NULL) {
53   memset(&codec_, 0, sizeof(codec_));
54   uint32_t seed = static_cast<uint32_t>(TickTime::MillisecondTimestamp());
55   srand(seed);
56 }
57
58 VP8EncoderImpl::~VP8EncoderImpl() {
59   Release();
60   delete rps_;
61 }
62
63 int VP8EncoderImpl::Release() {
64   if (encoded_image_._buffer != NULL) {
65     delete [] encoded_image_._buffer;
66     encoded_image_._buffer = NULL;
67   }
68   if (encoder_ != NULL) {
69     if (vpx_codec_destroy(encoder_)) {
70       return WEBRTC_VIDEO_CODEC_MEMORY;
71     }
72     delete encoder_;
73     encoder_ = NULL;
74   }
75   if (config_ != NULL) {
76     delete config_;
77     config_ = NULL;
78   }
79   if (raw_ != NULL) {
80     vpx_img_free(raw_);
81     raw_ = NULL;
82   }
83   delete temporal_layers_;
84   temporal_layers_ = NULL;
85   inited_ = false;
86   return WEBRTC_VIDEO_CODEC_OK;
87 }
88
89 int VP8EncoderImpl::SetRates(uint32_t new_bitrate_kbit,
90                              uint32_t new_framerate) {
91   if (!inited_) {
92     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
93   }
94   if (encoder_->err) {
95     return WEBRTC_VIDEO_CODEC_ERROR;
96   }
97   if (new_framerate < 1) {
98     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
99   }
100   // update bit rate
101   if (codec_.maxBitrate > 0 && new_bitrate_kbit > codec_.maxBitrate) {
102     new_bitrate_kbit = codec_.maxBitrate;
103   }
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;
108
109   // update encoder context
110   if (vpx_codec_enc_config_set(encoder_, config_)) {
111     return WEBRTC_VIDEO_CODEC_ERROR;
112   }
113   return WEBRTC_VIDEO_CODEC_OK;
114 }
115
116 int VP8EncoderImpl::InitEncode(const VideoCodec* inst,
117                                int number_of_cores,
118                                uint32_t /*max_payload_size*/) {
119   if (inst == NULL) {
120     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
121   }
122   if (inst->maxFramerate < 1) {
123     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
124   }
125   // allow zero to represent an unspecified maxBitRate
126   if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
127     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
128   }
129   if (inst->width < 1 || inst->height < 1) {
130     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
131   }
132   if (number_of_cores < 1) {
133     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
134   }
135   feedback_mode_ = inst->codecSpecific.VP8.feedbackModeOn;
136
137   int retVal = Release();
138   if (retVal < 0) {
139     return retVal;
140   }
141   if (encoder_ == NULL) {
142     encoder_ = new vpx_codec_ctx_t;
143   }
144   if (config_ == NULL) {
145     config_ = new vpx_codec_enc_cfg_t;
146   }
147   timestamp_ = 0;
148
149   if (&codec_ != inst) {
150     codec_ = *inst;
151   }
152
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;
157
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;
165
166   // allocate memory for encoded image
167   if (encoded_image_._buffer != NULL) {
168     delete [] encoded_image_._buffer;
169   }
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;
173
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,
178                       1, NULL);
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;
182   }
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;
191
192   // Set the error resilience mode according to user settings.
193   switch (inst->codecSpecific.VP8.resilience) {
194     case kResilienceOff:
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;
199       }
200       break;
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.
205       break;
206     case kResilientFrames:
207 #ifdef INDEPENDENT_PARTITIONS
208       config_->g_error_resilient = VPX_ERROR_RESILIENT_DEFAULT |
209       VPX_ERROR_RESILIENT_PARTITIONS;
210       break;
211 #else
212       return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;  // Not supported
213 #endif
214   }
215   config_->g_lag_in_frames = 0;  // 0- no frame lagging
216
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.
221   } else {
222     config_->g_threads = 1;  // 1 thread for VGA or less
223   }
224
225   // rate control settings
226   config_->rc_dropframe_thresh = inst->codecSpecific.VP8.frameDroppingOn ?
227       30 : 0;
228   config_->rc_end_usage = VPX_CBR;
229   config_->g_pass = VPX_RC_ONE_PASS;
230   config_->rc_resize_allowed = inst->codecSpecific.VP8.automaticResizeOn ?
231       1 : 0;
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);
241
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;
249   } else {
250     config_->kf_mode = VPX_KF_DISABLED;
251   }
252   switch (inst->codecSpecific.VP8.complexity) {
253     case kComplexityHigh:
254       cpu_speed_ = -5;
255       break;
256     case kComplexityHigher:
257       cpu_speed_ = -4;
258       break;
259     case kComplexityMax:
260       cpu_speed_ = -3;
261       break;
262     default:
263       cpu_speed_ = -6;
264       break;
265   }
266 #if defined(WEBRTC_ARCH_ARM)
267   // On mobile platform, always set to -12 to leverage between cpu usage
268   // and video quality
269   cpu_speed_ = -12;
270 #endif
271   rps_->Init();
272   return InitAndSetControlSettings(inst);
273 }
274
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
279   // video.
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;
283   }
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);
292 #endif
293   vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
294                     rc_max_intra_target_);
295   inited_ = true;
296   return WEBRTC_VIDEO_CODEC_OK;
297 }
298
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:
306
307   float scalePar = 0.5;
308   uint32_t targetPct = optimalBuffersize * scalePar * codec_.maxFramerate / 10;
309
310   // Don't go below 3 times the per frame bandwidth.
311   const uint32_t minIntraTh = 300;
312   return (targetPct < minIntraTh) ? minIntraTh: targetPct;
313 }
314
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());
319
320   if (!inited_) {
321     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
322   }
323   if (input_image.IsZeroSize()) {
324     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
325   }
326   if (encoded_complete_callback_ == NULL) {
327     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
328   }
329
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];
334   }
335
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);
340     if (ret < 0) {
341       return ret;
342     }
343   }
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);
353
354   int flags = temporal_layers_->EncodeFlags(input_image.timestamp());
355
356   bool send_keyframe = (frame_type == kKeyFrame);
357   if (send_keyframe) {
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) {
366         rps_->ReceivedRPSI(
367             codec_specific_info->codecSpecific.VP8.pictureIdRPSI);
368       }
369       if (codec_specific_info->codecSpecific.VP8.hasReceivedSLI) {
370         sendRefresh = rps_->ReceivedSLI(input_image.timestamp());
371       }
372     }
373     flags = rps_->EncodeFlags(picture_id_, sendRefresh,
374                               input_image.timestamp());
375   }
376
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,
385                        VPX_DL_REALTIME)) {
386     return WEBRTC_VIDEO_CODEC_ERROR;
387   }
388   timestamp_ += duration;
389
390   return GetEncodedPartitions(input_image);
391 }
392
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;
400
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);
405
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;
412   }
413   return WEBRTC_VIDEO_CODEC_OK;
414 }
415
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,
428           timestamp);
429   picture_id_ = (picture_id_ + 1) & 0x7FFF;  // prepare next
430 }
431
432 int VP8EncoderImpl::GetEncodedPartitions(const I420VideoFrame& input_image) {
433   vpx_codec_iter_t iter = NULL;
434   int part_idx = 0;
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;
440
441   const vpx_codec_cx_pkt_t *pkt = NULL;
442   while ((pkt = vpx_codec_get_cx_data(encoder_, &iter)) != NULL) {
443     switch (pkt->kind) {
444       case VPX_CODEC_CX_FRAME_PKT: {
445         memcpy(&encoded_image_._buffer[encoded_image_._length],
446                pkt->data.frame.buf,
447                pkt->data.frame.sz);
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);
454         ++part_idx;
455         break;
456       }
457       default: {
458         break;
459       }
460     }
461     // End of frame
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_);
467       }
468       PopulateCodecSpecific(&codec_specific, *pkt, input_image.timestamp());
469       break;
470     }
471   }
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,
479                                       &frag_info);
480   }
481   return WEBRTC_VIDEO_CODEC_OK;
482 }
483
484 int VP8EncoderImpl::SetChannelParameters(uint32_t /*packet_loss*/, int rtt) {
485   rps_->SetRtt(rtt);
486   return WEBRTC_VIDEO_CODEC_OK;
487 }
488
489 int VP8EncoderImpl::RegisterEncodeCompleteCallback(
490     EncodedImageCallback* callback) {
491   encoded_complete_callback_ = callback;
492   return WEBRTC_VIDEO_CODEC_OK;
493 }
494
495 VP8DecoderImpl::VP8DecoderImpl()
496     : decode_complete_callback_(NULL),
497       inited_(false),
498       feedback_mode_(false),
499       decoder_(NULL),
500       last_keyframe_(),
501       image_format_(VPX_IMG_FMT_NONE),
502       ref_frame_(NULL),
503       propagation_cnt_(-1),
504       mfqe_enabled_(false),
505       key_frame_required_(true) {
506   memset(&codec_, 0, sizeof(codec_));
507 }
508
509 VP8DecoderImpl::~VP8DecoderImpl() {
510   inited_ = true;  // in order to do the actual release
511   Release();
512 }
513
514 int VP8DecoderImpl::Reset() {
515   if (!inited_) {
516     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
517   }
518   InitDecode(&codec_, 1);
519   propagation_cnt_ = -1;
520   mfqe_enabled_ = false;
521   return WEBRTC_VIDEO_CODEC_OK;
522 }
523
524 int VP8DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
525   if (inst == NULL) {
526     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
527   }
528   int ret_val = Release();
529   if (ret_val < 0) {
530     return ret_val;
531   }
532   if (decoder_ == NULL) {
533     decoder_ = new vpx_dec_ctx_t;
534   }
535   if (inst->codecType == kVideoCodecVP8) {
536     feedback_mode_ = inst->codecSpecific.VP8.feedbackModeOn;
537   }
538   vpx_codec_dec_cfg_t  cfg;
539   // Setting number of threads to a constant value (1)
540   cfg.threads = 1;
541   cfg.h = cfg.w = 0;  // set after decode
542
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;
548   }
549 #ifdef INDEPENDENT_PARTITIONS
550   flags |= VPX_CODEC_USE_INPUT_PARTITION;
551 #endif
552 #endif
553
554   if (vpx_codec_dec_init(decoder_, vpx_codec_vp8_dx(), &cfg, flags)) {
555     return WEBRTC_VIDEO_CODEC_MEMORY;
556   }
557
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);
564 #endif
565
566   if (&codec_ != inst) {
567     // Save VideoCodec instance for later; mainly for duplicating the decoder.
568     codec_ = *inst;
569   }
570
571   propagation_cnt_ = -1;
572
573   inited_ = true;
574
575   // Always start with a complete key frame.
576   key_frame_required_ = true;
577
578   return WEBRTC_VIDEO_CODEC_OK;
579 }
580
581 int VP8DecoderImpl::Decode(const EncodedImage& input_image,
582                            bool missing_frames,
583                            const RTPFragmentationHeader* fragmentation,
584                            const CodecSpecificInfo* codec_specific_info,
585                            int64_t /*render_time_ms*/) {
586   if (!inited_) {
587     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
588   }
589   if (decode_complete_callback_ == NULL) {
590     return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
591   }
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;
597   }
598
599 #ifdef INDEPENDENT_PARTITIONS
600   if (fragmentation == NULL) {
601     return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
602   }
603 #endif
604
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
610     // header says.
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);
616   }
617 #endif
618
619
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;
627     } else {
628       return WEBRTC_VIDEO_CODEC_ERROR;
629     }
630   }
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)
642       propagation_cnt_++;
643   }
644
645   vpx_codec_iter_t iter = NULL;
646   vpx_image_t* img;
647   int ret;
648
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;
657     }
658     // We don't render this frame.
659     vpx_codec_get_frame(decoder_, &iter);
660     iter = NULL;
661   }
662
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;
668     }
669     return WEBRTC_VIDEO_CODEC_ERROR;
670   }
671 #else
672   uint8_t* buffer = input_image._buffer;
673   if (input_image._length == 0) {
674     buffer = NULL;  // Triggers full frame concealment.
675   }
676   if (vpx_codec_decode(decoder_,
677                        buffer,
678                        input_image._length,
679                        0,
680                        VPX_DL_REALTIME)) {
681     // Reset to avoid requesting key frames too often.
682     if (propagation_cnt_ > 0)
683       propagation_cnt_ = 0;
684     return WEBRTC_VIDEO_CODEC_ERROR;
685   }
686 #endif
687
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;
695     }
696
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) {
703       // Allocate memory.
704       last_keyframe_._size = bytes_to_copy;
705       last_keyframe_._buffer = new uint8_t[last_keyframe_._size];
706     }
707     // Copy encoded frame.
708     memcpy(last_keyframe_._buffer, input_image._buffer, bytes_to_copy);
709     last_keyframe_._length = bytes_to_copy;
710   }
711
712   img = vpx_codec_get_frame(decoder_, &iter);
713   ret = ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_);
714   if (ret != 0) {
715     // Reset to avoid requesting key frames too often.
716     if (ret < 0 && propagation_cnt_ > 0)
717       propagation_cnt_ = 0;
718     return ret;
719   }
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;
726
727     // Check for reference updates and last reference buffer corruption and
728     // signal successful reference propagation or frame corruption to the
729     // encoder.
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;
737     }
738     int corrupted = 0;
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;
744     }
745     int16_t picture_id = -1;
746     if (codec_specific_info) {
747       picture_id = codec_specific_info->codecSpecific.VP8.pictureId;
748     }
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);
753       }
754       decode_complete_callback_->ReceivedDecodedFrame(picture_id);
755     }
756     if (corrupted) {
757       // we can decode but with artifacts
758       return WEBRTC_VIDEO_CODEC_REQUEST_SLI;
759     }
760   }
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;
766   }
767   return WEBRTC_VIDEO_CODEC_OK;
768 }
769
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_,
779                          partition,
780                          partition_length,
781                          0,
782                          VPX_DL_REALTIME)) {
783       return WEBRTC_VIDEO_CODEC_ERROR;
784     }
785   }
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;
791 }
792
793 int VP8DecoderImpl::ReturnFrame(const vpx_image_t* img,
794                                 uint32_t timestamp,
795                                 int64_t ntp_time_ms) {
796   if (img == NULL) {
797     // Decoder OK and NULL image => No show frame
798     return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
799   }
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],
808                              img->d_w, img->d_h,
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_);
815   if (ret != 0)
816     return ret;
817
818   // Remember image format for later
819   image_format_ = img->fmt;
820   return WEBRTC_VIDEO_CODEC_OK;
821 }
822
823 int VP8DecoderImpl::RegisterDecodeCompleteCallback(
824     DecodedImageCallback* callback) {
825   decode_complete_callback_ = callback;
826   return WEBRTC_VIDEO_CODEC_OK;
827 }
828
829 int VP8DecoderImpl::Release() {
830   if (last_keyframe_._buffer != NULL) {
831     delete [] last_keyframe_._buffer;
832     last_keyframe_._buffer = NULL;
833   }
834   if (decoder_ != NULL) {
835     if (vpx_codec_destroy(decoder_)) {
836       return WEBRTC_VIDEO_CODEC_MEMORY;
837     }
838     delete decoder_;
839     decoder_ = NULL;
840   }
841   if (ref_frame_ != NULL) {
842     vpx_img_free(&ref_frame_->img);
843     delete ref_frame_;
844     ref_frame_ = NULL;
845   }
846   inited_ = false;
847   return WEBRTC_VIDEO_CODEC_OK;
848 }
849
850 VideoDecoder* VP8DecoderImpl::Copy() {
851   // Sanity checks.
852   if (!inited_) {
853     // Not initialized.
854     assert(false);
855     return NULL;
856   }
857   if (decoded_image_.IsZeroSize()) {
858     // Nothing has been decoded before; cannot clone.
859     return NULL;
860   }
861   if (last_keyframe_._buffer == NULL) {
862     // Cannot clone if we have no key frame to start with.
863     return NULL;
864   }
865   // Create a new VideoDecoder object
866   VP8DecoderImpl *copy = new VP8DecoderImpl;
867
868   // Initialize the new decoder
869   if (copy->InitDecode(&codec_, 1) != WEBRTC_VIDEO_CODEC_OK) {
870     delete copy;
871     return NULL;
872   }
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)) {
876     delete copy;
877     return NULL;
878   }
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.
884   if (ref_frame_ &&
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);
889     delete ref_frame_;
890     ref_frame_ = NULL;
891   }
892
893
894   if (!ref_frame_) {
895     ref_frame_ = new vpx_ref_frame_t;
896
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(),
901                        align)) {
902       assert(false);
903       delete copy;
904       return NULL;
905     }
906   }
907   const vpx_ref_frame_type_t type_vec[] = { VP8_LAST_FRAME, VP8_GOLD_FRAME,
908       VP8_ALTR_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) {
913       delete copy;
914       return NULL;
915     }
916   }
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);
925
926   return static_cast<VideoDecoder*>(copy);
927 }
928
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_)
933       != VPX_CODEC_OK) {
934     return -1;
935   }
936   if (vpx_codec_control(static_cast<VP8DecoderImpl*>(copyTo)->decoder_,
937                         VP8_SET_REFERENCE, ref_frame_) != VPX_CODEC_OK) {
938     return -1;
939   }
940   return 0;
941 }
942
943 }  // namespace webrtc