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