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