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