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