Files
mcde/programs/dtchat/headless.c
T
lotherk 1a6572a499 dtchat: add the headless voice test (T6.7)
dtchat-headless gains --call, --audio-in FILE and --audio-out FILE: it exchanges media-key on the ready link, calls the peer, answers an incoming ring (it is a test peer, so the answer is automatic), and pumps the call from its loop: a 20 ms frame from the raw s16le 48 kHz file is encoded and sent while in the call, received frames are decoded into the output file, and call/audio events go to stdout. tests/p2p-audio.sh starts two instances (A listens and records, B connects, calls and plays tests/tone.py's 2 s 440 Hz tone), waits for both in-call, for 100 received frames, prints the CPU time of both, quits them and has tests/tone-check.py verify the recording (length within 25 percent, RMS > 500, zero crossings within 15 percent). Standalone run: A 45475, both in-call, recording 2.00 s / RMS 6339 / 441 Hz, all ok. Wired into the harness as DtChat/p2p-audio (42 entries). In-tree build pending: a foreign make userland holds the lock.
2026-11-17 08:54:05 +00:00

691 lines
17 KiB
C

/*
* headless.c -- dtchat without a display
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* usage: dtchat-headless [--config DIR] [--listen [HOST:]PORT]
* [--peer HOST:PORT ...]
*
* Starts the local TLS listener and one reconnecting link per --peer. Every
* event is one JSON object on stdout; commands are JSON lines on stdin:
*
* {"cmd":"send","peer":"HOST:PORT"|"ID","text":"..."}
* {"cmd":"quit"}
*
* Events: ready, peer-online, peer-offline, message, typing, file-offer,
* error. The test harness is tests/p2p.sh.
*/
#include "dc_internal.h"
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct Link {
char target[256];
DcLocalPeer *peer;
int online;
char id[128];
struct Link *next;
};
struct Accepted {
DcLocalConn *conn;
char id[128];
char pin[128];
struct Accepted *next;
};
static DcLoop *loop;
static DcLocalServer *server;
static struct Link *links;
static struct Accepted *accepted;
static int quit_flag;
static int stdin_id;
static DcFrameBuf stdin_frame;
/* one call at a time: the headless tool is a test peer, not a switchboard */
static DcMediaCall *call;
static unsigned char call_priv[DC_MEDIA_KEY_LEN];
static char call_pub[DC_MEDIA_PUB_B64_LEN];
static char call_peer_pub[DC_MEDIA_PUB_B64_LEN];
static int call_offered;
static int call_initiator;
static int call_port;
static int call_answer = 1;
static int local_port;
static const char *audio_in_path;
static const char *audio_out_path;
static FILE *audio_in_fp;
static FILE *audio_out_fp;
static unsigned int call_in_frames;
static unsigned int call_out_frames;
static DcCallState last_call_state = DC_CALL_IDLE;
static int call_flag_enabled;
static void
emit(DcJson *json)
{
size_t len = 0;
char *text = dc_json_write(json, &len);
if (text != NULL) {
(void)write(STDOUT_FILENO, text, len);
(void)write(STDOUT_FILENO, "\n", 1);
free(text);
}
dc_json_free(json);
}
static void
emit_error(const char *text)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "event", dc_json_new_string("error"));
(void)dc_json_object_set(json, "text", dc_json_new_string(text));
emit(json);
}
static void
emit_peer(const char *event, const char *mode, const char *target,
const char *id, const char *pin)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "event", dc_json_new_string(event));
(void)dc_json_object_set(json, "mode", dc_json_new_string(mode));
if (target != NULL)
(void)dc_json_object_set(json, "target",
dc_json_new_string(target));
if (id != NULL)
(void)dc_json_object_set(json, "id", dc_json_new_string(id));
if (pin != NULL)
(void)dc_json_object_set(json, "pin",
dc_json_new_string(pin));
emit(json);
}
static struct Accepted *
accepted_find(DcLocalConn *conn)
{
struct Accepted *a;
for (a = accepted; a != NULL; a = a->next)
if (a->conn == conn)
return a;
return NULL;
}
static struct Accepted *
accepted_by_id(const char *id)
{
struct Accepted *a;
for (a = accepted; a != NULL; a = a->next)
if (strcmp(a->id, id) == 0)
return a;
return NULL;
}
static void
server_hello(DcLocalConn *conn, const DcJson *hello, void *arg)
{
struct Accepted *a = calloc(1, sizeof(*a));
const char *id = dc_json_string(dc_json_get(hello, "id"));
const char *pin = dc_json_string(dc_json_get(hello, "pin"));
(void)arg;
if (a == NULL)
return;
a->conn = conn;
snprintf(a->id, sizeof(a->id), "%s", id != NULL ? id : "");
snprintf(a->pin, sizeof(a->pin), "%s", pin != NULL ? pin : "");
a->next = accepted;
accepted = a;
emit_peer("peer-online", "server", NULL, a->id, a->pin);
}
static void
emit_message(const char *from, const DcJson *json)
{
DcJson *out = dc_json_new_object();
const char *text = dc_json_string(dc_json_get(json, "text"));
(void)dc_json_object_set(out, "event",
dc_json_new_string("message"));
(void)dc_json_object_set(out, "from",
dc_json_new_string(from != NULL ? from : ""));
(void)dc_json_object_set(out, "text",
dc_json_new_string(text != NULL ? text : ""));
emit(out);
}
static const char *
call_state_name(DcCallState state)
{
switch (state) {
case DC_CALL_IDLE:
return "idle";
case DC_CALL_RINGING:
return "ringing";
case DC_CALL_IN_CALL:
return "in-call";
case DC_CALL_ENDED:
return "ended";
}
return "?";
}
static void
emit_call(DcCallState state, int in, int out)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "event", dc_json_new_string("call"));
(void)dc_json_object_set(json, "state",
dc_json_new_string(call_state_name(state)));
if (in >= 0) {
(void)dc_json_object_set(json, "audio_in",
dc_json_new_int(in));
(void)dc_json_object_set(json, "audio_out",
dc_json_new_int(out));
}
emit(json);
}
static void
send_media_key(DcLocalConn *conn, int port)
{
DcJson *json;
if (conn == NULL)
return;
json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("media-key"));
(void)dc_json_object_set(json, "pub",
dc_json_new_string(call_pub));
(void)dc_json_object_set(json, "port", dc_json_new_int(port));
(void)dc_local_conn_send_json(conn, json);
dc_json_free(json);
}
static void
start_call(DcLocalConn *conn, int initiator)
{
DcMediaKeys keys;
DcMediaSend snd;
DcMediaRecv rcv;
char host[128] = "127.0.0.1";
char err[256] = "";
if (call != NULL || conn == NULL || call_port <= 0)
return;
if (local_port <= 0) {
emit_call(DC_CALL_ENDED, -1, -1);
return;
}
if (dc_media_keys_from_b64(call_priv, call_peer_pub, initiator,
&keys) != 0) {
emit_call(DC_CALL_ENDED, -1, -1);
return;
}
(void)dc_local_conn_remote_addr(conn, host, sizeof(host));
dc_media_send_init(&snd, keys.send);
dc_media_recv_init(&rcv, keys.recv);
call = dc_call_new_bound(local_port, host, call_port, &snd, &rcv,
err, sizeof(err));
if (call == NULL) {
emit_call(DC_CALL_ENDED, -1, -1);
return;
}
call_initiator = initiator;
last_call_state = DC_CALL_IDLE;
call_in_frames = 0;
call_out_frames = 0;
if (audio_in_path != NULL)
audio_in_fp = fopen(audio_in_path, "rb");
if (audio_out_path != NULL)
audio_out_fp = fopen(audio_out_path, "wb");
if (initiator)
(void)dc_call_ring(call);
emit_call(dc_call_state(call), -1, -1);
}
static void
handle_media_key(const DcJson *json, DcLocalConn *conn)
{
const char *pub = dc_json_string(dc_json_get(json, "pub"));
int port = (int)dc_json_int(dc_json_get(json, "port"));
if (pub == NULL || strlen(pub) != 44)
return;
snprintf(call_peer_pub, sizeof(call_peer_pub), "%s", pub);
call_port = port > 0 && port < 65536 ? port : 0;
if (call == NULL && call_offered) {
call_offered = 0;
start_call(conn, 1);
} else if (call == NULL && call_peer_pub[0] != '\0') {
char mypub[DC_MEDIA_PUB_B64_LEN];
if (dc_media_keypair_b64(mypub, call_priv) != 0)
return;
snprintf(call_pub, sizeof(call_pub), "%s", mypub);
start_call(conn, 0);
send_media_key(conn, local_port);
}
}
/* the audio files and the media packets, once per loop */
static void
call_pump(void)
{
int16_t pcm[DC_AUDIO_FRAME_SAMPLES];
DcCallState state;
if (call == NULL)
return;
(void)dc_call_drain(call);
if (audio_out_fp != NULL) {
while (dc_call_audio_out(call, pcm) == 1) {
if (fwrite(pcm, sizeof(int16_t),
DC_AUDIO_FRAME_SAMPLES, audio_out_fp) !=
DC_AUDIO_FRAME_SAMPLES)
break;
call_out_frames++;
}
} else {
while (dc_call_audio_out(call, pcm) == 1)
call_out_frames++;
}
if (audio_in_fp != NULL &&
dc_call_state(call) == DC_CALL_IN_CALL) {
size_t n = fread(pcm, sizeof(int16_t),
DC_AUDIO_FRAME_SAMPLES, audio_in_fp);
if (n > 0) {
if (n < DC_AUDIO_FRAME_SAMPLES)
memset(pcm + n, 0, (DC_AUDIO_FRAME_SAMPLES - n) *
sizeof(int16_t));
if (dc_call_audio_in(call, pcm) == 0)
call_in_frames++;
} else {
fclose(audio_in_fp);
audio_in_fp = NULL;
}
}
dc_call_tick(call);
if ((call_in_frames + call_out_frames) % 50 == 0 &&
(call_in_frames + call_out_frames) > 0) {
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "event",
dc_json_new_string("audio"));
(void)dc_json_object_set(json, "in",
dc_json_new_int(call_in_frames));
(void)dc_json_object_set(json, "out",
dc_json_new_int(call_out_frames));
emit(json);
}
state = dc_call_state(call);
if (state != last_call_state) {
last_call_state = state;
if (state == DC_CALL_RINGING && !call_initiator && call_answer)
(void)dc_call_accept(call);
emit_call(state, call_in_frames, call_out_frames);
}
}
static void
common_line(const char *from, DcLocalConn *conn, const DcJson *json)
{
const char *type = dc_json_string(dc_json_get(json, "type"));
if (type == NULL)
return;
if (strcmp(type, "media-key") == 0) {
handle_media_key(json, conn);
return;
}
if (strcmp(type, "msg") == 0) {
emit_message(from, json);
if (conn != NULL)
(void)dc_local_send_msg_ack(conn, dc_json_string(
dc_json_get(json, "client_id")));
} else if (strcmp(type, "typing") == 0) {
DcJson *out = dc_json_new_object();
(void)dc_json_object_set(out, "event",
dc_json_new_string("typing"));
(void)dc_json_object_set(out, "from",
dc_json_new_string(from));
(void)dc_json_object_set(out, "on", dc_json_new_bool(
dc_json_bool(dc_json_get(json, "on"))));
emit(out);
} else if (strcmp(type, "file-offer") == 0) {
DcJson *out = dc_json_new_object();
(void)dc_json_object_set(out, "event",
dc_json_new_string("file-offer"));
(void)dc_json_object_set(out, "from",
dc_json_new_string(from));
(void)dc_json_object_set(out, "name", dc_json_new_string(
dc_json_string(dc_json_get(json, "name"))));
(void)dc_json_object_set(out, "size",
dc_json_new_int(dc_json_get(json, "size") != NULL ?
dc_json_int(dc_json_get(json, "size")) : 0));
emit(out);
}
}
static void
server_line(DcLocalConn *conn, const DcJson *json, void *arg)
{
struct Accepted *a = accepted_find(conn);
(void)arg;
common_line(a != NULL ? a->id : "?", conn, json);
}
static void
server_closed(DcLocalConn *conn, void *arg)
{
struct Accepted **slot = &accepted;
(void)arg;
while (*slot != NULL) {
if ((*slot)->conn == conn) {
struct Accepted *dead = *slot;
emit_peer("peer-offline", "server", NULL, dead->id,
NULL);
*slot = dead->next;
free(dead);
return;
}
slot = &(*slot)->next;
}
}
static void
link_line(DcLocalPeer *peer, const DcJson *json, void *arg)
{
struct Link *link = arg;
(void)peer;
common_line(link->id, dc_local_peer_conn(peer), json);
}
static void
link_state(DcLocalPeer *peer, int online, void *arg)
{
struct Link *link = arg;
DcLocalConn *conn = dc_local_peer_conn(peer);
const char *id = conn != NULL ? dc_local_conn_peer_id(conn) : NULL;
const char *pin = conn != NULL ? dc_local_conn_peer_pin(conn) : NULL;
link->online = online;
if (online && id != NULL)
snprintf(link->id, sizeof(link->id), "%s", id);
if (online && call_flag_enabled && call_offered == 0 && call == NULL &&
call_pub[0] == '\0') {
if (dc_media_keypair_b64(call_pub, call_priv) == 0) {
call_offered = 1;
send_media_key(dc_local_peer_conn(peer), local_port);
}
}
emit_peer(online ? "peer-online" : "peer-offline", "client",
link->target, link->id, online ? pin : NULL);
}
static struct Link *
link_by_name(const char *name)
{
struct Link *link;
for (link = links; link != NULL; link = link->next)
if (strcmp(link->target, name) == 0 ||
(link->id[0] != '\0' && strcmp(link->id, name) == 0))
return link;
return NULL;
}
static void
stdin_readable(int fd, short revents, void *arg)
{
char buf[4096];
ssize_t n;
(void)revents;
(void)arg;
n = read(fd, buf, sizeof(buf));
if (n <= 0) {
quit_flag = 1;
return;
}
if (dc_frame_feed(&stdin_frame, buf, (size_t)n) != 0)
return;
for (;;) {
size_t len = 0;
char *line = dc_frame_next(&stdin_frame, &len);
DcJson *cmd;
const char *what;
if (line == NULL)
break;
cmd = dc_json_parse(line, len, NULL, 0);
free(line);
if (cmd == NULL) {
emit_error("invalid command");
continue;
}
what = dc_json_string(dc_json_get(cmd, "cmd"));
if (what == NULL) {
emit_error("missing cmd");
} else if (strcmp(what, "quit") == 0) {
quit_flag = 1;
} else if (strcmp(what, "send") == 0) {
const char *peer = dc_json_string(dc_json_get(cmd,
"peer"));
const char *text = dc_json_string(dc_json_get(cmd,
"text"));
struct Link *link = link_by_name(peer);
DcJson *msg;
if (link != NULL) {
msg = dc_json_new_object();
(void)dc_json_object_set(msg, "type",
dc_json_new_string("msg"));
(void)dc_json_object_set(msg, "text",
dc_json_new_string(text != NULL ?
text : ""));
if (dc_local_peer_send(link->peer, msg) != 0)
emit_error("peer is offline");
dc_json_free(msg);
} else {
struct Accepted *a = accepted_by_id(peer);
if (a != NULL) {
if (dc_local_send_msg(a->conn, text,
NULL) != 0)
emit_error("send failed");
} else {
emit_error("unknown peer");
}
}
} else {
emit_error("unknown cmd");
}
dc_json_free(cmd);
}
}
static int
split_host_port(const char *text, char *host, size_t hostlen, int *port)
{
const char *colon = strrchr(text, ':');
char *end = NULL;
long value;
if (colon == NULL) {
snprintf(host, hostlen, "127.0.0.1");
value = strtol(text, &end, 10);
} else {
size_t len = (size_t)(colon - text);
if (len >= hostlen)
return -1;
memcpy(host, text, len);
host[len] = '\0';
if (host[0] == '\0')
snprintf(host, hostlen, "127.0.0.1");
value = strtol(colon + 1, &end, 10);
}
if (end == NULL || *end != '\0' || value < 0 || value > 65535)
return -1;
*port = (int)value;
return 0;
}
int
main(int argc, char **argv)
{
const char *config = NULL;
char default_config[512];
const char *listen_text = NULL;
const char *peer_text[8];
int npeers = 0;
DcIdentity *identity;
int i;
int port = 0;
char listen_host[128] = "127.0.0.1";
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--config") == 0 && i + 1 < argc) {
config = argv[++i];
} else if (strcmp(argv[i], "--listen") == 0 &&
i + 1 < argc) {
listen_text = argv[++i];
} else if (strcmp(argv[i], "--call") == 0) {
call_flag_enabled = 1;
} else if (strcmp(argv[i], "--audio-in") == 0 &&
i + 1 < argc) {
audio_in_path = argv[++i];
} else if (strcmp(argv[i], "--audio-out") == 0 &&
i + 1 < argc) {
audio_out_path = argv[++i];
} else if (strcmp(argv[i], "--peer") == 0 &&
i + 1 < argc && npeers < 8) {
peer_text[npeers++] = argv[++i];
} else {
fprintf(stderr, "usage: %s [--config DIR] "
"[--listen [HOST:]PORT] [--peer HOST:PORT ...]\n",
argv[0]);
return 2;
}
}
if (config == NULL) {
const char *home = getenv("HOME");
if (home == NULL)
return 1;
snprintf(default_config, sizeof(default_config),
"%s/.dt/dtchat", home);
config = default_config;
}
signal(SIGPIPE, SIG_IGN);
identity = dc_identity_load_or_create(config);
if (identity == NULL) {
fprintf(stderr, "dtchat-headless: cannot load the identity\n");
return 1;
}
loop = dc_loop_new();
if (loop == NULL)
return 1;
if (listen_text != NULL) {
if (split_host_port(listen_text, listen_host,
sizeof(listen_host), &port) != 0) {
fprintf(stderr, "dtchat-headless: bad --listen\n");
return 2;
}
server = dc_local_server_new(loop, identity, listen_host, port,
NULL, NULL, server_hello, server_line, server_closed, NULL);
if (server == NULL) {
fprintf(stderr, "dtchat-headless: cannot listen\n");
return 1;
}
port = dc_local_server_port(server);
local_port = port;
}
for (i = 0; i < npeers; i++) {
char host[128];
int p;
struct Link *link;
if (split_host_port(peer_text[i], host, sizeof(host), &p) != 0 ||
p <= 0) {
fprintf(stderr, "dtchat-headless: bad --peer\n");
return 2;
}
link = calloc(1, sizeof(*link));
if (link == NULL)
return 1;
snprintf(link->target, sizeof(link->target), "%s", peer_text[i]);
link->next = links;
links = link;
link->peer = dc_local_peer_new(loop, identity, host, p, NULL,
link_line, link_state, link);
if (link->peer == NULL || dc_local_peer_start(link->peer) != 0)
emit_error("cannot start the peer link");
}
{
DcJson *ready = dc_json_new_object();
(void)dc_json_object_set(ready, "event",
dc_json_new_string("ready"));
(void)dc_json_object_set(ready, "listen", dc_json_new_int(port));
(void)dc_json_object_set(ready, "id", dc_json_new_string(
dc_identity_public_b64(identity)));
(void)dc_json_object_set(ready, "pin", dc_json_new_string(
dc_identity_pin(identity)));
emit(ready);
}
dc_frame_init(&stdin_frame);
stdin_id = dc_loop_add_fd(loop, STDIN_FILENO, POLLIN, stdin_readable,
NULL);
while (!quit_flag) {
(void)dc_loop_run(loop, 50);
call_pump();
}
if (stdin_id > 0)
(void)dc_loop_del_fd(loop, stdin_id);
while (links != NULL) {
struct Link *next = links->next;
dc_local_peer_free(links->peer);
free(links);
links = next;
}
if (call != NULL)
dc_call_free(call);
if (audio_in_fp != NULL)
fclose(audio_in_fp);
if (audio_out_fp != NULL)
fclose(audio_out_fp);
dc_local_server_free(server);
while (accepted != NULL) {
struct Accepted *next = accepted->next;
free(accepted);
accepted = next;
}
dc_frame_free(&stdin_frame);
dc_loop_free(loop);
dc_identity_free(identity);
return 0;
}