1/*
2 * MPEG-1/2 decoder
3 * Copyright (c) 2000, 2001 Fabrice Bellard
4 * Copyright (c) 2002-2013 Michael Niedermayer <michaelni@gmx.at>
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
24 * @file
25 * MPEG-1/2 decoder
26 */
27
28#define UNCHECKED_BITSTREAM_READER 1
29#include <inttypes.h>
30
31#include "libavutil/attributes.h"
32#include "libavutil/internal.h"
33#include "libavutil/stereo3d.h"
34
35#include "avcodec.h"
36#include "bytestream.h"
37#include "error_resilience.h"
38#include "idctdsp.h"
39#include "internal.h"
40#include "mpeg_er.h"
41#include "mpeg12.h"
42#include "mpeg12data.h"
43#include "mpegutils.h"
44#include "mpegvideo.h"
45#include "thread.h"
46#include "version.h"
47#include "vdpau_internal.h"
48#include "xvmc_internal.h"
49
50typedef struct Mpeg1Context {
51    MpegEncContext mpeg_enc_ctx;
52    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
53    int repeat_field;           /* true if we must repeat the field */
54    AVPanScan pan_scan;         /* some temporary storage for the panscan */
55    AVStereo3D stereo3d;
56    int has_stereo3d;
57    uint8_t *a53_caption;
58    int a53_caption_size;
59    int slice_count;
60    int save_aspect_info;
61    int save_width, save_height, save_progressive_seq;
62    AVRational frame_rate_ext;  /* MPEG-2 specific framerate modificator */
63    int sync;                   /* Did we reach a sync point like a GOP/SEQ/KEYFrame? */
64    int tmpgexs;
65    int first_slice;
66    int extradata_decoded;
67} Mpeg1Context;
68
69#define MB_TYPE_ZERO_MV   0x20000000
70
71static const uint32_t ptype2mb_type[7] = {
72                    MB_TYPE_INTRA,
73                    MB_TYPE_L0 | MB_TYPE_CBP | MB_TYPE_ZERO_MV | MB_TYPE_16x16,
74                    MB_TYPE_L0,
75                    MB_TYPE_L0 | MB_TYPE_CBP,
76    MB_TYPE_QUANT | MB_TYPE_INTRA,
77    MB_TYPE_QUANT | MB_TYPE_L0 | MB_TYPE_CBP | MB_TYPE_ZERO_MV | MB_TYPE_16x16,
78    MB_TYPE_QUANT | MB_TYPE_L0 | MB_TYPE_CBP,
79};
80
81static const uint32_t btype2mb_type[11] = {
82                    MB_TYPE_INTRA,
83                    MB_TYPE_L1,
84                    MB_TYPE_L1   | MB_TYPE_CBP,
85                    MB_TYPE_L0,
86                    MB_TYPE_L0   | MB_TYPE_CBP,
87                    MB_TYPE_L0L1,
88                    MB_TYPE_L0L1 | MB_TYPE_CBP,
89    MB_TYPE_QUANT | MB_TYPE_INTRA,
90    MB_TYPE_QUANT | MB_TYPE_L1   | MB_TYPE_CBP,
91    MB_TYPE_QUANT | MB_TYPE_L0   | MB_TYPE_CBP,
92    MB_TYPE_QUANT | MB_TYPE_L0L1 | MB_TYPE_CBP,
93};
94
95static const uint8_t non_linear_qscale[32] = {
96     0,  1,  2,  3,  4,  5,   6,   7,
97     8, 10, 12, 14, 16, 18,  20,  22,
98    24, 28, 32, 36, 40, 44,  48,  52,
99    56, 64, 72, 80, 88, 96, 104, 112,
100};
101
102/* as H.263, but only 17 codes */
103static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred)
104{
105    int code, sign, val, shift;
106
107    code = get_vlc2(&s->gb, ff_mv_vlc.table, MV_VLC_BITS, 2);
108    if (code == 0)
109        return pred;
110    if (code < 0)
111        return 0xffff;
112
113    sign  = get_bits1(&s->gb);
114    shift = fcode - 1;
115    val   = code;
116    if (shift) {
117        val  = (val - 1) << shift;
118        val |= get_bits(&s->gb, shift);
119        val++;
120    }
121    if (sign)
122        val = -val;
123    val += pred;
124
125    /* modulo decoding */
126    return sign_extend(val, 5 + shift);
127}
128
129#define check_scantable_index(ctx, x)                                         \
130    do {                                                                      \
131        if ((x) > 63) {                                                       \
132            av_log(ctx->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n",     \
133                   ctx->mb_x, ctx->mb_y);                                     \
134            return AVERROR_INVALIDDATA;                                       \
135        }                                                                     \
136    } while (0)
137
138static inline int mpeg1_decode_block_intra(MpegEncContext *s,
139                                           int16_t *block, int n)
140{
141    int level, dc, diff, i, j, run;
142    int component;
143    RLTable *rl                  = &ff_rl_mpeg1;
144    uint8_t *const scantable     = s->intra_scantable.permutated;
145    const uint16_t *quant_matrix = s->intra_matrix;
146    const int qscale             = s->qscale;
147
148    /* DC coefficient */
149    component = (n <= 3 ? 0 : n - 4 + 1);
150    diff = decode_dc(&s->gb, component);
151    if (diff >= 0xffff)
152        return -1;
153    dc  = s->last_dc[component];
154    dc += diff;
155    s->last_dc[component] = dc;
156    block[0] = dc * quant_matrix[0];
157    av_dlog(s->avctx, "dc=%d diff=%d\n", dc, diff);
158    i = 0;
159    {
160        OPEN_READER(re, &s->gb);
161        UPDATE_CACHE(re, &s->gb);
162        if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
163            goto end;
164
165        /* now quantify & encode AC coefficients */
166        for (;;) {
167            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
168                       TEX_VLC_BITS, 2, 0);
169
170            if (level != 0) {
171                i += run;
172                check_scantable_index(s, i);
173                j = scantable[i];
174                level = (level * qscale * quant_matrix[j]) >> 4;
175                level = (level - 1) | 1;
176                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
177                        SHOW_SBITS(re, &s->gb, 1);
178                SKIP_BITS(re, &s->gb, 1);
179            } else {
180                /* escape */
181                run = SHOW_UBITS(re, &s->gb, 6) + 1;
182                LAST_SKIP_BITS(re, &s->gb, 6);
183                UPDATE_CACHE(re, &s->gb);
184                level = SHOW_SBITS(re, &s->gb, 8);
185                SKIP_BITS(re, &s->gb, 8);
186                if (level == -128) {
187                    level = SHOW_UBITS(re, &s->gb, 8) - 256;
188                    SKIP_BITS(re, &s->gb, 8);
189                } else if (level == 0) {
190                    level = SHOW_UBITS(re, &s->gb, 8);
191                    SKIP_BITS(re, &s->gb, 8);
192                }
193                i += run;
194                check_scantable_index(s, i);
195                j = scantable[i];
196                if (level < 0) {
197                    level = -level;
198                    level = (level * qscale * quant_matrix[j]) >> 4;
199                    level = (level - 1) | 1;
200                    level = -level;
201                } else {
202                    level = (level * qscale * quant_matrix[j]) >> 4;
203                    level = (level - 1) | 1;
204                }
205            }
206
207            block[j] = level;
208            if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)
209               break;
210
211            UPDATE_CACHE(re, &s->gb);
212        }
213end:
214        LAST_SKIP_BITS(re, &s->gb, 2);
215        CLOSE_READER(re, &s->gb);
216    }
217    s->block_last_index[n] = i;
218    return 0;
219}
220
221int ff_mpeg1_decode_block_intra(MpegEncContext *s, int16_t *block, int n)
222{
223    return mpeg1_decode_block_intra(s, block, n);
224}
225
226static inline int mpeg1_decode_block_inter(MpegEncContext *s,
227                                           int16_t *block, int n)
228{
229    int level, i, j, run;
230    RLTable *rl                  = &ff_rl_mpeg1;
231    uint8_t *const scantable     = s->intra_scantable.permutated;
232    const uint16_t *quant_matrix = s->inter_matrix;
233    const int qscale             = s->qscale;
234
235    {
236        OPEN_READER(re, &s->gb);
237        i = -1;
238        // special case for first coefficient, no need to add second VLC table
239        UPDATE_CACHE(re, &s->gb);
240        if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
241            level = (3 * qscale * quant_matrix[0]) >> 5;
242            level = (level - 1) | 1;
243            if (GET_CACHE(re, &s->gb) & 0x40000000)
244                level = -level;
245            block[0] = level;
246            i++;
247            SKIP_BITS(re, &s->gb, 2);
248            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
249                goto end;
250        }
251        /* now quantify & encode AC coefficients */
252        for (;;) {
253            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
254                       TEX_VLC_BITS, 2, 0);
255
256            if (level != 0) {
257                i += run;
258                check_scantable_index(s, i);
259                j = scantable[i];
260                level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
261                level = (level - 1) | 1;
262                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
263                        SHOW_SBITS(re, &s->gb, 1);
264                SKIP_BITS(re, &s->gb, 1);
265            } else {
266                /* escape */
267                run = SHOW_UBITS(re, &s->gb, 6) + 1;
268                LAST_SKIP_BITS(re, &s->gb, 6);
269                UPDATE_CACHE(re, &s->gb);
270                level = SHOW_SBITS(re, &s->gb, 8);
271                SKIP_BITS(re, &s->gb, 8);
272                if (level == -128) {
273                    level = SHOW_UBITS(re, &s->gb, 8) - 256;
274                    SKIP_BITS(re, &s->gb, 8);
275                } else if (level == 0) {
276                    level = SHOW_UBITS(re, &s->gb, 8);
277                    SKIP_BITS(re, &s->gb, 8);
278                }
279                i += run;
280                check_scantable_index(s, i);
281                j = scantable[i];
282                if (level < 0) {
283                    level = -level;
284                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
285                    level = (level - 1) | 1;
286                    level = -level;
287                } else {
288                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
289                    level = (level - 1) | 1;
290                }
291            }
292
293            block[j] = level;
294            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
295                break;
296            UPDATE_CACHE(re, &s->gb);
297        }
298end:
299        LAST_SKIP_BITS(re, &s->gb, 2);
300        CLOSE_READER(re, &s->gb);
301    }
302    s->block_last_index[n] = i;
303    return 0;
304}
305
306/**
307 * Note: this function can read out of range and crash for corrupt streams.
308 * Changing this would eat up any speed benefits it has.
309 * Do not use "fast" flag if you need the code to be robust.
310 */
311static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s,
312                                                int16_t *block, int n)
313{
314    int level, i, j, run;
315    RLTable *rl              = &ff_rl_mpeg1;
316    uint8_t *const scantable = s->intra_scantable.permutated;
317    const int qscale         = s->qscale;
318
319    {
320        OPEN_READER(re, &s->gb);
321        i = -1;
322        // Special case for first coefficient, no need to add second VLC table.
323        UPDATE_CACHE(re, &s->gb);
324        if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
325            level = (3 * qscale) >> 1;
326            level = (level - 1) | 1;
327            if (GET_CACHE(re, &s->gb) & 0x40000000)
328                level = -level;
329            block[0] = level;
330            i++;
331            SKIP_BITS(re, &s->gb, 2);
332            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
333                goto end;
334        }
335
336        /* now quantify & encode AC coefficients */
337        for (;;) {
338            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
339                       TEX_VLC_BITS, 2, 0);
340
341            if (level != 0) {
342                i += run;
343                check_scantable_index(s, i);
344                j = scantable[i];
345                level = ((level * 2 + 1) * qscale) >> 1;
346                level = (level - 1) | 1;
347                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
348                        SHOW_SBITS(re, &s->gb, 1);
349                SKIP_BITS(re, &s->gb, 1);
350            } else {
351                /* escape */
352                run = SHOW_UBITS(re, &s->gb, 6) + 1;
353                LAST_SKIP_BITS(re, &s->gb, 6);
354                UPDATE_CACHE(re, &s->gb);
355                level = SHOW_SBITS(re, &s->gb, 8);
356                SKIP_BITS(re, &s->gb, 8);
357                if (level == -128) {
358                    level = SHOW_UBITS(re, &s->gb, 8) - 256;
359                    SKIP_BITS(re, &s->gb, 8);
360                } else if (level == 0) {
361                    level = SHOW_UBITS(re, &s->gb, 8);
362                    SKIP_BITS(re, &s->gb, 8);
363                }
364                i += run;
365                check_scantable_index(s, i);
366                j = scantable[i];
367                if (level < 0) {
368                    level = -level;
369                    level = ((level * 2 + 1) * qscale) >> 1;
370                    level = (level - 1) | 1;
371                    level = -level;
372                } else {
373                    level = ((level * 2 + 1) * qscale) >> 1;
374                    level = (level - 1) | 1;
375                }
376            }
377
378            block[j] = level;
379            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
380                break;
381            UPDATE_CACHE(re, &s->gb);
382        }
383end:
384        LAST_SKIP_BITS(re, &s->gb, 2);
385        CLOSE_READER(re, &s->gb);
386    }
387    s->block_last_index[n] = i;
388    return 0;
389}
390
391static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
392                                               int16_t *block, int n)
393{
394    int level, i, j, run;
395    RLTable *rl = &ff_rl_mpeg1;
396    uint8_t *const scantable = s->intra_scantable.permutated;
397    const uint16_t *quant_matrix;
398    const int qscale = s->qscale;
399    int mismatch;
400
401    mismatch = 1;
402
403    {
404        OPEN_READER(re, &s->gb);
405        i = -1;
406        if (n < 4)
407            quant_matrix = s->inter_matrix;
408        else
409            quant_matrix = s->chroma_inter_matrix;
410
411        // Special case for first coefficient, no need to add second VLC table.
412        UPDATE_CACHE(re, &s->gb);
413        if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
414            level = (3 * qscale * quant_matrix[0]) >> 5;
415            if (GET_CACHE(re, &s->gb) & 0x40000000)
416                level = -level;
417            block[0]  = level;
418            mismatch ^= level;
419            i++;
420            SKIP_BITS(re, &s->gb, 2);
421            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
422                goto end;
423        }
424
425        /* now quantify & encode AC coefficients */
426        for (;;) {
427            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
428                       TEX_VLC_BITS, 2, 0);
429
430            if (level != 0) {
431                i += run;
432                check_scantable_index(s, i);
433                j = scantable[i];
434                level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
435                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
436                        SHOW_SBITS(re, &s->gb, 1);
437                SKIP_BITS(re, &s->gb, 1);
438            } else {
439                /* escape */
440                run = SHOW_UBITS(re, &s->gb, 6) + 1;
441                LAST_SKIP_BITS(re, &s->gb, 6);
442                UPDATE_CACHE(re, &s->gb);
443                level = SHOW_SBITS(re, &s->gb, 12);
444                SKIP_BITS(re, &s->gb, 12);
445
446                i += run;
447                check_scantable_index(s, i);
448                j = scantable[i];
449                if (level < 0) {
450                    level = ((-level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
451                    level = -level;
452                } else {
453                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
454                }
455            }
456
457            mismatch ^= level;
458            block[j]  = level;
459            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
460                break;
461            UPDATE_CACHE(re, &s->gb);
462        }
463end:
464        LAST_SKIP_BITS(re, &s->gb, 2);
465        CLOSE_READER(re, &s->gb);
466    }
467    block[63] ^= (mismatch & 1);
468
469    s->block_last_index[n] = i;
470    return 0;
471}
472
473/**
474 * Note: this function can read out of range and crash for corrupt streams.
475 * Changing this would eat up any speed benefits it has.
476 * Do not use "fast" flag if you need the code to be robust.
477 */
478static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,
479                                                    int16_t *block, int n)
480{
481    int level, i, j, run;
482    RLTable *rl              = &ff_rl_mpeg1;
483    uint8_t *const scantable = s->intra_scantable.permutated;
484    const int qscale         = s->qscale;
485    OPEN_READER(re, &s->gb);
486    i = -1;
487
488    // special case for first coefficient, no need to add second VLC table
489    UPDATE_CACHE(re, &s->gb);
490    if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
491        level = (3 * qscale) >> 1;
492        if (GET_CACHE(re, &s->gb) & 0x40000000)
493            level = -level;
494        block[0] = level;
495        i++;
496        SKIP_BITS(re, &s->gb, 2);
497        if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
498            goto end;
499    }
500
501    /* now quantify & encode AC coefficients */
502    for (;;) {
503        GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);
504
505        if (level != 0) {
506            i += run;
507            j = scantable[i];
508            level = ((level * 2 + 1) * qscale) >> 1;
509            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
510                    SHOW_SBITS(re, &s->gb, 1);
511            SKIP_BITS(re, &s->gb, 1);
512        } else {
513            /* escape */
514            run = SHOW_UBITS(re, &s->gb, 6) + 1;
515            LAST_SKIP_BITS(re, &s->gb, 6);
516            UPDATE_CACHE(re, &s->gb);
517            level = SHOW_SBITS(re, &s->gb, 12);
518            SKIP_BITS(re, &s->gb, 12);
519
520            i += run;
521            j = scantable[i];
522            if (level < 0) {
523                level = ((-level * 2 + 1) * qscale) >> 1;
524                level = -level;
525            } else {
526                level = ((level * 2 + 1) * qscale) >> 1;
527            }
528        }
529
530        block[j] = level;
531        if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF || i > 63)
532            break;
533
534        UPDATE_CACHE(re, &s->gb);
535    }
536end:
537    LAST_SKIP_BITS(re, &s->gb, 2);
538    CLOSE_READER(re, &s->gb);
539    s->block_last_index[n] = i;
540    return 0;
541}
542
543static inline int mpeg2_decode_block_intra(MpegEncContext *s,
544                                           int16_t *block, int n)
545{
546    int level, dc, diff, i, j, run;
547    int component;
548    RLTable *rl;
549    uint8_t *const scantable = s->intra_scantable.permutated;
550    const uint16_t *quant_matrix;
551    const int qscale = s->qscale;
552    int mismatch;
553
554    /* DC coefficient */
555    if (n < 4) {
556        quant_matrix = s->intra_matrix;
557        component    = 0;
558    } else {
559        quant_matrix = s->chroma_intra_matrix;
560        component    = (n & 1) + 1;
561    }
562    diff = decode_dc(&s->gb, component);
563    if (diff >= 0xffff)
564        return -1;
565    dc  = s->last_dc[component];
566    dc += diff;
567    s->last_dc[component] = dc;
568    block[0] = dc << (3 - s->intra_dc_precision);
569    av_dlog(s->avctx, "dc=%d\n", block[0]);
570    mismatch = block[0] ^ 1;
571    i = 0;
572    if (s->intra_vlc_format)
573        rl = &ff_rl_mpeg2;
574    else
575        rl = &ff_rl_mpeg1;
576
577    {
578        OPEN_READER(re, &s->gb);
579        /* now quantify & encode AC coefficients */
580        for (;;) {
581            UPDATE_CACHE(re, &s->gb);
582            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
583                       TEX_VLC_BITS, 2, 0);
584
585            if (level == 127) {
586                break;
587            } else if (level != 0) {
588                i += run;
589                check_scantable_index(s, i);
590                j = scantable[i];
591                level = (level * qscale * quant_matrix[j]) >> 4;
592                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
593                        SHOW_SBITS(re, &s->gb, 1);
594                LAST_SKIP_BITS(re, &s->gb, 1);
595            } else {
596                /* escape */
597                run = SHOW_UBITS(re, &s->gb, 6) + 1;
598                LAST_SKIP_BITS(re, &s->gb, 6);
599                UPDATE_CACHE(re, &s->gb);
600                level = SHOW_SBITS(re, &s->gb, 12);
601                SKIP_BITS(re, &s->gb, 12);
602                i += run;
603                check_scantable_index(s, i);
604                j = scantable[i];
605                if (level < 0) {
606                    level = (-level * qscale * quant_matrix[j]) >> 4;
607                    level = -level;
608                } else {
609                    level = (level * qscale * quant_matrix[j]) >> 4;
610                }
611            }
612
613            mismatch ^= level;
614            block[j]  = level;
615        }
616        CLOSE_READER(re, &s->gb);
617    }
618    block[63] ^= mismatch & 1;
619
620    s->block_last_index[n] = i;
621    return 0;
622}
623
624/**
625 * Note: this function can read out of range and crash for corrupt streams.
626 * Changing this would eat up any speed benefits it has.
627 * Do not use "fast" flag if you need the code to be robust.
628 */
629static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s,
630                                                int16_t *block, int n)
631{
632    int level, dc, diff, i, j, run;
633    int component;
634    RLTable *rl;
635    uint8_t *const scantable = s->intra_scantable.permutated;
636    const uint16_t *quant_matrix;
637    const int qscale = s->qscale;
638
639    /* DC coefficient */
640    if (n < 4) {
641        quant_matrix = s->intra_matrix;
642        component    = 0;
643    } else {
644        quant_matrix = s->chroma_intra_matrix;
645        component    = (n & 1) + 1;
646    }
647    diff = decode_dc(&s->gb, component);
648    if (diff >= 0xffff)
649        return -1;
650    dc = s->last_dc[component];
651    dc += diff;
652    s->last_dc[component] = dc;
653    block[0] = dc << (3 - s->intra_dc_precision);
654    i = 0;
655    if (s->intra_vlc_format)
656        rl = &ff_rl_mpeg2;
657    else
658        rl = &ff_rl_mpeg1;
659
660    {
661        OPEN_READER(re, &s->gb);
662        /* now quantify & encode AC coefficients */
663        for (;;) {
664            UPDATE_CACHE(re, &s->gb);
665            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0],
666                       TEX_VLC_BITS, 2, 0);
667
668            if (level >= 64 || i > 63) {
669                break;
670            } else if (level != 0) {
671                i += run;
672                j = scantable[i];
673                level = (level * qscale * quant_matrix[j]) >> 4;
674                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
675                        SHOW_SBITS(re, &s->gb, 1);
676                LAST_SKIP_BITS(re, &s->gb, 1);
677            } else {
678                /* escape */
679                run = SHOW_UBITS(re, &s->gb, 6) + 1;
680                LAST_SKIP_BITS(re, &s->gb, 6);
681                UPDATE_CACHE(re, &s->gb);
682                level = SHOW_SBITS(re, &s->gb, 12);
683                SKIP_BITS(re, &s->gb, 12);
684                i += run;
685                j = scantable[i];
686                if (level < 0) {
687                    level = (-level * qscale * quant_matrix[j]) >> 4;
688                    level = -level;
689                } else {
690                    level = (level * qscale * quant_matrix[j]) >> 4;
691                }
692            }
693
694            block[j] = level;
695        }
696        CLOSE_READER(re, &s->gb);
697    }
698
699    s->block_last_index[n] = i;
700    return 0;
701}
702
703/******************************************/
704/* decoding */
705
706static inline int get_dmv(MpegEncContext *s)
707{
708    if (get_bits1(&s->gb))
709        return 1 - (get_bits1(&s->gb) << 1);
710    else
711        return 0;
712}
713
714static inline int get_qscale(MpegEncContext *s)
715{
716    int qscale = get_bits(&s->gb, 5);
717    if (s->q_scale_type)
718        return non_linear_qscale[qscale];
719    else
720        return qscale << 1;
721}
722
723
724/* motion type (for MPEG-2) */
725#define MT_FIELD 1
726#define MT_FRAME 2
727#define MT_16X8  2
728#define MT_DMV   3
729
730static int mpeg_decode_mb(MpegEncContext *s, int16_t block[12][64])
731{
732    int i, j, k, cbp, val, mb_type, motion_type;
733    const int mb_block_count = 4 + (1 << s->chroma_format);
734
735    av_dlog(s->avctx, "decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
736
737    av_assert2(s->mb_skipped == 0);
738
739    if (s->mb_skip_run-- != 0) {
740        if (s->pict_type == AV_PICTURE_TYPE_P) {
741            s->mb_skipped = 1;
742            s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] =
743                MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;
744        } else {
745            int mb_type;
746
747            if (s->mb_x)
748                mb_type = s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1];
749            else
750                // FIXME not sure if this is allowed in MPEG at all
751                mb_type = s->current_picture.mb_type[s->mb_width + (s->mb_y - 1) * s->mb_stride - 1];
752            if (IS_INTRA(mb_type)) {
753                av_log(s->avctx, AV_LOG_ERROR, "skip with previntra\n");
754                return -1;
755            }
756            s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] =
757                mb_type | MB_TYPE_SKIP;
758
759            if ((s->mv[0][0][0] | s->mv[0][0][1] | s->mv[1][0][0] | s->mv[1][0][1]) == 0)
760                s->mb_skipped = 1;
761        }
762
763        return 0;
764    }
765
766    switch (s->pict_type) {
767    default:
768    case AV_PICTURE_TYPE_I:
769        if (get_bits1(&s->gb) == 0) {
770            if (get_bits1(&s->gb) == 0) {
771                av_log(s->avctx, AV_LOG_ERROR,
772                       "invalid mb type in I Frame at %d %d\n",
773                       s->mb_x, s->mb_y);
774                return -1;
775            }
776            mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
777        } else {
778            mb_type = MB_TYPE_INTRA;
779        }
780        break;
781    case AV_PICTURE_TYPE_P:
782        mb_type = get_vlc2(&s->gb, ff_mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
783        if (mb_type < 0) {
784            av_log(s->avctx, AV_LOG_ERROR,
785                   "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
786            return -1;
787        }
788        mb_type = ptype2mb_type[mb_type];
789        break;
790    case AV_PICTURE_TYPE_B:
791        mb_type = get_vlc2(&s->gb, ff_mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
792        if (mb_type < 0) {
793            av_log(s->avctx, AV_LOG_ERROR,
794                   "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
795            return -1;
796        }
797        mb_type = btype2mb_type[mb_type];
798        break;
799    }
800    av_dlog(s->avctx, "mb_type=%x\n", mb_type);
801//    motion_type = 0; /* avoid warning */
802    if (IS_INTRA(mb_type)) {
803        s->bdsp.clear_blocks(s->block[0]);
804
805        if (!s->chroma_y_shift)
806            s->bdsp.clear_blocks(s->block[6]);
807
808        /* compute DCT type */
809        // FIXME: add an interlaced_dct coded var?
810        if (s->picture_structure == PICT_FRAME &&
811            !s->frame_pred_frame_dct)
812            s->interlaced_dct = get_bits1(&s->gb);
813
814        if (IS_QUANT(mb_type))
815            s->qscale = get_qscale(s);
816
817        if (s->concealment_motion_vectors) {
818            /* just parse them */
819            if (s->picture_structure != PICT_FRAME)
820                skip_bits1(&s->gb);  /* field select */
821
822            s->mv[0][0][0]      =
823            s->last_mv[0][0][0] =
824            s->last_mv[0][1][0] = mpeg_decode_motion(s, s->mpeg_f_code[0][0],
825                                                     s->last_mv[0][0][0]);
826            s->mv[0][0][1]      =
827            s->last_mv[0][0][1] =
828            s->last_mv[0][1][1] = mpeg_decode_motion(s, s->mpeg_f_code[0][1],
829                                                     s->last_mv[0][0][1]);
830
831            skip_bits1(&s->gb); /* marker */
832        } else {
833            /* reset mv prediction */
834            memset(s->last_mv, 0, sizeof(s->last_mv));
835        }
836        s->mb_intra = 1;
837        // if 1, we memcpy blocks in xvmcvideo
838        if ((CONFIG_MPEG1_XVMC_HWACCEL || CONFIG_MPEG2_XVMC_HWACCEL) && s->pack_pblocks)
839            ff_xvmc_pack_pblocks(s, -1); // inter are always full blocks
840
841        if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
842            if (s->flags2 & CODEC_FLAG2_FAST) {
843                for (i = 0; i < 6; i++)
844                    mpeg2_fast_decode_block_intra(s, *s->pblocks[i], i);
845            } else {
846                for (i = 0; i < mb_block_count; i++)
847                    if (mpeg2_decode_block_intra(s, *s->pblocks[i], i) < 0)
848                        return -1;
849            }
850        } else {
851            for (i = 0; i < 6; i++)
852                if (mpeg1_decode_block_intra(s, *s->pblocks[i], i) < 0)
853                    return -1;
854        }
855    } else {
856        if (mb_type & MB_TYPE_ZERO_MV) {
857            av_assert2(mb_type & MB_TYPE_CBP);
858
859            s->mv_dir = MV_DIR_FORWARD;
860            if (s->picture_structure == PICT_FRAME) {
861                if (s->picture_structure == PICT_FRAME
862                    && !s->frame_pred_frame_dct)
863                    s->interlaced_dct = get_bits1(&s->gb);
864                s->mv_type = MV_TYPE_16X16;
865            } else {
866                s->mv_type            = MV_TYPE_FIELD;
867                mb_type              |= MB_TYPE_INTERLACED;
868                s->field_select[0][0] = s->picture_structure - 1;
869            }
870
871            if (IS_QUANT(mb_type))
872                s->qscale = get_qscale(s);
873
874            s->last_mv[0][0][0] = 0;
875            s->last_mv[0][0][1] = 0;
876            s->last_mv[0][1][0] = 0;
877            s->last_mv[0][1][1] = 0;
878            s->mv[0][0][0]      = 0;
879            s->mv[0][0][1]      = 0;
880        } else {
881            av_assert2(mb_type & MB_TYPE_L0L1);
882            // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
883            /* get additional motion vector type */
884            if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) {
885                motion_type = MT_FRAME;
886            } else {
887                motion_type = get_bits(&s->gb, 2);
888                if (s->picture_structure == PICT_FRAME && HAS_CBP(mb_type))
889                    s->interlaced_dct = get_bits1(&s->gb);
890            }
891
892            if (IS_QUANT(mb_type))
893                s->qscale = get_qscale(s);
894
895            /* motion vectors */
896            s->mv_dir = (mb_type >> 13) & 3;
897            av_dlog(s->avctx, "motion_type=%d\n", motion_type);
898            switch (motion_type) {
899            case MT_FRAME: /* or MT_16X8 */
900                if (s->picture_structure == PICT_FRAME) {
901                    mb_type   |= MB_TYPE_16x16;
902                    s->mv_type = MV_TYPE_16X16;
903                    for (i = 0; i < 2; i++) {
904                        if (USES_LIST(mb_type, i)) {
905                            /* MT_FRAME */
906                            s->mv[i][0][0]      =
907                            s->last_mv[i][0][0] =
908                            s->last_mv[i][1][0] =
909                                mpeg_decode_motion(s, s->mpeg_f_code[i][0],
910                                                   s->last_mv[i][0][0]);
911                            s->mv[i][0][1]      =
912                            s->last_mv[i][0][1] =
913                            s->last_mv[i][1][1] =
914                                mpeg_decode_motion(s, s->mpeg_f_code[i][1],
915                                                   s->last_mv[i][0][1]);
916                            /* full_pel: only for MPEG-1 */
917                            if (s->full_pel[i]) {
918                                s->mv[i][0][0] <<= 1;
919                                s->mv[i][0][1] <<= 1;
920                            }
921                        }
922                    }
923                } else {
924                    mb_type   |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
925                    s->mv_type = MV_TYPE_16X8;
926                    for (i = 0; i < 2; i++) {
927                        if (USES_LIST(mb_type, i)) {
928                            /* MT_16X8 */
929                            for (j = 0; j < 2; j++) {
930                                s->field_select[i][j] = get_bits1(&s->gb);
931                                for (k = 0; k < 2; k++) {
932                                    val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
933                                                             s->last_mv[i][j][k]);
934                                    s->last_mv[i][j][k] = val;
935                                    s->mv[i][j][k]      = val;
936                                }
937                            }
938                        }
939                    }
940                }
941                break;
942            case MT_FIELD:
943                s->mv_type = MV_TYPE_FIELD;
944                if (s->picture_structure == PICT_FRAME) {
945                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
946                    for (i = 0; i < 2; i++) {
947                        if (USES_LIST(mb_type, i)) {
948                            for (j = 0; j < 2; j++) {
949                                s->field_select[i][j] = get_bits1(&s->gb);
950                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
951                                                         s->last_mv[i][j][0]);
952                                s->last_mv[i][j][0] = val;
953                                s->mv[i][j][0]      = val;
954                                av_dlog(s->avctx, "fmx=%d\n", val);
955                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
956                                                         s->last_mv[i][j][1] >> 1);
957                                s->last_mv[i][j][1] = val << 1;
958                                s->mv[i][j][1]      = val;
959                                av_dlog(s->avctx, "fmy=%d\n", val);
960                            }
961                        }
962                    }
963                } else {
964                    av_assert0(!s->progressive_sequence);
965                    mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
966                    for (i = 0; i < 2; i++) {
967                        if (USES_LIST(mb_type, i)) {
968                            s->field_select[i][0] = get_bits1(&s->gb);
969                            for (k = 0; k < 2; k++) {
970                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
971                                                         s->last_mv[i][0][k]);
972                                s->last_mv[i][0][k] = val;
973                                s->last_mv[i][1][k] = val;
974                                s->mv[i][0][k]      = val;
975                            }
976                        }
977                    }
978                }
979                break;
980            case MT_DMV:
981                if (s->progressive_sequence){
982                    av_log(s->avctx, AV_LOG_ERROR, "MT_DMV in progressive_sequence\n");
983                    return -1;
984                }
985                s->mv_type = MV_TYPE_DMV;
986                for (i = 0; i < 2; i++) {
987                    if (USES_LIST(mb_type, i)) {
988                        int dmx, dmy, mx, my, m;
989                        const int my_shift = s->picture_structure == PICT_FRAME;
990
991                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
992                                                s->last_mv[i][0][0]);
993                        s->last_mv[i][0][0] = mx;
994                        s->last_mv[i][1][0] = mx;
995                        dmx = get_dmv(s);
996                        my  = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
997                                                 s->last_mv[i][0][1] >> my_shift);
998                        dmy = get_dmv(s);
999
1000
1001                        s->last_mv[i][0][1] = my << my_shift;
1002                        s->last_mv[i][1][1] = my << my_shift;
1003
1004                        s->mv[i][0][0] = mx;
1005                        s->mv[i][0][1] = my;
1006                        s->mv[i][1][0] = mx; // not used
1007                        s->mv[i][1][1] = my; // not used
1008
1009                        if (s->picture_structure == PICT_FRAME) {
1010                            mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
1011
1012                            // m = 1 + 2 * s->top_field_first;
1013                            m = s->top_field_first ? 1 : 3;
1014
1015                            /* top -> top pred */
1016                            s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1017                            s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
1018                            m = 4 - m;
1019                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1020                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
1021                        } else {
1022                            mb_type |= MB_TYPE_16x16;
1023
1024                            s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
1025                            s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
1026                            if (s->picture_structure == PICT_TOP_FIELD)
1027                                s->mv[i][2][1]--;
1028                            else
1029                                s->mv[i][2][1]++;
1030                        }
1031                    }
1032                }
1033                break;
1034            default:
1035                av_log(s->avctx, AV_LOG_ERROR,
1036                       "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
1037                return -1;
1038            }
1039        }
1040
1041        s->mb_intra = 0;
1042        if (HAS_CBP(mb_type)) {
1043            s->bdsp.clear_blocks(s->block[0]);
1044
1045            cbp = get_vlc2(&s->gb, ff_mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
1046            if (mb_block_count > 6) {
1047                cbp <<= mb_block_count - 6;
1048                cbp  |= get_bits(&s->gb, mb_block_count - 6);
1049                s->bdsp.clear_blocks(s->block[6]);
1050            }
1051            if (cbp <= 0) {
1052                av_log(s->avctx, AV_LOG_ERROR,
1053                       "invalid cbp %d at %d %d\n", cbp, s->mb_x, s->mb_y);
1054                return -1;
1055            }
1056
1057            // if 1, we memcpy blocks in xvmcvideo
1058            if ((CONFIG_MPEG1_XVMC_HWACCEL || CONFIG_MPEG2_XVMC_HWACCEL) && s->pack_pblocks)
1059                ff_xvmc_pack_pblocks(s, cbp);
1060
1061            if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1062                if (s->flags2 & CODEC_FLAG2_FAST) {
1063                    for (i = 0; i < 6; i++) {
1064                        if (cbp & 32)
1065                            mpeg2_fast_decode_block_non_intra(s, *s->pblocks[i], i);
1066                        else
1067                            s->block_last_index[i] = -1;
1068                        cbp += cbp;
1069                    }
1070                } else {
1071                    cbp <<= 12 - mb_block_count;
1072
1073                    for (i = 0; i < mb_block_count; i++) {
1074                        if (cbp & (1 << 11)) {
1075                            if (mpeg2_decode_block_non_intra(s, *s->pblocks[i], i) < 0)
1076                                return -1;
1077                        } else {
1078                            s->block_last_index[i] = -1;
1079                        }
1080                        cbp += cbp;
1081                    }
1082                }
1083            } else {
1084                if (s->flags2 & CODEC_FLAG2_FAST) {
1085                    for (i = 0; i < 6; i++) {
1086                        if (cbp & 32)
1087                            mpeg1_fast_decode_block_inter(s, *s->pblocks[i], i);
1088                        else
1089                            s->block_last_index[i] = -1;
1090                        cbp += cbp;
1091                    }
1092                } else {
1093                    for (i = 0; i < 6; i++) {
1094                        if (cbp & 32) {
1095                            if (mpeg1_decode_block_inter(s, *s->pblocks[i], i) < 0)
1096                                return -1;
1097                        } else {
1098                            s->block_last_index[i] = -1;
1099                        }
1100                        cbp += cbp;
1101                    }
1102                }
1103            }
1104        } else {
1105            for (i = 0; i < 12; i++)
1106                s->block_last_index[i] = -1;
1107        }
1108    }
1109
1110    s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride] = mb_type;
1111
1112    return 0;
1113}
1114
1115static av_cold int mpeg_decode_init(AVCodecContext *avctx)
1116{
1117    Mpeg1Context *s    = avctx->priv_data;
1118    MpegEncContext *s2 = &s->mpeg_enc_ctx;
1119    int i;
1120
1121    /* we need some permutation to store matrices,
1122     * until MPV_common_init() sets the real permutation. */
1123    for (i = 0; i < 64; i++)
1124        s2->idsp.idct_permutation[i] = i;
1125
1126    ff_MPV_decode_defaults(s2);
1127
1128    s->mpeg_enc_ctx.avctx  = avctx;
1129    s->mpeg_enc_ctx.flags  = avctx->flags;
1130    s->mpeg_enc_ctx.flags2 = avctx->flags2;
1131    ff_mpeg12_common_init(&s->mpeg_enc_ctx);
1132    ff_mpeg12_init_vlcs();
1133
1134    s->mpeg_enc_ctx_allocated      = 0;
1135    s->mpeg_enc_ctx.picture_number = 0;
1136    s->repeat_field                = 0;
1137    s->mpeg_enc_ctx.codec_id       = avctx->codec->id;
1138    avctx->color_range             = AVCOL_RANGE_MPEG;
1139    if (avctx->codec->id == AV_CODEC_ID_MPEG1VIDEO)
1140        avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1141    else
1142        avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1143    return 0;
1144}
1145
1146static int mpeg_decode_update_thread_context(AVCodecContext *avctx,
1147                                             const AVCodecContext *avctx_from)
1148{
1149    Mpeg1Context *ctx = avctx->priv_data, *ctx_from = avctx_from->priv_data;
1150    MpegEncContext *s = &ctx->mpeg_enc_ctx, *s1 = &ctx_from->mpeg_enc_ctx;
1151    int err;
1152
1153    if (avctx == avctx_from               ||
1154        !ctx_from->mpeg_enc_ctx_allocated ||
1155        !s1->context_initialized)
1156        return 0;
1157
1158    err = ff_mpeg_update_thread_context(avctx, avctx_from);
1159    if (err)
1160        return err;
1161
1162    if (!ctx->mpeg_enc_ctx_allocated)
1163        memcpy(s + 1, s1 + 1, sizeof(Mpeg1Context) - sizeof(MpegEncContext));
1164
1165    if (!(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay))
1166        s->picture_number++;
1167
1168    return 0;
1169}
1170
1171static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm,
1172                                 const uint8_t *new_perm)
1173{
1174    uint16_t temp_matrix[64];
1175    int i;
1176
1177    memcpy(temp_matrix, matrix, 64 * sizeof(uint16_t));
1178
1179    for (i = 0; i < 64; i++)
1180        matrix[new_perm[i]] = temp_matrix[old_perm[i]];
1181}
1182
1183static const enum AVPixelFormat mpeg1_hwaccel_pixfmt_list_420[] = {
1184#if CONFIG_MPEG1_XVMC_HWACCEL
1185    AV_PIX_FMT_XVMC,
1186#endif
1187#if CONFIG_MPEG1_VDPAU_HWACCEL
1188    AV_PIX_FMT_VDPAU_MPEG1,
1189    AV_PIX_FMT_VDPAU,
1190#endif
1191    AV_PIX_FMT_YUV420P,
1192    AV_PIX_FMT_NONE
1193};
1194
1195static const enum AVPixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
1196#if CONFIG_MPEG2_XVMC_HWACCEL
1197    AV_PIX_FMT_XVMC,
1198#endif
1199#if CONFIG_MPEG2_VDPAU_HWACCEL
1200    AV_PIX_FMT_VDPAU_MPEG2,
1201    AV_PIX_FMT_VDPAU,
1202#endif
1203#if CONFIG_MPEG2_DXVA2_HWACCEL
1204    AV_PIX_FMT_DXVA2_VLD,
1205#endif
1206#if CONFIG_MPEG2_VAAPI_HWACCEL
1207    AV_PIX_FMT_VAAPI_VLD,
1208#endif
1209    AV_PIX_FMT_YUV420P,
1210    AV_PIX_FMT_NONE
1211};
1212
1213static inline int uses_vdpau(AVCodecContext *avctx) {
1214    return avctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG1 || avctx->pix_fmt == AV_PIX_FMT_VDPAU_MPEG2;
1215}
1216
1217static enum AVPixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)
1218{
1219    Mpeg1Context *s1  = avctx->priv_data;
1220    MpegEncContext *s = &s1->mpeg_enc_ctx;
1221
1222    if (s->chroma_format < 2)
1223        return ff_thread_get_format(avctx,
1224                                avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO ?
1225                                mpeg1_hwaccel_pixfmt_list_420 :
1226                                mpeg2_hwaccel_pixfmt_list_420);
1227    else if (s->chroma_format == 2)
1228        return AV_PIX_FMT_YUV422P;
1229    else
1230        return AV_PIX_FMT_YUV444P;
1231}
1232
1233static void setup_hwaccel_for_pixfmt(AVCodecContext *avctx)
1234{
1235    // until then pix_fmt may be changed right after codec init
1236    if (avctx->hwaccel || uses_vdpau(avctx))
1237        if (avctx->idct_algo == FF_IDCT_AUTO)
1238            avctx->idct_algo = FF_IDCT_SIMPLE;
1239
1240    if (avctx->hwaccel && avctx->pix_fmt == AV_PIX_FMT_XVMC) {
1241        Mpeg1Context *s1 = avctx->priv_data;
1242        MpegEncContext *s = &s1->mpeg_enc_ctx;
1243
1244        s->pack_pblocks = 1;
1245#if FF_API_XVMC
1246        avctx->xvmc_acceleration = 2;
1247#endif /* FF_API_XVMC */
1248    }
1249}
1250
1251/* Call this function when we know all parameters.
1252 * It may be called in different places for MPEG-1 and MPEG-2. */
1253static int mpeg_decode_postinit(AVCodecContext *avctx)
1254{
1255    Mpeg1Context *s1  = avctx->priv_data;
1256    MpegEncContext *s = &s1->mpeg_enc_ctx;
1257    uint8_t old_permutation[64];
1258    int ret;
1259
1260    if ((s1->mpeg_enc_ctx_allocated == 0)                   ||
1261        avctx->coded_width       != s->width                ||
1262        avctx->coded_height      != s->height               ||
1263        s1->save_width           != s->width                ||
1264        s1->save_height          != s->height               ||
1265        s1->save_aspect_info     != s->aspect_ratio_info    ||
1266        (s1->save_progressive_seq != s->progressive_sequence && FFALIGN(s->height, 16) != FFALIGN(s->height, 32)) ||
1267        0) {
1268        if (s1->mpeg_enc_ctx_allocated) {
1269            ParseContext pc = s->parse_context;
1270            s->parse_context.buffer = 0;
1271            ff_MPV_common_end(s);
1272            s->parse_context = pc;
1273            s1->mpeg_enc_ctx_allocated = 0;
1274        }
1275
1276        if ((s->width == 0) || (s->height == 0))
1277            return -2;
1278
1279        ret = ff_set_dimensions(avctx, s->width, s->height);
1280        if (ret < 0)
1281            return ret;
1282
1283        if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->bit_rate) {
1284            avctx->rc_max_rate = s->bit_rate;
1285        } else if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && s->bit_rate &&
1286                   (s->bit_rate != 0x3FFFF*400 || s->vbv_delay != 0xFFFF)) {
1287            avctx->bit_rate = s->bit_rate;
1288        }
1289        s1->save_aspect_info     = s->aspect_ratio_info;
1290        s1->save_width           = s->width;
1291        s1->save_height          = s->height;
1292        s1->save_progressive_seq = s->progressive_sequence;
1293
1294        /* low_delay may be forced, in this case we will have B-frames
1295         * that behave like P-frames. */
1296        avctx->has_b_frames = !s->low_delay;
1297
1298        if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
1299            // MPEG-1 fps
1300            avctx->time_base.den = ff_mpeg12_frame_rate_tab[s->frame_rate_index].num;
1301            avctx->time_base.num = ff_mpeg12_frame_rate_tab[s->frame_rate_index].den;
1302            // MPEG-1 aspect
1303            avctx->sample_aspect_ratio = av_d2q(1.0 / ff_mpeg1_aspect[s->aspect_ratio_info], 255);
1304            avctx->ticks_per_frame     = 1;
1305        } else { // MPEG-2
1306            // MPEG-2 fps
1307            av_reduce(&s->avctx->time_base.den,
1308                      &s->avctx->time_base.num,
1309                      ff_mpeg12_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num * 2,
1310                      ff_mpeg12_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
1311                      1 << 30);
1312            avctx->ticks_per_frame = 2;
1313            // MPEG-2 aspect
1314            if (s->aspect_ratio_info > 1) {
1315                AVRational dar =
1316                    av_mul_q(av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1317                                      (AVRational) { s1->pan_scan.width,
1318                                                     s1->pan_scan.height }),
1319                             (AVRational) { s->width, s->height });
1320
1321                /* We ignore the spec here and guess a bit as reality does not
1322                 * match the spec, see for example res_change_ffmpeg_aspect.ts
1323                 * and sequence-display-aspect.mpg.
1324                 * issue1613, 621, 562 */
1325                if ((s1->pan_scan.width == 0) || (s1->pan_scan.height == 0) ||
1326                    (av_cmp_q(dar, (AVRational) { 4, 3 }) &&
1327                     av_cmp_q(dar, (AVRational) { 16, 9 }))) {
1328                    s->avctx->sample_aspect_ratio =
1329                        av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1330                                 (AVRational) { s->width, s->height });
1331                } else {
1332                    s->avctx->sample_aspect_ratio =
1333                        av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1334                                 (AVRational) { s1->pan_scan.width, s1->pan_scan.height });
1335// issue1613 4/3 16/9 -> 16/9
1336// res_change_ffmpeg_aspect.ts 4/3 225/44 ->4/3
1337// widescreen-issue562.mpg 4/3 16/9 -> 16/9
1338//                    s->avctx->sample_aspect_ratio = av_mul_q(s->avctx->sample_aspect_ratio, (AVRational) {s->width, s->height});
1339                    av_dlog(avctx, "A %d/%d\n",
1340                            ff_mpeg2_aspect[s->aspect_ratio_info].num,
1341                            ff_mpeg2_aspect[s->aspect_ratio_info].den);
1342                    av_dlog(avctx, "B %d/%d\n", s->avctx->sample_aspect_ratio.num,
1343                            s->avctx->sample_aspect_ratio.den);
1344                }
1345            } else {
1346                s->avctx->sample_aspect_ratio =
1347                    ff_mpeg2_aspect[s->aspect_ratio_info];
1348            }
1349        } // MPEG-2
1350
1351        ff_set_sar(s->avctx, s->avctx->sample_aspect_ratio);
1352
1353        avctx->pix_fmt = mpeg_get_pixelformat(avctx);
1354        setup_hwaccel_for_pixfmt(avctx);
1355
1356        /* Quantization matrices may need reordering
1357         * if DCT permutation is changed. */
1358        memcpy(old_permutation, s->idsp.idct_permutation, 64 * sizeof(uint8_t));
1359
1360        if (ff_MPV_common_init(s) < 0)
1361            return -2;
1362
1363        quant_matrix_rebuild(s->intra_matrix,        old_permutation, s->idsp.idct_permutation);
1364        quant_matrix_rebuild(s->inter_matrix,        old_permutation, s->idsp.idct_permutation);
1365        quant_matrix_rebuild(s->chroma_intra_matrix, old_permutation, s->idsp.idct_permutation);
1366        quant_matrix_rebuild(s->chroma_inter_matrix, old_permutation, s->idsp.idct_permutation);
1367
1368        s1->mpeg_enc_ctx_allocated = 1;
1369    }
1370    return 0;
1371}
1372
1373static int mpeg1_decode_picture(AVCodecContext *avctx, const uint8_t *buf,
1374                                int buf_size)
1375{
1376    Mpeg1Context *s1  = avctx->priv_data;
1377    MpegEncContext *s = &s1->mpeg_enc_ctx;
1378    int ref, f_code, vbv_delay;
1379
1380    init_get_bits(&s->gb, buf, buf_size * 8);
1381
1382    ref = get_bits(&s->gb, 10); /* temporal ref */
1383    s->pict_type = get_bits(&s->gb, 3);
1384    if (s->pict_type == 0 || s->pict_type > 3)
1385        return -1;
1386
1387    vbv_delay = get_bits(&s->gb, 16);
1388    s->vbv_delay = vbv_delay;
1389    if (s->pict_type == AV_PICTURE_TYPE_P ||
1390        s->pict_type == AV_PICTURE_TYPE_B) {
1391        s->full_pel[0] = get_bits1(&s->gb);
1392        f_code = get_bits(&s->gb, 3);
1393        if (f_code == 0 && (avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)))
1394            return -1;
1395        f_code += !f_code;
1396        s->mpeg_f_code[0][0] = f_code;
1397        s->mpeg_f_code[0][1] = f_code;
1398    }
1399    if (s->pict_type == AV_PICTURE_TYPE_B) {
1400        s->full_pel[1] = get_bits1(&s->gb);
1401        f_code = get_bits(&s->gb, 3);
1402        if (f_code == 0 && (avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)))
1403            return -1;
1404        f_code += !f_code;
1405        s->mpeg_f_code[1][0] = f_code;
1406        s->mpeg_f_code[1][1] = f_code;
1407    }
1408    s->current_picture.f->pict_type = s->pict_type;
1409    s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1410
1411    if (avctx->debug & FF_DEBUG_PICT_INFO)
1412        av_log(avctx, AV_LOG_DEBUG,
1413               "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
1414
1415    s->y_dc_scale = 8;
1416    s->c_dc_scale = 8;
1417    return 0;
1418}
1419
1420static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
1421{
1422    MpegEncContext *s = &s1->mpeg_enc_ctx;
1423    int horiz_size_ext, vert_size_ext;
1424    int bit_rate_ext;
1425
1426    skip_bits(&s->gb, 1); /* profile and level esc*/
1427    s->avctx->profile       = get_bits(&s->gb, 3);
1428    s->avctx->level         = get_bits(&s->gb, 4);
1429    s->progressive_sequence = get_bits1(&s->gb);   /* progressive_sequence */
1430    s->chroma_format        = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
1431    horiz_size_ext          = get_bits(&s->gb, 2);
1432    vert_size_ext           = get_bits(&s->gb, 2);
1433    s->width  |= (horiz_size_ext << 12);
1434    s->height |= (vert_size_ext  << 12);
1435    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1436    s->bit_rate += (bit_rate_ext << 18) * 400;
1437    skip_bits1(&s->gb); /* marker */
1438    s->avctx->rc_buffer_size += get_bits(&s->gb, 8) * 1024 * 16 << 10;
1439
1440    s->low_delay = get_bits1(&s->gb);
1441    if (s->flags & CODEC_FLAG_LOW_DELAY)
1442        s->low_delay = 1;
1443
1444    s1->frame_rate_ext.num = get_bits(&s->gb, 2) + 1;
1445    s1->frame_rate_ext.den = get_bits(&s->gb, 5) + 1;
1446
1447    av_dlog(s->avctx, "sequence extension\n");
1448    s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
1449
1450    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1451        av_log(s->avctx, AV_LOG_DEBUG,
1452               "profile: %d, level: %d ps: %d cf:%d vbv buffer: %d, bitrate:%d\n",
1453               s->avctx->profile, s->avctx->level, s->progressive_sequence, s->chroma_format,
1454               s->avctx->rc_buffer_size, s->bit_rate);
1455}
1456
1457static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
1458{
1459    MpegEncContext *s = &s1->mpeg_enc_ctx;
1460    int color_description, w, h;
1461
1462    skip_bits(&s->gb, 3); /* video format */
1463    color_description = get_bits1(&s->gb);
1464    if (color_description) {
1465        s->avctx->color_primaries = get_bits(&s->gb, 8);
1466        s->avctx->color_trc       = get_bits(&s->gb, 8);
1467        s->avctx->colorspace      = get_bits(&s->gb, 8);
1468    }
1469    w = get_bits(&s->gb, 14);
1470    skip_bits(&s->gb, 1); // marker
1471    h = get_bits(&s->gb, 14);
1472    // remaining 3 bits are zero padding
1473
1474    s1->pan_scan.width  = 16 * w;
1475    s1->pan_scan.height = 16 * h;
1476
1477    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1478        av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
1479}
1480
1481static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
1482{
1483    MpegEncContext *s = &s1->mpeg_enc_ctx;
1484    int i, nofco;
1485
1486    nofco = 1;
1487    if (s->progressive_sequence) {
1488        if (s->repeat_first_field) {
1489            nofco++;
1490            if (s->top_field_first)
1491                nofco++;
1492        }
1493    } else {
1494        if (s->picture_structure == PICT_FRAME) {
1495            nofco++;
1496            if (s->repeat_first_field)
1497                nofco++;
1498        }
1499    }
1500    for (i = 0; i < nofco; i++) {
1501        s1->pan_scan.position[i][0] = get_sbits(&s->gb, 16);
1502        skip_bits(&s->gb, 1); // marker
1503        s1->pan_scan.position[i][1] = get_sbits(&s->gb, 16);
1504        skip_bits(&s->gb, 1); // marker
1505    }
1506
1507    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1508        av_log(s->avctx, AV_LOG_DEBUG,
1509               "pde (%"PRId16",%"PRId16") (%"PRId16",%"PRId16") (%"PRId16",%"PRId16")\n",
1510               s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
1511               s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
1512               s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]);
1513}
1514
1515static int load_matrix(MpegEncContext *s, uint16_t matrix0[64],
1516                       uint16_t matrix1[64], int intra)
1517{
1518    int i;
1519
1520    for (i = 0; i < 64; i++) {
1521        int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1522        int v = get_bits(&s->gb, 8);
1523        if (v == 0) {
1524            av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");
1525            return -1;
1526        }
1527        if (intra && i == 0 && v != 8) {
1528            av_log(s->avctx, AV_LOG_DEBUG, "intra matrix specifies invalid DC quantizer %d, ignoring\n", v);
1529            v = 8; // needed by pink.mpg / issue1046
1530        }
1531        matrix0[j] = v;
1532        if (matrix1)
1533            matrix1[j] = v;
1534    }
1535    return 0;
1536}
1537
1538static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1539{
1540    av_dlog(s->avctx, "matrix extension\n");
1541
1542    if (get_bits1(&s->gb))
1543        load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
1544    if (get_bits1(&s->gb))
1545        load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
1546    if (get_bits1(&s->gb))
1547        load_matrix(s, s->chroma_intra_matrix, NULL, 1);
1548    if (get_bits1(&s->gb))
1549        load_matrix(s, s->chroma_inter_matrix, NULL, 0);
1550}
1551
1552static void mpeg_decode_picture_coding_extension(Mpeg1Context *s1)
1553{
1554    MpegEncContext *s = &s1->mpeg_enc_ctx;
1555
1556    s->full_pel[0]       = s->full_pel[1] = 0;
1557    s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1558    s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1559    s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1560    s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1561    if (!s->pict_type && s1->mpeg_enc_ctx_allocated) {
1562        av_log(s->avctx, AV_LOG_ERROR,
1563               "Missing picture start code, guessing missing values\n");
1564        if (s->mpeg_f_code[1][0] == 15 && s->mpeg_f_code[1][1] == 15) {
1565            if (s->mpeg_f_code[0][0] == 15 && s->mpeg_f_code[0][1] == 15)
1566                s->pict_type = AV_PICTURE_TYPE_I;
1567            else
1568                s->pict_type = AV_PICTURE_TYPE_P;
1569        } else
1570            s->pict_type = AV_PICTURE_TYPE_B;
1571        s->current_picture.f->pict_type = s->pict_type;
1572        s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1573    }
1574    s->mpeg_f_code[0][0] += !s->mpeg_f_code[0][0];
1575    s->mpeg_f_code[0][1] += !s->mpeg_f_code[0][1];
1576    s->mpeg_f_code[1][0] += !s->mpeg_f_code[1][0];
1577    s->mpeg_f_code[1][1] += !s->mpeg_f_code[1][1];
1578
1579    s->intra_dc_precision         = get_bits(&s->gb, 2);
1580    s->picture_structure          = get_bits(&s->gb, 2);
1581    s->top_field_first            = get_bits1(&s->gb);
1582    s->frame_pred_frame_dct       = get_bits1(&s->gb);
1583    s->concealment_motion_vectors = get_bits1(&s->gb);
1584    s->q_scale_type               = get_bits1(&s->gb);
1585    s->intra_vlc_format           = get_bits1(&s->gb);
1586    s->alternate_scan             = get_bits1(&s->gb);
1587    s->repeat_first_field         = get_bits1(&s->gb);
1588    s->chroma_420_type            = get_bits1(&s->gb);
1589    s->progressive_frame          = get_bits1(&s->gb);
1590
1591    if (s->alternate_scan) {
1592        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
1593        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
1594    } else {
1595        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
1596        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
1597    }
1598
1599    /* composite display not parsed */
1600    av_dlog(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
1601    av_dlog(s->avctx, "picture_structure=%d\n", s->picture_structure);
1602    av_dlog(s->avctx, "top field first=%d\n", s->top_field_first);
1603    av_dlog(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
1604    av_dlog(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
1605    av_dlog(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
1606    av_dlog(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
1607    av_dlog(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1608    av_dlog(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
1609}
1610
1611static int mpeg_field_start(MpegEncContext *s, const uint8_t *buf, int buf_size)
1612{
1613    AVCodecContext *avctx = s->avctx;
1614    Mpeg1Context *s1      = (Mpeg1Context *) s;
1615
1616    /* start frame decoding */
1617    if (s->first_field || s->picture_structure == PICT_FRAME) {
1618        AVFrameSideData *pan_scan;
1619
1620        if (ff_MPV_frame_start(s, avctx) < 0)
1621            return -1;
1622
1623        ff_mpeg_er_frame_start(s);
1624
1625        /* first check if we must repeat the frame */
1626        s->current_picture_ptr->f->repeat_pict = 0;
1627        if (s->repeat_first_field) {
1628            if (s->progressive_sequence) {
1629                if (s->top_field_first)
1630                    s->current_picture_ptr->f->repeat_pict = 4;
1631                else
1632                    s->current_picture_ptr->f->repeat_pict = 2;
1633            } else if (s->progressive_frame) {
1634                s->current_picture_ptr->f->repeat_pict = 1;
1635            }
1636        }
1637
1638        pan_scan = av_frame_new_side_data(s->current_picture_ptr->f,
1639                                          AV_FRAME_DATA_PANSCAN,
1640                                          sizeof(s1->pan_scan));
1641        if (!pan_scan)
1642            return AVERROR(ENOMEM);
1643        memcpy(pan_scan->data, &s1->pan_scan, sizeof(s1->pan_scan));
1644
1645        if (s1->a53_caption) {
1646            AVFrameSideData *sd = av_frame_new_side_data(
1647                s->current_picture_ptr->f, AV_FRAME_DATA_A53_CC,
1648                s1->a53_caption_size);
1649            if (sd)
1650                memcpy(sd->data, s1->a53_caption, s1->a53_caption_size);
1651            av_freep(&s1->a53_caption);
1652        }
1653
1654        if (s1->has_stereo3d) {
1655            AVStereo3D *stereo = av_stereo3d_create_side_data(s->current_picture_ptr->f);
1656            if (!stereo)
1657                return AVERROR(ENOMEM);
1658
1659            *stereo = s1->stereo3d;
1660            s1->has_stereo3d = 0;
1661        }
1662        if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME))
1663            ff_thread_finish_setup(avctx);
1664    } else { // second field
1665        int i;
1666
1667        if (!s->current_picture_ptr) {
1668            av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
1669            return -1;
1670        }
1671
1672        if (s->avctx->hwaccel &&
1673            (s->avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
1674            if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1675                av_log(avctx, AV_LOG_ERROR,
1676                       "hardware accelerator failed to decode first field\n");
1677        }
1678
1679        for (i = 0; i < 4; i++) {
1680            s->current_picture.f->data[i] = s->current_picture_ptr->f->data[i];
1681            if (s->picture_structure == PICT_BOTTOM_FIELD)
1682                s->current_picture.f->data[i] +=
1683                    s->current_picture_ptr->f->linesize[i];
1684        }
1685    }
1686
1687    if (avctx->hwaccel) {
1688        if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
1689            return -1;
1690    }
1691
1692    return 0;
1693}
1694
1695#define DECODE_SLICE_ERROR -1
1696#define DECODE_SLICE_OK     0
1697
1698/**
1699 * Decode a slice.
1700 * MpegEncContext.mb_y must be set to the MB row from the startcode.
1701 * @return DECODE_SLICE_ERROR if the slice is damaged,
1702 *         DECODE_SLICE_OK if this slice is OK
1703 */
1704static int mpeg_decode_slice(MpegEncContext *s, int mb_y,
1705                             const uint8_t **buf, int buf_size)
1706{
1707    AVCodecContext *avctx = s->avctx;
1708    const int lowres      = s->avctx->lowres;
1709    const int field_pic   = s->picture_structure != PICT_FRAME;
1710
1711    s->resync_mb_x =
1712    s->resync_mb_y = -1;
1713
1714    av_assert0(mb_y < s->mb_height);
1715
1716    init_get_bits(&s->gb, *buf, buf_size * 8);
1717    if (s->codec_id != AV_CODEC_ID_MPEG1VIDEO && s->mb_height > 2800/16)
1718        skip_bits(&s->gb, 3);
1719
1720    ff_mpeg1_clean_buffers(s);
1721    s->interlaced_dct = 0;
1722
1723    s->qscale = get_qscale(s);
1724
1725    if (s->qscale == 0) {
1726        av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
1727        return -1;
1728    }
1729
1730    /* extra slice info */
1731    if (skip_1stop_8data_bits(&s->gb) < 0)
1732        return AVERROR_INVALIDDATA;
1733
1734    s->mb_x = 0;
1735
1736    if (mb_y == 0 && s->codec_tag == AV_RL32("SLIF")) {
1737        skip_bits1(&s->gb);
1738    } else {
1739        while (get_bits_left(&s->gb) > 0) {
1740            int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,
1741                                MBINCR_VLC_BITS, 2);
1742            if (code < 0) {
1743                av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
1744                return -1;
1745            }
1746            if (code >= 33) {
1747                if (code == 33)
1748                    s->mb_x += 33;
1749                /* otherwise, stuffing, nothing to do */
1750            } else {
1751                s->mb_x += code;
1752                break;
1753            }
1754        }
1755    }
1756
1757    if (s->mb_x >= (unsigned) s->mb_width) {
1758        av_log(s->avctx, AV_LOG_ERROR, "initial skip overflow\n");
1759        return -1;
1760    }
1761
1762    if (avctx->hwaccel && avctx->hwaccel->decode_slice) {
1763        const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */
1764        int start_code = -1;
1765        buf_end = avpriv_find_start_code(buf_start + 2, *buf + buf_size, &start_code);
1766        if (buf_end < *buf + buf_size)
1767            buf_end -= 4;
1768        s->mb_y = mb_y;
1769        if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_end - buf_start) < 0)
1770            return DECODE_SLICE_ERROR;
1771        *buf = buf_end;
1772        return DECODE_SLICE_OK;
1773    }
1774
1775    s->resync_mb_x = s->mb_x;
1776    s->resync_mb_y = s->mb_y = mb_y;
1777    s->mb_skip_run = 0;
1778    ff_init_block_index(s);
1779
1780    if (s->mb_y == 0 && s->mb_x == 0 && (s->first_field || s->picture_structure == PICT_FRAME)) {
1781        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
1782            av_log(s->avctx, AV_LOG_DEBUG,
1783                   "qp:%d fc:%2d%2d%2d%2d %s %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n",
1784                   s->qscale,
1785                   s->mpeg_f_code[0][0], s->mpeg_f_code[0][1],
1786                   s->mpeg_f_code[1][0], s->mpeg_f_code[1][1],
1787                   s->pict_type  == AV_PICTURE_TYPE_I ? "I" :
1788                   (s->pict_type == AV_PICTURE_TYPE_P ? "P" :
1789                   (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
1790                   s->progressive_sequence ? "ps"  : "",
1791                   s->progressive_frame    ? "pf"  : "",
1792                   s->alternate_scan       ? "alt" : "",
1793                   s->top_field_first      ? "top" : "",
1794                   s->intra_dc_precision, s->picture_structure,
1795                   s->frame_pred_frame_dct, s->concealment_motion_vectors,
1796                   s->q_scale_type, s->intra_vlc_format,
1797                   s->repeat_first_field, s->chroma_420_type ? "420" : "");
1798        }
1799    }
1800
1801    for (;;) {
1802        // If 1, we memcpy blocks in xvmcvideo.
1803        if ((CONFIG_MPEG1_XVMC_HWACCEL || CONFIG_MPEG2_XVMC_HWACCEL) && s->pack_pblocks)
1804            ff_xvmc_init_block(s); // set s->block
1805
1806        if (mpeg_decode_mb(s, s->block) < 0)
1807            return -1;
1808
1809        // Note motion_val is normally NULL unless we want to extract the MVs.
1810        if (s->current_picture.motion_val[0] && !s->encoding) {
1811            const int wrap = s->b8_stride;
1812            int xy         = s->mb_x * 2 + s->mb_y * 2 * wrap;
1813            int b8_xy      = 4 * (s->mb_x + s->mb_y * s->mb_stride);
1814            int motion_x, motion_y, dir, i;
1815
1816            for (i = 0; i < 2; i++) {
1817                for (dir = 0; dir < 2; dir++) {
1818                    if (s->mb_intra ||
1819                        (dir == 1 && s->pict_type != AV_PICTURE_TYPE_B)) {
1820                        motion_x = motion_y = 0;
1821                    } else if (s->mv_type == MV_TYPE_16X16 ||
1822                               (s->mv_type == MV_TYPE_FIELD && field_pic)) {
1823                        motion_x = s->mv[dir][0][0];
1824                        motion_y = s->mv[dir][0][1];
1825                    } else { /* if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8)) */
1826                        motion_x = s->mv[dir][i][0];
1827                        motion_y = s->mv[dir][i][1];
1828                    }
1829
1830                    s->current_picture.motion_val[dir][xy][0]     = motion_x;
1831                    s->current_picture.motion_val[dir][xy][1]     = motion_y;
1832                    s->current_picture.motion_val[dir][xy + 1][0] = motion_x;
1833                    s->current_picture.motion_val[dir][xy + 1][1] = motion_y;
1834                    s->current_picture.ref_index [dir][b8_xy]     =
1835                    s->current_picture.ref_index [dir][b8_xy + 1] = s->field_select[dir][i];
1836                    av_assert2(s->field_select[dir][i] == 0 ||
1837                               s->field_select[dir][i] == 1);
1838                }
1839                xy    += wrap;
1840                b8_xy += 2;
1841            }
1842        }
1843
1844        s->dest[0] += 16 >> lowres;
1845        s->dest[1] +=(16 >> lowres) >> s->chroma_x_shift;
1846        s->dest[2] +=(16 >> lowres) >> s->chroma_x_shift;
1847
1848        ff_MPV_decode_mb(s, s->block);
1849
1850        if (++s->mb_x >= s->mb_width) {
1851            const int mb_size = 16 >> s->avctx->lowres;
1852
1853            ff_mpeg_draw_horiz_band(s, mb_size * (s->mb_y >> field_pic), mb_size);
1854            ff_MPV_report_decode_progress(s);
1855
1856            s->mb_x  = 0;
1857            s->mb_y += 1 << field_pic;
1858
1859            if (s->mb_y >= s->mb_height) {
1860                int left   = get_bits_left(&s->gb);
1861                int is_d10 = s->chroma_format == 2 &&
1862                             s->pict_type == AV_PICTURE_TYPE_I &&
1863                             avctx->profile == 0 && avctx->level == 5 &&
1864                             s->intra_dc_precision == 2 &&
1865                             s->q_scale_type == 1 && s->alternate_scan == 0 &&
1866                             s->progressive_frame == 0
1867                             /* vbv_delay == 0xBBB || 0xE10 */;
1868
1869                if (left >= 32 && !is_d10) {
1870                    GetBitContext gb = s->gb;
1871                    align_get_bits(&gb);
1872                    if (show_bits(&gb, 24) == 0x060E2B) {
1873                        av_log(avctx, AV_LOG_DEBUG, "Invalid MXF data found in video stream\n");
1874                        is_d10 = 1;
1875                    }
1876                }
1877
1878                if (left < 0 ||
1879                    (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10) ||
1880                    ((avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_AGGRESSIVE)) && left > 8)) {
1881                    av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n",
1882                           left, show_bits(&s->gb, FFMIN(left, 23)));
1883                    return -1;
1884                } else
1885                    goto eos;
1886            }
1887            if (s->mb_y >= ((s->height + 15) >> 4) &&
1888                s->progressive_frame &&
1889                !s->progressive_sequence &&
1890                get_bits_left(&s->gb) <= 8 &&
1891                get_bits_left(&s->gb) >= 0 &&
1892                s->mb_skip_run == -1 &&
1893                show_bits(&s->gb, 8) == 0)
1894                goto eos;
1895
1896            ff_init_block_index(s);
1897        }
1898
1899        /* skip mb handling */
1900        if (s->mb_skip_run == -1) {
1901            /* read increment again */
1902            s->mb_skip_run = 0;
1903            for (;;) {
1904                int code = get_vlc2(&s->gb, ff_mbincr_vlc.table,
1905                                    MBINCR_VLC_BITS, 2);
1906                if (code < 0) {
1907                    av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
1908                    return -1;
1909                }
1910                if (code >= 33) {
1911                    if (code == 33) {
1912                        s->mb_skip_run += 33;
1913                    } else if (code == 35) {
1914                        if (s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0) {
1915                            av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
1916                            return -1;
1917                        }
1918                        goto eos; /* end of slice */
1919                    }
1920                    /* otherwise, stuffing, nothing to do */
1921                } else {
1922                    s->mb_skip_run += code;
1923                    break;
1924                }
1925            }
1926            if (s->mb_skip_run) {
1927                int i;
1928                if (s->pict_type == AV_PICTURE_TYPE_I) {
1929                    av_log(s->avctx, AV_LOG_ERROR,
1930                           "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1931                    return -1;
1932                }
1933
1934                /* skip mb */
1935                s->mb_intra = 0;
1936                for (i = 0; i < 12; i++)
1937                    s->block_last_index[i] = -1;
1938                if (s->picture_structure == PICT_FRAME)
1939                    s->mv_type = MV_TYPE_16X16;
1940                else
1941                    s->mv_type = MV_TYPE_FIELD;
1942                if (s->pict_type == AV_PICTURE_TYPE_P) {
1943                    /* if P type, zero motion vector is implied */
1944                    s->mv_dir             = MV_DIR_FORWARD;
1945                    s->mv[0][0][0]        = s->mv[0][0][1]      = 0;
1946                    s->last_mv[0][0][0]   = s->last_mv[0][0][1] = 0;
1947                    s->last_mv[0][1][0]   = s->last_mv[0][1][1] = 0;
1948                    s->field_select[0][0] = (s->picture_structure - 1) & 1;
1949                } else {
1950                    /* if B type, reuse previous vectors and directions */
1951                    s->mv[0][0][0] = s->last_mv[0][0][0];
1952                    s->mv[0][0][1] = s->last_mv[0][0][1];
1953                    s->mv[1][0][0] = s->last_mv[1][0][0];
1954                    s->mv[1][0][1] = s->last_mv[1][0][1];
1955                }
1956            }
1957        }
1958    }
1959eos: // end of slice
1960    if (get_bits_left(&s->gb) < 0)
1961        return AVERROR_INVALIDDATA;
1962    *buf += (get_bits_count(&s->gb) - 1) / 8;
1963    av_dlog(s, "y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
1964    return 0;
1965}
1966
1967static int slice_decode_thread(AVCodecContext *c, void *arg)
1968{
1969    MpegEncContext *s   = *(void **) arg;
1970    const uint8_t *buf  = s->gb.buffer;
1971    int mb_y            = s->start_mb_y;
1972    const int field_pic = s->picture_structure != PICT_FRAME;
1973
1974    s->er.error_count = (3 * (s->end_mb_y - s->start_mb_y) * s->mb_width) >> field_pic;
1975
1976    for (;;) {
1977        uint32_t start_code;
1978        int ret;
1979
1980        ret = mpeg_decode_slice(s, mb_y, &buf, s->gb.buffer_end - buf);
1981        emms_c();
1982        av_dlog(c, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
1983                ret, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y,
1984                s->start_mb_y, s->end_mb_y, s->er.error_count);
1985        if (ret < 0) {
1986            if (c->err_recognition & AV_EF_EXPLODE)
1987                return ret;
1988            if (s->resync_mb_x >= 0 && s->resync_mb_y >= 0)
1989                ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1990                                s->mb_x, s->mb_y,
1991                                ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
1992        } else {
1993            ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1994                            s->mb_x - 1, s->mb_y,
1995                            ER_AC_END | ER_DC_END | ER_MV_END);
1996        }
1997
1998        if (s->mb_y == s->end_mb_y)
1999            return 0;
2000
2001        start_code = -1;
2002        buf        = avpriv_find_start_code(buf, s->gb.buffer_end, &start_code);
2003        mb_y       = start_code - SLICE_MIN_START_CODE;
2004        if (s->codec_id != AV_CODEC_ID_MPEG1VIDEO && s->mb_height > 2800/16)
2005            mb_y += (*buf&0xE0)<<2;
2006        mb_y <<= field_pic;
2007        if (s->picture_structure == PICT_BOTTOM_FIELD)
2008            mb_y++;
2009        if (mb_y < 0 || mb_y >= s->end_mb_y)
2010            return -1;
2011    }
2012}
2013
2014/**
2015 * Handle slice ends.
2016 * @return 1 if it seems to be the last slice
2017 */
2018static int slice_end(AVCodecContext *avctx, AVFrame *pict)
2019{
2020    Mpeg1Context *s1  = avctx->priv_data;
2021    MpegEncContext *s = &s1->mpeg_enc_ctx;
2022
2023    if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
2024        return 0;
2025
2026    if (s->avctx->hwaccel) {
2027        if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
2028            av_log(avctx, AV_LOG_ERROR,
2029                   "hardware accelerator failed to decode picture\n");
2030    }
2031
2032    /* end of slice reached */
2033    if (/* s->mb_y << field_pic == s->mb_height && */ !s->first_field && !s1->first_slice) {
2034        /* end of image */
2035
2036        ff_er_frame_end(&s->er);
2037
2038        ff_MPV_frame_end(s);
2039
2040        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
2041            int ret = av_frame_ref(pict, s->current_picture_ptr->f);
2042            if (ret < 0)
2043                return ret;
2044            ff_print_debug_info(s, s->current_picture_ptr, pict);
2045            ff_mpv_export_qp_table(s, pict, s->current_picture_ptr, FF_QSCALE_TYPE_MPEG2);
2046        } else {
2047            if (avctx->active_thread_type & FF_THREAD_FRAME)
2048                s->picture_number++;
2049            /* latency of 1 frame for I- and P-frames */
2050            /* XXX: use another variable than picture_number */
2051            if (s->last_picture_ptr != NULL) {
2052                int ret = av_frame_ref(pict, s->last_picture_ptr->f);
2053                if (ret < 0)
2054                    return ret;
2055                ff_print_debug_info(s, s->last_picture_ptr, pict);
2056                ff_mpv_export_qp_table(s, pict, s->last_picture_ptr, FF_QSCALE_TYPE_MPEG2);
2057            }
2058        }
2059
2060        return 1;
2061    } else {
2062        return 0;
2063    }
2064}
2065
2066static int mpeg1_decode_sequence(AVCodecContext *avctx,
2067                                 const uint8_t *buf, int buf_size)
2068{
2069    Mpeg1Context *s1  = avctx->priv_data;
2070    MpegEncContext *s = &s1->mpeg_enc_ctx;
2071    int width, height;
2072    int i, v, j;
2073
2074    init_get_bits(&s->gb, buf, buf_size * 8);
2075
2076    width  = get_bits(&s->gb, 12);
2077    height = get_bits(&s->gb, 12);
2078    if (width == 0 || height == 0) {
2079        av_log(avctx, AV_LOG_WARNING,
2080               "Invalid horizontal or vertical size value.\n");
2081        if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
2082            return AVERROR_INVALIDDATA;
2083    }
2084    s->aspect_ratio_info = get_bits(&s->gb, 4);
2085    if (s->aspect_ratio_info == 0) {
2086        av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
2087        if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
2088            return -1;
2089    }
2090    s->frame_rate_index = get_bits(&s->gb, 4);
2091    if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
2092        return -1;
2093    s->bit_rate = get_bits(&s->gb, 18) * 400;
2094    if (get_bits1(&s->gb) == 0) /* marker */
2095        return -1;
2096    s->width  = width;
2097    s->height = height;
2098
2099    s->avctx->rc_buffer_size = get_bits(&s->gb, 10) * 1024 * 16;
2100    skip_bits(&s->gb, 1);
2101
2102    /* get matrix */
2103    if (get_bits1(&s->gb)) {
2104        load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
2105    } else {
2106        for (i = 0; i < 64; i++) {
2107            j = s->idsp.idct_permutation[i];
2108            v = ff_mpeg1_default_intra_matrix[i];
2109            s->intra_matrix[j]        = v;
2110            s->chroma_intra_matrix[j] = v;
2111        }
2112    }
2113    if (get_bits1(&s->gb)) {
2114        load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
2115    } else {
2116        for (i = 0; i < 64; i++) {
2117            int j = s->idsp.idct_permutation[i];
2118            v = ff_mpeg1_default_non_intra_matrix[i];
2119            s->inter_matrix[j]        = v;
2120            s->chroma_inter_matrix[j] = v;
2121        }
2122    }
2123
2124    if (show_bits(&s->gb, 23) != 0) {
2125        av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2126        return -1;
2127    }
2128
2129    /* We set MPEG-2 parameters so that it emulates MPEG-1. */
2130    s->progressive_sequence = 1;
2131    s->progressive_frame    = 1;
2132    s->picture_structure    = PICT_FRAME;
2133    s->first_field          = 0;
2134    s->frame_pred_frame_dct = 1;
2135    s->chroma_format        = 1;
2136    s->codec_id             =
2137    s->avctx->codec_id      = AV_CODEC_ID_MPEG1VIDEO;
2138    s->out_format           = FMT_MPEG1;
2139    s->swap_uv              = 0; // AFAIK VCR2 does not have SEQ_HEADER
2140    if (s->flags & CODEC_FLAG_LOW_DELAY)
2141        s->low_delay = 1;
2142
2143    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2144        av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n",
2145               s->avctx->rc_buffer_size, s->bit_rate);
2146
2147    return 0;
2148}
2149
2150static int vcr2_init_sequence(AVCodecContext *avctx)
2151{
2152    Mpeg1Context *s1  = avctx->priv_data;
2153    MpegEncContext *s = &s1->mpeg_enc_ctx;
2154    int i, v;
2155
2156    /* start new MPEG-1 context decoding */
2157    s->out_format = FMT_MPEG1;
2158    if (s1->mpeg_enc_ctx_allocated) {
2159        ff_MPV_common_end(s);
2160        s1->mpeg_enc_ctx_allocated = 0;
2161    }
2162    s->width            = avctx->coded_width;
2163    s->height           = avctx->coded_height;
2164    avctx->has_b_frames = 0; // true?
2165    s->low_delay        = 1;
2166
2167    avctx->pix_fmt = mpeg_get_pixelformat(avctx);
2168    setup_hwaccel_for_pixfmt(avctx);
2169
2170    if (ff_MPV_common_init(s) < 0)
2171        return -1;
2172    s1->mpeg_enc_ctx_allocated = 1;
2173
2174    for (i = 0; i < 64; i++) {
2175        int j = s->idsp.idct_permutation[i];
2176        v = ff_mpeg1_default_intra_matrix[i];
2177        s->intra_matrix[j]        = v;
2178        s->chroma_intra_matrix[j] = v;
2179
2180        v = ff_mpeg1_default_non_intra_matrix[i];
2181        s->inter_matrix[j]        = v;
2182        s->chroma_inter_matrix[j] = v;
2183    }
2184
2185    s->progressive_sequence  = 1;
2186    s->progressive_frame     = 1;
2187    s->picture_structure     = PICT_FRAME;
2188    s->first_field           = 0;
2189    s->frame_pred_frame_dct  = 1;
2190    s->chroma_format         = 1;
2191    if (s->codec_tag == AV_RL32("BW10")) {
2192        s->codec_id              = s->avctx->codec_id = AV_CODEC_ID_MPEG1VIDEO;
2193    } else {
2194        s->swap_uv = 1; // in case of xvmc we need to swap uv for each MB
2195        s->codec_id              = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
2196    }
2197    s1->save_width           = s->width;
2198    s1->save_height          = s->height;
2199    s1->save_progressive_seq = s->progressive_sequence;
2200    return 0;
2201}
2202
2203static int mpeg_decode_a53_cc(AVCodecContext *avctx,
2204                              const uint8_t *p, int buf_size)
2205{
2206    Mpeg1Context *s1 = avctx->priv_data;
2207
2208    if (buf_size >= 6 &&
2209        p[0] == 'G' && p[1] == 'A' && p[2] == '9' && p[3] == '4' &&
2210        p[4] == 3 && (p[5] & 0x40)) {
2211        /* extract A53 Part 4 CC data */
2212        int cc_count = p[5] & 0x1f;
2213        if (cc_count > 0 && buf_size >= 7 + cc_count * 3) {
2214            av_freep(&s1->a53_caption);
2215            s1->a53_caption_size = cc_count * 3;
2216            s1->a53_caption      = av_malloc(s1->a53_caption_size);
2217            if (s1->a53_caption)
2218                memcpy(s1->a53_caption, p + 7, s1->a53_caption_size);
2219        }
2220        return 1;
2221    } else if (buf_size >= 11 &&
2222               p[0] == 'C' && p[1] == 'C' && p[2] == 0x01 && p[3] == 0xf8) {
2223        /* extract DVD CC data */
2224        int cc_count = 0;
2225        int i;
2226        // There is a caption count field in the data, but it is often
2227        // incorect.  So count the number of captions present.
2228        for (i = 5; i + 6 <= buf_size && ((p[i] & 0xfe) == 0xfe); i += 6)
2229            cc_count++;
2230        // Transform the DVD format into A53 Part 4 format
2231        if (cc_count > 0) {
2232            av_freep(&s1->a53_caption);
2233            s1->a53_caption_size = cc_count * 6;
2234            s1->a53_caption      = av_malloc(s1->a53_caption_size);
2235            if (s1->a53_caption) {
2236                uint8_t field1 = !!(p[4] & 0x80);
2237                uint8_t *cap = s1->a53_caption;
2238                p += 5;
2239                for (i = 0; i < cc_count; i++) {
2240                    cap[0] = (p[0] == 0xff && field1) ? 0xfc : 0xfd;
2241                    cap[1] = p[1];
2242                    cap[2] = p[2];
2243                    cap[3] = (p[3] == 0xff && !field1) ? 0xfc : 0xfd;
2244                    cap[4] = p[4];
2245                    cap[5] = p[5];
2246                    cap += 6;
2247                    p += 6;
2248                }
2249            }
2250        }
2251        return 1;
2252    }
2253    return 0;
2254}
2255
2256static void mpeg_decode_user_data(AVCodecContext *avctx,
2257                                  const uint8_t *p, int buf_size)
2258{
2259    Mpeg1Context *s = avctx->priv_data;
2260    const uint8_t *buf_end = p + buf_size;
2261
2262    if (buf_size > 29){
2263        int i;
2264        for(i=0; i<20; i++)
2265            if (!memcmp(p+i, "\0TMPGEXS\0", 9)){
2266                s->tmpgexs= 1;
2267            }
2268
2269/*        for(i=0; !(!p[i-2] && !p[i-1] && p[i]==1) && i<buf_size; i++){
2270            av_log(avctx, AV_LOG_ERROR, "%c", p[i]);
2271        }
2272            av_log(avctx, AV_LOG_ERROR, "\n");*/
2273    }
2274
2275    /* we parse the DTG active format information */
2276    if (buf_end - p >= 5 &&
2277        p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2278        int flags = p[4];
2279        p += 5;
2280        if (flags & 0x80) {
2281            /* skip event id */
2282            p += 2;
2283        }
2284        if (flags & 0x40) {
2285            if (buf_end - p < 1)
2286                return;
2287            avctx->dtg_active_format = p[0] & 0x0f;
2288        }
2289    } else if (buf_end - p >= 6 &&
2290               p[0] == 'J' && p[1] == 'P' && p[2] == '3' && p[3] == 'D' &&
2291               p[4] == 0x03) { // S3D_video_format_length
2292        // the 0x7F mask ignores the reserved_bit value
2293        const uint8_t S3D_video_format_type = p[5] & 0x7F;
2294
2295        if (S3D_video_format_type == 0x03 ||
2296            S3D_video_format_type == 0x04 ||
2297            S3D_video_format_type == 0x08 ||
2298            S3D_video_format_type == 0x23) {
2299            Mpeg1Context *s1   = avctx->priv_data;
2300
2301            s1->has_stereo3d = 1;
2302
2303            switch (S3D_video_format_type) {
2304            case 0x03:
2305                s1->stereo3d.type = AV_STEREO3D_SIDEBYSIDE;
2306                break;
2307            case 0x04:
2308                s1->stereo3d.type = AV_STEREO3D_TOPBOTTOM;
2309                break;
2310            case 0x08:
2311                s1->stereo3d.type = AV_STEREO3D_2D;
2312                break;
2313            case 0x23:
2314                s1->stereo3d.type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2315                break;
2316            }
2317        }
2318    } else if (mpeg_decode_a53_cc(avctx, p, buf_size)) {
2319        return;
2320    }
2321}
2322
2323static void mpeg_decode_gop(AVCodecContext *avctx,
2324                            const uint8_t *buf, int buf_size)
2325{
2326    Mpeg1Context *s1  = avctx->priv_data;
2327    MpegEncContext *s = &s1->mpeg_enc_ctx;
2328    int broken_link;
2329    int64_t tc;
2330
2331    init_get_bits(&s->gb, buf, buf_size * 8);
2332
2333    tc = avctx->timecode_frame_start = get_bits(&s->gb, 25);
2334
2335    s->closed_gop = get_bits1(&s->gb);
2336    /* broken_link indicate that after editing the
2337     * reference frames of the first B-Frames after GOP I-Frame
2338     * are missing (open gop) */
2339    broken_link = get_bits1(&s->gb);
2340
2341    if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2342        char tcbuf[AV_TIMECODE_STR_SIZE];
2343        av_timecode_make_mpeg_tc_string(tcbuf, tc);
2344        av_log(s->avctx, AV_LOG_DEBUG,
2345               "GOP (%s) closed_gop=%d broken_link=%d\n",
2346               tcbuf, s->closed_gop, broken_link);
2347    }
2348}
2349
2350static int decode_chunks(AVCodecContext *avctx, AVFrame *picture,
2351                         int *got_output, const uint8_t *buf, int buf_size)
2352{
2353    Mpeg1Context *s = avctx->priv_data;
2354    MpegEncContext *s2 = &s->mpeg_enc_ctx;
2355    const uint8_t *buf_ptr = buf;
2356    const uint8_t *buf_end = buf + buf_size;
2357    int ret, input_size;
2358    int last_code = 0, skip_frame = 0;
2359    int picture_start_code_seen = 0;
2360
2361    for (;;) {
2362        /* find next start code */
2363        uint32_t start_code = -1;
2364        buf_ptr = avpriv_find_start_code(buf_ptr, buf_end, &start_code);
2365        if (start_code > 0x1ff) {
2366            if (!skip_frame) {
2367                if (HAVE_THREADS &&
2368                    (avctx->active_thread_type & FF_THREAD_SLICE) &&
2369                    !avctx->hwaccel) {
2370                    int i;
2371                    av_assert0(avctx->thread_count > 1);
2372
2373                    avctx->execute(avctx, slice_decode_thread,
2374                                   &s2->thread_context[0], NULL,
2375                                   s->slice_count, sizeof(void *));
2376                    for (i = 0; i < s->slice_count; i++)
2377                        s2->er.error_count += s2->thread_context[i]->er.error_count;
2378                }
2379
2380                if ((CONFIG_MPEG_VDPAU_DECODER || CONFIG_MPEG1_VDPAU_DECODER)
2381                    && uses_vdpau(avctx))
2382                    ff_vdpau_mpeg_picture_complete(s2, buf, buf_size, s->slice_count);
2383
2384                ret = slice_end(avctx, picture);
2385                if (ret < 0)
2386                    return ret;
2387                else if (ret) {
2388                    // FIXME: merge with the stuff in mpeg_decode_slice
2389                    if (s2->last_picture_ptr || s2->low_delay)
2390                        *got_output = 1;
2391                }
2392            }
2393            s2->pict_type = 0;
2394
2395            if (avctx->err_recognition & AV_EF_EXPLODE && s2->er.error_count)
2396                return AVERROR_INVALIDDATA;
2397
2398            return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
2399        }
2400
2401        input_size = buf_end - buf_ptr;
2402
2403        if (avctx->debug & FF_DEBUG_STARTCODE)
2404            av_log(avctx, AV_LOG_DEBUG, "%3"PRIX32" at %"PTRDIFF_SPECIFIER" left %d\n",
2405                   start_code, buf_ptr - buf, input_size);
2406
2407        /* prepare data for next start code */
2408        switch (start_code) {
2409        case SEQ_START_CODE:
2410            if (last_code == 0) {
2411                mpeg1_decode_sequence(avctx, buf_ptr, input_size);
2412                if (buf != avctx->extradata)
2413                    s->sync = 1;
2414            } else {
2415                av_log(avctx, AV_LOG_ERROR,
2416                       "ignoring SEQ_START_CODE after %X\n", last_code);
2417                if (avctx->err_recognition & AV_EF_EXPLODE)
2418                    return AVERROR_INVALIDDATA;
2419            }
2420            break;
2421
2422        case PICTURE_START_CODE:
2423            if (picture_start_code_seen && s2->picture_structure == PICT_FRAME) {
2424               /* If it's a frame picture, there can't be more than one picture header.
2425                  Yet, it does happen and we need to handle it. */
2426               av_log(avctx, AV_LOG_WARNING, "ignoring extra picture following a frame-picture\n");
2427               break;
2428            }
2429            picture_start_code_seen = 1;
2430
2431            if (s2->width <= 0 || s2->height <= 0) {
2432                av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d.\n",
2433                       s2->width, s2->height);
2434                return AVERROR_INVALIDDATA;
2435            }
2436
2437            if (s->tmpgexs){
2438                s2->intra_dc_precision= 3;
2439                s2->intra_matrix[0]= 1;
2440            }
2441            if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) &&
2442                !avctx->hwaccel && s->slice_count) {
2443                int i;
2444
2445                avctx->execute(avctx, slice_decode_thread,
2446                               s2->thread_context, NULL,
2447                               s->slice_count, sizeof(void *));
2448                for (i = 0; i < s->slice_count; i++)
2449                    s2->er.error_count += s2->thread_context[i]->er.error_count;
2450                s->slice_count = 0;
2451            }
2452            if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {
2453                ret = mpeg_decode_postinit(avctx);
2454                if (ret < 0) {
2455                    av_log(avctx, AV_LOG_ERROR,
2456                           "mpeg_decode_postinit() failure\n");
2457                    return ret;
2458                }
2459
2460                /* We have a complete image: we try to decompress it. */
2461                if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)
2462                    s2->pict_type = 0;
2463                s->first_slice = 1;
2464                last_code      = PICTURE_START_CODE;
2465            } else {
2466                av_log(avctx, AV_LOG_ERROR,
2467                       "ignoring pic after %X\n", last_code);
2468                if (avctx->err_recognition & AV_EF_EXPLODE)
2469                    return AVERROR_INVALIDDATA;
2470            }
2471            break;
2472        case EXT_START_CODE:
2473            init_get_bits(&s2->gb, buf_ptr, input_size * 8);
2474
2475            switch (get_bits(&s2->gb, 4)) {
2476            case 0x1:
2477                if (last_code == 0) {
2478                    mpeg_decode_sequence_extension(s);
2479                } else {
2480                    av_log(avctx, AV_LOG_ERROR,
2481                           "ignoring seq ext after %X\n", last_code);
2482                    if (avctx->err_recognition & AV_EF_EXPLODE)
2483                        return AVERROR_INVALIDDATA;
2484                }
2485                break;
2486            case 0x2:
2487                mpeg_decode_sequence_display_extension(s);
2488                break;
2489            case 0x3:
2490                mpeg_decode_quant_matrix_extension(s2);
2491                break;
2492            case 0x7:
2493                mpeg_decode_picture_display_extension(s);
2494                break;
2495            case 0x8:
2496                if (last_code == PICTURE_START_CODE) {
2497                    mpeg_decode_picture_coding_extension(s);
2498                } else {
2499                    av_log(avctx, AV_LOG_ERROR,
2500                           "ignoring pic cod ext after %X\n", last_code);
2501                    if (avctx->err_recognition & AV_EF_EXPLODE)
2502                        return AVERROR_INVALIDDATA;
2503                }
2504                break;
2505            }
2506            break;
2507        case USER_START_CODE:
2508            mpeg_decode_user_data(avctx, buf_ptr, input_size);
2509            break;
2510        case GOP_START_CODE:
2511            if (last_code == 0) {
2512                s2->first_field = 0;
2513                mpeg_decode_gop(avctx, buf_ptr, input_size);
2514                s->sync = 1;
2515            } else {
2516                av_log(avctx, AV_LOG_ERROR,
2517                       "ignoring GOP_START_CODE after %X\n", last_code);
2518                if (avctx->err_recognition & AV_EF_EXPLODE)
2519                    return AVERROR_INVALIDDATA;
2520            }
2521            break;
2522        default:
2523            if (start_code >= SLICE_MIN_START_CODE &&
2524                start_code <= SLICE_MAX_START_CODE && last_code == PICTURE_START_CODE) {
2525                if (s2->progressive_sequence && !s2->progressive_frame) {
2526                    s2->progressive_frame = 1;
2527                    av_log(s2->avctx, AV_LOG_ERROR,
2528                           "interlaced frame in progressive sequence, ignoring\n");
2529                }
2530
2531                if (s2->picture_structure == 0 ||
2532                    (s2->progressive_frame && s2->picture_structure != PICT_FRAME)) {
2533                    av_log(s2->avctx, AV_LOG_ERROR,
2534                           "picture_structure %d invalid, ignoring\n",
2535                           s2->picture_structure);
2536                    s2->picture_structure = PICT_FRAME;
2537                }
2538
2539                if (s2->progressive_sequence && !s2->frame_pred_frame_dct)
2540                    av_log(s2->avctx, AV_LOG_WARNING, "invalid frame_pred_frame_dct\n");
2541
2542                if (s2->picture_structure == PICT_FRAME) {
2543                    s2->first_field = 0;
2544                    s2->v_edge_pos  = 16 * s2->mb_height;
2545                } else {
2546                    s2->first_field ^= 1;
2547                    s2->v_edge_pos   = 8 * s2->mb_height;
2548                    memset(s2->mbskip_table, 0, s2->mb_stride * s2->mb_height);
2549                }
2550            }
2551            if (start_code >= SLICE_MIN_START_CODE &&
2552                start_code <= SLICE_MAX_START_CODE && last_code != 0) {
2553                const int field_pic = s2->picture_structure != PICT_FRAME;
2554                int mb_y = start_code - SLICE_MIN_START_CODE;
2555                last_code = SLICE_MIN_START_CODE;
2556                if (s2->codec_id != AV_CODEC_ID_MPEG1VIDEO && s2->mb_height > 2800/16)
2557                    mb_y += (*buf_ptr&0xE0)<<2;
2558
2559                mb_y <<= field_pic;
2560                if (s2->picture_structure == PICT_BOTTOM_FIELD)
2561                    mb_y++;
2562
2563                if (buf_end - buf_ptr < 2) {
2564                    av_log(s2->avctx, AV_LOG_ERROR, "slice too small\n");
2565                    return AVERROR_INVALIDDATA;
2566                }
2567
2568                if (mb_y >= s2->mb_height) {
2569                    av_log(s2->avctx, AV_LOG_ERROR,
2570                           "slice below image (%d >= %d)\n", mb_y, s2->mb_height);
2571                    return -1;
2572                }
2573
2574                if (s2->last_picture_ptr == NULL) {
2575                    /* Skip B-frames if we do not have reference frames and
2576                     * GOP is not closed. */
2577                    if (s2->pict_type == AV_PICTURE_TYPE_B) {
2578                        if (!s2->closed_gop) {
2579                            skip_frame = 1;
2580                            break;
2581                        }
2582                    }
2583                }
2584                if (s2->pict_type == AV_PICTURE_TYPE_I || (s2->flags2 & CODEC_FLAG2_SHOW_ALL))
2585                    s->sync = 1;
2586                if (s2->next_picture_ptr == NULL) {
2587                    /* Skip P-frames if we do not have a reference frame or
2588                     * we have an invalid header. */
2589                    if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) {
2590                        skip_frame = 1;
2591                        break;
2592                    }
2593                }
2594                if ((avctx->skip_frame >= AVDISCARD_NONREF &&
2595                     s2->pict_type == AV_PICTURE_TYPE_B) ||
2596                    (avctx->skip_frame >= AVDISCARD_NONKEY &&
2597                     s2->pict_type != AV_PICTURE_TYPE_I) ||
2598                    avctx->skip_frame >= AVDISCARD_ALL) {
2599                    skip_frame = 1;
2600                    break;
2601                }
2602
2603                if (!s->mpeg_enc_ctx_allocated)
2604                    break;
2605
2606                if (s2->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2607                    if (mb_y < avctx->skip_top ||
2608                        mb_y >= s2->mb_height - avctx->skip_bottom)
2609                        break;
2610                }
2611
2612                if (!s2->pict_type) {
2613                    av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2614                    if (avctx->err_recognition & AV_EF_EXPLODE)
2615                        return AVERROR_INVALIDDATA;
2616                    break;
2617                }
2618
2619                if (s->first_slice) {
2620                    skip_frame     = 0;
2621                    s->first_slice = 0;
2622                    if (mpeg_field_start(s2, buf, buf_size) < 0)
2623                        return -1;
2624                }
2625                if (!s2->current_picture_ptr) {
2626                    av_log(avctx, AV_LOG_ERROR,
2627                           "current_picture not initialized\n");
2628                    return AVERROR_INVALIDDATA;
2629                }
2630
2631                if (uses_vdpau(avctx)) {
2632                    s->slice_count++;
2633                    break;
2634                }
2635
2636                if (HAVE_THREADS &&
2637                    (avctx->active_thread_type & FF_THREAD_SLICE) &&
2638                    !avctx->hwaccel) {
2639                    int threshold = (s2->mb_height * s->slice_count +
2640                                     s2->slice_context_count / 2) /
2641                                    s2->slice_context_count;
2642                    av_assert0(avctx->thread_count > 1);
2643                    if (threshold <= mb_y) {
2644                        MpegEncContext *thread_context = s2->thread_context[s->slice_count];
2645
2646                        thread_context->start_mb_y = mb_y;
2647                        thread_context->end_mb_y   = s2->mb_height;
2648                        if (s->slice_count) {
2649                            s2->thread_context[s->slice_count - 1]->end_mb_y = mb_y;
2650                            ret = ff_update_duplicate_context(thread_context, s2);
2651                            if (ret < 0)
2652                                return ret;
2653                        }
2654                        init_get_bits(&thread_context->gb, buf_ptr, input_size * 8);
2655                        s->slice_count++;
2656                    }
2657                    buf_ptr += 2; // FIXME add minimum number of bytes per slice
2658                } else {
2659                    ret = mpeg_decode_slice(s2, mb_y, &buf_ptr, input_size);
2660                    emms_c();
2661
2662                    if (ret < 0) {
2663                        if (avctx->err_recognition & AV_EF_EXPLODE)
2664                            return ret;
2665                        if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)
2666                            ff_er_add_slice(&s2->er, s2->resync_mb_x,
2667                                            s2->resync_mb_y, s2->mb_x, s2->mb_y,
2668                                            ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
2669                    } else {
2670                        ff_er_add_slice(&s2->er, s2->resync_mb_x,
2671                                        s2->resync_mb_y, s2->mb_x - 1, s2->mb_y,
2672                                        ER_AC_END | ER_DC_END | ER_MV_END);
2673                    }
2674                }
2675            }
2676            break;
2677        }
2678    }
2679}
2680
2681static int mpeg_decode_frame(AVCodecContext *avctx, void *data,
2682                             int *got_output, AVPacket *avpkt)
2683{
2684    const uint8_t *buf = avpkt->data;
2685    int ret;
2686    int buf_size = avpkt->size;
2687    Mpeg1Context *s = avctx->priv_data;
2688    AVFrame *picture = data;
2689    MpegEncContext *s2 = &s->mpeg_enc_ctx;
2690
2691    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2692        /* special case for last picture */
2693        if (s2->low_delay == 0 && s2->next_picture_ptr) {
2694            int ret = av_frame_ref(picture, s2->next_picture_ptr->f);
2695            if (ret < 0)
2696                return ret;
2697
2698            s2->next_picture_ptr = NULL;
2699
2700            *got_output = 1;
2701        }
2702        return buf_size;
2703    }
2704
2705    if (s2->flags & CODEC_FLAG_TRUNCATED) {
2706        int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf,
2707                                           buf_size, NULL);
2708
2709        if (ff_combine_frame(&s2->parse_context, next,
2710                             (const uint8_t **) &buf, &buf_size) < 0)
2711            return buf_size;
2712    }
2713
2714    s2->codec_tag = avpriv_toupper4(avctx->codec_tag);
2715    if (s->mpeg_enc_ctx_allocated == 0 && (   s2->codec_tag == AV_RL32("VCR2")
2716                                           || s2->codec_tag == AV_RL32("BW10")
2717                                          ))
2718        vcr2_init_sequence(avctx);
2719
2720    s->slice_count = 0;
2721
2722    if (avctx->extradata && !s->extradata_decoded) {
2723        ret = decode_chunks(avctx, picture, got_output,
2724                            avctx->extradata, avctx->extradata_size);
2725        if (*got_output) {
2726            av_log(avctx, AV_LOG_ERROR, "picture in extradata\n");
2727            *got_output = 0;
2728        }
2729        s->extradata_decoded = 1;
2730        if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE)) {
2731            s2->current_picture_ptr = NULL;
2732            return ret;
2733        }
2734    }
2735
2736    ret = decode_chunks(avctx, picture, got_output, buf, buf_size);
2737    if (ret<0 || *got_output)
2738        s2->current_picture_ptr = NULL;
2739
2740    return ret;
2741}
2742
2743static void flush(AVCodecContext *avctx)
2744{
2745    Mpeg1Context *s = avctx->priv_data;
2746
2747    s->sync       = 0;
2748
2749    ff_mpeg_flush(avctx);
2750}
2751
2752static av_cold int mpeg_decode_end(AVCodecContext *avctx)
2753{
2754    Mpeg1Context *s = avctx->priv_data;
2755
2756    if (s->mpeg_enc_ctx_allocated)
2757        ff_MPV_common_end(&s->mpeg_enc_ctx);
2758    av_freep(&s->a53_caption);
2759    return 0;
2760}
2761
2762static const AVProfile mpeg2_video_profiles[] = {
2763    { FF_PROFILE_MPEG2_422,          "4:2:2"              },
2764    { FF_PROFILE_MPEG2_HIGH,         "High"               },
2765    { FF_PROFILE_MPEG2_SS,           "Spatially Scalable" },
2766    { FF_PROFILE_MPEG2_SNR_SCALABLE, "SNR Scalable"       },
2767    { FF_PROFILE_MPEG2_MAIN,         "Main"               },
2768    { FF_PROFILE_MPEG2_SIMPLE,       "Simple"             },
2769    { FF_PROFILE_RESERVED,           "Reserved"           },
2770    { FF_PROFILE_RESERVED,           "Reserved"           },
2771    { FF_PROFILE_UNKNOWN                                  },
2772};
2773
2774AVCodec ff_mpeg1video_decoder = {
2775    .name                  = "mpeg1video",
2776    .long_name             = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2777    .type                  = AVMEDIA_TYPE_VIDEO,
2778    .id                    = AV_CODEC_ID_MPEG1VIDEO,
2779    .priv_data_size        = sizeof(Mpeg1Context),
2780    .init                  = mpeg_decode_init,
2781    .close                 = mpeg_decode_end,
2782    .decode                = mpeg_decode_frame,
2783    .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2784                             CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2785                             CODEC_CAP_SLICE_THREADS,
2786    .flush                 = flush,
2787    .max_lowres            = 3,
2788    .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg_decode_update_thread_context)
2789};
2790
2791AVCodec ff_mpeg2video_decoder = {
2792    .name           = "mpeg2video",
2793    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
2794    .type           = AVMEDIA_TYPE_VIDEO,
2795    .id             = AV_CODEC_ID_MPEG2VIDEO,
2796    .priv_data_size = sizeof(Mpeg1Context),
2797    .init           = mpeg_decode_init,
2798    .close          = mpeg_decode_end,
2799    .decode         = mpeg_decode_frame,
2800    .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2801                      CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2802                      CODEC_CAP_SLICE_THREADS,
2803    .flush          = flush,
2804    .max_lowres     = 3,
2805    .profiles       = NULL_IF_CONFIG_SMALL(mpeg2_video_profiles),
2806};
2807
2808//legacy decoder
2809AVCodec ff_mpegvideo_decoder = {
2810    .name           = "mpegvideo",
2811    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2812    .type           = AVMEDIA_TYPE_VIDEO,
2813    .id             = AV_CODEC_ID_MPEG2VIDEO,
2814    .priv_data_size = sizeof(Mpeg1Context),
2815    .init           = mpeg_decode_init,
2816    .close          = mpeg_decode_end,
2817    .decode         = mpeg_decode_frame,
2818    .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
2819    .flush          = flush,
2820    .max_lowres     = 3,
2821};
2822
2823#if FF_API_XVMC
2824#if CONFIG_MPEG_XVMC_DECODER
2825static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx)
2826{
2827    if (avctx->active_thread_type & FF_THREAD_SLICE)
2828        return -1;
2829    if (!(avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
2830        return -1;
2831    if (!(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
2832        av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
2833    }
2834    mpeg_decode_init(avctx);
2835
2836    avctx->pix_fmt           = AV_PIX_FMT_XVMC_MPEG2_IDCT;
2837    avctx->xvmc_acceleration = 2; // 2 - the blocks are packed!
2838
2839    return 0;
2840}
2841
2842AVCodec ff_mpeg_xvmc_decoder = {
2843    .name           = "mpegvideo_xvmc",
2844    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video XvMC (X-Video Motion Compensation)"),
2845    .type           = AVMEDIA_TYPE_VIDEO,
2846    .id             = AV_CODEC_ID_MPEG2VIDEO_XVMC,
2847    .priv_data_size = sizeof(Mpeg1Context),
2848    .init           = mpeg_mc_decode_init,
2849    .close          = mpeg_decode_end,
2850    .decode         = mpeg_decode_frame,
2851    .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2852                      CODEC_CAP_TRUNCATED | CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
2853    .flush          = flush,
2854};
2855
2856#endif
2857#endif /* FF_API_XVMC */
2858
2859#if CONFIG_MPEG_VDPAU_DECODER
2860AVCodec ff_mpeg_vdpau_decoder = {
2861    .name           = "mpegvideo_vdpau",
2862    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video (VDPAU acceleration)"),
2863    .type           = AVMEDIA_TYPE_VIDEO,
2864    .id             = AV_CODEC_ID_MPEG2VIDEO,
2865    .priv_data_size = sizeof(Mpeg1Context),
2866    .init           = mpeg_decode_init,
2867    .close          = mpeg_decode_end,
2868    .decode         = mpeg_decode_frame,
2869    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED |
2870                      CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2871    .flush          = flush,
2872};
2873#endif
2874
2875#if CONFIG_MPEG1_VDPAU_DECODER
2876AVCodec ff_mpeg1_vdpau_decoder = {
2877    .name           = "mpeg1video_vdpau",
2878    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1 video (VDPAU acceleration)"),
2879    .type           = AVMEDIA_TYPE_VIDEO,
2880    .id             = AV_CODEC_ID_MPEG1VIDEO,
2881    .priv_data_size = sizeof(Mpeg1Context),
2882    .init           = mpeg_decode_init,
2883    .close          = mpeg_decode_end,
2884    .decode         = mpeg_decode_frame,
2885    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED |
2886                      CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2887    .flush          = flush,
2888};
2889#endif
2890