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;
90 if (!s->picture_ptr) {
91 s->picture = av_frame_alloc();
93 return AVERROR(ENOMEM);
94 s->picture_ptr = s->picture;
98 ff_hpeldsp_init(&s->hdsp, avctx->flags);
99 ff_dsputil_init(&s->dsp, avctx);
100 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
104 s->first_picture = 1;
106 s->org_height = avctx->coded_height;
107 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
109 build_basic_mjpeg_vlc(s);
111 if (s->extern_huff) {
112 av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
113 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
114 if (ff_mjpeg_decode_dht(s)) {
115 av_log(avctx, AV_LOG_ERROR,
116 "error using external huffman table, switching back to internal\n");
117 build_basic_mjpeg_vlc(s);
120 if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
121 s->interlace_polarity = 1; /* bottom field first */
122 av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
124 if (avctx->codec->id == AV_CODEC_ID_AMV)
131 /* quantize tables */
132 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
134 int len, index, i, j;
136 len = get_bits(&s->gb, 16) - 2;
139 int pr = get_bits(&s->gb, 4);
141 av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
142 return AVERROR_INVALIDDATA;
144 index = get_bits(&s->gb, 4);
147 av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
148 /* read quant table */
149 for (i = 0; i < 64; i++) {
150 j = s->scantable.permutated[i];
151 s->quant_matrixes[index][j] = get_bits(&s->gb, pr ? 16 : 8);
154 // XXX FIXME finetune, and perhaps add dc too
155 s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
156 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
157 av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
158 index, s->qscale[index]);
164 /* decode huffman tables and build VLC decoders */
165 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
167 int len, index, i, class, n, v, code_max;
168 uint8_t bits_table[17];
169 uint8_t val_table[256];
172 len = get_bits(&s->gb, 16) - 2;
176 return AVERROR_INVALIDDATA;
177 class = get_bits(&s->gb, 4);
179 return AVERROR_INVALIDDATA;
180 index = get_bits(&s->gb, 4);
182 return AVERROR_INVALIDDATA;
184 for (i = 1; i <= 16; i++) {
185 bits_table[i] = get_bits(&s->gb, 8);
189 if (len < n || n > 256)
190 return AVERROR_INVALIDDATA;
193 for (i = 0; i < n; i++) {
194 v = get_bits(&s->gb, 8);
201 /* build VLC and flush previous vlc if present */
202 ff_free_vlc(&s->vlcs[class][index]);
203 av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
204 class, index, code_max + 1);
205 if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
206 code_max + 1, 0, class > 0)) < 0)
210 ff_free_vlc(&s->vlcs[2][index]);
211 if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
212 code_max + 1, 0, 0)) < 0)
219 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
221 int len, nb_components, i, width, height, pix_fmt_id, ret;
222 int h_count[MAX_COMPONENTS];
223 int v_count[MAX_COMPONENTS];
226 s->upscale_h = s->upscale_v = 0;
228 /* XXX: verify len field validity */
229 len = get_bits(&s->gb, 16);
230 s->avctx->bits_per_raw_sample =
231 s->bits = get_bits(&s->gb, 8);
235 if (s->bits == 9 && !s->pegasus_rct)
236 s->rct = 1; // FIXME ugly
238 if(s->lossless && s->avctx->lowres){
239 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
243 height = get_bits(&s->gb, 16);
244 width = get_bits(&s->gb, 16);
246 // HACK for odd_height.mov
247 if (s->interlaced && s->width == width && s->height == height + 1)
250 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
251 if (av_image_check_size(width, height, 0, s->avctx))
252 return AVERROR_INVALIDDATA;
254 nb_components = get_bits(&s->gb, 8);
255 if (nb_components <= 0 ||
256 nb_components > MAX_COMPONENTS)
258 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
259 if (nb_components != s->nb_components) {
260 av_log(s->avctx, AV_LOG_ERROR,
261 "nb_components changing in interlaced picture\n");
262 return AVERROR_INVALIDDATA;
265 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
266 avpriv_report_missing_feature(s->avctx,
267 "JPEG-LS that is not <= 8 "
268 "bits/component or 16-bit gray");
269 return AVERROR_PATCHWELCOME;
271 s->nb_components = nb_components;
274 memset(h_count, 0, sizeof(h_count));
275 memset(v_count, 0, sizeof(v_count));
276 for (i = 0; i < nb_components; i++) {
278 s->component_id[i] = get_bits(&s->gb, 8) - 1;
279 h_count[i] = get_bits(&s->gb, 4);
280 v_count[i] = get_bits(&s->gb, 4);
281 /* compute hmax and vmax (only used in interleaved case) */
282 if (h_count[i] > s->h_max)
283 s->h_max = h_count[i];
284 if (v_count[i] > s->v_max)
285 s->v_max = v_count[i];
286 s->quant_index[i] = get_bits(&s->gb, 8);
287 if (s->quant_index[i] >= 4) {
288 av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
289 return AVERROR_INVALIDDATA;
291 if (!h_count[i] || !v_count[i]) {
292 av_log(s->avctx, AV_LOG_ERROR,
293 "Invalid sampling factor in component %d %d:%d\n",
294 i, h_count[i], v_count[i]);
295 return AVERROR_INVALIDDATA;
298 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
299 i, h_count[i], v_count[i],
300 s->component_id[i], s->quant_index[i]);
303 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
304 avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
305 return AVERROR_PATCHWELCOME;
309 /* if different size, realloc/alloc picture */
310 if ( width != s->width || height != s->height
311 || memcmp(s->h_count, h_count, sizeof(h_count))
312 || memcmp(s->v_count, v_count, sizeof(v_count))) {
316 memcpy(s->h_count, h_count, sizeof(h_count));
317 memcpy(s->v_count, v_count, sizeof(v_count));
321 /* test interlaced mode */
322 if (s->first_picture &&
323 s->org_height != 0 &&
324 s->height < ((s->org_height * 3) / 4)) {
326 s->bottom_field = s->interlace_polarity;
327 s->picture_ptr->interlaced_frame = 1;
328 s->picture_ptr->top_field_first = !s->interlace_polarity;
332 ret = ff_set_dimensions(s->avctx, width, height);
336 s->first_picture = 0;
339 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
340 if (s->progressive) {
341 avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
342 return AVERROR_INVALIDDATA;
345 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
347 else if (!s->lossless)
349 /* XXX: not complete test ! */
350 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
351 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
352 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
353 (s->h_count[3] << 4) | s->v_count[3];
354 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
355 /* NOTE we do not allocate pictures large enough for the possible
356 * padding of h/v_count being 4 */
357 if (!(pix_fmt_id & 0xD0D0D0D0))
358 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
359 if (!(pix_fmt_id & 0x0D0D0D0D))
360 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
362 switch (pix_fmt_id) {
365 s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_BGR48;
367 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
368 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_GBRP : AV_PIX_FMT_GBRP16;
370 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
371 else s->avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
372 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
375 av_assert0(s->nb_components == 3);
379 s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA64;
381 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_YUVA444P : AV_PIX_FMT_YUVA444P16;
382 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
384 av_assert0(s->nb_components == 4);
388 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
391 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
393 s->upscale_h = (pix_fmt_id == 0x22122100);
394 s->chroma_height = s->height;
398 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
401 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
402 s->upscale_v = (pix_fmt_id == 0x22211200);
404 s->chroma_height = s->height;
407 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
410 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
413 s->chroma_height = s->height / 2;
425 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
427 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
432 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
435 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
436 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
437 s->chroma_height = s->height / 2;
440 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
441 else s->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
442 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
446 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
449 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
450 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
453 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
454 else s->avctx->pix_fmt = AV_PIX_FMT_YUV420P16;
455 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
458 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
461 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
465 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
466 return AVERROR_PATCHWELCOME;
468 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
469 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
470 return AVERROR_PATCHWELCOME;
473 s->upscale_h = s->upscale_v = 0;
474 if (s->nb_components > 1)
475 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
476 else if (s->bits <= 8)
477 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
479 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
482 av_frame_unref(s->picture_ptr);
483 if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
485 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
486 s->picture_ptr->key_frame = 1;
489 for (i = 0; i < 3; i++)
490 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
492 av_dlog(s->avctx, "%d %d %d %d %d %d\n",
493 s->width, s->height, s->linesize[0], s->linesize[1],
494 s->interlaced, s->avctx->height);
496 if (len != (8 + (3 * nb_components)))
497 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
500 if (s->rgb && !s->lossless && !s->ls) {
501 av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
502 return AVERROR_PATCHWELCOME;
505 /* totally blank picture as progressive JPEG will only add details to it */
506 if (s->progressive) {
507 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
508 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
509 for (i = 0; i < s->nb_components; i++) {
510 int size = bw * bh * s->h_count[i] * s->v_count[i];
511 av_freep(&s->blocks[i]);
512 av_freep(&s->last_nnz[i]);
513 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
514 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
515 if (!s->blocks[i] || !s->last_nnz[i])
516 return AVERROR(ENOMEM);
517 s->block_stride[i] = bw * s->h_count[i];
519 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
524 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
527 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
528 if (code < 0 || code > 16) {
529 av_log(s->avctx, AV_LOG_WARNING,
530 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
531 0, dc_index, &s->vlcs[0][dc_index]);
536 return get_xbits(&s->gb, code);
541 /* decode block and dequantize */
542 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
543 int dc_index, int ac_index, int16_t *quant_matrix)
545 int code, i, j, level, val;
548 val = mjpeg_decode_dc(s, dc_index);
549 if (val == 0xfffff) {
550 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
551 return AVERROR_INVALIDDATA;
553 val = val * quant_matrix[0] + s->last_dc[component];
554 s->last_dc[component] = val;
558 {OPEN_READER(re, &s->gb);
560 UPDATE_CACHE(re, &s->gb);
561 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
563 i += ((unsigned)code) >> 4;
566 if (code > MIN_CACHE_BITS - 16)
567 UPDATE_CACHE(re, &s->gb);
570 int cache = GET_CACHE(re, &s->gb);
571 int sign = (~cache) >> 31;
572 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
575 LAST_SKIP_BITS(re, &s->gb, code);
578 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
579 return AVERROR_INVALIDDATA;
581 j = s->scantable.permutated[i];
582 block[j] = level * quant_matrix[j];
585 CLOSE_READER(re, &s->gb);}
590 static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
591 int component, int dc_index,
592 int16_t *quant_matrix, int Al)
595 s->dsp.clear_block(block);
596 val = mjpeg_decode_dc(s, dc_index);
597 if (val == 0xfffff) {
598 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
599 return AVERROR_INVALIDDATA;
601 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
602 s->last_dc[component] = val;
607 /* decode block and dequantize - progressive JPEG version */
608 static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
609 uint8_t *last_nnz, int ac_index,
610 int16_t *quant_matrix,
611 int ss, int se, int Al, int *EOBRUN)
613 int code, i, j, level, val, run;
621 OPEN_READER(re, &s->gb);
622 for (i = ss; ; i++) {
623 UPDATE_CACHE(re, &s->gb);
624 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
626 run = ((unsigned) code) >> 4;
630 if (code > MIN_CACHE_BITS - 16)
631 UPDATE_CACHE(re, &s->gb);
634 int cache = GET_CACHE(re, &s->gb);
635 int sign = (~cache) >> 31;
636 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
639 LAST_SKIP_BITS(re, &s->gb, code);
643 j = s->scantable.permutated[se];
644 block[j] = level * quant_matrix[j] << Al;
647 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
648 return AVERROR_INVALIDDATA;
650 j = s->scantable.permutated[i];
651 block[j] = level * quant_matrix[j] << Al;
653 if (run == 0xF) {// ZRL - skip 15 coefficients
656 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
657 return AVERROR_INVALIDDATA;
662 UPDATE_CACHE(re, &s->gb);
663 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
664 LAST_SKIP_BITS(re, &s->gb, run);
671 CLOSE_READER(re, &s->gb);
680 #define REFINE_BIT(j) { \
681 UPDATE_CACHE(re, &s->gb); \
682 sign = block[j] >> 15; \
683 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
684 ((quant_matrix[j] ^ sign) - sign) << Al; \
685 LAST_SKIP_BITS(re, &s->gb, 1); \
693 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
698 j = s->scantable.permutated[i]; \
701 else if (run-- == 0) \
705 /* decode block and dequantize - progressive JPEG refinement pass */
706 static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
708 int ac_index, int16_t *quant_matrix,
709 int ss, int se, int Al, int *EOBRUN)
711 int code, i = ss, j, sign, val, run;
712 int last = FFMIN(se, *last_nnz);
714 OPEN_READER(re, &s->gb);
719 UPDATE_CACHE(re, &s->gb);
720 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
723 run = ((unsigned) code) >> 4;
724 UPDATE_CACHE(re, &s->gb);
725 val = SHOW_UBITS(re, &s->gb, 1);
726 LAST_SKIP_BITS(re, &s->gb, 1);
728 j = s->scantable.permutated[i];
730 block[j] = ((quant_matrix[j]^val) - val) << Al;
734 CLOSE_READER(re, &s->gb);
738 run = ((unsigned) code) >> 4;
745 UPDATE_CACHE(re, &s->gb);
746 run += SHOW_UBITS(re, &s->gb, val);
747 LAST_SKIP_BITS(re, &s->gb, val);
759 for (; i <= last; i++) {
760 j = s->scantable.permutated[i];
764 CLOSE_READER(re, &s->gb);
771 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
776 if (s->restart_interval) {
778 if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
779 align_get_bits(&s->gb);
780 for (i = 0; i < nb_components; i++) /* reset dc */
781 s->last_dc[i] = (4 << s->bits);
784 i = 8 + ((-get_bits_count(&s->gb)) & 7);
786 if (s->restart_count == 0) {
787 if( show_bits(&s->gb, i) == (1 << i) - 1
788 || show_bits(&s->gb, i) == 0xFF) {
789 int pos = get_bits_count(&s->gb);
790 align_get_bits(&s->gb);
791 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
792 skip_bits(&s->gb, 8);
793 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
794 for (i = 0; i < nb_components; i++) /* reset dc */
795 s->last_dc[i] = (4 << s->bits);
798 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
805 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
808 uint16_t (*buffer)[4];
809 int left[4], top[4], topleft[4];
810 const int linesize = s->linesize[0];
811 const int mask = ((1 << s->bits) - 1) << point_transform;
815 if (s->nb_components != 3 && s->nb_components != 4)
816 return AVERROR_INVALIDDATA;
817 if (s->v_max != 1 || s->h_max != 1 || !s->lossless)
818 return AVERROR_INVALIDDATA;
821 s->restart_count = s->restart_interval;
823 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
824 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
825 buffer = s->ljpeg_buffer;
827 for (i = 0; i < 4; i++)
828 buffer[0][i] = 1 << (s->bits - 1);
830 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
831 uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
833 if (s->interlaced && s->bottom_field)
834 ptr += linesize >> 1;
836 for (i = 0; i < 4; i++)
837 top[i] = left[i] = topleft[i] = buffer[0][i];
839 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
840 int modified_predictor = predictor;
842 if (s->restart_interval && !s->restart_count){
843 s->restart_count = s->restart_interval;
847 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
849 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
850 modified_predictor = 1;
852 for (i=0;i<nb_components;i++) {
856 top[i] = buffer[mb_x][i];
858 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
860 dc = mjpeg_decode_dc(s, s->dc_index[i]);
864 left[i] = buffer[mb_x][i] =
865 mask & (pred + (dc << point_transform));
868 if (s->restart_interval && !--s->restart_count) {
869 align_get_bits(&s->gb);
870 skip_bits(&s->gb, 16); /* skip RSTn */
873 if (s->nb_components == 4) {
874 for(i=0; i<nb_components; i++) {
875 int c= s->comp_index[i];
877 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
878 ptr[4*mb_x+3-c] = buffer[mb_x][i];
880 } else if(s->bits == 9) {
881 return AVERROR_PATCHWELCOME;
883 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
884 ((uint16_t*)ptr)[4*mb_x+c] = buffer[mb_x][i];
889 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
890 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
891 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
892 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
894 } else if (s->pegasus_rct) {
895 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
896 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
897 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
898 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
901 for(i=0; i<nb_components; i++) {
902 int c= s->comp_index[i];
904 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
905 ptr[3*mb_x+2-c] = buffer[mb_x][i];
907 } else if(s->bits == 9) {
908 return AVERROR_PATCHWELCOME;
910 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
911 ((uint16_t*)ptr)[3*mb_x+2-c] = buffer[mb_x][i];
920 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
921 int point_transform, int nb_components)
923 int i, mb_x, mb_y, mask;
924 int bits= (s->bits+7)&~7;
928 point_transform += bits - s->bits;
929 mask = ((1 << s->bits) - 1) << point_transform;
931 av_assert0(nb_components>=1 && nb_components<=4);
933 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
934 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
935 if (s->restart_interval && !s->restart_count){
936 s->restart_count = s->restart_interval;
941 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
942 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
943 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
944 for (i = 0; i < nb_components; i++) {
947 int n, h, v, x, y, c, j, linesize;
949 c = s->comp_index[i];
954 linesize= s->linesize[c];
956 if(bits>8) linesize /= 2;
961 dc = mjpeg_decode_dc(s, s->dc_index[i]);
965 ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
968 pred= 1 << (bits - 1);
974 pred= ptr[-linesize];
976 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
980 if (s->interlaced && s->bottom_field)
981 ptr += linesize >> 1;
983 *ptr= pred + (dc << point_transform);
985 ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
988 pred= 1 << (bits - 1);
994 pred= ptr16[-linesize];
996 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1000 if (s->interlaced && s->bottom_field)
1001 ptr16 += linesize >> 1;
1003 *ptr16= pred + (dc << point_transform);
1012 for (i = 0; i < nb_components; i++) {
1015 int n, h, v, x, y, c, j, linesize, dc;
1016 n = s->nb_blocks[i];
1017 c = s->comp_index[i];
1022 linesize = s->linesize[c];
1024 if(bits>8) linesize /= 2;
1026 for (j = 0; j < n; j++) {
1029 dc = mjpeg_decode_dc(s, s->dc_index[i]);
1033 ptr = s->picture_ptr->data[c] +
1034 (linesize * (v * mb_y + y)) +
1035 (h * mb_x + x); //FIXME optimize this crap
1036 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
1039 *ptr = pred + (dc << point_transform);
1041 ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1042 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1045 *ptr16= pred + (dc << point_transform);
1055 if (s->restart_interval && !--s->restart_count) {
1056 align_get_bits(&s->gb);
1057 skip_bits(&s->gb, 16); /* skip RSTn */
1064 static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
1065 uint8_t *dst, const uint8_t *src,
1066 int linesize, int lowres)
1069 case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1071 case 1: copy_block4(dst, src, linesize, linesize, 4);
1073 case 2: copy_block2(dst, src, linesize, linesize, 2);
1075 case 3: *dst = *src;
1080 static void shift_output(MJpegDecodeContext *s, uint8_t *ptr, int linesize)
1082 int block_x, block_y;
1083 int size = 8 >> s->avctx->lowres;
1085 for (block_y=0; block_y<size; block_y++)
1086 for (block_x=0; block_x<size; block_x++)
1087 *(uint16_t*)(ptr + 2*block_x + block_y*linesize) <<= 16 - s->bits;
1089 for (block_y=0; block_y<size; block_y++)
1090 for (block_x=0; block_x<size; block_x++)
1091 *(ptr + block_x + block_y*linesize) <<= 8 - s->bits;
1095 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1096 int Al, const uint8_t *mb_bitmask,
1097 const AVFrame *reference)
1100 uint8_t *data[MAX_COMPONENTS];
1101 const uint8_t *reference_data[MAX_COMPONENTS];
1102 int linesize[MAX_COMPONENTS];
1103 GetBitContext mb_bitmask_gb;
1104 int bytes_per_pixel = 1 + (s->bits > 8);
1107 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1109 if (s->flipped && s->avctx->lowres) {
1110 av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
1113 s->restart_count = 0;
1114 for (i = 0; i < nb_components; i++) {
1115 int c = s->comp_index[i];
1116 data[c] = s->picture_ptr->data[c];
1117 reference_data[c] = reference ? reference->data[c] : NULL;
1118 linesize[c] = s->linesize[c];
1119 s->coefs_finished[c] |= 1;
1120 if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1121 // picture should be flipped upside-down for this codec
1122 int offset = (linesize[c] * (s->v_scount[i] *
1123 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
1125 reference_data[c] += offset;
1130 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1131 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1132 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1134 if (s->restart_interval && !s->restart_count)
1135 s->restart_count = s->restart_interval;
1137 if (get_bits_left(&s->gb) < 0) {
1138 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1139 -get_bits_left(&s->gb));
1140 return AVERROR_INVALIDDATA;
1142 for (i = 0; i < nb_components; i++) {
1144 int n, h, v, x, y, c, j;
1146 n = s->nb_blocks[i];
1147 c = s->comp_index[i];
1152 for (j = 0; j < n; j++) {
1153 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1154 (h * mb_x + x) * 8 * bytes_per_pixel) >> s->avctx->lowres);
1156 if (s->interlaced && s->bottom_field)
1157 block_offset += linesize[c] >> 1;
1158 ptr = data[c] + block_offset;
1159 if (!s->progressive) {
1161 mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1162 linesize[c], s->avctx->lowres);
1165 s->dsp.clear_block(s->block);
1166 if (decode_block(s, s->block, i,
1167 s->dc_index[i], s->ac_index[i],
1168 s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1169 av_log(s->avctx, AV_LOG_ERROR,
1170 "error y=%d x=%d\n", mb_y, mb_x);
1171 return AVERROR_INVALIDDATA;
1173 s->dsp.idct_put(ptr, linesize[c], s->block);
1175 shift_output(s, ptr, linesize[c]);
1178 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1180 int16_t *block = s->blocks[c][block_idx];
1182 block[0] += get_bits1(&s->gb) *
1183 s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1184 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1185 s->quant_matrixes[s->quant_sindex[i]],
1187 av_log(s->avctx, AV_LOG_ERROR,
1188 "error y=%d x=%d\n", mb_y, mb_x);
1189 return AVERROR_INVALIDDATA;
1192 av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1193 av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1194 mb_x, mb_y, x, y, c, s->bottom_field,
1195 (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1203 handle_rstn(s, nb_components);
1209 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1210 int se, int Ah, int Al)
1214 int c = s->comp_index[0];
1215 uint8_t *data = s->picture_ptr->data[c];
1216 int linesize = s->linesize[c];
1218 int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1219 int bytes_per_pixel = 1 + (s->bits > 8);
1221 av_assert0(ss>=0 && Ah>=0 && Al>=0);
1222 if (se < ss || se > 63) {
1223 av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1224 return AVERROR_INVALIDDATA;
1228 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1229 last_scan = !~s->coefs_finished[c];
1232 if (s->interlaced && s->bottom_field)
1233 data += linesize >> 1;
1235 s->restart_count = 0;
1237 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1238 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1239 int block_idx = mb_y * s->block_stride[c];
1240 int16_t (*block)[64] = &s->blocks[c][block_idx];
1241 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1242 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1244 if (s->restart_interval && !s->restart_count)
1245 s->restart_count = s->restart_interval;
1248 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1249 quant_matrix, ss, se, Al, &EOBRUN);
1251 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1252 quant_matrix, ss, se, Al, &EOBRUN);
1254 av_log(s->avctx, AV_LOG_ERROR,
1255 "error y=%d x=%d\n", mb_y, mb_x);
1256 return AVERROR_INVALIDDATA;
1260 s->dsp.idct_put(ptr, linesize, *block);
1262 shift_output(s, ptr, linesize);
1263 ptr += bytes_per_pixel*8 >> s->avctx->lowres;
1265 if (handle_rstn(s, 0))
1272 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1273 const AVFrame *reference)
1275 int len, nb_components, i, h, v, predictor, point_transform;
1277 const int block_size = s->lossless ? 1 : 8;
1278 int ilv, prev_shift;
1280 if (!s->got_picture) {
1281 av_log(s->avctx, AV_LOG_WARNING,
1282 "Can not process SOS before SOF, skipping\n");
1286 av_assert0(s->picture_ptr->data[0]);
1287 /* XXX: verify len field validity */
1288 len = get_bits(&s->gb, 16);
1289 nb_components = get_bits(&s->gb, 8);
1290 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1291 av_log(s->avctx, AV_LOG_ERROR,
1292 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1293 return AVERROR_PATCHWELCOME;
1295 if (len != 6 + 2 * nb_components) {
1296 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1297 return AVERROR_INVALIDDATA;
1299 for (i = 0; i < nb_components; i++) {
1300 id = get_bits(&s->gb, 8) - 1;
1301 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1302 /* find component index */
1303 for (index = 0; index < s->nb_components; index++)
1304 if (id == s->component_id[index])
1306 if (index == s->nb_components) {
1307 av_log(s->avctx, AV_LOG_ERROR,
1308 "decode_sos: index(%d) out of components\n", index);
1309 return AVERROR_INVALIDDATA;
1311 /* Metasoft MJPEG codec has Cb and Cr swapped */
1312 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1313 && nb_components == 3 && s->nb_components == 3 && i)
1316 s->quant_sindex[i] = s->quant_index[index];
1317 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1318 s->h_scount[i] = s->h_count[index];
1319 s->v_scount[i] = s->v_count[index];
1321 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1323 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1324 index = (index+2)%3;
1326 s->comp_index[i] = index;
1328 s->dc_index[i] = get_bits(&s->gb, 4);
1329 s->ac_index[i] = get_bits(&s->gb, 4);
1331 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1332 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1334 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))
1338 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1339 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1340 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1341 prev_shift = get_bits(&s->gb, 4); /* Ah */
1342 point_transform = get_bits(&s->gb, 4); /* Al */
1344 prev_shift = point_transform = 0;
1346 if (nb_components > 1) {
1347 /* interleaved stream */
1348 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1349 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1350 } else if (!s->ls) { /* skip this for JPEG-LS */
1351 h = s->h_max / s->h_scount[0];
1352 v = s->v_max / s->v_scount[0];
1353 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1354 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1355 s->nb_blocks[0] = 1;
1360 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1361 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1362 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1363 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1364 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1367 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1368 for (i = s->mjpb_skiptosod; i > 0; i--)
1369 skip_bits(&s->gb, 8);
1372 for (i = 0; i < nb_components; i++)
1373 s->last_dc[i] = (4 << s->bits);
1376 av_assert0(s->picture_ptr == s->picture);
1377 if (CONFIG_JPEGLS_DECODER && s->ls) {
1379 // reset_ls_coding_parameters(s, 0);
1381 if ((ret = ff_jpegls_decode_picture(s, predictor,
1382 point_transform, ilv)) < 0)
1386 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1389 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1391 nb_components)) < 0)
1396 if (s->progressive && predictor) {
1397 av_assert0(s->picture_ptr == s->picture);
1398 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1400 point_transform)) < 0)
1403 if ((ret = mjpeg_decode_scan(s, nb_components,
1404 prev_shift, point_transform,
1405 mb_bitmask, reference)) < 0)
1410 if (s->interlaced &&
1411 get_bits_left(&s->gb) > 32 &&
1412 show_bits(&s->gb, 8) == 0xFF) {
1413 GetBitContext bak = s->gb;
1414 align_get_bits(&bak);
1415 if (show_bits(&bak, 16) == 0xFFD1) {
1416 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1418 skip_bits(&s->gb, 16);
1419 s->bottom_field ^= 1;
1428 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1429 return AVERROR_INVALIDDATA;
1432 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1434 if (get_bits(&s->gb, 16) != 4)
1435 return AVERROR_INVALIDDATA;
1436 s->restart_interval = get_bits(&s->gb, 16);
1437 s->restart_count = 0;
1438 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1439 s->restart_interval);
1444 static int mjpeg_decode_app(MJpegDecodeContext *s)
1448 len = get_bits(&s->gb, 16);
1450 return AVERROR_INVALIDDATA;
1451 if (8 * len > get_bits_left(&s->gb))
1452 return AVERROR_INVALIDDATA;
1454 id = get_bits_long(&s->gb, 32);
1457 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1458 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X len=%d\n", id, len);
1460 /* Buggy AVID, it puts EOI only at every 10th frame. */
1461 /* Also, this fourcc is used by non-avid files too, it holds some
1462 information, but it's always present in AVID-created files. */
1463 if (id == AV_RB32("AVI1")) {
1469 4bytes field_size_less_padding
1472 i = get_bits(&s->gb, 8); len--;
1473 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1475 skip_bits(&s->gb, 8);
1476 skip_bits(&s->gb, 32);
1477 skip_bits(&s->gb, 32);
1485 if (id == AV_RB32("JFIF")) {
1486 int t_w, t_h, v1, v2;
1487 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1488 v1 = get_bits(&s->gb, 8);
1489 v2 = get_bits(&s->gb, 8);
1490 skip_bits(&s->gb, 8);
1492 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1493 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1495 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1496 av_log(s->avctx, AV_LOG_INFO,
1497 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1499 s->avctx->sample_aspect_ratio.num,
1500 s->avctx->sample_aspect_ratio.den);
1502 t_w = get_bits(&s->gb, 8);
1503 t_h = get_bits(&s->gb, 8);
1505 /* skip thumbnail */
1506 if (len -10 - (t_w * t_h * 3) > 0)
1507 len -= t_w * t_h * 3;
1513 if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1514 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1515 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1516 skip_bits(&s->gb, 16); /* version */
1517 skip_bits(&s->gb, 16); /* flags0 */
1518 skip_bits(&s->gb, 16); /* flags1 */
1519 skip_bits(&s->gb, 8); /* transform */
1524 if (id == AV_RB32("LJIF")) {
1525 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1526 av_log(s->avctx, AV_LOG_INFO,
1527 "Pegasus lossless jpeg header found\n");
1528 skip_bits(&s->gb, 16); /* version ? */
1529 skip_bits(&s->gb, 16); /* unknown always 0? */
1530 skip_bits(&s->gb, 16); /* unknown always 0? */
1531 skip_bits(&s->gb, 16); /* unknown always 0? */
1532 switch (i=get_bits(&s->gb, 8)) {
1542 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);
1547 if (id == AV_RL32("colr") && len > 0) {
1548 s->colr = get_bits(&s->gb, 8);
1549 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1550 av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1554 if (id == AV_RL32("xfrm") && len > 0) {
1555 s->xfrm = get_bits(&s->gb, 8);
1556 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1557 av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1563 if (s->start_code == APP1 && id == AV_RB32("Exif") && len >= 2) {
1564 GetByteContext gbytes;
1565 int ret, le, ifd_offset, bytes_read;
1566 const uint8_t *aligned;
1568 skip_bits(&s->gb, 16); // skip padding
1571 // init byte wise reading
1572 aligned = align_get_bits(&s->gb);
1573 bytestream2_init(&gbytes, aligned, len);
1576 ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
1578 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
1582 bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
1584 // read 0th IFD and store the metadata
1585 // (return values > 0 indicate the presence of subimage metadata)
1586 ret = ff_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
1588 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
1592 bytes_read = bytestream2_tell(&gbytes);
1593 skip_bits(&s->gb, bytes_read << 3);
1600 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1601 id = get_bits_long(&s->gb, 32);
1604 if (id == AV_RB32("mjpg")) {
1606 skip_bits(&s->gb, 32); /* field size */
1607 skip_bits(&s->gb, 32); /* pad field size */
1608 skip_bits(&s->gb, 32); /* next off */
1609 skip_bits(&s->gb, 32); /* quant off */
1610 skip_bits(&s->gb, 32); /* huff off */
1611 skip_bits(&s->gb, 32); /* image off */
1612 skip_bits(&s->gb, 32); /* scan off */
1613 skip_bits(&s->gb, 32); /* data off */
1615 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1616 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1621 /* slow but needed for extreme adobe jpegs */
1623 av_log(s->avctx, AV_LOG_ERROR,
1624 "mjpeg: error, decode_app parser read over the end\n");
1626 skip_bits(&s->gb, 8);
1631 static int mjpeg_decode_com(MJpegDecodeContext *s)
1633 int len = get_bits(&s->gb, 16);
1634 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1635 char *cbuf = av_malloc(len - 1);
1638 for (i = 0; i < len - 2; i++)
1639 cbuf[i] = get_bits(&s->gb, 8);
1640 if (i > 0 && cbuf[i - 1] == '\n')
1645 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1646 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1648 /* buggy avid, it puts EOI only at every 10th frame */
1649 if (!strncmp(cbuf, "AVID", 4)) {
1651 if (len > 14 && cbuf[12] == 1) /* 1 - NTSC, 2 - PAL */
1652 s->interlace_polarity = 1;
1653 } else if (!strcmp(cbuf, "CS=ITU601"))
1655 else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1656 (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1666 /* return the 8 bit start code value and update the search
1667 state. Return -1 if no start code found */
1668 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1670 const uint8_t *buf_ptr;
1675 buf_ptr = *pbuf_ptr;
1676 while (buf_end - buf_ptr > 1) {
1679 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1688 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1689 *pbuf_ptr = buf_ptr;
1693 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1694 const uint8_t **buf_ptr, const uint8_t *buf_end,
1695 const uint8_t **unescaped_buf_ptr,
1696 int *unescaped_buf_size)
1699 start_code = find_marker(buf_ptr, buf_end);
1701 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1703 return AVERROR(ENOMEM);
1705 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1706 if (start_code == SOS && !s->ls) {
1707 const uint8_t *src = *buf_ptr;
1708 uint8_t *dst = s->buffer;
1710 while (src < buf_end) {
1711 uint8_t x = *(src++);
1714 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1716 while (src < buf_end && x == 0xff)
1719 if (x >= 0xd0 && x <= 0xd7)
1726 *unescaped_buf_ptr = s->buffer;
1727 *unescaped_buf_size = dst - s->buffer;
1728 memset(s->buffer + *unescaped_buf_size, 0,
1729 FF_INPUT_BUFFER_PADDING_SIZE);
1731 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1732 (buf_end - *buf_ptr) - (dst - s->buffer));
1733 } else if (start_code == SOS && s->ls) {
1734 const uint8_t *src = *buf_ptr;
1735 uint8_t *dst = s->buffer;
1743 while (src + t < buf_end) {
1744 uint8_t x = src[t++];
1746 while ((src + t < buf_end) && x == 0xff)
1755 init_put_bits(&pb, dst, t);
1757 /* unescape bitstream */
1759 uint8_t x = src[b++];
1760 put_bits(&pb, 8, x);
1763 put_bits(&pb, 7, x);
1767 flush_put_bits(&pb);
1769 *unescaped_buf_ptr = dst;
1770 *unescaped_buf_size = (bit_count + 7) >> 3;
1771 memset(s->buffer + *unescaped_buf_size, 0,
1772 FF_INPUT_BUFFER_PADDING_SIZE);
1774 *unescaped_buf_ptr = *buf_ptr;
1775 *unescaped_buf_size = buf_end - *buf_ptr;
1781 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1784 const uint8_t *buf = avpkt->data;
1785 int buf_size = avpkt->size;
1786 MJpegDecodeContext *s = avctx->priv_data;
1787 const uint8_t *buf_end, *buf_ptr;
1788 const uint8_t *unescaped_buf_ptr;
1790 int unescaped_buf_size;
1795 av_dict_free(&s->exif_metadata);
1798 buf_end = buf + buf_size;
1799 while (buf_ptr < buf_end) {
1800 /* find start next marker */
1801 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1803 &unescaped_buf_size);
1805 if (start_code < 0) {
1807 } else if (unescaped_buf_size > INT_MAX / 8) {
1808 av_log(avctx, AV_LOG_ERROR,
1809 "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1810 start_code, unescaped_buf_size, buf_size);
1811 return AVERROR_INVALIDDATA;
1813 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1814 start_code, buf_end - buf_ptr);
1816 ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1819 av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1823 s->start_code = start_code;
1824 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1825 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1827 /* process markers */
1828 if (start_code >= 0xd0 && start_code <= 0xd7)
1829 av_log(avctx, AV_LOG_DEBUG,
1830 "restart marker: %d\n", start_code & 0x0f);
1832 else if (start_code >= APP0 && start_code <= APP15)
1833 mjpeg_decode_app(s);
1835 else if (start_code == COM)
1836 mjpeg_decode_com(s);
1840 if (!CONFIG_JPEGLS_DECODER &&
1841 (start_code == SOF48 || start_code == LSE)) {
1842 av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1843 return AVERROR(ENOSYS);
1846 switch (start_code) {
1848 s->restart_interval = 0;
1849 s->restart_count = 0;
1850 /* nothing to do on SOI */
1853 ff_mjpeg_decode_dqt(s);
1856 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1857 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1866 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1873 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1880 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1887 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1891 if (!CONFIG_JPEGLS_DECODER ||
1892 (ret = ff_jpegls_decode_lse(s)) < 0)
1898 if (!s->got_picture) {
1899 av_log(avctx, AV_LOG_WARNING,
1900 "Found EOI before any SOF, ignoring\n");
1903 if (s->interlaced) {
1904 s->bottom_field ^= 1;
1905 /* if not bottom field, do not output image yet */
1906 if (s->bottom_field == !s->interlace_polarity)
1909 if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)
1915 int qp = FFMAX3(s->qscale[0],
1918 int qpw = (s->width + 15) / 16;
1919 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
1921 memset(qp_table_buf->data, qp, qpw);
1922 av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
1925 if(avctx->debug & FF_DEBUG_QP)
1926 av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
1931 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1932 (avctx->err_recognition & AV_EF_EXPLODE))
1936 mjpeg_decode_dri(s);
1948 av_log(avctx, AV_LOG_ERROR,
1949 "mjpeg: unsupported coding type (%x)\n", start_code);
1953 /* eof process start code */
1954 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1955 av_log(avctx, AV_LOG_DEBUG,
1956 "marker parser used %d bytes (%d bits)\n",
1957 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1959 if (s->got_picture) {
1960 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1963 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1964 return AVERROR_INVALIDDATA;
1970 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1971 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1972 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1973 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1974 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1975 for (i = 0; i < s->chroma_height; i++) {
1976 for (index = s->width - 1; index; index--)
1977 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1978 line += s->linesize[s->upscale_h];
1982 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1984 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1985 w = s->width >> hshift;
1986 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1987 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1988 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1989 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1990 for (i = s->height - 1; i; i--) {
1991 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1992 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1994 memcpy(dst, src1, w);
1996 for (index = 0; index < w; index++)
1997 dst[index] = (src1[index] + src2[index]) >> 1;
1999 dst -= s->linesize[s->upscale_v];
2002 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
2004 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
2005 for (index=0; index<4; index++) {
2006 uint8_t *dst = s->picture_ptr->data[index];
2009 if(index && index<3){
2010 w = FF_CEIL_RSHIFT(w, hshift);
2011 h = FF_CEIL_RSHIFT(h, vshift);
2014 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
2015 for (i=0; i<h/2; i++) {
2017 FFSWAP(int, dst[j], dst2[j]);
2018 dst += s->linesize[index];
2019 dst2 -= s->linesize[index];
2025 av_dict_copy(avpriv_frame_get_metadatap(data), s->exif_metadata, 0);
2026 av_dict_free(&s->exif_metadata);
2028 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
2030 // return buf_end - buf_ptr;
2031 return buf_ptr - buf;
2034 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
2036 MJpegDecodeContext *s = avctx->priv_data;
2039 if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
2040 av_log(avctx, AV_LOG_INFO, "Single field\n");
2044 av_frame_free(&s->picture);
2045 s->picture_ptr = NULL;
2046 } else if (s->picture_ptr)
2047 av_frame_unref(s->picture_ptr);
2050 av_freep(&s->ljpeg_buffer);
2051 s->ljpeg_buffer_size = 0;
2053 for (i = 0; i < 3; i++) {
2054 for (j = 0; j < 4; j++)
2055 ff_free_vlc(&s->vlcs[i][j]);
2057 for (i = 0; i < MAX_COMPONENTS; i++) {
2058 av_freep(&s->blocks[i]);
2059 av_freep(&s->last_nnz[i]);
2061 av_dict_free(&s->exif_metadata);
2065 static void decode_flush(AVCodecContext *avctx)
2067 MJpegDecodeContext *s = avctx->priv_data;
2071 #if CONFIG_MJPEG_DECODER
2072 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
2073 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2074 static const AVOption options[] = {
2075 { "extern_huff", "Use external huffman table.",
2076 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
2080 static const AVClass mjpegdec_class = {
2081 .class_name = "MJPEG decoder",
2082 .item_name = av_default_item_name,
2084 .version = LIBAVUTIL_VERSION_INT,
2087 AVCodec ff_mjpeg_decoder = {
2089 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
2090 .type = AVMEDIA_TYPE_VIDEO,
2091 .id = AV_CODEC_ID_MJPEG,
2092 .priv_data_size = sizeof(MJpegDecodeContext),
2093 .init = ff_mjpeg_decode_init,
2094 .close = ff_mjpeg_decode_end,
2095 .decode = ff_mjpeg_decode_frame,
2096 .flush = decode_flush,
2097 .capabilities = CODEC_CAP_DR1,
2099 .priv_class = &mjpegdec_class,
2102 #if CONFIG_THP_DECODER
2103 AVCodec ff_thp_decoder = {
2105 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
2106 .type = AVMEDIA_TYPE_VIDEO,
2107 .id = AV_CODEC_ID_THP,
2108 .priv_data_size = sizeof(MJpegDecodeContext),
2109 .init = ff_mjpeg_decode_init,
2110 .close = ff_mjpeg_decode_end,
2111 .decode = ff_mjpeg_decode_frame,
2112 .flush = decode_flush,
2113 .capabilities = CODEC_CAP_DR1,