File size: 25,967 Bytes
f2b6e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// engine_rt.cpp β€” дСтСкція Π΄Π²ΠΈΠ³ΡƒΠ½Π° автомобіля Π² Ρ€Π΅Π°Π»ΡŒΠ½ΠΎΠΌΡƒ часі (ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½ Π°Π±ΠΎ WAV-Ρ„Π°ΠΉΠ»)
//
// ЗалСТності:  miniaudio.h (ΠΎΠ΄ΠΈΠ½ Π·Π°Π³ΠΎΠ»ΠΎΠ²ΠΎΠΊ, https://github.com/mackron/miniaudio)
//              ONNX Runtime (C++ API)
// Π€Π°ΠΉΠ»ΠΈ ΠΌΠΎΠ΄Π΅Π»Ρ– (ΡΡ‚Π²ΠΎΡ€ΡŽΡ” `python engine_detector.py export`):
//              engine.onnx, mel_fb.f32, engine_meta.txt
//
// ΠšΠΎΠ½Π²Π΅Ρ”Ρ€ (ΠΏΠΎΠ²Π½Ρ–ΡΡ‚ΡŽ ΠΏΠΎΠ²Ρ‚ΠΎΡ€ΡŽΡ” Python-Ρ„Ρ€ΠΎΠ½Ρ‚Π΅Π½Π΄ LogMel):
//   ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½ 16 ΠΊΠ“Ρ† mono β†’ ΠΊΡ–Π»ΡŒΡ†Π΅Π²ΠΈΠΉ Π±ΡƒΡ„Π΅Ρ€ β†’ останні 1 с β†’ reflect-pad β†’ STFT (Hann, n_fft=1024, hop=160)
//   β†’ |X|Β² β†’ mel (матриця Π· mel_fb.f32) β†’ (10Β·log10 + 40)/40 β†’ ONNX β†’ sigmoid β†’ EMA + гістСрСзис
//
// Π—Π±Ρ–Ρ€ΠΊΠ°: Π΄ΠΈΠ². CMakeLists.txt.  Запуск:
//   ./engine_rt --model-dir export --list            # список ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½Ρ–Π²
//   ./engine_rt --model-dir export [--device 1]      # дСтСкція Π· ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½Π° (Ctrl+C β€” Π²ΠΈΡ…Ρ–Π΄)
//   ./engine_rt --model-dir export --bench 500       # ΡˆΠ²ΠΈΠ΄ΠΊΡ–ΡΡ‚ΡŒ: Ρ„Ρ€ΠΎΠ½Ρ‚Π΅Π½Π΄ + ONNX ΠΎΠΊΡ€Π΅ΠΌΠΎ
//   ./engine_rt --model-dir export --wav test.wav    # ΠΏΠ΅Ρ€Π΅Π²Ρ–Ρ€ΠΊΠ° Π½Π° Ρ„Π°ΠΉΠ»Ρ– (16 ΠΊΠ“Ρ† WAV β€” Ρ‚ΠΎΡ‡Π½Π° Π²Ρ–Π΄ΠΏΠΎΠ²Ρ–Π΄Π½Ρ–ΡΡ‚ΡŒ Python)

#define MINIAUDIO_IMPLEMENTATION
#define MA_NO_ENCODING
#define MA_NO_GENERATION
#include "miniaudio.h"

#include <onnxruntime_cxx_api.h>

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <vector>

// ───────────────────────────────────────────────────────────────────────────
// ΠœΠ΅Ρ‚Π°Π΄Π°Π½Ρ– (engine_meta.txt: key=value)
// ───────────────────────────────────────────────────────────────────────────
struct Meta {
    int sr = 16000, window = 16000, n_fft = 1024, hop = 160, n_mels = 64, n_freqs = 513, frames = 101;
    float db_offset = 40.f, db_scale = 40.f, threshold = 0.5f;
    bool norm_mean = false;           // true: x = (dB - mean(dB)) / db_scale  (Π½Π΅ Π·Π°Π»Π΅ΠΆΠΈΡ‚ΡŒ Π²Ρ–Π΄ гучності)
};

static bool load_meta(const std::string& path, Meta& m) {
    std::ifstream f(path);
    if (!f) return false;
    std::string line;
    while (std::getline(f, line)) {
        auto eq = line.find('=');
        if (eq == std::string::npos) continue;
        std::string k = line.substr(0, eq), v = line.substr(eq + 1);
        if (k == "sample_rate") m.sr = std::stoi(v);
        else if (k == "window") m.window = std::stoi(v);
        else if (k == "n_fft") m.n_fft = std::stoi(v);
        else if (k == "hop_length") m.hop = std::stoi(v);
        else if (k == "n_mels") m.n_mels = std::stoi(v);
        else if (k == "n_freqs") m.n_freqs = std::stoi(v);
        else if (k == "frames") m.frames = std::stoi(v);
        else if (k == "db_offset") m.db_offset = std::stof(v);
        else if (k == "db_scale") m.db_scale = std::stof(v);
        else if (k == "threshold") m.threshold = std::stof(v);
        else if (k == "norm") m.norm_mean = (v == "mean");
    }
    return true;
}

// ───────────────────────────────────────────────────────────────────────────
// Log-mel Ρ„Ρ€ΠΎΠ½Ρ‚Π΅Π½Π΄ (Π±Π΅Π· Π·ΠΎΠ²Π½Ρ–ΡˆΠ½Ρ–Ρ… залСТностСй; власний radix-2 FFT)
// ───────────────────────────────────────────────────────────────────────────
class MelFrontend {
public:
    MelFrontend(const Meta& m, const std::string& fb_path) : m_(m) {
        const int n = m_.n_fft;
        if (n & (n - 1)) throw std::runtime_error("n_fft ΠΌΠ°Ρ” Π±ΡƒΡ‚ΠΈ стСпСнСм Π΄Π²Ρ–ΠΉΠΊΠΈ");

        // ΠœΠ°Ρ‚Ρ€ΠΈΡ†Ρ mel-Ρ„Ρ–Π»ΡŒΡ‚Ρ€Ρ–Π² (n_freqs Γ— n_mels, float32, row-major) β€” Π· torchaudio
        std::ifstream f(fb_path, std::ios::binary);
        if (!f) throw std::runtime_error("НС вдалося Π²Ρ–Π΄ΠΊΡ€ΠΈΡ‚ΠΈ " + fb_path);
        fb_.resize((size_t)m_.n_freqs * m_.n_mels);
        f.read(reinterpret_cast<char*>(fb_.data()), fb_.size() * sizeof(float));
        if (!f) throw std::runtime_error("mel_fb.f32 ΠΌΠ°Ρ” Π½Π΅ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½ΠΈΠΉ Ρ€ΠΎΠ·ΠΌΡ–Ρ€");

        // Hann (periodic β€” як torch.hann_window Π·Π° замовчуванням)
        const double PI = std::acos(-1.0);
        win_.resize(n);
        for (int i = 0; i < n; ++i) win_[i] = (float)(0.5 * (1.0 - std::cos(2.0 * PI * i / n)));

        cos_.resize(n / 2); sin_.resize(n / 2);
        for (int k = 0; k < n / 2; ++k) { cos_[k] = (float)std::cos(2.0 * PI * k / n); sin_[k] = (float)std::sin(2.0 * PI * k / n); }

        rev_.resize(n);
        int bits = 0; while ((1 << bits) < n) ++bits;
        for (int i = 0; i < n; ++i) {
            int r = 0; for (int b = 0; b < bits; ++b) if (i & (1 << b)) r |= 1 << (bits - 1 - b);
            rev_[i] = r;
        }
        re_.resize(n); im_.resize(n); pw_.resize(m_.n_freqs); mel_.resize(m_.n_mels);
    }

    // x: m.window Π²Ρ–Π΄Π»Ρ–ΠΊΡ–Π² β†’ out: [n_mels Γ— frames], row-major (індСкс = mel * frames + t)
    void compute(const float* x, float* out) {
        const int N = m_.window, nfft = m_.n_fft, pad = nfft / 2, hop = m_.hop;
        auto sample = [&](int i) -> float {          // reflect-padding, як center=True Ρƒ torch.stft
            if (i < 0) i = -i;
            if (i >= N) i = 2 * (N - 1) - i;
            return x[i];
        };
        for (int t = 0; t < m_.frames; ++t) {
            for (int k = 0; k < nfft; ++k) { re_[k] = sample(t * hop + k - pad) * win_[k]; im_[k] = 0.f; }
            fft();
            for (int f = 0; f < m_.n_freqs; ++f) pw_[f] = re_[f] * re_[f] + im_[f] * im_[f];
            std::fill(mel_.begin(), mel_.end(), 0.f);
            for (int f = 0; f < m_.n_freqs; ++f) {
                const float p = pw_[f]; const float* row = &fb_[(size_t)f * m_.n_mels];
                for (int m = 0; m < m_.n_mels; ++m) mel_[m] += p * row[m];
            }
            for (int m = 0; m < m_.n_mels; ++m)
                out[(size_t)m * m_.frames + t] = 10.f * std::log10(std::max(mel_[m], 1e-10f));   // dB
        }
        const size_t total = (size_t)m_.n_mels * m_.frames;
        if (m_.norm_mean) {
            double sum = 0; for (size_t i = 0; i < total; ++i) sum += out[i];
            const float mean = (float)(sum / total);
            for (size_t i = 0; i < total; ++i) out[i] = (out[i] - mean) / m_.db_scale;
        } else {
            for (size_t i = 0; i < total; ++i) out[i] = (out[i] + m_.db_offset) / m_.db_scale;
        }
    }

private:
    void fft() {                                     // in-place, прямий (e^{-j…})
        const int n = m_.n_fft;
        for (int i = 0; i < n; ++i) { int j = rev_[i]; if (j > i) { std::swap(re_[i], re_[j]); std::swap(im_[i], im_[j]); } }
        for (int len = 2; len <= n; len <<= 1) {
            const int half = len >> 1, step = n / len;
            for (int i = 0; i < n; i += len)
                for (int k = 0; k < half; ++k) {
                    const float wr = cos_[k * step], wi = -sin_[k * step];
                    const int a = i + k, b = a + half;
                    const float tr = re_[b] * wr - im_[b] * wi, ti = re_[b] * wi + im_[b] * wr;
                    re_[b] = re_[a] - tr; im_[b] = im_[a] - ti;
                    re_[a] += tr;         im_[a] += ti;
                }
        }
    }
    Meta m_;
    std::vector<float> fb_, win_, cos_, sin_, re_, im_, pw_, mel_;
    std::vector<int> rev_;
};

// ───────────────────────────────────────────────────────────────────────────
// ONNX Runtime
// ───────────────────────────────────────────────────────────────────────────
class OnnxEngine {
public:
    OnnxEngine(const std::string& path, int threads)
        : env_(ORT_LOGGING_LEVEL_WARNING, "engine_rt"), session_(nullptr),
          mem_(Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault)) {
        Ort::SessionOptions so;
        so.SetIntraOpNumThreads(threads);
        so.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
#ifdef _WIN32
        std::wstring w(path.begin(), path.end());
        session_ = Ort::Session(env_, w.c_str(), so);
#else
        session_ = Ort::Session(env_, path.c_str(), so);
#endif
    }
    // mel: [n_mels Γ— frames] β†’ ΠΉΠΌΠΎΠ²Ρ–Ρ€Π½Ρ–ΡΡ‚ΡŒ
    float prob(std::vector<float>& mel, int64_t n_mels, int64_t frames) {
        std::array<int64_t, 4> shape{1, 1, n_mels, frames};
        Ort::Value in = Ort::Value::CreateTensor<float>(mem_, mel.data(), mel.size(), shape.data(), shape.size());
        const char* in_names[] = {"mel"};
        const char* out_names[] = {"logit"};
        auto out = session_.Run(Ort::RunOptions{nullptr}, in_names, &in, 1, out_names, 1);
        const float logit = out[0].GetTensorData<float>()[0];
        return 1.f / (1.f + std::exp(-logit));
    }
private:
    Ort::Env env_;
    Ort::Session session_;
    Ort::MemoryInfo mem_;
};

// ───────────────────────────────────────────────────────────────────────────
// Lock-free SPSC ΠΊΡ–Π»ΡŒΡ†Π΅Π²ΠΈΠΉ Π±ΡƒΡ„Π΅Ρ€: callback ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½Π° (producer) β†’ Π³ΠΎΠ»ΠΎΠ²Π½ΠΈΠΉ ΠΏΠΎΡ‚Ρ–ΠΊ (consumer)
// ───────────────────────────────────────────────────────────────────────────
class Ring {
public:
    explicit Ring(size_t pow2) : buf_(pow2), mask_(pow2 - 1) {}
    void push(const float* d, size_t n) {
        const size_t h = head_.load(std::memory_order_relaxed), t = tail_.load(std::memory_order_acquire);
        const size_t space = buf_.size() - (h - t);
        if (n > space) { dropped_ += n - space; n = space; }
        for (size_t i = 0; i < n; ++i) buf_[(h + i) & mask_] = d[i];
        head_.store(h + n, std::memory_order_release);
    }
    size_t pop(float* d, size_t n) {
        const size_t t = tail_.load(std::memory_order_relaxed), h = head_.load(std::memory_order_acquire);
        n = std::min(n, h - t);
        for (size_t i = 0; i < n; ++i) d[i] = buf_[(t + i) & mask_];
        tail_.store(t + n, std::memory_order_release);
        return n;
    }
    size_t dropped() const { return dropped_.load(); }
private:
    std::vector<float> buf_;
    size_t mask_;
    std::atomic<size_t> head_{0}, tail_{0}, dropped_{0};
};

// ───────────────────────────────────────────────────────────────────────────
// Π Ρ–ΡˆΠ΅Π½Π½Ρ: EMA + гістСрСзис (Ρ‰ΠΎΠ± Π½Π΅ Β«ΠΌΠΈΠ³Π°Π»ΠΎΒ» Π½Π° ΠΊΠΎΠΆΠ½ΠΎΠΌΡƒ Π²Ρ–ΠΊΠ½Ρ–)
// ───────────────────────────────────────────────────────────────────────────
class Decider {
public:
    Decider(float thr, float off_ratio, float alpha, int need) : thr_(thr), off_(off_ratio), a_(alpha), need_(need) {}
    float ema() const { return ema_; }
    bool active() const { return active_; }
    int update(float p) {                      // +1 β€” ΠΏΠΎΡ‡Π°Ρ‚ΠΎΠΊ ΠΏΠΎΠ΄Ρ–Ρ—, βˆ’1 β€” ΠΊΡ–Π½Π΅Ρ†ΡŒ, 0 β€” Π±Π΅Π· Π·ΠΌΡ–Π½
        ema_ = init_ ? a_ * p + (1.f - a_) * ema_ : p; init_ = true;
        if (!active_) {
            on_ = (ema_ >= thr_) ? on_ + 1 : 0;
            if (on_ >= need_) { active_ = true; off_cnt_ = 0; return +1; }
        } else {
            off_cnt_ = (ema_ < thr_ * off_) ? off_cnt_ + 1 : 0;
            if (off_cnt_ >= need_) { active_ = false; on_ = 0; return -1; }
        }
        return 0;
    }
private:
    float thr_, off_, a_, ema_ = 0.f; int need_, on_ = 0, off_cnt_ = 0; bool init_ = false, active_ = false;
};

// ───────────────────────────────────────────────────────────────────────────
// Π£Ρ‚ΠΈΠ»Ρ–Ρ‚ΠΈ
// ───────────────────────────────────────────────────────────────────────────
static std::atomic<bool> g_run{true};
static void on_sigint(int) { g_run = false; }

static void data_cb(ma_device* dev, void*, const void* in, ma_uint32 frames) {
    if (in) static_cast<Ring*>(dev->pUserData)->push(static_cast<const float*>(in), frames);
}

static std::string bar(float p, int w = 20) {
    int n = std::clamp((int)std::lround(p * w), 0, w);
    return std::string(n, '#') + std::string(w - n, '.');
}

static float rms_dbfs(const float* x, size_t n) {
    double s = 0; for (size_t i = 0; i < n; ++i) s += (double)x[i] * x[i];
    return 20.f * std::log10((float)std::sqrt(s / std::max<size_t>(1, n)) + 1e-9f);
}

static bool read_audio_file(const std::string& path, int sr, std::vector<float>& out) {
    ma_decoder_config c = ma_decoder_config_init(ma_format_f32, 1, (ma_uint32)sr);   // β†’ mono, sr
    ma_decoder dec;
    if (ma_decoder_init_file(path.c_str(), &c, &dec) != MA_SUCCESS) return false;
    std::vector<float> chunk(4096);
    for (;;) {
        ma_uint64 n = 0;
        ma_result r = ma_decoder_read_pcm_frames(&dec, chunk.data(), chunk.size(), &n);
        out.insert(out.end(), chunk.begin(), chunk.begin() + (size_t)n);
        if (r != MA_SUCCESS || n == 0) break;
    }
    ma_decoder_uninit(&dec);
    return true;
}

struct Args {
    std::string model_dir = "export", wav;
    int device = -1, hop = 4000, threads = 1;
    float threshold = -1.f, gain_db = 0.f, off_ratio = 0.7f, alpha = 0.5f;
    int need = 2, bench = 0;
    bool list = false, verbose = false;
};

static Args parse_args(int argc, char** argv) {
    Args a;
    for (int i = 1; i < argc; ++i) {
        std::string k = argv[i];
        auto next = [&]() -> std::string { if (i + 1 >= argc) { std::fprintf(stderr, "НСмає значСння для %s\n", k.c_str()); std::exit(2); } return argv[++i]; };
        if (k == "--model-dir") a.model_dir = next();
        else if (k == "--wav") a.wav = next();
        else if (k == "--device") a.device = std::stoi(next());
        else if (k == "--hop") a.hop = std::stoi(next());
        else if (k == "--threshold") a.threshold = std::stof(next());
        else if (k == "--gain") a.gain_db = std::stof(next());
        else if (k == "--off-ratio") a.off_ratio = std::stof(next());
        else if (k == "--alpha") a.alpha = std::stof(next());
        else if (k == "--need") a.need = std::stoi(next());
        else if (k == "--threads") a.threads = std::stoi(next());
        else if (k == "--bench") a.bench = std::stoi(next());
        else if (k == "--list") a.list = true;
        else if (k == "--verbose") a.verbose = true;
        else {
            std::printf("Використання: engine_rt --model-dir DIR [--list] [--device N] [--wav FILE]\n"
                        "              [--bench N] [--threshold T] [--gain dB] [--hop SAMPLES] [--alpha A] [--off-ratio R] [--need N]\n");
            std::exit(k == "--help" ? 0 : 2);
        }
    }
    return a;
}

// ───────────────────────────────────────────────────────────────────────────
// Π’ΠΈΠΌΡ–Ρ€ ΡˆΠ²ΠΈΠ΄ΠΊΠΎΡΡ‚Ρ–: mel-Ρ„Ρ€ΠΎΠ½Ρ‚Π΅Π½Π΄ Ρ– ONNX ΠΎΠΊΡ€Π΅ΠΌΠΎ, Π½Π° синтСтичному ΡˆΡƒΠΌΡ–
// ───────────────────────────────────────────────────────────────────────────
static int run_bench(const Args& a, const Meta& m, MelFrontend& fe, OnnxEngine& eng) {
    std::mt19937 rng(1);
    std::normal_distribution<float> nd(0.f, 0.05f);
    std::vector<float> x(m.window), mel((size_t)m.n_mels * m.frames);
    for (auto& v : x) v = nd(rng);
    for (int i = 0; i < 20; ++i) { fe.compute(x.data(), mel.data()); eng.prob(mel, m.n_mels, m.frames); }   // ΠΏΡ€ΠΎΠ³Ρ€Ρ–Π²

    std::vector<double> tf, tn;
    using clk = std::chrono::steady_clock;
    for (int i = 0; i < a.bench; ++i) {
        auto t0 = clk::now(); fe.compute(x.data(), mel.data());
        auto t1 = clk::now(); eng.prob(mel, m.n_mels, m.frames);
        auto t2 = clk::now();
        tf.push_back(std::chrono::duration<double, std::milli>(t1 - t0).count());
        tn.push_back(std::chrono::duration<double, std::milli>(t2 - t1).count());
    }
    auto stat = [](std::vector<double> v, const char* name) {
        std::sort(v.begin(), v.end());
        double mean = 0; for (double e : v) mean += e; mean /= v.size();
        std::printf("  %-22s сСрСднє %7.3f мс | ΠΌΠ΅Π΄Ρ–Π°Π½Π° %7.3f | p95 %7.3f | макс %7.3f\n", name, mean, v[v.size() / 2], v[(size_t)(v.size() * 0.95)], v.back());
        return mean;
    };
    std::printf("Π‘Π΅Π½Ρ‡ΠΌΠ°Ρ€ΠΊ (%d запусків, ΠΏΠΎΡ‚ΠΎΠΊΡ–Π² ORT: %d)\n", a.bench, a.threads);
    double f = stat(tf, "mel-Ρ„Ρ€ΠΎΠ½Ρ‚Π΅Π½Π΄"), n = stat(tn, "ONNX-ΠΌΠ΅Ρ€Π΅ΠΆΠ°");
    const double hop_ms = a.hop * 1000.0 / m.sr;
    std::printf("  Π Π°Π·ΠΎΠΌ Π½Π° Π²Ρ–ΠΊΠ½ΠΎ: %.3f мс = %.2f%% ΠΊΡ€ΠΎΠΊΡƒ %.0f мс (запас Γ—%.0f)\n", f + n, (f + n) / hop_ms * 100, hop_ms, hop_ms / (f + n));
    return 0;
}

// ───────────────────────────────────────────────────────────────────────────
// Π Π΅ΠΆΠΈΠΌ Ρ„Π°ΠΉΠ»Ρƒ (ΠΏΠ΅Ρ€Π΅Π²Ρ–Ρ€ΠΊΠ° Π·Π±Ρ–Π³Ρƒ Π· Python)
// ───────────────────────────────────────────────────────────────────────────
static int run_file(const Args& a, const Meta& m, MelFrontend& fe, OnnxEngine& eng, float thr) {
    std::vector<float> x;
    if (!read_audio_file(a.wav, m.sr, x) || x.empty()) { std::fprintf(stderr, "НС вдалося ΠΏΡ€ΠΎΡ‡ΠΈΡ‚Π°Ρ‚ΠΈ %s\n", a.wav.c_str()); return 1; }
    const float g = std::pow(10.f, a.gain_db / 20.f);
    for (auto& v : x) v *= g;
    if ((int)x.size() < m.window) { std::vector<float> t; while ((int)t.size() < m.window) t.insert(t.end(), x.begin(), x.end()); t.resize(m.window); x.swap(t); }

    std::vector<int> starts;
    for (int s = 0; s + m.window <= (int)x.size(); s += a.hop) starts.push_back(s);
    if (starts.back() != (int)x.size() - m.window) starts.push_back((int)x.size() - m.window);

    Decider dec(thr, a.off_ratio, a.alpha, a.need);
    std::vector<float> mel((size_t)m.n_mels * m.frames);
    std::printf("Π€Π°ΠΉΠ»: %s, %.2f с, Π²Ρ–ΠΊΠΎΠ½: %zu, ΠΏΠΎΡ€Ρ–Π³ %.2f\n", a.wav.c_str(), x.size() / (float)m.sr, starts.size(), thr);
    for (int s : starts) {
        fe.compute(&x[s], mel.data());
        float p = eng.prob(mel, m.n_mels, m.frames);
        int ev = dec.update(p);
        std::printf("%7.2f с  p=%.4f  [%s]%s\n", s / (float)m.sr, p, bar(p).c_str(),
                    ev > 0 ? "  >>> DRONE" : ev < 0 ? "  <<< fin" : "");
    }
    return 0;
}

// ───────────────────────────────────────────────────────────────────────────
// Π Π΅ΠΆΠΈΠΌ ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½Π°
// ───────────────────────────────────────────────────────────────────────────
static int run_mic(const Args& a, const Meta& m, MelFrontend& fe, OnnxEngine& eng, float thr) {
    ma_context ctx;
    if (ma_context_init(nullptr, 0, nullptr, &ctx) != MA_SUCCESS) { std::fprintf(stderr, "ma_context_init нС вдалося\n"); return 1; }

    ma_device_info *play = nullptr, *cap = nullptr; ma_uint32 nplay = 0, ncap = 0;
    ma_context_get_devices(&ctx, &play, &nplay, &cap, &ncap);

    Ring ring(1 << 17);                                    // 131072 Π²Ρ–Π΄Π»Ρ–ΠΊΡ–Π² β‰ˆ 8 с запасу
    ma_device_config cfg = ma_device_config_init(ma_device_type_capture);
    cfg.capture.format = ma_format_f32;
    cfg.capture.channels = 1;                              // miniaudio сам Π·Π²Π΅Π΄Π΅ стСрСо β†’ ΠΌΠΎΠ½ΠΎ
    cfg.sampleRate = (ma_uint32)m.sr;                      // … Ρ– Π·Ρ€ΠΎΠ±ΠΈΡ‚ΡŒ рСсСмплінг Π΄ΠΎ 16 ΠΊΠ“Ρ†
    cfg.periodSizeInMilliseconds = 20;
    cfg.dataCallback = data_cb;
    cfg.pUserData = &ring;
    if (a.device >= 0) {
        if ((ma_uint32)a.device >= ncap) { std::fprintf(stderr, "НСмає ΠΏΡ€ΠΈΡΡ‚Ρ€ΠΎΡŽ #%d (--list)\n", a.device); return 1; }
        cfg.capture.pDeviceID = &cap[a.device].id;
    }

    ma_device dev;
    if (ma_device_init(&ctx, &cfg, &dev) != MA_SUCCESS) { std::fprintf(stderr, "НС вдалося Π²Ρ–Π΄ΠΊΡ€ΠΈΡ‚ΠΈ ΠΌΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½\n"); ma_context_uninit(&ctx); return 1; }
    if (ma_device_start(&dev) != MA_SUCCESS) { std::fprintf(stderr, "НС вдалося запустити захоплСння\n"); ma_device_uninit(&dev); ma_context_uninit(&ctx); return 1; }
    std::printf("ΠœΡ–ΠΊΡ€ΠΎΡ„ΠΎΠ½: %s | %d Π“Ρ† | ΠΏΠΎΡ€Ρ–Π³ %.2f | ΠΊΡ€ΠΎΠΊ %d Π²Ρ–Π΄Π». | gain %+.1f dB\nCtrl+C β€” Π²ΠΈΡ…Ρ–Π΄\n\n",
                dev.capture.name, m.sr, thr, a.hop, a.gain_db);

    const float g = std::pow(10.f, a.gain_db / 20.f);
    std::vector<float> win(m.window, 0.f), mel((size_t)m.n_mels * m.frames), tmp(2048);
    size_t filled = 0, since = 0;
    Decider dec(thr, a.off_ratio, a.alpha, a.need);
    const auto t0 = std::chrono::steady_clock::now();
    std::signal(SIGINT, on_sigint);

    while (g_run) {
        size_t n = ring.pop(tmp.data(), tmp.size());
        if (n == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); continue; }
        for (size_t i = 0; i < n; ++i) tmp[i] *= g;

        // зсув Π²Ρ–ΠΊΠ½Π° Ρ– дописування Π½ΠΎΠ²ΠΈΡ… Π²Ρ–Π΄Π»Ρ–ΠΊΡ–Π² Ρƒ ΠΊΡ–Π½Π΅Ρ†ΡŒ
        std::memmove(win.data(), win.data() + n, (win.size() - n) * sizeof(float));
        std::memcpy(win.data() + win.size() - n, tmp.data(), n * sizeof(float));
        filled = std::min<size_t>(win.size(), filled + n);
        since += n;
        if (filled < win.size() || since < (size_t)a.hop) continue;
        since = 0;

        const auto ti = std::chrono::steady_clock::now();
        fe.compute(win.data(), mel.data());
        const float p = eng.prob(mel, m.n_mels, m.frames);
        const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - ti).count();
        const double now = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
        const float lvl = rms_dbfs(win.data() + win.size() - a.hop, a.hop);

        const int ev = dec.update(p);
        if (ev != 0) std::printf("\r%-90s\r[%8.1f с] %s\n", "", now, ev > 0 ? ">>> Π”Π’Π˜Π“Π£Π Π’Π˜Π―Π’Π›Π•ΠΠž" : "<<< Π΄Π²ΠΈΠ³ΡƒΠ½ Π·Π½ΠΈΠΊ");
        std::printf("\r  p=%.2f  ema=%.2f  [%s]  %6.1f dBFS  %s%s", p, dec.ema(), bar(dec.ema()).c_str(), lvl,
                    dec.active() ? "Π”Π’Π˜Π“Π£Π" : "Ρ‚ΠΈΡ…ΠΎ/Ρ–Π½ΡˆΠ΅", (" " + std::to_string(ms).substr(0, 5) + " мс").c_str());
        std::fflush(stdout);
    }

    std::printf("\nΠ—Π°Π²Π΅Ρ€ΡˆΠ΅Π½Π½Ρβ€¦ (Π²Ρ‚Ρ€Π°Ρ‡Π΅Π½ΠΎ Π²Ρ–Π΄Π»Ρ–ΠΊΡ–Π²: %zu)\n", ring.dropped());
    ma_device_uninit(&dev);
    ma_context_uninit(&ctx);
    return 0;
}

int main(int argc, char** argv) {
    Args a = parse_args(argc, argv);
    try {
        if (a.list) {
            ma_context ctx; ma_context_init(nullptr, 0, nullptr, &ctx);
            ma_device_info *p, *c; ma_uint32 np, nc;
            ma_context_get_devices(&ctx, &p, &np, &c, &nc);
            std::printf("ΠŸΡ€ΠΈΡΡ‚Ρ€ΠΎΡ— захоплСння:\n");
            for (ma_uint32 i = 0; i < nc; ++i) std::printf("  [%u] %s%s\n", i, c[i].name, c[i].isDefault ? "  (Π·Π° замовчуванням)" : "");
            ma_context_uninit(&ctx);
            return 0;
        }
        Meta m;
        if (!load_meta(a.model_dir + "/engine_meta.txt", m)) { std::fprintf(stderr, "НСмає %s/engine_meta.txt\n", a.model_dir.c_str()); return 1; }
        MelFrontend fe(m, a.model_dir + "/mel_fb.f32");
        OnnxEngine eng(a.model_dir + "/engine.onnx", a.threads);
        const float thr = a.threshold >= 0.f ? a.threshold : m.threshold;
        if (a.bench > 0) return run_bench(a, m, fe, eng);
        return a.wav.empty() ? run_mic(a, m, fe, eng, thr) : run_file(a, m, fe, eng, thr);
    } catch (const std::exception& e) {
        std::fprintf(stderr, "Помилка: %s\n", e.what());
        return 1;
    }
}