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
36 #include "libavutil/imgutils.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/opt.h"
43 #include "jpeglsdec.h"
46 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
47 const uint8_t *val_table, int nb_codes,
48 int use_static, int is_ac)
50 uint8_t huff_size[256] = { 0 };
51 uint16_t huff_code[256];
52 uint16_t huff_sym[256];
55 assert(nb_codes <= 256);
57 ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
59 for (i = 0; i < 256; i++)
60 huff_sym[i] = i + 16 * is_ac;
63 huff_sym[0] = 16 * 256;
65 return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
66 huff_code, 2, 2, huff_sym, 2, 2, use_static);
69 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
71 build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
72 ff_mjpeg_val_dc, 12, 0, 0);
73 build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
74 ff_mjpeg_val_dc, 12, 0, 0);
75 build_vlc(&s->vlcs[1][0], ff_mjpeg_bits_ac_luminance,
76 ff_mjpeg_val_ac_luminance, 251, 0, 1);
77 build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
78 ff_mjpeg_val_ac_chrominance, 251, 0, 1);
79 build_vlc(&s->vlcs[2][0], ff_mjpeg_bits_ac_luminance,
80 ff_mjpeg_val_ac_luminance, 251, 0, 0);
81 build_vlc(&s->vlcs[2][1], ff_mjpeg_bits_ac_chrominance,
82 ff_mjpeg_val_ac_chrominance, 251, 0, 0);
85 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
87 MJpegDecodeContext *s = avctx->priv_data;
90 s->picture_ptr = &s->picture;
91 avcodec_get_frame_defaults(&s->picture);
94 ff_dsputil_init(&s->dsp, avctx);
95 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
100 s->org_height = avctx->coded_height;
101 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
103 build_basic_mjpeg_vlc(s);
105 if (s->extern_huff) {
106 av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
107 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
108 if (ff_mjpeg_decode_dht(s)) {
109 av_log(avctx, AV_LOG_ERROR,
110 "mjpeg: error using external huffman table, switching back to internal\n");
111 build_basic_mjpeg_vlc(s);
114 if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
115 s->interlace_polarity = 1; /* bottom field first */
116 av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
118 if (avctx->codec->id == CODEC_ID_AMV)
125 /* quantize tables */
126 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
128 int len, index, i, j;
130 len = get_bits(&s->gb, 16) - 2;
133 /* only 8 bit precision handled */
134 if (get_bits(&s->gb, 4) != 0) {
135 av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
138 index = get_bits(&s->gb, 4);
141 av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
142 /* read quant table */
143 for (i = 0; i < 64; i++) {
144 j = s->scantable.permutated[i];
145 s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
148 // XXX FIXME finetune, and perhaps add dc too
149 s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
150 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
151 av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
152 index, s->qscale[index]);
158 /* decode huffman tables and build VLC decoders */
159 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
161 int len, index, i, class, n, v, code_max;
162 uint8_t bits_table[17];
163 uint8_t val_table[256];
165 len = get_bits(&s->gb, 16) - 2;
170 class = get_bits(&s->gb, 4);
173 index = get_bits(&s->gb, 4);
177 for (i = 1; i <= 16; i++) {
178 bits_table[i] = get_bits(&s->gb, 8);
182 if (len < n || n > 256)
186 for (i = 0; i < n; i++) {
187 v = get_bits(&s->gb, 8);
194 /* build VLC and flush previous vlc if present */
195 ff_free_vlc(&s->vlcs[class][index]);
196 av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
197 class, index, code_max + 1);
198 if (build_vlc(&s->vlcs[class][index], bits_table, val_table,
199 code_max + 1, 0, class > 0) < 0)
203 ff_free_vlc(&s->vlcs[2][index]);
204 if (build_vlc(&s->vlcs[2][index], bits_table, val_table,
205 code_max + 1, 0, 0) < 0)
212 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
214 int len, nb_components, i, width, height, pix_fmt_id;
217 s->upscale_h = s->upscale_v = 0;
219 /* XXX: verify len field validity */
220 len = get_bits(&s->gb, 16);
221 s->bits = get_bits(&s->gb, 8);
225 if (s->bits == 9 && !s->pegasus_rct)
226 s->rct = 1; // FIXME ugly
228 if (s->bits != 8 && !s->lossless) {
229 av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
233 if(s->lossless && s->avctx->lowres){
234 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
238 height = get_bits(&s->gb, 16);
239 width = get_bits(&s->gb, 16);
241 // HACK for odd_height.mov
242 if (s->interlaced && s->width == width && s->height == height + 1)
245 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
246 if (av_image_check_size(width, height, 0, s->avctx))
249 nb_components = get_bits(&s->gb, 8);
250 if (nb_components <= 0 ||
251 nb_components > MAX_COMPONENTS)
253 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
254 if (nb_components != s->nb_components) {
255 av_log(s->avctx, AV_LOG_ERROR, "nb_components changing in interlaced picture\n");
256 return AVERROR_INVALIDDATA;
259 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
260 av_log(s->avctx, AV_LOG_ERROR,
261 "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
264 s->nb_components = nb_components;
267 for (i = 0; i < nb_components; i++) {
269 s->component_id[i] = get_bits(&s->gb, 8) - 1;
270 s->h_count[i] = get_bits(&s->gb, 4);
271 s->v_count[i] = get_bits(&s->gb, 4);
272 /* compute hmax and vmax (only used in interleaved case) */
273 if (s->h_count[i] > s->h_max)
274 s->h_max = s->h_count[i];
275 if (s->v_count[i] > s->v_max)
276 s->v_max = s->v_count[i];
277 if (!s->h_count[i] || !s->v_count[i]) {
278 av_log(s->avctx, AV_LOG_ERROR, "h/v_count is 0\n");
281 s->quant_index[i] = get_bits(&s->gb, 8);
282 if (s->quant_index[i] >= 4)
284 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
285 i, s->h_count[i], s->v_count[i],
286 s->component_id[i], s->quant_index[i]);
289 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
290 av_log(s->avctx, AV_LOG_ERROR,
291 "Subsampling in JPEG-LS is not supported.\n");
295 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && nb_components==3)
298 /* if different size, realloc/alloc picture */
299 /* XXX: also check h_count and v_count */
300 if (width != s->width || height != s->height) {
301 av_freep(&s->qscale_table);
307 /* test interlaced mode */
308 if (s->first_picture &&
309 s->org_height != 0 &&
310 s->height < ((s->org_height * 3) / 4)) {
312 s->bottom_field = s->interlace_polarity;
313 s->picture_ptr->interlaced_frame = 1;
314 s->picture_ptr->top_field_first = !s->interlace_polarity;
318 avcodec_set_dimensions(s->avctx, width, height);
320 s->qscale_table = av_mallocz((s->width + 15) / 16);
321 s->first_picture = 0;
324 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
325 if (s->progressive) {
326 av_log_ask_for_sample(s->avctx, "progressively coded interlaced pictures not supported\n");
327 return AVERROR_INVALIDDATA;
332 /* XXX: not complete test ! */
333 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
334 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
335 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
336 (s->h_count[3] << 4) | s->v_count[3];
337 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
338 /* NOTE we do not allocate pictures large enough for the possible
339 * padding of h/v_count being 4 */
340 if (!(pix_fmt_id & 0xD0D0D0D0))
341 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
342 if (!(pix_fmt_id & 0x0D0D0D0D))
343 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
345 switch (pix_fmt_id) {
348 s->avctx->pix_fmt = PIX_FMT_BGR24;
350 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
351 s->avctx->pix_fmt = PIX_FMT_GBR24P;
353 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
354 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
357 assert(s->nb_components == 3);
361 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
362 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
364 s->upscale_h = (pix_fmt_id == 0x22122100);
365 s->chroma_height = s->height;
369 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
370 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
371 s->upscale_v = (pix_fmt_id == 0x22211200);
373 s->chroma_height = s->height;
376 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
377 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
380 s->chroma_height = s->height / 2;
384 s->avctx->pix_fmt = PIX_FMT_GRAY8;
386 s->avctx->pix_fmt = PIX_FMT_GRAY16;
391 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV440P : PIX_FMT_YUVJ440P;
392 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
393 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
394 s->chroma_height = s->height / 2;
397 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
398 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
402 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
403 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
404 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
407 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
408 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
411 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
414 if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
415 av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
416 return AVERROR_PATCHWELCOME;
419 s->upscale_h = s->upscale_v = 0;
420 if (s->nb_components > 1)
421 s->avctx->pix_fmt = PIX_FMT_RGB24;
422 else if (s->bits <= 8)
423 s->avctx->pix_fmt = PIX_FMT_GRAY8;
425 s->avctx->pix_fmt = PIX_FMT_GRAY16;
428 if (s->picture_ptr->data[0])
429 s->avctx->release_buffer(s->avctx, s->picture_ptr);
431 if (s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0) {
432 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
435 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
436 s->picture_ptr->key_frame = 1;
439 for (i = 0; i < 3; i++)
440 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
442 // printf("%d %d %d %d %d %d\n",
443 // s->width, s->height, s->linesize[0], s->linesize[1],
444 // s->interlaced, s->avctx->height);
446 if (len != (8 + (3 * nb_components)))
447 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
449 /* totally blank picture as progressive JPEG will only add details to it */
450 if (s->progressive) {
451 int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
452 int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
453 for (i = 0; i < s->nb_components; i++) {
454 int size = bw * bh * s->h_count[i] * s->v_count[i];
455 av_freep(&s->blocks[i]);
456 av_freep(&s->last_nnz[i]);
457 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
458 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
459 s->block_stride[i] = bw * s->h_count[i];
461 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
466 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
469 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
471 av_log(s->avctx, AV_LOG_WARNING,
472 "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
473 0, dc_index, &s->vlcs[0][dc_index]);
478 return get_xbits(&s->gb, code);
483 /* decode block and dequantize */
484 static int decode_block(MJpegDecodeContext *s, DCTELEM *block, int component,
485 int dc_index, int ac_index, int16_t *quant_matrix)
487 int code, i, j, level, val;
490 val = mjpeg_decode_dc(s, dc_index);
492 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
495 val = val * quant_matrix[0] + s->last_dc[component];
496 s->last_dc[component] = val;
500 {OPEN_READER(re, &s->gb);
502 UPDATE_CACHE(re, &s->gb);
503 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
505 i += ((unsigned)code) >> 4;
508 if (code > MIN_CACHE_BITS - 16)
509 UPDATE_CACHE(re, &s->gb);
512 int cache = GET_CACHE(re, &s->gb);
513 int sign = (~cache) >> 31;
514 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
517 LAST_SKIP_BITS(re, &s->gb, code);
520 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
523 j = s->scantable.permutated[i];
524 block[j] = level * quant_matrix[j];
527 CLOSE_READER(re, &s->gb);}
532 static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block,
533 int component, int dc_index,
534 int16_t *quant_matrix, int Al)
537 s->dsp.clear_block(block);
538 val = mjpeg_decode_dc(s, dc_index);
540 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
543 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
544 s->last_dc[component] = val;
549 /* decode block and dequantize - progressive JPEG version */
550 static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block,
551 uint8_t *last_nnz, int ac_index,
552 int16_t *quant_matrix,
553 int ss, int se, int Al, int *EOBRUN)
555 int code, i, j, level, val, run;
563 OPEN_READER(re, &s->gb);
564 for (i = ss; ; i++) {
565 UPDATE_CACHE(re, &s->gb);
566 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
568 run = ((unsigned) code) >> 4;
572 if (code > MIN_CACHE_BITS - 16)
573 UPDATE_CACHE(re, &s->gb);
576 int cache = GET_CACHE(re, &s->gb);
577 int sign = (~cache) >> 31;
578 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
581 LAST_SKIP_BITS(re, &s->gb, code);
585 j = s->scantable.permutated[se];
586 block[j] = level * quant_matrix[j] << Al;
589 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
592 j = s->scantable.permutated[i];
593 block[j] = level * quant_matrix[j] << Al;
595 if (run == 0xF) {// ZRL - skip 15 coefficients
598 av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
604 UPDATE_CACHE(re, &s->gb);
605 val += NEG_USR32(GET_CACHE(re, &s->gb), run);
606 LAST_SKIP_BITS(re, &s->gb, run);
613 CLOSE_READER(re, &s->gb);
622 #define REFINE_BIT(j) { \
623 UPDATE_CACHE(re, &s->gb); \
624 sign = block[j] >> 15; \
625 block[j] += SHOW_UBITS(re, &s->gb, 1) * \
626 ((quant_matrix[j] ^ sign) - sign) << Al; \
627 LAST_SKIP_BITS(re, &s->gb, 1); \
635 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
640 j = s->scantable.permutated[i]; \
643 else if (run-- == 0) \
647 /* decode block and dequantize - progressive JPEG refinement pass */
648 static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block,
650 int ac_index, int16_t *quant_matrix,
651 int ss, int se, int Al, int *EOBRUN)
653 int code, i = ss, j, sign, val, run;
654 int last = FFMIN(se, *last_nnz);
656 OPEN_READER(re, &s->gb);
661 UPDATE_CACHE(re, &s->gb);
662 GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
665 run = ((unsigned) code) >> 4;
666 UPDATE_CACHE(re, &s->gb);
667 val = SHOW_UBITS(re, &s->gb, 1);
668 LAST_SKIP_BITS(re, &s->gb, 1);
670 j = s->scantable.permutated[i];
672 block[j] = ((quant_matrix[j]^val) - val) << Al;
676 CLOSE_READER(re, &s->gb);
680 run = ((unsigned) code) >> 4;
687 UPDATE_CACHE(re, &s->gb);
688 run += SHOW_UBITS(re, &s->gb, val);
689 LAST_SKIP_BITS(re, &s->gb, val);
701 for (; i <= last; i++) {
702 j = s->scantable.permutated[i];
706 CLOSE_READER(re, &s->gb);
713 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
716 uint16_t (*buffer)[4];
717 int left[3], top[3], topleft[3];
718 const int linesize = s->linesize[0];
719 const int mask = (1 << s->bits) - 1;
723 s->restart_count = s->restart_interval;
725 av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
726 (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
727 buffer = s->ljpeg_buffer;
729 for (i = 0; i < 3; i++)
730 buffer[0][i] = 1 << (s->bits - 1);
732 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
733 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
735 if (s->interlaced && s->bottom_field)
736 ptr += linesize >> 1;
738 for (i = 0; i < 3; i++)
739 top[i] = left[i] = topleft[i] = buffer[0][i];
741 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
742 int modified_predictor = predictor;
744 if (s->restart_interval && !s->restart_count){
745 s->restart_count = s->restart_interval;
749 top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
751 if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
752 modified_predictor = 1;
754 for (i=0;i<nb_components;i++) {
758 top[i] = buffer[mb_x][i];
760 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
762 dc = mjpeg_decode_dc(s, s->dc_index[i]);
766 left[i] = buffer[mb_x][i] =
767 mask & (pred + (dc << point_transform));
770 if (s->restart_interval && !--s->restart_count) {
771 align_get_bits(&s->gb);
772 skip_bits(&s->gb, 16); /* skip RSTn */
777 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
778 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
779 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
780 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
782 } else if (s->pegasus_rct) {
783 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
784 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
785 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
786 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
789 for(i=0; i<nb_components; i++) {
790 int c= s->comp_index[i];
791 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
792 ptr[3*mb_x+2-c] = buffer[mb_x][i];
800 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
804 const int nb_components=s->nb_components;
805 int bits= (s->bits+7)&~7;
809 point_transform += bits - s->bits;
811 av_assert0(nb_components==1 || nb_components==3);
813 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
814 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
815 if (s->restart_interval && !s->restart_count){
816 s->restart_count = s->restart_interval;
821 if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
822 int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
823 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
824 for (i = 0; i < nb_components; i++) {
827 int n, h, v, x, y, c, j, linesize;
829 c = s->comp_index[i];
834 linesize= s->linesize[c];
836 if(bits>8) linesize /= 2;
841 dc = mjpeg_decode_dc(s, s->dc_index[i]);
845 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
848 pred= 1 << (bits - 1);
854 pred= ptr[-linesize];
856 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
860 if (s->interlaced && s->bottom_field)
861 ptr += linesize >> 1;
862 pred &= (-1)<<(8-s->bits);
863 *ptr= pred + (dc << point_transform);
865 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
868 pred= 1 << (bits - 1);
874 pred= ptr16[-linesize];
876 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
880 if (s->interlaced && s->bottom_field)
881 ptr16 += linesize >> 1;
882 pred &= (-1)<<(16-s->bits);
883 *ptr16= pred + (dc << point_transform);
892 for (i = 0; i < nb_components; i++) {
895 int n, h, v, x, y, c, j, linesize, dc;
897 c = s->comp_index[i];
902 linesize = s->linesize[c];
904 if(bits>8) linesize /= 2;
906 for (j = 0; j < n; j++) {
909 dc = mjpeg_decode_dc(s, s->dc_index[i]);
913 ptr = s->picture.data[c] +
914 (linesize * (v * mb_y + y)) +
915 (h * mb_x + x); //FIXME optimize this crap
916 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
918 pred &= (-1)<<(8-s->bits);
919 *ptr = pred + (dc << point_transform);
921 ptr16 = (uint16_t*)(s->picture.data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
922 PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
924 pred &= (-1)<<(16-s->bits);
925 *ptr16= pred + (dc << point_transform);
935 if (s->restart_interval && !--s->restart_count) {
936 align_get_bits(&s->gb);
937 skip_bits(&s->gb, 16); /* skip RSTn */
944 static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
945 int linesize, int lowres)
948 case 0: copy_block8(dst, src, linesize, linesize, 8);
950 case 1: copy_block4(dst, src, linesize, linesize, 4);
952 case 2: copy_block2(dst, src, linesize, linesize, 2);
959 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
960 int Al, const uint8_t *mb_bitmask,
961 const AVFrame *reference)
964 uint8_t *data[MAX_COMPONENTS];
965 const uint8_t *reference_data[MAX_COMPONENTS];
966 int linesize[MAX_COMPONENTS];
967 GetBitContext mb_bitmask_gb;
970 init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
972 if (s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
973 av_log(s->avctx, AV_LOG_ERROR,
974 "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
978 for (i = 0; i < nb_components; i++) {
979 int c = s->comp_index[i];
980 data[c] = s->picture_ptr->data[c];
981 reference_data[c] = reference ? reference->data[c] : NULL;
982 linesize[c] = s->linesize[c];
983 s->coefs_finished[c] |= 1;
985 // picture should be flipped upside-down for this codec
986 int offset = (linesize[c] * (s->v_scount[i] *
987 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
989 reference_data[c] += offset;
994 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
995 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
996 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
998 if (s->restart_interval && !s->restart_count)
999 s->restart_count = s->restart_interval;
1001 if (get_bits_left(&s->gb) < 0) {
1002 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1003 -get_bits_left(&s->gb));
1006 for (i = 0; i < nb_components; i++) {
1008 int n, h, v, x, y, c, j;
1010 n = s->nb_blocks[i];
1011 c = s->comp_index[i];
1016 for (j = 0; j < n; j++) {
1017 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1018 (h * mb_x + x) * 8) >> s->avctx->lowres);
1020 if (s->interlaced && s->bottom_field)
1021 block_offset += linesize[c] >> 1;
1022 ptr = data[c] + block_offset;
1023 if (!s->progressive) {
1025 mjpeg_copy_block(ptr, reference_data[c] + block_offset,
1026 linesize[c], s->avctx->lowres);
1028 s->dsp.clear_block(s->block);
1029 if (decode_block(s, s->block, i,
1030 s->dc_index[i], s->ac_index[i],
1031 s->quant_matrixes[s->quant_index[c]]) < 0) {
1032 av_log(s->avctx, AV_LOG_ERROR,
1033 "error y=%d x=%d\n", mb_y, mb_x);
1036 s->dsp.idct_put(ptr, linesize[c], s->block);
1039 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1041 DCTELEM *block = s->blocks[c][block_idx];
1043 block[0] += get_bits1(&s->gb) *
1044 s->quant_matrixes[s->quant_index[c]][0] << Al;
1045 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1046 s->quant_matrixes[s->quant_index[c]],
1048 av_log(s->avctx, AV_LOG_ERROR,
1049 "error y=%d x=%d\n", mb_y, mb_x);
1053 // av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n",
1055 // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n",
1056 // mb_x, mb_y, x, y, c, s->bottom_field,
1057 // (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1065 if (s->restart_interval) {
1067 if(s->restart_count == 0 && s->avctx->codec_id == CODEC_ID_THP){
1068 align_get_bits(&s->gb);
1069 for (i = 0; i < nb_components; i++) /* reset dc */
1070 s->last_dc[i] = 1024;
1073 i = 8 + ((-get_bits_count(&s->gb)) & 7);
1075 if (show_bits(&s->gb, i) == (1 << i) - 1) {
1076 int pos = get_bits_count(&s->gb);
1077 align_get_bits(&s->gb);
1078 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
1079 skip_bits(&s->gb, 8);
1080 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
1081 for (i = 0; i < nb_components; i++) /* reset dc */
1082 s->last_dc[i] = 1024;
1084 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
1092 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1093 int se, int Ah, int Al)
1097 int c = s->comp_index[0];
1098 uint8_t *data = s->picture.data[c];
1099 int linesize = s->linesize[c];
1101 int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
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);
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 /* XXX: verify len field validity */
1148 len = get_bits(&s->gb, 16);
1149 nb_components = get_bits(&s->gb, 8);
1150 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1151 av_log(s->avctx, AV_LOG_ERROR,
1152 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1155 if (len != 6 + 2 * nb_components) {
1156 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1159 for (i = 0; i < nb_components; i++) {
1160 id = get_bits(&s->gb, 8) - 1;
1161 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1162 /* find component index */
1163 for (index = 0; index < s->nb_components; index++)
1164 if (id == s->component_id[index])
1166 if (index == s->nb_components) {
1167 av_log(s->avctx, AV_LOG_ERROR,
1168 "decode_sos: index(%d) out of components\n", index);
1171 /* Metasoft MJPEG codec has Cb and Cr swapped */
1172 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1173 && nb_components == 3 && s->nb_components == 3 && i)
1176 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
1178 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
1179 index = (index+2)%3;
1181 s->comp_index[i] = index;
1183 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1184 s->h_scount[i] = s->h_count[index];
1185 s->v_scount[i] = s->v_count[index];
1187 s->dc_index[i] = get_bits(&s->gb, 4);
1188 s->ac_index[i] = get_bits(&s->gb, 4);
1190 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1191 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1193 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))
1197 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1198 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1199 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1200 prev_shift = get_bits(&s->gb, 4); /* Ah */
1201 point_transform = get_bits(&s->gb, 4); /* Al */
1203 prev_shift = point_transform = 0;
1205 for (i = 0; i < nb_components; i++)
1206 s->last_dc[i] = 1024;
1208 if (nb_components > 1) {
1209 /* interleaved stream */
1210 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1211 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1212 } else if (!s->ls) { /* skip this for JPEG-LS */
1213 h = s->h_max / s->h_scount[0];
1214 v = s->v_max / s->v_scount[0];
1215 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1216 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1217 s->nb_blocks[0] = 1;
1222 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1223 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1224 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1225 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1226 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1229 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1230 for (i = s->mjpb_skiptosod; i > 0; i--)
1231 skip_bits(&s->gb, 8);
1234 av_assert0(s->picture_ptr == &s->picture);
1235 if (CONFIG_JPEGLS_DECODER && s->ls) {
1237 // reset_ls_coding_parameters(s, 0);
1239 if (ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
1243 if (ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform) < 0)
1246 if (ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
1251 if (s->progressive && predictor) {
1252 av_assert0(s->picture_ptr == &s->picture);
1253 if (mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift,
1254 point_transform) < 0)
1257 if (mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
1258 mb_bitmask, reference) < 0)
1265 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1269 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1271 if (get_bits(&s->gb, 16) != 4)
1273 s->restart_interval = get_bits(&s->gb, 16);
1274 s->restart_count = 0;
1275 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1276 s->restart_interval);
1281 static int mjpeg_decode_app(MJpegDecodeContext *s)
1285 len = get_bits(&s->gb, 16);
1288 if (8 * len > get_bits_left(&s->gb))
1291 id = get_bits_long(&s->gb, 32);
1292 id = av_be2ne32(id);
1295 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1296 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1298 /* Buggy AVID, it puts EOI only at every 10th frame. */
1299 /* Also, this fourcc is used by non-avid files too, it holds some
1300 information, but it's always present in AVID-created files. */
1301 if (id == AV_RL32("AVI1")) {
1307 4bytes field_size_less_padding
1310 // if (s->first_picture)
1311 // printf("mjpeg: workarounding buggy AVID\n");
1312 i = get_bits(&s->gb, 8); len--;
1313 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1315 skip_bits(&s->gb, 8);
1316 skip_bits(&s->gb, 32);
1317 skip_bits(&s->gb, 32);
1320 // if (s->interlace_polarity)
1321 // printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1327 if (id == AV_RL32("JFIF")) {
1328 int t_w, t_h, v1, v2;
1329 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1330 v1 = get_bits(&s->gb, 8);
1331 v2 = get_bits(&s->gb, 8);
1332 skip_bits(&s->gb, 8);
1334 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1335 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1337 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1338 av_log(s->avctx, AV_LOG_INFO,
1339 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1341 s->avctx->sample_aspect_ratio.num,
1342 s->avctx->sample_aspect_ratio.den);
1344 t_w = get_bits(&s->gb, 8);
1345 t_h = get_bits(&s->gb, 8);
1347 /* skip thumbnail */
1348 if (len -10 - (t_w * t_h * 3) > 0)
1349 len -= t_w * t_h * 3;
1355 if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1356 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1357 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1358 skip_bits(&s->gb, 16); /* version */
1359 skip_bits(&s->gb, 16); /* flags0 */
1360 skip_bits(&s->gb, 16); /* flags1 */
1361 skip_bits(&s->gb, 8); /* transform */
1366 if (id == AV_RL32("LJIF")) {
1367 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1368 av_log(s->avctx, AV_LOG_INFO,
1369 "Pegasus lossless jpeg header found\n");
1370 skip_bits(&s->gb, 16); /* version ? */
1371 skip_bits(&s->gb, 16); /* unknwon always 0? */
1372 skip_bits(&s->gb, 16); /* unknwon always 0? */
1373 skip_bits(&s->gb, 16); /* unknwon always 0? */
1374 switch (get_bits(&s->gb, 8)) {
1384 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1391 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1392 id = get_bits_long(&s->gb, 32);
1393 id = av_be2ne32(id);
1396 if (id == AV_RL32("mjpg")) {
1398 skip_bits(&s->gb, 32); /* field size */
1399 skip_bits(&s->gb, 32); /* pad field size */
1400 skip_bits(&s->gb, 32); /* next off */
1401 skip_bits(&s->gb, 32); /* quant off */
1402 skip_bits(&s->gb, 32); /* huff off */
1403 skip_bits(&s->gb, 32); /* image off */
1404 skip_bits(&s->gb, 32); /* scan off */
1405 skip_bits(&s->gb, 32); /* data off */
1407 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1408 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1413 /* slow but needed for extreme adobe jpegs */
1415 av_log(s->avctx, AV_LOG_ERROR,
1416 "mjpeg: error, decode_app parser read over the end\n");
1418 skip_bits(&s->gb, 8);
1423 static int mjpeg_decode_com(MJpegDecodeContext *s)
1425 int len = get_bits(&s->gb, 16);
1426 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1427 char *cbuf = av_malloc(len - 1);
1430 for (i = 0; i < len - 2; i++)
1431 cbuf[i] = get_bits(&s->gb, 8);
1432 if (i > 0 && cbuf[i - 1] == '\n')
1437 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1438 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1440 /* buggy avid, it puts EOI only at every 10th frame */
1441 if (!strcmp(cbuf, "AVID")) {
1443 // if (s->first_picture)
1444 // printf("mjpeg: workarounding buggy AVID\n");
1445 } else if (!strcmp(cbuf, "CS=ITU601"))
1447 else if ((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1448 (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1458 /* return the 8 bit start code value and update the search
1459 state. Return -1 if no start code found */
1460 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1462 const uint8_t *buf_ptr;
1467 buf_ptr = *pbuf_ptr;
1468 while (buf_ptr < buf_end) {
1471 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1479 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1480 *pbuf_ptr = buf_ptr;
1484 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1485 const uint8_t **buf_ptr, const uint8_t *buf_end,
1486 const uint8_t **unescaped_buf_ptr,
1487 int *unescaped_buf_size)
1490 start_code = find_marker(buf_ptr, buf_end);
1492 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1494 return AVERROR(ENOMEM);
1496 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1497 if (start_code == SOS && !s->ls) {
1498 const uint8_t *src = *buf_ptr;
1499 uint8_t *dst = s->buffer;
1501 while (src < buf_end) {
1502 uint8_t x = *(src++);
1505 if (s->avctx->codec_id != CODEC_ID_THP) {
1507 while (src < buf_end && x == 0xff)
1510 if (x >= 0xd0 && x <= 0xd7)
1517 *unescaped_buf_ptr = s->buffer;
1518 *unescaped_buf_size = dst - s->buffer;
1520 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1521 (buf_end - *buf_ptr) - (dst - s->buffer));
1522 } else if (start_code == SOS && s->ls) {
1523 const uint8_t *src = *buf_ptr;
1524 uint8_t *dst = s->buffer;
1532 while (src + t < buf_end) {
1533 uint8_t x = src[t++];
1535 while ((src + t < buf_end) && x == 0xff)
1544 init_put_bits(&pb, dst, t);
1546 /* unescape bitstream */
1548 uint8_t x = src[b++];
1549 put_bits(&pb, 8, x);
1552 put_bits(&pb, 7, x);
1556 flush_put_bits(&pb);
1558 *unescaped_buf_ptr = dst;
1559 *unescaped_buf_size = (bit_count + 7) >> 3;
1561 *unescaped_buf_ptr = *buf_ptr;
1562 *unescaped_buf_size = buf_end - *buf_ptr;
1568 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
1571 const uint8_t *buf = avpkt->data;
1572 int buf_size = avpkt->size;
1573 MJpegDecodeContext *s = avctx->priv_data;
1574 const uint8_t *buf_end, *buf_ptr;
1575 const uint8_t *unescaped_buf_ptr;
1576 int unescaped_buf_size;
1579 AVFrame *picture = data;
1581 s->got_picture = 0; // picture from previous image can not be reused
1583 buf_end = buf + buf_size;
1584 while (buf_ptr < buf_end) {
1585 /* find start next marker */
1586 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1588 &unescaped_buf_size);
1590 if (start_code < 0) {
1592 } else if (unescaped_buf_size > (1U<<29)) {
1593 av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",
1594 start_code, unescaped_buf_size, buf_size);
1595 return AVERROR_INVALIDDATA;
1597 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1598 start_code, buf_end - buf_ptr);
1600 init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size * 8);
1602 s->start_code = start_code;
1603 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1604 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1606 /* process markers */
1607 if (start_code >= 0xd0 && start_code <= 0xd7)
1608 av_log(avctx, AV_LOG_DEBUG,
1609 "restart marker: %d\n", start_code & 0x0f);
1611 else if (start_code >= APP0 && start_code <= APP15)
1612 mjpeg_decode_app(s);
1614 else if (start_code == COM)
1615 mjpeg_decode_com(s);
1617 switch (start_code) {
1619 s->restart_interval = 0;
1620 s->restart_count = 0;
1621 /* nothing to do on SOI */
1624 ff_mjpeg_decode_dqt(s);
1627 if (ff_mjpeg_decode_dht(s) < 0) {
1628 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1637 if (ff_mjpeg_decode_sof(s) < 0)
1644 if (ff_mjpeg_decode_sof(s) < 0)
1651 if (ff_mjpeg_decode_sof(s) < 0)
1658 if (ff_mjpeg_decode_sof(s) < 0)
1662 if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1668 if (!s->got_picture) {
1669 av_log(avctx, AV_LOG_WARNING,
1670 "Found EOI before any SOF, ignoring\n");
1673 if (s->interlaced) {
1674 s->bottom_field ^= 1;
1675 /* if not bottom field, do not output image yet */
1676 if (s->bottom_field == !s->interlace_polarity)
1679 *picture = *s->picture_ptr;
1680 *data_size = sizeof(AVFrame);
1683 picture->quality = FFMAX3(s->qscale[0],
1686 picture->qstride = 0;
1687 picture->qscale_table = s->qscale_table;
1688 memset(picture->qscale_table, picture->quality,
1689 (s->width + 15) / 16);
1690 if (avctx->debug & FF_DEBUG_QP)
1691 av_log(avctx, AV_LOG_DEBUG,
1692 "QP: %d\n", picture->quality);
1693 picture->quality *= FF_QP2LAMBDA;
1698 if (!s->got_picture) {
1699 av_log(avctx, AV_LOG_WARNING,
1700 "Can not process SOS before SOF, skipping\n");
1703 if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&
1704 (avctx->err_recognition & AV_EF_EXPLODE))
1705 return AVERROR_INVALIDDATA;
1708 mjpeg_decode_dri(s);
1720 av_log(avctx, AV_LOG_ERROR,
1721 "mjpeg: unsupported coding type (%x)\n", start_code);
1724 // printf("mjpeg: unsupported marker (%x)\n", start_code);
1728 /* eof process start code */
1729 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1730 av_log(avctx, AV_LOG_DEBUG,
1731 "marker parser used %d bytes (%d bits)\n",
1732 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1735 if (s->got_picture) {
1736 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1739 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1743 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1744 av_assert0(avctx->pix_fmt == PIX_FMT_YUVJ444P ||
1745 avctx->pix_fmt == PIX_FMT_YUV444P ||
1746 avctx->pix_fmt == PIX_FMT_YUVJ440P ||
1747 avctx->pix_fmt == PIX_FMT_YUV440P);
1748 for (i = 0; i < s->chroma_height; i++) {
1749 for (index = s->width - 1; index; index--)
1750 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1751 line += s->linesize[s->upscale_h];
1755 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1756 av_assert0(avctx->pix_fmt == PIX_FMT_YUVJ444P ||
1757 avctx->pix_fmt == PIX_FMT_YUV444P ||
1758 avctx->pix_fmt == PIX_FMT_YUVJ422P ||
1759 avctx->pix_fmt == PIX_FMT_YUV422P);
1760 for (i = s->height - 1; i; i--) {
1761 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1762 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1764 memcpy(dst, src1, s->width);
1766 for (index = 0; index < s->width; index++)
1767 dst[index] = (src1[index] + src2[index]) >> 1;
1769 dst -= s->linesize[s->upscale_v];
1772 av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n",
1774 // return buf_end - buf_ptr;
1775 return buf_ptr - buf;
1778 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1780 MJpegDecodeContext *s = avctx->priv_data;
1783 if (s->picture_ptr && s->picture_ptr->data[0])
1784 avctx->release_buffer(avctx, s->picture_ptr);
1787 av_free(s->qscale_table);
1788 av_freep(&s->ljpeg_buffer);
1789 s->ljpeg_buffer_size = 0;
1791 for (i = 0; i < 3; i++) {
1792 for (j = 0; j < 4; j++)
1793 ff_free_vlc(&s->vlcs[i][j]);
1795 for (i = 0; i < MAX_COMPONENTS; i++) {
1796 av_freep(&s->blocks[i]);
1797 av_freep(&s->last_nnz[i]);
1802 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1803 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1804 static const AVOption options[] = {
1805 { "extern_huff", "Use external huffman table.",
1806 OFFSET(extern_huff), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD },
1810 static const AVClass mjpegdec_class = {
1811 .class_name = "MJPEG decoder",
1812 .item_name = av_default_item_name,
1814 .version = LIBAVUTIL_VERSION_INT,
1817 AVCodec ff_mjpeg_decoder = {
1819 .type = AVMEDIA_TYPE_VIDEO,
1820 .id = CODEC_ID_MJPEG,
1821 .priv_data_size = sizeof(MJpegDecodeContext),
1822 .init = ff_mjpeg_decode_init,
1823 .close = ff_mjpeg_decode_end,
1824 .decode = ff_mjpeg_decode_frame,
1825 .capabilities = CODEC_CAP_DR1,
1827 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1828 .priv_class = &mjpegdec_class,
1831 AVCodec ff_thp_decoder = {
1833 .type = AVMEDIA_TYPE_VIDEO,
1835 .priv_data_size = sizeof(MJpegDecodeContext),
1836 .init = ff_mjpeg_decode_init,
1837 .close = ff_mjpeg_decode_end,
1838 .decode = ff_mjpeg_decode_frame,
1839 .capabilities = CODEC_CAP_DR1,
1841 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),