Libav 0.7.1
libavcodec/ffv1.c
Go to the documentation of this file.
00001 /*
00002  * FFV1 codec for libavcodec
00003  *
00004  * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
00005  *
00006  * This file is part of Libav.
00007  *
00008  * Libav is free software; you can redistribute it and/or
00009  * modify it under the terms of the GNU Lesser General Public
00010  * License as published by the Free Software Foundation; either
00011  * version 2.1 of the License, or (at your option) any later version.
00012  *
00013  * Libav is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  * Lesser General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU Lesser General Public
00019  * License along with Libav; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00028 #include "avcodec.h"
00029 #include "get_bits.h"
00030 #include "put_bits.h"
00031 #include "dsputil.h"
00032 #include "rangecoder.h"
00033 #include "golomb.h"
00034 #include "mathops.h"
00035 #include "libavutil/avassert.h"
00036 
00037 #define MAX_PLANES 4
00038 #define CONTEXT_SIZE 32
00039 
00040 #define MAX_QUANT_TABLES 8
00041 #define MAX_CONTEXT_INPUTS 5
00042 
00043 extern const uint8_t ff_log2_run[41];
00044 
00045 static const int8_t quant3[256]={
00046  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
00047  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
00048  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
00049  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
00050  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
00051  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
00052  1, 1, 1, 1, 1, 1, 1, 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-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
00098 -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
00099 -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,-1,-1,
00100 };
00101 static const int8_t quant7[256]={
00102  0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
00103  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
00104  2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
00105  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
00106  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
00107  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
00108  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
00109  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
00110 -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
00111 -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
00112 -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
00113 -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
00114 -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
00115 -3,-3,-3,-3,-3,-3,-3,-3,-3,-2,-2,-2,-2,-2,-2,-2,
00116 -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,
00117 -2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,-1,
00118 };
00119 static const int8_t quant9[256]={
00120  0, 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,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,
00186 -6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,
00187 -6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-5,
00188 -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
00189 -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,
00190 -4,-4,-4,-4,-4,-4,-4,-4,-4,-3,-3,-3,-3,-2,-2,-1,
00191 };
00192 
00193 static const uint8_t ver2_state[256]= {
00194    0,  10,  10,  10,  10,  16,  16,  16,  28,  16,  16,  29,  42,  49,  20,  49,
00195   59,  25,  26,  26,  27,  31,  33,  33,  33,  34,  34,  37,  67,  38,  39,  39,
00196   40,  40,  41,  79,  43,  44,  45,  45,  48,  48,  64,  50,  51,  52,  88,  52,
00197   53,  74,  55,  57,  58,  58,  74,  60, 101,  61,  62,  84,  66,  66,  68,  69,
00198   87,  82,  71,  97,  73,  73,  82,  75, 111,  77,  94,  78,  87,  81,  83,  97,
00199   85,  83,  94,  86,  99,  89,  90,  99, 111,  92,  93, 134,  95,  98, 105,  98,
00200  105, 110, 102, 108, 102, 118, 103, 106, 106, 113, 109, 112, 114, 112, 116, 125,
00201  115, 116, 117, 117, 126, 119, 125, 121, 121, 123, 145, 124, 126, 131, 127, 129,
00202  165, 130, 132, 138, 133, 135, 145, 136, 137, 139, 146, 141, 143, 142, 144, 148,
00203  147, 155, 151, 149, 151, 150, 152, 157, 153, 154, 156, 168, 158, 162, 161, 160,
00204  172, 163, 169, 164, 166, 184, 167, 170, 177, 174, 171, 173, 182, 176, 180, 178,
00205  175, 189, 179, 181, 186, 183, 192, 185, 200, 187, 191, 188, 190, 197, 193, 196,
00206  197, 194, 195, 196, 198, 202, 199, 201, 210, 203, 207, 204, 205, 206, 208, 214,
00207  209, 211, 221, 212, 213, 215, 224, 216, 217, 218, 219, 220, 222, 228, 223, 225,
00208  226, 224, 227, 229, 240, 230, 231, 232, 233, 234, 235, 236, 238, 239, 237, 242,
00209  241, 243, 242, 244, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255,
00210 };
00211 
00212 typedef struct VlcState{
00213     int16_t drift;
00214     uint16_t error_sum;
00215     int8_t bias;
00216     uint8_t count;
00217 } VlcState;
00218 
00219 typedef struct PlaneContext{
00220     int16_t quant_table[MAX_CONTEXT_INPUTS][256];
00221     int quant_table_index;
00222     int context_count;
00223     uint8_t (*state)[CONTEXT_SIZE];
00224     VlcState *vlc_state;
00225     uint8_t interlace_bit_state[2];
00226 } PlaneContext;
00227 
00228 #define MAX_SLICES 256
00229 
00230 typedef struct FFV1Context{
00231     AVCodecContext *avctx;
00232     RangeCoder c;
00233     GetBitContext gb;
00234     PutBitContext pb;
00235     uint64_t rc_stat[256][2];
00236     uint64_t (*rc_stat2[MAX_QUANT_TABLES])[32][2];
00237     int version;
00238     int width, height;
00239     int chroma_h_shift, chroma_v_shift;
00240     int flags;
00241     int picture_number;
00242     AVFrame picture;
00243     int plane_count;
00244     int ac;                              
00245     PlaneContext plane[MAX_PLANES];
00246     int16_t quant_table[MAX_CONTEXT_INPUTS][256];
00247     int16_t quant_tables[MAX_QUANT_TABLES][MAX_CONTEXT_INPUTS][256];
00248     int context_count[MAX_QUANT_TABLES];
00249     uint8_t state_transition[256];
00250     uint8_t (*initial_states[MAX_QUANT_TABLES])[32];
00251     int run_index;
00252     int colorspace;
00253     int16_t *sample_buffer;
00254     int gob_count;
00255 
00256     int quant_table_count;
00257 
00258     DSPContext dsp;
00259 
00260     struct FFV1Context *slice_context[MAX_SLICES];
00261     int slice_count;
00262     int num_v_slices;
00263     int num_h_slices;
00264     int slice_width;
00265     int slice_height;
00266     int slice_x;
00267     int slice_y;
00268 }FFV1Context;
00269 
00270 static av_always_inline int fold(int diff, int bits){
00271     if(bits==8)
00272         diff= (int8_t)diff;
00273     else{
00274         diff+= 1<<(bits-1);
00275         diff&=(1<<bits)-1;
00276         diff-= 1<<(bits-1);
00277     }
00278 
00279     return diff;
00280 }
00281 
00282 static inline int predict(int16_t *src, int16_t *last)
00283 {
00284     const int LT= last[-1];
00285     const int  T= last[ 0];
00286     const int L =  src[-1];
00287 
00288     return mid_pred(L, L + T - LT, T);
00289 }
00290 
00291 static inline int get_context(PlaneContext *p, int16_t *src,
00292                               int16_t *last, int16_t *last2)
00293 {
00294     const int LT= last[-1];
00295     const int  T= last[ 0];
00296     const int RT= last[ 1];
00297     const int L =  src[-1];
00298 
00299     if(p->quant_table[3][127]){
00300         const int TT= last2[0];
00301         const int LL=  src[-2];
00302         return p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF]
00303               +p->quant_table[3][(LL-L) & 0xFF] + p->quant_table[4][(TT-T) & 0xFF];
00304     }else
00305         return p->quant_table[0][(L-LT) & 0xFF] + p->quant_table[1][(LT-T) & 0xFF] + p->quant_table[2][(T-RT) & 0xFF];
00306 }
00307 
00308 static void find_best_state(uint8_t best_state[256][256], const uint8_t one_state[256]){
00309     int i,j,k,m;
00310     double l2tab[256];
00311 
00312     for(i=1; i<256; i++)
00313         l2tab[i]= log2(i/256.0);
00314 
00315     for(i=0; i<256; i++){
00316         double best_len[256];
00317         double p= i/256.0;
00318 
00319         for(j=0; j<256; j++)
00320             best_len[j]= 1<<30;
00321 
00322         for(j=FFMAX(i-10,1); j<FFMIN(i+11,256); j++){
00323             double occ[256]={0};
00324             double len=0;
00325             occ[j]=1.0;
00326             for(k=0; k<256; k++){
00327                 double newocc[256]={0};
00328                 for(m=0; m<256; m++){
00329                     if(occ[m]){
00330                         len -=occ[m]*(     p *l2tab[    m]
00331                                       + (1-p)*l2tab[256-m]);
00332                     }
00333                 }
00334                 if(len < best_len[k]){
00335                     best_len[k]= len;
00336                     best_state[i][k]= j;
00337                 }
00338                 for(m=0; m<256; m++){
00339                     if(occ[m]){
00340                         newocc[    one_state[    m]] += occ[m]*   p ;
00341                         newocc[256-one_state[256-m]] += occ[m]*(1-p);
00342                     }
00343                 }
00344                 memcpy(occ, newocc, sizeof(occ));
00345             }
00346         }
00347     }
00348 }
00349 
00350 static av_always_inline av_flatten void put_symbol_inline(RangeCoder *c, uint8_t *state, int v, int is_signed, uint64_t rc_stat[256][2], uint64_t rc_stat2[32][2]){
00351     int i;
00352 
00353 #define put_rac(C,S,B) \
00354 do{\
00355     if(rc_stat){\
00356     rc_stat[*(S)][B]++;\
00357         rc_stat2[(S)-state][B]++;\
00358     }\
00359     put_rac(C,S,B);\
00360 }while(0)
00361 
00362     if(v){
00363         const int a= FFABS(v);
00364         const int e= av_log2(a);
00365         put_rac(c, state+0, 0);
00366         if(e<=9){
00367             for(i=0; i<e; i++){
00368                 put_rac(c, state+1+i, 1);  //1..10
00369             }
00370             put_rac(c, state+1+i, 0);
00371 
00372             for(i=e-1; i>=0; i--){
00373                 put_rac(c, state+22+i, (a>>i)&1); //22..31
00374             }
00375 
00376             if(is_signed)
00377                 put_rac(c, state+11 + e, v < 0); //11..21
00378         }else{
00379             for(i=0; i<e; i++){
00380                 put_rac(c, state+1+FFMIN(i,9), 1);  //1..10
00381             }
00382             put_rac(c, state+1+9, 0);
00383 
00384             for(i=e-1; i>=0; i--){
00385                 put_rac(c, state+22+FFMIN(i,9), (a>>i)&1); //22..31
00386             }
00387 
00388             if(is_signed)
00389                 put_rac(c, state+11 + 10, v < 0); //11..21
00390         }
00391     }else{
00392         put_rac(c, state+0, 1);
00393     }
00394 #undef put_rac
00395 }
00396 
00397 static void av_noinline put_symbol(RangeCoder *c, uint8_t *state, int v, int is_signed){
00398     put_symbol_inline(c, state, v, is_signed, NULL, NULL);
00399 }
00400 
00401 static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state, int is_signed){
00402     if(get_rac(c, state+0))
00403         return 0;
00404     else{
00405         int i, e, a;
00406         e= 0;
00407         while(get_rac(c, state+1 + FFMIN(e,9))){ //1..10
00408             e++;
00409         }
00410 
00411         a= 1;
00412         for(i=e-1; i>=0; i--){
00413             a += a + get_rac(c, state+22 + FFMIN(i,9)); //22..31
00414         }
00415 
00416         e= -(is_signed && get_rac(c, state+11 + FFMIN(e, 10))); //11..21
00417         return (a^e)-e;
00418     }
00419 }
00420 
00421 static int av_noinline get_symbol(RangeCoder *c, uint8_t *state, int is_signed){
00422     return get_symbol_inline(c, state, is_signed);
00423 }
00424 
00425 static inline void update_vlc_state(VlcState * const state, const int v){
00426     int drift= state->drift;
00427     int count= state->count;
00428     state->error_sum += FFABS(v);
00429     drift += v;
00430 
00431     if(count == 128){ //FIXME variable
00432         count >>= 1;
00433         drift >>= 1;
00434         state->error_sum >>= 1;
00435     }
00436     count++;
00437 
00438     if(drift <= -count){
00439         if(state->bias > -128) state->bias--;
00440 
00441         drift += count;
00442         if(drift <= -count)
00443             drift= -count + 1;
00444     }else if(drift > 0){
00445         if(state->bias <  127) state->bias++;
00446 
00447         drift -= count;
00448         if(drift > 0)
00449             drift= 0;
00450     }
00451 
00452     state->drift= drift;
00453     state->count= count;
00454 }
00455 
00456 static inline void put_vlc_symbol(PutBitContext *pb, VlcState * const state, int v, int bits){
00457     int i, k, code;
00458 //printf("final: %d ", v);
00459     v = fold(v - state->bias, bits);
00460 
00461     i= state->count;
00462     k=0;
00463     while(i < state->error_sum){ //FIXME optimize
00464         k++;
00465         i += i;
00466     }
00467 
00468     assert(k<=8);
00469 
00470 #if 0 // JPEG LS
00471     if(k==0 && 2*state->drift <= - state->count) code= v ^ (-1);
00472     else                                         code= v;
00473 #else
00474      code= v ^ ((2*state->drift + state->count)>>31);
00475 #endif
00476 
00477 //printf("v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code, state->bias, state->error_sum, state->drift, state->count, k);
00478     set_sr_golomb(pb, code, k, 12, bits);
00479 
00480     update_vlc_state(state, v);
00481 }
00482 
00483 static inline int get_vlc_symbol(GetBitContext *gb, VlcState * const state, int bits){
00484     int k, i, v, ret;
00485 
00486     i= state->count;
00487     k=0;
00488     while(i < state->error_sum){ //FIXME optimize
00489         k++;
00490         i += i;
00491     }
00492 
00493     assert(k<=8);
00494 
00495     v= get_sr_golomb(gb, k, 12, bits);
00496 //printf("v:%d bias:%d error:%d drift:%d count:%d k:%d", v, state->bias, state->error_sum, state->drift, state->count, k);
00497 
00498 #if 0 // JPEG LS
00499     if(k==0 && 2*state->drift <= - state->count) v ^= (-1);
00500 #else
00501      v ^= ((2*state->drift + state->count)>>31);
00502 #endif
00503 
00504     ret= fold(v + state->bias, bits);
00505 
00506     update_vlc_state(state, v);
00507 //printf("final: %d\n", ret);
00508     return ret;
00509 }
00510 
00511 #if CONFIG_FFV1_ENCODER
00512 static av_always_inline int encode_line(FFV1Context *s, int w,
00513                                         int16_t *sample[2],
00514                                         int plane_index, int bits)
00515 {
00516     PlaneContext * const p= &s->plane[plane_index];
00517     RangeCoder * const c= &s->c;
00518     int x;
00519     int run_index= s->run_index;
00520     int run_count=0;
00521     int run_mode=0;
00522 
00523     if(s->ac){
00524         if(c->bytestream_end - c->bytestream < w*20){
00525             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
00526             return -1;
00527         }
00528     }else{
00529         if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < w*4){
00530             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
00531             return -1;
00532         }
00533     }
00534 
00535     for(x=0; x<w; x++){
00536         int diff, context;
00537 
00538         context= get_context(p, sample[0]+x, sample[1]+x, sample[2]+x);
00539         diff= sample[0][x] - predict(sample[0]+x, sample[1]+x);
00540 
00541         if(context < 0){
00542             context = -context;
00543             diff= -diff;
00544         }
00545 
00546         diff= fold(diff, bits);
00547 
00548         if(s->ac){
00549             if(s->flags & CODEC_FLAG_PASS1){
00550                 put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat, s->rc_stat2[p->quant_table_index][context]);
00551             }else{
00552                 put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);
00553             }
00554         }else{
00555             if(context == 0) run_mode=1;
00556 
00557             if(run_mode){
00558 
00559                 if(diff){
00560                     while(run_count >= 1<<ff_log2_run[run_index]){
00561                         run_count -= 1<<ff_log2_run[run_index];
00562                         run_index++;
00563                         put_bits(&s->pb, 1, 1);
00564                     }
00565 
00566                     put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
00567                     if(run_index) run_index--;
00568                     run_count=0;
00569                     run_mode=0;
00570                     if(diff>0) diff--;
00571                 }else{
00572                     run_count++;
00573                 }
00574             }
00575 
00576 //            printf("count:%d index:%d, mode:%d, x:%d y:%d pos:%d\n", run_count, run_index, run_mode, x, y, (int)put_bits_count(&s->pb));
00577 
00578             if(run_mode == 0)
00579                 put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
00580         }
00581     }
00582     if(run_mode){
00583         while(run_count >= 1<<ff_log2_run[run_index]){
00584             run_count -= 1<<ff_log2_run[run_index];
00585             run_index++;
00586             put_bits(&s->pb, 1, 1);
00587         }
00588 
00589         if(run_count)
00590             put_bits(&s->pb, 1, 1);
00591     }
00592     s->run_index= run_index;
00593 
00594     return 0;
00595 }
00596 
00597 static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
00598     int x,y,i;
00599     const int ring_size= s->avctx->context_model ? 3 : 2;
00600     int16_t *sample[3];
00601     s->run_index=0;
00602 
00603     memset(s->sample_buffer, 0, ring_size*(w+6)*sizeof(*s->sample_buffer));
00604 
00605     for(y=0; y<h; y++){
00606         for(i=0; i<ring_size; i++)
00607             sample[i]= s->sample_buffer + (w+6)*((h+i-y)%ring_size) + 3;
00608 
00609         sample[0][-1]= sample[1][0  ];
00610         sample[1][ w]= sample[1][w-1];
00611 //{START_TIMER
00612         if(s->avctx->bits_per_raw_sample<=8){
00613             for(x=0; x<w; x++){
00614                 sample[0][x]= src[x + stride*y];
00615             }
00616             encode_line(s, w, sample, plane_index, 8);
00617         }else{
00618             for(x=0; x<w; x++){
00619                 sample[0][x]= ((uint16_t*)(src + stride*y))[x] >> (16 - s->avctx->bits_per_raw_sample);
00620             }
00621             encode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
00622         }
00623 //STOP_TIMER("encode line")}
00624     }
00625 }
00626 
00627 static void encode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int stride){
00628     int x, y, p, i;
00629     const int ring_size= s->avctx->context_model ? 3 : 2;
00630     int16_t *sample[3][3];
00631     s->run_index=0;
00632 
00633     memset(s->sample_buffer, 0, ring_size*3*(w+6)*sizeof(*s->sample_buffer));
00634 
00635     for(y=0; y<h; y++){
00636         for(i=0; i<ring_size; i++)
00637             for(p=0; p<3; p++)
00638                 sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;
00639 
00640         for(x=0; x<w; x++){
00641             int v= src[x + stride*y];
00642             int b= v&0xFF;
00643             int g= (v>>8)&0xFF;
00644             int r= (v>>16)&0xFF;
00645 
00646             b -= g;
00647             r -= g;
00648             g += (b + r)>>2;
00649             b += 0x100;
00650             r += 0x100;
00651 
00652 //            assert(g>=0 && b>=0 && r>=0);
00653 //            assert(g<256 && b<512 && r<512);
00654             sample[0][0][x]= g;
00655             sample[1][0][x]= b;
00656             sample[2][0][x]= r;
00657         }
00658         for(p=0; p<3; p++){
00659             sample[p][0][-1]= sample[p][1][0  ];
00660             sample[p][1][ w]= sample[p][1][w-1];
00661             encode_line(s, w, sample[p], FFMIN(p, 1), 9);
00662         }
00663     }
00664 }
00665 
00666 static void write_quant_table(RangeCoder *c, int16_t *quant_table){
00667     int last=0;
00668     int i;
00669     uint8_t state[CONTEXT_SIZE];
00670     memset(state, 128, sizeof(state));
00671 
00672     for(i=1; i<128 ; i++){
00673         if(quant_table[i] != quant_table[i-1]){
00674             put_symbol(c, state, i-last-1, 0);
00675             last= i;
00676         }
00677     }
00678     put_symbol(c, state, i-last-1, 0);
00679 }
00680 
00681 static void write_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]){
00682     int i;
00683     for(i=0; i<5; i++)
00684         write_quant_table(c, quant_table[i]);
00685 }
00686 
00687 static void write_header(FFV1Context *f){
00688     uint8_t state[CONTEXT_SIZE];
00689     int i, j;
00690     RangeCoder * const c= &f->slice_context[0]->c;
00691 
00692     memset(state, 128, sizeof(state));
00693 
00694     if(f->version < 2){
00695         put_symbol(c, state, f->version, 0);
00696         put_symbol(c, state, f->ac, 0);
00697         if(f->ac>1){
00698             for(i=1; i<256; i++){
00699                 put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
00700             }
00701         }
00702         put_symbol(c, state, f->colorspace, 0); //YUV cs type
00703         if(f->version>0)
00704             put_symbol(c, state, f->avctx->bits_per_raw_sample, 0);
00705         put_rac(c, state, 1); //chroma planes
00706             put_symbol(c, state, f->chroma_h_shift, 0);
00707             put_symbol(c, state, f->chroma_v_shift, 0);
00708         put_rac(c, state, 0); //no transparency plane
00709 
00710         write_quant_tables(c, f->quant_table);
00711     }else{
00712         put_symbol(c, state, f->slice_count, 0);
00713         for(i=0; i<f->slice_count; i++){
00714             FFV1Context *fs= f->slice_context[i];
00715             put_symbol(c, state, (fs->slice_x     +1)*f->num_h_slices / f->width   , 0);
00716             put_symbol(c, state, (fs->slice_y     +1)*f->num_v_slices / f->height  , 0);
00717             put_symbol(c, state, (fs->slice_width +1)*f->num_h_slices / f->width -1, 0);
00718             put_symbol(c, state, (fs->slice_height+1)*f->num_v_slices / f->height-1, 0);
00719             for(j=0; j<f->plane_count; j++){
00720                 put_symbol(c, state, f->plane[j].quant_table_index, 0);
00721                 av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
00722             }
00723         }
00724     }
00725 }
00726 #endif /* CONFIG_FFV1_ENCODER */
00727 
00728 static av_cold int common_init(AVCodecContext *avctx){
00729     FFV1Context *s = avctx->priv_data;
00730 
00731     s->avctx= avctx;
00732     s->flags= avctx->flags;
00733 
00734     dsputil_init(&s->dsp, avctx);
00735 
00736     s->width = avctx->width;
00737     s->height= avctx->height;
00738 
00739     assert(s->width && s->height);
00740     //defaults
00741     s->num_h_slices=1;
00742     s->num_v_slices=1;
00743 
00744 
00745     return 0;
00746 }
00747 
00748 static int init_slice_state(FFV1Context *f){
00749     int i, j;
00750 
00751     for(i=0; i<f->slice_count; i++){
00752         FFV1Context *fs= f->slice_context[i];
00753         for(j=0; j<f->plane_count; j++){
00754             PlaneContext * const p= &fs->plane[j];
00755 
00756             if(fs->ac){
00757                 if(!p->    state) p->    state= av_malloc(CONTEXT_SIZE*p->context_count*sizeof(uint8_t));
00758                 if(!p->    state)
00759                     return AVERROR(ENOMEM);
00760             }else{
00761                 if(!p->vlc_state) p->vlc_state= av_malloc(p->context_count*sizeof(VlcState));
00762                 if(!p->vlc_state)
00763                     return AVERROR(ENOMEM);
00764             }
00765         }
00766 
00767         if (fs->ac>1){
00768             //FIXME only redo if state_transition changed
00769             for(j=1; j<256; j++){
00770                 fs->c.one_state [    j]= fs->state_transition[j];
00771                 fs->c.zero_state[256-j]= 256-fs->c.one_state [j];
00772             }
00773         }
00774     }
00775 
00776     return 0;
00777 }
00778 
00779 static av_cold int init_slice_contexts(FFV1Context *f){
00780     int i;
00781 
00782     f->slice_count= f->num_h_slices * f->num_v_slices;
00783 
00784     for(i=0; i<f->slice_count; i++){
00785         FFV1Context *fs= av_mallocz(sizeof(*fs));
00786         int sx= i % f->num_h_slices;
00787         int sy= i / f->num_h_slices;
00788         int sxs= f->avctx->width * sx    / f->num_h_slices;
00789         int sxe= f->avctx->width *(sx+1) / f->num_h_slices;
00790         int sys= f->avctx->height* sy    / f->num_v_slices;
00791         int sye= f->avctx->height*(sy+1) / f->num_v_slices;
00792         f->slice_context[i]= fs;
00793         memcpy(fs, f, sizeof(*fs));
00794         memset(fs->rc_stat2, 0, sizeof(fs->rc_stat2));
00795 
00796         fs->slice_width = sxe - sxs;
00797         fs->slice_height= sye - sys;
00798         fs->slice_x     = sxs;
00799         fs->slice_y     = sys;
00800 
00801         fs->sample_buffer = av_malloc(9 * (fs->width+6) * sizeof(*fs->sample_buffer));
00802         if (!fs->sample_buffer)
00803             return AVERROR(ENOMEM);
00804     }
00805     return 0;
00806 }
00807 
00808 static int allocate_initial_states(FFV1Context *f){
00809     int i;
00810 
00811     for(i=0; i<f->quant_table_count; i++){
00812         f->initial_states[i]= av_malloc(f->context_count[i]*sizeof(*f->initial_states[i]));
00813         if(!f->initial_states[i])
00814             return AVERROR(ENOMEM);
00815         memset(f->initial_states[i], 128, f->context_count[i]*sizeof(*f->initial_states[i]));
00816     }
00817     return 0;
00818 }
00819 
00820 #if CONFIG_FFV1_ENCODER
00821 static int write_extra_header(FFV1Context *f){
00822     RangeCoder * const c= &f->c;
00823     uint8_t state[CONTEXT_SIZE];
00824     int i, j, k;
00825     uint8_t state2[32][CONTEXT_SIZE];
00826 
00827     memset(state2, 128, sizeof(state2));
00828     memset(state, 128, sizeof(state));
00829 
00830     f->avctx->extradata= av_malloc(f->avctx->extradata_size= 10000 + (11*11*5*5*5+11*11*11)*32);
00831     ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);
00832     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
00833 
00834     put_symbol(c, state, f->version, 0);
00835     put_symbol(c, state, f->ac, 0);
00836     if(f->ac>1){
00837         for(i=1; i<256; i++){
00838             put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
00839         }
00840     }
00841     put_symbol(c, state, f->colorspace, 0); //YUV cs type
00842     put_symbol(c, state, f->avctx->bits_per_raw_sample, 0);
00843     put_rac(c, state, 1); //chroma planes
00844         put_symbol(c, state, f->chroma_h_shift, 0);
00845         put_symbol(c, state, f->chroma_v_shift, 0);
00846     put_rac(c, state, 0); //no transparency plane
00847     put_symbol(c, state, f->num_h_slices-1, 0);
00848     put_symbol(c, state, f->num_v_slices-1, 0);
00849 
00850     put_symbol(c, state, f->quant_table_count, 0);
00851     for(i=0; i<f->quant_table_count; i++)
00852         write_quant_tables(c, f->quant_tables[i]);
00853 
00854     for(i=0; i<f->quant_table_count; i++){
00855         for(j=0; j<f->context_count[i]*CONTEXT_SIZE; j++)
00856             if(f->initial_states[i] && f->initial_states[i][0][j] != 128)
00857                 break;
00858         if(j<f->context_count[i]*CONTEXT_SIZE){
00859             put_rac(c, state, 1);
00860             for(j=0; j<f->context_count[i]; j++){
00861                 for(k=0; k<CONTEXT_SIZE; k++){
00862                     int pred= j ? f->initial_states[i][j-1][k] : 128;
00863                     put_symbol(c, state2[k], (int8_t)(f->initial_states[i][j][k]-pred), 1);
00864                 }
00865             }
00866         }else{
00867             put_rac(c, state, 0);
00868         }
00869     }
00870 
00871     f->avctx->extradata_size= ff_rac_terminate(c);
00872 
00873     return 0;
00874 }
00875 
00876 static int sort_stt(FFV1Context *s, uint8_t stt[256]){
00877     int i,i2,changed,print=0;
00878 
00879     do{
00880         changed=0;
00881         for(i=12; i<244; i++){
00882             for(i2=i+1; i2<245 && i2<i+4; i2++){
00883 #define COST(old, new) \
00884     s->rc_stat[old][0]*-log2((256-(new))/256.0)\
00885    +s->rc_stat[old][1]*-log2(     (new) /256.0)
00886 
00887 #define COST2(old, new) \
00888     COST(old, new)\
00889    +COST(256-(old), 256-(new))
00890 
00891                 double size0= COST2(i, i ) + COST2(i2, i2);
00892                 double sizeX= COST2(i, i2) + COST2(i2, i );
00893                 if(sizeX < size0 && i!=128 && i2!=128){
00894                     int j;
00895                     FFSWAP(int, stt[    i], stt[    i2]);
00896                     FFSWAP(int, s->rc_stat[i    ][0],s->rc_stat[    i2][0]);
00897                     FFSWAP(int, s->rc_stat[i    ][1],s->rc_stat[    i2][1]);
00898                     if(i != 256-i2){
00899                         FFSWAP(int, stt[256-i], stt[256-i2]);
00900                         FFSWAP(int, s->rc_stat[256-i][0],s->rc_stat[256-i2][0]);
00901                         FFSWAP(int, s->rc_stat[256-i][1],s->rc_stat[256-i2][1]);
00902                     }
00903                     for(j=1; j<256; j++){
00904                         if     (stt[j] == i ) stt[j] = i2;
00905                         else if(stt[j] == i2) stt[j] = i ;
00906                         if(i != 256-i2){
00907                             if     (stt[256-j] == 256-i ) stt[256-j] = 256-i2;
00908                             else if(stt[256-j] == 256-i2) stt[256-j] = 256-i ;
00909                         }
00910                     }
00911                     print=changed=1;
00912                 }
00913             }
00914         }
00915     }while(changed);
00916     return print;
00917 }
00918 
00919 static av_cold int encode_init(AVCodecContext *avctx)
00920 {
00921     FFV1Context *s = avctx->priv_data;
00922     int i, j, k, m;
00923 
00924     common_init(avctx);
00925 
00926     s->version=0;
00927     s->ac= avctx->coder_type ? 2:0;
00928 
00929     if(s->ac>1)
00930         for(i=1; i<256; i++)
00931             s->state_transition[i]=ver2_state[i];
00932 
00933     s->plane_count=2;
00934     for(i=0; i<256; i++){
00935         s->quant_table_count=2;
00936         if(avctx->bits_per_raw_sample <=8){
00937             s->quant_tables[0][0][i]=           quant11[i];
00938             s->quant_tables[0][1][i]=        11*quant11[i];
00939             s->quant_tables[0][2][i]=     11*11*quant11[i];
00940             s->quant_tables[1][0][i]=           quant11[i];
00941             s->quant_tables[1][1][i]=        11*quant11[i];
00942             s->quant_tables[1][2][i]=     11*11*quant5 [i];
00943             s->quant_tables[1][3][i]=   5*11*11*quant5 [i];
00944             s->quant_tables[1][4][i]= 5*5*11*11*quant5 [i];
00945         }else{
00946             s->quant_tables[0][0][i]=           quant9_10bit[i];
00947             s->quant_tables[0][1][i]=        11*quant9_10bit[i];
00948             s->quant_tables[0][2][i]=     11*11*quant9_10bit[i];
00949             s->quant_tables[1][0][i]=           quant9_10bit[i];
00950             s->quant_tables[1][1][i]=        11*quant9_10bit[i];
00951             s->quant_tables[1][2][i]=     11*11*quant5_10bit[i];
00952             s->quant_tables[1][3][i]=   5*11*11*quant5_10bit[i];
00953             s->quant_tables[1][4][i]= 5*5*11*11*quant5_10bit[i];
00954         }
00955     }
00956     s->context_count[0]= (11*11*11+1)/2;
00957     s->context_count[1]= (11*11*5*5*5+1)/2;
00958     memcpy(s->quant_table, s->quant_tables[avctx->context_model], sizeof(s->quant_table));
00959 
00960     for(i=0; i<s->plane_count; i++){
00961         PlaneContext * const p= &s->plane[i];
00962 
00963         memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));
00964         p->quant_table_index= avctx->context_model;
00965         p->context_count= s->context_count[p->quant_table_index];
00966     }
00967 
00968     if(allocate_initial_states(s) < 0)
00969         return AVERROR(ENOMEM);
00970 
00971     avctx->coded_frame= &s->picture;
00972     switch(avctx->pix_fmt){
00973     case PIX_FMT_YUV444P16:
00974     case PIX_FMT_YUV422P16:
00975     case PIX_FMT_YUV420P16:
00976         if(avctx->bits_per_raw_sample <=8){
00977             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
00978             return -1;
00979         }
00980         if(!s->ac){
00981             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
00982             return -1;
00983         }
00984         s->version= FFMAX(s->version, 1);
00985     case PIX_FMT_YUV444P:
00986     case PIX_FMT_YUV422P:
00987     case PIX_FMT_YUV420P:
00988     case PIX_FMT_YUV411P:
00989     case PIX_FMT_YUV410P:
00990         s->colorspace= 0;
00991         break;
00992     case PIX_FMT_RGB32:
00993         s->colorspace= 1;
00994         break;
00995     default:
00996         av_log(avctx, AV_LOG_ERROR, "format not supported\n");
00997         return -1;
00998     }
00999     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
01000 
01001     s->picture_number=0;
01002 
01003     if(avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)){
01004         for(i=0; i<s->quant_table_count; i++){
01005             s->rc_stat2[i]= av_mallocz(s->context_count[i]*sizeof(*s->rc_stat2[i]));
01006             if(!s->rc_stat2[i])
01007                 return AVERROR(ENOMEM);
01008         }
01009     }
01010     if(avctx->stats_in){
01011         char *p= avctx->stats_in;
01012         uint8_t best_state[256][256];
01013         int gob_count=0;
01014         char *next;
01015 
01016         av_assert0(s->version>=2);
01017 
01018         for(;;){
01019             for(j=0; j<256; j++){
01020                 for(i=0; i<2; i++){
01021                     s->rc_stat[j][i]= strtol(p, &next, 0);
01022                     if(next==p){
01023                         av_log(avctx, AV_LOG_ERROR, "2Pass file invalid at %d %d [%s]\n", j,i,p);
01024                         return -1;
01025                     }
01026                     p=next;
01027                 }
01028             }
01029             for(i=0; i<s->quant_table_count; i++){
01030                 for(j=0; j<s->context_count[i]; j++){
01031                     for(k=0; k<32; k++){
01032                         for(m=0; m<2; m++){
01033                             s->rc_stat2[i][j][k][m]= strtol(p, &next, 0);
01034                             if(next==p){
01035                                 av_log(avctx, AV_LOG_ERROR, "2Pass file invalid at %d %d %d %d [%s]\n", i,j,k,m,p);
01036                                 return -1;
01037                             }
01038                             p=next;
01039                         }
01040                     }
01041                 }
01042             }
01043             gob_count= strtol(p, &next, 0);
01044             if(next==p || gob_count <0){
01045                 av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");
01046                 return -1;
01047             }
01048             p=next;
01049             while(*p=='\n' || *p==' ') p++;
01050             if(p[0]==0) break;
01051         }
01052         sort_stt(s, s->state_transition);
01053 
01054         find_best_state(best_state, s->state_transition);
01055 
01056         for(i=0; i<s->quant_table_count; i++){
01057             for(j=0; j<s->context_count[i]; j++){
01058                 for(k=0; k<32; k++){
01059                     double p= 128;
01060                     if(s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1]){
01061                         p=256.0*s->rc_stat2[i][j][k][1] / (s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1]);
01062                     }
01063                     s->initial_states[i][j][k]= best_state[av_clip(round(p), 1, 255)][av_clip((s->rc_stat2[i][j][k][0]+s->rc_stat2[i][j][k][1])/gob_count, 0, 255)];
01064                 }
01065             }
01066         }
01067     }
01068 
01069     if(s->version>1){
01070         s->num_h_slices=2;
01071         s->num_v_slices=2;
01072         write_extra_header(s);
01073     }
01074 
01075     if(init_slice_contexts(s) < 0)
01076         return -1;
01077     if(init_slice_state(s) < 0)
01078         return -1;
01079 
01080 #define STATS_OUT_SIZE 1024*1024*6
01081     if(avctx->flags & CODEC_FLAG_PASS1){
01082         avctx->stats_out= av_mallocz(STATS_OUT_SIZE);
01083         for(i=0; i<s->quant_table_count; i++){
01084             for(j=0; j<s->slice_count; j++){
01085                 FFV1Context *sf= s->slice_context[j];
01086                 av_assert0(!sf->rc_stat2[i]);
01087                 sf->rc_stat2[i]= av_mallocz(s->context_count[i]*sizeof(*sf->rc_stat2[i]));
01088                 if(!sf->rc_stat2[i])
01089                     return AVERROR(ENOMEM);
01090             }
01091         }
01092     }
01093 
01094     return 0;
01095 }
01096 #endif /* CONFIG_FFV1_ENCODER */
01097 
01098 
01099 static void clear_state(FFV1Context *f){
01100     int i, si, j;
01101 
01102     for(si=0; si<f->slice_count; si++){
01103         FFV1Context *fs= f->slice_context[si];
01104         for(i=0; i<f->plane_count; i++){
01105             PlaneContext *p= &fs->plane[i];
01106 
01107             p->interlace_bit_state[0]= 128;
01108             p->interlace_bit_state[1]= 128;
01109 
01110             if(fs->ac){
01111                 if(f->initial_states[p->quant_table_index]){
01112                     memcpy(p->state, f->initial_states[p->quant_table_index], CONTEXT_SIZE*p->context_count);
01113                 }else
01114                 memset(p->state, 128, CONTEXT_SIZE*p->context_count);
01115             }else{
01116             for(j=0; j<p->context_count; j++){
01117                     p->vlc_state[j].drift= 0;
01118                     p->vlc_state[j].error_sum= 4; //FFMAX((RANGE + 32)/64, 2);
01119                     p->vlc_state[j].bias= 0;
01120                     p->vlc_state[j].count= 1;
01121             }
01122             }
01123         }
01124     }
01125 }
01126 
01127 #if CONFIG_FFV1_ENCODER
01128 static int encode_slice(AVCodecContext *c, void *arg){
01129     FFV1Context *fs= *(void**)arg;
01130     FFV1Context *f= fs->avctx->priv_data;
01131     int width = fs->slice_width;
01132     int height= fs->slice_height;
01133     int x= fs->slice_x;
01134     int y= fs->slice_y;
01135     AVFrame * const p= &f->picture;
01136 
01137     if(f->colorspace==0){
01138         const int chroma_width = -((-width )>>f->chroma_h_shift);
01139         const int chroma_height= -((-height)>>f->chroma_v_shift);
01140         const int cx= x>>f->chroma_h_shift;
01141         const int cy= y>>f->chroma_v_shift;
01142 
01143         encode_plane(fs, p->data[0] + x + y*p->linesize[0], width, height, p->linesize[0], 0);
01144 
01145         encode_plane(fs, p->data[1] + cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
01146         encode_plane(fs, p->data[2] + cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
01147     }else{
01148         encode_rgb_frame(fs, (uint32_t*)(p->data[0]) + x + y*(p->linesize[0]/4), width, height, p->linesize[0]/4);
01149     }
01150     emms_c();
01151 
01152     return 0;
01153 }
01154 
01155 static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){
01156     FFV1Context *f = avctx->priv_data;
01157     RangeCoder * const c= &f->slice_context[0]->c;
01158     AVFrame *pict = data;
01159     AVFrame * const p= &f->picture;
01160     int used_count= 0;
01161     uint8_t keystate=128;
01162     uint8_t *buf_p;
01163     int i;
01164 
01165     ff_init_range_encoder(c, buf, buf_size);
01166     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
01167 
01168     *p = *pict;
01169     p->pict_type= AV_PICTURE_TYPE_I;
01170 
01171     if(avctx->gop_size==0 || f->picture_number % avctx->gop_size == 0){
01172         put_rac(c, &keystate, 1);
01173         p->key_frame= 1;
01174         f->gob_count++;
01175         write_header(f);
01176         clear_state(f);
01177     }else{
01178         put_rac(c, &keystate, 0);
01179         p->key_frame= 0;
01180     }
01181 
01182     if(!f->ac){
01183         used_count += ff_rac_terminate(c);
01184 //printf("pos=%d\n", used_count);
01185         init_put_bits(&f->slice_context[0]->pb, buf + used_count, buf_size - used_count);
01186     }else if (f->ac>1){
01187         int i;
01188         for(i=1; i<256; i++){
01189             c->one_state[i]= f->state_transition[i];
01190             c->zero_state[256-i]= 256-c->one_state[i];
01191         }
01192     }
01193 
01194     for(i=1; i<f->slice_count; i++){
01195         FFV1Context *fs= f->slice_context[i];
01196         uint8_t *start= buf + (buf_size-used_count)*i/f->slice_count;
01197         int len= buf_size/f->slice_count;
01198 
01199         if(fs->ac){
01200             ff_init_range_encoder(&fs->c, start, len);
01201         }else{
01202             init_put_bits(&fs->pb, start, len);
01203         }
01204     }
01205     avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
01206 
01207     buf_p=buf;
01208     for(i=0; i<f->slice_count; i++){
01209         FFV1Context *fs= f->slice_context[i];
01210         int bytes;
01211 
01212         if(fs->ac){
01213             uint8_t state=128;
01214             put_rac(&fs->c, &state, 0);
01215             bytes= ff_rac_terminate(&fs->c);
01216         }else{
01217             flush_put_bits(&fs->pb); //nicer padding FIXME
01218             bytes= used_count + (put_bits_count(&fs->pb)+7)/8;
01219             used_count= 0;
01220         }
01221         if(i>0){
01222             av_assert0(bytes < buf_size/f->slice_count);
01223             memmove(buf_p, fs->ac ? fs->c.bytestream_start : fs->pb.buf, bytes);
01224             av_assert0(bytes < (1<<24));
01225             AV_WB24(buf_p+bytes, bytes);
01226             bytes+=3;
01227         }
01228         buf_p += bytes;
01229     }
01230 
01231     if((avctx->flags&CODEC_FLAG_PASS1) && (f->picture_number&31)==0){
01232         int j, k, m;
01233         char *p= avctx->stats_out;
01234         char *end= p + STATS_OUT_SIZE;
01235 
01236         memset(f->rc_stat, 0, sizeof(f->rc_stat));
01237         for(i=0; i<f->quant_table_count; i++)
01238             memset(f->rc_stat2[i], 0, f->context_count[i]*sizeof(*f->rc_stat2[i]));
01239 
01240         for(j=0; j<f->slice_count; j++){
01241             FFV1Context *fs= f->slice_context[j];
01242             for(i=0; i<256; i++){
01243                 f->rc_stat[i][0] += fs->rc_stat[i][0];
01244                 f->rc_stat[i][1] += fs->rc_stat[i][1];
01245             }
01246             for(i=0; i<f->quant_table_count; i++){
01247                 for(k=0; k<f->context_count[i]; k++){
01248                     for(m=0; m<32; m++){
01249                         f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];
01250                         f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];
01251                     }
01252                 }
01253             }
01254         }
01255 
01256         for(j=0; j<256; j++){
01257             snprintf(p, end-p, "%"PRIu64" %"PRIu64" ", f->rc_stat[j][0], f->rc_stat[j][1]);
01258             p+= strlen(p);
01259         }
01260         snprintf(p, end-p, "\n");
01261 
01262         for(i=0; i<f->quant_table_count; i++){
01263             for(j=0; j<f->context_count[i]; j++){
01264                 for(m=0; m<32; m++){
01265                     snprintf(p, end-p, "%"PRIu64" %"PRIu64" ", f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);
01266                     p+= strlen(p);
01267                 }
01268             }
01269         }
01270         snprintf(p, end-p, "%d\n", f->gob_count);
01271     } else if(avctx->flags&CODEC_FLAG_PASS1)
01272         avctx->stats_out[0] = '\0';
01273 
01274     f->picture_number++;
01275     return buf_p-buf;
01276 }
01277 #endif /* CONFIG_FFV1_ENCODER */
01278 
01279 static av_cold int common_end(AVCodecContext *avctx){
01280     FFV1Context *s = avctx->priv_data;
01281     int i, j;
01282 
01283     if (avctx->codec->decode && s->picture.data[0])
01284         avctx->release_buffer(avctx, &s->picture);
01285 
01286     for(j=0; j<s->slice_count; j++){
01287         FFV1Context *fs= s->slice_context[j];
01288         for(i=0; i<s->plane_count; i++){
01289             PlaneContext *p= &fs->plane[i];
01290 
01291             av_freep(&p->state);
01292             av_freep(&p->vlc_state);
01293         }
01294         av_freep(&fs->sample_buffer);
01295     }
01296 
01297     av_freep(&avctx->stats_out);
01298     for(j=0; j<s->quant_table_count; j++){
01299         av_freep(&s->initial_states[j]);
01300         for(i=0; i<s->slice_count; i++){
01301             FFV1Context *sf= s->slice_context[i];
01302             av_freep(&sf->rc_stat2[j]);
01303         }
01304         av_freep(&s->rc_stat2[j]);
01305     }
01306 
01307     for(i=0; i<s->slice_count; i++){
01308         av_freep(&s->slice_context[i]);
01309     }
01310 
01311     return 0;
01312 }
01313 
01314 static av_always_inline void decode_line(FFV1Context *s, int w,
01315                                          int16_t *sample[2],
01316                                          int plane_index, int bits)
01317 {
01318     PlaneContext * const p= &s->plane[plane_index];
01319     RangeCoder * const c= &s->c;
01320     int x;
01321     int run_count=0;
01322     int run_mode=0;
01323     int run_index= s->run_index;
01324 
01325     for(x=0; x<w; x++){
01326         int diff, context, sign;
01327 
01328         context= get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
01329         if(context < 0){
01330             context= -context;
01331             sign=1;
01332         }else
01333             sign=0;
01334 
01335         av_assert2(context < p->context_count);
01336 
01337         if(s->ac){
01338             diff= get_symbol_inline(c, p->state[context], 1);
01339         }else{
01340             if(context == 0 && run_mode==0) run_mode=1;
01341 
01342             if(run_mode){
01343                 if(run_count==0 && run_mode==1){
01344                     if(get_bits1(&s->gb)){
01345                         run_count = 1<<ff_log2_run[run_index];
01346                         if(x + run_count <= w) run_index++;
01347                     }else{
01348                         if(ff_log2_run[run_index]) run_count = get_bits(&s->gb, ff_log2_run[run_index]);
01349                         else run_count=0;
01350                         if(run_index) run_index--;
01351                         run_mode=2;
01352                     }
01353                 }
01354                 run_count--;
01355                 if(run_count < 0){
01356                     run_mode=0;
01357                     run_count=0;
01358                     diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
01359                     if(diff>=0) diff++;
01360                 }else
01361                     diff=0;
01362             }else
01363                 diff= get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
01364 
01365 //            printf("count:%d index:%d, mode:%d, x:%d y:%d pos:%d\n", run_count, run_index, run_mode, x, y, get_bits_count(&s->gb));
01366         }
01367 
01368         if(sign) diff= -diff;
01369 
01370         sample[1][x]= (predict(sample[1] + x, sample[0] + x) + diff) & ((1<<bits)-1);
01371     }
01372     s->run_index= run_index;
01373 }
01374 
01375 static void decode_plane(FFV1Context *s, uint8_t *src, int w, int h, int stride, int plane_index){
01376     int x, y;
01377     int16_t *sample[2];
01378     sample[0]=s->sample_buffer    +3;
01379     sample[1]=s->sample_buffer+w+6+3;
01380 
01381     s->run_index=0;
01382 
01383     memset(s->sample_buffer, 0, 2*(w+6)*sizeof(*s->sample_buffer));
01384 
01385     for(y=0; y<h; y++){
01386         int16_t *temp = sample[0]; //FIXME try a normal buffer
01387 
01388         sample[0]= sample[1];
01389         sample[1]= temp;
01390 
01391         sample[1][-1]= sample[0][0  ];
01392         sample[0][ w]= sample[0][w-1];
01393 
01394 //{START_TIMER
01395         if(s->avctx->bits_per_raw_sample <= 8){
01396             decode_line(s, w, sample, plane_index, 8);
01397             for(x=0; x<w; x++){
01398                 src[x + stride*y]= sample[1][x];
01399             }
01400         }else{
01401             decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
01402             for(x=0; x<w; x++){
01403                 ((uint16_t*)(src + stride*y))[x]= sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
01404             }
01405         }
01406 //STOP_TIMER("decode-line")}
01407     }
01408 }
01409 
01410 static void decode_rgb_frame(FFV1Context *s, uint32_t *src, int w, int h, int stride){
01411     int x, y, p;
01412     int16_t *sample[3][2];
01413     for(x=0; x<3; x++){
01414         sample[x][0] = s->sample_buffer +  x*2   *(w+6) + 3;
01415         sample[x][1] = s->sample_buffer + (x*2+1)*(w+6) + 3;
01416     }
01417 
01418     s->run_index=0;
01419 
01420     memset(s->sample_buffer, 0, 6*(w+6)*sizeof(*s->sample_buffer));
01421 
01422     for(y=0; y<h; y++){
01423         for(p=0; p<3; p++){
01424             int16_t *temp = sample[p][0]; //FIXME try a normal buffer
01425 
01426             sample[p][0]= sample[p][1];
01427             sample[p][1]= temp;
01428 
01429             sample[p][1][-1]= sample[p][0][0  ];
01430             sample[p][0][ w]= sample[p][0][w-1];
01431             decode_line(s, w, sample[p], FFMIN(p, 1), 9);
01432         }
01433         for(x=0; x<w; x++){
01434             int g= sample[0][1][x];
01435             int b= sample[1][1][x];
01436             int r= sample[2][1][x];
01437 
01438 //            assert(g>=0 && b>=0 && r>=0);
01439 //            assert(g<256 && b<512 && r<512);
01440 
01441             b -= 0x100;
01442             r -= 0x100;
01443             g -= (b + r)>>2;
01444             b += g;
01445             r += g;
01446 
01447             src[x + stride*y]= b + (g<<8) + (r<<16) + (0xFF<<24);
01448         }
01449     }
01450 }
01451 
01452 static int decode_slice(AVCodecContext *c, void *arg){
01453     FFV1Context *fs= *(void**)arg;
01454     FFV1Context *f= fs->avctx->priv_data;
01455     int width = fs->slice_width;
01456     int height= fs->slice_height;
01457     int x= fs->slice_x;
01458     int y= fs->slice_y;
01459     AVFrame * const p= &f->picture;
01460 
01461     av_assert1(width && height);
01462     if(f->colorspace==0){
01463         const int chroma_width = -((-width )>>f->chroma_h_shift);
01464         const int chroma_height= -((-height)>>f->chroma_v_shift);
01465         const int cx= x>>f->chroma_h_shift;
01466         const int cy= y>>f->chroma_v_shift;
01467         decode_plane(fs, p->data[0] + x + y*p->linesize[0], width, height, p->linesize[0], 0);
01468 
01469         decode_plane(fs, p->data[1] + cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
01470         decode_plane(fs, p->data[2] + cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[2], 1);
01471     }else{
01472         decode_rgb_frame(fs, (uint32_t*)p->data[0] + x + y*(p->linesize[0]/4), width, height, p->linesize[0]/4);
01473     }
01474 
01475     emms_c();
01476 
01477     return 0;
01478 }
01479 
01480 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale){
01481     int v;
01482     int i=0;
01483     uint8_t state[CONTEXT_SIZE];
01484 
01485     memset(state, 128, sizeof(state));
01486 
01487     for(v=0; i<128 ; v++){
01488         int len= get_symbol(c, state, 0) + 1;
01489 
01490         if(len + i > 128) return -1;
01491 
01492         while(len--){
01493             quant_table[i] = scale*v;
01494             i++;
01495 //printf("%2d ",v);
01496 //if(i%16==0) printf("\n");
01497         }
01498     }
01499 
01500     for(i=1; i<128; i++){
01501         quant_table[256-i]= -quant_table[i];
01502     }
01503     quant_table[128]= -quant_table[127];
01504 
01505     return 2*v - 1;
01506 }
01507 
01508 static int read_quant_tables(RangeCoder *c, int16_t quant_table[MAX_CONTEXT_INPUTS][256]){
01509     int i;
01510     int context_count=1;
01511 
01512     for(i=0; i<5; i++){
01513         context_count*= read_quant_table(c, quant_table[i], context_count);
01514         if(context_count > 32768U){
01515             return -1;
01516         }
01517     }
01518     return (context_count+1)/2;
01519 }
01520 
01521 static int read_extra_header(FFV1Context *f){
01522     RangeCoder * const c= &f->c;
01523     uint8_t state[CONTEXT_SIZE];
01524     int i, j, k;
01525     uint8_t state2[32][CONTEXT_SIZE];
01526 
01527     memset(state2, 128, sizeof(state2));
01528     memset(state, 128, sizeof(state));
01529 
01530     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
01531     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
01532 
01533     f->version= get_symbol(c, state, 0);
01534     f->ac= f->avctx->coder_type= get_symbol(c, state, 0);
01535     if(f->ac>1){
01536         for(i=1; i<256; i++){
01537             f->state_transition[i]= get_symbol(c, state, 1) + c->one_state[i];
01538         }
01539     }
01540     f->colorspace= get_symbol(c, state, 0); //YUV cs type
01541     f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
01542     get_rac(c, state); //no chroma = false
01543     f->chroma_h_shift= get_symbol(c, state, 0);
01544     f->chroma_v_shift= get_symbol(c, state, 0);
01545     get_rac(c, state); //transparency plane
01546     f->plane_count= 2;
01547     f->num_h_slices= 1 + get_symbol(c, state, 0);
01548     f->num_v_slices= 1 + get_symbol(c, state, 0);
01549     if(f->num_h_slices > (unsigned)f->width || f->num_v_slices > (unsigned)f->height){
01550         av_log(f->avctx, AV_LOG_ERROR, "too many slices\n");
01551         return -1;
01552     }
01553 
01554     f->quant_table_count= get_symbol(c, state, 0);
01555     if(f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
01556         return -1;
01557     for(i=0; i<f->quant_table_count; i++){
01558         if((f->context_count[i]= read_quant_tables(c, f->quant_tables[i])) < 0){
01559             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
01560             return -1;
01561         }
01562     }
01563 
01564     if(allocate_initial_states(f) < 0)
01565         return AVERROR(ENOMEM);
01566 
01567     for(i=0; i<f->quant_table_count; i++){
01568         if(get_rac(c, state)){
01569             for(j=0; j<f->context_count[i]; j++){
01570                 for(k=0; k<CONTEXT_SIZE; k++){
01571                     int pred= j ? f->initial_states[i][j-1][k] : 128;
01572                     f->initial_states[i][j][k]= (pred+get_symbol(c, state2[k], 1))&0xFF;
01573                 }
01574             }
01575         }
01576     }
01577 
01578     return 0;
01579 }
01580 
01581 static int read_header(FFV1Context *f){
01582     uint8_t state[CONTEXT_SIZE];
01583     int i, j, context_count;
01584     RangeCoder * const c= &f->slice_context[0]->c;
01585 
01586     memset(state, 128, sizeof(state));
01587 
01588     if(f->version < 2){
01589         f->version= get_symbol(c, state, 0);
01590         f->ac= f->avctx->coder_type= get_symbol(c, state, 0);
01591         if(f->ac>1){
01592             for(i=1; i<256; i++){
01593                 f->state_transition[i]= get_symbol(c, state, 1) + c->one_state[i];
01594             }
01595         }
01596         f->colorspace= get_symbol(c, state, 0); //YUV cs type
01597         if(f->version>0)
01598             f->avctx->bits_per_raw_sample= get_symbol(c, state, 0);
01599         get_rac(c, state); //no chroma = false
01600         f->chroma_h_shift= get_symbol(c, state, 0);
01601         f->chroma_v_shift= get_symbol(c, state, 0);
01602         get_rac(c, state); //transparency plane
01603         f->plane_count= 2;
01604     }
01605 
01606     if(f->colorspace==0){
01607         if(f->avctx->bits_per_raw_sample<=8){
01608             switch(16*f->chroma_h_shift + f->chroma_v_shift){
01609             case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P; break;
01610             case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P; break;
01611             case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P; break;
01612             case 0x20: f->avctx->pix_fmt= PIX_FMT_YUV411P; break;
01613             case 0x22: f->avctx->pix_fmt= PIX_FMT_YUV410P; break;
01614             default:
01615                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
01616                 return -1;
01617             }
01618         }else{
01619             switch(16*f->chroma_h_shift + f->chroma_v_shift){
01620             case 0x00: f->avctx->pix_fmt= PIX_FMT_YUV444P16; break;
01621             case 0x10: f->avctx->pix_fmt= PIX_FMT_YUV422P16; break;
01622             case 0x11: f->avctx->pix_fmt= PIX_FMT_YUV420P16; break;
01623             default:
01624                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
01625                 return -1;
01626             }
01627         }
01628     }else if(f->colorspace==1){
01629         if(f->chroma_h_shift || f->chroma_v_shift){
01630             av_log(f->avctx, AV_LOG_ERROR, "chroma subsampling not supported in this colorspace\n");
01631             return -1;
01632         }
01633         f->avctx->pix_fmt= PIX_FMT_RGB32;
01634     }else{
01635         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
01636         return -1;
01637     }
01638 
01639 //printf("%d %d %d\n", f->chroma_h_shift, f->chroma_v_shift,f->avctx->pix_fmt);
01640     if(f->version < 2){
01641         context_count= read_quant_tables(c, f->quant_table);
01642         if(context_count < 0){
01643                 av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
01644                 return -1;
01645         }
01646     }else{
01647         f->slice_count= get_symbol(c, state, 0);
01648         if(f->slice_count > (unsigned)MAX_SLICES)
01649             return -1;
01650     }
01651 
01652     for(j=0; j<f->slice_count; j++){
01653         FFV1Context *fs= f->slice_context[j];
01654         fs->ac= f->ac;
01655 
01656         if(f->version >= 2){
01657             fs->slice_x     = get_symbol(c, state, 0)   *f->width ;
01658             fs->slice_y     = get_symbol(c, state, 0)   *f->height;
01659             fs->slice_width =(get_symbol(c, state, 0)+1)*f->width  + fs->slice_x;
01660             fs->slice_height=(get_symbol(c, state, 0)+1)*f->height + fs->slice_y;
01661 
01662             fs->slice_x /= f->num_h_slices;
01663             fs->slice_y /= f->num_v_slices;
01664             fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;
01665             fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
01666             if((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
01667                 return -1;
01668             if(    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
01669                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
01670                 return -1;
01671         }
01672 
01673         for(i=0; i<f->plane_count; i++){
01674             PlaneContext * const p= &fs->plane[i];
01675 
01676             if(f->version >= 2){
01677                 int idx=get_symbol(c, state, 0);
01678                 if(idx > (unsigned)f->quant_table_count){
01679                     av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
01680                     return -1;
01681                 }
01682                 p->quant_table_index= idx;
01683                 memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
01684                 context_count= f->context_count[idx];
01685             }else{
01686                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
01687             }
01688 
01689             if(p->context_count < context_count){
01690                 av_freep(&p->state);
01691                 av_freep(&p->vlc_state);
01692             }
01693             p->context_count= context_count;
01694         }
01695     }
01696 
01697     return 0;
01698 }
01699 
01700 static av_cold int decode_init(AVCodecContext *avctx)
01701 {
01702     FFV1Context *f = avctx->priv_data;
01703 
01704     common_init(avctx);
01705 
01706     if(avctx->extradata && read_extra_header(f) < 0)
01707         return -1;
01708 
01709     if(init_slice_contexts(f) < 0)
01710         return -1;
01711 
01712     return 0;
01713 }
01714 
01715 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt){
01716     const uint8_t *buf = avpkt->data;
01717     int buf_size = avpkt->size;
01718     FFV1Context *f = avctx->priv_data;
01719     RangeCoder * const c= &f->slice_context[0]->c;
01720     AVFrame * const p= &f->picture;
01721     int bytes_read, i;
01722     uint8_t keystate= 128;
01723     const uint8_t *buf_p;
01724 
01725     AVFrame *picture = data;
01726 
01727     /* release previously stored data */
01728     if (p->data[0])
01729         avctx->release_buffer(avctx, p);
01730 
01731     ff_init_range_decoder(c, buf, buf_size);
01732     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
01733 
01734 
01735     p->pict_type= AV_PICTURE_TYPE_I; //FIXME I vs. P
01736     if(get_rac(c, &keystate)){
01737         p->key_frame= 1;
01738         if(read_header(f) < 0)
01739             return -1;
01740         if(init_slice_state(f) < 0)
01741             return -1;
01742 
01743         clear_state(f);
01744     }else{
01745         p->key_frame= 0;
01746     }
01747     if(f->ac>1){
01748         int i;
01749         for(i=1; i<256; i++){
01750             c->one_state[i]= f->state_transition[i];
01751             c->zero_state[256-i]= 256-c->one_state[i];
01752         }
01753     }
01754 
01755     p->reference= 0;
01756     if(avctx->get_buffer(avctx, p) < 0){
01757         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
01758         return -1;
01759     }
01760 
01761     if(avctx->debug&FF_DEBUG_PICT_INFO)
01762         av_log(avctx, AV_LOG_ERROR, "keyframe:%d coder:%d\n", p->key_frame, f->ac);
01763 
01764     if(!f->ac){
01765         bytes_read = c->bytestream - c->bytestream_start - 1;
01766         if(bytes_read ==0) av_log(avctx, AV_LOG_ERROR, "error at end of AC stream\n"); //FIXME
01767 //printf("pos=%d\n", bytes_read);
01768         init_get_bits(&f->slice_context[0]->gb, buf + bytes_read, (buf_size - bytes_read) * 8);
01769     } else {
01770         bytes_read = 0; /* avoid warning */
01771     }
01772 
01773     buf_p= buf + buf_size;
01774     for(i=f->slice_count-1; i>0; i--){
01775         FFV1Context *fs= f->slice_context[i];
01776         int v= AV_RB24(buf_p-3)+3;
01777         if(buf_p - buf <= v){
01778             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
01779             return -1;
01780         }
01781         buf_p -= v;
01782         if(fs->ac){
01783             ff_init_range_decoder(&fs->c, buf_p, v);
01784         }else{
01785             init_get_bits(&fs->gb, buf_p, v * 8);
01786         }
01787     }
01788 
01789     avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
01790     f->picture_number++;
01791 
01792     *picture= *p;
01793     *data_size = sizeof(AVFrame);
01794 
01795     return buf_size;
01796 }
01797 
01798 AVCodec ff_ffv1_decoder = {
01799     "ffv1",
01800     AVMEDIA_TYPE_VIDEO,
01801     CODEC_ID_FFV1,
01802     sizeof(FFV1Context),
01803     decode_init,
01804     NULL,
01805     common_end,
01806     decode_frame,
01807     CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ | CODEC_CAP_SLICE_THREADS,
01808     NULL,
01809     .long_name= NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
01810 };
01811 
01812 #if CONFIG_FFV1_ENCODER
01813 AVCodec ff_ffv1_encoder = {
01814     "ffv1",
01815     AVMEDIA_TYPE_VIDEO,
01816     CODEC_ID_FFV1,
01817     sizeof(FFV1Context),
01818     encode_init,
01819     encode_frame,
01820     common_end,
01821     .capabilities = CODEC_CAP_SLICE_THREADS,
01822     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_YUV444P, PIX_FMT_YUV422P, PIX_FMT_YUV411P, PIX_FMT_YUV410P, PIX_FMT_RGB32, PIX_FMT_YUV420P16, PIX_FMT_YUV422P16, PIX_FMT_YUV444P16, PIX_FMT_NONE},
01823     .long_name= NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
01824 };
01825 #endif