Documentation
¶
Overview ¶
NMR (noise-to-mask ratio) scalefactor coder: an optimal Viterbi search over scalefactors with self rate control. Port of libavcodec/aaccoder_nmr.h @ d09d5afc3a in full; see that header's comment for the objective and the PNS integration.
Package coder implements the quantizer searches, the codebook sectioning trellis and the spectral quantize-and-encode core of the AAC encoder. Mirrors libavcodec/aaccoder.c, aaccoder_trellis.h, aacenc_quantization.h, aacenc_quantization_misc.h and aacenc_utils.h @ d09d5afc3a.
Index ¶
- Constants
- func ApplyTNS(sce *SingleChannelElement)
- func Coef2MinSF(coef float32) uint8
- func EncodeTNSInfo(pb *bits.Writer, sce *SingleChannelElement)
- func FindFormFactor(groupLen, swbSize int, thresh float32, scaled []float32, nzslope float32) float32
- func FindMaxVal(groupLen, swbSize int, scaled []float32) float32
- func FindMinBook(maxval float32, sf int) int
- func InitNextbandMap(sce *SingleChannelElement, nextband *[128]uint8)
- func SetSpecialBandScalefactors(sce *SingleChannelElement)
- func SfdeltaCanRemoveBand(sce *SingleChannelElement, nextband *[128]uint8, prevSF, band int) bool
- func SfdeltaCanReplace(sce *SingleChannelElement, nextband *[128]uint8, prevSF, newSF, band int) bool
- type ChannelElement
- type Coder
- func (c *Coder) CacheInit()
- func (c *Coder) CodebookTrellisRate(pb *bits.Writer, sce *SingleChannelElement, win, groupLen int, _ float32)
- func (c *Coder) MarkPNS(sampleRate, bandwidth int, sce *SingleChannelElement, psy *[128]PsyBand, ...)
- func (c *Coder) QuantizeAndEncodeBand(pb *bits.Writer, in []float32, scaleIdx, cb int, lambda float32, rtz bool)
- func (c *Coder) SearchForIS(sampleRate int, cpe *ChannelElement, psy0, psy1 *[128]PsyBand, lambda float32)
- func (c *Coder) SearchForMS(cpe *ChannelElement, psy0, psy1 *[128]PsyBand, lambda float32)
- func (c *Coder) SearchForPNS(sampleRate, bandwidth int, sce *SingleChannelElement, psy *[128]PsyBand, ...)
- func (c *Coder) SearchForQuantizersFast(bitRate, sampleRate, channels int, sce *SingleChannelElement, ...)
- func (c *Coder) SearchForQuantizersNMR(in *NMRInput, st *NMRState, sce *SingleChannelElement, psy *[128]PsyBand, ...)
- func (c *Coder) SearchForQuantizersTwoLoop(bitRate, sampleRate, channels, bitresAlloc, bandwidth int, pns bool, ...)
- func (c *Coder) SearchForTNS(samplerateIndex int, sce *SingleChannelElement, psy *[128]PsyBand)
- type IndividualChannelStream
- type NMRInput
- type NMRState
- type PsyBand
- type SingleChannelElement
- type TemporalNoiseShaping
Constants ¶
const ( ScaleDiv512 = 36 // sf difference corresponding to a scale change of 512x ScaleOnePos = 140 // sf index corresponding to scale 1.0 ScaleMaxPos = 255 // sf index maximum value ScaleMaxDiff = 60 // maximum sf difference allowed by the standard ScaleDiffZero = 60 // codebook index corresponding to a zero sf difference )
Scalefactor constants. Mirror libavcodec/aac.h @ d09d5afc3a.
const ( NoisePre = 256 // preamble for NOISE_BT, sent with the first noise band NoisePreBits = 9 // length of the preamble NoiseOffset = 90 // subtracted from global gain as the preamble offset )
Noise (PNS) scalefactor coding constants. Mirror libavcodec/aac.h @ d09d5afc3a. Unused until PNS lands; encodeScaleFactors carries the NOISE_BT delta chain from day one (docs/porting-guide.md pitfall 4).
const ( ZeroBT = 0 // scalefactors and spectral data are all zero FirstPairBT = 5 // this and later band types code 2 values per codeword EscBT = 11 // spectral data coded with an escape sequence ReservedBT = 12 // band types following are encoded differently NoiseBT = 13 // spectral data are scaled white noise (PNS) IntensityBT2 = 14 // intensity stereo positions, out of phase IntensityBT = 15 // intensity stereo positions, in phase )
Band types. Mirror enum BandType (libavcodec/aac.h @ d09d5afc3a).
const ( OnlyLongSequence = 0 LongStartSequence = 1 EightShortSequence = 2 LongStopSequence = 3 )
Window sequences. Mirror enum WindowSequence (libavcodec/aac.h @ d09d5afc3a).
const ( TypeSCE = 0 TypeCPE = 1 TypeCCE = 2 TypeLFE = 3 TypeDSE = 4 TypePCE = 5 TypeFIL = 6 TypeEND = 7 )
Raw data block types. Mirror enum RawDataBlockType (libavcodec/aac.h @ d09d5afc3a).
const ( CBTot = 12 CBTotAll = 15 )
Codebook counts. Mirror CB_TOT and CB_TOT_ALL (libavcodec/aacenctab.h @ d09d5afc3a).
const ( RoundStandard = 0.4054 RoundToZero = 0.1054 )
Quantizer rounding constants. Mirror libavcodec/aacenc_utils.h @ d09d5afc3a.
const BandCostIsSIMD = true
BandCostIsSIMD is true on the default build, recording that this package compiled the SIMD band-cost dispatch (bandcost_amd64.go, bandcost_arm64.go, and the portable stub bandcost_other.go on other architectures). The root package asserts it against aac.SIMDEnabled (simd_kernels_test.go).
const (
NMRNCand = 96 // per-band scalefactor candidates (aacenc.h NMR_NCAND)
)
NMR coder constants. Mirror aaccoder_nmr.h @ d09d5afc3a.
const NMRTrellisIsSIMD = true
NMRTrellisIsSIMD is true on the default build, recording that this file provides the SIMD dispatch. The root package asserts it against aac.SIMDEnabled (simd_kernels_test.go), so the public accessor cannot claim a kernel this package did not compile.
const (
TNSMaxOrder = 20 // TNS_MAX_ORDER (aac.h)
)
TNS constants. Mirror libavcodec/aac.h and aacenc_tns.c @ d09d5afc3a. At this pin both long and short coefficient resolutions are 4 bits, so the C's c_bits expression (TNS_Q_BITS == 4) is always 1.
Variables ¶
This section is empty.
Functions ¶
func ApplyTNS ¶
func ApplyTNS(sce *SingleChannelElement)
ApplyTNS filters the working spectrum with the quantized TNS filters, predicting from the pre-filter coefficients. Mirrors aacenc_tns.c:ff_aac_apply_tns @ d09d5afc3a.
func Coef2MinSF ¶
Coef2MinSF returns the minimum scalefactor where the quantized coef does not clip. Mirrors aacenc_utils.h:coef2minsf @ d09d5afc3a. The float expression is truncated once, after all four terms, exactly like the C.
func EncodeTNSInfo ¶
func EncodeTNSInfo(pb *bits.Writer, sce *SingleChannelElement)
EncodeTNSInfo writes the tns_data() payload for one channel. Mirrors aacenc_tns.c:ff_aac_encode_tns_info @ d09d5afc3a.
func FindFormFactor ¶
func FindFormFactor(groupLen, swbSize int, thresh float32, scaled []float32, nzslope float32) float32
FindFormFactor estimates how noisy or tonal a band is from the maxval-energy relation. Mirrors aacenc_utils.h:find_form_factor @ d09d5afc3a.
func FindMaxVal ¶
FindMaxVal returns the maximum pow34-scaled magnitude of a band across a window group. Mirrors aacenc_utils.h:find_max_val @ d09d5afc3a.
func FindMinBook ¶
FindMinBook returns the smallest codebook able to represent a band whose pow34 maximum is maxval at scalefactor index sf. Mirrors aacenc_utils.h:find_min_book @ d09d5afc3a.
func InitNextbandMap ¶
func InitNextbandMap(sce *SingleChannelElement, nextband *[128]uint8)
InitNextbandMap computes the nonzero-band successor map used by the scalefactor delta constraint utilities. Mirrors aacenc_utils.h:ff_init_nextband_map @ d09d5afc3a.
func SetSpecialBandScalefactors ¶
func SetSpecialBandScalefactors(sce *SingleChannelElement)
SetSpecialBandScalefactors derives scalefactor indices for NOISE and INTENSITY bands from their energy values and clips both special delta chains. Mirrors aaccoder.c:set_special_band_scalefactors @ d09d5afc3a.
func SfdeltaCanRemoveBand ¶
func SfdeltaCanRemoveBand(sce *SingleChannelElement, nextband *[128]uint8, prevSF, band int) bool
SfdeltaCanRemoveBand reports whether removing band keeps the scalefactor delta chain legal. Mirrors aacenc_utils.h:ff_sfdelta_can_remove_band @ d09d5afc3a.
func SfdeltaCanReplace ¶
func SfdeltaCanReplace(sce *SingleChannelElement, nextband *[128]uint8, prevSF, newSF, band int) bool
SfdeltaCanReplace reports whether a band's scalefactor can be replaced without violating the SF delta constraints. Mirrors aacenc_utils.h:ff_sfdelta_can_replace @ d09d5afc3a.
Types ¶
type ChannelElement ¶
type ChannelElement struct {
CommonWindow int // set if the channels share the window sequence
MsMode int // mid/side flags coding mode (0 none, 1 masked, 2 all)
IsMode bool // any band uses intensity stereo
MsMask [128]bool // mid/side used per band
IsMask [128]bool // intensity stereo used per band
Ch [2]SingleChannelElement
}
ChannelElement is the CPE wrapper around one or two channels. Mirrors struct ChannelElement (libavcodec/aacenc.h @ d09d5afc3a).
type Coder ¶
type Coder struct {
// RandomState is the deterministic PNS noise LFSR, seeded with
// 0x1f2e3d4c at init (aacenc.c:1640 @ d09d5afc3a).
RandomState int32
// contains filtered or unexported fields
}
Coder holds the scratch state shared by the quantizer search, the sectioning trellis and the quantize-and-encode core: the pow34-scaled coefficients, the integer quantization scratch, the memoization cache and the trellis path matrix. Mirrors the coder-owned fields of AACEncContext (libavcodec/aacenc.h @ d09d5afc3a: scoefs, qcoefs, quantize_band_cost_cache) plus the C stack scratch of codebook_trellis_rate, preallocated here so the encode path performs no steady-state allocations (docs/go-design.md allocation policy).
func (*Coder) CacheInit ¶
func (c *Coder) CacheInit()
CacheInit invalidates the quantize-band-cost cache by bumping the generation stamp. Mirrors aacenc.c:ff_quantize_band_cost_cache_init @ d09d5afc3a. Must be called per channel per search iteration (docs/porting-guide.md pitfall 6).
func (*Coder) CodebookTrellisRate ¶
func (c *Coder) CodebookTrellisRate(pb *bits.Writer, sce *SingleChannelElement, win, groupLen int, _ float32)
CodebookTrellisRate performs run-length codebook sectioning for one window group, minimizing section run bits plus exact spectral payload bits, then writes the section_data and updates the band types and zero flags to the chosen sections. Mirrors aaccoder_trellis.h:codebook_trellis_rate @ d09d5afc3a. The lambda parameter is kept for signature parity with the C coder table; the cost is pure bits.
func (*Coder) MarkPNS ¶
func (c *Coder) MarkPNS(sampleRate, bandwidth int, sce *SingleChannelElement, psy *[128]PsyBand, lambda float32)
MarkPNS flags the bands whose content is noise-like enough to be replaced by perceptual noise substitution. The NMR coder consumes can_pns directly. Mirrors aaccoder.c:mark_pns @ d09d5afc3a.
func (*Coder) QuantizeAndEncodeBand ¶
func (c *Coder) QuantizeAndEncodeBand(pb *bits.Writer, in []float32, scaleIdx, cb int, lambda float32, rtz bool)
QuantizeAndEncodeBand quantizes one band and writes its codewords. rtz selects round-to-zero quantization of ESC escapes for near-clipping windows. Mirrors aaccoder.c:quantize_and_encode_band @ d09d5afc3a (the rtz table differs from the standard one only in the ESC entry).
func (*Coder) SearchForIS ¶
func (c *Coder) SearchForIS(sampleRate int, cpe *ChannelElement, psy0, psy1 *[128]PsyBand, lambda float32)
SearchForIS decides intensity stereo per band for the twoloop and fast coder paths, after quantization. Mirrors aacenc_is.c:ff_aac_search_for_is @ d09d5afc3a.
func (*Coder) SearchForMS ¶
func (c *Coder) SearchForMS(cpe *ChannelElement, psy0, psy1 *[128]PsyBand, lambda float32)
SearchForMS decides mid/side coding per band for the twoloop and fast coder paths, after quantization and the intensity stereo search. Mirrors aaccoder.c:search_for_ms @ d09d5afc3a.
func (*Coder) SearchForPNS ¶
func (c *Coder) SearchForPNS(sampleRate, bandwidth int, sce *SingleChannelElement, psy *[128]PsyBand, lambda float32)
SearchForPNS decides perceptual noise substitution for the twoloop and fast coder paths, after quantization: noise-like near-threshold bands are recoded as NOISE_BT when the estimated noise rate-distortion beats the coded one. Uses the deterministic LFSR noise in RandomState. Mirrors aaccoder.c:search_for_pns @ d09d5afc3a. Splitting this faithfully ported C function would break the line-by-line mapping, hence the complexity waiver.
func (*Coder) SearchForQuantizersFast ¶
func (c *Coder) SearchForQuantizersFast(bitRate, sampleRate, channels int, sce *SingleChannelElement, psy *[128]PsyBand, lambda float32)
SearchForQuantizersFast selects scalefactor indices and band codebooks with the fast two-loop heuristic: derive zero bands and distortion limits from the psy thresholds, estimate initial scalefactors, then run an inner bit-fitting loop against the frame bit budget and an outer quality-improvement loop. Mirrors aaccoder.c:search_for_quantizers_fast @ d09d5afc3a (lines 343-488). The complexity waiver covers a faithful port of a single C function: splitting the nested search loops would break the line-by-line mapping to the pinned source (docs/porting-guide.md ground rule 1).
func (*Coder) SearchForQuantizersNMR ¶
func (c *Coder) SearchForQuantizersNMR(in *NMRInput, st *NMRState, sce *SingleChannelElement, psy *[128]PsyBand, lambda float32)
SearchForQuantizersNMR selects scalefactor indices, band codebooks and PNS decisions with the NMR trellis and runs the coder's self rate control. Mirrors aaccoder_nmr.h:search_for_quantizers_nmr @ d09d5afc3a. The complexity waiver covers a faithful port of a single 490-line C function; splitting it would break the line-by-line mapping to the pinned source (docs/porting-guide.md ground rule 1).
func (*Coder) SearchForQuantizersTwoLoop ¶
func (c *Coder) SearchForQuantizersTwoLoop(bitRate, sampleRate, channels, bitresAlloc, bandwidth int, pns bool, sce *SingleChannelElement, psy *[128]PsyBand, lambda float32)
SearchForQuantizersTwoLoop is the two-loop quantizer search taken from ISO 13818-7 Appendix C: derive zero bands and distortion limits from the psy output, apply noisy-band depriorization and tonal prioritization to the limits, then iterate an inner bit-fitting loop and an outer quality-improvement loop, optionally trading overdistorted bands for PNS-able zeroes under bit starvation. Mirrors aaccoder_twoloop.h:search_for_quantizers_twoloop @ d09d5afc3a. The QSCALE (constant quality) branches are not ported: the pipeline never sets AV_CODEC_FLAG_QSCALE (no VBR mode in the API); this also makes the C's pre-branch sfoffs computation dead, so it is omitted. Splitting this faithfully ported C function would break the line-by-line mapping to the pinned source, hence the complexity waiver.
func (*Coder) SearchForTNS ¶
func (c *Coder) SearchForTNS(samplerateIndex int, sce *SingleChannelElement, psy *[128]PsyBand)
SearchForTNS runs the per-window TNS decision: an LPC fit on the perceptually weighted spectrum of each filter region, gated on the predicted gain, then on the measured post-quantization gain of the filtered spectrum. The filter direction follows the temporal energy split of the windowed time signal retained in RetBuf. Mirrors aacenc_tns.c:ff_aac_search_for_tns @ d09d5afc3a. The negation of the reflection coefficients before quantization is load-bearing: the ff_lpc_calc_ref_coefs_f sign convention is opposite to what the decoder's MA filter needs; fed unnegated, TNS anti-whitens (docs/porting-guide.md pitfall 3, aacenc_tns.c:272). Splitting this faithfully ported C function would break the line-by-line mapping to the pinned source, hence the complexity waiver.
type IndividualChannelStream ¶
type IndividualChannelStream struct {
MaxSfb int // number of scalefactor bands per group
WindowSequence [2]int // current and previous window sequence
UseKBWindow [2]int // 1 = KBD window, 0 = sine, current and previous
GroupLen [8]int // window group lengths
SwbOffset []uint16 // offsets of the lowest line of each band
SwbSizes []uint8 // band sizes for the current window length
NumSwb int // number of scalefactor window bands
NumWindows int
TnsMaxBands int // ff_tns_max_bands_1024/_128 for the frame length
WindowClipping [8]bool // window is near clipping
ClipAvoidanceFactor float32 // attenuation to avoid clipping, 1.0 = none
}
IndividualChannelStream is the per-channel window and band metadata. Mirrors struct IndividualChannelStream (libavcodec/aacenc.h @ d09d5afc3a).
func (*IndividualChannelStream) EachBand ¶
func (ics *IndividualChannelStream) EachBand(nBands int, fn func(w, g, idx int))
EachBand invokes fn for every band position of the first nBands bands of each window group, with w the first window of the group, g the band and idx = w*16+g the canonical slot in the 128-entry band arrays. This is the single home of the band index convention (docs/architecture.md pitfall 1: band arrays are indexed w*16+g, groups iterate w += group_len[w]). GroupLen is >= 1 for every window of a valid ICS: the window decision sets it, and the C iterates the same way (w += ics->group_len[w]). But Go zero-values an array, so a partially initialized ICS would leave GroupLen[w] == 0 here and the loop would never advance -- a hang, in a library, from a struct that was merely forgotten. That is a programming error inside this package, not something a caller can provoke with any input, so it panics like an out-of-range index rather than wedging the caller's goroutine.
type NMRInput ¶
type NMRInput struct {
BitRate int // avctx->bit_rate
SampleRate int // avctx->sample_rate
Channels int // s->channels == avctx->ch_layout.nb_channels
FrameNum int64 // avctx->frame_num
BitresAlloc int // s->psy.bitres.alloc
Bandwidth int // s->bandwidth
CurChannel int // s->cur_channel
Speed int // s->options.nmr_speed
RateControlOK bool // !QSCALE && bit_rate > 0 && bit_rate_tolerance != 0
QScaleChannels int // bch: 2 under QSCALE, else channels
LastFramePBCount int // s->last_frame_pb_count
}
NMRInput carries the encoder-context inputs of search_for_quantizers_nmr that live outside the coder in C (AVCodecContext and AACEncContext fields @ d09d5afc3a).
type NMRState ¶
type NMRState struct {
Nd [128][NMRNCand]float32 // dist / threshold per candidate
Nb [128][NMRNCand]int32 // spectral bits per candidate
Lam [16]float32 // per-channel operating lambda of the previous frame
Counted [16]int // per-channel bits the trellis accounted for
SideEMA float32 // running estimate of real-minus-counted bits per frame
SideInited bool // SideEMA holds a measurement
RCFrameNum int64 // frame the reservoir was last advanced for
LamRC float32 // global-lambda rate control operating lambda
RCFill int // virtual bit reservoir fill, + = bits saved
FramesSinceShort int // long frames since the last short run
PrevWasShort bool // previous frame was a short block
RunBurst float32 // transient bit-burst factor
// contains filtered or unexported fields
}
NMRState is the NMR coder's persistent per-band candidate cost curves (~105 KiB) and rate-control carry-over. Allocated once, on the first encoder init or Reset that selects this coder, then reused across frames and retained across every later Reset (docs/porting-guide.md pitfall 12, issue #45). Mirrors struct AACNMRCurves (libavcodec/aacenc.h @ d09d5afc3a).
type PsyBand ¶
type PsyBand struct {
Bits int32
Energy float32
Threshold float32
Spread float32 // energy spread over the band
}
PsyBand is the per-band psychoacoustic output consumed by the quantizer searches. Mirrors struct FFPsyBand (libavcodec/psymodel.h @ d09d5afc3a).
type SingleChannelElement ¶
type SingleChannelElement struct {
ICS IndividualChannelStream
TNS TemporalNoiseShaping
BandType [128]int // band codebook per w*16+g slot
BandAlt [128]int // alternative band type (PNS bookkeeping)
SfIdx [128]int // scalefactor index per w*16+g slot
Zeroes [128]bool // band is not coded
CanPNS [128]bool // band is allowed to PNS (informative)
IsEner [128]float32 // intensity stereo position
PnsEner [128]float32 // noise energy values
PCoeffs [1024]float32 // MDCT output, pristine
Coeffs [1024]float32 // MDCT output, working copy
RetBuf [2048]float32 // windowed time-domain copy (TNS input later)
}
SingleChannelElement is the per-channel coding state. Mirrors struct SingleChannelElement (libavcodec/aacenc.h @ d09d5afc3a); the pulse field is never used by the encoder and is not ported.
type TemporalNoiseShaping ¶
type TemporalNoiseShaping struct {
Present bool
NFilt [8]int
Length [8][4]int
Direction [8][4]int
Order [8][4]int
CoefIdx [8][4][TNSMaxOrder]int
Coef [8][4][TNSMaxOrder]float32
}
TemporalNoiseShaping is the per-channel TNS decision state. Mirrors struct TemporalNoiseShaping (libavcodec/aacenc.h @ d09d5afc3a).