]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegvideo.c
73778f51b4bbce97ac1430e4636a05450108b4fd
[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 Libav.
9  *
10  * Libav 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  * Libav 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 Libav; 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 "internal.h"
38 #include "mathops.h"
39 #include "mpegvideo.h"
40 #include "mjpegenc.h"
41 #include "msmpeg4.h"
42 #include "xvmc_internal.h"
43 #include "thread.h"
44 #include <limits.h>
45
46 static const uint8_t ff_default_chroma_qscale_table[32] = {
47 //   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
48      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
49     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
50 };
51
52 const uint8_t ff_mpeg1_dc_scale_table[128] = {
53 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
54     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
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 };
63
64 static const uint8_t mpeg2_dc_scale_table1[128] = {
65 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
66     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
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 };
75
76 static const uint8_t mpeg2_dc_scale_table2[128] = {
77 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
78     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
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 };
87
88 static const uint8_t mpeg2_dc_scale_table3[128] = {
89 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
90     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
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 };
99
100 const uint8_t *const ff_mpeg2_dc_scale_table[4] = {
101     ff_mpeg1_dc_scale_table,
102     mpeg2_dc_scale_table1,
103     mpeg2_dc_scale_table2,
104     mpeg2_dc_scale_table3,
105 };
106
107 const enum AVPixelFormat ff_pixfmt_list_420[] = {
108     AV_PIX_FMT_YUV420P,
109     AV_PIX_FMT_NONE
110 };
111
112 static void dct_unquantize_mpeg1_intra_c(MpegEncContext *s,
113                                    int16_t *block, int n, int qscale)
114 {
115     int i, level, nCoeffs;
116     const uint16_t *quant_matrix;
117
118     nCoeffs= s->block_last_index[n];
119
120     if (n < 4)
121         block[0] = block[0] * s->y_dc_scale;
122     else
123         block[0] = block[0] * s->c_dc_scale;
124     /* XXX: only mpeg1 */
125     quant_matrix = s->intra_matrix;
126     for(i=1;i<=nCoeffs;i++) {
127         int j= s->intra_scantable.permutated[i];
128         level = block[j];
129         if (level) {
130             if (level < 0) {
131                 level = -level;
132                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
133                 level = (level - 1) | 1;
134                 level = -level;
135             } else {
136                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
137                 level = (level - 1) | 1;
138             }
139             block[j] = level;
140         }
141     }
142 }
143
144 static void dct_unquantize_mpeg1_inter_c(MpegEncContext *s,
145                                    int16_t *block, int n, int qscale)
146 {
147     int i, level, nCoeffs;
148     const uint16_t *quant_matrix;
149
150     nCoeffs= s->block_last_index[n];
151
152     quant_matrix = s->inter_matrix;
153     for(i=0; i<=nCoeffs; i++) {
154         int j= s->intra_scantable.permutated[i];
155         level = block[j];
156         if (level) {
157             if (level < 0) {
158                 level = -level;
159                 level = (((level << 1) + 1) * qscale *
160                          ((int) (quant_matrix[j]))) >> 4;
161                 level = (level - 1) | 1;
162                 level = -level;
163             } else {
164                 level = (((level << 1) + 1) * qscale *
165                          ((int) (quant_matrix[j]))) >> 4;
166                 level = (level - 1) | 1;
167             }
168             block[j] = level;
169         }
170     }
171 }
172
173 static void dct_unquantize_mpeg2_intra_c(MpegEncContext *s,
174                                    int16_t *block, int n, int qscale)
175 {
176     int i, level, nCoeffs;
177     const uint16_t *quant_matrix;
178
179     if(s->alternate_scan) nCoeffs= 63;
180     else nCoeffs= s->block_last_index[n];
181
182     if (n < 4)
183         block[0] = block[0] * s->y_dc_scale;
184     else
185         block[0] = block[0] * s->c_dc_scale;
186     quant_matrix = s->intra_matrix;
187     for(i=1;i<=nCoeffs;i++) {
188         int j= s->intra_scantable.permutated[i];
189         level = block[j];
190         if (level) {
191             if (level < 0) {
192                 level = -level;
193                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
194                 level = -level;
195             } else {
196                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
197             }
198             block[j] = level;
199         }
200     }
201 }
202
203 static void dct_unquantize_mpeg2_intra_bitexact(MpegEncContext *s,
204                                    int16_t *block, int n, int qscale)
205 {
206     int i, level, nCoeffs;
207     const uint16_t *quant_matrix;
208     int sum=-1;
209
210     if(s->alternate_scan) nCoeffs= 63;
211     else nCoeffs= s->block_last_index[n];
212
213     if (n < 4)
214         block[0] = block[0] * s->y_dc_scale;
215     else
216         block[0] = block[0] * s->c_dc_scale;
217     quant_matrix = s->intra_matrix;
218     for(i=1;i<=nCoeffs;i++) {
219         int j= s->intra_scantable.permutated[i];
220         level = block[j];
221         if (level) {
222             if (level < 0) {
223                 level = -level;
224                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
225                 level = -level;
226             } else {
227                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
228             }
229             block[j] = level;
230             sum+=level;
231         }
232     }
233     block[63]^=sum&1;
234 }
235
236 static void dct_unquantize_mpeg2_inter_c(MpegEncContext *s,
237                                    int16_t *block, int n, int qscale)
238 {
239     int i, level, nCoeffs;
240     const uint16_t *quant_matrix;
241     int sum=-1;
242
243     if(s->alternate_scan) nCoeffs= 63;
244     else nCoeffs= s->block_last_index[n];
245
246     quant_matrix = s->inter_matrix;
247     for(i=0; i<=nCoeffs; i++) {
248         int j= s->intra_scantable.permutated[i];
249         level = block[j];
250         if (level) {
251             if (level < 0) {
252                 level = -level;
253                 level = (((level << 1) + 1) * qscale *
254                          ((int) (quant_matrix[j]))) >> 4;
255                 level = -level;
256             } else {
257                 level = (((level << 1) + 1) * qscale *
258                          ((int) (quant_matrix[j]))) >> 4;
259             }
260             block[j] = level;
261             sum+=level;
262         }
263     }
264     block[63]^=sum&1;
265 }
266
267 static void dct_unquantize_h263_intra_c(MpegEncContext *s,
268                                   int16_t *block, int n, int qscale)
269 {
270     int i, level, qmul, qadd;
271     int nCoeffs;
272
273     assert(s->block_last_index[n]>=0);
274
275     qmul = qscale << 1;
276
277     if (!s->h263_aic) {
278         if (n < 4)
279             block[0] = block[0] * s->y_dc_scale;
280         else
281             block[0] = block[0] * s->c_dc_scale;
282         qadd = (qscale - 1) | 1;
283     }else{
284         qadd = 0;
285     }
286     if(s->ac_pred)
287         nCoeffs=63;
288     else
289         nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
290
291     for(i=1; i<=nCoeffs; i++) {
292         level = block[i];
293         if (level) {
294             if (level < 0) {
295                 level = level * qmul - qadd;
296             } else {
297                 level = level * qmul + qadd;
298             }
299             block[i] = level;
300         }
301     }
302 }
303
304 static void dct_unquantize_h263_inter_c(MpegEncContext *s,
305                                   int16_t *block, int n, int qscale)
306 {
307     int i, level, qmul, qadd;
308     int nCoeffs;
309
310     assert(s->block_last_index[n]>=0);
311
312     qadd = (qscale - 1) | 1;
313     qmul = qscale << 1;
314
315     nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
316
317     for(i=0; i<=nCoeffs; i++) {
318         level = block[i];
319         if (level) {
320             if (level < 0) {
321                 level = level * qmul - qadd;
322             } else {
323                 level = level * qmul + qadd;
324             }
325             block[i] = level;
326         }
327     }
328 }
329
330 static void mpeg_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
331                               int (*mv)[2][4][2],
332                               int mb_x, int mb_y, int mb_intra, int mb_skipped)
333 {
334     MpegEncContext *s = opaque;
335
336     s->mv_dir     = mv_dir;
337     s->mv_type    = mv_type;
338     s->mb_intra   = mb_intra;
339     s->mb_skipped = mb_skipped;
340     s->mb_x       = mb_x;
341     s->mb_y       = mb_y;
342     memcpy(s->mv, mv, sizeof(*mv));
343
344     ff_init_block_index(s);
345     ff_update_block_index(s);
346
347     s->dsp.clear_blocks(s->block[0]);
348
349     s->dest[0] = s->current_picture.f.data[0] + (s->mb_y *  16                       * s->linesize)   + s->mb_x *  16;
350     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);
351     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);
352
353     assert(ref == 0);
354     ff_MPV_decode_mb(s, s->block);
355 }
356
357 /* init common dct for both encoder and decoder */
358 av_cold int ff_dct_common_init(MpegEncContext *s)
359 {
360     ff_dsputil_init(&s->dsp, s->avctx);
361     ff_hpeldsp_init(&s->hdsp, s->avctx->flags);
362     ff_videodsp_init(&s->vdsp, s->avctx->bits_per_raw_sample);
363
364     s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_c;
365     s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_c;
366     s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_c;
367     s->dct_unquantize_mpeg1_inter = dct_unquantize_mpeg1_inter_c;
368     s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_c;
369     if (s->flags & CODEC_FLAG_BITEXACT)
370         s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_bitexact;
371     s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_c;
372
373     if (ARCH_ARM)
374         ff_MPV_common_init_arm(s);
375     if (ARCH_PPC)
376         ff_MPV_common_init_ppc(s);
377     if (ARCH_X86)
378         ff_MPV_common_init_x86(s);
379
380     /* load & permutate scantables
381      * note: only wmv uses different ones
382      */
383     if (s->alternate_scan) {
384         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
385         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
386     } else {
387         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
388         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
389     }
390     ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
391     ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
392
393     return 0;
394 }
395
396 static int frame_size_alloc(MpegEncContext *s, int linesize)
397 {
398     int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
399
400     // edge emu needs blocksize + filter length - 1
401     // (= 17x17 for  halfpel / 21x21 for  h264)
402     // VC1 computes luma and chroma simultaneously and needs 19X19 + 9x9
403     // at uvlinesize. It supports only YUV420 so 24x24 is enough
404     // linesize * interlaced * MBsize
405     FF_ALLOCZ_OR_GOTO(s->avctx, s->edge_emu_buffer, alloc_size * 2 * 24,
406                       fail);
407
408     FF_ALLOCZ_OR_GOTO(s->avctx, s->me.scratchpad, alloc_size * 2 * 16 * 3,
409                       fail)
410     s->me.temp         = s->me.scratchpad;
411     s->rd_scratchpad   = s->me.scratchpad;
412     s->b_scratchpad    = s->me.scratchpad;
413     s->obmc_scratchpad = s->me.scratchpad + 16;
414
415     return 0;
416 fail:
417     av_freep(&s->edge_emu_buffer);
418     return AVERROR(ENOMEM);
419 }
420
421 /**
422  * Allocate a frame buffer
423  */
424 static int alloc_frame_buffer(MpegEncContext *s, Picture *pic)
425 {
426     int edges_needed = av_codec_is_encoder(s->avctx->codec);
427     int r, ret;
428
429     pic->tf.f = &pic->f;
430     if (s->codec_id != AV_CODEC_ID_WMV3IMAGE &&
431         s->codec_id != AV_CODEC_ID_VC1IMAGE  &&
432         s->codec_id != AV_CODEC_ID_MSS2) {
433         if (edges_needed) {
434             pic->f.width  = s->avctx->width  + 2 * EDGE_WIDTH;
435             pic->f.height = s->avctx->height + 2 * EDGE_WIDTH;
436         }
437
438         r = ff_thread_get_buffer(s->avctx, &pic->tf,
439                                  pic->reference ? AV_GET_BUFFER_FLAG_REF : 0);
440     } else {
441         pic->f.width  = s->avctx->width;
442         pic->f.height = s->avctx->height;
443         pic->f.format = s->avctx->pix_fmt;
444         r = avcodec_default_get_buffer2(s->avctx, &pic->f, 0);
445     }
446
447     if (r < 0 || !pic->f.buf[0]) {
448         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (%d %p)\n",
449                r, pic->f.data[0]);
450         return -1;
451     }
452
453     if (edges_needed) {
454         int i;
455         for (i = 0; pic->f.data[i]; i++) {
456             int offset = (EDGE_WIDTH >> (i ? s->chroma_y_shift : 0)) *
457                          pic->f.linesize[i] +
458                          (EDGE_WIDTH >> (i ? s->chroma_x_shift : 0));
459             pic->f.data[i] += offset;
460         }
461         pic->f.width  = s->avctx->width;
462         pic->f.height = s->avctx->height;
463     }
464
465     if (s->avctx->hwaccel) {
466         assert(!pic->hwaccel_picture_private);
467         if (s->avctx->hwaccel->priv_data_size) {
468             pic->hwaccel_priv_buf = av_buffer_allocz(s->avctx->hwaccel->priv_data_size);
469             if (!pic->hwaccel_priv_buf) {
470                 av_log(s->avctx, AV_LOG_ERROR, "alloc_frame_buffer() failed (hwaccel private data allocation)\n");
471                 return -1;
472             }
473             pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
474         }
475     }
476
477     if (s->linesize && (s->linesize   != pic->f.linesize[0] ||
478                         s->uvlinesize != pic->f.linesize[1])) {
479         av_log(s->avctx, AV_LOG_ERROR,
480                "get_buffer() failed (stride changed)\n");
481         ff_mpeg_unref_picture(s, pic);
482         return -1;
483     }
484
485     if (pic->f.linesize[1] != pic->f.linesize[2]) {
486         av_log(s->avctx, AV_LOG_ERROR,
487                "get_buffer() failed (uv stride mismatch)\n");
488         ff_mpeg_unref_picture(s, pic);
489         return -1;
490     }
491
492     if (!s->edge_emu_buffer &&
493         (ret = frame_size_alloc(s, pic->f.linesize[0])) < 0) {
494         av_log(s->avctx, AV_LOG_ERROR,
495                "get_buffer() failed to allocate context scratch buffers.\n");
496         ff_mpeg_unref_picture(s, pic);
497         return ret;
498     }
499
500     return 0;
501 }
502
503 void ff_free_picture_tables(Picture *pic)
504 {
505     int i;
506
507     av_buffer_unref(&pic->mb_var_buf);
508     av_buffer_unref(&pic->mc_mb_var_buf);
509     av_buffer_unref(&pic->mb_mean_buf);
510     av_buffer_unref(&pic->mbskip_table_buf);
511     av_buffer_unref(&pic->qscale_table_buf);
512     av_buffer_unref(&pic->mb_type_buf);
513
514     for (i = 0; i < 2; i++) {
515         av_buffer_unref(&pic->motion_val_buf[i]);
516         av_buffer_unref(&pic->ref_index_buf[i]);
517     }
518 }
519
520 static int alloc_picture_tables(MpegEncContext *s, Picture *pic)
521 {
522     const int big_mb_num    = s->mb_stride * (s->mb_height + 1) + 1;
523     const int mb_array_size = s->mb_stride * s->mb_height;
524     const int b8_array_size = s->b8_stride * s->mb_height * 2;
525     int i;
526
527
528     pic->mbskip_table_buf = av_buffer_allocz(mb_array_size + 2);
529     pic->qscale_table_buf = av_buffer_allocz(big_mb_num + s->mb_stride);
530     pic->mb_type_buf      = av_buffer_allocz((big_mb_num + s->mb_stride) *
531                                              sizeof(uint32_t));
532     if (!pic->mbskip_table_buf || !pic->qscale_table_buf || !pic->mb_type_buf)
533         return AVERROR(ENOMEM);
534
535     if (s->encoding) {
536         pic->mb_var_buf    = av_buffer_allocz(mb_array_size * sizeof(int16_t));
537         pic->mc_mb_var_buf = av_buffer_allocz(mb_array_size * sizeof(int16_t));
538         pic->mb_mean_buf   = av_buffer_allocz(mb_array_size);
539         if (!pic->mb_var_buf || !pic->mc_mb_var_buf || !pic->mb_mean_buf)
540             return AVERROR(ENOMEM);
541     }
542
543     if (s->out_format == FMT_H263 || s->encoding) {
544         int mv_size        = 2 * (b8_array_size + 4) * sizeof(int16_t);
545         int ref_index_size = 4 * mb_array_size;
546
547         for (i = 0; mv_size && i < 2; i++) {
548             pic->motion_val_buf[i] = av_buffer_allocz(mv_size);
549             pic->ref_index_buf[i]  = av_buffer_allocz(ref_index_size);
550             if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
551                 return AVERROR(ENOMEM);
552         }
553     }
554
555     return 0;
556 }
557
558 static int make_tables_writable(Picture *pic)
559 {
560     int ret, i;
561 #define MAKE_WRITABLE(table) \
562 do {\
563     if (pic->table &&\
564        (ret = av_buffer_make_writable(&pic->table)) < 0)\
565     return ret;\
566 } while (0)
567
568     MAKE_WRITABLE(mb_var_buf);
569     MAKE_WRITABLE(mc_mb_var_buf);
570     MAKE_WRITABLE(mb_mean_buf);
571     MAKE_WRITABLE(mbskip_table_buf);
572     MAKE_WRITABLE(qscale_table_buf);
573     MAKE_WRITABLE(mb_type_buf);
574
575     for (i = 0; i < 2; i++) {
576         MAKE_WRITABLE(motion_val_buf[i]);
577         MAKE_WRITABLE(ref_index_buf[i]);
578     }
579
580     return 0;
581 }
582
583 /**
584  * Allocate a Picture.
585  * The pixels are allocated/set by calling get_buffer() if shared = 0
586  */
587 int ff_alloc_picture(MpegEncContext *s, Picture *pic, int shared)
588 {
589     int i, ret;
590
591     if (shared) {
592         assert(pic->f.data[0]);
593         pic->shared = 1;
594     } else {
595         assert(!pic->f.buf[0]);
596
597         if (alloc_frame_buffer(s, pic) < 0)
598             return -1;
599
600         s->linesize   = pic->f.linesize[0];
601         s->uvlinesize = pic->f.linesize[1];
602     }
603
604     if (!pic->qscale_table_buf)
605         ret = alloc_picture_tables(s, pic);
606     else
607         ret = make_tables_writable(pic);
608     if (ret < 0)
609         goto fail;
610
611     if (s->encoding) {
612         pic->mb_var    = (uint16_t*)pic->mb_var_buf->data;
613         pic->mc_mb_var = (uint16_t*)pic->mc_mb_var_buf->data;
614         pic->mb_mean   = pic->mb_mean_buf->data;
615     }
616
617     pic->mbskip_table = pic->mbskip_table_buf->data;
618     pic->qscale_table = pic->qscale_table_buf->data + 2 * s->mb_stride + 1;
619     pic->mb_type      = (uint32_t*)pic->mb_type_buf->data + 2 * s->mb_stride + 1;
620
621     if (pic->motion_val_buf[0]) {
622         for (i = 0; i < 2; i++) {
623             pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
624             pic->ref_index[i]  = pic->ref_index_buf[i]->data;
625         }
626     }
627
628     return 0;
629 fail:
630     av_log(s->avctx, AV_LOG_ERROR, "Error allocating a picture.\n");
631     ff_mpeg_unref_picture(s, pic);
632     ff_free_picture_tables(pic);
633     return AVERROR(ENOMEM);
634 }
635
636 /**
637  * Deallocate a picture.
638  */
639 void ff_mpeg_unref_picture(MpegEncContext *s, Picture *pic)
640 {
641     int off = offsetof(Picture, mb_mean) + sizeof(pic->mb_mean);
642
643     pic->tf.f = &pic->f;
644     /* WM Image / Screen codecs allocate internal buffers with different
645      * dimensions / colorspaces; ignore user-defined callbacks for these. */
646     if (s->codec_id != AV_CODEC_ID_WMV3IMAGE &&
647         s->codec_id != AV_CODEC_ID_VC1IMAGE  &&
648         s->codec_id != AV_CODEC_ID_MSS2)
649         ff_thread_release_buffer(s->avctx, &pic->tf);
650     else
651         av_frame_unref(&pic->f);
652
653     av_buffer_unref(&pic->hwaccel_priv_buf);
654
655     if (pic->needs_realloc)
656         ff_free_picture_tables(pic);
657
658     memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
659 }
660
661 static int update_picture_tables(Picture *dst, Picture *src)
662 {
663      int i;
664
665 #define UPDATE_TABLE(table)\
666 do {\
667     if (src->table &&\
668         (!dst->table || dst->table->buffer != src->table->buffer)) {\
669         av_buffer_unref(&dst->table);\
670         dst->table = av_buffer_ref(src->table);\
671         if (!dst->table) {\
672             ff_free_picture_tables(dst);\
673             return AVERROR(ENOMEM);\
674         }\
675     }\
676 } while (0)
677
678     UPDATE_TABLE(mb_var_buf);
679     UPDATE_TABLE(mc_mb_var_buf);
680     UPDATE_TABLE(mb_mean_buf);
681     UPDATE_TABLE(mbskip_table_buf);
682     UPDATE_TABLE(qscale_table_buf);
683     UPDATE_TABLE(mb_type_buf);
684     for (i = 0; i < 2; i++) {
685         UPDATE_TABLE(motion_val_buf[i]);
686         UPDATE_TABLE(ref_index_buf[i]);
687     }
688
689     dst->mb_var        = src->mb_var;
690     dst->mc_mb_var     = src->mc_mb_var;
691     dst->mb_mean       = src->mb_mean;
692     dst->mbskip_table  = src->mbskip_table;
693     dst->qscale_table  = src->qscale_table;
694     dst->mb_type       = src->mb_type;
695     for (i = 0; i < 2; i++) {
696         dst->motion_val[i] = src->motion_val[i];
697         dst->ref_index[i]  = src->ref_index[i];
698     }
699
700     return 0;
701 }
702
703 int ff_mpeg_ref_picture(MpegEncContext *s, Picture *dst, Picture *src)
704 {
705     int ret;
706
707     av_assert0(!dst->f.buf[0]);
708     av_assert0(src->f.buf[0]);
709
710     src->tf.f = &src->f;
711     dst->tf.f = &dst->f;
712     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
713     if (ret < 0)
714         goto fail;
715
716     ret = update_picture_tables(dst, src);
717     if (ret < 0)
718         goto fail;
719
720     if (src->hwaccel_picture_private) {
721         dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
722         if (!dst->hwaccel_priv_buf)
723             goto fail;
724         dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
725     }
726
727     dst->field_picture           = src->field_picture;
728     dst->mb_var_sum              = src->mb_var_sum;
729     dst->mc_mb_var_sum           = src->mc_mb_var_sum;
730     dst->b_frame_score           = src->b_frame_score;
731     dst->needs_realloc           = src->needs_realloc;
732     dst->reference               = src->reference;
733     dst->shared                  = src->shared;
734
735     return 0;
736 fail:
737     ff_mpeg_unref_picture(s, dst);
738     return ret;
739 }
740
741 static void exchange_uv(MpegEncContext *s)
742 {
743     int16_t (*tmp)[64];
744
745     tmp           = s->pblocks[4];
746     s->pblocks[4] = s->pblocks[5];
747     s->pblocks[5] = tmp;
748 }
749
750 static int init_duplicate_context(MpegEncContext *s)
751 {
752     int y_size = s->b8_stride * (2 * s->mb_height + 1);
753     int c_size = s->mb_stride * (s->mb_height + 1);
754     int yc_size = y_size + 2 * c_size;
755     int i;
756
757     s->edge_emu_buffer =
758     s->me.scratchpad   =
759     s->me.temp         =
760     s->rd_scratchpad   =
761     s->b_scratchpad    =
762     s->obmc_scratchpad = NULL;
763
764     if (s->encoding) {
765         FF_ALLOCZ_OR_GOTO(s->avctx, s->me.map,
766                           ME_MAP_SIZE * sizeof(uint32_t), fail)
767         FF_ALLOCZ_OR_GOTO(s->avctx, s->me.score_map,
768                           ME_MAP_SIZE * sizeof(uint32_t), fail)
769         if (s->avctx->noise_reduction) {
770             FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_error_sum,
771                               2 * 64 * sizeof(int), fail)
772         }
773     }
774     FF_ALLOCZ_OR_GOTO(s->avctx, s->blocks, 64 * 12 * 2 * sizeof(int16_t), fail)
775     s->block = s->blocks[0];
776
777     for (i = 0; i < 12; i++) {
778         s->pblocks[i] = &s->block[i];
779     }
780     if (s->avctx->codec_tag == AV_RL32("VCR2"))
781         exchange_uv(s);
782
783     if (s->out_format == FMT_H263) {
784         /* ac values */
785         FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_val_base,
786                           yc_size * sizeof(int16_t) * 16, fail);
787         s->ac_val[0] = s->ac_val_base + s->b8_stride + 1;
788         s->ac_val[1] = s->ac_val_base + y_size + s->mb_stride + 1;
789         s->ac_val[2] = s->ac_val[1] + c_size;
790     }
791
792     return 0;
793 fail:
794     return -1; // free() through ff_MPV_common_end()
795 }
796
797 static void free_duplicate_context(MpegEncContext *s)
798 {
799     if (s == NULL)
800         return;
801
802     av_freep(&s->edge_emu_buffer);
803     av_freep(&s->me.scratchpad);
804     s->me.temp =
805     s->rd_scratchpad =
806     s->b_scratchpad =
807     s->obmc_scratchpad = NULL;
808
809     av_freep(&s->dct_error_sum);
810     av_freep(&s->me.map);
811     av_freep(&s->me.score_map);
812     av_freep(&s->blocks);
813     av_freep(&s->ac_val_base);
814     s->block = NULL;
815 }
816
817 static void backup_duplicate_context(MpegEncContext *bak, MpegEncContext *src)
818 {
819 #define COPY(a) bak->a = src->a
820     COPY(edge_emu_buffer);
821     COPY(me.scratchpad);
822     COPY(me.temp);
823     COPY(rd_scratchpad);
824     COPY(b_scratchpad);
825     COPY(obmc_scratchpad);
826     COPY(me.map);
827     COPY(me.score_map);
828     COPY(blocks);
829     COPY(block);
830     COPY(start_mb_y);
831     COPY(end_mb_y);
832     COPY(me.map_generation);
833     COPY(pb);
834     COPY(dct_error_sum);
835     COPY(dct_count[0]);
836     COPY(dct_count[1]);
837     COPY(ac_val_base);
838     COPY(ac_val[0]);
839     COPY(ac_val[1]);
840     COPY(ac_val[2]);
841 #undef COPY
842 }
843
844 int ff_update_duplicate_context(MpegEncContext *dst, MpegEncContext *src)
845 {
846     MpegEncContext bak;
847     int i, ret;
848     // FIXME copy only needed parts
849     // START_TIMER
850     backup_duplicate_context(&bak, dst);
851     memcpy(dst, src, sizeof(MpegEncContext));
852     backup_duplicate_context(dst, &bak);
853     for (i = 0; i < 12; i++) {
854         dst->pblocks[i] = &dst->block[i];
855     }
856     if (dst->avctx->codec_tag == AV_RL32("VCR2"))
857         exchange_uv(dst);
858     if (!dst->edge_emu_buffer &&
859         (ret = frame_size_alloc(dst, dst->linesize)) < 0) {
860         av_log(dst->avctx, AV_LOG_ERROR, "failed to allocate context "
861                "scratch buffers.\n");
862         return ret;
863     }
864     // STOP_TIMER("update_duplicate_context")
865     // about 10k cycles / 0.01 sec for  1000frames on 1ghz with 2 threads
866     return 0;
867 }
868
869 int ff_mpeg_update_thread_context(AVCodecContext *dst,
870                                   const AVCodecContext *src)
871 {
872     int i, ret;
873     MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;
874
875     if (dst == src || !s1->context_initialized)
876         return 0;
877
878     // FIXME can parameters change on I-frames?
879     // in that case dst may need a reinit
880     if (!s->context_initialized) {
881         memcpy(s, s1, sizeof(MpegEncContext));
882
883         s->avctx                 = dst;
884         s->bitstream_buffer      = NULL;
885         s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;
886
887         ff_MPV_common_init(s);
888     }
889
890     if (s->height != s1->height || s->width != s1->width || s->context_reinit) {
891         int err;
892         s->context_reinit = 0;
893         s->height = s1->height;
894         s->width  = s1->width;
895         if ((err = ff_MPV_common_frame_size_change(s)) < 0)
896             return err;
897     }
898
899     s->avctx->coded_height  = s1->avctx->coded_height;
900     s->avctx->coded_width   = s1->avctx->coded_width;
901     s->avctx->width         = s1->avctx->width;
902     s->avctx->height        = s1->avctx->height;
903
904     s->coded_picture_number = s1->coded_picture_number;
905     s->picture_number       = s1->picture_number;
906
907     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
908         ff_mpeg_unref_picture(s, &s->picture[i]);
909         if (s1->picture[i].f.buf[0] &&
910             (ret = ff_mpeg_ref_picture(s, &s->picture[i], &s1->picture[i])) < 0)
911             return ret;
912     }
913
914 #define UPDATE_PICTURE(pic)\
915 do {\
916     ff_mpeg_unref_picture(s, &s->pic);\
917     if (s1->pic.f.buf[0])\
918         ret = ff_mpeg_ref_picture(s, &s->pic, &s1->pic);\
919     else\
920         ret = update_picture_tables(&s->pic, &s1->pic);\
921     if (ret < 0)\
922         return ret;\
923 } while (0)
924
925     UPDATE_PICTURE(current_picture);
926     UPDATE_PICTURE(last_picture);
927     UPDATE_PICTURE(next_picture);
928
929     s->last_picture_ptr    = REBASE_PICTURE(s1->last_picture_ptr,    s, s1);
930     s->current_picture_ptr = REBASE_PICTURE(s1->current_picture_ptr, s, s1);
931     s->next_picture_ptr    = REBASE_PICTURE(s1->next_picture_ptr,    s, s1);
932
933     // Error/bug resilience
934     s->next_p_frame_damaged = s1->next_p_frame_damaged;
935     s->workaround_bugs      = s1->workaround_bugs;
936
937     // MPEG4 timing info
938     memcpy(&s->last_time_base, &s1->last_time_base,
939            (char *) &s1->pb_field_time + sizeof(s1->pb_field_time) -
940            (char *) &s1->last_time_base);
941
942     // B-frame info
943     s->max_b_frames = s1->max_b_frames;
944     s->low_delay    = s1->low_delay;
945     s->droppable    = s1->droppable;
946
947     // DivX handling (doesn't work)
948     s->divx_packed  = s1->divx_packed;
949
950     if (s1->bitstream_buffer) {
951         if (s1->bitstream_buffer_size +
952             FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size)
953             av_fast_malloc(&s->bitstream_buffer,
954                            &s->allocated_bitstream_buffer_size,
955                            s1->allocated_bitstream_buffer_size);
956             s->bitstream_buffer_size = s1->bitstream_buffer_size;
957         memcpy(s->bitstream_buffer, s1->bitstream_buffer,
958                s1->bitstream_buffer_size);
959         memset(s->bitstream_buffer + s->bitstream_buffer_size, 0,
960                FF_INPUT_BUFFER_PADDING_SIZE);
961     }
962
963     // linesize dependend scratch buffer allocation
964     if (!s->edge_emu_buffer)
965         if (s1->linesize) {
966             if (frame_size_alloc(s, s1->linesize) < 0) {
967                 av_log(s->avctx, AV_LOG_ERROR, "Failed to allocate context "
968                        "scratch buffers.\n");
969                 return AVERROR(ENOMEM);
970             }
971         } else {
972             av_log(s->avctx, AV_LOG_ERROR, "Context scratch buffers could not "
973                    "be allocated due to unknown size.\n");
974             return AVERROR_BUG;
975         }
976
977     // MPEG2/interlacing info
978     memcpy(&s->progressive_sequence, &s1->progressive_sequence,
979            (char *) &s1->rtp_mode - (char *) &s1->progressive_sequence);
980
981     if (!s1->first_field) {
982         s->last_pict_type = s1->pict_type;
983         if (s1->current_picture_ptr)
984             s->last_lambda_for[s1->pict_type] = s1->current_picture_ptr->f.quality;
985     }
986
987     return 0;
988 }
989
990 /**
991  * Set the given MpegEncContext to common defaults
992  * (same for encoding and decoding).
993  * The changed fields will not depend upon the
994  * prior state of the MpegEncContext.
995  */
996 void ff_MPV_common_defaults(MpegEncContext *s)
997 {
998     s->y_dc_scale_table      =
999     s->c_dc_scale_table      = ff_mpeg1_dc_scale_table;
1000     s->chroma_qscale_table   = ff_default_chroma_qscale_table;
1001     s->progressive_frame     = 1;
1002     s->progressive_sequence  = 1;
1003     s->picture_structure     = PICT_FRAME;
1004
1005     s->coded_picture_number  = 0;
1006     s->picture_number        = 0;
1007
1008     s->f_code                = 1;
1009     s->b_code                = 1;
1010
1011     s->slice_context_count   = 1;
1012 }
1013
1014 /**
1015  * Set the given MpegEncContext to defaults for decoding.
1016  * the changed fields will not depend upon
1017  * the prior state of the MpegEncContext.
1018  */
1019 void ff_MPV_decode_defaults(MpegEncContext *s)
1020 {
1021     ff_MPV_common_defaults(s);
1022 }
1023
1024 static int init_er(MpegEncContext *s)
1025 {
1026     ERContext *er = &s->er;
1027     int mb_array_size = s->mb_height * s->mb_stride;
1028     int i;
1029
1030     er->avctx       = s->avctx;
1031     er->dsp         = &s->dsp;
1032
1033     er->mb_index2xy = s->mb_index2xy;
1034     er->mb_num      = s->mb_num;
1035     er->mb_width    = s->mb_width;
1036     er->mb_height   = s->mb_height;
1037     er->mb_stride   = s->mb_stride;
1038     er->b8_stride   = s->b8_stride;
1039
1040     er->er_temp_buffer     = av_malloc(s->mb_height * s->mb_stride);
1041     er->error_status_table = av_mallocz(mb_array_size);
1042     if (!er->er_temp_buffer || !er->error_status_table)
1043         goto fail;
1044
1045     er->mbskip_table  = s->mbskip_table;
1046     er->mbintra_table = s->mbintra_table;
1047
1048     for (i = 0; i < FF_ARRAY_ELEMS(s->dc_val); i++)
1049         er->dc_val[i] = s->dc_val[i];
1050
1051     er->decode_mb = mpeg_er_decode_mb;
1052     er->opaque    = s;
1053
1054     return 0;
1055 fail:
1056     av_freep(&er->er_temp_buffer);
1057     av_freep(&er->error_status_table);
1058     return AVERROR(ENOMEM);
1059 }
1060
1061 /**
1062  * Initialize and allocates MpegEncContext fields dependent on the resolution.
1063  */
1064 static int init_context_frame(MpegEncContext *s)
1065 {
1066     int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y;
1067
1068     s->mb_width   = (s->width + 15) / 16;
1069     s->mb_stride  = s->mb_width + 1;
1070     s->b8_stride  = s->mb_width * 2 + 1;
1071     s->b4_stride  = s->mb_width * 4 + 1;
1072     mb_array_size = s->mb_height * s->mb_stride;
1073     mv_table_size = (s->mb_height + 2) * s->mb_stride + 1;
1074
1075     /* set default edge pos, will be overriden
1076      * in decode_header if needed */
1077     s->h_edge_pos = s->mb_width * 16;
1078     s->v_edge_pos = s->mb_height * 16;
1079
1080     s->mb_num     = s->mb_width * s->mb_height;
1081
1082     s->block_wrap[0] =
1083     s->block_wrap[1] =
1084     s->block_wrap[2] =
1085     s->block_wrap[3] = s->b8_stride;
1086     s->block_wrap[4] =
1087     s->block_wrap[5] = s->mb_stride;
1088
1089     y_size  = s->b8_stride * (2 * s->mb_height + 1);
1090     c_size  = s->mb_stride * (s->mb_height + 1);
1091     yc_size = y_size + 2   * c_size;
1092
1093     FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_index2xy, (s->mb_num + 1) * sizeof(int),
1094                       fail); // error ressilience code looks cleaner with this
1095     for (y = 0; y < s->mb_height; y++)
1096         for (x = 0; x < s->mb_width; x++)
1097             s->mb_index2xy[x + y * s->mb_width] = x + y * s->mb_stride;
1098
1099     s->mb_index2xy[s->mb_height * s->mb_width] =
1100         (s->mb_height - 1) * s->mb_stride + s->mb_width; // FIXME really needed?
1101
1102     if (s->encoding) {
1103         /* Allocate MV tables */
1104         FF_ALLOCZ_OR_GOTO(s->avctx, s->p_mv_table_base,
1105                           mv_table_size * 2 * sizeof(int16_t), fail);
1106         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_forw_mv_table_base,
1107                           mv_table_size * 2 * sizeof(int16_t), fail);
1108         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_back_mv_table_base,
1109                           mv_table_size * 2 * sizeof(int16_t), fail);
1110         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_forw_mv_table_base,
1111                           mv_table_size * 2 * sizeof(int16_t), fail);
1112         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_back_mv_table_base,
1113                           mv_table_size * 2 * sizeof(int16_t), fail);
1114         FF_ALLOCZ_OR_GOTO(s->avctx, s->b_direct_mv_table_base,
1115                           mv_table_size * 2 * sizeof(int16_t), fail);
1116         s->p_mv_table            = s->p_mv_table_base + s->mb_stride + 1;
1117         s->b_forw_mv_table       = s->b_forw_mv_table_base + s->mb_stride + 1;
1118         s->b_back_mv_table       = s->b_back_mv_table_base + s->mb_stride + 1;
1119         s->b_bidir_forw_mv_table = s->b_bidir_forw_mv_table_base +
1120                                    s->mb_stride + 1;
1121         s->b_bidir_back_mv_table = s->b_bidir_back_mv_table_base +
1122                                    s->mb_stride + 1;
1123         s->b_direct_mv_table     = s->b_direct_mv_table_base + s->mb_stride + 1;
1124
1125         /* Allocate MB type table */
1126         FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_type, mb_array_size *
1127                           sizeof(uint16_t), fail); // needed for encoding
1128
1129         FF_ALLOCZ_OR_GOTO(s->avctx, s->lambda_table, mb_array_size *
1130                           sizeof(int), fail);
1131
1132         FF_ALLOC_OR_GOTO(s->avctx, s->cplx_tab,
1133                          mb_array_size * sizeof(float), fail);
1134         FF_ALLOC_OR_GOTO(s->avctx, s->bits_tab,
1135                          mb_array_size * sizeof(float), fail);
1136
1137     }
1138
1139     if (s->codec_id == AV_CODEC_ID_MPEG4 ||
1140         (s->flags & CODEC_FLAG_INTERLACED_ME)) {
1141         /* interlaced direct mode decoding tables */
1142         for (i = 0; i < 2; i++) {
1143             int j, k;
1144             for (j = 0; j < 2; j++) {
1145                 for (k = 0; k < 2; k++) {
1146                     FF_ALLOCZ_OR_GOTO(s->avctx,
1147                                       s->b_field_mv_table_base[i][j][k],
1148                                       mv_table_size * 2 * sizeof(int16_t),
1149                                       fail);
1150                     s->b_field_mv_table[i][j][k] = s->b_field_mv_table_base[i][j][k] +
1151                                                    s->mb_stride + 1;
1152                 }
1153                 FF_ALLOCZ_OR_GOTO(s->avctx, s->b_field_select_table [i][j],
1154                                   mb_array_size * 2 * sizeof(uint8_t), fail);
1155                 FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_mv_table_base[i][j],
1156                                   mv_table_size * 2 * sizeof(int16_t), fail);
1157                 s->p_field_mv_table[i][j] = s->p_field_mv_table_base[i][j]
1158                                             + s->mb_stride + 1;
1159             }
1160             FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_select_table[i],
1161                               mb_array_size * 2 * sizeof(uint8_t), fail);
1162         }
1163     }
1164     if (s->out_format == FMT_H263) {
1165         /* cbp values */
1166         FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size, fail);
1167         s->coded_block = s->coded_block_base + s->b8_stride + 1;
1168
1169         /* cbp, ac_pred, pred_dir */
1170         FF_ALLOCZ_OR_GOTO(s->avctx, s->cbp_table,
1171                           mb_array_size * sizeof(uint8_t), fail);
1172         FF_ALLOCZ_OR_GOTO(s->avctx, s->pred_dir_table,
1173                           mb_array_size * sizeof(uint8_t), fail);
1174     }
1175
1176     if (s->h263_pred || s->h263_plus || !s->encoding) {
1177         /* dc values */
1178         // MN: we need these for  error resilience of intra-frames
1179         FF_ALLOCZ_OR_GOTO(s->avctx, s->dc_val_base,
1180                           yc_size * sizeof(int16_t), fail);
1181         s->dc_val[0] = s->dc_val_base + s->b8_stride + 1;
1182         s->dc_val[1] = s->dc_val_base + y_size + s->mb_stride + 1;
1183         s->dc_val[2] = s->dc_val[1] + c_size;
1184         for (i = 0; i < yc_size; i++)
1185             s->dc_val_base[i] = 1024;
1186     }
1187
1188     /* which mb is a intra block */
1189     FF_ALLOCZ_OR_GOTO(s->avctx, s->mbintra_table, mb_array_size, fail);
1190     memset(s->mbintra_table, 1, mb_array_size);
1191
1192     /* init macroblock skip table */
1193     FF_ALLOCZ_OR_GOTO(s->avctx, s->mbskip_table, mb_array_size + 2, fail);
1194     // Note the + 1 is for  a quicker mpeg4 slice_end detection
1195
1196     return init_er(s);
1197 fail:
1198     return AVERROR(ENOMEM);
1199 }
1200
1201 /**
1202  * init common structure for both encoder and decoder.
1203  * this assumes that some variables like width/height are already set
1204  */
1205 av_cold int ff_MPV_common_init(MpegEncContext *s)
1206 {
1207     int i;
1208     int nb_slices = (HAVE_THREADS &&
1209                      s->avctx->active_thread_type & FF_THREAD_SLICE) ?
1210                     s->avctx->thread_count : 1;
1211
1212     if (s->encoding && s->avctx->slices)
1213         nb_slices = s->avctx->slices;
1214
1215     if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)
1216         s->mb_height = (s->height + 31) / 32 * 2;
1217     else
1218         s->mb_height = (s->height + 15) / 16;
1219
1220     if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
1221         av_log(s->avctx, AV_LOG_ERROR,
1222                "decoding to AV_PIX_FMT_NONE is not supported.\n");
1223         return -1;
1224     }
1225
1226     if (nb_slices > MAX_THREADS || (nb_slices > s->mb_height && s->mb_height)) {
1227         int max_slices;
1228         if (s->mb_height)
1229             max_slices = FFMIN(MAX_THREADS, s->mb_height);
1230         else
1231             max_slices = MAX_THREADS;
1232         av_log(s->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
1233                " reducing to %d\n", nb_slices, max_slices);
1234         nb_slices = max_slices;
1235     }
1236
1237     if ((s->width || s->height) &&
1238         av_image_check_size(s->width, s->height, 0, s->avctx))
1239         return -1;
1240
1241     ff_dct_common_init(s);
1242
1243     s->flags  = s->avctx->flags;
1244     s->flags2 = s->avctx->flags2;
1245
1246     /* set chroma shifts */
1247     av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
1248                                      &s->chroma_x_shift,
1249                                      &s->chroma_y_shift);
1250
1251     /* convert fourcc to upper case */
1252     s->codec_tag          = avpriv_toupper4(s->avctx->codec_tag);
1253
1254     s->stream_codec_tag   = avpriv_toupper4(s->avctx->stream_codec_tag);
1255
1256     FF_ALLOCZ_OR_GOTO(s->avctx, s->picture,
1257                       MAX_PICTURE_COUNT * sizeof(Picture), fail);
1258     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1259         av_frame_unref(&s->picture[i].f);
1260     }
1261     memset(&s->next_picture, 0, sizeof(s->next_picture));
1262     memset(&s->last_picture, 0, sizeof(s->last_picture));
1263     memset(&s->current_picture, 0, sizeof(s->current_picture));
1264     av_frame_unref(&s->next_picture.f);
1265     av_frame_unref(&s->last_picture.f);
1266     av_frame_unref(&s->current_picture.f);
1267
1268     if (s->width && s->height) {
1269         if (init_context_frame(s))
1270             goto fail;
1271
1272         s->parse_context.state = -1;
1273     }
1274
1275     s->context_initialized = 1;
1276     s->thread_context[0]   = s;
1277
1278     if (s->width && s->height) {
1279         if (nb_slices > 1) {
1280             for (i = 1; i < nb_slices; i++) {
1281                 s->thread_context[i] = av_malloc(sizeof(MpegEncContext));
1282                 memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
1283             }
1284
1285             for (i = 0; i < nb_slices; i++) {
1286                 if (init_duplicate_context(s->thread_context[i]) < 0)
1287                     goto fail;
1288                     s->thread_context[i]->start_mb_y =
1289                         (s->mb_height * (i) + nb_slices / 2) / nb_slices;
1290                     s->thread_context[i]->end_mb_y   =
1291                         (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
1292             }
1293         } else {
1294             if (init_duplicate_context(s) < 0)
1295                 goto fail;
1296             s->start_mb_y = 0;
1297             s->end_mb_y   = s->mb_height;
1298         }
1299         s->slice_context_count = nb_slices;
1300     }
1301
1302     return 0;
1303  fail:
1304     ff_MPV_common_end(s);
1305     return -1;
1306 }
1307
1308 /**
1309  * Frees and resets MpegEncContext fields depending on the resolution.
1310  * Is used during resolution changes to avoid a full reinitialization of the
1311  * codec.
1312  */
1313 static int free_context_frame(MpegEncContext *s)
1314 {
1315     int i, j, k;
1316
1317     av_freep(&s->mb_type);
1318     av_freep(&s->p_mv_table_base);
1319     av_freep(&s->b_forw_mv_table_base);
1320     av_freep(&s->b_back_mv_table_base);
1321     av_freep(&s->b_bidir_forw_mv_table_base);
1322     av_freep(&s->b_bidir_back_mv_table_base);
1323     av_freep(&s->b_direct_mv_table_base);
1324     s->p_mv_table            = NULL;
1325     s->b_forw_mv_table       = NULL;
1326     s->b_back_mv_table       = NULL;
1327     s->b_bidir_forw_mv_table = NULL;
1328     s->b_bidir_back_mv_table = NULL;
1329     s->b_direct_mv_table     = NULL;
1330     for (i = 0; i < 2; i++) {
1331         for (j = 0; j < 2; j++) {
1332             for (k = 0; k < 2; k++) {
1333                 av_freep(&s->b_field_mv_table_base[i][j][k]);
1334                 s->b_field_mv_table[i][j][k] = NULL;
1335             }
1336             av_freep(&s->b_field_select_table[i][j]);
1337             av_freep(&s->p_field_mv_table_base[i][j]);
1338             s->p_field_mv_table[i][j] = NULL;
1339         }
1340         av_freep(&s->p_field_select_table[i]);
1341     }
1342
1343     av_freep(&s->dc_val_base);
1344     av_freep(&s->coded_block_base);
1345     av_freep(&s->mbintra_table);
1346     av_freep(&s->cbp_table);
1347     av_freep(&s->pred_dir_table);
1348
1349     av_freep(&s->mbskip_table);
1350
1351     av_freep(&s->er.error_status_table);
1352     av_freep(&s->er.er_temp_buffer);
1353     av_freep(&s->mb_index2xy);
1354     av_freep(&s->lambda_table);
1355     av_freep(&s->cplx_tab);
1356     av_freep(&s->bits_tab);
1357
1358     s->linesize = s->uvlinesize = 0;
1359
1360     return 0;
1361 }
1362
1363 int ff_MPV_common_frame_size_change(MpegEncContext *s)
1364 {
1365     int i, err = 0;
1366
1367     if (s->slice_context_count > 1) {
1368         for (i = 0; i < s->slice_context_count; i++) {
1369             free_duplicate_context(s->thread_context[i]);
1370         }
1371         for (i = 1; i < s->slice_context_count; i++) {
1372             av_freep(&s->thread_context[i]);
1373         }
1374     } else
1375         free_duplicate_context(s);
1376
1377     if ((err = free_context_frame(s)) < 0)
1378         return err;
1379
1380     if (s->picture)
1381         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1382                 s->picture[i].needs_realloc = 1;
1383         }
1384
1385     s->last_picture_ptr         =
1386     s->next_picture_ptr         =
1387     s->current_picture_ptr      = NULL;
1388
1389     // init
1390     if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)
1391         s->mb_height = (s->height + 31) / 32 * 2;
1392     else
1393         s->mb_height = (s->height + 15) / 16;
1394
1395     if ((s->width || s->height) &&
1396         av_image_check_size(s->width, s->height, 0, s->avctx))
1397         return AVERROR_INVALIDDATA;
1398
1399     if ((err = init_context_frame(s)))
1400         goto fail;
1401
1402     s->thread_context[0]   = s;
1403
1404     if (s->width && s->height) {
1405         int nb_slices = s->slice_context_count;
1406         if (nb_slices > 1) {
1407             for (i = 1; i < nb_slices; i++) {
1408                 s->thread_context[i] = av_malloc(sizeof(MpegEncContext));
1409                 memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
1410             }
1411
1412             for (i = 0; i < nb_slices; i++) {
1413                 if (init_duplicate_context(s->thread_context[i]) < 0)
1414                     goto fail;
1415                     s->thread_context[i]->start_mb_y =
1416                         (s->mb_height * (i) + nb_slices / 2) / nb_slices;
1417                     s->thread_context[i]->end_mb_y   =
1418                         (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
1419             }
1420         } else {
1421             if (init_duplicate_context(s) < 0)
1422                 goto fail;
1423             s->start_mb_y = 0;
1424             s->end_mb_y   = s->mb_height;
1425         }
1426         s->slice_context_count = nb_slices;
1427     }
1428
1429     return 0;
1430  fail:
1431     ff_MPV_common_end(s);
1432     return err;
1433 }
1434
1435 /* init common structure for both encoder and decoder */
1436 void ff_MPV_common_end(MpegEncContext *s)
1437 {
1438     int i;
1439
1440     if (s->slice_context_count > 1) {
1441         for (i = 0; i < s->slice_context_count; i++) {
1442             free_duplicate_context(s->thread_context[i]);
1443         }
1444         for (i = 1; i < s->slice_context_count; i++) {
1445             av_freep(&s->thread_context[i]);
1446         }
1447         s->slice_context_count = 1;
1448     } else free_duplicate_context(s);
1449
1450     av_freep(&s->parse_context.buffer);
1451     s->parse_context.buffer_size = 0;
1452
1453     av_freep(&s->bitstream_buffer);
1454     s->allocated_bitstream_buffer_size = 0;
1455
1456     if (s->picture) {
1457         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1458             ff_free_picture_tables(&s->picture[i]);
1459             ff_mpeg_unref_picture(s, &s->picture[i]);
1460         }
1461     }
1462     av_freep(&s->picture);
1463     ff_free_picture_tables(&s->last_picture);
1464     ff_mpeg_unref_picture(s, &s->last_picture);
1465     ff_free_picture_tables(&s->current_picture);
1466     ff_mpeg_unref_picture(s, &s->current_picture);
1467     ff_free_picture_tables(&s->next_picture);
1468     ff_mpeg_unref_picture(s, &s->next_picture);
1469
1470     free_context_frame(s);
1471
1472     s->context_initialized      = 0;
1473     s->last_picture_ptr         =
1474     s->next_picture_ptr         =
1475     s->current_picture_ptr      = NULL;
1476     s->linesize = s->uvlinesize = 0;
1477 }
1478
1479 av_cold void ff_init_rl(RLTable *rl,
1480                         uint8_t static_store[2][2 * MAX_RUN + MAX_LEVEL + 3])
1481 {
1482     int8_t  max_level[MAX_RUN + 1], max_run[MAX_LEVEL + 1];
1483     uint8_t index_run[MAX_RUN + 1];
1484     int last, run, level, start, end, i;
1485
1486     /* If table is static, we can quit if rl->max_level[0] is not NULL */
1487     if (static_store && rl->max_level[0])
1488         return;
1489
1490     /* compute max_level[], max_run[] and index_run[] */
1491     for (last = 0; last < 2; last++) {
1492         if (last == 0) {
1493             start = 0;
1494             end = rl->last;
1495         } else {
1496             start = rl->last;
1497             end = rl->n;
1498         }
1499
1500         memset(max_level, 0, MAX_RUN + 1);
1501         memset(max_run, 0, MAX_LEVEL + 1);
1502         memset(index_run, rl->n, MAX_RUN + 1);
1503         for (i = start; i < end; i++) {
1504             run   = rl->table_run[i];
1505             level = rl->table_level[i];
1506             if (index_run[run] == rl->n)
1507                 index_run[run] = i;
1508             if (level > max_level[run])
1509                 max_level[run] = level;
1510             if (run > max_run[level])
1511                 max_run[level] = run;
1512         }
1513         if (static_store)
1514             rl->max_level[last] = static_store[last];
1515         else
1516             rl->max_level[last] = av_malloc(MAX_RUN + 1);
1517         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
1518         if (static_store)
1519             rl->max_run[last]   = static_store[last] + MAX_RUN + 1;
1520         else
1521             rl->max_run[last]   = av_malloc(MAX_LEVEL + 1);
1522         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
1523         if (static_store)
1524             rl->index_run[last] = static_store[last] + MAX_RUN + MAX_LEVEL + 2;
1525         else
1526             rl->index_run[last] = av_malloc(MAX_RUN + 1);
1527         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
1528     }
1529 }
1530
1531 av_cold void ff_init_vlc_rl(RLTable *rl)
1532 {
1533     int i, q;
1534
1535     for (q = 0; q < 32; q++) {
1536         int qmul = q * 2;
1537         int qadd = (q - 1) | 1;
1538
1539         if (q == 0) {
1540             qmul = 1;
1541             qadd = 0;
1542         }
1543         for (i = 0; i < rl->vlc.table_size; i++) {
1544             int code = rl->vlc.table[i][0];
1545             int len  = rl->vlc.table[i][1];
1546             int level, run;
1547
1548             if (len == 0) { // illegal code
1549                 run   = 66;
1550                 level = MAX_LEVEL;
1551             } else if (len < 0) { // more bits needed
1552                 run   = 0;
1553                 level = code;
1554             } else {
1555                 if (code == rl->n) { // esc
1556                     run   = 66;
1557                     level =  0;
1558                 } else {
1559                     run   = rl->table_run[code] + 1;
1560                     level = rl->table_level[code] * qmul + qadd;
1561                     if (code >= rl->last) run += 192;
1562                 }
1563             }
1564             rl->rl_vlc[q][i].len   = len;
1565             rl->rl_vlc[q][i].level = level;
1566             rl->rl_vlc[q][i].run   = run;
1567         }
1568     }
1569 }
1570
1571 static void release_unused_pictures(MpegEncContext *s)
1572 {
1573     int i;
1574
1575     /* release non reference frames */
1576     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1577         if (!s->picture[i].reference)
1578             ff_mpeg_unref_picture(s, &s->picture[i]);
1579     }
1580 }
1581
1582 static inline int pic_is_unused(MpegEncContext *s, Picture *pic)
1583 {
1584     if (pic->f.buf[0] == NULL)
1585         return 1;
1586     if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
1587         return 1;
1588     return 0;
1589 }
1590
1591 static int find_unused_picture(MpegEncContext *s, int shared)
1592 {
1593     int i;
1594
1595     if (shared) {
1596         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1597             if (s->picture[i].f.buf[0] == NULL)
1598                 return i;
1599         }
1600     } else {
1601         for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1602             if (pic_is_unused(s, &s->picture[i]))
1603                 return i;
1604         }
1605     }
1606
1607     return AVERROR_INVALIDDATA;
1608 }
1609
1610 int ff_find_unused_picture(MpegEncContext *s, int shared)
1611 {
1612     int ret = find_unused_picture(s, shared);
1613
1614     if (ret >= 0 && ret < MAX_PICTURE_COUNT) {
1615         if (s->picture[ret].needs_realloc) {
1616             s->picture[ret].needs_realloc = 0;
1617             ff_free_picture_tables(&s->picture[ret]);
1618             ff_mpeg_unref_picture(s, &s->picture[ret]);
1619         }
1620     }
1621     return ret;
1622 }
1623
1624 /**
1625  * generic function called after decoding
1626  * the header and before a frame is decoded.
1627  */
1628 int ff_MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
1629 {
1630     int i, ret;
1631     Picture *pic;
1632     s->mb_skipped = 0;
1633
1634     /* mark & release old frames */
1635     if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
1636         s->last_picture_ptr != s->next_picture_ptr &&
1637         s->last_picture_ptr->f.buf[0]) {
1638         ff_mpeg_unref_picture(s, s->last_picture_ptr);
1639     }
1640
1641     /* release forgotten pictures */
1642     /* if (mpeg124/h263) */
1643     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1644         if (&s->picture[i] != s->last_picture_ptr &&
1645             &s->picture[i] != s->next_picture_ptr &&
1646             s->picture[i].reference && !s->picture[i].needs_realloc) {
1647             if (!(avctx->active_thread_type & FF_THREAD_FRAME))
1648                 av_log(avctx, AV_LOG_ERROR,
1649                        "releasing zombie picture\n");
1650             ff_mpeg_unref_picture(s, &s->picture[i]);
1651         }
1652     }
1653
1654     ff_mpeg_unref_picture(s, &s->current_picture);
1655
1656     release_unused_pictures(s);
1657
1658     if (s->current_picture_ptr &&
1659         s->current_picture_ptr->f.buf[0] == NULL) {
1660         // we already have a unused image
1661         // (maybe it was set before reading the header)
1662         pic = s->current_picture_ptr;
1663     } else {
1664         i   = ff_find_unused_picture(s, 0);
1665         if (i < 0) {
1666             av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1667             return i;
1668         }
1669         pic = &s->picture[i];
1670     }
1671
1672     pic->reference = 0;
1673     if (!s->droppable) {
1674         if (s->pict_type != AV_PICTURE_TYPE_B)
1675             pic->reference = 3;
1676     }
1677
1678     pic->f.coded_picture_number = s->coded_picture_number++;
1679
1680     if (ff_alloc_picture(s, pic, 0) < 0)
1681         return -1;
1682
1683     s->current_picture_ptr = pic;
1684     // FIXME use only the vars from current_pic
1685     s->current_picture_ptr->f.top_field_first = s->top_field_first;
1686     if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
1687         s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1688         if (s->picture_structure != PICT_FRAME)
1689             s->current_picture_ptr->f.top_field_first =
1690                 (s->picture_structure == PICT_TOP_FIELD) == s->first_field;
1691     }
1692     s->current_picture_ptr->f.interlaced_frame = !s->progressive_frame &&
1693                                                  !s->progressive_sequence;
1694     s->current_picture_ptr->field_picture      =  s->picture_structure != PICT_FRAME;
1695
1696     s->current_picture_ptr->f.pict_type = s->pict_type;
1697     // if (s->flags && CODEC_FLAG_QSCALE)
1698     //     s->current_picture_ptr->quality = s->new_picture_ptr->quality;
1699     s->current_picture_ptr->f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1700
1701     if ((ret = ff_mpeg_ref_picture(s, &s->current_picture,
1702                                    s->current_picture_ptr)) < 0)
1703         return ret;
1704
1705     if (s->pict_type != AV_PICTURE_TYPE_B) {
1706         s->last_picture_ptr = s->next_picture_ptr;
1707         if (!s->droppable)
1708             s->next_picture_ptr = s->current_picture_ptr;
1709     }
1710     av_dlog(s->avctx, "L%p N%p C%p L%p N%p C%p type:%d drop:%d\n",
1711             s->last_picture_ptr, s->next_picture_ptr,s->current_picture_ptr,
1712             s->last_picture_ptr    ? s->last_picture_ptr->f.data[0]    : NULL,
1713             s->next_picture_ptr    ? s->next_picture_ptr->f.data[0]    : NULL,
1714             s->current_picture_ptr ? s->current_picture_ptr->f.data[0] : NULL,
1715             s->pict_type, s->droppable);
1716
1717     if ((s->last_picture_ptr == NULL ||
1718          s->last_picture_ptr->f.buf[0] == NULL) &&
1719         (s->pict_type != AV_PICTURE_TYPE_I ||
1720          s->picture_structure != PICT_FRAME)) {
1721         int h_chroma_shift, v_chroma_shift;
1722         av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
1723                                          &h_chroma_shift, &v_chroma_shift);
1724         if (s->pict_type != AV_PICTURE_TYPE_I)
1725             av_log(avctx, AV_LOG_ERROR,
1726                    "warning: first frame is no keyframe\n");
1727         else if (s->picture_structure != PICT_FRAME)
1728             av_log(avctx, AV_LOG_INFO,
1729                    "allocate dummy last picture for field based first keyframe\n");
1730
1731         /* Allocate a dummy frame */
1732         i = ff_find_unused_picture(s, 0);
1733         if (i < 0) {
1734             av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1735             return i;
1736         }
1737         s->last_picture_ptr = &s->picture[i];
1738
1739         s->last_picture_ptr->reference   = 3;
1740         s->last_picture_ptr->f.pict_type = AV_PICTURE_TYPE_I;
1741
1742         if (ff_alloc_picture(s, s->last_picture_ptr, 0) < 0) {
1743             s->last_picture_ptr = NULL;
1744             return -1;
1745         }
1746
1747         memset(s->last_picture_ptr->f.data[0], 0,
1748                avctx->height * s->last_picture_ptr->f.linesize[0]);
1749         memset(s->last_picture_ptr->f.data[1], 0x80,
1750                (avctx->height >> v_chroma_shift) *
1751                s->last_picture_ptr->f.linesize[1]);
1752         memset(s->last_picture_ptr->f.data[2], 0x80,
1753                (avctx->height >> v_chroma_shift) *
1754                s->last_picture_ptr->f.linesize[2]);
1755
1756         ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 0);
1757         ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 1);
1758     }
1759     if ((s->next_picture_ptr == NULL ||
1760          s->next_picture_ptr->f.buf[0] == NULL) &&
1761         s->pict_type == AV_PICTURE_TYPE_B) {
1762         /* Allocate a dummy frame */
1763         i = ff_find_unused_picture(s, 0);
1764         if (i < 0) {
1765             av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1766             return i;
1767         }
1768         s->next_picture_ptr = &s->picture[i];
1769
1770         s->next_picture_ptr->reference   = 3;
1771         s->next_picture_ptr->f.pict_type = AV_PICTURE_TYPE_I;
1772
1773         if (ff_alloc_picture(s, s->next_picture_ptr, 0) < 0) {
1774             s->next_picture_ptr = NULL;
1775             return -1;
1776         }
1777         ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 0);
1778         ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 1);
1779     }
1780
1781     if (s->last_picture_ptr) {
1782         ff_mpeg_unref_picture(s, &s->last_picture);
1783         if (s->last_picture_ptr->f.buf[0] &&
1784             (ret = ff_mpeg_ref_picture(s, &s->last_picture,
1785                                        s->last_picture_ptr)) < 0)
1786             return ret;
1787     }
1788     if (s->next_picture_ptr) {
1789         ff_mpeg_unref_picture(s, &s->next_picture);
1790         if (s->next_picture_ptr->f.buf[0] &&
1791             (ret = ff_mpeg_ref_picture(s, &s->next_picture,
1792                                        s->next_picture_ptr)) < 0)
1793             return ret;
1794     }
1795
1796     if (s->pict_type != AV_PICTURE_TYPE_I &&
1797         !(s->last_picture_ptr && s->last_picture_ptr->f.buf[0])) {
1798         av_log(s, AV_LOG_ERROR,
1799                "Non-reference picture received and no reference available\n");
1800         return AVERROR_INVALIDDATA;
1801     }
1802
1803     if (s->picture_structure!= PICT_FRAME) {
1804         int i;
1805         for (i = 0; i < 4; i++) {
1806             if (s->picture_structure == PICT_BOTTOM_FIELD) {
1807                 s->current_picture.f.data[i] +=
1808                     s->current_picture.f.linesize[i];
1809             }
1810             s->current_picture.f.linesize[i] *= 2;
1811             s->last_picture.f.linesize[i]    *= 2;
1812             s->next_picture.f.linesize[i]    *= 2;
1813         }
1814     }
1815
1816     s->err_recognition = avctx->err_recognition;
1817
1818     /* set dequantizer, we can't do it during init as
1819      * it might change for mpeg4 and we can't do it in the header
1820      * decode as init is not called for mpeg4 there yet */
1821     if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1822         s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
1823         s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
1824     } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
1825         s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
1826         s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
1827     } else {
1828         s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
1829         s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
1830     }
1831
1832 #if FF_API_XVMC
1833 FF_DISABLE_DEPRECATION_WARNINGS
1834     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1835         return ff_xvmc_field_start(s, avctx);
1836 FF_ENABLE_DEPRECATION_WARNINGS
1837 #endif /* FF_API_XVMC */
1838
1839     return 0;
1840 }
1841
1842 /* called after a frame has been decoded. */
1843 void ff_MPV_frame_end(MpegEncContext *s)
1844 {
1845 #if FF_API_XVMC
1846 FF_DISABLE_DEPRECATION_WARNINGS
1847     /* redraw edges for the frame if decoding didn't complete */
1848     // just to make sure that all data is rendered.
1849     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration) {
1850         ff_xvmc_field_end(s);
1851     } else
1852 FF_ENABLE_DEPRECATION_WARNINGS
1853 #endif /* FF_API_XVMC */
1854
1855     emms_c();
1856
1857     if (s->current_picture.reference)
1858         ff_thread_report_progress(&s->current_picture_ptr->tf, INT_MAX, 0);
1859 }
1860
1861 /**
1862  * Print debugging info for the given picture.
1863  */
1864 void ff_print_debug_info(MpegEncContext *s, Picture *p)
1865 {
1866     AVFrame *pict;
1867     if (s->avctx->hwaccel || !p || !p->mb_type)
1868         return;
1869     pict = &p->f;
1870
1871     if (s->avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {
1872         int x,y;
1873
1874         av_log(s->avctx,AV_LOG_DEBUG,"New frame, type: ");
1875         switch (pict->pict_type) {
1876         case AV_PICTURE_TYPE_I:
1877             av_log(s->avctx,AV_LOG_DEBUG,"I\n");
1878             break;
1879         case AV_PICTURE_TYPE_P:
1880             av_log(s->avctx,AV_LOG_DEBUG,"P\n");
1881             break;
1882         case AV_PICTURE_TYPE_B:
1883             av_log(s->avctx,AV_LOG_DEBUG,"B\n");
1884             break;
1885         case AV_PICTURE_TYPE_S:
1886             av_log(s->avctx,AV_LOG_DEBUG,"S\n");
1887             break;
1888         case AV_PICTURE_TYPE_SI:
1889             av_log(s->avctx,AV_LOG_DEBUG,"SI\n");
1890             break;
1891         case AV_PICTURE_TYPE_SP:
1892             av_log(s->avctx,AV_LOG_DEBUG,"SP\n");
1893             break;
1894         }
1895         for (y = 0; y < s->mb_height; y++) {
1896             for (x = 0; x < s->mb_width; x++) {
1897                 if (s->avctx->debug & FF_DEBUG_SKIP) {
1898                     int count = s->mbskip_table[x + y * s->mb_stride];
1899                     if (count > 9)
1900                         count = 9;
1901                     av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);
1902                 }
1903                 if (s->avctx->debug & FF_DEBUG_QP) {
1904                     av_log(s->avctx, AV_LOG_DEBUG, "%2d",
1905                            p->qscale_table[x + y * s->mb_stride]);
1906                 }
1907                 if (s->avctx->debug & FF_DEBUG_MB_TYPE) {
1908                     int mb_type = p->mb_type[x + y * s->mb_stride];
1909                     // Type & MV direction
1910                     if (IS_PCM(mb_type))
1911                         av_log(s->avctx, AV_LOG_DEBUG, "P");
1912                     else if (IS_INTRA(mb_type) && IS_ACPRED(mb_type))
1913                         av_log(s->avctx, AV_LOG_DEBUG, "A");
1914                     else if (IS_INTRA4x4(mb_type))
1915                         av_log(s->avctx, AV_LOG_DEBUG, "i");
1916                     else if (IS_INTRA16x16(mb_type))
1917                         av_log(s->avctx, AV_LOG_DEBUG, "I");
1918                     else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type))
1919                         av_log(s->avctx, AV_LOG_DEBUG, "d");
1920                     else if (IS_DIRECT(mb_type))
1921                         av_log(s->avctx, AV_LOG_DEBUG, "D");
1922                     else if (IS_GMC(mb_type) && IS_SKIP(mb_type))
1923                         av_log(s->avctx, AV_LOG_DEBUG, "g");
1924                     else if (IS_GMC(mb_type))
1925                         av_log(s->avctx, AV_LOG_DEBUG, "G");
1926                     else if (IS_SKIP(mb_type))
1927                         av_log(s->avctx, AV_LOG_DEBUG, "S");
1928                     else if (!USES_LIST(mb_type, 1))
1929                         av_log(s->avctx, AV_LOG_DEBUG, ">");
1930                     else if (!USES_LIST(mb_type, 0))
1931                         av_log(s->avctx, AV_LOG_DEBUG, "<");
1932                     else {
1933                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
1934                         av_log(s->avctx, AV_LOG_DEBUG, "X");
1935                     }
1936
1937                     // segmentation
1938                     if (IS_8X8(mb_type))
1939                         av_log(s->avctx, AV_LOG_DEBUG, "+");
1940                     else if (IS_16X8(mb_type))
1941                         av_log(s->avctx, AV_LOG_DEBUG, "-");
1942                     else if (IS_8X16(mb_type))
1943                         av_log(s->avctx, AV_LOG_DEBUG, "|");
1944                     else if (IS_INTRA(mb_type) || IS_16X16(mb_type))
1945                         av_log(s->avctx, AV_LOG_DEBUG, " ");
1946                     else
1947                         av_log(s->avctx, AV_LOG_DEBUG, "?");
1948
1949
1950                     if (IS_INTERLACED(mb_type))
1951                         av_log(s->avctx, AV_LOG_DEBUG, "=");
1952                     else
1953                         av_log(s->avctx, AV_LOG_DEBUG, " ");
1954                 }
1955             }
1956             av_log(s->avctx, AV_LOG_DEBUG, "\n");
1957         }
1958     }
1959 }
1960
1961 /**
1962  * find the lowest MB row referenced in the MVs
1963  */
1964 int ff_MPV_lowest_referenced_row(MpegEncContext *s, int dir)
1965 {
1966     int my_max = INT_MIN, my_min = INT_MAX, qpel_shift = !s->quarter_sample;
1967     int my, off, i, mvs;
1968
1969     if (s->picture_structure != PICT_FRAME || s->mcsel)
1970         goto unhandled;
1971
1972     switch (s->mv_type) {
1973         case MV_TYPE_16X16:
1974             mvs = 1;
1975             break;
1976         case MV_TYPE_16X8:
1977             mvs = 2;
1978             break;
1979         case MV_TYPE_8X8:
1980             mvs = 4;
1981             break;
1982         default:
1983             goto unhandled;
1984     }
1985
1986     for (i = 0; i < mvs; i++) {
1987         my = s->mv[dir][i][1]<<qpel_shift;
1988         my_max = FFMAX(my_max, my);
1989         my_min = FFMIN(my_min, my);
1990     }
1991
1992     off = (FFMAX(-my_min, my_max) + 63) >> 6;
1993
1994     return FFMIN(FFMAX(s->mb_y + off, 0), s->mb_height-1);
1995 unhandled:
1996     return s->mb_height-1;
1997 }
1998
1999 /* put block[] to dest[] */
2000 static inline void put_dct(MpegEncContext *s,
2001                            int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
2002 {
2003     s->dct_unquantize_intra(s, block, i, qscale);
2004     s->dsp.idct_put (dest, line_size, block);
2005 }
2006
2007 /* add block[] to dest[] */
2008 static inline void add_dct(MpegEncContext *s,
2009                            int16_t *block, int i, uint8_t *dest, int line_size)
2010 {
2011     if (s->block_last_index[i] >= 0) {
2012         s->dsp.idct_add (dest, line_size, block);
2013     }
2014 }
2015
2016 static inline void add_dequant_dct(MpegEncContext *s,
2017                            int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
2018 {
2019     if (s->block_last_index[i] >= 0) {
2020         s->dct_unquantize_inter(s, block, i, qscale);
2021
2022         s->dsp.idct_add (dest, line_size, block);
2023     }
2024 }
2025
2026 /**
2027  * Clean dc, ac, coded_block for the current non-intra MB.
2028  */
2029 void ff_clean_intra_table_entries(MpegEncContext *s)
2030 {
2031     int wrap = s->b8_stride;
2032     int xy = s->block_index[0];
2033
2034     s->dc_val[0][xy           ] =
2035     s->dc_val[0][xy + 1       ] =
2036     s->dc_val[0][xy     + wrap] =
2037     s->dc_val[0][xy + 1 + wrap] = 1024;
2038     /* ac pred */
2039     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
2040     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
2041     if (s->msmpeg4_version>=3) {
2042         s->coded_block[xy           ] =
2043         s->coded_block[xy + 1       ] =
2044         s->coded_block[xy     + wrap] =
2045         s->coded_block[xy + 1 + wrap] = 0;
2046     }
2047     /* chroma */
2048     wrap = s->mb_stride;
2049     xy = s->mb_x + s->mb_y * wrap;
2050     s->dc_val[1][xy] =
2051     s->dc_val[2][xy] = 1024;
2052     /* ac pred */
2053     memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
2054     memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
2055
2056     s->mbintra_table[xy]= 0;
2057 }
2058
2059 /* generic function called after a macroblock has been parsed by the
2060    decoder or after it has been encoded by the encoder.
2061
2062    Important variables used:
2063    s->mb_intra : true if intra macroblock
2064    s->mv_dir   : motion vector direction
2065    s->mv_type  : motion vector type
2066    s->mv       : motion vector
2067    s->interlaced_dct : true if interlaced dct used (mpeg2)
2068  */
2069 static av_always_inline
2070 void MPV_decode_mb_internal(MpegEncContext *s, int16_t block[12][64],
2071                             int is_mpeg12)
2072 {
2073     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
2074
2075 #if FF_API_XVMC
2076 FF_DISABLE_DEPRECATION_WARNINGS
2077     if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration){
2078         ff_xvmc_decode_mb(s);//xvmc uses pblocks
2079         return;
2080     }
2081 FF_ENABLE_DEPRECATION_WARNINGS
2082 #endif /* FF_API_XVMC */
2083
2084     if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
2085        /* print DCT coefficients */
2086        int i,j;
2087        av_log(s->avctx, AV_LOG_DEBUG, "DCT coeffs of MB at %dx%d:\n", s->mb_x, s->mb_y);
2088        for(i=0; i<6; i++){
2089            for(j=0; j<64; j++){
2090                av_log(s->avctx, AV_LOG_DEBUG, "%5d", block[i][s->dsp.idct_permutation[j]]);
2091            }
2092            av_log(s->avctx, AV_LOG_DEBUG, "\n");
2093        }
2094     }
2095
2096     s->current_picture.qscale_table[mb_xy] = s->qscale;
2097
2098     /* update DC predictors for P macroblocks */
2099     if (!s->mb_intra) {
2100         if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {
2101             if(s->mbintra_table[mb_xy])
2102                 ff_clean_intra_table_entries(s);
2103         } else {
2104             s->last_dc[0] =
2105             s->last_dc[1] =
2106             s->last_dc[2] = 128 << s->intra_dc_precision;
2107         }
2108     }
2109     else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))
2110         s->mbintra_table[mb_xy]=1;
2111
2112     if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==AV_PICTURE_TYPE_B) && s->avctx->mb_decision != FF_MB_DECISION_RD)) { //FIXME precalc
2113         uint8_t *dest_y, *dest_cb, *dest_cr;
2114         int dct_linesize, dct_offset;
2115         op_pixels_func (*op_pix)[4];
2116         qpel_mc_func (*op_qpix)[16];
2117         const int linesize   = s->current_picture.f.linesize[0]; //not s->linesize as this would be wrong for field pics
2118         const int uvlinesize = s->current_picture.f.linesize[1];
2119         const int readable= s->pict_type != AV_PICTURE_TYPE_B || s->encoding || s->avctx->draw_horiz_band;
2120         const int block_size = 8;
2121
2122         /* avoid copy if macroblock skipped in last frame too */
2123         /* skip only during decoding as we might trash the buffers during encoding a bit */
2124         if(!s->encoding){
2125             uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
2126
2127             if (s->mb_skipped) {
2128                 s->mb_skipped= 0;
2129                 assert(s->pict_type!=AV_PICTURE_TYPE_I);
2130                 *mbskip_ptr = 1;
2131             } else if(!s->current_picture.reference) {
2132                 *mbskip_ptr = 1;
2133             } else{
2134                 *mbskip_ptr = 0; /* not skipped */
2135             }
2136         }
2137
2138         dct_linesize = linesize << s->interlaced_dct;
2139         dct_offset   = s->interlaced_dct ? linesize : linesize * block_size;
2140
2141         if(readable){
2142             dest_y=  s->dest[0];
2143             dest_cb= s->dest[1];
2144             dest_cr= s->dest[2];
2145         }else{
2146             dest_y = s->b_scratchpad;
2147             dest_cb= s->b_scratchpad+16*linesize;
2148             dest_cr= s->b_scratchpad+32*linesize;
2149         }
2150
2151         if (!s->mb_intra) {
2152             /* motion handling */
2153             /* decoding or more than one mb_type (MC was already done otherwise) */
2154             if(!s->encoding){
2155
2156                 if(HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
2157                     if (s->mv_dir & MV_DIR_FORWARD) {
2158                         ff_thread_await_progress(&s->last_picture_ptr->tf,
2159                                                  ff_MPV_lowest_referenced_row(s, 0),
2160                                                  0);
2161                     }
2162                     if (s->mv_dir & MV_DIR_BACKWARD) {
2163                         ff_thread_await_progress(&s->next_picture_ptr->tf,
2164                                                  ff_MPV_lowest_referenced_row(s, 1),
2165                                                  0);
2166                     }
2167                 }
2168
2169                 op_qpix= s->me.qpel_put;
2170                 if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
2171                     op_pix = s->hdsp.put_pixels_tab;
2172                 }else{
2173                     op_pix = s->hdsp.put_no_rnd_pixels_tab;
2174                 }
2175                 if (s->mv_dir & MV_DIR_FORWARD) {
2176                     ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f.data, op_pix, op_qpix);
2177                     op_pix = s->hdsp.avg_pixels_tab;
2178                     op_qpix= s->me.qpel_avg;
2179                 }
2180                 if (s->mv_dir & MV_DIR_BACKWARD) {
2181                     ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f.data, op_pix, op_qpix);
2182                 }
2183             }
2184
2185             /* skip dequant / idct if we are really late ;) */
2186             if(s->avctx->skip_idct){
2187                 if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B)
2188                    ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I)
2189                    || s->avctx->skip_idct >= AVDISCARD_ALL)
2190                     goto skip_idct;
2191             }
2192
2193             /* add dct residue */
2194             if(s->encoding || !(   s->msmpeg4_version || s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO
2195                                 || (s->codec_id==AV_CODEC_ID_MPEG4 && !s->mpeg_quant))){
2196                 add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
2197                 add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
2198                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
2199                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
2200
2201                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2202                     if (s->chroma_y_shift){
2203                         add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
2204                         add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
2205                     }else{
2206                         dct_linesize >>= 1;
2207                         dct_offset >>=1;
2208                         add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
2209                         add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
2210                         add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
2211                         add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
2212                     }
2213                 }
2214             } else if(is_mpeg12 || (s->codec_id != AV_CODEC_ID_WMV2)){
2215                 add_dct(s, block[0], 0, dest_y                          , dct_linesize);
2216                 add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);
2217                 add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);
2218                 add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);
2219
2220                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2221                     if(s->chroma_y_shift){//Chroma420
2222                         add_dct(s, block[4], 4, dest_cb, uvlinesize);
2223                         add_dct(s, block[5], 5, dest_cr, uvlinesize);
2224                     }else{
2225                         //chroma422
2226                         dct_linesize = uvlinesize << s->interlaced_dct;
2227                         dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;
2228
2229                         add_dct(s, block[4], 4, dest_cb, dct_linesize);
2230                         add_dct(s, block[5], 5, dest_cr, dct_linesize);
2231                         add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);
2232                         add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);
2233                         if(!s->chroma_x_shift){//Chroma444
2234                             add_dct(s, block[8], 8, dest_cb+8, dct_linesize);
2235                             add_dct(s, block[9], 9, dest_cr+8, dct_linesize);
2236                             add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);
2237                             add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);
2238                         }
2239                     }
2240                 }//fi gray
2241             }
2242             else if (CONFIG_WMV2_DECODER || CONFIG_WMV2_ENCODER) {
2243                 ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
2244             }
2245         } else {
2246             /* dct only in intra block */
2247             if(s->encoding || !(s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO)){
2248                 put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
2249                 put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
2250                 put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
2251                 put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
2252
2253                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2254                     if(s->chroma_y_shift){
2255                         put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
2256                         put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
2257                     }else{
2258                         dct_offset >>=1;
2259                         dct_linesize >>=1;
2260                         put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
2261                         put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
2262                         put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
2263                         put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
2264                     }
2265                 }
2266             }else{
2267                 s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);
2268                 s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);
2269                 s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);
2270                 s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);
2271
2272                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2273                     if(s->chroma_y_shift){
2274                         s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
2275                         s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
2276                     }else{
2277
2278                         dct_linesize = uvlinesize << s->interlaced_dct;
2279                         dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;
2280
2281                         s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
2282                         s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
2283                         s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
2284                         s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
2285                         if(!s->chroma_x_shift){//Chroma444
2286                             s->dsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);
2287                             s->dsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);
2288                             s->dsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);
2289                             s->dsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);
2290                         }
2291                     }
2292                 }//gray
2293             }
2294         }
2295 skip_idct:
2296         if(!readable){
2297             s->hdsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
2298             s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
2299             s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
2300         }
2301     }
2302 }
2303
2304 void ff_MPV_decode_mb(MpegEncContext *s, int16_t block[12][64]){
2305 #if !CONFIG_SMALL
2306     if(s->out_format == FMT_MPEG1) {
2307         MPV_decode_mb_internal(s, block, 1);
2308     } else
2309 #endif
2310         MPV_decode_mb_internal(s, block, 0);
2311 }
2312
2313 /**
2314  * @param h is the normal height, this will be reduced automatically if needed for the last row
2315  */
2316 void ff_draw_horiz_band(AVCodecContext *avctx, Picture *cur,
2317                         Picture *last, int y, int h, int picture_structure,
2318                         int first_field, int low_delay)
2319 {
2320     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
2321     int vshift = desc->log2_chroma_h;
2322     const int field_pic = picture_structure != PICT_FRAME;
2323     if(field_pic){
2324         h <<= 1;
2325         y <<= 1;
2326     }
2327
2328     h = FFMIN(h, avctx->height - y);
2329
2330     if(field_pic && first_field && !(avctx->slice_flags&SLICE_FLAG_ALLOW_FIELD)) return;
2331
2332     if (avctx->draw_horiz_band) {
2333         AVFrame *src;
2334         int offset[AV_NUM_DATA_POINTERS];
2335         int i;
2336
2337         if(cur->f.pict_type == AV_PICTURE_TYPE_B || low_delay ||
2338            (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
2339             src = &cur->f;
2340         else if (last)
2341             src = &last->f;
2342         else
2343             return;
2344
2345         if (cur->f.pict_type == AV_PICTURE_TYPE_B &&
2346             picture_structure == PICT_FRAME &&
2347             avctx->codec_id != AV_CODEC_ID_SVQ3) {
2348             for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
2349                 offset[i] = 0;
2350         }else{
2351             offset[0]= y * src->linesize[0];
2352             offset[1]=
2353             offset[2]= (y >> vshift) * src->linesize[1];
2354             for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
2355                 offset[i] = 0;
2356         }
2357
2358         emms_c();
2359
2360         avctx->draw_horiz_band(avctx, src, offset,
2361                                y, picture_structure, h);
2362     }
2363 }
2364
2365 void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h)
2366 {
2367     ff_draw_horiz_band(s->avctx, &s->current_picture,
2368                        &s->last_picture, y, h, s->picture_structure,
2369                        s->first_field, s->low_delay);
2370 }
2371
2372 void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
2373     const int linesize   = s->current_picture.f.linesize[0]; //not s->linesize as this would be wrong for field pics
2374     const int uvlinesize = s->current_picture.f.linesize[1];
2375     const int mb_size= 4;
2376
2377     s->block_index[0]= s->b8_stride*(s->mb_y*2    ) - 2 + s->mb_x*2;
2378     s->block_index[1]= s->b8_stride*(s->mb_y*2    ) - 1 + s->mb_x*2;
2379     s->block_index[2]= s->b8_stride*(s->mb_y*2 + 1) - 2 + s->mb_x*2;
2380     s->block_index[3]= s->b8_stride*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
2381     s->block_index[4]= s->mb_stride*(s->mb_y + 1)                + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
2382     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;
2383     //block_index is not used by mpeg2, so it is not affected by chroma_format
2384
2385     s->dest[0] = s->current_picture.f.data[0] + ((s->mb_x - 1) <<  mb_size);
2386     s->dest[1] = s->current_picture.f.data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
2387     s->dest[2] = s->current_picture.f.data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
2388
2389     if(!(s->pict_type==AV_PICTURE_TYPE_B && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
2390     {
2391         if(s->picture_structure==PICT_FRAME){
2392         s->dest[0] += s->mb_y *   linesize << mb_size;
2393         s->dest[1] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
2394         s->dest[2] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
2395         }else{
2396             s->dest[0] += (s->mb_y>>1) *   linesize << mb_size;
2397             s->dest[1] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
2398             s->dest[2] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
2399             assert((s->mb_y&1) == (s->picture_structure == PICT_BOTTOM_FIELD));
2400         }
2401     }
2402 }
2403
2404 /**
2405  * Permute an 8x8 block.
2406  * @param block the block which will be permuted according to the given permutation vector
2407  * @param permutation the permutation vector
2408  * @param last the last non zero coefficient in scantable order, used to speed the permutation up
2409  * @param scantable the used scantable, this is only used to speed the permutation up, the block is not
2410  *                  (inverse) permutated to scantable order!
2411  */
2412 void ff_block_permute(int16_t *block, uint8_t *permutation, const uint8_t *scantable, int last)
2413 {
2414     int i;
2415     int16_t temp[64];
2416
2417     if(last<=0) return;
2418     //if(permutation[1]==1) return; //FIXME it is ok but not clean and might fail for some permutations
2419
2420     for(i=0; i<=last; i++){
2421         const int j= scantable[i];
2422         temp[j]= block[j];
2423         block[j]=0;
2424     }
2425
2426     for(i=0; i<=last; i++){
2427         const int j= scantable[i];
2428         const int perm_j= permutation[j];
2429         block[perm_j]= temp[j];
2430     }
2431 }
2432
2433 void ff_mpeg_flush(AVCodecContext *avctx){
2434     int i;
2435     MpegEncContext *s = avctx->priv_data;
2436
2437     if(s==NULL || s->picture==NULL)
2438         return;
2439
2440     for (i = 0; i < MAX_PICTURE_COUNT; i++)
2441         ff_mpeg_unref_picture(s, &s->picture[i]);
2442     s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
2443
2444     ff_mpeg_unref_picture(s, &s->current_picture);
2445     ff_mpeg_unref_picture(s, &s->last_picture);
2446     ff_mpeg_unref_picture(s, &s->next_picture);
2447
2448     s->mb_x= s->mb_y= 0;
2449
2450     s->parse_context.state= -1;
2451     s->parse_context.frame_start_found= 0;
2452     s->parse_context.overread= 0;
2453     s->parse_context.overread_index= 0;
2454     s->parse_context.index= 0;
2455     s->parse_context.last_index= 0;
2456     s->bitstream_buffer_size=0;
2457     s->pp_time=0;
2458 }
2459
2460 /**
2461  * set qscale and update qscale dependent variables.
2462  */
2463 void ff_set_qscale(MpegEncContext * s, int qscale)
2464 {
2465     if (qscale < 1)
2466         qscale = 1;
2467     else if (qscale > 31)
2468         qscale = 31;
2469
2470     s->qscale = qscale;
2471     s->chroma_qscale= s->chroma_qscale_table[qscale];
2472
2473     s->y_dc_scale= s->y_dc_scale_table[ qscale ];
2474     s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
2475 }
2476
2477 void ff_MPV_report_decode_progress(MpegEncContext *s)
2478 {
2479     if (s->pict_type != AV_PICTURE_TYPE_B && !s->partitioned_frame && !s->er.error_occurred)
2480         ff_thread_report_progress(&s->current_picture_ptr->tf, s->mb_y, 0);
2481 }
2482
2483 #if CONFIG_ERROR_RESILIENCE
2484 void ff_mpeg_er_frame_start(MpegEncContext *s)
2485 {
2486     ERContext *er = &s->er;
2487
2488     er->cur_pic  = s->current_picture_ptr;
2489     er->last_pic = s->last_picture_ptr;
2490     er->next_pic = s->next_picture_ptr;
2491
2492     er->pp_time           = s->pp_time;
2493     er->pb_time           = s->pb_time;
2494     er->quarter_sample    = s->quarter_sample;
2495     er->partitioned_frame = s->partitioned_frame;
2496
2497     ff_er_frame_start(er);
2498 }
2499 #endif /* CONFIG_ERROR_RESILIENCE */