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