fixed vertical alignment bug
[swftools.git] / lib / pdf / GFXOutputDev.cc
index 227ea4d..940f5a0 100644 (file)
 #endif
 //xpdf header files
 #include "config.h"
+#ifdef HAVE_POPPLER
+#include <goo/GooString.h>
+#include <goo/gfile.h>
+#else
 #include "gfile.h"
 #include "GString.h"
-#include "gmem.h"
+#endif
 #include "Object.h"
 #include "Stream.h"
 #include "Array.h"
 #include "OutputDev.h"
 #include "GfxFont.h"
 #include "GfxState.h"
-#include "CharCodeToUnicode.h"
 #include "NameToUnicodeTable.h"
 #include "GlobalParams.h"
-#include "FoFiType1C.h"
-#include "FoFiTrueType.h"
-#include "GHash.h"
 #include "GFXOutputDev.h"
 
 //  swftools header files
 #include "../devices/polyops.h"
 #include "../devices/render.h"
 
-#include "../art/libart.h"
-
 #include "../png.h"
 #include "fonts.h"
 
 #include <math.h>
 
+#define SQRT2 1.41421356237309504880
+
 typedef struct _fontfile
 {
     const char*filename;
@@ -125,7 +125,7 @@ struct fontentry {
 
 
 static int verbose = 0;
-static int dbgindent = 0;
+static int dbgindent = 1;
 static void dbg(const char*format, ...)
 {
     char buf[1024];
@@ -540,7 +540,7 @@ GFXOutputDev::GFXOutputDev(InfoOutputDev*info, PDFDoc*doc)
     this->info = info;
     this->doc = doc;
     this->xref = doc->getXRef();
-
+    
     this->jpeginfo = 0;
     this->textmodeinfo = 0;
     this->linkinfo = 0;
@@ -564,15 +564,18 @@ GFXOutputDev::GFXOutputDev(InfoOutputDev*info, PDFDoc*doc)
     this->pages = 0;
     this->pagebuflen = 0;
     this->pagepos = 0;
-    this->config_convertgradients=0;
+    this->config_bigchar=0;
+    this->config_convertgradients=1;
     this->config_break_on_warning=0;
     this->config_remapunicode=0;
     this->config_transparent=0;
     this->config_extrafontdata = 0;
     this->config_fontquality = 10;
     this->config_optimize_polygons = 0;
+    this->config_multiply = 1;
 
     this->gfxfontlist = gfxfontlist_create();
+    this->dashPattern = 0;
   
     memset(states, 0, sizeof(states));
     this->featurewarnings = 0;
@@ -590,19 +593,18 @@ void GFXOutputDev::setParameter(const char*key, const char*value)
         this->config_extrafontdata = atoi(value);
     } else if(!strcmp(key,"convertgradients")) {
         this->config_convertgradients = atoi(value);
+    } else if(!strcmp(key,"multiply")) {
+        this->config_multiply = atoi(value);
+        if(this->config_multiply<1) 
+            this->config_multiply=1;
     } else if(!strcmp(key,"optimize_polygons")) {
         this->config_optimize_polygons = atoi(value);
+    } else if(!strcmp(key,"bigchar")) {
+        this->config_bigchar = atoi(value);
     } else if(!strcmp(key,"fontquality")) {
         this->config_fontquality = atof(value);
        if(this->config_fontquality<=1)
            this->config_fontquality=1;
-    } else if(!strcmp(key,"help")) {
-       printf("\nPDF layer options:\n");
-       printf("breakonwarning=0/1  Abort conversion if graphic objects are found which\n");
-       printf("                    are not 100%% supported\n");
-       printf("transparent=0/1     Make PDF transparent (alpha background)\n");
-       printf("extrafontdata=0/1   Store Type3 characters and capture characters\n");
-       printf("fontquality=1..100  Curve approximation quality of the fonts\n");
     }
     
 }
@@ -1003,6 +1005,8 @@ GBool GFXOutputDev::axialShadedFill(GfxState *state, GfxAxialShading *shading)
     m.ty = (y0 + y1)/2 - 0.5;
 
     device->fillgradient(device, &p1, g, gfxgradient_linear, &m);
+
+    free(g);
     return gTrue;
 }
   
@@ -1026,8 +1030,13 @@ void GFXOutputDev::endPage()
        device->endclip(device);
        outer_clip_box = 0;
     }
+    this->dashPattern = 0;
+    /* notice: we're not fully done yet with this page- there might still be 
+       a few calls to drawLink() yet to come */
 }
 
+static inline double sqr(double x) {return x*x;}
+
 #define STROKE_FILL 1
 #define STROKE_CLIP 2
 void GFXOutputDev::strokeGfxline(GfxState *state, gfxline_t*line, int flags)
@@ -1048,7 +1057,7 @@ void GFXOutputDev::strokeGfxline(GfxState *state, gfxline_t*line, int flags)
     col.g = colToByte(rgb.g);
     col.b = colToByte(rgb.b);
     col.a = (unsigned char)(opaq*255);
-   
+
     gfx_capType capType = gfx_capRound;
     if(lineCap == 0) capType = gfx_capButt;
     else if(lineCap == 1) capType = gfx_capRound;
@@ -1059,28 +1068,39 @@ void GFXOutputDev::strokeGfxline(GfxState *state, gfxline_t*line, int flags)
     else if(lineJoin == 1) joinType = gfx_joinRound;
     else if(lineJoin == 2) joinType = gfx_joinBevel;
 
-    int dashnum = 0;
-    double dashphase = 0;
-    double * ldash = 0;
-    state->getLineDash(&ldash, &dashnum, &dashphase);
-
     gfxline_t*line2 = 0;
 
-    if(dashnum && ldash) {
-       float * dash = (float*)malloc(sizeof(float)*(dashnum+1));
+    if(this->dashLength && this->dashPattern) {
+       float * dash = (float*)malloc(sizeof(float)*(this->dashLength+1));
        int t;
-       msg("<trace> %d dashes", dashnum);
-       msg("<trace> |  phase: %f", dashphase);
-       for(t=0;t<dashnum;t++) {
-           dash[t] = (float)ldash[t];
-           msg("<trace> |  d%-3d: %f", t, ldash[t]);
+
+        /* try to find out how much the transformation matrix would
+           stretch the dashes, and factor that into the dash lengths.
+           This is not the entirely correct approach- it would be 
+           better to first convert the path to an unscaled version,
+           then apply dashing, and then transform the path using
+           the current transformation matrix. However there are few
+           PDFs which actually stretch a dashed path in a non-orthonormal
+           way */
+        double tx1, ty1, tx2, ty2;
+       this->transformXY(state, 0, 0, &tx1, &ty1);
+       this->transformXY(state, 1, 1, &tx2, &ty2);
+        double f = sqrt(sqr(tx2-tx1)+sqr(ty2-ty1)) / SQRT2;
+
+       msg("<trace> %d dashes", this->dashLength);
+       msg("<trace> |  phase: %f", this->dashStart);
+       for(t=0;t<this->dashLength;t++) {
+           dash[t] = (float)this->dashPattern[t] * f;
+            if(!dash[t])
+                dash[t] = 1e-37;
+           msg("<trace> |  d%-3d: %f", t, this->dashPattern[t]);
        }
-       dash[dashnum] = -1;
+       dash[this->dashLength] = -1;
        if(getLogLevel() >= LOGLEVEL_TRACE) {
            dump_outline(line);
        }
 
-       line2 = gfxtool_dash_line(line, dash, (float)dashphase);
+       line2 = gfxtool_dash_line(line, dash, (float)(this->dashStart*f));
        line = line2;
        free(dash);
        msg("<trace> After dashing:");
@@ -1091,7 +1111,7 @@ void GFXOutputDev::strokeGfxline(GfxState *state, gfxline_t*line, int flags)
                width,
                lineJoin==0?"miter": (lineJoin==1?"round":"bevel"),
                lineCap==0?"butt": (lineJoin==1?"round":"square"),
-               dashnum,
+               this->dashLength,
                col.r,col.g,col.b,col.a
                );
         dump_outline(line);
@@ -1112,7 +1132,7 @@ void GFXOutputDev::strokeGfxline(GfxState *state, gfxline_t*line, int flags)
         } else {
             device->fill(device, gfxline, &col);
         }
-        free(gfxline);
+        gfxline_free(gfxline);
        gfxpoly_free(poly);
     } else {
         if(flags&STROKE_CLIP) 
@@ -1187,7 +1207,8 @@ void GFXOutputDev::clipToStrokePath(GfxState *state)
     gfxline_t*line= gfxPath_to_gfxline(state, path, 0, user_movex + clipmovex, user_movey + clipmovey);
 
     if(getLogLevel() >= LOGLEVEL_TRACE)  {
-        msg("<trace> cliptostrokepath");
+        double width = state->getTransformedLineWidth();
+        msg("<trace> cliptostrokepath width=%f", width);
         dump_outline(line);
     }
 
@@ -1212,6 +1233,9 @@ GFXOutputDev::~GFXOutputDev()
     if(this->pages) {
        free(this->pages); this->pages = 0;
     }
+    if(this->dashPattern) {
+        free(this->dashPattern);this->dashPattern = 0;
+    }
     
     feature_t*f = this->featurewarnings;
     while(f) {
@@ -1348,7 +1372,8 @@ void GFXOutputDev::drawChar(GfxState *state, double x, double y,
     msg("<debug> drawChar(%f,%f,c='%c' (%d), u=%d <%d>) CID=%d render=%d glyphid=%d font=%08x",x,y,(charid&127)>=32?charid:'?', charid, u, uLen, font->isCIDFont(), render, glyphid, current_gfxfont);
 
     gfxmatrix_t m = this->current_font_matrix;
-    this->transformXY(state, x, y, &m.tx, &m.ty);
+    this->transformXY(state, x-originX, y-originY, &m.tx, &m.ty);
+    //m.tx += originX; m.ty += originY;
 
     if(render == RENDER_FILL || render == RENDER_INVISIBLE) {
        device->drawchar(device, current_gfxfont, glyphid, &col, &m);
@@ -1527,6 +1552,10 @@ void GFXOutputDev::startPage(int pageNum, GfxState *state, double crop_x1, doubl
     states[statepos].clipbbox.ymin = x1;
     states[statepos].clipbbox.xmax = x2;
     states[statepos].clipbbox.ymax = y2;
+    
+    this->dashPattern = 0;
+    this->dashLength = 0;
+    this->dashStart = 0;
 }
 
 
@@ -1719,45 +1748,70 @@ void GFXOutputDev::processLink(Link *link, Catalog *catalog)
 }
 
 void GFXOutputDev::saveState(GfxState *state) {
-    dbg("saveState");dbgindent+=2;
+    dbg("saveState %08x", state); dbgindent+=2;
 
-    msg("<trace> saveState");
+    msg("<trace> saveState %08x", state);
     updateAll(state);
     if(statepos>=64) {
-      msg("<error> Too many nested states in pdf.");
-      return;
+      msg("<fatal> Too many nested states in pdf.");
+      exit(1);
     }
     statepos ++;
+    states[statepos].state = state;
     states[statepos].createsoftmask = states[statepos-1].createsoftmask;
     states[statepos].transparencygroup = states[statepos-1].transparencygroup;
     states[statepos].clipping = 0;
+    states[statepos].olddevice = 0;
     states[statepos].clipbbox = states[statepos-1].clipbbox;
 };
 
 void GFXOutputDev::restoreState(GfxState *state) {
-  dbgindent-=2; dbg("restoreState");
+  dbgindent-=2; dbg("restoreState %08x", state);
 
   if(statepos==0) {
-      msg("<error> Invalid restoreState");
-      return;
+      msg("<fatal> Invalid restoreState");
+      exit(1);
   }
-  msg("<trace> restoreState%s%s", states[statepos].softmask?" (end softmask)":"",
+  msg("<trace> restoreState %08x%s%s", state,
+                                 states[statepos].softmask?" (end softmask)":"",
                                  states[statepos].clipping?" (end clipping)":"");
   if(states[statepos].softmask) {
       clearSoftMask(state);
   }
   updateAll(state);
+  
   while(states[statepos].clipping) {
       device->endclip(device);
       states[statepos].clipping--;
   }
+  if(states[statepos].state!=state) {
+      msg("<fatal> bad state nesting");
+      exit(1);
+  }
+  states[statepos].state=0;
   statepos--;
 }
+void GFXOutputDev::updateLineDash(GfxState *state) 
+{
+    if(this->dashPattern) {
+        free(this->dashPattern);this->dashPattern = 0;
+    }
+    double *pattern = 0;
+    state->getLineDash(&pattern, &this->dashLength, &this->dashStart);
+    msg("<debug> updateLineDash, %d dashes", this->dashLength);
+    if(!this->dashLength) {
+        this->dashPattern = 0;
+    } else {
+        double*p = (double*)malloc(this->dashLength*sizeof(this->dashPattern[0]));
+        memcpy(p, pattern, this->dashLength*sizeof(this->dashPattern[0]));
+        this->dashPattern = p;
+    }
+}
 
 void GFXOutputDev::updateLineWidth(GfxState *state)
 {
     double width = state->getTransformedLineWidth();
-    //swfoutput_setlinewidth(&device, width);
 }
 
 void GFXOutputDev::updateLineCap(GfxState *state)
@@ -1812,7 +1866,7 @@ void GFXOutputDev::updateStrokeColor(GfxState *state)
 }
 
 
-static gfxfont_t* createGfxFont(GfxFont*xpdffont, FontInfo*src, double config_fontquality)
+gfxfont_t* GFXOutputDev::createGfxFont(GfxFont*xpdffont, FontInfo*src)
 {
     gfxfont_t*font = (gfxfont_t*)malloc(sizeof(gfxfont_t));
     memset(font, 0, sizeof(gfxfont_t));
@@ -1821,11 +1875,14 @@ static gfxfont_t* createGfxFont(GfxFont*xpdffont, FontInfo*src, double config_fo
     memset(font->glyphs, 0, sizeof(gfxglyph_t)*src->num_glyphs);
     font->id = 0;
     int t;
-    
+
     double quality = (INTERNAL_FONT_SIZE * 200 / config_fontquality) / src->max_size;
     double scale = 1;
     //printf("%d glyphs\n", font->num_glyphs);
     font->num_glyphs = 0;
+    font->ascent = fabs(src->descender);
+    font->descent = fabs(src->ascender);
+    
     for(t=0;t<src->num_glyphs;t++) {
        if(src->glyphs[t]) {
            SplashPath*path = src->glyphs[t]->path;
@@ -1867,8 +1924,21 @@ static gfxfont_t* createGfxFont(GfxFont*xpdffont, FontInfo*src, double config_fo
             //                           (f&splashPathFirst)?"first":"",
             //                           (f&splashPathLast)?"last":"");
            }
+
            glyph->line = (gfxline_t*)drawer.result(&drawer);
-           glyph->advance = xmax*scale; // we don't know the real advance value, so this'll have to do
+           if(src->glyphs[t]->advance>0) {
+               glyph->advance = src->glyphs[t]->advance;
+           } else {
+               msg("<warning> Approximating advance value for glyph %d", t);
+               glyph->advance = xmax*scale;
+           }
+           if(this->config_bigchar) {
+               double max = src->glyphs[t]->advance_max;
+               if(max>0 && max > glyph->advance) {
+                   glyph->advance = max;
+               }
+           }
+
            font->num_glyphs++;
        }
     }
@@ -1914,7 +1984,7 @@ void GFXOutputDev::updateFont(GfxState *state)
     
     gfxfont_t*font = gfxfontlist_findfont(this->gfxfontlist,id);
     if(!font) {
-       font = createGfxFont(gfxFont, current_fontinfo, this->config_fontquality);
+       font = this->createGfxFont(gfxFont, current_fontinfo);
         font->id = strdup(id);
        this->gfxfontlist = gfxfontlist_addfont(this->gfxfontlist, font);
     }
@@ -1930,14 +2000,14 @@ void GFXOutputDev::updateFont(GfxState *state)
 
 unsigned char* antialize(unsigned char*data, int width, int height, int newwidth, int newheight, int palettesize)
 {
-    if((newwidth<2 || newheight<2) ||
+    if((newwidth<1 || newheight<1) ||
        (width<=newwidth || height<=newheight))
        return 0;
     unsigned char*newdata;
     int x,y;
     newdata= (unsigned char*)malloc(newwidth*newheight);
-    double fx = (double)(width)/newwidth;
-    double fy = (double)(height)/newheight;
+    double fx = ((double)width)/newwidth;
+    double fy = ((double)height)/newheight;
     double px = 0;
     int blocksize = (int)(8192/(fx*fy));
     int r = 8192*256/palettesize;
@@ -1945,17 +2015,21 @@ unsigned char* antialize(unsigned char*data, int width, int height, int newwidth
        double ex = px + fx;
        int fromx = (int)px;
        int tox = (int)ex;
-       int xweight1 = (int)(((fromx+1)-px)*256);
+       int xweight1 = (int)((1-(px-fromx))*256);
        int xweight2 = (int)((ex-tox)*256);
        double py =0;
        for(y=0;y<newheight;y++) {
            double ey = py + fy;
            int fromy = (int)py;
            int toy = (int)ey;
-           int yweight1 = (int)(((fromy+1)-py)*256);
+           int yweight1 = (int)((1-(py-fromy))*256);
            int yweight2 = (int)((ey-toy)*256);
            int a = 0;
            int xx,yy;
+            if(tox>=width) 
+                tox = width-1;
+            if(toy>=height) 
+                toy = height-1;
            for(xx=fromx;xx<=tox;xx++)
            for(yy=fromy;yy<=toy;yy++) {
                int b = 1-data[width*yy+xx];
@@ -1982,7 +2056,7 @@ static void drawimage(gfxdevice_t*dev, gfxcolor_t* data, int sizex,int sizey,
         double x1,double y1,
         double x2,double y2,
         double x3,double y3,
-        double x4,double y4, int type)
+        double x4,double y4, int type, int multiply)
 {
     gfxcolor_t*newpic=0;
     
@@ -2007,12 +2081,13 @@ static void drawimage(gfxdevice_t*dev, gfxcolor_t* data, int sizex,int sizey,
      p5.x = (int)(p5.x*20)/20.0;
      p5.y = (int)(p5.y*20)/20.0;
     }
-    
+
     gfxmatrix_t m;
     m.m00 = (p4.x-p1.x)/sizex; m.m10 = (p2.x-p1.x)/sizey;
     m.m01 = (p4.y-p1.y)/sizex; m.m11 = (p2.y-p1.y)/sizey;
-    m.tx = p1.x - 0.5;
-    m.ty = p1.y - 0.5;
+        
+    m.tx = p1.x - 0.5*multiply;
+    m.ty = p1.y - 0.5*multiply;
 
     gfximage_t img;
     img.data = (gfxcolor_t*)data;
@@ -2023,19 +2098,20 @@ static void drawimage(gfxdevice_t*dev, gfxcolor_t* data, int sizex,int sizey,
        /* TODO: pass image_dpi to device instead */
        dev->setparameter(dev, "next_bitmap_is_jpeg", "1");
 
+    dump_outline(&p1);
     dev->fillbitmap(dev, &p1, &img, &m, 0);
 }
 
 void drawimagejpeg(gfxdevice_t*dev, gfxcolor_t*mem, int sizex,int sizey, 
-        double x1,double y1, double x2,double y2, double x3,double y3, double x4,double y4)
+        double x1,double y1, double x2,double y2, double x3,double y3, double x4,double y4, int multiply)
 {
-    drawimage(dev,mem,sizex,sizey,x1,y1,x2,y2,x3,y3,x4,y4, IMAGE_TYPE_JPEG);
+    drawimage(dev,mem,sizex,sizey,x1,y1,x2,y2,x3,y3,x4,y4, IMAGE_TYPE_JPEG, multiply);
 }
 
 void drawimagelossless(gfxdevice_t*dev, gfxcolor_t*mem, int sizex,int sizey, 
-        double x1,double y1, double x2,double y2, double x3,double y3, double x4,double y4)
+        double x1,double y1, double x2,double y2, double x3,double y3, double x4,double y4, int multiply)
 {
-    drawimage(dev,mem,sizex,sizey,x1,y1,x2,y2,x3,y3,x4,y4, IMAGE_TYPE_LOSSLESS);
+    drawimage(dev,mem,sizex,sizey,x1,y1,x2,y2,x3,y3,x4,y4, IMAGE_TYPE_LOSSLESS, multiply);
 }
 
 
@@ -2044,6 +2120,8 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
                                   GBool inlineImg, int mask, int*maskColors,
                                   Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert, GfxImageColorMap*maskColorMap)
 {
+  /* the code in this function is *old*. It's not pretty, but it works. */
+
   double x1,y1,x2,y2,x3,y3,x4,y4;
   ImageStream *imgStr;
   Guchar pixBuf[4];
@@ -2098,7 +2176,7 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
   imgStr = new ImageStream(str, width, ncomps,bits);
   imgStr->reset();
 
-  if(!width || !height || (height<=1 && width<=1 && maskWidth<=1 && maskHeight<=1))
+  if(!width || !height || ((height+width)<=1 && (maskWidth+maskHeight)<=1))
   {
       msg("<verbose> Ignoring %d by %d image", width, height);
       unsigned char buf[8];
@@ -2118,6 +2196,16 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
   this->transformXY(state, 1, 0, &x3, &y3);
   this->transformXY(state, 1, 1, &x4, &y4);
 
+  if(type3active) {
+      /* as type 3 bitmaps are antialized, we need to place them
+        at integer coordinates, otherwise flash player's antializing
+        will kick in and make everything blurry */
+      x1 = (int)(x1);y1 = (int)(y1);
+      x2 = (int)(x2);y2 = (int)(y2);
+      x3 = (int)(x3);y3 = (int)(y3);
+      x4 = (int)(x4);y4 = (int)(y4);
+  }
+
   if(!pbminfo && !(str->getKind()==strDCT)) {
       if(!type3active) {
          msg("<notice> File contains pbm pictures %s",mask?"(masked)":"");
@@ -2156,11 +2244,7 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
                buf[0]=1-buf[0];
            pic[width*y+x] = buf[0];
       }
-      
-      /* the size of the drawn image is added to the identifier
-        as the same image may require different bitmaps if displayed
-        at different sizes (due to antialiasing): */
-      int found = -1;
+     
       if(type3active) {
          unsigned char*pic2 = 0;
          numpalette = 16;
@@ -2172,7 +2256,7 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
            delete imgStr;
            return;
          }
-
+          
          width = realwidth;
          height = realheight;
          delete[] pic;
@@ -2188,6 +2272,7 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
              pal[t].b = colToByte(rgb.b);
              pal[t].a = (unsigned char)(t*r);
          }
+          
       }
 
       gfxcolor_t*pic2 = new gfxcolor_t[width*height];
@@ -2196,7 +2281,7 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
          pic2[width*y+x] = pal[pic[y*width+x]];
        }
       }
-      drawimagelossless(device, pic2, width, height, x1,y1,x2,y2,x3,y3,x4,y4);
+      drawimagelossless(device, pic2, width, height, x1,y1,x2,y2,x3,y3,x4,y4, config_multiply);
       delete[] pic2;
       delete[] pic;
       delete imgStr;
@@ -2217,14 +2302,30 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
          pic[width*y+x].b = (unsigned char)(colToByte(rgb.b));
          pic[width*y+x].a = 255;//(U8)(rgb.a * 255 + 0.5);
          if(maskbitmap) {
-             pic[width*y+x].a = maskbitmap[(y*maskHeight/height)*maskWidth+(x*maskWidth/width)];
+              int x1 = x*maskWidth/width;
+              int y1 = y*maskHeight/height;
+              int x2 = (x+1)*maskWidth/width;
+              int y2 = (y+1)*maskHeight/height;
+              int xx,yy;
+              unsigned int alpha=0;
+              unsigned int count=0;
+              for(xx=x1;xx<x2;xx++)
+              for(yy=y1;yy<y2;yy++) {
+                  alpha += maskbitmap[yy*maskWidth+xx];
+                  count ++;
+              }
+              if(count) {
+                pic[width*y+x].a = alpha / count;
+              } else {
+                pic[width*y+x].a = maskbitmap[y1*maskWidth+x1];
+              }
          }
        }
       }
       if(str->getKind()==strDCT)
-         drawimagejpeg(device, pic, width, height, x1,y1,x2,y2,x3,y3,x4,y4);
+         drawimagejpeg(device, pic, width, height, x1,y1,x2,y2,x3,y3,x4,y4, config_multiply);
       else
-         drawimagelossless(device, pic, width, height, x1,y1,x2,y2,x3,y3,x4,y4);
+         drawimagelossless(device, pic, width, height, x1,y1,x2,y2,x3,y3,x4,y4, config_multiply);
       delete[] pic;
       delete imgStr;
       if(maskbitmap) free(maskbitmap);
@@ -2299,7 +2400,7 @@ void GFXOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
              height = maskHeight;
          }
       }
-      drawimagelossless(device, pic, width, height, x1,y1,x2,y2,x3,y3,x4,y4);
+      drawimagelossless(device, pic, width, height, x1,y1,x2,y2,x3,y3,x4,y4, config_multiply);
 
       delete[] pic;
       delete imgStr;
@@ -2511,17 +2612,20 @@ void GFXOutputDev::preparePage(int pdfpage, int outputpage)
 
     if(!this->pages) {
        this->pagebuflen = 1024;
+       if(pdfpage > this->pagebuflen)
+           this->pagebuflen = pdfpage+1;
        this->pages = (int*)malloc(this->pagebuflen*sizeof(int));
        memset(this->pages, -1, this->pagebuflen*sizeof(int));
-    } else {
-       while(pdfpage >= this->pagebuflen)
-       {
-           int oldlen = this->pagebuflen;
-           this->pagebuflen+=1024;
-           this->pages = (int*)realloc(this->pages, this->pagebuflen*sizeof(int));
-           memset(&this->pages[oldlen], -1, (this->pagebuflen-oldlen)*sizeof(int));
-       }
     }
+
+    while(pdfpage >= this->pagebuflen)
+    {
+       int oldlen = this->pagebuflen;
+       this->pagebuflen+=1024;
+       this->pages = (int*)realloc(this->pages, this->pagebuflen*sizeof(int));
+       memset(&this->pages[oldlen], -1, (this->pagebuflen-oldlen)*sizeof(int));
+    }
+
     this->pages[pdfpage] = outputpage;
     if(pdfpage>this->pagepos)
        this->pagepos = pdfpage;
@@ -2533,11 +2637,11 @@ void GFXOutputDev::beginTransparencyGroup(GfxState *state, double *bbox,
                                      GBool forSoftMask)
 {
     const char*colormodename = "";
-
+  
     if(blendingColorSpace) {
        colormodename = GfxColorSpace::getColorSpaceModeName(blendingColorSpace->getMode());
     }
-    dbg("beginTransparencyGroup %.1f/%.1f/%.1f/%.1f %s isolated=%d knockout=%d forsoftmask=%d", bbox[0],bbox[1],bbox[2],bbox[3], colormodename, isolated, knockout, forSoftMask);
+    dbg("beginTransparencyGroup device=%08x %.1f/%.1f/%.1f/%.1f %s isolated=%d knockout=%d forsoftmask=%d", device, bbox[0],bbox[1],bbox[2],bbox[3], colormodename, isolated, knockout, forSoftMask);
     msg("<verbose> beginTransparencyGroup %.1f/%.1f/%.1f/%.1f %s isolated=%d knockout=%d forsoftmask=%d", bbox[0],bbox[1],bbox[2],bbox[3], colormodename, isolated, knockout, forSoftMask);
     
     //states[statepos].createsoftmask |= forSoftMask;
@@ -2547,6 +2651,7 @@ void GFXOutputDev::beginTransparencyGroup(GfxState *state, double *bbox,
 
     states[statepos].olddevice = this->device;
     this->device = (gfxdevice_t*)rfx_calloc(sizeof(gfxdevice_t));
+    dbg("this->device now %08x (old: %08x)", this->device, states[statepos].olddevice);
 
     gfxdevice_record_init(this->device);
     
@@ -2561,11 +2666,21 @@ void GFXOutputDev::endTransparencyGroup(GfxState *state)
     dbgindent-=2;
     gfxdevice_t*r = this->device;
 
+    dbg("endTransparencyGroup this->device now back to %08x (destroying %08x)", states[statepos].olddevice, this->device);
+    
     this->device = states[statepos].olddevice;
+    if(!this->device) {
+       msg("<fatal> bad state nesting in transparency group- PDF file broken?");
+       /* if these errors occur more often, we should build a seperate
+          transparency group stack, like xpdf/SplashOutputDev.cc does */
+       restoreState(state);
+       this->device = states[statepos].olddevice;
+    }
+    states[statepos].olddevice = 0;
 
     gfxresult_t*recording = r->finish(r);
     
-    dbg("endTransparencyGroup forsoftmask=%d recording=%08x/%08x", states[statepos].createsoftmask, r, recording);
+    dbg("                     forsoftmask=%d recording=%08x/%08x", states[statepos].createsoftmask, r, recording);
     msg("<verbose> endTransparencyGroup forsoftmask=%d recording=%08x/%08x", states[statepos].createsoftmask, r, recording);
 
     if(states[statepos].createsoftmask) {
@@ -2585,9 +2700,9 @@ void GFXOutputDev::paintTransparencyGroup(GfxState *state, double *bbox)
                                "colordodge","colorburn","hardlight","softlight","difference",
                                "exclusion","hue","saturation","color","luminosity"};
 
-    dbg("paintTransparencyGroup blend=%s softmaskon=%d", blendmodes[state->getBlendMode()], states[statepos].softmask);
+    dbg("paintTransparencyGroup blend=%s softmaskon=%d recording=%08x", blendmodes[state->getBlendMode()], states[statepos].softmask, states[statepos].grouprecording);
     msg("<verbose> paintTransparencyGroup blend=%s softmaskon=%d", blendmodes[state->getBlendMode()], states[statepos].softmask);
-   
+
     if(state->getBlendMode() == gfxBlendNormal)
        infofeature("transparency groups");
     else {
@@ -2604,6 +2719,7 @@ void GFXOutputDev::paintTransparencyGroup(GfxState *state, double *bbox)
        if(blendmode == gfxBlendMultiply && alpha>200)
            alpha = 128;
        gfxdevice_t ops;
+       dbg("this->device=%08x, this->device->name=%s\n", this->device, this->device->name);
        gfxdevice_ops_init(&ops, this->device, alpha);
        gfxresult_record_replay(grouprecording, &ops);
        ops.finish(&ops);
@@ -2615,8 +2731,14 @@ void GFXOutputDev::paintTransparencyGroup(GfxState *state, double *bbox)
 
 void GFXOutputDev::setSoftMask(GfxState *state, double *bbox, GBool alpha, Function *transferFunc, GfxColor *rgb)
 {
+    if(states[statepos].softmask) {
+       /* shouldn't happen, but *does* happen */
+       clearSoftMask(state);
+    }
+
     /* alpha = 1: retrieve mask values from alpha layer
        alpha = 0: retrieve mask values from luminance */
+
     dbg("setSoftMask %.1f/%.1f/%.1f/%.1f alpha=%d backdrop=%02x%02x%02x",
            bbox[0], bbox[1], bbox[2], bbox[3], alpha, colToByte(rgb->c[0]), colToByte(rgb->c[1]), colToByte(rgb->c[2]));
     msg("<verbose> setSoftMask %.1f/%.1f/%.1f/%.1f alpha=%d backdrop=%02x%02x%02x",
@@ -2625,12 +2747,16 @@ void GFXOutputDev::setSoftMask(GfxState *state, double *bbox, GBool alpha, Funct
        infofeature("soft masks");
     else
        warnfeature("soft masks from alpha channel",0);
-    
+   
+    if(states[statepos].olddevice) {
+       msg("<fatal> Internal error: badly balanced softmasks/transparency groups");
+       exit(1);
+    }
     states[statepos].olddevice = this->device;
     this->device = (gfxdevice_t*)rfx_calloc(sizeof(gfxdevice_t));
     gfxdevice_record_init(this->device);
 
-    dbg("softmaskrecording is %08x at statepos %d\n", states[statepos].softmaskrecording, statepos);
+    dbg("softmaskrecording is %08x (dev=%08x) at statepos %d\n", states[statepos].softmaskrecording, this->device, statepos);
     
     states[statepos].softmask = 1;
     states[statepos].softmask_alpha = alpha;
@@ -2653,7 +2779,7 @@ void GFXOutputDev::clearSoftMask(GfxState *state)
        return;
     states[statepos].softmask = 0;
     dbg("clearSoftMask statepos=%d", statepos);
-    msg("<verbose> clearSoftMask");
+    msg("<verbose> clearSoftMask statepos=%d", statepos);
     
     if(!states[statepos].softmaskrecording || strcmp(this->device->name, "record")) {
        msg("<error> Error in softmask/tgroup ordering");