Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ 3b6bbfa0

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
    avcodec_get_frame_defaults(&s->picture);
88

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

    
99
    build_basic_mjpeg_vlc(s);
100

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

    
120
    return 0;
121
}
122

    
123

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

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

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

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

    
156
    return 0;
157
}
158

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
299
        s->first_picture = 0;
300
    }
301

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
452
    return 0;
453
}
454

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
909
    if(s->interlaced && s->bottom_field)
910
        data += linesize >> 1;
911

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

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

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

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

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

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

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

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

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

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

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

    
1018

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

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

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

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

    
1066
    return 0;
1067
}
1068

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

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

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

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

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

    
1116
//    len -= 2;
1117

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

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

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

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

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

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

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

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

    
1213
    return 0;
1214
}
1215

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

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

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

    
1248
            av_free(cbuf);
1249
        }
1250
    }
1251

    
1252
    return 0;
1253
}
1254

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

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

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

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

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

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

    
1326
                    while (src<buf_end)
1327
                    {
1328
                        uint8_t x = *(src++);
1329

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

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

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

    
1357
                    s->cur_scan++;
1358

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

    
1373
                    init_put_bits(&pb, dst, t);
1374

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

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

    
1396
    return start_code;
1397
}
1398

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

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

    
1426
                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1427

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

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

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

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

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

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

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

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

    
1581
    if (s->picture_ptr && s->picture_ptr->data[0])
1582
        avctx->release_buffer(avctx, s->picture_ptr);
1583

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

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

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

    
1615
AVCodec ff_thp_decoder = {
1616
    "thp",
1617
    AVMEDIA_TYPE_VIDEO,
1618
    CODEC_ID_THP,
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("Nintendo Gamecube THP video"),
1628
};