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