Coverage Report

Created: 2026-12-01 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/faac/libfaac/huff2.c
Line
Count
Source
1
/*
2
 * FAAC - Freeware Advanced Audio Coder
3
 * Huffman coding per ISO/IEC 14496-3
4
 * Copyright (C) 2026 Nils Schimmelmann
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 */
16
17
#include <stdio.h>
18
#include <stdlib.h>
19
#include <limits.h>
20
#include "coder.h"
21
#include "huffdata.h"
22
#include "huff2.h"
23
#include "bitstream.h"
24
#include "util.h"
25
26
/* Escape coding for HCB_ESC as per ISO/IEC 14496-3.
27
 * Represents values |q| >= 16 by sending 16 plus an escape suffix. */
28
static int escape(int x, int *code)
29
4.20M
{
30
4.20M
    if (x > MAX_HUFF_ESC_VAL) {
31
22.2k
        fprintf(stderr, "Huffman escape value out of range: %d\n", x);
32
22.2k
        return 0;
33
22.2k
    }
34
35
4.17M
    int preflen = 31 - CountLeadingZeros(x) - 4;
36
4.17M
    int base = 1 << (preflen + 4);
37
38
4.17M
    if (code) {
39
        /* Unary prefix: preflen 1s followed by a 0 */
40
4.17M
        *code = (1 << (preflen + 1)) - 2;
41
        /* Escape suffix is (preflen+4) bits: base starts at 16 (= 2^4), so the
42
         * value field is always at least 4 bits; each additional doubling adds one. */
43
4.17M
        *code = (*code << (preflen + 4)) | (x - base);
44
4.17M
    }
45
46
4.17M
    return (preflen + 1) + (preflen + 4);
47
4.20M
}
48
49
static const hcode16_t * const hmap[12] = {
50
    NULL, book01, book02, book03, book04, book05,
51
    book06, book07, book08, book09, book10, book11
52
};
53
54
55
/* Both books of a pair share the index expression; only the table differs.
56
 * One walk, two lookups.
57
 *
58
 * ISO 14496-3 multidimensional Huffman section tuple indexing. Constant dimensions
59
 * (DIM_S4, DIM_M4, DIM_S2) allow constant folding into shift-adds.
60
 *
61
 * bnum is HCB_1, HCB_3 or HCB_5; size_books walks the unsigned pair books
62
 * itself. HCB_3 leaves out its sign bits, which size_books adds. */
63
static void huffcode_size_pair(const int * __restrict qs, int len, int bnum, int *bits_a, int *bits_b)
64
654k
{
65
654k
    const hcode16_t *booka = hmap[bnum];
66
654k
    const hcode16_t *bookb = hmap[bnum + 1];
67
654k
    int a = 0, b = 0;
68
654k
    int i;
69
70
654k
    switch (bnum) {
71
140k
    case HCB_1:
72
824k
        for (i = 0; i < len; i += 4) {
73
684k
            int idx = 40 + DIM_S4*DIM_S4*DIM_S4 * qs[i] + DIM_S4*DIM_S4 * qs[i+1] + DIM_S4 * qs[i+2] + qs[i+3];
74
684k
            a += booka[idx].len;
75
684k
            b += bookb[idx].len;
76
684k
        }
77
140k
        break;
78
215k
    case HCB_3:
79
1.24M
        for (i = 0; i < len; i += 4) {
80
1.03M
            int a0 = abs(qs[i]), a1 = abs(qs[i+1]), a2 = abs(qs[i+2]), a3 = abs(qs[i+3]);
81
1.03M
            int idx = DIM_M4*DIM_M4*DIM_M4 * a0 + DIM_M4*DIM_M4 * a1 + DIM_M4 * a2 + a3;
82
1.03M
            a += booka[idx].len;
83
1.03M
            b += bookb[idx].len;
84
1.03M
        }
85
215k
        break;
86
299k
    case HCB_5:
87
3.04M
        for (i = 0; i < len; i += 2) {
88
2.75M
            int idx = 40 + DIM_S2 * qs[i] + qs[i+1];
89
2.75M
            a += booka[idx].len;
90
2.75M
            b += bookb[idx].len;
91
2.75M
        }
92
299k
        break;
93
0
    default:
94
0
        break;
95
654k
    }
96
97
654k
    *bits_a = a;
98
654k
    *bits_b = b;
99
654k
}
100
101
/* Sizes a band in every book from lo up. The unsigned pair books share one
102
 * walk: magnitudes are clamped to each table, and a book whose LAV the band
103
 * exceeds is sized but never picked, as lo is above it. Unsigned books pay one
104
 * sign bit per nonzero value, counted once. */
105
static void size_books(const int * __restrict qs, int len, int lo, int * __restrict c)
106
434k
{
107
434k
    int i, nnz = 0;
108
109
8.48M
    for (i = 0; i < len; i++)
110
8.04M
        nnz += qs[i] != 0;
111
1.08M
    for (i = lo; i < HCB_7; i += 2) {
112
654k
        huffcode_size_pair(qs, len, i, &c[i], &c[i + 1]);
113
654k
        if (i == HCB_3) {
114
215k
            c[i] += nnz;
115
215k
            c[i + 1] += nnz;
116
215k
        }
117
654k
    }
118
2.60M
    for (i = HCB_7; i <= HCB_ESC; i++)
119
2.17M
        c[i] = nnz;
120
4.45M
    for (i = 0; i < len; i += 2) {
121
4.02M
        int x0 = abs(qs[i]), x1 = abs(qs[i + 1]);
122
4.02M
        int i7 = DIM_M2_7 * ((x0 > LAV_7) ? LAV_7 : x0) + ((x1 > LAV_7) ? LAV_7 : x1);
123
4.02M
        int i9 = DIM_M2_12 * ((x0 > LAV_12) ? LAV_12 : x0) + ((x1 > LAV_12) ? LAV_12 : x1);
124
4.02M
        int ie = DIM_ESC * ((x0 > LAV_ESC) ? LAV_ESC : x0) + ((x1 > LAV_ESC) ? LAV_ESC : x1);
125
4.02M
        c[HCB_7] += book07[i7].len;
126
4.02M
        c[HCB_8] += book08[i7].len;
127
4.02M
        c[HCB_9] += book09[i9].len;
128
4.02M
        c[HCB_10] += book10[i9].len;
129
4.02M
        c[HCB_ESC] += book11[ie].len + ((x0 >= LAV_ESC) ? escape(x0, NULL) : 0)
130
4.02M
                    + ((x1 >= LAV_ESC) ? escape(x1, NULL) : 0);
131
4.02M
    }
132
434k
}
133
134
/* Appends the band's codewords to coder->s. */
135
static void huffcode_write(const int * __restrict qs, int len, int bnum, CoderInfo *coder)
136
832k
{
137
832k
    const hcode16_t *book = hmap[bnum];
138
832k
    int i;
139
832k
    int datacnt = coder->datacnt;
140
141
832k
    switch (bnum) {
142
19.9k
    case HCB_1:
143
80.2k
    case HCB_2:
144
482k
        for (i = 0; i < len; i += 4) {
145
401k
            int idx = 40 + DIM_S4*DIM_S4*DIM_S4 * qs[i] + DIM_S4*DIM_S4 * qs[i+1] + DIM_S4 * qs[i+2] + qs[i+3];
146
401k
            coder->s[datacnt++] = (uint32_t)book[idx].data | ((uint32_t)book[idx].len << 24);
147
401k
        }
148
80.2k
        break;
149
6.96k
    case HCB_3:
150
66.8k
    case HCB_4:
151
434k
        for (i = 0; i < len; i += 4) {
152
367k
            int q0 = qs[i], q1 = qs[i+1], q2 = qs[i+2], q3 = qs[i+3];
153
367k
            int a0 = abs(q0), a1 = abs(q1), a2 = abs(q2), a3 = abs(q3);
154
367k
            int idx = DIM_M4*DIM_M4*DIM_M4 * a0 + DIM_M4*DIM_M4 * a1 + DIM_M4 * a2 + a3;
155
367k
            int blen = book[idx].len;
156
367k
            int data = book[idx].data;
157
367k
            if (q0) { blen++; data = (data << 1) | (q0 < 0); }
158
367k
            if (q1) { blen++; data = (data << 1) | (q1 < 0); }
159
367k
            if (q2) { blen++; data = (data << 1) | (q2 < 0); }
160
367k
            if (q3) { blen++; data = (data << 1) | (q3 < 0); }
161
367k
            coder->s[datacnt++] = (uint32_t)data | ((uint32_t)blen << 24);
162
367k
        }
163
66.8k
        break;
164
6.04k
    case HCB_5:
165
79.2k
    case HCB_6:
166
754k
        for (i = 0; i < len; i += 2) {
167
675k
            int idx = 40 + DIM_S2 * qs[i] + qs[i+1];
168
675k
            coder->s[datacnt++] = (uint32_t)book[idx].data | ((uint32_t)book[idx].len << 24);
169
675k
        }
170
79.2k
        break;
171
6.39k
    case HCB_7:
172
49.0k
    case HCB_8:
173
502k
        for (i = 0; i < len; i += 2) {
174
453k
            int q0 = qs[i], q1 = qs[i+1];
175
453k
            int a0 = abs(q0), a1 = abs(q1);
176
453k
            int idx = DIM_M2_7 * a0 + a1;
177
453k
            int blen = book[idx].len;
178
453k
            int data = book[idx].data;
179
453k
            if (q0) { blen++; data = (data << 1) | (q0 < 0); }
180
453k
            if (q1) { blen++; data = (data << 1) | (q1 < 0); }
181
453k
            coder->s[datacnt++] = (uint32_t)data | ((uint32_t)blen << 24);
182
453k
        }
183
49.0k
        break;
184
4.92k
    case HCB_9:
185
120k
    case HCB_10:
186
1.19M
        for (i = 0; i < len; i += 2) {
187
1.07M
            int q0 = qs[i], q1 = qs[i+1];
188
1.07M
            int a0 = abs(q0), a1 = abs(q1);
189
1.07M
            int idx = DIM_M2_12 * a0 + a1;
190
1.07M
            int blen = book[idx].len;
191
1.07M
            int data = book[idx].data;
192
1.07M
            if (q0) { blen++; data = (data << 1) | (q0 < 0); }
193
1.07M
            if (q1) { blen++; data = (data << 1) | (q1 < 0); }
194
1.07M
            coder->s[datacnt++] = (uint32_t)data | ((uint32_t)blen << 24);
195
1.07M
        }
196
120k
        break;
197
436k
    case HCB_ESC:
198
4.15M
        for (i = 0; i < len; i += 2) {
199
3.71M
            int x0 = abs(qs[i]), x1 = abs(qs[i+1]);
200
3.71M
            int v0 = (x0 > LAV_ESC) ? LAV_ESC : x0;
201
3.71M
            int v1 = (x1 > LAV_ESC) ? LAV_ESC : x1;
202
3.71M
            int idx = DIM_ESC * v0 + v1;
203
3.71M
            int blen = book[idx].len;
204
3.71M
            int data = book[idx].data;
205
3.71M
            if (qs[i]) {
206
3.52M
                blen++;
207
3.52M
                data = (data << 1) | (qs[i] < 0);
208
3.52M
            }
209
3.71M
            if (qs[i+1]) {
210
3.52M
                blen++;
211
3.52M
                data = (data << 1) | (qs[i+1] < 0);
212
3.52M
            }
213
3.71M
            coder->s[datacnt++] = (uint32_t)data | ((uint32_t)blen << 24);
214
3.71M
            if (x0 >= LAV_ESC) {
215
2.12M
                int esc_code = 0;
216
2.12M
                int esc_len = escape(x0, &esc_code);
217
2.12M
                coder->s[datacnt++] = (uint32_t)esc_code | ((uint32_t)esc_len << 24);
218
2.12M
            }
219
3.71M
            if (x1 >= LAV_ESC) {
220
2.07M
                int esc_code = 0;
221
2.07M
                int esc_len = escape(x1, &esc_code);
222
2.07M
                coder->s[datacnt++] = (uint32_t)esc_code | ((uint32_t)esc_len << 24);
223
2.07M
            }
224
3.71M
        }
225
436k
        break;
226
0
    default:
227
0
        break;
228
832k
    }
229
230
832k
    coder->datacnt = datacnt;
231
832k
}
232
233
/* Choose every band's book jointly: per window group, a Viterbi over books
234
 * where a band costs its codewords in that book and each new section costs
235
 * a header, so a band can take a dearer book to stay in its neighbors'
236
 * section. qs holds the regular bands' values back to back, and book[] the
237
 * lowest book that covers each one's peak. State 0 stands for the band's
238
 * own zero/PNS/intensity book. Emits the codewords once the books are known. */
239
void huffbook(CoderInfo *coder, const int *qs)
240
137k
{
241
137k
    enum { NSTATE = HCB_ESC + 1 };
242
137k
    unsigned char from[MAX_SCFAC_BANDS][NSTATE];
243
137k
    int header = 4 + ((coder->block_type == ONLY_SHORT_WINDOW) ? 3 : 5);
244
137k
    int g, b, k, off = 0;
245
246
343k
    for (g = 0, b = 0; g < coder->groups.n; g++) {
247
205k
        int end = b + coder->sfbn, dp[NSTATE], c[NSTATE];
248
        /* the previous band's states and its cheapest; none before the first */
249
205k
        int plo = 1, phi = 0, best = 0, arg = 0;
250
251
4.94M
        for (; b < end; b++) {
252
4.74M
            int book = coder->book[b], lo = 0, hi = 0, nbest = INT_MAX, narg = 0;
253
254
4.74M
            c[0] = 0;
255
4.74M
            if (book >= HCB_1 && book <= HCB_ESC) {
256
832k
                int sfb = b % coder->sfbn;
257
832k
                int len = (coder->sfb_offset[sfb + 1] - coder->sfb_offset[sfb]) * coder->groups.len[g];
258
832k
                lo = ((book - 1) & ~1) + 1;
259
832k
                hi = HCB_ESC;
260
                /* An escape-only band has one choice, so its cost is moot. */
261
832k
                if (lo < HCB_ESC)
262
434k
                    size_books(qs + off, len, lo, c);
263
398k
                else
264
398k
                    c[HCB_ESC] = 0;
265
832k
                off += len;
266
832k
            }
267
268
12.4M
            for (k = lo; k <= hi; k++) {
269
7.65M
                int open = best + header;
270
7.65M
                int stay = (k >= plo && k <= phi && (k || coder->book[b - 1] == book)) ? dp[k] : INT_MAX;
271
7.65M
                from[b][k] = (stay <= open) ? k : arg;
272
7.65M
                dp[k] = c[k] + ((stay <= open) ? stay : open);
273
7.65M
                if (dp[k] < nbest) { nbest = dp[k]; narg = k; }
274
7.65M
            }
275
4.74M
            plo = lo; phi = hi; best = nbest; arg = narg;
276
4.74M
        }
277
278
4.94M
        for (k = arg, b = end - 1; b >= end - coder->sfbn; b--) {
279
4.74M
            if (k)
280
832k
                coder->book[b] = k;
281
4.74M
            k = from[b][k];
282
4.74M
        }
283
205k
        b = end;
284
205k
    }
285
286
4.88M
    for (b = 0, off = 0; b < coder->bandcnt; b++) {
287
4.74M
        int book = coder->book[b];
288
4.74M
        if (book >= HCB_1 && book <= HCB_ESC) {
289
832k
            int sfb = b % coder->sfbn;
290
832k
            int len = (coder->sfb_offset[sfb + 1] - coder->sfb_offset[sfb]) * coder->groups.len[b / coder->sfbn];
291
832k
            huffcode_write(qs + off, len, book, coder);
292
832k
            off += len;
293
832k
        }
294
4.74M
    }
295
137k
}
296
297
/* Encode the section data (codebook indices and run lengths). */
298
int writebooks(CoderInfo *coder, BitStream *stream)
299
137k
{
300
137k
    int bits = 0;
301
    /* Section run field is 3 bits for short windows (max 7 windows/section) and
302
     * 5 bits for long windows (max 31 bands/section) — ISO 14496-3 §4.6.8.2. */
303
137k
    int max_run = (coder->block_type == ONLY_SHORT_WINDOW) ? 7 : 31;
304
137k
    int run_bits = (coder->block_type == ONLY_SHORT_WINDOW) ? 3 : 5;
305
137k
    int g;
306
137k
    BitAccumulator acc = {0};
307
308
137k
    AccumBegin(&acc, stream);
309
310
343k
    for (g = 0; g < coder->groups.n; g++) {
311
205k
        int b = g * coder->sfbn;
312
205k
        int end = b + coder->sfbn;
313
498k
        while (b < end) {
314
293k
            int book = coder->book[b];
315
293k
            int run = 0;
316
5.03M
            while (b + run < end && coder->book[b + run] == book) run++;
317
293k
            b += run;
318
319
293k
            AccumPutBits(&acc, (uint32_t)book, 4);
320
293k
            bits += 4;
321
322
503k
            while (run >= max_run) {
323
209k
                AccumPutBits(&acc, (uint32_t)max_run, run_bits);
324
209k
                bits += run_bits;
325
209k
                run -= max_run;
326
209k
            }
327
293k
            AccumPutBits(&acc, (uint32_t)run, run_bits);
328
293k
            bits += run_bits;
329
293k
        }
330
205k
    }
331
332
137k
    AccumEnd(&acc);
333
137k
    return bits;
334
137k
}
335
336
/* Encode scalefactor deltas using HCB_DELTA (book12). */
337
int writesf(CoderInfo *coder, BitStream *stream)
338
137k
{
339
137k
    int i, bits = 0;
340
137k
    int lastsf = coder->global_gain;
341
137k
    int lastis = 0;
342
137k
    int lastpns = coder->global_gain - SF_PNS_OFFSET;
343
137k
    int is_first_pns = 1;
344
137k
    BitAccumulator acc = {0};
345
346
137k
    AccumBegin(&acc, stream);
347
348
4.88M
    for (i = 0; i < coder->bandcnt; i++) {
349
4.74M
        int book = coder->book[i];
350
4.74M
        int val = coder->sf[i];
351
4.74M
        int diff, code, len;
352
353
4.74M
        if (book == HCB_ZERO || book == HCB_NONE) continue;
354
355
1.49M
        if (book == HCB_INTENSITY || book == HCB_INTENSITY2) {
356
66.2k
            diff = clamp_sf_diff(val - lastis);
357
66.2k
            lastis += diff;
358
1.42M
        } else if (book == HCB_PNS) {
359
591k
            diff = val - lastpns;
360
591k
            if (is_first_pns) {
361
                /* First PNS band is coded as an absolute 9-bit value (biased by 256)
362
                 * because there is no prior PNS entry to delta from yet. */
363
25.9k
                AccumPutBits(&acc, (uint32_t)(diff + 256), 9);
364
25.9k
                bits += 9;
365
25.9k
                lastpns = val;
366
25.9k
                is_first_pns = 0;
367
25.9k
                continue;
368
25.9k
            }
369
565k
            diff = clamp_sf_diff(diff);
370
565k
            lastpns += diff;
371
832k
        } else {
372
832k
            diff = clamp_sf_diff(val - lastsf);
373
832k
            lastsf += diff;
374
832k
        }
375
376
1.46M
        code = book12[SF_DELTA + diff].data;
377
1.46M
        len = book12[SF_DELTA + diff].len;
378
1.46M
        AccumPutBits(&acc, (uint32_t)code, len);
379
1.46M
        bits += len;
380
1.46M
    }
381
382
137k
    AccumEnd(&acc);
383
137k
    return bits;
384
137k
}