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
29 * @file libavcodec/mjpegdec.c
40 #include "jpeglsdec.h"
43 static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,
44 int nb_codes, int use_static, int is_ac)
46 uint8_t huff_size[256+16];
47 uint16_t huff_code[256+16];
49 assert(nb_codes <= 256);
51 memset(huff_size, 0, sizeof(huff_size));
52 ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
55 memmove(huff_size+16, huff_size, sizeof(uint8_t)*nb_codes);
56 memmove(huff_code+16, huff_code, sizeof(uint16_t)*nb_codes);
57 memset(huff_size, 0, sizeof(uint8_t)*16);
58 memset(huff_code, 0, sizeof(uint16_t)*16);
62 return init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, use_static);
65 static void build_basic_mjpeg_vlc(MJpegDecodeContext * s) {
66 build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
67 ff_mjpeg_val_dc, 12, 0, 0);
68 build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
69 ff_mjpeg_val_dc, 12, 0, 0);
70 build_vlc(&s->vlcs[1][0], ff_mjpeg_bits_ac_luminance,
71 ff_mjpeg_val_ac_luminance, 251, 0, 1);
72 build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
73 ff_mjpeg_val_ac_chrominance, 251, 0, 1);
76 av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
78 MJpegDecodeContext *s = avctx->priv_data;
81 dsputil_init(&s->dsp, avctx);
82 ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
87 s->org_height = avctx->coded_height;
88 avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
90 build_basic_mjpeg_vlc(s);
92 if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)
94 av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
95 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
96 if (ff_mjpeg_decode_dht(s)) {
97 av_log(avctx, AV_LOG_ERROR, "mjpeg: error using external huffman table, switching back to internal\n");
98 build_basic_mjpeg_vlc(s);
101 if (avctx->extradata_size > 9 &&
102 AV_RL32(avctx->extradata + 4) == MKTAG('f','i','e','l')) {
103 if (avctx->extradata[9] == 6) { /* quicktime icefloe 019 */
104 s->interlace_polarity = 1; /* bottom field first */
105 av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
108 if (avctx->codec->id == CODEC_ID_AMV)
115 /* quantize tables */
116 int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
118 int len, index, i, j;
120 len = get_bits(&s->gb, 16) - 2;
123 /* only 8 bit precision handled */
124 if (get_bits(&s->gb, 4) != 0)
126 av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
129 index = get_bits(&s->gb, 4);
132 av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
133 /* read quant table */
135 j = s->scantable.permutated[i];
136 s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
139 //XXX FIXME finetune, and perhaps add dc too
140 s->qscale[index]= FFMAX(
141 s->quant_matrixes[index][s->scantable.permutated[1]],
142 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
143 av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n", index, s->qscale[index]);
150 /* decode huffman tables and build VLC decoders */
151 int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
153 int len, index, i, class, n, v, code_max;
154 uint8_t bits_table[17];
155 uint8_t val_table[256];
157 len = get_bits(&s->gb, 16) - 2;
162 class = get_bits(&s->gb, 4);
165 index = get_bits(&s->gb, 4);
170 bits_table[i] = get_bits(&s->gb, 8);
174 if (len < n || n > 256)
179 v = get_bits(&s->gb, 8);
186 /* build VLC and flush previous vlc if present */
187 free_vlc(&s->vlcs[class][index]);
188 av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
189 class, index, code_max + 1);
190 if(build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1, 0, class > 0) < 0){
197 int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
199 int len, nb_components, i, width, height, pix_fmt_id;
201 /* XXX: verify len field validity */
202 len = get_bits(&s->gb, 16);
203 s->bits= get_bits(&s->gb, 8);
205 if(s->pegasus_rct) s->bits=9;
206 if(s->bits==9 && !s->pegasus_rct) s->rct=1; //FIXME ugly
208 if (s->bits != 8 && !s->lossless){
209 av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
213 height = get_bits(&s->gb, 16);
214 width = get_bits(&s->gb, 16);
216 //HACK for odd_height.mov
217 if(s->interlaced && s->width == width && s->height == height + 1)
220 av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
221 if(avcodec_check_dimensions(s->avctx, width, height))
224 nb_components = get_bits(&s->gb, 8);
225 if (nb_components <= 0 ||
226 nb_components > MAX_COMPONENTS)
228 if (s->ls && !(s->bits <= 8 || nb_components == 1)){
229 av_log(s->avctx, AV_LOG_ERROR, "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
232 s->nb_components = nb_components;
235 for(i=0;i<nb_components;i++) {
237 s->component_id[i] = get_bits(&s->gb, 8) - 1;
238 s->h_count[i] = get_bits(&s->gb, 4);
239 s->v_count[i] = get_bits(&s->gb, 4);
240 /* compute hmax and vmax (only used in interleaved case) */
241 if (s->h_count[i] > s->h_max)
242 s->h_max = s->h_count[i];
243 if (s->v_count[i] > s->v_max)
244 s->v_max = s->v_count[i];
245 s->quant_index[i] = get_bits(&s->gb, 8);
246 if (s->quant_index[i] >= 4)
248 av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n", i, s->h_count[i],
249 s->v_count[i], s->component_id[i], s->quant_index[i]);
252 if(s->ls && (s->h_max > 1 || s->v_max > 1)) {
253 av_log(s->avctx, AV_LOG_ERROR, "Subsampling in JPEG-LS is not supported.\n");
257 if(s->v_max==1 && s->h_max==1 && s->lossless==1) s->rgb=1;
259 /* if different size, realloc/alloc picture */
260 /* XXX: also check h_count and v_count */
261 if (width != s->width || height != s->height) {
262 av_freep(&s->qscale_table);
268 /* test interlaced mode */
269 if (s->first_picture &&
270 s->org_height != 0 &&
271 s->height < ((s->org_height * 3) / 4)) {
273 s->bottom_field = s->interlace_polarity;
274 s->picture.interlaced_frame = 1;
275 s->picture.top_field_first = !s->interlace_polarity;
279 avcodec_set_dimensions(s->avctx, width, height);
281 s->qscale_table= av_mallocz((s->width+15)/16);
283 s->first_picture = 0;
286 if(s->interlaced && (s->bottom_field == !s->interlace_polarity))
289 /* XXX: not complete test ! */
290 pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
291 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
292 (s->h_count[2] << 12) | (s->v_count[2] << 8) |
293 (s->h_count[3] << 4) | s->v_count[3];
294 av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
295 if(!(pix_fmt_id & 0x10101010))
296 pix_fmt_id-= (pix_fmt_id & 0xF0F0F0F0)>>1;
297 if(!(pix_fmt_id & 0x01010101))
298 pix_fmt_id-= (pix_fmt_id & 0x0F0F0F0F)>>1;
303 s->avctx->pix_fmt = PIX_FMT_RGB32;
305 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
306 assert(s->nb_components==3);
309 s->avctx->pix_fmt = PIX_FMT_GRAY8;
312 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV440P : PIX_FMT_YUVJ440P;
315 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
318 s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
321 av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
325 if(s->nb_components > 1)
326 s->avctx->pix_fmt = PIX_FMT_RGB24;
327 else if(s->bits <= 8)
328 s->avctx->pix_fmt = PIX_FMT_GRAY8;
330 s->avctx->pix_fmt = PIX_FMT_GRAY16;
333 if(s->picture.data[0])
334 s->avctx->release_buffer(s->avctx, &s->picture);
336 s->picture.reference= 0;
337 if(s->avctx->get_buffer(s->avctx, &s->picture) < 0){
338 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
341 s->picture.pict_type= FF_I_TYPE;
342 s->picture.key_frame= 1;
346 s->linesize[i]= s->picture.linesize[i] << s->interlaced;
349 // printf("%d %d %d %d %d %d\n", s->width, s->height, s->linesize[0], s->linesize[1], s->interlaced, s->avctx->height);
351 if (len != (8+(3*nb_components)))
353 av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
356 /* totally blank picture as progressive JPEG will only add details to it */
358 int bw = (width + s->h_max*8-1) / (s->h_max*8);
359 int bh = (height + s->v_max*8-1) / (s->v_max*8);
360 for(i=0; i<s->nb_components; i++) {
361 int size = bw * bh * s->h_count[i] * s->v_count[i];
362 av_freep(&s->blocks[i]);
363 av_freep(&s->last_nnz[i]);
364 s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
365 s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
366 s->block_stride[i] = bw * s->h_count[i];
368 memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
373 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
376 code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
379 av_log(s->avctx, AV_LOG_WARNING, "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n", 0, dc_index,
380 &s->vlcs[0][dc_index]);
385 return get_xbits(&s->gb, code);
390 /* decode block and dequantize */
391 static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
392 int component, int dc_index, int ac_index, int16_t *quant_matrix)
394 int code, i, j, level, val;
397 val = mjpeg_decode_dc(s, dc_index);
399 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
402 val = val * quant_matrix[0] + s->last_dc[component];
403 s->last_dc[component] = val;
407 {OPEN_READER(re, &s->gb)
409 UPDATE_CACHE(re, &s->gb);
410 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
415 i += ((unsigned)code) >> 4;
418 if(code > MIN_CACHE_BITS - 16){
419 UPDATE_CACHE(re, &s->gb)
422 int cache=GET_CACHE(re,&s->gb);
423 int sign=(~cache)>>31;
424 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
427 LAST_SKIP_BITS(re, &s->gb, code)
431 j = s->scantable.permutated[63];
432 block[j] = level * quant_matrix[j];
435 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
438 j = s->scantable.permutated[i];
439 block[j] = level * quant_matrix[j];
442 CLOSE_READER(re, &s->gb)}
447 static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block, int component,
448 int dc_index, int16_t *quant_matrix, int Al)
451 s->dsp.clear_block(block);
452 val = mjpeg_decode_dc(s, dc_index);
454 av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
457 val = (val * quant_matrix[0] << Al) + s->last_dc[component];
458 s->last_dc[component] = val;
463 /* decode block and dequantize - progressive JPEG version */
464 static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
465 int ac_index, int16_t *quant_matrix,
466 int ss, int se, int Al, int *EOBRUN)
468 int code, i, j, level, val, run;
474 {OPEN_READER(re, &s->gb)
476 UPDATE_CACHE(re, &s->gb);
477 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
478 /* Progressive JPEG use AC coeffs from zero and this decoder sets offset 16 by default */
481 i += ((unsigned) code) >> 4;
483 if(code > MIN_CACHE_BITS - 16){
484 UPDATE_CACHE(re, &s->gb)
487 int cache=GET_CACHE(re,&s->gb);
488 int sign=(~cache)>>31;
489 level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
492 LAST_SKIP_BITS(re, &s->gb, code)
496 j = s->scantable.permutated[se];
497 block[j] = level * quant_matrix[j] << Al;
500 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
503 j = s->scantable.permutated[i];
504 block[j] = level * quant_matrix[j] << Al;
506 run = ((unsigned) code) >> 4;
507 if(run == 0xF){// ZRL - skip 15 coefficients
512 UPDATE_CACHE(re, &s->gb);
513 run += (GET_CACHE(re, &s->gb) >> (32 - val)) & (run - 1);
515 LAST_SKIP_BITS(re, &s->gb, val);
521 CLOSE_READER(re, &s->gb)}
527 #define REFINE_BIT(j) {\
528 UPDATE_CACHE(re, &s->gb);\
529 sign = block[j]>>15;\
530 block[j] += SHOW_UBITS(re, &s->gb, 1) * ((quant_matrix[j]^sign)-sign) << Al;\
531 LAST_SKIP_BITS(re, &s->gb, 1);\
539 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);\
544 j = s->scantable.permutated[i];\
551 /* decode block and dequantize - progressive JPEG refinement pass */
552 static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
553 int ac_index, int16_t *quant_matrix,
554 int ss, int se, int Al, int *EOBRUN)
556 int code, i=ss, j, sign, val, run;
557 int last = FFMIN(se, *last_nnz);
559 OPEN_READER(re, &s->gb);
564 UPDATE_CACHE(re, &s->gb);
565 GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
566 /* Progressive JPEG use AC coeffs from zero and this decoder sets offset 16 by default */
569 run = ((unsigned) code) >> 4;
570 UPDATE_CACHE(re, &s->gb);
571 val = SHOW_UBITS(re, &s->gb, 1);
572 LAST_SKIP_BITS(re, &s->gb, 1);
574 j = s->scantable.permutated[i];
576 block[j] = ((quant_matrix[j]^val)-val) << Al;
580 CLOSE_READER(re, &s->gb)
584 run = ((unsigned) code) >> 4;
591 UPDATE_CACHE(re, &s->gb);
592 run += SHOW_UBITS(re, &s->gb, val);
593 LAST_SKIP_BITS(re, &s->gb, val);
606 j = s->scantable.permutated[i];
610 CLOSE_READER(re, &s->gb);
617 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point_transform){
619 uint16_t buffer[32768][4];
620 int left[3], top[3], topleft[3];
621 const int linesize= s->linesize[0];
622 const int mask= (1<<s->bits)-1;
624 if((unsigned)s->mb_width > 32768) //dynamic alloc
628 buffer[0][i]= 1 << (s->bits + point_transform - 1);
630 for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
631 const int modified_predictor= mb_y ? predictor : 1;
632 uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
634 if (s->interlaced && s->bottom_field)
635 ptr += linesize >> 1;
638 top[i]= left[i]= topleft[i]= buffer[0][i];
640 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
641 if (s->restart_interval && !s->restart_count)
642 s->restart_count = s->restart_interval;
648 top[i]= buffer[mb_x][i];
650 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
653 buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
656 if (s->restart_interval && !--s->restart_count) {
657 align_get_bits(&s->gb);
658 skip_bits(&s->gb, 16); /* skip RSTn */
663 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
664 ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);
665 ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
666 ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
668 }else if(s->pegasus_rct){
669 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
670 ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);
671 ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
672 ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
675 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
676 ptr[4*mb_x+0] = buffer[mb_x][0];
677 ptr[4*mb_x+1] = buffer[mb_x][1];
678 ptr[4*mb_x+2] = buffer[mb_x][2];
685 static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
687 const int nb_components=3;
689 for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
690 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
691 if (s->restart_interval && !s->restart_count)
692 s->restart_count = s->restart_interval;
694 if(mb_x==0 || mb_y==0 || s->interlaced){
695 for(i=0;i<nb_components;i++) {
697 int n, h, v, x, y, c, j, linesize;
699 c = s->comp_index[i];
704 linesize= s->linesize[c];
709 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
712 pred= 128 << point_transform;
718 pred= ptr[-linesize];
720 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
724 if (s->interlaced && s->bottom_field)
725 ptr += linesize >> 1;
726 *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
735 for(i=0;i<nb_components;i++) {
737 int n, h, v, x, y, c, j, linesize;
739 c = s->comp_index[i];
744 linesize= s->linesize[c];
749 ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
750 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
751 *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
759 if (s->restart_interval && !--s->restart_count) {
760 align_get_bits(&s->gb);
761 skip_bits(&s->gb, 16); /* skip RSTn */
768 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al){
770 uint8_t* data[MAX_COMPONENTS];
771 int linesize[MAX_COMPONENTS];
773 for(i=0; i < nb_components; i++) {
774 int c = s->comp_index[i];
775 data[c] = s->picture.data[c];
776 linesize[c]=s->linesize[c];
777 s->coefs_finished[c] |= 1;
779 //picture should be flipped upside-down for this codec
780 assert(!(s->avctx->flags & CODEC_FLAG_EMU_EDGE));
781 data[c] += (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
786 for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
787 for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
788 if (s->restart_interval && !s->restart_count)
789 s->restart_count = s->restart_interval;
791 for(i=0;i<nb_components;i++) {
793 int n, h, v, x, y, c, j;
795 c = s->comp_index[i];
802 (((linesize[c] * (v * mb_y + y) * 8) +
803 (h * mb_x + x) * 8) >> s->avctx->lowres);
804 if(s->interlaced && s->bottom_field)
805 ptr += linesize[c] >> 1;
806 if(!s->progressive) {
807 s->dsp.clear_block(s->block);
808 if(decode_block(s, s->block, i,
809 s->dc_index[i], s->ac_index[i],
810 s->quant_matrixes[ s->quant_index[c] ]) < 0) {
811 av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
814 s->dsp.idct_put(ptr, linesize[c], s->block);
816 int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
817 DCTELEM *block = s->blocks[c][block_idx];
819 block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;
820 else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {
821 av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
825 // av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
826 //av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);
834 if (s->restart_interval && !--s->restart_count) {
835 align_get_bits(&s->gb);
836 skip_bits(&s->gb, 16); /* skip RSTn */
837 for (i=0; i<nb_components; i++) /* reset dc */
838 s->last_dc[i] = 1024;
845 static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
848 int c = s->comp_index[0];
849 uint8_t* data = s->picture.data[c];
850 int linesize = s->linesize[c];
852 int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
855 s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
856 last_scan = !~s->coefs_finished[c];
859 if(s->interlaced && s->bottom_field)
860 data += linesize >> 1;
862 for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
863 uint8_t *ptr = data + (mb_y*linesize*8 >> s->avctx->lowres);
864 int block_idx = mb_y * s->block_stride[c];
865 DCTELEM (*block)[64] = &s->blocks[c][block_idx];
866 uint8_t *last_nnz = &s->last_nnz[c][block_idx];
867 for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
870 ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
871 quant_matrix, ss, se, Al, &EOBRUN);
873 ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
874 quant_matrix, ss, se, Al, &EOBRUN);
876 av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
880 s->dsp.idct_put(ptr, linesize, *block);
881 ptr += 8 >> s->avctx->lowres;
888 int ff_mjpeg_decode_sos(MJpegDecodeContext *s)
890 int len, nb_components, i, h, v, predictor, point_transform;
892 const int block_size= s->lossless ? 1 : 8;
895 /* XXX: verify len field validity */
896 len = get_bits(&s->gb, 16);
897 nb_components = get_bits(&s->gb, 8);
898 if (len != 6+2*nb_components)
900 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
903 for(i=0;i<nb_components;i++) {
904 id = get_bits(&s->gb, 8) - 1;
905 av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
906 /* find component index */
907 for(index=0;index<s->nb_components;index++)
908 if (id == s->component_id[index])
910 if (index == s->nb_components)
912 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
916 s->comp_index[i] = index;
918 s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
919 s->h_scount[i] = s->h_count[index];
920 s->v_scount[i] = s->v_count[index];
922 s->dc_index[i] = get_bits(&s->gb, 4);
923 s->ac_index[i] = get_bits(&s->gb, 4);
925 if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
926 s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
928 if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
932 predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
933 ilv= get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
934 prev_shift = get_bits(&s->gb, 4); /* Ah */
935 point_transform= get_bits(&s->gb, 4); /* Al */
937 for(i=0;i<nb_components;i++)
938 s->last_dc[i] = 1024;
940 if (nb_components > 1) {
941 /* interleaved stream */
942 s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
943 s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
944 } else if(!s->ls) { /* skip this for JPEG-LS */
945 h = s->h_max / s->h_scount[0];
946 v = s->v_max / s->v_scount[0];
947 s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
948 s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
954 if(s->avctx->debug & FF_DEBUG_PICT_INFO)
955 av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n", s->lossless ? "lossless" : "sequencial DCT", s->rgb ? "RGB" : "",
956 predictor, point_transform, ilv, s->bits,
957 s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
960 /* mjpeg-b can have padding bytes between sos and image data, skip them */
961 for (i = s->mjpb_skiptosod; i > 0; i--)
962 skip_bits(&s->gb, 8);
965 if(CONFIG_JPEGLS_DECODER && s->ls){
967 // reset_ls_coding_parameters(s, 0);
969 if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
973 if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
976 if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
981 if(s->progressive && predictor) {
982 if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform) < 0)
985 if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform) < 0)
992 av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
996 static int mjpeg_decode_dri(MJpegDecodeContext *s)
998 if (get_bits(&s->gb, 16) != 4)
1000 s->restart_interval = get_bits(&s->gb, 16);
1001 s->restart_count = 0;
1002 av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1007 static int mjpeg_decode_app(MJpegDecodeContext *s)
1011 len = get_bits(&s->gb, 16);
1014 if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1017 id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
1021 if(s->avctx->debug & FF_DEBUG_STARTCODE){
1022 av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1025 /* buggy AVID, it puts EOI only at every 10th frame */
1026 /* also this fourcc is used by non-avid files too, it holds some
1027 informations, but it's always present in AVID creates files */
1028 if (id == AV_RL32("AVI1"))
1035 4bytes field_size_less_padding
1038 // if (s->first_picture)
1039 // printf("mjpeg: workarounding buggy AVID\n");
1040 i = get_bits(&s->gb, 8);
1041 if (i==2) s->bottom_field= 1;
1042 else if(i==1) s->bottom_field= 0;
1044 skip_bits(&s->gb, 8);
1045 skip_bits(&s->gb, 32);
1046 skip_bits(&s->gb, 32);
1049 // if (s->interlace_polarity)
1050 // printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1056 if (id == AV_RL32("JFIF"))
1058 int t_w, t_h, v1, v2;
1059 skip_bits(&s->gb, 8); /* the trailing zero-byte */
1060 v1= get_bits(&s->gb, 8);
1061 v2= get_bits(&s->gb, 8);
1062 skip_bits(&s->gb, 8);
1064 s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1065 s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1067 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1068 av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1070 s->avctx->sample_aspect_ratio.num,
1071 s->avctx->sample_aspect_ratio.den
1074 t_w = get_bits(&s->gb, 8);
1075 t_h = get_bits(&s->gb, 8);
1078 /* skip thumbnail */
1079 if (len-10-(t_w*t_h*3) > 0)
1086 if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
1088 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1089 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1090 skip_bits(&s->gb, 16); /* version */
1091 skip_bits(&s->gb, 16); /* flags0 */
1092 skip_bits(&s->gb, 16); /* flags1 */
1093 skip_bits(&s->gb, 8); /* transform */
1098 if (id == AV_RL32("LJIF")){
1099 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1100 av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
1101 skip_bits(&s->gb, 16); /* version ? */
1102 skip_bits(&s->gb, 16); /* unknwon always 0? */
1103 skip_bits(&s->gb, 16); /* unknwon always 0? */
1104 skip_bits(&s->gb, 16); /* unknwon always 0? */
1105 switch( get_bits(&s->gb, 8)){
1115 av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1122 if ((s->start_code == APP1) && (len > (0x28 - 8)))
1124 id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
1127 if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
1130 skip_bits(&s->gb, 32); /* field size */
1131 skip_bits(&s->gb, 32); /* pad field size */
1132 skip_bits(&s->gb, 32); /* next off */
1133 skip_bits(&s->gb, 32); /* quant off */
1134 skip_bits(&s->gb, 32); /* huff off */
1135 skip_bits(&s->gb, 32); /* image off */
1136 skip_bits(&s->gb, 32); /* scan off */
1137 skip_bits(&s->gb, 32); /* data off */
1139 if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1140 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1145 /* slow but needed for extreme adobe jpegs */
1147 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1149 skip_bits(&s->gb, 8);
1154 static int mjpeg_decode_com(MJpegDecodeContext *s)
1156 int len = get_bits(&s->gb, 16);
1157 if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
1158 char *cbuf = av_malloc(len - 1);
1161 for (i = 0; i < len - 2; i++)
1162 cbuf[i] = get_bits(&s->gb, 8);
1163 if (i > 0 && cbuf[i-1] == '\n')
1168 if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1169 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1171 /* buggy avid, it puts EOI only at every 10th frame */
1172 if (!strcmp(cbuf, "AVID"))
1175 // if (s->first_picture)
1176 // printf("mjpeg: workarounding buggy AVID\n");
1178 else if(!strcmp(cbuf, "CS=ITU601")){
1181 else if(len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)){
1193 static int valid_marker_list[] =
1195 /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1196 /* 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1197 /* 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1198 /* 2 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1199 /* 3 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1200 /* 4 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1201 /* 5 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1202 /* 6 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1203 /* 7 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1204 /* 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1205 /* 9 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1206 /* a */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1207 /* b */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1208 /* c */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1209 /* d */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1210 /* e */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1211 /* f */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1215 /* return the 8 bit start code value and update the search
1216 state. Return -1 if no start code found */
1217 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1219 const uint8_t *buf_ptr;
1226 buf_ptr = *pbuf_ptr;
1227 while (buf_ptr < buf_end) {
1230 if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1240 dprintf(NULL, "find_marker skipped %d bytes\n", skipped);
1241 *pbuf_ptr = buf_ptr;
1245 int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1246 void *data, int *data_size,
1249 const uint8_t *buf = avpkt->data;
1250 int buf_size = avpkt->size;
1251 MJpegDecodeContext *s = avctx->priv_data;
1252 const uint8_t *buf_end, *buf_ptr;
1254 AVFrame *picture = data;
1256 s->got_picture = 0; // picture from previous image can not be reused
1258 buf_end = buf + buf_size;
1259 while (buf_ptr < buf_end) {
1260 /* find start next marker */
1261 start_code = find_marker(&buf_ptr, buf_end);
1264 if (start_code < 0) {
1267 av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
1269 if ((buf_end - buf_ptr) > s->buffer_size)
1272 s->buffer_size = buf_end-buf_ptr;
1273 s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1274 av_log(avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1278 /* unescape buffer of SOS, use special treatment for JPEG-LS */
1279 if (start_code == SOS && !s->ls)
1281 const uint8_t *src = buf_ptr;
1282 uint8_t *dst = s->buffer;
1286 uint8_t x = *(src++);
1289 if (avctx->codec_id != CODEC_ID_THP)
1292 while (src < buf_end && x == 0xff)
1295 if (x >= 0xd0 && x <= 0xd7)
1302 init_get_bits(&s->gb, s->buffer, (dst - s->buffer)*8);
1304 av_log(avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1305 (buf_end - buf_ptr) - (dst - s->buffer));
1307 else if(start_code == SOS && s->ls){
1308 const uint8_t *src = buf_ptr;
1309 uint8_t *dst = s->buffer;
1317 while (src + t < buf_end){
1318 uint8_t x = src[t++];
1320 while((src + t < buf_end) && x == 0xff)
1330 init_put_bits(&pb, dst, t);
1332 /* unescape bitstream */
1334 uint8_t x = src[b++];
1335 put_bits(&pb, 8, x);
1338 put_bits(&pb, 7, x);
1342 flush_put_bits(&pb);
1344 init_get_bits(&s->gb, dst, bit_count);
1347 init_get_bits(&s->gb, buf_ptr, (buf_end - buf_ptr)*8);
1349 s->start_code = start_code;
1350 if(s->avctx->debug & FF_DEBUG_STARTCODE){
1351 av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1354 /* process markers */
1355 if (start_code >= 0xd0 && start_code <= 0xd7) {
1356 av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1358 } else if (start_code >= APP0 && start_code <= APP15) {
1359 mjpeg_decode_app(s);
1361 } else if (start_code == COM){
1362 mjpeg_decode_com(s);
1365 switch(start_code) {
1367 s->restart_interval = 0;
1369 s->restart_count = 0;
1370 /* nothing to do on SOI */
1373 ff_mjpeg_decode_dqt(s);
1376 if(ff_mjpeg_decode_dht(s) < 0){
1377 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1386 if (ff_mjpeg_decode_sof(s) < 0)
1393 if (ff_mjpeg_decode_sof(s) < 0)
1400 if (ff_mjpeg_decode_sof(s) < 0)
1407 if (ff_mjpeg_decode_sof(s) < 0)
1411 if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1416 if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1419 if (!s->got_picture) {
1420 av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
1424 if (s->interlaced) {
1425 s->bottom_field ^= 1;
1426 /* if not bottom field, do not output image yet */
1427 if (s->bottom_field == !s->interlace_polarity)
1430 *picture = s->picture;
1431 *data_size = sizeof(AVFrame);
1434 picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
1435 picture->qstride= 0;
1436 picture->qscale_table= s->qscale_table;
1437 memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1438 if(avctx->debug & FF_DEBUG_QP)
1439 av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1440 picture->quality*= FF_QP2LAMBDA;
1447 if (!s->got_picture) {
1448 av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
1451 ff_mjpeg_decode_sos(s);
1452 /* buggy avid puts EOI every 10-20th frame */
1453 /* if restart period is over process EOI */
1454 if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1458 mjpeg_decode_dri(s);
1470 av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1473 // printf("mjpeg: unsupported marker (%x)\n", start_code);
1478 /* eof process start code */
1479 buf_ptr += (get_bits_count(&s->gb)+7)/8;
1480 av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1481 (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1485 if (s->got_picture) {
1486 av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1489 av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1492 av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
1493 // return buf_end - buf_ptr;
1494 return buf_ptr - buf;
1497 av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1499 MJpegDecodeContext *s = avctx->priv_data;
1502 if (s->picture.data[0])
1503 avctx->release_buffer(avctx, &s->picture);
1506 av_free(s->qscale_table);
1510 free_vlc(&s->vlcs[i][j]);
1512 for(i=0; i<MAX_COMPONENTS; i++) {
1513 av_freep(&s->blocks[i]);
1514 av_freep(&s->last_nnz[i]);
1519 AVCodec mjpeg_decoder = {
1523 sizeof(MJpegDecodeContext),
1524 ff_mjpeg_decode_init,
1526 ff_mjpeg_decode_end,
1527 ff_mjpeg_decode_frame,
1530 .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1533 AVCodec thp_decoder = {
1537 sizeof(MJpegDecodeContext),
1538 ff_mjpeg_decode_init,
1540 ff_mjpeg_decode_end,
1541 ff_mjpeg_decode_frame,
1544 .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),