]> git.sesse.net Git - ffmpeg/blob - libavcodec/mjpegdec.c
x86/vp9lpf: add ff_vp9_loop_filter_[vh]_88_16_sse2()
[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 #include "libavutil/imgutils.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/opt.h"
36 #include "avcodec.h"
37 #include "copy_block.h"
38 #include "internal.h"
39 #include "mjpeg.h"
40 #include "mjpegdec.h"
41 #include "jpeglsdec.h"
42 #include "tiff.h"
43 #include "exif.h"
44 #include "bytestream.h"
45
46
47 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
48                      const uint8_t *val_table, int nb_codes,
49                      int use_static, int is_ac)
50 {
51     uint8_t huff_size[256] = { 0 };
52     uint16_t huff_code[256];
53     uint16_t huff_sym[256];
54     int i;
55
56     av_assert0(nb_codes <= 256);
57
58     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
59
60     for (i = 0; i < 256; i++)
61         huff_sym[i] = i + 16 * is_ac;
62
63     if (is_ac)
64         huff_sym[0] = 16 * 256;
65
66     return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
67                               huff_code, 2, 2, huff_sym, 2, 2, use_static);
68 }
69
70 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
71 {
72     build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
73               avpriv_mjpeg_val_dc, 12, 0, 0);
74     build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
75               avpriv_mjpeg_val_dc, 12, 0, 0);
76     build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
77               avpriv_mjpeg_val_ac_luminance, 251, 0, 1);
78     build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
79               avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);
80     build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
81               avpriv_mjpeg_val_ac_luminance, 251, 0, 0);
82     build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
83               avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);
84 }
85
86 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
87 {
88     MJpegDecodeContext *s = avctx->priv_data;
89
90     if (!s->picture_ptr) {
91         s->picture = av_frame_alloc();
92         if (!s->picture)
93             return AVERROR(ENOMEM);
94         s->picture_ptr = s->picture;
95     }
96
97     s->avctx = avctx;
98     ff_hpeldsp_init(&s->hdsp, avctx->flags);
99     ff_dsputil_init(&s->dsp, avctx);
100     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
101     s->buffer_size   = 0;
102     s->buffer        = NULL;
103     s->start_code    = -1;
104     s->first_picture = 1;
105     s->got_picture   = 0;
106     s->org_height    = avctx->coded_height;
107     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
108
109     build_basic_mjpeg_vlc(s);
110
111     if (s->extern_huff) {
112         av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
113         init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
114         if (ff_mjpeg_decode_dht(s)) {
115             av_log(avctx, AV_LOG_ERROR,
116                    "error using external huffman table, switching back to internal\n");
117             build_basic_mjpeg_vlc(s);
118         }
119     }
120     if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
121         s->interlace_polarity = 1;           /* bottom field first */
122         av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
123     }
124     if (avctx->codec->id == AV_CODEC_ID_AMV)
125         s->flipped = 1;
126
127     return 0;
128 }
129
130
131 /* quantize tables */
132 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
133 {
134     int len, index, i, j;
135
136     len = get_bits(&s->gb, 16) - 2;
137
138     while (len >= 65) {
139         int pr = get_bits(&s->gb, 4);
140         if (pr > 1) {
141             av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
142             return AVERROR_INVALIDDATA;
143         }
144         index = get_bits(&s->gb, 4);
145         if (index >= 4)
146             return -1;
147         av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
148         /* read quant table */
149         for (i = 0; i < 64; i++) {
150             j = s->scantable.permutated[i];
151             s->quant_matrixes[index][j] = get_bits(&s->gb, pr ? 16 : 8);
152         }
153
154         // XXX FIXME finetune, and perhaps add dc too
155         s->qscale[index] = FFMAX(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",
158                index, s->qscale[index]);
159         len -= 65;
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     int ret = 0;
171
172     len = get_bits(&s->gb, 16) - 2;
173
174     while (len > 0) {
175         if (len < 17)
176             return AVERROR_INVALIDDATA;
177         class = get_bits(&s->gb, 4);
178         if (class >= 2)
179             return AVERROR_INVALIDDATA;
180         index = get_bits(&s->gb, 4);
181         if (index >= 4)
182             return AVERROR_INVALIDDATA;
183         n = 0;
184         for (i = 1; i <= 16; i++) {
185             bits_table[i] = get_bits(&s->gb, 8);
186             n += bits_table[i];
187         }
188         len -= 17;
189         if (len < n || n > 256)
190             return AVERROR_INVALIDDATA;
191
192         code_max = 0;
193         for (i = 0; i < n; i++) {
194             v = get_bits(&s->gb, 8);
195             if (v > code_max)
196                 code_max = v;
197             val_table[i] = v;
198         }
199         len -= n;
200
201         /* build VLC and flush previous vlc if present */
202         ff_free_vlc(&s->vlcs[class][index]);
203         av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
204                class, index, code_max + 1);
205         if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
206                              code_max + 1, 0, class > 0)) < 0)
207             return ret;
208
209         if (class > 0) {
210             ff_free_vlc(&s->vlcs[2][index]);
211             if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
212                                  code_max + 1, 0, 0)) < 0)
213                 return ret;
214         }
215     }
216     return 0;
217 }
218
219 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
220 {
221     int len, nb_components, i, width, height, pix_fmt_id, ret;
222     int h_count[MAX_COMPONENTS];
223     int v_count[MAX_COMPONENTS];
224
225     s->cur_scan = 0;
226     s->upscale_h = s->upscale_v = 0;
227
228     /* XXX: verify len field validity */
229     len     = get_bits(&s->gb, 16);
230     s->avctx->bits_per_raw_sample =
231     s->bits = get_bits(&s->gb, 8);
232
233     if (s->pegasus_rct)
234         s->bits = 9;
235     if (s->bits == 9 && !s->pegasus_rct)
236         s->rct  = 1;    // FIXME ugly
237
238     if(s->lossless && s->avctx->lowres){
239         av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
240         return -1;
241     }
242
243     height = get_bits(&s->gb, 16);
244     width  = get_bits(&s->gb, 16);
245
246     // HACK for odd_height.mov
247     if (s->interlaced && s->width == width && s->height == height + 1)
248         height= s->height;
249
250     av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
251     if (av_image_check_size(width, height, 0, s->avctx))
252         return AVERROR_INVALIDDATA;
253
254     nb_components = get_bits(&s->gb, 8);
255     if (nb_components <= 0 ||
256         nb_components > MAX_COMPONENTS)
257         return -1;
258     if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
259         if (nb_components != s->nb_components) {
260             av_log(s->avctx, AV_LOG_ERROR,
261                    "nb_components changing in interlaced picture\n");
262             return AVERROR_INVALIDDATA;
263         }
264     }
265     if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
266         avpriv_report_missing_feature(s->avctx,
267                                       "JPEG-LS that is not <= 8 "
268                                       "bits/component or 16-bit gray");
269         return AVERROR_PATCHWELCOME;
270     }
271     s->nb_components = nb_components;
272     s->h_max         = 1;
273     s->v_max         = 1;
274     memset(h_count, 0, sizeof(h_count));
275     memset(v_count, 0, sizeof(v_count));
276     for (i = 0; i < nb_components; i++) {
277         /* component id */
278         s->component_id[i] = get_bits(&s->gb, 8) - 1;
279         h_count[i]         = get_bits(&s->gb, 4);
280         v_count[i]         = get_bits(&s->gb, 4);
281         /* compute hmax and vmax (only used in interleaved case) */
282         if (h_count[i] > s->h_max)
283             s->h_max = h_count[i];
284         if (v_count[i] > s->v_max)
285             s->v_max = v_count[i];
286         s->quant_index[i] = get_bits(&s->gb, 8);
287         if (s->quant_index[i] >= 4) {
288             av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
289             return AVERROR_INVALIDDATA;
290         }
291         if (!h_count[i] || !v_count[i]) {
292             av_log(s->avctx, AV_LOG_ERROR,
293                    "Invalid sampling factor in component %d %d:%d\n",
294                    i, h_count[i], v_count[i]);
295             return AVERROR_INVALIDDATA;
296         }
297
298         av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
299                i, h_count[i], v_count[i],
300                s->component_id[i], s->quant_index[i]);
301     }
302
303     if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
304         avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
305         return AVERROR_PATCHWELCOME;
306     }
307
308
309     /* if different size, realloc/alloc picture */
310     if (   width != s->width || height != s->height
311         || memcmp(s->h_count, h_count, sizeof(h_count))
312         || memcmp(s->v_count, v_count, sizeof(v_count))) {
313
314         s->width      = width;
315         s->height     = height;
316         memcpy(s->h_count, h_count, sizeof(h_count));
317         memcpy(s->v_count, v_count, sizeof(v_count));
318         s->interlaced = 0;
319         s->got_picture = 0;
320
321         /* test interlaced mode */
322         if (s->first_picture   &&
323             s->org_height != 0 &&
324             s->height < ((s->org_height * 3) / 4)) {
325             s->interlaced                    = 1;
326             s->bottom_field                  = s->interlace_polarity;
327             s->picture_ptr->interlaced_frame = 1;
328             s->picture_ptr->top_field_first  = !s->interlace_polarity;
329             height *= 2;
330         }
331
332         ret = ff_set_dimensions(s->avctx, width, height);
333         if (ret < 0)
334             return ret;
335
336         s->first_picture = 0;
337     }
338
339     if (s->got_picture && s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
340         if (s->progressive) {
341             avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
342             return AVERROR_INVALIDDATA;
343         }
344     } else{
345         if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
346             s->rgb = 1;
347         else if (!s->lossless)
348             s->rgb = 0;
349     /* XXX: not complete test ! */
350     pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
351                  (s->h_count[1] << 20) | (s->v_count[1] << 16) |
352                  (s->h_count[2] << 12) | (s->v_count[2] <<  8) |
353                  (s->h_count[3] <<  4) |  s->v_count[3];
354     av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
355     /* NOTE we do not allocate pictures large enough for the possible
356      * padding of h/v_count being 4 */
357     if (!(pix_fmt_id & 0xD0D0D0D0))
358         pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
359     if (!(pix_fmt_id & 0x0D0D0D0D))
360         pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
361
362     switch (pix_fmt_id) {
363     case 0x11111100:
364         if (s->rgb)
365             s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_BGR48;
366         else {
367             if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
368                 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_GBRP : AV_PIX_FMT_GBRP16;
369             } else {
370                 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
371                 else              s->avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
372             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
373             }
374         }
375         av_assert0(s->nb_components == 3);
376         break;
377     case 0x11111111:
378         if (s->rgb)
379             s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA64;
380         else {
381             s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_YUVA444P : AV_PIX_FMT_YUVA444P16;
382             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
383         }
384         av_assert0(s->nb_components == 4);
385         break;
386     case 0x12121100:
387     case 0x22122100:
388         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
389         else
390             goto unk_pixfmt;
391         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
392         s->upscale_v = 2;
393         s->upscale_h = (pix_fmt_id == 0x22122100);
394         s->chroma_height = s->height;
395         break;
396     case 0x21211100:
397     case 0x22211200:
398         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
399         else
400             goto unk_pixfmt;
401         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
402         s->upscale_v = (pix_fmt_id == 0x22211200);
403         s->upscale_h = 2;
404         s->chroma_height = s->height;
405         break;
406     case 0x22221100:
407         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
408         else
409             goto unk_pixfmt;
410         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
411         s->upscale_v = 2;
412         s->upscale_h = 2;
413         s->chroma_height = s->height / 2;
414         break;
415     case 0x11000000:
416     case 0x13000000:
417     case 0x14000000:
418     case 0x31000000:
419     case 0x33000000:
420     case 0x34000000:
421     case 0x41000000:
422     case 0x43000000:
423     case 0x44000000:
424         if(s->bits <= 8)
425             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
426         else
427             s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
428         break;
429     case 0x12111100:
430     case 0x22211100:
431     case 0x22112100:
432         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
433         else
434             goto unk_pixfmt;
435         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
436         s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
437         s->chroma_height = s->height / 2;
438         break;
439     case 0x21111100:
440         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
441         else              s->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
442         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
443         break;
444     case 0x22121100:
445     case 0x22111200:
446         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
447         else
448             goto unk_pixfmt;
449         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
450         s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
451         break;
452     case 0x22111100:
453         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
454         else              s->avctx->pix_fmt = AV_PIX_FMT_YUV420P16;
455         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
456         break;
457     case 0x41111100:
458         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
459         else
460             goto unk_pixfmt;
461         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
462         break;
463     default:
464 unk_pixfmt:
465         av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
466         return AVERROR_PATCHWELCOME;
467     }
468     if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
469         av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
470         return AVERROR_PATCHWELCOME;
471     }
472     if (s->ls) {
473         s->upscale_h = s->upscale_v = 0;
474         if (s->nb_components > 1)
475             s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
476         else if (s->bits <= 8)
477             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
478         else
479             s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
480     }
481
482     s->pix_desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
483     if (!s->pix_desc) {
484         av_log(s->avctx, AV_LOG_ERROR, "Could not get a pixel format descriptor.\n");
485         return AVERROR_BUG;
486     }
487
488     av_frame_unref(s->picture_ptr);
489     if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
490         return -1;
491     s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
492     s->picture_ptr->key_frame = 1;
493     s->got_picture            = 1;
494
495     for (i = 0; i < 3; i++)
496         s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
497
498     av_dlog(s->avctx, "%d %d %d %d %d %d\n",
499             s->width, s->height, s->linesize[0], s->linesize[1],
500             s->interlaced, s->avctx->height);
501
502     if (len != (8 + (3 * nb_components)))
503         av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
504     }
505
506     if (s->rgb && !s->lossless && !s->ls) {
507         av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
508         return AVERROR_PATCHWELCOME;
509     }
510
511     /* totally blank picture as progressive JPEG will only add details to it */
512     if (s->progressive) {
513         int bw = (width  + s->h_max * 8 - 1) / (s->h_max * 8);
514         int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
515         for (i = 0; i < s->nb_components; i++) {
516             int size = bw * bh * s->h_count[i] * s->v_count[i];
517             av_freep(&s->blocks[i]);
518             av_freep(&s->last_nnz[i]);
519             s->blocks[i]       = av_mallocz(size * sizeof(**s->blocks));
520             s->last_nnz[i]     = av_mallocz(size * sizeof(**s->last_nnz));
521             if (!s->blocks[i] || !s->last_nnz[i])
522                 return AVERROR(ENOMEM);
523             s->block_stride[i] = bw * s->h_count[i];
524         }
525         memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
526     }
527     return 0;
528 }
529
530 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
531 {
532     int code;
533     code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
534     if (code < 0 || code > 16) {
535         av_log(s->avctx, AV_LOG_WARNING,
536                "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
537                0, dc_index, &s->vlcs[0][dc_index]);
538         return 0xfffff;
539     }
540
541     if (code)
542         return get_xbits(&s->gb, code);
543     else
544         return 0;
545 }
546
547 /* decode block and dequantize */
548 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
549                         int dc_index, int ac_index, int16_t *quant_matrix)
550 {
551     int code, i, j, level, val;
552
553     /* DC coef */
554     val = mjpeg_decode_dc(s, dc_index);
555     if (val == 0xfffff) {
556         av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
557         return AVERROR_INVALIDDATA;
558     }
559     val = val * quant_matrix[0] + s->last_dc[component];
560     s->last_dc[component] = val;
561     block[0] = val;
562     /* AC coefs */
563     i = 0;
564     {OPEN_READER(re, &s->gb);
565     do {
566         UPDATE_CACHE(re, &s->gb);
567         GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
568
569         i += ((unsigned)code) >> 4;
570             code &= 0xf;
571         if (code) {
572             if (code > MIN_CACHE_BITS - 16)
573                 UPDATE_CACHE(re, &s->gb);
574
575             {
576                 int cache = GET_CACHE(re, &s->gb);
577                 int sign  = (~cache) >> 31;
578                 level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
579             }
580
581             LAST_SKIP_BITS(re, &s->gb, code);
582
583             if (i > 63) {
584                 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
585                 return AVERROR_INVALIDDATA;
586             }
587             j        = s->scantable.permutated[i];
588             block[j] = level * quant_matrix[j];
589         }
590     } while (i < 63);
591     CLOSE_READER(re, &s->gb);}
592
593     return 0;
594 }
595
596 static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
597                                  int component, int dc_index,
598                                  int16_t *quant_matrix, int Al)
599 {
600     int val;
601     s->dsp.clear_block(block);
602     val = mjpeg_decode_dc(s, dc_index);
603     if (val == 0xfffff) {
604         av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
605         return AVERROR_INVALIDDATA;
606     }
607     val = (val * quant_matrix[0] << Al) + s->last_dc[component];
608     s->last_dc[component] = val;
609     block[0] = val;
610     return 0;
611 }
612
613 /* decode block and dequantize - progressive JPEG version */
614 static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
615                                     uint8_t *last_nnz, int ac_index,
616                                     int16_t *quant_matrix,
617                                     int ss, int se, int Al, int *EOBRUN)
618 {
619     int code, i, j, level, val, run;
620
621     if (*EOBRUN) {
622         (*EOBRUN)--;
623         return 0;
624     }
625
626     {
627         OPEN_READER(re, &s->gb);
628         for (i = ss; ; i++) {
629             UPDATE_CACHE(re, &s->gb);
630             GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
631
632             run = ((unsigned) code) >> 4;
633             code &= 0xF;
634             if (code) {
635                 i += run;
636                 if (code > MIN_CACHE_BITS - 16)
637                     UPDATE_CACHE(re, &s->gb);
638
639                 {
640                     int cache = GET_CACHE(re, &s->gb);
641                     int sign  = (~cache) >> 31;
642                     level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
643                 }
644
645                 LAST_SKIP_BITS(re, &s->gb, code);
646
647                 if (i >= se) {
648                     if (i == se) {
649                         j = s->scantable.permutated[se];
650                         block[j] = level * quant_matrix[j] << Al;
651                         break;
652                     }
653                     av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
654                     return AVERROR_INVALIDDATA;
655                 }
656                 j = s->scantable.permutated[i];
657                 block[j] = level * quant_matrix[j] << Al;
658             } else {
659                 if (run == 0xF) {// ZRL - skip 15 coefficients
660                     i += 15;
661                     if (i >= se) {
662                         av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
663                         return AVERROR_INVALIDDATA;
664                     }
665                 } else {
666                     val = (1 << run);
667                     if (run) {
668                         UPDATE_CACHE(re, &s->gb);
669                         val += NEG_USR32(GET_CACHE(re, &s->gb), run);
670                         LAST_SKIP_BITS(re, &s->gb, run);
671                     }
672                     *EOBRUN = val - 1;
673                     break;
674                 }
675             }
676         }
677         CLOSE_READER(re, &s->gb);
678     }
679
680     if (i > *last_nnz)
681         *last_nnz = i;
682
683     return 0;
684 }
685
686 #define REFINE_BIT(j) {                                             \
687     UPDATE_CACHE(re, &s->gb);                                       \
688     sign = block[j] >> 15;                                          \
689     block[j] += SHOW_UBITS(re, &s->gb, 1) *                         \
690                 ((quant_matrix[j] ^ sign) - sign) << Al;            \
691     LAST_SKIP_BITS(re, &s->gb, 1);                                  \
692 }
693
694 #define ZERO_RUN                                                    \
695 for (; ; i++) {                                                     \
696     if (i > last) {                                                 \
697         i += run;                                                   \
698         if (i > se) {                                               \
699             av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
700             return -1;                                              \
701         }                                                           \
702         break;                                                      \
703     }                                                               \
704     j = s->scantable.permutated[i];                                 \
705     if (block[j])                                                   \
706         REFINE_BIT(j)                                               \
707     else if (run-- == 0)                                            \
708         break;                                                      \
709 }
710
711 /* decode block and dequantize - progressive JPEG refinement pass */
712 static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
713                                    uint8_t *last_nnz,
714                                    int ac_index, int16_t *quant_matrix,
715                                    int ss, int se, int Al, int *EOBRUN)
716 {
717     int code, i = ss, j, sign, val, run;
718     int last    = FFMIN(se, *last_nnz);
719
720     OPEN_READER(re, &s->gb);
721     if (*EOBRUN) {
722         (*EOBRUN)--;
723     } else {
724         for (; ; i++) {
725             UPDATE_CACHE(re, &s->gb);
726             GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
727
728             if (code & 0xF) {
729                 run = ((unsigned) code) >> 4;
730                 UPDATE_CACHE(re, &s->gb);
731                 val = SHOW_UBITS(re, &s->gb, 1);
732                 LAST_SKIP_BITS(re, &s->gb, 1);
733                 ZERO_RUN;
734                 j = s->scantable.permutated[i];
735                 val--;
736                 block[j] = ((quant_matrix[j]^val) - val) << Al;
737                 if (i == se) {
738                     if (i > *last_nnz)
739                         *last_nnz = i;
740                     CLOSE_READER(re, &s->gb);
741                     return 0;
742                 }
743             } else {
744                 run = ((unsigned) code) >> 4;
745                 if (run == 0xF) {
746                     ZERO_RUN;
747                 } else {
748                     val = run;
749                     run = (1 << run);
750                     if (val) {
751                         UPDATE_CACHE(re, &s->gb);
752                         run += SHOW_UBITS(re, &s->gb, val);
753                         LAST_SKIP_BITS(re, &s->gb, val);
754                     }
755                     *EOBRUN = run - 1;
756                     break;
757                 }
758             }
759         }
760
761         if (i > *last_nnz)
762             *last_nnz = i;
763     }
764
765     for (; i <= last; i++) {
766         j = s->scantable.permutated[i];
767         if (block[j])
768             REFINE_BIT(j)
769     }
770     CLOSE_READER(re, &s->gb);
771
772     return 0;
773 }
774 #undef REFINE_BIT
775 #undef ZERO_RUN
776
777 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
778 {
779     int i;
780     int reset = 0;
781
782     if (s->restart_interval) {
783         s->restart_count--;
784         if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
785             align_get_bits(&s->gb);
786             for (i = 0; i < nb_components; i++) /* reset dc */
787                 s->last_dc[i] = (4 << s->bits);
788         }
789
790         i = 8 + ((-get_bits_count(&s->gb)) & 7);
791         /* skip RSTn */
792         if (s->restart_count == 0) {
793             if(   show_bits(&s->gb, i) == (1 << i) - 1
794                || show_bits(&s->gb, i) == 0xFF) {
795                 int pos = get_bits_count(&s->gb);
796                 align_get_bits(&s->gb);
797                 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
798                     skip_bits(&s->gb, 8);
799                 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
800                     for (i = 0; i < nb_components; i++) /* reset dc */
801                         s->last_dc[i] = (4 << s->bits);
802                     reset = 1;
803                 } else
804                     skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
805             }
806         }
807     }
808     return reset;
809 }
810
811 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
812 {
813     int i, mb_x, mb_y;
814     uint16_t (*buffer)[4];
815     int left[4], top[4], topleft[4];
816     const int linesize = s->linesize[0];
817     const int mask     = ((1 << s->bits) - 1) << point_transform;
818     int resync_mb_y = 0;
819     int resync_mb_x = 0;
820
821     if (s->nb_components != 3 && s->nb_components != 4)
822         return AVERROR_INVALIDDATA;
823     if (s->v_max != 1 || s->h_max != 1 || !s->lossless)
824         return AVERROR_INVALIDDATA;
825
826
827     s->restart_count = s->restart_interval;
828
829     av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
830                    (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
831     buffer = s->ljpeg_buffer;
832
833     for (i = 0; i < 4; i++)
834         buffer[0][i] = 1 << (s->bits - 1);
835
836     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
837         uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
838
839         if (s->interlaced && s->bottom_field)
840             ptr += linesize >> 1;
841
842         for (i = 0; i < 4; i++)
843             top[i] = left[i] = topleft[i] = buffer[0][i];
844
845         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
846             int modified_predictor = predictor;
847
848             if (s->restart_interval && !s->restart_count){
849                 s->restart_count = s->restart_interval;
850                 resync_mb_x = mb_x;
851                 resync_mb_y = mb_y;
852                 for(i=0; i<4; i++)
853                     top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
854             }
855             if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
856                 modified_predictor = 1;
857
858             for (i=0;i<nb_components;i++) {
859                 int pred, dc;
860
861                 topleft[i] = top[i];
862                 top[i]     = buffer[mb_x][i];
863
864                 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
865
866                 dc = mjpeg_decode_dc(s, s->dc_index[i]);
867                 if(dc == 0xFFFFF)
868                     return -1;
869
870                 left[i] = buffer[mb_x][i] =
871                     mask & (pred + (dc << point_transform));
872             }
873
874             if (s->restart_interval && !--s->restart_count) {
875                 align_get_bits(&s->gb);
876                 skip_bits(&s->gb, 16); /* skip RSTn */
877             }
878         }
879         if (s->nb_components == 4) {
880             for(i=0; i<nb_components; i++) {
881                 int c= s->comp_index[i];
882                 if (s->bits <= 8) {
883                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
884                         ptr[4*mb_x+3-c] = buffer[mb_x][i];
885                     }
886                 } else if(s->bits == 9) {
887                     return AVERROR_PATCHWELCOME;
888                 } else {
889                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
890                         ((uint16_t*)ptr)[4*mb_x+c] = buffer[mb_x][i];
891                     }
892                 }
893             }
894         } else if (s->rct) {
895             for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
896                 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
897                 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
898                 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
899             }
900         } else if (s->pegasus_rct) {
901             for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
902                 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
903                 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
904                 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
905             }
906         } else {
907             for(i=0; i<nb_components; i++) {
908                 int c= s->comp_index[i];
909                 if (s->bits <= 8) {
910                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
911                         ptr[3*mb_x+2-c] = buffer[mb_x][i];
912                     }
913                 } else if(s->bits == 9) {
914                     return AVERROR_PATCHWELCOME;
915                 } else {
916                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
917                         ((uint16_t*)ptr)[3*mb_x+2-c] = buffer[mb_x][i];
918                     }
919                 }
920             }
921         }
922     }
923     return 0;
924 }
925
926 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
927                                  int point_transform, int nb_components)
928 {
929     int i, mb_x, mb_y, mask;
930     int bits= (s->bits+7)&~7;
931     int resync_mb_y = 0;
932     int resync_mb_x = 0;
933
934     point_transform += bits - s->bits;
935     mask = ((1 << s->bits) - 1) << point_transform;
936
937     av_assert0(nb_components>=1 && nb_components<=4);
938
939     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
940         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
941             if (s->restart_interval && !s->restart_count){
942                 s->restart_count = s->restart_interval;
943                 resync_mb_x = mb_x;
944                 resync_mb_y = mb_y;
945             }
946
947             if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
948                 int toprow  = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
949                 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
950                 for (i = 0; i < nb_components; i++) {
951                     uint8_t *ptr;
952                     uint16_t *ptr16;
953                     int n, h, v, x, y, c, j, linesize;
954                     n = s->nb_blocks[i];
955                     c = s->comp_index[i];
956                     h = s->h_scount[i];
957                     v = s->v_scount[i];
958                     x = 0;
959                     y = 0;
960                     linesize= s->linesize[c];
961
962                     if(bits>8) linesize /= 2;
963
964                     for(j=0; j<n; j++) {
965                         int pred, dc;
966
967                         dc = mjpeg_decode_dc(s, s->dc_index[i]);
968                         if(dc == 0xFFFFF)
969                             return -1;
970                         if(bits<=8){
971                         ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
972                         if(y==0 && toprow){
973                             if(x==0 && leftcol){
974                                 pred= 1 << (bits - 1);
975                             }else{
976                                 pred= ptr[-1];
977                             }
978                         }else{
979                             if(x==0 && leftcol){
980                                 pred= ptr[-linesize];
981                             }else{
982                                 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
983                             }
984                         }
985
986                         if (s->interlaced && s->bottom_field)
987                             ptr += linesize >> 1;
988                         pred &= mask;
989                         *ptr= pred + (dc << point_transform);
990                         }else{
991                             ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
992                             if(y==0 && toprow){
993                                 if(x==0 && leftcol){
994                                     pred= 1 << (bits - 1);
995                                 }else{
996                                     pred= ptr16[-1];
997                                 }
998                             }else{
999                                 if(x==0 && leftcol){
1000                                     pred= ptr16[-linesize];
1001                                 }else{
1002                                     PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1003                                 }
1004                             }
1005
1006                             if (s->interlaced && s->bottom_field)
1007                                 ptr16 += linesize >> 1;
1008                             pred &= mask;
1009                             *ptr16= pred + (dc << point_transform);
1010                         }
1011                         if (++x == h) {
1012                             x = 0;
1013                             y++;
1014                         }
1015                     }
1016                 }
1017             } else {
1018                 for (i = 0; i < nb_components; i++) {
1019                     uint8_t *ptr;
1020                     uint16_t *ptr16;
1021                     int n, h, v, x, y, c, j, linesize, dc;
1022                     n        = s->nb_blocks[i];
1023                     c        = s->comp_index[i];
1024                     h        = s->h_scount[i];
1025                     v        = s->v_scount[i];
1026                     x        = 0;
1027                     y        = 0;
1028                     linesize = s->linesize[c];
1029
1030                     if(bits>8) linesize /= 2;
1031
1032                     for (j = 0; j < n; j++) {
1033                         int pred;
1034
1035                         dc = mjpeg_decode_dc(s, s->dc_index[i]);
1036                         if(dc == 0xFFFFF)
1037                             return -1;
1038                         if(bits<=8){
1039                             ptr = s->picture_ptr->data[c] +
1040                               (linesize * (v * mb_y + y)) +
1041                               (h * mb_x + x); //FIXME optimize this crap
1042                             PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
1043
1044                             pred &= mask;
1045                             *ptr = pred + (dc << point_transform);
1046                         }else{
1047                             ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1048                             PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1049
1050                             pred &= mask;
1051                             *ptr16= pred + (dc << point_transform);
1052                         }
1053
1054                         if (++x == h) {
1055                             x = 0;
1056                             y++;
1057                         }
1058                     }
1059                 }
1060             }
1061             if (s->restart_interval && !--s->restart_count) {
1062                 align_get_bits(&s->gb);
1063                 skip_bits(&s->gb, 16); /* skip RSTn */
1064             }
1065         }
1066     }
1067     return 0;
1068 }
1069
1070 static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
1071                                               uint8_t *dst, const uint8_t *src,
1072                                               int linesize, int lowres)
1073 {
1074     switch (lowres) {
1075     case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1076         break;
1077     case 1: copy_block4(dst, src, linesize, linesize, 4);
1078         break;
1079     case 2: copy_block2(dst, src, linesize, linesize, 2);
1080         break;
1081     case 3: *dst = *src;
1082         break;
1083     }
1084 }
1085
1086 static void shift_output(MJpegDecodeContext *s, uint8_t *ptr, int linesize)
1087 {
1088     int block_x, block_y;
1089     int size = 8 >> s->avctx->lowres;
1090     if (s->bits > 8) {
1091         for (block_y=0; block_y<size; block_y++)
1092             for (block_x=0; block_x<size; block_x++)
1093                 *(uint16_t*)(ptr + 2*block_x + block_y*linesize) <<= 16 - s->bits;
1094     } else {
1095         for (block_y=0; block_y<size; block_y++)
1096             for (block_x=0; block_x<size; block_x++)
1097                 *(ptr + block_x + block_y*linesize) <<= 8 - s->bits;
1098     }
1099 }
1100
1101 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1102                              int Al, const uint8_t *mb_bitmask,
1103                              const AVFrame *reference)
1104 {
1105     int i, mb_x, mb_y;
1106     uint8_t *data[MAX_COMPONENTS];
1107     const uint8_t *reference_data[MAX_COMPONENTS];
1108     int linesize[MAX_COMPONENTS];
1109     GetBitContext mb_bitmask_gb;
1110     int bytes_per_pixel = 1 + (s->bits > 8);
1111
1112     if (mb_bitmask)
1113         init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1114
1115     s->restart_count = 0;
1116
1117     for (i = 0; i < nb_components; i++) {
1118         int c   = s->comp_index[i];
1119         data[c] = s->picture_ptr->data[c];
1120         reference_data[c] = reference ? reference->data[c] : NULL;
1121         linesize[c] = s->linesize[c];
1122         s->coefs_finished[c] |= 1;
1123     }
1124
1125     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1126         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1127             const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1128
1129             if (s->restart_interval && !s->restart_count)
1130                 s->restart_count = s->restart_interval;
1131
1132             if (get_bits_left(&s->gb) < 0) {
1133                 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1134                        -get_bits_left(&s->gb));
1135                 return AVERROR_INVALIDDATA;
1136             }
1137             for (i = 0; i < nb_components; i++) {
1138                 uint8_t *ptr;
1139                 int n, h, v, x, y, c, j;
1140                 int block_offset;
1141                 n = s->nb_blocks[i];
1142                 c = s->comp_index[i];
1143                 h = s->h_scount[i];
1144                 v = s->v_scount[i];
1145                 x = 0;
1146                 y = 0;
1147                 for (j = 0; j < n; j++) {
1148                     block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1149                                      (h * mb_x + x) * 8 * bytes_per_pixel) >> s->avctx->lowres);
1150
1151                     if (s->interlaced && s->bottom_field)
1152                         block_offset += linesize[c] >> 1;
1153                     ptr = data[c] + block_offset;
1154                     if (!s->progressive) {
1155                         if (copy_mb)
1156                             mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1157                                              linesize[c], s->avctx->lowres);
1158
1159                         else {
1160                             s->dsp.clear_block(s->block);
1161                             if (decode_block(s, s->block, i,
1162                                              s->dc_index[i], s->ac_index[i],
1163                                              s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1164                                 av_log(s->avctx, AV_LOG_ERROR,
1165                                        "error y=%d x=%d\n", mb_y, mb_x);
1166                                 return AVERROR_INVALIDDATA;
1167                             }
1168                             s->dsp.idct_put(ptr, linesize[c], s->block);
1169                             if (s->bits & 7)
1170                                 shift_output(s, ptr, linesize[c]);
1171                         }
1172                     } else {
1173                         int block_idx  = s->block_stride[c] * (v * mb_y + y) +
1174                                          (h * mb_x + x);
1175                         int16_t *block = s->blocks[c][block_idx];
1176                         if (Ah)
1177                             block[0] += get_bits1(&s->gb) *
1178                                         s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1179                         else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1180                                                        s->quant_matrixes[s->quant_sindex[i]],
1181                                                        Al) < 0) {
1182                             av_log(s->avctx, AV_LOG_ERROR,
1183                                    "error y=%d x=%d\n", mb_y, mb_x);
1184                             return AVERROR_INVALIDDATA;
1185                         }
1186                     }
1187                     av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1188                     av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1189                             mb_x, mb_y, x, y, c, s->bottom_field,
1190                             (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1191                     if (++x == h) {
1192                         x = 0;
1193                         y++;
1194                     }
1195                 }
1196             }
1197
1198             handle_rstn(s, nb_components);
1199         }
1200     }
1201     return 0;
1202 }
1203
1204 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1205                                             int se, int Ah, int Al)
1206 {
1207     int mb_x, mb_y;
1208     int EOBRUN = 0;
1209     int c = s->comp_index[0];
1210     uint8_t *data = s->picture_ptr->data[c];
1211     int linesize  = s->linesize[c];
1212     int last_scan = 0;
1213     int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1214     int bytes_per_pixel = 1 + (s->bits > 8);
1215
1216     av_assert0(ss>=0 && Ah>=0 && Al>=0);
1217     if (se < ss || se > 63) {
1218         av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1219         return AVERROR_INVALIDDATA;
1220     }
1221
1222     if (!Al) {
1223         s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1224         last_scan = !~s->coefs_finished[c];
1225     }
1226
1227     if (s->interlaced && s->bottom_field)
1228         data += linesize >> 1;
1229
1230     s->restart_count = 0;
1231
1232     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1233         uint8_t *ptr     = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1234         int block_idx    = mb_y * s->block_stride[c];
1235         int16_t (*block)[64] = &s->blocks[c][block_idx];
1236         uint8_t *last_nnz    = &s->last_nnz[c][block_idx];
1237         for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1238                 int ret;
1239                 if (s->restart_interval && !s->restart_count)
1240                     s->restart_count = s->restart_interval;
1241
1242                 if (Ah)
1243                     ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1244                                                   quant_matrix, ss, se, Al, &EOBRUN);
1245                 else
1246                     ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1247                                                    quant_matrix, ss, se, Al, &EOBRUN);
1248                 if (ret < 0) {
1249                     av_log(s->avctx, AV_LOG_ERROR,
1250                            "error y=%d x=%d\n", mb_y, mb_x);
1251                     return AVERROR_INVALIDDATA;
1252                 }
1253
1254             if (last_scan) {
1255                     s->dsp.idct_put(ptr, linesize, *block);
1256                     if (s->bits & 7)
1257                         shift_output(s, ptr, linesize);
1258                     ptr += bytes_per_pixel*8 >> s->avctx->lowres;
1259             }
1260             if (handle_rstn(s, 0))
1261                 EOBRUN = 0;
1262         }
1263     }
1264     return 0;
1265 }
1266
1267 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1268                         const AVFrame *reference)
1269 {
1270     int len, nb_components, i, h, v, predictor, point_transform;
1271     int index, id, ret;
1272     const int block_size = s->lossless ? 1 : 8;
1273     int ilv, prev_shift;
1274
1275     if (!s->got_picture) {
1276         av_log(s->avctx, AV_LOG_WARNING,
1277                 "Can not process SOS before SOF, skipping\n");
1278         return -1;
1279     }
1280
1281     av_assert0(s->picture_ptr->data[0]);
1282     /* XXX: verify len field validity */
1283     len = get_bits(&s->gb, 16);
1284     nb_components = get_bits(&s->gb, 8);
1285     if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1286         av_log(s->avctx, AV_LOG_ERROR,
1287                "decode_sos: nb_components (%d) unsupported\n", nb_components);
1288         return AVERROR_PATCHWELCOME;
1289     }
1290     if (len != 6 + 2 * nb_components) {
1291         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1292         return AVERROR_INVALIDDATA;
1293     }
1294     for (i = 0; i < nb_components; i++) {
1295         id = get_bits(&s->gb, 8) - 1;
1296         av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1297         /* find component index */
1298         for (index = 0; index < s->nb_components; index++)
1299             if (id == s->component_id[index])
1300                 break;
1301         if (index == s->nb_components) {
1302             av_log(s->avctx, AV_LOG_ERROR,
1303                    "decode_sos: index(%d) out of components\n", index);
1304             return AVERROR_INVALIDDATA;
1305         }
1306         /* Metasoft MJPEG codec has Cb and Cr swapped */
1307         if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1308             && nb_components == 3 && s->nb_components == 3 && i)
1309             index = 3 - i;
1310
1311         s->quant_sindex[i] = s->quant_index[index];
1312         s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1313         s->h_scount[i]  = s->h_count[index];
1314         s->v_scount[i]  = s->v_count[index];
1315
1316         if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1317             index = (i+2)%3;
1318         if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1319             index = (index+2)%3;
1320
1321         s->comp_index[i] = index;
1322
1323         s->dc_index[i] = get_bits(&s->gb, 4);
1324         s->ac_index[i] = get_bits(&s->gb, 4);
1325
1326         if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
1327             s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1328             goto out_of_range;
1329         if (!s->vlcs[0][s->dc_index[i]].table || !(s->progressive ? s->vlcs[2][s->ac_index[0]].table : s->vlcs[1][s->ac_index[i]].table))
1330             goto out_of_range;
1331     }
1332
1333     predictor = get_bits(&s->gb, 8);       /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1334     ilv = get_bits(&s->gb, 8);             /* JPEG Se / JPEG-LS ILV */
1335     if(s->avctx->codec_tag != AV_RL32("CJPG")){
1336         prev_shift      = get_bits(&s->gb, 4); /* Ah */
1337         point_transform = get_bits(&s->gb, 4); /* Al */
1338     }else
1339         prev_shift = point_transform = 0;
1340
1341     if (nb_components > 1) {
1342         /* interleaved stream */
1343         s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
1344         s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1345     } else if (!s->ls) { /* skip this for JPEG-LS */
1346         h = s->h_max / s->h_scount[0];
1347         v = s->v_max / s->v_scount[0];
1348         s->mb_width     = (s->width  + h * block_size - 1) / (h * block_size);
1349         s->mb_height    = (s->height + v * block_size - 1) / (v * block_size);
1350         s->nb_blocks[0] = 1;
1351         s->h_scount[0]  = 1;
1352         s->v_scount[0]  = 1;
1353     }
1354
1355     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1356         av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1357                s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1358                predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1359                s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1360
1361
1362     /* mjpeg-b can have padding bytes between sos and image data, skip them */
1363     for (i = s->mjpb_skiptosod; i > 0; i--)
1364         skip_bits(&s->gb, 8);
1365
1366 next_field:
1367     for (i = 0; i < nb_components; i++)
1368         s->last_dc[i] = (4 << s->bits);
1369
1370     if (s->lossless) {
1371         av_assert0(s->picture_ptr == s->picture);
1372         if (CONFIG_JPEGLS_DECODER && s->ls) {
1373 //            for () {
1374 //            reset_ls_coding_parameters(s, 0);
1375
1376             if ((ret = ff_jpegls_decode_picture(s, predictor,
1377                                                 point_transform, ilv)) < 0)
1378                 return ret;
1379         } else {
1380             if (s->rgb) {
1381                 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1382                     return ret;
1383             } else {
1384                 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1385                                                  point_transform,
1386                                                  nb_components)) < 0)
1387                     return ret;
1388             }
1389         }
1390     } else {
1391         if (s->progressive && predictor) {
1392             av_assert0(s->picture_ptr == s->picture);
1393             if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1394                                                         ilv, prev_shift,
1395                                                         point_transform)) < 0)
1396                 return ret;
1397         } else {
1398             if ((ret = mjpeg_decode_scan(s, nb_components,
1399                                          prev_shift, point_transform,
1400                                          mb_bitmask, reference)) < 0)
1401                 return ret;
1402         }
1403     }
1404
1405     if (s->interlaced &&
1406         get_bits_left(&s->gb) > 32 &&
1407         show_bits(&s->gb, 8) == 0xFF) {
1408         GetBitContext bak = s->gb;
1409         align_get_bits(&bak);
1410         if (show_bits(&bak, 16) == 0xFFD1) {
1411             av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1412             s->gb = bak;
1413             skip_bits(&s->gb, 16);
1414             s->bottom_field ^= 1;
1415
1416             goto next_field;
1417         }
1418     }
1419
1420     emms_c();
1421     return 0;
1422  out_of_range:
1423     av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1424     return AVERROR_INVALIDDATA;
1425 }
1426
1427 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1428 {
1429     if (get_bits(&s->gb, 16) != 4)
1430         return AVERROR_INVALIDDATA;
1431     s->restart_interval = get_bits(&s->gb, 16);
1432     s->restart_count    = 0;
1433     av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1434            s->restart_interval);
1435
1436     return 0;
1437 }
1438
1439 static int mjpeg_decode_app(MJpegDecodeContext *s)
1440 {
1441     int len, id, i;
1442
1443     len = get_bits(&s->gb, 16);
1444     if (len < 6)
1445         return AVERROR_INVALIDDATA;
1446     if (8 * len > get_bits_left(&s->gb))
1447         return AVERROR_INVALIDDATA;
1448
1449     id   = get_bits_long(&s->gb, 32);
1450     len -= 6;
1451
1452     if (s->avctx->debug & FF_DEBUG_STARTCODE)
1453         av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X len=%d\n", id, len);
1454
1455     /* Buggy AVID, it puts EOI only at every 10th frame. */
1456     /* Also, this fourcc is used by non-avid files too, it holds some
1457        information, but it's always present in AVID-created files. */
1458     if (id == AV_RB32("AVI1")) {
1459         /* structure:
1460             4bytes      AVI1
1461             1bytes      polarity
1462             1bytes      always zero
1463             4bytes      field_size
1464             4bytes      field_size_less_padding
1465         */
1466             s->buggy_avid = 1;
1467         i = get_bits(&s->gb, 8); len--;
1468         av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1469 #if 0
1470         skip_bits(&s->gb, 8);
1471         skip_bits(&s->gb, 32);
1472         skip_bits(&s->gb, 32);
1473         len -= 10;
1474 #endif
1475         goto out;
1476     }
1477
1478 //    len -= 2;
1479
1480     if (id == AV_RB32("JFIF")) {
1481         int t_w, t_h, v1, v2;
1482         skip_bits(&s->gb, 8); /* the trailing zero-byte */
1483         v1 = get_bits(&s->gb, 8);
1484         v2 = get_bits(&s->gb, 8);
1485         skip_bits(&s->gb, 8);
1486
1487         s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1488         s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1489
1490         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1491             av_log(s->avctx, AV_LOG_INFO,
1492                    "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1493                    v1, v2,
1494                    s->avctx->sample_aspect_ratio.num,
1495                    s->avctx->sample_aspect_ratio.den);
1496
1497         t_w = get_bits(&s->gb, 8);
1498         t_h = get_bits(&s->gb, 8);
1499         if (t_w && t_h) {
1500             /* skip thumbnail */
1501             if (len -10 - (t_w * t_h * 3) > 0)
1502                 len -= t_w * t_h * 3;
1503         }
1504         len -= 10;
1505         goto out;
1506     }
1507
1508     if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1509         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1510             av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1511         skip_bits(&s->gb, 16); /* version */
1512         skip_bits(&s->gb, 16); /* flags0 */
1513         skip_bits(&s->gb, 16); /* flags1 */
1514         skip_bits(&s->gb,  8); /* transform */
1515         len -= 7;
1516         goto out;
1517     }
1518
1519     if (id == AV_RB32("LJIF")) {
1520         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1521             av_log(s->avctx, AV_LOG_INFO,
1522                    "Pegasus lossless jpeg header found\n");
1523         skip_bits(&s->gb, 16); /* version ? */
1524         skip_bits(&s->gb, 16); /* unknown always 0? */
1525         skip_bits(&s->gb, 16); /* unknown always 0? */
1526         skip_bits(&s->gb, 16); /* unknown always 0? */
1527         switch (i=get_bits(&s->gb, 8)) {
1528         case 1:
1529             s->rgb         = 1;
1530             s->pegasus_rct = 0;
1531             break;
1532         case 2:
1533             s->rgb         = 1;
1534             s->pegasus_rct = 1;
1535             break;
1536         default:
1537             av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);
1538         }
1539         len -= 9;
1540         goto out;
1541     }
1542     if (id == AV_RL32("colr") && len > 0) {
1543         s->colr = get_bits(&s->gb, 8);
1544         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1545             av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1546         len --;
1547         goto out;
1548     }
1549     if (id == AV_RL32("xfrm") && len > 0) {
1550         s->xfrm = get_bits(&s->gb, 8);
1551         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1552             av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1553         len --;
1554         goto out;
1555     }
1556
1557     /* EXIF metadata */
1558     if (s->start_code == APP1 && id == AV_RB32("Exif") && len >= 2) {
1559         GetByteContext gbytes;
1560         int ret, le, ifd_offset, bytes_read;
1561         const uint8_t *aligned;
1562
1563         skip_bits(&s->gb, 16); // skip padding
1564         len -= 2;
1565
1566         // init byte wise reading
1567         aligned = align_get_bits(&s->gb);
1568         bytestream2_init(&gbytes, aligned, len);
1569
1570         // read TIFF header
1571         ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
1572         if (ret) {
1573             av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
1574             return ret;
1575         }
1576
1577         bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
1578
1579         // read 0th IFD and store the metadata
1580         // (return values > 0 indicate the presence of subimage metadata)
1581         ret = ff_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
1582         if (ret < 0) {
1583             av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
1584             return ret;
1585         }
1586
1587         bytes_read = bytestream2_tell(&gbytes);
1588         skip_bits(&s->gb, bytes_read << 3);
1589         len -= bytes_read;
1590
1591         goto out;
1592     }
1593
1594     /* Apple MJPEG-A */
1595     if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1596         id   = get_bits_long(&s->gb, 32);
1597         len -= 4;
1598         /* Apple MJPEG-A */
1599         if (id == AV_RB32("mjpg")) {
1600 #if 0
1601             skip_bits(&s->gb, 32); /* field size */
1602             skip_bits(&s->gb, 32); /* pad field size */
1603             skip_bits(&s->gb, 32); /* next off */
1604             skip_bits(&s->gb, 32); /* quant off */
1605             skip_bits(&s->gb, 32); /* huff off */
1606             skip_bits(&s->gb, 32); /* image off */
1607             skip_bits(&s->gb, 32); /* scan off */
1608             skip_bits(&s->gb, 32); /* data off */
1609 #endif
1610             if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1611                 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1612         }
1613     }
1614
1615 out:
1616     /* slow but needed for extreme adobe jpegs */
1617     if (len < 0)
1618         av_log(s->avctx, AV_LOG_ERROR,
1619                "mjpeg: error, decode_app parser read over the end\n");
1620     while (--len > 0)
1621         skip_bits(&s->gb, 8);
1622
1623     return 0;
1624 }
1625
1626 static int mjpeg_decode_com(MJpegDecodeContext *s)
1627 {
1628     int len = get_bits(&s->gb, 16);
1629     if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1630         char *cbuf = av_malloc(len - 1);
1631         if (cbuf) {
1632             int i;
1633             for (i = 0; i < len - 2; i++)
1634                 cbuf[i] = get_bits(&s->gb, 8);
1635             if (i > 0 && cbuf[i - 1] == '\n')
1636                 cbuf[i - 1] = 0;
1637             else
1638                 cbuf[i] = 0;
1639
1640             if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1641                 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1642
1643             /* buggy avid, it puts EOI only at every 10th frame */
1644             if (!strncmp(cbuf, "AVID", 4)) {
1645                 s->buggy_avid = 1;
1646                 if (len > 14 && cbuf[12] == 1) /* 1 - NTSC, 2 - PAL */
1647                     s->interlace_polarity = 1;
1648             } else if (!strcmp(cbuf, "CS=ITU601"))
1649                 s->cs_itu601 = 1;
1650             else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1651                      (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1652                 s->flipped = 1;
1653
1654             av_free(cbuf);
1655         }
1656     }
1657
1658     return 0;
1659 }
1660
1661 /* return the 8 bit start code value and update the search
1662    state. Return -1 if no start code found */
1663 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1664 {
1665     const uint8_t *buf_ptr;
1666     unsigned int v, v2;
1667     int val;
1668     int skipped = 0;
1669
1670     buf_ptr = *pbuf_ptr;
1671     while (buf_end - buf_ptr > 1) {
1672         v  = *buf_ptr++;
1673         v2 = *buf_ptr;
1674         if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1675             val = *buf_ptr++;
1676             goto found;
1677         }
1678         skipped++;
1679     }
1680     buf_ptr = buf_end;
1681     val = -1;
1682 found:
1683     av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1684     *pbuf_ptr = buf_ptr;
1685     return val;
1686 }
1687
1688 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1689                          const uint8_t **buf_ptr, const uint8_t *buf_end,
1690                          const uint8_t **unescaped_buf_ptr,
1691                          int *unescaped_buf_size)
1692 {
1693     int start_code;
1694     start_code = find_marker(buf_ptr, buf_end);
1695
1696     av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1697     if (!s->buffer)
1698         return AVERROR(ENOMEM);
1699
1700     /* unescape buffer of SOS, use special treatment for JPEG-LS */
1701     if (start_code == SOS && !s->ls) {
1702         const uint8_t *src = *buf_ptr;
1703         uint8_t *dst = s->buffer;
1704
1705         while (src < buf_end) {
1706             uint8_t x = *(src++);
1707
1708             *(dst++) = x;
1709             if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1710                 if (x == 0xff) {
1711                     while (src < buf_end && x == 0xff)
1712                         x = *(src++);
1713
1714                     if (x >= 0xd0 && x <= 0xd7)
1715                         *(dst++) = x;
1716                     else if (x)
1717                         break;
1718                 }
1719             }
1720         }
1721         *unescaped_buf_ptr  = s->buffer;
1722         *unescaped_buf_size = dst - s->buffer;
1723         memset(s->buffer + *unescaped_buf_size, 0,
1724                FF_INPUT_BUFFER_PADDING_SIZE);
1725
1726         av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1727                (buf_end - *buf_ptr) - (dst - s->buffer));
1728     } else if (start_code == SOS && s->ls) {
1729         const uint8_t *src = *buf_ptr;
1730         uint8_t *dst  = s->buffer;
1731         int bit_count = 0;
1732         int t = 0, b = 0;
1733         PutBitContext pb;
1734
1735         /* find marker */
1736         while (src + t < buf_end) {
1737             uint8_t x = src[t++];
1738             if (x == 0xff) {
1739                 while ((src + t < buf_end) && x == 0xff)
1740                     x = src[t++];
1741                 if (x & 0x80) {
1742                     t -= FFMIN(2, t);
1743                     break;
1744                 }
1745             }
1746         }
1747         bit_count = t * 8;
1748         init_put_bits(&pb, dst, t);
1749
1750         /* unescape bitstream */
1751         while (b < t) {
1752             uint8_t x = src[b++];
1753             put_bits(&pb, 8, x);
1754             if (x == 0xFF) {
1755                 x = src[b++];
1756                 put_bits(&pb, 7, x);
1757                 bit_count--;
1758             }
1759         }
1760         flush_put_bits(&pb);
1761
1762         *unescaped_buf_ptr  = dst;
1763         *unescaped_buf_size = (bit_count + 7) >> 3;
1764         memset(s->buffer + *unescaped_buf_size, 0,
1765                FF_INPUT_BUFFER_PADDING_SIZE);
1766     } else {
1767         *unescaped_buf_ptr  = *buf_ptr;
1768         *unescaped_buf_size = buf_end - *buf_ptr;
1769     }
1770
1771     return start_code;
1772 }
1773
1774 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1775                           AVPacket *avpkt)
1776 {
1777     AVFrame     *frame = data;
1778     const uint8_t *buf = avpkt->data;
1779     int buf_size       = avpkt->size;
1780     MJpegDecodeContext *s = avctx->priv_data;
1781     const uint8_t *buf_end, *buf_ptr;
1782     const uint8_t *unescaped_buf_ptr;
1783     int hshift, vshift;
1784     int unescaped_buf_size;
1785     int start_code;
1786     int i, index;
1787     int ret = 0;
1788
1789     av_dict_free(&s->exif_metadata);
1790
1791     buf_ptr = buf;
1792     buf_end = buf + buf_size;
1793     while (buf_ptr < buf_end) {
1794         /* find start next marker */
1795         start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1796                                           &unescaped_buf_ptr,
1797                                           &unescaped_buf_size);
1798         /* EOF */
1799         if (start_code < 0) {
1800             break;
1801         } else if (unescaped_buf_size > INT_MAX / 8) {
1802             av_log(avctx, AV_LOG_ERROR,
1803                    "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1804                    start_code, unescaped_buf_size, buf_size);
1805             return AVERROR_INVALIDDATA;
1806         }
1807         av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1808                start_code, buf_end - buf_ptr);
1809
1810         ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1811
1812         if (ret < 0) {
1813             av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1814             goto fail;
1815         }
1816
1817         s->start_code = start_code;
1818         if (s->avctx->debug & FF_DEBUG_STARTCODE)
1819             av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1820
1821         /* process markers */
1822         if (start_code >= 0xd0 && start_code <= 0xd7)
1823             av_log(avctx, AV_LOG_DEBUG,
1824                    "restart marker: %d\n", start_code & 0x0f);
1825             /* APP fields */
1826         else if (start_code >= APP0 && start_code <= APP15)
1827             mjpeg_decode_app(s);
1828             /* Comment */
1829         else if (start_code == COM)
1830             mjpeg_decode_com(s);
1831
1832         ret = -1;
1833
1834         if (!CONFIG_JPEGLS_DECODER &&
1835             (start_code == SOF48 || start_code == LSE)) {
1836             av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1837             return AVERROR(ENOSYS);
1838         }
1839
1840         switch (start_code) {
1841         case SOI:
1842             s->restart_interval = 0;
1843             s->restart_count    = 0;
1844             /* nothing to do on SOI */
1845             break;
1846         case DQT:
1847             ff_mjpeg_decode_dqt(s);
1848             break;
1849         case DHT:
1850             if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1851                 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1852                 goto fail;
1853             }
1854             break;
1855         case SOF0:
1856         case SOF1:
1857             s->lossless    = 0;
1858             s->ls          = 0;
1859             s->progressive = 0;
1860             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1861                 goto fail;
1862             break;
1863         case SOF2:
1864             s->lossless    = 0;
1865             s->ls          = 0;
1866             s->progressive = 1;
1867             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1868                 goto fail;
1869             break;
1870         case SOF3:
1871             s->lossless    = 1;
1872             s->ls          = 0;
1873             s->progressive = 0;
1874             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1875                 goto fail;
1876             break;
1877         case SOF48:
1878             s->lossless    = 1;
1879             s->ls          = 1;
1880             s->progressive = 0;
1881             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1882                 goto fail;
1883             break;
1884         case LSE:
1885             if (!CONFIG_JPEGLS_DECODER ||
1886                 (ret = ff_jpegls_decode_lse(s)) < 0)
1887                 goto fail;
1888             break;
1889         case EOI:
1890 eoi_parser:
1891             s->cur_scan = 0;
1892             if (!s->got_picture) {
1893                 av_log(avctx, AV_LOG_WARNING,
1894                        "Found EOI before any SOF, ignoring\n");
1895                 break;
1896             }
1897             if (s->interlaced) {
1898                 s->bottom_field ^= 1;
1899                 /* if not bottom field, do not output image yet */
1900                 if (s->bottom_field == !s->interlace_polarity)
1901                     break;
1902             }
1903             if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
1904                 return ret;
1905             *got_frame = 1;
1906             s->got_picture = 0;
1907
1908             if (!s->lossless) {
1909                 int qp = FFMAX3(s->qscale[0],
1910                                 s->qscale[1],
1911                                 s->qscale[2]);
1912                 int qpw = (s->width + 15) / 16;
1913                 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1914                 if (qp_table_buf) {
1915                     memset(qp_table_buf->data, qp, qpw);
1916                     av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1917                 }
1918
1919                 if(avctx->debug & FF_DEBUG_QP)
1920                     av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1921             }
1922
1923             goto the_end;
1924         case SOS:
1925             s->cur_scan++;
1926             if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1927                 (avctx->err_recognition & AV_EF_EXPLODE))
1928                 goto fail;
1929             break;
1930         case DRI:
1931             mjpeg_decode_dri(s);
1932             break;
1933         case SOF5:
1934         case SOF6:
1935         case SOF7:
1936         case SOF9:
1937         case SOF10:
1938         case SOF11:
1939         case SOF13:
1940         case SOF14:
1941         case SOF15:
1942         case JPG:
1943             av_log(avctx, AV_LOG_ERROR,
1944                    "mjpeg: unsupported coding type (%x)\n", start_code);
1945             break;
1946         }
1947
1948         /* eof process start code */
1949         buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1950         av_log(avctx, AV_LOG_DEBUG,
1951                "marker parser used %d bytes (%d bits)\n",
1952                (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1953     }
1954     if (s->got_picture && s->cur_scan) {
1955         av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1956         goto eoi_parser;
1957     }
1958     av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1959     return AVERROR_INVALIDDATA;
1960 fail:
1961     s->got_picture = 0;
1962     return ret;
1963 the_end:
1964     if (s->upscale_h) {
1965         uint8_t *line = s->picture_ptr->data[s->upscale_h];
1966         av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1967                    avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
1968                    avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1969                    avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1970         for (i = 0; i < s->chroma_height; i++) {
1971             for (index = s->width - 1; index; index--)
1972                 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1973             line += s->linesize[s->upscale_h];
1974         }
1975     }
1976     if (s->upscale_v) {
1977         uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1978         int w;
1979         avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1980         w = s->width >> hshift;
1981         av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1982                    avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
1983                    avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1984                    avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1985         for (i = s->height - 1; i; i--) {
1986             uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1987             uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1988             if (src1 == src2) {
1989                 memcpy(dst, src1, w);
1990             } else {
1991                 for (index = 0; index < w; index++)
1992                     dst[index] = (src1[index] + src2[index]) >> 1;
1993             }
1994             dst -= s->linesize[s->upscale_v];
1995         }
1996     }
1997     if (s->flipped) {
1998         int j;
1999         avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
2000         for (index=0; index<4; index++) {
2001             uint8_t *dst = s->picture_ptr->data[index];
2002             int w = s->picture_ptr->width;
2003             int h = s->picture_ptr->height;
2004             if(index && index<3){
2005                 w = FF_CEIL_RSHIFT(w, hshift);
2006                 h = FF_CEIL_RSHIFT(h, vshift);
2007             }
2008             if(dst){
2009                 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
2010                 for (i=0; i<h/2; i++) {
2011                     for (j=0; j<w; j++)
2012                         FFSWAP(int, dst[j], dst2[j]);
2013                     dst  += s->linesize[index];
2014                     dst2 -= s->linesize[index];
2015                 }
2016             }
2017         }
2018     }
2019
2020     av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);
2021     av_dict_free(&s->exif_metadata);
2022
2023     av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
2024            buf_end - buf_ptr);
2025 //  return buf_end - buf_ptr;
2026     return buf_ptr - buf;
2027 }
2028
2029 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
2030 {
2031     MJpegDecodeContext *s = avctx->priv_data;
2032     int i, j;
2033
2034     if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
2035         av_log(avctx, AV_LOG_INFO, "Single field\n");
2036     }
2037
2038     if (s->picture) {
2039         av_frame_free(&s->picture);
2040         s->picture_ptr = NULL;
2041     } else if (s->picture_ptr)
2042         av_frame_unref(s->picture_ptr);
2043
2044     av_free(s->buffer);
2045     av_freep(&s->ljpeg_buffer);
2046     s->ljpeg_buffer_size = 0;
2047
2048     for (i = 0; i < 3; i++) {
2049         for (j = 0; j < 4; j++)
2050             ff_free_vlc(&s->vlcs[i][j]);
2051     }
2052     for (i = 0; i < MAX_COMPONENTS; i++) {
2053         av_freep(&s->blocks[i]);
2054         av_freep(&s->last_nnz[i]);
2055     }
2056     av_dict_free(&s->exif_metadata);
2057     return 0;
2058 }
2059
2060 static void decode_flush(AVCodecContext *avctx)
2061 {
2062     MJpegDecodeContext *s = avctx->priv_data;
2063     s->got_picture = 0;
2064 }
2065
2066 #if CONFIG_MJPEG_DECODER
2067 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
2068 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2069 static const AVOption options[] = {
2070     { "extern_huff", "Use external huffman table.",
2071       OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
2072     { NULL },
2073 };
2074
2075 static const AVClass mjpegdec_class = {
2076     .class_name = "MJPEG decoder",
2077     .item_name  = av_default_item_name,
2078     .option     = options,
2079     .version    = LIBAVUTIL_VERSION_INT,
2080 };
2081
2082 AVCodec ff_mjpeg_decoder = {
2083     .name           = "mjpeg",
2084     .long_name      = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
2085     .type           = AVMEDIA_TYPE_VIDEO,
2086     .id             = AV_CODEC_ID_MJPEG,
2087     .priv_data_size = sizeof(MJpegDecodeContext),
2088     .init           = ff_mjpeg_decode_init,
2089     .close          = ff_mjpeg_decode_end,
2090     .decode         = ff_mjpeg_decode_frame,
2091     .flush          = decode_flush,
2092     .capabilities   = CODEC_CAP_DR1,
2093     .max_lowres     = 3,
2094     .priv_class     = &mjpegdec_class,
2095 };
2096 #endif
2097 #if CONFIG_THP_DECODER
2098 AVCodec ff_thp_decoder = {
2099     .name           = "thp",
2100     .long_name      = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
2101     .type           = AVMEDIA_TYPE_VIDEO,
2102     .id             = AV_CODEC_ID_THP,
2103     .priv_data_size = sizeof(MJpegDecodeContext),
2104     .init           = ff_mjpeg_decode_init,
2105     .close          = ff_mjpeg_decode_end,
2106     .decode         = ff_mjpeg_decode_frame,
2107     .flush          = decode_flush,
2108     .capabilities   = CODEC_CAP_DR1,
2109     .max_lowres     = 3,
2110 };
2111 #endif