Coverage Report

Created: 2026-12-01 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/examples/anim_util.c
Line
Count
Source
1
// Copyright 2015 Google Inc. All Rights Reserved.
2
//
3
// Use of this source code is governed by a BSD-style license
4
// that can be found in the COPYING file in the root of the source
5
// tree. An additional intellectual property rights grant can be found
6
// in the file PATENTS. All contributing project authors may
7
// be found in the AUTHORS file in the root of the source tree.
8
// -----------------------------------------------------------------------------
9
//
10
// Utilities for animated images
11
12
#include "./anim_util.h"
13
14
#include <assert.h>
15
#include <math.h>
16
#include <stdio.h>
17
#include <string.h>
18
19
#if defined(WEBP_HAVE_GIF)
20
#include <gif_lib.h>
21
#endif
22
23
#include "../imageio/imageio_util.h"
24
#include "./gifdec.h"
25
#include "./unicode.h"
26
#include "webp/decode.h"
27
#include "webp/demux.h"
28
#include "webp/format_constants.h"
29
#include "webp/mux_types.h"
30
#include "webp/types.h"
31
32
#if defined(_MSC_VER) && _MSC_VER < 1900
33
#define snprintf _snprintf
34
#endif
35
36
#ifndef WEBP_UINT64_MAX
37
0
#define WEBP_UINT64_MAX (~0ull)
38
#endif
39
40
static const int kNumChannels = 4;
41
42
// -----------------------------------------------------------------------------
43
// Common utilities.
44
45
#if defined(WEBP_HAVE_GIF)
46
// Returns true if the frame covers the full canvas.
47
static int IsFullFrame(int width, int height, int canvas_width,
48
0
                       int canvas_height) {
49
0
  return (width == canvas_width && height == canvas_height);
50
0
}
51
#endif  // WEBP_HAVE_GIF
52
53
10.1k
static int CheckSizeForOverflow(uint64_t size) {
54
10.1k
  return (size == (size_t)size);
55
10.1k
}
56
57
4.58k
static int AllocateFrames(AnimatedImage* const image, uint32_t num_frames) {
58
4.58k
  uint32_t i;
59
4.58k
  uint8_t* mem = NULL;
60
4.58k
  DecodedFrame* frames = NULL;
61
4.58k
  const uint64_t rgba_size =
62
4.58k
      (uint64_t)image->canvas_width * kNumChannels * image->canvas_height;
63
4.58k
  const uint64_t total_size = (uint64_t)num_frames * rgba_size * sizeof(*mem);
64
4.58k
  const uint64_t total_frame_size = (uint64_t)num_frames * sizeof(*frames);
65
4.58k
  if (!CheckSizeForOverflow(total_size) ||
66
4.58k
      !CheckSizeForOverflow(total_frame_size)) {
67
0
    return 0;
68
0
  }
69
4.58k
  mem = (uint8_t*)WebPMalloc((size_t)total_size);
70
4.58k
  frames = (DecodedFrame*)WebPMalloc((size_t)total_frame_size);
71
72
4.58k
  if (mem == NULL || frames == NULL) {
73
21
    WebPFree(mem);
74
21
    WebPFree(frames);
75
21
    return 0;
76
21
  }
77
4.56k
  WebPFree(image->raw_mem);
78
4.56k
  image->num_frames = num_frames;
79
4.56k
  image->frames = frames;
80
9.13k
  for (i = 0; i < num_frames; ++i) {
81
4.56k
    frames[i].rgba = mem + i * rgba_size;
82
4.56k
    frames[i].duration = 0;
83
4.56k
    frames[i].is_key_frame = 0;
84
4.56k
  }
85
4.56k
  image->raw_mem = mem;
86
4.56k
  return 1;
87
4.58k
}
88
89
8.48k
void ClearAnimatedImage(AnimatedImage* const image) {
90
8.48k
  if (image != NULL) {
91
8.48k
    WebPFree(image->raw_mem);
92
8.48k
    WebPFree(image->frames);
93
8.48k
    image->num_frames = 0;
94
8.48k
    image->frames = NULL;
95
8.48k
    image->raw_mem = NULL;
96
8.48k
  }
97
8.48k
}
98
99
WEBP_NODISCARD
100
962
int CheckMultiplicationOverflow(uint32_t val1, uint32_t val2, size_t* product) {
101
962
  const uint64_t size = (uint64_t)val1 * val2;
102
962
  if (CheckSizeForOverflow(size)) {
103
962
    *product = (size_t)size;
104
962
    return 1;
105
962
  }
106
0
  return 0;
107
962
}
108
109
WEBP_NODISCARD
110
0
int CheckAdditionOverflow(size_t val1, uint32_t val2, size_t* addition) {
111
0
  uint64_t size;
112
0
  if (val1 > WEBP_UINT64_MAX - val2) return 0;
113
0
  size = (uint64_t)val1 + val2;
114
0
  if (CheckSizeForOverflow(size)) {
115
0
    *addition = (size_t)size;
116
0
    return 1;
117
0
  }
118
0
  return 0;
119
0
}
120
121
#if defined(WEBP_HAVE_GIF)
122
123
// For the GIF functions below, the width, height, x_offset, y_offset fit on 16
124
// bits (but can fill the 16 bits) as per the GIF specification.
125
// Multiplications that can overflow are cast to 64 bits.
126
127
const uint32_t kGifDimMax = (1 << 16) - 1;
128
129
// Clear the canvas to transparent.
130
WEBP_NODISCARD
131
static int ZeroFillCanvas(uint8_t* rgba, uint32_t canvas_width,
132
0
                          uint32_t canvas_height) {
133
0
  size_t size;
134
0
  assert(canvas_width <= kGifDimMax && canvas_height <= kGifDimMax);
135
0
  if (!CheckMultiplicationOverflow(canvas_width * kNumChannels, canvas_height,
136
0
                                   &size)) {
137
0
    return 0;
138
0
  }
139
0
  memset(rgba, 0, size);
140
0
  return 1;
141
0
}
142
143
// Clear given frame rectangle to transparent.
144
WEBP_NODISCARD
145
static int ZeroFillFrameRect(uint8_t* rgba, uint32_t rgba_stride,
146
                             uint32_t x_offset, uint32_t y_offset,
147
0
                             uint32_t width, uint32_t height) {
148
0
  uint32_t j;
149
0
  size_t size, offset;
150
0
  assert(width <= kGifDimMax && x_offset <= kGifDimMax);
151
0
  assert(width * kNumChannels <= rgba_stride);
152
0
  if (!CheckMultiplicationOverflow(y_offset, rgba_stride, &size) ||
153
0
      !CheckAdditionOverflow(size, x_offset * kNumChannels, &offset)) {
154
0
    return 0;
155
0
  }
156
0
  rgba += offset;
157
0
  for (j = 0; j < height; ++j) {
158
0
    memset(rgba, 0, width * kNumChannels);
159
0
    rgba += rgba_stride;
160
0
  }
161
0
  return 1;
162
0
}
163
164
// Copy width * height pixels from 'src' to 'dst'.
165
WEBP_NODISCARD
166
static int CopyCanvas(const uint8_t* src, uint8_t* dst, uint32_t width,
167
0
                      uint32_t height) {
168
0
  size_t size;
169
0
  assert(width <= kGifDimMax && height <= kGifDimMax);
170
0
  if (!CheckMultiplicationOverflow(width * kNumChannels, height, &size)) {
171
0
    return 0;
172
0
  }
173
0
  assert(src != NULL && dst != NULL);
174
0
  memcpy(dst, src, size);
175
0
  return 1;
176
0
}
177
178
// Copy pixels in the given rectangle from 'src' to 'dst' honoring the 'stride'.
179
static int CopyFrameRectangle(const uint8_t* src, uint8_t* dst, uint32_t stride,
180
                              uint32_t x_offset, uint32_t y_offset,
181
0
                              uint32_t width, uint32_t height) {
182
0
  uint32_t j;
183
0
  const uint32_t width_in_bytes = width * kNumChannels;
184
0
  size_t offset, size;
185
0
  assert(width <= kGifDimMax && x_offset <= kGifDimMax);
186
0
  assert(width_in_bytes <= stride);
187
0
  if (!CheckMultiplicationOverflow(y_offset, stride, &size) ||
188
0
      !CheckAdditionOverflow(size, x_offset * kNumChannels, &offset)) {
189
0
    return 0;
190
0
  }
191
0
  src += offset;
192
0
  dst += offset;
193
0
  for (j = 0; j < height; ++j) {
194
0
    memcpy(dst, src, width_in_bytes);
195
0
    src += stride;
196
0
    dst += stride;
197
0
  }
198
0
  return 1;
199
0
}
200
#endif  // WEBP_HAVE_GIF
201
202
// Canonicalize all transparent pixels to transparent black to aid comparison.
203
static void CleanupTransparentPixels(uint32_t* rgba, uint32_t width,
204
962
                                     uint32_t height) {
205
962
  const uint32_t* const rgba_end = rgba + width * height;
206
19.3M
  while (rgba < rgba_end) {
207
19.3M
    const uint8_t alpha = (*rgba >> 24) & 0xff;
208
19.3M
    if (alpha == 0) {
209
3.02M
      *rgba = 0;
210
3.02M
    }
211
19.3M
    ++rgba;
212
19.3M
  }
213
962
}
214
215
// Dump frame to a PAM file. Returns true on success.
216
static int DumpFrame(const char filename[], const char dump_folder[],
217
                     uint32_t frame_num, const uint8_t rgba[], int canvas_width,
218
0
                     int canvas_height) {
219
0
  int ok = 0;
220
0
  size_t max_len;
221
0
  int y;
222
0
  const W_CHAR* base_name = NULL;
223
0
  W_CHAR* file_name = NULL;
224
0
  FILE* f = NULL;
225
0
  const char* row;
226
227
0
  if (dump_folder == NULL) dump_folder = (const char*)TO_W_CHAR(".");
228
229
0
  base_name = WSTRRCHR(filename, '/');
230
0
  base_name = (base_name == NULL) ? (const W_CHAR*)filename : base_name + 1;
231
0
  max_len = WSTRLEN(dump_folder) + 1 + WSTRLEN(base_name) + strlen("_frame_") +
232
0
            strlen(".pam") + 8;
233
0
  file_name = (W_CHAR*)WebPMalloc(max_len * sizeof(*file_name));
234
0
  if (file_name == NULL) goto End;
235
236
0
  if (WSNPRINTF(file_name, max_len, "%s/%s_frame_%d.pam",
237
0
                (const W_CHAR*)dump_folder, base_name, frame_num) < 0) {
238
0
    fprintf(stderr, "Error while generating file name\n");
239
0
    goto End;
240
0
  }
241
242
0
  f = WFOPEN(file_name, "wb");
243
0
  if (f == NULL) {
244
0
    WFPRINTF(stderr, "Error opening file for writing: %s\n", file_name);
245
0
    ok = 0;
246
0
    goto End;
247
0
  }
248
0
  if (fprintf(f,
249
0
              "P7\nWIDTH %d\nHEIGHT %d\n"
250
0
              "DEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n",
251
0
              canvas_width, canvas_height) < 0) {
252
0
    WFPRINTF(stderr, "Write error for file %s\n", file_name);
253
0
    goto End;
254
0
  }
255
0
  row = (const char*)rgba;
256
0
  for (y = 0; y < canvas_height; ++y) {
257
0
    if (fwrite(row, canvas_width * kNumChannels, 1, f) != 1) {
258
0
      WFPRINTF(stderr, "Error writing to file: %s\n", file_name);
259
0
      goto End;
260
0
    }
261
0
    row += canvas_width * kNumChannels;
262
0
  }
263
0
  ok = 1;
264
0
End:
265
0
  if (f != NULL) fclose(f);
266
0
  WebPFree(file_name);
267
0
  return ok;
268
0
}
269
270
// -----------------------------------------------------------------------------
271
// WebP Decoding.
272
273
// Returns true if this is a valid WebP bitstream.
274
8.48k
static int IsWebP(const WebPData* const webp_data) {
275
8.48k
  return (WebPGetInfo(webp_data->bytes, webp_data->size, NULL, NULL) != 0);
276
8.48k
}
277
278
// Read animated WebP bitstream 'webp_data' into 'AnimatedImage' struct.
279
static int ReadAnimatedWebP(const char filename[],
280
                            const WebPData* const webp_data,
281
                            AnimatedImage* const image, int dump_frames,
282
5.69k
                            const char dump_folder[]) {
283
5.69k
  int ok = 0;
284
5.69k
  int dump_ok = 1;
285
5.69k
  uint32_t frame_index = 0;
286
5.69k
  int prev_frame_timestamp = 0;
287
5.69k
  WebPAnimDecoder* dec;
288
5.69k
  WebPAnimInfo anim_info;
289
290
5.69k
  memset(image, 0, sizeof(*image));
291
292
5.69k
  dec = WebPAnimDecoderNew(webp_data, NULL);
293
5.69k
  if (dec == NULL) {
294
1.10k
    WFPRINTF(stderr, "Error parsing image: %s\n", (const W_CHAR*)filename);
295
1.10k
    goto End;
296
1.10k
  }
297
298
4.58k
  if (!WebPAnimDecoderGetInfo(dec, &anim_info)) {
299
0
    fprintf(stderr, "Error getting global info about the animation\n");
300
0
    goto End;
301
0
  }
302
303
  // Animation properties.
304
4.58k
  image->canvas_width = anim_info.canvas_width;
305
4.58k
  image->canvas_height = anim_info.canvas_height;
306
4.58k
  image->loop_count = anim_info.loop_count;
307
4.58k
  image->bgcolor = anim_info.bgcolor;
308
309
  // Allocate frames.
310
4.58k
  if (!AllocateFrames(image, anim_info.frame_count)) goto End;
311
312
  // Decode frames.
313
5.52k
  while (WebPAnimDecoderHasMoreFrames(dec)) {
314
4.56k
    DecodedFrame* curr_frame;
315
4.56k
    uint8_t* curr_rgba;
316
4.56k
    uint8_t* frame_rgba;
317
4.56k
    int timestamp;
318
4.56k
    size_t size;
319
320
4.56k
    if (!WebPAnimDecoderGetNext(dec, &frame_rgba, &timestamp)) {
321
3.60k
      fprintf(stderr, "Error decoding frame #%u\n", frame_index);
322
3.60k
      goto End;
323
3.60k
    }
324
4.56k
    assert(frame_index < anim_info.frame_count);
325
962
    curr_frame = &image->frames[frame_index];
326
962
    curr_rgba = curr_frame->rgba;
327
962
    curr_frame->duration = timestamp - prev_frame_timestamp;
328
962
    curr_frame->is_key_frame = 0;  // Unused.
329
962
    if (!CheckMultiplicationOverflow(image->canvas_width * kNumChannels,
330
962
                                     image->canvas_height, &size)) {
331
0
      goto End;
332
0
    }
333
962
    memcpy(curr_rgba, frame_rgba, size);
334
335
    // Needed only because we may want to compare with GIF later.
336
962
    CleanupTransparentPixels((uint32_t*)curr_rgba, image->canvas_width,
337
962
                             image->canvas_height);
338
339
962
    if (dump_frames && dump_ok) {
340
0
      dump_ok = DumpFrame(filename, dump_folder, frame_index, curr_rgba,
341
0
                          image->canvas_width, image->canvas_height);
342
0
      if (!dump_ok) {  // Print error once, but continue decode loop.
343
0
        fprintf(stderr, "Error dumping frames to %s\n", dump_folder);
344
0
      }
345
0
    }
346
347
962
    ++frame_index;
348
962
    prev_frame_timestamp = timestamp;
349
962
  }
350
962
  ok = dump_ok;
351
962
  if (ok) image->format = ANIM_WEBP;
352
353
5.69k
End:
354
5.69k
  WebPAnimDecoderDelete(dec);
355
5.69k
  return ok;
356
962
}
357
358
// -----------------------------------------------------------------------------
359
// GIF Decoding.
360
361
#if defined(WEBP_HAVE_GIF)
362
363
typedef struct {
364
  const uint8_t* data;
365
  size_t size;
366
  size_t offset;
367
} GifBufferContext;
368
369
68.7k
static int MemoryReadGIF(GifFileType* gif, GifByteType* dest, int len) {
370
68.7k
  GifBufferContext* const ctx = (GifBufferContext*)gif->UserData;
371
68.7k
  if (ctx->offset + len > ctx->size) {
372
53
    len = (int)(ctx->size - ctx->offset);
373
53
  }
374
68.7k
  if (len > 0) {
375
68.7k
    memcpy(dest, ctx->data + ctx->offset, len);
376
68.7k
    ctx->offset += len;
377
68.7k
  }
378
68.7k
  return len;
379
68.7k
}
380
381
// Returns true if this is a valid GIF bitstream.
382
2.79k
static int IsGIF(const WebPData* const data) {
383
2.79k
  return data->size > GIF_STAMP_LEN &&
384
2.36k
         (!memcmp(GIF_STAMP, data->bytes, GIF_STAMP_LEN) ||
385
2.36k
          !memcmp(GIF87_STAMP, data->bytes, GIF_STAMP_LEN) ||
386
2.31k
          !memcmp(GIF89_STAMP, data->bytes, GIF_STAMP_LEN));
387
2.79k
}
388
389
// GIFLIB_MAJOR is only defined in libgif >= 4.2.0.
390
#if defined(GIFLIB_MAJOR) && defined(GIFLIB_MINOR)
391
#define LOCAL_GIF_VERSION ((GIFLIB_MAJOR << 8) | GIFLIB_MINOR)
392
#define LOCAL_GIF_PREREQ(maj, min) (LOCAL_GIF_VERSION >= (((maj) << 8) | (min)))
393
#else
394
#define LOCAL_GIF_VERSION 0
395
#define LOCAL_GIF_PREREQ(maj, min) 0
396
#endif
397
398
#if !LOCAL_GIF_PREREQ(5, 0)
399
400
// Added in v5.0
401
typedef struct {
402
  int DisposalMode;
403
#define DISPOSAL_UNSPECIFIED 0  // No disposal specified
404
#define DISPOSE_DO_NOT 1        // Leave image in place
405
#define DISPOSE_BACKGROUND 2    // Set area to background color
406
#define DISPOSE_PREVIOUS 3      // Restore to previous content
407
  int UserInputFlag;            // User confirmation required before disposal
408
  int DelayTime;                // Pre-display delay in 0.01sec units
409
  int TransparentColor;         // Palette index for transparency, -1 if none
410
#define NO_TRANSPARENT_COLOR -1
411
} GraphicsControlBlock;
412
413
static int DGifExtensionToGCB(const size_t GifExtensionLength,
414
                              const GifByteType* GifExtension,
415
                              GraphicsControlBlock* gcb) {
416
  if (GifExtensionLength != 4) {
417
    return GIF_ERROR;
418
  }
419
  gcb->DisposalMode = (GifExtension[0] >> 2) & 0x07;
420
  gcb->UserInputFlag = (GifExtension[0] & 0x02) != 0;
421
  gcb->DelayTime = GifExtension[1] | (GifExtension[2] << 8);
422
  if (GifExtension[0] & 0x01) {
423
    gcb->TransparentColor = (int)GifExtension[3];
424
  } else {
425
    gcb->TransparentColor = NO_TRANSPARENT_COLOR;
426
  }
427
  return GIF_OK;
428
}
429
430
static int DGifSavedExtensionToGCB(GifFileType* GifFile, int ImageIndex,
431
                                   GraphicsControlBlock* gcb) {
432
  int i;
433
  if (ImageIndex < 0 || ImageIndex > GifFile->ImageCount - 1) {
434
    return GIF_ERROR;
435
  }
436
  gcb->DisposalMode = DISPOSAL_UNSPECIFIED;
437
  gcb->UserInputFlag = 0;
438
  gcb->DelayTime = 0;
439
  gcb->TransparentColor = NO_TRANSPARENT_COLOR;
440
441
  for (i = 0; i < GifFile->SavedImages[ImageIndex].ExtensionBlockCount; i++) {
442
    ExtensionBlock* ep = &GifFile->SavedImages[ImageIndex].ExtensionBlocks[i];
443
    if (ep->Function == GRAPHICS_EXT_FUNC_CODE) {
444
      return DGifExtensionToGCB(ep->ByteCount, (const GifByteType*)ep->Bytes,
445
                                gcb);
446
    }
447
  }
448
  return GIF_ERROR;
449
}
450
451
#define CONTINUE_EXT_FUNC_CODE 0x00
452
453
// Signature was changed in v5.0
454
#define DGifOpen(a, b, c) DGifOpen(a, b)
455
456
#endif  // !LOCAL_GIF_PREREQ(5, 0)
457
458
// Signature changed in v5.1
459
#if !LOCAL_GIF_PREREQ(5, 1)
460
#define DGifCloseFile(a, b) DGifCloseFile(a)
461
#endif
462
463
static int IsKeyFrameGIF(const GifImageDesc* prev_desc, int prev_dispose,
464
                         const DecodedFrame* const prev_frame, int canvas_width,
465
0
                         int canvas_height) {
466
0
  if (prev_frame == NULL) return 1;
467
0
  if (prev_dispose == DISPOSE_BACKGROUND) {
468
0
    if (IsFullFrame(prev_desc->Width, prev_desc->Height, canvas_width,
469
0
                    canvas_height)) {
470
0
      return 1;
471
0
    }
472
0
    if (prev_frame->is_key_frame) return 1;
473
0
  }
474
0
  return 0;
475
0
}
476
477
0
static int GetTransparentIndexGIF(GifFileType* gif) {
478
0
  GraphicsControlBlock first_gcb;
479
0
  memset(&first_gcb, 0, sizeof(first_gcb));
480
0
  DGifSavedExtensionToGCB(gif, 0, &first_gcb);
481
0
  return first_gcb.TransparentColor;
482
0
}
483
484
0
static uint32_t GetBackgroundColorGIF(GifFileType* gif) {
485
0
  const int transparent_index = GetTransparentIndexGIF(gif);
486
0
  const ColorMapObject* const color_map = gif->SColorMap;
487
0
  if (transparent_index != NO_TRANSPARENT_COLOR &&
488
0
      gif->SBackGroundColor == transparent_index) {
489
0
    return 0x00000000;  // Special case: transparent black.
490
0
  } else if (color_map == NULL || color_map->Colors == NULL ||
491
0
             gif->SBackGroundColor >= color_map->ColorCount) {
492
0
    return 0xffffffff;  // Invalid: assume white.
493
0
  } else {
494
0
    const GifColorType color = color_map->Colors[gif->SBackGroundColor];
495
0
    return (0xffu << 24) | (color.Red << 16) | (color.Green << 8) |
496
0
           (color.Blue << 0);
497
0
  }
498
0
}
499
500
// Find appropriate app extension and get loop count from the next extension.
501
// We use Chrome's interpretation of the 'loop_count' semantics:
502
//   if not present -> loop once
503
//   if present and loop_count == 0, return 0 ('infinite').
504
//   if present and loop_count != 0, it's the number of *extra* loops
505
//     so we need to return loop_count + 1 as total loop number.
506
0
static uint32_t GetLoopCountGIF(const GifFileType* const gif) {
507
0
  int i;
508
0
  for (i = 0; i < gif->ImageCount; ++i) {
509
0
    const SavedImage* const image = &gif->SavedImages[i];
510
0
    int j;
511
0
    for (j = 0; (j + 1) < image->ExtensionBlockCount; ++j) {
512
0
      const ExtensionBlock* const eb1 = image->ExtensionBlocks + j;
513
0
      const ExtensionBlock* const eb2 = image->ExtensionBlocks + j + 1;
514
0
      const char* const signature = (const char*)eb1->Bytes;
515
0
      const int signature_is_ok =
516
0
          (eb1->Function == APPLICATION_EXT_FUNC_CODE) &&
517
0
          (eb1->ByteCount == 11) &&
518
0
          (!memcmp(signature, "NETSCAPE2.0", 11) ||
519
0
           !memcmp(signature, "ANIMEXTS1.0", 11));
520
0
      if (signature_is_ok && eb2->Function == CONTINUE_EXT_FUNC_CODE &&
521
0
          eb2->ByteCount >= 3 && eb2->Bytes[0] == 1) {
522
0
        const uint32_t extra_loop =
523
0
            ((uint32_t)(eb2->Bytes[2]) << 8) + ((uint32_t)(eb2->Bytes[1]) << 0);
524
0
        return (extra_loop > 0) ? extra_loop + 1 : 0;
525
0
      }
526
0
    }
527
0
  }
528
0
  return 1;  // Default.
529
0
}
530
531
// Get duration of 'n'th frame in milliseconds.
532
0
static int GetFrameDurationGIF(GifFileType* gif, int n) {
533
0
  GraphicsControlBlock gcb;
534
0
  memset(&gcb, 0, sizeof(gcb));
535
0
  DGifSavedExtensionToGCB(gif, n, &gcb);
536
0
  return gcb.DelayTime * 10;
537
0
}
538
539
// Returns true if frame 'target' completely covers 'covered'.
540
static int CoversFrameGIF(const GifImageDesc* const target,
541
0
                          const GifImageDesc* const covered) {
542
0
  return target->Left <= covered->Left &&
543
0
         covered->Left + covered->Width <= target->Left + target->Width &&
544
0
         target->Top <= covered->Top &&
545
0
         covered->Top + covered->Height <= target->Top + target->Height;
546
0
}
547
548
WEBP_NODISCARD
549
static int RemapPixelsGIF(const uint8_t* const src,
550
                          const ColorMapObject* const cmap,
551
0
                          int transparent_color, int len, uint8_t* dst) {
552
0
  int i;
553
0
  for (i = 0; i < len; ++i) {
554
0
    if (src[i] != transparent_color) {
555
      // If a pixel in the current frame is transparent, we don't modify it, so
556
      // that we can see-through the corresponding pixel from an earlier frame.
557
0
      GifColorType c;
558
0
      if (src[i] >= cmap->ColorCount) {
559
0
        fprintf(stderr, "Invalid color index: %d\n", src[i]);
560
0
        return 0;
561
0
      }
562
0
      c = cmap->Colors[src[i]];
563
0
      dst[4 * i + 0] = c.Red;
564
0
      dst[4 * i + 1] = c.Green;
565
0
      dst[4 * i + 2] = c.Blue;
566
0
      dst[4 * i + 3] = 0xff;
567
0
    }
568
0
  }
569
0
  return 1;
570
0
}
571
572
WEBP_NODISCARD
573
static int ReadFrameGIF(const SavedImage* const gif_image,
574
                        const ColorMapObject* cmap, int transparent_color,
575
0
                        uint32_t out_stride, uint8_t* const dst) {
576
0
  const GifImageDesc* image_desc = &gif_image->ImageDesc;
577
0
  const uint8_t* in;
578
0
  uint8_t* out;
579
0
  int j;
580
0
  size_t size, offset;
581
582
0
  if (image_desc->ColorMap) cmap = image_desc->ColorMap;
583
584
0
  if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) {
585
0
    fprintf(stderr, "Potentially corrupt color map.\n");
586
0
    return 0;
587
0
  }
588
589
0
  in = (const uint8_t*)gif_image->RasterBits;
590
0
  if (!CheckMultiplicationOverflow(image_desc->Top, out_stride, &size) ||
591
0
      !CheckAdditionOverflow(size, image_desc->Left * kNumChannels, &offset)) {
592
0
    fprintf(stderr, "Invalid image description.\n");
593
0
    return 0;
594
0
  }
595
0
  out = dst + offset;
596
597
0
  for (j = 0; j < image_desc->Height; ++j) {
598
0
    if (!RemapPixelsGIF(in, cmap, transparent_color, image_desc->Width, out)) {
599
0
      return 0;
600
0
    }
601
0
    in += image_desc->Width;
602
0
    out += out_stride;
603
0
  }
604
0
  return 1;
605
0
}
606
607
// Read animated GIF bitstream from 'gif_data' into 'AnimatedImage' struct.
608
static int ReadAnimatedGIF(const char filename[],
609
                           const WebPData* const gif_data,
610
                           AnimatedImage* const image, int dump_frames,
611
82
                           const char dump_folder[]) {
612
82
  uint32_t frame_count;
613
82
  uint32_t canvas_width, canvas_height;
614
82
  uint32_t i;
615
82
  int gif_error;
616
82
  GifFileType* gif;
617
82
  GifBufferContext ctx;
618
619
82
  ctx.data = gif_data->bytes;
620
82
  ctx.size = gif_data->size;
621
82
  ctx.offset = 0;
622
82
  gif = DGifOpen(&ctx, MemoryReadGIF, &gif_error);
623
82
  if (gif == NULL) {
624
28
    WFPRINTF(stderr, "Could not read GIF from memory: %s.\n",
625
28
             (const W_CHAR*)filename);
626
28
    return 0;
627
28
  }
628
629
54
  gif_error = DGifSlurp(gif);
630
54
  if (gif_error != GIF_OK) {
631
54
    WFPRINTF(stderr, "Could not parse image: %s.\n", (const W_CHAR*)filename);
632
54
    GIFDisplayError(gif, gif_error);
633
54
    DGifCloseFile(gif, NULL);
634
54
    return 0;
635
54
  }
636
637
  // Animation properties.
638
0
  image->canvas_width = (uint32_t)gif->SWidth;
639
0
  image->canvas_height = (uint32_t)gif->SHeight;
640
0
  if (image->canvas_width > MAX_CANVAS_SIZE ||
641
0
      image->canvas_height > MAX_CANVAS_SIZE) {
642
0
    fprintf(stderr, "Invalid canvas dimension: %d x %d\n", image->canvas_width,
643
0
            image->canvas_height);
644
0
    DGifCloseFile(gif, NULL);
645
0
    return 0;
646
0
  }
647
0
  image->loop_count = GetLoopCountGIF(gif);
648
0
  image->bgcolor = GetBackgroundColorGIF(gif);
649
650
0
  frame_count = (uint32_t)gif->ImageCount;
651
0
  if (frame_count == 0) {
652
0
    DGifCloseFile(gif, NULL);
653
0
    return 0;
654
0
  }
655
656
0
  if (image->canvas_width == 0 || image->canvas_height == 0) {
657
0
    image->canvas_width = gif->SavedImages[0].ImageDesc.Width;
658
0
    image->canvas_height = gif->SavedImages[0].ImageDesc.Height;
659
0
    gif->SavedImages[0].ImageDesc.Left = 0;
660
0
    gif->SavedImages[0].ImageDesc.Top = 0;
661
0
    if (image->canvas_width == 0 || image->canvas_height == 0) {
662
0
      fprintf(stderr, "Invalid canvas size in GIF.\n");
663
0
      DGifCloseFile(gif, NULL);
664
0
      return 0;
665
0
    }
666
0
  }
667
  // Allocate frames.
668
0
  if (!AllocateFrames(image, frame_count)) {
669
0
    DGifCloseFile(gif, NULL);
670
0
    return 0;
671
0
  }
672
673
0
  canvas_width = image->canvas_width;
674
0
  canvas_height = image->canvas_height;
675
676
  // Decode and reconstruct frames.
677
0
  for (i = 0; i < frame_count; ++i) {
678
0
    const uint32_t canvas_width_in_bytes = canvas_width * kNumChannels;
679
0
    const SavedImage* const curr_gif_image = &gif->SavedImages[i];
680
0
    GraphicsControlBlock curr_gcb;
681
0
    DecodedFrame* curr_frame;
682
0
    uint8_t* curr_rgba;
683
0
    const int left = curr_gif_image->ImageDesc.Left;
684
0
    const int top = curr_gif_image->ImageDesc.Top;
685
0
    const int width = curr_gif_image->ImageDesc.Width;
686
0
    const int height = curr_gif_image->ImageDesc.Height;
687
688
0
    if (left < 0 || top < 0 || width <= 0 || height <= 0 ||
689
0
        (uint32_t)(left + width) > canvas_width ||
690
0
        (uint32_t)(top + height) > canvas_height) {
691
0
      DGifCloseFile(gif, NULL);
692
0
      return 0;
693
0
    }
694
0
    assert((uint32_t)width <= kGifDimMax && (uint32_t)height <= kGifDimMax);
695
696
0
    memset(&curr_gcb, 0, sizeof(curr_gcb));
697
0
    DGifSavedExtensionToGCB(gif, i, &curr_gcb);
698
699
0
    curr_frame = &image->frames[i];
700
0
    curr_rgba = curr_frame->rgba;
701
0
    curr_frame->duration = GetFrameDurationGIF(gif, i);
702
    // Force frames with a small or no duration to 100ms to be consistent
703
    // with web browsers and other transcoding tools (like gif2webp itself).
704
0
    if (curr_frame->duration <= 10) curr_frame->duration = 100;
705
706
0
    if (i == 0) {  // Initialize as transparent.
707
0
      curr_frame->is_key_frame = 1;
708
0
      if (!ZeroFillCanvas(curr_rgba, canvas_width, canvas_height)) {
709
0
        DGifCloseFile(gif, NULL);
710
0
        return 0;
711
0
      }
712
0
    } else {
713
0
      DecodedFrame* const prev_frame = &image->frames[i - 1];
714
0
      const GifImageDesc* const prev_desc = &gif->SavedImages[i - 1].ImageDesc;
715
0
      GraphicsControlBlock prev_gcb;
716
0
      memset(&prev_gcb, 0, sizeof(prev_gcb));
717
0
      DGifSavedExtensionToGCB(gif, i - 1, &prev_gcb);
718
719
0
      curr_frame->is_key_frame =
720
0
          IsKeyFrameGIF(prev_desc, prev_gcb.DisposalMode, prev_frame,
721
0
                        canvas_width, canvas_height);
722
723
0
      if (curr_frame->is_key_frame) {  // Initialize as transparent.
724
0
        if (!ZeroFillCanvas(curr_rgba, canvas_width, canvas_height)) {
725
0
          DGifCloseFile(gif, NULL);
726
0
          return 0;
727
0
        }
728
0
      } else {
729
0
        int prev_frame_disposed, curr_frame_opaque;
730
0
        int prev_frame_completely_covered;
731
        // Initialize with previous canvas.
732
0
        uint8_t* const prev_rgba = image->frames[i - 1].rgba;
733
0
        if (!CopyCanvas(prev_rgba, curr_rgba, canvas_width, canvas_height)) {
734
0
          DGifCloseFile(gif, NULL);
735
0
          return 0;
736
0
        }
737
738
        // Dispose previous frame rectangle.
739
0
        prev_frame_disposed = (prev_gcb.DisposalMode == DISPOSE_BACKGROUND ||
740
0
                               prev_gcb.DisposalMode == DISPOSE_PREVIOUS);
741
0
        curr_frame_opaque = (curr_gcb.TransparentColor == NO_TRANSPARENT_COLOR);
742
0
        prev_frame_completely_covered =
743
0
            curr_frame_opaque &&
744
0
            CoversFrameGIF(&curr_gif_image->ImageDesc, prev_desc);
745
746
0
        if (prev_frame_disposed && !prev_frame_completely_covered) {
747
0
          switch (prev_gcb.DisposalMode) {
748
0
            case DISPOSE_BACKGROUND: {
749
0
              if (!ZeroFillFrameRect(curr_rgba, canvas_width_in_bytes,
750
0
                                     prev_desc->Left, prev_desc->Top,
751
0
                                     prev_desc->Width, prev_desc->Height)) {
752
0
                DGifCloseFile(gif, NULL);
753
0
                return 0;
754
0
              }
755
0
              break;
756
0
            }
757
0
            case DISPOSE_PREVIOUS: {
758
0
              int src_frame_num = i - 2;
759
0
              while (src_frame_num >= 0) {
760
0
                GraphicsControlBlock src_frame_gcb;
761
0
                memset(&src_frame_gcb, 0, sizeof(src_frame_gcb));
762
0
                DGifSavedExtensionToGCB(gif, src_frame_num, &src_frame_gcb);
763
0
                if (src_frame_gcb.DisposalMode != DISPOSE_PREVIOUS) break;
764
0
                --src_frame_num;
765
0
              }
766
0
              if (src_frame_num >= 0) {
767
                // Restore pixels inside previous frame rectangle to
768
                // corresponding pixels in source canvas.
769
0
                uint8_t* const src_frame_rgba =
770
0
                    image->frames[src_frame_num].rgba;
771
0
                if (!CopyFrameRectangle(src_frame_rgba, curr_rgba,
772
0
                                        canvas_width_in_bytes, prev_desc->Left,
773
0
                                        prev_desc->Top, prev_desc->Width,
774
0
                                        prev_desc->Height)) {
775
0
                  DGifCloseFile(gif, NULL);
776
0
                  return 0;
777
0
                }
778
0
              } else {
779
                // Source canvas doesn't exist. So clear previous frame
780
                // rectangle to background.
781
0
                if (!ZeroFillFrameRect(curr_rgba, canvas_width_in_bytes,
782
0
                                       prev_desc->Left, prev_desc->Top,
783
0
                                       prev_desc->Width, prev_desc->Height)) {
784
0
                  DGifCloseFile(gif, NULL);
785
0
                  return 0;
786
0
                }
787
0
              }
788
0
              break;
789
0
            }
790
0
            default:
791
0
              break;  // Nothing to do.
792
0
          }
793
0
        }
794
0
      }
795
0
    }
796
797
    // Decode current frame.
798
0
    if (!ReadFrameGIF(curr_gif_image, gif->SColorMap, curr_gcb.TransparentColor,
799
0
                      canvas_width_in_bytes, curr_rgba)) {
800
0
      DGifCloseFile(gif, NULL);
801
0
      return 0;
802
0
    }
803
804
0
    if (dump_frames) {
805
0
      if (!DumpFrame(filename, dump_folder, i, curr_rgba, canvas_width,
806
0
                     canvas_height)) {
807
0
        DGifCloseFile(gif, NULL);
808
0
        return 0;
809
0
      }
810
0
    }
811
0
  }
812
0
  image->format = ANIM_GIF;
813
0
  DGifCloseFile(gif, NULL);
814
0
  return 1;
815
0
}
816
817
#else
818
819
static int IsGIF(const WebPData* const data) {
820
  (void)data;
821
  return 0;
822
}
823
824
static int ReadAnimatedGIF(const char filename[],
825
                           const WebPData* const gif_data,
826
                           AnimatedImage* const image, int dump_frames,
827
                           const char dump_folder[]) {
828
  (void)filename;
829
  (void)gif_data;
830
  (void)image;
831
  (void)dump_frames;
832
  (void)dump_folder;
833
  fprintf(stderr,
834
          "GIF support not compiled. Please install the libgif-dev "
835
          "package before building.\n");
836
  return 0;
837
}
838
839
#endif  // WEBP_HAVE_GIF
840
841
// -----------------------------------------------------------------------------
842
843
int ReadAnimatedImage(const char filename[], AnimatedImage* const image,
844
0
                      int dump_frames, const char dump_folder[]) {
845
0
  int ok = 0;
846
0
  WebPData webp_data;
847
848
0
  WebPDataInit(&webp_data);
849
850
0
  if (!ImgIoUtilReadFile(filename, &webp_data.bytes, &webp_data.size)) {
851
0
    WFPRINTF(stderr, "Error reading file: %s\n", (const W_CHAR*)filename);
852
0
    return 0;
853
0
  }
854
855
0
  ok = ReadAnimatedImageFromMemory(filename, webp_data.bytes, webp_data.size,
856
0
                                   image, dump_frames, dump_folder);
857
0
  if (!ok) {
858
0
    WFPRINTF(stderr, "Error parsing image: %s\n", (const W_CHAR*)filename);
859
0
  }
860
861
0
  WebPDataClear(&webp_data);
862
0
  return ok;
863
0
}
864
865
int ReadAnimatedImageFromMemory(const char filename[],
866
                                const uint8_t* const data, size_t size,
867
                                AnimatedImage* const image, int dump_frames,
868
8.48k
                                const char dump_folder[]) {
869
8.48k
  int ok = 0;
870
8.48k
  WebPData webp_data;
871
872
8.48k
  webp_data.bytes = data;
873
8.48k
  webp_data.size = size;
874
8.48k
  memset(image, 0, sizeof(*image));
875
876
8.48k
  if (IsWebP(&webp_data)) {
877
5.69k
    ok =
878
5.69k
        ReadAnimatedWebP(filename, &webp_data, image, dump_frames, dump_folder);
879
5.69k
  } else if (IsGIF(&webp_data)) {
880
82
    ok = ReadAnimatedGIF(filename, &webp_data, image, dump_frames, dump_folder);
881
2.70k
  } else {
882
2.70k
    WFPRINTF(stderr,
883
2.70k
             "Unknown file type: %s. Supported file types are WebP and GIF\n",
884
2.70k
             (const W_CHAR*)filename);
885
2.70k
    ok = 0;
886
2.70k
  }
887
8.48k
  if (!ok) ClearAnimatedImage(image);
888
8.48k
  return ok;
889
8.48k
}
890
891
static void Accumulate(double v1, double v2, double* const max_diff,
892
0
                       double* const sse) {
893
0
  const double diff = fabs(v1 - v2);
894
0
  if (diff > *max_diff) *max_diff = diff;
895
0
  *sse += diff * diff;
896
0
}
897
898
void GetDiffAndPSNR(const uint8_t rgba1[], const uint8_t rgba2[],
899
                    uint32_t width, uint32_t height, int premultiply,
900
0
                    int* const max_diff, double* const psnr) {
901
0
  const uint32_t stride = width * kNumChannels;
902
0
  const int kAlphaChannel = kNumChannels - 1;
903
0
  double f_max_diff = 0.;
904
0
  double sse = 0.;
905
0
  uint32_t x, y;
906
0
  for (y = 0; y < height; ++y) {
907
0
    for (x = 0; x < stride; x += kNumChannels) {
908
0
      int k;
909
0
      const size_t offset = (size_t)y * stride + x;
910
0
      const int alpha1 = rgba1[offset + kAlphaChannel];
911
0
      const int alpha2 = rgba2[offset + kAlphaChannel];
912
0
      Accumulate(alpha1, alpha2, &f_max_diff, &sse);
913
0
      if (!premultiply) {
914
0
        for (k = 0; k < kAlphaChannel; ++k) {
915
0
          Accumulate(rgba1[offset + k], rgba2[offset + k], &f_max_diff, &sse);
916
0
        }
917
0
      } else {
918
        // premultiply R/G/B channels with alpha value
919
0
        for (k = 0; k < kAlphaChannel; ++k) {
920
0
          Accumulate(rgba1[offset + k] * alpha1 / 255.,
921
0
                     rgba2[offset + k] * alpha2 / 255., &f_max_diff, &sse);
922
0
        }
923
0
      }
924
0
    }
925
0
  }
926
0
  *max_diff = (int)f_max_diff;
927
0
  if (*max_diff == 0) {
928
0
    *psnr = 99.;  // PSNR when images are identical.
929
0
  } else {
930
0
    sse /= stride * height;
931
0
    assert(sse != 0.0);
932
0
    *psnr = 4.3429448 * log(255. * 255. / sse);
933
0
  }
934
0
}
935
936
void GetAnimatedImageVersions(int* const decoder_version,
937
0
                              int* const demux_version) {
938
0
  *decoder_version = WebPGetDecoderVersion();
939
0
  *demux_version = WebPGetDemuxVersion();
940
0
}