]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegvideo.c
vp9/x86: add ff_vp9_loop_filter_[vh]_16_16_sse2().
[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     emms_c();
1856
1857     if (s->current_picture.reference)
1858         ff_thread_report_progress(&s->current_picture_ptr->tf, INT_MAX, 0);
1859 }
1860
1861 /**
1862  * Draw a line from (ex, ey) -> (sx, sy).
1863  * @param w width of the image
1864  * @param h height of the image
1865  * @param stride stride/linesize of the image
1866  * @param color color of the arrow
1867  */
1868 static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey,
1869                       int w, int h, int stride, int color)
1870 {
1871     int x, y, fr, f;
1872
1873     sx = av_clip(sx, 0, w - 1);
1874     sy = av_clip(sy, 0, h - 1);
1875     ex = av_clip(ex, 0, w - 1);
1876     ey = av_clip(ey, 0, h - 1);
1877
1878     buf[sy * stride + sx] += color;
1879
1880     if (FFABS(ex - sx) > FFABS(ey - sy)) {
1881         if (sx > ex) {
1882             FFSWAP(int, sx, ex);
1883             FFSWAP(int, sy, ey);
1884         }
1885         buf += sx + sy * stride;
1886         ex  -= sx;
1887         f    = ((ey - sy) << 16) / ex;
1888         for (x = 0; x <= ex; x++) {
1889             y  = (x * f) >> 16;
1890             fr = (x * f) & 0xFFFF;
1891             buf[y * stride + x]       += (color * (0x10000 - fr)) >> 16;
1892             if(fr) buf[(y + 1) * stride + x] += (color *            fr ) >> 16;
1893         }
1894     } else {
1895         if (sy > ey) {
1896             FFSWAP(int, sx, ex);
1897             FFSWAP(int, sy, ey);
1898         }
1899         buf += sx + sy * stride;
1900         ey  -= sy;
1901         if (ey)
1902             f = ((ex - sx) << 16) / ey;
1903         else
1904             f = 0;
1905         for(y= 0; y <= ey; y++){
1906             x  = (y*f) >> 16;
1907             fr = (y*f) & 0xFFFF;
1908             buf[y * stride + x]     += (color * (0x10000 - fr)) >> 16;
1909             if(fr) buf[y * stride + x + 1] += (color *            fr ) >> 16;
1910         }
1911     }
1912 }
1913
1914 /**
1915  * Draw an arrow from (ex, ey) -> (sx, sy).
1916  * @param w width of the image
1917  * @param h height of the image
1918  * @param stride stride/linesize of the image
1919  * @param color color of the arrow
1920  */
1921 static void draw_arrow(uint8_t *buf, int sx, int sy, int ex,
1922                        int ey, int w, int h, int stride, int color)
1923 {
1924     int dx,dy;
1925
1926     sx = av_clip(sx, -100, w + 100);
1927     sy = av_clip(sy, -100, h + 100);
1928     ex = av_clip(ex, -100, w + 100);
1929     ey = av_clip(ey, -100, h + 100);
1930
1931     dx = ex - sx;
1932     dy = ey - sy;
1933
1934     if (dx * dx + dy * dy > 3 * 3) {
1935         int rx =  dx + dy;
1936         int ry = -dx + dy;
1937         int length = ff_sqrt((rx * rx + ry * ry) << 8);
1938
1939         // FIXME subpixel accuracy
1940         rx = ROUNDED_DIV(rx * 3 << 4, length);
1941         ry = ROUNDED_DIV(ry * 3 << 4, length);
1942
1943         draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
1944         draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
1945     }
1946     draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
1947 }
1948
1949 /**
1950  * Print debugging info for the given picture.
1951  */
1952 void ff_print_debug_info2(AVCodecContext *avctx, Picture *p, AVFrame *pict, uint8_t *mbskip_table,
1953                          int *low_delay,
1954                          int mb_width, int mb_height, int mb_stride, int quarter_sample)
1955 {
1956     if (avctx->hwaccel || !p || !p->mb_type
1957         || (avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU))
1958         return;
1959
1960
1961     if (avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {
1962         int x,y;
1963
1964         av_log(avctx, AV_LOG_DEBUG, "New frame, type: %c\n",
1965                av_get_picture_type_char(pict->pict_type));
1966         for (y = 0; y < mb_height; y++) {
1967             for (x = 0; x < mb_width; x++) {
1968                 if (avctx->debug & FF_DEBUG_SKIP) {
1969                     int count = mbskip_table[x + y * mb_stride];
1970                     if (count > 9)
1971                         count = 9;
1972                     av_log(avctx, AV_LOG_DEBUG, "%1d", count);
1973                 }
1974                 if (avctx->debug & FF_DEBUG_QP) {
1975                     av_log(avctx, AV_LOG_DEBUG, "%2d",
1976                            p->qscale_table[x + y * mb_stride]);
1977                 }
1978                 if (avctx->debug & FF_DEBUG_MB_TYPE) {
1979                     int mb_type = p->mb_type[x + y * mb_stride];
1980                     // Type & MV direction
1981                     if (IS_PCM(mb_type))
1982                         av_log(avctx, AV_LOG_DEBUG, "P");
1983                     else if (IS_INTRA(mb_type) && IS_ACPRED(mb_type))
1984                         av_log(avctx, AV_LOG_DEBUG, "A");
1985                     else if (IS_INTRA4x4(mb_type))
1986                         av_log(avctx, AV_LOG_DEBUG, "i");
1987                     else if (IS_INTRA16x16(mb_type))
1988                         av_log(avctx, AV_LOG_DEBUG, "I");
1989                     else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type))
1990                         av_log(avctx, AV_LOG_DEBUG, "d");
1991                     else if (IS_DIRECT(mb_type))
1992                         av_log(avctx, AV_LOG_DEBUG, "D");
1993                     else if (IS_GMC(mb_type) && IS_SKIP(mb_type))
1994                         av_log(avctx, AV_LOG_DEBUG, "g");
1995                     else if (IS_GMC(mb_type))
1996                         av_log(avctx, AV_LOG_DEBUG, "G");
1997                     else if (IS_SKIP(mb_type))
1998                         av_log(avctx, AV_LOG_DEBUG, "S");
1999                     else if (!USES_LIST(mb_type, 1))
2000                         av_log(avctx, AV_LOG_DEBUG, ">");
2001                     else if (!USES_LIST(mb_type, 0))
2002                         av_log(avctx, AV_LOG_DEBUG, "<");
2003                     else {
2004                         av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
2005                         av_log(avctx, AV_LOG_DEBUG, "X");
2006                     }
2007
2008                     // segmentation
2009                     if (IS_8X8(mb_type))
2010                         av_log(avctx, AV_LOG_DEBUG, "+");
2011                     else if (IS_16X8(mb_type))
2012                         av_log(avctx, AV_LOG_DEBUG, "-");
2013                     else if (IS_8X16(mb_type))
2014                         av_log(avctx, AV_LOG_DEBUG, "|");
2015                     else if (IS_INTRA(mb_type) || IS_16X16(mb_type))
2016                         av_log(avctx, AV_LOG_DEBUG, " ");
2017                     else
2018                         av_log(avctx, AV_LOG_DEBUG, "?");
2019
2020
2021                     if (IS_INTERLACED(mb_type))
2022                         av_log(avctx, AV_LOG_DEBUG, "=");
2023                     else
2024                         av_log(avctx, AV_LOG_DEBUG, " ");
2025                 }
2026             }
2027             av_log(avctx, AV_LOG_DEBUG, "\n");
2028         }
2029     }
2030
2031     if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) ||
2032         (avctx->debug_mv)) {
2033         const int shift = 1 + quarter_sample;
2034         int mb_y;
2035         uint8_t *ptr;
2036         int i;
2037         int h_chroma_shift, v_chroma_shift, block_height;
2038         const int width          = avctx->width;
2039         const int height         = avctx->height;
2040         const int mv_sample_log2 = avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_SVQ3 ? 2 : 1;
2041         const int mv_stride      = (mb_width << mv_sample_log2) +
2042                                    (avctx->codec->id == AV_CODEC_ID_H264 ? 0 : 1);
2043
2044         *low_delay = 0; // needed to see the vectors without trashing the buffers
2045
2046         avcodec_get_chroma_sub_sample(avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
2047
2048         av_frame_make_writable(pict);
2049
2050         pict->opaque = NULL;
2051         ptr          = pict->data[0];
2052         block_height = 16 >> v_chroma_shift;
2053
2054         for (mb_y = 0; mb_y < mb_height; mb_y++) {
2055             int mb_x;
2056             for (mb_x = 0; mb_x < mb_width; mb_x++) {
2057                 const int mb_index = mb_x + mb_y * mb_stride;
2058                 if ((avctx->debug_mv) && p->motion_val[0]) {
2059                     int type;
2060                     for (type = 0; type < 3; type++) {
2061                         int direction = 0;
2062                         switch (type) {
2063                         case 0:
2064                             if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_P_FOR)) ||
2065                                 (pict->pict_type!= AV_PICTURE_TYPE_P))
2066                                 continue;
2067                             direction = 0;
2068                             break;
2069                         case 1:
2070                             if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_FOR)) ||
2071                                 (pict->pict_type!= AV_PICTURE_TYPE_B))
2072                                 continue;
2073                             direction = 0;
2074                             break;
2075                         case 2:
2076                             if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_BACK)) ||
2077                                 (pict->pict_type!= AV_PICTURE_TYPE_B))
2078                                 continue;
2079                             direction = 1;
2080                             break;
2081                         }
2082                         if (!USES_LIST(p->mb_type[mb_index], direction))
2083                             continue;
2084
2085                         if (IS_8X8(p->mb_type[mb_index])) {
2086                             int i;
2087                             for (i = 0; i < 4; i++) {
2088                                 int sx = mb_x * 16 + 4 + 8 * (i & 1);
2089                                 int sy = mb_y * 16 + 4 + 8 * (i >> 1);
2090                                 int xy = (mb_x * 2 + (i & 1) +
2091                                           (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
2092                                 int mx = (p->motion_val[direction][xy][0] >> shift) + sx;
2093                                 int my = (p->motion_val[direction][xy][1] >> shift) + sy;
2094                                 draw_arrow(ptr, sx, sy, mx, my, width,
2095                                            height, pict->linesize[0], 100);
2096                             }
2097                         } else if (IS_16X8(p->mb_type[mb_index])) {
2098                             int i;
2099                             for (i = 0; i < 2; i++) {
2100                                 int sx = mb_x * 16 + 8;
2101                                 int sy = mb_y * 16 + 4 + 8 * i;
2102                                 int xy = (mb_x * 2 + (mb_y * 2 + i) * mv_stride) << (mv_sample_log2 - 1);
2103                                 int mx = (p->motion_val[direction][xy][0] >> shift);
2104                                 int my = (p->motion_val[direction][xy][1] >> shift);
2105
2106                                 if (IS_INTERLACED(p->mb_type[mb_index]))
2107                                     my *= 2;
2108
2109                             draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,
2110                                        height, pict->linesize[0], 100);
2111                             }
2112                         } else if (IS_8X16(p->mb_type[mb_index])) {
2113                             int i;
2114                             for (i = 0; i < 2; i++) {
2115                                 int sx = mb_x * 16 + 4 + 8 * i;
2116                                 int sy = mb_y * 16 + 8;
2117                                 int xy = (mb_x * 2 + i + mb_y * 2 * mv_stride) << (mv_sample_log2 - 1);
2118                                 int mx = p->motion_val[direction][xy][0] >> shift;
2119                                 int my = p->motion_val[direction][xy][1] >> shift;
2120
2121                                 if (IS_INTERLACED(p->mb_type[mb_index]))
2122                                     my *= 2;
2123
2124                                 draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,
2125                                            height, pict->linesize[0], 100);
2126                             }
2127                         } else {
2128                               int sx= mb_x * 16 + 8;
2129                               int sy= mb_y * 16 + 8;
2130                               int xy= (mb_x + mb_y * mv_stride) << mv_sample_log2;
2131                               int mx= (p->motion_val[direction][xy][0]>>shift) + sx;
2132                               int my= (p->motion_val[direction][xy][1]>>shift) + sy;
2133                               draw_arrow(ptr, sx, sy, mx, my, width, height, pict->linesize[0], 100);
2134                         }
2135                     }
2136                 }
2137                 if ((avctx->debug & FF_DEBUG_VIS_QP)) {
2138                     uint64_t c = (p->qscale_table[mb_index] * 128 / 31) *
2139                                  0x0101010101010101ULL;
2140                     int y;
2141                     for (y = 0; y < block_height; y++) {
2142                         *(uint64_t *)(pict->data[1] + 8 * mb_x +
2143                                       (block_height * mb_y + y) *
2144                                       pict->linesize[1]) = c;
2145                         *(uint64_t *)(pict->data[2] + 8 * mb_x +
2146                                       (block_height * mb_y + y) *
2147                                       pict->linesize[2]) = c;
2148                     }
2149                 }
2150                 if ((avctx->debug & FF_DEBUG_VIS_MB_TYPE) &&
2151                     p->motion_val[0]) {
2152                     int mb_type = p->mb_type[mb_index];
2153                     uint64_t u,v;
2154                     int y;
2155 #define COLOR(theta, r) \
2156     u = (int)(128 + r * cos(theta * 3.141592 / 180)); \
2157     v = (int)(128 + r * sin(theta * 3.141592 / 180));
2158
2159
2160                     u = v = 128;
2161                     if (IS_PCM(mb_type)) {
2162                         COLOR(120, 48)
2163                     } else if ((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) ||
2164                                IS_INTRA16x16(mb_type)) {
2165                         COLOR(30, 48)
2166                     } else if (IS_INTRA4x4(mb_type)) {
2167                         COLOR(90, 48)
2168                     } else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type)) {
2169                         // COLOR(120, 48)
2170                     } else if (IS_DIRECT(mb_type)) {
2171                         COLOR(150, 48)
2172                     } else if (IS_GMC(mb_type) && IS_SKIP(mb_type)) {
2173                         COLOR(170, 48)
2174                     } else if (IS_GMC(mb_type)) {
2175                         COLOR(190, 48)
2176                     } else if (IS_SKIP(mb_type)) {
2177                         // COLOR(180, 48)
2178                     } else if (!USES_LIST(mb_type, 1)) {
2179                         COLOR(240, 48)
2180                     } else if (!USES_LIST(mb_type, 0)) {
2181                         COLOR(0, 48)
2182                     } else {
2183                         av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
2184                         COLOR(300,48)
2185                     }
2186
2187                     u *= 0x0101010101010101ULL;
2188                     v *= 0x0101010101010101ULL;
2189                     for (y = 0; y < block_height; y++) {
2190                         *(uint64_t *)(pict->data[1] + 8 * mb_x +
2191                                       (block_height * mb_y + y) * pict->linesize[1]) = u;
2192                         *(uint64_t *)(pict->data[2] + 8 * mb_x +
2193                                       (block_height * mb_y + y) * pict->linesize[2]) = v;
2194                     }
2195
2196                     // segmentation
2197                     if (IS_8X8(mb_type) || IS_16X8(mb_type)) {
2198                         *(uint64_t *)(pict->data[0] + 16 * mb_x + 0 +
2199                                       (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;
2200                         *(uint64_t *)(pict->data[0] + 16 * mb_x + 8 +
2201                                       (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;
2202                     }
2203                     if (IS_8X8(mb_type) || IS_8X16(mb_type)) {
2204                         for (y = 0; y < 16; y++)
2205                             pict->data[0][16 * mb_x + 8 + (16 * mb_y + y) *
2206                                           pict->linesize[0]] ^= 0x80;
2207                     }
2208                     if (IS_8X8(mb_type) && mv_sample_log2 >= 2) {
2209                         int dm = 1 << (mv_sample_log2 - 2);
2210                         for (i = 0; i < 4; i++) {
2211                             int sx = mb_x * 16 + 8 * (i & 1);
2212                             int sy = mb_y * 16 + 8 * (i >> 1);
2213                             int xy = (mb_x * 2 + (i & 1) +
2214                                      (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
2215                             // FIXME bidir
2216                             int32_t *mv = (int32_t *) &p->motion_val[0][xy];
2217                             if (mv[0] != mv[dm] ||
2218                                 mv[dm * mv_stride] != mv[dm * (mv_stride + 1)])
2219                                 for (y = 0; y < 8; y++)
2220                                     pict->data[0][sx + 4 + (sy + y) * pict->linesize[0]] ^= 0x80;
2221                             if (mv[0] != mv[dm * mv_stride] || mv[dm] != mv[dm * (mv_stride + 1)])
2222                                 *(uint64_t *)(pict->data[0] + sx + (sy + 4) *
2223                                               pict->linesize[0]) ^= 0x8080808080808080ULL;
2224                         }
2225                     }
2226
2227                     if (IS_INTERLACED(mb_type) &&
2228                         avctx->codec->id == AV_CODEC_ID_H264) {
2229                         // hmm
2230                     }
2231                 }
2232                 mbskip_table[mb_index] = 0;
2233             }
2234         }
2235     }
2236 }
2237
2238 void ff_print_debug_info(MpegEncContext *s, Picture *p, AVFrame *pict)
2239 {
2240     ff_print_debug_info2(s->avctx, p, pict, s->mbskip_table, &s->low_delay,
2241                          s->mb_width, s->mb_height, s->mb_stride, s->quarter_sample);
2242 }
2243
2244 int ff_mpv_export_qp_table(MpegEncContext *s, AVFrame *f, Picture *p, int qp_type)
2245 {
2246     AVBufferRef *ref = av_buffer_ref(p->qscale_table_buf);
2247     int offset = 2*s->mb_stride + 1;
2248     if(!ref)
2249         return AVERROR(ENOMEM);
2250     av_assert0(ref->size >= offset + s->mb_stride * ((f->height+15)/16));
2251     ref->size -= offset;
2252     ref->data += offset;
2253     return av_frame_set_qp_table(f, ref, s->mb_stride, qp_type);
2254 }
2255
2256 static inline int hpel_motion_lowres(MpegEncContext *s,
2257                                      uint8_t *dest, uint8_t *src,
2258                                      int field_based, int field_select,
2259                                      int src_x, int src_y,
2260                                      int width, int height, ptrdiff_t stride,
2261                                      int h_edge_pos, int v_edge_pos,
2262                                      int w, int h, h264_chroma_mc_func *pix_op,
2263                                      int motion_x, int motion_y)
2264 {
2265     const int lowres   = s->avctx->lowres;
2266     const int op_index = FFMIN(lowres, 3);
2267     const int s_mask   = (2 << lowres) - 1;
2268     int emu = 0;
2269     int sx, sy;
2270
2271     if (s->quarter_sample) {
2272         motion_x /= 2;
2273         motion_y /= 2;
2274     }
2275
2276     sx = motion_x & s_mask;
2277     sy = motion_y & s_mask;
2278     src_x += motion_x >> lowres + 1;
2279     src_y += motion_y >> lowres + 1;
2280
2281     src   += src_y * stride + src_x;
2282
2283     if ((unsigned)src_x > FFMAX( h_edge_pos - (!!sx) - w,                 0) ||
2284         (unsigned)src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
2285         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, src,
2286                                  s->linesize, s->linesize,
2287                                  w + 1, (h + 1) << field_based,
2288                                  src_x, src_y   << field_based,
2289                                  h_edge_pos, v_edge_pos);
2290         src = s->edge_emu_buffer;
2291         emu = 1;
2292     }
2293
2294     sx = (sx << 2) >> lowres;
2295     sy = (sy << 2) >> lowres;
2296     if (field_select)
2297         src += s->linesize;
2298     pix_op[op_index](dest, src, stride, h, sx, sy);
2299     return emu;
2300 }
2301
2302 /* apply one mpeg motion vector to the three components */
2303 static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,
2304                                                 uint8_t *dest_y,
2305                                                 uint8_t *dest_cb,
2306                                                 uint8_t *dest_cr,
2307                                                 int field_based,
2308                                                 int bottom_field,
2309                                                 int field_select,
2310                                                 uint8_t **ref_picture,
2311                                                 h264_chroma_mc_func *pix_op,
2312                                                 int motion_x, int motion_y,
2313                                                 int h, int mb_y)
2314 {
2315     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
2316     int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, sx, sy, uvsx, uvsy;
2317     ptrdiff_t uvlinesize, linesize;
2318     const int lowres     = s->avctx->lowres;
2319     const int op_index   = FFMIN(lowres-1+s->chroma_x_shift, 3);
2320     const int block_s    = 8>>lowres;
2321     const int s_mask     = (2 << lowres) - 1;
2322     const int h_edge_pos = s->h_edge_pos >> lowres;
2323     const int v_edge_pos = s->v_edge_pos >> lowres;
2324     linesize   = s->current_picture.f.linesize[0] << field_based;
2325     uvlinesize = s->current_picture.f.linesize[1] << field_based;
2326
2327     // FIXME obviously not perfect but qpel will not work in lowres anyway
2328     if (s->quarter_sample) {
2329         motion_x /= 2;
2330         motion_y /= 2;
2331     }
2332
2333     if(field_based){
2334         motion_y += (bottom_field - field_select)*((1 << lowres)-1);
2335     }
2336
2337     sx = motion_x & s_mask;
2338     sy = motion_y & s_mask;
2339     src_x = s->mb_x * 2 * block_s + (motion_x >> lowres + 1);
2340     src_y = (mb_y * 2 * block_s >> field_based) + (motion_y >> lowres + 1);
2341
2342     if (s->out_format == FMT_H263) {
2343         uvsx    = ((motion_x >> 1) & s_mask) | (sx & 1);
2344         uvsy    = ((motion_y >> 1) & s_mask) | (sy & 1);
2345         uvsrc_x = src_x >> 1;
2346         uvsrc_y = src_y >> 1;
2347     } else if (s->out_format == FMT_H261) {
2348         // even chroma mv's are full pel in H261
2349         mx      = motion_x / 4;
2350         my      = motion_y / 4;
2351         uvsx    = (2 * mx) & s_mask;
2352         uvsy    = (2 * my) & s_mask;
2353         uvsrc_x = s->mb_x * block_s + (mx >> lowres);
2354         uvsrc_y =    mb_y * block_s + (my >> lowres);
2355     } else {
2356         if(s->chroma_y_shift){
2357             mx      = motion_x / 2;
2358             my      = motion_y / 2;
2359             uvsx    = mx & s_mask;
2360             uvsy    = my & s_mask;
2361             uvsrc_x = s->mb_x * block_s                 + (mx >> lowres + 1);
2362             uvsrc_y =   (mb_y * block_s >> field_based) + (my >> lowres + 1);
2363         } else {
2364             if(s->chroma_x_shift){
2365             //Chroma422
2366                 mx = motion_x / 2;
2367                 uvsx = mx & s_mask;
2368                 uvsy = motion_y & s_mask;
2369                 uvsrc_y = src_y;
2370                 uvsrc_x = s->mb_x*block_s               + (mx >> (lowres+1));
2371             } else {
2372             //Chroma444
2373                 uvsx = motion_x & s_mask;
2374                 uvsy = motion_y & s_mask;
2375                 uvsrc_x = src_x;
2376                 uvsrc_y = src_y;
2377             }
2378         }
2379     }
2380
2381     ptr_y  = ref_picture[0] + src_y   * linesize   + src_x;
2382     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
2383     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
2384
2385     if ((unsigned) src_x > FFMAX( h_edge_pos - (!!sx) - 2 * block_s,       0) || uvsrc_y<0 ||
2386         (unsigned) src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
2387         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,
2388                                  linesize >> field_based, linesize >> field_based,
2389                                  17, 17 + field_based,
2390                                 src_x, src_y << field_based, h_edge_pos,
2391                                 v_edge_pos);
2392         ptr_y = s->edge_emu_buffer;
2393         if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2394             uint8_t *uvbuf = s->edge_emu_buffer + 18 * s->linesize;
2395             s->vdsp.emulated_edge_mc(uvbuf,  ptr_cb,
2396                                      uvlinesize >> field_based, uvlinesize >> field_based,
2397                                      9, 9 + field_based,
2398                                     uvsrc_x, uvsrc_y << field_based,
2399                                     h_edge_pos >> 1, v_edge_pos >> 1);
2400             s->vdsp.emulated_edge_mc(uvbuf + 16,  ptr_cr,
2401                                      uvlinesize >> field_based,uvlinesize >> field_based,
2402                                      9, 9 + field_based,
2403                                     uvsrc_x, uvsrc_y << field_based,
2404                                     h_edge_pos >> 1, v_edge_pos >> 1);
2405             ptr_cb = uvbuf;
2406             ptr_cr = uvbuf + 16;
2407         }
2408     }
2409
2410     // FIXME use this for field pix too instead of the obnoxious hack which changes picture.f.data
2411     if (bottom_field) {
2412         dest_y  += s->linesize;
2413         dest_cb += s->uvlinesize;
2414         dest_cr += s->uvlinesize;
2415     }
2416
2417     if (field_select) {
2418         ptr_y   += s->linesize;
2419         ptr_cb  += s->uvlinesize;
2420         ptr_cr  += s->uvlinesize;
2421     }
2422
2423     sx = (sx << 2) >> lowres;
2424     sy = (sy << 2) >> lowres;
2425     pix_op[lowres - 1](dest_y, ptr_y, linesize, h, sx, sy);
2426
2427     if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
2428         int hc = s->chroma_y_shift ? (h+1-bottom_field)>>1 : h;
2429         uvsx = (uvsx << 2) >> lowres;
2430         uvsy = (uvsy << 2) >> lowres;
2431         if (hc) {
2432             pix_op[op_index](dest_cb, ptr_cb, uvlinesize, hc, uvsx, uvsy);
2433             pix_op[op_index](dest_cr, ptr_cr, uvlinesize, hc, uvsx, uvsy);
2434         }
2435     }
2436     // FIXME h261 lowres loop filter
2437 }
2438
2439 static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
2440                                             uint8_t *dest_cb, uint8_t *dest_cr,
2441                                             uint8_t **ref_picture,
2442                                             h264_chroma_mc_func * pix_op,
2443                                             int mx, int my)
2444 {
2445     const int lowres     = s->avctx->lowres;
2446     const int op_index   = FFMIN(lowres, 3);
2447     const int block_s    = 8 >> lowres;
2448     const int s_mask     = (2 << lowres) - 1;
2449     const int h_edge_pos = s->h_edge_pos >> lowres + 1;
2450     const int v_edge_pos = s->v_edge_pos >> lowres + 1;
2451     int emu = 0, src_x, src_y, sx, sy;
2452     ptrdiff_t offset;
2453     uint8_t *ptr;
2454
2455     if (s->quarter_sample) {
2456         mx /= 2;
2457         my /= 2;
2458     }
2459
2460     /* In case of 8X8, we construct a single chroma motion vector
2461        with a special rounding */
2462     mx = ff_h263_round_chroma(mx);
2463     my = ff_h263_round_chroma(my);
2464
2465     sx = mx & s_mask;
2466     sy = my & s_mask;
2467     src_x = s->mb_x * block_s + (mx >> lowres + 1);
2468     src_y = s->mb_y * block_s + (my >> lowres + 1);
2469
2470     offset = src_y * s->uvlinesize + src_x;
2471     ptr = ref_picture[1] + offset;
2472     if ((unsigned) src_x > FFMAX(h_edge_pos - (!!sx) - block_s, 0) ||
2473         (unsigned) src_y > FFMAX(v_edge_pos - (!!sy) - block_s, 0)) {
2474         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
2475                                  s->uvlinesize, s->uvlinesize,
2476                                  9, 9,
2477                                  src_x, src_y, h_edge_pos, v_edge_pos);
2478         ptr = s->edge_emu_buffer;
2479         emu = 1;
2480     }
2481     sx = (sx << 2) >> lowres;
2482     sy = (sy << 2) >> lowres;
2483     pix_op[op_index](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);
2484
2485     ptr = ref_picture[2] + offset;
2486     if (emu) {
2487         s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr,
2488                                  s->uvlinesize, s->uvlinesize,
2489                                  9, 9,
2490                                  src_x, src_y, h_edge_pos, v_edge_pos);
2491         ptr = s->edge_emu_buffer;
2492     }
2493     pix_op[op_index](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
2494 }
2495
2496 /**
2497  * motion compensation of a single macroblock
2498  * @param s context
2499  * @param dest_y luma destination pointer
2500  * @param dest_cb chroma cb/u destination pointer
2501  * @param dest_cr chroma cr/v destination pointer
2502  * @param dir direction (0->forward, 1->backward)
2503  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
2504  * @param pix_op halfpel motion compensation function (average or put normally)
2505  * the motion vectors are taken from s->mv and the MV type from s->mv_type
2506  */
2507 static inline void MPV_motion_lowres(MpegEncContext *s,
2508                                      uint8_t *dest_y, uint8_t *dest_cb,
2509                                      uint8_t *dest_cr,
2510                                      int dir, uint8_t **ref_picture,
2511                                      h264_chroma_mc_func *pix_op)
2512 {
2513     int mx, my;
2514     int mb_x, mb_y, i;
2515     const int lowres  = s->avctx->lowres;
2516     const int block_s = 8 >>lowres;
2517
2518     mb_x = s->mb_x;
2519     mb_y = s->mb_y;
2520
2521     switch (s->mv_type) {
2522     case MV_TYPE_16X16:
2523         mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2524                            0, 0, 0,
2525                            ref_picture, pix_op,
2526                            s->mv[dir][0][0], s->mv[dir][0][1],
2527                            2 * block_s, mb_y);
2528         break;
2529     case MV_TYPE_8X8:
2530         mx = 0;
2531         my = 0;
2532         for (i = 0; i < 4; i++) {
2533             hpel_motion_lowres(s, dest_y + ((i & 1) + (i >> 1) *
2534                                s->linesize) * block_s,
2535                                ref_picture[0], 0, 0,
2536                                (2 * mb_x + (i & 1)) * block_s,
2537                                (2 * mb_y + (i >> 1)) * block_s,
2538                                s->width, s->height, s->linesize,
2539                                s->h_edge_pos >> lowres, s->v_edge_pos >> lowres,
2540                                block_s, block_s, pix_op,
2541                                s->mv[dir][i][0], s->mv[dir][i][1]);
2542
2543             mx += s->mv[dir][i][0];
2544             my += s->mv[dir][i][1];
2545         }
2546
2547         if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY))
2548             chroma_4mv_motion_lowres(s, dest_cb, dest_cr, ref_picture,
2549                                      pix_op, mx, my);
2550         break;
2551     case MV_TYPE_FIELD:
2552         if (s->picture_structure == PICT_FRAME) {
2553             /* top field */
2554             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2555                                1, 0, s->field_select[dir][0],
2556                                ref_picture, pix_op,
2557                                s->mv[dir][0][0], s->mv[dir][0][1],
2558                                block_s, mb_y);
2559             /* bottom field */
2560             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2561                                1, 1, s->field_select[dir][1],
2562                                ref_picture, pix_op,
2563                                s->mv[dir][1][0], s->mv[dir][1][1],
2564                                block_s, mb_y);
2565         } else {
2566             if (s->picture_structure != s->field_select[dir][0] + 1 &&
2567                 s->pict_type != AV_PICTURE_TYPE_B && !s->first_field) {
2568                 ref_picture = s->current_picture_ptr->f.data;
2569
2570             }
2571             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2572                                0, 0, s->field_select[dir][0],
2573                                ref_picture, pix_op,
2574                                s->mv[dir][0][0],
2575                                s->mv[dir][0][1], 2 * block_s, mb_y >> 1);
2576             }
2577         break;
2578     case MV_TYPE_16X8:
2579         for (i = 0; i < 2; i++) {
2580             uint8_t **ref2picture;
2581
2582             if (s->picture_structure == s->field_select[dir][i] + 1 ||
2583                 s->pict_type == AV_PICTURE_TYPE_B || s->first_field) {
2584                 ref2picture = ref_picture;
2585             } else {
2586                 ref2picture = s->current_picture_ptr->f.data;
2587             }
2588
2589             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2590                                0, 0, s->field_select[dir][i],
2591                                ref2picture, pix_op,
2592                                s->mv[dir][i][0], s->mv[dir][i][1] +
2593                                2 * block_s * i, block_s, mb_y >> 1);
2594
2595             dest_y  +=  2 * block_s *  s->linesize;
2596             dest_cb += (2 * block_s >> s->chroma_y_shift) * s->uvlinesize;
2597             dest_cr += (2 * block_s >> s->chroma_y_shift) * s->uvlinesize;
2598         }
2599         break;
2600     case MV_TYPE_DMV:
2601         if (s->picture_structure == PICT_FRAME) {
2602             for (i = 0; i < 2; i++) {
2603                 int j;
2604                 for (j = 0; j < 2; j++) {
2605                     mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2606                                        1, j, j ^ i,
2607                                        ref_picture, pix_op,
2608                                        s->mv[dir][2 * i + j][0],
2609                                        s->mv[dir][2 * i + j][1],
2610                                        block_s, mb_y);
2611                 }
2612                 pix_op = s->h264chroma.avg_h264_chroma_pixels_tab;
2613             }
2614         } else {
2615             for (i = 0; i < 2; i++) {
2616                 mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
2617                                    0, 0, s->picture_structure != i + 1,
2618                                    ref_picture, pix_op,
2619                                    s->mv[dir][2 * i][0],s->mv[dir][2 * i][1],
2620                                    2 * block_s, mb_y >> 1);
2621
2622                 // after put we make avg of the same block
2623                 pix_op = s->h264chroma.avg_h264_chroma_pixels_tab;
2624
2625                 // opposite parity is always in the same
2626                 // frame if this is second field
2627                 if (!s->first_field) {
2628                     ref_picture = s->current_picture_ptr->f.data;
2629                 }
2630             }
2631         }
2632         break;
2633     default:
2634         av_assert2(0);
2635     }
2636 }
2637
2638 /**
2639  * find the lowest MB row referenced in the MVs
2640  */
2641 int ff_MPV_lowest_referenced_row(MpegEncContext *s, int dir)
2642 {
2643     int my_max = INT_MIN, my_min = INT_MAX, qpel_shift = !s->quarter_sample;
2644     int my, off, i, mvs;
2645
2646     if (s->picture_structure != PICT_FRAME || s->mcsel)
2647         goto unhandled;
2648
2649     switch (s->mv_type) {
2650         case MV_TYPE_16X16:
2651             mvs = 1;
2652             break;
2653         case MV_TYPE_16X8:
2654             mvs = 2;
2655             break;
2656         case MV_TYPE_8X8:
2657             mvs = 4;
2658             break;
2659         default:
2660             goto unhandled;
2661     }
2662
2663     for (i = 0; i < mvs; i++) {
2664         my = s->mv[dir][i][1]<<qpel_shift;
2665         my_max = FFMAX(my_max, my);
2666         my_min = FFMIN(my_min, my);
2667     }
2668
2669     off = (FFMAX(-my_min, my_max) + 63) >> 6;
2670
2671     return FFMIN(FFMAX(s->mb_y + off, 0), s->mb_height-1);
2672 unhandled:
2673     return s->mb_height-1;
2674 }
2675
2676 /* put block[] to dest[] */
2677 static inline void put_dct(MpegEncContext *s,
2678                            int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
2679 {
2680     s->dct_unquantize_intra(s, block, i, qscale);
2681     s->dsp.idct_put (dest, line_size, block);
2682 }
2683
2684 /* add block[] to dest[] */
2685 static inline void add_dct(MpegEncContext *s,
2686                            int16_t *block, int i, uint8_t *dest, int line_size)
2687 {
2688     if (s->block_last_index[i] >= 0) {
2689         s->dsp.idct_add (dest, line_size, block);
2690     }
2691 }
2692
2693 static inline void add_dequant_dct(MpegEncContext *s,
2694                            int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
2695 {
2696     if (s->block_last_index[i] >= 0) {
2697         s->dct_unquantize_inter(s, block, i, qscale);
2698
2699         s->dsp.idct_add (dest, line_size, block);
2700     }
2701 }
2702
2703 /**
2704  * Clean dc, ac, coded_block for the current non-intra MB.
2705  */
2706 void ff_clean_intra_table_entries(MpegEncContext *s)
2707 {
2708     int wrap = s->b8_stride;
2709     int xy = s->block_index[0];
2710
2711     s->dc_val[0][xy           ] =
2712     s->dc_val[0][xy + 1       ] =
2713     s->dc_val[0][xy     + wrap] =
2714     s->dc_val[0][xy + 1 + wrap] = 1024;
2715     /* ac pred */
2716     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
2717     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
2718     if (s->msmpeg4_version>=3) {
2719         s->coded_block[xy           ] =
2720         s->coded_block[xy + 1       ] =
2721         s->coded_block[xy     + wrap] =
2722         s->coded_block[xy + 1 + wrap] = 0;
2723     }
2724     /* chroma */
2725     wrap = s->mb_stride;
2726     xy = s->mb_x + s->mb_y * wrap;
2727     s->dc_val[1][xy] =
2728     s->dc_val[2][xy] = 1024;
2729     /* ac pred */
2730     memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
2731     memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
2732
2733     s->mbintra_table[xy]= 0;
2734 }
2735
2736 /* generic function called after a macroblock has been parsed by the
2737    decoder or after it has been encoded by the encoder.
2738
2739    Important variables used:
2740    s->mb_intra : true if intra macroblock
2741    s->mv_dir   : motion vector direction
2742    s->mv_type  : motion vector type
2743    s->mv       : motion vector
2744    s->interlaced_dct : true if interlaced dct used (mpeg2)
2745  */
2746 static av_always_inline
2747 void MPV_decode_mb_internal(MpegEncContext *s, int16_t block[12][64],
2748                             int lowres_flag, int is_mpeg12)
2749 {
2750     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
2751
2752     if (CONFIG_XVMC &&
2753         s->avctx->hwaccel && s->avctx->hwaccel->decode_mb) {
2754         s->avctx->hwaccel->decode_mb(s);//xvmc uses pblocks
2755         return;
2756     }
2757
2758     if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
2759        /* print DCT coefficients */
2760        int i,j;
2761        av_log(s->avctx, AV_LOG_DEBUG, "DCT coeffs of MB at %dx%d:\n", s->mb_x, s->mb_y);
2762        for(i=0; i<6; i++){
2763            for(j=0; j<64; j++){
2764                av_log(s->avctx, AV_LOG_DEBUG, "%5d", block[i][s->dsp.idct_permutation[j]]);
2765            }
2766            av_log(s->avctx, AV_LOG_DEBUG, "\n");
2767        }
2768     }
2769
2770     s->current_picture.qscale_table[mb_xy] = s->qscale;
2771
2772     /* update DC predictors for P macroblocks */
2773     if (!s->mb_intra) {
2774         if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {
2775             if(s->mbintra_table[mb_xy])
2776                 ff_clean_intra_table_entries(s);
2777         } else {
2778             s->last_dc[0] =
2779             s->last_dc[1] =
2780             s->last_dc[2] = 128 << s->intra_dc_precision;
2781         }
2782     }
2783     else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))
2784         s->mbintra_table[mb_xy]=1;
2785
2786     if (   (s->flags&CODEC_FLAG_PSNR)
2787         || s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor
2788         || !(s->encoding && (s->intra_only || s->pict_type==AV_PICTURE_TYPE_B) && s->avctx->mb_decision != FF_MB_DECISION_RD)) { //FIXME precalc
2789         uint8_t *dest_y, *dest_cb, *dest_cr;
2790         int dct_linesize, dct_offset;
2791         op_pixels_func (*op_pix)[4];
2792         qpel_mc_func (*op_qpix)[16];
2793         const int linesize   = s->current_picture.f.linesize[0]; //not s->linesize as this would be wrong for field pics
2794         const int uvlinesize = s->current_picture.f.linesize[1];
2795         const int readable= s->pict_type != AV_PICTURE_TYPE_B || s->encoding || s->avctx->draw_horiz_band || lowres_flag;
2796         const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;
2797
2798         /* avoid copy if macroblock skipped in last frame too */
2799         /* skip only during decoding as we might trash the buffers during encoding a bit */
2800         if(!s->encoding){
2801             uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
2802
2803             if (s->mb_skipped) {
2804                 s->mb_skipped= 0;
2805                 av_assert2(s->pict_type!=AV_PICTURE_TYPE_I);
2806                 *mbskip_ptr = 1;
2807             } else if(!s->current_picture.reference) {
2808                 *mbskip_ptr = 1;
2809             } else{
2810                 *mbskip_ptr = 0; /* not skipped */
2811             }
2812         }
2813
2814         dct_linesize = linesize << s->interlaced_dct;
2815         dct_offset   = s->interlaced_dct ? linesize : linesize * block_size;
2816
2817         if(readable){
2818             dest_y=  s->dest[0];
2819             dest_cb= s->dest[1];
2820             dest_cr= s->dest[2];
2821         }else{
2822             dest_y = s->b_scratchpad;
2823             dest_cb= s->b_scratchpad+16*linesize;
2824             dest_cr= s->b_scratchpad+32*linesize;
2825         }
2826
2827         if (!s->mb_intra) {
2828             /* motion handling */
2829             /* decoding or more than one mb_type (MC was already done otherwise) */
2830             if(!s->encoding){
2831
2832                 if(HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {
2833                     if (s->mv_dir & MV_DIR_FORWARD) {
2834                         ff_thread_await_progress(&s->last_picture_ptr->tf,
2835                                                  ff_MPV_lowest_referenced_row(s, 0),
2836                                                  0);
2837                     }
2838                     if (s->mv_dir & MV_DIR_BACKWARD) {
2839                         ff_thread_await_progress(&s->next_picture_ptr->tf,
2840                                                  ff_MPV_lowest_referenced_row(s, 1),
2841                                                  0);
2842                     }
2843                 }
2844
2845                 if(lowres_flag){
2846                     h264_chroma_mc_func *op_pix = s->h264chroma.put_h264_chroma_pixels_tab;
2847
2848                     if (s->mv_dir & MV_DIR_FORWARD) {
2849                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f.data, op_pix);
2850                         op_pix = s->h264chroma.avg_h264_chroma_pixels_tab;
2851                     }
2852                     if (s->mv_dir & MV_DIR_BACKWARD) {
2853                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f.data, op_pix);
2854                     }
2855                 }else{
2856                     op_qpix = s->me.qpel_put;
2857                     if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
2858                         op_pix = s->hdsp.put_pixels_tab;
2859                     }else{
2860                         op_pix = s->hdsp.put_no_rnd_pixels_tab;
2861                     }
2862                     if (s->mv_dir & MV_DIR_FORWARD) {
2863                         ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f.data, op_pix, op_qpix);
2864                         op_pix = s->hdsp.avg_pixels_tab;
2865                         op_qpix= s->me.qpel_avg;
2866                     }
2867                     if (s->mv_dir & MV_DIR_BACKWARD) {
2868                         ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f.data, op_pix, op_qpix);
2869                     }
2870                 }
2871             }
2872
2873             /* skip dequant / idct if we are really late ;) */
2874             if(s->avctx->skip_idct){
2875                 if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B)
2876                    ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I)
2877                    || s->avctx->skip_idct >= AVDISCARD_ALL)
2878                     goto skip_idct;
2879             }
2880
2881             /* add dct residue */
2882             if(s->encoding || !(   s->msmpeg4_version || s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO
2883                                 || (s->codec_id==AV_CODEC_ID_MPEG4 && !s->mpeg_quant))){
2884                 add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
2885                 add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
2886                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
2887                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
2888
2889                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2890                     if (s->chroma_y_shift){
2891                         add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
2892                         add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
2893                     }else{
2894                         dct_linesize >>= 1;
2895                         dct_offset >>=1;
2896                         add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
2897                         add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
2898                         add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
2899                         add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
2900                     }
2901                 }
2902             } else if(is_mpeg12 || (s->codec_id != AV_CODEC_ID_WMV2)){
2903                 add_dct(s, block[0], 0, dest_y                          , dct_linesize);
2904                 add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);
2905                 add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);
2906                 add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);
2907
2908                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2909                     if(s->chroma_y_shift){//Chroma420
2910                         add_dct(s, block[4], 4, dest_cb, uvlinesize);
2911                         add_dct(s, block[5], 5, dest_cr, uvlinesize);
2912                     }else{
2913                         //chroma422
2914                         dct_linesize = uvlinesize << s->interlaced_dct;
2915                         dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
2916
2917                         add_dct(s, block[4], 4, dest_cb, dct_linesize);
2918                         add_dct(s, block[5], 5, dest_cr, dct_linesize);
2919                         add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);
2920                         add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);
2921                         if(!s->chroma_x_shift){//Chroma444
2922                             add_dct(s, block[8], 8, dest_cb+block_size, dct_linesize);
2923                             add_dct(s, block[9], 9, dest_cr+block_size, dct_linesize);
2924                             add_dct(s, block[10], 10, dest_cb+block_size+dct_offset, dct_linesize);
2925                             add_dct(s, block[11], 11, dest_cr+block_size+dct_offset, dct_linesize);
2926                         }
2927                     }
2928                 }//fi gray
2929             }
2930             else if (CONFIG_WMV2_DECODER || CONFIG_WMV2_ENCODER) {
2931                 ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
2932             }
2933         } else {
2934             /* dct only in intra block */
2935             if(s->encoding || !(s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO)){
2936                 put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
2937                 put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
2938                 put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
2939                 put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
2940
2941                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2942                     if(s->chroma_y_shift){
2943                         put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
2944                         put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
2945                     }else{
2946                         dct_offset >>=1;
2947                         dct_linesize >>=1;
2948                         put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
2949                         put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
2950                         put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
2951                         put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
2952                     }
2953                 }
2954             }else{
2955                 s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);
2956                 s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);
2957                 s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);
2958                 s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);
2959
2960                 if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
2961                     if(s->chroma_y_shift){
2962                         s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
2963                         s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
2964                     }else{
2965
2966                         dct_linesize = uvlinesize << s->interlaced_dct;
2967                         dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
2968
2969                         s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
2970                         s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
2971                         s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
2972                         s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
2973                         if(!s->chroma_x_shift){//Chroma444
2974                             s->dsp.idct_put(dest_cb + block_size,              dct_linesize, block[8]);
2975                             s->dsp.idct_put(dest_cr + block_size,              dct_linesize, block[9]);
2976                             s->dsp.idct_put(dest_cb + block_size + dct_offset, dct_linesize, block[10]);
2977                             s->dsp.idct_put(dest_cr + block_size + dct_offset, dct_linesize, block[11]);
2978                         }
2979                     }
2980                 }//gray
2981             }
2982         }
2983 skip_idct:
2984         if(!readable){
2985             s->hdsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
2986             s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
2987             s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
2988         }
2989     }
2990 }
2991
2992 void ff_MPV_decode_mb(MpegEncContext *s, int16_t block[12][64]){
2993 #if !CONFIG_SMALL
2994     if(s->out_format == FMT_MPEG1) {
2995         if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 1);
2996         else                 MPV_decode_mb_internal(s, block, 0, 1);
2997     } else
2998 #endif
2999     if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 0);
3000     else                  MPV_decode_mb_internal(s, block, 0, 0);
3001 }
3002
3003 /**
3004  * @param h is the normal height, this will be reduced automatically if needed for the last row
3005  */
3006 void ff_draw_horiz_band(AVCodecContext *avctx, DSPContext *dsp, Picture *cur,
3007                         Picture *last, int y, int h, int picture_structure,
3008                         int first_field, int low_delay,
3009                         int v_edge_pos, int h_edge_pos)
3010 {
3011     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
3012     int vshift = desc->log2_chroma_h;
3013     const int field_pic = picture_structure != PICT_FRAME;
3014     if(field_pic){
3015         h <<= 1;
3016         y <<= 1;
3017     }
3018
3019     h = FFMIN(h, avctx->height - y);
3020
3021     if(field_pic && first_field && !(avctx->slice_flags&SLICE_FLAG_ALLOW_FIELD)) return;
3022
3023     if (avctx->draw_horiz_band) {
3024         AVFrame *src;
3025         int offset[AV_NUM_DATA_POINTERS];
3026         int i;
3027
3028         if(cur->f.pict_type == AV_PICTURE_TYPE_B || low_delay ||
3029            (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
3030             src = &cur->f;
3031         else if (last)
3032             src = &last->f;
3033         else
3034             return;
3035
3036         if (cur->f.pict_type == AV_PICTURE_TYPE_B &&
3037             picture_structure == PICT_FRAME &&
3038             avctx->codec_id != AV_CODEC_ID_SVQ3) {
3039             for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
3040                 offset[i] = 0;
3041         }else{
3042             offset[0]= y * src->linesize[0];
3043             offset[1]=
3044             offset[2]= (y >> vshift) * src->linesize[1];
3045             for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
3046                 offset[i] = 0;
3047         }
3048
3049         emms_c();
3050
3051         avctx->draw_horiz_band(avctx, src, offset,
3052                                y, picture_structure, h);
3053     }
3054 }
3055
3056 void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h)
3057 {
3058     ff_draw_horiz_band(s->avctx, &s->dsp, s->current_picture_ptr,
3059                        s->last_picture_ptr, y, h, s->picture_structure,
3060                        s->first_field, s->low_delay,
3061                        s->v_edge_pos, s->h_edge_pos);
3062 }
3063
3064 void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
3065     const int linesize   = s->current_picture.f.linesize[0]; //not s->linesize as this would be wrong for field pics
3066     const int uvlinesize = s->current_picture.f.linesize[1];
3067     const int mb_size= 4 - s->avctx->lowres;
3068
3069     s->block_index[0]= s->b8_stride*(s->mb_y*2    ) - 2 + s->mb_x*2;
3070     s->block_index[1]= s->b8_stride*(s->mb_y*2    ) - 1 + s->mb_x*2;
3071     s->block_index[2]= s->b8_stride*(s->mb_y*2 + 1) - 2 + s->mb_x*2;
3072     s->block_index[3]= s->b8_stride*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
3073     s->block_index[4]= s->mb_stride*(s->mb_y + 1)                + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
3074     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;
3075     //block_index is not used by mpeg2, so it is not affected by chroma_format
3076
3077     s->dest[0] = s->current_picture.f.data[0] + ((s->mb_x - 1) <<  mb_size);
3078     s->dest[1] = s->current_picture.f.data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
3079     s->dest[2] = s->current_picture.f.data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
3080
3081     if(!(s->pict_type==AV_PICTURE_TYPE_B && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
3082     {
3083         if(s->picture_structure==PICT_FRAME){
3084         s->dest[0] += s->mb_y *   linesize << mb_size;
3085         s->dest[1] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
3086         s->dest[2] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
3087         }else{
3088             s->dest[0] += (s->mb_y>>1) *   linesize << mb_size;
3089             s->dest[1] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
3090             s->dest[2] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
3091             av_assert1((s->mb_y&1) == (s->picture_structure == PICT_BOTTOM_FIELD));
3092         }
3093     }
3094 }
3095
3096 /**
3097  * Permute an 8x8 block.
3098  * @param block the block which will be permuted according to the given permutation vector
3099  * @param permutation the permutation vector
3100  * @param last the last non zero coefficient in scantable order, used to speed the permutation up
3101  * @param scantable the used scantable, this is only used to speed the permutation up, the block is not
3102  *                  (inverse) permutated to scantable order!
3103  */
3104 void ff_block_permute(int16_t *block, uint8_t *permutation, const uint8_t *scantable, int last)
3105 {
3106     int i;
3107     int16_t temp[64];
3108
3109     if(last<=0) return;
3110     //if(permutation[1]==1) return; //FIXME it is ok but not clean and might fail for some permutations
3111
3112     for(i=0; i<=last; i++){
3113         const int j= scantable[i];
3114         temp[j]= block[j];
3115         block[j]=0;
3116     }
3117
3118     for(i=0; i<=last; i++){
3119         const int j= scantable[i];
3120         const int perm_j= permutation[j];
3121         block[perm_j]= temp[j];
3122     }
3123 }
3124
3125 void ff_mpeg_flush(AVCodecContext *avctx){
3126     int i;
3127     MpegEncContext *s = avctx->priv_data;
3128
3129     if(s==NULL || s->picture==NULL)
3130         return;
3131
3132     for (i = 0; i < MAX_PICTURE_COUNT; i++)
3133         ff_mpeg_unref_picture(s, &s->picture[i]);
3134     s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
3135
3136     ff_mpeg_unref_picture(s, &s->current_picture);
3137     ff_mpeg_unref_picture(s, &s->last_picture);
3138     ff_mpeg_unref_picture(s, &s->next_picture);
3139
3140     s->mb_x= s->mb_y= 0;
3141     s->closed_gop= 0;
3142
3143     s->parse_context.state= -1;
3144     s->parse_context.frame_start_found= 0;
3145     s->parse_context.overread= 0;
3146     s->parse_context.overread_index= 0;
3147     s->parse_context.index= 0;
3148     s->parse_context.last_index= 0;
3149     s->bitstream_buffer_size=0;
3150     s->pp_time=0;
3151 }
3152
3153 /**
3154  * set qscale and update qscale dependent variables.
3155  */
3156 void ff_set_qscale(MpegEncContext * s, int qscale)
3157 {
3158     if (qscale < 1)
3159         qscale = 1;
3160     else if (qscale > 31)
3161         qscale = 31;
3162
3163     s->qscale = qscale;
3164     s->chroma_qscale= s->chroma_qscale_table[qscale];
3165
3166     s->y_dc_scale= s->y_dc_scale_table[ qscale ];
3167     s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
3168 }
3169
3170 void ff_MPV_report_decode_progress(MpegEncContext *s)
3171 {
3172     if (s->pict_type != AV_PICTURE_TYPE_B && !s->partitioned_frame && !s->er.error_occurred)
3173         ff_thread_report_progress(&s->current_picture_ptr->tf, s->mb_y, 0);
3174 }
3175
3176 #if CONFIG_ERROR_RESILIENCE
3177 void ff_mpeg_er_frame_start(MpegEncContext *s)
3178 {
3179     ERContext *er = &s->er;
3180
3181     er->cur_pic  = s->current_picture_ptr;
3182     er->last_pic = s->last_picture_ptr;
3183     er->next_pic = s->next_picture_ptr;
3184
3185     er->pp_time           = s->pp_time;
3186     er->pb_time           = s->pb_time;
3187     er->quarter_sample    = s->quarter_sample;
3188     er->partitioned_frame = s->partitioned_frame;
3189
3190     ff_er_frame_start(er);
3191 }
3192 #endif /* CONFIG_ERROR_RESILIENCE */