Merge remote-tracking branch 'qatar/master'
[ffmpeg.git] / libavcodec / mpeg12.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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 #define UNCHECKED_BITSTREAM_READER 1
29
30 //#define DEBUG
31 #include "internal.h"
32 #include "avcodec.h"
33 #include "dsputil.h"
34 #include "mpegvideo.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/timecode.h"
37
38 #include "mpeg12.h"
39 #include "mpeg12data.h"
40 #include "mpeg12decdata.h"
41 #include "bytestream.h"
42 #include "vdpau_internal.h"
43 #include "xvmc_internal.h"
44 #include "thread.h"
45
46 //#undef NDEBUG
47 //#include <assert.h>
48
49
50 #define MV_VLC_BITS 9
51 #define MBINCR_VLC_BITS 9
52 #define MB_PAT_VLC_BITS 9
53 #define MB_PTYPE_VLC_BITS 6
54 #define MB_BTYPE_VLC_BITS 6
55
56 static VLC mv_vlc;
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, 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, DCTELEM *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, DCTELEM *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, DCTELEM *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, DCTELEM *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, DCTELEM *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                                                     DCTELEM *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, DCTELEM *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, DCTELEM *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 uint8_t ff_mpeg12_static_rl_table_store[2][2][2*MAX_RUN + MAX_LEVEL + 3];
598
599 #define INIT_2D_VLC_RL(rl, static_size)\
600 {\
601     static RL_VLC_ELEM rl_vlc_table[static_size];\
602     INIT_VLC_STATIC(&rl.vlc, TEX_VLC_BITS, rl.n + 2,\
603                     &rl.table_vlc[0][1], 4, 2,\
604                     &rl.table_vlc[0][0], 4, 2, static_size);\
605 \
606     rl.rl_vlc[0] = rl_vlc_table;\
607     init_2d_vlc_rl(&rl);\
608 }
609
610 static void init_2d_vlc_rl(RLTable *rl)
611 {
612     int i;
613
614     for (i = 0; i < rl->vlc.table_size; i++) {
615         int code = rl->vlc.table[i][0];
616         int len  = rl->vlc.table[i][1];
617         int level, run;
618
619         if (len == 0) { // illegal code
620             run   = 65;
621             level = MAX_LEVEL;
622         } else if (len<0) { //more bits needed
623             run   = 0;
624             level = code;
625         } else {
626             if (code == rl->n) { //esc
627                 run   = 65;
628                 level = 0;
629             } else if (code == rl->n+1) { //eob
630                 run   = 0;
631                 level = 127;
632             } else {
633                 run   = rl->table_run  [code] + 1;
634                 level = rl->table_level[code];
635             }
636         }
637         rl->rl_vlc[0][i].len   = len;
638         rl->rl_vlc[0][i].level = level;
639         rl->rl_vlc[0][i].run   = run;
640     }
641 }
642
643 void ff_mpeg12_common_init(MpegEncContext *s)
644 {
645
646     s->y_dc_scale_table =
647     s->c_dc_scale_table = ff_mpeg2_dc_scale_table[s->intra_dc_precision];
648
649 }
650
651 void ff_mpeg1_clean_buffers(MpegEncContext *s)
652 {
653     s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
654     s->last_dc[1] = s->last_dc[0];
655     s->last_dc[2] = s->last_dc[0];
656     memset(s->last_mv, 0, sizeof(s->last_mv));
657 }
658
659
660 /******************************************/
661 /* decoding */
662
663 VLC ff_dc_lum_vlc;
664 VLC ff_dc_chroma_vlc;
665
666 static VLC mbincr_vlc;
667 static VLC mb_ptype_vlc;
668 static VLC mb_btype_vlc;
669 static VLC mb_pat_vlc;
670
671 av_cold void ff_mpeg12_init_vlcs(void)
672 {
673     static int done = 0;
674
675     if (!done) {
676         done = 1;
677
678         INIT_VLC_STATIC(&ff_dc_lum_vlc, DC_VLC_BITS, 12,
679                         ff_mpeg12_vlc_dc_lum_bits, 1, 1,
680                         ff_mpeg12_vlc_dc_lum_code, 2, 2, 512);
681         INIT_VLC_STATIC(&ff_dc_chroma_vlc,  DC_VLC_BITS, 12,
682                         ff_mpeg12_vlc_dc_chroma_bits, 1, 1,
683                         ff_mpeg12_vlc_dc_chroma_code, 2, 2, 514);
684         INIT_VLC_STATIC(&mv_vlc, MV_VLC_BITS, 17,
685                         &ff_mpeg12_mbMotionVectorTable[0][1], 2, 1,
686                         &ff_mpeg12_mbMotionVectorTable[0][0], 2, 1, 518);
687         INIT_VLC_STATIC(&mbincr_vlc, MBINCR_VLC_BITS, 36,
688                         &ff_mpeg12_mbAddrIncrTable[0][1], 2, 1,
689                         &ff_mpeg12_mbAddrIncrTable[0][0], 2, 1, 538);
690         INIT_VLC_STATIC(&mb_pat_vlc, MB_PAT_VLC_BITS, 64,
691                         &ff_mpeg12_mbPatTable[0][1], 2, 1,
692                         &ff_mpeg12_mbPatTable[0][0], 2, 1, 512);
693
694         INIT_VLC_STATIC(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 7,
695                         &table_mb_ptype[0][1], 2, 1,
696                         &table_mb_ptype[0][0], 2, 1, 64);
697         INIT_VLC_STATIC(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11,
698                         &table_mb_btype[0][1], 2, 1,
699                         &table_mb_btype[0][0], 2, 1, 64);
700         ff_init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
701         ff_init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
702
703         INIT_2D_VLC_RL(ff_rl_mpeg1, 680);
704         INIT_2D_VLC_RL(ff_rl_mpeg2, 674);
705     }
706 }
707
708 static inline int get_dmv(MpegEncContext *s)
709 {
710     if (get_bits1(&s->gb))
711         return 1 - (get_bits1(&s->gb) << 1);
712     else
713         return 0;
714 }
715
716 static inline int get_qscale(MpegEncContext *s)
717 {
718     int qscale = get_bits(&s->gb, 5);
719     if (s->q_scale_type) {
720         return non_linear_qscale[qscale];
721     } else {
722         return qscale << 1;
723     }
724 }
725
726 static void exchange_uv(MpegEncContext *s)
727 {
728     DCTELEM (*tmp)[64];
729
730     tmp           = s->pblocks[4];
731     s->pblocks[4] = s->pblocks[5];
732     s->pblocks[5] = tmp;
733 }
734
735 /* motion type (for MPEG-2) */
736 #define MT_FIELD 1
737 #define MT_FRAME 2
738 #define MT_16X8  2
739 #define MT_DMV   3
740
741 static int mpeg_decode_mb(MpegEncContext *s, DCTELEM block[12][64])
742 {
743     int i, j, k, cbp, val, mb_type, motion_type;
744     const int mb_block_count = 4 + (1 << s->chroma_format);
745
746     av_dlog(s->avctx, "decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);
747
748     assert(s->mb_skipped == 0);
749
750     if (s->mb_skip_run-- != 0) {
751         if (s->pict_type == AV_PICTURE_TYPE_P) {
752             s->mb_skipped = 1;
753             s->current_picture.f.mb_type[s->mb_x + s->mb_y * s->mb_stride] = MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;
754         } else {
755             int mb_type;
756
757             if (s->mb_x)
758                 mb_type = s->current_picture.f.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1];
759             else
760                 mb_type = s->current_picture.f.mb_type[s->mb_width + (s->mb_y - 1) * s->mb_stride - 1]; // FIXME not sure if this is allowed in MPEG at all
761             if (IS_INTRA(mb_type))
762                 return -1;
763             s->current_picture.f.mb_type[s->mb_x + s->mb_y*s->mb_stride] =
764                 mb_type | MB_TYPE_SKIP;
765 //            assert(s->current_picture.f.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1] & (MB_TYPE_16x16 | MB_TYPE_16x8));
766
767             if ((s->mv[0][0][0] | s->mv[0][0][1] | s->mv[1][0][0] | s->mv[1][0][1]) == 0)
768                 s->mb_skipped = 1;
769         }
770
771         return 0;
772     }
773
774     switch (s->pict_type) {
775     default:
776     case AV_PICTURE_TYPE_I:
777         if (get_bits1(&s->gb) == 0) {
778             if (get_bits1(&s->gb) == 0) {
779                 av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in I Frame at %d %d\n", s->mb_x, s->mb_y);
780                 return -1;
781             }
782             mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
783         } else {
784             mb_type = MB_TYPE_INTRA;
785         }
786         break;
787     case AV_PICTURE_TYPE_P:
788         mb_type = get_vlc2(&s->gb, mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);
789         if (mb_type < 0) {
790             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in P Frame at %d %d\n", s->mb_x, s->mb_y);
791             return -1;
792         }
793         mb_type = ptype2mb_type[mb_type];
794         break;
795     case AV_PICTURE_TYPE_B:
796         mb_type = get_vlc2(&s->gb, mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);
797         if (mb_type < 0) {
798             av_log(s->avctx, AV_LOG_ERROR, "invalid mb type in B Frame at %d %d\n", s->mb_x, s->mb_y);
799             return -1;
800         }
801         mb_type = btype2mb_type[mb_type];
802         break;
803     }
804     av_dlog(s->avctx, "mb_type=%x\n", mb_type);
805 //    motion_type = 0; /* avoid warning */
806     if (IS_INTRA(mb_type)) {
807         s->dsp.clear_blocks(s->block[0]);
808
809         if (!s->chroma_y_shift) {
810             s->dsp.clear_blocks(s->block[6]);
811         }
812
813         /* compute DCT type */
814         if (s->picture_structure == PICT_FRAME && // FIXME add an interlaced_dct coded var?
815             !s->frame_pred_frame_dct) {
816             s->interlaced_dct = get_bits1(&s->gb);
817         }
818
819         if (IS_QUANT(mb_type))
820             s->qscale = get_qscale(s);
821
822         if (s->concealment_motion_vectors) {
823             /* just parse them */
824             if (s->picture_structure != PICT_FRAME)
825                 skip_bits1(&s->gb); /* field select */
826
827             s->mv[0][0][0]= s->last_mv[0][0][0]= s->last_mv[0][1][0] =
828                 mpeg_decode_motion(s, s->mpeg_f_code[0][0], s->last_mv[0][0][0]);
829             s->mv[0][0][1]= s->last_mv[0][0][1]= s->last_mv[0][1][1] =
830                 mpeg_decode_motion(s, s->mpeg_f_code[0][1], s->last_mv[0][0][1]);
831
832             skip_bits1(&s->gb); /* marker */
833         } else
834             memset(s->last_mv, 0, sizeof(s->last_mv)); /* reset mv prediction */
835         s->mb_intra = 1;
836         // if 1, we memcpy blocks in xvmcvideo
837         if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1) {
838             ff_xvmc_pack_pblocks(s, -1); // inter are always full blocks
839             if (s->swap_uv) {
840                 exchange_uv(s);
841             }
842         }
843
844         if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
845             if (s->flags2 & CODEC_FLAG2_FAST) {
846                 for (i = 0; i < 6; i++) {
847                     mpeg2_fast_decode_block_intra(s, *s->pblocks[i], i);
848                 }
849             } else {
850                 for (i = 0; i < mb_block_count; i++) {
851                     if (mpeg2_decode_block_intra(s, *s->pblocks[i], i) < 0)
852                         return -1;
853                 }
854             }
855         } else {
856             for (i = 0; i < 6; i++) {
857                 if (mpeg1_decode_block_intra(s, *s->pblocks[i], i) < 0)
858                     return -1;
859             }
860         }
861     } else {
862         if (mb_type & MB_TYPE_ZERO_MV) {
863             assert(mb_type & MB_TYPE_CBP);
864
865             s->mv_dir = MV_DIR_FORWARD;
866             if (s->picture_structure == PICT_FRAME) {
867                 if (!s->frame_pred_frame_dct)
868                     s->interlaced_dct = get_bits1(&s->gb);
869                 s->mv_type = MV_TYPE_16X16;
870             } else {
871                 s->mv_type = MV_TYPE_FIELD;
872                 mb_type |= MB_TYPE_INTERLACED;
873                 s->field_select[0][0] = s->picture_structure - 1;
874             }
875
876             if (IS_QUANT(mb_type))
877                 s->qscale = get_qscale(s);
878
879             s->last_mv[0][0][0] = 0;
880             s->last_mv[0][0][1] = 0;
881             s->last_mv[0][1][0] = 0;
882             s->last_mv[0][1][1] = 0;
883             s->mv[0][0][0] = 0;
884             s->mv[0][0][1] = 0;
885         } else {
886             assert(mb_type & MB_TYPE_L0L1);
887             // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
888             /* get additional motion vector type */
889             if (s->frame_pred_frame_dct)
890                 motion_type = MT_FRAME;
891             else {
892                 motion_type = get_bits(&s->gb, 2);
893                 if (s->picture_structure == PICT_FRAME && HAS_CBP(mb_type))
894                     s->interlaced_dct = get_bits1(&s->gb);
895             }
896
897             if (IS_QUANT(mb_type))
898                 s->qscale = get_qscale(s);
899
900             /* motion vectors */
901             s->mv_dir = (mb_type >> 13) & 3;
902             av_dlog(s->avctx, "motion_type=%d\n", motion_type);
903             switch (motion_type) {
904             case MT_FRAME: /* or MT_16X8 */
905                 if (s->picture_structure == PICT_FRAME) {
906                     mb_type |= MB_TYPE_16x16;
907                     s->mv_type = MV_TYPE_16X16;
908                     for (i = 0; i < 2; i++) {
909                         if (USES_LIST(mb_type, i)) {
910                             /* MT_FRAME */
911                             s->mv[i][0][0]= s->last_mv[i][0][0]= s->last_mv[i][1][0] =
912                                 mpeg_decode_motion(s, s->mpeg_f_code[i][0], s->last_mv[i][0][0]);
913                             s->mv[i][0][1]= s->last_mv[i][0][1]= s->last_mv[i][1][1] =
914                                 mpeg_decode_motion(s, s->mpeg_f_code[i][1], s->last_mv[i][0][1]);
915                             /* full_pel: only for MPEG-1 */
916                             if (s->full_pel[i]) {
917                                 s->mv[i][0][0] <<= 1;
918                                 s->mv[i][0][1] <<= 1;
919                             }
920                         }
921                     }
922                 } else {
923                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
924                     s->mv_type = MV_TYPE_16X8;
925                     for (i = 0; i < 2; i++) {
926                         if (USES_LIST(mb_type, i)) {
927                             /* MT_16X8 */
928                             for (j = 0; j < 2; j++) {
929                                 s->field_select[i][j] = get_bits1(&s->gb);
930                                 for (k = 0; k < 2; k++) {
931                                     val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
932                                                              s->last_mv[i][j][k]);
933                                     s->last_mv[i][j][k] = val;
934                                     s->mv[i][j][k]      = val;
935                                 }
936                             }
937                         }
938                     }
939                 }
940                 break;
941             case MT_FIELD:
942                 s->mv_type = MV_TYPE_FIELD;
943                 if (s->picture_structure == PICT_FRAME) {
944                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
945                     for (i = 0; i < 2; i++) {
946                         if (USES_LIST(mb_type, i)) {
947                             for (j = 0; j < 2; j++) {
948                                 s->field_select[i][j] = get_bits1(&s->gb);
949                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
950                                                          s->last_mv[i][j][0]);
951                                 s->last_mv[i][j][0] = val;
952                                 s->mv[i][j][0]      = val;
953                                 av_dlog(s->avctx, "fmx=%d\n", val);
954                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
955                                                          s->last_mv[i][j][1] >> 1);
956                                 s->last_mv[i][j][1] = val << 1;
957                                 s->mv[i][j][1]      = val;
958                                 av_dlog(s->avctx, "fmy=%d\n", val);
959                             }
960                         }
961                     }
962                 } else {
963                     av_assert0(!s->progressive_sequence);
964                     mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
965                     for (i = 0; i < 2; i++) {
966                         if (USES_LIST(mb_type, i)) {
967                             s->field_select[i][0] = get_bits1(&s->gb);
968                             for (k = 0; k < 2; k++) {
969                                 val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],
970                                                          s->last_mv[i][0][k]);
971                                 s->last_mv[i][0][k] = val;
972                                 s->last_mv[i][1][k] = val;
973                                 s->mv[i][0][k]      = val;
974                             }
975                         }
976                     }
977                 }
978                 break;
979             case MT_DMV:
980                 if(s->progressive_sequence){
981                     av_log(s->avctx, AV_LOG_ERROR, "MT_DMV in progressive_sequence\n");
982                     return -1;
983                 }
984                 s->mv_type = MV_TYPE_DMV;
985                 for (i = 0; i < 2; i++) {
986                     if (USES_LIST(mb_type, i)) {
987                         int dmx, dmy, mx, my, m;
988                         const int my_shift = s->picture_structure == PICT_FRAME;
989
990                         mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0],
991                                                 s->last_mv[i][0][0]);
992                         s->last_mv[i][0][0] = mx;
993                         s->last_mv[i][1][0] = mx;
994                         dmx = get_dmv(s);
995                         my  = mpeg_decode_motion(s, s->mpeg_f_code[i][1],
996                                                  s->last_mv[i][0][1] >> my_shift);
997                         dmy = get_dmv(s);
998
999
1000                         s->last_mv[i][0][1] = my << my_shift;
1001                         s->last_mv[i][1][1] = my << my_shift;
1002
1003                         s->mv[i][0][0] = mx;
1004                         s->mv[i][0][1] = my;
1005                         s->mv[i][1][0] = mx; // not used
1006                         s->mv[i][1][1] = my; // not used
1007
1008                         if (s->picture_structure == PICT_FRAME) {
1009                             mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
1010
1011                             // m = 1 + 2 * s->top_field_first;
1012                             m = s->top_field_first ? 1 : 3;
1013
1014                             /* top -> top pred */
1015                             s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1016                             s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
1017                             m = 4 - m;
1018                             s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
1019                             s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
1020                         } else {
1021                             mb_type |= MB_TYPE_16x16;
1022
1023                             s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
1024                             s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
1025                             if (s->picture_structure == PICT_TOP_FIELD)
1026                                 s->mv[i][2][1]--;
1027                             else
1028                                 s->mv[i][2][1]++;
1029                         }
1030                     }
1031                 }
1032                 break;
1033             default:
1034                 av_log(s->avctx, AV_LOG_ERROR, "00 motion_type at %d %d\n", s->mb_x, s->mb_y);
1035                 return -1;
1036             }
1037         }
1038
1039         s->mb_intra = 0;
1040         if (HAS_CBP(mb_type)) {
1041             s->dsp.clear_blocks(s->block[0]);
1042
1043             cbp = get_vlc2(&s->gb, mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);
1044             if (mb_block_count > 6) {
1045                  cbp <<= mb_block_count - 6;
1046                  cbp  |= get_bits(&s->gb, mb_block_count - 6);
1047                  s->dsp.clear_blocks(s->block[6]);
1048             }
1049             if (cbp <= 0) {
1050                 av_log(s->avctx, AV_LOG_ERROR, "invalid cbp at %d %d\n", s->mb_x, s->mb_y);
1051                 return -1;
1052             }
1053
1054             //if 1, we memcpy blocks in xvmcvideo
1055             if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1) {
1056                 ff_xvmc_pack_pblocks(s, cbp);
1057                 if (s->swap_uv) {
1058                     exchange_uv(s);
1059                 }
1060             }
1061
1062             if (s->codec_id == CODEC_ID_MPEG2VIDEO) {
1063                 if (s->flags2 & CODEC_FLAG2_FAST) {
1064                     for (i = 0; i < 6; i++) {
1065                         if (cbp & 32) {
1066                             mpeg2_fast_decode_block_non_intra(s, *s->pblocks[i], i);
1067                         } else {
1068                             s->block_last_index[i] = -1;
1069                         }
1070                         cbp += cbp;
1071                     }
1072                 } else {
1073                     cbp <<= 12-mb_block_count;
1074
1075                     for (i = 0; i < mb_block_count; i++) {
1076                         if (cbp & (1 << 11)) {
1077                             if (mpeg2_decode_block_non_intra(s, *s->pblocks[i], i) < 0)
1078                                 return -1;
1079                         } else {
1080                             s->block_last_index[i] = -1;
1081                         }
1082                         cbp += cbp;
1083                     }
1084                 }
1085             } else {
1086                 if (s->flags2 & CODEC_FLAG2_FAST) {
1087                     for (i = 0; i < 6; i++) {
1088                         if (cbp & 32) {
1089                             mpeg1_fast_decode_block_inter(s, *s->pblocks[i], i);
1090                         } else {
1091                             s->block_last_index[i] = -1;
1092                         }
1093                         cbp += cbp;
1094                     }
1095                 } else {
1096                     for (i = 0; i < 6; i++) {
1097                         if (cbp & 32) {
1098                             if (mpeg1_decode_block_inter(s, *s->pblocks[i], i) < 0)
1099                                 return -1;
1100                         } else {
1101                             s->block_last_index[i] = -1;
1102                         }
1103                         cbp += cbp;
1104                     }
1105                 }
1106             }
1107         } else {
1108             for (i = 0; i < 12; i++)
1109                 s->block_last_index[i] = -1;
1110         }
1111     }
1112
1113     s->current_picture.f.mb_type[s->mb_x + s->mb_y * s->mb_stride] = mb_type;
1114
1115     return 0;
1116 }
1117
1118 static av_cold int mpeg_decode_init(AVCodecContext *avctx)
1119 {
1120     Mpeg1Context *s = avctx->priv_data;
1121     MpegEncContext *s2 = &s->mpeg_enc_ctx;
1122     int i;
1123
1124     /* we need some permutation to store matrices,
1125      * until MPV_common_init() sets the real permutation. */
1126     for (i = 0; i < 64; i++)
1127        s2->dsp.idct_permutation[i]=i;
1128
1129     ff_MPV_decode_defaults(s2);
1130
1131     s->mpeg_enc_ctx.avctx  = avctx;
1132     s->mpeg_enc_ctx.flags  = avctx->flags;
1133     s->mpeg_enc_ctx.flags2 = avctx->flags2;
1134     ff_mpeg12_common_init(&s->mpeg_enc_ctx);
1135     ff_mpeg12_init_vlcs();
1136
1137     s->mpeg_enc_ctx_allocated      = 0;
1138     s->mpeg_enc_ctx.picture_number = 0;
1139     s->repeat_field                = 0;
1140     s->mpeg_enc_ctx.codec_id       = avctx->codec->id;
1141     avctx->color_range = AVCOL_RANGE_MPEG;
1142     if (avctx->codec->id == CODEC_ID_MPEG1VIDEO)
1143         avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
1144     else
1145         avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1146     return 0;
1147 }
1148
1149 static int mpeg_decode_update_thread_context(AVCodecContext *avctx, const AVCodecContext *avctx_from)
1150 {
1151     Mpeg1Context *ctx = avctx->priv_data, *ctx_from = avctx_from->priv_data;
1152     MpegEncContext *s = &ctx->mpeg_enc_ctx, *s1 = &ctx_from->mpeg_enc_ctx;
1153     int err;
1154
1155     if (avctx == avctx_from || !ctx_from->mpeg_enc_ctx_allocated || !s1->context_initialized)
1156         return 0;
1157
1158     err = ff_mpeg_update_thread_context(avctx, avctx_from);
1159     if (err) return err;
1160
1161     if (!ctx->mpeg_enc_ctx_allocated)
1162         memcpy(s + 1, s1 + 1, sizeof(Mpeg1Context) - sizeof(MpegEncContext));
1163
1164     if (!(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay))
1165         s->picture_number++;
1166
1167     return 0;
1168 }
1169
1170 static void quant_matrix_rebuild(uint16_t *matrix, const uint8_t *old_perm,
1171                                  const uint8_t *new_perm)
1172 {
1173     uint16_t temp_matrix[64];
1174     int i;
1175
1176     memcpy(temp_matrix, matrix, 64 * sizeof(uint16_t));
1177
1178     for (i = 0; i < 64; i++) {
1179         matrix[new_perm[i]] = temp_matrix[old_perm[i]];
1180     }
1181 }
1182
1183 static const enum PixelFormat mpeg1_hwaccel_pixfmt_list_420[] = {
1184 #if CONFIG_MPEG_XVMC_DECODER
1185     PIX_FMT_XVMC_MPEG2_IDCT,
1186     PIX_FMT_XVMC_MPEG2_MC,
1187 #endif
1188 #if CONFIG_MPEG1_VDPAU_HWACCEL
1189     PIX_FMT_VDPAU_MPEG1,
1190 #endif
1191     PIX_FMT_YUV420P,
1192     PIX_FMT_NONE
1193 };
1194
1195 static const enum PixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
1196 #if CONFIG_MPEG_XVMC_DECODER
1197     PIX_FMT_XVMC_MPEG2_IDCT,
1198     PIX_FMT_XVMC_MPEG2_MC,
1199 #endif
1200 #if CONFIG_MPEG2_VDPAU_HWACCEL
1201     PIX_FMT_VDPAU_MPEG2,
1202 #endif
1203 #if CONFIG_MPEG2_DXVA2_HWACCEL
1204     PIX_FMT_DXVA2_VLD,
1205 #endif
1206 #if CONFIG_MPEG2_VAAPI_HWACCEL
1207     PIX_FMT_VAAPI_VLD,
1208 #endif
1209     PIX_FMT_YUV420P,
1210     PIX_FMT_NONE
1211 };
1212
1213 static inline int uses_vdpau(AVCodecContext *avctx) {
1214     return avctx->pix_fmt == PIX_FMT_VDPAU_MPEG1 || avctx->pix_fmt == PIX_FMT_VDPAU_MPEG2;
1215 }
1216
1217 static enum PixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)
1218 {
1219     Mpeg1Context *s1 = avctx->priv_data;
1220     MpegEncContext *s = &s1->mpeg_enc_ctx;
1221
1222     if(s->chroma_format < 2) {
1223         enum PixelFormat res;
1224         res = avctx->get_format(avctx,
1225                                 avctx->codec_id == CODEC_ID_MPEG1VIDEO ?
1226                                 mpeg1_hwaccel_pixfmt_list_420 :
1227                                 mpeg2_hwaccel_pixfmt_list_420);
1228         if (res != PIX_FMT_XVMC_MPEG2_IDCT && res != PIX_FMT_XVMC_MPEG2_MC) {
1229             avctx->xvmc_acceleration = 0;
1230         } else if (!avctx->xvmc_acceleration) {
1231             avctx->xvmc_acceleration = 2;
1232         }
1233         return res;
1234     } else if(s->chroma_format == 2)
1235         return PIX_FMT_YUV422P;
1236     else
1237         return PIX_FMT_YUV444P;
1238 }
1239
1240 /* Call this function when we know all parameters.
1241  * It may be called in different places for MPEG-1 and MPEG-2. */
1242 static int mpeg_decode_postinit(AVCodecContext *avctx)
1243 {
1244     Mpeg1Context *s1 = avctx->priv_data;
1245     MpegEncContext *s = &s1->mpeg_enc_ctx;
1246     uint8_t old_permutation[64];
1247
1248     if ((s1->mpeg_enc_ctx_allocated == 0) ||
1249         avctx->coded_width  != s->width   ||
1250         avctx->coded_height != s->height  ||
1251         s1->save_width           != s->width                ||
1252         s1->save_height          != s->height               ||
1253         s1->save_aspect_info     != s->aspect_ratio_info    ||
1254         s1->save_progressive_seq != s->progressive_sequence ||
1255         0)
1256     {
1257
1258         if (s1->mpeg_enc_ctx_allocated) {
1259             ParseContext pc = s->parse_context;
1260             s->parse_context.buffer = 0;
1261             ff_MPV_common_end(s);
1262             s->parse_context = pc;
1263         }
1264
1265         if ((s->width == 0) || (s->height == 0))
1266             return -2;
1267
1268         avcodec_set_dimensions(avctx, s->width, s->height);
1269         avctx->bit_rate          = s->bit_rate;
1270         s1->save_aspect_info     = s->aspect_ratio_info;
1271         s1->save_width           = s->width;
1272         s1->save_height          = s->height;
1273         s1->save_progressive_seq = s->progressive_sequence;
1274
1275         /* low_delay may be forced, in this case we will have B-frames
1276          * that behave like P-frames. */
1277         avctx->has_b_frames = !s->low_delay;
1278
1279         if (avctx->codec_id == CODEC_ID_MPEG1VIDEO) {
1280             //MPEG-1 fps
1281             avctx->time_base.den = avpriv_frame_rate_tab[s->frame_rate_index].num;
1282             avctx->time_base.num = avpriv_frame_rate_tab[s->frame_rate_index].den;
1283             //MPEG-1 aspect
1284             avctx->sample_aspect_ratio = av_d2q(1.0/ff_mpeg1_aspect[s->aspect_ratio_info], 255);
1285             avctx->ticks_per_frame=1;
1286         } else {//MPEG-2
1287         //MPEG-2 fps
1288             av_reduce(&s->avctx->time_base.den,
1289                       &s->avctx->time_base.num,
1290                       avpriv_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num*2,
1291                       avpriv_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,
1292                       1 << 30);
1293             avctx->ticks_per_frame = 2;
1294             //MPEG-2 aspect
1295             if (s->aspect_ratio_info > 1) {
1296                 AVRational dar =
1297                     av_mul_q(av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1298                                       (AVRational) {s1->pan_scan.width, s1->pan_scan.height}),
1299                              (AVRational) {s->width, s->height});
1300
1301                 // we ignore the spec here and guess a bit as reality does not match the spec, see for example
1302                 // res_change_ffmpeg_aspect.ts and sequence-display-aspect.mpg
1303                 // issue1613, 621, 562
1304                 if ((s1->pan_scan.width == 0) || (s1->pan_scan.height == 0) ||
1305                    (av_cmp_q(dar, (AVRational) {4, 3}) && av_cmp_q(dar, (AVRational) {16, 9}))) {
1306                     s->avctx->sample_aspect_ratio =
1307                         av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1308                                  (AVRational) {s->width, s->height});
1309                 } else {
1310                     s->avctx->sample_aspect_ratio =
1311                         av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],
1312                                  (AVRational) {s1->pan_scan.width, s1->pan_scan.height});
1313 //issue1613 4/3 16/9 -> 16/9
1314 //res_change_ffmpeg_aspect.ts 4/3 225/44 ->4/3
1315 //widescreen-issue562.mpg 4/3 16/9 -> 16/9
1316 //                    s->avctx->sample_aspect_ratio = av_mul_q(s->avctx->sample_aspect_ratio, (AVRational) {s->width, s->height});
1317 //av_log(NULL, AV_LOG_ERROR, "A %d/%d\n", ff_mpeg2_aspect[s->aspect_ratio_info].num, ff_mpeg2_aspect[s->aspect_ratio_info].den);
1318 //av_log(NULL, AV_LOG_ERROR, "B %d/%d\n", s->avctx->sample_aspect_ratio.num, s->avctx->sample_aspect_ratio.den);
1319                 }
1320             } else {
1321                 s->avctx->sample_aspect_ratio =
1322                     ff_mpeg2_aspect[s->aspect_ratio_info];
1323             }
1324         } // MPEG-2
1325
1326         avctx->pix_fmt = mpeg_get_pixelformat(avctx);
1327         avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
1328         // until then pix_fmt may be changed right after codec init
1329         if (avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT ||
1330             avctx->hwaccel )
1331             if (avctx->idct_algo == FF_IDCT_AUTO)
1332                 avctx->idct_algo = FF_IDCT_SIMPLE;
1333
1334         /* Quantization matrices may need reordering
1335          * if DCT permutation is changed. */
1336         memcpy(old_permutation, s->dsp.idct_permutation, 64 * sizeof(uint8_t));
1337
1338         if (ff_MPV_common_init(s) < 0)
1339             return -2;
1340
1341         quant_matrix_rebuild(s->intra_matrix,        old_permutation, s->dsp.idct_permutation);
1342         quant_matrix_rebuild(s->inter_matrix,        old_permutation, s->dsp.idct_permutation);
1343         quant_matrix_rebuild(s->chroma_intra_matrix, old_permutation, s->dsp.idct_permutation);
1344         quant_matrix_rebuild(s->chroma_inter_matrix, old_permutation, s->dsp.idct_permutation);
1345
1346         s1->mpeg_enc_ctx_allocated = 1;
1347     }
1348     return 0;
1349 }
1350
1351 static int mpeg1_decode_picture(AVCodecContext *avctx,
1352                                 const uint8_t *buf, int buf_size)
1353 {
1354     Mpeg1Context *s1 = avctx->priv_data;
1355     MpegEncContext *s = &s1->mpeg_enc_ctx;
1356     int ref, f_code, vbv_delay;
1357
1358     init_get_bits(&s->gb, buf, buf_size*8);
1359
1360     ref = get_bits(&s->gb, 10); /* temporal ref */
1361     s->pict_type = get_bits(&s->gb, 3);
1362     if (s->pict_type == 0 || s->pict_type > 3)
1363         return -1;
1364
1365     vbv_delay = get_bits(&s->gb, 16);
1366     if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_B) {
1367         s->full_pel[0] = get_bits1(&s->gb);
1368         f_code = get_bits(&s->gb, 3);
1369         if (f_code == 0 && (avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)))
1370             return -1;
1371         f_code += !f_code;
1372         s->mpeg_f_code[0][0] = f_code;
1373         s->mpeg_f_code[0][1] = f_code;
1374     }
1375     if (s->pict_type == AV_PICTURE_TYPE_B) {
1376         s->full_pel[1] = get_bits1(&s->gb);
1377         f_code = get_bits(&s->gb, 3);
1378         if (f_code == 0 && (avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)))
1379             return -1;
1380         f_code += !f_code;
1381         s->mpeg_f_code[1][0] = f_code;
1382         s->mpeg_f_code[1][1] = f_code;
1383     }
1384     s->current_picture.f.pict_type = s->pict_type;
1385     s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1386
1387     if (avctx->debug & FF_DEBUG_PICT_INFO)
1388         av_log(avctx, AV_LOG_DEBUG, "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
1389
1390     s->y_dc_scale = 8;
1391     s->c_dc_scale = 8;
1392     return 0;
1393 }
1394
1395 static void mpeg_decode_sequence_extension(Mpeg1Context *s1)
1396 {
1397     MpegEncContext *s= &s1->mpeg_enc_ctx;
1398     int horiz_size_ext, vert_size_ext;
1399     int bit_rate_ext;
1400
1401     skip_bits(&s->gb, 1); /* profile and level esc*/
1402     s->avctx->profile       = get_bits(&s->gb, 3);
1403     s->avctx->level         = get_bits(&s->gb, 4);
1404     s->progressive_sequence = get_bits1(&s->gb); /* progressive_sequence */
1405     s->chroma_format        = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
1406     horiz_size_ext          = get_bits(&s->gb, 2);
1407     vert_size_ext           = get_bits(&s->gb, 2);
1408     s->width  |= (horiz_size_ext << 12);
1409     s->height |= (vert_size_ext  << 12);
1410     bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */
1411     s->bit_rate += (bit_rate_ext << 18) * 400;
1412     skip_bits1(&s->gb); /* marker */
1413     s->avctx->rc_buffer_size += get_bits(&s->gb, 8) * 1024 * 16 << 10;
1414
1415     s->low_delay = get_bits1(&s->gb);
1416     if (s->flags & CODEC_FLAG_LOW_DELAY)
1417         s->low_delay = 1;
1418
1419     s1->frame_rate_ext.num = get_bits(&s->gb, 2) + 1;
1420     s1->frame_rate_ext.den = get_bits(&s->gb, 5) + 1;
1421
1422     av_dlog(s->avctx, "sequence extension\n");
1423     s->codec_id      = s->avctx->codec_id = CODEC_ID_MPEG2VIDEO;
1424
1425     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1426         av_log(s->avctx, AV_LOG_DEBUG, "profile: %d, level: %d vbv buffer: %d, bitrate:%d\n",
1427                s->avctx->profile, s->avctx->level, s->avctx->rc_buffer_size, s->bit_rate);
1428
1429 }
1430
1431 static void mpeg_decode_sequence_display_extension(Mpeg1Context *s1)
1432 {
1433     MpegEncContext *s = &s1->mpeg_enc_ctx;
1434     int color_description, w, h;
1435
1436     skip_bits(&s->gb, 3); /* video format */
1437     color_description = get_bits1(&s->gb);
1438     if (color_description) {
1439         s->avctx->color_primaries = get_bits(&s->gb, 8);
1440         s->avctx->color_trc       = get_bits(&s->gb, 8);
1441         s->avctx->colorspace      = get_bits(&s->gb, 8);
1442     }
1443     w = get_bits(&s->gb, 14);
1444     skip_bits(&s->gb, 1); //marker
1445     h = get_bits(&s->gb, 14);
1446     // remaining 3 bits are zero padding
1447
1448     s1->pan_scan.width  = 16 * w;
1449     s1->pan_scan.height = 16 * h;
1450
1451     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1452         av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
1453 }
1454
1455 static void mpeg_decode_picture_display_extension(Mpeg1Context *s1)
1456 {
1457     MpegEncContext *s = &s1->mpeg_enc_ctx;
1458     int i, nofco;
1459
1460     nofco = 1;
1461     if (s->progressive_sequence) {
1462         if (s->repeat_first_field) {
1463             nofco++;
1464             if (s->top_field_first)
1465                 nofco++;
1466         }
1467     } else {
1468         if (s->picture_structure == PICT_FRAME) {
1469             nofco++;
1470             if (s->repeat_first_field)
1471                 nofco++;
1472         }
1473     }
1474     for (i = 0; i < nofco; i++) {
1475         s1->pan_scan.position[i][0] = get_sbits(&s->gb, 16);
1476         skip_bits(&s->gb, 1); // marker
1477         s1->pan_scan.position[i][1] = get_sbits(&s->gb, 16);
1478         skip_bits(&s->gb, 1); // marker
1479     }
1480
1481     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1482         av_log(s->avctx, AV_LOG_DEBUG, "pde (%d,%d) (%d,%d) (%d,%d)\n",
1483                s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
1484                s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
1485                s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]);
1486 }
1487
1488 static int load_matrix(MpegEncContext *s, uint16_t matrix0[64], uint16_t matrix1[64], int intra)
1489 {
1490     int i;
1491
1492     for (i = 0; i < 64; i++) {
1493         int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
1494         int v = get_bits(&s->gb, 8);
1495         if (v == 0) {
1496             av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");
1497             return -1;
1498         }
1499         if (intra && i == 0 && v != 8) {
1500             av_log(s->avctx, AV_LOG_DEBUG, "intra matrix specifies invalid DC quantizer %d, ignoring\n", v);
1501             v = 8; // needed by pink.mpg / issue1046
1502         }
1503         matrix0[j] = v;
1504         if (matrix1)
1505             matrix1[j] = v;
1506     }
1507     return 0;
1508 }
1509
1510 static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)
1511 {
1512     av_dlog(s->avctx, "matrix extension\n");
1513
1514     if (get_bits1(&s->gb)) load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
1515     if (get_bits1(&s->gb)) load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
1516     if (get_bits1(&s->gb)) load_matrix(s, s->chroma_intra_matrix, NULL           , 1);
1517     if (get_bits1(&s->gb)) load_matrix(s, s->chroma_inter_matrix, NULL           , 0);
1518 }
1519
1520 static void mpeg_decode_picture_coding_extension(Mpeg1Context *s1)
1521 {
1522     MpegEncContext *s = &s1->mpeg_enc_ctx;
1523
1524     s->full_pel[0] = s->full_pel[1] = 0;
1525     s->mpeg_f_code[0][0] = get_bits(&s->gb, 4);
1526     s->mpeg_f_code[0][1] = get_bits(&s->gb, 4);
1527     s->mpeg_f_code[1][0] = get_bits(&s->gb, 4);
1528     s->mpeg_f_code[1][1] = get_bits(&s->gb, 4);
1529     if (!s->pict_type && s1->mpeg_enc_ctx_allocated) {
1530         av_log(s->avctx, AV_LOG_ERROR, "Missing picture start code, guessing missing values\n");
1531         if (s->mpeg_f_code[1][0] == 15 && s->mpeg_f_code[1][1] == 15) {
1532             if (s->mpeg_f_code[0][0] == 15 && s->mpeg_f_code[0][1] == 15)
1533                 s->pict_type = AV_PICTURE_TYPE_I;
1534             else
1535                 s->pict_type = AV_PICTURE_TYPE_P;
1536         } else
1537             s->pict_type = AV_PICTURE_TYPE_B;
1538         s->current_picture.f.pict_type = s->pict_type;
1539         s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
1540     }
1541     s->mpeg_f_code[0][0] += !s->mpeg_f_code[0][0];
1542     s->mpeg_f_code[0][1] += !s->mpeg_f_code[0][1];
1543     s->mpeg_f_code[1][0] += !s->mpeg_f_code[1][0];
1544     s->mpeg_f_code[1][1] += !s->mpeg_f_code[1][1];
1545
1546     s->intra_dc_precision         = get_bits(&s->gb, 2);
1547     s->picture_structure          = get_bits(&s->gb, 2);
1548     s->top_field_first            = get_bits1(&s->gb);
1549     s->frame_pred_frame_dct       = get_bits1(&s->gb);
1550     s->concealment_motion_vectors = get_bits1(&s->gb);
1551     s->q_scale_type               = get_bits1(&s->gb);
1552     s->intra_vlc_format           = get_bits1(&s->gb);
1553     s->alternate_scan             = get_bits1(&s->gb);
1554     s->repeat_first_field         = get_bits1(&s->gb);
1555     s->chroma_420_type            = get_bits1(&s->gb);
1556     s->progressive_frame          = get_bits1(&s->gb);
1557
1558     if (s->progressive_sequence && !s->progressive_frame) {
1559         s->progressive_frame = 1;
1560         av_log(s->avctx, AV_LOG_ERROR, "interlaced frame in progressive sequence, ignoring\n");
1561     }
1562
1563     if (s->picture_structure == 0 || (s->progressive_frame && s->picture_structure != PICT_FRAME)) {
1564         av_log(s->avctx, AV_LOG_ERROR, "picture_structure %d invalid, ignoring\n", s->picture_structure);
1565         s->picture_structure = PICT_FRAME;
1566     }
1567
1568     if (s->progressive_sequence && !s->frame_pred_frame_dct) {
1569         av_log(s->avctx, AV_LOG_WARNING, "invalid frame_pred_frame_dct\n");
1570     }
1571
1572     if (s->picture_structure == PICT_FRAME) {
1573         s->first_field = 0;
1574         s->v_edge_pos  = 16 * s->mb_height;
1575     } else {
1576         s->first_field ^= 1;
1577         s->v_edge_pos   = 8 * s->mb_height;
1578         memset(s->mbskip_table, 0, s->mb_stride * s->mb_height);
1579     }
1580
1581     if (s->alternate_scan) {
1582         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
1583         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
1584     } else {
1585         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
1586         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
1587     }
1588
1589     /* composite display not parsed */
1590     av_dlog(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
1591     av_dlog(s->avctx, "picture_structure=%d\n", s->picture_structure);
1592     av_dlog(s->avctx, "top field first=%d\n", s->top_field_first);
1593     av_dlog(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
1594     av_dlog(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
1595     av_dlog(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
1596     av_dlog(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
1597     av_dlog(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1598     av_dlog(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
1599 }
1600
1601 static int mpeg_field_start(MpegEncContext *s, const uint8_t *buf, int buf_size)
1602 {
1603     AVCodecContext *avctx = s->avctx;
1604     Mpeg1Context *s1 = (Mpeg1Context*)s;
1605
1606     /* start frame decoding */
1607     if (s->first_field || s->picture_structure == PICT_FRAME) {
1608         if (ff_MPV_frame_start(s, avctx) < 0)
1609             return -1;
1610
1611         ff_er_frame_start(s);
1612
1613         /* first check if we must repeat the frame */
1614         s->current_picture_ptr->f.repeat_pict = 0;
1615         if (s->repeat_first_field) {
1616             if (s->progressive_sequence) {
1617                 if (s->top_field_first)
1618                     s->current_picture_ptr->f.repeat_pict = 4;
1619                 else
1620                     s->current_picture_ptr->f.repeat_pict = 2;
1621             } else if (s->progressive_frame) {
1622                 s->current_picture_ptr->f.repeat_pict = 1;
1623             }
1624         }
1625
1626         *s->current_picture_ptr->f.pan_scan = s1->pan_scan;
1627
1628         if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME))
1629             ff_thread_finish_setup(avctx);
1630     } else { // second field
1631         int i;
1632
1633         if (!s->current_picture_ptr) {
1634             av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
1635             return -1;
1636         }
1637
1638         for (i = 0; i < 4; i++) {
1639             s->current_picture.f.data[i] = s->current_picture_ptr->f.data[i];
1640             if (s->picture_structure == PICT_BOTTOM_FIELD) {
1641                 s->current_picture.f.data[i] += s->current_picture_ptr->f.linesize[i];
1642             }
1643         }
1644     }
1645
1646     if (avctx->hwaccel) {
1647         if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
1648             return -1;
1649     }
1650
1651 // MPV_frame_start will call this function too,
1652 // but we need to call it on every field
1653     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1654         if (ff_xvmc_field_start(s, avctx) < 0)
1655             return -1;
1656
1657     return 0;
1658 }
1659
1660 #define DECODE_SLICE_ERROR -1
1661 #define DECODE_SLICE_OK     0
1662
1663 /**
1664  * Decode a slice.
1665  * MpegEncContext.mb_y must be set to the MB row from the startcode.
1666  * @return DECODE_SLICE_ERROR if the slice is damaged,
1667  *         DECODE_SLICE_OK if this slice is OK
1668  */
1669 static int mpeg_decode_slice(MpegEncContext *s, int mb_y,
1670                              const uint8_t **buf, int buf_size)
1671 {
1672     AVCodecContext *avctx = s->avctx;
1673     const int lowres      = s->avctx->lowres;
1674     const int field_pic   = s->picture_structure != PICT_FRAME;
1675
1676     s->resync_mb_x =
1677     s->resync_mb_y = -1;
1678
1679     assert(mb_y < s->mb_height);
1680
1681     init_get_bits(&s->gb, *buf, buf_size * 8);
1682
1683     ff_mpeg1_clean_buffers(s);
1684     s->interlaced_dct = 0;
1685
1686     s->qscale = get_qscale(s);
1687
1688     if (s->qscale == 0) {
1689         av_log(s->avctx, AV_LOG_ERROR, "qscale == 0\n");
1690         return -1;
1691     }
1692
1693     /* extra slice info */
1694     while (get_bits1(&s->gb) != 0) {
1695         skip_bits(&s->gb, 8);
1696     }
1697
1698     s->mb_x = 0;
1699
1700     if (mb_y == 0 && s->codec_tag == AV_RL32("SLIF")) {
1701         skip_bits1(&s->gb);
1702     } else {
1703         while (get_bits_left(&s->gb) > 0) {
1704             int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1705             if (code < 0) {
1706                 av_log(s->avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
1707                 return -1;
1708             }
1709             if (code >= 33) {
1710                 if (code == 33) {
1711                     s->mb_x += 33;
1712                 }
1713                 /* otherwise, stuffing, nothing to do */
1714             } else {
1715                 s->mb_x += code;
1716                 break;
1717             }
1718         }
1719     }
1720
1721     if (s->mb_x >= (unsigned)s->mb_width) {
1722         av_log(s->avctx, AV_LOG_ERROR, "initial skip overflow\n");
1723         return -1;
1724     }
1725
1726     if (avctx->hwaccel) {
1727         const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */
1728         int start_code = -1;
1729         buf_end = avpriv_mpv_find_start_code(buf_start + 2, *buf + buf_size, &start_code);
1730         if (buf_end < *buf + buf_size)
1731             buf_end -= 4;
1732         s->mb_y = mb_y;
1733         if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_end - buf_start) < 0)
1734             return DECODE_SLICE_ERROR;
1735         *buf = buf_end;
1736         return DECODE_SLICE_OK;
1737     }
1738
1739     s->resync_mb_x = s->mb_x;
1740     s->resync_mb_y = s->mb_y = mb_y;
1741     s->mb_skip_run = 0;
1742     ff_init_block_index(s);
1743
1744     if (s->mb_y == 0 && s->mb_x == 0 && (s->first_field || s->picture_structure == PICT_FRAME)) {
1745         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
1746              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",
1747                     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],
1748                     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")),
1749                     s->progressive_sequence ? "ps" :"", s->progressive_frame ? "pf" : "", s->alternate_scan ? "alt" :"", s->top_field_first ? "top" :"",
1750                     s->intra_dc_precision, s->picture_structure, s->frame_pred_frame_dct, s->concealment_motion_vectors,
1751                     s->q_scale_type, s->intra_vlc_format, s->repeat_first_field, s->chroma_420_type ? "420" :"");
1752         }
1753     }
1754
1755     for (;;) {
1756         // If 1, we memcpy blocks in xvmcvideo.
1757         if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration > 1)
1758             ff_xvmc_init_block(s); // set s->block
1759
1760         if (mpeg_decode_mb(s, s->block) < 0)
1761             return -1;
1762
1763         if (s->current_picture.f.motion_val[0] && !s->encoding) { // note motion_val is normally NULL unless we want to extract the MVs
1764             const int wrap = s->b8_stride;
1765             int xy         = s->mb_x * 2 + s->mb_y * 2 * wrap;
1766             int b8_xy      = 4 * (s->mb_x + s->mb_y * s->mb_stride);
1767             int motion_x, motion_y, dir, i;
1768
1769             for (i = 0; i < 2; i++) {
1770                 for (dir = 0; dir < 2; dir++) {
1771                     if (s->mb_intra || (dir == 1 && s->pict_type != AV_PICTURE_TYPE_B)) {
1772                         motion_x = motion_y = 0;
1773                     } else if (s->mv_type == MV_TYPE_16X16 || (s->mv_type == MV_TYPE_FIELD && field_pic)) {
1774                         motion_x = s->mv[dir][0][0];
1775                         motion_y = s->mv[dir][0][1];
1776                     } else /*if ((s->mv_type == MV_TYPE_FIELD) || (s->mv_type == MV_TYPE_16X8))*/ {
1777                         motion_x = s->mv[dir][i][0];
1778                         motion_y = s->mv[dir][i][1];
1779                     }
1780
1781                     s->current_picture.f.motion_val[dir][xy    ][0] = motion_x;
1782                     s->current_picture.f.motion_val[dir][xy    ][1] = motion_y;
1783                     s->current_picture.f.motion_val[dir][xy + 1][0] = motion_x;
1784                     s->current_picture.f.motion_val[dir][xy + 1][1] = motion_y;
1785                     s->current_picture.f.ref_index [dir][b8_xy    ] =
1786                     s->current_picture.f.ref_index [dir][b8_xy + 1] = s->field_select[dir][i];
1787                     assert(s->field_select[dir][i] == 0 || s->field_select[dir][i] == 1);
1788                 }
1789                 xy += wrap;
1790                 b8_xy +=2;
1791             }
1792         }
1793
1794         s->dest[0] += 16 >> lowres;
1795         s->dest[1] +=(16 >> lowres) >> s->chroma_x_shift;
1796         s->dest[2] +=(16 >> lowres) >> s->chroma_x_shift;
1797
1798         ff_MPV_decode_mb(s, s->block);
1799
1800         if (++s->mb_x >= s->mb_width) {
1801             const int mb_size = 16 >> s->avctx->lowres;
1802
1803             ff_draw_horiz_band(s, mb_size*(s->mb_y >> field_pic), mb_size);
1804             ff_MPV_report_decode_progress(s);
1805
1806             s->mb_x = 0;
1807             s->mb_y += 1 << field_pic;
1808
1809             if (s->mb_y >= s->mb_height) {
1810                 int left   = get_bits_left(&s->gb);
1811                 int is_d10 = s->chroma_format == 2 && s->pict_type == AV_PICTURE_TYPE_I && avctx->profile == 0 && avctx->level == 5
1812                              && s->intra_dc_precision == 2 && s->q_scale_type == 1 && s->alternate_scan == 0
1813                              && s->progressive_frame == 0 /* vbv_delay == 0xBBB || 0xE10*/;
1814
1815                 if (left < 0 || (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10)
1816                     || ((avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_AGGRESSIVE)) && left > 8)) {
1817                     av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X\n", left, show_bits(&s->gb, FFMIN(left, 23)));
1818                     return -1;
1819                 } else
1820                     goto eos;
1821             }
1822
1823             ff_init_block_index(s);
1824         }
1825
1826         /* skip mb handling */
1827         if (s->mb_skip_run == -1) {
1828             /* read increment again */
1829             s->mb_skip_run = 0;
1830             for (;;) {
1831                 int code = get_vlc2(&s->gb, mbincr_vlc.table, MBINCR_VLC_BITS, 2);
1832                 if (code < 0) {
1833                     av_log(s->avctx, AV_LOG_ERROR, "mb incr damaged\n");
1834                     return -1;
1835                 }
1836                 if (code >= 33) {
1837                     if (code == 33) {
1838                         s->mb_skip_run += 33;
1839                     } else if (code == 35) {
1840                         if (s->mb_skip_run != 0 || show_bits(&s->gb, 15) != 0) {
1841                             av_log(s->avctx, AV_LOG_ERROR, "slice mismatch\n");
1842                             return -1;
1843                         }
1844                         goto eos; /* end of slice */
1845                     }
1846                     /* otherwise, stuffing, nothing to do */
1847                 } else {
1848                     s->mb_skip_run += code;
1849                     break;
1850                 }
1851             }
1852             if (s->mb_skip_run) {
1853                 int i;
1854                 if (s->pict_type == AV_PICTURE_TYPE_I) {
1855                     av_log(s->avctx, AV_LOG_ERROR, "skipped MB in I frame at %d %d\n", s->mb_x, s->mb_y);
1856                     return -1;
1857                 }
1858
1859                 /* skip mb */
1860                 s->mb_intra = 0;
1861                 for (i = 0; i < 12; i++)
1862                     s->block_last_index[i] = -1;
1863                 if (s->picture_structure == PICT_FRAME)
1864                     s->mv_type = MV_TYPE_16X16;
1865                 else
1866                     s->mv_type = MV_TYPE_FIELD;
1867                 if (s->pict_type == AV_PICTURE_TYPE_P) {
1868                     /* if P type, zero motion vector is implied */
1869                     s->mv_dir             = MV_DIR_FORWARD;
1870                     s->mv[0][0][0]        = s->mv[0][0][1]      = 0;
1871                     s->last_mv[0][0][0]   = s->last_mv[0][0][1] = 0;
1872                     s->last_mv[0][1][0]   = s->last_mv[0][1][1] = 0;
1873                     s->field_select[0][0] = (s->picture_structure - 1) & 1;
1874                 } else {
1875                     /* if B type, reuse previous vectors and directions */
1876                     s->mv[0][0][0] = s->last_mv[0][0][0];
1877                     s->mv[0][0][1] = s->last_mv[0][0][1];
1878                     s->mv[1][0][0] = s->last_mv[1][0][0];
1879                     s->mv[1][0][1] = s->last_mv[1][0][1];
1880                 }
1881             }
1882         }
1883     }
1884 eos: // end of slice
1885     *buf += (get_bits_count(&s->gb)-1)/8;
1886 //printf("y %d %d %d %d\n", s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y);
1887     return 0;
1888 }
1889
1890 static int slice_decode_thread(AVCodecContext *c, void *arg)
1891 {
1892     MpegEncContext *s   = *(void**)arg;
1893     const uint8_t *buf  = s->gb.buffer;
1894     int mb_y            = s->start_mb_y;
1895     const int field_pic = s->picture_structure != PICT_FRAME;
1896
1897     s->error_count = (3 * (s->end_mb_y - s->start_mb_y) * s->mb_width) >> field_pic;
1898
1899     for (;;) {
1900         uint32_t start_code;
1901         int ret;
1902
1903         ret = mpeg_decode_slice(s, mb_y, &buf, s->gb.buffer_end - buf);
1904         emms_c();
1905 //av_log(c, AV_LOG_DEBUG, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
1906 //ret, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, s->start_mb_y, s->end_mb_y, s->error_count);
1907         if (ret < 0) {
1908             if (c->err_recognition & AV_EF_EXPLODE)
1909                 return ret;
1910             if (s->resync_mb_x >= 0 && s->resync_mb_y >= 0)
1911                 ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
1912         } else {
1913             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, ER_AC_END | ER_DC_END | ER_MV_END);
1914         }
1915
1916         if (s->mb_y == s->end_mb_y)
1917             return 0;
1918
1919         start_code = -1;
1920         buf = avpriv_mpv_find_start_code(buf, s->gb.buffer_end, &start_code);
1921         mb_y= (start_code - SLICE_MIN_START_CODE) << field_pic;
1922         if (s->picture_structure == PICT_BOTTOM_FIELD)
1923             mb_y++;
1924         if (mb_y < 0 || mb_y >= s->end_mb_y)
1925             return -1;
1926     }
1927 }
1928
1929 /**
1930  * Handle slice ends.
1931  * @return 1 if it seems to be the last slice
1932  */
1933 static int slice_end(AVCodecContext *avctx, AVFrame *pict)
1934 {
1935     Mpeg1Context *s1 = avctx->priv_data;
1936     MpegEncContext *s = &s1->mpeg_enc_ctx;
1937
1938     if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)
1939         return 0;
1940
1941     if (s->avctx->hwaccel) {
1942         if (s->avctx->hwaccel->end_frame(s->avctx) < 0)
1943             av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
1944     }
1945
1946     if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
1947         ff_xvmc_field_end(s);
1948
1949     /* end of slice reached */
1950     if (/*s->mb_y << field_pic == s->mb_height &&*/ !s->first_field && !s->first_slice) {
1951         /* end of image */
1952
1953         s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_MPEG2;
1954
1955         ff_er_frame_end(s);
1956
1957         ff_MPV_frame_end(s);
1958
1959         if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
1960             *pict = s->current_picture_ptr->f;
1961             ff_print_debug_info(s, pict);
1962         } else {
1963             if (avctx->active_thread_type & FF_THREAD_FRAME)
1964                 s->picture_number++;
1965             /* latency of 1 frame for I- and P-frames */
1966             /* XXX: use another variable than picture_number */
1967             if (s->last_picture_ptr != NULL) {
1968                 *pict = s->last_picture_ptr->f;
1969                  ff_print_debug_info(s, pict);
1970             }
1971         }
1972
1973         return 1;
1974     } else {
1975         return 0;
1976     }
1977 }
1978
1979 static int mpeg1_decode_sequence(AVCodecContext *avctx,
1980                                  const uint8_t *buf, int buf_size)
1981 {
1982     Mpeg1Context *s1 = avctx->priv_data;
1983     MpegEncContext *s = &s1->mpeg_enc_ctx;
1984     int width, height;
1985     int i, v, j;
1986
1987     init_get_bits(&s->gb, buf, buf_size*8);
1988
1989     width  = get_bits(&s->gb, 12);
1990     height = get_bits(&s->gb, 12);
1991     if (width <= 0 || height <= 0)
1992         return -1;
1993     s->aspect_ratio_info = get_bits(&s->gb, 4);
1994     if (s->aspect_ratio_info == 0) {
1995         av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
1996         if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
1997             return -1;
1998     }
1999     s->frame_rate_index = get_bits(&s->gb, 4);
2000     if (s->frame_rate_index == 0 || s->frame_rate_index > 13)
2001         return -1;
2002     s->bit_rate = get_bits(&s->gb, 18) * 400;
2003     if (get_bits1(&s->gb) == 0) /* marker */
2004         return -1;
2005     s->width  = width;
2006     s->height = height;
2007
2008     s->avctx->rc_buffer_size = get_bits(&s->gb, 10) * 1024 * 16;
2009     skip_bits(&s->gb, 1);
2010
2011     /* get matrix */
2012     if (get_bits1(&s->gb)) {
2013         load_matrix(s, s->chroma_intra_matrix, s->intra_matrix, 1);
2014     } else {
2015         for (i = 0; i < 64; i++) {
2016             j = s->dsp.idct_permutation[i];
2017             v = ff_mpeg1_default_intra_matrix[i];
2018             s->intra_matrix[j]        = v;
2019             s->chroma_intra_matrix[j] = v;
2020         }
2021     }
2022     if (get_bits1(&s->gb)) {
2023         load_matrix(s, s->chroma_inter_matrix, s->inter_matrix, 0);
2024     } else {
2025         for (i = 0; i < 64; i++) {
2026             int j = s->dsp.idct_permutation[i];
2027             v = ff_mpeg1_default_non_intra_matrix[i];
2028             s->inter_matrix[j]        = v;
2029             s->chroma_inter_matrix[j] = v;
2030         }
2031     }
2032
2033     if (show_bits(&s->gb, 23) != 0) {
2034         av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
2035         return -1;
2036     }
2037
2038     /* we set MPEG-2 parameters so that it emulates MPEG-1 */
2039     s->progressive_sequence = 1;
2040     s->progressive_frame    = 1;
2041     s->picture_structure    = PICT_FRAME;
2042     s->first_field          = 0;
2043     s->frame_pred_frame_dct = 1;
2044     s->chroma_format        = 1;
2045     s->codec_id             = s->avctx->codec_id = CODEC_ID_MPEG1VIDEO;
2046     s->out_format           = FMT_MPEG1;
2047     s->swap_uv              = 0; // AFAIK VCR2 does not have SEQ_HEADER
2048     if (s->flags & CODEC_FLAG_LOW_DELAY)
2049         s->low_delay = 1;
2050
2051     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2052         av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%d\n",
2053                s->avctx->rc_buffer_size, s->bit_rate);
2054
2055     return 0;
2056 }
2057
2058 static int vcr2_init_sequence(AVCodecContext *avctx)
2059 {
2060     Mpeg1Context *s1 = avctx->priv_data;
2061     MpegEncContext *s = &s1->mpeg_enc_ctx;
2062     int i, v;
2063
2064     /* start new MPEG-1 context decoding */
2065     s->out_format = FMT_MPEG1;
2066     if (s1->mpeg_enc_ctx_allocated) {
2067         ff_MPV_common_end(s);
2068     }
2069     s->width  = avctx->coded_width;
2070     s->height = avctx->coded_height;
2071     avctx->has_b_frames = 0; // true?
2072     s->low_delay = 1;
2073
2074     avctx->pix_fmt = mpeg_get_pixelformat(avctx);
2075     avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
2076
2077     if( avctx->pix_fmt == PIX_FMT_XVMC_MPEG2_IDCT || avctx->hwaccel )
2078         if (avctx->idct_algo == FF_IDCT_AUTO)
2079             avctx->idct_algo = FF_IDCT_SIMPLE;
2080
2081     if (ff_MPV_common_init(s) < 0)
2082         return -1;
2083     s1->mpeg_enc_ctx_allocated = 1;
2084
2085     for (i = 0; i < 64; i++) {
2086         int j = s->dsp.idct_permutation[i];
2087         v = ff_mpeg1_default_intra_matrix[i];
2088         s->intra_matrix[j]        = v;
2089         s->chroma_intra_matrix[j] = v;
2090
2091         v = ff_mpeg1_default_non_intra_matrix[i];
2092         s->inter_matrix[j]        = v;
2093         s->chroma_inter_matrix[j] = v;
2094     }
2095
2096     s->progressive_sequence  = 1;
2097     s->progressive_frame     = 1;
2098     s->picture_structure     = PICT_FRAME;
2099     s->first_field           = 0;
2100     s->frame_pred_frame_dct  = 1;
2101     s->chroma_format         = 1;
2102     if (s->codec_tag == AV_RL32("BW10")) {
2103         s->codec_id              = s->avctx->codec_id = CODEC_ID_MPEG1VIDEO;
2104     } else {
2105         exchange_uv(s); // common init reset pblocks, so we swap them here
2106         s->swap_uv = 1; // in case of xvmc we need to swap uv for each MB
2107         s->codec_id              = s->avctx->codec_id = CODEC_ID_MPEG2VIDEO;
2108     }
2109     s1->save_width           = s->width;
2110     s1->save_height          = s->height;
2111     s1->save_progressive_seq = s->progressive_sequence;
2112     return 0;
2113 }
2114
2115
2116 static void mpeg_decode_user_data(AVCodecContext *avctx,
2117                                   const uint8_t *p, int buf_size)
2118 {
2119     Mpeg1Context *s = avctx->priv_data;
2120     const uint8_t *buf_end = p + buf_size;
2121
2122     if(buf_size > 29){
2123         int i;
2124         for(i=0; i<20; i++)
2125             if(!memcmp(p+i, "\0TMPGEXS\0", 9)){
2126                 s->tmpgexs= 1;
2127             }
2128
2129 /*        for(i=0; !(!p[i-2] && !p[i-1] && p[i]==1) && i<buf_size; i++){
2130             av_log(0,0, "%c", p[i]);
2131         }
2132             av_log(0,0, "\n");*/
2133     }
2134
2135     /* we parse the DTG active format information */
2136     if (buf_end - p >= 5 &&
2137         p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2138         int flags = p[4];
2139         p += 5;
2140         if (flags & 0x80) {
2141             /* skip event id */
2142             p += 2;
2143         }
2144         if (flags & 0x40) {
2145             if (buf_end - p < 1)
2146                 return;
2147             avctx->dtg_active_format = p[0] & 0x0f;
2148         }
2149     }
2150 }
2151
2152 static void mpeg_decode_gop(AVCodecContext *avctx,
2153                             const uint8_t *buf, int buf_size)
2154 {
2155     Mpeg1Context *s1  = avctx->priv_data;
2156     MpegEncContext *s = &s1->mpeg_enc_ctx;
2157     int broken_link;
2158     int64_t tc;
2159
2160     init_get_bits(&s->gb, buf, buf_size*8);
2161
2162     tc = avctx->timecode_frame_start = get_bits(&s->gb, 25);
2163
2164     s->closed_gop = get_bits1(&s->gb);
2165     /*broken_link indicate that after editing the
2166       reference frames of the first B-Frames after GOP I-Frame
2167       are missing (open gop)*/
2168     broken_link = get_bits1(&s->gb);
2169
2170     if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2171         char tcbuf[AV_TIMECODE_STR_SIZE];
2172         av_timecode_make_mpeg_tc_string(tcbuf, tc);
2173         av_log(s->avctx, AV_LOG_DEBUG,
2174                "GOP (%s) closed_gop=%d broken_link=%d\n",
2175                tcbuf, s->closed_gop, broken_link);
2176     }
2177 }
2178 /**
2179  * Find the end of the current frame in the bitstream.
2180  * @return the position of the first byte of the next frame, or -1
2181  */
2182 int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size, AVCodecParserContext *s)
2183 {
2184     int i;
2185     uint32_t state = pc->state;
2186
2187     /* EOF considered as end of frame */
2188     if (buf_size == 0)
2189         return 0;
2190
2191 /*
2192  0  frame start         -> 1/4
2193  1  first_SEQEXT        -> 0/2
2194  2  first field start   -> 3/0
2195  3  second_SEQEXT       -> 2/0
2196  4  searching end
2197 */
2198
2199     for (i = 0; i < buf_size; i++) {
2200         assert(pc->frame_start_found >= 0 && pc->frame_start_found <= 4);
2201         if (pc->frame_start_found & 1) {
2202             if (state == EXT_START_CODE && (buf[i] & 0xF0) != 0x80)
2203                 pc->frame_start_found--;
2204             else if (state == EXT_START_CODE + 2) {
2205                 if ((buf[i] & 3) == 3)
2206                     pc->frame_start_found = 0;
2207                 else
2208                     pc->frame_start_found = (pc->frame_start_found + 1) & 3;
2209             }
2210             state++;
2211         } else {
2212             i = avpriv_mpv_find_start_code(buf + i, buf + buf_size, &state) - buf - 1;
2213             if (pc->frame_start_found == 0 && state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE) {
2214                 i++;
2215                 pc->frame_start_found = 4;
2216             }
2217             if (state == SEQ_END_CODE) {
2218                 pc->frame_start_found = 0;
2219                 pc->state=-1;
2220                 return i+1;
2221             }
2222             if (pc->frame_start_found == 2 && state == SEQ_START_CODE)
2223                 pc->frame_start_found = 0;
2224             if (pc->frame_start_found  < 4 && state == EXT_START_CODE)
2225                 pc->frame_start_found++;
2226             if (pc->frame_start_found == 4 && (state & 0xFFFFFF00) == 0x100) {
2227                 if (state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE) {
2228                     pc->frame_start_found = 0;
2229                     pc->state             = -1;
2230                     return i - 3;
2231                 }
2232             }
2233             if (pc->frame_start_found == 0 && s && state == PICTURE_START_CODE) {
2234                 ff_fetch_timestamp(s, i - 3, 1);
2235             }
2236         }
2237     }
2238     pc->state = state;
2239     return END_NOT_FOUND;
2240 }
2241
2242 static int decode_chunks(AVCodecContext *avctx,
2243                          AVFrame *picture, int *data_size,
2244                          const uint8_t *buf, int buf_size);
2245
2246 /* handle buffering and image synchronisation */
2247 static int mpeg_decode_frame(AVCodecContext *avctx,
2248                              void *data, int *data_size,
2249                              AVPacket *avpkt)
2250 {
2251     const uint8_t *buf = avpkt->data;
2252     int buf_size = avpkt->size;
2253     Mpeg1Context *s = avctx->priv_data;
2254     AVFrame *picture = data;
2255     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2256     av_dlog(avctx, "fill_buffer\n");
2257
2258     if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2259         /* special case for last picture */
2260         if (s2->low_delay == 0 && s2->next_picture_ptr) {
2261             *picture = s2->next_picture_ptr->f;
2262             s2->next_picture_ptr = NULL;
2263
2264             *data_size = sizeof(AVFrame);
2265         }
2266         return buf_size;
2267     }
2268
2269     if (s2->flags & CODEC_FLAG_TRUNCATED) {
2270         int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size, NULL);
2271
2272         if (ff_combine_frame(&s2->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0)
2273             return buf_size;
2274     }
2275
2276     s2->codec_tag = avpriv_toupper4(avctx->codec_tag);
2277     if (s->mpeg_enc_ctx_allocated == 0 && (   s2->codec_tag == AV_RL32("VCR2")
2278                                            || s2->codec_tag == AV_RL32("BW10")
2279                                           ))
2280         vcr2_init_sequence(avctx);
2281
2282     s->slice_count = 0;
2283
2284     if (avctx->extradata && !avctx->frame_number) {
2285         int ret = decode_chunks(avctx, picture, data_size, avctx->extradata, avctx->extradata_size);
2286         if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
2287             return ret;
2288     }
2289
2290     return decode_chunks(avctx, picture, data_size, buf, buf_size);
2291 }
2292
2293 static int decode_chunks(AVCodecContext *avctx,
2294                          AVFrame *picture, int *data_size,
2295                          const uint8_t *buf, int buf_size)
2296 {
2297     Mpeg1Context *s = avctx->priv_data;
2298     MpegEncContext *s2 = &s->mpeg_enc_ctx;
2299     const uint8_t *buf_ptr = buf;
2300     const uint8_t *buf_end = buf + buf_size;
2301     int ret, input_size;
2302     int last_code = 0;
2303
2304     for (;;) {
2305         /* find next start code */
2306         uint32_t start_code = -1;
2307         buf_ptr = avpriv_mpv_find_start_code(buf_ptr, buf_end, &start_code);
2308         if (start_code > 0x1ff) {
2309             if (s2->pict_type != AV_PICTURE_TYPE_B || avctx->skip_frame <= AVDISCARD_DEFAULT) {
2310                 if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {
2311                     int i;
2312                     av_assert0(avctx->thread_count > 1);
2313
2314                     avctx->execute(avctx, slice_decode_thread,  &s2->thread_context[0], NULL, s->slice_count, sizeof(void*));
2315                     for (i = 0; i < s->slice_count; i++)
2316                         s2->error_count += s2->thread_context[i]->error_count;
2317                 }
2318
2319                 if (CONFIG_VDPAU && uses_vdpau(avctx))
2320                     ff_vdpau_mpeg_picture_complete(s2, buf, buf_size, s->slice_count);
2321
2322
2323                 if (slice_end(avctx, picture)) {
2324                     if (s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice
2325                         *data_size = sizeof(AVPicture);
2326                 }
2327             }
2328             s2->pict_type = 0;
2329             return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);
2330         }
2331
2332         input_size = buf_end - buf_ptr;
2333
2334         if (avctx->debug & FF_DEBUG_STARTCODE) {
2335             av_log(avctx, AV_LOG_DEBUG, "%3X at %td left %d\n", start_code, buf_ptr-buf, input_size);
2336         }
2337
2338         /* prepare data for next start code */
2339         switch (start_code) {
2340         case SEQ_START_CODE:
2341             if (last_code == 0) {
2342                 mpeg1_decode_sequence(avctx, buf_ptr, input_size);
2343                 if(buf != avctx->extradata)
2344                     s->sync=1;
2345             } else {
2346                 av_log(avctx, AV_LOG_ERROR, "ignoring SEQ_START_CODE after %X\n", last_code);
2347                 if (avctx->err_recognition & AV_EF_EXPLODE)
2348                     return AVERROR_INVALIDDATA;
2349             }
2350             break;
2351
2352         case PICTURE_START_CODE:
2353             if(s->tmpgexs){
2354                 s2->intra_dc_precision= 3;
2355                 s2->intra_matrix[0]= 1;
2356             }
2357             if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) && s->slice_count) {
2358                 int i;
2359
2360                 avctx->execute(avctx, slice_decode_thread,
2361                                s2->thread_context, NULL,
2362                                s->slice_count, sizeof(void*));
2363                 for (i = 0; i < s->slice_count; i++)
2364                     s2->error_count += s2->thread_context[i]->error_count;
2365                 s->slice_count = 0;
2366             }
2367             if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {
2368                 ret = mpeg_decode_postinit(avctx);
2369                 if (ret < 0) {
2370                     av_log(avctx, AV_LOG_ERROR, "mpeg_decode_postinit() failure\n");
2371                     return ret;
2372                 }
2373
2374                 /* we have a complete image: we try to decompress it */
2375                 if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)
2376                     s2->pict_type = 0;
2377                 s2->first_slice = 1;
2378                 last_code = PICTURE_START_CODE;
2379             } else {
2380                 av_log(avctx, AV_LOG_ERROR, "ignoring pic after %X\n", last_code);
2381                 if (avctx->err_recognition & AV_EF_EXPLODE)
2382                     return AVERROR_INVALIDDATA;
2383             }
2384             break;
2385         case EXT_START_CODE:
2386             init_get_bits(&s2->gb, buf_ptr, input_size*8);
2387
2388             switch (get_bits(&s2->gb, 4)) {
2389             case 0x1:
2390                 if (last_code == 0) {
2391                 mpeg_decode_sequence_extension(s);
2392                 } else {
2393                     av_log(avctx, AV_LOG_ERROR, "ignoring seq ext after %X\n", last_code);
2394                     if (avctx->err_recognition & AV_EF_EXPLODE)
2395                         return AVERROR_INVALIDDATA;
2396                 }
2397                 break;
2398             case 0x2:
2399                 mpeg_decode_sequence_display_extension(s);
2400                 break;
2401             case 0x3:
2402                 mpeg_decode_quant_matrix_extension(s2);
2403                 break;
2404             case 0x7:
2405                 mpeg_decode_picture_display_extension(s);
2406                 break;
2407             case 0x8:
2408                 if (last_code == PICTURE_START_CODE) {
2409                     mpeg_decode_picture_coding_extension(s);
2410                 } else {
2411                     av_log(avctx, AV_LOG_ERROR, "ignoring pic cod ext after %X\n", last_code);
2412                     if (avctx->err_recognition & AV_EF_EXPLODE)
2413                         return AVERROR_INVALIDDATA;
2414                 }
2415                 break;
2416             }
2417             break;
2418         case USER_START_CODE:
2419             mpeg_decode_user_data(avctx, buf_ptr, input_size);
2420             break;
2421         case GOP_START_CODE:
2422             if (last_code == 0) {
2423                 s2->first_field=0;
2424                 mpeg_decode_gop(avctx, buf_ptr, input_size);
2425                 s->sync=1;
2426             } else {
2427                 av_log(avctx, AV_LOG_ERROR, "ignoring GOP_START_CODE after %X\n", last_code);
2428                 if (avctx->err_recognition & AV_EF_EXPLODE)
2429                     return AVERROR_INVALIDDATA;
2430             }
2431             break;
2432         default:
2433             if (start_code >= SLICE_MIN_START_CODE &&
2434                 start_code <= SLICE_MAX_START_CODE && last_code != 0) {
2435                 const int field_pic = s2->picture_structure != PICT_FRAME;
2436                 int mb_y = (start_code - SLICE_MIN_START_CODE) << field_pic;
2437                 last_code = SLICE_MIN_START_CODE;
2438
2439                 if (s2->picture_structure == PICT_BOTTOM_FIELD)
2440                     mb_y++;
2441
2442                 if (mb_y >= s2->mb_height) {
2443                     av_log(s2->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s2->mb_height);
2444                     return -1;
2445                 }
2446
2447                 if (s2->last_picture_ptr == NULL) {
2448                 /* Skip B-frames if we do not have reference frames and gop is not closed */
2449                     if (s2->pict_type == AV_PICTURE_TYPE_B) {
2450                         if (!s2->closed_gop)
2451                             break;
2452                     }
2453                 }
2454                 if (s2->pict_type == AV_PICTURE_TYPE_I || (s2->flags2 & CODEC_FLAG2_SHOW_ALL))
2455                     s->sync=1;
2456                 if (s2->next_picture_ptr == NULL) {
2457                 /* Skip P-frames if we do not have a reference frame or we have an invalid header. */
2458                     if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) break;
2459                 }
2460                 if ((avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type == AV_PICTURE_TYPE_B) ||
2461                     (avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type != AV_PICTURE_TYPE_I) ||
2462                      avctx->skip_frame >= AVDISCARD_ALL)
2463                     break;
2464
2465                 if (!s->mpeg_enc_ctx_allocated)
2466                     break;
2467
2468                 if (s2->codec_id == CODEC_ID_MPEG2VIDEO) {
2469                     if (mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)
2470                         break;
2471                 }
2472
2473                 if (!s2->pict_type) {
2474                     av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2475                     if (avctx->err_recognition & AV_EF_EXPLODE)
2476                         return AVERROR_INVALIDDATA;
2477                     break;
2478                 }
2479
2480                 if (s2->first_slice) {
2481                     s2->first_slice = 0;
2482                     if (mpeg_field_start(s2, buf, buf_size) < 0)
2483                         return -1;
2484                 }
2485                 if (!s2->current_picture_ptr) {
2486                     av_log(avctx, AV_LOG_ERROR, "current_picture not initialized\n");
2487                     return AVERROR_INVALIDDATA;
2488                 }
2489
2490                 if (uses_vdpau(avctx)) {
2491                     s->slice_count++;
2492                     break;
2493                 }
2494
2495                 if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {
2496                     int threshold = (s2->mb_height * s->slice_count +
2497                                      s2->slice_context_count / 2) /
2498                                     s2->slice_context_count;
2499                     av_assert0(avctx->thread_count > 1);
2500                     if (threshold <= mb_y) {
2501                         MpegEncContext *thread_context = s2->thread_context[s->slice_count];
2502
2503                         thread_context->start_mb_y = mb_y;
2504                         thread_context->end_mb_y   = s2->mb_height;
2505                         if (s->slice_count) {
2506                             s2->thread_context[s->slice_count-1]->end_mb_y = mb_y;
2507                             ff_update_duplicate_context(thread_context, s2);
2508                         }
2509                         init_get_bits(&thread_context->gb, buf_ptr, input_size*8);
2510                         s->slice_count++;
2511                     }
2512                     buf_ptr += 2; // FIXME add minimum number of bytes per slice
2513                 } else {
2514                     ret = mpeg_decode_slice(s2, mb_y, &buf_ptr, input_size);
2515                     emms_c();
2516
2517                     if (ret < 0) {
2518                         if (avctx->err_recognition & AV_EF_EXPLODE)
2519                             return ret;
2520                         if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)
2521                             ff_er_add_slice(s2, s2->resync_mb_x, s2->resync_mb_y, s2->mb_x, s2->mb_y, ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
2522                     } else {
2523                         ff_er_add_slice(s2, s2->resync_mb_x, s2->resync_mb_y, s2->mb_x-1, s2->mb_y, ER_AC_END | ER_DC_END | ER_MV_END);
2524                     }
2525                 }
2526             }
2527             break;
2528         }
2529     }
2530 }
2531
2532 static void flush(AVCodecContext *avctx)
2533 {
2534     Mpeg1Context *s = avctx->priv_data;
2535
2536     s->sync=0;
2537
2538     ff_mpeg_flush(avctx);
2539 }
2540
2541 static int mpeg_decode_end(AVCodecContext *avctx)
2542 {
2543     Mpeg1Context *s = avctx->priv_data;
2544
2545     if (s->mpeg_enc_ctx_allocated)
2546         ff_MPV_common_end(&s->mpeg_enc_ctx);
2547     return 0;
2548 }
2549
2550 static const AVProfile mpeg2_video_profiles[] = {
2551     { FF_PROFILE_MPEG2_422,          "4:2:2"              },
2552     { FF_PROFILE_MPEG2_HIGH,         "High"               },
2553     { FF_PROFILE_MPEG2_SS,           "Spatially Scalable" },
2554     { FF_PROFILE_MPEG2_SNR_SCALABLE, "SNR Scalable"       },
2555     { FF_PROFILE_MPEG2_MAIN,         "Main"               },
2556     { FF_PROFILE_MPEG2_SIMPLE,       "Simple"             },
2557     { FF_PROFILE_RESERVED,           "Reserved"           },
2558     { FF_PROFILE_RESERVED,           "Reserved"           },
2559     { FF_PROFILE_UNKNOWN },
2560 };
2561
2562
2563 AVCodec ff_mpeg1video_decoder = {
2564     .name                  = "mpeg1video",
2565     .type                  = AVMEDIA_TYPE_VIDEO,
2566     .id                    = CODEC_ID_MPEG1VIDEO,
2567     .priv_data_size        = sizeof(Mpeg1Context),
2568     .init                  = mpeg_decode_init,
2569     .close                 = mpeg_decode_end,
2570     .decode                = mpeg_decode_frame,
2571     .capabilities          = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2572                              CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2573                              CODEC_CAP_SLICE_THREADS,
2574     .flush                 = flush,
2575     .max_lowres            = 3,
2576     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2577     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg_decode_update_thread_context)
2578 };
2579
2580 AVCodec ff_mpeg2video_decoder = {
2581     .name           = "mpeg2video",
2582     .type           = AVMEDIA_TYPE_VIDEO,
2583     .id             = CODEC_ID_MPEG2VIDEO,
2584     .priv_data_size = sizeof(Mpeg1Context),
2585     .init           = mpeg_decode_init,
2586     .close          = mpeg_decode_end,
2587     .decode         = mpeg_decode_frame,
2588     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2589                       CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY |
2590                       CODEC_CAP_SLICE_THREADS,
2591     .flush          = flush,
2592     .max_lowres     = 3,
2593     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
2594     .profiles       = NULL_IF_CONFIG_SMALL(mpeg2_video_profiles),
2595 };
2596
2597 //legacy decoder
2598 AVCodec ff_mpegvideo_decoder = {
2599     .name           = "mpegvideo",
2600     .type           = AVMEDIA_TYPE_VIDEO,
2601     .id             = CODEC_ID_MPEG2VIDEO,
2602     .priv_data_size = sizeof(Mpeg1Context),
2603     .init           = mpeg_decode_init,
2604     .close          = mpeg_decode_end,
2605     .decode         = mpeg_decode_frame,
2606     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
2607     .flush          = flush,
2608     .max_lowres     = 3,
2609     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
2610 };
2611
2612 #if CONFIG_MPEG_XVMC_DECODER
2613 static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx)
2614 {
2615     if (avctx->active_thread_type & FF_THREAD_SLICE)
2616         return -1;
2617     if (!(avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
2618         return -1;
2619     if (!(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD)) {
2620         av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");
2621     }
2622     mpeg_decode_init(avctx);
2623
2624     avctx->pix_fmt           = PIX_FMT_XVMC_MPEG2_IDCT;
2625     avctx->xvmc_acceleration = 2; // 2 - the blocks are packed!
2626
2627     return 0;
2628 }
2629
2630 AVCodec ff_mpeg_xvmc_decoder = {
2631     .name           = "mpegvideo_xvmc",
2632     .type           = AVMEDIA_TYPE_VIDEO,
2633     .id             = CODEC_ID_MPEG2VIDEO_XVMC,
2634     .priv_data_size = sizeof(Mpeg1Context),
2635     .init           = mpeg_mc_decode_init,
2636     .close          = mpeg_decode_end,
2637     .decode         = mpeg_decode_frame,
2638     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
2639                       CODEC_CAP_TRUNCATED| CODEC_CAP_HWACCEL | CODEC_CAP_DELAY,
2640     .flush          = flush,
2641     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video XvMC (X-Video Motion Compensation)"),
2642 };
2643
2644 #endif
2645
2646 #if CONFIG_MPEG_VDPAU_DECODER
2647 AVCodec ff_mpeg_vdpau_decoder = {
2648     .name           = "mpegvideo_vdpau",
2649     .type           = AVMEDIA_TYPE_VIDEO,
2650     .id             = CODEC_ID_MPEG2VIDEO,
2651     .priv_data_size = sizeof(Mpeg1Context),
2652     .init           = mpeg_decode_init,
2653     .close          = mpeg_decode_end,
2654     .decode         = mpeg_decode_frame,
2655     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED |
2656                       CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2657     .flush          = flush,
2658     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1/2 video (VDPAU acceleration)"),
2659 };
2660 #endif
2661
2662 #if CONFIG_MPEG1_VDPAU_DECODER
2663 AVCodec ff_mpeg1_vdpau_decoder = {
2664     .name           = "mpeg1video_vdpau",
2665     .type           = AVMEDIA_TYPE_VIDEO,
2666     .id             = CODEC_ID_MPEG1VIDEO,
2667     .priv_data_size = sizeof(Mpeg1Context),
2668     .init           = mpeg_decode_init,
2669     .close          = mpeg_decode_end,
2670     .decode         = mpeg_decode_frame,
2671     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED |
2672                       CODEC_CAP_HWACCEL_VDPAU | CODEC_CAP_DELAY,
2673     .flush          = flush,
2674     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-1 video (VDPAU acceleration)"),
2675 };
2676 #endif