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