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