babf3016dfefbb7ae785ceb082c1ec3dd250411a
[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;
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                 left[i]=
684                 buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
685             }
686
687             if (s->restart_interval && !--s->restart_count) {
688                 align_get_bits(&s->gb);
689                 skip_bits(&s->gb, 16); /* skip RSTn */
690             }
691         }
692
693         if(s->rct){
694             for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
695                 ptr[3*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);
696                 ptr[3*mb_x+0] = buffer[mb_x][1] + ptr[3*mb_x+1];
697                 ptr[3*mb_x+2] = buffer[mb_x][2] + ptr[3*mb_x+1];
698             }
699         }else if(s->pegasus_rct){
700             for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
701                 ptr[3*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);
702                 ptr[3*mb_x+0] = buffer[mb_x][1] + ptr[3*mb_x+1];
703                 ptr[3*mb_x+2] = buffer[mb_x][2] + ptr[3*mb_x+1];
704             }
705         }else{
706             for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
707                 ptr[3*mb_x+0] = buffer[mb_x][2];
708                 ptr[3*mb_x+1] = buffer[mb_x][1];
709                 ptr[3*mb_x+2] = buffer[mb_x][0];
710             }
711         }
712     }
713     return 0;
714 }
715
716 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
717     int i, mb_x, mb_y;
718     const int nb_components=3;
719
720     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
721         for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
722             if (s->restart_interval && !s->restart_count)
723                 s->restart_count = s->restart_interval;
724
725             if(mb_x==0 || mb_y==0 || s->interlaced){
726                 for(i=0;i<nb_components;i++) {
727                     uint8_t *ptr;
728                     int n, h, v, x, y, c, j, linesize;
729                     n = s->nb_blocks[i];
730                     c = s->comp_index[i];
731                     h = s->h_scount[i];
732                     v = s->v_scount[i];
733                     x = 0;
734                     y = 0;
735                     linesize= s->linesize[c];
736
737                     for(j=0; j<n; j++) {
738                         int pred;
739
740                         ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
741                         if(y==0 && mb_y==0){
742                             if(x==0 && mb_x==0){
743                                 pred= 128 << point_transform;
744                             }else{
745                                 pred= ptr[-1];
746                             }
747                         }else{
748                             if(x==0 && mb_x==0){
749                                 pred= ptr[-linesize];
750                             }else{
751                                 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
752                             }
753                         }
754
755                         if (s->interlaced && s->bottom_field)
756                             ptr += linesize >> 1;
757                         *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
758
759                         if (++x == h) {
760                             x = 0;
761                             y++;
762                         }
763                     }
764                 }
765             }else{
766                 for(i=0;i<nb_components;i++) {
767                     uint8_t *ptr;
768                     int n, h, v, x, y, c, j, linesize;
769                     n = s->nb_blocks[i];
770                     c = s->comp_index[i];
771                     h = s->h_scount[i];
772                     v = s->v_scount[i];
773                     x = 0;
774                     y = 0;
775                     linesize= s->linesize[c];
776
777                     for(j=0; j<n; j++) {
778                         int pred;
779
780                         ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
781                         PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
782                         *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
783                         if (++x == h) {
784                             x = 0;
785                             y++;
786                         }
787                     }
788                 }
789             }
790             if (s->restart_interval && !--s->restart_count) {
791                 align_get_bits(&s->gb);
792                 skip_bits(&s->gb, 16); /* skip RSTn */
793             }
794         }
795     }
796     return 0;
797 }
798
799 static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
800                                               int linesize, int lowres)
801 {
802     switch (lowres) {
803     case 0: copy_block8(dst, src, linesize, linesize, 8);
804         break;
805     case 1: copy_block4(dst, src, linesize, linesize, 4);
806         break;
807     case 2: copy_block2(dst, src, linesize, linesize, 2);
808         break;
809     case 3: *dst = *src;
810         break;
811     }
812 }
813
814 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,
815                              const uint8_t *mb_bitmask, const AVFrame *reference){
816     int i, mb_x, mb_y;
817     uint8_t* data[MAX_COMPONENTS];
818     const uint8_t *reference_data[MAX_COMPONENTS];
819     int linesize[MAX_COMPONENTS];
820     GetBitContext mb_bitmask_gb;
821
822     if (mb_bitmask) {
823         init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
824     }
825
826     if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
827         av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
828         s->flipped = 0;
829     }
830     for(i=0; i < nb_components; i++) {
831         int c = s->comp_index[i];
832         data[c] = s->picture_ptr->data[c];
833         reference_data[c] = reference ? reference->data[c] : NULL;
834         linesize[c]=s->linesize[c];
835         s->coefs_finished[c] |= 1;
836         if(s->flipped) {
837             //picture should be flipped upside-down for this codec
838             int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
839             data[c] += offset;
840             reference_data[c] += offset;
841             linesize[c] *= -1;
842         }
843     }
844
845     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
846         for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
847             const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
848
849             if (s->restart_interval && !s->restart_count)
850                 s->restart_count = s->restart_interval;
851
852             if(get_bits_count(&s->gb)>s->gb.size_in_bits){
853                 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n", get_bits_count(&s->gb) - s->gb.size_in_bits);
854                 return -1;
855             }
856             for(i=0;i<nb_components;i++) {
857                 uint8_t *ptr;
858                 int n, h, v, x, y, c, j;
859                 int block_offset;
860                 n = s->nb_blocks[i];
861                 c = s->comp_index[i];
862                 h = s->h_scount[i];
863                 v = s->v_scount[i];
864                 x = 0;
865                 y = 0;
866                 for(j=0;j<n;j++) {
867                     block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
868                                      (h * mb_x + x) * 8) >> s->avctx->lowres);
869
870                     if(s->interlaced && s->bottom_field)
871                         block_offset += linesize[c] >> 1;
872                     ptr = data[c] + block_offset;
873                     if(!s->progressive) {
874                         if (copy_mb) {
875                             mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);
876                         } else {
877                         s->dsp.clear_block(s->block);
878                         if(decode_block(s, s->block, i,
879                                      s->dc_index[i], s->ac_index[i],
880                                      s->quant_matrixes[ s->quant_index[c] ]) < 0) {
881                             av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
882                             return -1;
883                         }
884                         s->dsp.idct_put(ptr, linesize[c], s->block);
885                         }
886                     } else {
887                         int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
888                         DCTELEM *block = s->blocks[c][block_idx];
889                         if(Ah)
890                             block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;
891                         else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {
892                             av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
893                             return -1;
894                         }
895                     }
896 //                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
897 //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);
898                     if (++x == h) {
899                         x = 0;
900                         y++;
901                     }
902                 }
903             }
904
905             if (s->restart_interval) --s->restart_count;
906             i= 8+((-get_bits_count(&s->gb))&7);
907             if (s->restart_interval && show_bits(&s->gb, i)  == (1<<i)-1){ /* skip RSTn */
908                 int pos= get_bits_count(&s->gb);
909                 align_get_bits(&s->gb);
910                 while(get_bits_count(&s->gb) < s->gb.size_in_bits && show_bits(&s->gb, 8) == 0xFF)
911                     skip_bits(&s->gb, 8);
912                 if(get_bits_count(&s->gb) < s->gb.size_in_bits && (get_bits(&s->gb, 8)&0xF8) == 0xD0){
913                     for (i=0; i<nb_components; i++) /* reset dc */
914                         s->last_dc[i] = 1024;
915                 }else{
916                     skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
917                 }
918             }
919         }
920     }
921     return 0;
922 }
923
924 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
925     int mb_x, mb_y;
926     int EOBRUN = 0;
927     int c = s->comp_index[0];
928     uint8_t* data = s->picture.data[c];
929     int linesize = s->linesize[c];
930     int last_scan = 0;
931     int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
932
933     if(!Al) {
934         s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
935         last_scan = !~s->coefs_finished[c];
936     }
937
938     if(s->interlaced && s->bottom_field)
939         data += linesize >> 1;
940
941     for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
942         uint8_t *ptr = data + (mb_y*linesize*8 >> s->avctx->lowres);
943         int block_idx = mb_y * s->block_stride[c];
944         DCTELEM (*block)[64] = &s->blocks[c][block_idx];
945         uint8_t *last_nnz = &s->last_nnz[c][block_idx];
946         for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
947             int ret;
948             if(Ah)
949                 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
950                                               quant_matrix, ss, se, Al, &EOBRUN);
951             else
952                 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
953                                                quant_matrix, ss, se, Al, &EOBRUN);
954             if(ret < 0) {
955                 av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
956                 return -1;
957             }
958             if(last_scan) {
959                 s->dsp.idct_put(ptr, linesize, *block);
960                 ptr += 8 >> s->avctx->lowres;
961             }
962         }
963     }
964     return 0;
965 }
966
967 int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
968                         const uint8_t *mb_bitmask, const AVFrame *reference)
969 {
970     int len, nb_components, i, h, v, predictor, point_transform;
971     int index, id;
972     const int block_size= s->lossless ? 1 : 8;
973     int ilv, prev_shift;
974
975     /* XXX: verify len field validity */
976     len = get_bits(&s->gb, 16);
977     nb_components = get_bits(&s->gb, 8);
978     if (nb_components == 0 || nb_components > MAX_COMPONENTS){
979         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: nb_components (%d) unsupported\n", nb_components);
980         return -1;
981     }
982     if (len != 6+2*nb_components)
983     {
984         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
985         return -1;
986     }
987     for(i=0;i<nb_components;i++) {
988         id = get_bits(&s->gb, 8) - 1;
989         av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
990         /* find component index */
991         for(index=0;index<s->nb_components;index++)
992             if (id == s->component_id[index])
993                 break;
994         if (index == s->nb_components)
995         {
996             av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
997             return -1;
998         }
999         /* Metasoft MJPEG codec has Cb and Cr swapped */
1000         if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1001             && nb_components == 3 && s->nb_components == 3 && i)
1002             index = 3 - i;
1003
1004         if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
1005             index = (i+2)%3;
1006
1007         s->comp_index[i] = index;
1008
1009         s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1010         s->h_scount[i] = s->h_count[index];
1011         s->v_scount[i] = s->v_count[index];
1012
1013         s->dc_index[i] = get_bits(&s->gb, 4);
1014         s->ac_index[i] = get_bits(&s->gb, 4);
1015
1016         if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
1017             s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1018             goto out_of_range;
1019         if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
1020             goto out_of_range;
1021     }
1022
1023     predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1024     ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
1025     if(s->avctx->codec_tag != AV_RL32("CJPG")){
1026         prev_shift = get_bits(&s->gb, 4); /* Ah */
1027         point_transform= get_bits(&s->gb, 4); /* Al */
1028     }else
1029         prev_shift= point_transform= 0;
1030
1031     for(i=0;i<nb_components;i++)
1032         s->last_dc[i] = 1024;
1033
1034     if (nb_components > 1) {
1035         /* interleaved stream */
1036         s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
1037         s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1038     } else if(!s->ls) { /* skip this for JPEG-LS */
1039         h = s->h_max / s->h_scount[0];
1040         v = s->v_max / s->v_scount[0];
1041         s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
1042         s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1043         s->nb_blocks[0] = 1;
1044         s->h_scount[0] = 1;
1045         s->v_scount[0] = 1;
1046     }
1047
1048     if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1049         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" : "",
1050                predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1051                s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1052
1053
1054     /* mjpeg-b can have padding bytes between sos and image data, skip them */
1055     for (i = s->mjpb_skiptosod; i > 0; i--)
1056         skip_bits(&s->gb, 8);
1057
1058     if(s->lossless){
1059         av_assert0(s->picture_ptr == &s->picture);
1060         if(CONFIG_JPEGLS_DECODER && s->ls){
1061 //            for(){
1062 //            reset_ls_coding_parameters(s, 0);
1063
1064             if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
1065                 return -1;
1066         }else{
1067             if(s->rgb){
1068                 if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
1069                     return -1;
1070             }else{
1071                 if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
1072                     return -1;
1073             }
1074         }
1075     }else{
1076         if(s->progressive && predictor) {
1077             av_assert0(s->picture_ptr == &s->picture);
1078             if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform) < 0)
1079                 return -1;
1080         } else {
1081             if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
1082                                  mb_bitmask, reference) < 0)
1083                 return -1;
1084         }
1085     }
1086     emms_c();
1087     return 0;
1088  out_of_range:
1089     av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1090     return -1;
1091 }
1092
1093 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1094 {
1095     if (get_bits(&s->gb, 16) != 4)
1096         return -1;
1097     s->restart_interval = get_bits(&s->gb, 16);
1098     s->restart_count = 0;
1099     av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1100
1101     return 0;
1102 }
1103
1104 static int mjpeg_decode_app(MJpegDecodeContext *s)
1105 {
1106     int len, id, i;
1107
1108     len = get_bits(&s->gb, 16);
1109     if (len < 5)
1110         return -1;
1111     if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1112         return -1;
1113
1114     id = get_bits_long(&s->gb, 32);
1115     id = av_be2ne32(id);
1116     len -= 6;
1117
1118     if(s->avctx->debug & FF_DEBUG_STARTCODE){
1119         av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1120     }
1121
1122     /* Buggy AVID, it puts EOI only at every 10th frame. */
1123     /* Also, this fourcc is used by non-avid files too, it holds some
1124        information, but it's always present in AVID-created files. */
1125     if (id == AV_RL32("AVI1"))
1126     {
1127         /* structure:
1128             4bytes      AVI1
1129             1bytes      polarity
1130             1bytes      always zero
1131             4bytes      field_size
1132             4bytes      field_size_less_padding
1133         */
1134             s->buggy_avid = 1;
1135 //        if (s->first_picture)
1136 //            printf("mjpeg: workarounding buggy AVID\n");
1137         i = get_bits(&s->gb, 8); len--;
1138         av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1139 #if 0
1140         skip_bits(&s->gb, 8);
1141         skip_bits(&s->gb, 32);
1142         skip_bits(&s->gb, 32);
1143         len -= 10;
1144 #endif
1145 //        if (s->interlace_polarity)
1146 //            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1147         goto out;
1148     }
1149
1150 //    len -= 2;
1151
1152     if (id == AV_RL32("JFIF"))
1153     {
1154         int t_w, t_h, v1, v2;
1155         skip_bits(&s->gb, 8); /* the trailing zero-byte */
1156         v1= get_bits(&s->gb, 8);
1157         v2= get_bits(&s->gb, 8);
1158         skip_bits(&s->gb, 8);
1159
1160         s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1161         s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1162
1163         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1164             av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1165                 v1, v2,
1166                 s->avctx->sample_aspect_ratio.num,
1167                 s->avctx->sample_aspect_ratio.den
1168             );
1169
1170         t_w = get_bits(&s->gb, 8);
1171         t_h = get_bits(&s->gb, 8);
1172         if (t_w && t_h)
1173         {
1174             /* skip thumbnail */
1175             if (len-10-(t_w*t_h*3) > 0)
1176                 len -= t_w*t_h*3;
1177         }
1178         len -= 10;
1179         goto out;
1180     }
1181
1182     if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
1183     {
1184         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1185             av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1186         skip_bits(&s->gb, 16); /* version */
1187         skip_bits(&s->gb, 16); /* flags0 */
1188         skip_bits(&s->gb, 16); /* flags1 */
1189         skip_bits(&s->gb, 8);  /* transform */
1190         len -= 7;
1191         goto out;
1192     }
1193
1194     if (id == AV_RL32("LJIF")){
1195         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1196             av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
1197         skip_bits(&s->gb, 16); /* version ? */
1198         skip_bits(&s->gb, 16); /* unknwon always 0? */
1199         skip_bits(&s->gb, 16); /* unknwon always 0? */
1200         skip_bits(&s->gb, 16); /* unknwon always 0? */
1201         switch( get_bits(&s->gb, 8)){
1202         case 1:
1203             s->rgb= 1;
1204             s->pegasus_rct=0;
1205             break;
1206         case 2:
1207             s->rgb= 1;
1208             s->pegasus_rct=1;
1209             break;
1210         default:
1211             av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1212         }
1213         len -= 9;
1214         goto out;
1215     }
1216
1217     /* Apple MJPEG-A */
1218     if ((s->start_code == APP1) && (len > (0x28 - 8)))
1219     {
1220         id = get_bits_long(&s->gb, 32);
1221         id = av_be2ne32(id);
1222         len -= 4;
1223         if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
1224         {
1225 #if 0
1226             skip_bits(&s->gb, 32); /* field size */
1227             skip_bits(&s->gb, 32); /* pad field size */
1228             skip_bits(&s->gb, 32); /* next off */
1229             skip_bits(&s->gb, 32); /* quant off */
1230             skip_bits(&s->gb, 32); /* huff off */
1231             skip_bits(&s->gb, 32); /* image off */
1232             skip_bits(&s->gb, 32); /* scan off */
1233             skip_bits(&s->gb, 32); /* data off */
1234 #endif
1235             if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1236                 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1237         }
1238     }
1239
1240 out:
1241     /* slow but needed for extreme adobe jpegs */
1242     if (len < 0)
1243         av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1244     while(--len > 0)
1245         skip_bits(&s->gb, 8);
1246
1247     return 0;
1248 }
1249
1250 static int mjpeg_decode_com(MJpegDecodeContext *s)
1251 {
1252     int len = get_bits(&s->gb, 16);
1253     if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
1254         char *cbuf = av_malloc(len - 1);
1255         if (cbuf) {
1256             int i;
1257             for (i = 0; i < len - 2; i++)
1258                 cbuf[i] = get_bits(&s->gb, 8);
1259             if (i > 0 && cbuf[i-1] == '\n')
1260                 cbuf[i-1] = 0;
1261             else
1262                 cbuf[i] = 0;
1263
1264             if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1265                 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1266
1267             /* buggy avid, it puts EOI only at every 10th frame */
1268             if (!strcmp(cbuf, "AVID"))
1269             {
1270                 s->buggy_avid = 1;
1271                 //        if (s->first_picture)
1272                 //            printf("mjpeg: workarounding buggy AVID\n");
1273             }
1274             else if(!strcmp(cbuf, "CS=ITU601")){
1275                 s->cs_itu601= 1;
1276             }
1277             else if((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1278                     (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20))){
1279                 s->flipped = 1;
1280             }
1281
1282             av_free(cbuf);
1283         }
1284     }
1285
1286     return 0;
1287 }
1288
1289 /* return the 8 bit start code value and update the search
1290    state. Return -1 if no start code found */
1291 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1292 {
1293     const uint8_t *buf_ptr;
1294     unsigned int v, v2;
1295     int val;
1296     int skipped=0;
1297
1298     buf_ptr = *pbuf_ptr;
1299     while (buf_ptr < buf_end) {
1300         v = *buf_ptr++;
1301         v2 = *buf_ptr;
1302         if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1303             val = *buf_ptr++;
1304             goto found;
1305         }
1306         skipped++;
1307     }
1308     val = -1;
1309 found:
1310     av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1311     *pbuf_ptr = buf_ptr;
1312     return val;
1313 }
1314
1315 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1316                          const uint8_t **buf_ptr, const uint8_t *buf_end,
1317                          const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
1318 {
1319     int start_code;
1320     start_code = find_marker(buf_ptr, buf_end);
1321
1322                 if ((buf_end - *buf_ptr) > s->buffer_size)
1323                 {
1324                     av_free(s->buffer);
1325                     s->buffer_size = buf_end - *buf_ptr;
1326                     s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1327                     av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1328                         s->buffer_size);
1329                 }
1330
1331                 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1332                 if (start_code == SOS && !s->ls)
1333                 {
1334                     const uint8_t *src = *buf_ptr;
1335                     uint8_t *dst = s->buffer;
1336
1337                     while (src<buf_end)
1338                     {
1339                         uint8_t x = *(src++);
1340
1341                         *(dst++) = x;
1342                         if (s->avctx->codec_id != CODEC_ID_THP)
1343                         {
1344                             if (x == 0xff) {
1345                                 while (src < buf_end && x == 0xff)
1346                                     x = *(src++);
1347
1348                                 if (x >= 0xd0 && x <= 0xd7)
1349                                     *(dst++) = x;
1350                                 else if (x)
1351                                     break;
1352                             }
1353                         }
1354                     }
1355                     *unescaped_buf_ptr  = s->buffer;
1356                     *unescaped_buf_size = dst - s->buffer;
1357
1358                     av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1359                            (buf_end - *buf_ptr) - (dst - s->buffer));
1360                 }
1361                 else if(start_code == SOS && s->ls){
1362                     const uint8_t *src = *buf_ptr;
1363                     uint8_t *dst = s->buffer;
1364                     int bit_count = 0;
1365                     int t = 0, b = 0;
1366                     PutBitContext pb;
1367
1368                     s->cur_scan++;
1369
1370                     /* find marker */
1371                     while (src + t < buf_end){
1372                         uint8_t x = src[t++];
1373                         if (x == 0xff){
1374                             while((src + t < buf_end) && x == 0xff)
1375                                 x = src[t++];
1376                             if (x & 0x80) {
1377                                 t -= 2;
1378                                 break;
1379                             }
1380                         }
1381                     }
1382                     bit_count = t * 8;
1383
1384                     init_put_bits(&pb, dst, t);
1385
1386                     /* unescape bitstream */
1387                     while(b < t){
1388                         uint8_t x = src[b++];
1389                         put_bits(&pb, 8, x);
1390                         if(x == 0xFF){
1391                             x = src[b++];
1392                             put_bits(&pb, 7, x);
1393                             bit_count--;
1394                         }
1395                     }
1396                     flush_put_bits(&pb);
1397
1398                     *unescaped_buf_ptr  = dst;
1399                     *unescaped_buf_size = (bit_count + 7) >> 3;
1400                 }
1401                 else
1402                 {
1403                     *unescaped_buf_ptr  = *buf_ptr;
1404                     *unescaped_buf_size = buf_end - *buf_ptr;
1405                 }
1406
1407     return start_code;
1408 }
1409
1410 int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1411                               void *data, int *data_size,
1412                               AVPacket *avpkt)
1413 {
1414     const uint8_t *buf = avpkt->data;
1415     int buf_size = avpkt->size;
1416     MJpegDecodeContext *s = avctx->priv_data;
1417     const uint8_t *buf_end, *buf_ptr;
1418     const uint8_t *unescaped_buf_ptr;
1419     int unescaped_buf_size;
1420     int start_code;
1421     AVFrame *picture = data;
1422
1423     s->got_picture = 0; // picture from previous image can not be reused
1424     buf_ptr = buf;
1425     buf_end = buf + buf_size;
1426     while (buf_ptr < buf_end) {
1427         /* find start next marker */
1428         start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1429                                           &unescaped_buf_ptr, &unescaped_buf_size);
1430         {
1431             /* EOF */
1432             if (start_code < 0) {
1433                 goto the_end;
1434             } else {
1435                 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
1436
1437                 init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1438
1439                 s->start_code = start_code;
1440                 if(s->avctx->debug & FF_DEBUG_STARTCODE){
1441                     av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1442                 }
1443
1444                 /* process markers */
1445                 if (start_code >= 0xd0 && start_code <= 0xd7) {
1446                     av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1447                     /* APP fields */
1448                 } else if (start_code >= APP0 && start_code <= APP15) {
1449                     mjpeg_decode_app(s);
1450                     /* Comment */
1451                 } else if (start_code == COM){
1452                     mjpeg_decode_com(s);
1453                 }
1454
1455                 switch(start_code) {
1456                 case SOI:
1457                     s->restart_interval = 0;
1458
1459                     s->restart_count = 0;
1460                     /* nothing to do on SOI */
1461                     break;
1462                 case DQT:
1463                     ff_mjpeg_decode_dqt(s);
1464                     break;
1465                 case DHT:
1466                     if(ff_mjpeg_decode_dht(s) < 0){
1467                         av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1468                         return -1;
1469                     }
1470                     break;
1471                 case SOF0:
1472                 case SOF1:
1473                     s->lossless=0;
1474                     s->ls=0;
1475                     s->progressive=0;
1476                     if (ff_mjpeg_decode_sof(s) < 0)
1477                         return -1;
1478                     break;
1479                 case SOF2:
1480                     s->lossless=0;
1481                     s->ls=0;
1482                     s->progressive=1;
1483                     if (ff_mjpeg_decode_sof(s) < 0)
1484                         return -1;
1485                     break;
1486                 case SOF3:
1487                     s->lossless=1;
1488                     s->ls=0;
1489                     s->progressive=0;
1490                     if (ff_mjpeg_decode_sof(s) < 0)
1491                         return -1;
1492                     break;
1493                 case SOF48:
1494                     s->lossless=1;
1495                     s->ls=1;
1496                     s->progressive=0;
1497                     if (ff_mjpeg_decode_sof(s) < 0)
1498                         return -1;
1499                     break;
1500                 case LSE:
1501                     if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1502                         return -1;
1503                     break;
1504                 case EOI:
1505 eoi_parser:
1506                     s->cur_scan = 0;
1507                     if (!s->got_picture) {
1508                         av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
1509                         break;
1510                     }
1511                     if (s->interlaced) {
1512                         s->bottom_field ^= 1;
1513                         /* if not bottom field, do not output image yet */
1514                         if (s->bottom_field == !s->interlace_polarity)
1515                             break;
1516                     }
1517                     *picture = *s->picture_ptr;
1518                     *data_size = sizeof(AVFrame);
1519
1520                     if(!s->lossless){
1521                         picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
1522                         picture->qstride= 0;
1523                         picture->qscale_table= s->qscale_table;
1524                         memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1525                         if(avctx->debug & FF_DEBUG_QP)
1526                             av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1527                         picture->quality*= FF_QP2LAMBDA;
1528                     }
1529
1530                     goto the_end;
1531                 case SOS:
1532                     if (!s->got_picture) {
1533                         av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
1534                         break;
1535                     }
1536                     if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&
1537                         (avctx->err_recognition & AV_EF_EXPLODE))
1538                       return AVERROR_INVALIDDATA;
1539                     break;
1540                 case DRI:
1541                     mjpeg_decode_dri(s);
1542                     break;
1543                 case SOF5:
1544                 case SOF6:
1545                 case SOF7:
1546                 case SOF9:
1547                 case SOF10:
1548                 case SOF11:
1549                 case SOF13:
1550                 case SOF14:
1551                 case SOF15:
1552                 case JPG:
1553                     av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1554                     break;
1555 //                default:
1556 //                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1557 //                    break;
1558                 }
1559
1560                 /* eof process start code */
1561                 buf_ptr += (get_bits_count(&s->gb)+7)/8;
1562                 av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1563                        (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1564             }
1565         }
1566     }
1567     if (s->got_picture) {
1568         av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1569         goto eoi_parser;
1570     }
1571     av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1572     return -1;
1573 the_end:
1574     av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
1575 //    return buf_end - buf_ptr;
1576     return buf_ptr - buf;
1577 }
1578
1579 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1580 {
1581     MJpegDecodeContext *s = avctx->priv_data;
1582     int i, j;
1583
1584     if (s->picture_ptr && s->picture_ptr->data[0])
1585         avctx->release_buffer(avctx, s->picture_ptr);
1586
1587     av_free(s->buffer);
1588     av_free(s->qscale_table);
1589     av_freep(&s->ljpeg_buffer);
1590     s->ljpeg_buffer_size=0;
1591
1592     for(i=0;i<3;i++) {
1593         for(j=0;j<4;j++)
1594             free_vlc(&s->vlcs[i][j]);
1595     }
1596     for(i=0; i<MAX_COMPONENTS; i++) {
1597         av_freep(&s->blocks[i]);
1598         av_freep(&s->last_nnz[i]);
1599     }
1600     return 0;
1601 }
1602
1603 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1604 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1605 static const AVOption options[] = {
1606     { "extern_huff",        "Use external huffman table.",  OFFSET(extern_huff), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD },
1607     { NULL },
1608 };
1609
1610 static const AVClass mjpegdec_class = {
1611     .class_name = "MJPEG decoder",
1612     .item_name  = av_default_item_name,
1613     .option     = options,
1614     .version    = LIBAVUTIL_VERSION_INT,
1615 };
1616
1617 AVCodec ff_mjpeg_decoder = {
1618     .name           = "mjpeg",
1619     .type           = AVMEDIA_TYPE_VIDEO,
1620     .id             = CODEC_ID_MJPEG,
1621     .priv_data_size = sizeof(MJpegDecodeContext),
1622     .init           = ff_mjpeg_decode_init,
1623     .close          = ff_mjpeg_decode_end,
1624     .decode         = ff_mjpeg_decode_frame,
1625     .capabilities   = CODEC_CAP_DR1,
1626     .max_lowres = 3,
1627     .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1628     .priv_class     = &mjpegdec_class,
1629 };
1630
1631 AVCodec ff_thp_decoder = {
1632     .name           = "thp",
1633     .type           = AVMEDIA_TYPE_VIDEO,
1634     .id             = CODEC_ID_THP,
1635     .priv_data_size = sizeof(MJpegDecodeContext),
1636     .init           = ff_mjpeg_decode_init,
1637     .close          = ff_mjpeg_decode_end,
1638     .decode         = ff_mjpeg_decode_frame,
1639     .capabilities   = CODEC_CAP_DR1,
1640     .max_lowres = 3,
1641     .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1642 };