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"
40 #include "jpeglsdec.h"
43 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
44 const uint8_t *val_table, int nb_codes,
45 int use_static, int is_ac)
47 uint8_t huff_size[256] = { 0 };
48 uint16_t huff_code[256];
49 uint16_t huff_sym[256];
52 av_assert0(nb_codes <= 256);
54 ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
56 for (i = 0; i < 256; i++)
57 huff_sym[i] = i + 16 * is_ac;
60 huff_sym[0] = 16 * 256;
62 return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
63 huff_code, 2, 2, huff_sym, 2, 2, use_static);
66 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
68 build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
69 avpriv_mjpeg_val_dc, 12, 0, 0);
70 build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
71 avpriv_mjpeg_val_dc, 12, 0, 0);
72 build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
73 avpriv_mjpeg_val_ac_luminance, 251, 0, 1);
74 build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
75 avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);
76 build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
77 avpriv_mjpeg_val_ac_luminance, 251, 0, 0);
78 build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
79 avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);
82 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
84 MJpegDecodeContext *s = avctx->priv_data;
87 s->picture_ptr = &s->picture;
88 avcodec_get_frame_defaults(&s->picture);
91 ff_dsputil_init(&s->dsp, avctx);
92 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
97 s->org_height = avctx->coded_height;
98 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
100 build_basic_mjpeg_vlc(s);
102 if (s->extern_huff) {
103 av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
104 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
105 if (ff_mjpeg_decode_dht(s)) {
106 av_log(avctx, AV_LOG_ERROR,
107 "error using external huffman table, switching back to internal\n");
108 build_basic_mjpeg_vlc(s);
111 if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
112 s->interlace_polarity = 1; /* bottom field first */
113 av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
115 if (avctx->codec->id == AV_CODEC_ID_AMV)
122 /* quantize tables */
123 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
125 int len, index, i, j;
127 len = get_bits(&s->gb, 16) - 2;
130 /* only 8 bit precision handled */
131 if (get_bits(&s->gb, 4) != 0) {
132 av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
135 index = get_bits(&s->gb, 4);
138 av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
139 /* read quant table */
140 for (i = 0; i < 64; i++) {
141 j = s->scantable.permutated[i];
142 s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
145 // XXX FIXME finetune, and perhaps add dc too
146 s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
147 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
148 av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
149 index, s->qscale[index]);
155 /* decode huffman tables and build VLC decoders */
156 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
158 int len, index, i, class, n, v, code_max;
159 uint8_t bits_table[17];
160 uint8_t val_table[256];
163 len = get_bits(&s->gb, 16) - 2;
167 return AVERROR_INVALIDDATA;
168 class = get_bits(&s->gb, 4);
170 return AVERROR_INVALIDDATA;
171 index = get_bits(&s->gb, 4);
173 return AVERROR_INVALIDDATA;
175 for (i = 1; i <= 16; i++) {
176 bits_table[i] = get_bits(&s->gb, 8);
180 if (len < n || n > 256)
181 return AVERROR_INVALIDDATA;
184 for (i = 0; i < n; i++) {
185 v = get_bits(&s->gb, 8);
192 /* build VLC and flush previous vlc if present */
193 ff_free_vlc(&s->vlcs[class][index]);
194 av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
195 class, index, code_max + 1);
196 if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
197 code_max + 1, 0, class > 0)) < 0)
201 ff_free_vlc(&s->vlcs[2][index]);
202 if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
203 code_max + 1, 0, 0)) < 0)
210 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
212 int len, nb_components, i, width, height, pix_fmt_id;
215 s->upscale_h = s->upscale_v = 0;
217 /* XXX: verify len field validity */
218 len = get_bits(&s->gb, 16);
219 s->bits = get_bits(&s->gb, 8);
223 if (s->bits == 9 && !s->pegasus_rct)
224 s->rct = 1; // FIXME ugly
226 if (s->bits != 8 && !s->lossless) {
227 av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
231 if(s->lossless && s->avctx->lowres){
232 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
236 height = get_bits(&s->gb, 16);
237 width = get_bits(&s->gb, 16);
239 // HACK for odd_height.mov
240 if (s->interlaced && s->width == width && s->height == height + 1)
243 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
244 if (av_image_check_size(width, height, 0, s->avctx))
245 return AVERROR_INVALIDDATA;
247 nb_components = get_bits(&s->gb, 8);
248 if (nb_components <= 0 ||
249 nb_components > MAX_COMPONENTS)
251 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
252 if (nb_components != s->nb_components) {
253 av_log(s->avctx, AV_LOG_ERROR, "nb_components changing in interlaced picture\n");
254 return AVERROR_INVALIDDATA;
257 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
258 av_log_missing_feature(s->avctx,
259 "For JPEG-LS anything except <= 8 bits/component"
260 " or 16-bit gray", 0);
261 return AVERROR_PATCHWELCOME;
263 s->nb_components = nb_components;
266 for (i = 0; i < nb_components; i++) {
268 s->component_id[i] = get_bits(&s->gb, 8) - 1;
269 s->h_count[i] = get_bits(&s->gb, 4);
270 s->v_count[i] = get_bits(&s->gb, 4);
271 /* compute hmax and vmax (only used in interleaved case) */
272 if (s->h_count[i] > s->h_max)
273 s->h_max = s->h_count[i];
274 if (s->v_count[i] > s->v_max)
275 s->v_max = s->v_count[i];
276 if (!s->h_count[i] || !s->v_count[i]) {
277 av_log(s->avctx, AV_LOG_ERROR, "h/v_count is 0\n");
280 s->quant_index[i] = get_bits(&s->gb, 8);
281 if (s->quant_index[i] >= 4)
282 return AVERROR_INVALIDDATA;
283 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
284 i, s->h_count[i], s->v_count[i],
285 s->component_id[i], s->quant_index[i]);
288 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
289 av_log_missing_feature(s->avctx, "Subsampling in JPEG-LS", 0);
290 return AVERROR_PATCHWELCOME;
293 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && nb_components==3)
296 /* if different size, realloc/alloc picture */
297 /* XXX: also check h_count and v_count */
298 if (width != s->width || height != s->height) {
299 av_freep(&s->qscale_table);
305 /* test interlaced mode */
306 if (s->first_picture &&
307 s->org_height != 0 &&
308 s->height < ((s->org_height * 3) / 4)) {
310 s->bottom_field = s->interlace_polarity;
311 s->picture_ptr->interlaced_frame = 1;
312 s->picture_ptr->top_field_first = !s->interlace_polarity;
316 avcodec_set_dimensions(s->avctx, width, height);
318 s->qscale_table = av_mallocz((s->width + 15) / 16);
319 s->first_picture = 0;
322 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
323 if (s->progressive) {
324 av_log_ask_for_sample(s->avctx, "progressively coded interlaced pictures not supported\n");
325 return AVERROR_INVALIDDATA;
328 /* XXX: not complete test ! */
329 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
330 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
331 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
332 (s->h_count[3] << 4) | s->v_count[3];
333 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
334 /* NOTE we do not allocate pictures large enough for the possible
335 * padding of h/v_count being 4 */
336 if (!(pix_fmt_id & 0xD0D0D0D0))
337 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
338 if (!(pix_fmt_id & 0x0D0D0D0D))
339 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
341 switch (pix_fmt_id) {
344 s->avctx->pix_fmt = AV_PIX_FMT_BGR24;
346 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
347 s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
349 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
350 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
353 av_assert0(s->nb_components == 3);
357 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
358 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
360 s->upscale_h = (pix_fmt_id == 0x22122100);
361 s->chroma_height = s->height;
365 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
366 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
367 s->upscale_v = (pix_fmt_id == 0x22211200);
369 s->chroma_height = s->height;
372 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
373 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
376 s->chroma_height = s->height / 2;
380 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
382 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
387 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
388 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
389 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
390 s->chroma_height = s->height / 2;
393 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
394 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
398 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
399 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
400 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
403 s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
404 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
407 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
408 return AVERROR_PATCHWELCOME;
410 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
411 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
412 return AVERROR_PATCHWELCOME;
415 s->upscale_h = s->upscale_v = 0;
416 if (s->nb_components > 1)
417 s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
418 else if (s->bits <= 8)
419 s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
421 s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
424 if (s->picture_ptr->data[0])
425 s->avctx->release_buffer(s->avctx, s->picture_ptr);
427 if (s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0) {
428 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
431 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
432 s->picture_ptr->key_frame = 1;
435 for (i = 0; i < 3; i++)
436 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
438 av_dlog(s->avctx, "%d %d %d %d %d %d\n",
439 s->width, s->height, s->linesize[0], s->linesize[1],
440 s->interlaced, s->avctx->height);
442 if (len != (8 + (3 * nb_components)))
443 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
446 /* totally blank picture as progressive JPEG will only add details to it */
447 if (s->progressive) {
448 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
449 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
450 for (i = 0; i < s->nb_components; i++) {
451 int size = bw * bh * s->h_count[i] * s->v_count[i];
452 av_freep(&s->blocks[i]);
453 av_freep(&s->last_nnz[i]);
454 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
455 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
456 s->block_stride[i] = bw * s->h_count[i];
458 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
463 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
466 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
468 av_log(s->avctx, AV_LOG_WARNING,
469 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
470 0, dc_index, &s->vlcs[0][dc_index]);
475 return get_xbits(&s->gb, code);
480 /* decode block and dequantize */
481 static int decode_block(MJpegDecodeContext *s, DCTELEM *block, int component,
482 int dc_index, int ac_index, int16_t *quant_matrix)
484 int code, i, j, level, val;
487 val = mjpeg_decode_dc(s, dc_index);
489 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
490 return AVERROR_INVALIDDATA;
492 val = val * quant_matrix[0] + s->last_dc[component];
493 s->last_dc[component] = val;
497 {OPEN_READER(re, &s->gb);
499 UPDATE_CACHE(re, &s->gb);
500 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
502 i += ((unsigned)code) >> 4;
505 if (code > MIN_CACHE_BITS - 16)
506 UPDATE_CACHE(re, &s->gb);
509 int cache = GET_CACHE(re, &s->gb);
510 int sign = (~cache) >> 31;
511 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
514 LAST_SKIP_BITS(re, &s->gb, code);
517 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
518 return AVERROR_INVALIDDATA;
520 j = s->scantable.permutated[i];
521 block[j] = level * quant_matrix[j];
524 CLOSE_READER(re, &s->gb);}
529 static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block,
530 int component, int dc_index,
531 int16_t *quant_matrix, int Al)
534 s->dsp.clear_block(block);
535 val = mjpeg_decode_dc(s, dc_index);
537 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
538 return AVERROR_INVALIDDATA;
540 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
541 s->last_dc[component] = val;
546 /* decode block and dequantize - progressive JPEG version */
547 static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block,
548 uint8_t *last_nnz, int ac_index,
549 int16_t *quant_matrix,
550 int ss, int se, int Al, int *EOBRUN)
552 int code, i, j, level, val, run;
560 OPEN_READER(re, &s->gb);
561 for (i = ss; ; i++) {
562 UPDATE_CACHE(re, &s->gb);
563 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
565 run = ((unsigned) code) >> 4;
569 if (code > MIN_CACHE_BITS - 16)
570 UPDATE_CACHE(re, &s->gb);
573 int cache = GET_CACHE(re, &s->gb);
574 int sign = (~cache) >> 31;
575 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
578 LAST_SKIP_BITS(re, &s->gb, code);
582 j = s->scantable.permutated[se];
583 block[j] = level * quant_matrix[j] << Al;
586 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
587 return AVERROR_INVALIDDATA;
589 j = s->scantable.permutated[i];
590 block[j] = level * quant_matrix[j] << Al;
592 if (run == 0xF) {// ZRL - skip 15 coefficients
595 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
596 return AVERROR_INVALIDDATA;
601 UPDATE_CACHE(re, &s->gb);
602 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
603 LAST_SKIP_BITS(re, &s->gb, run);
610 CLOSE_READER(re, &s->gb);
619 #define REFINE_BIT(j) { \
620 UPDATE_CACHE(re, &s->gb); \
621 sign = block[j] >> 15; \
622 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
623 ((quant_matrix[j] ^ sign) - sign) << Al; \
624 LAST_SKIP_BITS(re, &s->gb, 1); \
632 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
637 j = s->scantable.permutated[i]; \
640 else if (run-- == 0) \
644 /* decode block and dequantize - progressive JPEG refinement pass */
645 static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block,
647 int ac_index, int16_t *quant_matrix,
648 int ss, int se, int Al, int *EOBRUN)
650 int code, i = ss, j, sign, val, run;
651 int last = FFMIN(se, *last_nnz);
653 OPEN_READER(re, &s->gb);
658 UPDATE_CACHE(re, &s->gb);
659 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
662 run = ((unsigned) code) >> 4;
663 UPDATE_CACHE(re, &s->gb);
664 val = SHOW_UBITS(re, &s->gb, 1);
665 LAST_SKIP_BITS(re, &s->gb, 1);
667 j = s->scantable.permutated[i];
669 block[j] = ((quant_matrix[j]^val) - val) << Al;
673 CLOSE_READER(re, &s->gb);
677 run = ((unsigned) code) >> 4;
684 UPDATE_CACHE(re, &s->gb);
685 run += SHOW_UBITS(re, &s->gb, val);
686 LAST_SKIP_BITS(re, &s->gb, val);
698 for (; i <= last; i++) {
699 j = s->scantable.permutated[i];
703 CLOSE_READER(re, &s->gb);
710 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
713 uint16_t (*buffer)[4];
714 int left[3], top[3], topleft[3];
715 const int linesize = s->linesize[0];
716 const int mask = (1 << s->bits) - 1;
720 s->restart_count = s->restart_interval;
722 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
723 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
724 buffer = s->ljpeg_buffer;
726 for (i = 0; i < 3; i++)
727 buffer[0][i] = 1 << (s->bits - 1);
729 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
730 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
732 if (s->interlaced && s->bottom_field)
733 ptr += linesize >> 1;
735 for (i = 0; i < 3; i++)
736 top[i] = left[i] = topleft[i] = buffer[0][i];
738 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
739 int modified_predictor = predictor;
741 if (s->restart_interval && !s->restart_count){
742 s->restart_count = s->restart_interval;
746 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
748 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
749 modified_predictor = 1;
751 for (i=0;i<nb_components;i++) {
755 top[i] = buffer[mb_x][i];
757 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
759 dc = mjpeg_decode_dc(s, s->dc_index[i]);
763 left[i] = buffer[mb_x][i] =
764 mask & (pred + (dc << point_transform));
767 if (s->restart_interval && !--s->restart_count) {
768 align_get_bits(&s->gb);
769 skip_bits(&s->gb, 16); /* skip RSTn */
774 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
775 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
776 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
777 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
779 } else if (s->pegasus_rct) {
780 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
781 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
782 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
783 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
786 for(i=0; i<nb_components; i++) {
787 int c= s->comp_index[i];
788 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
789 ptr[3*mb_x+2-c] = buffer[mb_x][i];
797 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
801 const int nb_components=s->nb_components;
802 int bits= (s->bits+7)&~7;
806 point_transform += bits - s->bits;
808 av_assert0(nb_components==1 || nb_components==3);
810 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
811 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
812 if (s->restart_interval && !s->restart_count){
813 s->restart_count = s->restart_interval;
818 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
819 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
820 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
821 for (i = 0; i < nb_components; i++) {
824 int n, h, v, x, y, c, j, linesize;
826 c = s->comp_index[i];
831 linesize= s->linesize[c];
833 if(bits>8) linesize /= 2;
838 dc = mjpeg_decode_dc(s, s->dc_index[i]);
842 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
845 pred= 1 << (bits - 1);
851 pred= ptr[-linesize];
853 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
857 if (s->interlaced && s->bottom_field)
858 ptr += linesize >> 1;
859 pred &= (-1)<<(8-s->bits);
860 *ptr= pred + (dc << point_transform);
862 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
865 pred= 1 << (bits - 1);
871 pred= ptr16[-linesize];
873 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
877 if (s->interlaced && s->bottom_field)
878 ptr16 += linesize >> 1;
879 pred &= (-1)<<(16-s->bits);
880 *ptr16= pred + (dc << point_transform);
889 for (i = 0; i < nb_components; i++) {
892 int n, h, v, x, y, c, j, linesize, dc;
894 c = s->comp_index[i];
899 linesize = s->linesize[c];
901 if(bits>8) linesize /= 2;
903 for (j = 0; j < n; j++) {
906 dc = mjpeg_decode_dc(s, s->dc_index[i]);
910 ptr = s->picture.data[c] +
911 (linesize * (v * mb_y + y)) +
912 (h * mb_x + x); //FIXME optimize this crap
913 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
915 pred &= (-1)<<(8-s->bits);
916 *ptr = pred + (dc << point_transform);
918 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
919 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
921 pred &= (-1)<<(16-s->bits);
922 *ptr16= pred + (dc << point_transform);
932 if (s->restart_interval && !--s->restart_count) {
933 align_get_bits(&s->gb);
934 skip_bits(&s->gb, 16); /* skip RSTn */
941 static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
942 int linesize, int lowres)
945 case 0: copy_block8(dst, src, linesize, linesize, 8);
947 case 1: copy_block4(dst, src, linesize, linesize, 4);
949 case 2: copy_block2(dst, src, linesize, linesize, 2);
956 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
957 int Al, const uint8_t *mb_bitmask,
958 const AVFrame *reference)
961 uint8_t *data[MAX_COMPONENTS];
962 const uint8_t *reference_data[MAX_COMPONENTS];
963 int linesize[MAX_COMPONENTS];
964 GetBitContext mb_bitmask_gb;
967 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
969 if (s->flipped && s->avctx->lowres) {
970 av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with lowres\n");
974 for (i = 0; i < nb_components; i++) {
975 int c = s->comp_index[i];
976 data[c] = s->picture_ptr->data[c];
977 reference_data[c] = reference ? reference->data[c] : NULL;
978 linesize[c] = s->linesize[c];
979 s->coefs_finished[c] |= 1;
980 if (s->flipped && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
981 // picture should be flipped upside-down for this codec
982 int offset = (linesize[c] * (s->v_scount[i] *
983 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
985 reference_data[c] += offset;
990 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
991 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
992 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
994 if (s->restart_interval && !s->restart_count)
995 s->restart_count = s->restart_interval;
997 if (get_bits_left(&s->gb) < 0) {
998 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
999 -get_bits_left(&s->gb));
1000 return AVERROR_INVALIDDATA;
1002 for (i = 0; i < nb_components; i++) {
1004 int n, h, v, x, y, c, j;
1006 n = s->nb_blocks[i];
1007 c = s->comp_index[i];
1012 for (j = 0; j < n; j++) {
1013 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1014 (h * mb_x + x) * 8) >> s->avctx->lowres);
1016 if (s->interlaced && s->bottom_field)
1017 block_offset += linesize[c] >> 1;
1018 ptr = data[c] + block_offset;
1019 if (!s->progressive) {
1021 mjpeg_copy_block(ptr, reference_data[c] + block_offset,
1022 linesize[c], s->avctx->lowres);
1024 s->dsp.clear_block(s->block);
1025 if (decode_block(s, s->block, i,
1026 s->dc_index[i], s->ac_index[i],
1027 s->quant_matrixes[s->quant_index[c]]) < 0) {
1028 av_log(s->avctx, AV_LOG_ERROR,
1029 "error y=%d x=%d\n", mb_y, mb_x);
1030 return AVERROR_INVALIDDATA;
1032 s->dsp.idct_put(ptr, linesize[c], s->block);
1035 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1037 DCTELEM *block = s->blocks[c][block_idx];
1039 block[0] += get_bits1(&s->gb) *
1040 s->quant_matrixes[s->quant_index[c]][0] << Al;
1041 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1042 s->quant_matrixes[s->quant_index[c]],
1044 av_log(s->avctx, AV_LOG_ERROR,
1045 "error y=%d x=%d\n", mb_y, mb_x);
1046 return AVERROR_INVALIDDATA;
1049 av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1050 av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1051 mb_x, mb_y, x, y, c, s->bottom_field,
1052 (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1060 if (s->restart_interval) {
1062 if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
1063 align_get_bits(&s->gb);
1064 for (i = 0; i < nb_components; i++) /* reset dc */
1065 s->last_dc[i] = 1024;
1068 i = 8 + ((-get_bits_count(&s->gb)) & 7);
1070 if (show_bits(&s->gb, i) == (1 << i) - 1) {
1071 int pos = get_bits_count(&s->gb);
1072 align_get_bits(&s->gb);
1073 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
1074 skip_bits(&s->gb, 8);
1075 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
1076 for (i = 0; i < nb_components; i++) /* reset dc */
1077 s->last_dc[i] = 1024;
1079 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
1087 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1088 int se, int Ah, int Al)
1092 int c = s->comp_index[0];
1093 uint8_t *data = s->picture.data[c];
1094 int linesize = s->linesize[c];
1096 int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
1099 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1100 last_scan = !~s->coefs_finished[c];
1103 if (s->interlaced && s->bottom_field)
1104 data += linesize >> 1;
1106 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1107 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1108 int block_idx = mb_y * s->block_stride[c];
1109 DCTELEM (*block)[64] = &s->blocks[c][block_idx];
1110 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1111 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1114 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1115 quant_matrix, ss, se, Al, &EOBRUN);
1117 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1118 quant_matrix, ss, se, Al, &EOBRUN);
1120 av_log(s->avctx, AV_LOG_ERROR,
1121 "error y=%d x=%d\n", mb_y, mb_x);
1122 return AVERROR_INVALIDDATA;
1126 s->dsp.idct_put(ptr, linesize, *block);
1127 ptr += 8 >> s->avctx->lowres;
1134 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1135 const AVFrame *reference)
1137 int len, nb_components, i, h, v, predictor, point_transform;
1139 const int block_size = s->lossless ? 1 : 8;
1140 int ilv, prev_shift;
1142 if (!s->got_picture) {
1143 av_log(s->avctx, AV_LOG_WARNING,
1144 "Can not process SOS before SOF, skipping\n");
1148 av_assert0(s->picture_ptr->data[0]);
1149 /* XXX: verify len field validity */
1150 len = get_bits(&s->gb, 16);
1151 nb_components = get_bits(&s->gb, 8);
1152 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1153 av_log(s->avctx, AV_LOG_ERROR,
1154 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1155 return AVERROR_PATCHWELCOME;
1157 if (len != 6 + 2 * nb_components) {
1158 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1159 return AVERROR_INVALIDDATA;
1161 for (i = 0; i < nb_components; i++) {
1162 id = get_bits(&s->gb, 8) - 1;
1163 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1164 /* find component index */
1165 for (index = 0; index < s->nb_components; index++)
1166 if (id == s->component_id[index])
1168 if (index == s->nb_components) {
1169 av_log(s->avctx, AV_LOG_ERROR,
1170 "decode_sos: index(%d) out of components\n", index);
1171 return AVERROR_INVALIDDATA;
1173 /* Metasoft MJPEG codec has Cb and Cr swapped */
1174 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1175 && nb_components == 3 && s->nb_components == 3 && i)
1178 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1180 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1181 index = (index+2)%3;
1183 s->comp_index[i] = index;
1185 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1186 s->h_scount[i] = s->h_count[index];
1187 s->v_scount[i] = s->v_count[index];
1189 s->dc_index[i] = get_bits(&s->gb, 4);
1190 s->ac_index[i] = get_bits(&s->gb, 4);
1192 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1193 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1195 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))
1199 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1200 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1201 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1202 prev_shift = get_bits(&s->gb, 4); /* Ah */
1203 point_transform = get_bits(&s->gb, 4); /* Al */
1205 prev_shift = point_transform = 0;
1207 if (nb_components > 1) {
1208 /* interleaved stream */
1209 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1210 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1211 } else if (!s->ls) { /* skip this for JPEG-LS */
1212 h = s->h_max / s->h_scount[0];
1213 v = s->v_max / s->v_scount[0];
1214 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1215 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1216 s->nb_blocks[0] = 1;
1221 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1222 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1223 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1224 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1225 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1228 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1229 for (i = s->mjpb_skiptosod; i > 0; i--)
1230 skip_bits(&s->gb, 8);
1233 for (i = 0; i < nb_components; i++)
1234 s->last_dc[i] = 1024;
1237 av_assert0(s->picture_ptr == &s->picture);
1238 if (CONFIG_JPEGLS_DECODER && s->ls) {
1240 // reset_ls_coding_parameters(s, 0);
1242 if ((ret = ff_jpegls_decode_picture(s, predictor,
1243 point_transform, ilv)) < 0)
1247 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1250 if ((ret = ljpeg_decode_yuv_scan(s, predictor, point_transform)) < 0)
1255 if (s->progressive && predictor) {
1256 av_assert0(s->picture_ptr == &s->picture);
1257 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1259 point_transform)) < 0)
1262 if ((ret = mjpeg_decode_scan(s, nb_components,
1263 prev_shift, point_transform,
1264 mb_bitmask, reference)) < 0)
1269 if (s->interlaced &&
1270 get_bits_left(&s->gb) > 32 &&
1271 show_bits(&s->gb, 8) == 0xFF) {
1272 GetBitContext bak = s->gb;
1273 align_get_bits(&bak);
1274 if (show_bits(&bak, 16) == 0xFFD1) {
1275 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1277 skip_bits(&s->gb, 16);
1278 s->bottom_field ^= 1;
1287 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1288 return AVERROR_INVALIDDATA;
1291 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1293 if (get_bits(&s->gb, 16) != 4)
1294 return AVERROR_INVALIDDATA;
1295 s->restart_interval = get_bits(&s->gb, 16);
1296 s->restart_count = 0;
1297 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1298 s->restart_interval);
1303 static int mjpeg_decode_app(MJpegDecodeContext *s)
1307 len = get_bits(&s->gb, 16);
1309 return AVERROR_INVALIDDATA;
1310 if (8 * len > get_bits_left(&s->gb))
1311 return AVERROR_INVALIDDATA;
1313 id = get_bits_long(&s->gb, 32);
1314 id = av_be2ne32(id);
1317 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1318 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1320 /* Buggy AVID, it puts EOI only at every 10th frame. */
1321 /* Also, this fourcc is used by non-avid files too, it holds some
1322 information, but it's always present in AVID-created files. */
1323 if (id == AV_RL32("AVI1")) {
1329 4bytes field_size_less_padding
1332 i = get_bits(&s->gb, 8); len--;
1333 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1335 skip_bits(&s->gb, 8);
1336 skip_bits(&s->gb, 32);
1337 skip_bits(&s->gb, 32);
1345 if (id == AV_RL32("JFIF")) {
1346 int t_w, t_h, v1, v2;
1347 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1348 v1 = get_bits(&s->gb, 8);
1349 v2 = get_bits(&s->gb, 8);
1350 skip_bits(&s->gb, 8);
1352 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1353 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1355 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1356 av_log(s->avctx, AV_LOG_INFO,
1357 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1359 s->avctx->sample_aspect_ratio.num,
1360 s->avctx->sample_aspect_ratio.den);
1362 t_w = get_bits(&s->gb, 8);
1363 t_h = get_bits(&s->gb, 8);
1365 /* skip thumbnail */
1366 if (len -10 - (t_w * t_h * 3) > 0)
1367 len -= t_w * t_h * 3;
1373 if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1374 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1375 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1376 skip_bits(&s->gb, 16); /* version */
1377 skip_bits(&s->gb, 16); /* flags0 */
1378 skip_bits(&s->gb, 16); /* flags1 */
1379 skip_bits(&s->gb, 8); /* transform */
1384 if (id == AV_RL32("LJIF")) {
1385 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1386 av_log(s->avctx, AV_LOG_INFO,
1387 "Pegasus lossless jpeg header found\n");
1388 skip_bits(&s->gb, 16); /* version ? */
1389 skip_bits(&s->gb, 16); /* unknwon always 0? */
1390 skip_bits(&s->gb, 16); /* unknwon always 0? */
1391 skip_bits(&s->gb, 16); /* unknwon always 0? */
1392 switch (get_bits(&s->gb, 8)) {
1402 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1409 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1410 id = get_bits_long(&s->gb, 32);
1411 id = av_be2ne32(id);
1414 if (id == AV_RL32("mjpg")) {
1416 skip_bits(&s->gb, 32); /* field size */
1417 skip_bits(&s->gb, 32); /* pad field size */
1418 skip_bits(&s->gb, 32); /* next off */
1419 skip_bits(&s->gb, 32); /* quant off */
1420 skip_bits(&s->gb, 32); /* huff off */
1421 skip_bits(&s->gb, 32); /* image off */
1422 skip_bits(&s->gb, 32); /* scan off */
1423 skip_bits(&s->gb, 32); /* data off */
1425 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1426 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1431 /* slow but needed for extreme adobe jpegs */
1433 av_log(s->avctx, AV_LOG_ERROR,
1434 "mjpeg: error, decode_app parser read over the end\n");
1436 skip_bits(&s->gb, 8);
1441 static int mjpeg_decode_com(MJpegDecodeContext *s)
1443 int len = get_bits(&s->gb, 16);
1444 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1445 char *cbuf = av_malloc(len - 1);
1448 for (i = 0; i < len - 2; i++)
1449 cbuf[i] = get_bits(&s->gb, 8);
1450 if (i > 0 && cbuf[i - 1] == '\n')
1455 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1456 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1458 /* buggy avid, it puts EOI only at every 10th frame */
1459 if (!strcmp(cbuf, "AVID")) {
1461 } else if (!strcmp(cbuf, "CS=ITU601"))
1463 else if ((len > 31 && !strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1464 (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1474 /* return the 8 bit start code value and update the search
1475 state. Return -1 if no start code found */
1476 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1478 const uint8_t *buf_ptr;
1483 buf_ptr = *pbuf_ptr;
1484 while (buf_ptr < buf_end) {
1487 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1495 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1496 *pbuf_ptr = buf_ptr;
1500 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1501 const uint8_t **buf_ptr, const uint8_t *buf_end,
1502 const uint8_t **unescaped_buf_ptr,
1503 int *unescaped_buf_size)
1506 start_code = find_marker(buf_ptr, buf_end);
1508 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1510 return AVERROR(ENOMEM);
1512 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1513 if (start_code == SOS && !s->ls) {
1514 const uint8_t *src = *buf_ptr;
1515 uint8_t *dst = s->buffer;
1517 while (src < buf_end) {
1518 uint8_t x = *(src++);
1521 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1523 while (src < buf_end && x == 0xff)
1526 if (x >= 0xd0 && x <= 0xd7)
1533 *unescaped_buf_ptr = s->buffer;
1534 *unescaped_buf_size = dst - s->buffer;
1536 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1537 (buf_end - *buf_ptr) - (dst - s->buffer));
1538 } else if (start_code == SOS && s->ls) {
1539 const uint8_t *src = *buf_ptr;
1540 uint8_t *dst = s->buffer;
1548 while (src + t < buf_end) {
1549 uint8_t x = src[t++];
1551 while ((src + t < buf_end) && x == 0xff)
1560 init_put_bits(&pb, dst, t);
1562 /* unescape bitstream */
1564 uint8_t x = src[b++];
1565 put_bits(&pb, 8, x);
1568 put_bits(&pb, 7, x);
1572 flush_put_bits(&pb);
1574 *unescaped_buf_ptr = dst;
1575 *unescaped_buf_size = (bit_count + 7) >> 3;
1577 *unescaped_buf_ptr = *buf_ptr;
1578 *unescaped_buf_size = buf_end - *buf_ptr;
1584 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
1587 const uint8_t *buf = avpkt->data;
1588 int buf_size = avpkt->size;
1589 MJpegDecodeContext *s = avctx->priv_data;
1590 const uint8_t *buf_end, *buf_ptr;
1591 const uint8_t *unescaped_buf_ptr;
1592 int unescaped_buf_size;
1596 AVFrame *picture = data;
1598 s->got_picture = 0; // picture from previous image can not be reused
1600 buf_end = buf + buf_size;
1601 while (buf_ptr < buf_end) {
1602 /* find start next marker */
1603 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1605 &unescaped_buf_size);
1607 if (start_code < 0) {
1609 } else if (unescaped_buf_size > (1U<<29)) {
1610 av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",
1611 start_code, unescaped_buf_size, buf_size);
1612 return AVERROR_INVALIDDATA;
1614 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1615 start_code, buf_end - buf_ptr);
1617 init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size * 8);
1619 s->start_code = start_code;
1620 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1621 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1623 /* process markers */
1624 if (start_code >= 0xd0 && start_code <= 0xd7)
1625 av_log(avctx, AV_LOG_DEBUG,
1626 "restart marker: %d\n", start_code & 0x0f);
1628 else if (start_code >= APP0 && start_code <= APP15)
1629 mjpeg_decode_app(s);
1631 else if (start_code == COM)
1632 mjpeg_decode_com(s);
1634 switch (start_code) {
1636 s->restart_interval = 0;
1637 s->restart_count = 0;
1638 /* nothing to do on SOI */
1641 ff_mjpeg_decode_dqt(s);
1644 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1645 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1654 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1661 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1668 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1675 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1679 if (!CONFIG_JPEGLS_DECODER ||
1680 (ret = ff_jpegls_decode_lse(s)) < 0)
1686 if (!s->got_picture) {
1687 av_log(avctx, AV_LOG_WARNING,
1688 "Found EOI before any SOF, ignoring\n");
1691 if (s->interlaced) {
1692 s->bottom_field ^= 1;
1693 /* if not bottom field, do not output image yet */
1694 if (s->bottom_field == !s->interlace_polarity)
1697 *picture = *s->picture_ptr;
1698 *data_size = sizeof(AVFrame);
1701 picture->quality = FFMAX3(s->qscale[0],
1704 picture->qstride = 0;
1705 picture->qscale_table = s->qscale_table;
1706 memset(picture->qscale_table, picture->quality,
1707 (s->width + 15) / 16);
1708 if (avctx->debug & FF_DEBUG_QP)
1709 av_log(avctx, AV_LOG_DEBUG,
1710 "QP: %d\n", picture->quality);
1711 picture->quality *= FF_QP2LAMBDA;
1716 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1717 (avctx->err_recognition & AV_EF_EXPLODE))
1721 mjpeg_decode_dri(s);
1733 av_log(avctx, AV_LOG_ERROR,
1734 "mjpeg: unsupported coding type (%x)\n", start_code);
1738 /* eof process start code */
1739 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1740 av_log(avctx, AV_LOG_DEBUG,
1741 "marker parser used %d bytes (%d bits)\n",
1742 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1745 if (s->got_picture) {
1746 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1749 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1750 return AVERROR_INVALIDDATA;
1753 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1754 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1755 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1756 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1757 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1758 for (i = 0; i < s->chroma_height; i++) {
1759 for (index = s->width - 1; index; index--)
1760 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1761 line += s->linesize[s->upscale_h];
1765 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1766 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1767 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1768 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1769 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1770 for (i = s->height - 1; i; i--) {
1771 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1772 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1774 memcpy(dst, src1, s->width);
1776 for (index = 0; index < s->width; index++)
1777 dst[index] = (src1[index] + src2[index]) >> 1;
1779 dst -= s->linesize[s->upscale_v];
1782 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1783 int hshift, vshift, j;
1784 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1785 for (index=0; index<4; index++) {
1786 uint8_t *dst = s->picture_ptr->data[index];
1789 if(index && index<3){
1790 w = -((-w) >> hshift);
1791 h = -((-h) >> vshift);
1794 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
1795 for (i=0; i<h/2; i++) {
1797 FFSWAP(int, dst[j], dst2[j]);
1798 dst += s->linesize[index];
1799 dst2 -= s->linesize[index];
1805 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
1807 // return buf_end - buf_ptr;
1808 return buf_ptr - buf;
1811 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1813 MJpegDecodeContext *s = avctx->priv_data;
1816 if (s->picture_ptr && s->picture_ptr->data[0])
1817 avctx->release_buffer(avctx, s->picture_ptr);
1820 av_free(s->qscale_table);
1821 av_freep(&s->ljpeg_buffer);
1822 s->ljpeg_buffer_size = 0;
1824 for (i = 0; i < 3; i++) {
1825 for (j = 0; j < 4; j++)
1826 ff_free_vlc(&s->vlcs[i][j]);
1828 for (i = 0; i < MAX_COMPONENTS; i++) {
1829 av_freep(&s->blocks[i]);
1830 av_freep(&s->last_nnz[i]);
1835 #if CONFIG_MJPEG_DECODER
1836 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1837 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1838 static const AVOption options[] = {
1839 { "extern_huff", "Use external huffman table.",
1840 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1844 static const AVClass mjpegdec_class = {
1845 .class_name = "MJPEG decoder",
1846 .item_name = av_default_item_name,
1848 .version = LIBAVUTIL_VERSION_INT,
1851 AVCodec ff_mjpeg_decoder = {
1853 .type = AVMEDIA_TYPE_VIDEO,
1854 .id = AV_CODEC_ID_MJPEG,
1855 .priv_data_size = sizeof(MJpegDecodeContext),
1856 .init = ff_mjpeg_decode_init,
1857 .close = ff_mjpeg_decode_end,
1858 .decode = ff_mjpeg_decode_frame,
1859 .capabilities = CODEC_CAP_DR1,
1861 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1862 .priv_class = &mjpegdec_class,
1865 #if CONFIG_THP_DECODER
1866 AVCodec ff_thp_decoder = {
1868 .type = AVMEDIA_TYPE_VIDEO,
1869 .id = AV_CODEC_ID_THP,
1870 .priv_data_size = sizeof(MJpegDecodeContext),
1871 .init = ff_mjpeg_decode_init,
1872 .close = ff_mjpeg_decode_end,
1873 .decode = ff_mjpeg_decode_frame,
1874 .capabilities = CODEC_CAP_DR1,
1876 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),