Path: blob/master/thirdparty/libwebp/src/utils/huffman_encode_utils.c
9912 views
// Copyright 2011 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// Author: Jyrki Alakuijala ([email protected])10//11// Entropy encoding (Huffman) for webp lossless.1213#include <assert.h>14#include <stdlib.h>15#include <string.h>16#include "src/utils/huffman_encode_utils.h"17#include "src/utils/utils.h"18#include "src/webp/format_constants.h"1920// -----------------------------------------------------------------------------21// Util function to optimize the symbol map for RLE coding2223// Heuristics for selecting the stride ranges to collapse.24static int ValuesShouldBeCollapsedToStrideAverage(int a, int b) {25return abs(a - b) < 4;26}2728// Change the population counts in a way that the consequent29// Huffman tree compression, especially its RLE-part, give smaller output.30static void OptimizeHuffmanForRle(int length, uint8_t* const good_for_rle,31uint32_t* const counts) {32// 1) Let's make the Huffman code more compatible with rle encoding.33int i;34for (; length >= 0; --length) {35if (length == 0) {36return; // All zeros.37}38if (counts[length - 1] != 0) {39// Now counts[0..length - 1] does not have trailing zeros.40break;41}42}43// 2) Let's mark all population counts that already can be encoded44// with an rle code.45{46// Let's not spoil any of the existing good rle codes.47// Mark any seq of 0's that is longer as 5 as a good_for_rle.48// Mark any seq of non-0's that is longer as 7 as a good_for_rle.49uint32_t symbol = counts[0];50int stride = 0;51for (i = 0; i < length + 1; ++i) {52if (i == length || counts[i] != symbol) {53if ((symbol == 0 && stride >= 5) ||54(symbol != 0 && stride >= 7)) {55int k;56for (k = 0; k < stride; ++k) {57good_for_rle[i - k - 1] = 1;58}59}60stride = 1;61if (i != length) {62symbol = counts[i];63}64} else {65++stride;66}67}68}69// 3) Let's replace those population counts that lead to more rle codes.70{71uint32_t stride = 0;72uint32_t limit = counts[0];73uint32_t sum = 0;74for (i = 0; i < length + 1; ++i) {75if (i == length || good_for_rle[i] ||76(i != 0 && good_for_rle[i - 1]) ||77!ValuesShouldBeCollapsedToStrideAverage(counts[i], limit)) {78if (stride >= 4 || (stride >= 3 && sum == 0)) {79uint32_t k;80// The stride must end, collapse what we have, if we have enough (4).81uint32_t count = (sum + stride / 2) / stride;82if (count < 1) {83count = 1;84}85if (sum == 0) {86// Don't make an all zeros stride to be upgraded to ones.87count = 0;88}89for (k = 0; k < stride; ++k) {90// We don't want to change value at counts[i],91// that is already belonging to the next stride. Thus - 1.92counts[i - k - 1] = count;93}94}95stride = 0;96sum = 0;97if (i < length - 3) {98// All interesting strides have a count of at least 4,99// at least when non-zeros.100limit = (counts[i] + counts[i + 1] +101counts[i + 2] + counts[i + 3] + 2) / 4;102} else if (i < length) {103limit = counts[i];104} else {105limit = 0;106}107}108++stride;109if (i != length) {110sum += counts[i];111if (stride >= 4) {112limit = (sum + stride / 2) / stride;113}114}115}116}117}118119// A comparer function for two Huffman trees: sorts first by 'total count'120// (more comes first), and then by 'value' (more comes first).121static int CompareHuffmanTrees(const void* ptr1, const void* ptr2) {122const HuffmanTree* const t1 = (const HuffmanTree*)ptr1;123const HuffmanTree* const t2 = (const HuffmanTree*)ptr2;124if (t1->total_count_ > t2->total_count_) {125return -1;126} else if (t1->total_count_ < t2->total_count_) {127return 1;128} else {129assert(t1->value_ != t2->value_);130return (t1->value_ < t2->value_) ? -1 : 1;131}132}133134static void SetBitDepths(const HuffmanTree* const tree,135const HuffmanTree* const pool,136uint8_t* const bit_depths, int level) {137if (tree->pool_index_left_ >= 0) {138SetBitDepths(&pool[tree->pool_index_left_], pool, bit_depths, level + 1);139SetBitDepths(&pool[tree->pool_index_right_], pool, bit_depths, level + 1);140} else {141bit_depths[tree->value_] = level;142}143}144145// Create an optimal Huffman tree.146//147// (data,length): population counts.148// tree_limit: maximum bit depth (inclusive) of the codes.149// bit_depths[]: how many bits are used for the symbol.150//151// Returns 0 when an error has occurred.152//153// The catch here is that the tree cannot be arbitrarily deep154//155// count_limit is the value that is to be faked as the minimum value156// and this minimum value is raised until the tree matches the157// maximum length requirement.158//159// This algorithm is not of excellent performance for very long data blocks,160// especially when population counts are longer than 2**tree_limit, but161// we are not planning to use this with extremely long blocks.162//163// See https://en.wikipedia.org/wiki/Huffman_coding164static void GenerateOptimalTree(const uint32_t* const histogram,165int histogram_size,166HuffmanTree* tree, int tree_depth_limit,167uint8_t* const bit_depths) {168uint32_t count_min;169HuffmanTree* tree_pool;170int tree_size_orig = 0;171int i;172173for (i = 0; i < histogram_size; ++i) {174if (histogram[i] != 0) {175++tree_size_orig;176}177}178179if (tree_size_orig == 0) { // pretty optimal already!180return;181}182183tree_pool = tree + tree_size_orig;184185// For block sizes with less than 64k symbols we never need to do a186// second iteration of this loop.187// If we actually start running inside this loop a lot, we would perhaps188// be better off with the Katajainen algorithm.189assert(tree_size_orig <= (1 << (tree_depth_limit - 1)));190for (count_min = 1; ; count_min *= 2) {191int tree_size = tree_size_orig;192// We need to pack the Huffman tree in tree_depth_limit bits.193// So, we try by faking histogram entries to be at least 'count_min'.194int idx = 0;195int j;196for (j = 0; j < histogram_size; ++j) {197if (histogram[j] != 0) {198const uint32_t count =199(histogram[j] < count_min) ? count_min : histogram[j];200tree[idx].total_count_ = count;201tree[idx].value_ = j;202tree[idx].pool_index_left_ = -1;203tree[idx].pool_index_right_ = -1;204++idx;205}206}207208// Build the Huffman tree.209qsort(tree, tree_size, sizeof(*tree), CompareHuffmanTrees);210211if (tree_size > 1) { // Normal case.212int tree_pool_size = 0;213while (tree_size > 1) { // Finish when we have only one root.214uint32_t count;215tree_pool[tree_pool_size++] = tree[tree_size - 1];216tree_pool[tree_pool_size++] = tree[tree_size - 2];217count = tree_pool[tree_pool_size - 1].total_count_ +218tree_pool[tree_pool_size - 2].total_count_;219tree_size -= 2;220{221// Search for the insertion point.222int k;223for (k = 0; k < tree_size; ++k) {224if (tree[k].total_count_ <= count) {225break;226}227}228memmove(tree + (k + 1), tree + k, (tree_size - k) * sizeof(*tree));229tree[k].total_count_ = count;230tree[k].value_ = -1;231232tree[k].pool_index_left_ = tree_pool_size - 1;233tree[k].pool_index_right_ = tree_pool_size - 2;234tree_size = tree_size + 1;235}236}237SetBitDepths(&tree[0], tree_pool, bit_depths, 0);238} else if (tree_size == 1) { // Trivial case: only one element.239bit_depths[tree[0].value_] = 1;240}241242{243// Test if this Huffman tree satisfies our 'tree_depth_limit' criteria.244int max_depth = bit_depths[0];245for (j = 1; j < histogram_size; ++j) {246if (max_depth < bit_depths[j]) {247max_depth = bit_depths[j];248}249}250if (max_depth <= tree_depth_limit) {251break;252}253}254}255}256257// -----------------------------------------------------------------------------258// Coding of the Huffman tree values259260static HuffmanTreeToken* CodeRepeatedValues(int repetitions,261HuffmanTreeToken* tokens,262int value, int prev_value) {263assert(value <= MAX_ALLOWED_CODE_LENGTH);264if (value != prev_value) {265tokens->code = value;266tokens->extra_bits = 0;267++tokens;268--repetitions;269}270while (repetitions >= 1) {271if (repetitions < 3) {272int i;273for (i = 0; i < repetitions; ++i) {274tokens->code = value;275tokens->extra_bits = 0;276++tokens;277}278break;279} else if (repetitions < 7) {280tokens->code = 16;281tokens->extra_bits = repetitions - 3;282++tokens;283break;284} else {285tokens->code = 16;286tokens->extra_bits = 3;287++tokens;288repetitions -= 6;289}290}291return tokens;292}293294static HuffmanTreeToken* CodeRepeatedZeros(int repetitions,295HuffmanTreeToken* tokens) {296while (repetitions >= 1) {297if (repetitions < 3) {298int i;299for (i = 0; i < repetitions; ++i) {300tokens->code = 0; // 0-value301tokens->extra_bits = 0;302++tokens;303}304break;305} else if (repetitions < 11) {306tokens->code = 17;307tokens->extra_bits = repetitions - 3;308++tokens;309break;310} else if (repetitions < 139) {311tokens->code = 18;312tokens->extra_bits = repetitions - 11;313++tokens;314break;315} else {316tokens->code = 18;317tokens->extra_bits = 0x7f; // 138 repeated 0s318++tokens;319repetitions -= 138;320}321}322return tokens;323}324325int VP8LCreateCompressedHuffmanTree(const HuffmanTreeCode* const tree,326HuffmanTreeToken* tokens, int max_tokens) {327HuffmanTreeToken* const starting_token = tokens;328HuffmanTreeToken* const ending_token = tokens + max_tokens;329const int depth_size = tree->num_symbols;330int prev_value = 8; // 8 is the initial value for rle.331int i = 0;332assert(tokens != NULL);333while (i < depth_size) {334const int value = tree->code_lengths[i];335int k = i + 1;336int runs;337while (k < depth_size && tree->code_lengths[k] == value) ++k;338runs = k - i;339if (value == 0) {340tokens = CodeRepeatedZeros(runs, tokens);341} else {342tokens = CodeRepeatedValues(runs, tokens, value, prev_value);343prev_value = value;344}345i += runs;346assert(tokens <= ending_token);347}348(void)ending_token; // suppress 'unused variable' warning349return (int)(tokens - starting_token);350}351352// -----------------------------------------------------------------------------353354// Pre-reversed 4-bit values.355static const uint8_t kReversedBits[16] = {3560x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,3570x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf358};359360static uint32_t ReverseBits(int num_bits, uint32_t bits) {361uint32_t retval = 0;362int i = 0;363while (i < num_bits) {364i += 4;365retval |= kReversedBits[bits & 0xf] << (MAX_ALLOWED_CODE_LENGTH + 1 - i);366bits >>= 4;367}368retval >>= (MAX_ALLOWED_CODE_LENGTH + 1 - num_bits);369return retval;370}371372// Get the actual bit values for a tree of bit depths.373static void ConvertBitDepthsToSymbols(HuffmanTreeCode* const tree) {374// 0 bit-depth means that the symbol does not exist.375int i;376int len;377uint32_t next_code[MAX_ALLOWED_CODE_LENGTH + 1];378int depth_count[MAX_ALLOWED_CODE_LENGTH + 1] = { 0 };379380assert(tree != NULL);381len = tree->num_symbols;382for (i = 0; i < len; ++i) {383const int code_length = tree->code_lengths[i];384assert(code_length <= MAX_ALLOWED_CODE_LENGTH);385++depth_count[code_length];386}387depth_count[0] = 0; // ignore unused symbol388next_code[0] = 0;389{390uint32_t code = 0;391for (i = 1; i <= MAX_ALLOWED_CODE_LENGTH; ++i) {392code = (code + depth_count[i - 1]) << 1;393next_code[i] = code;394}395}396for (i = 0; i < len; ++i) {397const int code_length = tree->code_lengths[i];398tree->codes[i] = ReverseBits(code_length, next_code[code_length]++);399}400}401402// -----------------------------------------------------------------------------403// Main entry point404405void VP8LCreateHuffmanTree(uint32_t* const histogram, int tree_depth_limit,406uint8_t* const buf_rle, HuffmanTree* const huff_tree,407HuffmanTreeCode* const huff_code) {408const int num_symbols = huff_code->num_symbols;409memset(buf_rle, 0, num_symbols * sizeof(*buf_rle));410OptimizeHuffmanForRle(num_symbols, buf_rle, histogram);411GenerateOptimalTree(histogram, num_symbols, huff_tree, tree_depth_limit,412huff_code->code_lengths);413// Create the actual bit codes for the bit lengths.414ConvertBitDepthsToSymbols(huff_code);415}416417418