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