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