Coverage Report

Created: 2025-10-12 07:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/src/enc/webp_enc.c
Line
Count
Source
1
// Copyright 2011 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
// WebP encoder: main entry point
11
//
12
// Author: Skal (pascal.massimino@gmail.com)
13
14
#include <assert.h>
15
#include <math.h>
16
#include <stdlib.h>
17
#include <string.h>
18
19
#include "src/dec/common_dec.h"
20
#include "src/dsp/dsp.h"
21
#include "src/enc/cost_enc.h"
22
#include "src/enc/vp8i_enc.h"
23
#include "src/enc/vp8li_enc.h"
24
#include "src/utils/utils.h"
25
#include "src/webp/encode.h"
26
#include "src/webp/types.h"
27
28
// #define PRINT_MEMORY_INFO
29
30
#ifdef PRINT_MEMORY_INFO
31
#include <stdio.h>
32
#endif
33
34
//------------------------------------------------------------------------------
35
36
30
int WebPGetEncoderVersion(void) {
37
30
  return (ENC_MAJ_VERSION << 16) | (ENC_MIN_VERSION << 8) | ENC_REV_VERSION;
38
30
}
39
40
//------------------------------------------------------------------------------
41
// VP8Encoder
42
//------------------------------------------------------------------------------
43
44
1.68k
static void ResetSegmentHeader(VP8Encoder* const enc) {
45
1.68k
  VP8EncSegmentHeader* const hdr = &enc->segment_hdr;
46
1.68k
  hdr->num_segments = enc->config->segments;
47
1.68k
  hdr->update_map = (hdr->num_segments > 1);
48
1.68k
  hdr->size = 0;
49
1.68k
}
50
51
1.68k
static void ResetFilterHeader(VP8Encoder* const enc) {
52
1.68k
  VP8EncFilterHeader* const hdr = &enc->filter_hdr;
53
1.68k
  hdr->simple = 1;
54
1.68k
  hdr->level = 0;
55
1.68k
  hdr->sharpness = 0;
56
1.68k
  hdr->i4x4_lf_delta = 0;
57
1.68k
}
58
59
1.68k
static void ResetBoundaryPredictions(VP8Encoder* const enc) {
60
  // init boundary values once for all
61
  // Note: actually, initializing the 'preds[]' is only needed for intra4.
62
1.68k
  int i;
63
1.68k
  uint8_t* const top = enc->preds - enc->preds_w;
64
1.68k
  uint8_t* const left = enc->preds - 1;
65
233k
  for (i = -1; i < 4 * enc->mb_w; ++i) {
66
232k
    top[i] = B_DC_PRED;
67
232k
  }
68
238k
  for (i = 0; i < 4 * enc->mb_h; ++i) {
69
236k
    left[i * enc->preds_w] = B_DC_PRED;
70
236k
  }
71
1.68k
  enc->nz[-1] = 0;  // constant
72
1.68k
}
73
74
// Mapping from config->method to coding tools used.
75
//-------------------+---+---+---+---+---+---+---+
76
//   Method          | 0 | 1 | 2 | 3 |(4)| 5 | 6 |
77
//-------------------+---+---+---+---+---+---+---+
78
// fast probe        | x |   |   | x |   |   |   |
79
//-------------------+---+---+---+---+---+---+---+
80
// dynamic proba     | ~ | x | x | x | x | x | x |
81
//-------------------+---+---+---+---+---+---+---+
82
// fast mode analysis|[x]|[x]|   |   | x | x | x |
83
//-------------------+---+---+---+---+---+---+---+
84
// basic rd-opt      |   |   |   | x | x | x | x |
85
//-------------------+---+---+---+---+---+---+---+
86
// disto-refine i4/16| x | x | x |   |   |   |   |
87
//-------------------+---+---+---+---+---+---+---+
88
// disto-refine uv   |   | x | x |   |   |   |   |
89
//-------------------+---+---+---+---+---+---+---+
90
// rd-opt i4/16      |   |   | ~ | x | x | x | x |
91
//-------------------+---+---+---+---+---+---+---+
92
// token buffer (opt)|   |   |   | x | x | x | x |
93
//-------------------+---+---+---+---+---+---+---+
94
// Trellis           |   |   |   |   |   | x |Ful|
95
//-------------------+---+---+---+---+---+---+---+
96
// full-SNS          |   |   |   |   | x | x | x |
97
//-------------------+---+---+---+---+---+---+---+
98
99
1.68k
static void MapConfigToTools(VP8Encoder* const enc) {
100
1.68k
  const WebPConfig* const config = enc->config;
101
1.68k
  const int method = config->method;
102
1.68k
  const int limit = 100 - config->partition_limit;
103
1.68k
  enc->method = method;
104
1.68k
  enc->rd_opt_level = (method >= 6)   ? RD_OPT_TRELLIS_ALL
105
1.68k
                      : (method >= 5) ? RD_OPT_TRELLIS
106
1.68k
                      : (method >= 3) ? RD_OPT_BASIC
107
1.68k
                                      : RD_OPT_NONE;
108
1.68k
  enc->max_i4_header_bits =
109
1.68k
      256 * 16 * 16 *                 // upper bound: up to 16bit per 4x4 block
110
1.68k
      (limit * limit) / (100 * 100);  // ... modulated with a quadratic curve.
111
112
  // partition0 = 512k max.
113
1.68k
  enc->mb_header_limit =
114
1.68k
      (score_t)256 * 510 * 8 * 1024 / (enc->mb_w * enc->mb_h);
115
116
1.68k
  enc->thread_level = config->thread_level;
117
118
1.68k
  enc->do_search = (config->target_size > 0 || config->target_PSNR > 0);
119
1.68k
  if (!config->low_memory) {
120
1.68k
#if !defined(DISABLE_TOKEN_BUFFER)
121
1.68k
    enc->use_tokens = (enc->rd_opt_level >= RD_OPT_BASIC);  // need rd stats
122
1.68k
#endif
123
1.68k
    if (enc->use_tokens) {
124
1.68k
      enc->num_parts = 1;  // doesn't work with multi-partition
125
1.68k
    }
126
1.68k
  }
127
1.68k
}
128
129
// Memory scaling with dimensions:
130
//  memory (bytes) ~= 2.25 * w + 0.0625 * w * h
131
//
132
// Typical memory footprint (614x440 picture)
133
//              encoder: 22111
134
//                 info: 4368
135
//                preds: 17741
136
//          top samples: 1263
137
//             non-zero: 175
138
//             lf-stats: 0
139
//                total: 45658
140
// Transient object sizes:
141
//       VP8EncIterator: 3360
142
//         VP8ModeScore: 872
143
//       VP8SegmentInfo: 732
144
//          VP8EncProba: 18352
145
//              LFStats: 2048
146
// Picture size (yuv): 419328
147
148
static VP8Encoder* InitVP8Encoder(const WebPConfig* const config,
149
1.68k
                                  WebPPicture* const picture) {
150
1.68k
  VP8Encoder* enc;
151
1.68k
  const int use_filter =
152
1.68k
      (config->filter_strength > 0) || (config->autofilter > 0);
153
1.68k
  const int mb_w = (picture->width + 15) >> 4;
154
1.68k
  const int mb_h = (picture->height + 15) >> 4;
155
1.68k
  const int preds_w = 4 * mb_w + 1;
156
1.68k
  const int preds_h = 4 * mb_h + 1;
157
1.68k
  const size_t preds_size = preds_w * preds_h * sizeof(*enc->preds);
158
1.68k
  const int top_stride = mb_w * 16;
159
1.68k
  const size_t nz_size = (mb_w + 1) * sizeof(*enc->nz) + WEBP_ALIGN_CST;
160
1.68k
  const size_t info_size = mb_w * mb_h * sizeof(*enc->mb_info);
161
1.68k
  const size_t samples_size =
162
1.68k
      2 * top_stride * sizeof(*enc->y_top)  // top-luma/u/v
163
1.68k
      + WEBP_ALIGN_CST;                     // align all
164
1.68k
  const size_t lf_stats_size =
165
1.68k
      config->autofilter ? sizeof(*enc->lf_stats) + WEBP_ALIGN_CST : 0;
166
1.68k
  const size_t top_derr_size =
167
1.68k
      (config->quality <= ERROR_DIFFUSION_QUALITY || config->pass > 1)
168
1.68k
          ? mb_w * sizeof(*enc->top_derr)
169
1.68k
          : 0;
170
1.68k
  uint8_t* mem;
171
1.68k
  const uint64_t size = (uint64_t)sizeof(*enc)  // main struct
172
1.68k
                        + WEBP_ALIGN_CST        // cache alignment
173
1.68k
                        + info_size             // modes info
174
1.68k
                        + preds_size            // prediction modes
175
1.68k
                        + samples_size          // top/left samples
176
1.68k
                        + top_derr_size         // top diffusion error
177
1.68k
                        + nz_size               // coeff context bits
178
1.68k
                        + lf_stats_size;        // autofilter stats
179
180
#ifdef PRINT_MEMORY_INFO
181
  printf("===================================\n");
182
  printf(
183
      "Memory used:\n"
184
      "             encoder: %ld\n"
185
      "                info: %ld\n"
186
      "               preds: %ld\n"
187
      "         top samples: %ld\n"
188
      "       top diffusion: %ld\n"
189
      "            non-zero: %ld\n"
190
      "            lf-stats: %ld\n"
191
      "               total: %ld\n",
192
      sizeof(*enc) + WEBP_ALIGN_CST, info_size, preds_size, samples_size,
193
      top_derr_size, nz_size, lf_stats_size, size);
194
  printf(
195
      "Transient object sizes:\n"
196
      "      VP8EncIterator: %ld\n"
197
      "        VP8ModeScore: %ld\n"
198
      "      VP8SegmentInfo: %ld\n"
199
      "         VP8EncProba: %ld\n"
200
      "             LFStats: %ld\n",
201
      sizeof(VP8EncIterator), sizeof(VP8ModeScore), sizeof(VP8SegmentInfo),
202
      sizeof(VP8EncProba), sizeof(LFStats));
203
  printf("Picture size (yuv): %ld\n", mb_w * mb_h * 384 * sizeof(uint8_t));
204
  printf("===================================\n");
205
#endif
206
1.68k
  mem = (uint8_t*)WebPSafeMalloc(size, sizeof(*mem));
207
1.68k
  if (mem == NULL) {
208
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
209
0
    return NULL;
210
0
  }
211
1.68k
  enc = (VP8Encoder*)mem;
212
1.68k
  mem = (uint8_t*)WEBP_ALIGN(mem + sizeof(*enc));
213
1.68k
  memset(enc, 0, sizeof(*enc));
214
1.68k
  enc->num_parts = 1 << config->partitions;
215
1.68k
  enc->mb_w = mb_w;
216
1.68k
  enc->mb_h = mb_h;
217
1.68k
  enc->preds_w = preds_w;
218
1.68k
  enc->mb_info = (VP8MBInfo*)mem;
219
1.68k
  mem += info_size;
220
1.68k
  enc->preds = mem + 1 + enc->preds_w;
221
1.68k
  mem += preds_size;
222
1.68k
  enc->nz = 1 + (uint32_t*)WEBP_ALIGN(mem);
223
1.68k
  mem += nz_size;
224
1.68k
  enc->lf_stats = lf_stats_size ? (LFStats*)WEBP_ALIGN(mem) : NULL;
225
1.68k
  mem += lf_stats_size;
226
227
  // top samples (all 16-aligned)
228
1.68k
  mem = (uint8_t*)WEBP_ALIGN(mem);
229
1.68k
  enc->y_top = mem;
230
1.68k
  enc->uv_top = enc->y_top + top_stride;
231
1.68k
  mem += 2 * top_stride;
232
1.68k
  enc->top_derr = top_derr_size ? (DError*)mem : NULL;
233
1.68k
  mem += top_derr_size;
234
1.68k
  assert(mem <= (uint8_t*)enc + size);
235
236
1.68k
  enc->config = config;
237
1.68k
  enc->profile = use_filter ? ((config->filter_type == 1) ? 0 : 1) : 2;
238
1.68k
  enc->pic = picture;
239
1.68k
  enc->percent = 0;
240
241
1.68k
  MapConfigToTools(enc);
242
1.68k
  VP8EncDspInit();
243
1.68k
  VP8DefaultProbas(enc);
244
1.68k
  ResetSegmentHeader(enc);
245
1.68k
  ResetFilterHeader(enc);
246
1.68k
  ResetBoundaryPredictions(enc);
247
1.68k
  VP8EncDspCostInit();
248
1.68k
  VP8EncInitAlpha(enc);
249
250
  // lower quality means smaller output -> we modulate a little the page
251
  // size based on quality. This is just a crude 1rst-order prediction.
252
1.68k
  {
253
1.68k
    const float scale = 1.f + config->quality * 5.f / 100.f;  // in [1,6]
254
1.68k
    VP8TBufferInit(&enc->tokens, (int)(mb_w * mb_h * 4 * scale));
255
1.68k
  }
256
1.68k
  return enc;
257
1.68k
}
258
259
1.68k
static int DeleteVP8Encoder(VP8Encoder* enc) {
260
1.68k
  int ok = 1;
261
1.68k
  if (enc != NULL) {
262
1.68k
    ok = VP8EncDeleteAlpha(enc);
263
1.68k
    VP8TBufferClear(&enc->tokens);
264
1.68k
    WebPSafeFree(enc);
265
1.68k
  }
266
1.68k
  return ok;
267
1.68k
}
268
269
//------------------------------------------------------------------------------
270
271
#if !defined(WEBP_DISABLE_STATS)
272
0
static double GetPSNR(uint64_t err, uint64_t size) {
273
0
  return (err > 0 && size > 0) ? 10. * log10(255. * 255. * size / err) : 99.;
274
0
}
275
276
0
static void FinalizePSNR(const VP8Encoder* const enc) {
277
0
  WebPAuxStats* stats = enc->pic->stats;
278
0
  const uint64_t size = enc->sse_count;
279
0
  const uint64_t* const sse = enc->sse;
280
0
  stats->PSNR[0] = (float)GetPSNR(sse[0], size);
281
0
  stats->PSNR[1] = (float)GetPSNR(sse[1], size / 4);
282
0
  stats->PSNR[2] = (float)GetPSNR(sse[2], size / 4);
283
0
  stats->PSNR[3] = (float)GetPSNR(sse[0] + sse[1] + sse[2], size * 3 / 2);
284
0
  stats->PSNR[4] = (float)GetPSNR(sse[3], size);
285
0
}
286
#endif  // !defined(WEBP_DISABLE_STATS)
287
288
1.68k
static void StoreStats(VP8Encoder* const enc) {
289
1.68k
#if !defined(WEBP_DISABLE_STATS)
290
1.68k
  WebPAuxStats* const stats = enc->pic->stats;
291
1.68k
  if (stats != NULL) {
292
0
    int i, s;
293
0
    for (i = 0; i < NUM_MB_SEGMENTS; ++i) {
294
0
      stats->segment_level[i] = enc->dqm[i].fstrength;
295
0
      stats->segment_quant[i] = enc->dqm[i].quant;
296
0
      for (s = 0; s <= 2; ++s) {
297
0
        stats->residual_bytes[s][i] = enc->residual_bytes[s][i];
298
0
      }
299
0
    }
300
0
    FinalizePSNR(enc);
301
0
    stats->coded_size = enc->coded_size;
302
0
    for (i = 0; i < 3; ++i) {
303
0
      stats->block_count[i] = enc->block_count[i];
304
0
    }
305
0
  }
306
#else   // defined(WEBP_DISABLE_STATS)
307
  WebPReportProgress(enc->pic, 100, &enc->percent);  // done!
308
#endif  // !defined(WEBP_DISABLE_STATS)
309
1.68k
}
310
311
int WebPEncodingSetError(const WebPPicture* const pic,
312
7.22k
                         WebPEncodingError error) {
313
7.22k
  assert((int)error < VP8_ENC_ERROR_LAST);
314
7.22k
  assert((int)error >= VP8_ENC_OK);
315
  // The oldest error reported takes precedence over the new one.
316
7.22k
  if (pic->error_code == VP8_ENC_OK) {
317
7.22k
    ((WebPPicture*)pic)->error_code = error;
318
7.22k
  }
319
7.22k
  return 0;
320
7.22k
}
321
322
int WebPReportProgress(const WebPPicture* const pic, int percent,
323
331M
                       int* const percent_store) {
324
331M
  if (percent_store != NULL && percent != *percent_store) {
325
77.1k
    *percent_store = percent;
326
77.1k
    if (pic->progress_hook && !pic->progress_hook(percent, pic)) {
327
      // user abort requested
328
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_USER_ABORT);
329
0
    }
330
77.1k
  }
331
331M
  return 1;  // ok
332
331M
}
333
//------------------------------------------------------------------------------
334
335
2.55k
int WebPEncode(const WebPConfig* config, WebPPicture* pic) {
336
2.55k
  int ok = 0;
337
2.55k
  if (pic == NULL) return 0;
338
339
2.55k
  pic->error_code = VP8_ENC_OK;  // all ok so far
340
2.55k
  if (config == NULL) {          // bad params
341
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_NULL_PARAMETER);
342
0
  }
343
2.55k
  if (!WebPValidateConfig(config)) {
344
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);
345
0
  }
346
2.55k
  if (!WebPValidatePicture(pic)) return 0;
347
2.55k
  if (pic->width > WEBP_MAX_DIMENSION || pic->height > WEBP_MAX_DIMENSION) {
348
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);
349
0
  }
350
351
2.55k
  if (pic->stats != NULL) memset(pic->stats, 0, sizeof(*pic->stats));
352
353
2.55k
  if (!config->lossless) {
354
1.68k
    VP8Encoder* enc = NULL;
355
356
1.68k
    if (pic->use_argb || pic->y == NULL || pic->u == NULL || pic->v == NULL) {
357
      // Make sure we have YUVA samples.
358
1.68k
      if (config->use_sharp_yuv || (config->preprocessing & 4)) {
359
0
        if (!WebPPictureSharpARGBToYUVA(pic)) {
360
0
          return 0;
361
0
        }
362
1.68k
      } else {
363
1.68k
        float dithering = 0.f;
364
1.68k
        if (config->preprocessing & 2) {
365
0
          const float x = config->quality / 100.f;
366
0
          const float x2 = x * x;
367
          // slowly decreasing from max dithering at low quality (q->0)
368
          // to 0.5 dithering amplitude at high quality (q->100)
369
0
          dithering = 1.0f + (0.5f - 1.0f) * x2 * x2;
370
0
        }
371
1.68k
        if (!WebPPictureARGBToYUVADithered(pic, WEBP_YUV420, dithering)) {
372
0
          return 0;
373
0
        }
374
1.68k
      }
375
1.68k
    }
376
377
1.68k
    if (!config->exact) {
378
1.68k
      WebPCleanupTransparentArea(pic);
379
1.68k
    }
380
381
1.68k
    enc = InitVP8Encoder(config, pic);
382
1.68k
    if (enc == NULL) return 0;  // pic->error is already set.
383
    // Note: each of the tasks below account for 20% in the progress report.
384
1.68k
    ok = VP8EncAnalyze(enc);
385
386
    // Analysis is done, proceed to actual coding.
387
1.68k
    ok = ok && VP8EncStartAlpha(enc);  // possibly done in parallel
388
1.68k
    if (!enc->use_tokens) {
389
0
      ok = ok && VP8EncLoop(enc);
390
1.68k
    } else {
391
1.68k
      ok = ok && VP8EncTokenLoop(enc);
392
1.68k
    }
393
1.68k
    ok = ok && VP8EncFinishAlpha(enc);
394
395
1.68k
    ok = ok && VP8EncWrite(enc);
396
1.68k
    StoreStats(enc);
397
1.68k
    if (!ok) {
398
0
      VP8EncFreeBitWriters(enc);
399
0
    }
400
1.68k
    ok &= DeleteVP8Encoder(enc);  // must always be called, even if !ok
401
1.68k
  } else {
402
    // Make sure we have ARGB samples.
403
873
    if (pic->argb == NULL && !WebPPictureYUVAToARGB(pic)) {
404
0
      return 0;
405
0
    }
406
407
873
    if (!config->exact) {
408
873
      WebPReplaceTransparentPixels(pic, 0x000000);
409
873
    }
410
411
873
    ok = VP8LEncodeImage(config, pic);  // Sets pic->error in case of problem.
412
873
  }
413
414
2.55k
  return ok;
415
2.55k
}