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