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