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