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