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