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