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