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