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 av_log(s->avctx, AV_LOG_ERROR, "SE %d is too large\n", se);
1100 return AVERROR_INVALIDDATA;
1104 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1105 last_scan = !~s->coefs_finished[c];
1108 if (s->interlaced && s->bottom_field)
1109 data += linesize >> 1;
1111 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1112 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1113 int block_idx = mb_y * s->block_stride[c];
1114 DCTELEM (*block)[64] = &s->blocks[c][block_idx];
1115 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1116 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1119 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1120 quant_matrix, ss, se, Al, &EOBRUN);
1122 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1123 quant_matrix, ss, se, Al, &EOBRUN);
1125 av_log(s->avctx, AV_LOG_ERROR,
1126 "error y=%d x=%d\n", mb_y, mb_x);
1127 return AVERROR_INVALIDDATA;
1131 s->dsp.idct_put(ptr, linesize, *block);
1132 ptr += 8 >> s->avctx->lowres;
1139 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1140 const AVFrame *reference)
1142 int len, nb_components, i, h, v, predictor, point_transform;
1144 const int block_size = s->lossless ? 1 : 8;
1145 int ilv, prev_shift;
1147 if (!s->got_picture) {
1148 av_log(s->avctx, AV_LOG_WARNING,
1149 "Can not process SOS before SOF, skipping\n");
1153 av_assert0(s->picture_ptr->data[0]);
1154 /* XXX: verify len field validity */
1155 len = get_bits(&s->gb, 16);
1156 nb_components = get_bits(&s->gb, 8);
1157 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1158 av_log(s->avctx, AV_LOG_ERROR,
1159 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1160 return AVERROR_PATCHWELCOME;
1162 if (len != 6 + 2 * nb_components) {
1163 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1164 return AVERROR_INVALIDDATA;
1166 for (i = 0; i < nb_components; i++) {
1167 id = get_bits(&s->gb, 8) - 1;
1168 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1169 /* find component index */
1170 for (index = 0; index < s->nb_components; index++)
1171 if (id == s->component_id[index])
1173 if (index == s->nb_components) {
1174 av_log(s->avctx, AV_LOG_ERROR,
1175 "decode_sos: index(%d) out of components\n", index);
1176 return AVERROR_INVALIDDATA;
1178 /* Metasoft MJPEG codec has Cb and Cr swapped */
1179 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1180 && nb_components == 3 && s->nb_components == 3 && i)
1183 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1185 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1186 index = (index+2)%3;
1188 s->comp_index[i] = index;
1190 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1191 s->h_scount[i] = s->h_count[index];
1192 s->v_scount[i] = s->v_count[index];
1194 s->dc_index[i] = get_bits(&s->gb, 4);
1195 s->ac_index[i] = get_bits(&s->gb, 4);
1197 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1198 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1200 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))
1204 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1205 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1206 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1207 prev_shift = get_bits(&s->gb, 4); /* Ah */
1208 point_transform = get_bits(&s->gb, 4); /* Al */
1210 prev_shift = point_transform = 0;
1212 if (nb_components > 1) {
1213 /* interleaved stream */
1214 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1215 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1216 } else if (!s->ls) { /* skip this for JPEG-LS */
1217 h = s->h_max / s->h_scount[0];
1218 v = s->v_max / s->v_scount[0];
1219 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1220 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1221 s->nb_blocks[0] = 1;
1226 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1227 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1228 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1229 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1230 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1233 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1234 for (i = s->mjpb_skiptosod; i > 0; i--)
1235 skip_bits(&s->gb, 8);
1238 for (i = 0; i < nb_components; i++)
1239 s->last_dc[i] = 1024;
1242 av_assert0(s->picture_ptr == &s->picture);
1243 if (CONFIG_JPEGLS_DECODER && s->ls) {
1245 // reset_ls_coding_parameters(s, 0);
1247 if ((ret = ff_jpegls_decode_picture(s, predictor,
1248 point_transform, ilv)) < 0)
1252 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1255 if ((ret = ljpeg_decode_yuv_scan(s, predictor, point_transform)) < 0)
1260 if (s->progressive && predictor) {
1261 av_assert0(s->picture_ptr == &s->picture);
1262 if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1264 point_transform)) < 0)
1267 if ((ret = mjpeg_decode_scan(s, nb_components,
1268 prev_shift, point_transform,
1269 mb_bitmask, reference)) < 0)
1274 if (s->interlaced &&
1275 get_bits_left(&s->gb) > 32 &&
1276 show_bits(&s->gb, 8) == 0xFF) {
1277 GetBitContext bak = s->gb;
1278 align_get_bits(&bak);
1279 if (show_bits(&bak, 16) == 0xFFD1) {
1280 av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1282 skip_bits(&s->gb, 16);
1283 s->bottom_field ^= 1;
1292 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1293 return AVERROR_INVALIDDATA;
1296 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1298 if (get_bits(&s->gb, 16) != 4)
1299 return AVERROR_INVALIDDATA;
1300 s->restart_interval = get_bits(&s->gb, 16);
1301 s->restart_count = 0;
1302 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1303 s->restart_interval);
1308 static int mjpeg_decode_app(MJpegDecodeContext *s)
1312 len = get_bits(&s->gb, 16);
1314 return AVERROR_INVALIDDATA;
1315 if (8 * len > get_bits_left(&s->gb))
1316 return AVERROR_INVALIDDATA;
1318 id = get_bits_long(&s->gb, 32);
1319 id = av_be2ne32(id);
1322 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1323 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1325 /* Buggy AVID, it puts EOI only at every 10th frame. */
1326 /* Also, this fourcc is used by non-avid files too, it holds some
1327 information, but it's always present in AVID-created files. */
1328 if (id == AV_RL32("AVI1")) {
1334 4bytes field_size_less_padding
1337 i = get_bits(&s->gb, 8); len--;
1338 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1340 skip_bits(&s->gb, 8);
1341 skip_bits(&s->gb, 32);
1342 skip_bits(&s->gb, 32);
1350 if (id == AV_RL32("JFIF")) {
1351 int t_w, t_h, v1, v2;
1352 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1353 v1 = get_bits(&s->gb, 8);
1354 v2 = get_bits(&s->gb, 8);
1355 skip_bits(&s->gb, 8);
1357 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1358 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1360 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1361 av_log(s->avctx, AV_LOG_INFO,
1362 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1364 s->avctx->sample_aspect_ratio.num,
1365 s->avctx->sample_aspect_ratio.den);
1367 t_w = get_bits(&s->gb, 8);
1368 t_h = get_bits(&s->gb, 8);
1370 /* skip thumbnail */
1371 if (len -10 - (t_w * t_h * 3) > 0)
1372 len -= t_w * t_h * 3;
1378 if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1379 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1380 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1381 skip_bits(&s->gb, 16); /* version */
1382 skip_bits(&s->gb, 16); /* flags0 */
1383 skip_bits(&s->gb, 16); /* flags1 */
1384 skip_bits(&s->gb, 8); /* transform */
1389 if (id == AV_RL32("LJIF")) {
1390 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1391 av_log(s->avctx, AV_LOG_INFO,
1392 "Pegasus lossless jpeg header found\n");
1393 skip_bits(&s->gb, 16); /* version ? */
1394 skip_bits(&s->gb, 16); /* unknwon always 0? */
1395 skip_bits(&s->gb, 16); /* unknwon always 0? */
1396 skip_bits(&s->gb, 16); /* unknwon always 0? */
1397 switch (get_bits(&s->gb, 8)) {
1407 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1414 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1415 id = get_bits_long(&s->gb, 32);
1416 id = av_be2ne32(id);
1419 if (id == AV_RL32("mjpg")) {
1421 skip_bits(&s->gb, 32); /* field size */
1422 skip_bits(&s->gb, 32); /* pad field size */
1423 skip_bits(&s->gb, 32); /* next off */
1424 skip_bits(&s->gb, 32); /* quant off */
1425 skip_bits(&s->gb, 32); /* huff off */
1426 skip_bits(&s->gb, 32); /* image off */
1427 skip_bits(&s->gb, 32); /* scan off */
1428 skip_bits(&s->gb, 32); /* data off */
1430 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1431 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1436 /* slow but needed for extreme adobe jpegs */
1438 av_log(s->avctx, AV_LOG_ERROR,
1439 "mjpeg: error, decode_app parser read over the end\n");
1441 skip_bits(&s->gb, 8);
1446 static int mjpeg_decode_com(MJpegDecodeContext *s)
1448 int len = get_bits(&s->gb, 16);
1449 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1450 char *cbuf = av_malloc(len - 1);
1453 for (i = 0; i < len - 2; i++)
1454 cbuf[i] = get_bits(&s->gb, 8);
1455 if (i > 0 && cbuf[i - 1] == '\n')
1460 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1461 av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1463 /* buggy avid, it puts EOI only at every 10th frame */
1464 if (!strcmp(cbuf, "AVID")) {
1466 } else if (!strcmp(cbuf, "CS=ITU601"))
1468 else if ((len > 31 && !strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32)) ||
1469 (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1479 /* return the 8 bit start code value and update the search
1480 state. Return -1 if no start code found */
1481 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1483 const uint8_t *buf_ptr;
1488 buf_ptr = *pbuf_ptr;
1489 while (buf_ptr < buf_end) {
1492 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1500 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1501 *pbuf_ptr = buf_ptr;
1505 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1506 const uint8_t **buf_ptr, const uint8_t *buf_end,
1507 const uint8_t **unescaped_buf_ptr,
1508 int *unescaped_buf_size)
1511 start_code = find_marker(buf_ptr, buf_end);
1513 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1515 return AVERROR(ENOMEM);
1517 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1518 if (start_code == SOS && !s->ls) {
1519 const uint8_t *src = *buf_ptr;
1520 uint8_t *dst = s->buffer;
1522 while (src < buf_end) {
1523 uint8_t x = *(src++);
1526 if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1528 while (src < buf_end && x == 0xff)
1531 if (x >= 0xd0 && x <= 0xd7)
1538 *unescaped_buf_ptr = s->buffer;
1539 *unescaped_buf_size = dst - s->buffer;
1541 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1542 (buf_end - *buf_ptr) - (dst - s->buffer));
1543 } else if (start_code == SOS && s->ls) {
1544 const uint8_t *src = *buf_ptr;
1545 uint8_t *dst = s->buffer;
1553 while (src + t < buf_end) {
1554 uint8_t x = src[t++];
1556 while ((src + t < buf_end) && x == 0xff)
1565 init_put_bits(&pb, dst, t);
1567 /* unescape bitstream */
1569 uint8_t x = src[b++];
1570 put_bits(&pb, 8, x);
1573 put_bits(&pb, 7, x);
1577 flush_put_bits(&pb);
1579 *unescaped_buf_ptr = dst;
1580 *unescaped_buf_size = (bit_count + 7) >> 3;
1582 *unescaped_buf_ptr = *buf_ptr;
1583 *unescaped_buf_size = buf_end - *buf_ptr;
1589 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
1592 const uint8_t *buf = avpkt->data;
1593 int buf_size = avpkt->size;
1594 MJpegDecodeContext *s = avctx->priv_data;
1595 const uint8_t *buf_end, *buf_ptr;
1596 const uint8_t *unescaped_buf_ptr;
1597 int unescaped_buf_size;
1601 AVFrame *picture = data;
1603 s->got_picture = 0; // picture from previous image can not be reused
1605 buf_end = buf + buf_size;
1606 while (buf_ptr < buf_end) {
1607 /* find start next marker */
1608 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1610 &unescaped_buf_size);
1612 if (start_code < 0) {
1614 } else if (unescaped_buf_size > (1U<<28)) {
1615 av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",
1616 start_code, unescaped_buf_size, buf_size);
1617 return AVERROR_INVALIDDATA;
1619 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1620 start_code, buf_end - buf_ptr);
1622 init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size * 8);
1624 s->start_code = start_code;
1625 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1626 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1628 /* process markers */
1629 if (start_code >= 0xd0 && start_code <= 0xd7)
1630 av_log(avctx, AV_LOG_DEBUG,
1631 "restart marker: %d\n", start_code & 0x0f);
1633 else if (start_code >= APP0 && start_code <= APP15)
1634 mjpeg_decode_app(s);
1636 else if (start_code == COM)
1637 mjpeg_decode_com(s);
1639 switch (start_code) {
1641 s->restart_interval = 0;
1642 s->restart_count = 0;
1643 /* nothing to do on SOI */
1646 ff_mjpeg_decode_dqt(s);
1649 if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1650 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1659 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1666 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1673 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1680 if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1684 if (!CONFIG_JPEGLS_DECODER ||
1685 (ret = ff_jpegls_decode_lse(s)) < 0)
1691 if (!s->got_picture) {
1692 av_log(avctx, AV_LOG_WARNING,
1693 "Found EOI before any SOF, ignoring\n");
1696 if (s->interlaced) {
1697 s->bottom_field ^= 1;
1698 /* if not bottom field, do not output image yet */
1699 if (s->bottom_field == !s->interlace_polarity)
1702 *picture = *s->picture_ptr;
1703 *data_size = sizeof(AVFrame);
1706 picture->quality = FFMAX3(s->qscale[0],
1709 picture->qstride = 0;
1710 picture->qscale_table = s->qscale_table;
1711 memset(picture->qscale_table, picture->quality,
1712 (s->width + 15) / 16);
1713 if (avctx->debug & FF_DEBUG_QP)
1714 av_log(avctx, AV_LOG_DEBUG,
1715 "QP: %d\n", picture->quality);
1716 picture->quality *= FF_QP2LAMBDA;
1721 if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
1722 (avctx->err_recognition & AV_EF_EXPLODE))
1726 mjpeg_decode_dri(s);
1738 av_log(avctx, AV_LOG_ERROR,
1739 "mjpeg: unsupported coding type (%x)\n", start_code);
1743 /* eof process start code */
1744 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1745 av_log(avctx, AV_LOG_DEBUG,
1746 "marker parser used %d bytes (%d bits)\n",
1747 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1750 if (s->got_picture) {
1751 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1754 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1755 return AVERROR_INVALIDDATA;
1758 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1759 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1760 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1761 avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
1762 avctx->pix_fmt == AV_PIX_FMT_YUV440P);
1763 for (i = 0; i < s->chroma_height; i++) {
1764 for (index = s->width - 1; index; index--)
1765 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1766 line += s->linesize[s->upscale_h];
1770 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1771 av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
1772 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
1773 avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
1774 avctx->pix_fmt == AV_PIX_FMT_YUV422P);
1775 for (i = s->height - 1; i; i--) {
1776 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1777 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1779 memcpy(dst, src1, s->width);
1781 for (index = 0; index < s->width; index++)
1782 dst[index] = (src1[index] + src2[index]) >> 1;
1784 dst -= s->linesize[s->upscale_v];
1787 if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {
1788 int hshift, vshift, j;
1789 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
1790 for (index=0; index<4; index++) {
1791 uint8_t *dst = s->picture_ptr->data[index];
1794 if(index && index<3){
1795 w = -((-w) >> hshift);
1796 h = -((-h) >> vshift);
1799 uint8_t *dst2 = dst + s->linesize[index]*(h-1);
1800 for (i=0; i<h/2; i++) {
1802 FFSWAP(int, dst[j], dst2[j]);
1803 dst += s->linesize[index];
1804 dst2 -= s->linesize[index];
1810 av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
1812 // return buf_end - buf_ptr;
1813 return buf_ptr - buf;
1816 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1818 MJpegDecodeContext *s = avctx->priv_data;
1821 if (s->picture_ptr && s->picture_ptr->data[0])
1822 avctx->release_buffer(avctx, s->picture_ptr);
1825 av_free(s->qscale_table);
1826 av_freep(&s->ljpeg_buffer);
1827 s->ljpeg_buffer_size = 0;
1829 for (i = 0; i < 3; i++) {
1830 for (j = 0; j < 4; j++)
1831 ff_free_vlc(&s->vlcs[i][j]);
1833 for (i = 0; i < MAX_COMPONENTS; i++) {
1834 av_freep(&s->blocks[i]);
1835 av_freep(&s->last_nnz[i]);
1840 #if CONFIG_MJPEG_DECODER
1841 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1842 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1843 static const AVOption options[] = {
1844 { "extern_huff", "Use external huffman table.",
1845 OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1849 static const AVClass mjpegdec_class = {
1850 .class_name = "MJPEG decoder",
1851 .item_name = av_default_item_name,
1853 .version = LIBAVUTIL_VERSION_INT,
1856 AVCodec ff_mjpeg_decoder = {
1858 .type = AVMEDIA_TYPE_VIDEO,
1859 .id = AV_CODEC_ID_MJPEG,
1860 .priv_data_size = sizeof(MJpegDecodeContext),
1861 .init = ff_mjpeg_decode_init,
1862 .close = ff_mjpeg_decode_end,
1863 .decode = ff_mjpeg_decode_frame,
1864 .capabilities = CODEC_CAP_DR1,
1866 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1867 .priv_class = &mjpegdec_class,
1870 #if CONFIG_THP_DECODER
1871 AVCodec ff_thp_decoder = {
1873 .type = AVMEDIA_TYPE_VIDEO,
1874 .id = AV_CODEC_ID_THP,
1875 .priv_data_size = sizeof(MJpegDecodeContext),
1876 .init = ff_mjpeg_decode_init,
1877 .close = ff_mjpeg_decode_end,
1878 .decode = ff_mjpeg_decode_frame,
1879 .capabilities = CODEC_CAP_DR1,
1881 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),