Coverage Report

Created: 2025-06-13 06:48

/src/libwebp/src/enc/vp8l_enc.c
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2012 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
// main entry for the lossless encoder.
11
//
12
// Author: Vikas Arora (vikaas.arora@gmail.com)
13
//
14
15
#include <assert.h>
16
#include <stdlib.h>
17
#include <string.h>
18
19
#include "src/dsp/lossless.h"
20
#include "src/dsp/lossless_common.h"
21
#include "src/enc/backward_references_enc.h"
22
#include "src/enc/histogram_enc.h"
23
#include "src/enc/vp8i_enc.h"
24
#include "src/enc/vp8li_enc.h"
25
#include "src/utils/bit_writer_utils.h"
26
#include "src/utils/huffman_encode_utils.h"
27
#include "src/utils/palette.h"
28
#include "src/utils/thread_utils.h"
29
#include "src/utils/utils.h"
30
#include "src/webp/encode.h"
31
#include "src/webp/format_constants.h"
32
#include "src/webp/types.h"
33
34
// Maximum number of histogram images (sub-blocks).
35
0
#define MAX_HUFF_IMAGE_SIZE       2600
36
0
#define MAX_HUFFMAN_BITS (MIN_HUFFMAN_BITS + (1 << NUM_HUFFMAN_BITS) - 1)
37
// Empirical value for which it becomes too computationally expensive to
38
// compute the best predictor image.
39
0
#define MAX_PREDICTOR_IMAGE_SIZE (1 << 14)
40
41
// -----------------------------------------------------------------------------
42
// Palette
43
44
// These five modes are evaluated and their respective entropy is computed.
45
typedef enum {
46
  kDirect = 0,
47
  kSpatial = 1,
48
  kSubGreen = 2,
49
  kSpatialSubGreen = 3,
50
  kPalette = 4,
51
  kPaletteAndSpatial = 5,
52
  kNumEntropyIx = 6
53
} EntropyIx;
54
55
typedef enum {
56
  kHistoAlpha = 0,
57
  kHistoAlphaPred,
58
  kHistoGreen,
59
  kHistoGreenPred,
60
  kHistoRed,
61
  kHistoRedPred,
62
  kHistoBlue,
63
  kHistoBluePred,
64
  kHistoRedSubGreen,
65
  kHistoRedPredSubGreen,
66
  kHistoBlueSubGreen,
67
  kHistoBluePredSubGreen,
68
  kHistoPalette,
69
  kHistoTotal  // Must be last.
70
} HistoIx;
71
72
static void AddSingleSubGreen(uint32_t p,
73
0
                              uint32_t* const r, uint32_t* const b) {
74
0
  const int green = (int)p >> 8;  // The upper bits are masked away later.
75
0
  ++r[(((int)p >> 16) - green) & 0xff];
76
0
  ++b[(((int)p >>  0) - green) & 0xff];
77
0
}
78
79
static void AddSingle(uint32_t p,
80
                      uint32_t* const a, uint32_t* const r,
81
0
                      uint32_t* const g, uint32_t* const b) {
82
0
  ++a[(p >> 24) & 0xff];
83
0
  ++r[(p >> 16) & 0xff];
84
0
  ++g[(p >>  8) & 0xff];
85
0
  ++b[(p >>  0) & 0xff];
86
0
}
87
88
0
static WEBP_INLINE uint32_t HashPix(uint32_t pix) {
89
  // Note that masking with 0xffffffffu is for preventing an
90
  // 'unsigned int overflow' warning. Doesn't impact the compiled code.
91
0
  return ((((uint64_t)pix + (pix >> 19)) * 0x39c5fba7ull) & 0xffffffffu) >> 24;
92
0
}
93
94
static int AnalyzeEntropy(const uint32_t* argb,
95
                          int width, int height, int argb_stride,
96
                          int use_palette,
97
                          int palette_size, int transform_bits,
98
                          EntropyIx* const min_entropy_ix,
99
0
                          int* const red_and_blue_always_zero) {
100
  // Allocate histogram set with cache_bits = 0.
101
0
  uint32_t* histo;
102
103
0
  if (use_palette && palette_size <= 16) {
104
    // In the case of small palettes, we pack 2, 4 or 8 pixels together. In
105
    // practice, small palettes are better than any other transform.
106
0
    *min_entropy_ix = kPalette;
107
0
    *red_and_blue_always_zero = 1;
108
0
    return 1;
109
0
  }
110
0
  histo = (uint32_t*)WebPSafeCalloc(kHistoTotal, sizeof(*histo) * 256);
111
0
  if (histo != NULL) {
112
0
    int i, x, y;
113
0
    const uint32_t* prev_row = NULL;
114
0
    const uint32_t* curr_row = argb;
115
0
    uint32_t pix_prev = argb[0];  // Skip the first pixel.
116
0
    for (y = 0; y < height; ++y) {
117
0
      for (x = 0; x < width; ++x) {
118
0
        const uint32_t pix = curr_row[x];
119
0
        const uint32_t pix_diff = VP8LSubPixels(pix, pix_prev);
120
0
        pix_prev = pix;
121
0
        if ((pix_diff == 0) || (prev_row != NULL && pix == prev_row[x])) {
122
0
          continue;
123
0
        }
124
0
        AddSingle(pix,
125
0
                  &histo[kHistoAlpha * 256],
126
0
                  &histo[kHistoRed * 256],
127
0
                  &histo[kHistoGreen * 256],
128
0
                  &histo[kHistoBlue * 256]);
129
0
        AddSingle(pix_diff,
130
0
                  &histo[kHistoAlphaPred * 256],
131
0
                  &histo[kHistoRedPred * 256],
132
0
                  &histo[kHistoGreenPred * 256],
133
0
                  &histo[kHistoBluePred * 256]);
134
0
        AddSingleSubGreen(pix,
135
0
                          &histo[kHistoRedSubGreen * 256],
136
0
                          &histo[kHistoBlueSubGreen * 256]);
137
0
        AddSingleSubGreen(pix_diff,
138
0
                          &histo[kHistoRedPredSubGreen * 256],
139
0
                          &histo[kHistoBluePredSubGreen * 256]);
140
0
        {
141
          // Approximate the palette by the entropy of the multiplicative hash.
142
0
          const uint32_t hash = HashPix(pix);
143
0
          ++histo[kHistoPalette * 256 + hash];
144
0
        }
145
0
      }
146
0
      prev_row = curr_row;
147
0
      curr_row += argb_stride;
148
0
    }
149
0
    {
150
0
      uint64_t entropy_comp[kHistoTotal];
151
0
      uint64_t entropy[kNumEntropyIx];
152
0
      int k;
153
0
      int last_mode_to_analyze = use_palette ? kPalette : kSpatialSubGreen;
154
0
      int j;
155
      // Let's add one zero to the predicted histograms. The zeros are removed
156
      // too efficiently by the pix_diff == 0 comparison, at least one of the
157
      // zeros is likely to exist.
158
0
      ++histo[kHistoRedPredSubGreen * 256];
159
0
      ++histo[kHistoBluePredSubGreen * 256];
160
0
      ++histo[kHistoRedPred * 256];
161
0
      ++histo[kHistoGreenPred * 256];
162
0
      ++histo[kHistoBluePred * 256];
163
0
      ++histo[kHistoAlphaPred * 256];
164
165
0
      for (j = 0; j < kHistoTotal; ++j) {
166
0
        entropy_comp[j] = VP8LBitsEntropy(&histo[j * 256], 256);
167
0
      }
168
0
      entropy[kDirect] = entropy_comp[kHistoAlpha] +
169
0
          entropy_comp[kHistoRed] +
170
0
          entropy_comp[kHistoGreen] +
171
0
          entropy_comp[kHistoBlue];
172
0
      entropy[kSpatial] = entropy_comp[kHistoAlphaPred] +
173
0
          entropy_comp[kHistoRedPred] +
174
0
          entropy_comp[kHistoGreenPred] +
175
0
          entropy_comp[kHistoBluePred];
176
0
      entropy[kSubGreen] = entropy_comp[kHistoAlpha] +
177
0
          entropy_comp[kHistoRedSubGreen] +
178
0
          entropy_comp[kHistoGreen] +
179
0
          entropy_comp[kHistoBlueSubGreen];
180
0
      entropy[kSpatialSubGreen] = entropy_comp[kHistoAlphaPred] +
181
0
          entropy_comp[kHistoRedPredSubGreen] +
182
0
          entropy_comp[kHistoGreenPred] +
183
0
          entropy_comp[kHistoBluePredSubGreen];
184
0
      entropy[kPalette] = entropy_comp[kHistoPalette];
185
186
      // When including transforms, there is an overhead in bits from
187
      // storing them. This overhead is small but matters for small images.
188
      // For spatial, there are 14 transformations.
189
0
      entropy[kSpatial] += (uint64_t)VP8LSubSampleSize(width, transform_bits) *
190
0
                           VP8LSubSampleSize(height, transform_bits) *
191
0
                           VP8LFastLog2(14);
192
      // For color transforms: 24 as only 3 channels are considered in a
193
      // ColorTransformElement.
194
0
      entropy[kSpatialSubGreen] +=
195
0
          (uint64_t)VP8LSubSampleSize(width, transform_bits) *
196
0
          VP8LSubSampleSize(height, transform_bits) * VP8LFastLog2(24);
197
      // For palettes, add the cost of storing the palette.
198
      // We empirically estimate the cost of a compressed entry as 8 bits.
199
      // The palette is differential-coded when compressed hence a much
200
      // lower cost than sizeof(uint32_t)*8.
201
0
      entropy[kPalette] += (palette_size * 8ull) << LOG_2_PRECISION_BITS;
202
203
0
      *min_entropy_ix = kDirect;
204
0
      for (k = kDirect + 1; k <= last_mode_to_analyze; ++k) {
205
0
        if (entropy[*min_entropy_ix] > entropy[k]) {
206
0
          *min_entropy_ix = (EntropyIx)k;
207
0
        }
208
0
      }
209
0
      assert((int)*min_entropy_ix <= last_mode_to_analyze);
210
0
      *red_and_blue_always_zero = 1;
211
      // Let's check if the histogram of the chosen entropy mode has
212
      // non-zero red and blue values. If all are zero, we can later skip
213
      // the cross color optimization.
214
0
      {
215
0
        static const uint8_t kHistoPairs[5][2] = {
216
0
          { kHistoRed, kHistoBlue },
217
0
          { kHistoRedPred, kHistoBluePred },
218
0
          { kHistoRedSubGreen, kHistoBlueSubGreen },
219
0
          { kHistoRedPredSubGreen, kHistoBluePredSubGreen },
220
0
          { kHistoRed, kHistoBlue }
221
0
        };
222
0
        const uint32_t* const red_histo =
223
0
            &histo[256 * kHistoPairs[*min_entropy_ix][0]];
224
0
        const uint32_t* const blue_histo =
225
0
            &histo[256 * kHistoPairs[*min_entropy_ix][1]];
226
0
        for (i = 1; i < 256; ++i) {
227
0
          if ((red_histo[i] | blue_histo[i]) != 0) {
228
0
            *red_and_blue_always_zero = 0;
229
0
            break;
230
0
          }
231
0
        }
232
0
      }
233
0
    }
234
0
    WebPSafeFree(histo);
235
0
    return 1;
236
0
  } else {
237
0
    return 0;
238
0
  }
239
0
}
240
241
// Clamp histogram and transform bits.
242
static int ClampBits(int width, int height, int bits, int min_bits,
243
0
                     int max_bits, int image_size_max) {
244
0
  int image_size;
245
0
  bits = (bits < min_bits) ? min_bits : (bits > max_bits) ? max_bits : bits;
246
0
  image_size = VP8LSubSampleSize(width, bits) * VP8LSubSampleSize(height, bits);
247
0
  while (bits < max_bits && image_size > image_size_max) {
248
0
    ++bits;
249
0
    image_size =
250
0
        VP8LSubSampleSize(width, bits) * VP8LSubSampleSize(height, bits);
251
0
  }
252
  // In case the bits reduce the image too much, choose the smallest value
253
  // setting the histogram image size to 1.
254
0
  while (bits > min_bits && image_size == 1) {
255
0
    image_size = VP8LSubSampleSize(width, bits - 1) *
256
0
                 VP8LSubSampleSize(height, bits - 1);
257
0
    if (image_size != 1) break;
258
0
    --bits;
259
0
  }
260
0
  return bits;
261
0
}
262
263
0
static int GetHistoBits(int method, int use_palette, int width, int height) {
264
  // Make tile size a function of encoding method (Range: 0 to 6).
265
0
  const int histo_bits = (use_palette ? 9 : 7) - method;
266
0
  return ClampBits(width, height, histo_bits, MIN_HUFFMAN_BITS,
267
0
                   MAX_HUFFMAN_BITS, MAX_HUFF_IMAGE_SIZE);
268
0
}
269
270
0
static int GetTransformBits(int method, int histo_bits) {
271
0
  const int max_transform_bits = (method < 4) ? 6 : (method > 4) ? 4 : 5;
272
0
  const int res =
273
0
      (histo_bits > max_transform_bits) ? max_transform_bits : histo_bits;
274
0
  assert(res <= MAX_TRANSFORM_BITS);
275
0
  return res;
276
0
}
277
278
// Set of parameters to be used in each iteration of the cruncher.
279
#define CRUNCH_SUBCONFIGS_MAX 2
280
typedef struct {
281
  int lz77;
282
  int do_no_cache;
283
} CrunchSubConfig;
284
typedef struct {
285
  int entropy_idx;
286
  PaletteSorting palette_sorting_type;
287
  CrunchSubConfig sub_configs[CRUNCH_SUBCONFIGS_MAX];
288
  int sub_configs_size;
289
} CrunchConfig;
290
291
// +2 because we add a palette sorting configuration for kPalette and
292
// kPaletteAndSpatial.
293
#define CRUNCH_CONFIGS_MAX (kNumEntropyIx + 2 * kPaletteSortingNum)
294
295
static int EncoderAnalyze(VP8LEncoder* const enc,
296
                          CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX],
297
                          int* const crunch_configs_size,
298
0
                          int* const red_and_blue_always_zero) {
299
0
  const WebPPicture* const pic = enc->pic;
300
0
  const int width = pic->width;
301
0
  const int height = pic->height;
302
0
  const WebPConfig* const config = enc->config;
303
0
  const int method = config->method;
304
0
  const int low_effort = (config->method == 0);
305
0
  int i;
306
0
  int use_palette, transform_bits;
307
0
  int n_lz77s;
308
  // If set to 0, analyze the cache with the computed cache value. If 1, also
309
  // analyze with no-cache.
310
0
  int do_no_cache = 0;
311
0
  assert(pic != NULL && pic->argb != NULL);
312
313
  // Check whether a palette is possible.
314
0
  enc->palette_size = GetColorPalette(pic, enc->palette_sorted);
315
0
  use_palette = (enc->palette_size <= MAX_PALETTE_SIZE);
316
0
  if (!use_palette) {
317
0
    enc->palette_size = 0;
318
0
  }
319
320
  // Empirical bit sizes.
321
0
  enc->histo_bits = GetHistoBits(method, use_palette,
322
0
                                 pic->width, pic->height);
323
0
  transform_bits = GetTransformBits(method, enc->histo_bits);
324
0
  enc->predictor_transform_bits = transform_bits;
325
0
  enc->cross_color_transform_bits = transform_bits;
326
327
0
  if (low_effort) {
328
    // AnalyzeEntropy is somewhat slow.
329
0
    crunch_configs[0].entropy_idx = use_palette ? kPalette : kSpatialSubGreen;
330
0
    crunch_configs[0].palette_sorting_type =
331
0
        use_palette ? kSortedDefault : kUnusedPalette;
332
0
    n_lz77s = 1;
333
0
    *crunch_configs_size = 1;
334
0
  } else {
335
0
    EntropyIx min_entropy_ix;
336
    // Try out multiple LZ77 on images with few colors.
337
0
    n_lz77s = (enc->palette_size > 0 && enc->palette_size <= 16) ? 2 : 1;
338
0
    if (!AnalyzeEntropy(pic->argb, width, height, pic->argb_stride, use_palette,
339
0
                        enc->palette_size, transform_bits, &min_entropy_ix,
340
0
                        red_and_blue_always_zero)) {
341
0
      return 0;
342
0
    }
343
0
    if (method == 6 && config->quality == 100) {
344
0
      do_no_cache = 1;
345
      // Go brute force on all transforms.
346
0
      *crunch_configs_size = 0;
347
0
      for (i = 0; i < kNumEntropyIx; ++i) {
348
        // We can only apply kPalette or kPaletteAndSpatial if we can indeed use
349
        // a palette.
350
0
        if ((i != kPalette && i != kPaletteAndSpatial) || use_palette) {
351
0
          assert(*crunch_configs_size < CRUNCH_CONFIGS_MAX);
352
0
          if (use_palette && (i == kPalette || i == kPaletteAndSpatial)) {
353
0
            int sorting_method;
354
0
            for (sorting_method = 0; sorting_method < kPaletteSortingNum;
355
0
                 ++sorting_method) {
356
0
              const PaletteSorting typed_sorting_method =
357
0
                  (PaletteSorting)sorting_method;
358
              // TODO(vrabaud) kSortedDefault should be tested. It is omitted
359
              // for now for backward compatibility.
360
0
              if (typed_sorting_method == kUnusedPalette ||
361
0
                  typed_sorting_method == kSortedDefault) {
362
0
                continue;
363
0
              }
364
0
              crunch_configs[(*crunch_configs_size)].entropy_idx = i;
365
0
              crunch_configs[(*crunch_configs_size)].palette_sorting_type =
366
0
                  typed_sorting_method;
367
0
              ++*crunch_configs_size;
368
0
            }
369
0
          } else {
370
0
            crunch_configs[(*crunch_configs_size)].entropy_idx = i;
371
0
            crunch_configs[(*crunch_configs_size)].palette_sorting_type =
372
0
                kUnusedPalette;
373
0
            ++*crunch_configs_size;
374
0
          }
375
0
        }
376
0
      }
377
0
    } else {
378
      // Only choose the guessed best transform.
379
0
      *crunch_configs_size = 1;
380
0
      crunch_configs[0].entropy_idx = min_entropy_ix;
381
0
      crunch_configs[0].palette_sorting_type =
382
0
          use_palette ? kMinimizeDelta : kUnusedPalette;
383
0
      if (config->quality >= 75 && method == 5) {
384
        // Test with and without color cache.
385
0
        do_no_cache = 1;
386
        // If we have a palette, also check in combination with spatial.
387
0
        if (min_entropy_ix == kPalette) {
388
0
          *crunch_configs_size = 2;
389
0
          crunch_configs[1].entropy_idx = kPaletteAndSpatial;
390
0
          crunch_configs[1].palette_sorting_type = kMinimizeDelta;
391
0
        }
392
0
      }
393
0
    }
394
0
  }
395
  // Fill in the different LZ77s.
396
0
  assert(n_lz77s <= CRUNCH_SUBCONFIGS_MAX);
397
0
  for (i = 0; i < *crunch_configs_size; ++i) {
398
0
    int j;
399
0
    for (j = 0; j < n_lz77s; ++j) {
400
0
      assert(j < CRUNCH_SUBCONFIGS_MAX);
401
0
      crunch_configs[i].sub_configs[j].lz77 =
402
0
          (j == 0) ? kLZ77Standard | kLZ77RLE : kLZ77Box;
403
0
      crunch_configs[i].sub_configs[j].do_no_cache = do_no_cache;
404
0
    }
405
0
    crunch_configs[i].sub_configs_size = n_lz77s;
406
0
  }
407
0
  return 1;
408
0
}
409
410
0
static int EncoderInit(VP8LEncoder* const enc) {
411
0
  const WebPPicture* const pic = enc->pic;
412
0
  const int width = pic->width;
413
0
  const int height = pic->height;
414
0
  const int pix_cnt = width * height;
415
  // we round the block size up, so we're guaranteed to have
416
  // at most MAX_REFS_BLOCK_PER_IMAGE blocks used:
417
0
  const int refs_block_size = (pix_cnt - 1) / MAX_REFS_BLOCK_PER_IMAGE + 1;
418
0
  int i;
419
0
  if (!VP8LHashChainInit(&enc->hash_chain, pix_cnt)) return 0;
420
421
0
  for (i = 0; i < 4; ++i) VP8LBackwardRefsInit(&enc->refs[i], refs_block_size);
422
423
0
  return 1;
424
0
}
425
426
// Returns false in case of memory error.
427
static int GetHuffBitLengthsAndCodes(
428
    const VP8LHistogramSet* const histogram_image,
429
0
    HuffmanTreeCode* const huffman_codes) {
430
0
  int i, k;
431
0
  int ok = 0;
432
0
  uint64_t total_length_size = 0;
433
0
  uint8_t* mem_buf = NULL;
434
0
  const int histogram_image_size = histogram_image->size;
435
0
  int max_num_symbols = 0;
436
0
  uint8_t* buf_rle = NULL;
437
0
  HuffmanTree* huff_tree = NULL;
438
439
  // Iterate over all histograms and get the aggregate number of codes used.
440
0
  for (i = 0; i < histogram_image_size; ++i) {
441
0
    const VP8LHistogram* const histo = histogram_image->histograms[i];
442
0
    HuffmanTreeCode* const codes = &huffman_codes[5 * i];
443
0
    assert(histo != NULL);
444
0
    for (k = 0; k < 5; ++k) {
445
0
      const int num_symbols =
446
0
          (k == 0) ? VP8LHistogramNumCodes(histo->palette_code_bits) :
447
0
          (k == 4) ? NUM_DISTANCE_CODES : 256;
448
0
      codes[k].num_symbols = num_symbols;
449
0
      total_length_size += num_symbols;
450
0
    }
451
0
  }
452
453
  // Allocate and Set Huffman codes.
454
0
  {
455
0
    uint16_t* codes;
456
0
    uint8_t* lengths;
457
0
    mem_buf = (uint8_t*)WebPSafeCalloc(total_length_size,
458
0
                                       sizeof(*lengths) + sizeof(*codes));
459
0
    if (mem_buf == NULL) goto End;
460
461
0
    codes = (uint16_t*)mem_buf;
462
0
    lengths = (uint8_t*)&codes[total_length_size];
463
0
    for (i = 0; i < 5 * histogram_image_size; ++i) {
464
0
      const int bit_length = huffman_codes[i].num_symbols;
465
0
      huffman_codes[i].codes = codes;
466
0
      huffman_codes[i].code_lengths = lengths;
467
0
      codes += bit_length;
468
0
      lengths += bit_length;
469
0
      if (max_num_symbols < bit_length) {
470
0
        max_num_symbols = bit_length;
471
0
      }
472
0
    }
473
0
  }
474
475
0
  buf_rle = (uint8_t*)WebPSafeMalloc(1ULL, max_num_symbols);
476
0
  huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * max_num_symbols,
477
0
                                           sizeof(*huff_tree));
478
0
  if (buf_rle == NULL || huff_tree == NULL) goto End;
479
480
  // Create Huffman trees.
481
0
  for (i = 0; i < histogram_image_size; ++i) {
482
0
    HuffmanTreeCode* const codes = &huffman_codes[5 * i];
483
0
    VP8LHistogram* const histo = histogram_image->histograms[i];
484
0
    VP8LCreateHuffmanTree(histo->literal, 15, buf_rle, huff_tree, codes + 0);
485
0
    VP8LCreateHuffmanTree(histo->red, 15, buf_rle, huff_tree, codes + 1);
486
0
    VP8LCreateHuffmanTree(histo->blue, 15, buf_rle, huff_tree, codes + 2);
487
0
    VP8LCreateHuffmanTree(histo->alpha, 15, buf_rle, huff_tree, codes + 3);
488
0
    VP8LCreateHuffmanTree(histo->distance, 15, buf_rle, huff_tree, codes + 4);
489
0
  }
490
0
  ok = 1;
491
0
 End:
492
0
  WebPSafeFree(huff_tree);
493
0
  WebPSafeFree(buf_rle);
494
0
  if (!ok) {
495
0
    WebPSafeFree(mem_buf);
496
0
    memset(huffman_codes, 0, 5 * histogram_image_size * sizeof(*huffman_codes));
497
0
  }
498
0
  return ok;
499
0
}
500
501
static void StoreHuffmanTreeOfHuffmanTreeToBitMask(
502
0
    VP8LBitWriter* const bw, const uint8_t* code_length_bitdepth) {
503
  // RFC 1951 will calm you down if you are worried about this funny sequence.
504
  // This sequence is tuned from that, but more weighted for lower symbol count,
505
  // and more spiking histograms.
506
0
  static const uint8_t kStorageOrder[CODE_LENGTH_CODES] = {
507
0
    17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
508
0
  };
509
0
  int i;
510
  // Throw away trailing zeros:
511
0
  int codes_to_store = CODE_LENGTH_CODES;
512
0
  for (; codes_to_store > 4; --codes_to_store) {
513
0
    if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {
514
0
      break;
515
0
    }
516
0
  }
517
0
  VP8LPutBits(bw, codes_to_store - 4, 4);
518
0
  for (i = 0; i < codes_to_store; ++i) {
519
0
    VP8LPutBits(bw, code_length_bitdepth[kStorageOrder[i]], 3);
520
0
  }
521
0
}
522
523
static void ClearHuffmanTreeIfOnlyOneSymbol(
524
0
    HuffmanTreeCode* const huffman_code) {
525
0
  int k;
526
0
  int count = 0;
527
0
  for (k = 0; k < huffman_code->num_symbols; ++k) {
528
0
    if (huffman_code->code_lengths[k] != 0) {
529
0
      ++count;
530
0
      if (count > 1) return;
531
0
    }
532
0
  }
533
0
  for (k = 0; k < huffman_code->num_symbols; ++k) {
534
0
    huffman_code->code_lengths[k] = 0;
535
0
    huffman_code->codes[k] = 0;
536
0
  }
537
0
}
538
539
static void StoreHuffmanTreeToBitMask(
540
    VP8LBitWriter* const bw,
541
    const HuffmanTreeToken* const tokens, const int num_tokens,
542
0
    const HuffmanTreeCode* const huffman_code) {
543
0
  int i;
544
0
  for (i = 0; i < num_tokens; ++i) {
545
0
    const int ix = tokens[i].code;
546
0
    const int extra_bits = tokens[i].extra_bits;
547
0
    VP8LPutBits(bw, huffman_code->codes[ix], huffman_code->code_lengths[ix]);
548
0
    switch (ix) {
549
0
      case 16:
550
0
        VP8LPutBits(bw, extra_bits, 2);
551
0
        break;
552
0
      case 17:
553
0
        VP8LPutBits(bw, extra_bits, 3);
554
0
        break;
555
0
      case 18:
556
0
        VP8LPutBits(bw, extra_bits, 7);
557
0
        break;
558
0
    }
559
0
  }
560
0
}
561
562
// 'huff_tree' and 'tokens' are pre-alloacted buffers.
563
static void StoreFullHuffmanCode(VP8LBitWriter* const bw,
564
                                 HuffmanTree* const huff_tree,
565
                                 HuffmanTreeToken* const tokens,
566
0
                                 const HuffmanTreeCode* const tree) {
567
0
  uint8_t code_length_bitdepth[CODE_LENGTH_CODES] = { 0 };
568
0
  uint16_t code_length_bitdepth_symbols[CODE_LENGTH_CODES] = { 0 };
569
0
  const int max_tokens = tree->num_symbols;
570
0
  int num_tokens;
571
0
  HuffmanTreeCode huffman_code;
572
0
  huffman_code.num_symbols = CODE_LENGTH_CODES;
573
0
  huffman_code.code_lengths = code_length_bitdepth;
574
0
  huffman_code.codes = code_length_bitdepth_symbols;
575
576
0
  VP8LPutBits(bw, 0, 1);
577
0
  num_tokens = VP8LCreateCompressedHuffmanTree(tree, tokens, max_tokens);
578
0
  {
579
0
    uint32_t histogram[CODE_LENGTH_CODES] = { 0 };
580
0
    uint8_t buf_rle[CODE_LENGTH_CODES] = { 0 };
581
0
    int i;
582
0
    for (i = 0; i < num_tokens; ++i) {
583
0
      ++histogram[tokens[i].code];
584
0
    }
585
586
0
    VP8LCreateHuffmanTree(histogram, 7, buf_rle, huff_tree, &huffman_code);
587
0
  }
588
589
0
  StoreHuffmanTreeOfHuffmanTreeToBitMask(bw, code_length_bitdepth);
590
0
  ClearHuffmanTreeIfOnlyOneSymbol(&huffman_code);
591
0
  {
592
0
    int trailing_zero_bits = 0;
593
0
    int trimmed_length = num_tokens;
594
0
    int write_trimmed_length;
595
0
    int length;
596
0
    int i = num_tokens;
597
0
    while (i-- > 0) {
598
0
      const int ix = tokens[i].code;
599
0
      if (ix == 0 || ix == 17 || ix == 18) {
600
0
        --trimmed_length;   // discount trailing zeros
601
0
        trailing_zero_bits += code_length_bitdepth[ix];
602
0
        if (ix == 17) {
603
0
          trailing_zero_bits += 3;
604
0
        } else if (ix == 18) {
605
0
          trailing_zero_bits += 7;
606
0
        }
607
0
      } else {
608
0
        break;
609
0
      }
610
0
    }
611
0
    write_trimmed_length = (trimmed_length > 1 && trailing_zero_bits > 12);
612
0
    length = write_trimmed_length ? trimmed_length : num_tokens;
613
0
    VP8LPutBits(bw, write_trimmed_length, 1);
614
0
    if (write_trimmed_length) {
615
0
      if (trimmed_length == 2) {
616
0
        VP8LPutBits(bw, 0, 3 + 2);     // nbitpairs=1, trimmed_length=2
617
0
      } else {
618
0
        const int nbits = BitsLog2Floor(trimmed_length - 2);
619
0
        const int nbitpairs = nbits / 2 + 1;
620
0
        assert(trimmed_length > 2);
621
0
        assert(nbitpairs - 1 < 8);
622
0
        VP8LPutBits(bw, nbitpairs - 1, 3);
623
0
        VP8LPutBits(bw, trimmed_length - 2, nbitpairs * 2);
624
0
      }
625
0
    }
626
0
    StoreHuffmanTreeToBitMask(bw, tokens, length, &huffman_code);
627
0
  }
628
0
}
629
630
// 'huff_tree' and 'tokens' are pre-alloacted buffers.
631
static void StoreHuffmanCode(VP8LBitWriter* const bw,
632
                             HuffmanTree* const huff_tree,
633
                             HuffmanTreeToken* const tokens,
634
0
                             const HuffmanTreeCode* const huffman_code) {
635
0
  int i;
636
0
  int count = 0;
637
0
  int symbols[2] = { 0, 0 };
638
0
  const int kMaxBits = 8;
639
0
  const int kMaxSymbol = 1 << kMaxBits;
640
641
  // Check whether it's a small tree.
642
0
  for (i = 0; i < huffman_code->num_symbols && count < 3; ++i) {
643
0
    if (huffman_code->code_lengths[i] != 0) {
644
0
      if (count < 2) symbols[count] = i;
645
0
      ++count;
646
0
    }
647
0
  }
648
649
0
  if (count == 0) {   // emit minimal tree for empty cases
650
    // bits: small tree marker: 1, count-1: 0, large 8-bit code: 0, code: 0
651
0
    VP8LPutBits(bw, 0x01, 4);
652
0
  } else if (count <= 2 && symbols[0] < kMaxSymbol && symbols[1] < kMaxSymbol) {
653
0
    VP8LPutBits(bw, 1, 1);  // Small tree marker to encode 1 or 2 symbols.
654
0
    VP8LPutBits(bw, count - 1, 1);
655
0
    if (symbols[0] <= 1) {
656
0
      VP8LPutBits(bw, 0, 1);  // Code bit for small (1 bit) symbol value.
657
0
      VP8LPutBits(bw, symbols[0], 1);
658
0
    } else {
659
0
      VP8LPutBits(bw, 1, 1);
660
0
      VP8LPutBits(bw, symbols[0], 8);
661
0
    }
662
0
    if (count == 2) {
663
0
      VP8LPutBits(bw, symbols[1], 8);
664
0
    }
665
0
  } else {
666
0
    StoreFullHuffmanCode(bw, huff_tree, tokens, huffman_code);
667
0
  }
668
0
}
669
670
static WEBP_INLINE void WriteHuffmanCode(VP8LBitWriter* const bw,
671
                             const HuffmanTreeCode* const code,
672
0
                             int code_index) {
673
0
  const int depth = code->code_lengths[code_index];
674
0
  const int symbol = code->codes[code_index];
675
0
  VP8LPutBits(bw, symbol, depth);
676
0
}
677
678
static WEBP_INLINE void WriteHuffmanCodeWithExtraBits(
679
    VP8LBitWriter* const bw,
680
    const HuffmanTreeCode* const code,
681
    int code_index,
682
    int bits,
683
0
    int n_bits) {
684
0
  const int depth = code->code_lengths[code_index];
685
0
  const int symbol = code->codes[code_index];
686
0
  VP8LPutBits(bw, (bits << depth) | symbol, depth + n_bits);
687
0
}
688
689
static int StoreImageToBitMask(VP8LBitWriter* const bw, int width,
690
                               int histo_bits,
691
                               const VP8LBackwardRefs* const refs,
692
                               const uint32_t* histogram_symbols,
693
                               const HuffmanTreeCode* const huffman_codes,
694
0
                               const WebPPicture* const pic) {
695
0
  const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;
696
0
  const int tile_mask = (histo_bits == 0) ? 0 : -(1 << histo_bits);
697
  // x and y trace the position in the image.
698
0
  int x = 0;
699
0
  int y = 0;
700
0
  int tile_x = x & tile_mask;
701
0
  int tile_y = y & tile_mask;
702
0
  int histogram_ix = (histogram_symbols[0] >> 8) & 0xffff;
703
0
  const HuffmanTreeCode* codes = huffman_codes + 5 * histogram_ix;
704
0
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
705
0
  while (VP8LRefsCursorOk(&c)) {
706
0
    const PixOrCopy* const v = c.cur_pos;
707
0
    if ((tile_x != (x & tile_mask)) || (tile_y != (y & tile_mask))) {
708
0
      tile_x = x & tile_mask;
709
0
      tile_y = y & tile_mask;
710
0
      histogram_ix = (histogram_symbols[(y >> histo_bits) * histo_xsize +
711
0
                                        (x >> histo_bits)] >>
712
0
                      8) &
713
0
                     0xffff;
714
0
      codes = huffman_codes + 5 * histogram_ix;
715
0
    }
716
0
    if (PixOrCopyIsLiteral(v)) {
717
0
      static const uint8_t order[] = { 1, 2, 0, 3 };
718
0
      int k;
719
0
      for (k = 0; k < 4; ++k) {
720
0
        const int code = PixOrCopyLiteral(v, order[k]);
721
0
        WriteHuffmanCode(bw, codes + k, code);
722
0
      }
723
0
    } else if (PixOrCopyIsCacheIdx(v)) {
724
0
      const int code = PixOrCopyCacheIdx(v);
725
0
      const int literal_ix = 256 + NUM_LENGTH_CODES + code;
726
0
      WriteHuffmanCode(bw, codes, literal_ix);
727
0
    } else {
728
0
      int bits, n_bits;
729
0
      int code;
730
731
0
      const int distance = PixOrCopyDistance(v);
732
0
      VP8LPrefixEncode(v->len, &code, &n_bits, &bits);
733
0
      WriteHuffmanCodeWithExtraBits(bw, codes, 256 + code, bits, n_bits);
734
735
      // Don't write the distance with the extra bits code since
736
      // the distance can be up to 18 bits of extra bits, and the prefix
737
      // 15 bits, totaling to 33, and our PutBits only supports up to 32 bits.
738
0
      VP8LPrefixEncode(distance, &code, &n_bits, &bits);
739
0
      WriteHuffmanCode(bw, codes + 4, code);
740
0
      VP8LPutBits(bw, bits, n_bits);
741
0
    }
742
0
    x += PixOrCopyLength(v);
743
0
    while (x >= width) {
744
0
      x -= width;
745
0
      ++y;
746
0
    }
747
0
    VP8LRefsCursorNext(&c);
748
0
  }
749
0
  if (bw->error) {
750
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
751
0
  }
752
0
  return 1;
753
0
}
754
755
// Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31.
756
// pic and percent are for progress.
757
static int EncodeImageNoHuffman(VP8LBitWriter* const bw,
758
                                const uint32_t* const argb,
759
                                VP8LHashChain* const hash_chain,
760
                                VP8LBackwardRefs* const refs_array, int width,
761
                                int height, int quality, int low_effort,
762
                                const WebPPicture* const pic, int percent_range,
763
0
                                int* const percent) {
764
0
  int i;
765
0
  int max_tokens = 0;
766
0
  VP8LBackwardRefs* refs;
767
0
  HuffmanTreeToken* tokens = NULL;
768
0
  HuffmanTreeCode huffman_codes[5] = {{0, NULL, NULL}};
769
0
  const uint32_t histogram_symbols[1] = {0};  // only one tree, one symbol
770
0
  int cache_bits = 0;
771
0
  VP8LHistogramSet* histogram_image = NULL;
772
0
  HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
773
0
      3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
774
0
  if (huff_tree == NULL) {
775
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
776
0
    goto Error;
777
0
  }
778
779
  // Calculate backward references from ARGB image.
780
0
  if (!VP8LHashChainFill(hash_chain, quality, argb, width, height, low_effort,
781
0
                         pic, percent_range / 2, percent)) {
782
0
    goto Error;
783
0
  }
784
0
  if (!VP8LGetBackwardReferences(width, height, argb, quality, /*low_effort=*/0,
785
0
                                 kLZ77Standard | kLZ77RLE, cache_bits,
786
0
                                 /*do_no_cache=*/0, hash_chain, refs_array,
787
0
                                 &cache_bits, pic,
788
0
                                 percent_range - percent_range / 2, percent)) {
789
0
    goto Error;
790
0
  }
791
0
  refs = &refs_array[0];
792
0
  histogram_image = VP8LAllocateHistogramSet(1, cache_bits);
793
0
  if (histogram_image == NULL) {
794
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
795
0
    goto Error;
796
0
  }
797
0
  VP8LHistogramSetClear(histogram_image);
798
799
  // Build histogram image and symbols from backward references.
800
0
  VP8LHistogramStoreRefs(refs, /*distance_modifier=*/NULL,
801
0
                         /*distance_modifier_arg0=*/0,
802
0
                         histogram_image->histograms[0]);
803
804
  // Create Huffman bit lengths and codes for each histogram image.
805
0
  assert(histogram_image->size == 1);
806
0
  if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
807
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
808
0
    goto Error;
809
0
  }
810
811
  // No color cache, no Huffman image.
812
0
  VP8LPutBits(bw, 0, 1);
813
814
  // Find maximum number of symbols for the huffman tree-set.
815
0
  for (i = 0; i < 5; ++i) {
816
0
    HuffmanTreeCode* const codes = &huffman_codes[i];
817
0
    if (max_tokens < codes->num_symbols) {
818
0
      max_tokens = codes->num_symbols;
819
0
    }
820
0
  }
821
822
0
  tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
823
0
  if (tokens == NULL) {
824
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
825
0
    goto Error;
826
0
  }
827
828
  // Store Huffman codes.
829
0
  for (i = 0; i < 5; ++i) {
830
0
    HuffmanTreeCode* const codes = &huffman_codes[i];
831
0
    StoreHuffmanCode(bw, huff_tree, tokens, codes);
832
0
    ClearHuffmanTreeIfOnlyOneSymbol(codes);
833
0
  }
834
835
  // Store actual literals.
836
0
  if (!StoreImageToBitMask(bw, width, 0, refs, histogram_symbols, huffman_codes,
837
0
                           pic)) {
838
0
    goto Error;
839
0
  }
840
841
0
 Error:
842
0
  WebPSafeFree(tokens);
843
0
  WebPSafeFree(huff_tree);
844
0
  VP8LFreeHistogramSet(histogram_image);
845
0
  WebPSafeFree(huffman_codes[0].codes);
846
0
  return (pic->error_code == VP8_ENC_OK);
847
0
}
848
849
// pic and percent are for progress.
850
static int EncodeImageInternal(
851
    VP8LBitWriter* const bw, const uint32_t* const argb,
852
    VP8LHashChain* const hash_chain, VP8LBackwardRefs refs_array[4], int width,
853
    int height, int quality, int low_effort, const CrunchConfig* const config,
854
    int* cache_bits, int histogram_bits_in, size_t init_byte_position,
855
    int* const hdr_size, int* const data_size, const WebPPicture* const pic,
856
0
    int percent_range, int* const percent) {
857
0
  const uint32_t histogram_image_xysize =
858
0
      VP8LSubSampleSize(width, histogram_bits_in) *
859
0
      VP8LSubSampleSize(height, histogram_bits_in);
860
0
  int remaining_percent = percent_range;
861
0
  int percent_start = *percent;
862
0
  VP8LHistogramSet* histogram_image = NULL;
863
0
  VP8LHistogram* tmp_histo = NULL;
864
0
  uint32_t i, histogram_image_size = 0;
865
0
  size_t bit_array_size = 0;
866
0
  HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
867
0
      3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
868
0
  HuffmanTreeToken* tokens = NULL;
869
0
  HuffmanTreeCode* huffman_codes = NULL;
870
0
  uint32_t* const histogram_argb = (uint32_t*)WebPSafeMalloc(
871
0
      histogram_image_xysize, sizeof(*histogram_argb));
872
0
  int sub_configs_idx;
873
0
  int cache_bits_init, write_histogram_image;
874
0
  VP8LBitWriter bw_init = *bw, bw_best;
875
0
  int hdr_size_tmp;
876
0
  VP8LHashChain hash_chain_histogram;  // histogram image hash chain
877
0
  size_t bw_size_best = ~(size_t)0;
878
0
  assert(histogram_bits_in >= MIN_HUFFMAN_BITS);
879
0
  assert(histogram_bits_in <= MAX_HUFFMAN_BITS);
880
0
  assert(hdr_size != NULL);
881
0
  assert(data_size != NULL);
882
883
0
  memset(&hash_chain_histogram, 0, sizeof(hash_chain_histogram));
884
0
  if (!VP8LBitWriterInit(&bw_best, 0)) {
885
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
886
0
    goto Error;
887
0
  }
888
889
  // Make sure we can allocate the different objects.
890
0
  if (huff_tree == NULL || histogram_argb == NULL ||
891
0
      !VP8LHashChainInit(&hash_chain_histogram, histogram_image_xysize)) {
892
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
893
0
    goto Error;
894
0
  }
895
896
0
  percent_range = remaining_percent / 5;
897
0
  if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,
898
0
                         low_effort, pic, percent_range, percent)) {
899
0
    goto Error;
900
0
  }
901
0
  percent_start += percent_range;
902
0
  remaining_percent -= percent_range;
903
904
  // If the value is different from zero, it has been set during the palette
905
  // analysis.
906
0
  cache_bits_init = (*cache_bits == 0) ? MAX_COLOR_CACHE_BITS : *cache_bits;
907
  // If several iterations will happen, clone into bw_best.
908
0
  if ((config->sub_configs_size > 1 || config->sub_configs[0].do_no_cache) &&
909
0
      !VP8LBitWriterClone(bw, &bw_best)) {
910
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
911
0
    goto Error;
912
0
  }
913
914
0
  for (sub_configs_idx = 0; sub_configs_idx < config->sub_configs_size;
915
0
       ++sub_configs_idx) {
916
0
    const CrunchSubConfig* const sub_config =
917
0
        &config->sub_configs[sub_configs_idx];
918
0
    int cache_bits_best, i_cache;
919
0
    int i_remaining_percent = remaining_percent / config->sub_configs_size;
920
0
    int i_percent_range = i_remaining_percent / 4;
921
0
    i_remaining_percent -= i_percent_range;
922
923
0
    if (!VP8LGetBackwardReferences(
924
0
            width, height, argb, quality, low_effort, sub_config->lz77,
925
0
            cache_bits_init, sub_config->do_no_cache, hash_chain,
926
0
            &refs_array[0], &cache_bits_best, pic, i_percent_range, percent)) {
927
0
      goto Error;
928
0
    }
929
930
0
    for (i_cache = 0; i_cache < (sub_config->do_no_cache ? 2 : 1); ++i_cache) {
931
0
      const int cache_bits_tmp = (i_cache == 0) ? cache_bits_best : 0;
932
0
      int histogram_bits = histogram_bits_in;
933
      // Speed-up: no need to study the no-cache case if it was already studied
934
      // in i_cache == 0.
935
0
      if (i_cache == 1 && cache_bits_best == 0) break;
936
937
      // Reset the bit writer for this iteration.
938
0
      VP8LBitWriterReset(&bw_init, bw);
939
940
      // Build histogram image and symbols from backward references.
941
0
      histogram_image =
942
0
          VP8LAllocateHistogramSet(histogram_image_xysize, cache_bits_tmp);
943
0
      tmp_histo = VP8LAllocateHistogram(cache_bits_tmp);
944
0
      if (histogram_image == NULL || tmp_histo == NULL) {
945
0
        WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
946
0
        goto Error;
947
0
      }
948
949
0
      i_percent_range = i_remaining_percent / 3;
950
0
      i_remaining_percent -= i_percent_range;
951
0
      if (!VP8LGetHistoImageSymbols(
952
0
              width, height, &refs_array[i_cache], quality, low_effort,
953
0
              histogram_bits, cache_bits_tmp, histogram_image, tmp_histo,
954
0
              histogram_argb, pic, i_percent_range, percent)) {
955
0
        goto Error;
956
0
      }
957
      // Create Huffman bit lengths and codes for each histogram image.
958
0
      histogram_image_size = histogram_image->size;
959
0
      bit_array_size = 5 * histogram_image_size;
960
0
      huffman_codes = (HuffmanTreeCode*)WebPSafeCalloc(bit_array_size,
961
0
                                                       sizeof(*huffman_codes));
962
      // Note: some histogram_image entries may point to tmp_histos[], so the
963
      // latter need to outlive the following call to
964
      // GetHuffBitLengthsAndCodes().
965
0
      if (huffman_codes == NULL ||
966
0
          !GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
967
0
        WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
968
0
        goto Error;
969
0
      }
970
      // Free combined histograms.
971
0
      VP8LFreeHistogramSet(histogram_image);
972
0
      histogram_image = NULL;
973
974
      // Free scratch histograms.
975
0
      VP8LFreeHistogram(tmp_histo);
976
0
      tmp_histo = NULL;
977
978
      // Color Cache parameters.
979
0
      if (cache_bits_tmp > 0) {
980
0
        VP8LPutBits(bw, 1, 1);
981
0
        VP8LPutBits(bw, cache_bits_tmp, 4);
982
0
      } else {
983
0
        VP8LPutBits(bw, 0, 1);
984
0
      }
985
986
      // Huffman image + meta huffman.
987
0
      histogram_image_size = 0;
988
0
      for (i = 0; i < histogram_image_xysize; ++i) {
989
0
        if (histogram_argb[i] >= histogram_image_size) {
990
0
          histogram_image_size = histogram_argb[i] + 1;
991
0
        }
992
0
        histogram_argb[i] <<= 8;
993
0
      }
994
995
0
      write_histogram_image = (histogram_image_size > 1);
996
0
      VP8LPutBits(bw, write_histogram_image, 1);
997
0
      if (write_histogram_image) {
998
0
        VP8LOptimizeSampling(histogram_argb, width, height, histogram_bits_in,
999
0
                             MAX_HUFFMAN_BITS, &histogram_bits);
1000
0
        VP8LPutBits(bw, histogram_bits - 2, 3);
1001
0
        i_percent_range = i_remaining_percent / 2;
1002
0
        i_remaining_percent -= i_percent_range;
1003
0
        if (!EncodeImageNoHuffman(
1004
0
                bw, histogram_argb, &hash_chain_histogram, &refs_array[2],
1005
0
                VP8LSubSampleSize(width, histogram_bits),
1006
0
                VP8LSubSampleSize(height, histogram_bits), quality, low_effort,
1007
0
                pic, i_percent_range, percent)) {
1008
0
          goto Error;
1009
0
        }
1010
0
      }
1011
1012
      // Store Huffman codes.
1013
0
      {
1014
0
        int max_tokens = 0;
1015
        // Find maximum number of symbols for the huffman tree-set.
1016
0
        for (i = 0; i < 5 * histogram_image_size; ++i) {
1017
0
          HuffmanTreeCode* const codes = &huffman_codes[i];
1018
0
          if (max_tokens < codes->num_symbols) {
1019
0
            max_tokens = codes->num_symbols;
1020
0
          }
1021
0
        }
1022
0
        tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
1023
0
        if (tokens == NULL) {
1024
0
          WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1025
0
          goto Error;
1026
0
        }
1027
0
        for (i = 0; i < 5 * histogram_image_size; ++i) {
1028
0
          HuffmanTreeCode* const codes = &huffman_codes[i];
1029
0
          StoreHuffmanCode(bw, huff_tree, tokens, codes);
1030
0
          ClearHuffmanTreeIfOnlyOneSymbol(codes);
1031
0
        }
1032
0
      }
1033
      // Store actual literals.
1034
0
      hdr_size_tmp = (int)(VP8LBitWriterNumBytes(bw) - init_byte_position);
1035
0
      if (!StoreImageToBitMask(bw, width, histogram_bits, &refs_array[i_cache],
1036
0
                               histogram_argb, huffman_codes, pic)) {
1037
0
        goto Error;
1038
0
      }
1039
      // Keep track of the smallest image so far.
1040
0
      if (VP8LBitWriterNumBytes(bw) < bw_size_best) {
1041
0
        bw_size_best = VP8LBitWriterNumBytes(bw);
1042
0
        *cache_bits = cache_bits_tmp;
1043
0
        *hdr_size = hdr_size_tmp;
1044
0
        *data_size =
1045
0
            (int)(VP8LBitWriterNumBytes(bw) - init_byte_position - *hdr_size);
1046
0
        VP8LBitWriterSwap(bw, &bw_best);
1047
0
      }
1048
0
      WebPSafeFree(tokens);
1049
0
      tokens = NULL;
1050
0
      if (huffman_codes != NULL) {
1051
0
        WebPSafeFree(huffman_codes->codes);
1052
0
        WebPSafeFree(huffman_codes);
1053
0
        huffman_codes = NULL;
1054
0
      }
1055
0
    }
1056
0
  }
1057
0
  VP8LBitWriterSwap(bw, &bw_best);
1058
1059
0
  if (!WebPReportProgress(pic, percent_start + remaining_percent, percent)) {
1060
0
    goto Error;
1061
0
  }
1062
1063
0
 Error:
1064
0
  WebPSafeFree(tokens);
1065
0
  WebPSafeFree(huff_tree);
1066
0
  VP8LFreeHistogramSet(histogram_image);
1067
0
  VP8LFreeHistogram(tmp_histo);
1068
0
  VP8LHashChainClear(&hash_chain_histogram);
1069
0
  if (huffman_codes != NULL) {
1070
0
    WebPSafeFree(huffman_codes->codes);
1071
0
    WebPSafeFree(huffman_codes);
1072
0
  }
1073
0
  WebPSafeFree(histogram_argb);
1074
0
  VP8LBitWriterWipeOut(&bw_best);
1075
0
  return (pic->error_code == VP8_ENC_OK);
1076
0
}
1077
1078
// -----------------------------------------------------------------------------
1079
// Transforms
1080
1081
static void ApplySubtractGreen(VP8LEncoder* const enc, int width, int height,
1082
0
                               VP8LBitWriter* const bw) {
1083
0
  VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
1084
0
  VP8LPutBits(bw, SUBTRACT_GREEN_TRANSFORM, 2);
1085
0
  VP8LSubtractGreenFromBlueAndRed(enc->argb, width * height);
1086
0
}
1087
1088
static int ApplyPredictFilter(VP8LEncoder* const enc, int width, int height,
1089
                              int quality, int low_effort,
1090
                              int used_subtract_green, VP8LBitWriter* const bw,
1091
0
                              int percent_range, int* const percent) {
1092
0
  int best_bits;
1093
0
  const int near_lossless_strength =
1094
0
      enc->use_palette ? 100 : enc->config->near_lossless;
1095
0
  const int max_bits = ClampBits(width, height, enc->predictor_transform_bits,
1096
0
                                 MIN_TRANSFORM_BITS, MAX_TRANSFORM_BITS,
1097
0
                                 MAX_PREDICTOR_IMAGE_SIZE);
1098
0
  const int min_bits = ClampBits(
1099
0
      width, height,
1100
0
      max_bits - 2 * (enc->config->method > 4 ? enc->config->method - 4 : 0),
1101
0
      MIN_TRANSFORM_BITS, MAX_TRANSFORM_BITS, MAX_PREDICTOR_IMAGE_SIZE);
1102
1103
0
  if (!VP8LResidualImage(width, height, min_bits, max_bits, low_effort,
1104
0
                         enc->argb, enc->argb_scratch, enc->transform_data,
1105
0
                         near_lossless_strength, enc->config->exact,
1106
0
                         used_subtract_green, enc->pic, percent_range / 2,
1107
0
                         percent, &best_bits)) {
1108
0
    return 0;
1109
0
  }
1110
0
  VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
1111
0
  VP8LPutBits(bw, PREDICTOR_TRANSFORM, 2);
1112
0
  assert(best_bits >= MIN_TRANSFORM_BITS && best_bits <= MAX_TRANSFORM_BITS);
1113
0
  VP8LPutBits(bw, best_bits - MIN_TRANSFORM_BITS, NUM_TRANSFORM_BITS);
1114
0
  enc->predictor_transform_bits = best_bits;
1115
0
  return EncodeImageNoHuffman(
1116
0
      bw, enc->transform_data, &enc->hash_chain, &enc->refs[0],
1117
0
      VP8LSubSampleSize(width, best_bits), VP8LSubSampleSize(height, best_bits),
1118
0
      quality, low_effort, enc->pic, percent_range - percent_range / 2,
1119
0
      percent);
1120
0
}
1121
1122
static int ApplyCrossColorFilter(VP8LEncoder* const enc, int width, int height,
1123
                                 int quality, int low_effort,
1124
                                 VP8LBitWriter* const bw, int percent_range,
1125
0
                                 int* const percent) {
1126
0
  const int min_bits = enc->cross_color_transform_bits;
1127
0
  int best_bits;
1128
1129
0
  if (!VP8LColorSpaceTransform(width, height, min_bits, quality, enc->argb,
1130
0
                               enc->transform_data, enc->pic,
1131
0
                               percent_range / 2, percent, &best_bits)) {
1132
0
    return 0;
1133
0
  }
1134
0
  VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
1135
0
  VP8LPutBits(bw, CROSS_COLOR_TRANSFORM, 2);
1136
0
  assert(best_bits >= MIN_TRANSFORM_BITS && best_bits <= MAX_TRANSFORM_BITS);
1137
0
  VP8LPutBits(bw, best_bits - MIN_TRANSFORM_BITS, NUM_TRANSFORM_BITS);
1138
0
  enc->cross_color_transform_bits = best_bits;
1139
0
  return EncodeImageNoHuffman(
1140
0
      bw, enc->transform_data, &enc->hash_chain, &enc->refs[0],
1141
0
      VP8LSubSampleSize(width, best_bits), VP8LSubSampleSize(height, best_bits),
1142
0
      quality, low_effort, enc->pic, percent_range - percent_range / 2,
1143
0
      percent);
1144
0
}
1145
1146
// -----------------------------------------------------------------------------
1147
1148
static int WriteRiffHeader(const WebPPicture* const pic, size_t riff_size,
1149
0
                           size_t vp8l_size) {
1150
0
  uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {
1151
0
    'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',
1152
0
    'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,
1153
0
  };
1154
0
  PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
1155
0
  PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);
1156
0
  return pic->writer(riff, sizeof(riff), pic);
1157
0
}
1158
1159
static int WriteImageSize(const WebPPicture* const pic,
1160
0
                          VP8LBitWriter* const bw) {
1161
0
  const int width = pic->width - 1;
1162
0
  const int height = pic->height - 1;
1163
0
  assert(width < WEBP_MAX_DIMENSION && height < WEBP_MAX_DIMENSION);
1164
1165
0
  VP8LPutBits(bw, width, VP8L_IMAGE_SIZE_BITS);
1166
0
  VP8LPutBits(bw, height, VP8L_IMAGE_SIZE_BITS);
1167
0
  return !bw->error;
1168
0
}
1169
1170
0
static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {
1171
0
  VP8LPutBits(bw, has_alpha, 1);
1172
0
  VP8LPutBits(bw, VP8L_VERSION, VP8L_VERSION_BITS);
1173
0
  return !bw->error;
1174
0
}
1175
1176
static int WriteImage(const WebPPicture* const pic, VP8LBitWriter* const bw,
1177
0
                      size_t* const coded_size) {
1178
0
  const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);
1179
0
  const size_t webpll_size = VP8LBitWriterNumBytes(bw);
1180
0
  const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;
1181
0
  const size_t pad = vp8l_size & 1;
1182
0
  const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;
1183
0
  *coded_size = 0;
1184
1185
0
  if (bw->error) {
1186
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1187
0
  }
1188
1189
0
  if (!WriteRiffHeader(pic, riff_size, vp8l_size) ||
1190
0
      !pic->writer(webpll_data, webpll_size, pic)) {
1191
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_WRITE);
1192
0
  }
1193
1194
0
  if (pad) {
1195
0
    const uint8_t pad_byte[1] = { 0 };
1196
0
    if (!pic->writer(pad_byte, 1, pic)) {
1197
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_WRITE);
1198
0
    }
1199
0
  }
1200
0
  *coded_size = CHUNK_HEADER_SIZE + riff_size;
1201
0
  return 1;
1202
0
}
1203
1204
// -----------------------------------------------------------------------------
1205
1206
0
static void ClearTransformBuffer(VP8LEncoder* const enc) {
1207
0
  WebPSafeFree(enc->transform_mem);
1208
0
  enc->transform_mem = NULL;
1209
0
  enc->transform_mem_size = 0;
1210
0
}
1211
1212
// Allocates the memory for argb (W x H) buffer, 2 rows of context for
1213
// prediction and transform data.
1214
// Flags influencing the memory allocated:
1215
//  enc->transform_bits
1216
//  enc->use_predict, enc->use_cross_color
1217
static int AllocateTransformBuffer(VP8LEncoder* const enc, int width,
1218
0
                                   int height) {
1219
0
  const uint64_t image_size = (uint64_t)width * height;
1220
  // VP8LResidualImage needs room for 2 scanlines of uint32 pixels with an extra
1221
  // pixel in each, plus 2 regular scanlines of bytes.
1222
  // TODO(skal): Clean up by using arithmetic in bytes instead of words.
1223
0
  const uint64_t argb_scratch_size =
1224
0
      enc->use_predict ? (width + 1) * 2 + (width * 2 + sizeof(uint32_t) - 1) /
1225
0
                                               sizeof(uint32_t)
1226
0
                        : 0;
1227
0
  const uint64_t transform_data_size =
1228
0
      (enc->use_predict || enc->use_cross_color)
1229
0
          ? (uint64_t)VP8LSubSampleSize(width, MIN_TRANSFORM_BITS) *
1230
0
                VP8LSubSampleSize(height, MIN_TRANSFORM_BITS)
1231
0
          : 0;
1232
0
  const uint64_t max_alignment_in_words =
1233
0
      (WEBP_ALIGN_CST + sizeof(uint32_t) - 1) / sizeof(uint32_t);
1234
0
  const uint64_t mem_size = image_size + max_alignment_in_words +
1235
0
                            argb_scratch_size + max_alignment_in_words +
1236
0
                            transform_data_size;
1237
0
  uint32_t* mem = enc->transform_mem;
1238
0
  if (mem == NULL || mem_size > enc->transform_mem_size) {
1239
0
    ClearTransformBuffer(enc);
1240
0
    mem = (uint32_t*)WebPSafeMalloc(mem_size, sizeof(*mem));
1241
0
    if (mem == NULL) {
1242
0
      return WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1243
0
    }
1244
0
    enc->transform_mem = mem;
1245
0
    enc->transform_mem_size = (size_t)mem_size;
1246
0
    enc->argb_content = kEncoderNone;
1247
0
  }
1248
0
  enc->argb = mem;
1249
0
  mem = (uint32_t*)WEBP_ALIGN(mem + image_size);
1250
0
  enc->argb_scratch = mem;
1251
0
  mem = (uint32_t*)WEBP_ALIGN(mem + argb_scratch_size);
1252
0
  enc->transform_data = mem;
1253
1254
0
  enc->current_width = width;
1255
0
  return 1;
1256
0
}
1257
1258
0
static int MakeInputImageCopy(VP8LEncoder* const enc) {
1259
0
  const WebPPicture* const picture = enc->pic;
1260
0
  const int width = picture->width;
1261
0
  const int height = picture->height;
1262
1263
0
  if (!AllocateTransformBuffer(enc, width, height)) return 0;
1264
0
  if (enc->argb_content == kEncoderARGB) return 1;
1265
1266
0
  {
1267
0
    uint32_t* dst = enc->argb;
1268
0
    const uint32_t* src = picture->argb;
1269
0
    int y;
1270
0
    for (y = 0; y < height; ++y) {
1271
0
      memcpy(dst, src, width * sizeof(*dst));
1272
0
      dst += width;
1273
0
      src += picture->argb_stride;
1274
0
    }
1275
0
  }
1276
0
  enc->argb_content = kEncoderARGB;
1277
0
  assert(enc->current_width == width);
1278
0
  return 1;
1279
0
}
1280
1281
// -----------------------------------------------------------------------------
1282
1283
0
#define APPLY_PALETTE_GREEDY_MAX 4
1284
1285
static WEBP_INLINE uint32_t SearchColorGreedy(const uint32_t palette[],
1286
                                              int palette_size,
1287
0
                                              uint32_t color) {
1288
0
  (void)palette_size;
1289
0
  assert(palette_size < APPLY_PALETTE_GREEDY_MAX);
1290
0
  assert(3 == APPLY_PALETTE_GREEDY_MAX - 1);
1291
0
  if (color == palette[0]) return 0;
1292
0
  if (color == palette[1]) return 1;
1293
0
  if (color == palette[2]) return 2;
1294
0
  return 3;
1295
0
}
1296
1297
0
static WEBP_INLINE uint32_t ApplyPaletteHash0(uint32_t color) {
1298
  // Focus on the green color.
1299
0
  return (color >> 8) & 0xff;
1300
0
}
1301
1302
0
#define PALETTE_INV_SIZE_BITS 11
1303
#define PALETTE_INV_SIZE (1 << PALETTE_INV_SIZE_BITS)
1304
1305
0
static WEBP_INLINE uint32_t ApplyPaletteHash1(uint32_t color) {
1306
  // Forget about alpha.
1307
0
  return ((uint32_t)((color & 0x00ffffffu) * 4222244071ull)) >>
1308
0
         (32 - PALETTE_INV_SIZE_BITS);
1309
0
}
1310
1311
0
static WEBP_INLINE uint32_t ApplyPaletteHash2(uint32_t color) {
1312
  // Forget about alpha.
1313
0
  return ((uint32_t)((color & 0x00ffffffu) * ((1ull << 31) - 1))) >>
1314
0
         (32 - PALETTE_INV_SIZE_BITS);
1315
0
}
1316
1317
// Use 1 pixel cache for ARGB pixels.
1318
0
#define APPLY_PALETTE_FOR(COLOR_INDEX) do {         \
1319
0
  uint32_t prev_pix = palette[0];                   \
1320
0
  uint32_t prev_idx = 0;                            \
1321
0
  for (y = 0; y < height; ++y) {                    \
1322
0
    for (x = 0; x < width; ++x) {                   \
1323
0
      const uint32_t pix = src[x];                  \
1324
0
      if (pix != prev_pix) {                        \
1325
0
        prev_idx = COLOR_INDEX;                     \
1326
0
        prev_pix = pix;                             \
1327
0
      }                                             \
1328
0
      tmp_row[x] = prev_idx;                        \
1329
0
    }                                               \
1330
0
    VP8LBundleColorMap(tmp_row, width, xbits, dst); \
1331
0
    src += src_stride;                              \
1332
0
    dst += dst_stride;                              \
1333
0
  }                                                 \
1334
0
} while (0)
1335
1336
// Remap argb values in src[] to packed palettes entries in dst[]
1337
// using 'row' as a temporary buffer of size 'width'.
1338
// We assume that all src[] values have a corresponding entry in the palette.
1339
// Note: src[] can be the same as dst[]
1340
static int ApplyPalette(const uint32_t* src, uint32_t src_stride, uint32_t* dst,
1341
                        uint32_t dst_stride, const uint32_t* palette,
1342
                        int palette_size, int width, int height, int xbits,
1343
0
                        const WebPPicture* const pic) {
1344
  // TODO(skal): this tmp buffer is not needed if VP8LBundleColorMap() can be
1345
  // made to work in-place.
1346
0
  uint8_t* const tmp_row = (uint8_t*)WebPSafeMalloc(width, sizeof(*tmp_row));
1347
0
  int x, y;
1348
1349
0
  if (tmp_row == NULL) {
1350
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1351
0
  }
1352
1353
0
  if (palette_size < APPLY_PALETTE_GREEDY_MAX) {
1354
0
    APPLY_PALETTE_FOR(SearchColorGreedy(palette, palette_size, pix));
1355
0
  } else {
1356
0
    int i, j;
1357
0
    uint16_t buffer[PALETTE_INV_SIZE];
1358
0
    uint32_t (*const hash_functions[])(uint32_t) = {
1359
0
        ApplyPaletteHash0, ApplyPaletteHash1, ApplyPaletteHash2
1360
0
    };
1361
1362
    // Try to find a perfect hash function able to go from a color to an index
1363
    // within 1 << PALETTE_INV_SIZE_BITS in order to build a hash map to go
1364
    // from color to index in palette.
1365
0
    for (i = 0; i < 3; ++i) {
1366
0
      int use_LUT = 1;
1367
      // Set each element in buffer to max uint16_t.
1368
0
      memset(buffer, 0xff, sizeof(buffer));
1369
0
      for (j = 0; j < palette_size; ++j) {
1370
0
        const uint32_t ind = hash_functions[i](palette[j]);
1371
0
        if (buffer[ind] != 0xffffu) {
1372
0
          use_LUT = 0;
1373
0
          break;
1374
0
        } else {
1375
0
          buffer[ind] = j;
1376
0
        }
1377
0
      }
1378
0
      if (use_LUT) break;
1379
0
    }
1380
1381
0
    if (i == 0) {
1382
0
      APPLY_PALETTE_FOR(buffer[ApplyPaletteHash0(pix)]);
1383
0
    } else if (i == 1) {
1384
0
      APPLY_PALETTE_FOR(buffer[ApplyPaletteHash1(pix)]);
1385
0
    } else if (i == 2) {
1386
0
      APPLY_PALETTE_FOR(buffer[ApplyPaletteHash2(pix)]);
1387
0
    } else {
1388
0
      uint32_t idx_map[MAX_PALETTE_SIZE];
1389
0
      uint32_t palette_sorted[MAX_PALETTE_SIZE];
1390
0
      PrepareMapToPalette(palette, palette_size, palette_sorted, idx_map);
1391
0
      APPLY_PALETTE_FOR(
1392
0
          idx_map[SearchColorNoIdx(palette_sorted, pix, palette_size)]);
1393
0
    }
1394
0
  }
1395
0
  WebPSafeFree(tmp_row);
1396
0
  return 1;
1397
0
}
1398
#undef APPLY_PALETTE_FOR
1399
#undef PALETTE_INV_SIZE_BITS
1400
#undef PALETTE_INV_SIZE
1401
#undef APPLY_PALETTE_GREEDY_MAX
1402
1403
// Note: Expects "enc->palette" to be set properly.
1404
0
static int MapImageFromPalette(VP8LEncoder* const enc) {
1405
0
  const WebPPicture* const pic = enc->pic;
1406
0
  const int width = pic->width;
1407
0
  const int height = pic->height;
1408
0
  const uint32_t* const palette = enc->palette;
1409
0
  const int palette_size = enc->palette_size;
1410
0
  int xbits;
1411
1412
  // Replace each input pixel by corresponding palette index.
1413
  // This is done line by line.
1414
0
  if (palette_size <= 4) {
1415
0
    xbits = (palette_size <= 2) ? 3 : 2;
1416
0
  } else {
1417
0
    xbits = (palette_size <= 16) ? 1 : 0;
1418
0
  }
1419
1420
0
  if (!AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height)) {
1421
0
    return 0;
1422
0
  }
1423
0
  if (!ApplyPalette(pic->argb, pic->argb_stride, enc->argb,
1424
0
                    enc->current_width, palette, palette_size, width, height,
1425
0
                    xbits, pic)) {
1426
0
    return 0;
1427
0
  }
1428
0
  enc->argb_content = kEncoderPalette;
1429
0
  return 1;
1430
0
}
1431
1432
// Save palette[] to bitstream.
1433
static int EncodePalette(VP8LBitWriter* const bw, int low_effort,
1434
                         VP8LEncoder* const enc, int percent_range,
1435
0
                         int* const percent) {
1436
0
  int i;
1437
0
  uint32_t tmp_palette[MAX_PALETTE_SIZE];
1438
0
  const int palette_size = enc->palette_size;
1439
0
  const uint32_t* const palette = enc->palette;
1440
  // If the last element is 0, do not store it and count on automatic palette
1441
  // 0-filling. This can only happen if there is no pixel packing, hence if
1442
  // there are strictly more than 16 colors (after 0 is removed).
1443
0
  const uint32_t encoded_palette_size =
1444
0
      (enc->palette[palette_size - 1] == 0 && palette_size > 17)
1445
0
          ? palette_size - 1
1446
0
          : palette_size;
1447
0
  VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
1448
0
  VP8LPutBits(bw, COLOR_INDEXING_TRANSFORM, 2);
1449
0
  assert(palette_size >= 1 && palette_size <= MAX_PALETTE_SIZE);
1450
0
  VP8LPutBits(bw, encoded_palette_size - 1, 8);
1451
0
  for (i = encoded_palette_size - 1; i >= 1; --i) {
1452
0
    tmp_palette[i] = VP8LSubPixels(palette[i], palette[i - 1]);
1453
0
  }
1454
0
  tmp_palette[0] = palette[0];
1455
0
  return EncodeImageNoHuffman(
1456
0
      bw, tmp_palette, &enc->hash_chain, &enc->refs[0], encoded_palette_size,
1457
0
      1, /*quality=*/20, low_effort, enc->pic, percent_range, percent);
1458
0
}
1459
1460
// -----------------------------------------------------------------------------
1461
// VP8LEncoder
1462
1463
static VP8LEncoder* VP8LEncoderNew(const WebPConfig* const config,
1464
0
                                   const WebPPicture* const picture) {
1465
0
  VP8LEncoder* const enc = (VP8LEncoder*)WebPSafeCalloc(1ULL, sizeof(*enc));
1466
0
  if (enc == NULL) {
1467
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1468
0
    return NULL;
1469
0
  }
1470
0
  enc->config = config;
1471
0
  enc->pic = picture;
1472
0
  enc->argb_content = kEncoderNone;
1473
1474
0
  VP8LEncDspInit();
1475
1476
0
  return enc;
1477
0
}
1478
1479
0
static void VP8LEncoderDelete(VP8LEncoder* enc) {
1480
0
  if (enc != NULL) {
1481
0
    int i;
1482
0
    VP8LHashChainClear(&enc->hash_chain);
1483
0
    for (i = 0; i < 4; ++i) VP8LBackwardRefsClear(&enc->refs[i]);
1484
0
    ClearTransformBuffer(enc);
1485
0
    WebPSafeFree(enc);
1486
0
  }
1487
0
}
1488
1489
// -----------------------------------------------------------------------------
1490
// Main call
1491
1492
typedef struct {
1493
  const WebPConfig* config;
1494
  const WebPPicture* picture;
1495
  VP8LBitWriter* bw;
1496
  VP8LEncoder* enc;
1497
  CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX];
1498
  int num_crunch_configs;
1499
  int red_and_blue_always_zero;
1500
  WebPAuxStats* stats;
1501
} StreamEncodeContext;
1502
1503
0
static int EncodeStreamHook(void* input, void* data2) {
1504
0
  StreamEncodeContext* const params = (StreamEncodeContext*)input;
1505
0
  const WebPConfig* const config = params->config;
1506
0
  const WebPPicture* const picture = params->picture;
1507
0
  VP8LBitWriter* const bw = params->bw;
1508
0
  VP8LEncoder* const enc = params->enc;
1509
0
  const CrunchConfig* const crunch_configs = params->crunch_configs;
1510
0
  const int num_crunch_configs = params->num_crunch_configs;
1511
0
  const int red_and_blue_always_zero = params->red_and_blue_always_zero;
1512
0
#if !defined(WEBP_DISABLE_STATS)
1513
0
  WebPAuxStats* const stats = params->stats;
1514
0
#endif
1515
0
  const int quality = (int)config->quality;
1516
0
  const int low_effort = (config->method == 0);
1517
0
#if (WEBP_NEAR_LOSSLESS == 1)
1518
0
  const int width = picture->width;
1519
0
#endif
1520
0
  const int height = picture->height;
1521
0
  const size_t byte_position = VP8LBitWriterNumBytes(bw);
1522
0
  int percent = 2;  // for WebPProgressHook
1523
0
#if (WEBP_NEAR_LOSSLESS == 1)
1524
0
  int use_near_lossless = 0;
1525
0
#endif
1526
0
  int hdr_size = 0;
1527
0
  int data_size = 0;
1528
0
  int idx;
1529
0
  size_t best_size = ~(size_t)0;
1530
0
  VP8LBitWriter bw_init = *bw, bw_best;
1531
0
  (void)data2;
1532
1533
0
  if (!VP8LBitWriterInit(&bw_best, 0) ||
1534
0
      (num_crunch_configs > 1 && !VP8LBitWriterClone(bw, &bw_best))) {
1535
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1536
0
    goto Error;
1537
0
  }
1538
1539
0
  for (idx = 0; idx < num_crunch_configs; ++idx) {
1540
0
    const int entropy_idx = crunch_configs[idx].entropy_idx;
1541
0
    int remaining_percent = 97 / num_crunch_configs, percent_range;
1542
0
    enc->use_palette =
1543
0
        (entropy_idx == kPalette) || (entropy_idx == kPaletteAndSpatial);
1544
0
    enc->use_subtract_green =
1545
0
        (entropy_idx == kSubGreen) || (entropy_idx == kSpatialSubGreen);
1546
0
    enc->use_predict = (entropy_idx == kSpatial) ||
1547
0
                       (entropy_idx == kSpatialSubGreen) ||
1548
0
                       (entropy_idx == kPaletteAndSpatial);
1549
    // When using a palette, R/B==0, hence no need to test for cross-color.
1550
0
    if (low_effort || enc->use_palette) {
1551
0
      enc->use_cross_color = 0;
1552
0
    } else {
1553
0
      enc->use_cross_color = red_and_blue_always_zero ? 0 : enc->use_predict;
1554
0
    }
1555
    // Reset any parameter in the encoder that is set in the previous iteration.
1556
0
    enc->cache_bits = 0;
1557
0
    VP8LBackwardRefsClear(&enc->refs[0]);
1558
0
    VP8LBackwardRefsClear(&enc->refs[1]);
1559
1560
0
#if (WEBP_NEAR_LOSSLESS == 1)
1561
    // Apply near-lossless preprocessing.
1562
0
    use_near_lossless = (config->near_lossless < 100) && !enc->use_palette &&
1563
0
                        !enc->use_predict;
1564
0
    if (use_near_lossless) {
1565
0
      if (!AllocateTransformBuffer(enc, width, height)) goto Error;
1566
0
      if ((enc->argb_content != kEncoderNearLossless) &&
1567
0
          !VP8ApplyNearLossless(picture, config->near_lossless, enc->argb)) {
1568
0
        WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1569
0
        goto Error;
1570
0
      }
1571
0
      enc->argb_content = kEncoderNearLossless;
1572
0
    } else {
1573
0
      enc->argb_content = kEncoderNone;
1574
0
    }
1575
#else
1576
    enc->argb_content = kEncoderNone;
1577
#endif
1578
1579
    // Encode palette
1580
0
    if (enc->use_palette) {
1581
0
      if (!PaletteSort(crunch_configs[idx].palette_sorting_type, enc->pic,
1582
0
                       enc->palette_sorted, enc->palette_size,
1583
0
                       enc->palette)) {
1584
0
        WebPEncodingSetError(enc->pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1585
0
        goto Error;
1586
0
      }
1587
0
      percent_range = remaining_percent / 4;
1588
0
      if (!EncodePalette(bw, low_effort, enc, percent_range, &percent)) {
1589
0
        goto Error;
1590
0
      }
1591
0
      remaining_percent -= percent_range;
1592
0
      if (!MapImageFromPalette(enc)) goto Error;
1593
      // If using a color cache, do not have it bigger than the number of
1594
      // colors.
1595
0
      if (enc->palette_size < (1 << MAX_COLOR_CACHE_BITS)) {
1596
0
        enc->cache_bits = BitsLog2Floor(enc->palette_size) + 1;
1597
0
      }
1598
0
    }
1599
    // In case image is not packed.
1600
0
    if (enc->argb_content != kEncoderNearLossless &&
1601
0
        enc->argb_content != kEncoderPalette) {
1602
0
      if (!MakeInputImageCopy(enc)) goto Error;
1603
0
    }
1604
1605
    // -------------------------------------------------------------------------
1606
    // Apply transforms and write transform data.
1607
1608
0
    if (enc->use_subtract_green) {
1609
0
      ApplySubtractGreen(enc, enc->current_width, height, bw);
1610
0
    }
1611
1612
0
    if (enc->use_predict) {
1613
0
      percent_range = remaining_percent / 3;
1614
0
      if (!ApplyPredictFilter(enc, enc->current_width, height, quality,
1615
0
                              low_effort, enc->use_subtract_green, bw,
1616
0
                              percent_range, &percent)) {
1617
0
        goto Error;
1618
0
      }
1619
0
      remaining_percent -= percent_range;
1620
0
    }
1621
1622
0
    if (enc->use_cross_color) {
1623
0
      percent_range = remaining_percent / 2;
1624
0
      if (!ApplyCrossColorFilter(enc, enc->current_width, height, quality,
1625
0
                                 low_effort, bw, percent_range, &percent)) {
1626
0
        goto Error;
1627
0
      }
1628
0
      remaining_percent -= percent_range;
1629
0
    }
1630
1631
0
    VP8LPutBits(bw, !TRANSFORM_PRESENT, 1);  // No more transforms.
1632
1633
    // -------------------------------------------------------------------------
1634
    // Encode and write the transformed image.
1635
0
    if (!EncodeImageInternal(
1636
0
            bw, enc->argb, &enc->hash_chain, enc->refs, enc->current_width,
1637
0
            height, quality, low_effort, &crunch_configs[idx],
1638
0
            &enc->cache_bits, enc->histo_bits, byte_position, &hdr_size,
1639
0
            &data_size, picture, remaining_percent, &percent)) {
1640
0
      goto Error;
1641
0
    }
1642
1643
    // If we are better than what we already have.
1644
0
    if (VP8LBitWriterNumBytes(bw) < best_size) {
1645
0
      best_size = VP8LBitWriterNumBytes(bw);
1646
      // Store the BitWriter.
1647
0
      VP8LBitWriterSwap(bw, &bw_best);
1648
0
#if !defined(WEBP_DISABLE_STATS)
1649
      // Update the stats.
1650
0
      if (stats != NULL) {
1651
0
        stats->lossless_features = 0;
1652
0
        if (enc->use_predict) stats->lossless_features |= 1;
1653
0
        if (enc->use_cross_color) stats->lossless_features |= 2;
1654
0
        if (enc->use_subtract_green) stats->lossless_features |= 4;
1655
0
        if (enc->use_palette) stats->lossless_features |= 8;
1656
0
        stats->histogram_bits = enc->histo_bits;
1657
0
        stats->transform_bits = enc->predictor_transform_bits;
1658
0
        stats->cross_color_transform_bits = enc->cross_color_transform_bits;
1659
0
        stats->cache_bits = enc->cache_bits;
1660
0
        stats->palette_size = enc->palette_size;
1661
0
        stats->lossless_size = (int)(best_size - byte_position);
1662
0
        stats->lossless_hdr_size = hdr_size;
1663
0
        stats->lossless_data_size = data_size;
1664
0
      }
1665
0
#endif
1666
0
    }
1667
    // Reset the bit writer for the following iteration if any.
1668
0
    if (num_crunch_configs > 1) VP8LBitWriterReset(&bw_init, bw);
1669
0
  }
1670
0
  VP8LBitWriterSwap(&bw_best, bw);
1671
1672
0
 Error:
1673
0
  VP8LBitWriterWipeOut(&bw_best);
1674
  // The hook should return false in case of error.
1675
0
  return (params->picture->error_code == VP8_ENC_OK);
1676
0
}
1677
1678
int VP8LEncodeStream(const WebPConfig* const config,
1679
                     const WebPPicture* const picture,
1680
0
                     VP8LBitWriter* const bw_main) {
1681
0
  VP8LEncoder* const enc_main = VP8LEncoderNew(config, picture);
1682
0
  VP8LEncoder* enc_side = NULL;
1683
0
  CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX];
1684
0
  int num_crunch_configs_main, num_crunch_configs_side = 0;
1685
0
  int idx;
1686
0
  int red_and_blue_always_zero = 0;
1687
0
  WebPWorker worker_main, worker_side;
1688
0
  StreamEncodeContext params_main, params_side;
1689
  // The main thread uses picture->stats, the side thread uses stats_side.
1690
0
  WebPAuxStats stats_side;
1691
0
  VP8LBitWriter bw_side;
1692
0
  WebPPicture picture_side;
1693
0
  const WebPWorkerInterface* const worker_interface = WebPGetWorkerInterface();
1694
0
  int ok_main;
1695
1696
0
  if (enc_main == NULL || !VP8LBitWriterInit(&bw_side, 0)) {
1697
0
    VP8LEncoderDelete(enc_main);
1698
0
    return WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1699
0
  }
1700
1701
  // Avoid "garbage value" error from Clang's static analysis tool.
1702
0
  if (!WebPPictureInit(&picture_side)) {
1703
0
    goto Error;
1704
0
  }
1705
1706
  // Analyze image (entropy, num_palettes etc)
1707
0
  if (!EncoderAnalyze(enc_main, crunch_configs, &num_crunch_configs_main,
1708
0
                      &red_and_blue_always_zero) ||
1709
0
      !EncoderInit(enc_main)) {
1710
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1711
0
    goto Error;
1712
0
  }
1713
1714
  // Split the configs between the main and side threads (if any).
1715
0
  if (config->thread_level > 0) {
1716
0
    num_crunch_configs_side = num_crunch_configs_main / 2;
1717
0
    for (idx = 0; idx < num_crunch_configs_side; ++idx) {
1718
0
      params_side.crunch_configs[idx] =
1719
0
          crunch_configs[num_crunch_configs_main - num_crunch_configs_side +
1720
0
                         idx];
1721
0
    }
1722
0
    params_side.num_crunch_configs = num_crunch_configs_side;
1723
0
  }
1724
0
  num_crunch_configs_main -= num_crunch_configs_side;
1725
0
  for (idx = 0; idx < num_crunch_configs_main; ++idx) {
1726
0
    params_main.crunch_configs[idx] = crunch_configs[idx];
1727
0
  }
1728
0
  params_main.num_crunch_configs = num_crunch_configs_main;
1729
1730
  // Fill in the parameters for the thread workers.
1731
0
  {
1732
0
    const int params_size = (num_crunch_configs_side > 0) ? 2 : 1;
1733
0
    for (idx = 0; idx < params_size; ++idx) {
1734
      // Create the parameters for each worker.
1735
0
      WebPWorker* const worker = (idx == 0) ? &worker_main : &worker_side;
1736
0
      StreamEncodeContext* const param =
1737
0
          (idx == 0) ? &params_main : &params_side;
1738
0
      param->config = config;
1739
0
      param->red_and_blue_always_zero = red_and_blue_always_zero;
1740
0
      if (idx == 0) {
1741
0
        param->picture = picture;
1742
0
        param->stats = picture->stats;
1743
0
        param->bw = bw_main;
1744
0
        param->enc = enc_main;
1745
0
      } else {
1746
        // Create a side picture (error_code is not thread-safe).
1747
0
        if (!WebPPictureView(picture, /*left=*/0, /*top=*/0, picture->width,
1748
0
                             picture->height, &picture_side)) {
1749
0
          assert(0);
1750
0
        }
1751
0
        picture_side.progress_hook = NULL;  // Progress hook is not thread-safe.
1752
0
        param->picture = &picture_side;  // No need to free a view afterwards.
1753
0
        param->stats = (picture->stats == NULL) ? NULL : &stats_side;
1754
        // Create a side bit writer.
1755
0
        if (!VP8LBitWriterClone(bw_main, &bw_side)) {
1756
0
          WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1757
0
          goto Error;
1758
0
        }
1759
0
        param->bw = &bw_side;
1760
        // Create a side encoder.
1761
0
        enc_side = VP8LEncoderNew(config, &picture_side);
1762
0
        if (enc_side == NULL || !EncoderInit(enc_side)) {
1763
0
          WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1764
0
          goto Error;
1765
0
        }
1766
        // Copy the values that were computed for the main encoder.
1767
0
        enc_side->histo_bits = enc_main->histo_bits;
1768
0
        enc_side->predictor_transform_bits =
1769
0
            enc_main->predictor_transform_bits;
1770
0
        enc_side->cross_color_transform_bits =
1771
0
            enc_main->cross_color_transform_bits;
1772
0
        enc_side->palette_size = enc_main->palette_size;
1773
0
        memcpy(enc_side->palette, enc_main->palette,
1774
0
               sizeof(enc_main->palette));
1775
0
        memcpy(enc_side->palette_sorted, enc_main->palette_sorted,
1776
0
               sizeof(enc_main->palette_sorted));
1777
0
        param->enc = enc_side;
1778
0
      }
1779
      // Create the workers.
1780
0
      worker_interface->Init(worker);
1781
0
      worker->data1 = param;
1782
0
      worker->data2 = NULL;
1783
0
      worker->hook = EncodeStreamHook;
1784
0
    }
1785
0
  }
1786
1787
  // Start the second thread if needed.
1788
0
  if (num_crunch_configs_side != 0) {
1789
0
    if (!worker_interface->Reset(&worker_side)) {
1790
0
      WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1791
0
      goto Error;
1792
0
    }
1793
0
#if !defined(WEBP_DISABLE_STATS)
1794
    // This line is here and not in the param initialization above to remove a
1795
    // Clang static analyzer warning.
1796
0
    if (picture->stats != NULL) {
1797
0
      memcpy(&stats_side, picture->stats, sizeof(stats_side));
1798
0
    }
1799
0
#endif
1800
0
    worker_interface->Launch(&worker_side);
1801
0
  }
1802
  // Execute the main thread.
1803
0
  worker_interface->Execute(&worker_main);
1804
0
  ok_main = worker_interface->Sync(&worker_main);
1805
0
  worker_interface->End(&worker_main);
1806
0
  if (num_crunch_configs_side != 0) {
1807
    // Wait for the second thread.
1808
0
    const int ok_side = worker_interface->Sync(&worker_side);
1809
0
    worker_interface->End(&worker_side);
1810
0
    if (!ok_main || !ok_side) {
1811
0
      if (picture->error_code == VP8_ENC_OK) {
1812
0
        assert(picture_side.error_code != VP8_ENC_OK);
1813
0
        WebPEncodingSetError(picture, picture_side.error_code);
1814
0
      }
1815
0
      goto Error;
1816
0
    }
1817
0
    if (VP8LBitWriterNumBytes(&bw_side) < VP8LBitWriterNumBytes(bw_main)) {
1818
0
      VP8LBitWriterSwap(bw_main, &bw_side);
1819
0
#if !defined(WEBP_DISABLE_STATS)
1820
0
      if (picture->stats != NULL) {
1821
0
        memcpy(picture->stats, &stats_side, sizeof(*picture->stats));
1822
0
      }
1823
0
#endif
1824
0
    }
1825
0
  }
1826
1827
0
 Error:
1828
0
  VP8LBitWriterWipeOut(&bw_side);
1829
0
  VP8LEncoderDelete(enc_main);
1830
0
  VP8LEncoderDelete(enc_side);
1831
0
  return (picture->error_code == VP8_ENC_OK);
1832
0
}
1833
1834
#undef CRUNCH_CONFIGS_MAX
1835
#undef CRUNCH_SUBCONFIGS_MAX
1836
1837
int VP8LEncodeImage(const WebPConfig* const config,
1838
0
                    const WebPPicture* const picture) {
1839
0
  int width, height;
1840
0
  int has_alpha;
1841
0
  size_t coded_size;
1842
0
  int percent = 0;
1843
0
  int initial_size;
1844
0
  VP8LBitWriter bw;
1845
1846
0
  if (picture == NULL) return 0;
1847
1848
0
  if (config == NULL || picture->argb == NULL) {
1849
0
    return WebPEncodingSetError(picture, VP8_ENC_ERROR_NULL_PARAMETER);
1850
0
  }
1851
1852
0
  width = picture->width;
1853
0
  height = picture->height;
1854
  // Initialize BitWriter with size corresponding to 16 bpp to photo images and
1855
  // 8 bpp for graphical images.
1856
0
  initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?
1857
0
      width * height : width * height * 2;
1858
0
  if (!VP8LBitWriterInit(&bw, initial_size)) {
1859
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1860
0
    goto Error;
1861
0
  }
1862
1863
0
  if (!WebPReportProgress(picture, 1, &percent)) {
1864
0
 UserAbort:
1865
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_USER_ABORT);
1866
0
    goto Error;
1867
0
  }
1868
  // Reset stats (for pure lossless coding)
1869
0
  if (picture->stats != NULL) {
1870
0
    WebPAuxStats* const stats = picture->stats;
1871
0
    memset(stats, 0, sizeof(*stats));
1872
0
    stats->PSNR[0] = 99.f;
1873
0
    stats->PSNR[1] = 99.f;
1874
0
    stats->PSNR[2] = 99.f;
1875
0
    stats->PSNR[3] = 99.f;
1876
0
    stats->PSNR[4] = 99.f;
1877
0
  }
1878
1879
  // Write image size.
1880
0
  if (!WriteImageSize(picture, &bw)) {
1881
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1882
0
    goto Error;
1883
0
  }
1884
1885
0
  has_alpha = WebPPictureHasTransparency(picture);
1886
  // Write the non-trivial Alpha flag and lossless version.
1887
0
  if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {
1888
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1889
0
    goto Error;
1890
0
  }
1891
1892
0
  if (!WebPReportProgress(picture, 2, &percent)) goto UserAbort;
1893
1894
  // Encode main image stream.
1895
0
  if (!VP8LEncodeStream(config, picture, &bw)) goto Error;
1896
1897
0
  if (!WebPReportProgress(picture, 99, &percent)) goto UserAbort;
1898
1899
  // Finish the RIFF chunk.
1900
0
  if (!WriteImage(picture, &bw, &coded_size)) goto Error;
1901
1902
0
  if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;
1903
1904
0
#if !defined(WEBP_DISABLE_STATS)
1905
  // Save size.
1906
0
  if (picture->stats != NULL) {
1907
0
    picture->stats->coded_size += (int)coded_size;
1908
0
    picture->stats->lossless_size = (int)coded_size;
1909
0
  }
1910
0
#endif
1911
1912
0
  if (picture->extra_info != NULL) {
1913
0
    const int mb_w = (width + 15) >> 4;
1914
0
    const int mb_h = (height + 15) >> 4;
1915
0
    memset(picture->extra_info, 0, mb_w * mb_h * sizeof(*picture->extra_info));
1916
0
  }
1917
1918
0
 Error:
1919
0
  if (bw.error) {
1920
0
    WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
1921
0
  }
1922
0
  VP8LBitWriterWipeOut(&bw);
1923
0
  return (picture->error_code == VP8_ENC_OK);
1924
0
}
1925
1926
//------------------------------------------------------------------------------