Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpegdec.c @ 944721c1

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

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

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

    
36
#include "avcodec.h"
37
#include "dsputil.h"
38
#include "bytestream.h"
39
#include "mjpeg.h"
40
#include "jpeglsdec.h"
41

    
42

    
43
static int mjpeg_decode_dht(MJpegDecodeContext *s);
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+16];
49
    uint16_t huff_code[256+16];
50

    
51
    assert(nb_codes <= 256);
52

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

    
56
    if(is_ac){
57
        memmove(huff_size+16, huff_size, sizeof(uint8_t)*nb_codes);
58
        memmove(huff_code+16, huff_code, sizeof(uint16_t)*nb_codes);
59
        memset(huff_size, 0, sizeof(uint8_t)*16);
60
        memset(huff_code, 0, sizeof(uint16_t)*16);
61
        nb_codes += 16;
62
    }
63

    
64
    return init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2, use_static);
65
}
66

    
67
static int mjpeg_decode_init(AVCodecContext *avctx)
68
{
69
    MJpegDecodeContext *s = avctx->priv_data;
70

    
71
    s->avctx = avctx;
72
    dsputil_init(&s->dsp, avctx);
73
    ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
74
    s->buffer_size = 0;
75
    s->buffer = NULL;
76
    s->start_code = -1;
77
    s->first_picture = 1;
78
    s->org_height = avctx->coded_height;
79

    
80
    build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
81
              ff_mjpeg_val_dc_luminance, 12, 0, 0);
82
    build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
83
              ff_mjpeg_val_dc_chrominance, 12, 0, 0);
84
    build_vlc(&s->vlcs[1][0], ff_mjpeg_bits_ac_luminance,
85
              ff_mjpeg_val_ac_luminance, 251, 0, 1);
86
    build_vlc(&s->vlcs[1][1], ff_mjpeg_bits_ac_chrominance,
87
              ff_mjpeg_val_ac_chrominance, 251, 0, 1);
88

    
89
    if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)
90
    {
91
        av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
92
        init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
93
        mjpeg_decode_dht(s);
94
        /* should check for error - but dunno */
95
    }
96
    if (avctx->extradata_size > 9 &&
97
        AV_RL32(avctx->extradata + 4) == MKTAG('f','i','e','l')) {
98
        if (avctx->extradata[9] == 6) { /* quicktime icefloe 019 */
99
            s->interlace_polarity = 1; /* bottom field first */
100
            av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
101
        }
102
    }
103

    
104
    return 0;
105
}
106

    
107

    
108
/* quantize tables */
109
static int mjpeg_decode_dqt(MJpegDecodeContext *s)
110
{
111
    int len, index, i, j;
112

    
113
    len = get_bits(&s->gb, 16) - 2;
114

    
115
    while (len >= 65) {
116
        /* only 8 bit precision handled */
117
        if (get_bits(&s->gb, 4) != 0)
118
        {
119
            av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
120
            return -1;
121
        }
122
        index = get_bits(&s->gb, 4);
123
        if (index >= 4)
124
            return -1;
125
        av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
126
        /* read quant table */
127
        for(i=0;i<64;i++) {
128
            j = s->scantable.permutated[i];
129
            s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
130
        }
131

    
132
        //XXX FIXME finetune, and perhaps add dc too
133
        s->qscale[index]= FFMAX(
134
            s->quant_matrixes[index][s->scantable.permutated[1]],
135
            s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
136
        av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n", index, s->qscale[index]);
137
        len -= 65;
138
    }
139

    
140
    return 0;
141
}
142

    
143
/* decode huffman tables and build VLC decoders */
144
static int mjpeg_decode_dht(MJpegDecodeContext *s)
145
{
146
    int len, index, i, class, n, v, code_max;
147
    uint8_t bits_table[17];
148
    uint8_t val_table[256];
149

    
150
    len = get_bits(&s->gb, 16) - 2;
151

    
152
    while (len > 0) {
153
        if (len < 17)
154
            return -1;
155
        class = get_bits(&s->gb, 4);
156
        if (class >= 2)
157
            return -1;
158
        index = get_bits(&s->gb, 4);
159
        if (index >= 4)
160
            return -1;
161
        n = 0;
162
        for(i=1;i<=16;i++) {
163
            bits_table[i] = get_bits(&s->gb, 8);
164
            n += bits_table[i];
165
        }
166
        len -= 17;
167
        if (len < n || n > 256)
168
            return -1;
169

    
170
        code_max = 0;
171
        for(i=0;i<n;i++) {
172
            v = get_bits(&s->gb, 8);
173
            if (v > code_max)
174
                code_max = v;
175
            val_table[i] = v;
176
        }
177
        len -= n;
178

    
179
        /* build VLC and flush previous vlc if present */
180
        free_vlc(&s->vlcs[class][index]);
181
        av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
182
               class, index, code_max + 1);
183
        if(build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1, 0, class > 0) < 0){
184
            return -1;
185
        }
186
    }
187
    return 0;
188
}
189

    
190
static int mjpeg_decode_sof(MJpegDecodeContext *s)
191
{
192
    int len, nb_components, i, width, height, pix_fmt_id;
193

    
194
    /* XXX: verify len field validity */
195
    len = get_bits(&s->gb, 16);
196
    s->bits= get_bits(&s->gb, 8);
197

    
198
    if(s->pegasus_rct) s->bits=9;
199
    if(s->bits==9 && !s->pegasus_rct) s->rct=1;    //FIXME ugly
200

    
201
    if (s->bits != 8 && !s->lossless){
202
        av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
203
        return -1;
204
    }
205

    
206
    height = get_bits(&s->gb, 16);
207
    width = get_bits(&s->gb, 16);
208

    
209
    //HACK for odd_height.mov
210
    if(s->interlaced && s->width == width && s->height == height + 1)
211
        height= s->height;
212

    
213
    av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
214
    if(avcodec_check_dimensions(s->avctx, width, height))
215
        return -1;
216

    
217
    nb_components = get_bits(&s->gb, 8);
218
    if (nb_components <= 0 ||
219
        nb_components > MAX_COMPONENTS)
220
        return -1;
221
    if (s->ls && !(s->bits <= 8 || nb_components == 1)){
222
        av_log(s->avctx, AV_LOG_ERROR, "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
223
        return -1;
224
    }
225
    s->nb_components = nb_components;
226
    s->h_max = 1;
227
    s->v_max = 1;
228
    for(i=0;i<nb_components;i++) {
229
        /* component id */
230
        s->component_id[i] = get_bits(&s->gb, 8) - 1;
231
        s->h_count[i] = get_bits(&s->gb, 4);
232
        s->v_count[i] = get_bits(&s->gb, 4);
233
        /* compute hmax and vmax (only used in interleaved case) */
234
        if (s->h_count[i] > s->h_max)
235
            s->h_max = s->h_count[i];
236
        if (s->v_count[i] > s->v_max)
237
            s->v_max = s->v_count[i];
238
        s->quant_index[i] = get_bits(&s->gb, 8);
239
        if (s->quant_index[i] >= 4)
240
            return -1;
241
        av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n", i, s->h_count[i],
242
               s->v_count[i], s->component_id[i], s->quant_index[i]);
243
    }
244

    
245
    if(s->ls && (s->h_max > 1 || s->v_max > 1)) {
246
        av_log(s->avctx, AV_LOG_ERROR, "Subsampling in JPEG-LS is not supported.\n");
247
        return -1;
248
    }
249

    
250
    if(s->v_max==1 && s->h_max==1 && s->lossless==1) s->rgb=1;
251

    
252
    /* if different size, realloc/alloc picture */
253
    /* XXX: also check h_count and v_count */
254
    if (width != s->width || height != s->height) {
255
        av_freep(&s->qscale_table);
256

    
257
        s->width = width;
258
        s->height = height;
259
        s->interlaced = 0;
260

    
261
        /* test interlaced mode */
262
        if (s->first_picture &&
263
            s->org_height != 0 &&
264
            s->height < ((s->org_height * 3) / 4)) {
265
            s->interlaced = 1;
266
            s->bottom_field = s->interlace_polarity;
267
            s->picture.interlaced_frame = 1;
268
            s->picture.top_field_first = !s->interlace_polarity;
269
            height *= 2;
270
        }
271

    
272
        avcodec_set_dimensions(s->avctx, width, height);
273

    
274
        s->qscale_table= av_mallocz((s->width+15)/16);
275

    
276
        s->first_picture = 0;
277
    }
278

    
279
    if(s->interlaced && (s->bottom_field == !s->interlace_polarity))
280
        return 0;
281

    
282
    /* XXX: not complete test ! */
283
    pix_fmt_id = (s->h_count[0] << 20) | (s->v_count[0] << 16) |
284
                 (s->h_count[1] << 12) | (s->v_count[1] <<  8) |
285
                 (s->h_count[2] <<  4) |  s->v_count[2];
286
    av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
287
    switch(pix_fmt_id){
288
    case 0x222222:
289
    case 0x111111:
290
        if(s->rgb){
291
            s->avctx->pix_fmt = PIX_FMT_RGB32;
292
        }else if(s->nb_components==3)
293
            s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
294
        else
295
            s->avctx->pix_fmt = PIX_FMT_GRAY8;
296
        break;
297
    case 0x211111:
298
    case 0x221212:
299
        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV422P : PIX_FMT_YUVJ422P;
300
        break;
301
    default:
302
    case 0x221111:
303
        s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420P;
304
        break;
305
    }
306
    if(s->ls){
307
        if(s->nb_components > 1)
308
            s->avctx->pix_fmt = PIX_FMT_RGB24;
309
        else if(s->bits <= 8)
310
            s->avctx->pix_fmt = PIX_FMT_GRAY8;
311
        else
312
            s->avctx->pix_fmt = PIX_FMT_GRAY16;
313
    }
314

    
315
    if(s->picture.data[0])
316
        s->avctx->release_buffer(s->avctx, &s->picture);
317

    
318
    s->picture.reference= 0;
319
    if(s->avctx->get_buffer(s->avctx, &s->picture) < 0){
320
        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
321
        return -1;
322
    }
323
    s->picture.pict_type= I_TYPE;
324
    s->picture.key_frame= 1;
325

    
326
    for(i=0; i<3; i++){
327
        s->linesize[i]= s->picture.linesize[i] << s->interlaced;
328
    }
329

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

    
332
    if (len != (8+(3*nb_components)))
333
    {
334
        av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
335
    }
336

    
337
    /* totally blank picture as progressive JPEG will only add details to it */
338
    if(s->progressive){
339
        memset(s->picture.data[0], 0, s->picture.linesize[0] * s->height);
340
        memset(s->picture.data[1], 0, s->picture.linesize[1] * s->height >> (s->v_max - s->v_count[1]));
341
        memset(s->picture.data[2], 0, s->picture.linesize[2] * s->height >> (s->v_max - s->v_count[2]));
342
    }
343
    return 0;
344
}
345

    
346
static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
347
{
348
    int code;
349
    code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
350
    if (code < 0)
351
    {
352
        av_log(s->avctx, AV_LOG_WARNING, "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n", 0, dc_index,
353
               &s->vlcs[0][dc_index]);
354
        return 0xffff;
355
    }
356

    
357
    if(code)
358
        return get_xbits(&s->gb, code);
359
    else
360
        return 0;
361
}
362

    
363
/* decode block and dequantize */
364
static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
365
                        int component, int dc_index, int ac_index, int16_t *quant_matrix)
366
{
367
    int code, i, j, level, val;
368

    
369
    /* DC coef */
370
    val = mjpeg_decode_dc(s, dc_index);
371
    if (val == 0xffff) {
372
        av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
373
        return -1;
374
    }
375
    val = val * quant_matrix[0] + s->last_dc[component];
376
    s->last_dc[component] = val;
377
    block[0] = val;
378
    /* AC coefs */
379
    i = 0;
380
    {OPEN_READER(re, &s->gb)
381
    for(;;) {
382
        UPDATE_CACHE(re, &s->gb);
383
        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
384

    
385
        /* EOB */
386
        if (code == 0x10)
387
            break;
388
        i += ((unsigned)code) >> 4;
389
        if(code != 0x100){
390
            code &= 0xf;
391
            if(code > MIN_CACHE_BITS - 16){
392
                UPDATE_CACHE(re, &s->gb)
393
            }
394
            {
395
                int cache=GET_CACHE(re,&s->gb);
396
                int sign=(~cache)>>31;
397
                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
398
            }
399

    
400
            LAST_SKIP_BITS(re, &s->gb, code)
401

    
402
            if (i >= 63) {
403
                if(i == 63){
404
                    j = s->scantable.permutated[63];
405
                    block[j] = level * quant_matrix[j];
406
                    break;
407
                }
408
                av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
409
                return -1;
410
            }
411
            j = s->scantable.permutated[i];
412
            block[j] = level * quant_matrix[j];
413
        }
414
    }
415
    CLOSE_READER(re, &s->gb)}
416

    
417
    return 0;
418
}
419

    
420
/* decode block and dequantize - progressive JPEG version */
421
static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block,
422
                        int component, int dc_index, int ac_index, int16_t *quant_matrix,
423
                        int ss, int se, int Ah, int Al, int *EOBRUN)
424
{
425
    int code, i, j, level, val, run;
426

    
427
    /* DC coef */
428
    if(!ss){
429
        val = mjpeg_decode_dc(s, dc_index);
430
        if (val == 0xffff) {
431
            av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
432
            return -1;
433
        }
434
        val = (val * quant_matrix[0] << Al) + s->last_dc[component];
435
    }else
436
        val = 0;
437
    s->last_dc[component] = val;
438
    block[0] = val;
439
    if(!se) return 0;
440
    /* AC coefs */
441
    if(*EOBRUN){
442
        (*EOBRUN)--;
443
        return 0;
444
    }
445
    {OPEN_READER(re, &s->gb)
446
    for(i=ss;;i++) {
447
        UPDATE_CACHE(re, &s->gb);
448
        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)
449
        /* Progressive JPEG use AC coeffs from zero and this decoder sets offset 16 by default */
450
        code -= 16;
451
        if(code & 0xF) {
452
            i += ((unsigned) code) >> 4;
453
            code &= 0xf;
454
            if(code > MIN_CACHE_BITS - 16){
455
                UPDATE_CACHE(re, &s->gb)
456
            }
457
            {
458
                int cache=GET_CACHE(re,&s->gb);
459
                int sign=(~cache)>>31;
460
                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
461
            }
462

    
463
            LAST_SKIP_BITS(re, &s->gb, code)
464

    
465
            if (i >= se) {
466
                if(i == se){
467
                    j = s->scantable.permutated[se];
468
                    block[j] = level * quant_matrix[j] << Al;
469
                    break;
470
                }
471
                av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
472
                return -1;
473
            }
474
            j = s->scantable.permutated[i];
475
            block[j] = level * quant_matrix[j] << Al;
476
        }else{
477
            run = ((unsigned) code) >> 4;
478
            if(run == 0xF){// ZRL - skip 15 coefficients
479
                i += 15;
480
            }else{
481
                val = run;
482
                run = (1 << run);
483
                UPDATE_CACHE(re, &s->gb);
484
                run += (GET_CACHE(re, &s->gb) >> (32 - val)) & (run - 1);
485
                if(val)
486
                    LAST_SKIP_BITS(re, &s->gb, val);
487
                *EOBRUN = run - 1;
488
                break;
489
            }
490
        }
491
    }
492
    CLOSE_READER(re, &s->gb)}
493

    
494
    return 0;
495
}
496

    
497
static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point_transform){
498
    int i, mb_x, mb_y;
499
    uint16_t buffer[32768][4];
500
    int left[3], top[3], topleft[3];
501
    const int linesize= s->linesize[0];
502
    const int mask= (1<<s->bits)-1;
503

    
504
    if((unsigned)s->mb_width > 32768) //dynamic alloc
505
        return -1;
506

    
507
    for(i=0; i<3; i++){
508
        buffer[0][i]= 1 << (s->bits + point_transform - 1);
509
    }
510
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
511
        const int modified_predictor= mb_y ? predictor : 1;
512
        uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
513

    
514
        if (s->interlaced && s->bottom_field)
515
            ptr += linesize >> 1;
516

    
517
        for(i=0; i<3; i++){
518
            top[i]= left[i]= topleft[i]= buffer[0][i];
519
        }
520
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
521
            if (s->restart_interval && !s->restart_count)
522
                s->restart_count = s->restart_interval;
523

    
524
            for(i=0;i<3;i++) {
525
                int pred;
526

    
527
                topleft[i]= top[i];
528
                top[i]= buffer[mb_x][i];
529

    
530
                PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
531

    
532
                left[i]=
533
                buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
534
            }
535

    
536
            if (s->restart_interval && !--s->restart_count) {
537
                align_get_bits(&s->gb);
538
                skip_bits(&s->gb, 16); /* skip RSTn */
539
            }
540
        }
541

    
542
        if(s->rct){
543
            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
544
                ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);
545
                ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
546
                ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
547
            }
548
        }else if(s->pegasus_rct){
549
            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
550
                ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);
551
                ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
552
                ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
553
            }
554
        }else{
555
            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
556
                ptr[4*mb_x+0] = buffer[mb_x][0];
557
                ptr[4*mb_x+1] = buffer[mb_x][1];
558
                ptr[4*mb_x+2] = buffer[mb_x][2];
559
            }
560
        }
561
    }
562
    return 0;
563
}
564

    
565
static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
566
    int i, mb_x, mb_y;
567
    const int nb_components=3;
568

    
569
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
570
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
571
            if (s->restart_interval && !s->restart_count)
572
                s->restart_count = s->restart_interval;
573

    
574
            if(mb_x==0 || mb_y==0 || s->interlaced){
575
                for(i=0;i<nb_components;i++) {
576
                    uint8_t *ptr;
577
                    int n, h, v, x, y, c, j, linesize;
578
                    n = s->nb_blocks[i];
579
                    c = s->comp_index[i];
580
                    h = s->h_scount[i];
581
                    v = s->v_scount[i];
582
                    x = 0;
583
                    y = 0;
584
                    linesize= s->linesize[c];
585

    
586
                    for(j=0; j<n; j++) {
587
                        int pred;
588

    
589
                        ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
590
                        if(y==0 && mb_y==0){
591
                            if(x==0 && mb_x==0){
592
                                pred= 128 << point_transform;
593
                            }else{
594
                                pred= ptr[-1];
595
                            }
596
                        }else{
597
                            if(x==0 && mb_x==0){
598
                                pred= ptr[-linesize];
599
                            }else{
600
                                PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
601
                            }
602
                        }
603

    
604
                        if (s->interlaced && s->bottom_field)
605
                            ptr += linesize >> 1;
606
                        *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
607

    
608
                        if (++x == h) {
609
                            x = 0;
610
                            y++;
611
                        }
612
                    }
613
                }
614
            }else{
615
                for(i=0;i<nb_components;i++) {
616
                    uint8_t *ptr;
617
                    int n, h, v, x, y, c, j, linesize;
618
                    n = s->nb_blocks[i];
619
                    c = s->comp_index[i];
620
                    h = s->h_scount[i];
621
                    v = s->v_scount[i];
622
                    x = 0;
623
                    y = 0;
624
                    linesize= s->linesize[c];
625

    
626
                    for(j=0; j<n; j++) {
627
                        int pred;
628

    
629
                        ptr = s->picture.data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
630
                        PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
631
                        *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
632
                        if (++x == h) {
633
                            x = 0;
634
                            y++;
635
                        }
636
                    }
637
                }
638
            }
639
            if (s->restart_interval && !--s->restart_count) {
640
                align_get_bits(&s->gb);
641
                skip_bits(&s->gb, 16); /* skip RSTn */
642
            }
643
        }
644
    }
645
    return 0;
646
}
647

    
648
static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int ss, int se, int Ah, int Al){
649
    int i, mb_x, mb_y;
650
    int EOBRUN = 0;
651

    
652
    if(Ah) return 0; /* TODO decode refinement planes too */
653
    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
654
        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
655
            if (s->restart_interval && !s->restart_count)
656
                s->restart_count = s->restart_interval;
657

    
658
            for(i=0;i<nb_components;i++) {
659
                uint8_t *ptr;
660
                int n, h, v, x, y, c, j;
661
                n = s->nb_blocks[i];
662
                c = s->comp_index[i];
663
                h = s->h_scount[i];
664
                v = s->v_scount[i];
665
                x = 0;
666
                y = 0;
667
                for(j=0;j<n;j++) {
668
                    memset(s->block, 0, sizeof(s->block));
669
                    if (!s->progressive && decode_block(s, s->block, i,
670
                                     s->dc_index[i], s->ac_index[i],
671
                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {
672
                        av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
673
                        return -1;
674
                    }
675
                    if (s->progressive && decode_block_progressive(s, s->block, i,
676
                                     s->dc_index[i], s->ac_index[i],
677
                                     s->quant_matrixes[ s->quant_index[c] ], ss, se, Ah, Al, &EOBRUN) < 0) {
678
                        av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
679
                        return -1;
680
                    }
681
//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
682
                    ptr = s->picture.data[c] +
683
                        (((s->linesize[c] * (v * mb_y + y) * 8) +
684
                        (h * mb_x + x) * 8) >> s->avctx->lowres);
685
                    if (s->interlaced && s->bottom_field)
686
                        ptr += s->linesize[c] >> 1;
687
//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);
688
                    if(!s->progressive)
689
                        s->dsp.idct_put(ptr, s->linesize[c], s->block);
690
                    else
691
                        s->dsp.idct_add(ptr, s->linesize[c], s->block);
692
                    if (++x == h) {
693
                        x = 0;
694
                        y++;
695
                    }
696
                }
697
            }
698
            /* (< 1350) buggy workaround for Spectralfan.mov, should be fixed */
699
            if (s->restart_interval && (s->restart_interval < 1350) &&
700
                !--s->restart_count) {
701
                align_get_bits(&s->gb);
702
                skip_bits(&s->gb, 16); /* skip RSTn */
703
                for (i=0; i<nb_components; i++) /* reset dc */
704
                    s->last_dc[i] = 1024;
705
            }
706
        }
707
    }
708
    return 0;
709
}
710

    
711
static int mjpeg_decode_sos(MJpegDecodeContext *s)
712
{
713
    int len, nb_components, i, h, v, predictor, point_transform;
714
    int vmax, hmax, index, id;
715
    const int block_size= s->lossless ? 1 : 8;
716
    int ilv, prev_shift;
717

    
718
    /* XXX: verify len field validity */
719
    len = get_bits(&s->gb, 16);
720
    nb_components = get_bits(&s->gb, 8);
721
    if (len != 6+2*nb_components)
722
    {
723
        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
724
        return -1;
725
    }
726
    vmax = 0;
727
    hmax = 0;
728
    for(i=0;i<nb_components;i++) {
729
        id = get_bits(&s->gb, 8) - 1;
730
        av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
731
        /* find component index */
732
        for(index=0;index<s->nb_components;index++)
733
            if (id == s->component_id[index])
734
                break;
735
        if (index == s->nb_components)
736
        {
737
            av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
738
            return -1;
739
        }
740

    
741
        s->comp_index[i] = index;
742

    
743
        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
744
        s->h_scount[i] = s->h_count[index];
745
        s->v_scount[i] = s->v_count[index];
746

    
747
        s->dc_index[i] = get_bits(&s->gb, 4);
748
        s->ac_index[i] = get_bits(&s->gb, 4);
749

    
750
        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
751
            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
752
            goto out_of_range;
753
#if 0 //buggy
754
        switch(s->start_code)
755
        {
756
            case SOF0:
757
                if (dc_index[i] > 1 || ac_index[i] > 1)
758
                    goto out_of_range;
759
                break;
760
            case SOF1:
761
            case SOF2:
762
                if (dc_index[i] > 3 || ac_index[i] > 3)
763
                    goto out_of_range;
764
                break;
765
            case SOF3:
766
                if (dc_index[i] > 3 || ac_index[i] != 0)
767
                    goto out_of_range;
768
                break;
769
        }
770
#endif
771
    }
772

    
773
    predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
774
    ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
775
    prev_shift = get_bits(&s->gb, 4); /* Ah */
776
    point_transform= get_bits(&s->gb, 4); /* Al */
777

    
778
    for(i=0;i<nb_components;i++)
779
        s->last_dc[i] = 1024;
780

    
781
    if (nb_components > 1) {
782
        /* interleaved stream */
783
        s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
784
        s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
785
    } else if(!s->ls) { /* skip this for JPEG-LS */
786
        h = s->h_max / s->h_scount[0];
787
        v = s->v_max / s->v_scount[0];
788
        s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
789
        s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
790
        s->nb_blocks[0] = 1;
791
        s->h_scount[0] = 1;
792
        s->v_scount[0] = 1;
793
    }
794

    
795
    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
796
        av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n", s->lossless ? "lossless" : "sequencial DCT", s->rgb ? "RGB" : "",
797
               predictor, point_transform, ilv, s->bits,
798
               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
799

    
800

    
801
    /* mjpeg-b can have padding bytes between sos and image data, skip them */
802
    for (i = s->mjpb_skiptosod; i > 0; i--)
803
        skip_bits(&s->gb, 8);
804

    
805
    if(s->lossless){
806
        if(s->ls){
807
//            for(){
808
//            reset_ls_coding_parameters(s, 0);
809

    
810
            ff_jpegls_decode_picture(s, predictor, point_transform, ilv);
811
        }else{
812
            if(s->rgb){
813
                if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
814
                    return -1;
815
            }else{
816
                if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
817
                    return -1;
818
            }
819
        }
820
    }else{
821
        if(mjpeg_decode_scan(s, nb_components, predictor, ilv, prev_shift, point_transform) < 0)
822
            return -1;
823
    }
824
    emms_c();
825
    return 0;
826
 out_of_range:
827
    av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
828
    return -1;
829
}
830

    
831
static int mjpeg_decode_dri(MJpegDecodeContext *s)
832
{
833
    if (get_bits(&s->gb, 16) != 4)
834
        return -1;
835
    s->restart_interval = get_bits(&s->gb, 16);
836
    s->restart_count = 0;
837
    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
838

    
839
    return 0;
840
}
841

    
842
static int mjpeg_decode_app(MJpegDecodeContext *s)
843
{
844
    int len, id, i;
845

    
846
    len = get_bits(&s->gb, 16);
847
    if (len < 5)
848
        return -1;
849
    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
850
        return -1;
851

    
852
    id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
853
    id = be2me_32(id);
854
    len -= 6;
855

    
856
    if(s->avctx->debug & FF_DEBUG_STARTCODE){
857
        av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
858
    }
859

    
860
    /* buggy AVID, it puts EOI only at every 10th frame */
861
    /* also this fourcc is used by non-avid files too, it holds some
862
       informations, but it's always present in AVID creates files */
863
    if (id == ff_get_fourcc("AVI1"))
864
    {
865
        /* structure:
866
            4bytes      AVI1
867
            1bytes      polarity
868
            1bytes      always zero
869
            4bytes      field_size
870
            4bytes      field_size_less_padding
871
        */
872
            s->buggy_avid = 1;
873
//        if (s->first_picture)
874
//            printf("mjpeg: workarounding buggy AVID\n");
875
        i = get_bits(&s->gb, 8);
876
        if     (i==2) s->bottom_field= 1;
877
        else if(i==1) s->bottom_field= 0;
878
#if 0
879
        skip_bits(&s->gb, 8);
880
        skip_bits(&s->gb, 32);
881
        skip_bits(&s->gb, 32);
882
        len -= 10;
883
#endif
884
//        if (s->interlace_polarity)
885
//            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
886
        goto out;
887
    }
888

    
889
//    len -= 2;
890

    
891
    if (id == ff_get_fourcc("JFIF"))
892
    {
893
        int t_w, t_h, v1, v2;
894
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
895
        v1= get_bits(&s->gb, 8);
896
        v2= get_bits(&s->gb, 8);
897
        skip_bits(&s->gb, 8);
898

    
899
        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
900
        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
901

    
902
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
903
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
904
                v1, v2,
905
                s->avctx->sample_aspect_ratio.num,
906
                s->avctx->sample_aspect_ratio.den
907
            );
908

    
909
        t_w = get_bits(&s->gb, 8);
910
        t_h = get_bits(&s->gb, 8);
911
        if (t_w && t_h)
912
        {
913
            /* skip thumbnail */
914
            if (len-10-(t_w*t_h*3) > 0)
915
                len -= t_w*t_h*3;
916
        }
917
        len -= 10;
918
        goto out;
919
    }
920

    
921
    if (id == ff_get_fourcc("Adob") && (get_bits(&s->gb, 8) == 'e'))
922
    {
923
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
924
            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
925
        skip_bits(&s->gb, 16); /* version */
926
        skip_bits(&s->gb, 16); /* flags0 */
927
        skip_bits(&s->gb, 16); /* flags1 */
928
        skip_bits(&s->gb, 8);  /* transform */
929
        len -= 7;
930
        goto out;
931
    }
932

    
933
    if (id == ff_get_fourcc("LJIF")){
934
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
935
            av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
936
        skip_bits(&s->gb, 16); /* version ? */
937
        skip_bits(&s->gb, 16); /* unknwon always 0? */
938
        skip_bits(&s->gb, 16); /* unknwon always 0? */
939
        skip_bits(&s->gb, 16); /* unknwon always 0? */
940
        switch( get_bits(&s->gb, 8)){
941
        case 1:
942
            s->rgb= 1;
943
            s->pegasus_rct=0;
944
            break;
945
        case 2:
946
            s->rgb= 1;
947
            s->pegasus_rct=1;
948
            break;
949
        default:
950
            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
951
        }
952
        len -= 9;
953
        goto out;
954
    }
955

    
956
    /* Apple MJPEG-A */
957
    if ((s->start_code == APP1) && (len > (0x28 - 8)))
958
    {
959
        id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
960
        id = be2me_32(id);
961
        len -= 4;
962
        if (id == ff_get_fourcc("mjpg")) /* Apple MJPEG-A */
963
        {
964
#if 0
965
            skip_bits(&s->gb, 32); /* field size */
966
            skip_bits(&s->gb, 32); /* pad field size */
967
            skip_bits(&s->gb, 32); /* next off */
968
            skip_bits(&s->gb, 32); /* quant off */
969
            skip_bits(&s->gb, 32); /* huff off */
970
            skip_bits(&s->gb, 32); /* image off */
971
            skip_bits(&s->gb, 32); /* scan off */
972
            skip_bits(&s->gb, 32); /* data off */
973
#endif
974
            if (s->avctx->debug & FF_DEBUG_PICT_INFO)
975
                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
976
        }
977
    }
978

    
979
out:
980
    /* slow but needed for extreme adobe jpegs */
981
    if (len < 0)
982
        av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
983
    while(--len > 0)
984
        skip_bits(&s->gb, 8);
985

    
986
    return 0;
987
}
988

    
989
static int mjpeg_decode_com(MJpegDecodeContext *s)
990
{
991
    int len = get_bits(&s->gb, 16);
992
    if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
993
        char *cbuf = av_malloc(len - 1);
994
        if (cbuf) {
995
            int i;
996
            for (i = 0; i < len - 2; i++)
997
                cbuf[i] = get_bits(&s->gb, 8);
998
            if (i > 0 && cbuf[i-1] == '\n')
999
                cbuf[i-1] = 0;
1000
            else
1001
                cbuf[i] = 0;
1002

    
1003
            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
1004
                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
1005

    
1006
            /* buggy avid, it puts EOI only at every 10th frame */
1007
            if (!strcmp(cbuf, "AVID"))
1008
            {
1009
                s->buggy_avid = 1;
1010
                //        if (s->first_picture)
1011
                //            printf("mjpeg: workarounding buggy AVID\n");
1012
            }
1013
            else if(!strcmp(cbuf, "CS=ITU601")){
1014
                s->cs_itu601= 1;
1015
            }
1016

    
1017
            av_free(cbuf);
1018
        }
1019
    }
1020

    
1021
    return 0;
1022
}
1023

    
1024
#if 0
1025
static int valid_marker_list[] =
1026
{
1027
        /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1028
/* 0 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1029
/* 1 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1030
/* 2 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1031
/* 3 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1032
/* 4 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1033
/* 5 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1034
/* 6 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1035
/* 7 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1036
/* 8 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1037
/* 9 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1038
/* a */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1039
/* b */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1040
/* c */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1041
/* d */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1042
/* e */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1043
/* f */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1044
}
1045
#endif
1046

    
1047
/* return the 8 bit start code value and update the search
1048
   state. Return -1 if no start code found */
1049
static int find_marker(uint8_t **pbuf_ptr, uint8_t *buf_end)
1050
{
1051
    uint8_t *buf_ptr;
1052
    unsigned int v, v2;
1053
    int val;
1054
#ifdef DEBUG
1055
    int skipped=0;
1056
#endif
1057

    
1058
    buf_ptr = *pbuf_ptr;
1059
    while (buf_ptr < buf_end) {
1060
        v = *buf_ptr++;
1061
        v2 = *buf_ptr;
1062
        if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1063
            val = *buf_ptr++;
1064
            goto found;
1065
        }
1066
#ifdef DEBUG
1067
        skipped++;
1068
#endif
1069
    }
1070
    val = -1;
1071
found:
1072
#ifdef DEBUG
1073
    av_log(NULL, AV_LOG_VERBOSE, "find_marker skipped %d bytes\n", skipped);
1074
#endif
1075
    *pbuf_ptr = buf_ptr;
1076
    return val;
1077
}
1078

    
1079
static int mjpeg_decode_frame(AVCodecContext *avctx,
1080
                              void *data, int *data_size,
1081
                              uint8_t *buf, int buf_size)
1082
{
1083
    MJpegDecodeContext *s = avctx->priv_data;
1084
    uint8_t *buf_end, *buf_ptr;
1085
    int start_code;
1086
    AVFrame *picture = data;
1087

    
1088
    buf_ptr = buf;
1089
    buf_end = buf + buf_size;
1090
    while (buf_ptr < buf_end) {
1091
        /* find start next marker */
1092
        start_code = find_marker(&buf_ptr, buf_end);
1093
        {
1094
            /* EOF */
1095
            if (start_code < 0) {
1096
                goto the_end;
1097
            } else {
1098
                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%d\n", start_code, buf_end - buf_ptr);
1099

    
1100
                if ((buf_end - buf_ptr) > s->buffer_size)
1101
                {
1102
                    av_free(s->buffer);
1103
                    s->buffer_size = buf_end-buf_ptr;
1104
                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
1105
                    av_log(avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
1106
                        s->buffer_size);
1107
                }
1108

    
1109
                /* unescape buffer of SOS, use special treatment for JPEG-LS */
1110
                if (start_code == SOS && !s->ls)
1111
                {
1112
                    uint8_t *src = buf_ptr;
1113
                    uint8_t *dst = s->buffer;
1114

    
1115
                    while (src<buf_end)
1116
                    {
1117
                        uint8_t x = *(src++);
1118

    
1119
                        *(dst++) = x;
1120
                        if (avctx->codec_id != CODEC_ID_THP)
1121
                        {
1122
                            if (x == 0xff) {
1123
                                while (src < buf_end && x == 0xff)
1124
                                    x = *(src++);
1125

    
1126
                                if (x >= 0xd0 && x <= 0xd7)
1127
                                    *(dst++) = x;
1128
                                else if (x)
1129
                                    break;
1130
                            }
1131
                        }
1132
                    }
1133
                    init_get_bits(&s->gb, s->buffer, (dst - s->buffer)*8);
1134

    
1135
                    av_log(avctx, AV_LOG_DEBUG, "escaping removed %d bytes\n",
1136
                           (buf_end - buf_ptr) - (dst - s->buffer));
1137
                }
1138
                else if(start_code == SOS && s->ls){
1139
                    uint8_t *src = buf_ptr;
1140
                    uint8_t *dst = s->buffer;
1141
                    int bit_count = 0;
1142
                    int t = 0, b = 0;
1143
                    PutBitContext pb;
1144

    
1145
                    s->cur_scan++;
1146

    
1147
                    /* find marker */
1148
                    while (src + t < buf_end){
1149
                        uint8_t x = src[t++];
1150
                        if (x == 0xff){
1151
                            while((src + t < buf_end) && x == 0xff)
1152
                                x = src[t++];
1153
                            if (x & 0x80) {
1154
                                t -= 2;
1155
                                break;
1156
                            }
1157
                        }
1158
                    }
1159
                    bit_count = t * 8;
1160

    
1161
                    init_put_bits(&pb, dst, t);
1162

    
1163
                    /* unescape bitstream */
1164
                    while(b < t){
1165
                        uint8_t x = src[b++];
1166
                        put_bits(&pb, 8, x);
1167
                        if(x == 0xFF){
1168
                            x = src[b++];
1169
                            put_bits(&pb, 7, x);
1170
                            bit_count--;
1171
                        }
1172
                    }
1173
                    flush_put_bits(&pb);
1174

    
1175
                    init_get_bits(&s->gb, dst, bit_count);
1176
                }
1177
                else
1178
                    init_get_bits(&s->gb, buf_ptr, (buf_end - buf_ptr)*8);
1179

    
1180
                s->start_code = start_code;
1181
                if(s->avctx->debug & FF_DEBUG_STARTCODE){
1182
                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1183
                }
1184

    
1185
                /* process markers */
1186
                if (start_code >= 0xd0 && start_code <= 0xd7) {
1187
                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
1188
                    /* APP fields */
1189
                } else if (start_code >= APP0 && start_code <= APP15) {
1190
                    mjpeg_decode_app(s);
1191
                    /* Comment */
1192
                } else if (start_code == COM){
1193
                    mjpeg_decode_com(s);
1194
                }
1195

    
1196
                switch(start_code) {
1197
                case SOI:
1198
                    s->restart_interval = 0;
1199

    
1200
                    s->restart_count = 0;
1201
                    /* nothing to do on SOI */
1202
                    break;
1203
                case DQT:
1204
                    mjpeg_decode_dqt(s);
1205
                    break;
1206
                case DHT:
1207
                    if(mjpeg_decode_dht(s) < 0){
1208
                        av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1209
                        return -1;
1210
                    }
1211
                    break;
1212
                case SOF0:
1213
                    s->lossless=0;
1214
                    s->ls=0;
1215
                    s->progressive=0;
1216
                    if (mjpeg_decode_sof(s) < 0)
1217
                        return -1;
1218
                    break;
1219
                case SOF2:
1220
                    s->lossless=0;
1221
                    s->ls=0;
1222
                    s->progressive=1;
1223
                    if (mjpeg_decode_sof(s) < 0)
1224
                        return -1;
1225
                    break;
1226
                case SOF3:
1227
                    s->lossless=1;
1228
                    s->ls=0;
1229
                    s->progressive=0;
1230
                    if (mjpeg_decode_sof(s) < 0)
1231
                        return -1;
1232
                    break;
1233
                case SOF48:
1234
                    s->lossless=1;
1235
                    s->ls=1;
1236
                    s->progressive=0;
1237
                    if (mjpeg_decode_sof(s) < 0)
1238
                        return -1;
1239
                    break;
1240
                case LSE:
1241
                    if (ff_jpegls_decode_lse(s) < 0)
1242
                        return -1;
1243
                    break;
1244
                case EOI:
1245
                    s->cur_scan = 0;
1246
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1247
                        break;
1248
eoi_parser:
1249
                    {
1250
                        if (s->interlaced) {
1251
                            s->bottom_field ^= 1;
1252
                            /* if not bottom field, do not output image yet */
1253
                            if (s->bottom_field == !s->interlace_polarity)
1254
                                goto not_the_end;
1255
                        }
1256
                        *picture = s->picture;
1257
                        *data_size = sizeof(AVFrame);
1258

    
1259
                        if(!s->lossless){
1260
                            picture->quality= FFMAX(FFMAX(s->qscale[0], s->qscale[1]), s->qscale[2]);
1261
                            picture->qstride= 0;
1262
                            picture->qscale_table= s->qscale_table;
1263
                            memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1264
                            if(avctx->debug & FF_DEBUG_QP)
1265
                                av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1266
                            picture->quality*= FF_QP2LAMBDA;
1267
                        }
1268

    
1269
                        goto the_end;
1270
                    }
1271
                    break;
1272
                case SOS:
1273
                    mjpeg_decode_sos(s);
1274
                    /* buggy avid puts EOI every 10-20th frame */
1275
                    /* if restart period is over process EOI */
1276
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1277
                        goto eoi_parser;
1278
                    break;
1279
                case DRI:
1280
                    mjpeg_decode_dri(s);
1281
                    break;
1282
                case SOF1:
1283
                case SOF5:
1284
                case SOF6:
1285
                case SOF7:
1286
                case SOF9:
1287
                case SOF10:
1288
                case SOF11:
1289
                case SOF13:
1290
                case SOF14:
1291
                case SOF15:
1292
                case JPG:
1293
                    av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
1294
                    break;
1295
//                default:
1296
//                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1297
//                    break;
1298
                }
1299

    
1300
not_the_end:
1301
                /* eof process start code */
1302
                buf_ptr += (get_bits_count(&s->gb)+7)/8;
1303
                av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
1304
                       (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1305
            }
1306
        }
1307
    }
1308
the_end:
1309
    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %d bytes\n", buf_end - buf_ptr);
1310
//    return buf_end - buf_ptr;
1311
    return buf_ptr - buf;
1312
}
1313

    
1314
static int mjpegb_decode_frame(AVCodecContext *avctx,
1315
                              void *data, int *data_size,
1316
                              uint8_t *buf, int buf_size)
1317
{
1318
    MJpegDecodeContext *s = avctx->priv_data;
1319
    uint8_t *buf_end, *buf_ptr;
1320
    AVFrame *picture = data;
1321
    GetBitContext hgb; /* for the header */
1322
    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;
1323
    uint32_t field_size, sod_offs;
1324

    
1325
    buf_ptr = buf;
1326
    buf_end = buf + buf_size;
1327

    
1328
read_header:
1329
    /* reset on every SOI */
1330
    s->restart_interval = 0;
1331
    s->restart_count = 0;
1332
    s->mjpb_skiptosod = 0;
1333

    
1334
    init_get_bits(&hgb, buf_ptr, /*buf_size*/(buf_end - buf_ptr)*8);
1335

    
1336
    skip_bits(&hgb, 32); /* reserved zeros */
1337

    
1338
    if (get_bits_long(&hgb, 32) != MKBETAG('m','j','p','g'))
1339
    {
1340
        av_log(avctx, AV_LOG_WARNING, "not mjpeg-b (bad fourcc)\n");
1341
        return 0;
1342
    }
1343

    
1344
    field_size = get_bits_long(&hgb, 32); /* field size */
1345
    av_log(avctx, AV_LOG_DEBUG, "field size: 0x%x\n", field_size);
1346
    skip_bits(&hgb, 32); /* padded field size */
1347
    second_field_offs = get_bits_long(&hgb, 32);
1348
    av_log(avctx, AV_LOG_DEBUG, "second field offs: 0x%x\n", second_field_offs);
1349

    
1350
    dqt_offs = get_bits_long(&hgb, 32);
1351
    av_log(avctx, AV_LOG_DEBUG, "dqt offs: 0x%x\n", dqt_offs);
1352
    if (dqt_offs)
1353
    {
1354
        init_get_bits(&s->gb, buf+dqt_offs, (buf_end - (buf+dqt_offs))*8);
1355
        s->start_code = DQT;
1356
        mjpeg_decode_dqt(s);
1357
    }
1358

    
1359
    dht_offs = get_bits_long(&hgb, 32);
1360
    av_log(avctx, AV_LOG_DEBUG, "dht offs: 0x%x\n", dht_offs);
1361
    if (dht_offs)
1362
    {
1363
        init_get_bits(&s->gb, buf+dht_offs, (buf_end - (buf+dht_offs))*8);
1364
        s->start_code = DHT;
1365
        mjpeg_decode_dht(s);
1366
    }
1367

    
1368
    sof_offs = get_bits_long(&hgb, 32);
1369
    av_log(avctx, AV_LOG_DEBUG, "sof offs: 0x%x\n", sof_offs);
1370
    if (sof_offs)
1371
    {
1372
        init_get_bits(&s->gb, buf+sof_offs, (buf_end - (buf+sof_offs))*8);
1373
        s->start_code = SOF0;
1374
        if (mjpeg_decode_sof(s) < 0)
1375
            return -1;
1376
    }
1377

    
1378
    sos_offs = get_bits_long(&hgb, 32);
1379
    av_log(avctx, AV_LOG_DEBUG, "sos offs: 0x%x\n", sos_offs);
1380
    sod_offs = get_bits_long(&hgb, 32);
1381
    av_log(avctx, AV_LOG_DEBUG, "sod offs: 0x%x\n", sod_offs);
1382
    if (sos_offs)
1383
    {
1384
//        init_get_bits(&s->gb, buf+sos_offs, (buf_end - (buf+sos_offs))*8);
1385
        init_get_bits(&s->gb, buf+sos_offs, field_size*8);
1386
        s->mjpb_skiptosod = (sod_offs - sos_offs - show_bits(&s->gb, 16));
1387
        s->start_code = SOS;
1388
        mjpeg_decode_sos(s);
1389
    }
1390

    
1391
    if (s->interlaced) {
1392
        s->bottom_field ^= 1;
1393
        /* if not bottom field, do not output image yet */
1394
        if (s->bottom_field && second_field_offs)
1395
        {
1396
            buf_ptr = buf + second_field_offs;
1397
            second_field_offs = 0;
1398
            goto read_header;
1399
            }
1400
    }
1401

    
1402
    //XXX FIXME factorize, this looks very similar to the EOI code
1403

    
1404
    *picture= s->picture;
1405
    *data_size = sizeof(AVFrame);
1406

    
1407
    if(!s->lossless){
1408
        picture->quality= FFMAX(FFMAX(s->qscale[0], s->qscale[1]), s->qscale[2]);
1409
        picture->qstride= 0;
1410
        picture->qscale_table= s->qscale_table;
1411
        memset(picture->qscale_table, picture->quality, (s->width+15)/16);
1412
        if(avctx->debug & FF_DEBUG_QP)
1413
            av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
1414
        picture->quality*= FF_QP2LAMBDA;
1415
    }
1416

    
1417
    return buf_ptr - buf;
1418
}
1419

    
1420
#include "sp5x.h"
1421

    
1422
static int sp5x_decode_frame(AVCodecContext *avctx,
1423
                              void *data, int *data_size,
1424
                              uint8_t *buf, int buf_size)
1425
{
1426
#if 0
1427
    MJpegDecodeContext *s = avctx->priv_data;
1428
#endif
1429
    const int qscale = 5;
1430
    uint8_t *buf_ptr, *buf_end, *recoded;
1431
    int i = 0, j = 0;
1432

    
1433
    if (!avctx->width || !avctx->height)
1434
        return -1;
1435

    
1436
    buf_ptr = buf;
1437
    buf_end = buf + buf_size;
1438

    
1439
#if 1
1440
    recoded = av_mallocz(buf_size + 1024);
1441
    if (!recoded)
1442
        return -1;
1443

    
1444
    /* SOI */
1445
    recoded[j++] = 0xFF;
1446
    recoded[j++] = 0xD8;
1447

    
1448
    memcpy(recoded+j, &sp5x_data_dqt[0], sizeof(sp5x_data_dqt));
1449
    memcpy(recoded+j+5, &sp5x_quant_table[qscale * 2], 64);
1450
    memcpy(recoded+j+70, &sp5x_quant_table[(qscale * 2) + 1], 64);
1451
    j += sizeof(sp5x_data_dqt);
1452

    
1453
    memcpy(recoded+j, &sp5x_data_dht[0], sizeof(sp5x_data_dht));
1454
    j += sizeof(sp5x_data_dht);
1455

    
1456
    memcpy(recoded+j, &sp5x_data_sof[0], sizeof(sp5x_data_sof));
1457
    recoded[j+5] = (avctx->coded_height >> 8) & 0xFF;
1458
    recoded[j+6] = avctx->coded_height & 0xFF;
1459
    recoded[j+7] = (avctx->coded_width >> 8) & 0xFF;
1460
    recoded[j+8] = avctx->coded_width & 0xFF;
1461
    j += sizeof(sp5x_data_sof);
1462

    
1463
    memcpy(recoded+j, &sp5x_data_sos[0], sizeof(sp5x_data_sos));
1464
    j += sizeof(sp5x_data_sos);
1465

    
1466
    for (i = 14; i < buf_size && j < buf_size+1024-2; i++)
1467
    {
1468
        recoded[j++] = buf[i];
1469
        if (buf[i] == 0xff)
1470
            recoded[j++] = 0;
1471
    }
1472

    
1473
    /* EOI */
1474
    recoded[j++] = 0xFF;
1475
    recoded[j++] = 0xD9;
1476

    
1477
    i = mjpeg_decode_frame(avctx, data, data_size, recoded, j);
1478

    
1479
    av_free(recoded);
1480

    
1481
#else
1482
    /* SOF */
1483
    s->bits = 8;
1484
    s->width  = avctx->coded_width;
1485
    s->height = avctx->coded_height;
1486
    s->nb_components = 3;
1487
    s->component_id[0] = 0;
1488
    s->h_count[0] = 2;
1489
    s->v_count[0] = 2;
1490
    s->quant_index[0] = 0;
1491
    s->component_id[1] = 1;
1492
    s->h_count[1] = 1;
1493
    s->v_count[1] = 1;
1494
    s->quant_index[1] = 1;
1495
    s->component_id[2] = 2;
1496
    s->h_count[2] = 1;
1497
    s->v_count[2] = 1;
1498
    s->quant_index[2] = 1;
1499
    s->h_max = 2;
1500
    s->v_max = 2;
1501

    
1502
    s->qscale_table = av_mallocz((s->width+15)/16);
1503
    avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV420P : PIX_FMT_YUVJ420;
1504
    s->interlaced = 0;
1505

    
1506
    s->picture.reference = 0;
1507
    if (avctx->get_buffer(avctx, &s->picture) < 0)
1508
    {
1509
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1510
        return -1;
1511
    }
1512

    
1513
    s->picture.pict_type = I_TYPE;
1514
    s->picture.key_frame = 1;
1515

    
1516
    for (i = 0; i < 3; i++)
1517
        s->linesize[i] = s->picture.linesize[i] << s->interlaced;
1518

    
1519
    /* DQT */
1520
    for (i = 0; i < 64; i++)
1521
    {
1522
        j = s->scantable.permutated[i];
1523
        s->quant_matrixes[0][j] = sp5x_quant_table[(qscale * 2) + i];
1524
    }
1525
    s->qscale[0] = FFMAX(
1526
        s->quant_matrixes[0][s->scantable.permutated[1]],
1527
        s->quant_matrixes[0][s->scantable.permutated[8]]) >> 1;
1528

    
1529
    for (i = 0; i < 64; i++)
1530
    {
1531
        j = s->scantable.permutated[i];
1532
        s->quant_matrixes[1][j] = sp5x_quant_table[(qscale * 2) + 1 + i];
1533
    }
1534
    s->qscale[1] = FFMAX(
1535
        s->quant_matrixes[1][s->scantable.permutated[1]],
1536
        s->quant_matrixes[1][s->scantable.permutated[8]]) >> 1;
1537

    
1538
    /* DHT */
1539

    
1540
    /* SOS */
1541
    s->comp_index[0] = 0;
1542
    s->nb_blocks[0] = s->h_count[0] * s->v_count[0];
1543
    s->h_scount[0] = s->h_count[0];
1544
    s->v_scount[0] = s->v_count[0];
1545
    s->dc_index[0] = 0;
1546
    s->ac_index[0] = 0;
1547

    
1548
    s->comp_index[1] = 1;
1549
    s->nb_blocks[1] = s->h_count[1] * s->v_count[1];
1550
    s->h_scount[1] = s->h_count[1];
1551
    s->v_scount[1] = s->v_count[1];
1552
    s->dc_index[1] = 1;
1553
    s->ac_index[1] = 1;
1554

    
1555
    s->comp_index[2] = 2;
1556
    s->nb_blocks[2] = s->h_count[2] * s->v_count[2];
1557
    s->h_scount[2] = s->h_count[2];
1558
    s->v_scount[2] = s->v_count[2];
1559
    s->dc_index[2] = 1;
1560
    s->ac_index[2] = 1;
1561

    
1562
    for (i = 0; i < 3; i++)
1563
        s->last_dc[i] = 1024;
1564

    
1565
    s->mb_width = (s->width * s->h_max * 8 -1) / (s->h_max * 8);
1566
    s->mb_height = (s->height * s->v_max * 8 -1) / (s->v_max * 8);
1567

    
1568
    init_get_bits(&s->gb, buf+14, (buf_size-14)*8);
1569

    
1570
    return mjpeg_decode_scan(s);
1571
#endif
1572

    
1573
    return i;
1574
}
1575

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

    
1581
    av_free(s->buffer);
1582
    av_free(s->qscale_table);
1583

    
1584
    for(i=0;i<2;i++) {
1585
        for(j=0;j<4;j++)
1586
            free_vlc(&s->vlcs[i][j]);
1587
    }
1588
    return 0;
1589
}
1590

    
1591
static int mjpega_dump_header(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args,
1592
                              uint8_t **poutbuf, int *poutbuf_size,
1593
                              const uint8_t *buf, int buf_size, int keyframe)
1594
{
1595
    uint8_t *poutbufp;
1596
    int i;
1597

    
1598
    if (avctx->codec_id != CODEC_ID_MJPEG) {
1599
        av_log(avctx, AV_LOG_ERROR, "mjpega bitstream filter only applies to mjpeg codec\n");
1600
        return 0;
1601
    }
1602

    
1603
    *poutbuf_size = 0;
1604
    *poutbuf = av_malloc(buf_size + 44 + FF_INPUT_BUFFER_PADDING_SIZE);
1605
    poutbufp = *poutbuf;
1606
    bytestream_put_byte(&poutbufp, 0xff);
1607
    bytestream_put_byte(&poutbufp, SOI);
1608
    bytestream_put_byte(&poutbufp, 0xff);
1609
    bytestream_put_byte(&poutbufp, APP1);
1610
    bytestream_put_be16(&poutbufp, 42); /* size */
1611
    bytestream_put_be32(&poutbufp, 0);
1612
    bytestream_put_buffer(&poutbufp, "mjpg", 4);
1613
    bytestream_put_be32(&poutbufp, buf_size + 44); /* field size */
1614
    bytestream_put_be32(&poutbufp, buf_size + 44); /* pad field size */
1615
    bytestream_put_be32(&poutbufp, 0);             /* next ptr */
1616

    
1617
    for (i = 0; i < buf_size - 1; i++) {
1618
        if (buf[i] == 0xff) {
1619
            switch (buf[i + 1]) {
1620
            case DQT:  /* quant off */
1621
            case DHT:  /* huff  off */
1622
            case SOF0: /* image off */
1623
                bytestream_put_be32(&poutbufp, i + 46);
1624
                break;
1625
            case SOS:
1626
                bytestream_put_be32(&poutbufp, i + 46); /* scan off */
1627
                bytestream_put_be32(&poutbufp, i + 46 + AV_RB16(buf + i + 2)); /* data off */
1628
                bytestream_put_buffer(&poutbufp, buf + 2, buf_size - 2); /* skip already written SOI */
1629
                *poutbuf_size = poutbufp - *poutbuf;
1630
                return 1;
1631
            case APP1:
1632
                if (i + 8 < buf_size && AV_RL32(buf + i + 8) == ff_get_fourcc("mjpg")) {
1633
                    av_log(avctx, AV_LOG_ERROR, "bitstream already formatted\n");
1634
                    memcpy(*poutbuf, buf, buf_size);
1635
                    *poutbuf_size = buf_size;
1636
                    return 1;
1637
                }
1638
            }
1639
        }
1640
    }
1641
    av_freep(poutbuf);
1642
    av_log(avctx, AV_LOG_ERROR, "could not find SOS marker in bitstream\n");
1643
    return 0;
1644
}
1645

    
1646
AVCodec mjpeg_decoder = {
1647
    "mjpeg",
1648
    CODEC_TYPE_VIDEO,
1649
    CODEC_ID_MJPEG,
1650
    sizeof(MJpegDecodeContext),
1651
    mjpeg_decode_init,
1652
    NULL,
1653
    mjpeg_decode_end,
1654
    mjpeg_decode_frame,
1655
    CODEC_CAP_DR1,
1656
    NULL
1657
};
1658

    
1659
AVCodec thp_decoder = {
1660
    "thp",
1661
    CODEC_TYPE_VIDEO,
1662
    CODEC_ID_THP,
1663
    sizeof(MJpegDecodeContext),
1664
    mjpeg_decode_init,
1665
    NULL,
1666
    mjpeg_decode_end,
1667
    mjpeg_decode_frame,
1668
    CODEC_CAP_DR1,
1669
    NULL
1670
};
1671

    
1672
AVCodec mjpegb_decoder = {
1673
    "mjpegb",
1674
    CODEC_TYPE_VIDEO,
1675
    CODEC_ID_MJPEGB,
1676
    sizeof(MJpegDecodeContext),
1677
    mjpeg_decode_init,
1678
    NULL,
1679
    mjpeg_decode_end,
1680
    mjpegb_decode_frame,
1681
    CODEC_CAP_DR1,
1682
    NULL
1683
};
1684

    
1685
AVCodec sp5x_decoder = {
1686
    "sp5x",
1687
    CODEC_TYPE_VIDEO,
1688
    CODEC_ID_SP5X,
1689
    sizeof(MJpegDecodeContext),
1690
    mjpeg_decode_init,
1691
    NULL,
1692
    mjpeg_decode_end,
1693
    sp5x_decode_frame,
1694
    CODEC_CAP_DR1,
1695
    NULL
1696
};
1697

    
1698
#ifdef CONFIG_MJPEGA_DUMP_HEADER_BSF
1699
AVBitStreamFilter mjpega_dump_header_bsf = {
1700
    "mjpegadump",
1701
    0,
1702
    mjpega_dump_header,
1703
};
1704
#endif