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];
51 uint16_t huff_code[256];
52 uint16_t huff_sym[256];
55 assert(nb_codes <= 256);
57 memset(huff_size, 0, sizeof(huff_size));
58 ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
60 for (i = 0; i < 256; i++)
61 huff_sym[i] = i + 16 * is_ac;
64 huff_sym[0] = 16 * 256;
66 return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
67 huff_code, 2, 2, huff_sym, 2, 2, use_static);
70 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
72 build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
73 ff_mjpeg_val_dc, 12, 0, 0);
74 build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
75 ff_mjpeg_val_dc, 12, 0, 0);
76 build_vlc(&s->vlcs[1][0], ff_mjpeg_bits_ac_luminance,
77 ff_mjpeg_val_ac_luminance, 251, 0, 1);
78 build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
79 ff_mjpeg_val_ac_chrominance, 251, 0, 1);
80 build_vlc(&s->vlcs[2][0], ff_mjpeg_bits_ac_luminance,
81 ff_mjpeg_val_ac_luminance, 251, 0, 0);
82 build_vlc(&s->vlcs[2][1], ff_mjpeg_bits_ac_chrominance,
83 ff_mjpeg_val_ac_chrominance, 251, 0, 0);
86 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
88 MJpegDecodeContext *s = avctx->priv_data;
91 s->picture_ptr = &s->picture;
92 avcodec_get_frame_defaults(&s->picture);
95 ff_dsputil_init(&s->dsp, avctx);
96 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
100 s->first_picture = 1;
101 s->org_height = avctx->coded_height;
102 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
104 build_basic_mjpeg_vlc(s);
106 if (s->extern_huff) {
107 av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
108 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
109 if (ff_mjpeg_decode_dht(s)) {
110 av_log(avctx, AV_LOG_ERROR,
111 "mjpeg: error using external huffman table, switching back to internal\n");
112 build_basic_mjpeg_vlc(s);
115 if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
116 s->interlace_polarity = 1; /* bottom field first */
117 av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
119 if (avctx->codec->id == CODEC_ID_AMV)
126 /* quantize tables */
127 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
129 int len, index, i, j;
131 len = get_bits(&s->gb, 16) - 2;
134 /* only 8 bit precision handled */
135 if (get_bits(&s->gb, 4) != 0) {
136 av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
139 index = get_bits(&s->gb, 4);
142 av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
143 /* read quant table */
144 for (i = 0; i < 64; i++) {
145 j = s->scantable.permutated[i];
146 s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
149 // XXX FIXME finetune, and perhaps add dc too
150 s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
151 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
152 av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
153 index, s->qscale[index]);
159 /* decode huffman tables and build VLC decoders */
160 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
162 int len, index, i, class, n, v, code_max;
163 uint8_t bits_table[17];
164 uint8_t val_table[256];
166 len = get_bits(&s->gb, 16) - 2;
171 class = get_bits(&s->gb, 4);
174 index = get_bits(&s->gb, 4);
178 for (i = 1; i <= 16; i++) {
179 bits_table[i] = get_bits(&s->gb, 8);
183 if (len < n || n > 256)
187 for (i = 0; i < n; i++) {
188 v = get_bits(&s->gb, 8);
195 /* build VLC and flush previous vlc if present */
196 ff_free_vlc(&s->vlcs[class][index]);
197 av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
198 class, index, code_max + 1);
199 if (build_vlc(&s->vlcs[class][index], bits_table, val_table,
200 code_max + 1, 0, class > 0) < 0)
204 ff_free_vlc(&s->vlcs[2][index]);
205 if (build_vlc(&s->vlcs[2][index], bits_table, val_table,
206 code_max + 1, 0, 0) < 0)
213 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
215 int len, nb_components, i, width, height, pix_fmt_id;
218 s->upscale_h = s->upscale_v = 0;
220 /* XXX: verify len field validity */
221 len = get_bits(&s->gb, 16);
222 s->bits = get_bits(&s->gb, 8);
226 if (s->bits == 9 && !s->pegasus_rct)
227 s->rct = 1; // FIXME ugly
229 if (s->bits != 8 && !s->lossless) {
230 av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
234 if(s->lossless && s->avctx->lowres){
235 av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
239 height = get_bits(&s->gb, 16);
240 width = get_bits(&s->gb, 16);
242 // HACK for odd_height.mov
243 if (s->interlaced && s->width == width && s->height == height + 1)
246 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
247 if (av_image_check_size(width, height, 0, s->avctx))
250 nb_components = get_bits(&s->gb, 8);
251 if (nb_components <= 0 ||
252 nb_components > MAX_COMPONENTS)
254 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
255 if (nb_components != s->nb_components) {
256 av_log(s->avctx, AV_LOG_ERROR, "nb_components changing in interlaced picture\n");
257 return AVERROR_INVALIDDATA;
260 if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
261 av_log(s->avctx, AV_LOG_ERROR,
262 "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
265 s->nb_components = nb_components;
268 for (i = 0; i < nb_components; i++) {
270 s->component_id[i] = get_bits(&s->gb, 8) - 1;
271 s->h_count[i] = get_bits(&s->gb, 4);
272 s->v_count[i] = get_bits(&s->gb, 4);
273 /* compute hmax and vmax (only used in interleaved case) */
274 if (s->h_count[i] > s->h_max)
275 s->h_max = s->h_count[i];
276 if (s->v_count[i] > s->v_max)
277 s->v_max = s->v_count[i];
278 if (!s->h_count[i] || !s->v_count[i]) {
279 av_log(s->avctx, AV_LOG_ERROR, "h/v_count is 0\n");
282 s->quant_index[i] = get_bits(&s->gb, 8);
283 if (s->quant_index[i] >= 4)
285 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
286 i, s->h_count[i], s->v_count[i],
287 s->component_id[i], s->quant_index[i]);
290 if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
291 av_log(s->avctx, AV_LOG_ERROR,
292 "Subsampling in JPEG-LS is not supported.\n");
296 if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && nb_components==3)
299 /* if different size, realloc/alloc picture */
300 /* XXX: also check h_count and v_count */
301 if (width != s->width || height != s->height) {
302 av_freep(&s->qscale_table);
308 /* test interlaced mode */
309 if (s->first_picture &&
310 s->org_height != 0 &&
311 s->height < ((s->org_height * 3) / 4)) {
313 s->bottom_field = s->interlace_polarity;
314 s->picture_ptr->interlaced_frame = 1;
315 s->picture_ptr->top_field_first = !s->interlace_polarity;
319 avcodec_set_dimensions(s->avctx, width, height);
321 s->qscale_table = av_mallocz((s->width + 15) / 16);
322 s->first_picture = 0;
325 if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
326 if (s->progressive) {
327 av_log_ask_for_sample(s->avctx, "progressively coded interlaced pictures not supported\n");
328 return AVERROR_INVALIDDATA;
333 /* XXX: not complete test ! */
334 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
335 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
336 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
337 (s->h_count[3] << 4) | s->v_count[3];
338 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
339 /* NOTE we do not allocate pictures large enough for the possible
340 * padding of h/v_count being 4 */
341 if (!(pix_fmt_id & 0xD0D0D0D0))
342 pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
343 if (!(pix_fmt_id & 0x0D0D0D0D))
344 pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
346 switch (pix_fmt_id) {
349 s->avctx->pix_fmt = PIX_FMT_BGR24;
351 if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
352 s->avctx->pix_fmt = PIX_FMT_GBR24P;
354 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
355 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
358 assert(s->nb_components == 3);
362 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
363 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
365 s->upscale_h = (pix_fmt_id == 0x22122100);
366 s->chroma_height = s->height;
370 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
371 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
372 s->upscale_v = (pix_fmt_id == 0x22211200);
374 s->chroma_height = s->height;
377 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
378 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
381 s->chroma_height = s->height / 2;
385 s->avctx->pix_fmt = PIX_FMT_GRAY8;
387 s->avctx->pix_fmt = PIX_FMT_GRAY16;
392 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV440P : PIX_FMT_YUVJ440P;
393 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
394 s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);
395 s->chroma_height = s->height / 2;
398 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
399 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
403 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
404 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
405 s->upscale_v = (pix_fmt_id == 0x22121100) + 1;
408 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
409 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
412 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
416 s->upscale_h = s->upscale_v = 0;
417 if (s->nb_components > 1)
418 s->avctx->pix_fmt = PIX_FMT_RGB24;
419 else if (s->bits <= 8)
420 s->avctx->pix_fmt = PIX_FMT_GRAY8;
422 s->avctx->pix_fmt = PIX_FMT_GRAY16;
425 if (s->picture_ptr->data[0])
426 s->avctx->release_buffer(s->avctx, s->picture_ptr);
428 if (s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0) {
429 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
432 s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
433 s->picture_ptr->key_frame = 1;
436 for (i = 0; i < 3; i++)
437 s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
439 // printf("%d %d %d %d %d %d\n",
440 // s->width, s->height, s->linesize[0], s->linesize[1],
441 // s->interlaced, s->avctx->height);
443 if (len != (8 + (3 * nb_components)))
444 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");
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);
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");
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);
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);
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 = 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 = 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->flags & CODEC_FLAG_EMU_EDGE) {
970 av_log(s->avctx, AV_LOG_ERROR,
971 "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
975 for (i = 0; i < nb_components; i++) {
976 int c = s->comp_index[i];
977 data[c] = s->picture_ptr->data[c];
978 reference_data[c] = reference ? reference->data[c] : NULL;
979 linesize[c] = s->linesize[c];
980 s->coefs_finished[c] |= 1;
982 // picture should be flipped upside-down for this codec
983 int offset = (linesize[c] * (s->v_scount[i] *
984 (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
986 reference_data[c] += offset;
991 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
992 for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
993 const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
995 if (s->restart_interval && !s->restart_count)
996 s->restart_count = s->restart_interval;
998 if (get_bits_left(&s->gb) < 0) {
999 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1000 -get_bits_left(&s->gb));
1003 for (i = 0; i < nb_components; i++) {
1005 int n, h, v, x, y, c, j;
1007 n = s->nb_blocks[i];
1008 c = s->comp_index[i];
1013 for (j = 0; j < n; j++) {
1014 block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1015 (h * mb_x + x) * 8) >> s->avctx->lowres);
1017 if (s->interlaced && s->bottom_field)
1018 block_offset += linesize[c] >> 1;
1019 ptr = data[c] + block_offset;
1020 if (!s->progressive) {
1022 mjpeg_copy_block(ptr, reference_data[c] + block_offset,
1023 linesize[c], s->avctx->lowres);
1025 s->dsp.clear_block(s->block);
1026 if (decode_block(s, s->block, i,
1027 s->dc_index[i], s->ac_index[i],
1028 s->quant_matrixes[s->quant_index[c]]) < 0) {
1029 av_log(s->avctx, AV_LOG_ERROR,
1030 "error y=%d x=%d\n", mb_y, mb_x);
1033 s->dsp.idct_put(ptr, linesize[c], s->block);
1036 int block_idx = s->block_stride[c] * (v * mb_y + y) +
1038 DCTELEM *block = s->blocks[c][block_idx];
1040 block[0] += get_bits1(&s->gb) *
1041 s->quant_matrixes[s->quant_index[c]][0] << Al;
1042 else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1043 s->quant_matrixes[s->quant_index[c]],
1045 av_log(s->avctx, AV_LOG_ERROR,
1046 "error y=%d x=%d\n", mb_y, mb_x);
1050 // av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n",
1052 // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n",
1053 // mb_x, mb_y, x, y, c, s->bottom_field,
1054 // (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1062 if (s->restart_interval) {
1064 if(s->restart_count == 0 && s->avctx->codec_id == CODEC_ID_THP){
1065 align_get_bits(&s->gb);
1066 for (i = 0; i < nb_components; i++) /* reset dc */
1067 s->last_dc[i] = 1024;
1070 i = 8 + ((-get_bits_count(&s->gb)) & 7);
1072 if (show_bits(&s->gb, i) == (1 << i) - 1) {
1073 int pos = get_bits_count(&s->gb);
1074 align_get_bits(&s->gb);
1075 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
1076 skip_bits(&s->gb, 8);
1077 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
1078 for (i = 0; i < nb_components; i++) /* reset dc */
1079 s->last_dc[i] = 1024;
1081 skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
1089 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
1090 int se, int Ah, int Al)
1094 int c = s->comp_index[0];
1095 uint8_t *data = s->picture.data[c];
1096 int linesize = s->linesize[c];
1098 int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
1101 s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
1102 last_scan = !~s->coefs_finished[c];
1105 if (s->interlaced && s->bottom_field)
1106 data += linesize >> 1;
1108 for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1109 uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1110 int block_idx = mb_y * s->block_stride[c];
1111 DCTELEM (*block)[64] = &s->blocks[c][block_idx];
1112 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1113 for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1116 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1117 quant_matrix, ss, se, Al, &EOBRUN);
1119 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1120 quant_matrix, ss, se, Al, &EOBRUN);
1122 av_log(s->avctx, AV_LOG_ERROR,
1123 "error y=%d x=%d\n", mb_y, mb_x);
1128 s->dsp.idct_put(ptr, linesize, *block);
1129 ptr += 8 >> s->avctx->lowres;
1136 int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
1137 const AVFrame *reference)
1139 int len, nb_components, i, h, v, predictor, point_transform;
1141 const int block_size = s->lossless ? 1 : 8;
1142 int ilv, prev_shift;
1144 /* XXX: verify len field validity */
1145 len = get_bits(&s->gb, 16);
1146 nb_components = get_bits(&s->gb, 8);
1147 if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1148 av_log(s->avctx, AV_LOG_ERROR,
1149 "decode_sos: nb_components (%d) unsupported\n", nb_components);
1152 if (len != 6 + 2 * nb_components) {
1153 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1156 for (i = 0; i < nb_components; i++) {
1157 id = get_bits(&s->gb, 8) - 1;
1158 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1159 /* find component index */
1160 for (index = 0; index < s->nb_components; index++)
1161 if (id == s->component_id[index])
1163 if (index == s->nb_components) {
1164 av_log(s->avctx, AV_LOG_ERROR,
1165 "decode_sos: index(%d) out of components\n", index);
1168 /* Metasoft MJPEG codec has Cb and Cr swapped */
1169 if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1170 && nb_components == 3 && s->nb_components == 3 && i)
1173 if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
1175 if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == PIX_FMT_GBR24P)
1176 index = (index+2)%3;
1178 s->comp_index[i] = index;
1180 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1181 s->h_scount[i] = s->h_count[index];
1182 s->v_scount[i] = s->v_count[index];
1184 s->dc_index[i] = get_bits(&s->gb, 4);
1185 s->ac_index[i] = get_bits(&s->gb, 4);
1187 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1188 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1190 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))
1194 predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1195 ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1196 if(s->avctx->codec_tag != AV_RL32("CJPG")){
1197 prev_shift = get_bits(&s->gb, 4); /* Ah */
1198 point_transform = get_bits(&s->gb, 4); /* Al */
1200 prev_shift = point_transform = 0;
1202 for (i = 0; i < nb_components; i++)
1203 s->last_dc[i] = 1024;
1205 if (nb_components > 1) {
1206 /* interleaved stream */
1207 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1208 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1209 } else if (!s->ls) { /* skip this for JPEG-LS */
1210 h = s->h_max / s->h_scount[0];
1211 v = s->v_max / s->v_scount[0];
1212 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1213 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1214 s->nb_blocks[0] = 1;
1219 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1220 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1221 s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1222 predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1223 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1226 /* mjpeg-b can have padding bytes between sos and image data, skip them */
1227 for (i = s->mjpb_skiptosod; i > 0; i--)
1228 skip_bits(&s->gb, 8);
1231 av_assert0(s->picture_ptr == &s->picture);
1232 if (CONFIG_JPEGLS_DECODER && s->ls) {
1234 // reset_ls_coding_parameters(s, 0);
1236 if (ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
1240 if (ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform) < 0)
1243 if (ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
1248 if (s->progressive && predictor) {
1249 av_assert0(s->picture_ptr == &s->picture);
1250 if (mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift,
1251 point_transform) < 0)
1254 if (mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
1255 mb_bitmask, reference) < 0)
1262 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1266 static int mjpeg_decode_dri(MJpegDecodeContext *s)
1268 if (get_bits(&s->gb, 16) != 4)
1270 s->restart_interval = get_bits(&s->gb, 16);
1271 s->restart_count = 0;
1272 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1273 s->restart_interval);
1278 static int mjpeg_decode_app(MJpegDecodeContext *s)
1282 len = get_bits(&s->gb, 16);
1285 if (8 * len > get_bits_left(&s->gb))
1288 id = get_bits_long(&s->gb, 32);
1289 id = av_be2ne32(id);
1292 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1293 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1295 /* Buggy AVID, it puts EOI only at every 10th frame. */
1296 /* Also, this fourcc is used by non-avid files too, it holds some
1297 information, but it's always present in AVID-created files. */
1298 if (id == AV_RL32("AVI1")) {
1304 4bytes field_size_less_padding
1307 // if (s->first_picture)
1308 // printf("mjpeg: workarounding buggy AVID\n");
1309 i = get_bits(&s->gb, 8); len--;
1310 av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1312 skip_bits(&s->gb, 8);
1313 skip_bits(&s->gb, 32);
1314 skip_bits(&s->gb, 32);
1317 // if (s->interlace_polarity)
1318 // printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1324 if (id == AV_RL32("JFIF")) {
1325 int t_w, t_h, v1, v2;
1326 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1327 v1 = get_bits(&s->gb, 8);
1328 v2 = get_bits(&s->gb, 8);
1329 skip_bits(&s->gb, 8);
1331 s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1332 s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1334 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1335 av_log(s->avctx, AV_LOG_INFO,
1336 "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1338 s->avctx->sample_aspect_ratio.num,
1339 s->avctx->sample_aspect_ratio.den);
1341 t_w = get_bits(&s->gb, 8);
1342 t_h = get_bits(&s->gb, 8);
1344 /* skip thumbnail */
1345 if (len -10 - (t_w * t_h * 3) > 0)
1346 len -= t_w * t_h * 3;
1352 if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1353 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1354 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1355 skip_bits(&s->gb, 16); /* version */
1356 skip_bits(&s->gb, 16); /* flags0 */
1357 skip_bits(&s->gb, 16); /* flags1 */
1358 skip_bits(&s->gb, 8); /* transform */
1363 if (id == AV_RL32("LJIF")) {
1364 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1365 av_log(s->avctx, AV_LOG_INFO,
1366 "Pegasus lossless jpeg header found\n");
1367 skip_bits(&s->gb, 16); /* version ? */
1368 skip_bits(&s->gb, 16); /* unknwon always 0? */
1369 skip_bits(&s->gb, 16); /* unknwon always 0? */
1370 skip_bits(&s->gb, 16); /* unknwon always 0? */
1371 switch (get_bits(&s->gb, 8)) {
1381 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1388 if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1389 id = get_bits_long(&s->gb, 32);
1390 id = av_be2ne32(id);
1393 if (id == AV_RL32("mjpg")) {
1395 skip_bits(&s->gb, 32); /* field size */
1396 skip_bits(&s->gb, 32); /* pad field size */
1397 skip_bits(&s->gb, 32); /* next off */
1398 skip_bits(&s->gb, 32); /* quant off */
1399 skip_bits(&s->gb, 32); /* huff off */
1400 skip_bits(&s->gb, 32); /* image off */
1401 skip_bits(&s->gb, 32); /* scan off */
1402 skip_bits(&s->gb, 32); /* data off */
1404 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1405 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1410 /* slow but needed for extreme adobe jpegs */
1412 av_log(s->avctx, AV_LOG_ERROR,
1413 "mjpeg: error, decode_app parser read over the end\n");
1415 skip_bits(&s->gb, 8);
1420 static int mjpeg_decode_com(MJpegDecodeContext *s)
1422 int len = get_bits(&s->gb, 16);
1423 if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1424 char *cbuf = av_malloc(len - 1);
1427 for (i = 0; i < len - 2; i++)
1428 cbuf[i] = get_bits(&s->gb, 8);
1429 if (i > 0 && cbuf[i - 1] == '\n')
1434 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1435 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1437 /* buggy avid, it puts EOI only at every 10th frame */
1438 if (!strcmp(cbuf, "AVID")) {
1440 // if (s->first_picture)
1441 // printf("mjpeg: workarounding buggy AVID\n");
1442 } else if (!strcmp(cbuf, "CS=ITU601"))
1444 else if ((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1445 (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1455 /* return the 8 bit start code value and update the search
1456 state. Return -1 if no start code found */
1457 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1459 const uint8_t *buf_ptr;
1464 buf_ptr = *pbuf_ptr;
1465 while (buf_ptr < buf_end) {
1468 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1476 av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1477 *pbuf_ptr = buf_ptr;
1481 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1482 const uint8_t **buf_ptr, const uint8_t *buf_end,
1483 const uint8_t **unescaped_buf_ptr,
1484 int *unescaped_buf_size)
1487 start_code = find_marker(buf_ptr, buf_end);
1489 av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1491 return AVERROR(ENOMEM);
1493 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1494 if (start_code == SOS && !s->ls) {
1495 const uint8_t *src = *buf_ptr;
1496 uint8_t *dst = s->buffer;
1498 while (src < buf_end) {
1499 uint8_t x = *(src++);
1502 if (s->avctx->codec_id != CODEC_ID_THP) {
1504 while (src < buf_end && x == 0xff)
1507 if (x >= 0xd0 && x <= 0xd7)
1514 *unescaped_buf_ptr = s->buffer;
1515 *unescaped_buf_size = dst - s->buffer;
1517 av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1518 (buf_end - *buf_ptr) - (dst - s->buffer));
1519 } else if (start_code == SOS && s->ls) {
1520 const uint8_t *src = *buf_ptr;
1521 uint8_t *dst = s->buffer;
1529 while (src + t < buf_end) {
1530 uint8_t x = src[t++];
1532 while ((src + t < buf_end) && x == 0xff)
1541 init_put_bits(&pb, dst, t);
1543 /* unescape bitstream */
1545 uint8_t x = src[b++];
1546 put_bits(&pb, 8, x);
1549 put_bits(&pb, 7, x);
1553 flush_put_bits(&pb);
1555 *unescaped_buf_ptr = dst;
1556 *unescaped_buf_size = (bit_count + 7) >> 3;
1558 *unescaped_buf_ptr = *buf_ptr;
1559 *unescaped_buf_size = buf_end - *buf_ptr;
1565 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
1568 const uint8_t *buf = avpkt->data;
1569 int buf_size = avpkt->size;
1570 MJpegDecodeContext *s = avctx->priv_data;
1571 const uint8_t *buf_end, *buf_ptr;
1572 const uint8_t *unescaped_buf_ptr;
1573 int unescaped_buf_size;
1576 AVFrame *picture = data;
1578 s->got_picture = 0; // picture from previous image can not be reused
1580 buf_end = buf + buf_size;
1581 while (buf_ptr < buf_end) {
1582 /* find start next marker */
1583 start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1585 &unescaped_buf_size);
1587 if (start_code < 0) {
1589 } else if (unescaped_buf_size > (1U<<29)) {
1590 av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",
1591 start_code, unescaped_buf_size, buf_size);
1592 return AVERROR_INVALIDDATA;
1594 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
1595 start_code, buf_end - buf_ptr);
1597 init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size * 8);
1599 s->start_code = start_code;
1600 if (s->avctx->debug & FF_DEBUG_STARTCODE)
1601 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1603 /* process markers */
1604 if (start_code >= 0xd0 && start_code <= 0xd7)
1605 av_log(avctx, AV_LOG_DEBUG,
1606 "restart marker: %d\n", start_code & 0x0f);
1608 else if (start_code >= APP0 && start_code <= APP15)
1609 mjpeg_decode_app(s);
1611 else if (start_code == COM)
1612 mjpeg_decode_com(s);
1614 switch (start_code) {
1616 s->restart_interval = 0;
1617 s->restart_count = 0;
1618 /* nothing to do on SOI */
1621 ff_mjpeg_decode_dqt(s);
1624 if (ff_mjpeg_decode_dht(s) < 0) {
1625 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1634 if (ff_mjpeg_decode_sof(s) < 0)
1641 if (ff_mjpeg_decode_sof(s) < 0)
1648 if (ff_mjpeg_decode_sof(s) < 0)
1655 if (ff_mjpeg_decode_sof(s) < 0)
1659 if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1665 if (!s->got_picture) {
1666 av_log(avctx, AV_LOG_WARNING,
1667 "Found EOI before any SOF, ignoring\n");
1670 if (s->interlaced) {
1671 s->bottom_field ^= 1;
1672 /* if not bottom field, do not output image yet */
1673 if (s->bottom_field == !s->interlace_polarity)
1676 *picture = *s->picture_ptr;
1677 *data_size = sizeof(AVFrame);
1680 picture->quality = FFMAX3(s->qscale[0],
1683 picture->qstride = 0;
1684 picture->qscale_table = s->qscale_table;
1685 memset(picture->qscale_table, picture->quality,
1686 (s->width + 15) / 16);
1687 if (avctx->debug & FF_DEBUG_QP)
1688 av_log(avctx, AV_LOG_DEBUG,
1689 "QP: %d\n", picture->quality);
1690 picture->quality *= FF_QP2LAMBDA;
1695 if (!s->got_picture) {
1696 av_log(avctx, AV_LOG_WARNING,
1697 "Can not process SOS before SOF, skipping\n");
1700 if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&
1701 (avctx->err_recognition & AV_EF_EXPLODE))
1702 return AVERROR_INVALIDDATA;
1705 mjpeg_decode_dri(s);
1717 av_log(avctx, AV_LOG_ERROR,
1718 "mjpeg: unsupported coding type (%x)\n", start_code);
1721 // printf("mjpeg: unsupported marker (%x)\n", start_code);
1725 /* eof process start code */
1726 buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
1727 av_log(avctx, AV_LOG_DEBUG,
1728 "marker parser used %d bytes (%d bits)\n",
1729 (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
1732 if (s->got_picture) {
1733 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1736 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1740 uint8_t *line = s->picture_ptr->data[s->upscale_h];
1741 av_assert0(avctx->pix_fmt == PIX_FMT_YUVJ444P ||
1742 avctx->pix_fmt == PIX_FMT_YUV444P ||
1743 avctx->pix_fmt == PIX_FMT_YUVJ440P ||
1744 avctx->pix_fmt == PIX_FMT_YUV440P);
1745 for (i = 0; i < s->chroma_height; i++) {
1746 for (index = s->width - 1; index; index--)
1747 line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
1748 line += s->linesize[s->upscale_h];
1752 uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];
1753 av_assert0(avctx->pix_fmt == PIX_FMT_YUVJ444P ||
1754 avctx->pix_fmt == PIX_FMT_YUV444P ||
1755 avctx->pix_fmt == PIX_FMT_YUVJ422P ||
1756 avctx->pix_fmt == PIX_FMT_YUV422P);
1757 for (i = s->height - 1; i; i--) {
1758 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];
1759 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];
1761 memcpy(dst, src1, s->width);
1763 for (index = 0; index < s->width; index++)
1764 dst[index] = (src1[index] + src2[index]) >> 1;
1766 dst -= s->linesize[s->upscale_v];
1769 av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n",
1771 // return buf_end - buf_ptr;
1772 return buf_ptr - buf;
1775 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1777 MJpegDecodeContext *s = avctx->priv_data;
1780 if (s->picture_ptr && s->picture_ptr->data[0])
1781 avctx->release_buffer(avctx, s->picture_ptr);
1784 av_free(s->qscale_table);
1785 av_freep(&s->ljpeg_buffer);
1786 s->ljpeg_buffer_size = 0;
1788 for (i = 0; i < 3; i++) {
1789 for (j = 0; j < 4; j++)
1790 ff_free_vlc(&s->vlcs[i][j]);
1792 for (i = 0; i < MAX_COMPONENTS; i++) {
1793 av_freep(&s->blocks[i]);
1794 av_freep(&s->last_nnz[i]);
1799 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
1800 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1801 static const AVOption options[] = {
1802 { "extern_huff", "Use external huffman table.",
1803 OFFSET(extern_huff), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD },
1807 static const AVClass mjpegdec_class = {
1808 .class_name = "MJPEG decoder",
1809 .item_name = av_default_item_name,
1811 .version = LIBAVUTIL_VERSION_INT,
1814 AVCodec ff_mjpeg_decoder = {
1816 .type = AVMEDIA_TYPE_VIDEO,
1817 .id = CODEC_ID_MJPEG,
1818 .priv_data_size = sizeof(MJpegDecodeContext),
1819 .init = ff_mjpeg_decode_init,
1820 .close = ff_mjpeg_decode_end,
1821 .decode = ff_mjpeg_decode_frame,
1822 .capabilities = CODEC_CAP_DR1,
1824 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1825 .priv_class = &mjpegdec_class,
1828 AVCodec ff_thp_decoder = {
1830 .type = AVMEDIA_TYPE_VIDEO,
1832 .priv_data_size = sizeof(MJpegDecodeContext),
1833 .init = ff_mjpeg_decode_init,
1834 .close = ff_mjpeg_decode_end,
1835 .decode = ff_mjpeg_decode_frame,
1836 .capabilities = CODEC_CAP_DR1,
1838 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),