Path: blob/master/3rdparty/libwebp/src/enc/vp8l_enc.c
16344 views
// Copyright 2012 Google Inc. All Rights Reserved.1//2// Use of this source code is governed by a BSD-style license3// that can be found in the COPYING file in the root of the source4// tree. An additional intellectual property rights grant can be found5// in the file PATENTS. All contributing project authors may6// be found in the AUTHORS file in the root of the source tree.7// -----------------------------------------------------------------------------8//9// main entry for the lossless encoder.10//11// Author: Vikas Arora ([email protected])12//1314#include <assert.h>15#include <stdlib.h>1617#include "src/enc/backward_references_enc.h"18#include "src/enc/histogram_enc.h"19#include "src/enc/vp8i_enc.h"20#include "src/enc/vp8li_enc.h"21#include "src/dsp/lossless.h"22#include "src/dsp/lossless_common.h"23#include "src/utils/bit_writer_utils.h"24#include "src/utils/huffman_encode_utils.h"25#include "src/utils/utils.h"26#include "src/webp/format_constants.h"2728// Maximum number of histogram images (sub-blocks).29#define MAX_HUFF_IMAGE_SIZE 26003031// Palette reordering for smaller sum of deltas (and for smaller storage).3233static int PaletteCompareColorsForQsort(const void* p1, const void* p2) {34const uint32_t a = WebPMemToUint32((uint8_t*)p1);35const uint32_t b = WebPMemToUint32((uint8_t*)p2);36assert(a != b);37return (a < b) ? -1 : 1;38}3940static WEBP_INLINE uint32_t PaletteComponentDistance(uint32_t v) {41return (v <= 128) ? v : (256 - v);42}4344// Computes a value that is related to the entropy created by the45// palette entry diff.46//47// Note that the last & 0xff is a no-operation in the next statement, but48// removed by most compilers and is here only for regularity of the code.49static WEBP_INLINE uint32_t PaletteColorDistance(uint32_t col1, uint32_t col2) {50const uint32_t diff = VP8LSubPixels(col1, col2);51const int kMoreWeightForRGBThanForAlpha = 9;52uint32_t score;53score = PaletteComponentDistance((diff >> 0) & 0xff);54score += PaletteComponentDistance((diff >> 8) & 0xff);55score += PaletteComponentDistance((diff >> 16) & 0xff);56score *= kMoreWeightForRGBThanForAlpha;57score += PaletteComponentDistance((diff >> 24) & 0xff);58return score;59}6061static WEBP_INLINE void SwapColor(uint32_t* const col1, uint32_t* const col2) {62const uint32_t tmp = *col1;63*col1 = *col2;64*col2 = tmp;65}6667static void GreedyMinimizeDeltas(uint32_t palette[], int num_colors) {68// Find greedily always the closest color of the predicted color to minimize69// deltas in the palette. This reduces storage needs since the70// palette is stored with delta encoding.71uint32_t predict = 0x00000000;72int i, k;73for (i = 0; i < num_colors; ++i) {74int best_ix = i;75uint32_t best_score = ~0U;76for (k = i; k < num_colors; ++k) {77const uint32_t cur_score = PaletteColorDistance(palette[k], predict);78if (best_score > cur_score) {79best_score = cur_score;80best_ix = k;81}82}83SwapColor(&palette[best_ix], &palette[i]);84predict = palette[i];85}86}8788// The palette has been sorted by alpha. This function checks if the other89// components of the palette have a monotonic development with regards to90// position in the palette. If all have monotonic development, there is91// no benefit to re-organize them greedily. A monotonic development92// would be spotted in green-only situations (like lossy alpha) or gray-scale93// images.94static int PaletteHasNonMonotonousDeltas(uint32_t palette[], int num_colors) {95uint32_t predict = 0x000000;96int i;97uint8_t sign_found = 0x00;98for (i = 0; i < num_colors; ++i) {99const uint32_t diff = VP8LSubPixels(palette[i], predict);100const uint8_t rd = (diff >> 16) & 0xff;101const uint8_t gd = (diff >> 8) & 0xff;102const uint8_t bd = (diff >> 0) & 0xff;103if (rd != 0x00) {104sign_found |= (rd < 0x80) ? 1 : 2;105}106if (gd != 0x00) {107sign_found |= (gd < 0x80) ? 8 : 16;108}109if (bd != 0x00) {110sign_found |= (bd < 0x80) ? 64 : 128;111}112predict = palette[i];113}114return (sign_found & (sign_found << 1)) != 0; // two consequent signs.115}116117// -----------------------------------------------------------------------------118// Palette119120// If number of colors in the image is less than or equal to MAX_PALETTE_SIZE,121// creates a palette and returns true, else returns false.122static int AnalyzeAndCreatePalette(const WebPPicture* const pic,123int low_effort,124uint32_t palette[MAX_PALETTE_SIZE],125int* const palette_size) {126const int num_colors = WebPGetColorPalette(pic, palette);127if (num_colors > MAX_PALETTE_SIZE) {128*palette_size = 0;129return 0;130}131*palette_size = num_colors;132qsort(palette, num_colors, sizeof(*palette), PaletteCompareColorsForQsort);133if (!low_effort && PaletteHasNonMonotonousDeltas(palette, num_colors)) {134GreedyMinimizeDeltas(palette, num_colors);135}136return 1;137}138139// These five modes are evaluated and their respective entropy is computed.140typedef enum {141kDirect = 0,142kSpatial = 1,143kSubGreen = 2,144kSpatialSubGreen = 3,145kPalette = 4,146kNumEntropyIx = 5147} EntropyIx;148149typedef enum {150kHistoAlpha = 0,151kHistoAlphaPred,152kHistoGreen,153kHistoGreenPred,154kHistoRed,155kHistoRedPred,156kHistoBlue,157kHistoBluePred,158kHistoRedSubGreen,159kHistoRedPredSubGreen,160kHistoBlueSubGreen,161kHistoBluePredSubGreen,162kHistoPalette,163kHistoTotal // Must be last.164} HistoIx;165166static void AddSingleSubGreen(int p, uint32_t* const r, uint32_t* const b) {167const int green = p >> 8; // The upper bits are masked away later.168++r[((p >> 16) - green) & 0xff];169++b[((p >> 0) - green) & 0xff];170}171172static void AddSingle(uint32_t p,173uint32_t* const a, uint32_t* const r,174uint32_t* const g, uint32_t* const b) {175++a[(p >> 24) & 0xff];176++r[(p >> 16) & 0xff];177++g[(p >> 8) & 0xff];178++b[(p >> 0) & 0xff];179}180181static WEBP_INLINE uint32_t HashPix(uint32_t pix) {182// Note that masking with 0xffffffffu is for preventing an183// 'unsigned int overflow' warning. Doesn't impact the compiled code.184return ((((uint64_t)pix + (pix >> 19)) * 0x39c5fba7ull) & 0xffffffffu) >> 24;185}186187static int AnalyzeEntropy(const uint32_t* argb,188int width, int height, int argb_stride,189int use_palette,190int palette_size, int transform_bits,191EntropyIx* const min_entropy_ix,192int* const red_and_blue_always_zero) {193// Allocate histogram set with cache_bits = 0.194uint32_t* histo;195196if (use_palette && palette_size <= 16) {197// In the case of small palettes, we pack 2, 4 or 8 pixels together. In198// practice, small palettes are better than any other transform.199*min_entropy_ix = kPalette;200*red_and_blue_always_zero = 1;201return 1;202}203histo = (uint32_t*)WebPSafeCalloc(kHistoTotal, sizeof(*histo) * 256);204if (histo != NULL) {205int i, x, y;206const uint32_t* prev_row = NULL;207const uint32_t* curr_row = argb;208uint32_t pix_prev = argb[0]; // Skip the first pixel.209for (y = 0; y < height; ++y) {210for (x = 0; x < width; ++x) {211const uint32_t pix = curr_row[x];212const uint32_t pix_diff = VP8LSubPixels(pix, pix_prev);213pix_prev = pix;214if ((pix_diff == 0) || (prev_row != NULL && pix == prev_row[x])) {215continue;216}217AddSingle(pix,218&histo[kHistoAlpha * 256],219&histo[kHistoRed * 256],220&histo[kHistoGreen * 256],221&histo[kHistoBlue * 256]);222AddSingle(pix_diff,223&histo[kHistoAlphaPred * 256],224&histo[kHistoRedPred * 256],225&histo[kHistoGreenPred * 256],226&histo[kHistoBluePred * 256]);227AddSingleSubGreen(pix,228&histo[kHistoRedSubGreen * 256],229&histo[kHistoBlueSubGreen * 256]);230AddSingleSubGreen(pix_diff,231&histo[kHistoRedPredSubGreen * 256],232&histo[kHistoBluePredSubGreen * 256]);233{234// Approximate the palette by the entropy of the multiplicative hash.235const uint32_t hash = HashPix(pix);236++histo[kHistoPalette * 256 + hash];237}238}239prev_row = curr_row;240curr_row += argb_stride;241}242{243double entropy_comp[kHistoTotal];244double entropy[kNumEntropyIx];245int k;246int last_mode_to_analyze = use_palette ? kPalette : kSpatialSubGreen;247int j;248// Let's add one zero to the predicted histograms. The zeros are removed249// too efficiently by the pix_diff == 0 comparison, at least one of the250// zeros is likely to exist.251++histo[kHistoRedPredSubGreen * 256];252++histo[kHistoBluePredSubGreen * 256];253++histo[kHistoRedPred * 256];254++histo[kHistoGreenPred * 256];255++histo[kHistoBluePred * 256];256++histo[kHistoAlphaPred * 256];257258for (j = 0; j < kHistoTotal; ++j) {259entropy_comp[j] = VP8LBitsEntropy(&histo[j * 256], 256);260}261entropy[kDirect] = entropy_comp[kHistoAlpha] +262entropy_comp[kHistoRed] +263entropy_comp[kHistoGreen] +264entropy_comp[kHistoBlue];265entropy[kSpatial] = entropy_comp[kHistoAlphaPred] +266entropy_comp[kHistoRedPred] +267entropy_comp[kHistoGreenPred] +268entropy_comp[kHistoBluePred];269entropy[kSubGreen] = entropy_comp[kHistoAlpha] +270entropy_comp[kHistoRedSubGreen] +271entropy_comp[kHistoGreen] +272entropy_comp[kHistoBlueSubGreen];273entropy[kSpatialSubGreen] = entropy_comp[kHistoAlphaPred] +274entropy_comp[kHistoRedPredSubGreen] +275entropy_comp[kHistoGreenPred] +276entropy_comp[kHistoBluePredSubGreen];277entropy[kPalette] = entropy_comp[kHistoPalette];278279// When including transforms, there is an overhead in bits from280// storing them. This overhead is small but matters for small images.281// For spatial, there are 14 transformations.282entropy[kSpatial] += VP8LSubSampleSize(width, transform_bits) *283VP8LSubSampleSize(height, transform_bits) *284VP8LFastLog2(14);285// For color transforms: 24 as only 3 channels are considered in a286// ColorTransformElement.287entropy[kSpatialSubGreen] += VP8LSubSampleSize(width, transform_bits) *288VP8LSubSampleSize(height, transform_bits) *289VP8LFastLog2(24);290// For palettes, add the cost of storing the palette.291// We empirically estimate the cost of a compressed entry as 8 bits.292// The palette is differential-coded when compressed hence a much293// lower cost than sizeof(uint32_t)*8.294entropy[kPalette] += palette_size * 8;295296*min_entropy_ix = kDirect;297for (k = kDirect + 1; k <= last_mode_to_analyze; ++k) {298if (entropy[*min_entropy_ix] > entropy[k]) {299*min_entropy_ix = (EntropyIx)k;300}301}302assert((int)*min_entropy_ix <= last_mode_to_analyze);303*red_and_blue_always_zero = 1;304// Let's check if the histogram of the chosen entropy mode has305// non-zero red and blue values. If all are zero, we can later skip306// the cross color optimization.307{308static const uint8_t kHistoPairs[5][2] = {309{ kHistoRed, kHistoBlue },310{ kHistoRedPred, kHistoBluePred },311{ kHistoRedSubGreen, kHistoBlueSubGreen },312{ kHistoRedPredSubGreen, kHistoBluePredSubGreen },313{ kHistoRed, kHistoBlue }314};315const uint32_t* const red_histo =316&histo[256 * kHistoPairs[*min_entropy_ix][0]];317const uint32_t* const blue_histo =318&histo[256 * kHistoPairs[*min_entropy_ix][1]];319for (i = 1; i < 256; ++i) {320if ((red_histo[i] | blue_histo[i]) != 0) {321*red_and_blue_always_zero = 0;322break;323}324}325}326}327WebPSafeFree(histo);328return 1;329} else {330return 0;331}332}333334static int GetHistoBits(int method, int use_palette, int width, int height) {335// Make tile size a function of encoding method (Range: 0 to 6).336int histo_bits = (use_palette ? 9 : 7) - method;337while (1) {338const int huff_image_size = VP8LSubSampleSize(width, histo_bits) *339VP8LSubSampleSize(height, histo_bits);340if (huff_image_size <= MAX_HUFF_IMAGE_SIZE) break;341++histo_bits;342}343return (histo_bits < MIN_HUFFMAN_BITS) ? MIN_HUFFMAN_BITS :344(histo_bits > MAX_HUFFMAN_BITS) ? MAX_HUFFMAN_BITS : histo_bits;345}346347static int GetTransformBits(int method, int histo_bits) {348const int max_transform_bits = (method < 4) ? 6 : (method > 4) ? 4 : 5;349const int res =350(histo_bits > max_transform_bits) ? max_transform_bits : histo_bits;351assert(res <= MAX_TRANSFORM_BITS);352return res;353}354355// Set of parameters to be used in each iteration of the cruncher.356#define CRUNCH_CONFIGS_LZ77_MAX 2357typedef struct {358int entropy_idx_;359int lz77s_types_to_try_[CRUNCH_CONFIGS_LZ77_MAX];360int lz77s_types_to_try_size_;361} CrunchConfig;362363#define CRUNCH_CONFIGS_MAX kNumEntropyIx364365static int EncoderAnalyze(VP8LEncoder* const enc,366CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX],367int* const crunch_configs_size,368int* const red_and_blue_always_zero) {369const WebPPicture* const pic = enc->pic_;370const int width = pic->width;371const int height = pic->height;372const WebPConfig* const config = enc->config_;373const int method = config->method;374const int low_effort = (config->method == 0);375int i;376int use_palette;377int n_lz77s;378assert(pic != NULL && pic->argb != NULL);379380use_palette =381AnalyzeAndCreatePalette(pic, low_effort,382enc->palette_, &enc->palette_size_);383384// Empirical bit sizes.385enc->histo_bits_ = GetHistoBits(method, use_palette,386pic->width, pic->height);387enc->transform_bits_ = GetTransformBits(method, enc->histo_bits_);388389if (low_effort) {390// AnalyzeEntropy is somewhat slow.391crunch_configs[0].entropy_idx_ = use_palette ? kPalette : kSpatialSubGreen;392n_lz77s = 1;393*crunch_configs_size = 1;394} else {395EntropyIx min_entropy_ix;396// Try out multiple LZ77 on images with few colors.397n_lz77s = (enc->palette_size_ > 0 && enc->palette_size_ <= 16) ? 2 : 1;398if (!AnalyzeEntropy(pic->argb, width, height, pic->argb_stride, use_palette,399enc->palette_size_, enc->transform_bits_,400&min_entropy_ix, red_and_blue_always_zero)) {401return 0;402}403if (method == 6 && config->quality == 100) {404// Go brute force on all transforms.405*crunch_configs_size = 0;406for (i = 0; i < kNumEntropyIx; ++i) {407if (i != kPalette || use_palette) {408assert(*crunch_configs_size < CRUNCH_CONFIGS_MAX);409crunch_configs[(*crunch_configs_size)++].entropy_idx_ = i;410}411}412} else {413// Only choose the guessed best transform.414*crunch_configs_size = 1;415crunch_configs[0].entropy_idx_ = min_entropy_ix;416}417}418// Fill in the different LZ77s.419assert(n_lz77s <= CRUNCH_CONFIGS_LZ77_MAX);420for (i = 0; i < *crunch_configs_size; ++i) {421int j;422for (j = 0; j < n_lz77s; ++j) {423crunch_configs[i].lz77s_types_to_try_[j] =424(j == 0) ? kLZ77Standard | kLZ77RLE : kLZ77Box;425}426crunch_configs[i].lz77s_types_to_try_size_ = n_lz77s;427}428return 1;429}430431static int EncoderInit(VP8LEncoder* const enc) {432const WebPPicture* const pic = enc->pic_;433const int width = pic->width;434const int height = pic->height;435const int pix_cnt = width * height;436// we round the block size up, so we're guaranteed to have437// at most MAX_REFS_BLOCK_PER_IMAGE blocks used:438const int refs_block_size = (pix_cnt - 1) / MAX_REFS_BLOCK_PER_IMAGE + 1;439int i;440if (!VP8LHashChainInit(&enc->hash_chain_, pix_cnt)) return 0;441442for (i = 0; i < 3; ++i) VP8LBackwardRefsInit(&enc->refs_[i], refs_block_size);443444return 1;445}446447// Returns false in case of memory error.448static int GetHuffBitLengthsAndCodes(449const VP8LHistogramSet* const histogram_image,450HuffmanTreeCode* const huffman_codes) {451int i, k;452int ok = 0;453uint64_t total_length_size = 0;454uint8_t* mem_buf = NULL;455const int histogram_image_size = histogram_image->size;456int max_num_symbols = 0;457uint8_t* buf_rle = NULL;458HuffmanTree* huff_tree = NULL;459460// Iterate over all histograms and get the aggregate number of codes used.461for (i = 0; i < histogram_image_size; ++i) {462const VP8LHistogram* const histo = histogram_image->histograms[i];463HuffmanTreeCode* const codes = &huffman_codes[5 * i];464for (k = 0; k < 5; ++k) {465const int num_symbols =466(k == 0) ? VP8LHistogramNumCodes(histo->palette_code_bits_) :467(k == 4) ? NUM_DISTANCE_CODES : 256;468codes[k].num_symbols = num_symbols;469total_length_size += num_symbols;470}471}472473// Allocate and Set Huffman codes.474{475uint16_t* codes;476uint8_t* lengths;477mem_buf = (uint8_t*)WebPSafeCalloc(total_length_size,478sizeof(*lengths) + sizeof(*codes));479if (mem_buf == NULL) goto End;480481codes = (uint16_t*)mem_buf;482lengths = (uint8_t*)&codes[total_length_size];483for (i = 0; i < 5 * histogram_image_size; ++i) {484const int bit_length = huffman_codes[i].num_symbols;485huffman_codes[i].codes = codes;486huffman_codes[i].code_lengths = lengths;487codes += bit_length;488lengths += bit_length;489if (max_num_symbols < bit_length) {490max_num_symbols = bit_length;491}492}493}494495buf_rle = (uint8_t*)WebPSafeMalloc(1ULL, max_num_symbols);496huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * max_num_symbols,497sizeof(*huff_tree));498if (buf_rle == NULL || huff_tree == NULL) goto End;499500// Create Huffman trees.501for (i = 0; i < histogram_image_size; ++i) {502HuffmanTreeCode* const codes = &huffman_codes[5 * i];503VP8LHistogram* const histo = histogram_image->histograms[i];504VP8LCreateHuffmanTree(histo->literal_, 15, buf_rle, huff_tree, codes + 0);505VP8LCreateHuffmanTree(histo->red_, 15, buf_rle, huff_tree, codes + 1);506VP8LCreateHuffmanTree(histo->blue_, 15, buf_rle, huff_tree, codes + 2);507VP8LCreateHuffmanTree(histo->alpha_, 15, buf_rle, huff_tree, codes + 3);508VP8LCreateHuffmanTree(histo->distance_, 15, buf_rle, huff_tree, codes + 4);509}510ok = 1;511End:512WebPSafeFree(huff_tree);513WebPSafeFree(buf_rle);514if (!ok) {515WebPSafeFree(mem_buf);516memset(huffman_codes, 0, 5 * histogram_image_size * sizeof(*huffman_codes));517}518return ok;519}520521static void StoreHuffmanTreeOfHuffmanTreeToBitMask(522VP8LBitWriter* const bw, const uint8_t* code_length_bitdepth) {523// RFC 1951 will calm you down if you are worried about this funny sequence.524// This sequence is tuned from that, but more weighted for lower symbol count,525// and more spiking histograms.526static const uint8_t kStorageOrder[CODE_LENGTH_CODES] = {52717, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15528};529int i;530// Throw away trailing zeros:531int codes_to_store = CODE_LENGTH_CODES;532for (; codes_to_store > 4; --codes_to_store) {533if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {534break;535}536}537VP8LPutBits(bw, codes_to_store - 4, 4);538for (i = 0; i < codes_to_store; ++i) {539VP8LPutBits(bw, code_length_bitdepth[kStorageOrder[i]], 3);540}541}542543static void ClearHuffmanTreeIfOnlyOneSymbol(544HuffmanTreeCode* const huffman_code) {545int k;546int count = 0;547for (k = 0; k < huffman_code->num_symbols; ++k) {548if (huffman_code->code_lengths[k] != 0) {549++count;550if (count > 1) return;551}552}553for (k = 0; k < huffman_code->num_symbols; ++k) {554huffman_code->code_lengths[k] = 0;555huffman_code->codes[k] = 0;556}557}558559static void StoreHuffmanTreeToBitMask(560VP8LBitWriter* const bw,561const HuffmanTreeToken* const tokens, const int num_tokens,562const HuffmanTreeCode* const huffman_code) {563int i;564for (i = 0; i < num_tokens; ++i) {565const int ix = tokens[i].code;566const int extra_bits = tokens[i].extra_bits;567VP8LPutBits(bw, huffman_code->codes[ix], huffman_code->code_lengths[ix]);568switch (ix) {569case 16:570VP8LPutBits(bw, extra_bits, 2);571break;572case 17:573VP8LPutBits(bw, extra_bits, 3);574break;575case 18:576VP8LPutBits(bw, extra_bits, 7);577break;578}579}580}581582// 'huff_tree' and 'tokens' are pre-alloacted buffers.583static void StoreFullHuffmanCode(VP8LBitWriter* const bw,584HuffmanTree* const huff_tree,585HuffmanTreeToken* const tokens,586const HuffmanTreeCode* const tree) {587uint8_t code_length_bitdepth[CODE_LENGTH_CODES] = { 0 };588uint16_t code_length_bitdepth_symbols[CODE_LENGTH_CODES] = { 0 };589const int max_tokens = tree->num_symbols;590int num_tokens;591HuffmanTreeCode huffman_code;592huffman_code.num_symbols = CODE_LENGTH_CODES;593huffman_code.code_lengths = code_length_bitdepth;594huffman_code.codes = code_length_bitdepth_symbols;595596VP8LPutBits(bw, 0, 1);597num_tokens = VP8LCreateCompressedHuffmanTree(tree, tokens, max_tokens);598{599uint32_t histogram[CODE_LENGTH_CODES] = { 0 };600uint8_t buf_rle[CODE_LENGTH_CODES] = { 0 };601int i;602for (i = 0; i < num_tokens; ++i) {603++histogram[tokens[i].code];604}605606VP8LCreateHuffmanTree(histogram, 7, buf_rle, huff_tree, &huffman_code);607}608609StoreHuffmanTreeOfHuffmanTreeToBitMask(bw, code_length_bitdepth);610ClearHuffmanTreeIfOnlyOneSymbol(&huffman_code);611{612int trailing_zero_bits = 0;613int trimmed_length = num_tokens;614int write_trimmed_length;615int length;616int i = num_tokens;617while (i-- > 0) {618const int ix = tokens[i].code;619if (ix == 0 || ix == 17 || ix == 18) {620--trimmed_length; // discount trailing zeros621trailing_zero_bits += code_length_bitdepth[ix];622if (ix == 17) {623trailing_zero_bits += 3;624} else if (ix == 18) {625trailing_zero_bits += 7;626}627} else {628break;629}630}631write_trimmed_length = (trimmed_length > 1 && trailing_zero_bits > 12);632length = write_trimmed_length ? trimmed_length : num_tokens;633VP8LPutBits(bw, write_trimmed_length, 1);634if (write_trimmed_length) {635if (trimmed_length == 2) {636VP8LPutBits(bw, 0, 3 + 2); // nbitpairs=1, trimmed_length=2637} else {638const int nbits = BitsLog2Floor(trimmed_length - 2);639const int nbitpairs = nbits / 2 + 1;640assert(trimmed_length > 2);641assert(nbitpairs - 1 < 8);642VP8LPutBits(bw, nbitpairs - 1, 3);643VP8LPutBits(bw, trimmed_length - 2, nbitpairs * 2);644}645}646StoreHuffmanTreeToBitMask(bw, tokens, length, &huffman_code);647}648}649650// 'huff_tree' and 'tokens' are pre-alloacted buffers.651static void StoreHuffmanCode(VP8LBitWriter* const bw,652HuffmanTree* const huff_tree,653HuffmanTreeToken* const tokens,654const HuffmanTreeCode* const huffman_code) {655int i;656int count = 0;657int symbols[2] = { 0, 0 };658const int kMaxBits = 8;659const int kMaxSymbol = 1 << kMaxBits;660661// Check whether it's a small tree.662for (i = 0; i < huffman_code->num_symbols && count < 3; ++i) {663if (huffman_code->code_lengths[i] != 0) {664if (count < 2) symbols[count] = i;665++count;666}667}668669if (count == 0) { // emit minimal tree for empty cases670// bits: small tree marker: 1, count-1: 0, large 8-bit code: 0, code: 0671VP8LPutBits(bw, 0x01, 4);672} else if (count <= 2 && symbols[0] < kMaxSymbol && symbols[1] < kMaxSymbol) {673VP8LPutBits(bw, 1, 1); // Small tree marker to encode 1 or 2 symbols.674VP8LPutBits(bw, count - 1, 1);675if (symbols[0] <= 1) {676VP8LPutBits(bw, 0, 1); // Code bit for small (1 bit) symbol value.677VP8LPutBits(bw, symbols[0], 1);678} else {679VP8LPutBits(bw, 1, 1);680VP8LPutBits(bw, symbols[0], 8);681}682if (count == 2) {683VP8LPutBits(bw, symbols[1], 8);684}685} else {686StoreFullHuffmanCode(bw, huff_tree, tokens, huffman_code);687}688}689690static WEBP_INLINE void WriteHuffmanCode(VP8LBitWriter* const bw,691const HuffmanTreeCode* const code,692int code_index) {693const int depth = code->code_lengths[code_index];694const int symbol = code->codes[code_index];695VP8LPutBits(bw, symbol, depth);696}697698static WEBP_INLINE void WriteHuffmanCodeWithExtraBits(699VP8LBitWriter* const bw,700const HuffmanTreeCode* const code,701int code_index,702int bits,703int n_bits) {704const int depth = code->code_lengths[code_index];705const int symbol = code->codes[code_index];706VP8LPutBits(bw, (bits << depth) | symbol, depth + n_bits);707}708709static WebPEncodingError StoreImageToBitMask(710VP8LBitWriter* const bw, int width, int histo_bits,711const VP8LBackwardRefs* const refs,712const uint16_t* histogram_symbols,713const HuffmanTreeCode* const huffman_codes) {714const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;715const int tile_mask = (histo_bits == 0) ? 0 : -(1 << histo_bits);716// x and y trace the position in the image.717int x = 0;718int y = 0;719int tile_x = x & tile_mask;720int tile_y = y & tile_mask;721int histogram_ix = histogram_symbols[0];722const HuffmanTreeCode* codes = huffman_codes + 5 * histogram_ix;723VP8LRefsCursor c = VP8LRefsCursorInit(refs);724while (VP8LRefsCursorOk(&c)) {725const PixOrCopy* const v = c.cur_pos;726if ((tile_x != (x & tile_mask)) || (tile_y != (y & tile_mask))) {727tile_x = x & tile_mask;728tile_y = y & tile_mask;729histogram_ix = histogram_symbols[(y >> histo_bits) * histo_xsize +730(x >> histo_bits)];731codes = huffman_codes + 5 * histogram_ix;732}733if (PixOrCopyIsLiteral(v)) {734static const uint8_t order[] = { 1, 2, 0, 3 };735int k;736for (k = 0; k < 4; ++k) {737const int code = PixOrCopyLiteral(v, order[k]);738WriteHuffmanCode(bw, codes + k, code);739}740} else if (PixOrCopyIsCacheIdx(v)) {741const int code = PixOrCopyCacheIdx(v);742const int literal_ix = 256 + NUM_LENGTH_CODES + code;743WriteHuffmanCode(bw, codes, literal_ix);744} else {745int bits, n_bits;746int code;747748const int distance = PixOrCopyDistance(v);749VP8LPrefixEncode(v->len, &code, &n_bits, &bits);750WriteHuffmanCodeWithExtraBits(bw, codes, 256 + code, bits, n_bits);751752// Don't write the distance with the extra bits code since753// the distance can be up to 18 bits of extra bits, and the prefix754// 15 bits, totaling to 33, and our PutBits only supports up to 32 bits.755VP8LPrefixEncode(distance, &code, &n_bits, &bits);756WriteHuffmanCode(bw, codes + 4, code);757VP8LPutBits(bw, bits, n_bits);758}759x += PixOrCopyLength(v);760while (x >= width) {761x -= width;762++y;763}764VP8LRefsCursorNext(&c);765}766return bw->error_ ? VP8_ENC_ERROR_OUT_OF_MEMORY : VP8_ENC_OK;767}768769// Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31770static WebPEncodingError EncodeImageNoHuffman(VP8LBitWriter* const bw,771const uint32_t* const argb,772VP8LHashChain* const hash_chain,773VP8LBackwardRefs* const refs_tmp1,774VP8LBackwardRefs* const refs_tmp2,775int width, int height,776int quality, int low_effort) {777int i;778int max_tokens = 0;779WebPEncodingError err = VP8_ENC_OK;780VP8LBackwardRefs* refs;781HuffmanTreeToken* tokens = NULL;782HuffmanTreeCode huffman_codes[5] = { { 0, NULL, NULL } };783const uint16_t histogram_symbols[1] = { 0 }; // only one tree, one symbol784int cache_bits = 0;785VP8LHistogramSet* histogram_image = NULL;786HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(7873ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));788if (huff_tree == NULL) {789err = VP8_ENC_ERROR_OUT_OF_MEMORY;790goto Error;791}792793// Calculate backward references from ARGB image.794if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,795low_effort)) {796err = VP8_ENC_ERROR_OUT_OF_MEMORY;797goto Error;798}799refs = VP8LGetBackwardReferences(width, height, argb, quality, 0,800kLZ77Standard | kLZ77RLE, &cache_bits,801hash_chain, refs_tmp1, refs_tmp2);802if (refs == NULL) {803err = VP8_ENC_ERROR_OUT_OF_MEMORY;804goto Error;805}806histogram_image = VP8LAllocateHistogramSet(1, cache_bits);807if (histogram_image == NULL) {808err = VP8_ENC_ERROR_OUT_OF_MEMORY;809goto Error;810}811812// Build histogram image and symbols from backward references.813VP8LHistogramStoreRefs(refs, histogram_image->histograms[0]);814815// Create Huffman bit lengths and codes for each histogram image.816assert(histogram_image->size == 1);817if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {818err = VP8_ENC_ERROR_OUT_OF_MEMORY;819goto Error;820}821822// No color cache, no Huffman image.823VP8LPutBits(bw, 0, 1);824825// Find maximum number of symbols for the huffman tree-set.826for (i = 0; i < 5; ++i) {827HuffmanTreeCode* const codes = &huffman_codes[i];828if (max_tokens < codes->num_symbols) {829max_tokens = codes->num_symbols;830}831}832833tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));834if (tokens == NULL) {835err = VP8_ENC_ERROR_OUT_OF_MEMORY;836goto Error;837}838839// Store Huffman codes.840for (i = 0; i < 5; ++i) {841HuffmanTreeCode* const codes = &huffman_codes[i];842StoreHuffmanCode(bw, huff_tree, tokens, codes);843ClearHuffmanTreeIfOnlyOneSymbol(codes);844}845846// Store actual literals.847err = StoreImageToBitMask(bw, width, 0, refs, histogram_symbols,848huffman_codes);849850Error:851WebPSafeFree(tokens);852WebPSafeFree(huff_tree);853VP8LFreeHistogramSet(histogram_image);854WebPSafeFree(huffman_codes[0].codes);855return err;856}857858static WebPEncodingError EncodeImageInternal(859VP8LBitWriter* const bw, const uint32_t* const argb,860VP8LHashChain* const hash_chain, VP8LBackwardRefs refs_array[3], int width,861int height, int quality, int low_effort, int use_cache,862const CrunchConfig* const config, int* cache_bits, int histogram_bits,863size_t init_byte_position, int* const hdr_size, int* const data_size) {864WebPEncodingError err = VP8_ENC_OK;865const uint32_t histogram_image_xysize =866VP8LSubSampleSize(width, histogram_bits) *867VP8LSubSampleSize(height, histogram_bits);868VP8LHistogramSet* histogram_image = NULL;869VP8LHistogram* tmp_histo = NULL;870int histogram_image_size = 0;871size_t bit_array_size = 0;872HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(8733ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));874HuffmanTreeToken* tokens = NULL;875HuffmanTreeCode* huffman_codes = NULL;876VP8LBackwardRefs* refs_best;877VP8LBackwardRefs* refs_tmp;878uint16_t* const histogram_symbols =879(uint16_t*)WebPSafeMalloc(histogram_image_xysize,880sizeof(*histogram_symbols));881int lz77s_idx;882VP8LBitWriter bw_init = *bw, bw_best;883int hdr_size_tmp;884assert(histogram_bits >= MIN_HUFFMAN_BITS);885assert(histogram_bits <= MAX_HUFFMAN_BITS);886assert(hdr_size != NULL);887assert(data_size != NULL);888889if (histogram_symbols == NULL) {890err = VP8_ENC_ERROR_OUT_OF_MEMORY;891goto Error;892}893894if (use_cache) {895// If the value is different from zero, it has been set during the896// palette analysis.897if (*cache_bits == 0) *cache_bits = MAX_COLOR_CACHE_BITS;898} else {899*cache_bits = 0;900}901// 'best_refs' is the reference to the best backward refs and points to one902// of refs_array[0] or refs_array[1].903// Calculate backward references from ARGB image.904if (huff_tree == NULL ||905!VP8LHashChainFill(hash_chain, quality, argb, width, height,906low_effort) ||907!VP8LBitWriterInit(&bw_best, 0) ||908(config->lz77s_types_to_try_size_ > 1 &&909!VP8LBitWriterClone(bw, &bw_best))) {910err = VP8_ENC_ERROR_OUT_OF_MEMORY;911goto Error;912}913for (lz77s_idx = 0; lz77s_idx < config->lz77s_types_to_try_size_;914++lz77s_idx) {915refs_best = VP8LGetBackwardReferences(916width, height, argb, quality, low_effort,917config->lz77s_types_to_try_[lz77s_idx], cache_bits, hash_chain,918&refs_array[0], &refs_array[1]);919if (refs_best == NULL) {920err = VP8_ENC_ERROR_OUT_OF_MEMORY;921goto Error;922}923// Keep the best references aside and use the other element from the first924// two as a temporary for later usage.925refs_tmp = &refs_array[refs_best == &refs_array[0] ? 1 : 0];926927histogram_image =928VP8LAllocateHistogramSet(histogram_image_xysize, *cache_bits);929tmp_histo = VP8LAllocateHistogram(*cache_bits);930if (histogram_image == NULL || tmp_histo == NULL) {931err = VP8_ENC_ERROR_OUT_OF_MEMORY;932goto Error;933}934935// Build histogram image and symbols from backward references.936if (!VP8LGetHistoImageSymbols(width, height, refs_best, quality, low_effort,937histogram_bits, *cache_bits, histogram_image,938tmp_histo, histogram_symbols)) {939err = VP8_ENC_ERROR_OUT_OF_MEMORY;940goto Error;941}942// Create Huffman bit lengths and codes for each histogram image.943histogram_image_size = histogram_image->size;944bit_array_size = 5 * histogram_image_size;945huffman_codes = (HuffmanTreeCode*)WebPSafeCalloc(bit_array_size,946sizeof(*huffman_codes));947// Note: some histogram_image entries may point to tmp_histos[], so the948// latter need to outlive the following call to GetHuffBitLengthsAndCodes().949if (huffman_codes == NULL ||950!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {951err = VP8_ENC_ERROR_OUT_OF_MEMORY;952goto Error;953}954// Free combined histograms.955VP8LFreeHistogramSet(histogram_image);956histogram_image = NULL;957958// Free scratch histograms.959VP8LFreeHistogram(tmp_histo);960tmp_histo = NULL;961962// Color Cache parameters.963if (*cache_bits > 0) {964VP8LPutBits(bw, 1, 1);965VP8LPutBits(bw, *cache_bits, 4);966} else {967VP8LPutBits(bw, 0, 1);968}969970// Huffman image + meta huffman.971{972const int write_histogram_image = (histogram_image_size > 1);973VP8LPutBits(bw, write_histogram_image, 1);974if (write_histogram_image) {975uint32_t* const histogram_argb =976(uint32_t*)WebPSafeMalloc(histogram_image_xysize,977sizeof(*histogram_argb));978int max_index = 0;979uint32_t i;980if (histogram_argb == NULL) {981err = VP8_ENC_ERROR_OUT_OF_MEMORY;982goto Error;983}984for (i = 0; i < histogram_image_xysize; ++i) {985const int symbol_index = histogram_symbols[i] & 0xffff;986histogram_argb[i] = (symbol_index << 8);987if (symbol_index >= max_index) {988max_index = symbol_index + 1;989}990}991histogram_image_size = max_index;992993VP8LPutBits(bw, histogram_bits - 2, 3);994err = EncodeImageNoHuffman(995bw, histogram_argb, hash_chain, refs_tmp, &refs_array[2],996VP8LSubSampleSize(width, histogram_bits),997VP8LSubSampleSize(height, histogram_bits), quality, low_effort);998WebPSafeFree(histogram_argb);999if (err != VP8_ENC_OK) goto Error;1000}1001}10021003// Store Huffman codes.1004{1005int i;1006int max_tokens = 0;1007// Find maximum number of symbols for the huffman tree-set.1008for (i = 0; i < 5 * histogram_image_size; ++i) {1009HuffmanTreeCode* const codes = &huffman_codes[i];1010if (max_tokens < codes->num_symbols) {1011max_tokens = codes->num_symbols;1012}1013}1014tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));1015if (tokens == NULL) {1016err = VP8_ENC_ERROR_OUT_OF_MEMORY;1017goto Error;1018}1019for (i = 0; i < 5 * histogram_image_size; ++i) {1020HuffmanTreeCode* const codes = &huffman_codes[i];1021StoreHuffmanCode(bw, huff_tree, tokens, codes);1022ClearHuffmanTreeIfOnlyOneSymbol(codes);1023}1024}1025// Store actual literals.1026hdr_size_tmp = (int)(VP8LBitWriterNumBytes(bw) - init_byte_position);1027err = StoreImageToBitMask(bw, width, histogram_bits, refs_best,1028histogram_symbols, huffman_codes);1029// Keep track of the smallest image so far.1030if (lz77s_idx == 0 ||1031VP8LBitWriterNumBytes(bw) < VP8LBitWriterNumBytes(&bw_best)) {1032*hdr_size = hdr_size_tmp;1033*data_size =1034(int)(VP8LBitWriterNumBytes(bw) - init_byte_position - *hdr_size);1035VP8LBitWriterSwap(bw, &bw_best);1036}1037// Reset the bit writer for the following iteration if any.1038if (config->lz77s_types_to_try_size_ > 1) VP8LBitWriterReset(&bw_init, bw);1039WebPSafeFree(tokens);1040tokens = NULL;1041if (huffman_codes != NULL) {1042WebPSafeFree(huffman_codes->codes);1043WebPSafeFree(huffman_codes);1044huffman_codes = NULL;1045}1046}1047VP8LBitWriterSwap(bw, &bw_best);10481049Error:1050WebPSafeFree(tokens);1051WebPSafeFree(huff_tree);1052VP8LFreeHistogramSet(histogram_image);1053VP8LFreeHistogram(tmp_histo);1054if (huffman_codes != NULL) {1055WebPSafeFree(huffman_codes->codes);1056WebPSafeFree(huffman_codes);1057}1058WebPSafeFree(histogram_symbols);1059VP8LBitWriterWipeOut(&bw_best);1060return err;1061}10621063// -----------------------------------------------------------------------------1064// Transforms10651066static void ApplySubtractGreen(VP8LEncoder* const enc, int width, int height,1067VP8LBitWriter* const bw) {1068VP8LPutBits(bw, TRANSFORM_PRESENT, 1);1069VP8LPutBits(bw, SUBTRACT_GREEN, 2);1070VP8LSubtractGreenFromBlueAndRed(enc->argb_, width * height);1071}10721073static WebPEncodingError ApplyPredictFilter(const VP8LEncoder* const enc,1074int width, int height,1075int quality, int low_effort,1076int used_subtract_green,1077VP8LBitWriter* const bw) {1078const int pred_bits = enc->transform_bits_;1079const int transform_width = VP8LSubSampleSize(width, pred_bits);1080const int transform_height = VP8LSubSampleSize(height, pred_bits);1081// we disable near-lossless quantization if palette is used.1082const int near_lossless_strength = enc->use_palette_ ? 1001083: enc->config_->near_lossless;10841085VP8LResidualImage(width, height, pred_bits, low_effort, enc->argb_,1086enc->argb_scratch_, enc->transform_data_,1087near_lossless_strength, enc->config_->exact,1088used_subtract_green);1089VP8LPutBits(bw, TRANSFORM_PRESENT, 1);1090VP8LPutBits(bw, PREDICTOR_TRANSFORM, 2);1091assert(pred_bits >= 2);1092VP8LPutBits(bw, pred_bits - 2, 3);1093return EncodeImageNoHuffman(1094bw, enc->transform_data_, (VP8LHashChain*)&enc->hash_chain_,1095(VP8LBackwardRefs*)&enc->refs_[0], // cast const away1096(VP8LBackwardRefs*)&enc->refs_[1], transform_width, transform_height,1097quality, low_effort);1098}10991100static WebPEncodingError ApplyCrossColorFilter(const VP8LEncoder* const enc,1101int width, int height,1102int quality, int low_effort,1103VP8LBitWriter* const bw) {1104const int ccolor_transform_bits = enc->transform_bits_;1105const int transform_width = VP8LSubSampleSize(width, ccolor_transform_bits);1106const int transform_height = VP8LSubSampleSize(height, ccolor_transform_bits);11071108VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,1109enc->argb_, enc->transform_data_);1110VP8LPutBits(bw, TRANSFORM_PRESENT, 1);1111VP8LPutBits(bw, CROSS_COLOR_TRANSFORM, 2);1112assert(ccolor_transform_bits >= 2);1113VP8LPutBits(bw, ccolor_transform_bits - 2, 3);1114return EncodeImageNoHuffman(1115bw, enc->transform_data_, (VP8LHashChain*)&enc->hash_chain_,1116(VP8LBackwardRefs*)&enc->refs_[0], // cast const away1117(VP8LBackwardRefs*)&enc->refs_[1], transform_width, transform_height,1118quality, low_effort);1119}11201121// -----------------------------------------------------------------------------11221123static WebPEncodingError WriteRiffHeader(const WebPPicture* const pic,1124size_t riff_size, size_t vp8l_size) {1125uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {1126'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',1127'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,1128};1129PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);1130PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);1131if (!pic->writer(riff, sizeof(riff), pic)) {1132return VP8_ENC_ERROR_BAD_WRITE;1133}1134return VP8_ENC_OK;1135}11361137static int WriteImageSize(const WebPPicture* const pic,1138VP8LBitWriter* const bw) {1139const int width = pic->width - 1;1140const int height = pic->height - 1;1141assert(width < WEBP_MAX_DIMENSION && height < WEBP_MAX_DIMENSION);11421143VP8LPutBits(bw, width, VP8L_IMAGE_SIZE_BITS);1144VP8LPutBits(bw, height, VP8L_IMAGE_SIZE_BITS);1145return !bw->error_;1146}11471148static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {1149VP8LPutBits(bw, has_alpha, 1);1150VP8LPutBits(bw, VP8L_VERSION, VP8L_VERSION_BITS);1151return !bw->error_;1152}11531154static WebPEncodingError WriteImage(const WebPPicture* const pic,1155VP8LBitWriter* const bw,1156size_t* const coded_size) {1157WebPEncodingError err = VP8_ENC_OK;1158const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);1159const size_t webpll_size = VP8LBitWriterNumBytes(bw);1160const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;1161const size_t pad = vp8l_size & 1;1162const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;11631164err = WriteRiffHeader(pic, riff_size, vp8l_size);1165if (err != VP8_ENC_OK) goto Error;11661167if (!pic->writer(webpll_data, webpll_size, pic)) {1168err = VP8_ENC_ERROR_BAD_WRITE;1169goto Error;1170}11711172if (pad) {1173const uint8_t pad_byte[1] = { 0 };1174if (!pic->writer(pad_byte, 1, pic)) {1175err = VP8_ENC_ERROR_BAD_WRITE;1176goto Error;1177}1178}1179*coded_size = CHUNK_HEADER_SIZE + riff_size;1180return VP8_ENC_OK;11811182Error:1183return err;1184}11851186// -----------------------------------------------------------------------------11871188static void ClearTransformBuffer(VP8LEncoder* const enc) {1189WebPSafeFree(enc->transform_mem_);1190enc->transform_mem_ = NULL;1191enc->transform_mem_size_ = 0;1192}11931194// Allocates the memory for argb (W x H) buffer, 2 rows of context for1195// prediction and transform data.1196// Flags influencing the memory allocated:1197// enc->transform_bits_1198// enc->use_predict_, enc->use_cross_color_1199static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,1200int width, int height) {1201WebPEncodingError err = VP8_ENC_OK;1202const uint64_t image_size = width * height;1203// VP8LResidualImage needs room for 2 scanlines of uint32 pixels with an extra1204// pixel in each, plus 2 regular scanlines of bytes.1205// TODO(skal): Clean up by using arithmetic in bytes instead of words.1206const uint64_t argb_scratch_size =1207enc->use_predict_1208? (width + 1) * 2 +1209(width * 2 + sizeof(uint32_t) - 1) / sizeof(uint32_t)1210: 0;1211const uint64_t transform_data_size =1212(enc->use_predict_ || enc->use_cross_color_)1213? VP8LSubSampleSize(width, enc->transform_bits_) *1214VP8LSubSampleSize(height, enc->transform_bits_)1215: 0;1216const uint64_t max_alignment_in_words =1217(WEBP_ALIGN_CST + sizeof(uint32_t) - 1) / sizeof(uint32_t);1218const uint64_t mem_size =1219image_size + max_alignment_in_words +1220argb_scratch_size + max_alignment_in_words +1221transform_data_size;1222uint32_t* mem = enc->transform_mem_;1223if (mem == NULL || mem_size > enc->transform_mem_size_) {1224ClearTransformBuffer(enc);1225mem = (uint32_t*)WebPSafeMalloc(mem_size, sizeof(*mem));1226if (mem == NULL) {1227err = VP8_ENC_ERROR_OUT_OF_MEMORY;1228goto Error;1229}1230enc->transform_mem_ = mem;1231enc->transform_mem_size_ = (size_t)mem_size;1232enc->argb_content_ = kEncoderNone;1233}1234enc->argb_ = mem;1235mem = (uint32_t*)WEBP_ALIGN(mem + image_size);1236enc->argb_scratch_ = mem;1237mem = (uint32_t*)WEBP_ALIGN(mem + argb_scratch_size);1238enc->transform_data_ = mem;12391240enc->current_width_ = width;1241Error:1242return err;1243}12441245static WebPEncodingError MakeInputImageCopy(VP8LEncoder* const enc) {1246WebPEncodingError err = VP8_ENC_OK;1247const WebPPicture* const picture = enc->pic_;1248const int width = picture->width;1249const int height = picture->height;1250int y;1251err = AllocateTransformBuffer(enc, width, height);1252if (err != VP8_ENC_OK) return err;1253if (enc->argb_content_ == kEncoderARGB) return VP8_ENC_OK;1254for (y = 0; y < height; ++y) {1255memcpy(enc->argb_ + y * width,1256picture->argb + y * picture->argb_stride,1257width * sizeof(*enc->argb_));1258}1259enc->argb_content_ = kEncoderARGB;1260assert(enc->current_width_ == width);1261return VP8_ENC_OK;1262}12631264// -----------------------------------------------------------------------------12651266static WEBP_INLINE int SearchColorNoIdx(const uint32_t sorted[], uint32_t color,1267int hi) {1268int low = 0;1269if (sorted[low] == color) return low; // loop invariant: sorted[low] != color1270while (1) {1271const int mid = (low + hi) >> 1;1272if (sorted[mid] == color) {1273return mid;1274} else if (sorted[mid] < color) {1275low = mid;1276} else {1277hi = mid;1278}1279}1280}12811282#define APPLY_PALETTE_GREEDY_MAX 412831284static WEBP_INLINE uint32_t SearchColorGreedy(const uint32_t palette[],1285int palette_size,1286uint32_t color) {1287(void)palette_size;1288assert(palette_size < APPLY_PALETTE_GREEDY_MAX);1289assert(3 == APPLY_PALETTE_GREEDY_MAX - 1);1290if (color == palette[0]) return 0;1291if (color == palette[1]) return 1;1292if (color == palette[2]) return 2;1293return 3;1294}12951296static WEBP_INLINE uint32_t ApplyPaletteHash0(uint32_t color) {1297// Focus on the green color.1298return (color >> 8) & 0xff;1299}13001301#define PALETTE_INV_SIZE_BITS 111302#define PALETTE_INV_SIZE (1 << PALETTE_INV_SIZE_BITS)13031304static WEBP_INLINE uint32_t ApplyPaletteHash1(uint32_t color) {1305// Forget about alpha.1306return ((uint32_t)((color & 0x00ffffffu) * 4222244071ull)) >>1307(32 - PALETTE_INV_SIZE_BITS);1308}13091310static WEBP_INLINE uint32_t ApplyPaletteHash2(uint32_t color) {1311// Forget about alpha.1312return ((uint32_t)((color & 0x00ffffffu) * ((1ull << 31) - 1))) >>1313(32 - PALETTE_INV_SIZE_BITS);1314}13151316// Sort palette in increasing order and prepare an inverse mapping array.1317static void PrepareMapToPalette(const uint32_t palette[], int num_colors,1318uint32_t sorted[], uint32_t idx_map[]) {1319int i;1320memcpy(sorted, palette, num_colors * sizeof(*sorted));1321qsort(sorted, num_colors, sizeof(*sorted), PaletteCompareColorsForQsort);1322for (i = 0; i < num_colors; ++i) {1323idx_map[SearchColorNoIdx(sorted, palette[i], num_colors)] = i;1324}1325}13261327// Use 1 pixel cache for ARGB pixels.1328#define APPLY_PALETTE_FOR(COLOR_INDEX) do { \1329uint32_t prev_pix = palette[0]; \1330uint32_t prev_idx = 0; \1331for (y = 0; y < height; ++y) { \1332for (x = 0; x < width; ++x) { \1333const uint32_t pix = src[x]; \1334if (pix != prev_pix) { \1335prev_idx = COLOR_INDEX; \1336prev_pix = pix; \1337} \1338tmp_row[x] = prev_idx; \1339} \1340VP8LBundleColorMap(tmp_row, width, xbits, dst); \1341src += src_stride; \1342dst += dst_stride; \1343} \1344} while (0)13451346// Remap argb values in src[] to packed palettes entries in dst[]1347// using 'row' as a temporary buffer of size 'width'.1348// We assume that all src[] values have a corresponding entry in the palette.1349// Note: src[] can be the same as dst[]1350static WebPEncodingError ApplyPalette(const uint32_t* src, uint32_t src_stride,1351uint32_t* dst, uint32_t dst_stride,1352const uint32_t* palette, int palette_size,1353int width, int height, int xbits) {1354// TODO(skal): this tmp buffer is not needed if VP8LBundleColorMap() can be1355// made to work in-place.1356uint8_t* const tmp_row = (uint8_t*)WebPSafeMalloc(width, sizeof(*tmp_row));1357int x, y;13581359if (tmp_row == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;13601361if (palette_size < APPLY_PALETTE_GREEDY_MAX) {1362APPLY_PALETTE_FOR(SearchColorGreedy(palette, palette_size, pix));1363} else {1364int i, j;1365uint16_t buffer[PALETTE_INV_SIZE];1366uint32_t (*const hash_functions[])(uint32_t) = {1367ApplyPaletteHash0, ApplyPaletteHash1, ApplyPaletteHash21368};13691370// Try to find a perfect hash function able to go from a color to an index1371// within 1 << PALETTE_INV_SIZE_BITS in order to build a hash map to go1372// from color to index in palette.1373for (i = 0; i < 3; ++i) {1374int use_LUT = 1;1375// Set each element in buffer to max uint16_t.1376memset(buffer, 0xff, sizeof(buffer));1377for (j = 0; j < palette_size; ++j) {1378const uint32_t ind = hash_functions[i](palette[j]);1379if (buffer[ind] != 0xffffu) {1380use_LUT = 0;1381break;1382} else {1383buffer[ind] = j;1384}1385}1386if (use_LUT) break;1387}13881389if (i == 0) {1390APPLY_PALETTE_FOR(buffer[ApplyPaletteHash0(pix)]);1391} else if (i == 1) {1392APPLY_PALETTE_FOR(buffer[ApplyPaletteHash1(pix)]);1393} else if (i == 2) {1394APPLY_PALETTE_FOR(buffer[ApplyPaletteHash2(pix)]);1395} else {1396uint32_t idx_map[MAX_PALETTE_SIZE];1397uint32_t palette_sorted[MAX_PALETTE_SIZE];1398PrepareMapToPalette(palette, palette_size, palette_sorted, idx_map);1399APPLY_PALETTE_FOR(1400idx_map[SearchColorNoIdx(palette_sorted, pix, palette_size)]);1401}1402}1403WebPSafeFree(tmp_row);1404return VP8_ENC_OK;1405}1406#undef APPLY_PALETTE_FOR1407#undef PALETTE_INV_SIZE_BITS1408#undef PALETTE_INV_SIZE1409#undef APPLY_PALETTE_GREEDY_MAX14101411// Note: Expects "enc->palette_" to be set properly.1412static WebPEncodingError MapImageFromPalette(VP8LEncoder* const enc,1413int in_place) {1414WebPEncodingError err = VP8_ENC_OK;1415const WebPPicture* const pic = enc->pic_;1416const int width = pic->width;1417const int height = pic->height;1418const uint32_t* const palette = enc->palette_;1419const uint32_t* src = in_place ? enc->argb_ : pic->argb;1420const int src_stride = in_place ? enc->current_width_ : pic->argb_stride;1421const int palette_size = enc->palette_size_;1422int xbits;14231424// Replace each input pixel by corresponding palette index.1425// This is done line by line.1426if (palette_size <= 4) {1427xbits = (palette_size <= 2) ? 3 : 2;1428} else {1429xbits = (palette_size <= 16) ? 1 : 0;1430}14311432err = AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height);1433if (err != VP8_ENC_OK) return err;14341435err = ApplyPalette(src, src_stride,1436enc->argb_, enc->current_width_,1437palette, palette_size, width, height, xbits);1438enc->argb_content_ = kEncoderPalette;1439return err;1440}14411442// Save palette_[] to bitstream.1443static WebPEncodingError EncodePalette(VP8LBitWriter* const bw, int low_effort,1444VP8LEncoder* const enc) {1445int i;1446uint32_t tmp_palette[MAX_PALETTE_SIZE];1447const int palette_size = enc->palette_size_;1448const uint32_t* const palette = enc->palette_;1449VP8LPutBits(bw, TRANSFORM_PRESENT, 1);1450VP8LPutBits(bw, COLOR_INDEXING_TRANSFORM, 2);1451assert(palette_size >= 1 && palette_size <= MAX_PALETTE_SIZE);1452VP8LPutBits(bw, palette_size - 1, 8);1453for (i = palette_size - 1; i >= 1; --i) {1454tmp_palette[i] = VP8LSubPixels(palette[i], palette[i - 1]);1455}1456tmp_palette[0] = palette[0];1457return EncodeImageNoHuffman(bw, tmp_palette, &enc->hash_chain_,1458&enc->refs_[0], &enc->refs_[1], palette_size, 1,145920 /* quality */, low_effort);1460}14611462// -----------------------------------------------------------------------------1463// VP8LEncoder14641465static VP8LEncoder* VP8LEncoderNew(const WebPConfig* const config,1466const WebPPicture* const picture) {1467VP8LEncoder* const enc = (VP8LEncoder*)WebPSafeCalloc(1ULL, sizeof(*enc));1468if (enc == NULL) {1469WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);1470return NULL;1471}1472enc->config_ = config;1473enc->pic_ = picture;1474enc->argb_content_ = kEncoderNone;14751476VP8LEncDspInit();14771478return enc;1479}14801481static void VP8LEncoderDelete(VP8LEncoder* enc) {1482if (enc != NULL) {1483int i;1484VP8LHashChainClear(&enc->hash_chain_);1485for (i = 0; i < 3; ++i) VP8LBackwardRefsClear(&enc->refs_[i]);1486ClearTransformBuffer(enc);1487WebPSafeFree(enc);1488}1489}14901491// -----------------------------------------------------------------------------1492// Main call14931494typedef struct {1495const WebPConfig* config_;1496const WebPPicture* picture_;1497VP8LBitWriter* bw_;1498VP8LEncoder* enc_;1499int use_cache_;1500CrunchConfig crunch_configs_[CRUNCH_CONFIGS_MAX];1501int num_crunch_configs_;1502int red_and_blue_always_zero_;1503WebPEncodingError err_;1504WebPAuxStats* stats_;1505} StreamEncodeContext;15061507static int EncodeStreamHook(void* input, void* data2) {1508StreamEncodeContext* const params = (StreamEncodeContext*)input;1509const WebPConfig* const config = params->config_;1510const WebPPicture* const picture = params->picture_;1511VP8LBitWriter* const bw = params->bw_;1512VP8LEncoder* const enc = params->enc_;1513const int use_cache = params->use_cache_;1514const CrunchConfig* const crunch_configs = params->crunch_configs_;1515const int num_crunch_configs = params->num_crunch_configs_;1516const int red_and_blue_always_zero = params->red_and_blue_always_zero_;1517#if !defined(WEBP_DISABLE_STATS)1518WebPAuxStats* const stats = params->stats_;1519#endif1520WebPEncodingError err = VP8_ENC_OK;1521const int quality = (int)config->quality;1522const int low_effort = (config->method == 0);1523#if (WEBP_NEAR_LOSSLESS == 1)1524const int width = picture->width;1525#endif1526const int height = picture->height;1527const size_t byte_position = VP8LBitWriterNumBytes(bw);1528#if (WEBP_NEAR_LOSSLESS == 1)1529int use_near_lossless = 0;1530#endif1531int hdr_size = 0;1532int data_size = 0;1533int use_delta_palette = 0;1534int idx;1535size_t best_size = 0;1536VP8LBitWriter bw_init = *bw, bw_best;1537(void)data2;15381539if (!VP8LBitWriterInit(&bw_best, 0) ||1540(num_crunch_configs > 1 && !VP8LBitWriterClone(bw, &bw_best))) {1541err = VP8_ENC_ERROR_OUT_OF_MEMORY;1542goto Error;1543}15441545for (idx = 0; idx < num_crunch_configs; ++idx) {1546const int entropy_idx = crunch_configs[idx].entropy_idx_;1547enc->use_palette_ = (entropy_idx == kPalette);1548enc->use_subtract_green_ =1549(entropy_idx == kSubGreen) || (entropy_idx == kSpatialSubGreen);1550enc->use_predict_ =1551(entropy_idx == kSpatial) || (entropy_idx == kSpatialSubGreen);1552if (low_effort) {1553enc->use_cross_color_ = 0;1554} else {1555enc->use_cross_color_ = red_and_blue_always_zero ? 0 : enc->use_predict_;1556}1557// Reset any parameter in the encoder that is set in the previous iteration.1558enc->cache_bits_ = 0;1559VP8LBackwardRefsClear(&enc->refs_[0]);1560VP8LBackwardRefsClear(&enc->refs_[1]);15611562#if (WEBP_NEAR_LOSSLESS == 1)1563// Apply near-lossless preprocessing.1564use_near_lossless = (config->near_lossless < 100) && !enc->use_palette_ &&1565!enc->use_predict_;1566if (use_near_lossless) {1567err = AllocateTransformBuffer(enc, width, height);1568if (err != VP8_ENC_OK) goto Error;1569if ((enc->argb_content_ != kEncoderNearLossless) &&1570!VP8ApplyNearLossless(picture, config->near_lossless, enc->argb_)) {1571err = VP8_ENC_ERROR_OUT_OF_MEMORY;1572goto Error;1573}1574enc->argb_content_ = kEncoderNearLossless;1575} else {1576enc->argb_content_ = kEncoderNone;1577}1578#else1579enc->argb_content_ = kEncoderNone;1580#endif15811582// Encode palette1583if (enc->use_palette_) {1584err = EncodePalette(bw, low_effort, enc);1585if (err != VP8_ENC_OK) goto Error;1586err = MapImageFromPalette(enc, use_delta_palette);1587if (err != VP8_ENC_OK) goto Error;1588// If using a color cache, do not have it bigger than the number of1589// colors.1590if (use_cache && enc->palette_size_ < (1 << MAX_COLOR_CACHE_BITS)) {1591enc->cache_bits_ = BitsLog2Floor(enc->palette_size_) + 1;1592}1593}1594if (!use_delta_palette) {1595// In case image is not packed.1596if (enc->argb_content_ != kEncoderNearLossless &&1597enc->argb_content_ != kEncoderPalette) {1598err = MakeInputImageCopy(enc);1599if (err != VP8_ENC_OK) goto Error;1600}16011602// -----------------------------------------------------------------------1603// Apply transforms and write transform data.16041605if (enc->use_subtract_green_) {1606ApplySubtractGreen(enc, enc->current_width_, height, bw);1607}16081609if (enc->use_predict_) {1610err = ApplyPredictFilter(enc, enc->current_width_, height, quality,1611low_effort, enc->use_subtract_green_, bw);1612if (err != VP8_ENC_OK) goto Error;1613}16141615if (enc->use_cross_color_) {1616err = ApplyCrossColorFilter(enc, enc->current_width_, height, quality,1617low_effort, bw);1618if (err != VP8_ENC_OK) goto Error;1619}1620}16211622VP8LPutBits(bw, !TRANSFORM_PRESENT, 1); // No more transforms.16231624// -------------------------------------------------------------------------1625// Encode and write the transformed image.1626err = EncodeImageInternal(bw, enc->argb_, &enc->hash_chain_, enc->refs_,1627enc->current_width_, height, quality, low_effort,1628use_cache, &crunch_configs[idx],1629&enc->cache_bits_, enc->histo_bits_,1630byte_position, &hdr_size, &data_size);1631if (err != VP8_ENC_OK) goto Error;16321633// If we are better than what we already have.1634if (idx == 0 || VP8LBitWriterNumBytes(bw) < best_size) {1635best_size = VP8LBitWriterNumBytes(bw);1636// Store the BitWriter.1637VP8LBitWriterSwap(bw, &bw_best);1638#if !defined(WEBP_DISABLE_STATS)1639// Update the stats.1640if (stats != NULL) {1641stats->lossless_features = 0;1642if (enc->use_predict_) stats->lossless_features |= 1;1643if (enc->use_cross_color_) stats->lossless_features |= 2;1644if (enc->use_subtract_green_) stats->lossless_features |= 4;1645if (enc->use_palette_) stats->lossless_features |= 8;1646stats->histogram_bits = enc->histo_bits_;1647stats->transform_bits = enc->transform_bits_;1648stats->cache_bits = enc->cache_bits_;1649stats->palette_size = enc->palette_size_;1650stats->lossless_size = (int)(best_size - byte_position);1651stats->lossless_hdr_size = hdr_size;1652stats->lossless_data_size = data_size;1653}1654#endif1655}1656// Reset the bit writer for the following iteration if any.1657if (num_crunch_configs > 1) VP8LBitWriterReset(&bw_init, bw);1658}1659VP8LBitWriterSwap(&bw_best, bw);16601661Error:1662VP8LBitWriterWipeOut(&bw_best);1663params->err_ = err;1664// The hook should return false in case of error.1665return (err == VP8_ENC_OK);1666}16671668WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,1669const WebPPicture* const picture,1670VP8LBitWriter* const bw_main,1671int use_cache) {1672WebPEncodingError err = VP8_ENC_OK;1673VP8LEncoder* const enc_main = VP8LEncoderNew(config, picture);1674VP8LEncoder* enc_side = NULL;1675CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX];1676int num_crunch_configs_main, num_crunch_configs_side = 0;1677int idx;1678int red_and_blue_always_zero = 0;1679WebPWorker worker_main, worker_side;1680StreamEncodeContext params_main, params_side;1681// The main thread uses picture->stats, the side thread uses stats_side.1682WebPAuxStats stats_side;1683VP8LBitWriter bw_side;1684const WebPWorkerInterface* const worker_interface = WebPGetWorkerInterface();1685int ok_main;16861687// Analyze image (entropy, num_palettes etc)1688if (enc_main == NULL ||1689!EncoderAnalyze(enc_main, crunch_configs, &num_crunch_configs_main,1690&red_and_blue_always_zero) ||1691!EncoderInit(enc_main) || !VP8LBitWriterInit(&bw_side, 0)) {1692err = VP8_ENC_ERROR_OUT_OF_MEMORY;1693goto Error;1694}16951696// Split the configs between the main and side threads (if any).1697if (config->thread_level > 0) {1698num_crunch_configs_side = num_crunch_configs_main / 2;1699for (idx = 0; idx < num_crunch_configs_side; ++idx) {1700params_side.crunch_configs_[idx] =1701crunch_configs[num_crunch_configs_main - num_crunch_configs_side +1702idx];1703}1704params_side.num_crunch_configs_ = num_crunch_configs_side;1705}1706num_crunch_configs_main -= num_crunch_configs_side;1707for (idx = 0; idx < num_crunch_configs_main; ++idx) {1708params_main.crunch_configs_[idx] = crunch_configs[idx];1709}1710params_main.num_crunch_configs_ = num_crunch_configs_main;17111712// Fill in the parameters for the thread workers.1713{1714const int params_size = (num_crunch_configs_side > 0) ? 2 : 1;1715for (idx = 0; idx < params_size; ++idx) {1716// Create the parameters for each worker.1717WebPWorker* const worker = (idx == 0) ? &worker_main : &worker_side;1718StreamEncodeContext* const param =1719(idx == 0) ? ¶ms_main : ¶ms_side;1720param->config_ = config;1721param->picture_ = picture;1722param->use_cache_ = use_cache;1723param->red_and_blue_always_zero_ = red_and_blue_always_zero;1724if (idx == 0) {1725param->stats_ = picture->stats;1726param->bw_ = bw_main;1727param->enc_ = enc_main;1728} else {1729param->stats_ = (picture->stats == NULL) ? NULL : &stats_side;1730// Create a side bit writer.1731if (!VP8LBitWriterClone(bw_main, &bw_side)) {1732err = VP8_ENC_ERROR_OUT_OF_MEMORY;1733goto Error;1734}1735param->bw_ = &bw_side;1736// Create a side encoder.1737enc_side = VP8LEncoderNew(config, picture);1738if (enc_side == NULL || !EncoderInit(enc_side)) {1739err = VP8_ENC_ERROR_OUT_OF_MEMORY;1740goto Error;1741}1742// Copy the values that were computed for the main encoder.1743enc_side->histo_bits_ = enc_main->histo_bits_;1744enc_side->transform_bits_ = enc_main->transform_bits_;1745enc_side->palette_size_ = enc_main->palette_size_;1746memcpy(enc_side->palette_, enc_main->palette_,1747sizeof(enc_main->palette_));1748param->enc_ = enc_side;1749}1750// Create the workers.1751worker_interface->Init(worker);1752worker->data1 = param;1753worker->data2 = NULL;1754worker->hook = EncodeStreamHook;1755}1756}17571758// Start the second thread if needed.1759if (num_crunch_configs_side != 0) {1760if (!worker_interface->Reset(&worker_side)) {1761err = VP8_ENC_ERROR_OUT_OF_MEMORY;1762goto Error;1763}1764#if !defined(WEBP_DISABLE_STATS)1765// This line is here and not in the param initialization above to remove a1766// Clang static analyzer warning.1767if (picture->stats != NULL) {1768memcpy(&stats_side, picture->stats, sizeof(stats_side));1769}1770#endif1771// This line is only useful to remove a Clang static analyzer warning.1772params_side.err_ = VP8_ENC_OK;1773worker_interface->Launch(&worker_side);1774}1775// Execute the main thread.1776worker_interface->Execute(&worker_main);1777ok_main = worker_interface->Sync(&worker_main);1778worker_interface->End(&worker_main);1779if (num_crunch_configs_side != 0) {1780// Wait for the second thread.1781const int ok_side = worker_interface->Sync(&worker_side);1782worker_interface->End(&worker_side);1783if (!ok_main || !ok_side) {1784err = ok_main ? params_side.err_ : params_main.err_;1785goto Error;1786}1787if (VP8LBitWriterNumBytes(&bw_side) < VP8LBitWriterNumBytes(bw_main)) {1788VP8LBitWriterSwap(bw_main, &bw_side);1789#if !defined(WEBP_DISABLE_STATS)1790if (picture->stats != NULL) {1791memcpy(picture->stats, &stats_side, sizeof(*picture->stats));1792}1793#endif1794}1795} else {1796if (!ok_main) {1797err = params_main.err_;1798goto Error;1799}1800}18011802Error:1803VP8LBitWriterWipeOut(&bw_side);1804VP8LEncoderDelete(enc_main);1805VP8LEncoderDelete(enc_side);1806return err;1807}18081809#undef CRUNCH_CONFIGS_MAX1810#undef CRUNCH_CONFIGS_LZ77_MAX18111812int VP8LEncodeImage(const WebPConfig* const config,1813const WebPPicture* const picture) {1814int width, height;1815int has_alpha;1816size_t coded_size;1817int percent = 0;1818int initial_size;1819WebPEncodingError err = VP8_ENC_OK;1820VP8LBitWriter bw;18211822if (picture == NULL) return 0;18231824if (config == NULL || picture->argb == NULL) {1825err = VP8_ENC_ERROR_NULL_PARAMETER;1826WebPEncodingSetError(picture, err);1827return 0;1828}18291830width = picture->width;1831height = picture->height;1832// Initialize BitWriter with size corresponding to 16 bpp to photo images and1833// 8 bpp for graphical images.1834initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?1835width * height : width * height * 2;1836if (!VP8LBitWriterInit(&bw, initial_size)) {1837err = VP8_ENC_ERROR_OUT_OF_MEMORY;1838goto Error;1839}18401841if (!WebPReportProgress(picture, 1, &percent)) {1842UserAbort:1843err = VP8_ENC_ERROR_USER_ABORT;1844goto Error;1845}1846// Reset stats (for pure lossless coding)1847if (picture->stats != NULL) {1848WebPAuxStats* const stats = picture->stats;1849memset(stats, 0, sizeof(*stats));1850stats->PSNR[0] = 99.f;1851stats->PSNR[1] = 99.f;1852stats->PSNR[2] = 99.f;1853stats->PSNR[3] = 99.f;1854stats->PSNR[4] = 99.f;1855}18561857// Write image size.1858if (!WriteImageSize(picture, &bw)) {1859err = VP8_ENC_ERROR_OUT_OF_MEMORY;1860goto Error;1861}18621863has_alpha = WebPPictureHasTransparency(picture);1864// Write the non-trivial Alpha flag and lossless version.1865if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {1866err = VP8_ENC_ERROR_OUT_OF_MEMORY;1867goto Error;1868}18691870if (!WebPReportProgress(picture, 5, &percent)) goto UserAbort;18711872// Encode main image stream.1873err = VP8LEncodeStream(config, picture, &bw, 1 /*use_cache*/);1874if (err != VP8_ENC_OK) goto Error;18751876if (!WebPReportProgress(picture, 90, &percent)) goto UserAbort;18771878// Finish the RIFF chunk.1879err = WriteImage(picture, &bw, &coded_size);1880if (err != VP8_ENC_OK) goto Error;18811882if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;18831884#if !defined(WEBP_DISABLE_STATS)1885// Save size.1886if (picture->stats != NULL) {1887picture->stats->coded_size += (int)coded_size;1888picture->stats->lossless_size = (int)coded_size;1889}1890#endif18911892if (picture->extra_info != NULL) {1893const int mb_w = (width + 15) >> 4;1894const int mb_h = (height + 15) >> 4;1895memset(picture->extra_info, 0, mb_w * mb_h * sizeof(*picture->extra_info));1896}18971898Error:1899if (bw.error_) err = VP8_ENC_ERROR_OUT_OF_MEMORY;1900VP8LBitWriterWipeOut(&bw);1901if (err != VP8_ENC_OK) {1902WebPEncodingSetError(picture, err);1903return 0;1904}1905return 1;1906}19071908//------------------------------------------------------------------------------190919101911