Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ f16055ee

History | View | Annotate | Download (54.7 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 Libav.
12
 *
13
 * Libav 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
 * Libav 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 Libav; 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
            for(i=0;i<nb_components;i++) {
828
                uint8_t *ptr;
829
                int n, h, v, x, y, c, j;
830
                int block_offset;
831
                n = s->nb_blocks[i];
832
                c = s->comp_index[i];
833
                h = s->h_scount[i];
834
                v = s->v_scount[i];
835
                x = 0;
836
                y = 0;
837
                for(j=0;j<n;j++) {
838
                    block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
839
                                     (h * mb_x + x) * 8) >> s->avctx->lowres);
840

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

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

    
887
static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al,
888
                                            const uint8_t *mb_bitmask, const AVFrame *reference){
889
    int mb_x, mb_y;
890
    int EOBRUN = 0;
891
    int c = s->comp_index[0];
892
    uint8_t* data = s->picture.data[c];
893
    const uint8_t *reference_data = reference ? reference->data[c] : NULL;
894
    int linesize = s->linesize[c];
895
    int last_scan = 0;
896
    int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
897
    GetBitContext mb_bitmask_gb;
898

    
899
    if (mb_bitmask) {
900
        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
901
    }
902

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

    
908
    if(s->interlaced && s->bottom_field) {
909
        int offset = linesize >> 1;
910
        data += offset;
911
        reference_data += offset;
912
    }
913

    
914
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
915
        int block_offset = (mb_y*linesize*8 >> s->avctx->lowres);
916
        uint8_t *ptr = data + block_offset;
917
        int block_idx = mb_y * s->block_stride[c];
918
        DCTELEM (*block)[64] = &s->blocks[c][block_idx];
919
        uint8_t *last_nnz = &s->last_nnz[c][block_idx];
920
        for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
921
            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
922

    
923
            if (!copy_mb) {
924
            int ret;
925
            if(Ah)
926
                ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
927
                                              quant_matrix, ss, se, Al, &EOBRUN);
928
            else
929
                ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
930
                                               quant_matrix, ss, se, Al, &EOBRUN);
931
            if(ret < 0) {
932
                av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
933
                return -1;
934
            }
935
            }
936

    
937
            if(last_scan) {
938
                if (copy_mb) {
939
                    mjpeg_copy_block(ptr, reference_data + block_offset, linesize, s->avctx->lowres);
940
                } else {
941
                s->dsp.idct_put(ptr, linesize, *block);
942
                ptr += 8 >> s->avctx->lowres;
943
                }
944
            }
945
        }
946
    }
947
    return 0;
948
}
949

    
950
int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
951
                        const uint8_t *mb_bitmask, const AVFrame *reference)
952
{
953
    int len, nb_components, i, h, v, predictor, point_transform;
954
    int index, id;
955
    const int block_size= s->lossless ? 1 : 8;
956
    int ilv, prev_shift;
957

    
958
    /* XXX: verify len field validity */
959
    len = get_bits(&s->gb, 16);
960
    nb_components = get_bits(&s->gb, 8);
961
    if (nb_components == 0 || nb_components > MAX_COMPONENTS){
962
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: nb_components (%d) unsupported\n", nb_components);
963
        return -1;
964
    }
965
    if (len != 6+2*nb_components)
966
    {
967
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
968
        return -1;
969
    }
970
    for(i=0;i<nb_components;i++) {
971
        id = get_bits(&s->gb, 8) - 1;
972
        av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
973
        /* find component index */
974
        for(index=0;index<s->nb_components;index++)
975
            if (id == s->component_id[index])
976
                break;
977
        if (index == s->nb_components)
978
        {
979
            av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
980
            return -1;
981
        }
982
        /* Metasoft MJPEG codec has Cb and Cr swapped */
983
        if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
984
            && nb_components == 3 && s->nb_components == 3 && i)
985
            index = 3 - i;
986

    
987
        s->comp_index[i] = index;
988

    
989
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
990
        s->h_scount[i] = s->h_count[index];
991
        s->v_scount[i] = s->v_count[index];
992

    
993
        s->dc_index[i] = get_bits(&s->gb, 4);
994
        s->ac_index[i] = get_bits(&s->gb, 4);
995

    
996
        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
997
            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
998
            goto out_of_range;
999
        if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
1000
            goto out_of_range;
1001
    }
1002

    
1003
    predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1004
    ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
1005
    prev_shift = get_bits(&s->gb, 4); /* Ah */
1006
    point_transform= get_bits(&s->gb, 4); /* Al */
1007

    
1008
    for(i=0;i<nb_components;i++)
1009
        s->last_dc[i] = 1024;
1010

    
1011
    if (nb_components > 1) {
1012
        /* interleaved stream */
1013
        s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
1014
        s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1015
    } else if(!s->ls) { /* skip this for JPEG-LS */
1016
        h = s->h_max / s->h_scount[0];
1017
        v = s->v_max / s->v_scount[0];
1018
        s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
1019
        s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1020
        s->nb_blocks[0] = 1;
1021
        s->h_scount[0] = 1;
1022
        s->v_scount[0] = 1;
1023
    }
1024

    
1025
    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1026
        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" : "",
1027
               predictor, point_transform, ilv, s->bits,
1028
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
1029

    
1030

    
1031
    /* mjpeg-b can have padding bytes between sos and image data, skip them */
1032
    for (i = s->mjpb_skiptosod; i > 0; i--)
1033
        skip_bits(&s->gb, 8);
1034

    
1035
    if(s->lossless){
1036
        if(CONFIG_JPEGLS_DECODER && s->ls){
1037
//            for(){
1038
//            reset_ls_coding_parameters(s, 0);
1039

    
1040
            if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
1041
                return -1;
1042
        }else{
1043
            if(s->rgb){
1044
                if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
1045
                    return -1;
1046
            }else{
1047
                if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
1048
                    return -1;
1049
            }
1050
        }
1051
    }else{
1052
        if(s->progressive && predictor) {
1053
            if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform,
1054
                                                mb_bitmask, reference) < 0)
1055
                return -1;
1056
        } else {
1057
            if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
1058
                                 mb_bitmask, reference) < 0)
1059
                return -1;
1060
        }
1061
    }
1062
    emms_c();
1063
    return 0;
1064
 out_of_range:
1065
    av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1066
    return -1;
1067
}
1068

    
1069
static int mjpeg_decode_dri(MJpegDecodeContext *s)
1070
{
1071
    if (get_bits(&s->gb, 16) != 4)
1072
        return -1;
1073
    s->restart_interval = get_bits(&s->gb, 16);
1074
    s->restart_count = 0;
1075
    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1076

    
1077
    return 0;
1078
}
1079

    
1080
static int mjpeg_decode_app(MJpegDecodeContext *s)
1081
{
1082
    int len, id, i;
1083

    
1084
    len = get_bits(&s->gb, 16);
1085
    if (len < 5)
1086
        return -1;
1087
    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1088
        return -1;
1089

    
1090
    id = get_bits_long(&s->gb, 32);
1091
    id = av_be2ne32(id);
1092
    len -= 6;
1093

    
1094
    if(s->avctx->debug & FF_DEBUG_STARTCODE){
1095
        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1096
    }
1097

    
1098
    /* buggy AVID, it puts EOI only at every 10th frame */
1099
    /* also this fourcc is used by non-avid files too, it holds some
1100
       informations, but it's always present in AVID creates files */
1101
    if (id == AV_RL32("AVI1"))
1102
    {
1103
        /* structure:
1104
            4bytes      AVI1
1105
            1bytes      polarity
1106
            1bytes      always zero
1107
            4bytes      field_size
1108
            4bytes      field_size_less_padding
1109
        */
1110
            s->buggy_avid = 1;
1111
//        if (s->first_picture)
1112
//            printf("mjpeg: workarounding buggy AVID\n");
1113
        i = get_bits(&s->gb, 8);
1114
        if     (i==2) s->bottom_field= 1;
1115
        else if(i==1) s->bottom_field= 0;
1116
#if 0
1117
        skip_bits(&s->gb, 8);
1118
        skip_bits(&s->gb, 32);
1119
        skip_bits(&s->gb, 32);
1120
        len -= 10;
1121
#endif
1122
//        if (s->interlace_polarity)
1123
//            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1124
        goto out;
1125
    }
1126

    
1127
//    len -= 2;
1128

    
1129
    if (id == AV_RL32("JFIF"))
1130
    {
1131
        int t_w, t_h, v1, v2;
1132
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
1133
        v1= get_bits(&s->gb, 8);
1134
        v2= get_bits(&s->gb, 8);
1135
        skip_bits(&s->gb, 8);
1136

    
1137
        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1138
        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1139

    
1140
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1141
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1142
                v1, v2,
1143
                s->avctx->sample_aspect_ratio.num,
1144
                s->avctx->sample_aspect_ratio.den
1145
            );
1146

    
1147
        t_w = get_bits(&s->gb, 8);
1148
        t_h = get_bits(&s->gb, 8);
1149
        if (t_w && t_h)
1150
        {
1151
            /* skip thumbnail */
1152
            if (len-10-(t_w*t_h*3) > 0)
1153
                len -= t_w*t_h*3;
1154
        }
1155
        len -= 10;
1156
        goto out;
1157
    }
1158

    
1159
    if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
1160
    {
1161
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1162
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
1163
        skip_bits(&s->gb, 16); /* version */
1164
        skip_bits(&s->gb, 16); /* flags0 */
1165
        skip_bits(&s->gb, 16); /* flags1 */
1166
        skip_bits(&s->gb, 8);  /* transform */
1167
        len -= 7;
1168
        goto out;
1169
    }
1170

    
1171
    if (id == AV_RL32("LJIF")){
1172
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1173
            av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
1174
        skip_bits(&s->gb, 16); /* version ? */
1175
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1176
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1177
        skip_bits(&s->gb, 16); /* unknwon always 0? */
1178
        switch( get_bits(&s->gb, 8)){
1179
        case 1:
1180
            s->rgb= 1;
1181
            s->pegasus_rct=0;
1182
            break;
1183
        case 2:
1184
            s->rgb= 1;
1185
            s->pegasus_rct=1;
1186
            break;
1187
        default:
1188
            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
1189
        }
1190
        len -= 9;
1191
        goto out;
1192
    }
1193

    
1194
    /* Apple MJPEG-A */
1195
    if ((s->start_code == APP1) && (len > (0x28 - 8)))
1196
    {
1197
        id = get_bits_long(&s->gb, 32);
1198
        id = av_be2ne32(id);
1199
        len -= 4;
1200
        if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
1201
        {
1202
#if 0
1203
            skip_bits(&s->gb, 32); /* field size */
1204
            skip_bits(&s->gb, 32); /* pad field size */
1205
            skip_bits(&s->gb, 32); /* next off */
1206
            skip_bits(&s->gb, 32); /* quant off */
1207
            skip_bits(&s->gb, 32); /* huff off */
1208
            skip_bits(&s->gb, 32); /* image off */
1209
            skip_bits(&s->gb, 32); /* scan off */
1210
            skip_bits(&s->gb, 32); /* data off */
1211
#endif
1212
            if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1213
                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1214
        }
1215
    }
1216

    
1217
out:
1218
    /* slow but needed for extreme adobe jpegs */
1219
    if (len < 0)
1220
        av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1221
    while(--len > 0)
1222
        skip_bits(&s->gb, 8);
1223

    
1224
    return 0;
1225
}
1226

    
1227
static int mjpeg_decode_com(MJpegDecodeContext *s)
1228
{
1229
    int len = get_bits(&s->gb, 16);
1230
    if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
1231
        char *cbuf = av_malloc(len - 1);
1232
        if (cbuf) {
1233
            int i;
1234
            for (i = 0; i < len - 2; i++)
1235
                cbuf[i] = get_bits(&s->gb, 8);
1236
            if (i > 0 && cbuf[i-1] == '\n')
1237
                cbuf[i-1] = 0;
1238
            else
1239
                cbuf[i] = 0;
1240

    
1241
            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1242
                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1243

    
1244
            /* buggy avid, it puts EOI only at every 10th frame */
1245
            if (!strcmp(cbuf, "AVID"))
1246
            {
1247
                s->buggy_avid = 1;
1248
                //        if (s->first_picture)
1249
                //            printf("mjpeg: workarounding buggy AVID\n");
1250
            }
1251
            else if(!strcmp(cbuf, "CS=ITU601")){
1252
                s->cs_itu601= 1;
1253
            }
1254
            else if((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
1255
                    (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20))){
1256
                s->flipped = 1;
1257
            }
1258

    
1259
            av_free(cbuf);
1260
        }
1261
    }
1262

    
1263
    return 0;
1264
}
1265

    
1266
#if 0
1267
static int valid_marker_list[] =
1268
{
1269
        /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1270
/* 0 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1271
/* 1 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1272
/* 2 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1273
/* 3 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1274
/* 4 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1275
/* 5 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1276
/* 6 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1277
/* 7 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1278
/* 8 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1279
/* 9 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1280
/* a */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1281
/* b */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1282
/* c */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1283
/* d */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1284
/* e */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1285
/* f */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1286
}
1287
#endif
1288

    
1289
/* return the 8 bit start code value and update the search
1290
   state. Return -1 if no start code found */
1291
static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1292
{
1293
    const uint8_t *buf_ptr;
1294
    unsigned int v, v2;
1295
    int val;
1296
#ifdef DEBUG
1297
    int skipped=0;
1298
#endif
1299

    
1300
    buf_ptr = *pbuf_ptr;
1301
    while (buf_ptr < buf_end) {
1302
        v = *buf_ptr++;
1303
        v2 = *buf_ptr;
1304
        if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1305
            val = *buf_ptr++;
1306
            goto found;
1307
        }
1308
#ifdef DEBUG
1309
        skipped++;
1310
#endif
1311
    }
1312
    val = -1;
1313
found:
1314
    av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1315
    *pbuf_ptr = buf_ptr;
1316
    return val;
1317
}
1318

    
1319
int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1320
                         const uint8_t **buf_ptr, const uint8_t *buf_end,
1321
                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
1322
{
1323
    int start_code;
1324
    start_code = find_marker(buf_ptr, buf_end);
1325

    
1326
                if ((buf_end - *buf_ptr) > s->buffer_size)
1327
                {
1328
                    av_free(s->buffer);
1329
                    s->buffer_size = buf_end - *buf_ptr;
1330
                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1331
                    av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1332
                        s->buffer_size);
1333
                }
1334

    
1335
                /* unescape buffer of SOS, use special treatment for JPEG-LS */
1336
                if (start_code == SOS && !s->ls)
1337
                {
1338
                    const uint8_t *src = *buf_ptr;
1339
                    uint8_t *dst = s->buffer;
1340

    
1341
                    while (src<buf_end)
1342
                    {
1343
                        uint8_t x = *(src++);
1344

    
1345
                        *(dst++) = x;
1346
                        if (s->avctx->codec_id != CODEC_ID_THP)
1347
                        {
1348
                            if (x == 0xff) {
1349
                                while (src < buf_end && x == 0xff)
1350
                                    x = *(src++);
1351

    
1352
                                if (x >= 0xd0 && x <= 0xd7)
1353
                                    *(dst++) = x;
1354
                                else if (x)
1355
                                    break;
1356
                            }
1357
                        }
1358
                    }
1359
                    *unescaped_buf_ptr  = s->buffer;
1360
                    *unescaped_buf_size = dst - s->buffer;
1361

    
1362
                    av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1363
                           (buf_end - *buf_ptr) - (dst - s->buffer));
1364
                }
1365
                else if(start_code == SOS && s->ls){
1366
                    const uint8_t *src = *buf_ptr;
1367
                    uint8_t *dst = s->buffer;
1368
                    int bit_count = 0;
1369
                    int t = 0, b = 0;
1370
                    PutBitContext pb;
1371

    
1372
                    s->cur_scan++;
1373

    
1374
                    /* find marker */
1375
                    while (src + t < buf_end){
1376
                        uint8_t x = src[t++];
1377
                        if (x == 0xff){
1378
                            while((src + t < buf_end) && x == 0xff)
1379
                                x = src[t++];
1380
                            if (x & 0x80) {
1381
                                t -= 2;
1382
                                break;
1383
                            }
1384
                        }
1385
                    }
1386
                    bit_count = t * 8;
1387

    
1388
                    init_put_bits(&pb, dst, t);
1389

    
1390
                    /* unescape bitstream */
1391
                    while(b < t){
1392
                        uint8_t x = src[b++];
1393
                        put_bits(&pb, 8, x);
1394
                        if(x == 0xFF){
1395
                            x = src[b++];
1396
                            put_bits(&pb, 7, x);
1397
                            bit_count--;
1398
                        }
1399
                    }
1400
                    flush_put_bits(&pb);
1401

    
1402
                    *unescaped_buf_ptr  = dst;
1403
                    *unescaped_buf_size = (bit_count + 7) >> 3;
1404
                }
1405
                else
1406
                {
1407
                    *unescaped_buf_ptr  = *buf_ptr;
1408
                    *unescaped_buf_size = buf_end - *buf_ptr;
1409
                }
1410

    
1411
    return start_code;
1412
}
1413

    
1414
int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1415
                              void *data, int *data_size,
1416
                              AVPacket *avpkt)
1417
{
1418
    const uint8_t *buf = avpkt->data;
1419
    int buf_size = avpkt->size;
1420
    MJpegDecodeContext *s = avctx->priv_data;
1421
    const uint8_t *buf_end, *buf_ptr;
1422
    const uint8_t *unescaped_buf_ptr;
1423
    int unescaped_buf_size;
1424
    int start_code;
1425
    AVFrame *picture = data;
1426

    
1427
    s->got_picture = 0; // picture from previous image can not be reused
1428
    buf_ptr = buf;
1429
    buf_end = buf + buf_size;
1430
    while (buf_ptr < buf_end) {
1431
        /* find start next marker */
1432
        start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1433
                                          &unescaped_buf_ptr, &unescaped_buf_size);
1434
        {
1435
            /* EOF */
1436
            if (start_code < 0) {
1437
                goto the_end;
1438
            } else {
1439
                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
1440

    
1441
                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1442

    
1443
                s->start_code = start_code;
1444
                if(s->avctx->debug & FF_DEBUG_STARTCODE){
1445
                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1446
                }
1447

    
1448
                /* process markers */
1449
                if (start_code >= 0xd0 && start_code <= 0xd7) {
1450
                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1451
                    /* APP fields */
1452
                } else if (start_code >= APP0 && start_code <= APP15) {
1453
                    mjpeg_decode_app(s);
1454
                    /* Comment */
1455
                } else if (start_code == COM){
1456
                    mjpeg_decode_com(s);
1457
                }
1458

    
1459
                switch(start_code) {
1460
                case SOI:
1461
                    s->restart_interval = 0;
1462

    
1463
                    s->restart_count = 0;
1464
                    /* nothing to do on SOI */
1465
                    break;
1466
                case DQT:
1467
                    ff_mjpeg_decode_dqt(s);
1468
                    break;
1469
                case DHT:
1470
                    if(ff_mjpeg_decode_dht(s) < 0){
1471
                        av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1472
                        return -1;
1473
                    }
1474
                    break;
1475
                case SOF0:
1476
                case SOF1:
1477
                    s->lossless=0;
1478
                    s->ls=0;
1479
                    s->progressive=0;
1480
                    if (ff_mjpeg_decode_sof(s) < 0)
1481
                        return -1;
1482
                    break;
1483
                case SOF2:
1484
                    s->lossless=0;
1485
                    s->ls=0;
1486
                    s->progressive=1;
1487
                    if (ff_mjpeg_decode_sof(s) < 0)
1488
                        return -1;
1489
                    break;
1490
                case SOF3:
1491
                    s->lossless=1;
1492
                    s->ls=0;
1493
                    s->progressive=0;
1494
                    if (ff_mjpeg_decode_sof(s) < 0)
1495
                        return -1;
1496
                    break;
1497
                case SOF48:
1498
                    s->lossless=1;
1499
                    s->ls=1;
1500
                    s->progressive=0;
1501
                    if (ff_mjpeg_decode_sof(s) < 0)
1502
                        return -1;
1503
                    break;
1504
                case LSE:
1505
                    if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
1506
                        return -1;
1507
                    break;
1508
                case EOI:
1509
                    s->cur_scan = 0;
1510
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1511
                        break;
1512
eoi_parser:
1513
                    if (!s->got_picture) {
1514
                        av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
1515
                        break;
1516
                    }
1517
                    {
1518
                        if (s->interlaced) {
1519
                            s->bottom_field ^= 1;
1520
                            /* if not bottom field, do not output image yet */
1521
                            if (s->bottom_field == !s->interlace_polarity)
1522
                                goto not_the_end;
1523
                        }
1524
                        *picture = s->picture;
1525
                        *data_size = sizeof(AVFrame);
1526

    
1527
                        if(!s->lossless){
1528
                            picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
1529
                            picture->qstride= 0;
1530
                            picture->qscale_table= s->qscale_table;
1531
                            memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1532
                            if(avctx->debug & FF_DEBUG_QP)
1533
                                av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1534
                            picture->quality*= FF_QP2LAMBDA;
1535
                        }
1536

    
1537
                        goto the_end;
1538
                    }
1539
                    break;
1540
                case SOS:
1541
                    if (!s->got_picture) {
1542
                        av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
1543
                        break;
1544
                    }
1545
                    ff_mjpeg_decode_sos(s, NULL, NULL);
1546
                    /* buggy avid puts EOI every 10-20th frame */
1547
                    /* if restart period is over process EOI */
1548
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1549
                        goto eoi_parser;
1550
                    break;
1551
                case DRI:
1552
                    mjpeg_decode_dri(s);
1553
                    break;
1554
                case SOF5:
1555
                case SOF6:
1556
                case SOF7:
1557
                case SOF9:
1558
                case SOF10:
1559
                case SOF11:
1560
                case SOF13:
1561
                case SOF14:
1562
                case SOF15:
1563
                case JPG:
1564
                    av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1565
                    break;
1566
//                default:
1567
//                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1568
//                    break;
1569
                }
1570

    
1571
not_the_end:
1572
                /* eof process start code */
1573
                buf_ptr += (get_bits_count(&s->gb)+7)/8;
1574
                av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1575
                       (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1576
            }
1577
        }
1578
    }
1579
    if (s->got_picture) {
1580
        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
1581
        goto eoi_parser;
1582
    }
1583
    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
1584
    return -1;
1585
the_end:
1586
    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
1587
//    return buf_end - buf_ptr;
1588
    return buf_ptr - buf;
1589
}
1590

    
1591
av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1592
{
1593
    MJpegDecodeContext *s = avctx->priv_data;
1594
    int i, j;
1595

    
1596
    if (s->picture.data[0])
1597
        avctx->release_buffer(avctx, &s->picture);
1598

    
1599
    av_free(s->buffer);
1600
    av_free(s->qscale_table);
1601
    av_freep(&s->ljpeg_buffer);
1602
    s->ljpeg_buffer_size=0;
1603

    
1604
    for(i=0;i<3;i++) {
1605
        for(j=0;j<4;j++)
1606
            free_vlc(&s->vlcs[i][j]);
1607
    }
1608
    for(i=0; i<MAX_COMPONENTS; i++) {
1609
        av_freep(&s->blocks[i]);
1610
        av_freep(&s->last_nnz[i]);
1611
    }
1612
    return 0;
1613
}
1614

    
1615
AVCodec ff_mjpeg_decoder = {
1616
    "mjpeg",
1617
    AVMEDIA_TYPE_VIDEO,
1618
    CODEC_ID_MJPEG,
1619
    sizeof(MJpegDecodeContext),
1620
    ff_mjpeg_decode_init,
1621
    NULL,
1622
    ff_mjpeg_decode_end,
1623
    ff_mjpeg_decode_frame,
1624
    CODEC_CAP_DR1,
1625
    NULL,
1626
    .max_lowres = 3,
1627
    .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1628
};
1629

    
1630
AVCodec ff_thp_decoder = {
1631
    "thp",
1632
    AVMEDIA_TYPE_VIDEO,
1633
    CODEC_ID_THP,
1634
    sizeof(MJpegDecodeContext),
1635
    ff_mjpeg_decode_init,
1636
    NULL,
1637
    ff_mjpeg_decode_end,
1638
    ff_mjpeg_decode_frame,
1639
    CODEC_CAP_DR1,
1640
    NULL,
1641
    .max_lowres = 3,
1642
    .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1643
};