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