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