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