Portierung der Python/Tkinter-Vorlage nach C++17/Qt6
Die fuer Debian 13 geschriebene Fassung (Python + Tkinter + matplotlib)
laeuft jetzt als Windows-Anwendung mit Qt 6. Oberflaeche, Bedienlogik und
alle DSP-Verfahren sind unveraendert uebernommen.
- core/ DSP, Audio-IO und Export ohne GUI-Abhaengigkeit
- ui/ Hauptfenster, eigene Wellenform-Anzeige, Uebersichtsleiste,
ffplay-Wiedergabe, Hintergrund-Worker
- tools/ Selbsttest gegen die Python-Vorlage, Ende-zu-Ende-Test der
ffmpeg-Kette, Messwerkzeuge fuer den Geschwindigkeitsvergleich
- chopper/ unveraenderte Vorlage als Referenz fuer die Pruefungen
Verifikation: verify.ps1 vergleicht den Auslieferungsbau gegen die Vorlage
(alle diskreten Ergebnisse identisch) und zusaetzlich einen double-Bau
gegen eine float64-Referenz (260 Werte innerhalb von 1e-9).
Die 14 Commits der Python-Vorlage liegen als chopper-history.bundle bei
(chopper/ war unter Debian ein eigenes Repository).
This commit is contained in:
+248
@@ -0,0 +1,248 @@
|
||||
// ---------------------------------------------------------------------------
|
||||
// Messwerkzeug: Zeitbedarf der Analyseschritte.
|
||||
//
|
||||
// Dasselbe Signal, dieselben Funktionen, einmal in C++ und einmal in Python
|
||||
// (tools/bench.py). Damit die Signalzeugung nicht selbst zum Messposten wird,
|
||||
// erzeugt NUR dieses Programm die Rohdatei (float32 mono); Python liest sie
|
||||
// nur ein. Sonst waere der Vergleich wertlos, weil eine Python-Schleife ueber
|
||||
// mehrere Millionen Samples Minuten braucht.
|
||||
//
|
||||
// Aufruf: sc_bench --gen <datei> [sekunden] Signal schreiben
|
||||
// sc_bench <datei> messen
|
||||
// ---------------------------------------------------------------------------
|
||||
#include "core/Analyze.h"
|
||||
#include "core/Dsp.h"
|
||||
#include "core/Fft.h"
|
||||
#include "core/Parallel.h"
|
||||
|
||||
#include <QElapsedTimer>
|
||||
#include <QFile>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <complex>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kSr = 22050;
|
||||
constexpr int kRepeats = 3;
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
/// Testsignal: vier Toene mit echten Pausen, danach wiederholt.
|
||||
///
|
||||
/// Der Zyklus entspricht dem des Selbsttests (dort 6 s), nur beliebig oft
|
||||
/// hintereinander -- so sind alle drei Detektoren sinnvoll beschaeftigt:
|
||||
/// Pausen (Einsaetze), Tonwechsel (Grundton), Anschlaege (Transienten).
|
||||
sc::Samples makeSignal(int seconds) {
|
||||
const std::size_t n = std::size_t(seconds) * kSr;
|
||||
sc::Samples x(n);
|
||||
std::uint32_t state = 12345u;
|
||||
const double cycle = 6.0;
|
||||
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
const double t = double(i) / double(kSr);
|
||||
const double c = std::fmod(t, cycle);
|
||||
double f = 0.0;
|
||||
double a = 0.0;
|
||||
if (c < 1.0) {
|
||||
f = 220.0;
|
||||
a = 0.5;
|
||||
} else if (c < 1.6) {
|
||||
a = 0.0;
|
||||
} else if (c < 2.6) {
|
||||
f = 440.0;
|
||||
a = 0.5;
|
||||
} else if (c < 3.2) {
|
||||
a = 0.0;
|
||||
} else if (c < 4.2) {
|
||||
f = 330.0;
|
||||
a = 0.5;
|
||||
} else if (c < 4.8) {
|
||||
a = 0.0;
|
||||
} else {
|
||||
f = 110.0;
|
||||
a = 0.4;
|
||||
}
|
||||
state = state * 1664525u + 1013904223u;
|
||||
const double noise = (double(state) / 4294967296.0) * 2.0 - 1.0;
|
||||
const double raw = a * std::sin(2.0 * kPi * f * t) + 0.001 * noise;
|
||||
x[i] = float(std::floor(raw * 10000.0 + 0.5) / 10000.0);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/// Misst fn() kRepeats mal und gibt den besten Lauf in Millisekunden aus.
|
||||
template <class Fn>
|
||||
void measure(const char* label, Fn&& fn) {
|
||||
double best = 1e300;
|
||||
for (int r = 0; r < kRepeats; ++r) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
fn();
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
const double ms =
|
||||
std::chrono::duration<double, std::milli>(t1 - t0).count();
|
||||
best = std::min(best, ms);
|
||||
}
|
||||
std::printf("%-28s %9.1f ms\n", label, best);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Zerlegt die teuerste Analyse in ihre Bestandteile.
|
||||
//
|
||||
// Grundfrage: wie viel von pitch_track ist ueberhaupt die FFT? Nur wenn das
|
||||
// bekannt ist, laesst sich sagen, was eine wie auch immer geartete
|
||||
// Mikrooptimierung (SIMD, Assembly, bessere FFT) ueberhaupt bringen koennte.
|
||||
//
|
||||
// Aufruf: sc_bench --fft
|
||||
// ---------------------------------------------------------------------------
|
||||
static int benchFftBreakdown() {
|
||||
// Ein 180-Sekunden-Lauf bei 22,05 kHz mit Hop 512 ergibt diese Framezahl.
|
||||
constexpr std::size_t kFrames = 7752;
|
||||
constexpr std::size_t kNfft = 4096;
|
||||
|
||||
std::vector<double> bufD(kNfft);
|
||||
for (std::size_t i = 0; i < kNfft; ++i)
|
||||
bufD[i] = std::sin(0.013 * double(i)) * 0.5;
|
||||
|
||||
std::vector<float> bufF(kNfft);
|
||||
for (std::size_t i = 0; i < kNfft; ++i) bufF[i] = float(bufD[i]);
|
||||
|
||||
std::vector<std::complex<double>> specD(kNfft / 2 + 1);
|
||||
std::vector<std::complex<float>> specF(kNfft / 2 + 1);
|
||||
std::vector<double> acfD(kNfft);
|
||||
std::vector<float> acfF(kNfft);
|
||||
|
||||
const sc::Fft fftD(kNfft);
|
||||
const sc::FftF fftF(kNfft);
|
||||
|
||||
std::printf("%zu Frames, %zu-Punkt-FFT -- genau der Innenlauf von pitch_track\n\n",
|
||||
kFrames, kNfft);
|
||||
|
||||
measure("FFT-Paar double", [&] {
|
||||
for (std::size_t f = 0; f < kFrames; ++f) {
|
||||
fftD.rfft(bufD.data(), specD.data());
|
||||
for (auto& s : specD) s = std::complex<double>(std::norm(s), 0.0);
|
||||
fftD.irfft(specD.data(), acfD.data());
|
||||
}
|
||||
});
|
||||
|
||||
measure("FFT-Paar float", [&] {
|
||||
for (std::size_t f = 0; f < kFrames; ++f) {
|
||||
fftF.rfft(bufF.data(), specF.data());
|
||||
for (auto& s : specF) s = std::complex<float>(std::norm(s), 0.0f);
|
||||
fftF.irfft(specF.data(), acfF.data());
|
||||
}
|
||||
});
|
||||
|
||||
// Nur die Vorwaertstransformation, um Packing und Ruecktransformation
|
||||
// getrennt zu sehen.
|
||||
measure("nur rfft double", [&] {
|
||||
for (std::size_t f = 0; f < kFrames; ++f) fftD.rfft(bufD.data(), specD.data());
|
||||
});
|
||||
measure("nur irfft double", [&] {
|
||||
for (std::size_t f = 0; f < kFrames; ++f) fftD.irfft(specD.data(), acfD.data());
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc > 1 && std::strcmp(argv[1], "--fft") == 0) {
|
||||
return benchFftBreakdown();
|
||||
}
|
||||
if (argc < 2) {
|
||||
std::fprintf(stderr, "Aufruf: sc_bench --gen <datei> [sekunden] | sc_bench <datei>\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (std::strcmp(argv[1], "--gen") == 0) {
|
||||
if (argc < 3) return 2;
|
||||
const int seconds = (argc > 3) ? std::atoi(argv[3]) : 180;
|
||||
const sc::Samples signal = makeSignal(seconds);
|
||||
QFile file(QString::fromLocal8Bit(argv[2]));
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
|
||||
std::fprintf(stderr, "kann %s nicht schreiben\n", argv[2]);
|
||||
return 1;
|
||||
}
|
||||
file.write(reinterpret_cast<const char*>(signal.data()),
|
||||
qint64(signal.size() * sizeof(float)));
|
||||
file.close();
|
||||
std::printf("%d s Signal (%.1f MB) -> %s\n", seconds,
|
||||
double(signal.size() * sizeof(float)) / 1e6, argv[2]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- Signal einlesen -------------------------------------------------
|
||||
QFile file(QString::fromLocal8Bit(argv[1]));
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
std::fprintf(stderr, "kann %s nicht lesen\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
const QByteArray raw = file.readAll();
|
||||
file.close();
|
||||
sc::Samples signal(std::size_t(raw.size()) / sizeof(float));
|
||||
std::memcpy(signal.data(), raw.constData(), signal.size() * sizeof(float));
|
||||
const double dur = double(signal.size()) / double(kSr);
|
||||
|
||||
std::printf("Signal: %.1f s, %zu Samples @ %d Hz\n", dur, signal.size(), kSr);
|
||||
std::printf("Kerne: %u (Thread-Pool nutzt %d)\n\n", sc::hardwareThreads(),
|
||||
sc::ThreadPool::instance().threads());
|
||||
|
||||
// Ergebnisse einmal vorab, damit die Messungen nur noch die Rechenzeit
|
||||
// zeigen und nicht die Ausgabe.
|
||||
sc::Curve fluxEnv; // normierte Transienten-Huellkurve
|
||||
sc::Curve rmsEnv; // RMS-Huellkurve
|
||||
sc::PitchCurve pitch;
|
||||
sc::Series onsets;
|
||||
sc::Series cuts;
|
||||
|
||||
std::printf("--- Einzelschritte (bester von %d Laeufen) ---\n", kRepeats);
|
||||
measure("frame_rms", [&] { rmsEnv = sc::frameRms(signal, kSr); });
|
||||
measure("spectral_flux", [&] { fluxEnv = sc::spectralFlux(signal, kSr); });
|
||||
measure("flux_envelope", [&] { fluxEnv = sc::fluxEnvelope(signal, kSr); });
|
||||
measure("onsets_from_flux", [&] {
|
||||
sc::Series thr;
|
||||
sc::onsetsFromFlux(fluxEnv, 0.5, kSr, thr, onsets);
|
||||
});
|
||||
measure("pitch_track", [&] { pitch = sc::pitchTrack(signal, kSr); });
|
||||
measure("detect_pitch_changes", [&] {
|
||||
sc::detectPitchChanges(pitch, rmsEnv.times, rmsEnv.values, -40.0);
|
||||
});
|
||||
|
||||
std::printf("\n--- Zusammengesetzt ---\n");
|
||||
sc::DetectorSet all;
|
||||
all.set(sc::Detector::Transient);
|
||||
all.set(sc::Detector::Onset);
|
||||
all.set(sc::Detector::Pitch);
|
||||
|
||||
measure("detect_cuts (alle 3)", [&] {
|
||||
cuts = sc::detectCuts(signal, kSr, all, 0.5, -40.0, 200.0, dur, 40.0, &fluxEnv,
|
||||
&rmsEnv, &pitch);
|
||||
});
|
||||
measure("analyze_material", [&] {
|
||||
sc::analyzeMaterial(signal, kSr, rmsEnv.times, rmsEnv.values, dur,
|
||||
QStringLiteral("phrases"), &fluxEnv, &pitch, nullptr);
|
||||
});
|
||||
|
||||
// Die Arbeit, die der Export je Datei leistet: einmal Flux + Grundton +
|
||||
// Erkennung, ohne Zwischenergebnisse wiederzuverwenden.
|
||||
measure("Datei komplett (Export)", [&] {
|
||||
const sc::Curve f = sc::fluxEnvelope(signal, kSr);
|
||||
const sc::Curve e = sc::frameRms(signal, kSr);
|
||||
const sc::PitchCurve p = sc::pitchTrack(signal, kSr);
|
||||
const sc::Series c =
|
||||
sc::detectCuts(signal, kSr, all, 0.5, -40.0, 200.0, dur, 40.0, &f, &e, &p);
|
||||
(void)c;
|
||||
});
|
||||
|
||||
std::printf("\nErgebnis: %zu Flux-Werte, %zu Onsets, %zu Chops\n", fluxEnv.values.size(),
|
||||
onsets.size(), cuts.size());
|
||||
return 0;
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Messwerkzeug: Zeitbedarf der Analyseschritte mit der ORIGINAL-Vorlage.
|
||||
|
||||
Liest dasselbe Rohsignal (float32 mono) wie tools/bench.cpp -- erzeugt wird es
|
||||
mit `sc_bench --gen`, damit die Signalzeugung nicht selbst zum Messposten wird
|
||||
(eine Python-Schleife ueber Millionen Samples braucht Minuten).
|
||||
|
||||
python tools/bench.py <rohdatei>
|
||||
|
||||
Gibt dieselben Zeilen aus wie sc_bench, damit sich beide direkt vergleichen
|
||||
lassen.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import types
|
||||
|
||||
SR = 22050
|
||||
REPEATS = 3
|
||||
|
||||
|
||||
def _module(name, **attrs):
|
||||
mod = types.ModuleType(name)
|
||||
for key, value in attrs.items():
|
||||
setattr(mod, key, value)
|
||||
sys.modules[name] = mod
|
||||
return mod
|
||||
|
||||
|
||||
def install_gui_stubs():
|
||||
"""matplotlib/tkinter als leere Attrappen einhaengen (wie reference_dump)."""
|
||||
mpl = _module("matplotlib", use=lambda *a, **k: None)
|
||||
figure = _module("matplotlib.figure", Figure=type("Figure", (), {}))
|
||||
mpl.figure = figure
|
||||
backends = _module("matplotlib.backends")
|
||||
mpl.backends = backends
|
||||
tkagg = _module("matplotlib.backends.backend_tkagg",
|
||||
FigureCanvasTkAgg=type("FigureCanvasTkAgg", (), {}))
|
||||
backends.backend_tkagg = tkagg
|
||||
|
||||
tk = _module("tkinter")
|
||||
ttk = _module("tkinter.ttk")
|
||||
filedialog = _module("tkinter.filedialog")
|
||||
messagebox = _module("tkinter.messagebox")
|
||||
tk.ttk = ttk
|
||||
tk.filedialog = filedialog
|
||||
tk.messagebox = messagebox
|
||||
|
||||
|
||||
def measure(label, fn):
|
||||
best = float("inf")
|
||||
for _ in range(REPEATS):
|
||||
t0 = time.perf_counter()
|
||||
fn()
|
||||
best = min(best, time.perf_counter() - t0)
|
||||
print(f"{label:<28} {best * 1000:9.1f} ms", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit(__doc__)
|
||||
|
||||
install_gui_stubs()
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(root, "chopper"))
|
||||
import sample_chopper4 as sc
|
||||
|
||||
import numpy as np
|
||||
import scipy # noqa: F401 -- nur zur Anzeige unten
|
||||
|
||||
with open(sys.argv[1], "rb") as fh:
|
||||
signal = np.frombuffer(fh.read(), dtype=np.float32)
|
||||
|
||||
dur = signal.size / SR
|
||||
print(f"Signal: {dur:.1f} s, {signal.size} Samples @ {SR} Hz")
|
||||
print(f"numpy: {np.__version__} scipy: {scipy.__version__} "
|
||||
f"(FFT-Pfad: {'scipy/float32' if sc._FFT_DTYPE == np.float32 else 'numpy/float64'})")
|
||||
print(f"Kerne: {os.cpu_count()}")
|
||||
print()
|
||||
|
||||
results = {}
|
||||
|
||||
print(f"--- Einzelschritte (bester von {REPEATS} Laeufen) ---")
|
||||
measure("frame_rms", lambda: results.__setitem__("rms", sc.frame_rms(signal, SR)))
|
||||
measure("spectral_flux", lambda: results.__setitem__("flux", sc.spectral_flux(signal, SR)))
|
||||
measure("flux_envelope", lambda: results.__setitem__("env", sc.flux_envelope(signal, SR)))
|
||||
measure("onsets_from_flux", lambda: results.__setitem__(
|
||||
"onsets", sc.onsets_from_flux(results["env"][0], results["env"][1], 0.5, SR)[1]))
|
||||
measure("pitch_track", lambda: results.__setitem__("pitch", sc.pitch_track(signal, SR)))
|
||||
|
||||
def run_detect_pitch_changes():
|
||||
p_t, p_f0, p_conf = results["pitch"]
|
||||
r_t, r_v = results["rms"]
|
||||
results["pitch_changes"] = sc.detect_pitch_changes(
|
||||
p_t, p_f0, p_conf, r_t, r_v, -40.0)
|
||||
|
||||
measure("detect_pitch_changes", run_detect_pitch_changes)
|
||||
|
||||
print()
|
||||
print("--- Zusammengesetzt ---")
|
||||
mode = {"transient", "onset", "pitch"}
|
||||
|
||||
def run_detect_cuts():
|
||||
results["cuts"] = sc.detect_cuts(
|
||||
signal, SR, mode, 0.5, -40.0, 200.0, dur, 40.0,
|
||||
flux_data=results["env"], envelope=results["rms"],
|
||||
pitch_data=results["pitch"])
|
||||
|
||||
measure("detect_cuts (alle 3)", run_detect_cuts)
|
||||
|
||||
def run_analyze():
|
||||
results["auto"] = sc.analyze_material(
|
||||
signal, SR, results["rms"][0], results["rms"][1], dur,
|
||||
target="phrases", flux_data=results["env"], pitch_data=results["pitch"])
|
||||
|
||||
measure("analyze_material", run_analyze)
|
||||
|
||||
def full_file():
|
||||
f = sc.flux_envelope(signal, SR)
|
||||
e = sc.frame_rms(signal, SR)
|
||||
p = sc.pitch_track(signal, SR)
|
||||
sc.detect_cuts(signal, SR, mode, 0.5, -40.0, 200.0, dur, 40.0,
|
||||
flux_data=f, envelope=e, pitch_data=p)
|
||||
|
||||
measure("Datei komplett (Export)", full_file)
|
||||
|
||||
print()
|
||||
print(f"Ergebnis: {results['env'][1].size} Flux-Werte, "
|
||||
f"{len(results['onsets'])} Onsets, {len(results['cuts'])} Chops")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Vergleicht die Ausgabe von sc_selftest (C++) mit den Referenzwerten der
|
||||
Python-Vorlage.
|
||||
|
||||
python tools/compare.py cpp.txt reference.txt [--mode functional|precise]
|
||||
|
||||
Exitcode 0 = alle Werte innerhalb der Toleranz.
|
||||
|
||||
Zwei Betriebsarten
|
||||
------------------
|
||||
`functional` (Default) vergleicht den AUSLIEFERUNGSBAU gegen die Vorlage, wie
|
||||
sie auf diesem Rechner wirklich laeuft -- mit scipy, also in complex64, weil
|
||||
die Vorlage diesen Pfad bevorzugt. Hier muss gelten:
|
||||
* Alle diskreten Ergebnisse sind EXAKT gleich (Onset-Zeitpunkte, Regionen,
|
||||
Tonwechsel, Cut-Listen, Auto-Einstellungen). Das ist die eigentliche
|
||||
Aussage: die Portierung entscheidet identisch.
|
||||
* Die Fließkomma-Zwischenwerte duerfen minimal abweichen.
|
||||
|
||||
`precise` vergleicht einen C++-Bau in double (SC_FLUX_DOUBLE) gegen eine
|
||||
Referenz, die mit --float64 erzeugt wurde und damit frei von der complex64-
|
||||
Rundung der Vorlage ist. Hier greift eine enge Toleranz -- so wird belegt,
|
||||
dass der ALGORITHMUS stimmt und die Abweichung im Auslieferungsbau
|
||||
ausschliesslich von der gewaehlten Rechengenauigkeit kommt.
|
||||
|
||||
Warum die Zwischenwerte ueberhaupt streuen
|
||||
------------------------------------------
|
||||
Der spektrale Flux ist eine Summe von 513 positiven Differenzen nahezu gleich
|
||||
grosser Betraege. Diese Ausloeschung verstaerkt den Rundungsunterschied zweier
|
||||
FFT-Implementierungen um mehrere Groessenordnungen. Gemessen (180-s-Datei):
|
||||
rund 5e-5 absolut auf Werten der Groessenordnung 1. Die Schwellen, mit denen
|
||||
daraus Onsets werden, liegen bei 0.02 bis 0.3 -- der Unterschied ist also drei
|
||||
Groessenordnungen kleiner als jede Entscheidungsgrenze. Genau deshalb ist die
|
||||
Forderung "diskrete Ergebnisse exakt gleich" die scharfe und richtige Pruefung.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
MODE = "functional"
|
||||
|
||||
# Toleranzen je Betriebsart.
|
||||
#
|
||||
# functional: Auslieferungsbau (FFT in float, wie der scipy-Pfad der Vorlage)
|
||||
# gegen die Vorlage mit scipy. Der gemessene Restfehler in den
|
||||
# ausloeschempfindlichen Flux-Zwischenwerten liegt bei rund 5e-5
|
||||
# absolut auf Werten der Groessenordnung 1.
|
||||
# precise: C++-Bau in double gegen eine mit --float64 erzeugte Referenz.
|
||||
# Dort ist die Vorlage selbst fehlerfrei, also darf es eng zugehen.
|
||||
TOLERANCES = {
|
||||
"functional": {"abs": 2e-4, "rel": 2e-5, "sumAbs": 1e-2},
|
||||
"precise": {"abs": 1e-9, "rel": 1e-9, "sumAbs": 1e-7},
|
||||
}
|
||||
|
||||
ABS_TOL = 2e-4
|
||||
REL_TOL = 2e-5
|
||||
SUM_ABS_TOL = 1e-2
|
||||
|
||||
# Schluessel, deren Wert eine diskrete Entscheidung ist und deshalb exakt
|
||||
# uebereinstimmen muss.
|
||||
EXACT_PREFIXES = (
|
||||
"onsets_", "onset_", "keep_", "silence_run_", "region_start_",
|
||||
"pitch_change_", "detect_cuts", "enforce_", "cap", "phrase", "finalized_",
|
||||
"drop_excluded", "stable_counts", "info_", "auto_", "hits_", "mode_",
|
||||
"rises", "rise_", "pause", "peaks_", "snap_", "measure_peak", "rms_t",
|
||||
"samples_n", "diag_mag_",
|
||||
)
|
||||
|
||||
|
||||
def load(path):
|
||||
values = {}
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
for lineno, raw in enumerate(fh, 1):
|
||||
line = raw.rstrip("\n")
|
||||
if not line.strip():
|
||||
continue
|
||||
if "\t" not in line:
|
||||
raise SystemExit(f"{path}:{lineno}: kein Tabulator in {line!r}")
|
||||
key, value = line.split("\t", 1)
|
||||
if key in values:
|
||||
raise SystemExit(f"{path}:{lineno}: Schluessel {key!r} doppelt")
|
||||
values[key] = value
|
||||
return values
|
||||
|
||||
|
||||
def close(a, b, abs_tol=ABS_TOL):
|
||||
if a == b:
|
||||
return True
|
||||
diff = abs(a - b)
|
||||
if diff <= abs_tol:
|
||||
return True
|
||||
scale = max(abs(a), abs(b))
|
||||
return diff <= REL_TOL * scale
|
||||
|
||||
|
||||
def must_be_exact(key):
|
||||
return any(key.startswith(prefix) for prefix in EXACT_PREFIXES)
|
||||
|
||||
|
||||
def main():
|
||||
global ABS_TOL, REL_TOL, SUM_ABS_TOL
|
||||
|
||||
# Argumente von Hand zerlegen: '--mode precise' kommt als zwei Tokens an,
|
||||
# '--mode=precise' als einer -- beides soll gehen.
|
||||
argv = sys.argv[1:]
|
||||
positional = []
|
||||
mode = "functional"
|
||||
i = 0
|
||||
while i < len(argv):
|
||||
arg = argv[i]
|
||||
if arg == "--mode":
|
||||
if i + 1 >= len(argv):
|
||||
raise SystemExit("--mode braucht einen Wert")
|
||||
mode = argv[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
if arg.startswith("--mode="):
|
||||
mode = arg.split("=", 1)[1]
|
||||
i += 1
|
||||
continue
|
||||
if arg.startswith("--"):
|
||||
i += 1
|
||||
continue
|
||||
positional.append(arg)
|
||||
i += 1
|
||||
|
||||
if mode not in TOLERANCES:
|
||||
raise SystemExit(f"Unbekannte Betriebsart {mode!r} "
|
||||
f"(erlaubt: {', '.join(TOLERANCES)})")
|
||||
ABS_TOL = TOLERANCES[mode]["abs"]
|
||||
REL_TOL = TOLERANCES[mode]["rel"]
|
||||
SUM_ABS_TOL = TOLERANCES[mode]["sumAbs"]
|
||||
|
||||
if len(positional) != 2:
|
||||
raise SystemExit(__doc__)
|
||||
print(f"Betriebsart: {mode} (abs={ABS_TOL:g}, rel={REL_TOL:g})")
|
||||
|
||||
cpp = load(positional[0])
|
||||
ref = load(positional[1])
|
||||
|
||||
only_cpp = sorted(set(cpp) - set(ref))
|
||||
only_ref = sorted(set(ref) - set(cpp))
|
||||
mismatches = []
|
||||
exactMismatches = []
|
||||
compared = 0
|
||||
|
||||
for key in sorted(set(cpp) & set(ref)):
|
||||
a, b = cpp[key], ref[key]
|
||||
try:
|
||||
fa, fb = float(a), float(b)
|
||||
except ValueError:
|
||||
if a != b:
|
||||
exactMismatches.append((key, a, b))
|
||||
continue
|
||||
compared += 1
|
||||
|
||||
# Zaehler und diskrete Ergebnisse: exakt.
|
||||
if key.endswith("_n"):
|
||||
if int(fa) != int(fb):
|
||||
exactMismatches.append((key, a, b))
|
||||
continue
|
||||
if must_be_exact(key):
|
||||
if not close(fa, fb):
|
||||
exactMismatches.append((key, a, b))
|
||||
continue
|
||||
|
||||
if key.endswith("_sum"):
|
||||
if not close(fa, fb, SUM_ABS_TOL):
|
||||
mismatches.append((key, a, b))
|
||||
continue
|
||||
|
||||
if not close(fa, fb):
|
||||
mismatches.append((key, a, b))
|
||||
|
||||
print(f"verglichen: {compared}")
|
||||
|
||||
if only_cpp:
|
||||
print(f"\nNur in C++ ({len(only_cpp)}):")
|
||||
for key in only_cpp[:40]:
|
||||
print(f" {key} = {cpp[key]}")
|
||||
|
||||
if only_ref:
|
||||
print(f"\nNur in Python ({len(only_ref)}):")
|
||||
for key in only_ref[:40]:
|
||||
print(f" {key} = {ref[key]}")
|
||||
|
||||
if exactMismatches:
|
||||
print(f"\nABWEICHUNGEN bei diskreten Ergebnissen ({len(exactMismatches)}):")
|
||||
for key, a, b in exactMismatches[:80]:
|
||||
print(f" {key}: C++={a} Python={b}")
|
||||
|
||||
if mismatches:
|
||||
print(f"\nGleitkomma-Abweichungen ({len(mismatches)}):")
|
||||
for key, a, b in mismatches[:80]:
|
||||
print(f" {key}: C++={a} Python={b}")
|
||||
|
||||
if exactMismatches:
|
||||
return 1
|
||||
if not (only_cpp or only_ref):
|
||||
if mismatches:
|
||||
print("OK: alle diskreten Ergebnisse identisch "
|
||||
f"({len(mismatches)} Zwischenwerte ausserhalb der Toleranz).")
|
||||
return 1
|
||||
print("OK: alle Werte innerhalb der Toleranz.")
|
||||
return 0
|
||||
print("Hinweis: Schluesselsatz weicht ab.")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ende-zu-Ende-Test der ffmpeg-Anbindung.
|
||||
//
|
||||
// Der Selbsttest (sc_selftest) prueft nur die DSP-Schicht gegen die
|
||||
// Python-Referenz -- er fasst ffmpeg nicht an. Hier laeuft die komplette
|
||||
// Kette auf einer echten Audiodatei: dekodieren, analysieren, Nulldurchgangs-
|
||||
// Referenz holen, "Stille entfernt" exportieren, Chops exportieren, und die
|
||||
// Ergebnisse anschliessend nachmessen.
|
||||
//
|
||||
// Aufruf: sc_e2e <quelldatei> <zielordner>
|
||||
// ---------------------------------------------------------------------------
|
||||
#include "core/Analyze.h"
|
||||
#include "core/AudioIO.h"
|
||||
#include "core/Dsp.h"
|
||||
#include "core/Exporter.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QProcess>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
|
||||
int g_failures = 0;
|
||||
|
||||
void check(bool ok, const QString& what) {
|
||||
std::printf("%s %s\n", ok ? "[ok] " : "[FEHL]", qPrintable(what));
|
||||
if (!ok) ++g_failures;
|
||||
}
|
||||
|
||||
/// Misst die Dauer einer Audiodatei ueber ffprobe/ffmpeg.
|
||||
double probeDuration(const QString& path) {
|
||||
QProcess proc;
|
||||
sc::configureChildProcess(proc);
|
||||
proc.start(sc::ffmpegPath(),
|
||||
{QStringLiteral("-v"), QStringLiteral("error"),
|
||||
QStringLiteral("-i"), path, QStringLiteral("-f"),
|
||||
QStringLiteral("f32le"), QStringLiteral("-ac"),
|
||||
QStringLiteral("1"), QStringLiteral("-ar"),
|
||||
QStringLiteral("1000"), QStringLiteral("-")});
|
||||
if (!proc.waitForStarted(10000)) return -1.0;
|
||||
QByteArray out;
|
||||
while (proc.state() != QProcess::NotRunning) {
|
||||
proc.waitForReadyRead(50);
|
||||
out += proc.readAllStandardOutput();
|
||||
proc.readAllStandardError();
|
||||
}
|
||||
out += proc.readAllStandardOutput();
|
||||
return double(out.size() / 4) / 1000.0; // 1000 float32-Samples je Sekunde
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
QCoreApplication app(argc, argv);
|
||||
if (argc < 3) {
|
||||
std::fprintf(stderr, "Aufruf: sc_e2e <quelldatei> <zielordner>\n");
|
||||
return 2;
|
||||
}
|
||||
const QString src = QString::fromLocal8Bit(argv[1]);
|
||||
const QString outDir = QString::fromLocal8Bit(argv[2]);
|
||||
|
||||
std::printf("Quelle: %s\nZiel: %s\n\n", qPrintable(src), qPrintable(outDir));
|
||||
|
||||
check(sc::ffmpegAvailable(), QStringLiteral("ffmpeg im PATH gefunden"));
|
||||
check(sc::ffplayAvailable(), QStringLiteral("ffplay im PATH gefunden"));
|
||||
check(QFileInfo::exists(src), QStringLiteral("Quelldatei vorhanden"));
|
||||
if (g_failures > 0) return 1;
|
||||
|
||||
QDir().mkpath(outDir);
|
||||
|
||||
// ---- 1. Dekodieren ---------------------------------------------------
|
||||
sc::DecodedPtr audio;
|
||||
try {
|
||||
audio = sc::loadAudio(src);
|
||||
} catch (const std::exception& e) {
|
||||
std::printf("[FEHL] Dekodieren: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
std::printf("dekodiert: %zu Frames, %.3f s, %zu Huellkurven-Stuetzstellen\n",
|
||||
audio->frames(), audio->dur, audio->rms.size());
|
||||
check(audio->dur > 1.0, QStringLiteral("Dekodierung liefert > 1 s Audio"));
|
||||
check(audio->combined.size() == audio->left.size() &&
|
||||
audio->left.size() == audio->right.size(),
|
||||
QStringLiteral("linker/rechter/kombinierter Kanal gleich lang"));
|
||||
|
||||
// ---- 2. Analysieren --------------------------------------------------
|
||||
const sc::Curve flux = sc::fluxEnvelope(audio->combined, sc::ANALYSIS_SR);
|
||||
const sc::PitchCurve pitch = sc::pitchTrack(audio->combined, sc::ANALYSIS_SR);
|
||||
sc::Series thr;
|
||||
sc::Series onsets;
|
||||
sc::onsetsFromFlux(flux, 0.5, sc::ANALYSIS_SR, thr, onsets);
|
||||
std::printf("Flux: %zu Werte, Onsets (Intensitaet 0.5): %zu\n", flux.values.size(),
|
||||
onsets.size());
|
||||
|
||||
sc::DetectorSet mode;
|
||||
mode.set(sc::Detector::Transient);
|
||||
mode.set(sc::Detector::Onset);
|
||||
const sc::Curve envelope{audio->times, audio->rms};
|
||||
const sc::Series cuts = sc::detectCuts(audio->combined, sc::ANALYSIS_SR, mode, 0.5,
|
||||
-40.0, 200.0, audio->dur, 40.0, &flux,
|
||||
&envelope, nullptr);
|
||||
std::printf("Chop-Punkte: %zu\n", cuts.size());
|
||||
check(!cuts.empty(), QStringLiteral("Chop-Erkennung findet etwas"));
|
||||
|
||||
// Auto-Analyse ueber die echte Datei
|
||||
sc::MaterialInfo info;
|
||||
const sc::FileSettings settings = sc::analyzeMaterial(
|
||||
audio->combined, sc::ANALYSIS_SR, audio->times, audio->rms, audio->dur,
|
||||
QStringLiteral("phrases"), &flux, &pitch, &info);
|
||||
std::printf("Auto: Modus=%s, Schwelle=%.1f dB, min_len=%.0f ms, Rand=%.0f ms\n",
|
||||
qPrintable(sc::modeToStr(settings.mode)), settings.thresh,
|
||||
settings.minLenMs, settings.pad);
|
||||
check(!settings.mode.empty(), QStringLiteral("Auto-Analyse waehlt einen Detektor"));
|
||||
|
||||
// ---- 3. Nulldurchgangs-Referenz + Zero-Crossing ----------------------
|
||||
sc::Samples zcRef;
|
||||
try {
|
||||
zcRef = sc::decodeMono(src, sc::ZC_SR);
|
||||
} catch (const std::exception& e) {
|
||||
std::printf("[FEHL] Mono-Dekodierung: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
std::printf("zc-Referenz: %zu Samples bei %d Hz\n", zcRef.size(), sc::ZC_SR);
|
||||
check(!zcRef.empty(), QStringLiteral("Mono-Dekodierung fuer Zero-Crossing"));
|
||||
|
||||
const double t0 = audio->dur * 0.5;
|
||||
const double snapped = sc::snapToZeroCrossing(zcRef, sc::ZC_SR, t0, 10.0);
|
||||
std::printf("Zero-Crossing: %.6f -> %.6f (Verschiebung %.3f ms)\n", t0, snapped,
|
||||
(snapped - t0) * 1000.0);
|
||||
check(std::abs(snapped - t0) <= 0.0101,
|
||||
QStringLiteral("Zero-Crossing bleibt im Suchfenster von +-10 ms"));
|
||||
|
||||
sc::ExportOptions options;
|
||||
options.bits = 24;
|
||||
options.rate = QStringLiteral("44100");
|
||||
options.channelMode = QStringLiteral("stereo");
|
||||
options.zeroCrossing = true;
|
||||
|
||||
// ---- 4. "Stille entfernt" exportieren --------------------------------
|
||||
const std::vector<sc::Segment> keeps =
|
||||
sc::keepSegments(audio->times, audio->rms, audio->dur, settings.thresh,
|
||||
settings.minsil, settings.pad);
|
||||
std::printf("Keep-Segmente: %zu\n", keeps.size());
|
||||
const QString trimmed = QDir(outDir).filePath(QStringLiteral("trimmed.wav"));
|
||||
try {
|
||||
sc::exportSilenceRemoved(src, trimmed, keeps, options, &zcRef, sc::ZC_SR);
|
||||
} catch (const std::exception& e) {
|
||||
std::printf("[FEHL] Export 'Stille entfernt': %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
check(QFileInfo::exists(trimmed), QStringLiteral("trimmed.wav angelegt"));
|
||||
|
||||
double keptSeconds = 0.0;
|
||||
for (const sc::Segment& s : keeps) keptSeconds += s.end - s.start;
|
||||
const double trimmedDur = probeDuration(trimmed);
|
||||
std::printf("trimmed.wav: %.3f s (erwartet ~%.3f s)\n", trimmedDur, keptSeconds);
|
||||
check(std::abs(trimmedDur - keptSeconds) < 0.25,
|
||||
QStringLiteral("Laenge von trimmed.wav passt zur Summe der Keep-Segmente"));
|
||||
|
||||
// ---- 5. Chops exportieren (mit Normalisierung, Monokanal) ------------
|
||||
sc::ExportOptions chopOptions = options;
|
||||
chopOptions.bits = 16;
|
||||
chopOptions.rate = QStringLiteral("Original");
|
||||
chopOptions.channelMode = QStringLiteral("combined");
|
||||
chopOptions.normalize = true;
|
||||
|
||||
const QString chopDir = QDir(outDir).filePath(QStringLiteral("chops"));
|
||||
int chopCount = 0;
|
||||
try {
|
||||
chopCount = sc::exportChops(src, chopDir, cuts, audio->dur, chopOptions, &zcRef,
|
||||
sc::ZC_SR, 10.0, &audio->left, &audio->right,
|
||||
sc::ANALYSIS_SR, QStringLiteral("Test"), 5.0);
|
||||
} catch (const std::exception& e) {
|
||||
std::printf("[FEHL] Chop-Export: %s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
std::printf("Chops exportiert: %d\n", chopCount);
|
||||
check(chopCount > 0, QStringLiteral("mindestens ein Chop geschrieben"));
|
||||
|
||||
const QString firstChop =
|
||||
QDir(chopDir).filePath(QStringLiteral("Test_001.wav"));
|
||||
check(QFileInfo::exists(firstChop),
|
||||
QStringLiteral("Chop-Titel wird als Dateiname verwendet (Test_001.wav)"));
|
||||
|
||||
// Alle Chops muessen eine messbare Laenge haben.
|
||||
int measured = 0;
|
||||
for (int i = 1; i <= chopCount; ++i) {
|
||||
const QString path =
|
||||
QDir(chopDir).filePath(QStringLiteral("Test_%1.wav").arg(i, 3, 10, QLatin1Char('0')));
|
||||
if (!QFileInfo::exists(path)) continue;
|
||||
if (probeDuration(path) > 0.01) ++measured;
|
||||
}
|
||||
check(measured == chopCount,
|
||||
QStringLiteral("alle %1 Chops haben eine messbare Laenge").arg(chopCount));
|
||||
|
||||
std::printf("\n%s (%d Fehler)\n", g_failures == 0 ? "E2E OK" : "E2E FEHLGESCHLAGEN",
|
||||
g_failures);
|
||||
return g_failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Erzeugt Referenzwerte mit den ORIGINAL-Funktionen aus chopper/sample_chopper4.py.
|
||||
|
||||
Das Modul importiert beim Laden matplotlib und tkinter. Beide werden hier durch
|
||||
Attrappen ersetzt, damit nur die DSP-Schicht geladen wird -- die GUI wird fuer
|
||||
den Vergleich nicht gebraucht.
|
||||
|
||||
python tools/reference_dump.py reference.txt
|
||||
|
||||
Die Ausgabe hat dasselbe Format wie sc_selftest (schluessel<TAB>wert) und wird
|
||||
von tools/compare.py gegen die C++-Ergebnisse geprueft.
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CHOPPER_DIR = os.path.join(ROOT, "chopper")
|
||||
|
||||
SR = 22050
|
||||
SECONDS = 4.0
|
||||
|
||||
|
||||
def _module(name, **attrs):
|
||||
mod = types.ModuleType(name)
|
||||
for key, value in attrs.items():
|
||||
setattr(mod, key, value)
|
||||
sys.modules[name] = mod
|
||||
return mod
|
||||
|
||||
|
||||
def install_gui_stubs():
|
||||
"""matplotlib/tkinter als leere Attrappen einhaengen."""
|
||||
mpl = _module("matplotlib", use=lambda *a, **k: None)
|
||||
figure = _module("matplotlib.figure", Figure=type("Figure", (), {}))
|
||||
mpl.figure = figure
|
||||
backends = _module("matplotlib.backends")
|
||||
mpl.backends = backends
|
||||
tkagg = _module("matplotlib.backends.backend_tkagg",
|
||||
FigureCanvasTkAgg=type("FigureCanvasTkAgg", (), {}))
|
||||
backends.backend_tkagg = tkagg
|
||||
|
||||
tk = _module("tkinter")
|
||||
ttk = _module("tkinter.ttk")
|
||||
filedialog = _module("tkinter.filedialog")
|
||||
messagebox = _module("tkinter.messagebox")
|
||||
tk.ttk = ttk
|
||||
tk.filedialog = filedialog
|
||||
tk.messagebox = messagebox
|
||||
# tkinterdnd2 fehlt absichtlich: der Import ist im Original optional.
|
||||
|
||||
|
||||
def make_signal():
|
||||
"""Deterministisches Testsignal -- identisch in tools/selftest.cpp.
|
||||
|
||||
Die Werte werden auf ein 1e-4-Raster gerundet, damit beide Seiten wirklich
|
||||
dieselben Samples sehen: sin() ist in libm und numpy nicht bitgleich, und
|
||||
der Flux verstaerkt einen 1e-7-Sampleunterschied auf ~1e-6 im Ergebnis.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
n = int(SECONDS * SR)
|
||||
x = np.zeros(n, dtype=np.float32)
|
||||
state = 12345
|
||||
for i in range(n):
|
||||
t = i / SR
|
||||
f = 0.0
|
||||
a = 0.0
|
||||
if t < 0.8:
|
||||
f, a = 220.0, 0.5
|
||||
elif t < 1.4:
|
||||
a = 0.0
|
||||
elif t < 2.2:
|
||||
f, a = 440.0, 0.5
|
||||
elif t < 2.6:
|
||||
a = 0.0
|
||||
else:
|
||||
f, a = 330.0, 0.5 * math.exp(-(t - 2.6) * 0.5)
|
||||
state = (state * 1664525 + 1013904223) % (2 ** 32)
|
||||
noise = (state / 2 ** 32) * 2.0 - 1.0
|
||||
raw = a * math.sin(2.0 * math.pi * f * t) + 0.001 * noise
|
||||
x[i] = np.float32(math.floor(raw * 10000.0 + 0.5) / 10000.0)
|
||||
return x
|
||||
|
||||
|
||||
def main():
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
flags = {a for a in sys.argv[1:] if a.startswith("--")}
|
||||
out_path = args[0] if args else None
|
||||
install_gui_stubs()
|
||||
sys.path.insert(0, CHOPPER_DIR)
|
||||
import sample_chopper4 as sc
|
||||
|
||||
import numpy as np
|
||||
|
||||
# --float64: den numpy-Rueckfallpfad der Vorlage erzwingen.
|
||||
#
|
||||
# Die Vorlage rechnet bei installiertem scipy in complex64. Fuer den
|
||||
# Genauigkeitsvergleich braucht es aber eine moeglichst fehlerfreie
|
||||
# Referenz -- sonst misst man die Rundung der Vorlage mit. Hier wird
|
||||
# deshalb auf np.fft (float64) umgeschaltet, was die Vorlage selbst als
|
||||
# gleichwertigen Pfad vorsieht.
|
||||
if "--float64" in flags:
|
||||
sc._FFT_DTYPE = np.float64
|
||||
sc._rfft = lambda a: np.fft.rfft(a, axis=1)
|
||||
|
||||
lines = []
|
||||
|
||||
def emit(key, value=""):
|
||||
lines.append(f"{key}\t{value}" if value != "" else str(key))
|
||||
|
||||
def emit_value(key, value):
|
||||
emit(key, "%.10g" % float(value))
|
||||
|
||||
def emit_int(key, value):
|
||||
emit(key, int(value))
|
||||
|
||||
def emit_precise(key, value):
|
||||
emit(key, "%.17g" % float(value))
|
||||
|
||||
def dump_series(tag, values, limit):
|
||||
values = list(values)
|
||||
emit_int(f"{tag}_n", len(values))
|
||||
for i, v in enumerate(values[:limit]):
|
||||
emit_value(f"{tag}_{i}", v)
|
||||
|
||||
def dump_curve_stats(prefix, values):
|
||||
values = np.asarray(values, dtype=float)
|
||||
emit_int(f"{prefix}_n", values.size)
|
||||
emit_value(f"{prefix}_sum", float(values.sum()) if values.size else 0.0)
|
||||
emit_value(f"{prefix}_max", float(values.max()) if values.size else 0.0)
|
||||
if values.size:
|
||||
emit_value(f"{prefix}_mid", float(values[values.size // 2]))
|
||||
|
||||
sig = make_signal()
|
||||
emit_int("samples_n", sig.size)
|
||||
|
||||
# ---- frame_rms -------------------------------------------------------
|
||||
rms_t, rms_v = sc.frame_rms(sig, SR)
|
||||
dump_curve_stats("rms", rms_v)
|
||||
emit_value("rms_t0", rms_t[0])
|
||||
emit_value("rms_t1", rms_t[-1])
|
||||
|
||||
# ---- spectral_flux / flux_envelope -----------------------------------
|
||||
fx_t, fx_v = sc.spectral_flux(sig, SR)
|
||||
dump_curve_stats("flux", fx_v)
|
||||
|
||||
env_t, env_v = sc.flux_envelope(sig, SR)
|
||||
dump_curve_stats("env", env_v)
|
||||
|
||||
# Diagnose: woher kommt der Unterschied bei env_mid?
|
||||
log_flux = np.log1p(fx_v.astype(np.float64))
|
||||
diag_base = float(np.median(log_flux))
|
||||
diag_top = float(np.percentile(log_flux, 98))
|
||||
emit_precise("diag_base", diag_base)
|
||||
emit_precise("diag_top", diag_top)
|
||||
emit_precise("diag_span", diag_top - diag_base)
|
||||
for idx in (0, 1, 100, 399, 400, 700):
|
||||
if idx < fx_v.size:
|
||||
emit_precise(f"diag_rawflux_{idx}", fx_v[idx])
|
||||
emit_precise(f"diag_logflux_{idx}", log_flux[idx])
|
||||
emit_precise(f"diag_env_{idx}", env_v[idx])
|
||||
|
||||
# Genauigkeit der FFT fuer EINEN Frame (isoliert von der Flux-Summe).
|
||||
fft_frame, fft_hop = 1024, 256
|
||||
win = np.hanning(fft_frame).astype(np.float64)
|
||||
x64 = np.ascontiguousarray(sig, dtype=np.float64)
|
||||
buf = x64[170 * fft_hop: 170 * fft_hop + fft_frame] * win
|
||||
mag = np.abs(np.fft.rfft(buf))
|
||||
for k in (0, 1, 2, 10, 100, 256, 512):
|
||||
emit_precise(f"diag_mag_{k}", mag[k])
|
||||
|
||||
# ---- onsets_from_flux -------------------------------------------------
|
||||
for sens in (0.15, 0.35, 0.5, 0.65, 0.9):
|
||||
thr, onsets = sc.onsets_from_flux(env_t, env_v, sens, SR)
|
||||
tag = "onsets_%.2f" % sens
|
||||
emit_int(f"{tag}_n", len(onsets))
|
||||
for i, v in enumerate(onsets[:24]):
|
||||
emit_value(f"{tag}_{i}", v)
|
||||
emit_value(f"{tag}_thrsum", float(np.sum(thr)))
|
||||
|
||||
# ---- Regionen / Stille ------------------------------------------------
|
||||
regions = sc.keep_segments(rms_t, rms_v, SECONDS, -40.0, 200.0, 20.0)
|
||||
emit_int("keep_n", len(regions))
|
||||
for i, (s, e) in enumerate(regions):
|
||||
emit_value(f"keep_{i}_start", s)
|
||||
emit_value(f"keep_{i}_end", e)
|
||||
|
||||
runs = sc.silence_runs(rms_t, rms_v, -40.0)
|
||||
emit_int("silence_runs_n", len(runs))
|
||||
for i, v in enumerate(list(runs)[:12]):
|
||||
emit_value(f"silence_run_{i}", v)
|
||||
|
||||
starts = sc.detect_region_starts(rms_t, rms_v, SECONDS, -40.0, 200.0)
|
||||
emit_int("region_starts_n", len(starts))
|
||||
for i, v in enumerate(starts[:12]):
|
||||
emit_value(f"region_start_{i}", v)
|
||||
|
||||
# ---- Grundton ---------------------------------------------------------
|
||||
p_t, p_f0, p_conf = sc.pitch_track(sig, SR)
|
||||
emit_int("pitch_n", p_t.size)
|
||||
for i in range(0, p_t.size, 20):
|
||||
emit_value(f"pitch_f0_{i}", p_f0[i])
|
||||
emit_value(f"pitch_conf_{i}", p_conf[i])
|
||||
|
||||
p_changes = sc.detect_pitch_changes(p_t, p_f0, p_conf, rms_t, rms_v, -40.0)
|
||||
emit_int("pitch_changes_n", len(p_changes))
|
||||
for i, v in enumerate(p_changes):
|
||||
emit_value(f"pitch_change_{i}", v)
|
||||
|
||||
# ---- Cut-Aufbereitung -------------------------------------------------
|
||||
cuts_in = [0.10, 0.42, 0.44, 0.80, 1.05, 1.62, 2.00, 2.05,
|
||||
2.60, 3.10, 3.11, 3.55]
|
||||
|
||||
det_cuts = sc.detect_cuts(sig, SR, {"transient", "onset", "pitch"},
|
||||
0.5, -40.0, 200.0, SECONDS)
|
||||
dump_series("detect_cuts", det_cuts, 64)
|
||||
|
||||
dump_series("enforce_min",
|
||||
sc.enforce_length_constraints(cuts_in, SECONDS, 0.35, 0.0), 64)
|
||||
dump_series("enforce_max",
|
||||
sc.enforce_length_constraints(cuts_in, SECONDS, 0.0, 0.5), 64)
|
||||
dump_series("cap5", sc.cap_by_strength(det_cuts, env_t, env_v, 5), 64)
|
||||
dump_series("pause",
|
||||
sc.pause_before_cuts(cuts_in, rms_t, rms_v, -40.0), 64)
|
||||
|
||||
scores = sc.cut_scores(cuts_in, env_t, env_v, rms_t, rms_v, -40.0)
|
||||
dump_series("scores", scores, 64)
|
||||
dump_series("phrase", sc.select_phrase_cuts(cuts_in, scores, SECONDS, 0.6), 64)
|
||||
|
||||
provider = lambda: (env_t, env_v)
|
||||
dump_series("finalized_phrase",
|
||||
sc.finalize_cuts(cuts_in, SECONDS, 0.5, 0.0, 0, True, provider,
|
||||
envelope=(rms_t, rms_v, -40.0)), 64)
|
||||
dump_series("finalized_hits",
|
||||
sc.finalize_cuts(cuts_in, SECONDS, 0.3, 0.4, 9, False, provider,
|
||||
envelope=(rms_t, rms_v, -40.0)), 64)
|
||||
dump_series("drop_excluded",
|
||||
sc._drop_excluded(cuts_in, [0.44, 2.05], 0.01), 64)
|
||||
|
||||
# ---- Anstiegszeiten / stabile Empfindlichkeit -------------------------
|
||||
rises = sc.rise_times(starts, rms_t, rms_v)
|
||||
dump_series("rises", rises, 16)
|
||||
emit_value("rise_median_ms", float(np.median(rises)) * 1000.0 if rises.size else 0.0)
|
||||
|
||||
sens, counts = sc.stable_sensitivity(env_t, env_v, SR)
|
||||
emit_value("stable_sens", sens)
|
||||
dump_series("stable_counts", counts, 32)
|
||||
|
||||
# ---- Auto-Analyse -----------------------------------------------------
|
||||
settings, info = sc.analyze_material(sig, SR, rms_t, rms_v, SECONDS,
|
||||
target="phrases",
|
||||
flux_data=(env_t, env_v),
|
||||
pitch_data=(p_t, p_f0, p_conf))
|
||||
emit_value("auto_thresh", settings["thresh"])
|
||||
emit_value("auto_minsil", settings["minsil"])
|
||||
emit_value("auto_pad", settings["pad"])
|
||||
emit_value("auto_sens", settings["sens"])
|
||||
emit("auto_mode\t" + sc.mode_to_str(settings["mode"]))
|
||||
emit_value("auto_minlen_ms", settings["min_len_ms"])
|
||||
emit_value("auto_maxlen_ms", settings["max_len_ms"])
|
||||
emit_int("auto_phrase", 1 if settings["phrase"] else 0)
|
||||
emit_value("auto_semitones", settings["semitones"])
|
||||
emit_value("info_floor_db", info["floor_db"])
|
||||
emit_value("info_loud_db", info["loud_db"])
|
||||
emit_value("info_rise_ms", info["rise_ms"])
|
||||
emit_value("info_silence_frac", info["silence_frac"])
|
||||
emit_value("info_onsets_per_s", info["onsets_per_s"])
|
||||
emit_value("info_voiced_frac", info["voiced_frac"])
|
||||
emit_value("info_region_gap", info["region_gap"])
|
||||
emit_value("info_ioi", info["ioi"])
|
||||
emit_int("info_regions", info["regions"])
|
||||
emit_int("info_onsets", info["onsets"])
|
||||
emit_int("info_pitch_changes", info["pitch_changes"])
|
||||
emit_value("info_min_len_s", info["min_len_s"])
|
||||
dump_series("info_counts", info["counts"], 32)
|
||||
|
||||
hits_settings, _ = sc.analyze_material(sig, SR, rms_t, rms_v, SECONDS,
|
||||
target="hits",
|
||||
flux_data=(env_t, env_v),
|
||||
pitch_data=(p_t, p_f0, p_conf))
|
||||
emit_value("hits_minlen_ms", hits_settings["min_len_ms"])
|
||||
emit_int("hits_phrase", 1 if hits_settings["phrase"] else 0)
|
||||
emit("hits_mode\t" + sc.mode_to_str(hits_settings["mode"]))
|
||||
|
||||
# ---- Anzeige / Export-Helfer ------------------------------------------
|
||||
px, pmins, pmaxs = sc.waveform_peaks_range(sig, SR, 0.5, 2.5, 400)
|
||||
emit_int("peaks_n", px.size)
|
||||
if px.size:
|
||||
emit_value("peaks_x0", px[0])
|
||||
emit_value("peaks_x1", px[-1])
|
||||
emit_value("peaks_minsum", float(np.sum(pmins)))
|
||||
emit_value("peaks_maxsum", float(np.sum(pmaxs)))
|
||||
|
||||
zc = np.array([np.float32(0.5 * math.sin(2.0 * math.pi * 220.0 * i / SR))
|
||||
for i in range(int(SECONDS * SR))], dtype=np.float32)
|
||||
for t in (0.5, 1.0, 2.0, 3.0):
|
||||
emit_value("snap_%.1f" % t, sc.snap_to_zero_crossing(zc, SR, t, 10.0))
|
||||
|
||||
emit_value("measure_peak_stereo",
|
||||
sc._measure_peak(sig, sig, "stereo", 1.4, 2.2, SR))
|
||||
emit_value("measure_peak_l", sc._measure_peak(sig, sig, "l", 1.4, 2.2, SR))
|
||||
|
||||
# ---- Modus-Persistenz -------------------------------------------------
|
||||
emit("mode_roundtrip\t" + sc.mode_to_str(sc.parse_mode("both")))
|
||||
emit("mode_legacy\t" + sc.mode_to_str(sc.parse_mode("pitch+onset")))
|
||||
emit("mode_off\t" + sc.mode_to_str(sc.parse_mode("")))
|
||||
|
||||
text = "\n".join(lines) + "\n"
|
||||
if out_path:
|
||||
with open(out_path, "w", encoding="utf-8", newline="\n") as fh:
|
||||
fh.write(text)
|
||||
print(f"{len(lines)} Referenzwerte -> {out_path}")
|
||||
else:
|
||||
sys.stdout.write(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,382 @@
|
||||
// ---------------------------------------------------------------------------
|
||||
// Selbsttest: rechnet die DSP-Kette auf einem deterministischen Testsignal
|
||||
// und gibt alle relevanten Werte als "schluessel<TAB>wert" aus.
|
||||
//
|
||||
// tools/reference_dump.py erzeugt dieselben Zeilen mit den Originalfunktionen
|
||||
// aus sample_chopper4.py; tools/compare.py vergleicht beide Ausgaben. Damit
|
||||
// ist belegbar, dass die Portierung nach C++ rechnet wie die Vorlage.
|
||||
//
|
||||
// Aufruf: sc_selftest [ausgabe.txt]
|
||||
// ---------------------------------------------------------------------------
|
||||
#include "core/Analyze.h"
|
||||
#include "core/Dsp.h"
|
||||
#include "core/Fft.h"
|
||||
#include "core/Stats.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QString>
|
||||
#include <QTextStream>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
constexpr int kSr = 22050;
|
||||
constexpr double kSeconds = 4.0;
|
||||
|
||||
QTextStream* g_out = nullptr;
|
||||
|
||||
void emitLine(const QString& line) {
|
||||
*g_out << line << '\n';
|
||||
// Sofort schreiben: bei einem Absturz ist sonst nicht zu sehen, wie weit
|
||||
// der Test gekommen ist.
|
||||
g_out->flush();
|
||||
}
|
||||
|
||||
/// %.10g wie in tools/reference_dump.py -- so sind beide Ausgaben direkt
|
||||
/// vergleichbar, auch ohne die Zahlen vorher zu parsen.
|
||||
void emitValue(const QString& key, double value) {
|
||||
char buffer[64];
|
||||
std::snprintf(buffer, sizeof(buffer), "%.10g", value);
|
||||
*g_out << key << '\t' << QLatin1String(buffer) << '\n';
|
||||
g_out->flush();
|
||||
}
|
||||
|
||||
void emitInt(const QString& key, long long value) {
|
||||
*g_out << key << '\t' << value << '\n';
|
||||
g_out->flush();
|
||||
}
|
||||
|
||||
/// Volle Genauigkeit -- fuer die Diagnose einzelner Zwischenwerte.
|
||||
void emitPrecise(const QString& key, double value) {
|
||||
char buffer[64];
|
||||
std::snprintf(buffer, sizeof(buffer), "%.17g", value);
|
||||
*g_out << key << '\t' << QLatin1String(buffer) << '\n';
|
||||
g_out->flush();
|
||||
}
|
||||
|
||||
/// Deterministisches Testsignal -- identisch in tools/reference_dump.py.
|
||||
///
|
||||
/// Drei Toene (220 / 440 / 330 Hz) mit zwei echten Pausen dazwischen und einem
|
||||
/// ausklingenden Ende, plus sehr leises Rauschen aus einem LCG. Damit sind
|
||||
/// alle Detektoren adressiert: Pausen (Einsaetze), Tonwechsel (Pitch),
|
||||
/// Anschlaege (Transienten) und ein Rauschboden fuer die Auto-Schwelle.
|
||||
///
|
||||
/// Die Werte werden auf ein 1e-4-Raster gerundet. Ohne das unterscheiden sich
|
||||
/// die Signale diesseits und jenseits der Sprachgrenze um ein bis zwei
|
||||
/// float32-ULPs, weil sin() in libm und in numpy nicht bitgleich ist. Der Flux
|
||||
/// ist eine Summe fast gleich grosser Differenzen und verstaerkt so einen
|
||||
/// 1e-7-Unterschied im Sample auf ~1e-6 im Ergebnis -- genug, um den Vergleich
|
||||
/// der beiden Implementierungen unbrauchbar zu machen. Das Raster ist fein
|
||||
/// genug, dass es die Analyse nicht beeinflusst (Amplitude 0.5 -> 5000 Stufen).
|
||||
sc::Samples makeSignal() {
|
||||
const std::size_t n = std::size_t(kSeconds * kSr);
|
||||
sc::Samples x(n);
|
||||
std::uint32_t state = 12345u;
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
const double t = double(i) / double(kSr);
|
||||
double f = 0.0;
|
||||
double a = 0.0;
|
||||
if (t < 0.8) {
|
||||
f = 220.0;
|
||||
a = 0.5;
|
||||
} else if (t < 1.4) {
|
||||
a = 0.0;
|
||||
} else if (t < 2.2) {
|
||||
f = 440.0;
|
||||
a = 0.5;
|
||||
} else if (t < 2.6) {
|
||||
a = 0.0;
|
||||
} else {
|
||||
f = 330.0;
|
||||
a = 0.5 * std::exp(-(t - 2.6) * 0.5);
|
||||
}
|
||||
state = state * 1664525u + 1013904223u;
|
||||
const double noise = (double(state) / 4294967296.0) * 2.0 - 1.0;
|
||||
const double raw = a * std::sin(2.0 * kPi * f * t) + 0.001 * noise;
|
||||
// floor(x+0.5) statt round(): gleiche Rundung in beiden Sprachen.
|
||||
x[i] = float(std::floor(raw * 10000.0 + 0.5) / 10000.0);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
void dumpCurveStats(const QString& prefix, const sc::Series& values) {
|
||||
double sum = 0.0;
|
||||
double mx = 0.0;
|
||||
for (double v : values) {
|
||||
sum += v;
|
||||
mx = std::max(mx, v);
|
||||
}
|
||||
emitInt(prefix + "_n", (long long)values.size());
|
||||
emitValue(prefix + "_sum", sum);
|
||||
emitValue(prefix + "_max", mx);
|
||||
if (!values.empty()) emitValue(prefix + "_mid", values[values.size() / 2]);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
QFile file;
|
||||
QTextStream fileStream;
|
||||
QTextStream console(stdout);
|
||||
QTextStream* out = &console;
|
||||
|
||||
if (argc > 1) {
|
||||
file.setFileName(QString::fromLocal8Bit(argv[1]));
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
|
||||
std::fprintf(stderr, "kann %s nicht schreiben\n", argv[1]);
|
||||
return 2;
|
||||
}
|
||||
fileStream.setDevice(&file);
|
||||
out = &fileStream;
|
||||
}
|
||||
g_out = out;
|
||||
|
||||
const sc::Samples signal = makeSignal();
|
||||
emitInt("samples_n", (long long)signal.size());
|
||||
|
||||
// ---- frame_rms -------------------------------------------------------
|
||||
const sc::Curve rms = sc::frameRms(signal, kSr);
|
||||
dumpCurveStats("rms", rms.values);
|
||||
emitValue("rms_t0", rms.times.empty() ? 0.0 : rms.times.front());
|
||||
emitValue("rms_t1", rms.times.empty() ? 0.0 : rms.times.back());
|
||||
|
||||
// ---- spectral_flux / flux_envelope -----------------------------------
|
||||
const sc::Curve flux = sc::spectralFlux(signal, kSr);
|
||||
dumpCurveStats("flux", flux.values);
|
||||
|
||||
const sc::Curve env = sc::fluxEnvelope(signal, kSr);
|
||||
dumpCurveStats("env", env.values);
|
||||
|
||||
{ // Diagnose: woher kommt der Unterschied bei env_mid?
|
||||
sc::Series logFlux = flux.values;
|
||||
for (double& v : logFlux) v = std::log1p(v);
|
||||
const double base = sc::median(logFlux);
|
||||
const double top = sc::percentile(logFlux, 98.0);
|
||||
emitPrecise("diag_base", base);
|
||||
emitPrecise("diag_top", top);
|
||||
emitPrecise("diag_span", top - base);
|
||||
for (std::size_t idx : {std::size_t(0), std::size_t(1), std::size_t(100),
|
||||
std::size_t(399), std::size_t(400), std::size_t(700)}) {
|
||||
if (idx < flux.values.size()) {
|
||||
emitPrecise(QStringLiteral("diag_rawflux_%1").arg(idx), flux.values[idx]);
|
||||
emitPrecise(QStringLiteral("diag_logflux_%1").arg(idx), logFlux[idx]);
|
||||
emitPrecise(QStringLiteral("diag_env_%1").arg(idx), env.values[idx]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{ // Diagnose: Genauigkeit der eigenen FFT gegen numpy fuer EINEN Frame.
|
||||
constexpr int kFrame = 170;
|
||||
constexpr int kFftFrame = 1024;
|
||||
constexpr int kFftHop = 256;
|
||||
sc::Fft fft(kFftFrame);
|
||||
const sc::Series win = sc::hanning(kFftFrame);
|
||||
std::vector<double> buf(kFftFrame);
|
||||
for (int j = 0; j < kFftFrame; ++j)
|
||||
buf[std::size_t(j)] =
|
||||
double(signal[std::size_t(kFrame * kFftHop + j)]) * win[std::size_t(j)];
|
||||
std::vector<double> mag(std::size_t(kFftFrame / 2 + 1));
|
||||
fft.rfftMagnitude(buf.data(), mag.data());
|
||||
for (int k : {0, 1, 2, 10, 100, 256, 512})
|
||||
emitPrecise(QStringLiteral("diag_mag_%1").arg(k), mag[std::size_t(k)]);
|
||||
}
|
||||
|
||||
// ---- onsets_from_flux bei mehreren Empfindlichkeiten -----------------
|
||||
for (double sens : {0.15, 0.35, 0.5, 0.65, 0.9}) {
|
||||
sc::Series thr;
|
||||
sc::Series onsets;
|
||||
sc::onsetsFromFlux(env, sens, kSr, thr, onsets);
|
||||
const QString tag = QStringLiteral("onsets_%1").arg(sens, 0, 'f', 2);
|
||||
emitInt(tag + "_n", (long long)onsets.size());
|
||||
for (std::size_t i = 0; i < onsets.size() && i < 24; ++i)
|
||||
emitValue(QStringLiteral("%1_%2").arg(tag).arg(i), onsets[i]);
|
||||
double thrSum = 0.0;
|
||||
for (double v : thr) thrSum += v;
|
||||
emitValue(tag + "_thrsum", thrSum);
|
||||
}
|
||||
|
||||
// ---- Region-Starts / silence_runs ------------------------------------
|
||||
const std::vector<sc::Segment> regions =
|
||||
sc::keepSegments(rms.times, rms.values, kSeconds, -40.0, 200.0, 20.0);
|
||||
emitInt("keep_n", (long long)regions.size());
|
||||
for (std::size_t i = 0; i < regions.size(); ++i) {
|
||||
emitValue(QStringLiteral("keep_%1_start").arg(i), regions[i].start);
|
||||
emitValue(QStringLiteral("keep_%1_end").arg(i), regions[i].end);
|
||||
}
|
||||
|
||||
const sc::Series runs = sc::silenceRuns(rms.times, rms.values, -40.0);
|
||||
emitInt("silence_runs_n", (long long)runs.size());
|
||||
for (std::size_t i = 0; i < runs.size() && i < 12; ++i)
|
||||
emitValue(QStringLiteral("silence_run_%1").arg(i), runs[i]);
|
||||
|
||||
const sc::Series regionStarts =
|
||||
sc::detectRegionStarts(rms.times, rms.values, kSeconds, -40.0, 200.0);
|
||||
emitInt("region_starts_n", (long long)regionStarts.size());
|
||||
for (std::size_t i = 0; i < regionStarts.size() && i < 12; ++i)
|
||||
emitValue(QStringLiteral("region_start_%1").arg(i), regionStarts[i]);
|
||||
|
||||
// ---- pitch_track / detect_pitch_changes ------------------------------
|
||||
const sc::PitchCurve pitch = sc::pitchTrack(signal, kSr);
|
||||
emitInt("pitch_n", (long long)pitch.times.size());
|
||||
for (std::size_t i = 0; i < pitch.times.size(); i += 20) {
|
||||
emitValue(QStringLiteral("pitch_f0_%1").arg(i), pitch.f0[i]);
|
||||
emitValue(QStringLiteral("pitch_conf_%1").arg(i), pitch.conf[i]);
|
||||
}
|
||||
const sc::Series pitchChanges =
|
||||
sc::detectPitchChanges(pitch, rms.times, rms.values, -40.0);
|
||||
emitInt("pitch_changes_n", (long long)pitchChanges.size());
|
||||
for (std::size_t i = 0; i < pitchChanges.size(); ++i)
|
||||
emitValue(QStringLiteral("pitch_change_%1").arg(i), pitchChanges[i]);
|
||||
|
||||
// ---- Cut-Aufbereitung ------------------------------------------------
|
||||
const sc::Series cutsIn{0.10, 0.42, 0.44, 0.80, 1.05, 1.62, 2.00, 2.05,
|
||||
2.60, 3.10, 3.11, 3.55};
|
||||
const sc::Series fluxCuts = sc::detectCuts(signal, kSr,
|
||||
[] {
|
||||
sc::DetectorSet s;
|
||||
s.set(sc::Detector::Transient);
|
||||
s.set(sc::Detector::Onset);
|
||||
s.set(sc::Detector::Pitch);
|
||||
return s;
|
||||
}(),
|
||||
0.5, -40.0, 200.0, kSeconds);
|
||||
|
||||
auto dumpSeries = [&](const QString& tag, const sc::Series& v, std::size_t limit) {
|
||||
emitInt(tag + "_n", (long long)v.size());
|
||||
for (std::size_t i = 0; i < v.size() && i < limit; ++i)
|
||||
emitValue(QStringLiteral("%1_%2").arg(tag).arg(i), v[i]);
|
||||
};
|
||||
|
||||
dumpSeries("detect_cuts", fluxCuts, 64);
|
||||
|
||||
const sc::Series minLen = sc::enforceLengthConstraints(cutsIn, kSeconds, 0.35, 0.0);
|
||||
dumpSeries("enforce_min", minLen, 64);
|
||||
const sc::Series maxLen = sc::enforceLengthConstraints(cutsIn, kSeconds, 0.0, 0.5);
|
||||
dumpSeries("enforce_max", maxLen, 64);
|
||||
|
||||
const sc::Series cap = sc::capByStrength(fluxCuts, env.times, env.values, 5);
|
||||
dumpSeries("cap5", cap, 64);
|
||||
|
||||
const sc::Series pause = sc::pauseBeforeCuts(cutsIn, rms.times, rms.values, -40.0);
|
||||
dumpSeries("pause", pause, 64);
|
||||
|
||||
const sc::Series scores =
|
||||
sc::cutScores(cutsIn, env.times, env.values, rms.times, rms.values, -40.0);
|
||||
dumpSeries("scores", scores, 64);
|
||||
|
||||
const sc::Series phrase = sc::selectPhraseCuts(cutsIn, scores, kSeconds, 0.6);
|
||||
dumpSeries("phrase", phrase, 64);
|
||||
|
||||
sc::FluxProvider provider = [&] { return std::make_pair(env.times, env.values); };
|
||||
const sc::Series finalized = sc::finalizeCuts(cutsIn, kSeconds, 0.5, 0.0, 0, true,
|
||||
provider, &rms.times, &rms.values, -40.0);
|
||||
dumpSeries("finalized_phrase", finalized, 64);
|
||||
|
||||
const sc::Series finalizedHits =
|
||||
sc::finalizeCuts(cutsIn, kSeconds, 0.3, 0.4, 9, false, provider, &rms.times,
|
||||
&rms.values, -40.0);
|
||||
dumpSeries("finalized_hits", finalizedHits, 64);
|
||||
|
||||
const sc::Series dropped = sc::dropExcluded(cutsIn, sc::Series{0.44, 2.05}, 0.01);
|
||||
dumpSeries("drop_excluded", dropped, 64);
|
||||
|
||||
// ---- rise_times / stable_sensitivity ---------------------------------
|
||||
const sc::Series rises = sc::riseTimes(regionStarts, rms.times, rms.values);
|
||||
dumpSeries("rises", rises, 16);
|
||||
emitValue("rise_median_ms",
|
||||
rises.empty() ? 0.0 : sc::median(rises) * 1000.0);
|
||||
|
||||
sc::Series counts;
|
||||
const double stableSens =
|
||||
sc::stableSensitivity(env.times, env.values, kSr, counts);
|
||||
emitValue("stable_sens", stableSens);
|
||||
dumpSeries("stable_counts", counts, 32);
|
||||
|
||||
// ---- analyze_material ------------------------------------------------
|
||||
sc::MaterialInfo info;
|
||||
const sc::FileSettings analysed =
|
||||
sc::analyzeMaterial(signal, kSr, rms.times, rms.values, kSeconds,
|
||||
QStringLiteral("phrases"), &env, &pitch, &info);
|
||||
emitValue("auto_thresh", analysed.thresh);
|
||||
emitValue("auto_minsil", analysed.minsil);
|
||||
emitValue("auto_pad", analysed.pad);
|
||||
emitValue("auto_sens", analysed.sens);
|
||||
emitLine("auto_mode\t" + sc::modeToStr(analysed.mode));
|
||||
emitValue("auto_minlen_ms", analysed.minLenMs);
|
||||
emitValue("auto_maxlen_ms", analysed.maxLenMs);
|
||||
emitInt("auto_phrase", analysed.phrase ? 1 : 0);
|
||||
emitValue("auto_semitones", analysed.semitones);
|
||||
emitValue("info_floor_db", info.floorDb);
|
||||
emitValue("info_loud_db", info.loudDb);
|
||||
emitValue("info_rise_ms", info.riseMs);
|
||||
emitValue("info_silence_frac", info.silenceFrac);
|
||||
emitValue("info_onsets_per_s", info.onsetsPerS);
|
||||
emitValue("info_voiced_frac", info.voicedFrac);
|
||||
emitValue("info_region_gap", info.regionGap);
|
||||
emitValue("info_ioi", info.ioi);
|
||||
emitInt("info_regions", info.regions);
|
||||
emitInt("info_onsets", info.onsets);
|
||||
emitInt("info_pitch_changes", info.pitchChanges);
|
||||
emitValue("info_min_len_s", info.minLenS);
|
||||
dumpSeries("info_counts", info.counts, 32);
|
||||
|
||||
const sc::FileSettings hits =
|
||||
sc::analyzeMaterial(signal, kSr, rms.times, rms.values, kSeconds,
|
||||
QStringLiteral("hits"), &env, &pitch, nullptr);
|
||||
emitValue("hits_minlen_ms", hits.minLenMs);
|
||||
emitInt("hits_phrase", hits.phrase ? 1 : 0);
|
||||
emitLine("hits_mode\t" + sc::modeToStr(hits.mode));
|
||||
|
||||
// ---- Anzeige / Export-Helfer -----------------------------------------
|
||||
sc::Series px, pmins, pmaxs;
|
||||
sc::waveformPeaksRange(signal, kSr, 0.5, 2.5, 400, px, pmins, pmaxs);
|
||||
emitInt("peaks_n", (long long)px.size());
|
||||
if (!px.empty()) {
|
||||
emitValue("peaks_x0", px.front());
|
||||
emitValue("peaks_x1", px.back());
|
||||
}
|
||||
{ // Pruefsumme ueber alle Buckets -- empfindlich gegen Verschiebungen
|
||||
double sumMin = 0.0;
|
||||
double sumMax = 0.0;
|
||||
for (double v : pmins) sumMin += v;
|
||||
for (double v : pmaxs) sumMax += v;
|
||||
emitValue("peaks_minsum", sumMin);
|
||||
emitValue("peaks_maxsum", sumMax);
|
||||
}
|
||||
|
||||
// Nulldurchgangs-Referenz: 220-Hz-Sinus, wie ihn decode_mono() liefern
|
||||
// wuerde (die echte Dekodierung haengt an ffmpeg und gehoert nicht hierher).
|
||||
sc::Samples zcRef(std::size_t(kSeconds * kSr));
|
||||
for (std::size_t i = 0; i < zcRef.size(); ++i)
|
||||
zcRef[i] = float(0.5 * std::sin(2.0 * kPi * 220.0 * double(i) / kSr));
|
||||
for (double t : {0.5, 1.0, 2.0, 3.0}) {
|
||||
emitValue(QStringLiteral("snap_%1").arg(t, 0, 'f', 1),
|
||||
sc::snapToZeroCrossing(zcRef, kSr, t, 10.0));
|
||||
}
|
||||
|
||||
const double peak = sc::measurePeak(&signal, &signal, QStringLiteral("stereo"),
|
||||
1.4, 2.2, kSr);
|
||||
emitValue("measure_peak_stereo", peak);
|
||||
const double peakL = sc::measurePeak(&signal, &signal, QStringLiteral("l"),
|
||||
1.4, 2.2, kSr);
|
||||
emitValue("measure_peak_l", peakL);
|
||||
|
||||
// ---- Modus-Persistenz ------------------------------------------------
|
||||
emitLine("mode_roundtrip\t" + sc::modeToStr(sc::parseMode(QStringLiteral("both"))));
|
||||
emitLine("mode_legacy\t" + sc::modeToStr(sc::parseMode(QStringLiteral("pitch+onset"))));
|
||||
emitLine("mode_off\t" + sc::modeToStr(sc::parseMode(QStringLiteral(""))));
|
||||
|
||||
if (file.isOpen()) {
|
||||
out->flush();
|
||||
file.close();
|
||||
} else {
|
||||
out->flush();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# Installiert Qt 6.8.3 fuer MinGW 13.1 samt passendem Compiler.
|
||||
#
|
||||
# Grund: Auf diesem Rechner ist Visual Studio 2022 zwar installiert, aber ohne
|
||||
# die C++-Workload (kein VC\Tools\MSVC, kein vcvars64.bat). Das MinGW-Paket von
|
||||
# Qt ist in sich stimmig und braucht keine Administratorrechte.
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
$log = 'C:\Users\Key & Co\Desktop\Programme\Samplechopper\_setup\qt_mingw_setup.log'
|
||||
Set-Content -Path $log -Value "=== Qt/MinGW setup $(Get-Date -Format s) ==="
|
||||
function L([string]$m) { $m | Tee-Object -FilePath $log -Append }
|
||||
|
||||
L "--- verfuegbare Varianten von tools_mingw1310 ---"
|
||||
& python -m aqt list-tool windows desktop tools_mingw1310 2>&1 | Tee-Object -FilePath $log -Append
|
||||
|
||||
L "--- MinGW 13.1 installieren ---"
|
||||
& python -m aqt install-tool windows desktop tools_mingw1310 qt.tools.win64_mingw1310 `
|
||||
--outputdir C:\Qt 2>&1 | Tee-Object -FilePath $log -Append
|
||||
L "exit: $LASTEXITCODE"
|
||||
|
||||
L "--- Qt 6.8.3 win64_mingw installieren ---"
|
||||
& python -m aqt install-qt windows desktop 6.8.3 win64_mingw `
|
||||
--outputdir C:\Qt --archives qtbase qttools 2>&1 | Tee-Object -FilePath $log -Append
|
||||
L "exit: $LASTEXITCODE"
|
||||
|
||||
L "--- Ergebnis ---"
|
||||
Get-ChildItem C:\Qt -Directory | Select-Object -ExpandProperty FullName | Tee-Object -FilePath $log -Append
|
||||
Get-ChildItem 'C:\Qt\6.8.3\mingw_64\bin\Qt6Widgets.dll' -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { L ("Widgets: " + $_.FullName) }
|
||||
Get-ChildItem 'C:\Qt\Tools' -Directory -ErrorAction SilentlyContinue |
|
||||
Select-Object -ExpandProperty FullName | Tee-Object -FilePath $log -Append
|
||||
L "=== done $(Get-Date -Format s) ==="
|
||||
@@ -0,0 +1,62 @@
|
||||
# Installiert Qt 6.8 (MSVC 2022) + CMake + Ninja fuer den Samplechopper-Port.
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
$root = 'C:\Users\Key & Co\Desktop\Programme\Samplechopper'
|
||||
$log = Join-Path $root '_setup\qt_setup.log'
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null
|
||||
Set-Content -Path $log -Value "=== Qt setup start $(Get-Date -Format s) ==="
|
||||
|
||||
function L([string]$m) { $m | Tee-Object -FilePath $log -Append }
|
||||
|
||||
# --- 1. pip-Werkzeuge -------------------------------------------------------
|
||||
L "--- pip install aqtinstall cmake ninja ---"
|
||||
& python -m pip install --upgrade --disable-pip-version-check aqtinstall cmake ninja 2>&1 |
|
||||
Tee-Object -FilePath $log -Append
|
||||
L "pip exit: $LASTEXITCODE"
|
||||
if ($LASTEXITCODE -ne 0) { L "FATAL: pip install fehlgeschlagen"; exit 1 }
|
||||
|
||||
# --- 2. Zielverzeichnis -----------------------------------------------------
|
||||
$qtDir = 'C:\Qt'
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $qtDir -ErrorAction Stop | Out-Null
|
||||
Test-Path $qtDir -PathType Container -ErrorAction Stop | Out-Null
|
||||
} catch {
|
||||
$qtDir = Join-Path $env:LOCALAPPDATA 'Qt'
|
||||
New-Item -ItemType Directory -Force -Path $qtDir | Out-Null
|
||||
}
|
||||
L "Qt-Zielverzeichnis: $qtDir"
|
||||
|
||||
# --- 3. Verfuegbare 6.8er-Version bestimmen ---------------------------------
|
||||
L "--- aqt list-qt (6.8) ---"
|
||||
$ver = (& python -m aqt list-qt windows desktop --latest-version 6.8 2>&1 | Select-Object -Last 1)
|
||||
$ver = "$ver".Trim()
|
||||
if (-not $ver -or $ver -notmatch '^6\.') { $ver = '6.8.3' }
|
||||
L "Qt-Version: $ver"
|
||||
|
||||
# --- 4. Qt installieren -----------------------------------------------------
|
||||
L "--- aqt install-qt $ver win64_msvc2022_64 (qtbase qttools) ---"
|
||||
& python -m aqt install-qt windows desktop $ver win64_msvc2022_64 `
|
||||
--outputdir $qtDir --archives qtbase qttools 2>&1 |
|
||||
Tee-Object -FilePath $log -Append
|
||||
$rc = $LASTEXITCODE
|
||||
L "aqt exit (archives): $rc"
|
||||
|
||||
if ($rc -ne 0) {
|
||||
L "--- Fallback: vollstaendige Basis-Archive ---"
|
||||
& python -m aqt install-qt windows desktop $ver win64_msvc2022_64 `
|
||||
--outputdir $qtDir 2>&1 | Tee-Object -FilePath $log -Append
|
||||
L "aqt exit (full): $LASTEXITCODE"
|
||||
}
|
||||
|
||||
# --- 5. Ergebnis pruefen ----------------------------------------------------
|
||||
L "--- Ergebnis ---"
|
||||
Get-ChildItem -Path $qtDir -Recurse -Filter 'Qt6Config.cmake' -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { L ("Qt6Config: " + $_.FullName) }
|
||||
Get-ChildItem -Path $qtDir -Recurse -Filter 'Qt6Widgets.dll' -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { L ("Qt6Widgets: " + $_.FullName) }
|
||||
foreach ($t in 'cmake', 'ninja') {
|
||||
$p = Get-Command $t -ErrorAction SilentlyContinue
|
||||
if ($p) { L "$t -> $($p.Source)" } else { L "$t -> FEHLT" }
|
||||
}
|
||||
L "=== Qt setup done $(Get-Date -Format s) ==="
|
||||
Reference in New Issue
Block a user