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