3 * Copyright (c) 2000, 2001 Fabrice Bellard
4 * Copyright (c) 2003 Alex Beregszaszi
5 * Copyright (c) 2003-2004 Michael Niedermayer
7 * Support for external huffman table, various fixes (AVID workaround),
8 * aspecting, new decode_frame mechanism and apple mjpeg-b support
11 * This file is part of FFmpeg.
13 * FFmpeg 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.
18 * FFmpeg 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.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with FFmpeg; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
33 #include "libavutil/imgutils.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/opt.h"
37 #include "copy_block.h"
41 #include "jpeglsdec.h"
44 #include "bytestream.h"
47 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
48 const uint8_t *val_table, int nb_codes,
49 int use_static, int is_ac)
51 uint8_t huff_size[256] = { 0 };
52 uint16_t huff_code[256];
53 uint16_t huff_sym[256];
56 av_assert0(nb_codes <= 256);
58 ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
60 for (i = 0; i < 256; i++)
61 huff_sym[i] = i + 16 * is_ac;
64 huff_sym[0] = 16 * 256;
66 return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
67 huff_code, 2, 2, huff_sym, 2, 2, use_static);
70 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
72 build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
73 avpriv_mjpeg_val_dc, 12, 0, 0);
74 build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
75 avpriv_mjpeg_val_dc, 12, 0, 0);
76 build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
77 avpriv_mjpeg_val_ac_luminance, 251, 0, 1);
78 build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
79 avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);
80 build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
81 avpriv_mjpeg_val_ac_luminance, 251, 0, 0);
82 build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
83 avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);
86 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
88 MJpegDecodeContext *s = avctx->priv_data;
91 s->picture_ptr = &s->picture;
92 avcodec_get_frame_defaults(&s->picture);
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);
101 s->first_picture = 1;
103 s->org_height = avctx->coded_height;
104 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
106 build_basic_mjpeg_vlc(s);
108 if (s->extern_huff) {
109 av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
110 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
111 if (ff_mjpeg_decode_dht(s)) {
112 av_log(avctx, AV_LOG_ERROR,
113 "error using external huffman table, switching back to internal\n");
114 build_basic_mjpeg_vlc(s);
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, "bottom field first\n");
121 if (avctx->codec->id == AV_CODEC_ID_AMV)
128 /* quantize tables */
129 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
131 int len, index, i, j;
133 len = get_bits(&s->gb, 16) - 2;
136 int pr = get_bits(&s->gb, 4);
138 av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
139 return AVERROR_INVALIDDATA;
141 index = get_bits(&s->gb, 4);
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, pr ? 16 : 8);
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]);
161 /* decode huffman tables and build VLC decoders */
162 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
164 int len, index, i, class, n, v, code_max;
165 uint8_t bits_table[17];
166 uint8_t val_table[256];
169 len = get_bits(&s->gb, 16) - 2;
173 return AVERROR_INVALIDDATA;
174 class = get_bits(&s->gb, 4);
176 return AVERROR_INVALIDDATA;
177 index = get_bits(&s->gb, 4);
179 return AVERROR_INVALIDDATA;
181 for (i = 1; i <= 16; i++) {
182 bits_table[i] = get_bits(&s->gb, 8);
186 if (len < n || n > 256)
187 return AVERROR_INVALIDDATA;
190 for (i = 0; i < n; i++) {
191 v = get_bits(&s->gb, 8);
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)
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)
216 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
218 int len, nb_components, i, width, height, pix_fmt_id;
219 int h_count[MAX_COMPONENTS];
220 int v_count[MAX_COMPONENTS];
223 s->upscale_h = s->upscale_v = 0;
225 /* XXX: verify len field validity */
226 len = get_bits(&s->gb, 16);
227 s->avctx->bits_per_raw_sample =
228 s->bits = get_bits(&s->gb, 8);
232 if (s->bits == 9 && !s->pegasus_rct)
233 s->rct = 1; // FIXME ugly
235 if (s->bits != 8 && !s->lossless) {
236 av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
240 if(s->lossless && s->avctx->lowres){
241 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
245 height = get_bits(&s->gb, 16);
246 width = get_bits(&s->gb, 16);
248 // HACK for odd_height.mov
249 if (s->interlaced && s->width == width && s->height == height + 1)
252 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
253 if (av_image_check_size(width, height, 0, s->avctx))
254 return AVERROR_INVALIDDATA;
256 nb_components = get_bits(&s->gb, 8);
257 if (nb_components <= 0 ||
258 nb_components > MAX_COMPONENTS)
260 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
261 if (nb_components != s->nb_components) {
262 av_log(s->avctx, AV_LOG_ERROR,
263 "nb_components changing in interlaced picture\n");
264 return AVERROR_INVALIDDATA;
267 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
268 avpriv_report_missing_feature(s->avctx,
269 "JPEG-LS that is not <= 8 "
270 "bits/component or 16-bit gray");
271 return AVERROR_PATCHWELCOME;
273 s->nb_components = nb_components;
276 memset(h_count, 0, sizeof(h_count));
277 memset(v_count, 0, sizeof(v_count));
278 for (i = 0; i < nb_components; i++) {
280 s->component_id[i] = get_bits(&s->gb, 8) - 1;
281 h_count[i] = get_bits(&s->gb, 4);
282 v_count[i] = get_bits(&s->gb, 4);
283 /* compute hmax and vmax (only used in interleaved case) */
284 if (h_count[i] > s->h_max)
285 s->h_max = h_count[i];
286 if (v_count[i] > s->v_max)
287 s->v_max = v_count[i];
288 s->quant_index[i] = get_bits(&s->gb, 8);
289 if (s->quant_index[i] >= 4) {
290 av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
291 return AVERROR_INVALIDDATA;
293 if (!h_count[i] || !v_count[i]) {
294 av_log(s->avctx, AV_LOG_ERROR,
295 "Invalid sampling factor in component %d %d:%d\n",
296 i, h_count[i], v_count[i]);
297 return AVERROR_INVALIDDATA;
300 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
301 i, h_count[i], v_count[i],
302 s->component_id[i], s->quant_index[i]);
305 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
306 avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
307 return AVERROR_PATCHWELCOME;
311 /* if different size, realloc/alloc picture */
312 if ( width != s->width || height != s->height
313 || memcmp(s->h_count, h_count, sizeof(h_count))
314 || memcmp(s->v_count, v_count, sizeof(v_count))) {
318 memcpy(s->h_count, h_count, sizeof(h_count));
319 memcpy(s->v_count, v_count, sizeof(v_count));
323 /* test interlaced mode */
324 if (s->first_picture &&
325 s->org_height != 0 &&
326 s->height < ((s->org_height * 3) / 4)) {
328 s->bottom_field = s->interlace_polarity;
329 s->picture_ptr->interlaced_frame = 1;
330 s->picture_ptr->top_field_first = !s->interlace_polarity;
334 avcodec_set_dimensions(s->avctx, width, height);
336 s->first_picture = 0;
339 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
340 if (s->progressive) {
341 avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
342 return AVERROR_INVALIDDATA;
345 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
347 else if (!s->lossless)
349 /* XXX: not complete test ! */
350 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
351 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
352 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
353 (s->h_count[3] << 4) | s->v_count[3];
354 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
355 /* NOTE we do not allocate pictures large enough for the possible
356 * padding of h/v_count being 4 */
357 if (!(pix_fmt_id & 0xD0D0D0D0))
358 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
359 if (!(pix_fmt_id & 0x0D0D0D0D))
360 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
362 switch (pix_fmt_id) {
365 s->avctx->pix_fmt = AV_PIX_FMT_BGR24;
367 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
368 s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
370 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
371 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
374 av_assert0(s->nb_components == 3);
378 s->avctx->pix_fmt = AV_PIX_FMT_ABGR;
380 s->avctx->pix_fmt = /*s->cs_itu601 ?*/ AV_PIX_FMT_YUVA444P/* : AV_PIX_FMT_YUVJA444P*/;
381 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
383 av_assert0(s->nb_components == 4);
387 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
388 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
390 s->upscale_h = (pix_fmt_id == 0x22122100);
391 s->chroma_height = s->height;
395 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
396 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
397 s->upscale_v = (pix_fmt_id == 0x22211200);
399 s->chroma_height = s->height;
402 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
403 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
406 s->chroma_height = s->height / 2;
418 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
420 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
425 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
426 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
427 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
428 s->chroma_height = s->height / 2;
431 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
432 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
436 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
437 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
438 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
441 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
442 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
445 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
446 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
449 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
450 return AVERROR_PATCHWELCOME;
452 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
453 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
454 return AVERROR_PATCHWELCOME;
457 s->upscale_h = s->upscale_v = 0;
458 if (s->nb_components > 1)
459 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
460 else if (s->bits <= 8)
461 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
463 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
466 av_frame_unref(s->picture_ptr);
467 if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
469 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
470 s->picture_ptr->key_frame = 1;
473 for (i = 0; i < 3; i++)
474 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
476 av_dlog(s->avctx, "%d %d %d %d %d %d\n",
477 s->width, s->height, s->linesize[0], s->linesize[1],
478 s->interlaced, s->avctx->height);
480 if (len != (8 + (3 * nb_components)))
481 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
484 if (s->rgb && !s->lossless && !s->ls) {
485 av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
486 return AVERROR_PATCHWELCOME;
489 /* totally blank picture as progressive JPEG will only add details to it */
490 if (s->progressive) {
491 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
492 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
493 for (i = 0; i < s->nb_components; i++) {
494 int size = bw * bh * s->h_count[i] * s->v_count[i];
495 av_freep(&s->blocks[i]);
496 av_freep(&s->last_nnz[i]);
497 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
498 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
499 s->block_stride[i] = bw * s->h_count[i];
501 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
506 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
509 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
510 if (code < 0 || code > 16) {
511 av_log(s->avctx, AV_LOG_WARNING,
512 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
513 0, dc_index, &s->vlcs[0][dc_index]);
518 return get_xbits(&s->gb, code);
523 /* decode block and dequantize */
524 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
525 int dc_index, int ac_index, int16_t *quant_matrix)
527 int code, i, j, level, val;
530 val = mjpeg_decode_dc(s, dc_index);
532 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
533 return AVERROR_INVALIDDATA;
535 val = val * quant_matrix[0] + s->last_dc[component];
536 s->last_dc[component] = val;
540 {OPEN_READER(re, &s->gb);
542 UPDATE_CACHE(re, &s->gb);
543 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
545 i += ((unsigned)code) >> 4;
548 if (code > MIN_CACHE_BITS - 16)
549 UPDATE_CACHE(re, &s->gb);
552 int cache = GET_CACHE(re, &s->gb);
553 int sign = (~cache) >> 31;
554 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
557 LAST_SKIP_BITS(re, &s->gb, code);
560 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
561 return AVERROR_INVALIDDATA;
563 j = s->scantable.permutated[i];
564 block[j] = level * quant_matrix[j];
567 CLOSE_READER(re, &s->gb);}
572 static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
573 int component, int dc_index,
574 int16_t *quant_matrix, int Al)
577 s->dsp.clear_block(block);
578 val = mjpeg_decode_dc(s, dc_index);
580 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
581 return AVERROR_INVALIDDATA;
583 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
584 s->last_dc[component] = val;
589 /* decode block and dequantize - progressive JPEG version */
590 static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
591 uint8_t *last_nnz, int ac_index,
592 int16_t *quant_matrix,
593 int ss, int se, int Al, int *EOBRUN)
595 int code, i, j, level, val, run;
603 OPEN_READER(re, &s->gb);
604 for (i = ss; ; i++) {
605 UPDATE_CACHE(re, &s->gb);
606 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
608 run = ((unsigned) code) >> 4;
612 if (code > MIN_CACHE_BITS - 16)
613 UPDATE_CACHE(re, &s->gb);
616 int cache = GET_CACHE(re, &s->gb);
617 int sign = (~cache) >> 31;
618 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
621 LAST_SKIP_BITS(re, &s->gb, code);
625 j = s->scantable.permutated[se];
626 block[j] = level * quant_matrix[j] << Al;
629 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
630 return AVERROR_INVALIDDATA;
632 j = s->scantable.permutated[i];
633 block[j] = level * quant_matrix[j] << Al;
635 if (run == 0xF) {// ZRL - skip 15 coefficients
638 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
639 return AVERROR_INVALIDDATA;
644 UPDATE_CACHE(re, &s->gb);
645 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
646 LAST_SKIP_BITS(re, &s->gb, run);
653 CLOSE_READER(re, &s->gb);
662 #define REFINE_BIT(j) { \
663 UPDATE_CACHE(re, &s->gb); \
664 sign = block[j] >> 15; \
665 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
666 ((quant_matrix[j] ^ sign) - sign) << Al; \
667 LAST_SKIP_BITS(re, &s->gb, 1); \
675 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
680 j = s->scantable.permutated[i]; \
683 else if (run-- == 0) \
687 /* decode block and dequantize - progressive JPEG refinement pass */
688 static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
690 int ac_index, int16_t *quant_matrix,
691 int ss, int se, int Al, int *EOBRUN)
693 int code, i = ss, j, sign, val, run;
694 int last = FFMIN(se, *last_nnz);
696 OPEN_READER(re, &s->gb);
701 UPDATE_CACHE(re, &s->gb);
702 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
705 run = ((unsigned) code) >> 4;
706 UPDATE_CACHE(re, &s->gb);
707 val = SHOW_UBITS(re, &s->gb, 1);
708 LAST_SKIP_BITS(re, &s->gb, 1);
710 j = s->scantable.permutated[i];
712 block[j] = ((quant_matrix[j]^val) - val) << Al;
716 CLOSE_READER(re, &s->gb);
720 run = ((unsigned) code) >> 4;
727 UPDATE_CACHE(re, &s->gb);
728 run += SHOW_UBITS(re, &s->gb, val);
729 LAST_SKIP_BITS(re, &s->gb, val);
741 for (; i <= last; i++) {
742 j = s->scantable.permutated[i];
746 CLOSE_READER(re, &s->gb);
753 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
758 if (s->restart_interval) {
760 if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
761 align_get_bits(&s->gb);
762 for (i = 0; i < nb_components; i++) /* reset dc */
763 s->last_dc[i] = 1024;
766 i = 8 + ((-get_bits_count(&s->gb)) & 7);
768 if (s->restart_count == 0) {
769 if( show_bits(&s->gb, i) == (1 << i) - 1
770 || show_bits(&s->gb, i) == 0xFF) {
771 int pos = get_bits_count(&s->gb);
772 align_get_bits(&s->gb);
773 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
774 skip_bits(&s->gb, 8);
775 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
776 for (i = 0; i < nb_components; i++) /* reset dc */
777 s->last_dc[i] = 1024;
780 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
787 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
790 uint16_t (*buffer)[4];
791 int left[4], top[4], topleft[4];
792 const int linesize = s->linesize[0];
793 const int mask = (1 << s->bits) - 1;
797 s->restart_count = s->restart_interval;
799 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
800 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
801 buffer = s->ljpeg_buffer;
803 for (i = 0; i < 4; i++)
804 buffer[0][i] = 1 << (s->bits - 1);
806 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
807 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
809 if (s->interlaced && s->bottom_field)
810 ptr += linesize >> 1;
812 for (i = 0; i < 4; i++)
813 top[i] = left[i] = topleft[i] = buffer[0][i];
815 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
816 int modified_predictor = predictor;
818 if (s->restart_interval && !s->restart_count){
819 s->restart_count = s->restart_interval;
823 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
825 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
826 modified_predictor = 1;
828 for (i=0;i<nb_components;i++) {
832 top[i] = buffer[mb_x][i];
834 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
836 dc = mjpeg_decode_dc(s, s->dc_index[i]);
840 left[i] = buffer[mb_x][i] =
841 mask & (pred + (dc << point_transform));
844 if (s->restart_interval && !--s->restart_count) {
845 align_get_bits(&s->gb);
846 skip_bits(&s->gb, 16); /* skip RSTn */
849 if (s->nb_components == 4) {
850 for(i=0; i<nb_components; i++) {
851 int c= s->comp_index[i];
852 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
853 ptr[4*mb_x+3-c] = buffer[mb_x][i];
857 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
858 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
859 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
860 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
862 } else if (s->pegasus_rct) {
863 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
864 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
865 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
866 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
869 for(i=0; i<nb_components; i++) {
870 int c= s->comp_index[i];
871 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
872 ptr[3*mb_x+2-c] = buffer[mb_x][i];
880 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
881 int point_transform, int nb_components)
884 int bits= (s->bits+7)&~7;
888 point_transform += bits - s->bits;
890 av_assert0(nb_components>=1 && nb_components<=4);
892 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
893 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
894 if (s->restart_interval && !s->restart_count){
895 s->restart_count = s->restart_interval;
900 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
901 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
902 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
903 for (i = 0; i < nb_components; i++) {
906 int n, h, v, x, y, c, j, linesize;
908 c = s->comp_index[i];
913 linesize= s->linesize[c];
915 if(bits>8) linesize /= 2;
920 dc = mjpeg_decode_dc(s, s->dc_index[i]);
924 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
927 pred= 1 << (bits - 1);
933 pred= ptr[-linesize];
935 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
939 if (s->interlaced && s->bottom_field)
940 ptr += linesize >> 1;
941 pred &= (-1)<<(8-s->bits);
942 *ptr= pred + (dc << point_transform);
944 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
947 pred= 1 << (bits - 1);
953 pred= ptr16[-linesize];
955 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
959 if (s->interlaced && s->bottom_field)
960 ptr16 += linesize >> 1;
961 pred &= (-1)<<(16-s->bits);
962 *ptr16= pred + (dc << point_transform);
971 for (i = 0; i < nb_components; i++) {
974 int n, h, v, x, y, c, j, linesize, dc;
976 c = s->comp_index[i];
981 linesize = s->linesize[c];
983 if(bits>8) linesize /= 2;
985 for (j = 0; j < n; j++) {
988 dc = mjpeg_decode_dc(s, s->dc_index[i]);
992 ptr = s->picture.data[c] +
993 (linesize * (v * mb_y + y)) +
994 (h * mb_x + x); //FIXME optimize this crap
995 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
997 pred &= (-1)<<(8-s->bits);
998 *ptr = pred + (dc << point_transform);
1000 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1001 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1003 pred &= (-1)<<(16-s->bits);
1004 *ptr16= pred + (dc << point_transform);
1014 if (s->restart_interval && !--s->restart_count) {
1015 align_get_bits(&s->gb);
1016 skip_bits(&s->gb, 16); /* skip RSTn */
1023 static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
1024 uint8_t *dst, const uint8_t *src,
1025 int linesize, int lowres)
1028 case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1030 case 1: copy_block4(dst, src, linesize, linesize, 4);
1032 case 2: copy_block2(dst, src, linesize, linesize, 2);
1034 case 3: *dst = *src;
1039 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1040 int Al, const uint8_t *mb_bitmask,
1041 const AVFrame *reference)
1044 uint8_t *data[MAX_COMPONENTS];
1045 const uint8_t *reference_data[MAX_COMPONENTS];
1046 int linesize[MAX_COMPONENTS];
1047 GetBitContext mb_bitmask_gb;
1050 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1052 if (s->flipped && s->avctx->lowres) {
1053 av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
1056 s->restart_count = 0;
1057 for (i = 0; i < nb_components; i++) {
1058 int c = s->comp_index[i];
1059 data[c] = s->picture_ptr->data[c];
1060 reference_data[c] = reference ? reference->data[c] : NULL;
1061 linesize[c] = s->linesize[c];
1062 s->coefs_finished[c] |= 1;
1063 if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1064 // picture should be flipped upside-down for this codec
1065 int offset = (linesize[c] * (s->v_scount[i] *
1066 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
1068 reference_data[c] += offset;
1073 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1074 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1075 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1077 if (s->restart_interval && !s->restart_count)
1078 s->restart_count = s->restart_interval;
1080 if (get_bits_left(&s->gb) < 0) {
1081 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1082 -get_bits_left(&s->gb));
1083 return AVERROR_INVALIDDATA;
1085 for (i = 0; i < nb_components; i++) {
1087 int n, h, v, x, y, c, j;
1089 n = s->nb_blocks[i];
1090 c = s->comp_index[i];
1095 for (j = 0; j < n; j++) {
1096 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1097 (h * mb_x + x) * 8) >> s->avctx->lowres);
1099 if (s->interlaced && s->bottom_field)
1100 block_offset += linesize[c] >> 1;
1101 ptr = data[c] + block_offset;
1102 if (!s->progressive) {
1104 mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1105 linesize[c], s->avctx->lowres);
1108 s->dsp.clear_block(s->block);
1109 if (decode_block(s, s->block, i,
1110 s->dc_index[i], s->ac_index[i],
1111 s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1112 av_log(s->avctx, AV_LOG_ERROR,
1113 "error y=%d x=%d\n", mb_y, mb_x);
1114 return AVERROR_INVALIDDATA;
1116 s->dsp.idct_put(ptr, linesize[c], s->block);
1119 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1121 int16_t *block = s->blocks[c][block_idx];
1123 block[0] += get_bits1(&s->gb) *
1124 s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1125 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1126 s->quant_matrixes[s->quant_sindex[i]],
1128 av_log(s->avctx, AV_LOG_ERROR,
1129 "error y=%d x=%d\n", mb_y, mb_x);
1130 return AVERROR_INVALIDDATA;
1133 av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1134 av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1135 mb_x, mb_y, x, y, c, s->bottom_field,
1136 (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1144 handle_rstn(s, nb_components);
1150 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1151 int se, int Ah, int Al)
1155 int c = s->comp_index[0];
1156 uint8_t *data = s->picture.data[c];
1157 int linesize = s->linesize[c];
1159 int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1161 av_assert0(ss>=0 && Ah>=0 && Al>=0);
1162 if (se < ss || se > 63) {
1163 av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1164 return AVERROR_INVALIDDATA;
1168 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1169 last_scan = !~s->coefs_finished[c];
1172 if (s->interlaced && s->bottom_field)
1173 data += linesize >> 1;
1175 s->restart_count = 0;
1177 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1178 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1179 int block_idx = mb_y * s->block_stride[c];
1180 int16_t (*block)[64] = &s->blocks[c][block_idx];
1181 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1182 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1184 if (s->restart_interval && !s->restart_count)
1185 s->restart_count = s->restart_interval;
1188 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1189 quant_matrix, ss, se, Al, &EOBRUN);
1191 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1192 quant_matrix, ss, se, Al, &EOBRUN);
1194 av_log(s->avctx, AV_LOG_ERROR,
1195 "error y=%d x=%d\n", mb_y, mb_x);
1196 return AVERROR_INVALIDDATA;
1200 s->dsp.idct_put(ptr, linesize, *block);
1201 ptr += 8 >> s->avctx->lowres;
1203 if (handle_rstn(s, 0))
1210 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1211 const AVFrame *reference)
1213 int len, nb_components, i, h, v, predictor, point_transform;
1215 const int block_size = s->lossless ? 1 : 8;
1216 int ilv, prev_shift;
1218 if (!s->got_picture) {
1219 av_log(s->avctx, AV_LOG_WARNING,
1220 "Can not process SOS before SOF, skipping\n");
1224 av_assert0(s->picture_ptr->data[0]);
1225 /* XXX: verify len field validity */
1226 len = get_bits(&s->gb, 16);
1227 nb_components = get_bits(&s->gb, 8);
1228 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1229 av_log(s->avctx, AV_LOG_ERROR,
1230 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1231 return AVERROR_PATCHWELCOME;
1233 if (len != 6 + 2 * nb_components) {
1234 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1235 return AVERROR_INVALIDDATA;
1237 for (i = 0; i < nb_components; i++) {
1238 id = get_bits(&s->gb, 8) - 1;
1239 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1240 /* find component index */
1241 for (index = 0; index < s->nb_components; index++)
1242 if (id == s->component_id[index])
1244 if (index == s->nb_components) {
1245 av_log(s->avctx, AV_LOG_ERROR,
1246 "decode_sos: index(%d) out of components\n", index);
1247 return AVERROR_INVALIDDATA;
1249 /* Metasoft MJPEG codec has Cb and Cr swapped */
1250 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1251 && nb_components == 3 && s->nb_components == 3 && i)
1254 s->quant_sindex[i] = s->quant_index[index];
1255 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1256 s->h_scount[i] = s->h_count[index];
1257 s->v_scount[i] = s->v_count[index];
1259 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1261 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1262 index = (index+2)%3;
1264 s->comp_index[i] = index;
1266 s->dc_index[i] = get_bits(&s->gb, 4);
1267 s->ac_index[i] = get_bits(&s->gb, 4);
1269 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1270 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1272 if (!s->vlcs[0][s->dc_index[i]].table || !(s->progressive ? s->vlcs[2][s->ac_index[0]].table : s->vlcs[1][s->ac_index[i]].table))
1276 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1277 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1278 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1279 prev_shift = get_bits(&s->gb, 4); /* Ah */
1280 point_transform = get_bits(&s->gb, 4); /* Al */
1282 prev_shift = point_transform = 0;
1284 if (nb_components > 1) {
1285 /* interleaved stream */
1286 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1287 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1288 } else if (!s->ls) { /* skip this for JPEG-LS */
1289 h = s->h_max / s->h_scount[0];
1290 v = s->v_max / s->v_scount[0];
1291 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1292 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1293 s->nb_blocks[0] = 1;
1298 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1299 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1300 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1301 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1302 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1305 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1306 for (i = s->mjpb_skiptosod; i > 0; i--)
1307 skip_bits(&s->gb, 8);
1310 for (i = 0; i < nb_components; i++)
1311 s->last_dc[i] = 1024;
1314 av_assert0(s->picture_ptr == &s->picture);
1315 if (CONFIG_JPEGLS_DECODER && s->ls) {
1317 // reset_ls_coding_parameters(s, 0);
1319 if ((ret = ff_jpegls_decode_picture(s, predictor,
1320 point_transform, ilv)) < 0)
1324 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1327 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1329 nb_components)) < 0)
1334 if (s->progressive && predictor) {
1335 av_assert0(s->picture_ptr == &s->picture);
1336 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1338 point_transform)) < 0)
1341 if ((ret = mjpeg_decode_scan(s, nb_components,
1342 prev_shift, point_transform,
1343 mb_bitmask, reference)) < 0)
1348 if (s->interlaced &&
1349 get_bits_left(&s->gb) > 32 &&
1350 show_bits(&s->gb, 8) == 0xFF) {
1351 GetBitContext bak = s->gb;
1352 align_get_bits(&bak);
1353 if (show_bits(&bak, 16) == 0xFFD1) {
1354 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1356 skip_bits(&s->gb, 16);
1357 s->bottom_field ^= 1;
1366 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1367 return AVERROR_INVALIDDATA;
1370 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1372 if (get_bits(&s->gb, 16) != 4)
1373 return AVERROR_INVALIDDATA;
1374 s->restart_interval = get_bits(&s->gb, 16);
1375 s->restart_count = 0;
1376 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1377 s->restart_interval);
1382 static int mjpeg_decode_app(MJpegDecodeContext *s)
1386 len = get_bits(&s->gb, 16);
1388 return AVERROR_INVALIDDATA;
1389 if (8 * len > get_bits_left(&s->gb))
1390 return AVERROR_INVALIDDATA;
1392 id = get_bits_long(&s->gb, 32);
1395 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1396 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X len=%d\n", id, len);
1398 /* Buggy AVID, it puts EOI only at every 10th frame. */
1399 /* Also, this fourcc is used by non-avid files too, it holds some
1400 information, but it's always present in AVID-created files. */
1401 if (id == AV_RB32("AVI1")) {
1407 4bytes field_size_less_padding
1410 i = get_bits(&s->gb, 8); len--;
1411 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1413 skip_bits(&s->gb, 8);
1414 skip_bits(&s->gb, 32);
1415 skip_bits(&s->gb, 32);
1423 if (id == AV_RB32("JFIF")) {
1424 int t_w, t_h, v1, v2;
1425 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1426 v1 = get_bits(&s->gb, 8);
1427 v2 = get_bits(&s->gb, 8);
1428 skip_bits(&s->gb, 8);
1430 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1431 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1433 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1434 av_log(s->avctx, AV_LOG_INFO,
1435 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1437 s->avctx->sample_aspect_ratio.num,
1438 s->avctx->sample_aspect_ratio.den);
1440 t_w = get_bits(&s->gb, 8);
1441 t_h = get_bits(&s->gb, 8);
1443 /* skip thumbnail */
1444 if (len -10 - (t_w * t_h * 3) > 0)
1445 len -= t_w * t_h * 3;
1451 if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1452 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1453 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1454 skip_bits(&s->gb, 16); /* version */
1455 skip_bits(&s->gb, 16); /* flags0 */
1456 skip_bits(&s->gb, 16); /* flags1 */
1457 skip_bits(&s->gb, 8); /* transform */
1462 if (id == AV_RB32("LJIF")) {
1463 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1464 av_log(s->avctx, AV_LOG_INFO,
1465 "Pegasus lossless jpeg header found\n");
1466 skip_bits(&s->gb, 16); /* version ? */
1467 skip_bits(&s->gb, 16); /* unknown always 0? */
1468 skip_bits(&s->gb, 16); /* unknown always 0? */
1469 skip_bits(&s->gb, 16); /* unknown always 0? */
1470 switch (get_bits(&s->gb, 8)) {
1480 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1485 if (id == AV_RL32("colr") && len > 0) {
1486 s->colr = get_bits(&s->gb, 8);
1487 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1488 av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1492 if (id == AV_RL32("xfrm") && len > 0) {
1493 s->xfrm = get_bits(&s->gb, 8);
1494 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1495 av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1501 if (s->start_code == APP1 && id == AV_RB32("Exif")) {
1502 GetByteContext gbytes;
1503 int ret, le, ifd_offset, bytes_read;
1504 const uint8_t *aligned;
1506 skip_bits(&s->gb, 16); // skip padding
1509 // init byte wise reading
1510 aligned = align_get_bits(&s->gb);
1511 bytestream2_init(&gbytes, aligned, len);
1514 ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
1516 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
1520 bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
1522 // read 0th IFD and store the metadata
1523 // (return values > 0 indicate the presence of subimage metadata)
1524 ret = ff_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
1526 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
1530 bytes_read = bytestream2_tell(&gbytes);
1531 skip_bits(&s->gb, bytes_read << 3);
1538 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1539 id = get_bits_long(&s->gb, 32);
1542 if (id == AV_RB32("mjpg")) {
1544 skip_bits(&s->gb, 32); /* field size */
1545 skip_bits(&s->gb, 32); /* pad field size */
1546 skip_bits(&s->gb, 32); /* next off */
1547 skip_bits(&s->gb, 32); /* quant off */
1548 skip_bits(&s->gb, 32); /* huff off */
1549 skip_bits(&s->gb, 32); /* image off */
1550 skip_bits(&s->gb, 32); /* scan off */
1551 skip_bits(&s->gb, 32); /* data off */
1553 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1554 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1559 /* slow but needed for extreme adobe jpegs */
1561 av_log(s->avctx, AV_LOG_ERROR,
1562 "mjpeg: error, decode_app parser read over the end\n");
1564 skip_bits(&s->gb, 8);
1569 static int mjpeg_decode_com(MJpegDecodeContext *s)
1571 int len = get_bits(&s->gb, 16);
1572 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1573 char *cbuf = av_malloc(len - 1);
1576 for (i = 0; i < len - 2; i++)
1577 cbuf[i] = get_bits(&s->gb, 8);
1578 if (i > 0 && cbuf[i - 1] == '\n')
1583 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1584 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1586 /* buggy avid, it puts EOI only at every 10th frame */
1587 if (!strncmp(cbuf, "AVID", 4)) {
1589 if (len > 14 && cbuf[12] == 1) /* 1 - NTSC, 2 - PAL */
1590 s->interlace_polarity = 1;
1591 } else if (!strcmp(cbuf, "CS=ITU601"))
1593 else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1594 (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1604 /* return the 8 bit start code value and update the search
1605 state. Return -1 if no start code found */
1606 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1608 const uint8_t *buf_ptr;
1613 buf_ptr = *pbuf_ptr;
1614 while (buf_end - buf_ptr > 1) {
1617 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1626 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1627 *pbuf_ptr = buf_ptr;
1631 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1632 const uint8_t **buf_ptr, const uint8_t *buf_end,
1633 const uint8_t **unescaped_buf_ptr,
1634 int *unescaped_buf_size)
1637 start_code = find_marker(buf_ptr, buf_end);
1639 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1641 return AVERROR(ENOMEM);
1643 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1644 if (start_code == SOS && !s->ls) {
1645 const uint8_t *src = *buf_ptr;
1646 uint8_t *dst = s->buffer;
1648 while (src < buf_end) {
1649 uint8_t x = *(src++);
1652 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1654 while (src < buf_end && x == 0xff)
1657 if (x >= 0xd0 && x <= 0xd7)
1664 *unescaped_buf_ptr = s->buffer;
1665 *unescaped_buf_size = dst - s->buffer;
1666 memset(s->buffer + *unescaped_buf_size, 0,
1667 FF_INPUT_BUFFER_PADDING_SIZE);
1669 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1670 (buf_end - *buf_ptr) - (dst - s->buffer));
1671 } else if (start_code == SOS && s->ls) {
1672 const uint8_t *src = *buf_ptr;
1673 uint8_t *dst = s->buffer;
1681 while (src + t < buf_end) {
1682 uint8_t x = src[t++];
1684 while ((src + t < buf_end) && x == 0xff)
1693 init_put_bits(&pb, dst, t);
1695 /* unescape bitstream */
1697 uint8_t x = src[b++];
1698 put_bits(&pb, 8, x);
1701 put_bits(&pb, 7, x);
1705 flush_put_bits(&pb);
1707 *unescaped_buf_ptr = dst;
1708 *unescaped_buf_size = (bit_count + 7) >> 3;
1709 memset(s->buffer + *unescaped_buf_size, 0,
1710 FF_INPUT_BUFFER_PADDING_SIZE);
1712 *unescaped_buf_ptr = *buf_ptr;
1713 *unescaped_buf_size = buf_end - *buf_ptr;
1719 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1722 const uint8_t *buf = avpkt->data;
1723 int buf_size = avpkt->size;
1724 MJpegDecodeContext *s = avctx->priv_data;
1725 const uint8_t *buf_end, *buf_ptr;
1726 const uint8_t *unescaped_buf_ptr;
1728 int unescaped_buf_size;
1733 av_dict_free(&s->exif_metadata);
1736 buf_end = buf + buf_size;
1737 while (buf_ptr < buf_end) {
1738 /* find start next marker */
1739 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1741 &unescaped_buf_size);
1743 if (start_code < 0) {
1745 } else if (unescaped_buf_size > INT_MAX / 8) {
1746 av_log(avctx, AV_LOG_ERROR,
1747 "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1748 start_code, unescaped_buf_size, buf_size);
1749 return AVERROR_INVALIDDATA;
1751 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1752 start_code, buf_end - buf_ptr);
1754 ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1757 av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1761 s->start_code = start_code;
1762 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1763 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1765 /* process markers */
1766 if (start_code >= 0xd0 && start_code <= 0xd7)
1767 av_log(avctx, AV_LOG_DEBUG,
1768 "restart marker: %d\n", start_code & 0x0f);
1770 else if (start_code >= APP0 && start_code <= APP15)
1771 mjpeg_decode_app(s);
1773 else if (start_code == COM)
1774 mjpeg_decode_com(s);
1778 if (!CONFIG_JPEGLS_DECODER &&
1779 (start_code == SOF48 || start_code == LSE)) {
1780 av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1781 return AVERROR(ENOSYS);
1784 switch (start_code) {
1786 s->restart_interval = 0;
1787 s->restart_count = 0;
1788 /* nothing to do on SOI */
1791 ff_mjpeg_decode_dqt(s);
1794 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1795 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1804 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1811 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1818 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1825 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1829 if (!CONFIG_JPEGLS_DECODER ||
1830 (ret = ff_jpegls_decode_lse(s)) < 0)
1836 if (!s->got_picture) {
1837 av_log(avctx, AV_LOG_WARNING,
1838 "Found EOI before any SOF, ignoring\n");
1841 if (s->interlaced) {
1842 s->bottom_field ^= 1;
1843 /* if not bottom field, do not output image yet */
1844 if (s->bottom_field == !s->interlace_polarity)
1847 if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)
1853 int qp = FFMAX3(s->qscale[0],
1856 int qpw = (s->width + 15) / 16;
1857 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1859 memset(qp_table_buf->data, qp, qpw);
1860 av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1863 if(avctx->debug & FF_DEBUG_QP)
1864 av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1869 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1870 (avctx->err_recognition & AV_EF_EXPLODE))
1874 mjpeg_decode_dri(s);
1886 av_log(avctx, AV_LOG_ERROR,
1887 "mjpeg: unsupported coding type (%x)\n", start_code);
1891 /* eof process start code */
1892 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1893 av_log(avctx, AV_LOG_DEBUG,
1894 "marker parser used %d bytes (%d bits)\n",
1895 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1897 if (s->got_picture) {
1898 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1901 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1902 return AVERROR_INVALIDDATA;
1908 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1909 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1910 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1911 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1912 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1913 for (i = 0; i < s->chroma_height; i++) {
1914 for (index = s->width - 1; index; index--)
1915 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1916 line += s->linesize[s->upscale_h];
1920 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1922 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1923 w = s->width >> hshift;
1924 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1925 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1926 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1927 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1928 for (i = s->height - 1; i; i--) {
1929 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1930 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1932 memcpy(dst, src1, w);
1934 for (index = 0; index < w; index++)
1935 dst[index] = (src1[index] + src2[index]) >> 1;
1937 dst -= s->linesize[s->upscale_v];
1940 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1942 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1943 for (index=0; index<4; index++) {
1944 uint8_t *dst = s->picture_ptr->data[index];
1947 if(index && index<3){
1948 w = FF_CEIL_RSHIFT(w, hshift);
1949 h = FF_CEIL_RSHIFT(h, vshift);
1952 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
1953 for (i=0; i<h/2; i++) {
1955 FFSWAP(int, dst[j], dst2[j]);
1956 dst += s->linesize[index];
1957 dst2 -= s->linesize[index];
1963 av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);
1964 av_dict_free(&s->exif_metadata);
1966 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
1968 // return buf_end - buf_ptr;
1969 return buf_ptr - buf;
1972 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1974 MJpegDecodeContext *s = avctx->priv_data;
1977 if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
1978 av_log(avctx, AV_LOG_INFO, "Single field\n");
1982 av_frame_unref(s->picture_ptr);
1985 av_freep(&s->ljpeg_buffer);
1986 s->ljpeg_buffer_size = 0;
1988 for (i = 0; i < 3; i++) {
1989 for (j = 0; j < 4; j++)
1990 ff_free_vlc(&s->vlcs[i][j]);
1992 for (i = 0; i < MAX_COMPONENTS; i++) {
1993 av_freep(&s->blocks[i]);
1994 av_freep(&s->last_nnz[i]);
1996 av_dict_free(&s->exif_metadata);
2000 static void decode_flush(AVCodecContext *avctx)
2002 MJpegDecodeContext *s = avctx->priv_data;
2006 #if CONFIG_MJPEG_DECODER
2007 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
2008 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2009 static const AVOption options[] = {
2010 { "extern_huff", "Use external huffman table.",
2011 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
2015 static const AVClass mjpegdec_class = {
2016 .class_name = "MJPEG decoder",
2017 .item_name = av_default_item_name,
2019 .version = LIBAVUTIL_VERSION_INT,
2022 AVCodec ff_mjpeg_decoder = {
2024 .type = AVMEDIA_TYPE_VIDEO,
2025 .id = AV_CODEC_ID_MJPEG,
2026 .priv_data_size = sizeof(MJpegDecodeContext),
2027 .init = ff_mjpeg_decode_init,
2028 .close = ff_mjpeg_decode_end,
2029 .decode = ff_mjpeg_decode_frame,
2030 .flush = decode_flush,
2031 .capabilities = CODEC_CAP_DR1,
2033 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
2034 .priv_class = &mjpegdec_class,
2037 #if CONFIG_THP_DECODER
2038 AVCodec ff_thp_decoder = {
2040 .type = AVMEDIA_TYPE_VIDEO,
2041 .id = AV_CODEC_ID_THP,
2042 .priv_data_size = sizeof(MJpegDecodeContext),
2043 .init = ff_mjpeg_decode_init,
2044 .close = ff_mjpeg_decode_end,
2045 .decode = ff_mjpeg_decode_frame,
2046 .flush = decode_flush,
2047 .capabilities = CODEC_CAP_DR1,
2049 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),