static void encode_frame_to_data_rate()

in media/libvpx/libvpx/vp8/encoder/onyx_if.c [3309:4766]


static void encode_frame_to_data_rate(VP8_COMP *cpi, size_t *size,
                                      unsigned char *dest,
                                      unsigned char *dest_end,
                                      unsigned int *frame_flags) {
  int Q;
  int frame_over_shoot_limit;
  int frame_under_shoot_limit;

  int Loop = 0;

  VP8_COMMON *cm = &cpi->common;
  int active_worst_qchanged = 0;

#if !CONFIG_REALTIME_ONLY
  int q_low;
  int q_high;
  int zbin_oq_high;
  int zbin_oq_low = 0;
  int top_index;
  int bottom_index;
  int overshoot_seen = 0;
  int undershoot_seen = 0;
#endif

  /* Clear down mmx registers to allow floating point in what follows */
  vpx_clear_system_state();

  if (cpi->force_next_frame_intra) {
    cm->frame_type = KEY_FRAME; /* delayed intra frame */
    cpi->force_next_frame_intra = 0;
  }

  /* For an alt ref frame in 2 pass we skip the call to the second pass
   * function that sets the target bandwidth
   */
  switch (cpi->pass) {
#if !CONFIG_REALTIME_ONLY
    case 2:
      if (cpi->common.refresh_alt_ref_frame) {
        /* Per frame bit target for the alt ref frame */
        cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
        /* per second target bitrate */
        cpi->target_bandwidth =
            (int)(cpi->twopass.gf_bits * cpi->output_framerate);
      }
      break;
#endif  // !CONFIG_REALTIME_ONLY
    default: {
      const double per_frame_bandwidth =
          round(cpi->target_bandwidth / cpi->output_framerate);
      cpi->per_frame_bandwidth = (int)VPXMIN(per_frame_bandwidth, INT_MAX);
      break;
    }
  }

  /* Default turn off buffer to buffer copying */
  cm->copy_buffer_to_gf = 0;
  cm->copy_buffer_to_arf = 0;

  /* Clear zbin over-quant value and mode boost values. */
  cpi->mb.zbin_over_quant = 0;
  cpi->mb.zbin_mode_boost = 0;

  /* Enable or disable mode based tweaking of the zbin
   * For 2 Pass Only used where GF/ARF prediction quality
   * is above a threshold
   */
  cpi->mb.zbin_mode_boost_enabled = 1;
  if (cpi->pass == 2) {
    if (cpi->gfu_boost <= 400) {
      cpi->mb.zbin_mode_boost_enabled = 0;
    }
  }

  /* Current default encoder behaviour for the altref sign bias */
  if (cpi->source_alt_ref_active) {
    cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
  } else {
    cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
  }

  /* Check to see if a key frame is signaled
   * For two pass with auto key frame enabled cm->frame_type may already
   * be set, but not for one pass.
   */
  if ((cm->current_video_frame == 0) || (cm->frame_flags & FRAMEFLAGS_KEY) ||
      (cpi->oxcf.auto_key &&
       (cpi->frames_since_key % cpi->key_frame_frequency == 0))) {
    /* Key frame from VFW/auto-keyframe/first frame */
    cm->frame_type = KEY_FRAME;
#if CONFIG_TEMPORAL_DENOISING
    if (cpi->oxcf.noise_sensitivity == 4) {
      // For adaptive mode, reset denoiser to normal mode on key frame.
      vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
    }
#endif
  }

#if CONFIG_MULTI_RES_ENCODING
  if (cpi->oxcf.mr_total_resolutions > 1) {
    LOWER_RES_FRAME_INFO *low_res_frame_info =
        (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;

    if (cpi->oxcf.mr_encoder_id) {
      // Check if lower resolution is available for motion vector reuse.
      if (cm->frame_type != KEY_FRAME) {
        cpi->mr_low_res_mv_avail = 1;
        cpi->mr_low_res_mv_avail &= !(low_res_frame_info->is_frame_dropped);

        if (cpi->ref_frame_flags & VP8_LAST_FRAME)
          cpi->mr_low_res_mv_avail &=
              (cpi->current_ref_frames[LAST_FRAME] ==
               low_res_frame_info->low_res_ref_frames[LAST_FRAME]);

        if (cpi->ref_frame_flags & VP8_GOLD_FRAME)
          cpi->mr_low_res_mv_avail &=
              (cpi->current_ref_frames[GOLDEN_FRAME] ==
               low_res_frame_info->low_res_ref_frames[GOLDEN_FRAME]);

        // Don't use altref to determine whether low res is available.
        // TODO (marpan): Should we make this type of condition on a
        // per-reference frame basis?
        /*
        if (cpi->ref_frame_flags & VP8_ALTR_FRAME)
            cpi->mr_low_res_mv_avail &= (cpi->current_ref_frames[ALTREF_FRAME]
                     == low_res_frame_info->low_res_ref_frames[ALTREF_FRAME]);
        */
      }
      // Disable motion vector reuse (i.e., disable any usage of the low_res)
      // if the previous lower stream is skipped/disabled.
      if (low_res_frame_info->skip_encoding_prev_stream) {
        cpi->mr_low_res_mv_avail = 0;
      }
    }
    // This stream is not skipped (i.e., it's being encoded), so set this skip
    // flag to 0. This is needed for the next stream (i.e., which is the next
    // frame to be encoded).
    low_res_frame_info->skip_encoding_prev_stream = 0;

    // On a key frame: For the lowest resolution, keep track of the key frame
    // counter value. For the higher resolutions, reset the current video
    // frame counter to that of the lowest resolution.
    // This is done to the handle the case where we may stop/start encoding
    // higher layer(s). The restart-encoding of higher layer is only signaled
    // by a key frame for now.
    // TODO (marpan): Add flag to indicate restart-encoding of higher layer.
    if (cm->frame_type == KEY_FRAME) {
      if (cpi->oxcf.mr_encoder_id) {
        // If the initial starting value of the buffer level is zero (this can
        // happen because we may have not started encoding this higher stream),
        // then reset it to non-zero value based on |starting_buffer_level|.
        if (cpi->common.current_video_frame == 0 && cpi->buffer_level == 0) {
          unsigned int i;
          cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
          cpi->buffer_level = cpi->oxcf.starting_buffer_level;
          for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
            LAYER_CONTEXT *lc = &cpi->layer_context[i];
            lc->bits_off_target = lc->starting_buffer_level;
            lc->buffer_level = lc->starting_buffer_level;
          }
        }
        cpi->common.current_video_frame =
            low_res_frame_info->key_frame_counter_value;
      } else {
        low_res_frame_info->key_frame_counter_value =
            cpi->common.current_video_frame;
      }
    }
  }
#endif

  // Find the reference frame closest to the current frame.
  cpi->closest_reference_frame = LAST_FRAME;
  if (cm->frame_type != KEY_FRAME) {
    int i;
    MV_REFERENCE_FRAME closest_ref = INTRA_FRAME;
    if (cpi->ref_frame_flags & VP8_LAST_FRAME) {
      closest_ref = LAST_FRAME;
    } else if (cpi->ref_frame_flags & VP8_GOLD_FRAME) {
      closest_ref = GOLDEN_FRAME;
    } else if (cpi->ref_frame_flags & VP8_ALTR_FRAME) {
      closest_ref = ALTREF_FRAME;
    }
    for (i = 1; i <= 3; ++i) {
      vpx_ref_frame_type_t ref_frame_type =
          (vpx_ref_frame_type_t)((i == 3) ? 4 : i);
      if (cpi->ref_frame_flags & ref_frame_type) {
        if ((cm->current_video_frame - cpi->current_ref_frames[i]) <
            (cm->current_video_frame - cpi->current_ref_frames[closest_ref])) {
          closest_ref = i;
        }
      }
    }
    cpi->closest_reference_frame = closest_ref;
  }

  /* Set various flags etc to special state if it is a key frame */
  if (cm->frame_type == KEY_FRAME) {
    int i;

    // Set the loop filter deltas and segmentation map update
    setup_features(cpi);

    /* The alternate reference frame cannot be active for a key frame */
    cpi->source_alt_ref_active = 0;

    /* Reset the RD threshold multipliers to default of * 1 (128) */
    for (i = 0; i < MAX_MODES; ++i) {
      cpi->mb.rd_thresh_mult[i] = 128;
    }

    // Reset the zero_last counter to 0 on key frame.
    memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
    memset(cpi->consec_zero_last_mvbias, 0,
           (cpi->common.mb_rows * cpi->common.mb_cols));
  }

#if 0
    /* Experimental code for lagged compress and one pass
     * Initialise one_pass GF frames stats
     * Update stats used for GF selection
     */
    {
        cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;

        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
    }
#endif

  update_rd_ref_frame_probs(cpi);

  if (vp8_check_drop_buffer(cpi)) {
    return;
  }

  /* Decide how big to make the frame */
  if (!vp8_pick_frame_size(cpi)) {
/*TODO: 2 drop_frame and return code could be put together. */
#if CONFIG_MULTI_RES_ENCODING
    vp8_store_drop_frame_info(cpi);
#endif
    cm->current_video_frame++;
    cpi->frames_since_key++;
    cpi->ext_refresh_frame_flags_pending = 0;
    // We advance the temporal pattern for dropped frames.
    cpi->temporal_pattern_counter++;
    return;
  }

  /* Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
   * This has a knock on effect on active best quality as well.
   * For CBR if the buffer reaches its maximum level then we can no longer
   * save up bits for later frames so we might as well use them up
   * on the current frame.
   */
  if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
      (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) &&
      cpi->buffered_mode) {
    /* Max adjustment is 1/4 */
    int Adjustment = cpi->active_worst_quality / 4;

    if (Adjustment) {
      int buff_lvl_step;

      if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size) {
        buff_lvl_step = (int)((cpi->oxcf.maximum_buffer_size -
                               cpi->oxcf.optimal_buffer_level) /
                              Adjustment);

        if (buff_lvl_step) {
          Adjustment =
              (int)((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) /
                    buff_lvl_step);
        } else {
          Adjustment = 0;
        }
      }

      cpi->active_worst_quality -= Adjustment;

      if (cpi->active_worst_quality < cpi->active_best_quality) {
        cpi->active_worst_quality = cpi->active_best_quality;
      }
    }
  }

  /* Set an active best quality and if necessary active worst quality
   * There is some odd behavior for one pass here that needs attention.
   */
  if ((cpi->pass == 2) || (cpi->ni_frames > 150)) {
    vpx_clear_system_state();

    Q = cpi->active_worst_quality;

    if (cm->frame_type == KEY_FRAME) {
      if (cpi->pass == 2) {
        if (cpi->gfu_boost > 600) {
          cpi->active_best_quality = kf_low_motion_minq[Q];
        } else {
          cpi->active_best_quality = kf_high_motion_minq[Q];
        }

        /* Special case for key frames forced because we have reached
         * the maximum key frame interval. Here force the Q to a range
         * based on the ambient Q to reduce the risk of popping
         */
        if (cpi->this_key_frame_forced) {
          if (cpi->active_best_quality > cpi->avg_frame_qindex * 7 / 8) {
            cpi->active_best_quality = cpi->avg_frame_qindex * 7 / 8;
          } else if (cpi->active_best_quality < (cpi->avg_frame_qindex >> 2)) {
            cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
          }
        }
      }
      /* One pass more conservative */
      else {
        cpi->active_best_quality = kf_high_motion_minq[Q];
      }
    }

    else if (cpi->oxcf.number_of_layers == 1 &&
             (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)) {
      /* Use the lower of cpi->active_worst_quality and recent
       * average Q as basis for GF/ARF Q limit unless last frame was
       * a key frame.
       */
      if ((cpi->frames_since_key > 1) &&
          (cpi->avg_frame_qindex < cpi->active_worst_quality)) {
        Q = cpi->avg_frame_qindex;
      }

      /* For constrained quality don't allow Q less than the cq level */
      if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
          (Q < cpi->cq_target_quality)) {
        Q = cpi->cq_target_quality;
      }

      if (cpi->pass == 2) {
        if (cpi->gfu_boost > 1000) {
          cpi->active_best_quality = gf_low_motion_minq[Q];
        } else if (cpi->gfu_boost < 400) {
          cpi->active_best_quality = gf_high_motion_minq[Q];
        } else {
          cpi->active_best_quality = gf_mid_motion_minq[Q];
        }

        /* Constrained quality use slightly lower active best. */
        if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
          cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
        }
      }
      /* One pass more conservative */
      else {
        cpi->active_best_quality = gf_high_motion_minq[Q];
      }
    } else {
      cpi->active_best_quality = inter_minq[Q];

      /* For the constant/constrained quality mode we don't want
       * q to fall below the cq level.
       */
      if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
          (cpi->active_best_quality < cpi->cq_target_quality)) {
        /* If we are strongly undershooting the target rate in the last
         * frames then use the user passed in cq value not the auto
         * cq value.
         */
        if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth) {
          cpi->active_best_quality = cpi->oxcf.cq_level;
        } else {
          cpi->active_best_quality = cpi->cq_target_quality;
        }
      }
    }

    /* If CBR and the buffer is as full then it is reasonable to allow
     * higher quality on the frames to prevent bits just going to waste.
     */
    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
      /* Note that the use of >= here elliminates the risk of a divide
       * by 0 error in the else if clause
       */
      if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size) {
        cpi->active_best_quality = cpi->best_quality;

      } else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level) {
        int Fraction =
            (int)(((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) /
                  (cpi->oxcf.maximum_buffer_size -
                   cpi->oxcf.optimal_buffer_level));
        int min_qadjustment =
            ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;

        cpi->active_best_quality -= min_qadjustment;
      }
    }
  }
  /* Make sure constrained quality mode limits are adhered to for the first
   * few frames of one pass encodes
   */
  else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
    if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
        cpi->common.refresh_alt_ref_frame) {
      cpi->active_best_quality = cpi->best_quality;
    } else if (cpi->active_best_quality < cpi->cq_target_quality) {
      cpi->active_best_quality = cpi->cq_target_quality;
    }
  }

  /* Clip the active best and worst quality values to limits */
  if (cpi->active_worst_quality > cpi->worst_quality) {
    cpi->active_worst_quality = cpi->worst_quality;
  }

  if (cpi->active_best_quality < cpi->best_quality) {
    cpi->active_best_quality = cpi->best_quality;
  }

  if (cpi->active_worst_quality < cpi->active_best_quality) {
    cpi->active_worst_quality = cpi->active_best_quality;
  }

  /* Determine initial Q to try */
  Q = vp8_regulate_q(cpi, cpi->this_frame_target);

#if !CONFIG_REALTIME_ONLY

  /* Set highest allowed value for Zbin over quant */
  if (cm->frame_type == KEY_FRAME) {
    zbin_oq_high = 0;
  } else if ((cpi->oxcf.number_of_layers == 1) &&
             ((cm->refresh_alt_ref_frame ||
               (cm->refresh_golden_frame && !cpi->source_alt_ref_active)))) {
    zbin_oq_high = 16;
  } else {
    zbin_oq_high = ZBIN_OQ_MAX;
  }
#endif

  compute_skin_map(cpi);

  /* Setup background Q adjustment for error resilient mode.
   * For multi-layer encodes only enable this for the base layer.
   */
  if (cpi->cyclic_refresh_mode_enabled) {
    // Special case for screen_content_mode with golden frame updates.
    int disable_cr_gf =
        (cpi->oxcf.screen_content_mode == 2 && cm->refresh_golden_frame);
    if (cpi->current_layer == 0 && cpi->force_maxqp == 0 && !disable_cr_gf) {
      cyclic_background_refresh(cpi, Q, 0);
    } else {
      disable_segmentation(cpi);
    }
  }

  vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
                                &frame_over_shoot_limit);

#if !CONFIG_REALTIME_ONLY
  /* Limit Q range for the adaptive loop. */
  bottom_index = cpi->active_best_quality;
  top_index = cpi->active_worst_quality;
  q_low = cpi->active_best_quality;
  q_high = cpi->active_worst_quality;
#endif

  vp8_save_coding_context(cpi);

  scale_and_extend_source(cpi->un_scaled_source, cpi);

#if CONFIG_TEMPORAL_DENOISING && CONFIG_POSTPROC
  // Option to apply spatial blur under the aggressive or adaptive
  // (temporal denoising) mode.
  if (cpi->oxcf.noise_sensitivity >= 3) {
    if (cpi->denoiser.denoise_pars.spatial_blur != 0) {
      vp8_de_noise(cm, cpi->Source, cpi->denoiser.denoise_pars.spatial_blur, 1);
    }
  }
#endif

#if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC && !(CONFIG_TEMPORAL_DENOISING)

  if (cpi->oxcf.noise_sensitivity > 0) {
    unsigned char *src;
    int l = 0;

    switch (cpi->oxcf.noise_sensitivity) {
      case 1: l = 20; break;
      case 2: l = 40; break;
      case 3: l = 60; break;
      case 4: l = 80; break;
      case 5: l = 100; break;
      case 6: l = 150; break;
    }

    if (cm->frame_type == KEY_FRAME) {
      vp8_de_noise(cm, cpi->Source, l, 1);
    } else {
      vp8_de_noise(cm, cpi->Source, l, 1);

      src = cpi->Source->y_buffer;

      if (cpi->Source->y_stride < 0) {
        src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
      }
    }
  }

#endif

#ifdef OUTPUT_YUV_SRC
  vpx_write_yuv_frame(yuv_file, cpi->Source);
#endif

  do {
    vpx_clear_system_state();

    vp8_set_quantizer(cpi, Q);

    /* setup skip prob for costing in mode/mv decision */
    if (cpi->common.mb_no_coeff_skip) {
      cpi->prob_skip_false = cpi->base_skip_false_prob[Q];

      if (cm->frame_type != KEY_FRAME) {
        if (cpi->common.refresh_alt_ref_frame) {
          if (cpi->last_skip_false_probs[2] != 0) {
            cpi->prob_skip_false = cpi->last_skip_false_probs[2];
          }

          /*
                              if(cpi->last_skip_false_probs[2]!=0 && abs(Q-
             cpi->last_skip_probs_q[2])<=16 )
             cpi->prob_skip_false = cpi->last_skip_false_probs[2];
                              else if (cpi->last_skip_false_probs[2]!=0)
             cpi->prob_skip_false = (cpi->last_skip_false_probs[2]  +
             cpi->prob_skip_false ) / 2;
             */
        } else if (cpi->common.refresh_golden_frame) {
          if (cpi->last_skip_false_probs[1] != 0) {
            cpi->prob_skip_false = cpi->last_skip_false_probs[1];
          }

          /*
                              if(cpi->last_skip_false_probs[1]!=0 && abs(Q-
             cpi->last_skip_probs_q[1])<=16 )
             cpi->prob_skip_false = cpi->last_skip_false_probs[1];
                              else if (cpi->last_skip_false_probs[1]!=0)
             cpi->prob_skip_false = (cpi->last_skip_false_probs[1]  +
             cpi->prob_skip_false ) / 2;
             */
        } else {
          if (cpi->last_skip_false_probs[0] != 0) {
            cpi->prob_skip_false = cpi->last_skip_false_probs[0];
          }

          /*
          if(cpi->last_skip_false_probs[0]!=0 && abs(Q-
          cpi->last_skip_probs_q[0])<=16 )
              cpi->prob_skip_false = cpi->last_skip_false_probs[0];
          else if(cpi->last_skip_false_probs[0]!=0)
              cpi->prob_skip_false = (cpi->last_skip_false_probs[0]  +
          cpi->prob_skip_false ) / 2;
              */
        }

        /* as this is for cost estimate, let's make sure it does not
         * go extreme eitehr way
         */
        if (cpi->prob_skip_false < 5) cpi->prob_skip_false = 5;

        if (cpi->prob_skip_false > 250) cpi->prob_skip_false = 250;

        if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref) {
          cpi->prob_skip_false = 1;
        }
      }

#if 0

            if (cpi->pass != 1)
            {
                FILE *f = fopen("skip.stt", "a");
                fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
                fclose(f);
            }

#endif
    }

    if (cm->frame_type == KEY_FRAME) {
      if (resize_key_frame(cpi)) {
        /* If the frame size has changed, need to reset Q, quantizer,
         * and background refresh.
         */
        Q = vp8_regulate_q(cpi, cpi->this_frame_target);
        if (cpi->cyclic_refresh_mode_enabled) {
          if (cpi->current_layer == 0) {
            cyclic_background_refresh(cpi, Q, 0);
          } else {
            disable_segmentation(cpi);
          }
        }
        // Reset the zero_last counter to 0 on key frame.
        memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
        memset(cpi->consec_zero_last_mvbias, 0,
               (cpi->common.mb_rows * cpi->common.mb_cols));
        vp8_set_quantizer(cpi, Q);
      }

      vp8_setup_key_frame(cpi);
    }

#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
    {
      if (cpi->oxcf.error_resilient_mode) cm->refresh_entropy_probs = 0;

      if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
        if (cm->frame_type == KEY_FRAME) cm->refresh_entropy_probs = 1;
      }

      if (cm->refresh_entropy_probs == 0) {
        /* save a copy for later refresh */
        memcpy(&cm->lfc, &cm->fc, sizeof(cm->fc));
      }

      vp8_update_coef_context(cpi);

      vp8_update_coef_probs(cpi);

      /* transform / motion compensation build reconstruction frame
       * +pack coef partitions
       */
      vp8_encode_frame(cpi);

      /* cpi->projected_frame_size is not needed for RT mode */
    }
#else
    /* transform / motion compensation build reconstruction frame */
    vp8_encode_frame(cpi);

    if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
        cpi->rt_drop_recode_on_overshoot == 1) {
      if (vp8_drop_encodedframe_overshoot(cpi, Q)) {
        vpx_clear_system_state();
        return;
      }
      if (cm->frame_type != KEY_FRAME)
        cpi->last_pred_err_mb =
            (int)(cpi->mb.prediction_error / cpi->common.MBs);
    }

    cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
    cpi->projected_frame_size =
        (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
#endif
    vpx_clear_system_state();

    /* Test to see if the stats generated for this frame indicate that
     * we should have coded a key frame (assuming that we didn't)!
     */

    if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME &&
        cpi->compressor_speed != 2) {
#if !CONFIG_REALTIME_ONLY
      if (decide_key_frame(cpi)) {
        /* Reset all our sizing numbers and recode */
        cm->frame_type = KEY_FRAME;

        vp8_pick_frame_size(cpi);

        /* Clear the Alt reference frame active flag when we have
         * a key frame
         */
        cpi->source_alt_ref_active = 0;

        // Set the loop filter deltas and segmentation map update
        setup_features(cpi);

        vp8_restore_coding_context(cpi);

        Q = vp8_regulate_q(cpi, cpi->this_frame_target);

        vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
                                      &frame_over_shoot_limit);

        /* Limit Q range for the adaptive loop. */
        bottom_index = cpi->active_best_quality;
        top_index = cpi->active_worst_quality;
        q_low = cpi->active_best_quality;
        q_high = cpi->active_worst_quality;

        Loop = 1;

        continue;
      }
#endif
    }

    vpx_clear_system_state();

    if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;

    /* Are we are overshooting and up against the limit of active max Q. */
    if (!cpi->rt_always_update_correction_factor &&
        ((cpi->pass != 2) ||
         (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
        (Q == cpi->active_worst_quality) &&
        (cpi->active_worst_quality < cpi->worst_quality) &&
        (cpi->projected_frame_size > frame_over_shoot_limit)) {
      int over_size_percent =
          ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) /
          frame_over_shoot_limit;

      /* If so is there any scope for relaxing it */
      while ((cpi->active_worst_quality < cpi->worst_quality) &&
             (over_size_percent > 0)) {
        cpi->active_worst_quality++;
        /* Assume 1 qstep = about 4% on frame size. */
        over_size_percent = (int)(over_size_percent * 0.96);
      }
#if !CONFIG_REALTIME_ONLY
      top_index = cpi->active_worst_quality;
#endif  // !CONFIG_REALTIME_ONLY
      /* If we have updated the active max Q do not call
       * vp8_update_rate_correction_factors() this loop.
       */
      active_worst_qchanged = 1;
    } else {
      active_worst_qchanged = 0;
    }

#if CONFIG_REALTIME_ONLY
    Loop = 0;
#else
    /* Special case handling for forced key frames */
    if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
      int last_q = Q;
      int kf_err = vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);

      /* The key frame is not good enough */
      if (kf_err > ((cpi->ambient_err * 7) >> 3)) {
        /* Lower q_high */
        q_high = (Q > q_low) ? (Q - 1) : q_low;

        /* Adjust Q */
        Q = (q_high + q_low) >> 1;
      }
      /* The key frame is much better than the previous frame */
      else if (kf_err < (cpi->ambient_err >> 1)) {
        /* Raise q_low */
        q_low = (Q < q_high) ? (Q + 1) : q_high;

        /* Adjust Q */
        Q = (q_high + q_low + 1) >> 1;
      }

      /* Clamp Q to upper and lower limits: */
      if (Q > q_high) {
        Q = q_high;
      } else if (Q < q_low) {
        Q = q_low;
      }

      Loop = Q != last_q;
    }

    /* Is the projected frame size out of range and are we allowed
     * to attempt to recode.
     */
    else if (recode_loop_test(cpi, frame_over_shoot_limit,
                              frame_under_shoot_limit, Q, top_index,
                              bottom_index)) {
      int last_q = Q;
      int Retries = 0;

      /* Frame size out of permitted range. Update correction factor
       * & compute new Q to try...
       */

      /* Frame is too large */
      if (cpi->projected_frame_size > cpi->this_frame_target) {
        /* Raise Qlow as to at least the current value */
        q_low = (Q < q_high) ? (Q + 1) : q_high;

        /* If we are using over quant do the same for zbin_oq_low */
        if (cpi->mb.zbin_over_quant > 0) {
          zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
                            ? (cpi->mb.zbin_over_quant + 1)
                            : zbin_oq_high;
        }

        if (undershoot_seen) {
          /* Update rate_correction_factor unless
           * cpi->active_worst_quality has changed.
           */
          if (!active_worst_qchanged) {
            vp8_update_rate_correction_factors(cpi, 1);
          }

          Q = (q_high + q_low + 1) / 2;

          /* Adjust cpi->zbin_over_quant (only allowed when Q
           * is max)
           */
          if (Q < MAXQ) {
            cpi->mb.zbin_over_quant = 0;
          } else {
            zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
                              ? (cpi->mb.zbin_over_quant + 1)
                              : zbin_oq_high;
            cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
          }
        } else {
          /* Update rate_correction_factor unless
           * cpi->active_worst_quality has changed.
           */
          if (!active_worst_qchanged) {
            vp8_update_rate_correction_factors(cpi, 0);
          }

          Q = vp8_regulate_q(cpi, cpi->this_frame_target);

          while (((Q < q_low) || (cpi->mb.zbin_over_quant < zbin_oq_low)) &&
                 (Retries < 10)) {
            vp8_update_rate_correction_factors(cpi, 0);
            Q = vp8_regulate_q(cpi, cpi->this_frame_target);
            Retries++;
          }
        }

        overshoot_seen = 1;
      }
      /* Frame is too small */
      else {
        if (cpi->mb.zbin_over_quant == 0) {
          /* Lower q_high if not using over quant */
          q_high = (Q > q_low) ? (Q - 1) : q_low;
        } else {
          /* else lower zbin_oq_high */
          zbin_oq_high = (cpi->mb.zbin_over_quant > zbin_oq_low)
                             ? (cpi->mb.zbin_over_quant - 1)
                             : zbin_oq_low;
        }

        if (overshoot_seen) {
          /* Update rate_correction_factor unless
           * cpi->active_worst_quality has changed.
           */
          if (!active_worst_qchanged) {
            vp8_update_rate_correction_factors(cpi, 1);
          }

          Q = (q_high + q_low) / 2;

          /* Adjust cpi->zbin_over_quant (only allowed when Q
           * is max)
           */
          if (Q < MAXQ) {
            cpi->mb.zbin_over_quant = 0;
          } else {
            cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
          }
        } else {
          /* Update rate_correction_factor unless
           * cpi->active_worst_quality has changed.
           */
          if (!active_worst_qchanged) {
            vp8_update_rate_correction_factors(cpi, 0);
          }

          Q = vp8_regulate_q(cpi, cpi->this_frame_target);

          /* Special case reset for qlow for constrained quality.
           * This should only trigger where there is very substantial
           * undershoot on a frame and the auto cq level is above
           * the user passsed in value.
           */
          if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
              (Q < q_low)) {
            q_low = Q;
          }

          while (((Q > q_high) || (cpi->mb.zbin_over_quant > zbin_oq_high)) &&
                 (Retries < 10)) {
            vp8_update_rate_correction_factors(cpi, 0);
            Q = vp8_regulate_q(cpi, cpi->this_frame_target);
            Retries++;
          }
        }

        undershoot_seen = 1;
      }

      /* Clamp Q to upper and lower limits: */
      if (Q > q_high) {
        Q = q_high;
      } else if (Q < q_low) {
        Q = q_low;
      }

      /* Clamp cpi->zbin_over_quant */
      cpi->mb.zbin_over_quant =
          (cpi->mb.zbin_over_quant < zbin_oq_low)    ? zbin_oq_low
          : (cpi->mb.zbin_over_quant > zbin_oq_high) ? zbin_oq_high
                                                     : cpi->mb.zbin_over_quant;

      Loop = Q != last_q;
    } else {
      Loop = 0;
    }
#endif  // CONFIG_REALTIME_ONLY

    if (cpi->is_src_frame_alt_ref) Loop = 0;

    if (Loop == 1) {
      vp8_restore_coding_context(cpi);
#if CONFIG_INTERNAL_STATS
      cpi->tot_recode_hits++;
#endif
    }
  } while (Loop == 1);

#if defined(DROP_UNCODED_FRAMES)
  /* if there are no coded macroblocks at all drop this frame */
  if (cpi->common.MBs == cpi->mb.skip_true_count &&
      (cpi->drop_frame_count & 7) != 7 && cm->frame_type != KEY_FRAME) {
    cpi->common.current_video_frame++;
    cpi->frames_since_key++;
    cpi->drop_frame_count++;
    cpi->ext_refresh_frame_flags_pending = 0;
    // We advance the temporal pattern for dropped frames.
    cpi->temporal_pattern_counter++;
    return;
  }
  cpi->drop_frame_count = 0;
#endif

#if 0
    /* Experimental code for lagged and one pass
     * Update stats used for one pass GF selection
     */
    {
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
        cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
    }
#endif

  /* Special case code to reduce pulsing when key frames are forced at a
   * fixed interval. Note the reconstruction error if it is the frame before
   * the force key frame
   */
  if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
    cpi->ambient_err =
        vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
  }

/* This frame's MVs are saved and will be used in next frame's MV predictor.
 * Last frame has one more line(add to bottom) and one more column(add to
 * right) than cm->mip. The edge elements are initialized to 0.
 */
#if CONFIG_MULTI_RES_ENCODING
  if (!cpi->oxcf.mr_encoder_id && cm->show_frame)
#else
  if (cm->show_frame) /* do not save for altref frame */
#endif
  {
    int mb_row;
    int mb_col;
    /* Point to beginning of allocated MODE_INFO arrays. */
    MODE_INFO *tmp = cm->mip;

    if (cm->frame_type != KEY_FRAME) {
      for (mb_row = 0; mb_row < cm->mb_rows + 1; ++mb_row) {
        for (mb_col = 0; mb_col < cm->mb_cols + 1; ++mb_col) {
          if (tmp->mbmi.ref_frame != INTRA_FRAME) {
            cpi->lfmv[mb_col + mb_row * (cm->mode_info_stride + 1)].as_int =
                tmp->mbmi.mv.as_int;
          }

          cpi->lf_ref_frame_sign_bias[mb_col +
                                      mb_row * (cm->mode_info_stride + 1)] =
              cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
          cpi->lf_ref_frame[mb_col + mb_row * (cm->mode_info_stride + 1)] =
              tmp->mbmi.ref_frame;
          tmp++;
        }
      }
    }
  }

  /* Count last ref frame 0,0 usage on current encoded frame. */
  {
    int mb_row;
    int mb_col;
    /* Point to beginning of MODE_INFO arrays. */
    MODE_INFO *tmp = cm->mi;

    cpi->zeromv_count = 0;

    if (cm->frame_type != KEY_FRAME) {
      for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
        for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
          if (tmp->mbmi.mode == ZEROMV && tmp->mbmi.ref_frame == LAST_FRAME) {
            cpi->zeromv_count++;
          }
          tmp++;
        }
        tmp++;
      }
    }
  }

#if CONFIG_MULTI_RES_ENCODING
  vp8_cal_dissimilarity(cpi);
#endif

  /* Update the GF usage maps.
   * This is done after completing the compression of a frame when all
   * modes etc. are finalized but before loop filter
   */
  if (cpi->oxcf.number_of_layers == 1) {
    vp8_update_gf_usage_maps(cpi, cm, &cpi->mb);
  }

  if (cm->frame_type == KEY_FRAME) cm->refresh_last_frame = 1;

#if 0
    {
        FILE *f = fopen("gfactive.stt", "a");
        fprintf(f, "%8d %8d %8d %8d %8d\n", cm->current_video_frame, (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols), cpi->this_iiratio, cpi->next_iiratio, cm->refresh_golden_frame);
        fclose(f);
    }
#endif

  /* For inter frames the current default behavior is that when
   * cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
   * This is purely an encoder decision at present.
   * Avoid this behavior when refresh flags are set by the user.
   */
  if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame &&
      !cpi->ext_refresh_frame_flags_pending) {
    cm->copy_buffer_to_arf = 2;
  } else {
    cm->copy_buffer_to_arf = 0;
  }

  cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];

#if CONFIG_TEMPORAL_DENOISING
  // Get some measure of the amount of noise, by measuring the (partial) mse
  // between source and denoised buffer, for y channel. Partial refers to
  // computing the sse for a sub-sample of the frame (i.e., skip x blocks along
  // row/column),
  // and only for blocks in that set that are consecutive ZEROMV_LAST mode.
  // Do this every ~8 frames, to further reduce complexity.
  // TODO(marpan): Keep this for now for the case cpi->oxcf.noise_sensitivity <
  // 4,
  // should be removed in favor of the process_denoiser_mode_change() function
  // below.
  if (cpi->oxcf.noise_sensitivity > 0 && cpi->oxcf.noise_sensitivity < 4 &&
      !cpi->oxcf.screen_content_mode && cpi->frames_since_key % 8 == 0 &&
      cm->frame_type != KEY_FRAME) {
    cpi->mse_source_denoised = measure_square_diff_partial(
        &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi->Source, cpi);
  }

  // For the adaptive denoising mode (noise_sensitivity == 4), sample the mse
  // of source diff (between current and previous frame), and determine if we
  // should switch the denoiser mode. Sampling refers to computing the mse for
  // a sub-sample of the frame (i.e., skip x blocks along row/column), and
  // only for blocks in that set that have used ZEROMV LAST, along with some
  // constraint on the sum diff between blocks. This process is called every
  // ~8 frames, to further reduce complexity.
  if (cpi->oxcf.noise_sensitivity == 4 && !cpi->oxcf.screen_content_mode &&
      cpi->frames_since_key % 8 == 0 && cm->frame_type != KEY_FRAME) {
    process_denoiser_mode_change(cpi);
  }
#endif

#ifdef OUTPUT_YUV_SKINMAP
  if (cpi->common.current_video_frame > 1) {
    vp8_compute_skin_map(cpi, yuv_skinmap_file);
  }
#endif

#if CONFIG_MULTITHREAD
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
    /* start loopfilter in separate thread */
    vp8_sem_post(&cpi->h_event_start_lpf);
    cpi->b_lpf_running = 1;
    /* wait for the filter_level to be picked so that we can continue with
     * stream packing */
    vp8_sem_wait(&cpi->h_event_end_lpf);
  } else
#endif
  {
    vp8_loopfilter_frame(cpi, cm);
  }

  update_reference_frames(cpi);

#ifdef OUTPUT_YUV_DENOISED
  vpx_write_yuv_frame(yuv_denoised_file,
                      &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
#endif

#if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
  if (cpi->oxcf.error_resilient_mode) {
    cm->refresh_entropy_probs = 0;
  }
#endif

  /* build the bitstream */
  vp8_pack_bitstream(cpi, dest, dest_end, size);

  /* Move storing frame_type out of the above loop since it is also
   * needed in motion search besides loopfilter */
  cm->last_frame_type = cm->frame_type;

  /* Update rate control heuristics */
  cpi->total_byte_count += (*size);
  cpi->projected_frame_size = (int)(*size) << 3;

  if (cpi->oxcf.number_of_layers > 1) {
    unsigned int i;
    for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
      cpi->layer_context[i].total_byte_count += (*size);
    }
  }

  if (!active_worst_qchanged) vp8_update_rate_correction_factors(cpi, 2);

  cpi->last_q[cm->frame_type] = cm->base_qindex;

  if (cm->frame_type == KEY_FRAME) {
    vp8_adjust_key_frame_context(cpi);
  }

  /* Keep a record of ambient average Q. */
  if (cm->frame_type != KEY_FRAME) {
    cpi->avg_frame_qindex =
        (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
  }

  /* Keep a record from which we can calculate the average Q excluding
   * GF updates and key frames
   */
  if ((cm->frame_type != KEY_FRAME) &&
      ((cpi->oxcf.number_of_layers > 1) ||
       (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame))) {
    cpi->ni_frames++;

    /* Calculate the average Q for normal inter frames (not key or GFU
     * frames).
     */
    if (cpi->pass == 2) {
      cpi->ni_tot_qi += Q;
      cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
    } else {
      /* Damp value for first few frames */
      if (cpi->ni_frames > 150) {
        cpi->ni_tot_qi += Q;
        cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
      }
      /* For one pass, early in the clip ... average the current frame Q
       * value with the worstq entered by the user as a dampening measure
       */
      else {
        cpi->ni_tot_qi += Q;
        cpi->ni_av_qi =
            ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
      }

      /* If the average Q is higher than what was used in the last
       * frame (after going through the recode loop to keep the frame
       * size within range) then use the last frame value - 1. The -1
       * is designed to stop Q and hence the data rate, from
       * progressively falling away during difficult sections, but at
       * the same time reduce the number of iterations around the
       * recode loop.
       */
      if (Q > cpi->ni_av_qi) cpi->ni_av_qi = Q - 1;
    }
  }

  /* Update the buffer level variable. */
  /* Non-viewable frames are a special case and are treated as pure overhead. */
  if (!cm->show_frame) {
    cpi->bits_off_target -= cpi->projected_frame_size;
  } else {
    cpi->bits_off_target +=
        cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
  }

  /* Clip the buffer level to the maximum specified buffer size */
  if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
    cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
  }

  // Don't let the buffer level go below some threshold, given here
  // by -|maximum_buffer_size|. For now we only do this for
  // screen content input.
  if (cpi->oxcf.screen_content_mode &&
      cpi->bits_off_target < -cpi->oxcf.maximum_buffer_size) {
    cpi->bits_off_target = -cpi->oxcf.maximum_buffer_size;
  }

  /* Rolling monitors of whether we are over or underspending used to
   * help regulate min and Max Q in two pass.
   */
  cpi->rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
      (int64_t)cpi->rolling_target_bits * 3 + cpi->this_frame_target, 2);
  cpi->rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
      (int64_t)cpi->rolling_actual_bits * 3 + cpi->projected_frame_size, 2);
  cpi->long_rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
      (int64_t)cpi->long_rolling_target_bits * 31 + cpi->this_frame_target, 5);
  cpi->long_rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
      (int64_t)cpi->long_rolling_actual_bits * 31 + cpi->projected_frame_size,
      5);

  /* Actual bits spent */
  cpi->total_actual_bits += cpi->projected_frame_size;

#if 0 && CONFIG_INTERNAL_STATS
  /* Debug stats */
  cpi->total_target_vs_actual +=
      (cpi->this_frame_target - cpi->projected_frame_size);
#endif

  cpi->buffer_level = cpi->bits_off_target;

  /* Propagate values to higher temporal layers */
  if (cpi->oxcf.number_of_layers > 1) {
    unsigned int i;

    for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
      LAYER_CONTEXT *lc = &cpi->layer_context[i];
      int bits_off_for_this_layer = (int)round(
          lc->target_bandwidth / lc->framerate - cpi->projected_frame_size);

      lc->bits_off_target += bits_off_for_this_layer;

      /* Clip buffer level to maximum buffer size for the layer */
      if (lc->bits_off_target > lc->maximum_buffer_size) {
        lc->bits_off_target = lc->maximum_buffer_size;
      }

      lc->total_actual_bits += cpi->projected_frame_size;
      lc->total_target_vs_actual += bits_off_for_this_layer;
      lc->buffer_level = lc->bits_off_target;
    }
  }

  /* Update bits left to the kf and gf groups to account for overshoot
   * or undershoot on these frames
   */
  if (cm->frame_type == KEY_FRAME) {
    cpi->twopass.kf_group_bits +=
        cpi->this_frame_target - cpi->projected_frame_size;

    if (cpi->twopass.kf_group_bits < 0) cpi->twopass.kf_group_bits = 0;
  } else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame) {
    cpi->twopass.gf_group_bits +=
        cpi->this_frame_target - cpi->projected_frame_size;

    if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
  }

  if (cm->frame_type != KEY_FRAME) {
    if (cpi->common.refresh_alt_ref_frame) {
      cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
      cpi->last_skip_probs_q[2] = cm->base_qindex;
    } else if (cpi->common.refresh_golden_frame) {
      cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
      cpi->last_skip_probs_q[1] = cm->base_qindex;
    } else {
      cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
      cpi->last_skip_probs_q[0] = cm->base_qindex;

      /* update the baseline */
      cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
    }
  }

#if 0 && CONFIG_INTERNAL_STATS
    {
        FILE *f = fopen("tmp.stt", "a");

        vpx_clear_system_state();

        if (cpi->twopass.total_left_stats.coded_error != 0.0)
            fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
                       "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
                       "%8.2lf %"PRId64" %10.3lf %10"PRId64" %8d\n",
                       cpi->common.current_video_frame, cpi->this_frame_target,
                       cpi->projected_frame_size,
                       (cpi->projected_frame_size - cpi->this_frame_target),
                       cpi->total_target_vs_actual,
                       cpi->buffer_level,
                       (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
                       cpi->total_actual_bits, cm->base_qindex,
                       cpi->active_best_quality, cpi->active_worst_quality,
                       cpi->ni_av_qi, cpi->cq_target_quality,
                       cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
                       cm->frame_type, cpi->gfu_boost,
                       cpi->twopass.est_max_qcorrection_factor,
                       cpi->twopass.bits_left,
                       cpi->twopass.total_left_stats.coded_error,
                       (double)cpi->twopass.bits_left /
                           cpi->twopass.total_left_stats.coded_error,
                       cpi->tot_recode_hits);
        else
            fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
                       "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
                       "%8.2lf %"PRId64" %10.3lf %8d\n",
                       cpi->common.current_video_frame, cpi->this_frame_target,
                       cpi->projected_frame_size,
                       (cpi->projected_frame_size - cpi->this_frame_target),
                       cpi->total_target_vs_actual,
                       cpi->buffer_level,
                       (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
                       cpi->total_actual_bits, cm->base_qindex,
                       cpi->active_best_quality, cpi->active_worst_quality,
                       cpi->ni_av_qi, cpi->cq_target_quality,
                       cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
                       cm->frame_type, cpi->gfu_boost,
                       cpi->twopass.est_max_qcorrection_factor,
                       cpi->twopass.bits_left,
                       cpi->twopass.total_left_stats.coded_error,
                       cpi->tot_recode_hits);

        fclose(f);

        {
            FILE *fmodes = fopen("Modes.stt", "a");

            fprintf(fmodes, "%6d:%1d:%1d:%1d ",
                        cpi->common.current_video_frame,
                        cm->frame_type, cm->refresh_golden_frame,
                        cm->refresh_alt_ref_frame);

            fprintf(fmodes, "\n");

            fclose(fmodes);
        }
    }

#endif

  cpi->ext_refresh_frame_flags_pending = 0;

  if (cm->refresh_golden_frame == 1) {
    cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
  } else {
    cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_GOLDEN;
  }

  if (cm->refresh_alt_ref_frame == 1) {
    cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
  } else {
    cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_ALTREF;
  }

  if (cm->refresh_last_frame & cm->refresh_golden_frame) { /* both refreshed */
    cpi->gold_is_last = 1;
  } else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) {
    /* 1 refreshed but not the other */
    cpi->gold_is_last = 0;
  }

  if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) { /* both refreshed */
    cpi->alt_is_last = 1;
  } else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) {
    /* 1 refreshed but not the other */
    cpi->alt_is_last = 0;
  }

  if (cm->refresh_alt_ref_frame &
      cm->refresh_golden_frame) { /* both refreshed */
    cpi->gold_is_alt = 1;
  } else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) {
    /* 1 refreshed but not the other */
    cpi->gold_is_alt = 0;
  }

  cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;

  if (cpi->gold_is_last) cpi->ref_frame_flags &= ~VP8_GOLD_FRAME;

  if (cpi->alt_is_last) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;

  if (cpi->gold_is_alt) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;

  if (!cpi->oxcf.error_resilient_mode) {
    if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame &&
        (cm->frame_type != KEY_FRAME)) {
      /* Update the alternate reference frame stats as appropriate. */
      update_alt_ref_frame_stats(cpi);
    } else {
      /* Update the Golden frame stats as appropriate. */
      update_golden_frame_stats(cpi);
    }
  }

  if (cm->frame_type == KEY_FRAME) {
    /* Tell the caller that the frame was coded as a key frame */
    *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;

    /* As this frame is a key frame  the next defaults to an inter frame. */
    cm->frame_type = INTER_FRAME;

    cpi->last_frame_percent_intra = 100;
  } else {
    *frame_flags = cm->frame_flags & ~FRAMEFLAGS_KEY;

    cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
  }

  /* Clear the one shot update flags for segmentation map and mode/ref
   * loop filter deltas.
   */
  cpi->mb.e_mbd.update_mb_segmentation_map = 0;
  cpi->mb.e_mbd.update_mb_segmentation_data = 0;
  cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;

  /* Don't increment frame counters if this was an altref buffer update
   * not a real frame
   */
  if (cm->show_frame) {
    cm->current_video_frame++;
    cpi->frames_since_key++;
    cpi->temporal_pattern_counter++;
  }

#if 0
    {
        char filename[512];
        FILE *recon_file;
        sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
        recon_file = fopen(filename, "wb");
        fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
               cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
        fclose(recon_file);
    }
#endif

  /* DEBUG */
  /* vpx_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show); */
}