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