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