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