• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavcodec/snowenc.c

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2004 Michael Niedermayer <michaelni@gmx.at>
00003  *
00004  * This file is part of Libav.
00005  *
00006  * Libav is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * Libav is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with Libav; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00021 #include "libavutil/intmath.h"
00022 #include "libavutil/log.h"
00023 #include "libavutil/opt.h"
00024 #include "avcodec.h"
00025 #include "dsputil.h"
00026 #include "dwt.h"
00027 #include "snow.h"
00028 
00029 #include "rangecoder.h"
00030 #include "mathops.h"
00031 
00032 #include "mpegvideo.h"
00033 #include "h263.h"
00034 
00035 #undef NDEBUG
00036 #include <assert.h>
00037 
00038 #define QUANTIZE2 0
00039 
00040 #if QUANTIZE2==1
00041 #define Q2_STEP 8
00042 
00043 static void find_sse(SnowContext *s, Plane *p, int *score, int score_stride, IDWTELEM *r0, IDWTELEM *r1, int level, int orientation){
00044     SubBand *b= &p->band[level][orientation];
00045     int x, y;
00046     int xo=0;
00047     int yo=0;
00048     int step= 1 << (s->spatial_decomposition_count - level);
00049 
00050     if(orientation&1)
00051         xo= step>>1;
00052     if(orientation&2)
00053         yo= step>>1;
00054 
00055     //FIXME bias for nonzero ?
00056     //FIXME optimize
00057     memset(score, 0, sizeof(*score)*score_stride*((p->height + Q2_STEP-1)/Q2_STEP));
00058     for(y=0; y<p->height; y++){
00059         for(x=0; x<p->width; x++){
00060             int sx= (x-xo + step/2) / step / Q2_STEP;
00061             int sy= (y-yo + step/2) / step / Q2_STEP;
00062             int v= r0[x + y*p->width] - r1[x + y*p->width];
00063             assert(sx>=0 && sy>=0 && sx < score_stride);
00064             v= ((v+8)>>4)<<4;
00065             score[sx + sy*score_stride] += v*v;
00066             assert(score[sx + sy*score_stride] >= 0);
00067         }
00068     }
00069 }
00070 
00071 static void dequantize_all(SnowContext *s, Plane *p, IDWTELEM *buffer, int width, int height){
00072     int level, orientation;
00073 
00074     for(level=0; level<s->spatial_decomposition_count; level++){
00075         for(orientation=level ? 1 : 0; orientation<4; orientation++){
00076             SubBand *b= &p->band[level][orientation];
00077             IDWTELEM *dst= buffer + (b->ibuf - s->spatial_idwt_buffer);
00078 
00079             dequantize(s, b, dst, b->stride);
00080         }
00081     }
00082 }
00083 
00084 static void dwt_quantize(SnowContext *s, Plane *p, DWTELEM *buffer, int width, int height, int stride, int type){
00085     int level, orientation, ys, xs, x, y, pass;
00086     IDWTELEM best_dequant[height * stride];
00087     IDWTELEM idwt2_buffer[height * stride];
00088     const int score_stride= (width + 10)/Q2_STEP;
00089     int best_score[(width + 10)/Q2_STEP * (height + 10)/Q2_STEP]; //FIXME size
00090     int score[(width + 10)/Q2_STEP * (height + 10)/Q2_STEP]; //FIXME size
00091     int threshold= (s->m.lambda * s->m.lambda) >> 6;
00092 
00093     //FIXME pass the copy cleanly ?
00094 
00095 //    memcpy(dwt_buffer, buffer, height * stride * sizeof(DWTELEM));
00096     ff_spatial_dwt(buffer, width, height, stride, type, s->spatial_decomposition_count);
00097 
00098     for(level=0; level<s->spatial_decomposition_count; level++){
00099         for(orientation=level ? 1 : 0; orientation<4; orientation++){
00100             SubBand *b= &p->band[level][orientation];
00101             IDWTELEM *dst= best_dequant + (b->ibuf - s->spatial_idwt_buffer);
00102              DWTELEM *src=       buffer + (b-> buf - s->spatial_dwt_buffer);
00103             assert(src == b->buf); // code does not depend on this but it is true currently
00104 
00105             quantize(s, b, dst, src, b->stride, s->qbias);
00106         }
00107     }
00108     for(pass=0; pass<1; pass++){
00109         if(s->qbias == 0) //keyframe
00110             continue;
00111         for(level=0; level<s->spatial_decomposition_count; level++){
00112             for(orientation=level ? 1 : 0; orientation<4; orientation++){
00113                 SubBand *b= &p->band[level][orientation];
00114                 IDWTELEM *dst= idwt2_buffer + (b->ibuf - s->spatial_idwt_buffer);
00115                 IDWTELEM *best_dst= best_dequant + (b->ibuf - s->spatial_idwt_buffer);
00116 
00117                 for(ys= 0; ys<Q2_STEP; ys++){
00118                     for(xs= 0; xs<Q2_STEP; xs++){
00119                         memcpy(idwt2_buffer, best_dequant, height * stride * sizeof(IDWTELEM));
00120                         dequantize_all(s, p, idwt2_buffer, width, height);
00121                         ff_spatial_idwt(idwt2_buffer, width, height, stride, type, s->spatial_decomposition_count);
00122                         find_sse(s, p, best_score, score_stride, idwt2_buffer, s->spatial_idwt_buffer, level, orientation);
00123                         memcpy(idwt2_buffer, best_dequant, height * stride * sizeof(IDWTELEM));
00124                         for(y=ys; y<b->height; y+= Q2_STEP){
00125                             for(x=xs; x<b->width; x+= Q2_STEP){
00126                                 if(dst[x + y*b->stride]<0) dst[x + y*b->stride]++;
00127                                 if(dst[x + y*b->stride]>0) dst[x + y*b->stride]--;
00128                                 //FIXME try more than just --
00129                             }
00130                         }
00131                         dequantize_all(s, p, idwt2_buffer, width, height);
00132                         ff_spatial_idwt(idwt2_buffer, width, height, stride, type, s->spatial_decomposition_count);
00133                         find_sse(s, p, score, score_stride, idwt2_buffer, s->spatial_idwt_buffer, level, orientation);
00134                         for(y=ys; y<b->height; y+= Q2_STEP){
00135                             for(x=xs; x<b->width; x+= Q2_STEP){
00136                                 int score_idx= x/Q2_STEP + (y/Q2_STEP)*score_stride;
00137                                 if(score[score_idx] <= best_score[score_idx] + threshold){
00138                                     best_score[score_idx]= score[score_idx];
00139                                     if(best_dst[x + y*b->stride]<0) best_dst[x + y*b->stride]++;
00140                                     if(best_dst[x + y*b->stride]>0) best_dst[x + y*b->stride]--;
00141                                     //FIXME copy instead
00142                                 }
00143                             }
00144                         }
00145                     }
00146                 }
00147             }
00148         }
00149     }
00150     memcpy(s->spatial_idwt_buffer, best_dequant, height * stride * sizeof(IDWTELEM)); //FIXME work with that directly instead of copy at the end
00151 }
00152 
00153 #endif /* QUANTIZE2==1 */
00154 
00155 #if CONFIG_SNOW_ENCODER
00156 static av_cold int encode_init(AVCodecContext *avctx)
00157 {
00158     SnowContext *s = avctx->priv_data;
00159     int plane_index;
00160 
00161     if(avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
00162         av_log(avctx, AV_LOG_ERROR, "This codec is under development, files encoded with it may not be decodable with future versions!!!\n"
00163                "Use vstrict=-2 / -strict -2 to use it anyway.\n");
00164         return -1;
00165     }
00166 
00167     if(avctx->prediction_method == DWT_97
00168        && (avctx->flags & CODEC_FLAG_QSCALE)
00169        && avctx->global_quality == 0){
00170         av_log(avctx, AV_LOG_ERROR, "The 9/7 wavelet is incompatible with lossless mode.\n");
00171         return -1;
00172     }
00173 
00174     s->spatial_decomposition_type= avctx->prediction_method; //FIXME add decorrelator type r transform_type
00175 
00176     s->mv_scale       = (avctx->flags & CODEC_FLAG_QPEL) ? 2 : 4;
00177     s->block_max_depth= (avctx->flags & CODEC_FLAG_4MV ) ? 1 : 0;
00178 
00179     for(plane_index=0; plane_index<3; plane_index++){
00180         s->plane[plane_index].diag_mc= 1;
00181         s->plane[plane_index].htaps= 6;
00182         s->plane[plane_index].hcoeff[0]=  40;
00183         s->plane[plane_index].hcoeff[1]= -10;
00184         s->plane[plane_index].hcoeff[2]=   2;
00185         s->plane[plane_index].fast_mc= 1;
00186     }
00187 
00188     ff_snow_common_init(avctx);
00189     ff_snow_alloc_blocks(s);
00190 
00191     s->version=0;
00192 
00193     s->m.avctx   = avctx;
00194     s->m.flags   = avctx->flags;
00195     s->m.bit_rate= avctx->bit_rate;
00196 
00197     s->m.me.temp      =
00198     s->m.me.scratchpad= av_mallocz((avctx->width+64)*2*16*2*sizeof(uint8_t));
00199     s->m.me.map       = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
00200     s->m.me.score_map = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
00201     s->m.obmc_scratchpad= av_mallocz(MB_SIZE*MB_SIZE*12*sizeof(uint32_t));
00202     h263_encode_init(&s->m); //mv_penalty
00203 
00204     s->max_ref_frames = FFMAX(FFMIN(avctx->refs, MAX_REF_FRAMES), 1);
00205 
00206     if(avctx->flags&CODEC_FLAG_PASS1){
00207         if(!avctx->stats_out)
00208             avctx->stats_out = av_mallocz(256);
00209     }
00210     if((avctx->flags&CODEC_FLAG_PASS2) || !(avctx->flags&CODEC_FLAG_QSCALE)){
00211         if(ff_rate_control_init(&s->m) < 0)
00212             return -1;
00213     }
00214     s->pass1_rc= !(avctx->flags & (CODEC_FLAG_QSCALE|CODEC_FLAG_PASS2));
00215 
00216     avctx->coded_frame= &s->current_picture;
00217     switch(avctx->pix_fmt){
00218 //    case PIX_FMT_YUV444P:
00219 //    case PIX_FMT_YUV422P:
00220     case PIX_FMT_YUV420P:
00221     case PIX_FMT_GRAY8:
00222 //    case PIX_FMT_YUV411P:
00223 //    case PIX_FMT_YUV410P:
00224         s->colorspace_type= 0;
00225         break;
00226 /*    case PIX_FMT_RGB32:
00227         s->colorspace= 1;
00228         break;*/
00229     default:
00230         av_log(avctx, AV_LOG_ERROR, "pixel format not supported\n");
00231         return -1;
00232     }
00233 //    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
00234     s->chroma_h_shift= 1;
00235     s->chroma_v_shift= 1;
00236 
00237     ff_set_cmp(&s->dsp, s->dsp.me_cmp, s->avctx->me_cmp);
00238     ff_set_cmp(&s->dsp, s->dsp.me_sub_cmp, s->avctx->me_sub_cmp);
00239 
00240     s->avctx->get_buffer(s->avctx, &s->input_picture);
00241 
00242     if(s->avctx->me_method == ME_ITER){
00243         int i;
00244         int size= s->b_width * s->b_height << 2*s->block_max_depth;
00245         for(i=0; i<s->max_ref_frames; i++){
00246             s->ref_mvs[i]= av_mallocz(size*sizeof(int16_t[2]));
00247             s->ref_scores[i]= av_mallocz(size*sizeof(uint32_t));
00248         }
00249     }
00250 
00251     return 0;
00252 }
00253 
00254 //near copy & paste from dsputil, FIXME
00255 static int pix_sum(uint8_t * pix, int line_size, int w)
00256 {
00257     int s, i, j;
00258 
00259     s = 0;
00260     for (i = 0; i < w; i++) {
00261         for (j = 0; j < w; j++) {
00262             s += pix[0];
00263             pix ++;
00264         }
00265         pix += line_size - w;
00266     }
00267     return s;
00268 }
00269 
00270 //near copy & paste from dsputil, FIXME
00271 static int pix_norm1(uint8_t * pix, int line_size, int w)
00272 {
00273     int s, i, j;
00274     uint32_t *sq = ff_squareTbl + 256;
00275 
00276     s = 0;
00277     for (i = 0; i < w; i++) {
00278         for (j = 0; j < w; j ++) {
00279             s += sq[pix[0]];
00280             pix ++;
00281         }
00282         pix += line_size - w;
00283     }
00284     return s;
00285 }
00286 
00287 //FIXME copy&paste
00288 #define P_LEFT P[1]
00289 #define P_TOP P[2]
00290 #define P_TOPRIGHT P[3]
00291 #define P_MEDIAN P[4]
00292 #define P_MV1 P[9]
00293 #define FLAG_QPEL   1 //must be 1
00294 
00295 static int encode_q_branch(SnowContext *s, int level, int x, int y){
00296     uint8_t p_buffer[1024];
00297     uint8_t i_buffer[1024];
00298     uint8_t p_state[sizeof(s->block_state)];
00299     uint8_t i_state[sizeof(s->block_state)];
00300     RangeCoder pc, ic;
00301     uint8_t *pbbak= s->c.bytestream;
00302     uint8_t *pbbak_start= s->c.bytestream_start;
00303     int score, score2, iscore, i_len, p_len, block_s, sum, base_bits;
00304     const int w= s->b_width  << s->block_max_depth;
00305     const int h= s->b_height << s->block_max_depth;
00306     const int rem_depth= s->block_max_depth - level;
00307     const int index= (x + y*w) << rem_depth;
00308     const int block_w= 1<<(LOG2_MB_SIZE - level);
00309     int trx= (x+1)<<rem_depth;
00310     int try= (y+1)<<rem_depth;
00311     const BlockNode *left  = x ? &s->block[index-1] : &null_block;
00312     const BlockNode *top   = y ? &s->block[index-w] : &null_block;
00313     const BlockNode *right = trx<w ? &s->block[index+1] : &null_block;
00314     const BlockNode *bottom= try<h ? &s->block[index+w] : &null_block;
00315     const BlockNode *tl    = y && x ? &s->block[index-w-1] : left;
00316     const BlockNode *tr    = y && trx<w && ((x&1)==0 || level==0) ? &s->block[index-w+(1<<rem_depth)] : tl; //FIXME use lt
00317     int pl = left->color[0];
00318     int pcb= left->color[1];
00319     int pcr= left->color[2];
00320     int pmx, pmy;
00321     int mx=0, my=0;
00322     int l,cr,cb;
00323     const int stride= s->current_picture.linesize[0];
00324     const int uvstride= s->current_picture.linesize[1];
00325     uint8_t *current_data[3]= { s->input_picture.data[0] + (x + y*  stride)*block_w,
00326                                 s->input_picture.data[1] + (x + y*uvstride)*block_w/2,
00327                                 s->input_picture.data[2] + (x + y*uvstride)*block_w/2};
00328     int P[10][2];
00329     int16_t last_mv[3][2];
00330     int qpel= !!(s->avctx->flags & CODEC_FLAG_QPEL); //unused
00331     const int shift= 1+qpel;
00332     MotionEstContext *c= &s->m.me;
00333     int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
00334     int mx_context= av_log2(2*FFABS(left->mx - top->mx));
00335     int my_context= av_log2(2*FFABS(left->my - top->my));
00336     int s_context= 2*left->level + 2*top->level + tl->level + tr->level;
00337     int ref, best_ref, ref_score, ref_mx, ref_my;
00338 
00339     assert(sizeof(s->block_state) >= 256);
00340     if(s->keyframe){
00341         set_blocks(s, level, x, y, pl, pcb, pcr, 0, 0, 0, BLOCK_INTRA);
00342         return 0;
00343     }
00344 
00345 //    clip predictors / edge ?
00346 
00347     P_LEFT[0]= left->mx;
00348     P_LEFT[1]= left->my;
00349     P_TOP [0]= top->mx;
00350     P_TOP [1]= top->my;
00351     P_TOPRIGHT[0]= tr->mx;
00352     P_TOPRIGHT[1]= tr->my;
00353 
00354     last_mv[0][0]= s->block[index].mx;
00355     last_mv[0][1]= s->block[index].my;
00356     last_mv[1][0]= right->mx;
00357     last_mv[1][1]= right->my;
00358     last_mv[2][0]= bottom->mx;
00359     last_mv[2][1]= bottom->my;
00360 
00361     s->m.mb_stride=2;
00362     s->m.mb_x=
00363     s->m.mb_y= 0;
00364     c->skip= 0;
00365 
00366     assert(c->  stride ==   stride);
00367     assert(c->uvstride == uvstride);
00368 
00369     c->penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_cmp);
00370     c->sub_penalty_factor= get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_sub_cmp);
00371     c->mb_penalty_factor = get_penalty_factor(s->lambda, s->lambda2, c->avctx->mb_cmp);
00372     c->current_mv_penalty= c->mv_penalty[s->m.f_code=1] + MAX_MV;
00373 
00374     c->xmin = - x*block_w - 16+3;
00375     c->ymin = - y*block_w - 16+3;
00376     c->xmax = - (x+1)*block_w + (w<<(LOG2_MB_SIZE - s->block_max_depth)) + 16-3;
00377     c->ymax = - (y+1)*block_w + (h<<(LOG2_MB_SIZE - s->block_max_depth)) + 16-3;
00378 
00379     if(P_LEFT[0]     > (c->xmax<<shift)) P_LEFT[0]    = (c->xmax<<shift);
00380     if(P_LEFT[1]     > (c->ymax<<shift)) P_LEFT[1]    = (c->ymax<<shift);
00381     if(P_TOP[0]      > (c->xmax<<shift)) P_TOP[0]     = (c->xmax<<shift);
00382     if(P_TOP[1]      > (c->ymax<<shift)) P_TOP[1]     = (c->ymax<<shift);
00383     if(P_TOPRIGHT[0] < (c->xmin<<shift)) P_TOPRIGHT[0]= (c->xmin<<shift);
00384     if(P_TOPRIGHT[0] > (c->xmax<<shift)) P_TOPRIGHT[0]= (c->xmax<<shift); //due to pmx no clip
00385     if(P_TOPRIGHT[1] > (c->ymax<<shift)) P_TOPRIGHT[1]= (c->ymax<<shift);
00386 
00387     P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
00388     P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
00389 
00390     if (!y) {
00391         c->pred_x= P_LEFT[0];
00392         c->pred_y= P_LEFT[1];
00393     } else {
00394         c->pred_x = P_MEDIAN[0];
00395         c->pred_y = P_MEDIAN[1];
00396     }
00397 
00398     score= INT_MAX;
00399     best_ref= 0;
00400     for(ref=0; ref<s->ref_frames; ref++){
00401         init_ref(c, current_data, s->last_picture[ref].data, NULL, block_w*x, block_w*y, 0);
00402 
00403         ref_score= ff_epzs_motion_search(&s->m, &ref_mx, &ref_my, P, 0, /*ref_index*/ 0, last_mv,
00404                                          (1<<16)>>shift, level-LOG2_MB_SIZE+4, block_w);
00405 
00406         assert(ref_mx >= c->xmin);
00407         assert(ref_mx <= c->xmax);
00408         assert(ref_my >= c->ymin);
00409         assert(ref_my <= c->ymax);
00410 
00411         ref_score= c->sub_motion_search(&s->m, &ref_mx, &ref_my, ref_score, 0, 0, level-LOG2_MB_SIZE+4, block_w);
00412         ref_score= ff_get_mb_score(&s->m, ref_mx, ref_my, 0, 0, level-LOG2_MB_SIZE+4, block_w, 0);
00413         ref_score+= 2*av_log2(2*ref)*c->penalty_factor;
00414         if(s->ref_mvs[ref]){
00415             s->ref_mvs[ref][index][0]= ref_mx;
00416             s->ref_mvs[ref][index][1]= ref_my;
00417             s->ref_scores[ref][index]= ref_score;
00418         }
00419         if(score > ref_score){
00420             score= ref_score;
00421             best_ref= ref;
00422             mx= ref_mx;
00423             my= ref_my;
00424         }
00425     }
00426     //FIXME if mb_cmp != SSE then intra cannot be compared currently and mb_penalty vs. lambda2
00427 
00428   //  subpel search
00429     base_bits= get_rac_count(&s->c) - 8*(s->c.bytestream - s->c.bytestream_start);
00430     pc= s->c;
00431     pc.bytestream_start=
00432     pc.bytestream= p_buffer; //FIXME end/start? and at the other stoo
00433     memcpy(p_state, s->block_state, sizeof(s->block_state));
00434 
00435     if(level!=s->block_max_depth)
00436         put_rac(&pc, &p_state[4 + s_context], 1);
00437     put_rac(&pc, &p_state[1 + left->type + top->type], 0);
00438     if(s->ref_frames > 1)
00439         put_symbol(&pc, &p_state[128 + 1024 + 32*ref_context], best_ref, 0);
00440     pred_mv(s, &pmx, &pmy, best_ref, left, top, tr);
00441     put_symbol(&pc, &p_state[128 + 32*(mx_context + 16*!!best_ref)], mx - pmx, 1);
00442     put_symbol(&pc, &p_state[128 + 32*(my_context + 16*!!best_ref)], my - pmy, 1);
00443     p_len= pc.bytestream - pc.bytestream_start;
00444     score += (s->lambda2*(get_rac_count(&pc)-base_bits))>>FF_LAMBDA_SHIFT;
00445 
00446     block_s= block_w*block_w;
00447     sum = pix_sum(current_data[0], stride, block_w);
00448     l= (sum + block_s/2)/block_s;
00449     iscore = pix_norm1(current_data[0], stride, block_w) - 2*l*sum + l*l*block_s;
00450 
00451     block_s= block_w*block_w>>2;
00452     sum = pix_sum(current_data[1], uvstride, block_w>>1);
00453     cb= (sum + block_s/2)/block_s;
00454 //    iscore += pix_norm1(&current_mb[1][0], uvstride, block_w>>1) - 2*cb*sum + cb*cb*block_s;
00455     sum = pix_sum(current_data[2], uvstride, block_w>>1);
00456     cr= (sum + block_s/2)/block_s;
00457 //    iscore += pix_norm1(&current_mb[2][0], uvstride, block_w>>1) - 2*cr*sum + cr*cr*block_s;
00458 
00459     ic= s->c;
00460     ic.bytestream_start=
00461     ic.bytestream= i_buffer; //FIXME end/start? and at the other stoo
00462     memcpy(i_state, s->block_state, sizeof(s->block_state));
00463     if(level!=s->block_max_depth)
00464         put_rac(&ic, &i_state[4 + s_context], 1);
00465     put_rac(&ic, &i_state[1 + left->type + top->type], 1);
00466     put_symbol(&ic, &i_state[32],  l-pl , 1);
00467     put_symbol(&ic, &i_state[64], cb-pcb, 1);
00468     put_symbol(&ic, &i_state[96], cr-pcr, 1);
00469     i_len= ic.bytestream - ic.bytestream_start;
00470     iscore += (s->lambda2*(get_rac_count(&ic)-base_bits))>>FF_LAMBDA_SHIFT;
00471 
00472 //    assert(score==256*256*256*64-1);
00473     assert(iscore < 255*255*256 + s->lambda2*10);
00474     assert(iscore >= 0);
00475     assert(l>=0 && l<=255);
00476     assert(pl>=0 && pl<=255);
00477 
00478     if(level==0){
00479         int varc= iscore >> 8;
00480         int vard= score >> 8;
00481         if (vard <= 64 || vard < varc)
00482             c->scene_change_score+= ff_sqrt(vard) - ff_sqrt(varc);
00483         else
00484             c->scene_change_score+= s->m.qscale;
00485     }
00486 
00487     if(level!=s->block_max_depth){
00488         put_rac(&s->c, &s->block_state[4 + s_context], 0);
00489         score2 = encode_q_branch(s, level+1, 2*x+0, 2*y+0);
00490         score2+= encode_q_branch(s, level+1, 2*x+1, 2*y+0);
00491         score2+= encode_q_branch(s, level+1, 2*x+0, 2*y+1);
00492         score2+= encode_q_branch(s, level+1, 2*x+1, 2*y+1);
00493         score2+= s->lambda2>>FF_LAMBDA_SHIFT; //FIXME exact split overhead
00494 
00495         if(score2 < score && score2 < iscore)
00496             return score2;
00497     }
00498 
00499     if(iscore < score){
00500         pred_mv(s, &pmx, &pmy, 0, left, top, tr);
00501         memcpy(pbbak, i_buffer, i_len);
00502         s->c= ic;
00503         s->c.bytestream_start= pbbak_start;
00504         s->c.bytestream= pbbak + i_len;
00505         set_blocks(s, level, x, y, l, cb, cr, pmx, pmy, 0, BLOCK_INTRA);
00506         memcpy(s->block_state, i_state, sizeof(s->block_state));
00507         return iscore;
00508     }else{
00509         memcpy(pbbak, p_buffer, p_len);
00510         s->c= pc;
00511         s->c.bytestream_start= pbbak_start;
00512         s->c.bytestream= pbbak + p_len;
00513         set_blocks(s, level, x, y, pl, pcb, pcr, mx, my, best_ref, 0);
00514         memcpy(s->block_state, p_state, sizeof(s->block_state));
00515         return score;
00516     }
00517 }
00518 
00519 static void encode_q_branch2(SnowContext *s, int level, int x, int y){
00520     const int w= s->b_width  << s->block_max_depth;
00521     const int rem_depth= s->block_max_depth - level;
00522     const int index= (x + y*w) << rem_depth;
00523     int trx= (x+1)<<rem_depth;
00524     BlockNode *b= &s->block[index];
00525     const BlockNode *left  = x ? &s->block[index-1] : &null_block;
00526     const BlockNode *top   = y ? &s->block[index-w] : &null_block;
00527     const BlockNode *tl    = y && x ? &s->block[index-w-1] : left;
00528     const BlockNode *tr    = y && trx<w && ((x&1)==0 || level==0) ? &s->block[index-w+(1<<rem_depth)] : tl; //FIXME use lt
00529     int pl = left->color[0];
00530     int pcb= left->color[1];
00531     int pcr= left->color[2];
00532     int pmx, pmy;
00533     int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
00534     int mx_context= av_log2(2*FFABS(left->mx - top->mx)) + 16*!!b->ref;
00535     int my_context= av_log2(2*FFABS(left->my - top->my)) + 16*!!b->ref;
00536     int s_context= 2*left->level + 2*top->level + tl->level + tr->level;
00537 
00538     if(s->keyframe){
00539         set_blocks(s, level, x, y, pl, pcb, pcr, 0, 0, 0, BLOCK_INTRA);
00540         return;
00541     }
00542 
00543     if(level!=s->block_max_depth){
00544         if(same_block(b,b+1) && same_block(b,b+w) && same_block(b,b+w+1)){
00545             put_rac(&s->c, &s->block_state[4 + s_context], 1);
00546         }else{
00547             put_rac(&s->c, &s->block_state[4 + s_context], 0);
00548             encode_q_branch2(s, level+1, 2*x+0, 2*y+0);
00549             encode_q_branch2(s, level+1, 2*x+1, 2*y+0);
00550             encode_q_branch2(s, level+1, 2*x+0, 2*y+1);
00551             encode_q_branch2(s, level+1, 2*x+1, 2*y+1);
00552             return;
00553         }
00554     }
00555     if(b->type & BLOCK_INTRA){
00556         pred_mv(s, &pmx, &pmy, 0, left, top, tr);
00557         put_rac(&s->c, &s->block_state[1 + (left->type&1) + (top->type&1)], 1);
00558         put_symbol(&s->c, &s->block_state[32], b->color[0]-pl , 1);
00559         put_symbol(&s->c, &s->block_state[64], b->color[1]-pcb, 1);
00560         put_symbol(&s->c, &s->block_state[96], b->color[2]-pcr, 1);
00561         set_blocks(s, level, x, y, b->color[0], b->color[1], b->color[2], pmx, pmy, 0, BLOCK_INTRA);
00562     }else{
00563         pred_mv(s, &pmx, &pmy, b->ref, left, top, tr);
00564         put_rac(&s->c, &s->block_state[1 + (left->type&1) + (top->type&1)], 0);
00565         if(s->ref_frames > 1)
00566             put_symbol(&s->c, &s->block_state[128 + 1024 + 32*ref_context], b->ref, 0);
00567         put_symbol(&s->c, &s->block_state[128 + 32*mx_context], b->mx - pmx, 1);
00568         put_symbol(&s->c, &s->block_state[128 + 32*my_context], b->my - pmy, 1);
00569         set_blocks(s, level, x, y, pl, pcb, pcr, b->mx, b->my, b->ref, 0);
00570     }
00571 }
00572 
00573 static int get_dc(SnowContext *s, int mb_x, int mb_y, int plane_index){
00574     int i, x2, y2;
00575     Plane *p= &s->plane[plane_index];
00576     const int block_size = MB_SIZE >> s->block_max_depth;
00577     const int block_w    = plane_index ? block_size/2 : block_size;
00578     const uint8_t *obmc  = plane_index ? obmc_tab[s->block_max_depth+1] : obmc_tab[s->block_max_depth];
00579     const int obmc_stride= plane_index ? block_size : 2*block_size;
00580     const int ref_stride= s->current_picture.linesize[plane_index];
00581     uint8_t *src= s-> input_picture.data[plane_index];
00582     IDWTELEM *dst= (IDWTELEM*)s->m.obmc_scratchpad + plane_index*block_size*block_size*4; //FIXME change to unsigned
00583     const int b_stride = s->b_width << s->block_max_depth;
00584     const int w= p->width;
00585     const int h= p->height;
00586     int index= mb_x + mb_y*b_stride;
00587     BlockNode *b= &s->block[index];
00588     BlockNode backup= *b;
00589     int ab=0;
00590     int aa=0;
00591 
00592     b->type|= BLOCK_INTRA;
00593     b->color[plane_index]= 0;
00594     memset(dst, 0, obmc_stride*obmc_stride*sizeof(IDWTELEM));
00595 
00596     for(i=0; i<4; i++){
00597         int mb_x2= mb_x + (i &1) - 1;
00598         int mb_y2= mb_y + (i>>1) - 1;
00599         int x= block_w*mb_x2 + block_w/2;
00600         int y= block_w*mb_y2 + block_w/2;
00601 
00602         add_yblock(s, 0, NULL, dst + ((i&1)+(i>>1)*obmc_stride)*block_w, NULL, obmc,
00603                     x, y, block_w, block_w, w, h, obmc_stride, ref_stride, obmc_stride, mb_x2, mb_y2, 0, 0, plane_index);
00604 
00605         for(y2= FFMAX(y, 0); y2<FFMIN(h, y+block_w); y2++){
00606             for(x2= FFMAX(x, 0); x2<FFMIN(w, x+block_w); x2++){
00607                 int index= x2-(block_w*mb_x - block_w/2) + (y2-(block_w*mb_y - block_w/2))*obmc_stride;
00608                 int obmc_v= obmc[index];
00609                 int d;
00610                 if(y<0) obmc_v += obmc[index + block_w*obmc_stride];
00611                 if(x<0) obmc_v += obmc[index + block_w];
00612                 if(y+block_w>h) obmc_v += obmc[index - block_w*obmc_stride];
00613                 if(x+block_w>w) obmc_v += obmc[index - block_w];
00614                 //FIXME precalculate this or simplify it somehow else
00615 
00616                 d = -dst[index] + (1<<(FRAC_BITS-1));
00617                 dst[index] = d;
00618                 ab += (src[x2 + y2*ref_stride] - (d>>FRAC_BITS)) * obmc_v;
00619                 aa += obmc_v * obmc_v; //FIXME precalculate this
00620             }
00621         }
00622     }
00623     *b= backup;
00624 
00625     return av_clip(((ab<<LOG2_OBMC_MAX) + aa/2)/aa, 0, 255); //FIXME we should not need clipping
00626 }
00627 
00628 static inline int get_block_bits(SnowContext *s, int x, int y, int w){
00629     const int b_stride = s->b_width << s->block_max_depth;
00630     const int b_height = s->b_height<< s->block_max_depth;
00631     int index= x + y*b_stride;
00632     const BlockNode *b     = &s->block[index];
00633     const BlockNode *left  = x ? &s->block[index-1] : &null_block;
00634     const BlockNode *top   = y ? &s->block[index-b_stride] : &null_block;
00635     const BlockNode *tl    = y && x ? &s->block[index-b_stride-1] : left;
00636     const BlockNode *tr    = y && x+w<b_stride ? &s->block[index-b_stride+w] : tl;
00637     int dmx, dmy;
00638 //  int mx_context= av_log2(2*FFABS(left->mx - top->mx));
00639 //  int my_context= av_log2(2*FFABS(left->my - top->my));
00640 
00641     if(x<0 || x>=b_stride || y>=b_height)
00642         return 0;
00643 /*
00644 1            0      0
00645 01X          1-2    1
00646 001XX        3-6    2-3
00647 0001XXX      7-14   4-7
00648 00001XXXX   15-30   8-15
00649 */
00650 //FIXME try accurate rate
00651 //FIXME intra and inter predictors if surrounding blocks are not the same type
00652     if(b->type & BLOCK_INTRA){
00653         return 3+2*( av_log2(2*FFABS(left->color[0] - b->color[0]))
00654                    + av_log2(2*FFABS(left->color[1] - b->color[1]))
00655                    + av_log2(2*FFABS(left->color[2] - b->color[2])));
00656     }else{
00657         pred_mv(s, &dmx, &dmy, b->ref, left, top, tr);
00658         dmx-= b->mx;
00659         dmy-= b->my;
00660         return 2*(1 + av_log2(2*FFABS(dmx)) //FIXME kill the 2* can be merged in lambda
00661                     + av_log2(2*FFABS(dmy))
00662                     + av_log2(2*b->ref));
00663     }
00664 }
00665 
00666 static int get_block_rd(SnowContext *s, int mb_x, int mb_y, int plane_index, const uint8_t *obmc_edged){
00667     Plane *p= &s->plane[plane_index];
00668     const int block_size = MB_SIZE >> s->block_max_depth;
00669     const int block_w    = plane_index ? block_size/2 : block_size;
00670     const int obmc_stride= plane_index ? block_size : 2*block_size;
00671     const int ref_stride= s->current_picture.linesize[plane_index];
00672     uint8_t *dst= s->current_picture.data[plane_index];
00673     uint8_t *src= s->  input_picture.data[plane_index];
00674     IDWTELEM *pred= (IDWTELEM*)s->m.obmc_scratchpad + plane_index*block_size*block_size*4;
00675     uint8_t *cur = s->scratchbuf;
00676     uint8_t tmp[ref_stride*(2*MB_SIZE+HTAPS_MAX-1)];
00677     const int b_stride = s->b_width << s->block_max_depth;
00678     const int b_height = s->b_height<< s->block_max_depth;
00679     const int w= p->width;
00680     const int h= p->height;
00681     int distortion;
00682     int rate= 0;
00683     const int penalty_factor= get_penalty_factor(s->lambda, s->lambda2, s->avctx->me_cmp);
00684     int sx= block_w*mb_x - block_w/2;
00685     int sy= block_w*mb_y - block_w/2;
00686     int x0= FFMAX(0,-sx);
00687     int y0= FFMAX(0,-sy);
00688     int x1= FFMIN(block_w*2, w-sx);
00689     int y1= FFMIN(block_w*2, h-sy);
00690     int i,x,y;
00691 
00692     ff_snow_pred_block(s, cur, tmp, ref_stride, sx, sy, block_w*2, block_w*2, &s->block[mb_x + mb_y*b_stride], plane_index, w, h);
00693 
00694     for(y=y0; y<y1; y++){
00695         const uint8_t *obmc1= obmc_edged + y*obmc_stride;
00696         const IDWTELEM *pred1 = pred + y*obmc_stride;
00697         uint8_t *cur1 = cur + y*ref_stride;
00698         uint8_t *dst1 = dst + sx + (sy+y)*ref_stride;
00699         for(x=x0; x<x1; x++){
00700 #if FRAC_BITS >= LOG2_OBMC_MAX
00701             int v = (cur1[x] * obmc1[x]) << (FRAC_BITS - LOG2_OBMC_MAX);
00702 #else
00703             int v = (cur1[x] * obmc1[x] + (1<<(LOG2_OBMC_MAX - FRAC_BITS-1))) >> (LOG2_OBMC_MAX - FRAC_BITS);
00704 #endif
00705             v = (v + pred1[x]) >> FRAC_BITS;
00706             if(v&(~255)) v= ~(v>>31);
00707             dst1[x] = v;
00708         }
00709     }
00710 
00711     /* copy the regions where obmc[] = (uint8_t)256 */
00712     if(LOG2_OBMC_MAX == 8
00713         && (mb_x == 0 || mb_x == b_stride-1)
00714         && (mb_y == 0 || mb_y == b_height-1)){
00715         if(mb_x == 0)
00716             x1 = block_w;
00717         else
00718             x0 = block_w;
00719         if(mb_y == 0)
00720             y1 = block_w;
00721         else
00722             y0 = block_w;
00723         for(y=y0; y<y1; y++)
00724             memcpy(dst + sx+x0 + (sy+y)*ref_stride, cur + x0 + y*ref_stride, x1-x0);
00725     }
00726 
00727     if(block_w==16){
00728         /* FIXME rearrange dsputil to fit 32x32 cmp functions */
00729         /* FIXME check alignment of the cmp wavelet vs the encoding wavelet */
00730         /* FIXME cmps overlap but do not cover the wavelet's whole support.
00731          * So improving the score of one block is not strictly guaranteed
00732          * to improve the score of the whole frame, thus iterative motion
00733          * estimation does not always converge. */
00734         if(s->avctx->me_cmp == FF_CMP_W97)
00735             distortion = ff_w97_32_c(&s->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, 32);
00736         else if(s->avctx->me_cmp == FF_CMP_W53)
00737             distortion = ff_w53_32_c(&s->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, 32);
00738         else{
00739             distortion = 0;
00740             for(i=0; i<4; i++){
00741                 int off = sx+16*(i&1) + (sy+16*(i>>1))*ref_stride;
00742                 distortion += s->dsp.me_cmp[0](&s->m, src + off, dst + off, ref_stride, 16);
00743             }
00744         }
00745     }else{
00746         assert(block_w==8);
00747         distortion = s->dsp.me_cmp[0](&s->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, block_w*2);
00748     }
00749 
00750     if(plane_index==0){
00751         for(i=0; i<4; i++){
00752 /* ..RRr
00753  * .RXx.
00754  * rxx..
00755  */
00756             rate += get_block_bits(s, mb_x + (i&1) - (i>>1), mb_y + (i>>1), 1);
00757         }
00758         if(mb_x == b_stride-2)
00759             rate += get_block_bits(s, mb_x + 1, mb_y + 1, 1);
00760     }
00761     return distortion + rate*penalty_factor;
00762 }
00763 
00764 static int get_4block_rd(SnowContext *s, int mb_x, int mb_y, int plane_index){
00765     int i, y2;
00766     Plane *p= &s->plane[plane_index];
00767     const int block_size = MB_SIZE >> s->block_max_depth;
00768     const int block_w    = plane_index ? block_size/2 : block_size;
00769     const uint8_t *obmc  = plane_index ? obmc_tab[s->block_max_depth+1] : obmc_tab[s->block_max_depth];
00770     const int obmc_stride= plane_index ? block_size : 2*block_size;
00771     const int ref_stride= s->current_picture.linesize[plane_index];
00772     uint8_t *dst= s->current_picture.data[plane_index];
00773     uint8_t *src= s-> input_picture.data[plane_index];
00774     //FIXME zero_dst is const but add_yblock changes dst if add is 0 (this is never the case for dst=zero_dst
00775     // const has only been removed from zero_dst to suppress a warning
00776     static IDWTELEM zero_dst[4096]; //FIXME
00777     const int b_stride = s->b_width << s->block_max_depth;
00778     const int w= p->width;
00779     const int h= p->height;
00780     int distortion= 0;
00781     int rate= 0;
00782     const int penalty_factor= get_penalty_factor(s->lambda, s->lambda2, s->avctx->me_cmp);
00783 
00784     for(i=0; i<9; i++){
00785         int mb_x2= mb_x + (i%3) - 1;
00786         int mb_y2= mb_y + (i/3) - 1;
00787         int x= block_w*mb_x2 + block_w/2;
00788         int y= block_w*mb_y2 + block_w/2;
00789 
00790         add_yblock(s, 0, NULL, zero_dst, dst, obmc,
00791                    x, y, block_w, block_w, w, h, /*dst_stride*/0, ref_stride, obmc_stride, mb_x2, mb_y2, 1, 1, plane_index);
00792 
00793         //FIXME find a cleaner/simpler way to skip the outside stuff
00794         for(y2= y; y2<0; y2++)
00795             memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, block_w);
00796         for(y2= h; y2<y+block_w; y2++)
00797             memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, block_w);
00798         if(x<0){
00799             for(y2= y; y2<y+block_w; y2++)
00800                 memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, -x);
00801         }
00802         if(x+block_w > w){
00803             for(y2= y; y2<y+block_w; y2++)
00804                 memcpy(dst + w + y2*ref_stride, src + w + y2*ref_stride, x+block_w - w);
00805         }
00806 
00807         assert(block_w== 8 || block_w==16);
00808         distortion += s->dsp.me_cmp[block_w==8](&s->m, src + x + y*ref_stride, dst + x + y*ref_stride, ref_stride, block_w);
00809     }
00810 
00811     if(plane_index==0){
00812         BlockNode *b= &s->block[mb_x+mb_y*b_stride];
00813         int merged= same_block(b,b+1) && same_block(b,b+b_stride) && same_block(b,b+b_stride+1);
00814 
00815 /* ..RRRr
00816  * .RXXx.
00817  * .RXXx.
00818  * rxxx.
00819  */
00820         if(merged)
00821             rate = get_block_bits(s, mb_x, mb_y, 2);
00822         for(i=merged?4:0; i<9; i++){
00823             static const int dxy[9][2] = {{0,0},{1,0},{0,1},{1,1},{2,0},{2,1},{-1,2},{0,2},{1,2}};
00824             rate += get_block_bits(s, mb_x + dxy[i][0], mb_y + dxy[i][1], 1);
00825         }
00826     }
00827     return distortion + rate*penalty_factor;
00828 }
00829 
00830 static int encode_subband_c0run(SnowContext *s, SubBand *b, IDWTELEM *src, IDWTELEM *parent, int stride, int orientation){
00831     const int w= b->width;
00832     const int h= b->height;
00833     int x, y;
00834 
00835     if(1){
00836         int run=0;
00837         int runs[w*h];
00838         int run_index=0;
00839         int max_index;
00840 
00841         for(y=0; y<h; y++){
00842             for(x=0; x<w; x++){
00843                 int v, p=0;
00844                 int /*ll=0, */l=0, lt=0, t=0, rt=0;
00845                 v= src[x + y*stride];
00846 
00847                 if(y){
00848                     t= src[x + (y-1)*stride];
00849                     if(x){
00850                         lt= src[x - 1 + (y-1)*stride];
00851                     }
00852                     if(x + 1 < w){
00853                         rt= src[x + 1 + (y-1)*stride];
00854                     }
00855                 }
00856                 if(x){
00857                     l= src[x - 1 + y*stride];
00858                     /*if(x > 1){
00859                         if(orientation==1) ll= src[y + (x-2)*stride];
00860                         else               ll= src[x - 2 + y*stride];
00861                     }*/
00862                 }
00863                 if(parent){
00864                     int px= x>>1;
00865                     int py= y>>1;
00866                     if(px<b->parent->width && py<b->parent->height)
00867                         p= parent[px + py*2*stride];
00868                 }
00869                 if(!(/*ll|*/l|lt|t|rt|p)){
00870                     if(v){
00871                         runs[run_index++]= run;
00872                         run=0;
00873                     }else{
00874                         run++;
00875                     }
00876                 }
00877             }
00878         }
00879         max_index= run_index;
00880         runs[run_index++]= run;
00881         run_index=0;
00882         run= runs[run_index++];
00883 
00884         put_symbol2(&s->c, b->state[30], max_index, 0);
00885         if(run_index <= max_index)
00886             put_symbol2(&s->c, b->state[1], run, 3);
00887 
00888         for(y=0; y<h; y++){
00889             if(s->c.bytestream_end - s->c.bytestream < w*40){
00890                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
00891                 return -1;
00892             }
00893             for(x=0; x<w; x++){
00894                 int v, p=0;
00895                 int /*ll=0, */l=0, lt=0, t=0, rt=0;
00896                 v= src[x + y*stride];
00897 
00898                 if(y){
00899                     t= src[x + (y-1)*stride];
00900                     if(x){
00901                         lt= src[x - 1 + (y-1)*stride];
00902                     }
00903                     if(x + 1 < w){
00904                         rt= src[x + 1 + (y-1)*stride];
00905                     }
00906                 }
00907                 if(x){
00908                     l= src[x - 1 + y*stride];
00909                     /*if(x > 1){
00910                         if(orientation==1) ll= src[y + (x-2)*stride];
00911                         else               ll= src[x - 2 + y*stride];
00912                     }*/
00913                 }
00914                 if(parent){
00915                     int px= x>>1;
00916                     int py= y>>1;
00917                     if(px<b->parent->width && py<b->parent->height)
00918                         p= parent[px + py*2*stride];
00919                 }
00920                 if(/*ll|*/l|lt|t|rt|p){
00921                     int context= av_log2(/*FFABS(ll) + */3*FFABS(l) + FFABS(lt) + 2*FFABS(t) + FFABS(rt) + FFABS(p));
00922 
00923                     put_rac(&s->c, &b->state[0][context], !!v);
00924                 }else{
00925                     if(!run){
00926                         run= runs[run_index++];
00927 
00928                         if(run_index <= max_index)
00929                             put_symbol2(&s->c, b->state[1], run, 3);
00930                         assert(v);
00931                     }else{
00932                         run--;
00933                         assert(!v);
00934                     }
00935                 }
00936                 if(v){
00937                     int context= av_log2(/*FFABS(ll) + */3*FFABS(l) + FFABS(lt) + 2*FFABS(t) + FFABS(rt) + FFABS(p));
00938                     int l2= 2*FFABS(l) + (l<0);
00939                     int t2= 2*FFABS(t) + (t<0);
00940 
00941                     put_symbol2(&s->c, b->state[context + 2], FFABS(v)-1, context-4);
00942                     put_rac(&s->c, &b->state[0][16 + 1 + 3 + quant3bA[l2&0xFF] + 3*quant3bA[t2&0xFF]], v<0);
00943                 }
00944             }
00945         }
00946     }
00947     return 0;
00948 }
00949 
00950 static int encode_subband(SnowContext *s, SubBand *b, IDWTELEM *src, IDWTELEM *parent, int stride, int orientation){
00951 //    encode_subband_qtree(s, b, src, parent, stride, orientation);
00952 //    encode_subband_z0run(s, b, src, parent, stride, orientation);
00953     return encode_subband_c0run(s, b, src, parent, stride, orientation);
00954 //    encode_subband_dzr(s, b, src, parent, stride, orientation);
00955 }
00956 
00957 static av_always_inline int check_block(SnowContext *s, int mb_x, int mb_y, int p[3], int intra, const uint8_t *obmc_edged, int *best_rd){
00958     const int b_stride= s->b_width << s->block_max_depth;
00959     BlockNode *block= &s->block[mb_x + mb_y * b_stride];
00960     BlockNode backup= *block;
00961     unsigned value;
00962     int rd, index;
00963 
00964     assert(mb_x>=0 && mb_y>=0);
00965     assert(mb_x<b_stride);
00966 
00967     if(intra){
00968         block->color[0] = p[0];
00969         block->color[1] = p[1];
00970         block->color[2] = p[2];
00971         block->type |= BLOCK_INTRA;
00972     }else{
00973         index= (p[0] + 31*p[1]) & (ME_CACHE_SIZE-1);
00974         value= s->me_cache_generation + (p[0]>>10) + (p[1]<<6) + (block->ref<<12);
00975         if(s->me_cache[index] == value)
00976             return 0;
00977         s->me_cache[index]= value;
00978 
00979         block->mx= p[0];
00980         block->my= p[1];
00981         block->type &= ~BLOCK_INTRA;
00982     }
00983 
00984     rd= get_block_rd(s, mb_x, mb_y, 0, obmc_edged);
00985 
00986 //FIXME chroma
00987     if(rd < *best_rd){
00988         *best_rd= rd;
00989         return 1;
00990     }else{
00991         *block= backup;
00992         return 0;
00993     }
00994 }
00995 
00996 /* special case for int[2] args we discard afterwards,
00997  * fixes compilation problem with gcc 2.95 */
00998 static av_always_inline int check_block_inter(SnowContext *s, int mb_x, int mb_y, int p0, int p1, const uint8_t *obmc_edged, int *best_rd){
00999     int p[2] = {p0, p1};
01000     return check_block(s, mb_x, mb_y, p, 0, obmc_edged, best_rd);
01001 }
01002 
01003 static av_always_inline int check_4block_inter(SnowContext *s, int mb_x, int mb_y, int p0, int p1, int ref, int *best_rd){
01004     const int b_stride= s->b_width << s->block_max_depth;
01005     BlockNode *block= &s->block[mb_x + mb_y * b_stride];
01006     BlockNode backup[4]= {block[0], block[1], block[b_stride], block[b_stride+1]};
01007     unsigned value;
01008     int rd, index;
01009 
01010     assert(mb_x>=0 && mb_y>=0);
01011     assert(mb_x<b_stride);
01012     assert(((mb_x|mb_y)&1) == 0);
01013 
01014     index= (p0 + 31*p1) & (ME_CACHE_SIZE-1);
01015     value= s->me_cache_generation + (p0>>10) + (p1<<6) + (block->ref<<12);
01016     if(s->me_cache[index] == value)
01017         return 0;
01018     s->me_cache[index]= value;
01019 
01020     block->mx= p0;
01021     block->my= p1;
01022     block->ref= ref;
01023     block->type &= ~BLOCK_INTRA;
01024     block[1]= block[b_stride]= block[b_stride+1]= *block;
01025 
01026     rd= get_4block_rd(s, mb_x, mb_y, 0);
01027 
01028 //FIXME chroma
01029     if(rd < *best_rd){
01030         *best_rd= rd;
01031         return 1;
01032     }else{
01033         block[0]= backup[0];
01034         block[1]= backup[1];
01035         block[b_stride]= backup[2];
01036         block[b_stride+1]= backup[3];
01037         return 0;
01038     }
01039 }
01040 
01041 static void iterative_me(SnowContext *s){
01042     int pass, mb_x, mb_y;
01043     const int b_width = s->b_width  << s->block_max_depth;
01044     const int b_height= s->b_height << s->block_max_depth;
01045     const int b_stride= b_width;
01046     int color[3];
01047 
01048     {
01049         RangeCoder r = s->c;
01050         uint8_t state[sizeof(s->block_state)];
01051         memcpy(state, s->block_state, sizeof(s->block_state));
01052         for(mb_y= 0; mb_y<s->b_height; mb_y++)
01053             for(mb_x= 0; mb_x<s->b_width; mb_x++)
01054                 encode_q_branch(s, 0, mb_x, mb_y);
01055         s->c = r;
01056         memcpy(s->block_state, state, sizeof(s->block_state));
01057     }
01058 
01059     for(pass=0; pass<25; pass++){
01060         int change= 0;
01061 
01062         for(mb_y= 0; mb_y<b_height; mb_y++){
01063             for(mb_x= 0; mb_x<b_width; mb_x++){
01064                 int dia_change, i, j, ref;
01065                 int best_rd= INT_MAX, ref_rd;
01066                 BlockNode backup, ref_b;
01067                 const int index= mb_x + mb_y * b_stride;
01068                 BlockNode *block= &s->block[index];
01069                 BlockNode *tb =                   mb_y            ? &s->block[index-b_stride  ] : NULL;
01070                 BlockNode *lb = mb_x                              ? &s->block[index         -1] : NULL;
01071                 BlockNode *rb = mb_x+1<b_width                    ? &s->block[index         +1] : NULL;
01072                 BlockNode *bb =                   mb_y+1<b_height ? &s->block[index+b_stride  ] : NULL;
01073                 BlockNode *tlb= mb_x           && mb_y            ? &s->block[index-b_stride-1] : NULL;
01074                 BlockNode *trb= mb_x+1<b_width && mb_y            ? &s->block[index-b_stride+1] : NULL;
01075                 BlockNode *blb= mb_x           && mb_y+1<b_height ? &s->block[index+b_stride-1] : NULL;
01076                 BlockNode *brb= mb_x+1<b_width && mb_y+1<b_height ? &s->block[index+b_stride+1] : NULL;
01077                 const int b_w= (MB_SIZE >> s->block_max_depth);
01078                 uint8_t obmc_edged[b_w*2][b_w*2];
01079 
01080                 if(pass && (block->type & BLOCK_OPT))
01081                     continue;
01082                 block->type |= BLOCK_OPT;
01083 
01084                 backup= *block;
01085 
01086                 if(!s->me_cache_generation)
01087                     memset(s->me_cache, 0, sizeof(s->me_cache));
01088                 s->me_cache_generation += 1<<22;
01089 
01090                 //FIXME precalculate
01091                 {
01092                     int x, y;
01093                     memcpy(obmc_edged, obmc_tab[s->block_max_depth], b_w*b_w*4);
01094                     if(mb_x==0)
01095                         for(y=0; y<b_w*2; y++)
01096                             memset(obmc_edged[y], obmc_edged[y][0] + obmc_edged[y][b_w-1], b_w);
01097                     if(mb_x==b_stride-1)
01098                         for(y=0; y<b_w*2; y++)
01099                             memset(obmc_edged[y]+b_w, obmc_edged[y][b_w] + obmc_edged[y][b_w*2-1], b_w);
01100                     if(mb_y==0){
01101                         for(x=0; x<b_w*2; x++)
01102                             obmc_edged[0][x] += obmc_edged[b_w-1][x];
01103                         for(y=1; y<b_w; y++)
01104                             memcpy(obmc_edged[y], obmc_edged[0], b_w*2);
01105                     }
01106                     if(mb_y==b_height-1){
01107                         for(x=0; x<b_w*2; x++)
01108                             obmc_edged[b_w*2-1][x] += obmc_edged[b_w][x];
01109                         for(y=b_w; y<b_w*2-1; y++)
01110                             memcpy(obmc_edged[y], obmc_edged[b_w*2-1], b_w*2);
01111                     }
01112                 }
01113 
01114                 //skip stuff outside the picture
01115                 if(mb_x==0 || mb_y==0 || mb_x==b_width-1 || mb_y==b_height-1){
01116                     uint8_t *src= s->  input_picture.data[0];
01117                     uint8_t *dst= s->current_picture.data[0];
01118                     const int stride= s->current_picture.linesize[0];
01119                     const int block_w= MB_SIZE >> s->block_max_depth;
01120                     const int sx= block_w*mb_x - block_w/2;
01121                     const int sy= block_w*mb_y - block_w/2;
01122                     const int w= s->plane[0].width;
01123                     const int h= s->plane[0].height;
01124                     int y;
01125 
01126                     for(y=sy; y<0; y++)
01127                         memcpy(dst + sx + y*stride, src + sx + y*stride, block_w*2);
01128                     for(y=h; y<sy+block_w*2; y++)
01129                         memcpy(dst + sx + y*stride, src + sx + y*stride, block_w*2);
01130                     if(sx<0){
01131                         for(y=sy; y<sy+block_w*2; y++)
01132                             memcpy(dst + sx + y*stride, src + sx + y*stride, -sx);
01133                     }
01134                     if(sx+block_w*2 > w){
01135                         for(y=sy; y<sy+block_w*2; y++)
01136                             memcpy(dst + w + y*stride, src + w + y*stride, sx+block_w*2 - w);
01137                     }
01138                 }
01139 
01140                 // intra(black) = neighbors' contribution to the current block
01141                 for(i=0; i<3; i++)
01142                     color[i]= get_dc(s, mb_x, mb_y, i);
01143 
01144                 // get previous score (cannot be cached due to OBMC)
01145                 if(pass > 0 && (block->type&BLOCK_INTRA)){
01146                     int color0[3]= {block->color[0], block->color[1], block->color[2]};
01147                     check_block(s, mb_x, mb_y, color0, 1, *obmc_edged, &best_rd);
01148                 }else
01149                     check_block_inter(s, mb_x, mb_y, block->mx, block->my, *obmc_edged, &best_rd);
01150 
01151                 ref_b= *block;
01152                 ref_rd= best_rd;
01153                 for(ref=0; ref < s->ref_frames; ref++){
01154                     int16_t (*mvr)[2]= &s->ref_mvs[ref][index];
01155                     if(s->ref_scores[ref][index] > s->ref_scores[ref_b.ref][index]*3/2) //FIXME tune threshold
01156                         continue;
01157                     block->ref= ref;
01158                     best_rd= INT_MAX;
01159 
01160                     check_block_inter(s, mb_x, mb_y, mvr[0][0], mvr[0][1], *obmc_edged, &best_rd);
01161                     check_block_inter(s, mb_x, mb_y, 0, 0, *obmc_edged, &best_rd);
01162                     if(tb)
01163                         check_block_inter(s, mb_x, mb_y, mvr[-b_stride][0], mvr[-b_stride][1], *obmc_edged, &best_rd);
01164                     if(lb)
01165                         check_block_inter(s, mb_x, mb_y, mvr[-1][0], mvr[-1][1], *obmc_edged, &best_rd);
01166                     if(rb)
01167                         check_block_inter(s, mb_x, mb_y, mvr[1][0], mvr[1][1], *obmc_edged, &best_rd);
01168                     if(bb)
01169                         check_block_inter(s, mb_x, mb_y, mvr[b_stride][0], mvr[b_stride][1], *obmc_edged, &best_rd);
01170 
01171                     /* fullpel ME */
01172                     //FIXME avoid subpel interpolation / round to nearest integer
01173                     do{
01174                         dia_change=0;
01175                         for(i=0; i<FFMAX(s->avctx->dia_size, 1); i++){
01176                             for(j=0; j<i; j++){
01177                                 dia_change |= check_block_inter(s, mb_x, mb_y, block->mx+4*(i-j), block->my+(4*j), *obmc_edged, &best_rd);
01178                                 dia_change |= check_block_inter(s, mb_x, mb_y, block->mx-4*(i-j), block->my-(4*j), *obmc_edged, &best_rd);
01179                                 dia_change |= check_block_inter(s, mb_x, mb_y, block->mx+4*(i-j), block->my-(4*j), *obmc_edged, &best_rd);
01180                                 dia_change |= check_block_inter(s, mb_x, mb_y, block->mx-4*(i-j), block->my+(4*j), *obmc_edged, &best_rd);
01181                             }
01182                         }
01183                     }while(dia_change);
01184                     /* subpel ME */
01185                     do{
01186                         static const int square[8][2]= {{+1, 0},{-1, 0},{ 0,+1},{ 0,-1},{+1,+1},{-1,-1},{+1,-1},{-1,+1},};
01187                         dia_change=0;
01188                         for(i=0; i<8; i++)
01189                             dia_change |= check_block_inter(s, mb_x, mb_y, block->mx+square[i][0], block->my+square[i][1], *obmc_edged, &best_rd);
01190                     }while(dia_change);
01191                     //FIXME or try the standard 2 pass qpel or similar
01192 
01193                     mvr[0][0]= block->mx;
01194                     mvr[0][1]= block->my;
01195                     if(ref_rd > best_rd){
01196                         ref_rd= best_rd;
01197                         ref_b= *block;
01198                     }
01199                 }
01200                 best_rd= ref_rd;
01201                 *block= ref_b;
01202                 check_block(s, mb_x, mb_y, color, 1, *obmc_edged, &best_rd);
01203                 //FIXME RD style color selection
01204                 if(!same_block(block, &backup)){
01205                     if(tb ) tb ->type &= ~BLOCK_OPT;
01206                     if(lb ) lb ->type &= ~BLOCK_OPT;
01207                     if(rb ) rb ->type &= ~BLOCK_OPT;
01208                     if(bb ) bb ->type &= ~BLOCK_OPT;
01209                     if(tlb) tlb->type &= ~BLOCK_OPT;
01210                     if(trb) trb->type &= ~BLOCK_OPT;
01211                     if(blb) blb->type &= ~BLOCK_OPT;
01212                     if(brb) brb->type &= ~BLOCK_OPT;
01213                     change ++;
01214                 }
01215             }
01216         }
01217         av_log(s->avctx, AV_LOG_ERROR, "pass:%d changed:%d\n", pass, change);
01218         if(!change)
01219             break;
01220     }
01221 
01222     if(s->block_max_depth == 1){
01223         int change= 0;
01224         for(mb_y= 0; mb_y<b_height; mb_y+=2){
01225             for(mb_x= 0; mb_x<b_width; mb_x+=2){
01226                 int i;
01227                 int best_rd, init_rd;
01228                 const int index= mb_x + mb_y * b_stride;
01229                 BlockNode *b[4];
01230 
01231                 b[0]= &s->block[index];
01232                 b[1]= b[0]+1;
01233                 b[2]= b[0]+b_stride;
01234                 b[3]= b[2]+1;
01235                 if(same_block(b[0], b[1]) &&
01236                    same_block(b[0], b[2]) &&
01237                    same_block(b[0], b[3]))
01238                     continue;
01239 
01240                 if(!s->me_cache_generation)
01241                     memset(s->me_cache, 0, sizeof(s->me_cache));
01242                 s->me_cache_generation += 1<<22;
01243 
01244                 init_rd= best_rd= get_4block_rd(s, mb_x, mb_y, 0);
01245 
01246                 //FIXME more multiref search?
01247                 check_4block_inter(s, mb_x, mb_y,
01248                                    (b[0]->mx + b[1]->mx + b[2]->mx + b[3]->mx + 2) >> 2,
01249                                    (b[0]->my + b[1]->my + b[2]->my + b[3]->my + 2) >> 2, 0, &best_rd);
01250 
01251                 for(i=0; i<4; i++)
01252                     if(!(b[i]->type&BLOCK_INTRA))
01253                         check_4block_inter(s, mb_x, mb_y, b[i]->mx, b[i]->my, b[i]->ref, &best_rd);
01254 
01255                 if(init_rd != best_rd)
01256                     change++;
01257             }
01258         }
01259         av_log(s->avctx, AV_LOG_ERROR, "pass:4mv changed:%d\n", change*4);
01260     }
01261 }
01262 
01263 static void encode_blocks(SnowContext *s, int search){
01264     int x, y;
01265     int w= s->b_width;
01266     int h= s->b_height;
01267 
01268     if(s->avctx->me_method == ME_ITER && !s->keyframe && search)
01269         iterative_me(s);
01270 
01271     for(y=0; y<h; y++){
01272         if(s->c.bytestream_end - s->c.bytestream < w*MB_SIZE*MB_SIZE*3){ //FIXME nicer limit
01273             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
01274             return;
01275         }
01276         for(x=0; x<w; x++){
01277             if(s->avctx->me_method == ME_ITER || !search)
01278                 encode_q_branch2(s, 0, x, y);
01279             else
01280                 encode_q_branch (s, 0, x, y);
01281         }
01282     }
01283 }
01284 
01285 static void quantize(SnowContext *s, SubBand *b, IDWTELEM *dst, DWTELEM *src, int stride, int bias){
01286     const int w= b->width;
01287     const int h= b->height;
01288     const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);
01289     const int qmul= qexp[qlog&(QROOT-1)]<<((qlog>>QSHIFT) + ENCODER_EXTRA_BITS);
01290     int x,y, thres1, thres2;
01291 
01292     if(s->qlog == LOSSLESS_QLOG){
01293         for(y=0; y<h; y++)
01294             for(x=0; x<w; x++)
01295                 dst[x + y*stride]= src[x + y*stride];
01296         return;
01297     }
01298 
01299     bias= bias ? 0 : (3*qmul)>>3;
01300     thres1= ((qmul - bias)>>QEXPSHIFT) - 1;
01301     thres2= 2*thres1;
01302 
01303     if(!bias){
01304         for(y=0; y<h; y++){
01305             for(x=0; x<w; x++){
01306                 int i= src[x + y*stride];
01307 
01308                 if((unsigned)(i+thres1) > thres2){
01309                     if(i>=0){
01310                         i<<= QEXPSHIFT;
01311                         i/= qmul; //FIXME optimize
01312                         dst[x + y*stride]=  i;
01313                     }else{
01314                         i= -i;
01315                         i<<= QEXPSHIFT;
01316                         i/= qmul; //FIXME optimize
01317                         dst[x + y*stride]= -i;
01318                     }
01319                 }else
01320                     dst[x + y*stride]= 0;
01321             }
01322         }
01323     }else{
01324         for(y=0; y<h; y++){
01325             for(x=0; x<w; x++){
01326                 int i= src[x + y*stride];
01327 
01328                 if((unsigned)(i+thres1) > thres2){
01329                     if(i>=0){
01330                         i<<= QEXPSHIFT;
01331                         i= (i + bias) / qmul; //FIXME optimize
01332                         dst[x + y*stride]=  i;
01333                     }else{
01334                         i= -i;
01335                         i<<= QEXPSHIFT;
01336                         i= (i + bias) / qmul; //FIXME optimize
01337                         dst[x + y*stride]= -i;
01338                     }
01339                 }else
01340                     dst[x + y*stride]= 0;
01341             }
01342         }
01343     }
01344 }
01345 
01346 static void dequantize(SnowContext *s, SubBand *b, IDWTELEM *src, int stride){
01347     const int w= b->width;
01348     const int h= b->height;
01349     const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);
01350     const int qmul= qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);
01351     const int qadd= (s->qbias*qmul)>>QBIAS_SHIFT;
01352     int x,y;
01353 
01354     if(s->qlog == LOSSLESS_QLOG) return;
01355 
01356     for(y=0; y<h; y++){
01357         for(x=0; x<w; x++){
01358             int i= src[x + y*stride];
01359             if(i<0){
01360                 src[x + y*stride]= -((-i*qmul + qadd)>>(QEXPSHIFT)); //FIXME try different bias
01361             }else if(i>0){
01362                 src[x + y*stride]=  (( i*qmul + qadd)>>(QEXPSHIFT));
01363             }
01364         }
01365     }
01366 }
01367 
01368 static void decorrelate(SnowContext *s, SubBand *b, IDWTELEM *src, int stride, int inverse, int use_median){
01369     const int w= b->width;
01370     const int h= b->height;
01371     int x,y;
01372 
01373     for(y=h-1; y>=0; y--){
01374         for(x=w-1; x>=0; x--){
01375             int i= x + y*stride;
01376 
01377             if(x){
01378                 if(use_median){
01379                     if(y && x+1<w) src[i] -= mid_pred(src[i - 1], src[i - stride], src[i - stride + 1]);
01380                     else  src[i] -= src[i - 1];
01381                 }else{
01382                     if(y) src[i] -= mid_pred(src[i - 1], src[i - stride], src[i - 1] + src[i - stride] - src[i - 1 - stride]);
01383                     else  src[i] -= src[i - 1];
01384                 }
01385             }else{
01386                 if(y) src[i] -= src[i - stride];
01387             }
01388         }
01389     }
01390 }
01391 
01392 static void correlate(SnowContext *s, SubBand *b, IDWTELEM *src, int stride, int inverse, int use_median){
01393     const int w= b->width;
01394     const int h= b->height;
01395     int x,y;
01396 
01397     for(y=0; y<h; y++){
01398         for(x=0; x<w; x++){
01399             int i= x + y*stride;
01400 
01401             if(x){
01402                 if(use_median){
01403                     if(y && x+1<w) src[i] += mid_pred(src[i - 1], src[i - stride], src[i - stride + 1]);
01404                     else  src[i] += src[i - 1];
01405                 }else{
01406                     if(y) src[i] += mid_pred(src[i - 1], src[i - stride], src[i - 1] + src[i - stride] - src[i - 1 - stride]);
01407                     else  src[i] += src[i - 1];
01408                 }
01409             }else{
01410                 if(y) src[i] += src[i - stride];
01411             }
01412         }
01413     }
01414 }
01415 
01416 static void encode_qlogs(SnowContext *s){
01417     int plane_index, level, orientation;
01418 
01419     for(plane_index=0; plane_index<2; plane_index++){
01420         for(level=0; level<s->spatial_decomposition_count; level++){
01421             for(orientation=level ? 1:0; orientation<4; orientation++){
01422                 if(orientation==2) continue;
01423                 put_symbol(&s->c, s->header_state, s->plane[plane_index].band[level][orientation].qlog, 1);
01424             }
01425         }
01426     }
01427 }
01428 
01429 static void encode_header(SnowContext *s){
01430     int plane_index, i;
01431     uint8_t kstate[32];
01432 
01433     memset(kstate, MID_STATE, sizeof(kstate));
01434 
01435     put_rac(&s->c, kstate, s->keyframe);
01436     if(s->keyframe || s->always_reset){
01437         ff_snow_reset_contexts(s);
01438         s->last_spatial_decomposition_type=
01439         s->last_qlog=
01440         s->last_qbias=
01441         s->last_mv_scale=
01442         s->last_block_max_depth= 0;
01443         for(plane_index=0; plane_index<2; plane_index++){
01444             Plane *p= &s->plane[plane_index];
01445             p->last_htaps=0;
01446             p->last_diag_mc=0;
01447             memset(p->last_hcoeff, 0, sizeof(p->last_hcoeff));
01448         }
01449     }
01450     if(s->keyframe){
01451         put_symbol(&s->c, s->header_state, s->version, 0);
01452         put_rac(&s->c, s->header_state, s->always_reset);
01453         put_symbol(&s->c, s->header_state, s->temporal_decomposition_type, 0);
01454         put_symbol(&s->c, s->header_state, s->temporal_decomposition_count, 0);
01455         put_symbol(&s->c, s->header_state, s->spatial_decomposition_count, 0);
01456         put_symbol(&s->c, s->header_state, s->colorspace_type, 0);
01457         put_symbol(&s->c, s->header_state, s->chroma_h_shift, 0);
01458         put_symbol(&s->c, s->header_state, s->chroma_v_shift, 0);
01459         put_rac(&s->c, s->header_state, s->spatial_scalability);
01460 //        put_rac(&s->c, s->header_state, s->rate_scalability);
01461         put_symbol(&s->c, s->header_state, s->max_ref_frames-1, 0);
01462 
01463         encode_qlogs(s);
01464     }
01465 
01466     if(!s->keyframe){
01467         int update_mc=0;
01468         for(plane_index=0; plane_index<2; plane_index++){
01469             Plane *p= &s->plane[plane_index];
01470             update_mc |= p->last_htaps   != p->htaps;
01471             update_mc |= p->last_diag_mc != p->diag_mc;
01472             update_mc |= !!memcmp(p->last_hcoeff, p->hcoeff, sizeof(p->hcoeff));
01473         }
01474         put_rac(&s->c, s->header_state, update_mc);
01475         if(update_mc){
01476             for(plane_index=0; plane_index<2; plane_index++){
01477                 Plane *p= &s->plane[plane_index];
01478                 put_rac(&s->c, s->header_state, p->diag_mc);
01479                 put_symbol(&s->c, s->header_state, p->htaps/2-1, 0);
01480                 for(i= p->htaps/2; i; i--)
01481                     put_symbol(&s->c, s->header_state, FFABS(p->hcoeff[i]), 0);
01482             }
01483         }
01484         if(s->last_spatial_decomposition_count != s->spatial_decomposition_count){
01485             put_rac(&s->c, s->header_state, 1);
01486             put_symbol(&s->c, s->header_state, s->spatial_decomposition_count, 0);
01487             encode_qlogs(s);
01488         }else
01489             put_rac(&s->c, s->header_state, 0);
01490     }
01491 
01492     put_symbol(&s->c, s->header_state, s->spatial_decomposition_type - s->last_spatial_decomposition_type, 1);
01493     put_symbol(&s->c, s->header_state, s->qlog            - s->last_qlog    , 1);
01494     put_symbol(&s->c, s->header_state, s->mv_scale        - s->last_mv_scale, 1);
01495     put_symbol(&s->c, s->header_state, s->qbias           - s->last_qbias   , 1);
01496     put_symbol(&s->c, s->header_state, s->block_max_depth - s->last_block_max_depth, 1);
01497 
01498 }
01499 
01500 static void update_last_header_values(SnowContext *s){
01501     int plane_index;
01502 
01503     if(!s->keyframe){
01504         for(plane_index=0; plane_index<2; plane_index++){
01505             Plane *p= &s->plane[plane_index];
01506             p->last_diag_mc= p->diag_mc;
01507             p->last_htaps  = p->htaps;
01508             memcpy(p->last_hcoeff, p->hcoeff, sizeof(p->hcoeff));
01509         }
01510     }
01511 
01512     s->last_spatial_decomposition_type  = s->spatial_decomposition_type;
01513     s->last_qlog                        = s->qlog;
01514     s->last_qbias                       = s->qbias;
01515     s->last_mv_scale                    = s->mv_scale;
01516     s->last_block_max_depth             = s->block_max_depth;
01517     s->last_spatial_decomposition_count = s->spatial_decomposition_count;
01518 }
01519 
01520 static int qscale2qlog(int qscale){
01521     return rint(QROOT*log(qscale / (float)FF_QP2LAMBDA)/log(2))
01522            + 61*QROOT/8; 
01523 }
01524 
01525 static int ratecontrol_1pass(SnowContext *s, AVFrame *pict)
01526 {
01527     /* Estimate the frame's complexity as a sum of weighted dwt coefficients.
01528      * FIXME we know exact mv bits at this point,
01529      * but ratecontrol isn't set up to include them. */
01530     uint32_t coef_sum= 0;
01531     int level, orientation, delta_qlog;
01532 
01533     for(level=0; level<s->spatial_decomposition_count; level++){
01534         for(orientation=level ? 1 : 0; orientation<4; orientation++){
01535             SubBand *b= &s->plane[0].band[level][orientation];
01536             IDWTELEM *buf= b->ibuf;
01537             const int w= b->width;
01538             const int h= b->height;
01539             const int stride= b->stride;
01540             const int qlog= av_clip(2*QROOT + b->qlog, 0, QROOT*16);
01541             const int qmul= qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);
01542             const int qdiv= (1<<16)/qmul;
01543             int x, y;
01544             //FIXME this is ugly
01545             for(y=0; y<h; y++)
01546                 for(x=0; x<w; x++)
01547                     buf[x+y*stride]= b->buf[x+y*stride];
01548             if(orientation==0)
01549                 decorrelate(s, b, buf, stride, 1, 0);
01550             for(y=0; y<h; y++)
01551                 for(x=0; x<w; x++)
01552                     coef_sum+= abs(buf[x+y*stride]) * qdiv >> 16;
01553         }
01554     }
01555 
01556     /* ugly, ratecontrol just takes a sqrt again */
01557     coef_sum = (uint64_t)coef_sum * coef_sum >> 16;
01558     assert(coef_sum < INT_MAX);
01559 
01560     if(pict->pict_type == AV_PICTURE_TYPE_I){
01561         s->m.current_picture.mb_var_sum= coef_sum;
01562         s->m.current_picture.mc_mb_var_sum= 0;
01563     }else{
01564         s->m.current_picture.mc_mb_var_sum= coef_sum;
01565         s->m.current_picture.mb_var_sum= 0;
01566     }
01567 
01568     pict->quality= ff_rate_estimate_qscale(&s->m, 1);
01569     if (pict->quality < 0)
01570         return INT_MIN;
01571     s->lambda= pict->quality * 3/2;
01572     delta_qlog= qscale2qlog(pict->quality) - s->qlog;
01573     s->qlog+= delta_qlog;
01574     return delta_qlog;
01575 }
01576 
01577 static void calculate_visual_weight(SnowContext *s, Plane *p){
01578     int width = p->width;
01579     int height= p->height;
01580     int level, orientation, x, y;
01581 
01582     for(level=0; level<s->spatial_decomposition_count; level++){
01583         for(orientation=level ? 1 : 0; orientation<4; orientation++){
01584             SubBand *b= &p->band[level][orientation];
01585             IDWTELEM *ibuf= b->ibuf;
01586             int64_t error=0;
01587 
01588             memset(s->spatial_idwt_buffer, 0, sizeof(*s->spatial_idwt_buffer)*width*height);
01589             ibuf[b->width/2 + b->height/2*b->stride]= 256*16;
01590             ff_spatial_idwt(s->spatial_idwt_buffer, width, height, width, s->spatial_decomposition_type, s->spatial_decomposition_count);
01591             for(y=0; y<height; y++){
01592                 for(x=0; x<width; x++){
01593                     int64_t d= s->spatial_idwt_buffer[x + y*width]*16;
01594                     error += d*d;
01595                 }
01596             }
01597 
01598             b->qlog= (int)(log(352256.0/sqrt(error)) / log(pow(2.0, 1.0/QROOT))+0.5);
01599         }
01600     }
01601 }
01602 
01603 static int encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){
01604     SnowContext *s = avctx->priv_data;
01605     RangeCoder * const c= &s->c;
01606     AVFrame *pict = data;
01607     const int width= s->avctx->width;
01608     const int height= s->avctx->height;
01609     int level, orientation, plane_index, i, y;
01610     uint8_t rc_header_bak[sizeof(s->header_state)];
01611     uint8_t rc_block_bak[sizeof(s->block_state)];
01612 
01613     ff_init_range_encoder(c, buf, buf_size);
01614     ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
01615 
01616     for(i=0; i<3; i++){
01617         int shift= !!i;
01618         for(y=0; y<(height>>shift); y++)
01619             memcpy(&s->input_picture.data[i][y * s->input_picture.linesize[i]],
01620                    &pict->data[i][y * pict->linesize[i]],
01621                    width>>shift);
01622     }
01623     s->new_picture = *pict;
01624 
01625     s->m.picture_number= avctx->frame_number;
01626     if(avctx->flags&CODEC_FLAG_PASS2){
01627         s->m.pict_type =
01628         pict->pict_type= s->m.rc_context.entry[avctx->frame_number].new_pict_type;
01629         s->keyframe= pict->pict_type==AV_PICTURE_TYPE_I;
01630         if(!(avctx->flags&CODEC_FLAG_QSCALE)) {
01631             pict->quality= ff_rate_estimate_qscale(&s->m, 0);
01632             if (pict->quality < 0)
01633                 return -1;
01634         }
01635     }else{
01636         s->keyframe= avctx->gop_size==0 || avctx->frame_number % avctx->gop_size == 0;
01637         s->m.pict_type=
01638         pict->pict_type= s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
01639     }
01640 
01641     if(s->pass1_rc && avctx->frame_number == 0)
01642         pict->quality= 2*FF_QP2LAMBDA;
01643     if(pict->quality){
01644         s->qlog= qscale2qlog(pict->quality);
01645         s->lambda = pict->quality * 3/2;
01646     }
01647     if(s->qlog < 0 || (!pict->quality && (avctx->flags & CODEC_FLAG_QSCALE))){
01648         s->qlog= LOSSLESS_QLOG;
01649         s->lambda = 0;
01650     }//else keep previous frame's qlog until after motion estimation
01651 
01652     ff_snow_frame_start(s);
01653 
01654     s->m.current_picture_ptr= &s->m.current_picture;
01655     s->m.last_picture.f.pts = s->m.current_picture.f.pts;
01656     s->m.current_picture.f.pts = pict->pts;
01657     if(pict->pict_type == AV_PICTURE_TYPE_P){
01658         int block_width = (width +15)>>4;
01659         int block_height= (height+15)>>4;
01660         int stride= s->current_picture.linesize[0];
01661 
01662         assert(s->current_picture.data[0]);
01663         assert(s->last_picture[0].data[0]);
01664 
01665         s->m.avctx= s->avctx;
01666         s->m.current_picture.f.data[0] = s->current_picture.data[0];
01667         s->m.   last_picture.f.data[0] = s->last_picture[0].data[0];
01668         s->m.    new_picture.f.data[0] = s->  input_picture.data[0];
01669         s->m.   last_picture_ptr= &s->m.   last_picture;
01670         s->m.linesize=
01671         s->m.   last_picture.f.linesize[0] =
01672         s->m.    new_picture.f.linesize[0] =
01673         s->m.current_picture.f.linesize[0] = stride;
01674         s->m.uvlinesize= s->current_picture.linesize[1];
01675         s->m.width = width;
01676         s->m.height= height;
01677         s->m.mb_width = block_width;
01678         s->m.mb_height= block_height;
01679         s->m.mb_stride=   s->m.mb_width+1;
01680         s->m.b8_stride= 2*s->m.mb_width+1;
01681         s->m.f_code=1;
01682         s->m.pict_type= pict->pict_type;
01683         s->m.me_method= s->avctx->me_method;
01684         s->m.me.scene_change_score=0;
01685         s->m.flags= s->avctx->flags;
01686         s->m.quarter_sample= (s->avctx->flags & CODEC_FLAG_QPEL)!=0;
01687         s->m.out_format= FMT_H263;
01688         s->m.unrestricted_mv= 1;
01689 
01690         s->m.lambda = s->lambda;
01691         s->m.qscale= (s->m.lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
01692         s->lambda2= s->m.lambda2= (s->m.lambda*s->m.lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
01693 
01694         s->m.dsp= s->dsp; //move
01695         ff_init_me(&s->m);
01696         s->dsp= s->m.dsp;
01697     }
01698 
01699     if(s->pass1_rc){
01700         memcpy(rc_header_bak, s->header_state, sizeof(s->header_state));
01701         memcpy(rc_block_bak, s->block_state, sizeof(s->block_state));
01702     }
01703 
01704 redo_frame:
01705 
01706     if(pict->pict_type == AV_PICTURE_TYPE_I)
01707         s->spatial_decomposition_count= 5;
01708     else
01709         s->spatial_decomposition_count= 5;
01710 
01711     s->m.pict_type = pict->pict_type;
01712     s->qbias= pict->pict_type == AV_PICTURE_TYPE_P ? 2 : 0;
01713 
01714     ff_snow_common_init_after_header(avctx);
01715 
01716     if(s->last_spatial_decomposition_count != s->spatial_decomposition_count){
01717         for(plane_index=0; plane_index<3; plane_index++){
01718             calculate_visual_weight(s, &s->plane[plane_index]);
01719         }
01720     }
01721 
01722     encode_header(s);
01723     s->m.misc_bits = 8*(s->c.bytestream - s->c.bytestream_start);
01724     encode_blocks(s, 1);
01725     s->m.mv_bits = 8*(s->c.bytestream - s->c.bytestream_start) - s->m.misc_bits;
01726 
01727     for(plane_index=0; plane_index<3; plane_index++){
01728         Plane *p= &s->plane[plane_index];
01729         int w= p->width;
01730         int h= p->height;
01731         int x, y;
01732 //        int bits= put_bits_count(&s->c.pb);
01733 
01734         if (!s->memc_only) {
01735             //FIXME optimize
01736             if(pict->data[plane_index]) //FIXME gray hack
01737                 for(y=0; y<h; y++){
01738                     for(x=0; x<w; x++){
01739                         s->spatial_idwt_buffer[y*w + x]= pict->data[plane_index][y*pict->linesize[plane_index] + x]<<FRAC_BITS;
01740                     }
01741                 }
01742             predict_plane(s, s->spatial_idwt_buffer, plane_index, 0);
01743 
01744             if(   plane_index==0
01745                && pict->pict_type == AV_PICTURE_TYPE_P
01746                && !(avctx->flags&CODEC_FLAG_PASS2)
01747                && s->m.me.scene_change_score > s->avctx->scenechange_threshold){
01748                 ff_init_range_encoder(c, buf, buf_size);
01749                 ff_build_rac_states(c, 0.05*(1LL<<32), 256-8);
01750                 pict->pict_type= AV_PICTURE_TYPE_I;
01751                 s->keyframe=1;
01752                 s->current_picture.key_frame=1;
01753                 goto redo_frame;
01754             }
01755 
01756             if(s->qlog == LOSSLESS_QLOG){
01757                 for(y=0; y<h; y++){
01758                     for(x=0; x<w; x++){
01759                         s->spatial_dwt_buffer[y*w + x]= (s->spatial_idwt_buffer[y*w + x] + (1<<(FRAC_BITS-1))-1)>>FRAC_BITS;
01760                     }
01761                 }
01762             }else{
01763                 for(y=0; y<h; y++){
01764                     for(x=0; x<w; x++){
01765                         s->spatial_dwt_buffer[y*w + x]=s->spatial_idwt_buffer[y*w + x]<<ENCODER_EXTRA_BITS;
01766                     }
01767                 }
01768             }
01769 
01770             /*  if(QUANTIZE2)
01771                 dwt_quantize(s, p, s->spatial_dwt_buffer, w, h, w, s->spatial_decomposition_type);
01772             else*/
01773                 ff_spatial_dwt(s->spatial_dwt_buffer, w, h, w, s->spatial_decomposition_type, s->spatial_decomposition_count);
01774 
01775             if(s->pass1_rc && plane_index==0){
01776                 int delta_qlog = ratecontrol_1pass(s, pict);
01777                 if (delta_qlog <= INT_MIN)
01778                     return -1;
01779                 if(delta_qlog){
01780                     //reordering qlog in the bitstream would eliminate this reset
01781                     ff_init_range_encoder(c, buf, buf_size);
01782                     memcpy(s->header_state, rc_header_bak, sizeof(s->header_state));
01783                     memcpy(s->block_state, rc_block_bak, sizeof(s->block_state));
01784                     encode_header(s);
01785                     encode_blocks(s, 0);
01786                 }
01787             }
01788 
01789             for(level=0; level<s->spatial_decomposition_count; level++){
01790                 for(orientation=level ? 1 : 0; orientation<4; orientation++){
01791                     SubBand *b= &p->band[level][orientation];
01792 
01793                     if(!QUANTIZE2)
01794                         quantize(s, b, b->ibuf, b->buf, b->stride, s->qbias);
01795                     if(orientation==0)
01796                         decorrelate(s, b, b->ibuf, b->stride, pict->pict_type == AV_PICTURE_TYPE_P, 0);
01797                     encode_subband(s, b, b->ibuf, b->parent ? b->parent->ibuf : NULL, b->stride, orientation);
01798                     assert(b->parent==NULL || b->parent->stride == b->stride*2);
01799                     if(orientation==0)
01800                         correlate(s, b, b->ibuf, b->stride, 1, 0);
01801                 }
01802             }
01803 
01804             for(level=0; level<s->spatial_decomposition_count; level++){
01805                 for(orientation=level ? 1 : 0; orientation<4; orientation++){
01806                     SubBand *b= &p->band[level][orientation];
01807 
01808                     dequantize(s, b, b->ibuf, b->stride);
01809                 }
01810             }
01811 
01812             ff_spatial_idwt(s->spatial_idwt_buffer, w, h, w, s->spatial_decomposition_type, s->spatial_decomposition_count);
01813             if(s->qlog == LOSSLESS_QLOG){
01814                 for(y=0; y<h; y++){
01815                     for(x=0; x<w; x++){
01816                         s->spatial_idwt_buffer[y*w + x]<<=FRAC_BITS;
01817                     }
01818                 }
01819             }
01820             predict_plane(s, s->spatial_idwt_buffer, plane_index, 1);
01821         }else{
01822             //ME/MC only
01823             if(pict->pict_type == AV_PICTURE_TYPE_I){
01824                 for(y=0; y<h; y++){
01825                     for(x=0; x<w; x++){
01826                         s->current_picture.data[plane_index][y*s->current_picture.linesize[plane_index] + x]=
01827                             pict->data[plane_index][y*pict->linesize[plane_index] + x];
01828                     }
01829                 }
01830             }else{
01831                 memset(s->spatial_idwt_buffer, 0, sizeof(IDWTELEM)*w*h);
01832                 predict_plane(s, s->spatial_idwt_buffer, plane_index, 1);
01833             }
01834         }
01835         if(s->avctx->flags&CODEC_FLAG_PSNR){
01836             int64_t error= 0;
01837 
01838             if(pict->data[plane_index]) //FIXME gray hack
01839                 for(y=0; y<h; y++){
01840                     for(x=0; x<w; x++){
01841                         int d= s->current_picture.data[plane_index][y*s->current_picture.linesize[plane_index] + x] - pict->data[plane_index][y*pict->linesize[plane_index] + x];
01842                         error += d*d;
01843                     }
01844                 }
01845             s->avctx->error[plane_index] += error;
01846             s->current_picture.error[plane_index] = error;
01847         }
01848 
01849     }
01850 
01851     update_last_header_values(s);
01852 
01853     ff_snow_release_buffer(avctx);
01854 
01855     s->current_picture.coded_picture_number = avctx->frame_number;
01856     s->current_picture.pict_type = pict->pict_type;
01857     s->current_picture.quality = pict->quality;
01858     s->m.frame_bits = 8*(s->c.bytestream - s->c.bytestream_start);
01859     s->m.p_tex_bits = s->m.frame_bits - s->m.misc_bits - s->m.mv_bits;
01860     s->m.current_picture.f.display_picture_number =
01861     s->m.current_picture.f.coded_picture_number   = avctx->frame_number;
01862     s->m.current_picture.f.quality                = pict->quality;
01863     s->m.total_bits += 8*(s->c.bytestream - s->c.bytestream_start);
01864     if(s->pass1_rc)
01865         if (ff_rate_estimate_qscale(&s->m, 0) < 0)
01866             return -1;
01867     if(avctx->flags&CODEC_FLAG_PASS1)
01868         ff_write_pass1_stats(&s->m);
01869     s->m.last_pict_type = s->m.pict_type;
01870     avctx->frame_bits = s->m.frame_bits;
01871     avctx->mv_bits = s->m.mv_bits;
01872     avctx->misc_bits = s->m.misc_bits;
01873     avctx->p_tex_bits = s->m.p_tex_bits;
01874 
01875     emms_c();
01876 
01877     return ff_rac_terminate(c);
01878 }
01879 
01880 static av_cold int encode_end(AVCodecContext *avctx)
01881 {
01882     SnowContext *s = avctx->priv_data;
01883 
01884     ff_snow_common_end(s);
01885     if (s->input_picture.data[0])
01886         avctx->release_buffer(avctx, &s->input_picture);
01887     av_free(avctx->stats_out);
01888 
01889     return 0;
01890 }
01891 
01892 #define OFFSET(x) offsetof(SnowContext, x)
01893 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
01894 static const AVOption options[] = {
01895     { "memc_only",      "Only do ME/MC (I frames -> ref, P frame -> ME+MC).",   OFFSET(memc_only), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
01896     { NULL },
01897 };
01898 
01899 static const AVClass snowenc_class = {
01900     .class_name = "snow encoder",
01901     .item_name  = av_default_item_name,
01902     .option     = options,
01903     .version    = LIBAVUTIL_VERSION_INT,
01904 };
01905 
01906 AVCodec ff_snow_encoder = {
01907     .name           = "snow",
01908     .type           = AVMEDIA_TYPE_VIDEO,
01909     .id             = CODEC_ID_SNOW,
01910     .priv_data_size = sizeof(SnowContext),
01911     .init           = encode_init,
01912     .encode         = encode_frame,
01913     .close          = encode_end,
01914     .long_name = NULL_IF_CONFIG_SMALL("Snow"),
01915     .priv_class     = &snowenc_class,
01916 };
01917 #endif
Generated on Sun Apr 22 2012 21:54:04 for Libav by doxygen 1.7.1