Path: blob/master/thirdparty/libwebp/src/utils/huffman_utils.c
20959 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// Utilities for building and looking up Huffman trees.10//11// Author: Urvang Joshi ([email protected])1213#include <assert.h>14#include <stdlib.h>15#include <string.h>1617#include "src/utils/huffman_utils.h"18#include "src/utils/utils.h"19#include "src/webp/format_constants.h"20#include "src/webp/types.h"2122// Huffman data read via DecodeImageStream is represented in two (red and green)23// bytes.24#define MAX_HTREE_GROUPS 0x100002526HTreeGroup* VP8LHtreeGroupsNew(int num_htree_groups) {27HTreeGroup* const htree_groups =28(HTreeGroup*)WebPSafeMalloc(num_htree_groups, sizeof(*htree_groups));29if (htree_groups == NULL) {30return NULL;31}32assert(num_htree_groups <= MAX_HTREE_GROUPS);33return htree_groups;34}3536void VP8LHtreeGroupsFree(HTreeGroup* const htree_groups) {37if (htree_groups != NULL) {38WebPSafeFree(htree_groups);39}40}4142// Returns reverse(reverse(key, len) + 1, len), where reverse(key, len) is the43// bit-wise reversal of the len least significant bits of key.44static WEBP_INLINE uint32_t GetNextKey(uint32_t key, int len) {45uint32_t step = 1 << (len - 1);46while (key & step) {47step >>= 1;48}49return step ? (key & (step - 1)) + step : key;50}5152// Stores code in table[0], table[step], table[2*step], ..., table[end].53// Assumes that end is an integer multiple of step.54static WEBP_INLINE void ReplicateValue(HuffmanCode* table,55int step, int end,56HuffmanCode code) {57assert(end % step == 0);58do {59end -= step;60table[end] = code;61} while (end > 0);62}6364// Returns the table width of the next 2nd level table. count is the histogram65// of bit lengths for the remaining symbols, len is the code length of the next66// processed symbol67static WEBP_INLINE int NextTableBitSize(const int* const count,68int len, int root_bits) {69int left = 1 << (len - root_bits);70while (len < MAX_ALLOWED_CODE_LENGTH) {71left -= count[len];72if (left <= 0) break;73++len;74left <<= 1;75}76return len - root_bits;77}7879// sorted[code_lengths_size] is a pre-allocated array for sorting symbols80// by code length.81static int BuildHuffmanTable(HuffmanCode* const root_table, int root_bits,82const int code_lengths[], int code_lengths_size,83uint16_t sorted[]) {84HuffmanCode* table = root_table; // next available space in table85int total_size = 1 << root_bits; // total size root table + 2nd level table86int len; // current code length87int symbol; // symbol index in original or sorted table88// number of codes of each length:89int count[MAX_ALLOWED_CODE_LENGTH + 1] = { 0 };90// offsets in sorted table for each length:91int offset[MAX_ALLOWED_CODE_LENGTH + 1];9293assert(code_lengths_size != 0);94assert(code_lengths != NULL);95assert((root_table != NULL && sorted != NULL) ||96(root_table == NULL && sorted == NULL));97assert(root_bits > 0);9899// Build histogram of code lengths.100for (symbol = 0; symbol < code_lengths_size; ++symbol) {101if (code_lengths[symbol] > MAX_ALLOWED_CODE_LENGTH) {102return 0;103}104++count[code_lengths[symbol]];105}106107// Error, all code lengths are zeros.108if (count[0] == code_lengths_size) {109return 0;110}111112// Generate offsets into sorted symbol table by code length.113offset[1] = 0;114for (len = 1; len < MAX_ALLOWED_CODE_LENGTH; ++len) {115if (count[len] > (1 << len)) {116return 0;117}118offset[len + 1] = offset[len] + count[len];119}120121// Sort symbols by length, by symbol order within each length.122for (symbol = 0; symbol < code_lengths_size; ++symbol) {123const int symbol_code_length = code_lengths[symbol];124if (code_lengths[symbol] > 0) {125if (sorted != NULL) {126if(offset[symbol_code_length] >= code_lengths_size) {127return 0;128}129sorted[offset[symbol_code_length]++] = symbol;130} else {131offset[symbol_code_length]++;132}133}134}135136// Special case code with only one value.137if (offset[MAX_ALLOWED_CODE_LENGTH] == 1) {138if (sorted != NULL) {139HuffmanCode code;140code.bits = 0;141code.value = (uint16_t)sorted[0];142ReplicateValue(table, 1, total_size, code);143}144return total_size;145}146147{148int step; // step size to replicate values in current table149uint32_t low = 0xffffffffu; // low bits for current root entry150uint32_t mask = total_size - 1; // mask for low bits151uint32_t key = 0; // reversed prefix code152int num_nodes = 1; // number of Huffman tree nodes153int num_open = 1; // number of open branches in current tree level154int table_bits = root_bits; // key length of current table155int table_size = 1 << table_bits; // size of current table156symbol = 0;157// Fill in root table.158for (len = 1, step = 2; len <= root_bits; ++len, step <<= 1) {159num_open <<= 1;160num_nodes += num_open;161num_open -= count[len];162if (num_open < 0) {163return 0;164}165if (root_table == NULL) continue;166for (; count[len] > 0; --count[len]) {167HuffmanCode code;168code.bits = (uint8_t)len;169code.value = (uint16_t)sorted[symbol++];170ReplicateValue(&table[key], step, table_size, code);171key = GetNextKey(key, len);172}173}174175// Fill in 2nd level tables and add pointers to root table.176for (len = root_bits + 1, step = 2; len <= MAX_ALLOWED_CODE_LENGTH;177++len, step <<= 1) {178num_open <<= 1;179num_nodes += num_open;180num_open -= count[len];181if (num_open < 0) {182return 0;183}184for (; count[len] > 0; --count[len]) {185HuffmanCode code;186if ((key & mask) != low) {187if (root_table != NULL) table += table_size;188table_bits = NextTableBitSize(count, len, root_bits);189table_size = 1 << table_bits;190total_size += table_size;191low = key & mask;192if (root_table != NULL) {193root_table[low].bits = (uint8_t)(table_bits + root_bits);194root_table[low].value = (uint16_t)((table - root_table) - low);195}196}197if (root_table != NULL) {198code.bits = (uint8_t)(len - root_bits);199code.value = (uint16_t)sorted[symbol++];200ReplicateValue(&table[key >> root_bits], step, table_size, code);201}202key = GetNextKey(key, len);203}204}205206// Check if tree is full.207if (num_nodes != 2 * offset[MAX_ALLOWED_CODE_LENGTH] - 1) {208return 0;209}210}211212return total_size;213}214215// Maximum code_lengths_size is 2328 (reached for 11-bit color_cache_bits).216// More commonly, the value is around ~280.217#define MAX_CODE_LENGTHS_SIZE \218((1 << MAX_CACHE_BITS) + NUM_LITERAL_CODES + NUM_LENGTH_CODES)219// Cut-off value for switching between heap and stack allocation.220#define SORTED_SIZE_CUTOFF 512221int VP8LBuildHuffmanTable(HuffmanTables* const root_table, int root_bits,222const int code_lengths[], int code_lengths_size) {223const int total_size =224BuildHuffmanTable(NULL, root_bits, code_lengths, code_lengths_size, NULL);225assert(code_lengths_size <= MAX_CODE_LENGTHS_SIZE);226if (total_size == 0 || root_table == NULL) return total_size;227228if (root_table->curr_segment->curr_table + total_size >=229root_table->curr_segment->start + root_table->curr_segment->size) {230// If 'root_table' does not have enough memory, allocate a new segment.231// The available part of root_table->curr_segment is left unused because we232// need a contiguous buffer.233const int segment_size = root_table->curr_segment->size;234struct HuffmanTablesSegment* next =235(HuffmanTablesSegment*)WebPSafeMalloc(1, sizeof(*next));236if (next == NULL) return 0;237// Fill the new segment.238// We need at least 'total_size' but if that value is small, it is better to239// allocate a big chunk to prevent more allocations later. 'segment_size' is240// therefore chosen (any other arbitrary value could be chosen).241next->size = total_size > segment_size ? total_size : segment_size;242next->start =243(HuffmanCode*)WebPSafeMalloc(next->size, sizeof(*next->start));244if (next->start == NULL) {245WebPSafeFree(next);246return 0;247}248next->curr_table = next->start;249next->next = NULL;250// Point to the new segment.251root_table->curr_segment->next = next;252root_table->curr_segment = next;253}254if (code_lengths_size <= SORTED_SIZE_CUTOFF) {255// use local stack-allocated array.256uint16_t sorted[SORTED_SIZE_CUTOFF];257BuildHuffmanTable(root_table->curr_segment->curr_table, root_bits,258code_lengths, code_lengths_size, sorted);259} else { // rare case. Use heap allocation.260uint16_t* const sorted =261(uint16_t*)WebPSafeMalloc(code_lengths_size, sizeof(*sorted));262if (sorted == NULL) return 0;263BuildHuffmanTable(root_table->curr_segment->curr_table, root_bits,264code_lengths, code_lengths_size, sorted);265WebPSafeFree(sorted);266}267return total_size;268}269270int VP8LHuffmanTablesAllocate(int size, HuffmanTables* huffman_tables) {271// Have 'segment' point to the first segment for now, 'root'.272HuffmanTablesSegment* const root = &huffman_tables->root;273huffman_tables->curr_segment = root;274root->next = NULL;275// Allocate root.276root->start = (HuffmanCode*)WebPSafeMalloc(size, sizeof(*root->start));277if (root->start == NULL) return 0;278root->curr_table = root->start;279root->size = size;280return 1;281}282283void VP8LHuffmanTablesDeallocate(HuffmanTables* const huffman_tables) {284HuffmanTablesSegment *current, *next;285if (huffman_tables == NULL) return;286// Free the root node.287current = &huffman_tables->root;288next = current->next;289WebPSafeFree(current->start);290current->start = NULL;291current->next = NULL;292current = next;293// Free the following nodes.294while (current != NULL) {295next = current->next;296WebPSafeFree(current->start);297WebPSafeFree(current);298current = next;299}300}301302303