00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00034 #include <string.h>
00035
00036 #include "avcodec.h"
00037 #include "rangecoder.h"
00038 #include "bytestream.h"
00039
00040
00041 void ff_init_range_encoder(RangeCoder *c, uint8_t *buf, int buf_size){
00042 c->bytestream_start=
00043 c->bytestream= buf;
00044 c->bytestream_end= buf + buf_size;
00045
00046 c->low= 0;
00047 c->range= 0xFF00;
00048 c->outstanding_count= 0;
00049 c->outstanding_byte= -1;
00050 }
00051
00052 void ff_init_range_decoder(RangeCoder *c, const uint8_t *buf, int buf_size){
00053
00054 ff_init_range_encoder(c, (uint8_t *) buf, buf_size);
00055
00056 c->low = bytestream_get_be16(&c->bytestream);
00057 }
00058
00059 void ff_build_rac_states(RangeCoder *c, int factor, int max_p){
00060 const int64_t one= 1LL<<32;
00061 int64_t p;
00062 int last_p8, p8, i;
00063
00064 memset(c->zero_state, 0, sizeof(c->zero_state));
00065 memset(c-> one_state, 0, sizeof(c-> one_state));
00066
00067 last_p8= 0;
00068 p= one/2;
00069 for(i=0; i<128; i++){
00070 p8= (256*p + one/2) >> 32;
00071 if(p8 <= last_p8) p8= last_p8+1;
00072 if(last_p8 && last_p8<256 && p8<=max_p)
00073 c->one_state[last_p8]= p8;
00074
00075 p+= ((one-p)*factor + one/2) >> 32;
00076 last_p8= p8;
00077 }
00078
00079 for(i=256-max_p; i<=max_p; i++){
00080 if(c->one_state[i])
00081 continue;
00082
00083 p= (i*one + 128) >> 8;
00084 p+= ((one-p)*factor + one/2) >> 32;
00085 p8= (256*p + one/2) >> 32;
00086 if(p8 <= i) p8= i+1;
00087 if(p8 > max_p) p8= max_p;
00088 c->one_state[ i]= p8;
00089 }
00090
00091 for(i=1; i<255; i++)
00092 c->zero_state[i]= 256-c->one_state[256-i];
00093 }
00094
00099 int ff_rac_terminate(RangeCoder *c){
00100 c->range=0xFF;
00101 c->low +=0xFF;
00102 renorm_encoder(c);
00103 c->range=0xFF;
00104 renorm_encoder(c);
00105
00106 assert(c->low == 0);
00107 assert(c->range >= 0x100);
00108
00109 return c->bytestream - c->bytestream_start;
00110 }
00111
00112 #ifdef TEST
00113 #define SIZE 10240
00114 #undef random
00115 int main(void){
00116 RangeCoder c;
00117 uint8_t b[9*SIZE];
00118 uint8_t r[9*SIZE];
00119 int i;
00120 uint8_t state[10]= {0};
00121
00122 ff_init_range_encoder(&c, b, SIZE);
00123 ff_build_rac_states(&c, 0.05*(1LL<<32), 128+64+32+16);
00124
00125 memset(state, 128, sizeof(state));
00126
00127 for(i=0; i<SIZE; i++){
00128 r[i]= random()%7;
00129 }
00130
00131 for(i=0; i<SIZE; i++){
00132 START_TIMER
00133 put_rac(&c, state, r[i]&1);
00134 STOP_TIMER("put_rac")
00135 }
00136
00137 ff_rac_terminate(&c);
00138
00139 ff_init_range_decoder(&c, b, SIZE);
00140
00141 memset(state, 128, sizeof(state));
00142
00143 for(i=0; i<SIZE; i++){
00144 START_TIMER
00145 if( (r[i]&1) != get_rac(&c, state) )
00146 av_log(NULL, AV_LOG_DEBUG, "rac failure at %d\n", i);
00147 STOP_TIMER("get_rac")
00148 }
00149
00150 return 0;
00151 }
00152 #endif