@@ -782,11 +782,19 @@ PNG_STATIC int DecodePNG(PNGIMAGE *pPage, void *pUser, int iOptions)
782782 // number of bytes remaining in buffer
783783 iBytesRead -= iOffset;
784784 }
785- d_stream.next_in = &pPage->ucFileBuf [iOffset];
786- d_stream.avail_in = iBytesRead;
787- iLen -= iBytesRead;
788- if (iLen < 0 ) iLen = 0 ;
789- iOffset += iBytesRead;
785+ if (iBytesRead > iLen) { // we read too much
786+ d_stream.next_in = &pPage->ucFileBuf [iOffset];
787+ d_stream.avail_in = iLen;
788+ iOffset += iLen; // point to start of next marker
789+ iBytesRead -= iLen; // keep remaining byte count
790+ iLen = 0 ; // every byte will be decoded
791+ } else {
792+ d_stream.next_in = &pPage->ucFileBuf [iOffset];
793+ d_stream.avail_in = iBytesRead;
794+ iLen -= iBytesRead;
795+ iOffset += iBytesRead;
796+ iBytesRead = 0 ;
797+ }
790798 // if (iMarker == 0x66644154) // data starts at offset 4 in APNG frame data block
791799 // {
792800 // d_stream.next_in += 4;
@@ -840,9 +848,15 @@ PNG_STATIC int DecodePNG(PNGIMAGE *pPage, void *pUser, int iOptions)
840848 } // while (iLen)
841849 if (y != pPage->iHeight && iFileOffset < pPage->PNGFile .iSize ) {
842850 // need to read more IDAT chunks
843- iBytesRead = (*pPage->pfnRead )(&pPage->PNGFile , pPage->ucFileBuf , PNG_FILE_BUF_SIZE);
844- iFileOffset += iBytesRead;
845- iOffset = 0 ;
851+ if (iBytesRead) { // data remaining in buffer
852+ // move the data down
853+ memmove (pPage->ucFileBuf , &pPage->ucFileBuf [iOffset], iBytesRead);
854+ iOffset = 0 ;
855+ } else {
856+ iBytesRead = (*pPage->pfnRead )(&pPage->PNGFile , pPage->ucFileBuf , PNG_FILE_BUF_SIZE);
857+ iFileOffset += iBytesRead;
858+ iOffset = 0 ;
859+ }
846860 }
847861 break ;
848862 // case 0x69545874: //'iTXt'
0 commit comments