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