OSDN Git Service

Merge commit '142e76f1055de5dde44696e71a5f63f2cb11dedf'
[coroid/ffmpeg_saccubus.git] / libavcodec / mpegvideo_enc.c
1 /*
2  * The simplest mpeg encoder (well, it was the simplest!)
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 /**
26  * @file
27  * The simplest mpeg encoder (well, it was the simplest!).
28  */
29
30 #include "libavutil/intmath.h"
31 #include "libavutil/mathematics.h"
32 #include "avcodec.h"
33 #include "dsputil.h"
34 #include "mpegvideo.h"
35 #include "mpegvideo_common.h"
36 #include "h263.h"
37 #include "mjpegenc.h"
38 #include "msmpeg4.h"
39 #include "faandct.h"
40 #include "thread.h"
41 #include "aandcttab.h"
42 #include "flv.h"
43 #include "mpeg4video.h"
44 #include "internal.h"
45 #include <limits.h>
46
47 //#undef NDEBUG
48 //#include <assert.h>
49
50 static int encode_picture(MpegEncContext *s, int picture_number);
51 static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
52 static int sse_mb(MpegEncContext *s);
53 static void denoise_dct_c(MpegEncContext *s, DCTELEM *block);
54 static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
55
56 /* enable all paranoid tests for rounding, overflows, etc... */
57 //#define PARANOID
58
59 //#define DEBUG
60
61 static uint8_t default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
62 static uint8_t default_fcode_tab[MAX_MV*2+1];
63
64 void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
65                            const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
66 {
67     int qscale;
68     int shift=0;
69
70     for(qscale=qmin; qscale<=qmax; qscale++){
71         int i;
72         if (dsp->fdct == ff_jpeg_fdct_islow
73 #ifdef FAAN_POSTSCALE
74             || dsp->fdct == ff_faandct
75 #endif
76             ) {
77             for(i=0;i<64;i++) {
78                 const int j= dsp->idct_permutation[i];
79                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
80                 /* 19952             <= ff_aanscales[i] * qscale * quant_matrix[i]               <= 249205026 */
81                 /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1 << 36) / 249205026 */
82                 /* 3444240           >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
83
84                 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
85                                 (qscale * quant_matrix[j]));
86             }
87         } else if (dsp->fdct == fdct_ifast
88 #ifndef FAAN_POSTSCALE
89                    || dsp->fdct == ff_faandct
90 #endif
91                    ) {
92             for(i=0;i<64;i++) {
93                 const int j= dsp->idct_permutation[i];
94                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
95                 /* 19952             <= ff_aanscales[i] * qscale * quant_matrix[i]               <= 249205026 */
96                 /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
97                 /* 3444240           >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
98
99                 qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
100                                 (ff_aanscales[i] * qscale * quant_matrix[j]));
101             }
102         } else {
103             for(i=0;i<64;i++) {
104                 const int j= dsp->idct_permutation[i];
105                 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
106                    So 16           <= qscale * quant_matrix[i]             <= 7905
107                    so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
108                    so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
109                 */
110                 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
111 //                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
112                 qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
113
114                 if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
115                 qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
116             }
117         }
118
119         for(i=intra; i<64; i++){
120             int64_t max= 8191;
121             if (dsp->fdct == fdct_ifast
122 #ifndef FAAN_POSTSCALE
123                    || dsp->fdct == ff_faandct
124 #endif
125                    ) {
126                 max = (8191LL*ff_aanscales[i]) >> 14;
127             }
128             while(((max * qmat[qscale][i]) >> shift) > INT_MAX){
129                 shift++;
130             }
131         }
132     }
133     if(shift){
134         av_log(NULL, AV_LOG_INFO, "Warning, QMAT_SHIFT is larger than %d, overflows possible\n", QMAT_SHIFT - shift);
135     }
136 }
137
138 static inline void update_qscale(MpegEncContext *s){
139     s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
140     s->qscale= av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
141
142     s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
143 }
144
145 void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix){
146     int i;
147
148     if(matrix){
149         put_bits(pb, 1, 1);
150         for(i=0;i<64;i++) {
151             put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
152         }
153     }else
154         put_bits(pb, 1, 0);
155 }
156
157 /**
158  * init s->current_picture.qscale_table from s->lambda_table
159  */
160 void ff_init_qscale_tab(MpegEncContext *s){
161     int8_t * const qscale_table= s->current_picture.qscale_table;
162     int i;
163
164     for(i=0; i<s->mb_num; i++){
165         unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
166         int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
167         qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
168     }
169 }
170
171 static void copy_picture_attributes(MpegEncContext *s, AVFrame *dst, AVFrame *src){
172     int i;
173
174     dst->pict_type              = src->pict_type;
175     dst->quality                = src->quality;
176     dst->coded_picture_number   = src->coded_picture_number;
177     dst->display_picture_number = src->display_picture_number;
178 //    dst->reference              = src->reference;
179     dst->pts                    = src->pts;
180     dst->interlaced_frame       = src->interlaced_frame;
181     dst->top_field_first        = src->top_field_first;
182
183     if(s->avctx->me_threshold){
184         if(!src->motion_val[0])
185             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_val not set!\n");
186         if(!src->mb_type)
187             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.mb_type not set!\n");
188         if(!src->ref_index[0])
189             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.ref_index not set!\n");
190         if(src->motion_subsample_log2 != dst->motion_subsample_log2)
191             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_subsample_log2 doesn't match! (%d!=%d)\n",
192             src->motion_subsample_log2, dst->motion_subsample_log2);
193
194         memcpy(dst->mb_type, src->mb_type, s->mb_stride * s->mb_height * sizeof(dst->mb_type[0]));
195
196         for(i=0; i<2; i++){
197             int stride= ((16*s->mb_width )>>src->motion_subsample_log2) + 1;
198             int height= ((16*s->mb_height)>>src->motion_subsample_log2);
199
200             if(src->motion_val[i] && src->motion_val[i] != dst->motion_val[i]){
201                 memcpy(dst->motion_val[i], src->motion_val[i], 2*stride*height*sizeof(int16_t));
202             }
203             if(src->ref_index[i] && src->ref_index[i] != dst->ref_index[i]){
204                 memcpy(dst->ref_index[i], src->ref_index[i], s->mb_stride*4*s->mb_height*sizeof(int8_t));
205             }
206         }
207     }
208 }
209
210 static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
211 #define COPY(a) dst->a= src->a
212     COPY(pict_type);
213     COPY(current_picture);
214     COPY(f_code);
215     COPY(b_code);
216     COPY(qscale);
217     COPY(lambda);
218     COPY(lambda2);
219     COPY(picture_in_gop_number);
220     COPY(gop_picture_number);
221     COPY(frame_pred_frame_dct); //FIXME don't set in encode_header
222     COPY(progressive_frame); //FIXME don't set in encode_header
223     COPY(partitioned_frame); //FIXME don't set in encode_header
224 #undef COPY
225 }
226
227 /**
228  * sets the given MpegEncContext to defaults for encoding.
229  * the changed fields will not depend upon the prior state of the MpegEncContext.
230  */
231 static void MPV_encode_defaults(MpegEncContext *s){
232     int i;
233     MPV_common_defaults(s);
234
235     for(i=-16; i<16; i++){
236         default_fcode_tab[i + MAX_MV]= 1;
237     }
238     s->me.mv_penalty= default_mv_penalty;
239     s->fcode_tab= default_fcode_tab;
240 }
241
242 /* init video encoder */
243 av_cold int MPV_encode_init(AVCodecContext *avctx)
244 {
245     MpegEncContext *s = avctx->priv_data;
246     int i;
247     int chroma_h_shift, chroma_v_shift;
248
249     MPV_encode_defaults(s);
250
251     switch (avctx->codec_id) {
252     case CODEC_ID_MPEG2VIDEO:
253         if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){
254             av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");
255             return -1;
256         }
257         break;
258     case CODEC_ID_LJPEG:
259         if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_YUVJ444P && avctx->pix_fmt != PIX_FMT_BGRA &&
260            ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P && avctx->pix_fmt != PIX_FMT_YUV444P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
261             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in LJPEG\n");
262             return -1;
263         }
264         break;
265     case CODEC_ID_MJPEG:
266         if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P &&
267            ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
268             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
269             return -1;
270         }
271         break;
272     default:
273         if(avctx->pix_fmt != PIX_FMT_YUV420P){
274             av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
275             return -1;
276         }
277     }
278
279     switch (avctx->pix_fmt) {
280     case PIX_FMT_YUVJ422P:
281     case PIX_FMT_YUV422P:
282         s->chroma_format = CHROMA_422;
283         break;
284     case PIX_FMT_YUVJ420P:
285     case PIX_FMT_YUV420P:
286     default:
287         s->chroma_format = CHROMA_420;
288         break;
289     }
290
291     s->bit_rate = avctx->bit_rate;
292     s->width = avctx->width;
293     s->height = avctx->height;
294     if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){
295         av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
296         avctx->gop_size=600;
297     }
298     s->gop_size = avctx->gop_size;
299     s->avctx = avctx;
300     s->flags= avctx->flags;
301     s->flags2= avctx->flags2;
302     s->max_b_frames= avctx->max_b_frames;
303     s->codec_id= avctx->codec->id;
304     s->luma_elim_threshold  = avctx->luma_elim_threshold;
305     s->chroma_elim_threshold= avctx->chroma_elim_threshold;
306     s->strict_std_compliance= avctx->strict_std_compliance;
307     s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
308     s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
309     s->mpeg_quant= avctx->mpeg_quant;
310     s->rtp_mode= !!avctx->rtp_payload_size;
311     s->intra_dc_precision= avctx->intra_dc_precision;
312     s->user_specified_pts = AV_NOPTS_VALUE;
313
314     if (s->gop_size <= 1) {
315         s->intra_only = 1;
316         s->gop_size = 12;
317     } else {
318         s->intra_only = 0;
319     }
320
321     s->me_method = avctx->me_method;
322
323     /* Fixed QSCALE */
324     s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
325
326     s->adaptive_quant= (   s->avctx->lumi_masking
327                         || s->avctx->dark_masking
328                         || s->avctx->temporal_cplx_masking
329                         || s->avctx->spatial_cplx_masking
330                         || s->avctx->p_masking
331                         || s->avctx->border_masking
332                         || (s->flags&CODEC_FLAG_QP_RD))
333                        && !s->fixed_qscale;
334
335     s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
336     s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
337     s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
338     s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);
339     s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);
340
341     if(avctx->rc_max_rate && !avctx->rc_buffer_size){
342         av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
343         return -1;
344     }
345
346     if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
347         av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
348     }
349
350     if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){
351         av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
352         return -1;
353     }
354
355     if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){
356         av_log(avctx, AV_LOG_ERROR, "bitrate above max bitrate\n");
357         return -1;
358     }
359
360     if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){
361         av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
362     }
363
364     if(avctx->rc_buffer_size && avctx->bit_rate*(int64_t)avctx->time_base.num > avctx->rc_buffer_size * (int64_t)avctx->time_base.den){
365         av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
366         return -1;
367     }
368
369     if(!s->fixed_qscale && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
370         av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
371         return -1;
372     }
373
374     if(   s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate
375        && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)
376        && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){
377
378         av_log(avctx, AV_LOG_INFO, "Warning vbv_delay will be set to 0xFFFF (=VBR) as the specified vbv buffer is too large for the given bitrate!\n");
379     }
380
381     if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4
382        && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
383         av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
384         return -1;
385     }
386
387     if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
388         av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");
389         return -1;
390     }
391
392     if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
393         av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
394         return -1;
395     }
396
397     if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
398         av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
399         return -1;
400     }
401
402     if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
403         av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
404         return -1;
405     }
406
407     if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
408         av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
409         return -1;
410     }
411
412     if ((s->codec_id == CODEC_ID_MPEG4 || s->codec_id == CODEC_ID_H263 ||
413          s->codec_id == CODEC_ID_H263P) &&
414         (avctx->sample_aspect_ratio.num > 255 || avctx->sample_aspect_ratio.den > 255)) {
415         av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
416                avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
417         return -1;
418     }
419
420     if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))
421        && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){
422         av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
423         return -1;
424     }
425
426     if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
427         av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");
428         return -1;
429     }
430
431     if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){
432         av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
433         return -1;
434     }
435
436     if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
437         av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
438         return -1;
439     }
440
441     if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
442         av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");
443         return -1;
444     }
445
446     if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){
447         av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");
448         return -1;
449     }
450
451     if(s->flags & CODEC_FLAG_LOW_DELAY){
452         if (s->codec_id != CODEC_ID_MPEG2VIDEO){
453             av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");
454             return -1;
455         }
456         if (s->max_b_frames != 0){
457             av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");
458             return -1;
459         }
460     }
461
462     if(s->q_scale_type == 1){
463         if(s->codec_id != CODEC_ID_MPEG2VIDEO){
464             av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");
465             return -1;
466         }
467         if(avctx->qmax > 12){
468             av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");
469             return -1;
470         }
471     }
472
473     if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4
474        && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO
475        && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
476         av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
477         return -1;
478     }
479
480     if(s->avctx->thread_count < 1){
481         av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");
482         return -1;
483     }
484
485     if(s->avctx->thread_count > 1)
486         s->rtp_mode= 1;
487
488     if(!avctx->time_base.den || !avctx->time_base.num){
489         av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
490         return -1;
491     }
492
493     i= (INT_MAX/2+128)>>8;
494     if(avctx->me_threshold >= i){
495         av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);
496         return -1;
497     }
498     if(avctx->mb_threshold >= i){
499         av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);
500         return -1;
501     }
502
503     if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){
504         av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");
505         avctx->b_frame_strategy = 0;
506     }
507
508     i= av_gcd(avctx->time_base.den, avctx->time_base.num);
509     if(i > 1){
510         av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
511         avctx->time_base.den /= i;
512         avctx->time_base.num /= i;
513 //        return -1;
514     }
515
516     if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO || s->codec_id==CODEC_ID_MJPEG){
517         s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
518         s->inter_quant_bias= 0;
519     }else{
520         s->intra_quant_bias=0;
521         s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
522     }
523
524     if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
525         s->intra_quant_bias= avctx->intra_quant_bias;
526     if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
527         s->inter_quant_bias= avctx->inter_quant_bias;
528
529     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
530
531     if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
532         av_log(avctx, AV_LOG_ERROR, "timebase %d/%d not supported by MPEG 4 standard, "
533                "the maximum admitted value for the timebase denominator is %d\n",
534                s->avctx->time_base.num, s->avctx->time_base.den, (1<<16)-1);
535         return -1;
536     }
537     s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
538
539     switch(avctx->codec->id) {
540     case CODEC_ID_MPEG1VIDEO:
541         s->out_format = FMT_MPEG1;
542         s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
543         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
544         break;
545     case CODEC_ID_MPEG2VIDEO:
546         s->out_format = FMT_MPEG1;
547         s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
548         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
549         s->rtp_mode= 1;
550         break;
551     case CODEC_ID_LJPEG:
552     case CODEC_ID_MJPEG:
553         s->out_format = FMT_MJPEG;
554         s->intra_only = 1; /* force intra only for jpeg */
555         if(avctx->codec->id == CODEC_ID_LJPEG && avctx->pix_fmt == PIX_FMT_BGRA){
556             s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
557             s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
558             s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
559         }else{
560             s->mjpeg_vsample[0] = 2;
561             s->mjpeg_vsample[1] = 2>>chroma_v_shift;
562             s->mjpeg_vsample[2] = 2>>chroma_v_shift;
563             s->mjpeg_hsample[0] = 2;
564             s->mjpeg_hsample[1] = 2>>chroma_h_shift;
565             s->mjpeg_hsample[2] = 2>>chroma_h_shift;
566         }
567         if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)
568             || ff_mjpeg_encode_init(s) < 0)
569             return -1;
570         avctx->delay=0;
571         s->low_delay=1;
572         break;
573     case CODEC_ID_H261:
574         if (!CONFIG_H261_ENCODER)  return -1;
575         if (ff_h261_get_picture_format(s->width, s->height) < 0) {
576             av_log(avctx, AV_LOG_ERROR, "The specified picture size of %dx%d is not valid for the H.261 codec.\nValid sizes are 176x144, 352x288\n", s->width, s->height);
577             return -1;
578         }
579         s->out_format = FMT_H261;
580         avctx->delay=0;
581         s->low_delay=1;
582         break;
583     case CODEC_ID_H263:
584         if (!CONFIG_H263_ENCODER)  return -1;
585         if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 8) {
586             av_log(avctx, AV_LOG_ERROR, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);
587             return -1;
588         }
589         s->out_format = FMT_H263;
590         s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
591         avctx->delay=0;
592         s->low_delay=1;
593         break;
594     case CODEC_ID_H263P:
595         s->out_format = FMT_H263;
596         s->h263_plus = 1;
597         /* Fx */
598         s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
599         s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;
600         s->modified_quant= s->h263_aic;
601         s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
602         s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
603         s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
604         s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
605         s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
606
607         /* /Fx */
608         /* These are just to be sure */
609         avctx->delay=0;
610         s->low_delay=1;
611         break;
612     case CODEC_ID_FLV1:
613         s->out_format = FMT_H263;
614         s->h263_flv = 2; /* format = 1; 11-bit codes */
615         s->unrestricted_mv = 1;
616         s->rtp_mode=0; /* don't allow GOB */
617         avctx->delay=0;
618         s->low_delay=1;
619         break;
620     case CODEC_ID_RV10:
621         s->out_format = FMT_H263;
622         avctx->delay=0;
623         s->low_delay=1;
624         break;
625     case CODEC_ID_RV20:
626         s->out_format = FMT_H263;
627         avctx->delay=0;
628         s->low_delay=1;
629         s->modified_quant=1;
630         s->h263_aic=1;
631         s->h263_plus=1;
632         s->loop_filter=1;
633         s->unrestricted_mv= 0;
634         break;
635     case CODEC_ID_MPEG4:
636         s->out_format = FMT_H263;
637         s->h263_pred = 1;
638         s->unrestricted_mv = 1;
639         s->low_delay= s->max_b_frames ? 0 : 1;
640         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
641         break;
642     case CODEC_ID_MSMPEG4V2:
643         s->out_format = FMT_H263;
644         s->h263_pred = 1;
645         s->unrestricted_mv = 1;
646         s->msmpeg4_version= 2;
647         avctx->delay=0;
648         s->low_delay=1;
649         break;
650     case CODEC_ID_MSMPEG4V3:
651         s->out_format = FMT_H263;
652         s->h263_pred = 1;
653         s->unrestricted_mv = 1;
654         s->msmpeg4_version= 3;
655         s->flipflop_rounding=1;
656         avctx->delay=0;
657         s->low_delay=1;
658         break;
659     case CODEC_ID_WMV1:
660         s->out_format = FMT_H263;
661         s->h263_pred = 1;
662         s->unrestricted_mv = 1;
663         s->msmpeg4_version= 4;
664         s->flipflop_rounding=1;
665         avctx->delay=0;
666         s->low_delay=1;
667         break;
668     case CODEC_ID_WMV2:
669         s->out_format = FMT_H263;
670         s->h263_pred = 1;
671         s->unrestricted_mv = 1;
672         s->msmpeg4_version= 5;
673         s->flipflop_rounding=1;
674         avctx->delay=0;
675         s->low_delay=1;
676         break;
677     default:
678         return -1;
679     }
680
681     avctx->has_b_frames= !s->low_delay;
682
683     s->encoding = 1;
684
685     s->progressive_frame=
686     s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
687
688     /* init */
689     if (MPV_common_init(s) < 0)
690         return -1;
691
692     if(!s->dct_quantize)
693         s->dct_quantize = dct_quantize_c;
694     if(!s->denoise_dct)
695         s->denoise_dct = denoise_dct_c;
696     s->fast_dct_quantize = s->dct_quantize;
697     if(avctx->trellis)
698         s->dct_quantize = dct_quantize_trellis_c;
699
700     if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
701         s->chroma_qscale_table= ff_h263_chroma_qscale_table;
702
703     s->quant_precision=5;
704
705     ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
706     ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
707
708     if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
709         ff_h261_encode_init(s);
710     if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
711         h263_encode_init(s);
712     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
713         ff_msmpeg4_encode_init(s);
714     if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
715         && s->out_format == FMT_MPEG1)
716         ff_mpeg1_encode_init(s);
717
718     /* init q matrix */
719     for(i=0;i<64;i++) {
720         int j= s->dsp.idct_permutation[i];
721         if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
722             s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
723             s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
724         }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
725             s->intra_matrix[j] =
726             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
727         }else
728         { /* mpeg1/2 */
729             s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
730             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
731         }
732         if(s->avctx->intra_matrix)
733             s->intra_matrix[j] = s->avctx->intra_matrix[i];
734         if(s->avctx->inter_matrix)
735             s->inter_matrix[j] = s->avctx->inter_matrix[i];
736     }
737
738     /* precompute matrix */
739     /* for mjpeg, we do include qscale in the matrix */
740     if (s->out_format != FMT_MJPEG) {
741         ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
742                        s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);
743         ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
744                        s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);
745     }
746
747     if(ff_rate_control_init(s) < 0)
748         return -1;
749
750     return 0;
751 }
752
753 av_cold int MPV_encode_end(AVCodecContext *avctx)
754 {
755     MpegEncContext *s = avctx->priv_data;
756
757     ff_rate_control_uninit(s);
758
759     MPV_common_end(s);
760     if ((CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER) && s->out_format == FMT_MJPEG)
761         ff_mjpeg_encode_close(s);
762
763     av_freep(&avctx->extradata);
764
765     return 0;
766 }
767
768 static int get_sae(uint8_t *src, int ref, int stride){
769     int x,y;
770     int acc=0;
771
772     for(y=0; y<16; y++){
773         for(x=0; x<16; x++){
774             acc+= FFABS(src[x+y*stride] - ref);
775         }
776     }
777
778     return acc;
779 }
780
781 static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
782     int x, y, w, h;
783     int acc=0;
784
785     w= s->width &~15;
786     h= s->height&~15;
787
788     for(y=0; y<h; y+=16){
789         for(x=0; x<w; x+=16){
790             int offset= x + y*stride;
791             int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
792             int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
793             int sae = get_sae(src + offset, mean, stride);
794
795             acc+= sae + 500 < sad;
796         }
797     }
798     return acc;
799 }
800
801
802 static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
803     AVFrame *pic=NULL;
804     int64_t pts;
805     int i;
806     const int encoding_delay= s->max_b_frames;
807     int direct=1;
808
809     if(pic_arg){
810         pts= pic_arg->pts;
811         pic_arg->display_picture_number= s->input_picture_number++;
812
813         if(pts != AV_NOPTS_VALUE){
814             if(s->user_specified_pts != AV_NOPTS_VALUE){
815                 int64_t time= pts;
816                 int64_t last= s->user_specified_pts;
817
818                 if(time <= last){
819                     av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
820                     return -1;
821                 }
822             }
823             s->user_specified_pts= pts;
824         }else{
825             if(s->user_specified_pts != AV_NOPTS_VALUE){
826                 s->user_specified_pts=
827                 pts= s->user_specified_pts + 1;
828                 av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
829             }else{
830                 pts= pic_arg->display_picture_number;
831             }
832         }
833     }
834
835   if(pic_arg){
836     if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
837     if(pic_arg->linesize[0] != s->linesize) direct=0;
838     if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
839     if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
840
841 //    av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
842
843     if(direct){
844         i= ff_find_unused_picture(s, 1);
845
846         pic= (AVFrame*)&s->picture[i];
847         pic->reference= 3;
848
849         for(i=0; i<4; i++){
850             pic->data[i]= pic_arg->data[i];
851             pic->linesize[i]= pic_arg->linesize[i];
852         }
853         if(ff_alloc_picture(s, (Picture*)pic, 1) < 0){
854             return -1;
855         }
856     }else{
857         i= ff_find_unused_picture(s, 0);
858
859         pic= (AVFrame*)&s->picture[i];
860         pic->reference= 3;
861
862         if(ff_alloc_picture(s, (Picture*)pic, 0) < 0){
863             return -1;
864         }
865
866         if(   pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
867            && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
868            && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
869        // empty
870         }else{
871             int h_chroma_shift, v_chroma_shift;
872             avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
873
874             for(i=0; i<3; i++){
875                 int src_stride= pic_arg->linesize[i];
876                 int dst_stride= i ? s->uvlinesize : s->linesize;
877                 int h_shift= i ? h_chroma_shift : 0;
878                 int v_shift= i ? v_chroma_shift : 0;
879                 int w= s->width >>h_shift;
880                 int h= s->height>>v_shift;
881                 uint8_t *src= pic_arg->data[i];
882                 uint8_t *dst= pic->data[i];
883
884                 if(!s->avctx->rc_buffer_size)
885                     dst +=INPLACE_OFFSET;
886
887                 if(src_stride==dst_stride)
888                     memcpy(dst, src, src_stride*h);
889                 else{
890                     while(h--){
891                         memcpy(dst, src, w);
892                         dst += dst_stride;
893                         src += src_stride;
894                     }
895                 }
896             }
897         }
898     }
899     copy_picture_attributes(s, pic, pic_arg);
900     pic->pts= pts; //we set this here to avoid modifiying pic_arg
901   }
902
903     /* shift buffer entries */
904     for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
905         s->input_picture[i-1]= s->input_picture[i];
906
907     s->input_picture[encoding_delay]= (Picture*)pic;
908
909     return 0;
910 }
911
912 static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
913     int x, y, plane;
914     int score=0;
915     int64_t score64=0;
916
917     for(plane=0; plane<3; plane++){
918         const int stride= p->linesize[plane];
919         const int bw= plane ? 1 : 2;
920         for(y=0; y<s->mb_height*bw; y++){
921             for(x=0; x<s->mb_width*bw; x++){
922                 int off= p->type == FF_BUFFER_TYPE_SHARED ? 0: 16;
923                 int v= s->dsp.frame_skip_cmp[1](s, p->data[plane] + 8*(x + y*stride)+off, ref->data[plane] + 8*(x + y*stride), stride, 8);
924
925                 switch(s->avctx->frame_skip_exp){
926                     case 0: score= FFMAX(score, v); break;
927                     case 1: score+= FFABS(v);break;
928                     case 2: score+= v*v;break;
929                     case 3: score64+= FFABS(v*v*(int64_t)v);break;
930                     case 4: score64+= v*v*(int64_t)(v*v);break;
931                 }
932             }
933         }
934     }
935
936     if(score) score64= score;
937
938     if(score64 < s->avctx->frame_skip_threshold)
939         return 1;
940     if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
941         return 1;
942     return 0;
943 }
944
945 static int estimate_best_b_count(MpegEncContext *s){
946     AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
947     AVCodecContext *c = avcodec_alloc_context3(NULL);
948     AVFrame input[FF_MAX_B_FRAMES+2];
949     const int scale= s->avctx->brd_scale;
950     int i, j, out_size, p_lambda, b_lambda, lambda2;
951     int outbuf_size= s->width * s->height; //FIXME
952     uint8_t *outbuf= av_malloc(outbuf_size);
953     int64_t best_rd= INT64_MAX;
954     int best_b_count= -1;
955
956     assert(scale>=0 && scale <=3);
957
958 //    emms_c();
959     p_lambda= s->last_lambda_for[AV_PICTURE_TYPE_P]; //s->next_picture_ptr->quality;
960     b_lambda= s->last_lambda_for[AV_PICTURE_TYPE_B]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
961     if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
962     lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
963
964     c->width = s->width >> scale;
965     c->height= s->height>> scale;
966     c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
967     c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
968     c->mb_decision= s->avctx->mb_decision;
969     c->me_cmp= s->avctx->me_cmp;
970     c->mb_cmp= s->avctx->mb_cmp;
971     c->me_sub_cmp= s->avctx->me_sub_cmp;
972     c->pix_fmt = PIX_FMT_YUV420P;
973     c->time_base= s->avctx->time_base;
974     c->max_b_frames= s->max_b_frames;
975
976     if (avcodec_open2(c, codec, NULL) < 0)
977         return -1;
978
979     for(i=0; i<s->max_b_frames+2; i++){
980         int ysize= c->width*c->height;
981         int csize= (c->width/2)*(c->height/2);
982         Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
983
984         avcodec_get_frame_defaults(&input[i]);
985         input[i].data[0]= av_malloc(ysize + 2*csize);
986         input[i].data[1]= input[i].data[0] + ysize;
987         input[i].data[2]= input[i].data[1] + csize;
988         input[i].linesize[0]= c->width;
989         input[i].linesize[1]=
990         input[i].linesize[2]= c->width/2;
991
992         if(pre_input_ptr && (!i || s->input_picture[i-1])) {
993             pre_input= *pre_input_ptr;
994
995             if(pre_input.type != FF_BUFFER_TYPE_SHARED && i) {
996                 pre_input.data[0]+=INPLACE_OFFSET;
997                 pre_input.data[1]+=INPLACE_OFFSET;
998                 pre_input.data[2]+=INPLACE_OFFSET;
999             }
1000
1001             s->dsp.shrink[scale](input[i].data[0], input[i].linesize[0], pre_input.data[0], pre_input.linesize[0], c->width, c->height);
1002             s->dsp.shrink[scale](input[i].data[1], input[i].linesize[1], pre_input.data[1], pre_input.linesize[1], c->width>>1, c->height>>1);
1003             s->dsp.shrink[scale](input[i].data[2], input[i].linesize[2], pre_input.data[2], pre_input.linesize[2], c->width>>1, c->height>>1);
1004         }
1005     }
1006
1007     for(j=0; j<s->max_b_frames+1; j++){
1008         int64_t rd=0;
1009
1010         if(!s->input_picture[j])
1011             break;
1012
1013         c->error[0]= c->error[1]= c->error[2]= 0;
1014
1015         input[0].pict_type= AV_PICTURE_TYPE_I;
1016         input[0].quality= 1 * FF_QP2LAMBDA;
1017         out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
1018 //        rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
1019
1020         for(i=0; i<s->max_b_frames+1; i++){
1021             int is_p= i % (j+1) == j || i==s->max_b_frames;
1022
1023             input[i+1].pict_type= is_p ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
1024             input[i+1].quality= is_p ? p_lambda : b_lambda;
1025             out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
1026             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
1027         }
1028
1029         /* get the delayed frames */
1030         while(out_size){
1031             out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
1032             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
1033         }
1034
1035         rd += c->error[0] + c->error[1] + c->error[2];
1036
1037         if(rd < best_rd){
1038             best_rd= rd;
1039             best_b_count= j;
1040         }
1041     }
1042
1043     av_freep(&outbuf);
1044     avcodec_close(c);
1045     av_freep(&c);
1046
1047     for(i=0; i<s->max_b_frames+2; i++){
1048         av_freep(&input[i].data[0]);
1049     }
1050
1051     return best_b_count;
1052 }
1053
1054 static int select_input_picture(MpegEncContext *s){
1055     int i;
1056
1057     for(i=1; i<MAX_PICTURE_COUNT; i++)
1058         s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
1059     s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
1060
1061     /* set next picture type & ordering */
1062     if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
1063         if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
1064             s->reordered_input_picture[0]= s->input_picture[0];
1065             s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_I;
1066             s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
1067         }else{
1068             int b_frames;
1069
1070             if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
1071                 if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
1072                 //FIXME check that te gop check above is +-1 correct
1073 //av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->data[0], s->input_picture[0]->pts);
1074
1075                     if(s->input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
1076                         for(i=0; i<4; i++)
1077                             s->input_picture[0]->data[i]= NULL;
1078                         s->input_picture[0]->type= 0;
1079                     }else{
1080                         assert(   s->input_picture[0]->type==FF_BUFFER_TYPE_USER
1081                                || s->input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
1082
1083                         s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
1084                     }
1085
1086                     emms_c();
1087                     ff_vbv_update(s, 0);
1088
1089                     goto no_output_pic;
1090                 }
1091             }
1092
1093             if(s->flags&CODEC_FLAG_PASS2){
1094                 for(i=0; i<s->max_b_frames+1; i++){
1095                     int pict_num= s->input_picture[0]->display_picture_number + i;
1096
1097                     if(pict_num >= s->rc_context.num_entries)
1098                         break;
1099                     if(!s->input_picture[i]){
1100                         s->rc_context.entry[pict_num-1].new_pict_type = AV_PICTURE_TYPE_P;
1101                         break;
1102                     }
1103
1104                     s->input_picture[i]->pict_type=
1105                         s->rc_context.entry[pict_num].new_pict_type;
1106                 }
1107             }
1108
1109             if(s->avctx->b_frame_strategy==0){
1110                 b_frames= s->max_b_frames;
1111                 while(b_frames && !s->input_picture[b_frames]) b_frames--;
1112             }else if(s->avctx->b_frame_strategy==1){
1113                 for(i=1; i<s->max_b_frames+1; i++){
1114                     if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
1115                         s->input_picture[i]->b_frame_score=
1116                             get_intra_count(s, s->input_picture[i  ]->data[0],
1117                                                s->input_picture[i-1]->data[0], s->linesize) + 1;
1118                     }
1119                 }
1120                 for(i=0; i<s->max_b_frames+1; i++){
1121                     if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
1122                 }
1123
1124                 b_frames= FFMAX(0, i-1);
1125
1126                 /* reset scores */
1127                 for(i=0; i<b_frames+1; i++){
1128                     s->input_picture[i]->b_frame_score=0;
1129                 }
1130             }else if(s->avctx->b_frame_strategy==2){
1131                 b_frames= estimate_best_b_count(s);
1132             }else{
1133                 av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
1134                 b_frames=0;
1135             }
1136
1137             emms_c();
1138 //static int b_count=0;
1139 //b_count+= b_frames;
1140 //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
1141
1142             for(i= b_frames - 1; i>=0; i--){
1143                 int type= s->input_picture[i]->pict_type;
1144                 if(type && type != AV_PICTURE_TYPE_B)
1145                     b_frames= i;
1146             }
1147             if(s->input_picture[b_frames]->pict_type == AV_PICTURE_TYPE_B && b_frames == s->max_b_frames){
1148                 av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
1149             }
1150
1151             if(s->picture_in_gop_number + b_frames >= s->gop_size){
1152               if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
1153                     b_frames= s->gop_size - s->picture_in_gop_number - 1;
1154               }else{
1155                 if(s->flags & CODEC_FLAG_CLOSED_GOP)
1156                     b_frames=0;
1157                 s->input_picture[b_frames]->pict_type= AV_PICTURE_TYPE_I;
1158               }
1159             }
1160
1161             if(   (s->flags & CODEC_FLAG_CLOSED_GOP)
1162                && b_frames
1163                && s->input_picture[b_frames]->pict_type== AV_PICTURE_TYPE_I)
1164                 b_frames--;
1165
1166             s->reordered_input_picture[0]= s->input_picture[b_frames];
1167             if(s->reordered_input_picture[0]->pict_type != AV_PICTURE_TYPE_I)
1168                 s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_P;
1169             s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
1170             for(i=0; i<b_frames; i++){
1171                 s->reordered_input_picture[i+1]= s->input_picture[i];
1172                 s->reordered_input_picture[i+1]->pict_type= AV_PICTURE_TYPE_B;
1173                 s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
1174             }
1175         }
1176     }
1177 no_output_pic:
1178     if(s->reordered_input_picture[0]){
1179         s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=AV_PICTURE_TYPE_B ? 3 : 0;
1180
1181         ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
1182
1183         if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size){
1184             // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
1185
1186             int i= ff_find_unused_picture(s, 0);
1187             Picture *pic= &s->picture[i];
1188
1189             pic->reference              = s->reordered_input_picture[0]->reference;
1190             if(ff_alloc_picture(s, pic, 0) < 0){
1191                 return -1;
1192             }
1193
1194             /* mark us unused / free shared pic */
1195             if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_INTERNAL)
1196                 s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
1197             for(i=0; i<4; i++)
1198                 s->reordered_input_picture[0]->data[i]= NULL;
1199             s->reordered_input_picture[0]->type= 0;
1200
1201             copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
1202
1203             s->current_picture_ptr= pic;
1204         }else{
1205             // input is not a shared pix -> reuse buffer for current_pix
1206
1207             assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
1208                    || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
1209
1210             s->current_picture_ptr= s->reordered_input_picture[0];
1211             for(i=0; i<4; i++){
1212                 s->new_picture.data[i]+= INPLACE_OFFSET;
1213             }
1214         }
1215         ff_copy_picture(&s->current_picture, s->current_picture_ptr);
1216
1217         s->picture_number= s->new_picture.display_picture_number;
1218 //printf("dpn:%d\n", s->picture_number);
1219     }else{
1220        memset(&s->new_picture, 0, sizeof(Picture));
1221     }
1222     return 0;
1223 }
1224
1225 int MPV_encode_picture(AVCodecContext *avctx,
1226                        unsigned char *buf, int buf_size, void *data)
1227 {
1228     MpegEncContext *s = avctx->priv_data;
1229     AVFrame *pic_arg = data;
1230     int i, stuffing_count, context_count = avctx->thread_count;
1231
1232     for(i=0; i<context_count; i++){
1233         int start_y= s->thread_context[i]->start_mb_y;
1234         int   end_y= s->thread_context[i]->  end_mb_y;
1235         int h= s->mb_height;
1236         uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
1237         uint8_t *end  = buf + (size_t)(((int64_t) buf_size)*  end_y/h);
1238
1239         init_put_bits(&s->thread_context[i]->pb, start, end - start);
1240     }
1241
1242     s->picture_in_gop_number++;
1243
1244     if(load_input_picture(s, pic_arg) < 0)
1245         return -1;
1246
1247     if(select_input_picture(s) < 0){
1248         return -1;
1249     }
1250
1251     /* output? */
1252     if(s->new_picture.data[0]){
1253         s->pict_type= s->new_picture.pict_type;
1254 //emms_c();
1255 //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
1256         MPV_frame_start(s, avctx);
1257 vbv_retry:
1258         if (encode_picture(s, s->picture_number) < 0)
1259             return -1;
1260
1261         avctx->header_bits = s->header_bits;
1262         avctx->mv_bits     = s->mv_bits;
1263         avctx->misc_bits   = s->misc_bits;
1264         avctx->i_tex_bits  = s->i_tex_bits;
1265         avctx->p_tex_bits  = s->p_tex_bits;
1266         avctx->i_count     = s->i_count;
1267         avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
1268         avctx->skip_count  = s->skip_count;
1269
1270         MPV_frame_end(s);
1271
1272         if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
1273             ff_mjpeg_encode_picture_trailer(s);
1274
1275         if(avctx->rc_buffer_size){
1276             RateControlContext *rcc= &s->rc_context;
1277             int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
1278
1279             if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
1280                 s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
1281                 if(s->adaptive_quant){
1282                     int i;
1283                     for(i=0; i<s->mb_height*s->mb_stride; i++)
1284                         s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
1285                 }
1286                 s->mb_skipped = 0;        //done in MPV_frame_start()
1287                 if(s->pict_type==AV_PICTURE_TYPE_P){ //done in encode_picture() so we must undo it
1288                     if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
1289                         s->no_rounding ^= 1;
1290                 }
1291                 if(s->pict_type!=AV_PICTURE_TYPE_B){
1292                     s->time_base= s->last_time_base;
1293                     s->last_non_b_time= s->time - s->pp_time;
1294                 }
1295 //                av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
1296                 for(i=0; i<context_count; i++){
1297                     PutBitContext *pb= &s->thread_context[i]->pb;
1298                     init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
1299                 }
1300                 goto vbv_retry;
1301             }
1302
1303             assert(s->avctx->rc_max_rate);
1304         }
1305
1306         if(s->flags&CODEC_FLAG_PASS1)
1307             ff_write_pass1_stats(s);
1308
1309         for(i=0; i<4; i++){
1310             s->current_picture_ptr->error[i]= s->current_picture.error[i];
1311             avctx->error[i] += s->current_picture_ptr->error[i];
1312         }
1313
1314         if(s->flags&CODEC_FLAG_PASS1)
1315             assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
1316         flush_put_bits(&s->pb);
1317         s->frame_bits  = put_bits_count(&s->pb);
1318
1319         stuffing_count= ff_vbv_update(s, s->frame_bits);
1320         if(stuffing_count){
1321             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
1322                 av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
1323                 return -1;
1324             }
1325
1326             switch(s->codec_id){
1327             case CODEC_ID_MPEG1VIDEO:
1328             case CODEC_ID_MPEG2VIDEO:
1329                 while(stuffing_count--){
1330                     put_bits(&s->pb, 8, 0);
1331                 }
1332             break;
1333             case CODEC_ID_MPEG4:
1334                 put_bits(&s->pb, 16, 0);
1335                 put_bits(&s->pb, 16, 0x1C3);
1336                 stuffing_count -= 4;
1337                 while(stuffing_count--){
1338                     put_bits(&s->pb, 8, 0xFF);
1339                 }
1340             break;
1341             default:
1342                 av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
1343             }
1344             flush_put_bits(&s->pb);
1345             s->frame_bits  = put_bits_count(&s->pb);
1346         }
1347
1348         /* update mpeg1/2 vbv_delay for CBR */
1349         if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
1350            && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
1351             int vbv_delay, min_delay;
1352             double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
1353             int    minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
1354             double bits   = s->rc_context.buffer_index + minbits - inbits;
1355
1356             if(bits<0)
1357                 av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
1358
1359             assert(s->repeat_first_field==0);
1360
1361             vbv_delay=     bits * 90000                               / s->avctx->rc_max_rate;
1362             min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
1363
1364             vbv_delay= FFMAX(vbv_delay, min_delay);
1365
1366             assert(vbv_delay < 0xFFFF);
1367
1368             s->vbv_delay_ptr[0] &= 0xF8;
1369             s->vbv_delay_ptr[0] |= vbv_delay>>13;
1370             s->vbv_delay_ptr[1]  = vbv_delay>>5;
1371             s->vbv_delay_ptr[2] &= 0x07;
1372             s->vbv_delay_ptr[2] |= vbv_delay<<3;
1373             avctx->vbv_delay = vbv_delay*300;
1374         }
1375         s->total_bits += s->frame_bits;
1376         avctx->frame_bits  = s->frame_bits;
1377     }else{
1378         assert((put_bits_ptr(&s->pb) == s->pb.buf));
1379         s->frame_bits=0;
1380     }
1381     assert((s->frame_bits&7)==0);
1382
1383     return s->frame_bits/8;
1384 }
1385
1386 static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
1387 {
1388     static const char tab[64]=
1389         {3,2,2,1,1,1,1,1,
1390          1,1,1,1,1,1,1,1,
1391          1,1,1,1,1,1,1,1,
1392          0,0,0,0,0,0,0,0,
1393          0,0,0,0,0,0,0,0,
1394          0,0,0,0,0,0,0,0,
1395          0,0,0,0,0,0,0,0,
1396          0,0,0,0,0,0,0,0};
1397     int score=0;
1398     int run=0;
1399     int i;
1400     DCTELEM *block= s->block[n];
1401     const int last_index= s->block_last_index[n];
1402     int skip_dc;
1403
1404     if(threshold<0){
1405         skip_dc=0;
1406         threshold= -threshold;
1407     }else
1408         skip_dc=1;
1409
1410     /* Are all we could set to zero already zero? */
1411     if(last_index<=skip_dc - 1) return;
1412
1413     for(i=0; i<=last_index; i++){
1414         const int j = s->intra_scantable.permutated[i];
1415         const int level = FFABS(block[j]);
1416         if(level==1){
1417             if(skip_dc && i==0) continue;
1418             score+= tab[run];
1419             run=0;
1420         }else if(level>1){
1421             return;
1422         }else{
1423             run++;
1424         }
1425     }
1426     if(score >= threshold) return;
1427     for(i=skip_dc; i<=last_index; i++){
1428         const int j = s->intra_scantable.permutated[i];
1429         block[j]=0;
1430     }
1431     if(block[0]) s->block_last_index[n]= 0;
1432     else         s->block_last_index[n]= -1;
1433 }
1434
1435 static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
1436 {
1437     int i;
1438     const int maxlevel= s->max_qcoeff;
1439     const int minlevel= s->min_qcoeff;
1440     int overflow=0;
1441
1442     if(s->mb_intra){
1443         i=1; //skip clipping of intra dc
1444     }else
1445         i=0;
1446
1447     for(;i<=last_index; i++){
1448         const int j= s->intra_scantable.permutated[i];
1449         int level = block[j];
1450
1451         if     (level>maxlevel){
1452             level=maxlevel;
1453             overflow++;
1454         }else if(level<minlevel){
1455             level=minlevel;
1456             overflow++;
1457         }
1458
1459         block[j]= level;
1460     }
1461
1462     if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
1463         av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
1464 }
1465
1466 static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
1467     int x, y;
1468 //FIXME optimize
1469     for(y=0; y<8; y++){
1470         for(x=0; x<8; x++){
1471             int x2, y2;
1472             int sum=0;
1473             int sqr=0;
1474             int count=0;
1475
1476             for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
1477                 for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
1478                     int v= ptr[x2 + y2*stride];
1479                     sum += v;
1480                     sqr += v*v;
1481                     count++;
1482                 }
1483             }
1484             weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
1485         }
1486     }
1487 }
1488
1489 static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
1490 {
1491     int16_t weight[8][64];
1492     DCTELEM orig[8][64];
1493     const int mb_x= s->mb_x;
1494     const int mb_y= s->mb_y;
1495     int i;
1496     int skip_dct[8];
1497     int dct_offset   = s->linesize*8; //default for progressive frames
1498     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
1499     int wrap_y, wrap_c;
1500
1501     for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
1502
1503     if(s->adaptive_quant){
1504         const int last_qp= s->qscale;
1505         const int mb_xy= mb_x + mb_y*s->mb_stride;
1506
1507         s->lambda= s->lambda_table[mb_xy];
1508         update_qscale(s);
1509
1510         if(!(s->flags&CODEC_FLAG_QP_RD)){
1511             s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
1512             s->dquant= s->qscale - last_qp;
1513
1514             if(s->out_format==FMT_H263){
1515                 s->dquant= av_clip(s->dquant, -2, 2);
1516
1517                 if(s->codec_id==CODEC_ID_MPEG4){
1518                     if(!s->mb_intra){
1519                         if(s->pict_type == AV_PICTURE_TYPE_B){
1520                             if(s->dquant&1 || s->mv_dir&MV_DIRECT)
1521                                 s->dquant= 0;
1522                         }
1523                         if(s->mv_type==MV_TYPE_8X8)
1524                             s->dquant=0;
1525                     }
1526                 }
1527             }
1528         }
1529         ff_set_qscale(s, last_qp + s->dquant);
1530     }else if(s->flags&CODEC_FLAG_QP_RD)
1531         ff_set_qscale(s, s->qscale + s->dquant);
1532
1533     wrap_y = s->linesize;
1534     wrap_c = s->uvlinesize;
1535     ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
1536     ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1537     ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1538
1539     if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
1540         uint8_t *ebuf= s->edge_emu_buffer + 32;
1541         s->dsp.emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
1542         ptr_y= ebuf;
1543         s->dsp.emulated_edge_mc(ebuf+18*wrap_y  , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
1544         ptr_cb= ebuf+18*wrap_y;
1545         s->dsp.emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
1546         ptr_cr= ebuf+18*wrap_y+8;
1547     }
1548
1549     if (s->mb_intra) {
1550         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1551             int progressive_score, interlaced_score;
1552
1553             s->interlaced_dct=0;
1554             progressive_score= s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y, 8)
1555                               +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
1556
1557             if(progressive_score > 0){
1558                 interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y*2, 8)
1559                                   +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y  , NULL, wrap_y*2, 8);
1560                 if(progressive_score > interlaced_score){
1561                     s->interlaced_dct=1;
1562
1563                     dct_offset= wrap_y;
1564                     wrap_y<<=1;
1565                     if (s->chroma_format == CHROMA_422)
1566                         wrap_c<<=1;
1567                 }
1568             }
1569         }
1570
1571         s->dsp.get_pixels(s->block[0], ptr_y                 , wrap_y);
1572         s->dsp.get_pixels(s->block[1], ptr_y              + 8, wrap_y);
1573         s->dsp.get_pixels(s->block[2], ptr_y + dct_offset    , wrap_y);
1574         s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
1575
1576         if(s->flags&CODEC_FLAG_GRAY){
1577             skip_dct[4]= 1;
1578             skip_dct[5]= 1;
1579         }else{
1580             s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
1581             s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
1582             if(!s->chroma_y_shift){ /* 422 */
1583                 s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
1584                 s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
1585             }
1586         }
1587     }else{
1588         op_pixels_func (*op_pix)[4];
1589         qpel_mc_func (*op_qpix)[16];
1590         uint8_t *dest_y, *dest_cb, *dest_cr;
1591
1592         dest_y  = s->dest[0];
1593         dest_cb = s->dest[1];
1594         dest_cr = s->dest[2];
1595
1596         if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
1597             op_pix = s->dsp.put_pixels_tab;
1598             op_qpix= s->dsp.put_qpel_pixels_tab;
1599         }else{
1600             op_pix = s->dsp.put_no_rnd_pixels_tab;
1601             op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
1602         }
1603
1604         if (s->mv_dir & MV_DIR_FORWARD) {
1605             MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
1606             op_pix = s->dsp.avg_pixels_tab;
1607             op_qpix= s->dsp.avg_qpel_pixels_tab;
1608         }
1609         if (s->mv_dir & MV_DIR_BACKWARD) {
1610             MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
1611         }
1612
1613         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1614             int progressive_score, interlaced_score;
1615
1616             s->interlaced_dct=0;
1617             progressive_score= s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y, 8)
1618                               +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
1619
1620             if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
1621
1622             if(progressive_score>0){
1623                 interlaced_score = s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y*2, 8)
1624                                   +s->dsp.ildct_cmp[0](s, dest_y + wrap_y  , ptr_y + wrap_y  , wrap_y*2, 8);
1625
1626                 if(progressive_score > interlaced_score){
1627                     s->interlaced_dct=1;
1628
1629                     dct_offset= wrap_y;
1630                     wrap_y<<=1;
1631                     if (s->chroma_format == CHROMA_422)
1632                         wrap_c<<=1;
1633                 }
1634             }
1635         }
1636
1637         s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
1638         s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
1639         s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
1640         s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
1641
1642         if(s->flags&CODEC_FLAG_GRAY){
1643             skip_dct[4]= 1;
1644             skip_dct[5]= 1;
1645         }else{
1646             s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
1647             s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
1648             if(!s->chroma_y_shift){ /* 422 */
1649                 s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
1650                 s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
1651             }
1652         }
1653         /* pre quantization */
1654         if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
1655             //FIXME optimize
1656             if(s->dsp.sad[1](NULL, ptr_y               , dest_y               , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
1657             if(s->dsp.sad[1](NULL, ptr_y            + 8, dest_y            + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
1658             if(s->dsp.sad[1](NULL, ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
1659             if(s->dsp.sad[1](NULL, ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y, 8) < 20*s->qscale) skip_dct[3]= 1;
1660             if(s->dsp.sad[1](NULL, ptr_cb              , dest_cb              , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
1661             if(s->dsp.sad[1](NULL, ptr_cr              , dest_cr              , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
1662             if(!s->chroma_y_shift){ /* 422 */
1663                 if(s->dsp.sad[1](NULL, ptr_cb +(dct_offset>>1), dest_cb +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[6]= 1;
1664                 if(s->dsp.sad[1](NULL, ptr_cr +(dct_offset>>1), dest_cr +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[7]= 1;
1665             }
1666         }
1667     }
1668
1669     if(s->avctx->quantizer_noise_shaping){
1670         if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y                 , wrap_y);
1671         if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y              + 8, wrap_y);
1672         if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);
1673         if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
1674         if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb                , wrap_c);
1675         if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr                , wrap_c);
1676         if(!s->chroma_y_shift){ /* 422 */
1677             if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
1678             if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
1679         }
1680         memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
1681     }
1682
1683     /* DCT & quantize */
1684     assert(s->out_format!=FMT_MJPEG || s->qscale==8);
1685     {
1686         for(i=0;i<mb_block_count;i++) {
1687             if(!skip_dct[i]){
1688                 int overflow;
1689                 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
1690             // FIXME we could decide to change to quantizer instead of clipping
1691             // JS: I don't think that would be a good idea it could lower quality instead
1692             //     of improve it. Just INTRADC clipping deserves changes in quantizer
1693                 if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
1694             }else
1695                 s->block_last_index[i]= -1;
1696         }
1697         if(s->avctx->quantizer_noise_shaping){
1698             for(i=0;i<mb_block_count;i++) {
1699                 if(!skip_dct[i]){
1700                     s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
1701                 }
1702             }
1703         }
1704
1705         if(s->luma_elim_threshold && !s->mb_intra)
1706             for(i=0; i<4; i++)
1707                 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
1708         if(s->chroma_elim_threshold && !s->mb_intra)
1709             for(i=4; i<mb_block_count; i++)
1710                 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
1711
1712         if(s->flags & CODEC_FLAG_CBP_RD){
1713             for(i=0;i<mb_block_count;i++) {
1714                 if(s->block_last_index[i] == -1)
1715                     s->coded_score[i]= INT_MAX/256;
1716             }
1717         }
1718     }
1719
1720     if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
1721         s->block_last_index[4]=
1722         s->block_last_index[5]= 0;
1723         s->block[4][0]=
1724         s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
1725     }
1726
1727     //non c quantize code returns incorrect block_last_index FIXME
1728     if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
1729         for(i=0; i<mb_block_count; i++){
1730             int j;
1731             if(s->block_last_index[i]>0){
1732                 for(j=63; j>0; j--){
1733                     if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
1734                 }
1735                 s->block_last_index[i]= j;
1736             }
1737         }
1738     }
1739
1740     /* huffman encode */
1741     switch(s->codec_id){ //FIXME funct ptr could be slightly faster
1742     case CODEC_ID_MPEG1VIDEO:
1743     case CODEC_ID_MPEG2VIDEO:
1744         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
1745             mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1746         break;
1747     case CODEC_ID_MPEG4:
1748         if (CONFIG_MPEG4_ENCODER)
1749             mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1750         break;
1751     case CODEC_ID_MSMPEG4V2:
1752     case CODEC_ID_MSMPEG4V3:
1753     case CODEC_ID_WMV1:
1754         if (CONFIG_MSMPEG4_ENCODER)
1755             msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1756         break;
1757     case CODEC_ID_WMV2:
1758         if (CONFIG_WMV2_ENCODER)
1759             ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
1760         break;
1761     case CODEC_ID_H261:
1762         if (CONFIG_H261_ENCODER)
1763             ff_h261_encode_mb(s, s->block, motion_x, motion_y);
1764         break;
1765     case CODEC_ID_H263:
1766     case CODEC_ID_H263P:
1767     case CODEC_ID_FLV1:
1768     case CODEC_ID_RV10:
1769     case CODEC_ID_RV20:
1770         if (CONFIG_H263_ENCODER)
1771             h263_encode_mb(s, s->block, motion_x, motion_y);
1772         break;
1773     case CODEC_ID_MJPEG:
1774         if (CONFIG_MJPEG_ENCODER)
1775             ff_mjpeg_encode_mb(s, s->block);
1776         break;
1777     default:
1778         assert(0);
1779     }
1780 }
1781
1782 static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
1783 {
1784     if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 6);
1785     else                                encode_mb_internal(s, motion_x, motion_y, 16, 8);
1786 }
1787
1788 static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1789     int i;
1790
1791     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
1792
1793     /* mpeg1 */
1794     d->mb_skip_run= s->mb_skip_run;
1795     for(i=0; i<3; i++)
1796         d->last_dc[i]= s->last_dc[i];
1797
1798     /* statistics */
1799     d->mv_bits= s->mv_bits;
1800     d->i_tex_bits= s->i_tex_bits;
1801     d->p_tex_bits= s->p_tex_bits;
1802     d->i_count= s->i_count;
1803     d->f_count= s->f_count;
1804     d->b_count= s->b_count;
1805     d->skip_count= s->skip_count;
1806     d->misc_bits= s->misc_bits;
1807     d->last_bits= 0;
1808
1809     d->mb_skipped= 0;
1810     d->qscale= s->qscale;
1811     d->dquant= s->dquant;
1812
1813     d->esc3_level_length= s->esc3_level_length;
1814 }
1815
1816 static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
1817     int i;
1818
1819     memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
1820     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
1821
1822     /* mpeg1 */
1823     d->mb_skip_run= s->mb_skip_run;
1824     for(i=0; i<3; i++)
1825         d->last_dc[i]= s->last_dc[i];
1826
1827     /* statistics */
1828     d->mv_bits= s->mv_bits;
1829     d->i_tex_bits= s->i_tex_bits;
1830     d->p_tex_bits= s->p_tex_bits;
1831     d->i_count= s->i_count;
1832     d->f_count= s->f_count;
1833     d->b_count= s->b_count;
1834     d->skip_count= s->skip_count;
1835     d->misc_bits= s->misc_bits;
1836
1837     d->mb_intra= s->mb_intra;
1838     d->mb_skipped= s->mb_skipped;
1839     d->mv_type= s->mv_type;
1840     d->mv_dir= s->mv_dir;
1841     d->pb= s->pb;
1842     if(s->data_partitioning){
1843         d->pb2= s->pb2;
1844         d->tex_pb= s->tex_pb;
1845     }
1846     d->block= s->block;
1847     for(i=0; i<8; i++)
1848         d->block_last_index[i]= s->block_last_index[i];
1849     d->interlaced_dct= s->interlaced_dct;
1850     d->qscale= s->qscale;
1851
1852     d->esc3_level_length= s->esc3_level_length;
1853 }
1854
1855 static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
1856                            PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
1857                            int *dmin, int *next_block, int motion_x, int motion_y)
1858 {
1859     int score;
1860     uint8_t *dest_backup[3];
1861
1862     copy_context_before_encode(s, backup, type);
1863
1864     s->block= s->blocks[*next_block];
1865     s->pb= pb[*next_block];
1866     if(s->data_partitioning){
1867         s->pb2   = pb2   [*next_block];
1868         s->tex_pb= tex_pb[*next_block];
1869     }
1870
1871     if(*next_block){
1872         memcpy(dest_backup, s->dest, sizeof(s->dest));
1873         s->dest[0] = s->rd_scratchpad;
1874         s->dest[1] = s->rd_scratchpad + 16*s->linesize;
1875         s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
1876         assert(s->linesize >= 32); //FIXME
1877     }
1878
1879     encode_mb(s, motion_x, motion_y);
1880
1881     score= put_bits_count(&s->pb);
1882     if(s->data_partitioning){
1883         score+= put_bits_count(&s->pb2);
1884         score+= put_bits_count(&s->tex_pb);
1885     }
1886
1887     if(s->avctx->mb_decision == FF_MB_DECISION_RD){
1888         MPV_decode_mb(s, s->block);
1889
1890         score *= s->lambda2;
1891         score += sse_mb(s) << FF_LAMBDA_SHIFT;
1892     }
1893
1894     if(*next_block){
1895         memcpy(s->dest, dest_backup, sizeof(s->dest));
1896     }
1897
1898     if(score<*dmin){
1899         *dmin= score;
1900         *next_block^=1;
1901
1902         copy_context_after_encode(best, s, type);
1903     }
1904 }
1905
1906 static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
1907     uint32_t *sq = ff_squareTbl + 256;
1908     int acc=0;
1909     int x,y;
1910
1911     if(w==16 && h==16)
1912         return s->dsp.sse[0](NULL, src1, src2, stride, 16);
1913     else if(w==8 && h==8)
1914         return s->dsp.sse[1](NULL, src1, src2, stride, 8);
1915
1916     for(y=0; y<h; y++){
1917         for(x=0; x<w; x++){
1918             acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
1919         }
1920     }
1921
1922     assert(acc>=0);
1923
1924     return acc;
1925 }
1926
1927 static int sse_mb(MpegEncContext *s){
1928     int w= 16;
1929     int h= 16;
1930
1931     if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
1932     if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
1933
1934     if(w==16 && h==16)
1935       if(s->avctx->mb_cmp == FF_CMP_NSSE){
1936         return  s->dsp.nsse[0](s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
1937                +s->dsp.nsse[1](s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
1938                +s->dsp.nsse[1](s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
1939       }else{
1940         return  s->dsp.sse[0](NULL, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
1941                +s->dsp.sse[1](NULL, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
1942                +s->dsp.sse[1](NULL, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
1943       }
1944     else
1945         return  sse(s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
1946                +sse(s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
1947                +sse(s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
1948 }
1949
1950 static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
1951     MpegEncContext *s= *(void**)arg;
1952
1953
1954     s->me.pre_pass=1;
1955     s->me.dia_size= s->avctx->pre_dia_size;
1956     s->first_slice_line=1;
1957     for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
1958         for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
1959             ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1960         }
1961         s->first_slice_line=0;
1962     }
1963
1964     s->me.pre_pass=0;
1965
1966     return 0;
1967 }
1968
1969 static int estimate_motion_thread(AVCodecContext *c, void *arg){
1970     MpegEncContext *s= *(void**)arg;
1971
1972     ff_check_alignment();
1973
1974     s->me.dia_size= s->avctx->dia_size;
1975     s->first_slice_line=1;
1976     for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
1977         s->mb_x=0; //for block init below
1978         ff_init_block_index(s);
1979         for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
1980             s->block_index[0]+=2;
1981             s->block_index[1]+=2;
1982             s->block_index[2]+=2;
1983             s->block_index[3]+=2;
1984
1985             /* compute motion vector & mb_type and store in context */
1986             if(s->pict_type==AV_PICTURE_TYPE_B)
1987                 ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
1988             else
1989                 ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1990         }
1991         s->first_slice_line=0;
1992     }
1993     return 0;
1994 }
1995
1996 static int mb_var_thread(AVCodecContext *c, void *arg){
1997     MpegEncContext *s= *(void**)arg;
1998     int mb_x, mb_y;
1999
2000     ff_check_alignment();
2001
2002     for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2003         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2004             int xx = mb_x * 16;
2005             int yy = mb_y * 16;
2006             uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
2007             int varc;
2008             int sum = s->dsp.pix_sum(pix, s->linesize);
2009
2010             varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
2011
2012             s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
2013             s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
2014             s->me.mb_var_sum_temp    += varc;
2015         }
2016     }
2017     return 0;
2018 }
2019
2020 static void write_slice_end(MpegEncContext *s){
2021     if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
2022         if(s->partitioned_frame){
2023             ff_mpeg4_merge_partitions(s);
2024         }
2025
2026         ff_mpeg4_stuffing(&s->pb);
2027     }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
2028         ff_mjpeg_encode_stuffing(&s->pb);
2029     }
2030
2031     align_put_bits(&s->pb);
2032     flush_put_bits(&s->pb);
2033
2034     if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
2035         s->misc_bits+= get_bits_diff(s);
2036 }
2037
2038 static int encode_thread(AVCodecContext *c, void *arg){
2039     MpegEncContext *s= *(void**)arg;
2040     int mb_x, mb_y, pdif = 0;
2041     int chr_h= 16>>s->chroma_y_shift;
2042     int i, j;
2043     MpegEncContext best_s, backup_s;
2044     uint8_t bit_buf[2][MAX_MB_BYTES];
2045     uint8_t bit_buf2[2][MAX_MB_BYTES];
2046     uint8_t bit_buf_tex[2][MAX_MB_BYTES];
2047     PutBitContext pb[2], pb2[2], tex_pb[2];
2048 //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
2049
2050     ff_check_alignment();
2051
2052     for(i=0; i<2; i++){
2053         init_put_bits(&pb    [i], bit_buf    [i], MAX_MB_BYTES);
2054         init_put_bits(&pb2   [i], bit_buf2   [i], MAX_MB_BYTES);
2055         init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
2056     }
2057
2058     s->last_bits= put_bits_count(&s->pb);
2059     s->mv_bits=0;
2060     s->misc_bits=0;
2061     s->i_tex_bits=0;
2062     s->p_tex_bits=0;
2063     s->i_count=0;
2064     s->f_count=0;
2065     s->b_count=0;
2066     s->skip_count=0;
2067
2068     for(i=0; i<3; i++){
2069         /* init last dc values */
2070         /* note: quant matrix value (8) is implied here */
2071         s->last_dc[i] = 128 << s->intra_dc_precision;
2072
2073         s->current_picture.error[i] = 0;
2074     }
2075     s->mb_skip_run = 0;
2076     memset(s->last_mv, 0, sizeof(s->last_mv));
2077
2078     s->last_mv_dir = 0;
2079
2080     switch(s->codec_id){
2081     case CODEC_ID_H263:
2082     case CODEC_ID_H263P:
2083     case CODEC_ID_FLV1:
2084         if (CONFIG_H263_ENCODER)
2085             s->gob_index = ff_h263_get_gob_height(s);
2086         break;
2087     case CODEC_ID_MPEG4:
2088         if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
2089             ff_mpeg4_init_partitions(s);
2090         break;
2091     }
2092
2093     s->resync_mb_x=0;
2094     s->resync_mb_y=0;
2095     s->first_slice_line = 1;
2096     s->ptr_lastgob = s->pb.buf;
2097     for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2098 //    printf("row %d at %X\n", s->mb_y, (int)s);
2099         s->mb_x=0;
2100         s->mb_y= mb_y;
2101
2102         ff_set_qscale(s, s->qscale);
2103         ff_init_block_index(s);
2104
2105         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2106             int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
2107             int mb_type= s->mb_type[xy];
2108 //            int d;
2109             int dmin= INT_MAX;
2110             int dir;
2111
2112             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
2113                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2114                 return -1;
2115             }
2116             if(s->data_partitioning){
2117                 if(   s->pb2   .buf_end - s->pb2   .buf - (put_bits_count(&s->    pb2)>>3) < MAX_MB_BYTES
2118                    || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
2119                     av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2120                     return -1;
2121                 }
2122             }
2123
2124             s->mb_x = mb_x;
2125             s->mb_y = mb_y;  // moved into loop, can get changed by H.261
2126             ff_update_block_index(s);
2127
2128             if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
2129                 ff_h261_reorder_mb_index(s);
2130                 xy= s->mb_y*s->mb_stride + s->mb_x;
2131                 mb_type= s->mb_type[xy];
2132             }
2133
2134             /* write gob / video packet header  */
2135             if(s->rtp_mode){
2136                 int current_packet_size, is_gob_start;
2137
2138                 current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
2139
2140                 is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
2141
2142                 if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
2143
2144                 switch(s->codec_id){
2145                 case CODEC_ID_H263:
2146                 case CODEC_ID_H263P:
2147                     if(!s->h263_slice_structured)
2148                         if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
2149                     break;
2150                 case CODEC_ID_MPEG2VIDEO:
2151                     if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
2152                 case CODEC_ID_MPEG1VIDEO:
2153                     if(s->mb_skip_run) is_gob_start=0;
2154                     break;
2155                 }
2156
2157                 if(is_gob_start){
2158                     if(s->start_mb_y != mb_y || mb_x!=0){
2159                         write_slice_end(s);
2160
2161                         if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
2162                             ff_mpeg4_init_partitions(s);
2163                         }
2164                     }
2165
2166                     assert((put_bits_count(&s->pb)&7) == 0);
2167                     current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
2168
2169                     if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
2170                         int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
2171                         int d= 100 / s->avctx->error_rate;
2172                         if(r % d == 0){
2173                             current_packet_size=0;
2174                             s->pb.buf_ptr= s->ptr_lastgob;
2175                             assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
2176                         }
2177                     }
2178
2179                     if (s->avctx->rtp_callback){
2180                         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
2181                         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
2182                     }
2183
2184                     switch(s->codec_id){
2185                     case CODEC_ID_MPEG4:
2186                         if (CONFIG_MPEG4_ENCODER) {
2187                             ff_mpeg4_encode_video_packet_header(s);
2188                             ff_mpeg4_clean_buffers(s);
2189                         }
2190                     break;
2191                     case CODEC_ID_MPEG1VIDEO:
2192                     case CODEC_ID_MPEG2VIDEO:
2193                         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
2194                             ff_mpeg1_encode_slice_header(s);
2195                             ff_mpeg1_clean_buffers(s);
2196                         }
2197                     break;
2198                     case CODEC_ID_H263:
2199                     case CODEC_ID_H263P:
2200                         if (CONFIG_H263_ENCODER)
2201                             h263_encode_gob_header(s, mb_y);
2202                     break;
2203                     }
2204
2205                     if(s->flags&CODEC_FLAG_PASS1){
2206                         int bits= put_bits_count(&s->pb);
2207                         s->misc_bits+= bits - s->last_bits;
2208                         s->last_bits= bits;
2209                     }
2210
2211                     s->ptr_lastgob += current_packet_size;
2212                     s->first_slice_line=1;
2213                     s->resync_mb_x=mb_x;
2214                     s->resync_mb_y=mb_y;
2215                 }
2216             }
2217
2218             if(  (s->resync_mb_x   == s->mb_x)
2219                && s->resync_mb_y+1 == s->mb_y){
2220                 s->first_slice_line=0;
2221             }
2222
2223             s->mb_skipped=0;
2224             s->dquant=0; //only for QP_RD
2225
2226             if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
2227                 int next_block=0;
2228                 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
2229
2230                 copy_context_before_encode(&backup_s, s, -1);
2231                 backup_s.pb= s->pb;
2232                 best_s.data_partitioning= s->data_partitioning;
2233                 best_s.partitioned_frame= s->partitioned_frame;
2234                 if(s->data_partitioning){
2235                     backup_s.pb2= s->pb2;
2236                     backup_s.tex_pb= s->tex_pb;
2237                 }
2238
2239                 if(mb_type&CANDIDATE_MB_TYPE_INTER){
2240                     s->mv_dir = MV_DIR_FORWARD;
2241                     s->mv_type = MV_TYPE_16X16;
2242                     s->mb_intra= 0;
2243                     s->mv[0][0][0] = s->p_mv_table[xy][0];
2244                     s->mv[0][0][1] = s->p_mv_table[xy][1];
2245                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
2246                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2247                 }
2248                 if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
2249                     s->mv_dir = MV_DIR_FORWARD;
2250                     s->mv_type = MV_TYPE_FIELD;
2251                     s->mb_intra= 0;
2252                     for(i=0; i<2; i++){
2253                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2254                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2255                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2256                     }
2257                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
2258                                  &dmin, &next_block, 0, 0);
2259                 }
2260                 if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
2261                     s->mv_dir = MV_DIR_FORWARD;
2262                     s->mv_type = MV_TYPE_16X16;
2263                     s->mb_intra= 0;
2264                     s->mv[0][0][0] = 0;
2265                     s->mv[0][0][1] = 0;
2266                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
2267                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2268                 }
2269                 if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
2270                     s->mv_dir = MV_DIR_FORWARD;
2271                     s->mv_type = MV_TYPE_8X8;
2272                     s->mb_intra= 0;
2273                     for(i=0; i<4; i++){
2274                         s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
2275                         s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
2276                     }
2277                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
2278                                  &dmin, &next_block, 0, 0);
2279                 }
2280                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
2281                     s->mv_dir = MV_DIR_FORWARD;
2282                     s->mv_type = MV_TYPE_16X16;
2283                     s->mb_intra= 0;
2284                     s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2285                     s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2286                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
2287                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2288                 }
2289                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
2290                     s->mv_dir = MV_DIR_BACKWARD;
2291                     s->mv_type = MV_TYPE_16X16;
2292                     s->mb_intra= 0;
2293                     s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2294                     s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2295                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
2296                                  &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
2297                 }
2298                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
2299                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2300                     s->mv_type = MV_TYPE_16X16;
2301                     s->mb_intra= 0;
2302                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2303                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2304                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2305                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2306                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
2307                                  &dmin, &next_block, 0, 0);
2308                 }
2309                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
2310                     s->mv_dir = MV_DIR_FORWARD;
2311                     s->mv_type = MV_TYPE_FIELD;
2312                     s->mb_intra= 0;
2313                     for(i=0; i<2; i++){
2314                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2315                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2316                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2317                     }
2318                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
2319                                  &dmin, &next_block, 0, 0);
2320                 }
2321                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
2322                     s->mv_dir = MV_DIR_BACKWARD;
2323                     s->mv_type = MV_TYPE_FIELD;
2324                     s->mb_intra= 0;
2325                     for(i=0; i<2; i++){
2326                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2327                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2328                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2329                     }
2330                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
2331                                  &dmin, &next_block, 0, 0);
2332                 }
2333                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
2334                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2335                     s->mv_type = MV_TYPE_FIELD;
2336                     s->mb_intra= 0;
2337                     for(dir=0; dir<2; dir++){
2338                         for(i=0; i<2; i++){
2339                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2340                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2341                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2342                         }
2343                     }
2344                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
2345                                  &dmin, &next_block, 0, 0);
2346                 }
2347                 if(mb_type&CANDIDATE_MB_TYPE_INTRA){
2348                     s->mv_dir = 0;
2349                     s->mv_type = MV_TYPE_16X16;
2350                     s->mb_intra= 1;
2351                     s->mv[0][0][0] = 0;
2352                     s->mv[0][0][1] = 0;
2353                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
2354                                  &dmin, &next_block, 0, 0);
2355                     if(s->h263_pred || s->h263_aic){
2356                         if(best_s.mb_intra)
2357                             s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
2358                         else
2359                             ff_clean_intra_table_entries(s); //old mode?
2360                     }
2361                 }
2362
2363                 if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
2364                     if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
2365                         const int last_qp= backup_s.qscale;
2366                         int qpi, qp, dc[6];
2367                         DCTELEM ac[6][16];
2368                         const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
2369                         static const int dquant_tab[4]={-1,1,-2,2};
2370
2371                         assert(backup_s.dquant == 0);
2372
2373                         //FIXME intra
2374                         s->mv_dir= best_s.mv_dir;
2375                         s->mv_type = MV_TYPE_16X16;
2376                         s->mb_intra= best_s.mb_intra;
2377                         s->mv[0][0][0] = best_s.mv[0][0][0];
2378                         s->mv[0][0][1] = best_s.mv[0][0][1];
2379                         s->mv[1][0][0] = best_s.mv[1][0][0];
2380                         s->mv[1][0][1] = best_s.mv[1][0][1];
2381
2382                         qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
2383                         for(; qpi<4; qpi++){
2384                             int dquant= dquant_tab[qpi];
2385                             qp= last_qp + dquant;
2386                             if(qp < s->avctx->qmin || qp > s->avctx->qmax)
2387                                 continue;
2388                             backup_s.dquant= dquant;
2389                             if(s->mb_intra && s->dc_val[0]){
2390                                 for(i=0; i<6; i++){
2391                                     dc[i]= s->dc_val[0][ s->block_index[i] ];
2392                                     memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
2393                                 }
2394                             }
2395
2396                             encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2397                                          &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
2398                             if(best_s.qscale != qp){
2399                                 if(s->mb_intra && s->dc_val[0]){
2400                                     for(i=0; i<6; i++){
2401                                         s->dc_val[0][ s->block_index[i] ]= dc[i];
2402                                         memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
2403                                     }
2404                                 }
2405                             }
2406                         }
2407                     }
2408                 }
2409                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
2410                     int mx= s->b_direct_mv_table[xy][0];
2411                     int my= s->b_direct_mv_table[xy][1];
2412
2413                     backup_s.dquant = 0;
2414                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2415                     s->mb_intra= 0;
2416                     ff_mpeg4_set_direct_mv(s, mx, my);
2417                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2418                                  &dmin, &next_block, mx, my);
2419                 }
2420                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
2421                     backup_s.dquant = 0;
2422                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2423                     s->mb_intra= 0;
2424                     ff_mpeg4_set_direct_mv(s, 0, 0);
2425                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2426                                  &dmin, &next_block, 0, 0);
2427                 }
2428                 if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
2429                     int coded=0;
2430                     for(i=0; i<6; i++)
2431                         coded |= s->block_last_index[i];
2432                     if(coded){
2433                         int mx,my;
2434                         memcpy(s->mv, best_s.mv, sizeof(s->mv));
2435                         if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
2436                             mx=my=0; //FIXME find the one we actually used
2437                             ff_mpeg4_set_direct_mv(s, mx, my);
2438                         }else if(best_s.mv_dir&MV_DIR_BACKWARD){
2439                             mx= s->mv[1][0][0];
2440                             my= s->mv[1][0][1];
2441                         }else{
2442                             mx= s->mv[0][0][0];
2443                             my= s->mv[0][0][1];
2444                         }
2445
2446                         s->mv_dir= best_s.mv_dir;
2447                         s->mv_type = best_s.mv_type;
2448                         s->mb_intra= 0;
2449 /*                        s->mv[0][0][0] = best_s.mv[0][0][0];
2450                         s->mv[0][0][1] = best_s.mv[0][0][1];
2451                         s->mv[1][0][0] = best_s.mv[1][0][0];
2452                         s->mv[1][0][1] = best_s.mv[1][0][1];*/
2453                         backup_s.dquant= 0;
2454                         s->skipdct=1;
2455                         encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2456                                         &dmin, &next_block, mx, my);
2457                         s->skipdct=0;
2458                     }
2459                 }
2460
2461                 s->current_picture.qscale_table[xy]= best_s.qscale;
2462
2463                 copy_context_after_encode(s, &best_s, -1);
2464
2465                 pb_bits_count= put_bits_count(&s->pb);
2466                 flush_put_bits(&s->pb);
2467                 ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
2468                 s->pb= backup_s.pb;
2469
2470                 if(s->data_partitioning){
2471                     pb2_bits_count= put_bits_count(&s->pb2);
2472                     flush_put_bits(&s->pb2);
2473                     ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
2474                     s->pb2= backup_s.pb2;
2475
2476                     tex_pb_bits_count= put_bits_count(&s->tex_pb);
2477                     flush_put_bits(&s->tex_pb);
2478                     ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
2479                     s->tex_pb= backup_s.tex_pb;
2480                 }
2481                 s->last_bits= put_bits_count(&s->pb);
2482
2483                 if (CONFIG_H263_ENCODER &&
2484                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
2485                     ff_h263_update_motion_val(s);
2486
2487                 if(next_block==0){ //FIXME 16 vs linesize16
2488                     s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad                     , s->linesize  ,16);
2489                     s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize    , s->uvlinesize, 8);
2490                     s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
2491                 }
2492
2493                 if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
2494                     MPV_decode_mb(s, s->block);
2495             } else {
2496                 int motion_x = 0, motion_y = 0;
2497                 s->mv_type=MV_TYPE_16X16;
2498                 // only one MB-Type possible
2499
2500                 switch(mb_type){
2501                 case CANDIDATE_MB_TYPE_INTRA:
2502                     s->mv_dir = 0;
2503                     s->mb_intra= 1;
2504                     motion_x= s->mv[0][0][0] = 0;
2505                     motion_y= s->mv[0][0][1] = 0;
2506                     break;
2507                 case CANDIDATE_MB_TYPE_INTER:
2508                     s->mv_dir = MV_DIR_FORWARD;
2509                     s->mb_intra= 0;
2510                     motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
2511                     motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
2512                     break;
2513                 case CANDIDATE_MB_TYPE_INTER_I:
2514                     s->mv_dir = MV_DIR_FORWARD;
2515                     s->mv_type = MV_TYPE_FIELD;
2516                     s->mb_intra= 0;
2517                     for(i=0; i<2; i++){
2518                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2519                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2520                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2521                     }
2522                     break;
2523                 case CANDIDATE_MB_TYPE_INTER4V:
2524                     s->mv_dir = MV_DIR_FORWARD;
2525                     s->mv_type = MV_TYPE_8X8;
2526                     s->mb_intra= 0;
2527                     for(i=0; i<4; i++){
2528                         s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
2529                         s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
2530                     }
2531                     break;
2532                 case CANDIDATE_MB_TYPE_DIRECT:
2533                     if (CONFIG_MPEG4_ENCODER) {
2534                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2535                         s->mb_intra= 0;
2536                         motion_x=s->b_direct_mv_table[xy][0];
2537                         motion_y=s->b_direct_mv_table[xy][1];
2538                         ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
2539                     }
2540                     break;
2541                 case CANDIDATE_MB_TYPE_DIRECT0:
2542                     if (CONFIG_MPEG4_ENCODER) {
2543                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2544                         s->mb_intra= 0;
2545                         ff_mpeg4_set_direct_mv(s, 0, 0);
2546                     }
2547                     break;
2548                 case CANDIDATE_MB_TYPE_BIDIR:
2549                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2550                     s->mb_intra= 0;
2551                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2552                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2553                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2554                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2555                     break;
2556                 case CANDIDATE_MB_TYPE_BACKWARD:
2557                     s->mv_dir = MV_DIR_BACKWARD;
2558                     s->mb_intra= 0;
2559                     motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2560                     motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2561                     break;
2562                 case CANDIDATE_MB_TYPE_FORWARD:
2563                     s->mv_dir = MV_DIR_FORWARD;
2564                     s->mb_intra= 0;
2565                     motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2566                     motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2567 //                    printf(" %d %d ", motion_x, motion_y);
2568                     break;
2569                 case CANDIDATE_MB_TYPE_FORWARD_I:
2570                     s->mv_dir = MV_DIR_FORWARD;
2571                     s->mv_type = MV_TYPE_FIELD;
2572                     s->mb_intra= 0;
2573                     for(i=0; i<2; i++){
2574                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2575                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2576                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2577                     }
2578                     break;
2579                 case CANDIDATE_MB_TYPE_BACKWARD_I:
2580                     s->mv_dir = MV_DIR_BACKWARD;
2581                     s->mv_type = MV_TYPE_FIELD;
2582                     s->mb_intra= 0;
2583                     for(i=0; i<2; i++){
2584                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2585                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2586                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2587                     }
2588                     break;
2589                 case CANDIDATE_MB_TYPE_BIDIR_I:
2590                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2591                     s->mv_type = MV_TYPE_FIELD;
2592                     s->mb_intra= 0;
2593                     for(dir=0; dir<2; dir++){
2594                         for(i=0; i<2; i++){
2595                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2596                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2597                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2598                         }
2599                     }
2600                     break;
2601                 default:
2602                     av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
2603                 }
2604
2605                 encode_mb(s, motion_x, motion_y);
2606
2607                 // RAL: Update last macroblock type
2608                 s->last_mv_dir = s->mv_dir;
2609
2610                 if (CONFIG_H263_ENCODER &&
2611                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
2612                     ff_h263_update_motion_val(s);
2613
2614                 MPV_decode_mb(s, s->block);
2615             }
2616
2617             /* clean the MV table in IPS frames for direct mode in B frames */
2618             if(s->mb_intra /* && I,P,S_TYPE */){
2619                 s->p_mv_table[xy][0]=0;
2620                 s->p_mv_table[xy][1]=0;
2621             }
2622
2623             if(s->flags&CODEC_FLAG_PSNR){
2624                 int w= 16;
2625                 int h= 16;
2626
2627                 if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
2628                 if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
2629
2630                 s->current_picture.error[0] += sse(
2631                     s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
2632                     s->dest[0], w, h, s->linesize);
2633                 s->current_picture.error[1] += sse(
2634                     s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
2635                     s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
2636                 s->current_picture.error[2] += sse(
2637                     s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
2638                     s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
2639             }
2640             if(s->loop_filter){
2641                 if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
2642                     ff_h263_loop_filter(s);
2643             }
2644 //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
2645         }
2646     }
2647
2648     //not beautiful here but we must write it before flushing so it has to be here
2649     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
2650         msmpeg4_encode_ext_header(s);
2651
2652     write_slice_end(s);
2653
2654     /* Send the last GOB if RTP */
2655     if (s->avctx->rtp_callback) {
2656         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
2657         pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
2658         /* Call the RTP callback to send the last GOB */
2659         emms_c();
2660         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
2661     }
2662
2663     return 0;
2664 }
2665
2666 #define MERGE(field) dst->field += src->field; src->field=0
2667 static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
2668     MERGE(me.scene_change_score);
2669     MERGE(me.mc_mb_var_sum_temp);
2670     MERGE(me.mb_var_sum_temp);
2671 }
2672
2673 static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
2674     int i;
2675
2676     MERGE(dct_count[0]); //note, the other dct vars are not part of the context
2677     MERGE(dct_count[1]);
2678     MERGE(mv_bits);
2679     MERGE(i_tex_bits);
2680     MERGE(p_tex_bits);
2681     MERGE(i_count);
2682     MERGE(f_count);
2683     MERGE(b_count);
2684     MERGE(skip_count);
2685     MERGE(misc_bits);
2686     MERGE(error_count);
2687     MERGE(padding_bug_score);
2688     MERGE(current_picture.error[0]);
2689     MERGE(current_picture.error[1]);
2690     MERGE(current_picture.error[2]);
2691
2692     if(dst->avctx->noise_reduction){
2693         for(i=0; i<64; i++){
2694             MERGE(dct_error_sum[0][i]);
2695             MERGE(dct_error_sum[1][i]);
2696         }
2697     }
2698
2699     assert(put_bits_count(&src->pb) % 8 ==0);
2700     assert(put_bits_count(&dst->pb) % 8 ==0);
2701     ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
2702     flush_put_bits(&dst->pb);
2703 }
2704
2705 static int estimate_qp(MpegEncContext *s, int dry_run){
2706     if (s->next_lambda){
2707         s->current_picture_ptr->quality=
2708         s->current_picture.quality = s->next_lambda;
2709         if(!dry_run) s->next_lambda= 0;
2710     } else if (!s->fixed_qscale) {
2711         s->current_picture_ptr->quality=
2712         s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
2713         if (s->current_picture.quality < 0)
2714             return -1;
2715     }
2716
2717     if(s->adaptive_quant){
2718         switch(s->codec_id){
2719         case CODEC_ID_MPEG4:
2720             if (CONFIG_MPEG4_ENCODER)
2721                 ff_clean_mpeg4_qscales(s);
2722             break;
2723         case CODEC_ID_H263:
2724         case CODEC_ID_H263P:
2725         case CODEC_ID_FLV1:
2726             if (CONFIG_H263_ENCODER)
2727                 ff_clean_h263_qscales(s);
2728             break;
2729         default:
2730             ff_init_qscale_tab(s);
2731         }
2732
2733         s->lambda= s->lambda_table[0];
2734         //FIXME broken
2735     }else
2736         s->lambda= s->current_picture.quality;
2737 //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
2738     update_qscale(s);
2739     return 0;
2740 }
2741
2742 /* must be called before writing the header */
2743 static void set_frame_distances(MpegEncContext * s){
2744     assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
2745     s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
2746
2747     if(s->pict_type==AV_PICTURE_TYPE_B){
2748         s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2749         assert(s->pb_time > 0 && s->pb_time < s->pp_time);
2750     }else{
2751         s->pp_time= s->time - s->last_non_b_time;
2752         s->last_non_b_time= s->time;
2753         assert(s->picture_number==0 || s->pp_time > 0);
2754     }
2755 }
2756
2757 static int encode_picture(MpegEncContext *s, int picture_number)
2758 {
2759     int i;
2760     int bits;
2761     int context_count = s->avctx->thread_count;
2762
2763     s->picture_number = picture_number;
2764
2765     /* Reset the average MB variance */
2766     s->me.mb_var_sum_temp    =
2767     s->me.mc_mb_var_sum_temp = 0;
2768
2769     /* we need to initialize some time vars before we can encode b-frames */
2770     // RAL: Condition added for MPEG1VIDEO
2771     if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
2772         set_frame_distances(s);
2773     if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
2774         ff_set_mpeg4_time(s);
2775
2776     s->me.scene_change_score=0;
2777
2778 //    s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
2779
2780     if(s->pict_type==AV_PICTURE_TYPE_I){
2781         if(s->msmpeg4_version >= 3) s->no_rounding=1;
2782         else                        s->no_rounding=0;
2783     }else if(s->pict_type!=AV_PICTURE_TYPE_B){
2784         if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
2785             s->no_rounding ^= 1;
2786     }
2787
2788     if(s->flags & CODEC_FLAG_PASS2){
2789         if (estimate_qp(s,1) < 0)
2790             return -1;
2791         ff_get_2pass_fcode(s);
2792     }else if(!(s->flags & CODEC_FLAG_QSCALE)){
2793         if(s->pict_type==AV_PICTURE_TYPE_B)
2794             s->lambda= s->last_lambda_for[s->pict_type];
2795         else
2796             s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
2797         update_qscale(s);
2798     }
2799
2800     s->mb_intra=0; //for the rate distortion & bit compare functions
2801     for(i=1; i<context_count; i++){
2802         ff_update_duplicate_context(s->thread_context[i], s);
2803     }
2804
2805     if(ff_init_me(s)<0)
2806         return -1;
2807
2808     /* Estimate motion for every MB */
2809     if(s->pict_type != AV_PICTURE_TYPE_I){
2810         s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
2811         s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
2812         if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
2813             if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
2814                 s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2815             }
2816         }
2817
2818         s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2819     }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
2820         /* I-Frame */
2821         for(i=0; i<s->mb_stride*s->mb_height; i++)
2822             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2823
2824         if(!s->fixed_qscale){
2825             /* finding spatial complexity for I-frame rate control */
2826             s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2827         }
2828     }
2829     for(i=1; i<context_count; i++){
2830         merge_context_after_me(s, s->thread_context[i]);
2831     }
2832     s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
2833     s->current_picture.   mb_var_sum= s->current_picture_ptr->   mb_var_sum= s->me.   mb_var_sum_temp;
2834     emms_c();
2835
2836     if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
2837         s->pict_type= AV_PICTURE_TYPE_I;
2838         for(i=0; i<s->mb_stride*s->mb_height; i++)
2839             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2840 //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
2841     }
2842
2843     if(!s->umvplus){
2844         if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
2845             s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
2846
2847             if(s->flags & CODEC_FLAG_INTERLACED_ME){
2848                 int a,b;
2849                 a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
2850                 b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
2851                 s->f_code= FFMAX3(s->f_code, a, b);
2852             }
2853
2854             ff_fix_long_p_mvs(s);
2855             ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
2856             if(s->flags & CODEC_FLAG_INTERLACED_ME){
2857                 int j;
2858                 for(i=0; i<2; i++){
2859                     for(j=0; j<2; j++)
2860                         ff_fix_long_mvs(s, s->p_field_select_table[i], j,
2861                                         s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
2862                 }
2863             }
2864         }
2865
2866         if(s->pict_type==AV_PICTURE_TYPE_B){
2867             int a, b;
2868
2869             a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
2870             b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2871             s->f_code = FFMAX(a, b);
2872
2873             a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
2874             b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2875             s->b_code = FFMAX(a, b);
2876
2877             ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
2878             ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
2879             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2880             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2881             if(s->flags & CODEC_FLAG_INTERLACED_ME){
2882                 int dir, j;
2883                 for(dir=0; dir<2; dir++){
2884                     for(i=0; i<2; i++){
2885                         for(j=0; j<2; j++){
2886                             int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
2887                                           : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
2888                             ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
2889                                             s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
2890                         }
2891                     }
2892                 }
2893             }
2894         }
2895     }
2896
2897     if (estimate_qp(s, 0) < 0)
2898         return -1;
2899
2900     if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
2901         s->qscale= 3; //reduce clipping problems
2902
2903     if (s->out_format == FMT_MJPEG) {
2904         /* for mjpeg, we do include qscale in the matrix */
2905         for(i=1;i<64;i++){
2906             int j= s->dsp.idct_permutation[i];
2907
2908             s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
2909         }
2910         s->y_dc_scale_table=
2911         s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
2912         s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
2913         ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
2914                        s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
2915         s->qscale= 8;
2916     }
2917
2918     //FIXME var duplication
2919     s->current_picture_ptr->key_frame=
2920     s->current_picture.key_frame= s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
2921     s->current_picture_ptr->pict_type=
2922     s->current_picture.pict_type= s->pict_type;
2923
2924     if(s->current_picture.key_frame)
2925         s->picture_in_gop_number=0;
2926
2927     s->last_bits= put_bits_count(&s->pb);
2928     switch(s->out_format) {
2929     case FMT_MJPEG:
2930         if (CONFIG_MJPEG_ENCODER)
2931             ff_mjpeg_encode_picture_header(s);
2932         break;
2933     case FMT_H261:
2934         if (CONFIG_H261_ENCODER)
2935             ff_h261_encode_picture_header(s, picture_number);
2936         break;
2937     case FMT_H263:
2938         if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
2939             ff_wmv2_encode_picture_header(s, picture_number);
2940         else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
2941             msmpeg4_encode_picture_header(s, picture_number);
2942         else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
2943             mpeg4_encode_picture_header(s, picture_number);
2944         else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
2945             rv10_encode_picture_header(s, picture_number);
2946         else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
2947             rv20_encode_picture_header(s, picture_number);
2948         else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
2949             ff_flv_encode_picture_header(s, picture_number);
2950         else if (CONFIG_H263_ENCODER)
2951             h263_encode_picture_header(s, picture_number);
2952         break;
2953     case FMT_MPEG1:
2954         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
2955             mpeg1_encode_picture_header(s, picture_number);
2956         break;
2957     case FMT_H264:
2958         break;
2959     default:
2960         assert(0);
2961     }
2962     bits= put_bits_count(&s->pb);
2963     s->header_bits= bits - s->last_bits;
2964
2965     for(i=1; i<context_count; i++){
2966         update_duplicate_context_after_me(s->thread_context[i], s);
2967     }
2968     s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2969     for(i=1; i<context_count; i++){
2970         merge_context_after_encode(s, s->thread_context[i]);
2971     }
2972     emms_c();
2973     return 0;
2974 }
2975
2976 static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
2977     const int intra= s->mb_intra;
2978     int i;
2979
2980     s->dct_count[intra]++;
2981
2982     for(i=0; i<64; i++){
2983         int level= block[i];
2984
2985         if(level){
2986             if(level>0){
2987                 s->dct_error_sum[intra][i] += level;
2988                 level -= s->dct_offset[intra][i];
2989                 if(level<0) level=0;
2990             }else{
2991                 s->dct_error_sum[intra][i] -= level;
2992                 level += s->dct_offset[intra][i];
2993                 if(level>0) level=0;
2994             }
2995             block[i]= level;
2996         }
2997     }
2998 }
2999
3000 static int dct_quantize_trellis_c(MpegEncContext *s,
3001                                   DCTELEM *block, int n,
3002                                   int qscale, int *overflow){
3003     const int *qmat;
3004     const uint8_t *scantable= s->intra_scantable.scantable;
3005     const uint8_t *perm_scantable= s->intra_scantable.permutated;
3006     int max=0;
3007     unsigned int threshold1, threshold2;
3008     int bias=0;
3009     int run_tab[65];
3010     int level_tab[65];
3011     int score_tab[65];
3012     int survivor[65];
3013     int survivor_count;
3014     int last_run=0;
3015     int last_level=0;
3016     int last_score= 0;
3017     int last_i;
3018     int coeff[2][64];
3019     int coeff_count[64];
3020     int qmul, qadd, start_i, last_non_zero, i, dc;
3021     const int esc_length= s->ac_esc_length;
3022     uint8_t * length;
3023     uint8_t * last_length;
3024     const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
3025
3026     s->dsp.fdct (block);
3027
3028     if(s->dct_error_sum)
3029         s->denoise_dct(s, block);
3030     qmul= qscale*16;
3031     qadd= ((qscale-1)|1)*8;
3032
3033     if (s->mb_intra) {
3034         int q;
3035         if (!s->h263_aic) {
3036             if (n < 4)
3037                 q = s->y_dc_scale;
3038             else
3039                 q = s->c_dc_scale;
3040             q = q << 3;
3041         } else{
3042             /* For AIC we skip quant/dequant of INTRADC */
3043             q = 1 << 3;
3044             qadd=0;
3045         }
3046
3047         /* note: block[0] is assumed to be positive */
3048         block[0] = (block[0] + (q >> 1)) / q;
3049         start_i = 1;
3050         last_non_zero = 0;
3051         qmat = s->q_intra_matrix[qscale];
3052         if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3053             bias= 1<<(QMAT_SHIFT-1);
3054         length     = s->intra_ac_vlc_length;
3055         last_length= s->intra_ac_vlc_last_length;
3056     } else {
3057         start_i = 0;
3058         last_non_zero = -1;
3059         qmat = s->q_inter_matrix[qscale];
3060         length     = s->inter_ac_vlc_length;
3061         last_length= s->inter_ac_vlc_last_length;
3062     }
3063     last_i= start_i;
3064
3065     threshold1= (1<<QMAT_SHIFT) - bias - 1;
3066     threshold2= (threshold1<<1);
3067
3068     for(i=63; i>=start_i; i--) {
3069         const int j = scantable[i];
3070         int level = block[j] * qmat[j];
3071
3072         if(((unsigned)(level+threshold1))>threshold2){
3073             last_non_zero = i;
3074             break;
3075         }
3076     }
3077
3078     for(i=start_i; i<=last_non_zero; i++) {
3079         const int j = scantable[i];
3080         int level = block[j] * qmat[j];
3081
3082 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
3083 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
3084         if(((unsigned)(level+threshold1))>threshold2){
3085             if(level>0){
3086                 level= (bias + level)>>QMAT_SHIFT;
3087                 coeff[0][i]= level;
3088                 coeff[1][i]= level-1;
3089 //                coeff[2][k]= level-2;
3090             }else{
3091                 level= (bias - level)>>QMAT_SHIFT;
3092                 coeff[0][i]= -level;
3093                 coeff[1][i]= -level+1;
3094 //                coeff[2][k]= -level+2;
3095             }
3096             coeff_count[i]= FFMIN(level, 2);
3097             assert(coeff_count[i]);
3098             max |=level;
3099         }else{
3100             coeff[0][i]= (level>>31)|1;
3101             coeff_count[i]= 1;
3102         }
3103     }
3104
3105     *overflow= s->max_qcoeff < max; //overflow might have happened
3106
3107     if(last_non_zero < start_i){
3108         memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3109         return last_non_zero;
3110     }
3111
3112     score_tab[start_i]= 0;
3113     survivor[0]= start_i;
3114     survivor_count= 1;
3115
3116     for(i=start_i; i<=last_non_zero; i++){
3117         int level_index, j, zero_distortion;
3118         int dct_coeff= FFABS(block[ scantable[i] ]);
3119         int best_score=256*256*256*120;
3120
3121         if (   s->dsp.fdct == fdct_ifast
3122 #ifndef FAAN_POSTSCALE
3123             || s->dsp.fdct == ff_faandct
3124 #endif
3125            )
3126             dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
3127         zero_distortion= dct_coeff*dct_coeff;
3128
3129         for(level_index=0; level_index < coeff_count[i]; level_index++){
3130             int distortion;
3131             int level= coeff[level_index][i];
3132             const int alevel= FFABS(level);
3133             int unquant_coeff;
3134
3135             assert(level);
3136
3137             if(s->out_format == FMT_H263){
3138                 unquant_coeff= alevel*qmul + qadd;
3139             }else{ //MPEG1
3140                 j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
3141                 if(s->mb_intra){
3142                         unquant_coeff = (int)(  alevel  * qscale * s->intra_matrix[j]) >> 3;
3143                         unquant_coeff =   (unquant_coeff - 1) | 1;
3144                 }else{
3145                         unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
3146                         unquant_coeff =   (unquant_coeff - 1) | 1;
3147                 }
3148                 unquant_coeff<<= 3;
3149             }
3150
3151             distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
3152             level+=64;
3153             if((level&(~127)) == 0){
3154                 for(j=survivor_count-1; j>=0; j--){
3155                     int run= i - survivor[j];
3156                     int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3157                     score += score_tab[i-run];
3158
3159                     if(score < best_score){
3160                         best_score= score;
3161                         run_tab[i+1]= run;
3162                         level_tab[i+1]= level-64;
3163                     }
3164                 }
3165
3166                 if(s->out_format == FMT_H263){
3167                     for(j=survivor_count-1; j>=0; j--){
3168                         int run= i - survivor[j];
3169                         int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3170                         score += score_tab[i-run];
3171                         if(score < last_score){
3172                             last_score= score;
3173                             last_run= run;
3174                             last_level= level-64;
3175                             last_i= i+1;
3176                         }
3177                     }
3178                 }
3179             }else{
3180                 distortion += esc_length*lambda;
3181                 for(j=survivor_count-1; j>=0; j--){
3182                     int run= i - survivor[j];
3183                     int score= distortion + score_tab[i-run];
3184
3185                     if(score < best_score){
3186                         best_score= score;
3187                         run_tab[i+1]= run;
3188                         level_tab[i+1]= level-64;
3189                     }
3190                 }
3191
3192                 if(s->out_format == FMT_H263){
3193                   for(j=survivor_count-1; j>=0; j--){
3194                         int run= i - survivor[j];
3195                         int score= distortion + score_tab[i-run];
3196                         if(score < last_score){
3197                             last_score= score;
3198                             last_run= run;
3199                             last_level= level-64;
3200                             last_i= i+1;
3201                         }
3202                     }
3203                 }
3204             }
3205         }
3206
3207         score_tab[i+1]= best_score;
3208
3209         //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
3210         if(last_non_zero <= 27){
3211             for(; survivor_count; survivor_count--){
3212                 if(score_tab[ survivor[survivor_count-1] ] <= best_score)
3213                     break;
3214             }
3215         }else{
3216             for(; survivor_count; survivor_count--){
3217                 if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
3218                     break;
3219             }
3220         }
3221
3222         survivor[ survivor_count++ ]= i+1;
3223     }
3224
3225     if(s->out_format != FMT_H263){
3226         last_score= 256*256*256*120;
3227         for(i= survivor[0]; i<=last_non_zero + 1; i++){
3228             int score= score_tab[i];
3229             if(i) score += lambda*2; //FIXME exacter?
3230
3231             if(score < last_score){
3232                 last_score= score;
3233                 last_i= i;
3234                 last_level= level_tab[i];
3235                 last_run= run_tab[i];
3236             }
3237         }
3238     }
3239
3240     s->coded_score[n] = last_score;
3241
3242     dc= FFABS(block[0]);
3243     last_non_zero= last_i - 1;
3244     memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3245
3246     if(last_non_zero < start_i)
3247         return last_non_zero;
3248
3249     if(last_non_zero == 0 && start_i == 0){
3250         int best_level= 0;
3251         int best_score= dc * dc;
3252
3253         for(i=0; i<coeff_count[0]; i++){
3254             int level= coeff[i][0];
3255             int alevel= FFABS(level);
3256             int unquant_coeff, score, distortion;
3257
3258             if(s->out_format == FMT_H263){
3259                     unquant_coeff= (alevel*qmul + qadd)>>3;
3260             }else{ //MPEG1
3261                     unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
3262                     unquant_coeff =   (unquant_coeff - 1) | 1;
3263             }
3264             unquant_coeff = (unquant_coeff + 4) >> 3;
3265             unquant_coeff<<= 3 + 3;
3266
3267             distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
3268             level+=64;
3269             if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
3270             else                    score= distortion + esc_length*lambda;
3271
3272             if(score < best_score){
3273                 best_score= score;
3274                 best_level= level - 64;
3275             }
3276         }
3277         block[0]= best_level;
3278         s->coded_score[n] = best_score - dc*dc;
3279         if(best_level == 0) return -1;
3280         else                return last_non_zero;
3281     }
3282
3283     i= last_i;
3284     assert(last_level);
3285
3286     block[ perm_scantable[last_non_zero] ]= last_level;
3287     i -= last_run + 1;
3288
3289     for(; i>start_i; i -= run_tab[i] + 1){
3290         block[ perm_scantable[i-1] ]= level_tab[i];
3291     }
3292
3293     return last_non_zero;
3294 }
3295
3296 //#define REFINE_STATS 1
3297 static int16_t basis[64][64];
3298
3299 static void build_basis(uint8_t *perm){
3300     int i, j, x, y;
3301     emms_c();
3302     for(i=0; i<8; i++){
3303         for(j=0; j<8; j++){
3304             for(y=0; y<8; y++){
3305                 for(x=0; x<8; x++){
3306                     double s= 0.25*(1<<BASIS_SHIFT);
3307                     int index= 8*i + j;
3308                     int perm_index= perm[index];
3309                     if(i==0) s*= sqrt(0.5);
3310                     if(j==0) s*= sqrt(0.5);
3311                     basis[perm_index][8*x + y]= lrintf(s * cos((M_PI/8.0)*i*(x+0.5)) * cos((M_PI/8.0)*j*(y+0.5)));
3312                 }
3313             }
3314         }
3315     }
3316 }
3317
3318 static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
3319                         DCTELEM *block, int16_t *weight, DCTELEM *orig,
3320                         int n, int qscale){
3321     int16_t rem[64];
3322     LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
3323     const uint8_t *scantable= s->intra_scantable.scantable;
3324     const uint8_t *perm_scantable= s->intra_scantable.permutated;
3325 //    unsigned int threshold1, threshold2;
3326 //    int bias=0;
3327     int run_tab[65];
3328     int prev_run=0;
3329     int prev_level=0;
3330     int qmul, qadd, start_i, last_non_zero, i, dc;
3331     uint8_t * length;
3332     uint8_t * last_length;
3333     int lambda;
3334     int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
3335 #ifdef REFINE_STATS
3336 static int count=0;
3337 static int after_last=0;
3338 static int to_zero=0;
3339 static int from_zero=0;
3340 static int raise=0;
3341 static int lower=0;
3342 static int messed_sign=0;
3343 #endif
3344
3345     if(basis[0][0] == 0)
3346         build_basis(s->dsp.idct_permutation);
3347
3348     qmul= qscale*2;
3349     qadd= (qscale-1)|1;
3350     if (s->mb_intra) {
3351         if (!s->h263_aic) {
3352             if (n < 4)
3353                 q = s->y_dc_scale;
3354             else
3355                 q = s->c_dc_scale;
3356         } else{
3357             /* For AIC we skip quant/dequant of INTRADC */
3358             q = 1;
3359             qadd=0;
3360         }
3361         q <<= RECON_SHIFT-3;
3362         /* note: block[0] is assumed to be positive */
3363         dc= block[0]*q;
3364 //        block[0] = (block[0] + (q >> 1)) / q;
3365         start_i = 1;
3366 //        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3367 //            bias= 1<<(QMAT_SHIFT-1);
3368         length     = s->intra_ac_vlc_length;
3369         last_length= s->intra_ac_vlc_last_length;
3370     } else {
3371         dc= 0;
3372         start_i = 0;
3373         length     = s->inter_ac_vlc_length;
3374         last_length= s->inter_ac_vlc_last_length;
3375     }
3376     last_non_zero = s->block_last_index[n];
3377
3378 #ifdef REFINE_STATS
3379 {START_TIMER
3380 #endif
3381     dc += (1<<(RECON_SHIFT-1));
3382     for(i=0; i<64; i++){
3383         rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME  use orig dirrectly instead of copying to rem[]
3384     }
3385 #ifdef REFINE_STATS
3386 STOP_TIMER("memset rem[]")}
3387 #endif
3388     sum=0;
3389     for(i=0; i<64; i++){
3390         int one= 36;
3391         int qns=4;
3392         int w;
3393
3394         w= FFABS(weight[i]) + qns*one;
3395         w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
3396
3397         weight[i] = w;
3398 //        w=weight[i] = (63*qns + (w/2)) / w;
3399
3400         assert(w>0);
3401         assert(w<(1<<6));
3402         sum += w*w;
3403     }
3404     lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
3405 #ifdef REFINE_STATS
3406 {START_TIMER
3407 #endif
3408     run=0;
3409     rle_index=0;
3410     for(i=start_i; i<=last_non_zero; i++){
3411         int j= perm_scantable[i];
3412         const int level= block[j];
3413         int coeff;
3414
3415         if(level){
3416             if(level<0) coeff= qmul*level - qadd;
3417             else        coeff= qmul*level + qadd;
3418             run_tab[rle_index++]=run;
3419             run=0;
3420
3421             s->dsp.add_8x8basis(rem, basis[j], coeff);
3422         }else{
3423             run++;
3424         }
3425     }
3426 #ifdef REFINE_STATS
3427 if(last_non_zero>0){
3428 STOP_TIMER("init rem[]")
3429 }
3430 }
3431
3432 {START_TIMER
3433 #endif
3434     for(;;){
3435         int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
3436         int best_coeff=0;
3437         int best_change=0;
3438         int run2, best_unquant_change=0, analyze_gradient;
3439 #ifdef REFINE_STATS
3440 {START_TIMER
3441 #endif
3442         analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
3443
3444         if(analyze_gradient){
3445 #ifdef REFINE_STATS
3446 {START_TIMER
3447 #endif
3448             for(i=0; i<64; i++){
3449                 int w= weight[i];
3450
3451                 d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
3452             }
3453 #ifdef REFINE_STATS
3454 STOP_TIMER("rem*w*w")}
3455 {START_TIMER
3456 #endif
3457             s->dsp.fdct(d1);
3458 #ifdef REFINE_STATS
3459 STOP_TIMER("dct")}
3460 #endif
3461         }
3462
3463         if(start_i){
3464             const int level= block[0];
3465             int change, old_coeff;
3466
3467             assert(s->mb_intra);
3468
3469             old_coeff= q*level;
3470
3471             for(change=-1; change<=1; change+=2){
3472                 int new_level= level + change;
3473                 int score, new_coeff;
3474
3475                 new_coeff= q*new_level;
3476                 if(new_coeff >= 2048 || new_coeff < 0)
3477                     continue;
3478
3479                 score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
3480                 if(score<best_score){
3481                     best_score= score;
3482                     best_coeff= 0;
3483                     best_change= change;
3484                     best_unquant_change= new_coeff - old_coeff;
3485                 }
3486             }
3487         }
3488
3489         run=0;
3490         rle_index=0;
3491         run2= run_tab[rle_index++];
3492         prev_level=0;
3493         prev_run=0;
3494
3495         for(i=start_i; i<64; i++){
3496             int j= perm_scantable[i];
3497             const int level= block[j];
3498             int change, old_coeff;
3499
3500             if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
3501                 break;
3502
3503             if(level){
3504                 if(level<0) old_coeff= qmul*level - qadd;
3505                 else        old_coeff= qmul*level + qadd;
3506                 run2= run_tab[rle_index++]; //FIXME ! maybe after last
3507             }else{
3508                 old_coeff=0;
3509                 run2--;
3510                 assert(run2>=0 || i >= last_non_zero );
3511             }
3512
3513             for(change=-1; change<=1; change+=2){
3514                 int new_level= level + change;
3515                 int score, new_coeff, unquant_change;
3516
3517                 score=0;
3518                 if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
3519                    continue;
3520
3521                 if(new_level){
3522                     if(new_level<0) new_coeff= qmul*new_level - qadd;
3523                     else            new_coeff= qmul*new_level + qadd;
3524                     if(new_coeff >= 2048 || new_coeff <= -2048)
3525                         continue;
3526                     //FIXME check for overflow
3527
3528                     if(level){
3529                         if(level < 63 && level > -63){
3530                             if(i < last_non_zero)
3531                                 score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]
3532                                          - length[UNI_AC_ENC_INDEX(run, level+64)];
3533                             else
3534                                 score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
3535                                          - last_length[UNI_AC_ENC_INDEX(run, level+64)];
3536                         }
3537                     }else{
3538                         assert(FFABS(new_level)==1);
3539
3540                         if(analyze_gradient){
3541                             int g= d1[ scantable[i] ];
3542                             if(g && (g^new_level) >= 0)
3543                                 continue;
3544                         }
3545
3546                         if(i < last_non_zero){
3547                             int next_i= i + run2 + 1;
3548                             int next_level= block[ perm_scantable[next_i] ] + 64;
3549
3550                             if(next_level&(~127))
3551                                 next_level= 0;
3552
3553                             if(next_i < last_non_zero)
3554                                 score +=   length[UNI_AC_ENC_INDEX(run, 65)]
3555                                          + length[UNI_AC_ENC_INDEX(run2, next_level)]
3556                                          - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3557                             else
3558                                 score +=  length[UNI_AC_ENC_INDEX(run, 65)]
3559                                         + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3560                                         - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3561                         }else{
3562                             score += last_length[UNI_AC_ENC_INDEX(run, 65)];
3563                             if(prev_level){
3564                                 score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3565                                         - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3566                             }
3567                         }
3568                     }
3569                 }else{
3570                     new_coeff=0;
3571                     assert(FFABS(level)==1);
3572
3573                     if(i < last_non_zero){
3574                         int next_i= i + run2 + 1;
3575                         int next_level= block[ perm_scantable[next_i] ] + 64;
3576
3577                         if(next_level&(~127))
3578                             next_level= 0;
3579
3580                         if(next_i < last_non_zero)
3581                             score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3582                                      - length[UNI_AC_ENC_INDEX(run2, next_level)]
3583                                      - length[UNI_AC_ENC_INDEX(run, 65)];
3584                         else
3585                             score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3586                                      - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3587                                      - length[UNI_AC_ENC_INDEX(run, 65)];
3588                     }else{
3589                         score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
3590                         if(prev_level){
3591                             score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3592                                     - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3593                         }
3594                     }
3595                 }
3596
3597                 score *= lambda;
3598
3599                 unquant_change= new_coeff - old_coeff;
3600                 assert((score < 100*lambda && score > -100*lambda) || lambda==0);
3601
3602                 score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
3603                 if(score<best_score){
3604                     best_score= score;
3605                     best_coeff= i;
3606                     best_change= change;
3607                     best_unquant_change= unquant_change;
3608                 }
3609             }
3610             if(level){
3611                 prev_level= level + 64;
3612                 if(prev_level&(~127))
3613                     prev_level= 0;
3614                 prev_run= run;
3615                 run=0;
3616             }else{
3617                 run++;
3618             }
3619         }
3620 #ifdef REFINE_STATS
3621 STOP_TIMER("iterative step")}
3622 #endif
3623
3624         if(best_change){
3625             int j= perm_scantable[ best_coeff ];
3626
3627             block[j] += best_change;
3628
3629             if(best_coeff > last_non_zero){
3630                 last_non_zero= best_coeff;
3631                 assert(block[j]);
3632 #ifdef REFINE_STATS
3633 after_last++;
3634 #endif
3635             }else{
3636 #ifdef REFINE_STATS
3637 if(block[j]){
3638     if(block[j] - best_change){
3639         if(FFABS(block[j]) > FFABS(block[j] - best_change)){
3640             raise++;
3641         }else{
3642             lower++;
3643         }
3644     }else{
3645         from_zero++;
3646     }
3647 }else{
3648     to_zero++;
3649 }
3650 #endif
3651                 for(; last_non_zero>=start_i; last_non_zero--){
3652                     if(block[perm_scantable[last_non_zero]])
3653                         break;
3654                 }
3655             }
3656 #ifdef REFINE_STATS
3657 count++;
3658 if(256*256*256*64 % count == 0){
3659     printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
3660 }
3661 #endif
3662             run=0;
3663             rle_index=0;
3664             for(i=start_i; i<=last_non_zero; i++){
3665                 int j= perm_scantable[i];
3666                 const int level= block[j];
3667
3668                  if(level){
3669                      run_tab[rle_index++]=run;
3670                      run=0;
3671                  }else{
3672                      run++;
3673                  }
3674             }
3675
3676             s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
3677         }else{
3678             break;
3679         }
3680     }
3681 #ifdef REFINE_STATS
3682 if(last_non_zero>0){
3683 STOP_TIMER("iterative search")
3684 }
3685 }
3686 #endif
3687
3688     return last_non_zero;
3689 }
3690
3691 int dct_quantize_c(MpegEncContext *s,
3692                         DCTELEM *block, int n,
3693                         int qscale, int *overflow)
3694 {
3695     int i, j, level, last_non_zero, q, start_i;
3696     const int *qmat;
3697     const uint8_t *scantable= s->intra_scantable.scantable;
3698     int bias;
3699     int max=0;
3700     unsigned int threshold1, threshold2;
3701
3702     s->dsp.fdct (block);
3703
3704     if(s->dct_error_sum)
3705         s->denoise_dct(s, block);
3706
3707     if (s->mb_intra) {
3708         if (!s->h263_aic) {
3709             if (n < 4)
3710                 q = s->y_dc_scale;
3711             else
3712                 q = s->c_dc_scale;
3713             q = q << 3;
3714         } else
3715             /* For AIC we skip quant/dequant of INTRADC */
3716             q = 1 << 3;
3717
3718         /* note: block[0] is assumed to be positive */
3719         block[0] = (block[0] + (q >> 1)) / q;
3720         start_i = 1;
3721         last_non_zero = 0;
3722         qmat = s->q_intra_matrix[qscale];
3723         bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
3724     } else {
3725         start_i = 0;
3726         last_non_zero = -1;
3727         qmat = s->q_inter_matrix[qscale];
3728         bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
3729     }
3730     threshold1= (1<<QMAT_SHIFT) - bias - 1;
3731     threshold2= (threshold1<<1);
3732     for(i=63;i>=start_i;i--) {
3733         j = scantable[i];
3734         level = block[j] * qmat[j];
3735
3736         if(((unsigned)(level+threshold1))>threshold2){
3737             last_non_zero = i;
3738             break;
3739         }else{
3740             block[j]=0;
3741         }
3742     }
3743     for(i=start_i; i<=last_non_zero; i++) {
3744         j = scantable[i];
3745         level = block[j] * qmat[j];
3746
3747 //        if(   bias+level >= (1<<QMAT_SHIFT)
3748 //           || bias-level >= (1<<QMAT_SHIFT)){
3749         if(((unsigned)(level+threshold1))>threshold2){
3750             if(level>0){
3751                 level= (bias + level)>>QMAT_SHIFT;
3752                 block[j]= level;
3753             }else{
3754                 level= (bias - level)>>QMAT_SHIFT;
3755                 block[j]= -level;
3756             }
3757             max |=level;
3758         }else{
3759             block[j]=0;
3760         }
3761     }
3762     *overflow= s->max_qcoeff < max; //overflow might have happened
3763
3764     /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
3765     if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
3766         ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
3767
3768     return last_non_zero;
3769 }
3770
3771 AVCodec ff_h263_encoder = {
3772     "h263",
3773     AVMEDIA_TYPE_VIDEO,
3774     CODEC_ID_H263,
3775     sizeof(MpegEncContext),
3776     MPV_encode_init,
3777     MPV_encode_picture,
3778     MPV_encode_end,
3779     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3780     .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
3781 };
3782
3783 AVCodec ff_h263p_encoder = {
3784     "h263p",
3785     AVMEDIA_TYPE_VIDEO,
3786     CODEC_ID_H263P,
3787     sizeof(MpegEncContext),
3788     MPV_encode_init,
3789     MPV_encode_picture,
3790     MPV_encode_end,
3791     .capabilities = CODEC_CAP_SLICE_THREADS,
3792     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3793     .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
3794 };
3795
3796 AVCodec ff_msmpeg4v2_encoder = {
3797     "msmpeg4v2",
3798     AVMEDIA_TYPE_VIDEO,
3799     CODEC_ID_MSMPEG4V2,
3800     sizeof(MpegEncContext),
3801     MPV_encode_init,
3802     MPV_encode_picture,
3803     MPV_encode_end,
3804     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3805     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
3806 };
3807
3808 AVCodec ff_msmpeg4v3_encoder = {
3809     "msmpeg4",
3810     AVMEDIA_TYPE_VIDEO,
3811     CODEC_ID_MSMPEG4V3,
3812     sizeof(MpegEncContext),
3813     MPV_encode_init,
3814     MPV_encode_picture,
3815     MPV_encode_end,
3816     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3817     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
3818 };
3819
3820 AVCodec ff_wmv1_encoder = {
3821     "wmv1",
3822     AVMEDIA_TYPE_VIDEO,
3823     CODEC_ID_WMV1,
3824     sizeof(MpegEncContext),
3825     MPV_encode_init,
3826     MPV_encode_picture,
3827     MPV_encode_end,
3828     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3829     .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
3830 };