Coverage Report

Created: 2026-11-26 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cgif/src/cgif.c
Line
Count
Source
1
#include <stdint.h>
2
#include <stdio.h>
3
#include <string.h>
4
#include <stdlib.h>
5
6
#include "cgif.h"
7
#include "cgif_raw.h"
8
9
6.03M
#define MULU16(a, b) (((uint32_t)a) * ((uint32_t)b)) // helper macro to correctly multiply two U16's without default signed int promotion
10
35.0k
#define SIZE_FRAME_QUEUE (3)
11
12
// CGIF_Frame type
13
// note: internal sections, subject to change in future versions
14
typedef struct {
15
  CGIF_FrameConfig config;
16
  uint8_t          disposalMethod;
17
  uint8_t          transIndex;
18
} CGIF_Frame;
19
20
// CGIF type
21
// note: internal sections, subject to change in future versions
22
struct st_gif {
23
  CGIF_Frame*        aFrames[SIZE_FRAME_QUEUE]; // (internal) we need to keep the last three frames in memory.
24
  CGIF_Config        config;                    // (internal) configuration parameters of the GIF
25
  CGIFRaw*           pGIFRaw;                   // (internal) raw GIF stream
26
  FILE*              pFile;
27
  cgif_result        curResult;
28
  int                iHEAD;                     // (internal) index to current HEAD frame in aFrames queue
29
};
30
31
// dimension result type
32
typedef struct {
33
  uint16_t width;
34
  uint16_t height;
35
  uint16_t top;
36
  uint16_t left;
37
} DimResult;
38
39
/* calculate next power of two exponent of given number (n MUST be <= 256) */
40
918
static uint8_t calcNextPower2Ex(uint16_t n) {
41
918
  uint8_t nextPow2;
42
43
2.28k
  for (nextPow2 = 0; n > (1uL << nextPow2); ++nextPow2);
44
918
  return nextPow2;
45
918
}
46
47
/* write callback. returns 0 on success or -1 on error.  */
48
58.5k
static int writecb(void* pContext, const uint8_t* pData, const size_t numBytes) {
49
58.5k
  CGIF* pGIF;
50
58.5k
  size_t r;
51
52
58.5k
  pGIF = (CGIF*)pContext;
53
58.5k
  if(pGIF->pFile) {
54
58.5k
    r = fwrite(pData, 1, numBytes, pGIF->pFile);
55
58.5k
    if(r == numBytes) return 0;
56
0
    else return -1;
57
58.5k
  } else if(pGIF->config.pWriteFn) {
58
0
    return pGIF->config.pWriteFn(pGIF->config.pContext, pData, numBytes);
59
0
  }
60
0
  return 0;
61
58.5k
}
62
63
/* free space allocated for CGIF struct */
64
2.07k
static void freeCGIF(CGIF* pGIF) {
65
2.07k
  if((pGIF->config.attrFlags & CGIF_ATTR_NO_GLOBAL_TABLE) == 0) {
66
1.98k
    free(pGIF->config.pGlobalPalette);
67
1.98k
  }
68
2.07k
  free(pGIF);
69
2.07k
}
70
71
/* create a new GIF */
72
2.08k
CGIF* cgif_newgif(CGIF_Config* pConfig) {
73
2.08k
  FILE*          pFile;
74
2.08k
  CGIF*          pGIF;
75
2.08k
  CGIFRaw*       pGIFRaw; // raw GIF stream
76
2.08k
  CGIFRaw_Config rawConfig = {0};
77
  // width or heigth cannot be zero
78
2.08k
  if(!pConfig->width || !pConfig->height) {
79
9
    return NULL;
80
9
  }
81
2.07k
  pFile = NULL;
82
  // open output file (if necessary)
83
2.07k
  if(pConfig->path) {
84
2.07k
    pFile = fopen(pConfig->path, "wb");
85
2.07k
    if(pFile == NULL) {
86
0
      return NULL; // error: fopen failed
87
0
    }
88
2.07k
  }
89
  // allocate space for CGIF context
90
2.07k
  pGIF = malloc(sizeof(CGIF));
91
2.07k
  if(pGIF == NULL) {
92
0
    if(pFile) {
93
0
      fclose(pFile);
94
0
    }
95
0
    return NULL; // error -> malloc failed
96
0
  }
97
98
2.07k
  memset(pGIF, 0, sizeof(CGIF));
99
2.07k
  pGIF->pFile = pFile;
100
2.07k
  pGIF->iHEAD = 1;
101
2.07k
  memcpy(&(pGIF->config), pConfig, sizeof(CGIF_Config));
102
  // make a deep copy of global color tabele (GCT), if required.
103
2.07k
  if((pConfig->attrFlags & CGIF_ATTR_NO_GLOBAL_TABLE) == 0) {
104
1.98k
    pGIF->config.pGlobalPalette = malloc(pConfig->numGlobalPaletteEntries * 3);
105
1.98k
    if(pGIF->config.pGlobalPalette == NULL) {
106
0
      if(pFile) {
107
0
        fclose(pFile);
108
0
      }
109
0
      free(pGIF);
110
0
      return NULL;
111
0
    }
112
1.98k
    memcpy(pGIF->config.pGlobalPalette, pConfig->pGlobalPalette, pConfig->numGlobalPaletteEntries * 3);
113
1.98k
  }
114
115
2.07k
  rawConfig.pGCT      = pConfig->pGlobalPalette;
116
2.07k
  rawConfig.sizeGCT   = (pConfig->attrFlags & CGIF_ATTR_NO_GLOBAL_TABLE) ? 0 : pConfig->numGlobalPaletteEntries;
117
  // translate CGIF_ATTR_* to CGIF_RAW_ATTR_* flags
118
2.07k
  rawConfig.attrFlags = (pConfig->attrFlags & CGIF_ATTR_IS_ANIMATED) ? CGIF_RAW_ATTR_IS_ANIMATED : 0;
119
2.07k
  rawConfig.attrFlags |= (pConfig->attrFlags & CGIF_ATTR_NO_LOOP) ? CGIF_RAW_ATTR_NO_LOOP : 0;
120
2.07k
  rawConfig.width     = pConfig->width;
121
2.07k
  rawConfig.height    = pConfig->height;
122
2.07k
  rawConfig.numLoops  = pConfig->numLoops;
123
2.07k
  rawConfig.pWriteFn  = writecb;
124
2.07k
  rawConfig.pContext  = (void*)pGIF;
125
  // pass config down and create a new raw GIF stream.
126
2.07k
  pGIFRaw = cgif_raw_newgif(&rawConfig);
127
  // check for errors
128
2.07k
  if(pGIFRaw == NULL) {
129
9
    if(pFile) {
130
9
      fclose(pFile);
131
9
    }
132
9
    freeCGIF(pGIF);
133
9
    return NULL;
134
9
  }
135
136
2.06k
  pGIF->pGIFRaw = pGIFRaw;
137
  // assume error per default.
138
  // set to CGIF_OK by the first successful cgif_addframe() call, as a GIF without frames is invalid.
139
2.06k
  pGIF->curResult = CGIF_PENDING;
140
2.06k
  return pGIF;
141
2.07k
}
142
143
/* compare given pixel indices using the correct local or global color table; returns 0 if the two pixels are RGB equal */
144
1.31M
static int cmpPixel(const CGIF* pGIF, const CGIF_FrameConfig* pCur, const CGIF_FrameConfig* pBef, const uint8_t iCur, const uint8_t iBef) {
145
1.31M
  uint8_t* pBefCT; // color table to use for pBef
146
1.31M
  uint8_t* pCurCT; // color table to use for pCur
147
148
1.31M
  if((pCur->attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) && iCur == pCur->transIndex) {
149
16.7k
    return 0; // identical
150
16.7k
  }
151
1.30M
  if((pBef->attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) && iBef == pBef->transIndex) {
152
1.53k
    return 1; // done: cannot compare
153
1.53k
  }
154
  // safety bounds check
155
1.29M
  const uint16_t sizeCTBef = (pBef->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) ? pBef->numLocalPaletteEntries : pGIF->config.numGlobalPaletteEntries;
156
1.29M
  const uint16_t sizeCTCur = (pCur->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) ? pCur->numLocalPaletteEntries : pGIF->config.numGlobalPaletteEntries;
157
1.29M
  if((iBef >= sizeCTBef) || (iCur >= sizeCTCur)) {
158
817k
    return 1; // error: out-of-bounds - cannot compare
159
817k
  }
160
481k
  pBefCT = (pBef->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) ? pBef->pLocalPalette : pGIF->config.pGlobalPalette; // local or global table used?
161
481k
  pCurCT = (pCur->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) ? pCur->pLocalPalette : pGIF->config.pGlobalPalette; // local or global table used?
162
481k
  return memcmp(pBefCT + iBef * 3, pCurCT + iCur * 3, 3);
163
1.29M
}
164
165
// compare given frames; returns 0 if frames are equal and 1 if they differ. If they differ, pResult returns area of difference
166
1.12k
static int getDiffArea(CGIF* pGIF, CGIF_FrameConfig* pCur, CGIF_FrameConfig* pBef, DimResult *pResult) {
167
1.12k
  const uint8_t* pCurImageData;
168
1.12k
  const uint8_t* pBefImageData;
169
1.12k
  uint16_t       i, x;
170
1.12k
  uint16_t       newHeight, newWidth, newLeft, newTop;
171
1.12k
  const uint16_t width  = pGIF->config.width;
172
1.12k
  const uint16_t height = pGIF->config.height;
173
1.12k
  uint8_t        iCur, iBef;
174
175
1.12k
  pCurImageData = pCur->pImageData;
176
1.12k
  pBefImageData = pBef->pImageData;
177
  // find top
178
1.12k
  i = 0;
179
32.2k
  while(i < height) {
180
65.2k
    for(int c = 0; c < width; ++c) {
181
34.1k
      iCur = *(pCurImageData + MULU16(i, width) + c);
182
34.1k
      iBef = *(pBefImageData + MULU16(i, width) + c);
183
34.1k
      if(cmpPixel(pGIF, pCur, pBef, iCur, iBef) != 0) {
184
1.02k
        goto FoundTop;
185
1.02k
      }
186
34.1k
    }
187
31.1k
    ++i;
188
31.1k
  }
189
1.12k
FoundTop:
190
1.12k
  if(i == height) {
191
102
    return 0;
192
102
  }
193
1.02k
  newTop = i;
194
195
  // find actual height
196
1.02k
  i = height - 1;
197
3.06k
  while(i > newTop) {
198
4.93k
    for(int c = 0; c < width; ++c) {
199
2.88k
      iCur = *(pCurImageData + MULU16(i, width) + c);
200
2.88k
      iBef = *(pBefImageData + MULU16(i, width) + c);
201
2.88k
      if(cmpPixel(pGIF, pCur, pBef, iCur, iBef) != 0) {
202
408
        goto FoundHeight;
203
408
      }
204
2.88k
    }
205
2.04k
    --i;
206
2.04k
  }
207
1.02k
FoundHeight:
208
1.02k
  newHeight = (i + 1) - newTop;
209
210
  // find left
211
1.02k
  i = newTop;
212
1.02k
  x = 0;
213
3.03k
  while(cmpPixel(pGIF, pCur, pBef, pCurImageData[MULU16(i, width) + x], pBefImageData[MULU16(i, width) + x]) == 0) {
214
2.01k
    ++i;
215
2.01k
    if(i > (newTop + newHeight - 1)) {
216
1.28k
      ++x; //(x==width cannot happen as return 0 is trigged in the only possible case before)
217
1.28k
      i = newTop;
218
1.28k
    }
219
2.01k
  }
220
1.02k
  newLeft = x;
221
222
  // find actual width
223
1.02k
  i = newTop;
224
1.02k
  x = width - 1;
225
2.65k
  while(cmpPixel(pGIF, pCur, pBef, pCurImageData[MULU16(i, width) + x], pBefImageData[MULU16(i, width) + x]) == 0) {
226
1.63k
    ++i;
227
1.63k
    if(i > (newTop + newHeight - 1)) {
228
1.34k
      --x; //(x<newLeft cannot happen as return 0 is trigged in the only possible case before)
229
1.34k
      i = newTop;
230
1.34k
    }
231
1.63k
  }
232
1.02k
  newWidth = (x + 1) - newLeft;
233
234
1.02k
  pResult->width  = newWidth;
235
1.02k
  pResult->height = newHeight;
236
1.02k
  pResult->top    = newTop;
237
1.02k
  pResult->left   = newLeft;
238
1.02k
  return 1;
239
1.02k
}
240
241
// compare given global palette frames; returns 0 if frames are equal and 1 if they differ. If they differ, pResult returns area of difference
242
600
static int getDiffAreaGlobalPalette(CGIF* pGIF, CGIF_FrameConfig* pCur, CGIF_FrameConfig* pBef, DimResult *pResult) {
243
600
  const uint8_t* pCurImageData;
244
600
  const uint8_t* pBefImageData;
245
600
  uint32_t       offset;
246
600
  uint16_t       i, x;
247
600
  uint16_t       newHeight, newWidth, newLeft, newTop;
248
600
  const uint16_t width  = pGIF->config.width;
249
600
  const uint16_t height = pGIF->config.height;
250
251
600
  pCurImageData = pCur->pImageData;
252
600
  pBefImageData = pBef->pImageData;
253
  // find top
254
600
  i = 0;
255
600
  offset = 0;
256
20.5k
  while(i < height) {
257
20.4k
    if (memcmp(pCurImageData + offset, pBefImageData + offset, width)) {
258
547
      break;
259
547
    }
260
19.9k
    ++i;
261
19.9k
    offset += width;
262
19.9k
  }
263
264
600
  if(i == height) {
265
53
    return 0;
266
53
  }
267
547
  newTop = i;
268
269
  // find actual height
270
547
  i = height - 1;
271
547
  offset = MULU16(i, width);
272
1.74k
  while(i > newTop) {
273
1.48k
    if (memcmp(pCurImageData + offset, pBefImageData + offset, width)) {
274
283
      break;
275
283
    }
276
1.20k
    --i;
277
1.20k
    offset -= width;
278
1.20k
  }
279
547
  newHeight = (i + 1) - newTop;
280
281
  // find left
282
547
  i = newTop;
283
547
  x = 0;
284
547
  offset = MULU16(i, width);
285
20.6k
  while(pCurImageData[offset + x] == pBefImageData[offset + x]) {
286
20.0k
    ++i;
287
20.0k
    offset += width;
288
20.0k
    if(i > (newTop + newHeight - 1)) {
289
745
      ++x; //(x==width cannot happen as return 0 is triggered in the only possible case before)
290
745
      i = newTop;
291
745
      offset = MULU16(i, width);
292
745
    }
293
20.0k
  }
294
547
  newLeft = x;
295
296
  // find actual width
297
547
  i = newTop;
298
547
  x = width - 1;
299
547
  offset = MULU16(i, width);
300
28.6k
  while(pCurImageData[offset + x] == pBefImageData[offset + x]) {
301
28.0k
    ++i;
302
28.0k
    offset += width;
303
28.0k
    if(i > (newTop + newHeight - 1)) {
304
532
      --x; //(x<newLeft cannot happen as return 0 is triggered in the only possible case before)
305
532
      i = newTop;
306
532
      offset = MULU16(i, width);
307
532
    }
308
28.0k
  }
309
547
  newWidth = (x + 1) - newLeft;
310
311
547
  pResult->width  = newWidth;
312
547
  pResult->height = newHeight;
313
547
  pResult->top    = newTop;
314
547
  pResult->left   = newLeft;
315
547
  return 1;
316
600
}
317
318
/* optimize GIF file size by only redrawing the rectangular area that differs from previous frame */
319
1.72k
static uint8_t* doWidthHeightOptim(CGIF* pGIF, CGIF_FrameConfig* pCur, CGIF_FrameConfig* pBef, DimResult* pResult) {
320
1.72k
  uint16_t i;
321
1.72k
  uint8_t* pNewImageData;
322
1.72k
  const uint16_t width  = pGIF->config.width;
323
1.72k
  const uint8_t* pCurImageData = pCur->pImageData;
324
1.72k
  int diffFrame;
325
326
1.72k
  if ((pBef->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) == 0 && (pCur->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) == 0
327
1.15k
      && (pBef->attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) == 0 && (pCur->attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) == 0) {
328
    // Both frames use global palette; use fast comparison.
329
600
    diffFrame = getDiffAreaGlobalPalette(pGIF, pCur, pBef, pResult);
330
1.12k
  } else {
331
1.12k
    diffFrame = getDiffArea(pGIF, pCur, pBef, pResult);
332
1.12k
  }
333
334
1.72k
  if (diffFrame == 0) { // need dummy pixel (frame is identical with one before)
335
    // TBD we might make it possible to merge identical frames in the future
336
155
    pResult->width  = 1;
337
155
    pResult->height = 1;
338
155
    pResult->left   = 0;
339
155
    pResult->top    = 0;
340
155
  }
341
342
  // create new image data
343
1.72k
  pNewImageData = malloc(MULU16(pResult->width, pResult->height));
344
1.72k
  if(pNewImageData == NULL) {
345
0
    return NULL; // allocation failed
346
0
  }
347
1.61M
  for (i = 0; i < pResult->height; ++i) {
348
1.61M
    memcpy(pNewImageData + MULU16(i, pResult->width), pCurImageData + MULU16((i + pResult->top), width) + pResult->left, pResult->width);
349
1.61M
  }
350
351
1.72k
  return pNewImageData;
352
1.72k
}
353
354
/* move frame down to the raw GIF API */
355
4.69k
static cgif_result flushFrame(CGIF* pGIF, CGIF_Frame* pCur, CGIF_Frame* pBef) {
356
4.69k
  CGIFRaw_FrameConfig rawConfig;
357
4.69k
  DimResult           dimResult;
358
4.69k
  uint8_t*            pTmpImageData;
359
4.69k
  uint8_t*            pBefImageData;
360
4.69k
  int                 isFirstFrame, useLCT, hasAlpha, hasSetTransp;
361
4.69k
  uint16_t            numPaletteEntries;
362
4.69k
  uint16_t            imageWidth, imageHeight, width, height, top, left;
363
4.69k
  uint8_t             transIndex, disposalMethod;
364
4.69k
  cgif_result         r;
365
366
4.69k
  imageWidth     = pGIF->config.width;
367
4.69k
  imageHeight    = pGIF->config.height;
368
4.69k
  isFirstFrame   = (pBef == NULL) ? 1 : 0;
369
4.69k
  useLCT         = (pCur->config.attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) ? 1 : 0; // LCT stands for "local color table"
370
4.69k
  hasAlpha       = ((pGIF->config.attrFlags & CGIF_ATTR_HAS_TRANSPARENCY) || (pCur->config.attrFlags & CGIF_FRAME_ATTR_HAS_ALPHA)) ? 1 : 0;
371
4.69k
  hasSetTransp   = (pCur->config.attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) ? 1 : 0;
372
4.69k
  disposalMethod = pCur->disposalMethod;
373
4.69k
  transIndex     = pCur->transIndex;
374
  // deactivate impossible size optimizations
375
  //  => in case alpha channel is used
376
  // CGIF_FRAME_GEN_USE_TRANSPARENCY and CGIF_FRAME_GEN_USE_DIFF_WINDOW are not possible
377
4.69k
  if(isFirstFrame || hasAlpha) {
378
2.25k
    pCur->config.genFlags &= ~(CGIF_FRAME_GEN_USE_TRANSPARENCY | CGIF_FRAME_GEN_USE_DIFF_WINDOW);
379
2.25k
  }
380
  // transparency setting (which areas are identical to the frame before) provided by user:
381
  // CGIF_FRAME_GEN_USE_TRANSPARENCY not possible
382
4.69k
  if(hasSetTransp) {
383
1.34k
    pCur->config.genFlags &= ~(CGIF_FRAME_GEN_USE_TRANSPARENCY);
384
1.34k
  }
385
4.69k
  numPaletteEntries = (useLCT) ? pCur->config.numLocalPaletteEntries : pGIF->config.numGlobalPaletteEntries;
386
  // switch off transparency optimization if color table is full (no free spot for the transparent index), TBD: count used colors, adapt table
387
4.69k
  if(numPaletteEntries == 256) {
388
168
    pCur->config.genFlags &= ~CGIF_FRAME_GEN_USE_TRANSPARENCY;
389
168
  }
390
391
  // purge overlap of current frame and frame before (width - height optim), if required (CGIF_FRAME_GEN_USE_DIFF_WINDOW set)
392
4.69k
  if(pCur->config.genFlags & CGIF_FRAME_GEN_USE_DIFF_WINDOW) {
393
1.72k
    pTmpImageData = doWidthHeightOptim(pGIF, &pCur->config, &pBef->config, &dimResult);
394
1.72k
    if(pTmpImageData == NULL) {
395
0
      return CGIF_EALLOC; // allocation failed in doWidthHeightOptim
396
0
    }
397
1.72k
    width  = dimResult.width;
398
1.72k
    height = dimResult.height;
399
1.72k
    top    = dimResult.top;
400
1.72k
    left   = dimResult.left;
401
2.97k
  } else {
402
2.97k
    pTmpImageData = NULL;
403
2.97k
    width         = imageWidth;
404
2.97k
    height        = imageHeight;
405
2.97k
    top           = 0;
406
2.97k
    left          = 0;
407
2.97k
  }
408
409
  // mark matching areas of the previous frame as transparent, if required (CGIF_FRAME_GEN_USE_TRANSPARENCY set)
410
4.69k
  if(pCur->config.genFlags & CGIF_FRAME_GEN_USE_TRANSPARENCY) {
411
    // set transIndex to next free index
412
918
    int pow2 = calcNextPower2Ex(numPaletteEntries);
413
918
    pow2 = (pow2 < 2) ? 2 : pow2; // TBD keep transparency index behavior as in V0.1.0 (for now)
414
918
    transIndex = (1 << pow2) - 1;
415
918
    if(transIndex < numPaletteEntries) {
416
103
      transIndex = (1 << (pow2 + 1)) - 1;
417
103
    }
418
918
    if(pTmpImageData == NULL) {
419
199
      pTmpImageData = malloc(MULU16(imageWidth, imageHeight));
420
199
      if(pTmpImageData == NULL) {
421
0
        return CGIF_EALLOC; // allocation failed
422
0
      }
423
199
      memcpy(pTmpImageData, pCur->config.pImageData, MULU16(imageWidth, imageHeight));
424
199
    }
425
918
    pBefImageData = pBef->config.pImageData;
426
760k
    for(int i = 0; i < height; ++i) {
427
2.00M
      for(int x = 0; x < width; ++x) {
428
1.24M
        if(cmpPixel(pGIF, &pCur->config, &pBef->config, pTmpImageData[MULU16(i, width) + x], pBefImageData[MULU16(top + i, imageWidth) + (left + x)]) == 0) {
429
177k
          pTmpImageData[MULU16(i, width) + x] = transIndex;
430
177k
        }
431
1.24M
      }
432
759k
    }
433
918
  }
434
435
  // move frame down to GIF raw API
436
4.69k
  rawConfig.pLCT           = pCur->config.pLocalPalette;
437
4.69k
  rawConfig.pImageData     = (pTmpImageData) ? pTmpImageData : pCur->config.pImageData;
438
4.69k
  rawConfig.attrFlags      = 0;
439
4.69k
  if(hasAlpha || (pCur->config.genFlags & CGIF_FRAME_GEN_USE_TRANSPARENCY) || hasSetTransp) {
440
3.06k
    rawConfig.attrFlags |= CGIF_RAW_FRAME_ATTR_HAS_TRANS;
441
3.06k
  }
442
4.69k
  rawConfig.attrFlags |= (pCur->config.attrFlags & CGIF_FRAME_ATTR_INTERLACED) ? CGIF_RAW_FRAME_ATTR_INTERLACED : 0;
443
4.69k
  rawConfig.width          = width;
444
4.69k
  rawConfig.height         = height;
445
4.69k
  rawConfig.top            = top;
446
4.69k
  rawConfig.left           = left;
447
4.69k
  rawConfig.delay          = pCur->config.delay;
448
4.69k
  rawConfig.sizeLCT        = (useLCT) ? pCur->config.numLocalPaletteEntries : 0;
449
4.69k
  rawConfig.disposalMethod = disposalMethod;
450
4.69k
  rawConfig.transIndex     = transIndex;
451
4.69k
  r = cgif_raw_addframe(pGIF->pGIFRaw, &rawConfig);
452
4.69k
  free(pTmpImageData);
453
4.69k
  return r;
454
4.69k
}
455
456
7.77k
static void freeFrame(CGIF_Frame* pFrame) {
457
7.77k
  if(pFrame) {
458
4.86k
    free(pFrame->config.pImageData);
459
4.86k
    if(pFrame->config.attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) {
460
1.00k
      free(pFrame->config.pLocalPalette);
461
1.00k
    }
462
4.86k
    free(pFrame);
463
4.86k
  }
464
7.77k
}
465
466
4.86k
static void copyFrameConfig(CGIF_FrameConfig* pDest, CGIF_FrameConfig* pSrc) {
467
4.86k
  pDest->pLocalPalette          = pSrc->pLocalPalette; // might need a deep copy
468
4.86k
  pDest->pImageData             = pSrc->pImageData;    // might need a deep copy
469
4.86k
  pDest->attrFlags              = pSrc->attrFlags;
470
4.86k
  pDest->genFlags               = pSrc->genFlags;
471
4.86k
  pDest->delay                  = pSrc->delay;
472
4.86k
  pDest->numLocalPaletteEntries = pSrc->numLocalPaletteEntries;
473
  // copy transIndex if necessary (field added with V0.2.0; avoid binary incompatibility)
474
4.86k
  if(pSrc->attrFlags & (CGIF_FRAME_ATTR_HAS_ALPHA | CGIF_FRAME_ATTR_HAS_SET_TRANS)) {
475
2.01k
    pDest->transIndex = pSrc->transIndex;
476
2.01k
  }
477
4.86k
}
478
479
/* queue a new GIF frame */
480
5.41k
int cgif_addframe(CGIF* pGIF, CGIF_FrameConfig* pConfig) {
481
5.41k
  CGIF_Frame* pNewFrame;
482
5.41k
  int         hasAlpha, hasSetTransp;
483
5.41k
  uint32_t    i;
484
5.41k
  cgif_result r;
485
486
  // check for previous errors
487
5.41k
  if(pGIF->curResult != CGIF_OK && pGIF->curResult != CGIF_PENDING) {
488
258
    return pGIF->curResult;
489
258
  }
490
5.15k
  hasAlpha     = ((pGIF->config.attrFlags & CGIF_ATTR_HAS_TRANSPARENCY) || (pConfig->attrFlags & CGIF_FRAME_ATTR_HAS_ALPHA)) ? 1 : 0; // alpha channel is present
491
5.15k
  hasSetTransp = (pConfig->attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) ? 1 : 0;  // user provided transparency setting (identical areas marked by user)
492
  // check for invalid configs:
493
  // cannot set alpha channel and user-provided transparency at the same time.
494
5.15k
  if(hasAlpha && hasSetTransp) {
495
19
    pGIF->curResult = CGIF_ERROR;
496
19
    return pGIF->curResult;
497
19
  }
498
  // cannot set global and local alpha channel at the same time
499
5.13k
  if((pGIF->config.attrFlags & CGIF_ATTR_HAS_TRANSPARENCY) && (pConfig->attrFlags & CGIF_FRAME_ATTR_HAS_ALPHA)) {
500
1
    pGIF->curResult = CGIF_ERROR;
501
1
    return pGIF->curResult;
502
1
  }
503
  // sanity check:
504
  // at least one valid CT needed (global or local)
505
5.13k
  if(!(pConfig->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) && (pGIF->config.attrFlags & CGIF_ATTR_NO_GLOBAL_TABLE)) {
506
6
    pGIF->curResult = CGIF_ERROR;
507
6
    return CGIF_ERROR; // invalid config
508
6
  }
509
510
  // if frame matches previous frame, drop it completely and sum the frame delay
511
5.13k
  if(pGIF->aFrames[pGIF->iHEAD] != NULL) {
512
3.21k
    const uint32_t frameDelay = pConfig->delay + pGIF->aFrames[pGIF->iHEAD]->config.delay;
513
3.21k
    if(frameDelay <= 0xFFFF && !(pGIF->config.genFlags & CGIF_GEN_KEEP_IDENT_FRAMES)) {
514
1.71k
      int sameFrame = 1;
515
1.71k
      if ((pConfig->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) == 0 && (pGIF->aFrames[pGIF->iHEAD]->config.attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) == 0
516
1.10k
          && (pConfig->attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) == 0 && (pGIF->aFrames[pGIF->iHEAD]->config.attrFlags & CGIF_FRAME_ATTR_HAS_SET_TRANS) == 0) {
517
681
        if (memcmp(pConfig->pImageData, pGIF->aFrames[pGIF->iHEAD]->config.pImageData, MULU16(pGIF->config.width, pGIF->config.height))) {
518
597
          sameFrame = 0;
519
597
        }
520
1.03k
      } else {
521
28.9k
        for(i = 0; i < MULU16(pGIF->config.width, pGIF->config.height); i++) {
522
28.8k
          if(cmpPixel(pGIF, pConfig, &pGIF->aFrames[pGIF->iHEAD]->config, pConfig->pImageData[i], pGIF->aFrames[pGIF->iHEAD]->config.pImageData[i])) {
523
901
            sameFrame = 0;
524
901
            break;
525
901
          }
526
28.8k
        }
527
1.03k
      }
528
529
1.71k
      if (sameFrame) {
530
220
        pGIF->aFrames[pGIF->iHEAD]->config.delay = frameDelay;
531
220
        return CGIF_OK;
532
220
      }
533
1.71k
    }
534
3.21k
  }
535
536
  // search for free slot in frame queue
537
7.90k
  for(i = pGIF->iHEAD; i < SIZE_FRAME_QUEUE && pGIF->aFrames[i] != NULL; ++i);
538
  // check whether the queue is full
539
  // when queue is full: we need to flush one frame.
540
4.91k
  if(i == SIZE_FRAME_QUEUE) {
541
1.56k
    r = flushFrame(pGIF, pGIF->aFrames[1], pGIF->aFrames[0]);
542
1.56k
    freeFrame(pGIF->aFrames[0]);
543
1.56k
    pGIF->aFrames[0] = NULL; // avoid potential double free in cgif_close
544
    // check for errors
545
1.56k
    if(r != CGIF_OK) {
546
48
      pGIF->curResult = r;
547
48
      return pGIF->curResult;
548
48
    }
549
1.52k
    i = SIZE_FRAME_QUEUE - 1;
550
    // keep the flushed frame in memory, as we might need it to write the next one.
551
1.52k
    pGIF->aFrames[0] = pGIF->aFrames[1];
552
1.52k
    pGIF->aFrames[1] = pGIF->aFrames[2];
553
1.52k
    pGIF->aFrames[2] = NULL;
554
1.52k
  }
555
  // create new Frame struct + make a deep copy of pConfig.
556
4.86k
  pNewFrame = malloc(sizeof(CGIF_Frame));
557
4.86k
  if(pNewFrame == NULL) {
558
0
    pGIF->curResult = CGIF_EALLOC;
559
0
    return pGIF->curResult;
560
0
  }
561
4.86k
  copyFrameConfig(&(pNewFrame->config), pConfig);
562
4.86k
  pNewFrame->config.pImageData = malloc(MULU16(pGIF->config.width, pGIF->config.height));
563
4.86k
  if(pNewFrame->config.pImageData == NULL) {
564
0
    free(pNewFrame);
565
0
    pGIF->curResult = CGIF_EALLOC;
566
0
    return pGIF->curResult;
567
0
  }
568
4.86k
  memcpy(pNewFrame->config.pImageData, pConfig->pImageData, MULU16(pGIF->config.width, pGIF->config.height));
569
  // make a deep copy of the local color table, if required.
570
4.86k
  if(pConfig->attrFlags & CGIF_FRAME_ATTR_USE_LOCAL_TABLE) {
571
1.00k
    pNewFrame->config.pLocalPalette  = malloc(pConfig->numLocalPaletteEntries * 3);
572
1.00k
    if(pNewFrame->config.pLocalPalette == NULL) {
573
0
      free(pNewFrame->config.pImageData);
574
0
      free(pNewFrame);
575
0
      pGIF->curResult = CGIF_EALLOC;
576
0
      return pGIF->curResult;
577
0
    }
578
1.00k
    memcpy(pNewFrame->config.pLocalPalette, pConfig->pLocalPalette, pConfig->numLocalPaletteEntries * 3);
579
1.00k
  }
580
4.86k
  pNewFrame->disposalMethod        = DISPOSAL_METHOD_LEAVE;
581
4.86k
  pNewFrame->transIndex            = 0;
582
4.86k
  pGIF->aFrames[i]                 = pNewFrame; // add frame to queue
583
4.86k
  pGIF->iHEAD                      = i;         // update HEAD index
584
  // check whether we need to adapt the disposal method of the frame before.
585
4.86k
  if(pGIF->config.attrFlags & CGIF_ATTR_HAS_TRANSPARENCY) {
586
188
    pGIF->aFrames[i]->disposalMethod = DISPOSAL_METHOD_BACKGROUND; // TBD might be removed
587
188
    pGIF->aFrames[i]->transIndex     = 0;
588
188
    if(pGIF->aFrames[i - 1] != NULL) {
589
134
      pGIF->aFrames[i - 1]->config.genFlags &= ~(CGIF_FRAME_GEN_USE_TRANSPARENCY | CGIF_FRAME_GEN_USE_DIFF_WINDOW);
590
134
      pGIF->aFrames[i - 1]->disposalMethod   = DISPOSAL_METHOD_BACKGROUND; // restore to background color
591
134
    }
592
188
  }
593
  // set per-frame alpha channel (we need to adapt the disposal method of the frame before)
594
4.86k
  if(pConfig->attrFlags & CGIF_FRAME_ATTR_HAS_ALPHA) {
595
657
    pGIF->aFrames[i]->transIndex = pConfig->transIndex;
596
657
    if(pGIF->aFrames[i - 1] != NULL) {
597
241
      pGIF->aFrames[i - 1]->config.genFlags &= ~(CGIF_FRAME_GEN_USE_DIFF_WINDOW); // width/height optim not possible for frame before
598
241
      pGIF->aFrames[i - 1]->disposalMethod   = DISPOSAL_METHOD_BACKGROUND; // restore to background color
599
241
    }
600
657
  }
601
  // user provided transparency setting
602
4.86k
  if(hasSetTransp) {
603
1.36k
    pGIF->aFrames[i]->transIndex = pConfig->transIndex;
604
1.36k
  }
605
4.86k
  pGIF->curResult = CGIF_OK;
606
4.86k
  return pGIF->curResult;
607
4.86k
}
608
609
/* close the GIF-file and free allocated space */
610
2.06k
int cgif_close(CGIF* pGIF) {
611
2.06k
  int         r;
612
2.06k
  cgif_result result;
613
614
  // check for previous errors
615
2.06k
  if(pGIF->curResult != CGIF_OK) {
616
213
    goto CGIF_CLOSE_Cleanup;
617
213
  }
618
619
  // flush all remaining frames in queue
620
4.55k
  for(int i = 1; i < SIZE_FRAME_QUEUE; ++i) {
621
3.54k
    if(pGIF->aFrames[i] != NULL) {
622
3.12k
      r = flushFrame(pGIF, pGIF->aFrames[i], pGIF->aFrames[i - 1]);
623
3.12k
      if(r != CGIF_OK) {
624
839
        pGIF->curResult = r;
625
839
        break;
626
839
      }
627
3.12k
    }
628
3.54k
  }
629
630
  // cleanup
631
2.06k
CGIF_CLOSE_Cleanup:
632
2.06k
  r = cgif_raw_close(pGIF->pGIFRaw); // close raw GIF stream
633
  // check for errors
634
2.06k
  if(r != CGIF_OK) {
635
1.04k
    pGIF->curResult = r;
636
1.04k
  }
637
638
2.06k
  if(pGIF->pFile) {
639
2.06k
    r = fclose(pGIF->pFile); // we are done at this point => close the file
640
2.06k
    if(r) {
641
0
      pGIF->curResult = CGIF_ECLOSE; // error: fclose failed
642
0
    }
643
2.06k
  }
644
8.26k
  for(int i = 0; i < SIZE_FRAME_QUEUE; ++i) {
645
6.20k
    freeFrame(pGIF->aFrames[i]);
646
6.20k
  }
647
648
2.06k
  result = pGIF->curResult;
649
2.06k
  freeCGIF(pGIF);
650
  // catch internal value CGIF_PENDING
651
2.06k
  if(result == CGIF_PENDING) {
652
158
    result = CGIF_ERROR;
653
158
  }
654
2.06k
  return result; // return previous result
655
1.85k
}