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->lossless && s->avctx->lowres){
236 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
240 height = get_bits(&s->gb, 16);
241 width = get_bits(&s->gb, 16);
243 // HACK for odd_height.mov
244 if (s->interlaced && s->width == width && s->height == height + 1)
247 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
248 if (av_image_check_size(width, height, 0, s->avctx))
249 return AVERROR_INVALIDDATA;
251 nb_components = get_bits(&s->gb, 8);
252 if (nb_components <= 0 ||
253 nb_components > MAX_COMPONENTS)
255 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
256 if (nb_components != s->nb_components) {
257 av_log(s->avctx, AV_LOG_ERROR,
258 "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 s->quant_index[i] = get_bits(&s->gb, 8);
284 if (s->quant_index[i] >= 4) {
285 av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
286 return AVERROR_INVALIDDATA;
288 if (!h_count[i] || !v_count[i]) {
289 av_log(s->avctx, AV_LOG_ERROR,
290 "Invalid sampling factor in component %d %d:%d\n",
291 i, h_count[i], v_count[i]);
292 return AVERROR_INVALIDDATA;
295 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
296 i, h_count[i], v_count[i],
297 s->component_id[i], s->quant_index[i]);
300 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
301 avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
302 return AVERROR_PATCHWELCOME;
306 /* if different size, realloc/alloc picture */
307 if ( width != s->width || height != s->height
308 || memcmp(s->h_count, h_count, sizeof(h_count))
309 || memcmp(s->v_count, v_count, sizeof(v_count))) {
313 memcpy(s->h_count, h_count, sizeof(h_count));
314 memcpy(s->v_count, v_count, sizeof(v_count));
318 /* test interlaced mode */
319 if (s->first_picture &&
320 s->org_height != 0 &&
321 s->height < ((s->org_height * 3) / 4)) {
323 s->bottom_field = s->interlace_polarity;
324 s->picture_ptr->interlaced_frame = 1;
325 s->picture_ptr->top_field_first = !s->interlace_polarity;
329 avcodec_set_dimensions(s->avctx, width, height);
331 s->first_picture = 0;
334 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
335 if (s->progressive) {
336 avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
337 return AVERROR_INVALIDDATA;
340 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
342 else if (!s->lossless)
344 /* XXX: not complete test ! */
345 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
346 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
347 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
348 (s->h_count[3] << 4) | s->v_count[3];
349 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
350 /* NOTE we do not allocate pictures large enough for the possible
351 * padding of h/v_count being 4 */
352 if (!(pix_fmt_id & 0xD0D0D0D0))
353 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
354 if (!(pix_fmt_id & 0x0D0D0D0D))
355 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
357 switch (pix_fmt_id) {
360 s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_BGR48;
362 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
363 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_GBRP : AV_PIX_FMT_GBRP16;
365 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
366 else s->avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
367 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
370 av_assert0(s->nb_components == 3);
374 s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA64;
376 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_YUVA444P : AV_PIX_FMT_YUVA444P16;
377 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
379 av_assert0(s->nb_components == 4);
383 if (s->bits <= 8) 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;
388 s->upscale_h = (pix_fmt_id == 0x22122100);
389 s->chroma_height = s->height;
393 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
396 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
397 s->upscale_v = (pix_fmt_id == 0x22211200);
399 s->chroma_height = s->height;
402 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
405 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
408 s->chroma_height = s->height / 2;
420 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
422 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
427 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
430 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
431 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
432 s->chroma_height = s->height / 2;
435 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
436 else s->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
437 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
441 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
444 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
445 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
448 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
449 else s->avctx->pix_fmt = AV_PIX_FMT_YUV420P16;
450 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
453 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
456 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
460 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
461 return AVERROR_PATCHWELCOME;
463 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
464 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
465 return AVERROR_PATCHWELCOME;
468 s->upscale_h = s->upscale_v = 0;
469 if (s->nb_components > 1)
470 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
471 else if (s->bits <= 8)
472 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
474 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
477 av_frame_unref(s->picture_ptr);
478 if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
480 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
481 s->picture_ptr->key_frame = 1;
484 for (i = 0; i < 3; i++)
485 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
487 av_dlog(s->avctx, "%d %d %d %d %d %d\n",
488 s->width, s->height, s->linesize[0], s->linesize[1],
489 s->interlaced, s->avctx->height);
491 if (len != (8 + (3 * nb_components)))
492 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
495 if (s->rgb && !s->lossless && !s->ls) {
496 av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
497 return AVERROR_PATCHWELCOME;
500 /* totally blank picture as progressive JPEG will only add details to it */
501 if (s->progressive) {
502 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
503 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
504 for (i = 0; i < s->nb_components; i++) {
505 int size = bw * bh * s->h_count[i] * s->v_count[i];
506 av_freep(&s->blocks[i]);
507 av_freep(&s->last_nnz[i]);
508 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
509 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
510 if (!s->blocks[i] || !s->last_nnz[i])
511 return AVERROR(ENOMEM);
512 s->block_stride[i] = bw * s->h_count[i];
514 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
519 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
522 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
523 if (code < 0 || code > 16) {
524 av_log(s->avctx, AV_LOG_WARNING,
525 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
526 0, dc_index, &s->vlcs[0][dc_index]);
531 return get_xbits(&s->gb, code);
536 /* decode block and dequantize */
537 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
538 int dc_index, int ac_index, int16_t *quant_matrix)
540 int code, i, j, level, val;
543 val = mjpeg_decode_dc(s, dc_index);
544 if (val == 0xfffff) {
545 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
546 return AVERROR_INVALIDDATA;
548 val = val * quant_matrix[0] + s->last_dc[component];
549 s->last_dc[component] = val;
553 {OPEN_READER(re, &s->gb);
555 UPDATE_CACHE(re, &s->gb);
556 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
558 i += ((unsigned)code) >> 4;
561 if (code > MIN_CACHE_BITS - 16)
562 UPDATE_CACHE(re, &s->gb);
565 int cache = GET_CACHE(re, &s->gb);
566 int sign = (~cache) >> 31;
567 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
570 LAST_SKIP_BITS(re, &s->gb, code);
573 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
574 return AVERROR_INVALIDDATA;
576 j = s->scantable.permutated[i];
577 block[j] = level * quant_matrix[j];
580 CLOSE_READER(re, &s->gb);}
585 static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
586 int component, int dc_index,
587 int16_t *quant_matrix, int Al)
590 s->dsp.clear_block(block);
591 val = mjpeg_decode_dc(s, dc_index);
592 if (val == 0xfffff) {
593 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
594 return AVERROR_INVALIDDATA;
596 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
597 s->last_dc[component] = val;
602 /* decode block and dequantize - progressive JPEG version */
603 static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
604 uint8_t *last_nnz, int ac_index,
605 int16_t *quant_matrix,
606 int ss, int se, int Al, int *EOBRUN)
608 int code, i, j, level, val, run;
616 OPEN_READER(re, &s->gb);
617 for (i = ss; ; i++) {
618 UPDATE_CACHE(re, &s->gb);
619 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
621 run = ((unsigned) code) >> 4;
625 if (code > MIN_CACHE_BITS - 16)
626 UPDATE_CACHE(re, &s->gb);
629 int cache = GET_CACHE(re, &s->gb);
630 int sign = (~cache) >> 31;
631 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
634 LAST_SKIP_BITS(re, &s->gb, code);
638 j = s->scantable.permutated[se];
639 block[j] = level * quant_matrix[j] << Al;
642 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
643 return AVERROR_INVALIDDATA;
645 j = s->scantable.permutated[i];
646 block[j] = level * quant_matrix[j] << Al;
648 if (run == 0xF) {// ZRL - skip 15 coefficients
651 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
652 return AVERROR_INVALIDDATA;
657 UPDATE_CACHE(re, &s->gb);
658 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
659 LAST_SKIP_BITS(re, &s->gb, run);
666 CLOSE_READER(re, &s->gb);
675 #define REFINE_BIT(j) { \
676 UPDATE_CACHE(re, &s->gb); \
677 sign = block[j] >> 15; \
678 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
679 ((quant_matrix[j] ^ sign) - sign) << Al; \
680 LAST_SKIP_BITS(re, &s->gb, 1); \
688 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
693 j = s->scantable.permutated[i]; \
696 else if (run-- == 0) \
700 /* decode block and dequantize - progressive JPEG refinement pass */
701 static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
703 int ac_index, int16_t *quant_matrix,
704 int ss, int se, int Al, int *EOBRUN)
706 int code, i = ss, j, sign, val, run;
707 int last = FFMIN(se, *last_nnz);
709 OPEN_READER(re, &s->gb);
714 UPDATE_CACHE(re, &s->gb);
715 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
718 run = ((unsigned) code) >> 4;
719 UPDATE_CACHE(re, &s->gb);
720 val = SHOW_UBITS(re, &s->gb, 1);
721 LAST_SKIP_BITS(re, &s->gb, 1);
723 j = s->scantable.permutated[i];
725 block[j] = ((quant_matrix[j]^val) - val) << Al;
729 CLOSE_READER(re, &s->gb);
733 run = ((unsigned) code) >> 4;
740 UPDATE_CACHE(re, &s->gb);
741 run += SHOW_UBITS(re, &s->gb, val);
742 LAST_SKIP_BITS(re, &s->gb, val);
754 for (; i <= last; i++) {
755 j = s->scantable.permutated[i];
759 CLOSE_READER(re, &s->gb);
766 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
771 if (s->restart_interval) {
773 if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
774 align_get_bits(&s->gb);
775 for (i = 0; i < nb_components; i++) /* reset dc */
776 s->last_dc[i] = (4 << s->bits);
779 i = 8 + ((-get_bits_count(&s->gb)) & 7);
781 if (s->restart_count == 0) {
782 if( show_bits(&s->gb, i) == (1 << i) - 1
783 || show_bits(&s->gb, i) == 0xFF) {
784 int pos = get_bits_count(&s->gb);
785 align_get_bits(&s->gb);
786 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
787 skip_bits(&s->gb, 8);
788 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
789 for (i = 0; i < nb_components; i++) /* reset dc */
790 s->last_dc[i] = (4 << s->bits);
793 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
800 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
803 uint16_t (*buffer)[4];
804 int left[4], top[4], topleft[4];
805 const int linesize = s->linesize[0];
806 const int mask = ((1 << s->bits) - 1) << point_transform;
810 if (s->nb_components != 3 && s->nb_components != 4)
811 return AVERROR_INVALIDDATA;
812 if (s->v_max != 1 || s->h_max != 1 || !s->lossless)
813 return AVERROR_INVALIDDATA;
816 s->restart_count = s->restart_interval;
818 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
819 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
820 buffer = s->ljpeg_buffer;
822 for (i = 0; i < 4; i++)
823 buffer[0][i] = 1 << (s->bits - 1);
825 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
826 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
828 if (s->interlaced && s->bottom_field)
829 ptr += linesize >> 1;
831 for (i = 0; i < 4; i++)
832 top[i] = left[i] = topleft[i] = buffer[0][i];
834 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
835 int modified_predictor = predictor;
837 if (s->restart_interval && !s->restart_count){
838 s->restart_count = s->restart_interval;
842 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
844 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
845 modified_predictor = 1;
847 for (i=0;i<nb_components;i++) {
851 top[i] = buffer[mb_x][i];
853 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
855 dc = mjpeg_decode_dc(s, s->dc_index[i]);
859 left[i] = buffer[mb_x][i] =
860 mask & (pred + (dc << point_transform));
863 if (s->restart_interval && !--s->restart_count) {
864 align_get_bits(&s->gb);
865 skip_bits(&s->gb, 16); /* skip RSTn */
868 if (s->nb_components == 4) {
869 for(i=0; i<nb_components; i++) {
870 int c= s->comp_index[i];
872 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
873 ptr[4*mb_x+3-c] = buffer[mb_x][i];
875 } else if(s->bits == 9) {
876 return AVERROR_PATCHWELCOME;
878 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
879 ((uint16_t*)ptr)[4*mb_x+c] = buffer[mb_x][i];
884 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
885 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
886 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
887 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
889 } else if (s->pegasus_rct) {
890 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
891 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
892 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
893 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
896 for(i=0; i<nb_components; i++) {
897 int c= s->comp_index[i];
899 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
900 ptr[3*mb_x+2-c] = buffer[mb_x][i];
902 } else if(s->bits == 9) {
903 return AVERROR_PATCHWELCOME;
905 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
906 ((uint16_t*)ptr)[3*mb_x+2-c] = buffer[mb_x][i];
915 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
916 int point_transform, int nb_components)
918 int i, mb_x, mb_y, mask;
919 int bits= (s->bits+7)&~7;
923 point_transform += bits - s->bits;
924 mask = ((1 << s->bits) - 1) << point_transform;
926 av_assert0(nb_components>=1 && nb_components<=4);
928 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
929 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
930 if (s->restart_interval && !s->restart_count){
931 s->restart_count = s->restart_interval;
936 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
937 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
938 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
939 for (i = 0; i < nb_components; i++) {
942 int n, h, v, x, y, c, j, linesize;
944 c = s->comp_index[i];
949 linesize= s->linesize[c];
951 if(bits>8) linesize /= 2;
956 dc = mjpeg_decode_dc(s, s->dc_index[i]);
960 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
963 pred= 1 << (bits - 1);
969 pred= ptr[-linesize];
971 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
975 if (s->interlaced && s->bottom_field)
976 ptr += linesize >> 1;
978 *ptr= pred + (dc << point_transform);
980 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
983 pred= 1 << (bits - 1);
989 pred= ptr16[-linesize];
991 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
995 if (s->interlaced && s->bottom_field)
996 ptr16 += linesize >> 1;
998 *ptr16= pred + (dc << point_transform);
1007 for (i = 0; i < nb_components; i++) {
1010 int n, h, v, x, y, c, j, linesize, dc;
1011 n = s->nb_blocks[i];
1012 c = s->comp_index[i];
1017 linesize = s->linesize[c];
1019 if(bits>8) linesize /= 2;
1021 for (j = 0; j < n; j++) {
1024 dc = mjpeg_decode_dc(s, s->dc_index[i]);
1028 ptr = s->picture.data[c] +
1029 (linesize * (v * mb_y + y)) +
1030 (h * mb_x + x); //FIXME optimize this crap
1031 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
1034 *ptr = pred + (dc << point_transform);
1036 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1037 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1040 *ptr16= pred + (dc << point_transform);
1050 if (s->restart_interval && !--s->restart_count) {
1051 align_get_bits(&s->gb);
1052 skip_bits(&s->gb, 16); /* skip RSTn */
1059 static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
1060 uint8_t *dst, const uint8_t *src,
1061 int linesize, int lowres)
1064 case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1066 case 1: copy_block4(dst, src, linesize, linesize, 4);
1068 case 2: copy_block2(dst, src, linesize, linesize, 2);
1070 case 3: *dst = *src;
1075 static void shift_output(MJpegDecodeContext *s, uint8_t *ptr, int linesize)
1077 int block_x, block_y;
1078 int size = 8 >> s->avctx->lowres;
1080 for (block_y=0; block_y<size; block_y++)
1081 for (block_x=0; block_x<size; block_x++)
1082 *(uint16_t*)(ptr + 2*block_x + block_y*linesize) <<= 16 - s->bits;
1084 for (block_y=0; block_y<size; block_y++)
1085 for (block_x=0; block_x<size; block_x++)
1086 *(ptr + block_x + block_y*linesize) <<= 8 - s->bits;
1090 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1091 int Al, const uint8_t *mb_bitmask,
1092 const AVFrame *reference)
1095 uint8_t *data[MAX_COMPONENTS];
1096 const uint8_t *reference_data[MAX_COMPONENTS];
1097 int linesize[MAX_COMPONENTS];
1098 GetBitContext mb_bitmask_gb;
1099 int bytes_per_pixel = 1 + (s->bits > 8);
1102 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1104 if (s->flipped && s->avctx->lowres) {
1105 av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
1108 s->restart_count = 0;
1109 for (i = 0; i < nb_components; i++) {
1110 int c = s->comp_index[i];
1111 data[c] = s->picture_ptr->data[c];
1112 reference_data[c] = reference ? reference->data[c] : NULL;
1113 linesize[c] = s->linesize[c];
1114 s->coefs_finished[c] |= 1;
1115 if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1116 // picture should be flipped upside-down for this codec
1117 int offset = (linesize[c] * (s->v_scount[i] *
1118 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
1120 reference_data[c] += offset;
1125 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1126 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1127 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1129 if (s->restart_interval && !s->restart_count)
1130 s->restart_count = s->restart_interval;
1132 if (get_bits_left(&s->gb) < 0) {
1133 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1134 -get_bits_left(&s->gb));
1135 return AVERROR_INVALIDDATA;
1137 for (i = 0; i < nb_components; i++) {
1139 int n, h, v, x, y, c, j;
1141 n = s->nb_blocks[i];
1142 c = s->comp_index[i];
1147 for (j = 0; j < n; j++) {
1148 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1149 (h * mb_x + x) * 8 * bytes_per_pixel) >> s->avctx->lowres);
1151 if (s->interlaced && s->bottom_field)
1152 block_offset += linesize[c] >> 1;
1153 ptr = data[c] + block_offset;
1154 if (!s->progressive) {
1156 mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1157 linesize[c], s->avctx->lowres);
1160 s->dsp.clear_block(s->block);
1161 if (decode_block(s, s->block, i,
1162 s->dc_index[i], s->ac_index[i],
1163 s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1164 av_log(s->avctx, AV_LOG_ERROR,
1165 "error y=%d x=%d\n", mb_y, mb_x);
1166 return AVERROR_INVALIDDATA;
1168 s->dsp.idct_put(ptr, linesize[c], s->block);
1170 shift_output(s, ptr, linesize[c]);
1173 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1175 int16_t *block = s->blocks[c][block_idx];
1177 block[0] += get_bits1(&s->gb) *
1178 s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1179 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1180 s->quant_matrixes[s->quant_sindex[i]],
1182 av_log(s->avctx, AV_LOG_ERROR,
1183 "error y=%d x=%d\n", mb_y, mb_x);
1184 return AVERROR_INVALIDDATA;
1187 av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1188 av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1189 mb_x, mb_y, x, y, c, s->bottom_field,
1190 (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1198 handle_rstn(s, nb_components);
1204 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1205 int se, int Ah, int Al)
1209 int c = s->comp_index[0];
1210 uint8_t *data = s->picture.data[c];
1211 int linesize = s->linesize[c];
1213 int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1214 int bytes_per_pixel = 1 + (s->bits > 8);
1216 av_assert0(ss>=0 && Ah>=0 && Al>=0);
1217 if (se < ss || se > 63) {
1218 av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1219 return AVERROR_INVALIDDATA;
1223 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1224 last_scan = !~s->coefs_finished[c];
1227 if (s->interlaced && s->bottom_field)
1228 data += linesize >> 1;
1230 s->restart_count = 0;
1232 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1233 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1234 int block_idx = mb_y * s->block_stride[c];
1235 int16_t (*block)[64] = &s->blocks[c][block_idx];
1236 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1237 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1239 if (s->restart_interval && !s->restart_count)
1240 s->restart_count = s->restart_interval;
1243 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1244 quant_matrix, ss, se, Al, &EOBRUN);
1246 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1247 quant_matrix, ss, se, Al, &EOBRUN);
1249 av_log(s->avctx, AV_LOG_ERROR,
1250 "error y=%d x=%d\n", mb_y, mb_x);
1251 return AVERROR_INVALIDDATA;
1255 s->dsp.idct_put(ptr, linesize, *block);
1257 shift_output(s, ptr, linesize);
1258 ptr += bytes_per_pixel*8 >> s->avctx->lowres;
1260 if (handle_rstn(s, 0))
1267 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1268 const AVFrame *reference)
1270 int len, nb_components, i, h, v, predictor, point_transform;
1272 const int block_size = s->lossless ? 1 : 8;
1273 int ilv, prev_shift;
1275 if (!s->got_picture) {
1276 av_log(s->avctx, AV_LOG_WARNING,
1277 "Can not process SOS before SOF, skipping\n");
1281 av_assert0(s->picture_ptr->data[0]);
1282 /* XXX: verify len field validity */
1283 len = get_bits(&s->gb, 16);
1284 nb_components = get_bits(&s->gb, 8);
1285 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1286 av_log(s->avctx, AV_LOG_ERROR,
1287 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1288 return AVERROR_PATCHWELCOME;
1290 if (len != 6 + 2 * nb_components) {
1291 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1292 return AVERROR_INVALIDDATA;
1294 for (i = 0; i < nb_components; i++) {
1295 id = get_bits(&s->gb, 8) - 1;
1296 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1297 /* find component index */
1298 for (index = 0; index < s->nb_components; index++)
1299 if (id == s->component_id[index])
1301 if (index == s->nb_components) {
1302 av_log(s->avctx, AV_LOG_ERROR,
1303 "decode_sos: index(%d) out of components\n", index);
1304 return AVERROR_INVALIDDATA;
1306 /* Metasoft MJPEG codec has Cb and Cr swapped */
1307 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1308 && nb_components == 3 && s->nb_components == 3 && i)
1311 s->quant_sindex[i] = s->quant_index[index];
1312 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1313 s->h_scount[i] = s->h_count[index];
1314 s->v_scount[i] = s->v_count[index];
1316 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1318 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1319 index = (index+2)%3;
1321 s->comp_index[i] = index;
1323 s->dc_index[i] = get_bits(&s->gb, 4);
1324 s->ac_index[i] = get_bits(&s->gb, 4);
1326 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1327 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1329 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))
1333 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1334 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1335 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1336 prev_shift = get_bits(&s->gb, 4); /* Ah */
1337 point_transform = get_bits(&s->gb, 4); /* Al */
1339 prev_shift = point_transform = 0;
1341 if (nb_components > 1) {
1342 /* interleaved stream */
1343 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1344 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1345 } else if (!s->ls) { /* skip this for JPEG-LS */
1346 h = s->h_max / s->h_scount[0];
1347 v = s->v_max / s->v_scount[0];
1348 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1349 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1350 s->nb_blocks[0] = 1;
1355 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1356 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1357 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1358 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1359 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1362 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1363 for (i = s->mjpb_skiptosod; i > 0; i--)
1364 skip_bits(&s->gb, 8);
1367 for (i = 0; i < nb_components; i++)
1368 s->last_dc[i] = (4 << s->bits);
1371 av_assert0(s->picture_ptr == &s->picture);
1372 if (CONFIG_JPEGLS_DECODER && s->ls) {
1374 // reset_ls_coding_parameters(s, 0);
1376 if ((ret = ff_jpegls_decode_picture(s, predictor,
1377 point_transform, ilv)) < 0)
1381 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1384 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1386 nb_components)) < 0)
1391 if (s->progressive && predictor) {
1392 av_assert0(s->picture_ptr == &s->picture);
1393 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1395 point_transform)) < 0)
1398 if ((ret = mjpeg_decode_scan(s, nb_components,
1399 prev_shift, point_transform,
1400 mb_bitmask, reference)) < 0)
1405 if (s->interlaced &&
1406 get_bits_left(&s->gb) > 32 &&
1407 show_bits(&s->gb, 8) == 0xFF) {
1408 GetBitContext bak = s->gb;
1409 align_get_bits(&bak);
1410 if (show_bits(&bak, 16) == 0xFFD1) {
1411 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1413 skip_bits(&s->gb, 16);
1414 s->bottom_field ^= 1;
1423 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1424 return AVERROR_INVALIDDATA;
1427 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1429 if (get_bits(&s->gb, 16) != 4)
1430 return AVERROR_INVALIDDATA;
1431 s->restart_interval = get_bits(&s->gb, 16);
1432 s->restart_count = 0;
1433 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1434 s->restart_interval);
1439 static int mjpeg_decode_app(MJpegDecodeContext *s)
1443 len = get_bits(&s->gb, 16);
1445 return AVERROR_INVALIDDATA;
1446 if (8 * len > get_bits_left(&s->gb))
1447 return AVERROR_INVALIDDATA;
1449 id = get_bits_long(&s->gb, 32);
1452 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1453 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X len=%d\n", id, len);
1455 /* Buggy AVID, it puts EOI only at every 10th frame. */
1456 /* Also, this fourcc is used by non-avid files too, it holds some
1457 information, but it's always present in AVID-created files. */
1458 if (id == AV_RB32("AVI1")) {
1464 4bytes field_size_less_padding
1467 i = get_bits(&s->gb, 8); len--;
1468 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1470 skip_bits(&s->gb, 8);
1471 skip_bits(&s->gb, 32);
1472 skip_bits(&s->gb, 32);
1480 if (id == AV_RB32("JFIF")) {
1481 int t_w, t_h, v1, v2;
1482 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1483 v1 = get_bits(&s->gb, 8);
1484 v2 = get_bits(&s->gb, 8);
1485 skip_bits(&s->gb, 8);
1487 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1488 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1490 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1491 av_log(s->avctx, AV_LOG_INFO,
1492 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1494 s->avctx->sample_aspect_ratio.num,
1495 s->avctx->sample_aspect_ratio.den);
1497 t_w = get_bits(&s->gb, 8);
1498 t_h = get_bits(&s->gb, 8);
1500 /* skip thumbnail */
1501 if (len -10 - (t_w * t_h * 3) > 0)
1502 len -= t_w * t_h * 3;
1508 if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1509 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1510 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1511 skip_bits(&s->gb, 16); /* version */
1512 skip_bits(&s->gb, 16); /* flags0 */
1513 skip_bits(&s->gb, 16); /* flags1 */
1514 skip_bits(&s->gb, 8); /* transform */
1519 if (id == AV_RB32("LJIF")) {
1520 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1521 av_log(s->avctx, AV_LOG_INFO,
1522 "Pegasus lossless jpeg header found\n");
1523 skip_bits(&s->gb, 16); /* version ? */
1524 skip_bits(&s->gb, 16); /* unknown always 0? */
1525 skip_bits(&s->gb, 16); /* unknown always 0? */
1526 skip_bits(&s->gb, 16); /* unknown always 0? */
1527 switch (i=get_bits(&s->gb, 8)) {
1537 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);
1542 if (id == AV_RL32("colr") && len > 0) {
1543 s->colr = get_bits(&s->gb, 8);
1544 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1545 av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1549 if (id == AV_RL32("xfrm") && len > 0) {
1550 s->xfrm = get_bits(&s->gb, 8);
1551 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1552 av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1558 if (s->start_code == APP1 && id == AV_RB32("Exif")) {
1559 GetByteContext gbytes;
1560 int ret, le, ifd_offset, bytes_read;
1561 const uint8_t *aligned;
1563 skip_bits(&s->gb, 16); // skip padding
1566 // init byte wise reading
1567 aligned = align_get_bits(&s->gb);
1568 bytestream2_init(&gbytes, aligned, len);
1571 ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
1573 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
1577 bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
1579 // read 0th IFD and store the metadata
1580 // (return values > 0 indicate the presence of subimage metadata)
1581 ret = ff_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
1583 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
1587 bytes_read = bytestream2_tell(&gbytes);
1588 skip_bits(&s->gb, bytes_read << 3);
1595 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1596 id = get_bits_long(&s->gb, 32);
1599 if (id == AV_RB32("mjpg")) {
1601 skip_bits(&s->gb, 32); /* field size */
1602 skip_bits(&s->gb, 32); /* pad field size */
1603 skip_bits(&s->gb, 32); /* next off */
1604 skip_bits(&s->gb, 32); /* quant off */
1605 skip_bits(&s->gb, 32); /* huff off */
1606 skip_bits(&s->gb, 32); /* image off */
1607 skip_bits(&s->gb, 32); /* scan off */
1608 skip_bits(&s->gb, 32); /* data off */
1610 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1611 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1616 /* slow but needed for extreme adobe jpegs */
1618 av_log(s->avctx, AV_LOG_ERROR,
1619 "mjpeg: error, decode_app parser read over the end\n");
1621 skip_bits(&s->gb, 8);
1626 static int mjpeg_decode_com(MJpegDecodeContext *s)
1628 int len = get_bits(&s->gb, 16);
1629 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1630 char *cbuf = av_malloc(len - 1);
1633 for (i = 0; i < len - 2; i++)
1634 cbuf[i] = get_bits(&s->gb, 8);
1635 if (i > 0 && cbuf[i - 1] == '\n')
1640 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1641 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1643 /* buggy avid, it puts EOI only at every 10th frame */
1644 if (!strncmp(cbuf, "AVID", 4)) {
1646 if (len > 14 && cbuf[12] == 1) /* 1 - NTSC, 2 - PAL */
1647 s->interlace_polarity = 1;
1648 } else if (!strcmp(cbuf, "CS=ITU601"))
1650 else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1651 (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1661 /* return the 8 bit start code value and update the search
1662 state. Return -1 if no start code found */
1663 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1665 const uint8_t *buf_ptr;
1670 buf_ptr = *pbuf_ptr;
1671 while (buf_end - buf_ptr > 1) {
1674 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1683 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1684 *pbuf_ptr = buf_ptr;
1688 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1689 const uint8_t **buf_ptr, const uint8_t *buf_end,
1690 const uint8_t **unescaped_buf_ptr,
1691 int *unescaped_buf_size)
1694 start_code = find_marker(buf_ptr, buf_end);
1696 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1698 return AVERROR(ENOMEM);
1700 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1701 if (start_code == SOS && !s->ls) {
1702 const uint8_t *src = *buf_ptr;
1703 uint8_t *dst = s->buffer;
1705 while (src < buf_end) {
1706 uint8_t x = *(src++);
1709 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1711 while (src < buf_end && x == 0xff)
1714 if (x >= 0xd0 && x <= 0xd7)
1721 *unescaped_buf_ptr = s->buffer;
1722 *unescaped_buf_size = dst - s->buffer;
1723 memset(s->buffer + *unescaped_buf_size, 0,
1724 FF_INPUT_BUFFER_PADDING_SIZE);
1726 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1727 (buf_end - *buf_ptr) - (dst - s->buffer));
1728 } else if (start_code == SOS && s->ls) {
1729 const uint8_t *src = *buf_ptr;
1730 uint8_t *dst = s->buffer;
1738 while (src + t < buf_end) {
1739 uint8_t x = src[t++];
1741 while ((src + t < buf_end) && x == 0xff)
1750 init_put_bits(&pb, dst, t);
1752 /* unescape bitstream */
1754 uint8_t x = src[b++];
1755 put_bits(&pb, 8, x);
1758 put_bits(&pb, 7, x);
1762 flush_put_bits(&pb);
1764 *unescaped_buf_ptr = dst;
1765 *unescaped_buf_size = (bit_count + 7) >> 3;
1766 memset(s->buffer + *unescaped_buf_size, 0,
1767 FF_INPUT_BUFFER_PADDING_SIZE);
1769 *unescaped_buf_ptr = *buf_ptr;
1770 *unescaped_buf_size = buf_end - *buf_ptr;
1776 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1779 const uint8_t *buf = avpkt->data;
1780 int buf_size = avpkt->size;
1781 MJpegDecodeContext *s = avctx->priv_data;
1782 const uint8_t *buf_end, *buf_ptr;
1783 const uint8_t *unescaped_buf_ptr;
1785 int unescaped_buf_size;
1790 av_dict_free(&s->exif_metadata);
1793 buf_end = buf + buf_size;
1794 while (buf_ptr < buf_end) {
1795 /* find start next marker */
1796 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1798 &unescaped_buf_size);
1800 if (start_code < 0) {
1802 } else if (unescaped_buf_size > INT_MAX / 8) {
1803 av_log(avctx, AV_LOG_ERROR,
1804 "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1805 start_code, unescaped_buf_size, buf_size);
1806 return AVERROR_INVALIDDATA;
1808 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1809 start_code, buf_end - buf_ptr);
1811 ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1814 av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1818 s->start_code = start_code;
1819 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1820 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1822 /* process markers */
1823 if (start_code >= 0xd0 && start_code <= 0xd7)
1824 av_log(avctx, AV_LOG_DEBUG,
1825 "restart marker: %d\n", start_code & 0x0f);
1827 else if (start_code >= APP0 && start_code <= APP15)
1828 mjpeg_decode_app(s);
1830 else if (start_code == COM)
1831 mjpeg_decode_com(s);
1835 if (!CONFIG_JPEGLS_DECODER &&
1836 (start_code == SOF48 || start_code == LSE)) {
1837 av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1838 return AVERROR(ENOSYS);
1841 switch (start_code) {
1843 s->restart_interval = 0;
1844 s->restart_count = 0;
1845 /* nothing to do on SOI */
1848 ff_mjpeg_decode_dqt(s);
1851 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1852 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1861 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1868 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1875 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1882 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1886 if (!CONFIG_JPEGLS_DECODER ||
1887 (ret = ff_jpegls_decode_lse(s)) < 0)
1893 if (!s->got_picture) {
1894 av_log(avctx, AV_LOG_WARNING,
1895 "Found EOI before any SOF, ignoring\n");
1898 if (s->interlaced) {
1899 s->bottom_field ^= 1;
1900 /* if not bottom field, do not output image yet */
1901 if (s->bottom_field == !s->interlace_polarity)
1904 if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)
1910 int qp = FFMAX3(s->qscale[0],
1913 int qpw = (s->width + 15) / 16;
1914 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1916 memset(qp_table_buf->data, qp, qpw);
1917 av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1920 if(avctx->debug & FF_DEBUG_QP)
1921 av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1926 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1927 (avctx->err_recognition & AV_EF_EXPLODE))
1931 mjpeg_decode_dri(s);
1943 av_log(avctx, AV_LOG_ERROR,
1944 "mjpeg: unsupported coding type (%x)\n", start_code);
1948 /* eof process start code */
1949 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1950 av_log(avctx, AV_LOG_DEBUG,
1951 "marker parser used %d bytes (%d bits)\n",
1952 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1954 if (s->got_picture) {
1955 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1958 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1959 return AVERROR_INVALIDDATA;
1965 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1966 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1967 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1968 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1969 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1970 for (i = 0; i < s->chroma_height; i++) {
1971 for (index = s->width - 1; index; index--)
1972 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1973 line += s->linesize[s->upscale_h];
1977 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1979 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1980 w = s->width >> hshift;
1981 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1982 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1983 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1984 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1985 for (i = s->height - 1; i; i--) {
1986 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1987 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1989 memcpy(dst, src1, w);
1991 for (index = 0; index < w; index++)
1992 dst[index] = (src1[index] + src2[index]) >> 1;
1994 dst -= s->linesize[s->upscale_v];
1997 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1999 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
2000 for (index=0; index<4; index++) {
2001 uint8_t *dst = s->picture_ptr->data[index];
2004 if(index && index<3){
2005 w = FF_CEIL_RSHIFT(w, hshift);
2006 h = FF_CEIL_RSHIFT(h, vshift);
2009 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
2010 for (i=0; i<h/2; i++) {
2012 FFSWAP(int, dst[j], dst2[j]);
2013 dst += s->linesize[index];
2014 dst2 -= s->linesize[index];
2020 av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);
2021 av_dict_free(&s->exif_metadata);
2023 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
2025 // return buf_end - buf_ptr;
2026 return buf_ptr - buf;
2029 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
2031 MJpegDecodeContext *s = avctx->priv_data;
2034 if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
2035 av_log(avctx, AV_LOG_INFO, "Single field\n");
2039 av_frame_unref(s->picture_ptr);
2042 av_freep(&s->ljpeg_buffer);
2043 s->ljpeg_buffer_size = 0;
2045 for (i = 0; i < 3; i++) {
2046 for (j = 0; j < 4; j++)
2047 ff_free_vlc(&s->vlcs[i][j]);
2049 for (i = 0; i < MAX_COMPONENTS; i++) {
2050 av_freep(&s->blocks[i]);
2051 av_freep(&s->last_nnz[i]);
2053 av_dict_free(&s->exif_metadata);
2057 static void decode_flush(AVCodecContext *avctx)
2059 MJpegDecodeContext *s = avctx->priv_data;
2063 #if CONFIG_MJPEG_DECODER
2064 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
2065 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2066 static const AVOption options[] = {
2067 { "extern_huff", "Use external huffman table.",
2068 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
2072 static const AVClass mjpegdec_class = {
2073 .class_name = "MJPEG decoder",
2074 .item_name = av_default_item_name,
2076 .version = LIBAVUTIL_VERSION_INT,
2079 AVCodec ff_mjpeg_decoder = {
2081 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
2082 .type = AVMEDIA_TYPE_VIDEO,
2083 .id = AV_CODEC_ID_MJPEG,
2084 .priv_data_size = sizeof(MJpegDecodeContext),
2085 .init = ff_mjpeg_decode_init,
2086 .close = ff_mjpeg_decode_end,
2087 .decode = ff_mjpeg_decode_frame,
2088 .flush = decode_flush,
2089 .capabilities = CODEC_CAP_DR1,
2091 .priv_class = &mjpegdec_class,
2094 #if CONFIG_THP_DECODER
2095 AVCodec ff_thp_decoder = {
2097 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
2098 .type = AVMEDIA_TYPE_VIDEO,
2099 .id = AV_CODEC_ID_THP,
2100 .priv_data_size = sizeof(MJpegDecodeContext),
2101 .init = ff_mjpeg_decode_init,
2102 .close = ff_mjpeg_decode_end,
2103 .decode = ff_mjpeg_decode_frame,
2104 .flush = decode_flush,
2105 .capabilities = CODEC_CAP_DR1,