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