Coverage Report

Created: 2026-04-01 07:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/mjpegdec.c
Line
Count
Source
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 "config_components.h"
34
35
#include "libavutil/attributes.h"
36
#include "libavutil/imgutils.h"
37
#include "libavutil/avassert.h"
38
#include "libavutil/mem.h"
39
#include "libavutil/opt.h"
40
#include "avcodec.h"
41
#include "blockdsp.h"
42
#include "codec_internal.h"
43
#include "copy_block.h"
44
#include "decode.h"
45
#include "exif.h"
46
#include "hwaccel_internal.h"
47
#include "hwconfig.h"
48
#include "idctdsp.h"
49
#include "internal.h"
50
#include "jpegtables.h"
51
#include "mjpeg.h"
52
#include "mjpegdec.h"
53
#include "jpeglsdec.h"
54
#include "profiles.h"
55
#include "put_bits.h"
56
57
58
static void mjpeg_find_raw_scan_data(MJpegDecodeContext *s,
59
                                     const uint8_t **pbuf_ptr, size_t *pbuf_size);
60
61
static int init_default_huffman_tables(MJpegDecodeContext *s)
62
76.6k
{
63
76.6k
    static const struct {
64
76.6k
        int class;
65
76.6k
        int index;
66
76.6k
        const uint8_t *bits;
67
76.6k
        const uint8_t *values;
68
76.6k
        int length;
69
76.6k
    } ht[] = {
70
76.6k
        { 0, 0, ff_mjpeg_bits_dc_luminance,
71
76.6k
                ff_mjpeg_val_dc, 12 },
72
76.6k
        { 0, 1, ff_mjpeg_bits_dc_chrominance,
73
76.6k
                ff_mjpeg_val_dc, 12 },
74
76.6k
        { 1, 0, ff_mjpeg_bits_ac_luminance,
75
76.6k
                ff_mjpeg_val_ac_luminance,   162 },
76
76.6k
        { 1, 1, ff_mjpeg_bits_ac_chrominance,
77
76.6k
                ff_mjpeg_val_ac_chrominance, 162 },
78
76.6k
        { 2, 0, ff_mjpeg_bits_ac_luminance,
79
76.6k
                ff_mjpeg_val_ac_luminance,   162 },
80
76.6k
        { 2, 1, ff_mjpeg_bits_ac_chrominance,
81
76.6k
                ff_mjpeg_val_ac_chrominance, 162 },
82
76.6k
    };
83
76.6k
    int i, ret;
84
85
536k
    for (i = 0; i < FF_ARRAY_ELEMS(ht); i++) {
86
460k
        ff_vlc_free(&s->vlcs[ht[i].class][ht[i].index]);
87
460k
        ret = ff_mjpeg_build_vlc(&s->vlcs[ht[i].class][ht[i].index],
88
460k
                                 ht[i].bits, ht[i].values,
89
460k
                                 ht[i].class == 1, s->avctx);
90
460k
        if (ret < 0)
91
0
            return ret;
92
93
460k
        if (ht[i].class < 2) {
94
306k
            memcpy(s->raw_huffman_lengths[ht[i].class][ht[i].index],
95
306k
                   ht[i].bits + 1, 16);
96
306k
            memcpy(s->raw_huffman_values[ht[i].class][ht[i].index],
97
306k
                   ht[i].values, ht[i].length);
98
306k
        }
99
460k
    }
100
101
76.6k
    return 0;
102
76.6k
}
103
104
static void parse_avid(MJpegDecodeContext *s, uint8_t *buf, int len)
105
11.6k
{
106
11.6k
    if (len > 12 && buf[12] == 1) /* 1 - NTSC */
107
2.28k
        s->interlace_polarity = 1;
108
11.6k
    if (len > 12 && buf[12] == 2) /* 2 - PAL */
109
3.20k
        s->interlace_polarity = 0;
110
11.6k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
111
0
        av_log(s->avctx, AV_LOG_INFO, "AVID: len:%d %d\n", len, len > 12 ? buf[12] : -1);
112
11.6k
}
113
114
static void init_idct(AVCodecContext *avctx)
115
651k
{
116
651k
    MJpegDecodeContext *s = avctx->priv_data;
117
118
651k
    ff_idctdsp_init(&s->idsp, avctx);
119
651k
    ff_permute_scantable(s->permutated_scantable, ff_zigzag_direct,
120
651k
                         s->idsp.idct_permutation);
121
651k
}
122
123
av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
124
76.6k
{
125
76.6k
    MJpegDecodeContext *s = avctx->priv_data;
126
76.6k
    int ret;
127
128
76.6k
    if (!s->picture_ptr) {
129
71.5k
        s->picture = av_frame_alloc();
130
71.5k
        if (!s->picture)
131
0
            return AVERROR(ENOMEM);
132
71.5k
        s->picture_ptr = s->picture;
133
71.5k
    }
134
135
76.6k
    s->avctx = avctx;
136
76.6k
    ff_blockdsp_init(&s->bdsp);
137
76.6k
    init_idct(avctx);
138
76.6k
    s->buffer_size   = 0;
139
76.6k
    s->buffer        = NULL;
140
76.6k
    s->first_picture = 1;
141
76.6k
    s->got_picture   = 0;
142
76.6k
    s->orig_height    = avctx->coded_height;
143
76.6k
    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
144
76.6k
    avctx->colorspace = AVCOL_SPC_BT470BG;
145
76.6k
    s->hwaccel_pix_fmt = s->hwaccel_sw_pix_fmt = AV_PIX_FMT_NONE;
146
147
76.6k
    if ((ret = init_default_huffman_tables(s)) < 0)
148
0
        return ret;
149
150
76.6k
#if FF_API_MJPEG_EXTERN_HUFF
151
76.6k
    if (s->extern_huff && avctx->extradata) {
152
0
        av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
153
0
        bytestream2_init(&s->gB, avctx->extradata, avctx->extradata_size);
154
0
        if (ff_mjpeg_decode_dht(s)) {
155
0
            av_log(avctx, AV_LOG_ERROR,
156
0
                   "error using external huffman table, switching back to internal\n");
157
0
            if ((ret = init_default_huffman_tables(s)) < 0)
158
0
                return ret;
159
0
        }
160
0
    }
161
76.6k
#endif
162
76.6k
    if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
163
0
        s->interlace_polarity = 1;           /* bottom field first */
164
0
        av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
165
76.6k
    } else if (avctx->field_order == AV_FIELD_UNKNOWN) {
166
76.6k
        if (avctx->codec_tag == AV_RL32("MJPG"))
167
30
            s->interlace_polarity = 1;
168
76.6k
    }
169
170
76.6k
    if (avctx->codec_id == AV_CODEC_ID_SMVJPEG) {
171
5.05k
        if (avctx->extradata_size >= 4)
172
4.87k
            s->smv_frames_per_jpeg = AV_RL32(avctx->extradata);
173
174
5.05k
        if (s->smv_frames_per_jpeg <= 0) {
175
193
            av_log(avctx, AV_LOG_ERROR, "Invalid number of frames per jpeg.\n");
176
193
            return AVERROR_INVALIDDATA;
177
193
        }
178
179
4.86k
        s->smv_frame = av_frame_alloc();
180
4.86k
        if (!s->smv_frame)
181
0
            return AVERROR(ENOMEM);
182
71.6k
    } else if (avctx->extradata_size > 8
183
1.09k
        && AV_RL32(avctx->extradata) == 0x2C
184
91
        && AV_RL32(avctx->extradata + 4) == 0x18) {
185
35
        parse_avid(s, avctx->extradata, avctx->extradata_size);
186
35
    }
187
188
76.5k
    if (avctx->codec->id == AV_CODEC_ID_AMV)
189
6.87k
        s->flipped = 1;
190
191
76.5k
    return 0;
192
76.6k
}
193
194
195
static int mjpeg_parse_len(MJpegDecodeContext *s, int *plen, const char *name)
196
8.91M
{
197
8.91M
    int len = bytestream2_get_be16u(&s->gB);
198
8.91M
    if (len < 2 || bytestream2_get_bytes_left(&s->gB) < (len - 2)) {
199
990k
        av_log(s->avctx, AV_LOG_ERROR, "%s: invalid len %d\n", name, len);
200
990k
        return AVERROR_INVALIDDATA;
201
990k
    }
202
7.92M
    *plen = len - 2;
203
7.92M
    return 0;
204
8.91M
}
205
206
/* quantize tables */
207
int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
208
1.21M
{
209
1.21M
    int len, index, i;
210
211
1.21M
    int ret = mjpeg_parse_len(s, &len, "dqt");
212
1.21M
    if (ret < 0)
213
37.2k
        return ret;
214
215
3.44M
    while (len >= 65) {
216
2.28M
        uint8_t b = bytestream2_get_byteu(&s->gB);
217
2.28M
        int pr = b >> 4;
218
2.28M
        if (pr > 1) {
219
4.28k
            av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
220
4.28k
            return AVERROR_INVALIDDATA;
221
4.28k
        }
222
2.28M
        if (len < (1 + 64 * (1 + pr)))
223
4.29k
            return AVERROR_INVALIDDATA;
224
2.27M
        index = b & 0x0F;
225
2.27M
        if (index >= 4)
226
2.00k
            return AVERROR_INVALIDDATA;
227
2.27M
        av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
228
        /* read quant table */
229
147M
        for (i = 0; i < 64; i++) {
230
145M
            s->quant_matrixes[index][i] = pr ? bytestream2_get_be16u(&s->gB) : bytestream2_get_byteu(&s->gB);
231
145M
            if (s->quant_matrixes[index][i] == 0) {
232
47.0M
                int log_level = s->avctx->err_recognition & AV_EF_EXPLODE ? AV_LOG_ERROR : AV_LOG_WARNING;
233
47.0M
                av_log(s->avctx, log_level, "dqt: 0 quant value\n");
234
47.0M
                if (s->avctx->err_recognition & AV_EF_EXPLODE)
235
10.0k
                    return AVERROR_INVALIDDATA;
236
47.0M
            }
237
145M
        }
238
239
        // XXX FIXME fine-tune, and perhaps add dc too
240
2.26M
        s->qscale[index] = FFMAX(s->quant_matrixes[index][1],
241
2.26M
                                 s->quant_matrixes[index][8]) >> 1;
242
2.26M
        av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
243
2.26M
               index, s->qscale[index]);
244
2.26M
        len -= 1 + 64 * (1 + pr);
245
2.26M
    }
246
1.15M
    return 0;
247
1.17M
}
248
249
/* decode huffman tables and build VLC decoders */
250
int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
251
819k
{
252
819k
    int len, index, i, class, n, v;
253
819k
    uint8_t bits_table[17];
254
819k
    uint8_t val_table[256];
255
819k
    int ret = 0;
256
257
819k
    ret = mjpeg_parse_len(s, &len, "dht");
258
819k
    if (ret < 0)
259
19.9k
        return ret;
260
261
3.73M
    while (len > 0) {
262
2.97M
        if (len < 17)
263
12.1k
            return AVERROR_INVALIDDATA;
264
2.95M
        uint8_t b = bytestream2_get_byteu(&s->gB);
265
2.95M
        class = b >> 4;
266
2.95M
        if (class >= 2)
267
3.92k
            return AVERROR_INVALIDDATA;
268
2.95M
        index = b & 0x0F;
269
2.95M
        if (index >= 4)
270
3.59k
            return AVERROR_INVALIDDATA;
271
2.95M
        n = 0;
272
50.1M
        for (i = 1; i <= 16; i++) {
273
47.2M
            bits_table[i] = bytestream2_get_byteu(&s->gB);
274
47.2M
            n += bits_table[i];
275
47.2M
        }
276
2.95M
        len -= 17;
277
2.95M
        if (len < n || n > 256)
278
8.08k
            return AVERROR_INVALIDDATA;
279
280
250M
        for (i = 0; i < n; i++) {
281
247M
            v = bytestream2_get_byteu(&s->gB);
282
247M
            val_table[i] = v;
283
247M
        }
284
2.94M
        len -= n;
285
286
        /* build VLC and flush previous vlc if present */
287
2.94M
        ff_vlc_free(&s->vlcs[class][index]);
288
2.94M
        av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
289
2.94M
               class, index, n);
290
2.94M
        if ((ret = ff_mjpeg_build_vlc(&s->vlcs[class][index], bits_table,
291
2.94M
                                      val_table, class > 0, s->avctx)) < 0)
292
3.80k
            return ret;
293
294
2.93M
        if (class > 0) {
295
1.46M
            ff_vlc_free(&s->vlcs[2][index]);
296
1.46M
            if ((ret = ff_mjpeg_build_vlc(&s->vlcs[2][index], bits_table,
297
1.46M
                                          val_table, 0, s->avctx)) < 0)
298
0
                return ret;
299
1.46M
        }
300
301
49.9M
        for (i = 0; i < 16; i++)
302
47.0M
            s->raw_huffman_lengths[class][index][i] = bits_table[i + 1];
303
755M
        for (i = 0; i < 256; i++)
304
752M
            s->raw_huffman_values[class][index][i] = val_table[i];
305
2.93M
    }
306
768k
    return 0;
307
799k
}
308
309
int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
310
2.59M
{
311
2.59M
    int len, nb_components, i, width, height, bits, ret, size_change;
312
2.59M
    unsigned pix_fmt_id;
313
2.59M
    int h_count[MAX_COMPONENTS] = { 0 };
314
2.59M
    int v_count[MAX_COMPONENTS] = { 0 };
315
316
2.59M
    s->cur_scan = 0;
317
2.59M
    memset(s->upscale_h, 0, sizeof(s->upscale_h));
318
2.59M
    memset(s->upscale_v, 0, sizeof(s->upscale_v));
319
320
2.59M
    ret = mjpeg_parse_len(s, &len, "sof");
321
2.59M
    if (ret < 0)
322
101k
        return ret;
323
2.49M
    if (len < 6)
324
3.12k
        return AVERROR_INVALIDDATA;
325
2.49M
    bits = bytestream2_get_byteu(&s->gB);
326
327
2.49M
    if (bits > 16 || bits < 1) {
328
14.8k
        av_log(s->avctx, AV_LOG_ERROR, "bits %d is invalid\n", bits);
329
14.8k
        return AVERROR_INVALIDDATA;
330
14.8k
    }
331
332
2.47M
    if (s->avctx->bits_per_raw_sample != bits) {
333
574k
        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);
334
574k
        s->avctx->bits_per_raw_sample = bits;
335
574k
        init_idct(s->avctx);
336
574k
    }
337
2.47M
    if (s->pegasus_rct)
338
70.8k
        bits = 9;
339
2.47M
    if (bits == 9 && !s->pegasus_rct)
340
103k
        s->rct  = 1;    // FIXME ugly
341
342
2.47M
    if (s->lossless && s->avctx->lowres) {
343
10.9k
        av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
344
10.9k
        return AVERROR(ENOSYS);
345
10.9k
    }
346
347
2.46M
    height = bytestream2_get_be16u(&s->gB);
348
2.46M
    width  = bytestream2_get_be16u(&s->gB);
349
350
    // HACK for odd_height.mov
351
2.46M
    if (s->interlaced && s->width == width && s->height == height + 1)
352
12.3k
        height = s->height;
353
354
2.46M
    av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
355
2.46M
    if (av_image_check_size(width, height, 0, s->avctx) < 0)
356
33.9k
        return AVERROR_INVALIDDATA;
357
358
2.43M
    if (!s->progressive && !s->ls) {
359
        // A valid frame requires at least 1 bit for DC + 1 bit for AC for each 8x8 block.
360
1.76M
        if (s->buf_size && (width + 7) / 8 * ((height + 7) / 8) > s->buf_size * 4LL)
361
373k
            return AVERROR_INVALIDDATA;
362
1.76M
    }
363
364
2.05M
    nb_components = bytestream2_get_byteu(&s->gB);
365
2.05M
    if (nb_components <= 0 ||
366
2.04M
        nb_components > MAX_COMPONENTS)
367
32.3k
        return AVERROR_INVALIDDATA;
368
2.02M
    if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
369
106k
        if (nb_components != s->nb_components) {
370
1.94k
            av_log(s->avctx, AV_LOG_ERROR,
371
1.94k
                   "nb_components changing in interlaced picture\n");
372
1.94k
            return AVERROR_INVALIDDATA;
373
1.94k
        }
374
106k
    }
375
2.02M
    if (s->ls && !(bits <= 8 || nb_components == 1)) {
376
1.78k
        avpriv_report_missing_feature(s->avctx,
377
1.78k
                                      "JPEG-LS that is not <= 8 "
378
1.78k
                                      "bits/component or 16-bit gray");
379
1.78k
        return AVERROR_PATCHWELCOME;
380
1.78k
    }
381
2.02M
    len -= 6;
382
2.02M
    if (len != 3 * nb_components) {
383
5.87k
        av_log(s->avctx, AV_LOG_ERROR, "decode_sof0: error, len(%d) mismatch %d components\n", len, nb_components);
384
5.87k
        return AVERROR_INVALIDDATA;
385
5.87k
    }
386
387
2.01M
    s->nb_components = nb_components;
388
2.01M
    s->h_max         = 1;
389
2.01M
    s->v_max         = 1;
390
6.76M
    for (i = 0; i < nb_components; i++) {
391
        /* component id */
392
4.80M
        s->component_id[i] = bytestream2_get_byteu(&s->gB);
393
4.80M
        uint8_t b = bytestream2_get_byteu(&s->gB);
394
4.80M
        h_count[i]         = b >> 4;
395
4.80M
        v_count[i]         = b & 0x0F;
396
        /* compute hmax and vmax (only used in interleaved case) */
397
4.80M
        if (h_count[i] > s->h_max)
398
1.43M
            s->h_max = h_count[i];
399
4.80M
        if (v_count[i] > s->v_max)
400
1.16M
            s->v_max = v_count[i];
401
4.80M
        s->quant_index[i] = bytestream2_get_byteu(&s->gB);
402
4.80M
        if (s->quant_index[i] >= 4) {
403
41.3k
            av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
404
41.3k
            return AVERROR_INVALIDDATA;
405
41.3k
        }
406
4.75M
        if (!h_count[i] || !v_count[i]) {
407
15.4k
            av_log(s->avctx, AV_LOG_ERROR,
408
15.4k
                   "Invalid sampling factor in component %d %d:%d\n",
409
15.4k
                   i, h_count[i], v_count[i]);
410
15.4k
            return AVERROR_INVALIDDATA;
411
15.4k
        }
412
413
4.74M
        av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
414
4.74M
               i, h_count[i], v_count[i],
415
4.74M
               s->component_id[i], s->quant_index[i]);
416
4.74M
    }
417
1.96M
    if (   nb_components == 4
418
126k
        && s->component_id[0] == 'C'
419
62.6k
        && s->component_id[1] == 'M'
420
53.9k
        && s->component_id[2] == 'Y'
421
25.4k
        && s->component_id[3] == 'K')
422
19.4k
        s->adobe_transform = 0;
423
424
1.96M
    if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
425
4.66k
        avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
426
4.66k
        return AVERROR_PATCHWELCOME;
427
4.66k
    }
428
429
1.95M
    if (s->bayer) {
430
49.0k
        if (nb_components == 2) {
431
            /* Bayer images embedded in DNGs can contain 2 interleaved components and the
432
               width stored in their SOF3 markers is the width of each one.  We only output
433
               a single component, therefore we need to adjust the output image width.  We
434
               handle the deinterleaving (but not the debayering) in this file. */
435
90
            width *= 2;
436
90
        }
437
        /* They can also contain 1 component, which is double the width and half the height
438
            of the final image (rows are interleaved).  We don't handle the decoding in this
439
            file, but leave that to the TIFF/DNG decoder. */
440
49.0k
    }
441
442
    /* if different size, realloc/alloc picture */
443
1.95M
    if (width != s->width || height != s->height || bits != s->bits ||
444
1.29M
        memcmp(s->h_count, h_count, sizeof(h_count))                ||
445
1.21M
        memcmp(s->v_count, v_count, sizeof(v_count))) {
446
774k
        size_change = 1;
447
448
774k
        s->width      = width;
449
774k
        s->height     = height;
450
774k
        s->bits       = bits;
451
774k
        memcpy(s->h_count, h_count, sizeof(h_count));
452
774k
        memcpy(s->v_count, v_count, sizeof(v_count));
453
774k
        s->interlaced = 0;
454
774k
        s->got_picture = 0;
455
456
        /* test interlaced mode */
457
774k
        if (s->first_picture   &&
458
55.0k
            (s->multiscope != 2 || s->avctx->pkt_timebase.den >= 25 * s->avctx->pkt_timebase.num) &&
459
55.0k
            s->orig_height != 0 &&
460
13.8k
            s->height < ((s->orig_height * 3) / 4)) {
461
5.53k
            s->interlaced                    = 1;
462
5.53k
            s->bottom_field                  = s->interlace_polarity;
463
5.53k
            s->picture_ptr->flags |= AV_FRAME_FLAG_INTERLACED;
464
5.53k
            s->picture_ptr->flags |= AV_FRAME_FLAG_TOP_FIELD_FIRST * !s->interlace_polarity;
465
5.53k
            height *= 2;
466
5.53k
        }
467
468
774k
        ret = ff_set_dimensions(s->avctx, width, height);
469
774k
        if (ret < 0)
470
5.33k
            return ret;
471
472
768k
        if (s->avctx->codec_id != AV_CODEC_ID_SMVJPEG &&
473
691k
            (s->avctx->codec_tag == MKTAG('A', 'V', 'R', 'n') ||
474
688k
             s->avctx->codec_tag == MKTAG('A', 'V', 'D', 'J')) &&
475
117k
            s->orig_height < height)
476
46.6k
            s->avctx->height = AV_CEIL_RSHIFT(s->orig_height, s->avctx->lowres);
477
478
768k
        s->first_picture = 0;
479
1.18M
    } else {
480
1.18M
        size_change = 0;
481
1.18M
    }
482
483
1.95M
    if (s->avctx->codec_id == AV_CODEC_ID_SMVJPEG) {
484
198k
        s->avctx->height = s->avctx->coded_height / s->smv_frames_per_jpeg;
485
198k
        if (s->avctx->height <= 0)
486
5.42k
            return AVERROR_INVALIDDATA;
487
198k
    }
488
1.94M
    if (s->bayer && s->progressive) {
489
610
        avpriv_request_sample(s->avctx, "progressively coded bayer picture");
490
610
        return AVERROR_INVALIDDATA;
491
610
    }
492
493
1.94M
    if (s->got_picture && s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
494
96.8k
        if (s->progressive) {
495
1.54k
            avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
496
1.54k
            return AVERROR_INVALIDDATA;
497
1.54k
        }
498
1.84M
    } else {
499
1.84M
        if (s->v_max == 1 && s->h_max == 1 && s->lossless == 1 && (nb_components == 3 || nb_components == 4))
500
46.2k
            s->rgb = 1;
501
1.80M
        else if (!s->lossless)
502
1.35M
            s->rgb = 0;
503
        /* XXX: not complete test ! */
504
1.84M
        pix_fmt_id = ((unsigned)s->h_count[0] << 28) | (s->v_count[0] << 24) |
505
1.84M
                     (s->h_count[1] << 20) | (s->v_count[1] << 16) |
506
1.84M
                     (s->h_count[2] << 12) | (s->v_count[2] <<  8) |
507
1.84M
                     (s->h_count[3] <<  4) |  s->v_count[3];
508
1.84M
        av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
509
        /* NOTE we do not allocate pictures large enough for the possible
510
         * padding of h/v_count being 4 */
511
1.84M
        if (!(pix_fmt_id & 0xD0D0D0D0))
512
129k
            pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
513
1.84M
        if (!(pix_fmt_id & 0x0D0D0D0D))
514
149k
            pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
515
516
16.6M
        for (i = 0; i < 8; i++) {
517
14.7M
            int j = 6 + (i & 1) - (i & 6);
518
14.7M
            int is = (pix_fmt_id >> (4 * i)) & 0xF;
519
14.7M
            int js = (pix_fmt_id >> (4 * j)) & 0xF;
520
521
14.7M
            if (is == 1 && js != 2 && (i < 2 || i > 5))
522
1.72M
                js = (pix_fmt_id >> ( 8 + 4 * (i & 1))) & 0xF;
523
14.7M
            if (is == 1 && js != 2 && (i < 2 || i > 5))
524
1.70M
                js = (pix_fmt_id >> (16 + 4 * (i & 1))) & 0xF;
525
526
14.7M
            if (is == 1 && js == 2) {
527
374k
                if (i & 1) s->upscale_h[j / 2] = 1;
528
163k
                else       s->upscale_v[j / 2] = 1;
529
374k
            }
530
14.7M
        }
531
532
1.84M
        if (s->bayer) {
533
48.4k
            if (pix_fmt_id != 0x11110000 && pix_fmt_id != 0x11000000)
534
481
                goto unk_pixfmt;
535
48.4k
        }
536
537
1.84M
        switch (pix_fmt_id) {
538
2.30k
        case 0x11110000: /* for bayer-encoded huffman lossless JPEGs embedded in DNGs */
539
2.30k
            if (!s->bayer)
540
2.21k
                goto unk_pixfmt;
541
90
            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16LE;
542
90
            break;
543
85.8k
        case 0x11111100:
544
85.8k
            if (s->rgb)
545
33.3k
                s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_BGR48;
546
52.4k
            else {
547
52.4k
                if (   s->adobe_transform == 0
548
48.8k
                    || s->component_id[0] == 'R' && s->component_id[1] == 'G' && s->component_id[2] == 'B') {
549
6.14k
                    s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_GBRP : AV_PIX_FMT_GBRP16;
550
46.2k
                } else {
551
46.2k
                    if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
552
19.7k
                    else              s->avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
553
46.2k
                    s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
554
46.2k
                }
555
52.4k
            }
556
85.8k
            av_assert0(s->nb_components == 3);
557
85.8k
            break;
558
85.8k
        case 0x11111111:
559
37.1k
            if (s->rgb)
560
12.9k
                s->avctx->pix_fmt = s->bits <= 9 ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA64;
561
24.2k
            else {
562
24.2k
                if (s->adobe_transform == 0 && s->bits <= 8) {
563
3.67k
                    s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
564
20.5k
                } else {
565
20.5k
                    s->avctx->pix_fmt = s->bits <= 8 ? AV_PIX_FMT_YUVA444P : AV_PIX_FMT_YUVA444P16;
566
20.5k
                    s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
567
20.5k
                }
568
24.2k
            }
569
37.1k
            av_assert0(s->nb_components == 4);
570
37.1k
            break;
571
37.1k
        case 0x11412100:
572
15.8k
            if (s->bits > 8)
573
3.33k
                goto unk_pixfmt;
574
12.4k
            if (s->component_id[0] == 'R' && s->component_id[1] == 'G' && s->component_id[2] == 'B') {
575
4.12k
                s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
576
4.12k
                s->upscale_h[0] = 4;
577
4.12k
                s->upscale_h[1] = 0;
578
4.12k
                s->upscale_h[2] = 1;
579
8.36k
            } else {
580
8.36k
                goto unk_pixfmt;
581
8.36k
            }
582
4.12k
            break;
583
6.19k
        case 0x22111122:
584
73.7k
        case 0x22111111:
585
73.7k
            if (s->adobe_transform == 0 && s->bits <= 8) {
586
22.0k
                s->avctx->pix_fmt = AV_PIX_FMT_GBRAP;
587
22.0k
                s->upscale_v[1] = s->upscale_v[2] = 1;
588
22.0k
                s->upscale_h[1] = s->upscale_h[2] = 1;
589
51.7k
            } else if (s->adobe_transform == 2 && s->bits <= 8) {
590
4.43k
                s->avctx->pix_fmt = AV_PIX_FMT_YUVA444P;
591
4.43k
                s->upscale_v[1] = s->upscale_v[2] = 1;
592
4.43k
                s->upscale_h[1] = s->upscale_h[2] = 1;
593
4.43k
                s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
594
47.2k
            } else {
595
47.2k
                if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
596
24.4k
                else              s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P16;
597
47.2k
                s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
598
47.2k
            }
599
73.7k
            av_assert0(s->nb_components == 4);
600
73.7k
            break;
601
73.7k
        case 0x12121100:
602
19.3k
        case 0x22122100:
603
23.1k
        case 0x21211100:
604
28.9k
        case 0x21112100:
605
43.8k
        case 0x22211200:
606
54.8k
        case 0x22221100:
607
61.6k
        case 0x22112200:
608
64.1k
        case 0x11222200:
609
64.1k
            if (s->bits > 8)
610
3.26k
                goto unk_pixfmt;
611
60.8k
            if (s->adobe_transform == 0 || s->component_id[0] == 'R' &&
612
10.6k
                s->component_id[1] == 'G' && s->component_id[2] == 'B') {
613
5.62k
                s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
614
55.2k
            } else {
615
55.2k
                s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
616
55.2k
                s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
617
55.2k
            }
618
60.8k
            break;
619
496k
        case 0x11000000:
620
513k
        case 0x13000000:
621
529k
        case 0x14000000:
622
571k
        case 0x31000000:
623
582k
        case 0x33000000:
624
599k
        case 0x34000000:
625
622k
        case 0x41000000:
626
627k
        case 0x43000000:
627
632k
        case 0x44000000:
628
632k
            if (s->bits <= 8)
629
375k
                s->avctx->pix_fmt = s->force_pal8 ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8;
630
257k
            else
631
257k
                s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
632
632k
            break;
633
24.2k
        case 0x12111100:
634
27.4k
        case 0x14121200:
635
37.0k
        case 0x14111100:
636
45.7k
        case 0x22211100:
637
78.8k
        case 0x22112100:
638
78.8k
            if (s->component_id[0] == 'R' && s->component_id[1] == 'G' && s->component_id[2] == 'B') {
639
10.0k
                if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
640
2.72k
                else
641
2.72k
                    goto unk_pixfmt;
642
7.35k
                s->upscale_v[1] = s->upscale_v[2] = 1;
643
68.7k
            } else {
644
68.7k
                if (pix_fmt_id == 0x14111100)
645
9.58k
                    s->upscale_v[1] = s->upscale_v[2] = 1;
646
68.7k
                if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
647
5.19k
                else
648
5.19k
                    goto unk_pixfmt;
649
63.5k
                s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
650
63.5k
            }
651
70.9k
            break;
652
124k
        case 0x21111100:
653
124k
            if (s->component_id[0] == 'R' && s->component_id[1] == 'G' && s->component_id[2] == 'B') {
654
17.7k
                if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
655
2.89k
                else
656
2.89k
                    goto unk_pixfmt;
657
14.8k
                s->upscale_h[1] = s->upscale_h[2] = 1;
658
107k
            } else {
659
107k
                if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
660
4.94k
                else              s->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
661
107k
                s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
662
107k
            }
663
122k
            break;
664
122k
        case 0x11311100:
665
13.4k
            if (s->bits > 8)
666
2.16k
                goto unk_pixfmt;
667
11.2k
            if (s->component_id[0] == 'R' && s->component_id[1] == 'G' && s->component_id[2] == 'B')
668
3.22k
                s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
669
8.03k
            else
670
8.03k
                goto unk_pixfmt;
671
3.22k
            s->upscale_h[0] = s->upscale_h[2] = 2;
672
3.22k
            break;
673
14.9k
        case 0x31111100:
674
14.9k
            if (s->bits > 8)
675
2.78k
                goto unk_pixfmt;
676
12.1k
            s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
677
12.1k
            s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
678
12.1k
            s->upscale_h[1] = s->upscale_h[2] = 2;
679
12.1k
            break;
680
12.1k
        case 0x22121100:
681
29.8k
        case 0x22111200:
682
44.8k
        case 0x41211100:
683
44.8k
            if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
684
6.90k
            else
685
6.90k
                goto unk_pixfmt;
686
37.9k
            s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
687
37.9k
            break;
688
535k
        case 0x22111100:
689
581k
        case 0x23111100:
690
601k
        case 0x42111100:
691
617k
        case 0x24111100:
692
617k
            if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
693
17.6k
            else              s->avctx->pix_fmt = AV_PIX_FMT_YUV420P16;
694
617k
            s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
695
617k
            if (pix_fmt_id == 0x42111100) {
696
19.8k
                if (s->bits > 8)
697
4.09k
                    goto unk_pixfmt;
698
15.7k
                s->upscale_h[1] = s->upscale_h[2] = 1;
699
597k
            } else if (pix_fmt_id == 0x24111100) {
700
15.8k
                if (s->bits > 8)
701
3.11k
                    goto unk_pixfmt;
702
12.6k
                s->upscale_v[1] = s->upscale_v[2] = 1;
703
581k
            } else if (pix_fmt_id == 0x23111100) {
704
45.7k
                if (s->bits > 8)
705
2.49k
                    goto unk_pixfmt;
706
43.2k
                s->upscale_v[1] = s->upscale_v[2] = 2;
707
43.2k
            }
708
607k
            break;
709
607k
        case 0x41111100:
710
13.7k
            if (s->bits <= 8) s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV411P : AV_PIX_FMT_YUVJ411P;
711
2.01k
            else
712
2.01k
                goto unk_pixfmt;
713
11.7k
            s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
714
11.7k
            break;
715
27.2k
        default:
716
87.2k
    unk_pixfmt:
717
87.2k
            avpriv_report_missing_feature(s->avctx, "Pixel format 0x%x bits:%d", pix_fmt_id, s->bits);
718
87.2k
            memset(s->upscale_h, 0, sizeof(s->upscale_h));
719
87.2k
            memset(s->upscale_v, 0, sizeof(s->upscale_v));
720
87.2k
            return AVERROR_PATCHWELCOME;
721
1.84M
        }
722
1.76M
        if ((AV_RB32(s->upscale_h) || AV_RB32(s->upscale_v)) && s->avctx->lowres) {
723
16.4k
            avpriv_report_missing_feature(s->avctx, "Lowres for weird subsampling");
724
16.4k
            return AVERROR_PATCHWELCOME;
725
16.4k
        }
726
1.74M
        if (s->ls) {
727
275k
            memset(s->upscale_h, 0, sizeof(s->upscale_h));
728
275k
            memset(s->upscale_v, 0, sizeof(s->upscale_v));
729
275k
            if (s->nb_components == 3) {
730
14.6k
                s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
731
260k
            } else if (s->nb_components != 1) {
732
1.57k
                av_log(s->avctx, AV_LOG_ERROR, "Unsupported number of components %d\n", s->nb_components);
733
1.57k
                return AVERROR_PATCHWELCOME;
734
258k
            } else if ((s->palette_index || s->force_pal8) && s->bits <= 8)
735
37.2k
                s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
736
221k
            else if (s->bits <= 8)
737
114k
                s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
738
107k
            else
739
107k
                s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
740
275k
        }
741
742
1.74M
        s->pix_desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
743
1.74M
        if (!s->pix_desc) {
744
0
            av_log(s->avctx, AV_LOG_ERROR, "Could not get a pixel format descriptor.\n");
745
0
            return AVERROR_BUG;
746
0
        }
747
748
1.74M
        if (s->avctx->pix_fmt == s->hwaccel_sw_pix_fmt && !size_change) {
749
1.01M
            s->avctx->pix_fmt = s->hwaccel_pix_fmt;
750
1.01M
        } else {
751
728k
            enum AVPixelFormat pix_fmts[] = {
752
#if CONFIG_MJPEG_NVDEC_HWACCEL
753
                AV_PIX_FMT_CUDA,
754
#endif
755
#if CONFIG_MJPEG_VAAPI_HWACCEL
756
                AV_PIX_FMT_VAAPI,
757
#endif
758
728k
                s->avctx->pix_fmt,
759
728k
                AV_PIX_FMT_NONE,
760
728k
            };
761
728k
            s->hwaccel_pix_fmt = ff_get_format(s->avctx, pix_fmts);
762
728k
            if (s->hwaccel_pix_fmt < 0)
763
0
                return AVERROR(EINVAL);
764
765
728k
            s->hwaccel_sw_pix_fmt = s->avctx->pix_fmt;
766
728k
            s->avctx->pix_fmt     = s->hwaccel_pix_fmt;
767
728k
        }
768
769
1.74M
        if (s->avctx->skip_frame == AVDISCARD_ALL) {
770
58.1k
            s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
771
58.1k
            s->picture_ptr->flags |= AV_FRAME_FLAG_KEY;
772
58.1k
            s->got_picture            = 1;
773
58.1k
            return 0;
774
58.1k
        }
775
776
1.68M
        av_frame_unref(s->picture_ptr);
777
1.68M
        ret = ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF);
778
1.68M
        if (ret < 0)
779
3.38k
            return ret;
780
1.68M
        s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
781
1.68M
        s->picture_ptr->flags |= AV_FRAME_FLAG_KEY;
782
1.68M
        s->got_picture            = 1;
783
784
        // Lets clear the palette to avoid leaving uninitialized values in it
785
1.68M
        if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
786
56.5k
            memset(s->picture_ptr->data[1], 0, 1024);
787
788
8.40M
        for (i = 0; i < 4; i++)
789
6.72M
            s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
790
791
1.68M
        ff_dlog(s->avctx, "%d %d %d %d %d %d\n",
792
1.68M
                s->width, s->height, s->linesize[0], s->linesize[1],
793
1.68M
                s->interlaced, s->avctx->height);
794
795
1.68M
    }
796
797
1.77M
    if ((s->rgb && !s->lossless && !s->ls) ||
798
1.77M
        (!s->rgb && s->ls && s->nb_components > 1) ||
799
1.77M
        (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 && !s->ls)
800
1.77M
    ) {
801
21.5k
        av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
802
21.5k
        return AVERROR_PATCHWELCOME;
803
21.5k
    }
804
805
    /* totally blank picture as progressive JPEG will only add details to it */
806
1.75M
    if (s->progressive) {
807
289k
        int bw = (width  + s->h_max * 8 - 1) / (s->h_max * 8);
808
289k
        int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
809
996k
        for (i = 0; i < s->nb_components; i++) {
810
707k
            int size = bw * bh * s->h_count[i] * s->v_count[i];
811
707k
            av_freep(&s->blocks[i]);
812
707k
            av_freep(&s->last_nnz[i]);
813
707k
            s->blocks[i]       = av_calloc(size, sizeof(**s->blocks));
814
707k
            s->last_nnz[i]     = av_calloc(size, sizeof(**s->last_nnz));
815
707k
            if (!s->blocks[i] || !s->last_nnz[i])
816
0
                return AVERROR(ENOMEM);
817
707k
            s->block_stride[i] = bw * s->h_count[i];
818
707k
        }
819
289k
        memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
820
289k
    }
821
822
1.75M
    if (s->avctx->hwaccel) {
823
0
        const FFHWAccel *hwaccel = ffhwaccel(s->avctx->hwaccel);
824
0
        s->hwaccel_picture_private =
825
0
            av_mallocz(hwaccel->frame_priv_data_size);
826
0
        if (!s->hwaccel_picture_private)
827
0
            return AVERROR(ENOMEM);
828
829
0
        ret = hwaccel->start_frame(s->avctx, NULL, s->raw_image_buffer,
830
0
                                   s->raw_image_buffer_size);
831
0
        if (ret < 0)
832
0
            return ret;
833
0
    }
834
835
1.75M
    return 0;
836
1.75M
}
837
838
static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index, int *val)
839
175M
{
840
175M
    int code;
841
175M
    code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
842
175M
    if (code < 0 || code > 16) {
843
60.6k
        av_log(s->avctx, AV_LOG_ERROR,
844
60.6k
               "mjpeg_decode_dc: bad vlc: %d\n", dc_index);
845
60.6k
        return AVERROR_INVALIDDATA;
846
60.6k
    }
847
848
175M
    *val = code ? get_xbits(&s->gb, code) : 0;
849
175M
    return 0;
850
175M
}
851
852
/* decode block and dequantize */
853
static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
854
                        int dc_index, int ac_index, uint16_t *quant_matrix)
855
18.5M
{
856
18.5M
    int code, i, j, level, val;
857
858
    /* DC coef */
859
18.5M
    int ret = mjpeg_decode_dc(s, dc_index, &val);
860
18.5M
    if (ret < 0)
861
16.8k
        return ret;
862
863
18.5M
    val = val * (unsigned)quant_matrix[0] + s->last_dc[component];
864
18.5M
    s->last_dc[component] = val;
865
18.5M
    block[0] = av_clip_int16(val);
866
    /* AC coefs */
867
18.5M
    i = 0;
868
18.5M
    {
869
18.5M
        OPEN_READER(re, &s->gb);
870
426M
        do {
871
426M
            UPDATE_CACHE(re, &s->gb);
872
426M
            GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
873
874
426M
            i += ((unsigned)code) >> 4;
875
426M
            code &= 0xf;
876
426M
            if (code) {
877
                // GET_VLC updates the cache if parsing reaches the second stage.
878
                // So we have at least MIN_CACHE_BITS - 9 > 15 bits left here
879
                // and don't need to refill the cache.
880
413M
                {
881
413M
                    int cache = GET_CACHE(re, &s->gb);
882
413M
                    int sign  = (~cache) >> 31;
883
413M
                    level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
884
413M
                }
885
886
413M
                LAST_SKIP_BITS(re, &s->gb, code);
887
888
413M
                if (i > 63) {
889
42.6k
                    av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
890
42.6k
                    return AVERROR_INVALIDDATA;
891
42.6k
                }
892
413M
                j        = s->permutated_scantable[i];
893
413M
                block[j] = level * quant_matrix[i];
894
413M
            }
895
426M
        } while (i < 63);
896
18.5M
        CLOSE_READER(re, &s->gb);
897
18.5M
    }
898
899
0
    return 0;
900
18.5M
}
901
902
static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
903
                                 int component, int dc_index,
904
                                 uint16_t *quant_matrix, int Al)
905
5.55M
{
906
5.55M
    unsigned val;
907
5.55M
    s->bdsp.clear_block(block);
908
5.55M
    int ret = mjpeg_decode_dc(s, dc_index, &val);
909
5.55M
    if (ret < 0)
910
9.73k
        return ret;
911
912
5.54M
    val = (val * (quant_matrix[0] << Al)) + s->last_dc[component];
913
5.54M
    s->last_dc[component] = val;
914
5.54M
    block[0] = val;
915
5.54M
    return 0;
916
5.55M
}
917
918
/* decode block and dequantize - progressive JPEG version */
919
static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
920
                                    uint8_t *last_nnz, int ac_index,
921
                                    uint16_t *quant_matrix,
922
                                    int Ss, int Se, int Al, int *EOBRUN)
923
6.15M
{
924
6.15M
    int code, i, j, val, run;
925
6.15M
    unsigned level;
926
927
6.15M
    if (*EOBRUN) {
928
3.82M
        (*EOBRUN)--;
929
3.82M
        return 0;
930
3.82M
    }
931
932
2.33M
    {
933
2.33M
        OPEN_READER(re, &s->gb);
934
7.79M
        for (i = Ss; ; i++) {
935
7.79M
            UPDATE_CACHE(re, &s->gb);
936
7.79M
            GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
937
938
7.79M
            run = ((unsigned) code) >> 4;
939
7.79M
            code &= 0xF;
940
7.79M
            if (code) {
941
6.93M
                i += run;
942
943
6.93M
                {
944
6.93M
                    int cache = GET_CACHE(re, &s->gb);
945
6.93M
                    int sign  = (~cache) >> 31;
946
6.93M
                    level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
947
6.93M
                }
948
949
6.93M
                LAST_SKIP_BITS(re, &s->gb, code);
950
951
6.93M
                if (i >= Se) {
952
1.48M
                    if (i == Se) {
953
1.47M
                        j = s->permutated_scantable[Se];
954
1.47M
                        block[j] = level * (quant_matrix[Se] << Al);
955
1.47M
                        break;
956
1.47M
                    }
957
10.9k
                    av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
958
10.9k
                    return AVERROR_INVALIDDATA;
959
1.48M
                }
960
5.45M
                j = s->permutated_scantable[i];
961
5.45M
                block[j] = level * (quant_matrix[i] << Al);
962
5.45M
            } else {
963
853k
                if (run == 0xF) { // ZRL - skip 15 coefficients
964
12.1k
                    i += 15;
965
12.1k
                    if (i >= Se) {
966
4.00k
                        av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
967
4.00k
                        return AVERROR_INVALIDDATA;
968
4.00k
                    }
969
841k
                } else {
970
841k
                    val = (1 << run);
971
841k
                    if (run) {
972
                        // Given that GET_VLC reloads internally, we always
973
                        // have at least 16 bits in the cache here.
974
172k
                        val += NEG_USR32(GET_CACHE(re, &s->gb), run);
975
172k
                        LAST_SKIP_BITS(re, &s->gb, run);
976
172k
                    }
977
841k
                    *EOBRUN = val - 1;
978
841k
                    break;
979
841k
                }
980
853k
            }
981
7.79M
        }
982
2.31M
        CLOSE_READER(re, &s->gb);
983
2.31M
    }
984
985
2.31M
    if (i > *last_nnz)
986
1.02M
        *last_nnz = i;
987
988
2.31M
    return 0;
989
2.33M
}
990
991
3.39M
#define REFINE_BIT(j) {                                             \
992
3.39M
    UPDATE_CACHE(re, &s->gb);                                       \
993
3.39M
    sign = block[j] >> 15;                                          \
994
3.39M
    block[j] += SHOW_UBITS(re, &s->gb, 1) *                         \
995
3.39M
                ((quant_matrix[i] ^ sign) - sign) << Al;            \
996
3.39M
    LAST_SKIP_BITS(re, &s->gb, 1);                                  \
997
3.39M
}
998
999
5.27M
#define ZERO_RUN                                                    \
1000
8.04M
for (; ; i++) {                                                     \
1001
8.04M
    if (i > last) {                                                 \
1002
3.89M
        i += run;                                                   \
1003
3.89M
        if (i > Se) {                                               \
1004
26.1k
            av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
1005
26.1k
            return -1;                                              \
1006
26.1k
        }                                                           \
1007
3.89M
        break;                                                      \
1008
3.89M
    }                                                               \
1009
8.04M
    j = s->permutated_scantable[i];                                 \
1010
4.15M
    if (block[j])                                                   \
1011
4.15M
        REFINE_BIT(j)                                               \
1012
4.15M
    else if (run-- == 0)                                            \
1013
2.26M
        break;                                                      \
1014
4.15M
}
1015
1016
/* decode block and dequantize - progressive JPEG refinement pass */
1017
static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
1018
                                   uint8_t *last_nnz,
1019
                                   int ac_index, uint16_t *quant_matrix,
1020
                                   int Ss, int Se, int Al, int *EOBRUN)
1021
7.14M
{
1022
7.14M
    int code, i = Ss, j, sign, val, run;
1023
7.14M
    int last    = FFMIN(Se, *last_nnz);
1024
1025
7.14M
    OPEN_READER(re, &s->gb);
1026
7.14M
    if (*EOBRUN) {
1027
5.50M
        (*EOBRUN)--;
1028
5.50M
    } else {
1029
6.67M
        for (; ; i++) {
1030
6.67M
            UPDATE_CACHE(re, &s->gb);
1031
6.67M
            GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
1032
1033
6.67M
            if (code & 0xF) {
1034
5.23M
                run = ((unsigned) code) >> 4;
1035
5.23M
                val = SHOW_UBITS(re, &s->gb, 1);
1036
5.23M
                LAST_SKIP_BITS(re, &s->gb, 1);
1037
5.23M
                ZERO_RUN;
1038
5.21M
                j = s->permutated_scantable[i];
1039
5.21M
                val--;
1040
5.21M
                block[j] = ((quant_matrix[i] << Al) ^ val) - val;
1041
5.21M
                if (i == Se) {
1042
206k
                    if (i > *last_nnz)
1043
138k
                        *last_nnz = i;
1044
206k
                    CLOSE_READER(re, &s->gb);
1045
206k
                    return 0;
1046
206k
                }
1047
5.21M
            } else {
1048
1.44M
                run = ((unsigned) code) >> 4;
1049
1.44M
                if (run == 0xF) {
1050
33.3k
                    ZERO_RUN;
1051
1.40M
                } else {
1052
1.40M
                    val = run;
1053
1.40M
                    run = (1 << run);
1054
1.40M
                    if (val) {
1055
                        // Given that GET_VLC reloads internally, we always
1056
                        // have at least 16 bits in the cache here.
1057
81.9k
                        run += SHOW_UBITS(re, &s->gb, val);
1058
81.9k
                        LAST_SKIP_BITS(re, &s->gb, val);
1059
81.9k
                    }
1060
1.40M
                    *EOBRUN = run - 1;
1061
1.40M
                    break;
1062
1.40M
                }
1063
1.44M
            }
1064
6.67M
        }
1065
1066
1.40M
        if (i > *last_nnz)
1067
864k
            *last_nnz = i;
1068
1.40M
    }
1069
1070
11.6M
    for (; i <= last; i++) {
1071
4.75M
        j = s->permutated_scantable[i];
1072
4.75M
        if (block[j])
1073
1.50M
            REFINE_BIT(j)
1074
4.75M
    }
1075
6.91M
    CLOSE_READER(re, &s->gb);
1076
1077
6.91M
    return 0;
1078
7.14M
}
1079
#undef REFINE_BIT
1080
#undef ZERO_RUN
1081
1082
/* Handles 1 to 4 components */
1083
static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s)
1084
74.8k
{
1085
74.8k
    int nb_components = s->nb_components_sos;
1086
74.8k
    int predictor = s->Ss;
1087
74.8k
    int point_transform = s->Al;
1088
74.8k
    int i, mb_x, mb_y;
1089
74.8k
    unsigned width;
1090
74.8k
    uint16_t (*buffer)[4];
1091
74.8k
    int left[4], top[4], topleft[4];
1092
74.8k
    const int linesize = s->linesize[0];
1093
74.8k
    const int mask     = ((1 << s->bits) - 1) << point_transform;
1094
74.8k
    int resync_mb_y = 0;
1095
74.8k
    int resync_mb_x = 0;
1096
74.8k
    int vpred[6];
1097
74.8k
    int ret;
1098
1099
74.8k
    if (!s->bayer && s->nb_components < 3)
1100
4.31k
        return AVERROR_INVALIDDATA;
1101
70.4k
    if (s->bayer && s->nb_components > 2)
1102
0
        return AVERROR_INVALIDDATA;
1103
70.4k
    if (s->nb_components <= 0 || s->nb_components > 4)
1104
0
        return AVERROR_INVALIDDATA;
1105
70.4k
    if (s->v_max != 1 || s->h_max != 1 || !s->lossless)
1106
7.27k
        return AVERROR_INVALIDDATA;
1107
63.2k
    if (s->bayer) {
1108
8.35k
        if (s->rct || s->pegasus_rct)
1109
520
            return AVERROR_INVALIDDATA;
1110
8.35k
    }
1111
1112
1113
438k
    for (i = 0; i < 6; i++)
1114
376k
        vpred[i] = 1 << (s->bits - 1);
1115
1116
62.6k
    if (s->bayer)
1117
7.83k
        width = s->mb_width / nb_components; /* Interleaved, width stored is the total so need to divide */
1118
54.8k
    else
1119
54.8k
        width = s->mb_width;
1120
1121
62.6k
    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size, width * 4 * sizeof(s->ljpeg_buffer[0][0]));
1122
62.6k
    if (!s->ljpeg_buffer)
1123
13
        return AVERROR(ENOMEM);
1124
1125
62.6k
    buffer = s->ljpeg_buffer;
1126
1127
313k
    for (i = 0; i < 4; i++)
1128
250k
        buffer[0][i] = 1 << (s->bits - 1);
1129
1130
62.6k
    s->restart_count = -1;
1131
1132
2.69M
    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1133
2.68M
        uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
1134
1135
2.68M
        if (s->interlaced && s->bottom_field)
1136
8.89k
            ptr += linesize >> 1;
1137
1138
13.4M
        for (i = 0; i < 4; i++)
1139
10.7M
            top[i] = left[i] = topleft[i] = buffer[0][i];
1140
1141
17.6M
        for (mb_x = 0; mb_x < width; mb_x++) {
1142
15.0M
            int modified_predictor = predictor;
1143
15.0M
            int restart;
1144
1145
15.0M
            ret = ff_mjpeg_handle_restart(s, &restart);
1146
15.0M
            if (ret < 0)
1147
0
                return ret;
1148
15.0M
            if (restart) {
1149
4.26M
                resync_mb_x = mb_x;
1150
4.26M
                resync_mb_y = mb_y;
1151
21.3M
                for (i = 0; i < 4; i++)
1152
17.0M
                    top[i] = left[i] = topleft[i] = 1 << (s->bits - 1);
1153
4.26M
            }
1154
1155
15.0M
            if (get_bits_left(&s->gb) < 1) {
1156
37.2k
                av_log(s->avctx, AV_LOG_ERROR, "bitstream end in rgb_scan\n");
1157
37.2k
                return AVERROR_INVALIDDATA;
1158
37.2k
            }
1159
1160
15.0M
            if (mb_y == resync_mb_y || mb_y == resync_mb_y + 1 && mb_x < resync_mb_x || !mb_x)
1161
10.3M
                modified_predictor = 1;
1162
1163
35.4M
            for (i = 0; i < nb_components; i++) {
1164
20.3M
                int pred, dc;
1165
1166
20.3M
                topleft[i] = top[i];
1167
20.3M
                top[i]     = buffer[mb_x][i];
1168
1169
20.3M
                ret = mjpeg_decode_dc(s, s->dc_index[i], &dc);
1170
20.3M
                if (ret < 0)
1171
13.8k
                    return ret;
1172
1173
20.3M
                if (!s->bayer || mb_x) {
1174
20.3M
                    pred = left[i];
1175
20.3M
                } else { /* This path runs only for the first line in bayer images */
1176
32.9k
                    vpred[i] += dc;
1177
32.9k
                    pred = vpred[i] - dc;
1178
32.9k
                }
1179
1180
20.3M
                PREDICT(pred, topleft[i], top[i], pred, modified_predictor);
1181
1182
20.3M
                left[i] = buffer[mb_x][i] =
1183
20.3M
                    mask & (pred + (unsigned)(dc * (1 << point_transform)));
1184
20.3M
            }
1185
15.0M
        }
1186
2.63M
        if (s->rct && s->nb_components == 4) {
1187
1.00M
            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1188
592k
                ptr[4 * mb_x + 2] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
1189
592k
                ptr[4 * mb_x + 1] = buffer[mb_x][1] + ptr[4 * mb_x + 2];
1190
592k
                ptr[4 * mb_x + 3] = buffer[mb_x][2] + ptr[4 * mb_x + 2];
1191
592k
                ptr[4 * mb_x + 0] = buffer[mb_x][3];
1192
592k
            }
1193
2.22M
        } else if (s->nb_components == 4) {
1194
3.81M
            for (i = 0; i < nb_components; i++) {
1195
1.92M
                int c = s->comp_index[i];
1196
1.92M
                if (s->bits <= 8) {
1197
4.33M
                    for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1198
3.12M
                        ptr[4 * mb_x + 3 - c] = buffer[mb_x][i];
1199
3.12M
                    }
1200
1.20M
                } else if (s->bits == 9) {
1201
2.32k
                    return AVERROR_PATCHWELCOME;
1202
718k
                } else {
1203
6.31M
                    for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1204
5.59M
                        ((uint16_t*)ptr)[4 * mb_x + c] = buffer[mb_x][i];
1205
5.59M
                    }
1206
718k
                }
1207
1.92M
            }
1208
1.88M
        } else if (s->rct) {
1209
1.34M
            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1210
1.32M
                ptr[3 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
1211
1.32M
                ptr[3 * mb_x + 0] = buffer[mb_x][1] + ptr[3 * mb_x + 1];
1212
1.32M
                ptr[3 * mb_x + 2] = buffer[mb_x][2] + ptr[3 * mb_x + 1];
1213
1.32M
            }
1214
315k
        } else if (s->pegasus_rct) {
1215
24.0k
            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1216
18.6k
                ptr[3 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
1217
18.6k
                ptr[3 * mb_x + 0] = buffer[mb_x][1] + ptr[3 * mb_x + 1];
1218
18.6k
                ptr[3 * mb_x + 2] = buffer[mb_x][2] + ptr[3 * mb_x + 1];
1219
18.6k
            }
1220
310k
        } else if (s->bayer) {
1221
26.6k
            if (s->bits <= 8)
1222
496
                return AVERROR_PATCHWELCOME;
1223
26.1k
            if (nb_components == 1) {
1224
                /* Leave decoding to the TIFF/DNG decoder (see comment in ff_mjpeg_decode_sof) */
1225
870k
                for (mb_x = 0; mb_x < width; mb_x++)
1226
850k
                    ((uint16_t*)ptr)[mb_x] = buffer[mb_x][0];
1227
19.9k
            } else if (nb_components == 2) {
1228
66.1k
                for (mb_x = 0; mb_x < width; mb_x++) {
1229
62.2k
                    ((uint16_t*)ptr)[2 * mb_x + 0] = buffer[mb_x][0];
1230
62.2k
                    ((uint16_t*)ptr)[2 * mb_x + 1] = buffer[mb_x][1];
1231
62.2k
                }
1232
3.88k
            }
1233
283k
        } else {
1234
977k
            for (i = 0; i < nb_components; i++) {
1235
693k
                int c = s->comp_index[i];
1236
693k
                if (s->bits <= 8) {
1237
7.79M
                    for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1238
7.13M
                        ptr[3 * mb_x + 2 - c] = buffer[mb_x][i];
1239
7.13M
                    }
1240
660k
                } else if (s->bits == 9) {
1241
0
                    return AVERROR_PATCHWELCOME;
1242
32.8k
                } else {
1243
356k
                    for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1244
323k
                        ((uint16_t*)ptr)[3 * mb_x + 2 - c] = buffer[mb_x][i];
1245
323k
                    }
1246
32.8k
                }
1247
693k
            }
1248
283k
        }
1249
2.63M
    }
1250
8.79k
    return 0;
1251
62.6k
}
1252
1253
static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s)
1254
73.5k
{
1255
73.5k
    int predictor = s->Ss;
1256
73.5k
    int point_transform = s->Al;
1257
73.5k
    int nb_components = s->nb_components_sos;
1258
73.5k
    int i, mb_x, mb_y, mask;
1259
73.5k
    int bits = (s->bits + 7) & ~7;
1260
73.5k
    int resync_mb_y = 0;
1261
73.5k
    int resync_mb_x = 0;
1262
73.5k
    int ret;
1263
1264
73.5k
    point_transform += bits - s->bits;
1265
73.5k
    mask = ((1 << s->bits) - 1) << point_transform;
1266
1267
73.5k
    av_assert0(nb_components >= 1 && nb_components <= 4);
1268
1269
73.5k
    s->restart_count = -1;
1270
1271
18.2M
    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1272
126M
        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1273
108M
            int restart;
1274
108M
            ret = ff_mjpeg_handle_restart(s, &restart);
1275
108M
            if (ret < 0)
1276
0
                return ret;
1277
108M
            if (restart) {
1278
84.2M
                resync_mb_x = mb_x;
1279
84.2M
                resync_mb_y = mb_y;
1280
84.2M
            }
1281
1282
108M
            if (get_bits_left(&s->gb) < 1) {
1283
49.4k
                av_log(s->avctx, AV_LOG_ERROR, "bitstream end in yuv_scan\n");
1284
49.4k
                return AVERROR_INVALIDDATA;
1285
49.4k
            }
1286
1287
108M
            if (!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y + 1 && mb_x < resync_mb_x || s->interlaced) {
1288
95.8M
                int toprow  = mb_y == resync_mb_y || mb_y == resync_mb_y + 1 && mb_x < resync_mb_x;
1289
95.8M
                int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
1290
193M
                for (i = 0; i < nb_components; i++) {
1291
97.8M
                    uint8_t *ptr;
1292
97.8M
                    uint16_t *ptr16;
1293
97.8M
                    int n, h, v, x, y, c, j, linesize;
1294
97.8M
                    n = s->nb_blocks[i];
1295
97.8M
                    c = s->comp_index[i];
1296
97.8M
                    h = s->h_scount[i];
1297
97.8M
                    v = s->v_scount[i];
1298
97.8M
                    x = 0;
1299
97.8M
                    y = 0;
1300
97.8M
                    linesize = s->linesize[c];
1301
1302
97.8M
                    if (bits > 8) linesize /= 2;
1303
1304
200M
                    for (j = 0; j < n; j++) {
1305
102M
                        int pred, dc;
1306
1307
102M
                        ret = mjpeg_decode_dc(s, s->dc_index[i], &dc);
1308
102M
                        if (ret < 0)
1309
15.3k
                            return ret;
1310
1311
102M
                        if (   h * mb_x + x >= s->width
1312
102M
                            || v * mb_y + y >= s->height) {
1313
                            // Nothing to do
1314
102M
                        } else if (bits <= 8) {
1315
100M
                            ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); // FIXME optimize this crap
1316
100M
                            if (y == 0 && toprow) {
1317
94.3M
                                if (x == 0 && leftcol) {
1318
83.8M
                                    pred = 1 << (bits - 1);
1319
83.8M
                                } else {
1320
10.5M
                                    pred = ptr[-1];
1321
10.5M
                                }
1322
94.3M
                            } else {
1323
5.99M
                                if (x == 0 && leftcol) {
1324
2.57M
                                    pred = ptr[-linesize];
1325
3.42M
                                } else {
1326
3.42M
                                    PREDICT(pred, ptr[-linesize - 1], ptr[-linesize], ptr[-1], predictor);
1327
3.42M
                                }
1328
5.99M
                            }
1329
1330
100M
                            if (s->interlaced && s->bottom_field)
1331
6.32k
                                ptr += linesize >> 1;
1332
100M
                            pred &= mask;
1333
100M
                            *ptr = pred + ((unsigned)dc << point_transform);
1334
100M
                        } else {
1335
2.00M
                            ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2 * (linesize * (v * mb_y + y)) + 2 * (h * mb_x + x)); // FIXME optimize this crap
1336
2.00M
                            if (y == 0 && toprow) {
1337
1.13M
                                if (x == 0 && leftcol) {
1338
472k
                                    pred = 1 << (bits - 1);
1339
657k
                                } else {
1340
657k
                                    pred = ptr16[-1];
1341
657k
                                }
1342
1.13M
                            } else {
1343
872k
                                if (x == 0 && leftcol) {
1344
351k
                                    pred = ptr16[-linesize];
1345
521k
                                } else {
1346
521k
                                    PREDICT(pred, ptr16[-linesize - 1], ptr16[-linesize], ptr16[-1], predictor);
1347
521k
                                }
1348
872k
                            }
1349
1350
2.00M
                            if (s->interlaced && s->bottom_field)
1351
3.61k
                                ptr16 += linesize >> 1;
1352
2.00M
                            pred &= mask;
1353
2.00M
                            *ptr16 = pred + ((unsigned)dc << point_transform);
1354
2.00M
                        }
1355
102M
                        if (++x == h) {
1356
99.1M
                            x = 0;
1357
99.1M
                            y++;
1358
99.1M
                        }
1359
102M
                    }
1360
97.8M
                }
1361
95.8M
            } else {
1362
31.3M
                for (i = 0; i < nb_components; i++) {
1363
18.9M
                    uint8_t *ptr;
1364
18.9M
                    uint16_t *ptr16;
1365
18.9M
                    int n, h, v, x, y, c, j, linesize, dc;
1366
18.9M
                    n        = s->nb_blocks[i];
1367
18.9M
                    c        = s->comp_index[i];
1368
18.9M
                    h        = s->h_scount[i];
1369
18.9M
                    v        = s->v_scount[i];
1370
18.9M
                    x        = 0;
1371
18.9M
                    y        = 0;
1372
18.9M
                    linesize = s->linesize[c];
1373
1374
18.9M
                    if (bits > 8) linesize /= 2;
1375
1376
47.8M
                    for (j = 0; j < n; j++) {
1377
28.8M
                        int pred;
1378
1379
28.8M
                        ret = mjpeg_decode_dc(s, s->dc_index[i], &dc);
1380
28.8M
                        if (ret < 0)
1381
4.85k
                            return ret;
1382
1383
28.8M
                        if (   h * mb_x + x >= s->width
1384
27.9M
                            || v * mb_y + y >= s->height) {
1385
                            // Nothing to do
1386
27.9M
                        } else if (bits <= 8) {
1387
26.1M
                            ptr = s->picture_ptr->data[c] +
1388
26.1M
                              (linesize * (v * mb_y + y)) +
1389
26.1M
                              (h * mb_x + x); // FIXME optimize this crap
1390
26.1M
                            PREDICT(pred, ptr[-linesize - 1], ptr[-linesize], ptr[-1], predictor);
1391
1392
26.1M
                            pred &= mask;
1393
26.1M
                            *ptr = pred + ((unsigned)dc << point_transform);
1394
26.1M
                        } else {
1395
1.85M
                            ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2 * (linesize * (v * mb_y + y)) + 2 * (h * mb_x + x)); // FIXME optimize this crap
1396
1.85M
                            PREDICT(pred, ptr16[-linesize - 1], ptr16[-linesize], ptr16[-1], predictor);
1397
1398
1.85M
                            pred &= mask;
1399
1.85M
                            *ptr16 = pred + ((unsigned)dc << point_transform);
1400
1.85M
                        }
1401
1402
28.8M
                        if (++x == h) {
1403
21.1M
                            x = 0;
1404
21.1M
                            y++;
1405
21.1M
                        }
1406
28.8M
                    }
1407
18.9M
                }
1408
12.3M
            }
1409
108M
        }
1410
18.2M
    }
1411
3.90k
    return 0;
1412
73.5k
}
1413
1414
static av_always_inline void mjpeg_copy_block(MJpegDecodeContext *s,
1415
                                              uint8_t *dst, const uint8_t *src,
1416
                                              int linesize, int lowres)
1417
361k
{
1418
361k
    switch (lowres) {
1419
357k
    case 0: s->copy_block(dst, src, linesize, 8);
1420
357k
        break;
1421
1.69k
    case 1: copy_block4(dst, src, linesize, linesize, 4);
1422
1.69k
        break;
1423
314
    case 2: copy_block2(dst, src, linesize, linesize, 2);
1424
314
        break;
1425
2.88k
    case 3: *dst = *src;
1426
2.88k
        break;
1427
361k
    }
1428
361k
}
1429
1430
static void shift_output(MJpegDecodeContext *s, uint8_t *ptr, int linesize)
1431
61.6M
{
1432
61.6M
    int block_x, block_y;
1433
61.6M
    int size = 8 >> s->avctx->lowres;
1434
61.6M
    if (s->bits > 8) {
1435
231M
        for (block_y = 0; block_y < size; block_y++)
1436
1.83G
            for (block_x = 0; block_x < size; block_x++)
1437
1.62G
                *(uint16_t*)(ptr + 2 * block_x + block_y * linesize) <<= 16 - s->bits;
1438
35.0M
    } else {
1439
300M
        for (block_y = 0; block_y < size; block_y++)
1440
2.35G
            for (block_x = 0; block_x < size; block_x++)
1441
2.08G
                *(ptr + block_x + block_y * linesize) <<= 8 - s->bits;
1442
35.0M
    }
1443
61.6M
}
1444
1445
static int mjpeg_decode_scan(MJpegDecodeContext *s)
1446
990k
{
1447
990k
    int nb_components = s->nb_components_sos;
1448
990k
    int Ah = s->Ah;
1449
990k
    int Al = s->Al;
1450
990k
    const uint8_t *mb_bitmask = NULL;
1451
990k
    const AVFrame *reference = NULL;
1452
990k
    int i, mb_x, mb_y, chroma_h_shift, chroma_v_shift, chroma_width, chroma_height;
1453
990k
    uint8_t *data[MAX_COMPONENTS];
1454
990k
    const uint8_t *reference_data[MAX_COMPONENTS];
1455
990k
    int linesize[MAX_COMPONENTS];
1456
990k
    GetBitContext mb_bitmask_gb = {0}; // initialize to silence gcc warning
1457
990k
    int bytes_per_pixel = 1 + (s->bits > 8);
1458
990k
    int ret;
1459
1460
990k
    if (s->avctx->codec_id == AV_CODEC_ID_MXPEG) {
1461
14.5k
        mb_bitmask = s->mb_bitmask;
1462
14.5k
        reference = s->reference;
1463
14.5k
    }
1464
1465
990k
    if (mb_bitmask) {
1466
7.53k
        if (s->mb_bitmask_size != (s->mb_width * s->mb_height + 7) >> 3) {
1467
325
            av_log(s->avctx, AV_LOG_ERROR, "mb_bitmask_size mismatches\n");
1468
325
            return AVERROR_INVALIDDATA;
1469
325
        }
1470
7.20k
        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1471
7.20k
    }
1472
1473
990k
    av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt, &chroma_h_shift,
1474
990k
                                     &chroma_v_shift);
1475
990k
    chroma_width  = AV_CEIL_RSHIFT(s->width,  chroma_h_shift);
1476
990k
    chroma_height = AV_CEIL_RSHIFT(s->height, chroma_v_shift);
1477
1478
3.48M
    for (i = 0; i < nb_components; i++) {
1479
2.49M
        int c   = s->comp_index[i];
1480
2.49M
        data[c] = s->picture_ptr->data[c];
1481
2.49M
        reference_data[c] = reference ? reference->data[c] : NULL;
1482
2.49M
        linesize[c] = s->linesize[c];
1483
2.49M
        s->coefs_finished[c] |= 1;
1484
2.49M
    }
1485
1486
993k
next_field:
1487
993k
    s->restart_count = -1;
1488
1489
3.28M
    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1490
23.0M
        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1491
20.7M
            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1492
20.7M
            int restart;
1493
1494
20.7M
            if (s->avctx->codec_id == AV_CODEC_ID_THP) {
1495
1.32M
                if (s->restart_count < 0) {
1496
14.6k
                    ret = ff_mjpeg_unescape_sos(s);
1497
14.6k
                    if (ret < 0)
1498
0
                        return ret;
1499
14.6k
                }
1500
1.32M
                restart = ff_mjpeg_should_restart(s);
1501
1.32M
                if (restart)
1502
78.1k
                    align_get_bits(&s->gb);
1503
19.4M
            } else {
1504
19.4M
                ret = ff_mjpeg_handle_restart(s, &restart);
1505
19.4M
                if (ret < 0)
1506
0
                    return ret;
1507
19.4M
            }
1508
20.7M
            if (restart) {
1509
24.7M
                for (i = 0; i < nb_components; i++)
1510
14.5M
                    s->last_dc[i] = (4 << s->bits);
1511
10.1M
            }
1512
1513
20.7M
            if (get_bits_left(&s->gb) < 0) {
1514
812k
                av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1515
812k
                       -get_bits_left(&s->gb));
1516
812k
                return AVERROR_INVALIDDATA;
1517
812k
            }
1518
48.1M
            for (i = 0; i < nb_components; i++) {
1519
28.2M
                uint8_t *ptr;
1520
28.2M
                int n, h, v, x, y, c, j;
1521
28.2M
                int block_offset;
1522
28.2M
                n = s->nb_blocks[i];
1523
28.2M
                c = s->comp_index[i];
1524
28.2M
                h = s->h_scount[i];
1525
28.2M
                v = s->v_scount[i];
1526
28.2M
                x = 0;
1527
28.2M
                y = 0;
1528
63.1M
                for (j = 0; j < n; j++) {
1529
34.9M
                    block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1530
34.9M
                                     (h * mb_x + x) * 8 * bytes_per_pixel) >> s->avctx->lowres);
1531
1532
34.9M
                    if (s->interlaced && s->bottom_field)
1533
1.03M
                        block_offset += linesize[c] >> 1;
1534
34.9M
                    if (   8 * (h * mb_x + x) < ((c == 1) || (c == 2) ? chroma_width  : s->width)
1535
34.2M
                        && 8 * (v * mb_y + y) < ((c == 1) || (c == 2) ? chroma_height : s->height)) {
1536
32.8M
                        ptr = data[c] + block_offset;
1537
32.8M
                    } else
1538
2.13M
                        ptr = NULL;
1539
34.9M
                    if (!s->progressive) {
1540
19.0M
                        if (copy_mb) {
1541
505k
                            if (ptr)
1542
361k
                                mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1543
361k
                                                 linesize[c], s->avctx->lowres);
1544
1545
18.5M
                        } else {
1546
18.5M
                            s->bdsp.clear_block(s->block);
1547
18.5M
                            if (decode_block(s, s->block, i,
1548
18.5M
                                             s->dc_index[i], s->ac_index[i],
1549
18.5M
                                             s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1550
59.4k
                                av_log(s->avctx, AV_LOG_ERROR,
1551
59.4k
                                       "error y=%d x=%d\n", mb_y, mb_x);
1552
59.4k
                                return AVERROR_INVALIDDATA;
1553
59.4k
                            }
1554
18.5M
                            if (ptr && linesize[c]) {
1555
17.2M
                                s->idsp.idct_put(ptr, linesize[c], s->block);
1556
17.2M
                                if (s->bits & 7)
1557
6.24M
                                    shift_output(s, ptr, linesize[c]);
1558
17.2M
                            }
1559
18.5M
                        }
1560
19.0M
                    } else {
1561
15.8M
                        int block_idx  = s->block_stride[c] * (v * mb_y + y) +
1562
15.8M
                                         (h * mb_x + x);
1563
15.8M
                        int16_t *block = s->blocks[c][block_idx];
1564
15.8M
                        if (Ah)
1565
10.3M
                            block[0] += get_bits1(&s->gb) *
1566
10.3M
                                        s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1567
5.55M
                        else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1568
5.55M
                                                       s->quant_matrixes[s->quant_sindex[i]],
1569
5.55M
                                                       Al) < 0) {
1570
9.73k
                            av_log(s->avctx, AV_LOG_ERROR,
1571
9.73k
                                   "error y=%d x=%d\n", mb_y, mb_x);
1572
9.73k
                            return AVERROR_INVALIDDATA;
1573
9.73k
                        }
1574
15.8M
                    }
1575
34.9M
                    ff_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1576
34.9M
                    ff_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1577
34.9M
                            mb_x, mb_y, x, y, c, s->bottom_field,
1578
34.9M
                            (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1579
34.9M
                    if (++x == h) {
1580
29.8M
                        x = 0;
1581
29.8M
                        y++;
1582
29.8M
                    }
1583
34.9M
                }
1584
28.2M
            }
1585
19.9M
        }
1586
3.16M
    }
1587
1588
111k
    if (s->interlaced &&
1589
40.7k
        bytestream2_get_bytes_left(&s->gB) > 2 &&
1590
40.2k
        bytestream2_tell(&s->gB) > 2 &&
1591
40.2k
        s->gB.buffer[-2] == 0xFF &&
1592
4.59k
        s->gB.buffer[-1] == 0xD1) {
1593
3.09k
        av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1594
3.09k
        s->bottom_field ^= 1;
1595
1596
3.09k
        goto next_field;
1597
3.09k
    }
1598
1599
108k
    return 0;
1600
111k
}
1601
1602
static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s)
1603
167k
{
1604
167k
    int Ss = s->Ss;
1605
167k
    int Se = s->Se;
1606
167k
    int Ah = s->Ah;
1607
167k
    int Al = s->Al;
1608
167k
    int mb_x, mb_y;
1609
167k
    int EOBRUN = 0;
1610
167k
    int c = s->comp_index[0];
1611
167k
    uint16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1612
1613
167k
    av_assert0(Ss >= 0 && Ah >= 0 && Al >= 0);
1614
167k
    if (Se < Ss || Se > 63) {
1615
29.1k
        av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", Ss, Se);
1616
29.1k
        return AVERROR_INVALIDDATA;
1617
29.1k
    }
1618
1619
    // s->coefs_finished is a bitmask for coefficients coded
1620
    // Ss and Se are parameters telling start and end coefficients
1621
138k
    s->coefs_finished[c] |= (2ULL << Se) - (1ULL << Ss);
1622
1623
138k
    s->restart_count = -1;
1624
1625
2.49M
    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1626
2.48M
        int block_idx    = mb_y * s->block_stride[c];
1627
2.48M
        int16_t (*block)[64] = &s->blocks[c][block_idx];
1628
2.48M
        uint8_t *last_nnz    = &s->last_nnz[c][block_idx];
1629
15.6M
        for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1630
13.2M
            int ret;
1631
13.2M
            int restart;
1632
13.2M
            ret = ff_mjpeg_handle_restart(s, &restart);
1633
13.2M
            if (ret < 0)
1634
0
                return ret;
1635
13.2M
            if (restart)
1636
1.60M
                EOBRUN = 0;
1637
1638
13.2M
            if (Ah)
1639
7.14M
                ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1640
7.14M
                                              quant_matrix, Ss, Se, Al, &EOBRUN);
1641
6.15M
            else
1642
6.15M
                ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1643
6.15M
                                               quant_matrix, Ss, Se, Al, &EOBRUN);
1644
1645
13.2M
            if (ret >= 0 && get_bits_left(&s->gb) < 0)
1646
89.1k
                ret = AVERROR_INVALIDDATA;
1647
13.2M
            if (ret < 0) {
1648
130k
                av_log(s->avctx, AV_LOG_ERROR,
1649
130k
                       "error y=%d x=%d\n", mb_y, mb_x);
1650
130k
                return AVERROR_INVALIDDATA;
1651
130k
            }
1652
13.2M
        }
1653
2.48M
    }
1654
8.27k
    return 0;
1655
138k
}
1656
1657
static void mjpeg_idct_scan_progressive_ac(MJpegDecodeContext *s)
1658
174k
{
1659
174k
    int mb_x, mb_y;
1660
174k
    int c;
1661
174k
    const int bytes_per_pixel = 1 + (s->bits > 8);
1662
174k
    const int block_size = s->lossless ? 1 : 8;
1663
1664
594k
    for (c = 0; c < s->nb_components; c++) {
1665
419k
        uint8_t *data = s->picture_ptr->data[c];
1666
419k
        int linesize  = s->linesize[c];
1667
419k
        int h = s->h_max / s->h_count[c];
1668
419k
        int v = s->v_max / s->v_count[c];
1669
419k
        int mb_width     = (s->width  + h * block_size - 1) / (h * block_size);
1670
419k
        int mb_height    = (s->height + v * block_size - 1) / (v * block_size);
1671
1672
419k
        if (~s->coefs_finished[c])
1673
414k
            av_log(s->avctx, AV_LOG_WARNING, "component %d is incomplete\n", c);
1674
1675
419k
        if (s->interlaced && s->bottom_field)
1676
3.15k
            data += linesize >> 1;
1677
1678
9.19M
        for (mb_y = 0; mb_y < mb_height; mb_y++) {
1679
8.77M
            uint8_t *ptr     = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1680
8.77M
            int block_idx    = mb_y * s->block_stride[c];
1681
8.77M
            int16_t (*block)[64] = &s->blocks[c][block_idx];
1682
101M
            for (mb_x = 0; mb_x < mb_width; mb_x++, block++) {
1683
92.9M
                s->idsp.idct_put(ptr, linesize, *block);
1684
92.9M
                if (s->bits & 7)
1685
55.3M
                    shift_output(s, ptr, linesize);
1686
92.9M
                ptr += bytes_per_pixel * 8 >> s->avctx->lowres;
1687
92.9M
            }
1688
8.77M
        }
1689
419k
    }
1690
174k
}
1691
1692
int ff_mjpeg_decode_sos(MJpegDecodeContext *s)
1693
3.22M
{
1694
3.22M
    int len, i, h, v;
1695
3.22M
    int index, id, ret;
1696
3.22M
    const int block_size = s->lossless ? 1 : 8;
1697
1698
3.22M
    if (!s->got_picture) {
1699
187k
        av_log(s->avctx, AV_LOG_WARNING,
1700
187k
                "Can not process SOS before SOF, skipping\n");
1701
187k
        return AVERROR_INVALIDDATA;
1702
187k
    }
1703
1704
3.03M
    ret = mjpeg_parse_len(s, &len, "sos");
1705
3.03M
    if (ret < 0)
1706
460k
        return ret;
1707
2.57M
    if (len < 1)
1708
5.54k
        return AVERROR_INVALIDDATA;
1709
2.56M
    s->nb_components_sos = bytestream2_get_byteu(&s->gB);
1710
2.56M
    if (s->nb_components_sos == 0 || s->nb_components_sos > MAX_COMPONENTS) {
1711
293k
        avpriv_report_missing_feature(s->avctx,
1712
293k
                                      "decode_sos: nb_components (%d)",
1713
293k
                                      s->nb_components_sos);
1714
293k
        return AVERROR_PATCHWELCOME;
1715
293k
    }
1716
2.27M
    if (len != 4 + 2 * s->nb_components_sos) {
1717
83.0k
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: len(%d) mismatch %d components\n", len, s->nb_components_sos);
1718
83.0k
        return AVERROR_INVALIDDATA;
1719
83.0k
    }
1720
5.71M
    for (i = 0; i < s->nb_components_sos; i++) {
1721
3.98M
        id = bytestream2_get_byteu(&s->gB);
1722
3.98M
        av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1723
        /* find component index */
1724
7.05M
        for (index = 0; index < s->nb_components; index++)
1725
6.71M
            if (id == s->component_id[index])
1726
3.64M
                break;
1727
3.98M
        if (index == s->nb_components) {
1728
338k
            av_log(s->avctx, AV_LOG_ERROR,
1729
338k
                   "decode_sos: index(%d) out of components\n", index);
1730
338k
            return AVERROR_INVALIDDATA;
1731
338k
        }
1732
        /* Metasoft MJPEG codec has Cb and Cr swapped */
1733
3.64M
        if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1734
19.1k
            && s->nb_components_sos == 3 && s->nb_components == 3 && i)
1735
7.80k
            index = 3 - i;
1736
1737
3.64M
        s->quant_sindex[i] = s->quant_index[index];
1738
3.64M
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1739
3.64M
        s->h_scount[i]  = s->h_count[index];
1740
3.64M
        s->v_scount[i]  = s->v_count[index];
1741
1742
3.64M
        s->comp_index[i] = index;
1743
1744
3.64M
        uint8_t b = bytestream2_get_byteu(&s->gB);
1745
3.64M
        s->dc_index[i] = b >> 4;
1746
3.64M
        s->ac_index[i] = b & 0x0F;
1747
1748
3.64M
        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
1749
3.64M
            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1750
68.1k
            goto out_of_range;
1751
3.57M
        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))
1752
52.9k
            goto out_of_range;
1753
3.57M
    }
1754
1755
1.73M
    s->Ss = bytestream2_get_byteu(&s->gB); /* JPEG Ss / lossless JPEG predictor / JPEG-LS NEAR */
1756
1.73M
    s->Se = bytestream2_get_byteu(&s->gB); /* JPEG Se / JPEG-LS ILV */
1757
1.73M
    uint8_t b = bytestream2_get_byteu(&s->gB);
1758
1.73M
    s->Ah = b >> 4;   /* Ah */
1759
1.73M
    s->Al = b & 0x0F; /* Al */
1760
1761
1.73M
    if (s->nb_components_sos > 1) {
1762
        /* interleaved stream */
1763
933k
        s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
1764
933k
        s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1765
933k
    } else if (!s->ls) { /* skip this for JPEG-LS */
1766
427k
        h = s->h_max / s->h_scount[0];
1767
427k
        v = s->v_max / s->v_scount[0];
1768
427k
        s->mb_width     = (s->width  + h * block_size - 1) / (h * block_size);
1769
427k
        s->mb_height    = (s->height + v * block_size - 1) / (v * block_size);
1770
427k
        s->nb_blocks[0] = 1;
1771
427k
        s->h_scount[0]  = 1;
1772
427k
        s->v_scount[0]  = 1;
1773
427k
    }
1774
1775
1.73M
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1776
0
        av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1777
0
               s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1778
0
               s->Ss, s->Al, s->Se, s->bits, s->mjpb_skiptosod,
1779
0
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), s->nb_components_sos);
1780
1781
1782
    /* mjpeg-b can have padding bytes between sos and image data, skip them */
1783
1.73M
    if (s->mjpb_skiptosod)
1784
189k
        bytestream2_skip(&s->gB, s->mjpb_skiptosod);
1785
1786
1.73M
    if (s->avctx->hwaccel) {
1787
0
        const uint8_t *buf_ptr;
1788
0
        size_t buf_size;
1789
1790
0
        mjpeg_find_raw_scan_data(s, &buf_ptr, &buf_size);
1791
1792
0
        ret = FF_HW_CALL(s->avctx, decode_slice, buf_ptr, buf_size);
1793
0
        if (ret < 0)
1794
0
            return ret;
1795
1796
1.73M
    } else {
1797
1.73M
        if (s->lossless) {
1798
573k
            av_assert0(s->picture_ptr == s->picture);
1799
573k
            if (CONFIG_JPEGLS_DECODER && s->ls) {
1800
425k
                if ((ret = ff_jpegls_decode_picture(s)) < 0)
1801
408k
                    return ret;
1802
425k
            } else {
1803
148k
                if (s->rgb || s->bayer) {
1804
74.8k
                    if ((ret = ljpeg_decode_rgb_scan(s)) < 0)
1805
66.0k
                        return ret;
1806
74.8k
                } else {
1807
73.5k
                    if ((ret = ljpeg_decode_yuv_scan(s)) < 0)
1808
69.6k
                        return ret;
1809
73.5k
                }
1810
148k
            }
1811
1.15M
        } else {
1812
1.15M
            if (s->progressive && s->Ss) {
1813
167k
                av_assert0(s->picture_ptr == s->picture);
1814
167k
                if ((ret = mjpeg_decode_scan_progressive_ac(s)) < 0)
1815
159k
                    return ret;
1816
990k
            } else {
1817
990k
                if ((ret = mjpeg_decode_scan(s)) < 0)
1818
882k
                    return ret;
1819
990k
            }
1820
1.15M
        }
1821
1.73M
    }
1822
1823
147k
    if (s->avctx->codec_id == AV_CODEC_ID_MEDIA100 ||
1824
116k
        s->avctx->codec_id == AV_CODEC_ID_MJPEGB ||
1825
114k
        s->avctx->codec_id == AV_CODEC_ID_THP) {
1826
        /* Add the amount of bits read from the unescaped image data buffer
1827
         * into the GetByteContext. */
1828
44.4k
        bytestream2_skipu(&s->gB, (get_bits_count(&s->gb) + 7) / 8);
1829
44.4k
    }
1830
1831
147k
    return 0;
1832
121k
 out_of_range:
1833
121k
    av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1834
121k
    return AVERROR_INVALIDDATA;
1835
1.73M
}
1836
1837
static int mjpeg_decode_dri(MJpegDecodeContext *s)
1838
72.0k
{
1839
72.0k
    if (bytestream2_get_be16u(&s->gB) != 4)
1840
19.8k
        return AVERROR_INVALIDDATA;
1841
52.1k
    s->restart_interval = bytestream2_get_be16u(&s->gB);
1842
52.1k
    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1843
52.1k
           s->restart_interval);
1844
1845
52.1k
    return 0;
1846
72.0k
}
1847
1848
static int mjpeg_decode_app(MJpegDecodeContext *s, int start_code)
1849
1.07M
{
1850
1.07M
    int len, id, i;
1851
1852
1.07M
    int ret = mjpeg_parse_len(s, &len, "app");
1853
1.07M
    if (ret < 0)
1854
312k
        return AVERROR_INVALIDDATA;
1855
1856
762k
    if (len < 4) {
1857
7.20k
        if (s->avctx->err_recognition & AV_EF_EXPLODE)
1858
1.30k
            return AVERROR_INVALIDDATA;
1859
5.90k
        av_log(s->avctx, AV_LOG_VERBOSE, "skipping APPx stub (len=%" PRId32 ")\n", len);
1860
5.90k
        goto out;
1861
7.20k
    }
1862
1863
755k
    id   = bytestream2_get_be32u(&s->gB);
1864
755k
    len -= 4;
1865
1866
755k
    if (s->avctx->debug & FF_DEBUG_STARTCODE)
1867
0
        av_log(s->avctx, AV_LOG_DEBUG, "APPx (%s / %8X) len=%d\n",
1868
0
               av_fourcc2str(av_bswap32(id)), id, len);
1869
1870
    /* This fourcc is used by non-avid files too, it holds some
1871
       information, but it's always present in AVID-created files. */
1872
755k
    if (id == AV_RB32("AVI1")) {
1873
        /* structure:
1874
            4bytes      AVI1
1875
            1bytes      polarity
1876
            1bytes      always zero
1877
            4bytes      field_size
1878
            4bytes      field_size_less_padding
1879
        */
1880
6.29k
        if (len < 1)
1881
1.28k
            goto out;
1882
5.01k
        i = bytestream2_get_byteu(&s->gB); len--;
1883
5.01k
        av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1884
5.01k
        goto out;
1885
6.29k
    }
1886
1887
749k
    if (id == AV_RB32("JFIF")) {
1888
68.8k
        int t_w, t_h, v1, v2;
1889
68.8k
        if (len < 8)
1890
3.45k
            goto out;
1891
65.4k
        bytestream2_skipu(&s->gB, 1); /* the trailing zero-byte */
1892
65.4k
        v1 = bytestream2_get_byteu(&s->gB);
1893
65.4k
        v2 = bytestream2_get_byteu(&s->gB);
1894
65.4k
        bytestream2_skipu(&s->gB, 1);
1895
1896
65.4k
        s->avctx->sample_aspect_ratio.num = bytestream2_get_be16u(&s->gB);
1897
65.4k
        s->avctx->sample_aspect_ratio.den = bytestream2_get_be16u(&s->gB);
1898
65.4k
        if (   s->avctx->sample_aspect_ratio.num <= 0
1899
61.5k
            || s->avctx->sample_aspect_ratio.den <= 0) {
1900
12.6k
            s->avctx->sample_aspect_ratio.num = 0;
1901
12.6k
            s->avctx->sample_aspect_ratio.den = 1;
1902
12.6k
        }
1903
1904
65.4k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1905
0
            av_log(s->avctx, AV_LOG_INFO,
1906
0
                   "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1907
0
                   v1, v2,
1908
0
                   s->avctx->sample_aspect_ratio.num,
1909
0
                   s->avctx->sample_aspect_ratio.den);
1910
1911
65.4k
        len -= 8;
1912
65.4k
        if (len >= 2) {
1913
62.0k
            t_w = bytestream2_get_byteu(&s->gB);
1914
62.0k
            t_h = bytestream2_get_byteu(&s->gB);
1915
62.0k
            if (t_w && t_h) {
1916
                /* skip thumbnail */
1917
45.6k
                if (len - 10 - (t_w * t_h * 3) > 0)
1918
2.55k
                    len -= t_w * t_h * 3;
1919
45.6k
            }
1920
62.0k
            len -= 2;
1921
62.0k
        }
1922
65.4k
        goto out;
1923
68.8k
    }
1924
1925
680k
    if (   id == AV_RB32("Adob")
1926
62.4k
        && len >= 8
1927
60.1k
        && bytestream2_peek_byteu(&s->gB) == 'e'
1928
57.2k
        && bytestream2_peek_be32u(&s->gB) != AV_RB32("e_CM")) {
1929
55.4k
        bytestream2_skipu(&s->gB, 1); /* 'e' */
1930
55.4k
        bytestream2_skipu(&s->gB, 2); /* version */
1931
55.4k
        bytestream2_skipu(&s->gB, 2); /* flags0 */
1932
55.4k
        bytestream2_skipu(&s->gB, 2); /* flags1 */
1933
55.4k
        s->adobe_transform = bytestream2_get_byteu(&s->gB);
1934
55.4k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1935
0
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found, transform=%d\n", s->adobe_transform);
1936
55.4k
        len -= 8;
1937
55.4k
        goto out;
1938
55.4k
    }
1939
1940
625k
    if (id == AV_RB32("LJIF")) {
1941
30.7k
        int rgb = s->rgb;
1942
30.7k
        int pegasus_rct = s->pegasus_rct;
1943
30.7k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1944
0
            av_log(s->avctx, AV_LOG_INFO,
1945
0
                   "Pegasus lossless jpeg header found\n");
1946
30.7k
        if (len < 9)
1947
14.4k
            goto out;
1948
16.2k
        bytestream2_skipu(&s->gB, 2); /* version ? */
1949
16.2k
        bytestream2_skipu(&s->gB, 2); /* unknown always 0? */
1950
16.2k
        bytestream2_skipu(&s->gB, 2); /* unknown always 0? */
1951
16.2k
        bytestream2_skipu(&s->gB, 2); /* unknown always 0? */
1952
16.2k
        switch (i = bytestream2_get_byteu(&s->gB)) {
1953
3.74k
        case 1:
1954
3.74k
            rgb         = 1;
1955
3.74k
            pegasus_rct = 0;
1956
3.74k
            break;
1957
8.08k
        case 2:
1958
8.08k
            rgb         = 1;
1959
8.08k
            pegasus_rct = 1;
1960
8.08k
            break;
1961
4.40k
        default:
1962
4.40k
            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);
1963
16.2k
        }
1964
1965
16.2k
        len -= 9;
1966
16.2k
        if (s->bayer)
1967
141
            goto out;
1968
16.0k
        if (s->got_picture)
1969
12.3k
            if (rgb != s->rgb || pegasus_rct != s->pegasus_rct) {
1970
7.68k
                av_log(s->avctx, AV_LOG_WARNING, "Mismatching LJIF tag\n");
1971
7.68k
                goto out;
1972
7.68k
            }
1973
1974
8.40k
        s->rgb = rgb;
1975
8.40k
        s->pegasus_rct = pegasus_rct;
1976
1977
8.40k
        goto out;
1978
16.0k
    }
1979
594k
    if (id == AV_RL32("colr") && len > 0) {
1980
7.45k
        s->colr = bytestream2_get_byteu(&s->gB);
1981
7.45k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1982
0
            av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1983
7.45k
        len--;
1984
7.45k
        goto out;
1985
7.45k
    }
1986
586k
    if (id == AV_RL32("xfrm") && len > 0) {
1987
8.53k
        s->xfrm = bytestream2_get_byteu(&s->gB);
1988
8.53k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1989
0
            av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1990
8.53k
        len--;
1991
8.53k
        goto out;
1992
8.53k
    }
1993
1994
    /* JPS extension by VRex */
1995
578k
    if (start_code == APP3 && id == AV_RB32("_JPS") && len >= 10) {
1996
59.0k
        int flags, layout, type;
1997
59.0k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1998
0
            av_log(s->avctx, AV_LOG_INFO, "_JPSJPS_\n");
1999
2000
59.0k
        bytestream2_skipu(&s->gB, 4); len -= 4;  /* JPS_ */
2001
59.0k
        bytestream2_skipu(&s->gB, 2); len -= 2;  /* block length */
2002
59.0k
        bytestream2_skipu(&s->gB, 1);            /* reserved */
2003
59.0k
        flags  = bytestream2_get_byteu(&s->gB);
2004
59.0k
        layout = bytestream2_get_byteu(&s->gB);
2005
59.0k
        type   = bytestream2_get_byteu(&s->gB);
2006
59.0k
        len -= 4;
2007
2008
59.0k
        av_freep(&s->stereo3d);
2009
59.0k
        s->stereo3d = av_stereo3d_alloc();
2010
59.0k
        if (!s->stereo3d) {
2011
0
            goto out;
2012
0
        }
2013
59.0k
        if (type == 0) {
2014
21.0k
            s->stereo3d->type = AV_STEREO3D_2D;
2015
38.0k
        } else if (type == 1) {
2016
8.92k
            switch (layout) {
2017
1.71k
            case 0x01:
2018
1.71k
                s->stereo3d->type = AV_STEREO3D_LINES;
2019
1.71k
                break;
2020
1.47k
            case 0x02:
2021
1.47k
                s->stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
2022
1.47k
                break;
2023
1.36k
            case 0x03:
2024
1.36k
                s->stereo3d->type = AV_STEREO3D_TOPBOTTOM;
2025
1.36k
                break;
2026
8.92k
            }
2027
8.92k
            if (!(flags & 0x04)) {
2028
4.95k
                s->stereo3d->flags = AV_STEREO3D_FLAG_INVERT;
2029
4.95k
            }
2030
8.92k
        }
2031
59.0k
        goto out;
2032
59.0k
    }
2033
2034
    /* EXIF metadata */
2035
519k
    if (start_code == APP1 && id == AV_RB32("Exif") && len >= 2) {
2036
236k
        int ret;
2037
2038
236k
        bytestream2_skipu(&s->gB, 2); // skip padding
2039
236k
        len -= 2;
2040
2041
236k
        if (s->exif_metadata.entries) {
2042
29.1k
            av_log(s->avctx, AV_LOG_WARNING, "multiple EXIF\n");
2043
29.1k
            goto out;
2044
29.1k
        }
2045
2046
206k
        ret = av_exif_parse_buffer(s->avctx, s->gB.buffer, len, &s->exif_metadata, AV_EXIF_TIFF_HEADER);
2047
206k
        if (ret < 0) {
2048
118k
            av_log(s->avctx, AV_LOG_WARNING, "unable to parse EXIF buffer\n");
2049
118k
            goto out;
2050
118k
        }
2051
2052
88.4k
        bytestream2_skipu(&s->gB, ret);
2053
88.4k
        len -= ret;
2054
2055
88.4k
        goto out;
2056
206k
    }
2057
2058
    /* Apple MJPEG-A */
2059
283k
    if ((start_code == APP1) && (len > (0x28 - 8))) {
2060
21.8k
        id   = bytestream2_get_be32u(&s->gB);
2061
21.8k
        len -= 4;
2062
        /* Apple MJPEG-A */
2063
21.8k
        if (id == AV_RB32("mjpg")) {
2064
            /* structure:
2065
                4bytes      field size
2066
                4bytes      pad field size
2067
                4bytes      next off
2068
                4bytes      quant off
2069
                4bytes      huff off
2070
                4bytes      image off
2071
                4bytes      scan off
2072
                4bytes      data off
2073
            */
2074
2.09k
            if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2075
0
                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
2076
2.09k
        }
2077
21.8k
    }
2078
2079
283k
    if (start_code == APP2 && id == AV_RB32("ICC_") && len >= 10) {
2080
98.9k
        int id2;
2081
98.9k
        unsigned seqno;
2082
98.9k
        unsigned nummarkers;
2083
2084
98.9k
        id   = bytestream2_get_be32u(&s->gB);
2085
98.9k
        id2  = bytestream2_get_be24u(&s->gB);
2086
98.9k
        len -= 7;
2087
98.9k
        if (id != AV_RB32("PROF") || id2 != AV_RB24("ILE")) {
2088
20.8k
            av_log(s->avctx, AV_LOG_WARNING, "Invalid ICC_PROFILE header in APP2\n");
2089
20.8k
            goto out;
2090
20.8k
        }
2091
2092
78.1k
        bytestream2_skipu(&s->gB, 1);
2093
78.1k
        seqno  = bytestream2_get_byteu(&s->gB);
2094
78.1k
        len   -= 2;
2095
78.1k
        if (seqno == 0) {
2096
3.47k
            av_log(s->avctx, AV_LOG_WARNING, "Invalid sequence number in APP2\n");
2097
3.47k
            goto out;
2098
3.47k
        }
2099
2100
74.6k
        nummarkers  = bytestream2_get_byteu(&s->gB);
2101
74.6k
        len        -= 1;
2102
74.6k
        if (nummarkers == 0) {
2103
4.80k
            av_log(s->avctx, AV_LOG_WARNING, "Invalid number of markers coded in APP2\n");
2104
4.80k
            goto out;
2105
69.8k
        } else if (s->iccnum != 0 && nummarkers != s->iccnum) {
2106
9.10k
            av_log(s->avctx, AV_LOG_WARNING, "Mismatch in coded number of ICC markers between markers\n");
2107
9.10k
            goto out;
2108
60.7k
        } else if (seqno > nummarkers) {
2109
4.57k
            av_log(s->avctx, AV_LOG_WARNING, "Mismatching sequence number and coded number of ICC markers\n");
2110
4.57k
            goto out;
2111
4.57k
        }
2112
2113
        /* Allocate if this is the first APP2 we've seen. */
2114
56.1k
        if (s->iccnum == 0) {
2115
43.3k
            if (!FF_ALLOCZ_TYPED_ARRAY(s->iccentries, nummarkers)) {
2116
0
                av_log(s->avctx, AV_LOG_ERROR, "Could not allocate ICC data arrays\n");
2117
0
                return AVERROR(ENOMEM);
2118
0
            }
2119
43.3k
            s->iccnum = nummarkers;
2120
43.3k
        }
2121
2122
56.1k
        if (s->iccentries[seqno - 1].data) {
2123
8.16k
            av_log(s->avctx, AV_LOG_WARNING, "Duplicate ICC sequence number\n");
2124
8.16k
            goto out;
2125
8.16k
        }
2126
2127
47.9k
        s->iccentries[seqno - 1].length = len;
2128
47.9k
        s->iccentries[seqno - 1].data   = av_malloc(len);
2129
47.9k
        if (!s->iccentries[seqno - 1].data) {
2130
0
            av_log(s->avctx, AV_LOG_ERROR, "Could not allocate ICC data buffer\n");
2131
0
            return AVERROR(ENOMEM);
2132
0
        }
2133
2134
47.9k
        bytestream2_get_bufferu(&s->gB, s->iccentries[seqno - 1].data, len);
2135
47.9k
        len = 0;
2136
47.9k
        s->iccread++;
2137
2138
47.9k
        if (s->iccread > s->iccnum)
2139
0
            av_log(s->avctx, AV_LOG_WARNING, "Read more ICC markers than are supposed to be coded\n");
2140
47.9k
    }
2141
2142
761k
out:
2143
    /* slow but needed for extreme adobe jpegs */
2144
761k
    if (len < 0)
2145
0
        av_log(s->avctx, AV_LOG_ERROR,
2146
0
               "mjpeg: error, decode_app parser read over the end\n");
2147
761k
    if (len > 0)
2148
542k
        bytestream2_skipu(&s->gB, len);
2149
2150
761k
    return 0;
2151
283k
}
2152
2153
static int mjpeg_decode_com(MJpegDecodeContext *s)
2154
172k
{
2155
172k
    int len;
2156
172k
    int ret = mjpeg_parse_len(s, &len, "com");
2157
172k
    if (ret < 0)
2158
59.0k
        return ret;
2159
113k
    if (!len)
2160
17.7k
        return 0;
2161
2162
95.5k
    int i;
2163
95.5k
    char *cbuf = av_malloc(len + 1);
2164
95.5k
    if (!cbuf)
2165
0
        return AVERROR(ENOMEM);
2166
2167
10.8M
    for (i = 0; i < len; i++)
2168
10.7M
        cbuf[i] = bytestream2_get_byteu(&s->gB);
2169
95.5k
    if (cbuf[i - 1] == '\n')
2170
5.93k
        cbuf[i - 1] = 0;
2171
89.5k
    else
2172
89.5k
        cbuf[i] = 0;
2173
2174
95.5k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2175
0
        av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
2176
2177
    /* buggy avid, it puts EOI only at every 10th frame */
2178
95.5k
    if (!strncmp(cbuf, "AVID", 4)) {
2179
11.5k
        parse_avid(s, cbuf, len);
2180
83.9k
    } else if (!strcmp(cbuf, "CS=ITU601"))
2181
8.36k
        s->cs_itu601 = 1;
2182
75.5k
    else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32) && s->avctx->codec_tag) ||
2183
70.8k
             (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
2184
11.5k
        s->flipped = 1;
2185
63.9k
    else if (!strcmp(cbuf, "MULTISCOPE II")) {
2186
4.96k
        s->avctx->sample_aspect_ratio = (AVRational) { 1, 2 };
2187
4.96k
        s->multiscope = 2;
2188
4.96k
    }
2189
2190
95.5k
    av_free(cbuf);
2191
2192
95.5k
    return 0;
2193
95.5k
}
2194
2195
/* return the 8 bit start code value and update the search
2196
   state. Return -1 if no start code found */
2197
int ff_mjpeg_find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
2198
11.7M
{
2199
11.7M
    const uint8_t *buf_ptr;
2200
11.7M
    int val;
2201
2202
11.7M
    buf_ptr = *pbuf_ptr;
2203
15.5M
    while ((buf_ptr = memchr(buf_ptr, 0xff, buf_end - buf_ptr))) {
2204
14.5M
        buf_ptr++;
2205
23.8M
        while (buf_ptr < buf_end) {
2206
23.7M
            val = *buf_ptr++;
2207
23.7M
            if (val != 0xff) {
2208
14.3M
                if ((val >= SOF0) && (val <= COM))
2209
10.6M
                    goto found;
2210
3.75M
                break;
2211
14.3M
            }
2212
23.7M
        }
2213
14.5M
    }
2214
1.08M
    buf_ptr = buf_end;
2215
1.08M
    val = -1;
2216
11.7M
found:
2217
11.7M
    ff_dlog(NULL, "find_marker skipped %td bytes\n",
2218
11.7M
            (buf_ptr - *pbuf_ptr) - (val < 0 ? 0 : 2));
2219
11.7M
    *pbuf_ptr = buf_ptr;
2220
11.7M
    return val;
2221
1.08M
}
2222
2223
static void mjpeg_find_raw_scan_data(MJpegDecodeContext *s,
2224
                                     const uint8_t **pbuf_ptr, size_t *pbuf_size)
2225
0
{
2226
0
    const uint8_t *buf_ptr = s->gB.buffer;
2227
0
    const uint8_t *buf_end = buf_ptr + bytestream2_get_bytes_left(&s->gB);
2228
2229
    /* Find size of image data buffer (including restart markers).
2230
     * No unescaping is performed. */
2231
0
    const uint8_t *ptr = buf_ptr;
2232
0
    while ((ptr = memchr(ptr, 0xff, buf_end - ptr))) {
2233
0
        ptr++;
2234
0
        if (ptr < buf_end) {
2235
0
            uint8_t x = *ptr++;
2236
            /* Discard multiple optional 0xFF fill bytes. */
2237
0
            while (x == 0xff && ptr < buf_end)
2238
0
                x = *ptr++;
2239
0
            if (x && (x < RST0 || x > RST7)) {
2240
                /* Non-restart marker */
2241
0
                ptr -= 2;
2242
0
                goto found_hw;
2243
0
            }
2244
0
        }
2245
0
    }
2246
0
    ptr = buf_end;
2247
0
found_hw:
2248
0
    *pbuf_ptr = buf_ptr;
2249
0
    *pbuf_size = ptr - buf_ptr;
2250
0
    bytestream2_skipu(&s->gB, *pbuf_size);
2251
0
}
2252
2253
int ff_mjpeg_unescape_sos(MJpegDecodeContext *s)
2254
100M
{
2255
100M
    const uint8_t *buf_ptr = s->gB.buffer;
2256
100M
    const uint8_t *buf_end = buf_ptr + bytestream2_get_bytes_left(&s->gB);
2257
100M
    const uint8_t *unescaped_buf_ptr;
2258
100M
    size_t unescaped_buf_size;
2259
2260
100M
    if (s->avctx->codec_id == AV_CODEC_ID_MEDIA100 ||
2261
100M
        s->avctx->codec_id == AV_CODEC_ID_MJPEGB ||
2262
100M
        s->avctx->codec_id == AV_CODEC_ID_THP) {
2263
        /* The image data buffer is already unescaped. The only way to
2264
         * find the size of the buffer is by fully decoding it. */
2265
90.4M
        unescaped_buf_ptr  = buf_ptr;
2266
90.4M
        unescaped_buf_size = buf_end - buf_ptr;
2267
90.4M
        goto the_end;
2268
90.4M
    }
2269
2270
10.4M
    av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - buf_ptr);
2271
10.4M
    if (!s->buffer)
2272
0
        return AVERROR(ENOMEM);
2273
2274
    /* unescape buffer of SOS, use special treatment for JPEG-LS */
2275
10.4M
    if (!s->ls) {
2276
10.1M
        const uint8_t *src = buf_ptr;
2277
10.1M
        const uint8_t *ptr = src;
2278
10.1M
        uint8_t *dst = s->buffer;
2279
10.1M
        PutByteContext pb;
2280
2281
10.1M
        bytestream2_init_writer(&pb, dst, buf_end - src);
2282
2283
12.1M
        while ((ptr = memchr(ptr, 0xff, buf_end - ptr))) {
2284
11.7M
            ptr++;
2285
11.7M
            if (ptr < buf_end) {
2286
                /* Copy verbatim data. */
2287
11.7M
                ptrdiff_t length = (ptr - 1) - src;
2288
11.7M
                if (length > 0)
2289
1.51M
                    bytestream2_put_bufferu(&pb, src, length);
2290
2291
11.7M
                uint8_t x = *ptr++;
2292
                /* Discard multiple optional 0xFF fill bytes. */
2293
13.0M
                while (x == 0xff && ptr < buf_end)
2294
1.25M
                    x = *ptr++;
2295
2296
11.7M
                src = ptr;
2297
11.7M
                if (x == 0) {
2298
                    /* Stuffed zero byte */
2299
1.93M
                    bytestream2_put_byteu(&pb, 0xff);
2300
9.85M
                } else if (x >= RST0 && x <= RST7) {
2301
                    /* Restart marker */
2302
39.8k
                    goto found;
2303
9.81M
                } else {
2304
                    /* Non-restart marker */
2305
9.81M
                    ptr -= 2;
2306
9.81M
                    goto found;
2307
9.81M
                }
2308
11.7M
            }
2309
11.7M
        }
2310
        /* Copy remaining verbatim data. */
2311
327k
        ptr = buf_end;
2312
327k
        ptrdiff_t length = ptr - src;
2313
327k
        if (length > 0)
2314
51.8k
            bytestream2_put_bufferu(&pb, src, length);
2315
2316
10.1M
found:
2317
10.1M
        unescaped_buf_ptr  = s->buffer;
2318
10.1M
        unescaped_buf_size = bytestream2_tell_p(&pb);
2319
10.1M
        memset(s->buffer + unescaped_buf_size, 0,
2320
10.1M
               AV_INPUT_BUFFER_PADDING_SIZE);
2321
2322
10.1M
        bytestream2_skipu(&s->gB, ptr - buf_ptr);
2323
2324
10.1M
        av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
2325
10.1M
               (buf_end - buf_ptr) - (unescaped_buf_size));
2326
10.1M
    } else {
2327
291k
        const uint8_t *src = buf_ptr;
2328
291k
        const uint8_t *ptr = src;
2329
291k
        uint8_t *dst  = s->buffer;
2330
291k
        PutBitContext pb;
2331
2332
291k
        init_put_bits(&pb, dst, buf_end - src);
2333
2334
663k
        while ((ptr = memchr(ptr, 0xff, buf_end - ptr))) {
2335
630k
            ptr++;
2336
630k
            if (ptr < buf_end) {
2337
                /* Copy verbatim data. */
2338
630k
                ptrdiff_t length = (ptr - 1) - src;
2339
630k
                if (length > 0)
2340
563k
                    ff_copy_bits(&pb, src, length * 8);
2341
2342
630k
                uint8_t x = *ptr++;
2343
                /* Discard multiple optional 0xFF fill bytes. */
2344
1.49M
                while (x == 0xff && ptr < buf_end)
2345
861k
                    x = *ptr++;
2346
2347
630k
                src = ptr;
2348
630k
                if (!(x & 0x80)) {
2349
                    /* Stuffed zero bit */
2350
371k
                    put_bits(&pb, 15, 0x7f80 | x);
2351
371k
                } else if (x >= RST0 && x <= RST7) {
2352
                    /* Restart marker */
2353
3.82k
                    goto found_ls;
2354
254k
                } else {
2355
                    /* Non-restart marker */
2356
254k
                    ptr -= 2;
2357
254k
                    goto found_ls;
2358
254k
                }
2359
630k
            }
2360
630k
        }
2361
        /* Copy remaining verbatim data. */
2362
32.9k
        ptr = buf_end;
2363
32.9k
        ptrdiff_t length = ptr - src;
2364
32.9k
        if (length > 0)
2365
29.6k
            ff_copy_bits(&pb, src, length * 8);
2366
2367
291k
found_ls:
2368
291k
        flush_put_bits(&pb);
2369
2370
291k
        unescaped_buf_ptr  = dst;
2371
291k
        unescaped_buf_size = put_bytes_output(&pb);
2372
291k
        memset(s->buffer + unescaped_buf_size, 0,
2373
291k
               AV_INPUT_BUFFER_PADDING_SIZE);
2374
2375
291k
        bytestream2_skipu(&s->gB, ptr - buf_ptr);
2376
291k
    }
2377
2378
100M
the_end:
2379
100M
    return init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
2380
10.4M
}
2381
2382
static void reset_icc_profile(MJpegDecodeContext *s)
2383
119k
{
2384
119k
    int i;
2385
2386
119k
    if (s->iccentries) {
2387
2.29M
        for (i = 0; i < s->iccnum; i++)
2388
2.25M
            av_freep(&s->iccentries[i].data);
2389
43.3k
        av_freep(&s->iccentries);
2390
43.3k
    }
2391
2392
119k
    s->iccread = 0;
2393
119k
    s->iccnum  = 0;
2394
119k
}
2395
2396
int ff_mjpeg_decode_frame_from_buf(AVCodecContext *avctx, AVFrame *frame,
2397
                                   int *got_frame, const AVPacket *avpkt,
2398
                                   const uint8_t *buf, const int buf_size)
2399
2.45M
{
2400
2.45M
    MJpegDecodeContext *s = avctx->priv_data;
2401
2.45M
    const uint8_t *buf_end, *buf_ptr;
2402
2.45M
    int hshift, vshift;
2403
2.45M
    int start_code;
2404
2.45M
    int index;
2405
2.45M
    int ret = 0;
2406
2.45M
    int is16bit;
2407
2408
2.45M
    s->force_pal8 = 0;
2409
2410
2.45M
    s->buf_size = buf_size;
2411
2412
2.45M
    av_exif_free(&s->exif_metadata);
2413
2.45M
    av_freep(&s->stereo3d);
2414
2.45M
    s->adobe_transform = -1;
2415
2416
2.45M
    if (s->iccnum != 0)
2417
42.6k
        reset_icc_profile(s);
2418
2419
2.47M
redo_for_pal8:
2420
2.47M
    buf_ptr = buf;
2421
2.47M
    buf_end = buf + buf_size;
2422
11.7M
    while (buf_ptr < buf_end) {
2423
        /* find start next marker */
2424
11.4M
        start_code = ff_mjpeg_find_marker(&buf_ptr, buf_end);
2425
        /* EOF */
2426
11.4M
        if (start_code < 0)
2427
984k
            break;
2428
2429
10.4M
        ptrdiff_t bytes_left = buf_end - buf_ptr;
2430
10.4M
        if (bytes_left > INT_MAX / 8) {
2431
0
            av_log(avctx, AV_LOG_ERROR,
2432
0
                   "MJPEG packet 0x%x too big (%td/%d), corrupt data?\n",
2433
0
                   start_code, bytes_left, buf_size);
2434
0
            return AVERROR_INVALIDDATA;
2435
0
        }
2436
10.4M
        av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
2437
10.4M
               start_code, buf_end - buf_ptr);
2438
2439
10.4M
        bytestream2_init(&s->gB, buf_ptr, bytes_left);
2440
2441
10.4M
        if (avctx->debug & FF_DEBUG_STARTCODE)
2442
0
            av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
2443
2444
        /* process markers */
2445
10.4M
        if (start_code >= RST0 && start_code <= RST7) {
2446
260k
            av_log(avctx, AV_LOG_DEBUG,
2447
260k
                   "restart marker: %d\n", start_code & 0x0f);
2448
            /* APP fields */
2449
10.2M
        } else if (start_code >= APP0 && start_code <= APP15) {
2450
1.07M
            if ((ret = mjpeg_decode_app(s, start_code)) < 0)
2451
313k
                av_log(avctx, AV_LOG_ERROR, "unable to decode APP fields: %s\n",
2452
313k
                       av_err2str(ret));
2453
            /* Comment */
2454
9.15M
        } else if (start_code == COM) {
2455
172k
            ret = mjpeg_decode_com(s);
2456
172k
            if (ret < 0)
2457
59.0k
                return ret;
2458
8.98M
        } else if (start_code == DQT) {
2459
843k
            ret = ff_mjpeg_decode_dqt(s);
2460
843k
            if (ret < 0)
2461
44.3k
                return ret;
2462
843k
        }
2463
2464
10.3M
        ret = -1;
2465
2466
10.3M
        if (!CONFIG_JPEGLS_DECODER &&
2467
0
            (start_code == SOF55 || start_code == LSE)) {
2468
0
            av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
2469
0
            return AVERROR(ENOSYS);
2470
0
        }
2471
2472
10.3M
        if (avctx->skip_frame == AVDISCARD_ALL) {
2473
87.5k
            switch (start_code) {
2474
3.99k
            case SOF0:
2475
5.90k
            case SOF1:
2476
8.55k
            case SOF2:
2477
10.5k
            case SOF3:
2478
63.9k
            case SOF55:
2479
63.9k
                break;
2480
23.5k
            default:
2481
23.5k
                goto skip;
2482
87.5k
            }
2483
87.5k
        }
2484
2485
10.3M
        switch (start_code) {
2486
1.11M
        case SOI:
2487
1.11M
            s->restart_interval = 0;
2488
1.11M
            s->raw_image_buffer      = buf_ptr;
2489
1.11M
            s->raw_image_buffer_size = buf_end - buf_ptr;
2490
            /* nothing to do on SOI */
2491
1.11M
            break;
2492
808k
        case DHT:
2493
808k
            if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
2494
45.7k
                av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
2495
45.7k
                goto fail;
2496
45.7k
            }
2497
762k
            break;
2498
970k
        case SOF0:
2499
1.14M
        case SOF1:
2500
1.14M
            if (start_code == SOF0)
2501
970k
                avctx->profile = AV_PROFILE_MJPEG_HUFFMAN_BASELINE_DCT;
2502
172k
            else
2503
172k
                avctx->profile = AV_PROFILE_MJPEG_HUFFMAN_EXTENDED_SEQUENTIAL_DCT;
2504
1.14M
            s->lossless    = 0;
2505
1.14M
            s->ls          = 0;
2506
1.14M
            s->progressive = 0;
2507
1.14M
            if ((ret = ff_mjpeg_decode_sof(s)) < 0)
2508
321k
                goto fail;
2509
821k
            break;
2510
821k
        case SOF2:
2511
404k
            avctx->profile = AV_PROFILE_MJPEG_HUFFMAN_PROGRESSIVE_DCT;
2512
404k
            s->lossless    = 0;
2513
404k
            s->ls          = 0;
2514
404k
            s->progressive = 1;
2515
404k
            if ((ret = ff_mjpeg_decode_sof(s)) < 0)
2516
113k
                goto fail;
2517
291k
            break;
2518
291k
        case SOF3:
2519
265k
            avctx->profile     = AV_PROFILE_MJPEG_HUFFMAN_LOSSLESS;
2520
265k
#if FF_API_CODEC_PROPS
2521
265k
FF_DISABLE_DEPRECATION_WARNINGS
2522
265k
            avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
2523
265k
FF_ENABLE_DEPRECATION_WARNINGS
2524
265k
#endif
2525
265k
            s->lossless    = 1;
2526
265k
            s->ls          = 0;
2527
265k
            s->progressive = 0;
2528
265k
            if ((ret = ff_mjpeg_decode_sof(s)) < 0)
2529
73.8k
                goto fail;
2530
191k
            break;
2531
319k
        case SOF55:
2532
319k
            avctx->profile     = AV_PROFILE_MJPEG_JPEG_LS;
2533
319k
#if FF_API_CODEC_PROPS
2534
319k
FF_DISABLE_DEPRECATION_WARNINGS
2535
319k
            avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
2536
319k
FF_ENABLE_DEPRECATION_WARNINGS
2537
319k
#endif
2538
319k
            s->lossless    = 1;
2539
319k
            s->ls          = 1;
2540
319k
            s->progressive = 0;
2541
319k
            if ((ret = ff_mjpeg_decode_sof(s)) < 0)
2542
45.5k
                goto fail;
2543
273k
            break;
2544
273k
        case LSE:
2545
166k
            if (!CONFIG_JPEGLS_DECODER ||
2546
166k
                (ret = ff_jpegls_decode_lse(s)) < 0)
2547
46.8k
                goto fail;
2548
119k
            if (ret == 1)
2549
27.3k
                goto redo_for_pal8;
2550
92.0k
            break;
2551
400k
        case EOI:
2552
852k
eoi_parser:
2553
852k
            if (!avctx->hwaccel &&
2554
852k
                s->progressive && s->cur_scan && s->got_picture)
2555
174k
                mjpeg_idct_scan_progressive_ac(s);
2556
852k
            s->cur_scan = 0;
2557
852k
            if (!s->got_picture) {
2558
36.4k
                av_log(avctx, AV_LOG_WARNING,
2559
36.4k
                       "Found EOI before any SOF, ignoring\n");
2560
36.4k
                break;
2561
36.4k
            }
2562
815k
            if (s->interlaced) {
2563
8.93k
                s->bottom_field ^= 1;
2564
                /* if not bottom field, do not output image yet */
2565
8.93k
                if (s->bottom_field == !s->interlace_polarity)
2566
5.03k
                    break;
2567
8.93k
            }
2568
810k
            if (avctx->hwaccel) {
2569
0
                ret = FF_HW_SIMPLE_CALL(avctx, end_frame);
2570
0
                if (ret < 0)
2571
0
                    return ret;
2572
2573
0
                av_freep(&s->hwaccel_picture_private);
2574
0
            }
2575
810k
            if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
2576
0
                return ret;
2577
810k
            if (s->lossless)
2578
159k
                frame->flags |= AV_FRAME_FLAG_LOSSLESS;
2579
810k
            *got_frame = 1;
2580
810k
            s->got_picture = 0;
2581
2582
810k
            if (!s->lossless && avctx->debug & FF_DEBUG_QP) {
2583
32.9k
                int qp = FFMAX3(s->qscale[0],
2584
32.9k
                                s->qscale[1],
2585
32.9k
                                s->qscale[2]);
2586
2587
32.9k
                av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
2588
32.9k
            }
2589
2590
810k
            goto the_end;
2591
3.00M
        case SOS:
2592
3.00M
            s->cur_scan++;
2593
2594
3.00M
            if ((ret = ff_mjpeg_decode_sos(s)) < 0 &&
2595
2.89M
                (avctx->err_recognition & AV_EF_EXPLODE))
2596
9.91k
                goto fail;
2597
2.99M
            break;
2598
2.99M
        case DRI:
2599
72.0k
            if ((ret = mjpeg_decode_dri(s)) < 0)
2600
19.8k
                return ret;
2601
52.1k
            break;
2602
52.1k
        case SOF5:
2603
13.7k
        case SOF6:
2604
30.3k
        case SOF7:
2605
82.9k
        case SOF9:
2606
112k
        case SOF10:
2607
121k
        case SOF11:
2608
134k
        case SOF13:
2609
147k
        case SOF14:
2610
180k
        case SOF15:
2611
189k
        case JPG:
2612
189k
            av_log(avctx, AV_LOG_ERROR,
2613
189k
                   "mjpeg: unsupported coding type (%x)\n", start_code);
2614
189k
            break;
2615
10.3M
        }
2616
2617
9.30M
        if (avctx->skip_frame == AVDISCARD_ALL) {
2618
57.6k
            switch (start_code) {
2619
2.09k
            case SOF0:
2620
3.19k
            case SOF1:
2621
4.68k
            case SOF2:
2622
5.68k
            case SOF3:
2623
57.6k
            case SOF55:
2624
57.6k
                s->got_picture = 0;
2625
57.6k
                goto the_end_no_picture;
2626
57.6k
            }
2627
57.6k
        }
2628
2629
9.27M
skip:
2630
        /* eof process start code */
2631
9.27M
        buf_ptr += bytestream2_tell(&s->gB);
2632
9.27M
        av_log(avctx, AV_LOG_DEBUG,
2633
9.27M
               "marker parser used %d bytes\n",
2634
9.27M
               bytestream2_tell(&s->gB));
2635
9.27M
    }
2636
1.25M
    if (s->got_picture && s->cur_scan) {
2637
451k
        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
2638
451k
        goto eoi_parser;
2639
451k
    }
2640
802k
    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
2641
802k
    return AVERROR_INVALIDDATA;
2642
656k
fail:
2643
656k
    s->got_picture = 0;
2644
656k
    return ret;
2645
810k
the_end:
2646
2647
810k
    is16bit = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].step > 1;
2648
2649
810k
    if (AV_RB32(s->upscale_h)) {
2650
128k
        int p;
2651
128k
        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
2652
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
2653
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
2654
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUV440P  ||
2655
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||
2656
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
2657
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUV422P  ||
2658
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
2659
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUV420P  ||
2660
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUV420P16||
2661
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P  ||
2662
128k
                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P16||
2663
128k
                   avctx->pix_fmt == AV_PIX_FMT_GBRP     ||
2664
128k
                   avctx->pix_fmt == AV_PIX_FMT_GBRAP
2665
128k
                  );
2666
128k
        ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &hshift, &vshift);
2667
128k
        if (ret)
2668
0
            return ret;
2669
2670
128k
        av_assert0(s->nb_components == av_pix_fmt_count_planes(s->picture_ptr->format));
2671
552k
        for (p = 0; p < s->nb_components; p++) {
2672
423k
            uint8_t *line = s->picture_ptr->data[p];
2673
423k
            int w = s->width;
2674
423k
            int h = s->height;
2675
423k
            if (!s->upscale_h[p])
2676
242k
                continue;
2677
181k
            if (p == 1 || p == 2) {
2678
141k
                w = AV_CEIL_RSHIFT(w, hshift);
2679
141k
                h = AV_CEIL_RSHIFT(h, vshift);
2680
141k
            }
2681
181k
            if (s->upscale_v[p] == 1)
2682
77.7k
                h = (h + 1) >> 1;
2683
181k
            av_assert0(w > 0);
2684
16.3M
            for (int i = 0; i < h; i++) {
2685
16.1M
                if (s->upscale_h[p] == 1) {
2686
9.42M
                    if (is16bit) ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 2];
2687
8.61M
                    else                      line[w - 1] = line[(w - 1) / 2];
2688
747M
                    for (index = w - 2; index > 0; index--) {
2689
738M
                        if (is16bit)
2690
49.1M
                            ((uint16_t*)line)[index] = (((uint16_t*)line)[index / 2] + ((uint16_t*)line)[(index + 1) / 2]) >> 1;
2691
688M
                        else
2692
688M
                            line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
2693
738M
                    }
2694
9.42M
                } else if (s->upscale_h[p] == 2) {
2695
6.48M
                    if (is16bit) {
2696
0
                        ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 3];
2697
0
                        if (w > 1)
2698
0
                            ((uint16_t*)line)[w - 2] = ((uint16_t*)line)[w - 1];
2699
6.48M
                    } else {
2700
6.48M
                        line[w - 1] = line[(w - 1) / 3];
2701
6.48M
                        if (w > 1)
2702
6.13M
                            line[w - 2] = line[w - 1];
2703
6.48M
                    }
2704
195M
                    for (index = w - 3; index > 0; index--) {
2705
188M
                        line[index] = (line[index / 3] + line[(index + 1) / 3] + line[(index + 2) / 3] + 1) / 3;
2706
188M
                    }
2707
6.48M
                } else if (s->upscale_h[p] == 4) {
2708
259k
                    if (is16bit) {
2709
0
                        uint16_t *line16 = (uint16_t *) line;
2710
0
                        line16[w - 1] = line16[(w - 1) >> 2];
2711
0
                        if (w > 1)
2712
0
                            line16[w - 2] = (line16[(w - 1) >> 2] * 3 + line16[(w - 2) >> 2]) >> 2;
2713
0
                        if (w > 2)
2714
0
                            line16[w - 3] = (line16[(w - 1) >> 2] + line16[(w - 2) >> 2]) >> 1;
2715
259k
                    } else {
2716
259k
                        line[w - 1] = line[(w - 1) >> 2];
2717
259k
                        if (w > 1)
2718
145k
                            line[w - 2] = (line[(w - 1) >> 2] * 3 + line[(w - 2) >> 2]) >> 2;
2719
259k
                        if (w > 2)
2720
145k
                            line[w - 3] = (line[(w - 1) >> 2] + line[(w - 2) >> 2]) >> 1;
2721
259k
                    }
2722
69.0M
                    for (index = w - 4; index > 0; index--)
2723
68.8M
                        line[index] = (line[(index + 3) >> 2] + line[(index + 2) >> 2]
2724
68.8M
                            + line[(index + 1) >> 2] + line[index >> 2]) >> 2;
2725
259k
                }
2726
16.1M
                line += s->linesize[p];
2727
16.1M
            }
2728
181k
        }
2729
128k
    }
2730
810k
    if (AV_RB32(s->upscale_v)) {
2731
126k
        int p;
2732
126k
        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
2733
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||
2734
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
2735
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUV422P  ||
2736
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
2737
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUV420P  ||
2738
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUV440P  ||
2739
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
2740
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||
2741
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P  ||
2742
126k
                   avctx->pix_fmt == AV_PIX_FMT_YUVA420P16||
2743
126k
                   avctx->pix_fmt == AV_PIX_FMT_GBRP     ||
2744
126k
                   avctx->pix_fmt == AV_PIX_FMT_GBRAP
2745
126k
                   );
2746
126k
        ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &hshift, &vshift);
2747
126k
        if (ret)
2748
0
            return ret;
2749
2750
126k
        av_assert0(s->nb_components == av_pix_fmt_count_planes(s->picture_ptr->format));
2751
545k
        for (p = 0; p < s->nb_components; p++) {
2752
418k
            uint8_t *dst;
2753
418k
            int w = s->width;
2754
418k
            int h = s->height;
2755
418k
            if (!s->upscale_v[p])
2756
218k
                continue;
2757
200k
            if (p == 1 || p == 2) {
2758
162k
                w = AV_CEIL_RSHIFT(w, hshift);
2759
162k
                h = AV_CEIL_RSHIFT(h, vshift);
2760
162k
            }
2761
200k
            dst = &((uint8_t *)s->picture_ptr->data[p])[(h - 1) * s->linesize[p]];
2762
17.4M
            for (int i = h - 1; i; i--) {
2763
17.2M
                uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[p])[i * s->upscale_v[p] / (s->upscale_v[p] + 1) * s->linesize[p]];
2764
17.2M
                uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[p])[(i + 1) * s->upscale_v[p] / (s->upscale_v[p] + 1) * s->linesize[p]];
2765
17.2M
                if (s->upscale_v[p] != 2 && (src1 == src2 || i == h - 1)) {
2766
8.14M
                    memcpy(dst, src1, w);
2767
9.12M
                } else {
2768
676M
                    for (index = 0; index < w; index++)
2769
667M
                        dst[index] = (src1[index] + src2[index]) >> 1;
2770
9.12M
                }
2771
17.2M
                dst -= s->linesize[p];
2772
17.2M
            }
2773
200k
        }
2774
126k
    }
2775
810k
    if (s->flipped && !s->rgb) {
2776
299k
        ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &hshift, &vshift);
2777
299k
        if (ret)
2778
0
            return ret;
2779
2780
299k
        av_assert0(s->nb_components == av_pix_fmt_count_planes(frame->format));
2781
1.16M
        for (index = 0; index < s->nb_components; index++) {
2782
869k
            int h = frame->height;
2783
869k
            if (index && index < 3)
2784
547k
                h = AV_CEIL_RSHIFT(h, vshift);
2785
869k
            if (frame->data[index]) {
2786
869k
                frame->data[index]     += (h - 1) * frame->linesize[index];
2787
869k
                frame->linesize[index] *= -1;
2788
869k
            }
2789
869k
        }
2790
299k
    }
2791
2792
810k
    if (avctx->pix_fmt == AV_PIX_FMT_GBRP) {
2793
12.0k
        av_assert0(s->nb_components == 3);
2794
12.0k
        FFSWAP(uint8_t *, frame->data[0], frame->data[2]);
2795
12.0k
        FFSWAP(uint8_t *, frame->data[0], frame->data[1]);
2796
12.0k
        FFSWAP(int, frame->linesize[0], frame->linesize[2]);
2797
12.0k
        FFSWAP(int, frame->linesize[0], frame->linesize[1]);
2798
12.0k
    }
2799
2800
810k
    if (s->adobe_transform == 0 && avctx->pix_fmt == AV_PIX_FMT_GBRAP) {
2801
13.4k
        int w = s->picture_ptr->width;
2802
13.4k
        int h = s->picture_ptr->height;
2803
13.4k
        av_assert0(s->nb_components == 4);
2804
827k
        for (int i = 0; i < h; i++) {
2805
813k
            int j;
2806
813k
            uint8_t *dst[4];
2807
4.06M
            for (index = 0; index < 4; index++) {
2808
3.25M
                dst[index] =   s->picture_ptr->data[index]
2809
3.25M
                             + s->picture_ptr->linesize[index]*i;
2810
3.25M
            }
2811
112M
            for (j = 0; j < w; j++) {
2812
111M
                int k = dst[3][j];
2813
111M
                int r = dst[0][j] * k;
2814
111M
                int g = dst[1][j] * k;
2815
111M
                int b = dst[2][j] * k;
2816
111M
                dst[0][j] = g * 257 >> 16;
2817
111M
                dst[1][j] = b * 257 >> 16;
2818
111M
                dst[2][j] = r * 257 >> 16;
2819
111M
            }
2820
813k
            memset(dst[3], 255, w);
2821
813k
        }
2822
13.4k
    }
2823
810k
    if (s->adobe_transform == 2 && avctx->pix_fmt == AV_PIX_FMT_YUVA444P) {
2824
5.71k
        int w = s->picture_ptr->width;
2825
5.71k
        int h = s->picture_ptr->height;
2826
5.71k
        av_assert0(s->nb_components == 4);
2827
339k
        for (int i = 0; i < h; i++) {
2828
333k
            int j;
2829
333k
            uint8_t *dst[4];
2830
1.66M
            for (index = 0; index < 4; index++) {
2831
1.33M
                dst[index] =   s->picture_ptr->data[index]
2832
1.33M
                             + s->picture_ptr->linesize[index]*i;
2833
1.33M
            }
2834
21.1M
            for (j = 0; j < w; j++) {
2835
20.7M
                int k = dst[3][j];
2836
20.7M
                int r = (255 - dst[0][j]) * k;
2837
20.7M
                int g = (128 - dst[1][j]) * k;
2838
20.7M
                int b = (128 - dst[2][j]) * k;
2839
20.7M
                dst[0][j] = r * 257 >> 16;
2840
20.7M
                dst[1][j] = (g * 257 >> 16) + 128;
2841
20.7M
                dst[2][j] = (b * 257 >> 16) + 128;
2842
20.7M
            }
2843
333k
            memset(dst[3], 255, w);
2844
333k
        }
2845
5.71k
    }
2846
2847
810k
    if (s->stereo3d) {
2848
21.5k
        AVStereo3D *stereo = av_stereo3d_create_side_data(frame);
2849
21.5k
        if (stereo) {
2850
21.5k
            stereo->type  = s->stereo3d->type;
2851
21.5k
            stereo->flags = s->stereo3d->flags;
2852
21.5k
        }
2853
21.5k
        av_freep(&s->stereo3d);
2854
21.5k
    }
2855
2856
810k
    if (s->iccnum != 0 && s->iccnum == s->iccread) {
2857
23.5k
        AVFrameSideData *sd;
2858
23.5k
        size_t offset = 0;
2859
23.5k
        int total_size = 0;
2860
2861
        /* Sum size of all parts. */
2862
51.3k
        for (int i = 0; i < s->iccnum; i++)
2863
27.8k
            total_size += s->iccentries[i].length;
2864
2865
23.5k
        ret = ff_frame_new_side_data(avctx, frame, AV_FRAME_DATA_ICC_PROFILE, total_size, &sd);
2866
23.5k
        if (ret < 0) {
2867
0
            av_log(avctx, AV_LOG_ERROR, "Could not allocate frame side data\n");
2868
0
            return ret;
2869
0
        }
2870
2871
23.5k
        if (sd) {
2872
            /* Reassemble the parts, which are now in-order. */
2873
51.3k
            for (int i = 0; i < s->iccnum; i++) {
2874
27.8k
                memcpy(sd->data + offset, s->iccentries[i].data, s->iccentries[i].length);
2875
27.8k
                offset += s->iccentries[i].length;
2876
27.8k
            }
2877
23.5k
        }
2878
23.5k
    }
2879
2880
810k
    if (s->exif_metadata.entries) {
2881
48.8k
        ret = ff_decode_exif_attach_ifd(avctx, frame, &s->exif_metadata);
2882
48.8k
        av_exif_free(&s->exif_metadata);
2883
48.8k
        if (ret < 0)
2884
0
            av_log(avctx, AV_LOG_WARNING, "couldn't attach EXIF metadata\n");
2885
48.8k
    }
2886
2887
810k
    if (avctx->codec_id != AV_CODEC_ID_SMVJPEG &&
2888
742k
        (avctx->codec_tag == MKTAG('A', 'V', 'R', 'n') ||
2889
740k
         avctx->codec_tag == MKTAG('A', 'V', 'D', 'J')) &&
2890
71.0k
        avctx->coded_height > s->orig_height) {
2891
48.3k
        frame->height   = AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres);
2892
48.3k
        frame->crop_top = frame->height - avctx->height;
2893
48.3k
    }
2894
2895
868k
the_end_no_picture:
2896
868k
    av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",
2897
868k
           buf_end - buf_ptr);
2898
868k
    return buf_ptr - buf;
2899
810k
}
2900
2901
int ff_mjpeg_decode_frame(AVCodecContext *avctx, AVFrame *frame, int *got_frame,
2902
                          AVPacket *avpkt)
2903
1.75M
{
2904
1.75M
    return ff_mjpeg_decode_frame_from_buf(avctx, frame, got_frame,
2905
1.75M
                                          avpkt, avpkt->data, avpkt->size);
2906
1.75M
}
2907
2908
2909
/* mxpeg may call the following function (with a blank MJpegDecodeContext)
2910
 * even without having called ff_mjpeg_decode_init(). */
2911
av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
2912
76.6k
{
2913
76.6k
    MJpegDecodeContext *s = avctx->priv_data;
2914
76.6k
    int i, j;
2915
2916
76.6k
    if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_num) {
2917
392
        av_log(avctx, AV_LOG_INFO, "Single field\n");
2918
392
    }
2919
2920
76.6k
    av_frame_free(&s->picture);
2921
76.6k
    s->picture_ptr = NULL;
2922
2923
76.6k
    av_frame_free(&s->smv_frame);
2924
2925
76.6k
    av_freep(&s->buffer);
2926
76.6k
    av_freep(&s->stereo3d);
2927
76.6k
    av_freep(&s->ljpeg_buffer);
2928
76.6k
    s->ljpeg_buffer_size = 0;
2929
2930
306k
    for (i = 0; i < 3; i++) {
2931
1.15M
        for (j = 0; j < 4; j++)
2932
920k
            ff_vlc_free(&s->vlcs[i][j]);
2933
230k
    }
2934
383k
    for (i = 0; i < MAX_COMPONENTS; i++) {
2935
306k
        av_freep(&s->blocks[i]);
2936
306k
        av_freep(&s->last_nnz[i]);
2937
306k
    }
2938
76.6k
    av_exif_free(&s->exif_metadata);
2939
2940
76.6k
    reset_icc_profile(s);
2941
2942
76.6k
    av_freep(&s->hwaccel_picture_private);
2943
76.6k
    av_freep(&s->jls_state);
2944
2945
76.6k
    return 0;
2946
76.6k
}
2947
2948
static av_cold void decode_flush(AVCodecContext *avctx)
2949
468k
{
2950
468k
    MJpegDecodeContext *s = avctx->priv_data;
2951
468k
    s->got_picture = 0;
2952
2953
468k
    s->smv_next_frame = 0;
2954
468k
    av_frame_unref(s->smv_frame);
2955
468k
}
2956
2957
#if CONFIG_MJPEG_DECODER
2958
#if FF_API_MJPEG_EXTERN_HUFF
2959
#define OFFSET(x) offsetof(MJpegDecodeContext, x)
2960
#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2961
static const AVOption options[] = {
2962
    { "extern_huff", "Use external huffman table.",
2963
      OFFSET(extern_huff), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD | AV_OPT_FLAG_DEPRECATED },
2964
    { NULL },
2965
};
2966
#endif
2967
2968
static const AVClass mjpegdec_class = {
2969
    .class_name = "MJPEG decoder",
2970
    .item_name  = av_default_item_name,
2971
#if FF_API_MJPEG_EXTERN_HUFF
2972
    .option     = options,
2973
#endif
2974
    .version    = LIBAVUTIL_VERSION_INT,
2975
};
2976
2977
const FFCodec ff_mjpeg_decoder = {
2978
    .p.name         = "mjpeg",
2979
    CODEC_LONG_NAME("MJPEG (Motion JPEG)"),
2980
    .p.type         = AVMEDIA_TYPE_VIDEO,
2981
    .p.id           = AV_CODEC_ID_MJPEG,
2982
    .priv_data_size = sizeof(MJpegDecodeContext),
2983
    .init           = ff_mjpeg_decode_init,
2984
    .close          = ff_mjpeg_decode_end,
2985
    FF_CODEC_DECODE_CB(ff_mjpeg_decode_frame),
2986
    .flush          = decode_flush,
2987
    .p.capabilities = AV_CODEC_CAP_DR1,
2988
    .p.max_lowres   = 3,
2989
    .p.priv_class   = &mjpegdec_class,
2990
    .p.profiles     = NULL_IF_CONFIG_SMALL(ff_mjpeg_profiles),
2991
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP |
2992
                      FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM |
2993
                      FF_CODEC_CAP_ICC_PROFILES,
2994
    .hw_configs     = (const AVCodecHWConfigInternal *const []) {
2995
#if CONFIG_MJPEG_NVDEC_HWACCEL
2996
                        HWACCEL_NVDEC(mjpeg),
2997
#endif
2998
#if CONFIG_MJPEG_VAAPI_HWACCEL
2999
                        HWACCEL_VAAPI(mjpeg),
3000
#endif
3001
                        NULL
3002
                    },
3003
};
3004
#endif
3005
#if CONFIG_THP_DECODER
3006
const FFCodec ff_thp_decoder = {
3007
    .p.name         = "thp",
3008
    CODEC_LONG_NAME("Nintendo Gamecube THP video"),
3009
    .p.type         = AVMEDIA_TYPE_VIDEO,
3010
    .p.id           = AV_CODEC_ID_THP,
3011
    .priv_data_size = sizeof(MJpegDecodeContext),
3012
    .init           = ff_mjpeg_decode_init,
3013
    .close          = ff_mjpeg_decode_end,
3014
    FF_CODEC_DECODE_CB(ff_mjpeg_decode_frame),
3015
    .flush          = decode_flush,
3016
    .p.capabilities = AV_CODEC_CAP_DR1,
3017
    .p.max_lowres   = 3,
3018
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
3019
};
3020
#endif
3021
3022
#if CONFIG_SMVJPEG_DECODER
3023
// SMV JPEG just stacks several output frames into one JPEG picture
3024
// we handle that by setting up the cropping parameters appropriately
3025
static void smv_process_frame(AVCodecContext *avctx, AVFrame *frame)
3026
262k
{
3027
262k
    MJpegDecodeContext *s = avctx->priv_data;
3028
3029
262k
    av_assert0((s->smv_next_frame + 1) * avctx->height <= avctx->coded_height);
3030
3031
262k
    frame->width       = avctx->coded_width;
3032
262k
    frame->height      = avctx->coded_height;
3033
262k
    frame->crop_top    = FFMIN(s->smv_next_frame * avctx->height, frame->height);
3034
262k
    frame->crop_bottom = frame->height - (s->smv_next_frame + 1) * avctx->height;
3035
3036
262k
    if (s->smv_frame->pts != AV_NOPTS_VALUE)
3037
0
        s->smv_frame->pts += s->smv_frame->duration;
3038
262k
    s->smv_next_frame = (s->smv_next_frame + 1) % s->smv_frames_per_jpeg;
3039
3040
262k
    if (s->smv_next_frame == 0)
3041
64.2k
        av_frame_unref(s->smv_frame);
3042
262k
}
3043
3044
static int smvjpeg_receive_frame(AVCodecContext *avctx, AVFrame *frame)
3045
616k
{
3046
616k
    MJpegDecodeContext *s = avctx->priv_data;
3047
616k
    AVPacket *const pkt = avctx->internal->in_pkt;
3048
616k
    int got_frame = 0;
3049
616k
    int ret;
3050
3051
616k
    if (s->smv_next_frame > 0)
3052
193k
        goto return_frame;
3053
3054
423k
    ret = ff_decode_get_packet(avctx, pkt);
3055
423k
    if (ret < 0)
3056
71.6k
        return ret;
3057
3058
351k
    av_frame_unref(s->smv_frame);
3059
3060
351k
    ret = ff_mjpeg_decode_frame(avctx, s->smv_frame, &got_frame, pkt);
3061
351k
    s->smv_frame->pkt_dts = pkt->dts;
3062
351k
    av_packet_unref(pkt);
3063
351k
    if (ret < 0)
3064
257k
        return ret;
3065
3066
93.3k
    if (!got_frame)
3067
25.0k
        return AVERROR(EAGAIN);
3068
3069
    // packet duration covers all the frames in the packet
3070
68.3k
    s->smv_frame->duration /= s->smv_frames_per_jpeg;
3071
3072
262k
return_frame:
3073
262k
    av_assert0(s->smv_frame->buf[0]);
3074
262k
    ret = av_frame_ref(frame, s->smv_frame);
3075
262k
    if (ret < 0)
3076
0
        return ret;
3077
3078
262k
    smv_process_frame(avctx, frame);
3079
262k
    return 0;
3080
262k
}
3081
3082
const FFCodec ff_smvjpeg_decoder = {
3083
    .p.name         = "smvjpeg",
3084
    CODEC_LONG_NAME("SMV JPEG"),
3085
    .p.type         = AVMEDIA_TYPE_VIDEO,
3086
    .p.id           = AV_CODEC_ID_SMVJPEG,
3087
    .priv_data_size = sizeof(MJpegDecodeContext),
3088
    .init           = ff_mjpeg_decode_init,
3089
    .close          = ff_mjpeg_decode_end,
3090
    FF_CODEC_RECEIVE_FRAME_CB(smvjpeg_receive_frame),
3091
    .flush          = decode_flush,
3092
    .p.capabilities = AV_CODEC_CAP_DR1,
3093
    .caps_internal  = FF_CODEC_CAP_EXPORTS_CROPPING |
3094
                      FF_CODEC_CAP_INIT_CLEANUP,
3095
};
3096
#endif