allow ffmpeg video to resample curr_pos, add bluray format
[goodguy/history.git] / cinelerra-5.0 / quicktime / libmjpeg.c
1 /*
2  * This library is free software; you can redistribute it and/or modify it
3  * under the terms of the GNU Lesser General Public License as published
4  * by the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This library is distributed in the hope that it will be useful, but
8  * WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  * Lesser General Public License for more details.
11  *
12  * You should have received a copy of the GNU Lesser General Public
13  * License along with this library; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
15  * USA
16  */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include "colormodels.h"
22 #include "libmjpeg.h"
23
24 /* JPEG MARKERS */
25 #define   M_SOF0    0xc0
26 #define   M_SOF1    0xc1
27 #define   M_SOF2    0xc2
28 #define   M_SOF3    0xc3
29 #define   M_SOF5    0xc5
30 #define   M_SOF6    0xc6
31 #define   M_SOF7    0xc7
32 #define   M_JPG     0xc8
33 #define   M_SOF9    0xc9
34 #define   M_SOF10   0xca
35 #define   M_SOF11   0xcb
36 #define   M_SOF13   0xcd
37 #define   M_SOF14   0xce
38 #define   M_SOF15   0xcf
39 #define   M_DHT     0xc4
40 #define   M_DAC     0xcc
41 #define   M_RST0    0xd0
42 #define   M_RST1    0xd1
43 #define   M_RST2    0xd2
44 #define   M_RST3    0xd3
45 #define   M_RST4    0xd4
46 #define   M_RST5    0xd5
47 #define   M_RST6    0xd6
48 #define   M_RST7    0xd7
49 #define   M_SOI     0xd8
50 #define   M_EOI     0xd9
51 #define   M_SOS     0xda
52 #define   M_DQT     0xdb
53 #define   M_DNL     0xdc
54 #define   M_DRI     0xdd
55 #define   M_DHP     0xde
56 #define   M_EXP     0xdf
57 #define   M_APP0    0xe0
58 #define   M_APP1    0xe1
59 #define   M_APP2    0xe2
60 #define   M_APP3    0xe3
61 #define   M_APP4    0xe4
62 #define   M_APP5    0xe5
63 #define   M_APP6    0xe6
64 #define   M_APP7    0xe7
65 #define   M_APP8    0xe8
66 #define   M_APP9    0xe9
67 #define   M_APP10   0xea
68 #define   M_APP11   0xeb
69 #define   M_APP12   0xec
70 #define   M_APP13   0xed
71 #define   M_APP14   0xee
72 #define   M_APP15   0xef
73 #define   M_JPG0    0xf0
74 #define   M_JPG13   0xfd
75 #define   M_COM     0xfe
76 #define   M_TEM     0x01
77 #define   M_ERROR   0x100
78
79 #define QUICKTIME_MARKER_SIZE 0x2c
80 #define AVI_MARKER_SIZE 0x12
81 #define QUICKTIME_JPEG_TAG 0x6d6a7067
82 #define QUICKTIME_AVI_TAG 0x41564931
83
84
85 METHODDEF(void) mjpeg_error_exit (j_common_ptr cinfo)
86 {
87 /* cinfo->err really points to a mjpeg_error_mgr struct, so coerce pointer */
88         mjpeg_error_ptr mjpegerr = (mjpeg_error_ptr) cinfo->err;
89
90 /* Always display the message. */
91 /* We could postpone this until after returning, if we chose. */
92         (*cinfo->err->output_message) (cinfo);
93
94 /* Return control to the setjmp point */
95         longjmp(mjpegerr->setjmp_buffer, 1);
96 }
97
98 typedef struct
99 {
100         struct jpeg_destination_mgr pub; /* public fields */
101
102         JOCTET *buffer;         /* Pointer to buffer */
103         mjpeg_compressor *engine;
104 } mjpeg_destination_mgr;
105
106 typedef mjpeg_destination_mgr *mjpeg_dest_ptr;
107
108
109 /*
110  * Initialize destination --- called by jpeg_start_compress
111  * before any data is actually written.
112  */
113
114 METHODDEF(void) init_destination(j_compress_ptr cinfo)
115 {
116         mjpeg_dest_ptr dest = (mjpeg_dest_ptr)cinfo->dest;
117
118 /* Set the pointer to the preallocated buffer */
119         if(!dest->engine->output_buffer)
120         {
121                 dest->engine->output_buffer = calloc(1, 65536);
122                 dest->engine->output_allocated = 65536;
123         }
124         dest->buffer = dest->engine->output_buffer;
125         dest->pub.next_output_byte = dest->engine->output_buffer;
126         dest->pub.free_in_buffer = dest->engine->output_allocated;
127 }
128
129 /*
130  * Empty the output buffer --- called whenever buffer fills up.
131  *
132  * In typical applications, this should write the entire output buffer
133  * (ignoring the current state of next_output_byte & free_in_buffer),
134  * reset the pointer & count to the start of the buffer, and return TRUE
135  * indicating that the buffer has been dumped.
136  *
137  * In applications that need to be able to suspend compression due to output
138  * overrun, a FALSE return indicates that the buffer cannot be emptied now.
139  * In this situation, the compressor will return to its caller (possibly with
140  * an indication that it has not accepted all the supplied scanlines).  The
141  * application should resume compression after it has made more room in the
142  * output buffer.  Note that there are substantial restrictions on the use of
143  * suspension --- see the documentation.
144  *
145  * When suspending, the compressor will back up to a convenient restart point
146  * (typically the start of the current MCU). next_output_byte & free_in_buffer
147  * indicate where the restart point will be if the current call returns FALSE.
148  * Data beyond this point will be regenerated after resumption, so do not
149  * write it out when emptying the buffer externally.
150  */
151
152 METHODDEF(boolean) empty_output_buffer(j_compress_ptr cinfo)
153 {
154 /* Allocate a bigger buffer. */
155         mjpeg_dest_ptr dest = (mjpeg_dest_ptr)cinfo->dest;
156
157         dest->engine->output_size = dest->engine->output_allocated;
158         dest->engine->output_allocated *= 2;
159         dest->engine->output_buffer = realloc(dest->engine->output_buffer,
160                 dest->engine->output_allocated);
161         dest->buffer = dest->engine->output_buffer;
162         dest->pub.next_output_byte = dest->buffer + dest->engine->output_size;
163         dest->pub.free_in_buffer = dest->engine->output_allocated - dest->engine->output_size;
164
165         return TRUE;
166 }
167
168 /*
169  * Terminate destination --- called by jpeg_finish_compress
170  * after all data has been written.  Usually needs to flush buffer.
171  *
172  * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
173  * application must deal with any cleanup that should happen even
174  * for error exit.
175  */
176 METHODDEF(void) term_destination(j_compress_ptr cinfo)
177 {
178 /* Just get the length */
179         mjpeg_dest_ptr dest = (mjpeg_dest_ptr)cinfo->dest;
180         dest->engine->output_size = dest->engine->output_allocated - dest->pub.free_in_buffer;
181 }
182
183 GLOBAL(void) jpeg_buffer_dest(j_compress_ptr cinfo, mjpeg_compressor *engine)
184 {
185         mjpeg_dest_ptr dest;
186
187 /* The destination object is made permanent so that multiple JPEG images
188  * can be written to the same file without re-executing jpeg_stdio_dest.
189  * This makes it dangerous to use this manager and a different destination
190  * manager serially with the same JPEG object, because their private object
191  * sizes may be different.  Caveat programmer.
192  */
193         if(cinfo->dest == NULL)
194         {
195 /* first time for this JPEG object? */
196         cinfo->dest = (struct jpeg_destination_mgr *)
197                 (*cinfo->mem->alloc_small)((j_common_ptr)cinfo,
198                                 JPOOL_PERMANENT,
199                                 sizeof(mjpeg_destination_mgr));
200         }
201
202         dest = (mjpeg_dest_ptr)cinfo->dest;
203         dest->pub.init_destination = init_destination;
204         dest->pub.empty_output_buffer = empty_output_buffer;
205         dest->pub.term_destination = term_destination;
206         dest->engine = engine;
207 }
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 typedef struct {
223         struct jpeg_source_mgr pub;     /* public fields */
224
225         JOCTET * buffer;                /* start of buffer */
226         int bytes;             /* total size of buffer */
227 } mjpeg_source_mgr;
228
229 typedef mjpeg_source_mgr* mjpeg_src_ptr;
230
231 METHODDEF(void) init_source(j_decompress_ptr cinfo)
232 {
233     //mjpeg_src_ptr src = (mjpeg_src_ptr) cinfo->src;
234 }
235
236 METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo)
237 {
238         mjpeg_src_ptr src = (mjpeg_src_ptr) cinfo->src;
239
240         src->buffer[0] = (JOCTET)0xFF;
241         src->buffer[1] = (JOCTET)M_EOI;
242         src->pub.next_input_byte = src->buffer;
243         src->pub.bytes_in_buffer = 2;
244
245         return TRUE;
246 }
247
248
249 METHODDEF(void) skip_input_data(j_decompress_ptr cinfo, long num_bytes)
250 {
251         mjpeg_src_ptr src = (mjpeg_src_ptr)cinfo->src;
252
253         src->pub.next_input_byte += (size_t)num_bytes;
254         src->pub.bytes_in_buffer -= (size_t)num_bytes;
255 }
256
257
258 METHODDEF(void) term_source(j_decompress_ptr cinfo)
259 {
260 }
261
262 GLOBAL(void) jpeg_buffer_src(j_decompress_ptr cinfo, unsigned char *buffer, long bytes)
263 {
264         mjpeg_src_ptr src;
265
266 /* first time for this JPEG object? */
267         if(cinfo->src == NULL)
268         {
269         cinfo->src = (struct jpeg_source_mgr*)
270                 (*cinfo->mem->alloc_small)((j_common_ptr)cinfo,
271                         JPOOL_PERMANENT,
272                                         sizeof(mjpeg_source_mgr));
273         src = (mjpeg_src_ptr)cinfo->src;
274         }
275
276         src = (mjpeg_src_ptr)cinfo->src;
277         src->pub.init_source = init_source;
278         src->pub.fill_input_buffer = fill_input_buffer;
279         src->pub.skip_input_data = skip_input_data;
280         src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
281         src->pub.term_source = term_source;
282         src->pub.bytes_in_buffer = bytes;
283         src->pub.next_input_byte = buffer;
284         src->buffer = buffer;
285         src->bytes = bytes;
286 }
287
288 /* JPEG DHT Segment for YCrCb omitted from MJPEG data */
289 static
290 unsigned char jpeg_odml_dht[0x1a4] = {
291     0xff, 0xc4, 0x01, 0xa2,
292
293     0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
294     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
295
296     0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
297     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
298
299     0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d,
300     0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
301     0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
302     0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
303     0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
304     0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
305     0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
306     0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
307     0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
308     0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
309     0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
310     0xf9, 0xfa,
311
312     0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77,
313     0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
314     0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
315     0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
316     0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
317     0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
318     0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
319     0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
320     0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
321     0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
322     0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
323     0xf9, 0xfa
324 };
325
326
327 /*
328  * Parse the DHT table.
329  * This code comes from jpeg6b (jdmarker.c).
330  */
331 static
332 int jpeg_load_dht (struct jpeg_decompress_struct *info, unsigned char *dht,
333               JHUFF_TBL *ac_tables[], JHUFF_TBL *dc_tables[])
334 {
335     unsigned int length = (dht[2] << 8) + dht[3] - 2;
336     unsigned int pos = 4;
337     unsigned int count, i;
338     int index;
339
340     JHUFF_TBL **hufftbl;
341     unsigned char bits[17];
342     unsigned char huffval[256];
343
344     while (length > 16)
345     {
346        bits[0] = 0;
347        index = dht[pos++];
348        count = 0;
349        for (i = 1; i <= 16; ++i)
350        {
351            bits[i] = dht[pos++];
352            count += bits[i];
353        }
354        length -= 17;
355
356        if (count > 256 || count > length)
357            return -1;
358
359        for (i = 0; i < count; ++i)
360            huffval[i] = dht[pos++];
361        length -= count;
362
363        if (index & 0x10)
364        {
365            index -= 0x10;
366            hufftbl = &ac_tables[index];
367        }
368        else
369            hufftbl = &dc_tables[index];
370
371        if (index < 0 || index >= NUM_HUFF_TBLS)
372            return -1;
373
374        if (*hufftbl == NULL)
375            *hufftbl = jpeg_alloc_huff_table ((j_common_ptr)info);
376        if (*hufftbl == NULL)
377            return -1;
378
379        memcpy ((*hufftbl)->bits, bits, sizeof (*hufftbl)->bits);
380        memcpy ((*hufftbl)->huffval, huffval, sizeof (*hufftbl)->huffval);
381     }
382
383     if (length != 0)
384        return -1;
385
386     return 0;
387 }
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403 static void reset_buffer(unsigned char **buffer, long *size, long *allocated)
404 {
405         *size = 0;
406 }
407
408 static void delete_buffer(unsigned char **buffer, long *size, long *allocated)
409 {
410         if(*buffer)
411         {
412                 free(*buffer);
413                 *size = 0;
414                 *allocated = 0;
415         }
416 }
417
418 static void append_buffer(unsigned char **buffer,
419         long *size,
420         long *allocated,
421         unsigned char *data,
422         long data_size)
423 {
424         if(!*buffer)
425         {
426                 *buffer = calloc(1, 65536);
427                 *size = 0;
428                 *allocated = 65536;
429         }
430
431         if(*size + data_size + 0x100 > *allocated)
432         {
433                 *allocated = *size + data_size + 0x100;
434                 *buffer = realloc(*buffer, *allocated);
435         }
436
437         memcpy(*buffer + *size, data, data_size);
438         *size += data_size;
439 }
440
441 static void allocate_temps(mjpeg_t *mjpeg)
442 {
443         int i;
444
445         if(!mjpeg->temp_data)
446     {
447         switch(mjpeg->jpeg_color_model)
448         {
449             case BC_YUV422P:
450 //printf("allocate_temps 1\n");
451                     mjpeg->temp_data = calloc(1, mjpeg->coded_w * mjpeg->coded_h * 2);
452                     mjpeg->temp_rows[0] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
453                     mjpeg->temp_rows[1] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
454                     mjpeg->temp_rows[2] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
455                     for(i = 0; i < mjpeg->coded_h; i++)
456                     {
457                             mjpeg->temp_rows[0][i] = mjpeg->temp_data + i * mjpeg->coded_w;
458                             mjpeg->temp_rows[1][i] = mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h + i * mjpeg->coded_w / 2;
459                             mjpeg->temp_rows[2][i] = mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h + mjpeg->coded_w / 2 * mjpeg->coded_h + i * mjpeg->coded_w / 2;
460                     }
461                 break;
462
463             case BC_YUV444P:
464                     mjpeg->temp_data = calloc(1, mjpeg->coded_w * mjpeg->coded_h * 3);
465                     mjpeg->temp_rows[0] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
466                     mjpeg->temp_rows[1] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
467                     mjpeg->temp_rows[2] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
468                     if(mjpeg->greyscale)
469                                 {
470                                         memset(mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h,
471                                                 0x80,
472                                                 mjpeg->coded_w * mjpeg->coded_h * 2);
473                                 }
474                                 for(i = 0; i < mjpeg->coded_h; i++)
475                     {
476                             mjpeg->temp_rows[0][i] = mjpeg->temp_data + i * mjpeg->coded_w;
477                             mjpeg->temp_rows[1][i] = mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h + i * mjpeg->coded_w;
478                             mjpeg->temp_rows[2][i] = mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h + mjpeg->coded_w * mjpeg->coded_h + i * mjpeg->coded_w;
479                     }
480                 break;
481
482             case BC_YUV420P:
483                     mjpeg->temp_data = calloc(1, mjpeg->coded_w * mjpeg->coded_h + mjpeg->coded_w * mjpeg->coded_h / 2);
484                     mjpeg->temp_rows[0] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
485                     mjpeg->temp_rows[1] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h / 2);
486                     mjpeg->temp_rows[2] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h / 2);
487                     for(i = 0; i < mjpeg->coded_h; i++)
488                     {
489                             mjpeg->temp_rows[0][i] = mjpeg->temp_data + i * mjpeg->coded_w;
490                             if(i < mjpeg->coded_h / 2)
491                             {
492                                     mjpeg->temp_rows[1][i] = mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h + i * (mjpeg->coded_w / 2);
493                                     mjpeg->temp_rows[2][i] = mjpeg->temp_data + mjpeg->coded_w * mjpeg->coded_h + (mjpeg->coded_h / 2) * (mjpeg->coded_w / 2) + i * (mjpeg->coded_w / 2);
494                             }
495                     }
496                 break;
497         }
498     }
499 }
500
501 static int get_input_row(mjpeg_t *mjpeg, mjpeg_compressor *compressor, int i)
502 {
503         int input_row;
504         if(mjpeg->fields > 1)
505                 input_row = i * 2 + compressor->instance;
506         else
507                 input_row = i;
508         if(input_row >= mjpeg->coded_h) input_row = mjpeg->coded_h - 1;
509         return input_row;
510 }
511
512 // Get pointers to rows for the JPEG compressor
513 static void get_rows(mjpeg_t *mjpeg, mjpeg_compressor *compressor)
514 {
515         int i;
516     switch(mjpeg->jpeg_color_model)
517     {
518                 case BC_YUV444P:
519                 {
520                         if(!compressor->rows[0])
521                         {
522                                 compressor->rows[0] = calloc(1, sizeof(unsigned char*) * compressor->coded_field_h);
523                                 compressor->rows[1] = calloc(1, sizeof(unsigned char*) * compressor->coded_field_h);
524                                 compressor->rows[2] = calloc(1, sizeof(unsigned char*) * compressor->coded_field_h);
525                         }
526
527 // User colormodel matches jpeg colormodel
528                         if(mjpeg->color_model == BC_YUV444P &&
529                                 mjpeg->output_w == mjpeg->coded_w &&
530                                 mjpeg->output_h == mjpeg->coded_h)
531                         {
532                                 for(i = 0; i < compressor->coded_field_h; i++)
533                                 {
534                                         int input_row = get_input_row(mjpeg, compressor, i);
535                                         compressor->rows[0][i] = mjpeg->y_argument +
536                                                 mjpeg->coded_w * input_row;
537                                         compressor->rows[1][i] = mjpeg->u_argument +
538                                                 mjpeg->coded_w * input_row;
539                                         compressor->rows[2][i] = mjpeg->v_argument +
540                                                 mjpeg->coded_w * input_row;
541                                 }
542                         }
543                         else
544                         {
545                                 for(i = 0; i < compressor->coded_field_h; i++)
546                                 {
547                                         int input_row = get_input_row(mjpeg, compressor, i);
548                                         compressor->rows[0][i] = mjpeg->temp_rows[0][input_row];
549                                         compressor->rows[1][i] = mjpeg->temp_rows[1][input_row];
550                                         compressor->rows[2][i] = mjpeg->temp_rows[2][input_row];
551                                 }
552                         }
553                         break;
554                 }
555
556                 case BC_YUV422P:
557                 {
558                         if(!compressor->rows[0])
559                         {
560                                 compressor->rows[0] = calloc(1, sizeof(unsigned char*) * compressor->coded_field_h);
561                                 compressor->rows[1] = calloc(1, sizeof(unsigned char*) * compressor->coded_field_h);
562                                 compressor->rows[2] = calloc(1, sizeof(unsigned char*) * compressor->coded_field_h);
563                         }
564
565 // User colormodel matches jpeg colormodel
566                         if(mjpeg->color_model == BC_YUV422P &&
567                                 mjpeg->output_w == mjpeg->coded_w &&
568                                 mjpeg->output_h == mjpeg->coded_h)
569                         {
570                                 for(i = 0; i < compressor->coded_field_h; i++)
571                                 {
572                                         int input_row = get_input_row(mjpeg, compressor, i);
573                                         compressor->rows[0][i] = mjpeg->y_argument +
574                                                 mjpeg->coded_w * input_row;
575                                         compressor->rows[1][i] = mjpeg->u_argument +
576                                                 (mjpeg->coded_w / 2) * input_row;
577                                         compressor->rows[2][i] = mjpeg->v_argument +
578                                                 (mjpeg->coded_w / 2) * input_row;
579                                 }
580                         }
581                         else
582                         {
583                                 for(i = 0; i < compressor->coded_field_h; i++)
584                                 {
585                                         int input_row = get_input_row(mjpeg, compressor, i);
586                                         compressor->rows[0][i] = mjpeg->temp_rows[0][input_row];
587                                         compressor->rows[1][i] = mjpeg->temp_rows[1][input_row];
588                                         compressor->rows[2][i] = mjpeg->temp_rows[2][input_row];
589                                 }
590                         }
591                         break;
592                 }
593
594                 case BC_YUV420P:
595                 {
596                         if(!compressor->rows[0])
597                         {
598                                 compressor->rows[0] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h);
599                                 compressor->rows[1] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h / 2);
600                                 compressor->rows[2] = calloc(1, sizeof(unsigned char*) * mjpeg->coded_h / 2);
601                         }
602
603 // User colormodel matches jpeg colormodel
604                         if(mjpeg->color_model == BC_YUV420P &&
605                                 mjpeg->output_w == mjpeg->coded_w &&
606                                 mjpeg->output_h == mjpeg->coded_h)
607                         {
608                                 for(i = 0; i < compressor->coded_field_h; i++)
609                                 {
610                                         int input_row = get_input_row(mjpeg, compressor, i);
611                                         compressor->rows[0][i] = mjpeg->y_argument +
612                                                 mjpeg->coded_w * input_row;
613                         if(i < compressor->coded_field_h / 2)
614                         {
615                                         compressor->rows[1][i] = mjpeg->u_argument +
616                                                 (mjpeg->coded_w / 2) * input_row;
617                                         compressor->rows[2][i] = mjpeg->v_argument +
618                                                 (mjpeg->coded_w / 2) * input_row;
619                         }
620                                 }
621                         }
622                         else
623                         {
624                                 for(i = 0; i < compressor->coded_field_h; i++)
625                                 {
626                                         int input_row = get_input_row(mjpeg, compressor, i);
627                                         compressor->rows[0][i] = mjpeg->temp_rows[0][input_row];
628                         if(i < compressor->coded_field_h / 2)
629                         {
630                                         compressor->rows[1][i] = mjpeg->temp_rows[1][input_row];
631                                         compressor->rows[2][i] = mjpeg->temp_rows[2][input_row];
632                         }
633                                 }
634                         }
635                         break;
636                 }
637         }
638 }
639
640 static void delete_rows(mjpeg_compressor *compressor)
641 {
642         if(compressor->rows[0])
643         {
644                 free(compressor->rows[0]);
645                 free(compressor->rows[1]);
646                 free(compressor->rows[2]);
647         }
648 }
649
650 /* replacement routine to suppress decompress warnings */
651 static void mjpeg_emit_message(j_common_ptr cinfo, int msg_level)
652 {
653   struct jpeg_error_mgr * err = cinfo->err;
654   if (msg_level < 0) {
655     err->num_warnings++;
656     if(err->trace_level >= 3)
657       (*err->output_message) (cinfo);
658   } else {
659     if (err->trace_level >= msg_level)
660       (*err->output_message) (cinfo);
661   }
662 }
663
664 static void new_jpeg_objects(mjpeg_compressor *engine)
665 {
666         engine->jpeg_decompress.err = jpeg_std_error(&(engine->jpeg_error.pub));
667         engine->jpeg_error.pub.error_exit = mjpeg_error_exit;
668         engine->jpeg_error.pub.emit_message = mjpeg_emit_message;
669 /* Ideally the error handler would be set here but it must be called in a thread */
670         jpeg_create_decompress(&(engine->jpeg_decompress));
671         engine->jpeg_decompress.raw_data_out = TRUE;
672 #if JPEG_LIB_VERSION >= 70
673         engine->jpeg_decompress.do_fancy_upsampling = FALSE;
674 #endif
675         engine->jpeg_decompress.dct_method = JDCT_IFAST;
676 }
677
678 static void delete_jpeg_objects(mjpeg_compressor *engine)
679 {
680         jpeg_destroy_decompress(&(engine->jpeg_decompress));
681 }
682
683
684
685 static void unlock_compress_loop(mjpeg_compressor *engine)
686 {
687         pthread_mutex_unlock(&(engine->input_lock));
688 }
689
690 static void lock_compress_loop(mjpeg_compressor *engine)
691 {
692         pthread_mutex_lock(&(engine->output_lock));
693 }
694
695 // Make temp rows for compressor
696 static void get_mcu_rows(mjpeg_t *mjpeg,
697         mjpeg_compressor *engine,
698         int start_row)
699 {
700         int i, j, scanline;
701         for(i = 0; i < 3; i++)
702         {
703                 for(j = 0; j < 16; j++)
704                 {
705                         if(i > 0 && j >= 8 && mjpeg->jpeg_color_model == BC_YUV420P) break;
706
707                         scanline = start_row;
708                         if(i > 0 && mjpeg->jpeg_color_model == BC_YUV420P) scanline /= 2;
709                         scanline += j;
710                         if(scanline >= engine->coded_field_h) scanline = engine->coded_field_h - 1;
711                         engine->mcu_rows[i][j] = engine->rows[i][scanline];
712                 }
713         }
714 }
715
716
717 static void decompress_field(mjpeg_compressor *engine)
718 {
719         mjpeg_t *mjpeg = engine->mjpeg;
720         long buffer_offset = engine->instance * mjpeg->input_field2;
721         unsigned char *buffer = mjpeg->input_data + buffer_offset;
722         long buffer_size;
723
724 //printf("decompress_field %02x%02x %d\n", buffer[0], buffer[1], engine->instance * mjpeg->input_field2);
725         if(engine->instance == 0 && mjpeg->fields > 1)
726                 buffer_size = mjpeg->input_field2 - buffer_offset;
727         else
728                 buffer_size = mjpeg->input_size - buffer_offset;
729
730         mjpeg->error = 0;
731
732         if(setjmp(engine->jpeg_error.setjmp_buffer))
733         {
734 /* If we get here, the JPEG code has signaled an error. */
735 printf("decompress_field %d\n", __LINE__);
736                 delete_jpeg_objects(engine);
737 printf("decompress_field %d\n", __LINE__);
738                 new_jpeg_objects(engine);
739 printf("decompress_field %d\n", __LINE__);
740                 mjpeg->error = 1;
741 printf("decompress_field %d\n", __LINE__);
742                 goto finish;
743         }
744
745 //printf("decompress_field 2\n");
746         jpeg_buffer_src(&engine->jpeg_decompress,
747                 buffer,
748                 buffer_size);
749         jpeg_read_header(&engine->jpeg_decompress, TRUE);
750
751         if ( engine->jpeg_decompress.ac_huff_tbl_ptrs[0] == NULL &&
752              engine->jpeg_decompress.ac_huff_tbl_ptrs[1] == NULL &&
753              engine->jpeg_decompress.dc_huff_tbl_ptrs[0] == NULL &&
754              engine->jpeg_decompress.dc_huff_tbl_ptrs[1] == NULL )
755                 jpeg_load_dht(  &engine->jpeg_decompress,
756                                 jpeg_odml_dht,
757                                 engine->jpeg_decompress.ac_huff_tbl_ptrs,
758                                 engine->jpeg_decompress.dc_huff_tbl_ptrs );
759 // Reset by jpeg_read_header
760         engine->jpeg_decompress.raw_data_out = TRUE;
761 #if JPEG_LIB_VERSION >= 70
762         engine->jpeg_decompress.do_fancy_upsampling = FALSE;
763 #endif
764         jpeg_start_decompress(&engine->jpeg_decompress);
765
766 // Generate colormodel from jpeg sampling
767         if(engine->jpeg_decompress.comp_info[0].v_samp_factor == 2 &&
768                 engine->jpeg_decompress.comp_info[0].h_samp_factor == 2)
769         mjpeg->jpeg_color_model = BC_YUV420P;
770     else
771         if(engine->jpeg_decompress.comp_info[0].v_samp_factor == 1 &&
772                 engine->jpeg_decompress.comp_info[0].h_samp_factor == 2)
773         mjpeg->jpeg_color_model = BC_YUV422P;
774         else
775                 mjpeg->jpeg_color_model = BC_YUV444P;
776
777         if(engine->jpeg_decompress.jpeg_color_space == JCS_GRAYSCALE)
778                 mjpeg->greyscale = 1;
779
780 //printf("%d %d\n", engine->jpeg_decompress.comp_info[0].h_samp_factor, engine->jpeg_decompress.comp_info[0].v_samp_factor);
781 // Must be here because the color model isn't known until now
782         pthread_mutex_lock(&(mjpeg->decompress_init));
783         allocate_temps(mjpeg);
784         pthread_mutex_unlock(&(mjpeg->decompress_init));
785         get_rows(mjpeg, engine);
786
787 //printf("decompress_field 30\n");
788
789         while(engine->jpeg_decompress.output_scanline < engine->jpeg_decompress.output_height)
790         {
791                 get_mcu_rows(mjpeg, engine, engine->jpeg_decompress.output_scanline);
792                 jpeg_read_raw_data(&engine->jpeg_decompress,
793                         engine->mcu_rows,
794                         engine->coded_field_h);
795         }
796         jpeg_finish_decompress(&engine->jpeg_decompress);
797
798 //printf("decompress_field 40\n");
799
800 finish:
801         ;
802 }
803
804 void mjpeg_decompress_loop(mjpeg_compressor *engine)
805 {
806         while(!engine->done)
807         {
808                 pthread_mutex_lock(&engine->input_lock);
809                 if(!engine->done)
810                 {
811                         decompress_field(engine);
812                 }
813                 pthread_mutex_unlock(&(engine->output_lock));
814         }
815 }
816
817
818 static void compress_field(mjpeg_compressor *engine)
819 {
820         mjpeg_t *mjpeg = engine->mjpeg;
821
822 //printf("compress_field 1\n");
823         get_rows(engine->mjpeg, engine);
824         reset_buffer(&engine->output_buffer, &engine->output_size, &engine->output_allocated);
825         jpeg_buffer_dest(&engine->jpeg_compress, engine);
826
827
828         engine->jpeg_compress.raw_data_in = TRUE;
829 #if JPEG_LIB_VERSION >= 70
830         engine->jpeg_compress.do_fancy_downsampling = FALSE;
831 #endif
832         jpeg_start_compress(&engine->jpeg_compress, TRUE);
833
834         while(engine->jpeg_compress.next_scanline < engine->jpeg_compress.image_height)
835         {
836                 get_mcu_rows(mjpeg, engine, engine->jpeg_compress.next_scanline);
837
838                 jpeg_write_raw_data(&engine->jpeg_compress,
839                         engine->mcu_rows,
840                         engine->coded_field_h);
841         }
842         jpeg_finish_compress(&engine->jpeg_compress);
843 //printf("compress_field 2\n");
844 }
845
846
847 void mjpeg_compress_loop(mjpeg_compressor *engine)
848 {
849         while(!engine->done)
850         {
851                 pthread_mutex_lock(&engine->input_lock);
852                 if(!engine->done)
853                 {
854                         compress_field(engine);
855                 }
856                 pthread_mutex_unlock(&engine->output_lock);
857         }
858 }
859
860 static void delete_temps(mjpeg_t *mjpeg)
861 {
862         if(mjpeg->temp_data)
863     {
864             free(mjpeg->temp_data);
865             free(mjpeg->temp_rows[0]);
866             free(mjpeg->temp_rows[1]);
867             free(mjpeg->temp_rows[2]);
868                 mjpeg->temp_data = 0;
869         }
870 }
871
872 mjpeg_compressor* mjpeg_new_decompressor(mjpeg_t *mjpeg, int instance)
873 {
874         mjpeg_compressor *result = calloc(1, sizeof(mjpeg_compressor));
875         pthread_attr_t  attr;
876         pthread_mutexattr_t mutex_attr;
877
878         result->mjpeg = mjpeg;
879         result->instance = instance;
880         new_jpeg_objects(result);
881         result->field_h = mjpeg->output_h / mjpeg->fields;
882         result->coded_field_h = (result->field_h % 16) ?
883                 result->field_h + (16 - (result->field_h % 16)) : result->field_h;
884
885         result->mcu_rows[0] = malloc(16 * sizeof(unsigned char*));
886         result->mcu_rows[1] = malloc(16 * sizeof(unsigned char*));
887         result->mcu_rows[2] = malloc(16 * sizeof(unsigned char*));
888
889         pthread_mutexattr_init(&mutex_attr);
890 //      pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ADAPTIVE_NP);
891         pthread_mutex_init(&(result->input_lock), &mutex_attr);
892         pthread_mutex_lock(&(result->input_lock));
893         pthread_mutex_init(&(result->output_lock), &mutex_attr);
894         pthread_mutex_lock(&(result->output_lock));
895
896         pthread_attr_init(&attr);
897         pthread_create(&(result->tid), &attr, (void*)mjpeg_decompress_loop, result);
898
899         return result;
900 }
901
902 void mjpeg_delete_decompressor(mjpeg_compressor *engine)
903 {
904         engine->done = 1;
905         pthread_mutex_unlock(&(engine->input_lock));
906         pthread_join(engine->tid, 0);
907         pthread_mutex_destroy(&(engine->input_lock));
908         pthread_mutex_destroy(&(engine->output_lock));
909         jpeg_destroy_decompress(&(engine->jpeg_decompress));
910         delete_rows(engine);
911         free(engine->mcu_rows[0]);
912         free(engine->mcu_rows[1]);
913         free(engine->mcu_rows[2]);
914         free(engine);
915 }
916
917 mjpeg_compressor* mjpeg_new_compressor(mjpeg_t *mjpeg, int instance)
918 {
919         pthread_attr_t  attr;
920         pthread_mutexattr_t mutex_attr;
921         mjpeg_compressor *result = calloc(1, sizeof(mjpeg_compressor));
922
923         result->field_h = mjpeg->output_h / mjpeg->fields;
924         result->coded_field_h = (result->field_h % 16) ?
925                 result->field_h + (16 - (result->field_h % 16)) : result->field_h;
926         result->mjpeg = mjpeg;
927         result->instance = instance;
928         result->jpeg_compress.err = jpeg_std_error(&(result->jpeg_error.pub));
929         jpeg_create_compress(&(result->jpeg_compress));
930         result->jpeg_compress.image_width = mjpeg->output_w;
931         result->jpeg_compress.image_height = result->field_h;
932         result->jpeg_compress.input_components = 3;
933         result->jpeg_compress.in_color_space = JCS_RGB;
934         jpeg_set_defaults(&(result->jpeg_compress));
935         result->jpeg_compress.input_components = 3;
936         result->jpeg_compress.in_color_space = JCS_RGB;
937         jpeg_set_quality(&(result->jpeg_compress), mjpeg->quality, 0);
938
939         if(mjpeg->use_float)
940                 result->jpeg_compress.dct_method = JDCT_FLOAT;
941         else
942                 result->jpeg_compress.dct_method = JDCT_IFAST;
943 //              result->jpeg_compress.dct_method = JDCT_ISLOW;
944
945 /* Fix sampling */
946         switch(mjpeg->fields)
947     {
948         case 1:
949                 mjpeg->jpeg_color_model = BC_YUV420P;
950                     result->jpeg_compress.comp_info[0].h_samp_factor = 2;
951                     result->jpeg_compress.comp_info[0].v_samp_factor = 2;
952                     result->jpeg_compress.comp_info[1].h_samp_factor = 1;
953                     result->jpeg_compress.comp_info[1].v_samp_factor = 1;
954                     result->jpeg_compress.comp_info[2].h_samp_factor = 1;
955                     result->jpeg_compress.comp_info[2].v_samp_factor = 1;
956                 break;
957         case 2:
958                 mjpeg->jpeg_color_model = BC_YUV422P;
959                     result->jpeg_compress.comp_info[0].h_samp_factor = 2;
960                     result->jpeg_compress.comp_info[0].v_samp_factor = 1;
961                     result->jpeg_compress.comp_info[1].h_samp_factor = 1;
962                     result->jpeg_compress.comp_info[1].v_samp_factor = 1;
963                     result->jpeg_compress.comp_info[2].h_samp_factor = 1;
964                     result->jpeg_compress.comp_info[2].v_samp_factor = 1;
965                 break;
966     }
967     allocate_temps(mjpeg);
968
969         result->mcu_rows[0] = malloc(16 * sizeof(unsigned char*));
970         result->mcu_rows[1] = malloc(16 * sizeof(unsigned char*));
971         result->mcu_rows[2] = malloc(16 * sizeof(unsigned char*));
972
973         pthread_mutexattr_init(&mutex_attr);
974 //      pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ADAPTIVE_NP);
975         pthread_mutex_init(&(result->input_lock), &mutex_attr);
976         pthread_mutex_lock(&(result->input_lock));
977         pthread_mutex_init(&(result->output_lock), &mutex_attr);
978         pthread_mutex_lock(&(result->output_lock));
979
980         pthread_attr_init(&attr);
981         pthread_create(&(result->tid), &attr, (void*)mjpeg_compress_loop, result);
982         return result;
983 }
984
985
986 void mjpeg_delete_compressor(mjpeg_compressor *engine)
987 {
988         engine->done = 1;
989         pthread_mutex_unlock(&(engine->input_lock));
990         pthread_join(engine->tid, 0);
991         pthread_mutex_destroy(&(engine->input_lock));
992         pthread_mutex_destroy(&(engine->output_lock));
993         jpeg_destroy((j_common_ptr)&(engine->jpeg_compress));
994         if(engine->output_buffer) free(engine->output_buffer);
995         delete_rows(engine);
996         free(engine->mcu_rows[0]);
997         free(engine->mcu_rows[1]);
998         free(engine->mcu_rows[2]);
999         free(engine);
1000 }
1001
1002 unsigned char* mjpeg_output_buffer(mjpeg_t *mjpeg)
1003 {
1004         return mjpeg->output_data;
1005 }
1006
1007 long mjpeg_output_field2(mjpeg_t *mjpeg)
1008 {
1009         return mjpeg->output_field2;
1010 }
1011
1012 long mjpeg_output_size(mjpeg_t *mjpeg)
1013 {
1014         return mjpeg->output_size;
1015 }
1016
1017 long mjpeg_output_allocated(mjpeg_t *mjpeg)
1018 {
1019         return mjpeg->output_allocated;
1020 }
1021
1022 void mjpeg_set_output_size(mjpeg_t *mjpeg, long output_size)
1023 {
1024         mjpeg->output_size = output_size;
1025 }
1026
1027
1028 int mjpeg_compress(mjpeg_t *mjpeg,
1029         unsigned char **row_pointers,
1030         unsigned char *y_plane,
1031         unsigned char *u_plane,
1032         unsigned char *v_plane,
1033         int color_model,
1034         int cpus)
1035 {
1036         int i, result = 0;
1037         int corrected_fields = mjpeg->fields;
1038         mjpeg->color_model = color_model;
1039         mjpeg->cpus = cpus;
1040
1041 //printf("mjpeg_compress 1 %d\n", color_model);
1042 /* Reset output buffer */
1043         reset_buffer(&mjpeg->output_data,
1044                 &mjpeg->output_size,
1045                 &mjpeg->output_allocated);
1046
1047 /* Create compression engines as needed */
1048         for(i = 0; i < mjpeg->fields; i++)
1049         {
1050                 if(!mjpeg->compressors[i])
1051                 {
1052                         mjpeg->compressors[i] = mjpeg_new_compressor(mjpeg, i);
1053                 }
1054         }
1055
1056 /* Arm YUV buffers */
1057         mjpeg->row_argument = row_pointers;
1058         mjpeg->y_argument = y_plane;
1059         mjpeg->u_argument = u_plane;
1060         mjpeg->v_argument = v_plane;
1061 // User colormodel doesn't match encoder colormodel
1062 // Copy to interlacing buffer first
1063         if(mjpeg->color_model != mjpeg->jpeg_color_model ||
1064                 mjpeg->output_w != mjpeg->coded_w ||
1065                 mjpeg->output_h != mjpeg->coded_h)
1066         {
1067 /*
1068  * printf("mjpeg_compress %d %d %d %d\n",
1069  * mjpeg->output_w, mjpeg->output_h, mjpeg->coded_w, mjpeg->coded_h);
1070  */
1071                 cmodel_transfer(0,
1072                         row_pointers,
1073                         mjpeg->temp_rows[0][0],
1074                         mjpeg->temp_rows[1][0],
1075                         mjpeg->temp_rows[2][0],
1076                         y_plane,
1077                         u_plane,
1078                         v_plane,
1079                         0,
1080                         0,
1081                         mjpeg->output_w,
1082                         mjpeg->output_h,
1083                         0,
1084                         0,
1085                         mjpeg->output_w,
1086                         mjpeg->output_h,
1087                         mjpeg->color_model,
1088                         mjpeg->jpeg_color_model,
1089                         0,
1090                         mjpeg->output_w,
1091                         mjpeg->coded_w);
1092         }
1093
1094 /* Start the compressors on the image fields */
1095         if(mjpeg->deinterlace) corrected_fields = 1;
1096         for(i = 0; i < corrected_fields && !result; i++)
1097         {
1098                 unlock_compress_loop(mjpeg->compressors[i]);
1099
1100                 if(mjpeg->cpus < 2 && i < corrected_fields - 1)
1101                 {
1102                         lock_compress_loop(mjpeg->compressors[i]);
1103                 }
1104         }
1105
1106 /* Wait for the compressors and store in master output */
1107         for(i = 0; i < corrected_fields && !result; i++)
1108         {
1109                 if(mjpeg->cpus > 1 || i == corrected_fields - 1)
1110                 {
1111                         lock_compress_loop(mjpeg->compressors[i]);
1112                 }
1113
1114                 append_buffer(&mjpeg->output_data,
1115                         &mjpeg->output_size,
1116                         &mjpeg->output_allocated,
1117                         mjpeg->compressors[i]->output_buffer,
1118                         mjpeg->compressors[i]->output_size);
1119                 if(i == 0) mjpeg->output_field2 = mjpeg->output_size;
1120         }
1121
1122         if(corrected_fields < mjpeg->fields)
1123         {
1124                 append_buffer(&mjpeg->output_data,
1125                         &mjpeg->output_size,
1126                         &mjpeg->output_allocated,
1127                         mjpeg->compressors[0]->output_buffer,
1128                         mjpeg->compressors[0]->output_size);
1129         }
1130 //printf("mjpeg_compress 2\n");
1131         return 0;
1132 }
1133
1134
1135
1136 int mjpeg_decompress(mjpeg_t *mjpeg,
1137         unsigned char *buffer,
1138         long buffer_len,
1139         long input_field2,
1140         unsigned char **row_pointers,
1141         unsigned char *y_plane,
1142         unsigned char *u_plane,
1143         unsigned char *v_plane,
1144         int color_model,
1145         int cpus)
1146 {
1147         int i, result = 0;
1148         int got_first_thread = 0;
1149
1150 //printf("mjpeg_decompress 1 %d\n", color_model);
1151         if(buffer_len == 0) return 1;
1152         if(input_field2 == 0 && mjpeg->fields > 1) return 1;
1153
1154 //printf("mjpeg_decompress 2\n");
1155 /* Create decompression engines as needed */
1156         for(i = 0; i < mjpeg->fields; i++)
1157         {
1158                 if(!mjpeg->decompressors[i])
1159                 {
1160                         mjpeg->decompressors[i] = mjpeg_new_decompressor(mjpeg, i);
1161                 }
1162         }
1163
1164 //printf("mjpeg_decompress 3\n");
1165 /* Arm YUV buffers */
1166         mjpeg->row_argument = row_pointers;
1167         mjpeg->y_argument = y_plane;
1168         mjpeg->u_argument = u_plane;
1169         mjpeg->v_argument = v_plane;
1170         mjpeg->input_data = buffer;
1171         mjpeg->input_size = buffer_len;
1172         mjpeg->input_field2 = input_field2;
1173         mjpeg->color_model = color_model;
1174         mjpeg->cpus = cpus;
1175
1176 //printf("mjpeg_decompress 4 %02x %02x %d %02x %02x\n", buffer[0], buffer[1], input_field2, buffer[input_field2], buffer[input_field2 + 1]);
1177 /* Start decompressors */
1178         for(i = 0; i < mjpeg->fields && !result; i++)
1179         {
1180 //printf("mjpeg_decompress 5\n");
1181                 unlock_compress_loop(mjpeg->decompressors[i]);
1182 //printf("mjpeg_decompress 6\n");
1183
1184 // For dual CPUs, don't want second thread to start until temp data is allocated by the first.
1185 // For single CPUs, don't want two threads running simultaneously
1186                 if(mjpeg->cpus < 2 || !mjpeg->temp_data)
1187                 {
1188 //printf("mjpeg_decompress 7\n");
1189                         lock_compress_loop(mjpeg->decompressors[i]);
1190 //printf("mjpeg_decompress 8\n");
1191                         if(i == 0) got_first_thread = 1;
1192                 }
1193         }
1194
1195 //printf("mjpeg_decompress 10\n");
1196 /* Wait for decompressors */
1197         for(i = 0; i < mjpeg->fields && !result; i++)
1198         {
1199                 if(mjpeg->cpus > 1)
1200                 {
1201                         if(i > 0 || !got_first_thread)
1202                                 lock_compress_loop(mjpeg->decompressors[i]);
1203                 }
1204         }
1205
1206 /* Convert colormodel */
1207 // User colormodel didn't match decompressor
1208 /*
1209  *      if(!mjpeg->error &&
1210  *              (mjpeg->jpeg_color_model != mjpeg->color_model ||
1211  *              mjpeg->coded_w != mjpeg->output_w ||
1212  *              mjpeg->coded_h != mjpeg->output_h))
1213  */
1214
1215 //printf("mjpeg_decompress 6 %d %d %d %d\n", mjpeg->coded_w, mjpeg->coded_h, mjpeg->output_w, mjpeg->output_h);
1216         if((mjpeg->jpeg_color_model != mjpeg->color_model ||
1217                 mjpeg->coded_w != mjpeg->output_w ||
1218                 mjpeg->coded_h != mjpeg->output_h)
1219                 &&
1220                 (mjpeg->temp_data ||
1221                 !mjpeg->error))
1222         {
1223                 unsigned char *y_in = mjpeg->temp_rows[0][0];
1224                 unsigned char *u_in = mjpeg->temp_rows[1][0];
1225                 unsigned char *v_in = mjpeg->temp_rows[2][0];
1226
1227
1228 /*
1229  * printf("mjpeg_decompress 7 coded_w=%d coded_h=%d output_w=%d output_h=%d out_rowspan=%d in_colormodel=%d out_colormodel=%d\n",
1230  * mjpeg->coded_w,
1231  * mjpeg->coded_h,
1232  * mjpeg->output_w,
1233  * mjpeg->output_h,
1234  * mjpeg->rowspan ? mjpeg->rowspan : mjpeg->output_w,
1235  * mjpeg->jpeg_color_model,
1236  * mjpeg->color_model);
1237  */
1238
1239                 cmodel_transfer(row_pointers,
1240                         0,
1241                         y_plane,
1242                         u_plane,
1243                         v_plane,
1244                         y_in,
1245                         u_in,
1246                         v_in,
1247                         0,
1248                         0,
1249                         mjpeg->output_w,
1250                         mjpeg->output_h,
1251                         0,
1252                         0,
1253                         mjpeg->output_w,
1254                         mjpeg->output_h,
1255                         mjpeg->jpeg_color_model,
1256                         mjpeg->color_model,
1257                         0,
1258                         mjpeg->coded_w,
1259                         mjpeg->rowspan ? mjpeg->rowspan : mjpeg->output_w);
1260 //printf("mjpeg_decompress 8\n");
1261         }
1262         return 0;
1263 }
1264
1265
1266 void mjpeg_set_deinterlace(mjpeg_t *mjpeg, int value)
1267 {
1268         mjpeg->deinterlace = value;
1269 }
1270
1271 void mjpeg_set_quality(mjpeg_t *mjpeg, int quality)
1272 {
1273         mjpeg->quality = quality;
1274 }
1275
1276 void mjpeg_set_float(mjpeg_t *mjpeg, int use_float)
1277 {
1278         mjpeg->use_float = use_float;
1279 }
1280
1281 void mjpeg_set_cpus(mjpeg_t *mjpeg, int cpus)
1282 {
1283         mjpeg->cpus = cpus;
1284 }
1285
1286 void mjpeg_set_rowspan(mjpeg_t *mjpeg, int rowspan)
1287 {
1288         mjpeg->rowspan = rowspan;
1289 }
1290
1291 int mjpeg_get_fields(mjpeg_t *mjpeg)
1292 {
1293         return mjpeg->fields;
1294 }
1295
1296
1297 mjpeg_t* mjpeg_new(int w,
1298         int h,
1299         int fields)
1300 {
1301         mjpeg_t *result = calloc(1, sizeof(mjpeg_t));
1302         pthread_mutexattr_t mutex_attr;
1303
1304         result->output_w = w;
1305         result->output_h = h;
1306         result->fields = fields;
1307         result->color_model = BC_RGB888;
1308         result->cpus = 1;
1309         result->quality = 80;
1310         result->use_float = 0;
1311
1312         pthread_mutexattr_init(&mutex_attr);
1313 //      pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ADAPTIVE_NP);
1314         pthread_mutex_init(&(result->decompress_init), &mutex_attr);
1315
1316
1317 // Calculate coded dimensions
1318 // An interlaced frame with 4:2:0 sampling must be a multiple of 32
1319
1320         result->coded_w = (w % 16) ? w + (16 - (w % 16)) : w;
1321
1322         if(fields == 1)
1323                 result->coded_h = (h % 16) ? h + (16 - (h % 16)) : h;
1324         else
1325                 result->coded_h = (h % 32) ? h + (32 - (h % 32)) : h;
1326
1327
1328
1329 //printf("mjpeg_new %d %d %d %d\n", result->output_w, result->output_h, result->coded_w, result->coded_h);
1330         return result;
1331 }
1332
1333
1334
1335
1336 void mjpeg_delete(mjpeg_t *mjpeg)
1337 {
1338         int i;
1339 //printf("mjpeg_delete 1\n");
1340         for(i = 0; i < mjpeg->fields; i++)
1341         {
1342 //printf("mjpeg_delete 2\n");
1343                 if(mjpeg->compressors[i]) mjpeg_delete_compressor(mjpeg->compressors[i]);
1344 //printf("mjpeg_delete 3\n");
1345                 if(mjpeg->decompressors[i]) mjpeg_delete_decompressor(mjpeg->decompressors[i]);
1346 //printf("mjpeg_delete 4\n");
1347         }
1348 //printf("mjpeg_delete 5\n");
1349         delete_temps(mjpeg);
1350 //printf("mjpeg_delete 6\n");
1351         delete_buffer(&mjpeg->output_data, &mjpeg->output_size, &mjpeg->output_allocated);
1352 //printf("mjpeg_delete 7\n");
1353         free(mjpeg);
1354 //printf("mjpeg_delete 2\n");
1355 }
1356
1357
1358 /* Open up a space to insert a marker */
1359 static void insert_space(unsigned char **buffer,
1360         long *buffer_size,
1361         long *buffer_allocated,
1362         long space_start,
1363         long space_len)
1364 {
1365         int in, out;
1366 // Make sure enough space is available
1367         if(*buffer_allocated - *buffer_size < space_len)
1368         {
1369                 *buffer_allocated += space_len;
1370                 *buffer = realloc(*buffer, *buffer_allocated);
1371         }
1372
1373 // Shift data back
1374         for(in = *buffer_size - 1, out = *buffer_size - 1 + space_len;
1375                 in >= space_start;
1376                 in--, out--)
1377         {
1378                 (*buffer)[out] = (*buffer)[in];
1379         }
1380         *buffer_size += space_len;
1381 }
1382
1383
1384 static inline int nextbyte(unsigned char *data, long *offset, long length)
1385 {
1386         if(length - *offset < 1) return 0;
1387         *offset += 1;
1388         return (unsigned char)data[*offset - 1];
1389 }
1390
1391 static inline int read_int32(unsigned char *data, long *offset, long length)
1392 {
1393         if(length - *offset < 4)
1394         {
1395                 *offset = length;
1396                 return 0;
1397         }
1398         *offset += 4;
1399         return ((((unsigned int)data[*offset - 4]) << 24) |
1400                 (((unsigned int)data[*offset - 3]) << 16) |
1401                 (((unsigned int)data[*offset - 2]) << 8) |
1402                 (((unsigned int)data[*offset - 1])));
1403 }
1404
1405 static inline int read_int16(unsigned char *data, long *offset, long length)
1406 {
1407         if(length - *offset < 2)
1408         {
1409                 *offset = length;
1410                 return 0;
1411         }
1412
1413         *offset += 2;
1414         return ((((unsigned int)data[*offset - 2]) << 8) |
1415                 (((unsigned int)data[*offset - 1])));
1416 }
1417
1418 static inline unsigned char read_char(unsigned char *data, long *offset, long length)
1419 {
1420         if(length - *offset < 1)
1421         {
1422                 *offset = length;
1423                 return 0;
1424         }
1425
1426         *offset += 1;
1427         return (unsigned char)data[*offset - 1];
1428 }
1429
1430 static inline int next_int16(unsigned char *data, long *offset, long length)
1431 {
1432         if(length - *offset < 2)
1433         {
1434                 return 0;
1435         }
1436
1437         return ((((unsigned int)data[*offset]) << 8) |
1438                 (((unsigned int)data[*offset + 1])));
1439 }
1440
1441 static inline void write_int32(unsigned char *data, long *offset, long length, unsigned int value)
1442 {
1443         if(length - *offset < 4)
1444         {
1445                 *offset = length;
1446                 return;
1447         }
1448
1449
1450         data[(*offset)++] = (unsigned int)(value & 0xff000000) >> 24;
1451         data[(*offset)++] = (unsigned int)(value & 0xff0000) >> 16;
1452         data[(*offset)++] = (unsigned int)(value & 0xff00) >> 8;
1453         data[(*offset)++] = (unsigned char)(value & 0xff);
1454         return;
1455 }
1456
1457 static inline void write_char(unsigned char *data, long *offset, long length, unsigned char value)
1458 {
1459         if(length - *offset < 1)
1460         {
1461                 *offset = length;
1462                 return;
1463         }
1464
1465         data[(*offset)++] = value;
1466         return;
1467 }
1468
1469 static int next_marker(unsigned char *buffer, long *offset, long buffer_size)
1470 {
1471         while(*offset < buffer_size - 1) {
1472                 if(buffer[*offset] == 0xff && buffer[*offset + 1] != 0xff) {
1473                         (*offset) += 2;
1474                         return buffer[*offset - 1];
1475                 }
1476                 (*offset)++;
1477         }
1478         return 0;
1479 }
1480
1481 /* Find the next marker after offset and return 0 on success */
1482 static int find_marker(unsigned char *buffer,
1483         long *offset,
1484         long buffer_size,
1485         unsigned long marker_type)
1486 {
1487         long result = 0;
1488
1489         while(!result && *offset < buffer_size - 1)
1490         {
1491                 int marker = next_marker(buffer, offset, buffer_size);
1492                 if(marker == (marker_type & 0xff)) result = 1;
1493         }
1494
1495         return !result;
1496 }
1497
1498
1499 typedef struct
1500 {
1501         int field_size;
1502         int padded_field_size;
1503         int next_offset;
1504         int quant_offset;
1505         int huffman_offset;
1506         int image_offset;
1507         int scan_offset;
1508         int data_offset;
1509 } qt_hdr_t;
1510
1511 typedef struct
1512 {
1513         int field_number;
1514         int field_size;
1515         int unpadded_field_size;
1516 } avi_hdr_t;
1517
1518 #define LML_MARKER_SIZE 0x2c
1519 #define LML_MARKER_TAG 0xffe3
1520 void insert_lml33_markers(unsigned char **buffer,
1521         long *field2_offset,
1522         long *buffer_size,
1523         long *buffer_allocated)
1524 {
1525         long marker_offset = -1;
1526
1527 /* Search for existing marker to replace */
1528 //      marker_offset = find_marker(*buffer, *buffer_size, LML_MARKER_TAG);
1529
1530 /* Insert new marker */
1531         if(marker_offset < 0)
1532         {
1533                 marker_offset = 2;
1534                 insert_space(buffer,
1535                         buffer_size,
1536                         buffer_allocated,
1537                         2,
1538                         LML_MARKER_SIZE);
1539         }
1540 }
1541
1542 static int qt_table_offsets(unsigned char *buffer,
1543         long buffer_size,
1544         qt_hdr_t *header)
1545 {
1546         int done = 0;
1547         long offset = 0;
1548         int marker = 0;
1549         int field = 0;
1550         int len;
1551         int result = 0;
1552
1553         bzero(header, sizeof(qt_hdr_t) * 2);
1554
1555 // Read every marker to get the offsets for the headers
1556         for(field = 0; field < 2; field++)
1557         {
1558                 done = 0;
1559
1560                 while(!done)
1561                 {
1562                         marker = next_marker(buffer,
1563                                 &offset,
1564                                 buffer_size);
1565
1566                         len = 0;
1567
1568                         switch(marker)
1569                         {
1570                                 case M_SOI:
1571 // The first field may be padded
1572                                         if(field > 0)
1573                                         {
1574                                                 header[0].next_offset =
1575                                                         header[0].padded_field_size =
1576                                                         offset - 2;
1577                                         }
1578                                         len = 0;
1579                                         break;
1580
1581                                 case M_APP1:
1582 // Quicktime marker already exists.  Abort.
1583                                         if(buffer[offset + 6] == 'm' &&
1584                                                 buffer[offset + 7] == 'j' &&
1585                                                 buffer[offset + 8] == 'p' &&
1586                                                 buffer[offset + 9] == 'a')
1587                                         {
1588                                                 result = 1;
1589                                                 done = 1;
1590                                         }
1591                                         break;
1592
1593                                 case M_DQT:
1594                                         if(!header[field].quant_offset)
1595                                         {
1596                                                 header[field].quant_offset = offset - 2;
1597                                                 if(field > 0)
1598                                                         header[field].quant_offset -= header[0].next_offset;
1599                                         }
1600                                         len = read_int16(buffer, &offset, buffer_size);
1601                                         len -= 2;
1602                                         break;
1603
1604                                 case M_DHT:
1605                                         if(!header[field].huffman_offset)
1606                                         {
1607                                                 header[field].huffman_offset = offset - 2;
1608                                                 if(field > 0)
1609                                                         header[field].huffman_offset -= header[0].next_offset;
1610                                         }
1611                                         len = read_int16(buffer, &offset, buffer_size);
1612                                         len -= 2;
1613                                         break;
1614
1615                                 case M_SOF0:
1616                                         if(!header[field].image_offset)
1617                                         {
1618                                                 header[field].image_offset = offset - 2;
1619                                                 if(field > 0)
1620                                                         header[field].image_offset -= header[0].next_offset;
1621                                         }
1622                                         len = read_int16(buffer, &offset, buffer_size);
1623                                         len -= 2;
1624                                         break;
1625
1626                                 case M_SOS:
1627                                         header[field].scan_offset = offset - 2;
1628                                         if(field > 0)
1629                                                 header[field].scan_offset -= header[0].next_offset;
1630                                         len = read_int16(buffer, &offset, buffer_size);
1631                                         len -= 2;
1632                                         header[field].data_offset = offset + len;
1633                                         if(field > 0)
1634                                                 header[field].data_offset -= header[0].next_offset;
1635                                         break;
1636
1637 //                              case 0:
1638                                 case M_EOI:
1639                                         if(field > 0)
1640                                         {
1641                                                 header[field].field_size =
1642                                                         header[field].padded_field_size =
1643                                                         offset - header[0].next_offset;
1644                                                 header[field].next_offset = 0;
1645                                         }
1646                                         else
1647                                         {
1648 // Often misses second SOI but gets first EOI
1649 //                                              header[0].next_offset =
1650 //                                                      header[0].padded_field_size =
1651 //                                                      offset;
1652                                         }
1653 //printf("table_offsets M_EOI %d %x\n", field, offset);
1654                                         done = 1;
1655                                         len = 0;
1656                                         break;
1657
1658                                 default:
1659 // Junk appears between fields
1660                                         len = 0;
1661 //                                      len = read_int16(buffer, &offset, buffer_size);
1662 //                                      len -= 2;
1663                                         break;
1664                         }
1665
1666                         if(!done) offset += len;
1667                         if(offset >= buffer_size) done = 1;
1668                 }
1669 //printf("qt_table_offsets 10 %d\n", field);
1670         }
1671
1672         return result;
1673 }
1674
1675 static void insert_quicktime_marker(unsigned char *buffer,
1676         long buffer_size,
1677         long offset,
1678         qt_hdr_t *header)
1679 {
1680         write_int32(buffer, &offset, buffer_size, 0xff000000 |
1681                         ((unsigned long)M_APP1 << 16) |
1682                         (QUICKTIME_MARKER_SIZE - 2));
1683         write_int32(buffer, &offset, buffer_size, 0);
1684         write_int32(buffer, &offset, buffer_size, QUICKTIME_JPEG_TAG);
1685         write_int32(buffer, &offset, buffer_size, header->field_size);
1686         write_int32(buffer, &offset, buffer_size, header->padded_field_size);
1687         write_int32(buffer, &offset, buffer_size, header->next_offset);
1688         write_int32(buffer, &offset, buffer_size, header->quant_offset);
1689         write_int32(buffer, &offset, buffer_size, header->huffman_offset);
1690         write_int32(buffer, &offset, buffer_size, header->image_offset);
1691         write_int32(buffer, &offset, buffer_size, header->scan_offset);
1692         write_int32(buffer, &offset, buffer_size, header->data_offset);
1693 }
1694
1695
1696 void mjpeg_insert_quicktime_markers(unsigned char **buffer,
1697         long *buffer_size,
1698         long *buffer_allocated,
1699         int fields,
1700         long *field2_offset)
1701 {
1702         qt_hdr_t header[2];
1703         int exists = 0;
1704         *field2_offset = -1;
1705
1706         if(fields < 2) return;
1707
1708
1709 // Get offsets for tables in both fields
1710         exists = qt_table_offsets(*buffer, *buffer_size, header);
1711
1712 // APP1 for quicktime already exists
1713         if(exists) return;
1714
1715 //printf("mjpeg_insert_quicktime_markers %x %02x %02x\n",
1716 //      header[0].next_offset, (*buffer)[*field2_offset], (*buffer)[*field2_offset + 1]);
1717 //if(*field2_offset == 0)
1718 //      fwrite(*buffer, *buffer_size, 1, stdout);
1719
1720
1721
1722         header[0].field_size += QUICKTIME_MARKER_SIZE;
1723         header[0].padded_field_size += QUICKTIME_MARKER_SIZE;
1724         header[0].next_offset += QUICKTIME_MARKER_SIZE;
1725         header[0].quant_offset += QUICKTIME_MARKER_SIZE;
1726         header[0].huffman_offset += QUICKTIME_MARKER_SIZE;
1727         header[0].image_offset += QUICKTIME_MARKER_SIZE;
1728         header[0].scan_offset += QUICKTIME_MARKER_SIZE;
1729         header[0].data_offset += QUICKTIME_MARKER_SIZE;
1730         header[1].field_size += QUICKTIME_MARKER_SIZE;
1731         header[1].padded_field_size += QUICKTIME_MARKER_SIZE;
1732         header[1].quant_offset += QUICKTIME_MARKER_SIZE;
1733         header[1].huffman_offset += QUICKTIME_MARKER_SIZE;
1734         header[1].image_offset += QUICKTIME_MARKER_SIZE;
1735         header[1].scan_offset += QUICKTIME_MARKER_SIZE;
1736         header[1].data_offset += QUICKTIME_MARKER_SIZE;
1737         *field2_offset = header[0].next_offset;
1738
1739
1740
1741 // Insert APP1 marker
1742         insert_space(buffer,
1743                 buffer_size,
1744                 buffer_allocated,
1745                 2,
1746                 QUICKTIME_MARKER_SIZE);
1747
1748         insert_quicktime_marker(*buffer,
1749                 *buffer_size,
1750                 2,
1751                 &header[0]);
1752
1753         insert_space(buffer,
1754                 buffer_size,
1755                 buffer_allocated,
1756                 header[0].next_offset + 2,
1757                 QUICKTIME_MARKER_SIZE);
1758
1759         header[1].next_offset = 0;
1760         insert_quicktime_marker(*buffer,
1761                 *buffer_size,
1762                 header[0].next_offset + 2,
1763                 &header[1]);
1764 }
1765
1766
1767 static int avi_table_offsets(unsigned char *buffer,
1768         long buffer_size,
1769         avi_hdr_t *header)
1770 {
1771         int field2 = mjpeg_get_field2(buffer, buffer_size);
1772
1773         header[0].field_number = 1;
1774         header[0].field_size = field2;
1775         header[0].unpadded_field_size = field2;
1776
1777         header[1].field_number = 2;
1778         header[1].field_size = buffer_size - field2;
1779         header[1].unpadded_field_size = buffer_size - field2;
1780         return 0;
1781 }
1782
1783 static void insert_avi_marker(unsigned char *buffer,
1784         long buffer_size,
1785         long offset,
1786         avi_hdr_t *header)
1787 {
1788         write_int32(buffer, &offset, buffer_size, 0xff000000 |
1789                         ((unsigned long)M_APP0 << 16) |
1790                         (AVI_MARKER_SIZE - 2));
1791         write_int32(buffer, &offset, buffer_size, QUICKTIME_AVI_TAG);
1792
1793 // One version of McRoweSoft only allows field polarity while
1794 // another version allows field size.
1795         write_char(buffer, &offset, buffer_size, header->field_number);
1796         write_char(buffer, &offset, buffer_size, 0);
1797         write_int32(buffer, &offset, buffer_size, header->field_size);
1798         write_int32(buffer, &offset, buffer_size, header->unpadded_field_size);
1799 }
1800
1801 void mjpeg_insert_avi_markers(unsigned char **buffer,
1802         long *buffer_size,
1803         long *buffer_allocated,
1804         int fields,
1805         long *field2_offset)
1806 {
1807         avi_hdr_t header[2];
1808         long offset = 0;
1809         *field2_offset = -1;
1810
1811
1812 // Test for existing marker
1813         if(!find_marker(*buffer, &offset, *buffer_size, M_APP0))
1814         {
1815                 if((*buffer)[offset + 2] == 'A' &&
1816                         (*buffer)[offset + 3] == 'V' &&
1817                         (*buffer)[offset + 4] == 'I' &&
1818                         (*buffer)[offset + 5] == '1')
1819                         return;
1820         }
1821
1822
1823         avi_table_offsets(*buffer, *buffer_size, header);
1824
1825         header[0].field_size += AVI_MARKER_SIZE;
1826         header[0].unpadded_field_size += AVI_MARKER_SIZE;
1827         header[1].field_size += AVI_MARKER_SIZE;
1828         header[1].unpadded_field_size += AVI_MARKER_SIZE;
1829         *field2_offset = header[0].field_size;
1830
1831 // Insert APP0 marker into field 1
1832         insert_space(buffer,
1833                 buffer_size,
1834                 buffer_allocated,
1835                 2,
1836                 AVI_MARKER_SIZE);
1837         insert_avi_marker(*buffer,
1838                 *buffer_size,
1839                 2,
1840                 &header[0]);
1841
1842         insert_space(buffer,
1843                 buffer_size,
1844                 buffer_allocated,
1845                 *field2_offset + 2,
1846                 AVI_MARKER_SIZE);
1847         insert_avi_marker(*buffer,
1848                 *buffer_size,
1849                 *field2_offset + 2,
1850                 &header[1]);
1851
1852
1853
1854 }
1855
1856
1857 static void read_avi_markers(unsigned char *buffer,
1858         long buffer_size,
1859         avi_hdr_t *header)
1860 {
1861         long offset = 0;
1862         int marker_count = 0;
1863         int result = 0;
1864         int marker_size = 0;
1865         while(marker_count < 2 && offset < buffer_size && !result)
1866         {
1867                 result = find_marker(buffer,
1868                         &offset,
1869                         buffer_size,
1870                         M_APP0);
1871                 marker_size = ((unsigned char)buffer[offset] << 8) | (unsigned char)buffer[offset];
1872
1873
1874                 if(!result && marker_size >= 16)
1875                 {
1876 // Marker size, AVI1
1877                         offset += 6;
1878 // field polarity
1879                         header[marker_count].field_number = read_char(buffer, &offset, buffer_size);
1880                         read_char(buffer, &offset, buffer_size);
1881                         header[marker_count].field_size = read_int32(buffer, &offset, buffer_size);
1882                         header[marker_count].unpadded_field_size = read_int32(buffer, &offset, buffer_size);
1883                         marker_count++;
1884                 }
1885         }
1886 }
1887
1888
1889 static void read_quicktime_markers(unsigned char *buffer,
1890         long buffer_size,
1891         qt_hdr_t *header)
1892 {
1893         long offset = 0;
1894         int marker_count = 0;
1895         int result = 0;
1896
1897         while(marker_count < 2 && offset < buffer_size && !result)
1898         {
1899                 result = find_marker(buffer,
1900                         &offset,
1901                         buffer_size,
1902                         M_APP1);
1903
1904                 if(!result)
1905                 {
1906 // Marker size
1907                         read_int16(buffer, &offset, buffer_size);
1908 // Zero
1909                         read_int32(buffer, &offset, buffer_size);
1910 // MJPA
1911                         read_int32(buffer, &offset, buffer_size);
1912 // Information
1913                         header[marker_count].field_size = read_int32(buffer, &offset, buffer_size);
1914                         header[marker_count].padded_field_size = read_int32(buffer, &offset, buffer_size);
1915                         header[marker_count].next_offset = read_int32(buffer, &offset, buffer_size);
1916                         header[marker_count].quant_offset = read_int32(buffer, &offset, buffer_size);
1917                         header[marker_count].huffman_offset = read_int32(buffer, &offset, buffer_size);
1918                         header[marker_count].image_offset = read_int32(buffer, &offset, buffer_size);
1919                         header[marker_count].scan_offset = read_int32(buffer, &offset, buffer_size);
1920                         header[marker_count].data_offset = read_int32(buffer, &offset, buffer_size);
1921                         marker_count++;
1922                 }
1923         }
1924 //printf("read_quicktime_markers 1 %d\n", marker_count);
1925 }
1926
1927 long mjpeg_get_quicktime_field2(unsigned char *buffer, long buffer_size)
1928 {
1929         qt_hdr_t header[2];
1930         bzero(&header, sizeof(qt_hdr_t) * 2);
1931
1932         read_quicktime_markers(buffer, buffer_size, header);
1933         return header[0].next_offset;
1934 }
1935
1936 long mjpeg_get_avi_field2(unsigned char *buffer,
1937         long buffer_size,
1938         int *field_dominance)
1939 {
1940         avi_hdr_t header[2];
1941         bzero(&header, sizeof(avi_hdr_t) * 2);
1942         read_avi_markers(buffer, buffer_size, header);
1943
1944         *field_dominance = (header[0].field_number == 1) ? 1 : 2;
1945
1946 // One version of McRoweSoft only allows field polarity while
1947 // another version allows field size.
1948         if(header[0].field_size)
1949         {
1950                 return header[0].field_size;
1951         }
1952         else
1953         {
1954                 return mjpeg_get_field2(buffer, buffer_size);
1955         }
1956         return 0;
1957 }
1958
1959 long mjpeg_get_field2(unsigned char *buffer, long buffer_size)
1960 {
1961         int total_fields = 0;
1962         long field2_offset = 0;
1963         int i;
1964
1965         for(i = 0; i < buffer_size; i++)
1966         {
1967                 if(buffer[i] == 0xff && buffer[i + 1] == M_SOI)
1968                 {
1969                         total_fields++;
1970                         field2_offset = i;
1971                         if(total_fields == 2) break;
1972                 }
1973         }
1974         return field2_offset;
1975 }
1976
1977 void mjpeg_video_size(unsigned char *data, long data_size, int *w, int *h)
1978 {
1979           long offset = 0;
1980           find_marker(data,
1981                           &offset,
1982                           data_size,
1983                           M_SOF0);
1984           *h = (data[offset + 3] << 8) | (data[offset + 4]);
1985           *w = (data[offset + 5] << 8) | (data[offset + 6]);
1986 }
1987
1988