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