]> git.sesse.net Git - ffmpeg/blob - libavcodec/mjpeg.c
fix got_picture output
[ffmpeg] / libavcodec / mjpeg.c
1 /*
2  * MJPEG encoder and decoder
3  * Copyright (c) 2000, 2001 Gerard Lantau.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program 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
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 #include "avcodec.h"
20 #include "dsputil.h"
21 #include "mpegvideo.h"
22
23 typedef struct MJpegContext {
24     UINT8 huff_size_dc_luminance[12];
25     UINT16 huff_code_dc_luminance[12];
26     UINT8 huff_size_dc_chrominance[12];
27     UINT16 huff_code_dc_chrominance[12];
28
29     UINT8 huff_size_ac_luminance[256];
30     UINT16 huff_code_ac_luminance[256];
31     UINT8 huff_size_ac_chrominance[256];
32     UINT16 huff_code_ac_chrominance[256];
33 } MJpegContext;
34
35 #define SOF0 0xc0
36 #define SOI 0xd8
37 #define EOI 0xd9
38 #define DQT 0xdb
39 #define DHT 0xc4
40 #define SOS 0xda
41
42 #if 0
43 /* These are the sample quantization tables given in JPEG spec section K.1.
44  * The spec says that the values given produce "good" quality, and
45  * when divided by 2, "very good" quality.
46  */
47 static const unsigned char std_luminance_quant_tbl[64] = {
48     16,  11,  10,  16,  24,  40,  51,  61,
49     12,  12,  14,  19,  26,  58,  60,  55,
50     14,  13,  16,  24,  40,  57,  69,  56,
51     14,  17,  22,  29,  51,  87,  80,  62,
52     18,  22,  37,  56,  68, 109, 103,  77,
53     24,  35,  55,  64,  81, 104, 113,  92,
54     49,  64,  78,  87, 103, 121, 120, 101,
55     72,  92,  95,  98, 112, 100, 103,  99
56 };
57 static const unsigned char std_chrominance_quant_tbl[64] = {
58     17,  18,  24,  47,  99,  99,  99,  99,
59     18,  21,  26,  66,  99,  99,  99,  99,
60     24,  26,  56,  99,  99,  99,  99,  99,
61     47,  66,  99,  99,  99,  99,  99,  99,
62     99,  99,  99,  99,  99,  99,  99,  99,
63     99,  99,  99,  99,  99,  99,  99,  99,
64     99,  99,  99,  99,  99,  99,  99,  99,
65     99,  99,  99,  99,  99,  99,  99,  99
66 };
67 #endif
68
69 /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
70 /* IMPORTANT: these are only valid for 8-bit data precision! */
71 static const UINT8 bits_dc_luminance[17] =
72 { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
73 static const UINT8 val_dc_luminance[] =
74 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
75
76 static const UINT8 bits_dc_chrominance[17] =
77 { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
78 static const UINT8 val_dc_chrominance[] =
79 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
80
81 static const UINT8 bits_ac_luminance[17] =
82 { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
83 static const UINT8 val_ac_luminance[] =
84 { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
85   0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
86   0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
87   0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
88   0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
89   0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
90   0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
91   0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
92   0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
93   0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
94   0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
95   0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
96   0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
97   0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
98   0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
99   0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
100   0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
101   0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
102   0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
103   0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
104   0xf9, 0xfa 
105 };
106
107 static const UINT8 bits_ac_chrominance[17] =
108 { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
109
110 static const UINT8 val_ac_chrominance[] =
111 { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
112   0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
113   0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
114   0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
115   0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
116   0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
117   0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
118   0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
119   0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
120   0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
121   0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
122   0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
123   0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
124   0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
125   0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
126   0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
127   0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
128   0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
129   0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
130   0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
131   0xf9, 0xfa 
132 };
133
134
135 /* isn't this function nicer than the one in the libjpeg ? */
136 static void build_huffman_codes(UINT8 *huff_size, UINT16 *huff_code,
137                                 const UINT8 *bits_table, const UINT8 *val_table)
138 {
139     int i, j, k,nb, code, sym;
140
141     code = 0;
142     k = 0;
143     for(i=1;i<=16;i++) {
144         nb = bits_table[i];
145         for(j=0;j<nb;j++) {
146             sym = val_table[k++];
147             huff_size[sym] = i;
148             huff_code[sym] = code;
149             code++;
150         }
151         code <<= 1;
152     }
153 }
154
155 int mjpeg_init(MpegEncContext *s)
156 {
157     MJpegContext *m;
158     
159     m = malloc(sizeof(MJpegContext));
160     if (!m)
161         return -1;
162
163     /* build all the huffman tables */
164     build_huffman_codes(m->huff_size_dc_luminance,
165                         m->huff_code_dc_luminance,
166                         bits_dc_luminance,
167                         val_dc_luminance);
168     build_huffman_codes(m->huff_size_dc_chrominance,
169                         m->huff_code_dc_chrominance,
170                         bits_dc_chrominance,
171                         val_dc_chrominance);
172     build_huffman_codes(m->huff_size_ac_luminance,
173                         m->huff_code_ac_luminance,
174                         bits_ac_luminance,
175                         val_ac_luminance);
176     build_huffman_codes(m->huff_size_ac_chrominance,
177                         m->huff_code_ac_chrominance,
178                         bits_ac_chrominance,
179                         val_ac_chrominance);
180     
181     s->mjpeg_ctx = m;
182     return 0;
183 }
184
185 void mjpeg_close(MpegEncContext *s)
186 {
187     free(s->mjpeg_ctx);
188 }
189
190 static inline void put_marker(PutBitContext *p, int code)
191 {
192     put_bits(p, 8, 0xff);
193     put_bits(p, 8, code);
194 }
195
196 /* table_class: 0 = DC coef, 1 = AC coefs */
197 static int put_huffman_table(MpegEncContext *s, int table_class, int table_id,
198                              const UINT8 *bits_table, const UINT8 *value_table)
199 {
200     PutBitContext *p = &s->pb;
201     int n, i;
202
203     put_bits(p, 4, table_class);
204     put_bits(p, 4, table_id);
205
206     n = 0;
207     for(i=1;i<=16;i++) {
208         n += bits_table[i];
209         put_bits(p, 8, bits_table[i]);
210     }
211
212     for(i=0;i<n;i++)
213         put_bits(p, 8, value_table[i]);
214
215     return n + 17;
216 }
217
218 static void jpeg_table_header(MpegEncContext *s)
219 {
220     PutBitContext *p = &s->pb;
221     int i, j, size;
222     UINT8 *ptr;
223
224     /* quant matrixes */
225     put_marker(p, DQT);
226     put_bits(p, 16, 2 + 1 * (1 + 64));
227     put_bits(p, 4, 0); /* 8 bit precision */
228     put_bits(p, 4, 0); /* table 0 */
229     for(i=0;i<64;i++) {
230         j = zigzag_direct[i];
231         put_bits(p, 8, s->intra_matrix[j]);
232     }
233 #if 0
234     put_bits(p, 4, 0); /* 8 bit precision */
235     put_bits(p, 4, 1); /* table 1 */
236     for(i=0;i<64;i++) {
237         j = zigzag_direct[i];
238         put_bits(p, 8, s->chroma_intra_matrix[j]);
239     }
240 #endif
241
242     /* huffman table */
243     put_marker(p, DHT);
244     flush_put_bits(p);
245     ptr = p->buf_ptr;
246     put_bits(p, 16, 0); /* patched later */
247     size = 2;
248     size += put_huffman_table(s, 0, 0, bits_dc_luminance, val_dc_luminance);
249     size += put_huffman_table(s, 0, 1, bits_dc_chrominance, val_dc_chrominance);
250     
251     size += put_huffman_table(s, 1, 0, bits_ac_luminance, val_ac_luminance);
252     size += put_huffman_table(s, 1, 1, bits_ac_chrominance, val_ac_chrominance);
253     ptr[0] = size >> 8;
254     ptr[1] = size;
255 }
256
257 void mjpeg_picture_header(MpegEncContext *s)
258 {
259     put_marker(&s->pb, SOI);
260
261     jpeg_table_header(s);
262
263     put_marker(&s->pb, SOF0);
264
265     put_bits(&s->pb, 16, 17);
266     put_bits(&s->pb, 8, 8); /* 8 bits/component */
267     put_bits(&s->pb, 16, s->height);
268     put_bits(&s->pb, 16, s->width);
269     put_bits(&s->pb, 8, 3); /* 3 components */
270     
271     /* Y component */
272     put_bits(&s->pb, 8, 1); /* component number */
273     put_bits(&s->pb, 4, 2); /* H factor */
274     put_bits(&s->pb, 4, 2); /* V factor */
275     put_bits(&s->pb, 8, 0); /* select matrix */
276     
277     /* Cb component */
278     put_bits(&s->pb, 8, 2); /* component number */
279     put_bits(&s->pb, 4, 1); /* H factor */
280     put_bits(&s->pb, 4, 1); /* V factor */
281     put_bits(&s->pb, 8, 0); /* select matrix */
282
283     /* Cr component */
284     put_bits(&s->pb, 8, 3); /* component number */
285     put_bits(&s->pb, 4, 1); /* H factor */
286     put_bits(&s->pb, 4, 1); /* V factor */
287     put_bits(&s->pb, 8, 0); /* select matrix */
288
289     /* scan header */
290     put_marker(&s->pb, SOS);
291     put_bits(&s->pb, 16, 12); /* length */
292     put_bits(&s->pb, 8, 3); /* 3 components */
293     
294     /* Y component */
295     put_bits(&s->pb, 8, 1); /* index */
296     put_bits(&s->pb, 4, 0); /* DC huffman table index */
297     put_bits(&s->pb, 4, 0); /* AC huffman table index */
298     
299     /* Cb component */
300     put_bits(&s->pb, 8, 2); /* index */
301     put_bits(&s->pb, 4, 1); /* DC huffman table index */
302     put_bits(&s->pb, 4, 1); /* AC huffman table index */
303     
304     /* Cr component */
305     put_bits(&s->pb, 8, 3); /* index */
306     put_bits(&s->pb, 4, 1); /* DC huffman table index */
307     put_bits(&s->pb, 4, 1); /* AC huffman table index */
308
309     put_bits(&s->pb, 8, 0); /* Ss (not used) */
310     put_bits(&s->pb, 8, 63); /* Se (not used) */
311     put_bits(&s->pb, 8, 0); /* (not used) */
312 }
313
314 void mjpeg_picture_trailer(MpegEncContext *s)
315 {
316     jflush_put_bits(&s->pb);
317     put_marker(&s->pb, EOI);
318 }
319
320 static inline void encode_dc(MpegEncContext *s, int val, 
321                              UINT8 *huff_size, UINT16 *huff_code)
322 {
323     int mant, nbits;
324
325     if (val == 0) {
326         jput_bits(&s->pb, huff_size[0], huff_code[0]);
327     } else {
328         mant = val;
329         if (val < 0) {
330             val = -val;
331             mant--;
332         }
333         
334         /* compute the log (XXX: optimize) */
335         nbits = 0;
336         while (val != 0) {
337             val = val >> 1;
338             nbits++;
339         }
340             
341         jput_bits(&s->pb, huff_size[nbits], huff_code[nbits]);
342         
343         jput_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
344     }
345 }
346
347 static void encode_block(MpegEncContext *s, DCTELEM *block, int n)
348 {
349     int mant, nbits, code, i, j;
350     int component, dc, run, last_index, val;
351     MJpegContext *m = s->mjpeg_ctx;
352     UINT8 *huff_size_ac;
353     UINT16 *huff_code_ac;
354     
355     /* DC coef */
356     component = (n <= 3 ? 0 : n - 4 + 1);
357     dc = block[0]; /* overflow is impossible */
358     val = dc - s->last_dc[component];
359     if (n < 4) {
360         encode_dc(s, val, m->huff_size_dc_luminance, m->huff_code_dc_luminance);
361         huff_size_ac = m->huff_size_ac_luminance;
362         huff_code_ac = m->huff_code_ac_luminance;
363     } else {
364         encode_dc(s, val, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);
365         huff_size_ac = m->huff_size_ac_chrominance;
366         huff_code_ac = m->huff_code_ac_chrominance;
367     }
368     s->last_dc[component] = dc;
369     
370     /* AC coefs */
371     
372     run = 0;
373     last_index = s->block_last_index[n];
374     for(i=1;i<=last_index;i++) {
375         j = zigzag_direct[i];
376         val = block[j];
377         if (val == 0) {
378             run++;
379         } else {
380             while (run >= 16) {
381                 jput_bits(&s->pb, huff_size_ac[0xf0], huff_code_ac[0xf0]);
382                 run -= 16;
383             }
384             mant = val;
385             if (val < 0) {
386                 val = -val;
387                 mant--;
388             }
389             
390             /* compute the log (XXX: optimize) */
391             nbits = 0;
392             while (val != 0) {
393                 val = val >> 1;
394                 nbits++;
395             }
396             code = (run << 4) | nbits;
397
398             jput_bits(&s->pb, huff_size_ac[code], huff_code_ac[code]);
399         
400             jput_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
401             run = 0;
402         }
403     }
404
405     /* output EOB only if not already 64 values */
406     if (last_index < 63 || run != 0)
407         jput_bits(&s->pb, huff_size_ac[0], huff_code_ac[0]);
408 }
409
410 void mjpeg_encode_mb(MpegEncContext *s, 
411                      DCTELEM block[6][64])
412 {
413     int i;
414     for(i=0;i<6;i++) {
415         encode_block(s, block[i], i);
416     }
417 }
418
419 /******************************************/
420 /* decoding */
421
422 //#define DEBUG
423
424 #ifndef CONFIG_WIN32
425
426 #ifdef DEBUG
427 #define dprintf(fmt,args...) printf(fmt, ## args)
428 #else
429 #define dprintf(fmt,args...)
430 #endif
431
432 #else
433
434 inline void dprintf(const char* fmt,...) {}
435
436 #endif
437
438 /* compressed picture size */
439 #define PICTURE_BUFFER_SIZE 100000
440
441 #define MAX_COMPONENTS 4
442
443 typedef struct MJpegDecodeContext {
444     GetBitContext gb;
445     UINT32 header_state;
446     int start_code; /* current start code */
447     UINT8 *buf_ptr;
448     int buffer_size;
449     int mpeg_enc_ctx_allocated; /* true if decoding context allocated */
450     INT16 quant_matrixes[4][64];
451     VLC vlcs[2][4];
452
453     int org_width, org_height;  /* size given at codec init */
454     int first_picture;    /* true if decoding first picture */
455     int interlaced;     /* true if interlaced */
456     int bottom_field;   /* true if bottom field */
457
458     int width, height;
459     int nb_components;
460     int component_id[MAX_COMPONENTS];
461     int h_count[MAX_COMPONENTS]; /* horizontal and vertical count for each component */
462     int v_count[MAX_COMPONENTS];
463     int h_max, v_max; /* maximum h and v counts */
464     int quant_index[4];   /* quant table index for each component */
465     int last_dc[MAX_COMPONENTS]; /* last DEQUANTIZED dc (XXX: am I right to do that ?) */
466     UINT8 *current_picture[MAX_COMPONENTS]; /* picture structure */
467     int linesize[MAX_COMPONENTS];
468     DCTELEM block[64] __align8;
469     UINT8 buffer[PICTURE_BUFFER_SIZE]; 
470 } MJpegDecodeContext;
471
472 static void build_vlc(VLC *vlc, const UINT8 *bits_table, const UINT8 *val_table, 
473                       int nb_codes)
474 {
475     UINT8 huff_size[256];
476     UINT16 huff_code[256];
477
478     memset(huff_size, 0, sizeof(huff_size));
479     build_huffman_codes(huff_size, huff_code, bits_table, val_table);
480     
481     init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2);
482 }
483
484 static int mjpeg_decode_init(AVCodecContext *avctx)
485 {
486     MJpegDecodeContext *s = avctx->priv_data;
487
488     s->header_state = 0;
489     s->mpeg_enc_ctx_allocated = 0;
490     s->buffer_size = PICTURE_BUFFER_SIZE - 1; /* minus 1 to take into
491                                                  account FF 00 case */
492     s->start_code = -1;
493     s->buf_ptr = s->buffer;
494     s->first_picture = 1;
495     s->org_width = avctx->width;
496     s->org_height = avctx->height;
497
498     build_vlc(&s->vlcs[0][0], bits_dc_luminance, val_dc_luminance, 12);
499     build_vlc(&s->vlcs[0][1], bits_dc_chrominance, val_dc_chrominance, 12);
500     build_vlc(&s->vlcs[1][0], bits_ac_luminance, val_ac_luminance, 251);
501     build_vlc(&s->vlcs[1][1], bits_ac_chrominance, val_ac_chrominance, 251);
502     return 0;
503 }
504
505 /* quantize tables */
506 static int mjpeg_decode_dqt(MJpegDecodeContext *s,
507                             UINT8 *buf, int buf_size)
508 {
509     int len, index, i, j;
510     init_get_bits(&s->gb, buf, buf_size);
511
512     len = get_bits(&s->gb, 16);
513     len -= 2;
514
515     while (len >= 65) {
516         /* only 8 bit precision handled */
517         if (get_bits(&s->gb, 4) != 0)
518             return -1;
519         index = get_bits(&s->gb, 4);
520         if (index >= 4)
521             return -1;
522         dprintf("index=%d\n", index);
523         /* read quant table */
524         for(i=0;i<64;i++) {
525             j = zigzag_direct[i];
526             s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
527         }
528         len -= 65;
529     }
530     return 0;
531 }
532
533 /* decode huffman tables and build VLC decoders */
534 static int mjpeg_decode_dht(MJpegDecodeContext *s,
535                             UINT8 *buf, int buf_size)
536 {
537     int len, index, i, class, n, v, code_max;
538     UINT8 bits_table[17];
539     UINT8 val_table[256];
540     
541     init_get_bits(&s->gb, buf, buf_size);
542
543     len = get_bits(&s->gb, 16);
544     len -= 2;
545
546     while (len > 0) {
547         if (len < 17)
548             return -1;
549         class = get_bits(&s->gb, 4);
550         if (class >= 2)
551             return -1;
552         index = get_bits(&s->gb, 4);
553         if (index >= 4)
554             return -1;
555         n = 0;
556         for(i=1;i<=16;i++) {
557             bits_table[i] = get_bits(&s->gb, 8);
558             n += bits_table[i];
559         }
560         len -= 17;
561         if (len < n || n > 256)
562             return -1;
563
564         code_max = 0;
565         for(i=0;i<n;i++) {
566             v = get_bits(&s->gb, 8);
567             if (v > code_max)
568                 code_max = v;
569             val_table[i] = v;
570         }
571         len -= n;
572
573         /* build VLC and flush previous vlc if present */
574         free_vlc(&s->vlcs[class][index]);
575         dprintf("class=%d index=%d nb_codes=%d\n",
576                class, index, code_max + 1);
577         build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1);
578     }
579     return 0;
580 }
581
582 static int mjpeg_decode_sof0(MJpegDecodeContext *s,
583                              UINT8 *buf, int buf_size)
584 {
585     int len, nb_components, i, width, height;
586
587     init_get_bits(&s->gb, buf, buf_size);
588
589     /* XXX: verify len field validity */
590     len = get_bits(&s->gb, 16);
591     /* only 8 bits/component accepted */
592     if (get_bits(&s->gb, 8) != 8)
593         return -1;
594     height = get_bits(&s->gb, 16);
595     width = get_bits(&s->gb, 16);
596
597     nb_components = get_bits(&s->gb, 8);
598     if (nb_components <= 0 ||
599         nb_components > MAX_COMPONENTS)
600         return -1;
601     s->nb_components = nb_components;
602     s->h_max = 1;
603     s->v_max = 1;
604     for(i=0;i<nb_components;i++) {
605         /* component id */
606         s->component_id[i] = get_bits(&s->gb, 8) - 1;
607         s->h_count[i] = get_bits(&s->gb, 4);
608         s->v_count[i] = get_bits(&s->gb, 4);
609         /* compute hmax and vmax (only used in interleaved case) */
610         if (s->h_count[i] > s->h_max)
611             s->h_max = s->h_count[i];
612         if (s->v_count[i] > s->v_max)
613             s->v_max = s->v_count[i];
614         s->quant_index[i] = get_bits(&s->gb, 8);
615         if (s->quant_index[i] >= 4)
616             return -1;
617         dprintf("component %d %d:%d\n", i, s->h_count[i], s->v_count[i]);
618     }
619
620     /* if different size, realloc/alloc picture */
621     /* XXX: also check h_count and v_count */
622     if (width != s->width || height != s->height) {
623         for(i=0;i<MAX_COMPONENTS;i++) {
624             free(s->current_picture[i]);
625             s->current_picture[i] = NULL;
626         }
627         s->width = width;
628         s->height = height;
629         /* test interlaced mode */
630         if (s->first_picture &&
631             s->org_height != 0 &&
632             s->height < ((s->org_height * 3) / 4)) {
633             s->interlaced = 1;
634             s->bottom_field = 0;
635         }
636
637         for(i=0;i<nb_components;i++) {
638             int w, h, hh, vv;
639             hh = s->h_max / s->h_count[i];
640             vv = s->v_max / s->v_count[i];
641             w = (s->width + 8 * hh - 1) / (8 * hh);
642             h = (s->height + 8 * vv - 1) / (8 * vv);
643             w = w * 8;
644             h = h * 8;
645             if (s->interlaced)
646                 w *= 2;
647             s->linesize[i] = w;
648             /* memory test is done in mjpeg_decode_sos() */
649             s->current_picture[i] = av_mallocz(w * h);
650         }
651         s->first_picture = 0;
652     }
653     
654     return 0;
655 }
656
657 static inline int decode_dc(MJpegDecodeContext *s, int dc_index)
658 {
659     VLC *dc_vlc;
660     int code, diff;
661
662     dc_vlc = &s->vlcs[0][dc_index];
663     code = get_vlc(&s->gb, dc_vlc);
664     if (code < 0)
665         return 0xffff;
666     if (code == 0) {
667         diff = 0;
668     } else {
669         diff = get_bits(&s->gb, code);
670         if ((diff & (1 << (code - 1))) == 0) 
671             diff = (-1 << code) | (diff + 1);
672     }
673     return diff;
674 }
675
676 /* decode block and dequantize */
677 static int decode_block(MJpegDecodeContext *s, DCTELEM *block, 
678                         int component, int dc_index, int ac_index, int quant_index)
679 {
680     int nbits, code, i, j, level;
681     int run, val;
682     VLC *ac_vlc;
683     INT16 *quant_matrix;
684
685     quant_matrix = s->quant_matrixes[quant_index];
686     /* DC coef */
687     val = decode_dc(s, dc_index);
688     if (val == 0xffff) {
689         dprintf("error dc\n");
690         return -1;
691     }
692     val = val * quant_matrix[0] + s->last_dc[component];
693     s->last_dc[component] = val;
694     block[0] = val;
695     /* AC coefs */
696     ac_vlc = &s->vlcs[1][ac_index];
697     i = 1;
698     for(;;) {
699         code = get_vlc(&s->gb, ac_vlc);
700         if (code < 0) {
701             dprintf("error ac\n");
702             return -1;
703         }
704         /* EOB */
705         if (code == 0)
706             break;
707         if (code == 0xf0) {
708             i += 16;
709         } else {
710             run = code >> 4;
711             nbits = code & 0xf;
712             level = get_bits(&s->gb, nbits);
713             if ((level & (1 << (nbits - 1))) == 0) 
714                 level = (-1 << nbits) | (level + 1);
715             i += run;
716             if (i >= 64) {
717                 dprintf("error count: %d\n", i);
718                 return -1;
719             }
720             j = zigzag_direct[i];
721             block[j] = level * quant_matrix[j];
722             i++;
723             if (i >= 64)
724                 break;
725         }
726     }
727     return 0;
728 }
729
730 static int mjpeg_decode_sos(MJpegDecodeContext *s,
731                             UINT8 *buf, int buf_size)
732 {
733     int len, nb_components, i, j, n, h, v, ret;
734     int mb_width, mb_height, mb_x, mb_y, vmax, hmax, index, id;
735     int comp_index[4];
736     int dc_index[4];
737     int ac_index[4];
738     int nb_blocks[4];
739     int h_count[4];
740     int v_count[4];
741     
742     init_get_bits(&s->gb, buf, buf_size);
743     /* XXX: verify len field validity */
744     len = get_bits(&s->gb, 16);
745     nb_components = get_bits(&s->gb, 8);
746     /* XXX: only interleaved scan accepted */
747     if (nb_components != 3)
748         return -1;
749     vmax = 0;
750     hmax = 0;
751     for(i=0;i<nb_components;i++) {
752         id = get_bits(&s->gb, 8) - 1;
753         /* find component index */
754         for(index=0;index<s->nb_components;index++)
755             if (id == s->component_id[index])
756                 break;
757         if (index == s->nb_components)
758             return -1;
759
760         comp_index[i] = index;
761         nb_blocks[i] = s->h_count[index] * s->v_count[index];
762         h_count[i] = s->h_count[index];
763         v_count[i] = s->v_count[index];
764
765         dc_index[i] = get_bits(&s->gb, 4);
766         if (dc_index[i] >= 4)
767             return -1;
768         ac_index[i] = get_bits(&s->gb, 4);
769         if (ac_index[i] >= 4)
770             return -1;
771     }
772     get_bits(&s->gb, 8); /* Ss */
773     get_bits(&s->gb, 8); /* Se */
774     get_bits(&s->gb, 8); /* not used */
775
776     for(i=0;i<nb_components;i++) 
777         s->last_dc[i] = 1024;
778
779     if (nb_components > 1) {
780         /* interleaved stream */
781         mb_width = (s->width + s->h_max * 8 - 1) / (s->h_max * 8);
782         mb_height = (s->height + s->v_max * 8 - 1) / (s->v_max * 8);
783     } else {
784         h = s->h_max / s->h_count[comp_index[0]];
785         v = s->v_max / s->v_count[comp_index[0]];
786         mb_width = (s->width + h * 8 - 1) / (h * 8);
787         mb_height = (s->height + v * 8 - 1) / (v * 8);
788         nb_blocks[0] = 1;
789         h_count[0] = 1;
790         v_count[0] = 1;
791     }
792
793     for(mb_y = 0; mb_y < mb_height; mb_y++) {
794         for(mb_x = 0; mb_x < mb_width; mb_x++) {
795             for(i=0;i<nb_components;i++) {
796                 UINT8 *ptr;
797                 int x, y, c;
798                 n = nb_blocks[i];
799                 c = comp_index[i];
800                 h = h_count[i];
801                 v = v_count[i];
802                 x = 0;
803                 y = 0;
804                 for(j=0;j<n;j++) {
805                     memset(s->block, 0, sizeof(s->block));
806                     if (decode_block(s, s->block, i, 
807                                      dc_index[i], ac_index[i], 
808                                      s->quant_index[c]) < 0) {
809                         dprintf("error %d %d\n", mb_y, mb_x);
810                         ret = -1;
811                         goto the_end;
812                     }
813                     ff_idct (s->block);
814                     ptr = s->current_picture[c] + 
815                         (s->linesize[c] * (v * mb_y + y) * 8) + 
816                         (h * mb_x + x) * 8;
817                     if (s->interlaced && s->bottom_field)
818                         ptr += s->linesize[c] >> 1;
819                     put_pixels_clamped(s->block, ptr, s->linesize[c]);
820                     if (++x == h) {
821                         x = 0;
822                         y++;
823                     }
824                 }
825             }
826         }
827     }
828     ret = 0;
829  the_end:
830     emms_c();
831     return ret;
832 }
833
834 /* return the 8 bit start code value and update the search
835    state. Return -1 if no start code found */
836 static int find_marker(UINT8 **pbuf_ptr, UINT8 *buf_end, 
837                        UINT32 *header_state)
838 {
839     UINT8 *buf_ptr;
840     unsigned int state, v;
841     int val;
842
843     state = *header_state;
844     buf_ptr = *pbuf_ptr;
845     if (state) {
846         /* get marker */
847     found:
848         if (buf_ptr < buf_end) {
849             val = *buf_ptr++;
850             state = 0;
851         } else {
852             val = -1;
853         }
854     } else {
855         while (buf_ptr < buf_end) {
856             v = *buf_ptr++;
857             if (v == 0xff) {
858                 state = 1;
859                 goto found;
860             }
861         }
862         val = -1;
863     }
864     *pbuf_ptr = buf_ptr;
865     *header_state = state;
866     return val;
867 }
868
869 static int mjpeg_decode_frame(AVCodecContext *avctx, 
870                               void *data, int *data_size,
871                               UINT8 *buf, int buf_size)
872 {
873     MJpegDecodeContext *s = avctx->priv_data;
874     UINT8 *buf_end, *buf_ptr, *buf_start;
875     int len, code, start_code, input_size, i;
876     AVPicture *picture = data;
877
878     *data_size = 0;
879
880     /* no supplementary picture */
881     if (buf_size == 0)
882         return 0;
883
884     buf_ptr = buf;
885     buf_end = buf + buf_size;
886     while (buf_ptr < buf_end) {
887         buf_start = buf_ptr;
888         /* find start next marker */
889         code = find_marker(&buf_ptr, buf_end, &s->header_state);
890         /* copy to buffer */
891         len = buf_ptr - buf_start;
892         if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {
893             /* data too big : flush */
894             s->buf_ptr = s->buffer;
895             if (code > 0)
896                 s->start_code = code;
897         } else {
898             memcpy(s->buf_ptr, buf_start, len);
899             s->buf_ptr += len;
900             /* if we got FF 00, we copy FF to the stream to unescape FF 00 */
901             if (code == 0) {
902                 s->buf_ptr--;
903             } else if (code > 0) {
904                 /* prepare data for next start code */
905                 input_size = s->buf_ptr - s->buffer;
906                 start_code = s->start_code;
907                 s->buf_ptr = s->buffer;
908                 s->start_code = code;
909                 dprintf("marker=%x\n", start_code);
910                 switch(start_code) {
911                 case SOI:
912                     /* nothing to do on SOI */
913                     break;
914                 case DQT:
915                     mjpeg_decode_dqt(s, s->buffer, input_size);
916                     break;
917                 case DHT:
918                     mjpeg_decode_dht(s, s->buffer, input_size);
919                     break;
920                 case SOF0:
921                     mjpeg_decode_sof0(s, s->buffer, input_size);
922                     break;
923                 case SOS:
924                     mjpeg_decode_sos(s, s->buffer, input_size);
925                     if (s->start_code == EOI) {
926                         int l;
927                         if (s->interlaced) {
928                             s->bottom_field ^= 1;
929                             /* if not bottom field, do not output image yet */
930                             if (s->bottom_field)
931                                 goto the_end;
932                         }
933                         for(i=0;i<3;i++) {
934                             picture->data[i] = s->current_picture[i];
935                             l = s->linesize[i];
936                             if (s->interlaced)
937                                 l >>= 1;
938                             picture->linesize[i] = l;
939                         }
940                         *data_size = sizeof(AVPicture);
941                         avctx->height = s->height;
942                         if (s->interlaced)
943                             avctx->height *= 2;
944                         avctx->width = s->width;
945                         /* XXX: not complete test ! */
946                         switch((s->h_count[0] << 4) | s->v_count[0]) {
947                         case 0x11:
948                             avctx->pix_fmt = PIX_FMT_YUV444P;
949                             break;
950                         case 0x21:
951                             avctx->pix_fmt = PIX_FMT_YUV422P;
952                             break;
953                         default:
954                         case 0x22:
955                             avctx->pix_fmt = PIX_FMT_YUV420P;
956                             break;
957                         }
958                         /* dummy quality */
959                         /* XXX: infer it with matrix */
960                         avctx->quality = 3; 
961                         goto the_end;
962                     }
963                     break;
964                 }
965             }
966         }
967     }
968  the_end:
969     return buf_ptr - buf;
970 }
971
972 static int mjpeg_decode_end(AVCodecContext *avctx)
973 {
974     MJpegDecodeContext *s = avctx->priv_data;
975     int i, j;
976
977     for(i=0;i<MAX_COMPONENTS;i++)
978         free(s->current_picture[i]);
979     for(i=0;i<2;i++) {
980         for(j=0;j<4;j++)
981             free_vlc(&s->vlcs[i][j]);
982     }
983     return 0;
984 }
985
986 AVCodec mjpeg_decoder = {
987     "mjpeg",
988     CODEC_TYPE_VIDEO,
989     CODEC_ID_MJPEG,
990     sizeof(MJpegDecodeContext),
991     mjpeg_decode_init,
992     NULL,
993     mjpeg_decode_end,
994     mjpeg_decode_frame,
995 };