# BS.1770-4 integrated loudness vs pyloudnorm reference values
# (generated by scripts/save_loudness_ref.py in the 0.1.7 container)

sr <- 24000
t <- (0:(5 * sr - 1)) / sr

# pyloudnorm matches to 6 decimals on synthetic signals
expect_equal(chatterbox::integrated_loudness(0.5 * sin(2 * pi * 1000 * t), sr),
    -9.077427, tolerance = 1e-5)
expect_equal(chatterbox::integrated_loudness(0.1 * sin(2 * pi * 100 * t), sr),
    -24.873270, tolerance = 1e-5)
expect_equal(
    chatterbox::integrated_loudness(
        0.3 * sin(2 * pi * 440 * t) + 0.2 * sin(2 * pi * 2500 * t), sr),
    -11.144152, tolerance = 1e-5)
# amplitude-modulated signal exercises the block gating
expect_equal(
    chatterbox::integrated_loudness(
        (0.5 * sin(2 * pi * 0.3 * t)^2) * sin(2 * pi * 500 * t), sr),
    -12.942599, tolerance = 1e-5)

# real audio: jfk.wav downmixed to mono (librosa-style channel mean)
jfk <- chatterbox::read_audio(
    system.file("audio", "jfk.wav", package = "chatterbox"))
expect_equal(jfk$sr, 48000)
expect_equal(chatterbox::integrated_loudness(jfk$samples, jfk$sr),
    -26.644728, tolerance = 1e-5)

# normalization hits the target exactly
normed <- chatterbox::normalize_loudness(jfk$samples, jfk$sr)
expect_equal(chatterbox::integrated_loudness(normed, jfk$sr),
    -27, tolerance = 1e-6)

# silence passes through unchanged (gain would be non-finite)
silence <- numeric(sr)
expect_identical(chatterbox::normalize_loudness(silence, sr), silence)

# too-short input errors
expect_error(chatterbox::integrated_loudness(numeric(100), sr), "400 ms")
