Просмотр исходного кода

WIP edison165: FL lossy normalize (phase rotation search), generate noise at full scale, [DEC] notes

Ka1-S 1 месяц назад
Родитель
Сommit
ebb4595022

+ 16 - 0
docs/analise/REA_rodada165l.md

@@ -68,3 +68,19 @@ start from the same shapes (the numbers, not the files).
 - The editor: "Edit: Wave / Volume / Panning / Stereo sep" (E) like Edison's edit selector; the envelopes are heard when
   playing and mixed down by Tools › Mixdown amp envelopes; Tools menu in FL's groups (Envelope, Amp, Waveform, Time,
   Channels, Synthesis, Noise gating, Spectral, Regions).
+
+## 4. Decompiled behaviour [DEC] (FLEngine_x64.dll, read-only project of r165f)
+
+- **Normalize menu (TEditor `NormalizeMenuClick` 0xce57c0)** dispatches on the item tag. Fade in (8) / fade out (9)
+  are a volume ramp 0→1 / 1→0 with tension 0.999999 / 0.9999; "mono if mono" (10) only converts when the channels
+  are identical; declick in/out (11/12) are the region declickers.
+- **Lossy normalize (tag 15, 0x697920)**: only when the selection is ≤ 30 000 ms (`len * 1000 / rate`), else a plain
+  normalize. It tries passes k = 1..249 with an angle `k * 0.0251327 = k * 2π/250`, measures the peak of the
+  selection after each trial transform, keeps the lowest, applies it, then normalizes to 1.0 and reports
+  `Gain: x dB` = 20·log10(old peak / new peak). The trial transform works on a 2^n FFT (n = log2 of a size derived
+  from the sample rate, clamped 4..20) and does not change the magnitude spectrum, i.e. a constant phase rotation.
+  LYNX: `lossyNormalize` = the same search with an analytic-signal (Hilbert) rotation `x cos t + H(x) sin t`, then
+  normalize; returns the ratio. (Was a soft-clip guess before.)
+- **Generate noise (WDelMenuClick tag 10)**: fills the selection with noise then normalizes it to 1.0.
+- **Claw machine (0xcd2070)**: the form is modal; OK runs the core (0xc7b460) on the selection under one undo step
+  named "claw machine".

+ 67 - 33
src/core/AudioEditTools.cpp

@@ -4,6 +4,8 @@
 #include <cmath>
 #include <functional>
 #include <numeric>
+#include <tuple>
+#include <utility>
 
 namespace lynx::audioedit
 {
@@ -587,50 +589,82 @@ void ampTool (Document& doc, Range r, const AmpSettings& s)
     }
 }
 
-float lossyNormalize (Document& doc, Range r, double clipFraction)
+float lossyNormalize (Document& doc, Range r, double maxSeconds)
 {
+    // FL's way [DEC 0x697920]: try 249 phase rotations of the selection (k * 2pi / 250, the signal turned through its
+    // analytic counterpart: x cos t + H(x) sin t), keep the one with the lowest peak, then normalize to full scale.
+    // A phase rotation does not change the magnitude spectrum, so the sound stays the same to the ear (mostly) while
+    // its peaks get lower, so it can be made louder. Over `maxSeconds` (FL: 30 s) it is a plain normalize.
     r = orAll (doc, r);
     auto& a = doc.audio;
-    if (r.empty())
+    if (r.empty() || a.channels.empty())
         return 1.0f;
-    // the level that only `clipFraction` of the samples exceed (a 4096-bin histogram of |x| up to the peak)
-    float peak = 0.0f;
+    float before = 0.0f;
     for (const auto& ch : a.channels)
-        peak = std::max (peak, peakOf (ch, r.start, r.end));
-    if (peak <= 1.0e-9f)
+        before = std::max (before, peakOf (ch, r.start, r.end));
+    if (before <= 1.0e-9f)
         return 1.0f;
-    constexpr int bins = 4096;
-    std::vector<std::int64_t> hist (bins, 0);
-    std::int64_t total = 0;
-    for (const auto& ch : a.channels)
-        for (auto i = r.start; i < r.end; ++i)
+    const auto len = (std::size_t) (r.end - r.start);
+    if ((double) len <= maxSeconds * a.sampleRate)
+    {
+        std::size_t n = 1;
+        while (n < len * 2) // padded: the rotation is circular, the padding keeps the ends apart
+            n <<= 1;
+        std::vector<std::vector<double>> hil;
+        for (const auto& ch : a.channels)
         {
-            ++hist[(std::size_t) std::min (bins - 1, (int) (std::abs (ch[(std::size_t) i]) / peak * bins))];
-            ++total;
+            std::vector<double> re (n, 0.0), im (n, 0.0);
+            for (std::size_t i = 0; i < len; ++i)
+                re[i] = ch[(std::size_t) r.start + i];
+            fftInPlace (re, im, false);
+            // the Hilbert transform: -j on positive frequencies, +j on negative ones, 0 at DC and Nyquist
+            for (std::size_t k = 1; k < n / 2; ++k)
+            {
+                std::tie (re[k], im[k]) = std::pair (im[k], -re[k]);
+                std::tie (re[n - k], im[n - k]) = std::pair (-im[n - k], re[n - k]);
+            }
+            re[0] = im[0] = re[n / 2] = im[n / 2] = 0.0;
+            fftInPlace (re, im, true);
+            for (auto& v : re)
+                v /= (double) n;
+            re.resize (len);
+            hil.push_back (std::move (re));
+        }
+        double bestPeak = before, bestAngle = 0.0;
+        for (int k = 1; k < 250; ++k)
+        {
+            const auto t = (double) k * 2.0 * pi / 250.0, c = std::cos (t), s = std::sin (t);
+            double pk = 0.0;
+            for (std::size_t chn = 0; chn < a.channels.size() && pk < bestPeak; ++chn)
+                for (std::size_t i = 0; i < len; ++i)
+                    pk = std::max (pk, std::abs (a.channels[chn][(std::size_t) r.start + i] * c + hil[chn][i] * s));
+            if (pk < bestPeak)
+            {
+                bestPeak = pk;
+                bestAngle = t;
+            }
+        }
+        if (bestAngle != 0.0)
+        {
+            const auto c = std::cos (bestAngle), s = std::sin (bestAngle);
+            for (std::size_t chn = 0; chn < a.channels.size(); ++chn)
+                for (std::size_t i = 0; i < len; ++i)
+                {
+                    auto& v = a.channels[chn][(std::size_t) r.start + i];
+                    v = (float) (v * c + hil[chn][i] * s);
+                }
         }
-    const auto allowed = (std::int64_t) std::ceil (std::clamp (clipFraction, 0.0, 0.1) * (double) total);
-    std::int64_t above = 0;
-    int b = bins - 1;
-    for (; b > 0; --b)
-    {
-        if (above + hist[(std::size_t) b] > allowed)
-            break;
-        above += hist[(std::size_t) b];
     }
-    const auto level = std::max (peak * 0.25f, peak * (float) (b + 1) / bins); // never more than +12 dB over normalize
-    const auto gain = 1.0f / level;
-    constexpr float knee = 0.9f;
+    float after = 0.0f;
+    for (const auto& ch : a.channels)
+        after = std::max (after, peakOf (ch, r.start, r.end));
+    if (after <= 1.0e-9f)
+        return 1.0f;
+    const auto gain = 1.0f / after;
     for (auto& ch : a.channels)
         for (auto i = r.start; i < r.end; ++i)
-        {
-            const auto x = ch[(std::size_t) i] * gain;
-            const auto m = std::abs (x);
-            if (m > knee)
-                ch[(std::size_t) i] = std::copysign (knee + (1.0f - knee) * std::tanh ((m - knee) / (1.0f - knee)), x);
-            else
-                ch[(std::size_t) i] = x;
-        }
-    return gain;
+            ch[(std::size_t) i] = std::clamp (ch[(std::size_t) i] * gain, -1.0f, 1.0f);
+    return before / after; // how much lower the peak got (FL shows it in dB after the edit)
 }
 
 bool monoIfMono (Document& doc, float tolerance)

+ 5 - 3
src/core/AudioEditTools.h

@@ -93,9 +93,11 @@ struct AmpSettings
 };
 void ampTool (Document& doc, Range r, const AmpSettings& s);
 
-// Lossy normalize: normalizes so that `clipFraction` of the samples (the loudest few) go over full scale and are
-// soft-clipped, giving a louder result than a plain normalize. Returns the gain applied.
-float lossyNormalize (Document& doc, Range r, double clipFraction = 0.0005);
+// Lossy normalize (FL's): turns the phase of the selection (one rotation for all of it, the one of 249 that lowers the
+// peak most) and normalizes, so it ends up louder than a plain normalize with the same magnitude spectrum. Selections
+// longer than `maxSeconds` get a plain normalize. Returns how much lower the peak got by
+// the rotation (old peak / rotated peak, 1 = none: FL reports it as "Gain: x dB").
+float lossyNormalize (Document& doc, Range r, double maxSeconds = 30.0);
 // Stereo audio whose channels are the same (within `tolerance`) becomes mono. True if it was converted.
 bool monoIfMono (Document& doc, float tolerance = 1.0e-6f);
 // White noise at `level` (peak, linear) over the range (an empty range: inserted at r.start, `frames` long).

+ 1 - 1
src/ui/AudioEditor.cpp

@@ -2776,7 +2776,7 @@ juce::PopupMenu AudioEditor::mainMenu()
         }
         const auto at = selection.empty() ? cursor : selection.start;
         const auto length = selection.empty() ? (std::int64_t) doc.audio.sampleRate : selection.length();
-        ae::generateNoise (doc, selection, 0.5f, (std::uint32_t) juce::Random::getSystemRandom().nextInt(), length);
+        ae::generateNoise (doc, selection, 1.0f, (std::uint32_t) juce::Random::getSystemRandom().nextInt(), length);
         selection = { at, at + length };
         commit (tr ("Generate noise"));
         if (history.size() <= 2)

+ 5 - 4
tests/AudioEditToolsTests.inc

@@ -127,12 +127,13 @@ TEST (audioedittools_amp_mixdown_and_levels_round165l)
     CHECK (std::abs (rmsOf (v.audio.channels[0], 0, vn / 4) - 0.5 / std::sqrt (2.0)) < 0.01);
     CHECK (rmsOf (v.audio.channels[0], vn - vn / 50, vn) < 0.01);
 
-    // lossy normalize: louder than plain normalize, never over full scale
-    auto ln = noiseDoc (0.5, 0.25f);
-    ln.audio.channels[0][100] = 0.9f; // one stray peak
+    // lossy normalize (a phase rotation that lowers the peaks, then normalize): a click train gets much louder
+    auto ln = noiseDoc (0.5, 0.0f);
+    for (std::size_t i = 50; i < ln.audio.channels[0].size(); i += 100)
+        ln.audio.channels[0][i] = 0.9f;
     auto plain = ln;
     ae::normalize (plain, {}, 0.0f);
-    ae::lossyNormalize (ln, {});
+    CHECK (ae::lossyNormalize (ln, {}) > 1.5f);
     CHECK (rmsOf (ln.audio.channels[0], 0, ln.audio.frames()) > 1.5 * rmsOf (plain.audio.channels[0], 0, plain.audio.frames()));
     CHECK (ae::peak (ln.audio, {}) <= 1.0f);