static int dct_quantize_refine(MpegEncContext *s,
                        DCTELEM *block, int16_t *weight, DCTELEM *orig,
                        int n, int qscale){
    int16_t rem[64];
    DECLARE_ALIGNED_16(DCTELEM, d1[64]);
    const int *qmat;
    const uint8_t *scantable= s->intra_scantable.scantable;
    const uint8_t *perm_scantable= s->intra_scantable.permutated;
    int run_tab[65];
    int prev_run=0;
    int prev_level=0;
    int qmul, qadd, start_i, last_non_zero, i, dc;
    uint8_t * length;
    uint8_t * last_length;
    int lambda;
    int rle_index, run, q = 1, sum;
#ifdef REFINE_STATS
static int count=0;
static int after_last=0;
static int to_zero=0;
static int from_zero=0;
static int raise=0;
static int lower=0;
static int messed_sign=0;
#endif
    if(basis[0][0] == 0)
        build_basis(s->dsp.idct_permutation);
    qmul= qscale*2;
    qadd= (qscale-1)|1;
    if (s->mb_intra) {
        if (!s->h263_aic) {
            if (n < 4)
                q = s->y_dc_scale;
            else
                q = s->c_dc_scale;
        } else{
            q = 1;
            qadd=0;
        }
        q <<= RECON_SHIFT-3;
        dc= block[0]*q;
        start_i = 1;
        qmat = s->q_intra_matrix[qscale];
        length     = s->intra_ac_vlc_length;
        last_length= s->intra_ac_vlc_last_length;
    } else {
        dc= 0;
        start_i = 0;
        qmat = s->q_inter_matrix[qscale];
        length     = s->inter_ac_vlc_length;
        last_length= s->inter_ac_vlc_last_length;
    }
    last_non_zero = s->block_last_index[n];
#ifdef REFINE_STATS
{START_TIMER
#endif
    dc += (1<<(RECON_SHIFT-1));
    for(i=0; i<64; i++){
        rem[i]= dc - (orig[i]<<RECON_SHIFT);
    }
#ifdef REFINE_STATS
STOP_TIMER("memset rem[]")}
#endif
    sum=0;
    for(i=0; i<64; i++){
        int one= 36;
        int qns=4;
        int w;
        w= FFABS(weight[i]) + qns*one;
        w= 15 + (48*qns*one + w/2)/w;
        weight[i] = w;
        assert(w>0);
        assert(w<(1<<6));
        sum += w*w;
    }
    lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
#ifdef REFINE_STATS
{START_TIMER
#endif
    run=0;
    rle_index=0;
    for(i=start_i; i<=last_non_zero; i++){
        int j= perm_scantable[i];
        const int level= block[j];
        int coeff;
        if(level){
            if(level<0) coeff= qmul*level - qadd;
            else        coeff= qmul*level + qadd;
            run_tab[rle_index++]=run;
            run=0;
            s->dsp.add_8x8basis(rem, basis[j], coeff);
        }else{
            run++;
        }
    }
#ifdef REFINE_STATS
if(last_non_zero>0){
STOP_TIMER("init rem[]")
}
}
{START_TIMER
#endif
    for(;;){
        int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
        int best_coeff=0;
        int best_change=0;
        int run2, best_unquant_change=0, analyze_gradient;
#ifdef REFINE_STATS
{START_TIMER
#endif
        analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
        if(analyze_gradient){
#ifdef REFINE_STATS
{START_TIMER
#endif
            for(i=0; i<64; i++){
                int w= weight[i];
                d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
            }
#ifdef REFINE_STATS
STOP_TIMER("rem*w*w")}
{START_TIMER
#endif
            s->dsp.fdct(d1);
#ifdef REFINE_STATS
STOP_TIMER("dct")}
#endif
        }
        if(start_i){
            const int level= block[0];
            int change, old_coeff;
            assert(s->mb_intra);
            old_coeff= q*level;
            for(change=-1; change<=1; change+=2){
                int new_level= level + change;
                int score, new_coeff;
                new_coeff= q*new_level;
                if(new_coeff >= 2048 || new_coeff < 0)
                    continue;
                score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
                if(score<best_score){
                    best_score= score;
                    best_coeff= 0;
                    best_change= change;
                    best_unquant_change= new_coeff - old_coeff;
                }
            }
        }
        run=0;
        rle_index=0;
        run2= run_tab[rle_index++];
        prev_level=0;
        prev_run=0;
        for(i=start_i; i<64; i++){
            int j= perm_scantable[i];
            const int level= block[j];
            int change, old_coeff;
            if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
                break;
            if(level){
                if(level<0) old_coeff= qmul*level - qadd;
                else        old_coeff= qmul*level + qadd;
                run2= run_tab[rle_index++];
            }else{
                old_coeff=0;
                run2--;
                assert(run2>=0 || i >= last_non_zero );
            }
            for(change=-1; change<=1; change+=2){
                int new_level= level + change;
                int score, new_coeff, unquant_change;
                score=0;
                if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
                   continue;
                if(new_level){
                    if(new_level<0) new_coeff= qmul*new_level - qadd;
                    else            new_coeff= qmul*new_level + qadd;
                    if(new_coeff >= 2048 || new_coeff <= -2048)
                        continue;
                    if(level){
                        if(level < 63 && level > -63){
                            if(i < last_non_zero)
                                score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]
                                         - length[UNI_AC_ENC_INDEX(run, level+64)];
                            else
                                score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
                                         - last_length[UNI_AC_ENC_INDEX(run, level+64)];
                        }
                    }else{
                        assert(FFABS(new_level)==1);
                        if(analyze_gradient){
                            int g= d1[ scantable[i] ];
                            if(g && (g^new_level) >= 0)
                                continue;
                        }
                        if(i < last_non_zero){
                            int next_i= i + run2 + 1;
                            int next_level= block[ perm_scantable[next_i] ] + 64;
                            if(next_level&(~127))
                                next_level= 0;
                            if(next_i < last_non_zero)
                                score +=   length[UNI_AC_ENC_INDEX(run, 65)]
                                         + length[UNI_AC_ENC_INDEX(run2, next_level)]
                                         - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
                            else
                                score +=  length[UNI_AC_ENC_INDEX(run, 65)]
                                        + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
                                        - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
                        }else{
                            score += last_length[UNI_AC_ENC_INDEX(run, 65)];
                            if(prev_level){
                                score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
                                        - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
                            }
                        }
                    }
                }else{
                    new_coeff=0;
                    assert(FFABS(level)==1);
                    if(i < last_non_zero){
                        int next_i= i + run2 + 1;
                        int next_level= block[ perm_scantable[next_i] ] + 64;
                        if(next_level&(~127))
                            next_level= 0;
                        if(next_i < last_non_zero)
                            score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
                                     - length[UNI_AC_ENC_INDEX(run2, next_level)]
                                     - length[UNI_AC_ENC_INDEX(run, 65)];
                        else
                            score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
                                     - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
                                     - length[UNI_AC_ENC_INDEX(run, 65)];
                    }else{
                        score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
                        if(prev_level){
                            score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
                                    - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
                        }
                    }
                }
                score *= lambda;
                unquant_change= new_coeff - old_coeff;
                assert((score < 100*lambda && score > -100*lambda) || lambda==0);
                score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
                if(score<best_score){
                    best_score= score;
                    best_coeff= i;
                    best_change= change;
                    best_unquant_change= unquant_change;
                }
            }
            if(level){
                prev_level= level + 64;
                if(prev_level&(~127))
                    prev_level= 0;
                prev_run= run;
                run=0;
            }else{
                run++;
            }
        }
#ifdef REFINE_STATS
STOP_TIMER("iterative step")}
#endif
        if(best_change){
            int j= perm_scantable[ best_coeff ];
            block[j] += best_change;
            if(best_coeff > last_non_zero){
                last_non_zero= best_coeff;
                assert(block[j]);
#ifdef REFINE_STATS
after_last++;
#endif
            }else{
#ifdef REFINE_STATS
if(block[j]){
    if(block[j] - best_change){
        if(FFABS(block[j]) > FFABS(block[j] - best_change)){
            raise++;
        }else{
            lower++;
        }
    }else{
        from_zero++;
    }
}else{
    to_zero++;
}
#endif
                for(; last_non_zero>=start_i; last_non_zero--){
                    if(block[perm_scantable[last_non_zero]])
                        break;
                }
            }
#ifdef REFINE_STATS
count++;
if(256*256*256*64 % count == 0){
    printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
}
#endif
            run=0;
            rle_index=0;
            for(i=start_i; i<=last_non_zero; i++){
                int j= perm_scantable[i];
                const int level= block[j];
                 if(level){
                     run_tab[rle_index++]=run;
                     run=0;
                 }else{
                     run++;
                 }
            }
            s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
        }else{
            break;
        }
    }
#ifdef REFINE_STATS
if(last_non_zero>0){
STOP_TIMER("iterative search")
}
}
#endif
    return last_non_zero;
}
['static int dct_quantize_refine(MpegEncContext *s,\n                        DCTELEM *block, int16_t *weight, DCTELEM *orig,\n                        int n, int qscale){\n    int16_t rem[64];\n    DECLARE_ALIGNED_16(DCTELEM, d1[64]);\n    const int *qmat;\n    const uint8_t *scantable= s->intra_scantable.scantable;\n    const uint8_t *perm_scantable= s->intra_scantable.permutated;\n    int run_tab[65];\n    int prev_run=0;\n    int prev_level=0;\n    int qmul, qadd, start_i, last_non_zero, i, dc;\n    uint8_t * length;\n    uint8_t * last_length;\n    int lambda;\n    int rle_index, run, q = 1, sum;\n#ifdef REFINE_STATS\nstatic int count=0;\nstatic int after_last=0;\nstatic int to_zero=0;\nstatic int from_zero=0;\nstatic int raise=0;\nstatic int lower=0;\nstatic int messed_sign=0;\n#endif\n    if(basis[0][0] == 0)\n        build_basis(s->dsp.idct_permutation);\n    qmul= qscale*2;\n    qadd= (qscale-1)|1;\n    if (s->mb_intra) {\n        if (!s->h263_aic) {\n            if (n < 4)\n                q = s->y_dc_scale;\n            else\n                q = s->c_dc_scale;\n        } else{\n            q = 1;\n            qadd=0;\n        }\n        q <<= RECON_SHIFT-3;\n        dc= block[0]*q;\n        start_i = 1;\n        qmat = s->q_intra_matrix[qscale];\n        length     = s->intra_ac_vlc_length;\n        last_length= s->intra_ac_vlc_last_length;\n    } else {\n        dc= 0;\n        start_i = 0;\n        qmat = s->q_inter_matrix[qscale];\n        length     = s->inter_ac_vlc_length;\n        last_length= s->inter_ac_vlc_last_length;\n    }\n    last_non_zero = s->block_last_index[n];\n#ifdef REFINE_STATS\n{START_TIMER\n#endif\n    dc += (1<<(RECON_SHIFT-1));\n    for(i=0; i<64; i++){\n        rem[i]= dc - (orig[i]<<RECON_SHIFT);\n    }\n#ifdef REFINE_STATS\nSTOP_TIMER("memset rem[]")}\n#endif\n    sum=0;\n    for(i=0; i<64; i++){\n        int one= 36;\n        int qns=4;\n        int w;\n        w= FFABS(weight[i]) + qns*one;\n        w= 15 + (48*qns*one + w/2)/w;\n        weight[i] = w;\n        assert(w>0);\n        assert(w<(1<<6));\n        sum += w*w;\n    }\n    lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);\n#ifdef REFINE_STATS\n{START_TIMER\n#endif\n    run=0;\n    rle_index=0;\n    for(i=start_i; i<=last_non_zero; i++){\n        int j= perm_scantable[i];\n        const int level= block[j];\n        int coeff;\n        if(level){\n            if(level<0) coeff= qmul*level - qadd;\n            else        coeff= qmul*level + qadd;\n            run_tab[rle_index++]=run;\n            run=0;\n            s->dsp.add_8x8basis(rem, basis[j], coeff);\n        }else{\n            run++;\n        }\n    }\n#ifdef REFINE_STATS\nif(last_non_zero>0){\nSTOP_TIMER("init rem[]")\n}\n}\n{START_TIMER\n#endif\n    for(;;){\n        int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);\n        int best_coeff=0;\n        int best_change=0;\n        int run2, best_unquant_change=0, analyze_gradient;\n#ifdef REFINE_STATS\n{START_TIMER\n#endif\n        analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;\n        if(analyze_gradient){\n#ifdef REFINE_STATS\n{START_TIMER\n#endif\n            for(i=0; i<64; i++){\n                int w= weight[i];\n                d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);\n            }\n#ifdef REFINE_STATS\nSTOP_TIMER("rem*w*w")}\n{START_TIMER\n#endif\n            s->dsp.fdct(d1);\n#ifdef REFINE_STATS\nSTOP_TIMER("dct")}\n#endif\n        }\n        if(start_i){\n            const int level= block[0];\n            int change, old_coeff;\n            assert(s->mb_intra);\n            old_coeff= q*level;\n            for(change=-1; change<=1; change+=2){\n                int new_level= level + change;\n                int score, new_coeff;\n                new_coeff= q*new_level;\n                if(new_coeff >= 2048 || new_coeff < 0)\n                    continue;\n                score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);\n                if(score<best_score){\n                    best_score= score;\n                    best_coeff= 0;\n                    best_change= change;\n                    best_unquant_change= new_coeff - old_coeff;\n                }\n            }\n        }\n        run=0;\n        rle_index=0;\n        run2= run_tab[rle_index++];\n        prev_level=0;\n        prev_run=0;\n        for(i=start_i; i<64; i++){\n            int j= perm_scantable[i];\n            const int level= block[j];\n            int change, old_coeff;\n            if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)\n                break;\n            if(level){\n                if(level<0) old_coeff= qmul*level - qadd;\n                else        old_coeff= qmul*level + qadd;\n                run2= run_tab[rle_index++];\n            }else{\n                old_coeff=0;\n                run2--;\n                assert(run2>=0 || i >= last_non_zero );\n            }\n            for(change=-1; change<=1; change+=2){\n                int new_level= level + change;\n                int score, new_coeff, unquant_change;\n                score=0;\n                if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))\n                   continue;\n                if(new_level){\n                    if(new_level<0) new_coeff= qmul*new_level - qadd;\n                    else            new_coeff= qmul*new_level + qadd;\n                    if(new_coeff >= 2048 || new_coeff <= -2048)\n                        continue;\n                    if(level){\n                        if(level < 63 && level > -63){\n                            if(i < last_non_zero)\n                                score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]\n                                         - length[UNI_AC_ENC_INDEX(run, level+64)];\n                            else\n                                score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]\n                                         - last_length[UNI_AC_ENC_INDEX(run, level+64)];\n                        }\n                    }else{\n                        assert(FFABS(new_level)==1);\n                        if(analyze_gradient){\n                            int g= d1[ scantable[i] ];\n                            if(g && (g^new_level) >= 0)\n                                continue;\n                        }\n                        if(i < last_non_zero){\n                            int next_i= i + run2 + 1;\n                            int next_level= block[ perm_scantable[next_i] ] + 64;\n                            if(next_level&(~127))\n                                next_level= 0;\n                            if(next_i < last_non_zero)\n                                score +=   length[UNI_AC_ENC_INDEX(run, 65)]\n                                         + length[UNI_AC_ENC_INDEX(run2, next_level)]\n                                         - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];\n                            else\n                                score +=  length[UNI_AC_ENC_INDEX(run, 65)]\n                                        + last_length[UNI_AC_ENC_INDEX(run2, next_level)]\n                                        - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];\n                        }else{\n                            score += last_length[UNI_AC_ENC_INDEX(run, 65)];\n                            if(prev_level){\n                                score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]\n                                        - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];\n                            }\n                        }\n                    }\n                }else{\n                    new_coeff=0;\n                    assert(FFABS(level)==1);\n                    if(i < last_non_zero){\n                        int next_i= i + run2 + 1;\n                        int next_level= block[ perm_scantable[next_i] ] + 64;\n                        if(next_level&(~127))\n                            next_level= 0;\n                        if(next_i < last_non_zero)\n                            score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]\n                                     - length[UNI_AC_ENC_INDEX(run2, next_level)]\n                                     - length[UNI_AC_ENC_INDEX(run, 65)];\n                        else\n                            score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]\n                                     - last_length[UNI_AC_ENC_INDEX(run2, next_level)]\n                                     - length[UNI_AC_ENC_INDEX(run, 65)];\n                    }else{\n                        score += -last_length[UNI_AC_ENC_INDEX(run, 65)];\n                        if(prev_level){\n                            score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]\n                                    - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];\n                        }\n                    }\n                }\n                score *= lambda;\n                unquant_change= new_coeff - old_coeff;\n                assert((score < 100*lambda && score > -100*lambda) || lambda==0);\n                score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);\n                if(score<best_score){\n                    best_score= score;\n                    best_coeff= i;\n                    best_change= change;\n                    best_unquant_change= unquant_change;\n                }\n            }\n            if(level){\n                prev_level= level + 64;\n                if(prev_level&(~127))\n                    prev_level= 0;\n                prev_run= run;\n                run=0;\n            }else{\n                run++;\n            }\n        }\n#ifdef REFINE_STATS\nSTOP_TIMER("iterative step")}\n#endif\n        if(best_change){\n            int j= perm_scantable[ best_coeff ];\n            block[j] += best_change;\n            if(best_coeff > last_non_zero){\n                last_non_zero= best_coeff;\n                assert(block[j]);\n#ifdef REFINE_STATS\nafter_last++;\n#endif\n            }else{\n#ifdef REFINE_STATS\nif(block[j]){\n    if(block[j] - best_change){\n        if(FFABS(block[j]) > FFABS(block[j] - best_change)){\n            raise++;\n        }else{\n            lower++;\n        }\n    }else{\n        from_zero++;\n    }\n}else{\n    to_zero++;\n}\n#endif\n                for(; last_non_zero>=start_i; last_non_zero--){\n                    if(block[perm_scantable[last_non_zero]])\n                        break;\n                }\n            }\n#ifdef REFINE_STATS\ncount++;\nif(256*256*256*64 % count == 0){\n    printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);\n}\n#endif\n            run=0;\n            rle_index=0;\n            for(i=start_i; i<=last_non_zero; i++){\n                int j= perm_scantable[i];\n                const int level= block[j];\n                 if(level){\n                     run_tab[rle_index++]=run;\n                     run=0;\n                 }else{\n                     run++;\n                 }\n            }\n            s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);\n        }else{\n            break;\n        }\n    }\n#ifdef REFINE_STATS\nif(last_non_zero>0){\nSTOP_TIMER("iterative search")\n}\n}\n#endif\n    return last_non_zero;\n}']