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