bugfixes, parametrized image algorithm in record device
[swftools.git] / lib / devices / record.c
1 /* gfxdevice_record.cc
2
3    Part of the swftools package.
4
5    Copyright (c) 2005 Matthias Kramm <kramm@quiss.org> 
6  
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <math.h>
24 #include "../../config.h"
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <memory.h>
29 #ifdef HAVE_IO_H
30 #include <io.h>
31 #endif
32 #include <zlib.h>
33 #include <string.h>
34 #include <assert.h>
35 #include "../gfxdevice.h"
36 #include "../gfxtools.h"
37 #include "../types.h"
38 #include "../bitio.h"
39 #include "../log.h"
40 #include "../os.h"
41 #include "../png.h"
42 #ifdef HAVE_FASTLZ
43 #include "../fastlz.h"
44 #endif
45 #include "record.h"
46
47 //#define STATS
48 #define COMPRESS_IMAGES
49 //#define FILTER_IMAGES
50
51 typedef struct _state {
52     char*last_string[16];
53     gfxcolor_t last_color[16];
54     gfxmatrix_t last_matrix[16];
55
56 #ifdef STATS
57     int size_matrices;
58     int size_positions;
59     int size_images;
60     int size_lines;
61     int size_colors;
62     int size_fonts;
63     int size_chars;
64 #endif
65 } state_t;
66
67 typedef struct _internal {
68     gfxfontlist_t* fontlist;
69     state_t state;
70
71     writer_t w;
72     int cliplevel;
73     char use_tempfile;
74     char*filename;
75 } internal_t;
76
77 typedef struct _internal_result {
78     char use_tempfile;
79     char*filename;
80     void*data;
81     int length;
82 } internal_result_t;
83
84 #define OP_END 0x00
85 #define OP_SETPARAM 0x01
86 #define OP_STROKE 0x02
87 #define OP_STARTCLIP 0x03
88 #define OP_ENDCLIP 0x04
89 #define OP_FILL 0x05
90 #define OP_FILLBITMAP 0x06
91 #define OP_FILLGRADIENT 0x07
92 #define OP_ADDFONT 0x08
93 #define OP_DRAWCHAR 0x09
94 #define OP_DRAWLINK 0x0a
95 #define OP_STARTPAGE 0x0b
96 #define OP_ENDPAGE 0x0c
97 #define OP_FINISH 0x0d
98
99 #define FLAG_SAME_AS_LAST 0x10
100
101 #define LINE_MOVETO 0x0e
102 #define LINE_LINETO 0x0f
103 #define LINE_SPLINETO 0x10
104
105 /* ----------------- reading/writing of low level primitives -------------- */
106
107 static void dumpLine(writer_t*w, state_t*state, gfxline_t*line)
108 {
109     while(line) {
110         if(line->type == gfx_moveTo) {
111             writer_writeU8(w, LINE_MOVETO);
112             writer_writeDouble(w, line->x);
113             writer_writeDouble(w, line->y);
114 #ifdef STATS
115             state->size_lines += 1+8+8;
116 #endif
117         } else if(line->type == gfx_lineTo) {
118             writer_writeU8(w, LINE_LINETO);
119             writer_writeDouble(w, line->x);
120             writer_writeDouble(w, line->y);
121 #ifdef STATS
122             state->size_lines += 1+8+8;
123 #endif
124         } else if(line->type == gfx_splineTo) {
125             writer_writeU8(w, LINE_SPLINETO);
126             writer_writeDouble(w, line->x);
127             writer_writeDouble(w, line->y);
128             writer_writeDouble(w, line->sx);
129             writer_writeDouble(w, line->sy);
130 #ifdef STATS
131             state->size_lines += 1+8+8+8+8;
132 #endif
133         }
134         line = line->next;
135     }
136     writer_writeU8(w, OP_END);
137 #ifdef STATS
138     state->size_lines += 1;
139 #endif
140 }
141 static gfxline_t* readLine(reader_t*r, state_t*s)
142 {
143     gfxline_t*start = 0, *pos = 0;
144     while(1) {
145         unsigned char op = reader_readU8(r);
146         if(op == OP_END)
147             break;
148         gfxline_t*line = (gfxline_t*)rfx_calloc(sizeof(gfxline_t));
149         if(!start) {
150             start = pos = line;
151         } else {
152             pos->next = line;
153             pos = line;
154         }
155         if(op == LINE_MOVETO) {
156             line->type = gfx_moveTo;
157             line->x = reader_readDouble(r);
158             line->y = reader_readDouble(r);
159         } else if(op == LINE_LINETO) {
160             line->type = gfx_lineTo;
161             line->x = reader_readDouble(r);
162             line->y = reader_readDouble(r);
163         } else if(op == LINE_SPLINETO) {
164             line->type = gfx_splineTo;
165             line->x = reader_readDouble(r);
166             line->y = reader_readDouble(r);
167             line->sx = reader_readDouble(r);
168             line->sy = reader_readDouble(r);
169         }
170     }
171     return start;
172 }
173
174 static void dumpImage(writer_t*w, state_t*state, gfximage_t*img)
175 {
176     int oldpos = w->pos;
177     writer_writeU16(w, img->width);
178     writer_writeU16(w, img->height);
179 #ifdef COMPRESS_IMAGES
180     //35.3% images (2027305 bytes) (with filter, Z_BEST_COMPRESSION)
181     //39.9% images (2458904 bytes) (with filter, Z_BEST_SPEED)
182     //45.2% images (3055340 bytes) (without filter)
183     //45.9% images (3149247 bytes) (without filter, 5)
184     //48.0% images (3480495 bytes) (with filter, fastlz)
185     //48.0% images (3488650 bytes) (without filter, Z_BEST_SPEED)
186     //55.3% images (4665889 bytes) (without filter, fastlz level 2)
187     //55.6% images (4726334 bytes) (without filter, fastlz level 1)
188
189     gfxcolor_t*image;
190 #ifdef FILTER_IMAGES
191     unsigned char*filter = malloc(img->height);
192     int y;
193     image = malloc(img->width*img->height*sizeof(gfxcolor_t));
194     for(y=0;y<img->height;y++) {
195         filter[y] = png_apply_filter_32(
196                 (void*)&image[y*img->width], 
197                 (void*)&img->data[y*img->width], img->width, y);
198     }
199 #else
200     image = img->data;
201 #endif
202     int size = img->width*img->height;
203     uLongf compressdata_size = compressBound(size*sizeof(gfxcolor_t));
204     void*compressdata = malloc(compressdata_size);
205
206 #ifdef HAVE_FASTLZ
207     compressdata_size = fastlz_compress_level(2, (void*)image, size*sizeof(gfxcolor_t), compressdata);
208 #else
209     compress2(compressdata, &compressdata_size, (void*)image, sizeof(gfxcolor_t)*size, 6);
210 #endif
211
212     writer_writeU32(w, compressdata_size);
213 #ifdef FILTER_IMAGES
214     w->write(w, filter, img->height);
215     free(filter);
216     free(image);
217 #endif
218     w->write(w, compressdata, compressdata_size);
219 #else
220     w->write(w, img->data, img->width*img->height*sizeof(gfxcolor_t));
221 #endif
222 #ifdef STATS
223     state->size_images += w->pos - oldpos;
224 #endif
225 }
226 static gfximage_t readImage(reader_t*r, state_t*state)
227 {
228     gfximage_t img;
229     img.width = reader_readU16(r);
230     img.height = reader_readU16(r);
231     uLongf size = img.width*img.height*sizeof(gfxcolor_t);
232     img.data = malloc(size);
233 #ifdef COMPRESS_IMAGES
234     uLongf compressdata_size = reader_readU32(r);
235     void*compressdata = malloc(compressdata_size);
236 # ifdef FILTER_IMAGES
237     unsigned char*filter = malloc(img.height);
238     r->read(r, filter, img.height);
239 # endif
240     r->read(r, compressdata, compressdata_size);
241    
242 # ifdef HAVE_FASTLZ
243     fastlz_decompress(compressdata, compressdata_size, (void*)img.data, size);
244 # else
245     uncompress((void*)img.data, &size, compressdata, compressdata_size);
246 # endif
247
248 # ifdef FILTER_IMAGES
249     int y;
250     unsigned char*line = malloc(img.width*sizeof(gfxcolor_t));
251     for(y=0;y<img.height;y++) {
252         png_inverse_filter_32(filter[y], (void*)&img.data[y*img.width], 
253                               y?(void*)&img.data[(y-1)*img.width]:(void*)0, 
254                               line, img.width);
255         memcpy(&img.data[y*img.width], line, img.width*sizeof(gfxcolor_t));
256     }
257     free(line);
258     free(filter);
259 # endif
260
261 #else
262     r->read(r, img.data, size);
263 #endif
264     return img;
265 }
266
267 static void dumpMatrix(writer_t*w, state_t*state, gfxmatrix_t*matrix)
268 {
269     writer_writeDouble(w, matrix->m00);
270     writer_writeDouble(w, matrix->m01);
271     writer_writeDouble(w, matrix->m10);
272     writer_writeDouble(w, matrix->m11);
273     writer_writeDouble(w, matrix->tx);
274     writer_writeDouble(w, matrix->ty);
275 #ifdef STATS
276     state->size_matrices += 6*8;
277 #endif
278 }
279 static gfxmatrix_t readMatrix(reader_t*r, state_t*state)
280 {
281     gfxmatrix_t matrix;
282     matrix.m00 = reader_readDouble(r);
283     matrix.m01 = reader_readDouble(r);
284     matrix.m10 = reader_readDouble(r);
285     matrix.m11 = reader_readDouble(r);
286     matrix.tx = reader_readDouble(r);
287     matrix.ty = reader_readDouble(r);
288     return matrix;
289 }
290 static void dumpXY(writer_t*w, state_t*state, gfxmatrix_t*matrix)
291 {
292     writer_writeDouble(w, matrix->tx);
293     writer_writeDouble(w, matrix->ty);
294 #ifdef STATS
295     state->size_positions += 2*8;
296 #endif
297 }
298 static void readXY(reader_t*r, state_t*state, gfxmatrix_t*m)
299 {
300     m->tx = reader_readDouble(r);
301     m->ty = reader_readDouble(r);
302 }
303
304 static void dumpColor(writer_t*w, state_t*state, gfxcolor_t*color)
305 {
306     writer_writeU8(w, color->r);
307     writer_writeU8(w, color->g);
308     writer_writeU8(w, color->b);
309     writer_writeU8(w, color->a);
310 #ifdef STATS
311     state->size_colors += 4;
312 #endif
313 }
314 static gfxcolor_t readColor(reader_t*r, state_t*state)
315 {
316     gfxcolor_t col;
317     col.r = reader_readU8(r);
318     col.g = reader_readU8(r);
319     col.b = reader_readU8(r);
320     col.a = reader_readU8(r);
321     return col;
322 }
323
324 static void dumpGradient(writer_t*w, state_t*state, gfxgradient_t*gradient)
325 {
326     while(gradient) {
327         writer_writeU8(w, 1);
328         dumpColor(w, state, &gradient->color);
329         writer_writeFloat(w, gradient->pos);
330         gradient = gradient->next;
331     }
332     writer_writeU8(w, 0);
333 }
334 static gfxgradient_t* readGradient(reader_t*r, state_t*state)
335 {
336     gfxgradient_t*start = 0, *pos = 0;
337     while(1) {
338         U8 op = reader_readU8(r);
339         if(!op)
340             break;
341         gfxgradient_t*g = (gfxgradient_t*)rfx_calloc(sizeof(gfxgradient_t));
342         if(!start) {
343             start = pos = g;
344         } else {
345             pos->next = g;
346             pos = g;
347         }
348         g->color = readColor(r, state);
349         g->pos = reader_readFloat(r);
350     }
351     return start;
352 }
353
354 static void dumpCXForm(writer_t*w, state_t*state, gfxcxform_t*c)
355 {
356     if(!c) {
357         writer_writeU8(w, 0);
358     } else {
359         writer_writeU8(w, 1);
360         writer_writeFloat(w, c->rr); writer_writeFloat(w, c->rg); writer_writeFloat(w, c->rb); writer_writeFloat(w, c->ra);
361         writer_writeFloat(w, c->gr); writer_writeFloat(w, c->gg); writer_writeFloat(w, c->gb); writer_writeFloat(w, c->ga);
362         writer_writeFloat(w, c->br); writer_writeFloat(w, c->bg); writer_writeFloat(w, c->bb); writer_writeFloat(w, c->ba);
363         writer_writeFloat(w, c->ar); writer_writeFloat(w, c->ag); writer_writeFloat(w, c->ab); writer_writeFloat(w, c->aa);
364     }
365 }
366 static gfxcxform_t* readCXForm(reader_t*r, state_t*state)
367 {
368     U8 type = reader_readU8(r);
369     if(!type)
370         return 0;
371     gfxcxform_t* c = (gfxcxform_t*)rfx_calloc(sizeof(gfxcxform_t));
372     c->rr = reader_readFloat(r); c->rg = reader_readFloat(r); c->rb = reader_readFloat(r); c->ra = reader_readFloat(r);
373     c->gr = reader_readFloat(r); c->gg = reader_readFloat(r); c->gb = reader_readFloat(r); c->ga = reader_readFloat(r);
374     c->br = reader_readFloat(r); c->bg = reader_readFloat(r); c->bb = reader_readFloat(r); c->ba = reader_readFloat(r);
375     c->ar = reader_readFloat(r); c->ag = reader_readFloat(r); c->ab = reader_readFloat(r); c->aa = reader_readFloat(r);
376     return c;
377 }
378
379 static void dumpFont(writer_t*w, state_t*state, gfxfont_t*font)
380 {
381     int oldpos = w->pos;
382 #ifdef STATS
383     int old_size_lines = state->size_lines;
384 #endif
385     writer_writeString(w, font->id);
386     writer_writeU32(w, font->num_glyphs);
387     writer_writeU32(w, font->max_unicode);
388     writer_writeDouble(w, font->ascent);
389     writer_writeDouble(w, font->descent);
390     int t;
391     for(t=0;t<font->num_glyphs;t++) {
392         dumpLine(w, state, font->glyphs[t].line);
393         writer_writeDouble(w, font->glyphs[t].advance);
394         writer_writeU32(w, font->glyphs[t].unicode);
395         if(font->glyphs[t].name) {
396             writer_writeString(w,font->glyphs[t].name);
397         } else {
398             writer_writeU8(w,0);
399         }
400     }
401     for(t=0;t<font->max_unicode;t++) {
402         writer_writeU32(w, font->unicode2glyph[t]);
403     }
404     writer_writeU32(w, font->kerning_size);
405     for(t=0;t<font->kerning_size;t++) {
406         writer_writeU32(w, font->kerning[t].c1);
407         writer_writeU32(w, font->kerning[t].c2);
408         writer_writeU32(w, font->kerning[t].advance);
409     }
410 #ifdef STATS
411     state->size_lines = old_size_lines;
412     state->size_fonts += w->pos - oldpos;
413 #endif
414 }
415 static gfxfont_t*readFont(reader_t*r, state_t*state)
416 {
417     gfxfont_t* font = (gfxfont_t*)rfx_calloc(sizeof(gfxfont_t));
418     font->id = reader_readString(r);
419     font->num_glyphs = reader_readU32(r);
420     font->max_unicode = reader_readU32(r);
421     font->ascent = reader_readDouble(r);
422     font->descent = reader_readDouble(r);
423     font->glyphs = (gfxglyph_t*)rfx_calloc(sizeof(gfxglyph_t)*font->num_glyphs);
424     font->unicode2glyph = (int*)rfx_calloc(sizeof(font->unicode2glyph[0])*font->max_unicode);
425     int t;
426     for(t=0;t<font->num_glyphs;t++) {
427         font->glyphs[t].line = readLine(r, state);
428         font->glyphs[t].advance = reader_readDouble(r);
429         font->glyphs[t].unicode = reader_readU32(r);
430         font->glyphs[t].name = reader_readString(r);
431         if(!font->glyphs[t].name[0]) {
432             free((void*)(font->glyphs[t].name));
433             font->glyphs[t].name = 0;
434         }
435     }
436     for(t=0;t<font->max_unicode;t++) {
437         font->unicode2glyph[t] = reader_readU32(r);
438     }
439     font->kerning_size = reader_readU32(r);
440     if(font->kerning_size) {
441         font->kerning = malloc(sizeof(gfxkerning_t)*font->kerning_size);
442         for(t=0;t<font->kerning_size;t++) {
443             font->kerning[t].c1 = reader_readU32(r);
444             font->kerning[t].c2 = reader_readU32(r);
445             font->kerning[t].advance = reader_readU32(r);
446         }
447     }
448     return font;
449 }
450
451 /* ----------------- reading/writing of primitives with caching -------------- */
452
453 static char* read_string(reader_t*r, state_t*state, U8 id, U8 flags)
454 {
455     assert(id>=0 && id<16);
456     if(flags&FLAG_SAME_AS_LAST) {
457         assert(state->last_string[id]);
458         return strdup(state->last_string[id]);
459     }
460     char*s = reader_readString(r);
461     state->last_string[id] = strdup(s);
462     return s;
463 }
464 static gfxcolor_t read_color(reader_t*r, state_t*state, U8 id, U8 flags)
465 {
466     assert(id>=0 && id<16);
467     if(flags&FLAG_SAME_AS_LAST)
468         return state->last_color[id];
469     gfxcolor_t c = readColor(r, state);
470     state->last_color[id] = c;
471     return c;
472 }
473 static gfxmatrix_t read_matrix(reader_t*r, state_t*state, U8 id, U8 flags)
474 {
475     assert(id>=0 && id<16);
476     if(flags&FLAG_SAME_AS_LAST) {
477         gfxmatrix_t m = state->last_matrix[id];
478         readXY(r, state, &m);
479         return m;
480     }
481     gfxmatrix_t m = readMatrix(r, state);
482     state->last_matrix[id] = m;
483     return m;
484 }
485
486 /* --------------------------- record device operations ---------------------- */
487
488 static int record_setparameter(struct _gfxdevice*dev, const char*key, const char*value)
489 {
490     internal_t*i = (internal_t*)dev->internal;
491     msg("<trace> record: %08x SETPARAM %s %s\n", dev, key, value);
492     writer_writeU8(&i->w, OP_SETPARAM);
493     writer_writeString(&i->w, key);
494     writer_writeString(&i->w, value);
495     return 1;
496 }
497
498 static void record_stroke(struct _gfxdevice*dev, gfxline_t*line, gfxcoord_t width, gfxcolor_t*color, gfx_capType cap_style, gfx_joinType joint_style, gfxcoord_t miterLimit)
499 {
500     internal_t*i = (internal_t*)dev->internal;
501     msg("<trace> record: %08x STROKE\n", dev);
502     writer_writeU8(&i->w, OP_STROKE);
503     writer_writeDouble(&i->w, width);
504     writer_writeDouble(&i->w, miterLimit);
505     dumpColor(&i->w, &i->state, color);
506     writer_writeU8(&i->w, cap_style);
507     writer_writeU8(&i->w, joint_style);
508     dumpLine(&i->w, &i->state, line);
509 }
510
511 static void record_startclip(struct _gfxdevice*dev, gfxline_t*line)
512 {
513     internal_t*i = (internal_t*)dev->internal;
514     msg("<trace> record: %08x STARTCLIP\n", dev);
515     writer_writeU8(&i->w, OP_STARTCLIP);
516     dumpLine(&i->w, &i->state, line);
517     i->cliplevel++;
518 }
519
520 static void record_endclip(struct _gfxdevice*dev)
521 {
522     internal_t*i = (internal_t*)dev->internal;
523     msg("<trace> record: %08x ENDCLIP\n", dev);
524     writer_writeU8(&i->w, OP_ENDCLIP);
525     i->cliplevel--;
526     if(i->cliplevel<0) {
527         msg("<error> record: endclip() without startclip()");
528     }
529 }
530
531 static void record_fill(struct _gfxdevice*dev, gfxline_t*line, gfxcolor_t*color)
532 {
533     internal_t*i = (internal_t*)dev->internal;
534     msg("<trace> record: %08x FILL\n", dev);
535     writer_writeU8(&i->w, OP_FILL);
536     dumpColor(&i->w, &i->state, color);
537     dumpLine(&i->w, &i->state, line);
538 }
539
540 static void record_fillbitmap(struct _gfxdevice*dev, gfxline_t*line, gfximage_t*img, gfxmatrix_t*matrix, gfxcxform_t*cxform)
541 {
542     internal_t*i = (internal_t*)dev->internal;
543     msg("<trace> record: %08x FILLBITMAP\n", dev);
544     writer_writeU8(&i->w, OP_FILLBITMAP);
545     dumpImage(&i->w, &i->state, img);
546     dumpMatrix(&i->w, &i->state, matrix);
547     dumpLine(&i->w, &i->state, line);
548     dumpCXForm(&i->w, &i->state, cxform);
549 }
550
551 static void record_fillgradient(struct _gfxdevice*dev, gfxline_t*line, gfxgradient_t*gradient, gfxgradienttype_t type, gfxmatrix_t*matrix)
552 {
553     internal_t*i = (internal_t*)dev->internal;
554     msg("<trace> record: %08x FILLGRADIENT %08x\n", dev, gradient);
555     writer_writeU8(&i->w, OP_FILLGRADIENT);
556     writer_writeU8(&i->w, type);
557     dumpGradient(&i->w, &i->state, gradient);
558     dumpMatrix(&i->w, &i->state, matrix);
559     dumpLine(&i->w, &i->state, line);
560 }
561
562 static void record_addfont(struct _gfxdevice*dev, gfxfont_t*font)
563 {
564     internal_t*i = (internal_t*)dev->internal;
565     msg("<trace> record: %08x ADDFONT %s\n", dev, font->id);
566     if(font && !gfxfontlist_hasfont(i->fontlist, font)) {
567         writer_writeU8(&i->w, OP_ADDFONT);
568         dumpFont(&i->w, &i->state, font);
569         i->fontlist = gfxfontlist_addfont(i->fontlist, font);
570     }
571 }
572
573 static void record_drawchar(struct _gfxdevice*dev, gfxfont_t*font, int glyphnr, gfxcolor_t*color, gfxmatrix_t*matrix)
574 {
575     internal_t*i = (internal_t*)dev->internal;
576     if(font && !gfxfontlist_hasfont(i->fontlist, font)) {
577         record_addfont(dev, font);
578     }
579
580     msg("<trace> record: %08x DRAWCHAR %d\n", glyphnr, dev);
581     const char*font_id = font->id?font->id:"*NULL*";
582     
583     gfxmatrix_t*l = &i->state.last_matrix[OP_DRAWCHAR];
584
585     char same_font = i->state.last_string[OP_DRAWCHAR] && !strcmp(i->state.last_string[OP_DRAWCHAR], font_id);
586     char same_matrix = (l->m00 == matrix->m00) && (l->m01 == matrix->m01) && (l->m10 == matrix->m10) && (l->m11 == matrix->m11);
587     char same_color = !memcmp(color, &i->state.last_color[OP_DRAWCHAR], sizeof(gfxcolor_t));
588     U8 flags = 0;
589     if(same_font && same_matrix && same_color)
590         flags |= FLAG_SAME_AS_LAST;
591
592     writer_writeU8(&i->w, OP_DRAWCHAR|flags);
593     writer_writeU32(&i->w, glyphnr);
594 #ifdef STATS
595     i->state.size_chars += 5;
596 #endif
597
598     if(!(flags&FLAG_SAME_AS_LAST)) {
599         writer_writeString(&i->w, font_id);
600         dumpColor(&i->w, &i->state, color);
601         dumpMatrix(&i->w, &i->state, matrix);
602         i->state.last_string[OP_DRAWCHAR] = strdup(font_id);
603         i->state.last_color[OP_DRAWCHAR] = *color;
604         i->state.last_matrix[OP_DRAWCHAR] = *matrix;
605     } else {
606         dumpXY(&i->w, &i->state, matrix);
607     }
608 }
609
610 static void record_startpage(struct _gfxdevice*dev, int width, int height)
611 {
612     internal_t*i = (internal_t*)dev->internal;
613     msg("<trace> record: %08x STARTPAGE\n", dev);
614     writer_writeU8(&i->w, OP_STARTPAGE);
615     writer_writeU16(&i->w, width);
616     writer_writeU16(&i->w, height);
617 }
618
619 static void record_endpage(struct _gfxdevice*dev)
620 {
621     internal_t*i = (internal_t*)dev->internal;
622     msg("<trace> record: %08x ENDPAGE\n", dev);
623     writer_writeU8(&i->w, OP_ENDPAGE);
624 }
625
626 static void record_drawlink(struct _gfxdevice*dev, gfxline_t*line, const char*action)
627 {
628     internal_t*i = (internal_t*)dev->internal;
629     msg("<trace> record: %08x DRAWLINK\n", dev);
630     writer_writeU8(&i->w, OP_DRAWLINK);
631     dumpLine(&i->w, &i->state, line);
632     writer_writeString(&i->w, action);
633 }
634
635 /* ------------------------------- replaying --------------------------------- */
636
637 static void replay(struct _gfxdevice*dev, gfxdevice_t*out, reader_t*r)
638 {
639     internal_t*i = 0;
640     if(dev) {
641         i = (internal_t*)dev->internal;
642     }
643
644     state_t state;
645     memset(&state, 0, sizeof(state));
646
647     gfxfontlist_t* fontlist = gfxfontlist_create();
648
649     while(1) {
650         unsigned char op;
651         if(r->read(r, &op, 1)!=1)
652             break;
653         unsigned char flags = op&0xf0;
654         op&=0x0f;
655
656         switch(op) {
657             case OP_END:
658                 goto finish;
659             case OP_SETPARAM: {
660                 msg("<trace> replay: SETPARAM");
661                 char*key;
662                 char*value;
663                 key = reader_readString(r);
664                 value = reader_readString(r);
665                 out->setparameter(out, key, value);
666                 free(key);
667                 free(value);
668                 break;
669             }
670             case OP_STARTPAGE: {
671                 msg("<trace> replay: STARTPAGE");
672                 U16 width = reader_readU16(r);
673                 U16 height = reader_readU16(r);
674                 out->startpage(out, width, height);
675                 break;
676             }
677             case OP_ENDPAGE: {
678                 msg("<trace> replay: ENDPAGE");
679                 out->endpage(out);
680                 break;
681             }
682             case OP_FINISH: {
683                 msg("<trace> replay: FINISH");
684                 break;
685             }
686             case OP_STROKE: {
687                 msg("<trace> replay: STROKE");
688                 double width = reader_readDouble(r);
689                 double miterlimit = reader_readDouble(r);
690                 gfxcolor_t color = readColor(r, &state);
691                 gfx_capType captype;
692                 int v = reader_readU8(r);
693                 switch (v) {
694                     case 0: captype = gfx_capButt; break;
695                     case 1: captype = gfx_capRound; break;
696                     case 2: captype = gfx_capSquare; break;
697                 }
698                 gfx_joinType jointtype;
699                 v = reader_readU8(r);
700                 switch (v) {
701                     case 0: jointtype = gfx_joinMiter; break;
702                     case 1: jointtype = gfx_joinRound; break;
703                     case 2: jointtype = gfx_joinBevel; break;
704                 }
705                 gfxline_t* line = readLine(r, &state);
706                 out->stroke(out, line, width, &color, captype, jointtype,miterlimit);
707                 gfxline_free(line);
708                 break;
709             }
710             case OP_STARTCLIP: {
711                 msg("<trace> replay: STARTCLIP");
712                 gfxline_t* line = readLine(r, &state);
713                 out->startclip(out, line);
714                 gfxline_free(line);
715                 break;
716             }
717             case OP_ENDCLIP: {
718                 msg("<trace> replay: ENDCLIP");
719                 out->endclip(out);
720                 break;
721             }
722             case OP_FILL: {
723                 msg("<trace> replay: FILL");
724                 gfxcolor_t color = readColor(r, &state);
725                 gfxline_t* line = readLine(r, &state);
726                 out->fill(out, line, &color);
727                 gfxline_free(line);
728                 break;
729             }
730             case OP_FILLBITMAP: {
731                 msg("<trace> replay: FILLBITMAP");
732                 gfximage_t img = readImage(r, &state);
733                 gfxmatrix_t matrix = readMatrix(r, &state);
734                 gfxline_t* line = readLine(r, &state);
735                 gfxcxform_t* cxform = readCXForm(r, &state);
736                 out->fillbitmap(out, line, &img, &matrix, cxform);
737                 gfxline_free(line);
738                 if(cxform)
739                     free(cxform);
740                 free(img.data);img.data=0;
741                 break;
742             }
743             case OP_FILLGRADIENT: {
744                 msg("<trace> replay: FILLGRADIENT");
745                 gfxgradienttype_t type;
746                 int v = reader_readU8(r);
747                 switch (v) {
748                     case 0: 
749                       type = gfxgradient_radial; break;
750                     case 1:
751                       type = gfxgradient_linear; break;
752                 }  
753                 gfxgradient_t*gradient = readGradient(r, &state);
754                 gfxmatrix_t matrix = readMatrix(r, &state);
755                 gfxline_t* line = readLine(r, &state);
756                 out->fillgradient(out, line, gradient, type, &matrix);
757                 break;
758             }
759             case OP_DRAWLINK: {
760                 msg("<trace> replay: DRAWLINK");
761                 gfxline_t* line = readLine(r, &state);
762                 char* s = reader_readString(r);
763                 out->drawlink(out,line,s);
764                 gfxline_free(line);
765                 free(s);
766                 break;
767             }
768             case OP_ADDFONT: {
769                 msg("<trace> replay: ADDFONT out=%08x(%s)", out, out->name);
770                 gfxfont_t*font = readFont(r, &state);
771                 fontlist = gfxfontlist_addfont(fontlist, font);
772                 out->addfont(out, font);
773                 break;
774             }
775             case OP_DRAWCHAR: {
776                 U32 glyph = reader_readU32(r);
777                 gfxmatrix_t m = {1,0,0, 0,1,0};
778                 char* id = read_string(r, &state, op, flags);
779                 gfxcolor_t color = read_color(r, &state, op, flags);
780                 gfxmatrix_t matrix = read_matrix(r, &state, op, flags);
781
782                 gfxfont_t*font = id?gfxfontlist_findfont(fontlist, id):0;
783                 if(i && !font) {
784                     font = gfxfontlist_findfont(i->fontlist, id);
785                 }
786                 msg("<trace> replay: DRAWCHAR font=%s glyph=%d", id, glyph);
787                 out->drawchar(out, font, glyph, &color, &matrix);
788                 free(id);
789                 break;
790             }
791         }
792     }
793 finish:
794     r->dealloc(r);
795     /* problem: if we just replayed into a device which stores the
796        font for later use (the record device itself is a nice example),
797        then we can't free it yet */
798     //gfxfontlist_free(fontlist, 1);
799     gfxfontlist_free(fontlist, 0);
800 }
801 void gfxresult_record_replay(gfxresult_t*result, gfxdevice_t*device)
802 {
803     internal_result_t*i = (internal_result_t*)result->internal;
804     
805     reader_t r;
806     if(i->use_tempfile) {
807         reader_init_filereader2(&r, i->filename);
808     } else {
809         reader_init_memreader(&r, i->data, i->length);
810     }
811
812     replay(0, device, &r);
813 }
814
815 static void record_result_write(gfxresult_t*r, int filedesc)
816 {
817     internal_result_t*i = (internal_result_t*)r->internal;
818     if(i->data) {
819         write(filedesc, i->data, i->length);
820     }
821 }
822 static int record_result_save(gfxresult_t*r, const char*filename)
823 {
824     internal_result_t*i = (internal_result_t*)r->internal;
825     if(i->use_tempfile) {
826         move_file(i->filename, filename);
827     } else {
828         FILE*fi = fopen(filename, "wb");
829         if(!fi) {
830             fprintf(stderr, "Couldn't open file %s for writing\n", filename);
831             return -1;
832         }
833         fwrite(i->data, i->length, 1, fi);
834         fclose(fi);
835     }
836     return 0;
837 }
838 static void*record_result_get(gfxresult_t*r, const char*name)
839 {
840     internal_result_t*i = (internal_result_t*)r->internal;
841     if(!strcmp(name, "data")) {
842         return i->data;
843     } else if(!strcmp(name, "length")) {
844         return &i->length;
845     }
846     return 0;
847 }
848 static void record_result_destroy(gfxresult_t*r)
849 {
850     internal_result_t*i = (internal_result_t*)r->internal;
851     if(i->data) {
852         free(i->data);i->data = 0;
853     }
854     if(i->filename) {
855         unlink(i->filename);
856         free(i->filename);
857     }
858     free(r->internal);r->internal = 0;
859     free(r);
860 }
861
862 static unsigned char printable(unsigned char a)
863 {
864     if(a<32 || a==127) return '.';
865     else return a;
866 }
867
868 static void hexdumpMem(unsigned char*data, int len)
869 {
870     int t;
871     char ascii[32];
872     for(t=0;t<len;t++) {
873         printf("%02x ", data[t]);
874         ascii[t&15] = printable(data[t]);
875         if((t && ((t&15)==15)) || (t==len-1))
876         {
877             int s,p=((t)&15)+1;
878             ascii[p] = 0;
879             for(s=p-1;s<16;s++) {
880                 printf("   ");
881             }
882             printf(" %s\n", ascii);
883         }
884     }
885 }
886
887 void gfxdevice_record_flush(gfxdevice_t*dev, gfxdevice_t*out)
888 {
889     internal_t*i = (internal_t*)dev->internal;
890     if(out) {
891         if(!i->use_tempfile) {
892             int len=0;
893             void*data = writer_growmemwrite_memptr(&i->w, &len);
894             reader_t r;
895             reader_init_memreader(&r, data, len);
896             replay(dev, out, &r);
897             writer_growmemwrite_reset(&i->w);
898         } else {
899             msg("<fatal> Flushing not supported for file based record device");
900             exit(1);
901         }
902     }
903 }
904
905 static gfxresult_t* record_finish(struct _gfxdevice*dev)
906 {
907     internal_t*i = (internal_t*)dev->internal;
908     msg("<trace> record: %08x END", dev);
909
910     if(i->cliplevel) {
911         msg("<error> Warning: unclosed cliplevels");
912     }
913
914 #ifdef STATS
915     int total = i->w.pos;
916     if(total && i->use_tempfile) {
917         state_t*s = &i->state;
918         msg("<notice> record device finished. stats:");
919         msg("<notice> %4.1f%% matrices (%d bytes)", s->size_matrices*100.0/total, s->size_matrices);
920         msg("<notice> %4.1f%% positions (%d bytes)", s->size_positions*100.0/total, s->size_positions);
921         msg("<notice> %4.1f%% colors (%d bytes)", s->size_colors*100.0/total, s->size_colors);
922         msg("<notice> %4.1f%% lines (%d bytes)", s->size_lines*100.0/total, s->size_lines);
923         msg("<notice> %4.1f%% fonts (%d bytes)", s->size_fonts*100.0/total, s->size_fonts);
924         msg("<notice> %4.1f%% images (%d bytes)", s->size_images*100.0/total, s->size_images);
925         msg("<notice> %4.1f%% characters (%d bytes)", s->size_chars*100.0/total, s->size_chars);
926         msg("<notice> total: %d bytes", total);
927     }
928 #endif
929     
930     writer_writeU8(&i->w, OP_END);
931     
932     gfxfontlist_free(i->fontlist, 0);
933    
934     internal_result_t*ir = (internal_result_t*)rfx_calloc(sizeof(gfxresult_t));
935    
936     ir->use_tempfile = i->use_tempfile;
937     if(i->use_tempfile) {
938         ir->filename = i->filename;
939     } else {
940         ir->data = writer_growmemwrite_getmem(&i->w);
941         ir->length = i->w.pos;
942     }
943     i->w.finish(&i->w);
944
945     gfxresult_t*result= (gfxresult_t*)rfx_calloc(sizeof(gfxresult_t));
946     result->save = record_result_save;
947     result->get = record_result_get;
948     result->destroy = record_result_destroy;
949     result->internal = ir;
950
951     free(dev->internal);memset(dev, 0, sizeof(gfxdevice_t));
952     
953     return result;
954 }
955
956 void gfxdevice_record_init(gfxdevice_t*dev, char use_tempfile)
957 {
958     internal_t*i = (internal_t*)rfx_calloc(sizeof(internal_t));
959     memset(dev, 0, sizeof(gfxdevice_t));
960     
961     dev->name = "record";
962
963     dev->internal = i;
964   
965     i->use_tempfile = use_tempfile;
966     if(!use_tempfile) {
967         writer_init_growingmemwriter(&i->w, 1048576);
968     } else {
969         char buffer[128];
970         i->filename = strdup(mktempname(buffer, "gfx"));
971         writer_init_filewriter2(&i->w, i->filename);
972     }
973     i->fontlist = gfxfontlist_create();
974     i->cliplevel = 0;
975
976     dev->setparameter = record_setparameter;
977     dev->startpage = record_startpage;
978     dev->startclip = record_startclip;
979     dev->endclip = record_endclip;
980     dev->stroke = record_stroke;
981     dev->fill = record_fill;
982     dev->fillbitmap = record_fillbitmap;
983     dev->fillgradient = record_fillgradient;
984     dev->addfont = record_addfont;
985     dev->drawchar = record_drawchar;
986     dev->drawlink = record_drawlink;
987     dev->endpage = record_endpage;
988     dev->finish = record_finish;
989 }
990