Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ dfd2a005

History | View | Annotate | Download (51.9 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 "libavcore/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 int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al){
775
    int i, mb_x, mb_y;
776
    uint8_t* data[MAX_COMPONENTS];
777
    int linesize[MAX_COMPONENTS];
778

    
779
    if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
780
        av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
781
        s->flipped = 0;
782
    }
783
    for(i=0; i < nb_components; i++) {
784
        int c = s->comp_index[i];
785
        data[c] = s->picture.data[c];
786
        linesize[c]=s->linesize[c];
787
        s->coefs_finished[c] |= 1;
788
        if(s->flipped) {
789
            //picture should be flipped upside-down for this codec
790
            data[c] += (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
791
            linesize[c] *= -1;
792
        }
793
    }
794

    
795
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
796
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
797
            if (s->restart_interval && !s->restart_count)
798
                s->restart_count = s->restart_interval;
799

    
800
            for(i=0;i<nb_components;i++) {
801
                uint8_t *ptr;
802
                int n, h, v, x, y, c, j;
803
                n = s->nb_blocks[i];
804
                c = s->comp_index[i];
805
                h = s->h_scount[i];
806
                v = s->v_scount[i];
807
                x = 0;
808
                y = 0;
809
                for(j=0;j<n;j++) {
810
                    ptr = data[c] +
811
                        (((linesize[c] * (v * mb_y + y) * 8) +
812
                        (h * mb_x + x) * 8) >> s->avctx->lowres);
813
                    if(s->interlaced && s->bottom_field)
814
                        ptr += linesize[c] >> 1;
815
                    if(!s->progressive) {
816
                        s->dsp.clear_block(s->block);
817
                        if(decode_block(s, s->block, i,
818
                                     s->dc_index[i], s->ac_index[i],
819
                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {
820
                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
821
                            return -1;
822
                        }
823
                        s->dsp.idct_put(ptr, linesize[c], s->block);
824
                    } else {
825
                        int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
826
                        DCTELEM *block = s->blocks[c][block_idx];
827
                        if(Ah)
828
                            block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;
829
                        else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {
830
                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
831
                            return -1;
832
                        }
833
                    }
834
//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
835
//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);
836
                    if (++x == h) {
837
                        x = 0;
838
                        y++;
839
                    }
840
                }
841
            }
842

    
843
            if (s->restart_interval && !--s->restart_count) {
844
                align_get_bits(&s->gb);
845
                skip_bits(&s->gb, 16); /* skip RSTn */
846
                for (i=0; i<nb_components; i++) /* reset dc */
847
                    s->last_dc[i] = 1024;
848
            }
849
        }
850
    }
851
    return 0;
852
}
853

    
854
static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
855
    int mb_x, mb_y;
856
    int EOBRUN = 0;
857
    int c = s->comp_index[0];
858
    uint8_t* data = s->picture.data[c];
859
    int linesize = s->linesize[c];
860
    int last_scan = 0;
861
    int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
862

    
863
    if(!Al) {
864
        s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
865
        last_scan = !~s->coefs_finished[c];
866
    }
867

    
868
    if(s->interlaced && s->bottom_field)
869
        data += linesize >> 1;
870

    
871
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
872
        uint8_t *ptr = data + (mb_y*linesize*8 >> s->avctx->lowres);
873
        int block_idx = mb_y * s->block_stride[c];
874
        DCTELEM (*block)[64] = &s->blocks[c][block_idx];
875
        uint8_t *last_nnz = &s->last_nnz[c][block_idx];
876
        for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
877
            int ret;
878
            if(Ah)
879
                ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
880
                                              quant_matrix, ss, se, Al, &EOBRUN);
881
            else
882
                ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
883
                                               quant_matrix, ss, se, Al, &EOBRUN);
884
            if(ret < 0) {
885
                av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
886
                return -1;
887
            }
888
            if(last_scan) {
889
                s->dsp.idct_put(ptr, linesize, *block);
890
                ptr += 8 >> s->avctx->lowres;
891
            }
892
        }
893
    }
894
    return 0;
895
}
896

    
897
int ff_mjpeg_decode_sos(MJpegDecodeContext *s)
898
{
899
    int len, nb_components, i, h, v, predictor, point_transform;
900
    int index, id;
901
    const int block_size= s->lossless ? 1 : 8;
902
    int ilv, prev_shift;
903

    
904
    /* XXX: verify len field validity */
905
    len = get_bits(&s->gb, 16);
906
    nb_components = get_bits(&s->gb, 8);
907
    if (nb_components == 0 || nb_components > MAX_COMPONENTS){
908
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: nb_components (%d) unsupported\n", nb_components);
909
        return -1;
910
    }
911
    if (len != 6+2*nb_components)
912
    {
913
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
914
        return -1;
915
    }
916
    for(i=0;i<nb_components;i++) {
917
        id = get_bits(&s->gb, 8) - 1;
918
        av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
919
        /* find component index */
920
        for(index=0;index<s->nb_components;index++)
921
            if (id == s->component_id[index])
922
                break;
923
        if (index == s->nb_components)
924
        {
925
            av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
926
            return -1;
927
        }
928
        /* Metasoft MJPEG codec has Cb and Cr swapped */
929
        if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
930
            && nb_components == 3 && s->nb_components == 3 && i)
931
            index = 3 - i;
932

    
933
        s->comp_index[i] = index;
934

    
935
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
936
        s->h_scount[i] = s->h_count[index];
937
        s->v_scount[i] = s->v_count[index];
938

    
939
        s->dc_index[i] = get_bits(&s->gb, 4);
940
        s->ac_index[i] = get_bits(&s->gb, 4);
941

    
942
        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
943
            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
944
            goto out_of_range;
945
        if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
946
            goto out_of_range;
947
    }
948

    
949
    predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
950
    ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
951
    prev_shift = get_bits(&s->gb, 4); /* Ah */
952
    point_transform= get_bits(&s->gb, 4); /* Al */
953

    
954
    for(i=0;i<nb_components;i++)
955
        s->last_dc[i] = 1024;
956

    
957
    if (nb_components > 1) {
958
        /* interleaved stream */
959
        s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
960
        s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
961
    } else if(!s->ls) { /* skip this for JPEG-LS */
962
        h = s->h_max / s->h_scount[0];
963
        v = s->v_max / s->v_scount[0];
964
        s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
965
        s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
966
        s->nb_blocks[0] = 1;
967
        s->h_scount[0] = 1;
968
        s->v_scount[0] = 1;
969
    }
970

    
971
    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
972
        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" : "",
973
               predictor, point_transform, ilv, s->bits,
974
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
975

    
976

    
977
    /* mjpeg-b can have padding bytes between sos and image data, skip them */
978
    for (i = s->mjpb_skiptosod; i > 0; i--)
979
        skip_bits(&s->gb, 8);
980

    
981
    if(s->lossless){
982
        if(CONFIG_JPEGLS_DECODER && s->ls){
983
//            for(){
984
//            reset_ls_coding_parameters(s, 0);
985

    
986
            if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
987
                return -1;
988
        }else{
989
            if(s->rgb){
990
                if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
991
                    return -1;
992
            }else{
993
                if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
994
                    return -1;
995
            }
996
        }
997
    }else{
998
        if(s->progressive && predictor) {
999
            if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform) < 0)
1000
                return -1;
1001
        } else {
1002
            if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform) < 0)
1003
                return -1;
1004
        }
1005
    }
1006
    emms_c();
1007
    return 0;
1008
 out_of_range:
1009
    av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1010
    return -1;
1011
}
1012

    
1013
static int mjpeg_decode_dri(MJpegDecodeContext *s)
1014
{
1015
    if (get_bits(&s->gb, 16) != 4)
1016
        return -1;
1017
    s->restart_interval = get_bits(&s->gb, 16);
1018
    s->restart_count = 0;
1019
    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1020

    
1021
    return 0;
1022
}
1023

    
1024
static int mjpeg_decode_app(MJpegDecodeContext *s)
1025
{
1026
    int len, id, i;
1027

    
1028
    len = get_bits(&s->gb, 16);
1029
    if (len < 5)
1030
        return -1;
1031
    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1032
        return -1;
1033

    
1034
    id = get_bits_long(&s->gb, 32);
1035
    id = av_be2ne32(id);
1036
    len -= 6;
1037

    
1038
    if(s->avctx->debug & FF_DEBUG_STARTCODE){
1039
        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1040
    }
1041

    
1042
    /* buggy AVID, it puts EOI only at every 10th frame */
1043
    /* also this fourcc is used by non-avid files too, it holds some
1044
       informations, but it's always present in AVID creates files */
1045
    if (id == AV_RL32("AVI1"))
1046
    {
1047
        /* structure:
1048
            4bytes      AVI1
1049
            1bytes      polarity
1050
            1bytes      always zero
1051
            4bytes      field_size
1052
            4bytes      field_size_less_padding
1053
        */
1054
            s->buggy_avid = 1;
1055
//        if (s->first_picture)
1056
//            printf("mjpeg: workarounding buggy AVID\n");
1057
        i = get_bits(&s->gb, 8);
1058
        if     (i==2) s->bottom_field= 1;
1059
        else if(i==1) s->bottom_field= 0;
1060
#if 0
1061
        skip_bits(&s->gb, 8);
1062
        skip_bits(&s->gb, 32);
1063
        skip_bits(&s->gb, 32);
1064
        len -= 10;
1065
#endif
1066
//        if (s->interlace_polarity)
1067
//            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1068
        goto out;
1069
    }
1070

    
1071
//    len -= 2;
1072

    
1073
    if (id == AV_RL32("JFIF"))
1074
    {
1075
        int t_w, t_h, v1, v2;
1076
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
1077
        v1= get_bits(&s->gb, 8);
1078
        v2= get_bits(&s->gb, 8);
1079
        skip_bits(&s->gb, 8);
1080

    
1081
        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1082
        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1083

    
1084
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1085
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1086
                v1, v2,
1087
                s->avctx->sample_aspect_ratio.num,
1088
                s->avctx->sample_aspect_ratio.den
1089
            );
1090

    
1091
        t_w = get_bits(&s->gb, 8);
1092
        t_h = get_bits(&s->gb, 8);
1093
        if (t_w && t_h)
1094
        {
1095
            /* skip thumbnail */
1096
            if (len-10-(t_w*t_h*3) > 0)
1097
                len -= t_w*t_h*3;
1098
        }
1099
        len -= 10;
1100
        goto out;
1101
    }
1102

    
1103
    if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
1104
    {
1105
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1106
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1107
        skip_bits(&s->gb, 16); /* version */
1108
        skip_bits(&s->gb, 16); /* flags0 */
1109
        skip_bits(&s->gb, 16); /* flags1 */
1110
        skip_bits(&s->gb, 8);  /* transform */
1111
        len -= 7;
1112
        goto out;
1113
    }
1114

    
1115
    if (id == AV_RL32("LJIF")){
1116
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1117
            av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
1118
        skip_bits(&s->gb, 16); /* version ? */
1119
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1120
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1121
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1122
        switch( get_bits(&s->gb, 8)){
1123
        case 1:
1124
            s->rgb= 1;
1125
            s->pegasus_rct=0;
1126
            break;
1127
        case 2:
1128
            s->rgb= 1;
1129
            s->pegasus_rct=1;
1130
            break;
1131
        default:
1132
            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1133
        }
1134
        len -= 9;
1135
        goto out;
1136
    }
1137

    
1138
    /* Apple MJPEG-A */
1139
    if ((s->start_code == APP1) && (len > (0x28 - 8)))
1140
    {
1141
        id = get_bits_long(&s->gb, 32);
1142
        id = av_be2ne32(id);
1143
        len -= 4;
1144
        if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
1145
        {
1146
#if 0
1147
            skip_bits(&s->gb, 32); /* field size */
1148
            skip_bits(&s->gb, 32); /* pad field size */
1149
            skip_bits(&s->gb, 32); /* next off */
1150
            skip_bits(&s->gb, 32); /* quant off */
1151
            skip_bits(&s->gb, 32); /* huff off */
1152
            skip_bits(&s->gb, 32); /* image off */
1153
            skip_bits(&s->gb, 32); /* scan off */
1154
            skip_bits(&s->gb, 32); /* data off */
1155
#endif
1156
            if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1157
                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1158
        }
1159
    }
1160

    
1161
out:
1162
    /* slow but needed for extreme adobe jpegs */
1163
    if (len < 0)
1164
        av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1165
    while(--len > 0)
1166
        skip_bits(&s->gb, 8);
1167

    
1168
    return 0;
1169
}
1170

    
1171
static int mjpeg_decode_com(MJpegDecodeContext *s)
1172
{
1173
    int len = get_bits(&s->gb, 16);
1174
    if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
1175
        char *cbuf = av_malloc(len - 1);
1176
        if (cbuf) {
1177
            int i;
1178
            for (i = 0; i < len - 2; i++)
1179
                cbuf[i] = get_bits(&s->gb, 8);
1180
            if (i > 0 && cbuf[i-1] == '\n')
1181
                cbuf[i-1] = 0;
1182
            else
1183
                cbuf[i] = 0;
1184

    
1185
            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1186
                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1187

    
1188
            /* buggy avid, it puts EOI only at every 10th frame */
1189
            if (!strcmp(cbuf, "AVID"))
1190
            {
1191
                s->buggy_avid = 1;
1192
                //        if (s->first_picture)
1193
                //            printf("mjpeg: workarounding buggy AVID\n");
1194
            }
1195
            else if(!strcmp(cbuf, "CS=ITU601")){
1196
                s->cs_itu601= 1;
1197
            }
1198
            else if((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1199
                    (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20))){
1200
                s->flipped = 1;
1201
            }
1202

    
1203
            av_free(cbuf);
1204
        }
1205
    }
1206

    
1207
    return 0;
1208
}
1209

    
1210
#if 0
1211
static int valid_marker_list[] =
1212
{
1213
        /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1214
/* 0 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1215
/* 1 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1216
/* 2 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1217
/* 3 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1218
/* 4 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1219
/* 5 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1220
/* 6 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1221
/* 7 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1222
/* 8 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1223
/* 9 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1224
/* a */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1225
/* b */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1226
/* c */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1227
/* d */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1228
/* e */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1229
/* f */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1230
}
1231
#endif
1232

    
1233
/* return the 8 bit start code value and update the search
1234
   state. Return -1 if no start code found */
1235
static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1236
{
1237
    const uint8_t *buf_ptr;
1238
    unsigned int v, v2;
1239
    int val;
1240
#ifdef DEBUG
1241
    int skipped=0;
1242
#endif
1243

    
1244
    buf_ptr = *pbuf_ptr;
1245
    while (buf_ptr < buf_end) {
1246
        v = *buf_ptr++;
1247
        v2 = *buf_ptr;
1248
        if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1249
            val = *buf_ptr++;
1250
            goto found;
1251
        }
1252
#ifdef DEBUG
1253
        skipped++;
1254
#endif
1255
    }
1256
    val = -1;
1257
found:
1258
    av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1259
    *pbuf_ptr = buf_ptr;
1260
    return val;
1261
}
1262

    
1263
int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1264
                              void *data, int *data_size,
1265
                              AVPacket *avpkt)
1266
{
1267
    const uint8_t *buf = avpkt->data;
1268
    int buf_size = avpkt->size;
1269
    MJpegDecodeContext *s = avctx->priv_data;
1270
    const uint8_t *buf_end, *buf_ptr;
1271
    int start_code;
1272
    AVFrame *picture = data;
1273

    
1274
    s->got_picture = 0; // picture from previous image can not be reused
1275
    buf_ptr = buf;
1276
    buf_end = buf + buf_size;
1277
    while (buf_ptr < buf_end) {
1278
        /* find start next marker */
1279
        start_code = find_marker(&buf_ptr, buf_end);
1280
        {
1281
            /* EOF */
1282
            if (start_code < 0) {
1283
                goto the_end;
1284
            } else {
1285
                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
1286

    
1287
                if ((buf_end - buf_ptr) > s->buffer_size)
1288
                {
1289
                    av_free(s->buffer);
1290
                    s->buffer_size = buf_end-buf_ptr;
1291
                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1292
                    av_log(avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1293
                        s->buffer_size);
1294
                }
1295

    
1296
                /* unescape buffer of SOS, use special treatment for JPEG-LS */
1297
                if (start_code == SOS && !s->ls)
1298
                {
1299
                    const uint8_t *src = buf_ptr;
1300
                    uint8_t *dst = s->buffer;
1301

    
1302
                    while (src<buf_end)
1303
                    {
1304
                        uint8_t x = *(src++);
1305

    
1306
                        *(dst++) = x;
1307
                        if (avctx->codec_id != CODEC_ID_THP)
1308
                        {
1309
                            if (x == 0xff) {
1310
                                while (src < buf_end && x == 0xff)
1311
                                    x = *(src++);
1312

    
1313
                                if (x >= 0xd0 && x <= 0xd7)
1314
                                    *(dst++) = x;
1315
                                else if (x)
1316
                                    break;
1317
                            }
1318
                        }
1319
                    }
1320
                    init_get_bits(&s->gb, s->buffer, (dst - s->buffer)*8);
1321

    
1322
                    av_log(avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1323
                           (buf_end - buf_ptr) - (dst - s->buffer));
1324
                }
1325
                else if(start_code == SOS && s->ls){
1326
                    const uint8_t *src = buf_ptr;
1327
                    uint8_t *dst = s->buffer;
1328
                    int bit_count = 0;
1329
                    int t = 0, b = 0;
1330
                    PutBitContext pb;
1331

    
1332
                    s->cur_scan++;
1333

    
1334
                    /* find marker */
1335
                    while (src + t < buf_end){
1336
                        uint8_t x = src[t++];
1337
                        if (x == 0xff){
1338
                            while((src + t < buf_end) && x == 0xff)
1339
                                x = src[t++];
1340
                            if (x & 0x80) {
1341
                                t -= 2;
1342
                                break;
1343
                            }
1344
                        }
1345
                    }
1346
                    bit_count = t * 8;
1347

    
1348
                    init_put_bits(&pb, dst, t);
1349

    
1350
                    /* unescape bitstream */
1351
                    while(b < t){
1352
                        uint8_t x = src[b++];
1353
                        put_bits(&pb, 8, x);
1354
                        if(x == 0xFF){
1355
                            x = src[b++];
1356
                            put_bits(&pb, 7, x);
1357
                            bit_count--;
1358
                        }
1359
                    }
1360
                    flush_put_bits(&pb);
1361

    
1362
                    init_get_bits(&s->gb, dst, bit_count);
1363
                }
1364
                else
1365
                    init_get_bits(&s->gb, buf_ptr, (buf_end - buf_ptr)*8);
1366

    
1367
                s->start_code = start_code;
1368
                if(s->avctx->debug & FF_DEBUG_STARTCODE){
1369
                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1370
                }
1371

    
1372
                /* process markers */
1373
                if (start_code >= 0xd0 && start_code <= 0xd7) {
1374
                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1375
                    /* APP fields */
1376
                } else if (start_code >= APP0 && start_code <= APP15) {
1377
                    mjpeg_decode_app(s);
1378
                    /* Comment */
1379
                } else if (start_code == COM){
1380
                    mjpeg_decode_com(s);
1381
                }
1382

    
1383
                switch(start_code) {
1384
                case SOI:
1385
                    s->restart_interval = 0;
1386

    
1387
                    s->restart_count = 0;
1388
                    /* nothing to do on SOI */
1389
                    break;
1390
                case DQT:
1391
                    ff_mjpeg_decode_dqt(s);
1392
                    break;
1393
                case DHT:
1394
                    if(ff_mjpeg_decode_dht(s) < 0){
1395
                        av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1396
                        return -1;
1397
                    }
1398
                    break;
1399
                case SOF0:
1400
                case SOF1:
1401
                    s->lossless=0;
1402
                    s->ls=0;
1403
                    s->progressive=0;
1404
                    if (ff_mjpeg_decode_sof(s) < 0)
1405
                        return -1;
1406
                    break;
1407
                case SOF2:
1408
                    s->lossless=0;
1409
                    s->ls=0;
1410
                    s->progressive=1;
1411
                    if (ff_mjpeg_decode_sof(s) < 0)
1412
                        return -1;
1413
                    break;
1414
                case SOF3:
1415
                    s->lossless=1;
1416
                    s->ls=0;
1417
                    s->progressive=0;
1418
                    if (ff_mjpeg_decode_sof(s) < 0)
1419
                        return -1;
1420
                    break;
1421
                case SOF48:
1422
                    s->lossless=1;
1423
                    s->ls=1;
1424
                    s->progressive=0;
1425
                    if (ff_mjpeg_decode_sof(s) < 0)
1426
                        return -1;
1427
                    break;
1428
                case LSE:
1429
                    if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1430
                        return -1;
1431
                    break;
1432
                case EOI:
1433
                    s->cur_scan = 0;
1434
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1435
                        break;
1436
eoi_parser:
1437
                    if (!s->got_picture) {
1438
                        av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
1439
                        break;
1440
                    }
1441
                    {
1442
                        if (s->interlaced) {
1443
                            s->bottom_field ^= 1;
1444
                            /* if not bottom field, do not output image yet */
1445
                            if (s->bottom_field == !s->interlace_polarity)
1446
                                goto not_the_end;
1447
                        }
1448
                        *picture = s->picture;
1449
                        *data_size = sizeof(AVFrame);
1450

    
1451
                        if(!s->lossless){
1452
                            picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
1453
                            picture->qstride= 0;
1454
                            picture->qscale_table= s->qscale_table;
1455
                            memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1456
                            if(avctx->debug & FF_DEBUG_QP)
1457
                                av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1458
                            picture->quality*= FF_QP2LAMBDA;
1459
                        }
1460

    
1461
                        goto the_end;
1462
                    }
1463
                    break;
1464
                case SOS:
1465
                    if (!s->got_picture) {
1466
                        av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
1467
                        break;
1468
                    }
1469
                    ff_mjpeg_decode_sos(s);
1470
                    /* buggy avid puts EOI every 10-20th frame */
1471
                    /* if restart period is over process EOI */
1472
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1473
                        goto eoi_parser;
1474
                    break;
1475
                case DRI:
1476
                    mjpeg_decode_dri(s);
1477
                    break;
1478
                case SOF5:
1479
                case SOF6:
1480
                case SOF7:
1481
                case SOF9:
1482
                case SOF10:
1483
                case SOF11:
1484
                case SOF13:
1485
                case SOF14:
1486
                case SOF15:
1487
                case JPG:
1488
                    av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1489
                    break;
1490
//                default:
1491
//                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1492
//                    break;
1493
                }
1494

    
1495
not_the_end:
1496
                /* eof process start code */
1497
                buf_ptr += (get_bits_count(&s->gb)+7)/8;
1498
                av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1499
                       (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1500
            }
1501
        }
1502
    }
1503
    if (s->got_picture) {
1504
        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1505
        goto eoi_parser;
1506
    }
1507
    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1508
    return -1;
1509
the_end:
1510
    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
1511
//    return buf_end - buf_ptr;
1512
    return buf_ptr - buf;
1513
}
1514

    
1515
av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1516
{
1517
    MJpegDecodeContext *s = avctx->priv_data;
1518
    int i, j;
1519

    
1520
    if (s->picture.data[0])
1521
        avctx->release_buffer(avctx, &s->picture);
1522

    
1523
    av_free(s->buffer);
1524
    av_free(s->qscale_table);
1525
    av_freep(&s->ljpeg_buffer);
1526
    s->ljpeg_buffer_size=0;
1527

    
1528
    for(i=0;i<3;i++) {
1529
        for(j=0;j<4;j++)
1530
            free_vlc(&s->vlcs[i][j]);
1531
    }
1532
    for(i=0; i<MAX_COMPONENTS; i++) {
1533
        av_freep(&s->blocks[i]);
1534
        av_freep(&s->last_nnz[i]);
1535
    }
1536
    return 0;
1537
}
1538

    
1539
AVCodec ff_mjpeg_decoder = {
1540
    "mjpeg",
1541
    AVMEDIA_TYPE_VIDEO,
1542
    CODEC_ID_MJPEG,
1543
    sizeof(MJpegDecodeContext),
1544
    ff_mjpeg_decode_init,
1545
    NULL,
1546
    ff_mjpeg_decode_end,
1547
    ff_mjpeg_decode_frame,
1548
    CODEC_CAP_DR1,
1549
    NULL,
1550
    .max_lowres = 4,
1551
    .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1552
};
1553

    
1554
AVCodec ff_thp_decoder = {
1555
    "thp",
1556
    AVMEDIA_TYPE_VIDEO,
1557
    CODEC_ID_THP,
1558
    sizeof(MJpegDecodeContext),
1559
    ff_mjpeg_decode_init,
1560
    NULL,
1561
    ff_mjpeg_decode_end,
1562
    ff_mjpeg_decode_frame,
1563
    CODEC_CAP_DR1,
1564
    NULL,
1565
    .max_lowres = 3,
1566
    .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1567
};