/*
 * Copyright (C) 2007 Loren Merritt <lorenm@u.washington.edu>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "common.h"

#if !defined(RDO_SKIP_BS) && defined(DEBUG_RAC_COUNT)
#define LOG_START {uint8_t *logp = h->out.c.bytestream;
#define LOG_STOP(id) h->stat.id += h->out.c.bytestream - logp;}
#else
#undef LOG_START
#undef LOG_STOP
#define LOG_START
#define LOG_STOP(id)
#endif

static void write_golomb( xlsc_t *h, uint8_t *model, int v )
{
    UNUSED xlsc_rac_t *c = &h->out.c;
    int i;
    int a = abs(v);
    int prefix = xlsc_log2(a);
    for( i=0; i<prefix; i++ )
        put_rac( c, model+1+MIN(i,6), 0 );
    put_rac( c, model+1+MIN(i,6), 1 );
    while( prefix-- )
        put_rac( c, model, (a>>prefix)&1 );
    put_rac_bypass( c, v<0 );
}

static void write_mvd( xlsc_t *h )
{
    UNUSED xlsc_rac_t *c = &h->out.c;
    uint8_t *model = h->model.mv;
    int i;

    LOG_START;
    for( i=0; i<2; i++ )
    {
        int delta = i ? h->mb.mv.y - h->mb.mvp.y : h->mb.mv.x - h->mb.mvp.x;
        put_rac( c, model+0, !!delta );
        if( delta )
            write_golomb( h, model+1, delta );
    }
    LOG_STOP(rac_mv);
}

static void write_residual( xlsc_t *h, int b )
{
    UNUSED xlsc_rac_t *c = &h->out.c;
    uint8_t *model = h->model.coef[h->mb.intra];
    int16_t *dct = h->mb.dct_zigzag[b];
    int last = 63;
    int i;

    while( last >= 0 && !dct[last] )
        last--;
    LOG_START;
    put_rac( c, model+0, last >= 0 );
    LOG_STOP(rac_cbp);
    if( last < 0 )
        return;

    for( i=0; i<=last; i++ )
    {
        int v = dct[i];
        LOG_START;
        if( i < 63 )
            put_rac( c, model+1+i, !!v );
        LOG_STOP(rac_nnz);
        if( v )
        {
            LOG_START;
            write_golomb( h, model+127+8*xlsc_coef_abs_context[i], v );
            LOG_STOP(rac_coef);
            LOG_START;
            if( i < 63 )
                put_rac( c, model+64+i, i==last );
            LOG_STOP(rac_eob);
        }
    }
}

void xlsc_macroblock_write( xlsc_t *h )
{
    int i;
    if( !h->fdec->intra )
    {
        LOG_START;
        put_rac( &h->out.c, h->model.mb, h->mb.intra );
        LOG_STOP(rac_mb);
        if( !h->mb.intra )
            write_mvd( h );
    }
    for( i=0; i<4; i++ )
        write_residual( h, i );
}

