Skip to content

Python Repair and Room Types ​

The records returned by and passed to the repair functions, and the room-acoustics records. The mastering_repair_* functions, their stereo and linked forms and the detect_* measurements are on Python Dynamics and Repair API; mastering_audio_profile and its AudioDefects are on Python Mastering API; analyze_impulse_response, detect_acoustic, estimate_room, synthesize_rir, room_morph and room_morph_stereo are on Python Effects API.

Detections ​

Every defect family has a detection record: what one channel's detector found, measured without repairing anything. A detection is also the detected field of the matching report below. AudioDefects gathers all six, and is what mastering_audio_profile and mastering_repair_analyze report.

python
# What one channel's click detector found, independent of repair.
@dataclass(frozen=True, slots=True)
class ClickDetection:
    count: int
    rejected: int
    longest_run_samples: int
    per_second: float

# What one channel's clip detector found, independent of repair.
@dataclass(frozen=True, slots=True)
class ClipDetection:
    clipped_samples: int
    clipped_ratio: float
    run_count: int
    longest_run_samples: int
    flat_run_count: int
    longest_flat_run_samples: int
    flat_sample_count: int
    flat_level: float | None

# What one channel's crackle detector found, independent of repair.
@dataclass(frozen=True, slots=True)
class CrackleDetection:
    sample_count: int
    sample_fraction: float
    per_second: float

# What one channel's hum detector found, independent of repair.
@dataclass(frozen=True, slots=True, eq=False)
class HumDetection:
    fundamental_hz: float
    fundamental_prominence: float
    harmonics: int
    harmonic_dbfs: npt.NDArray[np.float32]

# The noise floor a denoise pass estimated, before the mask.
@dataclass(frozen=True, slots=True, eq=False)
class NoiseDetection:
    floor_dbfs: float | None
    band_floor_dbfs: npt.NDArray[np.float32]
    band_floor_band: npt.NDArray[np.int32]

# What a dereverb pass measured while deciding how much to subtract.
@dataclass(frozen=True, slots=True)
class ReverbDetection:
    late_decay_ratio_db: float | None
    late_predictability: float | None

# What the six repair detectors measured, one detection per detector.
@dataclass(frozen=True, slots=True)
class AudioDefects:
    click: ClickDetection
    clip: ClipDetection
    crackle: CrackleDetection
    noise: NoiseDetection
    hum: HumDetection
    reverb: ReverbDetection
  • ClipDetection.clipped_ratio and CrackleDetection.sample_fraction are fractions in 0..1 of the input length. flat_level is a linear magnitude, and is None when there are no flat-top runs.
  • HumDetection.fundamental_prominence is a linear energy ratio, not dB; 1.0 means no peak, and harmonics is then 0. harmonic_dbfs holds at most 16 entries, one per multiple of the fundamental in ascending order.
  • NoiseDetection.band_floor_dbfs has 32 entries on a geometric grid from 20 Hz to Nyquist, low to high; mastering_repair_noise_band_bins returns the bin boundaries of that grid.
  • ReverbDetection.late_predictability is None when the WPE stage is off. In AudioDefects from the profile and the analysis it is always None, because neither runs WPE.

Reports and results of the one-channel passes ​

A repair pass returns a result with the repaired samples (same length as the input) and a report: the channel's own detected measurement plus what the pass did. The stereo form returns left, right, length and one report per channel.

python
# What one channel's declick pass found and did to it.
@dataclass(frozen=True, slots=True)
class DeclickReport:
    detected: ClickDetection
    repaired_runs: int
    repaired_samples: int
    linked_runs: int
    lpc_model_used: bool

# A declicked mono buffer and what the pass did to it.
@dataclass(frozen=True, slots=True, eq=False)
class DeclickResult:
    samples: NDArray[np.float32]
    report: DeclickReport

# A declicked stereo pair and what each channel's pass did.
@dataclass(frozen=True, slots=True, eq=False)
class DeclickStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    length: int
    left_report: DeclickReport
    right_report: DeclickReport

# What one channel's declip pass found and did to it.
@dataclass(frozen=True, slots=True)
class DeclipReport:
    detected: ClipDetection
    lpc_reconstructed_runs: int
    unreconstructed_runs: int
    repaired_samples: int
    linked_runs: int

# A declipped mono buffer and what the pass did to it.
@dataclass(frozen=True, slots=True, eq=False)
class DeclipResult:
    samples: NDArray[np.float32]
    report: DeclipReport

# A declipped stereo pair and what each channel's pass did.
@dataclass(frozen=True, slots=True, eq=False)
class DeclipStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    length: int
    left_report: DeclipReport
    right_report: DeclipReport

# What one channel's decrackle pass found and did to it.
@dataclass(frozen=True, slots=True)
class DecrackleReport:
    detected: CrackleDetection
    replaced_samples: int
    detail_coefficients: int
    shrunk_coefficients: int
    noise_sigma: float

# A decrackled mono buffer and what the pass did to it.
@dataclass(frozen=True, slots=True, eq=False)
class DecrackleResult:
    samples: NDArray[np.float32]
    report: DecrackleReport

# A decrackled stereo pair and what each channel's pass did.
@dataclass(frozen=True, slots=True, eq=False)
class DecrackleStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    length: int
    left_report: DecrackleReport
    right_report: DecrackleReport

# What one channel's dehum pass found and did to it.
@dataclass(frozen=True, slots=True)
class DehumReport:
    detected: HumDetection
    notched_harmonics: int
    applied_fundamental_hz: float
    fundamental_drift_hz: float

# A dehummed mono buffer and what the pass did to it.
@dataclass(frozen=True, slots=True, eq=False)
class DehumResult:
    samples: NDArray[np.float32]
    report: DehumReport

# A dehummed stereo pair and what each channel's pass did.
@dataclass(frozen=True, slots=True, eq=False)
class DehumStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    length: int
    left_report: DehumReport
    right_report: DehumReport
  • DeclickReport.repaired_runs includes runs inside a transient that detected.count leaves out. lpc_model_used is False when the input was too short for lpc_order and every fill used linear interpolation.
  • linked_runs (declick and declip) counts repaired runs that this channel's own detection did not produce (stereo repair works over both channels' runs); it is always 0 from the mono entry point.
  • DeclipReport.unreconstructed_runs counts runs left clipped, including runs longer than 512 samples or without a usable LPC reconstruction.
  • DecrackleReport fields depend on the mode: replaced_samples is median mode only, and detail_coefficients, shrunk_coefficients and noise_sigma are wavelet mode only. The other mode's fields read 0.
  • DehumReport.applied_fundamental_hz is the frequency the last notch refresh used; fundamental_drift_hz is the largest excursion of the tracked frequency from the configured one, 0 without adaptive tracking. notched_harmonics is lower than harmonics once a harmonic reaches Nyquist.

Denoise and dereverb reports ​

Denoise and dereverb apply one mask over the channel-summed power to every channel, so a stereo pair or any number of channels returns one report for the whole set.

python
# What a denoise pass found and what it removed.
@dataclass(frozen=True, slots=True)
class DenoiseReport:
    detected: NoiseDetection
    mean_reduction_db: float
    max_reduction_db: float
    floor_limited_fraction: float

# A denoised mono buffer and what the pass did to it.
@dataclass(frozen=True, slots=True, eq=False)
class DenoiseResult:
    samples: NDArray[np.float32]
    report: DenoiseReport

# A denoised stereo pair and the one mask that produced it.
@dataclass(frozen=True, slots=True, eq=False)
class DenoiseStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    length: int
    report: DenoiseReport

# Any number of denoised channels and the one mask that produced them.
@dataclass(frozen=True, slots=True)
class DenoiseLinkedResult:
    channels: list[NDArray[np.float32]]
    report: DenoiseReport

# What a dereverb pass found and what it removed.
@dataclass(frozen=True, slots=True)
class DereverbReport:
    detected: ReverbDetection
    mean_reduction_db: float
    suppressed_fraction: float
    wpe_predictor_norm: float

# A dereverberated mono buffer and what the pass did to it.
@dataclass(frozen=True, slots=True, eq=False)
class DereverbResult:
    samples: NDArray[np.float32]
    report: DereverbReport

# A dereverberated stereo pair and the one mask that produced it.
@dataclass(frozen=True, slots=True, eq=False)
class DereverbStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    length: int
    report: DereverbReport

# Any number of dereverberated channels and the one mask behind them.
@dataclass(frozen=True, slots=True)
class DereverbLinkedResult:
    channels: list[NDArray[np.float32]]
    report: DereverbReport
  • In DenoiseReport, mean_reduction_db of 0 reads the same whether the mask was transparent or no mask ran. floor_limited_fraction is always 0 in "spectralSubtraction" mode, which floors on spectral_floor instead.
  • NoiseDetection carries absolute levels, and for a linked set they are the set's: N identical channels read 10*log10(N) dB above one of them. Every attenuation figure is a fraction or a dB attenuation and does not shift with the channel count.
  • Every field of DereverbReport is a ratio or a fraction, so a figure measured over a set is comparable to a mono one. wpe_predictor_norm is the mean norm actually applied, after the clamp; 0 when WPE did not run.

Stage settings ​

One record per repair stage, for mastering_repair_apply and the recommended list of mastering_repair_analyze. stage is a fixed discriminator, so a stage list is told apart by it. Every other field is None for that function's own default; the fields mirror the keyword arguments of the matching mastering_repair_* function.

python
# Declip settings as :func:`mastering_repair_declip` takes them; None is its default.
@dataclass(frozen=True, slots=True, kw_only=True)
class DeclipStage:
    stage: Literal['declip'] = field(default='declip', init=False)
    clip_threshold_db: float | None = None
    lpc_order: int | None = None
    iterations: int | None = None
    link_channels: bool | None = None

# Declick settings as :func:`mastering_repair_declick` takes them; None is its default.
@dataclass(frozen=True, slots=True, kw_only=True)
class DeclickStage:
    stage: Literal['declick'] = field(default='declick', init=False)
    threshold: float | None = None
    neighbor_ratio: float | None = None
    max_click_samples: int | None = None
    lpc_order: int | None = None
    residual_ratio: float | None = None

# Decrackle settings as :func:`mastering_repair_decrackle` takes them; None is its default.
@dataclass(frozen=True, slots=True, kw_only=True)
class DecrackleStage:
    stage: Literal['decrackle'] = field(default='decrackle', init=False)
    threshold: float | None = None
    mode: str | None = None
    levels: int | None = None

# Dehum settings as :func:`mastering_repair_dehum` takes them; None is its default.
@dataclass(frozen=True, slots=True, kw_only=True)
class DehumStage:
    stage: Literal['dehum'] = field(default='dehum', init=False)
    fundamental_hz: float | None = None
    harmonics: int | None = None
    q: float | None = None
    adaptive: bool | None = None
    search_range_hz: float | None = None
    adaptation: float | None = None
    frame_size: int | None = None
    pll_bandwidth: float | None = None
    mode: str | None = None

# Linked denoise settings as :func:`mastering_repair_denoise_classical` takes them.
@dataclass(frozen=True, slots=True, kw_only=True)
class DenoiseStage:
    stage: Literal['denoise'] = field(default='denoise', init=False)
    mode: str | None = None
    noise_estimator: str | None = None
    n_fft: int | None = None
    hop_length: int | None = None
    dd_alpha: float | None = None
    reduction_db: float | None = None
    over_subtraction: float | None = None
    spectral_floor: float | None = None
    noise_estimation_quantile: float | None = None
    speech_presence_gain: bool | None = None
    gain_smoothing: bool | None = None

# Linked dereverb settings as :func:`mastering_repair_dereverb_classical` takes them.
@dataclass(frozen=True, slots=True, kw_only=True)
class DereverbStage:
    stage: Literal['dereverb'] = field(default='dereverb', init=False)
    threshold: float | None = None
    attenuation: float | None = None
    n_fft: int | None = None
    hop_length: int | None = None
    t60_sec: float | None = None
    late_delay_ms: float | None = None
    over_subtraction: float | None = None
    spectral_floor: float | None = None
    wpe_enabled: bool | None = None
    wpe_iterations: int | None = None
    wpe_taps: int | None = None
    wpe_strength: float | None = None

mode of DecrackleStage takes "median" or "waveletShrinkage"; of DehumStage, "subtract" or "notch"; of DenoiseStage, "logMmse", "mmseStsa" or "spectralSubtraction"; noise_estimator takes "quantile", "mcra", "imcra" or "spp". RepairStage is the union of the six records.

Analysis and application ​

mastering_repair_analyze returns the measurement and the stages it recommends, ready to pass to mastering_repair_apply, which returns the repaired channels and one RepairStageReports per applied stage.

python
# Result of :func:`mastering_repair_analyze`.
@dataclass(frozen=True, slots=True)
class MasteringRepairAnalysis:
    defects: AudioDefects | None
    channels: list[AudioDefects] | None
    declip_threshold_safe: bool
    integrated_lufs: float
    recommended: list[RepairStage]
    explanation: list[str]

# Repaired channels, in input order, and one entry per applied stage, in application order.
@dataclass(frozen=True, slots=True)
class RepairApplyResult:
    channels: list[NDArray[np.float32]]
    reports: list[RepairStageReports]

# One stage a repair application ran and what it reported.
@dataclass(frozen=True, slots=True)
class RepairStageReports:
    stage: str
    scope: str
    reports: list[DeclipReport | DeclickReport | DecrackleReport | DehumReport | DenoiseReport | DereverbReport]
    changes: list[RepairChannelChange]
  • MasteringRepairAnalysis.defects aggregates every channel; channels holds each channel's own. Both are None when the input was too short for the detectors.
  • declip_threshold_safe is False when a declip at the flat level would touch louder audio; declip is then withheld from recommended. Dereverb is never recommended.
  • RepairStageReports.scope is "channel" with one report per channel in input order, or "linked" with exactly one report for the whole set (denoise and dereverb). stage is one of "declip", "declick", "decrackle", "dehum", "denoise", "dereverb".

A RepairChannelChange reports the number of changed samples and the RMS change level in dBFS for one channel; change_level_db is negative infinity when the stage made no change.

python
# How much one repair stage changed one channel.
@dataclass(frozen=True, slots=True)
class RepairChannelChange:
    changed_samples: int
    change_level_db: float

Room acoustics ​

analyze_impulse_response and detect_acoustic return an AcousticResult; estimate_room returns a RoomEstimate, which room_geometry_from_estimate turns into a RoomGeometry for synthesize_rir.

python
# Room acoustic parameters from a blind recording or a measured impulse response (``is_blind`` distinguishes the two).
@dataclass(frozen=True, slots=True, eq=False)
class AcousticResult:
    rt60: float | None
    edt: float | None
    c50: float | None
    c80: float | None
    d50: float | None
    rt60_bands: npt.NDArray[np.float32]
    edt_bands: npt.NDArray[np.float32] | None
    c50_bands: npt.NDArray[np.float32] | None
    c80_bands: npt.NDArray[np.float32] | None
    confidence: float
    is_blind: bool

# Blind equivalent-room estimate (volume/dimensions/absorption/DRR).
@dataclass(frozen=True, slots=True, eq=False)
class RoomEstimate:
    volume: float | None
    length_m: float | None
    width_m: float | None
    height_m: float | None
    drr_db: float | None
    confidence: float
    band_absorption: npt.NDArray[np.float32]
    rt60_bands: npt.NDArray[np.float32]

# Room geometry in the shape :func:`libsonare.synthesize_rir` takes.
class RoomGeometry(TypedDict):
    length_m: float
    width_m: float
    height_m: float
    source: tuple[float, float, float]
    listener: tuple[float, float, float]
    absorption: NotRequired[float]
    band_absorption: NotRequired[npt.NDArray[np.float32]]
  • AcousticResult.rt60 and rt60_bands are in seconds and estimated in both modes. When is_blind is true, edt, c50, c80, d50 and their band arrays are None: they need a known direct-sound arrival time, which only a measured impulse response provides. d50 is the early-energy fraction in 0..1; confidence is in 0..1.
  • RoomEstimate.volume is in cubic metres, length_m, width_m and height_m in metres. They are NaN, with confidence 0, when the recording has no measurable broadband decay; rt60_bands is NaN where a band's fit failed. band_absorption has the same length as rt60_bands.
  • RoomGeometry is a TypedDict: splat it into the call with synthesize_rir(**geometry, sample_rate=...). source and listener are (x, y, z) in metres. absorption and band_absorption are present only when the estimate has finite bands; an absent key leaves that argument at its default.

Room impulse responses and morphs ​

python
# One diagnostic reported by the RIR synthesizer.
@dataclass(frozen=True, slots=True)
class RirDiagnostic:
    code: str
    message: str
    severity: str

# Room impulse response synthesized from shoebox geometry.
@dataclass(frozen=True, slots=True, eq=False)
class RirResult:
    rir: npt.NDArray[np.float32]
    sample_rate: int
    diagnostics: list[RirDiagnostic] = field(default_factory=list)

# Morphed audio and what the target-room synthesis had to change to make it.
@dataclass(frozen=True, slots=True, eq=False)
class RoomMorphResult:
    audio: npt.NDArray[np.float32]
    sample_rate: int
    diagnostics: list[RirDiagnostic] = field(default_factory=list)

# Morphed stereo audio and the target-room synthesis warnings.
@dataclass(frozen=True, slots=True, eq=False)
class RoomMorphStereoResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    sample_rate: int
    diagnostics: list[RirDiagnostic] = field(default_factory=list)

RirDiagnostic.severity is "info", "warning" or "error". A refused synthesis raises SonareError, so every entry on a returned result is a warning; read diagnostics, because a truncated response looks the same as a complete one. The codes a synthesis or morph can report are:

CodeMeaning
acoustic.rir_length_clampedmax_sec cut the reverb tail
acoustic.rir_length_flooredmax_sec was shorter than the direct sound's arrival and was raised to fit it
acoustic.rir_tail_truncatedmax_sec cut the longest band before it decayed by 60 dB, so its RT60 cannot be measured from the response
acoustic.no_late_tailthe request was reduced from early reflections plus a diffuse tail to early reflections only
acoustic.ism_order_clampedthe image-source order was reduced to the safe maximum (morphs)

Dereverb configuration ​

mastering_repair_dereverb_config_for_room returns a DereverbClassicalConfig for a measured room, a complete configuration for mastering_repair_dereverb_classical.

python
# A complete classical-dereverberator configuration.
class DereverbClassicalConfig(TypedDict):
    threshold: float
    attenuation: float
    n_fft: int
    hop_length: int
    t60_sec: float
    late_delay_ms: float
    over_subtraction: float
    spectral_floor: float
    wpe_enabled: bool
    wpe_iterations: int
    wpe_taps: int
    wpe_strength: float

Ranges: threshold, spectral_floor and wpe_strength are in 0..1; attenuation is 0 (none) to 1 (all); n_fft is a power of two; hop_length is in (0, n_fft / 2]; t60_sec is in (0, 10]; late_delay_ms is 0 to 500; over_subtraction is 0 to 16; wpe_iterations is 1 to 16; wpe_taps is 1 to 32.