]> git.sesse.net Git - ffmpeg/blob - libavcodec/snowenc.c
Merge commit 'bf58545aace7d14522ce4fa680c7b3ff62109a3a'
[ffmpeg] / libavcodec / snowenc.c
1 /*
2  * Copyright (C) 2004 Michael Niedermayer <michaelni@gmx.at>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavutil/intmath.h"
22 #include "libavutil/libm.h"
23 #include "libavutil/log.h"
24 #include "libavutil/opt.h"
25 #include "avcodec.h"
26 #include "internal.h"
27 #include "snow_dwt.h"
28 #include "snow.h"
29
30 #include "rangecoder.h"
31 #include "mathops.h"
32
33 #include "mpegvideo.h"
34 #include "h263.h"
35
36 #define FF_ME_ITER 50
37
38 static av_cold int encode_init(AVCodecContext *avctx)
39 {
40     SnowContext *s = avctx->priv_data;
41     int plane_index, ret;
42     int i;
43
44 #if FF_API_PRIVATE_OPT
45 FF_DISABLE_DEPRECATION_WARNINGS
46     if (avctx->prediction_method)
47         s->pred = avctx->prediction_method;
48 FF_ENABLE_DEPRECATION_WARNINGS
49 #endif
50
51     if(s->pred == DWT_97
52        && (avctx->flags & AV_CODEC_FLAG_QSCALE)
53        && avctx->global_quality == 0){
54         av_log(avctx, AV_LOG_ERROR, "The 9/7 wavelet is incompatible with lossless mode.\n");
55         return -1;
56     }
57 #if FF_API_MOTION_EST
58 FF_DISABLE_DEPRECATION_WARNINGS
59     if (avctx->me_method == ME_ITER)
60         s->motion_est = FF_ME_ITER;
61 FF_ENABLE_DEPRECATION_WARNINGS
62 #endif
63
64     s->spatial_decomposition_type= s->pred; //FIXME add decorrelator type r transform_type
65
66     s->mv_scale       = (avctx->flags & AV_CODEC_FLAG_QPEL) ? 2 : 4;
67     s->block_max_depth= (avctx->flags & AV_CODEC_FLAG_4MV ) ? 1 : 0;
68
69     for(plane_index=0; plane_index<3; plane_index++){
70         s->plane[plane_index].diag_mc= 1;
71         s->plane[plane_index].htaps= 6;
72         s->plane[plane_index].hcoeff[0]=  40;
73         s->plane[plane_index].hcoeff[1]= -10;
74         s->plane[plane_index].hcoeff[2]=   2;
75         s->plane[plane_index].fast_mc= 1;
76     }
77
78     if ((ret = ff_snow_common_init(avctx)) < 0) {
79         return ret;
80     }
81     ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);
82
83     ff_snow_alloc_blocks(s);
84
85     s->version=0;
86
87     s->m.avctx   = avctx;
88     s->m.bit_rate= avctx->bit_rate;
89
90     s->m.me.temp      =
91     s->m.me.scratchpad= av_mallocz_array((avctx->width+64), 2*16*2*sizeof(uint8_t));
92     s->m.me.map       = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
93     s->m.me.score_map = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
94     s->m.sc.obmc_scratchpad= av_mallocz(MB_SIZE*MB_SIZE*12*sizeof(uint32_t));
95     if (!s->m.me.scratchpad || !s->m.me.map || !s->m.me.score_map || !s->m.sc.obmc_scratchpad)
96         return AVERROR(ENOMEM);
97
98     ff_h263_encode_init(&s->m); //mv_penalty
99
100     s->max_ref_frames = av_clip(avctx->refs, 1, MAX_REF_FRAMES);
101
102     if(avctx->flags&AV_CODEC_FLAG_PASS1){
103         if(!avctx->stats_out)
104             avctx->stats_out = av_mallocz(256);
105
106         if (!avctx->stats_out)
107             return AVERROR(ENOMEM);
108     }
109     if((avctx->flags&AV_CODEC_FLAG_PASS2) || !(avctx->flags&CODEC_FLAG_QSCALE)){
110         if(ff_rate_control_init(&s->m) < 0)
111             return -1;
112     }
113     s->pass1_rc= !(avctx->flags & (AV_CODEC_FLAG_QSCALE|CODEC_FLAG_PASS2));
114
115     switch(avctx->pix_fmt){
116     case AV_PIX_FMT_YUV444P:
117 //    case AV_PIX_FMT_YUV422P:
118     case AV_PIX_FMT_YUV420P:
119 //    case AV_PIX_FMT_YUV411P:
120     case AV_PIX_FMT_YUV410P:
121         s->nb_planes = 3;
122         s->colorspace_type= 0;
123         break;
124     case AV_PIX_FMT_GRAY8:
125         s->nb_planes = 1;
126         s->colorspace_type = 1;
127         break;
128 /*    case AV_PIX_FMT_RGB32:
129         s->colorspace= 1;
130         break;*/
131     default:
132         av_log(avctx, AV_LOG_ERROR, "pixel format not supported\n");
133         return -1;
134     }
135     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
136
137     ff_set_cmp(&s->mecc, s->mecc.me_cmp, s->avctx->me_cmp);
138     ff_set_cmp(&s->mecc, s->mecc.me_sub_cmp, s->avctx->me_sub_cmp);
139
140     s->input_picture = av_frame_alloc();
141     if (!s->input_picture)
142         return AVERROR(ENOMEM);
143
144     if ((ret = ff_snow_get_buffer(s, s->input_picture)) < 0)
145         return ret;
146
147     if(s->motion_est == FF_ME_ITER){
148         int size= s->b_width * s->b_height << 2*s->block_max_depth;
149         for(i=0; i<s->max_ref_frames; i++){
150             s->ref_mvs[i]= av_mallocz_array(size, sizeof(int16_t[2]));
151             s->ref_scores[i]= av_mallocz_array(size, sizeof(uint32_t));
152             if (!s->ref_mvs[i] || !s->ref_scores[i])
153                 return AVERROR(ENOMEM);
154         }
155     }
156
157     return 0;
158 }
159
160 //near copy & paste from dsputil, FIXME
161 static int pix_sum(uint8_t * pix, int line_size, int w, int h)
162 {
163     int s, i, j;
164
165     s = 0;
166     for (i = 0; i < h; i++) {
167         for (j = 0; j < w; j++) {
168             s += pix[0];
169             pix ++;
170         }
171         pix += line_size - w;
172     }
173     return s;
174 }
175
176 //near copy & paste from dsputil, FIXME
177 static int pix_norm1(uint8_t * pix, int line_size, int w)
178 {
179     int s, i, j;
180     uint32_t *sq = ff_square_tab + 256;
181
182     s = 0;
183     for (i = 0; i < w; i++) {
184         for (j = 0; j < w; j ++) {
185             s += sq[pix[0]];
186             pix ++;
187         }
188         pix += line_size - w;
189     }
190     return s;
191 }
192
193 static inline int get_penalty_factor(int lambda, int lambda2, int type){
194     switch(type&0xFF){
195     default:
196     case FF_CMP_SAD:
197         return lambda>>FF_LAMBDA_SHIFT;
198     case FF_CMP_DCT:
199         return (3*lambda)>>(FF_LAMBDA_SHIFT+1);
200     case FF_CMP_W53:
201         return (4*lambda)>>(FF_LAMBDA_SHIFT);
202     case FF_CMP_W97:
203         return (2*lambda)>>(FF_LAMBDA_SHIFT);
204     case FF_CMP_SATD:
205     case FF_CMP_DCT264:
206         return (2*lambda)>>FF_LAMBDA_SHIFT;
207     case FF_CMP_RD:
208     case FF_CMP_PSNR:
209     case FF_CMP_SSE:
210     case FF_CMP_NSSE:
211         return lambda2>>FF_LAMBDA_SHIFT;
212     case FF_CMP_BIT:
213         return 1;
214     }
215 }
216
217 //FIXME copy&paste
218 #define P_LEFT P[1]
219 #define P_TOP P[2]
220 #define P_TOPRIGHT P[3]
221 #define P_MEDIAN P[4]
222 #define P_MV1 P[9]
223 #define FLAG_QPEL   1 //must be 1
224
225 static int encode_q_branch(SnowContext *s, int level, int x, int y){
226     uint8_t p_buffer[1024];
227     uint8_t i_buffer[1024];
228     uint8_t p_state[sizeof(s->block_state)];
229     uint8_t i_state[sizeof(s->block_state)];
230     RangeCoder pc, ic;
231     uint8_t *pbbak= s->c.bytestream;
232     uint8_t *pbbak_start= s->c.bytestream_start;
233     int score, score2, iscore, i_len, p_len, block_s, sum, base_bits;
234     const int w= s->b_width  << s->block_max_depth;
235     const int h= s->b_height << s->block_max_depth;
236     const int rem_depth= s->block_max_depth - level;
237     const int index= (x + y*w) << rem_depth;
238     const int block_w= 1<<(LOG2_MB_SIZE - level);
239     int trx= (x+1)<<rem_depth;
240     int try= (y+1)<<rem_depth;
241     const BlockNode *left  = x ? &s->block[index-1] : &null_block;
242     const BlockNode *top   = y ? &s->block[index-w] : &null_block;
243     const BlockNode *right = trx<w ? &s->block[index+1] : &null_block;
244     const BlockNode *bottom= try<h ? &s->block[index+w] : &null_block;
245     const BlockNode *tl    = y && x ? &s->block[index-w-1] : left;
246     const BlockNode *tr    = y && trx<w && ((x&1)==0 || level==0) ? &s->block[index-w+(1<<rem_depth)] : tl; //FIXME use lt
247     int pl = left->color[0];
248     int pcb= left->color[1];
249     int pcr= left->color[2];
250     int pmx, pmy;
251     int mx=0, my=0;
252     int l,cr,cb;
253     const int stride= s->current_picture->linesize[0];
254     const int uvstride= s->current_picture->linesize[1];
255     uint8_t *current_data[3]= { s->input_picture->data[0] + (x + y*  stride)*block_w,
256                                 s->input_picture->data[1] + ((x*block_w)>>s->chroma_h_shift) + ((y*uvstride*block_w)>>s->chroma_v_shift),
257                                 s->input_picture->data[2] + ((x*block_w)>>s->chroma_h_shift) + ((y*uvstride*block_w)>>s->chroma_v_shift)};
258     int P[10][2];
259     int16_t last_mv[3][2];
260     int qpel= !!(s->avctx->flags & AV_CODEC_FLAG_QPEL); //unused
261     const int shift= 1+qpel;
262     MotionEstContext *c= &s->m.me;
263     int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
264     int mx_context= av_log2(2*FFABS(left->mx - top->mx));
265     int my_context= av_log2(2*FFABS(left->my - top->my));
266     int s_context= 2*left->level + 2*top->level + tl->level + tr->level;
267     int ref, best_ref, ref_score, ref_mx, ref_my;
268
269     av_assert0(sizeof(s->block_state) >= 256);
270     if(s->keyframe){
271         set_blocks(s, level, x, y, pl, pcb, pcr, 0, 0, 0, BLOCK_INTRA);
272         return 0;
273     }
274
275 //    clip predictors / edge ?
276
277     P_LEFT[0]= left->mx;
278     P_LEFT[1]= left->my;
279     P_TOP [0]= top->mx;
280     P_TOP [1]= top->my;
281     P_TOPRIGHT[0]= tr->mx;
282     P_TOPRIGHT[1]= tr->my;
283
284     last_mv[0][0]= s->block[index].mx;
285     last_mv[0][1]= s->block[index].my;
286     last_mv[1][0]= right->mx;
287     last_mv[1][1]= right->my;
288     last_mv[2][0]= bottom->mx;
289     last_mv[2][1]= bottom->my;
290
291     s->m.mb_stride=2;
292     s->m.mb_x=
293     s->m.mb_y= 0;
294     c->skip= 0;
295
296     av_assert1(c->  stride ==   stride);
297     av_assert1(c->uvstride == uvstride);
298
299     c->penalty_factor    = get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_cmp);
300     c->sub_penalty_factor= get_penalty_factor(s->lambda, s->lambda2, c->avctx->me_sub_cmp);
301     c->mb_penalty_factor = get_penalty_factor(s->lambda, s->lambda2, c->avctx->mb_cmp);
302     c->current_mv_penalty= c->mv_penalty[s->m.f_code=1] + MAX_DMV;
303
304     c->xmin = - x*block_w - 16+3;
305     c->ymin = - y*block_w - 16+3;
306     c->xmax = - (x+1)*block_w + (w<<(LOG2_MB_SIZE - s->block_max_depth)) + 16-3;
307     c->ymax = - (y+1)*block_w + (h<<(LOG2_MB_SIZE - s->block_max_depth)) + 16-3;
308
309     if(P_LEFT[0]     > (c->xmax<<shift)) P_LEFT[0]    = (c->xmax<<shift);
310     if(P_LEFT[1]     > (c->ymax<<shift)) P_LEFT[1]    = (c->ymax<<shift);
311     if(P_TOP[0]      > (c->xmax<<shift)) P_TOP[0]     = (c->xmax<<shift);
312     if(P_TOP[1]      > (c->ymax<<shift)) P_TOP[1]     = (c->ymax<<shift);
313     if(P_TOPRIGHT[0] < (c->xmin<<shift)) P_TOPRIGHT[0]= (c->xmin<<shift);
314     if(P_TOPRIGHT[0] > (c->xmax<<shift)) P_TOPRIGHT[0]= (c->xmax<<shift); //due to pmx no clip
315     if(P_TOPRIGHT[1] > (c->ymax<<shift)) P_TOPRIGHT[1]= (c->ymax<<shift);
316
317     P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
318     P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
319
320     if (!y) {
321         c->pred_x= P_LEFT[0];
322         c->pred_y= P_LEFT[1];
323     } else {
324         c->pred_x = P_MEDIAN[0];
325         c->pred_y = P_MEDIAN[1];
326     }
327
328     score= INT_MAX;
329     best_ref= 0;
330     for(ref=0; ref<s->ref_frames; ref++){
331         init_ref(c, current_data, s->last_picture[ref]->data, NULL, block_w*x, block_w*y, 0);
332
333         ref_score= ff_epzs_motion_search(&s->m, &ref_mx, &ref_my, P, 0, /*ref_index*/ 0, last_mv,
334                                          (1<<16)>>shift, level-LOG2_MB_SIZE+4, block_w);
335
336         av_assert2(ref_mx >= c->xmin);
337         av_assert2(ref_mx <= c->xmax);
338         av_assert2(ref_my >= c->ymin);
339         av_assert2(ref_my <= c->ymax);
340
341         ref_score= c->sub_motion_search(&s->m, &ref_mx, &ref_my, ref_score, 0, 0, level-LOG2_MB_SIZE+4, block_w);
342         ref_score= ff_get_mb_score(&s->m, ref_mx, ref_my, 0, 0, level-LOG2_MB_SIZE+4, block_w, 0);
343         ref_score+= 2*av_log2(2*ref)*c->penalty_factor;
344         if(s->ref_mvs[ref]){
345             s->ref_mvs[ref][index][0]= ref_mx;
346             s->ref_mvs[ref][index][1]= ref_my;
347             s->ref_scores[ref][index]= ref_score;
348         }
349         if(score > ref_score){
350             score= ref_score;
351             best_ref= ref;
352             mx= ref_mx;
353             my= ref_my;
354         }
355     }
356     //FIXME if mb_cmp != SSE then intra cannot be compared currently and mb_penalty vs. lambda2
357
358   //  subpel search
359     base_bits= get_rac_count(&s->c) - 8*(s->c.bytestream - s->c.bytestream_start);
360     pc= s->c;
361     pc.bytestream_start=
362     pc.bytestream= p_buffer; //FIXME end/start? and at the other stoo
363     memcpy(p_state, s->block_state, sizeof(s->block_state));
364
365     if(level!=s->block_max_depth)
366         put_rac(&pc, &p_state[4 + s_context], 1);
367     put_rac(&pc, &p_state[1 + left->type + top->type], 0);
368     if(s->ref_frames > 1)
369         put_symbol(&pc, &p_state[128 + 1024 + 32*ref_context], best_ref, 0);
370     pred_mv(s, &pmx, &pmy, best_ref, left, top, tr);
371     put_symbol(&pc, &p_state[128 + 32*(mx_context + 16*!!best_ref)], mx - pmx, 1);
372     put_symbol(&pc, &p_state[128 + 32*(my_context + 16*!!best_ref)], my - pmy, 1);
373     p_len= pc.bytestream - pc.bytestream_start;
374     score += (s->lambda2*(get_rac_count(&pc)-base_bits))>>FF_LAMBDA_SHIFT;
375
376     block_s= block_w*block_w;
377     sum = pix_sum(current_data[0], stride, block_w, block_w);
378     l= (sum + block_s/2)/block_s;
379     iscore = pix_norm1(current_data[0], stride, block_w) - 2*l*sum + l*l*block_s;
380
381     if (s->nb_planes > 2) {
382         block_s= block_w*block_w>>(s->chroma_h_shift + s->chroma_v_shift);
383         sum = pix_sum(current_data[1], uvstride, block_w>>s->chroma_h_shift, block_w>>s->chroma_v_shift);
384         cb= (sum + block_s/2)/block_s;
385     //    iscore += pix_norm1(&current_mb[1][0], uvstride, block_w>>1) - 2*cb*sum + cb*cb*block_s;
386         sum = pix_sum(current_data[2], uvstride, block_w>>s->chroma_h_shift, block_w>>s->chroma_v_shift);
387         cr= (sum + block_s/2)/block_s;
388     //    iscore += pix_norm1(&current_mb[2][0], uvstride, block_w>>1) - 2*cr*sum + cr*cr*block_s;
389     }else
390         cb = cr = 0;
391
392     ic= s->c;
393     ic.bytestream_start=
394     ic.bytestream= i_buffer; //FIXME end/start? and at the other stoo
395     memcpy(i_state, s->block_state, sizeof(s->block_state));
396     if(level!=s->block_max_depth)
397         put_rac(&ic, &i_state[4 + s_context], 1);
398     put_rac(&ic, &i_state[1 + left->type + top->type], 1);
399     put_symbol(&ic, &i_state[32],  l-pl , 1);
400     if (s->nb_planes > 2) {
401         put_symbol(&ic, &i_state[64], cb-pcb, 1);
402         put_symbol(&ic, &i_state[96], cr-pcr, 1);
403     }
404     i_len= ic.bytestream - ic.bytestream_start;
405     iscore += (s->lambda2*(get_rac_count(&ic)-base_bits))>>FF_LAMBDA_SHIFT;
406
407     av_assert1(iscore < 255*255*256 + s->lambda2*10);
408     av_assert1(iscore >= 0);
409     av_assert1(l>=0 && l<=255);
410     av_assert1(pl>=0 && pl<=255);
411
412     if(level==0){
413         int varc= iscore >> 8;
414         int vard= score >> 8;
415         if (vard <= 64 || vard < varc)
416             c->scene_change_score+= ff_sqrt(vard) - ff_sqrt(varc);
417         else
418             c->scene_change_score+= s->m.qscale;
419     }
420
421     if(level!=s->block_max_depth){
422         put_rac(&s->c, &s->block_state[4 + s_context], 0);
423         score2 = encode_q_branch(s, level+1, 2*x+0, 2*y+0);
424         score2+= encode_q_branch(s, level+1, 2*x+1, 2*y+0);
425         score2+= encode_q_branch(s, level+1, 2*x+0, 2*y+1);
426         score2+= encode_q_branch(s, level+1, 2*x+1, 2*y+1);
427         score2+= s->lambda2>>FF_LAMBDA_SHIFT; //FIXME exact split overhead
428
429         if(score2 < score && score2 < iscore)
430             return score2;
431     }
432
433     if(iscore < score){
434         pred_mv(s, &pmx, &pmy, 0, left, top, tr);
435         memcpy(pbbak, i_buffer, i_len);
436         s->c= ic;
437         s->c.bytestream_start= pbbak_start;
438         s->c.bytestream= pbbak + i_len;
439         set_blocks(s, level, x, y, l, cb, cr, pmx, pmy, 0, BLOCK_INTRA);
440         memcpy(s->block_state, i_state, sizeof(s->block_state));
441         return iscore;
442     }else{
443         memcpy(pbbak, p_buffer, p_len);
444         s->c= pc;
445         s->c.bytestream_start= pbbak_start;
446         s->c.bytestream= pbbak + p_len;
447         set_blocks(s, level, x, y, pl, pcb, pcr, mx, my, best_ref, 0);
448         memcpy(s->block_state, p_state, sizeof(s->block_state));
449         return score;
450     }
451 }
452
453 static void encode_q_branch2(SnowContext *s, int level, int x, int y){
454     const int w= s->b_width  << s->block_max_depth;
455     const int rem_depth= s->block_max_depth - level;
456     const int index= (x + y*w) << rem_depth;
457     int trx= (x+1)<<rem_depth;
458     BlockNode *b= &s->block[index];
459     const BlockNode *left  = x ? &s->block[index-1] : &null_block;
460     const BlockNode *top   = y ? &s->block[index-w] : &null_block;
461     const BlockNode *tl    = y && x ? &s->block[index-w-1] : left;
462     const BlockNode *tr    = y && trx<w && ((x&1)==0 || level==0) ? &s->block[index-w+(1<<rem_depth)] : tl; //FIXME use lt
463     int pl = left->color[0];
464     int pcb= left->color[1];
465     int pcr= left->color[2];
466     int pmx, pmy;
467     int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
468     int mx_context= av_log2(2*FFABS(left->mx - top->mx)) + 16*!!b->ref;
469     int my_context= av_log2(2*FFABS(left->my - top->my)) + 16*!!b->ref;
470     int s_context= 2*left->level + 2*top->level + tl->level + tr->level;
471
472     if(s->keyframe){
473         set_blocks(s, level, x, y, pl, pcb, pcr, 0, 0, 0, BLOCK_INTRA);
474         return;
475     }
476
477     if(level!=s->block_max_depth){
478         if(same_block(b,b+1) && same_block(b,b+w) && same_block(b,b+w+1)){
479             put_rac(&s->c, &s->block_state[4 + s_context], 1);
480         }else{
481             put_rac(&s->c, &s->block_state[4 + s_context], 0);
482             encode_q_branch2(s, level+1, 2*x+0, 2*y+0);
483             encode_q_branch2(s, level+1, 2*x+1, 2*y+0);
484             encode_q_branch2(s, level+1, 2*x+0, 2*y+1);
485             encode_q_branch2(s, level+1, 2*x+1, 2*y+1);
486             return;
487         }
488     }
489     if(b->type & BLOCK_INTRA){
490         pred_mv(s, &pmx, &pmy, 0, left, top, tr);
491         put_rac(&s->c, &s->block_state[1 + (left->type&1) + (top->type&1)], 1);
492         put_symbol(&s->c, &s->block_state[32], b->color[0]-pl , 1);
493         if (s->nb_planes > 2) {
494             put_symbol(&s->c, &s->block_state[64], b->color[1]-pcb, 1);
495             put_symbol(&s->c, &s->block_state[96], b->color[2]-pcr, 1);
496         }
497         set_blocks(s, level, x, y, b->color[0], b->color[1], b->color[2], pmx, pmy, 0, BLOCK_INTRA);
498     }else{
499         pred_mv(s, &pmx, &pmy, b->ref, left, top, tr);
500         put_rac(&s->c, &s->block_state[1 + (left->type&1) + (top->type&1)], 0);
501         if(s->ref_frames > 1)
502             put_symbol(&s->c, &s->block_state[128 + 1024 + 32*ref_context], b->ref, 0);
503         put_symbol(&s->c, &s->block_state[128 + 32*mx_context], b->mx - pmx, 1);
504         put_symbol(&s->c, &s->block_state[128 + 32*my_context], b->my - pmy, 1);
505         set_blocks(s, level, x, y, pl, pcb, pcr, b->mx, b->my, b->ref, 0);
506     }
507 }
508
509 static int get_dc(SnowContext *s, int mb_x, int mb_y, int plane_index){
510     int i, x2, y2;
511     Plane *p= &s->plane[plane_index];
512     const int block_size = MB_SIZE >> s->block_max_depth;
513     const int block_w    = plane_index ? block_size>>s->chroma_h_shift : block_size;
514     const int block_h    = plane_index ? block_size>>s->chroma_v_shift : block_size;
515     const uint8_t *obmc  = plane_index ? ff_obmc_tab[s->block_max_depth+s->chroma_h_shift] : ff_obmc_tab[s->block_max_depth];
516     const int obmc_stride= plane_index ? (2*block_size)>>s->chroma_h_shift : 2*block_size;
517     const int ref_stride= s->current_picture->linesize[plane_index];
518     uint8_t *src= s-> input_picture->data[plane_index];
519     IDWTELEM *dst= (IDWTELEM*)s->m.sc.obmc_scratchpad + plane_index*block_size*block_size*4; //FIXME change to unsigned
520     const int b_stride = s->b_width << s->block_max_depth;
521     const int w= p->width;
522     const int h= p->height;
523     int index= mb_x + mb_y*b_stride;
524     BlockNode *b= &s->block[index];
525     BlockNode backup= *b;
526     int ab=0;
527     int aa=0;
528
529     av_assert2(s->chroma_h_shift == s->chroma_v_shift); //obmc stuff above
530
531     b->type|= BLOCK_INTRA;
532     b->color[plane_index]= 0;
533     memset(dst, 0, obmc_stride*obmc_stride*sizeof(IDWTELEM));
534
535     for(i=0; i<4; i++){
536         int mb_x2= mb_x + (i &1) - 1;
537         int mb_y2= mb_y + (i>>1) - 1;
538         int x= block_w*mb_x2 + block_w/2;
539         int y= block_h*mb_y2 + block_h/2;
540
541         add_yblock(s, 0, NULL, dst + (i&1)*block_w + (i>>1)*obmc_stride*block_h, NULL, obmc,
542                     x, y, block_w, block_h, w, h, obmc_stride, ref_stride, obmc_stride, mb_x2, mb_y2, 0, 0, plane_index);
543
544         for(y2= FFMAX(y, 0); y2<FFMIN(h, y+block_h); y2++){
545             for(x2= FFMAX(x, 0); x2<FFMIN(w, x+block_w); x2++){
546                 int index= x2-(block_w*mb_x - block_w/2) + (y2-(block_h*mb_y - block_h/2))*obmc_stride;
547                 int obmc_v= obmc[index];
548                 int d;
549                 if(y<0) obmc_v += obmc[index + block_h*obmc_stride];
550                 if(x<0) obmc_v += obmc[index + block_w];
551                 if(y+block_h>h) obmc_v += obmc[index - block_h*obmc_stride];
552                 if(x+block_w>w) obmc_v += obmc[index - block_w];
553                 //FIXME precalculate this or simplify it somehow else
554
555                 d = -dst[index] + (1<<(FRAC_BITS-1));
556                 dst[index] = d;
557                 ab += (src[x2 + y2*ref_stride] - (d>>FRAC_BITS)) * obmc_v;
558                 aa += obmc_v * obmc_v; //FIXME precalculate this
559             }
560         }
561     }
562     *b= backup;
563
564     return av_clip_uint8( ROUNDED_DIV(ab<<LOG2_OBMC_MAX, aa) ); //FIXME we should not need clipping
565 }
566
567 static inline int get_block_bits(SnowContext *s, int x, int y, int w){
568     const int b_stride = s->b_width << s->block_max_depth;
569     const int b_height = s->b_height<< s->block_max_depth;
570     int index= x + y*b_stride;
571     const BlockNode *b     = &s->block[index];
572     const BlockNode *left  = x ? &s->block[index-1] : &null_block;
573     const BlockNode *top   = y ? &s->block[index-b_stride] : &null_block;
574     const BlockNode *tl    = y && x ? &s->block[index-b_stride-1] : left;
575     const BlockNode *tr    = y && x+w<b_stride ? &s->block[index-b_stride+w] : tl;
576     int dmx, dmy;
577 //  int mx_context= av_log2(2*FFABS(left->mx - top->mx));
578 //  int my_context= av_log2(2*FFABS(left->my - top->my));
579
580     if(x<0 || x>=b_stride || y>=b_height)
581         return 0;
582 /*
583 1            0      0
584 01X          1-2    1
585 001XX        3-6    2-3
586 0001XXX      7-14   4-7
587 00001XXXX   15-30   8-15
588 */
589 //FIXME try accurate rate
590 //FIXME intra and inter predictors if surrounding blocks are not the same type
591     if(b->type & BLOCK_INTRA){
592         return 3+2*( av_log2(2*FFABS(left->color[0] - b->color[0]))
593                    + av_log2(2*FFABS(left->color[1] - b->color[1]))
594                    + av_log2(2*FFABS(left->color[2] - b->color[2])));
595     }else{
596         pred_mv(s, &dmx, &dmy, b->ref, left, top, tr);
597         dmx-= b->mx;
598         dmy-= b->my;
599         return 2*(1 + av_log2(2*FFABS(dmx)) //FIXME kill the 2* can be merged in lambda
600                     + av_log2(2*FFABS(dmy))
601                     + av_log2(2*b->ref));
602     }
603 }
604
605 static int get_block_rd(SnowContext *s, int mb_x, int mb_y, int plane_index, uint8_t (*obmc_edged)[MB_SIZE * 2]){
606     Plane *p= &s->plane[plane_index];
607     const int block_size = MB_SIZE >> s->block_max_depth;
608     const int block_w    = plane_index ? block_size>>s->chroma_h_shift : block_size;
609     const int block_h    = plane_index ? block_size>>s->chroma_v_shift : block_size;
610     const int obmc_stride= plane_index ? (2*block_size)>>s->chroma_h_shift : 2*block_size;
611     const int ref_stride= s->current_picture->linesize[plane_index];
612     uint8_t *dst= s->current_picture->data[plane_index];
613     uint8_t *src= s->  input_picture->data[plane_index];
614     IDWTELEM *pred= (IDWTELEM*)s->m.sc.obmc_scratchpad + plane_index*block_size*block_size*4;
615     uint8_t *cur = s->scratchbuf;
616     uint8_t *tmp = s->emu_edge_buffer;
617     const int b_stride = s->b_width << s->block_max_depth;
618     const int b_height = s->b_height<< s->block_max_depth;
619     const int w= p->width;
620     const int h= p->height;
621     int distortion;
622     int rate= 0;
623     const int penalty_factor= get_penalty_factor(s->lambda, s->lambda2, s->avctx->me_cmp);
624     int sx= block_w*mb_x - block_w/2;
625     int sy= block_h*mb_y - block_h/2;
626     int x0= FFMAX(0,-sx);
627     int y0= FFMAX(0,-sy);
628     int x1= FFMIN(block_w*2, w-sx);
629     int y1= FFMIN(block_h*2, h-sy);
630     int i,x,y;
631
632     av_assert2(s->chroma_h_shift == s->chroma_v_shift); //obmc and square assumtions below chckinhg only block_w
633
634     ff_snow_pred_block(s, cur, tmp, ref_stride, sx, sy, block_w*2, block_h*2, &s->block[mb_x + mb_y*b_stride], plane_index, w, h);
635
636     for(y=y0; y<y1; y++){
637         const uint8_t *obmc1= obmc_edged[y];
638         const IDWTELEM *pred1 = pred + y*obmc_stride;
639         uint8_t *cur1 = cur + y*ref_stride;
640         uint8_t *dst1 = dst + sx + (sy+y)*ref_stride;
641         for(x=x0; x<x1; x++){
642 #if FRAC_BITS >= LOG2_OBMC_MAX
643             int v = (cur1[x] * obmc1[x]) << (FRAC_BITS - LOG2_OBMC_MAX);
644 #else
645             int v = (cur1[x] * obmc1[x] + (1<<(LOG2_OBMC_MAX - FRAC_BITS-1))) >> (LOG2_OBMC_MAX - FRAC_BITS);
646 #endif
647             v = (v + pred1[x]) >> FRAC_BITS;
648             if(v&(~255)) v= ~(v>>31);
649             dst1[x] = v;
650         }
651     }
652
653     /* copy the regions where obmc[] = (uint8_t)256 */
654     if(LOG2_OBMC_MAX == 8
655         && (mb_x == 0 || mb_x == b_stride-1)
656         && (mb_y == 0 || mb_y == b_height-1)){
657         if(mb_x == 0)
658             x1 = block_w;
659         else
660             x0 = block_w;
661         if(mb_y == 0)
662             y1 = block_h;
663         else
664             y0 = block_h;
665         for(y=y0; y<y1; y++)
666             memcpy(dst + sx+x0 + (sy+y)*ref_stride, cur + x0 + y*ref_stride, x1-x0);
667     }
668
669     if(block_w==16){
670         /* FIXME rearrange dsputil to fit 32x32 cmp functions */
671         /* FIXME check alignment of the cmp wavelet vs the encoding wavelet */
672         /* FIXME cmps overlap but do not cover the wavelet's whole support.
673          * So improving the score of one block is not strictly guaranteed
674          * to improve the score of the whole frame, thus iterative motion
675          * estimation does not always converge. */
676         if(s->avctx->me_cmp == FF_CMP_W97)
677             distortion = ff_w97_32_c(&s->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, 32);
678         else if(s->avctx->me_cmp == FF_CMP_W53)
679             distortion = ff_w53_32_c(&s->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, 32);
680         else{
681             distortion = 0;
682             for(i=0; i<4; i++){
683                 int off = sx+16*(i&1) + (sy+16*(i>>1))*ref_stride;
684                 distortion += s->mecc.me_cmp[0](&s->m, src + off, dst + off, ref_stride, 16);
685             }
686         }
687     }else{
688         av_assert2(block_w==8);
689         distortion = s->mecc.me_cmp[0](&s->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, block_w*2);
690     }
691
692     if(plane_index==0){
693         for(i=0; i<4; i++){
694 /* ..RRr
695  * .RXx.
696  * rxx..
697  */
698             rate += get_block_bits(s, mb_x + (i&1) - (i>>1), mb_y + (i>>1), 1);
699         }
700         if(mb_x == b_stride-2)
701             rate += get_block_bits(s, mb_x + 1, mb_y + 1, 1);
702     }
703     return distortion + rate*penalty_factor;
704 }
705
706 static int get_4block_rd(SnowContext *s, int mb_x, int mb_y, int plane_index){
707     int i, y2;
708     Plane *p= &s->plane[plane_index];
709     const int block_size = MB_SIZE >> s->block_max_depth;
710     const int block_w    = plane_index ? block_size>>s->chroma_h_shift : block_size;
711     const int block_h    = plane_index ? block_size>>s->chroma_v_shift : block_size;
712     const uint8_t *obmc  = plane_index ? ff_obmc_tab[s->block_max_depth+s->chroma_h_shift] : ff_obmc_tab[s->block_max_depth];
713     const int obmc_stride= plane_index ? (2*block_size)>>s->chroma_h_shift : 2*block_size;
714     const int ref_stride= s->current_picture->linesize[plane_index];
715     uint8_t *dst= s->current_picture->data[plane_index];
716     uint8_t *src= s-> input_picture->data[plane_index];
717     //FIXME zero_dst is const but add_yblock changes dst if add is 0 (this is never the case for dst=zero_dst
718     // const has only been removed from zero_dst to suppress a warning
719     static IDWTELEM zero_dst[4096]; //FIXME
720     const int b_stride = s->b_width << s->block_max_depth;
721     const int w= p->width;
722     const int h= p->height;
723     int distortion= 0;
724     int rate= 0;
725     const int penalty_factor= get_penalty_factor(s->lambda, s->lambda2, s->avctx->me_cmp);
726
727     av_assert2(s->chroma_h_shift == s->chroma_v_shift); //obmc and square assumtions below
728
729     for(i=0; i<9; i++){
730         int mb_x2= mb_x + (i%3) - 1;
731         int mb_y2= mb_y + (i/3) - 1;
732         int x= block_w*mb_x2 + block_w/2;
733         int y= block_h*mb_y2 + block_h/2;
734
735         add_yblock(s, 0, NULL, zero_dst, dst, obmc,
736                    x, y, block_w, block_h, w, h, /*dst_stride*/0, ref_stride, obmc_stride, mb_x2, mb_y2, 1, 1, plane_index);
737
738         //FIXME find a cleaner/simpler way to skip the outside stuff
739         for(y2= y; y2<0; y2++)
740             memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, block_w);
741         for(y2= h; y2<y+block_h; y2++)
742             memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, block_w);
743         if(x<0){
744             for(y2= y; y2<y+block_h; y2++)
745                 memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, -x);
746         }
747         if(x+block_w > w){
748             for(y2= y; y2<y+block_h; y2++)
749                 memcpy(dst + w + y2*ref_stride, src + w + y2*ref_stride, x+block_w - w);
750         }
751
752         av_assert1(block_w== 8 || block_w==16);
753         distortion += s->mecc.me_cmp[block_w==8](&s->m, src + x + y*ref_stride, dst + x + y*ref_stride, ref_stride, block_h);
754     }
755
756     if(plane_index==0){
757         BlockNode *b= &s->block[mb_x+mb_y*b_stride];
758         int merged= same_block(b,b+1) && same_block(b,b+b_stride) && same_block(b,b+b_stride+1);
759
760 /* ..RRRr
761  * .RXXx.
762  * .RXXx.
763  * rxxx.
764  */
765         if(merged)
766             rate = get_block_bits(s, mb_x, mb_y, 2);
767         for(i=merged?4:0; i<9; i++){
768             static const int dxy[9][2] = {{0,0},{1,0},{0,1},{1,1},{2,0},{2,1},{-1,2},{0,2},{1,2}};
769             rate += get_block_bits(s, mb_x + dxy[i][0], mb_y + dxy[i][1], 1);
770         }
771     }
772     return distortion + rate*penalty_factor;
773 }
774
775 static int encode_subband_c0run(SnowContext *s, SubBand *b, const IDWTELEM *src, const IDWTELEM *parent, int stride, int orientation){
776     const int w= b->width;
777     const int h= b->height;
778     int x, y;
779
780     if(1){
781         int run=0;
782         int *runs = s->run_buffer;
783         int run_index=0;
784         int max_index;
785
786         for(y=0; y<h; y++){
787             for(x=0; x<w; x++){
788                 int v, p=0;
789                 int /*ll=0, */l=0, lt=0, t=0, rt=0;
790                 v= src[x + y*stride];
791
792                 if(y){
793                     t= src[x + (y-1)*stride];
794                     if(x){
795                         lt= src[x - 1 + (y-1)*stride];
796                     }
797                     if(x + 1 < w){
798                         rt= src[x + 1 + (y-1)*stride];
799                     }
800                 }
801                 if(x){
802                     l= src[x - 1 + y*stride];
803                     /*if(x > 1){
804                         if(orientation==1) ll= src[y + (x-2)*stride];
805                         else               ll= src[x - 2 + y*stride];
806                     }*/
807                 }
808                 if(parent){
809                     int px= x>>1;
810                     int py= y>>1;
811                     if(px<b->parent->width && py<b->parent->height)
812                         p= parent[px + py*2*stride];
813                 }
814                 if(!(/*ll|*/l|lt|t|rt|p)){
815                     if(v){
816                         runs[run_index++]= run;
817                         run=0;
818                     }else{
819                         run++;
820                     }
821                 }
822             }
823         }
824         max_index= run_index;
825         runs[run_index++]= run;
826         run_index=0;
827         run= runs[run_index++];
828
829         put_symbol2(&s->c, b->state[30], max_index, 0);
830         if(run_index <= max_index)
831             put_symbol2(&s->c, b->state[1], run, 3);
832
833         for(y=0; y<h; y++){
834             if(s->c.bytestream_end - s->c.bytestream < w*40){
835                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
836                 return -1;
837             }
838             for(x=0; x<w; x++){
839                 int v, p=0;
840                 int /*ll=0, */l=0, lt=0, t=0, rt=0;
841                 v= src[x + y*stride];
842
843                 if(y){
844                     t= src[x + (y-1)*stride];
845                     if(x){
846                         lt= src[x - 1 + (y-1)*stride];
847                     }
848                     if(x + 1 < w){
849                         rt= src[x + 1 + (y-1)*stride];
850                     }
851                 }
852                 if(x){
853                     l= src[x - 1 + y*stride];
854                     /*if(x > 1){
855                         if(orientation==1) ll= src[y + (x-2)*stride];
856                         else               ll= src[x - 2 + y*stride];
857                     }*/
858                 }
859                 if(parent){
860                     int px= x>>1;
861                     int py= y>>1;
862                     if(px<b->parent->width && py<b->parent->height)
863                         p= parent[px + py*2*stride];
864                 }
865                 if(/*ll|*/l|lt|t|rt|p){
866                     int context= av_log2(/*FFABS(ll) + */3*FFABS(l) + FFABS(lt) + 2*FFABS(t) + FFABS(rt) + FFABS(p));
867
868                     put_rac(&s->c, &b->state[0][context], !!v);
869                 }else{
870                     if(!run){
871                         run= runs[run_index++];
872
873                         if(run_index <= max_index)
874                             put_symbol2(&s->c, b->state[1], run, 3);
875                         av_assert2(v);
876                     }else{
877                         run--;
878                         av_assert2(!v);
879                     }
880                 }
881                 if(v){
882                     int context= av_log2(/*FFABS(ll) + */3*FFABS(l) + FFABS(lt) + 2*FFABS(t) + FFABS(rt) + FFABS(p));
883                     int l2= 2*FFABS(l) + (l<0);
884                     int t2= 2*FFABS(t) + (t<0);
885
886                     put_symbol2(&s->c, b->state[context + 2], FFABS(v)-1, context-4);
887                     put_rac(&s->c, &b->state[0][16 + 1 + 3 + ff_quant3bA[l2&0xFF] + 3*ff_quant3bA[t2&0xFF]], v<0);
888                 }
889             }
890         }
891     }
892     return 0;
893 }
894
895 static int encode_subband(SnowContext *s, SubBand *b, const IDWTELEM *src, const IDWTELEM *parent, int stride, int orientation){
896 //    encode_subband_qtree(s, b, src, parent, stride, orientation);
897 //    encode_subband_z0run(s, b, src, parent, stride, orientation);
898     return encode_subband_c0run(s, b, src, parent, stride, orientation);
899 //    encode_subband_dzr(s, b, src, parent, stride, orientation);
900 }
901
902 static av_always_inline int check_block(SnowContext *s, int mb_x, int mb_y, int p[3], int intra, uint8_t (*obmc_edged)[MB_SIZE * 2], int *best_rd){
903     const int b_stride= s->b_width << s->block_max_depth;
904     BlockNode *block= &s->block[mb_x + mb_y * b_stride];
905     BlockNode backup= *block;
906     unsigned value;
907     int rd, index;
908
909     av_assert2(mb_x>=0 && mb_y>=0);
910     av_assert2(mb_x<b_stride);
911
912     if(intra){
913         block->color[0] = p[0];
914         block->color[1] = p[1];
915         block->color[2] = p[2];
916         block->type |= BLOCK_INTRA;
917     }else{
918         index= (p[0] + 31*p[1]) & (ME_CACHE_SIZE-1);
919         value= s->me_cache_generation + (p[0]>>10) + (p[1]<<6) + (block->ref<<12);
920         if(s->me_cache[index] == value)
921             return 0;
922         s->me_cache[index]= value;
923
924         block->mx= p[0];
925         block->my= p[1];
926         block->type &= ~BLOCK_INTRA;
927     }
928
929     rd= get_block_rd(s, mb_x, mb_y, 0, obmc_edged) + s->intra_penalty * !!intra;
930
931 //FIXME chroma
932     if(rd < *best_rd){
933         *best_rd= rd;
934         return 1;
935     }else{
936         *block= backup;
937         return 0;
938     }
939 }
940
941 /* special case for int[2] args we discard afterwards,
942  * fixes compilation problem with gcc 2.95 */
943 static av_always_inline int check_block_inter(SnowContext *s, int mb_x, int mb_y, int p0, int p1, uint8_t (*obmc_edged)[MB_SIZE * 2], int *best_rd){
944     int p[2] = {p0, p1};
945     return check_block(s, mb_x, mb_y, p, 0, obmc_edged, best_rd);
946 }
947
948 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){
949     const int b_stride= s->b_width << s->block_max_depth;
950     BlockNode *block= &s->block[mb_x + mb_y * b_stride];
951     BlockNode backup[4];
952     unsigned value;
953     int rd, index;
954
955     /* We don't initialize backup[] during variable declaration, because
956      * that fails to compile on MSVC: "cannot convert from 'BlockNode' to
957      * 'int16_t'". */
958     backup[0] = block[0];
959     backup[1] = block[1];
960     backup[2] = block[b_stride];
961     backup[3] = block[b_stride + 1];
962
963     av_assert2(mb_x>=0 && mb_y>=0);
964     av_assert2(mb_x<b_stride);
965     av_assert2(((mb_x|mb_y)&1) == 0);
966
967     index= (p0 + 31*p1) & (ME_CACHE_SIZE-1);
968     value= s->me_cache_generation + (p0>>10) + (p1<<6) + (block->ref<<12);
969     if(s->me_cache[index] == value)
970         return 0;
971     s->me_cache[index]= value;
972
973     block->mx= p0;
974     block->my= p1;
975     block->ref= ref;
976     block->type &= ~BLOCK_INTRA;
977     block[1]= block[b_stride]= block[b_stride+1]= *block;
978
979     rd= get_4block_rd(s, mb_x, mb_y, 0);
980
981 //FIXME chroma
982     if(rd < *best_rd){
983         *best_rd= rd;
984         return 1;
985     }else{
986         block[0]= backup[0];
987         block[1]= backup[1];
988         block[b_stride]= backup[2];
989         block[b_stride+1]= backup[3];
990         return 0;
991     }
992 }
993
994 static void iterative_me(SnowContext *s){
995     int pass, mb_x, mb_y;
996     const int b_width = s->b_width  << s->block_max_depth;
997     const int b_height= s->b_height << s->block_max_depth;
998     const int b_stride= b_width;
999     int color[3];
1000
1001     {
1002         RangeCoder r = s->c;
1003         uint8_t state[sizeof(s->block_state)];
1004         memcpy(state, s->block_state, sizeof(s->block_state));
1005         for(mb_y= 0; mb_y<s->b_height; mb_y++)
1006             for(mb_x= 0; mb_x<s->b_width; mb_x++)
1007                 encode_q_branch(s, 0, mb_x, mb_y);
1008         s->c = r;
1009         memcpy(s->block_state, state, sizeof(s->block_state));
1010     }
1011
1012     for(pass=0; pass<25; pass++){
1013         int change= 0;
1014
1015         for(mb_y= 0; mb_y<b_height; mb_y++){
1016             for(mb_x= 0; mb_x<b_width; mb_x++){
1017                 int dia_change, i, j, ref;
1018                 int best_rd= INT_MAX, ref_rd;
1019                 BlockNode backup, ref_b;
1020                 const int index= mb_x + mb_y * b_stride;
1021                 BlockNode *block= &s->block[index];
1022                 BlockNode *tb =                   mb_y            ? &s->block[index-b_stride  ] : NULL;
1023                 BlockNode *lb = mb_x                              ? &s->block[index         -1] : NULL;
1024                 BlockNode *rb = mb_x+1<b_width                    ? &s->block[index         +1] : NULL;
1025                 BlockNode *bb =                   mb_y+1<b_height ? &s->block[index+b_stride  ] : NULL;
1026                 BlockNode *tlb= mb_x           && mb_y            ? &s->block[index-b_stride-1] : NULL;
1027                 BlockNode *trb= mb_x+1<b_width && mb_y            ? &s->block[index-b_stride+1] : NULL;
1028                 BlockNode *blb= mb_x           && mb_y+1<b_height ? &s->block[index+b_stride-1] : NULL;
1029                 BlockNode *brb= mb_x+1<b_width && mb_y+1<b_height ? &s->block[index+b_stride+1] : NULL;
1030                 const int b_w= (MB_SIZE >> s->block_max_depth);
1031                 uint8_t obmc_edged[MB_SIZE * 2][MB_SIZE * 2];
1032
1033                 if(pass && (block->type & BLOCK_OPT))
1034                     continue;
1035                 block->type |= BLOCK_OPT;
1036
1037                 backup= *block;
1038
1039                 if(!s->me_cache_generation)
1040                     memset(s->me_cache, 0, sizeof(s->me_cache));
1041                 s->me_cache_generation += 1<<22;
1042
1043                 //FIXME precalculate
1044                 {
1045                     int x, y;
1046                     for (y = 0; y < b_w * 2; y++)
1047                         memcpy(obmc_edged[y], ff_obmc_tab[s->block_max_depth] + y * b_w * 2, b_w * 2);
1048                     if(mb_x==0)
1049                         for(y=0; y<b_w*2; y++)
1050                             memset(obmc_edged[y], obmc_edged[y][0] + obmc_edged[y][b_w-1], b_w);
1051                     if(mb_x==b_stride-1)
1052                         for(y=0; y<b_w*2; y++)
1053                             memset(obmc_edged[y]+b_w, obmc_edged[y][b_w] + obmc_edged[y][b_w*2-1], b_w);
1054                     if(mb_y==0){
1055                         for(x=0; x<b_w*2; x++)
1056                             obmc_edged[0][x] += obmc_edged[b_w-1][x];
1057                         for(y=1; y<b_w; y++)
1058                             memcpy(obmc_edged[y], obmc_edged[0], b_w*2);
1059                     }
1060                     if(mb_y==b_height-1){
1061                         for(x=0; x<b_w*2; x++)
1062                             obmc_edged[b_w*2-1][x] += obmc_edged[b_w][x];
1063                         for(y=b_w; y<b_w*2-1; y++)
1064                             memcpy(obmc_edged[y], obmc_edged[b_w*2-1], b_w*2);
1065                     }
1066                 }
1067
1068                 //skip stuff outside the picture
1069                 if(mb_x==0 || mb_y==0 || mb_x==b_width-1 || mb_y==b_height-1){
1070                     uint8_t *src= s->  input_picture->data[0];
1071                     uint8_t *dst= s->current_picture->data[0];
1072                     const int stride= s->current_picture->linesize[0];
1073                     const int block_w= MB_SIZE >> s->block_max_depth;
1074                     const int block_h= MB_SIZE >> s->block_max_depth;
1075                     const int sx= block_w*mb_x - block_w/2;
1076                     const int sy= block_h*mb_y - block_h/2;
1077                     const int w= s->plane[0].width;
1078                     const int h= s->plane[0].height;
1079                     int y;
1080
1081                     for(y=sy; y<0; y++)
1082                         memcpy(dst + sx + y*stride, src + sx + y*stride, block_w*2);
1083                     for(y=h; y<sy+block_h*2; y++)
1084                         memcpy(dst + sx + y*stride, src + sx + y*stride, block_w*2);
1085                     if(sx<0){
1086                         for(y=sy; y<sy+block_h*2; y++)
1087                             memcpy(dst + sx + y*stride, src + sx + y*stride, -sx);
1088                     }
1089                     if(sx+block_w*2 > w){
1090                         for(y=sy; y<sy+block_h*2; y++)
1091                             memcpy(dst + w + y*stride, src + w + y*stride, sx+block_w*2 - w);
1092                     }
1093                 }
1094
1095                 // intra(black) = neighbors' contribution to the current block
1096                 for(i=0; i < s->nb_planes; i++)
1097                     color[i]= get_dc(s, mb_x, mb_y, i);
1098
1099                 // get previous score (cannot be cached due to OBMC)
1100                 if(pass > 0 && (block->type&BLOCK_INTRA)){
1101                     int color0[3]= {block->color[0], block->color[1], block->color[2]};
1102                     check_block(s, mb_x, mb_y, color0, 1, obmc_edged, &best_rd);
1103                 }else
1104                     check_block_inter(s, mb_x, mb_y, block->mx, block->my, obmc_edged, &best_rd);
1105
1106                 ref_b= *block;
1107                 ref_rd= best_rd;
1108                 for(ref=0; ref < s->ref_frames; ref++){
1109                     int16_t (*mvr)[2]= &s->ref_mvs[ref][index];
1110                     if(s->ref_scores[ref][index] > s->ref_scores[ref_b.ref][index]*3/2) //FIXME tune threshold
1111                         continue;
1112                     block->ref= ref;
1113                     best_rd= INT_MAX;
1114
1115                     check_block_inter(s, mb_x, mb_y, mvr[0][0], mvr[0][1], obmc_edged, &best_rd);
1116                     check_block_inter(s, mb_x, mb_y, 0, 0, obmc_edged, &best_rd);
1117                     if(tb)
1118                         check_block_inter(s, mb_x, mb_y, mvr[-b_stride][0], mvr[-b_stride][1], obmc_edged, &best_rd);
1119                     if(lb)
1120                         check_block_inter(s, mb_x, mb_y, mvr[-1][0], mvr[-1][1], obmc_edged, &best_rd);
1121                     if(rb)
1122                         check_block_inter(s, mb_x, mb_y, mvr[1][0], mvr[1][1], obmc_edged, &best_rd);
1123                     if(bb)
1124                         check_block_inter(s, mb_x, mb_y, mvr[b_stride][0], mvr[b_stride][1], obmc_edged, &best_rd);
1125
1126                     /* fullpel ME */
1127                     //FIXME avoid subpel interpolation / round to nearest integer
1128                     do{
1129                         int newx = block->mx;
1130                         int newy = block->my;
1131                         int dia_size = s->iterative_dia_size ? s->iterative_dia_size : FFMAX(s->avctx->dia_size, 1);
1132                         dia_change=0;
1133                         for(i=0; i < dia_size; i++){
1134                             for(j=0; j<i; j++){
1135                                 dia_change |= check_block_inter(s, mb_x, mb_y, newx+4*(i-j), newy+(4*j), obmc_edged, &best_rd);
1136                                 dia_change |= check_block_inter(s, mb_x, mb_y, newx-4*(i-j), newy-(4*j), obmc_edged, &best_rd);
1137                                 dia_change |= check_block_inter(s, mb_x, mb_y, newx-(4*j), newy+4*(i-j), obmc_edged, &best_rd);
1138                                 dia_change |= check_block_inter(s, mb_x, mb_y, newx+(4*j), newy-4*(i-j), obmc_edged, &best_rd);
1139                             }
1140                         }
1141                     }while(dia_change);
1142                     /* subpel ME */
1143                     do{
1144                         static const int square[8][2]= {{+1, 0},{-1, 0},{ 0,+1},{ 0,-1},{+1,+1},{-1,-1},{+1,-1},{-1,+1},};
1145                         dia_change=0;
1146                         for(i=0; i<8; i++)
1147                             dia_change |= check_block_inter(s, mb_x, mb_y, block->mx+square[i][0], block->my+square[i][1], obmc_edged, &best_rd);
1148                     }while(dia_change);
1149                     //FIXME or try the standard 2 pass qpel or similar
1150
1151                     mvr[0][0]= block->mx;
1152                     mvr[0][1]= block->my;
1153                     if(ref_rd > best_rd){
1154                         ref_rd= best_rd;
1155                         ref_b= *block;
1156                     }
1157                 }
1158                 best_rd= ref_rd;
1159                 *block= ref_b;
1160                 check_block(s, mb_x, mb_y, color, 1, obmc_edged, &best_rd);
1161                 //FIXME RD style color selection
1162                 if(!same_block(block, &backup)){
1163                     if(tb ) tb ->type &= ~BLOCK_OPT;
1164                     if(lb ) lb ->type &= ~BLOCK_OPT;
1165                     if(rb ) rb ->type &= ~BLOCK_OPT;
1166                     if(bb ) bb ->type &= ~BLOCK_OPT;
1167                     if(tlb) tlb->type &= ~BLOCK_OPT;
1168                     if(trb) trb->type &= ~BLOCK_OPT;
1169                     if(blb) blb->type &= ~BLOCK_OPT;
1170                     if(brb) brb->type &= ~BLOCK_OPT;
1171                     change ++;
1172                 }
1173             }
1174         }
1175         av_log(s->avctx, AV_LOG_DEBUG, "pass:%d changed:%d\n", pass, change);
1176         if(!change)
1177             break;
1178     }
1179
1180     if(s->block_max_depth == 1){
1181         int change= 0;
1182         for(mb_y= 0; mb_y<b_height; mb_y+=2){
1183             for(mb_x= 0; mb_x<b_width; mb_x+=2){
1184                 int i;
1185                 int best_rd, init_rd;
1186                 const int index= mb_x + mb_y * b_stride;
1187                 BlockNode *b[4];
1188
1189                 b[0]= &s->block[index];
1190                 b[1]= b[0]+1;
1191                 b[2]= b[0]+b_stride;
1192                 b[3]= b[2]+1;
1193                 if(same_block(b[0], b[1]) &&
1194                    same_block(b[0], b[2]) &&
1195                    same_block(b[0], b[3]))
1196                     continue;
1197
1198                 if(!s->me_cache_generation)
1199                     memset(s->me_cache, 0, sizeof(s->me_cache));
1200                 s->me_cache_generation += 1<<22;
1201
1202                 init_rd= best_rd= get_4block_rd(s, mb_x, mb_y, 0);
1203
1204                 //FIXME more multiref search?
1205                 check_4block_inter(s, mb_x, mb_y,
1206                                    (b[0]->mx + b[1]->mx + b[2]->mx + b[3]->mx + 2) >> 2,
1207                                    (b[0]->my + b[1]->my + b[2]->my + b[3]->my + 2) >> 2, 0, &best_rd);
1208
1209                 for(i=0; i<4; i++)
1210                     if(!(b[i]->type&BLOCK_INTRA))
1211                         check_4block_inter(s, mb_x, mb_y, b[i]->mx, b[i]->my, b[i]->ref, &best_rd);
1212
1213                 if(init_rd != best_rd)
1214                     change++;
1215             }
1216         }
1217         av_log(s->avctx, AV_LOG_ERROR, "pass:4mv changed:%d\n", change*4);
1218     }
1219 }
1220
1221 static void encode_blocks(SnowContext *s, int search){
1222     int x, y;
1223     int w= s->b_width;
1224     int h= s->b_height;
1225
1226     if(s->motion_est == FF_ME_ITER && !s->keyframe && search)
1227         iterative_me(s);
1228
1229     for(y=0; y<h; y++){
1230         if(s->c.bytestream_end - s->c.bytestream < w*MB_SIZE*MB_SIZE*3){ //FIXME nicer limit
1231             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
1232             return;
1233         }
1234         for(x=0; x<w; x++){
1235             if(s->motion_est == FF_ME_ITER || !search)
1236                 encode_q_branch2(s, 0, x, y);
1237             else
1238                 encode_q_branch (s, 0, x, y);
1239         }
1240     }
1241 }
1242
1243 static void quantize(SnowContext *s, SubBand *b, IDWTELEM *dst, DWTELEM *src, int stride, int bias){
1244     const int w= b->width;
1245     const int h= b->height;
1246     const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);
1247     const int qmul= ff_qexp[qlog&(QROOT-1)]<<((qlog>>QSHIFT) + ENCODER_EXTRA_BITS);
1248     int x,y, thres1, thres2;
1249
1250     if(s->qlog == LOSSLESS_QLOG){
1251         for(y=0; y<h; y++)
1252             for(x=0; x<w; x++)
1253                 dst[x + y*stride]= src[x + y*stride];
1254         return;
1255     }
1256
1257     bias= bias ? 0 : (3*qmul)>>3;
1258     thres1= ((qmul - bias)>>QEXPSHIFT) - 1;
1259     thres2= 2*thres1;
1260
1261     if(!bias){
1262         for(y=0; y<h; y++){
1263             for(x=0; x<w; x++){
1264                 int i= src[x + y*stride];
1265
1266                 if((unsigned)(i+thres1) > thres2){
1267                     if(i>=0){
1268                         i<<= QEXPSHIFT;
1269                         i/= qmul; //FIXME optimize
1270                         dst[x + y*stride]=  i;
1271                     }else{
1272                         i= -i;
1273                         i<<= QEXPSHIFT;
1274                         i/= qmul; //FIXME optimize
1275                         dst[x + y*stride]= -i;
1276                     }
1277                 }else
1278                     dst[x + y*stride]= 0;
1279             }
1280         }
1281     }else{
1282         for(y=0; y<h; y++){
1283             for(x=0; x<w; x++){
1284                 int i= src[x + y*stride];
1285
1286                 if((unsigned)(i+thres1) > thres2){
1287                     if(i>=0){
1288                         i<<= QEXPSHIFT;
1289                         i= (i + bias) / qmul; //FIXME optimize
1290                         dst[x + y*stride]=  i;
1291                     }else{
1292                         i= -i;
1293                         i<<= QEXPSHIFT;
1294                         i= (i + bias) / qmul; //FIXME optimize
1295                         dst[x + y*stride]= -i;
1296                     }
1297                 }else
1298                     dst[x + y*stride]= 0;
1299             }
1300         }
1301     }
1302 }
1303
1304 static void dequantize(SnowContext *s, SubBand *b, IDWTELEM *src, int stride){
1305     const int w= b->width;
1306     const int h= b->height;
1307     const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);
1308     const int qmul= ff_qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);
1309     const int qadd= (s->qbias*qmul)>>QBIAS_SHIFT;
1310     int x,y;
1311
1312     if(s->qlog == LOSSLESS_QLOG) return;
1313
1314     for(y=0; y<h; y++){
1315         for(x=0; x<w; x++){
1316             int i= src[x + y*stride];
1317             if(i<0){
1318                 src[x + y*stride]= -((-i*qmul + qadd)>>(QEXPSHIFT)); //FIXME try different bias
1319             }else if(i>0){
1320                 src[x + y*stride]=  (( i*qmul + qadd)>>(QEXPSHIFT));
1321             }
1322         }
1323     }
1324 }
1325
1326 static void decorrelate(SnowContext *s, SubBand *b, IDWTELEM *src, int stride, int inverse, int use_median){
1327     const int w= b->width;
1328     const int h= b->height;
1329     int x,y;
1330
1331     for(y=h-1; y>=0; y--){
1332         for(x=w-1; x>=0; x--){
1333             int i= x + y*stride;
1334
1335             if(x){
1336                 if(use_median){
1337                     if(y && x+1<w) src[i] -= mid_pred(src[i - 1], src[i - stride], src[i - stride + 1]);
1338                     else  src[i] -= src[i - 1];
1339                 }else{
1340                     if(y) src[i] -= mid_pred(src[i - 1], src[i - stride], src[i - 1] + src[i - stride] - src[i - 1 - stride]);
1341                     else  src[i] -= src[i - 1];
1342                 }
1343             }else{
1344                 if(y) src[i] -= src[i - stride];
1345             }
1346         }
1347     }
1348 }
1349
1350 static void correlate(SnowContext *s, SubBand *b, IDWTELEM *src, int stride, int inverse, int use_median){
1351     const int w= b->width;
1352     const int h= b->height;
1353     int x,y;
1354
1355     for(y=0; y<h; y++){
1356         for(x=0; x<w; x++){
1357             int i= x + y*stride;
1358
1359             if(x){
1360                 if(use_median){
1361                     if(y && x+1<w) src[i] += mid_pred(src[i - 1], src[i - stride], src[i - stride + 1]);
1362                     else  src[i] += src[i - 1];
1363                 }else{
1364                     if(y) src[i] += mid_pred(src[i - 1], src[i - stride], src[i - 1] + src[i - stride] - src[i - 1 - stride]);
1365                     else  src[i] += src[i - 1];
1366                 }
1367             }else{
1368                 if(y) src[i] += src[i - stride];
1369             }
1370         }
1371     }
1372 }
1373
1374 static void encode_qlogs(SnowContext *s){
1375     int plane_index, level, orientation;
1376
1377     for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){
1378         for(level=0; level<s->spatial_decomposition_count; level++){
1379             for(orientation=level ? 1:0; orientation<4; orientation++){
1380                 if(orientation==2) continue;
1381                 put_symbol(&s->c, s->header_state, s->plane[plane_index].band[level][orientation].qlog, 1);
1382             }
1383         }
1384     }
1385 }
1386
1387 static void encode_header(SnowContext *s){
1388     int plane_index, i;
1389     uint8_t kstate[32];
1390
1391     memset(kstate, MID_STATE, sizeof(kstate));
1392
1393     put_rac(&s->c, kstate, s->keyframe);
1394     if(s->keyframe || s->always_reset){
1395         ff_snow_reset_contexts(s);
1396         s->last_spatial_decomposition_type=
1397         s->last_qlog=
1398         s->last_qbias=
1399         s->last_mv_scale=
1400         s->last_block_max_depth= 0;
1401         for(plane_index=0; plane_index<2; plane_index++){
1402             Plane *p= &s->plane[plane_index];
1403             p->last_htaps=0;
1404             p->last_diag_mc=0;
1405             memset(p->last_hcoeff, 0, sizeof(p->last_hcoeff));
1406         }
1407     }
1408     if(s->keyframe){
1409         put_symbol(&s->c, s->header_state, s->version, 0);
1410         put_rac(&s->c, s->header_state, s->always_reset);
1411         put_symbol(&s->c, s->header_state, s->temporal_decomposition_type, 0);
1412         put_symbol(&s->c, s->header_state, s->temporal_decomposition_count, 0);
1413         put_symbol(&s->c, s->header_state, s->spatial_decomposition_count, 0);
1414         put_symbol(&s->c, s->header_state, s->colorspace_type, 0);
1415         if (s->nb_planes > 2) {
1416             put_symbol(&s->c, s->header_state, s->chroma_h_shift, 0);
1417             put_symbol(&s->c, s->header_state, s->chroma_v_shift, 0);
1418         }
1419         put_rac(&s->c, s->header_state, s->spatial_scalability);
1420 //        put_rac(&s->c, s->header_state, s->rate_scalability);
1421         put_symbol(&s->c, s->header_state, s->max_ref_frames-1, 0);
1422
1423         encode_qlogs(s);
1424     }
1425
1426     if(!s->keyframe){
1427         int update_mc=0;
1428         for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){
1429             Plane *p= &s->plane[plane_index];
1430             update_mc |= p->last_htaps   != p->htaps;
1431             update_mc |= p->last_diag_mc != p->diag_mc;
1432             update_mc |= !!memcmp(p->last_hcoeff, p->hcoeff, sizeof(p->hcoeff));
1433         }
1434         put_rac(&s->c, s->header_state, update_mc);
1435         if(update_mc){
1436             for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){
1437                 Plane *p= &s->plane[plane_index];
1438                 put_rac(&s->c, s->header_state, p->diag_mc);
1439                 put_symbol(&s->c, s->header_state, p->htaps/2-1, 0);
1440                 for(i= p->htaps/2; i; i--)
1441                     put_symbol(&s->c, s->header_state, FFABS(p->hcoeff[i]), 0);
1442             }
1443         }
1444         if(s->last_spatial_decomposition_count != s->spatial_decomposition_count){
1445             put_rac(&s->c, s->header_state, 1);
1446             put_symbol(&s->c, s->header_state, s->spatial_decomposition_count, 0);
1447             encode_qlogs(s);
1448         }else
1449             put_rac(&s->c, s->header_state, 0);
1450     }
1451
1452     put_symbol(&s->c, s->header_state, s->spatial_decomposition_type - s->last_spatial_decomposition_type, 1);
1453     put_symbol(&s->c, s->header_state, s->qlog            - s->last_qlog    , 1);
1454     put_symbol(&s->c, s->header_state, s->mv_scale        - s->last_mv_scale, 1);
1455     put_symbol(&s->c, s->header_state, s->qbias           - s->last_qbias   , 1);
1456     put_symbol(&s->c, s->header_state, s->block_max_depth - s->last_block_max_depth, 1);
1457
1458 }
1459
1460 static void update_last_header_values(SnowContext *s){
1461     int plane_index;
1462
1463     if(!s->keyframe){
1464         for(plane_index=0; plane_index<2; plane_index++){
1465             Plane *p= &s->plane[plane_index];
1466             p->last_diag_mc= p->diag_mc;
1467             p->last_htaps  = p->htaps;
1468             memcpy(p->last_hcoeff, p->hcoeff, sizeof(p->hcoeff));
1469         }
1470     }
1471
1472     s->last_spatial_decomposition_type  = s->spatial_decomposition_type;
1473     s->last_qlog                        = s->qlog;
1474     s->last_qbias                       = s->qbias;
1475     s->last_mv_scale                    = s->mv_scale;
1476     s->last_block_max_depth             = s->block_max_depth;
1477     s->last_spatial_decomposition_count = s->spatial_decomposition_count;
1478 }
1479
1480 static int qscale2qlog(int qscale){
1481     return lrint(QROOT*log2(qscale / (float)FF_QP2LAMBDA))
1482            + 61*QROOT/8; ///< 64 > 60
1483 }
1484
1485 static int ratecontrol_1pass(SnowContext *s, AVFrame *pict)
1486 {
1487     /* Estimate the frame's complexity as a sum of weighted dwt coefficients.
1488      * FIXME we know exact mv bits at this point,
1489      * but ratecontrol isn't set up to include them. */
1490     uint32_t coef_sum= 0;
1491     int level, orientation, delta_qlog;
1492
1493     for(level=0; level<s->spatial_decomposition_count; level++){
1494         for(orientation=level ? 1 : 0; orientation<4; orientation++){
1495             SubBand *b= &s->plane[0].band[level][orientation];
1496             IDWTELEM *buf= b->ibuf;
1497             const int w= b->width;
1498             const int h= b->height;
1499             const int stride= b->stride;
1500             const int qlog= av_clip(2*QROOT + b->qlog, 0, QROOT*16);
1501             const int qmul= ff_qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);
1502             const int qdiv= (1<<16)/qmul;
1503             int x, y;
1504             //FIXME this is ugly
1505             for(y=0; y<h; y++)
1506                 for(x=0; x<w; x++)
1507                     buf[x+y*stride]= b->buf[x+y*stride];
1508             if(orientation==0)
1509                 decorrelate(s, b, buf, stride, 1, 0);
1510             for(y=0; y<h; y++)
1511                 for(x=0; x<w; x++)
1512                     coef_sum+= abs(buf[x+y*stride]) * qdiv >> 16;
1513         }
1514     }
1515
1516     /* ugly, ratecontrol just takes a sqrt again */
1517     av_assert0(coef_sum < INT_MAX);
1518     coef_sum = (uint64_t)coef_sum * coef_sum >> 16;
1519
1520     if(pict->pict_type == AV_PICTURE_TYPE_I){
1521         s->m.current_picture.mb_var_sum= coef_sum;
1522         s->m.current_picture.mc_mb_var_sum= 0;
1523     }else{
1524         s->m.current_picture.mc_mb_var_sum= coef_sum;
1525         s->m.current_picture.mb_var_sum= 0;
1526     }
1527
1528     pict->quality= ff_rate_estimate_qscale(&s->m, 1);
1529     if (pict->quality < 0)
1530         return INT_MIN;
1531     s->lambda= pict->quality * 3/2;
1532     delta_qlog= qscale2qlog(pict->quality) - s->qlog;
1533     s->qlog+= delta_qlog;
1534     return delta_qlog;
1535 }
1536
1537 static void calculate_visual_weight(SnowContext *s, Plane *p){
1538     int width = p->width;
1539     int height= p->height;
1540     int level, orientation, x, y;
1541
1542     for(level=0; level<s->spatial_decomposition_count; level++){
1543         for(orientation=level ? 1 : 0; orientation<4; orientation++){
1544             SubBand *b= &p->band[level][orientation];
1545             IDWTELEM *ibuf= b->ibuf;
1546             int64_t error=0;
1547
1548             memset(s->spatial_idwt_buffer, 0, sizeof(*s->spatial_idwt_buffer)*width*height);
1549             ibuf[b->width/2 + b->height/2*b->stride]= 256*16;
1550             ff_spatial_idwt(s->spatial_idwt_buffer, s->temp_idwt_buffer, width, height, width, s->spatial_decomposition_type, s->spatial_decomposition_count);
1551             for(y=0; y<height; y++){
1552                 for(x=0; x<width; x++){
1553                     int64_t d= s->spatial_idwt_buffer[x + y*width]*16;
1554                     error += d*d;
1555                 }
1556             }
1557
1558             b->qlog= (int)(QROOT * log2(352256.0/sqrt(error)) + 0.5);
1559         }
1560     }
1561 }
1562
1563 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1564                         const AVFrame *pict, int *got_packet)
1565 {
1566     SnowContext *s = avctx->priv_data;
1567     RangeCoder * const c= &s->c;
1568     AVFrame *pic;
1569     const int width= s->avctx->width;
1570     const int height= s->avctx->height;
1571     int level, orientation, plane_index, i, y, ret;
1572     uint8_t rc_header_bak[sizeof(s->header_state)];
1573     uint8_t rc_block_bak[sizeof(s->block_state)];
1574
1575     if ((ret = ff_alloc_packet2(avctx, pkt, s->b_width*s->b_height*MB_SIZE*MB_SIZE*3 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
1576         return ret;
1577
1578     ff_init_range_encoder(c, pkt->data, pkt->size);
1579     ff_build_rac_states(c, (1LL<<32)/20, 256-8);
1580
1581     for(i=0; i < s->nb_planes; i++){
1582         int hshift= i ? s->chroma_h_shift : 0;
1583         int vshift= i ? s->chroma_v_shift : 0;
1584         for(y=0; y<AV_CEIL_RSHIFT(height, vshift); y++)
1585             memcpy(&s->input_picture->data[i][y * s->input_picture->linesize[i]],
1586                    &pict->data[i][y * pict->linesize[i]],
1587                    AV_CEIL_RSHIFT(width, hshift));
1588         s->mpvencdsp.draw_edges(s->input_picture->data[i], s->input_picture->linesize[i],
1589                                 AV_CEIL_RSHIFT(width, hshift), AV_CEIL_RSHIFT(height, vshift),
1590                                 EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
1591                                 EDGE_TOP | EDGE_BOTTOM);
1592
1593     }
1594     emms_c();
1595     pic = s->input_picture;
1596     pic->pict_type = pict->pict_type;
1597     pic->quality = pict->quality;
1598
1599     s->m.picture_number= avctx->frame_number;
1600     if(avctx->flags&AV_CODEC_FLAG_PASS2){
1601         s->m.pict_type = pic->pict_type = s->m.rc_context.entry[avctx->frame_number].new_pict_type;
1602         s->keyframe = pic->pict_type == AV_PICTURE_TYPE_I;
1603         if(!(avctx->flags&AV_CODEC_FLAG_QSCALE)) {
1604             pic->quality = ff_rate_estimate_qscale(&s->m, 0);
1605             if (pic->quality < 0)
1606                 return -1;
1607         }
1608     }else{
1609         s->keyframe= avctx->gop_size==0 || avctx->frame_number % avctx->gop_size == 0;
1610         s->m.pict_type = pic->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
1611     }
1612
1613     if(s->pass1_rc && avctx->frame_number == 0)
1614         pic->quality = 2*FF_QP2LAMBDA;
1615     if (pic->quality) {
1616         s->qlog   = qscale2qlog(pic->quality);
1617         s->lambda = pic->quality * 3/2;
1618     }
1619     if (s->qlog < 0 || (!pic->quality && (avctx->flags & AV_CODEC_FLAG_QSCALE))) {
1620         s->qlog= LOSSLESS_QLOG;
1621         s->lambda = 0;
1622     }//else keep previous frame's qlog until after motion estimation
1623
1624     if (s->current_picture->data[0]
1625 #if FF_API_EMU_EDGE
1626         && !(s->avctx->flags&CODEC_FLAG_EMU_EDGE)
1627 #endif
1628         ) {
1629         int w = s->avctx->width;
1630         int h = s->avctx->height;
1631
1632         s->mpvencdsp.draw_edges(s->current_picture->data[0],
1633                                 s->current_picture->linesize[0], w   , h   ,
1634                                 EDGE_WIDTH  , EDGE_WIDTH  , EDGE_TOP | EDGE_BOTTOM);
1635         if (s->current_picture->data[2]) {
1636             s->mpvencdsp.draw_edges(s->current_picture->data[1],
1637                                     s->current_picture->linesize[1], w>>s->chroma_h_shift, h>>s->chroma_v_shift,
1638                                     EDGE_WIDTH>>s->chroma_h_shift, EDGE_WIDTH>>s->chroma_v_shift, EDGE_TOP | EDGE_BOTTOM);
1639             s->mpvencdsp.draw_edges(s->current_picture->data[2],
1640                                     s->current_picture->linesize[2], w>>s->chroma_h_shift, h>>s->chroma_v_shift,
1641                                     EDGE_WIDTH>>s->chroma_h_shift, EDGE_WIDTH>>s->chroma_v_shift, EDGE_TOP | EDGE_BOTTOM);
1642         }
1643         emms_c();
1644     }
1645
1646     ff_snow_frame_start(s);
1647     av_frame_unref(avctx->coded_frame);
1648     ret = av_frame_ref(avctx->coded_frame, s->current_picture);
1649     if (ret < 0)
1650         return ret;
1651
1652     s->m.current_picture_ptr= &s->m.current_picture;
1653     s->m.current_picture.f = s->current_picture;
1654     s->m.current_picture.f->pts = pict->pts;
1655     if(pic->pict_type == AV_PICTURE_TYPE_P){
1656         int block_width = (width +15)>>4;
1657         int block_height= (height+15)>>4;
1658         int stride= s->current_picture->linesize[0];
1659
1660         av_assert0(s->current_picture->data[0]);
1661         av_assert0(s->last_picture[0]->data[0]);
1662
1663         s->m.avctx= s->avctx;
1664         s->m.   last_picture.f = s->last_picture[0];
1665         s->m.    new_picture.f = s->input_picture;
1666         s->m.   last_picture_ptr= &s->m.   last_picture;
1667         s->m.linesize = stride;
1668         s->m.uvlinesize= s->current_picture->linesize[1];
1669         s->m.width = width;
1670         s->m.height= height;
1671         s->m.mb_width = block_width;
1672         s->m.mb_height= block_height;
1673         s->m.mb_stride=   s->m.mb_width+1;
1674         s->m.b8_stride= 2*s->m.mb_width+1;
1675         s->m.f_code=1;
1676         s->m.pict_type = pic->pict_type;
1677 #if FF_API_MOTION_EST
1678         s->m.me_method= s->avctx->me_method;
1679 #endif
1680         s->m.motion_est= s->motion_est;
1681         s->m.me.scene_change_score=0;
1682         s->m.me.dia_size = avctx->dia_size;
1683         s->m.quarter_sample= (s->avctx->flags & AV_CODEC_FLAG_QPEL)!=0;
1684         s->m.out_format= FMT_H263;
1685         s->m.unrestricted_mv= 1;
1686
1687         s->m.lambda = s->lambda;
1688         s->m.qscale= (s->m.lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
1689         s->lambda2= s->m.lambda2= (s->m.lambda*s->m.lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
1690
1691         s->m.mecc= s->mecc; //move
1692         s->m.qdsp= s->qdsp; //move
1693         s->m.hdsp = s->hdsp;
1694         ff_init_me(&s->m);
1695         s->hdsp = s->m.hdsp;
1696         s->mecc= s->m.mecc;
1697     }
1698
1699     if(s->pass1_rc){
1700         memcpy(rc_header_bak, s->header_state, sizeof(s->header_state));
1701         memcpy(rc_block_bak, s->block_state, sizeof(s->block_state));
1702     }
1703
1704 redo_frame:
1705
1706     s->spatial_decomposition_count= 5;
1707
1708     while(   !(width >>(s->chroma_h_shift + s->spatial_decomposition_count))
1709           || !(height>>(s->chroma_v_shift + s->spatial_decomposition_count)))
1710         s->spatial_decomposition_count--;
1711
1712     if (s->spatial_decomposition_count <= 0) {
1713         av_log(avctx, AV_LOG_ERROR, "Resolution too low\n");
1714         return AVERROR(EINVAL);
1715     }
1716
1717     s->m.pict_type = pic->pict_type;
1718     s->qbias = pic->pict_type == AV_PICTURE_TYPE_P ? 2 : 0;
1719
1720     ff_snow_common_init_after_header(avctx);
1721
1722     if(s->last_spatial_decomposition_count != s->spatial_decomposition_count){
1723         for(plane_index=0; plane_index < s->nb_planes; plane_index++){
1724             calculate_visual_weight(s, &s->plane[plane_index]);
1725         }
1726     }
1727
1728     encode_header(s);
1729     s->m.misc_bits = 8*(s->c.bytestream - s->c.bytestream_start);
1730     encode_blocks(s, 1);
1731     s->m.mv_bits = 8*(s->c.bytestream - s->c.bytestream_start) - s->m.misc_bits;
1732
1733     for(plane_index=0; plane_index < s->nb_planes; plane_index++){
1734         Plane *p= &s->plane[plane_index];
1735         int w= p->width;
1736         int h= p->height;
1737         int x, y;
1738 //        int bits= put_bits_count(&s->c.pb);
1739
1740         if (!s->memc_only) {
1741             //FIXME optimize
1742             if(pict->data[plane_index]) //FIXME gray hack
1743                 for(y=0; y<h; y++){
1744                     for(x=0; x<w; x++){
1745                         s->spatial_idwt_buffer[y*w + x]= pict->data[plane_index][y*pict->linesize[plane_index] + x]<<FRAC_BITS;
1746                     }
1747                 }
1748             predict_plane(s, s->spatial_idwt_buffer, plane_index, 0);
1749
1750 #if FF_API_PRIVATE_OPT
1751 FF_DISABLE_DEPRECATION_WARNINGS
1752             if(s->avctx->scenechange_threshold)
1753                 s->scenechange_threshold = s->avctx->scenechange_threshold;
1754 FF_ENABLE_DEPRECATION_WARNINGS
1755 #endif
1756
1757             if(   plane_index==0
1758                && pic->pict_type == AV_PICTURE_TYPE_P
1759                && !(avctx->flags&AV_CODEC_FLAG_PASS2)
1760                && s->m.me.scene_change_score > s->scenechange_threshold){
1761                 ff_init_range_encoder(c, pkt->data, pkt->size);
1762                 ff_build_rac_states(c, (1LL<<32)/20, 256-8);
1763                 pic->pict_type= AV_PICTURE_TYPE_I;
1764                 s->keyframe=1;
1765                 s->current_picture->key_frame=1;
1766                 goto redo_frame;
1767             }
1768
1769             if(s->qlog == LOSSLESS_QLOG){
1770                 for(y=0; y<h; y++){
1771                     for(x=0; x<w; x++){
1772                         s->spatial_dwt_buffer[y*w + x]= (s->spatial_idwt_buffer[y*w + x] + (1<<(FRAC_BITS-1))-1)>>FRAC_BITS;
1773                     }
1774                 }
1775             }else{
1776                 for(y=0; y<h; y++){
1777                     for(x=0; x<w; x++){
1778                         s->spatial_dwt_buffer[y*w + x]=s->spatial_idwt_buffer[y*w + x]<<ENCODER_EXTRA_BITS;
1779                     }
1780                 }
1781             }
1782
1783             ff_spatial_dwt(s->spatial_dwt_buffer, s->temp_dwt_buffer, w, h, w, s->spatial_decomposition_type, s->spatial_decomposition_count);
1784
1785             if(s->pass1_rc && plane_index==0){
1786                 int delta_qlog = ratecontrol_1pass(s, pic);
1787                 if (delta_qlog <= INT_MIN)
1788                     return -1;
1789                 if(delta_qlog){
1790                     //reordering qlog in the bitstream would eliminate this reset
1791                     ff_init_range_encoder(c, pkt->data, pkt->size);
1792                     memcpy(s->header_state, rc_header_bak, sizeof(s->header_state));
1793                     memcpy(s->block_state, rc_block_bak, sizeof(s->block_state));
1794                     encode_header(s);
1795                     encode_blocks(s, 0);
1796                 }
1797             }
1798
1799             for(level=0; level<s->spatial_decomposition_count; level++){
1800                 for(orientation=level ? 1 : 0; orientation<4; orientation++){
1801                     SubBand *b= &p->band[level][orientation];
1802
1803                     quantize(s, b, b->ibuf, b->buf, b->stride, s->qbias);
1804                     if(orientation==0)
1805                         decorrelate(s, b, b->ibuf, b->stride, pic->pict_type == AV_PICTURE_TYPE_P, 0);
1806                     if (!s->no_bitstream)
1807                     encode_subband(s, b, b->ibuf, b->parent ? b->parent->ibuf : NULL, b->stride, orientation);
1808                     av_assert0(b->parent==NULL || b->parent->stride == b->stride*2);
1809                     if(orientation==0)
1810                         correlate(s, b, b->ibuf, b->stride, 1, 0);
1811                 }
1812             }
1813
1814             for(level=0; level<s->spatial_decomposition_count; level++){
1815                 for(orientation=level ? 1 : 0; orientation<4; orientation++){
1816                     SubBand *b= &p->band[level][orientation];
1817
1818                     dequantize(s, b, b->ibuf, b->stride);
1819                 }
1820             }
1821
1822             ff_spatial_idwt(s->spatial_idwt_buffer, s->temp_idwt_buffer, w, h, w, s->spatial_decomposition_type, s->spatial_decomposition_count);
1823             if(s->qlog == LOSSLESS_QLOG){
1824                 for(y=0; y<h; y++){
1825                     for(x=0; x<w; x++){
1826                         s->spatial_idwt_buffer[y*w + x]<<=FRAC_BITS;
1827                     }
1828                 }
1829             }
1830             predict_plane(s, s->spatial_idwt_buffer, plane_index, 1);
1831         }else{
1832             //ME/MC only
1833             if(pic->pict_type == AV_PICTURE_TYPE_I){
1834                 for(y=0; y<h; y++){
1835                     for(x=0; x<w; x++){
1836                         s->current_picture->data[plane_index][y*s->current_picture->linesize[plane_index] + x]=
1837                             pict->data[plane_index][y*pict->linesize[plane_index] + x];
1838                     }
1839                 }
1840             }else{
1841                 memset(s->spatial_idwt_buffer, 0, sizeof(IDWTELEM)*w*h);
1842                 predict_plane(s, s->spatial_idwt_buffer, plane_index, 1);
1843             }
1844         }
1845         if(s->avctx->flags&AV_CODEC_FLAG_PSNR){
1846             int64_t error= 0;
1847
1848             if(pict->data[plane_index]) //FIXME gray hack
1849                 for(y=0; y<h; y++){
1850                     for(x=0; x<w; x++){
1851                         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];
1852                         error += d*d;
1853                     }
1854                 }
1855             s->avctx->error[plane_index] += error;
1856             s->encoding_error[plane_index] = error;
1857         }
1858
1859     }
1860     emms_c();
1861
1862     update_last_header_values(s);
1863
1864     ff_snow_release_buffer(avctx);
1865
1866     s->current_picture->coded_picture_number = avctx->frame_number;
1867     s->current_picture->pict_type = pic->pict_type;
1868     s->current_picture->quality = pic->quality;
1869     s->m.frame_bits = 8*(s->c.bytestream - s->c.bytestream_start);
1870     s->m.p_tex_bits = s->m.frame_bits - s->m.misc_bits - s->m.mv_bits;
1871     s->m.current_picture.f->display_picture_number =
1872     s->m.current_picture.f->coded_picture_number   = avctx->frame_number;
1873     s->m.current_picture.f->quality                = pic->quality;
1874     s->m.total_bits += 8*(s->c.bytestream - s->c.bytestream_start);
1875     if(s->pass1_rc)
1876         if (ff_rate_estimate_qscale(&s->m, 0) < 0)
1877             return -1;
1878     if(avctx->flags&AV_CODEC_FLAG_PASS1)
1879         ff_write_pass1_stats(&s->m);
1880     s->m.last_pict_type = s->m.pict_type;
1881     avctx->frame_bits = s->m.frame_bits;
1882     avctx->mv_bits = s->m.mv_bits;
1883     avctx->misc_bits = s->m.misc_bits;
1884     avctx->p_tex_bits = s->m.p_tex_bits;
1885
1886     emms_c();
1887
1888     ff_side_data_set_encoder_stats(pkt, s->current_picture->quality,
1889                                    s->encoding_error,
1890                                    (s->avctx->flags&AV_CODEC_FLAG_PSNR) ? 4 : 0,
1891                                    s->current_picture->pict_type);
1892
1893 #if FF_API_ERROR_FRAME
1894 FF_DISABLE_DEPRECATION_WARNINGS
1895     memcpy(s->current_picture->error, s->encoding_error, sizeof(s->encoding_error));
1896 FF_ENABLE_DEPRECATION_WARNINGS
1897 #endif
1898
1899     pkt->size = ff_rac_terminate(c);
1900     if (s->current_picture->key_frame)
1901         pkt->flags |= AV_PKT_FLAG_KEY;
1902     *got_packet = 1;
1903
1904     return 0;
1905 }
1906
1907 static av_cold int encode_end(AVCodecContext *avctx)
1908 {
1909     SnowContext *s = avctx->priv_data;
1910
1911     ff_snow_common_end(s);
1912     ff_rate_control_uninit(&s->m);
1913     av_frame_free(&s->input_picture);
1914     av_freep(&avctx->stats_out);
1915
1916     return 0;
1917 }
1918
1919 #define OFFSET(x) offsetof(SnowContext, x)
1920 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1921 static const AVOption options[] = {
1922     FF_MPV_COMMON_OPTS
1923     { "iter",           NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_ME_ITER }, 0, 0, FF_MPV_OPT_FLAGS, "motion_est" },
1924     { "memc_only",      "Only do ME/MC (I frames -> ref, P frame -> ME+MC).",   OFFSET(memc_only), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1925     { "no_bitstream",   "Skip final bitstream writeout.",                    OFFSET(no_bitstream), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1926     { "intra_penalty",  "Penalty for intra blocks in block decission",      OFFSET(intra_penalty), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
1927     { "iterative_dia_size",  "Dia size for the iterative ME",          OFFSET(iterative_dia_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
1928     { "sc_threshold",   "Scene change threshold",                   OFFSET(scenechange_threshold), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, VE },
1929     { "pred",           "Spatial decomposition type",                                OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, DWT_97, DWT_53, VE, "pred" },
1930         { "dwt97", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
1931         { "dwt53", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "pred" },
1932     { NULL },
1933 };
1934
1935 static const AVClass snowenc_class = {
1936     .class_name = "snow encoder",
1937     .item_name  = av_default_item_name,
1938     .option     = options,
1939     .version    = LIBAVUTIL_VERSION_INT,
1940 };
1941
1942 AVCodec ff_snow_encoder = {
1943     .name           = "snow",
1944     .long_name      = NULL_IF_CONFIG_SMALL("Snow"),
1945     .type           = AVMEDIA_TYPE_VIDEO,
1946     .id             = AV_CODEC_ID_SNOW,
1947     .priv_data_size = sizeof(SnowContext),
1948     .init           = encode_init,
1949     .encode2        = encode_frame,
1950     .close          = encode_end,
1951     .pix_fmts       = (const enum AVPixelFormat[]){
1952         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV444P,
1953         AV_PIX_FMT_GRAY8,
1954         AV_PIX_FMT_NONE
1955     },
1956     .priv_class     = &snowenc_class,
1957     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
1958                       FF_CODEC_CAP_INIT_CLEANUP,
1959 };