fixed preloader rate reading if BACKTICKS isn't set
[swftools.git] / pdf2swf / pdf2swf.cc
1 /* pdf2swf.cc
2    main routine for pdf2swf(1)
3
4    Part of the swftools package.
5    
6    Copyright (c) 2001,2002,2003 Matthias Kramm <kramm@quiss.org> 
7  
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include "../config.h"
28 #ifdef HAVE_DIRENT_H
29 #include <dirent.h>
30 #endif
31 #ifdef HAVE_SYS_STAT_H
32 #include <sys/stat.h>
33 #endif
34 #include "../lib/args.h"
35 #include "../lib/os.h"
36 #include "../lib/rfxswf.h"
37 #include "SWFOutputDev.h"
38 #include "log.h"
39
40 #define FONTDIR concatPaths(getInstallationPath(), "fonts")
41 #define SWFDIR concatPaths(getInstallationPath(), "swfs")
42
43 static char * outputname = 0;
44 static int loglevel = 3;
45 static char * pagerange = 0;
46 static char * filename = 0;
47 static char * password = 0;
48 static int zlib = 0;
49
50 static char * preloader = 0;
51 static char * viewer = 0;
52 static int xnup = 1;
53 static int ynup = 1;
54
55 char* fontpaths[256];
56 int fontpathpos = 0;
57
58 static int system_quiet=0;
59
60 int systemf(const char* format, ...)
61 {
62     char buf[1024];
63     int ret;
64     va_list arglist;
65     va_start(arglist, format);
66     vsprintf(buf, format, arglist);
67     va_end(arglist);
68
69     if(!system_quiet) {
70         printf("%s\n", buf);
71         fflush(stdout);
72     }
73     ret = system(buf);
74     if(ret) {
75         fprintf(stderr, "system() returned %d\n", ret);
76         exit(ret);
77     }
78     return ret;
79 }
80
81 int args_callback_option(char*name,char*val) {
82     if (!strcmp(name, "o"))
83     {
84         outputname = val;
85         return 1;
86     }
87     else if (!strcmp(name, "v"))
88     {
89         loglevel ++;
90         setConsoleLogging(loglevel);
91         return 0;
92     }
93     else if (!strcmp(name, "2"))
94     {
95         xnup = 2;
96         ynup = 1;
97         return 0;
98     }
99     else if (!strcmp(name, "4"))
100     {
101         xnup = 2;
102         ynup = 2;
103         return 0;
104     }
105     else if (!strcmp(name, "9"))
106     {
107         xnup = 3;
108         ynup = 3;
109         return 0;
110     }
111     else if (!strcmp(name, "q"))
112     {
113         loglevel --;
114         setConsoleLogging(loglevel);
115         system_quiet = 1;
116         return 0;
117     }
118     else if (name[0]=='p')
119     {
120         /* check whether the page range follows the p directly, like 
121            in -p1,2 */
122         do {
123             name++;
124         } while(*name == 32 || *name == 13 || *name == 10 || *name == '\t');
125
126         if(*name) {
127             pagerange = name;
128             return 0;
129         } 
130         pagerange = val;        
131         return 1;
132     }
133     else if (!strcmp(name, "P"))
134     {
135         password = val;
136         return 1;
137     }
138     else if (!strcmp(name, "s"))
139     {
140         char*s = strdup(val);
141         char*c = strchr(s, '=');
142         if(c && *c && c[1])  {
143             *c = 0;
144             c++;
145             pdfswf_setparameter(s,c);
146         }
147         else
148             pdfswf_setparameter(s,"1");
149         return 1;
150     }
151     else if (!strcmp(name, "S"))
152     {
153         pdfswf_setparameter("drawonlyshapes", "1");
154         return 0;
155     }
156     else if (!strcmp(name, "i"))
157     {
158         pdfswf_setparameter("ignoredraworder", "1");
159         return 0;
160     }
161     else if (!strcmp(name, "z"))
162     {
163         pdfswf_setparameter("enablezlib", "1");
164         zlib = 1;
165         return 0;
166     }
167     else if (!strcmp(name, "n"))
168     {
169         pdfswf_setparameter("opennewwindow", "1");
170         return 0;
171     }
172     else if (!strcmp(name, "t"))
173     {
174         pdfswf_setparameter("insertstop", "1");
175         return 0;
176     }
177     else if (!strcmp(name, "T"))
178     {
179         if(!strcasecmp(val, "mx"))
180             pdfswf_setparameter("flashversion", "6");
181         else
182             pdfswf_setparameter("flashversion", val);
183
184         return 1;
185     }
186     else if (!strcmp(name, "f"))
187     {
188         pdfswf_setparameter("storeallcharacters", "1");
189         return 0;
190     }
191     else if (!strcmp(name, "w"))
192     {
193         pdfswf_setparameter("linksopennewwindow", "0");
194         return 0;
195     }
196     else if (!strcmp(name, "F"))
197     {
198         char *s = strdup(val);
199         int l = strlen(s);
200         while(l && s[l-1]=='/') {
201             s[l-1] = 0;
202             l--;
203         }
204         fontpaths[fontpathpos++] = s;
205         return 1;
206     }
207     else if (!strcmp(name, "l"))
208     {
209         char buf[256];
210         sprintf(buf, "%s/default_loader.swf", SWFDIR);
211         preloader = strdup(buf);
212         return 0;
213     }
214     else if (!strcmp(name, "b"))
215     {
216         char buf[256];
217         sprintf(buf, "%s/default_viewer.swf", SWFDIR);
218         viewer = strdup(buf);
219         return 0;
220     }
221     else if (!strcmp(name, "L"))
222     {
223         if(val)
224         {
225             preloader = val;
226         }
227         else
228         {
229             systemf("ls %s/*_loader.swf", SWFDIR);
230             if(!system_quiet)
231                 printf("\n");
232             exit(1);
233         }
234         return 1;
235     }
236     else if (!strcmp(name, "B"))
237     {
238         if(val)
239         {
240             viewer = val;
241         }
242         else
243         {
244             systemf("ls %s/*_viewer.swf", SWFDIR);
245             if(!system_quiet)
246                 printf("\n");
247             exit(1);
248         }
249         return 1;
250     }
251     else if (!strcmp(name, "j"))
252     {
253         if(name[1]) {
254             pdfswf_setparameter("jpegquality", &name[1]);
255             return 0;
256         } else {
257             pdfswf_setparameter("jpegquality", val);
258             return 1;
259         }
260     }
261     else if (!strcmp(name, "V"))
262     {   
263         printf("pdf2swf - part of %s %s\n", PACKAGE, VERSION);
264         exit(0);
265     }
266     else 
267     {
268         fprintf(stderr, "Unknown option: -%s\n", name);
269         exit(1);
270     }
271     return 0;
272 }
273
274 /*struct docoptions_t options[] =
275 {{"o","output","filename::Specify output file"},
276  {"V","version","Print program version"},
277  {"i","ignore","Ignore draw order (makes the SWF file smaller, but may produce graphic errors)"},
278  {"z","zlib","Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)"},
279  {"s","shapes","Don't use SWF Fonts, but store everything as shape"},
280  {"j","jpegquality","Set quality of embedded jpeg pictures (default: 85)"},
281  {"p","pages","Convert only pages in range. (E.g. 3-85)"},
282  {"w","samewindow","Don't open a new browser window for links in the SWF"},
283  {"f","fonts","Stroe full fonts in SWF. (Don't reduce to used characters)"},
284  {"F","fontpath","path::Add directory to font search path"},
285  {"B","viewer","name::Link viewer \"name\" to the pdf"},
286  {"L","preloader","file.swf::Link preloader \"file.swf\" to the pdf"},
287  {"b","defaultviewer","Link default viewer to the pdf"},
288  {"l","defaultpreloader","Link default preloader to the pdf"}
289  {0,0}
290 };*/
291 struct options_t options[] =
292 {{"o","output"},
293  {"q","quiet"},
294  {"V","version"},
295  {"i","ignore"},
296  {"z","zlib"},
297  {"s","set"},
298  {"S","shapes"},
299  {"j","jpegquality"},
300  {"p","pages"},
301  {"w","samewindow"},
302  {"f","fonts"},
303  {"F","fontdir"},
304  {"B","viewer"},
305  {"L","preloader"},
306  {"b","defaultviewer"},
307  {"l","defaultpreloader"},
308  {"t","stop"},
309  {"T","flashversion"},
310  {0,0}
311 };
312
313 int args_callback_longoption(char*name,char*val) {
314     return args_long2shortoption(options, name, val);
315 }
316
317 int args_callback_command(char*name, char*val) {
318     if (!filename) 
319         filename = name;
320     else {
321         if(outputname)
322         {
323              fprintf(stderr, "Error: Do you want the output to go to %s or to %s?", 
324                      outputname, name);
325              exit(1);
326         }
327         outputname = name;
328     }
329     return 0;
330 }
331
332 void args_callback_usage(char*name)
333 {
334     printf("Usage: %s [Options] input.pdf [-o output.swf]\n", name);
335     printf("\nBasic options:\n");
336     printf("-p  --pages=range          Convert only pages in range\n");
337     printf("-P  --password=password    Use password for deciphering the pdf\n");
338     printf("-v  --verbose              Be verbose. Use more than one -v for greater effect\n");
339     printf("-q  --quiet                Suppress normal messages. Use -qq to suppress warnings, also.\n");
340 #ifdef HAVE_DIRENT_H
341     printf("-F  --fontdir directory    Add directory to font search path\n");
342 #endif
343     printf("-V  --version              Print program version\n");
344     printf("\nEnhanced conversion options:\n");
345     printf("-S  --shapes               Don't use SWF Fonts, but store everything as shape\n");
346     printf("-z  --zlib                 Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)\n");
347     printf("-w  --samewindow           Don't open a new Browser Window for Links in the SWF\n");
348     printf("-f  --fonts                Store full fonts in SWF. (Don't reduce to used characters)\n");
349     printf("-T  --flashversion=num     Set the flash version in the header to num (default: 4)\n");
350     printf("-s insertstop              Insert a \"Stop\" Tag in every frame (don't turn pages automatically)\n");
351     printf("-s zoom=factor             Scale result, default: 72\n");
352     printf("-s jpegquality=quality     Set quality of embedded jpeg pictures (default:85)\n");
353     printf("-s caplinewidth=value      Set the minimum line width to trigger cap style handling to value. (3)\n");
354     printf("-s splinequality=value     Set the quality of spline convertion to value (0-100, default: 100).\n");
355     printf("-s fontquality=value       Set the quality of font convertion to value (0-100, default: 100).\n");
356     printf("-s ignoredraworder         Ignore draw order (makes the SWF file smaller and faster, but may produce\n"
357            "                           graphic errors)\n");
358     printf("-s filloverlap             Make intersecting shapes overlap, instead of canceling each\n"
359            "                           other out. (Needed for some Powerpoint PDFs)\n");
360     //deliberately undocumented (for now)
361     //printf("-2                         Put 2 pages into each frame.\n");
362     //printf("-4                         Put 4 pages into each frame.\n");
363     printf("Postprocessing options:\n");
364 #ifndef SYSTEM_BACKTICKS
365     printf("(They might not work because your system call doesn't support command substitution)\n");
366 #endif
367     printf("-b  --defaultviewer        Link default viewer to the pdf (%s)\n", concatPaths(SWFDIR, "default_viewer.swf"));
368     printf("-l  --defaultpreloader     Link default preloader the pdf (%s)\n", concatPaths(SWFDIR, "default_loader.swf"));
369     printf("-B  --viewer=filename      Link viewer \"name\" to the pdf (\"%s -B\" for list)\n", name);
370     printf("-L  --preloader=filename   Link preloader \"name\" to the pdf (\"%s -L\" for list)\n",name);
371 }
372
373 float getRate(char*filename)
374 {
375     int fi;
376     SWF swf;
377     fi = open(filename,O_RDONLY|O_BINARY);
378     if(fi<0) { 
379         char buffer[256];
380         sprintf(buffer, "Couldn't open %s", filename);
381         perror(buffer);
382         exit(1);
383     }
384     if(swf_ReadSWF(fi,&swf) < 0)
385     { 
386         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
387         close(fi);
388         exit(1);
389     }
390     swf_FreeTags(&swf);
391     return swf.frameRate / 256.0;
392 }
393
394 int main(int argn, char *argv[])
395 {
396     int ret;
397     char buf[256];
398     int numfonts = 0;
399     int t;
400     char t1searchpath[1024];
401     int nup_pos = 0;
402     int x,y;
403     
404     initLog(0,-1,0,0,-1,loglevel);
405
406 #if defined(WIN32) && defined(HAVE_STAT) && defined(HAVE_SYS_STAT_H)
407     FILE*test = fopen(concatPaths(FONTDIR,"\\d050000l.afm"), "rb");
408     if(!test) {
409         fprintf(stderr, "Couldn't find file %s - pdf2swf not installed properly? OS says:\n", concatPaths(FONTDIR, "\\d050000l.afm"));
410         perror("open");
411         exit(1);
412     }
413     fclose(test);
414 #endif
415
416 #ifdef HAVE_SRAND48
417     srand48(time(0));
418 #else
419 #ifdef HAVE_SRAND
420     srand(time(0));
421 #endif
422 #endif
423     processargs(argn, argv);
424
425     if(!filename)
426     {
427         fprintf(stderr, "Please specify an input file\n");
428         exit(1);
429     }
430
431     if(!outputname)
432     {
433         if(filename) {
434             outputname = stripFilename(filename, ".swf");
435             msg("<notice> Output filename not given. Writing to %s", outputname);
436         } 
437     }
438         
439     if(!outputname)
440     {
441         fprintf(stderr, "Please use -o to specify an output file\n");
442         exit(1);
443     }
444
445     // test if the page range is o.k.
446     is_in_range(0x7fffffff, pagerange);
447
448     if (!filename) {
449         args_callback_usage(argv[0]);
450         exit(0);
451     }
452
453     /* add fonts */
454     pdfswf_addfontdir(FONTDIR);
455     for(t=0;t<fontpathpos;t++) {
456         pdfswf_addfontdir(fontpaths[t]);
457     }
458
459     pdf_doc_t* pdf = pdf_init(filename, password);
460     if(!pdf) {
461         msg("<error> Couldn't open %s", filename);
462         exit(1);
463     }
464
465     swf_output_t* swf = swf_output_init();
466
467     struct mypage_t {
468         int x;
469         int y;
470         pdf_page_t*page;
471         pdf_page_info_t*info;
472     } pages[4];
473
474     int pagenum = 0;
475     int frame = 1;
476     
477     for(int pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
478     {
479         if(is_in_range(pagenr, pagerange)) {
480             swf_output_preparepage(swf, pagenr, frame);
481             pagenum++;
482         }
483         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
484             pagenum = 0;
485             frame++;
486         }
487     }
488
489     pagenum = 0;
490
491     for(int pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
492     {
493         if(is_in_range(pagenr, pagerange)) {
494             pdf_page_t* page = pages[pagenum].page = pdf_getpage(pdf, pagenr);
495             pdf_page_info_t* info = pdf_page_getinfo(page);
496             pages[pagenum].x = 0;
497             pages[pagenum].y = 0;
498             pages[pagenum].info = info;
499             pages[pagenum].page = page;
500             pagenum++;
501         }
502         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
503
504             int t;
505             int xmax[xnup], ymax[xnup];
506             int x,y;
507             int width=0, height=0;
508
509             memset(xmax, 0, xnup*sizeof(int));
510             memset(ymax, 0, ynup*sizeof(int));
511
512             for(y=0;y<ynup;y++)
513             for(x=0;x<xnup;x++) {
514                 int t = y*xnup + x;
515
516                 if(pages[t].info->xMax-pages[t].info->xMin > xmax[x])
517                     xmax[x] = pages[t].info->xMax-pages[t].info->xMin;
518                 if(pages[t].info->yMax-pages[t].info->yMin > ymax[y])
519                     ymax[y] = pages[t].info->yMax-pages[t].info->yMin;
520             }
521             for(x=0;x<xnup;x++) {
522                 width += xmax[x];
523                 xmax[x] = width;
524             }
525             for(y=0;y<ynup;y++) {
526                 height += ymax[y];
527                 ymax[y] = height;
528             }
529             swf_output_startframe(swf, width, height);
530             for(t=0;t<pagenum;t++) {
531                 int x = t%xnup;
532                 int y = t/xnup;
533                 int xpos = x>0?xmax[x-1]:0;
534                 int ypos = y>0?ymax[y-1]:0;
535                 pdf_page_info_t*info = pages[t].info;
536                 xpos -= info->xMin;
537                 ypos -= info->yMin;
538                 msg("<verbose> Render (%d,%d)-(%d,%d) move:%d/%d\n",
539                         info->xMin + xpos,
540                         info->yMin + ypos,
541                         info->xMax + xpos,
542                         info->yMax + ypos, xpos, ypos);
543                 pdf_page_rendersection(pages[t].page, swf, xpos, 
544                                                            ypos,
545                                                            info->xMin + xpos, 
546                                                            info->yMin + ypos, 
547                                                            info->xMax + xpos, 
548                                                            info->yMax + ypos);
549             }
550             swf_output_endframe(swf);
551             for(t=0;t<pagenum;t++)  {
552                 pdf_page_info_destroy(pages[t].info);
553                 pdf_page_destroy(pages[t].page);
554             }
555             pagenum = 0;
556         }
557     }
558     if(swf_output_save(swf, outputname) < 0) {
559         exit(1);
560     }
561     int width = (int)swf_output_get(swf, "width");
562     int height = (int)swf_output_get(swf, "height");
563     msg("<notice> SWF written");
564     swf_output_destroy(swf);
565
566     pdf_destroy(pdf);
567
568     char*zip = "";
569     if(zlib)
570         zip = "-z";
571 #undef SYSTEM_BACKTICKS
572     if(viewer && !preloader) {
573 #ifdef SYSTEM_BACKTICKS
574         systemf("swfcombine %s `swfdump -XY \"%s\"` \"%s\" viewport=\"%s\" -o \"%s\"",zip,
575                 viewer, outputname, outputname);
576 #else
577         systemf("swfcombine %s -X %d -Y %d \"%s\" viewport=\"%s\" -o \"%s\"",zip,width,height,
578                 viewer, outputname, outputname);
579 #endif
580         if(!system_quiet)
581             printf("\n");
582     }
583     if(preloader && !viewer) {
584         msg("<warning> --preloader option without --viewer option doesn't make very much sense.");
585 #ifdef SYSTEM_BACKTICKS
586         ret = systemf("swfcombine %s `swfdump -r \"%s\"` %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",zip,
587                 preloader, SWFDIR, preloader, outputname, outputname);
588 #else
589         ret = systemf("swfcombine %s -Y %d -X %d %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",zip,width,height,
590                 SWFDIR, preloader, outputname, outputname);
591 #endif
592         if(!system_quiet)
593             printf("\n");
594     }
595     if(preloader && viewer) {
596         systemf("swfcombine \"%s\" viewport=%s -o __tmp__.swf",
597                 viewer, outputname, outputname);
598 #ifdef SYSTEM_BACKTICKS
599         systemf("swfcombine %s `swfdump -XY \"%s\"` `swfdump -r \"%s\"` %s/PreLoaderTemplate.swf loader=%s movie=__tmp__.swf -o \"%s\"",zip,
600                 outputname, preloader, SWFDIR, preloader, outputname);
601 #else
602         /* TODO: read out rate */
603         systemf("swfcombine %s -X %d -Y %d -r %f %s/PreLoaderTemplate.swf loader=%s movie=__tmp__.swf -o \"%s\"",zip,width,height,
604                 getRate(preloader), preloader, SWFDIR, preloader, outputname);
605 #endif
606         systemf("rm __tmp__.swf");
607     }
608
609     return 0;
610 }
611