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