Skip to content

Psychoacoustic model, fixed point

Latest

Choose a tag to compare

@toots toots released this 30 Nov 00:09
· 1 commit to main since this release

Shine is a fixed-point MP3 encoder: it runs on devices without a floating-point unit, and it's fast everywhere else too. The last release was in 2017, and this one is a big one: shine finally has a psychoacoustic model.

What's new

  • A psychoacoustic model, on by default: masking thresholds, noise allocation, a bit reservoir, short blocks for transients, mid/side stereo decided frame by frame, and a lowpass at low bitrates. It's all still fixed point, with no floating point and no libm in the library. If you want the details, the whole model is written up in doc/psy.
  • It holds up against LAME, at about three times the speed. Scored with PEAQ's 2f model on 53 music and speech clips, shine gets 60.7 at 64 kbps stereo and LAME (default settings) 56.6; at 96 kbps it's 78.1 against 77.5, and at 128 kbps 90.1 against 90.2. On an Apple M5, shine encodes 128 kbps stereo at 425x realtime, LAME at 154x. The 64 kbps number uses -r, which lets shine drop to a lower samplerate at low bitrates. It's off by default, so the stream always keeps the samplerate you give it unless you ask.
  • A fast mode for devices that can't afford the model: -Q 0 is the original encoder, two to four times faster again (1630x on the same machine).
  • Gapless playback: shine writes the same Info frame as LAME, which FFmpeg, GStreamer and Firefox know how to read, and streams no longer get cut short at the end.
  • Faster across the board, with NEON and AVX2 code picked at run time and identical output everywhere.
  • Lots of fixes: invalid streams at some samplerates and bitrates, output that was 1 dB too loud, distortion on loud input, and different output on ARM and MIPS.

Speed and quality

Encoding speed at 44.1 kHz stereo 128 kbps: shine's fast mode 1630x, shine 425x, LAME -q 7 310x, FDK AAC-LC 240x, LAME default 154x realtime Quality against bitrate at 44.1 kHz stereo, 64 to 192 kbps: shine above LAME at 64 kbps and level with it from 96, FDK AAC-LC highest up to 128 kbps, shine's fast mode lowest

How this was made

Most of this release was written with an AI coding assistant. The programmer set the direction and the constraints (fixed point, no libm, no floating point in the library), reviewed every change, did the listening and made the design decisions.

A clean-room spec. LAME served as the reference model, but its code never reached the encoder. The work ran in three passes, each reading only what the previous one wrote: first a description of how LAME's psychoacoustic model behaves, then a spec for shine written from that description, with MUST/SHOULD/MAY rules, named constants and known pitfalls, and finally a fixed-point implementation written from the spec alone. The spec lives in doc/psy and is complete enough to rebuild the model without the code. It remains the source of truth: every later change went into the spec first, then into the code.

Optimization loops. Quality tuning is automated around PEAQ. A special build exposes the model's constants as knobs, candidates are screened on a few clips, and the survivors face a gate on the full 53-clip corpus: no clip may lose more than 5 points, and the mean may not drop. What passes goes into the spec, then into the code, and the release build must produce exactly the same streams as the gated one. Hundreds of candidates went through this loop, with blind listening tests as checkpoints.

CPU time got a loop of its own. We profiled each encoding step, read the assembly the compiler produced for the hot ones, and tried vectorization options: compiler flags, loop shapes, intrinsics. An option stayed only if it was faster and bit-identical to the reference, and was then written directly into the code. The result is a set of NEON and AVX2 kernels picked at run time, all matching the portable C version bit for bit.

Tooling. With an assistant, tooling is cheap to build, so we built a lot of it: a quality report and a quality gate that score any encoder against LAME and FDK AAC, a speed and memory report, per-step profiles, disassembly of the built encoder to see what the compiler vectorized, and timed test builds of each vectorization option, compared bit for bit against the reference. Add to that a reference oracle for the fixed-point model, a check that keeps floating point out of the library, golden hashes that pin the output on every architecture, diagnosis scripts for block types, bit usage and error spectra, the README charts and the blind-test page. CI covers x86, ARM, s390x (big-endian), WebAssembly and sanitizers.

Upgrading

This release breaks the API and the ABI, so you'll need to recompile. The new header is shine/shine.h, and every name is now prefixed (SHINE_MONO, mpeg.bitrate, ...). Your 3.x code should still build as is through shine/layer3.h; the compiler will just point out each old name you're using. Everything is listed in the ChangeLog.

The JavaScript package, @toots/shine.js, goes to 2.0.0: it's now an ES module compiled to WebAssembly, and it gets the model too.

Come listen

Those scores come from a model of human hearing, not from people. So what do your ears say? There's a blind test that puts shine 4.0 next to LAME and AAC (Fraunhofer's FDK) on 15 music and speech clips. The results update live, right next to what the model predicted: https://toots.github.io/shine/listen/

It's eight short tests, about fifteen minutes with headphones. Every answer helps, especially if your ears disagree with the scores.

Full changes

New:
* A psychoacoustic model (`doc/psy/`) behind a quality setting:
  `mpeg.quality`, 0 to `SHINE_QUALITY_MAX` (1), default 1; `shineenc -Q`;
  `quality` in the JavaScript package. Quality 1 adds masking thresholds,
  noise allocation, the bit reservoir, short blocks, M/S per frame, and a
  lowpass at low bitrates. At quality 1 a call returns zero or more whole
  frames, and the encoder delay is 784 samples. Quality 0 runs none of it.
  (#26, #27)
* Opt-in resampling at low bitrates, which the model is tuned for:
  `shine_recommended_samplerate()` with `shine_initialise_at()`,
  `shineenc -r`, `resample` in the JavaScript package.
  `shine_initialise()` keeps the input's samplerate; `shine_samplerate()`
  gives the stream's.
* `shine_flush()` drains the filterbank: streams no longer end 1057 samples
  short. `shine_encoder_delay()` gives the delay. A second call writes
  nothing.
* The returned data pointer is never NULL, and `written` is -1 on every call
  once the encoder has failed (out of memory), where it was 0.
* Gapless playback: `shine_info_frame()` returns an Info frame in the LAME
  format (a Xing header with LAME's extension), the one FFmpeg, GStreamer
  and Firefox read the encoder delay, length and end padding from. shineenc
  writes it to files; `-T` sets another format name.
* Faster: fast transforms for the filterbank and MDCT, with arm64 NEON and
  x86-64 AVX2 kernels chosen at run time, identical output
  (`SHINE_KERNELS=plain|neon|avx2` forces a set).
* The library uses no floating point and no libm. Its tables are
  precomputed and shared between encoders, about 50 KB less per encoder.

Breaking changes (API and ABI):
* The header is `shine/shine.h`. `shine/layer3.h` keeps the 3.x names
  below, deprecated: 3.x code compiles unchanged, with a warning at each
  use under GCC and clang, but must be recompiled.
* Public names are prefixed and config fields spelled out:
  - `MONO`, `STEREO`, `JOINT_STEREO`, `DUAL_CHANNEL` (`enum modes`):
    `SHINE_MONO`, `SHINE_STEREO`, `SHINE_JOINT_STEREO`,
    `SHINE_DUAL_CHANNEL` (`enum shine_mode`).
  - `NONE`, `MU50_15`, `CITT` (`enum emph`): `SHINE_EMPHASIS_NONE`,
    `SHINE_EMPHASIS_50_15`, `SHINE_EMPHASIS_CCITT` (`enum shine_emphasis`).
  - `MPEG_I`, `MPEG_II`, `MPEG_25` (`enum mpeg_versions`): `SHINE_MPEG_I`,
    `SHINE_MPEG_II`, `SHINE_MPEG_25` (`enum shine_mpeg_version`).
  - `shine_mpeg_t.bitr` and `.emph`: `.bitrate` and `.emphasis`.
  - `PCM_MONO`, `PCM_STEREO` and `LAYER_III` are removed:
    `shine_wave_t.channels` is an int, 1 or 2.
* `shine_mpeg_t` has a `quality` field.
* Input is const: `shine_initialise()` takes a const config,
  `shine_encode_buffer()` samples as `int16_t *const *`,
  `shine_encode_buffer_interleaved()` as `const int16_t *`.
* `shine_initialise()` returns NULL unless `wave.channels` is 1 or 2 and
  `mpeg.mode` is `SHINE_MONO` exactly when it is 1.
* `shine.h` can be included from C++.

Fixed:
* Invalid streams: the padding bit at 8, 16 and 32 kHz (#39), stuffing bits
  at high bitrate mono, stuffing counted as coefficients in
  `part2_3_length`, and Huffman bits miscounted when big values end in the
  first two scalefactor bands.
* `shine_flush()` dropping the last bytes of the stream (#37).
* Output 1 dB too loud (a gain of 9/8), and distortion on full scale input:
  the MDCT has headroom instead of saturating (#24).
* Scalefactor band tables at 16 kHz (two typos) and 24 kHz (band 18), and
  the end of region 0 in short granules at 8 kHz.
* Huffman tables 1 to 12 never chosen, and region addresses carried over
  from the previous granule.
* Quantizer rounding before the 3/4 power, and out-of-bounds reads at low
  bitrates that quantized every coefficient to zero.
* Architectures with assembly multiplies (ARM, MIPS) now produce the same
  output as every other; the assembly is removed.

shineenc:
* Two channels are coded as joint stereo by default; `-s` asks for plain
  stereo. `-m` downmixes stereo input.
* WAV reading: big endian machines (#34), the end of the data chunk,
  files with no channels or a zero byte rate.
* Fix crashes on command lines made only of options.

JavaScript:
* Built to WebAssembly with clang (`make wasm`) instead of Emscripten, as
  an ES module (#36).
* `close()` encodes the samples still buffered, `StereoMode.STEREO` means
  plain stereo, and `encode()` rejects channels of different lengths.

Build:
* The Android ndk-build files are removed: use `configure --host` with the
  NDK's clang.