Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mjpeg.c @ 983e3246

History | View | Annotate | Download (47.5 KB)

1
/*
2
 * MJPEG encoder and decoder
3
 * Copyright (c) 2000, 2001 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 *
19
 * Support for external huffman table, various fixes (AVID workaround),
20
 * aspecting, new decode_frame mechanism and apple mjpeg-b support
21
 *                                  by Alex Beregszaszi <alex@naxine.org>
22
 */
23

    
24
/**
25
 * @file mjpeg.c
26
 * MJPEG encoder and decoder.
27
 */
28
 
29
//#define DEBUG
30
#include "avcodec.h"
31
#include "dsputil.h"
32
#include "mpegvideo.h"
33

    
34
/* use two quantizer tables (one for luminance and one for chrominance) */
35
/* not yet working */
36
#undef TWOMATRIXES
37

    
38
typedef struct MJpegContext {
39
    uint8_t huff_size_dc_luminance[12];
40
    uint16_t huff_code_dc_luminance[12];
41
    uint8_t huff_size_dc_chrominance[12];
42
    uint16_t huff_code_dc_chrominance[12];
43

    
44
    uint8_t huff_size_ac_luminance[256];
45
    uint16_t huff_code_ac_luminance[256];
46
    uint8_t huff_size_ac_chrominance[256];
47
    uint16_t huff_code_ac_chrominance[256];
48
} MJpegContext;
49

    
50
/* JPEG marker codes */
51
typedef enum {
52
    /* start of frame */
53
    SOF0  = 0xc0,        /* baseline */
54
    SOF1  = 0xc1,        /* extended sequential, huffman */
55
    SOF2  = 0xc2,        /* progressive, huffman */
56
    SOF3  = 0xc3,        /* lossless, huffman */
57

    
58
    SOF5  = 0xc5,        /* differential sequential, huffman */
59
    SOF6  = 0xc6,        /* differential progressive, huffman */
60
    SOF7  = 0xc7,        /* differential lossless, huffman */
61
    JPG   = 0xc8,        /* reserved for JPEG extension */
62
    SOF9  = 0xc9,        /* extended sequential, arithmetic */
63
    SOF10 = 0xca,        /* progressive, arithmetic */
64
    SOF11 = 0xcb,        /* lossless, arithmetic */
65

    
66
    SOF13 = 0xcd,        /* differential sequential, arithmetic */
67
    SOF14 = 0xce,        /* differential progressive, arithmetic */
68
    SOF15 = 0xcf,        /* differential lossless, arithmetic */
69

    
70
    DHT   = 0xc4,        /* define huffman tables */
71

    
72
    DAC   = 0xcc,        /* define arithmetic-coding conditioning */
73

    
74
    /* restart with modulo 8 count "m" */
75
    RST0  = 0xd0,
76
    RST1  = 0xd1,
77
    RST2  = 0xd2,
78
    RST3  = 0xd3,
79
    RST4  = 0xd4,
80
    RST5  = 0xd5,
81
    RST6  = 0xd6,
82
    RST7  = 0xd7,
83

    
84
    SOI   = 0xd8,        /* start of image */
85
    EOI   = 0xd9,        /* end of image */
86
    SOS   = 0xda,        /* start of scan */
87
    DQT   = 0xdb,        /* define quantization tables */
88
    DNL   = 0xdc,        /* define number of lines */
89
    DRI   = 0xdd,        /* define restart interval */
90
    DHP   = 0xde,        /* define hierarchical progression */
91
    EXP   = 0xdf,        /* expand reference components */
92

    
93
    APP0  = 0xe0,
94
    APP1  = 0xe1,
95
    APP2  = 0xe2,
96
    APP3  = 0xe3,
97
    APP4  = 0xe4,
98
    APP5  = 0xe5,
99
    APP6  = 0xe6,
100
    APP7  = 0xe7,
101
    APP8  = 0xe8,
102
    APP9  = 0xe9,
103
    APP10 = 0xea,
104
    APP11 = 0xeb,
105
    APP12 = 0xec,
106
    APP13 = 0xed,
107
    APP14 = 0xee,
108
    APP15 = 0xef,
109

    
110
    JPG0  = 0xf0,
111
    JPG1  = 0xf1,
112
    JPG2  = 0xf2,
113
    JPG3  = 0xf3,
114
    JPG4  = 0xf4,
115
    JPG5  = 0xf5,
116
    JPG6  = 0xf6,
117
    JPG7  = 0xf7,
118
    JPG8  = 0xf8,
119
    JPG9  = 0xf9,
120
    JPG10 = 0xfa,
121
    JPG11 = 0xfb,
122
    JPG12 = 0xfc,
123
    JPG13 = 0xfd,
124

    
125
    COM   = 0xfe,        /* comment */
126

    
127
    TEM   = 0x01,        /* temporary private use for arithmetic coding */
128

    
129
    /* 0x02 -> 0xbf reserved */
130
} JPEG_MARKER;
131

    
132
#if 0
133
/* These are the sample quantization tables given in JPEG spec section K.1.
134
 * The spec says that the values given produce "good" quality, and
135
 * when divided by 2, "very good" quality.
136
 */
137
static const unsigned char std_luminance_quant_tbl[64] = {
138
    16,  11,  10,  16,  24,  40,  51,  61,
139
    12,  12,  14,  19,  26,  58,  60,  55,
140
    14,  13,  16,  24,  40,  57,  69,  56,
141
    14,  17,  22,  29,  51,  87,  80,  62,
142
    18,  22,  37,  56,  68, 109, 103,  77,
143
    24,  35,  55,  64,  81, 104, 113,  92,
144
    49,  64,  78,  87, 103, 121, 120, 101,
145
    72,  92,  95,  98, 112, 100, 103,  99
146
};
147
static const unsigned char std_chrominance_quant_tbl[64] = {
148
    17,  18,  24,  47,  99,  99,  99,  99,
149
    18,  21,  26,  66,  99,  99,  99,  99,
150
    24,  26,  56,  99,  99,  99,  99,  99,
151
    47,  66,  99,  99,  99,  99,  99,  99,
152
    99,  99,  99,  99,  99,  99,  99,  99,
153
    99,  99,  99,  99,  99,  99,  99,  99,
154
    99,  99,  99,  99,  99,  99,  99,  99,
155
    99,  99,  99,  99,  99,  99,  99,  99
156
};
157
#endif
158

    
159
/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
160
/* IMPORTANT: these are only valid for 8-bit data precision! */
161
static const uint8_t bits_dc_luminance[17] =
162
{ /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
163
static const uint8_t val_dc_luminance[] =
164
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
165

    
166
static const uint8_t bits_dc_chrominance[17] =
167
{ /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
168
static const uint8_t val_dc_chrominance[] =
169
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
170

    
171
static const uint8_t bits_ac_luminance[17] =
172
{ /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
173
static const uint8_t val_ac_luminance[] =
174
{ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
175
  0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
176
  0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
177
  0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
178
  0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
179
  0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
180
  0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
181
  0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
182
  0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
183
  0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
184
  0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
185
  0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
186
  0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
187
  0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
188
  0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
189
  0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
190
  0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
191
  0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
192
  0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
193
  0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
194
  0xf9, 0xfa 
195
};
196

    
197
static const uint8_t bits_ac_chrominance[17] =
198
{ /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
199

    
200
static const uint8_t val_ac_chrominance[] =
201
{ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
202
  0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
203
  0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
204
  0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
205
  0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
206
  0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
207
  0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
208
  0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
209
  0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
210
  0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
211
  0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
212
  0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
213
  0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
214
  0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
215
  0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
216
  0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
217
  0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
218
  0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
219
  0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
220
  0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
221
  0xf9, 0xfa 
222
};
223

    
224
/* isn't this function nicer than the one in the libjpeg ? */
225
static void build_huffman_codes(uint8_t *huff_size, uint16_t *huff_code,
226
                                const uint8_t *bits_table, const uint8_t *val_table)
227
{
228
    int i, j, k,nb, code, sym;
229

    
230
    code = 0;
231
    k = 0;
232
    for(i=1;i<=16;i++) {
233
        nb = bits_table[i];
234
        for(j=0;j<nb;j++) {
235
            sym = val_table[k++];
236
            huff_size[sym] = i;
237
            huff_code[sym] = code;
238
            code++;
239
        }
240
        code <<= 1;
241
    }
242
}
243

    
244
int mjpeg_init(MpegEncContext *s)
245
{
246
    MJpegContext *m;
247
    
248
    m = av_malloc(sizeof(MJpegContext));
249
    if (!m)
250
        return -1;
251
    
252
    s->min_qcoeff=-1023;
253
    s->max_qcoeff= 1023;
254
    s->intra_quant_bias= 1<<(QUANT_BIAS_SHIFT-1); //(a + x/2)/x
255

    
256
    /* build all the huffman tables */
257
    build_huffman_codes(m->huff_size_dc_luminance,
258
                        m->huff_code_dc_luminance,
259
                        bits_dc_luminance,
260
                        val_dc_luminance);
261
    build_huffman_codes(m->huff_size_dc_chrominance,
262
                        m->huff_code_dc_chrominance,
263
                        bits_dc_chrominance,
264
                        val_dc_chrominance);
265
    build_huffman_codes(m->huff_size_ac_luminance,
266
                        m->huff_code_ac_luminance,
267
                        bits_ac_luminance,
268
                        val_ac_luminance);
269
    build_huffman_codes(m->huff_size_ac_chrominance,
270
                        m->huff_code_ac_chrominance,
271
                        bits_ac_chrominance,
272
                        val_ac_chrominance);
273
    
274
    s->mjpeg_ctx = m;
275
    return 0;
276
}
277

    
278
void mjpeg_close(MpegEncContext *s)
279
{
280
    av_free(s->mjpeg_ctx);
281
}
282

    
283
static inline void put_marker(PutBitContext *p, int code)
284
{
285
    put_bits(p, 8, 0xff);
286
    put_bits(p, 8, code);
287
}
288

    
289
/* table_class: 0 = DC coef, 1 = AC coefs */
290
static int put_huffman_table(MpegEncContext *s, int table_class, int table_id,
291
                             const uint8_t *bits_table, const uint8_t *value_table)
292
{
293
    PutBitContext *p = &s->pb;
294
    int n, i;
295

    
296
    put_bits(p, 4, table_class);
297
    put_bits(p, 4, table_id);
298

    
299
    n = 0;
300
    for(i=1;i<=16;i++) {
301
        n += bits_table[i];
302
        put_bits(p, 8, bits_table[i]);
303
    }
304

    
305
    for(i=0;i<n;i++)
306
        put_bits(p, 8, value_table[i]);
307

    
308
    return n + 17;
309
}
310

    
311
static void jpeg_table_header(MpegEncContext *s)
312
{
313
    PutBitContext *p = &s->pb;
314
    int i, j, size;
315
    uint8_t *ptr;
316

    
317
    /* quant matrixes */
318
    put_marker(p, DQT);
319
#ifdef TWOMATRIXES
320
    put_bits(p, 16, 2 + 2 * (1 + 64));
321
#else
322
    put_bits(p, 16, 2 + 1 * (1 + 64));
323
#endif
324
    put_bits(p, 4, 0); /* 8 bit precision */
325
    put_bits(p, 4, 0); /* table 0 */
326
    for(i=0;i<64;i++) {
327
        j = s->intra_scantable.permutated[i];
328
        put_bits(p, 8, s->intra_matrix[j]);
329
    }
330
#ifdef TWOMATRIXES
331
    put_bits(p, 4, 0); /* 8 bit precision */
332
    put_bits(p, 4, 1); /* table 1 */
333
    for(i=0;i<64;i++) {
334
        j = s->intra_scantable.permutated[i];
335
        put_bits(p, 8, s->chroma_intra_matrix[j]);
336
    }
337
#endif
338

    
339
    /* huffman table */
340
    put_marker(p, DHT);
341
    flush_put_bits(p);
342
    ptr = pbBufPtr(p);
343
    put_bits(p, 16, 0); /* patched later */
344
    size = 2;
345
    size += put_huffman_table(s, 0, 0, bits_dc_luminance, val_dc_luminance);
346
    size += put_huffman_table(s, 0, 1, bits_dc_chrominance, val_dc_chrominance);
347
    
348
    size += put_huffman_table(s, 1, 0, bits_ac_luminance, val_ac_luminance);
349
    size += put_huffman_table(s, 1, 1, bits_ac_chrominance, val_ac_chrominance);
350
    ptr[0] = size >> 8;
351
    ptr[1] = size;
352
}
353

    
354
static void jpeg_put_comments(MpegEncContext *s)
355
{
356
    PutBitContext *p = &s->pb;
357
    int size;
358
    uint8_t *ptr;
359

    
360
    if (s->aspect_ratio_info)
361
    {
362
    /* JFIF header */
363
    put_marker(p, APP0);
364
    put_bits(p, 16, 16);
365
    put_string(p, "JFIF"); /* this puts the trailing zero-byte too */
366
    put_bits(p, 16, 0x0201); /* v 1.02 */
367
    put_bits(p, 8, 0); /* units type: 0 - aspect ratio */
368
    switch(s->aspect_ratio_info)
369
    {
370
        case FF_ASPECT_4_3_625:
371
        case FF_ASPECT_4_3_525:
372
            put_bits(p, 16, 4); 
373
            put_bits(p, 16, 3);
374
            break;
375
        case FF_ASPECT_16_9_625:
376
        case FF_ASPECT_16_9_525:
377
            put_bits(p, 16, 16); 
378
            put_bits(p, 16, 9);
379
            break;
380
        case FF_ASPECT_EXTENDED:
381
            put_bits(p, 16, s->aspected_width);
382
            put_bits(p, 16, s->aspected_height);
383
            break;
384
        case FF_ASPECT_SQUARE:
385
        default:
386
            put_bits(p, 16, 1); /* aspect: 1:1 */
387
            put_bits(p, 16, 1);
388
            break;
389
    }
390
    put_bits(p, 8, 0); /* thumbnail width */
391
    put_bits(p, 8, 0); /* thumbnail height */
392
    }
393

    
394
    /* comment */
395
    if(!(s->flags & CODEC_FLAG_BITEXACT)){
396
        put_marker(p, COM);
397
        flush_put_bits(p);
398
        ptr = pbBufPtr(p);
399
        put_bits(p, 16, 0); /* patched later */
400
#define MJPEG_VERSION "FFmpeg" LIBAVCODEC_VERSION "b" LIBAVCODEC_BUILD_STR
401
        put_string(p, MJPEG_VERSION);
402
        size = strlen(MJPEG_VERSION)+3;
403
#undef MJPEG_VERSION
404
        ptr[0] = size >> 8;
405
        ptr[1] = size;
406
    }
407
}
408

    
409
void mjpeg_picture_header(MpegEncContext *s)
410
{
411
    put_marker(&s->pb, SOI);
412

    
413
    if (!s->mjpeg_data_only_frames)
414
    {
415
    jpeg_put_comments(s);    
416

    
417
    if (s->mjpeg_write_tables) jpeg_table_header(s);
418

    
419
    put_marker(&s->pb, SOF0);
420

    
421
    put_bits(&s->pb, 16, 17);
422
    put_bits(&s->pb, 8, 8); /* 8 bits/component */
423
    put_bits(&s->pb, 16, s->height);
424
    put_bits(&s->pb, 16, s->width);
425
    put_bits(&s->pb, 8, 3); /* 3 components */
426
    
427
    /* Y component */
428
    put_bits(&s->pb, 8, 1); /* component number */
429
    put_bits(&s->pb, 4, s->mjpeg_hsample[0]); /* H factor */
430
    put_bits(&s->pb, 4, s->mjpeg_vsample[0]); /* V factor */
431
    put_bits(&s->pb, 8, 0); /* select matrix */
432
    
433
    /* Cb component */
434
    put_bits(&s->pb, 8, 2); /* component number */
435
    put_bits(&s->pb, 4, s->mjpeg_hsample[1]); /* H factor */
436
    put_bits(&s->pb, 4, s->mjpeg_vsample[1]); /* V factor */
437
#ifdef TWOMATRIXES
438
    put_bits(&s->pb, 8, 1); /* select matrix */
439
#else
440
    put_bits(&s->pb, 8, 0); /* select matrix */
441
#endif
442

    
443
    /* Cr component */
444
    put_bits(&s->pb, 8, 3); /* component number */
445
    put_bits(&s->pb, 4, s->mjpeg_hsample[2]); /* H factor */
446
    put_bits(&s->pb, 4, s->mjpeg_vsample[2]); /* V factor */
447
#ifdef TWOMATRIXES
448
    put_bits(&s->pb, 8, 1); /* select matrix */
449
#else
450
    put_bits(&s->pb, 8, 0); /* select matrix */
451
#endif
452
    }
453

    
454
    /* scan header */
455
    put_marker(&s->pb, SOS);
456
    put_bits(&s->pb, 16, 12); /* length */
457
    put_bits(&s->pb, 8, 3); /* 3 components */
458
    
459
    /* Y component */
460
    put_bits(&s->pb, 8, 1); /* index */
461
    put_bits(&s->pb, 4, 0); /* DC huffman table index */
462
    put_bits(&s->pb, 4, 0); /* AC huffman table index */
463
    
464
    /* Cb component */
465
    put_bits(&s->pb, 8, 2); /* index */
466
    put_bits(&s->pb, 4, 1); /* DC huffman table index */
467
    put_bits(&s->pb, 4, 1); /* AC huffman table index */
468
    
469
    /* Cr component */
470
    put_bits(&s->pb, 8, 3); /* index */
471
    put_bits(&s->pb, 4, 1); /* DC huffman table index */
472
    put_bits(&s->pb, 4, 1); /* AC huffman table index */
473

    
474
    put_bits(&s->pb, 8, 0); /* Ss (not used) */
475
    put_bits(&s->pb, 8, 63); /* Se (not used) */
476
    put_bits(&s->pb, 8, 0); /* Ah/Al (not used) */
477
}
478

    
479
static void escape_FF(MpegEncContext *s, int start)
480
{
481
    int size= get_bit_count(&s->pb) - start*8;
482
    int i, ff_count;
483
    uint8_t *buf= s->pb.buf + start;
484
    int align= (-(int)(buf))&3;
485
    
486
    assert((size&7) == 0);
487
    size >>= 3;
488
    
489
    ff_count=0;
490
    for(i=0; i<size && i<align; i++){
491
        if(buf[i]==0xFF) ff_count++;
492
    }
493
    for(; i<size-15; i+=16){
494
        int acc, v;
495

    
496
        v= *(uint32_t*)(&buf[i]);
497
        acc= (((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
498
        v= *(uint32_t*)(&buf[i+4]);
499
        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
500
        v= *(uint32_t*)(&buf[i+8]);
501
        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
502
        v= *(uint32_t*)(&buf[i+12]);
503
        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
504

    
505
        acc>>=4;
506
        acc+= (acc>>16);
507
        acc+= (acc>>8);
508
        ff_count+= acc&0xFF;
509
    }
510
    for(; i<size; i++){
511
        if(buf[i]==0xFF) ff_count++;
512
    }
513

    
514
    if(ff_count==0) return;
515
    
516
    /* skip put bits */
517
    for(i=0; i<ff_count-3; i+=4)
518
        put_bits(&s->pb, 32, 0);
519
    put_bits(&s->pb, (ff_count-i)*8, 0);
520
    flush_put_bits(&s->pb); 
521

    
522
    for(i=size-1; ff_count; i--){
523
        int v= buf[i];
524

    
525
        if(v==0xFF){
526
//printf("%d %d\n", i, ff_count);
527
            buf[i+ff_count]= 0;
528
            ff_count--;
529
        }
530

    
531
        buf[i+ff_count]= v;
532
    }
533
}
534

    
535
void mjpeg_picture_trailer(MpegEncContext *s)
536
{
537
    int pad= (-get_bit_count(&s->pb))&7;
538
    
539
    put_bits(&s->pb, pad,0xFF>>(8-pad));
540
    flush_put_bits(&s->pb);
541

    
542
    assert((s->header_bits&7)==0);
543
    
544
    escape_FF(s, s->header_bits>>3);
545

    
546
    put_marker(&s->pb, EOI);
547
}
548

    
549
static inline void mjpeg_encode_dc(MpegEncContext *s, int val,
550
                                   uint8_t *huff_size, uint16_t *huff_code)
551
{
552
    int mant, nbits;
553

    
554
    if (val == 0) {
555
        put_bits(&s->pb, huff_size[0], huff_code[0]);
556
    } else {
557
        mant = val;
558
        if (val < 0) {
559
            val = -val;
560
            mant--;
561
        }
562
        
563
        /* compute the log (XXX: optimize) */
564
        nbits = 0;
565
        while (val != 0) {
566
            val = val >> 1;
567
            nbits++;
568
        }
569
            
570
        put_bits(&s->pb, huff_size[nbits], huff_code[nbits]);
571
        
572
        put_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
573
    }
574
}
575

    
576
static void encode_block(MpegEncContext *s, DCTELEM *block, int n)
577
{
578
    int mant, nbits, code, i, j;
579
    int component, dc, run, last_index, val;
580
    MJpegContext *m = s->mjpeg_ctx;
581
    uint8_t *huff_size_ac;
582
    uint16_t *huff_code_ac;
583
    
584
    /* DC coef */
585
    component = (n <= 3 ? 0 : n - 4 + 1);
586
    dc = block[0]; /* overflow is impossible */
587
    val = dc - s->last_dc[component];
588
    if (n < 4) {
589
        mjpeg_encode_dc(s, val, m->huff_size_dc_luminance, m->huff_code_dc_luminance);
590
        huff_size_ac = m->huff_size_ac_luminance;
591
        huff_code_ac = m->huff_code_ac_luminance;
592
    } else {
593
        mjpeg_encode_dc(s, val, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);
594
        huff_size_ac = m->huff_size_ac_chrominance;
595
        huff_code_ac = m->huff_code_ac_chrominance;
596
    }
597
    s->last_dc[component] = dc;
598
    
599
    /* AC coefs */
600
    
601
    run = 0;
602
    last_index = s->block_last_index[n];
603
    for(i=1;i<=last_index;i++) {
604
        j = s->intra_scantable.permutated[i];
605
        val = block[j];
606
        if (val == 0) {
607
            run++;
608
        } else {
609
            while (run >= 16) {
610
                put_bits(&s->pb, huff_size_ac[0xf0], huff_code_ac[0xf0]);
611
                run -= 16;
612
            }
613
            mant = val;
614
            if (val < 0) {
615
                val = -val;
616
                mant--;
617
            }
618
            
619
            /* compute the log (XXX: optimize) */
620
            nbits = 0;
621
            while (val != 0) {
622
                val = val >> 1;
623
                nbits++;
624
            }
625
            code = (run << 4) | nbits;
626

    
627
            put_bits(&s->pb, huff_size_ac[code], huff_code_ac[code]);
628
        
629
            put_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
630
            run = 0;
631
        }
632
    }
633

    
634
    /* output EOB only if not already 64 values */
635
    if (last_index < 63 || run != 0)
636
        put_bits(&s->pb, huff_size_ac[0], huff_code_ac[0]);
637
}
638

    
639
void mjpeg_encode_mb(MpegEncContext *s, 
640
                     DCTELEM block[6][64])
641
{
642
    int i;
643
    for(i=0;i<6;i++) {
644
        encode_block(s, block[i], i);
645
    }
646
}
647

    
648
/******************************************/
649
/* decoding */
650

    
651
#define MAX_COMPONENTS 4
652

    
653
typedef struct MJpegDecodeContext {
654
    AVCodecContext *avctx;
655
    GetBitContext gb;
656
    int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
657

    
658
    int start_code; /* current start code */
659
    int buffer_size;
660
    uint8_t *buffer;
661

    
662
    int16_t quant_matrixes[4][64];
663
    VLC vlcs[2][4];
664

    
665
    int org_width, org_height;  /* size given at codec init */
666
    int first_picture;    /* true if decoding first picture */
667
    int interlaced;     /* true if interlaced */
668
    int bottom_field;   /* true if bottom field */
669

    
670
    int width, height;
671
    int nb_components;
672
    int component_id[MAX_COMPONENTS];
673
    int h_count[MAX_COMPONENTS]; /* horizontal and vertical count for each component */
674
    int v_count[MAX_COMPONENTS];
675
    int h_max, v_max; /* maximum h and v counts */
676
    int quant_index[4];   /* quant table index for each component */
677
    int last_dc[MAX_COMPONENTS]; /* last DEQUANTIZED dc (XXX: am I right to do that ?) */
678
    uint8_t *current_picture[MAX_COMPONENTS]; /* picture structure */
679
    int linesize[MAX_COMPONENTS];
680
    DCTELEM block[64] __align8;
681
    ScanTable scantable;
682
    void (*idct_put)(uint8_t *dest/*align 8*/, int line_size, DCTELEM *block/*align 16*/);
683

    
684
    int restart_interval;
685
    int restart_count;
686

    
687
    int buggy_avid;
688
    int interlace_polarity;
689
} MJpegDecodeContext;
690

    
691
static int mjpeg_decode_dht(MJpegDecodeContext *s);
692

    
693
static void build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table, 
694
                      int nb_codes)
695
{
696
    uint8_t huff_size[256];
697
    uint16_t huff_code[256];
698

    
699
    memset(huff_size, 0, sizeof(huff_size));
700
    build_huffman_codes(huff_size, huff_code, bits_table, val_table);
701
    
702
    init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2);
703
}
704

    
705
static int mjpeg_decode_init(AVCodecContext *avctx)
706
{
707
    MJpegDecodeContext *s = avctx->priv_data;
708
    MpegEncContext s2;
709

    
710
    s->avctx = avctx;
711

    
712
    /* ugly way to get the idct & scantable FIXME */
713
    memset(&s2, 0, sizeof(MpegEncContext));
714
    s2.flags= avctx->flags;
715
    s2.avctx= avctx;
716
//    s2->out_format = FMT_MJPEG;
717
    s2.width = 8;
718
    s2.height = 8;
719
    if (MPV_common_init(&s2) < 0)
720
       return -1;
721
    s->scantable= s2.intra_scantable;
722
    s->idct_put= s2.dsp.idct_put;
723
    MPV_common_end(&s2);
724

    
725
    s->mpeg_enc_ctx_allocated = 0;
726
    s->buffer_size = 102400; /* smaller buffer should be enough,
727
                                but photojpg files could ahive bigger sizes */
728
    s->buffer = av_malloc(s->buffer_size);
729
    if (!s->buffer)
730
        return -1;
731
    s->start_code = -1;
732
    s->first_picture = 1;
733
    s->org_width = avctx->width;
734
    s->org_height = avctx->height;
735
    
736
    build_vlc(&s->vlcs[0][0], bits_dc_luminance, val_dc_luminance, 12);
737
    build_vlc(&s->vlcs[0][1], bits_dc_chrominance, val_dc_chrominance, 12);
738
    build_vlc(&s->vlcs[1][0], bits_ac_luminance, val_ac_luminance, 251);
739
    build_vlc(&s->vlcs[1][1], bits_ac_chrominance, val_ac_chrominance, 251);
740

    
741
    if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)
742
    {
743
        printf("mjpeg: using external huffman table\n");
744
        init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
745
        mjpeg_decode_dht(s);
746
        /* should check for error - but dunno */
747
    }
748

    
749
    return 0;
750
}
751

    
752
/* quantize tables */
753
static int mjpeg_decode_dqt(MJpegDecodeContext *s)
754
{
755
    int len, index, i, j;
756
    
757
    len = get_bits(&s->gb, 16) - 2;
758

    
759
    while (len >= 65) {
760
        /* only 8 bit precision handled */
761
        if (get_bits(&s->gb, 4) != 0)
762
        {
763
            dprintf("dqt: 16bit precision\n");
764
            return -1;
765
        }
766
        index = get_bits(&s->gb, 4);
767
        if (index >= 4)
768
            return -1;
769
        dprintf("index=%d\n", index);
770
        /* read quant table */
771
        for(i=0;i<64;i++) {
772
            j = s->scantable.permutated[i];
773
            s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
774
        }
775
        len -= 65;
776
    }
777
    
778
    return 0;
779
}
780

    
781
/* decode huffman tables and build VLC decoders */
782
static int mjpeg_decode_dht(MJpegDecodeContext *s)
783
{
784
    int len, index, i, class, n, v, code_max;
785
    uint8_t bits_table[17];
786
    uint8_t val_table[256];
787
    
788
    len = get_bits(&s->gb, 16) - 2;
789

    
790
    while (len > 0) {
791
        if (len < 17)
792
            return -1;
793
        class = get_bits(&s->gb, 4);
794
        if (class >= 2)
795
            return -1;
796
        index = get_bits(&s->gb, 4);
797
        if (index >= 4)
798
            return -1;
799
        n = 0;
800
        for(i=1;i<=16;i++) {
801
            bits_table[i] = get_bits(&s->gb, 8);
802
            n += bits_table[i];
803
        }
804
        len -= 17;
805
        if (len < n || n > 256)
806
            return -1;
807

    
808
        code_max = 0;
809
        for(i=0;i<n;i++) {
810
            v = get_bits(&s->gb, 8);
811
            if (v > code_max)
812
                code_max = v;
813
            val_table[i] = v;
814
        }
815
        len -= n;
816

    
817
        /* build VLC and flush previous vlc if present */
818
        free_vlc(&s->vlcs[class][index]);
819
        dprintf("class=%d index=%d nb_codes=%d\n",
820
               class, index, code_max + 1);
821
        build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1);
822
    }
823
    return 0;
824
}
825

    
826
static int mjpeg_decode_sof0(MJpegDecodeContext *s)
827
{
828
    int len, nb_components, i, width, height;
829

    
830
    /* XXX: verify len field validity */
831
    len = get_bits(&s->gb, 16);
832
    /* only 8 bits/component accepted */
833
    if (get_bits(&s->gb, 8) != 8)
834
        return -1;
835
    height = get_bits(&s->gb, 16);
836
    width = get_bits(&s->gb, 16);
837
    dprintf("sof0: picture: %dx%d\n", width, height);
838

    
839
    nb_components = get_bits(&s->gb, 8);
840
    if (nb_components <= 0 ||
841
        nb_components > MAX_COMPONENTS)
842
        return -1;
843
    s->nb_components = nb_components;
844
    s->h_max = 1;
845
    s->v_max = 1;
846
    for(i=0;i<nb_components;i++) {
847
        /* component id */
848
        s->component_id[i] = get_bits(&s->gb, 8) - 1;
849
        s->h_count[i] = get_bits(&s->gb, 4);
850
        s->v_count[i] = get_bits(&s->gb, 4);
851
        /* compute hmax and vmax (only used in interleaved case) */
852
        if (s->h_count[i] > s->h_max)
853
            s->h_max = s->h_count[i];
854
        if (s->v_count[i] > s->v_max)
855
            s->v_max = s->v_count[i];
856
        s->quant_index[i] = get_bits(&s->gb, 8);
857
        if (s->quant_index[i] >= 4)
858
            return -1;
859
        dprintf("component %d %d:%d id: %d quant:%d\n", i, s->h_count[i],
860
            s->v_count[i], s->component_id[i], s->quant_index[i]);
861
    }
862

    
863
    /* if different size, realloc/alloc picture */
864
    /* XXX: also check h_count and v_count */
865
    if (width != s->width || height != s->height) {
866
        for(i=0;i<MAX_COMPONENTS;i++)
867
            av_freep(&s->current_picture[i]);
868
        s->width = width;
869
        s->height = height;
870
        /* test interlaced mode */
871
        if (s->first_picture &&
872
            s->org_height != 0 &&
873
            s->height < ((s->org_height * 3) / 4)) {
874
            s->interlaced = 1;
875
//            s->bottom_field = (s->interlace_polarity) ? 1 : 0;
876
            s->bottom_field = 0;
877
        }
878

    
879
        for(i=0;i<nb_components;i++) {
880
            int w, h;
881
            w = (s->width  + 8 * s->h_max - 1) / (8 * s->h_max);
882
            h = (s->height + 8 * s->v_max - 1) / (8 * s->v_max);
883
            w = w * 8 * s->h_count[i];
884
            h = h * 8 * s->v_count[i];
885
            if (s->interlaced)
886
                w *= 2;
887
            s->linesize[i] = w;
888
            s->current_picture[i] = av_mallocz(w * h);
889
            if (!s->current_picture[i])
890
            {
891
                dprintf("error: no picture buffers allocated\n");
892
                return -1;
893
            }
894
        }
895
        s->first_picture = 0;
896
    }
897

    
898
    if (len != (8+(3*nb_components)))
899
    {
900
        dprintf("decode_sof0: error, len(%d) mismatch\n", len);
901
    }
902
    
903
    return 0;
904
}
905

    
906
static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
907
{
908
    int code, diff;
909
#if 1
910
    code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
911
#else
912
    code = get_vlc(&s->gb, &s->vlcs[0][dc_index]);
913
#endif
914
    if (code < 0)
915
    {
916
        dprintf("mjpeg_decode_dc: bad vlc: %d:%d (%p)\n", 0, dc_index,
917
                &s->vlcs[0][dc_index]);
918
        return 0xffff;
919
    }
920
    if (code == 0) {
921
        diff = 0;
922
    } else {
923
        diff = get_bits(&s->gb, code);
924
        if ((diff & (1 << (code - 1))) == 0) 
925
            diff = (-1 << code) | (diff + 1);
926
    }
927
    return diff;
928
}
929

    
930
/* decode block and dequantize */
931
static int decode_block(MJpegDecodeContext *s, DCTELEM *block, 
932
                        int component, int dc_index, int ac_index, int quant_index)
933
{
934
    int nbits, code, i, j, level;
935
    int run, val;
936
    VLC *ac_vlc;
937
    int16_t *quant_matrix;
938

    
939
    /* DC coef */
940
    val = mjpeg_decode_dc(s, dc_index);
941
    if (val == 0xffff) {
942
        dprintf("error dc\n");
943
        return -1;
944
    }
945
    quant_matrix = s->quant_matrixes[quant_index];
946
    val = val * quant_matrix[0] + s->last_dc[component];
947
    s->last_dc[component] = val;
948
    block[0] = val;
949
    /* AC coefs */
950
    ac_vlc = &s->vlcs[1][ac_index];
951
    i = 1;
952
    for(;;) {
953
#if 1
954
        code = get_vlc2(&s->gb, s->vlcs[1][ac_index].table, 9, 2);
955
#else
956
        code = get_vlc(&s->gb, ac_vlc);
957
#endif
958
        if (code < 0) {
959
            dprintf("error ac\n");
960
            return -1;
961
        }
962
        /* EOB */
963
        if (code == 0)
964
            break;
965
        if (code == 0xf0) {
966
            i += 16;
967
        } else {
968
            run = code >> 4;
969
            nbits = code & 0xf;
970
            level = get_bits(&s->gb, nbits);
971
            if ((level & (1 << (nbits - 1))) == 0) 
972
                level = (-1 << nbits) | (level + 1);
973
            i += run;
974
            if (i >= 64) {
975
                dprintf("error count: %d\n", i);
976
                return -1;
977
            }
978
            j = s->scantable.permutated[i];
979
            block[j] = level * quant_matrix[j];
980
            i++;
981
            if (i >= 64)
982
                break;
983
        }
984
    }
985
    return 0;
986
}
987

    
988
static int mjpeg_decode_sos(MJpegDecodeContext *s)
989
{
990
    int len, nb_components, i, j, n, h, v, ret;
991
    int mb_width, mb_height, mb_x, mb_y, vmax, hmax, index, id;
992
    int comp_index[4];
993
    int dc_index[4];
994
    int ac_index[4];
995
    int nb_blocks[4];
996
    int h_count[4];
997
    int v_count[4];
998
    
999
    /* XXX: verify len field validity */
1000
    len = get_bits(&s->gb, 16);
1001
    nb_components = get_bits(&s->gb, 8);
1002
    if (len != 6+2*nb_components)
1003
    {
1004
        dprintf("decode_sos: invalid len (%d)\n", len);
1005
        return -1;
1006
    }
1007
    /* XXX: only interleaved scan accepted */
1008
    if (nb_components != 3)
1009
    {
1010
        dprintf("decode_sos: components(%d) mismatch\n", nb_components);
1011
        return -1;
1012
    }
1013
    vmax = 0;
1014
    hmax = 0;
1015
    for(i=0;i<nb_components;i++) {
1016
        id = get_bits(&s->gb, 8) - 1;
1017
        dprintf("component: %d\n", id);
1018
        /* find component index */
1019
        for(index=0;index<s->nb_components;index++)
1020
            if (id == s->component_id[index])
1021
                break;
1022
        if (index == s->nb_components)
1023
        {
1024
            dprintf("decode_sos: index(%d) out of components\n", index);
1025
            return -1;
1026
        }
1027

    
1028
        comp_index[i] = index;
1029
        nb_blocks[i] = s->h_count[index] * s->v_count[index];
1030
        h_count[i] = s->h_count[index];
1031
        v_count[i] = s->v_count[index];
1032

    
1033
        dc_index[i] = get_bits(&s->gb, 4);
1034
        ac_index[i] = get_bits(&s->gb, 4);
1035

    
1036
        if (dc_index[i] < 0 || ac_index[i] < 0 ||
1037
            dc_index[i] >= 4 || ac_index[i] >= 4)
1038
            goto out_of_range;
1039
        switch(s->start_code)
1040
        {
1041
            case SOF0:
1042
                if (dc_index[i] > 1 || ac_index[i] > 1)
1043
                    goto out_of_range;
1044
                break;
1045
            case SOF1:
1046
            case SOF2:
1047
                if (dc_index[i] > 3 || ac_index[i] > 3)
1048
                    goto out_of_range;
1049
                break;
1050
            case SOF3:
1051
                if (dc_index[i] > 3 || ac_index[i] != 0)
1052
                    goto out_of_range;
1053
                break;        
1054
        }
1055
    }
1056
    skip_bits(&s->gb, 8); /* Ss */
1057
    skip_bits(&s->gb, 8); /* Se */
1058
    skip_bits(&s->gb, 8); /* Ah and Al (each are 4 bits) */
1059

    
1060
    for(i=0;i<nb_components;i++) 
1061
        s->last_dc[i] = 1024;
1062

    
1063
    if (nb_components > 1) {
1064
        /* interleaved stream */
1065
        mb_width = (s->width + s->h_max * 8 - 1) / (s->h_max * 8);
1066
        mb_height = (s->height + s->v_max * 8 - 1) / (s->v_max * 8);
1067
    } else {
1068
        h = s->h_max / s->h_count[comp_index[0]];
1069
        v = s->v_max / s->v_count[comp_index[0]];
1070
        mb_width = (s->width + h * 8 - 1) / (h * 8);
1071
        mb_height = (s->height + v * 8 - 1) / (v * 8);
1072
        nb_blocks[0] = 1;
1073
        h_count[0] = 1;
1074
        v_count[0] = 1;
1075
    }
1076
    
1077
    for(mb_y = 0; mb_y < mb_height; mb_y++) {
1078
        for(mb_x = 0; mb_x < mb_width; mb_x++) {
1079
            for(i=0;i<nb_components;i++) {
1080
                uint8_t *ptr;
1081
                int x, y, c;
1082
                n = nb_blocks[i];
1083
                c = comp_index[i];
1084
                h = h_count[i];
1085
                v = v_count[i];
1086
                x = 0;
1087
                y = 0;
1088
                if (s->restart_interval && !s->restart_count)
1089
                    s->restart_count = s->restart_interval;
1090
                for(j=0;j<n;j++) {
1091
                    memset(s->block, 0, sizeof(s->block));
1092
                    if (decode_block(s, s->block, i, 
1093
                                     dc_index[i], ac_index[i], 
1094
                                     s->quant_index[c]) < 0) {
1095
                        dprintf("error y=%d x=%d\n", mb_y, mb_x);
1096
                        ret = -1;
1097
                        goto the_end;
1098
                    }
1099
//                    dprintf("mb: %d %d processed\n", mb_y, mb_x);
1100
                    ptr = s->current_picture[c] + 
1101
                        (s->linesize[c] * (v * mb_y + y) * 8) + 
1102
                        (h * mb_x + x) * 8;
1103
                    if (s->interlaced && s->bottom_field)
1104
                        ptr += s->linesize[c] >> 1;
1105
                    s->idct_put(ptr, s->linesize[c], s->block);
1106
                    if (++x == h) {
1107
                        x = 0;
1108
                        y++;
1109
                    }
1110
                }
1111
            }
1112
            /* (< 1350) buggy workaround for Spectralfan.mov, should be fixed */
1113
            if (s->restart_interval && (s->restart_interval < 1350) &&
1114
                !--s->restart_count) {
1115
                align_get_bits(&s->gb);
1116
                skip_bits(&s->gb, 16); /* skip RSTn */
1117
                for (j=0; j<nb_components; j++) /* reset dc */
1118
                    s->last_dc[j] = 1024;
1119
            }
1120
        }
1121
    }
1122
    ret = 0;
1123
 the_end:
1124
    emms_c();
1125
    return ret;
1126
 out_of_range:
1127
    dprintf("decode_sos: ac/dc index out of range\n");
1128
    return -1;
1129
}
1130

    
1131
static int mjpeg_decode_dri(MJpegDecodeContext *s)
1132
{
1133
    if (get_bits(&s->gb, 16) != 4)
1134
        return -1;
1135
    s->restart_interval = get_bits(&s->gb, 16);
1136
    dprintf("restart interval: %d\n", s->restart_interval);
1137

    
1138
    return 0;
1139
}
1140

    
1141
static int mjpeg_decode_app(MJpegDecodeContext *s)
1142
{
1143
    int len, id;
1144

    
1145
    /* XXX: verify len field validity */
1146
    len = get_bits(&s->gb, 16);
1147
    if (len < 5)
1148
        return -1;
1149

    
1150
    id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
1151
    id = be2me_32(id);
1152
    len -= 6;
1153

    
1154
    /* buggy AVID, it puts EOI only at every 10th frame */
1155
    /* also this fourcc is used by non-avid files too, it holds some
1156
       informations, but it's always present in AVID creates files */
1157
    if (id == ff_get_fourcc("AVI1"))
1158
    {
1159
        /* structure:
1160
            4bytes        AVI1
1161
            1bytes        polarity
1162
            1bytes        always zero
1163
            4bytes        field_size
1164
            4bytes        field_size_less_padding
1165
        */
1166
            s->buggy_avid = 1;
1167
//        if (s->first_picture)
1168
//            printf("mjpeg: workarounding buggy AVID\n");
1169
        s->interlace_polarity = get_bits(&s->gb, 8);
1170
#if 0
1171
        skip_bits(&s->gb, 8);
1172
        skip_bits(&s->gb, 32);
1173
        skip_bits(&s->gb, 32);
1174
        len -= 10;
1175
#endif
1176
//        if (s->interlace_polarity)
1177
//            printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
1178
        goto out;
1179
    }
1180
    
1181
//    len -= 2;
1182
    
1183
    if (id == ff_get_fourcc("JFIF"))
1184
    {
1185
        int t_w, t_h;
1186
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
1187
        printf("mjpeg: JFIF header found (version: %x.%x)\n",
1188
            get_bits(&s->gb, 8), get_bits(&s->gb, 8));
1189
        if (get_bits(&s->gb, 8) == 0)
1190
        {
1191
            int x_density, y_density; 
1192
            x_density = get_bits(&s->gb, 16);
1193
            y_density = get_bits(&s->gb, 16);
1194

    
1195
            dprintf("x/y density: %d (%f), %d (%f)\n", x_density,
1196
                (float)x_density, y_density, (float)y_density);
1197
#if 0
1198
            //MN: needs to be checked
1199
            if(x_density)
1200
//                s->avctx->aspect_ratio= s->width*y_density/((float)s->height*x_density);
1201
                s->avctx->aspect_ratio = (float)x_density/y_density;
1202
                /* it's better, but every JFIF I have seen stores 1:1 */
1203
            else
1204
                s->avctx->aspect_ratio= 0.0;
1205
#endif
1206
        }
1207
        else
1208
        {
1209
            skip_bits(&s->gb, 16);
1210
            skip_bits(&s->gb, 16);
1211
        }
1212

    
1213
        t_w = get_bits(&s->gb, 8);
1214
        t_h = get_bits(&s->gb, 8);
1215
        if (t_w && t_h)
1216
        {
1217
            /* skip thumbnail */
1218
            if (len-10-(t_w*t_h*3) > 0)
1219
                len -= t_w*t_h*3;
1220
        }
1221
        len -= 10;
1222
        goto out;
1223
    }
1224
    
1225
    if (id == ff_get_fourcc("Adob") && (get_bits(&s->gb, 8) == 'e'))
1226
    {
1227
        printf("mjpeg: Adobe header found\n");
1228
        skip_bits(&s->gb, 16); /* version */
1229
        skip_bits(&s->gb, 16); /* flags0 */
1230
        skip_bits(&s->gb, 16); /* flags1 */
1231
        skip_bits(&s->gb, 8); /* transform */
1232
        len -= 7;
1233
        goto out;
1234
    }
1235
    
1236
    /* Apple MJPEG-A */
1237
    if ((s->start_code == APP1) && (len > (0x28 - 8)))
1238
    {
1239
        id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
1240
        id = be2me_32(id);
1241
        len -= 4;
1242
        if (id == ff_get_fourcc("mjpg")) /* Apple MJPEG-A */
1243
        {
1244
#if 0
1245
            skip_bits(&s->gb, 32); /* field size */
1246
            skip_bits(&s->gb, 32); /* pad field size */
1247
            skip_bits(&s->gb, 32); /* next off */
1248
            skip_bits(&s->gb, 32); /* quant off */
1249
            skip_bits(&s->gb, 32); /* huff off */
1250
            skip_bits(&s->gb, 32); /* image off */
1251
            skip_bits(&s->gb, 32); /* scan off */
1252
            skip_bits(&s->gb, 32); /* data off */
1253
#endif
1254
            if (s->first_picture)
1255
                printf("mjpeg: Apple MJPEG-A header found\n");
1256
        }
1257
    }
1258

    
1259
out:
1260
    /* slow but needed for extreme adobe jpegs */
1261
    if (len < 0)
1262
        printf("mjpeg: error, decode_app parser read over the end\n");
1263
    while(--len > 0)
1264
        skip_bits(&s->gb, 8);
1265

    
1266
    return 0;
1267
}
1268

    
1269
static int mjpeg_decode_com(MJpegDecodeContext *s)
1270
{
1271
    /* XXX: verify len field validity */
1272
    unsigned int len = get_bits(&s->gb, 16);
1273
    if (len >= 2 && len < 32768) {
1274
        /* XXX: any better upper bound */
1275
        uint8_t *cbuf = av_malloc(len - 1);
1276
        if (cbuf) {
1277
            int i;
1278
            for (i = 0; i < len - 2; i++)
1279
                cbuf[i] = get_bits(&s->gb, 8);
1280
            if (i > 0 && cbuf[i-1] == '\n')
1281
                cbuf[i-1] = 0;
1282
            else
1283
                cbuf[i] = 0;
1284

    
1285
            printf("mjpeg comment: '%s'\n", cbuf);
1286

    
1287
            /* buggy avid, it puts EOI only at every 10th frame */
1288
            if (!strcmp(cbuf, "AVID"))
1289
            {
1290
                s->buggy_avid = 1;
1291
                //        if (s->first_picture)
1292
                //            printf("mjpeg: workarounding buggy AVID\n");
1293
            }
1294

    
1295
            av_free(cbuf);
1296
        }
1297
    }
1298

    
1299
    return 0;
1300
}
1301

    
1302
#if 0
1303
static int valid_marker_list[] =
1304
{
1305
        /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f */
1306
/* 0 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1307
/* 1 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1308
/* 2 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1309
/* 3 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1310
/* 4 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1311
/* 5 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1312
/* 6 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1313
/* 7 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1314
/* 8 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1315
/* 9 */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1316
/* a */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1317
/* b */    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1318
/* c */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1319
/* d */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1320
/* e */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1321
/* f */    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1322
}
1323
#endif
1324

    
1325
/* return the 8 bit start code value and update the search
1326
   state. Return -1 if no start code found */
1327
static int find_marker(uint8_t **pbuf_ptr, uint8_t *buf_end)
1328
{
1329
    uint8_t *buf_ptr;
1330
    unsigned int v, v2;
1331
    int val;
1332
#ifdef DEBUG
1333
    int skipped=0;
1334
#endif
1335

    
1336
    buf_ptr = *pbuf_ptr;
1337
    while (buf_ptr < buf_end) {
1338
        v = *buf_ptr++;
1339
        v2 = *buf_ptr;
1340
        if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe)) {
1341
            val = *buf_ptr++;
1342
            goto found;
1343
        }
1344
#ifdef DEBUG
1345
        skipped++;
1346
#endif
1347
    }
1348
    val = -1;
1349
found:
1350
#ifdef DEBUG
1351
    dprintf("find_marker skipped %d bytes\n", skipped);
1352
#endif
1353
    *pbuf_ptr = buf_ptr;
1354
    return val;
1355
}
1356

    
1357
static int mjpeg_decode_frame(AVCodecContext *avctx, 
1358
                              void *data, int *data_size,
1359
                              uint8_t *buf, int buf_size)
1360
{
1361
    MJpegDecodeContext *s = avctx->priv_data;
1362
    uint8_t *buf_end, *buf_ptr;
1363
    int i, start_code;
1364
    AVPicture *picture = data;
1365

    
1366
    *data_size = 0;
1367

    
1368
    /* no supplementary picture */
1369
    if (buf_size == 0)
1370
        return 0;
1371

    
1372
    buf_ptr = buf;
1373
    buf_end = buf + buf_size;
1374
    while (buf_ptr < buf_end) {
1375
        /* find start next marker */
1376
        start_code = find_marker(&buf_ptr, buf_end);
1377
        {
1378
            /* EOF */
1379
            if (start_code < 0) {
1380
                goto the_end;
1381
            } else {
1382
                dprintf("marker=%x avail_size_in_buf=%d\n", start_code, buf_end - buf_ptr);
1383
                
1384
                if ((buf_end - buf_ptr) > s->buffer_size)
1385
                {
1386
                    av_free(s->buffer);
1387
                    s->buffer_size = buf_end-buf_ptr;
1388
                    s->buffer = av_malloc(s->buffer_size);
1389
                    dprintf("buffer too small, expanding to %d bytes\n",
1390
                        s->buffer_size);
1391
                }
1392
                
1393
                /* unescape buffer of SOS */
1394
                if (start_code == SOS)
1395
                {
1396
                    uint8_t *src = buf_ptr;
1397
                    uint8_t *dst = s->buffer;
1398

    
1399
                    while (src<buf_end)
1400
                    {
1401
                        uint8_t x = *(src++);
1402

    
1403
                        *(dst++) = x;
1404
                        if (x == 0xff)
1405
                        {
1406
                            while(*src == 0xff) src++;
1407

    
1408
                            x = *(src++);
1409
                            if (x >= 0xd0 && x <= 0xd7)
1410
                                *(dst++) = x;
1411
                            else if (x)
1412
                                break;
1413
                        }
1414
                    }
1415
                    init_get_bits(&s->gb, s->buffer, (dst - s->buffer)*8);
1416
                    
1417
                    dprintf("escaping removed %d bytes\n",
1418
                        (buf_end - buf_ptr) - (dst - s->buffer));
1419
                }
1420
                else
1421
                    init_get_bits(&s->gb, buf_ptr, (buf_end - buf_ptr)*8);
1422
                
1423
                s->start_code = start_code;
1424

    
1425
                /* process markers */
1426
                if (start_code >= 0xd0 && start_code <= 0xd7) {
1427
                    dprintf("restart marker: %d\n", start_code&0x0f);
1428
                } else if (s->first_picture) {
1429
                    /* APP fields */
1430
                    if (start_code >= 0xe0 && start_code <= 0xef)
1431
                        mjpeg_decode_app(s);
1432
                    /* Comment */
1433
                    else if (start_code == COM)
1434
                        mjpeg_decode_com(s);
1435
                }
1436

    
1437
                switch(start_code) {
1438
                case SOI:
1439
                    s->restart_interval = 0;
1440
                    /* nothing to do on SOI */
1441
                    break;
1442
                case DQT:
1443
                    mjpeg_decode_dqt(s);
1444
                    break;
1445
                case DHT:
1446
                    mjpeg_decode_dht(s);
1447
                    break;
1448
                case SOF0:
1449
                    if (mjpeg_decode_sof0(s) < 0)
1450
                        return -1;
1451
                    break;
1452
                case EOI:
1453
eoi_parser:
1454
                    {
1455
                        if (s->interlaced) {
1456
                            s->bottom_field ^= 1;
1457
                            /* if not bottom field, do not output image yet */
1458
                            if (s->bottom_field)
1459
                                goto not_the_end;
1460
                        }
1461
                        for(i=0;i<3;i++) {
1462
                            picture->data[i] = s->current_picture[i];
1463
                            picture->linesize[i] = (s->interlaced) ?
1464
                                s->linesize[i] >> 1 : s->linesize[i];
1465
                        }
1466
                        *data_size = sizeof(AVPicture);
1467
                        avctx->height = s->height;
1468
                        if (s->interlaced)
1469
                            avctx->height *= 2;
1470
                        avctx->width = s->width;
1471
                        /* XXX: not complete test ! */
1472
                        switch((s->h_count[0] << 4) | s->v_count[0]) {
1473
                        case 0x11:
1474
                            avctx->pix_fmt = PIX_FMT_YUV444P;
1475
                            break;
1476
                        case 0x21:
1477
                            avctx->pix_fmt = PIX_FMT_YUV422P;
1478
                            break;
1479
                        default:
1480
                        case 0x22:
1481
                            avctx->pix_fmt = PIX_FMT_YUV420P;
1482
                            break;
1483
                        }
1484
                        /* dummy quality */
1485
                        /* XXX: infer it with matrix */
1486
//                            avctx->quality = 3; 
1487
                        goto the_end;
1488
                    }
1489
                    break;
1490
                case SOS:
1491
                    mjpeg_decode_sos(s);
1492
                    /* buggy avid puts EOI every 10-20th frame */
1493
                    /* if restart period is over process EOI */
1494
                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
1495
                        goto eoi_parser;
1496
                    break;
1497
                case DRI:
1498
                    mjpeg_decode_dri(s);
1499
                    break;
1500
                case SOF1:
1501
                case SOF2:
1502
                case SOF3:
1503
                case SOF5:
1504
                case SOF6:
1505
                case SOF7:
1506
                case SOF9:
1507
                case SOF10:
1508
                case SOF11:
1509
                case SOF13:
1510
                case SOF14:
1511
                case SOF15:
1512
                case JPG:
1513
                    printf("mjpeg: unsupported coding type (%x)\n", start_code);
1514
                    break;
1515
//                default:
1516
//                    printf("mjpeg: unsupported marker (%x)\n", start_code);
1517
//                    break;
1518
                }
1519

    
1520
not_the_end:
1521
                /* eof process start code */
1522
                buf_ptr += (get_bits_count(&s->gb)+7)/8;
1523
                dprintf("marker parser used %d bytes (%d bits)\n",
1524
                    (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
1525
            }
1526
        }
1527
    }
1528
the_end:
1529
    dprintf("mjpeg decode frame unused %d bytes\n", buf_end - buf_ptr);
1530
//    return buf_end - buf_ptr;
1531
    return buf_ptr - buf;
1532
}
1533

    
1534
static int mjpegb_decode_frame(AVCodecContext *avctx, 
1535
                              void *data, int *data_size,
1536
                              uint8_t *buf, int buf_size)
1537
{
1538
    MJpegDecodeContext *s = avctx->priv_data;
1539
    uint8_t *buf_end, *buf_ptr;
1540
    int i;
1541
    AVPicture *picture = data;
1542
    GetBitContext hgb; /* for the header */
1543
    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;
1544
    uint32_t field_size;
1545

    
1546
    *data_size = 0;
1547

    
1548
    /* no supplementary picture */
1549
    if (buf_size == 0)
1550
        return 0;
1551

    
1552
    buf_ptr = buf;
1553
    buf_end = buf + buf_size;
1554
    
1555
read_header:
1556
    /* reset on every SOI */
1557
    s->restart_interval = 0;
1558

    
1559
    init_get_bits(&hgb, buf_ptr, /*buf_size*/(buf_end - buf_ptr)*8);
1560

    
1561
    skip_bits(&hgb, 32); /* reserved zeros */
1562
    
1563
    if (get_bits(&hgb, 32) != be2me_32(ff_get_fourcc("mjpg")))
1564
    {
1565
        dprintf("not mjpeg-b (bad fourcc)\n");
1566
        return 0;
1567
    }
1568

    
1569
    field_size = get_bits(&hgb, 32); /* field size */
1570
    dprintf("field size: 0x%x\n", field_size);
1571
    skip_bits(&hgb, 32); /* padded field size */
1572
    second_field_offs = get_bits(&hgb, 32);
1573
    dprintf("second field offs: 0x%x\n", second_field_offs);
1574
    if (second_field_offs)
1575
        s->interlaced = 1;
1576

    
1577
    dqt_offs = get_bits(&hgb, 32);
1578
    dprintf("dqt offs: 0x%x\n", dqt_offs);
1579
    if (dqt_offs)
1580
    {
1581
        init_get_bits(&s->gb, buf+dqt_offs, (buf_end - (buf+dqt_offs))*8);
1582
        s->start_code = DQT;
1583
        mjpeg_decode_dqt(s);
1584
    }
1585
    
1586
    dht_offs = get_bits(&hgb, 32);
1587
    dprintf("dht offs: 0x%x\n", dht_offs);
1588
    if (dht_offs)
1589
    {
1590
        init_get_bits(&s->gb, buf+dht_offs, (buf_end - (buf+dht_offs))*8);
1591
        s->start_code = DHT;
1592
        mjpeg_decode_dht(s);
1593
    }
1594

    
1595
    sof_offs = get_bits(&hgb, 32);
1596
    dprintf("sof offs: 0x%x\n", sof_offs);
1597
    if (sof_offs)
1598
    {
1599
        init_get_bits(&s->gb, buf+sof_offs, (buf_end - (buf+sof_offs))*8);
1600
        s->start_code = SOF0;
1601
        if (mjpeg_decode_sof0(s) < 0)
1602
            return -1;
1603
    }
1604

    
1605
    sos_offs = get_bits(&hgb, 32);
1606
    dprintf("sos offs: 0x%x\n", sos_offs);
1607
    if (sos_offs)
1608
    {
1609
//        init_get_bits(&s->gb, buf+sos_offs, (buf_end - (buf+sos_offs))*8);
1610
        init_get_bits(&s->gb, buf+sos_offs, field_size*8);
1611
        s->start_code = SOS;
1612
        mjpeg_decode_sos(s);
1613
    }
1614

    
1615
    skip_bits(&hgb, 32); /* start of data offset */
1616

    
1617
    if (s->interlaced) {
1618
        s->bottom_field ^= 1;
1619
        /* if not bottom field, do not output image yet */
1620
        if (s->bottom_field && second_field_offs)
1621
        {
1622
            buf_ptr = buf + second_field_offs;
1623
            second_field_offs = 0;
1624
            goto read_header;
1625
            }
1626
    }
1627

    
1628
    for(i=0;i<3;i++) {
1629
        picture->data[i] = s->current_picture[i];
1630
        picture->linesize[i] = (s->interlaced) ?
1631
                s->linesize[i] >> 1 : s->linesize[i];
1632
    }
1633
    *data_size = sizeof(AVPicture);
1634
    avctx->height = s->height;
1635
    if (s->interlaced)
1636
        avctx->height *= 2;
1637
    avctx->width = s->width;
1638
    /* XXX: not complete test ! */
1639
    switch((s->h_count[0] << 4) | s->v_count[0]) {
1640
        case 0x11:
1641
                avctx->pix_fmt = PIX_FMT_YUV444P;
1642
            break;
1643
        case 0x21:
1644
            avctx->pix_fmt = PIX_FMT_YUV422P;
1645
            break;
1646
        default:
1647
        case 0x22:
1648
            avctx->pix_fmt = PIX_FMT_YUV420P;
1649
            break;
1650
    }
1651
    /* dummy quality */
1652
    /* XXX: infer it with matrix */
1653
//    avctx->quality = 3; 
1654

    
1655
    return buf_ptr - buf;
1656
}
1657

    
1658

    
1659
static int mjpeg_decode_end(AVCodecContext *avctx)
1660
{
1661
    MJpegDecodeContext *s = avctx->priv_data;
1662
    int i, j;
1663

    
1664
    av_free(s->buffer);
1665
    for(i=0;i<MAX_COMPONENTS;i++)
1666
        av_free(s->current_picture[i]);
1667
    for(i=0;i<2;i++) {
1668
        for(j=0;j<4;j++)
1669
            free_vlc(&s->vlcs[i][j]);
1670
    }
1671
    return 0;
1672
}
1673

    
1674
AVCodec mjpeg_decoder = {
1675
    "mjpeg",
1676
    CODEC_TYPE_VIDEO,
1677
    CODEC_ID_MJPEG,
1678
    sizeof(MJpegDecodeContext),
1679
    mjpeg_decode_init,
1680
    NULL,
1681
    mjpeg_decode_end,
1682
    mjpeg_decode_frame,
1683
    0,
1684
    NULL
1685
};
1686

    
1687
AVCodec mjpegb_decoder = {
1688
    "mjpegb",
1689
    CODEC_TYPE_VIDEO,
1690
    CODEC_ID_MJPEGB,
1691
    sizeof(MJpegDecodeContext),
1692
    mjpeg_decode_init,
1693
    NULL,
1694
    mjpeg_decode_end,
1695
    mjpegb_decode_frame,
1696
    0,
1697
    NULL
1698
};