LCOV - code coverage report
Current view: top level - libavcodec - mjpegdec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 793 1629 48.7 %
Date: 2017-12-18 06:23:41 Functions: 22 31 71.0 %

          Line data    Source code
       1             : /*
       2             :  * MJPEG decoder
       3             :  * Copyright (c) 2000, 2001 Fabrice Bellard
       4             :  * Copyright (c) 2003 Alex Beregszaszi
       5             :  * Copyright (c) 2003-2004 Michael Niedermayer
       6             :  *
       7             :  * Support for external huffman table, various fixes (AVID workaround),
       8             :  * aspecting, new decode_frame mechanism and apple mjpeg-b support
       9             :  *                                  by Alex Beregszaszi
      10             :  *
      11             :  * This file is part of FFmpeg.
      12             :  *
      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.
      17             :  *
      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.
      22             :  *
      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
      26             :  */
      27             : 
      28             : /**
      29             :  * @file
      30             :  * MJPEG decoder.
      31             :  */
      32             : 
      33             : #include "libavutil/imgutils.h"
      34             : #include "libavutil/avassert.h"
      35             : #include "libavutil/opt.h"
      36             : #include "avcodec.h"
      37             : #include "blockdsp.h"
      38             : #include "copy_block.h"
      39             : #include "idctdsp.h"
      40             : #include "internal.h"
      41             : #include "jpegtables.h"
      42             : #include "mjpeg.h"
      43             : #include "mjpegdec.h"
      44             : #include "jpeglsdec.h"
      45             : #include "put_bits.h"
      46             : #include "tiff.h"
      47             : #include "exif.h"
      48             : #include "bytestream.h"
      49             : 
      50             : 
      51       14415 : static int build_vlc(VLC *vlc, const uint8_t *bits_table,
      52             :                      const uint8_t *val_table, int nb_codes,
      53             :                      int use_static, int is_ac)
      54             : {
      55       14415 :     uint8_t huff_size[256] = { 0 };
      56             :     uint16_t huff_code[256];
      57             :     uint16_t huff_sym[256];
      58             :     int i;
      59             : 
      60       14415 :     av_assert0(nb_codes <= 256);
      61             : 
      62       14415 :     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
      63             : 
      64     3704655 :     for (i = 0; i < 256; i++)
      65     3690240 :         huff_sym[i] = i + 16 * is_ac;
      66             : 
      67       14415 :     if (is_ac)
      68        4805 :         huff_sym[0] = 16 * 256;
      69             : 
      70       14415 :     return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
      71             :                               huff_code, 2, 2, huff_sym, 2, 2, use_static);
      72             : }
      73             : 
      74         129 : static int build_basic_mjpeg_vlc(MJpegDecodeContext *s)
      75             : {
      76             :     int ret;
      77             : 
      78         129 :     if ((ret = build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
      79             :                          avpriv_mjpeg_val_dc, 12, 0, 0)) < 0)
      80           0 :         return ret;
      81             : 
      82         129 :     if ((ret = build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
      83             :                          avpriv_mjpeg_val_dc, 12, 0, 0)) < 0)
      84           0 :         return ret;
      85             : 
      86         129 :     if ((ret = build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
      87             :                          avpriv_mjpeg_val_ac_luminance, 251, 0, 1)) < 0)
      88           0 :         return ret;
      89             : 
      90         129 :     if ((ret = build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
      91             :                          avpriv_mjpeg_val_ac_chrominance, 251, 0, 1)) < 0)
      92           0 :         return ret;
      93             : 
      94         129 :     if ((ret = build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
      95             :                          avpriv_mjpeg_val_ac_luminance, 251, 0, 0)) < 0)
      96           0 :         return ret;
      97             : 
      98         129 :     if ((ret = build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
      99             :                          avpriv_mjpeg_val_ac_chrominance, 251, 0, 0)) < 0)
     100           0 :         return ret;
     101             : 
     102             : 
     103         129 :     return 0;
     104             : }
     105             : 
     106           0 : static void parse_avid(MJpegDecodeContext *s, uint8_t *buf, int len)
     107             : {
     108           0 :     s->buggy_avid = 1;
     109           0 :     if (len > 14 && buf[12] == 1) /* 1 - NTSC */
     110           0 :         s->interlace_polarity = 1;
     111           0 :     if (len > 14 && buf[12] == 2) /* 2 - PAL */
     112           0 :         s->interlace_polarity = 0;
     113           0 :     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
     114           0 :         av_log(s->avctx, AV_LOG_INFO, "AVID: len:%d %d\n", len, len > 14 ? buf[12] : -1);
     115           0 : }
     116             : 
     117         204 : static void init_idct(AVCodecContext *avctx)
     118             : {
     119         204 :     MJpegDecodeContext *s = avctx->priv_data;
     120             : 
     121         204 :     ff_idctdsp_init(&s->idsp, avctx);
     122         204 :     ff_init_scantable(s->idsp.idct_permutation, &s->scantable,
     123             :                       ff_zigzag_direct);
     124         204 : }
     125             : 
     126         129 : av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
     127             : {
     128         129 :     MJpegDecodeContext *s = avctx->priv_data;
     129             :     int ret;
     130             : 
     131         129 :     if (!s->picture_ptr) {
     132         127 :         s->picture = av_frame_alloc();
     133         127 :         if (!s->picture)
     134           0 :             return AVERROR(ENOMEM);
     135         127 :         s->picture_ptr = s->picture;
     136             :     }
     137             : 
     138         129 :     s->avctx = avctx;
     139         129 :     ff_blockdsp_init(&s->bdsp, avctx);
     140         129 :     ff_hpeldsp_init(&s->hdsp, avctx->flags);
     141         129 :     init_idct(avctx);
     142         129 :     s->buffer_size   = 0;
     143         129 :     s->buffer        = NULL;
     144         129 :     s->start_code    = -1;
     145         129 :     s->first_picture = 1;
     146         129 :     s->got_picture   = 0;
     147         129 :     s->org_height    = avctx->coded_height;
     148         129 :     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
     149         129 :     avctx->colorspace = AVCOL_SPC_BT470BG;
     150             : 
     151         129 :     if ((ret = build_basic_mjpeg_vlc(s)) < 0)
     152           0 :         return ret;
     153             : 
     154         129 :     if (s->extern_huff) {
     155           0 :         av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
     156           0 :         if ((ret = init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8)) < 0)
     157           0 :             return ret;
     158           0 :         if (ff_mjpeg_decode_dht(s)) {
     159           0 :             av_log(avctx, AV_LOG_ERROR,
     160             :                    "error using external huffman table, switching back to internal\n");
     161           0 :             build_basic_mjpeg_vlc(s);
     162             :         }
     163             :     }
     164         129 :     if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
     165           0 :         s->interlace_polarity = 1;           /* bottom field first */
     166           0 :         av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
     167         129 :     } else if (avctx->field_order == AV_FIELD_UNKNOWN) {
     168         127 :         if (avctx->codec_tag == AV_RL32("MJPG"))
     169          49 :             s->interlace_polarity = 1;
     170             :     }
     171             : 
     172         129 :     if (   avctx->extradata_size > 8
     173           0 :         && AV_RL32(avctx->extradata) == 0x2C
     174           0 :         && AV_RL32(avctx->extradata+4) == 0x18) {
     175           0 :         parse_avid(s, avctx->extradata, avctx->extradata_size);
     176             :     }
     177             : 
     178         129 :     if (avctx->codec->id == AV_CODEC_ID_AMV)
     179          11 :         s->flipped = 1;
     180             : 
     181         129 :     return 0;
     182             : }
     183             : 
     184             : 
     185             : /* quantize tables */
     186        2504 : int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
     187             : {
     188             :     int len, index, i;
     189             : 
     190        2504 :     len = get_bits(&s->gb, 16) - 2;
     191             : 
     192        2504 :     if (8*len > get_bits_left(&s->gb)) {
     193           0 :         av_log(s->avctx, AV_LOG_ERROR, "dqt: len %d is too large\n", len);
     194           0 :         return AVERROR_INVALIDDATA;
     195             :     }
     196             : 
     197        7988 :     while (len >= 65) {
     198        2980 :         int pr = get_bits(&s->gb, 4);
     199        2980 :         if (pr > 1) {
     200           0 :             av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
     201           0 :             return AVERROR_INVALIDDATA;
     202             :         }
     203        2980 :         index = get_bits(&s->gb, 4);
     204        2980 :         if (index >= 4)
     205           0 :             return -1;
     206        2980 :         av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
     207             :         /* read quant table */
     208      193700 :         for (i = 0; i < 64; i++) {
     209      190720 :             s->quant_matrixes[index][i] = get_bits(&s->gb, pr ? 16 : 8);
     210      190720 :             if (s->quant_matrixes[index][i] == 0) {
     211           0 :                 av_log(s->avctx, AV_LOG_ERROR, "dqt: 0 quant value\n");
     212           0 :                 return AVERROR_INVALIDDATA;
     213             :             }
     214             :         }
     215             : 
     216             :         // XXX FIXME fine-tune, and perhaps add dc too
     217        8940 :         s->qscale[index] = FFMAX(s->quant_matrixes[index][1],
     218        5960 :                                  s->quant_matrixes[index][8]) >> 1;
     219        2980 :         av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
     220             :                index, s->qscale[index]);
     221        2980 :         len -= 1 + 64 * (1+pr);
     222             :     }
     223        2504 :     return 0;
     224             : }
     225             : 
     226             : /* decode huffman tables and build VLC decoders */
     227        2538 : int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
     228             : {
     229             :     int len, index, i, class, n, v, code_max;
     230             :     uint8_t bits_table[17];
     231             :     uint8_t val_table[256];
     232        2538 :     int ret = 0;
     233             : 
     234        2538 :     len = get_bits(&s->gb, 16) - 2;
     235             : 
     236        2538 :     if (8*len > get_bits_left(&s->gb)) {
     237           0 :         av_log(s->avctx, AV_LOG_ERROR, "dht: len %d is too large\n", len);
     238           0 :         return AVERROR_INVALIDDATA;
     239             :     }
     240             : 
     241       14170 :     while (len > 0) {
     242        9094 :         if (len < 17)
     243           0 :             return AVERROR_INVALIDDATA;
     244        9094 :         class = get_bits(&s->gb, 4);
     245        9094 :         if (class >= 2)
     246           0 :             return AVERROR_INVALIDDATA;
     247        9094 :         index = get_bits(&s->gb, 4);
     248        9094 :         if (index >= 4)
     249           0 :             return AVERROR_INVALIDDATA;
     250        9094 :         n = 0;
     251      154598 :         for (i = 1; i <= 16; i++) {
     252      145504 :             bits_table[i] = get_bits(&s->gb, 8);
     253      145504 :             n += bits_table[i];
     254             :         }
     255        9094 :         len -= 17;
     256        9094 :         if (len < n || n > 256)
     257           0 :             return AVERROR_INVALIDDATA;
     258             : 
     259        9094 :         code_max = 0;
     260      454786 :         for (i = 0; i < n; i++) {
     261      445692 :             v = get_bits(&s->gb, 8);
     262      445692 :             if (v > code_max)
     263      111627 :                 code_max = v;
     264      445692 :             val_table[i] = v;
     265             :         }
     266        9094 :         len -= n;
     267             : 
     268             :         /* build VLC and flush previous vlc if present */
     269        9094 :         ff_free_vlc(&s->vlcs[class][index]);
     270        9094 :         av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
     271             :                class, index, code_max + 1);
     272        9094 :         if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
     273             :                              code_max + 1, 0, class > 0)) < 0)
     274           0 :             return ret;
     275             : 
     276        9094 :         if (class > 0) {
     277        4547 :             ff_free_vlc(&s->vlcs[2][index]);
     278        4547 :             if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
     279             :                                  code_max + 1, 0, 0)) < 0)
     280           0 :                 return ret;
     281             :         }
     282             :     }
     283        2538 :     return 0;
     284             : }
     285             : 
     286        2534 : int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
     287             : {
     288             :     int len, nb_components, i, width, height, bits, ret;
     289             :     unsigned pix_fmt_id;
     290        2534 :     int h_count[MAX_COMPONENTS] = { 0 };
     291        2534 :     int v_count[MAX_COMPONENTS] = { 0 };
     292             : 
     293        2534 :     s->cur_scan = 0;
     294        2534 :     memset(s->upscale_h, 0, sizeof(s->upscale_h));
     295        2534 :     memset(s->upscale_v, 0, sizeof(s->upscale_v));
     296             : 
     297             :     /* XXX: verify len field validity */
     298        2534 :     len     = get_bits(&s->gb, 16);
     299        2534 :     bits    = get_bits(&s->gb, 8);
     300             : 
     301        2534 :     if (bits > 16 || bits < 1) {
     302           0 :         av_log(s->avctx, AV_LOG_ERROR, "bits %d is invalid\n", bits);
     303           0 :         return AVERROR_INVALIDDATA;
     304             :     }
     305             : 
     306        2534 :     if (s->avctx->bits_per_raw_sample != bits) {
     307          75 :         av_log(s->avctx, s->avctx->bits_per_raw_sample > 0 ? AV_LOG_INFO : AV_LOG_DEBUG, "Changing bps from %d to %d\n", s->avctx->bits_per_raw_sample, bits);
     308          75 :         s->avctx->bits_per_raw_sample = bits;
     309          75 :         init_idct(s->avctx);
     310             :     }
     311        2534 :     if (s->pegasus_rct)
     312           0 :         bits = 9;
     313        2534 :     if (bits == 9 && !s->pegasus_rct)
     314           0 :         s->rct  = 1;    // FIXME ugly
     315             : 
     316        2534 :     if(s->lossless && s->avctx->lowres){
     317           0 :         av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
     318           0 :         return -1;
     319             :     }
     320             : 
     321        2534 :     height = get_bits(&s->gb, 16);
     322        2534 :     width  = get_bits(&s->gb, 16);
     323             : 
     324             :     // HACK for odd_height.mov
     325        2534 :     if (s->interlaced && s->width == width && s->height == height + 1)
     326           0 :         height= s->height;
     327             : 
     328        2534 :     av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
     329        2534 :     if (av_image_check_size(width, height, 0, s->avctx) < 0)
     330           0 :         return AVERROR_INVALIDDATA;
     331             : 
     332        2534 :     nb_components = get_bits(&s->gb, 8);
     333        2534 :     if (nb_components <= 0 ||
     334             :         nb_components > MAX_COMPONENTS)
     335           0 :         return -1;
     336        2534 :     if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
     337          11 :         if (nb_components != s->nb_components) {
     338           0 :             av_log(s->avctx, AV_LOG_ERROR,
     339             :                    "nb_components changing in interlaced picture\n");
     340           0 :             return AVERROR_INVALIDDATA;
     341             :         }
     342             :     }
     343        2534 :     if (s->ls && !(bits <= 8 || nb_components == 1)) {
     344           0 :         avpriv_report_missing_feature(s->avctx,
     345             :                                       "JPEG-LS that is not <= 8 "
     346             :                                       "bits/component or 16-bit gray");
     347           0 :         return AVERROR_PATCHWELCOME;
     348             :     }
     349        2534 :     s->nb_components = nb_components;
     350        2534 :     s->h_max         = 1;
     351        2534 :     s->v_max         = 1;
     352       10132 :     for (i = 0; i < nb_components; i++) {
     353             :         /* component id */
     354        7598 :         s->component_id[i] = get_bits(&s->gb, 8) - 1;
     355        7598 :         h_count[i]         = get_bits(&s->gb, 4);
     356        7598 :         v_count[i]         = get_bits(&s->gb, 4);
     357             :         /* compute hmax and vmax (only used in interleaved case) */
     358        7598 :         if (h_count[i] > s->h_max)
     359        2120 :             s->h_max = h_count[i];
     360        7598 :         if (v_count[i] > s->v_max)
     361        2298 :             s->v_max = v_count[i];
     362        7598 :         s->quant_index[i] = get_bits(&s->gb, 8);
     363        7598 :         if (s->quant_index[i] >= 4) {
     364           0 :             av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
     365           0 :             return AVERROR_INVALIDDATA;
     366             :         }
     367        7598 :         if (!h_count[i] || !v_count[i]) {
     368           0 :             av_log(s->avctx, AV_LOG_ERROR,
     369             :                    "Invalid sampling factor in component %d %d:%d\n",
     370             :                    i, h_count[i], v_count[i]);
     371           0 :             return AVERROR_INVALIDDATA;
     372             :         }
     373             : 
     374        7598 :         av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
     375             :                i, h_count[i], v_count[i],
     376             :                s->component_id[i], s->quant_index[i]);
     377             :     }
     378        2534 :     if (   nb_components == 4
     379           0 :         && s->component_id[0] == 'C' - 1
     380           0 :         && s->component_id[1] == 'M' - 1
     381           0 :         && s->component_id[2] == 'Y' - 1
     382           0 :         && s->component_id[3] == 'K' - 1)
     383           0 :         s->adobe_transform = 0;
     384             : 
     385        2534 :     if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
     386           0 :         avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
     387           0 :         return AVERROR_PATCHWELCOME;
     388             :     }
     389             : 
     390             : 
     391             :     /* if different size, realloc/alloc picture */
     392        4741 :     if (width != s->width || height != s->height || bits != s->bits ||
     393        4414 :         memcmp(s->h_count, h_count, sizeof(h_count))                ||
     394        2207 :         memcmp(s->v_count, v_count, sizeof(v_count))) {
     395             : 
     396         327 :         s->width      = width;
     397         327 :         s->height     = height;
     398         327 :         s->bits       = bits;
     399         327 :         memcpy(s->h_count, h_count, sizeof(h_count));
     400         327 :         memcpy(s->v_count, v_count, sizeof(v_count));
     401         327 :         s->interlaced = 0;
     402         327 :         s->got_picture = 0;
     403             : 
     404             :         /* test interlaced mode */
     405         451 :         if (s->first_picture   &&
     406         248 :             (s->multiscope != 2 || s->avctx->time_base.den >= 25 * s->avctx->time_base.num) &&
     407         225 :             s->org_height != 0 &&
     408         101 :             s->height < ((s->org_height * 3) / 4)) {
     409           2 :             s->interlaced                    = 1;
     410           2 :             s->bottom_field                  = s->interlace_polarity;
     411           2 :             s->picture_ptr->interlaced_frame = 1;
     412           2 :             s->picture_ptr->top_field_first  = !s->interlace_polarity;
     413           2 :             height *= 2;
     414             :         }
     415             : 
     416         327 :         ret = ff_set_dimensions(s->avctx, width, height);
     417         327 :         if (ret < 0)
     418           0 :             return ret;
     419             : 
     420         327 :         s->first_picture = 0;
     421             :     }
     422             : 
     423        2534 :     if (s->got_picture && s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
     424          22 :         if (s->progressive) {
     425           0 :             avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
     426           0 :             return AVERROR_INVALIDDATA;
     427             :         }
     428             :     } else{
     429        2523 :         if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
     430         205 :             s->rgb = 1;
     431        2318 :         else if (!s->lossless)
     432        2113 :             s->rgb = 0;
     433             :     /* XXX: not complete test ! */
     434        7569 :     pix_fmt_id = ((unsigned)s->h_count[0] << 28) | (s->v_count[0] << 24) |
     435        7569 :                  (s->h_count[1] << 20) | (s->v_count[1] << 16) |
     436        7569 :                  (s->h_count[2] << 12) | (s->v_count[2] <<  8) |
     437        5046 :                  (s->h_count[3] <<  4) |  s->v_count[3];
     438        2523 :     av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
     439             :     /* NOTE we do not allocate pictures large enough for the possible
     440             :      * padding of h/v_count being 4 */
     441        2523 :     if (!(pix_fmt_id & 0xD0D0D0D0))
     442           0 :         pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
     443        2523 :     if (!(pix_fmt_id & 0x0D0D0D0D))
     444         408 :         pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
     445             : 
     446       22707 :     for (i = 0; i < 8; i++) {
     447       20184 :         int j = 6 + (i&1) - (i&6);
     448       20184 :         int is = (pix_fmt_id >> (4*i)) & 0xF;
     449       20184 :         int js = (pix_fmt_id >> (4*j)) & 0xF;
     450             : 
     451       20184 :         if (is == 1 && js != 2 && (i < 2 || i > 5))
     452        1047 :             js = (pix_fmt_id >> ( 8 + 4*(i&1))) & 0xF;
     453       20184 :         if (is == 1 && js != 2 && (i < 2 || i > 5))
     454        1047 :             js = (pix_fmt_id >> (16 + 4*(i&1))) & 0xF;
     455             : 
     456       20184 :         if (is == 1 && js == 2) {
     457           0 :             if (i & 1) s->upscale_h[j/2] = 1;
     458           0 :             else       s->upscale_v[j/2] = 1;
     459             :         }
     460             :     }
     461             : 
     462        2523 :     switch (pix_fmt_id) {
     463         412 :     case 0x11111100:
     464         412 :         if (s->rgb)
     465         205 :             s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_BGR48;
     466             :         else {
     467         207 :             if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
     468           0 :                 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_GBRP : AV_PIX_FMT_GBRP16;
     469             :             } else {
     470         207 :                 if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
     471           0 :                 else              s->avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
     472         207 :             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     473             :             }
     474             :         }
     475         412 :         av_assert0(s->nb_components == 3);
     476         412 :         break;
     477           0 :     case 0x11111111:
     478           0 :         if (s->rgb)
     479           0 :             s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA64;
     480             :         else {
     481           0 :             if (s->adobe_transform == 0 && s->bits <= 8) {
     482           0 :                 s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
     483             :             } else {
     484           0 :                 s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_YUVA444P : AV_PIX_FMT_YUVA444P16;
     485           0 :                 s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     486             :             }
     487             :         }
     488           0 :         av_assert0(s->nb_components == 4);
     489           0 :         break;
     490           0 :     case 0x22111122:
     491             :     case 0x22111111:
     492           0 :         if (s->adobe_transform == 0 && s->bits <= 8) {
     493           0 :             s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
     494           0 :             s->upscale_v[1] = s->upscale_v[2] = 1;
     495           0 :             s->upscale_h[1] = s->upscale_h[2] = 1;
     496           0 :         } else if (s->adobe_transform == 2 && s->bits <= 8) {
     497           0 :             s->avctx->pix_fmt = AV_PIX_FMT_YUVA444P;
     498           0 :             s->upscale_v[1] = s->upscale_v[2] = 1;
     499           0 :             s->upscale_h[1] = s->upscale_h[2] = 1;
     500           0 :             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     501             :         } else {
     502           0 :             if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
     503           0 :             else              s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P16;
     504           0 :             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     505             :         }
     506           0 :         av_assert0(s->nb_components == 4);
     507           0 :         break;
     508           0 :     case 0x12121100:
     509             :     case 0x22122100:
     510             :     case 0x21211100:
     511             :     case 0x22211200:
     512           0 :         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
     513             :         else
     514           0 :             goto unk_pixfmt;
     515           0 :         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     516           0 :         break;
     517           0 :     case 0x22221100:
     518             :     case 0x22112200:
     519             :     case 0x11222200:
     520           0 :         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
     521             :         else
     522           0 :             goto unk_pixfmt;
     523           0 :         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     524           0 :         break;
     525           2 :     case 0x11000000:
     526             :     case 0x13000000:
     527             :     case 0x14000000:
     528             :     case 0x31000000:
     529             :     case 0x33000000:
     530             :     case 0x34000000:
     531             :     case 0x41000000:
     532             :     case 0x43000000:
     533             :     case 0x44000000:
     534           2 :         if(s->bits <= 8)
     535           0 :             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
     536             :         else
     537           2 :             s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
     538           2 :         break;
     539           0 :     case 0x12111100:
     540             :     case 0x14121200:
     541             :     case 0x14111100:
     542             :     case 0x22211100:
     543             :     case 0x22112100:
     544           0 :         if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
     545           0 :             if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
     546             :             else
     547           0 :                 goto unk_pixfmt;
     548           0 :             s->upscale_v[0] = s->upscale_v[1] = 1;
     549             :         } else {
     550           0 :             if (pix_fmt_id == 0x14111100)
     551           0 :                 s->upscale_v[1] = s->upscale_v[2] = 1;
     552           0 :             if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
     553             :             else
     554           0 :                 goto unk_pixfmt;
     555           0 :             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     556             :         }
     557           0 :         break;
     558         219 :     case 0x21111100:
     559         219 :         if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
     560           0 :             if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
     561             :             else
     562           0 :                 goto unk_pixfmt;
     563           0 :             s->upscale_h[0] = s->upscale_h[1] = 1;
     564             :         } else {
     565         219 :             if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
     566           0 :             else              s->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
     567         219 :             s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     568             :         }
     569         219 :         break;
     570           0 :     case 0x31111100:
     571           0 :         if (s->bits > 8)
     572           0 :             goto unk_pixfmt;
     573           0 :         s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
     574           0 :         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     575           0 :         s->upscale_h[1] = s->upscale_h[2] = 2;
     576           0 :         break;
     577           0 :     case 0x22121100:
     578             :     case 0x22111200:
     579           0 :         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
     580             :         else
     581           0 :             goto unk_pixfmt;
     582           0 :         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     583           0 :         break;
     584        1890 :     case 0x22111100:
     585             :     case 0x42111100:
     586             :     case 0x24111100:
     587        1890 :         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
     588           0 :         else              s->avctx->pix_fmt = AV_PIX_FMT_YUV420P16;
     589        1890 :         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     590        1890 :         if (pix_fmt_id == 0x42111100) {
     591           0 :             if (s->bits > 8)
     592           0 :                 goto unk_pixfmt;
     593           0 :             s->upscale_h[1] = s->upscale_h[2] = 1;
     594        1890 :         } else if (pix_fmt_id == 0x24111100) {
     595           0 :             if (s->bits > 8)
     596           0 :                 goto unk_pixfmt;
     597           0 :             s->upscale_v[1] = s->upscale_v[2] = 1;
     598             :         }
     599        1890 :         break;
     600           0 :     case 0x41111100:
     601           0 :         if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
     602             :         else
     603           0 :             goto unk_pixfmt;
     604           0 :         s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
     605           0 :         break;
     606             :     default:
     607           0 : unk_pixfmt:
     608           0 :         avpriv_report_missing_feature(s->avctx, "Pixel format 0x%x bits:%d", pix_fmt_id, s->bits);
     609           0 :         memset(s->upscale_h, 0, sizeof(s->upscale_h));
     610           0 :         memset(s->upscale_v, 0, sizeof(s->upscale_v));
     611           0 :         return AVERROR_PATCHWELCOME;
     612             :     }
     613        2523 :     if ((AV_RB32(s->upscale_h) || AV_RB32(s->upscale_v)) && s->avctx->lowres) {
     614           0 :         avpriv_report_missing_feature(s->avctx, "Lowres for weird subsampling");
     615           0 :         return AVERROR_PATCHWELCOME;
     616             :     }
     617        2523 :     if (s->ls) {
     618         205 :         memset(s->upscale_h, 0, sizeof(s->upscale_h));
     619         205 :         memset(s->upscale_v, 0, sizeof(s->upscale_v));
     620         205 :         if (s->nb_components == 3) {
     621         205 :             s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
     622           0 :         } else if (s->nb_components != 1) {
     623           0 :             av_log(s->avctx, AV_LOG_ERROR, "Unsupported number of components %d\n", s->nb_components);
     624           0 :             return AVERROR_PATCHWELCOME;
     625           0 :         } else if (s->palette_index && s->bits <= 8)
     626           0 :             s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
     627           0 :         else if (s->bits <= 8)
     628           0 :             s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
     629             :         else
     630           0 :             s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
     631             :     }
     632             : 
     633        2523 :     s->pix_desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
     634        2523 :     if (!s->pix_desc) {
     635           0 :         av_log(s->avctx, AV_LOG_ERROR, "Could not get a pixel format descriptor.\n");
     636           0 :         return AVERROR_BUG;
     637             :     }
     638             : 
     639        2523 :     if (s->avctx->skip_frame == AVDISCARD_ALL) {
     640          55 :         s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
     641          55 :         s->picture_ptr->key_frame = 1;
     642          55 :         s->got_picture            = 1;
     643          55 :         return 0;
     644             :     }
     645             : 
     646        2468 :     av_frame_unref(s->picture_ptr);
     647        2468 :     if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0)
     648           0 :         return -1;
     649        2468 :     s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
     650        2468 :     s->picture_ptr->key_frame = 1;
     651        2468 :     s->got_picture            = 1;
     652             : 
     653       12340 :     for (i = 0; i < 4; i++)
     654        9872 :         s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
     655             : 
     656             :     ff_dlog(s->avctx, "%d %d %d %d %d %d\n",
     657             :             s->width, s->height, s->linesize[0], s->linesize[1],
     658             :             s->interlaced, s->avctx->height);
     659             : 
     660        2468 :     if (len != (8 + (3 * nb_components)))
     661           0 :         av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
     662             :     }
     663             : 
     664        4958 :     if ((s->rgb && !s->lossless && !s->ls) ||
     665        4753 :         (!s->rgb && s->ls && s->nb_components > 1)) {
     666           0 :         av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
     667           0 :         return AVERROR_PATCHWELCOME;
     668             :     }
     669             : 
     670             :     /* totally blank picture as progressive JPEG will only add details to it */
     671        2479 :     if (s->progressive) {
     672           0 :         int bw = (width  + s->h_max * 8 - 1) / (s->h_max * 8);
     673           0 :         int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
     674           0 :         for (i = 0; i < s->nb_components; i++) {
     675           0 :             int size = bw * bh * s->h_count[i] * s->v_count[i];
     676           0 :             av_freep(&s->blocks[i]);
     677           0 :             av_freep(&s->last_nnz[i]);
     678           0 :             s->blocks[i]       = av_mallocz_array(size, sizeof(**s->blocks));
     679           0 :             s->last_nnz[i]     = av_mallocz_array(size, sizeof(**s->last_nnz));
     680           0 :             if (!s->blocks[i] || !s->last_nnz[i])
     681           0 :                 return AVERROR(ENOMEM);
     682           0 :             s->block_stride[i] = bw * s->h_count[i];
     683             :         }
     684           0 :         memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
     685             :     }
     686        2479 :     return 0;
     687             : }
     688             : 
     689    26743556 : static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
     690             : {
     691             :     int code;
     692    26743556 :     code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
     693    26743556 :     if (code < 0 || code > 16) {
     694           0 :         av_log(s->avctx, AV_LOG_WARNING,
     695             :                "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
     696             :                0, dc_index, &s->vlcs[0][dc_index]);
     697           0 :         return 0xfffff;
     698             :     }
     699             : 
     700    26743556 :     if (code)
     701    23729299 :         return get_xbits(&s->gb, code);
     702             :     else
     703     3014257 :         return 0;
     704             : }
     705             : 
     706             : /* decode block and dequantize */
     707     3847256 : static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
     708             :                         int dc_index, int ac_index, uint16_t *quant_matrix)
     709             : {
     710             :     int code, i, j, level, val;
     711             : 
     712             :     /* DC coef */
     713     3847256 :     val = mjpeg_decode_dc(s, dc_index);
     714     3847256 :     if (val == 0xfffff) {
     715           0 :         av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
     716           0 :         return AVERROR_INVALIDDATA;
     717             :     }
     718     3847256 :     val = val * quant_matrix[0] + s->last_dc[component];
     719     3847256 :     val = av_clip_int16(val);
     720     3847256 :     s->last_dc[component] = val;
     721     3847256 :     block[0] = val;
     722             :     /* AC coefs */
     723     3847256 :     i = 0;
     724     3847256 :     {OPEN_READER(re, &s->gb);
     725             :     do {
     726    35366737 :         UPDATE_CACHE(re, &s->gb);
     727    35366737 :         GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
     728             : 
     729    35366737 :         i += ((unsigned)code) >> 4;
     730    35366737 :             code &= 0xf;
     731    35366737 :         if (code) {
     732    31560657 :             if (code > MIN_CACHE_BITS - 16)
     733         240 :                 UPDATE_CACHE(re, &s->gb);
     734             : 
     735             :             {
     736    31560657 :                 int cache = GET_CACHE(re, &s->gb);
     737    31560657 :                 int sign  = (~cache) >> 31;
     738    31560657 :                 level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
     739             :             }
     740             : 
     741    31560657 :             LAST_SKIP_BITS(re, &s->gb, code);
     742             : 
     743    31560657 :             if (i > 63) {
     744           0 :                 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
     745           0 :                 return AVERROR_INVALIDDATA;
     746             :             }
     747    31560657 :             j        = s->scantable.permutated[i];
     748    31560657 :             block[j] = level * quant_matrix[i];
     749             :         }
     750    35366737 :     } while (i < 63);
     751     3847256 :     CLOSE_READER(re, &s->gb);}
     752             : 
     753     3847256 :     return 0;
     754             : }
     755             : 
     756           0 : static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
     757             :                                  int component, int dc_index,
     758             :                                  uint16_t *quant_matrix, int Al)
     759             : {
     760             :     unsigned val;
     761           0 :     s->bdsp.clear_block(block);
     762           0 :     val = mjpeg_decode_dc(s, dc_index);
     763           0 :     if (val == 0xfffff) {
     764           0 :         av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
     765           0 :         return AVERROR_INVALIDDATA;
     766             :     }
     767           0 :     val = (val * (quant_matrix[0] << Al)) + s->last_dc[component];
     768           0 :     s->last_dc[component] = val;
     769           0 :     block[0] = val;
     770           0 :     return 0;
     771             : }
     772             : 
     773             : /* decode block and dequantize - progressive JPEG version */
     774           0 : static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
     775             :                                     uint8_t *last_nnz, int ac_index,
     776             :                                     uint16_t *quant_matrix,
     777             :                                     int ss, int se, int Al, int *EOBRUN)
     778             : {
     779             :     int code, i, j, val, run;
     780             :     unsigned level;
     781             : 
     782           0 :     if (*EOBRUN) {
     783           0 :         (*EOBRUN)--;
     784           0 :         return 0;
     785             :     }
     786             : 
     787             :     {
     788           0 :         OPEN_READER(re, &s->gb);
     789           0 :         for (i = ss; ; i++) {
     790           0 :             UPDATE_CACHE(re, &s->gb);
     791           0 :             GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
     792             : 
     793           0 :             run = ((unsigned) code) >> 4;
     794           0 :             code &= 0xF;
     795           0 :             if (code) {
     796           0 :                 i += run;
     797           0 :                 if (code > MIN_CACHE_BITS - 16)
     798           0 :                     UPDATE_CACHE(re, &s->gb);
     799             : 
     800             :                 {
     801           0 :                     int cache = GET_CACHE(re, &s->gb);
     802           0 :                     int sign  = (~cache) >> 31;
     803           0 :                     level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
     804             :                 }
     805             : 
     806           0 :                 LAST_SKIP_BITS(re, &s->gb, code);
     807             : 
     808           0 :                 if (i >= se) {
     809           0 :                     if (i == se) {
     810           0 :                         j = s->scantable.permutated[se];
     811           0 :                         block[j] = level * (quant_matrix[se] << Al);
     812           0 :                         break;
     813             :                     }
     814           0 :                     av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
     815           0 :                     return AVERROR_INVALIDDATA;
     816             :                 }
     817           0 :                 j = s->scantable.permutated[i];
     818           0 :                 block[j] = level * (quant_matrix[i] << Al);
     819             :             } else {
     820           0 :                 if (run == 0xF) {// ZRL - skip 15 coefficients
     821           0 :                     i += 15;
     822           0 :                     if (i >= se) {
     823           0 :                         av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
     824           0 :                         return AVERROR_INVALIDDATA;
     825             :                     }
     826             :                 } else {
     827           0 :                     val = (1 << run);
     828           0 :                     if (run) {
     829           0 :                         UPDATE_CACHE(re, &s->gb);
     830           0 :                         val += NEG_USR32(GET_CACHE(re, &s->gb), run);
     831           0 :                         LAST_SKIP_BITS(re, &s->gb, run);
     832             :                     }
     833           0 :                     *EOBRUN = val - 1;
     834           0 :                     break;
     835             :                 }
     836             :             }
     837             :         }
     838           0 :         CLOSE_READER(re, &s->gb);
     839             :     }
     840             : 
     841           0 :     if (i > *last_nnz)
     842           0 :         *last_nnz = i;
     843             : 
     844           0 :     return 0;
     845             : }
     846             : 
     847             : #define REFINE_BIT(j) {                                             \
     848             :     UPDATE_CACHE(re, &s->gb);                                       \
     849             :     sign = block[j] >> 15;                                          \
     850             :     block[j] += SHOW_UBITS(re, &s->gb, 1) *                         \
     851             :                 ((quant_matrix[i] ^ sign) - sign) << Al;            \
     852             :     LAST_SKIP_BITS(re, &s->gb, 1);                                  \
     853             : }
     854             : 
     855             : #define ZERO_RUN                                                    \
     856             : for (; ; i++) {                                                     \
     857             :     if (i > last) {                                                 \
     858             :         i += run;                                                   \
     859             :         if (i > se) {                                               \
     860             :             av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
     861             :             return -1;                                              \
     862             :         }                                                           \
     863             :         break;                                                      \
     864             :     }                                                               \
     865             :     j = s->scantable.permutated[i];                                 \
     866             :     if (block[j])                                                   \
     867             :         REFINE_BIT(j)                                               \
     868             :     else if (run-- == 0)                                            \
     869             :         break;                                                      \
     870             : }
     871             : 
     872             : /* decode block and dequantize - progressive JPEG refinement pass */
     873           0 : static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
     874             :                                    uint8_t *last_nnz,
     875             :                                    int ac_index, uint16_t *quant_matrix,
     876             :                                    int ss, int se, int Al, int *EOBRUN)
     877             : {
     878           0 :     int code, i = ss, j, sign, val, run;
     879           0 :     int last    = FFMIN(se, *last_nnz);
     880             : 
     881           0 :     OPEN_READER(re, &s->gb);
     882           0 :     if (*EOBRUN) {
     883           0 :         (*EOBRUN)--;
     884             :     } else {
     885           0 :         for (; ; i++) {
     886           0 :             UPDATE_CACHE(re, &s->gb);
     887           0 :             GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
     888             : 
     889           0 :             if (code & 0xF) {
     890           0 :                 run = ((unsigned) code) >> 4;
     891           0 :                 UPDATE_CACHE(re, &s->gb);
     892           0 :                 val = SHOW_UBITS(re, &s->gb, 1);
     893           0 :                 LAST_SKIP_BITS(re, &s->gb, 1);
     894           0 :                 ZERO_RUN;
     895           0 :                 j = s->scantable.permutated[i];
     896           0 :                 val--;
     897           0 :                 block[j] = ((quant_matrix[i] << Al) ^ val) - val;
     898           0 :                 if (i == se) {
     899           0 :                     if (i > *last_nnz)
     900           0 :                         *last_nnz = i;
     901           0 :                     CLOSE_READER(re, &s->gb);
     902           0 :                     return 0;
     903             :                 }
     904             :             } else {
     905           0 :                 run = ((unsigned) code) >> 4;
     906           0 :                 if (run == 0xF) {
     907           0 :                     ZERO_RUN;
     908             :                 } else {
     909           0 :                     val = run;
     910           0 :                     run = (1 << run);
     911           0 :                     if (val) {
     912           0 :                         UPDATE_CACHE(re, &s->gb);
     913           0 :                         run += SHOW_UBITS(re, &s->gb, val);
     914           0 :                         LAST_SKIP_BITS(re, &s->gb, val);
     915             :                     }
     916           0 :                     *EOBRUN = run - 1;
     917           0 :                     break;
     918             :                 }
     919             :             }
     920             :         }
     921             : 
     922           0 :         if (i > *last_nnz)
     923           0 :             *last_nnz = i;
     924             :     }
     925             : 
     926           0 :     for (; i <= last; i++) {
     927           0 :         j = s->scantable.permutated[i];
     928           0 :         if (block[j])
     929           0 :             REFINE_BIT(j)
     930             :     }
     931           0 :     CLOSE_READER(re, &s->gb);
     932             : 
     933           0 :     return 0;
     934             : }
     935             : #undef REFINE_BIT
     936             : #undef ZERO_RUN
     937             : 
     938      763235 : static int handle_rstn(MJpegDecodeContext *s, int nb_components)
     939             : {
     940             :     int i;
     941      763235 :     int reset = 0;
     942             : 
     943      763235 :     if (s->restart_interval) {
     944           0 :         s->restart_count--;
     945           0 :         if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
     946           0 :             align_get_bits(&s->gb);
     947           0 :             for (i = 0; i < nb_components; i++) /* reset dc */
     948           0 :                 s->last_dc[i] = (4 << s->bits);
     949             :         }
     950             : 
     951           0 :         i = 8 + ((-get_bits_count(&s->gb)) & 7);
     952             :         /* skip RSTn */
     953           0 :         if (s->restart_count == 0) {
     954           0 :             if(   show_bits(&s->gb, i) == (1 << i) - 1
     955           0 :                || show_bits(&s->gb, i) == 0xFF) {
     956           0 :                 int pos = get_bits_count(&s->gb);
     957           0 :                 align_get_bits(&s->gb);
     958           0 :                 while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
     959           0 :                     skip_bits(&s->gb, 8);
     960           0 :                 if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
     961           0 :                     for (i = 0; i < nb_components; i++) /* reset dc */
     962           0 :                         s->last_dc[i] = (4 << s->bits);
     963           0 :                     reset = 1;
     964             :                 } else
     965           0 :                     skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
     966             :             }
     967             :         }
     968             :     }
     969      763235 :     return reset;
     970             : }
     971             : 
     972           0 : static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
     973             : {
     974             :     int i, mb_x, mb_y;
     975             :     uint16_t (*buffer)[4];
     976             :     int left[4], top[4], topleft[4];
     977           0 :     const int linesize = s->linesize[0];
     978           0 :     const int mask     = ((1 << s->bits) - 1) << point_transform;
     979           0 :     int resync_mb_y = 0;
     980           0 :     int resync_mb_x = 0;
     981             : 
     982           0 :     if (s->nb_components != 3 && s->nb_components != 4)
     983           0 :         return AVERROR_INVALIDDATA;
     984           0 :     if (s->v_max != 1 || s->h_max != 1 || !s->lossless)
     985           0 :         return AVERROR_INVALIDDATA;
     986             : 
     987             : 
     988           0 :     s->restart_count = s->restart_interval;
     989             : 
     990           0 :     av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
     991           0 :                    (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
     992           0 :     if (!s->ljpeg_buffer)
     993           0 :         return AVERROR(ENOMEM);
     994             : 
     995           0 :     buffer = s->ljpeg_buffer;
     996             : 
     997           0 :     for (i = 0; i < 4; i++)
     998           0 :         buffer[0][i] = 1 << (s->bits - 1);
     999             : 
    1000           0 :     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
    1001           0 :         uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
    1002             : 
    1003           0 :         if (s->interlaced && s->bottom_field)
    1004           0 :             ptr += linesize >> 1;
    1005             : 
    1006           0 :         for (i = 0; i < 4; i++)
    1007           0 :             top[i] = left[i] = topleft[i] = buffer[0][i];
    1008             : 
    1009           0 :         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1010           0 :             int modified_predictor = predictor;
    1011             : 
    1012           0 :             if (s->restart_interval && !s->restart_count){
    1013           0 :                 s->restart_count = s->restart_interval;
    1014           0 :                 resync_mb_x = mb_x;
    1015           0 :                 resync_mb_y = mb_y;
    1016           0 :                 for(i=0; i<4; i++)
    1017           0 :                     top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
    1018             :             }
    1019           0 :             if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
    1020           0 :                 modified_predictor = 1;
    1021             : 
    1022           0 :             for (i=0;i<nb_components;i++) {
    1023             :                 int pred, dc;
    1024             : 
    1025           0 :                 topleft[i] = top[i];
    1026           0 :                 top[i]     = buffer[mb_x][i];
    1027             : 
    1028           0 :                 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
    1029             : 
    1030           0 :                 dc = mjpeg_decode_dc(s, s->dc_index[i]);
    1031           0 :                 if(dc == 0xFFFFF)
    1032           0 :                     return -1;
    1033             : 
    1034           0 :                 left[i] = buffer[mb_x][i] =
    1035           0 :                     mask & (pred + (dc * (1 << point_transform)));
    1036             :             }
    1037             : 
    1038           0 :             if (s->restart_interval && !--s->restart_count) {
    1039           0 :                 align_get_bits(&s->gb);
    1040           0 :                 skip_bits(&s->gb, 16); /* skip RSTn */
    1041             :             }
    1042             :         }
    1043           0 :         if (s->rct && s->nb_components == 4) {
    1044           0 :             for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1045           0 :                 ptr[4*mb_x + 2] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
    1046           0 :                 ptr[4*mb_x + 1] = buffer[mb_x][1] + ptr[4*mb_x + 2];
    1047           0 :                 ptr[4*mb_x + 3] = buffer[mb_x][2] + ptr[4*mb_x + 2];
    1048           0 :                 ptr[4*mb_x + 0] = buffer[mb_x][3];
    1049             :             }
    1050           0 :         } else if (s->nb_components == 4) {
    1051           0 :             for(i=0; i<nb_components; i++) {
    1052           0 :                 int c= s->comp_index[i];
    1053           0 :                 if (s->bits <= 8) {
    1054           0 :                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1055           0 :                         ptr[4*mb_x+3-c] = buffer[mb_x][i];
    1056             :                     }
    1057           0 :                 } else if(s->bits == 9) {
    1058           0 :                     return AVERROR_PATCHWELCOME;
    1059             :                 } else {
    1060           0 :                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1061           0 :                         ((uint16_t*)ptr)[4*mb_x+c] = buffer[mb_x][i];
    1062             :                     }
    1063             :                 }
    1064             :             }
    1065           0 :         } else if (s->rct) {
    1066           0 :             for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1067           0 :                 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
    1068           0 :                 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
    1069           0 :                 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
    1070             :             }
    1071           0 :         } else if (s->pegasus_rct) {
    1072           0 :             for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1073           0 :                 ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
    1074           0 :                 ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
    1075           0 :                 ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
    1076             :             }
    1077             :         } else {
    1078           0 :             for(i=0; i<nb_components; i++) {
    1079           0 :                 int c= s->comp_index[i];
    1080           0 :                 if (s->bits <= 8) {
    1081           0 :                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1082           0 :                         ptr[3*mb_x+2-c] = buffer[mb_x][i];
    1083             :                     }
    1084           0 :                 } else if(s->bits == 9) {
    1085           0 :                     return AVERROR_PATCHWELCOME;
    1086             :                 } else {
    1087           0 :                     for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1088           0 :                         ((uint16_t*)ptr)[3*mb_x+2-c] = buffer[mb_x][i];
    1089             :                     }
    1090             :                 }
    1091             :             }
    1092             :         }
    1093             :     }
    1094           0 :     return 0;
    1095             : }
    1096             : 
    1097         200 : static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
    1098             :                                  int point_transform, int nb_components)
    1099             : {
    1100             :     int i, mb_x, mb_y, mask;
    1101         200 :     int bits= (s->bits+7)&~7;
    1102         200 :     int resync_mb_y = 0;
    1103         200 :     int resync_mb_x = 0;
    1104             : 
    1105         200 :     point_transform += bits - s->bits;
    1106         200 :     mask = ((1 << s->bits) - 1) << point_transform;
    1107             : 
    1108         200 :     av_assert0(nb_components>=1 && nb_components<=4);
    1109             : 
    1110       22650 :     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
    1111     3838500 :         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1112     3816050 :             if (get_bits_left(&s->gb) < 1) {
    1113           0 :                 av_log(s->avctx, AV_LOG_ERROR, "bitstream end in yuv_scan\n");
    1114           0 :                 return AVERROR_INVALIDDATA;
    1115             :             }
    1116     3816050 :             if (s->restart_interval && !s->restart_count){
    1117           0 :                 s->restart_count = s->restart_interval;
    1118           0 :                 resync_mb_x = mb_x;
    1119           0 :                 resync_mb_y = mb_y;
    1120             :             }
    1121             : 
    1122     3865550 :             if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
    1123       49500 :                 int toprow  = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
    1124       49500 :                 int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
    1125      198000 :                 for (i = 0; i < nb_components; i++) {
    1126             :                     uint8_t *ptr;
    1127             :                     uint16_t *ptr16;
    1128             :                     int n, h, v, x, y, c, j, linesize;
    1129      148500 :                     n = s->nb_blocks[i];
    1130      148500 :                     c = s->comp_index[i];
    1131      148500 :                     h = s->h_scount[i];
    1132      148500 :                     v = s->v_scount[i];
    1133      148500 :                     x = 0;
    1134      148500 :                     y = 0;
    1135      148500 :                     linesize= s->linesize[c];
    1136             : 
    1137      148500 :                     if(bits>8) linesize /= 2;
    1138             : 
    1139      445500 :                     for(j=0; j<n; j++) {
    1140             :                         int pred, dc;
    1141             : 
    1142      297000 :                         dc = mjpeg_decode_dc(s, s->dc_index[i]);
    1143      297000 :                         if(dc == 0xFFFFF)
    1144           0 :                             return -1;
    1145      297000 :                         if (   h * mb_x + x >= s->width
    1146      297000 :                             || v * mb_y + y >= s->height) {
    1147             :                             // Nothing to do
    1148      297000 :                         } else if (bits<=8) {
    1149      297000 :                         ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
    1150      297000 :                         if(y==0 && toprow){
    1151      218000 :                             if(x==0 && leftcol){
    1152         600 :                                 pred= 1 << (bits - 1);
    1153             :                             }else{
    1154      108400 :                                 pred= ptr[-1];
    1155             :                             }
    1156             :                         }else{
    1157      188000 :                             if(x==0 && leftcol){
    1158       89200 :                                 pred= ptr[-linesize];
    1159             :                             }else{
    1160       98800 :                                 PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
    1161             :                             }
    1162             :                         }
    1163             : 
    1164      297000 :                         if (s->interlaced && s->bottom_field)
    1165           0 :                             ptr += linesize >> 1;
    1166      297000 :                         pred &= mask;
    1167      297000 :                         *ptr= pred + ((unsigned)dc << point_transform);
    1168             :                         }else{
    1169           0 :                             ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
    1170           0 :                             if(y==0 && toprow){
    1171           0 :                                 if(x==0 && leftcol){
    1172           0 :                                     pred= 1 << (bits - 1);
    1173             :                                 }else{
    1174           0 :                                     pred= ptr16[-1];
    1175             :                                 }
    1176             :                             }else{
    1177           0 :                                 if(x==0 && leftcol){
    1178           0 :                                     pred= ptr16[-linesize];
    1179             :                                 }else{
    1180           0 :                                     PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
    1181             :                                 }
    1182             :                             }
    1183             : 
    1184           0 :                             if (s->interlaced && s->bottom_field)
    1185           0 :                                 ptr16 += linesize >> 1;
    1186           0 :                             pred &= mask;
    1187           0 :                             *ptr16= pred + ((unsigned)dc << point_transform);
    1188             :                         }
    1189      297000 :                         if (++x == h) {
    1190      198000 :                             x = 0;
    1191      198000 :                             y++;
    1192             :                         }
    1193             :                     }
    1194             :                 }
    1195             :             } else {
    1196    15066200 :                 for (i = 0; i < nb_components; i++) {
    1197             :                     uint8_t *ptr;
    1198             :                     uint16_t *ptr16;
    1199             :                     int n, h, v, x, y, c, j, linesize, dc;
    1200    11299650 :                     n        = s->nb_blocks[i];
    1201    11299650 :                     c        = s->comp_index[i];
    1202    11299650 :                     h        = s->h_scount[i];
    1203    11299650 :                     v        = s->v_scount[i];
    1204    11299650 :                     x        = 0;
    1205    11299650 :                     y        = 0;
    1206    11299650 :                     linesize = s->linesize[c];
    1207             : 
    1208    11299650 :                     if(bits>8) linesize /= 2;
    1209             : 
    1210    33898950 :                     for (j = 0; j < n; j++) {
    1211             :                         int pred;
    1212             : 
    1213    22599300 :                         dc = mjpeg_decode_dc(s, s->dc_index[i]);
    1214    22599300 :                         if(dc == 0xFFFFF)
    1215           0 :                             return -1;
    1216    22599300 :                         if (   h * mb_x + x >= s->width
    1217    22599300 :                             || v * mb_y + y >= s->height) {
    1218             :                             // Nothing to do
    1219    22599300 :                         } else if (bits<=8) {
    1220    45198600 :                             ptr = s->picture_ptr->data[c] +
    1221    45198600 :                               (linesize * (v * mb_y + y)) +
    1222    22599300 :                               (h * mb_x + x); //FIXME optimize this crap
    1223    22599300 :                             PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
    1224             : 
    1225    22599300 :                             pred &= mask;
    1226    22599300 :                             *ptr = pred + ((unsigned)dc << point_transform);
    1227             :                         }else{
    1228           0 :                             ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
    1229           0 :                             PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
    1230             : 
    1231           0 :                             pred &= mask;
    1232           0 :                             *ptr16= pred + ((unsigned)dc << point_transform);
    1233             :                         }
    1234             : 
    1235    22599300 :                         if (++x == h) {
    1236    15066200 :                             x = 0;
    1237    15066200 :                             y++;
    1238             :                         }
    1239             :                     }
    1240             :                 }
    1241             :             }
    1242     3816050 :             if (s->restart_interval && !--s->restart_count) {
    1243           0 :                 align_get_bits(&s->gb);
    1244           0 :                 skip_bits(&s->gb, 16); /* skip RSTn */
    1245             :             }
    1246             :         }
    1247             :     }
    1248         200 :     return 0;
    1249             : }
    1250             : 
    1251      786684 : static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
    1252             :                                               uint8_t *dst, const uint8_t *src,
    1253             :                                               int linesize, int lowres)
    1254             : {
    1255      786684 :     switch (lowres) {
    1256      786684 :     case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
    1257      786684 :         break;
    1258           0 :     case 1: copy_block4(dst, src, linesize, linesize, 4);
    1259           0 :         break;
    1260           0 :     case 2: copy_block2(dst, src, linesize, linesize, 2);
    1261           0 :         break;
    1262           0 :     case 3: *dst = *src;
    1263           0 :         break;
    1264             :     }
    1265      786684 : }
    1266             : 
    1267       11750 : static void shift_output(MJpegDecodeContext *s, uint8_t *ptr, int linesize)
    1268             : {
    1269             :     int block_x, block_y;
    1270       11750 :     int size = 8 >> s->avctx->lowres;
    1271       11750 :     if (s->bits > 8) {
    1272      105750 :         for (block_y=0; block_y<size; block_y++)
    1273      846000 :             for (block_x=0; block_x<size; block_x++)
    1274      752000 :                 *(uint16_t*)(ptr + 2*block_x + block_y*linesize) <<= 16 - s->bits;
    1275             :     } else {
    1276           0 :         for (block_y=0; block_y<size; block_y++)
    1277           0 :             for (block_x=0; block_x<size; block_x++)
    1278           0 :                 *(ptr + block_x + block_y*linesize) <<= 8 - s->bits;
    1279             :     }
    1280       11750 : }
    1281             : 
    1282        2103 : static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
    1283             :                              int Al, const uint8_t *mb_bitmask,
    1284             :                              int mb_bitmask_size,
    1285             :                              const AVFrame *reference)
    1286             : {
    1287             :     int i, mb_x, mb_y, chroma_h_shift, chroma_v_shift, chroma_width, chroma_height;
    1288             :     uint8_t *data[MAX_COMPONENTS];
    1289             :     const uint8_t *reference_data[MAX_COMPONENTS];
    1290             :     int linesize[MAX_COMPONENTS];
    1291        2103 :     GetBitContext mb_bitmask_gb = {0}; // initialize to silence gcc warning
    1292        2103 :     int bytes_per_pixel = 1 + (s->bits > 8);
    1293             : 
    1294        2103 :     if (mb_bitmask) {
    1295          31 :         if (mb_bitmask_size != (s->mb_width * s->mb_height + 7)>>3) {
    1296           0 :             av_log(s->avctx, AV_LOG_ERROR, "mb_bitmask_size mismatches\n");
    1297           0 :             return AVERROR_INVALIDDATA;
    1298             :         }
    1299          31 :         init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
    1300             :     }
    1301             : 
    1302        2103 :     s->restart_count = 0;
    1303             : 
    1304        2103 :     av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt, &chroma_h_shift,
    1305             :                                      &chroma_v_shift);
    1306        2103 :     chroma_width  = AV_CEIL_RSHIFT(s->width,  chroma_h_shift);
    1307        2103 :     chroma_height = AV_CEIL_RSHIFT(s->height, chroma_v_shift);
    1308             : 
    1309        8410 :     for (i = 0; i < nb_components; i++) {
    1310        6307 :         int c   = s->comp_index[i];
    1311        6307 :         data[c] = s->picture_ptr->data[c];
    1312        6307 :         reference_data[c] = reference ? reference->data[c] : NULL;
    1313        6307 :         linesize[c] = s->linesize[c];
    1314        6307 :         s->coefs_finished[c] |= 1;
    1315             :     }
    1316             : 
    1317       29852 :     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
    1318      790984 :         for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
    1319      763235 :             const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
    1320             : 
    1321      763235 :             if (s->restart_interval && !s->restart_count)
    1322           0 :                 s->restart_count = s->restart_interval;
    1323             : 
    1324      763235 :             if (get_bits_left(&s->gb) < 0) {
    1325           0 :                 av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
    1326           0 :                        -get_bits_left(&s->gb));
    1327           0 :                 return AVERROR_INVALIDDATA;
    1328             :             }
    1329     3029440 :             for (i = 0; i < nb_components; i++) {
    1330             :                 uint8_t *ptr;
    1331             :                 int n, h, v, x, y, c, j;
    1332             :                 int block_offset;
    1333     2266205 :                 n = s->nb_blocks[i];
    1334     2266205 :                 c = s->comp_index[i];
    1335     2266205 :                 h = s->h_scount[i];
    1336     2266205 :                 v = s->v_scount[i];
    1337     2266205 :                 x = 0;
    1338     2266205 :                 y = 0;
    1339     6900145 :                 for (j = 0; j < n; j++) {
    1340    13901820 :                     block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
    1341     9267880 :                                      (h * mb_x + x) * 8 * bytes_per_pixel) >> s->avctx->lowres);
    1342             : 
    1343     4633940 :                     if (s->interlaced && s->bottom_field)
    1344        3520 :                         block_offset += linesize[c] >> 1;
    1345     4633940 :                     if (   8*(h * mb_x + x) < ((c == 1) || (c == 2) ? chroma_width  : s->width)
    1346     4632032 :                         && 8*(v * mb_y + y) < ((c == 1) || (c == 2) ? chroma_height : s->height)) {
    1347     4626112 :                         ptr = data[c] + block_offset;
    1348             :                     } else
    1349        7828 :                         ptr = NULL;
    1350     4633940 :                     if (!s->progressive) {
    1351     4633940 :                         if (copy_mb) {
    1352      786684 :                             if (ptr)
    1353      786684 :                                 mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
    1354      786684 :                                                 linesize[c], s->avctx->lowres);
    1355             : 
    1356             :                         } else {
    1357     3847256 :                             s->bdsp.clear_block(s->block);
    1358     3847256 :                             if (decode_block(s, s->block, i,
    1359             :                                              s->dc_index[i], s->ac_index[i],
    1360     3847256 :                                              s->quant_matrixes[s->quant_sindex[i]]) < 0) {
    1361           0 :                                 av_log(s->avctx, AV_LOG_ERROR,
    1362             :                                        "error y=%d x=%d\n", mb_y, mb_x);
    1363           0 :                                 return AVERROR_INVALIDDATA;
    1364             :                             }
    1365     3847256 :                             if (ptr) {
    1366     3839428 :                                 s->idsp.idct_put(ptr, linesize[c], s->block);
    1367     3839428 :                                 if (s->bits & 7)
    1368       11750 :                                     shift_output(s, ptr, linesize[c]);
    1369             :                             }
    1370             :                         }
    1371             :                     } else {
    1372           0 :                         int block_idx  = s->block_stride[c] * (v * mb_y + y) +
    1373           0 :                                          (h * mb_x + x);
    1374           0 :                         int16_t *block = s->blocks[c][block_idx];
    1375           0 :                         if (Ah)
    1376           0 :                             block[0] += get_bits1(&s->gb) *
    1377           0 :                                         s->quant_matrixes[s->quant_sindex[i]][0] << Al;
    1378           0 :                         else if (decode_dc_progressive(s, block, i, s->dc_index[i],
    1379           0 :                                                        s->quant_matrixes[s->quant_sindex[i]],
    1380             :                                                        Al) < 0) {
    1381           0 :                             av_log(s->avctx, AV_LOG_ERROR,
    1382             :                                    "error y=%d x=%d\n", mb_y, mb_x);
    1383           0 :                             return AVERROR_INVALIDDATA;
    1384             :                         }
    1385             :                     }
    1386             :                     ff_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
    1387             :                     ff_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
    1388             :                             mb_x, mb_y, x, y, c, s->bottom_field,
    1389             :                             (v * mb_y + y) * 8, (h * mb_x + x) * 8);
    1390     4633940 :                     if (++x == h) {
    1391     3373280 :                         x = 0;
    1392     3373280 :                         y++;
    1393             :                     }
    1394             :                 }
    1395             :             }
    1396             : 
    1397      763235 :             handle_rstn(s, nb_components);
    1398             :         }
    1399             :     }
    1400        2103 :     return 0;
    1401             : }
    1402             : 
    1403           0 : static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
    1404             :                                             int se, int Ah, int Al)
    1405             : {
    1406             :     int mb_x, mb_y;
    1407           0 :     int EOBRUN = 0;
    1408           0 :     int c = s->comp_index[0];
    1409           0 :     uint16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
    1410             : 
    1411           0 :     av_assert0(ss>=0 && Ah>=0 && Al>=0);
    1412           0 :     if (se < ss || se > 63) {
    1413           0 :         av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
    1414           0 :         return AVERROR_INVALIDDATA;
    1415             :     }
    1416             : 
    1417             :     // s->coefs_finished is a bitmask for coefficients coded
    1418             :     // ss and se are parameters telling start and end coefficients
    1419           0 :     s->coefs_finished[c] |= (2ULL << se) - (1ULL << ss);
    1420             : 
    1421           0 :     s->restart_count = 0;
    1422             : 
    1423           0 :     for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
    1424           0 :         int block_idx    = mb_y * s->block_stride[c];
    1425           0 :         int16_t (*block)[64] = &s->blocks[c][block_idx];
    1426           0 :         uint8_t *last_nnz    = &s->last_nnz[c][block_idx];
    1427           0 :         if (get_bits_left(&s->gb) <= 0) {
    1428           0 :             av_log(s->avctx, AV_LOG_ERROR, "bitstream truncated in mjpeg_decode_scan_progressive_ac\n");
    1429           0 :             return AVERROR_INVALIDDATA;
    1430             :         }
    1431           0 :         for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
    1432             :                 int ret;
    1433           0 :                 if (s->restart_interval && !s->restart_count)
    1434           0 :                     s->restart_count = s->restart_interval;
    1435             : 
    1436           0 :                 if (Ah)
    1437           0 :                     ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
    1438             :                                                   quant_matrix, ss, se, Al, &EOBRUN);
    1439             :                 else
    1440           0 :                     ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
    1441             :                                                    quant_matrix, ss, se, Al, &EOBRUN);
    1442           0 :                 if (ret < 0) {
    1443           0 :                     av_log(s->avctx, AV_LOG_ERROR,
    1444             :                            "error y=%d x=%d\n", mb_y, mb_x);
    1445           0 :                     return AVERROR_INVALIDDATA;
    1446             :                 }
    1447             : 
    1448           0 :             if (handle_rstn(s, 0))
    1449           0 :                 EOBRUN = 0;
    1450             :         }
    1451             :     }
    1452           0 :     return 0;
    1453             : }
    1454             : 
    1455           0 : static void mjpeg_idct_scan_progressive_ac(MJpegDecodeContext *s)
    1456             : {
    1457             :     int mb_x, mb_y;
    1458             :     int c;
    1459           0 :     const int bytes_per_pixel = 1 + (s->bits > 8);
    1460           0 :     const int block_size = s->lossless ? 1 : 8;
    1461             : 
    1462           0 :     for (c = 0; c < s->nb_components; c++) {
    1463           0 :         uint8_t *data = s->picture_ptr->data[c];
    1464           0 :         int linesize  = s->linesize[c];
    1465           0 :         int h = s->h_max / s->h_count[c];
    1466           0 :         int v = s->v_max / s->v_count[c];
    1467           0 :         int mb_width     = (s->width  + h * block_size - 1) / (h * block_size);
    1468           0 :         int mb_height    = (s->height + v * block_size - 1) / (v * block_size);
    1469             : 
    1470           0 :         if (~s->coefs_finished[c])
    1471           0 :             av_log(s->avctx, AV_LOG_WARNING, "component %d is incomplete\n", c);
    1472             : 
    1473           0 :         if (s->interlaced && s->bottom_field)
    1474           0 :             data += linesize >> 1;
    1475             : 
    1476           0 :         for (mb_y = 0; mb_y < mb_height; mb_y++) {
    1477           0 :             uint8_t *ptr     = data + (mb_y * linesize * 8 >> s->avctx->lowres);
    1478           0 :             int block_idx    = mb_y * s->block_stride[c];
    1479           0 :             int16_t (*block)[64] = &s->blocks[c][block_idx];
    1480           0 :             for (mb_x = 0; mb_x < mb_width; mb_x++, block++) {
    1481           0 :                 s->idsp.idct_put(ptr, linesize, *block);
    1482           0 :                 if (s->bits & 7)
    1483           0 :                     shift_output(s, ptr, linesize);
    1484           0 :                 ptr += bytes_per_pixel*8 >> s->avctx->lowres;
    1485             :             }
    1486             :         }
    1487             :     }
    1488           0 : }
    1489             : 
    1490        2508 : int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
    1491             :                         int mb_bitmask_size, const AVFrame *reference)
    1492             : {
    1493             :     int len, nb_components, i, h, v, predictor, point_transform;
    1494             :     int index, id, ret;
    1495        2508 :     const int block_size = s->lossless ? 1 : 8;
    1496             :     int ilv, prev_shift;
    1497             : 
    1498        2508 :     if (!s->got_picture) {
    1499           0 :         av_log(s->avctx, AV_LOG_WARNING,
    1500             :                 "Can not process SOS before SOF, skipping\n");
    1501           0 :         return -1;
    1502             :     }
    1503             : 
    1504        2508 :     if (reference) {
    1505          62 :         if (reference->width  != s->picture_ptr->width  ||
    1506          62 :             reference->height != s->picture_ptr->height ||
    1507          31 :             reference->format != s->picture_ptr->format) {
    1508           0 :             av_log(s->avctx, AV_LOG_ERROR, "Reference mismatching\n");
    1509           0 :             return AVERROR_INVALIDDATA;
    1510             :         }
    1511             :     }
    1512             : 
    1513        2508 :     av_assert0(s->picture_ptr->data[0]);
    1514             :     /* XXX: verify len field validity */
    1515        2508 :     len = get_bits(&s->gb, 16);
    1516        2508 :     nb_components = get_bits(&s->gb, 8);
    1517        2508 :     if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
    1518           0 :         avpriv_report_missing_feature(s->avctx,
    1519             :                                       "decode_sos: nb_components (%d)",
    1520             :                                       nb_components);
    1521           0 :         return AVERROR_PATCHWELCOME;
    1522             :     }
    1523        2508 :     if (len != 6 + 2 * nb_components) {
    1524           0 :         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
    1525           0 :         return AVERROR_INVALIDDATA;
    1526             :     }
    1527       10030 :     for (i = 0; i < nb_components; i++) {
    1528        7522 :         id = get_bits(&s->gb, 8) - 1;
    1529        7522 :         av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
    1530             :         /* find component index */
    1531       15043 :         for (index = 0; index < s->nb_components; index++)
    1532       15043 :             if (id == s->component_id[index])
    1533        7522 :                 break;
    1534        7522 :         if (index == s->nb_components) {
    1535           0 :             av_log(s->avctx, AV_LOG_ERROR,
    1536             :                    "decode_sos: index(%d) out of components\n", index);
    1537           0 :             return AVERROR_INVALIDDATA;
    1538             :         }
    1539             :         /* Metasoft MJPEG codec has Cb and Cr swapped */
    1540        7522 :         if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
    1541           0 :             && nb_components == 3 && s->nb_components == 3 && i)
    1542           0 :             index = 3 - i;
    1543             : 
    1544        7522 :         s->quant_sindex[i] = s->quant_index[index];
    1545        7522 :         s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
    1546        7522 :         s->h_scount[i]  = s->h_count[index];
    1547        7522 :         s->v_scount[i]  = s->v_count[index];
    1548             : 
    1549        7522 :         if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
    1550           0 :             index = (i+2)%3;
    1551        7522 :         if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
    1552           0 :             index = (index+2)%3;
    1553             : 
    1554        7522 :         s->comp_index[i] = index;
    1555             : 
    1556        7522 :         s->dc_index[i] = get_bits(&s->gb, 4);
    1557        7522 :         s->ac_index[i] = get_bits(&s->gb, 4);
    1558             : 
    1559       15044 :         if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
    1560       15044 :             s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
    1561             :             goto out_of_range;
    1562       22566 :         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))
    1563             :             goto out_of_range;
    1564             :     }
    1565             : 
    1566        2508 :     predictor = get_bits(&s->gb, 8);       /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
    1567        2508 :     ilv = get_bits(&s->gb, 8);             /* JPEG Se / JPEG-LS ILV */
    1568        2508 :     if(s->avctx->codec_tag != AV_RL32("CJPG")){
    1569        2508 :         prev_shift      = get_bits(&s->gb, 4); /* Ah */
    1570        2508 :         point_transform = get_bits(&s->gb, 4); /* Al */
    1571             :     }else
    1572           0 :         prev_shift = point_transform = 0;
    1573             : 
    1574        2508 :     if (nb_components > 1) {
    1575             :         /* interleaved stream */
    1576        2507 :         s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
    1577        2507 :         s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
    1578           1 :     } else if (!s->ls) { /* skip this for JPEG-LS */
    1579           1 :         h = s->h_max / s->h_scount[0];
    1580           1 :         v = s->v_max / s->v_scount[0];
    1581           1 :         s->mb_width     = (s->width  + h * block_size - 1) / (h * block_size);
    1582           1 :         s->mb_height    = (s->height + v * block_size - 1) / (v * block_size);
    1583           1 :         s->nb_blocks[0] = 1;
    1584           1 :         s->h_scount[0]  = 1;
    1585           1 :         s->v_scount[0]  = 1;
    1586             :     }
    1587             : 
    1588        2508 :     if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1589           0 :         av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
    1590           0 :                s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
    1591             :                predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
    1592           0 :                s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
    1593             : 
    1594             : 
    1595             :     /* mjpeg-b can have padding bytes between sos and image data, skip them */
    1596        2530 :     for (i = s->mjpb_skiptosod; i > 0; i--)
    1597          22 :         skip_bits(&s->gb, 8);
    1598             : 
    1599        2508 : next_field:
    1600       10030 :     for (i = 0; i < nb_components; i++)
    1601        7522 :         s->last_dc[i] = (4 << s->bits);
    1602             : 
    1603        2508 :     if (s->lossless) {
    1604         405 :         av_assert0(s->picture_ptr == s->picture);
    1605         405 :         if (CONFIG_JPEGLS_DECODER && s->ls) {
    1606             : //            for () {
    1607             : //            reset_ls_coding_parameters(s, 0);
    1608             : 
    1609         205 :             if ((ret = ff_jpegls_decode_picture(s, predictor,
    1610             :                                                 point_transform, ilv)) < 0)
    1611           0 :                 return ret;
    1612             :         } else {
    1613         200 :             if (s->rgb) {
    1614           0 :                 if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
    1615           0 :                     return ret;
    1616             :             } else {
    1617         200 :                 if ((ret = ljpeg_decode_yuv_scan(s, predictor,
    1618             :                                                  point_transform,
    1619             :                                                  nb_components)) < 0)
    1620           0 :                     return ret;
    1621             :             }
    1622             :         }
    1623             :     } else {
    1624        2103 :         if (s->progressive && predictor) {
    1625           0 :             av_assert0(s->picture_ptr == s->picture);
    1626           0 :             if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
    1627             :                                                         ilv, prev_shift,
    1628             :                                                         point_transform)) < 0)
    1629           0 :                 return ret;
    1630             :         } else {
    1631        2103 :             if ((ret = mjpeg_decode_scan(s, nb_components,
    1632             :                                          prev_shift, point_transform,
    1633             :                                          mb_bitmask, mb_bitmask_size, reference)) < 0)
    1634           0 :                 return ret;
    1635             :         }
    1636             :     }
    1637             : 
    1638        2530 :     if (s->interlaced &&
    1639          37 :         get_bits_left(&s->gb) > 32 &&
    1640          15 :         show_bits(&s->gb, 8) == 0xFF) {
    1641           0 :         GetBitContext bak = s->gb;
    1642           0 :         align_get_bits(&bak);
    1643           0 :         if (show_bits(&bak, 16) == 0xFFD1) {
    1644           0 :             av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
    1645           0 :             s->gb = bak;
    1646           0 :             skip_bits(&s->gb, 16);
    1647           0 :             s->bottom_field ^= 1;
    1648             : 
    1649           0 :             goto next_field;
    1650             :         }
    1651             :     }
    1652             : 
    1653        2508 :     emms_c();
    1654        2508 :     return 0;
    1655           0 :  out_of_range:
    1656           0 :     av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
    1657           0 :     return AVERROR_INVALIDDATA;
    1658             : }
    1659             : 
    1660           0 : static int mjpeg_decode_dri(MJpegDecodeContext *s)
    1661             : {
    1662           0 :     if (get_bits(&s->gb, 16) != 4)
    1663           0 :         return AVERROR_INVALIDDATA;
    1664           0 :     s->restart_interval = get_bits(&s->gb, 16);
    1665           0 :     s->restart_count    = 0;
    1666           0 :     av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
    1667             :            s->restart_interval);
    1668             : 
    1669           0 :     return 0;
    1670             : }
    1671             : 
    1672         132 : static int mjpeg_decode_app(MJpegDecodeContext *s)
    1673             : {
    1674             :     int len, id, i;
    1675             : 
    1676         132 :     len = get_bits(&s->gb, 16);
    1677         132 :     if (len < 6)
    1678           0 :         return AVERROR_INVALIDDATA;
    1679         132 :     if (8 * len > get_bits_left(&s->gb))
    1680           0 :         return AVERROR_INVALIDDATA;
    1681             : 
    1682         132 :     id   = get_bits_long(&s->gb, 32);
    1683         132 :     len -= 6;
    1684             : 
    1685         132 :     if (s->avctx->debug & FF_DEBUG_STARTCODE)
    1686           0 :         av_log(s->avctx, AV_LOG_DEBUG, "APPx (%s / %8X) len=%d\n",
    1687           0 :                av_fourcc2str(av_bswap32(id)), id, len);
    1688             : 
    1689             :     /* Buggy AVID, it puts EOI only at every 10th frame. */
    1690             :     /* Also, this fourcc is used by non-avid files too, it holds some
    1691             :        information, but it's always present in AVID-created files. */
    1692         132 :     if (id == AV_RB32("AVI1")) {
    1693             :         /* structure:
    1694             :             4bytes      AVI1
    1695             :             1bytes      polarity
    1696             :             1bytes      always zero
    1697             :             4bytes      field_size
    1698             :             4bytes      field_size_less_padding
    1699             :         */
    1700           0 :             s->buggy_avid = 1;
    1701           0 :         i = get_bits(&s->gb, 8); len--;
    1702           0 :         av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
    1703           0 :         goto out;
    1704             :     }
    1705             : 
    1706         132 :     if (id == AV_RB32("JFIF")) {
    1707             :         int t_w, t_h, v1, v2;
    1708         109 :         if (len < 8)
    1709           0 :             goto out;
    1710         109 :         skip_bits(&s->gb, 8); /* the trailing zero-byte */
    1711         109 :         v1 = get_bits(&s->gb, 8);
    1712         109 :         v2 = get_bits(&s->gb, 8);
    1713         109 :         skip_bits(&s->gb, 8);
    1714             : 
    1715         109 :         s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
    1716         109 :         s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
    1717         109 :         if (   s->avctx->sample_aspect_ratio.num <= 0
    1718         109 :             || s->avctx->sample_aspect_ratio.den <= 0) {
    1719           0 :             s->avctx->sample_aspect_ratio.num = 0;
    1720           0 :             s->avctx->sample_aspect_ratio.den = 1;
    1721             :         }
    1722             : 
    1723         109 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1724           0 :             av_log(s->avctx, AV_LOG_INFO,
    1725             :                    "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
    1726             :                    v1, v2,
    1727           0 :                    s->avctx->sample_aspect_ratio.num,
    1728           0 :                    s->avctx->sample_aspect_ratio.den);
    1729             : 
    1730         109 :         len -= 8;
    1731         109 :         if (len >= 2) {
    1732         107 :             t_w = get_bits(&s->gb, 8);
    1733         107 :             t_h = get_bits(&s->gb, 8);
    1734         107 :             if (t_w && t_h) {
    1735             :                 /* skip thumbnail */
    1736           0 :                 if (len -10 - (t_w * t_h * 3) > 0)
    1737           0 :                     len -= t_w * t_h * 3;
    1738             :             }
    1739         107 :             len -= 2;
    1740             :         }
    1741         109 :         goto out;
    1742             :     }
    1743             : 
    1744          23 :     if (   id == AV_RB32("Adob")
    1745           5 :         && len >= 7
    1746           5 :         && show_bits(&s->gb, 8) == 'e'
    1747           5 :         && show_bits_long(&s->gb, 32) != AV_RB32("e_CM")) {
    1748           5 :         skip_bits(&s->gb,  8); /* 'e' */
    1749           5 :         skip_bits(&s->gb, 16); /* version */
    1750           5 :         skip_bits(&s->gb, 16); /* flags0 */
    1751           5 :         skip_bits(&s->gb, 16); /* flags1 */
    1752           5 :         s->adobe_transform = get_bits(&s->gb,  8);
    1753           5 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1754           0 :             av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found, transform=%d\n", s->adobe_transform);
    1755           5 :         len -= 7;
    1756           5 :         goto out;
    1757             :     }
    1758             : 
    1759          18 :     if (id == AV_RB32("LJIF")) {
    1760           0 :         int rgb = s->rgb;
    1761           0 :         int pegasus_rct = s->pegasus_rct;
    1762           0 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1763           0 :             av_log(s->avctx, AV_LOG_INFO,
    1764             :                    "Pegasus lossless jpeg header found\n");
    1765           0 :         skip_bits(&s->gb, 16); /* version ? */
    1766           0 :         skip_bits(&s->gb, 16); /* unknown always 0? */
    1767           0 :         skip_bits(&s->gb, 16); /* unknown always 0? */
    1768           0 :         skip_bits(&s->gb, 16); /* unknown always 0? */
    1769           0 :         switch (i=get_bits(&s->gb, 8)) {
    1770           0 :         case 1:
    1771           0 :             rgb         = 1;
    1772           0 :             pegasus_rct = 0;
    1773           0 :             break;
    1774           0 :         case 2:
    1775           0 :             rgb         = 1;
    1776           0 :             pegasus_rct = 1;
    1777           0 :             break;
    1778           0 :         default:
    1779           0 :             av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);
    1780             :         }
    1781             : 
    1782           0 :         len -= 9;
    1783           0 :         if (s->got_picture)
    1784           0 :             if (rgb != s->rgb || pegasus_rct != s->pegasus_rct) {
    1785           0 :                 av_log(s->avctx, AV_LOG_WARNING, "Mismatching LJIF tag\n");
    1786           0 :                 goto out;
    1787             :             }
    1788             : 
    1789           0 :         s->rgb = rgb;
    1790           0 :         s->pegasus_rct = pegasus_rct;
    1791             : 
    1792           0 :         goto out;
    1793             :     }
    1794          18 :     if (id == AV_RL32("colr") && len > 0) {
    1795           0 :         s->colr = get_bits(&s->gb, 8);
    1796           0 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1797           0 :             av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
    1798           0 :         len --;
    1799           0 :         goto out;
    1800             :     }
    1801          18 :     if (id == AV_RL32("xfrm") && len > 0) {
    1802           0 :         s->xfrm = get_bits(&s->gb, 8);
    1803           0 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1804           0 :             av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
    1805           0 :         len --;
    1806           0 :         goto out;
    1807             :     }
    1808             : 
    1809             :     /* JPS extension by VRex */
    1810          18 :     if (s->start_code == APP3 && id == AV_RB32("_JPS") && len >= 10) {
    1811             :         int flags, layout, type;
    1812           0 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1813           0 :             av_log(s->avctx, AV_LOG_INFO, "_JPSJPS_\n");
    1814             : 
    1815           0 :         skip_bits(&s->gb, 32); len -= 4;  /* JPS_ */
    1816           0 :         skip_bits(&s->gb, 16); len -= 2;  /* block length */
    1817           0 :         skip_bits(&s->gb, 8);             /* reserved */
    1818           0 :         flags  = get_bits(&s->gb, 8);
    1819           0 :         layout = get_bits(&s->gb, 8);
    1820           0 :         type   = get_bits(&s->gb, 8);
    1821           0 :         len -= 4;
    1822             : 
    1823           0 :         s->stereo3d = av_stereo3d_alloc();
    1824           0 :         if (!s->stereo3d) {
    1825           0 :             goto out;
    1826             :         }
    1827           0 :         if (type == 0) {
    1828           0 :             s->stereo3d->type = AV_STEREO3D_2D;
    1829           0 :         } else if (type == 1) {
    1830           0 :             switch (layout) {
    1831           0 :             case 0x01:
    1832           0 :                 s->stereo3d->type = AV_STEREO3D_LINES;
    1833           0 :                 break;
    1834           0 :             case 0x02:
    1835           0 :                 s->stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
    1836           0 :                 break;
    1837           0 :             case 0x03:
    1838           0 :                 s->stereo3d->type = AV_STEREO3D_TOPBOTTOM;
    1839           0 :                 break;
    1840             :             }
    1841           0 :             if (!(flags & 0x04)) {
    1842           0 :                 s->stereo3d->flags = AV_STEREO3D_FLAG_INVERT;
    1843             :             }
    1844             :         }
    1845           0 :         goto out;
    1846             :     }
    1847             : 
    1848             :     /* EXIF metadata */
    1849          18 :     if (s->start_code == APP1 && id == AV_RB32("Exif") && len >= 2) {
    1850             :         GetByteContext gbytes;
    1851             :         int ret, le, ifd_offset, bytes_read;
    1852             :         const uint8_t *aligned;
    1853             : 
    1854          12 :         skip_bits(&s->gb, 16); // skip padding
    1855          12 :         len -= 2;
    1856             : 
    1857             :         // init byte wise reading
    1858          12 :         aligned = align_get_bits(&s->gb);
    1859          12 :         bytestream2_init(&gbytes, aligned, len);
    1860             : 
    1861             :         // read TIFF header
    1862          12 :         ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
    1863          12 :         if (ret) {
    1864           0 :             av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
    1865             :         } else {
    1866          12 :             bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
    1867             : 
    1868             :             // read 0th IFD and store the metadata
    1869             :             // (return values > 0 indicate the presence of subimage metadata)
    1870          12 :             ret = ff_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
    1871          12 :             if (ret < 0) {
    1872           0 :                 av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
    1873             :             }
    1874             :         }
    1875             : 
    1876          12 :         bytes_read = bytestream2_tell(&gbytes);
    1877          12 :         skip_bits(&s->gb, bytes_read << 3);
    1878          12 :         len -= bytes_read;
    1879             : 
    1880          12 :         goto out;
    1881             :     }
    1882             : 
    1883             :     /* Apple MJPEG-A */
    1884           6 :     if ((s->start_code == APP1) && (len > (0x28 - 8))) {
    1885           2 :         id   = get_bits_long(&s->gb, 32);
    1886           2 :         len -= 4;
    1887             :         /* Apple MJPEG-A */
    1888           2 :         if (id == AV_RB32("mjpg")) {
    1889             :             /* structure:
    1890             :                 4bytes      field size
    1891             :                 4bytes      pad field size
    1892             :                 4bytes      next off
    1893             :                 4bytes      quant off
    1894             :                 4bytes      huff off
    1895             :                 4bytes      image off
    1896             :                 4bytes      scan off
    1897             :                 4bytes      data off
    1898             :             */
    1899           0 :             if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1900           0 :                 av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
    1901             :         }
    1902             :     }
    1903             : 
    1904           6 :     if (s->start_code == APP2 && id == AV_RB32("ICC_") && len >= 10) {
    1905             :         int id2;
    1906             :         unsigned seqno;
    1907             :         unsigned nummarkers;
    1908             : 
    1909           0 :         id   = get_bits_long(&s->gb, 32);
    1910           0 :         id2  = get_bits_long(&s->gb, 24);
    1911           0 :         len -= 7;
    1912           0 :         if (id != AV_RB32("PROF") || id2 != AV_RB24("ILE")) {
    1913           0 :             av_log(s->avctx, AV_LOG_WARNING, "Invalid ICC_PROFILE header in APP2\n");
    1914           0 :             goto out;
    1915             :         }
    1916             : 
    1917           0 :         skip_bits(&s->gb, 8);
    1918           0 :         seqno  = get_bits(&s->gb, 8);
    1919           0 :         len   -= 2;
    1920           0 :         if (seqno == 0) {
    1921           0 :             av_log(s->avctx, AV_LOG_WARNING, "Invalid sequence number in APP2\n");
    1922           0 :             goto out;
    1923             :         }
    1924             : 
    1925           0 :         nummarkers  = get_bits(&s->gb, 8);
    1926           0 :         len        -= 1;
    1927           0 :         if (nummarkers == 0) {
    1928           0 :             av_log(s->avctx, AV_LOG_WARNING, "Invalid number of markers coded in APP2\n");
    1929           0 :             goto out;
    1930           0 :         } else if (s->iccnum != 0 && nummarkers != s->iccnum) {
    1931           0 :             av_log(s->avctx, AV_LOG_WARNING, "Mistmatch in coded number of ICC markers between markers\n");
    1932           0 :             goto out;
    1933           0 :         } else if (seqno > nummarkers) {
    1934           0 :             av_log(s->avctx, AV_LOG_WARNING, "Mismatching sequence number and coded number of ICC markers\n");
    1935           0 :             goto out;
    1936             :         }
    1937             : 
    1938             :         /* Allocate if this is the first APP2 we've seen. */
    1939           0 :         if (s->iccnum == 0) {
    1940           0 :             s->iccdata     = av_mallocz(nummarkers * sizeof(*(s->iccdata)));
    1941           0 :             s->iccdatalens = av_mallocz(nummarkers * sizeof(*(s->iccdatalens)));
    1942           0 :             if (!s->iccdata || !s->iccdatalens) {
    1943           0 :                 av_log(s->avctx, AV_LOG_ERROR, "Could not allocate ICC data arrays\n");
    1944           0 :                 return AVERROR(ENOMEM);
    1945             :             }
    1946           0 :             s->iccnum = nummarkers;
    1947             :         }
    1948             : 
    1949           0 :         if (s->iccdata[seqno - 1]) {
    1950           0 :             av_log(s->avctx, AV_LOG_WARNING, "Duplicate ICC sequence number\n");
    1951           0 :             goto out;
    1952             :         }
    1953             : 
    1954           0 :         s->iccdatalens[seqno - 1]  = len;
    1955           0 :         s->iccdata[seqno - 1]      = av_malloc(len);
    1956           0 :         if (!s->iccdata[seqno - 1]) {
    1957           0 :             av_log(s->avctx, AV_LOG_ERROR, "Could not allocate ICC data buffer\n");
    1958           0 :             return AVERROR(ENOMEM);
    1959             :         }
    1960             : 
    1961           0 :         memcpy(s->iccdata[seqno - 1], align_get_bits(&s->gb), len);
    1962           0 :         skip_bits(&s->gb, len << 3);
    1963           0 :         len = 0;
    1964           0 :         s->iccread++;
    1965             : 
    1966           0 :         if (s->iccread > s->iccnum)
    1967           0 :             av_log(s->avctx, AV_LOG_WARNING, "Read more ICC markers than are supposed to be coded\n");
    1968             :     }
    1969             : 
    1970         138 : out:
    1971             :     /* slow but needed for extreme adobe jpegs */
    1972         132 :     if (len < 0)
    1973           0 :         av_log(s->avctx, AV_LOG_ERROR,
    1974             :                "mjpeg: error, decode_app parser read over the end\n");
    1975      126536 :     while (--len > 0)
    1976      126272 :         skip_bits(&s->gb, 8);
    1977             : 
    1978         132 :     return 0;
    1979             : }
    1980             : 
    1981         209 : static int mjpeg_decode_com(MJpegDecodeContext *s)
    1982             : {
    1983         209 :     int len = get_bits(&s->gb, 16);
    1984         209 :     if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
    1985             :         int i;
    1986         209 :         char *cbuf = av_malloc(len - 1);
    1987         209 :         if (!cbuf)
    1988           0 :             return AVERROR(ENOMEM);
    1989             : 
    1990        2393 :         for (i = 0; i < len - 2; i++)
    1991        2184 :             cbuf[i] = get_bits(&s->gb, 8);
    1992         209 :         if (i > 0 && cbuf[i - 1] == '\n')
    1993           1 :             cbuf[i - 1] = 0;
    1994             :         else
    1995         208 :             cbuf[i] = 0;
    1996             : 
    1997         209 :         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
    1998           0 :             av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
    1999             : 
    2000             :         /* buggy avid, it puts EOI only at every 10th frame */
    2001         209 :         if (!strncmp(cbuf, "AVID", 4)) {
    2002           0 :             parse_avid(s, cbuf, len);
    2003         209 :         } else if (!strcmp(cbuf, "CS=ITU601"))
    2004         205 :             s->cs_itu601 = 1;
    2005           8 :         else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32) && s->avctx->codec_tag) ||
    2006           4 :                  (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
    2007           0 :             s->flipped = 1;
    2008           4 :         else if (!strcmp(cbuf, "MULTISCOPE II")) {
    2009           0 :             s->avctx->sample_aspect_ratio = (AVRational) { 1, 2 };
    2010           0 :             s->multiscope = 2;
    2011             :         }
    2012             : 
    2013         209 :         av_free(cbuf);
    2014             :     }
    2015             : 
    2016         209 :     return 0;
    2017             : }
    2018             : 
    2019             : /* return the 8 bit start code value and update the search
    2020             :    state. Return -1 if no start code found */
    2021       15686 : static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
    2022             : {
    2023             :     const uint8_t *buf_ptr;
    2024             :     unsigned int v, v2;
    2025             :     int val;
    2026       15686 :     int skipped = 0;
    2027             : 
    2028       15686 :     buf_ptr = *pbuf_ptr;
    2029      277633 :     while (buf_end - buf_ptr > 1) {
    2030      261942 :         v  = *buf_ptr++;
    2031      261942 :         v2 = *buf_ptr;
    2032      261942 :         if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
    2033       15681 :             val = *buf_ptr++;
    2034       15681 :             goto found;
    2035             :         }
    2036      246261 :         skipped++;
    2037             :     }
    2038           5 :     buf_ptr = buf_end;
    2039           5 :     val = -1;
    2040       15686 : found:
    2041             :     ff_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
    2042       15686 :     *pbuf_ptr = buf_ptr;
    2043       15686 :     return val;
    2044             : }
    2045             : 
    2046       15686 : int ff_mjpeg_find_marker(MJpegDecodeContext *s,
    2047             :                          const uint8_t **buf_ptr, const uint8_t *buf_end,
    2048             :                          const uint8_t **unescaped_buf_ptr,
    2049             :                          int *unescaped_buf_size)
    2050             : {
    2051             :     int start_code;
    2052       15686 :     start_code = find_marker(buf_ptr, buf_end);
    2053             : 
    2054       15686 :     av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
    2055       15686 :     if (!s->buffer)
    2056           0 :         return AVERROR(ENOMEM);
    2057             : 
    2058             :     /* unescape buffer of SOS, use special treatment for JPEG-LS */
    2059       18022 :     if (start_code == SOS && !s->ls) {
    2060        2336 :         const uint8_t *src = *buf_ptr;
    2061        2336 :         const uint8_t *ptr = src;
    2062        2336 :         uint8_t *dst = s->buffer;
    2063             : 
    2064             :         #define copy_data_segment(skip) do {       \
    2065             :             ptrdiff_t length = (ptr - src) - (skip);  \
    2066             :             if (length > 0) {                         \
    2067             :                 memcpy(dst, src, length);             \
    2068             :                 dst += length;                        \
    2069             :                 src = ptr;                            \
    2070             :             }                                         \
    2071             :         } while (0)
    2072             : 
    2073        2336 :         if (s->avctx->codec_id == AV_CODEC_ID_THP) {
    2074          74 :             ptr = buf_end;
    2075          74 :             copy_data_segment(0);
    2076             :         } else {
    2077    41721575 :             while (ptr < buf_end) {
    2078    41719313 :                 uint8_t x = *(ptr++);
    2079             : 
    2080    41719313 :                 if (x == 0xff) {
    2081      175167 :                     ptrdiff_t skip = 0;
    2082      525501 :                     while (ptr < buf_end && x == 0xff) {
    2083      175167 :                         x = *(ptr++);
    2084      175167 :                         skip++;
    2085             :                     }
    2086             : 
    2087             :                     /* 0xFF, 0xFF, ... */
    2088      175167 :                     if (skip > 1) {
    2089           0 :                         copy_data_segment(skip);
    2090             : 
    2091             :                         /* decrement src as it is equal to ptr after the
    2092             :                          * copy_data_segment macro and we might want to
    2093             :                          * copy the current value of x later on */
    2094           0 :                         src--;
    2095             :                     }
    2096             : 
    2097      175167 :                     if (x < 0xd0 || x > 0xd7) {
    2098      175091 :                         copy_data_segment(1);
    2099      175091 :                         if (x)
    2100        2262 :                             break;
    2101             :                     }
    2102             :                 }
    2103             :             }
    2104        2262 :             if (src < ptr)
    2105           0 :                 copy_data_segment(0);
    2106             :         }
    2107             :         #undef copy_data_segment
    2108             : 
    2109        2336 :         *unescaped_buf_ptr  = s->buffer;
    2110        2336 :         *unescaped_buf_size = dst - s->buffer;
    2111        2336 :         memset(s->buffer + *unescaped_buf_size, 0,
    2112             :                AV_INPUT_BUFFER_PADDING_SIZE);
    2113             : 
    2114        2336 :         av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %"PTRDIFF_SPECIFIER" bytes\n",
    2115        2336 :                (buf_end - *buf_ptr) - (dst - s->buffer));
    2116       13555 :     } else if (start_code == SOS && s->ls) {
    2117         205 :         const uint8_t *src = *buf_ptr;
    2118         205 :         uint8_t *dst  = s->buffer;
    2119         205 :         int bit_count = 0;
    2120         205 :         int t = 0, b = 0;
    2121             :         PutBitContext pb;
    2122             : 
    2123             :         /* find marker */
    2124    26357540 :         while (src + t < buf_end) {
    2125    26357335 :             uint8_t x = src[t++];
    2126    26357335 :             if (x == 0xff) {
    2127      443793 :                 while ((src + t < buf_end) && x == 0xff)
    2128      147931 :                     x = src[t++];
    2129      147931 :                 if (x & 0x80) {
    2130         205 :                     t -= FFMIN(2, t);
    2131         205 :                     break;
    2132             :                 }
    2133             :             }
    2134             :         }
    2135         205 :         bit_count = t * 8;
    2136         205 :         init_put_bits(&pb, dst, t);
    2137             : 
    2138             :         /* unescape bitstream */
    2139    26357540 :         while (b < t) {
    2140    26357130 :             uint8_t x = src[b++];
    2141    26357130 :             put_bits(&pb, 8, x);
    2142    26357130 :             if (x == 0xFF && b < t) {
    2143      147726 :                 x = src[b++];
    2144      147726 :                 if (x & 0x80) {
    2145           0 :                     av_log(s->avctx, AV_LOG_WARNING, "Invalid escape sequence\n");
    2146           0 :                     x &= 0x7f;
    2147             :                 }
    2148      147726 :                 put_bits(&pb, 7, x);
    2149      147726 :                 bit_count--;
    2150             :             }
    2151             :         }
    2152         205 :         flush_put_bits(&pb);
    2153             : 
    2154         205 :         *unescaped_buf_ptr  = dst;
    2155         205 :         *unescaped_buf_size = (bit_count + 7) >> 3;
    2156         205 :         memset(s->buffer + *unescaped_buf_size, 0,
    2157             :                AV_INPUT_BUFFER_PADDING_SIZE);
    2158             :     } else {
    2159       13145 :         *unescaped_buf_ptr  = *buf_ptr;
    2160       13145 :         *unescaped_buf_size = buf_end - *buf_ptr;
    2161             :     }
    2162             : 
    2163       15686 :     return start_code;
    2164             : }
    2165             : 
    2166         129 : static void reset_icc_profile(MJpegDecodeContext *s)
    2167             : {
    2168             :     int i;
    2169             : 
    2170         129 :     if (s->iccdata)
    2171           0 :         for (i = 0; i < s->iccnum; i++)
    2172           0 :             av_freep(&s->iccdata[i]);
    2173         129 :     av_freep(&s->iccdata);
    2174         129 :     av_freep(&s->iccdatalens);
    2175             : 
    2176         129 :     s->iccread = 0;
    2177         129 :     s->iccnum  = 0;
    2178         129 : }
    2179             : 
    2180        2511 : int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
    2181             :                           AVPacket *avpkt)
    2182             : {
    2183        2511 :     AVFrame     *frame = data;
    2184        2511 :     const uint8_t *buf = avpkt->data;
    2185        2511 :     int buf_size       = avpkt->size;
    2186        2511 :     MJpegDecodeContext *s = avctx->priv_data;
    2187             :     const uint8_t *buf_end, *buf_ptr;
    2188             :     const uint8_t *unescaped_buf_ptr;
    2189             :     int hshift, vshift;
    2190             :     int unescaped_buf_size;
    2191             :     int start_code;
    2192             :     int i, index;
    2193        2511 :     int ret = 0;
    2194             :     int is16bit;
    2195             : 
    2196        2511 :     av_dict_free(&s->exif_metadata);
    2197        2511 :     av_freep(&s->stereo3d);
    2198        2511 :     s->adobe_transform = -1;
    2199             : 
    2200        2511 :     if (s->iccnum != 0)
    2201           0 :         reset_icc_profile(s);
    2202             : 
    2203        2511 :     buf_ptr = buf;
    2204        2511 :     buf_end = buf + buf_size;
    2205       17995 :     while (buf_ptr < buf_end) {
    2206             :         /* find start next marker */
    2207       15484 :         start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
    2208             :                                           &unescaped_buf_ptr,
    2209             :                                           &unescaped_buf_size);
    2210             :         /* EOF */
    2211       15484 :         if (start_code < 0) {
    2212           5 :             break;
    2213       15479 :         } else if (unescaped_buf_size > INT_MAX / 8) {
    2214           0 :             av_log(avctx, AV_LOG_ERROR,
    2215             :                    "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
    2216             :                    start_code, unescaped_buf_size, buf_size);
    2217           0 :             return AVERROR_INVALIDDATA;
    2218             :         }
    2219       15479 :         av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%"PTRDIFF_SPECIFIER"\n",
    2220             :                start_code, buf_end - buf_ptr);
    2221             : 
    2222       15479 :         ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
    2223             : 
    2224       15479 :         if (ret < 0) {
    2225           0 :             av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
    2226           0 :             goto fail;
    2227             :         }
    2228             : 
    2229       15479 :         s->start_code = start_code;
    2230       15479 :         if (s->avctx->debug & FF_DEBUG_STARTCODE)
    2231           0 :             av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
    2232             : 
    2233             :         /* process markers */
    2234       15479 :         if (start_code >= 0xd0 && start_code <= 0xd7) {
    2235           2 :             av_log(avctx, AV_LOG_DEBUG,
    2236             :                    "restart marker: %d\n", start_code & 0x0f);
    2237             :             /* APP fields */
    2238       15477 :         } else if (start_code >= APP0 && start_code <= APP15) {
    2239         264 :             if ((ret = mjpeg_decode_app(s)) < 0)
    2240           0 :                 av_log(avctx, AV_LOG_ERROR, "unable to decode APP fields: %s\n",
    2241           0 :                        av_err2str(ret));
    2242             :             /* Comment */
    2243       15345 :         } else if (start_code == COM) {
    2244         209 :             ret = mjpeg_decode_com(s);
    2245         209 :             if (ret < 0)
    2246           0 :                 return ret;
    2247       15136 :         } else if (start_code == DQT) {
    2248        2478 :             ret = ff_mjpeg_decode_dqt(s);
    2249        2478 :             if (ret < 0)
    2250           0 :                 return ret;
    2251             :         }
    2252             : 
    2253       15479 :         ret = -1;
    2254             : 
    2255             :         if (!CONFIG_JPEGLS_DECODER &&
    2256             :             (start_code == SOF48 || start_code == LSE)) {
    2257             :             av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
    2258             :             return AVERROR(ENOSYS);
    2259             :         }
    2260             : 
    2261       15479 :         if (avctx->skip_frame == AVDISCARD_ALL) {
    2262         447 :             switch(start_code) {
    2263         216 :             case SOF0:
    2264             :             case SOF1:
    2265             :             case SOF2:
    2266             :             case SOF3:
    2267             :             case SOF48:
    2268             :             case SOI:
    2269             :             case SOS:
    2270             :             case EOI:
    2271         216 :                 break;
    2272         231 :             default:
    2273         231 :                 goto skip;
    2274             :             }
    2275       15032 :         }
    2276             : 
    2277       15248 :         switch (start_code) {
    2278        2510 :         case SOI:
    2279        2510 :             s->restart_interval = 0;
    2280        2510 :             s->restart_count    = 0;
    2281             :             /* nothing to do on SOI */
    2282        2510 :             break;
    2283        2508 :         case DHT:
    2284        2508 :             if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
    2285           0 :                 av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
    2286           0 :                 goto fail;
    2287             :             }
    2288        2508 :             break;
    2289        2100 :         case SOF0:
    2290             :         case SOF1:
    2291        2100 :             s->lossless    = 0;
    2292        2100 :             s->ls          = 0;
    2293        2100 :             s->progressive = 0;
    2294        2100 :             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
    2295           0 :                 goto fail;
    2296        2100 :             break;
    2297           0 :         case SOF2:
    2298           0 :             s->lossless    = 0;
    2299           0 :             s->ls          = 0;
    2300           0 :             s->progressive = 1;
    2301           0 :             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
    2302           0 :                 goto fail;
    2303           0 :             break;
    2304         205 :         case SOF3:
    2305         205 :             s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
    2306         205 :             s->lossless    = 1;
    2307         205 :             s->ls          = 0;
    2308         205 :             s->progressive = 0;
    2309         205 :             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
    2310           0 :                 goto fail;
    2311         205 :             break;
    2312         205 :         case SOF48:
    2313         205 :             s->avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
    2314         205 :             s->lossless    = 1;
    2315         205 :             s->ls          = 1;
    2316         205 :             s->progressive = 0;
    2317         205 :             if ((ret = ff_mjpeg_decode_sof(s)) < 0)
    2318           0 :                 goto fail;
    2319         205 :             break;
    2320           0 :         case LSE:
    2321           0 :             if (!CONFIG_JPEGLS_DECODER ||
    2322             :                 (ret = ff_jpegls_decode_lse(s)) < 0)
    2323           0 :                 goto fail;
    2324           0 :             break;
    2325             :         case EOI:
    2326        2510 : eoi_parser:
    2327        2510 :             if (avctx->skip_frame != AVDISCARD_ALL && s->progressive && s->cur_scan && s->got_picture)
    2328           0 :                 mjpeg_idct_scan_progressive_ac(s);
    2329        2510 :             s->cur_scan = 0;
    2330        2510 :             if (!s->got_picture) {
    2331           0 :                 av_log(avctx, AV_LOG_WARNING,
    2332             :                        "Found EOI before any SOF, ignoring\n");
    2333           0 :                 break;
    2334             :             }
    2335        2510 :             if (s->interlaced) {
    2336           0 :                 s->bottom_field ^= 1;
    2337             :                 /* if not bottom field, do not output image yet */
    2338           0 :                 if (s->bottom_field == !s->interlace_polarity)
    2339           0 :                     break;
    2340             :             }
    2341        2510 :             if (avctx->skip_frame == AVDISCARD_ALL) {
    2342          55 :                 s->got_picture = 0;
    2343          55 :                 goto the_end_no_picture;
    2344             :             }
    2345        2455 :             if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
    2346           0 :                 return ret;
    2347        2455 :             *got_frame = 1;
    2348        2455 :             s->got_picture = 0;
    2349             : 
    2350        2455 :             if (!s->lossless) {
    2351        2050 :                 int qp = FFMAX3(s->qscale[0],
    2352             :                                 s->qscale[1],
    2353             :                                 s->qscale[2]);
    2354        2050 :                 int qpw = (s->width + 15) / 16;
    2355        2050 :                 AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
    2356        2050 :                 if (qp_table_buf) {
    2357        2050 :                     memset(qp_table_buf->data, qp, qpw);
    2358        2050 :                     av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
    2359             :                 }
    2360             : 
    2361        2050 :                 if(avctx->debug & FF_DEBUG_QP)
    2362           0 :                     av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
    2363             :             }
    2364             : 
    2365        2455 :             goto the_end;
    2366        2510 :         case SOS:
    2367        2510 :             s->cur_scan++;
    2368        2510 :             if (avctx->skip_frame == AVDISCARD_ALL) {
    2369          55 :                 skip_bits(&s->gb, get_bits_left(&s->gb));
    2370          55 :                 break;
    2371             :             }
    2372             : 
    2373        2455 :             if ((ret = ff_mjpeg_decode_sos(s, NULL, 0, NULL)) < 0 &&
    2374           0 :                 (avctx->err_recognition & AV_EF_EXPLODE))
    2375           0 :                 goto fail;
    2376        2455 :             break;
    2377           0 :         case DRI:
    2378           0 :             if ((ret = mjpeg_decode_dri(s)) < 0)
    2379           0 :                 return ret;
    2380           0 :             break;
    2381           0 :         case SOF5:
    2382             :         case SOF6:
    2383             :         case SOF7:
    2384             :         case SOF9:
    2385             :         case SOF10:
    2386             :         case SOF11:
    2387             :         case SOF13:
    2388             :         case SOF14:
    2389             :         case SOF15:
    2390             :         case JPG:
    2391           0 :             av_log(avctx, AV_LOG_ERROR,
    2392             :                    "mjpeg: unsupported coding type (%x)\n", start_code);
    2393           0 :             break;
    2394             :         }
    2395             : 
    2396       12973 : skip:
    2397             :         /* eof process start code */
    2398       12973 :         buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
    2399       25946 :         av_log(avctx, AV_LOG_DEBUG,
    2400             :                "marker parser used %d bytes (%d bits)\n",
    2401       25946 :                (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
    2402             :     }
    2403           5 :     if (s->got_picture && s->cur_scan) {
    2404           4 :         av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
    2405           4 :         goto eoi_parser;
    2406             :     }
    2407           1 :     av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
    2408           1 :     return AVERROR_INVALIDDATA;
    2409           0 : fail:
    2410           0 :     s->got_picture = 0;
    2411           0 :     return ret;
    2412        2455 : the_end:
    2413             : 
    2414        2455 :     is16bit = av_pix_fmt_desc_get(s->avctx->pix_fmt)->comp[0].step > 1;
    2415             : 
    2416        2455 :     if (AV_RB32(s->upscale_h)) {
    2417             :         int p;
    2418           0 :         av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
    2419             :                    avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
    2420             :                    avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
    2421             :                    avctx->pix_fmt == AV_PIX_FMT_YUV440P  ||
    2422             :                    avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||
    2423             :                    avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
    2424             :                    avctx->pix_fmt == AV_PIX_FMT_YUV420P  ||
    2425             :                    avctx->pix_fmt == AV_PIX_FMT_YUV420P16||
    2426             :                    avctx->pix_fmt == AV_PIX_FMT_YUVA420P  ||
    2427             :                    avctx->pix_fmt == AV_PIX_FMT_YUVA420P16||
    2428             :                    avctx->pix_fmt == AV_PIX_FMT_GBRP     ||
    2429             :                    avctx->pix_fmt == AV_PIX_FMT_GBRAP
    2430             :                   );
    2431           0 :         ret = av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
    2432           0 :         if (ret)
    2433           0 :             return ret;
    2434             : 
    2435           0 :         av_assert0(s->nb_components == av_pix_fmt_count_planes(s->picture_ptr->format));
    2436           0 :         for (p = 0; p<s->nb_components; p++) {
    2437           0 :             uint8_t *line = s->picture_ptr->data[p];
    2438           0 :             int w = s->width;
    2439           0 :             int h = s->height;
    2440           0 :             if (!s->upscale_h[p])
    2441           0 :                 continue;
    2442           0 :             if (p==1 || p==2) {
    2443           0 :                 w = AV_CEIL_RSHIFT(w, hshift);
    2444           0 :                 h = AV_CEIL_RSHIFT(h, vshift);
    2445             :             }
    2446           0 :             if (s->upscale_v[p])
    2447           0 :                 h = (h+1)>>1;
    2448           0 :             av_assert0(w > 0);
    2449           0 :             for (i = 0; i < h; i++) {
    2450           0 :                 if (s->upscale_h[p] == 1) {
    2451           0 :                     if (is16bit) ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 2];
    2452           0 :                     else                      line[w - 1] = line[(w - 1) / 2];
    2453           0 :                     for (index = w - 2; index > 0; index--) {
    2454           0 :                         if (is16bit)
    2455           0 :                             ((uint16_t*)line)[index] = (((uint16_t*)line)[index / 2] + ((uint16_t*)line)[(index + 1) / 2]) >> 1;
    2456             :                         else
    2457           0 :                             line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
    2458             :                     }
    2459           0 :                 } else if (s->upscale_h[p] == 2) {
    2460           0 :                     if (is16bit) {
    2461           0 :                         ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 3];
    2462           0 :                         if (w > 1)
    2463           0 :                             ((uint16_t*)line)[w - 2] = ((uint16_t*)line)[w - 1];
    2464             :                     } else {
    2465           0 :                         line[w - 1] = line[(w - 1) / 3];
    2466           0 :                         if (w > 1)
    2467           0 :                             line[w - 2] = line[w - 1];
    2468             :                     }
    2469           0 :                     for (index = w - 3; index > 0; index--) {
    2470           0 :                         line[index] = (line[index / 3] + line[(index + 1) / 3] + line[(index + 2) / 3] + 1) / 3;
    2471             :                     }
    2472             :                 }
    2473           0 :                 line += s->linesize[p];
    2474             :             }
    2475             :         }
    2476             :     }
    2477        2455 :     if (AV_RB32(s->upscale_v)) {
    2478             :         int p;
    2479           0 :         av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
    2480             :                    avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
    2481             :                    avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
    2482             :                    avctx->pix_fmt == AV_PIX_FMT_YUV422P  ||
    2483             :                    avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
    2484             :                    avctx->pix_fmt == AV_PIX_FMT_YUV420P  ||
    2485             :                    avctx->pix_fmt == AV_PIX_FMT_YUV440P  ||
    2486             :                    avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
    2487             :                    avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||
    2488             :                    avctx->pix_fmt == AV_PIX_FMT_YUVA420P  ||
    2489             :                    avctx->pix_fmt == AV_PIX_FMT_YUVA420P16||
    2490             :                    avctx->pix_fmt == AV_PIX_FMT_GBRP     ||
    2491             :                    avctx->pix_fmt == AV_PIX_FMT_GBRAP
    2492             :                    );
    2493           0 :         ret = av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
    2494           0 :         if (ret)
    2495           0 :             return ret;
    2496             : 
    2497           0 :         av_assert0(s->nb_components == av_pix_fmt_count_planes(s->picture_ptr->format));
    2498           0 :         for (p = 0; p < s->nb_components; p++) {
    2499             :             uint8_t *dst;
    2500           0 :             int w = s->width;
    2501           0 :             int h = s->height;
    2502           0 :             if (!s->upscale_v[p])
    2503           0 :                 continue;
    2504           0 :             if (p==1 || p==2) {
    2505           0 :                 w = AV_CEIL_RSHIFT(w, hshift);
    2506           0 :                 h = AV_CEIL_RSHIFT(h, vshift);
    2507             :             }
    2508           0 :             dst = &((uint8_t *)s->picture_ptr->data[p])[(h - 1) * s->linesize[p]];
    2509           0 :             for (i = h - 1; i; i--) {
    2510           0 :                 uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[p])[i / 2 * s->linesize[p]];
    2511           0 :                 uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[p])[(i + 1) / 2 * s->linesize[p]];
    2512           0 :                 if (src1 == src2 || i == h - 1) {
    2513           0 :                     memcpy(dst, src1, w);
    2514             :                 } else {
    2515           0 :                     for (index = 0; index < w; index++)
    2516           0 :                         dst[index] = (src1[index] + src2[index]) >> 1;
    2517             :                 }
    2518           0 :                 dst -= s->linesize[p];
    2519             :             }
    2520             :         }
    2521             :     }
    2522        2455 :     if (s->flipped && !s->rgb) {
    2523             :         int j;
    2524         367 :         ret = av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
    2525         367 :         if (ret)
    2526           0 :             return ret;
    2527             : 
    2528         367 :         av_assert0(s->nb_components == av_pix_fmt_count_planes(s->picture_ptr->format));
    2529        1468 :         for (index=0; index<s->nb_components; index++) {
    2530        1101 :             uint8_t *dst = s->picture_ptr->data[index];
    2531        1101 :             int w = s->picture_ptr->width;
    2532        1101 :             int h = s->picture_ptr->height;
    2533        1101 :             if(index && index<3){
    2534         734 :                 w = AV_CEIL_RSHIFT(w, hshift);
    2535         734 :                 h = AV_CEIL_RSHIFT(h, vshift);
    2536             :             }
    2537        1101 :             if(dst){
    2538        1101 :                 uint8_t *dst2 = dst + s->picture_ptr->linesize[index]*(h-1);
    2539       66408 :                 for (i=0; i<h/2; i++) {
    2540    14088753 :                     for (j=0; j<w; j++)
    2541    14023446 :                         FFSWAP(int, dst[j], dst2[j]);
    2542       65307 :                     dst  += s->picture_ptr->linesize[index];
    2543       65307 :                     dst2 -= s->picture_ptr->linesize[index];
    2544             :                 }
    2545             :             }
    2546             :         }
    2547             :     }
    2548        2455 :     if (s->adobe_transform == 0 && s->avctx->pix_fmt == AV_PIX_FMT_GBRAP) {
    2549           0 :         int w = s->picture_ptr->width;
    2550           0 :         int h = s->picture_ptr->height;
    2551           0 :         av_assert0(s->nb_components == 4);
    2552           0 :         for (i=0; i<h; i++) {
    2553             :             int j;
    2554             :             uint8_t *dst[4];
    2555           0 :             for (index=0; index<4; index++) {
    2556           0 :                 dst[index] =   s->picture_ptr->data[index]
    2557           0 :                              + s->picture_ptr->linesize[index]*i;
    2558             :             }
    2559           0 :             for (j=0; j<w; j++) {
    2560           0 :                 int k = dst[3][j];
    2561           0 :                 int r = dst[0][j] * k;
    2562           0 :                 int g = dst[1][j] * k;
    2563           0 :                 int b = dst[2][j] * k;
    2564           0 :                 dst[0][j] = g*257 >> 16;
    2565           0 :                 dst[1][j] = b*257 >> 16;
    2566           0 :                 dst[2][j] = r*257 >> 16;
    2567           0 :                 dst[3][j] = 255;
    2568             :             }
    2569             :         }
    2570             :     }
    2571        2455 :     if (s->adobe_transform == 2 && s->avctx->pix_fmt == AV_PIX_FMT_YUVA444P) {
    2572           0 :         int w = s->picture_ptr->width;
    2573           0 :         int h = s->picture_ptr->height;
    2574           0 :         av_assert0(s->nb_components == 4);
    2575           0 :         for (i=0; i<h; i++) {
    2576             :             int j;
    2577             :             uint8_t *dst[4];
    2578           0 :             for (index=0; index<4; index++) {
    2579           0 :                 dst[index] =   s->picture_ptr->data[index]
    2580           0 :                              + s->picture_ptr->linesize[index]*i;
    2581             :             }
    2582           0 :             for (j=0; j<w; j++) {
    2583           0 :                 int k = dst[3][j];
    2584           0 :                 int r = (255 - dst[0][j]) * k;
    2585           0 :                 int g = (128 - dst[1][j]) * k;
    2586           0 :                 int b = (128 - dst[2][j]) * k;
    2587           0 :                 dst[0][j] = r*257 >> 16;
    2588           0 :                 dst[1][j] = (g*257 >> 16) + 128;
    2589           0 :                 dst[2][j] = (b*257 >> 16) + 128;
    2590           0 :                 dst[3][j] = 255;
    2591             :             }
    2592             :         }
    2593             :     }
    2594             : 
    2595        2455 :     if (s->stereo3d) {
    2596           0 :         AVStereo3D *stereo = av_stereo3d_create_side_data(data);
    2597           0 :         if (stereo) {
    2598           0 :             stereo->type  = s->stereo3d->type;
    2599           0 :             stereo->flags = s->stereo3d->flags;
    2600             :         }
    2601           0 :         av_freep(&s->stereo3d);
    2602             :     }
    2603             : 
    2604        2455 :     if (s->iccnum != 0 && s->iccnum == s->iccread) {
    2605             :         AVFrameSideData *sd;
    2606           0 :         size_t offset = 0;
    2607           0 :         int total_size = 0;
    2608             :         int i;
    2609             : 
    2610             :         /* Sum size of all parts. */
    2611           0 :         for (i = 0; i < s->iccnum; i++)
    2612           0 :             total_size += s->iccdatalens[i];
    2613             : 
    2614           0 :         sd = av_frame_new_side_data(data, AV_FRAME_DATA_ICC_PROFILE, total_size);
    2615           0 :         if (!sd) {
    2616           0 :             av_log(s->avctx, AV_LOG_ERROR, "Could not allocate frame side data\n");
    2617           0 :             return AVERROR(ENOMEM);
    2618             :         }
    2619             : 
    2620             :         /* Reassemble the parts, which are now in-order. */
    2621           0 :         for (i = 0; i < s->iccnum; i++) {
    2622           0 :             memcpy(sd->data + offset, s->iccdata[i], s->iccdatalens[i]);
    2623           0 :             offset += s->iccdatalens[i];
    2624             :         }
    2625             :     }
    2626             : 
    2627        2455 :     av_dict_copy(&((AVFrame *) data)->metadata, s->exif_metadata, 0);
    2628        2455 :     av_dict_free(&s->exif_metadata);
    2629             : 
    2630        2510 : the_end_no_picture:
    2631        2510 :     av_log(avctx, AV_LOG_DEBUG, "decode frame unused %"PTRDIFF_SPECIFIER" bytes\n",
    2632             :            buf_end - buf_ptr);
    2633             : //  return buf_end - buf_ptr;
    2634        2510 :     return buf_ptr - buf;
    2635             : }
    2636             : 
    2637         129 : av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
    2638             : {
    2639         129 :     MJpegDecodeContext *s = avctx->priv_data;
    2640             :     int i, j;
    2641             : 
    2642         129 :     if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
    2643           0 :         av_log(avctx, AV_LOG_INFO, "Single field\n");
    2644             :     }
    2645             : 
    2646         129 :     if (s->picture) {
    2647         127 :         av_frame_free(&s->picture);
    2648         127 :         s->picture_ptr = NULL;
    2649           2 :     } else if (s->picture_ptr)
    2650           0 :         av_frame_unref(s->picture_ptr);
    2651             : 
    2652         129 :     av_freep(&s->buffer);
    2653         129 :     av_freep(&s->stereo3d);
    2654         129 :     av_freep(&s->ljpeg_buffer);
    2655         129 :     s->ljpeg_buffer_size = 0;
    2656             : 
    2657         516 :     for (i = 0; i < 3; i++) {
    2658        1935 :         for (j = 0; j < 4; j++)
    2659        1548 :             ff_free_vlc(&s->vlcs[i][j]);
    2660             :     }
    2661         645 :     for (i = 0; i < MAX_COMPONENTS; i++) {
    2662         516 :         av_freep(&s->blocks[i]);
    2663         516 :         av_freep(&s->last_nnz[i]);
    2664             :     }
    2665         129 :     av_dict_free(&s->exif_metadata);
    2666             : 
    2667         129 :     reset_icc_profile(s);
    2668             : 
    2669         129 :     return 0;
    2670             : }
    2671             : 
    2672           0 : static void decode_flush(AVCodecContext *avctx)
    2673             : {
    2674           0 :     MJpegDecodeContext *s = avctx->priv_data;
    2675           0 :     s->got_picture = 0;
    2676           0 : }
    2677             : 
    2678             : #if CONFIG_MJPEG_DECODER
    2679             : #define OFFSET(x) offsetof(MJpegDecodeContext, x)
    2680             : #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
    2681             : static const AVOption options[] = {
    2682             :     { "extern_huff", "Use external huffman table.",
    2683             :       OFFSET(extern_huff), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
    2684             :     { NULL },
    2685             : };
    2686             : 
    2687             : static const AVClass mjpegdec_class = {
    2688             :     .class_name = "MJPEG decoder",
    2689             :     .item_name  = av_default_item_name,
    2690             :     .option     = options,
    2691             :     .version    = LIBAVUTIL_VERSION_INT,
    2692             : };
    2693             : 
    2694             : AVCodec ff_mjpeg_decoder = {
    2695             :     .name           = "mjpeg",
    2696             :     .long_name      = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
    2697             :     .type           = AVMEDIA_TYPE_VIDEO,
    2698             :     .id             = AV_CODEC_ID_MJPEG,
    2699             :     .priv_data_size = sizeof(MJpegDecodeContext),
    2700             :     .init           = ff_mjpeg_decode_init,
    2701             :     .close          = ff_mjpeg_decode_end,
    2702             :     .decode         = ff_mjpeg_decode_frame,
    2703             :     .flush          = decode_flush,
    2704             :     .capabilities   = AV_CODEC_CAP_DR1,
    2705             :     .max_lowres     = 3,
    2706             :     .priv_class     = &mjpegdec_class,
    2707             :     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
    2708             :                       FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
    2709             : };
    2710             : #endif
    2711             : #if CONFIG_THP_DECODER
    2712             : AVCodec ff_thp_decoder = {
    2713             :     .name           = "thp",
    2714             :     .long_name      = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
    2715             :     .type           = AVMEDIA_TYPE_VIDEO,
    2716             :     .id             = AV_CODEC_ID_THP,
    2717             :     .priv_data_size = sizeof(MJpegDecodeContext),
    2718             :     .init           = ff_mjpeg_decode_init,
    2719             :     .close          = ff_mjpeg_decode_end,
    2720             :     .decode         = ff_mjpeg_decode_frame,
    2721             :     .flush          = decode_flush,
    2722             :     .capabilities   = AV_CODEC_CAP_DR1,
    2723             :     .max_lowres     = 3,
    2724             :     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
    2725             : };
    2726             : #endif

Generated by: LCOV version 1.13