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