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 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
45 const uint8_t *val_table, int nb_codes,
46 int use_static, int is_ac)
48 uint8_t huff_size[256] = { 0 };
49 uint16_t huff_code[256];
50 uint16_t huff_sym[256];
53 av_assert0(nb_codes <= 256);
55 ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
57 for (i = 0; i < 256; i++)
58 huff_sym[i] = i + 16 * is_ac;
61 huff_sym[0] = 16 * 256;
63 return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
64 huff_code, 2, 2, huff_sym, 2, 2, use_static);
67 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
69 build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
70 avpriv_mjpeg_val_dc, 12, 0, 0);
71 build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
72 avpriv_mjpeg_val_dc, 12, 0, 0);
73 build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
74 avpriv_mjpeg_val_ac_luminance, 251, 0, 1);
75 build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
76 avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);
77 build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
78 avpriv_mjpeg_val_ac_luminance, 251, 0, 0);
79 build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
80 avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);
83 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
85 MJpegDecodeContext *s = avctx->priv_data;
88 s->picture_ptr = &s->picture;
89 avcodec_get_frame_defaults(&s->picture);
92 ff_hpeldsp_init(&s->hdsp, avctx->flags);
93 ff_dsputil_init(&s->dsp, avctx);
94 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
100 s->org_height = avctx->coded_height;
101 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
103 build_basic_mjpeg_vlc(s);
105 if (s->extern_huff) {
106 av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
107 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
108 if (ff_mjpeg_decode_dht(s)) {
109 av_log(avctx, AV_LOG_ERROR,
110 "error using external huffman table, switching back to internal\n");
111 build_basic_mjpeg_vlc(s);
114 if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
115 s->interlace_polarity = 1; /* bottom field first */
116 av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
118 if (avctx->codec->id == AV_CODEC_ID_AMV)
125 /* quantize tables */
126 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
128 int len, index, i, j;
130 len = get_bits(&s->gb, 16) - 2;
133 int pr = get_bits(&s->gb, 4);
135 av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
136 return AVERROR_INVALIDDATA;
138 index = get_bits(&s->gb, 4);
141 av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
142 /* read quant table */
143 for (i = 0; i < 64; i++) {
144 j = s->scantable.permutated[i];
145 s->quant_matrixes[index][j] = get_bits(&s->gb, pr ? 16 : 8);
148 // XXX FIXME finetune, and perhaps add dc too
149 s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
150 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
151 av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
152 index, s->qscale[index]);
158 /* decode huffman tables and build VLC decoders */
159 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
161 int len, index, i, class, n, v, code_max;
162 uint8_t bits_table[17];
163 uint8_t val_table[256];
166 len = get_bits(&s->gb, 16) - 2;
170 return AVERROR_INVALIDDATA;
171 class = get_bits(&s->gb, 4);
173 return AVERROR_INVALIDDATA;
174 index = get_bits(&s->gb, 4);
176 return AVERROR_INVALIDDATA;
178 for (i = 1; i <= 16; i++) {
179 bits_table[i] = get_bits(&s->gb, 8);
183 if (len < n || n > 256)
184 return AVERROR_INVALIDDATA;
187 for (i = 0; i < n; i++) {
188 v = get_bits(&s->gb, 8);
195 /* build VLC and flush previous vlc if present */
196 ff_free_vlc(&s->vlcs[class][index]);
197 av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
198 class, index, code_max + 1);
199 if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
200 code_max + 1, 0, class > 0)) < 0)
204 ff_free_vlc(&s->vlcs[2][index]);
205 if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
206 code_max + 1, 0, 0)) < 0)
213 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
215 int len, nb_components, i, width, height, pix_fmt_id;
216 int h_count[MAX_COMPONENTS];
217 int v_count[MAX_COMPONENTS];
220 s->upscale_h = s->upscale_v = 0;
222 /* XXX: verify len field validity */
223 len = get_bits(&s->gb, 16);
224 s->bits = get_bits(&s->gb, 8);
228 if (s->bits == 9 && !s->pegasus_rct)
229 s->rct = 1; // FIXME ugly
231 if (s->bits != 8 && !s->lossless) {
232 av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
236 if(s->lossless && s->avctx->lowres){
237 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
241 height = get_bits(&s->gb, 16);
242 width = get_bits(&s->gb, 16);
244 // HACK for odd_height.mov
245 if (s->interlaced && s->width == width && s->height == height + 1)
248 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
249 if (av_image_check_size(width, height, 0, s->avctx))
250 return AVERROR_INVALIDDATA;
252 nb_components = get_bits(&s->gb, 8);
253 if (nb_components <= 0 ||
254 nb_components > MAX_COMPONENTS)
256 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
257 if (nb_components != s->nb_components) {
258 av_log(s->avctx, AV_LOG_ERROR, "nb_components changing in interlaced picture\n");
259 return AVERROR_INVALIDDATA;
262 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
263 avpriv_report_missing_feature(s->avctx,
264 "JPEG-LS that is not <= 8 "
265 "bits/component or 16-bit gray");
266 return AVERROR_PATCHWELCOME;
268 s->nb_components = nb_components;
271 memset(h_count, 0, sizeof(h_count));
272 memset(v_count, 0, sizeof(v_count));
273 for (i = 0; i < nb_components; i++) {
275 s->component_id[i] = get_bits(&s->gb, 8) - 1;
276 h_count[i] = get_bits(&s->gb, 4);
277 v_count[i] = get_bits(&s->gb, 4);
278 /* compute hmax and vmax (only used in interleaved case) */
279 if (h_count[i] > s->h_max)
280 s->h_max = h_count[i];
281 if (v_count[i] > s->v_max)
282 s->v_max = v_count[i];
283 if (!h_count[i] || !v_count[i]) {
284 av_log(s->avctx, AV_LOG_ERROR, "h/v_count is 0\n");
287 s->quant_index[i] = get_bits(&s->gb, 8);
288 if (s->quant_index[i] >= 4) {
289 av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
290 return AVERROR_INVALIDDATA;
292 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
293 i, h_count[i], v_count[i],
294 s->component_id[i], s->quant_index[i]);
297 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
298 avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
299 return AVERROR_PATCHWELCOME;
303 /* if different size, realloc/alloc picture */
304 if ( width != s->width || height != s->height
305 || memcmp(s->h_count, h_count, sizeof(h_count))
306 || memcmp(s->v_count, v_count, sizeof(v_count))) {
310 memcpy(s->h_count, h_count, sizeof(h_count));
311 memcpy(s->v_count, v_count, sizeof(v_count));
315 /* test interlaced mode */
316 if (s->first_picture &&
317 s->org_height != 0 &&
318 s->height < ((s->org_height * 3) / 4)) {
320 s->bottom_field = s->interlace_polarity;
321 s->picture_ptr->interlaced_frame = 1;
322 s->picture_ptr->top_field_first = !s->interlace_polarity;
326 avcodec_set_dimensions(s->avctx, width, height);
328 s->first_picture = 0;
331 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
332 if (s->progressive) {
333 avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
334 return AVERROR_INVALIDDATA;
337 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && nb_components==3)
339 else if (!s->lossless)
341 /* XXX: not complete test ! */
342 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
343 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
344 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
345 (s->h_count[3] << 4) | s->v_count[3];
346 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
347 /* NOTE we do not allocate pictures large enough for the possible
348 * padding of h/v_count being 4 */
349 if (!(pix_fmt_id & 0xD0D0D0D0))
350 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
351 if (!(pix_fmt_id & 0x0D0D0D0D))
352 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
354 switch (pix_fmt_id) {
357 s->avctx->pix_fmt = AV_PIX_FMT_BGR24;
359 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
360 s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
362 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
363 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
366 av_assert0(s->nb_components == 3);
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;
373 s->upscale_h = (pix_fmt_id == 0x22122100);
374 s->chroma_height = s->height;
378 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
379 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
380 s->upscale_v = (pix_fmt_id == 0x22211200);
382 s->chroma_height = s->height;
385 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
386 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
389 s->chroma_height = s->height / 2;
401 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
403 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
408 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
409 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
410 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
411 s->chroma_height = s->height / 2;
414 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
415 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
419 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
420 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
421 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
424 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
425 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
428 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
429 return AVERROR_PATCHWELCOME;
431 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
432 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
433 return AVERROR_PATCHWELCOME;
436 s->upscale_h = s->upscale_v = 0;
437 if (s->nb_components > 1)
438 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
439 else if (s->bits <= 8)
440 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
442 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
445 av_frame_unref(s->picture_ptr);
446 if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
448 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
449 s->picture_ptr->key_frame = 1;
452 for (i = 0; i < 3; i++)
453 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
455 av_dlog(s->avctx, "%d %d %d %d %d %d\n",
456 s->width, s->height, s->linesize[0], s->linesize[1],
457 s->interlaced, s->avctx->height);
459 if (len != (8 + (3 * nb_components)))
460 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
463 if (s->rgb && !s->lossless && !s->ls) {
464 av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
465 return AVERROR_PATCHWELCOME;
468 /* totally blank picture as progressive JPEG will only add details to it */
469 if (s->progressive) {
470 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
471 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
472 for (i = 0; i < s->nb_components; i++) {
473 int size = bw * bh * s->h_count[i] * s->v_count[i];
474 av_freep(&s->blocks[i]);
475 av_freep(&s->last_nnz[i]);
476 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
477 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
478 s->block_stride[i] = bw * s->h_count[i];
480 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
485 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
488 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
490 av_log(s->avctx, AV_LOG_WARNING,
491 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
492 0, dc_index, &s->vlcs[0][dc_index]);
497 return get_xbits(&s->gb, code);
502 /* decode block and dequantize */
503 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
504 int dc_index, int ac_index, int16_t *quant_matrix)
506 int code, i, j, level, val;
509 val = mjpeg_decode_dc(s, dc_index);
511 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
512 return AVERROR_INVALIDDATA;
514 val = val * quant_matrix[0] + s->last_dc[component];
515 s->last_dc[component] = val;
519 {OPEN_READER(re, &s->gb);
521 UPDATE_CACHE(re, &s->gb);
522 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
524 i += ((unsigned)code) >> 4;
527 if (code > MIN_CACHE_BITS - 16)
528 UPDATE_CACHE(re, &s->gb);
531 int cache = GET_CACHE(re, &s->gb);
532 int sign = (~cache) >> 31;
533 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
536 LAST_SKIP_BITS(re, &s->gb, code);
539 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
540 return AVERROR_INVALIDDATA;
542 j = s->scantable.permutated[i];
543 block[j] = level * quant_matrix[j];
546 CLOSE_READER(re, &s->gb);}
551 static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
552 int component, int dc_index,
553 int16_t *quant_matrix, int Al)
556 s->dsp.clear_block(block);
557 val = mjpeg_decode_dc(s, dc_index);
559 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
560 return AVERROR_INVALIDDATA;
562 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
563 s->last_dc[component] = val;
568 /* decode block and dequantize - progressive JPEG version */
569 static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
570 uint8_t *last_nnz, int ac_index,
571 int16_t *quant_matrix,
572 int ss, int se, int Al, int *EOBRUN)
574 int code, i, j, level, val, run;
582 OPEN_READER(re, &s->gb);
583 for (i = ss; ; i++) {
584 UPDATE_CACHE(re, &s->gb);
585 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
587 run = ((unsigned) code) >> 4;
591 if (code > MIN_CACHE_BITS - 16)
592 UPDATE_CACHE(re, &s->gb);
595 int cache = GET_CACHE(re, &s->gb);
596 int sign = (~cache) >> 31;
597 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
600 LAST_SKIP_BITS(re, &s->gb, code);
604 j = s->scantable.permutated[se];
605 block[j] = level * quant_matrix[j] << Al;
608 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
609 return AVERROR_INVALIDDATA;
611 j = s->scantable.permutated[i];
612 block[j] = level * quant_matrix[j] << Al;
614 if (run == 0xF) {// ZRL - skip 15 coefficients
617 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
618 return AVERROR_INVALIDDATA;
623 UPDATE_CACHE(re, &s->gb);
624 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
625 LAST_SKIP_BITS(re, &s->gb, run);
632 CLOSE_READER(re, &s->gb);
641 #define REFINE_BIT(j) { \
642 UPDATE_CACHE(re, &s->gb); \
643 sign = block[j] >> 15; \
644 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
645 ((quant_matrix[j] ^ sign) - sign) << Al; \
646 LAST_SKIP_BITS(re, &s->gb, 1); \
654 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
659 j = s->scantable.permutated[i]; \
662 else if (run-- == 0) \
666 /* decode block and dequantize - progressive JPEG refinement pass */
667 static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
669 int ac_index, int16_t *quant_matrix,
670 int ss, int se, int Al, int *EOBRUN)
672 int code, i = ss, j, sign, val, run;
673 int last = FFMIN(se, *last_nnz);
675 OPEN_READER(re, &s->gb);
680 UPDATE_CACHE(re, &s->gb);
681 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
684 run = ((unsigned) code) >> 4;
685 UPDATE_CACHE(re, &s->gb);
686 val = SHOW_UBITS(re, &s->gb, 1);
687 LAST_SKIP_BITS(re, &s->gb, 1);
689 j = s->scantable.permutated[i];
691 block[j] = ((quant_matrix[j]^val) - val) << Al;
695 CLOSE_READER(re, &s->gb);
699 run = ((unsigned) code) >> 4;
706 UPDATE_CACHE(re, &s->gb);
707 run += SHOW_UBITS(re, &s->gb, val);
708 LAST_SKIP_BITS(re, &s->gb, val);
720 for (; i <= last; i++) {
721 j = s->scantable.permutated[i];
725 CLOSE_READER(re, &s->gb);
732 static void handle_rstn(MJpegDecodeContext *s, int nb_components)
735 if (s->restart_interval) {
737 if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
738 align_get_bits(&s->gb);
739 for (i = 0; i < nb_components; i++) /* reset dc */
740 s->last_dc[i] = 1024;
743 i = 8 + ((-get_bits_count(&s->gb)) & 7);
745 if (s->restart_count == 0) {
746 if( show_bits(&s->gb, i) == (1 << i) - 1
747 || show_bits(&s->gb, i) == 0xFF) {
748 int pos = get_bits_count(&s->gb);
749 align_get_bits(&s->gb);
750 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
751 skip_bits(&s->gb, 8);
752 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
753 for (i = 0; i < nb_components; i++) /* reset dc */
754 s->last_dc[i] = 1024;
756 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
762 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
765 uint16_t (*buffer)[4];
766 int left[3], top[3], topleft[3];
767 const int linesize = s->linesize[0];
768 const int mask = (1 << s->bits) - 1;
772 s->restart_count = s->restart_interval;
774 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
775 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
776 buffer = s->ljpeg_buffer;
778 for (i = 0; i < 3; i++)
779 buffer[0][i] = 1 << (s->bits - 1);
781 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
782 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
784 if (s->interlaced && s->bottom_field)
785 ptr += linesize >> 1;
787 for (i = 0; i < 3; i++)
788 top[i] = left[i] = topleft[i] = buffer[0][i];
790 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
791 int modified_predictor = predictor;
793 if (s->restart_interval && !s->restart_count){
794 s->restart_count = s->restart_interval;
798 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
800 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
801 modified_predictor = 1;
803 for (i=0;i<nb_components;i++) {
807 top[i] = buffer[mb_x][i];
809 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
811 dc = mjpeg_decode_dc(s, s->dc_index[i]);
815 left[i] = buffer[mb_x][i] =
816 mask & (pred + (dc << point_transform));
819 if (s->restart_interval && !--s->restart_count) {
820 align_get_bits(&s->gb);
821 skip_bits(&s->gb, 16); /* skip RSTn */
826 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
827 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
828 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
829 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
831 } else if (s->pegasus_rct) {
832 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
833 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
834 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
835 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
838 for(i=0; i<nb_components; i++) {
839 int c= s->comp_index[i];
840 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
841 ptr[3*mb_x+2-c] = buffer[mb_x][i];
849 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int nb_components, int predictor,
853 int bits= (s->bits+7)&~7;
857 point_transform += bits - s->bits;
859 av_assert0(nb_components>=1 && nb_components<=3);
861 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
862 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
863 if (s->restart_interval && !s->restart_count){
864 s->restart_count = s->restart_interval;
869 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
870 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
871 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
872 for (i = 0; i < nb_components; i++) {
875 int n, h, v, x, y, c, j, linesize;
877 c = s->comp_index[i];
882 linesize= s->linesize[c];
884 if(bits>8) linesize /= 2;
889 dc = mjpeg_decode_dc(s, s->dc_index[i]);
893 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
896 pred= 1 << (bits - 1);
902 pred= ptr[-linesize];
904 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
908 if (s->interlaced && s->bottom_field)
909 ptr += linesize >> 1;
910 pred &= (-1)<<(8-s->bits);
911 *ptr= pred + (dc << point_transform);
913 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
916 pred= 1 << (bits - 1);
922 pred= ptr16[-linesize];
924 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
928 if (s->interlaced && s->bottom_field)
929 ptr16 += linesize >> 1;
930 pred &= (-1)<<(16-s->bits);
931 *ptr16= pred + (dc << point_transform);
940 for (i = 0; i < nb_components; i++) {
943 int n, h, v, x, y, c, j, linesize, dc;
945 c = s->comp_index[i];
950 linesize = s->linesize[c];
952 if(bits>8) linesize /= 2;
954 for (j = 0; j < n; j++) {
957 dc = mjpeg_decode_dc(s, s->dc_index[i]);
961 ptr = s->picture.data[c] +
962 (linesize * (v * mb_y + y)) +
963 (h * mb_x + x); //FIXME optimize this crap
964 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
966 pred &= (-1)<<(8-s->bits);
967 *ptr = pred + (dc << point_transform);
969 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
970 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
972 pred &= (-1)<<(16-s->bits);
973 *ptr16= pred + (dc << point_transform);
983 if (s->restart_interval && !--s->restart_count) {
984 align_get_bits(&s->gb);
985 skip_bits(&s->gb, 16); /* skip RSTn */
992 static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
993 uint8_t *dst, const uint8_t *src,
994 int linesize, int lowres)
997 case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
999 case 1: copy_block4(dst, src, linesize, linesize, 4);
1001 case 2: copy_block2(dst, src, linesize, linesize, 2);
1003 case 3: *dst = *src;
1008 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1009 int Al, const uint8_t *mb_bitmask,
1010 const AVFrame *reference)
1013 uint8_t *data[MAX_COMPONENTS];
1014 const uint8_t *reference_data[MAX_COMPONENTS];
1015 int linesize[MAX_COMPONENTS];
1016 GetBitContext mb_bitmask_gb;
1019 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1021 if (s->flipped && s->avctx->lowres) {
1022 av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
1026 for (i = 0; i < nb_components; i++) {
1027 int c = s->comp_index[i];
1028 data[c] = s->picture_ptr->data[c];
1029 reference_data[c] = reference ? reference->data[c] : NULL;
1030 linesize[c] = s->linesize[c];
1031 s->coefs_finished[c] |= 1;
1032 if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1033 // picture should be flipped upside-down for this codec
1034 int offset = (linesize[c] * (s->v_scount[i] *
1035 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
1037 reference_data[c] += offset;
1042 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1043 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1044 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1046 if (s->restart_interval && !s->restart_count)
1047 s->restart_count = s->restart_interval;
1049 if (get_bits_left(&s->gb) < 0) {
1050 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1051 -get_bits_left(&s->gb));
1052 return AVERROR_INVALIDDATA;
1054 for (i = 0; i < nb_components; i++) {
1056 int n, h, v, x, y, c, j;
1058 n = s->nb_blocks[i];
1059 c = s->comp_index[i];
1064 for (j = 0; j < n; j++) {
1065 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1066 (h * mb_x + x) * 8) >> s->avctx->lowres);
1068 if (s->interlaced && s->bottom_field)
1069 block_offset += linesize[c] >> 1;
1070 ptr = data[c] + block_offset;
1071 if (!s->progressive) {
1073 mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1074 linesize[c], s->avctx->lowres);
1077 s->dsp.clear_block(s->block);
1078 if (decode_block(s, s->block, i,
1079 s->dc_index[i], s->ac_index[i],
1080 s->quant_matrixes[s->quant_index[c]]) < 0) {
1081 av_log(s->avctx, AV_LOG_ERROR,
1082 "error y=%d x=%d\n", mb_y, mb_x);
1083 return AVERROR_INVALIDDATA;
1085 s->dsp.idct_put(ptr, linesize[c], s->block);
1088 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1090 int16_t *block = s->blocks[c][block_idx];
1092 block[0] += get_bits1(&s->gb) *
1093 s->quant_matrixes[s->quant_index[c]][0] << Al;
1094 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1095 s->quant_matrixes[s->quant_index[c]],
1097 av_log(s->avctx, AV_LOG_ERROR,
1098 "error y=%d x=%d\n", mb_y, mb_x);
1099 return AVERROR_INVALIDDATA;
1102 av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1103 av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1104 mb_x, mb_y, x, y, c, s->bottom_field,
1105 (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1113 handle_rstn(s, nb_components);
1119 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1120 int se, int Ah, int Al)
1124 int c = s->comp_index[0];
1125 uint8_t *data = s->picture.data[c];
1126 int linesize = s->linesize[c];
1128 int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
1131 av_log(s->avctx, AV_LOG_ERROR, "SE %d is too large\n", se);
1132 return AVERROR_INVALIDDATA;
1136 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1137 last_scan = !~s->coefs_finished[c];
1140 if (s->interlaced && s->bottom_field)
1141 data += linesize >> 1;
1143 s->restart_count = 0;
1145 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1146 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1147 int block_idx = mb_y * s->block_stride[c];
1148 int16_t (*block)[64] = &s->blocks[c][block_idx];
1149 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1150 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1152 if (s->restart_interval && !s->restart_count)
1153 s->restart_count = s->restart_interval;
1156 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1157 quant_matrix, ss, se, Al, &EOBRUN);
1159 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1160 quant_matrix, ss, se, Al, &EOBRUN);
1162 av_log(s->avctx, AV_LOG_ERROR,
1163 "error y=%d x=%d\n", mb_y, mb_x);
1164 return AVERROR_INVALIDDATA;
1168 s->dsp.idct_put(ptr, linesize, *block);
1169 ptr += 8 >> s->avctx->lowres;
1177 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1178 const AVFrame *reference)
1180 int len, nb_components, i, h, v, predictor, point_transform;
1182 const int block_size = s->lossless ? 1 : 8;
1183 int ilv, prev_shift;
1185 if (!s->got_picture) {
1186 av_log(s->avctx, AV_LOG_WARNING,
1187 "Can not process SOS before SOF, skipping\n");
1191 av_assert0(s->picture_ptr->data[0]);
1192 /* XXX: verify len field validity */
1193 len = get_bits(&s->gb, 16);
1194 nb_components = get_bits(&s->gb, 8);
1195 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1196 av_log(s->avctx, AV_LOG_ERROR,
1197 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1198 return AVERROR_PATCHWELCOME;
1200 if (len != 6 + 2 * nb_components) {
1201 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1202 return AVERROR_INVALIDDATA;
1204 for (i = 0; i < nb_components; i++) {
1205 id = get_bits(&s->gb, 8) - 1;
1206 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1207 /* find component index */
1208 for (index = 0; index < s->nb_components; index++)
1209 if (id == s->component_id[index])
1211 if (index == s->nb_components) {
1212 av_log(s->avctx, AV_LOG_ERROR,
1213 "decode_sos: index(%d) out of components\n", index);
1214 return AVERROR_INVALIDDATA;
1216 /* Metasoft MJPEG codec has Cb and Cr swapped */
1217 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1218 && nb_components == 3 && s->nb_components == 3 && i)
1221 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1223 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1224 index = (index+2)%3;
1226 s->comp_index[i] = index;
1228 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1229 s->h_scount[i] = s->h_count[index];
1230 s->v_scount[i] = s->v_count[index];
1232 s->dc_index[i] = get_bits(&s->gb, 4);
1233 s->ac_index[i] = get_bits(&s->gb, 4);
1235 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1236 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1238 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))
1242 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1243 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1244 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1245 prev_shift = get_bits(&s->gb, 4); /* Ah */
1246 point_transform = get_bits(&s->gb, 4); /* Al */
1248 prev_shift = point_transform = 0;
1250 if (nb_components > 1) {
1251 /* interleaved stream */
1252 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1253 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1254 } else if (!s->ls) { /* skip this for JPEG-LS */
1255 h = s->h_max / s->h_scount[0];
1256 v = s->v_max / s->v_scount[0];
1257 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1258 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1259 s->nb_blocks[0] = 1;
1264 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1265 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1266 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1267 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1268 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1271 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1272 for (i = s->mjpb_skiptosod; i > 0; i--)
1273 skip_bits(&s->gb, 8);
1276 for (i = 0; i < nb_components; i++)
1277 s->last_dc[i] = 1024;
1280 av_assert0(s->picture_ptr == &s->picture);
1281 if (CONFIG_JPEGLS_DECODER && s->ls) {
1283 // reset_ls_coding_parameters(s, 0);
1285 if ((ret = ff_jpegls_decode_picture(s, predictor,
1286 point_transform, ilv)) < 0)
1290 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1293 if ((ret = ljpeg_decode_yuv_scan(s, nb_components, predictor, point_transform)) < 0)
1298 if (s->progressive && predictor) {
1299 av_assert0(s->picture_ptr == &s->picture);
1300 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1302 point_transform)) < 0)
1305 if ((ret = mjpeg_decode_scan(s, nb_components,
1306 prev_shift, point_transform,
1307 mb_bitmask, reference)) < 0)
1312 if (s->interlaced &&
1313 get_bits_left(&s->gb) > 32 &&
1314 show_bits(&s->gb, 8) == 0xFF) {
1315 GetBitContext bak = s->gb;
1316 align_get_bits(&bak);
1317 if (show_bits(&bak, 16) == 0xFFD1) {
1318 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1320 skip_bits(&s->gb, 16);
1321 s->bottom_field ^= 1;
1330 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1331 return AVERROR_INVALIDDATA;
1334 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1336 if (get_bits(&s->gb, 16) != 4)
1337 return AVERROR_INVALIDDATA;
1338 s->restart_interval = get_bits(&s->gb, 16);
1339 s->restart_count = 0;
1340 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1341 s->restart_interval);
1346 static int mjpeg_decode_app(MJpegDecodeContext *s)
1350 len = get_bits(&s->gb, 16);
1352 return AVERROR_INVALIDDATA;
1353 if (8 * len > get_bits_left(&s->gb))
1354 return AVERROR_INVALIDDATA;
1356 id = get_bits_long(&s->gb, 32);
1359 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1360 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1362 /* Buggy AVID, it puts EOI only at every 10th frame. */
1363 /* Also, this fourcc is used by non-avid files too, it holds some
1364 information, but it's always present in AVID-created files. */
1365 if (id == AV_RB32("AVI1")) {
1371 4bytes field_size_less_padding
1374 i = get_bits(&s->gb, 8); len--;
1375 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1377 skip_bits(&s->gb, 8);
1378 skip_bits(&s->gb, 32);
1379 skip_bits(&s->gb, 32);
1387 if (id == AV_RB32("JFIF")) {
1388 int t_w, t_h, v1, v2;
1389 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1390 v1 = get_bits(&s->gb, 8);
1391 v2 = get_bits(&s->gb, 8);
1392 skip_bits(&s->gb, 8);
1394 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1395 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1397 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1398 av_log(s->avctx, AV_LOG_INFO,
1399 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1401 s->avctx->sample_aspect_ratio.num,
1402 s->avctx->sample_aspect_ratio.den);
1404 t_w = get_bits(&s->gb, 8);
1405 t_h = get_bits(&s->gb, 8);
1407 /* skip thumbnail */
1408 if (len -10 - (t_w * t_h * 3) > 0)
1409 len -= t_w * t_h * 3;
1415 if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1416 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1417 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1418 skip_bits(&s->gb, 16); /* version */
1419 skip_bits(&s->gb, 16); /* flags0 */
1420 skip_bits(&s->gb, 16); /* flags1 */
1421 skip_bits(&s->gb, 8); /* transform */
1426 if (id == AV_RB32("LJIF")) {
1427 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1428 av_log(s->avctx, AV_LOG_INFO,
1429 "Pegasus lossless jpeg header found\n");
1430 skip_bits(&s->gb, 16); /* version ? */
1431 skip_bits(&s->gb, 16); /* unknown always 0? */
1432 skip_bits(&s->gb, 16); /* unknown always 0? */
1433 skip_bits(&s->gb, 16); /* unknown always 0? */
1434 switch (get_bits(&s->gb, 8)) {
1444 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1451 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1452 id = get_bits_long(&s->gb, 32);
1455 if (id == AV_RB32("mjpg")) {
1457 skip_bits(&s->gb, 32); /* field size */
1458 skip_bits(&s->gb, 32); /* pad field size */
1459 skip_bits(&s->gb, 32); /* next off */
1460 skip_bits(&s->gb, 32); /* quant off */
1461 skip_bits(&s->gb, 32); /* huff off */
1462 skip_bits(&s->gb, 32); /* image off */
1463 skip_bits(&s->gb, 32); /* scan off */
1464 skip_bits(&s->gb, 32); /* data off */
1466 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1467 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1472 /* slow but needed for extreme adobe jpegs */
1474 av_log(s->avctx, AV_LOG_ERROR,
1475 "mjpeg: error, decode_app parser read over the end\n");
1477 skip_bits(&s->gb, 8);
1482 static int mjpeg_decode_com(MJpegDecodeContext *s)
1484 int len = get_bits(&s->gb, 16);
1485 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1486 char *cbuf = av_malloc(len - 1);
1489 for (i = 0; i < len - 2; i++)
1490 cbuf[i] = get_bits(&s->gb, 8);
1491 if (i > 0 && cbuf[i - 1] == '\n')
1496 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1497 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1499 /* buggy avid, it puts EOI only at every 10th frame */
1500 if (!strcmp(cbuf, "AVID")) {
1502 } else if (!strcmp(cbuf, "CS=ITU601"))
1504 else if ((len > 31 && !strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1505 (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1515 /* return the 8 bit start code value and update the search
1516 state. Return -1 if no start code found */
1517 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1519 const uint8_t *buf_ptr;
1524 buf_ptr = *pbuf_ptr;
1525 while (buf_ptr < buf_end) {
1528 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1536 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1537 *pbuf_ptr = buf_ptr;
1541 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1542 const uint8_t **buf_ptr, const uint8_t *buf_end,
1543 const uint8_t **unescaped_buf_ptr,
1544 int *unescaped_buf_size)
1547 start_code = find_marker(buf_ptr, buf_end);
1549 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1551 return AVERROR(ENOMEM);
1553 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1554 if (start_code == SOS && !s->ls) {
1555 const uint8_t *src = *buf_ptr;
1556 uint8_t *dst = s->buffer;
1558 while (src < buf_end) {
1559 uint8_t x = *(src++);
1562 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1564 while (src < buf_end && x == 0xff)
1567 if (x >= 0xd0 && x <= 0xd7)
1574 *unescaped_buf_ptr = s->buffer;
1575 *unescaped_buf_size = dst - s->buffer;
1576 memset(s->buffer + *unescaped_buf_size, 0,
1577 FF_INPUT_BUFFER_PADDING_SIZE);
1579 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1580 (buf_end - *buf_ptr) - (dst - s->buffer));
1581 } else if (start_code == SOS && s->ls) {
1582 const uint8_t *src = *buf_ptr;
1583 uint8_t *dst = s->buffer;
1591 while (src + t < buf_end) {
1592 uint8_t x = src[t++];
1594 while ((src + t < buf_end) && x == 0xff)
1603 init_put_bits(&pb, dst, t);
1605 /* unescape bitstream */
1607 uint8_t x = src[b++];
1608 put_bits(&pb, 8, x);
1611 put_bits(&pb, 7, x);
1615 flush_put_bits(&pb);
1617 *unescaped_buf_ptr = dst;
1618 *unescaped_buf_size = (bit_count + 7) >> 3;
1619 memset(s->buffer + *unescaped_buf_size, 0,
1620 FF_INPUT_BUFFER_PADDING_SIZE);
1622 *unescaped_buf_ptr = *buf_ptr;
1623 *unescaped_buf_size = buf_end - *buf_ptr;
1629 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1632 const uint8_t *buf = avpkt->data;
1633 int buf_size = avpkt->size;
1634 MJpegDecodeContext *s = avctx->priv_data;
1635 const uint8_t *buf_end, *buf_ptr;
1636 const uint8_t *unescaped_buf_ptr;
1638 int unescaped_buf_size;
1644 buf_end = buf + buf_size;
1645 while (buf_ptr < buf_end) {
1646 /* find start next marker */
1647 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1649 &unescaped_buf_size);
1651 if (start_code < 0) {
1653 } else if (unescaped_buf_size > (1U<<28)) {
1654 av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",
1655 start_code, unescaped_buf_size, buf_size);
1656 return AVERROR_INVALIDDATA;
1658 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1659 start_code, buf_end - buf_ptr);
1660 if ((ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size)) < 0) {
1661 av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1665 s->start_code = start_code;
1666 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1667 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1669 /* process markers */
1670 if (start_code >= 0xd0 && start_code <= 0xd7)
1671 av_log(avctx, AV_LOG_DEBUG,
1672 "restart marker: %d\n", start_code & 0x0f);
1674 else if (start_code >= APP0 && start_code <= APP15)
1675 mjpeg_decode_app(s);
1677 else if (start_code == COM)
1678 mjpeg_decode_com(s);
1681 switch (start_code) {
1683 s->restart_interval = 0;
1684 s->restart_count = 0;
1685 /* nothing to do on SOI */
1688 ff_mjpeg_decode_dqt(s);
1691 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1692 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1701 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1708 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1715 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1722 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1726 if (!CONFIG_JPEGLS_DECODER ||
1727 (ret = ff_jpegls_decode_lse(s)) < 0)
1733 if (!s->got_picture) {
1734 av_log(avctx, AV_LOG_WARNING,
1735 "Found EOI before any SOF, ignoring\n");
1738 if (s->interlaced) {
1739 s->bottom_field ^= 1;
1740 /* if not bottom field, do not output image yet */
1741 if (s->bottom_field == !s->interlace_polarity)
1744 if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)
1750 int qp = FFMAX3(s->qscale[0],
1753 int qpw = (s->width + 15) / 16;
1754 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1756 memset(qp_table_buf->data, qp, qpw);
1757 av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1760 if(avctx->debug & FF_DEBUG_QP)
1761 av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1766 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1767 (avctx->err_recognition & AV_EF_EXPLODE))
1771 mjpeg_decode_dri(s);
1783 av_log(avctx, AV_LOG_ERROR,
1784 "mjpeg: unsupported coding type (%x)\n", start_code);
1788 /* eof process start code */
1789 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1790 av_log(avctx, AV_LOG_DEBUG,
1791 "marker parser used %d bytes (%d bits)\n",
1792 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1795 if (s->got_picture) {
1796 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1799 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1800 return AVERROR_INVALIDDATA;
1806 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1807 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1808 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1809 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1810 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1811 for (i = 0; i < s->chroma_height; i++) {
1812 for (index = s->width - 1; index; index--)
1813 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1814 line += s->linesize[s->upscale_h];
1818 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1820 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1821 w = s->width >> hshift;
1822 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1823 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1824 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1825 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1826 for (i = s->height - 1; i; i--) {
1827 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1828 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1830 memcpy(dst, src1, w);
1832 for (index = 0; index < w; index++)
1833 dst[index] = (src1[index] + src2[index]) >> 1;
1835 dst -= s->linesize[s->upscale_v];
1838 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1840 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1841 for (index=0; index<4; index++) {
1842 uint8_t *dst = s->picture_ptr->data[index];
1845 if(index && index<3){
1846 w = -((-w) >> hshift);
1847 h = -((-h) >> vshift);
1850 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
1851 for (i=0; i<h/2; i++) {
1853 FFSWAP(int, dst[j], dst2[j]);
1854 dst += s->linesize[index];
1855 dst2 -= s->linesize[index];
1861 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
1863 // return buf_end - buf_ptr;
1864 return buf_ptr - buf;
1867 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1869 MJpegDecodeContext *s = avctx->priv_data;
1873 av_frame_unref(s->picture_ptr);
1876 av_freep(&s->ljpeg_buffer);
1877 s->ljpeg_buffer_size = 0;
1879 for (i = 0; i < 3; i++) {
1880 for (j = 0; j < 4; j++)
1881 ff_free_vlc(&s->vlcs[i][j]);
1883 for (i = 0; i < MAX_COMPONENTS; i++) {
1884 av_freep(&s->blocks[i]);
1885 av_freep(&s->last_nnz[i]);
1890 static void decode_flush(AVCodecContext *avctx)
1892 MJpegDecodeContext *s = avctx->priv_data;
1896 #if CONFIG_MJPEG_DECODER
1897 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1898 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1899 static const AVOption options[] = {
1900 { "extern_huff", "Use external huffman table.",
1901 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1905 static const AVClass mjpegdec_class = {
1906 .class_name = "MJPEG decoder",
1907 .item_name = av_default_item_name,
1909 .version = LIBAVUTIL_VERSION_INT,
1912 AVCodec ff_mjpeg_decoder = {
1914 .type = AVMEDIA_TYPE_VIDEO,
1915 .id = AV_CODEC_ID_MJPEG,
1916 .priv_data_size = sizeof(MJpegDecodeContext),
1917 .init = ff_mjpeg_decode_init,
1918 .close = ff_mjpeg_decode_end,
1919 .decode = ff_mjpeg_decode_frame,
1920 .flush = decode_flush,
1921 .capabilities = CODEC_CAP_DR1,
1923 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1924 .priv_class = &mjpegdec_class,
1927 #if CONFIG_THP_DECODER
1928 AVCodec ff_thp_decoder = {
1930 .type = AVMEDIA_TYPE_VIDEO,
1931 .id = AV_CODEC_ID_THP,
1932 .priv_data_size = sizeof(MJpegDecodeContext),
1933 .init = ff_mjpeg_decode_init,
1934 .close = ff_mjpeg_decode_end,
1935 .decode = ff_mjpeg_decode_frame,
1936 .flush = decode_flush,
1937 .capabilities = CODEC_CAP_DR1,
1939 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),