]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegvideo.c
Merge commit '054013a0fc6f2b52c60cee3e051be8cc7f82cef3'
[ffmpeg] / libavcodec / mpegvideo.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/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/timer.h"
35 #include "avcodec.h"
36 #include "dsputil.h"
37 #include "h264chroma.h"
38 #include "internal.h"
39 #include "mathops.h"
40 #include "mpegutils.h"
41 #include "mpegvideo.h"
42 #include "mjpegenc.h"
43 #include "msmpeg4.h"
44 #include "thread.h"
45 #include <limits.h>
46
47 static const uint8_t ff_default_chroma_qscale_table[32] = {
48 //   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
49      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
50     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
51 };
52
53 const uint8_t ff_mpeg1_dc_scale_table[128] = {
54 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
55     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
56     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
57     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
58     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
59     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
60     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
61     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
62     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
63 };
64
65 static const uint8_t mpeg2_dc_scale_table1[128] = {
66 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
67     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
68     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
69     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
70     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
71     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
72     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
73     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
74     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
75 };
76
77 static const uint8_t mpeg2_dc_scale_table2[128] = {
78 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
79     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
80     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
81     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
82     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
83     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
84     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
85     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
86     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
87 };
88
89 static const uint8_t mpeg2_dc_scale_table3[128] = {
90 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
91     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
92     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
93     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
94     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
95     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
96     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
97     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
98     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
99 };
100
101 const uint8_t *const ff_mpeg2_dc_scale_table[4] = {
102     ff_mpeg1_dc_scale_table,
103     mpeg2_dc_scale_table1,
104     mpeg2_dc_scale_table2,
105     mpeg2_dc_scale_table3,
106 };
107
108 const uint8_t ff_alternate_horizontal_scan[64] = {
109      0,  1,  2,  3,  8,  9, 16, 17,
110     10, 11,  4,  5,  6,  7, 15, 14,
111     13, 12, 19, 18, 24, 25, 32, 33,
112     26, 27, 20, 21, 22, 23, 28, 29,
113     30, 31, 34, 35, 40, 41, 48, 49,
114     42, 43, 36, 37, 38, 39, 44, 45,
115     46, 47, 50, 51, 56, 57, 58, 59,
116     52, 53, 54, 55, 60, 61, 62, 63,
117 };
118
119 const uint8_t ff_alternate_vertical_scan[64] = {
120      0,  8, 16, 24,  1,  9,  2, 10,
121     17, 25, 32, 40, 48, 56, 57, 49,
122     41, 33, 26, 18,  3, 11,  4, 12,
123     19, 27, 34, 42, 50, 58, 35, 43,
124     51, 59, 20, 28,  5, 13,  6, 14,
125     21, 29, 36, 44, 52, 60, 37, 45,
126     53, 61, 22, 30,  7, 15, 23, 31,
127     38, 46, 54, 62, 39, 47, 55, 63,
128 };
129
130 static void dct_unquantize_mpeg1_intra_c(MpegEncContext *s,
131                                    int16_t *block, int n, int qscale)
132 {
133     int i, level, nCoeffs;
134     const uint16_t *quant_matrix;
135
136     nCoeffs= s->block_last_index[n];
137
138     block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
139     /* XXX: only mpeg1 */
140     quant_matrix = s->intra_matrix;
141     for(i=1;i<=nCoeffs;i++) {
142         int j= s->intra_scantable.permutated[i];
143         level = block[j];
144         if (level) {
145             if (level < 0) {
146                 level = -level;
147                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
148                 level = (level - 1) | 1;
149                 level = -level;
150             } else {
151                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
152                 level = (level - 1) | 1;
153             }
154             block[j] = level;
155         }
156     }
157 }
158
159 static void dct_unquantize_mpeg1_inter_c(MpegEncContext *s,
160                                    int16_t *block, int n, int qscale)
161 {
162     int i, level, nCoeffs;
163     const uint16_t *quant_matrix;
164
165     nCoeffs= s->block_last_index[n];
166
167     quant_matrix = s->inter_matrix;
168     for(i=0; i<=nCoeffs; i++) {
169         int j= s->intra_scantable.permutated[i];
170         level = block[j];
171         if (level) {
172             if (level < 0) {
173                 level = -level;
174                 level = (((level << 1) + 1) * qscale *
175                          ((int) (quant_matrix[j]))) >> 4;
176                 level = (level - 1) | 1;
177                 level = -level;
178             } else {
179                 level = (((level << 1) + 1) * qscale *
180                          ((int) (quant_matrix[j]))) >> 4;
181                 level = (level - 1) | 1;
182             }
183             block[j] = level;
184         }
185     }
186 }
187
188 static void dct_unquantize_mpeg2_intra_c(MpegEncContext *s,
189                                    int16_t *block, int n, int qscale)
190 {
191     int i, level, nCoeffs;
192     const uint16_t *quant_matrix;
193
194     if(s->alternate_scan) nCoeffs= 63;
195     else nCoeffs= s->block_last_index[n];
196
197     block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
198     quant_matrix = s->intra_matrix;
199     for(i=1;i<=nCoeffs;i++) {
200         int j= s->intra_scantable.permutated[i];
201         level = block[j];
202         if (level) {
203             if (level < 0) {
204                 level = -level;
205                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
206                 level = -level;
207             } else {
208                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
209             }
210             block[j] = level;
211         }
212     }
213 }
214
215 static void dct_unquantize_mpeg2_intra_bitexact(MpegEncContext *s,
216                                    int16_t *block, int n, int qscale)
217 {
218     int i, level, nCoeffs;
219     const uint16_t *quant_matrix;
220     int sum=-1;
221
222     if(s->alternate_scan) nCoeffs= 63;
223     else nCoeffs= s->block_last_index[n];
224
225     block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
226     sum += block[0];
227     quant_matrix = s->intra_matrix;
228     for(i=1;i<=nCoeffs;i++) {
229         int j= s->intra_scantable.permutated[i];
230         level = block[j];
231         if (level) {
232             if (level < 0) {
233                 level = -level;
234                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
235                 level = -level;
236             } else {
237                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
238             }
239             block[j] = level;
240             sum+=level;
241         }
242     }
243     block[63]^=sum&1;
244 }
245
246 static void dct_unquantize_mpeg2_inter_c(MpegEncContext *s,
247                                    int16_t *block, int n, int qscale)
248 {
249     int i, level, nCoeffs;
250     const uint16_t *quant_matrix;
251     int sum=-1;
252
253     if(s->alternate_scan) nCoeffs= 63;
254     else nCoeffs= s->block_last_index[n];
255
256     quant_matrix = s->inter_matrix;
257     for(i=0; i<=nCoeffs; i++) {
258         int j= s->intra_scantable.permutated[i];
259         level = block[j];
260         if (level) {
261             if (level < 0) {
262                 level = -level;
263                 level = (((level << 1) + 1) * qscale *
264                          ((int) (quant_matrix[j]))) >> 4;
265                 level = -level;
266             } else {
267                 level = (((level << 1) + 1) * qscale *
268                          ((int) (quant_matrix[j]))) >> 4;
269             }
270             block[j] = level;
271             sum+=level;
272         }
273     }
274     block[63]^=sum&1;
275 }
276
277 static void dct_unquantize_h263_intra_c(MpegEncContext *s,
278                                   int16_t *block, int n, int qscale)
279 {
280     int i, level, qmul, qadd;
281     int nCoeffs;
282
283     av_assert2(s->block_last_index[n]>=0 || s->h263_aic);
284
285     qmul = qscale << 1;
286
287     if (!s->h263_aic) {
288         block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
289         qadd = (qscale - 1) | 1;
290     }else{
291         qadd = 0;
292     }
293     if(s->ac_pred)
294         nCoeffs=63;
295     else
296         nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
297
298     for(i=1; i<=nCoeffs; i++) {
299         level = block[i];
300         if (level) {
301             if (level < 0) {
302                 level = level * qmul - qadd;
303             } else {
304                 level = level * qmul + qadd;
305             }
306             block[i] = level;
307         }
308     }
309 }
310
311 static void dct_unquantize_h263_inter_c(MpegEncContext *s,
312                                   int16_t *block, int n, int qscale)
313 {
314     int i, level, qmul, qadd;
315     int nCoeffs;
316
317     av_assert2(s->block_last_index[n]>=0);
318
319     qadd = (qscale - 1) | 1;
320     qmul = qscale << 1;
321
322     nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
323
324     for(i=0; i<=nCoeffs; i++) {
325         level = block[i];
326         if (level) {
327             if (level < 0) {
328                 level = level * qmul - qadd;
329             } else {
330                 level = level * qmul + qadd;
331             }
332             block[i] = level;
333         }
334     }
335 }
336
337 static void mpeg_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
338                               int (*mv)[2][4][2],
339                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
340 {
341     MpegEncContext *s = opaque;
342
343     s->mv_dir     = mv_dir;
344     s->mv_type    = mv_type;
345     s->mb_intra   = mb_intra;
346     s->mb_skipped = mb_skipped;
347     s->mb_x       = mb_x;
348     s->mb_y       = mb_y;
349     memcpy(s->mv, mv, sizeof(*mv));
350
351     ff_init_block_index(s);
352     ff_update_block_index(s);
353
354     s->dsp.clear_blocks(s->block[0]);
355
356     s->dest[0] = s->current_picture.f->data[0] + (s->mb_y *  16                       * s->linesize)   + s->mb_x *  16;
357     s->dest[1] = s->current_picture.f->data[1] + (s->mb_y * (16 >> s->chroma_y_shift) * s->uvlinesize) + s->mb_x * (16 >> s->chroma_x_shift);
358     s->dest[2] = s->current_picture.f->data[2] + (s->mb_y * (16 >> s->chroma_y_shift) * s->uvlinesize) + s->mb_x * (16 >> s->chroma_x_shift);
359
360     if (ref)
361         av_log(s->avctx, AV_LOG_DEBUG, "Interlaced error concealment is not fully implemented\n");
362     ff_MPV_decode_mb(s, s->block);
363 }
364
365 static void gray16(uint8_t *dst, const uint8_t *src, ptrdiff_t linesize, int h)
366 {
367     while(h--)
368         memset(dst + h*linesize, 128, 16);
369 }
370
371 static void gray8(uint8_t *dst, const uint8_t *src, ptrdiff_t linesize, int h)
372 {
373     while(h--)
374         memset(dst + h*linesize, 128, 8);
375 }
376
377 /* init common dct for both encoder and decoder */
378 av_cold int ff_dct_common_init(MpegEncContext *s)
379 {
380     ff_dsputil_init(&s->dsp, s->avctx);
381     ff_h264chroma_init(&s->h264chroma, 8); //for lowres
382     ff_hpeldsp_init(&s->hdsp, s->avctx->flags);
383     ff_videodsp_init(&s->vdsp, s->avctx->bits_per_raw_sample);
384
385     if (s->avctx->debug & FF_DEBUG_NOMC) {
386         int i;
387         for (i=0; i<4; i++) {
388             s->hdsp.avg_pixels_tab[0][i] = gray16;
389             s->hdsp.put_pixels_tab[0][i] = gray16;
390             s->hdsp.put_no_rnd_pixels_tab[0][i] = gray16;
391
392             s->hdsp.avg_pixels_tab[1][i] = gray8;
393             s->hdsp.put_pixels_tab[1][i] = gray8;
394             s->hdsp.put_no_rnd_pixels_tab[1][i] = gray8;
395         }
396     }
397
398     s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_c;
399     s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_c;
400     s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_c;
401     s->dct_unquantize_mpeg1_inter = dct_unquantize_mpeg1_inter_c;
402     s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_c;
403     if (s->flags & CODEC_FLAG_BITEXACT)
404         s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_bitexact;
405     s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_c;
406
407     if (ARCH_ALPHA)
408         ff_MPV_common_init_axp(s);
409     if (ARCH_ARM)
410         ff_MPV_common_init_arm(s);
411     if (ARCH_PPC)
412         ff_MPV_common_init_ppc(s);
413     if (ARCH_X86)
414         ff_MPV_common_init_x86(s);
415
416     /* load & permutate scantables
417      * note: only wmv uses different ones
418      */
419     if (s->alternate_scan) {
420         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
421         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
422     } else {
423         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
424         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
425     }
426     ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
427     ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
428
429     return 0;
430 }
431
432 static int frame_size_alloc(MpegEncContext *s, int linesize)
433 {
434     int alloc_size = FFALIGN(FFABS(linesize) + 64, 32);
435
436     // edge emu needs blocksize + filter length - 1
437     // (= 17x17 for  halfpel / 21x21 for  h264)
438     // VC1 computes luma and chroma simultaneously and needs 19X19 + 9x9
439     // at uvlinesize. It supports only YUV420 so 24x24 is enough
440     // linesize * interlaced * MBsize
441     FF_ALLOCZ_OR_GOTO(s->avctx, s->edge_emu_buffer, alloc_size * 4 * 24,
442                       fail);
443
444     FF_ALLOCZ_OR_GOTO(s->avctx, s->me.scratchpad, alloc_size * 4 * 16 * 2,
445                       fail)
446     s->me.temp         = s->me.scratchpad;
447     s->rd_scratchpad   = s->me.scratchpad;
448     s->b_scratchpad    = s->me.scratchpad;
449     s->obmc_scratchpad = s->me.scratchpad + 16;
450
451     return 0;
452 fail:
453     av_freep(&s->edge_emu_buffer);
454     return AVERROR(ENOMEM);
455 }
456
457 /**
458  * Allocate a frame buffer
459  */
460 static int alloc_frame_buffer(MpegEncContext *s, Picture *pic)
461 {
462     int edges_needed = av_codec_is_encoder(s->avctx->codec);
463     int r, ret;
464
465     pic->tf.f = pic->f;
466     if (s->codec_id != AV_CODEC_ID_WMV3IMAGE &&
467         s->codec_id != AV_CODEC_ID_VC1IMAGE  &&
468         s->codec_id != AV_CODEC_ID_MSS2) {
469         if (edges_needed) {
470             pic->f->width  = s->avctx->width  + 2 * EDGE_WIDTH;
471             pic->f->height = s->avctx->height + 2 * EDGE_WIDTH;
472         }
473
474         r = ff_thread_get_buffer(s->avctx, &pic->tf,
475                                  pic->reference ? AV_GET_BUFFER_FLAG_REF : 0);
476     } else {
477         pic->f->width  = s->avctx->width;
478         pic->f->height = s->avctx->height;
479         pic->f->format = s->avctx->pix_fmt;
480         r = avcodec_default_get_buffer2(s->avctx, pic->f, 0);
481     }
482
483     if (r < 0 || !pic->f->buf[0]) {
484         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (%d %p)\n",
485                r, pic->f->data[0]);
486         return -1;
487     }
488
489     if (edges_needed) {
490         int i;
491         for (i = 0; pic->f->data[i]; i++) {
492             int offset = (EDGE_WIDTH >> (i ? s->chroma_y_shift : 0)) *
493                          pic->f->linesize[i] +
494                          (EDGE_WIDTH >> (i ? s->chroma_x_shift : 0));
495             pic->f->data[i] += offset;
496         }
497         pic->f->width  = s->avctx->width;
498         pic->f->height = s->avctx->height;
499     }
500
501     if (s->avctx->hwaccel) {
502         assert(!pic->hwaccel_picture_private);
503         if (s->avctx->hwaccel->frame_priv_data_size) {
504             pic->hwaccel_priv_buf = av_buffer_allocz(s->avctx->hwaccel->frame_priv_data_size);
505             if (!pic->hwaccel_priv_buf) {
506                 av_log(s->avctx, AV_LOG_ERROR, "alloc_frame_buffer() failed (hwaccel private data allocation)\n");
507                 return -1;
508             }
509             pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
510         }
511     }
512
513     if (s->linesize && (s->linesize   != pic->f->linesize[0] ||
514                         s->uvlinesize != pic->f->linesize[1])) {
515         av_log(s->avctx, AV_LOG_ERROR,
516                "get_buffer() failed (stride changed)\n");
517         ff_mpeg_unref_picture(s, pic);
518         return -1;
519     }
520
521     if (pic->f->linesize[1] != pic->f->linesize[2]) {
522         av_log(s->avctx, AV_LOG_ERROR,
523                "get_buffer() failed (uv stride mismatch)\n");
524         ff_mpeg_unref_picture(s, pic);
525         return -1;
526     }
527
528     if (!s->edge_emu_buffer &&
529         (ret = frame_size_alloc(s, pic->f->linesize[0])) < 0) {
530         av_log(s->avctx, AV_LOG_ERROR,
531                "get_buffer() failed to allocate context scratch buffers.\n");
532         ff_mpeg_unref_picture(s, pic);
533         return ret;
534     }
535
536     return 0;
537 }
538
539 void ff_free_picture_tables(Picture *pic)
540 {
541     int i;
542
543     pic->alloc_mb_width  =
544     pic->alloc_mb_height = 0;
545
546     av_buffer_unref(&pic->mb_var_buf);
547     av_buffer_unref(&pic->mc_mb_var_buf);
548     av_buffer_unref(&pic->mb_mean_buf);
549     av_buffer_unref(&pic->mbskip_table_buf);
550     av_buffer_unref(&pic->qscale_table_buf);
551     av_buffer_unref(&pic->mb_type_buf);
552
553     for (i = 0; i < 2; i++) {
554         av_buffer_unref(&pic->motion_val_buf[i]);
555         av_buffer_unref(&pic->ref_index_buf[i]);
556     }
557 }
558
559 static int alloc_picture_tables(MpegEncContext *s, Picture *pic)
560 {
561     const int big_mb_num    = s->mb_stride * (s->mb_height + 1) + 1;
562     const int mb_array_size = s->mb_stride * s->mb_height;
563     const int b8_array_size = s->b8_stride * s->mb_height * 2;
564     int i;
565
566
567     pic->mbskip_table_buf = av_buffer_allocz(mb_array_size + 2);
568     pic->qscale_table_buf = av_buffer_allocz(big_mb_num + s->mb_stride);
569     pic->mb_type_buf      = av_buffer_allocz((big_mb_num + s->mb_stride) *
570                                              sizeof(uint32_t));
571     if (!pic->mbskip_table_buf || !pic->qscale_table_buf || !pic->mb_type_buf)
572         return AVERROR(ENOMEM);
573
574     if (s->encoding) {
575         pic->mb_var_buf    = av_buffer_allocz(mb_array_size * sizeof(int16_t));
576         pic->mc_mb_var_buf = av_buffer_allocz(mb_array_size * sizeof(int16_t));
577         pic->mb_mean_buf   = av_buffer_allocz(mb_array_size);
578         if (!pic->mb_var_buf || !pic->mc_mb_var_buf || !pic->mb_mean_buf)
579             return AVERROR(ENOMEM);
580     }
581
582     if (s->out_format == FMT_H263 || s->encoding || s->avctx->debug_mv) {
583         int mv_size        = 2 * (b8_array_size + 4) * sizeof(int16_t);
584         int ref_index_size = 4 * mb_array_size;
585
586         for (i = 0; mv_size && i < 2; i++) {
587             pic->motion_val_buf[i] = av_buffer_allocz(mv_size);
588             pic->ref_index_buf[i]  = av_buffer_allocz(ref_index_size);
589             if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
590                 return AVERROR(ENOMEM);
591         }
592     }
593
594     pic->alloc_mb_width  = s->mb_width;
595     pic->alloc_mb_height = s->mb_height;
596
597     return 0;
598 }
599
600 static int make_tables_writable(Picture *pic)
601 {
602     int ret, i;
603 #define MAKE_WRITABLE(table) \
604 do {\
605     if (pic->table &&\
606        (ret = av_buffer_make_writable(&pic->table)) < 0)\
607     return ret;\
608 } while (0)
609
610     MAKE_WRITABLE(mb_var_buf);
611     MAKE_WRITABLE(mc_mb_var_buf);
612     MAKE_WRITABLE(mb_mean_buf);
613     MAKE_WRITABLE(mbskip_table_buf);
614     MAKE_WRITABLE(qscale_table_buf);
615     MAKE_WRITABLE(mb_type_buf);
616
617     for (i = 0; i < 2; i++) {
618         MAKE_WRITABLE(motion_val_buf[i]);
619         MAKE_WRITABLE(ref_index_buf[i]);
620     }
621
622     return 0;
623 }
624
625 /**
626  * Allocate a Picture.
627  * The pixels are allocated/set by calling get_buffer() if shared = 0
628  */
629 int ff_alloc_picture(MpegEncContext *s, Picture *pic, int shared)
630 {
631     int i, ret;
632
633     if (pic->qscale_table_buf)
634         if (   pic->alloc_mb_width  != s->mb_width
635             || pic->alloc_mb_height != s->mb_height)
636             ff_free_picture_tables(pic);
637
638     if (shared) {
639         av_assert0(pic->f->data[0]);
640         pic->shared = 1;
641     } else {
642         av_assert0(!pic->f->buf[0]);
643
644         if (alloc_frame_buffer(s, pic) < 0)
645             return -1;
646
647         s->linesize   = pic->f->linesize[0];
648         s->uvlinesize = pic->f->linesize[1];
649     }
650
651     if (!pic->qscale_table_buf)
652         ret = alloc_picture_tables(s, pic);
653     else
654         ret = make_tables_writable(pic);
655     if (ret < 0)
656         goto fail;
657
658     if (s->encoding) {
659         pic->mb_var    = (uint16_t*)pic->mb_var_buf->data;
660         pic->mc_mb_var = (uint16_t*)pic->mc_mb_var_buf->data;
661         pic->mb_mean   = pic->mb_mean_buf->data;
662     }
663
664     pic->mbskip_table = pic->mbskip_table_buf->data;
665     pic->qscale_table = pic->qscale_table_buf->data + 2 * s->mb_stride + 1;
666     pic->mb_type      = (uint32_t*)pic->mb_type_buf->data + 2 * s->mb_stride + 1;
667
668     if (pic->motion_val_buf[0]) {
669         for (i = 0; i < 2; i++) {
670             pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
671             pic->ref_index[i]  = pic->ref_index_buf[i]->data;
672         }
673     }
674
675     return 0;
676 fail:
677     av_log(s->avctx, AV_LOG_ERROR, "Error allocating a picture.\n");
678     ff_mpeg_unref_picture(s, pic);
679     ff_free_picture_tables(pic);
680     return AVERROR(ENOMEM);
681 }
682
683 /**
684  * Deallocate a picture.
685  */
686 void ff_mpeg_unref_picture(MpegEncContext *s, Picture *pic)
687 {
688     int off = offsetof(Picture, mb_mean) + sizeof(pic->mb_mean);
689
690     pic->tf.f = pic->f;
691     /* WM Image / Screen codecs allocate internal buffers with different
692      * dimensions / colorspaces; ignore user-defined callbacks for these. */
693     if (s->codec_id != AV_CODEC_ID_WMV3IMAGE &&
694         s->codec_id != AV_CODEC_ID_VC1IMAGE  &&
695         s->codec_id != AV_CODEC_ID_MSS2)
696         ff_thread_release_buffer(s->avctx, &pic->tf);
697     else if (pic->f)
698         av_frame_unref(pic->f);
699
700     av_buffer_unref(&pic->hwaccel_priv_buf);
701
702     if (pic->needs_realloc)
703         ff_free_picture_tables(pic);
704
705     memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
706 }
707
708 static int update_picture_tables(Picture *dst, Picture *src)
709 {
710      int i;
711
712 #define UPDATE_TABLE(table)\
713 do {\
714     if (src->table &&\
715         (!dst->table || dst->table->buffer != src->table->buffer)) {\
716         av_buffer_unref(&dst->table);\
717         dst->table = av_buffer_ref(src->table);\
718         if (!dst->table) {\
719             ff_free_picture_tables(dst);\
720             return AVERROR(ENOMEM);\
721         }\
722     }\
723 } while (0)
724
725     UPDATE_TABLE(mb_var_buf);
726     UPDATE_TABLE(mc_mb_var_buf);
727     UPDATE_TABLE(mb_mean_buf);
728     UPDATE_TABLE(mbskip_table_buf);
729     UPDATE_TABLE(qscale_table_buf);
730     UPDATE_TABLE(mb_type_buf);
731     for (i = 0; i < 2; i++) {
732         UPDATE_TABLE(motion_val_buf[i]);
733         UPDATE_TABLE(ref_index_buf[i]);
734     }
735
736     dst->mb_var        = src->mb_var;
737     dst->mc_mb_var     = src->mc_mb_var;
738     dst->mb_mean       = src->mb_mean;
739     dst->mbskip_table  = src->mbskip_table;
740     dst->qscale_table  = src->qscale_table;
741     dst->mb_type       = src->mb_type;
742     for (i = 0; i < 2; i++) {
743         dst->motion_val[i] = src->motion_val[i];
744         dst->ref_index[i]  = src->ref_index[i];
745     }
746
747     dst->alloc_mb_width  = src->alloc_mb_width;
748     dst->alloc_mb_height = src->alloc_mb_height;
749
750     return 0;
751 }
752
753 int ff_mpeg_ref_picture(MpegEncContext *s, Picture *dst, Picture *src)
754 {
755     int ret;
756
757     av_assert0(!dst->f->buf[0]);
758     av_assert0(src->f->buf[0]);
759
760     src->tf.f = src->f;
761     dst->tf.f = dst->f;
762     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
763     if (ret < 0)
764         goto fail;
765
766     ret = update_picture_tables(dst, src);
767     if (ret < 0)
768         goto fail;
769
770     if (src->hwaccel_picture_private) {
771         dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
772         if (!dst->hwaccel_priv_buf)
773             goto fail;
774         dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
775     }
776
777     dst->field_picture           = src->field_picture;
778     dst->mb_var_sum              = src->mb_var_sum;
779     dst->mc_mb_var_sum           = src->mc_mb_var_sum;
780     dst->b_frame_score           = src->b_frame_score;
781     dst->needs_realloc           = src->needs_realloc;
782     dst->reference               = src->reference;
783     dst->shared                  = src->shared;
784
785     return 0;
786 fail:
787     ff_mpeg_unref_picture(s, dst);
788     return ret;
789 }
790
791 static void exchange_uv(MpegEncContext *s)
792 {
793     int16_t (*tmp)[64];
794
795     tmp           = s->pblocks[4];
796     s->pblocks[4] = s->pblocks[5];
797     s->pblocks[5] = tmp;
798 }
799
800 static int init_duplicate_context(MpegEncContext *s)
801 {
802     int y_size = s->b8_stride * (2 * s->mb_height + 1);
803     int c_size = s->mb_stride * (s->mb_height + 1);
804     int yc_size = y_size + 2 * c_size;
805     int i;
806
807     if (s->mb_height & 1)
808         yc_size += 2*s->b8_stride + 2*s->mb_stride;
809
810     s->edge_emu_buffer =
811     s->me.scratchpad   =
812     s->me.temp         =
813     s->rd_scratchpad   =
814     s->b_scratchpad    =
815     s->obmc_scratchpad = NULL;
816
817     if (s->encoding) {
818         FF_ALLOCZ_OR_GOTO(s->avctx, s->me.map,
819                           ME_MAP_SIZE * sizeof(uint32_t), fail)
820         FF_ALLOCZ_OR_GOTO(s->avctx, s->me.score_map,
821                           ME_MAP_SIZE * sizeof(uint32_t), fail)
822         if (s->avctx->noise_reduction) {
823             FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_error_sum,
824                               2 * 64 * sizeof(int), fail)
825         }
826     }
827     FF_ALLOCZ_OR_GOTO(s->avctx, s->blocks, 64 * 12 * 2 * sizeof(int16_t), fail)
828     s->block = s->blocks[0];
829
830     for (i = 0; i < 12; i++) {
831         s->pblocks[i] = &s->block[i];
832     }
833     if (s->avctx->codec_tag == AV_RL32("VCR2"))
834         exchange_uv(s);
835
836     if (s->out_format == FMT_H263) {
837         /* ac values */
838         FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_val_base,
839                           yc_size * sizeof(int16_t) * 16, fail);
840         s->ac_val[0] = s->ac_val_base + s->b8_stride + 1;
841         s->ac_val[1] = s->ac_val_base + y_size + s->mb_stride + 1;
842         s->ac_val[2] = s->ac_val[1] + c_size;
843     }
844
845     return 0;
846 fail:
847     return -1; // free() through ff_MPV_common_end()
848 }
849
850 static void free_duplicate_context(MpegEncContext *s)
851 {
852     if (s == NULL)
853         return;
854
855     av_freep(&s->edge_emu_buffer);
856     av_freep(&s->me.scratchpad);
857     s->me.temp =
858     s->rd_scratchpad =
859     s->b_scratchpad =
860     s->obmc_scratchpad = NULL;
861
862     av_freep(&s->dct_error_sum);
863     av_freep(&s->me.map);
864     av_freep(&s->me.score_map);
865     av_freep(&s->blocks);
866     av_freep(&s->ac_val_base);
867     s->block = NULL;
868 }
869
870 static void backup_duplicate_context(MpegEncContext *bak, MpegEncContext *src)
871 {
872 #define COPY(a) bak->a = src->a
873     COPY(edge_emu_buffer);
874     COPY(me.scratchpad);
875     COPY(me.temp);
876     COPY(rd_scratchpad);
877     COPY(b_scratchpad);
878     COPY(obmc_scratchpad);
879     COPY(me.map);
880     COPY(me.score_map);
881     COPY(blocks);
882     COPY(block);
883     COPY(start_mb_y);
884     COPY(end_mb_y);
885     COPY(me.map_generation);
886     COPY(pb);
887     COPY(dct_error_sum);
888     COPY(dct_count[0]);
889     COPY(dct_count[1]);
890     COPY(ac_val_base);
891     COPY(ac_val[0]);
892     COPY(ac_val[1]);
893     COPY(ac_val[2]);
894 #undef COPY
895 }
896
897 int ff_update_duplicate_context(MpegEncContext *dst, MpegEncContext *src)
898 {
899     MpegEncContext bak;
900     int i, ret;
901     // FIXME copy only needed parts
902     // START_TIMER
903     backup_duplicate_context(&bak, dst);
904     memcpy(dst, src, sizeof(MpegEncContext));
905     backup_duplicate_context(dst, &bak);
906     for (i = 0; i < 12; i++) {
907         dst->pblocks[i] = &dst->block[i];
908     }
909     if (dst->avctx->codec_tag == AV_RL32("VCR2"))
910         exchange_uv(dst);
911     if (!dst->edge_emu_buffer &&
912         (ret = frame_size_alloc(dst, dst->linesize)) < 0) {
913         av_log(dst->avctx, AV_LOG_ERROR, "failed to allocate context "
914                "scratch buffers.\n");
915         return ret;
916     }
917     // STOP_TIMER("update_duplicate_context")
918     // about 10k cycles / 0.01 sec for  1000frames on 1ghz with 2 threads
919     return 0;
920 }
921
922 int ff_mpeg_update_thread_context(AVCodecContext *dst,
923                                   const AVCodecContext *src)
924 {
925     int i, ret;
926     MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;
927
928     if (dst == src)
929         return 0;
930
931     av_assert0(s != s1);
932
933     // FIXME can parameters change on I-frames?
934     // in that case dst may need a reinit
935     if (!s->context_initialized) {
936         memcpy(s, s1, sizeof(MpegEncContext));
937
938         s->avctx                 = dst;
939         s->bitstream_buffer      = NULL;
940         s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;
941
942         if (s1->context_initialized){
943 //             s->picture_range_start  += MAX_PICTURE_COUNT;
944 //             s->picture_range_end    += MAX_PICTURE_COUNT;
945             if((ret = ff_MPV_common_init(s)) < 0){
946                 memset(s, 0, sizeof(MpegEncContext));
947                 s->avctx = dst;
948                 return ret;
949             }
950         }
951     }
952
953     if (s->height != s1->height || s->width != s1->width || s->context_reinit) {
954         s->context_reinit = 0;
955         s->height = s1->height;
956         s->width  = s1->width;
957         if ((ret = ff_MPV_common_frame_size_change(s)) < 0)
958             return ret;
959     }
960
961     s->avctx->coded_height  = s1->avctx->coded_height;
962     s->avctx->coded_width   = s1->avctx->coded_width;
963     s->avctx->width         = s1->avctx->width;
964     s->avctx->height        = s1->avctx->height;
965
966     s->coded_picture_number = s1->coded_picture_number;
967     s->picture_number       = s1->picture_number;
968
969     av_assert0(!s->picture || s->picture != s1->picture);
970     if(s->picture)
971     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
972         ff_mpeg_unref_picture(s, &s->picture[i]);
973         if (s1->picture[i].f->buf[0] &&
974             (ret = ff_mpeg_ref_picture(s, &s->picture[i], &s1->picture[i])) < 0)
975             return ret;
976     }
977
978 #define UPDATE_PICTURE(pic)\
979 do {\
980     ff_mpeg_unref_picture(s, &s->pic);\
981     if (s1->pic.f && s1->pic.f->buf[0])\
982         ret = ff_mpeg_ref_picture(s, &s->pic, &s1->pic);\
983     else\
984         ret = update_picture_tables(&s->pic, &s1->pic);\
985     if (ret < 0)\
986         return ret;\
987 } while (0)
988
989     UPDATE_PICTURE(current_picture);
990     UPDATE_PICTURE(last_picture);
991     UPDATE_PICTURE(next_picture);
992
993     s->last_picture_ptr    = REBASE_PICTURE(s1->last_picture_ptr,    s, s1);
994     s->current_picture_ptr = REBASE_PICTURE(s1->current_picture_ptr, s, s1);
995     s->next_picture_ptr    = REBASE_PICTURE(s1->next_picture_ptr,    s, s1);
996
997     // Error/bug resilience
998     s->next_p_frame_damaged = s1->next_p_frame_damaged;
999     s->workaround_bugs      = s1->workaround_bugs;
1000     s->padding_bug_score    = s1->padding_bug_score;
1001
1002     // MPEG4 timing info
1003     memcpy(&s->last_time_base, &s1->last_time_base,
1004            (char *) &s1->pb_field_time + sizeof(s1->pb_field_time) -
1005            (char *) &s1->last_time_base);
1006
1007     // B-frame info
1008     s->max_b_frames = s1->max_b_frames;
1009     s->low_delay    = s1->low_delay;
1010     s->droppable    = s1->droppable;
1011
1012     // DivX handling (doesn't work)
1013     s->divx_packed  = s1->divx_packed;
1014
1015     if (s1->bitstream_buffer) {
1016         if (s1->bitstream_buffer_size +
1017             FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size)
1018             av_fast_malloc(&s->bitstream_buffer,
1019                            &s->allocated_bitstream_buffer_size,
1020                            s1->allocated_bitstream_buffer_size);
1021             s->bitstream_buffer_size = s1->bitstream_buffer_size;
1022         memcpy(s->bitstream_buffer, s1->bitstream_buffer,
1023                s1->bitstream_buffer_size);
1024         memset(s->bitstream_buffer + s->bitstream_buffer_size, 0,
1025                FF_INPUT_BUFFER_PADDING_SIZE);
1026     }
1027
1028     // linesize dependend scratch buffer allocation
1029     if (!s->edge_emu_buffer)
1030         if (s1->linesize) {
1031             if (frame_size_alloc(s, s1->linesize) < 0) {
1032                 av_log(s->avctx, AV_LOG_ERROR, "Failed to allocate context "
1033                        "scratch buffers.\n");
1034                 return AVERROR(ENOMEM);
1035             }
1036         } else {
1037             av_log(s->avctx, AV_LOG_ERROR, "Context scratch buffers could not "
1038                    "be allocated due to unknown size.\n");
1039         }
1040
1041     // MPEG2/interlacing info
1042     memcpy(&s->progressive_sequence, &s1->progressive_sequence,
1043            (char *) &s1->rtp_mode - (char *) &s1->progressive_sequence);
1044
1045     if (!s1->first_field) {
1046         s->last_pict_type = s1->pict_type;
1047         if (s1->current_picture_ptr)
1048             s->last_lambda_for[s1->pict_type] = s1->current_picture_ptr->f->quality;
1049     }
1050
1051     return 0;
1052 }
1053
1054 /**
1055  * Set the given MpegEncContext to common defaults
1056  * (same for encoding and decoding).
1057  * The changed fields will not depend upon the
1058  * prior state of the MpegEncContext.
1059  */
1060 void ff_MPV_common_defaults(MpegEncContext *s)
1061 {
1062     s->y_dc_scale_table      =
1063     s->c_dc_scale_table      = ff_mpeg1_dc_scale_table;
1064     s->chroma_qscale_table   = ff_default_chroma_qscale_table;
1065     s->progressive_frame     = 1;
1066     s->progressive_sequence  = 1;
1067     s->picture_structure     = PICT_FRAME;
1068
1069     s->coded_picture_number  = 0;
1070     s->picture_number        = 0;
1071
1072     s->f_code                = 1;
1073     s->b_code                = 1;
1074
1075     s->slice_context_count   = 1;
1076 }
1077
1078 /**
1079  * Set the given MpegEncContext to defaults for decoding.
1080  * the changed fields will not depend upon
1081  * the prior state of the MpegEncContext.
1082  */
1083 void ff_MPV_decode_defaults(MpegEncContext *s)
1084 {
1085     ff_MPV_common_defaults(s);
1086 }
1087
1088 static int init_er(MpegEncContext *s)
1089 {
1090     ERContext *er = &s->er;
1091     int mb_array_size = s->mb_height * s->mb_stride;
1092     int i;
1093
1094     er->avctx       = s->avctx;
1095     er->dsp         = &s->dsp;
1096
1097     er->mb_index2xy = s->mb_index2xy;
1098     er->mb_num      = s->mb_num;
1099     er->mb_width    = s->mb_width;
1100     er->mb_height   = s->mb_height;
1101     er->mb_stride   = s->mb_stride;
1102     er->b8_stride   = s->b8_stride;
1103
1104     er->er_temp_buffer     = av_malloc(s->mb_height * s->mb_stride);
1105     er->error_status_table = av_mallocz(mb_array_size);
1106     if (!er->er_temp_buffer || !er->error_status_table)
1107         goto fail;
1108
1109     er->mbskip_table  = s->mbskip_table;
1110     er->mbintra_table = s->mbintra_table;
1111
1112     for (i = 0; i < FF_ARRAY_ELEMS(s->dc_val); i++)
1113         er->dc_val[i] = s->dc_val[i];
1114
1115     er->decode_mb = mpeg_er_decode_mb;
1116     er->opaque    = s;
1117
1118     return 0;
1119 fail:
1120     av_freep(&er->er_temp_buffer);
1121     av_freep(&er->error_status_table);
1122     return AVERROR(ENOMEM);
1123 }
1124
1125 /**
1126  * Initialize and allocates MpegEncContext fields dependent on the resolution.
1127  */
1128 static int init_context_frame(MpegEncContext *s)
1129 {
1130     int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y;
1131
1132     s->mb_width   = (s->width + 15) / 16;
1133     s->mb_stride  = s->mb_width + 1;
1134     s->b8_stride  = s->mb_width * 2 + 1;
1135     mb_array_size = s->mb_height * s->mb_stride;
1136     mv_table_size = (s->mb_height + 2) * s->mb_stride + 1;
1137
1138     /* set default edge pos, will be overridden
1139      * in decode_header if needed */
1140     s->h_edge_pos = s->mb_width * 16;
1141     s->v_edge_pos = s->mb_height * 16;
1142
1143     s->mb_num     = s->mb_width * s->mb_height;
1144
1145     s->block_wrap[0] =
1146     s->block_wrap[1] =
1147     s->block_wrap[2] =
1148     s->block_wrap[3] = s->b8_stride;
1149     s->block_wrap[4] =
1150     s->block_wrap[5] = s->mb_stride;
1151
1152     y_size  = s->b8_stride * (2 * s->mb_height + 1);
1153     c_size  = s->mb_stride * (s->mb_height + 1);
1154     yc_size = y_size + 2   * c_size;
1155
1156     if (s->mb_height & 1)
1157         yc_size += 2*s->b8_stride + 2*s->mb_stride;
1158
1159     FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_index2xy, (s->mb_num + 1) * sizeof(int), fail); // error ressilience code looks cleaner with this
1160     for (y = 0; y < s->mb_height; y++)
1161         for (x = 0; x < s->mb_width; x++)
1162             s->mb_index2xy[x + y * s->mb_width] = x + y * s->mb_stride;
1163
1164     s->mb_index2xy[s->mb_height * s->mb_width] = (s->mb_height - 1) * s->mb_stride + s->mb_width; // FIXME really needed?
1165
1166     if (s->encoding) {
1167         /* Allocate MV tables */
1168         FF_ALLOCZ_OR_GOTO(s->avctx, s->p_mv_table_base,                 mv_table_size * 2 * sizeof(int16_t), fail)
1169         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_forw_mv_table_base,            mv_table_size * 2 * sizeof(int16_t), fail)
1170         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_back_mv_table_base,            mv_table_size * 2 * sizeof(int16_t), fail)
1171         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_forw_mv_table_base,      mv_table_size * 2 * sizeof(int16_t), fail)
1172         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_back_mv_table_base,      mv_table_size * 2 * sizeof(int16_t), fail)
1173         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_direct_mv_table_base,          mv_table_size * 2 * sizeof(int16_t), fail)
1174         s->p_mv_table            = s->p_mv_table_base + s->mb_stride + 1;
1175         s->b_forw_mv_table       = s->b_forw_mv_table_base + s->mb_stride + 1;
1176         s->b_back_mv_table       = s->b_back_mv_table_base + s->mb_stride + 1;
1177         s->b_bidir_forw_mv_table = s->b_bidir_forw_mv_table_base + s->mb_stride + 1;
1178         s->b_bidir_back_mv_table = s->b_bidir_back_mv_table_base + s->mb_stride + 1;
1179         s->b_direct_mv_table     = s->b_direct_mv_table_base + s->mb_stride + 1;
1180
1181         /* Allocate MB type table */
1182         FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_type, mb_array_size * sizeof(uint16_t), fail) // needed for encoding
1183
1184         FF_ALLOCZ_OR_GOTO(s->avctx, s->lambda_table, mb_array_size * sizeof(int), fail)
1185
1186         FF_ALLOC_OR_GOTO(s->avctx, s->cplx_tab,
1187                          mb_array_size * sizeof(float), fail);
1188         FF_ALLOC_OR_GOTO(s->avctx, s->bits_tab,
1189                          mb_array_size * sizeof(float), fail);
1190
1191     }
1192
1193     if (s->codec_id == AV_CODEC_ID_MPEG4 ||
1194         (s->flags & CODEC_FLAG_INTERLACED_ME)) {
1195         /* interlaced direct mode decoding tables */
1196         for (i = 0; i < 2; i++) {
1197             int j, k;
1198             for (j = 0; j < 2; j++) {
1199                 for (k = 0; k < 2; k++) {
1200                     FF_ALLOCZ_OR_GOTO(s->avctx,
1201                                       s->b_field_mv_table_base[i][j][k],
1202                                       mv_table_size * 2 * sizeof(int16_t),
1203                                       fail);
1204                     s->b_field_mv_table[i][j][k] = s->b_field_mv_table_base[i][j][k] +
1205                                                    s->mb_stride + 1;
1206                 }
1207                 FF_ALLOCZ_OR_GOTO(s->avctx, s->b_field_select_table [i][j], mb_array_size * 2 * sizeof(uint8_t), fail)
1208                 FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_mv_table_base[i][j], mv_table_size * 2 * sizeof(int16_t), fail)
1209                 s->p_field_mv_table[i][j] = s->p_field_mv_table_base[i][j] + s->mb_stride + 1;
1210             }
1211             FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_select_table[i], mb_array_size * 2 * sizeof(uint8_t), fail)
1212         }
1213     }
1214     if (s->out_format == FMT_H263) {
1215         /* cbp values */
1216         FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size + (s->mb_height&1)*2*s->b8_stride, fail);
1217         s->coded_block = s->coded_block_base + s->b8_stride + 1;
1218
1219         /* cbp, ac_pred, pred_dir */
1220         FF_ALLOCZ_OR_GOTO(s->avctx, s->cbp_table     , mb_array_size * sizeof(uint8_t), fail);
1221         FF_ALLOCZ_OR_GOTO(s->avctx, s->pred_dir_table, mb_array_size * sizeof(uint8_t), fail);
1222     }
1223
1224     if (s->h263_pred || s->h263_plus || !s->encoding) {
1225         /* dc values */
1226         // MN: we need these for  error resilience of intra-frames
1227         FF_ALLOCZ_OR_GOTO(s->avctx, s->dc_val_base, yc_size * sizeof(int16_t), fail);
1228         s->dc_val[0] = s->dc_val_base + s->b8_stride + 1;
1229         s->dc_val[1] = s->dc_val_base + y_size + s->mb_stride + 1;
1230         s->dc_val[2] = s->dc_val[1] + c_size;
1231         for (i = 0; i < yc_size; i++)
1232             s->dc_val_base[i] = 1024;
1233     }
1234
1235     /* which mb is a intra block */
1236     FF_ALLOCZ_OR_GOTO(s->avctx, s->mbintra_table, mb_array_size, fail);
1237     memset(s->mbintra_table, 1, mb_array_size);
1238
1239     /* init macroblock skip table */
1240     FF_ALLOCZ_OR_GOTO(s->avctx, s->mbskip_table, mb_array_size + 2, fail);
1241     // Note the + 1 is for  a quicker mpeg4 slice_end detection
1242
1243     return init_er(s);
1244 fail:
1245     return AVERROR(ENOMEM);
1246 }
1247
1248 /**
1249  * init common structure for both encoder and decoder.
1250  * this assumes that some variables like width/height are already set
1251  */
1252 av_cold int ff_MPV_common_init(MpegEncContext *s)
1253 {
1254     int i;
1255     int nb_slices = (HAVE_THREADS &&
1256                      s->avctx->active_thread_type & FF_THREAD_SLICE) ?
1257                     s->avctx->thread_count : 1;
1258
1259     if (s->encoding && s->avctx->slices)
1260         nb_slices = s->avctx->slices;
1261
1262     if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)
1263         s->mb_height = (s->height + 31) / 32 * 2;
1264     else
1265         s->mb_height = (s->height + 15) / 16;
1266
1267     if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
1268         av_log(s->avctx, AV_LOG_ERROR,
1269                "decoding to AV_PIX_FMT_NONE is not supported.\n");
1270         return -1;
1271     }
1272
1273     if (nb_slices > MAX_THREADS || (nb_slices > s->mb_height && s->mb_height)) {
1274         int max_slices;
1275         if (s->mb_height)
1276             max_slices = FFMIN(MAX_THREADS, s->mb_height);
1277         else
1278             max_slices = MAX_THREADS;
1279         av_log(s->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
1280                " reducing to %d\n", nb_slices, max_slices);
1281         nb_slices = max_slices;
1282     }
1283
1284     if ((s->width || s->height) &&
1285         av_image_check_size(s->width, s->height, 0, s->avctx))
1286         return -1;
1287
1288     ff_dct_common_init(s);
1289
1290     s->flags  = s->avctx->flags;
1291     s->flags2 = s->avctx->flags2;
1292
1293     /* set chroma shifts */
1294     avcodec_get_chroma_sub_sample(s->avctx->pix_fmt,
1295                                   &s->chroma_x_shift,
1296                                   &s->chroma_y_shift);
1297
1298     /* convert fourcc to upper case */
1299     s->codec_tag          = avpriv_toupper4(s->avctx->codec_tag);
1300
1301     s->stream_codec_tag   = avpriv_toupper4(s->avctx->stream_codec_tag);
1302
1303     FF_ALLOCZ_OR_GOTO(s->avctx, s->picture,
1304                       MAX_PICTURE_COUNT * sizeof(Picture), fail);
1305     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1306         s->picture[i].f = av_frame_alloc();
1307         if (!s->picture[i].f)
1308             goto fail;
1309     }
1310     memset(&s->next_picture, 0, sizeof(s->next_picture));
1311     memset(&s->last_picture, 0, sizeof(s->last_picture));
1312     memset(&s->current_picture, 0, sizeof(s->current_picture));
1313     memset(&s->new_picture, 0, sizeof(s->new_picture));
1314     s->next_picture.f = av_frame_alloc();
1315     if (!s->next_picture.f)
1316         goto fail;
1317     s->last_picture.f = av_frame_alloc();
1318     if (!s->last_picture.f)
1319         goto fail;
1320     s->current_picture.f = av_frame_alloc();
1321     if (!s->current_picture.f)
1322         goto fail;
1323     s->new_picture.f = av_frame_alloc();
1324     if (!s->new_picture.f)
1325         goto fail;
1326
1327         if (init_context_frame(s))
1328             goto fail;
1329
1330         s->parse_context.state = -1;
1331
1332         s->context_initialized = 1;
1333         s->thread_context[0]   = s;
1334
1335 //     if (s->width && s->height) {
1336         if (nb_slices > 1) {
1337             for (i = 1; i < nb_slices; i++) {
1338                 s->thread_context[i] = av_malloc(sizeof(MpegEncContext));
1339                 memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
1340             }
1341
1342             for (i = 0; i < nb_slices; i++) {
1343                 if (init_duplicate_context(s->thread_context[i]) < 0)
1344                     goto fail;
1345                     s->thread_context[i]->start_mb_y =
1346                         (s->mb_height * (i) + nb_slices / 2) / nb_slices;
1347                     s->thread_context[i]->end_mb_y   =
1348                         (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
1349             }
1350         } else {
1351             if (init_duplicate_context(s) < 0)
1352                 goto fail;
1353             s->start_mb_y = 0;
1354             s->end_mb_y   = s->mb_height;
1355         }
1356         s->slice_context_count = nb_slices;
1357 //     }
1358
1359     return 0;
1360  fail:
1361     ff_MPV_common_end(s);
1362     return -1;
1363 }
1364
1365 /**
1366  * Frees and resets MpegEncContext fields depending on the resolution.
1367  * Is used during resolution changes to avoid a full reinitialization of the
1368  * codec.
1369  */
1370 static int free_context_frame(MpegEncContext *s)
1371 {
1372     int i, j, k;
1373
1374     av_freep(&s->mb_type);
1375     av_freep(&s->p_mv_table_base);
1376     av_freep(&s->b_forw_mv_table_base);
1377     av_freep(&s->b_back_mv_table_base);
1378     av_freep(&s->b_bidir_forw_mv_table_base);
1379     av_freep(&s->b_bidir_back_mv_table_base);
1380     av_freep(&s->b_direct_mv_table_base);
1381     s->p_mv_table            = NULL;
1382     s->b_forw_mv_table       = NULL;
1383     s->b_back_mv_table       = NULL;
1384     s->b_bidir_forw_mv_table = NULL;
1385     s->b_bidir_back_mv_table = NULL;
1386     s->b_direct_mv_table     = NULL;
1387     for (i = 0; i < 2; i++) {
1388         for (j = 0; j < 2; j++) {
1389             for (k = 0; k < 2; k++) {
1390                 av_freep(&s->b_field_mv_table_base[i][j][k]);
1391                 s->b_field_mv_table[i][j][k] = NULL;
1392             }
1393             av_freep(&s->b_field_select_table[i][j]);
1394             av_freep(&s->p_field_mv_table_base[i][j]);
1395             s->p_field_mv_table[i][j] = NULL;
1396         }
1397         av_freep(&s->p_field_select_table[i]);
1398     }
1399
1400     av_freep(&s->dc_val_base);
1401     av_freep(&s->coded_block_base);
1402     av_freep(&s->mbintra_table);
1403     av_freep(&s->cbp_table);
1404     av_freep(&s->pred_dir_table);
1405
1406     av_freep(&s->mbskip_table);
1407
1408     av_freep(&s->er.error_status_table);
1409     av_freep(&s->er.er_temp_buffer);
1410     av_freep(&s->mb_index2xy);
1411     av_freep(&s->lambda_table);
1412
1413     av_freep(&s->cplx_tab);
1414     av_freep(&s->bits_tab);
1415
1416     s->linesize = s->uvlinesize = 0;
1417
1418     return 0;
1419 }
1420
1421 int ff_MPV_common_frame_size_change(MpegEncContext *s)
1422 {
1423     int i, err = 0;
1424
1425     if (s->slice_context_count > 1) {
1426         for (i = 0; i < s->slice_context_count; i++) {
1427             free_duplicate_context(s->thread_context[i]);
1428         }
1429         for (i = 1; i < s->slice_context_count; i++) {
1430             av_freep(&s->thread_context[i]);
1431         }
1432     } else
1433         free_duplicate_context(s);
1434
1435     if ((err = free_context_frame(s)) < 0)
1436         return err;
1437
1438     if (s->picture)
1439         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1440                 s->picture[i].needs_realloc = 1;
1441         }
1442
1443     s->last_picture_ptr         =
1444     s->next_picture_ptr         =
1445     s->current_picture_ptr      = NULL;
1446
1447     // init
1448     if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)
1449         s->mb_height = (s->height + 31) / 32 * 2;
1450     else
1451         s->mb_height = (s->height + 15) / 16;
1452
1453     if ((s->width || s->height) &&
1454         av_image_check_size(s->width, s->height, 0, s->avctx))
1455         return AVERROR_INVALIDDATA;
1456
1457     if ((err = init_context_frame(s)))
1458         goto fail;
1459
1460     s->thread_context[0]   = s;
1461
1462     if (s->width && s->height) {
1463         int nb_slices = s->slice_context_count;
1464         if (nb_slices > 1) {
1465             for (i = 1; i < nb_slices; i++) {
1466                 s->thread_context[i] = av_malloc(sizeof(MpegEncContext));
1467                 memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
1468             }
1469
1470             for (i = 0; i < nb_slices; i++) {
1471                 if (init_duplicate_context(s->thread_context[i]) < 0)
1472                     goto fail;
1473                     s->thread_context[i]->start_mb_y =
1474                         (s->mb_height * (i) + nb_slices / 2) / nb_slices;
1475                     s->thread_context[i]->end_mb_y   =
1476                         (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
1477             }
1478         } else {
1479             err = init_duplicate_context(s);
1480             if (err < 0)
1481                 goto fail;
1482             s->start_mb_y = 0;
1483             s->end_mb_y   = s->mb_height;
1484         }
1485         s->slice_context_count = nb_slices;
1486     }
1487
1488     return 0;
1489  fail:
1490     ff_MPV_common_end(s);
1491     return err;
1492 }
1493
1494 /* init common structure for both encoder and decoder */
1495 void ff_MPV_common_end(MpegEncContext *s)
1496 {
1497     int i;
1498
1499     if (s->slice_context_count > 1) {
1500         for (i = 0; i < s->slice_context_count; i++) {
1501             free_duplicate_context(s->thread_context[i]);
1502         }
1503         for (i = 1; i < s->slice_context_count; i++) {
1504             av_freep(&s->thread_context[i]);
1505         }
1506         s->slice_context_count = 1;
1507     } else free_duplicate_context(s);
1508
1509     av_freep(&s->parse_context.buffer);
1510     s->parse_context.buffer_size = 0;
1511
1512     av_freep(&s->bitstream_buffer);
1513     s->allocated_bitstream_buffer_size = 0;
1514
1515     if (s->picture) {
1516         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1517             ff_free_picture_tables(&s->picture[i]);
1518             ff_mpeg_unref_picture(s, &s->picture[i]);
1519             av_frame_free(&s->picture[i].f);
1520         }
1521     }
1522     av_freep(&s->picture);
1523     ff_free_picture_tables(&s->last_picture);
1524     ff_mpeg_unref_picture(s, &s->last_picture);
1525     av_frame_free(&s->last_picture.f);
1526     ff_free_picture_tables(&s->current_picture);
1527     ff_mpeg_unref_picture(s, &s->current_picture);
1528     av_frame_free(&s->current_picture.f);
1529     ff_free_picture_tables(&s->next_picture);
1530     ff_mpeg_unref_picture(s, &s->next_picture);
1531     av_frame_free(&s->next_picture.f);
1532     ff_free_picture_tables(&s->new_picture);
1533     ff_mpeg_unref_picture(s, &s->new_picture);
1534     av_frame_free(&s->new_picture.f);
1535
1536     free_context_frame(s);
1537
1538     s->context_initialized      = 0;
1539     s->last_picture_ptr         =
1540     s->next_picture_ptr         =
1541     s->current_picture_ptr      = NULL;
1542     s->linesize = s->uvlinesize = 0;
1543 }
1544
1545 av_cold void ff_init_rl(RLTable *rl,
1546                         uint8_t static_store[2][2 * MAX_RUN + MAX_LEVEL + 3])
1547 {
1548     int8_t  max_level[MAX_RUN + 1], max_run[MAX_LEVEL + 1];
1549     uint8_t index_run[MAX_RUN + 1];
1550     int last, run, level, start, end, i;
1551
1552     /* If table is static, we can quit if rl->max_level[0] is not NULL */
1553     if (static_store && rl->max_level[0])
1554         return;
1555
1556     /* compute max_level[], max_run[] and index_run[] */
1557     for (last = 0; last < 2; last++) {
1558         if (last == 0) {
1559             start = 0;
1560             end = rl->last;
1561         } else {
1562             start = rl->last;
1563             end = rl->n;
1564         }
1565
1566         memset(max_level, 0, MAX_RUN + 1);
1567         memset(max_run, 0, MAX_LEVEL + 1);
1568         memset(index_run, rl->n, MAX_RUN + 1);
1569         for (i = start; i < end; i++) {
1570             run   = rl->table_run[i];
1571             level = rl->table_level[i];
1572             if (index_run[run] == rl->n)
1573                 index_run[run] = i;
1574             if (level > max_level[run])
1575                 max_level[run] = level;
1576             if (run > max_run[level])
1577                 max_run[level] = run;
1578         }
1579         if (static_store)
1580             rl->max_level[last] = static_store[last];
1581         else
1582             rl->max_level[last] = av_malloc(MAX_RUN + 1);
1583         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
1584         if (static_store)
1585             rl->max_run[last]   = static_store[last] + MAX_RUN + 1;
1586         else
1587             rl->max_run[last]   = av_malloc(MAX_LEVEL + 1);
1588         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
1589         if (static_store)
1590             rl->index_run[last] = static_store[last] + MAX_RUN + MAX_LEVEL + 2;
1591         else
1592             rl->index_run[last] = av_malloc(MAX_RUN + 1);
1593         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
1594     }
1595 }
1596
1597 av_cold void ff_init_vlc_rl(RLTable *rl)
1598 {
1599     int i, q;
1600
1601     for (q = 0; q < 32; q++) {
1602         int qmul = q * 2;
1603         int qadd = (q - 1) | 1;
1604
1605         if (q == 0) {
1606             qmul = 1;
1607             qadd = 0;
1608         }
1609         for (i = 0; i < rl->vlc.table_size; i++) {
1610             int code = rl->vlc.table[i][0];
1611             int len  = rl->vlc.table[i][1];
1612             int level, run;
1613
1614             if (len == 0) { // illegal code
1615                 run   = 66;
1616                 level = MAX_LEVEL;
1617             } else if (len < 0) { // more bits needed
1618                 run   = 0;
1619                 level = code;
1620             } else {
1621                 if (code == rl->n) { // esc
1622                     run   = 66;
1623                     level =  0;
1624                 } else {
1625                     run   = rl->table_run[code] + 1;
1626                     level = rl->table_level[code] * qmul + qadd;
1627                     if (code >= rl->last) run += 192;
1628                 }
1629             }
1630             rl->rl_vlc[q][i].len   = len;
1631             rl->rl_vlc[q][i].level = level;
1632             rl->rl_vlc[q][i].run   = run;
1633         }
1634     }
1635 }
1636
1637 static void release_unused_pictures(MpegEncContext *s)
1638 {
1639     int i;
1640
1641     /* release non reference frames */
1642     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1643         if (!s->picture[i].reference)
1644             ff_mpeg_unref_picture(s, &s->picture[i]);
1645     }
1646 }
1647
1648 static inline int pic_is_unused(MpegEncContext *s, Picture *pic)
1649 {
1650     if (pic == s->last_picture_ptr)
1651         return 0;
1652     if (pic->f->buf[0] == NULL)
1653         return 1;
1654     if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
1655         return 1;
1656     return 0;
1657 }
1658
1659 static int find_unused_picture(MpegEncContext *s, int shared)
1660 {
1661     int i;
1662
1663     if (shared) {
1664         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1665             if (s->picture[i].f->buf[0] == NULL && &s->picture[i] != s->last_picture_ptr)
1666                 return i;
1667         }
1668     } else {
1669         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1670             if (pic_is_unused(s, &s->picture[i]))
1671                 return i;
1672         }
1673     }
1674
1675     av_log(s->avctx, AV_LOG_FATAL,
1676            "Internal error, picture buffer overflow\n");
1677     /* We could return -1, but the codec would crash trying to draw into a
1678      * non-existing frame anyway. This is safer than waiting for a random crash.
1679      * Also the return of this is never useful, an encoder must only allocate
1680      * as much as allowed in the specification. This has no relationship to how
1681      * much libavcodec could allocate (and MAX_PICTURE_COUNT is always large
1682      * enough for such valid streams).
1683      * Plus, a decoder has to check stream validity and remove frames if too
1684      * many reference frames are around. Waiting for "OOM" is not correct at
1685      * all. Similarly, missing reference frames have to be replaced by
1686      * interpolated/MC frames, anything else is a bug in the codec ...
1687      */
1688     abort();
1689     return -1;
1690 }
1691
1692 int ff_find_unused_picture(MpegEncContext *s, int shared)
1693 {
1694     int ret = find_unused_picture(s, shared);
1695
1696     if (ret >= 0 && ret < MAX_PICTURE_COUNT) {
1697         if (s->picture[ret].needs_realloc) {
1698             s->picture[ret].needs_realloc = 0;
1699             ff_free_picture_tables(&s->picture[ret]);
1700             ff_mpeg_unref_picture(s, &s->picture[ret]);
1701         }
1702     }
1703     return ret;
1704 }
1705
1706 static void gray_frame(AVFrame *frame)
1707 {
1708     int i, h_chroma_shift, v_chroma_shift;
1709
1710     av_pix_fmt_get_chroma_sub_sample(frame->format, &h_chroma_shift, &v_chroma_shift);
1711
1712     for(i=0; i<frame->height; i++)
1713         memset(frame->data[0] + frame->linesize[0]*i, 0x80, frame->width);
1714     for(i=0; i<FF_CEIL_RSHIFT(frame->height, v_chroma_shift); i++) {
1715         memset(frame->data[1] + frame->linesize[1]*i,
1716                0x80, FF_CEIL_RSHIFT(frame->width, h_chroma_shift));
1717         memset(frame->data[2] + frame->linesize[2]*i,
1718                0x80, FF_CEIL_RSHIFT(frame->width, h_chroma_shift));
1719     }
1720 }
1721
1722 /**
1723  * generic function called after decoding
1724  * the header and before a frame is decoded.
1725  */
1726 int ff_MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
1727 {
1728     int i, ret;
1729     Picture *pic;
1730     s->mb_skipped = 0;
1731
1732     if (!ff_thread_can_start_frame(avctx)) {
1733         av_log(avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1734         return -1;
1735     }
1736
1737     /* mark & release old frames */
1738     if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
1739         s->last_picture_ptr != s->next_picture_ptr &&
1740         s->last_picture_ptr->f->buf[0]) {
1741         ff_mpeg_unref_picture(s, s->last_picture_ptr);
1742     }
1743
1744     /* release forgotten pictures */
1745     /* if (mpeg124/h263) */
1746     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1747         if (&s->picture[i] != s->last_picture_ptr &&
1748             &s->picture[i] != s->next_picture_ptr &&
1749             s->picture[i].reference && !s->picture[i].needs_realloc) {
1750             if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1751                 av_log(avctx, AV_LOG_ERROR,
1752                        "releasing zombie picture\n");
1753             ff_mpeg_unref_picture(s, &s->picture[i]);
1754         }
1755     }
1756
1757     ff_mpeg_unref_picture(s, &s->current_picture);
1758
1759     release_unused_pictures(s);
1760
1761     if (s->current_picture_ptr &&
1762         s->current_picture_ptr->f->buf[0] == NULL) {
1763         // we already have a unused image
1764         // (maybe it was set before reading the header)
1765         pic = s->current_picture_ptr;
1766     } else {
1767         i   = ff_find_unused_picture(s, 0);
1768         if (i < 0) {
1769             av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1770             return i;
1771         }
1772         pic = &s->picture[i];
1773     }
1774
1775     pic->reference = 0;
1776     if (!s->droppable) {
1777         if (s->pict_type != AV_PICTURE_TYPE_B)
1778             pic->reference = 3;
1779     }
1780
1781     pic->f->coded_picture_number = s->coded_picture_number++;
1782
1783     if (ff_alloc_picture(s, pic, 0) < 0)
1784         return -1;
1785
1786     s->current_picture_ptr = pic;
1787     // FIXME use only the vars from current_pic
1788     s->current_picture_ptr->f->top_field_first = s->top_field_first;
1789     if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
1790         s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1791         if (s->picture_structure != PICT_FRAME)
1792             s->current_picture_ptr->f->top_field_first =
1793                 (s->picture_structure == PICT_TOP_FIELD) == s->first_field;
1794     }
1795     s->current_picture_ptr->f->interlaced_frame = !s->progressive_frame &&
1796                                                  !s->progressive_sequence;
1797     s->current_picture_ptr->field_picture      =  s->picture_structure != PICT_FRAME;
1798
1799     s->current_picture_ptr->f->pict_type = s->pict_type;
1800     // if (s->flags && CODEC_FLAG_QSCALE)
1801     //     s->current_picture_ptr->quality = s->new_picture_ptr->quality;
1802     s->current_picture_ptr->f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1803
1804     if ((ret = ff_mpeg_ref_picture(s, &s->current_picture,
1805                                    s->current_picture_ptr)) < 0)
1806         return ret;
1807
1808     if (s->pict_type != AV_PICTURE_TYPE_B) {
1809         s->last_picture_ptr = s->next_picture_ptr;
1810         if (!s->droppable)
1811             s->next_picture_ptr = s->current_picture_ptr;
1812     }
1813     av_dlog(s->avctx, "L%p N%p C%p L%p N%p C%p type:%d drop:%d\n",
1814             s->last_picture_ptr, s->next_picture_ptr,s->current_picture_ptr,
1815             s->last_picture_ptr    ? s->last_picture_ptr->f->data[0]    : NULL,
1816             s->next_picture_ptr    ? s->next_picture_ptr->f->data[0]    : NULL,
1817             s->current_picture_ptr ? s->current_picture_ptr->f->data[0] : NULL,
1818             s->pict_type, s->droppable);
1819
1820     if ((s->last_picture_ptr == NULL ||
1821          s->last_picture_ptr->f->buf[0] == NULL) &&
1822         (s->pict_type != AV_PICTURE_TYPE_I ||
1823          s->picture_structure != PICT_FRAME)) {
1824         int h_chroma_shift, v_chroma_shift;
1825         av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
1826                                          &h_chroma_shift, &v_chroma_shift);
1827         if (s->pict_type == AV_PICTURE_TYPE_B && s->next_picture_ptr && s->next_picture_ptr->f->buf[0])
1828             av_log(avctx, AV_LOG_DEBUG,
1829                    "allocating dummy last picture for B frame\n");
1830         else if (s->pict_type != AV_PICTURE_TYPE_I)
1831             av_log(avctx, AV_LOG_ERROR,
1832                    "warning: first frame is no keyframe\n");
1833         else if (s->picture_structure != PICT_FRAME)
1834             av_log(avctx, AV_LOG_DEBUG,
1835                    "allocate dummy last picture for field based first keyframe\n");
1836
1837         /* Allocate a dummy frame */
1838         i = ff_find_unused_picture(s, 0);
1839         if (i < 0) {
1840             av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1841             return i;
1842         }
1843         s->last_picture_ptr = &s->picture[i];
1844
1845         s->last_picture_ptr->reference   = 3;
1846         s->last_picture_ptr->f->key_frame = 0;
1847         s->last_picture_ptr->f->pict_type = AV_PICTURE_TYPE_P;
1848
1849         if (ff_alloc_picture(s, s->last_picture_ptr, 0) < 0) {
1850             s->last_picture_ptr = NULL;
1851             return -1;
1852         }
1853
1854         if (!avctx->hwaccel && !(avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)) {
1855             for(i=0; i<avctx->height; i++)
1856                 memset(s->last_picture_ptr->f->data[0] + s->last_picture_ptr->f->linesize[0]*i,
1857                        0x80, avctx->width);
1858             for(i=0; i<FF_CEIL_RSHIFT(avctx->height, v_chroma_shift); i++) {
1859                 memset(s->last_picture_ptr->f->data[1] + s->last_picture_ptr->f->linesize[1]*i,
1860                        0x80, FF_CEIL_RSHIFT(avctx->width, h_chroma_shift));
1861                 memset(s->last_picture_ptr->f->data[2] + s->last_picture_ptr->f->linesize[2]*i,
1862                        0x80, FF_CEIL_RSHIFT(avctx->width, h_chroma_shift));
1863             }
1864
1865             if(s->codec_id == AV_CODEC_ID_FLV1 || s->codec_id == AV_CODEC_ID_H263){
1866                 for(i=0; i<avctx->height; i++)
1867                 memset(s->last_picture_ptr->f->data[0] + s->last_picture_ptr->f->linesize[0]*i, 16, avctx->width);
1868             }
1869         }
1870
1871         ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 0);
1872         ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 1);
1873     }
1874     if ((s->next_picture_ptr == NULL ||
1875          s->next_picture_ptr->f->buf[0] == NULL) &&
1876         s->pict_type == AV_PICTURE_TYPE_B) {
1877         /* Allocate a dummy frame */
1878         i = ff_find_unused_picture(s, 0);
1879         if (i < 0) {
1880             av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1881             return i;
1882         }
1883         s->next_picture_ptr = &s->picture[i];
1884
1885         s->next_picture_ptr->reference   = 3;
1886         s->next_picture_ptr->f->key_frame = 0;
1887         s->next_picture_ptr->f->pict_type = AV_PICTURE_TYPE_P;
1888
1889         if (ff_alloc_picture(s, s->next_picture_ptr, 0) < 0) {
1890             s->next_picture_ptr = NULL;
1891             return -1;
1892         }
1893         ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 0);
1894         ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 1);
1895     }
1896
1897 #if 0 // BUFREF-FIXME
1898     memset(s->last_picture.f->data, 0, sizeof(s->last_picture.f->data));
1899     memset(s->next_picture.f->data, 0, sizeof(s->next_picture.f->data));
1900 #endif
1901     if (s->last_picture_ptr) {
1902         ff_mpeg_unref_picture(s, &s->last_picture);
1903         if (s->last_picture_ptr->f->buf[0] &&
1904             (ret = ff_mpeg_ref_picture(s, &s->last_picture,
1905                                        s->last_picture_ptr)) < 0)
1906             return ret;
1907     }
1908     if (s->next_picture_ptr) {
1909         ff_mpeg_unref_picture(s, &s->next_picture);
1910         if (s->next_picture_ptr->f->buf[0] &&
1911             (ret = ff_mpeg_ref_picture(s, &s->next_picture,
1912                                        s->next_picture_ptr)) < 0)
1913             return ret;
1914     }
1915
1916     av_assert0(s->pict_type == AV_PICTURE_TYPE_I || (s->last_picture_ptr &&
1917                                                  s->last_picture_ptr->f->buf[0]));
1918
1919     if (s->picture_structure!= PICT_FRAME) {
1920         int i;
1921         for (i = 0; i < 4; i++) {
1922             if (s->picture_structure == PICT_BOTTOM_FIELD) {
1923                 s->current_picture.f->data[i] +=
1924                     s->current_picture.f->linesize[i];
1925             }
1926             s->current_picture.f->linesize[i] *= 2;
1927             s->last_picture.f->linesize[i]    *= 2;
1928             s->next_picture.f->linesize[i]    *= 2;
1929         }
1930     }
1931
1932     s->err_recognition = avctx->err_recognition;
1933
1934     /* set dequantizer, we can't do it during init as
1935      * it might change for mpeg4 and we can't do it in the header
1936      * decode as init is not called for mpeg4 there yet */
1937     if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1938         s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
1939         s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
1940     } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
1941         s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
1942         s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
1943     } else {
1944         s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
1945         s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
1946     }
1947
1948     if (s->avctx->debug & FF_DEBUG_NOMC) {
1949         gray_frame(s->current_picture_ptr->f);
1950     }
1951
1952     return 0;
1953 }
1954
1955 /* called after a frame has been decoded. */
1956 void ff_MPV_frame_end(MpegEncContext *s)
1957 {
1958     emms_c();
1959
1960     if (s->current_picture.reference)
1961         ff_thread_report_progress(&s->current_picture_ptr->tf, INT_MAX, 0);
1962 }
1963
1964 /**
1965  * Draw a line from (ex, ey) -> (sx, sy).
1966  * @param w width of the image
1967  * @param h height of the image
1968  * @param stride stride/linesize of the image
1969  * @param color color of the arrow
1970  */
1971 static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey,
1972                       int w, int h, int stride, int color)
1973 {
1974     int x, y, fr, f;
1975
1976     sx = av_clip(sx, 0, w - 1);
1977     sy = av_clip(sy, 0, h - 1);
1978     ex = av_clip(ex, 0, w - 1);
1979     ey = av_clip(ey, 0, h - 1);
1980
1981     buf[sy * stride + sx] += color;
1982
1983     if (FFABS(ex - sx) > FFABS(ey - sy)) {
1984         if (sx > ex) {
1985             FFSWAP(int, sx, ex);
1986             FFSWAP(int, sy, ey);
1987         }
1988         buf += sx + sy * stride;
1989         ex  -= sx;
1990         f    = ((ey - sy) << 16) / ex;
1991         for (x = 0; x <= ex; x++) {
1992             y  = (x * f) >> 16;
1993             fr = (x * f) & 0xFFFF;
1994             buf[y * stride + x]       += (color * (0x10000 - fr)) >> 16;
1995             if(fr) buf[(y + 1) * stride + x] += (color *            fr ) >> 16;
1996         }
1997     } else {
1998         if (sy > ey) {
1999             FFSWAP(int, sx, ex);
2000             FFSWAP(int, sy, ey);
2001         }
2002         buf += sx + sy * stride;
2003         ey  -= sy;
2004         if (ey)
2005             f = ((ex - sx) << 16) / ey;
2006         else
2007             f = 0;
2008         for(y= 0; y <= ey; y++){
2009             x  = (y*f) >> 16;
2010             fr = (y*f) & 0xFFFF;
2011             buf[y * stride + x]     += (color * (0x10000 - fr)) >> 16;
2012             if(fr) buf[y * stride + x + 1] += (color *            fr ) >> 16;
2013         }
2014     }
2015 }
2016
2017 /**
2018  * Draw an arrow from (ex, ey) -> (sx, sy).
2019  * @param w width of the image
2020  * @param h height of the image
2021  * @param stride stride/linesize of the image
2022  * @param color color of the arrow
2023  */
2024 static void draw_arrow(uint8_t *buf, int sx, int sy, int ex,
2025                        int ey, int w, int h, int stride, int color)
2026 {
2027     int dx,dy;
2028
2029     sx = av_clip(sx, -100, w + 100);
2030     sy = av_clip(sy, -100, h + 100);
2031     ex = av_clip(ex, -100, w + 100);
2032     ey = av_clip(ey, -100, h + 100);
2033
2034     dx = ex - sx;
2035     dy = ey - sy;
2036
2037     if (dx * dx + dy * dy > 3 * 3) {
2038         int rx =  dx + dy;
2039         int ry = -dx + dy;
2040         int length = ff_sqrt((rx * rx + ry * ry) << 8);
2041
2042         // FIXME subpixel accuracy
2043         rx = ROUNDED_DIV(rx * 3 << 4, length);
2044         ry = ROUNDED_DIV(ry * 3 << 4, length);
2045
2046         draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
2047         draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
2048     }
2049     draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
2050 }
2051
2052 /**
2053  * Print debugging info for the given picture.
2054  */
2055 void ff_print_debug_info2(AVCodecContext *avctx, AVFrame *pict, uint8_t *mbskip_table,
2056                          uint32_t *mbtype_table, int8_t *qscale_table, int16_t (*motion_val[2])[2],
2057                          int *low_delay,
2058                          int mb_width, int mb_height, int mb_stride, int quarter_sample)
2059 {
2060     if (avctx->hwaccel || !mbtype_table
2061         || (avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU))
2062         return;
2063
2064
2065     if (avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {
2066         int x,y;
2067
2068         av_log(avctx, AV_LOG_DEBUG, "New frame, type: %c\n",
2069                av_get_picture_type_char(pict->pict_type));
2070         for (y = 0; y < mb_height; y++) {
2071             for (x = 0; x < mb_width; x++) {
2072                 if (avctx->debug & FF_DEBUG_SKIP) {
2073                     int count = mbskip_table[x + y * mb_stride];
2074                     if (count > 9)
2075                         count = 9;
2076                     av_log(avctx, AV_LOG_DEBUG, "%1d", count);
2077                 }
2078                 if (avctx->debug & FF_DEBUG_QP) {
2079                     av_log(avctx, AV_LOG_DEBUG, "%2d",
2080                            qscale_table[x + y * mb_stride]);
2081                 }
2082                 if (avctx->debug & FF_DEBUG_MB_TYPE) {
2083                     int mb_type = mbtype_table[x + y * mb_stride];
2084                     // Type & MV direction
2085                     if (IS_PCM(mb_type))
2086                         av_log(avctx, AV_LOG_DEBUG, "P");
2087                     else if (IS_INTRA(mb_type) && IS_ACPRED(mb_type))
2088                         av_log(avctx, AV_LOG_DEBUG, "A");
2089                     else if (IS_INTRA4x4(mb_type))
2090                         av_log(avctx, AV_LOG_DEBUG, "i");
2091                     else if (IS_INTRA16x16(mb_type))
2092                         av_log(avctx, AV_LOG_DEBUG, "I");
2093                     else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type))
2094                         av_log(avctx, AV_LOG_DEBUG, "d");
2095                     else if (IS_DIRECT(mb_type))
2096                         av_log(avctx, AV_LOG_DEBUG, "D");
2097                     else if (IS_GMC(mb_type) && IS_SKIP(mb_type))
2098                         av_log(avctx, AV_LOG_DEBUG, "g");
2099                     else if (IS_GMC(mb_type))
2100                         av_log(avctx, AV_LOG_DEBUG, "G");
2101                     else if (IS_SKIP(mb_type))
2102                         av_log(avctx, AV_LOG_DEBUG, "S");
2103                     else if (!USES_LIST(mb_type, 1))
2104                         av_log(avctx, AV_LOG_DEBUG, ">");
2105                     else if (!USES_LIST(mb_type, 0))
2106                         av_log(avctx, AV_LOG_DEBUG, "<");
2107                     else {
2108                         av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
2109                         av_log(avctx, AV_LOG_DEBUG, "X");
2110                     }
2111
2112                     // segmentation
2113                     if (IS_8X8(mb_type))
2114                         av_log(avctx, AV_LOG_DEBUG, "+");
2115                     else if (IS_16X8(mb_type))
2116                         av_log(avctx, AV_LOG_DEBUG, "-");
2117                     else if (IS_8X16(mb_type))
2118                         av_log(avctx, AV_LOG_DEBUG, "|");
2119                     else if (IS_INTRA(mb_type) || IS_16X16(mb_type))
2120                         av_log(avctx, AV_LOG_DEBUG, " ");
2121                     else
2122                         av_log(avctx, AV_LOG_DEBUG, "?");
2123
2124
2125                     if (IS_INTERLACED(mb_type))
2126                         av_log(avctx, AV_LOG_DEBUG, "=");
2127                     else
2128                         av_log(avctx, AV_LOG_DEBUG, " ");
2129                 }
2130             }
2131             av_log(avctx, AV_LOG_DEBUG, "\n");
2132         }
2133     }
2134
2135     if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) ||
2136         (avctx->debug_mv)) {
2137         const int shift = 1 + quarter_sample;
2138         int mb_y;
2139         uint8_t *ptr;
2140         int i;
2141         int h_chroma_shift, v_chroma_shift, block_height;
2142         const int width          = avctx->width;
2143         const int height         = avctx->height;
2144         const int mv_sample_log2 = avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_SVQ3 ? 2 : 1;
2145         const int mv_stride      = (mb_width << mv_sample_log2) +
2146                                    (avctx->codec->id == AV_CODEC_ID_H264 ? 0 : 1);
2147
2148         *low_delay = 0; // needed to see the vectors without trashing the buffers
2149
2150         avcodec_get_chroma_sub_sample(avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
2151
2152         av_frame_make_writable(pict);
2153
2154         pict->opaque = NULL;
2155         ptr          = pict->data[0];
2156         block_height = 16 >> v_chroma_shift;
2157
2158         for (mb_y = 0; mb_y < mb_height; mb_y++) {
2159             int mb_x;
2160             for (mb_x = 0; mb_x < mb_width; mb_x++) {
2161                 const int mb_index = mb_x + mb_y * mb_stride;
2162                 if ((avctx->debug_mv) && motion_val[0]) {
2163                     int type;
2164                     for (type = 0; type < 3; type++) {
2165                         int direction = 0;
2166                         switch (type) {
2167                         case 0:
2168                             if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_P_FOR)) ||
2169                                 (pict->pict_type!= AV_PICTURE_TYPE_P))
2170                                 continue;
2171                             direction = 0;
2172                             break;
2173                         case 1:
2174                             if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_FOR)) ||
2175                                 (pict->pict_type!= AV_PICTURE_TYPE_B))
2176                                 continue;
2177                             direction = 0;
2178                             break;
2179                         case 2:
2180                             if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_BACK)) ||
2181                                 (pict->pict_type!= AV_PICTURE_TYPE_B))
2182                                 continue;
2183                             direction = 1;
2184                             break;
2185                         }
2186                         if (!USES_LIST(mbtype_table[mb_index], direction))
2187                             continue;
2188
2189                         if (IS_8X8(mbtype_table[mb_index])) {
2190                             int i;
2191                             for (i = 0; i < 4; i++) {
2192                                 int sx = mb_x * 16 + 4 + 8 * (i & 1);
2193                                 int sy = mb_y * 16 + 4 + 8 * (i >> 1);
2194                                 int xy = (mb_x * 2 + (i & 1) +
2195                                           (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
2196                                 int mx = (motion_val[direction][xy][0] >> shift) + sx;
2197                                 int my = (motion_val[direction][xy][1] >> shift) + sy;
2198                                 draw_arrow(ptr, sx, sy, mx, my, width,
2199                                            height, pict->linesize[0], 100);
2200                             }
2201                         } else if (IS_16X8(mbtype_table[mb_index])) {
2202                             int i;
2203                             for (i = 0; i < 2; i++) {
2204                                 int sx = mb_x * 16 + 8;
2205                                 int sy = mb_y * 16 + 4 + 8 * i;
2206                                 int xy = (mb_x * 2 + (mb_y * 2 + i) * mv_stride) << (mv_sample_log2 - 1);
2207                                 int mx = (motion_val[direction][xy][0] >> shift);
2208                                 int my = (motion_val[direction][xy][1] >> shift);
2209
2210                                 if (IS_INTERLACED(mbtype_table[mb_index]))
2211                                     my *= 2;
2212
2213                             draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,
2214                                        height, pict->linesize[0], 100);
2215                             }
2216                         } else if (IS_8X16(mbtype_table[mb_index])) {
2217                             int i;
2218                             for (i = 0; i < 2; i++) {
2219                                 int sx = mb_x * 16 + 4 + 8 * i;
2220                                 int sy = mb_y * 16 + 8;
2221                                 int xy = (mb_x * 2 + i + mb_y * 2 * mv_stride) << (mv_sample_log2 - 1);
2222                                 int mx = motion_val[direction][xy][0] >> shift;
2223                                 int my = motion_val[direction][xy][1] >> shift;
2224
2225                                 if (IS_INTERLACED(mbtype_table[mb_index]))
2226                                     my *= 2;
2227
2228                                 draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,
2229                                            height, pict->linesize[0], 100);
2230                             }
2231                         } else {
2232                               int sx= mb_x * 16 + 8;
2233                               int sy= mb_y * 16 + 8;
2234                               int xy= (mb_x + mb_y * mv_stride) << mv_sample_log2;
2235                               int mx= (motion_val[direction][xy][0]>>shift) + sx;
2236                               int my= (motion_val[direction][xy][1]>>shift) + sy;
2237                               draw_arrow(ptr, sx, sy, mx, my, width, height, pict->linesize[0], 100);
2238                         }
2239                     }
2240                 }
2241                 if ((avctx->debug & FF_DEBUG_VIS_QP)) {
2242                     uint64_t c = (qscale_table[mb_index] * 128 / 31) *
2243                                  0x0101010101010101ULL;
2244                     int y;
2245                     for (y = 0; y < block_height; y++) {
2246                         *(uint64_t *)(pict->data[1] + 8 * mb_x +
2247                                       (block_height * mb_y + y) *
2248                                       pict->linesize[1]) = c;
2249                         *(uint64_t *)(pict->data[2] + 8 * mb_x +
2250                                       (block_height * mb_y + y) *
2251                                       pict->linesize[2]) = c;
2252                     }
2253                 }
2254                 if ((avctx->debug & FF_DEBUG_VIS_MB_TYPE) &&
2255                     motion_val[0]) {
2256                     int mb_type = mbtype_table[mb_index];
2257                     uint64_t u,v;
2258                     int y;
2259 #define COLOR(theta, r) \
2260     u = (int)(128 + r * cos(theta * 3.141592 / 180)); \
2261     v = (int)(128 + r * sin(theta * 3.141592 / 180));
2262
2263
2264                     u = v = 128;
2265                     if (IS_PCM(mb_type)) {
2266                         COLOR(120, 48)
2267                     } else if ((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) ||
2268                                IS_INTRA16x16(mb_type)) {
2269                         COLOR(30, 48)
2270                     } else if (IS_INTRA4x4(mb_type)) {
2271                         COLOR(90, 48)
2272                     } else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type)) {
2273                         // COLOR(120, 48)
2274                     } else if (IS_DIRECT(mb_type)) {
2275                         COLOR(150, 48)
2276                     } else if (IS_GMC(mb_type) && IS_SKIP(mb_type)) {
2277                         COLOR(170, 48)
2278                     } else if (IS_GMC(mb_type)) {
2279                         COLOR(190, 48)
2280                     } else if (IS_SKIP(mb_type)) {
2281                         // COLOR(180, 48)
2282                     } else if (!USES_LIST(mb_type, 1)) {
2283                         COLOR(240, 48)
2284                     } else if (!USES_LIST(mb_type, 0)) {
2285                         COLOR(0, 48)
2286                     } else {
2287                         av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
2288                         COLOR(300,48)
2289                     }
2290
2291                     u *= 0x0101010101010101ULL;
2292                     v *= 0x0101010101010101ULL;
2293                     for (y = 0; y < block_height; y++) {
2294                         *(uint64_t *)(pict->data[1] + 8 * mb_x +
2295                                       (block_height * mb_y + y) * pict->linesize[1]) = u;
2296                         *(uint64_t *)(pict->data[2] + 8 * mb_x +
2297                                       (block_height * mb_y + y) * pict->linesize[2]) = v;
2298                     }
2299
2300                     // segmentation
2301                     if (IS_8X8(mb_type) || IS_16X8(mb_type)) {
2302                         *(uint64_t *)(pict->data[0] + 16 * mb_x + 0 +
2303                                       (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;
2304                         *(uint64_t *)(pict->data[0] + 16 * mb_x + 8 +
2305                                       (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;
2306                     }
2307                     if (IS_8X8(mb_type) || IS_8X16(mb_type)) {
2308                         for (y = 0; y < 16; y++)
2309                             pict->data[0][16 * mb_x + 8 + (16 * mb_y + y) *
2310                                           pict->linesize[0]] ^= 0x80;
2311                     }
2312                     if (IS_8X8(mb_type) && mv_sample_log2 >= 2) {
2313                         int dm = 1 << (mv_sample_log2 - 2);
2314                         for (i = 0; i < 4; i++) {
2315                             int sx = mb_x * 16 + 8 * (i & 1);
2316                             int sy = mb_y * 16 + 8 * (i >> 1);
2317                             int xy = (mb_x * 2 + (i & 1) +
2318                                      (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
2319                             // FIXME bidir
2320                             int32_t *mv = (int32_t *) &motion_val[0][xy];
2321                             if (mv[0] != mv[dm] ||
2322                                 mv[dm * mv_stride] != mv[dm * (mv_stride + 1)])
2323                                 for (y = 0; y < 8; y++)
2324                                     pict->data[0][sx + 4 + (sy + y) * pict->linesize[0]] ^= 0x80;
2325                             if (mv[0] != mv[dm * mv_stride] || mv[dm] != mv[dm * (mv_stride + 1)])
2326                                 *(uint64_t *)(pict->data[0] + sx + (sy + 4) *
2327                                               pict->linesize[0]) ^= 0x8080808080808080ULL;
2328                         }
2329                     }
2330
2331                     if (IS_INTERLACED(mb_type) &&
2332                         avctx->codec->id == AV_CODEC_ID_H264) {
2333                         // hmm
2334                     }
2335                 }
2336                 mbskip_table[mb_index] = 0;
2337             }
2338         }
2339     }
2340 }
2341
2342 void ff_print_debug_info(MpegEncContext *s, Picture *p, AVFrame *pict)
2343 {
2344     ff_print_debug_info2(s->avctx, pict, s->mbskip_table, p->mb_type,
2345                          p->qscale_table, p->motion_val, &s->low_delay,
2346                          s->mb_width, s->mb_height, s->mb_stride, s->quarter_sample);
2347 }
2348
2349 int ff_mpv_export_qp_table(MpegEncContext *s, AVFrame *f, Picture *p, int qp_type)
2350 {
2351     AVBufferRef *ref = av_buffer_ref(p->qscale_table_buf);
2352     int offset = 2*s->mb_stride + 1;
2353     if(!ref)
2354         return AVERROR(ENOMEM);
2355     av_assert0(ref->size >= offset + s->mb_stride * ((f->height+15)/16));
2356     ref->size -= offset;
2357     ref->data += offset;
2358     return av_frame_set_qp_table(f, ref, s->mb_stride, qp_type);
2359 }
2360
2361 static inline int hpel_motion_lowres(MpegEncContext *s,
2362                                      uint8_t *dest, uint8_t *src,
2363                                      int field_based, int field_select,
2364                                      int src_x, int src_y,
2365                                      int width, int height, ptrdiff_t stride,
2366                                      int h_edge_pos, int v_edge_pos,
2367                                      int w, int h, h264_chroma_mc_func *pix_op,
2368                                      int motion_x, int motion_y)
2369 {
2370     const int lowres   = s->avctx->lowres;
2371     const int op_index = FFMIN(lowres, 3);
2372     const int s_mask   = (2 << lowres) - 1;
2373     int emu = 0;
2374     int sx, sy;
2375
2376     if (s->quarter_sample) {
2377         motion_x /= 2;
2378         motion_y /= 2;
2379     }
2380
2381     sx = motion_x & s_mask;
2382     sy = motion_y & s_mask;
2383     src_x += motion_x >> lowres + 1;
2384     src_y += motion_y >> lowres + 1;
2385
2386     src   += src_y * stride + src_x;
2387
2388     if ((unsigned)src_x > FFMAX( h_edge_pos - (!!sx) - w,                 0) ||
2389         (unsigned)src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
2390         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src,
2391                                  s->linesize, s->linesize,
2392                                  w + 1, (h + 1) << field_based,
2393                                  src_x, src_y   << field_based,
2394                                  h_edge_pos, v_edge_pos);
2395         src = s->edge_emu_buffer;
2396         emu = 1;
2397     }
2398
2399     sx = (sx << 2) >> lowres;
2400     sy = (sy << 2) >> lowres;
2401     if (field_select)
2402         src += s->linesize;
2403     pix_op[op_index](dest, src, stride, h, sx, sy);
2404     return emu;
2405 }
2406
2407 /* apply one mpeg motion vector to the three components */
2408 static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,
2409                                                 uint8_t *dest_y,
2410                                                 uint8_t *dest_cb,
2411                                                 uint8_t *dest_cr,
2412                                                 int field_based,
2413                                                 int bottom_field,
2414                                                 int field_select,
2415                                                 uint8_t **ref_picture,
2416                                                 h264_chroma_mc_func *pix_op,
2417                                                 int motion_x, int motion_y,
2418                                                 int h, int mb_y)
2419 {
2420     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
2421     int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, sx, sy, uvsx, uvsy;
2422     ptrdiff_t uvlinesize, linesize;
2423     const int lowres     = s->avctx->lowres;
2424     const int op_index   = FFMIN(lowres-1+s->chroma_x_shift, 3);
2425     const int block_s    = 8>>lowres;
2426     const int s_mask     = (2 << lowres) - 1;
2427     const int h_edge_pos = s->h_edge_pos >> lowres;
2428     const int v_edge_pos = s->v_edge_pos >> lowres;
2429     linesize   = s->current_picture.f->linesize[0] << field_based;
2430     uvlinesize = s->current_picture.f->linesize[1] << field_based;
2431
2432     // FIXME obviously not perfect but qpel will not work in lowres anyway
2433     if (s->quarter_sample) {
2434         motion_x /= 2;
2435         motion_y /= 2;
2436     }
2437
2438     if(field_based){
2439         motion_y += (bottom_field - field_select)*((1 << lowres)-1);
2440     }
2441
2442     sx = motion_x & s_mask;
2443     sy = motion_y & s_mask;
2444     src_x = s->mb_x * 2 * block_s + (motion_x >> lowres + 1);
2445     src_y = (mb_y * 2 * block_s >> field_based) + (motion_y >> lowres + 1);
2446
2447     if (s->out_format == FMT_H263) {
2448         uvsx    = ((motion_x >> 1) & s_mask) | (sx & 1);
2449         uvsy    = ((motion_y >> 1) & s_mask) | (sy & 1);
2450         uvsrc_x = src_x >> 1;
2451         uvsrc_y = src_y >> 1;
2452     } else if (s->out_format == FMT_H261) {
2453         // even chroma mv's are full pel in H261
2454         mx      = motion_x / 4;
2455         my      = motion_y / 4;
2456         uvsx    = (2 * mx) & s_mask;
2457         uvsy    = (2 * my) & s_mask;
2458         uvsrc_x = s->mb_x * block_s + (mx >> lowres);
2459         uvsrc_y =    mb_y * block_s + (my >> lowres);
2460     } else {
2461         if(s->chroma_y_shift){
2462             mx      = motion_x / 2;
2463             my      = motion_y / 2;
2464             uvsx    = mx & s_mask;
2465             uvsy    = my & s_mask;
2466             uvsrc_x = s->mb_x * block_s                 + (mx >> lowres + 1);
2467             uvsrc_y =   (mb_y * block_s >> field_based) + (my >> lowres + 1);
2468         } else {
2469             if(s->chroma_x_shift){
2470             //Chroma422
2471                 mx = motion_x / 2;
2472                 uvsx = mx & s_mask;
2473                 uvsy = motion_y & s_mask;
2474                 uvsrc_y = src_y;
2475                 uvsrc_x = s->mb_x*block_s               + (mx >> (lowres+1));
2476             } else {
2477             //Chroma444
2478                 uvsx = motion_x & s_mask;
2479                 uvsy = motion_y & s_mask;
2480                 uvsrc_x = src_x;
2481                 uvsrc_y = src_y;
2482             }
2483         }
2484     }
2485
2486     ptr_y  = ref_picture[0] + src_y   * linesize   + src_x;
2487     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
2488     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
2489
2490     if ((unsigned) src_x > FFMAX( h_edge_pos - (!!sx) - 2 * block_s,       0) || uvsrc_y<0 ||
2491         (unsigned) src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
2492         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,
2493                                  linesize >> field_based, linesize >> field_based,
2494                                  17, 17 + field_based,
2495                                 src_x, src_y << field_based, h_edge_pos,
2496                                 v_edge_pos);
2497         ptr_y = s->edge_emu_buffer;
2498         if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2499             uint8_t *uvbuf = s->edge_emu_buffer + 18 * s->linesize;
2500             s->vdsp.emulated_edge_mc(uvbuf,  ptr_cb,
2501                                      uvlinesize >> field_based, uvlinesize >> field_based,
2502                                      9, 9 + field_based,
2503                                     uvsrc_x, uvsrc_y << field_based,
2504                                     h_edge_pos >> 1, v_edge_pos >> 1);
2505             s->vdsp.emulated_edge_mc(uvbuf + 16,  ptr_cr,
2506                                      uvlinesize >> field_based,uvlinesize >> field_based,
2507                                      9, 9 + field_based,
2508                                     uvsrc_x, uvsrc_y << field_based,
2509                                     h_edge_pos >> 1, v_edge_pos >> 1);
2510             ptr_cb = uvbuf;
2511             ptr_cr = uvbuf + 16;
2512         }
2513     }
2514
2515     // FIXME use this for field pix too instead of the obnoxious hack which changes picture.f->data
2516     if (bottom_field) {
2517         dest_y  += s->linesize;
2518         dest_cb += s->uvlinesize;
2519         dest_cr += s->uvlinesize;
2520     }
2521
2522     if (field_select) {
2523         ptr_y   += s->linesize;
2524         ptr_cb  += s->uvlinesize;
2525         ptr_cr  += s->uvlinesize;
2526     }
2527
2528     sx = (sx << 2) >> lowres;
2529     sy = (sy << 2) >> lowres;
2530     pix_op[lowres - 1](dest_y, ptr_y, linesize, h, sx, sy);
2531
2532     if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2533         int hc = s->chroma_y_shift ? (h+1-bottom_field)>>1 : h;
2534         uvsx = (uvsx << 2) >> lowres;
2535         uvsy = (uvsy << 2) >> lowres;
2536         if (hc) {
2537             pix_op[op_index](dest_cb, ptr_cb, uvlinesize, hc, uvsx, uvsy);
2538             pix_op[op_index](dest_cr, ptr_cr, uvlinesize, hc, uvsx, uvsy);
2539         }
2540     }
2541     // FIXME h261 lowres loop filter
2542 }
2543
2544 static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
2545                                             uint8_t *dest_cb, uint8_t *dest_cr,
2546                                             uint8_t **ref_picture,
2547                                             h264_chroma_mc_func * pix_op,
2548                                             int mx, int my)
2549 {
2550     const int lowres     = s->avctx->lowres;
2551     const int op_index   = FFMIN(lowres, 3);
2552     const int block_s    = 8 >> lowres;
2553     const int s_mask     = (2 << lowres) - 1;
2554     const int h_edge_pos = s->h_edge_pos >> lowres + 1;
2555     const int v_edge_pos = s->v_edge_pos >> lowres + 1;
2556     int emu = 0, src_x, src_y, sx, sy;
2557     ptrdiff_t offset;
2558     uint8_t *ptr;
2559
2560     if (s->quarter_sample) {
2561         mx /= 2;
2562         my /= 2;
2563     }
2564
2565     /* In case of 8X8, we construct a single chroma motion vector
2566        with a special rounding */
2567     mx = ff_h263_round_chroma(mx);
2568     my = ff_h263_round_chroma(my);
2569
2570     sx = mx & s_mask;
2571     sy = my & s_mask;
2572     src_x = s->mb_x * block_s + (mx >> lowres + 1);
2573     src_y = s->mb_y * block_s + (my >> lowres + 1);
2574
2575     offset = src_y * s->uvlinesize + src_x;
2576     ptr = ref_picture[1] + offset;
2577     if ((unsigned) src_x > FFMAX(h_edge_pos - (!!sx) - block_s, 0) ||
2578         (unsigned) src_y > FFMAX(v_edge_pos - (!!sy) - block_s, 0)) {
2579         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
2580                                  s->uvlinesize, s->uvlinesize,
2581                                  9, 9,
2582                                  src_x, src_y, h_edge_pos, v_edge_pos);
2583         ptr = s->edge_emu_buffer;
2584         emu = 1;
2585     }
2586     sx = (sx << 2) >> lowres;
2587     sy = (sy << 2) >> lowres;
2588     pix_op[op_index](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);
2589
2590     ptr = ref_picture[2] + offset;
2591     if (emu) {
2592         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
2593                                  s->uvlinesize, s->uvlinesize,
2594                                  9, 9,
2595                                  src_x, src_y, h_edge_pos, v_edge_pos);
2596         ptr = s->edge_emu_buffer;
2597     }
2598     pix_op[op_index](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
2599 }
2600
2601 /**
2602  * motion compensation of a single macroblock
2603  * @param s context
2604  * @param dest_y luma destination pointer
2605  * @param dest_cb chroma cb/u destination pointer
2606  * @param dest_cr chroma cr/v destination pointer
2607  * @param dir direction (0->forward, 1->backward)
2608  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
2609  * @param pix_op halfpel motion compensation function (average or put normally)
2610  * the motion vectors are taken from s->mv and the MV type from s->mv_type
2611  */
2612 static inline void MPV_motion_lowres(MpegEncContext *s,
2613                                      uint8_t *dest_y, uint8_t *dest_cb,
2614                                      uint8_t *dest_cr,
2615                                      int dir, uint8_t **ref_picture,
2616                                      h264_chroma_mc_func *pix_op)
2617 {
2618     int mx, my;
2619     int mb_x, mb_y, i;
2620     const int lowres  = s->avctx->lowres;
2621     const int block_s = 8 >>lowres;
2622
2623     mb_x = s->mb_x;
2624     mb_y = s->mb_y;
2625
2626     switch (s->mv_type) {
2627     case MV_TYPE_16X16:
2628         mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2629                            0, 0, 0,
2630                            ref_picture, pix_op,
2631                            s->mv[dir][0][0], s->mv[dir][0][1],
2632                            2 * block_s, mb_y);
2633         break;
2634     case MV_TYPE_8X8:
2635         mx = 0;
2636         my = 0;
2637         for (i = 0; i < 4; i++) {
2638             hpel_motion_lowres(s, dest_y + ((i & 1) + (i >> 1) *
2639                                s->linesize) * block_s,
2640                                ref_picture[0], 0, 0,
2641                                (2 * mb_x + (i & 1)) * block_s,
2642                                (2 * mb_y + (i >> 1)) * block_s,
2643                                s->width, s->height, s->linesize,
2644                                s->h_edge_pos >> lowres, s->v_edge_pos >> lowres,
2645                                block_s, block_s, pix_op,
2646                                s->mv[dir][i][0], s->mv[dir][i][1]);
2647
2648             mx += s->mv[dir][i][0];
2649             my += s->mv[dir][i][1];
2650         }
2651
2652         if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY))
2653             chroma_4mv_motion_lowres(s, dest_cb, dest_cr, ref_picture,
2654                                      pix_op, mx, my);
2655         break;
2656     case MV_TYPE_FIELD:
2657         if (s->picture_structure == PICT_FRAME) {
2658             /* top field */
2659             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2660                                1, 0, s->field_select[dir][0],
2661                                ref_picture, pix_op,
2662                                s->mv[dir][0][0], s->mv[dir][0][1],
2663                                block_s, mb_y);
2664             /* bottom field */
2665             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2666                                1, 1, s->field_select[dir][1],
2667                                ref_picture, pix_op,
2668                                s->mv[dir][1][0], s->mv[dir][1][1],
2669                                block_s, mb_y);
2670         } else {
2671             if (s->picture_structure != s->field_select[dir][0] + 1 &&
2672                 s->pict_type != AV_PICTURE_TYPE_B && !s->first_field) {
2673                 ref_picture = s->current_picture_ptr->f->data;
2674
2675             }
2676             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2677                                0, 0, s->field_select[dir][0],
2678                                ref_picture, pix_op,
2679                                s->mv[dir][0][0],
2680                                s->mv[dir][0][1], 2 * block_s, mb_y >> 1);
2681             }
2682         break;
2683     case MV_TYPE_16X8:
2684         for (i = 0; i < 2; i++) {
2685             uint8_t **ref2picture;
2686
2687             if (s->picture_structure == s->field_select[dir][i] + 1 ||
2688                 s->pict_type == AV_PICTURE_TYPE_B || s->first_field) {
2689                 ref2picture = ref_picture;
2690             } else {
2691                 ref2picture = s->current_picture_ptr->f->data;
2692             }
2693
2694             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2695                                0, 0, s->field_select[dir][i],
2696                                ref2picture, pix_op,
2697                                s->mv[dir][i][0], s->mv[dir][i][1] +
2698                                2 * block_s * i, block_s, mb_y >> 1);
2699
2700             dest_y  +=  2 * block_s *  s->linesize;
2701             dest_cb += (2 * block_s >> s->chroma_y_shift) * s->uvlinesize;
2702             dest_cr += (2 * block_s >> s->chroma_y_shift) * s->uvlinesize;
2703         }
2704         break;
2705     case MV_TYPE_DMV:
2706         if (s->picture_structure == PICT_FRAME) {
2707             for (i = 0; i < 2; i++) {
2708                 int j;
2709                 for (j = 0; j < 2; j++) {
2710                     mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2711                                        1, j, j ^ i,
2712                                        ref_picture, pix_op,
2713                                        s->mv[dir][2 * i + j][0],
2714                                        s->mv[dir][2 * i + j][1],
2715                                        block_s, mb_y);
2716                 }
2717                 pix_op = s->h264chroma.avg_h264_chroma_pixels_tab;
2718             }
2719         } else {
2720             for (i = 0; i < 2; i++) {
2721                 mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2722                                    0, 0, s->picture_structure != i + 1,
2723                                    ref_picture, pix_op,
2724                                    s->mv[dir][2 * i][0],s->mv[dir][2 * i][1],
2725                                    2 * block_s, mb_y >> 1);
2726
2727                 // after put we make avg of the same block
2728                 pix_op = s->h264chroma.avg_h264_chroma_pixels_tab;
2729
2730                 // opposite parity is always in the same
2731                 // frame if this is second field
2732                 if (!s->first_field) {
2733                     ref_picture = s->current_picture_ptr->f->data;
2734                 }
2735             }
2736         }
2737         break;
2738     default:
2739         av_assert2(0);
2740     }
2741 }
2742
2743 /**
2744  * find the lowest MB row referenced in the MVs
2745  */
2746 int ff_MPV_lowest_referenced_row(MpegEncContext *s, int dir)
2747 {
2748     int my_max = INT_MIN, my_min = INT_MAX, qpel_shift = !s->quarter_sample;
2749     int my, off, i, mvs;
2750
2751     if (s->picture_structure != PICT_FRAME || s->mcsel)
2752         goto unhandled;
2753
2754     switch (s->mv_type) {
2755         case MV_TYPE_16X16:
2756             mvs = 1;
2757             break;
2758         case MV_TYPE_16X8:
2759             mvs = 2;
2760             break;
2761         case MV_TYPE_8X8:
2762             mvs = 4;
2763             break;
2764         default:
2765             goto unhandled;
2766     }
2767
2768     for (i = 0; i < mvs; i++) {
2769         my = s->mv[dir][i][1]<<qpel_shift;
2770         my_max = FFMAX(my_max, my);
2771         my_min = FFMIN(my_min, my);
2772     }
2773
2774     off = (FFMAX(-my_min, my_max) + 63) >> 6;
2775
2776     return FFMIN(FFMAX(s->mb_y + off, 0), s->mb_height-1);
2777 unhandled:
2778     return s->mb_height-1;
2779 }
2780
2781 /* put block[] to dest[] */
2782 static inline void put_dct(MpegEncContext *s,
2783                            int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
2784 {
2785     s->dct_unquantize_intra(s, block, i, qscale);
2786     s->dsp.idct_put (dest, line_size, block);
2787 }
2788
2789 /* add block[] to dest[] */
2790 static inline void add_dct(MpegEncContext *s,
2791                            int16_t *block, int i, uint8_t *dest, int line_size)
2792 {
2793     if (s->block_last_index[i] >= 0) {
2794         s->dsp.idct_add (dest, line_size, block);
2795     }
2796 }
2797
2798 static inline void add_dequant_dct(MpegEncContext *s,
2799                            int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
2800 {
2801     if (s->block_last_index[i] >= 0) {
2802         s->dct_unquantize_inter(s, block, i, qscale);
2803
2804         s->dsp.idct_add (dest, line_size, block);
2805     }
2806 }
2807
2808 /**
2809  * Clean dc, ac, coded_block for the current non-intra MB.
2810  */
2811 void ff_clean_intra_table_entries(MpegEncContext *s)
2812 {
2813     int wrap = s->b8_stride;
2814     int xy = s->block_index[0];
2815
2816     s->dc_val[0][xy           ] =
2817     s->dc_val[0][xy + 1       ] =
2818     s->dc_val[0][xy     + wrap] =
2819     s->dc_val[0][xy + 1 + wrap] = 1024;
2820     /* ac pred */
2821     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
2822     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
2823     if (s->msmpeg4_version>=3) {
2824         s->coded_block[xy           ] =
2825         s->coded_block[xy + 1       ] =
2826         s->coded_block[xy     + wrap] =
2827         s->coded_block[xy + 1 + wrap] = 0;
2828     }
2829     /* chroma */
2830     wrap = s->mb_stride;
2831     xy = s->mb_x + s->mb_y * wrap;
2832     s->dc_val[1][xy] =
2833     s->dc_val[2][xy] = 1024;
2834     /* ac pred */
2835     memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
2836     memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
2837
2838     s->mbintra_table[xy]= 0;
2839 }
2840
2841 /* generic function called after a macroblock has been parsed by the
2842    decoder or after it has been encoded by the encoder.
2843
2844    Important variables used:
2845    s->mb_intra : true if intra macroblock
2846    s->mv_dir   : motion vector direction
2847    s->mv_type  : motion vector type
2848    s->mv       : motion vector
2849    s->interlaced_dct : true if interlaced dct used (mpeg2)
2850  */
2851 static av_always_inline
2852 void MPV_decode_mb_internal(MpegEncContext *s, int16_t block[12][64],
2853                             int lowres_flag, int is_mpeg12)
2854 {
2855     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
2856
2857     if (CONFIG_XVMC &&
2858         s->avctx->hwaccel && s->avctx->hwaccel->decode_mb) {
2859         s->avctx->hwaccel->decode_mb(s);//xvmc uses pblocks
2860         return;
2861     }
2862
2863     if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
2864        /* print DCT coefficients */
2865        int i,j;
2866        av_log(s->avctx, AV_LOG_DEBUG, "DCT coeffs of MB at %dx%d:\n", s->mb_x, s->mb_y);
2867        for(i=0; i<6; i++){
2868            for(j=0; j<64; j++){
2869                av_log(s->avctx, AV_LOG_DEBUG, "%5d", block[i][s->dsp.idct_permutation[j]]);
2870            }
2871            av_log(s->avctx, AV_LOG_DEBUG, "\n");
2872        }
2873     }
2874
2875     s->current_picture.qscale_table[mb_xy] = s->qscale;
2876
2877     /* update DC predictors for P macroblocks */
2878     if (!s->mb_intra) {
2879         if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {
2880             if(s->mbintra_table[mb_xy])
2881                 ff_clean_intra_table_entries(s);
2882         } else {
2883             s->last_dc[0] =
2884             s->last_dc[1] =
2885             s->last_dc[2] = 128 << s->intra_dc_precision;
2886         }
2887     }
2888     else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))
2889         s->mbintra_table[mb_xy]=1;
2890
2891     if (   (s->flags&CODEC_FLAG_PSNR)
2892         || s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor
2893         || !(s->encoding && (s->intra_only || s->pict_type==AV_PICTURE_TYPE_B) && s->avctx->mb_decision != FF_MB_DECISION_RD)) { //FIXME precalc
2894         uint8_t *dest_y, *dest_cb, *dest_cr;
2895         int dct_linesize, dct_offset;
2896         op_pixels_func (*op_pix)[4];
2897         qpel_mc_func (*op_qpix)[16];
2898         const int linesize   = s->current_picture.f->linesize[0]; //not s->linesize as this would be wrong for field pics
2899         const int uvlinesize = s->current_picture.f->linesize[1];
2900         const int readable= s->pict_type != AV_PICTURE_TYPE_B || s->encoding || s->avctx->draw_horiz_band || lowres_flag;
2901         const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;
2902
2903         /* avoid copy if macroblock skipped in last frame too */
2904         /* skip only during decoding as we might trash the buffers during encoding a bit */
2905         if(!s->encoding){
2906             uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
2907
2908             if (s->mb_skipped) {
2909                 s->mb_skipped= 0;
2910                 av_assert2(s->pict_type!=AV_PICTURE_TYPE_I);
2911                 *mbskip_ptr = 1;
2912             } else if(!s->current_picture.reference) {
2913                 *mbskip_ptr = 1;
2914             } else{
2915                 *mbskip_ptr = 0; /* not skipped */
2916             }
2917         }
2918
2919         dct_linesize = linesize << s->interlaced_dct;
2920         dct_offset   = s->interlaced_dct ? linesize : linesize * block_size;
2921
2922         if(readable){
2923             dest_y=  s->dest[0];
2924             dest_cb= s->dest[1];
2925             dest_cr= s->dest[2];
2926         }else{
2927             dest_y = s->b_scratchpad;
2928             dest_cb= s->b_scratchpad+16*linesize;
2929             dest_cr= s->b_scratchpad+32*linesize;
2930         }
2931
2932         if (!s->mb_intra) {
2933             /* motion handling */
2934             /* decoding or more than one mb_type (MC was already done otherwise) */
2935             if(!s->encoding){
2936
2937                 if(HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
2938                     if (s->mv_dir & MV_DIR_FORWARD) {
2939                         ff_thread_await_progress(&s->last_picture_ptr->tf,
2940                                                  ff_MPV_lowest_referenced_row(s, 0),
2941                                                  0);
2942                     }
2943                     if (s->mv_dir & MV_DIR_BACKWARD) {
2944                         ff_thread_await_progress(&s->next_picture_ptr->tf,
2945                                                  ff_MPV_lowest_referenced_row(s, 1),
2946                                                  0);
2947                     }
2948                 }
2949
2950                 if(lowres_flag){
2951                     h264_chroma_mc_func *op_pix = s->h264chroma.put_h264_chroma_pixels_tab;
2952
2953                     if (s->mv_dir & MV_DIR_FORWARD) {
2954                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f->data, op_pix);
2955                         op_pix = s->h264chroma.avg_h264_chroma_pixels_tab;
2956                     }
2957                     if (s->mv_dir & MV_DIR_BACKWARD) {
2958                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f->data, op_pix);
2959                     }
2960                 }else{
2961                     op_qpix = s->me.qpel_put;
2962                     if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
2963                         op_pix = s->hdsp.put_pixels_tab;
2964                     }else{
2965                         op_pix = s->hdsp.put_no_rnd_pixels_tab;
2966                     }
2967                     if (s->mv_dir & MV_DIR_FORWARD) {
2968                         ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f->data, op_pix, op_qpix);
2969                         op_pix = s->hdsp.avg_pixels_tab;
2970                         op_qpix= s->me.qpel_avg;
2971                     }
2972                     if (s->mv_dir & MV_DIR_BACKWARD) {
2973                         ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f->data, op_pix, op_qpix);
2974                     }
2975                 }
2976             }
2977
2978             /* skip dequant / idct if we are really late ;) */
2979             if(s->avctx->skip_idct){
2980                 if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B)
2981                    ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I)
2982                    || s->avctx->skip_idct >= AVDISCARD_ALL)
2983                     goto skip_idct;
2984             }
2985
2986             /* add dct residue */
2987             if(s->encoding || !(   s->msmpeg4_version || s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO
2988                                 || (s->codec_id==AV_CODEC_ID_MPEG4 && !s->mpeg_quant))){
2989                 add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
2990                 add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
2991                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
2992                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
2993
2994                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2995                     if (s->chroma_y_shift){
2996                         add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
2997                         add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
2998                     }else{
2999                         dct_linesize >>= 1;
3000                         dct_offset >>=1;
3001                         add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
3002                         add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
3003                         add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
3004                         add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
3005                     }
3006                 }
3007             } else if(is_mpeg12 || (s->codec_id != AV_CODEC_ID_WMV2)){
3008                 add_dct(s, block[0], 0, dest_y                          , dct_linesize);
3009                 add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);
3010                 add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);
3011                 add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);
3012
3013                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
3014                     if(s->chroma_y_shift){//Chroma420
3015                         add_dct(s, block[4], 4, dest_cb, uvlinesize);
3016                         add_dct(s, block[5], 5, dest_cr, uvlinesize);
3017                     }else{
3018                         //chroma422
3019                         dct_linesize = uvlinesize << s->interlaced_dct;
3020                         dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
3021
3022                         add_dct(s, block[4], 4, dest_cb, dct_linesize);
3023                         add_dct(s, block[5], 5, dest_cr, dct_linesize);
3024                         add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);
3025                         add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);
3026                         if(!s->chroma_x_shift){//Chroma444
3027                             add_dct(s, block[8], 8, dest_cb+block_size, dct_linesize);
3028                             add_dct(s, block[9], 9, dest_cr+block_size, dct_linesize);
3029                             add_dct(s, block[10], 10, dest_cb+block_size+dct_offset, dct_linesize);
3030                             add_dct(s, block[11], 11, dest_cr+block_size+dct_offset, dct_linesize);
3031                         }
3032                     }
3033                 }//fi gray
3034             }
3035             else if (CONFIG_WMV2_DECODER || CONFIG_WMV2_ENCODER) {
3036                 ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
3037             }
3038         } else {
3039             /* dct only in intra block */
3040             if(s->encoding || !(s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO)){
3041                 put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
3042                 put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
3043                 put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
3044                 put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
3045
3046                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
3047                     if(s->chroma_y_shift){
3048                         put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
3049                         put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
3050                     }else{
3051                         dct_offset >>=1;
3052                         dct_linesize >>=1;
3053                         put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
3054                         put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
3055                         put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
3056                         put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
3057                     }
3058                 }
3059             }else{
3060                 s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);
3061                 s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);
3062                 s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);
3063                 s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);
3064
3065                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
3066                     if(s->chroma_y_shift){
3067                         s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
3068                         s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
3069                     }else{
3070
3071                         dct_linesize = uvlinesize << s->interlaced_dct;
3072                         dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
3073
3074                         s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
3075                         s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
3076                         s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
3077                         s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
3078                         if(!s->chroma_x_shift){//Chroma444
3079                             s->dsp.idct_put(dest_cb + block_size,              dct_linesize, block[8]);
3080                             s->dsp.idct_put(dest_cr + block_size,              dct_linesize, block[9]);
3081                             s->dsp.idct_put(dest_cb + block_size + dct_offset, dct_linesize, block[10]);
3082                             s->dsp.idct_put(dest_cr + block_size + dct_offset, dct_linesize, block[11]);
3083                         }
3084                     }
3085                 }//gray
3086             }
3087         }
3088 skip_idct:
3089         if(!readable){
3090             s->hdsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
3091             s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
3092             s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
3093         }
3094     }
3095 }
3096
3097 void ff_MPV_decode_mb(MpegEncContext *s, int16_t block[12][64]){
3098 #if !CONFIG_SMALL
3099     if(s->out_format == FMT_MPEG1) {
3100         if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 1);
3101         else                 MPV_decode_mb_internal(s, block, 0, 1);
3102     } else
3103 #endif
3104     if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 0);
3105     else                  MPV_decode_mb_internal(s, block, 0, 0);
3106 }
3107
3108 void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h)
3109 {
3110     ff_draw_horiz_band(s->avctx, s->current_picture_ptr->f,
3111                        s->last_picture_ptr ? s->last_picture_ptr->f : NULL, y, h, s->picture_structure,
3112                        s->first_field, s->low_delay);
3113 }
3114
3115 void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
3116     const int linesize   = s->current_picture.f->linesize[0]; //not s->linesize as this would be wrong for field pics
3117     const int uvlinesize = s->current_picture.f->linesize[1];
3118     const int mb_size= 4 - s->avctx->lowres;
3119
3120     s->block_index[0]= s->b8_stride*(s->mb_y*2    ) - 2 + s->mb_x*2;
3121     s->block_index[1]= s->b8_stride*(s->mb_y*2    ) - 1 + s->mb_x*2;
3122     s->block_index[2]= s->b8_stride*(s->mb_y*2 + 1) - 2 + s->mb_x*2;
3123     s->block_index[3]= s->b8_stride*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
3124     s->block_index[4]= s->mb_stride*(s->mb_y + 1)                + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
3125     s->block_index[5]= s->mb_stride*(s->mb_y + s->mb_height + 2) + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
3126     //block_index is not used by mpeg2, so it is not affected by chroma_format
3127
3128     s->dest[0] = s->current_picture.f->data[0] + ((s->mb_x - 1) <<  mb_size);
3129     s->dest[1] = s->current_picture.f->data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
3130     s->dest[2] = s->current_picture.f->data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
3131
3132     if(!(s->pict_type==AV_PICTURE_TYPE_B && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
3133     {
3134         if(s->picture_structure==PICT_FRAME){
3135         s->dest[0] += s->mb_y *   linesize << mb_size;
3136         s->dest[1] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
3137         s->dest[2] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
3138         }else{
3139             s->dest[0] += (s->mb_y>>1) *   linesize << mb_size;
3140             s->dest[1] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
3141             s->dest[2] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
3142             av_assert1((s->mb_y&1) == (s->picture_structure == PICT_BOTTOM_FIELD));
3143         }
3144     }
3145 }
3146
3147 /**
3148  * Permute an 8x8 block.
3149  * @param block the block which will be permuted according to the given permutation vector
3150  * @param permutation the permutation vector
3151  * @param last the last non zero coefficient in scantable order, used to speed the permutation up
3152  * @param scantable the used scantable, this is only used to speed the permutation up, the block is not
3153  *                  (inverse) permutated to scantable order!
3154  */
3155 void ff_block_permute(int16_t *block, uint8_t *permutation, const uint8_t *scantable, int last)
3156 {
3157     int i;
3158     int16_t temp[64];
3159
3160     if(last<=0) return;
3161     //if(permutation[1]==1) return; //FIXME it is ok but not clean and might fail for some permutations
3162
3163     for(i=0; i<=last; i++){
3164         const int j= scantable[i];
3165         temp[j]= block[j];
3166         block[j]=0;
3167     }
3168
3169     for(i=0; i<=last; i++){
3170         const int j= scantable[i];
3171         const int perm_j= permutation[j];
3172         block[perm_j]= temp[j];
3173     }
3174 }
3175
3176 void ff_mpeg_flush(AVCodecContext *avctx){
3177     int i;
3178     MpegEncContext *s = avctx->priv_data;
3179
3180     if(s==NULL || s->picture==NULL)
3181         return;
3182
3183     for (i = 0; i < MAX_PICTURE_COUNT; i++)
3184         ff_mpeg_unref_picture(s, &s->picture[i]);
3185     s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
3186
3187     ff_mpeg_unref_picture(s, &s->current_picture);
3188     ff_mpeg_unref_picture(s, &s->last_picture);
3189     ff_mpeg_unref_picture(s, &s->next_picture);
3190
3191     s->mb_x= s->mb_y= 0;
3192     s->closed_gop= 0;
3193
3194     s->parse_context.state= -1;
3195     s->parse_context.frame_start_found= 0;
3196     s->parse_context.overread= 0;
3197     s->parse_context.overread_index= 0;
3198     s->parse_context.index= 0;
3199     s->parse_context.last_index= 0;
3200     s->bitstream_buffer_size=0;
3201     s->pp_time=0;
3202 }
3203
3204 /**
3205  * set qscale and update qscale dependent variables.
3206  */
3207 void ff_set_qscale(MpegEncContext * s, int qscale)
3208 {
3209     if (qscale < 1)
3210         qscale = 1;
3211     else if (qscale > 31)
3212         qscale = 31;
3213
3214     s->qscale = qscale;
3215     s->chroma_qscale= s->chroma_qscale_table[qscale];
3216
3217     s->y_dc_scale= s->y_dc_scale_table[ qscale ];
3218     s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
3219 }
3220
3221 void ff_MPV_report_decode_progress(MpegEncContext *s)
3222 {
3223     if (s->pict_type != AV_PICTURE_TYPE_B && !s->partitioned_frame && !s->er.error_occurred)
3224         ff_thread_report_progress(&s->current_picture_ptr->tf, s->mb_y, 0);
3225 }
3226
3227 #if CONFIG_ERROR_RESILIENCE
3228 void ff_mpeg_set_erpic(ERPicture *dst, Picture *src)
3229 {
3230     int i;
3231
3232     memset(dst, 0, sizeof(*dst));
3233     if (!src)
3234         return;
3235
3236     dst->f = src->f;
3237     dst->tf = &src->tf;
3238
3239     for (i = 0; i < 2; i++) {
3240         dst->motion_val[i] = src->motion_val[i];
3241         dst->ref_index[i] = src->ref_index[i];
3242     }
3243
3244     dst->mb_type = src->mb_type;
3245     dst->field_picture = src->field_picture;
3246 }
3247
3248 void ff_mpeg_er_frame_start(MpegEncContext *s)
3249 {
3250     ERContext *er = &s->er;
3251
3252     ff_mpeg_set_erpic(&er->cur_pic, s->current_picture_ptr);
3253     ff_mpeg_set_erpic(&er->next_pic, s->next_picture_ptr);
3254     ff_mpeg_set_erpic(&er->last_pic, s->last_picture_ptr);
3255
3256     er->pp_time           = s->pp_time;
3257     er->pb_time           = s->pb_time;
3258     er->quarter_sample    = s->quarter_sample;
3259     er->partitioned_frame = s->partitioned_frame;
3260
3261     ff_er_frame_start(er);
3262 }
3263 #endif /* CONFIG_ERROR_RESILIENCE */