Skip to content

Upgrade libsonare from 1.10 to 2.0 ​

2.0 changes the public interface of every binding, the C ABI and both command-line front-ends. No 1.10 spelling is kept as an alias: a renamed function, argument, field, flag or token is refused under its old name. A JSON document written by 1.10 that uses a removed key or token is refused when it loads, and nothing converts it; see Documents written by 1.10.

This page is the map: how to find the places your code has to change, and the rules behind the changes, each with a before and after. The complete per-name tables for C, Python, Node, WASM and the command line are in UPGRADING.md in the libsonare repository.

What You Will Learn ​

By the end of this page you should be able to:

  • list every 1.10 name in a JavaScript source tree that 2.0 renamed, removed or changed;
  • recognize the conventions that most renames follow, and write the 2.0 form of each;
  • know what changes per surface (C, Python, Node, WASM and the command line) and where the full table is;
  • tell what happens when a 1.10 project, scene or preset reaches the 2.0 engine.

Find every change your code touches ​

The npm package ships a migration ledger, a JSON file that lists every 1.10 name the JavaScript package changed. Import it as @libraz/libsonare/migration.json; it is { "entry": [...] }, and each entry has these fields.

FieldMeaning
kindWhat the old name was: function, class, type, method, field, option (a parameter of a function or method, written name(parameter)), export or value (a removed string token, written Type='token').
oldThe 1.10 spelling, as name or Owner.name.
newThe 2.0 name when the change is a pure rename.
toThe 2.0 name when the change is more than the name; read changed too.
removedThe name is gone; the text says what to call instead, or that there is no replacement.
changedThe name stays or moves and the caller has to change something; the text says what.
ruleThe convention the change follows; each convention below names its rule.
domainThe area of the library: core, analysis, effects, mastering, engine or project.
entryThe package subpath that exports it, such as ./analysis or ./worklet. . or absent means the main entry.

The script below reads the ledger and reports, for a source tree, each place that spells an old name together with what the entry asks for. Save it as migrate-scan.mjs next to your package.json, after npm install @libraz/libsonare@2, and run it with the directory to scan.

js
import { readdirSync, readFileSync } from 'node:fs';
import { extname, join, sep } from 'node:path';
import ledger from '@libraz/libsonare/migration.json' with { type: 'json' };

const [root = '.', ...flags] = process.argv.slice(2);
const SOURCE = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.svelte']);
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const detail = (e) =>
  e.removed
    ? `removed: ${e.removed}`
    : [`-> ${e.to ?? e.new ?? '(same name)'}`, e.changed].filter(Boolean).join(': ');

// Group entries by the name source code spells: `old` without a `(parameter)` suffix.
const byName = new Map();
for (const e of ledger.entry) {
  if (e.kind === 'value') continue;
  if (flags.includes('--breaking') && !(e.removed || e.to || e.new)) continue;
  const name = e.old.replace(/\(.*$/, '');
  byName.set(name, [...(byName.get(name) ?? []), e]);
}
const matchers = [...byName].map(([name, list]) => ({
  name,
  details: [...new Set(list.map(detail))],
  re: new RegExp(`(?<![\\w$])${escape(name)}(?![\\w$])`, 'g'),
}));

let hits = 0;
for (const rel of readdirSync(root, { recursive: true })) {
  if (rel.split(sep).includes('node_modules') || !SOURCE.has(extname(rel))) continue;
  const text = readFileSync(join(root, rel), 'utf8');
  for (const { name, details, re } of matchers) {
    for (const hit of text.matchAll(re)) {
      console.log(`${join(root, rel)}:${text.slice(0, hit.index).split('\n').length}  ${name}`);
      for (const d of details) console.log(`    ${d}`);
      hits += 1;
    }
  }
}
console.log(`${hits} place(s) to check`);
process.exitCode = hits ? 1 : 0;
sh
node migrate-scan.mjs src --breaking

For a file src/player.ts whose first two lines are const mixer = Mixer.fromSceneJson(json); and const result = analyzeWithProgress(samples, 44100, log);, the output is:

text
src/player.ts:2  analyzeWithProgress
    removed: call analyze with onProgress in the request, for example analyze({ samples, sampleRate, onProgress })
src/player.ts:1  Mixer.fromSceneJson
    -> Mixer.fromJson: static fromJson(json, { sampleRate, maxBlockSize? }) replaces fromSceneJson(json, sampleRate = 48000, blockSize = 512); sampleRate is required; an unread insert params key is refused as InvalidFormat with its indexed document path and the sorted accepted keys
2 place(s) to check

What the scan does and does not catch:

  • It matches the old name as a whole word, so detectBpm is found and detectBpmFast is not. A dotted name such as Mixer.fromSceneJson is matched as written, so it is found when you call it through the class and missed when you call it on an instance.
  • Without --breaking it also reports names that still exist in 2.0 but behave differently, for example a function that now requires sampleRate. Those are reviews rather than errors, and there are many of them; --breaking keeps only entries that give a replacement name or a removal.
  • It does not read value entries, the removed string tokens. Renamed fields and options spelled bare, such as frequency: in an object literal, are missed too. After you upgrade the package, the TypeScript compiler finds those: the 2.0 declarations no longer have the old names.
  • It exits with status 1 when it finds anything, so it can run in CI while you work through the list.

The ledger covers the JavaScript package only. Python and C callers read the per-name tables in UPGRADING.md.

The conventions behind the changes ​

Most of the thousands of renames follow one of a few rules. Each section below states the rule, shows the 1.10 spelling as it was written, and then the 2.0 form, which runs as written on the 2.0 engine. The names are the ones in UPGRADING.md; a ledger rule id is given where the JavaScript ledger has one.

The JavaScript examples assume this setup: samples is a mono Float32Array decoded at 44.1 kHz, and left and right are two such arrays.

ts
import {
  analyze,
  analyzeBpm,
  detectBpm,
  ErrorCode,
  init,
  isSonareError,
  masterAudio,
  masteringNormalizeLoudness,
  melSpectrogram,
  meteringStereoCorrelation,
  Mixer,
  OfflineWorkerClient,
  stft,
  synthesizeRir,
  timeStretch,
  tone,
} from '@libraz/libsonare';

await init();

Sample rate is required wherever samples are passed ​

In 1.10 most analysis and effect calls assumed 22050 Hz when the sample rate was left out, so a 44.1 kHz buffer gave wrong results without a warning. In 2.0 every call that takes samples requires the sample rate and refuses a call without it with a TypeError. Ledger rule: sample-rate-required.

1.x:

ts
const bpm = detectBpm(samples); // assumed 22050 Hz

2.0:

ts
const bpm = detectBpm(samples, 44100);

One-shot calls take a request object ​

The request object is the canonical form. A call that takes samples keeps at most one positional form, (samples, sampleRate, options?); longer positional lists are removed, and an extra argument after a request object is a TypeError. Ledger rule: one-positional-form.

1.x:

ts
timeStretch(samples, 44100, 1.25, 2048, 512);

2.0:

ts
const stretched = timeStretch({ samples, sampleRate: 44100, speedRatio: 1.25, nFft: 2048, hopLength: 512 });

Seconds are spelled Sec ​

A time in seconds ends in Sec (_sec in Python and C, -sec in command-line flags). A Seconds suffix or a bare name is renamed. Ledger rule: seconds-suffix.

1.x:

ts
const rir = synthesizeRir({ maxSeconds: 2 });

2.0:

ts
const rir = synthesizeRir({ sampleRate: 48000, maxSec: 0.5 });

The 2.0 call also names sampleRate, which is required here. The old key maxSeconds is refused with a TypeError that names it.

Physical quantities carry their unit in the name ​

Names end in Sec, Ms, Hz, Db, Cents, Semitones, Bpm and similar, so a value cannot be read in the wrong unit. A bare gain stays linear. Ledger rule: unit-in-name.

1.x:

ts
const sine = tone({ frequency: 440, duration: 1 });

2.0:

ts
const sine = tone({ frequencyHz: 440, durationSec: 1, sampleRate: 44100 });

A value that is not given is absent, never 0, -1 or '' ​

An optional input is left out in JavaScript (None in Python). An explicit 0 where 0 used to mean the default is refused with a RangeError, so a stale sentinel fails loudly instead of changing the result. Ledger rule: absent-not-sentinel.

1.x:

ts
melSpectrogram({ samples, sampleRate: 44100, fmax: 0 }); // 0 meant Nyquist

2.0:

ts
const mel = melSpectrogram({ samples, sampleRate: 44100 }); // omit the upper edge for Nyquist

An explicit zero is refused: synthesizeRir({ sampleRate: 48000, maxSec: 0 }) throws a RangeError reading synthesizeRir: maxSec must not be 0; omit it for the default.

Closed sets are string unions, not numbers ​

A parameter that takes one of a closed set accepts the string token only and refuses a number. Ledger rule: string-closed-sets.

1.x:

ts
mixer.setPan(0, 0.5, 1); // ordinal

2.0:

ts
const scene = JSON.stringify({ version: 2, strips: [{ id: 'a' }], buses: [{ id: 'master', role: 'master' }] });
const mixer = Mixer.fromJson(scene, { sampleRate: 48000 });
mixer.setPan(0, 0.5, 'stereoPan');
mixer.destroy();

Two-dimensional results are one Matrix2D type ​

A 2-D result is { data, rows, cols }, row-major, with bins or coefficients as rows and frames as columns. The per-result dimension names such as nBins and nFrames are gone. Ledger rule: matrix-2d.

1.x:

ts
const { magnitude, nBins, nFrames } = stft({ samples, sampleRate: 44100 });
const v = magnitude[bin * nFrames + frame];

2.0:

ts
const { magnitude } = stft({ samples, sampleRate: 44100 });
const v = magnitude.data[2 * magnitude.cols + 3]; // bin 2, frame 3

masterAudio is the mastering entry ​

masterAudio is the main mastering call. The 1.10 mastering only normalized loudness, so it is now masteringNormalizeLoudness (mastering-normalize-loudness on the command line). Ledger rule: mastering-names.

1.x:

ts
const out = mastering({ samples, sampleRate: 44100, targetLufs: -14 });

2.0:

ts
const out = masteringNormalizeLoudness({ samples, sampleRate: 44100, targetLufs: -14 });
const mastered = masterAudio({ samples, sampleRate: 44100, preset: 'streaming' });

A masterAudio call that gives neither preset nor overrides throws a TypeError; pass overrides: {} for an empty chain.

Handles are released with destroy() ​

A JavaScript handle releases its native resources with destroy() or [Symbol.dispose](), so it works with using. dispose, close and delete are no longer public; in Python a handle is closed with close() or a with block. Ledger rule: teardown.

1.x:

ts
const mixer = Mixer.fromSceneJson(json);
mixer.delete();

2.0:

ts
const mixer = Mixer.fromJson(scene, { sampleRate: 48000 });
mixer.destroy();
// or, in a scope: using mixer = Mixer.fromJson(scene, { sampleRate: 48000 });

Here scene is the document from the closed-sets example. The sample rate is required; fromSceneJson defaulted it to 48000.

Progress is onProgress and cancellation is signal or cancel ​

The *WithProgress twins are removed: the request takes onProgress, a (progress, stage) callback. A synchronous call stops when its cancel function returns true; a promise-returning call takes { signal }. Either way a canceled call is a SonareError with code Cancelled. Ledger rules: progress-callback, cancellation.

1.x:

ts
const result = analyzeWithProgress(samples, 44100, (p, stage) => log(p, stage));

2.0:

ts
const stages = [];
const result = analyze({ samples, sampleRate: 44100, onProgress: (p, stage) => stages.push(stage) });

try {
  analyze({ samples, sampleRate: 44100, cancel: () => true });
} catch (e) {
  if (isSonareError(e) && e.code === ErrorCode.Cancelled) console.log('cancelled');
}

Errors are coded by cause ​

Wrong argument types and unknown request keys throw TypeError. Out-of-range values and unknown names throw RangeError. Other failures use a coded SonareError. For example, a missing Worker is NotSupported. Ledger rule: error-class-by-cause.

1.x:

ts
try { new OfflineWorkerClient(); } catch (e) { /* plain Error */ }

2.0:

ts
let supported = true;
try {
  new OfflineWorkerClient();
} catch (e) {
  if (isSonareError(e) && e.code === ErrorCode.NotSupported) supported = false;
}

Multichannel audio is planar, and stereo-only calls take left and right ​

N-channel audio is channels: Float32Array[] plus sampleRate; Python uses a (channels, n) array. A function defined on exactly two channels, such as correlation, mid/side or pan, takes left and right instead. Ledger rules: planar-channels, stereo-pair.

1.x:

ts
const r = meteringStereoCorrelation(left, right); // assumed 22050 Hz

2.0:

ts
const r = meteringStereoCorrelation({ left, right, sampleRate: 44100 });

Public tempo searches default to 60-200 BPM ​

In 1.10 analyzeBpm and beat detection searched 30-300 BPM while analyze searched 60-200, so one recording could report two tempos. In 2.0 every public entry that takes a tempo range defaults to 60-200 BPM. Pass the range to keep the old search. Ledger rule: tempo-range.

1.x:

ts
analyzeBpm({ samples, sampleRate: 44100 }); // searched 30-300 BPM

2.0:

ts
const tempo = analyzeBpm({ samples, sampleRate: 44100 }); // searches 60-200 BPM
const wide = analyzeBpm({ samples, sampleRate: 44100, bpmMin: 30, bpmMax: 300 }); // the 1.x range

Python keyword arguments are snake_case only, and results are frozen dataclasses ​

Python keyword arguments and attributes are snake_case; the camelCase spellings are no longer accepted. A composite result is a frozen dataclass. A JSON document you author or persist, such as a mastering chain config or a mix scene, keeps the camelCase keys the engine reads, on every surface.

1.x:

python
caps = capabilities()
caps.features.mixingAssistant

2.0:

python
from libsonare import capabilities

caps = capabilities()
caps.features.mixing_assistant

A record stays snake_case whatever its wire form looks like, and a result cannot be assigned to:

python
from libsonare import Audio

audio = Audio.from_buffer(samples, 44100)
result = audio.analyze_bpm()
result.bpm = 100.0  # raises dataclasses.FrozenInstanceError

By surface ​

Each surface has its own section in UPGRADING.md with a table per area of the library, and its own reference on this site.

C ​

Rebuild every consumer against the 2.0 headers. A configuration struct carries struct_size and is seeded by its *_init function, which writes every default. A constructor returns SonareError and hands the object back through an out pointer. A result is released by the function named after it, such as sonare_audio_destroy or sonare_free_string. Full table: C in UPGRADING.md. Reference: C ABI.

c
SonareTimeStretchOptions opts;
sonare_time_stretch_options_init(&opts);
opts.n_fft = 2048;
sonare_time_stretch(samples, length, 44100, 1.25f, &opts, &out, &out_length);

SonareMixer* mixer = NULL;
SonareError err = sonare_mixer_create(48000, 512, &mixer);
if (err != SONARE_OK) { /* inspect sonare_last_error_message() */ }

Python ​

Keyword arguments and attributes are snake_case, a closed set is a string token (key.mode == 'minor'), an option left out is None, a quantity names its unit, and every public type imports from libsonare. sr=22050 survives only on the functions that mirror librosa; a function that is libsonare's own takes a required sample_rate. Full table: Python in UPGRADING.md. Reference: Python API.

Node ​

The Node addon and the WASM package share one vocabulary, so a name has the same 2.0 spelling in both. A refused argument is a TypeError or RangeError, and results are typed values rather than JSON strings. Full table: Node in UPGRADING.md. Reference: Node.js Native API.

WASM and the browser ​

The package exports @libraz/libsonare, @libraz/libsonare/analysis, @libraz/libsonare/worklet and @libraz/libsonare/vocal-edit-worker, and the ledger records which entry a name belongs to. The ./worklet entry exports only its documented surface. Full table: WASM in UPGRADING.md. Reference: WebAssembly Guide and the JavaScript/TypeScript reference.

Command line ​

Both front-ends take the primary input as a positional argument and use the same command names, flags and defaults. --in, --input, --smf and --midi2 are removed. Seconds flags end in -sec, the loudness-only command is mastering-normalize-loudness, and --json result keys are snake_case. Full table: Command line in UPGRADING.md. Reference: CLI reference.

1.x:

sh
sonare fade song.wav --fade-in 0.5 -o out.wav
sonare mastering song.wav --target-lufs -14 -o out.wav

2.0:

sh
sonare fade song.wav --fade-in-sec 0.5 -o out.wav
sonare mastering-normalize-loudness song.wav --target-lufs -14 -o out.wav

A failure prints an Error: line on stderr and nothing on stdout, with --json too, and the exit status says why: 2 for a command-line mistake, before any input is read; 4 for a file that cannot be opened; 5 for a document that cannot be parsed. sonare mastering with neither a preset nor a chain config is a usage error that points to mastering-normalize-loudness.

Live MIDI input timing ​

Details follow in the 2.0 change list.

Beat, onset and meter analysis ​

Details follow in the 2.0 change list.

Documents written by 1.10 ​

A project, mix scene or preset written by 1.10 that uses a removed key or token is refused with InvalidFormat when it loads. Nothing converts it: rewrite the document with the 2.0 names. This example shows a retired mix-scene key: its refusal gives the path and sorted accepted keys without a replacement-spelling hint.

ts
import { init, isSonareError, Mixer } from '@libraz/libsonare';

await init();
const old = JSON.stringify({
  version: 2,
  strips: [{ id: 'a', fader_db: -3 }],
  buses: [{ id: 'master', role: 'master' }],
});

try {
  Mixer.fromJson(old, { sampleRate: 48000 });
} catch (e) {
  if (isSonareError(e)) console.log(e.codeName, e.message);
}

The engine answers with the code InvalidFormat and this message:

text
Mixer.fromJson: unknown key strips[0].fader_db (expected channelDelaySamples, dualPanLeft, dualPanRight, eq, faderDb, id, inputTrimDb, inserts, metering, muted, pan, panLaw, panMode, polarityInvertLeft, polarityInvertRight, sends, soloSafe, soloed, sourceLayout, surroundPan, vcaOffsetDb, width)

Mixer.fromJson takes JSON text: a non-string argument is a TypeError, while malformed or structurally invalid JSON is InvalidFormat. To catch a document with an unknown key, test isSonareError(e) && e.codeName === 'InvalidFormat' and inspect the indexed path and accepted-key list.