Use avpriv_report_missing_feature() where appropriate
[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 avpriv_report_missing_feature(s->avctx, "Pixel format 0x%x", 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 avpriv_report_missing_feature(s->avctx,
1039 "decode_sos: nb_components (%d)",
1040 nb_components);
1041 return AVERROR_PATCHWELCOME;
1042 }
1043 if (len != 6 + 2 * nb_components) {
1044 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1045 return AVERROR_INVALIDDATA;
1046 }
1047 for (i = 0; i < nb_components; i++) {
1048 id = get_bits(&s->gb, 8) - 1;
1049 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1050 /* find component index */
1051 for (index = 0; index < s->nb_components; index++)
1052 if (id == s->component_id[index])
1053 break;
1054 if (index == s->nb_components) {
1055 av_log(s->avctx, AV_LOG_ERROR,
1056 "decode_sos: index(%d) out of components\n", index);
1057 return AVERROR_INVALIDDATA;
1058 }
1059 /* Metasoft MJPEG codec has Cb and Cr swapped */
1060 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1061 && nb_components == 3 && s->nb_components == 3 && i)
1062 index = 3 - i;
1063
1064 s->comp_index[i] = index;
1065
1066 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1067 s->h_scount[i] = s->h_count[index];
1068 s->v_scount[i] = s->v_count[index];
1069
1070 s->dc_index[i] = get_bits(&s->gb, 4);
1071 s->ac_index[i] = get_bits(&s->gb, 4);
1072
1073 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1074 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1075 goto out_of_range;
1076 if (!s->vlcs[0][s->dc_index[i]].table ||
1077 !s->vlcs[1][s->ac_index[i]].table)
1078 goto out_of_range;
1079 }
1080
1081 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1082 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1083 prev_shift = get_bits(&s->gb, 4); /* Ah */
1084 point_transform = get_bits(&s->gb, 4); /* Al */
1085
1086 if (nb_components > 1) {
1087 /* interleaved stream */
1088 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1089 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1090 } else if (!s->ls) { /* skip this for JPEG-LS */
1091 h = s->h_max / s->h_scount[0];
1092 v = s->v_max / s->v_scount[0];
1093 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1094 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1095 s->nb_blocks[0] = 1;
1096 s->h_scount[0] = 1;
1097 s->v_scount[0] = 1;
1098 }
1099
1100 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1101 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n",
1102 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1103 predictor, point_transform, ilv, s->bits,
1104 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
1105
1106
1107 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1108 for (i = s->mjpb_skiptosod; i > 0; i--)
1109 skip_bits(&s->gb, 8);
1110
1111 next_field:
1112 for (i = 0; i < nb_components; i++)
1113 s->last_dc[i] = 1024;
1114
1115 if (s->lossless) {
1116 if (CONFIG_JPEGLS_DECODER && s->ls) {
1117 // for () {
1118 // reset_ls_coding_parameters(s, 0);
1119
1120 if ((ret = ff_jpegls_decode_picture(s, predictor,
1121 point_transform, ilv)) < 0)
1122 return ret;
1123 } else {
1124 if (s->rgb) {
1125 if ((ret = ljpeg_decode_rgb_scan(s, predictor,
1126 point_transform)) < 0)
1127 return ret;
1128 } else {
1129 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1130 point_transform,
1131 nb_components)) < 0)
1132 return ret;
1133 }
1134 }
1135 } else {
1136 if (s->progressive && predictor) {
1137 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1138 ilv, prev_shift,
1139 point_transform,
1140 mb_bitmask,
1141 reference)) < 0)
1142 return ret;
1143 } else {
1144 if ((ret = mjpeg_decode_scan(s, nb_components,
1145 prev_shift, point_transform,
1146 mb_bitmask, reference)) < 0)
1147 return ret;
1148 }
1149 }
1150
1151 if (s->interlaced &&
1152 get_bits_left(&s->gb) > 32 &&
1153 show_bits(&s->gb, 8) == 0xFF) {
1154 GetBitContext bak = s->gb;
1155 align_get_bits(&bak);
1156 if (show_bits(&bak, 16) == 0xFFD1) {
1157 ff_dlog(s->avctx, "AVRn interlaced picture marker found\n");
1158 s->gb = bak;
1159 skip_bits(&s->gb, 16);
1160 s->bottom_field ^= 1;
1161
1162 goto next_field;
1163 }
1164 }
1165
1166 emms_c();
1167 return 0;
1168 out_of_range:
1169 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1170 return AVERROR_INVALIDDATA;
1171 }
1172
1173 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1174 {
1175 if (get_bits(&s->gb, 16) != 4)
1176 return AVERROR_INVALIDDATA;
1177 s->restart_interval = get_bits(&s->gb, 16);
1178 s->restart_count = 0;
1179 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1180 s->restart_interval);
1181
1182 return 0;
1183 }
1184
1185 static int mjpeg_decode_app(MJpegDecodeContext *s)
1186 {
1187 int len, id, i;
1188
1189 len = get_bits(&s->gb, 16);
1190 if (len < 5)
1191 return AVERROR_INVALIDDATA;
1192 if (8 * len > get_bits_left(&s->gb))
1193 return AVERROR_INVALIDDATA;
1194
1195 id = get_bits_long(&s->gb, 32);
1196 id = av_be2ne32(id);
1197 len -= 6;
1198
1199 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1200 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1201
1202 /* Buggy AVID, it puts EOI only at every 10th frame. */
1203 /* Also, this fourcc is used by non-avid files too, it holds some
1204 information, but it's always present in AVID-created files. */
1205 if (id == AV_RL32("AVI1")) {
1206 /* structure:
1207 4bytes AVI1
1208 1bytes polarity
1209 1bytes always zero
1210 4bytes field_size
1211 4bytes field_size_less_padding
1212 */
1213 s->buggy_avid = 1;
1214 i = get_bits(&s->gb, 8);
1215 if (i == 2)
1216 s->bottom_field = 1;
1217 else if (i == 1)
1218 s->bottom_field = 0;
1219 goto out;
1220 }
1221
1222 if (id == AV_RL32("JFIF")) {
1223 int t_w, t_h, v1, v2;
1224 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1225 v1 = get_bits(&s->gb, 8);
1226 v2 = get_bits(&s->gb, 8);
1227 skip_bits(&s->gb, 8);
1228
1229 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1230 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1231 ff_set_sar(s->avctx, s->avctx->sample_aspect_ratio);
1232
1233 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1234 av_log(s->avctx, AV_LOG_INFO,
1235 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1236 v1, v2,
1237 s->avctx->sample_aspect_ratio.num,
1238 s->avctx->sample_aspect_ratio.den);
1239
1240 t_w = get_bits(&s->gb, 8);
1241 t_h = get_bits(&s->gb, 8);
1242 if (t_w && t_h) {
1243 /* skip thumbnail */
1244 if (len -10 - (t_w * t_h * 3) > 0)
1245 len -= t_w * t_h * 3;
1246 }
1247 len -= 10;
1248 goto out;
1249 }
1250
1251 if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1252 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1253 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1254 skip_bits(&s->gb, 16); /* version */
1255 skip_bits(&s->gb, 16); /* flags0 */
1256 skip_bits(&s->gb, 16); /* flags1 */
1257 skip_bits(&s->gb, 8); /* transform */
1258 len -= 7;
1259 goto out;
1260 }
1261
1262 if (id == AV_RL32("LJIF")) {
1263 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1264 av_log(s->avctx, AV_LOG_INFO,
1265 "Pegasus lossless jpeg header found\n");
1266 skip_bits(&s->gb, 16); /* version ? */
1267 skip_bits(&s->gb, 16); /* unknown always 0? */
1268 skip_bits(&s->gb, 16); /* unknown always 0? */
1269 skip_bits(&s->gb, 16); /* unknown always 0? */
1270 switch (get_bits(&s->gb, 8)) {
1271 case 1:
1272 s->rgb = 1;
1273 s->pegasus_rct = 0;
1274 break;
1275 case 2:
1276 s->rgb = 1;
1277 s->pegasus_rct = 1;
1278 break;
1279 default:
1280 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1281 }
1282 len -= 9;
1283 goto out;
1284 }
1285
1286 /* Apple MJPEG-A */
1287 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1288 id = get_bits_long(&s->gb, 32);
1289 id = av_be2ne32(id);
1290 len -= 4;
1291 /* Apple MJPEG-A */
1292 if (id == AV_RL32("mjpg")) {
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 int i;
1314 char *cbuf = av_malloc(len - 1);
1315 if (!cbuf)
1316 return AVERROR(ENOMEM);
1317
1318 for (i = 0; i < len - 2; i++)
1319 cbuf[i] = get_bits(&s->gb, 8);
1320 if (i > 0 && cbuf[i - 1] == '\n')
1321 cbuf[i - 1] = 0;
1322 else
1323 cbuf[i] = 0;
1324
1325 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1326 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1327
1328 /* buggy avid, it puts EOI only at every 10th frame */
1329 if (!strcmp(cbuf, "AVID")) {
1330 s->buggy_avid = 1;
1331 } else if (!strcmp(cbuf, "CS=ITU601"))
1332 s->cs_itu601 = 1;
1333 else if ((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1334 (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1335 s->flipped = 1;
1336
1337 av_free(cbuf);
1338 }
1339
1340 return 0;
1341 }
1342
1343 /* return the 8 bit start code value and update the search
1344 state. Return -1 if no start code found */
1345 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1346 {
1347 const uint8_t *buf_ptr;
1348 unsigned int v, v2;
1349 int val;
1350 #ifdef DEBUG
1351 int skipped = 0;
1352 #endif
1353
1354 buf_ptr = *pbuf_ptr;
1355 while (buf_ptr < buf_end) {
1356 v = *buf_ptr++;
1357 v2 = *buf_ptr;
1358 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1359 val = *buf_ptr++;
1360 goto found;
1361 }
1362 #ifdef DEBUG
1363 skipped++;
1364 #endif
1365 }
1366 val = -1;
1367 found:
1368 ff_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1369 *pbuf_ptr = buf_ptr;
1370 return val;
1371 }
1372
1373 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1374 const uint8_t **buf_ptr, const uint8_t *buf_end,
1375 const uint8_t **unescaped_buf_ptr,
1376 int *unescaped_buf_size)
1377 {
1378 int start_code;
1379 start_code = find_marker(buf_ptr, buf_end);
1380
1381 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1382 if (!s->buffer)
1383 return AVERROR(ENOMEM);
1384
1385 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1386 if (start_code == SOS && !s->ls) {
1387 const uint8_t *src = *buf_ptr;
1388 uint8_t *dst = s->buffer;
1389
1390 while (src < buf_end) {
1391 uint8_t x = *(src++);
1392
1393 *(dst++) = x;
1394 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1395 if (x == 0xff) {
1396 while (src < buf_end && x == 0xff)
1397 x = *(src++);
1398
1399 if (x >= 0xd0 && x <= 0xd7)
1400 *(dst++) = x;
1401 else if (x)
1402 break;
1403 }
1404 }
1405 }
1406 *unescaped_buf_ptr = s->buffer;
1407 *unescaped_buf_size = dst - s->buffer;
1408 memset(s->buffer + *unescaped_buf_size, 0,
1409 AV_INPUT_BUFFER_PADDING_SIZE);
1410
1411 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1412 (buf_end - *buf_ptr) - (dst - s->buffer));
1413 } else if (start_code == SOS && s->ls) {
1414 const uint8_t *src = *buf_ptr;
1415 uint8_t *dst = s->buffer;
1416 int bit_count = 0;
1417 int t = 0, b = 0;
1418 PutBitContext pb;
1419
1420 s->cur_scan++;
1421
1422 /* find marker */
1423 while (src + t < buf_end) {
1424 uint8_t x = src[t++];
1425 if (x == 0xff) {
1426 while ((src + t < buf_end) && x == 0xff)
1427 x = src[t++];
1428 if (x & 0x80) {
1429 t -= 2;
1430 break;
1431 }
1432 }
1433 }
1434 bit_count = t * 8;
1435 init_put_bits(&pb, dst, t);
1436
1437 /* unescape bitstream */
1438 while (b < t) {
1439 uint8_t x = src[b++];
1440 put_bits(&pb, 8, x);
1441 if (x == 0xFF) {
1442 x = src[b++];
1443 put_bits(&pb, 7, x);
1444 bit_count--;
1445 }
1446 }
1447 flush_put_bits(&pb);
1448
1449 *unescaped_buf_ptr = dst;
1450 *unescaped_buf_size = (bit_count + 7) >> 3;
1451 memset(s->buffer + *unescaped_buf_size, 0,
1452 AV_INPUT_BUFFER_PADDING_SIZE);
1453 } else {
1454 *unescaped_buf_ptr = *buf_ptr;
1455 *unescaped_buf_size = buf_end - *buf_ptr;
1456 }
1457
1458 return start_code;
1459 }
1460
1461 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1462 AVPacket *avpkt)
1463 {
1464 AVFrame *frame = data;
1465 const uint8_t *buf = avpkt->data;
1466 int buf_size = avpkt->size;
1467 MJpegDecodeContext *s = avctx->priv_data;
1468 const uint8_t *buf_end, *buf_ptr;
1469 const uint8_t *unescaped_buf_ptr;
1470 int unescaped_buf_size;
1471 int start_code;
1472 int ret = 0;
1473
1474 s->got_picture = 0; // picture from previous image can not be reused
1475 buf_ptr = buf;
1476 buf_end = buf + buf_size;
1477 while (buf_ptr < buf_end) {
1478 /* find start next marker */
1479 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1480 &unescaped_buf_ptr,
1481 &unescaped_buf_size);
1482 /* EOF */
1483 if (start_code < 0) {
1484 goto the_end;
1485 } else if (unescaped_buf_size > INT_MAX / 8) {
1486 av_log(avctx, AV_LOG_ERROR,
1487 "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1488 start_code, unescaped_buf_size, buf_size);
1489 return AVERROR_INVALIDDATA;
1490 }
1491
1492 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1493 start_code, buf_end - buf_ptr);
1494
1495 ret = init_get_bits(&s->gb, unescaped_buf_ptr,
1496 unescaped_buf_size * 8);
1497 if (ret < 0)
1498 return ret;
1499
1500 s->start_code = start_code;
1501 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1502 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1503
1504 /* process markers */
1505 if (start_code >= 0xd0 && start_code <= 0xd7)
1506 av_log(avctx, AV_LOG_DEBUG,
1507 "restart marker: %d\n", start_code & 0x0f);
1508 /* APP fields */
1509 else if (start_code >= APP0 && start_code <= APP15)
1510 mjpeg_decode_app(s);
1511 /* Comment */
1512 else if (start_code == COM) {
1513 ret = mjpeg_decode_com(s);
1514 if (ret < 0)
1515 return ret;
1516 }
1517
1518 if (!CONFIG_JPEGLS_DECODER &&
1519 (start_code == SOF48 || start_code == LSE)) {
1520 av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1521 return AVERROR(ENOSYS);
1522 }
1523
1524 switch (start_code) {
1525 case SOI:
1526 s->restart_interval = 0;
1527 s->restart_count = 0;
1528 /* nothing to do on SOI */
1529 break;
1530 case DQT:
1531 ff_mjpeg_decode_dqt(s);
1532 break;
1533 case DHT:
1534 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1535 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1536 return ret;
1537 }
1538 break;
1539 case SOF0:
1540 case SOF1:
1541 s->lossless = 0;
1542 s->ls = 0;
1543 s->progressive = 0;
1544 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1545 return ret;
1546 break;
1547 case SOF2:
1548 s->lossless = 0;
1549 s->ls = 0;
1550 s->progressive = 1;
1551 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1552 return ret;
1553 break;
1554 case SOF3:
1555 s->lossless = 1;
1556 s->ls = 0;
1557 s->progressive = 0;
1558 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1559 return ret;
1560 break;
1561 case SOF48:
1562 s->lossless = 1;
1563 s->ls = 1;
1564 s->progressive = 0;
1565 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1566 return ret;
1567 break;
1568 case LSE:
1569 if (!CONFIG_JPEGLS_DECODER ||
1570 (ret = ff_jpegls_decode_lse(s)) < 0)
1571 return ret;
1572 break;
1573 case EOI:
1574 s->cur_scan = 0;
1575 if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1576 break;
1577 eoi_parser:
1578 if (!s->got_picture) {
1579 av_log(avctx, AV_LOG_WARNING,
1580 "Found EOI before any SOF, ignoring\n");
1581 break;
1582 }
1583 if (s->interlaced) {
1584 s->bottom_field ^= 1;
1585 /* if not bottom field, do not output image yet */
1586 if (s->bottom_field == !s->interlace_polarity)
1587 goto not_the_end;
1588 }
1589 if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
1590 return ret;
1591 if (s->flipped) {
1592 int i;
1593 for (i = 0; frame->data[i]; i++) {
1594 int h = frame->height >> ((i == 1 || i == 2) ?
1595 s->pix_desc->log2_chroma_h : 0);
1596 frame->data[i] += frame->linesize[i] * (h - 1);
1597 frame->linesize[i] *= -1;
1598 }
1599 }
1600 *got_frame = 1;
1601
1602 if (!s->lossless &&
1603 avctx->debug & FF_DEBUG_QP) {
1604 av_log(avctx, AV_LOG_DEBUG,
1605 "QP: %d\n", FFMAX3(s->qscale[0],
1606 s->qscale[1],
1607 s->qscale[2]));
1608 }
1609
1610 goto the_end;
1611 case SOS:
1612 if (!s->got_picture) {
1613 av_log(avctx, AV_LOG_WARNING,
1614 "Can not process SOS before SOF, skipping\n");
1615 break;
1616 }
1617 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1618 (avctx->err_recognition & AV_EF_EXPLODE))
1619 return ret;
1620 /* buggy avid puts EOI every 10-20th frame */
1621 /* if restart period is over process EOI */
1622 if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1623 goto eoi_parser;
1624 break;
1625 case DRI:
1626 mjpeg_decode_dri(s);
1627 break;
1628 case SOF5:
1629 case SOF6:
1630 case SOF7:
1631 case SOF9:
1632 case SOF10:
1633 case SOF11:
1634 case SOF13:
1635 case SOF14:
1636 case SOF15:
1637 case JPG:
1638 av_log(avctx, AV_LOG_ERROR,
1639 "mjpeg: unsupported coding type (%x)\n", start_code);
1640 break;
1641 }
1642
1643 not_the_end:
1644 /* eof process start code */
1645 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1646 av_log(avctx, AV_LOG_DEBUG,
1647 "marker parser used %d bytes (%d bits)\n",
1648 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1649 }
1650 if (s->got_picture) {
1651 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1652 goto eoi_parser;
1653 }
1654 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1655 return AVERROR_INVALIDDATA;
1656 the_end:
1657 av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n",
1658 buf_end - buf_ptr);
1659 // return buf_end - buf_ptr;
1660 return buf_ptr - buf;
1661 }
1662
1663 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1664 {
1665 MJpegDecodeContext *s = avctx->priv_data;
1666 int i, j;
1667
1668 if (s->picture) {
1669 av_frame_free(&s->picture);
1670 s->picture_ptr = NULL;
1671 } else if (s->picture_ptr)
1672 av_frame_unref(s->picture_ptr);
1673
1674 av_free(s->buffer);
1675 av_freep(&s->ljpeg_buffer);
1676 s->ljpeg_buffer_size = 0;
1677
1678 for (i = 0; i < 3; i++) {
1679 for (j = 0; j < 4; j++)
1680 ff_free_vlc(&s->vlcs[i][j]);
1681 }
1682 for (i = 0; i < MAX_COMPONENTS; i++) {
1683 av_freep(&s->blocks[i]);
1684 av_freep(&s->last_nnz[i]);
1685 }
1686 return 0;
1687 }
1688
1689 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1690 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1691 static const AVOption options[] = {
1692 { "extern_huff", "Use external huffman table.",
1693 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1694 { NULL },
1695 };
1696
1697 static const AVClass mjpegdec_class = {
1698 .class_name = "MJPEG decoder",
1699 .item_name = av_default_item_name,
1700 .option = options,
1701 .version = LIBAVUTIL_VERSION_INT,
1702 };
1703
1704 AVCodec ff_mjpeg_decoder = {
1705 .name = "mjpeg",
1706 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1707 .type = AVMEDIA_TYPE_VIDEO,
1708 .id = AV_CODEC_ID_MJPEG,
1709 .priv_data_size = sizeof(MJpegDecodeContext),
1710 .init = ff_mjpeg_decode_init,
1711 .close = ff_mjpeg_decode_end,
1712 .decode = ff_mjpeg_decode_frame,
1713 .capabilities = AV_CODEC_CAP_DR1,
1714 .priv_class = &mjpegdec_class,
1715 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1716 };
1717
1718 AVCodec ff_thp_decoder = {
1719 .name = "thp",
1720 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1721 .type = AVMEDIA_TYPE_VIDEO,
1722 .id = AV_CODEC_ID_THP,
1723 .priv_data_size = sizeof(MJpegDecodeContext),
1724 .init = ff_mjpeg_decode_init,
1725 .close = ff_mjpeg_decode_end,
1726 .decode = ff_mjpeg_decode_frame,
1727 .capabilities = AV_CODEC_CAP_DR1,
1728 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1729 };