Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ ce5e49b0

History | View | Annotate | Download (54.4 KB)

1
/*
2
 * MJPEG decoder
3
 * Copyright (c) 2000, 2001 Fabrice Bellard
4
 * Copyright (c) 2003 Alex Beregszaszi
5
 * Copyright (c) 2003-2004 Michael Niedermayer
6
 *
7
 * Support for external huffman table, various fixes (AVID workaround),
8
 * aspecting, new decode_frame mechanism and apple mjpeg-b support
9
 *                                  by Alex Beregszaszi
10
 *
11
 * This file is part of FFmpeg.
12
 *
13
 * FFmpeg is free software; you can redistribute it and/or
14
 * modify it under the terms of the GNU Lesser General Public
15
 * License as published by the Free Software Foundation; either
16
 * version 2.1 of the License, or (at your option) any later version.
17
 *
18
 * FFmpeg is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21
 * Lesser General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Lesser General Public
24
 * License along with FFmpeg; if not, write to the Free Software
25
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26
 */
27

    
28
/**
29
 * @file
30
 * MJPEG decoder.
31
 */
32

    
33
//#define DEBUG
34
#include <assert.h>
35

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

    
44

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

    
53
    assert(nb_codes <= 256);
54

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

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

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

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

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

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

    
85
    if (!s->picture_ptr)
86
        s->picture_ptr = &s->picture;
87

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

    
98
    build_basic_mjpeg_vlc(s);
99

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

    
119
    return 0;
120
}
121

    
122

    
123
/* quantize tables */
124
int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
125
{
126
    int len, index, i, j;
127

    
128
    len = get_bits(&s->gb, 16) - 2;
129

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

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

    
155
    return 0;
156
}
157

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

    
165
    len = get_bits(&s->gb, 16) - 2;
166

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

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

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

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

    
212
int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
213
{
214
    int len, nb_components, i, width, height, pix_fmt_id;
215

    
216
    /* XXX: verify len field validity */
217
    len = get_bits(&s->gb, 16);
218
    s->bits= get_bits(&s->gb, 8);
219

    
220
    if(s->pegasus_rct) s->bits=9;
221
    if(s->bits==9 && !s->pegasus_rct) s->rct=1;    //FIXME ugly
222

    
223
    if (s->bits != 8 && !s->lossless){
224
        av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
225
        return -1;
226
    }
227

    
228
    height = get_bits(&s->gb, 16);
229
    width = get_bits(&s->gb, 16);
230

    
231
    //HACK for odd_height.mov
232
    if(s->interlaced && s->width == width && s->height == height + 1)
233
        height= s->height;
234

    
235
    av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
236
    if(av_image_check_size(width, height, 0, s->avctx))
237
        return -1;
238

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

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

    
272
    if(s->v_max==1 && s->h_max==1 && s->lossless==1) s->rgb=1;
273

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

    
279
        s->width = width;
280
        s->height = height;
281
        s->interlaced = 0;
282

    
283
        /* test interlaced mode */
284
        if (s->first_picture &&
285
            s->org_height != 0 &&
286
            s->height < ((s->org_height * 3) / 4)) {
287
            s->interlaced = 1;
288
            s->bottom_field = s->interlace_polarity;
289
            s->picture_ptr->interlaced_frame = 1;
290
            s->picture_ptr->top_field_first = !s->interlace_polarity;
291
            height *= 2;
292
        }
293

    
294
        avcodec_set_dimensions(s->avctx, width, height);
295

    
296
        s->qscale_table= av_mallocz((s->width+15)/16);
297

    
298
        s->first_picture = 0;
299
    }
300

    
301
    if(s->interlaced && (s->bottom_field == !s->interlace_polarity))
302
        return 0;
303

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

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

    
349
    if(s->picture_ptr->data[0])
350
        s->avctx->release_buffer(s->avctx, s->picture_ptr);
351

    
352
    if(s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0){
353
        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
354
        return -1;
355
    }
356
    s->picture_ptr->pict_type= AV_PICTURE_TYPE_I;
357
    s->picture_ptr->key_frame= 1;
358
    s->got_picture = 1;
359

    
360
    for(i=0; i<3; i++){
361
        s->linesize[i]= s->picture_ptr->linesize[i] << s->interlaced;
362
    }
363

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

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

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

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

    
399
    if(code)
400
        return get_xbits(&s->gb, code);
401
    else
402
        return 0;
403
}
404

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

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

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

    
439
            LAST_SKIP_BITS(re, &s->gb, code);
440

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

    
451
    return 0;
452
}
453

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

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

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

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

    
499
            LAST_SKIP_BITS(re, &s->gb, code);
500

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

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

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

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

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

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

    
610
        if(i > *last_nnz)
611
            *last_nnz = i;
612
    }
613

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

    
621
    return 0;
622
}
623
#undef REFINE_BIT
624
#undef ZERO_RUN
625

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

    
633
    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size, (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
634
    buffer= s->ljpeg_buffer;
635

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

    
643
        if (s->interlaced && s->bottom_field)
644
            ptr += linesize >> 1;
645

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

    
653
            for(i=0;i<3;i++) {
654
                int pred;
655

    
656
                topleft[i]= top[i];
657
                top[i]= buffer[mb_x][i];
658

    
659
                PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
660

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

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

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

    
694
static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
695
    int i, mb_x, mb_y;
696
    const int nb_components=3;
697

    
698
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
699
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
700
            if (s->restart_interval && !s->restart_count)
701
                s->restart_count = s->restart_interval;
702

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

    
715
                    for(j=0; j<n; j++) {
716
                        int pred;
717

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

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

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

    
755
                    for(j=0; j<n; j++) {
756
                        int pred;
757

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

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

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

    
800
    if (mb_bitmask) {
801
        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
802
    }
803

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

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

    
827
            if (s->restart_interval && !s->restart_count)
828
                s->restart_count = s->restart_interval;
829

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

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

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

    
894
static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al){
895
    int mb_x, mb_y;
896
    int EOBRUN = 0;
897
    int c = s->comp_index[0];
898
    uint8_t* data = s->picture.data[c];
899
    int linesize = s->linesize[c];
900
    int last_scan = 0;
901
    int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
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
        data += linesize >> 1;
910

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

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

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

    
974
        s->comp_index[i] = index;
975

    
976
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
977
        s->h_scount[i] = s->h_count[index];
978
        s->v_scount[i] = s->v_count[index];
979

    
980
        s->dc_index[i] = get_bits(&s->gb, 4);
981
        s->ac_index[i] = get_bits(&s->gb, 4);
982

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

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

    
995
    for(i=0;i<nb_components;i++)
996
        s->last_dc[i] = 1024;
997

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

    
1012
    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1013
        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" : "",
1014
               predictor, point_transform, ilv, s->bits,
1015
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
1016

    
1017

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

    
1022
    if(s->lossless){
1023
        av_assert0(s->picture_ptr == &s->picture);
1024
        if(CONFIG_JPEGLS_DECODER && s->ls){
1025
//            for(){
1026
//            reset_ls_coding_parameters(s, 0);
1027

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

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

    
1065
    return 0;
1066
}
1067

    
1068
static int mjpeg_decode_app(MJpegDecodeContext *s)
1069
{
1070
    int len, id, i;
1071

    
1072
    len = get_bits(&s->gb, 16);
1073
    if (len < 5)
1074
        return -1;
1075
    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1076
        return -1;
1077

    
1078
    id = get_bits_long(&s->gb, 32);
1079
    id = av_be2ne32(id);
1080
    len -= 6;
1081

    
1082
    if(s->avctx->debug & FF_DEBUG_STARTCODE){
1083
        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1084
    }
1085

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

    
1115
//    len -= 2;
1116

    
1117
    if (id == AV_RL32("JFIF"))
1118
    {
1119
        int t_w, t_h, v1, v2;
1120
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
1121
        v1= get_bits(&s->gb, 8);
1122
        v2= get_bits(&s->gb, 8);
1123
        skip_bits(&s->gb, 8);
1124

    
1125
        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1126
        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1127

    
1128
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1129
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1130
                v1, v2,
1131
                s->avctx->sample_aspect_ratio.num,
1132
                s->avctx->sample_aspect_ratio.den
1133
            );
1134

    
1135
        t_w = get_bits(&s->gb, 8);
1136
        t_h = get_bits(&s->gb, 8);
1137
        if (t_w && t_h)
1138
        {
1139
            /* skip thumbnail */
1140
            if (len-10-(t_w*t_h*3) > 0)
1141
                len -= t_w*t_h*3;
1142
        }
1143
        len -= 10;
1144
        goto out;
1145
    }
1146

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

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

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

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

    
1212
    return 0;
1213
}
1214

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

    
1229
            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1230
                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1231

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

    
1247
            av_free(cbuf);
1248
        }
1249
    }
1250

    
1251
    return 0;
1252
}
1253

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

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

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

    
1307
int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1308
                         const uint8_t **buf_ptr, const uint8_t *buf_end,
1309
                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
1310
{
1311
    int start_code;
1312
    start_code = find_marker(buf_ptr, buf_end);
1313

    
1314
                if ((buf_end - *buf_ptr) > s->buffer_size)
1315
                {
1316
                    av_free(s->buffer);
1317
                    s->buffer_size = buf_end - *buf_ptr;
1318
                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1319
                    av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1320
                        s->buffer_size);
1321
                }
1322

    
1323
                /* unescape buffer of SOS, use special treatment for JPEG-LS */
1324
                if (start_code == SOS && !s->ls)
1325
                {
1326
                    const uint8_t *src = *buf_ptr;
1327
                    uint8_t *dst = s->buffer;
1328

    
1329
                    while (src<buf_end)
1330
                    {
1331
                        uint8_t x = *(src++);
1332

    
1333
                        *(dst++) = x;
1334
                        if (s->avctx->codec_id != CODEC_ID_THP)
1335
                        {
1336
                            if (x == 0xff) {
1337
                                while (src < buf_end && x == 0xff)
1338
                                    x = *(src++);
1339

    
1340
                                if (x >= 0xd0 && x <= 0xd7)
1341
                                    *(dst++) = x;
1342
                                else if (x)
1343
                                    break;
1344
                            }
1345
                        }
1346
                    }
1347
                    *unescaped_buf_ptr  = s->buffer;
1348
                    *unescaped_buf_size = dst - s->buffer;
1349

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

    
1360
                    s->cur_scan++;
1361

    
1362
                    /* find marker */
1363
                    while (src + t < buf_end){
1364
                        uint8_t x = src[t++];
1365
                        if (x == 0xff){
1366
                            while((src + t < buf_end) && x == 0xff)
1367
                                x = src[t++];
1368
                            if (x & 0x80) {
1369
                                t -= 2;
1370
                                break;
1371
                            }
1372
                        }
1373
                    }
1374
                    bit_count = t * 8;
1375

    
1376
                    init_put_bits(&pb, dst, t);
1377

    
1378
                    /* unescape bitstream */
1379
                    while(b < t){
1380
                        uint8_t x = src[b++];
1381
                        put_bits(&pb, 8, x);
1382
                        if(x == 0xFF){
1383
                            x = src[b++];
1384
                            put_bits(&pb, 7, x);
1385
                            bit_count--;
1386
                        }
1387
                    }
1388
                    flush_put_bits(&pb);
1389

    
1390
                    *unescaped_buf_ptr  = dst;
1391
                    *unescaped_buf_size = (bit_count + 7) >> 3;
1392
                }
1393
                else
1394
                {
1395
                    *unescaped_buf_ptr  = *buf_ptr;
1396
                    *unescaped_buf_size = buf_end - *buf_ptr;
1397
                }
1398

    
1399
    return start_code;
1400
}
1401

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

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

    
1429
                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1430

    
1431
                s->start_code = start_code;
1432
                if(s->avctx->debug & FF_DEBUG_STARTCODE){
1433
                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1434
                }
1435

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

    
1447
                switch(start_code) {
1448
                case SOI:
1449
                    s->restart_interval = 0;
1450

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

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

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

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

    
1579
av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1580
{
1581
    MJpegDecodeContext *s = avctx->priv_data;
1582
    int i, j;
1583

    
1584
    if (s->picture_ptr && s->picture_ptr->data[0])
1585
        avctx->release_buffer(avctx, s->picture_ptr);
1586

    
1587
    av_free(s->buffer);
1588
    av_free(s->qscale_table);
1589
    av_freep(&s->ljpeg_buffer);
1590
    s->ljpeg_buffer_size=0;
1591

    
1592
    for(i=0;i<3;i++) {
1593
        for(j=0;j<4;j++)
1594
            free_vlc(&s->vlcs[i][j]);
1595
    }
1596
    for(i=0; i<MAX_COMPONENTS; i++) {
1597
        av_freep(&s->blocks[i]);
1598
        av_freep(&s->last_nnz[i]);
1599
    }
1600
    return 0;
1601
}
1602

    
1603
AVCodec ff_mjpeg_decoder = {
1604
    "mjpeg",
1605
    AVMEDIA_TYPE_VIDEO,
1606
    CODEC_ID_MJPEG,
1607
    sizeof(MJpegDecodeContext),
1608
    ff_mjpeg_decode_init,
1609
    NULL,
1610
    ff_mjpeg_decode_end,
1611
    ff_mjpeg_decode_frame,
1612
    CODEC_CAP_DR1,
1613
    NULL,
1614
    .max_lowres = 3,
1615
    .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1616
};
1617

    
1618
AVCodec ff_thp_decoder = {
1619
    "thp",
1620
    AVMEDIA_TYPE_VIDEO,
1621
    CODEC_ID_THP,
1622
    sizeof(MJpegDecodeContext),
1623
    ff_mjpeg_decode_init,
1624
    NULL,
1625
    ff_mjpeg_decode_end,
1626
    ff_mjpeg_decode_frame,
1627
    CODEC_CAP_DR1,
1628
    NULL,
1629
    .max_lowres = 3,
1630
    .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1631
};