Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ 7e6a9e64

History | View | Annotate | Download (54.1 KB)

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
//#define DEBUG
34
#include <assert.h>
35

    
36
#include "libavutil/imgutils.h"
37
#include "avcodec.h"
38
#include "dsputil.h"
39
#include "mjpeg.h"
40
#include "mjpegdec.h"
41
#include "jpeglsdec.h"
42

    
43

    
44
static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,
45
                      int nb_codes, int use_static, int is_ac)
46
{
47
    uint8_t huff_size[256];
48
    uint16_t huff_code[256];
49
    uint16_t huff_sym[256];
50
    int i;
51

    
52
    assert(nb_codes <= 256);
53

    
54
    memset(huff_size, 0, sizeof(huff_size));
55
    ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
56

    
57
    for(i=0; i<256; i++)
58
        huff_sym[i]= i + 16*is_ac;
59

    
60
    if(is_ac) huff_sym[0]= 16*256;
61

    
62
    return init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, huff_sym, 2, 2, use_static);
63
}
64

    
65
static void build_basic_mjpeg_vlc(MJpegDecodeContext * s) {
66
    build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
67
              ff_mjpeg_val_dc, 12, 0, 0);
68
    build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
69
              ff_mjpeg_val_dc, 12, 0, 0);
70
    build_vlc(&s->vlcs[1][0], ff_mjpeg_bits_ac_luminance,
71
              ff_mjpeg_val_ac_luminance, 251, 0, 1);
72
    build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
73
              ff_mjpeg_val_ac_chrominance, 251, 0, 1);
74
    build_vlc(&s->vlcs[2][0], ff_mjpeg_bits_ac_luminance,
75
              ff_mjpeg_val_ac_luminance, 251, 0, 0);
76
    build_vlc(&s->vlcs[2][1], ff_mjpeg_bits_ac_chrominance,
77
              ff_mjpeg_val_ac_chrominance, 251, 0, 0);
78
}
79

    
80
av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
81
{
82
    MJpegDecodeContext *s = avctx->priv_data;
83

    
84
    s->avctx = avctx;
85
    dsputil_init(&s->dsp, avctx);
86
    ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
87
    s->buffer_size = 0;
88
    s->buffer = NULL;
89
    s->start_code = -1;
90
    s->first_picture = 1;
91
    s->org_height = avctx->coded_height;
92
    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
93

    
94
    build_basic_mjpeg_vlc(s);
95

    
96
    if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)
97
    {
98
        av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
99
        init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
100
        if (ff_mjpeg_decode_dht(s)) {
101
            av_log(avctx, AV_LOG_ERROR, "mjpeg: error using external huffman table, switching back to internal\n");
102
            build_basic_mjpeg_vlc(s);
103
        }
104
    }
105
    if (avctx->extradata_size > 9 &&
106
        AV_RL32(avctx->extradata + 4) == MKTAG('f','i','e','l')) {
107
        if (avctx->extradata[9] == 6) { /* quicktime icefloe 019 */
108
            s->interlace_polarity = 1; /* bottom field first */
109
            av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
110
        }
111
    }
112
    if (avctx->codec->id == CODEC_ID_AMV)
113
        s->flipped = 1;
114

    
115
    return 0;
116
}
117

    
118

    
119
/* quantize tables */
120
int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
121
{
122
    int len, index, i, j;
123

    
124
    len = get_bits(&s->gb, 16) - 2;
125

    
126
    while (len >= 65) {
127
        /* only 8 bit precision handled */
128
        if (get_bits(&s->gb, 4) != 0)
129
        {
130
            av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
131
            return -1;
132
        }
133
        index = get_bits(&s->gb, 4);
134
        if (index >= 4)
135
            return -1;
136
        av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
137
        /* read quant table */
138
        for(i=0;i<64;i++) {
139
            j = s->scantable.permutated[i];
140
            s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
141
        }
142

    
143
        //XXX FIXME finetune, and perhaps add dc too
144
        s->qscale[index]= FFMAX(
145
            s->quant_matrixes[index][s->scantable.permutated[1]],
146
            s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
147
        av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n", index, s->qscale[index]);
148
        len -= 65;
149
    }
150

    
151
    return 0;
152
}
153

    
154
/* decode huffman tables and build VLC decoders */
155
int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
156
{
157
    int len, index, i, class, n, v, code_max;
158
    uint8_t bits_table[17];
159
    uint8_t val_table[256];
160

    
161
    len = get_bits(&s->gb, 16) - 2;
162

    
163
    while (len > 0) {
164
        if (len < 17)
165
            return -1;
166
        class = get_bits(&s->gb, 4);
167
        if (class >= 2)
168
            return -1;
169
        index = get_bits(&s->gb, 4);
170
        if (index >= 4)
171
            return -1;
172
        n = 0;
173
        for(i=1;i<=16;i++) {
174
            bits_table[i] = get_bits(&s->gb, 8);
175
            n += bits_table[i];
176
        }
177
        len -= 17;
178
        if (len < n || n > 256)
179
            return -1;
180

    
181
        code_max = 0;
182
        for(i=0;i<n;i++) {
183
            v = get_bits(&s->gb, 8);
184
            if (v > code_max)
185
                code_max = v;
186
            val_table[i] = v;
187
        }
188
        len -= n;
189

    
190
        /* build VLC and flush previous vlc if present */
191
        free_vlc(&s->vlcs[class][index]);
192
        av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
193
               class, index, code_max + 1);
194
        if(build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1, 0, class > 0) < 0){
195
            return -1;
196
        }
197

    
198
        if(class>0){
199
            free_vlc(&s->vlcs[2][index]);
200
            if(build_vlc(&s->vlcs[2][index], bits_table, val_table, code_max + 1, 0, 0) < 0){
201
            return -1;
202
            }
203
        }
204
    }
205
    return 0;
206
}
207

    
208
int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
209
{
210
    int len, nb_components, i, width, height, pix_fmt_id;
211

    
212
    /* XXX: verify len field validity */
213
    len = get_bits(&s->gb, 16);
214
    s->bits= get_bits(&s->gb, 8);
215

    
216
    if(s->pegasus_rct) s->bits=9;
217
    if(s->bits==9 && !s->pegasus_rct) s->rct=1;    //FIXME ugly
218

    
219
    if (s->bits != 8 && !s->lossless){
220
        av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
221
        return -1;
222
    }
223

    
224
    height = get_bits(&s->gb, 16);
225
    width = get_bits(&s->gb, 16);
226

    
227
    //HACK for odd_height.mov
228
    if(s->interlaced && s->width == width && s->height == height + 1)
229
        height= s->height;
230

    
231
    av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
232
    if(av_image_check_size(width, height, 0, s->avctx))
233
        return -1;
234

    
235
    nb_components = get_bits(&s->gb, 8);
236
    if (nb_components <= 0 ||
237
        nb_components > MAX_COMPONENTS)
238
        return -1;
239
    if (s->ls && !(s->bits <= 8 || nb_components == 1)){
240
        av_log(s->avctx, AV_LOG_ERROR, "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
241
        return -1;
242
    }
243
    s->nb_components = nb_components;
244
    s->h_max = 1;
245
    s->v_max = 1;
246
    for(i=0;i<nb_components;i++) {
247
        /* component id */
248
        s->component_id[i] = get_bits(&s->gb, 8) - 1;
249
        s->h_count[i] = get_bits(&s->gb, 4);
250
        s->v_count[i] = get_bits(&s->gb, 4);
251
        /* compute hmax and vmax (only used in interleaved case) */
252
        if (s->h_count[i] > s->h_max)
253
            s->h_max = s->h_count[i];
254
        if (s->v_count[i] > s->v_max)
255
            s->v_max = s->v_count[i];
256
        s->quant_index[i] = get_bits(&s->gb, 8);
257
        if (s->quant_index[i] >= 4)
258
            return -1;
259
        av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n", i, s->h_count[i],
260
               s->v_count[i], s->component_id[i], s->quant_index[i]);
261
    }
262

    
263
    if(s->ls && (s->h_max > 1 || s->v_max > 1)) {
264
        av_log(s->avctx, AV_LOG_ERROR, "Subsampling in JPEG-LS is not supported.\n");
265
        return -1;
266
    }
267

    
268
    if(s->v_max==1 && s->h_max==1 && s->lossless==1) s->rgb=1;
269

    
270
    /* if different size, realloc/alloc picture */
271
    /* XXX: also check h_count and v_count */
272
    if (width != s->width || height != s->height) {
273
        av_freep(&s->qscale_table);
274

    
275
        s->width = width;
276
        s->height = height;
277
        s->interlaced = 0;
278

    
279
        /* test interlaced mode */
280
        if (s->first_picture &&
281
            s->org_height != 0 &&
282
            s->height < ((s->org_height * 3) / 4)) {
283
            s->interlaced = 1;
284
            s->bottom_field = s->interlace_polarity;
285
            s->picture.interlaced_frame = 1;
286
            s->picture.top_field_first = !s->interlace_polarity;
287
            height *= 2;
288
        }
289

    
290
        avcodec_set_dimensions(s->avctx, width, height);
291

    
292
        s->qscale_table= av_mallocz((s->width+15)/16);
293

    
294
        s->first_picture = 0;
295
    }
296

    
297
    if(s->interlaced && (s->bottom_field == !s->interlace_polarity))
298
        return 0;
299

    
300
    /* XXX: not complete test ! */
301
    pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
302
                 (s->h_count[1] << 20) | (s->v_count[1] << 16) |
303
                 (s->h_count[2] << 12) | (s->v_count[2] <<  8) |
304
                 (s->h_count[3] <<  4) |  s->v_count[3];
305
    av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
306
    //NOTE we do not allocate pictures large enough for the possible padding of h/v_count being 4
307
    if(!(pix_fmt_id & 0xD0D0D0D0))
308
        pix_fmt_id-= (pix_fmt_id & 0xF0F0F0F0)>>1;
309
    if(!(pix_fmt_id & 0x0D0D0D0D))
310
        pix_fmt_id-= (pix_fmt_id & 0x0F0F0F0F)>>1;
311

    
312
    switch(pix_fmt_id){
313
    case 0x11111100:
314
        if(s->rgb){
315
            s->avctx->pix_fmt = PIX_FMT_BGRA;
316
        }else
317
            s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
318
        assert(s->nb_components==3);
319
        break;
320
    case 0x11000000:
321
        s->avctx->pix_fmt = PIX_FMT_GRAY8;
322
        break;
323
    case 0x12111100:
324
        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV440P : PIX_FMT_YUVJ440P;
325
        break;
326
    case 0x21111100:
327
        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
328
        break;
329
    case 0x22111100:
330
        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
331
        break;
332
    default:
333
        av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
334
        return -1;
335
    }
336
    if(s->ls){
337
        if(s->nb_components > 1)
338
            s->avctx->pix_fmt = PIX_FMT_RGB24;
339
        else if(s->bits <= 8)
340
            s->avctx->pix_fmt = PIX_FMT_GRAY8;
341
        else
342
            s->avctx->pix_fmt = PIX_FMT_GRAY16;
343
    }
344

    
345
    if(s->picture.data[0])
346
        s->avctx->release_buffer(s->avctx, &s->picture);
347

    
348
    s->picture.reference= 0;
349
    if(s->avctx->get_buffer(s->avctx, &s->picture) < 0){
350
        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
351
        return -1;
352
    }
353
    s->picture.pict_type= FF_I_TYPE;
354
    s->picture.key_frame= 1;
355
    s->got_picture = 1;
356

    
357
    for(i=0; i<3; i++){
358
        s->linesize[i]= s->picture.linesize[i] << s->interlaced;
359
    }
360

    
361
//    printf("%d %d %d %d %d %d\n", s->width, s->height, s->linesize[0], s->linesize[1], s->interlaced, s->avctx->height);
362

    
363
    if (len != (8+(3*nb_components)))
364
    {
365
        av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
366
    }
367

    
368
    /* totally blank picture as progressive JPEG will only add details to it */
369
    if(s->progressive){
370
        int bw = (width  + s->h_max*8-1) / (s->h_max*8);
371
        int bh = (height + s->v_max*8-1) / (s->v_max*8);
372
        for(i=0; i<s->nb_components; i++) {
373
            int size = bw * bh * s->h_count[i] * s->v_count[i];
374
            av_freep(&s->blocks[i]);
375
            av_freep(&s->last_nnz[i]);
376
            s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
377
            s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
378
            s->block_stride[i] = bw * s->h_count[i];
379
        }
380
        memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
381
    }
382
    return 0;
383
}
384

    
385
static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
386
{
387
    int code;
388
    code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
389
    if (code < 0)
390
    {
391
        av_log(s->avctx, AV_LOG_WARNING, "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n", 0, dc_index,
392
               &s->vlcs[0][dc_index]);
393
        return 0xffff;
394
    }
395

    
396
    if(code)
397
        return get_xbits(&s->gb, code);
398
    else
399
        return 0;
400
}
401

    
402
/* decode block and dequantize */
403
static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
404
                        int component, int dc_index, int ac_index, int16_t *quant_matrix)
405
{
406
    int code, i, j, level, val;
407

    
408
    /* DC coef */
409
    val = mjpeg_decode_dc(s, dc_index);
410
    if (val == 0xffff) {
411
        av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
412
        return -1;
413
    }
414
    val = val * quant_matrix[0] + s->last_dc[component];
415
    s->last_dc[component] = val;
416
    block[0] = val;
417
    /* AC coefs */
418
    i = 0;
419
    {OPEN_READER(re, &s->gb);
420
    do {
421
        UPDATE_CACHE(re, &s->gb);
422
        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
423

    
424
        i += ((unsigned)code) >> 4;
425
            code &= 0xf;
426
        if(code){
427
            if(code > MIN_CACHE_BITS - 16){
428
                UPDATE_CACHE(re, &s->gb);
429
            }
430
            {
431
                int cache=GET_CACHE(re,&s->gb);
432
                int sign=(~cache)>>31;
433
                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
434
            }
435

    
436
            LAST_SKIP_BITS(re, &s->gb, code);
437

    
438
            if (i > 63) {
439
                av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
440
                return -1;
441
            }
442
            j = s->scantable.permutated[i];
443
            block[j] = level * quant_matrix[j];
444
        }
445
    }while(i<63);
446
    CLOSE_READER(re, &s->gb);}
447

    
448
    return 0;
449
}
450

    
451
static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block, int component,
452
                                 int dc_index, int16_t *quant_matrix, int Al)
453
{
454
    int val;
455
    s->dsp.clear_block(block);
456
    val = mjpeg_decode_dc(s, dc_index);
457
    if (val == 0xffff) {
458
        av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
459
        return -1;
460
    }
461
    val = (val * quant_matrix[0] << Al) + s->last_dc[component];
462
    s->last_dc[component] = val;
463
    block[0] = val;
464
    return 0;
465
}
466

    
467
/* decode block and dequantize - progressive JPEG version */
468
static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
469
                                    int ac_index, int16_t *quant_matrix,
470
                                    int ss, int se, int Al, int *EOBRUN)
471
{
472
    int code, i, j, level, val, run;
473

    
474
    if(*EOBRUN){
475
        (*EOBRUN)--;
476
        return 0;
477
    }
478
    {OPEN_READER(re, &s->gb);
479
    for(i=ss;;i++) {
480
        UPDATE_CACHE(re, &s->gb);
481
        GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
482

    
483
        run = ((unsigned) code) >> 4;
484
        code &= 0xF;
485
        if(code) {
486
            i += run;
487
            if(code > MIN_CACHE_BITS - 16){
488
                UPDATE_CACHE(re, &s->gb);
489
            }
490
            {
491
                int cache=GET_CACHE(re,&s->gb);
492
                int sign=(~cache)>>31;
493
                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
494
            }
495

    
496
            LAST_SKIP_BITS(re, &s->gb, code);
497

    
498
            if (i >= se) {
499
                if(i == se){
500
                    j = s->scantable.permutated[se];
501
                    block[j] = level * quant_matrix[j] << Al;
502
                    break;
503
                }
504
                av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
505
                return -1;
506
            }
507
            j = s->scantable.permutated[i];
508
            block[j] = level * quant_matrix[j] << Al;
509
        }else{
510
            if(run == 0xF){// ZRL - skip 15 coefficients
511
                i += 15;
512
                if (i >= se) {
513
                    av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
514
                    return -1;
515
                }
516
            }else{
517
                val = (1 << run);
518
                if(run){
519
                    UPDATE_CACHE(re, &s->gb);
520
                    val += NEG_USR32(GET_CACHE(re, &s->gb), run);
521
                    LAST_SKIP_BITS(re, &s->gb, run);
522
                }
523
                *EOBRUN = val - 1;
524
                break;
525
            }
526
        }
527
    }
528
    CLOSE_READER(re, &s->gb);}
529
    if(i > *last_nnz)
530
        *last_nnz = i;
531
    return 0;
532
}
533

    
534
#define REFINE_BIT(j) {\
535
    UPDATE_CACHE(re, &s->gb);\
536
    sign = block[j]>>15;\
537
    block[j] += SHOW_UBITS(re, &s->gb, 1) * ((quant_matrix[j]^sign)-sign) << Al;\
538
    LAST_SKIP_BITS(re, &s->gb, 1);\
539
}
540

    
541
#define ZERO_RUN \
542
for(;;i++) {\
543
    if(i > last) {\
544
        i += run;\
545
        if(i > se) {\
546
            av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);\
547
            return -1;\
548
        }\
549
        break;\
550
    }\
551
    j = s->scantable.permutated[i];\
552
    if(block[j])\
553
        REFINE_BIT(j)\
554
    else if(run-- == 0)\
555
        break;\
556
}
557

    
558
/* decode block and dequantize - progressive JPEG refinement pass */
559
static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
560
                        int ac_index, int16_t *quant_matrix,
561
                        int ss, int se, int Al, int *EOBRUN)
562
{
563
    int code, i=ss, j, sign, val, run;
564
    int last = FFMIN(se, *last_nnz);
565

    
566
    OPEN_READER(re, &s->gb);
567
    if(*EOBRUN)
568
        (*EOBRUN)--;
569
    else {
570
        for(;;i++) {
571
            UPDATE_CACHE(re, &s->gb);
572
            GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
573

    
574
            if(code & 0xF) {
575
                run = ((unsigned) code) >> 4;
576
                UPDATE_CACHE(re, &s->gb);
577
                val = SHOW_UBITS(re, &s->gb, 1);
578
                LAST_SKIP_BITS(re, &s->gb, 1);
579
                ZERO_RUN;
580
                j = s->scantable.permutated[i];
581
                val--;
582
                block[j] = ((quant_matrix[j]^val)-val) << Al;
583
                if(i == se) {
584
                    if(i > *last_nnz)
585
                        *last_nnz = i;
586
                    CLOSE_READER(re, &s->gb);
587
                    return 0;
588
                }
589
            }else{
590
                run = ((unsigned) code) >> 4;
591
                if(run == 0xF){
592
                    ZERO_RUN;
593
                }else{
594
                    val = run;
595
                    run = (1 << run);
596
                    if(val) {
597
                        UPDATE_CACHE(re, &s->gb);
598
                        run += SHOW_UBITS(re, &s->gb, val);
599
                        LAST_SKIP_BITS(re, &s->gb, val);
600
                    }
601
                    *EOBRUN = run - 1;
602
                    break;
603
                }
604
            }
605
        }
606

    
607
        if(i > *last_nnz)
608
            *last_nnz = i;
609
    }
610

    
611
    for(;i<=last;i++) {
612
        j = s->scantable.permutated[i];
613
        if(block[j])
614
            REFINE_BIT(j)
615
    }
616
    CLOSE_READER(re, &s->gb);
617

    
618
    return 0;
619
}
620
#undef REFINE_BIT
621
#undef ZERO_RUN
622

    
623
static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point_transform){
624
    int i, mb_x, mb_y;
625
    uint16_t (*buffer)[4];
626
    int left[3], top[3], topleft[3];
627
    const int linesize= s->linesize[0];
628
    const int mask= (1<<s->bits)-1;
629

    
630
    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size, (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
631
    buffer= s->ljpeg_buffer;
632

    
633
    for(i=0; i<3; i++){
634
        buffer[0][i]= 1 << (s->bits + point_transform - 1);
635
    }
636
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
637
        const int modified_predictor= mb_y ? predictor : 1;
638
        uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
639

    
640
        if (s->interlaced && s->bottom_field)
641
            ptr += linesize >> 1;
642

    
643
        for(i=0; i<3; i++){
644
            top[i]= left[i]= topleft[i]= buffer[0][i];
645
        }
646
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
647
            if (s->restart_interval && !s->restart_count)
648
                s->restart_count = s->restart_interval;
649

    
650
            for(i=0;i<3;i++) {
651
                int pred;
652

    
653
                topleft[i]= top[i];
654
                top[i]= buffer[mb_x][i];
655

    
656
                PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
657

    
658
                left[i]=
659
                buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
660
            }
661

    
662
            if (s->restart_interval && !--s->restart_count) {
663
                align_get_bits(&s->gb);
664
                skip_bits(&s->gb, 16); /* skip RSTn */
665
            }
666
        }
667

    
668
        if(s->rct){
669
            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
670
                ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);
671
                ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
672
                ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
673
            }
674
        }else if(s->pegasus_rct){
675
            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
676
                ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);
677
                ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
678
                ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
679
            }
680
        }else{
681
            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
682
                ptr[4*mb_x+0] = buffer[mb_x][2];
683
                ptr[4*mb_x+1] = buffer[mb_x][1];
684
                ptr[4*mb_x+2] = buffer[mb_x][0];
685
            }
686
        }
687
    }
688
    return 0;
689
}
690

    
691
static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
692
    int i, mb_x, mb_y;
693
    const int nb_components=3;
694

    
695
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
696
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
697
            if (s->restart_interval && !s->restart_count)
698
                s->restart_count = s->restart_interval;
699

    
700
            if(mb_x==0 || mb_y==0 || s->interlaced){
701
                for(i=0;i<nb_components;i++) {
702
                    uint8_t *ptr;
703
                    int n, h, v, x, y, c, j, linesize;
704
                    n = s->nb_blocks[i];
705
                    c = s->comp_index[i];
706
                    h = s->h_scount[i];
707
                    v = s->v_scount[i];
708
                    x = 0;
709
                    y = 0;
710
                    linesize= s->linesize[c];
711

    
712
                    for(j=0; j<n; j++) {
713
                        int pred;
714

    
715
                        ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
716
                        if(y==0 && mb_y==0){
717
                            if(x==0 && mb_x==0){
718
                                pred= 128 << point_transform;
719
                            }else{
720
                                pred= ptr[-1];
721
                            }
722
                        }else{
723
                            if(x==0 && mb_x==0){
724
                                pred= ptr[-linesize];
725
                            }else{
726
                                PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
727
                            }
728
                        }
729

    
730
                        if (s->interlaced && s->bottom_field)
731
                            ptr += linesize >> 1;
732
                        *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
733

    
734
                        if (++x == h) {
735
                            x = 0;
736
                            y++;
737
                        }
738
                    }
739
                }
740
            }else{
741
                for(i=0;i<nb_components;i++) {
742
                    uint8_t *ptr;
743
                    int n, h, v, x, y, c, j, linesize;
744
                    n = s->nb_blocks[i];
745
                    c = s->comp_index[i];
746
                    h = s->h_scount[i];
747
                    v = s->v_scount[i];
748
                    x = 0;
749
                    y = 0;
750
                    linesize= s->linesize[c];
751

    
752
                    for(j=0; j<n; j++) {
753
                        int pred;
754

    
755
                        ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
756
                        PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
757
                        *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
758
                        if (++x == h) {
759
                            x = 0;
760
                            y++;
761
                        }
762
                    }
763
                }
764
            }
765
            if (s->restart_interval && !--s->restart_count) {
766
                align_get_bits(&s->gb);
767
                skip_bits(&s->gb, 16); /* skip RSTn */
768
            }
769
        }
770
    }
771
    return 0;
772
}
773

    
774
static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
775
                                              int linesize, int lowres)
776
{
777
    switch (lowres) {
778
    case 0: copy_block8(dst, src, linesize, linesize, 8);
779
        break;
780
    case 1: copy_block4(dst, src, linesize, linesize, 4);
781
        break;
782
    case 2: copy_block2(dst, src, linesize, linesize, 2);
783
        break;
784
    case 3: *dst = *src;
785
        break;
786
    }
787
}
788

    
789
static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,
790
                             const uint8_t *mb_bitmask, const AVFrame *reference){
791
    int i, mb_x, mb_y;
792
    uint8_t* data[MAX_COMPONENTS];
793
    const uint8_t *reference_data[MAX_COMPONENTS];
794
    int linesize[MAX_COMPONENTS];
795
    GetBitContext mb_bitmask_gb;
796

    
797
    if (mb_bitmask) {
798
        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
799
    }
800

    
801
    if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
802
        av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
803
        s->flipped = 0;
804
    }
805
    for(i=0; i < nb_components; i++) {
806
        int c = s->comp_index[i];
807
        data[c] = s->picture.data[c];
808
        reference_data[c] = reference ? reference->data[c] : NULL;
809
        linesize[c]=s->linesize[c];
810
        s->coefs_finished[c] |= 1;
811
        if(s->flipped) {
812
            //picture should be flipped upside-down for this codec
813
            int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
814
            data[c] += offset;
815
            reference_data[c] += offset;
816
            linesize[c] *= -1;
817
        }
818
    }
819

    
820
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
821
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
822
            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
823

    
824
            if (s->restart_interval && !s->restart_count)
825
                s->restart_count = s->restart_interval;
826

    
827
            if(get_bits_count(&s->gb)>s->gb.size_in_bits){
828
                av_log(s->avctx, AV_LOG_ERROR, "overread %d\n", get_bits_count(&s->gb) - s->gb.size_in_bits);
829
                return -1;
830
            }
831
            for(i=0;i<nb_components;i++) {
832
                uint8_t *ptr;
833
                int n, h, v, x, y, c, j;
834
                int block_offset;
835
                n = s->nb_blocks[i];
836
                c = s->comp_index[i];
837
                h = s->h_scount[i];
838
                v = s->v_scount[i];
839
                x = 0;
840
                y = 0;
841
                for(j=0;j<n;j++) {
842
                    block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
843
                                     (h * mb_x + x) * 8) >> s->avctx->lowres);
844

    
845
                    if(s->interlaced && s->bottom_field)
846
                        block_offset += linesize[c] >> 1;
847
                    ptr = data[c] + block_offset;
848
                    if(!s->progressive) {
849
                        if (copy_mb) {
850
                            mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);
851
                        } else {
852
                        s->dsp.clear_block(s->block);
853
                        if(decode_block(s, s->block, i,
854
                                     s->dc_index[i], s->ac_index[i],
855
                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {
856
                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
857
                            return -1;
858
                        }
859
                        s->dsp.idct_put(ptr, linesize[c], s->block);
860
                        }
861
                    } else {
862
                        int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
863
                        DCTELEM *block = s->blocks[c][block_idx];
864
                        if(Ah)
865
                            block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;
866
                        else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {
867
                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
868
                            return -1;
869
                        }
870
                    }
871
//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
872
//av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);
873
                    if (++x == h) {
874
                        x = 0;
875
                        y++;
876
                    }
877
                }
878
            }
879

    
880
            if (s->restart_interval && !--s->restart_count) {
881
                align_get_bits(&s->gb);
882
                skip_bits(&s->gb, 16); /* skip RSTn */
883
                for (i=0; i<nb_components; i++) /* reset dc */
884
                    s->last_dc[i] = 1024;
885
            }
886
        }
887
    }
888
    return 0;
889
}
890

    
891
static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
892
    int mb_x, mb_y;
893
    int EOBRUN = 0;
894
    int c = s->comp_index[0];
895
    uint8_t* data = s->picture.data[c];
896
    int linesize = s->linesize[c];
897
    int last_scan = 0;
898
    int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
899

    
900
    if(!Al) {
901
        s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
902
        last_scan = !~s->coefs_finished[c];
903
    }
904

    
905
    if(s->interlaced && s->bottom_field)
906
        data += linesize >> 1;
907

    
908
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
909
        uint8_t *ptr = data + (mb_y*linesize*8 >> s->avctx->lowres);
910
        int block_idx = mb_y * s->block_stride[c];
911
        DCTELEM (*block)[64] = &s->blocks[c][block_idx];
912
        uint8_t *last_nnz = &s->last_nnz[c][block_idx];
913
        for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
914
            int ret;
915
            if(Ah)
916
                ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
917
                                              quant_matrix, ss, se, Al, &EOBRUN);
918
            else
919
                ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
920
                                               quant_matrix, ss, se, Al, &EOBRUN);
921
            if(ret < 0) {
922
                av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
923
                return -1;
924
            }
925
            if(last_scan) {
926
                s->dsp.idct_put(ptr, linesize, *block);
927
                ptr += 8 >> s->avctx->lowres;
928
            }
929
        }
930
    }
931
    return 0;
932
}
933

    
934
int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
935
                        const uint8_t *mb_bitmask, const AVFrame *reference)
936
{
937
    int len, nb_components, i, h, v, predictor, point_transform;
938
    int index, id;
939
    const int block_size= s->lossless ? 1 : 8;
940
    int ilv, prev_shift;
941

    
942
    /* XXX: verify len field validity */
943
    len = get_bits(&s->gb, 16);
944
    nb_components = get_bits(&s->gb, 8);
945
    if (nb_components == 0 || nb_components > MAX_COMPONENTS){
946
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: nb_components (%d) unsupported\n", nb_components);
947
        return -1;
948
    }
949
    if (len != 6+2*nb_components)
950
    {
951
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
952
        return -1;
953
    }
954
    for(i=0;i<nb_components;i++) {
955
        id = get_bits(&s->gb, 8) - 1;
956
        av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
957
        /* find component index */
958
        for(index=0;index<s->nb_components;index++)
959
            if (id == s->component_id[index])
960
                break;
961
        if (index == s->nb_components)
962
        {
963
            av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
964
            return -1;
965
        }
966
        /* Metasoft MJPEG codec has Cb and Cr swapped */
967
        if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
968
            && nb_components == 3 && s->nb_components == 3 && i)
969
            index = 3 - i;
970

    
971
        s->comp_index[i] = index;
972

    
973
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
974
        s->h_scount[i] = s->h_count[index];
975
        s->v_scount[i] = s->v_count[index];
976

    
977
        s->dc_index[i] = get_bits(&s->gb, 4);
978
        s->ac_index[i] = get_bits(&s->gb, 4);
979

    
980
        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
981
            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
982
            goto out_of_range;
983
        if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
984
            goto out_of_range;
985
    }
986

    
987
    predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
988
    ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
989
    prev_shift = get_bits(&s->gb, 4); /* Ah */
990
    point_transform= get_bits(&s->gb, 4); /* Al */
991

    
992
    for(i=0;i<nb_components;i++)
993
        s->last_dc[i] = 1024;
994

    
995
    if (nb_components > 1) {
996
        /* interleaved stream */
997
        s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
998
        s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
999
    } else if(!s->ls) { /* skip this for JPEG-LS */
1000
        h = s->h_max / s->h_scount[0];
1001
        v = s->v_max / s->v_scount[0];
1002
        s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
1003
        s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1004
        s->nb_blocks[0] = 1;
1005
        s->h_scount[0] = 1;
1006
        s->v_scount[0] = 1;
1007
    }
1008

    
1009
    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1010
        av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n", s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1011
               predictor, point_transform, ilv, s->bits,
1012
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
1013

    
1014

    
1015
    /* mjpeg-b can have padding bytes between sos and image data, skip them */
1016
    for (i = s->mjpb_skiptosod; i > 0; i--)
1017
        skip_bits(&s->gb, 8);
1018

    
1019
    if(s->lossless){
1020
        if(CONFIG_JPEGLS_DECODER && s->ls){
1021
//            for(){
1022
//            reset_ls_coding_parameters(s, 0);
1023

    
1024
            if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
1025
                return -1;
1026
        }else{
1027
            if(s->rgb){
1028
                if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
1029
                    return -1;
1030
            }else{
1031
                if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
1032
                    return -1;
1033
            }
1034
        }
1035
    }else{
1036
        if(s->progressive && predictor) {
1037
            if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform) < 0)
1038
                return -1;
1039
        } else {
1040
            if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
1041
                                 mb_bitmask, reference) < 0)
1042
                return -1;
1043
        }
1044
    }
1045
    emms_c();
1046
    return 0;
1047
 out_of_range:
1048
    av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1049
    return -1;
1050
}
1051

    
1052
static int mjpeg_decode_dri(MJpegDecodeContext *s)
1053
{
1054
    if (get_bits(&s->gb, 16) != 4)
1055
        return -1;
1056
    s->restart_interval = get_bits(&s->gb, 16);
1057
    s->restart_count = 0;
1058
    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1059

    
1060
    return 0;
1061
}
1062

    
1063
static int mjpeg_decode_app(MJpegDecodeContext *s)
1064
{
1065
    int len, id, i;
1066

    
1067
    len = get_bits(&s->gb, 16);
1068
    if (len < 5)
1069
        return -1;
1070
    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1071
        return -1;
1072

    
1073
    id = get_bits_long(&s->gb, 32);
1074
    id = av_be2ne32(id);
1075
    len -= 6;
1076

    
1077
    if(s->avctx->debug & FF_DEBUG_STARTCODE){
1078
        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1079
    }
1080

    
1081
    /* buggy AVID, it puts EOI only at every 10th frame */
1082
    /* also this fourcc is used by non-avid files too, it holds some
1083
       informations, but it's always present in AVID creates files */
1084
    if (id == AV_RL32("AVI1"))
1085
    {
1086
        /* structure:
1087
            4bytes      AVI1
1088
            1bytes      polarity
1089
            1bytes      always zero
1090
            4bytes      field_size
1091
            4bytes      field_size_less_padding
1092
        */
1093
            s->buggy_avid = 1;
1094
//        if (s->first_picture)
1095
//            printf("mjpeg: workarounding buggy AVID\n");
1096
        i = get_bits(&s->gb, 8);
1097
        if     (i==2) s->bottom_field= 1;
1098
        else if(i==1) s->bottom_field= 0;
1099
#if 0
1100
        skip_bits(&s->gb, 8);
1101
        skip_bits(&s->gb, 32);
1102
        skip_bits(&s->gb, 32);
1103
        len -= 10;
1104
#endif
1105
//        if (s->interlace_polarity)
1106
//            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1107
        goto out;
1108
    }
1109

    
1110
//    len -= 2;
1111

    
1112
    if (id == AV_RL32("JFIF"))
1113
    {
1114
        int t_w, t_h, v1, v2;
1115
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
1116
        v1= get_bits(&s->gb, 8);
1117
        v2= get_bits(&s->gb, 8);
1118
        skip_bits(&s->gb, 8);
1119

    
1120
        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1121
        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1122

    
1123
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1124
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1125
                v1, v2,
1126
                s->avctx->sample_aspect_ratio.num,
1127
                s->avctx->sample_aspect_ratio.den
1128
            );
1129

    
1130
        t_w = get_bits(&s->gb, 8);
1131
        t_h = get_bits(&s->gb, 8);
1132
        if (t_w && t_h)
1133
        {
1134
            /* skip thumbnail */
1135
            if (len-10-(t_w*t_h*3) > 0)
1136
                len -= t_w*t_h*3;
1137
        }
1138
        len -= 10;
1139
        goto out;
1140
    }
1141

    
1142
    if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
1143
    {
1144
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1145
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1146
        skip_bits(&s->gb, 16); /* version */
1147
        skip_bits(&s->gb, 16); /* flags0 */
1148
        skip_bits(&s->gb, 16); /* flags1 */
1149
        skip_bits(&s->gb, 8);  /* transform */
1150
        len -= 7;
1151
        goto out;
1152
    }
1153

    
1154
    if (id == AV_RL32("LJIF")){
1155
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1156
            av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
1157
        skip_bits(&s->gb, 16); /* version ? */
1158
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1159
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1160
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1161
        switch( get_bits(&s->gb, 8)){
1162
        case 1:
1163
            s->rgb= 1;
1164
            s->pegasus_rct=0;
1165
            break;
1166
        case 2:
1167
            s->rgb= 1;
1168
            s->pegasus_rct=1;
1169
            break;
1170
        default:
1171
            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1172
        }
1173
        len -= 9;
1174
        goto out;
1175
    }
1176

    
1177
    /* Apple MJPEG-A */
1178
    if ((s->start_code == APP1) && (len > (0x28 - 8)))
1179
    {
1180
        id = get_bits_long(&s->gb, 32);
1181
        id = av_be2ne32(id);
1182
        len -= 4;
1183
        if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
1184
        {
1185
#if 0
1186
            skip_bits(&s->gb, 32); /* field size */
1187
            skip_bits(&s->gb, 32); /* pad field size */
1188
            skip_bits(&s->gb, 32); /* next off */
1189
            skip_bits(&s->gb, 32); /* quant off */
1190
            skip_bits(&s->gb, 32); /* huff off */
1191
            skip_bits(&s->gb, 32); /* image off */
1192
            skip_bits(&s->gb, 32); /* scan off */
1193
            skip_bits(&s->gb, 32); /* data off */
1194
#endif
1195
            if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1196
                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1197
        }
1198
    }
1199

    
1200
out:
1201
    /* slow but needed for extreme adobe jpegs */
1202
    if (len < 0)
1203
        av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1204
    while(--len > 0)
1205
        skip_bits(&s->gb, 8);
1206

    
1207
    return 0;
1208
}
1209

    
1210
static int mjpeg_decode_com(MJpegDecodeContext *s)
1211
{
1212
    int len = get_bits(&s->gb, 16);
1213
    if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
1214
        char *cbuf = av_malloc(len - 1);
1215
        if (cbuf) {
1216
            int i;
1217
            for (i = 0; i < len - 2; i++)
1218
                cbuf[i] = get_bits(&s->gb, 8);
1219
            if (i > 0 && cbuf[i-1] == '\n')
1220
                cbuf[i-1] = 0;
1221
            else
1222
                cbuf[i] = 0;
1223

    
1224
            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1225
                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1226

    
1227
            /* buggy avid, it puts EOI only at every 10th frame */
1228
            if (!strcmp(cbuf, "AVID"))
1229
            {
1230
                s->buggy_avid = 1;
1231
                //        if (s->first_picture)
1232
                //            printf("mjpeg: workarounding buggy AVID\n");
1233
            }
1234
            else if(!strcmp(cbuf, "CS=ITU601")){
1235
                s->cs_itu601= 1;
1236
            }
1237
            else if((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1238
                    (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20))){
1239
                s->flipped = 1;
1240
            }
1241

    
1242
            av_free(cbuf);
1243
        }
1244
    }
1245

    
1246
    return 0;
1247
}
1248

    
1249
#if 0
1250
static int valid_marker_list[] =
1251
{
1252
        /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1253
/* 0 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1254
/* 1 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1255
/* 2 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1256
/* 3 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1257
/* 4 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1258
/* 5 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1259
/* 6 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1260
/* 7 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1261
/* 8 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1262
/* 9 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1263
/* a */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1264
/* b */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1265
/* c */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1266
/* d */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1267
/* e */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1268
/* f */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1269
}
1270
#endif
1271

    
1272
/* return the 8 bit start code value and update the search
1273
   state. Return -1 if no start code found */
1274
static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1275
{
1276
    const uint8_t *buf_ptr;
1277
    unsigned int v, v2;
1278
    int val;
1279
#ifdef DEBUG
1280
    int skipped=0;
1281
#endif
1282

    
1283
    buf_ptr = *pbuf_ptr;
1284
    while (buf_ptr < buf_end) {
1285
        v = *buf_ptr++;
1286
        v2 = *buf_ptr;
1287
        if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1288
            val = *buf_ptr++;
1289
            goto found;
1290
        }
1291
#ifdef DEBUG
1292
        skipped++;
1293
#endif
1294
    }
1295
    val = -1;
1296
found:
1297
    av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1298
    *pbuf_ptr = buf_ptr;
1299
    return val;
1300
}
1301

    
1302
int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1303
                         const uint8_t **buf_ptr, const uint8_t *buf_end,
1304
                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
1305
{
1306
    int start_code;
1307
    start_code = find_marker(buf_ptr, buf_end);
1308

    
1309
                if ((buf_end - *buf_ptr) > s->buffer_size)
1310
                {
1311
                    av_free(s->buffer);
1312
                    s->buffer_size = buf_end - *buf_ptr;
1313
                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1314
                    av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1315
                        s->buffer_size);
1316
                }
1317

    
1318
                /* unescape buffer of SOS, use special treatment for JPEG-LS */
1319
                if (start_code == SOS && !s->ls)
1320
                {
1321
                    const uint8_t *src = *buf_ptr;
1322
                    uint8_t *dst = s->buffer;
1323

    
1324
                    while (src<buf_end)
1325
                    {
1326
                        uint8_t x = *(src++);
1327

    
1328
                        *(dst++) = x;
1329
                        if (s->avctx->codec_id != CODEC_ID_THP)
1330
                        {
1331
                            if (x == 0xff) {
1332
                                while (src < buf_end && x == 0xff)
1333
                                    x = *(src++);
1334

    
1335
                                if (x >= 0xd0 && x <= 0xd7)
1336
                                    *(dst++) = x;
1337
                                else if (x)
1338
                                    break;
1339
                            }
1340
                        }
1341
                    }
1342
                    *unescaped_buf_ptr  = s->buffer;
1343
                    *unescaped_buf_size = dst - s->buffer;
1344

    
1345
                    av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1346
                           (buf_end - *buf_ptr) - (dst - s->buffer));
1347
                }
1348
                else if(start_code == SOS && s->ls){
1349
                    const uint8_t *src = *buf_ptr;
1350
                    uint8_t *dst = s->buffer;
1351
                    int bit_count = 0;
1352
                    int t = 0, b = 0;
1353
                    PutBitContext pb;
1354

    
1355
                    s->cur_scan++;
1356

    
1357
                    /* find marker */
1358
                    while (src + t < buf_end){
1359
                        uint8_t x = src[t++];
1360
                        if (x == 0xff){
1361
                            while((src + t < buf_end) && x == 0xff)
1362
                                x = src[t++];
1363
                            if (x & 0x80) {
1364
                                t -= 2;
1365
                                break;
1366
                            }
1367
                        }
1368
                    }
1369
                    bit_count = t * 8;
1370

    
1371
                    init_put_bits(&pb, dst, t);
1372

    
1373
                    /* unescape bitstream */
1374
                    while(b < t){
1375
                        uint8_t x = src[b++];
1376
                        put_bits(&pb, 8, x);
1377
                        if(x == 0xFF){
1378
                            x = src[b++];
1379
                            put_bits(&pb, 7, x);
1380
                            bit_count--;
1381
                        }
1382
                    }
1383
                    flush_put_bits(&pb);
1384

    
1385
                    *unescaped_buf_ptr  = dst;
1386
                    *unescaped_buf_size = (bit_count + 7) >> 3;
1387
                }
1388
                else
1389
                {
1390
                    *unescaped_buf_ptr  = *buf_ptr;
1391
                    *unescaped_buf_size = buf_end - *buf_ptr;
1392
                }
1393

    
1394
    return start_code;
1395
}
1396

    
1397
int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1398
                              void *data, int *data_size,
1399
                              AVPacket *avpkt)
1400
{
1401
    const uint8_t *buf = avpkt->data;
1402
    int buf_size = avpkt->size;
1403
    MJpegDecodeContext *s = avctx->priv_data;
1404
    const uint8_t *buf_end, *buf_ptr;
1405
    const uint8_t *unescaped_buf_ptr;
1406
    int unescaped_buf_size;
1407
    int start_code;
1408
    AVFrame *picture = data;
1409

    
1410
    s->got_picture = 0; // picture from previous image can not be reused
1411
    buf_ptr = buf;
1412
    buf_end = buf + buf_size;
1413
    while (buf_ptr < buf_end) {
1414
        /* find start next marker */
1415
        start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1416
                                          &unescaped_buf_ptr, &unescaped_buf_size);
1417
        {
1418
            /* EOF */
1419
            if (start_code < 0) {
1420
                goto the_end;
1421
            } else {
1422
                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
1423

    
1424
                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1425

    
1426
                s->start_code = start_code;
1427
                if(s->avctx->debug & FF_DEBUG_STARTCODE){
1428
                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1429
                }
1430

    
1431
                /* process markers */
1432
                if (start_code >= 0xd0 && start_code <= 0xd7) {
1433
                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1434
                    /* APP fields */
1435
                } else if (start_code >= APP0 && start_code <= APP15) {
1436
                    mjpeg_decode_app(s);
1437
                    /* Comment */
1438
                } else if (start_code == COM){
1439
                    mjpeg_decode_com(s);
1440
                }
1441

    
1442
                switch(start_code) {
1443
                case SOI:
1444
                    s->restart_interval = 0;
1445

    
1446
                    s->restart_count = 0;
1447
                    /* nothing to do on SOI */
1448
                    break;
1449
                case DQT:
1450
                    ff_mjpeg_decode_dqt(s);
1451
                    break;
1452
                case DHT:
1453
                    if(ff_mjpeg_decode_dht(s) < 0){
1454
                        av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1455
                        return -1;
1456
                    }
1457
                    break;
1458
                case SOF0:
1459
                case SOF1:
1460
                    s->lossless=0;
1461
                    s->ls=0;
1462
                    s->progressive=0;
1463
                    if (ff_mjpeg_decode_sof(s) < 0)
1464
                        return -1;
1465
                    break;
1466
                case SOF2:
1467
                    s->lossless=0;
1468
                    s->ls=0;
1469
                    s->progressive=1;
1470
                    if (ff_mjpeg_decode_sof(s) < 0)
1471
                        return -1;
1472
                    break;
1473
                case SOF3:
1474
                    s->lossless=1;
1475
                    s->ls=0;
1476
                    s->progressive=0;
1477
                    if (ff_mjpeg_decode_sof(s) < 0)
1478
                        return -1;
1479
                    break;
1480
                case SOF48:
1481
                    s->lossless=1;
1482
                    s->ls=1;
1483
                    s->progressive=0;
1484
                    if (ff_mjpeg_decode_sof(s) < 0)
1485
                        return -1;
1486
                    break;
1487
                case LSE:
1488
                    if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1489
                        return -1;
1490
                    break;
1491
                case EOI:
1492
                    s->cur_scan = 0;
1493
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1494
                        break;
1495
eoi_parser:
1496
                    if (!s->got_picture) {
1497
                        av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
1498
                        break;
1499
                    }
1500
                    {
1501
                        if (s->interlaced) {
1502
                            s->bottom_field ^= 1;
1503
                            /* if not bottom field, do not output image yet */
1504
                            if (s->bottom_field == !s->interlace_polarity)
1505
                                goto not_the_end;
1506
                        }
1507
                        *picture = s->picture;
1508
                        *data_size = sizeof(AVFrame);
1509

    
1510
                        if(!s->lossless){
1511
                            picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
1512
                            picture->qstride= 0;
1513
                            picture->qscale_table= s->qscale_table;
1514
                            memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1515
                            if(avctx->debug & FF_DEBUG_QP)
1516
                                av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1517
                            picture->quality*= FF_QP2LAMBDA;
1518
                        }
1519

    
1520
                        goto the_end;
1521
                    }
1522
                    break;
1523
                case SOS:
1524
                    if (!s->got_picture) {
1525
                        av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
1526
                        break;
1527
                    }
1528
                    ff_mjpeg_decode_sos(s, NULL, NULL);
1529
                    /* buggy avid puts EOI every 10-20th frame */
1530
                    /* if restart period is over process EOI */
1531
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1532
                        goto eoi_parser;
1533
                    break;
1534
                case DRI:
1535
                    mjpeg_decode_dri(s);
1536
                    break;
1537
                case SOF5:
1538
                case SOF6:
1539
                case SOF7:
1540
                case SOF9:
1541
                case SOF10:
1542
                case SOF11:
1543
                case SOF13:
1544
                case SOF14:
1545
                case SOF15:
1546
                case JPG:
1547
                    av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1548
                    break;
1549
//                default:
1550
//                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1551
//                    break;
1552
                }
1553

    
1554
not_the_end:
1555
                /* eof process start code */
1556
                buf_ptr += (get_bits_count(&s->gb)+7)/8;
1557
                av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1558
                       (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1559
            }
1560
        }
1561
    }
1562
    if (s->got_picture) {
1563
        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1564
        goto eoi_parser;
1565
    }
1566
    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1567
    return -1;
1568
the_end:
1569
    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
1570
//    return buf_end - buf_ptr;
1571
    return buf_ptr - buf;
1572
}
1573

    
1574
av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1575
{
1576
    MJpegDecodeContext *s = avctx->priv_data;
1577
    int i, j;
1578

    
1579
    if (s->picture.data[0])
1580
        avctx->release_buffer(avctx, &s->picture);
1581

    
1582
    av_free(s->buffer);
1583
    av_free(s->qscale_table);
1584
    av_freep(&s->ljpeg_buffer);
1585
    s->ljpeg_buffer_size=0;
1586

    
1587
    for(i=0;i<3;i++) {
1588
        for(j=0;j<4;j++)
1589
            free_vlc(&s->vlcs[i][j]);
1590
    }
1591
    for(i=0; i<MAX_COMPONENTS; i++) {
1592
        av_freep(&s->blocks[i]);
1593
        av_freep(&s->last_nnz[i]);
1594
    }
1595
    return 0;
1596
}
1597

    
1598
AVCodec ff_mjpeg_decoder = {
1599
    "mjpeg",
1600
    AVMEDIA_TYPE_VIDEO,
1601
    CODEC_ID_MJPEG,
1602
    sizeof(MJpegDecodeContext),
1603
    ff_mjpeg_decode_init,
1604
    NULL,
1605
    ff_mjpeg_decode_end,
1606
    ff_mjpeg_decode_frame,
1607
    CODEC_CAP_DR1,
1608
    NULL,
1609
    .max_lowres = 3,
1610
    .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1611
};
1612

    
1613
AVCodec ff_thp_decoder = {
1614
    "thp",
1615
    AVMEDIA_TYPE_VIDEO,
1616
    CODEC_ID_THP,
1617
    sizeof(MJpegDecodeContext),
1618
    ff_mjpeg_decode_init,
1619
    NULL,
1620
    ff_mjpeg_decode_end,
1621
    ff_mjpeg_decode_frame,
1622
    CODEC_CAP_DR1,
1623
    NULL,
1624
    .max_lowres = 3,
1625
    .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1626
};