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, "nb_components changing in interlaced picture\n");
263 return AVERROR_INVALIDDATA;
266 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
267 avpriv_report_missing_feature(s->avctx,
268 "JPEG-LS that is not <= 8 "
269 "bits/component or 16-bit gray");
270 return AVERROR_PATCHWELCOME;
272 s->nb_components = nb_components;
275 memset(h_count, 0, sizeof(h_count));
276 memset(v_count, 0, sizeof(v_count));
277 for (i = 0; i < nb_components; i++) {
279 s->component_id[i] = get_bits(&s->gb, 8) - 1;
280 h_count[i] = get_bits(&s->gb, 4);
281 v_count[i] = get_bits(&s->gb, 4);
282 /* compute hmax and vmax (only used in interleaved case) */
283 if (h_count[i] > s->h_max)
284 s->h_max = h_count[i];
285 if (v_count[i] > s->v_max)
286 s->v_max = v_count[i];
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 if (!h_count[i] || !v_count[i]) {
293 av_log(s->avctx, AV_LOG_ERROR,
294 "Invalid sampling factor in component %d %d:%d\n",
295 i, h_count[i], v_count[i]);
296 return AVERROR_INVALIDDATA;
299 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
300 i, h_count[i], v_count[i],
301 s->component_id[i], s->quant_index[i]);
304 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
305 avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
306 return AVERROR_PATCHWELCOME;
310 /* if different size, realloc/alloc picture */
311 if ( width != s->width || height != s->height
312 || memcmp(s->h_count, h_count, sizeof(h_count))
313 || memcmp(s->v_count, v_count, sizeof(v_count))) {
317 memcpy(s->h_count, h_count, sizeof(h_count));
318 memcpy(s->v_count, v_count, sizeof(v_count));
322 /* test interlaced mode */
323 if (s->first_picture &&
324 s->org_height != 0 &&
325 s->height < ((s->org_height * 3) / 4)) {
327 s->bottom_field = s->interlace_polarity;
328 s->picture_ptr->interlaced_frame = 1;
329 s->picture_ptr->top_field_first = !s->interlace_polarity;
333 avcodec_set_dimensions(s->avctx, width, height);
335 s->first_picture = 0;
338 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
339 if (s->progressive) {
340 avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
341 return AVERROR_INVALIDDATA;
344 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
346 else if (!s->lossless)
348 /* XXX: not complete test ! */
349 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
350 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
351 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
352 (s->h_count[3] << 4) | s->v_count[3];
353 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
354 /* NOTE we do not allocate pictures large enough for the possible
355 * padding of h/v_count being 4 */
356 if (!(pix_fmt_id & 0xD0D0D0D0))
357 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
358 if (!(pix_fmt_id & 0x0D0D0D0D))
359 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
361 switch (pix_fmt_id) {
364 s->avctx->pix_fmt = AV_PIX_FMT_BGR24;
366 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
367 s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
369 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
370 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
373 av_assert0(s->nb_components == 3);
377 s->avctx->pix_fmt = AV_PIX_FMT_ABGR;
379 s->avctx->pix_fmt = /*s->cs_itu601 ?*/ AV_PIX_FMT_YUVA444P/* : AV_PIX_FMT_YUVJA444P*/;
380 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
382 av_assert0(s->nb_components == 4);
386 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
387 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
389 s->upscale_h = (pix_fmt_id == 0x22122100);
390 s->chroma_height = s->height;
394 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
395 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
396 s->upscale_v = (pix_fmt_id == 0x22211200);
398 s->chroma_height = s->height;
401 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
402 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
405 s->chroma_height = s->height / 2;
417 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
419 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
424 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
425 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
426 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
427 s->chroma_height = s->height / 2;
430 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
431 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
435 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
436 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
437 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
440 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
441 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
444 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
445 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
448 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
449 return AVERROR_PATCHWELCOME;
451 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
452 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
453 return AVERROR_PATCHWELCOME;
456 s->upscale_h = s->upscale_v = 0;
457 if (s->nb_components > 1)
458 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
459 else if (s->bits <= 8)
460 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
462 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
465 av_frame_unref(s->picture_ptr);
466 if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
468 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
469 s->picture_ptr->key_frame = 1;
472 for (i = 0; i < 3; i++)
473 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
475 av_dlog(s->avctx, "%d %d %d %d %d %d\n",
476 s->width, s->height, s->linesize[0], s->linesize[1],
477 s->interlaced, s->avctx->height);
479 if (len != (8 + (3 * nb_components)))
480 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
483 if (s->rgb && !s->lossless && !s->ls) {
484 av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
485 return AVERROR_PATCHWELCOME;
488 /* totally blank picture as progressive JPEG will only add details to it */
489 if (s->progressive) {
490 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
491 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
492 for (i = 0; i < s->nb_components; i++) {
493 int size = bw * bh * s->h_count[i] * s->v_count[i];
494 av_freep(&s->blocks[i]);
495 av_freep(&s->last_nnz[i]);
496 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
497 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
498 s->block_stride[i] = bw * s->h_count[i];
500 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
505 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
508 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
509 if (code < 0 || code > 16) {
510 av_log(s->avctx, AV_LOG_WARNING,
511 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
512 0, dc_index, &s->vlcs[0][dc_index]);
517 return get_xbits(&s->gb, code);
522 /* decode block and dequantize */
523 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
524 int dc_index, int ac_index, int16_t *quant_matrix)
526 int code, i, j, level, val;
529 val = mjpeg_decode_dc(s, dc_index);
531 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
532 return AVERROR_INVALIDDATA;
534 val = val * quant_matrix[0] + s->last_dc[component];
535 s->last_dc[component] = val;
539 {OPEN_READER(re, &s->gb);
541 UPDATE_CACHE(re, &s->gb);
542 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
544 i += ((unsigned)code) >> 4;
547 if (code > MIN_CACHE_BITS - 16)
548 UPDATE_CACHE(re, &s->gb);
551 int cache = GET_CACHE(re, &s->gb);
552 int sign = (~cache) >> 31;
553 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
556 LAST_SKIP_BITS(re, &s->gb, code);
559 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
560 return AVERROR_INVALIDDATA;
562 j = s->scantable.permutated[i];
563 block[j] = level * quant_matrix[j];
566 CLOSE_READER(re, &s->gb);}
571 static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
572 int component, int dc_index,
573 int16_t *quant_matrix, int Al)
576 s->dsp.clear_block(block);
577 val = mjpeg_decode_dc(s, dc_index);
579 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
580 return AVERROR_INVALIDDATA;
582 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
583 s->last_dc[component] = val;
588 /* decode block and dequantize - progressive JPEG version */
589 static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
590 uint8_t *last_nnz, int ac_index,
591 int16_t *quant_matrix,
592 int ss, int se, int Al, int *EOBRUN)
594 int code, i, j, level, val, run;
602 OPEN_READER(re, &s->gb);
603 for (i = ss; ; i++) {
604 UPDATE_CACHE(re, &s->gb);
605 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
607 run = ((unsigned) code) >> 4;
611 if (code > MIN_CACHE_BITS - 16)
612 UPDATE_CACHE(re, &s->gb);
615 int cache = GET_CACHE(re, &s->gb);
616 int sign = (~cache) >> 31;
617 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
620 LAST_SKIP_BITS(re, &s->gb, code);
624 j = s->scantable.permutated[se];
625 block[j] = level * quant_matrix[j] << Al;
628 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
629 return AVERROR_INVALIDDATA;
631 j = s->scantable.permutated[i];
632 block[j] = level * quant_matrix[j] << Al;
634 if (run == 0xF) {// ZRL - skip 15 coefficients
637 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
638 return AVERROR_INVALIDDATA;
643 UPDATE_CACHE(re, &s->gb);
644 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
645 LAST_SKIP_BITS(re, &s->gb, run);
652 CLOSE_READER(re, &s->gb);
661 #define REFINE_BIT(j) { \
662 UPDATE_CACHE(re, &s->gb); \
663 sign = block[j] >> 15; \
664 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
665 ((quant_matrix[j] ^ sign) - sign) << Al; \
666 LAST_SKIP_BITS(re, &s->gb, 1); \
674 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
679 j = s->scantable.permutated[i]; \
682 else if (run-- == 0) \
686 /* decode block and dequantize - progressive JPEG refinement pass */
687 static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
689 int ac_index, int16_t *quant_matrix,
690 int ss, int se, int Al, int *EOBRUN)
692 int code, i = ss, j, sign, val, run;
693 int last = FFMIN(se, *last_nnz);
695 OPEN_READER(re, &s->gb);
700 UPDATE_CACHE(re, &s->gb);
701 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
704 run = ((unsigned) code) >> 4;
705 UPDATE_CACHE(re, &s->gb);
706 val = SHOW_UBITS(re, &s->gb, 1);
707 LAST_SKIP_BITS(re, &s->gb, 1);
709 j = s->scantable.permutated[i];
711 block[j] = ((quant_matrix[j]^val) - val) << Al;
715 CLOSE_READER(re, &s->gb);
719 run = ((unsigned) code) >> 4;
726 UPDATE_CACHE(re, &s->gb);
727 run += SHOW_UBITS(re, &s->gb, val);
728 LAST_SKIP_BITS(re, &s->gb, val);
740 for (; i <= last; i++) {
741 j = s->scantable.permutated[i];
745 CLOSE_READER(re, &s->gb);
752 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
757 if (s->restart_interval) {
759 if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
760 align_get_bits(&s->gb);
761 for (i = 0; i < nb_components; i++) /* reset dc */
762 s->last_dc[i] = 1024;
765 i = 8 + ((-get_bits_count(&s->gb)) & 7);
767 if (s->restart_count == 0) {
768 if( show_bits(&s->gb, i) == (1 << i) - 1
769 || show_bits(&s->gb, i) == 0xFF) {
770 int pos = get_bits_count(&s->gb);
771 align_get_bits(&s->gb);
772 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
773 skip_bits(&s->gb, 8);
774 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
775 for (i = 0; i < nb_components; i++) /* reset dc */
776 s->last_dc[i] = 1024;
779 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
786 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
789 uint16_t (*buffer)[4];
790 int left[4], top[4], topleft[4];
791 const int linesize = s->linesize[0];
792 const int mask = (1 << s->bits) - 1;
796 s->restart_count = s->restart_interval;
798 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
799 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
800 buffer = s->ljpeg_buffer;
802 for (i = 0; i < 4; i++)
803 buffer[0][i] = 1 << (s->bits - 1);
805 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
806 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
808 if (s->interlaced && s->bottom_field)
809 ptr += linesize >> 1;
811 for (i = 0; i < 4; i++)
812 top[i] = left[i] = topleft[i] = buffer[0][i];
814 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
815 int modified_predictor = predictor;
817 if (s->restart_interval && !s->restart_count){
818 s->restart_count = s->restart_interval;
822 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
824 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
825 modified_predictor = 1;
827 for (i=0;i<nb_components;i++) {
831 top[i] = buffer[mb_x][i];
833 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
835 dc = mjpeg_decode_dc(s, s->dc_index[i]);
839 left[i] = buffer[mb_x][i] =
840 mask & (pred + (dc << point_transform));
843 if (s->restart_interval && !--s->restart_count) {
844 align_get_bits(&s->gb);
845 skip_bits(&s->gb, 16); /* skip RSTn */
848 if (s->nb_components == 4) {
849 for(i=0; i<nb_components; i++) {
850 int c= s->comp_index[i];
851 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
852 ptr[4*mb_x+3-c] = buffer[mb_x][i];
856 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
857 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
858 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
859 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
861 } else if (s->pegasus_rct) {
862 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
863 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
864 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
865 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
868 for(i=0; i<nb_components; i++) {
869 int c= s->comp_index[i];
870 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
871 ptr[3*mb_x+2-c] = buffer[mb_x][i];
879 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
880 int point_transform, int nb_components)
883 int bits= (s->bits+7)&~7;
887 point_transform += bits - s->bits;
889 av_assert0(nb_components>=1 && nb_components<=4);
891 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
892 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
893 if (s->restart_interval && !s->restart_count){
894 s->restart_count = s->restart_interval;
899 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
900 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
901 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
902 for (i = 0; i < nb_components; i++) {
905 int n, h, v, x, y, c, j, linesize;
907 c = s->comp_index[i];
912 linesize= s->linesize[c];
914 if(bits>8) linesize /= 2;
919 dc = mjpeg_decode_dc(s, s->dc_index[i]);
923 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
926 pred= 1 << (bits - 1);
932 pred= ptr[-linesize];
934 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
938 if (s->interlaced && s->bottom_field)
939 ptr += linesize >> 1;
940 pred &= (-1)<<(8-s->bits);
941 *ptr= pred + (dc << point_transform);
943 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
946 pred= 1 << (bits - 1);
952 pred= ptr16[-linesize];
954 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
958 if (s->interlaced && s->bottom_field)
959 ptr16 += linesize >> 1;
960 pred &= (-1)<<(16-s->bits);
961 *ptr16= pred + (dc << point_transform);
970 for (i = 0; i < nb_components; i++) {
973 int n, h, v, x, y, c, j, linesize, dc;
975 c = s->comp_index[i];
980 linesize = s->linesize[c];
982 if(bits>8) linesize /= 2;
984 for (j = 0; j < n; j++) {
987 dc = mjpeg_decode_dc(s, s->dc_index[i]);
991 ptr = s->picture.data[c] +
992 (linesize * (v * mb_y + y)) +
993 (h * mb_x + x); //FIXME optimize this crap
994 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
996 pred &= (-1)<<(8-s->bits);
997 *ptr = pred + (dc << point_transform);
999 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1000 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1002 pred &= (-1)<<(16-s->bits);
1003 *ptr16= pred + (dc << point_transform);
1013 if (s->restart_interval && !--s->restart_count) {
1014 align_get_bits(&s->gb);
1015 skip_bits(&s->gb, 16); /* skip RSTn */
1022 static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
1023 uint8_t *dst, const uint8_t *src,
1024 int linesize, int lowres)
1027 case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1029 case 1: copy_block4(dst, src, linesize, linesize, 4);
1031 case 2: copy_block2(dst, src, linesize, linesize, 2);
1033 case 3: *dst = *src;
1038 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1039 int Al, const uint8_t *mb_bitmask,
1040 const AVFrame *reference)
1043 uint8_t *data[MAX_COMPONENTS];
1044 const uint8_t *reference_data[MAX_COMPONENTS];
1045 int linesize[MAX_COMPONENTS];
1046 GetBitContext mb_bitmask_gb;
1049 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1051 if (s->flipped && s->avctx->lowres) {
1052 av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
1055 s->restart_count = 0;
1056 for (i = 0; i < nb_components; i++) {
1057 int c = s->comp_index[i];
1058 data[c] = s->picture_ptr->data[c];
1059 reference_data[c] = reference ? reference->data[c] : NULL;
1060 linesize[c] = s->linesize[c];
1061 s->coefs_finished[c] |= 1;
1062 if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1063 // picture should be flipped upside-down for this codec
1064 int offset = (linesize[c] * (s->v_scount[i] *
1065 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
1067 reference_data[c] += offset;
1072 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1073 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1074 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1076 if (s->restart_interval && !s->restart_count)
1077 s->restart_count = s->restart_interval;
1079 if (get_bits_left(&s->gb) < 0) {
1080 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1081 -get_bits_left(&s->gb));
1082 return AVERROR_INVALIDDATA;
1084 for (i = 0; i < nb_components; i++) {
1086 int n, h, v, x, y, c, j;
1088 n = s->nb_blocks[i];
1089 c = s->comp_index[i];
1094 for (j = 0; j < n; j++) {
1095 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1096 (h * mb_x + x) * 8) >> s->avctx->lowres);
1098 if (s->interlaced && s->bottom_field)
1099 block_offset += linesize[c] >> 1;
1100 ptr = data[c] + block_offset;
1101 if (!s->progressive) {
1103 mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1104 linesize[c], s->avctx->lowres);
1107 s->dsp.clear_block(s->block);
1108 if (decode_block(s, s->block, i,
1109 s->dc_index[i], s->ac_index[i],
1110 s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1111 av_log(s->avctx, AV_LOG_ERROR,
1112 "error y=%d x=%d\n", mb_y, mb_x);
1113 return AVERROR_INVALIDDATA;
1115 s->dsp.idct_put(ptr, linesize[c], s->block);
1118 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1120 int16_t *block = s->blocks[c][block_idx];
1122 block[0] += get_bits1(&s->gb) *
1123 s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1124 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1125 s->quant_matrixes[s->quant_sindex[i]],
1127 av_log(s->avctx, AV_LOG_ERROR,
1128 "error y=%d x=%d\n", mb_y, mb_x);
1129 return AVERROR_INVALIDDATA;
1132 av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1133 av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1134 mb_x, mb_y, x, y, c, s->bottom_field,
1135 (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1143 handle_rstn(s, nb_components);
1149 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1150 int se, int Ah, int Al)
1154 int c = s->comp_index[0];
1155 uint8_t *data = s->picture.data[c];
1156 int linesize = s->linesize[c];
1158 int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1160 av_assert0(ss>=0 && Ah>=0 && Al>=0);
1161 if (se < ss || se > 63) {
1162 av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1163 return AVERROR_INVALIDDATA;
1167 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1168 last_scan = !~s->coefs_finished[c];
1171 if (s->interlaced && s->bottom_field)
1172 data += linesize >> 1;
1174 s->restart_count = 0;
1176 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1177 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1178 int block_idx = mb_y * s->block_stride[c];
1179 int16_t (*block)[64] = &s->blocks[c][block_idx];
1180 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1181 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1183 if (s->restart_interval && !s->restart_count)
1184 s->restart_count = s->restart_interval;
1187 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1188 quant_matrix, ss, se, Al, &EOBRUN);
1190 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1191 quant_matrix, ss, se, Al, &EOBRUN);
1193 av_log(s->avctx, AV_LOG_ERROR,
1194 "error y=%d x=%d\n", mb_y, mb_x);
1195 return AVERROR_INVALIDDATA;
1199 s->dsp.idct_put(ptr, linesize, *block);
1200 ptr += 8 >> s->avctx->lowres;
1202 if (handle_rstn(s, 0))
1209 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1210 const AVFrame *reference)
1212 int len, nb_components, i, h, v, predictor, point_transform;
1214 const int block_size = s->lossless ? 1 : 8;
1215 int ilv, prev_shift;
1217 if (!s->got_picture) {
1218 av_log(s->avctx, AV_LOG_WARNING,
1219 "Can not process SOS before SOF, skipping\n");
1223 av_assert0(s->picture_ptr->data[0]);
1224 /* XXX: verify len field validity */
1225 len = get_bits(&s->gb, 16);
1226 nb_components = get_bits(&s->gb, 8);
1227 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1228 av_log(s->avctx, AV_LOG_ERROR,
1229 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1230 return AVERROR_PATCHWELCOME;
1232 if (len != 6 + 2 * nb_components) {
1233 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1234 return AVERROR_INVALIDDATA;
1236 for (i = 0; i < nb_components; i++) {
1237 id = get_bits(&s->gb, 8) - 1;
1238 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1239 /* find component index */
1240 for (index = 0; index < s->nb_components; index++)
1241 if (id == s->component_id[index])
1243 if (index == s->nb_components) {
1244 av_log(s->avctx, AV_LOG_ERROR,
1245 "decode_sos: index(%d) out of components\n", index);
1246 return AVERROR_INVALIDDATA;
1248 /* Metasoft MJPEG codec has Cb and Cr swapped */
1249 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1250 && nb_components == 3 && s->nb_components == 3 && i)
1253 s->quant_sindex[i] = s->quant_index[index];
1254 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1255 s->h_scount[i] = s->h_count[index];
1256 s->v_scount[i] = s->v_count[index];
1258 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1260 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1261 index = (index+2)%3;
1263 s->comp_index[i] = index;
1265 s->dc_index[i] = get_bits(&s->gb, 4);
1266 s->ac_index[i] = get_bits(&s->gb, 4);
1268 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1269 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1271 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))
1275 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1276 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1277 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1278 prev_shift = get_bits(&s->gb, 4); /* Ah */
1279 point_transform = get_bits(&s->gb, 4); /* Al */
1281 prev_shift = point_transform = 0;
1283 if (nb_components > 1) {
1284 /* interleaved stream */
1285 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1286 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1287 } else if (!s->ls) { /* skip this for JPEG-LS */
1288 h = s->h_max / s->h_scount[0];
1289 v = s->v_max / s->v_scount[0];
1290 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1291 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1292 s->nb_blocks[0] = 1;
1297 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1298 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1299 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1300 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1301 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1304 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1305 for (i = s->mjpb_skiptosod; i > 0; i--)
1306 skip_bits(&s->gb, 8);
1309 for (i = 0; i < nb_components; i++)
1310 s->last_dc[i] = 1024;
1313 av_assert0(s->picture_ptr == &s->picture);
1314 if (CONFIG_JPEGLS_DECODER && s->ls) {
1316 // reset_ls_coding_parameters(s, 0);
1318 if ((ret = ff_jpegls_decode_picture(s, predictor,
1319 point_transform, ilv)) < 0)
1323 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1326 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1328 nb_components)) < 0)
1333 if (s->progressive && predictor) {
1334 av_assert0(s->picture_ptr == &s->picture);
1335 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1337 point_transform)) < 0)
1340 if ((ret = mjpeg_decode_scan(s, nb_components,
1341 prev_shift, point_transform,
1342 mb_bitmask, reference)) < 0)
1347 if (s->interlaced &&
1348 get_bits_left(&s->gb) > 32 &&
1349 show_bits(&s->gb, 8) == 0xFF) {
1350 GetBitContext bak = s->gb;
1351 align_get_bits(&bak);
1352 if (show_bits(&bak, 16) == 0xFFD1) {
1353 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1355 skip_bits(&s->gb, 16);
1356 s->bottom_field ^= 1;
1365 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1366 return AVERROR_INVALIDDATA;
1369 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1371 if (get_bits(&s->gb, 16) != 4)
1372 return AVERROR_INVALIDDATA;
1373 s->restart_interval = get_bits(&s->gb, 16);
1374 s->restart_count = 0;
1375 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1376 s->restart_interval);
1381 static int mjpeg_decode_app(MJpegDecodeContext *s)
1385 len = get_bits(&s->gb, 16);
1387 return AVERROR_INVALIDDATA;
1388 if (8 * len > get_bits_left(&s->gb))
1389 return AVERROR_INVALIDDATA;
1391 id = get_bits_long(&s->gb, 32);
1394 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1395 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X len=%d\n", id, len);
1397 /* Buggy AVID, it puts EOI only at every 10th frame. */
1398 /* Also, this fourcc is used by non-avid files too, it holds some
1399 information, but it's always present in AVID-created files. */
1400 if (id == AV_RB32("AVI1")) {
1406 4bytes field_size_less_padding
1409 i = get_bits(&s->gb, 8); len--;
1410 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1412 skip_bits(&s->gb, 8);
1413 skip_bits(&s->gb, 32);
1414 skip_bits(&s->gb, 32);
1422 if (id == AV_RB32("JFIF")) {
1423 int t_w, t_h, v1, v2;
1424 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1425 v1 = get_bits(&s->gb, 8);
1426 v2 = get_bits(&s->gb, 8);
1427 skip_bits(&s->gb, 8);
1429 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1430 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1432 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1433 av_log(s->avctx, AV_LOG_INFO,
1434 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1436 s->avctx->sample_aspect_ratio.num,
1437 s->avctx->sample_aspect_ratio.den);
1439 t_w = get_bits(&s->gb, 8);
1440 t_h = get_bits(&s->gb, 8);
1442 /* skip thumbnail */
1443 if (len -10 - (t_w * t_h * 3) > 0)
1444 len -= t_w * t_h * 3;
1450 if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1451 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1452 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1453 skip_bits(&s->gb, 16); /* version */
1454 skip_bits(&s->gb, 16); /* flags0 */
1455 skip_bits(&s->gb, 16); /* flags1 */
1456 skip_bits(&s->gb, 8); /* transform */
1461 if (id == AV_RB32("LJIF")) {
1462 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1463 av_log(s->avctx, AV_LOG_INFO,
1464 "Pegasus lossless jpeg header found\n");
1465 skip_bits(&s->gb, 16); /* version ? */
1466 skip_bits(&s->gb, 16); /* unknown always 0? */
1467 skip_bits(&s->gb, 16); /* unknown always 0? */
1468 skip_bits(&s->gb, 16); /* unknown always 0? */
1469 switch (get_bits(&s->gb, 8)) {
1479 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1484 if (id == AV_RL32("colr") && len > 0) {
1485 s->colr = get_bits(&s->gb, 8);
1486 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1487 av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1491 if (id == AV_RL32("xfrm") && len > 0) {
1492 s->xfrm = get_bits(&s->gb, 8);
1493 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1494 av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1500 if (s->start_code == APP1 && id == AV_RB32("Exif")) {
1501 GetByteContext gbytes;
1502 int ret, le, ifd_offset, bytes_read;
1503 const uint8_t *aligned;
1505 skip_bits(&s->gb, 16); // skip padding
1508 // init byte wise reading
1509 aligned = align_get_bits(&s->gb);
1510 bytestream2_init(&gbytes, aligned, len);
1513 ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
1515 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
1519 bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
1521 // read 0th IFD and store the metadata
1522 // (return values > 0 indicate the presence of subimage metadata)
1523 ret = ff_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
1525 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
1529 bytes_read = bytestream2_tell(&gbytes);
1530 skip_bits(&s->gb, bytes_read << 3);
1537 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1538 id = get_bits_long(&s->gb, 32);
1541 if (id == AV_RB32("mjpg")) {
1543 skip_bits(&s->gb, 32); /* field size */
1544 skip_bits(&s->gb, 32); /* pad field size */
1545 skip_bits(&s->gb, 32); /* next off */
1546 skip_bits(&s->gb, 32); /* quant off */
1547 skip_bits(&s->gb, 32); /* huff off */
1548 skip_bits(&s->gb, 32); /* image off */
1549 skip_bits(&s->gb, 32); /* scan off */
1550 skip_bits(&s->gb, 32); /* data off */
1552 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1553 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1558 /* slow but needed for extreme adobe jpegs */
1560 av_log(s->avctx, AV_LOG_ERROR,
1561 "mjpeg: error, decode_app parser read over the end\n");
1563 skip_bits(&s->gb, 8);
1568 static int mjpeg_decode_com(MJpegDecodeContext *s)
1570 int len = get_bits(&s->gb, 16);
1571 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1572 char *cbuf = av_malloc(len - 1);
1575 for (i = 0; i < len - 2; i++)
1576 cbuf[i] = get_bits(&s->gb, 8);
1577 if (i > 0 && cbuf[i - 1] == '\n')
1582 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1583 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1585 /* buggy avid, it puts EOI only at every 10th frame */
1586 if (!strncmp(cbuf, "AVID", 4)) {
1588 if (len > 14 && cbuf[12] == 1) /* 1 - NTSC, 2 - PAL */
1589 s->interlace_polarity = 1;
1590 } else if (!strcmp(cbuf, "CS=ITU601"))
1592 else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1593 (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1603 /* return the 8 bit start code value and update the search
1604 state. Return -1 if no start code found */
1605 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1607 const uint8_t *buf_ptr;
1612 buf_ptr = *pbuf_ptr;
1613 while (buf_ptr < buf_end) {
1616 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1624 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1625 *pbuf_ptr = buf_ptr;
1629 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1630 const uint8_t **buf_ptr, const uint8_t *buf_end,
1631 const uint8_t **unescaped_buf_ptr,
1632 int *unescaped_buf_size)
1635 start_code = find_marker(buf_ptr, buf_end);
1637 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1639 return AVERROR(ENOMEM);
1641 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1642 if (start_code == SOS && !s->ls) {
1643 const uint8_t *src = *buf_ptr;
1644 uint8_t *dst = s->buffer;
1646 while (src < buf_end) {
1647 uint8_t x = *(src++);
1650 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1652 while (src < buf_end && x == 0xff)
1655 if (x >= 0xd0 && x <= 0xd7)
1662 *unescaped_buf_ptr = s->buffer;
1663 *unescaped_buf_size = dst - s->buffer;
1664 memset(s->buffer + *unescaped_buf_size, 0,
1665 FF_INPUT_BUFFER_PADDING_SIZE);
1667 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1668 (buf_end - *buf_ptr) - (dst - s->buffer));
1669 } else if (start_code == SOS && s->ls) {
1670 const uint8_t *src = *buf_ptr;
1671 uint8_t *dst = s->buffer;
1679 while (src + t < buf_end) {
1680 uint8_t x = src[t++];
1682 while ((src + t < buf_end) && x == 0xff)
1691 init_put_bits(&pb, dst, t);
1693 /* unescape bitstream */
1695 uint8_t x = src[b++];
1696 put_bits(&pb, 8, x);
1699 put_bits(&pb, 7, x);
1703 flush_put_bits(&pb);
1705 *unescaped_buf_ptr = dst;
1706 *unescaped_buf_size = (bit_count + 7) >> 3;
1707 memset(s->buffer + *unescaped_buf_size, 0,
1708 FF_INPUT_BUFFER_PADDING_SIZE);
1710 *unescaped_buf_ptr = *buf_ptr;
1711 *unescaped_buf_size = buf_end - *buf_ptr;
1717 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1720 const uint8_t *buf = avpkt->data;
1721 int buf_size = avpkt->size;
1722 MJpegDecodeContext *s = avctx->priv_data;
1723 const uint8_t *buf_end, *buf_ptr;
1724 const uint8_t *unescaped_buf_ptr;
1726 int unescaped_buf_size;
1731 av_dict_free(&s->exif_metadata);
1734 buf_end = buf + buf_size;
1735 while (buf_ptr < buf_end) {
1736 /* find start next marker */
1737 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1739 &unescaped_buf_size);
1741 if (start_code < 0) {
1743 } else if (unescaped_buf_size > INT_MAX / 8) {
1744 av_log(avctx, AV_LOG_ERROR,
1745 "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1746 start_code, unescaped_buf_size, buf_size);
1747 return AVERROR_INVALIDDATA;
1749 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1750 start_code, buf_end - buf_ptr);
1752 ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1755 av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1759 s->start_code = start_code;
1760 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1761 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1763 /* process markers */
1764 if (start_code >= 0xd0 && start_code <= 0xd7)
1765 av_log(avctx, AV_LOG_DEBUG,
1766 "restart marker: %d\n", start_code & 0x0f);
1768 else if (start_code >= APP0 && start_code <= APP15)
1769 mjpeg_decode_app(s);
1771 else if (start_code == COM)
1772 mjpeg_decode_com(s);
1776 if (!CONFIG_JPEGLS_DECODER &&
1777 (start_code == SOF48 || start_code == LSE)) {
1778 av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1779 return AVERROR(ENOSYS);
1782 switch (start_code) {
1784 s->restart_interval = 0;
1785 s->restart_count = 0;
1786 /* nothing to do on SOI */
1789 ff_mjpeg_decode_dqt(s);
1792 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1793 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1802 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1809 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1816 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1823 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1827 if (!CONFIG_JPEGLS_DECODER ||
1828 (ret = ff_jpegls_decode_lse(s)) < 0)
1834 if (!s->got_picture) {
1835 av_log(avctx, AV_LOG_WARNING,
1836 "Found EOI before any SOF, ignoring\n");
1839 if (s->interlaced) {
1840 s->bottom_field ^= 1;
1841 /* if not bottom field, do not output image yet */
1842 if (s->bottom_field == !s->interlace_polarity)
1845 if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)
1851 int qp = FFMAX3(s->qscale[0],
1854 int qpw = (s->width + 15) / 16;
1855 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1857 memset(qp_table_buf->data, qp, qpw);
1858 av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1861 if(avctx->debug & FF_DEBUG_QP)
1862 av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1867 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1868 (avctx->err_recognition & AV_EF_EXPLODE))
1872 mjpeg_decode_dri(s);
1884 av_log(avctx, AV_LOG_ERROR,
1885 "mjpeg: unsupported coding type (%x)\n", start_code);
1889 /* eof process start code */
1890 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1891 av_log(avctx, AV_LOG_DEBUG,
1892 "marker parser used %d bytes (%d bits)\n",
1893 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1895 if (s->got_picture) {
1896 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1899 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1900 return AVERROR_INVALIDDATA;
1906 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1907 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1908 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1909 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1910 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1911 for (i = 0; i < s->chroma_height; i++) {
1912 for (index = s->width - 1; index; index--)
1913 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1914 line += s->linesize[s->upscale_h];
1918 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1920 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1921 w = s->width >> hshift;
1922 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1923 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1924 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1925 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1926 for (i = s->height - 1; i; i--) {
1927 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1928 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1930 memcpy(dst, src1, w);
1932 for (index = 0; index < w; index++)
1933 dst[index] = (src1[index] + src2[index]) >> 1;
1935 dst -= s->linesize[s->upscale_v];
1938 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1940 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1941 for (index=0; index<4; index++) {
1942 uint8_t *dst = s->picture_ptr->data[index];
1945 if(index && index<3){
1946 w = FF_CEIL_RSHIFT(w, hshift);
1947 h = FF_CEIL_RSHIFT(h, vshift);
1950 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
1951 for (i=0; i<h/2; i++) {
1953 FFSWAP(int, dst[j], dst2[j]);
1954 dst += s->linesize[index];
1955 dst2 -= s->linesize[index];
1961 av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);
1962 av_dict_free(&s->exif_metadata);
1964 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
1966 // return buf_end - buf_ptr;
1967 return buf_ptr - buf;
1970 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1972 MJpegDecodeContext *s = avctx->priv_data;
1975 if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
1976 av_log(avctx, AV_LOG_INFO, "Single field\n");
1980 av_frame_unref(s->picture_ptr);
1983 av_freep(&s->ljpeg_buffer);
1984 s->ljpeg_buffer_size = 0;
1986 for (i = 0; i < 3; i++) {
1987 for (j = 0; j < 4; j++)
1988 ff_free_vlc(&s->vlcs[i][j]);
1990 for (i = 0; i < MAX_COMPONENTS; i++) {
1991 av_freep(&s->blocks[i]);
1992 av_freep(&s->last_nnz[i]);
1994 av_dict_free(&s->exif_metadata);
1998 static void decode_flush(AVCodecContext *avctx)
2000 MJpegDecodeContext *s = avctx->priv_data;
2004 #if CONFIG_MJPEG_DECODER
2005 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
2006 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2007 static const AVOption options[] = {
2008 { "extern_huff", "Use external huffman table.",
2009 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
2013 static const AVClass mjpegdec_class = {
2014 .class_name = "MJPEG decoder",
2015 .item_name = av_default_item_name,
2017 .version = LIBAVUTIL_VERSION_INT,
2020 AVCodec ff_mjpeg_decoder = {
2022 .type = AVMEDIA_TYPE_VIDEO,
2023 .id = AV_CODEC_ID_MJPEG,
2024 .priv_data_size = sizeof(MJpegDecodeContext),
2025 .init = ff_mjpeg_decode_init,
2026 .close = ff_mjpeg_decode_end,
2027 .decode = ff_mjpeg_decode_frame,
2028 .flush = decode_flush,
2029 .capabilities = CODEC_CAP_DR1,
2031 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
2032 .priv_class = &mjpegdec_class,
2035 #if CONFIG_THP_DECODER
2036 AVCodec ff_thp_decoder = {
2038 .type = AVMEDIA_TYPE_VIDEO,
2039 .id = AV_CODEC_ID_THP,
2040 .priv_data_size = sizeof(MJpegDecodeContext),
2041 .init = ff_mjpeg_decode_init,
2042 .close = ff_mjpeg_decode_end,
2043 .decode = ff_mjpeg_decode_frame,
2044 .flush = decode_flush,
2045 .capabilities = CODEC_CAP_DR1,
2047 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),