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