-/*\r
- * File: ximagif.cpp\r
- * Purpose: Platform Independent GIF Image Class Loader and Writer\r
- * 07/Aug/2001 Davide Pizzolato - www.xdp.it\r
- * CxImage version 6.0.0 02/Feb/2008\r
- */\r
-\r
-#include "ximagif.h"\r
-\r
-#if CXIMAGE_SUPPORT_GIF\r
-\r
-#include "ximaiter.h"\r
-\r
-#if defined (_WIN32_WCE)\r
- #define assert(s)\r
-#else\r
- #include <assert.h>\r
-#endif\r
-\r
-////////////////////////////////////////////////////////////////////////////////\r
-#if CXIMAGE_SUPPORT_DECODE\r
-////////////////////////////////////////////////////////////////////////////////\r
-bool CxImageGIF::Decode(CxFile *fp)\r
-{\r
- /* AD - for transparency */\r
- struct_dscgif dscgif;\r
- struct_image image;\r
- struct_TabCol TabCol;\r
-\r
- if (fp == NULL) return false;\r
-\r
- fp->Read(&dscgif,/*sizeof(dscgif)*/13,1);\r
- //if (strncmp(dscgif.header,"GIF8",3)!=0) {\r
- if (strncmp(dscgif.header,"GIF8",4)!=0) return FALSE;\r
-\r
- // Avoid Byte order problem with Mac <AMSN>\r
- dscgif.scrheight = ntohs(dscgif.scrheight);\r
- dscgif.scrwidth = ntohs(dscgif.scrwidth);\r
-\r
- if (info.nEscape == -1) {\r
- // Return output dimensions only\r
- head.biWidth = dscgif.scrwidth;\r
- head.biHeight = dscgif.scrheight;\r
- info.dwType = CXIMAGE_FORMAT_GIF;\r
- return true;\r
- }\r
-\r
- /* AD - for interlace */\r
- TabCol.sogct = (short)(1 << ((dscgif.pflds & 0x07)+1));\r
- TabCol.colres = (short)(((dscgif.pflds & 0x70) >> 4) + 1);\r
-\r
- // assume that the image is a truecolor-gif if\r
- // 1) no global color map found\r
- // 2) (image.w, image.h) of the 1st image != (dscgif.scrwidth, dscgif.scrheight)\r
- long bTrueColor=0;\r
- CxImage* imaRGB=NULL;\r
-\r
- // Global colour map?\r
- if (dscgif.pflds & 0x80)\r
- fp->Read(TabCol.paleta,sizeof(struct rgb_color)*TabCol.sogct,1);\r
- else \r
- bTrueColor++; //first chance for a truecolor gif\r
-\r
- long first_transparent_index = 0;\r
-\r
- int iImage = 0;\r
- info.nNumFrames=get_num_frames(fp,&TabCol,&dscgif);\r
-\r
- if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)) return false;\r
-\r
- //it cannot be a true color GIF with only one frame\r
- if (info.nNumFrames == 1)\r
- bTrueColor=0;\r
-\r
- char ch;\r
- bool bPreviousWasNull = true;\r
- int prevdispmeth = 0;\r
- CxImage *previousFrame = NULL;\r
-\r
- for (BOOL bContinue = TRUE; bContinue; )\r
- {\r
- if (fp->Read(&ch, sizeof(ch), 1) != 1) {break;}\r
-\r
- if (info.nEscape > 0) return false; // <vho> - cancel decoding\r
- if (bPreviousWasNull || ch==0)\r
- {\r
- switch (ch)\r
- {\r
- case '!': // extension\r
- {\r
- bContinue = DecodeExtension(fp);\r
- break;\r
- }\r
- case ',': // image\r
- {\r
- assert(sizeof(image) == 9);\r
- fp->Read(&image,sizeof(image),1);\r
- //avoid byte order problems with Solaris <candan> <AMSN>\r
- image.l = ntohs(image.l);\r
- image.t = ntohs(image.t);\r
- image.w = ntohs(image.w);\r
- image.h = ntohs(image.h);\r
-\r
- if (((image.l + image.w) > dscgif.scrwidth)||((image.t + image.h) > dscgif.scrheight))\r
- break;\r
-\r
- // check if it could be a truecolor gif\r
- if ((iImage==0) && (image.w != dscgif.scrwidth) && (image.h != dscgif.scrheight))\r
- bTrueColor++;\r
-\r
- rgb_color locpal[256]; //Local Palette \r
- rgb_color* pcurpal = TabCol.paleta; //Current Palette \r
- short palcount = TabCol.sogct; //Current Palette color count \r
-\r
- // Local colour map?\r
- if (image.pf & 0x80) {\r
- palcount = (short)(1 << ((image.pf & 0x07) +1));\r
- assert(3 == sizeof(struct rgb_color));\r
- fp->Read(locpal,sizeof(struct rgb_color)*palcount,1);\r
- pcurpal = locpal;\r
- }\r
-\r
- int bpp; //<DP> select the correct bit per pixel value\r
- if (palcount <= 2) bpp = 1;\r
- else if (palcount <= 16) bpp = 4;\r
- else bpp = 8;\r
-\r
- CxImageGIF backimage;\r
- backimage.CopyInfo(*this);\r
- if (iImage==0){\r
- //first frame: build image background\r
- backimage.Create(dscgif.scrwidth, dscgif.scrheight, bpp, CXIMAGE_FORMAT_GIF);\r
- first_transparent_index = info.nBkgndIndex;\r
- backimage.Clear((BYTE)gifgce.transpcolindex);\r
- previousFrame = new CxImage(backimage);\r
- previousFrame->SetRetreiveAllFrames(false);\r
- } else {\r
- //generic frame: handle disposal method from previous one\r
- /*Values : 0 - No disposal specified. The decoder is\r
- not required to take any action.\r
- 1 - Do not dispose. The graphic is to be left\r
- in place.\r
- 2 - Restore to background color. The area used by the\r
- graphic must be restored to the background color.\r
- 3 - Restore to previous. The decoder is required to\r
- restore the area overwritten by the graphic with\r
- what was there prior to rendering the graphic.\r
- */\r
- /* backimage.Copy(*this);\r
- if (prevdispmeth==2){\r
- backimage.Clear((BYTE)first_transparent_index);\r
- }*/\r
- if (prevdispmeth==2){\r
- backimage.Copy(*this,false,false,false);\r
- backimage.Clear((BYTE)first_transparent_index);\r
- } else if (prevdispmeth==3) {\r
- backimage.Copy(*this,false,false,false);\r
- backimage.Create(previousFrame->GetWidth(),\r
- previousFrame->GetHeight(),\r
- previousFrame->GetBpp(),CXIMAGE_FORMAT_GIF);\r
- memcpy(backimage.GetDIB(),previousFrame->GetDIB(),\r
- backimage.GetSize());\r
- backimage.AlphaSet(*previousFrame);\r
- } else {\r
- backimage.Copy(*this);\r
- }\r
- }\r
-\r
- //active frame\r
- Create(image.w, image.h, bpp, CXIMAGE_FORMAT_GIF);\r
-\r
- if ((image.pf & 0x80) || (dscgif.pflds & 0x80)) {\r
- unsigned char r[256], g[256], b[256];\r
- int i, has_white = 0;\r
-\r
- for (i=0; i < palcount; i++) {\r
- r[i] = pcurpal[i].r;\r
- g[i] = pcurpal[i].g;\r
- b[i] = pcurpal[i].b;\r
- if (RGB(r[i],g[i],b[i]) == 0xFFFFFF) has_white = 1;\r
- }\r
-\r
- // Force transparency colour white...\r
- //if (0) if (info.nBkgndIndex >= 0)\r
- // r[info.nBkgndIndex] = g[info.nBkgndIndex] = b[info.nBkgndIndex] = 255;\r
- // Fill in with white // AD\r
- if (info.nBkgndIndex >= 0) {\r
- while (i < 256) {\r
- has_white = 1;\r
- r[i] = g[i] = b[i] = 255;\r
- i++;\r
- }\r
- }\r
-\r
- // Force last colour to white... // AD\r
- //if ((info.nBkgndIndex >= 0) && !has_white) {\r
- // r[255] = g[255] = b[255] = 255;\r
- //}\r
-\r
- SetPalette((info.nBkgndIndex >= 0 ? 256 : palcount), r, g, b);\r
- }\r
-\r
- CImageIterator* iter = new CImageIterator(this);\r
- iter->Upset();\r
- int badcode=0;\r
- ibf = GIFBUFTAM+1;\r
-\r
- interlaced = image.pf & 0x40;\r
- iheight = image.h;\r
- istep = 8;\r
- iypos = 0;\r
- ipass = 0;\r
-\r
- long pos_start = fp->Tell();\r
- //if (interlaced) log << "Interlaced" << endl;\r
- decoder(fp, iter, image.w, badcode);\r
- delete iter;\r
-\r
- if (info.nEscape) return false; // <vho> - cancel decoding\r
-\r
- if (bTrueColor<2 ){ //standard GIF: mix frame with background\r
- backimage.GifMix(*this,image);\r
- backimage.SetTransIndex(first_transparent_index);\r
- backimage.SetPalette(GetPalette());\r
- Transfer(backimage,false);\r
- } else { //it's a truecolor gif!\r
- //force full image decoding\r
- info.nFrame=info.nNumFrames-1;\r
- //build the RGB image\r
- if (imaRGB==NULL) imaRGB = new CxImage(dscgif.scrwidth,dscgif.scrheight,24,CXIMAGE_FORMAT_GIF);\r
- //copy the partial image into the full RGB image\r
- for(long y=0;y<image.h;y++){\r
- for (long x=0;x<image.w;x++){\r
- imaRGB->SetPixelColor(x+image.l,dscgif.scrheight-1-image.t-y,GetPixelColor(x,image.h-y-1));\r
- }\r
- }\r
- }\r
-\r
- prevdispmeth = (gifgce.flags >> 2) & 0x7;\r
-\r
- //restore the correct position in the file for the next image\r
- if (badcode){\r
- seek_next_image(fp,pos_start);\r
- } else {\r
- fp->Seek(-(ibfmax - ibf - 1), SEEK_CUR);\r
- }\r
-\r
- if (info.bGetAllFrames && imaRGB == NULL) {\r
- if (iImage == 0) {\r
- DestroyFrames();\r
- ppFrames = new CxImage*[info.nNumFrames];\r
- for(int frameIdx = 0; frameIdx < info.nNumFrames; frameIdx++){\r
- ppFrames[frameIdx] = NULL;\r
- }\r
- }\r
- ppFrames[iImage] = new CxImage(*this);\r
- ppFrames[iImage]->SetRetreiveAllFrames(false);\r
- }\r
- if (prevdispmeth <= 1) {\r
- delete previousFrame;\r
- previousFrame = new CxImage(*this);\r
- previousFrame->SetRetreiveAllFrames(false);\r
- }\r
-\r
- if (info.nFrame==iImage) bContinue=false; else iImage++;\r
-\r
- break;\r
- }\r
- case ';': //terminator\r
- bContinue=false;\r
- break;\r
- default:\r
- bPreviousWasNull = (ch==0);\r
- break;\r
- }\r
- }\r
- }\r
-\r
- if (bTrueColor>=2 && imaRGB){\r
- if (gifgce.flags & 0x1){\r
- imaRGB->SetTransColor(GetPaletteColor((BYTE)info.nBkgndIndex));\r
- imaRGB->SetTransIndex(0);\r
- }\r
- Transfer(*imaRGB);\r
- }\r
- delete imaRGB;\r
-\r
- delete previousFrame;\r
-\r
- return true;\r
-\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-bool CxImageGIF::DecodeExtension(CxFile *fp)\r
-{\r
- bool bContinue;\r
- unsigned char count;\r
- unsigned char fc;\r
-\r
- bContinue = (1 == fp->Read(&fc, sizeof(fc), 1));\r
- if (bContinue) {\r
- /* AD - for transparency */\r
- if (fc == 0xF9) {\r
- bContinue = (1 == fp->Read(&count, sizeof(count), 1));\r
- if (bContinue) {\r
- assert(sizeof(gifgce) == 4);\r
- bContinue = (count == fp->Read(&gifgce, 1, sizeof(gifgce)));\r
- gifgce.delaytime = ntohs(gifgce.delaytime); // Avoid Byte order problem with Mac <AMSN>\r
- if (bContinue) {\r
- info.nBkgndIndex = (gifgce.flags & 0x1) ? gifgce.transpcolindex : -1;\r
- info.dwFrameDelay = gifgce.delaytime;\r
- SetDisposalMethod((gifgce.flags >> 2) & 0x7);\r
- } } }\r
-\r
- if (fc == 0xFE) { //<DP> Comment block\r
- bContinue = (1 == fp->Read(&count, sizeof(count), 1));\r
- if (bContinue) {\r
- bContinue = (1 == fp->Read(m_comment, count, 1));\r
- m_comment[count]='\0';\r
- } }\r
-\r
- if (fc == 0xFF) { //<DP> Application Extension block\r
- bContinue = (1 == fp->Read(&count, sizeof(count), 1));\r
- if (bContinue) {\r
- bContinue = (count==11);\r
- if (bContinue){\r
- char AppID[11];\r
- bContinue = (1 == fp->Read(AppID, count, 1));\r
- if (bContinue) {\r
- bContinue = (1 == fp->Read(&count, sizeof(count), 1));\r
- if (bContinue) {\r
- BYTE* dati = (BYTE*)malloc(count);\r
- bContinue = (dati!=NULL);\r
- if (bContinue){\r
- bContinue = (1 == fp->Read(dati, count, 1));\r
- if (count>2){\r
- m_loops = dati[1]+256*dati[2];\r
- }\r
- }\r
- free(dati);\r
- } } } } }\r
-\r
- while (bContinue && fp->Read(&count, sizeof(count), 1) && count) {\r
- //log << "Skipping " << count << " bytes" << endl;\r
- fp->Seek(count, SEEK_CUR);\r
- }\r
- }\r
- return bContinue;\r
-\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-#endif //CXIMAGE_SUPPORT_DECODE\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-// - This external (machine specific) function is expected to return\r
-// either the next BYTE from the GIF file, or a negative error number.\r
-int CxImageGIF::get_byte(CxFile* file)\r
-{\r
- if (ibf>=GIFBUFTAM){\r
- // FW 06/02/98 >>>\r
- ibfmax = (int)file->Read( buf , 1 , GIFBUFTAM) ;\r
- if( ibfmax < GIFBUFTAM ) buf[ ibfmax ] = 255 ;\r
- // FW 06/02/98 <<<\r
- ibf = 0;\r
- }\r
- if (ibf>=ibfmax) return -1; //<DP> avoid overflows\r
- return buf[ibf++];\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-/* - This function takes a full line of pixels (one BYTE per pixel) and\r
- * displays them (or does whatever your program wants with them...). It\r
- * should return zero, or negative if an error or some other event occurs\r
- * which would require aborting the decode process... Note that the length\r
- * passed will almost always be equal to the line length passed to the\r
- * decoder function, with the sole exception occurring when an ending code\r
- * occurs in an odd place in the GIF file... In any case, linelen will be\r
- * equal to the number of pixels passed...\r
-*/\r
-int CxImageGIF::out_line(CImageIterator* iter, unsigned char *pixels, int linelen)\r
-{\r
- if (iter == NULL || pixels == NULL)\r
- return -1;\r
-\r
- //<DP> for 1 & 4 bpp images, the pixels are compressed\r
- if (head.biBitCount < 8){\r
- for(long x=0;x<head.biWidth;x++){\r
- BYTE pos;\r
- BYTE* iDst= pixels + (x*head.biBitCount >> 3);\r
- if (head.biBitCount==4){\r
- pos = (BYTE)(4*(1-x%2));\r
- *iDst &= ~(0x0F<<pos);\r
- *iDst |= ((pixels[x] & 0x0F)<<pos);\r
- } else if (head.biBitCount==1){\r
- pos = (BYTE)(7-x%8);\r
- *iDst &= ~(0x01<<pos);\r
- *iDst |= ((pixels[x] & 0x01)<<pos);\r
- }\r
- }\r
- }\r
-\r
- /* AD - for interlace */\r
- if (interlaced) {\r
- iter->SetY(iheight-iypos-1);\r
- iter->SetRow(pixels, linelen);\r
-\r
- if ((iypos += istep) >= iheight) {\r
- do {\r
- if (ipass++ > 0) istep /= 2;\r
- iypos = istep / 2;\r
- }\r
- while (iypos > iheight);\r
- }\r
- return 0;\r
- } else {\r
- if (iter->ItOK()) {\r
- iter->SetRow(pixels, linelen);\r
- (void)iter->PrevRow();\r
- return 0;\r
- } else {\r
- // puts("chafeo");\r
- return -1;\r
- }\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-#if CXIMAGE_SUPPORT_ENCODE\r
-////////////////////////////////////////////////////////////////////////////////\r
-// SaveFile - writes GIF87a gif file\r
-// Randy Spann 6/15/97\r
-// R.Spann@ConnRiver.net\r
-bool CxImageGIF::Encode(CxFile * fp)\r
-{\r
- if (EncodeSafeCheck(fp)) return false;\r
-\r
- if(head.biBitCount > 8) {\r
- //strcpy(info.szLastError,"GIF Images must be 8 bit or less");\r
- //return FALSE;\r
- return EncodeRGB(fp);\r
- }\r
-\r
- if ( GetNumFrames()>1 && ppFrames ) {\r
- return Encode(fp, ppFrames, GetNumFrames() );\r
- }\r
-\r
- EncodeHeader(fp);\r
-\r
- EncodeExtension(fp);\r
-\r
- EncodeComment(fp);\r
-\r
- EncodeBody(fp);\r
-\r
- fp->PutC(';'); // Write the GIF file terminator\r
-\r
- return true; // done!\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-bool CxImageGIF::Encode(CxFile * fp, CxImage ** pImages, int pagecount, bool bLocalColorMap, bool bLocalDispMeth)\r
-{\r
- cx_try {\r
- if (fp==NULL) cx_throw("invalid file pointer");\r
- if (pImages==NULL || pagecount<=0 || pImages[0]==NULL) cx_throw("multipage GIF, no images!");\r
-\r
- int i;\r
- for (i=0; i<pagecount; i++){\r
- if (pImages[i]==NULL)\r
- cx_throw("Bad image pointer");\r
- if (!(pImages[i]->IsValid()))\r
- cx_throw("Empty image");\r
- if (pImages[i]->GetNumColors()==0)\r
- cx_throw("CxImageGIF::Encode cannot create animated GIFs with a true color frame. Use DecreaseBpp before");\r
- }\r
-\r
- CxImageGIF ghost;\r
-\r
- //write the first image\r
- ghost.Ghost(pImages[0]);\r
- ghost.EncodeHeader(fp);\r
-\r
- if (m_loops!=1){\r
- ghost.SetLoops(max(0,m_loops-1));\r
- ghost.EncodeLoopExtension(fp);\r
- }\r
-\r
- if (bLocalDispMeth) {\r
- ghost.EncodeExtension(fp);\r
- } else {\r
- BYTE dm = ghost.GetDisposalMethod();\r
- ghost.SetDisposalMethod(GetDisposalMethod());\r
- ghost.EncodeExtension(fp);\r
- ghost.SetDisposalMethod(dm);\r
- }\r
-\r
- EncodeComment(fp);\r
-\r
- ghost.EncodeBody(fp);\r
-\r
- for (i=1; i<pagecount; i++){\r
- ghost.Ghost(pImages[i]);\r
-\r
- if (bLocalDispMeth) {\r
- ghost.EncodeExtension(fp);\r
- } else {\r
- BYTE dm = ghost.GetDisposalMethod();\r
- ghost.SetDisposalMethod(GetDisposalMethod());\r
- ghost.EncodeExtension(fp);\r
- ghost.SetDisposalMethod(dm);\r
- }\r
-\r
- ghost.EncodeBody(fp,bLocalColorMap);\r
- }\r
-\r
- fp->PutC(';'); // Write the GIF file terminator\r
-\r
- } cx_catch {\r
- if (strcmp(message,"")) strncpy(info.szLastError,message,255);\r
- return false;\r
- }\r
- return true;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::EncodeHeader(CxFile *fp)\r
-{\r
- fp->Write("GIF89a",1,6); //GIF Header\r
-\r
- Putword(head.biWidth,fp); //Logical screen descriptor\r
- Putword(head.biHeight,fp);\r
-\r
- BYTE Flags;\r
- if (head.biClrUsed==0){\r
- Flags=0x11;\r
- } else {\r
- Flags = 0x80;\r
- Flags |=(head.biBitCount - 1) << 5;\r
- Flags |=(head.biBitCount - 1);\r
- }\r
-\r
- fp->PutC(Flags); //GIF "packed fields"\r
- fp->PutC(0); //GIF "BackGround"\r
- fp->PutC(0); //GIF "pixel aspect ratio"\r
-\r
- if (head.biClrUsed!=0){\r
- RGBQUAD* pPal = GetPalette();\r
- for(DWORD i=0; i<head.biClrUsed; ++i) \r
- {\r
- fp->PutC(pPal[i].rgbRed);\r
- fp->PutC(pPal[i].rgbGreen);\r
- fp->PutC(pPal[i].rgbBlue);\r
- }\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::EncodeExtension(CxFile *fp)\r
-{\r
- // TRK BEGIN : transparency\r
- fp->PutC('!');\r
- fp->PutC(TRANSPARENCY_CODE);\r
-\r
- gifgce.flags = 0;\r
- gifgce.flags |= ((info.nBkgndIndex != -1) ? 1 : 0);\r
- gifgce.flags |= ((GetDisposalMethod() & 0x7) << 2);\r
- gifgce.delaytime = (WORD)info.dwFrameDelay;\r
- gifgce.transpcolindex = (BYTE)info.nBkgndIndex; \r
-\r
- //Invert byte order in case we use a byte order arch, then set it back <AMSN>\r
- gifgce.delaytime = ntohs(gifgce.delaytime);\r
- fp->PutC(sizeof(gifgce));\r
- fp->Write(&gifgce, sizeof(gifgce), 1);\r
- gifgce.delaytime = ntohs(gifgce.delaytime);\r
-\r
- fp->PutC(0);\r
- // TRK END\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::EncodeLoopExtension(CxFile *fp)\r
-{\r
- fp->PutC('!'); //byte 1 : 33 (hex 0x21) GIF Extension code\r
- fp->PutC(255); //byte 2 : 255 (hex 0xFF) Application Extension Label\r
- fp->PutC(11); //byte 3 : 11 (hex (0x0B) Length of Application Block (eleven bytes of data to follow)\r
- fp->Write("NETSCAPE2.0",11,1);\r
- fp->PutC(3); //byte 15 : 3 (hex 0x03) Length of Data Sub-Block (three bytes of data to follow)\r
- fp->PutC(1); //byte 16 : 1 (hex 0x01)\r
- Putword(m_loops,fp); //bytes 17 to 18 : 0 to 65535, an unsigned integer in lo-hi byte format. \r
- //This indicate the number of iterations the loop should be executed.\r
- fp->PutC(0); //bytes 19 : 0 (hex 0x00) a Data Sub-block Terminator. \r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::EncodeBody(CxFile *fp, bool bLocalColorMap)\r
-{\r
- curx = 0;\r
- cury = head.biHeight - 1; //because we read the image bottom to top\r
- CountDown = (long)head.biWidth * (long)head.biHeight;\r
-\r
- fp->PutC(',');\r
-\r
- Putword(info.xOffset,fp);\r
- Putword(info.yOffset,fp);\r
- Putword(head.biWidth,fp);\r
- Putword(head.biHeight,fp);\r
-\r
- BYTE Flags=0x00; //non-interlaced (0x40 = interlaced) (0x80 = LocalColorMap)\r
- if (bLocalColorMap) { Flags|=0x80; Flags|=head.biBitCount-1; }\r
- fp->PutC(Flags);\r
-\r
- if (bLocalColorMap){\r
- Flags|=0x87;\r
- RGBQUAD* pPal = GetPalette();\r
- for(DWORD i=0; i<head.biClrUsed; ++i) \r
- {\r
- fp->PutC(pPal[i].rgbRed);\r
- fp->PutC(pPal[i].rgbGreen);\r
- fp->PutC(pPal[i].rgbBlue);\r
- }\r
- }\r
-\r
- int InitCodeSize = head.biBitCount <=1 ? 2 : head.biBitCount;\r
- // Write out the initial code size\r
- fp->PutC((BYTE)InitCodeSize);\r
-\r
- // Go and actually compress the data\r
- switch (GetCodecOption(CXIMAGE_FORMAT_GIF))\r
- {\r
- case 1: //uncompressed\r
- compressNONE(InitCodeSize+1, fp);\r
- break;\r
- case 2: //RLE\r
- compressRLE(InitCodeSize+1, fp);\r
- break;\r
- default: //LZW\r
- compressLZW(InitCodeSize+1, fp);\r
- }\r
-\r
- // Write out a Zero-length packet (to end the series)\r
- fp->PutC(0);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::EncodeComment(CxFile *fp)\r
-{\r
- unsigned long n = (unsigned long) strlen(m_comment);\r
- if (n>255) n=255;\r
- if (n) {\r
- fp->PutC('!'); //extension code:\r
- fp->PutC(254); //comment extension\r
- fp->PutC((BYTE)n); //size of comment\r
- fp->Write(m_comment,n,1);\r
- fp->PutC(0); //block terminator\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-bool CxImageGIF::EncodeRGB(CxFile *fp)\r
-{\r
- EncodeHeader(fp);\r
-\r
-// EncodeLoopExtension(fp);\r
-\r
- EncodeComment(fp);\r
-\r
- unsigned long w,h;\r
- w=h=0;\r
- const long cellw = 17;\r
- const long cellh = 15;\r
- CxImageGIF tmp;\r
- for (long y=0;y<head.biHeight;y+=cellh){\r
- for (long x=0;x<head.biWidth;x+=cellw){\r
- if ((head.biWidth -x)<cellw) w=head.biWidth -x; else w=cellw;\r
- if ((head.biHeight-y)<cellh) h=head.biHeight-y; else h=cellh;\r
-\r
- if (w!=tmp.GetWidth() || h!=tmp.GetHeight()) tmp.Create(w,h,8);\r
-\r
- if (IsTransparent()){\r
- tmp.SetTransIndex(0);\r
- tmp.SetPaletteColor(0,GetTransColor());\r
- }\r
-\r
- BYTE i;\r
- for (unsigned long j=0;j<h;j++){\r
- for (unsigned long k=0;k<w;k++){\r
- i=(BYTE)(1+k+cellw*j);\r
- tmp.SetPaletteColor(i,GetPixelColor(x+k,head.biHeight-y-h+j));\r
- tmp.SetPixelIndex(k,j,tmp.GetNearestIndex(tmp.GetPaletteColor(i)));\r
- }\r
- }\r
-\r
- tmp.SetOffset(x,y);\r
- tmp.EncodeExtension(fp);\r
- tmp.EncodeBody(fp,true);\r
- }\r
- }\r
-\r
- fp->PutC(';'); // Write the GIF file terminator\r
-\r
- return true; // done!\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-#endif // CXIMAGE_SUPPORT_ENCODE\r
-////////////////////////////////////////////////////////////////////////////////\r
-// Return the next pixel from the image\r
-// <DP> fix for 1 & 4 bpp images\r
-int CxImageGIF::GifNextPixel( )\r
-{\r
- if( CountDown == 0 ) return EOF;\r
- --CountDown;\r
- int r = GetPixelIndex(curx,cury);\r
- // Bump the current X position\r
- ++curx;\r
- if( curx == head.biWidth ){\r
- curx = 0;\r
- cury--; //bottom to top\r
- }\r
- return r;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::Putword(int w, CxFile *fp )\r
-{\r
- fp->PutC((BYTE)(w & 0xff));\r
- fp->PutC((BYTE)((w >> 8) & 0xff));\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::compressNONE( int init_bits, CxFile* outfile)\r
-{\r
- register long c;\r
- register long ent;\r
-\r
- // g_init_bits - initial number of bits\r
- // g_outfile - pointer to output file\r
- g_init_bits = init_bits;\r
- g_outfile = outfile;\r
-\r
- // Set up the necessary values\r
- cur_accum = cur_bits = clear_flg = 0;\r
- maxcode = (short)MAXCODE(n_bits = g_init_bits);\r
- code_int maxmaxcode = (code_int)1 << MAXBITSCODES;\r
-\r
- ClearCode = (1 << (init_bits - 1));\r
- EOFCode = ClearCode + 1;\r
- free_ent = (short)(ClearCode + 2);\r
-\r
- a_count=0;\r
- ent = GifNextPixel( );\r
-\r
- output( (code_int)ClearCode );\r
-\r
- while ( ent != EOF ) { \r
- c = GifNextPixel();\r
-\r
- output ( (code_int) ent );\r
- ent = c;\r
- if ( free_ent < maxmaxcode ) { \r
- free_ent++;\r
- } else {\r
- free_ent=(short)(ClearCode+2);\r
- clear_flg=1;\r
- output((code_int)ClearCode);\r
- }\r
- }\r
- // Put out the final code.\r
- output( (code_int) EOFCode );\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-/***************************************************************************\r
- *\r
- * GIFCOMPR.C - LZW GIF Image compression routines\r
- *\r
- ***************************************************************************/\r
-\r
-void CxImageGIF::compressLZW( int init_bits, CxFile* outfile)\r
-{\r
- register long fcode;\r
- register long c;\r
- register long ent;\r
- register long hshift;\r
- register long disp;\r
- register long i;\r
-\r
- // g_init_bits - initial number of bits\r
- // g_outfile - pointer to output file\r
- g_init_bits = init_bits;\r
- g_outfile = outfile;\r
-\r
- // Set up the necessary values\r
- cur_accum = cur_bits = clear_flg = 0;\r
- maxcode = (short)MAXCODE(n_bits = g_init_bits);\r
- code_int maxmaxcode = (code_int)1 << MAXBITSCODES;\r
-\r
- ClearCode = (1 << (init_bits - 1));\r
- EOFCode = ClearCode + 1;\r
- free_ent = (short)(ClearCode + 2);\r
-\r
- a_count=0;\r
- ent = GifNextPixel( );\r
-\r
- hshift = 0;\r
- for ( fcode = (long) HSIZE; fcode < 65536L; fcode *= 2L ) ++hshift;\r
- hshift = 8 - hshift; /* set hash code range bound */\r
- cl_hash((long)HSIZE); /* clear hash table */\r
- output( (code_int)ClearCode );\r
-\r
- while ( (c = GifNextPixel( )) != EOF ) { \r
-\r
- fcode = (long) (((long) c << MAXBITSCODES) + ent);\r
- i = (((code_int)c << hshift) ^ ent); /* xor hashing */\r
-\r
- if ( HashTabOf (i) == fcode ) {\r
- ent = CodeTabOf (i);\r
- continue;\r
- } else if ( (long)HashTabOf (i) < 0 ) /* empty slot */\r
- goto nomatch;\r
- disp = HSIZE - i; /* secondary hash (after G. Knott) */\r
- if ( i == 0 ) disp = 1;\r
-probe:\r
- if ( (i -= disp) < 0 ) i += HSIZE;\r
- if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; }\r
- if ( (long)HashTabOf (i) > 0 ) goto probe;\r
-nomatch:\r
- output ( (code_int) ent );\r
- ent = c;\r
- if ( free_ent < maxmaxcode ) { \r
- CodeTabOf (i) = free_ent++; /* code -> hashtable */\r
- HashTabOf (i) = fcode;\r
- } else {\r
- cl_hash((long)HSIZE);\r
- free_ent=(short)(ClearCode+2);\r
- clear_flg=1;\r
- output((code_int)ClearCode);\r
- }\r
- }\r
- // Put out the final code.\r
- output( (code_int)ent );\r
- output( (code_int) EOFCode );\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-static const unsigned long code_mask[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,\r
- 0x001F, 0x003F, 0x007F, 0x00FF,\r
- 0x01FF, 0x03FF, 0x07FF, 0x0FFF,\r
- 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };\r
-\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::output( code_int code)\r
-{\r
- cur_accum &= code_mask[ cur_bits ];\r
-\r
- if( cur_bits > 0 )\r
- cur_accum |= ((long)code << cur_bits);\r
- else\r
- cur_accum = code;\r
-\r
- cur_bits += n_bits;\r
-\r
- while( cur_bits >= 8 ) {\r
- char_out( (unsigned int)(cur_accum & 0xff) );\r
- cur_accum >>= 8;\r
- cur_bits -= 8;\r
- }\r
-\r
- /*\r
- * If the next entry is going to be too big for the code size,\r
- * then increase it, if possible.\r
- */\r
-\r
- if ( free_ent > maxcode || clear_flg ) {\r
- if( clear_flg ) {\r
- maxcode = (short)MAXCODE(n_bits = g_init_bits);\r
- clear_flg = 0;\r
- } else {\r
- ++n_bits;\r
- if ( n_bits == MAXBITSCODES )\r
- maxcode = (code_int)1 << MAXBITSCODES; /* should NEVER generate this code */\r
- else\r
- maxcode = (short)MAXCODE(n_bits);\r
- }\r
- }\r
- \r
- if( code == EOFCode ) {\r
- // At EOF, write the rest of the buffer.\r
- while( cur_bits > 0 ) {\r
- char_out( (unsigned int)(cur_accum & 0xff) );\r
- cur_accum >>= 8;\r
- cur_bits -= 8;\r
- }\r
- \r
- flush_char();\r
- g_outfile->Flush();\r
-\r
- if(g_outfile->Error()) strcpy(info.szLastError,"Write Error in GIF file");\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-void CxImageGIF::cl_hash(long hsize)\r
-\r
-{\r
- register long *htab_p = htab+hsize;\r
-\r
- register long i;\r
- register long m1 = -1L;\r
-\r
- i = hsize - 16;\r
-\r
- do {\r
- *(htab_p-16)=m1;\r
- *(htab_p-15)=m1;\r
- *(htab_p-14)=m1;\r
- *(htab_p-13)=m1;\r
- *(htab_p-12)=m1;\r
- *(htab_p-11)=m1;\r
- *(htab_p-10)=m1;\r
- *(htab_p-9)=m1;\r
- *(htab_p-8)=m1;\r
- *(htab_p-7)=m1;\r
- *(htab_p-6)=m1;\r
- *(htab_p-5)=m1;\r
- *(htab_p-4)=m1;\r
- *(htab_p-3)=m1;\r
- *(htab_p-2)=m1;\r
- *(htab_p-1)=m1;\r
- \r
- htab_p-=16;\r
- } while ((i-=16) >=0);\r
-\r
- for (i+=16;i>0;--i)\r
- *--htab_p=m1;\r
-}\r
-\r
-/*******************************************************************************\r
-* GIF specific\r
-*******************************************************************************/\r
-\r
-void CxImageGIF::char_out(int c)\r
-{\r
- accum[a_count++]=(char)c;\r
- if (a_count >=254)\r
- flush_char();\r
-}\r
-\r
-void CxImageGIF::flush_char()\r
-{\r
- if (a_count > 0) {\r
- g_outfile->PutC((BYTE)a_count);\r
- g_outfile->Write(accum,1,a_count);\r
- a_count=0;\r
- }\r
-}\r
-\r
-/*******************************************************************************\r
-* GIF decoder\r
-*******************************************************************************/\r
-/* DECODE.C - An LZW decoder for GIF\r
- * Copyright (C) 1987, by Steven A. Bennett\r
- * Copyright (C) 1994, C++ version by Alejandro Aguilar Sierra\r
-*\r
- * Permission is given by the author to freely redistribute and include\r
- * this code in any program as long as this credit is given where due.\r
- *\r
- * In accordance with the above, I want to credit Steve Wilhite who wrote\r
- * the code which this is heavily inspired by...\r
- *\r
- * GIF and 'Graphics Interchange Format' are trademarks (tm) of\r
- * Compuserve, Incorporated, an H&R Block Company.\r
- *\r
- * Release Notes: This file contains a decoder routine for GIF images\r
- * which is similar, structurally, to the original routine by Steve Wilhite.\r
- * It is, however, somewhat noticably faster in most cases.\r
- *\r
- */\r
-\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-short CxImageGIF::init_exp(short size)\r
-{\r
- curr_size = (short)(size + 1);\r
- top_slot = (short)(1 << curr_size);\r
- clear = (short)(1 << size);\r
- ending = (short)(clear + 1);\r
- slot = newcodes = (short)(ending + 1);\r
- navail_bytes = nbits_left = 0;\r
-\r
- memset(stack,0,MAX_CODES + 1);\r
- memset(prefix,0,MAX_CODES + 1);\r
- memset(suffix,0,MAX_CODES + 1);\r
- return(0);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-/* get_next_code()\r
- * - gets the next code from the GIF file. Returns the code, or else\r
- * a negative number in case of file errors...\r
- */\r
-short CxImageGIF::get_next_code(CxFile* file)\r
-{\r
- short i, x;\r
- DWORD ret;\r
-\r
- if (nbits_left == 0) {\r
- if (navail_bytes <= 0) {\r
- /* Out of bytes in current block, so read next block */\r
- pbytes = byte_buff;\r
- if ((navail_bytes = (short)get_byte(file)) < 0)\r
- return(navail_bytes);\r
- else if (navail_bytes) {\r
- for (i = 0; i < navail_bytes; ++i) {\r
- if ((x = (short)get_byte(file)) < 0) return(x);\r
- byte_buff[i] = (BYTE)x;\r
- }\r
- }\r
- }\r
- b1 = *pbytes++;\r
- nbits_left = 8;\r
- --navail_bytes;\r
- }\r
-\r
- if (navail_bytes<0) return ending; // prevent deadlocks (thanks to Mike Melnikov)\r
-\r
- ret = b1 >> (8 - nbits_left);\r
- while (curr_size > nbits_left){\r
- if (navail_bytes <= 0){\r
- /* Out of bytes in current block, so read next block*/\r
- pbytes = byte_buff;\r
- if ((navail_bytes = (short)get_byte(file)) < 0)\r
- return(navail_bytes);\r
- else if (navail_bytes){\r
- for (i = 0; i < navail_bytes; ++i){\r
- if ((x = (short)get_byte(file)) < 0) return(x);\r
- byte_buff[i] = (BYTE)x;\r
- }\r
- }\r
- }\r
- b1 = *pbytes++;\r
- ret |= b1 << nbits_left;\r
- nbits_left += 8;\r
- --navail_bytes;\r
- }\r
- nbits_left = (short)(nbits_left-curr_size);\r
- ret &= code_mask[curr_size];\r
- return((short)(ret));\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-\r
-/* short decoder(linewidth)\r
- * short linewidth; * Pixels per line of image *\r
- *\r
- * - This function decodes an LZW image, according to the method used\r
- * in the GIF spec. Every *linewidth* "characters" (ie. pixels) decoded\r
- * will generate a call to out_line(), which is a user specific function\r
- * to display a line of pixels. The function gets it's codes from\r
- * get_next_code() which is responsible for reading blocks of data and\r
- * seperating them into the proper size codes. Finally, get_byte() is\r
- * the global routine to read the next BYTE from the GIF file.\r
- *\r
- * It is generally a good idea to have linewidth correspond to the actual\r
- * width of a line (as specified in the Image header) to make your own\r
- * code a bit simpler, but it isn't absolutely necessary.\r
- *\r
- * Returns: 0 if successful, else negative. (See ERRS.H)\r
- *\r
- */\r
-/* bad_code_count is incremented each time an out of range code is read.\r
- * When this value is non-zero after a decode, your GIF file is probably\r
- * corrupt in some way...\r
- */\r
-short CxImageGIF::decoder(CxFile* file, CImageIterator* iter, short linewidth, int &bad_code_count)\r
-{\r
- register BYTE *sp, *bufptr;\r
- BYTE *buf;\r
- register short code, fc, oc, bufcnt;\r
- short c, size, ret;\r
-\r
- /* Initialize for decoding a new image... */\r
- bad_code_count = 0;\r
- if ((size = (short)get_byte(file)) < 0) return(size);\r
- if (size < 2 || 9 < size) return(BAD_CODE_SIZE);\r
- // out_line = outline;\r
- init_exp(size);\r
- //printf("L %d %x\n",linewidth,size);\r
-\r
- /* Initialize in case they forgot to put in a clear code.\r
- * (This shouldn't happen, but we'll try and decode it anyway...)\r
- */\r
- oc = fc = 0;\r
-\r
- /* Allocate space for the decode buffer */\r
- if ((buf = new BYTE[linewidth + 1]) == NULL) return(OUT_OF_MEMORY);\r
-\r
- /* Set up the stack pointer and decode buffer pointer */\r
- sp = stack;\r
- bufptr = buf;\r
- bufcnt = linewidth;\r
-\r
- /* This is the main loop. For each code we get we pass through the\r
- * linked list of prefix codes, pushing the corresponding "character" for\r
- * each code onto the stack. When the list reaches a single "character"\r
- * we push that on the stack too, and then start unstacking each\r
- * character for output in the correct order. Special handling is\r
- * included for the clear code, and the whole thing ends when we get\r
- * an ending code.\r
- */\r
- while ((c = get_next_code(file)) != ending) {\r
- /* If we had a file error, return without completing the decode*/\r
- if (c < 0){\r
- delete [] buf;\r
- return(0);\r
- }\r
- /* If the code is a clear code, reinitialize all necessary items.*/\r
- if (c == clear){\r
- curr_size = (short)(size + 1);\r
- slot = newcodes;\r
- top_slot = (short)(1 << curr_size);\r
-\r
- /* Continue reading codes until we get a non-clear code\r
- * (Another unlikely, but possible case...)\r
- */\r
- while ((c = get_next_code(file)) == clear);\r
-\r
- /* If we get an ending code immediately after a clear code\r
- * (Yet another unlikely case), then break out of the loop.\r
- */\r
- if (c == ending) break;\r
-\r
- /* Finally, if the code is beyond the range of already set codes,\r
- * (This one had better NOT happen... I have no idea what will\r
- * result from this, but I doubt it will look good...) then set it\r
- * to color zero.\r
- */\r
- if (c >= slot) c = 0;\r
- oc = fc = c;\r
-\r
- /* And let us not forget to put the char into the buffer... And\r
- * if, on the off chance, we were exactly one pixel from the end\r
- * of the line, we have to send the buffer to the out_line()\r
- * routine...\r
- */\r
- *bufptr++ = (BYTE)c;\r
- if (--bufcnt == 0) {\r
- if (iter) {\r
- if ((ret = (short)out_line(iter, buf, linewidth)) < 0) {\r
- delete [] buf;\r
- return(ret);\r
- }\r
- }\r
- bufptr = buf;\r
- bufcnt = linewidth;\r
- }\r
- } else {\r
- /* In this case, it's not a clear code or an ending code, so\r
- * it must be a code code... So we can now decode the code into\r
- * a stack of character codes. (Clear as mud, right?)\r
- */\r
- code = c;\r
-\r
- /* Here we go again with one of those off chances... If, on the\r
- * off chance, the code we got is beyond the range of those already\r
- * set up (Another thing which had better NOT happen...) we trick\r
- * the decoder into thinking it actually got the last code read.\r
- * (Hmmn... I'm not sure why this works... But it does...)\r
- */\r
- if (code >= slot && sp<(stack+MAX_CODES-1)) {\r
- if (code > slot)\r
- ++bad_code_count;\r
- code = oc;\r
- *sp++ = (BYTE)fc;\r
- }\r
-\r
- /* Here we scan back along the linked list of prefixes, pushing\r
- * helpless characters (ie. suffixes) onto the stack as we do so.\r
- */\r
- while (code >= newcodes && sp<(stack+MAX_CODES-1)) {\r
- *sp++ = suffix[code];\r
- code = prefix[code];\r
- }\r
-\r
- /* Push the last character on the stack, and set up the new\r
- * prefix and suffix, and if the required slot number is greater\r
- * than that allowed by the current bit size, increase the bit\r
- * size. (NOTE - If we are all full, we *don't* save the new\r
- * suffix and prefix... I'm not certain if this is correct...\r
- * it might be more proper to overwrite the last code...\r
- */\r
- *sp++ = (BYTE)code;\r
- if (slot < top_slot){\r
- suffix[slot] = (BYTE)(fc = (BYTE)code);\r
- prefix[slot++] = oc;\r
- oc = c;\r
- }\r
- if (slot >= top_slot){\r
- if (curr_size < 12) {\r
- top_slot <<= 1;\r
- ++curr_size;\r
- }\r
- }\r
-\r
- /* Now that we've pushed the decoded string (in reverse order)\r
- * onto the stack, lets pop it off and put it into our decode\r
- * buffer... And when the decode buffer is full, write another\r
- * line...\r
- */\r
- while (sp > stack) {\r
- *bufptr++ = *(--sp);\r
- if (--bufcnt == 0) {\r
- if (iter) {\r
- if ((ret = (short)out_line(iter, buf, linewidth)) < 0) {\r
- delete [] buf;\r
- return(ret);\r
- }\r
- }\r
- bufptr = buf;\r
- bufcnt = linewidth;\r
- }\r
- }\r
- }\r
- }\r
- ret = 0;\r
- if (bufcnt != linewidth && iter)\r
- ret = (short)out_line(iter, buf, (linewidth - bufcnt));\r
- delete [] buf;\r
- return(ret);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-int CxImageGIF::get_num_frames(CxFile *fp,struct_TabCol* TabColSrc,struct_dscgif* dscgif)\r
-{\r
- struct_image image;\r
-\r
- long pos=fp->Tell();\r
- int nframes=0;\r
-\r
- struct_TabCol TempTabCol;\r
- memcpy(&TempTabCol,TabColSrc,sizeof(struct_TabCol));\r
-\r
- char ch;\r
- bool bPreviousWasNull = true;\r
-\r
- for (BOOL bContinue = TRUE; bContinue; )\r
- {\r
- if (fp->Read(&ch, sizeof(ch), 1) != 1) {break;}\r
-\r
- if (bPreviousWasNull || ch==0)\r
- {\r
- switch (ch)\r
- {\r
- case '!': // extension\r
- {\r
- DecodeExtension(fp);\r
- break;\r
- }\r
- case ',': // image\r
- {\r
-\r
- assert(sizeof(image) == 9);\r
- //log << "Image header" << endl;\r
- fp->Read(&image,sizeof(image),1);\r
-\r
- //avoid byte order problems with Solaris <candan> <AMSN>\r
- image.l = ntohs(image.l);\r
- image.t = ntohs(image.t);\r
- image.w = ntohs(image.w);\r
- image.h = ntohs(image.h);\r
-\r
- // in case of images with empty screen descriptor, give a last chance\r
- if (dscgif->scrwidth==0 && dscgif->scrheight==0){\r
- dscgif->scrwidth = image.w;\r
- dscgif->scrheight = image.h;\r
- }\r
-\r
- if (((image.l + image.w) > dscgif->scrwidth)||((image.t + image.h) > dscgif->scrheight))\r
- break;\r
-\r
- nframes++;\r
-\r
- // Local colour map?\r
- if (image.pf & 0x80) {\r
- TempTabCol.sogct = (short)(1 << ((image.pf & 0x07) +1));\r
- assert(3 == sizeof(struct rgb_color));\r
- fp->Read(TempTabCol.paleta,sizeof(struct rgb_color)*TempTabCol.sogct,1);\r
- //log << "Local colour map" << endl;\r
- }\r
-\r
- int badcode=0;\r
- ibf = GIFBUFTAM+1;\r
-\r
- interlaced = image.pf & 0x40;\r
- iheight = image.h;\r
- istep = 8;\r
- iypos = 0;\r
- ipass = 0;\r
-\r
- long pos_start = fp->Tell();\r
-\r
- //if (interlaced) log << "Interlaced" << endl;\r
- decoder(fp, 0, image.w, badcode);\r
-\r
- if (badcode){\r
- seek_next_image(fp,pos_start);\r
- } else {\r
- fp->Seek(-(ibfmax - ibf - 1), SEEK_CUR);\r
- }\r
- \r
- break;\r
- }\r
- case ';': //terminator\r
- bContinue=false;\r
- break;\r
- default:\r
- bPreviousWasNull = (ch==0);\r
- break;\r
- }\r
- }\r
- }\r
-\r
- fp->Seek(pos,SEEK_SET);\r
- return nframes;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-long CxImageGIF::seek_next_image(CxFile* fp, long position)\r
-{\r
- fp->Seek(position, SEEK_SET);\r
- char ch1,ch2;\r
- ch1=ch2=0;\r
- while(fp->Read(&ch2,sizeof(char),1)>0){\r
- if (ch1 == 0 && ch2 == ','){\r
- fp->Seek(-1,SEEK_CUR);\r
- return fp->Tell();\r
- } else {\r
- ch1 = ch2;\r
- }\r
- }\r
- return -1;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::SetLoops(int loops)\r
-{ m_loops=loops; }\r
-////////////////////////////////////////////////////////////////////////////////\r
-long CxImageGIF::GetLoops()\r
-{ return m_loops; }\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::SetComment(const char* sz_comment_in)\r
-{ if (sz_comment_in) strncpy(m_comment,sz_comment_in,255); }\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::GetComment(char* sz_comment_out)\r
-{ if (sz_comment_out) strncpy(sz_comment_out,m_comment,255); }\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::GifMix(CxImage & imgsrc2, struct_image & imgdesc)\r
-{\r
- long ymin = max(0,(long)(GetHeight()-imgdesc.t - imgdesc.h));\r
- long ymax = GetHeight()-imgdesc.t;\r
- long xmin = imgdesc.l;\r
- long xmax = min(GetWidth(), (DWORD)(imgdesc.l + imgdesc.w));\r
-\r
- long ibg2= imgsrc2.GetTransIndex();\r
- BYTE i2;\r
-\r
- for(long y = ymin; y < ymax; y++){\r
- for(long x = xmin; x < xmax; x++){\r
- i2 = imgsrc2.GetPixelIndex(x-xmin,y-ymin);\r
- if(i2!=ibg2) SetPixelIndex(x,y,i2);\r
- }\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-/*-----------------------------------------------------------------------\r
- *\r
- * miGIF Compression - mouse and ivo's GIF-compatible compression\r
- *\r
- * -run length encoding compression routines-\r
- *\r
- * Copyright (C) 1998 Hutchison Avenue Software Corporation\r
- * http://www.hasc.com\r
- * info@hasc.com\r
- *\r
- * Permission to use, copy, modify, and distribute this software and its\r
- * documentation for any purpose and without fee is hereby granted, provided\r
- * that the above copyright notice appear in all copies and that both that\r
- * copyright notice and this permission notice appear in supporting\r
- * documentation. This software is provided "AS IS." The Hutchison Avenue \r
- * Software Corporation disclaims all warranties, either express or implied, \r
- * including but not limited to implied warranties of merchantability and \r
- * fitness for a particular purpose, with respect to this code and accompanying\r
- * documentation. \r
- * \r
- * The miGIF compression routines do not, strictly speaking, generate files \r
- * conforming to the GIF spec, since the image data is not LZW-compressed \r
- * (this is the point: in order to avoid transgression of the Unisys patent \r
- * on the LZW algorithm.) However, miGIF generates data streams that any \r
- * reasonably sane LZW decompresser will decompress to what we want.\r
- *\r
- * miGIF compression uses run length encoding. It compresses horizontal runs \r
- * of pixels of the same color. This type of compression gives good results\r
- * on images with many runs, for example images with lines, text and solid \r
- * shapes on a solid-colored background. It gives little or no compression \r
- * on images with few runs, for example digital or scanned photos.\r
- *\r
- * der Mouse\r
- * mouse@rodents.montreal.qc.ca\r
- * 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B\r
- *\r
- * ivo@hasc.com\r
- *\r
- * The Graphics Interchange Format(c) is the Copyright property of\r
- * CompuServe Incorporated. GIF(sm) is a Service Mark property of\r
- * CompuServe Incorporated.\r
- *\r
- */\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_clear(struct_RLE* rle)\r
-{\r
- rle->out_bits = rle->out_bits_init;\r
- rle->out_bump = rle->out_bump_init;\r
- rle->out_clear = rle->out_clear_init;\r
- rle->out_count = 0;\r
- rle->rl_table_max = 0;\r
- rle->just_cleared = 1;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_flush(struct_RLE* rle)\r
-{\r
- if (rle->rl_count == 1){\r
- rle_output_plain(rle->rl_pixel,rle);\r
- rle->rl_count = 0;\r
- return;\r
- }\r
- if (rle->just_cleared){\r
- rle_flush_fromclear(rle->rl_count,rle);\r
- } else if ((rle->rl_table_max < 2) || (rle->rl_table_pixel != rle->rl_pixel)) {\r
- rle_flush_clearorrep(rle->rl_count,rle);\r
- } else {\r
- rle_flush_withtable(rle->rl_count,rle);\r
- }\r
- rle->rl_count = 0;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_output_plain(int c,struct_RLE* rle)\r
-{\r
- rle->just_cleared = 0;\r
- rle_output(c,rle);\r
- rle->out_count++;\r
- if (rle->out_count >= rle->out_bump){\r
- rle->out_bits ++;\r
- rle->out_bump += 1 << (rle->out_bits - 1);\r
- }\r
- if (rle->out_count >= rle->out_clear){\r
- rle_output(rle->code_clear,rle);\r
- rle_clear(rle);\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_flush_fromclear(int count,struct_RLE* rle)\r
-{\r
- int n;\r
-\r
- rle->out_clear = rle->max_ocodes;\r
- rle->rl_table_pixel = rle->rl_pixel;\r
- n = 1;\r
- while (count > 0){\r
- if (n == 1){\r
- rle->rl_table_max = 1;\r
- rle_output_plain(rle->rl_pixel,rle);\r
- count --;\r
- } else if (count >= n){\r
- rle->rl_table_max = n;\r
- rle_output_plain(rle->rl_basecode+n-2,rle);\r
- count -= n;\r
- } else if (count == 1){\r
- rle->rl_table_max ++;\r
- rle_output_plain(rle->rl_pixel,rle);\r
- count = 0;\r
- } else {\r
- rle->rl_table_max ++;\r
- rle_output_plain(rle->rl_basecode+count-2,rle);\r
- count = 0;\r
- }\r
- if (rle->out_count == 0) n = 1; else n ++;\r
- }\r
- rle_reset_out_clear(rle);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_reset_out_clear(struct_RLE* rle)\r
-{\r
- rle->out_clear = rle->out_clear_init;\r
- if (rle->out_count >= rle->out_clear){\r
- rle_output(rle->code_clear,rle);\r
- rle_clear(rle);\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_flush_withtable(int count, struct_RLE* rle)\r
-{\r
- int repmax;\r
- int repleft;\r
- int leftover;\r
-\r
- repmax = count / rle->rl_table_max;\r
- leftover = count % rle->rl_table_max;\r
- repleft = (leftover ? 1 : 0);\r
- if (rle->out_count+repmax+repleft > rle->max_ocodes){\r
- repmax = rle->max_ocodes - rle->out_count;\r
- leftover = count - (repmax * rle->rl_table_max);\r
- repleft = 1 + rle_compute_triangle_count(leftover,rle->max_ocodes);\r
- }\r
- if (1+rle_compute_triangle_count(count,rle->max_ocodes) < (unsigned int)(repmax+repleft)){\r
- rle_output(rle->code_clear,rle);\r
- rle_clear(rle);\r
- rle_flush_fromclear(count,rle);\r
- return;\r
- }\r
- rle->out_clear = rle->max_ocodes;\r
- for (;repmax>0;repmax--) rle_output_plain(rle->rl_basecode+rle->rl_table_max-2,rle);\r
- if (leftover){\r
- if (rle->just_cleared){\r
- rle_flush_fromclear(leftover,rle);\r
- } else if (leftover == 1){\r
- rle_output_plain(rle->rl_pixel,rle);\r
- } else {\r
- rle_output_plain(rle->rl_basecode+leftover-2,rle);\r
- }\r
- }\r
- rle_reset_out_clear(rle);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-unsigned int CxImageGIF::rle_compute_triangle_count(unsigned int count, unsigned int nrepcodes)\r
-{\r
- unsigned int perrep;\r
- unsigned int cost;\r
-\r
- cost = 0;\r
- perrep = (nrepcodes * (nrepcodes+1)) / 2;\r
- while (count >= perrep){\r
- cost += nrepcodes;\r
- count -= perrep;\r
- }\r
- if (count > 0){\r
- unsigned int n;\r
- n = rle_isqrt(count);\r
- while ((n*(n+1)) >= 2*count) n --;\r
- while ((n*(n+1)) < 2*count) n ++;\r
- cost += n;\r
- }\r
- return(cost);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-unsigned int CxImageGIF::rle_isqrt(unsigned int x)\r
-{\r
- unsigned int r;\r
- unsigned int v;\r
-\r
- if (x < 2) return(x);\r
- for (v=x,r=1;v;v>>=2,r<<=1) ;\r
- for( ;; )\r
- {\r
- v = ((x / r) + r) / 2;\r
- if ((v == r) || (v == r+1)) return(r);\r
- r = v;\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_flush_clearorrep(int count, struct_RLE* rle)\r
-{\r
- int withclr;\r
- withclr = 1 + rle_compute_triangle_count(count,rle->max_ocodes);\r
- if (withclr < count) {\r
- rle_output(rle->code_clear,rle);\r
- rle_clear(rle);\r
- rle_flush_fromclear(count,rle);\r
- } else {\r
- for (;count>0;count--) rle_output_plain(rle->rl_pixel,rle);\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_write_block(struct_RLE* rle)\r
-{\r
- g_outfile->PutC((BYTE)rle->oblen);\r
- g_outfile->Write(rle->oblock,1,rle->oblen);\r
- rle->oblen = 0;\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_block_out(unsigned char c, struct_RLE* rle)\r
-{\r
- rle->oblock[rle->oblen++] = c;\r
- if (rle->oblen >= 255) rle_write_block(rle);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_block_flush(struct_RLE* rle)\r
-{\r
- if (rle->oblen > 0) rle_write_block(rle);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_output(int val, struct_RLE* rle)\r
-{\r
- rle->obuf |= val << rle->obits;\r
- rle->obits += rle->out_bits;\r
- while (rle->obits >= 8){\r
- rle_block_out((unsigned char)(rle->obuf&0xff),rle);\r
- rle->obuf >>= 8;\r
- rle->obits -= 8;\r
- }\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::rle_output_flush(struct_RLE* rle)\r
-{\r
- if (rle->obits > 0) rle_block_out((unsigned char)(rle->obuf),rle);\r
- rle_block_flush(rle);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-void CxImageGIF::compressRLE( int init_bits, CxFile* outfile)\r
-{\r
- g_init_bits = init_bits;\r
- g_outfile = outfile;\r
-\r
- struct_RLE rle;\r
- rle.code_clear = 1 << (init_bits - 1);\r
- rle.code_eof = rle.code_clear + 1;\r
- rle.rl_basecode = rle.code_eof + 1;\r
- rle.out_bump_init = (1 << (init_bits - 1)) - 1;\r
- rle.out_clear_init = (init_bits <= 3) ? 9 : (rle.out_bump_init-1);\r
- rle.out_bits_init = init_bits;\r
- rle.max_ocodes = (1 << MAXBITSCODES) - ((1 << (rle.out_bits_init - 1)) + 3);\r
- rle.rl_count = 0;\r
- rle_clear(&rle);\r
- rle.obuf = 0;\r
- rle.obits = 0;\r
- rle.oblen = 0;\r
-\r
- rle_output(rle.code_clear,&rle);\r
-\r
- int c;\r
- for( ;; )\r
- {\r
- c = GifNextPixel();\r
- if ((rle.rl_count > 0) && (c != rle.rl_pixel)) rle_flush(&rle);\r
- if (c == EOF) break;\r
- if (rle.rl_pixel == c){\r
- rle.rl_count++;\r
- } else {\r
- rle.rl_pixel = c;\r
- rle.rl_count = 1;\r
- }\r
- }\r
- rle_output(rle.code_eof,&rle);\r
- rle_output_flush(&rle);\r
-}\r
-////////////////////////////////////////////////////////////////////////////////\r
-#endif // CXIMAGE_SUPPORT_GIF\r
+/*
+ * File: ximagif.cpp
+ * Purpose: Platform Independent GIF Image Class Loader and Writer
+ * 07/Aug/2001 Davide Pizzolato - www.xdp.it
+ * CxImage version 6.0.0 02/Feb/2008
+ */
+
+#include "ximagif.h"
+
+#if CXIMAGE_SUPPORT_GIF
+
+#include "ximaiter.h"
+
+#if defined (_WIN32_WCE)
+ #define assert(s)
+#else
+ #include <assert.h>
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+#if CXIMAGE_SUPPORT_DECODE
+////////////////////////////////////////////////////////////////////////////////
+bool CxImageGIF::Decode(CxFile *fp)
+{
+ /* AD - for transparency */
+ struct_dscgif dscgif;
+ struct_image image;
+ struct_TabCol TabCol;
+
+ if (fp == NULL) return false;
+
+ fp->Read(&dscgif,/*sizeof(dscgif)*/13,1);
+ //if (strncmp(dscgif.header,"GIF8",3)!=0) {
+ if (strncmp(dscgif.header,"GIF8",4)!=0) return FALSE;
+
+ // Avoid Byte order problem with Mac <AMSN>
+ dscgif.scrheight = ntohs(dscgif.scrheight);
+ dscgif.scrwidth = ntohs(dscgif.scrwidth);
+
+ if (info.nEscape == -1) {
+ // Return output dimensions only
+ head.biWidth = dscgif.scrwidth;
+ head.biHeight = dscgif.scrheight;
+ info.dwType = CXIMAGE_FORMAT_GIF;
+ return true;
+ }
+
+ /* AD - for interlace */
+ TabCol.sogct = (short)(1 << ((dscgif.pflds & 0x07)+1));
+ TabCol.colres = (short)(((dscgif.pflds & 0x70) >> 4) + 1);
+
+ // assume that the image is a truecolor-gif if
+ // 1) no global color map found
+ // 2) (image.w, image.h) of the 1st image != (dscgif.scrwidth, dscgif.scrheight)
+ long bTrueColor=0;
+ CxImage* imaRGB=NULL;
+
+ // Global colour map?
+ if (dscgif.pflds & 0x80)
+ fp->Read(TabCol.paleta,sizeof(struct rgb_color)*TabCol.sogct,1);
+ else
+ bTrueColor++; //first chance for a truecolor gif
+
+ long first_transparent_index = 0;
+
+ int iImage = 0;
+ info.nNumFrames=get_num_frames(fp,&TabCol,&dscgif);
+
+ if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)) return false;
+
+ //it cannot be a true color GIF with only one frame
+ if (info.nNumFrames == 1)
+ bTrueColor=0;
+
+ char ch;
+ bool bPreviousWasNull = true;
+ int prevdispmeth = 0;
+ CxImage *previousFrame = NULL;
+
+ for (BOOL bContinue = TRUE; bContinue; )
+ {
+ if (fp->Read(&ch, sizeof(ch), 1) != 1) {break;}
+
+ if (info.nEscape > 0) return false; // <vho> - cancel decoding
+ if (bPreviousWasNull || ch==0)
+ {
+ switch (ch)
+ {
+ case '!': // extension
+ {
+ bContinue = DecodeExtension(fp);
+ break;
+ }
+ case ',': // image
+ {
+ assert(sizeof(image) == 9);
+ fp->Read(&image,sizeof(image),1);
+ //avoid byte order problems with Solaris <candan> <AMSN>
+ image.l = ntohs(image.l);
+ image.t = ntohs(image.t);
+ image.w = ntohs(image.w);
+ image.h = ntohs(image.h);
+
+ if (((image.l + image.w) > dscgif.scrwidth)||((image.t + image.h) > dscgif.scrheight))
+ break;
+
+ // check if it could be a truecolor gif
+ if ((iImage==0) && (image.w != dscgif.scrwidth) && (image.h != dscgif.scrheight))
+ bTrueColor++;
+
+ rgb_color locpal[256]; //Local Palette
+ rgb_color* pcurpal = TabCol.paleta; //Current Palette
+ short palcount = TabCol.sogct; //Current Palette color count
+
+ // Local colour map?
+ if (image.pf & 0x80) {
+ palcount = (short)(1 << ((image.pf & 0x07) +1));
+ assert(3 == sizeof(struct rgb_color));
+ fp->Read(locpal,sizeof(struct rgb_color)*palcount,1);
+ pcurpal = locpal;
+ }
+
+ int bpp; //<DP> select the correct bit per pixel value
+ if (palcount <= 2) bpp = 1;
+ else if (palcount <= 16) bpp = 4;
+ else bpp = 8;
+
+ CxImageGIF backimage;
+ backimage.CopyInfo(*this);
+ if (iImage==0){
+ //first frame: build image background
+ backimage.Create(dscgif.scrwidth, dscgif.scrheight, bpp, CXIMAGE_FORMAT_GIF);
+ first_transparent_index = info.nBkgndIndex;
+ backimage.Clear((BYTE)gifgce.transpcolindex);
+ previousFrame = new CxImage(backimage);
+ previousFrame->SetRetreiveAllFrames(false);
+ } else {
+ //generic frame: handle disposal method from previous one
+ /*Values : 0 - No disposal specified. The decoder is
+ not required to take any action.
+ 1 - Do not dispose. The graphic is to be left
+ in place.
+ 2 - Restore to background color. The area used by the
+ graphic must be restored to the background color.
+ 3 - Restore to previous. The decoder is required to
+ restore the area overwritten by the graphic with
+ what was there prior to rendering the graphic.
+ */
+ /* backimage.Copy(*this);
+ if (prevdispmeth==2){
+ backimage.Clear((BYTE)first_transparent_index);
+ }*/
+ if (prevdispmeth==2){
+ backimage.Copy(*this,false,false,false);
+ backimage.Clear((BYTE)first_transparent_index);
+ } else if (prevdispmeth==3) {
+ backimage.Copy(*this,false,false,false);
+ backimage.Create(previousFrame->GetWidth(),
+ previousFrame->GetHeight(),
+ previousFrame->GetBpp(),CXIMAGE_FORMAT_GIF);
+ memcpy(backimage.GetDIB(),previousFrame->GetDIB(),
+ backimage.GetSize());
+ backimage.AlphaSet(*previousFrame);
+ } else {
+ backimage.Copy(*this);
+ }
+ }
+
+ //active frame
+ Create(image.w, image.h, bpp, CXIMAGE_FORMAT_GIF);
+
+ if ((image.pf & 0x80) || (dscgif.pflds & 0x80)) {
+ unsigned char r[256], g[256], b[256];
+ int i, has_white = 0;
+
+ for (i=0; i < palcount; i++) {
+ r[i] = pcurpal[i].r;
+ g[i] = pcurpal[i].g;
+ b[i] = pcurpal[i].b;
+ if (RGB(r[i],g[i],b[i]) == 0xFFFFFF) has_white = 1;
+ }
+
+ // Force transparency colour white...
+ //if (0) if (info.nBkgndIndex >= 0)
+ // r[info.nBkgndIndex] = g[info.nBkgndIndex] = b[info.nBkgndIndex] = 255;
+ // Fill in with white // AD
+ if (info.nBkgndIndex >= 0) {
+ while (i < 256) {
+ has_white = 1;
+ r[i] = g[i] = b[i] = 255;
+ i++;
+ }
+ }
+
+ // Force last colour to white... // AD
+ //if ((info.nBkgndIndex >= 0) && !has_white) {
+ // r[255] = g[255] = b[255] = 255;
+ //}
+
+ SetPalette((info.nBkgndIndex >= 0 ? 256 : palcount), r, g, b);
+ }
+
+ CImageIterator* iter = new CImageIterator(this);
+ iter->Upset();
+ int badcode=0;
+ ibf = GIFBUFTAM+1;
+
+ interlaced = image.pf & 0x40;
+ iheight = image.h;
+ istep = 8;
+ iypos = 0;
+ ipass = 0;
+
+ long pos_start = fp->Tell();
+ //if (interlaced) log << "Interlaced" << endl;
+ decoder(fp, iter, image.w, badcode);
+ delete iter;
+
+ if (info.nEscape) return false; // <vho> - cancel decoding
+
+ if (bTrueColor<2 ){ //standard GIF: mix frame with background
+ backimage.GifMix(*this,image);
+ backimage.SetTransIndex(first_transparent_index);
+ backimage.SetPalette(GetPalette());
+ Transfer(backimage,false);
+ } else { //it's a truecolor gif!
+ //force full image decoding
+ info.nFrame=info.nNumFrames-1;
+ //build the RGB image
+ if (imaRGB==NULL) imaRGB = new CxImage(dscgif.scrwidth,dscgif.scrheight,24,CXIMAGE_FORMAT_GIF);
+ //copy the partial image into the full RGB image
+ for(long y=0;y<image.h;y++){
+ for (long x=0;x<image.w;x++){
+ imaRGB->SetPixelColor(x+image.l,dscgif.scrheight-1-image.t-y,GetPixelColor(x,image.h-y-1));
+ }
+ }
+ }
+
+ prevdispmeth = (gifgce.flags >> 2) & 0x7;
+
+ //restore the correct position in the file for the next image
+ if (badcode){
+ seek_next_image(fp,pos_start);
+ } else {
+ fp->Seek(-(ibfmax - ibf - 1), SEEK_CUR);
+ }
+
+ if (info.bGetAllFrames && imaRGB == NULL) {
+ if (iImage == 0) {
+ DestroyFrames();
+ ppFrames = new CxImage*[info.nNumFrames];
+ for(int frameIdx = 0; frameIdx < info.nNumFrames; frameIdx++){
+ ppFrames[frameIdx] = NULL;
+ }
+ }
+ ppFrames[iImage] = new CxImage(*this);
+ ppFrames[iImage]->SetRetreiveAllFrames(false);
+ }
+ if (prevdispmeth <= 1) {
+ delete previousFrame;
+ previousFrame = new CxImage(*this);
+ previousFrame->SetRetreiveAllFrames(false);
+ }
+
+ if (info.nFrame==iImage) bContinue=false; else iImage++;
+
+ break;
+ }
+ case ';': //terminator
+ bContinue=false;
+ break;
+ default:
+ bPreviousWasNull = (ch==0);
+ break;
+ }
+ }
+ }
+
+ if (bTrueColor>=2 && imaRGB){
+ if (gifgce.flags & 0x1){
+ imaRGB->SetTransColor(GetPaletteColor((BYTE)info.nBkgndIndex));
+ imaRGB->SetTransIndex(0);
+ }
+ Transfer(*imaRGB);
+ }
+ delete imaRGB;
+
+ delete previousFrame;
+
+ return true;
+
+}
+////////////////////////////////////////////////////////////////////////////////
+bool CxImageGIF::DecodeExtension(CxFile *fp)
+{
+ bool bContinue;
+ unsigned char count;
+ unsigned char fc;
+
+ bContinue = (1 == fp->Read(&fc, sizeof(fc), 1));
+ if (bContinue) {
+ /* AD - for transparency */
+ if (fc == 0xF9) {
+ bContinue = (1 == fp->Read(&count, sizeof(count), 1));
+ if (bContinue) {
+ assert(sizeof(gifgce) == 4);
+ bContinue = (count == fp->Read(&gifgce, 1, sizeof(gifgce)));
+ gifgce.delaytime = ntohs(gifgce.delaytime); // Avoid Byte order problem with Mac <AMSN>
+ if (bContinue) {
+ info.nBkgndIndex = (gifgce.flags & 0x1) ? gifgce.transpcolindex : -1;
+ info.dwFrameDelay = gifgce.delaytime;
+ SetDisposalMethod((gifgce.flags >> 2) & 0x7);
+ } } }
+
+ if (fc == 0xFE) { //<DP> Comment block
+ bContinue = (1 == fp->Read(&count, sizeof(count), 1));
+ if (bContinue) {
+ bContinue = (1 == fp->Read(m_comment, count, 1));
+ m_comment[count]='\0';
+ } }
+
+ if (fc == 0xFF) { //<DP> Application Extension block
+ bContinue = (1 == fp->Read(&count, sizeof(count), 1));
+ if (bContinue) {
+ bContinue = (count==11);
+ if (bContinue){
+ char AppID[11];
+ bContinue = (1 == fp->Read(AppID, count, 1));
+ if (bContinue) {
+ bContinue = (1 == fp->Read(&count, sizeof(count), 1));
+ if (bContinue) {
+ BYTE* dati = (BYTE*)malloc(count);
+ bContinue = (dati!=NULL);
+ if (bContinue){
+ bContinue = (1 == fp->Read(dati, count, 1));
+ if (count>2){
+ m_loops = dati[1]+256*dati[2];
+ }
+ }
+ free(dati);
+ } } } } }
+
+ while (bContinue && fp->Read(&count, sizeof(count), 1) && count) {
+ //log << "Skipping " << count << " bytes" << endl;
+ fp->Seek(count, SEEK_CUR);
+ }
+ }
+ return bContinue;
+
+}
+////////////////////////////////////////////////////////////////////////////////
+#endif //CXIMAGE_SUPPORT_DECODE
+////////////////////////////////////////////////////////////////////////////////
+
+// - This external (machine specific) function is expected to return
+// either the next BYTE from the GIF file, or a negative error number.
+int CxImageGIF::get_byte(CxFile* file)
+{
+ if (ibf>=GIFBUFTAM){
+ // FW 06/02/98 >>>
+ ibfmax = (int)file->Read( buf , 1 , GIFBUFTAM) ;
+ if( ibfmax < GIFBUFTAM ) buf[ ibfmax ] = 255 ;
+ // FW 06/02/98 <<<
+ ibf = 0;
+ }
+ if (ibf>=ibfmax) return -1; //<DP> avoid overflows
+ return buf[ibf++];
+}
+////////////////////////////////////////////////////////////////////////////////
+/* - This function takes a full line of pixels (one BYTE per pixel) and
+ * displays them (or does whatever your program wants with them...). It
+ * should return zero, or negative if an error or some other event occurs
+ * which would require aborting the decode process... Note that the length
+ * passed will almost always be equal to the line length passed to the
+ * decoder function, with the sole exception occurring when an ending code
+ * occurs in an odd place in the GIF file... In any case, linelen will be
+ * equal to the number of pixels passed...
+*/
+int CxImageGIF::out_line(CImageIterator* iter, unsigned char *pixels, int linelen)
+{
+ if (iter == NULL || pixels == NULL)
+ return -1;
+
+ //<DP> for 1 & 4 bpp images, the pixels are compressed
+ if (head.biBitCount < 8){
+ for(long x=0;x<head.biWidth;x++){
+ BYTE pos;
+ BYTE* iDst= pixels + (x*head.biBitCount >> 3);
+ if (head.biBitCount==4){
+ pos = (BYTE)(4*(1-x%2));
+ *iDst &= ~(0x0F<<pos);
+ *iDst |= ((pixels[x] & 0x0F)<<pos);
+ } else if (head.biBitCount==1){
+ pos = (BYTE)(7-x%8);
+ *iDst &= ~(0x01<<pos);
+ *iDst |= ((pixels[x] & 0x01)<<pos);
+ }
+ }
+ }
+
+ /* AD - for interlace */
+ if (interlaced) {
+ iter->SetY(iheight-iypos-1);
+ iter->SetRow(pixels, linelen);
+
+ if ((iypos += istep) >= iheight) {
+ do {
+ if (ipass++ > 0) istep /= 2;
+ iypos = istep / 2;
+ }
+ while (iypos > iheight);
+ }
+ return 0;
+ } else {
+ if (iter->ItOK()) {
+ iter->SetRow(pixels, linelen);
+ (void)iter->PrevRow();
+ return 0;
+ } else {
+ // puts("chafeo");
+ return -1;
+ }
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+#if CXIMAGE_SUPPORT_ENCODE
+////////////////////////////////////////////////////////////////////////////////
+// SaveFile - writes GIF87a gif file
+// Randy Spann 6/15/97
+// R.Spann@ConnRiver.net
+bool CxImageGIF::Encode(CxFile * fp)
+{
+ if (EncodeSafeCheck(fp)) return false;
+
+ if(head.biBitCount > 8) {
+ //strcpy(info.szLastError,"GIF Images must be 8 bit or less");
+ //return FALSE;
+ return EncodeRGB(fp);
+ }
+
+ if ( GetNumFrames()>1 && ppFrames ) {
+ return Encode(fp, ppFrames, GetNumFrames() );
+ }
+
+ EncodeHeader(fp);
+
+ EncodeExtension(fp);
+
+ EncodeComment(fp);
+
+ EncodeBody(fp);
+
+ fp->PutC(';'); // Write the GIF file terminator
+
+ return true; // done!
+}
+////////////////////////////////////////////////////////////////////////////////
+bool CxImageGIF::Encode(CxFile * fp, CxImage ** pImages, int pagecount, bool bLocalColorMap, bool bLocalDispMeth)
+{
+ cx_try {
+ if (fp==NULL) cx_throw("invalid file pointer");
+ if (pImages==NULL || pagecount<=0 || pImages[0]==NULL) cx_throw("multipage GIF, no images!");
+
+ int i;
+ for (i=0; i<pagecount; i++){
+ if (pImages[i]==NULL)
+ cx_throw("Bad image pointer");
+ if (!(pImages[i]->IsValid()))
+ cx_throw("Empty image");
+ if (pImages[i]->GetNumColors()==0)
+ cx_throw("CxImageGIF::Encode cannot create animated GIFs with a true color frame. Use DecreaseBpp before");
+ }
+
+ CxImageGIF ghost;
+
+ //write the first image
+ ghost.Ghost(pImages[0]);
+ ghost.EncodeHeader(fp);
+
+ if (m_loops!=1){
+ ghost.SetLoops(max(0,m_loops-1));
+ ghost.EncodeLoopExtension(fp);
+ }
+
+ if (bLocalDispMeth) {
+ ghost.EncodeExtension(fp);
+ } else {
+ BYTE dm = ghost.GetDisposalMethod();
+ ghost.SetDisposalMethod(GetDisposalMethod());
+ ghost.EncodeExtension(fp);
+ ghost.SetDisposalMethod(dm);
+ }
+
+ EncodeComment(fp);
+
+ ghost.EncodeBody(fp);
+
+ for (i=1; i<pagecount; i++){
+ ghost.Ghost(pImages[i]);
+
+ if (bLocalDispMeth) {
+ ghost.EncodeExtension(fp);
+ } else {
+ BYTE dm = ghost.GetDisposalMethod();
+ ghost.SetDisposalMethod(GetDisposalMethod());
+ ghost.EncodeExtension(fp);
+ ghost.SetDisposalMethod(dm);
+ }
+
+ ghost.EncodeBody(fp,bLocalColorMap);
+ }
+
+ fp->PutC(';'); // Write the GIF file terminator
+
+ } cx_catch {
+ if (strcmp(message,"")) strncpy(info.szLastError,message,255);
+ return false;
+ }
+ return true;
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::EncodeHeader(CxFile *fp)
+{
+ fp->Write("GIF89a",1,6); //GIF Header
+
+ Putword(head.biWidth,fp); //Logical screen descriptor
+ Putword(head.biHeight,fp);
+
+ BYTE Flags;
+ if (head.biClrUsed==0){
+ Flags=0x11;
+ } else {
+ Flags = 0x80;
+ Flags |=(head.biBitCount - 1) << 5;
+ Flags |=(head.biBitCount - 1);
+ }
+
+ fp->PutC(Flags); //GIF "packed fields"
+ fp->PutC(0); //GIF "BackGround"
+ fp->PutC(0); //GIF "pixel aspect ratio"
+
+ if (head.biClrUsed!=0){
+ RGBQUAD* pPal = GetPalette();
+ for(DWORD i=0; i<head.biClrUsed; ++i)
+ {
+ fp->PutC(pPal[i].rgbRed);
+ fp->PutC(pPal[i].rgbGreen);
+ fp->PutC(pPal[i].rgbBlue);
+ }
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::EncodeExtension(CxFile *fp)
+{
+ // TRK BEGIN : transparency
+ fp->PutC('!');
+ fp->PutC(TRANSPARENCY_CODE);
+
+ gifgce.flags = 0;
+ gifgce.flags |= ((info.nBkgndIndex != -1) ? 1 : 0);
+ gifgce.flags |= ((GetDisposalMethod() & 0x7) << 2);
+ gifgce.delaytime = (WORD)info.dwFrameDelay;
+ gifgce.transpcolindex = (BYTE)info.nBkgndIndex;
+
+ //Invert byte order in case we use a byte order arch, then set it back <AMSN>
+ gifgce.delaytime = ntohs(gifgce.delaytime);
+ fp->PutC(sizeof(gifgce));
+ fp->Write(&gifgce, sizeof(gifgce), 1);
+ gifgce.delaytime = ntohs(gifgce.delaytime);
+
+ fp->PutC(0);
+ // TRK END
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::EncodeLoopExtension(CxFile *fp)
+{
+ fp->PutC('!'); //byte 1 : 33 (hex 0x21) GIF Extension code
+ fp->PutC(255); //byte 2 : 255 (hex 0xFF) Application Extension Label
+ fp->PutC(11); //byte 3 : 11 (hex (0x0B) Length of Application Block (eleven bytes of data to follow)
+ fp->Write("NETSCAPE2.0",11,1);
+ fp->PutC(3); //byte 15 : 3 (hex 0x03) Length of Data Sub-Block (three bytes of data to follow)
+ fp->PutC(1); //byte 16 : 1 (hex 0x01)
+ Putword(m_loops,fp); //bytes 17 to 18 : 0 to 65535, an unsigned integer in lo-hi byte format.
+ //This indicate the number of iterations the loop should be executed.
+ fp->PutC(0); //bytes 19 : 0 (hex 0x00) a Data Sub-block Terminator.
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::EncodeBody(CxFile *fp, bool bLocalColorMap)
+{
+ curx = 0;
+ cury = head.biHeight - 1; //because we read the image bottom to top
+ CountDown = (long)head.biWidth * (long)head.biHeight;
+
+ fp->PutC(',');
+
+ Putword(info.xOffset,fp);
+ Putword(info.yOffset,fp);
+ Putword(head.biWidth,fp);
+ Putword(head.biHeight,fp);
+
+ BYTE Flags=0x00; //non-interlaced (0x40 = interlaced) (0x80 = LocalColorMap)
+ if (bLocalColorMap) { Flags|=0x80; Flags|=head.biBitCount-1; }
+ fp->PutC(Flags);
+
+ if (bLocalColorMap){
+ Flags|=0x87;
+ RGBQUAD* pPal = GetPalette();
+ for(DWORD i=0; i<head.biClrUsed; ++i)
+ {
+ fp->PutC(pPal[i].rgbRed);
+ fp->PutC(pPal[i].rgbGreen);
+ fp->PutC(pPal[i].rgbBlue);
+ }
+ }
+
+ int InitCodeSize = head.biBitCount <=1 ? 2 : head.biBitCount;
+ // Write out the initial code size
+ fp->PutC((BYTE)InitCodeSize);
+
+ // Go and actually compress the data
+ switch (GetCodecOption(CXIMAGE_FORMAT_GIF))
+ {
+ case 1: //uncompressed
+ compressNONE(InitCodeSize+1, fp);
+ break;
+ case 2: //RLE
+ compressRLE(InitCodeSize+1, fp);
+ break;
+ default: //LZW
+ compressLZW(InitCodeSize+1, fp);
+ }
+
+ // Write out a Zero-length packet (to end the series)
+ fp->PutC(0);
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::EncodeComment(CxFile *fp)
+{
+ unsigned long n = (unsigned long) strlen(m_comment);
+ if (n>255) n=255;
+ if (n) {
+ fp->PutC('!'); //extension code:
+ fp->PutC(254); //comment extension
+ fp->PutC((BYTE)n); //size of comment
+ fp->Write(m_comment,n,1);
+ fp->PutC(0); //block terminator
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+bool CxImageGIF::EncodeRGB(CxFile *fp)
+{
+ EncodeHeader(fp);
+
+// EncodeLoopExtension(fp);
+
+ EncodeComment(fp);
+
+ unsigned long w,h;
+ w=h=0;
+ const long cellw = 17;
+ const long cellh = 15;
+ CxImageGIF tmp;
+ for (long y=0;y<head.biHeight;y+=cellh){
+ for (long x=0;x<head.biWidth;x+=cellw){
+ if ((head.biWidth -x)<cellw) w=head.biWidth -x; else w=cellw;
+ if ((head.biHeight-y)<cellh) h=head.biHeight-y; else h=cellh;
+
+ if (w!=tmp.GetWidth() || h!=tmp.GetHeight()) tmp.Create(w,h,8);
+
+ if (IsTransparent()){
+ tmp.SetTransIndex(0);
+ tmp.SetPaletteColor(0,GetTransColor());
+ }
+
+ BYTE i;
+ for (unsigned long j=0;j<h;j++){
+ for (unsigned long k=0;k<w;k++){
+ i=(BYTE)(1+k+cellw*j);
+ tmp.SetPaletteColor(i,GetPixelColor(x+k,head.biHeight-y-h+j));
+ tmp.SetPixelIndex(k,j,tmp.GetNearestIndex(tmp.GetPaletteColor(i)));
+ }
+ }
+
+ tmp.SetOffset(x,y);
+ tmp.EncodeExtension(fp);
+ tmp.EncodeBody(fp,true);
+ }
+ }
+
+ fp->PutC(';'); // Write the GIF file terminator
+
+ return true; // done!
+}
+////////////////////////////////////////////////////////////////////////////////
+#endif // CXIMAGE_SUPPORT_ENCODE
+////////////////////////////////////////////////////////////////////////////////
+// Return the next pixel from the image
+// <DP> fix for 1 & 4 bpp images
+int CxImageGIF::GifNextPixel( )
+{
+ if( CountDown == 0 ) return EOF;
+ --CountDown;
+ int r = GetPixelIndex(curx,cury);
+ // Bump the current X position
+ ++curx;
+ if( curx == head.biWidth ){
+ curx = 0;
+ cury--; //bottom to top
+ }
+ return r;
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::Putword(int w, CxFile *fp )
+{
+ fp->PutC((BYTE)(w & 0xff));
+ fp->PutC((BYTE)((w >> 8) & 0xff));
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::compressNONE( int init_bits, CxFile* outfile)
+{
+ register long c;
+ register long ent;
+
+ // g_init_bits - initial number of bits
+ // g_outfile - pointer to output file
+ g_init_bits = init_bits;
+ g_outfile = outfile;
+
+ // Set up the necessary values
+ cur_accum = cur_bits = clear_flg = 0;
+ maxcode = (short)MAXCODE(n_bits = g_init_bits);
+ code_int maxmaxcode = (code_int)1 << MAXBITSCODES;
+
+ ClearCode = (1 << (init_bits - 1));
+ EOFCode = ClearCode + 1;
+ free_ent = (short)(ClearCode + 2);
+
+ a_count=0;
+ ent = GifNextPixel( );
+
+ output( (code_int)ClearCode );
+
+ while ( ent != EOF ) {
+ c = GifNextPixel();
+
+ output ( (code_int) ent );
+ ent = c;
+ if ( free_ent < maxmaxcode ) {
+ free_ent++;
+ } else {
+ free_ent=(short)(ClearCode+2);
+ clear_flg=1;
+ output((code_int)ClearCode);
+ }
+ }
+ // Put out the final code.
+ output( (code_int) EOFCode );
+}
+////////////////////////////////////////////////////////////////////////////////
+
+/***************************************************************************
+ *
+ * GIFCOMPR.C - LZW GIF Image compression routines
+ *
+ ***************************************************************************/
+
+void CxImageGIF::compressLZW( int init_bits, CxFile* outfile)
+{
+ register long fcode;
+ register long c;
+ register long ent;
+ register long hshift;
+ register long disp;
+ register long i;
+
+ // g_init_bits - initial number of bits
+ // g_outfile - pointer to output file
+ g_init_bits = init_bits;
+ g_outfile = outfile;
+
+ // Set up the necessary values
+ cur_accum = cur_bits = clear_flg = 0;
+ maxcode = (short)MAXCODE(n_bits = g_init_bits);
+ code_int maxmaxcode = (code_int)1 << MAXBITSCODES;
+
+ ClearCode = (1 << (init_bits - 1));
+ EOFCode = ClearCode + 1;
+ free_ent = (short)(ClearCode + 2);
+
+ a_count=0;
+ ent = GifNextPixel( );
+
+ hshift = 0;
+ for ( fcode = (long) HSIZE; fcode < 65536L; fcode *= 2L ) ++hshift;
+ hshift = 8 - hshift; /* set hash code range bound */
+ cl_hash((long)HSIZE); /* clear hash table */
+ output( (code_int)ClearCode );
+
+ while ( (c = GifNextPixel( )) != EOF ) {
+
+ fcode = (long) (((long) c << MAXBITSCODES) + ent);
+ i = (((code_int)c << hshift) ^ ent); /* xor hashing */
+
+ if ( HashTabOf (i) == fcode ) {
+ ent = CodeTabOf (i);
+ continue;
+ } else if ( (long)HashTabOf (i) < 0 ) /* empty slot */
+ goto nomatch;
+ disp = HSIZE - i; /* secondary hash (after G. Knott) */
+ if ( i == 0 ) disp = 1;
+probe:
+ if ( (i -= disp) < 0 ) i += HSIZE;
+ if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; }
+ if ( (long)HashTabOf (i) > 0 ) goto probe;
+nomatch:
+ output ( (code_int) ent );
+ ent = c;
+ if ( free_ent < maxmaxcode ) {
+ CodeTabOf (i) = free_ent++; /* code -> hashtable */
+ HashTabOf (i) = fcode;
+ } else {
+ cl_hash((long)HSIZE);
+ free_ent=(short)(ClearCode+2);
+ clear_flg=1;
+ output((code_int)ClearCode);
+ }
+ }
+ // Put out the final code.
+ output( (code_int)ent );
+ output( (code_int) EOFCode );
+}
+////////////////////////////////////////////////////////////////////////////////
+
+static const unsigned long code_mask[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
+ 0x001F, 0x003F, 0x007F, 0x00FF,
+ 0x01FF, 0x03FF, 0x07FF, 0x0FFF,
+ 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
+
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::output( code_int code)
+{
+ cur_accum &= code_mask[ cur_bits ];
+
+ if( cur_bits > 0 )
+ cur_accum |= ((long)code << cur_bits);
+ else
+ cur_accum = code;
+
+ cur_bits += n_bits;
+
+ while( cur_bits >= 8 ) {
+ char_out( (unsigned int)(cur_accum & 0xff) );
+ cur_accum >>= 8;
+ cur_bits -= 8;
+ }
+
+ /*
+ * If the next entry is going to be too big for the code size,
+ * then increase it, if possible.
+ */
+
+ if ( free_ent > maxcode || clear_flg ) {
+ if( clear_flg ) {
+ maxcode = (short)MAXCODE(n_bits = g_init_bits);
+ clear_flg = 0;
+ } else {
+ ++n_bits;
+ if ( n_bits == MAXBITSCODES )
+ maxcode = (code_int)1 << MAXBITSCODES; /* should NEVER generate this code */
+ else
+ maxcode = (short)MAXCODE(n_bits);
+ }
+ }
+
+ if( code == EOFCode ) {
+ // At EOF, write the rest of the buffer.
+ while( cur_bits > 0 ) {
+ char_out( (unsigned int)(cur_accum & 0xff) );
+ cur_accum >>= 8;
+ cur_bits -= 8;
+ }
+
+ flush_char();
+ g_outfile->Flush();
+
+ if(g_outfile->Error()) strcpy(info.szLastError,"Write Error in GIF file");
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+
+void CxImageGIF::cl_hash(long hsize)
+
+{
+ register long *htab_p = htab+hsize;
+
+ register long i;
+ register long m1 = -1L;
+
+ i = hsize - 16;
+
+ do {
+ *(htab_p-16)=m1;
+ *(htab_p-15)=m1;
+ *(htab_p-14)=m1;
+ *(htab_p-13)=m1;
+ *(htab_p-12)=m1;
+ *(htab_p-11)=m1;
+ *(htab_p-10)=m1;
+ *(htab_p-9)=m1;
+ *(htab_p-8)=m1;
+ *(htab_p-7)=m1;
+ *(htab_p-6)=m1;
+ *(htab_p-5)=m1;
+ *(htab_p-4)=m1;
+ *(htab_p-3)=m1;
+ *(htab_p-2)=m1;
+ *(htab_p-1)=m1;
+
+ htab_p-=16;
+ } while ((i-=16) >=0);
+
+ for (i+=16;i>0;--i)
+ *--htab_p=m1;
+}
+
+/*******************************************************************************
+* GIF specific
+*******************************************************************************/
+
+void CxImageGIF::char_out(int c)
+{
+ accum[a_count++]=(char)c;
+ if (a_count >=254)
+ flush_char();
+}
+
+void CxImageGIF::flush_char()
+{
+ if (a_count > 0) {
+ g_outfile->PutC((BYTE)a_count);
+ g_outfile->Write(accum,1,a_count);
+ a_count=0;
+ }
+}
+
+/*******************************************************************************
+* GIF decoder
+*******************************************************************************/
+/* DECODE.C - An LZW decoder for GIF
+ * Copyright (C) 1987, by Steven A. Bennett
+ * Copyright (C) 1994, C++ version by Alejandro Aguilar Sierra
+*
+ * Permission is given by the author to freely redistribute and include
+ * this code in any program as long as this credit is given where due.
+ *
+ * In accordance with the above, I want to credit Steve Wilhite who wrote
+ * the code which this is heavily inspired by...
+ *
+ * GIF and 'Graphics Interchange Format' are trademarks (tm) of
+ * Compuserve, Incorporated, an H&R Block Company.
+ *
+ * Release Notes: This file contains a decoder routine for GIF images
+ * which is similar, structurally, to the original routine by Steve Wilhite.
+ * It is, however, somewhat noticably faster in most cases.
+ *
+ */
+
+////////////////////////////////////////////////////////////////////////////////
+
+short CxImageGIF::init_exp(short size)
+{
+ curr_size = (short)(size + 1);
+ top_slot = (short)(1 << curr_size);
+ clear = (short)(1 << size);
+ ending = (short)(clear + 1);
+ slot = newcodes = (short)(ending + 1);
+ navail_bytes = nbits_left = 0;
+
+ memset(stack,0,MAX_CODES + 1);
+ memset(prefix,0,MAX_CODES + 1);
+ memset(suffix,0,MAX_CODES + 1);
+ return(0);
+}
+////////////////////////////////////////////////////////////////////////////////
+
+/* get_next_code()
+ * - gets the next code from the GIF file. Returns the code, or else
+ * a negative number in case of file errors...
+ */
+short CxImageGIF::get_next_code(CxFile* file)
+{
+ short i, x;
+ DWORD ret;
+
+ if (nbits_left == 0) {
+ if (navail_bytes <= 0) {
+ /* Out of bytes in current block, so read next block */
+ pbytes = byte_buff;
+ if ((navail_bytes = (short)get_byte(file)) < 0)
+ return(navail_bytes);
+ else if (navail_bytes) {
+ for (i = 0; i < navail_bytes; ++i) {
+ if ((x = (short)get_byte(file)) < 0) return(x);
+ byte_buff[i] = (BYTE)x;
+ }
+ }
+ }
+ b1 = *pbytes++;
+ nbits_left = 8;
+ --navail_bytes;
+ }
+
+ if (navail_bytes<0) return ending; // prevent deadlocks (thanks to Mike Melnikov)
+
+ ret = b1 >> (8 - nbits_left);
+ while (curr_size > nbits_left){
+ if (navail_bytes <= 0){
+ /* Out of bytes in current block, so read next block*/
+ pbytes = byte_buff;
+ if ((navail_bytes = (short)get_byte(file)) < 0)
+ return(navail_bytes);
+ else if (navail_bytes){
+ for (i = 0; i < navail_bytes; ++i){
+ if ((x = (short)get_byte(file)) < 0) return(x);
+ byte_buff[i] = (BYTE)x;
+ }
+ }
+ }
+ b1 = *pbytes++;
+ ret |= b1 << nbits_left;
+ nbits_left += 8;
+ --navail_bytes;
+ }
+ nbits_left = (short)(nbits_left-curr_size);
+ ret &= code_mask[curr_size];
+ return((short)(ret));
+}
+////////////////////////////////////////////////////////////////////////////////
+
+/* short decoder(linewidth)
+ * short linewidth; * Pixels per line of image *
+ *
+ * - This function decodes an LZW image, according to the method used
+ * in the GIF spec. Every *linewidth* "characters" (ie. pixels) decoded
+ * will generate a call to out_line(), which is a user specific function
+ * to display a line of pixels. The function gets it's codes from
+ * get_next_code() which is responsible for reading blocks of data and
+ * seperating them into the proper size codes. Finally, get_byte() is
+ * the global routine to read the next BYTE from the GIF file.
+ *
+ * It is generally a good idea to have linewidth correspond to the actual
+ * width of a line (as specified in the Image header) to make your own
+ * code a bit simpler, but it isn't absolutely necessary.
+ *
+ * Returns: 0 if successful, else negative. (See ERRS.H)
+ *
+ */
+/* bad_code_count is incremented each time an out of range code is read.
+ * When this value is non-zero after a decode, your GIF file is probably
+ * corrupt in some way...
+ */
+short CxImageGIF::decoder(CxFile* file, CImageIterator* iter, short linewidth, int &bad_code_count)
+{
+ register BYTE *sp, *bufptr;
+ BYTE *buf;
+ register short code, fc, oc, bufcnt;
+ short c, size, ret;
+
+ /* Initialize for decoding a new image... */
+ bad_code_count = 0;
+ if ((size = (short)get_byte(file)) < 0) return(size);
+ if (size < 2 || 9 < size) return(BAD_CODE_SIZE);
+ // out_line = outline;
+ init_exp(size);
+ //printf("L %d %x\n",linewidth,size);
+
+ /* Initialize in case they forgot to put in a clear code.
+ * (This shouldn't happen, but we'll try and decode it anyway...)
+ */
+ oc = fc = 0;
+
+ /* Allocate space for the decode buffer */
+ if ((buf = new BYTE[linewidth + 1]) == NULL) return(OUT_OF_MEMORY);
+
+ /* Set up the stack pointer and decode buffer pointer */
+ sp = stack;
+ bufptr = buf;
+ bufcnt = linewidth;
+
+ /* This is the main loop. For each code we get we pass through the
+ * linked list of prefix codes, pushing the corresponding "character" for
+ * each code onto the stack. When the list reaches a single "character"
+ * we push that on the stack too, and then start unstacking each
+ * character for output in the correct order. Special handling is
+ * included for the clear code, and the whole thing ends when we get
+ * an ending code.
+ */
+ while ((c = get_next_code(file)) != ending) {
+ /* If we had a file error, return without completing the decode*/
+ if (c < 0){
+ delete [] buf;
+ return(0);
+ }
+ /* If the code is a clear code, reinitialize all necessary items.*/
+ if (c == clear){
+ curr_size = (short)(size + 1);
+ slot = newcodes;
+ top_slot = (short)(1 << curr_size);
+
+ /* Continue reading codes until we get a non-clear code
+ * (Another unlikely, but possible case...)
+ */
+ while ((c = get_next_code(file)) == clear);
+
+ /* If we get an ending code immediately after a clear code
+ * (Yet another unlikely case), then break out of the loop.
+ */
+ if (c == ending) break;
+
+ /* Finally, if the code is beyond the range of already set codes,
+ * (This one had better NOT happen... I have no idea what will
+ * result from this, but I doubt it will look good...) then set it
+ * to color zero.
+ */
+ if (c >= slot) c = 0;
+ oc = fc = c;
+
+ /* And let us not forget to put the char into the buffer... And
+ * if, on the off chance, we were exactly one pixel from the end
+ * of the line, we have to send the buffer to the out_line()
+ * routine...
+ */
+ *bufptr++ = (BYTE)c;
+ if (--bufcnt == 0) {
+ if (iter) {
+ if ((ret = (short)out_line(iter, buf, linewidth)) < 0) {
+ delete [] buf;
+ return(ret);
+ }
+ }
+ bufptr = buf;
+ bufcnt = linewidth;
+ }
+ } else {
+ /* In this case, it's not a clear code or an ending code, so
+ * it must be a code code... So we can now decode the code into
+ * a stack of character codes. (Clear as mud, right?)
+ */
+ code = c;
+
+ /* Here we go again with one of those off chances... If, on the
+ * off chance, the code we got is beyond the range of those already
+ * set up (Another thing which had better NOT happen...) we trick
+ * the decoder into thinking it actually got the last code read.
+ * (Hmmn... I'm not sure why this works... But it does...)
+ */
+ if (code >= slot && sp<(stack+MAX_CODES-1)) {
+ if (code > slot)
+ ++bad_code_count;
+ code = oc;
+ *sp++ = (BYTE)fc;
+ }
+
+ /* Here we scan back along the linked list of prefixes, pushing
+ * helpless characters (ie. suffixes) onto the stack as we do so.
+ */
+ while (code >= newcodes && sp<(stack+MAX_CODES-1)) {
+ *sp++ = suffix[code];
+ code = prefix[code];
+ }
+
+ /* Push the last character on the stack, and set up the new
+ * prefix and suffix, and if the required slot number is greater
+ * than that allowed by the current bit size, increase the bit
+ * size. (NOTE - If we are all full, we *don't* save the new
+ * suffix and prefix... I'm not certain if this is correct...
+ * it might be more proper to overwrite the last code...
+ */
+ *sp++ = (BYTE)code;
+ if (slot < top_slot){
+ suffix[slot] = (BYTE)(fc = (BYTE)code);
+ prefix[slot++] = oc;
+ oc = c;
+ }
+ if (slot >= top_slot){
+ if (curr_size < 12) {
+ top_slot <<= 1;
+ ++curr_size;
+ }
+ }
+
+ /* Now that we've pushed the decoded string (in reverse order)
+ * onto the stack, lets pop it off and put it into our decode
+ * buffer... And when the decode buffer is full, write another
+ * line...
+ */
+ while (sp > stack) {
+ *bufptr++ = *(--sp);
+ if (--bufcnt == 0) {
+ if (iter) {
+ if ((ret = (short)out_line(iter, buf, linewidth)) < 0) {
+ delete [] buf;
+ return(ret);
+ }
+ }
+ bufptr = buf;
+ bufcnt = linewidth;
+ }
+ }
+ }
+ }
+ ret = 0;
+ if (bufcnt != linewidth && iter)
+ ret = (short)out_line(iter, buf, (linewidth - bufcnt));
+ delete [] buf;
+ return(ret);
+}
+////////////////////////////////////////////////////////////////////////////////
+int CxImageGIF::get_num_frames(CxFile *fp,struct_TabCol* TabColSrc,struct_dscgif* dscgif)
+{
+ struct_image image;
+
+ long pos=fp->Tell();
+ int nframes=0;
+
+ struct_TabCol TempTabCol;
+ memcpy(&TempTabCol,TabColSrc,sizeof(struct_TabCol));
+
+ char ch;
+ bool bPreviousWasNull = true;
+
+ for (BOOL bContinue = TRUE; bContinue; )
+ {
+ if (fp->Read(&ch, sizeof(ch), 1) != 1) {break;}
+
+ if (bPreviousWasNull || ch==0)
+ {
+ switch (ch)
+ {
+ case '!': // extension
+ {
+ DecodeExtension(fp);
+ break;
+ }
+ case ',': // image
+ {
+
+ assert(sizeof(image) == 9);
+ //log << "Image header" << endl;
+ fp->Read(&image,sizeof(image),1);
+
+ //avoid byte order problems with Solaris <candan> <AMSN>
+ image.l = ntohs(image.l);
+ image.t = ntohs(image.t);
+ image.w = ntohs(image.w);
+ image.h = ntohs(image.h);
+
+ // in case of images with empty screen descriptor, give a last chance
+ if (dscgif->scrwidth==0 && dscgif->scrheight==0){
+ dscgif->scrwidth = image.w;
+ dscgif->scrheight = image.h;
+ }
+
+ if (((image.l + image.w) > dscgif->scrwidth)||((image.t + image.h) > dscgif->scrheight))
+ break;
+
+ nframes++;
+
+ // Local colour map?
+ if (image.pf & 0x80) {
+ TempTabCol.sogct = (short)(1 << ((image.pf & 0x07) +1));
+ assert(3 == sizeof(struct rgb_color));
+ fp->Read(TempTabCol.paleta,sizeof(struct rgb_color)*TempTabCol.sogct,1);
+ //log << "Local colour map" << endl;
+ }
+
+ int badcode=0;
+ ibf = GIFBUFTAM+1;
+
+ interlaced = image.pf & 0x40;
+ iheight = image.h;
+ istep = 8;
+ iypos = 0;
+ ipass = 0;
+
+ long pos_start = fp->Tell();
+
+ //if (interlaced) log << "Interlaced" << endl;
+ decoder(fp, 0, image.w, badcode);
+
+ if (badcode){
+ seek_next_image(fp,pos_start);
+ } else {
+ fp->Seek(-(ibfmax - ibf - 1), SEEK_CUR);
+ }
+
+ break;
+ }
+ case ';': //terminator
+ bContinue=false;
+ break;
+ default:
+ bPreviousWasNull = (ch==0);
+ break;
+ }
+ }
+ }
+
+ fp->Seek(pos,SEEK_SET);
+ return nframes;
+}
+////////////////////////////////////////////////////////////////////////////////
+long CxImageGIF::seek_next_image(CxFile* fp, long position)
+{
+ fp->Seek(position, SEEK_SET);
+ char ch1,ch2;
+ ch1=ch2=0;
+ while(fp->Read(&ch2,sizeof(char),1)>0){
+ if (ch1 == 0 && ch2 == ','){
+ fp->Seek(-1,SEEK_CUR);
+ return fp->Tell();
+ } else {
+ ch1 = ch2;
+ }
+ }
+ return -1;
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::SetLoops(int loops)
+{ m_loops=loops; }
+////////////////////////////////////////////////////////////////////////////////
+long CxImageGIF::GetLoops()
+{ return m_loops; }
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::SetComment(const char* sz_comment_in)
+{ if (sz_comment_in) strncpy(m_comment,sz_comment_in,255); }
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::GetComment(char* sz_comment_out)
+{ if (sz_comment_out) strncpy(sz_comment_out,m_comment,255); }
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::GifMix(CxImage & imgsrc2, struct_image & imgdesc)
+{
+ long ymin = max(0,(long)(GetHeight()-imgdesc.t - imgdesc.h));
+ long ymax = GetHeight()-imgdesc.t;
+ long xmin = imgdesc.l;
+ long xmax = min(GetWidth(), (DWORD)(imgdesc.l + imgdesc.w));
+
+ long ibg2= imgsrc2.GetTransIndex();
+ BYTE i2;
+
+ for(long y = ymin; y < ymax; y++){
+ for(long x = xmin; x < xmax; x++){
+ i2 = imgsrc2.GetPixelIndex(x-xmin,y-ymin);
+ if(i2!=ibg2) SetPixelIndex(x,y,i2);
+ }
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+/*-----------------------------------------------------------------------
+ *
+ * miGIF Compression - mouse and ivo's GIF-compatible compression
+ *
+ * -run length encoding compression routines-
+ *
+ * Copyright (C) 1998 Hutchison Avenue Software Corporation
+ * http://www.hasc.com
+ * info@hasc.com
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose and without fee is hereby granted, provided
+ * that the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation. This software is provided "AS IS." The Hutchison Avenue
+ * Software Corporation disclaims all warranties, either express or implied,
+ * including but not limited to implied warranties of merchantability and
+ * fitness for a particular purpose, with respect to this code and accompanying
+ * documentation.
+ *
+ * The miGIF compression routines do not, strictly speaking, generate files
+ * conforming to the GIF spec, since the image data is not LZW-compressed
+ * (this is the point: in order to avoid transgression of the Unisys patent
+ * on the LZW algorithm.) However, miGIF generates data streams that any
+ * reasonably sane LZW decompresser will decompress to what we want.
+ *
+ * miGIF compression uses run length encoding. It compresses horizontal runs
+ * of pixels of the same color. This type of compression gives good results
+ * on images with many runs, for example images with lines, text and solid
+ * shapes on a solid-colored background. It gives little or no compression
+ * on images with few runs, for example digital or scanned photos.
+ *
+ * der Mouse
+ * mouse@rodents.montreal.qc.ca
+ * 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B
+ *
+ * ivo@hasc.com
+ *
+ * The Graphics Interchange Format(c) is the Copyright property of
+ * CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ * CompuServe Incorporated.
+ *
+ */
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_clear(struct_RLE* rle)
+{
+ rle->out_bits = rle->out_bits_init;
+ rle->out_bump = rle->out_bump_init;
+ rle->out_clear = rle->out_clear_init;
+ rle->out_count = 0;
+ rle->rl_table_max = 0;
+ rle->just_cleared = 1;
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_flush(struct_RLE* rle)
+{
+ if (rle->rl_count == 1){
+ rle_output_plain(rle->rl_pixel,rle);
+ rle->rl_count = 0;
+ return;
+ }
+ if (rle->just_cleared){
+ rle_flush_fromclear(rle->rl_count,rle);
+ } else if ((rle->rl_table_max < 2) || (rle->rl_table_pixel != rle->rl_pixel)) {
+ rle_flush_clearorrep(rle->rl_count,rle);
+ } else {
+ rle_flush_withtable(rle->rl_count,rle);
+ }
+ rle->rl_count = 0;
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_output_plain(int c,struct_RLE* rle)
+{
+ rle->just_cleared = 0;
+ rle_output(c,rle);
+ rle->out_count++;
+ if (rle->out_count >= rle->out_bump){
+ rle->out_bits ++;
+ rle->out_bump += 1 << (rle->out_bits - 1);
+ }
+ if (rle->out_count >= rle->out_clear){
+ rle_output(rle->code_clear,rle);
+ rle_clear(rle);
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_flush_fromclear(int count,struct_RLE* rle)
+{
+ int n;
+
+ rle->out_clear = rle->max_ocodes;
+ rle->rl_table_pixel = rle->rl_pixel;
+ n = 1;
+ while (count > 0){
+ if (n == 1){
+ rle->rl_table_max = 1;
+ rle_output_plain(rle->rl_pixel,rle);
+ count --;
+ } else if (count >= n){
+ rle->rl_table_max = n;
+ rle_output_plain(rle->rl_basecode+n-2,rle);
+ count -= n;
+ } else if (count == 1){
+ rle->rl_table_max ++;
+ rle_output_plain(rle->rl_pixel,rle);
+ count = 0;
+ } else {
+ rle->rl_table_max ++;
+ rle_output_plain(rle->rl_basecode+count-2,rle);
+ count = 0;
+ }
+ if (rle->out_count == 0) n = 1; else n ++;
+ }
+ rle_reset_out_clear(rle);
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_reset_out_clear(struct_RLE* rle)
+{
+ rle->out_clear = rle->out_clear_init;
+ if (rle->out_count >= rle->out_clear){
+ rle_output(rle->code_clear,rle);
+ rle_clear(rle);
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_flush_withtable(int count, struct_RLE* rle)
+{
+ int repmax;
+ int repleft;
+ int leftover;
+
+ repmax = count / rle->rl_table_max;
+ leftover = count % rle->rl_table_max;
+ repleft = (leftover ? 1 : 0);
+ if (rle->out_count+repmax+repleft > rle->max_ocodes){
+ repmax = rle->max_ocodes - rle->out_count;
+ leftover = count - (repmax * rle->rl_table_max);
+ repleft = 1 + rle_compute_triangle_count(leftover,rle->max_ocodes);
+ }
+ if (1+rle_compute_triangle_count(count,rle->max_ocodes) < (unsigned int)(repmax+repleft)){
+ rle_output(rle->code_clear,rle);
+ rle_clear(rle);
+ rle_flush_fromclear(count,rle);
+ return;
+ }
+ rle->out_clear = rle->max_ocodes;
+ for (;repmax>0;repmax--) rle_output_plain(rle->rl_basecode+rle->rl_table_max-2,rle);
+ if (leftover){
+ if (rle->just_cleared){
+ rle_flush_fromclear(leftover,rle);
+ } else if (leftover == 1){
+ rle_output_plain(rle->rl_pixel,rle);
+ } else {
+ rle_output_plain(rle->rl_basecode+leftover-2,rle);
+ }
+ }
+ rle_reset_out_clear(rle);
+}
+////////////////////////////////////////////////////////////////////////////////
+unsigned int CxImageGIF::rle_compute_triangle_count(unsigned int count, unsigned int nrepcodes)
+{
+ unsigned int perrep;
+ unsigned int cost;
+
+ cost = 0;
+ perrep = (nrepcodes * (nrepcodes+1)) / 2;
+ while (count >= perrep){
+ cost += nrepcodes;
+ count -= perrep;
+ }
+ if (count > 0){
+ unsigned int n;
+ n = rle_isqrt(count);
+ while ((n*(n+1)) >= 2*count) n --;
+ while ((n*(n+1)) < 2*count) n ++;
+ cost += n;
+ }
+ return(cost);
+}
+////////////////////////////////////////////////////////////////////////////////
+unsigned int CxImageGIF::rle_isqrt(unsigned int x)
+{
+ unsigned int r;
+ unsigned int v;
+
+ if (x < 2) return(x);
+ for (v=x,r=1;v;v>>=2,r<<=1) ;
+ for( ;; )
+ {
+ v = ((x / r) + r) / 2;
+ if ((v == r) || (v == r+1)) return(r);
+ r = v;
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_flush_clearorrep(int count, struct_RLE* rle)
+{
+ int withclr;
+ withclr = 1 + rle_compute_triangle_count(count,rle->max_ocodes);
+ if (withclr < count) {
+ rle_output(rle->code_clear,rle);
+ rle_clear(rle);
+ rle_flush_fromclear(count,rle);
+ } else {
+ for (;count>0;count--) rle_output_plain(rle->rl_pixel,rle);
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_write_block(struct_RLE* rle)
+{
+ g_outfile->PutC((BYTE)rle->oblen);
+ g_outfile->Write(rle->oblock,1,rle->oblen);
+ rle->oblen = 0;
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_block_out(unsigned char c, struct_RLE* rle)
+{
+ rle->oblock[rle->oblen++] = c;
+ if (rle->oblen >= 255) rle_write_block(rle);
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_block_flush(struct_RLE* rle)
+{
+ if (rle->oblen > 0) rle_write_block(rle);
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_output(int val, struct_RLE* rle)
+{
+ rle->obuf |= val << rle->obits;
+ rle->obits += rle->out_bits;
+ while (rle->obits >= 8){
+ rle_block_out((unsigned char)(rle->obuf&0xff),rle);
+ rle->obuf >>= 8;
+ rle->obits -= 8;
+ }
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::rle_output_flush(struct_RLE* rle)
+{
+ if (rle->obits > 0) rle_block_out((unsigned char)(rle->obuf),rle);
+ rle_block_flush(rle);
+}
+////////////////////////////////////////////////////////////////////////////////
+void CxImageGIF::compressRLE( int init_bits, CxFile* outfile)
+{
+ g_init_bits = init_bits;
+ g_outfile = outfile;
+
+ struct_RLE rle;
+ rle.code_clear = 1 << (init_bits - 1);
+ rle.code_eof = rle.code_clear + 1;
+ rle.rl_basecode = rle.code_eof + 1;
+ rle.out_bump_init = (1 << (init_bits - 1)) - 1;
+ rle.out_clear_init = (init_bits <= 3) ? 9 : (rle.out_bump_init-1);
+ rle.out_bits_init = init_bits;
+ rle.max_ocodes = (1 << MAXBITSCODES) - ((1 << (rle.out_bits_init - 1)) + 3);
+ rle.rl_count = 0;
+ rle_clear(&rle);
+ rle.obuf = 0;
+ rle.obits = 0;
+ rle.oblen = 0;
+
+ rle_output(rle.code_clear,&rle);
+
+ int c;
+ for( ;; )
+ {
+ c = GifNextPixel();
+ if ((rle.rl_count > 0) && (c != rle.rl_pixel)) rle_flush(&rle);
+ if (c == EOF) break;
+ if (rle.rl_pixel == c){
+ rle.rl_count++;
+ } else {
+ rle.rl_pixel = c;
+ rle.rl_count = 1;
+ }
+ }
+ rle_output(rle.code_eof,&rle);
+ rle_output_flush(&rle);
+}
+////////////////////////////////////////////////////////////////////////////////
+#endif // CXIMAGE_SUPPORT_GIF