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