Skip to content

Node.js Native Types ​

This page lists the TypeScript interfaces, unions, and exported type names of the @libraz/libsonare-native package. For the functions and classes that use them, see Node.js Native API and Node.js Native Analysis, Effects and Utilities.

Types ​

typescript
interface Key {
  root: PitchClass;    // Pitch-class number, 0..11 (C = 0), as on WASM and Python
  mode: KeyMode;       // 'major' | 'minor' | 'dorian' | 'phrygian' | 'lydian' | 'mixolydian' | 'locrian'
  confidence: number;  // detectKey: softmax share in [0, 1); analyze(): chord-refined, up to 1
  name: string;        // "C major", "A minor"
  shortName: string;   // "C", "Am"
}

interface KeyDetection extends Key {
  tuningCents: number; // cents used for the chroma (given or measured)
}

interface TimeSignature {
  numerator: number;
  denominator: number;
  confidence: number;  // MeterEstimate.timeSignature: margin over the runner-up;
                       // MeterEstimate.candidates[]: share of summed support
}

interface BpmCandidate {
  bpm: number;
  confidence: number;
}

interface AnalysisBpmCandidate extends BpmCandidate {
  relation: 'primary' | 'half' | 'double' | 'other';
}

// One chord from detectChords(...) and from analyze(). root/bass are pitch
// classes (0..11, C = 0); rootName/bassName carry the canonical core spelling,
// identical on every language binding. quality is a string token.
interface Chord {
  root: PitchClass;
  bass: PitchClass;
  rootName: string;
  bassName: string;
  quality: ChordQuality;   // 'major' | 'minor' | 'dominant7' | 'major7' | 'minor7' | 'sus4' | ... | 'unknown'
  name: string;            // Canonical symbol, e.g. "Cmaj7", "Am/C", "N.C."
  startSec: number;
  endSec: number;
  durationSec: number;     // endSec minus startSec
  confidence: number;
}

interface ChordAnalysisResult {
  chords: Chord[];
  tuningCents: number; // cents used for the chroma (given or measured)
}

type ChordFunction = 'tonic' | 'subdominant' | 'dominant' | 'chromatic' | 'none';

// A timed chord plus its place in a key, from chordFunctionalAnalysis(...) and chordFunctions(...).
type FunctionalChord<T = Chord> = T & {
  romanNumeral: string;     // 'I', 'V7'; 'N.C.' when the chord is unknown
  function: ChordFunction;
};

// The key chordFunctions(...) reads; detectKey's result fits as it is.
interface ChordFunctionsKey {
  root: PitchClass;
  mode: KeyMode;
}

type SectionType =
  | 'intro' | 'verse' | 'preChorus' | 'chorus' | 'bridge'
  | 'instrumental' | 'outro' | 'unknown';

// One section from analyzeSections(...) and from analyze().
interface Section {
  type: SectionType;
  name: string;        // Human-readable, e.g. "Chorus"
  startSec: number;
  endSec: number;
  energyLevel: number; // Relative energy, [0, 1]
  confidence: number;  // [0, 1]
  group: number;       // Index of the repeated-material group the section belongs to
}

// analyzeSections(...) returns the sections with the form label.
interface SectionAnalysis {
  sections: Section[];
  form: string;
}

// The chord shape inside AnalysisResult: a Chord plus its place in the detected key.
interface AnalysisChord extends Chord {
  romanNumeral: string; // relative to AnalysisResult.key; empty for N.C.
}

interface Beat {
  timeSec: number;
  strength: number;    // Raw, unbounded onset-envelope frame nearest this beat
}

// Beat-level evidence used by the downbeat and meter decisions.
interface BeatObservations {
  accent: number[];              // Maximum 5 ms RMS near each beat's strongest attack
  hasAttack: boolean[];           // Empty means every beat was treated as attacked
  lowFrequencyEnergy: number[];  // Empty disables masked-beat judgments
  subdivisionAccent: number[];   // One midpoint value per interval; empty when unmeasured
  chordChange: number[];         // Empty until chords are analyzed
}

interface AnalysisResult {
  bpm?: number;
  bpmConfidence: number;
  bpmCandidates: AnalysisBpmCandidate[];
  key: Key;
  timeSignature: TimeSignature;
  timeSignatureCandidates: TimeSignature[];
  beats: Beat[];
  beatObservations: BeatObservations;            // Per-beat evidence
  beatLocalBpm: number[];                        // Empty unless computeTempoCurve
  downbeats: Beat[];                             // The beats that start a bar
  downbeatPhase: number;                         // Beat index the first bar starts on
  chords: AnalysisChord[];                       // Detected chord progression
  sections: Section[];                           // Song-structure sections
  timbre: TimbreFrame;                           // Aggregate timbre summary
  dynamics: AnalysisDynamics;                    // Aggregate dynamics summary
  rhythm: AnalysisRhythm;                        // Aggregate rhythm summary
  melody: AnalysisMelody;                        // Melody-contour summary
  form: string;                                  // Musical form label, e.g. "AABA"
  tuningCents: number;                           // Cents used for the chromagrams
}
// analyze() returns the full result above. The dedicated detect*/analyze*
// functions remain available for targeted or parameterized analysis.

// A matrix is one flat row-major array with its shape.
interface Matrix2D {
  data: Float32Array;
  rows: number;
  cols: number;
}

interface HpssResult {
  harmonic: Float32Array;
  percussive: Float32Array;
  residual?: Float32Array;  // Present when the request set withResidual
  sampleRate: number;
}

interface StftResult {
  nFft: number;
  hopLength: number;
  sampleRate: number;
  magnitude: Matrix2D;      // nBins rows × nFrames columns
  power: Matrix2D;
  db?: Matrix2D;            // Present when the request set db
}

interface MelSpectrogramResult {
  sampleRate: number;
  hopLength: number;
  nFft: number;
  fminHz: number;           // Lower Mel edge in Hz, as applied
  fmaxHz: number;           // Upper edge as applied; Nyquist when the request left it out
  htk: boolean;
  power: Matrix2D;          // nMels rows × nFrames columns
  db: Matrix2D;
}

interface MfccResult {
  sampleRate: number;
  hopLength: number;
  nFft: number;
  nMels: number;
  fminHz: number;
  fmaxHz: number;           // As applied
  htk: boolean;
  lifter: number;           // 0 means none
  coefficients: Matrix2D;   // nMfcc rows × nFrames columns
}

interface ChromaResult {
  sampleRate: number;
  hopLength: number;
  features: Matrix2D;       // 12 rows × nFrames columns
  meanEnergy: number[];     // 12 values
}

interface PitchResult {
  f0: Float32Array;         // Fundamental frequency per frame (Hz)
  voicedProb: Float32Array; // Voicing probability per frame (0–1)
  voicedFlag: boolean[];    // Voiced/unvoiced decision per frame
  medianF0?: number;
  meanF0?: number;
}

// Per-frame voicing decision, one entry per f0Hz frame. Accepted by the
// `voiced` argument and by PitchCorrectOptions.voiced.
type VoicedFlags =
  | Int32Array
  | Uint8Array
  | Float32Array
  | readonly number[]
  | readonly boolean[];

interface MasteringAssistantSuggestStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate: number;
  targetLufs?: number;
  ceilingDbtp?: number;
  enableRepair?: boolean;
  preferStreamingSafe?: boolean;
  speechMonoAmount?: number;
  targetPlatform?: MasteringPlatform;
  preset?: MasteringPreset;
}

interface MasteringAudioProfileStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate: number;
  nFft?: number;
  hopLength?: number;
  truePeakOversample?: number;
  detectDefects?: boolean;
}

interface MasteringStreamingPreviewStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate: number;
  platforms?: StreamingPlatform[];   // Absent: the built-in set
}

// Equivalent-room estimate from estimateRoom(...); lengths in metres.
interface RoomEstimateResult {
  volume?: number;              // m^3; absent with the dimensions when no broadband decay was measurable
  lengthM?: number;             // absent when no decay could be measured
  widthM?: number;
  heightM?: number;
  drrDb?: number;               // direct-to-reverberant ratio; absent when not measurable
  confidence: number;
  bandAbsorption?: Float32Array; // per octave band, same length as rt60Bands
  rt60Bands?: Float32Array;      // seconds per octave band
}

Key.root is a pitch-class number, the form detectChords and chordFunctions take back: the keyRoot / keyMode inputs of detectChords, chordFunctionalAnalysis and Audio.chordFunctionalAnalysis and the key of chordFunctions take a pitch class and a mode name, so a detected key passes straight back. keyRoot also accepts a pitch-class name ('C#'); an unknown name is a RangeError naming the field. Chord.root and Chord.bass are pitch-class numbers as well, and rootName / bassName hold their spelling.

What Key.confidence measures ​

Key.confidence from detectKey and detectKeyCandidates is a softmax over the profile correlation of every scored candidate. It lies in [0, 1), the candidates' confidences sum to 1, and a share of 24 candidates therefore cannot reach 1. It falls as the runner-up closes in, so two keys that split the evidence — a relative major and minor, typically — each report about half.

Read it as how decisively the chroma picked one candidate out of the set, not as how often that pick is right: nothing here is calibrated against annotated recordings, so a confident wrong answer is entirely possible. A pipeline that branches on it has to pick its own threshold against its own material.

analyze() is different. It refines its key against the detected chords, so AnalysisResult.key can name a different key than detectKey on the same input, and its confidence is a combined score that can reach 1 rather than a softmax share. Use detectKey when you need the share reading.

Chord-tone anagrams ​

A sixth and a seventh can spell the same notes

A major6 spells the same four pitch classes as the minor7 a minor third below it, a minor6 the same as the halfDim7 a minor third below, and a dominant7Sus4 the same as the sus2Add4 a fourth above. Nothing in a chromagram separates a pair like that, so the established reading stays the default and only bass evidence promotes the sixth.

Reading the beat fields ​

downbeats holds the beats that start a bar, so it is shorter than beats. downbeatPhase is the beat index the first measure starts on.

Each beat's strength is the raw onset-envelope value in one frame at that beat. beatObservations.accent is the maximum 5 ms RMS near the strongest attack around the beat, in linear units. It is the windowed measurement used by the downbeat and meter analysis. estimateMeter(...) takes the AnalysisResult.beatObservations record as observations, including optional attack, low-frequency, and subdivision evidence. Its MeterEstimate.unobservedBeats result lists masked beats excluded from scoring in ascending zero-based order. It is empty without per-beat energy.

The native package also exports TypeScript helper types for option objects, callbacks, streaming snapshots, and realtime engine messages. Use these names when annotating application code instead of re-declaring the shapes locally.

AreaExported types
Analysis options/resultsBeat, BeatObservations, BpmCandidate, AnalysisBpmCandidate, Chord, ChordAnalysisResult, AnalysisChord, ChordChromaMethod, ChordDetectionOptions, EstimateMeterRequest, KeyMode, KeyProfile, KeyDetectionOptions, MelodyPoint, MeterEstimate, Section, SectionAnalysis, SectionType, TempogramMode, TrimSilenceMode, KeyDetection, ChordFunction, ChordFunctionsInput, ChordFunctionsKey, FunctionalChord, ScaleKind, Matrix2D, OptionsOf
DecodingDecodedChannels, ChannelLayout
Feature extractionDecomposeStemsRequest, DecomposeStemsResult, DecomposeStemsLinkedRequest, DecomposeStemsLinkedResult, NoteSegment, NoteSegmentsRequest
Streaming analysisStreamConfig, StreamStats, StreamFrames, StreamFramesI16, StreamFramesU8, StreamQuantizeConfig, StreamProgressiveEstimate, StreamChordChange, StreamBarChord, StreamPatternScore
Mastering and meteringMasteringPreset, MasteringInsertParamInfo, MasteringInsertTiming, MasteringProcessorCatalogEntry, MasteringInsertSlot, SoloProcessor, StreamingPlatform, DynamicsProcessorResult, CompressorDetector, DecrackleMode, DenoiseClassicalMode, DenoiseClassicalNoiseEstimator, EqBandInput, EqPhaseMode, EqSpectrumSnapshot, NormalizeMode, MasteringRepairStage, MasteringRepairStageName, MasteringRepairAnalysis, MasteringRepairAnalyzeRequest, MasteringRepairApplyRequest, MasteringRepairApplyResult, MasteringRepairStageReports, StreamingLoudnessGainRequest, StreamingLoudnessGainStereoRequest, StreamingLoudnessGainResult
Capability catalogCapabilities, CapabilityCatalog, CapabilityCatalogPresets, CapabilityCatalogChain, CapabilityCatalogChainStage, CapabilityCatalogChainList, MasteringProcessorCatalogEntry, MasteringPresetCatalogEntry, MasteringInsertParamChoice, MasteringInsertParamUnit, MasteringInsertParamScale, MasteringInsertParamRelation, MasteringInsertParamDependency
Stereo mastering and metering requestsMasteringAssistantSuggestStereoRequest, MasteringAudioProfileStereoRequest, MasteringStreamingPreviewStereoRequest, MeteringCrestFactorDbStereoRequest, NormalizeStereoRequest, NormalizeStereoResult
Pitch correctionPitchCorrectOptions, VoicedFlags, AutoTuneKey, AutoTuneOptions, AutoTuneResult
Room acousticsAcousticModeName, MaterialPresetName, RoomGeometry, RoomMorphOptions, RoomMorphResult, RoomMorphStereoResult, RoomPlacement
Mastering chain configMasteringChainConfig, MultibandCompressorBand
Synth descriptorsSynthParamInfo, SynthParamCondition, SynthPatch, SynthEngineMode
MixingAutomationCurve, GoniometerPoint, MeterTap, MixMeterSnapshot, MixResult, MixerProcessResult, PanLaw, PanMode, SendTiming, SidechainCheck, SidechainRefusal
Realtime voiceVoicePresetId, VoicePresetCategory, RealtimeVoiceChangerPresetMetadata, RealtimeVoiceChangerPreset, RealtimeVoiceChangerConfigInput, RealtimeVoiceChangerConfig, RealtimeVoiceChangerOptions
Realtime engine graphEngineGraphSpec, EngineGraphNode, EngineGraphNodeType, EngineGraphConnection, EngineGraphMix, EngineGraphParameterBinding, EngineParameterInfo
Realtime engine transportEngineTransportState, EngineMarker, EngineClip, EngineAutomationPoint, EngineMetronomeConfig, EngineTrackMonitorMode
Project metadata and automationExternalInstrument, ExternalInstrumentEvent, ProjectAssistSidecar, ProjectAssistSidecarInput, ProjectAutomationTargetKind, ProjectAutomationLaneDesc
Realtime engine jobs/telemetryEngineBounceOptions, EngineBounceResult, EngineFreezeOptions, EngineFreezeResult, EngineCaptureStatus, EngineTelemetry, EngineTelemetryType, EngineTelemetryError, EngineMeterTelemetry

MasteringPresetCatalogEntry carries name, kind, targetLufs, truePeakCeilingDbtp, and maxLimiterGainReductionDb; restoration entries leave the three numeric fields out. A processor entry's slots describe conditional parameter groups, and MasteringInsertParamInfo adds the corresponding slot to each descriptor. The catalog's chain section (CapabilityCatalogChain) describes every flat mastering chain key: the stages (CapabilityCatalogChainStage), the indexed lists with their item counts (CapabilityCatalogChainList), and the params descriptors; presets.playbackRoom is always present. A descriptor's unit is a MasteringInsertParamUnit (a closed set, null for non-numeric keys), scale a MasteringInsertParamScale ('linear' or 'log'), and dependsOn a list of MasteringInsertParamDependency (key, relation, factor, read as this <relation> factor * sibling) whose relation is a MasteringInsertParamRelation; coupledWith is a string[] of the other siblings that move the key's accepted range (min / max are measured with them at their defaults); uiMin and uiMax give the display range. Every processor entry also carries causal. masteringInsertTiming({ insert, params, sampleRate }) returns MasteringInsertTiming with latencySamples and tailSamples, while masteringPresetParams(preset) returns a MasteringChainConfig suitable for masterAudio({ samples, sampleRate, overrides }).