]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegvideo_enc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / 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  * Set 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         if (i < 0)
868             return i;
869
870         pic= (AVFrame*)&s->picture[i];
871         pic->reference= 3;
872
873         for(i=0; i<4; i++){
874             pic->data[i]= pic_arg->data[i];
875             pic->linesize[i]= pic_arg->linesize[i];
876         }
877         if(ff_alloc_picture(s, (Picture*)pic, 1) < 0){
878             return -1;
879         }
880     }else{
881         i= ff_find_unused_picture(s, 0);
882         if (i < 0)
883             return i;
884
885         pic= (AVFrame*)&s->picture[i];
886         pic->reference= 3;
887
888         if(ff_alloc_picture(s, (Picture*)pic, 0) < 0){
889             return -1;
890         }
891
892         if(   pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
893            && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
894            && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
895        // empty
896         }else{
897             int h_chroma_shift, v_chroma_shift;
898             avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
899
900             for(i=0; i<3; i++){
901                 int src_stride= pic_arg->linesize[i];
902                 int dst_stride= i ? s->uvlinesize : s->linesize;
903                 int h_shift= i ? h_chroma_shift : 0;
904                 int v_shift= i ? v_chroma_shift : 0;
905                 int w= s->width >>h_shift;
906                 int h= s->height>>v_shift;
907                 uint8_t *src= pic_arg->data[i];
908                 uint8_t *dst= pic->data[i];
909
910                 if(s->codec_id == CODEC_ID_AMV && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)){
911                     h= ((s->height+15)/16*16)>>v_shift;
912                 }
913
914                 if(!s->avctx->rc_buffer_size)
915                     dst +=INPLACE_OFFSET;
916
917                 if(src_stride==dst_stride)
918                     memcpy(dst, src, src_stride*h);
919                 else{
920                     while(h--){
921                         memcpy(dst, src, w);
922                         dst += dst_stride;
923                         src += src_stride;
924                     }
925                 }
926             }
927         }
928     }
929     copy_picture_attributes(s, pic, pic_arg);
930     pic->pts= pts; //we set this here to avoid modifiying pic_arg
931   }
932
933     /* shift buffer entries */
934     for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
935         s->input_picture[i-1]= s->input_picture[i];
936
937     s->input_picture[encoding_delay]= (Picture*)pic;
938
939     return 0;
940 }
941
942 static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
943     int x, y, plane;
944     int score=0;
945     int64_t score64=0;
946
947     for(plane=0; plane<3; plane++){
948         const int stride = p->f.linesize[plane];
949         const int bw= plane ? 1 : 2;
950         for(y=0; y<s->mb_height*bw; y++){
951             for(x=0; x<s->mb_width*bw; x++){
952                 int off = p->f.type == FF_BUFFER_TYPE_SHARED ? 0: 16;
953                 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);
954
955                 switch(s->avctx->frame_skip_exp){
956                     case 0: score= FFMAX(score, v); break;
957                     case 1: score+= FFABS(v);break;
958                     case 2: score+= v*v;break;
959                     case 3: score64+= FFABS(v*v*(int64_t)v);break;
960                     case 4: score64+= v*v*(int64_t)(v*v);break;
961                 }
962             }
963         }
964     }
965
966     if(score) score64= score;
967
968     if(score64 < s->avctx->frame_skip_threshold)
969         return 1;
970     if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
971         return 1;
972     return 0;
973 }
974
975 static int estimate_best_b_count(MpegEncContext *s){
976     AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
977     AVCodecContext *c = avcodec_alloc_context3(NULL);
978     AVFrame input[FF_MAX_B_FRAMES+2];
979     const int scale= s->avctx->brd_scale;
980     int i, j, out_size, p_lambda, b_lambda, lambda2;
981     int outbuf_size= s->width * s->height; //FIXME
982     uint8_t *outbuf= av_malloc(outbuf_size);
983     int64_t best_rd= INT64_MAX;
984     int best_b_count= -1;
985
986     assert(scale>=0 && scale <=3);
987
988 //    emms_c();
989     p_lambda= s->last_lambda_for[AV_PICTURE_TYPE_P]; //s->next_picture_ptr->quality;
990     b_lambda= s->last_lambda_for[AV_PICTURE_TYPE_B]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
991     if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
992     lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
993
994     c->width = s->width >> scale;
995     c->height= s->height>> scale;
996     c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
997     c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
998     c->mb_decision= s->avctx->mb_decision;
999     c->me_cmp= s->avctx->me_cmp;
1000     c->mb_cmp= s->avctx->mb_cmp;
1001     c->me_sub_cmp= s->avctx->me_sub_cmp;
1002     c->pix_fmt = PIX_FMT_YUV420P;
1003     c->time_base= s->avctx->time_base;
1004     c->max_b_frames= s->max_b_frames;
1005
1006     if (avcodec_open2(c, codec, NULL) < 0)
1007         return -1;
1008
1009     for(i=0; i<s->max_b_frames+2; i++){
1010         int ysize= c->width*c->height;
1011         int csize= (c->width/2)*(c->height/2);
1012         Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
1013
1014         avcodec_get_frame_defaults(&input[i]);
1015         input[i].data[0]= av_malloc(ysize + 2*csize);
1016         input[i].data[1]= input[i].data[0] + ysize;
1017         input[i].data[2]= input[i].data[1] + csize;
1018         input[i].linesize[0]= c->width;
1019         input[i].linesize[1]=
1020         input[i].linesize[2]= c->width/2;
1021
1022         if(pre_input_ptr && (!i || s->input_picture[i-1])) {
1023             pre_input= *pre_input_ptr;
1024
1025             if (pre_input.f.type != FF_BUFFER_TYPE_SHARED && i) {
1026                 pre_input.f.data[0] += INPLACE_OFFSET;
1027                 pre_input.f.data[1] += INPLACE_OFFSET;
1028                 pre_input.f.data[2] += INPLACE_OFFSET;
1029             }
1030
1031             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);
1032             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);
1033             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);
1034         }
1035     }
1036
1037     for(j=0; j<s->max_b_frames+1; j++){
1038         int64_t rd=0;
1039
1040         if(!s->input_picture[j])
1041             break;
1042
1043         c->error[0]= c->error[1]= c->error[2]= 0;
1044
1045         input[0].pict_type= AV_PICTURE_TYPE_I;
1046         input[0].quality= 1 * FF_QP2LAMBDA;
1047         out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
1048 //        rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
1049
1050         for(i=0; i<s->max_b_frames+1; i++){
1051             int is_p= i % (j+1) == j || i==s->max_b_frames;
1052
1053             input[i+1].pict_type= is_p ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
1054             input[i+1].quality= is_p ? p_lambda : b_lambda;
1055             out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
1056             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
1057         }
1058
1059         /* get the delayed frames */
1060         while(out_size){
1061             out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
1062             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
1063         }
1064
1065         rd += c->error[0] + c->error[1] + c->error[2];
1066
1067         if(rd < best_rd){
1068             best_rd= rd;
1069             best_b_count= j;
1070         }
1071     }
1072
1073     av_freep(&outbuf);
1074     avcodec_close(c);
1075     av_freep(&c);
1076
1077     for(i=0; i<s->max_b_frames+2; i++){
1078         av_freep(&input[i].data[0]);
1079     }
1080
1081     return best_b_count;
1082 }
1083
1084 static int select_input_picture(MpegEncContext *s){
1085     int i;
1086
1087     for(i=1; i<MAX_PICTURE_COUNT; i++)
1088         s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
1089     s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
1090
1091     /* set next picture type & ordering */
1092     if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
1093         if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
1094             s->reordered_input_picture[0]= s->input_picture[0];
1095             s->reordered_input_picture[0]->f.pict_type = AV_PICTURE_TYPE_I;
1096             s->reordered_input_picture[0]->f.coded_picture_number = s->coded_picture_number++;
1097         }else{
1098             int b_frames;
1099
1100             if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
1101                 if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
1102                 //FIXME check that te gop check above is +-1 correct
1103 //av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->f.data[0], s->input_picture[0]->pts);
1104
1105                     if (s->input_picture[0]->f.type == FF_BUFFER_TYPE_SHARED) {
1106                         for(i=0; i<4; i++)
1107                             s->input_picture[0]->f.data[i] = NULL;
1108                         s->input_picture[0]->f.type = 0;
1109                     }else{
1110                         assert(   s->input_picture[0]->f.type == FF_BUFFER_TYPE_USER
1111                                || s->input_picture[0]->f.type == FF_BUFFER_TYPE_INTERNAL);
1112
1113                         s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
1114                     }
1115
1116                     emms_c();
1117                     ff_vbv_update(s, 0);
1118
1119                     goto no_output_pic;
1120                 }
1121             }
1122
1123             if(s->flags&CODEC_FLAG_PASS2){
1124                 for(i=0; i<s->max_b_frames+1; i++){
1125                     int pict_num = s->input_picture[0]->f.display_picture_number + i;
1126
1127                     if(pict_num >= s->rc_context.num_entries)
1128                         break;
1129                     if(!s->input_picture[i]){
1130                         s->rc_context.entry[pict_num-1].new_pict_type = AV_PICTURE_TYPE_P;
1131                         break;
1132                     }
1133
1134                     s->input_picture[i]->f.pict_type =
1135                         s->rc_context.entry[pict_num].new_pict_type;
1136                 }
1137             }
1138
1139             if(s->avctx->b_frame_strategy==0){
1140                 b_frames= s->max_b_frames;
1141                 while(b_frames && !s->input_picture[b_frames]) b_frames--;
1142             }else if(s->avctx->b_frame_strategy==1){
1143                 for(i=1; i<s->max_b_frames+1; i++){
1144                     if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
1145                         s->input_picture[i]->b_frame_score=
1146                             get_intra_count(s, s->input_picture[i  ]->f.data[0],
1147                                                s->input_picture[i-1]->f.data[0], s->linesize) + 1;
1148                     }
1149                 }
1150                 for(i=0; i<s->max_b_frames+1; i++){
1151                     if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
1152                 }
1153
1154                 b_frames= FFMAX(0, i-1);
1155
1156                 /* reset scores */
1157                 for(i=0; i<b_frames+1; i++){
1158                     s->input_picture[i]->b_frame_score=0;
1159                 }
1160             }else if(s->avctx->b_frame_strategy==2){
1161                 b_frames= estimate_best_b_count(s);
1162             }else{
1163                 av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
1164                 b_frames=0;
1165             }
1166
1167             emms_c();
1168 //static int b_count=0;
1169 //b_count+= b_frames;
1170 //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
1171
1172             for(i= b_frames - 1; i>=0; i--){
1173                 int type = s->input_picture[i]->f.pict_type;
1174                 if(type && type != AV_PICTURE_TYPE_B)
1175                     b_frames= i;
1176             }
1177             if (s->input_picture[b_frames]->f.pict_type == AV_PICTURE_TYPE_B && b_frames == s->max_b_frames){
1178                 av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
1179             }
1180
1181             if(s->picture_in_gop_number + b_frames >= s->gop_size){
1182               if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
1183                     b_frames= s->gop_size - s->picture_in_gop_number - 1;
1184               }else{
1185                 if(s->flags & CODEC_FLAG_CLOSED_GOP)
1186                     b_frames=0;
1187                 s->input_picture[b_frames]->f.pict_type = AV_PICTURE_TYPE_I;
1188               }
1189             }
1190
1191             if(   (s->flags & CODEC_FLAG_CLOSED_GOP)
1192                && b_frames
1193                && s->input_picture[b_frames]->f.pict_type== AV_PICTURE_TYPE_I)
1194                 b_frames--;
1195
1196             s->reordered_input_picture[0]= s->input_picture[b_frames];
1197             if (s->reordered_input_picture[0]->f.pict_type != AV_PICTURE_TYPE_I)
1198                 s->reordered_input_picture[0]->f.pict_type = AV_PICTURE_TYPE_P;
1199             s->reordered_input_picture[0]->f.coded_picture_number = s->coded_picture_number++;
1200             for(i=0; i<b_frames; i++){
1201                 s->reordered_input_picture[i + 1] = s->input_picture[i];
1202                 s->reordered_input_picture[i + 1]->f.pict_type = AV_PICTURE_TYPE_B;
1203                 s->reordered_input_picture[i + 1]->f.coded_picture_number = s->coded_picture_number++;
1204             }
1205         }
1206     }
1207 no_output_pic:
1208     if(s->reordered_input_picture[0]){
1209         s->reordered_input_picture[0]->f.reference = s->reordered_input_picture[0]->f.pict_type!=AV_PICTURE_TYPE_B ? 3 : 0;
1210
1211         ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
1212
1213         if (s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size) {
1214             // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
1215
1216             Picture *pic;
1217             int i= ff_find_unused_picture(s, 0);
1218             if (i < 0)
1219                 return i;
1220             pic = &s->picture[i];
1221
1222             pic->f.reference = s->reordered_input_picture[0]->f.reference;
1223             if(ff_alloc_picture(s, pic, 0) < 0){
1224                 return -1;
1225             }
1226
1227             /* mark us unused / free shared pic */
1228             if (s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_INTERNAL)
1229                 s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
1230             for(i=0; i<4; i++)
1231                 s->reordered_input_picture[0]->f.data[i] = NULL;
1232             s->reordered_input_picture[0]->f.type = 0;
1233
1234             copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
1235
1236             s->current_picture_ptr= pic;
1237         }else{
1238             // input is not a shared pix -> reuse buffer for current_pix
1239
1240             assert(   s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_USER
1241                    || s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_INTERNAL);
1242
1243             s->current_picture_ptr= s->reordered_input_picture[0];
1244             for(i=0; i<4; i++){
1245                 s->new_picture.f.data[i] += INPLACE_OFFSET;
1246             }
1247         }
1248         ff_copy_picture(&s->current_picture, s->current_picture_ptr);
1249
1250         s->picture_number = s->new_picture.f.display_picture_number;
1251 //printf("dpn:%d\n", s->picture_number);
1252     }else{
1253        memset(&s->new_picture, 0, sizeof(Picture));
1254     }
1255     return 0;
1256 }
1257
1258 int MPV_encode_picture(AVCodecContext *avctx,
1259                        unsigned char *buf, int buf_size, void *data)
1260 {
1261     MpegEncContext *s = avctx->priv_data;
1262     AVFrame *pic_arg = data;
1263     int i, stuffing_count, context_count = avctx->thread_count;
1264
1265     for(i=0; i<context_count; i++){
1266         int start_y= s->thread_context[i]->start_mb_y;
1267         int   end_y= s->thread_context[i]->  end_mb_y;
1268         int h= s->mb_height;
1269         uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
1270         uint8_t *end  = buf + (size_t)(((int64_t) buf_size)*  end_y/h);
1271
1272         init_put_bits(&s->thread_context[i]->pb, start, end - start);
1273     }
1274
1275     s->picture_in_gop_number++;
1276
1277     if(load_input_picture(s, pic_arg) < 0)
1278         return -1;
1279
1280     if(select_input_picture(s) < 0){
1281         return -1;
1282     }
1283
1284     /* output? */
1285     if (s->new_picture.f.data[0]) {
1286         s->pict_type = s->new_picture.f.pict_type;
1287 //emms_c();
1288 //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
1289         MPV_frame_start(s, avctx);
1290 vbv_retry:
1291         if (encode_picture(s, s->picture_number) < 0)
1292             return -1;
1293
1294         avctx->header_bits = s->header_bits;
1295         avctx->mv_bits     = s->mv_bits;
1296         avctx->misc_bits   = s->misc_bits;
1297         avctx->i_tex_bits  = s->i_tex_bits;
1298         avctx->p_tex_bits  = s->p_tex_bits;
1299         avctx->i_count     = s->i_count;
1300         avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
1301         avctx->skip_count  = s->skip_count;
1302
1303         MPV_frame_end(s);
1304
1305         if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
1306             ff_mjpeg_encode_picture_trailer(s);
1307
1308         if(avctx->rc_buffer_size){
1309             RateControlContext *rcc= &s->rc_context;
1310             int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
1311
1312             if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
1313                 s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
1314                 if(s->adaptive_quant){
1315                     int i;
1316                     for(i=0; i<s->mb_height*s->mb_stride; i++)
1317                         s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
1318                 }
1319                 s->mb_skipped = 0;        //done in MPV_frame_start()
1320                 if(s->pict_type==AV_PICTURE_TYPE_P){ //done in encode_picture() so we must undo it
1321                     if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
1322                         s->no_rounding ^= 1;
1323                 }
1324                 if(s->pict_type!=AV_PICTURE_TYPE_B){
1325                     s->time_base= s->last_time_base;
1326                     s->last_non_b_time= s->time - s->pp_time;
1327                 }
1328 //                av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
1329                 for(i=0; i<context_count; i++){
1330                     PutBitContext *pb= &s->thread_context[i]->pb;
1331                     init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
1332                 }
1333                 goto vbv_retry;
1334             }
1335
1336             assert(s->avctx->rc_max_rate);
1337         }
1338
1339         if(s->flags&CODEC_FLAG_PASS1)
1340             ff_write_pass1_stats(s);
1341
1342         for(i=0; i<4; i++){
1343             s->current_picture_ptr->f.error[i]  = s->current_picture.f.error[i];
1344             avctx->error[i]                        += s->current_picture_ptr->f.error[i];
1345         }
1346
1347         if(s->flags&CODEC_FLAG_PASS1)
1348             assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
1349         flush_put_bits(&s->pb);
1350         s->frame_bits  = put_bits_count(&s->pb);
1351
1352         stuffing_count= ff_vbv_update(s, s->frame_bits);
1353         if(stuffing_count){
1354             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
1355                 av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
1356                 return -1;
1357             }
1358
1359             switch(s->codec_id){
1360             case CODEC_ID_MPEG1VIDEO:
1361             case CODEC_ID_MPEG2VIDEO:
1362                 while(stuffing_count--){
1363                     put_bits(&s->pb, 8, 0);
1364                 }
1365             break;
1366             case CODEC_ID_MPEG4:
1367                 put_bits(&s->pb, 16, 0);
1368                 put_bits(&s->pb, 16, 0x1C3);
1369                 stuffing_count -= 4;
1370                 while(stuffing_count--){
1371                     put_bits(&s->pb, 8, 0xFF);
1372                 }
1373             break;
1374             default:
1375                 av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
1376             }
1377             flush_put_bits(&s->pb);
1378             s->frame_bits  = put_bits_count(&s->pb);
1379         }
1380
1381         /* update mpeg1/2 vbv_delay for CBR */
1382         if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
1383            && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
1384             int vbv_delay, min_delay;
1385             double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
1386             int    minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
1387             double bits   = s->rc_context.buffer_index + minbits - inbits;
1388
1389             if(bits<0)
1390                 av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
1391
1392             assert(s->repeat_first_field==0);
1393
1394             vbv_delay=     bits * 90000                               / s->avctx->rc_max_rate;
1395             min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
1396
1397             vbv_delay= FFMAX(vbv_delay, min_delay);
1398
1399             assert(vbv_delay < 0xFFFF);
1400
1401             s->vbv_delay_ptr[0] &= 0xF8;
1402             s->vbv_delay_ptr[0] |= vbv_delay>>13;
1403             s->vbv_delay_ptr[1]  = vbv_delay>>5;
1404             s->vbv_delay_ptr[2] &= 0x07;
1405             s->vbv_delay_ptr[2] |= vbv_delay<<3;
1406             avctx->vbv_delay = vbv_delay*300;
1407         }
1408         s->total_bits += s->frame_bits;
1409         avctx->frame_bits  = s->frame_bits;
1410     }else{
1411         assert((put_bits_ptr(&s->pb) == s->pb.buf));
1412         s->frame_bits=0;
1413     }
1414     assert((s->frame_bits&7)==0);
1415
1416     return s->frame_bits/8;
1417 }
1418
1419 static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
1420 {
1421     static const char tab[64]=
1422         {3,2,2,1,1,1,1,1,
1423          1,1,1,1,1,1,1,1,
1424          1,1,1,1,1,1,1,1,
1425          0,0,0,0,0,0,0,0,
1426          0,0,0,0,0,0,0,0,
1427          0,0,0,0,0,0,0,0,
1428          0,0,0,0,0,0,0,0,
1429          0,0,0,0,0,0,0,0};
1430     int score=0;
1431     int run=0;
1432     int i;
1433     DCTELEM *block= s->block[n];
1434     const int last_index= s->block_last_index[n];
1435     int skip_dc;
1436
1437     if(threshold<0){
1438         skip_dc=0;
1439         threshold= -threshold;
1440     }else
1441         skip_dc=1;
1442
1443     /* Are all we could set to zero already zero? */
1444     if(last_index<=skip_dc - 1) return;
1445
1446     for(i=0; i<=last_index; i++){
1447         const int j = s->intra_scantable.permutated[i];
1448         const int level = FFABS(block[j]);
1449         if(level==1){
1450             if(skip_dc && i==0) continue;
1451             score+= tab[run];
1452             run=0;
1453         }else if(level>1){
1454             return;
1455         }else{
1456             run++;
1457         }
1458     }
1459     if(score >= threshold) return;
1460     for(i=skip_dc; i<=last_index; i++){
1461         const int j = s->intra_scantable.permutated[i];
1462         block[j]=0;
1463     }
1464     if(block[0]) s->block_last_index[n]= 0;
1465     else         s->block_last_index[n]= -1;
1466 }
1467
1468 static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
1469 {
1470     int i;
1471     const int maxlevel= s->max_qcoeff;
1472     const int minlevel= s->min_qcoeff;
1473     int overflow=0;
1474
1475     if(s->mb_intra){
1476         i=1; //skip clipping of intra dc
1477     }else
1478         i=0;
1479
1480     for(;i<=last_index; i++){
1481         const int j= s->intra_scantable.permutated[i];
1482         int level = block[j];
1483
1484         if     (level>maxlevel){
1485             level=maxlevel;
1486             overflow++;
1487         }else if(level<minlevel){
1488             level=minlevel;
1489             overflow++;
1490         }
1491
1492         block[j]= level;
1493     }
1494
1495     if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
1496         av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
1497 }
1498
1499 static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
1500     int x, y;
1501 //FIXME optimize
1502     for(y=0; y<8; y++){
1503         for(x=0; x<8; x++){
1504             int x2, y2;
1505             int sum=0;
1506             int sqr=0;
1507             int count=0;
1508
1509             for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
1510                 for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
1511                     int v= ptr[x2 + y2*stride];
1512                     sum += v;
1513                     sqr += v*v;
1514                     count++;
1515                 }
1516             }
1517             weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
1518         }
1519     }
1520 }
1521
1522 static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
1523 {
1524     int16_t weight[8][64];
1525     DCTELEM orig[8][64];
1526     const int mb_x= s->mb_x;
1527     const int mb_y= s->mb_y;
1528     int i;
1529     int skip_dct[8];
1530     int dct_offset   = s->linesize*8; //default for progressive frames
1531     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
1532     int wrap_y, wrap_c;
1533
1534     for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
1535
1536     if(s->adaptive_quant){
1537         const int last_qp= s->qscale;
1538         const int mb_xy= mb_x + mb_y*s->mb_stride;
1539
1540         s->lambda= s->lambda_table[mb_xy];
1541         update_qscale(s);
1542
1543         if(!(s->flags&CODEC_FLAG_QP_RD)){
1544             s->qscale = s->current_picture_ptr->f.qscale_table[mb_xy];
1545             s->dquant= s->qscale - last_qp;
1546
1547             if(s->out_format==FMT_H263){
1548                 s->dquant= av_clip(s->dquant, -2, 2);
1549
1550                 if(s->codec_id==CODEC_ID_MPEG4){
1551                     if(!s->mb_intra){
1552                         if(s->pict_type == AV_PICTURE_TYPE_B){
1553                             if(s->dquant&1 || s->mv_dir&MV_DIRECT)
1554                                 s->dquant= 0;
1555                         }
1556                         if(s->mv_type==MV_TYPE_8X8)
1557                             s->dquant=0;
1558                     }
1559                 }
1560             }
1561         }
1562         ff_set_qscale(s, last_qp + s->dquant);
1563     }else if(s->flags&CODEC_FLAG_QP_RD)
1564         ff_set_qscale(s, s->qscale + s->dquant);
1565
1566     wrap_y = s->linesize;
1567     wrap_c = s->uvlinesize;
1568     ptr_y  = s->new_picture.f.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
1569     ptr_cb = s->new_picture.f.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1570     ptr_cr = s->new_picture.f.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1571
1572     if((mb_x*16+16 > s->width || mb_y*16+16 > s->height) && s->codec_id != CODEC_ID_AMV){
1573         uint8_t *ebuf= s->edge_emu_buffer + 32;
1574         s->dsp.emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
1575         ptr_y= ebuf;
1576         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);
1577         ptr_cb= ebuf+18*wrap_y;
1578         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);
1579         ptr_cr= ebuf+18*wrap_y+8;
1580     }
1581
1582     if (s->mb_intra) {
1583         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1584             int progressive_score, interlaced_score;
1585
1586             s->interlaced_dct=0;
1587             progressive_score= s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y, 8)
1588                               +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
1589
1590             if(progressive_score > 0){
1591                 interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y*2, 8)
1592                                   +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y  , NULL, wrap_y*2, 8);
1593                 if(progressive_score > interlaced_score){
1594                     s->interlaced_dct=1;
1595
1596                     dct_offset= wrap_y;
1597                     wrap_y<<=1;
1598                     if (s->chroma_format == CHROMA_422)
1599                         wrap_c<<=1;
1600                 }
1601             }
1602         }
1603
1604         s->dsp.get_pixels(s->block[0], ptr_y                 , wrap_y);
1605         s->dsp.get_pixels(s->block[1], ptr_y              + 8, wrap_y);
1606         s->dsp.get_pixels(s->block[2], ptr_y + dct_offset    , wrap_y);
1607         s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
1608
1609         if(s->flags&CODEC_FLAG_GRAY){
1610             skip_dct[4]= 1;
1611             skip_dct[5]= 1;
1612         }else{
1613             s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
1614             s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
1615             if(!s->chroma_y_shift){ /* 422 */
1616                 s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
1617                 s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
1618             }
1619         }
1620     }else{
1621         op_pixels_func (*op_pix)[4];
1622         qpel_mc_func (*op_qpix)[16];
1623         uint8_t *dest_y, *dest_cb, *dest_cr;
1624
1625         dest_y  = s->dest[0];
1626         dest_cb = s->dest[1];
1627         dest_cr = s->dest[2];
1628
1629         if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
1630             op_pix = s->dsp.put_pixels_tab;
1631             op_qpix= s->dsp.put_qpel_pixels_tab;
1632         }else{
1633             op_pix = s->dsp.put_no_rnd_pixels_tab;
1634             op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
1635         }
1636
1637         if (s->mv_dir & MV_DIR_FORWARD) {
1638             MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f.data, op_pix, op_qpix);
1639             op_pix = s->dsp.avg_pixels_tab;
1640             op_qpix= s->dsp.avg_qpel_pixels_tab;
1641         }
1642         if (s->mv_dir & MV_DIR_BACKWARD) {
1643             MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f.data, op_pix, op_qpix);
1644         }
1645
1646         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1647             int progressive_score, interlaced_score;
1648
1649             s->interlaced_dct=0;
1650             progressive_score= s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y, 8)
1651                               +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
1652
1653             if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
1654
1655             if(progressive_score>0){
1656                 interlaced_score = s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y*2, 8)
1657                                   +s->dsp.ildct_cmp[0](s, dest_y + wrap_y  , ptr_y + wrap_y  , wrap_y*2, 8);
1658
1659                 if(progressive_score > interlaced_score){
1660                     s->interlaced_dct=1;
1661
1662                     dct_offset= wrap_y;
1663                     wrap_y<<=1;
1664                     if (s->chroma_format == CHROMA_422)
1665                         wrap_c<<=1;
1666                 }
1667             }
1668         }
1669
1670         s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
1671         s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
1672         s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
1673         s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
1674
1675         if(s->flags&CODEC_FLAG_GRAY){
1676             skip_dct[4]= 1;
1677             skip_dct[5]= 1;
1678         }else{
1679             s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
1680             s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
1681             if(!s->chroma_y_shift){ /* 422 */
1682                 s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
1683                 s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
1684             }
1685         }
1686         /* pre quantization */
1687         if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
1688             //FIXME optimize
1689             if(s->dsp.sad[1](NULL, ptr_y               , dest_y               , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
1690             if(s->dsp.sad[1](NULL, ptr_y            + 8, dest_y            + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
1691             if(s->dsp.sad[1](NULL, ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
1692             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;
1693             if(s->dsp.sad[1](NULL, ptr_cb              , dest_cb              , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
1694             if(s->dsp.sad[1](NULL, ptr_cr              , dest_cr              , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
1695             if(!s->chroma_y_shift){ /* 422 */
1696                 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;
1697                 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;
1698             }
1699         }
1700     }
1701
1702     if(s->avctx->quantizer_noise_shaping){
1703         if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y                 , wrap_y);
1704         if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y              + 8, wrap_y);
1705         if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);
1706         if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
1707         if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb                , wrap_c);
1708         if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr                , wrap_c);
1709         if(!s->chroma_y_shift){ /* 422 */
1710             if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
1711             if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
1712         }
1713         memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
1714     }
1715
1716     /* DCT & quantize */
1717     assert(s->out_format!=FMT_MJPEG || s->qscale==8);
1718     {
1719         for(i=0;i<mb_block_count;i++) {
1720             if(!skip_dct[i]){
1721                 int overflow;
1722                 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
1723             // FIXME we could decide to change to quantizer instead of clipping
1724             // JS: I don't think that would be a good idea it could lower quality instead
1725             //     of improve it. Just INTRADC clipping deserves changes in quantizer
1726                 if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
1727             }else
1728                 s->block_last_index[i]= -1;
1729         }
1730         if(s->avctx->quantizer_noise_shaping){
1731             for(i=0;i<mb_block_count;i++) {
1732                 if(!skip_dct[i]){
1733                     s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
1734                 }
1735             }
1736         }
1737
1738         if(s->luma_elim_threshold && !s->mb_intra)
1739             for(i=0; i<4; i++)
1740                 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
1741         if(s->chroma_elim_threshold && !s->mb_intra)
1742             for(i=4; i<mb_block_count; i++)
1743                 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
1744
1745         if(s->flags & CODEC_FLAG_CBP_RD){
1746             for(i=0;i<mb_block_count;i++) {
1747                 if(s->block_last_index[i] == -1)
1748                     s->coded_score[i]= INT_MAX/256;
1749             }
1750         }
1751     }
1752
1753     if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
1754         s->block_last_index[4]=
1755         s->block_last_index[5]= 0;
1756         s->block[4][0]=
1757         s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
1758     }
1759
1760     //non c quantize code returns incorrect block_last_index FIXME
1761     if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
1762         for(i=0; i<mb_block_count; i++){
1763             int j;
1764             if(s->block_last_index[i]>0){
1765                 for(j=63; j>0; j--){
1766                     if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
1767                 }
1768                 s->block_last_index[i]= j;
1769             }
1770         }
1771     }
1772
1773     /* huffman encode */
1774     switch(s->codec_id){ //FIXME funct ptr could be slightly faster
1775     case CODEC_ID_MPEG1VIDEO:
1776     case CODEC_ID_MPEG2VIDEO:
1777         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
1778             mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1779         break;
1780     case CODEC_ID_MPEG4:
1781         if (CONFIG_MPEG4_ENCODER)
1782             mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1783         break;
1784     case CODEC_ID_MSMPEG4V2:
1785     case CODEC_ID_MSMPEG4V3:
1786     case CODEC_ID_WMV1:
1787         if (CONFIG_MSMPEG4_ENCODER)
1788             msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1789         break;
1790     case CODEC_ID_WMV2:
1791         if (CONFIG_WMV2_ENCODER)
1792             ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
1793         break;
1794     case CODEC_ID_H261:
1795         if (CONFIG_H261_ENCODER)
1796             ff_h261_encode_mb(s, s->block, motion_x, motion_y);
1797         break;
1798     case CODEC_ID_H263:
1799     case CODEC_ID_H263P:
1800     case CODEC_ID_FLV1:
1801     case CODEC_ID_RV10:
1802     case CODEC_ID_RV20:
1803         if (CONFIG_H263_ENCODER)
1804             h263_encode_mb(s, s->block, motion_x, motion_y);
1805         break;
1806     case CODEC_ID_MJPEG:
1807     case CODEC_ID_AMV:
1808         if (CONFIG_MJPEG_ENCODER)
1809             ff_mjpeg_encode_mb(s, s->block);
1810         break;
1811     default:
1812         assert(0);
1813     }
1814 }
1815
1816 static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
1817 {
1818     if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 6);
1819     else                                encode_mb_internal(s, motion_x, motion_y, 16, 8);
1820 }
1821
1822 static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1823     int i;
1824
1825     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
1826
1827     /* mpeg1 */
1828     d->mb_skip_run= s->mb_skip_run;
1829     for(i=0; i<3; i++)
1830         d->last_dc[i]= s->last_dc[i];
1831
1832     /* statistics */
1833     d->mv_bits= s->mv_bits;
1834     d->i_tex_bits= s->i_tex_bits;
1835     d->p_tex_bits= s->p_tex_bits;
1836     d->i_count= s->i_count;
1837     d->f_count= s->f_count;
1838     d->b_count= s->b_count;
1839     d->skip_count= s->skip_count;
1840     d->misc_bits= s->misc_bits;
1841     d->last_bits= 0;
1842
1843     d->mb_skipped= 0;
1844     d->qscale= s->qscale;
1845     d->dquant= s->dquant;
1846
1847     d->esc3_level_length= s->esc3_level_length;
1848 }
1849
1850 static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
1851     int i;
1852
1853     memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
1854     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
1855
1856     /* mpeg1 */
1857     d->mb_skip_run= s->mb_skip_run;
1858     for(i=0; i<3; i++)
1859         d->last_dc[i]= s->last_dc[i];
1860
1861     /* statistics */
1862     d->mv_bits= s->mv_bits;
1863     d->i_tex_bits= s->i_tex_bits;
1864     d->p_tex_bits= s->p_tex_bits;
1865     d->i_count= s->i_count;
1866     d->f_count= s->f_count;
1867     d->b_count= s->b_count;
1868     d->skip_count= s->skip_count;
1869     d->misc_bits= s->misc_bits;
1870
1871     d->mb_intra= s->mb_intra;
1872     d->mb_skipped= s->mb_skipped;
1873     d->mv_type= s->mv_type;
1874     d->mv_dir= s->mv_dir;
1875     d->pb= s->pb;
1876     if(s->data_partitioning){
1877         d->pb2= s->pb2;
1878         d->tex_pb= s->tex_pb;
1879     }
1880     d->block= s->block;
1881     for(i=0; i<8; i++)
1882         d->block_last_index[i]= s->block_last_index[i];
1883     d->interlaced_dct= s->interlaced_dct;
1884     d->qscale= s->qscale;
1885
1886     d->esc3_level_length= s->esc3_level_length;
1887 }
1888
1889 static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
1890                            PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
1891                            int *dmin, int *next_block, int motion_x, int motion_y)
1892 {
1893     int score;
1894     uint8_t *dest_backup[3];
1895
1896     copy_context_before_encode(s, backup, type);
1897
1898     s->block= s->blocks[*next_block];
1899     s->pb= pb[*next_block];
1900     if(s->data_partitioning){
1901         s->pb2   = pb2   [*next_block];
1902         s->tex_pb= tex_pb[*next_block];
1903     }
1904
1905     if(*next_block){
1906         memcpy(dest_backup, s->dest, sizeof(s->dest));
1907         s->dest[0] = s->rd_scratchpad;
1908         s->dest[1] = s->rd_scratchpad + 16*s->linesize;
1909         s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
1910         assert(s->linesize >= 32); //FIXME
1911     }
1912
1913     encode_mb(s, motion_x, motion_y);
1914
1915     score= put_bits_count(&s->pb);
1916     if(s->data_partitioning){
1917         score+= put_bits_count(&s->pb2);
1918         score+= put_bits_count(&s->tex_pb);
1919     }
1920
1921     if(s->avctx->mb_decision == FF_MB_DECISION_RD){
1922         MPV_decode_mb(s, s->block);
1923
1924         score *= s->lambda2;
1925         score += sse_mb(s) << FF_LAMBDA_SHIFT;
1926     }
1927
1928     if(*next_block){
1929         memcpy(s->dest, dest_backup, sizeof(s->dest));
1930     }
1931
1932     if(score<*dmin){
1933         *dmin= score;
1934         *next_block^=1;
1935
1936         copy_context_after_encode(best, s, type);
1937     }
1938 }
1939
1940 static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
1941     uint32_t *sq = ff_squareTbl + 256;
1942     int acc=0;
1943     int x,y;
1944
1945     if(w==16 && h==16)
1946         return s->dsp.sse[0](NULL, src1, src2, stride, 16);
1947     else if(w==8 && h==8)
1948         return s->dsp.sse[1](NULL, src1, src2, stride, 8);
1949
1950     for(y=0; y<h; y++){
1951         for(x=0; x<w; x++){
1952             acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
1953         }
1954     }
1955
1956     assert(acc>=0);
1957
1958     return acc;
1959 }
1960
1961 static int sse_mb(MpegEncContext *s){
1962     int w= 16;
1963     int h= 16;
1964
1965     if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
1966     if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
1967
1968     if(w==16 && h==16)
1969       if(s->avctx->mb_cmp == FF_CMP_NSSE){
1970         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)
1971                +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)
1972                +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);
1973       }else{
1974         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)
1975                +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)
1976                +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);
1977       }
1978     else
1979         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)
1980                +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)
1981                +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);
1982 }
1983
1984 static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
1985     MpegEncContext *s= *(void**)arg;
1986
1987
1988     s->me.pre_pass=1;
1989     s->me.dia_size= s->avctx->pre_dia_size;
1990     s->first_slice_line=1;
1991     for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
1992         for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
1993             ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1994         }
1995         s->first_slice_line=0;
1996     }
1997
1998     s->me.pre_pass=0;
1999
2000     return 0;
2001 }
2002
2003 static int estimate_motion_thread(AVCodecContext *c, void *arg){
2004     MpegEncContext *s= *(void**)arg;
2005
2006     ff_check_alignment();
2007
2008     s->me.dia_size= s->avctx->dia_size;
2009     s->first_slice_line=1;
2010     for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
2011         s->mb_x=0; //for block init below
2012         ff_init_block_index(s);
2013         for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
2014             s->block_index[0]+=2;
2015             s->block_index[1]+=2;
2016             s->block_index[2]+=2;
2017             s->block_index[3]+=2;
2018
2019             /* compute motion vector & mb_type and store in context */
2020             if(s->pict_type==AV_PICTURE_TYPE_B)
2021                 ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
2022             else
2023                 ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
2024         }
2025         s->first_slice_line=0;
2026     }
2027     return 0;
2028 }
2029
2030 static int mb_var_thread(AVCodecContext *c, void *arg){
2031     MpegEncContext *s= *(void**)arg;
2032     int mb_x, mb_y;
2033
2034     ff_check_alignment();
2035
2036     for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2037         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2038             int xx = mb_x * 16;
2039             int yy = mb_y * 16;
2040             uint8_t *pix = s->new_picture.f.data[0] + (yy * s->linesize) + xx;
2041             int varc;
2042             int sum = s->dsp.pix_sum(pix, s->linesize);
2043
2044             varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)sum*sum)>>8) + 500 + 128)>>8;
2045
2046             s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
2047             s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
2048             s->me.mb_var_sum_temp    += varc;
2049         }
2050     }
2051     return 0;
2052 }
2053
2054 static void write_slice_end(MpegEncContext *s){
2055     if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
2056         if(s->partitioned_frame){
2057             ff_mpeg4_merge_partitions(s);
2058         }
2059
2060         ff_mpeg4_stuffing(&s->pb);
2061     }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
2062         ff_mjpeg_encode_stuffing(&s->pb);
2063     }
2064
2065     avpriv_align_put_bits(&s->pb);
2066     flush_put_bits(&s->pb);
2067
2068     if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
2069         s->misc_bits+= get_bits_diff(s);
2070 }
2071
2072 static int encode_thread(AVCodecContext *c, void *arg){
2073     MpegEncContext *s= *(void**)arg;
2074     int mb_x, mb_y, pdif = 0;
2075     int chr_h= 16>>s->chroma_y_shift;
2076     int i, j;
2077     MpegEncContext best_s, backup_s;
2078     uint8_t bit_buf[2][MAX_MB_BYTES];
2079     uint8_t bit_buf2[2][MAX_MB_BYTES];
2080     uint8_t bit_buf_tex[2][MAX_MB_BYTES];
2081     PutBitContext pb[2], pb2[2], tex_pb[2];
2082 //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
2083
2084     ff_check_alignment();
2085
2086     for(i=0; i<2; i++){
2087         init_put_bits(&pb    [i], bit_buf    [i], MAX_MB_BYTES);
2088         init_put_bits(&pb2   [i], bit_buf2   [i], MAX_MB_BYTES);
2089         init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
2090     }
2091
2092     s->last_bits= put_bits_count(&s->pb);
2093     s->mv_bits=0;
2094     s->misc_bits=0;
2095     s->i_tex_bits=0;
2096     s->p_tex_bits=0;
2097     s->i_count=0;
2098     s->f_count=0;
2099     s->b_count=0;
2100     s->skip_count=0;
2101
2102     for(i=0; i<3; i++){
2103         /* init last dc values */
2104         /* note: quant matrix value (8) is implied here */
2105         s->last_dc[i] = 128 << s->intra_dc_precision;
2106
2107         s->current_picture.f.error[i] = 0;
2108     }
2109     if(s->codec_id==CODEC_ID_AMV){
2110         s->last_dc[0] = 128*8/13;
2111         s->last_dc[1] = 128*8/14;
2112         s->last_dc[2] = 128*8/14;
2113     }
2114     s->mb_skip_run = 0;
2115     memset(s->last_mv, 0, sizeof(s->last_mv));
2116
2117     s->last_mv_dir = 0;
2118
2119     switch(s->codec_id){
2120     case CODEC_ID_H263:
2121     case CODEC_ID_H263P:
2122     case CODEC_ID_FLV1:
2123         if (CONFIG_H263_ENCODER)
2124             s->gob_index = ff_h263_get_gob_height(s);
2125         break;
2126     case CODEC_ID_MPEG4:
2127         if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
2128             ff_mpeg4_init_partitions(s);
2129         break;
2130     }
2131
2132     s->resync_mb_x=0;
2133     s->resync_mb_y=0;
2134     s->first_slice_line = 1;
2135     s->ptr_lastgob = s->pb.buf;
2136     for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2137 //    printf("row %d at %X\n", s->mb_y, (int)s);
2138         s->mb_x=0;
2139         s->mb_y= mb_y;
2140
2141         ff_set_qscale(s, s->qscale);
2142         ff_init_block_index(s);
2143
2144         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2145             int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
2146             int mb_type= s->mb_type[xy];
2147 //            int d;
2148             int dmin= INT_MAX;
2149             int dir;
2150
2151             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
2152                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2153                 return -1;
2154             }
2155             if(s->data_partitioning){
2156                 if(   s->pb2   .buf_end - s->pb2   .buf - (put_bits_count(&s->    pb2)>>3) < MAX_MB_BYTES
2157                    || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
2158                     av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2159                     return -1;
2160                 }
2161             }
2162
2163             s->mb_x = mb_x;
2164             s->mb_y = mb_y;  // moved into loop, can get changed by H.261
2165             ff_update_block_index(s);
2166
2167             if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
2168                 ff_h261_reorder_mb_index(s);
2169                 xy= s->mb_y*s->mb_stride + s->mb_x;
2170                 mb_type= s->mb_type[xy];
2171             }
2172
2173             /* write gob / video packet header  */
2174             if(s->rtp_mode){
2175                 int current_packet_size, is_gob_start;
2176
2177                 current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
2178
2179                 is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
2180
2181                 if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
2182
2183                 switch(s->codec_id){
2184                 case CODEC_ID_H263:
2185                 case CODEC_ID_H263P:
2186                     if(!s->h263_slice_structured)
2187                         if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
2188                     break;
2189                 case CODEC_ID_MPEG2VIDEO:
2190                     if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
2191                 case CODEC_ID_MPEG1VIDEO:
2192                     if(s->mb_skip_run) is_gob_start=0;
2193                     break;
2194                 }
2195
2196                 if(is_gob_start){
2197                     if(s->start_mb_y != mb_y || mb_x!=0){
2198                         write_slice_end(s);
2199
2200                         if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
2201                             ff_mpeg4_init_partitions(s);
2202                         }
2203                     }
2204
2205                     assert((put_bits_count(&s->pb)&7) == 0);
2206                     current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
2207
2208                     if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
2209                         int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
2210                         int d= 100 / s->avctx->error_rate;
2211                         if(r % d == 0){
2212                             current_packet_size=0;
2213                             s->pb.buf_ptr= s->ptr_lastgob;
2214                             assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
2215                         }
2216                     }
2217
2218                     if (s->avctx->rtp_callback){
2219                         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
2220                         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
2221                     }
2222
2223                     switch(s->codec_id){
2224                     case CODEC_ID_MPEG4:
2225                         if (CONFIG_MPEG4_ENCODER) {
2226                             ff_mpeg4_encode_video_packet_header(s);
2227                             ff_mpeg4_clean_buffers(s);
2228                         }
2229                     break;
2230                     case CODEC_ID_MPEG1VIDEO:
2231                     case CODEC_ID_MPEG2VIDEO:
2232                         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
2233                             ff_mpeg1_encode_slice_header(s);
2234                             ff_mpeg1_clean_buffers(s);
2235                         }
2236                     break;
2237                     case CODEC_ID_H263:
2238                     case CODEC_ID_H263P:
2239                         if (CONFIG_H263_ENCODER)
2240                             h263_encode_gob_header(s, mb_y);
2241                     break;
2242                     }
2243
2244                     if(s->flags&CODEC_FLAG_PASS1){
2245                         int bits= put_bits_count(&s->pb);
2246                         s->misc_bits+= bits - s->last_bits;
2247                         s->last_bits= bits;
2248                     }
2249
2250                     s->ptr_lastgob += current_packet_size;
2251                     s->first_slice_line=1;
2252                     s->resync_mb_x=mb_x;
2253                     s->resync_mb_y=mb_y;
2254                 }
2255             }
2256
2257             if(  (s->resync_mb_x   == s->mb_x)
2258                && s->resync_mb_y+1 == s->mb_y){
2259                 s->first_slice_line=0;
2260             }
2261
2262             s->mb_skipped=0;
2263             s->dquant=0; //only for QP_RD
2264
2265             if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
2266                 int next_block=0;
2267                 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
2268
2269                 copy_context_before_encode(&backup_s, s, -1);
2270                 backup_s.pb= s->pb;
2271                 best_s.data_partitioning= s->data_partitioning;
2272                 best_s.partitioned_frame= s->partitioned_frame;
2273                 if(s->data_partitioning){
2274                     backup_s.pb2= s->pb2;
2275                     backup_s.tex_pb= s->tex_pb;
2276                 }
2277
2278                 if(mb_type&CANDIDATE_MB_TYPE_INTER){
2279                     s->mv_dir = MV_DIR_FORWARD;
2280                     s->mv_type = MV_TYPE_16X16;
2281                     s->mb_intra= 0;
2282                     s->mv[0][0][0] = s->p_mv_table[xy][0];
2283                     s->mv[0][0][1] = s->p_mv_table[xy][1];
2284                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
2285                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2286                 }
2287                 if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
2288                     s->mv_dir = MV_DIR_FORWARD;
2289                     s->mv_type = MV_TYPE_FIELD;
2290                     s->mb_intra= 0;
2291                     for(i=0; i<2; i++){
2292                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2293                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2294                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2295                     }
2296                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
2297                                  &dmin, &next_block, 0, 0);
2298                 }
2299                 if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
2300                     s->mv_dir = MV_DIR_FORWARD;
2301                     s->mv_type = MV_TYPE_16X16;
2302                     s->mb_intra= 0;
2303                     s->mv[0][0][0] = 0;
2304                     s->mv[0][0][1] = 0;
2305                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
2306                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2307                 }
2308                 if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
2309                     s->mv_dir = MV_DIR_FORWARD;
2310                     s->mv_type = MV_TYPE_8X8;
2311                     s->mb_intra= 0;
2312                     for(i=0; i<4; i++){
2313                         s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
2314                         s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
2315                     }
2316                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
2317                                  &dmin, &next_block, 0, 0);
2318                 }
2319                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
2320                     s->mv_dir = MV_DIR_FORWARD;
2321                     s->mv_type = MV_TYPE_16X16;
2322                     s->mb_intra= 0;
2323                     s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2324                     s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2325                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
2326                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2327                 }
2328                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
2329                     s->mv_dir = MV_DIR_BACKWARD;
2330                     s->mv_type = MV_TYPE_16X16;
2331                     s->mb_intra= 0;
2332                     s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2333                     s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2334                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
2335                                  &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
2336                 }
2337                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
2338                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2339                     s->mv_type = MV_TYPE_16X16;
2340                     s->mb_intra= 0;
2341                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2342                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2343                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2344                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2345                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
2346                                  &dmin, &next_block, 0, 0);
2347                 }
2348                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
2349                     s->mv_dir = MV_DIR_FORWARD;
2350                     s->mv_type = MV_TYPE_FIELD;
2351                     s->mb_intra= 0;
2352                     for(i=0; i<2; i++){
2353                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2354                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2355                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2356                     }
2357                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
2358                                  &dmin, &next_block, 0, 0);
2359                 }
2360                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
2361                     s->mv_dir = MV_DIR_BACKWARD;
2362                     s->mv_type = MV_TYPE_FIELD;
2363                     s->mb_intra= 0;
2364                     for(i=0; i<2; i++){
2365                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2366                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2367                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2368                     }
2369                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
2370                                  &dmin, &next_block, 0, 0);
2371                 }
2372                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
2373                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2374                     s->mv_type = MV_TYPE_FIELD;
2375                     s->mb_intra= 0;
2376                     for(dir=0; dir<2; dir++){
2377                         for(i=0; i<2; i++){
2378                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2379                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2380                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2381                         }
2382                     }
2383                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
2384                                  &dmin, &next_block, 0, 0);
2385                 }
2386                 if(mb_type&CANDIDATE_MB_TYPE_INTRA){
2387                     s->mv_dir = 0;
2388                     s->mv_type = MV_TYPE_16X16;
2389                     s->mb_intra= 1;
2390                     s->mv[0][0][0] = 0;
2391                     s->mv[0][0][1] = 0;
2392                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
2393                                  &dmin, &next_block, 0, 0);
2394                     if(s->h263_pred || s->h263_aic){
2395                         if(best_s.mb_intra)
2396                             s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
2397                         else
2398                             ff_clean_intra_table_entries(s); //old mode?
2399                     }
2400                 }
2401
2402                 if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
2403                     if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
2404                         const int last_qp= backup_s.qscale;
2405                         int qpi, qp, dc[6];
2406                         DCTELEM ac[6][16];
2407                         const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
2408                         static const int dquant_tab[4]={-1,1,-2,2};
2409
2410                         assert(backup_s.dquant == 0);
2411
2412                         //FIXME intra
2413                         s->mv_dir= best_s.mv_dir;
2414                         s->mv_type = MV_TYPE_16X16;
2415                         s->mb_intra= best_s.mb_intra;
2416                         s->mv[0][0][0] = best_s.mv[0][0][0];
2417                         s->mv[0][0][1] = best_s.mv[0][0][1];
2418                         s->mv[1][0][0] = best_s.mv[1][0][0];
2419                         s->mv[1][0][1] = best_s.mv[1][0][1];
2420
2421                         qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
2422                         for(; qpi<4; qpi++){
2423                             int dquant= dquant_tab[qpi];
2424                             qp= last_qp + dquant;
2425                             if(qp < s->avctx->qmin || qp > s->avctx->qmax)
2426                                 continue;
2427                             backup_s.dquant= dquant;
2428                             if(s->mb_intra && s->dc_val[0]){
2429                                 for(i=0; i<6; i++){
2430                                     dc[i]= s->dc_val[0][ s->block_index[i] ];
2431                                     memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
2432                                 }
2433                             }
2434
2435                             encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2436                                          &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
2437                             if(best_s.qscale != qp){
2438                                 if(s->mb_intra && s->dc_val[0]){
2439                                     for(i=0; i<6; i++){
2440                                         s->dc_val[0][ s->block_index[i] ]= dc[i];
2441                                         memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
2442                                     }
2443                                 }
2444                             }
2445                         }
2446                     }
2447                 }
2448                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
2449                     int mx= s->b_direct_mv_table[xy][0];
2450                     int my= s->b_direct_mv_table[xy][1];
2451
2452                     backup_s.dquant = 0;
2453                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2454                     s->mb_intra= 0;
2455                     ff_mpeg4_set_direct_mv(s, mx, my);
2456                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2457                                  &dmin, &next_block, mx, my);
2458                 }
2459                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
2460                     backup_s.dquant = 0;
2461                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2462                     s->mb_intra= 0;
2463                     ff_mpeg4_set_direct_mv(s, 0, 0);
2464                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2465                                  &dmin, &next_block, 0, 0);
2466                 }
2467                 if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
2468                     int coded=0;
2469                     for(i=0; i<6; i++)
2470                         coded |= s->block_last_index[i];
2471                     if(coded){
2472                         int mx,my;
2473                         memcpy(s->mv, best_s.mv, sizeof(s->mv));
2474                         if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
2475                             mx=my=0; //FIXME find the one we actually used
2476                             ff_mpeg4_set_direct_mv(s, mx, my);
2477                         }else if(best_s.mv_dir&MV_DIR_BACKWARD){
2478                             mx= s->mv[1][0][0];
2479                             my= s->mv[1][0][1];
2480                         }else{
2481                             mx= s->mv[0][0][0];
2482                             my= s->mv[0][0][1];
2483                         }
2484
2485                         s->mv_dir= best_s.mv_dir;
2486                         s->mv_type = best_s.mv_type;
2487                         s->mb_intra= 0;
2488 /*                        s->mv[0][0][0] = best_s.mv[0][0][0];
2489                         s->mv[0][0][1] = best_s.mv[0][0][1];
2490                         s->mv[1][0][0] = best_s.mv[1][0][0];
2491                         s->mv[1][0][1] = best_s.mv[1][0][1];*/
2492                         backup_s.dquant= 0;
2493                         s->skipdct=1;
2494                         encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2495                                         &dmin, &next_block, mx, my);
2496                         s->skipdct=0;
2497                     }
2498                 }
2499
2500                 s->current_picture.f.qscale_table[xy] = best_s.qscale;
2501
2502                 copy_context_after_encode(s, &best_s, -1);
2503
2504                 pb_bits_count= put_bits_count(&s->pb);
2505                 flush_put_bits(&s->pb);
2506                 avpriv_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
2507                 s->pb= backup_s.pb;
2508
2509                 if(s->data_partitioning){
2510                     pb2_bits_count= put_bits_count(&s->pb2);
2511                     flush_put_bits(&s->pb2);
2512                     avpriv_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
2513                     s->pb2= backup_s.pb2;
2514
2515                     tex_pb_bits_count= put_bits_count(&s->tex_pb);
2516                     flush_put_bits(&s->tex_pb);
2517                     avpriv_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
2518                     s->tex_pb= backup_s.tex_pb;
2519                 }
2520                 s->last_bits= put_bits_count(&s->pb);
2521
2522                 if (CONFIG_H263_ENCODER &&
2523                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
2524                     ff_h263_update_motion_val(s);
2525
2526                 if(next_block==0){ //FIXME 16 vs linesize16
2527                     s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad                     , s->linesize  ,16);
2528                     s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize    , s->uvlinesize, 8);
2529                     s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
2530                 }
2531
2532                 if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
2533                     MPV_decode_mb(s, s->block);
2534             } else {
2535                 int motion_x = 0, motion_y = 0;
2536                 s->mv_type=MV_TYPE_16X16;
2537                 // only one MB-Type possible
2538
2539                 switch(mb_type){
2540                 case CANDIDATE_MB_TYPE_INTRA:
2541                     s->mv_dir = 0;
2542                     s->mb_intra= 1;
2543                     motion_x= s->mv[0][0][0] = 0;
2544                     motion_y= s->mv[0][0][1] = 0;
2545                     break;
2546                 case CANDIDATE_MB_TYPE_INTER:
2547                     s->mv_dir = MV_DIR_FORWARD;
2548                     s->mb_intra= 0;
2549                     motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
2550                     motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
2551                     break;
2552                 case CANDIDATE_MB_TYPE_INTER_I:
2553                     s->mv_dir = MV_DIR_FORWARD;
2554                     s->mv_type = MV_TYPE_FIELD;
2555                     s->mb_intra= 0;
2556                     for(i=0; i<2; i++){
2557                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2558                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2559                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2560                     }
2561                     break;
2562                 case CANDIDATE_MB_TYPE_INTER4V:
2563                     s->mv_dir = MV_DIR_FORWARD;
2564                     s->mv_type = MV_TYPE_8X8;
2565                     s->mb_intra= 0;
2566                     for(i=0; i<4; i++){
2567                         s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
2568                         s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
2569                     }
2570                     break;
2571                 case CANDIDATE_MB_TYPE_DIRECT:
2572                     if (CONFIG_MPEG4_ENCODER) {
2573                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2574                         s->mb_intra= 0;
2575                         motion_x=s->b_direct_mv_table[xy][0];
2576                         motion_y=s->b_direct_mv_table[xy][1];
2577                         ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
2578                     }
2579                     break;
2580                 case CANDIDATE_MB_TYPE_DIRECT0:
2581                     if (CONFIG_MPEG4_ENCODER) {
2582                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2583                         s->mb_intra= 0;
2584                         ff_mpeg4_set_direct_mv(s, 0, 0);
2585                     }
2586                     break;
2587                 case CANDIDATE_MB_TYPE_BIDIR:
2588                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2589                     s->mb_intra= 0;
2590                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2591                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2592                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2593                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2594                     break;
2595                 case CANDIDATE_MB_TYPE_BACKWARD:
2596                     s->mv_dir = MV_DIR_BACKWARD;
2597                     s->mb_intra= 0;
2598                     motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2599                     motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2600                     break;
2601                 case CANDIDATE_MB_TYPE_FORWARD:
2602                     s->mv_dir = MV_DIR_FORWARD;
2603                     s->mb_intra= 0;
2604                     motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2605                     motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2606 //                    printf(" %d %d ", motion_x, motion_y);
2607                     break;
2608                 case CANDIDATE_MB_TYPE_FORWARD_I:
2609                     s->mv_dir = MV_DIR_FORWARD;
2610                     s->mv_type = MV_TYPE_FIELD;
2611                     s->mb_intra= 0;
2612                     for(i=0; i<2; i++){
2613                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2614                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2615                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2616                     }
2617                     break;
2618                 case CANDIDATE_MB_TYPE_BACKWARD_I:
2619                     s->mv_dir = MV_DIR_BACKWARD;
2620                     s->mv_type = MV_TYPE_FIELD;
2621                     s->mb_intra= 0;
2622                     for(i=0; i<2; i++){
2623                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2624                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2625                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2626                     }
2627                     break;
2628                 case CANDIDATE_MB_TYPE_BIDIR_I:
2629                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2630                     s->mv_type = MV_TYPE_FIELD;
2631                     s->mb_intra= 0;
2632                     for(dir=0; dir<2; dir++){
2633                         for(i=0; i<2; i++){
2634                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2635                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2636                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2637                         }
2638                     }
2639                     break;
2640                 default:
2641                     av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
2642                 }
2643
2644                 encode_mb(s, motion_x, motion_y);
2645
2646                 // RAL: Update last macroblock type
2647                 s->last_mv_dir = s->mv_dir;
2648
2649                 if (CONFIG_H263_ENCODER &&
2650                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
2651                     ff_h263_update_motion_val(s);
2652
2653                 MPV_decode_mb(s, s->block);
2654             }
2655
2656             /* clean the MV table in IPS frames for direct mode in B frames */
2657             if(s->mb_intra /* && I,P,S_TYPE */){
2658                 s->p_mv_table[xy][0]=0;
2659                 s->p_mv_table[xy][1]=0;
2660             }
2661
2662             if(s->flags&CODEC_FLAG_PSNR){
2663                 int w= 16;
2664                 int h= 16;
2665
2666                 if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
2667                 if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
2668
2669                 s->current_picture.f.error[0] += sse(
2670                     s, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
2671                     s->dest[0], w, h, s->linesize);
2672                 s->current_picture.f.error[1] += sse(
2673                     s, s->new_picture.f.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
2674                     s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
2675                 s->current_picture.f.error[2] += sse(
2676                     s, s->new_picture.f.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
2677                     s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
2678             }
2679             if(s->loop_filter){
2680                 if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
2681                     ff_h263_loop_filter(s);
2682             }
2683 //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
2684         }
2685     }
2686
2687     //not beautiful here but we must write it before flushing so it has to be here
2688     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
2689         msmpeg4_encode_ext_header(s);
2690
2691     write_slice_end(s);
2692
2693     /* Send the last GOB if RTP */
2694     if (s->avctx->rtp_callback) {
2695         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
2696         pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
2697         /* Call the RTP callback to send the last GOB */
2698         emms_c();
2699         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
2700     }
2701
2702     return 0;
2703 }
2704
2705 #define MERGE(field) dst->field += src->field; src->field=0
2706 static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
2707     MERGE(me.scene_change_score);
2708     MERGE(me.mc_mb_var_sum_temp);
2709     MERGE(me.mb_var_sum_temp);
2710 }
2711
2712 static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
2713     int i;
2714
2715     MERGE(dct_count[0]); //note, the other dct vars are not part of the context
2716     MERGE(dct_count[1]);
2717     MERGE(mv_bits);
2718     MERGE(i_tex_bits);
2719     MERGE(p_tex_bits);
2720     MERGE(i_count);
2721     MERGE(f_count);
2722     MERGE(b_count);
2723     MERGE(skip_count);
2724     MERGE(misc_bits);
2725     MERGE(error_count);
2726     MERGE(padding_bug_score);
2727     MERGE(current_picture.f.error[0]);
2728     MERGE(current_picture.f.error[1]);
2729     MERGE(current_picture.f.error[2]);
2730
2731     if(dst->avctx->noise_reduction){
2732         for(i=0; i<64; i++){
2733             MERGE(dct_error_sum[0][i]);
2734             MERGE(dct_error_sum[1][i]);
2735         }
2736     }
2737
2738     assert(put_bits_count(&src->pb) % 8 ==0);
2739     assert(put_bits_count(&dst->pb) % 8 ==0);
2740     avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
2741     flush_put_bits(&dst->pb);
2742 }
2743
2744 static int estimate_qp(MpegEncContext *s, int dry_run){
2745     if (s->next_lambda){
2746         s->current_picture_ptr->f.quality =
2747         s->current_picture.f.quality = s->next_lambda;
2748         if(!dry_run) s->next_lambda= 0;
2749     } else if (!s->fixed_qscale) {
2750         s->current_picture_ptr->f.quality =
2751         s->current_picture.f.quality = ff_rate_estimate_qscale(s, dry_run);
2752         if (s->current_picture.f.quality < 0)
2753             return -1;
2754     }
2755
2756     if(s->adaptive_quant){
2757         switch(s->codec_id){
2758         case CODEC_ID_MPEG4:
2759             if (CONFIG_MPEG4_ENCODER)
2760                 ff_clean_mpeg4_qscales(s);
2761             break;
2762         case CODEC_ID_H263:
2763         case CODEC_ID_H263P:
2764         case CODEC_ID_FLV1:
2765             if (CONFIG_H263_ENCODER)
2766                 ff_clean_h263_qscales(s);
2767             break;
2768         default:
2769             ff_init_qscale_tab(s);
2770         }
2771
2772         s->lambda= s->lambda_table[0];
2773         //FIXME broken
2774     }else
2775         s->lambda = s->current_picture.f.quality;
2776 //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
2777     update_qscale(s);
2778     return 0;
2779 }
2780
2781 /* must be called before writing the header */
2782 static void set_frame_distances(MpegEncContext * s){
2783     assert(s->current_picture_ptr->f.pts != AV_NOPTS_VALUE);
2784     s->time = s->current_picture_ptr->f.pts * s->avctx->time_base.num;
2785
2786     if(s->pict_type==AV_PICTURE_TYPE_B){
2787         s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2788         assert(s->pb_time > 0 && s->pb_time < s->pp_time);
2789     }else{
2790         s->pp_time= s->time - s->last_non_b_time;
2791         s->last_non_b_time= s->time;
2792         assert(s->picture_number==0 || s->pp_time > 0);
2793     }
2794 }
2795
2796 static int encode_picture(MpegEncContext *s, int picture_number)
2797 {
2798     int i;
2799     int bits;
2800     int context_count = s->avctx->thread_count;
2801
2802     s->picture_number = picture_number;
2803
2804     /* Reset the average MB variance */
2805     s->me.mb_var_sum_temp    =
2806     s->me.mc_mb_var_sum_temp = 0;
2807
2808     /* we need to initialize some time vars before we can encode b-frames */
2809     // RAL: Condition added for MPEG1VIDEO
2810     if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
2811         set_frame_distances(s);
2812     if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
2813         ff_set_mpeg4_time(s);
2814
2815     s->me.scene_change_score=0;
2816
2817 //    s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
2818
2819     if(s->pict_type==AV_PICTURE_TYPE_I){
2820         if(s->msmpeg4_version >= 3) s->no_rounding=1;
2821         else                        s->no_rounding=0;
2822     }else if(s->pict_type!=AV_PICTURE_TYPE_B){
2823         if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
2824             s->no_rounding ^= 1;
2825     }
2826
2827     if(s->flags & CODEC_FLAG_PASS2){
2828         if (estimate_qp(s,1) < 0)
2829             return -1;
2830         ff_get_2pass_fcode(s);
2831     }else if(!(s->flags & CODEC_FLAG_QSCALE)){
2832         if(s->pict_type==AV_PICTURE_TYPE_B)
2833             s->lambda= s->last_lambda_for[s->pict_type];
2834         else
2835             s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
2836         update_qscale(s);
2837     }
2838
2839     if(s->codec_id != CODEC_ID_AMV){
2840         if(s->q_chroma_intra_matrix   != s->q_intra_matrix  ) av_freep(&s->q_chroma_intra_matrix);
2841         if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
2842         s->q_chroma_intra_matrix   = s->q_intra_matrix;
2843         s->q_chroma_intra_matrix16 = s->q_intra_matrix16;
2844     }
2845
2846     s->mb_intra=0; //for the rate distortion & bit compare functions
2847     for(i=1; i<context_count; i++){
2848         ff_update_duplicate_context(s->thread_context[i], s);
2849     }
2850
2851     if(ff_init_me(s)<0)
2852         return -1;
2853
2854     /* Estimate motion for every MB */
2855     if(s->pict_type != AV_PICTURE_TYPE_I){
2856         s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
2857         s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
2858         if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
2859             if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
2860                 s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2861             }
2862         }
2863
2864         s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2865     }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
2866         /* I-Frame */
2867         for(i=0; i<s->mb_stride*s->mb_height; i++)
2868             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2869
2870         if(!s->fixed_qscale){
2871             /* finding spatial complexity for I-frame rate control */
2872             s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
2873         }
2874     }
2875     for(i=1; i<context_count; i++){
2876         merge_context_after_me(s, s->thread_context[i]);
2877     }
2878     s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
2879     s->current_picture.   mb_var_sum= s->current_picture_ptr->   mb_var_sum= s->me.   mb_var_sum_temp;
2880     emms_c();
2881
2882     if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
2883         s->pict_type= AV_PICTURE_TYPE_I;
2884         for(i=0; i<s->mb_stride*s->mb_height; i++)
2885             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2886 //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
2887     }
2888
2889     if(!s->umvplus){
2890         if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
2891             s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
2892
2893             if(s->flags & CODEC_FLAG_INTERLACED_ME){
2894                 int a,b;
2895                 a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
2896                 b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
2897                 s->f_code= FFMAX3(s->f_code, a, b);
2898             }
2899
2900             ff_fix_long_p_mvs(s);
2901             ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
2902             if(s->flags & CODEC_FLAG_INTERLACED_ME){
2903                 int j;
2904                 for(i=0; i<2; i++){
2905                     for(j=0; j<2; j++)
2906                         ff_fix_long_mvs(s, s->p_field_select_table[i], j,
2907                                         s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
2908                 }
2909             }
2910         }
2911
2912         if(s->pict_type==AV_PICTURE_TYPE_B){
2913             int a, b;
2914
2915             a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
2916             b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2917             s->f_code = FFMAX(a, b);
2918
2919             a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
2920             b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2921             s->b_code = FFMAX(a, b);
2922
2923             ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
2924             ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
2925             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2926             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2927             if(s->flags & CODEC_FLAG_INTERLACED_ME){
2928                 int dir, j;
2929                 for(dir=0; dir<2; dir++){
2930                     for(i=0; i<2; i++){
2931                         for(j=0; j<2; j++){
2932                             int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
2933                                           : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
2934                             ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
2935                                             s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
2936                         }
2937                     }
2938                 }
2939             }
2940         }
2941     }
2942
2943     if (estimate_qp(s, 0) < 0)
2944         return -1;
2945
2946     if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
2947         s->qscale= 3; //reduce clipping problems
2948
2949     if (s->out_format == FMT_MJPEG) {
2950         /* for mjpeg, we do include qscale in the matrix */
2951         for(i=1;i<64;i++){
2952             int j= s->dsp.idct_permutation[i];
2953
2954             s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
2955         }
2956         s->y_dc_scale_table=
2957         s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
2958         s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
2959         ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
2960                        s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
2961         s->qscale= 8;
2962     }
2963     if(s->codec_id == CODEC_ID_AMV){
2964         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};
2965         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};
2966         for(i=1;i<64;i++){
2967             int j= s->dsp.idct_permutation[ff_zigzag_direct[i]];
2968
2969             s->intra_matrix[j] = sp5x_quant_table[5*2+0][i];
2970             s->chroma_intra_matrix[j] = sp5x_quant_table[5*2+1][i];
2971         }
2972         s->y_dc_scale_table= y;
2973         s->c_dc_scale_table= c;
2974         s->intra_matrix[0] = 13;
2975         s->chroma_intra_matrix[0] = 14;
2976         ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
2977                        s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
2978         ff_convert_matrix(&s->dsp, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
2979                        s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
2980         s->qscale= 8;
2981     }
2982
2983     //FIXME var duplication
2984     s->current_picture_ptr->f.key_frame =
2985     s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
2986     s->current_picture_ptr->f.pict_type =
2987     s->current_picture.f.pict_type = s->pict_type;
2988
2989     if (s->current_picture.f.key_frame)
2990         s->picture_in_gop_number=0;
2991
2992     s->last_bits= put_bits_count(&s->pb);
2993     switch(s->out_format) {
2994     case FMT_MJPEG:
2995         if (CONFIG_MJPEG_ENCODER)
2996             ff_mjpeg_encode_picture_header(s);
2997         break;
2998     case FMT_H261:
2999         if (CONFIG_H261_ENCODER)
3000             ff_h261_encode_picture_header(s, picture_number);
3001         break;
3002     case FMT_H263:
3003         if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
3004             ff_wmv2_encode_picture_header(s, picture_number);
3005         else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
3006             msmpeg4_encode_picture_header(s, picture_number);
3007         else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
3008             mpeg4_encode_picture_header(s, picture_number);
3009         else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
3010             rv10_encode_picture_header(s, picture_number);
3011         else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
3012             rv20_encode_picture_header(s, picture_number);
3013         else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
3014             ff_flv_encode_picture_header(s, picture_number);
3015         else if (CONFIG_H263_ENCODER)
3016             h263_encode_picture_header(s, picture_number);
3017         break;
3018     case FMT_MPEG1:
3019         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
3020             mpeg1_encode_picture_header(s, picture_number);
3021         break;
3022     case FMT_H264:
3023         break;
3024     default:
3025         assert(0);
3026     }
3027     bits= put_bits_count(&s->pb);
3028     s->header_bits= bits - s->last_bits;
3029
3030     for(i=1; i<context_count; i++){
3031         update_duplicate_context_after_me(s->thread_context[i], s);
3032     }
3033     s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
3034     for(i=1; i<context_count; i++){
3035         merge_context_after_encode(s, s->thread_context[i]);
3036     }
3037     emms_c();
3038     return 0;
3039 }
3040
3041 static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
3042     const int intra= s->mb_intra;
3043     int i;
3044
3045     s->dct_count[intra]++;
3046
3047     for(i=0; i<64; i++){
3048         int level= block[i];
3049
3050         if(level){
3051             if(level>0){
3052                 s->dct_error_sum[intra][i] += level;
3053                 level -= s->dct_offset[intra][i];
3054                 if(level<0) level=0;
3055             }else{
3056                 s->dct_error_sum[intra][i] -= level;
3057                 level += s->dct_offset[intra][i];
3058                 if(level>0) level=0;
3059             }
3060             block[i]= level;
3061         }
3062     }
3063 }
3064
3065 static int dct_quantize_trellis_c(MpegEncContext *s,
3066                                   DCTELEM *block, int n,
3067                                   int qscale, int *overflow){
3068     const int *qmat;
3069     const uint8_t *scantable= s->intra_scantable.scantable;
3070     const uint8_t *perm_scantable= s->intra_scantable.permutated;
3071     int max=0;
3072     unsigned int threshold1, threshold2;
3073     int bias=0;
3074     int run_tab[65];
3075     int level_tab[65];
3076     int score_tab[65];
3077     int survivor[65];
3078     int survivor_count;
3079     int last_run=0;
3080     int last_level=0;
3081     int last_score= 0;
3082     int last_i;
3083     int coeff[2][64];
3084     int coeff_count[64];
3085     int qmul, qadd, start_i, last_non_zero, i, dc;
3086     const int esc_length= s->ac_esc_length;
3087     uint8_t * length;
3088     uint8_t * last_length;
3089     const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
3090
3091     s->dsp.fdct (block);
3092
3093     if(s->dct_error_sum)
3094         s->denoise_dct(s, block);
3095     qmul= qscale*16;
3096     qadd= ((qscale-1)|1)*8;
3097
3098     if (s->mb_intra) {
3099         int q;
3100         if (!s->h263_aic) {
3101             if (n < 4)
3102                 q = s->y_dc_scale;
3103             else
3104                 q = s->c_dc_scale;
3105             q = q << 3;
3106         } else{
3107             /* For AIC we skip quant/dequant of INTRADC */
3108             q = 1 << 3;
3109             qadd=0;
3110         }
3111
3112         /* note: block[0] is assumed to be positive */
3113         block[0] = (block[0] + (q >> 1)) / q;
3114         start_i = 1;
3115         last_non_zero = 0;
3116         qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
3117         if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3118             bias= 1<<(QMAT_SHIFT-1);
3119         length     = s->intra_ac_vlc_length;
3120         last_length= s->intra_ac_vlc_last_length;
3121     } else {
3122         start_i = 0;
3123         last_non_zero = -1;
3124         qmat = s->q_inter_matrix[qscale];
3125         length     = s->inter_ac_vlc_length;
3126         last_length= s->inter_ac_vlc_last_length;
3127     }
3128     last_i= start_i;
3129
3130     threshold1= (1<<QMAT_SHIFT) - bias - 1;
3131     threshold2= (threshold1<<1);
3132
3133     for(i=63; i>=start_i; i--) {
3134         const int j = scantable[i];
3135         int level = block[j] * qmat[j];
3136
3137         if(((unsigned)(level+threshold1))>threshold2){
3138             last_non_zero = i;
3139             break;
3140         }
3141     }
3142
3143     for(i=start_i; i<=last_non_zero; i++) {
3144         const int j = scantable[i];
3145         int level = block[j] * qmat[j];
3146
3147 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
3148 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
3149         if(((unsigned)(level+threshold1))>threshold2){
3150             if(level>0){
3151                 level= (bias + level)>>QMAT_SHIFT;
3152                 coeff[0][i]= level;
3153                 coeff[1][i]= level-1;
3154 //                coeff[2][k]= level-2;
3155             }else{
3156                 level= (bias - level)>>QMAT_SHIFT;
3157                 coeff[0][i]= -level;
3158                 coeff[1][i]= -level+1;
3159 //                coeff[2][k]= -level+2;
3160             }
3161             coeff_count[i]= FFMIN(level, 2);
3162             assert(coeff_count[i]);
3163             max |=level;
3164         }else{
3165             coeff[0][i]= (level>>31)|1;
3166             coeff_count[i]= 1;
3167         }
3168     }
3169
3170     *overflow= s->max_qcoeff < max; //overflow might have happened
3171
3172     if(last_non_zero < start_i){
3173         memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3174         return last_non_zero;
3175     }
3176
3177     score_tab[start_i]= 0;
3178     survivor[0]= start_i;
3179     survivor_count= 1;
3180
3181     for(i=start_i; i<=last_non_zero; i++){
3182         int level_index, j, zero_distortion;
3183         int dct_coeff= FFABS(block[ scantable[i] ]);
3184         int best_score=256*256*256*120;
3185
3186         if (   s->dsp.fdct == fdct_ifast
3187 #ifndef FAAN_POSTSCALE
3188             || s->dsp.fdct == ff_faandct
3189 #endif
3190            )
3191             dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
3192         zero_distortion= dct_coeff*dct_coeff;
3193
3194         for(level_index=0; level_index < coeff_count[i]; level_index++){
3195             int distortion;
3196             int level= coeff[level_index][i];
3197             const int alevel= FFABS(level);
3198             int unquant_coeff;
3199
3200             assert(level);
3201
3202             if(s->out_format == FMT_H263){
3203                 unquant_coeff= alevel*qmul + qadd;
3204             }else{ //MPEG1
3205                 j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
3206                 if(s->mb_intra){
3207                         unquant_coeff = (int)(  alevel  * qscale * s->intra_matrix[j]) >> 3;
3208                         unquant_coeff =   (unquant_coeff - 1) | 1;
3209                 }else{
3210                         unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
3211                         unquant_coeff =   (unquant_coeff - 1) | 1;
3212                 }
3213                 unquant_coeff<<= 3;
3214             }
3215
3216             distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
3217             level+=64;
3218             if((level&(~127)) == 0){
3219                 for(j=survivor_count-1; j>=0; j--){
3220                     int run= i - survivor[j];
3221                     int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3222                     score += score_tab[i-run];
3223
3224                     if(score < best_score){
3225                         best_score= score;
3226                         run_tab[i+1]= run;
3227                         level_tab[i+1]= level-64;
3228                     }
3229                 }
3230
3231                 if(s->out_format == FMT_H263){
3232                     for(j=survivor_count-1; j>=0; j--){
3233                         int run= i - survivor[j];
3234                         int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3235                         score += score_tab[i-run];
3236                         if(score < last_score){
3237                             last_score= score;
3238                             last_run= run;
3239                             last_level= level-64;
3240                             last_i= i+1;
3241                         }
3242                     }
3243                 }
3244             }else{
3245                 distortion += esc_length*lambda;
3246                 for(j=survivor_count-1; j>=0; j--){
3247                     int run= i - survivor[j];
3248                     int score= distortion + score_tab[i-run];
3249
3250                     if(score < best_score){
3251                         best_score= score;
3252                         run_tab[i+1]= run;
3253                         level_tab[i+1]= level-64;
3254                     }
3255                 }
3256
3257                 if(s->out_format == FMT_H263){
3258                   for(j=survivor_count-1; j>=0; j--){
3259                         int run= i - survivor[j];
3260                         int score= distortion + score_tab[i-run];
3261                         if(score < last_score){
3262                             last_score= score;
3263                             last_run= run;
3264                             last_level= level-64;
3265                             last_i= i+1;
3266                         }
3267                     }
3268                 }
3269             }
3270         }
3271
3272         score_tab[i+1]= best_score;
3273
3274         //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
3275         if(last_non_zero <= 27){
3276             for(; survivor_count; survivor_count--){
3277                 if(score_tab[ survivor[survivor_count-1] ] <= best_score)
3278                     break;
3279             }
3280         }else{
3281             for(; survivor_count; survivor_count--){
3282                 if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
3283                     break;
3284             }
3285         }
3286
3287         survivor[ survivor_count++ ]= i+1;
3288     }
3289
3290     if(s->out_format != FMT_H263){
3291         last_score= 256*256*256*120;
3292         for(i= survivor[0]; i<=last_non_zero + 1; i++){
3293             int score= score_tab[i];
3294             if(i) score += lambda*2; //FIXME exacter?
3295
3296             if(score < last_score){
3297                 last_score= score;
3298                 last_i= i;
3299                 last_level= level_tab[i];
3300                 last_run= run_tab[i];
3301             }
3302         }
3303     }
3304
3305     s->coded_score[n] = last_score;
3306
3307     dc= FFABS(block[0]);
3308     last_non_zero= last_i - 1;
3309     memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3310
3311     if(last_non_zero < start_i)
3312         return last_non_zero;
3313
3314     if(last_non_zero == 0 && start_i == 0){
3315         int best_level= 0;
3316         int best_score= dc * dc;
3317
3318         for(i=0; i<coeff_count[0]; i++){
3319             int level= coeff[i][0];
3320             int alevel= FFABS(level);
3321             int unquant_coeff, score, distortion;
3322
3323             if(s->out_format == FMT_H263){
3324                     unquant_coeff= (alevel*qmul + qadd)>>3;
3325             }else{ //MPEG1
3326                     unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
3327                     unquant_coeff =   (unquant_coeff - 1) | 1;
3328             }
3329             unquant_coeff = (unquant_coeff + 4) >> 3;
3330             unquant_coeff<<= 3 + 3;
3331
3332             distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
3333             level+=64;
3334             if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
3335             else                    score= distortion + esc_length*lambda;
3336
3337             if(score < best_score){
3338                 best_score= score;
3339                 best_level= level - 64;
3340             }
3341         }
3342         block[0]= best_level;
3343         s->coded_score[n] = best_score - dc*dc;
3344         if(best_level == 0) return -1;
3345         else                return last_non_zero;
3346     }
3347
3348     i= last_i;
3349     assert(last_level);
3350
3351     block[ perm_scantable[last_non_zero] ]= last_level;
3352     i -= last_run + 1;
3353
3354     for(; i>start_i; i -= run_tab[i] + 1){
3355         block[ perm_scantable[i-1] ]= level_tab[i];
3356     }
3357
3358     return last_non_zero;
3359 }
3360
3361 //#define REFINE_STATS 1
3362 static int16_t basis[64][64];
3363
3364 static void build_basis(uint8_t *perm){
3365     int i, j, x, y;
3366     emms_c();
3367     for(i=0; i<8; i++){
3368         for(j=0; j<8; j++){
3369             for(y=0; y<8; y++){
3370                 for(x=0; x<8; x++){
3371                     double s= 0.25*(1<<BASIS_SHIFT);
3372                     int index= 8*i + j;
3373                     int perm_index= perm[index];
3374                     if(i==0) s*= sqrt(0.5);
3375                     if(j==0) s*= sqrt(0.5);
3376                     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)));
3377                 }
3378             }
3379         }
3380     }
3381 }
3382
3383 static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
3384                         DCTELEM *block, int16_t *weight, DCTELEM *orig,
3385                         int n, int qscale){
3386     int16_t rem[64];
3387     LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
3388     const uint8_t *scantable= s->intra_scantable.scantable;
3389     const uint8_t *perm_scantable= s->intra_scantable.permutated;
3390 //    unsigned int threshold1, threshold2;
3391 //    int bias=0;
3392     int run_tab[65];
3393     int prev_run=0;
3394     int prev_level=0;
3395     int qmul, qadd, start_i, last_non_zero, i, dc;
3396     uint8_t * length;
3397     uint8_t * last_length;
3398     int lambda;
3399     int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
3400 #ifdef REFINE_STATS
3401 static int count=0;
3402 static int after_last=0;
3403 static int to_zero=0;
3404 static int from_zero=0;
3405 static int raise=0;
3406 static int lower=0;
3407 static int messed_sign=0;
3408 #endif
3409
3410     if(basis[0][0] == 0)
3411         build_basis(s->dsp.idct_permutation);
3412
3413     qmul= qscale*2;
3414     qadd= (qscale-1)|1;
3415     if (s->mb_intra) {
3416         if (!s->h263_aic) {
3417             if (n < 4)
3418                 q = s->y_dc_scale;
3419             else
3420                 q = s->c_dc_scale;
3421         } else{
3422             /* For AIC we skip quant/dequant of INTRADC */
3423             q = 1;
3424             qadd=0;
3425         }
3426         q <<= RECON_SHIFT-3;
3427         /* note: block[0] is assumed to be positive */
3428         dc= block[0]*q;
3429 //        block[0] = (block[0] + (q >> 1)) / q;
3430         start_i = 1;
3431 //        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3432 //            bias= 1<<(QMAT_SHIFT-1);
3433         length     = s->intra_ac_vlc_length;
3434         last_length= s->intra_ac_vlc_last_length;
3435     } else {
3436         dc= 0;
3437         start_i = 0;
3438         length     = s->inter_ac_vlc_length;
3439         last_length= s->inter_ac_vlc_last_length;
3440     }
3441     last_non_zero = s->block_last_index[n];
3442
3443 #ifdef REFINE_STATS
3444 {START_TIMER
3445 #endif
3446     dc += (1<<(RECON_SHIFT-1));
3447     for(i=0; i<64; i++){
3448         rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME  use orig dirrectly instead of copying to rem[]
3449     }
3450 #ifdef REFINE_STATS
3451 STOP_TIMER("memset rem[]")}
3452 #endif
3453     sum=0;
3454     for(i=0; i<64; i++){
3455         int one= 36;
3456         int qns=4;
3457         int w;
3458
3459         w= FFABS(weight[i]) + qns*one;
3460         w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
3461
3462         weight[i] = w;
3463 //        w=weight[i] = (63*qns + (w/2)) / w;
3464
3465         assert(w>0);
3466         assert(w<(1<<6));
3467         sum += w*w;
3468     }
3469     lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
3470 #ifdef REFINE_STATS
3471 {START_TIMER
3472 #endif
3473     run=0;
3474     rle_index=0;
3475     for(i=start_i; i<=last_non_zero; i++){
3476         int j= perm_scantable[i];
3477         const int level= block[j];
3478         int coeff;
3479
3480         if(level){
3481             if(level<0) coeff= qmul*level - qadd;
3482             else        coeff= qmul*level + qadd;
3483             run_tab[rle_index++]=run;
3484             run=0;
3485
3486             s->dsp.add_8x8basis(rem, basis[j], coeff);
3487         }else{
3488             run++;
3489         }
3490     }
3491 #ifdef REFINE_STATS
3492 if(last_non_zero>0){
3493 STOP_TIMER("init rem[]")
3494 }
3495 }
3496
3497 {START_TIMER
3498 #endif
3499     for(;;){
3500         int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
3501         int best_coeff=0;
3502         int best_change=0;
3503         int run2, best_unquant_change=0, analyze_gradient;
3504 #ifdef REFINE_STATS
3505 {START_TIMER
3506 #endif
3507         analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
3508
3509         if(analyze_gradient){
3510 #ifdef REFINE_STATS
3511 {START_TIMER
3512 #endif
3513             for(i=0; i<64; i++){
3514                 int w= weight[i];
3515
3516                 d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
3517             }
3518 #ifdef REFINE_STATS
3519 STOP_TIMER("rem*w*w")}
3520 {START_TIMER
3521 #endif
3522             s->dsp.fdct(d1);
3523 #ifdef REFINE_STATS
3524 STOP_TIMER("dct")}
3525 #endif
3526         }
3527
3528         if(start_i){
3529             const int level= block[0];
3530             int change, old_coeff;
3531
3532             assert(s->mb_intra);
3533
3534             old_coeff= q*level;
3535
3536             for(change=-1; change<=1; change+=2){
3537                 int new_level= level + change;
3538                 int score, new_coeff;
3539
3540                 new_coeff= q*new_level;
3541                 if(new_coeff >= 2048 || new_coeff < 0)
3542                     continue;
3543
3544                 score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
3545                 if(score<best_score){
3546                     best_score= score;
3547                     best_coeff= 0;
3548                     best_change= change;
3549                     best_unquant_change= new_coeff - old_coeff;
3550                 }
3551             }
3552         }
3553
3554         run=0;
3555         rle_index=0;
3556         run2= run_tab[rle_index++];
3557         prev_level=0;
3558         prev_run=0;
3559
3560         for(i=start_i; i<64; i++){
3561             int j= perm_scantable[i];
3562             const int level= block[j];
3563             int change, old_coeff;
3564
3565             if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
3566                 break;
3567
3568             if(level){
3569                 if(level<0) old_coeff= qmul*level - qadd;
3570                 else        old_coeff= qmul*level + qadd;
3571                 run2= run_tab[rle_index++]; //FIXME ! maybe after last
3572             }else{
3573                 old_coeff=0;
3574                 run2--;
3575                 assert(run2>=0 || i >= last_non_zero );
3576             }
3577
3578             for(change=-1; change<=1; change+=2){
3579                 int new_level= level + change;
3580                 int score, new_coeff, unquant_change;
3581
3582                 score=0;
3583                 if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
3584                    continue;
3585
3586                 if(new_level){
3587                     if(new_level<0) new_coeff= qmul*new_level - qadd;
3588                     else            new_coeff= qmul*new_level + qadd;
3589                     if(new_coeff >= 2048 || new_coeff <= -2048)
3590                         continue;
3591                     //FIXME check for overflow
3592
3593                     if(level){
3594                         if(level < 63 && level > -63){
3595                             if(i < last_non_zero)
3596                                 score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]
3597                                          - length[UNI_AC_ENC_INDEX(run, level+64)];
3598                             else
3599                                 score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
3600                                          - last_length[UNI_AC_ENC_INDEX(run, level+64)];
3601                         }
3602                     }else{
3603                         assert(FFABS(new_level)==1);
3604
3605                         if(analyze_gradient){
3606                             int g= d1[ scantable[i] ];
3607                             if(g && (g^new_level) >= 0)
3608                                 continue;
3609                         }
3610
3611                         if(i < last_non_zero){
3612                             int next_i= i + run2 + 1;
3613                             int next_level= block[ perm_scantable[next_i] ] + 64;
3614
3615                             if(next_level&(~127))
3616                                 next_level= 0;
3617
3618                             if(next_i < last_non_zero)
3619                                 score +=   length[UNI_AC_ENC_INDEX(run, 65)]
3620                                          + length[UNI_AC_ENC_INDEX(run2, next_level)]
3621                                          - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3622                             else
3623                                 score +=  length[UNI_AC_ENC_INDEX(run, 65)]
3624                                         + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3625                                         - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3626                         }else{
3627                             score += last_length[UNI_AC_ENC_INDEX(run, 65)];
3628                             if(prev_level){
3629                                 score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3630                                         - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3631                             }
3632                         }
3633                     }
3634                 }else{
3635                     new_coeff=0;
3636                     assert(FFABS(level)==1);
3637
3638                     if(i < last_non_zero){
3639                         int next_i= i + run2 + 1;
3640                         int next_level= block[ perm_scantable[next_i] ] + 64;
3641
3642                         if(next_level&(~127))
3643                             next_level= 0;
3644
3645                         if(next_i < last_non_zero)
3646                             score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3647                                      - length[UNI_AC_ENC_INDEX(run2, next_level)]
3648                                      - length[UNI_AC_ENC_INDEX(run, 65)];
3649                         else
3650                             score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3651                                      - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3652                                      - length[UNI_AC_ENC_INDEX(run, 65)];
3653                     }else{
3654                         score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
3655                         if(prev_level){
3656                             score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3657                                     - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3658                         }
3659                     }
3660                 }
3661
3662                 score *= lambda;
3663
3664                 unquant_change= new_coeff - old_coeff;
3665                 assert((score < 100*lambda && score > -100*lambda) || lambda==0);
3666
3667                 score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
3668                 if(score<best_score){
3669                     best_score= score;
3670                     best_coeff= i;
3671                     best_change= change;
3672                     best_unquant_change= unquant_change;
3673                 }
3674             }
3675             if(level){
3676                 prev_level= level + 64;
3677                 if(prev_level&(~127))
3678                     prev_level= 0;
3679                 prev_run= run;
3680                 run=0;
3681             }else{
3682                 run++;
3683             }
3684         }
3685 #ifdef REFINE_STATS
3686 STOP_TIMER("iterative step")}
3687 #endif
3688
3689         if(best_change){
3690             int j= perm_scantable[ best_coeff ];
3691
3692             block[j] += best_change;
3693
3694             if(best_coeff > last_non_zero){
3695                 last_non_zero= best_coeff;
3696                 assert(block[j]);
3697 #ifdef REFINE_STATS
3698 after_last++;
3699 #endif
3700             }else{
3701 #ifdef REFINE_STATS
3702 if(block[j]){
3703     if(block[j] - best_change){
3704         if(FFABS(block[j]) > FFABS(block[j] - best_change)){
3705             raise++;
3706         }else{
3707             lower++;
3708         }
3709     }else{
3710         from_zero++;
3711     }
3712 }else{
3713     to_zero++;
3714 }
3715 #endif
3716                 for(; last_non_zero>=start_i; last_non_zero--){
3717                     if(block[perm_scantable[last_non_zero]])
3718                         break;
3719                 }
3720             }
3721 #ifdef REFINE_STATS
3722 count++;
3723 if(256*256*256*64 % count == 0){
3724     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);
3725 }
3726 #endif
3727             run=0;
3728             rle_index=0;
3729             for(i=start_i; i<=last_non_zero; i++){
3730                 int j= perm_scantable[i];
3731                 const int level= block[j];
3732
3733                  if(level){
3734                      run_tab[rle_index++]=run;
3735                      run=0;
3736                  }else{
3737                      run++;
3738                  }
3739             }
3740
3741             s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
3742         }else{
3743             break;
3744         }
3745     }
3746 #ifdef REFINE_STATS
3747 if(last_non_zero>0){
3748 STOP_TIMER("iterative search")
3749 }
3750 }
3751 #endif
3752
3753     return last_non_zero;
3754 }
3755
3756 int dct_quantize_c(MpegEncContext *s,
3757                         DCTELEM *block, int n,
3758                         int qscale, int *overflow)
3759 {
3760     int i, j, level, last_non_zero, q, start_i;
3761     const int *qmat;
3762     const uint8_t *scantable= s->intra_scantable.scantable;
3763     int bias;
3764     int max=0;
3765     unsigned int threshold1, threshold2;
3766
3767     s->dsp.fdct (block);
3768
3769     if(s->dct_error_sum)
3770         s->denoise_dct(s, block);
3771
3772     if (s->mb_intra) {
3773         if (!s->h263_aic) {
3774             if (n < 4)
3775                 q = s->y_dc_scale;
3776             else
3777                 q = s->c_dc_scale;
3778             q = q << 3;
3779         } else
3780             /* For AIC we skip quant/dequant of INTRADC */
3781             q = 1 << 3;
3782
3783         /* note: block[0] is assumed to be positive */
3784         block[0] = (block[0] + (q >> 1)) / q;
3785         start_i = 1;
3786         last_non_zero = 0;
3787         qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
3788         bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
3789     } else {
3790         start_i = 0;
3791         last_non_zero = -1;
3792         qmat = s->q_inter_matrix[qscale];
3793         bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
3794     }
3795     threshold1= (1<<QMAT_SHIFT) - bias - 1;
3796     threshold2= (threshold1<<1);
3797     for(i=63;i>=start_i;i--) {
3798         j = scantable[i];
3799         level = block[j] * qmat[j];
3800
3801         if(((unsigned)(level+threshold1))>threshold2){
3802             last_non_zero = i;
3803             break;
3804         }else{
3805             block[j]=0;
3806         }
3807     }
3808     for(i=start_i; i<=last_non_zero; i++) {
3809         j = scantable[i];
3810         level = block[j] * qmat[j];
3811
3812 //        if(   bias+level >= (1<<QMAT_SHIFT)
3813 //           || bias-level >= (1<<QMAT_SHIFT)){
3814         if(((unsigned)(level+threshold1))>threshold2){
3815             if(level>0){
3816                 level= (bias + level)>>QMAT_SHIFT;
3817                 block[j]= level;
3818             }else{
3819                 level= (bias - level)>>QMAT_SHIFT;
3820                 block[j]= -level;
3821             }
3822             max |=level;
3823         }else{
3824             block[j]=0;
3825         }
3826     }
3827     *overflow= s->max_qcoeff < max; //overflow might have happened
3828
3829     /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
3830     if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
3831         ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
3832
3833     return last_non_zero;
3834 }
3835
3836 #define OFFSET(x) offsetof(MpegEncContext, x)
3837 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
3838 static const AVOption h263_options[] = {
3839     { "obmc",         "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
3840     { "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},
3841     { NULL },
3842 };
3843
3844 static const AVClass h263_class = {
3845     .class_name = "H.263 encoder",
3846     .item_name  = av_default_item_name,
3847     .option     = h263_options,
3848     .version    = LIBAVUTIL_VERSION_INT,
3849 };
3850
3851 AVCodec ff_h263_encoder = {
3852     .name           = "h263",
3853     .type           = AVMEDIA_TYPE_VIDEO,
3854     .id             = CODEC_ID_H263,
3855     .priv_data_size = sizeof(MpegEncContext),
3856     .init           = MPV_encode_init,
3857     .encode         = MPV_encode_picture,
3858     .close          = MPV_encode_end,
3859     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3860     .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
3861     .priv_class     = &h263_class,
3862 };
3863
3864 static const AVOption h263p_options[] = {
3865     { "umv",        "Use unlimited motion vectors.",    OFFSET(umvplus), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
3866     { "aiv",        "Use alternative inter VLC.",       OFFSET(alt_inter_vlc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
3867     { "obmc",       "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
3868     { "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},
3869     { NULL },
3870 };
3871 static const AVClass h263p_class = {
3872     .class_name = "H.263p encoder",
3873     .item_name  = av_default_item_name,
3874     .option     = h263p_options,
3875     .version    = LIBAVUTIL_VERSION_INT,
3876 };
3877
3878 AVCodec ff_h263p_encoder = {
3879     .name           = "h263p",
3880     .type           = AVMEDIA_TYPE_VIDEO,
3881     .id             = CODEC_ID_H263P,
3882     .priv_data_size = sizeof(MpegEncContext),
3883     .init           = MPV_encode_init,
3884     .encode         = MPV_encode_picture,
3885     .close          = MPV_encode_end,
3886     .capabilities = CODEC_CAP_SLICE_THREADS,
3887     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3888     .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
3889     .priv_class     = &h263p_class,
3890 };
3891
3892 AVCodec ff_msmpeg4v2_encoder = {
3893     .name           = "msmpeg4v2",
3894     .type           = AVMEDIA_TYPE_VIDEO,
3895     .id             = CODEC_ID_MSMPEG4V2,
3896     .priv_data_size = sizeof(MpegEncContext),
3897     .init           = MPV_encode_init,
3898     .encode         = MPV_encode_picture,
3899     .close          = MPV_encode_end,
3900     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3901     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
3902 };
3903
3904 AVCodec ff_msmpeg4v3_encoder = {
3905     .name           = "msmpeg4",
3906     .type           = AVMEDIA_TYPE_VIDEO,
3907     .id             = CODEC_ID_MSMPEG4V3,
3908     .priv_data_size = sizeof(MpegEncContext),
3909     .init           = MPV_encode_init,
3910     .encode         = MPV_encode_picture,
3911     .close          = MPV_encode_end,
3912     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3913     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
3914 };
3915
3916 AVCodec ff_wmv1_encoder = {
3917     .name           = "wmv1",
3918     .type           = AVMEDIA_TYPE_VIDEO,
3919     .id             = CODEC_ID_WMV1,
3920     .priv_data_size = sizeof(MpegEncContext),
3921     .init           = MPV_encode_init,
3922     .encode         = MPV_encode_picture,
3923     .close          = MPV_encode_end,
3924     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3925     .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
3926 };