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