Add bounded shared audio history and time weighted histogram snapshots

This commit is contained in:
evgeny committed 2026-10-30 21:11:05 +01:00
1 parent bef7b2ffac
commit c6c4b72487
2 files changed
+95

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
/* Снимок диагностики звонка за 30с. RX — запас Opus+DSP до выдачи PCM устройству;
* TX — все логические Router-очереди ядра плюс ожидающее аудио этого звонка.
* Нижний транспорт показан отдельно: его копии уже входят в Router inflight.
* Все времена — get_time_us()/1000. UI только читает, скрытие графика не останавливает сбор.
* Гистограмма описывает запас RX, не одностороннюю задержку сети. Старые интервалы
* имеют вес exp2(-возраст/10с). Это наблюдение; алгоритм воспроизведения оно не меняет. */
#ifndef CALL_AUDIO_HISTORY_H
#define CALL_AUDIO_HISTORY_H
#include <stdint.h>
#define CALL_HISTORY_MS 30000
#define CALL_HISTORY_STEP_MS 50
#define CALL_HISTORY_POINTS (CALL_HISTORY_MS / CALL_HISTORY_STEP_MS + 1)
#define CALL_HISTORY_BIN_MS 50
#define CALL_HISTORY_BINS 61 /* 0..2999мс, последний столбец >=3000мс. */
struct call_history_rx {
uint64_t at_ms; /* Монотонная отметка последнего измерения интервала. */
int depth_ms, reserve_ms, tempo_x100;
int low_ms, high_ms; /* Экстремумы внутри 50мс: короткий провал не исчезает при укрупнении графика. */
unsigned rendered_samples, missing_samples; /* После первого звука; начальное накопление сюда не входит. */
};
struct call_history_tx {
uint64_t at_ms, queued_bytes, inflight_bytes, transport_bytes;
};
struct call_audio_history {
uint64_t now_ms;
unsigned rx_count, tx_count;
struct call_history_rx rx[CALL_HISTORY_POINTS]; /* По возрастанию времени, только последние 30с. */
struct call_history_tx tx[CALL_HISTORY_POINTS];
double histogram[CALL_HISTORY_BINS]; /* Доли времени 0..1, с учётом давности. */
double observed_ms, missing_ms; /* Взвешенные длительности наблюдения и недостающего PCM. */
};
#endif
+63
View File
@@ -0,0 +1,63 @@
/* Ограниченная история диагностики; владелец сериализует все обращения своим mutex.
* В hot path нет аллокаций. Гистограмма учитывает длительность каждого выданного
* блока, а не число pull/пакетов. Возраст укрупняется до 50мс; окна интерфейса не владеют историей. */
#pragma once
#include "call_audio_history.h"
#include "../../lib/debug_config.h"
#include <algorithm>
#include <cmath>
class CallHistoryStore {
struct RxBucket { call_history_rx point{}; unsigned bins[CALL_HISTORY_BINS]{}; };
RxBucket rx[CALL_HISTORY_POINTS]{};
call_history_tx tx[CALL_HISTORY_POINTS]{};
unsigned rxNext = 0, txNext = 0, rxUsed = 0, txUsed = 0;
public:
// samples/missing — PCM на выходной шкале; до первого звука samples=0, но график глубины продолжается.
void receive(uint64_t now, int depth, int reserve, int tempo, unsigned samples, unsigned missing) {
unsigned index = (rxNext + CALL_HISTORY_POINTS - 1) % CALL_HISTORY_POINTS;
if (rxUsed && now < rx[index].point.at_ms) {
DEBUG_WARN(DEBUG_CATEGORY_CALL, "audio history RX clock regressed"); return;
}
if (!rxUsed || now / CALL_HISTORY_STEP_MS != rx[index].point.at_ms / CALL_HISTORY_STEP_MS) {
index = rxNext; rxNext = (rxNext + 1) % CALL_HISTORY_POINTS;
rxUsed = std::min(rxUsed + 1, (unsigned)CALL_HISTORY_POINTS); rx[index] = {};
rx[index].point.low_ms = rx[index].point.high_ms = depth;
}
auto& b = rx[index]; auto& p = b.point;
p.at_ms = now; p.depth_ms = depth; p.reserve_ms = reserve; p.tempo_x100 = tempo;
p.low_ms = std::min(p.low_ms, depth); p.high_ms = std::max(p.high_ms, depth);
p.rendered_samples += samples; p.missing_samples += std::min(samples, missing);
b.bins[std::min(CALL_HISTORY_BINS - 1, std::max(0, depth) / CALL_HISTORY_BIN_MS)] += samples;
}
// Все значения принадлежат одному снимку uasync; никаких чтений живых очередей из UI.
void transmit(const call_history_tx& p) {
unsigned index = (txNext + CALL_HISTORY_POINTS - 1) % CALL_HISTORY_POINTS;
if (txUsed && p.at_ms < tx[index].at_ms) {
DEBUG_WARN(DEBUG_CATEGORY_CALL, "audio history TX clock regressed"); return;
}
if (!txUsed || p.at_ms / CALL_HISTORY_STEP_MS != tx[index].at_ms / CALL_HISTORY_STEP_MS) {
index = txNext; txNext = (txNext + 1) % CALL_HISTORY_POINTS;
txUsed = std::min(txUsed + 1, (unsigned)CALL_HISTORY_POINTS);
}
tx[index] = p;
}
// out — независимая копия. Пустые/старые участки не интерполируются и не становятся нулевыми измерениями.
void snapshot(uint64_t now, call_audio_history& out) const {
out = {}; out.now_ms = now;
for (unsigned i = 0; i < rxUsed; ++i) {
const auto& b = rx[(rxNext + CALL_HISTORY_POINTS - rxUsed + i) % CALL_HISTORY_POINTS];
if (b.point.at_ms > now || now - b.point.at_ms >= CALL_HISTORY_MS) continue;
out.rx[out.rx_count++] = b.point;
double weight = std::exp2(-(double)(now - b.point.at_ms) / 10000.0) / 48.0;
out.observed_ms += b.point.rendered_samples * weight;
out.missing_ms += b.point.missing_samples * weight;
for (unsigned k = 0; k < CALL_HISTORY_BINS; ++k) out.histogram[k] += b.bins[k] * weight;
}
if (out.observed_ms > 0) for (auto& value : out.histogram) value /= out.observed_ms;
for (unsigned i = 0; i < txUsed; ++i) {
const auto& p = tx[(txNext + CALL_HISTORY_POINTS - txUsed + i) % CALL_HISTORY_POINTS];
if (p.at_ms <= now && now - p.at_ms < CALL_HISTORY_MS) out.tx[out.tx_count++] = p;
}
}
};