Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ 76cd98b4

History | View | Annotate | Download (55 KB)

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

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

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

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

    
43

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

    
52
    assert(nb_codes <= 256);
53

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

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

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

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

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

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

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

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

    
97
    build_basic_mjpeg_vlc(s);
98

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

    
118
    return 0;
119
}
120

    
121

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

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

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

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

    
154
    return 0;
155
}
156

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
297
        s->first_picture = 0;
298
    }
299

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
450
    return 0;
451
}
452

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
893
static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al,
894
                                            const uint8_t *mb_bitmask, const AVFrame *reference){
895
    int mb_x, mb_y;
896
    int EOBRUN = 0;
897
    int c = s->comp_index[0];
898
    uint8_t* data = s->picture_ptr->data[c];
899
    const uint8_t *reference_data = reference ? reference->data[c] : NULL;
900
    int linesize = s->linesize[c];
901
    int last_scan = 0;
902
    int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
903
    GetBitContext mb_bitmask_gb;
904

    
905
    if (mb_bitmask) {
906
        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
907
    }
908

    
909
    if(!Al) {
910
        s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
911
        last_scan = !~s->coefs_finished[c];
912
    }
913

    
914
    if(s->interlaced && s->bottom_field) {
915
        int offset = linesize >> 1;
916
        data += offset;
917
        reference_data += offset;
918
    }
919

    
920
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
921
        int block_offset = (mb_y*linesize*8 >> s->avctx->lowres);
922
        uint8_t *ptr = data + block_offset;
923
        int block_idx = mb_y * s->block_stride[c];
924
        DCTELEM (*block)[64] = &s->blocks[c][block_idx];
925
        uint8_t *last_nnz = &s->last_nnz[c][block_idx];
926
        for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
927
            const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
928

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

    
943
            if(last_scan) {
944
                if (copy_mb) {
945
                    mjpeg_copy_block(ptr, reference_data + block_offset, linesize, s->avctx->lowres);
946
                } else {
947
                s->dsp.idct_put(ptr, linesize, *block);
948
                ptr += 8 >> s->avctx->lowres;
949
                }
950
            }
951
        }
952
    }
953
    return 0;
954
}
955

    
956
int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
957
                        const uint8_t *mb_bitmask, const AVFrame *reference)
958
{
959
    int len, nb_components, i, h, v, predictor, point_transform;
960
    int index, id;
961
    const int block_size= s->lossless ? 1 : 8;
962
    int ilv, prev_shift;
963

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

    
993
        s->comp_index[i] = index;
994

    
995
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
996
        s->h_scount[i] = s->h_count[index];
997
        s->v_scount[i] = s->v_count[index];
998

    
999
        s->dc_index[i] = get_bits(&s->gb, 4);
1000
        s->ac_index[i] = get_bits(&s->gb, 4);
1001

    
1002
        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
1003
            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1004
            goto out_of_range;
1005
        if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
1006
            goto out_of_range;
1007
    }
1008

    
1009
    predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1010
    ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
1011
    prev_shift = get_bits(&s->gb, 4); /* Ah */
1012
    point_transform= get_bits(&s->gb, 4); /* Al */
1013

    
1014
    for(i=0;i<nb_components;i++)
1015
        s->last_dc[i] = 1024;
1016

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

    
1031
    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1032
        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" : "",
1033
               predictor, point_transform, ilv, s->bits,
1034
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
1035

    
1036

    
1037
    /* mjpeg-b can have padding bytes between sos and image data, skip them */
1038
    for (i = s->mjpb_skiptosod; i > 0; i--)
1039
        skip_bits(&s->gb, 8);
1040

    
1041
    if(s->lossless){
1042
        if(CONFIG_JPEGLS_DECODER && s->ls){
1043
//            for(){
1044
//            reset_ls_coding_parameters(s, 0);
1045

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

    
1075
static int mjpeg_decode_dri(MJpegDecodeContext *s)
1076
{
1077
    if (get_bits(&s->gb, 16) != 4)
1078
        return -1;
1079
    s->restart_interval = get_bits(&s->gb, 16);
1080
    s->restart_count = 0;
1081
    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
1082

    
1083
    return 0;
1084
}
1085

    
1086
static int mjpeg_decode_app(MJpegDecodeContext *s)
1087
{
1088
    int len, id, i;
1089

    
1090
    len = get_bits(&s->gb, 16);
1091
    if (len < 5)
1092
        return -1;
1093
    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
1094
        return -1;
1095

    
1096
    id = get_bits_long(&s->gb, 32);
1097
    id = av_be2ne32(id);
1098
    len -= 6;
1099

    
1100
    if(s->avctx->debug & FF_DEBUG_STARTCODE){
1101
        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
1102
    }
1103

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

    
1133
//    len -= 2;
1134

    
1135
    if (id == AV_RL32("JFIF"))
1136
    {
1137
        int t_w, t_h, v1, v2;
1138
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
1139
        v1= get_bits(&s->gb, 8);
1140
        v2= get_bits(&s->gb, 8);
1141
        skip_bits(&s->gb, 8);
1142

    
1143
        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
1144
        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
1145

    
1146
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1147
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1148
                v1, v2,
1149
                s->avctx->sample_aspect_ratio.num,
1150
                s->avctx->sample_aspect_ratio.den
1151
            );
1152

    
1153
        t_w = get_bits(&s->gb, 8);
1154
        t_h = get_bits(&s->gb, 8);
1155
        if (t_w && t_h)
1156
        {
1157
            /* skip thumbnail */
1158
            if (len-10-(t_w*t_h*3) > 0)
1159
                len -= t_w*t_h*3;
1160
        }
1161
        len -= 10;
1162
        goto out;
1163
    }
1164

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

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

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

    
1223
out:
1224
    /* slow but needed for extreme adobe jpegs */
1225
    if (len < 0)
1226
        av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
1227
    while(--len > 0)
1228
        skip_bits(&s->gb, 8);
1229

    
1230
    return 0;
1231
}
1232

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

    
1247
            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1248
                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1249

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

    
1265
            av_free(cbuf);
1266
        }
1267
    }
1268

    
1269
    return 0;
1270
}
1271

    
1272
#if 0
1273
static int valid_marker_list[] =
1274
{
1275
        /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1276
/* 0 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1277
/* 1 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1278
/* 2 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1279
/* 3 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1280
/* 4 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1281
/* 5 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1282
/* 6 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1283
/* 7 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1284
/* 8 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1285
/* 9 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1286
/* a */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1287
/* b */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1288
/* c */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1289
/* d */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1290
/* e */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1291
/* f */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1292
}
1293
#endif
1294

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

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

    
1325
int ff_mjpeg_find_marker(MJpegDecodeContext *s,
1326
                         const uint8_t **buf_ptr, const uint8_t *buf_end,
1327
                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
1328
{
1329
    int start_code;
1330
    start_code = find_marker(buf_ptr, buf_end);
1331

    
1332
                if ((buf_end - *buf_ptr) > s->buffer_size)
1333
                {
1334
                    av_free(s->buffer);
1335
                    s->buffer_size = buf_end - *buf_ptr;
1336
                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1337
                    av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1338
                        s->buffer_size);
1339
                }
1340

    
1341
                /* unescape buffer of SOS, use special treatment for JPEG-LS */
1342
                if (start_code == SOS && !s->ls)
1343
                {
1344
                    const uint8_t *src = *buf_ptr;
1345
                    uint8_t *dst = s->buffer;
1346

    
1347
                    while (src<buf_end)
1348
                    {
1349
                        uint8_t x = *(src++);
1350

    
1351
                        *(dst++) = x;
1352
                        if (s->avctx->codec_id != CODEC_ID_THP)
1353
                        {
1354
                            if (x == 0xff) {
1355
                                while (src < buf_end && x == 0xff)
1356
                                    x = *(src++);
1357

    
1358
                                if (x >= 0xd0 && x <= 0xd7)
1359
                                    *(dst++) = x;
1360
                                else if (x)
1361
                                    break;
1362
                            }
1363
                        }
1364
                    }
1365
                    *unescaped_buf_ptr  = s->buffer;
1366
                    *unescaped_buf_size = dst - s->buffer;
1367

    
1368
                    av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
1369
                           (buf_end - *buf_ptr) - (dst - s->buffer));
1370
                }
1371
                else if(start_code == SOS && s->ls){
1372
                    const uint8_t *src = *buf_ptr;
1373
                    uint8_t *dst = s->buffer;
1374
                    int bit_count = 0;
1375
                    int t = 0, b = 0;
1376
                    PutBitContext pb;
1377

    
1378
                    s->cur_scan++;
1379

    
1380
                    /* find marker */
1381
                    while (src + t < buf_end){
1382
                        uint8_t x = src[t++];
1383
                        if (x == 0xff){
1384
                            while((src + t < buf_end) && x == 0xff)
1385
                                x = src[t++];
1386
                            if (x & 0x80) {
1387
                                t -= 2;
1388
                                break;
1389
                            }
1390
                        }
1391
                    }
1392
                    bit_count = t * 8;
1393

    
1394
                    init_put_bits(&pb, dst, t);
1395

    
1396
                    /* unescape bitstream */
1397
                    while(b < t){
1398
                        uint8_t x = src[b++];
1399
                        put_bits(&pb, 8, x);
1400
                        if(x == 0xFF){
1401
                            x = src[b++];
1402
                            put_bits(&pb, 7, x);
1403
                            bit_count--;
1404
                        }
1405
                    }
1406
                    flush_put_bits(&pb);
1407

    
1408
                    *unescaped_buf_ptr  = dst;
1409
                    *unescaped_buf_size = (bit_count + 7) >> 3;
1410
                }
1411
                else
1412
                {
1413
                    *unescaped_buf_ptr  = *buf_ptr;
1414
                    *unescaped_buf_size = buf_end - *buf_ptr;
1415
                }
1416

    
1417
    return start_code;
1418
}
1419

    
1420
int ff_mjpeg_decode_frame(AVCodecContext *avctx,
1421
                              void *data, int *data_size,
1422
                              AVPacket *avpkt)
1423
{
1424
    const uint8_t *buf = avpkt->data;
1425
    int buf_size = avpkt->size;
1426
    MJpegDecodeContext *s = avctx->priv_data;
1427
    const uint8_t *buf_end, *buf_ptr;
1428
    const uint8_t *unescaped_buf_ptr;
1429
    int unescaped_buf_size;
1430
    int start_code;
1431
    AVFrame *picture = data;
1432

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

    
1447
                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
1448

    
1449
                s->start_code = start_code;
1450
                if(s->avctx->debug & FF_DEBUG_STARTCODE){
1451
                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1452
                }
1453

    
1454
                /* process markers */
1455
                if (start_code >= 0xd0 && start_code <= 0xd7) {
1456
                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1457
                    /* APP fields */
1458
                } else if (start_code >= APP0 && start_code <= APP15) {
1459
                    mjpeg_decode_app(s);
1460
                    /* Comment */
1461
                } else if (start_code == COM){
1462
                    mjpeg_decode_com(s);
1463
                }
1464

    
1465
                switch(start_code) {
1466
                case SOI:
1467
                    s->restart_interval = 0;
1468

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

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

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

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

    
1597
av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
1598
{
1599
    MJpegDecodeContext *s = avctx->priv_data;
1600
    int i, j;
1601

    
1602
    if (s->picture_ptr && s->picture_ptr->data[0])
1603
        avctx->release_buffer(avctx, s->picture_ptr);
1604

    
1605
    av_free(s->buffer);
1606
    av_free(s->qscale_table);
1607
    av_freep(&s->ljpeg_buffer);
1608
    s->ljpeg_buffer_size=0;
1609

    
1610
    for(i=0;i<3;i++) {
1611
        for(j=0;j<4;j++)
1612
            free_vlc(&s->vlcs[i][j]);
1613
    }
1614
    for(i=0; i<MAX_COMPONENTS; i++) {
1615
        av_freep(&s->blocks[i]);
1616
        av_freep(&s->last_nnz[i]);
1617
    }
1618
    return 0;
1619
}
1620

    
1621
AVCodec ff_mjpeg_decoder = {
1622
    "mjpeg",
1623
    AVMEDIA_TYPE_VIDEO,
1624
    CODEC_ID_MJPEG,
1625
    sizeof(MJpegDecodeContext),
1626
    ff_mjpeg_decode_init,
1627
    NULL,
1628
    ff_mjpeg_decode_end,
1629
    ff_mjpeg_decode_frame,
1630
    CODEC_CAP_DR1,
1631
    NULL,
1632
    .max_lowres = 3,
1633
    .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
1634
};
1635

    
1636
AVCodec ff_thp_decoder = {
1637
    "thp",
1638
    AVMEDIA_TYPE_VIDEO,
1639
    CODEC_ID_THP,
1640
    sizeof(MJpegDecodeContext),
1641
    ff_mjpeg_decode_init,
1642
    NULL,
1643
    ff_mjpeg_decode_end,
1644
    ff_mjpeg_decode_frame,
1645
    CODEC_CAP_DR1,
1646
    NULL,
1647
    .max_lowres = 3,
1648
    .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
1649
};