Build call audio batches only when Router grants a send slot

This commit is contained in:
evgeny committed 2026-10-30 19:21:29 +01:00
1 parent c15f26171b
commit a3bacc9844
2 files changed
+68 -115

No files matched your search

+65 -110
View File
@@ -47,7 +47,7 @@ struct call_audio_pending {
uint16_t seq;
};
static void call_tx_flush(struct call_session* s);
static void call_audio_batch_tick(void* arg);
static void call_tx_flush(struct call_session* s);
/* ───────────────────────────────────────────────────────────────────────── */
@@ -150,7 +150,6 @@ static struct call_session* call_session_new(struct call_ctx* ctx, uint64_t call
s->state = CALL_ST_IDLE;
s->started_tb = get_time_tb();
s->ctx = ctx;
call_audio_batch_init(&s->audio_batch, get_time_us());
s->tx_q = queue_new(ctx->inst->ua, 0, 0, 0, "call_txq");
if (!s->tx_q) { queue_entry_free(qe); return NULL; }
// При провале queue_data_put_with_index сам освобождает qe (вместе с s), поэтому
@@ -172,10 +171,7 @@ static void call_session_free_cb(void* arg) {
* дренировать tx_q (без отправки). Безопасно вызывать из uasync-потока. */
static void call_session_cleanup(struct call_ctx* ctx, struct call_session* s) {
call_video_transport_stop(s);
if (s->audio_batch_timer) uasync_cancel_timeout(ctx->inst->ua, s->audio_batch_timer);
if (s->audio_flush_timer) uasync_cancel_timeout(ctx->inst->ua, s->audio_flush_timer);
s->audio_batch_timer = s->audio_flush_timer = NULL;
etcp_router_cancel_send_ready(ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO, &s->send_waiter);
etcp_router_cancel_request(&s->audio_send);
if (s->tx_q) {
struct ll_entry* e;
while ((e = queue_data_get(s->tx_q)) != NULL) {
@@ -431,9 +427,8 @@ static void call_activate(struct call_session* s) {
if (s->state == CALL_ST_ACTIVE || s->state == CALL_ST_ENDED) return;
struct call_ctx* ctx = s->ctx;
s->state = CALL_ST_ACTIVE;
call_audio_batch_tick(s);
DEBUG_INFO(DEBUG_CATEGORY_CALL, "audio batch startup call=%llx target=%u hold_us=%u",
(unsigned long long)s->call_id, s->audio_batch.target, s->audio_batch.hold_us);
DEBUG_INFO(DEBUG_CATEGORY_CALL, "audio batch startup call=%llx mode=router-ready max_frames=%u max_bytes=%u",
(unsigned long long)s->call_id, CALL_AUDIO_BATCH_MAX, CALL_MEDIA_MAX_BYTES);
DEBUG_INFO(DEBUG_CATEGORY_CALL, "%s: accepted id=%016llx -> ACTIVE (router delivery)", CALL_ID,
(unsigned long long)s->call_id);
call_event_id(ctx, CHAT_EVT_CALL_ACCEPTED, s->call_id, 0);
@@ -537,6 +532,16 @@ static void call_post_stats(struct call_session* s) {
(unsigned long long)s->call_id, s->tx_wait_frames, s->tx_q ? (size_t)queue_entry_count(s->tx_q) : 0, oldest_ms,
(unsigned long long)(s->tx_wait_frames ? s->tx_wait_total_ms / s->tx_wait_frames : 0), s->tx_wait_max_ms);
s->tx_wait_frames = s->tx_wait_max_ms = 0; s->tx_wait_total_ms = 0;
struct ETCP_ROUTER_TX_STATS net = {0};
etcp_router_tx_stats(ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO, get_time_us(), &net);
const char *wait = !s->audio_send.conn ? "idle" : !net.ready ? "handshake" : net.no_route ? "no-route"
: net.receive_busy ? "peer-busy" : rconn && net.inflight_packets >= rconn->inflight_limit ? "window" : "transport";
DEBUG_DEBUG(DEBUG_CATEGORY_CALL, "audio batch flow call=%llx wait=%s queued=%u/%llu inflight=%u/%llu "
"enqueue_ack_us=%llu submit_ack_us=%u ack_bytes_500ms=%llu tx_frames=%u tx_batches=%u rx_frames=%u rx_batches=%u",
(unsigned long long)s->call_id, wait, net.queued_packets, (unsigned long long)net.queued_age_us,
net.inflight_packets, (unsigned long long)net.inflight_age_us, (unsigned long long)net.delivery_rtt_us,
net.rtt_us, (unsigned long long)net.window.bytes, s->c_tx_frames, s->tx_batches, s->c_rx_frames, s->rx_batches);
call_tx_flush(s); /* Повтор регистрации после reset/ошибки выделения; обычный drain работает по событиям. */
DEBUG_DEBUG(DEBUG_CATEGORY_CALL, "%s: stats id=%016llx recv_peer=%016llx rtt_tb=%u rtt_ms=%u buffer=%dms tempo=%d dropped=%u underruns=%u",
CALL_ID, (unsigned long long)s->call_id,
(unsigned long long)(rconn && rconn->recv_conn ? rconn->recv_conn->peer_node_id : 0),
@@ -995,110 +1000,60 @@ void call_set_audio_ops(struct UTUN_INSTANCE* inst, const struct call_audio_ops*
/* ─────────────────── TX медиа: tx_q + backpressure ─────────────────── */
static void call_tx_flush(struct call_session* s);
static void call_tx_drain_cb(struct ll_queue* q, void* arg) {
(void)q;
struct call_session* s = (struct call_session*)arg;
if (!s || !s->ctx) return;
if (s->state == CALL_ST_ENDED) return;
call_tx_flush(s);
}
/* Deadline относится к возрасту головы; новые кадры не отодвигают срок отправки. */
static void call_audio_flush_timer(void* arg) {
struct call_session *s = arg; s->audio_flush_timer = NULL; call_tx_flush(s);
}
static void call_audio_batch_tick(void* arg) {
struct call_session *s = arg; s->audio_batch_timer = NULL;
if (s->state != CALL_ST_ACTIVE) return;
uint64_t now = get_time_us();
struct ETCP_ROUTER_TX_STATS net = {0};
int found = etcp_router_tx_stats(s->ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO, now, &net) == 0;
if (call_audio_batch_step(&s->audio_batch, now, found ? &net : NULL)) s->audio_batch.hold_us = 0;
if (now - s->audio_report_us >= 1000000) {
s->audio_report_us = now;
DEBUG_DEBUG(DEBUG_CATEGORY_CALL,
"audio batch flow call=%llx target=%u hold_us=%u router_rtt_us=%llu queued=%u/%llu inflight=%u/%llu "
"ack_bytes_500ms=%llu local_frames=%d tx_frames=%u tx_batches=%u rx_frames=%u rx_batches=%u",
(unsigned long long)s->call_id, s->audio_batch.target, s->audio_batch.hold_us,
(unsigned long long)net.delivery_rtt_us, net.queued_packets, (unsigned long long)net.queued_age_us,
net.inflight_packets, (unsigned long long)net.inflight_age_us, (unsigned long long)net.window.bytes,
s->tx_q ? queue_entry_count(s->tx_q) : 0, s->c_tx_frames, s->tx_batches, s->c_rx_frames, s->rx_batches);
}
call_tx_flush(s);
if (s->state != CALL_ST_ACTIVE) return;
s->audio_batch_timer = uasync_set_timeout(s->ctx->inst->ua, 500, s, call_audio_batch_tick, "audio_batch");
if (!s->audio_batch_timer) {
s->audio_batch.hold_us = 0;
DEBUG_ERROR(DEBUG_CATEGORY_CALL, "audio batch timer allocation failed; immediate TX");
}
}
/* Пачка формируется до Router: принятые им кодограммы не изменяются. */
static void call_tx_flush(struct call_session* s) {
struct call_ctx* ctx = s->ctx;
/* Пачка формируется по готовности Router; до принятия все кадры остаются в FIFO сервиса. */
static void call_tx_ready(struct ETCP_ROUTER_CONN* rconn, void* arg) {
struct call_session *s = arg;
if (s->state != CALL_ST_ACTIVE || !s->tx_q || !s->tx_q->head) return;
if (s->audio_flush_timer) { uasync_cancel_timeout(ctx->inst->ua, s->audio_flush_timer); s->audio_flush_timer = NULL; }
if (!etcp_router_conn_get(ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO)) {
DEBUG_ERROR(DEBUG_CATEGORY_CALL, "audio router channel unavailable; retaining frames"); return;
struct call_audio_pending *first = (struct call_audio_pending*)s->tx_q->head->data;
struct call_audio_batch_view batch = {.header = {.subcmd = CALL_SUBCMD_MEDIA, .call_id = s->call_id,
.track_id = CALL_TRACK_AUDIO, .capture_epoch = first->timing.epoch,
.codec_delay_samples = first->timing.delay_samples, .sent_ms = (uint32_t)(get_time_tb() / 10)}};
size_t size = CALL_MEDIA_HDR_SIZE;
struct ll_entry *next = s->tx_q->head;
const char *reason = "available";
while (next && batch.header.count < CALL_AUDIO_BATCH_MAX) {
struct call_audio_pending *p = (struct call_audio_pending*)next->data;
if (p->timing.epoch != first->timing.epoch || p->timing.delay_samples != first->timing.delay_samples) {
reason = "capture-change"; break;
}
if (size + CALL_AUDIO_FRAME_HDR_SIZE + next->len > CALL_MEDIA_MAX_BYTES) { reason = "bytes"; break; }
batch.frames[batch.header.count++] = (struct call_audio_frame_view){
.header = {p->seq, p->timing.pts_us, next->len}, .opus = next->dgram};
size += CALL_AUDIO_FRAME_HDR_SIZE + next->len; next = next->next;
}
while (s->state == CALL_ST_ACTIVE && s->tx_q && s->tx_q->head) {
if (!etcp_router_send_q_has_room(ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO)) {
etcp_router_on_send_ready(ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO,
&s->send_waiter, call_tx_drain_cb, s);
return;
}
struct call_audio_pending *first = (struct call_audio_pending*)s->tx_q->head->data;
struct call_audio_batch_view batch = {.header = {.subcmd = CALL_SUBCMD_MEDIA, .call_id = s->call_id,
.track_id = CALL_TRACK_AUDIO, .capture_epoch = first->timing.epoch,
.codec_delay_samples = first->timing.delay_samples, .sent_ms = (uint32_t)(get_time_tb() / 10)}};
size_t size = CALL_MEDIA_HDR_SIZE;
struct ll_entry *next = s->tx_q->head;
while (next && batch.header.count < s->audio_batch.target) {
struct call_audio_pending *p = (struct call_audio_pending*)next->data;
if (p->timing.epoch != first->timing.epoch || p->timing.delay_samples != first->timing.delay_samples
|| size + CALL_AUDIO_FRAME_HDR_SIZE + next->len > CALL_MEDIA_MAX_BYTES) break;
batch.frames[batch.header.count++] = (struct call_audio_frame_view){
.header = {p->seq, p->timing.pts_us, next->len}, .opus = next->dgram};
size += CALL_AUDIO_FRAME_HDR_SIZE + next->len; next = next->next;
}
uint64_t now = get_time_us(), age = now - first->created_us;
if (!next && batch.header.count < s->audio_batch.target && age < s->audio_batch.hold_us) {
s->audio_flush_timer = uasync_set_timeout(ctx->inst->ua, (s->audio_batch.hold_us - age + 199) / 100,
s, call_audio_flush_timer, "audio_batch_flush");
if (s->audio_flush_timer) return;
DEBUG_ERROR(DEBUG_CATEGORY_CALL, "audio flush timer allocation failed; sending incomplete batch");
}
struct ll_entry *wire = ll_alloc_lldgram(1 + size);
if (!wire) { DEBUG_ERROR(DEBUG_CATEGORY_CALL, "audio batch allocation failed bytes=%zu", size); return; }
wire->dgram[0] = ETCP_RT_ID_CALL_AUDIO;
size_t encoded = 0;
if (call_audio_batch_encode(&batch, wire->dgram + 1, size, &encoded)) {
queue_dgram_free(wire); queue_entry_free(wire); return;
}
wire->len = 1 + encoded;
unsigned count = batch.header.count;
int64_t last_pts = batch.frames[count - 1].header.capture_pts_us;
/* Снять исходные кадры до синхронных callbacks Router, которые могут завершить звонок. */
for (unsigned i = 0; i < count; i++) {
struct ll_entry *e = queue_data_get(s->tx_q);
uint32_t wait_ms = (uint32_t)((now - ((struct call_audio_pending*)e->data)->created_us) / 1000);
s->tx_wait_frames++; s->tx_wait_total_ms += wait_ms;
if (wait_ms > s->tx_wait_max_ms) s->tx_wait_max_ms = wait_ms;
queue_dgram_free(e); queue_entry_free(e);
}
DEBUG_DEBUG(DEBUG_CATEGORY_CALL, "audio batch TX call=%llx frames=%u target=%u bytes=%zu oldest_us=%llu first_seq=%u",
(unsigned long long)s->call_id, count, s->audio_batch.target, encoded,
(unsigned long long)age, batch.frames[0].header.seq);
if (etcp_route_send(ctx->inst, s->group_id, s->peer_node_id, wire, 1, ROUTE_CRYPTO_SIGN | ROUTE_CRYPTO_ENCRYPT) == 0) {
s->c_tx_frames += count; s->tx_batches++;
if (s->state == CALL_ST_ACTIVE && last_pts != INT64_MIN) call_video_audio_sent(s, last_pts + 20000);
} else {
s->c_tx_dropped += count;
DEBUG_WARN(DEBUG_CATEGORY_CALL, "audio batch enqueue failed call=%llx frames=%u", (unsigned long long)s->call_id, count);
}
if (batch.header.count == CALL_AUDIO_BATCH_MAX) reason = "frames";
uint8_t wire[CALL_MEDIA_MAX_BYTES];
size_t encoded = 0;
if (call_audio_batch_encode(&batch, wire, sizeof(wire), &encoded)) return;
uint64_t now = get_time_us(), age = now - first->created_us;
unsigned count = batch.header.count;
int64_t last_pts = batch.frames[count - 1].header.capture_pts_us;
/* Внутри ready Router только копирует пакет; сервисные callbacks до возврата не вызываются. */
if (etcp_router_conn_send(rconn, wire, encoded, ROUTE_CRYPTO_SIGN | ROUTE_CRYPTO_ENCRYPT)) {
DEBUG_WARN(DEBUG_CATEGORY_CALL, "audio batch enqueue failed call=%llx frames=%u; retaining Opus",
(unsigned long long)s->call_id, count);
return;
}
for (unsigned i = 0; i < count; i++) {
struct ll_entry *e = queue_data_get(s->tx_q);
uint32_t wait_ms = (uint32_t)((now - ((struct call_audio_pending*)e->data)->created_us) / 1000);
s->tx_wait_frames++; s->tx_wait_total_ms += wait_ms;
if (wait_ms > s->tx_wait_max_ms) s->tx_wait_max_ms = wait_ms;
queue_dgram_free(e); queue_entry_free(e);
}
s->c_tx_frames += count; s->tx_batches++;
DEBUG_DEBUG(DEBUG_CATEGORY_CALL, "audio batch TX call=%llx frames=%u bytes=%zu oldest_us=%llu first_seq=%u reason=%s remaining=%d",
(unsigned long long)s->call_id, count, encoded, (unsigned long long)age,
batch.frames[0].header.seq, reason, queue_entry_count(s->tx_q));
if (last_pts != INT64_MIN) call_video_audio_sent(s, last_pts + 20000);
call_tx_flush(s);
}
static void call_tx_flush(struct call_session* s) {
if (s->state != CALL_ST_ACTIVE || !s->tx_q || !s->tx_q->head || s->audio_send.conn) return;
struct ETCP_ROUTER_CONN *rconn = etcp_router_conn_get(s->ctx->inst, s->group_id, s->peer_node_id, ETCP_RT_ID_CALL_AUDIO);
if (etcp_router_request_send(rconn, &s->audio_send, call_tx_ready, s))
DEBUG_ERROR(DEBUG_CATEGORY_CALL, "audio router request failed call=%llx; retaining Opus", (unsigned long long)s->call_id);
}
int call_send_media(struct UTUN_INSTANCE* inst, uint64_t call_id, const uint8_t* opus, int len,
+3 -5
View File
@@ -11,6 +11,7 @@
#define CALL_PRIV_H
#include "call.h"
#include "call_audio_batch.h"
#include "../routing_layer/etcp_router.h"
#include "../../lib/ll_queue.h"
/* IDLE — только создание; RINGING бывает у обеих ролей, WAIT_DECISION — ожидание force
@@ -34,14 +35,11 @@ struct call_session {
uint8_t connection_reported, connection_type; /* Было событие CONNECTION / последний router path.type (0..3). */
uint64_t connection_next_hop, last_media_tb; /* Кэш next hop и время последнего RX; watchdog использует traffic_timer. */
uint16_t tx_media_seq; /* Следующий sequence аудиопакета с wrap uint16; расходуется до выделения TX entry. */
struct call_audio_batch_control audio_batch; /* Только uasync; reset при смене Router epoch. */
void *audio_batch_timer, *audio_flush_timer; /* Наблюдение 50мс и deadline неполной пачки. */
uint64_t audio_report_us;
uint32_t tx_batches, rx_batches; /* Число Router-кодограмм, отдельно от аудиокадров. */
struct ll_queue *tx_q; /* FIFO Opus с локальными seq/PTS/created_us в entry->data; до 750, overflow удаляет голову. */
struct queue_waiter_handle send_waiter; /* Отменяемое одноразовое ожидание места в router audio send_q. */
struct router_send_request audio_send; /* Слот отправки: до callback кадры остаются в tx_q. */
uint32_t c_tx_frames, c_rx_frames, c_tx_dropped, c_rx_dropped; /* TX принят router / валидный RX / TX overflow / RX не ведётся. */
uint64_t tx_wait_total_ms; /* Сумма времени audio enqueue->drain, включая отказ router; сброс при отчёте stats. */
uint64_t tx_wait_total_ms; /* Сумма времени enqueue->принятие Router; сброс при отчёте stats. */
uint32_t tx_wait_frames, tx_wait_max_ms; /* Число drained кадров/максимальное ожидание за тот же отчётный интервал. */
struct call_video_transport *video; /* Собственное ленивое состояние видеотрека; cleanup обнуляет и освобождает его. */
};