00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00026 #include "avcodec.h"
00027 #include "get_bits.h"
00028 #include "huffman.h"
00029
00030
00031 #define HNODE -1
00032
00033
00034 static void get_tree_codes(uint32_t *bits, int16_t *lens, uint8_t *xlat, Node *nodes, int node, uint32_t pfx, int pl, int *pos, int no_zero_count)
00035 {
00036 int s;
00037
00038 s = nodes[node].sym;
00039 if(s != HNODE || (no_zero_count && !nodes[node].count)){
00040 bits[*pos] = pfx;
00041 lens[*pos] = pl;
00042 xlat[*pos] = s;
00043 (*pos)++;
00044 }else{
00045 pfx <<= 1;
00046 pl++;
00047 get_tree_codes(bits, lens, xlat, nodes, nodes[node].n0, pfx, pl, pos,
00048 no_zero_count);
00049 pfx |= 1;
00050 get_tree_codes(bits, lens, xlat, nodes, nodes[node].n0+1, pfx, pl, pos,
00051 no_zero_count);
00052 }
00053 }
00054
00055 static int build_huff_tree(VLC *vlc, Node *nodes, int head, int flags)
00056 {
00057 int no_zero_count = !(flags & FF_HUFFMAN_FLAG_ZERO_COUNT);
00058 uint32_t bits[256];
00059 int16_t lens[256];
00060 uint8_t xlat[256];
00061 int pos = 0;
00062
00063 get_tree_codes(bits, lens, xlat, nodes, head, 0, 0, &pos, no_zero_count);
00064 return ff_init_vlc_sparse(vlc, 9, pos, lens, 2, 2, bits, 4, 4, xlat, 1, 1, 0);
00065 }
00066
00067
00072 int ff_huff_build_tree(AVCodecContext *avctx, VLC *vlc, int nb_codes,
00073 Node *nodes, HuffCmp cmp, int flags)
00074 {
00075 int i, j;
00076 int cur_node;
00077 int64_t sum = 0;
00078
00079 for(i = 0; i < nb_codes; i++){
00080 nodes[i].sym = i;
00081 nodes[i].n0 = -2;
00082 sum += nodes[i].count;
00083 }
00084
00085 if(sum >> 31) {
00086 av_log(avctx, AV_LOG_ERROR, "Too high symbol frequencies. Tree construction is not possible\n");
00087 return -1;
00088 }
00089 qsort(nodes, nb_codes, sizeof(Node), cmp);
00090 cur_node = nb_codes;
00091 nodes[nb_codes*2-1].count = 0;
00092 for(i = 0; i < nb_codes*2-1; i += 2){
00093 uint32_t cur_count = nodes[i].count + nodes[i+1].count;
00094
00095
00096 for(j = cur_node; j > i + 2; j--){
00097 if(cur_count > nodes[j-1].count ||
00098 (cur_count == nodes[j-1].count &&
00099 !(flags & FF_HUFFMAN_FLAG_HNODE_FIRST)))
00100 break;
00101 nodes[j] = nodes[j - 1];
00102 }
00103 nodes[j].sym = HNODE;
00104 nodes[j].count = cur_count;
00105 nodes[j].n0 = i;
00106 cur_node++;
00107 }
00108 if(build_huff_tree(vlc, nodes, nb_codes*2-2, flags) < 0){
00109 av_log(avctx, AV_LOG_ERROR, "Error building tree\n");
00110 return -1;
00111 }
00112 return 0;
00113 }