Merge remote-tracking branch 'qatar/master'
[ffmpeg.git] / libavcodec / mjpegdec.c
1 /*
2  * MJPEG decoder
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  * Copyright (c) 2003 Alex Beregszaszi
5  * Copyright (c) 2003-2004 Michael Niedermayer
6  *
7  * Support for external huffman table, various fixes (AVID workaround),
8  * aspecting, new decode_frame mechanism and apple mjpeg-b support
9  *                                  by Alex Beregszaszi
10  *
11  * This file is part of FFmpeg.
12  *
13  * FFmpeg is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * FFmpeg is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with FFmpeg; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26  */
27
28 /**
29  * @file
30  * MJPEG decoder.
31  */
32
33 //#define DEBUG
34 #include <assert.h>
35
36 #include "libavutil/imgutils.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/opt.h"
39 #include "avcodec.h"
40 #include "dsputil.h"
41 #include "mjpeg.h"
42 #include "mjpegdec.h"
43 #include "jpeglsdec.h"
44
45
46 static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,
47                       int nb_codes, int use_static, int is_ac)
48 {
49     uint8_t huff_size[256];
50     uint16_t huff_code[256];
51     uint16_t huff_sym[256];
52     int i;
53
54     assert(nb_codes <= 256);
55
56     memset(huff_size, 0, sizeof(huff_size));
57     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
58
59     for(i=0; i<256; i++)
60         huff_sym[i]= i + 16*is_ac;
61
62     if(is_ac) huff_sym[0]= 16*256;
63
64     return init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, huff_sym, 2, 2, use_static);
65 }
66
67 static void build_basic_mjpeg_vlc(MJpegDecodeContext * s) {
68     build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
69               ff_mjpeg_val_dc, 12, 0, 0);
70     build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
71               ff_mjpeg_val_dc, 12, 0, 0);
72     build_vlc(&s->vlcs[1][0], ff_mjpeg_bits_ac_luminance,
73               ff_mjpeg_val_ac_luminance, 251, 0, 1);
74     build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
75               ff_mjpeg_val_ac_chrominance, 251, 0, 1);
76     build_vlc(&s->vlcs[2][0], ff_mjpeg_bits_ac_luminance,
77               ff_mjpeg_val_ac_luminance, 251, 0, 0);
78     build_vlc(&s->vlcs[2][1], ff_mjpeg_bits_ac_chrominance,
79               ff_mjpeg_val_ac_chrominance, 251, 0, 0);
80 }
81
82 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
83 {
84     MJpegDecodeContext *s = avctx->priv_data;
85
86     if (!s->picture_ptr)
87         s->picture_ptr = &s->picture;
88     avcodec_get_frame_defaults(&s->picture);
89
90     s->avctx = avctx;
91     dsputil_init(&s->dsp, avctx);
92     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
93     s->buffer_size = 0;
94     s->buffer = NULL;
95     s->start_code = -1;
96     s->first_picture = 1;
97     s->org_height = avctx->coded_height;
98     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
99
100     build_basic_mjpeg_vlc(s);
101
102 #if FF_API_MJPEG_GLOBAL_OPTS
103     if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)
104         s->extern_huff = 1;
105 #endif
106     if (s->extern_huff)
107     {
108         av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
109         init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
110         if (ff_mjpeg_decode_dht(s)) {
111             av_log(avctx, AV_LOG_ERROR, "mjpeg: error using external huffman table, switching back to internal\n");
112             build_basic_mjpeg_vlc(s);
113         }
114     }
115     if (avctx->extradata_size > 9 &&
116         AV_RL32(avctx->extradata + 4) == MKTAG('f','i','e','l')) {
117         if (avctx->extradata[9] == 6) { /* quicktime icefloe 019 */
118             s->interlace_polarity = 1; /* bottom field first */
119             av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
120         }
121     }
122     if (avctx->codec->id == CODEC_ID_AMV)
123         s->flipped = 1;
124
125     return 0;
126 }
127
128
129 /* quantize tables */
130 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
131 {
132     int len, index, i, j;
133
134     len = get_bits(&s->gb, 16) - 2;
135
136     while (len >= 65) {
137         /* only 8 bit precision handled */
138         if (get_bits(&s->gb, 4) != 0)
139         {
140             av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
141             return -1;
142         }
143         index = get_bits(&s->gb, 4);
144         if (index >= 4)
145             return -1;
146         av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
147         /* read quant table */
148         for(i=0;i<64;i++) {
149             j = s->scantable.permutated[i];
150             s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
151         }
152
153         //XXX FIXME finetune, and perhaps add dc too
154         s->qscale[index]= FFMAX(
155             s->quant_matrixes[index][s->scantable.permutated[1]],
156             s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
157         av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n", index, s->qscale[index]);
158         len -= 65;
159     }
160
161     return 0;
162 }
163
164 /* decode huffman tables and build VLC decoders */
165 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
166 {
167     int len, index, i, class, n, v, code_max;
168     uint8_t bits_table[17];
169     uint8_t val_table[256];
170
171     len = get_bits(&s->gb, 16) - 2;
172
173     while (len > 0) {
174         if (len < 17)
175             return -1;
176         class = get_bits(&s->gb, 4);
177         if (class >= 2)
178             return -1;
179         index = get_bits(&s->gb, 4);
180         if (index >= 4)
181             return -1;
182         n = 0;
183         for(i=1;i<=16;i++) {
184             bits_table[i] = get_bits(&s->gb, 8);
185             n += bits_table[i];
186         }
187         len -= 17;
188         if (len < n || n > 256)
189             return -1;
190
191         code_max = 0;
192         for(i=0;i<n;i++) {
193             v = get_bits(&s->gb, 8);
194             if (v > code_max)
195                 code_max = v;
196             val_table[i] = v;
197         }
198         len -= n;
199
200         /* build VLC and flush previous vlc if present */
201         free_vlc(&s->vlcs[class][index]);
202         av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
203                class, index, code_max + 1);
204         if(build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1, 0, class > 0) < 0){
205             return -1;
206         }
207
208         if(class>0){
209             free_vlc(&s->vlcs[2][index]);
210             if(build_vlc(&s->vlcs[2][index], bits_table, val_table, code_max + 1, 0, 0) < 0){
211             return -1;
212             }
213         }
214     }
215     return 0;
216 }
217
218 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
219 {
220     int len, nb_components, i, width, height, pix_fmt_id;
221
222     s->cur_scan = 0;
223
224     /* XXX: verify len field validity */
225     len = get_bits(&s->gb, 16);
226     s->bits= get_bits(&s->gb, 8);
227
228     if(s->pegasus_rct) s->bits=9;
229     if(s->bits==9 && !s->pegasus_rct) s->rct=1;    //FIXME ugly
230
231     if (s->bits != 8 && !s->lossless){
232         av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
233         return -1;
234     }
235
236     height = get_bits(&s->gb, 16);
237     width = get_bits(&s->gb, 16);
238
239     //HACK for odd_height.mov
240     if(s->interlaced && s->width == width && s->height == height + 1)
241         height= s->height;
242
243     av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
244     if(av_image_check_size(width, height, 0, s->avctx))
245         return -1;
246
247     nb_components = get_bits(&s->gb, 8);
248     if (nb_components <= 0 ||
249         nb_components > MAX_COMPONENTS)
250         return -1;
251     if (s->ls && !(s->bits <= 8 || nb_components == 1)){
252         av_log(s->avctx, AV_LOG_ERROR, "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
253         return -1;
254     }
255     s->nb_components = nb_components;
256     s->h_max = 1;
257     s->v_max = 1;
258     for(i=0;i<nb_components;i++) {
259         /* component id */
260         s->component_id[i] = get_bits(&s->gb, 8) - 1;
261         s->h_count[i] = get_bits(&s->gb, 4);
262         s->v_count[i] = get_bits(&s->gb, 4);
263         /* compute hmax and vmax (only used in interleaved case) */
264         if (s->h_count[i] > s->h_max)
265             s->h_max = s->h_count[i];
266         if (s->v_count[i] > s->v_max)
267             s->v_max = s->v_count[i];
268         s->quant_index[i] = get_bits(&s->gb, 8);
269         if (s->quant_index[i] >= 4)
270             return -1;
271         av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n", i, s->h_count[i],
272                s->v_count[i], s->component_id[i], s->quant_index[i]);
273     }
274
275     if(s->ls && (s->h_max > 1 || s->v_max > 1)) {
276         av_log(s->avctx, AV_LOG_ERROR, "Subsampling in JPEG-LS is not supported.\n");
277         return -1;
278     }
279
280     if(s->v_max==1 && s->h_max==1 && s->lossless==1) s->rgb=1;
281
282     /* if different size, realloc/alloc picture */
283     /* XXX: also check h_count and v_count */
284     if (width != s->width || height != s->height) {
285         av_freep(&s->qscale_table);
286
287         s->width = width;
288         s->height = height;
289         s->interlaced = 0;
290
291         /* test interlaced mode */
292         if (s->first_picture &&
293             s->org_height != 0 &&
294             s->height < ((s->org_height * 3) / 4)) {
295             s->interlaced = 1;
296             s->bottom_field = s->interlace_polarity;
297             s->picture_ptr->interlaced_frame = 1;
298             s->picture_ptr->top_field_first = !s->interlace_polarity;
299             height *= 2;
300         }
301
302         avcodec_set_dimensions(s->avctx, width, height);
303
304         s->qscale_table= av_mallocz((s->width+15)/16);
305
306         s->first_picture = 0;
307     }
308
309     if(s->interlaced && (s->bottom_field == !s->interlace_polarity))
310         return 0;
311
312     /* XXX: not complete test ! */
313     pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
314                  (s->h_count[1] << 20) | (s->v_count[1] << 16) |
315                  (s->h_count[2] << 12) | (s->v_count[2] <<  8) |
316                  (s->h_count[3] <<  4) |  s->v_count[3];
317     av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
318     //NOTE we do not allocate pictures large enough for the possible padding of h/v_count being 4
319     if(!(pix_fmt_id & 0xD0D0D0D0))
320         pix_fmt_id-= (pix_fmt_id & 0xF0F0F0F0)>>1;
321     if(!(pix_fmt_id & 0x0D0D0D0D))
322         pix_fmt_id-= (pix_fmt_id & 0x0F0F0F0F)>>1;
323
324     switch(pix_fmt_id){
325     case 0x11111100:
326         if(s->rgb){
327             s->avctx->pix_fmt = PIX_FMT_BGRA;
328         }else{
329             s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
330             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
331         }
332         assert(s->nb_components==3);
333         break;
334     case 0x11000000:
335         s->avctx->pix_fmt = PIX_FMT_GRAY8;
336         break;
337     case 0x12111100:
338         s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV440P : PIX_FMT_YUVJ440P;
339         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
340         break;
341     case 0x21111100:
342         s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
343         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
344         break;
345     case 0x22111100:
346         s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
347         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
348         break;
349     default:
350         av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
351         return -1;
352     }
353     if(s->ls){
354         if(s->nb_components > 1)
355             s->avctx->pix_fmt = PIX_FMT_RGB24;
356         else if(s->bits <= 8)
357             s->avctx->pix_fmt = PIX_FMT_GRAY8;
358         else
359             s->avctx->pix_fmt = PIX_FMT_GRAY16;
360     }
361
362     if(s->picture_ptr->data[0])
363         s->avctx->release_buffer(s->avctx, s->picture_ptr);
364
365     if(s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0){
366         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
367         return -1;
368     }
369     s->picture_ptr->pict_type= AV_PICTURE_TYPE_I;
370     s->picture_ptr->key_frame= 1;
371     s->got_picture = 1;
372
373     for(i=0; i<3; i++){
374         s->linesize[i]= s->picture_ptr->linesize[i] << s->interlaced;
375     }
376
377 //    printf("%d %d %d %d %d %d\n", s->width, s->height, s->linesize[0], s->linesize[1], s->interlaced, s->avctx->height);
378
379     if (len != (8+(3*nb_components)))
380     {
381         av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
382     }
383
384     /* totally blank picture as progressive JPEG will only add details to it */
385     if(s->progressive){
386         int bw = (width  + s->h_max*8-1) / (s->h_max*8);
387         int bh = (height + s->v_max*8-1) / (s->v_max*8);
388         for(i=0; i<s->nb_components; i++) {
389             int size = bw * bh * s->h_count[i] * s->v_count[i];
390             av_freep(&s->blocks[i]);
391             av_freep(&s->last_nnz[i]);
392             s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
393             s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
394             s->block_stride[i] = bw * s->h_count[i];
395         }
396         memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
397     }
398     return 0;
399 }
400
401 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
402 {
403     int code;
404     code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
405     if (code < 0)
406     {
407         av_log(s->avctx, AV_LOG_WARNING, "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n", 0, dc_index,
408                &s->vlcs[0][dc_index]);
409         return 0xffff;
410     }
411
412     if(code)
413         return get_xbits(&s->gb, code);
414     else
415         return 0;
416 }
417
418 /* decode block and dequantize */
419 static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
420                         int component, int dc_index, int ac_index, int16_t *quant_matrix)
421 {
422     int code, i, j, level, val;
423
424     /* DC coef */
425     val = mjpeg_decode_dc(s, dc_index);
426     if (val == 0xffff) {
427         av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
428         return -1;
429     }
430     val = val * quant_matrix[0] + s->last_dc[component];
431     s->last_dc[component] = val;
432     block[0] = val;
433     /* AC coefs */
434     i = 0;
435     {OPEN_READER(re, &s->gb);
436     do {
437         UPDATE_CACHE(re, &s->gb);
438         GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
439
440         i += ((unsigned)code) >> 4;
441             code &= 0xf;
442         if(code){
443             if(code > MIN_CACHE_BITS - 16){
444                 UPDATE_CACHE(re, &s->gb);
445             }
446             {
447                 int cache=GET_CACHE(re,&s->gb);
448                 int sign=(~cache)>>31;
449                 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
450             }
451
452             LAST_SKIP_BITS(re, &s->gb, code);
453
454             if (i > 63) {
455                 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
456                 return -1;
457             }
458             j = s->scantable.permutated[i];
459             block[j] = level * quant_matrix[j];
460         }
461     }while(i<63);
462     CLOSE_READER(re, &s->gb);}
463
464     return 0;
465 }
466
467 static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block, int component,
468                                  int dc_index, int16_t *quant_matrix, int Al)
469 {
470     int val;
471     s->dsp.clear_block(block);
472     val = mjpeg_decode_dc(s, dc_index);
473     if (val == 0xffff) {
474         av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
475         return -1;
476     }
477     val = (val * quant_matrix[0] << Al) + s->last_dc[component];
478     s->last_dc[component] = val;
479     block[0] = val;
480     return 0;
481 }
482
483 /* decode block and dequantize - progressive JPEG version */
484 static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
485                                     int ac_index, int16_t *quant_matrix,
486                                     int ss, int se, int Al, int *EOBRUN)
487 {
488     int code, i, j, level, val, run;
489
490     if(*EOBRUN){
491         (*EOBRUN)--;
492         return 0;
493     }
494     {OPEN_READER(re, &s->gb);
495     for(i=ss;;i++) {
496         UPDATE_CACHE(re, &s->gb);
497         GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
498
499         run = ((unsigned) code) >> 4;
500         code &= 0xF;
501         if(code) {
502             i += run;
503             if(code > MIN_CACHE_BITS - 16){
504                 UPDATE_CACHE(re, &s->gb);
505             }
506             {
507                 int cache=GET_CACHE(re,&s->gb);
508                 int sign=(~cache)>>31;
509                 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
510             }
511
512             LAST_SKIP_BITS(re, &s->gb, code);
513
514             if (i >= se) {
515                 if(i == se){
516                     j = s->scantable.permutated[se];
517                     block[j] = level * quant_matrix[j] << Al;
518                     break;
519                 }
520                 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
521                 return -1;
522             }
523             j = s->scantable.permutated[i];
524             block[j] = level * quant_matrix[j] << Al;
525         }else{
526             if(run == 0xF){// ZRL - skip 15 coefficients
527                 i += 15;
528                 if (i >= se) {
529                     av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
530                     return -1;
531                 }
532             }else{
533                 val = (1 << run);
534                 if(run){
535                     UPDATE_CACHE(re, &s->gb);
536                     val += NEG_USR32(GET_CACHE(re, &s->gb), run);
537                     LAST_SKIP_BITS(re, &s->gb, run);
538                 }
539                 *EOBRUN = val - 1;
540                 break;
541             }
542         }
543     }
544     CLOSE_READER(re, &s->gb);}
545     if(i > *last_nnz)
546         *last_nnz = i;
547     return 0;
548 }
549
550 #define REFINE_BIT(j) {\
551     UPDATE_CACHE(re, &s->gb);\
552     sign = block[j]>>15;\
553     block[j] += SHOW_UBITS(re, &s->gb, 1) * ((quant_matrix[j]^sign)-sign) << Al;\
554     LAST_SKIP_BITS(re, &s->gb, 1);\
555 }
556
557 #define ZERO_RUN \
558 for(;;i++) {\
559     if(i > last) {\
560         i += run;\
561         if(i > se) {\
562             av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);\
563             return -1;\
564         }\
565         break;\
566     }\
567     j = s->scantable.permutated[i];\
568     if(block[j])\
569         REFINE_BIT(j)\
570     else if(run-- == 0)\
571         break;\
572 }
573
574 /* decode block and dequantize - progressive JPEG refinement pass */
575 static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
576                         int ac_index, int16_t *quant_matrix,
577                         int ss, int se, int Al, int *EOBRUN)
578 {
579     int code, i=ss, j, sign, val, run;
580     int last = FFMIN(se, *last_nnz);
581
582     OPEN_READER(re, &s->gb);
583     if(*EOBRUN)
584         (*EOBRUN)--;
585     else {
586         for(;;i++) {
587             UPDATE_CACHE(re, &s->gb);
588             GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
589
590             if(code & 0xF) {
591                 run = ((unsigned) code) >> 4;
592                 UPDATE_CACHE(re, &s->gb);
593                 val = SHOW_UBITS(re, &s->gb, 1);
594                 LAST_SKIP_BITS(re, &s->gb, 1);
595                 ZERO_RUN;
596                 j = s->scantable.permutated[i];
597                 val--;
598                 block[j] = ((quant_matrix[j]^val)-val) << Al;
599                 if(i == se) {
600                     if(i > *last_nnz)
601                         *last_nnz = i;
602                     CLOSE_READER(re, &s->gb);
603                     return 0;
604                 }
605             }else{
606                 run = ((unsigned) code) >> 4;
607                 if(run == 0xF){
608                     ZERO_RUN;
609                 }else{
610                     val = run;
611                     run = (1 << run);
612                     if(val) {
613                         UPDATE_CACHE(re, &s->gb);
614                         run += SHOW_UBITS(re, &s->gb, val);
615                         LAST_SKIP_BITS(re, &s->gb, val);
616                     }
617                     *EOBRUN = run - 1;
618                     break;
619                 }
620             }
621         }
622
623         if(i > *last_nnz)
624             *last_nnz = i;
625     }
626
627     for(;i<=last;i++) {
628         j = s->scantable.permutated[i];
629         if(block[j])
630             REFINE_BIT(j)
631     }
632     CLOSE_READER(re, &s->gb);
633
634     return 0;
635 }
636 #undef REFINE_BIT
637 #undef ZERO_RUN
638
639 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point_transform){
640     int i, mb_x, mb_y;
641     uint16_t (*buffer)[4];
642     int left[3], top[3], topleft[3];
643     const int linesize= s->linesize[0];
644     const int mask= (1<<s->bits)-1;
645
646     av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size, (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
647     buffer= s->ljpeg_buffer;
648
649     for(i=0; i<3; i++){
650         buffer[0][i]= 1 << (s->bits + point_transform - 1);
651     }
652     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
653         const int modified_predictor= mb_y ? predictor : 1;
654         uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
655
656         if (s->interlaced && s->bottom_field)
657             ptr += linesize >> 1;
658
659         for(i=0; i<3; i++){
660             top[i]= left[i]= topleft[i]= buffer[0][i];
661         }
662         for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
663             if (s->restart_interval && !s->restart_count)
664                 s->restart_count = s->restart_interval;
665
666             for(i=0;i<3;i++) {
667                 int pred;
668
669                 topleft[i]= top[i];
670                 top[i]= buffer[mb_x][i];
671
672                 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
673
674                 left[i]=
675                 buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
676             }
677
678             if (s->restart_interval && !--s->restart_count) {
679                 align_get_bits(&s->gb);
680                 skip_bits(&s->gb, 16); /* skip RSTn */
681             }
682         }
683
684         if(s->rct){
685             for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
686                 ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);
687                 ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
688                 ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
689             }
690         }else if(s->pegasus_rct){
691             for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
692                 ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);
693                 ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
694                 ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
695             }
696         }else{
697             for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
698                 ptr[4*mb_x+0] = buffer[mb_x][2];
699                 ptr[4*mb_x+1] = buffer[mb_x][1];
700                 ptr[4*mb_x+2] = buffer[mb_x][0];
701             }
702         }
703     }
704     return 0;
705 }
706
707 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
708     int i, mb_x, mb_y;
709     const int nb_components=3;
710
711     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
712         for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
713             if (s->restart_interval && !s->restart_count)
714                 s->restart_count = s->restart_interval;
715
716             if(mb_x==0 || mb_y==0 || s->interlaced){
717                 for(i=0;i<nb_components;i++) {
718                     uint8_t *ptr;
719                     int n, h, v, x, y, c, j, linesize;
720                     n = s->nb_blocks[i];
721                     c = s->comp_index[i];
722                     h = s->h_scount[i];
723                     v = s->v_scount[i];
724                     x = 0;
725                     y = 0;
726                     linesize= s->linesize[c];
727
728                     for(j=0; j<n; j++) {
729                         int pred;
730
731                         ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
732                         if(y==0 && mb_y==0){
733                             if(x==0 && mb_x==0){
734                                 pred= 128 << point_transform;
735                             }else{
736                                 pred= ptr[-1];
737                             }
738                         }else{
739                             if(x==0 && mb_x==0){
740                                 pred= ptr[-linesize];
741                             }else{
742                                 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
743                             }
744                         }
745
746                         if (s->interlaced && s->bottom_field)
747                             ptr += linesize >> 1;
748                         *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
749
750                         if (++x == h) {
751                             x = 0;
752                             y++;
753                         }
754                     }
755                 }
756             }else{
757                 for(i=0;i<nb_components;i++) {
758                     uint8_t *ptr;
759                     int n, h, v, x, y, c, j, linesize;
760                     n = s->nb_blocks[i];
761                     c = s->comp_index[i];
762                     h = s->h_scount[i];
763                     v = s->v_scount[i];
764                     x = 0;
765                     y = 0;
766                     linesize= s->linesize[c];
767
768                     for(j=0; j<n; j++) {
769                         int pred;
770
771                         ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
772                         PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
773                         *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
774                         if (++x == h) {
775                             x = 0;
776                             y++;
777                         }
778                     }
779                 }
780             }
781             if (s->restart_interval && !--s->restart_count) {
782                 align_get_bits(&s->gb);
783                 skip_bits(&s->gb, 16); /* skip RSTn */
784             }
785         }
786     }
787     return 0;
788 }
789
790 static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
791                                               int linesize, int lowres)
792 {
793     switch (lowres) {
794     case 0: copy_block8(dst, src, linesize, linesize, 8);
795         break;
796     case 1: copy_block4(dst, src, linesize, linesize, 4);
797         break;
798     case 2: copy_block2(dst, src, linesize, linesize, 2);
799         break;
800     case 3: *dst = *src;
801         break;
802     }
803 }
804
805 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,
806                              const uint8_t *mb_bitmask, const AVFrame *reference){
807     int i, mb_x, mb_y;
808     uint8_t* data[MAX_COMPONENTS];
809     const uint8_t *reference_data[MAX_COMPONENTS];
810     int linesize[MAX_COMPONENTS];
811     GetBitContext mb_bitmask_gb;
812
813     if (mb_bitmask) {
814         init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
815     }
816
817     if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
818         av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
819         s->flipped = 0;
820     }
821     for(i=0; i < nb_components; i++) {
822         int c = s->comp_index[i];
823         data[c] = s->picture_ptr->data[c];
824         reference_data[c] = reference ? reference->data[c] : NULL;
825         linesize[c]=s->linesize[c];
826         s->coefs_finished[c] |= 1;
827         if(s->flipped) {
828             //picture should be flipped upside-down for this codec
829             int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
830             data[c] += offset;
831             reference_data[c] += offset;
832             linesize[c] *= -1;
833         }
834     }
835
836     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
837         for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
838             const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
839
840             if (s->restart_interval && !s->restart_count)
841                 s->restart_count = s->restart_interval;
842
843             if(get_bits_count(&s->gb)>s->gb.size_in_bits){
844                 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n", get_bits_count(&s->gb) - s->gb.size_in_bits);
845                 return -1;
846             }
847             for(i=0;i<nb_components;i++) {
848                 uint8_t *ptr;
849                 int n, h, v, x, y, c, j;
850                 int block_offset;
851                 n = s->nb_blocks[i];
852                 c = s->comp_index[i];
853                 h = s->h_scount[i];
854                 v = s->v_scount[i];
855                 x = 0;
856                 y = 0;
857                 for(j=0;j<n;j++) {
858                     block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
859                                      (h * mb_x + x) * 8) >> s->avctx->lowres);
860
861                     if(s->interlaced && s->bottom_field)
862                         block_offset += linesize[c] >> 1;
863                     ptr = data[c] + block_offset;
864                     if(!s->progressive) {
865                         if (copy_mb) {
866                             mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);
867                         } else {
868                         s->dsp.clear_block(s->block);
869                         if(decode_block(s, s->block, i,
870                                      s->dc_index[i], s->ac_index[i],
871                                      s->quant_matrixes[ s->quant_index[c] ]) < 0) {
872                             av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
873                             return -1;
874                         }
875                         s->dsp.idct_put(ptr, linesize[c], s->block);
876                         }
877                     } else {
878                         int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
879                         DCTELEM *block = s->blocks[c][block_idx];
880                         if(Ah)
881                             block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;
882                         else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {
883                             av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
884                             return -1;
885                         }
886                     }
887 //                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
888 //av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);
889                     if (++x == h) {
890                         x = 0;
891                         y++;
892                     }
893                 }
894             }
895
896             if (s->restart_interval) --s->restart_count;
897             i= 8+((-get_bits_count(&s->gb))&7);
898             if (s->restart_interval && show_bits(&s->gb, i)  == (1<<i)-1){ /* skip RSTn */
899                 int pos= get_bits_count(&s->gb);
900                 align_get_bits(&s->gb);
901                 while(get_bits_count(&s->gb) < s->gb.size_in_bits && show_bits(&s->gb, 8) == 0xFF)
902                     skip_bits(&s->gb, 8);
903                 if(get_bits_count(&s->gb) < s->gb.size_in_bits && (get_bits(&s->gb, 8)&0xF8) == 0xD0){
904                     for (i=0; i<nb_components; i++) /* reset dc */
905                         s->last_dc[i] = 1024;
906                 }else{
907                     skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
908                 }
909             }
910         }
911     }
912     return 0;
913 }
914
915 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
916     int mb_x, mb_y;
917     int EOBRUN = 0;
918     int c = s->comp_index[0];
919     uint8_t* data = s->picture.data[c];
920     int linesize = s->linesize[c];
921     int last_scan = 0;
922     int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
923
924     if(!Al) {
925         s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
926         last_scan = !~s->coefs_finished[c];
927     }
928
929     if(s->interlaced && s->bottom_field)
930         data += linesize >> 1;
931
932     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
933         uint8_t *ptr = data + (mb_y*linesize*8 >> s->avctx->lowres);
934         int block_idx = mb_y * s->block_stride[c];
935         DCTELEM (*block)[64] = &s->blocks[c][block_idx];
936         uint8_t *last_nnz = &s->last_nnz[c][block_idx];
937         for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
938             int ret;
939             if(Ah)
940                 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
941                                               quant_matrix, ss, se, Al, &EOBRUN);
942             else
943                 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
944                                                quant_matrix, ss, se, Al, &EOBRUN);
945             if(ret < 0) {
946                 av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
947                 return -1;
948             }
949             if(last_scan) {
950                 s->dsp.idct_put(ptr, linesize, *block);
951                 ptr += 8 >> s->avctx->lowres;
952             }
953         }
954     }
955     return 0;
956 }
957
958 int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
959                         const uint8_t *mb_bitmask, const AVFrame *reference)
960 {
961     int len, nb_components, i, h, v, predictor, point_transform;
962     int index, id;
963     const int block_size= s->lossless ? 1 : 8;
964     int ilv, prev_shift;
965
966     /* XXX: verify len field validity */
967     len = get_bits(&s->gb, 16);
968     nb_components = get_bits(&s->gb, 8);
969     if (nb_components == 0 || nb_components > MAX_COMPONENTS){
970         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: nb_components (%d) unsupported\n", nb_components);
971         return -1;
972     }
973     if (len != 6+2*nb_components)
974     {
975         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
976         return -1;
977     }
978     for(i=0;i<nb_components;i++) {
979         id = get_bits(&s->gb, 8) - 1;
980         av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
981         /* find component index */
982         for(index=0;index<s->nb_components;index++)
983             if (id == s->component_id[index])
984                 break;
985         if (index == s->nb_components)
986         {
987             av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
988             return -1;
989         }
990         /* Metasoft MJPEG codec has Cb and Cr swapped */
991         if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
992             && nb_components == 3 && s->nb_components == 3 && i)
993             index = 3 - i;
994
995         s->comp_index[i] = index;
996
997         s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
998         s->h_scount[i] = s->h_count[index];
999         s->v_scount[i] = s->v_count[index];
1000
1001         s->dc_index[i] = get_bits(&s->gb, 4);
1002         s->ac_index[i] = get_bits(&s->gb, 4);
1003
1004         if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
1005             s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1006             goto out_of_range;
1007         if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
1008             goto out_of_range;
1009     }
1010
1011     predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1012     ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
1013     if(s->avctx->codec_tag != AV_RL32("CJPG")){
1014         prev_shift = get_bits(&s->gb, 4); /* Ah */
1015         point_transform= get_bits(&s->gb, 4); /* Al */
1016     }else
1017         prev_shift= point_transform= 0;
1018
1019     for(i=0;i<nb_components;i++)
1020         s->last_dc[i] = 1024;
1021
1022     if (nb_components > 1) {
1023         /* interleaved stream */
1024         s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
1025         s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1026     } else if(!s->ls) { /* skip this for JPEG-LS */
1027         h = s->h_max / s->h_scount[0];
1028         v = s->v_max / s->v_scount[0];
1029         s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
1030         s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1031         s->nb_blocks[0] = 1;
1032         s->h_scount[0] = 1;
1033         s->v_scount[0] = 1;
1034     }
1035
1036     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1037         av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n", s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1038                predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1039                s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1040
1041
1042     /* mjpeg-b can have padding bytes between sos and image data, skip them */
1043     for (i = s->mjpb_skiptosod; i > 0; i--)
1044         skip_bits(&s->gb, 8);
1045
1046     if(s->lossless){
1047         av_assert0(s->picture_ptr == &s->picture);
1048         if(CONFIG_JPEGLS_DECODER && s->ls){
1049 //            for(){
1050 //            reset_ls_coding_parameters(s, 0);
1051
1052             if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
1053                 return -1;
1054         }else{
1055             if(s->rgb){
1056                 if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
1057                     return -1;
1058             }else{
1059                 if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
1060                     return -1;
1061             }
1062         }
1063     }else{
1064         if(s->progressive && predictor) {
1065             av_assert0(s->picture_ptr == &s->picture);
1066             if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform) < 0)
1067                 return -1;
1068         } else {
1069             if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
1070                                  mb_bitmask, reference) < 0)
1071                 return -1;
1072         }
1073     }
1074     emms_c();
1075     return 0;
1076  out_of_range:
1077     av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1078     return -1;
1079 }
1080
1081 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1082 {
1083     if (get_bits(&s->gb, 16) != 4)
1084         return -1;
1085     s->restart_interval = get_bits(&s->gb, 16);
1086     s->restart_count = 0;
1087     av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1088
1089     return 0;
1090 }
1091
1092 static int mjpeg_decode_app(MJpegDecodeContext *s)
1093 {
1094     int len, id, i;
1095
1096     len = get_bits(&s->gb, 16);
1097     if (len < 5)
1098         return -1;
1099     if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1100         return -1;
1101
1102     id = get_bits_long(&s->gb, 32);
1103     id = av_be2ne32(id);
1104     len -= 6;
1105
1106     if(s->avctx->debug & FF_DEBUG_STARTCODE){
1107         av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1108     }
1109
1110     /* buggy AVID, it puts EOI only at every 10th frame */
1111     /* also this fourcc is used by non-avid files too, it holds some
1112        informations, but it's always present in AVID creates files */
1113     if (id == AV_RL32("AVI1"))
1114     {
1115         /* structure:
1116             4bytes      AVI1
1117             1bytes      polarity
1118             1bytes      always zero
1119             4bytes      field_size
1120             4bytes      field_size_less_padding
1121         */
1122             s->buggy_avid = 1;
1123 //        if (s->first_picture)
1124 //            printf("mjpeg: workarounding buggy AVID\n");
1125         i = get_bits(&s->gb, 8); len--;
1126         av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1127 #if 0
1128         skip_bits(&s->gb, 8);
1129         skip_bits(&s->gb, 32);
1130         skip_bits(&s->gb, 32);
1131         len -= 10;
1132 #endif
1133 //        if (s->interlace_polarity)
1134 //            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1135         goto out;
1136     }
1137
1138 //    len -= 2;
1139
1140     if (id == AV_RL32("JFIF"))
1141     {
1142         int t_w, t_h, v1, v2;
1143         skip_bits(&s->gb, 8); /* the trailing zero-byte */
1144         v1= get_bits(&s->gb, 8);
1145         v2= get_bits(&s->gb, 8);
1146         skip_bits(&s->gb, 8);
1147
1148         s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1149         s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1150
1151         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1152             av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1153                 v1, v2,
1154                 s->avctx->sample_aspect_ratio.num,
1155                 s->avctx->sample_aspect_ratio.den
1156             );
1157
1158         t_w = get_bits(&s->gb, 8);
1159         t_h = get_bits(&s->gb, 8);
1160         if (t_w && t_h)
1161         {
1162             /* skip thumbnail */
1163             if (len-10-(t_w*t_h*3) > 0)
1164                 len -= t_w*t_h*3;
1165         }
1166         len -= 10;
1167         goto out;
1168     }
1169
1170     if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
1171     {
1172         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1173             av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1174         skip_bits(&s->gb, 16); /* version */
1175         skip_bits(&s->gb, 16); /* flags0 */
1176         skip_bits(&s->gb, 16); /* flags1 */
1177         skip_bits(&s->gb, 8);  /* transform */
1178         len -= 7;
1179         goto out;
1180     }
1181
1182     if (id == AV_RL32("LJIF")){
1183         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1184             av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
1185         skip_bits(&s->gb, 16); /* version ? */
1186         skip_bits(&s->gb, 16); /* unknwon always 0? */
1187         skip_bits(&s->gb, 16); /* unknwon always 0? */
1188         skip_bits(&s->gb, 16); /* unknwon always 0? */
1189         switch( get_bits(&s->gb, 8)){
1190         case 1:
1191             s->rgb= 1;
1192             s->pegasus_rct=0;
1193             break;
1194         case 2:
1195             s->rgb= 1;
1196             s->pegasus_rct=1;
1197             break;
1198         default:
1199             av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1200         }
1201         len -= 9;
1202         goto out;
1203     }
1204
1205     /* Apple MJPEG-A */
1206     if ((s->start_code == APP1) && (len > (0x28 - 8)))
1207     {
1208         id = get_bits_long(&s->gb, 32);
1209         id = av_be2ne32(id);
1210         len -= 4;
1211         if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
1212         {
1213 #if 0
1214             skip_bits(&s->gb, 32); /* field size */
1215             skip_bits(&s->gb, 32); /* pad field size */
1216             skip_bits(&s->gb, 32); /* next off */
1217             skip_bits(&s->gb, 32); /* quant off */
1218             skip_bits(&s->gb, 32); /* huff off */
1219             skip_bits(&s->gb, 32); /* image off */
1220             skip_bits(&s->gb, 32); /* scan off */
1221             skip_bits(&s->gb, 32); /* data off */
1222 #endif
1223             if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1224                 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1225         }
1226     }
1227
1228 out:
1229     /* slow but needed for extreme adobe jpegs */
1230     if (len < 0)
1231         av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1232     while(--len > 0)
1233         skip_bits(&s->gb, 8);
1234
1235     return 0;
1236 }
1237
1238 static int mjpeg_decode_com(MJpegDecodeContext *s)
1239 {
1240     int len = get_bits(&s->gb, 16);
1241     if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
1242         char *cbuf = av_malloc(len - 1);
1243         if (cbuf) {
1244             int i;
1245             for (i = 0; i < len - 2; i++)
1246                 cbuf[i] = get_bits(&s->gb, 8);
1247             if (i > 0 && cbuf[i-1] == '\n')
1248                 cbuf[i-1] = 0;
1249             else
1250                 cbuf[i] = 0;
1251
1252             if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1253                 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1254
1255             /* buggy avid, it puts EOI only at every 10th frame */
1256             if (!strcmp(cbuf, "AVID"))
1257             {
1258                 s->buggy_avid = 1;
1259                 //        if (s->first_picture)
1260                 //            printf("mjpeg: workarounding buggy AVID\n");
1261             }
1262             else if(!strcmp(cbuf, "CS=ITU601")){
1263                 s->cs_itu601= 1;
1264             }
1265             else if((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1266                     (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20))){
1267                 s->flipped = 1;
1268             }
1269
1270             av_free(cbuf);
1271         }
1272     }
1273
1274     return 0;
1275 }
1276
1277 /* return the 8 bit start code value and update the search
1278    state. Return -1 if no start code found */
1279 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1280 {
1281     const uint8_t *buf_ptr;
1282     unsigned int v, v2;
1283     int val;
1284     int skipped=0;
1285
1286     buf_ptr = *pbuf_ptr;
1287     while (buf_ptr < buf_end) {
1288         v = *buf_ptr++;
1289         v2 = *buf_ptr;
1290         if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1291             val = *buf_ptr++;
1292             goto found;
1293         }
1294         skipped++;
1295     }
1296     val = -1;
1297 found:
1298     av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1299     *pbuf_ptr = buf_ptr;
1300     return val;
1301 }
1302
1303 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1304                          const uint8_t **buf_ptr, const uint8_t *buf_end,
1305                          const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
1306 {
1307     int start_code;
1308     start_code = find_marker(buf_ptr, buf_end);
1309
1310                 if ((buf_end - *buf_ptr) > s->buffer_size)
1311                 {
1312                     av_free(s->buffer);
1313                     s->buffer_size = buf_end - *buf_ptr;
1314                     s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1315                     av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1316                         s->buffer_size);
1317                 }
1318
1319                 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1320                 if (start_code == SOS && !s->ls)
1321                 {
1322                     const uint8_t *src = *buf_ptr;
1323                     uint8_t *dst = s->buffer;
1324
1325                     while (src<buf_end)
1326                     {
1327                         uint8_t x = *(src++);
1328
1329                         *(dst++) = x;
1330                         if (s->avctx->codec_id != CODEC_ID_THP)
1331                         {
1332                             if (x == 0xff) {
1333                                 while (src < buf_end && x == 0xff)
1334                                     x = *(src++);
1335
1336                                 if (x >= 0xd0 && x <= 0xd7)
1337                                     *(dst++) = x;
1338                                 else if (x)
1339                                     break;
1340                             }
1341                         }
1342                     }
1343                     *unescaped_buf_ptr  = s->buffer;
1344                     *unescaped_buf_size = dst - s->buffer;
1345
1346                     av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1347                            (buf_end - *buf_ptr) - (dst - s->buffer));
1348                 }
1349                 else if(start_code == SOS && s->ls){
1350                     const uint8_t *src = *buf_ptr;
1351                     uint8_t *dst = s->buffer;
1352                     int bit_count = 0;
1353                     int t = 0, b = 0;
1354                     PutBitContext pb;
1355
1356                     s->cur_scan++;
1357
1358                     /* find marker */
1359                     while (src + t < buf_end){
1360                         uint8_t x = src[t++];
1361                         if (x == 0xff){
1362                             while((src + t < buf_end) && x == 0xff)
1363                                 x = src[t++];
1364                             if (x & 0x80) {
1365                                 t -= 2;
1366                                 break;
1367                             }
1368                         }
1369                     }
1370                     bit_count = t * 8;
1371
1372                     init_put_bits(&pb, dst, t);
1373
1374                     /* unescape bitstream */
1375                     while(b < t){
1376                         uint8_t x = src[b++];
1377                         put_bits(&pb, 8, x);
1378                         if(x == 0xFF){
1379                             x = src[b++];
1380                             put_bits(&pb, 7, x);
1381                             bit_count--;
1382                         }
1383                     }
1384                     flush_put_bits(&pb);
1385
1386                     *unescaped_buf_ptr  = dst;
1387                     *unescaped_buf_size = (bit_count + 7) >> 3;
1388                 }
1389                 else
1390                 {
1391                     *unescaped_buf_ptr  = *buf_ptr;
1392                     *unescaped_buf_size = buf_end - *buf_ptr;
1393                 }
1394
1395     return start_code;
1396 }
1397
1398 int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1399                               void *data, int *data_size,
1400                               AVPacket *avpkt)
1401 {
1402     const uint8_t *buf = avpkt->data;
1403     int buf_size = avpkt->size;
1404     MJpegDecodeContext *s = avctx->priv_data;
1405     const uint8_t *buf_end, *buf_ptr;
1406     const uint8_t *unescaped_buf_ptr;
1407     int unescaped_buf_size;
1408     int start_code;
1409     AVFrame *picture = data;
1410
1411     s->got_picture = 0; // picture from previous image can not be reused
1412     buf_ptr = buf;
1413     buf_end = buf + buf_size;
1414     while (buf_ptr < buf_end) {
1415         /* find start next marker */
1416         start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1417                                           &unescaped_buf_ptr, &unescaped_buf_size);
1418         {
1419             /* EOF */
1420             if (start_code < 0) {
1421                 goto the_end;
1422             } else {
1423                 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
1424
1425                 init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1426
1427                 s->start_code = start_code;
1428                 if(s->avctx->debug & FF_DEBUG_STARTCODE){
1429                     av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1430                 }
1431
1432                 /* process markers */
1433                 if (start_code >= 0xd0 && start_code <= 0xd7) {
1434                     av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1435                     /* APP fields */
1436                 } else if (start_code >= APP0 && start_code <= APP15) {
1437                     mjpeg_decode_app(s);
1438                     /* Comment */
1439                 } else if (start_code == COM){
1440                     mjpeg_decode_com(s);
1441                 }
1442
1443                 switch(start_code) {
1444                 case SOI:
1445                     s->restart_interval = 0;
1446
1447                     s->restart_count = 0;
1448                     /* nothing to do on SOI */
1449                     break;
1450                 case DQT:
1451                     ff_mjpeg_decode_dqt(s);
1452                     break;
1453                 case DHT:
1454                     if(ff_mjpeg_decode_dht(s) < 0){
1455                         av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1456                         return -1;
1457                     }
1458                     break;
1459                 case SOF0:
1460                 case SOF1:
1461                     s->lossless=0;
1462                     s->ls=0;
1463                     s->progressive=0;
1464                     if (ff_mjpeg_decode_sof(s) < 0)
1465                         return -1;
1466                     break;
1467                 case SOF2:
1468                     s->lossless=0;
1469                     s->ls=0;
1470                     s->progressive=1;
1471                     if (ff_mjpeg_decode_sof(s) < 0)
1472                         return -1;
1473                     break;
1474                 case SOF3:
1475                     s->lossless=1;
1476                     s->ls=0;
1477                     s->progressive=0;
1478                     if (ff_mjpeg_decode_sof(s) < 0)
1479                         return -1;
1480                     break;
1481                 case SOF48:
1482                     s->lossless=1;
1483                     s->ls=1;
1484                     s->progressive=0;
1485                     if (ff_mjpeg_decode_sof(s) < 0)
1486                         return -1;
1487                     break;
1488                 case LSE:
1489                     if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1490                         return -1;
1491                     break;
1492                 case EOI:
1493 eoi_parser:
1494                     s->cur_scan = 0;
1495                     if (!s->got_picture) {
1496                         av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
1497                         break;
1498                     }
1499                     if (s->interlaced) {
1500                         s->bottom_field ^= 1;
1501                         /* if not bottom field, do not output image yet */
1502                         if (s->bottom_field == !s->interlace_polarity)
1503                             break;
1504                     }
1505                     *picture = *s->picture_ptr;
1506                     *data_size = sizeof(AVFrame);
1507
1508                     if(!s->lossless){
1509                         picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
1510                         picture->qstride= 0;
1511                         picture->qscale_table= s->qscale_table;
1512                         memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1513                         if(avctx->debug & FF_DEBUG_QP)
1514                             av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1515                         picture->quality*= FF_QP2LAMBDA;
1516                     }
1517
1518                     goto the_end;
1519                 case SOS:
1520                     if (!s->got_picture) {
1521                         av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
1522                         break;
1523                     }
1524                     if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&
1525                         (avctx->err_recognition & AV_EF_EXPLODE))
1526                       return AVERROR_INVALIDDATA;
1527                     break;
1528                 case DRI:
1529                     mjpeg_decode_dri(s);
1530                     break;
1531                 case SOF5:
1532                 case SOF6:
1533                 case SOF7:
1534                 case SOF9:
1535                 case SOF10:
1536                 case SOF11:
1537                 case SOF13:
1538                 case SOF14:
1539                 case SOF15:
1540                 case JPG:
1541                     av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1542                     break;
1543 //                default:
1544 //                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1545 //                    break;
1546                 }
1547
1548                 /* eof process start code */
1549                 buf_ptr += (get_bits_count(&s->gb)+7)/8;
1550                 av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1551                        (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1552             }
1553         }
1554     }
1555     if (s->got_picture) {
1556         av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1557         goto eoi_parser;
1558     }
1559     av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1560     return -1;
1561 the_end:
1562     av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
1563 //    return buf_end - buf_ptr;
1564     return buf_ptr - buf;
1565 }
1566
1567 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1568 {
1569     MJpegDecodeContext *s = avctx->priv_data;
1570     int i, j;
1571
1572     if (s->picture_ptr && s->picture_ptr->data[0])
1573         avctx->release_buffer(avctx, s->picture_ptr);
1574
1575     av_free(s->buffer);
1576     av_free(s->qscale_table);
1577     av_freep(&s->ljpeg_buffer);
1578     s->ljpeg_buffer_size=0;
1579
1580     for(i=0;i<3;i++) {
1581         for(j=0;j<4;j++)
1582             free_vlc(&s->vlcs[i][j]);
1583     }
1584     for(i=0; i<MAX_COMPONENTS; i++) {
1585         av_freep(&s->blocks[i]);
1586         av_freep(&s->last_nnz[i]);
1587     }
1588     return 0;
1589 }
1590
1591 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1592 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1593 static const AVOption options[] = {
1594     { "extern_huff",        "Use external huffman table.",  OFFSET(extern_huff), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD },
1595     { NULL },
1596 };
1597
1598 static const AVClass mjpegdec_class = {
1599     .class_name = "MJPEG decoder",
1600     .item_name  = av_default_item_name,
1601     .option     = options,
1602     .version    = LIBAVUTIL_VERSION_INT,
1603 };
1604
1605 AVCodec ff_mjpeg_decoder = {
1606     .name           = "mjpeg",
1607     .type           = AVMEDIA_TYPE_VIDEO,
1608     .id             = CODEC_ID_MJPEG,
1609     .priv_data_size = sizeof(MJpegDecodeContext),
1610     .init           = ff_mjpeg_decode_init,
1611     .close          = ff_mjpeg_decode_end,
1612     .decode         = ff_mjpeg_decode_frame,
1613     .capabilities   = CODEC_CAP_DR1,
1614     .max_lowres = 3,
1615     .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1616     .priv_class     = &mjpegdec_class,
1617 };
1618
1619 AVCodec ff_thp_decoder = {
1620     .name           = "thp",
1621     .type           = AVMEDIA_TYPE_VIDEO,
1622     .id             = CODEC_ID_THP,
1623     .priv_data_size = sizeof(MJpegDecodeContext),
1624     .init           = ff_mjpeg_decode_init,
1625     .close          = ff_mjpeg_decode_end,
1626     .decode         = ff_mjpeg_decode_frame,
1627     .capabilities   = CODEC_CAP_DR1,
1628     .max_lowres = 3,
1629     .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1630 };