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