enc

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package enc is the clean-room MPEG-1 Layer III encoder for go-mp3.

Provenance: every algorithm in this package is derived only from ISO/IEC 11172-3 (and its published errata) and from openly published papers on MPEG audio coding. No LGPL, GPL, or field-of-use-restricted codec source (LAME, Shine, dist10, libmad, mpg123, FFmpeg, Helix) is consulted during its development; LAME, ffmpeg, and mpg123 binaries are used only as black-box compatibility and quality references, never read as source. See PROVENANCE.md at the repository root.

This package must never import internal/dec: the decoder (a function- by-function port of minimp3, see PROVENANCE.md) and the encoder are two separately sourced provenance tracks, and the import graph enforces that separation at compile time. Tests are the one sanctioned exception: a white-box reconstruction gate lives in internal/dec as a _test.go file (package dec) and imports internal/enc to drive the decoder's synthesis filterbank with this package's analysis output, because verifying the forward transform against its own inverse is the only oracle available for an encoder with no bit-exact reference stream.

Index

Constants

View Source
const ChainDelay = 1057

ChainDelay is the measured encoder+decoder algorithmic delay in samples per channel: decoding this encoder's output reproduces the input shifted by exactly this many samples. Measured once at 44.1kHz/320kbps/mono by cross-correlating a deterministic multi-tone input against the decoded output (internal/dec/encx_roundtrip_test.go, TestEncoderChainDelay: the lag that maximizes the raw, unnormalized input-vs-output dot product, over a lag window of [0, 2304)): 1057 samples, exactly the predicted 1057 = 576 (one granule of MDCT prev-history buffering: MDCTGranule needs the PRECEDING granule's subband samples before it emits the first granule's true output) + 481 (the analysis+synthesis polyphase filterbank chain delay, frozen as fbChainDelay in internal/dec/encx_filterbank_test.go:90).

Re-measured (and reconfirmed at this same 1057) after the held-frame one-frame PCM lookahead for attack detection and block switching landed (design decision 11): EncodeFrame now needs one extra input call before a frame's coding can even start (call 1 stashes into held and appends nothing; call n codes the frame stashed since call n-1, once call n's samples supply that frame's lookahead), so N input calls plus a drain still total N+1 emitted frames, and the drain call itself now codes TWO frames back to back (the held real frame, once next is zeroed to silence, then the silence flush frame) instead of one. Both of those are CALL-LATENCY and drain-shape facts about the EncodeFrame API contract, not sample-domain delay: frame k of the emitted STREAM still codes input samples [k*1152, (k+1)*1152) exactly as before the held-frame design, so the decoded-output-vs-input lag this constant measures is unchanged. A roadmap draft once proposed 1057 + 1152 = 2209 for this constant, reasoning from the one-frame call latency; that conflates call latency with stream alignment and was rejected (decision 12): migrating the constant would falsely claim the bitstream carries an extra leading silence frame, which would corrupt any downstream gapless-playback math built on it. ChainDelay < 1152 is asserted alongside the measurement: it is what makes the drain design correct regardless of how many frames the drain call itself codes, since even the wider two-frame drain flush covers more than the chain's total lag, so draining once is enough to push every real sample through the pipeline and out the decoder.

View Source
const PCMScale = 0.5

PCMScale is the input scaling from float32 [-1,1] PCM into the spectral domain the (minimp3-parity, hence ISO-parity) decoder expects. Measured by the Task 2 reconstruction gate (internal/dec/encx_filterbank_test.go, TestReconstructionGate): the brief predicted 32768, reasoning that mp3dScalePcm's final /32768 division needed to be pre-cancelled on the analysis side. The measurement disagreed: with PCMScale=32768 the round-trip chain gain came out at 65536.52 (2^16, not 1), which means the analysis (this package's window/matrix pair) plus synthesis (mp3dSynthGranule) round trip already carries an intrinsic gain of about 2.0 even before mp3dScalePcm's /32768 is folded in. 32768 * 2.0 / 65536 = 1, so the correct pre-scale is 32768/65536 = 0.5, not 32768; that intrinsic factor of 2 most likely traces to the analysis matrix producing values on a scale the decoder's dequantized-spectral-domain synthesis input does not otherwise carry (this port bypasses MDCT/dequantization entirely, so there is no independent scaling stage to absorb it). 0.5 converges the measured gain to 1.0 within the 1% granule-consistency check TestReconstructionGate enforces; see that test for the frozen fbChainGain and fbChainDelay this value was calibrated against.

View Source
const XminScale float64 = 0x1.fed2bcc6bd0f8p-21

XminScale converts the psymodel's energy domain (PsyOut.Xmin/En, the Hann-windowed FFT analysis over raw [-1,1] PCM) into the coding path's xr domain (PCMScale-scaled MDCT lines quantizeGranule/noiseGranule work in): xminXr[sfb] = PsyOut.Xmin[sfb] * XminScale. MEASURED then frozen by internal/dec's TestPsyXrCalibration (Step 3 of Task 5): the two domains differ by the fixed gain between the analysis FFT and the polyphase+MDCT chain, the PCMScale=0.5 amplitude factor, and the window energy ratios; predicting it analytically repeats the quantGainBase=214 mistake, so the measurement wins and the derivation is documented at TestPsyXrCalibration. Exported (unlike quantGainBase, which has no direct calibration test) so that test can assert against this exact value rather than carrying its own hand-synced copy, following PCMScale's and ChainDelay's precedent for measured cross-package calibration constants in this file.

Measured as the median-of-medians of sum(xr[i]^2 over an sfb)/PsyOut.En [sfb] across a 3-sample-rate x 2-program grid (broadband LCG noise and testsignal.MultiTone), restricted to bands with non-negligible per-line energy density (a tonal program leaves most bands pure window-sidelobe leakage, whose ratio is meaningless noise): see psyXrCalibrationDensityFloor's doc comment in encx_roundtrip_test.go. The winning case was 32kHz LCG noise, 9.514823425525474e-07; the six per-case medians clustered tightly (9.4466e-07 to 1.0171e-06, under 8% spread end to end), and TestPsyXrCalibration re-asserts every surviving individual per-band ratio stays within 4x of this frozen value.

View Source
const XminScaleShort float64 = 0x1.f72d3b5af9b7dp-17

XminScaleShort is XminScale's short-block counterpart (design decision 14): xminXr[b] = PsyOut.XminS[b] * XminScaleShort for a short granule's coding band b. Decision 14 predicted XminScale itself would apply unchanged to XminS, since the psymodel's band-energy mapping and the coding-path spectrum transform look structurally identical for short bands; that prediction did NOT hold. TestPsyXrCalibrationShort (internal/enc/psymodel_test.go) measures the SAME ratio methodology TestPsyXrCalibration uses for XminScale (sum(xr[i]^2 over a coding band)/PsyOut.EnS[band], density-floored, median-of-medians across a 3-sample-rate x 2-program grid of STATIONARY content, entirely bypassing Encoder/quantizeGranule/outerLoop so the freeze is not tautological) and found a systematic, tightly-clustered factor of about 15.76x XminScale (the six per-case medians spanned only 1.31e-05 to 1.53e-05, a much TIGHTER spread than XminScale's own long-block calibration grid), not the "applies unchanged" the decision predicted. This surfaced as a real masking-contract regression before the freeze: TestEncoderMaskingContract failed on a hard silence-to-full-amplitude onset (the granule immediately following stream start, where attackDetect's zero initial carry legitimately calls it an attack) once short blocks were live, because XminScale alone made XminS-derived thresholds far tighter than the short-band coding path could ever satisfy, independent of budget. Freezing this separate, measured constant is exactly decision 14's documented contingency for that outcome, not a silent absorption.

Variables

View Source
var AliasCA = [8]float64{
	-0x1.076bfcd6fbecdp-01,
	-0x1.e30db485db66p-02,
	-0x1.40e604f4701fcp-02,
	-0x1.748ee85851aecp-03,
	-0x1.83603a7f2535ap-04,
	-0x1.4f970dd8206dp-05,
	-0x1.d14239d59a7c1p-07,
	-0x1.e4f68c708d3f4p-09,
}
View Source
var AliasCS = [8]float64{
	0x1.b7095010f9356p-01,
	0x1.c373afe3fa80cp-01,
	0x1.e635b9ee7b56ep-01,
	0x1.f77502a0dd15bp-01,
	0x1.fdb482dd30f5bp-01,
	0x1.ff91f901a8104p-01,
	0x1.fff2c98dbe44ep-01,
	0x1.ffff1a52805d2p-01,
}

AliasCS and AliasCA are the encoder-side antialiasing butterfly coefficients, derived from the ISO/IEC 11172-3:1993 Table B.9 "c" coefficients c = {-0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037} (Annex C, section C.1.5.1) via

cs[i] = 1 / sqrt(1 + c[i]*c[i])
ca[i] = c[i] / sqrt(1 + c[i]*c[i])

Each literal is the exact hex float64 encoding of the corresponding math.Sqrt-derived value from the same throwaway generator as MDCTWindow; the committed literal is the runtime truth. cs is positive for every i (matches the decoder's gAA[0], internal/dec/tables.go, bit for bit in float32); ca is negative because every Table B.9 c is negative, so it matches the decoder's gAA[1] in magnitude only, not sign (see TestEncAliasCoefficientsMatchDec, internal/dec/encx_mdct_test.go).

View Source
var ErrInvalidAudio = errors.New("go-mp3/enc: invalid audio sample")

ErrInvalidAudio is returned by EncodeFrame when samples contains a NaN or an Inf anywhere. Returning it appends nothing to dst and poisons the Encoder: every subsequent call, including a nil drain call, also returns ErrInvalidAudio until Reset. See EncodeFrame's doc comment for the full validation contract.

View Source
var MDCTWindow = [36]float64{
	0x1.65547c4694e11p-05,
	0x1.0b5150f6da2dp-03,
	0x1.bb44b13b62571p-03,
	0x1.33ec389a5a81ep-02,
	0x1.87de2a6aea963p-02,
	0x1.d8d4a0e345738p-02,
	0x1.1318ef2c01a5bp-01,
	0x1.37af93f9513eap-01,
	0x1.59e6f5ae6a0a6p-01,
	0x1.797c6a435ce84p-01,
	0x1.963268b572491p-01,
	0x1.afd100eafc28fp-01,
	0x1.c62648af6577p-01,
	0x1.d906bcf328d46p-01,
	0x1.e84d9692357ep-01,
	0x1.f3dd11fb974b6p-01,
	0x1.fb9ea92ec689bp-01,
	0x1.ff833f9da45f7p-01,
	0x1.ff833f9da45f7p-01,
	0x1.fb9ea92ec689bp-01,
	0x1.f3dd11fb974b6p-01,
	0x1.e84d9692357e1p-01,
	0x1.d906bcf328d46p-01,
	0x1.c62648af65771p-01,
	0x1.afd100eafc291p-01,
	0x1.963268b572492p-01,
	0x1.797c6a435ce85p-01,
	0x1.59e6f5ae6a0a8p-01,
	0x1.37af93f9513ecp-01,
	0x1.1318ef2c01a5dp-01,
	0x1.d8d4a0e345738p-02,
	0x1.87de2a6aea964p-02,
	0x1.33ec389a5a821p-02,
	0x1.bb44b13b6257cp-03,
	0x1.0b5150f6da2cfp-03,
	0x1.65547c4694e1cp-05,
}

MDCTWindow holds the 36 coefficients of the long-block sine window from ISO/IEC 11172-3:1993, section 2.4.3.4.10.3 ("Windowing"), block_type 0: w[i] = sin(pi/36 * (i + 0.5)) for i = 0..35. Each literal is the exact hex float64 encoding of math.Sin(math.Pi/36*(float64(i)+0.5)) computed by a throwaway generator (scratchpad, never committed; see fbtables.go for the same pattern), so no math.Sin call runs at package init or runtime; the committed literal is the runtime truth. This is the forward-transform twin of the decoder's gMdctWindow (internal/dec/tables.go): the two halves of gMdctWindow[0] are this same window, halved and reordered (see TestEncMdctWindowMatchesDec, internal/dec/encx_mdct_test.go).

View Source
var MDCTWindowShort = [12]float64{
	0x1.0b5150f6da2d1p-03,
	0x1.87de2a6aea964p-02,
	0x1.37af93f9513ebp-01,
	0x1.963268b572492p-01,
	0x1.d906bcf328d47p-01,
	0x1.fb9ea92ec689cp-01,
	0x1.fb9ea92ec689bp-01,
	0x1.d906bcf328d46p-01,
	0x1.963268b572492p-01,
	0x1.37af93f9513e8p-01,
	0x1.87de2a6aea95dp-02,
	0x1.0b5150f6da2bfp-03,
}

MDCTWindowShort holds the 12 coefficients of the short-block sine window from ISO/IEC 11172-3:1993, section 2.4.3.4.10.3, block_type 2: w[j] = sin(pi/12 * (j + 0.5)) for j = 0..11, applied identically to each of the three 12-point sub-windows a short-block granule computes per subband (MDCTGranuleBlock, mdct.go). Each literal is the exact hex float64 encoding of the formula, computed by the same throwaway generator as MDCTWindow; the committed literal is the runtime truth, no math.Sin call runs at package init or runtime.

View Source
var MDCTWindowStart = [36]float64{
	0x1.65547c4694e11p-05,
	0x1.0b5150f6da2dp-03,
	0x1.bb44b13b62571p-03,
	0x1.33ec389a5a81ep-02,
	0x1.87de2a6aea963p-02,
	0x1.d8d4a0e345738p-02,
	0x1.1318ef2c01a5bp-01,
	0x1.37af93f9513eap-01,
	0x1.59e6f5ae6a0a6p-01,
	0x1.797c6a435ce84p-01,
	0x1.963268b572491p-01,
	0x1.afd100eafc28fp-01,
	0x1.c62648af6577p-01,
	0x1.d906bcf328d46p-01,
	0x1.e84d9692357ep-01,
	0x1.f3dd11fb974b6p-01,
	0x1.fb9ea92ec689bp-01,
	0x1.ff833f9da45f7p-01,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1.fb9ea92ec689bp-01,
	0x1.d906bcf328d46p-01,
	0x1.963268b572492p-01,
	0x1.37af93f9513e8p-01,
	0x1.87de2a6aea95dp-02,
	0x1.0b5150f6da2bfp-03,
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x0p+00,
}

MDCTWindowStart holds the 36 coefficients of the start-block sine window from ISO/IEC 11172-3:1993, section 2.4.3.4.10.3, block_type 1: long rise (the same sin(pi/36*(i+0.5)) as MDCTWindow for i = 0..17, so that the overlap with a preceding long block stays consistent), a flat plateau of 1.0 for i = 18..23, a short fall of sin(pi/12*(i-18+0.5)) for i = 24..29 (the falling half of the 12-point short window, so the overlap with a following short block stays consistent), and a zero tail for i = 30..35. Each literal is the exact hex float64 encoding of the piecewise formula above, computed by a throwaway generator (scratchpad, never committed; see MDCTWindow's doc comment for the same pattern); the committed literal is the runtime truth, no math.Sin call runs at package init or runtime. The first 18 entries are bit-exact equal to MDCTWindow[:18] (both compute the same formula); see TestMdctShortTablesRecompute.

View Source
var MDCTWindowStop = [36]float64{
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x0p+00,
	0x1.0b5150f6da2bfp-03,
	0x1.87de2a6aea95dp-02,
	0x1.37af93f9513e8p-01,
	0x1.963268b572492p-01,
	0x1.d906bcf328d46p-01,
	0x1.fb9ea92ec689bp-01,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1p+00,
	0x1.ff833f9da45f7p-01,
	0x1.fb9ea92ec689bp-01,
	0x1.f3dd11fb974b6p-01,
	0x1.e84d9692357ep-01,
	0x1.d906bcf328d46p-01,
	0x1.c62648af6577p-01,
	0x1.afd100eafc28fp-01,
	0x1.963268b572491p-01,
	0x1.797c6a435ce84p-01,
	0x1.59e6f5ae6a0a6p-01,
	0x1.37af93f9513eap-01,
	0x1.1318ef2c01a5bp-01,
	0x1.d8d4a0e345738p-02,
	0x1.87de2a6aea963p-02,
	0x1.33ec389a5a81ep-02,
	0x1.bb44b13b62571p-03,
	0x1.0b5150f6da2dp-03,
	0x1.65547c4694e11p-05,
}

MDCTWindowStop holds the 36 coefficients of the stop-block sine window from ISO/IEC 11172-3:1993, section 2.4.3.4.10.3, block_type 3: the exact time reverse of MDCTWindowStart, i.e. MDCTWindowStop[i] = MDCTWindowStart[35-i] (decision 3). This gives a zero head (i = 0..5), a short rise of sin(pi/12*(i-6+0.5)) (i = 6..11, the mirror of MDCTWindowStart's short fall), a flat plateau of 1.0 (i = 12..17), and a long fall of sin(pi/36*(i+0.5)) (i = 18..35, mathematically identical to MDCTWindow's own second half via the sin(pi-x) = sin(x) symmetry, and equal within the recompute tolerance: because these literals are the exact reverse of MDCTWindowStart rather than an independent re-evaluation of the sine at i = 18..35, 12 of the 18 tail entries differ from MDCTWindow[18:36] by 1 ULP, which is expected and harmless). Each literal is the exact hex float64 encoding of MDCTWindowStart[35-i] from the same throwaway generator as MDCTWindowStart; the committed literal is the runtime truth. See TestMdctShortTablesRecompute for the reverse-relationship check.

Functions

func AliasReduce

func AliasReduce(xr *[576]float64)

AliasReduce applies the encoder-side aliasing butterflies (the exact inverse rotation of the decoder's l3Antialias) across the 31 subband boundaries of a long-block granule, in place.

Exported for the same cross-package test reason as FlipOddSubbands.

CORRECTNESS PIN (re-derived and verified empirically against TestEncMdctTDACRoundTrip and TestEncAliasCancellation, internal/dec/encx_mdct_test.go; this deviates from the Task 3 brief's literal Step 3 pseudocode, see the task report for the full derivation): l3Antialias (internal/dec/stereo.go) computes, in terms of the decoder's own tables, g[18+i] = u*gAA0 - d*gAA1, g[17-i] = u*gAA1 + d*gAA0, with both gAA0 and gAA1 POSITIVE. AliasCS is bit-exact equal to gAA0, but AliasCA (Step 1c: c/sqrt(1+c*c) with every Table B.9 c negative) is the SIGNED, NEGATIVE value, so gAA1 = -AliasCA, not +AliasCA. Substituting that identity into l3Antialias's formula and solving the resulting linear system for the encoder's (u2,d2) such that applying l3Antialias to (u2,d2) reproduces the original (u,d) gives:

u2 = u*AliasCS[i] - d*AliasCA[i]
d2 = u*AliasCA[i] + d*AliasCS[i]

A naive transpose of the rotation written with a POSITIVE "ca" (i.e. u2 = u*cs + d*ca, d2 = d*cs - u*ca) is only correct if ca is positive; plugging in the signed, negative AliasCA there flips a sign relative to the true inverse and produces gross reconstruction error (empirically measured max abs error 1.24 on values of order 1, versus ~1e-7 with the formula above). TestEncMdctTDACRoundTrip is the arbiter: it fails loudly on a wrong sign, and confirms the formula above, not the naive one.

func AppendFramePin

func AppendFramePin(dst []byte, bitrateIndex, srIndex, padding, mode int, xr *[2][2][576]float64, nch int) []byte

AppendFramePin codes xr[g][ch] through the production codeGranule (real budget arithmetic, including the maxPart23Length cap) and assembles one frame via the production assembleFrame. Test-only.

func AppendFrameScfPin

func AppendFrameScfPin(dst []byte, bitrateIndex, srIndex, padding, mode int, xr *[2][2][576]float64, pins *[2][2]ScfPin, useScfsi bool, nch int) []byte

AppendFrameScfPin codes xr[g][ch] through the production codeGranule with each granule-channel's scalefactor state PRESET from pins (the inner rate loop only; no outer loop chooses the scalefactors here, that is Task 4/5's job), picks each granule-channel's cheapest covering scalefac_compress via chooseScalefacCompress, optionally detects and applies scfsi across granule 0/1 per channel, and assembles one frame via the production assembleFrame. Test-only, the AppendFramePin precedent.

scalefac_compress is chosen, and gc.part2Bits set, BEFORE codeGranule runs: chooseScalefacCompress depends only on the pinned sf, not on the quantized spectrum, so the granule-channel's part2 cost is already known. codeGranule is then budgeted at budget-part2 (not the raw per-granule share), so its Huffman rate loop leaves exactly enough room for the scalefactor bits assembleFrame will also have to write; without that reduction, part2 would land on top of an already-full Huffman budget and overflow the frame's fixed byte length.

func AppendFrameShortPin

func AppendFrameShortPin(dst []byte, bitrateIndex, srIndex, nch int, blockTypes *[2][2]int, xr *[2][2][576]float64, xmin *[2][2][39]float64) []byte

AppendFrameShortPin codes one self-contained frame (main_data_begin 0, the AppendFramePin precedent) with each granule-channel's block type FORCED from blockTypes, through the real production pipeline: outerLoop (the masking-driven inner rate loop, unchanged by this task) picking scalefactors/subblock_gain/global_gain against xmin, codeGranule's regionsFor dispatch routing a window-switching granule to chooseRegionsWS, and the same render path (writeSideInfo, writeScalefactors, writeSpectrum) every other pin uses. xr must already be in CODING order for any granule-channel whose blockTypes entry is blockShort (callers run reorderShort first; see bandLayout's doc comment for what "coding order" means for a short granule).

Padding is fixed at 0 and mode is derived from nch (single_channel for mono, L/R stereo for two channels): this pin exists to drive the window-switching side-info and readback gates, not to exercise every header permutation AppendFramePin/AppendFrameScfPin already cover.

func AppendFrameShortPinSG

func AppendFrameShortPinSG(dst []byte, bitrateIndex, srIndex, nch int, blockTypes *[2][2]int, xr *[2][2][576]float64, subblockGain *[2][2][3]int) []byte

AppendFrameShortPinSG is AppendFrameShortPin's sibling for driving subblock_gain directly: instead of letting outerLoop's masking escalation (escalateSubblockGain) pick subblock_gain, each granule-channel's value is FORCED from subblockGain and the inner rate loop alone (codeGranule) codes the granule against it, the AppendFrameScfPin precedent for scf/ scalefacScale/preflag applied here to subblock_gain instead.

This exists because escalateSubblockGain, as integrated into outerLoop, is largely a no-op in practice (a separate, already-flagged concern): driving a nonzero subblock_gain through the real outer loop is unreliable, but the decoder-readback gate for the iscf += subblockGain[i] << sh dequant term (internal/dec/scalefactors.go) needs a known nonzero value regardless of whether the escalation policy would ever choose one. blockTypes must pick blockShort/blockStart/blockStop for any granule-channel given a nonzero subblockGain; a long granule ignores it entirely (ISO 2.4.1.7, no subblock_gain field).

func BigTableDim

func BigTableDim(t int) int

BigTableDim and BigTableLinbits expose bigTables[t]'s shape: the round-trip gate needs a table's dimension (to sweep every (x,y) pair in its domain) and linbits (to build escape-magnitude test values and to cross-check against the decoder's linbitsTable) without duplicating ISO Table B.7's per-table layout in the test. See this section's doc comment for why they are exported.

func BigTableLinbits

func BigTableLinbits(t int) int

BigTableLinbits is documented on BigTableDim.

func EncodeHuffmanPin

func EncodeHuffmanPin(w *bits.Writer, ix *[576]int32, bigValues, count1 int, table, count1Table uint8, sfbWidths *[22]int) int

EncodeHuffmanPin Huffman-codes ix's first bigValues pairs (all under codebook table) followed by count1 count1-quads (under count1Table, 0 = table A, 1 = table B), exactly as writeSpectrum would for a chooseRegions result that picked table for every region. Returns the bits written.

func FlipOddSubbands

func FlipOddSubbands(s *[18][32]float64)

FlipOddSubbands negates every odd-indexed sample of every odd subband (the polyphase frequency inversion; the decoder undoes it in l3ChangeSign, internal/dec/decode.go). Applied to each granule's subband samples after analysis, before they enter MDCT history: s[t][b] is negated for t odd (1, 3, .. 17) and b odd (1, 3, .. 31), mirroring l3ChangeSign's index pattern (it negates odd sample indices 1,3..17 of subbands 1,3..31).

Exported: like Filterbank/AnalyzeGranule/PCMScale (see doc.go), the Task 3 brief's illustrative interface listed this unexported, but its decoder-inverse gates live in internal/dec (package dec) and must call it directly; Go visibility is package-scoped, so exporting is the only way to satisfy that cross-package test requirement.

func MDCTGranule

func MDCTGranule(prev, cur *[18][32]float64, xr *[576]float64)

MDCTGranule computes the 36-point forward MDCT with the long sine window for every subband: z = window applied over prev granule's 18 samples then cur's 18, per subband; output xr[b*18+k] is spectral line k of subband b. prev is zero for the first granule of a stream.

Exported for the same cross-package test reason as FlipOddSubbands.

MDCTGranule is a thin wrapper over mdctGranuleWindowed with the long sine window; the shared 36-point kernel and its float64()-wrap FMA-blocking discipline are documented on its pure-Go reference, mdctGranuleWindowedGo, below.

func MDCTGranuleBlock

func MDCTGranuleBlock(prev, cur *[18][32]float64, xr *[576]float64, blockType int)

MDCTGranuleBlock computes one granule's forward MDCT for the given block type (blockLong, blockStart, blockShort or blockStop, blocktypes.go). blockLong, blockStart and blockStop share mdctGranuleWindowed, parameterized by their respective window; blockShort runs mdctGranuleShort's three 12-point MDCTs per subband instead. AliasReduce is NOT called here for any block type; the caller applies it afterward for blockLong/blockStart/blockStop only, mirroring the decoder's antialias gating (l3Decode, internal/dec/decode.go, skips l3Antialias for a pure short granule via aaBands = nLongBands - 1 = -1).

func PretabLongPin

func PretabLongPin() [21]int

PretabLongPin exposes pretabLong to the internal/dec encx_ cross-check (test-only entry; the AppendFramePin precedent).

func ReorderShort

func ReorderShort(src, dst *[576]float64, widths *[13]int)

ReorderShort exposes reorderShort to internal/dec's white-box inverse gate (encx_reorder_test.go), the sanctioned cross-package test exception (see doc.go and huffman.go's identical "Test-only cross-package surface" precedent): the gate needs to drive reorderShort directly and feed its output through the decoder's unexported l3Reorder to check the round trip.

func ResCapBytesPin

func ResCapBytesPin(kbps, sampleRateHz, nch int) int

ResCapBytesPin exposes the occupancy cap to the internal/dec occupancy-replay validator (test-only entry, the AppendFramePin precedent), keyed by the header-derived kbps and sample rate. Guards both map lookups (carry-forward from Task 1's review: an unknown kbps or sampleRateHz would otherwise silently fall through to index 0 and compute a wrong, possibly negative cap) with a panic instead, since a caller passing an illegal combination is a test-harness bug this pin should surface immediately rather than let ripple into a confusing replay failure. Defense in depth only: real callers derive kbps/sampleRateHz from a decoder-validated header, which already rejects illegal bitrate and sample-rate indices at sync.

func SfbWidthsLongRow

func SfbWidthsLongRow(rate int) [22]int

SfbWidthsLongRow returns a copy of sfbWidthsLong[rate] (rate: 0=44100, 1=48000, 2=32000 Hz), for the round-trip gate's grInfo.sfbTab pin and for cross-checking against the decoder's scfLongTable rows. Returned by value, not as a pointer into the package-level sfbWidthsLong array: a live pointer would let any future cross-package caller mutate (or race on) this package's internal table. See this section's doc comment for why it is exported.

func SfbWidthsShortRow

func SfbWidthsShortRow(rate int) [13]int

SfbWidthsShortRow returns a copy of sfbWidthsShort[rate] (rate: 0=44100, 1=48000, 2=32000 Hz), for cross-checking against the decoder's scfShortTable rows. Returned by value for the same reason as SfbWidthsLongRow (huffman.go): a live pointer into the package-level table would let a cross-package caller mutate or race on it.

func ValidBitrateKbps

func ValidBitrateKbps(kbps int) bool

ValidBitrateKbps reports whether kbps is one of the 14 legal MPEG-1 Layer III CBR bitrates, ISO/IEC 11172-3 Table B.1. The single source of truth for bitrate legality: bitrateIndexForKbps's key set.

Types

type Config

type Config struct {
	SampleRate  int // 32000, 44100, 48000
	Channels    int // 1 or 2
	BitrateKbps int // 32..320, the 14 MPEG-1 Layer III values

	// FastRateControl selects the inner rate loop's global_gain search:
	// false (the default) is the exact upward linear scan, true is the
	// binary search (codeGranule's fast path). See the public RateControl.
	FastRateControl bool
}

Config is the validated internal encoder configuration.

type DiagGranule

type DiagGranule struct {
	Noise            [39]float64
	XminXr           [39]float64
	Exempt           [39]bool
	BudgetBits       int
	CapacityLeftBits int
	Xr               [576]float64

	// BlockType is this granule-channel's decided window shape
	// (blocktypes.go's blockLong/Start/Short/Stop), added for Inc7's block
	// switching: a caller needs it to pick the matching bandLayout
	// (layoutFor) before re-running outerLoop/noiseGranule/maskingMetrics
	// against the captured Xr/XminXr, since a frame's granule-channels can
	// now carry different block types.
	BlockType int
}

DiagGranule is one granule-channel's post-escalation diagnostic snapshot (captured AFTER Stage 2's masking-driven budget escalation, so every field reflects the frame's FINAL coding, design decision 9): the per-sfb quantization noise the final coding produced (recomputed via noiseGranule against that granule-channel's own gc.ix/globalGain/sf), the calibrated xminXr threshold the outer loop targeted, and which bands are beyond the loop's reach (diagFloorBound: structurally capped, or empirically proven futile to amplify further), where a residual xmin violation is expected, not a defect. BudgetBits is the ceiling this granule-channel was last coded against (post-escalation reclaim, so it equals its kept part23Length); CapacityLeftBits is the frame-level headroom beyond every granule-channel's current BudgetBits (hi*8 minus their sum), the same value for every granule-channel diagnosed in one frame. Xr is a copy of this granule-channel's MDCT spectrum, so a gate can re-run outerLoop against the captured spectrum at a larger budget to check whether a residual violation is genuinely capacity-bound or under-allocation with room to spare (TestEncoderMaskingContract's distinguisher). Test-only, filled by SetDiagHookPin.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder is a stateful MPEG-1 Layer III encoder: it carries the analysis filterbank shift registers, the MDCT overlap history, and the CBR padding accumulator between EncodeFrame calls, so frames from the same stream must be encoded in order with the same Encoder. An Encoder is not safe for concurrent use.

func New

func New(cfg Config) (*Encoder, error)

New returns a new Encoder for cfg, or an error if cfg is not a legal MPEG-1 Layer III CBR configuration.

func (*Encoder) Drained

func (e *Encoder) Drained() bool

Drained reports whether the encoder has emitted its final (silence, history-flushing) frame in response to a nil EncodeFrame call.

func (*Encoder) EncodeFrame

func (e *Encoder) EncodeFrame(dst []byte, samples [][]float32) ([]byte, error)

EncodeFrame consumes exactly 1152 samples per channel of planar float32 PCM in [-1, 1] and appends zero or more complete MP3 frames to dst: the bit reservoir (Task 3) holds a coded frame in the internal FIFO until its main-data area is fully threaded through by later frames' spend, so one call may append nothing, one frame, or several frames that only just became complete.

Validation order: while the encoder is poisoned (a prior call saw a NaN or Inf), every call, including a nil drain call, returns dst unchanged with ErrInvalidAudio; only Reset clears that state. Otherwise, samples == nil drains: it encodes one final frame of silence that flushes the filterbank and MDCT history (ChainDelay < 1152 guarantees that one frame suffices), then force-flushes every frame still held in the FIFO (zero-filling any unfilled area bytes), marks the encoder drained, and is counted in Stats; further nil calls after that append nothing and return a nil error.

Drain is terminal: once drained, any subsequent non-nil call panics (a caller-bug class, matching the length-mismatch panics below), rather than silently encoding more audio whose tail (ChainDelay samples) would never get flushed and whose Drained()==true state would then be misleading. Reset is the only way to encode more audio after draining.

For a non-nil call, samples must have exactly Channels entries, each of exactly 1152 samples; a violation panics (a caller-bug class, distinct from ErrInvalidAudio, matching bits.Writer's n-range panic precedent). The encoder then scans every sample for NaN or Inf before touching any state: a hit returns dst unchanged with ErrInvalidAudio and poisons the stream. Once the scan passes, every finite sample is clamped to [-1, 1] at ingest, which also guarantees global_gain 255 keeps every quantized line within maxQuant, so loud input cannot drive the coder out of range.

func (*Encoder) Reset

func (e *Encoder) Reset(cfg Config) error

Reset clears all stream state (filterbank history, MDCT overlap, padding accumulator, bit reservoir, pending FIFO, poison, drain, and Stats) and revalidates cfg, as at the start of a fresh stream. It is the only way to clear a poisoned Encoder.

func (*Encoder) SetDiagHookPin

func (e *Encoder) SetDiagHookPin(hook func(g, ch int, diag DiagGranule))

SetDiagHookPin installs a test-only hook that codeFrame invokes once per granule-channel, immediately after the outer loop lands its result in gc, with that granule-channel's diagnostic snapshot (g: 0 or 1, ch: the channel index). Nil (the default, and the only value any production path sets) disables it: the single not-nil check codeFrame makes per granule-channel costs nothing measurable, and the Exempt computation (diagFloorBound, a per-band recode-and-compare probe) runs only when a hook is installed, so this method and its hook body never allocate or spend cycles on the encode path.

func (*Encoder) Stats

func (e *Encoder) Stats() Stats

Stats returns the encoder's cumulative counters. MeanGlobalGain divides the integer sum accumulated in codeFrame only here, at read time, so the float division never touches the encode path (and so never perturbs the determinism goldens).

type Filterbank

type Filterbank struct {
	// contains filtered or unexported fields
}

Filterbank is the per-channel 32-band polyphase analysis filterbank (ISO/IEC 11172-3, Annex C, section 3-C.1.3 "Analysis Subband Filter"): a 512-sample sliding window, the C analysis window (fbWindow), and the 32x64 cosine matrix (fbMatrix).

Exported: the task brief's illustrative interface listed this type and its methods unexported (Task 3, same package, was the only stated consumer), but the same brief also requires the reconstruction gate to live in internal/dec (package dec, a different package) and import internal/enc to drive it. Go visibility is package-scoped regardless of test-file status, so an external package's test cannot reach an unexported type or method; exporting Filterbank/AnalyzeGranule/PCMScale is the only way to satisfy that requirement. Reset is exported too, for the Encoder (a later task) to call, not because the cross-package test needs it. The package stays under internal/, so nothing leaks outside this module.

func (*Filterbank) AnalyzeGranule

func (fb *Filterbank) AnalyzeGranule(in []float64, out *[18][32]float64)

AnalyzeGranule consumes 576 input samples (one granule) for one channel and produces 18 blocks of 32 subband samples: out[t][b] is subband b at subband-sample time t. in has length 576; samples are already scaled by PCMScale by the caller.

Float discipline: matrixStep's accumulate, sum += float64(fbMatrix[b][j] * y[j]), carries an explicit float64() conversion that is the load-bearing barrier against arm64 fusing the multiply into an FMA with the accumulator (a bare local assignment does not block that; the compiler fuses across statements). window's product, z[i] = float64(fb.x[i] * fbWindow[i]), feeds a store into z[i], not an adjacent +/-, so its float64() wrap is not a barrier there; this was verified empirically (GOARCH=arm64 go build -gcflags=-S produces byte-identical codegen for that line with or without the wrap). The wrap is kept anyway, as defensive uniformity across the package rather than a correctness requirement. The partial sums in step 3 are plain adds of already-rounded float64 values with no multiply involved, so they need no wrapping. Accumulation in matrixStep runs left to right in index order, fixing the association order for determinism across amd64 and arm64.

func (*Filterbank) Reset

func (fb *Filterbank) Reset()

Reset clears the shift register, as at the start of a fresh stream. It is the stream-restart hook a later task's Encoder calls between streams, mirroring dec.Decoder.Reset; it has no caller within this package or the test suite today.

type PsyModel

type PsyModel struct {
	// contains filtered or unexported fields
}

PsyModel is one channel's psychoacoustic model 2 state. See the plan for field semantics. Not safe for concurrent use; all scratch is preallocated here so AnalyzeGranule is allocation-free.

func (*PsyModel) AnalyzeGranule

func (p *PsyModel) AnalyzeGranule(pcm []float64, out *PsyOut)

AnalyzeGranule runs the full model 2 long-block analysis on a 1024-sample window of one channel's PCM (float64 in [-1, 1], oldest first), plus the short-path outputs (decision 8: always computed, every granule, independent of the granule's actual block type). Allocation-free after Reset.

pcm is CENTERED on the granule (design decision 11, increment 7): the granule's own 576 samples occupy pcm[224:800), with 224 samples of history before them and 224 samples of lookahead after, rather than the pre-increment-7 causal window that ended at the granule's last sample. The caller (Encoder.codeFrame) assembles this window from pcmHist, which holds the one-frame PCM lookahead the centering needs.

func (*PsyModel) Reset

func (p *PsyModel) Reset(srIndex int)

Reset prepares the model for a fresh stream at srIndex (0 = 44100, 1 = 48000, 2 = 32000, the project's srIndex order).

type PsyOut

type PsyOut struct {
	Xmin [22]float64
	En   [22]float64
	SMR  [22]float64
	PE   float64

	// XminS, EnS, and PES are the short-path counterparts, always filled
	// (decision 8: the short analysis runs on every granule regardless of
	// its actual block type, mirroring increment 6's all-four-
	// representations rule), but consumed only for a granule the encoder
	// has chosen to code as short (increment 7's block-switch wiring,
	// task B2). Coding order: band b = 3*sfb + w for short sfb 0..12 and
	// window 0..2 (blocktypes.go's bandLayout convention), so XminS and
	// EnS drop straight into a short granule's bandLayout without
	// reordering.
	XminS [39]float64
	EnS   [39]float64
	PES   float64
}

PsyOut is one granule-channel's psychoacoustic model output over the 22 long scalefactor bands of the current sample rate. Xmin is the allowed noise energy per band (the outer loop's distortion target), En the model's signal energy per band, SMR their ratio (0 where En is 0), and PE the perceptual entropy in BITS (Johnston's convention: line counts times log2 of the energy-to-threshold ratio), so increment 7's block-switch decision can compare against the literature's absolute thresholds (about 1800 bits) directly.

type ScfPin

type ScfPin struct {
	Scf           [21]int
	ScalefacScale int
	Preflag       int
}

ScfPin is one granule-channel's pinned scalefactor state for AppendFrameScfPin: the internal/dec encx_ readback tests drive the inner rate loop at these exact scalefactors instead of the implicit all-zero state codeGranule otherwise sees.

type Stats

type Stats struct {
	Frames         int64
	Bytes          int64
	PaddedFrames   int64
	MeanGlobalGain float64 // mean over all coded granule-channels
	ScfsiBitsSaved int64   // total part2 bits saved by scfsi across every coded frame
}

Stats counts what the encoder emitted since New/Reset.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL