Add configurable Opus burst batches for radio transmission
This commit is contained in:
1 parent
5f3a3fe93c
commit
2aed90a7a6
21 files changed
+417
-46
No files matched your search
@@ -0,0 +1,51 @@
|
||||
Пачки Opus в рации
|
||||
=================
|
||||
|
||||
Настройка radio_burst_frames в [chatserver]: 1..10, по умолчанию4.
|
||||
Desktop: Настройки → Рация → Размер burst-пачки (кадров Opus).
|
||||
Android: Настройки → Рация → Opus → Размер burst-пачки (кадров Opus).
|
||||
Значение сохраняется в настройках приложения и фиксируется ядром при следующем
|
||||
radio_talk_begin — для ручной PTT, VAD, передачи по уровню и headless одинаково.
|
||||
Изменение только размера пачки не перезапускает захват desktop/Android.
|
||||
|
||||
Входной API по-прежнему принимает один Opus-кадр; uasync-контекст группы собирает
|
||||
до заданного числа кадров. Полная пачка отправляется сразу. При END сначала
|
||||
уходит неполный хвост DATA, затем отдельный FIN. Повторный BEGIN закрывает прежнюю
|
||||
передачу с её хвостом и FIN. Отправка после END не переоткрывает передачу.
|
||||
Если захват остановился без END, хвост уходит не позже target*20мс от первого
|
||||
кадра (плюс задержка планировщика). Новые кадры не продлевают этот deadline.
|
||||
Destroy отменяет таймер и логирует отброшенный хвост.
|
||||
|
||||
Кадр20мс: при регулярном захвате накопление первой полной пачки добавляет
|
||||
(N-1)*20мс, то есть60мс для4 и180мс для10. Это не ограничение полной задержки
|
||||
сети/воспроизведения. Размер не адаптивный: задаётся пользователем.
|
||||
|
||||
Wire после ETCP_ID_RADIO:
|
||||
group_id:u64, src_node_id:u64, stream_id:u16, seq:u16,
|
||||
flags:u8, hop_count:u8, count:u8, hop_list:u64[hop_count],
|
||||
затем count записей length:u16 + opus[length].
|
||||
Порядок байтов чисел хоста, как в прежнем протоколе рации.
|
||||
Заголовок23 байта без hop_list. DATA: flags=0, count1..10, length1..512.
|
||||
FIN: flags=1, count0, без тела. Остальные flags/хвостовые байты запрещены.
|
||||
seq — номер первого кадра пачки; следующий кадр увеличивает seq по модулю65536.
|
||||
FIN использует следующий seq после последнего кадра. Приёмник полностью
|
||||
проверяет пачку до выдачи первого кадра и изменения кэша дедупликации.
|
||||
Callback аудио по-прежнему получает отдельные кадры с последовательными seq.
|
||||
FIN передаётся отдельным callback с opus=NULL/len0.
|
||||
|
||||
Промежуточный узел дописывает hop, сохраняя границы пачки и тело. Дедупликация
|
||||
по (src,stream,seq) работает на уровне пачек; повтор не выдаёт кадры повторно.
|
||||
Максимальный пакет с16hops: 1+23+128+10*(2+512)=5292 байта, меньше лимита
|
||||
кодограммы normalizer16384; фрагментация остаётся в существующем транспорте.
|
||||
Совместимость со старым форматом отсутствует: обновить отправителей,
|
||||
получателей и транзитные узлы рации.
|
||||
|
||||
radio=info: BEGIN с target/deadline, обычная статистика отправки/завершения.
|
||||
radio=debug: TX/RX каждой пачки, stream/seq/count/bytes, причина full/end/deadline.
|
||||
Неверные пакеты, отказ таймера и уничтожение с непереданным хвостом логируются.
|
||||
|
||||
Проверки: test_radio_batch (1..10, максимальные кадры, неизменный target внутри
|
||||
передачи, частичный END, FIN, дубли, повреждённые пакеты, deadline и teardown),
|
||||
test_radio_mesh (передача пачек по разным путям), test_chat_setting (границы),
|
||||
test_radio_panel (редактор, сохранение/повторное чтение и отсутствие перезапуска
|
||||
захвата при изменении только пачки), прежние radio/headless/audio-проверки.
|
||||
@@ -4,6 +4,35 @@
|
||||
|
||||
## Текущие задачи
|
||||
|
||||
[ ] **Нестабильность общего check: STUN/stream/member_files timeout и media_async latency** — 30.10.2026.
|
||||
При проверке radio burst первый прогон прошёл эти4 теста: STUN69,073с, stream80,069с,
|
||||
member_files45,859с, media_async2,008с. Повторный прогон:228/232 PASS; первые3 превысили90с,
|
||||
media_async сделал41378 операций без ошибок, но UUID max9,093мс превысил порог5мс.
|
||||
В STUN логе многократные event-loop stalls1–2,5с, в stream stall56,650с и задержка CPU sample21,064с.
|
||||
member_files остановился после Busy для REMOVE bulk_47: receipts full, retry_after111,173с.
|
||||
Причина пауз не установлена; ошибки находятся вне изменённых путей рации, весь radio-набор проходит.
|
||||
Пользователь подтвердил подвисание всей системы в это время. check использовал20 параллельных тестов.
|
||||
После эпизода (17:34:50): RAM30GiB/available9,6GiB, /tmp на tmpfs занимает13GiB,
|
||||
swap511MiB заполнен; Gradle/Kotlin daemons RSS3,5+2,14GB. PSI memory full avg300=2,76%, IO full=5,90%.
|
||||
В kernel journal warning+ нет OOM/GPU reset/lockup за последние25мин; эти данные указывают на ресурсные
|
||||
задержки, но не доказывают конкретную первопричину. Повторные проверки выполняются по одному.
|
||||
Логи: tests/logs/test_{stun_nat,stream_service,member_files_network,media_async}.log;
|
||||
сводки /tmp/radio-burst-check{,-final}.log. Последовательный повтор без повышения таймаутов/порогов:
|
||||
STUN66,643с, stream88,957с, member_files43,098с, media_async2,008с —4/4 PASS;
|
||||
логи /tmp/radio-burst-recheck/. Нужна отдельная диагностика ресурсных пауз; полные прогоны ограничивать jobs1–2.
|
||||
|
||||
[+] **Рация: настраиваемые burst-пачки Opus 1..10, по умолчанию4** — 30.10.2026.
|
||||
`radio_burst_frames` сохраняется desktop/Android и читается при следующем PTT/VAD BEGIN, общий для headless.
|
||||
Новый wire: общий header23, count, length:u16 перед каждым кадром. Приём валидирует всю пачку до доставки;
|
||||
пересылка сохраняет её границы, дедупликация по первому seq, аудио получает отдельные последовательные кадры.
|
||||
Неполный хвост уходит перед FIN либо по deadline N*20мс; teardown отменяет таймер.
|
||||
Изменение только burst не перезапускает захват. Добавлены RU/EN подписи и логи target/count/seq/причины отправки.
|
||||
Ядро, desktop GUI и Android APK собраны; Android unit и4 desktop voice/UI-теста PASS.
|
||||
test_radio_batch проверяет1..10, максимальный Opus, хвост/FIN, malformed, дубли, deadline и отсутствие утечек;
|
||||
radio/mesh/headless и сохранение/повторное чтение настройки PASS. A52 отключён от ADB, новый APK не установлен.
|
||||
Общий прогон228/232; оставшиеся4 теста прошли последовательный повтор (см. задачу о системных паузах выше).
|
||||
Формат требует обновления участников и транзитных узлов. Контракт: [radio_burst.txt](radio_burst.txt).
|
||||
|
||||
[+] **Звонок: адаптивные пачки Opus 1..10 по полному времени Router enqueue→ACK** — 30.10.2026.
|
||||
`call_audio_batch` объединяет кадры в одну подписанную/зашифрованную Router-кодограмму; общий CALL header27,
|
||||
описание кадра12 байт. seq/PTS сохраняются, capture epoch/codec delay общие; count1..10, пакет до1024 байт.
|
||||
|
||||
@@ -41,6 +41,7 @@ static const struct chat_setting_def g_setting_defs[] = {
|
||||
{"opus_codec_preset", CHAT_SETTING_INT, 1, 0, 2},
|
||||
{"radio_opus_mode", CHAT_SETTING_INT, 0, 0, 1},
|
||||
{"radio_opus_bitrate", CHAT_SETTING_INT, 32, 16, 128},
|
||||
{"radio_burst_frames", CHAT_SETTING_INT, 4, 1, 10}, /* Opus-кадров в пакете; со следующего PTT/VAD BEGIN. */
|
||||
{"radio_capture_stereo", CHAT_SETTING_INT, 0, 0, 1},
|
||||
{"compressor_enabled", CHAT_SETTING_BOOL, 1, 0, 1},
|
||||
{"compressor_max_gain_db", CHAT_SETTING_INT, 15, 1, 60},
|
||||
|
||||
+94
-25
@@ -24,6 +24,7 @@
|
||||
#include "../routing_layer/topo_group.h"
|
||||
#include "../routing_layer/topo_node_sqlite.h"
|
||||
#include "../chat/chat_event.h"
|
||||
#include "../chat/chat_setting.h"
|
||||
#include "../stream/stream.h"
|
||||
#include "radio.h"
|
||||
#include "radio_proto.h"
|
||||
@@ -49,9 +50,13 @@ struct radio_ctx {
|
||||
uint16_t stream_id; /* id текущей передачи (talk-burst) */
|
||||
uint16_t seq; /* seq следующего исходящего кадра */
|
||||
int talking; /* 1 = идёт передача (PTT зажата) */
|
||||
uint8_t burst_target, burst_count; /* Настройка текущей передачи и число накопленных кадров. */
|
||||
uint8_t burst_body[RADIO_MAX_BODY]; /* Записи length:u16 + Opus, принадлежат uasync. */
|
||||
size_t burst_bytes; /* Занятый префикс burst_body. */
|
||||
void* burst_timer; /* Deadline неполной пачки; отменяется до освобождения ctx. */
|
||||
uint32_t c_tx_frames; /* отправлено кадров */
|
||||
uint32_t c_rx_frames; /* доставлено локально (мы подписаны) */
|
||||
uint32_t c_fwd_frames; /* форварднуто кадров */
|
||||
uint32_t c_fwd_frames; /* отправлено пачек соседям (DATA/FIN) */
|
||||
uint32_t c_loop_dropped; /* дропнуто из-за цикла (self в hop_list) */
|
||||
uint32_t c_nosub_dropped; /* не отправлено: за соседом нет подписчиков */
|
||||
uint32_t c_bad_dropped; /* дропнуто некорректных пакетов */
|
||||
@@ -104,6 +109,9 @@ int radio_init(struct TOPO_GROUP* group) {
|
||||
void radio_destroy(struct TOPO_GROUP* group) {
|
||||
if (!group || !group->radio) return;
|
||||
struct radio_ctx* ctx = group->radio;
|
||||
if (ctx->burst_timer) uasync_cancel_timeout(group->instance->ua, ctx->burst_timer);
|
||||
if (ctx->burst_count) DEBUG_WARN(DEBUG_CATEGORY_RADIO, "radio: destroy discards pending batch group=%llx frames=%u",
|
||||
(unsigned long long)group->group_id, ctx->burst_count);
|
||||
if (ctx->talker_timer) { uasync_cancel_timeout(group->instance->ua, ctx->talker_timer); ctx->talker_timer = NULL; }
|
||||
DEBUG_INFO(DEBUG_CATEGORY_RADIO, "%s: destroy grp=%016llx (tx=%u rx=%u fwd=%u loop=%u nosub=%u bad=%u dup=%u)",
|
||||
RADIO_ID, (unsigned long long)group->group_id,
|
||||
@@ -119,7 +127,7 @@ void radio_destroy(struct TOPO_GROUP* group) {
|
||||
/* Пишет payload рации (начиная с group_id) в buf, возвращает длину. */
|
||||
static size_t radio_build(uint8_t* buf, uint64_t group_id, uint64_t src, uint16_t stream,
|
||||
uint16_t seq, uint8_t flags, const uint64_t* hops, uint8_t hop_count,
|
||||
const uint8_t* opus, int opus_len) {
|
||||
uint8_t count, const uint8_t* body, size_t body_len) {
|
||||
size_t off = 0;
|
||||
memcpy(buf + off, &group_id, 8); off += 8;
|
||||
memcpy(buf + off, &src, 8); off += 8;
|
||||
@@ -127,8 +135,9 @@ static size_t radio_build(uint8_t* buf, uint64_t group_id, uint64_t src, uint16_
|
||||
memcpy(buf + off, &seq, 2); off += 2;
|
||||
buf[off++] = flags;
|
||||
buf[off++] = hop_count;
|
||||
buf[off++] = count;
|
||||
if (hop_count) { memcpy(buf + off, hops, (size_t)hop_count * 8); off += (size_t)hop_count * 8; }
|
||||
if (opus_len > 0) { memcpy(buf + off, opus, (size_t)opus_len); off += (size_t)opus_len; }
|
||||
if (body_len) { memcpy(buf + off, body, body_len); off += body_len; }
|
||||
return off;
|
||||
}
|
||||
|
||||
@@ -335,7 +344,7 @@ static void radio_recv(struct TOPO_GROUP* group, struct ETCP_CONN* from_conn,
|
||||
flags = p[RADIO_OFF_FLAGS];
|
||||
hop_count = p[RADIO_OFF_HOPS];
|
||||
|
||||
if (group_id != group->group_id || hop_count > RADIO_MAX_HOPS
|
||||
if (group_id != group->group_id || !hop_count || hop_count > RADIO_MAX_HOPS
|
||||
|| payload_len < RADIO_HDR_SIZE + (size_t)hop_count * 8) {
|
||||
ctx->c_bad_dropped++;
|
||||
DEBUG_WARN(DEBUG_CATEGORY_RADIO, "%s: bad pkt grp=%016llx hops=%u len=%zu from=%s",
|
||||
@@ -344,9 +353,22 @@ static void radio_recv(struct TOPO_GROUP* group, struct ETCP_CONN* from_conn,
|
||||
}
|
||||
uint64_t hops[RADIO_MAX_HOPS]; // wire hop-list может начинаться с невыровненного адреса
|
||||
memcpy(hops, p + RADIO_OFF_HOPLIST, (size_t)hop_count * sizeof(hops[0]));
|
||||
const uint8_t* opus = p + RADIO_OFF_HOPLIST + (size_t)hop_count * 8;
|
||||
int opus_len = (int)(payload_len - RADIO_OFF_HOPLIST - (size_t)hop_count * 8);
|
||||
if (opus_len > RADIO_MAX_OPUS) { ctx->c_bad_dropped++; return; }
|
||||
const uint8_t* body = p + RADIO_OFF_HOPLIST + (size_t)hop_count * 8;
|
||||
size_t body_len = payload_len - RADIO_OFF_HOPLIST - (size_t)hop_count * 8;
|
||||
uint8_t count = p[RADIO_OFF_COUNT];
|
||||
const uint8_t* frames[RADIO_MAX_BURST];
|
||||
uint16_t lengths[RADIO_MAX_BURST];
|
||||
size_t offset = 0;
|
||||
/* Проверить всю пачку до изменения дедупликации, индикации и выдачи первого кадра. */
|
||||
if ((flags == RADIO_FLAG_FIN && (count || body_len))
|
||||
|| (flags != RADIO_FLAG_FIN && (flags || !count || count > RADIO_MAX_BURST))) goto malformed;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
if (body_len - offset < 2) goto malformed;
|
||||
memcpy(&lengths[i], body + offset, 2); offset += 2;
|
||||
if (!lengths[i] || lengths[i] > RADIO_MAX_OPUS || lengths[i] > body_len - offset) goto malformed;
|
||||
frames[i] = body + offset; offset += lengths[i];
|
||||
}
|
||||
if (offset != body_len) goto malformed;
|
||||
|
||||
uint64_t self = group->instance->node_id;
|
||||
|
||||
@@ -368,18 +390,21 @@ static void radio_recv(struct TOPO_GROUP* group, struct ETCP_CONN* from_conn,
|
||||
|
||||
/* начало передачи (первый кадр burst): видно и на транзитных узлах (коло), не только у подписчиков */
|
||||
if (seq == 0) {
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_RADIO, "%s: recv burst src=%016llx stream=%u fin=%u len=%d sub=%d",
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_RADIO, "%s: recv burst src=%016llx stream=%u fin=%u bytes=%zu sub=%d",
|
||||
RADIO_ID, (unsigned long long)src, stream, (flags & RADIO_FLAG_FIN) ? 1 : 0,
|
||||
opus_len, group->radio_active ? 1 : 0);
|
||||
body_len, group->radio_active ? 1 : 0);
|
||||
}
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_RADIO, "radio: RX batch src=%llx stream=%u seq=%u count=%u bytes=%zu fin=%u",
|
||||
(unsigned long long)src, stream, seq, count, body_len, flags);
|
||||
|
||||
/* доставка локально, если мы подписаны */
|
||||
if (group->radio_active && ctx->group) {
|
||||
struct radio_instance* ri = radio_inst(group->instance);
|
||||
if (ri && ri->frame_fn) {
|
||||
ri->frame_fn(group->instance, group_id, src, stream, seq,
|
||||
(flags & RADIO_FLAG_FIN) ? 1 : 0, opus, opus_len, ri->frame_arg);
|
||||
ctx->c_rx_frames++;
|
||||
for (unsigned i = 0; i < count; i++)
|
||||
ri->frame_fn(group->instance, group_id, src, stream, (uint16_t)(seq + i), 0, frames[i], lengths[i], ri->frame_arg);
|
||||
if (flags & RADIO_FLAG_FIN) ri->frame_fn(group->instance, group_id, src, stream, seq, 1, NULL, 0, ri->frame_arg);
|
||||
ctx->c_rx_frames += count + !!(flags & RADIO_FLAG_FIN);
|
||||
}
|
||||
/* индикация говорящих: старт/стоп передачи */
|
||||
if (flags & RADIO_FLAG_FIN) radio_talker_off(ctx, src);
|
||||
@@ -396,13 +421,19 @@ static void radio_recv(struct TOPO_GROUP* group, struct ETCP_CONN* from_conn,
|
||||
memcpy(new_hops, hops, (size_t)hop_count * 8);
|
||||
new_hops[hop_count] = self;
|
||||
|
||||
uint8_t out[RADIO_HDR_SIZE + RADIO_MAX_HOPS * 8 + RADIO_MAX_OPUS];
|
||||
size_t out_len = radio_build(out, group_id, src, stream, seq, flags, new_hops, new_count, opus, opus_len);
|
||||
uint8_t out[RADIO_HDR_SIZE + RADIO_MAX_HOPS * 8 + RADIO_MAX_BODY];
|
||||
size_t out_len = radio_build(out, group_id, src, stream, seq, flags, new_hops, new_count, count, body, body_len);
|
||||
radio_flood(group, from_conn, out, out_len, new_hops, new_count);
|
||||
return;
|
||||
malformed:
|
||||
ctx->c_bad_dropped++;
|
||||
DEBUG_WARN(DEBUG_CATEGORY_RADIO, "radio: malformed batch src=%llx stream=%u seq=%u flags=%u count=%u bytes=%zu offset=%zu",
|
||||
(unsigned long long)src, stream, seq, flags, count, body_len, offset);
|
||||
}
|
||||
|
||||
static void radio_recv_dispatcher(struct ETCP_CONN* from_conn, struct ll_entry* entry) {
|
||||
if (!from_conn || !entry || entry->len < 1 + 8 + RADIO_HDR_SIZE) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_RADIO, "radio: invalid receive entry bytes=%zu", entry ? (size_t)entry->len : 0);
|
||||
if (entry) { queue_dgram_free(entry); queue_entry_free(entry); }
|
||||
return;
|
||||
}
|
||||
@@ -621,25 +652,56 @@ uint32_t radio_dup_dropped(struct UTUN_INSTANCE* inst, uint64_t group_id) {
|
||||
|
||||
/* ── передача (PTT) ── */
|
||||
|
||||
/* Отправить накопленные кадры одной кодограммой; новый кадр не продлевает deadline. */
|
||||
static void radio_flush(struct radio_ctx* ctx, const char* reason) {
|
||||
if (ctx->burst_timer) {
|
||||
uasync_cancel_timeout(ctx->group->instance->ua, ctx->burst_timer); ctx->burst_timer = NULL;
|
||||
}
|
||||
if (!ctx->burst_count) return;
|
||||
uint64_t self = ctx->group->instance->node_id;
|
||||
uint8_t out[RADIO_HDR_SIZE + 8 + RADIO_MAX_BODY];
|
||||
uint16_t first_seq = (uint16_t)(ctx->seq - ctx->burst_count);
|
||||
size_t len = radio_build(out, ctx->group->group_id, self, ctx->stream_id, first_seq, 0, &self, 1,
|
||||
ctx->burst_count, ctx->burst_body, ctx->burst_bytes);
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_RADIO, "radio: TX batch group=%llx stream=%u seq=%u count=%u bytes=%zu reason=%s",
|
||||
(unsigned long long)ctx->group->group_id, ctx->stream_id, first_seq, ctx->burst_count, len, reason);
|
||||
ctx->burst_count = 0; ctx->burst_bytes = 0;
|
||||
radio_flood(ctx->group, NULL, out, len, &self, 1);
|
||||
}
|
||||
|
||||
/* Кадры перестали поступать: отправить хвост, не дожидаясь END. */
|
||||
static void radio_burst_timeout(void* arg) {
|
||||
struct radio_ctx* ctx = arg;
|
||||
ctx->burst_timer = NULL;
|
||||
radio_flush(ctx, "deadline");
|
||||
}
|
||||
|
||||
int radio_talk_begin(struct UTUN_INSTANCE* inst, uint64_t group_id) {
|
||||
if (!inst || !inst->topo_groups) return -1;
|
||||
struct TOPO_GROUP* group = topo_groups_find(inst->topo_groups, group_id);
|
||||
if (!group) { DEBUG_WARN(DEBUG_CATEGORY_RADIO, "%s: talk_begin group 0x%016llx not found", RADIO_ID, (unsigned long long)group_id); return -1; }
|
||||
struct radio_ctx* ctx = radio_of(group);
|
||||
if (!ctx) return -1;
|
||||
if (ctx->talking) {
|
||||
DEBUG_WARN(DEBUG_CATEGORY_RADIO, "radio: BEGIN closes unfinished stream=%u", ctx->stream_id);
|
||||
radio_talk_end(inst, group_id);
|
||||
}
|
||||
ctx->stream_id = (uint16_t)(ctx->stream_id + 1);
|
||||
ctx->seq = 0;
|
||||
ctx->talking = 1;
|
||||
DEBUG_DEBUG(DEBUG_CATEGORY_RADIO, "%s: talk_begin grp=%016llx stream=%u", RADIO_ID, (unsigned long long)group_id, ctx->stream_id);
|
||||
ctx->burst_target = (uint8_t)chat_setting_get_int(inst, "radio_burst_frames", 4);
|
||||
DEBUG_INFO(DEBUG_CATEGORY_RADIO, "%s: talk_begin grp=%016llx stream=%u burst_frames=%u deadline_ms=%u",
|
||||
RADIO_ID, (unsigned long long)group_id, ctx->stream_id, ctx->burst_target, ctx->burst_target * 20);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int radio_talk_send(struct UTUN_INSTANCE* inst, uint64_t group_id, const uint8_t* opus, int len) {
|
||||
if (!inst || !inst->topo_groups || !opus || len < 0 || len > RADIO_MAX_OPUS) return -1;
|
||||
if (!inst || !inst->topo_groups || !opus || len <= 0 || len > RADIO_MAX_OPUS) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_RADIO, "radio: invalid send frame len=%d", len); return -1;
|
||||
}
|
||||
struct TOPO_GROUP* group = topo_groups_find(inst->topo_groups, group_id);
|
||||
if (!group) return -1;
|
||||
struct radio_ctx* ctx = radio_of(group);
|
||||
if (!ctx) return -1;
|
||||
if (!ctx) { DEBUG_ERROR(DEBUG_CATEGORY_RADIO, "radio: send group unavailable group=%llx", (unsigned long long)group_id); return -1; }
|
||||
if (!ctx->talking) {
|
||||
/* burst не открыт: хвостовой кадр, пришедший после radio_talk_end (гонка релиза PTT) —
|
||||
* не переоткрываем передачу, иначе получится burst без FIN и «говорит» зависнет у пиров. */
|
||||
@@ -647,14 +709,20 @@ int radio_talk_send(struct UTUN_INSTANCE* inst, uint64_t group_id, const uint8_t
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint64_t self = inst->node_id;
|
||||
uint64_t hops[1] = { self };
|
||||
uint8_t out[RADIO_HDR_SIZE + 8 + RADIO_MAX_OPUS];
|
||||
size_t out_len = radio_build(out, group_id, self, ctx->stream_id, ctx->seq, 0, hops, 1, opus, len);
|
||||
uint16_t size = (uint16_t)len;
|
||||
memcpy(ctx->burst_body + ctx->burst_bytes, &size, 2); ctx->burst_bytes += 2;
|
||||
memcpy(ctx->burst_body + ctx->burst_bytes, opus, (size_t)len); ctx->burst_bytes += (size_t)len;
|
||||
ctx->burst_count++;
|
||||
ctx->seq++;
|
||||
ctx->c_tx_frames++;
|
||||
|
||||
radio_flood(group, NULL, out, out_len, hops, 1);
|
||||
if (ctx->burst_count == ctx->burst_target) radio_flush(ctx, "full");
|
||||
else if (!ctx->burst_timer) {
|
||||
ctx->burst_timer = uasync_set_timeout(inst->ua, ctx->burst_target * 200, ctx, radio_burst_timeout, "radio_burst");
|
||||
if (!ctx->burst_timer) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_RADIO, "radio: batch timer allocation failed; flushing frames=%u", ctx->burst_count);
|
||||
radio_flush(ctx, "timer_failed");
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -666,11 +734,12 @@ int radio_talk_end(struct UTUN_INSTANCE* inst, uint64_t group_id) {
|
||||
if (!ctx) return -1;
|
||||
if (!ctx->talking) return 0;
|
||||
|
||||
radio_flush(ctx, "end");
|
||||
uint64_t self = inst->node_id;
|
||||
uint64_t hops[1] = { self };
|
||||
uint8_t out[RADIO_HDR_SIZE + 8];
|
||||
size_t out_len = radio_build(out, group_id, self, ctx->stream_id, ctx->seq,
|
||||
RADIO_FLAG_FIN, hops, 1, NULL, 0);
|
||||
RADIO_FLAG_FIN, hops, 1, 0, NULL, 0);
|
||||
ctx->seq++;
|
||||
ctx->c_tx_frames++;
|
||||
ctx->talking = 0;
|
||||
|
||||
+6
-1
@@ -28,6 +28,8 @@ void radio_destroy_instance(struct UTUN_INSTANCE* inst); /* etcp_unbind */
|
||||
|
||||
/* ── приём Opus-кадра пира (для аудио-движка radio_audio) ── */
|
||||
|
||||
/* После проверки всей пачки вызывается для каждого кадра; Opus заимствован до возврата.
|
||||
* fin=1 приходит отдельно с opus=NULL, len=0 и seq после последнего кадра. */
|
||||
typedef void (*radio_frame_fn)(struct UTUN_INSTANCE* inst, uint64_t group_id,
|
||||
uint64_t src_node_id, uint16_t stream_id, uint16_t seq,
|
||||
uint8_t fin, const uint8_t* opus, int len, void* arg);
|
||||
@@ -53,8 +55,11 @@ void radio_set_mute_cb(struct UTUN_INSTANCE* inst, radio_mute_fn fn, void* arg);
|
||||
/* ── передача (PTT), uasync-поток ── */
|
||||
|
||||
int radio_talk_begin(struct UTUN_INSTANCE* inst, uint64_t group_id); /* новая передача, seq=0 */
|
||||
/* Копирует один Opus-кадр (1..512 байт); собирает radio_burst_frames (1..10, default4).
|
||||
* Настройка фиксируется при BEGIN. Неполная пачка уходит при END или через target*20мс от первого кадра.
|
||||
* 0 — принят/устаревший хвост после END проигнорирован, -1 — неверные аргументы/нет группы. */
|
||||
int radio_talk_send(struct UTUN_INSTANCE* inst, uint64_t group_id, const uint8_t* opus, int len);
|
||||
int radio_talk_end(struct UTUN_INSTANCE* inst, uint64_t group_id); /* FIN-кадр */
|
||||
int radio_talk_end(struct UTUN_INSTANCE* inst, uint64_t group_id); /* Сначала хвост DATA, затем отдельный FIN. */
|
||||
|
||||
/* Включить/выключить прослушивание рации канала (флаг + BGP-рассылка). */
|
||||
void radio_set_active(struct UTUN_INSTANCE* inst, uint64_t group_id, int on);
|
||||
|
||||
+10
-6
@@ -5,10 +5,11 @@
|
||||
// RPF-обрезанием ветвей без подписчиков (узел с radio==1 в NODEINFO).
|
||||
//
|
||||
// Формат payload (после dgram[0] = ETCP_ID_RADIO):
|
||||
// [group_id:8][src_node_id:8][stream_id:2][seq:2][flags:1][hop_count:1]
|
||||
// [hop_list:8*hop_count][opus...]
|
||||
// flags: bit0 = FIN (последний кадр передачи)
|
||||
// stream_id — случайный идентификатор передачи (talk-burst), seq нумерует кадры от 0.
|
||||
// [group_id:8][src_node_id:8][stream_id:2][seq:2][flags:1][hop_count:1][count:1]
|
||||
// [hop_list:8*hop_count] затем count раз [length:2][opus:length]. Числа в порядке байтов хоста.
|
||||
// DATA: flags=0, count=1..10; FIN: flags=1, count=0, без тела, после отправки хвоста DATA.
|
||||
// stream_id — идентификатор передачи, seq — номер первого кадра пачки; каждый кадр увеличивает seq.
|
||||
// FIN использует следующий seq. Пересылка не меняет границы пачек; дедупликация по (src,stream,seq).
|
||||
#ifndef RADIO_PROTO_H
|
||||
#define RADIO_PROTO_H
|
||||
|
||||
@@ -22,8 +23,10 @@ extern "C" {
|
||||
|
||||
#define RADIO_MAX_HOPS 16
|
||||
#define RADIO_MAX_OPUS 512 /* макс. Opus-кадр (стерео 128кбит/с 20мс = 320 байт + запас) */
|
||||
#define RADIO_MAX_BURST 10
|
||||
#define RADIO_MAX_BODY (RADIO_MAX_BURST * (2 + RADIO_MAX_OPUS))
|
||||
|
||||
#define RADIO_HDR_SIZE 22 /* group(8)+src(8)+stream(2)+seq(2)+flags(1)+hop_count(1), без hop_list */
|
||||
#define RADIO_HDR_SIZE 23 /* group(8)+src(8)+stream(2)+seq(2)+flags(1)+hop_count(1)+count(1), без hop_list */
|
||||
|
||||
#define RADIO_OFF_GROUP 0
|
||||
#define RADIO_OFF_SRC 8
|
||||
@@ -31,7 +34,8 @@ extern "C" {
|
||||
#define RADIO_OFF_SEQ 18
|
||||
#define RADIO_OFF_FLAGS 20
|
||||
#define RADIO_OFF_HOPS 21
|
||||
#define RADIO_OFF_HOPLIST 22
|
||||
#define RADIO_OFF_COUNT 22
|
||||
#define RADIO_OFF_HOPLIST 23
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
||||
@@ -160,6 +160,7 @@ check_PROGRAMS += \
|
||||
test_ipv6_sockets \
|
||||
test_radio_headless \
|
||||
test_radio_mesh \
|
||||
test_radio_batch \
|
||||
test_nat_stress \
|
||||
test_stcp \
|
||||
test_call_headless \
|
||||
@@ -1127,6 +1128,10 @@ test_radio_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/src/chat -I$(top_srcdir)
|
||||
test_radio_LDADD = $(LIBUTUN) $(CRYPTO_LIBS) $(COMMON_LIBS)
|
||||
test_radio_LDFLAGS = $(test_clock_ldflags)
|
||||
|
||||
test_radio_batch_SOURCES = test_radio_batch.c
|
||||
test_radio_batch_CFLAGS = $(test_radio_CFLAGS)
|
||||
test_radio_batch_LDADD = $(test_radio_LDADD)
|
||||
|
||||
test_radio_headless_SOURCES = test_radio_headless.c
|
||||
test_radio_headless_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/src/chat -I$(top_srcdir)/src/dm -I$(top_srcdir)/src/call -I$(top_srcdir)/src/radio -I$(top_srcdir)/src/routing_layer -I$(top_srcdir)/src/transport_layer -I$(top_srcdir)/lib
|
||||
test_radio_headless_LDADD = $(LIBUTUN) $(CRYPTO_LIBS) $(COMMON_LIBS)
|
||||
|
||||
@@ -21,6 +21,7 @@ static void test_reads(void) {
|
||||
assert(chat_setting_get_int_state(&state, "stream_subblocks", 77) == 77);
|
||||
assert(!strcmp(chat_setting_get_state(&state, "call_video_bitrate_range_kbps"), "300:4000"));
|
||||
assert(!chat_setting_set_state(&state, "stream_subblocks", "8"));
|
||||
assert(chat_setting_get_int_state(&state, "radio_burst_frames", 0) == 4);
|
||||
struct chat_setting_state before = state;
|
||||
const char* blocks = chat_setting_get_state(&state, "stream_subblocks");
|
||||
const char* bitrate = chat_setting_get_state(&state, "radio_opus_bitrate");
|
||||
@@ -68,6 +69,11 @@ static void test_validation(void) {
|
||||
assert(!strcmp(chat_setting_get_state(&state, "member_files_path"), ""));
|
||||
assert(!chat_setting_set_state(&state, "radio_level_on_dbfs", "-90"));
|
||||
assert(!strcmp(chat_setting_get_state(&state, "radio_level_on_dbfs"), "-90"));
|
||||
assert(!chat_setting_set_state(&state, "radio_burst_frames", "1"));
|
||||
assert(!chat_setting_set_state(&state, "radio_burst_frames", "10"));
|
||||
assert(chat_setting_set_state(&state, "radio_burst_frames", "0") == -2);
|
||||
assert(chat_setting_set_state(&state, "radio_burst_frames", "11") == -2);
|
||||
assert(chat_setting_get_int_state(&state, "radio_burst_frames", 0) == 10);
|
||||
DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "PASS settings validation: invalid values preserve zero/initialized state, bool aliases, signed range,255-byte path and clearing");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/* Настоящие radio TX/RX без сокетов: размеры1..10, хвост/FIN, malformed, дедупликация и таймеры. */
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "../src/radio/radio.h"
|
||||
#include "../src/chat/chat_setting.h"
|
||||
#include "../src/utun_instance.h"
|
||||
#include "../src/routing_layer/topo_group.h"
|
||||
#include "../src/routing_layer/topo_node.h"
|
||||
#include "../src/transport_layer/etcp.h"
|
||||
#include "../src/transport_layer/etcp_api.h"
|
||||
#include "../lib/u_async.h"
|
||||
#include "../lib/ll_queue.h"
|
||||
#include "../lib/debug_config.h"
|
||||
#include "../lib/mem.h"
|
||||
|
||||
static unsigned received, fins, expected_seq;
|
||||
static void receive_frame(struct UTUN_INSTANCE* inst, uint64_t group, uint64_t src, uint16_t stream,
|
||||
uint16_t seq, uint8_t fin, const uint8_t* opus, int len, void* arg) {
|
||||
(void)inst; (void)stream; (void)arg;
|
||||
assert(group == 77 && src == 1 && seq == expected_seq++);
|
||||
if (fin) { assert(!len && !opus); fins++; return; }
|
||||
assert(len == RADIO_MAX_OPUS);
|
||||
for (int i = 0; i < len; i++) assert(opus[i] == (uint8_t)seq);
|
||||
received++;
|
||||
}
|
||||
|
||||
/* Скопировать исходящий пакет как входящий от другого узла; ownership передаётся dispatcher. */
|
||||
static void inject(struct UTUN_INSTANCE* inst, struct ETCP_CONN* conn, const uint8_t* wire, size_t len) {
|
||||
struct ll_entry* e = ll_alloc_lldgram((uint16_t)len); assert(e);
|
||||
memcpy(e->dgram, wire, len); e->len = len;
|
||||
inst->api_bindings.callbacks[ETCP_ID_RADIO](conn, e);
|
||||
}
|
||||
|
||||
static void poll_for(struct UASYNC* ua, unsigned duration_tb) {
|
||||
uint64_t until = get_time_tb() + duration_tb;
|
||||
while (get_time_tb() < until) uasync_poll(ua, 10);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
debug_config_init(); debug_set_level(DEBUG_LEVEL_ERROR);
|
||||
size_t baseline = u_get_allocated_count();
|
||||
struct UASYNC* ua = uasync_create(); assert(ua);
|
||||
struct UTUN_INSTANCE inst = {.ua = ua, .node_id = 2};
|
||||
struct TOPO_GROUPS groups = {.instance = &inst}; inst.topo_groups = &groups;
|
||||
groups.group_list = queue_new(ua, 16, 0, 8, "radio_test_groups"); assert(groups.group_list);
|
||||
struct TOPO_GROUP* group = (void*)queue_entry_new(sizeof(*group) - sizeof(struct ll_entry)); assert(group);
|
||||
group->instance = &inst; group->group_id = 77; group->radio_active = 1;
|
||||
assert(!queue_data_put_with_index(groups.group_list, &group->ll));
|
||||
group->nodes = queue_new(ua, 0, 0, 0, "radio_test_nodes");
|
||||
group->senders_list = queue_new(ua, 0, 0, 0, "radio_test_senders");
|
||||
struct ETCP_CONN conn = {.instance = &inst, .peer_node_id = 1};
|
||||
conn.send_input_q = queue_new(ua, 0, 0, 0, "radio_test_wire");
|
||||
assert(group->nodes && group->senders_list && conn.send_input_q);
|
||||
struct TOPO_GROUP_NODE* node = (void*)queue_entry_new(sizeof(*node) - sizeof(struct ll_entry)); assert(node);
|
||||
node->node_id = 1; node->radio = 1; node->paths = queue_new(ua, 0, 0, 0, "radio_test_paths"); assert(node->paths);
|
||||
struct TOPO_NODEPATH* path = (void*)queue_entry_new(sizeof(*path) - sizeof(struct ll_entry)); assert(path);
|
||||
path->conn = &conn; assert(!queue_data_put(node->paths, &path->ll)); assert(!queue_data_put(group->nodes, &node->ll));
|
||||
struct ll_entry* sender = queue_entry_new(sizeof(struct TOPO_GROUP_CONN_ITEM)); assert(sender);
|
||||
((struct TOPO_GROUP_CONN_ITEM*)sender->data)->conn = &conn; assert(!queue_data_put(group->senders_list, sender));
|
||||
assert(!radio_init(group) && !radio_init_instance(&inst));
|
||||
radio_set_frame_cb(&inst, receive_frame, NULL);
|
||||
uint8_t opus[RADIO_MAX_OPUS], sample[1 + RADIO_HDR_SIZE + 8 + RADIO_MAX_BODY]; size_t sample_len = 0;
|
||||
for (unsigned target = 1; target <= 10; target++) {
|
||||
char value[8]; snprintf(value, sizeof(value), "%u", target);
|
||||
assert(!chat_setting_set(&inst, "radio_burst_frames", value));
|
||||
assert(!radio_talk_begin(&inst, 77));
|
||||
/* Смена настройки не меняет уже открытую передачу. */
|
||||
assert(!chat_setting_set(&inst, "radio_burst_frames", "1"));
|
||||
unsigned total = target + 1;
|
||||
for (unsigned i = 0; i < total; i++) {
|
||||
memset(opus, (int)i, sizeof(opus)); assert(!radio_talk_send(&inst, 77, opus, sizeof(opus)));
|
||||
assert(conn.send_input_q->count == (int)((i + 1) / target));
|
||||
}
|
||||
assert(!radio_talk_end(&inst, 77));
|
||||
assert(conn.send_input_q->count == (int)((total + target - 1) / target + 1));
|
||||
received = fins = expected_seq = 0;
|
||||
struct ll_entry* e;
|
||||
while ((e = queue_data_get(conn.send_input_q))) {
|
||||
uint8_t* p = e->dgram + 1;
|
||||
assert(e->dgram[0] == ETCP_ID_RADIO && p[RADIO_OFF_HOPS] == 1);
|
||||
uint64_t peer = 1; memcpy(p + RADIO_OFF_SRC, &peer, 8); memcpy(p + RADIO_OFF_HOPLIST, &peer, 8);
|
||||
unsigned before = received, before_fins = fins;
|
||||
inject(&inst, &conn, e->dgram, e->len);
|
||||
assert(received == before + p[RADIO_OFF_COUNT]);
|
||||
assert(fins == before_fins + !!p[RADIO_OFF_FLAGS]);
|
||||
inject(&inst, &conn, e->dgram, e->len); // Дубль пачки не выдаёт кадры повторно.
|
||||
assert(received == before + p[RADIO_OFF_COUNT] && fins == before_fins + !!p[RADIO_OFF_FLAGS]);
|
||||
if (target == 10 && p[RADIO_OFF_COUNT] == 10) {
|
||||
sample_len = e->len; memcpy(sample, e->dgram, sample_len);
|
||||
}
|
||||
queue_dgram_free(e); queue_entry_free(e); queue_resume_callback(conn.send_input_q);
|
||||
}
|
||||
assert(received == total && fins == 1);
|
||||
}
|
||||
/* Повреждённый последний кадр не должен выдать даже корректный префикс. */
|
||||
assert(sample_len); uint16_t stream = 60000;
|
||||
memcpy(sample + 1 + RADIO_OFF_STREAM, &stream, 2);
|
||||
unsigned before = received;
|
||||
for (size_t len = 0; len < sample_len; len++) inject(&inst, &conn, sample, len);
|
||||
assert(received == before);
|
||||
uint8_t invalid[sizeof(sample) + 1]; memcpy(invalid, sample, sample_len); invalid[sample_len] = 0;
|
||||
inject(&inst, &conn, invalid, sample_len + 1);
|
||||
for (unsigned count = 0; count <= 11; count += 11) {
|
||||
invalid[1 + RADIO_OFF_COUNT] = count; inject(&inst, &conn, invalid, sample_len);
|
||||
}
|
||||
memcpy(invalid, sample, sample_len); invalid[1 + RADIO_OFF_FLAGS] = RADIO_FLAG_FIN;
|
||||
inject(&inst, &conn, invalid, sample_len);
|
||||
invalid[1 + RADIO_OFF_FLAGS] = 2; inject(&inst, &conn, invalid, sample_len);
|
||||
memcpy(invalid, sample, sample_len); memset(invalid + 1 + RADIO_HDR_SIZE + 8, 0, 2);
|
||||
inject(&inst, &conn, invalid, sample_len);
|
||||
assert(received == before);
|
||||
received = fins = expected_seq = 0; inject(&inst, &conn, sample, sample_len); assert(received == 10 && !fins);
|
||||
/* Пауза захвата: частичная пачка уйдёт по deadline без END. */
|
||||
assert(!chat_setting_set(&inst, "radio_burst_frames", "10"));
|
||||
assert(!radio_talk_begin(&inst, 77)); memset(opus, 0, sizeof(opus));
|
||||
assert(!radio_talk_send(&inst, 77, opus, sizeof(opus))); assert(!conn.send_input_q->count);
|
||||
poll_for(ua, 2500); assert(conn.send_input_q->count == 1);
|
||||
struct ll_entry* e = queue_data_get(conn.send_input_q); assert(e->dgram[1 + RADIO_OFF_COUNT] == 1);
|
||||
queue_dgram_free(e); queue_entry_free(e); queue_resume_callback(conn.send_input_q);
|
||||
/* Destroy отменяет timer, не отправляет данные уже закрытой группы. */
|
||||
assert(!radio_talk_send(&inst, 77, opus, sizeof(opus)));
|
||||
radio_destroy(group); poll_for(ua, 2500); assert(!conn.send_input_q->count);
|
||||
radio_destroy_instance(&inst);
|
||||
queue_entry_free(queue_data_get(node->paths)); queue_free(node->paths);
|
||||
queue_entry_free(queue_data_get(group->nodes)); queue_free(group->nodes);
|
||||
queue_entry_free(queue_data_get(group->senders_list)); queue_free(group->senders_list);
|
||||
queue_entry_free(queue_data_get(groups.group_list)); queue_free(groups.group_list);
|
||||
queue_free(conn.send_input_q); uasync_destroy(ua, 0);
|
||||
if (u_get_allocated_count() != baseline) DEBUG_ERROR(DEBUG_CATEGORY_RADIO, "radio test retained allocations before=%zu after=%zu",
|
||||
baseline, u_get_allocated_count());
|
||||
assert(u_get_allocated_count() == baseline);
|
||||
debug_set_level(DEBUG_LEVEL_INFO);
|
||||
DEBUG_INFO(DEBUG_CATEGORY_RADIO, "PASS radio batches:1..10/max Opus, immutable target, tail/FIN, dedup, malformed, deadline, teardown, no leaks");
|
||||
return 0;
|
||||
}
|
||||
@@ -52,6 +52,7 @@
|
||||
#define TICK_TB 100 /* 10 ms на такт */
|
||||
#define MAX_TICKS 4000 /* глобальный таймаут ≈ 40 c */
|
||||
#define N_FRAMES 5
|
||||
#define N_PACKETS 3 /* default burst4: DATA4 + DATA1 + FIN */
|
||||
|
||||
enum mesh_phase {
|
||||
P_WAIT_CONN,
|
||||
@@ -132,7 +133,7 @@ static void mesh_radio_recv(struct ETCP_CONN* conn, struct ll_entry* entry) {
|
||||
g_radio_recv(conn, entry);
|
||||
if (g_hold_node >= 0 && self == g_hold_node && peer == IDX_C
|
||||
&& g_rx[self].frames == N_FRAMES && g_rx[self].fin_seen && !g_released) {
|
||||
if (g_held_count != N_FRAMES + 1) {
|
||||
if (g_held_count != N_PACKETS) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh gate: incomplete held burst node=%s held=%u", g_names[self], g_held_count);
|
||||
abort();
|
||||
}
|
||||
@@ -468,14 +469,14 @@ static int mesh_burst_result(struct mesh_ctx* t) {
|
||||
if (g_held_count) return 0;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
for (int j = 0; j < 4; ++j) if (g_wire_tx[i][j] != g_wire_rx[j][i]) return 0;
|
||||
if (g_hold_node >= 0 && (!g_released || dup[g_hold_node] != N_FRAMES + 1 || dup[IDX_C]
|
||||
if (g_hold_node >= 0 && (!g_released || dup[g_hold_node] != N_PACKETS || dup[IDX_C]
|
||||
|| g_wire_tx[g_hold_node][IDX_C] || g_wire_rx[IDX_C][g_hold_node])) {
|
||||
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh: forced order failed hold=%s released=%d dupB=%u dupD=%u dupC=%u",
|
||||
g_names[g_hold_node], g_released, dup[IDX_B], dup[IDX_D], dup[IDX_C]);
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
if ((uint64_t)dup[IDX_B] + dup[IDX_D] + dup[IDX_C] < N_FRAMES + 1) return 0;
|
||||
if ((uint64_t)dup[IDX_B] + dup[IDX_D] + dup[IDX_C] < N_PACKETS) return 0;
|
||||
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh scenario=%d PASS frames=5/5/5 FIN=1/1/1 dupB=%u dupD=%u dupC=%u",
|
||||
t->scenario, dup[IDX_B], dup[IDX_D], dup[IDX_C]);
|
||||
return 1;
|
||||
|
||||
@@ -154,6 +154,7 @@ class ConfigProvider(private val context: Context) {
|
||||
private val radioMicSourceKey = intPreferencesKey("radio_mic_source")
|
||||
private val radioOpusModeKey = intPreferencesKey("radio_opus_mode")
|
||||
private val radioOpusBitrateKey = intPreferencesKey("radio_opus_bitrate")
|
||||
private val radioBurstFramesKey = intPreferencesKey("radio_burst_frames")
|
||||
private val radioCaptureStereoKey = intPreferencesKey("radio_capture_stereo")
|
||||
private val radioCompressorEnabledKey = intPreferencesKey("radio_compressor_enabled")
|
||||
private val radioCompressorMaxGainDbKey = intPreferencesKey("radio_compressor_max_gain_db")
|
||||
@@ -391,6 +392,7 @@ class ConfigProvider(private val context: Context) {
|
||||
"radio.vad_compressor_max_gain_db" -> prefs[radioVadCompressorMaxGainDbKey] ?: 15
|
||||
"radio.opus_mode" -> prefs[radioOpusModeKey] ?: 0
|
||||
"radio.opus_bitrate" -> prefs[radioOpusBitrateKey] ?: 32
|
||||
"radio.burst_frames" -> (prefs[radioBurstFramesKey] ?: 4).coerceIn(1, 10)
|
||||
"radio.capture_stereo" -> prefs[radioCaptureStereoKey] ?: 0
|
||||
"radio.compressor_enabled" -> prefs[radioCompressorEnabledKey] ?: 1
|
||||
"radio.compressor_max_gain_db" -> prefs[radioCompressorMaxGainDbKey] ?: 15
|
||||
@@ -441,6 +443,11 @@ class ConfigProvider(private val context: Context) {
|
||||
"radio.vad_compressor_max_gain_db" -> prefs[radioVadCompressorMaxGainDbKey] = (value.toIntOrNull() ?: 15).coerceIn(1, 60)
|
||||
"radio.opus_mode" -> prefs[radioOpusModeKey] = value.toIntOrNull() ?: 0
|
||||
"radio.opus_bitrate" -> prefs[radioOpusBitrateKey] = value.toIntOrNull() ?: 32
|
||||
"radio.burst_frames" -> {
|
||||
val frames = value.toInt()
|
||||
require(frames in 1..10) { "Radio burst size must be 1..10: $frames" }
|
||||
prefs[radioBurstFramesKey] = frames
|
||||
}
|
||||
"radio.capture_stereo" -> prefs[radioCaptureStereoKey] = value.toIntOrNull() ?: 0
|
||||
"radio.compressor_enabled" -> prefs[radioCompressorEnabledKey] = value.toIntOrNull() ?: 1
|
||||
"radio.compressor_max_gain_db" -> prefs[radioCompressorMaxGainDbKey] = value.toIntOrNull() ?: 15
|
||||
@@ -923,6 +930,7 @@ class ConfigProvider(private val context: Context) {
|
||||
appendLine("radio_vad_compressor_max_gain_db=${radioAuto.vadGain}")
|
||||
appendLine("radio_opus_mode=$radioOpusMode")
|
||||
appendLine("radio_opus_bitrate=$radioOpusBitrate")
|
||||
appendLine("radio_burst_frames=${intValue("radio.burst_frames", prefs)}")
|
||||
appendLine("radio_capture_stereo=$radioCaptureStereo")
|
||||
appendLine("radio_compressor_enabled=$radioCompEnabled")
|
||||
appendLine("radio_compressor_max_gain_db=$radioCompMaxGain")
|
||||
|
||||
@@ -1138,6 +1138,27 @@ private fun RadioSettingsTab() {
|
||||
var opusBitrate by remember { mutableStateOf(provider.getInt("radio.opus_bitrate")) }
|
||||
var opusBitrateExpanded by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.radio_opus), style = MaterialTheme.typography.titleMedium)
|
||||
var burstFrames by remember { mutableIntStateOf(provider.getInt("radio.burst_frames")) }
|
||||
var burstExpanded by remember { mutableStateOf(false) }
|
||||
ExposedDropdownMenuBox(expanded = burstExpanded, onExpandedChange = { burstExpanded = it }) {
|
||||
OutlinedTextField(burstFrames.toString(), {}, readOnly = true, singleLine = true,
|
||||
label = { Text(stringResource(R.string.radio_burst_frames)) },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(burstExpanded) },
|
||||
modifier = Modifier.menuAnchor().heightIn(min = 40.dp))
|
||||
ExposedDropdownMenu(burstExpanded, onDismissRequest = { burstExpanded = false }) {
|
||||
(1..10).forEach { frames ->
|
||||
DropdownMenuItem(text = { Text(frames.toString()) }, onClick = {
|
||||
provider.changes.submit("radio burst frames") {
|
||||
provider.setValue("radio.burst_frames", frames.toString())
|
||||
if (NativeLib.isReady()) NativeLib.setChatSetting("radio_burst_frames", frames.toString())
|
||||
burstFrames = frames
|
||||
}
|
||||
burstExpanded = false
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(stringResource(R.string.radio_burst_hint), style = MaterialTheme.typography.bodySmall)
|
||||
ExposedDropdownMenuBox(expanded = opusModeExpanded, onExpandedChange = { opusModeExpanded = it }) {
|
||||
OutlinedTextField(opusModes[opusMode], {}, readOnly = true, singleLine = true,
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(opusModeExpanded) },
|
||||
|
||||
@@ -637,4 +637,6 @@
|
||||
<string name="ble_devices_failed">Не удалось обновить список устройств</string>
|
||||
<string name="ble_lqi_unavailable">LQI —</string>
|
||||
<string name="ble_broadcast_received">RX %1$d</string>
|
||||
<string name="radio_burst_frames">Размер burst-пачки (кадров Opus)</string>
|
||||
<string name="radio_burst_hint">Со следующей передачи. Кадр — 20 мс; большая пачка уменьшает накладные расходы, но добавляет задержку. Последняя неполная пачка отправляется сразу.</string>
|
||||
</resources>
|
||||
@@ -636,4 +636,6 @@
|
||||
<string name="ble_devices_failed">Could not refresh the device list</string>
|
||||
<string name="ble_lqi_unavailable">LQI —</string>
|
||||
<string name="ble_broadcast_received">RX %1$d</string>
|
||||
<string name="radio_burst_frames">Burst size (Opus frames)</string>
|
||||
<string name="radio_burst_hint">Applies to the next transmission. Each frame is 20 ms; larger batches reduce overhead but add delay. The final partial batch is sent immediately.</string>
|
||||
</resources>
|
||||
@@ -25,14 +25,14 @@ extern "C" {
|
||||
namespace {
|
||||
constexpr const char* settingKeys[] = {"radio_auto_enabled", "radio_vad_threshold", "radio_auto_hangover_ms",
|
||||
"radio_compressor_enabled", "radio_compressor_max_gain_db", "radio_vad_compressor_max_gain_db",
|
||||
"radio_auto_mode", "radio_level_on_dbfs", "radio_level_off_dbfs"};
|
||||
constexpr int settingMin[] = {0, 10, 50, 0, 1, 1, 1, -90, -90}, settingMax[] = {1, 95, 2000, 1, 60, 60, 2, 0, 0};
|
||||
"radio_auto_mode", "radio_level_on_dbfs", "radio_level_off_dbfs", "radio_burst_frames"};
|
||||
constexpr int settingMin[] = {0, 10, 50, 0, 1, 1, 1, -90, -90, 1}, settingMax[] = {1, 95, 2000, 1, 60, 60, 2, 0, 0, 10};
|
||||
struct SettingsRequest {
|
||||
posted_task task; // Первое поле: очередь освобождает весь запрос, включая отмену при shutdown.
|
||||
RadioAudioEngine* engine;
|
||||
UTUN_INSTANCE* inst;
|
||||
uint64_t generation; // Неизменяемая копия GUI-поколения; uasync не читает состояние engine.
|
||||
std::array<int, 9> values;
|
||||
std::array<int, 10> values;
|
||||
bool apply;
|
||||
};
|
||||
}
|
||||
@@ -137,7 +137,7 @@ bool RadioAudioEngine::applySettings(const QMap<QString, int>& values) {
|
||||
}
|
||||
|
||||
/* Возврат в GUI происходит после применения всей группы настроек в uasync. */
|
||||
void RadioAudioEngine::postSettings(const std::array<int, 9>& values, bool apply) {
|
||||
void RadioAudioEngine::postSettings(const std::array<int, 10>& values, bool apply) {
|
||||
auto* inst = gui_bridge_get_inst();
|
||||
void* memory = inst && gui_bridge_is_uasync_ready() ? u_malloc(sizeof(SettingsRequest)) : nullptr;
|
||||
if (!memory) {
|
||||
@@ -177,6 +177,8 @@ void RadioAudioEngine::postSettings(const std::array<int, 9>& values, bool apply
|
||||
return;
|
||||
}
|
||||
bool changed = engine->m_settings != snapshot;
|
||||
bool burstOnly = snapshot[9] != engine->m_settings[9]
|
||||
&& std::equal(snapshot.begin(), snapshot.begin() + 9, engine->m_settings.begin());
|
||||
engine->m_settings = snapshot;
|
||||
engine->m_settingsReady = true;
|
||||
engine->m_settingsBusy = false;
|
||||
@@ -186,10 +188,10 @@ void RadioAudioEngine::postSettings(const std::array<int, 9>& values, bool apply
|
||||
}
|
||||
if (!success) engine->m_settingsError = QCoreApplication::translate("ChatGui", "The core rejected radio settings");
|
||||
DEBUG_INFO(DEBUG_CATEGORY_RADIO, "RadioAudio: settings complete generation=%llu apply=%d success=%d "
|
||||
"auto=%d threshold=%d hangover=%dms TX_AGC=%d TX_gain=%ddB VAD_gain=%ddB mode=%d level_on=%d level_off=%d",
|
||||
"auto=%d threshold=%d hangover=%dms TX_AGC=%d TX_gain=%ddB VAD_gain=%ddB mode=%d level_on=%d level_off=%d burst=%d",
|
||||
(unsigned long long)generation, apply, success, snapshot[0], snapshot[1], snapshot[2],
|
||||
snapshot[3], snapshot[4], snapshot[5], snapshot[6], snapshot[7], snapshot[8]);
|
||||
if ((changed || apply) && engine->m_active) engine->reconfigureCapture();
|
||||
snapshot[3], snapshot[4], snapshot[5], snapshot[6], snapshot[7], snapshot[8], snapshot[9]);
|
||||
if ((changed || apply) && !burstOnly && engine->m_active) engine->reconfigureCapture();
|
||||
emit engine->stateChanged();
|
||||
}, Qt::QueuedConnection);
|
||||
request->~SettingsRequest();
|
||||
|
||||
@@ -87,9 +87,9 @@ private:
|
||||
void openCapture(); // Подписка Role::Radio; ready/stopped запускают/останавливают core capture и его worker.
|
||||
void updateState(); // Снимает статус ядра и готовность устройств, уведомляет GUI при изменениях.
|
||||
void reconfigureCapture(); // Переоткрывает только capture, сохраняя RX/output и ручной запрос PTT.
|
||||
void postSettings(const std::array<int, 9>& values, bool apply); // Публикует read/apply в uasync с возвратом снимка в GUI.
|
||||
void postSettings(const std::array<int, 10>& values, bool apply); // Публикует read/apply в uasync с возвратом снимка в GUI.
|
||||
/* auto_enabled, vad_threshold (%), hangover (мс), compressor_enabled, TX/VAD gain (dB), auto_mode, on/off (dBFS). */
|
||||
std::array<int, 9> m_settings{0, 50, 200, 1, 15, 15, 1, -35, -45};
|
||||
std::array<int, 10> m_settings{0, 50, 200, 1, 15, 15, 1, -35, -45, 4}; // Последнее поле — размер сетевой пачки.
|
||||
QString m_configPath; // INI для последующего сохранения изменённых полей в [chatserver].
|
||||
QString m_settingsError; // Ошибка загрузки/валидации/сохранения/применения настроек.
|
||||
uint64_t m_settingsGeneration = 0; // Только GUI; каждый loadSettings инвалидирует старые queued completions.
|
||||
|
||||
@@ -97,6 +97,9 @@ RadioActivationSettings::RadioActivationSettings(bool compact, QWidget* parent)
|
||||
m_hangover = add(QCoreApplication::translate("ChatGui", "Silence before ending transmission:"), "radioHangover", 50, 2000,
|
||||
QCoreApplication::translate("ChatGui", " ms"));
|
||||
if (!compact) {
|
||||
m_burstFrames = add(QCoreApplication::translate("ChatGui", "Burst size (Opus frames):"), "radioBurstFrames", 1, 10, QString());
|
||||
m_burstFrames->setToolTip(QCoreApplication::translate("ChatGui",
|
||||
"Applies to the next transmission. Each frame is 20 ms; larger batches reduce overhead but add delay. The final partial batch is sent immediately."));
|
||||
m_compressor = new QCheckBox(QCoreApplication::translate("ChatGui", "Transmission and VAD compressor"), this);
|
||||
form->addRow(m_compressor);
|
||||
connect(m_compressor, &QCheckBox::toggled, this, &RadioActivationSettings::updateControls);
|
||||
@@ -123,6 +126,7 @@ QMap<QString, int> RadioActivationSettings::values() const {
|
||||
{"radio_level_off_dbfs", m_levelOff->value()}, {"radio_vad_threshold", m_threshold->value()},
|
||||
{"radio_auto_hangover_ms", m_hangover->value()}, {"radio_vad_compressor_max_gain_db", m_vadGain->value()}};
|
||||
if (!m_compact) {
|
||||
result.insert(QStringLiteral("radio_burst_frames"), m_burstFrames->value());
|
||||
result.insert(QStringLiteral("radio_compressor_enabled"), m_compressor->isChecked() ? 1 : 0);
|
||||
result.insert(QStringLiteral("radio_compressor_max_gain_db"), m_txGain->value());
|
||||
}
|
||||
@@ -156,6 +160,7 @@ void RadioActivationSettings::loadSettings() {
|
||||
m_hangover->setValue(engine->setting(QStringLiteral("radio_auto_hangover_ms")));
|
||||
m_vadGain->setValue(engine->setting(QStringLiteral("radio_vad_compressor_max_gain_db")));
|
||||
if (!m_compact) {
|
||||
m_burstFrames->setValue(engine->setting(QStringLiteral("radio_burst_frames")));
|
||||
m_compressor->setChecked(engine->setting(QStringLiteral("radio_compressor_enabled")) != 0);
|
||||
m_txGain->setValue(engine->setting(QStringLiteral("radio_compressor_max_gain_db")));
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ private:
|
||||
QButtonGroup* m_mode; // Дочерняя группа: 1=VAD, 2=уровень сигнала.
|
||||
QSpinBox *m_threshold, *m_hangover, *m_txGain = nullptr, *m_vadGain, *m_levelOn, *m_levelOff; // %, мс, TX/VAD dB, on/off dBFS.
|
||||
QCheckBox* m_compressor = nullptr; // Общий флаг компрессора, отсутствует в compact.
|
||||
QSpinBox* m_burstFrames = nullptr; // 1..10 Opus-кадров в сетевой пачке; только полная вкладка.
|
||||
RadioLevelMeter *m_levelMeter, *m_vadMeter; // Дочерние шкалы уровня/вероятности с отметками черновых порогов.
|
||||
QLabel *m_levelText, *m_vadText, *m_gainText, *m_error; // Дочерние подписи измерений и ошибки.
|
||||
};
|
||||
|
||||
@@ -245,6 +245,12 @@ int main(int argc, char** argv) {
|
||||
|
||||
RadioSettingsPage settings(nullptr);
|
||||
settings.resize(620, 780); settings.show();
|
||||
auto* burst = settings.findChild<QSpinBox*>("radioBurstFrames");
|
||||
REQUIRE(burst && burst->minimum() == 1 && burst->maximum() == 10 && burst->value() == 4);
|
||||
oldInputs = inputs; oldOutputs = outputs;
|
||||
burst->setValue(10); REQUIRE(settings.apply());
|
||||
await([&]() { return !engine->settingsBusy(); });
|
||||
REQUIRE(engine->setting("radio_burst_frames") == 10 && inputs == oldInputs && outputs == oldOutputs);
|
||||
auto* mode = settings.findChild<QPushButton*>("radioModeLevel");
|
||||
auto* on = settings.findChild<QSpinBox*>("radioLevelOn");
|
||||
auto* off = settings.findChild<QSpinBox*>("radioLevelOff");
|
||||
@@ -288,7 +294,7 @@ int main(int argc, char** argv) {
|
||||
config.close();
|
||||
REQUIRE(saved.contains("radio_auto_enabled=1") && saved.contains("radio_vad_threshold=65") &&
|
||||
saved.contains("radio_auto_hangover_ms=400") && saved.contains("radio_vad_compressor_max_gain_db=30") &&
|
||||
saved.contains("radio_opus_bitrate=32"));
|
||||
saved.contains("radio_opus_bitrate=32") && saved.contains("radio_burst_frames=10"));
|
||||
// Как при рестарте приложения: runtime-настройки заново читаются парсером из сохранённого INI.
|
||||
auto* parsed = parse_config(configPath.toUtf8().constData());
|
||||
REQUIRE(parsed);
|
||||
@@ -296,7 +302,7 @@ int main(int argc, char** argv) {
|
||||
free_config(parsed);
|
||||
engine->loadSettings(configPath);
|
||||
await([&]() { return !engine->settingsBusy(); });
|
||||
REQUIRE(engine->autoEnabled() && engine->setting("radio_vad_threshold") == 65);
|
||||
REQUIRE(engine->autoEnabled() && engine->setting("radio_vad_threshold") == 65 && engine->setting("radio_burst_frames") == 10);
|
||||
detectorAvailable = true;
|
||||
REQUIRE(engine->start(8) == 0);
|
||||
await([&]() { return engine->autoAvailable(); });
|
||||
|
||||
@@ -2748,5 +2748,13 @@ See log:
|
||||
<source>Failed to save Bluetooth settings. Check the configuration file.</source>
|
||||
<translation>Failed to save Bluetooth settings. Check the configuration file.</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Burst size (Opus frames):</source>
|
||||
<translation>Burst size (Opus frames):</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Applies to the next transmission. Each frame is 20 ms; larger batches reduce overhead but add delay. The final partial batch is sent immediately.</source>
|
||||
<translation>Applies to the next transmission. Each frame is 20 ms; larger batches reduce overhead but add delay. The final partial batch is sent immediately.</translation>
|
||||
</message>
|
||||
</context>
|
||||
</TS>
|
||||
@@ -2757,5 +2757,13 @@ See log:
|
||||
<source>Failed to save Bluetooth settings. Check the configuration file.</source>
|
||||
<translation>Не удалось сохранить настройки Bluetooth. Проверьте файл конфигурации.</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Burst size (Opus frames):</source>
|
||||
<translation>Размер burst-пачки (кадров Opus):</translation>
|
||||
</message>
|
||||
<message>
|
||||
<source>Applies to the next transmission. Each frame is 20 ms; larger batches reduce overhead but add delay. The final partial batch is sent immediately.</source>
|
||||
<translation>Со следующей передачи. Кадр — 20 мс; большая пачка уменьшает накладные расходы, но добавляет задержку. Последняя неполная пачка отправляется сразу.</translation>
|
||||
</message>
|
||||
</context>
|
||||
</TS>
|
||||
Reference in new issue
Block a user