544e7c9308ccef5b1edf990cf23bf5e9ed1f240a
[swftools.git] / src / jpeg2swf.c
1 /* jpeg2swf.c
2
3    JPEG to SWF converter tool
4
5    Part of the swftools package.
6
7    Copyright (c) 2001 Rainer Böhme <rfxswf@reflex-studio.de>
8    Copyright (c) 2002,2003 Matthias Kramm <kramm@quiss.org>
9  
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
23  
24 #include <stdio.h>
25 #include <math.h>
26 #include <fcntl.h>
27 #include <jpeglib.h>
28 #include "../lib/rfxswf.h"
29 #include "../lib/args.h"        // not really a header ;-)
30
31 #define MAX_INPUT_FILES 1024
32 #define VERBOSE(x) (global.verbose>=x)
33
34 struct {
35     int quality;
36     float framerate;
37     int max_image_width;
38     int max_image_height;
39     int force_width;
40     int force_height;
41     int nfiles;
42     int verbose;
43     char *outfile;
44     int mx;
45     int next_id;
46     char *asset_name;
47     int version;
48     int fit_to_movie;
49     float scale;
50 } global;
51
52 static int custom_move=0;
53 static int move_x=0;
54 static int move_y=0;
55 static int clip_x1=0,clip_y1=0,clip_x2=0,clip_y2=0;
56 static int custom_clip = 0;
57
58 typedef struct _image {
59     char *filename;
60     int quality;
61     int width;
62     int height;
63 } image_t;
64 image_t image[MAX_INPUT_FILES];
65
66 VIDEOSTREAM stream;
67
68 TAG *MovieStart(SWF * swf, float framerate, int dx, int dy)
69 {
70     TAG *t;
71     RGBA rgb;
72
73     memset(swf, 0x00, sizeof(SWF));
74
75     swf->fileVersion = global.version;
76     swf->frameRate = (int)(256.0 * framerate);
77
78     if(custom_clip) {
79         swf->movieSize.xmin = clip_x1 * 20;
80         swf->movieSize.ymin = clip_y1 * 20;
81         swf->movieSize.xmax = clip_x2 * 20;
82         swf->movieSize.ymax = clip_y2 * 20;
83     } else {
84         swf->movieSize.xmin = 0;
85         swf->movieSize.ymin = 0;
86         swf->movieSize.xmax = swf->movieSize.xmin + dx * 20;
87         swf->movieSize.ymax = swf->movieSize.ymin + dy * 20;
88     }
89
90     t = swf->firstTag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
91
92     rgb.r = rgb.g = rgb.b = rgb.a = 0x00;
93     swf_SetRGB(t, &rgb);
94
95     if (global.mx) {
96         t = swf_InsertTag(t, ST_DEFINEVIDEOSTREAM);
97         swf_SetU16(t, 0xf00d);
98         swf_SetVideoStreamDefine(t, &stream, 65535, dx, dy);
99     } else if (global.asset_name) {
100         t = swf_InsertTag(t, ST_DEFINESPRITE);
101         swf_SetU16(t, 1);
102         swf_SetU16(t, global.next_id++);
103     }
104
105     return t;
106 }
107
108 int MovieFinish(SWF * swf, TAG * t, char *sname)
109 {
110     int handle, so = fileno(stdout);
111
112     if (global.asset_name) {
113         SWFPLACEOBJECT obj;
114
115         t = swf_InsertTag(t, ST_END);
116         t = swf_InsertTag(t, ST_EXPORTASSETS);
117         swf_SetU16(t, 1);
118         swf_SetU16(t, 1);
119         swf_SetString(t, global.asset_name);
120
121         t = swf_InsertTag(t, ST_PLACEOBJECT2);
122         swf_GetPlaceObject(0, &obj);
123         obj.depth = 1;
124         obj.id = 1;
125         swf_SetPlaceObject(t, &obj);
126
127         t = swf_InsertTag(t, ST_SHOWFRAME);
128     }
129
130     t = swf_InsertTag(t, ST_END);
131
132     if ((!isatty(so)) && (!sname))
133         handle = so;
134     else {
135         if (!sname)
136             sname = "output.swf";
137         handle = open(sname, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0666);
138     }
139     if (swf_WriteSWF(handle, swf)<0) 
140         fprintf(stderr, "Unable to write output file: %s\n", sname);
141
142     if (handle != so)
143         close(handle);
144
145     swf_FreeTags(swf);
146     return 0;
147 }
148
149 int getJPEG(char*filename, int* width, int* height, RGBA**pic2)
150 {
151     struct jpeg_decompress_struct cinfo;
152     struct jpeg_error_mgr jerr;
153     struct jpeg_source_mgr mgr;
154     int x,y;
155     FILE*f;
156     RGBA*pic,*js;
157     U8*buf;
158
159     if ((f=fopen(filename,"rb"))==NULL) {
160         fprintf(stderr, "rfxswf: file open error\n");
161         return 0;
162     }
163
164     cinfo.err = jpeg_std_error(&jerr);
165     jpeg_create_decompress(&cinfo); 
166     jpeg_stdio_src(&cinfo, f);
167     jpeg_read_header(&cinfo, TRUE);
168     jpeg_start_decompress(&cinfo);
169
170     pic = malloc(cinfo.output_width*cinfo.output_height*sizeof(RGBA));
171     buf = malloc(cinfo.output_width*4);
172     memset(pic, 255, cinfo.output_width*cinfo.output_height*sizeof(RGBA));
173     js = pic;
174
175     *width = cinfo.output_width;
176     *height = cinfo.output_height;
177     
178     for (y=0;y<cinfo.output_height;y++) {
179         int x;
180         jpeg_read_scanlines(&cinfo,&buf,1);
181
182         if(cinfo.out_color_space == JCS_GRAYSCALE) {
183             for(x=0;x<cinfo.output_width;x++) {
184                 js[x].r = js[x].g = js[x].b = buf[x];
185             }
186         } else if(cinfo.out_color_space == JCS_RGB) {
187             for (x=0;x<cinfo.output_width;x++)
188             { 
189                 js[x].r = buf[x*3+0];
190                 js[x].g = buf[x*3+1];
191                 js[x].b = buf[x*3+2];
192             }
193         } else if(cinfo.out_color_space == JCS_YCCK) {
194             //FIXME
195             fprintf(stderr, "Error: Can't convert YCCK to RGB.\n");
196             return -1;
197         } else if(cinfo.out_color_space == JCS_YCbCr) {
198             for(x=0;x<cinfo.output_width;x++) {
199                 int y = buf[x*3+0];
200                 int u = buf[x*3+1];
201                 int v = buf[x*3+1];
202                 js[x].r = y + ((360*(v-128))>>8);
203                 js[x].g = y - ((88*(u-128)+183*(v-128))>>8);
204                 js[x].b = y + ((455 * (u-128))>>8);
205             }
206         }
207         else if(cinfo.out_color_space == JCS_CMYK) 
208         { 
209             for(x=0;x<cinfo.output_width;x++) {
210                   int white = 255 - buf[x*4+3];
211                   js[x].r = white - ((buf[x*4]*white)>>8);
212                   js[x].g = white - ((buf[x*4+1]*white)>>8);
213                   js[x].b = white - ((buf[x*4+2]*white)>>8);
214             }
215         }
216         js += cinfo.output_width;
217     }
218
219     jpeg_finish_decompress(&cinfo);
220     jpeg_destroy_decompress(&cinfo);
221     
222     free(buf);
223     *pic2 = pic;
224     return 1;
225 }
226
227
228 int frame = 0;
229 TAG *MovieAddFrame(SWF * swf, TAG * t, char *sname, int quality, 
230                    int width, int height)
231 {
232     SHAPE *s;
233     SRECT r;
234     MATRIX m;
235     int fs;
236     int movie_width = swf->movieSize.xmax - swf->movieSize.xmin;
237     int movie_height = swf->movieSize.ymax - swf->movieSize.ymin;
238
239     if(global.mx) {
240         int sizex, sizey;
241         RGBA * pic2;
242         SWFPLACEOBJECT obj;
243         int quant=0;
244         getJPEG(sname, &sizex, &sizey, &pic2);
245         if(sizex != stream.owidth || sizey != stream.oheight) {
246             fprintf(stderr, "All images must have the same dimensions if using -m!");
247             exit(1);
248         }
249
250         t = swf_InsertTag(t, ST_VIDEOFRAME);
251         swf_SetU16(t, 0xf00d);
252         quant = 1+(30-(30*quality)/100);
253         if(!(frame%20)) {
254             swf_SetVideoStreamIFrame(t, &stream, pic2, quant);
255         } else {
256             swf_SetVideoStreamPFrame(t, &stream, pic2, quant);
257         }
258
259         t = swf_InsertTag(t, ST_PLACEOBJECT2);
260         swf_GetPlaceObject(0, &obj);
261         if(frame==0) {
262             obj.depth = 1;
263             obj.id = 0xf00d;
264         } else {
265             obj.depth = 1;
266             obj.move = 1;
267             obj.ratio = frame;
268         }
269         swf_SetPlaceObject(t,&obj);
270
271         t = swf_InsertTag(t, ST_SHOWFRAME);
272     } else {
273         t = swf_InsertTag(t, ST_DEFINEBITSJPEG2);
274         swf_SetU16(t, global.next_id);          // id
275         swf_SetJPEGBits(t,sname,quality);
276
277         t = swf_InsertTag(t, ST_DEFINESHAPE);
278         swf_ShapeNew(&s);
279         swf_GetMatrix(NULL, &m);
280         if (global.fit_to_movie) {
281             m.sx = 0x10000 * movie_width / width;
282             m.sy = 0x10000 * movie_height / height;
283             width = movie_width / 20;
284             height = movie_height / 20;
285         } else {
286             m.sx = 20 * 0x10000;
287             m.sy = 20 * 0x10000;
288         }
289         m.tx = 0;
290         m.ty = 0;
291         fs = swf_ShapeAddBitmapFillStyle(s, &m, global.next_id, 1);
292         global.next_id++;
293         swf_SetU16(t, global.next_id);  // id
294         r.xmin = 0;
295         r.ymin = 0;
296         r.xmax = r.xmin + width * 20;
297         r.ymax = r.ymin + height * 20;
298         swf_SetRect(t, &r);
299         swf_SetShapeHeader(t, s);
300         swf_ShapeSetAll(t, s, r.xmin, r.ymin, 0, fs, 0);
301         swf_ShapeSetLine(t, s, r.xmax - r.xmin, 0);
302         swf_ShapeSetLine(t, s, 0, r.ymax - r.ymin);
303         swf_ShapeSetLine(t, s, -r.xmax + r.xmin, 0);
304         swf_ShapeSetLine(t, s, 0, -r.ymax + r.ymin);
305         swf_ShapeSetEnd(t);
306
307         if(frame) {
308             t = swf_InsertTag(t, ST_REMOVEOBJECT2);
309             swf_SetU16(t, 1);           // depth
310         }
311
312         t = swf_InsertTag(t, ST_PLACEOBJECT2);
313         swf_GetMatrix(NULL, &m);
314         m.sx = (int)(0x10000 * global.scale);
315         m.sy = (int)(0x10000 * global.scale);
316
317         if(custom_move) {
318             m.tx = move_x*20;
319             m.ty = move_y*20;
320         } else {
321             m.tx = (movie_width - (width * global.scale * 20)) / 2;
322             m.ty = (movie_height - (height * global.scale * 20)) / 2;
323         }
324         swf_ObjectPlace(t, global.next_id, 1, &m, NULL, NULL);
325         global.next_id++;
326         t = swf_InsertTag(t, ST_SHOWFRAME);
327     }
328     frame++;
329
330     return t;
331 }
332
333 int CheckInputFile(image_t* i, char *fname, char **realname)
334 {
335     struct jpeg_decompress_struct cinfo;
336     struct jpeg_error_mgr jerr;
337     FILE *f;
338     char *s = malloc(strlen(fname) + 5);
339     int width, height;
340
341     if (!s)
342         exit(2);
343     (*realname) = s;
344     strcpy(s, fname);
345
346     // Check whether file exists (with typical extensions)
347
348     if ((f = fopen(s, "rb")) == NULL) {
349         sprintf(s, "%s.jpg", fname);
350         if ((f = fopen(s, "rb")) == NULL) {
351             sprintf(s, "%s.jpeg", fname);
352             if ((f = fopen(s, "rb")) == NULL) {
353                 sprintf(s, "%s.JPG", fname);
354                 if ((f = fopen(s, "rb")) == NULL) {
355                     sprintf(s, "%s.JPEG", fname);
356                     if ((f = fopen(s, "rb")) == NULL)
357                         return -1;
358                 }
359             }
360         }
361     }
362
363     cinfo.err = jpeg_std_error(&jerr);
364     jpeg_create_decompress(&cinfo);
365     jpeg_stdio_src(&cinfo, f);
366     jpeg_read_header(&cinfo, TRUE);
367
368     width = cinfo.image_width;
369     height = cinfo.image_height;
370
371     i->width = width;
372     i->height = height;
373
374     // Get image dimensions
375
376     if (global.max_image_width < width)
377         global.max_image_width = width;
378     if (global.max_image_height < height)
379         global.max_image_height = height;
380
381     jpeg_destroy_decompress(&cinfo);
382     fclose(f);
383
384     return 0;
385 }
386
387 int args_callback_option(char *arg, char *val)
388 {
389     int res = 0;
390     if (arg[1])
391         res = -1;
392     else
393         switch (arg[0]) {
394         case 'q':
395             if (val)
396                 global.quality = atoi(val);
397             if ((global.quality < 1) ||(global.quality > 100)) {
398                 if (VERBOSE(1))
399                     fprintf(stderr,
400                             "Error: You must specify a valid quality between 1 and 100.\n");
401                 exit(1);
402             }
403             res = 1;
404             break;
405
406         case 'r':
407             if (val)
408                 global.framerate = atof(val);
409             if ((global.framerate < 1.0/256) || (global.framerate >= 256.0)) {
410                 if (VERBOSE(1))
411                     fprintf(stderr,
412                             "Error: You must specify a valid framerate between 1 and 10000.\n");
413                 exit(1);
414             }
415             res = 1;
416             break;
417
418         case 'o':
419             if (val)
420                 global.outfile = val;
421             res = 1;
422             break;
423
424         case 'v':
425             global.verbose++;
426             res = 0;
427             break;
428
429 /*      case 'q':
430             global.verbose--;
431             if(global.verbose<0)
432                 global.verbose = 0;
433             res = 0;
434             break;*/
435
436         case 'X':
437             if (val)
438                 global.force_width = atoi(val);
439             res = 1;
440             break;
441
442         case 'z':
443             global.version = 6;
444             return 0;
445
446         case 'Y':
447             if (val)
448                 global.force_height = atoi(val);
449             res = 1;
450             break;
451
452         case 'V':
453             printf("jpeg2swf - part of %s %s\n", PACKAGE, VERSION);
454             exit(0);
455
456         case 'e':
457             if (val)
458                 global.asset_name = val;
459             res = 1;
460             break;
461         
462         case 'T':
463             global.version = atoi(val);
464             res = 1;
465             break;
466
467         case 'f':
468             global.fit_to_movie = 1;
469             res = 0;
470             break;
471         
472         case 'c': {
473             char*s = strdup(val);
474             char*x1 = strtok(s, ":");
475             char*y1 = strtok(0, ":");
476             char*x2 = strtok(0, ":");
477             char*y2 = strtok(0, ":");
478             if(!(x1 && y1 && x2 && y2)) {
479                 fprintf(stderr, "-m option requires four arguments, <x1>:<y1>:<x2>:<y2>\n");
480                 exit(1);
481             }
482             custom_clip = 1;
483             clip_x1 = atoi(x1);
484             clip_y1 = atoi(y1);
485             clip_x2 = atoi(x2);
486             clip_y2 = atoi(y2);
487             free(s);
488
489             res = 1;
490             break;
491         }
492
493         case 'M': {
494             global.mx = 1;
495             res = 1;
496             break;
497         }
498
499         case 'm': {
500             char*s = strdup(val);
501             char*c = strchr(s, ':');
502             if(!c) {
503                 fprintf(stderr, "-m option requires two arguments, <x>:<y>\n");
504                 exit(1);
505             }
506             *c = 0;
507             custom_move = 1;
508             move_x = atoi(val);
509             move_y = atoi(c+1);
510             free(s);
511
512             res = 1;
513             break;
514         }
515         
516         case 's': {
517             global.scale = atof(val)/100;
518             res = 1;
519             break;
520         }
521
522         default:
523             res = -1;
524             break;
525         }
526
527     if (res < 0) {
528         if (VERBOSE(1))
529             fprintf(stderr, "Unknown option: -%s\n", arg);
530         exit(1);
531         return 0;
532     }
533     return res;
534 }
535
536 static struct options_t options[] = {
537 {"o", "output"},
538 {"q", "quality"},
539 {"r", "rate"},
540 {"z", "zlib"},
541 {"M", "mx"},
542 {"x", "xoffset"},
543 {"y", "yoffset"},
544 {"X", "width"},
545 {"Y", "height"},
546 {"v", "verbose"},
547 {"V", "version"},
548 {"f", "fit-to-movie"},
549 {"e", "export"},
550 {0,0}
551 };
552
553 int args_callback_longoption(char *name, char *val)
554 {
555     return args_long2shortoption(options, name, val);
556 }
557
558 int args_callback_command(char *arg, char *next)        // actually used as filename
559 {
560     char *s;
561     image_t* i = &image[global.nfiles];
562     if (CheckInputFile(i, arg, &s) < 0) {
563         if (VERBOSE(1))
564             fprintf(stderr, "Unable to open input file: %s\n", arg);
565         free(s);
566     } else {
567         i->filename = s;
568         i->quality = global.quality;
569         global.nfiles++;
570         if (global.nfiles >= MAX_INPUT_FILES) {
571             if (VERBOSE(1))
572                 fprintf(stderr, "Error: Too many input files.\n");
573             exit(1);
574         }
575     }
576     return 0;
577 }
578
579 void args_callback_usage(char *name)
580 {
581     printf("\n");
582     printf("Usage: %s [-options [value]] imagefiles[.jpg]|[.jpeg] [...]\n", name);
583     printf("\n");
584     printf("-o , --output <outputfile>     Explicitly specify output file. (otherwise, output.swf will be used)\n");
585     printf("-q , --quality <quality>       Set compression quality (1-100, 1=worst, 100=best)\n");
586     printf("-r , --rate <framerate>        Set movie framerate (frames per second)\n");
587     printf("-z , --zlib <zlib>             Enable Flash 6 (MX) Zlib Compression\n");
588     printf("-M , --mx                      Use Flash MX H.263 compression (use for correlated images)\n");
589     printf("-x , --xoffset <offset>        horizontally offset images by <offset>\n");
590     printf("-y , --yoffset <offset>        vertically offset images by <offset>\n");
591     printf("-X , --width <width>           Force movie width to <width> (default: autodetect)\n");
592     printf("-Y , --height <height>         Force movie height to <height> (default: autodetect)\n");
593     printf("-v , --verbose <level>         Set verbose level to <level> (0=quiet, 1=default, 2=debug)\n");
594     printf("-V , --version                 Print version information and exit\n");
595     printf("-f , --fit-to-movie            Fit images to movie size\n");
596     printf("-e , --export <assetname>          Make importable as asset with <assetname>\n");
597     printf("\n");
598 }
599
600
601 int main(int argc, char **argv)
602 {
603     SWF swf;
604     TAG *t;
605
606     memset(&global, 0x00, sizeof(global));
607
608     global.quality = 60;
609     global.framerate = 1.0;
610     global.verbose = 1;
611     global.version = 4;
612     global.asset_name = NULL;
613     global.next_id = 1;
614     global.fit_to_movie = 0;
615     global.scale = 1.0;
616         
617     processargs(argc, argv);
618
619     if (VERBOSE(2))
620         fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
621
622     t = MovieStart(&swf, global.framerate,
623                    global.force_width ? global.force_width : (int)(global.max_image_width*global.scale),
624                    global.force_height ? global.force_height : (int)(global.max_image_height*global.scale));
625
626     {
627         int i;
628         for (i = 0; i < global.nfiles; i++) {
629             if (VERBOSE(3))
630                 fprintf(stderr, "[%03i] %s (%i%%, 1/%i)\n", i,
631                         image[i].filename, image[i].quality);
632             t = MovieAddFrame(&swf, t, image[i].filename, image[i].quality,
633                               image[i].width, image[i].height);
634             free(image[i].filename);
635         }
636     }
637
638     MovieFinish(&swf, t, global.outfile);
639
640     return 0;
641 }