static int rate_control(AVCodecContext *avctx, void *arg)
{
    SliceArgs *slice_dat = arg;
    VC2EncContext *s = slice_dat->ctx;
    const int sx = slice_dat->x;
    const int sy = slice_dat->y;
    int bits_last = INT_MAX, quant_buf[2] = {-1, -1};
    int quant = slice_dat->quant_idx, range = quant/5;
    const int top = slice_dat->bits_ceil;
    const int bottom = slice_dat->bits_floor;
    int bits = count_hq_slice(s, slice_dat->cache, sx, sy, quant);
    range -= range & 1; /* Make it an even number */
    while ((bits > top) || (bits < bottom)) {
        range *= bits > top ? +1 : -1;
        quant = av_clip(quant + range, 0, s->q_ceil);
        bits = count_hq_slice(s, slice_dat->cache, sx, sy, quant);
        range = av_clip(range/2, 1, s->q_ceil);
        if (quant_buf[1] == quant) {
            quant = bits_last < bits ? quant_buf[0] : quant;
            bits  = bits_last < bits ? bits_last : bits;
            break;
        }
        quant_buf[1] = quant_buf[0];
        quant_buf[0] = quant;
        bits_last = bits;
    }
    slice_dat->quant_idx = av_clip(quant, 0, s->q_ceil);
    slice_dat->bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;
    slice_dat->bytes_left = s->slice_max_bytes - slice_dat->bytes;

    return 0;
}