diff --git a/README.md b/README.md index d0c4c65..821b671 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ are thin native shells over one small C library, libdmodemctl, so they behave the same. - **Modem**: the call's state, dial, answer and hang up, and the line it uses +- **Phone**: voice calls through the sound card (dial, answer, keypad), and an + answering machine that takes messages on this computer when turned on (off by default) - **Terminal**: the AT console, and the modem's own setup screens (AT!CF, AT!CT) - **Settings**: every modem setting as a native control, from AT!M - **Call Stats**: the last call's rate, modulation, error control and line figures (AT#UD, ATI11) @@ -24,6 +26,8 @@ behave the same. The Linux app's Settings page The Windows app's Terminal with the modem's setup screen +The Linux app's Phone page The Windows app's Phone page taking a message + ## Quick start Linux: diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 02d1da5..9d1cbfe 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -9,6 +9,7 @@ set(DMODEMCTL_SOURCES src/diag.c src/vt.c src/daemon.c + src/voice.c src/util.c) if(DMODEMCTL_SHARED) @@ -24,3 +25,6 @@ if(MSVC) else() target_compile_options(dmodemctl PRIVATE -Wall -Wextra -Wshadow) endif() +if(UNIX) + target_link_libraries(dmodemctl PRIVATE m) +endif() diff --git a/core/include/dmodemctl.h b/core/include/dmodemctl.h index 7c9f81d..fca8ef5 100644 --- a/core/include/dmodemctl.h +++ b/core/include/dmodemctl.h @@ -25,6 +25,9 @@ * has no terminal widget (Windows and macOS): the AT console and the * full-screen configurator (AT!CF). * - dmc_daemon_*: starting dmodemd and reading what it prints. + * - dmc_voice_*: voice calls on the session (V.253's voice mode: the + * call's audio both ways, 8 kHz), the answering machine that takes + * a message, and WAV files for greetings and messages. * * Strings are UTF-8. A const char * the library returns stays valid * until the next call on the same object. @@ -49,7 +52,7 @@ extern "C" { #endif /* the library's version: major * 10000 + minor * 100 + patch */ -#define DMC_VERSION 10000 +#define DMC_VERSION 10100 DMC_API int dmc_version(void); /* @@ -71,7 +74,9 @@ enum { DMC_ONLINE, /* CONNECT: data mode */ DMC_ONLINE_COMMAND, /* escaped (+++) during a call */ DMC_HANGING_UP, /* going back on hook */ - DMC_CONFIGURATOR /* AT!C, AT!CF or AT!CT runs */ + DMC_CONFIGURATOR, /* AT!C, AT!CF or AT!CT runs */ + DMC_VOICE, /* a voice call: its audio both ways */ + DMC_VOICEMAIL /* the answering machine has the call */ }; /* what dmc_next_event() reports */ @@ -86,7 +91,15 @@ enum { /* a result code nobody waited for (RING, NO CARRIER...): result */ DMC_EV_RESULT, /* caller ID after a RING: text "NMBR=5551234" and the like */ - DMC_EV_CALLER + DMC_EV_CALLER, + /* in a voice call, what the modem heard on the line: text its + code ("5" a DTMF digit, "l" the far end hung up, "b" a busy + tone), result its name ("digit", "hangup", "busy") */ + DMC_EV_VOICE, + /* the answering machine is done: ok 1 with a message + (dmc_voice_message()), 0 if the caller left none; text the + caller's number, if caller ID gave it */ + DMC_EV_MESSAGE }; typedef struct dmc_event { @@ -155,6 +168,81 @@ DMC_API int dmc_connect_rate(const dmc_session *s); DMC_API const char *dmc_caller_number(const dmc_session *s); DMC_API const char *dmc_caller_name(const dmc_session *s); +/* + * Voice calls + * + * A voice call is the modem in voice mode (AT+FCLASS=8) with its audio + * both ways (AT+VTR), G.711 mu-law on the DTE: the library sends ours + * at the line's pace from dmc_poll() (call it every 20 ms or so in a + * call: dmc_poll() says so) and gives the far end's to dmc_voice_read(), + * both as 16-bit samples at 8000 a second. dmc_hangup() ends a call, + * and the far end's hanging up does too (DMC_EV_VOICE "l"); either way + * the modem goes back to data mode. + */ + +/* the sample rate of voice calls, messages and greetings */ +#define DMC_VOICE_RATE 8000 + +/* dial a voice call (OK when the far end answers, BUSY, NO ANSWER); + answer the ringing call as a voice call: a tag as dmc_command()'s, + -1 if the modem is not idle (or ringing, to answer) */ +DMC_API int dmc_voice_dial(dmc_session *s, const char *number); +DMC_API int dmc_voice_answer(dmc_session *s); + +/* the far end's samples: up to max into pcm, how many (a second at + most is kept: the oldest are dropped if they are not read) */ +DMC_API int dmc_voice_read(dmc_session *s, int16_t *pcm, int max); +/* our samples (the microphone's), sent at the line's pace; silence + when there are none, and the oldest dropped when more than a third + of a second waits */ +DMC_API void dmc_voice_write(dmc_session *s, const int16_t *pcm, int n); +/* a DTMF digit (0-9, *, #, A-D) played into the call, after any + others still playing; 0, or -1 for no call or no digit */ +DMC_API int dmc_voice_dtmf(dmc_session *s, char digit); + +/* + * The answering machine + * + * It answers the ringing call in voice mode, plays the greeting, a + * beep, and records the caller's message: until they hang up, are + * silent for silence_s seconds, or max_s seconds have gone. Then it + * hangs up, with DMC_EV_MESSAGE. While it runs (DMC_VOICEMAIL) the + * caller can be heard with dmc_voice_read() (screening), and + * dmc_voice_pickup() makes it a voice call. + */ + +/* the greeting (8 kHz samples, copied; none: the beep alone) and the + message's limits (0: 120 s and 7 s) */ +DMC_API void dmc_voicemail_set(dmc_session *s, const int16_t *greeting, + int n, int max_s, int silence_s); +/* answer the ringing call with the answering machine: a tag as + dmc_voice_answer()'s */ +DMC_API int dmc_voicemail_answer(dmc_session *s); +/* the answering machine answers by itself after rings RINGs (0 never, + the default) */ +DMC_API void dmc_voicemail_auto(dmc_session *s, int rings); +/* the call the answering machine has, taken as a voice call (its + message dropped): 0, or -1 if it has none */ +DMC_API int dmc_voice_pickup(dmc_session *s); +/* the last message's samples into *pcm (valid until the next message): + how many */ +DMC_API int dmc_voice_message(const dmc_session *s, const int16_t **pcm); +/* the RINGs of the call ringing now */ +DMC_API int dmc_ring_count(const dmc_session *s); + +/* + * WAV files (greetings and messages) + */ + +/* the 44-byte header of a WAV file of n 16-bit samples, 8 kHz, mono, + into buf (44 bytes): 44 */ +DMC_API int dmc_wav_header(char *buf, int n); +/* a WAV file's samples at 8 kHz, mono, 16-bit (from 8 or 16-bit PCM, + A-law or mu-law, any rate and channels): how many, *pcm then + allocated (dmc_free() it); -1 if it is not a WAV file of those */ +DMC_API int dmc_wav_decode(const char *data, int n, int16_t **pcm); +DMC_API void dmc_free(void *p); + /* * The settings model (AT!M) */ diff --git a/core/src/session.c b/core/src/session.c index 642e9f5..fc0b4ce 100644 --- a/core/src/session.c +++ b/core/src/session.c @@ -15,6 +15,13 @@ * for; while a configurator runs, only the OK that ends it (or the * ERROR that refuses it). Results need the modem's verbose result * codes (V1, its default). + * + * A voice call is AT+FCLASS=8 and AT+VSM=4 (G.711 mu-law), then ATD + * (its OK the far end's answer) or AT+VLS=1 (the ringing call + * answered), then AT+VTR: after its CONNECT the bytes both ways are + * samples, doubled, and the modem's codes are what it heard + * on the line. ^ from us ends the stream (the modem's + * and OK), and ATH puts the modem on hook, in data mode again. */ #include #include @@ -22,6 +29,7 @@ #include "dmodemctl.h" #include "util.h" +#include "voice.h" /* the usual time a command may take, and dialling's or answering's */ #define COMMAND_MS 5000 @@ -36,6 +44,58 @@ screens come with no line ends, and its OK after the last one) */ #define LINE_MAX 4096 +/* voice: how far ahead of the line our samples go (60 ms), how many of + the far end's are kept (1 s), how many of ours may wait (a third of + a second: then they are cut to 100 ms) */ +#define VOICE_LEAD (DMC_VOICE_RATE * 60 / 1000) +#define VOICE_RX_MAX DMC_VOICE_RATE +#define VOICE_TX_MAX (DMC_VOICE_RATE / 3) +#define VOICE_TX_KEEP (DMC_VOICE_RATE / 10) +/* how long the modem may take to end the stream (, OK) */ +#define VOICE_END_MS 3000 +/* a DTMF digit's tone and the gap after it, in samples, and its + level; the answering machine's beep */ +#define DTMF_ON (DMC_VOICE_RATE / 10) +#define DTMF_OFF (DMC_VOICE_RATE * 6 / 100) +#define DTMF_AMP 16000 +#define BEEP_HZ 1000 +#define BEEP_LEN (DMC_VOICE_RATE / 2) +#define BEEP_AMP 8000 +/* the answering machine: quieter than this is silence; its usual + longest message and silence (s); the shortest message kept (1 s); + how much of a busy or dial tone to cut from a message's end (2 s); + the silence kept at its end (0.5 s) */ +#define QUIET_LEVEL 400 +#define MESSAGE_MAX_S 120 +#define MESSAGE_SILENCE_S 7 +#define MESSAGE_MIN (DMC_VOICE_RATE) +#define TONE_TRIM (2 * DMC_VOICE_RATE) +#define QUIET_KEEP (DMC_VOICE_RATE / 2) + +#define DLE 0x10 +#define ETX 0x03 + +/* the session's own flags on its commands (above dmc_command()'s) */ +enum { + CMD_VSETUP = 0x100, /* AT+FCLASS=8, AT+VSM: voice mode */ + CMD_VCALL = 0x200, /* ATD or AT+VLS=1: the call */ + CMD_VTR = 0x400, /* AT+VTR: the stream */ + CMD_VHANG = 0x800 /* ATH: the call over, data mode */ +}; + +/* what a voice call is for, and where it is */ +enum { V_NONE, V_LIVE, V_MACHINE }; +enum { + VS_NONE, + VS_SETUP, /* the commands before the stream */ + VS_STREAM, /* samples both ways */ + VS_ENDING, /* ^ sent, the modem's awaited */ + VS_ENDED, /* come, its OK awaited */ + VS_HANGUP /* ATH */ +}; +/* the answering machine's steps */ +enum { MP_GREETING, MP_BEEP, MP_RECORD }; + struct command { int tag; /* 0: the session's own */ char *cmd; /* with its AT */ @@ -72,6 +132,22 @@ struct dmc_session { int64_t ring_until; char *connect_text, *caller_number, *caller_name; int connect_rate; + int rings; + /* a voice call */ + int voice, vstep; + int vdle, vpacket; /* a came; inside a X packet */ + int vhang; /* to be ended once its stream starts */ + int64_t vstart, vsent, vend_at; + dmc_ring rx, tx; + char dtmf[32]; + int dtmf_n, tone_gap; + dmc_tone tone, beep; + /* the answering machine */ + int16_t *greeting; + int greeting_n, max_s, silence_s, auto_rings; + int mphase, gpos, mdone; + int16_t *rec, *msg; + int rec_n, rec_cap, quiet, msg_n; }; static void command_free(struct command *c) @@ -112,10 +188,18 @@ static void push_event(dmc_session *s, int type, int tag, int ok, s->events_tail = e; } +static void machine_done(dmc_session *s, int trim); +static void voice_reset(dmc_session *s); + static void set_state(dmc_session *s, int state) { if (s->state == state) return; + if (state == DMC_IDLE || state == DMC_CLOSED) { + if (s->voice == V_MACHINE && !s->mdone) + machine_done(s, 0); + voice_reset(s); + } s->state = state; if (state != DMC_RINGING) { s->ring_until = 0; @@ -127,6 +211,23 @@ static void set_state(dmc_session *s, int state) push_event(s, DMC_EV_STATE, 0, 1, "", ""); } +/* the voice call's state: the far end's samples, ours, the tones */ +static void voice_reset(dmc_session *s) +{ + s->voice = V_NONE; + s->vstep = VS_NONE; + s->vdle = s->vpacket = s->vhang = 0; + ring_clear(&s->rx); + ring_clear(&s->tx); + s->dtmf_n = s->tone_gap = 0; + s->tone.left = s->beep.left = 0; + free(s->rec); + s->rec = NULL; + s->rec_n = s->rec_cap = s->quiet = 0; + s->mphase = MP_GREETING; + s->gpos = s->mdone = 0; +} + static void clear_queue(dmc_session *s) { while (s->queue) { @@ -145,6 +246,8 @@ dmc_session *dmc_session_new(void) if (!s) abort(); s->next_tag = 1; + ring_init(&s->rx, VOICE_RX_MAX); + ring_init(&s->tx, DMC_VOICE_RATE); s->connect_text = dup_str(""); s->caller_number = dup_str(""); s->caller_name = dup_str(""); @@ -170,6 +273,11 @@ void dmc_session_free(dmc_session *s) free(s->connect_text); free(s->caller_number); free(s->caller_name); + free(s->rec); + free(s->msg); + free(s->greeting); + ring_free(&s->rx); + ring_free(&s->tx); free(s); } @@ -181,6 +289,7 @@ void dmc_open(dmc_session *s, int64_t now_ms) buf_clear(&s->typed); s->now = now_ms; s->hang = HANG_NONE; + voice_reset(s); set_state(s, DMC_IDLE); } @@ -260,6 +369,9 @@ static void pump(dmc_session *s) return; if (s->hang == HANG_GUARD || s->hang == HANG_ESCAPED) return; + /* (the stream's bytes are samples, not commands) */ + if (s->vstep == VS_STREAM || s->vstep == VS_ENDING) + return; struct command *c = s->queue; s->queue = c->next; c->next = NULL; @@ -270,6 +382,9 @@ static void pump(dmc_session *s) buf_adds(&s->out, c->cmd); buf_addc(&s->out, '\r'); command_sent(s, c->cmd); + /* (AT+VLS=1 answers the ringing call) */ + if ((c->flags & CMD_VCALL) && s->state != DMC_DIALING) + set_state(s, DMC_ANSWERING); } static int enqueue(dmc_session *s, const char *cmd, int flags, @@ -316,7 +431,8 @@ static int enqueue(dmc_session *s, const char *cmd, int flags, int dmc_command(dmc_session *s, const char *cmd, int flags, int timeout_ms) { if (!cmd || s->state == DMC_CLOSED || s->state == DMC_ONLINE || - s->state == DMC_CONFIGURATOR) + s->state == DMC_CONFIGURATOR || s->state == DMC_VOICE || + s->state == DMC_VOICEMAIL || s->voice) return -1; int tag = s->next_tag++; if (s->next_tag <= 0) @@ -341,8 +457,17 @@ int dmc_answer(dmc_session *s) return dmc_command(s, "ATA", 0, 0); } +static void voice_end(dmc_session *s); + void dmc_hangup(dmc_session *s) { + if (s->voice && s->state != DMC_DIALING) { + if (s->voice == V_MACHINE && !s->mdone && + s->mphase == MP_RECORD) + machine_done(s, 0); + voice_end(s); + return; + } switch (s->state) { case DMC_ONLINE: if (s->hang == HANG_NONE) { @@ -435,11 +560,18 @@ static void unsolicited(dmc_session *s, const char *l, int kind) if (s->state == DMC_IDLE) { set_str(&s->caller_number, ""); set_str(&s->caller_name, ""); + s->rings = 0; } set_state(s, DMC_RINGING); s->ring_until = s->now + RING_GAP_MS; + s->rings++; } push_event(s, DMC_EV_RESULT, 0, 1, "", l); + /* the answering machine's turn */ + if (s->state == DMC_RINGING && s->auto_rings > 0 && + s->rings >= s->auto_rings && !s->voice && !s->active && + !s->queue) + dmc_voicemail_answer(s); return; } if (caller_line(s, l)) @@ -470,11 +602,52 @@ static void unsolicited(dmc_session *s, const char *l, int kind) "", l); } +static void voice_fail(dmc_session *s, const char *result); +static void stream_start(dmc_session *s); + +/* a voice command's final result: 1 if it was one */ +static int voice_finish(dmc_session *s, struct command *c, const char *result, + int kind) +{ + int ok; + if (!(c->flags & (CMD_VSETUP | CMD_VCALL | CMD_VTR | CMD_VHANG))) + return 0; + ok = kind == R_OK || ((c->flags & CMD_VTR) && kind == R_CONNECT); + if (c->tag) + push_event(s, DMC_EV_RESPONSE, c->tag, ok, + buf_str(&s->response), result); + buf_clear(&s->response); + if (c->flags & CMD_VHANG) { + command_free(c); + set_state(s, DMC_IDLE); + } else if (!s->voice) { + /* (a call given up while its command ran) */ + command_free(c); + } else if (!ok) { + command_free(c); + voice_fail(s, result); + } else if (c->flags & CMD_VCALL) { + command_free(c); + set_state(s, s->voice == V_MACHINE ? DMC_VOICEMAIL : DMC_VOICE); + enqueue(s, "AT+VTR", DMC_QUIET | CMD_VTR, COMMAND_MS, 0, 1); + return 1; + } else if (c->flags & CMD_VTR) { + command_free(c); + stream_start(s); + } else { + command_free(c); + } + pump(s); + return 1; +} + /* the active command's final result */ static void finish(dmc_session *s, const char *result, int kind) { struct command *c = s->active; s->active = NULL; + if (voice_finish(s, c, result, kind)) + return; char first = first_command(c->cmd); switch (kind) { case R_CONNECT: @@ -509,6 +682,14 @@ static void finish(dmc_session *s, const char *result, int kind) /* a whole line from the modem (no CR or LF) */ static void line_in(dmc_session *s, const char *l) { + /* the stream over: its OK, then ATH */ + if (s->vstep == VS_ENDED) { + if (!strcmp(l, "OK") || !strcmp(l, "ERROR")) { + s->vstep = VS_HANGUP; + enqueue(s, "ATH", DMC_QUIET | CMD_VHANG, 0, 0, 1); + } + return; + } /* online: the call's data, but for its end */ if (s->state == DMC_ONLINE || (s->state == DMC_HANGING_UP && s->hang == HANG_GUARD)) { @@ -587,12 +768,18 @@ static void line_in(dmc_session *s, const char *l) unsolicited(s, l, kind); } +static void voice_byte(dmc_session *s, unsigned char c); + void dmc_feed(dmc_session *s, const char *data, int n) { if (s->state == DMC_CLOSED) return; for (int i = 0; i < n; i++) { char c = data[i]; + if (s->vstep == VS_STREAM || s->vstep == VS_ENDING) { + voice_byte(s, (unsigned char)c); + continue; + } int quiet = s->active && (s->active->flags & DMC_QUIET); if (!quiet) buf_addc(&s->term, c); @@ -613,6 +800,9 @@ void dmc_type(dmc_session *s, const char *data, int n) { if (s->state == DMC_CLOSED) return; + /* (nothing typed gets into a voice call's samples) */ + if (s->voice) + return; buf_add(&s->out, data, n); if (s->state == DMC_ONLINE) { /* the escape typed by hand: its OK is command mode */ @@ -637,6 +827,8 @@ void dmc_type(dmc_session *s, const char *data, int n) } } +static void voice_send(dmc_session *s); + int dmc_poll(dmc_session *s, int64_t now_ms) { s->now = now_ms; @@ -654,8 +846,31 @@ int dmc_poll(dmc_session *s, int64_t now_ms) } if (s->hang != HANG_NONE) next = s->hang_at - now_ms; + if (s->vstep == VS_STREAM) { + voice_send(s); + next = 20; + } else if ((s->vstep == VS_ENDING || s->vstep == VS_ENDED) && + now_ms >= s->vend_at) { + /* no end from the modem: on hook all the same */ + if (s->vstep == VS_ENDING) { + buf_addc(&s->out, DLE); + buf_addc(&s->out, '^'); + } + s->vstep = VS_HANGUP; + enqueue(s, "ATH", DMC_QUIET | CMD_VHANG, 0, 0, 1); + } else if (s->vstep == VS_ENDING || s->vstep == VS_ENDED) { + int64_t d = s->vend_at - now_ms; + if (next < 0 || d < next) + next = d; + } if (s->state == DMC_RINGING && s->ring_until && now_ms >= s->ring_until) set_state(s, DMC_IDLE); + /* (the answering machine's turn, if a command was in the way at + the RING) */ + if (s->state == DMC_RINGING && s->auto_rings > 0 && + s->rings >= s->auto_rings && !s->voice && !s->active && + !s->queue) + dmc_voicemail_answer(s); if (s->state == DMC_RINGING && s->ring_until) { int64_t d = s->ring_until - now_ms; if (next < 0 || d < next) @@ -664,16 +879,23 @@ int dmc_poll(dmc_session *s, int64_t now_ms) if (s->active) { if (now_ms >= s->active_until) { struct command *c = s->active; + int voice = c->flags & (CMD_VSETUP | CMD_VCALL | + CMD_VTR | CMD_VHANG); s->active = NULL; if (s->state == DMC_DIALING || s->state == DMC_ANSWERING) { buf_addc(&s->out, '\r'); - set_state(s, DMC_IDLE); + if (!voice) + set_state(s, DMC_IDLE); } if (c->tag) push_event(s, DMC_EV_RESPONSE, c->tag, 0, buf_str(&s->response), "timeout"); command_free(c); buf_clear(&s->response); + if (voice & CMD_VHANG) + set_state(s, DMC_IDLE); + else if (voice && s->voice) + voice_fail(s, "timeout"); } else { int64_t d = s->active_until - now_ms; if (next < 0 || d < next) @@ -733,6 +955,8 @@ const char *dmc_state_name(int state) case DMC_ONLINE_COMMAND: return "Online (command mode)"; case DMC_HANGING_UP: return "Hanging up"; case DMC_CONFIGURATOR: return "Configurator"; + case DMC_VOICE: return "Voice call"; + case DMC_VOICEMAIL: return "Taking a message"; } return ""; } @@ -761,3 +985,386 @@ int dmc_version(void) { return DMC_VERSION; } + +/* + * Voice calls + */ + +/* the voice call given up (a command of it failed): its commands still + queued answered with result, the modem on hook in data mode */ +static void voice_fail(dmc_session *s, const char *result) +{ + struct command **q = &s->queue; + while (*q) { + struct command *c = *q; + if (!(c->flags & (CMD_VSETUP | CMD_VCALL | CMD_VTR))) { + q = &c->next; + continue; + } + *q = c->next; + if (c->tag) + push_event(s, DMC_EV_RESPONSE, c->tag, 0, "", result); + command_free(c); + } + if (s->state == DMC_IDLE) { + if (s->voice == V_MACHINE && !s->mdone) + machine_done(s, 0); + voice_reset(s); + } else { + set_state(s, DMC_IDLE); + } + enqueue(s, "ATH", DMC_QUIET | CMD_VHANG, 0, 0, 1); +} + +/* AT+VTR's CONNECT: the samples flow */ +static void stream_start(dmc_session *s) +{ + s->vstep = VS_STREAM; + s->vstart = s->now; + s->vsent = 0; + s->vdle = s->vpacket = 0; + ring_clear(&s->rx); + ring_clear(&s->tx); + s->mphase = MP_GREETING; + s->gpos = 0; + if (s->vhang) + voice_end(s); +} + +/* the call ended from here: the stream (^), or a call still being + set up once its stream starts */ +static void voice_end(dmc_session *s) +{ + switch (s->vstep) { + case VS_SETUP: + s->vhang = 1; + break; + case VS_STREAM: + buf_addc(&s->out, DLE); + buf_addc(&s->out, '^'); + s->vstep = VS_ENDING; + s->vend_at = s->now + VOICE_END_MS; + set_state(s, DMC_HANGING_UP); + break; + default: + break; + } +} + +/* the answering machine's message over: trim samples of its end cut + (a busy tone's), then its quiet end but for QUIET_KEEP; the + DMC_EV_MESSAGE */ +static void machine_done(dmc_session *s, int trim) +{ + int n = s->rec_n - trim, ok; + if (s->mdone) + return; + s->mdone = 1; + if (s->mphase == MP_RECORD && s->quiet > QUIET_KEEP) { + int q = s->quiet - QUIET_KEEP; + if (trim < q) + n = s->rec_n - q; + } + ok = s->mphase == MP_RECORD && n >= MESSAGE_MIN; + free(s->msg); + s->msg = NULL; + s->msg_n = 0; + if (ok) { + s->msg = s->rec; + s->msg_n = n; + s->rec = NULL; + s->rec_n = s->rec_cap = 0; + } + push_event(s, DMC_EV_MESSAGE, 0, ok, s->caller_number, ""); +} + +/* a sample of the caller's for the message: the message over when it is + long enough, or the caller silent long enough */ +static void record(dmc_session *s, int16_t x) +{ + int max = (s->max_s > 0 ? s->max_s : MESSAGE_MAX_S) * DMC_VOICE_RATE; + int quiet = (s->silence_s > 0 ? s->silence_s : MESSAGE_SILENCE_S) * + DMC_VOICE_RATE; + if (s->mdone) + return; + if (s->rec_n == s->rec_cap) { + int cap = s->rec_cap ? s->rec_cap * 2 : DMC_VOICE_RATE * 8; + int16_t *p; + if (cap > max) + cap = max; + p = realloc(s->rec, (size_t)cap * sizeof(int16_t)); + if (!p) + abort(); + s->rec = p; + s->rec_cap = cap; + } + s->rec[s->rec_n++] = x; + if (x > -QUIET_LEVEL && x < QUIET_LEVEL) + s->quiet++; + else + s->quiet = 0; + if (s->rec_n >= max || s->quiet >= quiet) { + machine_done(s, 0); + voice_end(s); + } +} + +/* a sample of the far end's */ +static void voice_sample(dmc_session *s, unsigned char u) +{ + int16_t x = ulaw_decode(u); + ring_put(&s->rx, &x, 1); + if (s->voice == V_MACHINE && s->mphase == MP_RECORD) + record(s, x); +} + +/* a code from the modem: what it heard on the line */ +static void voice_event(dmc_session *s, unsigned char c) +{ + const char *name; + char code[2]; + if ((c >= '0' && c <= '9') || c == '*' || c == '#' || + (c >= 'A' && c <= 'D')) + name = "digit"; + else switch (c) { + case 'l': name = "hangup"; break; + case 'b': name = "busy"; break; + case 'd': name = "dial tone"; break; + case 'r': name = "ringing"; break; + case 'a': case 'f': name = "answer tone"; break; + case 'c': name = "fax"; break; + case 'e': name = "data"; break; + case 's': name = "silence"; break; + case 'q': name = "quiet"; break; + default: return; + } + code[0] = (char)c; + code[1] = '\0'; + push_event(s, DMC_EV_VOICE, 0, 1, code, name); + if (c == 'l' || c == 'b' || c == 'd') { + /* the far end has gone (a busy or dial tone: the + exchange's word for it) */ + if (s->voice == V_MACHINE && s->mphase == MP_RECORD) + machine_done(s, c == 'l' ? 0 : TONE_TRIM); + voice_end(s); + } +} + +/* a byte of the stream from the modem */ +static void voice_byte(dmc_session *s, unsigned char c) +{ + if (s->vdle) { + s->vdle = 0; + switch (c) { + case DLE: + if (!s->vpacket) + voice_sample(s, c); + break; + case ETX: + /* the stream's end: its OK to come */ + s->vstep = VS_ENDED; + s->vend_at = s->now + VOICE_END_MS; + if (s->state != DMC_HANGING_UP) + set_state(s, DMC_HANGING_UP); + buf_clear(&s->line); + break; + case 'X': + s->vpacket = 1; + break; + case '.': + s->vpacket = 0; + break; + default: + voice_event(s, c); + break; + } + return; + } + if (c == DLE) { + s->vdle = 1; + return; + } + if (!s->vpacket) + voice_sample(s, c); +} + +/* our next sample: the answering machine's greeting and beep, or the + microphone's; the DTMF digits over it */ +static int next_sample(dmc_session *s) +{ + int x = 0; + int16_t m; + if (s->voice == V_MACHINE) { + if (s->mphase == MP_GREETING) { + if (s->gpos < s->greeting_n) { + x = s->greeting[s->gpos++]; + } else { + s->mphase = MP_BEEP; + tone_start(&s->beep, BEEP_HZ, 0, BEEP_LEN, + BEEP_AMP); + } + } + if (s->mphase == MP_BEEP) { + if (s->beep.left > 0) { + x = tone_next(&s->beep); + } else { + s->mphase = MP_RECORD; + s->rec_n = 0; + s->quiet = 0; + } + } + } else if (ring_get(&s->tx, &m, 1)) { + x = m; + } + if (s->tone.left > 0) { + x += tone_next(&s->tone); + } else if (s->tone_gap > 0) { + s->tone_gap--; + } else if (s->dtmf_n) { + double lo, hi; + if (!dtmf_freqs(s->dtmf[0], &lo, &hi)) + tone_start(&s->tone, lo, hi, DTMF_ON, DTMF_AMP); + s->tone_gap = DTMF_OFF; + memmove(s->dtmf, s->dtmf + 1, (size_t)--s->dtmf_n); + } + return x > 32767 ? 32767 : x < -32768 ? -32768 : x; +} + +/* our samples to the modem, as many as the time says, a little + ahead */ +static void voice_send(dmc_session *s) +{ + int64_t due = (s->now - s->vstart) * DMC_VOICE_RATE / 1000 + + VOICE_LEAD; + /* (a second behind: the app stalled, and the line went on) */ + if (due - s->vsent > DMC_VOICE_RATE) + s->vsent = due - VOICE_LEAD; + while (s->vsent < due && s->vstep == VS_STREAM) { + unsigned char u = ulaw_encode((int16_t)next_sample(s)); + buf_addc(&s->out, (char)u); + if (u == DLE) + buf_addc(&s->out, (char)DLE); + s->vsent++; + } +} + +/* the voice call's start: voice mode, mu-law, then the call's command + (with the tag) */ +static int voice_begin(dmc_session *s, int voice, const char *cmd, + int timeout_ms) +{ + int tag = s->next_tag++; + if (s->next_tag <= 0) + s->next_tag = 1; + s->voice = voice; + s->vstep = VS_SETUP; + s->vhang = 0; + s->mdone = 0; + enqueue(s, "AT+FCLASS=8", DMC_QUIET | CMD_VSETUP, 0, 0, 0); + enqueue(s, "AT+VSM=4", DMC_QUIET | CMD_VSETUP, 0, 0, 0); + return enqueue(s, cmd, CMD_VCALL, timeout_ms, tag, 0); +} + +int dmc_voice_dial(dmc_session *s, const char *number) +{ + dmc_buf b = { 0 }; + int tag; + if (s->state != DMC_IDLE || s->voice) + return -1; + buf_adds(&b, "ATD"); + for (const char *p = number ? number : ""; *p; p++) + if (*p != '\r' && *p != '\n' && *p != ';') + buf_addc(&b, *p); + tag = voice_begin(s, V_LIVE, buf_str(&b), CALL_MS); + buf_free(&b); + return tag; +} + +static int answer_as(dmc_session *s, int voice) +{ + if (s->state != DMC_RINGING || s->voice) + return -1; + return voice_begin(s, voice, "AT+VLS=1", 30000); +} + +int dmc_voice_answer(dmc_session *s) +{ + return answer_as(s, V_LIVE); +} + +int dmc_voicemail_answer(dmc_session *s) +{ + return answer_as(s, V_MACHINE); +} + +int dmc_voice_read(dmc_session *s, int16_t *pcm, int max) +{ + return max > 0 ? ring_get(&s->rx, pcm, max) : 0; +} + +void dmc_voice_write(dmc_session *s, const int16_t *pcm, int n) +{ + if (s->vstep != VS_STREAM || n <= 0) + return; + ring_put(&s->tx, pcm, n); + if (s->tx.n > VOICE_TX_MAX) + ring_keep(&s->tx, VOICE_TX_KEEP); +} + +int dmc_voice_dtmf(dmc_session *s, char digit) +{ + double lo, hi; + if (!s->voice || s->dtmf_n >= (int)sizeof(s->dtmf) || + dtmf_freqs(digit, &lo, &hi)) + return -1; + s->dtmf[s->dtmf_n++] = digit; + return 0; +} + +void dmc_voicemail_set(dmc_session *s, const int16_t *greeting, int n, + int max_s, int silence_s) +{ + free(s->greeting); + s->greeting = NULL; + s->greeting_n = 0; + if (greeting && n > 0) { + s->greeting = malloc((size_t)n * sizeof(int16_t)); + if (!s->greeting) + abort(); + memcpy(s->greeting, greeting, (size_t)n * sizeof(int16_t)); + s->greeting_n = n; + } + s->max_s = max_s; + s->silence_s = silence_s; +} + +void dmc_voicemail_auto(dmc_session *s, int rings) +{ + s->auto_rings = rings > 0 ? rings : 0; +} + +int dmc_voice_pickup(dmc_session *s) +{ + if (s->voice != V_MACHINE || s->mdone) + return -1; + s->voice = V_LIVE; + s->mdone = 1; + s->beep.left = 0; + free(s->rec); + s->rec = NULL; + s->rec_n = s->rec_cap = 0; + if (s->state == DMC_VOICEMAIL) + set_state(s, DMC_VOICE); + return 0; +} + +int dmc_voice_message(const dmc_session *s, const int16_t **pcm) +{ + *pcm = s->msg; + return s->msg_n; +} + +int dmc_ring_count(const dmc_session *s) +{ + return s->state == DMC_RINGING ? s->rings : 0; +} diff --git a/core/src/voice.c b/core/src/voice.c new file mode 100644 index 0000000..4a98cac --- /dev/null +++ b/core/src/voice.c @@ -0,0 +1,307 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * voice.c - G.711, rings of samples, tones, and WAV files (dmodemctl.h) + */ +#include +#include +#include + +#include "dmodemctl.h" +#include "voice.h" + +/* + * G.711 + */ + +unsigned char ulaw_encode(int16_t x) +{ + int v = x, sign = 0, exp, mant; + if (v < 0) { + v = -v; + sign = 0x80; + } + v += 0x84; + if (v > 0x7fff) + v = 0x7fff; + for (exp = 7; exp > 0 && !(v & (0x4000 >> (7 - exp))); exp--) + ; + mant = (v >> (exp + 3)) & 0x0f; + return (unsigned char)~(sign | (exp << 4) | mant); +} + +int16_t ulaw_decode(unsigned char u) +{ + int v, exp, mant; + u = (unsigned char)~u; + exp = (u >> 4) & 7; + mant = u & 0x0f; + v = ((mant << 3) + 0x84) << exp; + v -= 0x84; + return (int16_t)((u & 0x80) ? -v : v); +} + +int16_t alaw_decode(unsigned char a) +{ + int v, exp, mant; + a ^= 0x55; + exp = (a >> 4) & 7; + mant = a & 0x0f; + v = exp ? ((mant << 4) + 0x108) << (exp - 1) : (mant << 4) + 8; + return (int16_t)((a & 0x80) ? v : -v); +} + +/* + * Rings + */ + +void ring_init(dmc_ring *r, int cap) +{ + memset(r, 0, sizeof(*r)); + r->p = calloc((size_t)cap, sizeof(int16_t)); + if (!r->p) + abort(); + r->cap = cap; +} + +void ring_free(dmc_ring *r) +{ + free(r->p); + memset(r, 0, sizeof(*r)); +} + +void ring_clear(dmc_ring *r) +{ + r->head = r->n = 0; +} + +void ring_put(dmc_ring *r, const int16_t *x, int n) +{ + int i; + if (!r->cap) + return; + for (i = 0; i < n; i++) { + int at = (r->head + r->n) % r->cap; + r->p[at] = x ? x[i] : 0; + if (r->n < r->cap) + r->n++; + else + r->head = (r->head + 1) % r->cap; + } +} + +int ring_get(dmc_ring *r, int16_t *out, int max) +{ + int i, n = r->n < max ? r->n : max; + for (i = 0; i < n; i++) { + out[i] = r->p[r->head]; + r->head = (r->head + 1) % r->cap; + } + r->n -= n; + return n; +} + +void ring_keep(dmc_ring *r, int n) +{ + if (r->n <= n) + return; + r->head = (r->head + r->n - n) % r->cap; + r->n = n; +} + +/* + * Tones + */ + +#define PI 3.14159265358979323846 + +void tone_start(dmc_tone *t, double f1, double f2, int samples, + double amp) +{ + memset(t, 0, sizeof(*t)); + t->k1 = 2 * PI * f1 / DMC_VOICE_RATE; + t->k2 = 2 * PI * f2 / DMC_VOICE_RATE; + t->c1 = t->c2 = 1; + t->two = f2 > 0; + t->left = samples; + t->amp = amp; +} + +/* (each oscillator a unit vector turned by its step each sample) */ +static double turn(double *c, double *s, double k) +{ + double c0 = *c, s0 = *s, ck = cos(k), sk = sin(k), m; + *c = c0 * ck - s0 * sk; + *s = c0 * sk + s0 * ck; + /* (kept on the circle) */ + m = sqrt(*c * *c + *s * *s); + if (m > 0) { + *c /= m; + *s /= m; + } + return s0; +} + +int tone_next(dmc_tone *t) +{ + double y; + if (t->left <= 0) + return 0; + t->left--; + y = turn(&t->c1, &t->s1, t->k1); + if (t->two) + y = (y + turn(&t->c2, &t->s2, t->k2)) / 2; + return (int)(y * t->amp); +} + +int dtmf_freqs(char digit, double *lo, double *hi) +{ + static const char keys[] = "123A456B789C*0#D"; + static const double row[] = { 697, 770, 852, 941 }; + static const double col[] = { 1209, 1336, 1477, 1633 }; + const char *k; + char d = digit; + if (d >= 'a' && d <= 'd') + d = (char)(d - 'a' + 'A'); + k = d ? strchr(keys, d) : NULL; + if (!k) + return -1; + *lo = row[(k - keys) / 4]; + *hi = col[(k - keys) % 4]; + return 0; +} + +/* + * WAV files + */ + +static void put16(char *p, unsigned v) +{ + p[0] = (char)(v & 0xff); + p[1] = (char)((v >> 8) & 0xff); +} + +static void put32(char *p, unsigned long v) +{ + put16(p, (unsigned)(v & 0xffff)); + put16(p + 2, (unsigned)((v >> 16) & 0xffff)); +} + +static unsigned get16(const char *p) +{ + return (unsigned char)p[0] | ((unsigned)(unsigned char)p[1] << 8); +} + +static unsigned long get32(const char *p) +{ + return get16(p) | ((unsigned long)get16(p + 2) << 16); +} + +int dmc_wav_header(char *buf, int n) +{ + unsigned long bytes = n > 0 ? (unsigned long)n * 2 : 0; + memcpy(buf, "RIFF", 4); + put32(buf + 4, 36 + bytes); + memcpy(buf + 8, "WAVEfmt ", 8); + put32(buf + 16, 16); + put16(buf + 20, 1); /* PCM */ + put16(buf + 22, 1); /* mono */ + put32(buf + 24, DMC_VOICE_RATE); + put32(buf + 28, DMC_VOICE_RATE * 2); + put16(buf + 32, 2); + put16(buf + 34, 16); + memcpy(buf + 36, "data", 4); + put32(buf + 40, bytes); + return 44; +} + +int dmc_wav_decode(const char *data, int n, int16_t **pcm) +{ + unsigned format = 0, channels = 0, bits = 0; + unsigned long rate = 0; + const char *samples = NULL; + long bytes = 0, frames, out_n, i; + int have_fmt = 0, width; + const char *p, *end; + int16_t *out; + + *pcm = NULL; + if (!data || n < 12 || memcmp(data, "RIFF", 4) || + memcmp(data + 8, "WAVE", 4)) + return -1; + p = data + 12; + end = data + n; + while (end - p >= 8) { + unsigned long len = get32(p + 4); + const char *body = p + 8; + long left = (long)(end - body); + if (!memcmp(p, "fmt ", 4) && len >= 16 && left >= 16) { + format = get16(body); + channels = get16(body + 2); + rate = get32(body + 4); + bits = get16(body + 14); + /* WAVE_FORMAT_EXTENSIBLE: its subformat's code */ + if (format == 0xfffe && len >= 26 && left >= 26) + format = get16(body + 24); + have_fmt = 1; + } else if (!memcmp(p, "data", 4)) { + samples = body; + bytes = len > (unsigned long)left ? left : (long)len; + break; + } + if (len > (unsigned long)left) + break; + p = body + len + (len & 1); + } + if (!have_fmt || !samples || !channels || channels > 8 || + rate < 1000 || rate > 192000) + return -1; + if (format == 1 && (bits == 8 || bits == 16)) + width = (int)bits / 8; + else if ((format == 6 || format == 7) && bits == 8) + width = 1; + else + return -1; + frames = bytes / (long)(width * (int)channels); + out_n = (long)((double)frames * DMC_VOICE_RATE / (double)rate); + out = malloc((size_t)(out_n > 0 ? out_n : 1) * sizeof(int16_t)); + if (!out) + return -1; + for (i = 0; i < out_n; i++) { + /* (linear between the two frames around it, each the mean + of its channels) */ + double at = (double)i * (double)rate / DMC_VOICE_RATE; + long f = (long)at; + double frac = at - (double)f, y = 0; + int k, c; + for (k = 0; k < 2; k++) { + long ff = f + k < frames ? f + k : frames - 1; + double sum = 0; + for (c = 0; c < (int)channels; c++) { + const char *q = samples + + (ff * (long)channels + c) * width; + int v; + if (format == 7) + v = ulaw_decode((unsigned char)*q); + else if (format == 6) + v = alaw_decode((unsigned char)*q); + else if (width == 1) + v = ((int)(unsigned char)*q - 128) * 256; + else + v = (int16_t)get16(q); + sum += v; + } + sum /= channels; + y += k ? frac * sum : (1 - frac) * sum; + } + out[i] = (int16_t)(y > 32767 ? 32767 : y < -32768 ? -32768 : y); + } + *pcm = out; + return (int)out_n; +} + +void dmc_free(void *p) +{ + free(p); +} diff --git a/core/src/voice.h b/core/src/voice.h new file mode 100644 index 0000000..572fff7 --- /dev/null +++ b/core/src/voice.h @@ -0,0 +1,49 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * voice.h - what the session's voice calls are made of: G.711 mu-law, + * rings of samples, the tones we play (DTMF, the beep) + */ +#ifndef DMC_VOICE_H +#define DMC_VOICE_H + +#include + +/* G.711 mu-law, the samples on the DTE in a call (AT+VSM=4) */ +unsigned char ulaw_encode(int16_t x); +int16_t ulaw_decode(unsigned char u); +/* and A-law, for WAV files */ +int16_t alaw_decode(unsigned char a); + +/* a ring of samples that keeps the newest cap of them */ +typedef struct dmc_ring { + int16_t *p; + int cap, head, n; +} dmc_ring; + +void ring_init(dmc_ring *r, int cap); +void ring_free(dmc_ring *r); +void ring_clear(dmc_ring *r); +/* n samples in: the oldest dropped when it is full */ +void ring_put(dmc_ring *r, const int16_t *x, int n); +/* up to max out of it: how many */ +int ring_get(dmc_ring *r, int16_t *out, int max); +/* the oldest taken out until n are left */ +void ring_keep(dmc_ring *r, int n); + +/* a tone of one or two frequencies, n samples long */ +typedef struct dmc_tone { + double c1, s1, k1, c2, s2, k2; /* each oscillator's state, step */ + int two, left; + double amp; +} dmc_tone; + +void tone_start(dmc_tone *t, double f1, double f2, int samples, + double amp); +/* its next sample (0 when it has ended) */ +int tone_next(dmc_tone *t); +/* a DTMF digit's two frequencies: 0, or -1 for none */ +int dtmf_freqs(char digit, double *lo, double *hi); + +#endif diff --git a/core/test/dmodemctl_test.c b/core/test/dmodemctl_test.c index 95603bd..c0e7667 100644 --- a/core/test/dmodemctl_test.c +++ b/core/test/dmodemctl_test.c @@ -473,6 +473,280 @@ static void test_daemon(void) CHECK(!dmc_daemon_error("13:21:22.774 sip: SIP on 127.0.0.1:5060")); } +/* the session's bytes to the modem, binary: how many into b */ +static int outb(dmc_session *s, unsigned char *b, int max) +{ + return dmc_output(s, (char *)b, max); +} + +static void feedb(dmc_session *s, const unsigned char *b, int n) +{ + dmc_feed(s, (const char *)b, n); +} + +/* the setup of a voice call: voice mode, mu-law, then cmd and its + result; the stream started */ +static void voice_setup(dmc_session *s, const char *cmd, int state) +{ + CHECK_STR(out(s), "AT+FCLASS=8\r"); + feed(s, "AT+FCLASS=8\r\r\nOK\r\n"); + CHECK_STR(out(s), "AT+VSM=4\r"); + feed(s, "AT+VSM=4\r\r\nOK\r\n"); + char want[64]; + snprintf(want, sizeof(want), "%s\r", cmd); + CHECK_STR(out(s), want); + snprintf(want, sizeof(want), "%s\r\r\nOK\r\n", cmd); + feed(s, want); + CHECK(dmc_state(s) == state); + CHECK_STR(out(s), "AT+VTR\r"); + term(s); + feed(s, "AT+VTR\r\r\nCONNECT\r\n"); + /* (none of it on the screen) */ + CHECK_STR(term(s), ""); +} + +/* a voice call dialled: the samples both ways, DTMF, hanging up */ +static void test_voice(void) +{ + dmc_session *s = dmc_session_new(); + dmc_event ev; + static unsigned char b[65536]; + int16_t pcm[256]; + dmc_open(s, 0); + int tag = dmc_voice_dial(s, "555-1000"); + CHECK(tag > 0); + CHECK(dmc_voice_dial(s, "1") == -1); + CHECK(dmc_command(s, "ATI3", 0, 0) == -1); + CHECK_STR(out(s), "AT+FCLASS=8\r"); + feed(s, "AT+FCLASS=8\r\r\nOK\r\n"); + CHECK_STR(out(s), "AT+VSM=4\r"); + feed(s, "AT+VSM=4\r\r\nOK\r\n"); + CHECK_STR(out(s), "ATD555-1000\r"); + CHECK(dmc_state(s) == DMC_DIALING); + feed(s, "ATD555-1000\r\r\nOK\r\n"); + CHECK(next_of(s, DMC_EV_RESPONSE, &ev)); + CHECK(ev.tag == tag && ev.ok); + CHECK(dmc_state(s) == DMC_VOICE); + CHECK_STR(dmc_state_name(DMC_VOICE), "Voice call"); + CHECK_STR(out(s), "AT+VTR\r"); + term(s); + /* the stream: samples (a DLE among them doubled), a digit */ + unsigned char in[] = { 'C', 'O', 'N', 'N', 'E', 'C', 'T', '\r', '\n', + 0xff, 0x80, 0x10, 0x10, 0x00, 0x10, '5', + 0x10, '~', 0x7f }; + feedb(s, in, sizeof(in)); + CHECK_STR(term(s), ""); + int n = dmc_voice_read(s, pcm, 256); + CHECK(n == 5); + CHECK(pcm[0] == 0); + CHECK(pcm[1] == 32124); + CHECK(pcm[3] == -32124); + CHECK(pcm[4] == 0); + CHECK(next_of(s, DMC_EV_VOICE, &ev)); + CHECK_STR(ev.text, "5"); + CHECK_STR(ev.result, "digit"); + CHECK(!next_of(s, DMC_EV_VOICE, &ev)); + /* ours: silence, 60 ms ahead, then at the line's pace */ + CHECK(dmc_poll(s, 0) == 20); + n = outb(s, b, sizeof(b)); + CHECK(n == 480); + CHECK(b[0] == 0xff && b[479] == 0xff); + for (int i = 0; i < 160; i++) + pcm[i] = 8000; + dmc_voice_write(s, pcm, 160); + dmc_poll(s, 20); + n = outb(s, b, sizeof(b)); + CHECK(n == 160); + CHECK(b[0] != 0xff && b[0] == b[159]); + /* a sample that is a DLE: doubled */ + pcm[0] = -15996; + dmc_voice_write(s, pcm, 1); + dmc_poll(s, 21); + n = outb(s, b, sizeof(b)); + CHECK(n == 9 && b[0] == 0x10 && b[1] == 0x10); + /* a DTMF digit: its tone in our samples */ + CHECK(dmc_voice_dtmf(s, '!') == -1); + CHECK(dmc_voice_dtmf(s, '1') == 0); + dmc_poll(s, 41); + n = outb(s, b, sizeof(b)); + int tone = 0; + for (int i = 0; i < n; i++) + if (b[i] != 0xff) + tone++; + CHECK(n == 160 && tone > 100); + /* hung up here: ^, the modem's and OK, ATH */ + dmc_hangup(s); + n = outb(s, b, sizeof(b)); + CHECK(n == 2 && b[0] == 0x10 && b[1] == '^'); + CHECK(dmc_state(s) == DMC_HANGING_UP); + unsigned char end[] = { 0xff, 0x10, 0x03, '\r', '\n', 'O', 'K', '\r', + '\n' }; + feedb(s, end, sizeof(end)); + CHECK_STR(out(s), "ATH\r"); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(dmc_state(s) == DMC_IDLE); + CHECK(dmc_poll(s, 100) == -1); + + /* the far end hangs up: l, then the stream ended as before */ + tag = dmc_voice_dial(s, "1"); + CHECK_STR(out(s), "AT+FCLASS=8\r"); + feed(s, "AT+FCLASS=8\r\r\nOK\r\nAT+VSM=4\r\r\nOK\r\n"); + CHECK_STR(out(s), "AT+VSM=4\rATD1\r"); + feed(s, "ATD1\r\r\nOK\r\nAT+VTR\r\r\nCONNECT\r\n"); + CHECK(dmc_state(s) == DMC_VOICE); + unsigned char lci[] = { 0x10, 'l' }; + feedb(s, lci, 2); + CHECK(next_of(s, DMC_EV_VOICE, &ev)); + CHECK_STR(ev.result, "hangup"); + n = outb(s, b, sizeof(b)); + CHECK(n >= 2 && b[n - 2] == 0x10 && b[n - 1] == '^'); + feedb(s, end + 1, sizeof(end) - 1); + CHECK_STR(out(s), "ATH\r"); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(dmc_state(s) == DMC_IDLE); + + /* busy: the call given up, the modem on hook in data mode */ + tag = dmc_voice_dial(s, "2"); + out(s); + feed(s, "AT+FCLASS=8\r\r\nOK\r\nAT+VSM=4\r\r\nOK\r\n"); + out(s); + feed(s, "ATD2\r\r\nBUSY\r\n"); + CHECK(next_of(s, DMC_EV_RESPONSE, &ev)); + CHECK(ev.tag == tag && !ev.ok); + CHECK_STR(ev.result, "BUSY"); + CHECK(dmc_state(s) == DMC_IDLE); + CHECK_STR(out(s), "ATH\r"); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(dmc_state(s) == DMC_IDLE); + + /* a modem with no voice mode: the call refused */ + tag = dmc_voice_dial(s, "3"); + out(s); + feed(s, "AT+FCLASS=8\r\r\nERROR\r\n"); + CHECK(next_of(s, DMC_EV_RESPONSE, &ev)); + CHECK(ev.tag == tag && !ev.ok); + CHECK_STR(out(s), "ATH\r"); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(dmc_command(s, "ATI3", 0, 0) > 0); + CHECK_STR(out(s), "ATI3\r"); + feed(s, "ATI3\r\r\nOK\r\n"); + + /* answered: RING, AT+VLS=1 */ + CHECK(dmc_voice_answer(s) == -1); + feed(s, "RING\r\n"); + CHECK(dmc_ring_count(s) == 1); + tag = dmc_voice_answer(s); + CHECK(tag > 0); + voice_setup(s, "AT+VLS=1", DMC_VOICE); + dmc_close(s); + CHECK(dmc_state(s) == DMC_CLOSED); + dmc_session_free(s); +} + +/* the answering machine: answers after two RINGs, the greeting, the + beep, the caller's message until they are quiet */ +static void test_voicemail(void) +{ + dmc_session *s = dmc_session_new(); + dmc_event ev; + static unsigned char b[65536]; + static int16_t greeting[800]; + for (int i = 0; i < 800; i++) + greeting[i] = (int16_t)(i & 1 ? 6000 : -6000); + dmc_voicemail_set(s, greeting, 800, 10, 1); + dmc_voicemail_auto(s, 2); + dmc_open(s, 0); + feed(s, "RING\r\n\r\nNMBR = 5551234\r\n"); + CHECK_STR(out(s), ""); + feed(s, "RING\r\n"); + voice_setup(s, "AT+VLS=1", DMC_VOICEMAIL); + CHECK_STR(dmc_state_name(DMC_VOICEMAIL), "Taking a message"); + /* the greeting, then the beep: 0.1 s and 0.5 s */ + dmc_poll(s, 0); + dmc_poll(s, 1000); + int n = outb(s, b, sizeof(b)); + CHECK(n == 8480); + CHECK(b[0] == b[2] && b[0] != 0xff && b[1] != b[0]); + CHECK(b[902] != 0xff); + CHECK(b[4900] == 0xff); + /* the caller speaks for 2 s, then is quiet for 1 s */ + static unsigned char talk[24000]; + for (int i = 0; i < 16000; i++) + talk[i] = (unsigned char)(i & 1 ? 0x90 : 0x10 + 0x80); + memset(talk + 16000, 0xff, 8000); + feedb(s, talk, 24000); + CHECK(next_of(s, DMC_EV_MESSAGE, &ev)); + CHECK(ev.ok); + CHECK_STR(ev.text, "5551234"); + const int16_t *msg; + n = dmc_voice_message(s, &msg); + CHECK(n == 16000 + 4000); + CHECK(msg[0] != 0 && msg[n - 1] == 0); + n = outb(s, b, sizeof(b)); + CHECK(n >= 2 && b[n - 2] == 0x10 && b[n - 1] == '^'); + unsigned char end[] = { 0x10, 0x03, '\r', '\n', 'O', 'K', '\r', '\n' }; + feedb(s, end, sizeof(end)); + CHECK_STR(out(s), "ATH\r"); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(dmc_state(s) == DMC_IDLE); + + /* a caller who hangs up in the greeting: no message */ + dmc_voicemail_auto(s, 0); + feed(s, "RING\r\n"); + CHECK_STR(out(s), ""); + CHECK(dmc_voicemail_answer(s) > 0); + voice_setup(s, "AT+VLS=1", DMC_VOICEMAIL); + unsigned char lci[] = { 0x10, 'l' }; + feedb(s, lci, 2); + feedb(s, end, sizeof(end)); + out(s); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(next_of(s, DMC_EV_MESSAGE, &ev)); + CHECK(!ev.ok); + CHECK(dmc_state(s) == DMC_IDLE); + + /* picked up while it plays the greeting: a voice call */ + feed(s, "RING\r\n"); + CHECK(dmc_voicemail_answer(s) > 0); + voice_setup(s, "AT+VLS=1", DMC_VOICEMAIL); + CHECK(dmc_voice_pickup(s) == 0); + CHECK(dmc_state(s) == DMC_VOICE); + CHECK(dmc_voice_pickup(s) == -1); + dmc_hangup(s); + feedb(s, end, sizeof(end)); + out(s); + feed(s, "ATH\r\r\nOK\r\n"); + CHECK(dmc_state(s) == DMC_IDLE); + CHECK(!next_of(s, DMC_EV_MESSAGE, &ev)); + dmc_session_free(s); +} + +/* WAV files: ours read back; 16 kHz stereo made 8 kHz mono */ +static void test_wav(void) +{ + char h[44 + 8]; + int16_t *pcm; + CHECK(dmc_wav_header(h, 4) == 44); + CHECK(!memcmp(h, "RIFF", 4) && !memcmp(h + 36, "data", 4)); + CHECK((unsigned char)h[40] == 8); + memcpy(h + 44, "\x10\x00\xf0\xff\x00\x40\x00\x80", 8); + CHECK(dmc_wav_decode(h, sizeof(h), &pcm) == 4); + CHECK(pcm[0] == 16 && pcm[1] == -16 && pcm[2] == 16384 && + pcm[3] == -32768); + dmc_free(pcm); + /* 16 kHz, two channels, 8 frames: 4 samples */ + char w[44 + 32]; + dmc_wav_header(w, 16); + w[22] = 2; /* channels */ + w[24] = (char)0x80; w[25] = 0x3e; /* 16000 */ + memset(w + 44, 0, 32); + w[44] = 0x00; w[45] = 0x10; /* frame 0: 4096 and 0 */ + CHECK(dmc_wav_decode(w, sizeof(w), &pcm) == 4); + CHECK(pcm[0] == 2048 && pcm[1] == 0); + dmc_free(pcm); + CHECK(dmc_wav_decode("RIFF", 4, &pcm) == -1 && !pcm); +} + int main(int argc, char **argv) { const char *dir = argc > 1 ? argv[1] : "."; @@ -485,6 +759,9 @@ int main(int argc, char **argv) test_diag(dir); test_vt(); test_daemon(); + test_voice(); + test_voicemail(); + test_wav(); printf("%d checks, %d failed\n", checks, failures); return failures ? 1 : 0; } diff --git a/docs/design.md b/docs/design.md index 854bdba..13b86d9 100644 --- a/docs/design.md +++ b/docs/design.md @@ -33,11 +33,12 @@ each time the modem opens. ## The same screens everywhere -Each app has the same five pages, with the same words: +Each app has the same six pages, with the same words: | Page | Contents | | --- | --- | | Modem | The state ("Idle", "Dialling", "Online") and its detail (the CONNECT line, the caller), Dial, Answer, Hang Up, the line and the device, Start or Stop | +| Phone | A voice call's state, Call and Answer, the keypad (DTMF), Mute and Listen; the answering machine (on or off, rings, the greeting) and its messages | | Terminal | The AT console; the buttons **Full-screen setup** (AT!CF) and **Command-line setup** (AT!CT) | | Settings | Groups of settings as native controls, changed ones marked; Defaults (ATZ), the init string and Keep | | Call Stats | AT#UD's rows and ATI11's report, refreshed after each call | @@ -62,6 +63,31 @@ own group (`-g`), so that dmodemd needs no root. Each app can instead use a modem that already runs: a device path on Linux and macOS; a TCP address or a COM port on Windows. +## Voice calls and the answering machine + +Voice uses dmodemd's V.253 voice mode: `AT+FCLASS=8`, `AT+VSM=4` (G.711 +μ-law at 8 kHz), then `ATD` or `AT+VLS=1`, and `AT+VTR` for the full-duplex +stream. libdmodemctl does all of it: the DLE framing and its events +(hangup, busy, dial tone, digits, caller ID), μ-law, the pacing of the +stream by the clock given to `dmc_poll`, DTMF, and the answering machine. +The apps only move 8 kHz 16-bit samples between it and the sound card +(`dmc_voice_read`, `dmc_voice_write`): + +| | Sound | Settings | Messages | +| --- | --- | --- | --- | +| Linux | PulseAudio on the GLib main loop (or PipeWire's Pulse server) | `settings.ini`, `[voice]` | `~/.local/share/dmodem-gui/voicemail` | +| Windows | `waveOut` and `waveIn` with window callbacks (Windows 95 has them) | `dmodem.ini`, `[voice]` | `%APPDATA%\D-Modem\Voicemail`, or beside the exe | +| macOS | AVAudioEngine, converted to 8 kHz | UserDefaults | `~/Library/Application Support/D-Modem/Voicemail` | + +The answering machine is off until it is turned on. When on, after the +chosen number of rings (4 by default) it answers, plays the greeting (or +none), beeps, and records until the caller hangs up, 7 s of silence, or +2 minutes. Each message is a WAV file named for its time and the caller's +number; one under a second is dropped. A greeting can be recorded from the +microphone or chosen from any WAV file, which is converted to 8 kHz mono. +Pick Up turns a message being taken into a call; Listen plays it as it is +left. Messages stay on this computer. + ## Windows 95 and later The Windows app is plain Win32 in C++98, so that one binary runs from diff --git a/docs/images/linux-phone.png b/docs/images/linux-phone.png new file mode 100644 index 0000000..62ca312 Binary files /dev/null and b/docs/images/linux-phone.png differ diff --git a/docs/images/linux-voicemail.png b/docs/images/linux-voicemail.png new file mode 100644 index 0000000..15e5ed6 Binary files /dev/null and b/docs/images/linux-voicemail.png differ diff --git a/docs/images/windows-phone.png b/docs/images/windows-phone.png new file mode 100644 index 0000000..c99a62e Binary files /dev/null and b/docs/images/windows-phone.png differ diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt index 0052053..1ab6068 100644 --- a/linux/CMakeLists.txt +++ b/linux/CMakeLists.txt @@ -5,8 +5,19 @@ add_executable(dmodem-gui src/modem.c src/config.c src/settings.c - src/stats.c) + src/stats.c + src/voice.c + src/audio.c) target_link_libraries(dmodem-gui PRIVATE dmodemctl PkgConfig::GTK) +# the sound of voice calls: PulseAudio's client (PipeWire serves it +# too); without it the app has no sound +pkg_check_modules(PULSE IMPORTED_TARGET libpulse-mainloop-glib) +if(PULSE_FOUND) + target_link_libraries(dmodem-gui PRIVATE PkgConfig::PULSE) + target_compile_definitions(dmodem-gui PRIVATE HAVE_PULSE) +else() + message(STATUS "libpulse-mainloop-glib not found: the Linux app has no sound for voice calls") +endif() target_compile_options(dmodem-gui PRIVATE -Wall -Wextra -Wno-unused-parameter) include(GNUInstallDirs) diff --git a/linux/src/app.h b/linux/src/app.h index e3789de..d91c980 100644 --- a/linux/src/app.h +++ b/linux/src/app.h @@ -27,6 +27,10 @@ typedef struct Config { char *dmodemd; /* its path, "" to look for it */ char *init; /* commands sent when the modem opens */ int debug; /* dmodemd -d */ + /* the answering machine ([voice]): on, after how many RINGs, a + message's longest (s) */ + gboolean voicemail; + int vm_rings, vm_max; } Config; typedef struct App App; @@ -69,6 +73,9 @@ struct App { GPtrArray *stats_rows; GtkWidget *stats_report, *stats_empty; GtkTextBuffer *log; + + /* the Phone page (voice.c) */ + struct Voice *voice; }; /* config.c */ @@ -89,6 +96,9 @@ void modem_type(App *a, const char *data, gsize n); /* a command; fn (may be NULL) gets its response */ int modem_command(App *a, const char *cmd, int flags, ResponseFn fn, gpointer data); +/* fn (may be NULL) gets the response of the session's command tag + (dmc_voice_dial()'s and the like) */ +void modem_wait(App *a, int tag, ResponseFn fn, gpointer data); /* the session's output, terminal bytes and events handled now */ void modem_pump(App *a); void app_log(App *a, const char *line); @@ -108,6 +118,25 @@ void settings_load(App *a); void settings_clear(App *a); void settings_sensitive(App *a, gboolean on); +/* voice.c: the Phone page, voice calls' audio, the answering machine + and its messages */ +GtkWidget *voice_page_new(App *a); +void voice_state(App *a); +void voice_event(App *a, const dmc_event *ev); +/* the answering machine's settings to the session */ +void voice_configure(App *a); + +/* audio.c: the sound card, 8 kHz mono (PulseAudio, or PipeWire's) */ +/* the speaker's next samples: how many of n there were (the rest + silence); the microphone's */ +typedef int (*AudioPull)(App *a, int16_t *pcm, int n); +typedef void (*AudioPush)(App *a, const int16_t *pcm, int n); +/* sound from pull and to push (either NULL for none): FALSE if there + is no sound here */ +gboolean audio_start(App *a, AudioPull pull, AudioPush push); +void audio_stop(App *a); +gboolean audio_available(void); + /* stats.c */ GtkWidget *stats_page_new(App *a); void stats_refresh(App *a); diff --git a/linux/src/audio.c b/linux/src/audio.c new file mode 100644 index 0000000..2822cfe --- /dev/null +++ b/linux/src/audio.c @@ -0,0 +1,217 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * audio.c - the sound card for voice calls, greetings and messages: + * PulseAudio (or PipeWire's pulse server) on GLib's main + * loop, so that no thread is needed; 16-bit mono at 8 kHz, + * the line's own rate, and the server converts + * + * Without libpulse the app builds all the same, with no sound. + */ +#include + +#include "app.h" + +#ifdef HAVE_PULSE + +#include +#include + +/* the speaker's and the microphone's buffers: 40 ms, 20 ms a read */ +#define PLAY_MS 40 +#define READ_MS 20 + +static struct { + App *a; + pa_glib_mainloop *loop; + pa_context *ctx; + pa_stream *play, *rec; + AudioPull pull; + AudioPush push; + gboolean failed; +} au; + +static const pa_sample_spec spec = { + PA_SAMPLE_S16NE, DMC_VOICE_RATE, 1 +}; + +static void writable(pa_stream *st, size_t bytes, void *data) +{ + (void)data; + while (bytes >= 2) { + void *p = NULL; + size_t n = bytes; + if (pa_stream_begin_write(st, &p, &n) < 0 || !p) + return; + int want = (int)(n / 2), got = 0; + if (au.pull) + got = au.pull(au.a, p, want); + if (got < want) + memset((int16_t *)p + got, 0, + (size_t)(want - got) * 2); + pa_stream_write(st, p, (size_t)want * 2, NULL, 0, + PA_SEEK_RELATIVE); + bytes -= (size_t)want * 2; + } +} + +static void readable(pa_stream *st, size_t bytes, void *data) +{ + (void)bytes; + (void)data; + const void *p; + size_t n; + while (pa_stream_readable_size(st) > 0) { + if (pa_stream_peek(st, &p, &n) < 0) + return; + if (!n) + break; + /* (a hole: none of it) */ + if (p && au.push) + au.push(au.a, p, (int)(n / 2)); + pa_stream_drop(st); + } +} + +static void streams_close(void) +{ + if (au.play) { + pa_stream_disconnect(au.play); + pa_stream_unref(au.play); + au.play = NULL; + } + if (au.rec) { + pa_stream_disconnect(au.rec); + pa_stream_unref(au.rec); + au.rec = NULL; + } +} + +static void streams_open(void) +{ + pa_buffer_attr at; + memset(&at, 0xff, sizeof(at)); + if (au.pull && !au.play) { + au.play = pa_stream_new(au.ctx, "Voice call", &spec, NULL); + pa_stream_set_write_callback(au.play, writable, NULL); + at.tlength = (uint32_t)pa_usec_to_bytes(PLAY_MS * 1000, &spec); + at.minreq = (uint32_t)pa_usec_to_bytes(READ_MS * 1000, &spec); + pa_stream_connect_playback(au.play, NULL, &at, + PA_STREAM_ADJUST_LATENCY, NULL, + NULL); + } + memset(&at, 0xff, sizeof(at)); + if (au.push && !au.rec) { + au.rec = pa_stream_new(au.ctx, "Voice call", &spec, NULL); + pa_stream_set_read_callback(au.rec, readable, NULL); + at.fragsize = (uint32_t)pa_usec_to_bytes(READ_MS * 1000, &spec); + pa_stream_connect_record(au.rec, NULL, &at, + PA_STREAM_ADJUST_LATENCY); + } +} + +static gboolean unref_later(gpointer c) +{ + pa_context_unref(c); + return G_SOURCE_REMOVE; +} + +static void context_state(pa_context *c, void *data) +{ + (void)data; + switch (pa_context_get_state(c)) { + case PA_CONTEXT_READY: + streams_open(); + break; + case PA_CONTEXT_FAILED: + case PA_CONTEXT_TERMINATED: + /* (a new context the next time; this one let go outside its + own callback) */ + if (au.ctx != c) + break; + streams_close(); + au.ctx = NULL; + pa_context_set_state_callback(c, NULL, NULL); + g_idle_add(unref_later, c); + if (au.a && (au.pull || au.push) && !au.failed) { + au.failed = TRUE; + window_toast(au.a, "No sound: the sound server is not " + "running"); + } + break; + default: + break; + } +} + +gboolean audio_available(void) +{ + return TRUE; +} + +gboolean audio_start(App *a, AudioPull pull, AudioPush push) +{ + streams_close(); + au.a = a; + au.pull = pull; + au.push = push; + au.failed = FALSE; + if (!au.loop) + au.loop = pa_glib_mainloop_new(NULL); + if (!au.ctx) { + pa_proplist *pl = pa_proplist_new(); + pa_proplist_sets(pl, PA_PROP_APPLICATION_ID, APP_ID); + pa_proplist_sets(pl, PA_PROP_APPLICATION_ICON_NAME, APP_ID); + pa_proplist_sets(pl, PA_PROP_MEDIA_ROLE, "phone"); + au.ctx = pa_context_new_with_proplist( + pa_glib_mainloop_get_api(au.loop), "D-Modem", pl); + pa_proplist_free(pl); + pa_context_set_state_callback(au.ctx, context_state, NULL); + if (pa_context_connect(au.ctx, NULL, PA_CONTEXT_NOFLAGS, + NULL) < 0) { + /* (its state callback may have let it go already) */ + if (au.ctx) { + pa_context_set_state_callback(au.ctx, NULL, + NULL); + pa_context_unref(au.ctx); + au.ctx = NULL; + } + return FALSE; + } + return TRUE; + } + if (pa_context_get_state(au.ctx) == PA_CONTEXT_READY) + streams_open(); + return TRUE; +} + +void audio_stop(App *a) +{ + (void)a; + au.pull = NULL; + au.push = NULL; + streams_close(); +} + +#else + +gboolean audio_available(void) +{ + return FALSE; +} + +gboolean audio_start(App *a, AudioPull pull, AudioPush push) +{ + (void)a; + (void)pull; + (void)push; + return FALSE; +} + +void audio_stop(App *a) +{ + (void)a; +} + +#endif diff --git a/linux/src/config.c b/linux/src/config.c index 1d25515..59e08c2 100644 --- a/linux/src/config.c +++ b/linux/src/config.c @@ -56,6 +56,17 @@ void config_load(Config *c) c->dmodemd = get_s(k, "dmodemd", ""); c->init = get_s(k, "init", ""); c->debug = g_key_file_get_integer(k, "line", "debug", NULL); + /* the answering machine: off until the user turns it on */ + GError *e = NULL; + c->voicemail = g_key_file_get_boolean(k, "voice", "voicemail", NULL); + c->vm_rings = g_key_file_get_integer(k, "voice", "rings", &e); + if (e || c->vm_rings < 1) + c->vm_rings = 4; + g_clear_error(&e); + c->vm_max = g_key_file_get_integer(k, "voice", "max-seconds", &e); + if (e || c->vm_max < 10) + c->vm_max = 120; + g_clear_error(&e); g_key_file_unref(k); } @@ -78,6 +89,9 @@ void config_save(const Config *c) g_key_file_set_string(k, "line", "dmodemd", c->dmodemd); g_key_file_set_string(k, "line", "init", c->init); g_key_file_set_integer(k, "line", "debug", c->debug); + g_key_file_set_boolean(k, "voice", "voicemail", c->voicemail); + g_key_file_set_integer(k, "voice", "rings", c->vm_rings); + g_key_file_set_integer(k, "voice", "max-seconds", c->vm_max); char *p = path(); char *dir = g_path_get_dirname(p); g_mkdir_with_parents(dir, 0700); diff --git a/linux/src/modem.c b/linux/src/modem.c index 905840d..ffb3833 100644 --- a/linux/src/modem.c +++ b/linux/src/modem.c @@ -401,6 +401,17 @@ void modem_type(App *a, const char *data, gsize n) modem_pump(a); } +void modem_wait(App *a, int tag, ResponseFn fn, gpointer data) +{ + if (tag > 0) { + Waiting *w = g_new0(Waiting, 1); + w->fn = fn; + w->data = data; + g_hash_table_insert(a->waiting, GINT_TO_POINTER(tag), w); + modem_pump(a); + } +} + int modem_command(App *a, const char *cmd, int flags, ResponseFn fn, gpointer data) { diff --git a/linux/src/voice.c b/linux/src/voice.c new file mode 100644 index 0000000..420c319 --- /dev/null +++ b/linux/src/voice.c @@ -0,0 +1,860 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * voice.c - the Phone page: voice calls dialled and answered, their + * sound on the sound card, the keypad's DTMF; the answering + * machine (off until the user turns it on), its greeting and + * the messages it took, kept as WAV files in + * ~/.local/share/dmodem-gui/voicemail + */ +#include +#include + +#include + +#include "app.h" + +/* the longest greeting recorded (s) */ +#define GREETING_MAX_S 30 + +typedef struct Voice { + GtkWidget *status, *number, *call_btn, *answer_btn, *message_btn; + GtkWidget *pickup_btn, *hangup_btn, *keypad, *mute_btn, *listen_btn; + GtkWidget *vm_switch, *vm_rings, *greeting_row, *record_btn; + GtkWidget *greeting_play, *greeting_clear; + AdwPreferencesGroup *messages; + GPtrArray *message_rows; + GtkWidget *messages_empty; + guint fast; /* the 20 ms tick of a call */ + int last_state; + gboolean muted, listening, listen_on; + /* what plays (a message, the greeting), and what is recorded */ + int16_t *play; + int play_n, play_pos; + guint play_end; + GArray *recording; + /* the greeting, 8 kHz */ + int16_t *greeting; + int greeting_n; +} Voice; + +/* + * files + */ + +static char *data_dir(void) +{ + return g_build_filename(g_get_user_data_dir(), "dmodem-gui", NULL); +} + +static char *messages_dir(void) +{ + return g_build_filename(g_get_user_data_dir(), "dmodem-gui", + "voicemail", NULL); +} + +static char *greeting_path(void) +{ + return g_build_filename(g_get_user_data_dir(), "dmodem-gui", + "greeting.wav", NULL); +} + +/* samples as a WAV file at path */ +static gboolean write_wav(const char *path, const int16_t *pcm, int n, + GError **e) +{ + char *dir = g_path_get_dirname(path); + g_mkdir_with_parents(dir, 0700); + g_free(dir); + gsize len = 44 + (gsize)n * 2; + char *b = g_malloc(len); + dmc_wav_header(b, n); + for (int i = 0; i < n; i++) { + guint16 v = GUINT16_TO_LE((guint16)pcm[i]); + memcpy(b + 44 + i * 2, &v, 2); + } + gboolean ok = g_file_set_contents_full(path, b, (gssize)len, + G_FILE_SET_CONTENTS_CONSISTENT, + 0600, e); + g_free(b); + return ok; +} + +/* a WAV file's samples at 8 kHz: how many (*pcm to dmc_free()), -1 */ +static int read_wav(const char *path, int16_t **pcm) +{ + char *b; + gsize len; + *pcm = NULL; + if (!g_file_get_contents(path, &b, &len, NULL)) + return -1; + int n = len > G_MAXINT ? -1 : dmc_wav_decode(b, (int)len, pcm); + g_free(b); + return n; +} + +/* + * sound + */ + +static int call_pull(App *a, int16_t *pcm, int n) +{ + return dmc_voice_read(a->s, pcm, n); +} + +static void call_push(App *a, const int16_t *pcm, int n) +{ + if (!a->voice->muted) + dmc_voice_write(a->s, pcm, n); +} + +static gboolean play_done(gpointer data) +{ + App *a = data; + Voice *v = a->voice; + v->play_end = 0; + audio_stop(a); + g_clear_pointer(&v->play, dmc_free); + v->play_n = v->play_pos = 0; + voice_state(a); + return G_SOURCE_REMOVE; +} + +static int play_pull(App *a, int16_t *pcm, int n) +{ + Voice *v = a->voice; + int k = v->play_n - v->play_pos; + if (k > n) + k = n; + if (k > 0) { + memcpy(pcm, v->play + v->play_pos, (size_t)k * 2); + v->play_pos += k; + } + /* (stopped from the main loop, not inside the sound's callback) */ + if (v->play_pos >= v->play_n && !v->play_end) + v->play_end = g_timeout_add(300, play_done, a); + return k; +} + +static void record_push(App *a, const int16_t *pcm, int n) +{ + Voice *v = a->voice; + if (!v->recording) + return; + int room = GREETING_MAX_S * DMC_VOICE_RATE - (int)v->recording->len; + if (n > room) + n = room; + if (n > 0) + g_array_append_vals(v->recording, pcm, (guint)n); +} + +static void stop_sound(App *a) +{ + Voice *v = a->voice; + if (v->play_end) { + g_source_remove(v->play_end); + v->play_end = 0; + } + audio_stop(a); + g_clear_pointer(&v->play, dmc_free); + v->play_n = v->play_pos = 0; + if (v->recording) { + g_array_unref(v->recording); + v->recording = NULL; + } +} + +/* pcm (taken: dmc_free()d when done) played */ +static void play(App *a, int16_t *pcm, int n) +{ + Voice *v = a->voice; + stop_sound(a); + v->play = pcm; + v->play_n = n; + v->play_pos = 0; + if (!audio_start(a, play_pull, NULL)) { + window_toast(a, "No sound: D-Modem was built without " + "PulseAudio"); + stop_sound(a); + } + voice_state(a); +} + +/* + * the answering machine's greeting and messages + */ + +static void load_greeting(App *a) +{ + Voice *v = a->voice; + char *p = greeting_path(); + g_clear_pointer(&v->greeting, dmc_free); + v->greeting_n = 0; + int16_t *pcm; + int n = read_wav(p, &pcm); + if (n > 0) { + v->greeting = pcm; + v->greeting_n = n; + } else if (pcm) { + dmc_free(pcm); + } + g_free(p); +} + +void voice_configure(App *a) +{ + Voice *v = a->voice; + dmc_voicemail_set(a->s, v->greeting, v->greeting_n, a->cfg.vm_max, 0); + dmc_voicemail_auto(a->s, a->cfg.voicemail ? a->cfg.vm_rings : 0); +} + +static void refresh_messages(App *a); + +static void play_message(GtkWidget *w, gpointer data) +{ + App *a = data; + const char *path = g_object_get_data(G_OBJECT(w), "path"); + int16_t *pcm; + int n = read_wav(path, &pcm); + if (n <= 0) { + if (pcm) + dmc_free(pcm); + window_toast(a, "Can't read the message"); + return; + } + play(a, pcm, n); +} + +static void delete_message(GtkWidget *w, gpointer data) +{ + App *a = data; + const char *path = g_object_get_data(G_OBJECT(w), "path"); + stop_sound(a); + if (g_remove(path) < 0) + window_toast(a, "Can't delete the message"); + refresh_messages(a); + voice_state(a); +} + +static int newest_first(gconstpointer x, gconstpointer y) +{ + return -g_strcmp0(*(char *const *)x, *(char *const *)y); +} + +/* the message list from the files: 20261111-120501_5551234.wav */ +static void refresh_messages(App *a) +{ + Voice *v = a->voice; + for (guint i = 0; i < v->message_rows->len; i++) + adw_preferences_group_remove(v->messages, + g_ptr_array_index(v->message_rows, i)); + g_ptr_array_set_size(v->message_rows, 0); + char *dir = messages_dir(); + GDir *d = g_dir_open(dir, 0, NULL); + GPtrArray *names = g_ptr_array_new_with_free_func(g_free); + const char *n; + while (d && (n = g_dir_read_name(d))) + if (g_str_has_suffix(n, ".wav")) + g_ptr_array_add(names, g_strdup(n)); + if (d) + g_dir_close(d); + g_ptr_array_sort(names, newest_first); + for (guint i = 0; i < names->len; i++) { + const char *name = g_ptr_array_index(names, i); + char *path = g_build_filename(dir, name, NULL); + int y, mo, da, h, mi, se; + char who[64] = ""; + if (sscanf(name, "%4d%2d%2d-%2d%2d%2d_%63[^.]", &y, &mo, &da, + &h, &mi, &se, who) < 6) { + g_free(path); + continue; + } + GStatBuf st; + long secs = !g_stat(path, &st) && st.st_size > 44 ? + (long)((st.st_size - 44) / (2 * DMC_VOICE_RATE)) : 0; + GtkWidget *row = adw_action_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(row), + *who ? who : "Unknown caller"); + char *sub = g_strdup_printf("%04d-%02d-%02d %02d:%02d · %ld:%02ld", + y, mo, da, h, mi, secs / 60, + secs % 60); + adw_action_row_set_subtitle(ADW_ACTION_ROW(row), sub); + g_free(sub); + GtkWidget *pb = gtk_button_new_from_icon_name( + "media-playback-start-symbolic"); + gtk_widget_set_tooltip_text(pb, "Play"); + gtk_widget_set_valign(pb, GTK_ALIGN_CENTER); + gtk_widget_add_css_class(pb, "flat"); + g_object_set_data_full(G_OBJECT(pb), "path", g_strdup(path), + g_free); + g_signal_connect(pb, "clicked", G_CALLBACK(play_message), a); + GtkWidget *db = gtk_button_new_from_icon_name( + "user-trash-symbolic"); + gtk_widget_set_tooltip_text(db, "Delete"); + gtk_widget_set_valign(db, GTK_ALIGN_CENTER); + gtk_widget_add_css_class(db, "flat"); + g_object_set_data_full(G_OBJECT(db), "path", path, g_free); + g_signal_connect(db, "clicked", G_CALLBACK(delete_message), a); + adw_action_row_add_suffix(ADW_ACTION_ROW(row), pb); + adw_action_row_add_suffix(ADW_ACTION_ROW(row), db); + adw_preferences_group_add(v->messages, row); + g_ptr_array_add(v->message_rows, row); + } + gtk_widget_set_visible(v->messages_empty, v->message_rows->len == 0); + g_ptr_array_unref(names); + g_free(dir); +} + +/* the message the answering machine took, kept */ +static void save_message(App *a, const char *number) +{ + const int16_t *pcm; + int n = dmc_voice_message(a->s, &pcm); + if (n <= 0) + return; + GDateTime *now = g_date_time_new_now_local(); + char *stamp = g_date_time_format(now, "%Y%m%d-%H%M%S"); + g_date_time_unref(now); + /* (the number as a file name allows: digits, + * #) */ + GString *who = g_string_new(""); + for (const char *p = number; *p && who->len < 32; p++) + if (g_ascii_isalnum(*p) || *p == '+' || *p == '*' || *p == '#') + g_string_append_c(who, *p); + char *name = g_strdup_printf("%s_%s.wav", stamp, who->str); + char *dir = messages_dir(); + char *path = g_build_filename(dir, name, NULL); + GError *e = NULL; + if (!write_wav(path, pcm, n, &e)) { + char *m = g_strdup_printf("Can't keep the message: %s", + e->message); + window_toast(a, m); + g_free(m); + g_error_free(e); + } else { + GNotification *nt = g_notification_new("New voice message"); + char *body = g_strdup_printf("From %s", *who->str ? who->str : + "an unknown caller"); + g_notification_set_body(nt, body); + g_application_send_notification(G_APPLICATION(a->gapp), + "voicemail", nt); + g_object_unref(nt); + g_free(body); + app_log(a, "The answering machine took a message."); + } + g_free(path); + g_free(dir); + g_free(name); + g_free(stamp); + g_string_free(who, TRUE); + refresh_messages(a); +} + +/* the greeting: recorded from the microphone */ +static void record_greeting(GtkWidget *w, gpointer data) +{ + App *a = data; + Voice *v = a->voice; + (void)w; + if (v->recording) { + /* stopped: kept */ + GArray *r = g_array_ref(v->recording); + stop_sound(a); + if (r->len > DMC_VOICE_RATE / 2) { + char *p = greeting_path(); + GError *e = NULL; + if (!write_wav(p, (int16_t *)r->data, (int)r->len, &e)) { + window_toast(a, e->message); + g_error_free(e); + } + g_free(p); + load_greeting(a); + voice_configure(a); + } + g_array_unref(r); + voice_state(a); + return; + } + stop_sound(a); + v->recording = g_array_new(FALSE, FALSE, sizeof(int16_t)); + if (!audio_start(a, NULL, record_push)) { + window_toast(a, "No sound: D-Modem was built without " + "PulseAudio"); + stop_sound(a); + } + voice_state(a); +} + +static void play_greeting(GtkWidget *w, gpointer data) +{ + App *a = data; + Voice *v = a->voice; + (void)w; + if (v->play) { + stop_sound(a); + voice_state(a); + return; + } + if (!v->greeting_n) + return; + /* (play() frees it with dmc_free(), which is free()) */ + int16_t *copy = malloc((size_t)v->greeting_n * 2); + if (!copy) + return; + memcpy(copy, v->greeting, (size_t)v->greeting_n * 2); + play(a, copy, v->greeting_n); +} + +static void clear_greeting(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + char *p = greeting_path(); + g_remove(p); + g_free(p); + load_greeting(a); + voice_configure(a); + voice_state(a); +} + +static void greeting_chosen(GObject *src, GAsyncResult *res, gpointer data) +{ + App *a = data; + GFile *f = gtk_file_dialog_open_finish(GTK_FILE_DIALOG(src), res, NULL); + if (!f) + return; + char *path = g_file_get_path(f); + g_object_unref(f); + int16_t *pcm; + int n = path ? read_wav(path, &pcm) : -1; + g_free(path); + if (n <= 0) { + if (n == 0) + dmc_free(pcm); + window_toast(a, "That isn't a WAV file D-Modem can play " + "(PCM, A-law or µ-law)"); + return; + } + char *p = greeting_path(); + GError *e = NULL; + if (!write_wav(p, pcm, n, &e)) { + window_toast(a, e->message); + g_error_free(e); + } + g_free(p); + dmc_free(pcm); + load_greeting(a); + voice_configure(a); + voice_state(a); +} + +static void choose_greeting(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + GtkFileDialog *d = gtk_file_dialog_new(); + gtk_file_dialog_set_title(d, "Greeting"); + GtkFileFilter *f = gtk_file_filter_new(); + gtk_file_filter_set_name(f, "WAV files"); + gtk_file_filter_add_suffix(f, "wav"); + GListStore *filters = g_list_store_new(GTK_TYPE_FILE_FILTER); + g_list_store_append(filters, f); + gtk_file_dialog_set_filters(d, G_LIST_MODEL(filters)); + g_object_unref(filters); + g_object_unref(f); + gtk_file_dialog_open(d, a->window, NULL, greeting_chosen, a); + g_object_unref(d); +} + +static void voicemail_switched(GObject *o, GParamSpec *ps, gpointer data) +{ + App *a = data; + (void)ps; + a->cfg.voicemail = adw_switch_row_get_active(ADW_SWITCH_ROW(o)); + config_save(&a->cfg); + voice_configure(a); +} + +static void rings_changed(GObject *o, GParamSpec *ps, gpointer data) +{ + App *a = data; + (void)ps; + a->cfg.vm_rings = (int)adw_spin_row_get_value(ADW_SPIN_ROW(o)); + config_save(&a->cfg); + voice_configure(a); +} + +/* + * calls + */ + +static void dialled(App *a, const dmc_event *ev, gpointer data) +{ + (void)data; + if (!ev->ok) { + char *m = !strcmp(ev->result, "ERROR") ? + g_strdup("The modem has no voice mode (D-Modem 1.1 " + "or later has)") : + g_strdup_printf("%c%s", g_ascii_toupper(ev->result[0]), + ev->result + 1); + window_toast(a, m); + g_free(m); + } +} + +static void call(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + const char *n = gtk_editable_get_text(GTK_EDITABLE(a->voice->number)); + if (!*n) { + window_toast(a, "Enter a number to call"); + return; + } + stop_sound(a); + modem_wait(a, dmc_voice_dial(a->s, n), dialled, NULL); +} + +static void answer(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + stop_sound(a); + modem_wait(a, dmc_voice_answer(a->s), dialled, NULL); +} + +static void take_message(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + stop_sound(a); + modem_wait(a, dmc_voicemail_answer(a->s), dialled, NULL); +} + +static void pickup(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + dmc_voice_pickup(a->s); + modem_pump(a); +} + +static void hangup(GtkWidget *w, gpointer data) +{ + App *a = data; + (void)w; + dmc_hangup(a->s); + modem_pump(a); +} + +static void key(GtkWidget *w, gpointer data) +{ + App *a = data; + const char *k = gtk_button_get_label(GTK_BUTTON(w)); + int st = dmc_state(a->s); + if (st == DMC_VOICE) { + dmc_voice_dtmf(a->s, k[0]); + } else { + GtkEditable *e = GTK_EDITABLE(a->voice->number); + int pos = -1; + gtk_editable_insert_text(e, k, 1, &pos); + } +} + +static void mute(GtkWidget *w, gpointer data) +{ + App *a = data; + a->voice->muted = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w)); +} + +static void listen_toggled(GtkWidget *w, gpointer data) +{ + App *a = data; + a->voice->listening = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w)); + voice_state(a); +} + +static gboolean fast_tick(gpointer data) +{ + modem_pump(data); + return G_SOURCE_CONTINUE; +} + +/* the sound as the call needs it: both ways in a call; the caller (if + listening) while the answering machine has the call */ +static void call_sound(App *a, int st) +{ + Voice *v = a->voice; + int was = v->last_state; + gboolean in = st == DMC_VOICE || st == DMC_VOICEMAIL; + gboolean listen = st == DMC_VOICEMAIL && v->listening; + if (in && !v->fast) { + v->fast = g_timeout_add(20, fast_tick, a); + } else if (!in && st != DMC_HANGING_UP && v->fast) { + g_source_remove(v->fast); + v->fast = 0; + } + if (st == DMC_VOICE && was != DMC_VOICE) { + stop_sound(a); + v->listen_on = FALSE; + if (!audio_start(a, call_pull, call_push)) + window_toast(a, "No sound: D-Modem was built without " + "PulseAudio"); + } else if (listen && !v->listen_on) { + audio_start(a, call_pull, NULL); + v->listen_on = TRUE; + } else if (!listen && v->listen_on) { + audio_stop(a); + v->listen_on = FALSE; + } else if (was == DMC_VOICE && st != DMC_VOICE) { + audio_stop(a); + } + v->last_state = st; +} + +void voice_state(App *a) +{ + Voice *v = a->voice; + if (!v) + return; + int st = dmc_state(a->s); + call_sound(a, st); + const char *who = dmc_caller_number(a->s); + char *status; + switch (st) { + case DMC_CLOSED: + status = g_strdup("The modem isn't running"); + break; + case DMC_RINGING: + status = g_strdup_printf("Ringing%s%s", *who ? ": " : "", who); + break; + case DMC_VOICE: + status = g_strdup("In a call"); + break; + case DMC_VOICEMAIL: + status = g_strdup_printf("Taking a message%s%s", + *who ? " from " : "", who); + break; + default: + status = g_strdup(dmc_state_name(st)); + break; + } + adw_action_row_set_subtitle(ADW_ACTION_ROW(v->status), status); + g_free(status); + gboolean idle = st == DMC_IDLE; + gboolean busy = v->play || v->recording; + gtk_widget_set_sensitive(v->call_btn, idle); + gtk_widget_set_sensitive(v->answer_btn, st == DMC_RINGING); + gtk_widget_set_sensitive(v->message_btn, st == DMC_RINGING); + gtk_widget_set_visible(v->pickup_btn, st == DMC_VOICEMAIL); + gtk_widget_set_visible(v->listen_btn, st == DMC_VOICEMAIL); + gtk_widget_set_sensitive(v->hangup_btn, + st == DMC_VOICE || st == DMC_VOICEMAIL || + (st == DMC_DIALING || st == DMC_ANSWERING)); + gtk_widget_set_sensitive(v->mute_btn, st == DMC_VOICE); + gtk_widget_set_sensitive(v->keypad, st == DMC_VOICE || idle || + st == DMC_CLOSED); + gtk_button_set_label(GTK_BUTTON(v->record_btn), + v->recording ? "Stop" : "Record"); + gtk_widget_set_sensitive(v->record_btn, !v->play && + audio_available() && + st != DMC_VOICE && st != DMC_VOICEMAIL); + gtk_button_set_icon_name(GTK_BUTTON(v->greeting_play), + v->play ? "media-playback-stop-symbolic" : + "media-playback-start-symbolic"); + gtk_widget_set_sensitive(v->greeting_play, + (v->greeting_n > 0 || v->play) && + !v->recording); + gtk_widget_set_sensitive(v->greeting_clear, + v->greeting_n > 0 && !busy); + char *g = v->recording ? g_strdup("Recording: speak, then Stop") : + v->greeting_n ? + g_strdup_printf("Your recording (%d s)", + (v->greeting_n + DMC_VOICE_RATE / 2) / + DMC_VOICE_RATE) : + g_strdup("None: callers hear a beep"); + adw_action_row_set_subtitle(ADW_ACTION_ROW(v->greeting_row), g); + g_free(g); +} + +void voice_event(App *a, const dmc_event *ev) +{ + if (ev->type == DMC_EV_MESSAGE) { + if (ev->ok) + save_message(a, ev->text); + } else if (ev->type == DMC_EV_VOICE) { + if (!strcmp(ev->text, "b")) + window_toast(a, "Busy"); + else if (!strcmp(ev->text, "l") && + dmc_state(a->s) != DMC_VOICEMAIL) + window_toast(a, "The other end hung up"); + } +} + +/* + * the page + */ + +static GtkWidget *button(const char *label, GCallback fn, App *a) +{ + GtkWidget *b = gtk_button_new_with_label(label); + gtk_widget_set_valign(b, GTK_ALIGN_CENTER); + g_signal_connect(b, "clicked", fn, a); + return b; +} + +static GtkWidget *icon_button(const char *icon, const char *tip, + GCallback fn, App *a) +{ + GtkWidget *b = gtk_button_new_from_icon_name(icon); + gtk_widget_set_tooltip_text(b, tip); + gtk_widget_set_valign(b, GTK_ALIGN_CENTER); + gtk_widget_add_css_class(b, "flat"); + g_signal_connect(b, "clicked", fn, a); + return b; +} + +GtkWidget *voice_page_new(App *a) +{ + Voice *v = g_new0(Voice, 1); + a->voice = v; + v->message_rows = g_ptr_array_new(); + v->last_state = DMC_CLOSED; + GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 24); + gtk_widget_set_margin_top(box, 24); + gtk_widget_set_margin_bottom(box, 24); + gtk_widget_set_margin_start(box, 12); + gtk_widget_set_margin_end(box, 12); + + /* the call */ + GtkWidget *cg = adw_preferences_group_new(); + adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(cg), "Voice Call"); + adw_preferences_group_set_description(ADW_PREFERENCES_GROUP(cg), + "Calls through the modem's voice mode, with the computer's " + "microphone and speakers"); + v->status = adw_action_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->status), "Phone"); + v->hangup_btn = button("Hang Up", G_CALLBACK(hangup), a); + gtk_widget_add_css_class(v->hangup_btn, "destructive-action"); + v->pickup_btn = button("Pick Up", G_CALLBACK(pickup), a); + gtk_widget_set_tooltip_text(v->pickup_btn, + "Talk to the caller yourself"); + v->listen_btn = gtk_toggle_button_new_with_label("Listen"); + gtk_widget_set_valign(v->listen_btn, GTK_ALIGN_CENTER); + gtk_widget_set_tooltip_text(v->listen_btn, + "Hear the caller leave the message"); + g_signal_connect(v->listen_btn, "toggled", G_CALLBACK(listen_toggled), a); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->status), v->listen_btn); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->status), v->pickup_btn); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->status), v->hangup_btn); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(cg), v->status); + + v->number = adw_entry_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->number), + "Number to call"); + v->call_btn = button("Call", G_CALLBACK(call), a); + gtk_widget_add_css_class(v->call_btn, "suggested-action"); + adw_entry_row_add_suffix(ADW_ENTRY_ROW(v->number), v->call_btn); + g_signal_connect(v->number, "entry-activated", G_CALLBACK(call), a); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(cg), v->number); + + GtkWidget *ring = adw_action_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(ring), "A call ringing"); + v->answer_btn = button("Answer", G_CALLBACK(answer), a); + v->message_btn = button("Take a Message", G_CALLBACK(take_message), a); + adw_action_row_add_suffix(ADW_ACTION_ROW(ring), v->message_btn); + adw_action_row_add_suffix(ADW_ACTION_ROW(ring), v->answer_btn); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(cg), ring); + gtk_box_append(GTK_BOX(box), cg); + + /* the keypad: digits for the number, DTMF in a call */ + GtkWidget *pad = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(pad), 6); + gtk_grid_set_column_spacing(GTK_GRID(pad), 6); + gtk_grid_set_row_homogeneous(GTK_GRID(pad), TRUE); + gtk_grid_set_column_homogeneous(GTK_GRID(pad), TRUE); + static const char *const keys = "123456789*0#"; + for (int i = 0; i < 12; i++) { + char k[2] = { keys[i], 0 }; + GtkWidget *b = gtk_button_new_with_label(k); + gtk_widget_add_css_class(b, "title-3"); + gtk_widget_set_size_request(b, 72, 44); + g_signal_connect(b, "clicked", G_CALLBACK(key), a); + gtk_grid_attach(GTK_GRID(pad), b, i % 3, i / 3, 1, 1); + } + v->mute_btn = gtk_toggle_button_new_with_label("Mute"); + g_signal_connect(v->mute_btn, "toggled", G_CALLBACK(mute), a); + gtk_grid_attach(GTK_GRID(pad), v->mute_btn, 0, 4, 3, 1); + gtk_widget_set_halign(pad, GTK_ALIGN_CENTER); + v->keypad = pad; + gtk_box_append(GTK_BOX(box), pad); + + /* the answering machine */ + GtkWidget *mg = adw_preferences_group_new(); + adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(mg), + "Answering Machine"); + adw_preferences_group_set_description(ADW_PREFERENCES_GROUP(mg), + "Messages are kept on this computer only"); + v->vm_switch = adw_switch_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->vm_switch), + "Take messages"); + adw_action_row_set_subtitle(ADW_ACTION_ROW(v->vm_switch), + "Answer calls nobody picks up, play the greeting and record"); + adw_switch_row_set_active(ADW_SWITCH_ROW(v->vm_switch), a->cfg.voicemail); + g_signal_connect(v->vm_switch, "notify::active", + G_CALLBACK(voicemail_switched), a); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), v->vm_switch); + v->vm_rings = adw_spin_row_new_with_range(1, 15, 1); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->vm_rings), + "Rings before it answers"); + adw_spin_row_set_value(ADW_SPIN_ROW(v->vm_rings), a->cfg.vm_rings); + g_signal_connect(v->vm_rings, "notify::value", + G_CALLBACK(rings_changed), a); + g_object_bind_property(v->vm_switch, "active", v->vm_rings, + "sensitive", G_BINDING_SYNC_CREATE); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), v->vm_rings); + v->greeting_row = adw_action_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->greeting_row), + "Greeting"); + v->greeting_play = icon_button("media-playback-start-symbolic", "Play", + G_CALLBACK(play_greeting), a); + v->record_btn = button("Record", G_CALLBACK(record_greeting), a); + GtkWidget *choose = icon_button("document-open-symbolic", + "Use a WAV file", + G_CALLBACK(choose_greeting), a); + v->greeting_clear = icon_button("user-trash-symbolic", + "No greeting: the beep alone", + G_CALLBACK(clear_greeting), a); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), v->greeting_play); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), v->record_btn); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), choose); + adw_action_row_add_suffix(ADW_ACTION_ROW(v->greeting_row), v->greeting_clear); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(mg), v->greeting_row); + gtk_box_append(GTK_BOX(box), mg); + + /* the messages */ + v->messages = ADW_PREFERENCES_GROUP(adw_preferences_group_new()); + adw_preferences_group_set_title(v->messages, "Messages"); + v->messages_empty = adw_action_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(v->messages_empty), + "No messages"); + gtk_widget_add_css_class(v->messages_empty, "dim-label"); + adw_preferences_group_add(v->messages, v->messages_empty); + gtk_box_append(GTK_BOX(box), GTK_WIDGET(v->messages)); + + char *d = data_dir(); + g_mkdir_with_parents(d, 0700); + g_free(d); + load_greeting(a); + refresh_messages(a); + voice_configure(a); + + GtkWidget *clamp = adw_clamp_new(); + adw_clamp_set_maximum_size(ADW_CLAMP(clamp), 560); + adw_clamp_set_child(ADW_CLAMP(clamp), box); + GtkWidget *scroll = gtk_scrolled_window_new(); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), + GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scroll), clamp); + return scroll; +} diff --git a/linux/src/window.c b/linux/src/window.c index bbff8a0..b502f95 100644 --- a/linux/src/window.c +++ b/linux/src/window.c @@ -30,6 +30,10 @@ static const char *state_icon(int state) return "network-transmit-receive-symbolic"; case DMC_CONFIGURATOR: return "preferences-system-symbolic"; + case DMC_VOICE: + return "audio-input-microphone-symbolic"; + case DMC_VOICEMAIL: + return "media-record-symbolic"; default: return "call-start-symbolic"; } @@ -80,6 +84,7 @@ void window_state(App *a) gtk_widget_set_sensitive(a->copy_btn, a->fd >= 0); gtk_widget_set_sensitive(a->term_buttons, st == DMC_IDLE); settings_sensitive(a, st == DMC_IDLE); + voice_state(a); } void window_opened(App *a) @@ -131,6 +136,10 @@ void window_event(App *a, const dmc_event *ev) case DMC_EV_CALLER: window_state(a); break; + case DMC_EV_VOICE: + case DMC_EV_MESSAGE: + voice_event(a, ev); + break; } } @@ -444,6 +453,9 @@ void window_build(App *a) a->stack = ADW_VIEW_STACK(adw_view_stack_new()); adw_view_stack_add_titled_with_icon(a->stack, modem_page(a), "modem", "Modem", "call-start-symbolic"); + adw_view_stack_add_titled_with_icon(a->stack, voice_page_new(a), + "phone", "Phone", + "audio-input-microphone-symbolic"); adw_view_stack_add_titled_with_icon(a->stack, terminal_page(a), "terminal", "Terminal", "utilities-terminal-symbolic"); diff --git a/macos/DModem/ContentView.swift b/macos/DModem/ContentView.swift index 717437c..4197bd8 100644 --- a/macos/DModem/ContentView.swift +++ b/macos/DModem/ContentView.swift @@ -7,12 +7,13 @@ import SwiftUI enum Page: String, CaseIterable, Identifiable { - case modem = "Modem", terminal = "Terminal", settings = "Settings" + case modem = "Modem", phone = "Phone", terminal = "Terminal", settings = "Settings" case stats = "Call Stats", log = "Log" var id: String { rawValue } var icon: String { switch self { case .modem: return "phone.connection" + case .phone: return "phone" case .terminal: return "terminal" case .settings: return "slider.horizontal.3" case .stats: return "chart.bar" @@ -35,6 +36,7 @@ struct ContentView: View { Group { switch page ?? .modem { case .modem: ModemPage() + case .phone: PhonePage() case .terminal: TerminalPane() case .settings: SettingsPage() case .stats: StatsPage() @@ -80,6 +82,8 @@ struct ModemPage: View { case Int(DMC_DIALING), Int(DMC_ANSWERING): return "phone.arrow.up.right" case Int(DMC_ONLINE), Int(DMC_ONLINE_COMMAND): return "arrow.up.arrow.down" case Int(DMC_CONFIGURATOR): return "gearshape" + case Int(DMC_VOICE): return "phone.fill" + case Int(DMC_VOICEMAIL): return "recordingtape" default: return "phone" } } diff --git a/macos/DModem/DModemApp.swift b/macos/DModem/DModemApp.swift index 7514e1a..73893f8 100644 --- a/macos/DModem/DModemApp.swift +++ b/macos/DModem/DModemApp.swift @@ -14,6 +14,7 @@ struct DModemApp: App { Window("D-Modem", id: "main") { ContentView() .environmentObject(modem) + .environmentObject(modem.voice) .frame(minWidth: 760, minHeight: 520) .onAppear { delegate.modem = modem } } diff --git a/macos/DModem/Modem.swift b/macos/DModem/Modem.swift index fd07406..80eda5d 100644 --- a/macos/DModem/Modem.swift +++ b/macos/DModem/Modem.swift @@ -76,6 +76,8 @@ final class Modem: ObservableObject { let session: OpaquePointer let vt: OpaquePointer + /// voice calls and the answering machine (Voice.swift) + let voice = Voice() private var process: Process? private var fd: Int32 = -1 @@ -90,6 +92,8 @@ final class Modem: ObservableObject { init() { session = dmc_session_new() vt = dmc_vt_new(80, 24, 2000) + voice.modem = self + voice.configure() let t = Timer(timeInterval: 0.05, repeats: true) { [weak self] _ in self?.pump() } @@ -126,10 +130,13 @@ final class Modem: ObservableObject { var isOpen: Bool { state != Int(DMC_CLOSED) } var isIdle: Bool { state == Int(DMC_IDLE) } var canHangUp: Bool { - [DMC_DIALING, DMC_ANSWERING, DMC_ONLINE, DMC_ONLINE_COMMAND, DMC_RINGING] + [DMC_DIALING, DMC_ANSWERING, DMC_ONLINE, DMC_ONLINE_COMMAND, DMC_RINGING, + DMC_VOICE, DMC_VOICEMAIL] .map { Int($0) }.contains(state) } + var callerNumber: String { cstr(dmc_caller_number(session)) } + func say(_ text: String) { toast = text } @@ -169,6 +176,45 @@ final class Modem: ObservableObject { pump() } + /// done gets the response of the session's command tag + private func expect(_ tag: Int32, _ done: @escaping (Response) -> Void) { + guard tag > 0 else { return } + waiting[tag] = done + pump() + } + + private func voiceResult(_ r: Response) { + if !r.ok { + say(r.result == "ERROR" ? "The modem has no voice mode (D-Modem 1.1 or later has)" + : r.result.capitalized) + } + } + + func voiceDial(_ number: String) { + let n = number.trimmingCharacters(in: .whitespaces) + guard !n.isEmpty else { return say("Enter a number to call") } + voice.stopSound() + expect(dmc_voice_dial(session, n)) { [weak self] r in self?.voiceResult(r) } + } + + func voiceAnswer() { + expect(dmc_voice_answer(session)) { [weak self] r in self?.voiceResult(r) } + } + + func voicemailAnswer() { + expect(dmc_voicemail_answer(session)) { [weak self] r in self?.voiceResult(r) } + } + + func pickUp() { + dmc_voice_pickup(session) + pump() + } + + func dtmf(_ key: String) { + guard let c = key.utf8.first else { return } + dmc_voice_dtmf(session, CChar(bitPattern: c)) + } + /// bytes typed in the terminal func type(_ bytes: [UInt8]) { guard fd >= 0, !bytes.isEmpty else { return } @@ -200,6 +246,7 @@ final class Modem: ObservableObject { } func pump() { + voice.beforePoll() dmc_poll(session, Modem.now()) var buf = [CChar](repeating: 0, count: 4096) var n: Int32 @@ -234,9 +281,11 @@ final class Modem: ObservableObject { result: cstr(ev.result)) if let fn = waiting.removeValue(forKey: ev.tag) { fn(r) } } else { - event(type, state: Int(ev.state), result: cstr(ev.result)) + event(type, state: Int(ev.state), result: cstr(ev.result), + text: cstr(ev.text), ok: ev.ok != 0) } } + voice.afterPoll() } private func flush() { @@ -251,12 +300,13 @@ final class Modem: ObservableObject { } } - private func event(_ type: Int, state st: Int, result: String) { + private func event(_ type: Int, state st: Int, result: String, text: String, ok: Bool) { switch type { case Int(DMC_EV_STATE): let was = lastState lastState = st state = st + voice.sound(st) let calls = [DMC_ONLINE, DMC_ONLINE_COMMAND, DMC_HANGING_UP, DMC_DIALING, DMC_ANSWERING].map { Int($0) } // a call over: its statistics @@ -271,6 +321,8 @@ final class Modem: ObservableObject { } case Int(DMC_EV_CALLER): objectWillChange.send() + case Int(DMC_EV_VOICE), Int(DMC_EV_MESSAGE): + voice.event(type, text: text, ok: ok) default: break } @@ -358,6 +410,7 @@ final class Modem: ObservableObject { } state = Int(DMC_CLOSED) lastState = state + voice.sound(state) clearSettings() running = process != nil } diff --git a/macos/DModem/Voice.swift b/macos/DModem/Voice.swift new file mode 100644 index 0000000..c9ba0a6 --- /dev/null +++ b/macos/DModem/Voice.swift @@ -0,0 +1,652 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 D-Modem Authors +// +// Voice.swift - the Phone page: voice calls dialled and answered, their +// sound on the Mac's microphone and speakers (AVAudioEngine), the +// keypad's DTMF; the answering machine (off until the user turns it on), +// its greeting and the messages it took, kept as WAV files in +// ~/Library/Application Support/D-Modem/Voicemail + +import AppKit +import AVFoundation +import SwiftUI +import UniformTypeIdentifiers +import UserNotifications + +/// Samples between the sound card's thread and the main one, the newest +/// `capacity` of them kept. +final class SampleQueue { + private var buf: [Float] + private var head = 0 + private var count = 0 + private let lock = NSLock() + + init(capacity: Int) { + buf = [Float](repeating: 0, count: capacity) + } + + func push(_ x: UnsafeBufferPointer) { + lock.lock() + for v in x { + if count == buf.count { + head = (head + 1) % buf.count + count -= 1 + } + buf[(head + count) % buf.count] = v + count += 1 + } + lock.unlock() + } + + /// up to n into p: how many + func pop(into p: UnsafeMutablePointer, _ n: Int) -> Int { + lock.lock() + let k = min(n, count) + for i in 0.. Bool { + stop() + let e = AVAudioEngine() + let fmt = format + if play { + let q = speaker + let src = AVAudioSourceNode(format: fmt) { _, _, frames, abl -> OSStatus in + let list = UnsafeMutableAudioBufferListPointer(abl) + guard let p = list[0].mData?.assumingMemoryBound(to: Float.self) else { return noErr } + let n = Int(frames) + let got = q.pop(into: p, n) + var i = got + while i < n { + p[i] = 0 + i += 1 + } + return noErr + } + e.attach(src) + e.connect(src, to: e.mainMixerNode, format: fmt) + } + if record { + let input = e.inputNode + let hw = input.outputFormat(forBus: 0) + guard hw.sampleRate > 0, hw.channelCount > 0, + let conv = AVAudioConverter(from: hw, to: fmt) else { return false } + let q = mic + input.installTap(onBus: 0, bufferSize: 1024, format: hw) { buffer, _ in + let cap = AVAudioFrameCount(Double(buffer.frameLength) * fmt.sampleRate / hw.sampleRate) + 32 + guard let out = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: cap) else { return } + var given = false + var err: NSError? + _ = conv.convert(to: out, error: &err) { _, status in + if given { + status.pointee = .noDataNow + return nil + } + given = true + status.pointee = .haveData + return buffer + } + if let d = out.floatChannelData?[0], out.frameLength > 0 { + q.push(UnsafeBufferPointer(start: d, count: Int(out.frameLength))) + } + } + tapped = true + } + do { + e.prepare() + try e.start() + } catch { + if tapped { e.inputNode.removeTap(onBus: 0) } + tapped = false + return false + } + engine = e + return true + } + + func stop() { + if let e = engine { + if tapped { e.inputNode.removeTap(onBus: 0) } + e.stop() + } + tapped = false + engine = nil + speaker.clear() + mic.clear() + } +} + +/// A message the answering machine took. +struct VoiceMessage: Identifiable { + var url: URL + var who: String + var date: Date + var seconds: Int + var id: URL { url } +} + +final class Voice: ObservableObject { + weak var modem: Modem? + let audio = AudioIO() + + @Published var voicemail: Bool { + didSet { save(); configure() } + } + @Published var rings: Int { + didSet { save(); configure() } + } + @Published var muted = false + @Published var listening = false { + didSet { modem.map { sound(Int($0.state)) } } + } + @Published private(set) var messages: [VoiceMessage] = [] + @Published private(set) var greetingSeconds = 0 + @Published private(set) var recording = false + /// what plays: a message's file, or the greeting's + @Published private(set) var playing: URL? + + private let maxSeconds: Int + private var greeting: [Int16] = [] + private var playBuf: [Int16] = [] + private var playPos = 0 + private var recBuf: [Int16] = [] + private var timer: Timer? + private var lastState = Int(DMC_CLOSED) + private var listenOn = false + + /// the longest greeting recorded (s) + private static let greetingMax = 30 + private static let defaults = UserDefaults.standard + + init() { + let d = Voice.defaults + voicemail = d.bool(forKey: "voicemail") + let r = d.integer(forKey: "voicemailRings") + rings = (1...15).contains(r) ? r : 4 + let m = d.integer(forKey: "voicemailMaxSeconds") + maxSeconds = m >= 10 ? m : 120 + loadGreeting() + refreshMessages() + } + + private func save() { + let d = Voice.defaults + d.set(voicemail, forKey: "voicemail") + d.set(rings, forKey: "voicemailRings") + } + + // MARK: - files + + private static var dir: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("D-Modem") + } + private static var messagesDir: URL { dir.appendingPathComponent("Voicemail") } + static var greetingURL: URL { dir.appendingPathComponent("greeting.wav") } + + static func writeWav(_ pcm: [Int16], to url: URL) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + var head = [CChar](repeating: 0, count: 44) + dmc_wav_header(&head, Int32(pcm.count)) + var d = Data(head.map { UInt8(bitPattern: $0) }) + d.reserveCapacity(44 + pcm.count * 2) + for v in pcm { + let u = UInt16(bitPattern: v) + d.append(UInt8(u & 0xff)) + d.append(UInt8(u >> 8)) + } + try d.write(to: url, options: .atomic) + } + + /// a WAV file's samples at 8 kHz, nil if it is not one D-Modem reads + static func readWav(_ url: URL) -> [Int16]? { + guard let d = try? Data(contentsOf: url), d.count < Int(Int32.max) else { return nil } + var pcm: UnsafeMutablePointer? + let n = d.withUnsafeBytes { b in + dmc_wav_decode(b.baseAddress?.assumingMemoryBound(to: CChar.self), + Int32(b.count), &pcm) + } + defer { dmc_free(pcm) } + guard n >= 0, let p = pcm else { return nil } + return Array(UnsafeBufferPointer(start: p, count: Int(n))) + } + + private func loadGreeting() { + greeting = Voice.readWav(Voice.greetingURL) ?? [] + greetingSeconds = (greeting.count + Int(DMC_VOICE_RATE) / 2) / Int(DMC_VOICE_RATE) + } + + /// the answering machine's settings to the session + func configure() { + guard let s = modem?.session else { return } + greeting.withUnsafeBufferPointer { g in + dmc_voicemail_set(s, g.baseAddress, Int32(g.count), Int32(maxSeconds), 0) + } + dmc_voicemail_auto(s, voicemail ? Int32(rings) : 0) + } + + func refreshMessages() { + let fm = FileManager.default + let names = (try? fm.contentsOfDirectory(atPath: Voice.messagesDir.path)) ?? [] + let parse = DateFormatter() + parse.dateFormat = "yyyyMMdd-HHmmss" + parse.locale = Locale(identifier: "en_US_POSIX") + messages = names.filter { $0.hasSuffix(".wav") }.sorted(by: >).compactMap { name in + // 20261111-120501_5551234.wav + let base = String(name.dropLast(4)) + let parts = base.split(separator: "_", maxSplits: 1, omittingEmptySubsequences: false) + guard let stamp = parts.first, let date = parse.date(from: String(stamp)) else { return nil } + let who = parts.count > 1 ? String(parts[1]) : "" + let url = Voice.messagesDir.appendingPathComponent(name) + let size = (try? fm.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0 + return VoiceMessage(url: url, who: who.isEmpty ? "Unknown caller" : who, date: date, + seconds: max(0, (size - 44) / (2 * Int(DMC_VOICE_RATE)))) + } + } + + /// the message the answering machine took, kept + private func saveMessage(from number: String) { + guard let s = modem?.session else { return } + var p: UnsafePointer? + let n = dmc_voice_message(s, &p) + guard n > 0, let p else { return } + let pcm = Array(UnsafeBufferPointer(start: p, count: Int(n))) + let who = String(number.filter { $0.isLetter || $0.isNumber || $0 == "+" || $0 == "#" }.prefix(32)) + let f = DateFormatter() + f.dateFormat = "yyyyMMdd-HHmmss" + f.locale = Locale(identifier: "en_US_POSIX") + let url = Voice.messagesDir.appendingPathComponent("\(f.string(from: Date()))_\(who).wav") + do { + try Voice.writeWav(pcm, to: url) + } catch { + modem?.say("Can't keep the message: \(error.localizedDescription)") + return + } + modem?.addLog("The answering machine took a message.") + refreshMessages() + let c = UNMutableNotificationContent() + c.title = "New voice message" + c.body = "From " + (who.isEmpty ? "an unknown caller" : who) + let center = UNUserNotificationCenter.current() + center.requestAuthorization(options: [.alert, .sound]) { ok, _ in + guard ok else { return } + center.add(UNNotificationRequest(identifier: "voicemail", content: c, trigger: nil)) + } + } + + // MARK: - what the session does + + /// the session's events of voice calls + func event(_ type: Int, text: String, ok: Bool) { + if type == Int(DMC_EV_MESSAGE) { + if ok { saveMessage(from: text) } + } else if type == Int(DMC_EV_VOICE) { + if text == "b" { modem?.say("Busy") } + if text == "l" && lastState != Int(DMC_VOICEMAIL) { modem?.say("The other end hung up") } + } + } + + /// the sound as the call needs it: both ways in a call; the caller (if + /// listening) while the answering machine has the call + func sound(_ st: Int) { + let was = lastState + let inCall = st == Int(DMC_VOICE) || st == Int(DMC_VOICEMAIL) + let listen = st == Int(DMC_VOICEMAIL) && listening + if st == Int(DMC_VOICE) && was != Int(DMC_VOICE) { + stopSound() + listenOn = false + if !audio.start(play: true, record: true) { + modem?.say("No sound: allow D-Modem the microphone in System Settings") + } + } else if listen && !listenOn { + _ = audio.start(play: true, record: false) + listenOn = true + } else if !listen && listenOn { + audio.stop() + listenOn = false + } else if was == Int(DMC_VOICE) && st != Int(DMC_VOICE) { + audio.stop() + } + lastState = st + tick(inCall || playing != nil || recording) + } + + /// the 20 ms tick that a call, a playback or a recording needs + private func tick(_ on: Bool) { + if on && timer == nil { + let t = Timer(timeInterval: 0.02, repeats: true) { [weak self] _ in + self?.modem?.pump() + } + RunLoop.main.add(t, forMode: .common) + timer = t + } else if !on, let t = timer { + t.invalidate() + timer = nil + } + } + + /// before the session runs: the microphone's samples to it (or to the + /// greeting being recorded) + func beforePoll() { + guard audio.running else { return } + var f = [Float](repeating: 0, count: 512) + while true { + let n = f.withUnsafeMutableBufferPointer { audio.mic.pop(into: $0.baseAddress!, 512) } + if n <= 0 { break } + let pcm = f[0..= playBuf.count && audio.speaker.available == 0 { + stopSound() + } + return + } + guard audio.running, let s = modem?.session else { return } + var pcm = [Int16](repeating: 0, count: 512) + while true { + let n = Int(dmc_voice_read(s, &pcm, 512)) + if n <= 0 { break } + let f = pcm[0.. Int(DMC_VOICE_RATE) / 2 { + do { + try Voice.writeWav(pcm, to: Voice.greetingURL) + } catch { + modem?.say("Can't keep the greeting: \(error.localizedDescription)") + } + loadGreeting() + configure() + } + return + } + stopSound() + recBuf = [] + guard audio.start(play: false, record: true) else { + modem?.say("No microphone: allow D-Modem the microphone in System Settings") + return + } + recording = true + tick(true) + } + + func chooseGreeting() { + let p = NSOpenPanel() + p.title = "Greeting" + p.allowedContentTypes = [UTType.wav] + p.allowsMultipleSelection = false + guard p.runModal() == .OK, let url = p.url else { return } + guard let pcm = Voice.readWav(url), !pcm.isEmpty else { + modem?.say("That isn't a WAV file D-Modem can play (PCM, A-law or µ-law)") + return + } + do { + try Voice.writeWav(pcm, to: Voice.greetingURL) + } catch { + modem?.say("Can't keep the greeting: \(error.localizedDescription)") + } + loadGreeting() + configure() + } + + func clearGreeting() { + if playing == Voice.greetingURL { stopSound() } + try? FileManager.default.removeItem(at: Voice.greetingURL) + loadGreeting() + configure() + } +} + +// MARK: - the page + +struct PhonePage: View { + @EnvironmentObject var modem: Modem + @EnvironmentObject var voice: Voice + @State private var number = "" + + private var st: Int { modem.state } + + private var status: String { + let who = modem.callerNumber + switch st { + case Int(DMC_CLOSED): return "The modem isn't running" + case Int(DMC_RINGING): return who.isEmpty ? "Ringing" : "Ringing: \(who)" + case Int(DMC_VOICE): return "In a call" + case Int(DMC_VOICEMAIL): return who.isEmpty ? "Taking a message" : "Taking a message from \(who)" + default: return modem.stateName + } + } + + private let keys = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["*", "0", "#"]] + + private func key(_ k: String) { + if st == Int(DMC_VOICE) { + modem.dtmf(k) + } else { + number += k + } + } + + private static let when: DateFormatter = { + let f = DateFormatter() + f.dateStyle = .medium + f.timeStyle = .short + return f + }() + + var body: some View { + Form { + Section { + LabeledContent("Phone", value: status) + HStack { + TextField("Number to call", text: $number) + .onSubmit { if modem.isIdle { modem.voiceDial(number) } } + Button("Call") { modem.voiceDial(number) } + .disabled(!modem.isIdle) + } + HStack { + Button("Answer") { voice.stopSound(); modem.voiceAnswer() } + .disabled(st != Int(DMC_RINGING)) + Button("Take a Message") { voice.stopSound(); modem.voicemailAnswer() } + .disabled(st != Int(DMC_RINGING)) + if st == Int(DMC_VOICEMAIL) { + Button("Pick Up") { modem.pickUp() } + .help("Talk to the caller yourself") + Toggle("Listen", isOn: $voice.listening) + .help("Hear the caller leave the message") + } + Spacer() + Toggle("Mute", isOn: $voice.muted) + .disabled(st != Int(DMC_VOICE)) + Button("Hang Up", role: .destructive) { modem.hangUp() } + .disabled(![DMC_VOICE, DMC_VOICEMAIL, DMC_DIALING, DMC_ANSWERING] + .map { Int($0) }.contains(st)) + } + Grid(horizontalSpacing: 8, verticalSpacing: 8) { + ForEach(keys, id: \.self) { row in + GridRow { + ForEach(row, id: \.self) { k in + Button { key(k) } label: { + Text(k).font(.title2.monospacedDigit()).frame(width: 48, height: 28) + } + } + } + } + } + .frame(maxWidth: .infinity) + .disabled(!(st == Int(DMC_VOICE) || st == Int(DMC_IDLE) || st == Int(DMC_CLOSED))) + } header: { + Text("Voice Call") + } footer: { + Text("Calls through the modem's voice mode, with the Mac's microphone and speakers.") + } + + Section { + Toggle("Take messages", isOn: $voice.voicemail) + Stepper("Rings before it answers: \(voice.rings)", value: $voice.rings, in: 1...15) + .disabled(!voice.voicemail) + LabeledContent("Greeting") { + HStack { + Text(voice.recording ? "Recording: speak, then Stop" + : voice.greetingSeconds > 0 ? "Your recording (\(voice.greetingSeconds) s)" + : "None: callers hear a beep") + .foregroundStyle(.secondary) + Button { voice.playGreeting() } label: { + Image(systemName: voice.playing == Voice.greetingURL ? "stop.fill" : "play.fill") + } + .help("Play") + .disabled(voice.greetingSeconds == 0 || voice.recording) + Button(voice.recording ? "Stop" : "Record") { voice.recordGreeting() } + .disabled(voice.playing != nil || st == Int(DMC_VOICE) || st == Int(DMC_VOICEMAIL)) + Button { voice.chooseGreeting() } label: { Image(systemName: "folder") } + .help("Use a WAV file") + Button { voice.clearGreeting() } label: { Image(systemName: "trash") } + .help("No greeting: the beep alone") + .disabled(voice.greetingSeconds == 0 || voice.recording) + } + .buttonStyle(.borderless) + } + } header: { + Text("Answering Machine") + } footer: { + Text("It answers calls nobody picks up, plays the greeting and records. Messages are kept on this Mac only.") + } + + Section("Messages") { + if voice.messages.isEmpty { + Text("No messages").foregroundStyle(.secondary) + } + ForEach(voice.messages) { m in + HStack { + VStack(alignment: .leading) { + Text(m.who) + Text("\(PhonePage.when.string(from: m.date)) · \(m.seconds / 60):\(String(format: "%02d", m.seconds % 60))") + .font(.caption).foregroundStyle(.secondary) + } + Spacer() + Button { voice.play(m) } label: { + Image(systemName: voice.playing == m.url ? "stop.fill" : "play.fill") + } + .help("Play") + .disabled(voice.recording || st == Int(DMC_VOICE)) + Button { voice.delete(m) } label: { Image(systemName: "trash") } + .help("Delete") + } + .buttonStyle(.borderless) + } + } + } + .formStyle(.grouped) + } +} diff --git a/macos/project.yml b/macos/project.yml index 0b8e16f..aa96954 100644 --- a/macos/project.yml +++ b/macos/project.yml @@ -28,9 +28,16 @@ targets: INFOPLIST_KEY_CFBundleDisplayName: D-Modem INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.utilities INFOPLIST_KEY_NSHumanReadableCopyright: Copyright (C) 2026 D-Modem Authors. AGPL-3.0-only. + INFOPLIST_KEY_NSMicrophoneUsageDescription: D-Modem uses the microphone for voice calls and to record the answering machine's greeting. ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon CODE_SIGN_IDENTITY: "-" ENABLE_HARDENED_RUNTIME: YES # dmodemd runs as a child process and the modem's pty is opened: # no sandbox ENABLE_APP_SANDBOX: NO + # the microphone, for voice calls (the hardened runtime asks for it) + ENABLE_RESOURCE_ACCESS_AUDIO_INPUT: YES + entitlements: + path: DModem/DModem.entitlements + properties: + com.apple.security.device.audio-input: true diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index b8b37d0..faf6729 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -9,9 +9,11 @@ add_executable(dmodem WIN32 src/term.cpp src/settings.cpp src/config.cpp + src/voice.cpp + src/audio.cpp res/app.rc) target_include_directories(dmodem PRIVATE src) -target_link_libraries(dmodem PRIVATE dmodemctl comctl32 wsock32 comdlg32 gdi32) +target_link_libraries(dmodem PRIVATE dmodemctl comctl32 wsock32 comdlg32 gdi32 winmm) if(MSVC) target_compile_definitions(dmodem PRIVATE _CRT_SECURE_NO_WARNINGS) # (a manifest of our own in app.rc) diff --git a/windows/build-watcom.sh b/windows/build-watcom.sh index f0d6a0e..8d79a45 100755 --- a/windows/build-watcom.sh +++ b/windows/build-watcom.sh @@ -43,7 +43,7 @@ wrc -q -r -bt=nt -i="$WATCOM/h/nt" -i="$here/src" -i="$here/res" \ # Windows 95 and NT 4 take a subsystem version of 4.0 echo "runtime windows=4.0" for o in $objs; do echo "file $o"; done - echo "library comctl32.lib, wsock32.lib, comdlg32.lib" + echo "library comctl32.lib, wsock32.lib, comdlg32.lib, winmm.lib" echo "option resource=app.res" } > dmodem.lnk wlink @dmodem.lnk diff --git a/windows/src/app.h b/windows/src/app.h index 86dabde..ea9a262 100644 --- a/windows/src/app.h +++ b/windows/src/app.h @@ -54,8 +54,14 @@ struct Config { char tcp[256]; /* host:port */ char com[32]; /* COM1 */ char init[256]; /* commands when the modem opens */ + /* the answering machine ([voice]): on, after how many RINGs, a + message's longest (s) */ + int voicemail, vm_rings, vm_max; }; +/* where the app keeps its files: %APPDATA%\D-Modem, or beside the + app */ +void app_data_dir(char *out, int n); void config_load(Config *c); void config_save(const Config *c); /* "SIP: alice@sip.example.com" and the like, into out */ @@ -70,7 +76,7 @@ typedef void (*ResponseFn)(const dmc_event *ev, void *data); struct App { HINSTANCE inst; HWND main, tabs; - HWND pages[5]; + HWND pages[6]; HFONT font, bold_font, big_font, mono_font; Config cfg; dmc_session *s; @@ -91,9 +97,13 @@ void link_pump(); void link_socket(WPARAM w, LPARAM l); void link_type(const char *data, int n); int link_command(const char *cmd, int flags, ResponseFn fn, void *data); +/* fn gets the response of the session's command tag (dmc_voice_dial()'s + and the like) */ +void link_wait(int tag, ResponseFn fn, void *data); #define WM_APP_SOCKET (WM_APP + 1) #define TIMER_PUMP 1 +#define TIMER_VOICE 2 /* main.cpp */ void app_log(const char *line); @@ -131,6 +141,26 @@ void settings_load(); void settings_clear(); void settings_state(); +/* voice.cpp: the Phone page: voice calls, the answering machine and + its messages */ +HWND voice_page_new(HWND parent); +void voice_page_layout(HWND page, int w, int h); +void voice_state(); +void voice_event(const dmc_event *ev); +/* the answering machine's settings to the session */ +void voice_configure(); + +/* audio.cpp: the sound card (waveOut and waveIn: Windows 95 has them), + 16-bit mono at 8 kHz */ +/* the speaker's next samples: how many of n there were (the rest + silence); the microphone's */ +typedef int (*AudioPull)(short *pcm, int n); +typedef void (*AudioPush)(const short *pcm, int n); +/* sound from pull and to push (either NULL for none): false if there + is no sound card */ +bool audio_start(AudioPull pull, AudioPush push); +void audio_stop(); + /* util */ /* UTF-8 to the ANSI code page (Windows 9x has few W functions) */ void to_ansi(const char *utf8, char *out, int n); diff --git a/windows/src/audio.cpp b/windows/src/audio.cpp new file mode 100644 index 0000000..32e5bae --- /dev/null +++ b/windows/src/audio.cpp @@ -0,0 +1,162 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * audio.cpp - the sound card for voice calls, greetings and messages: + * waveOut and waveIn, which Windows 95 has, at the line's + * own 8 kHz (the wave mapper converts), their buffers + * handed back as window messages (no thread of ours) + * + * Each buffer that comes back is a chance to run the session too, so + * that our samples reach the line on time where the timer is coarse + * (Windows 9x's ticks are 55 ms). + */ +#include + +#include "app.h" +#include + +/* six buffers of 20 ms to the speaker, four from the microphone */ +#define FRAME (DMC_VOICE_RATE / 50) +#define OUT_BUFS 6 +#define IN_BUFS 4 + +static HWND win; +static HWAVEOUT wo; +static HWAVEIN wi; +static WAVEHDR oh[OUT_BUFS], ih[IN_BUFS]; +static short ob[OUT_BUFS][FRAME], ib[IN_BUFS][FRAME]; +static AudioPull pull_fn; +static AudioPush push_fn; +static bool stopping; + +/* a speaker's buffer filled from pull (silence where it has none) */ +static void fill(WAVEHDR *h) +{ + short *p = (short *)h->lpData; + int got = pull_fn ? pull_fn(p, FRAME) : 0; + if (got < 0) + got = 0; + if (got < FRAME) + memset(p + got, 0, (FRAME - got) * sizeof(short)); +} + +static LRESULT CALLBACK audio_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) +{ + WAVEHDR *h = (WAVEHDR *)lp; + switch (m) { + case MM_WOM_DONE: + /* (a buffer of a device closed since, or queued again + already, is not ours to write) */ + if ((HWAVEOUT)wp != wo || !wo || stopping || + !(h->dwFlags & WHDR_DONE)) + return 0; + fill(h); + waveOutWrite(wo, h, sizeof(*h)); + link_pump(); + return 0; + case MM_WIM_DATA: + if ((HWAVEIN)wp != wi || !wi || stopping || + !(h->dwFlags & WHDR_DONE)) + return 0; + if (push_fn && h->dwBytesRecorded) + push_fn((const short *)h->lpData, + (int)(h->dwBytesRecorded / sizeof(short))); + waveInAddBuffer(wi, h, sizeof(*h)); + return 0; + } + return DefWindowProc(w, m, wp, lp); +} + +static bool make_window() +{ + if (win) + return true; + WNDCLASS wc; + memset(&wc, 0, sizeof(wc)); + wc.lpfnWndProc = audio_proc; + wc.hInstance = app.inst; + wc.lpszClassName = "DModemAudio"; + RegisterClass(&wc); + /* (hidden: it only takes the devices' messages) */ + win = CreateWindowEx(0, "DModemAudio", "", WS_POPUP, 0, 0, 0, 0, + NULL, NULL, app.inst, NULL); + return win != NULL; +} + +static void format(WAVEFORMATEX *f) +{ + memset(f, 0, sizeof(*f)); + f->wFormatTag = WAVE_FORMAT_PCM; + f->nChannels = 1; + f->nSamplesPerSec = DMC_VOICE_RATE; + f->wBitsPerSample = 16; + f->nBlockAlign = 2; + f->nAvgBytesPerSec = DMC_VOICE_RATE * 2; +} + +bool audio_start(AudioPull pull, AudioPush push) +{ + audio_stop(); + if (!make_window()) + return false; + pull_fn = pull; + push_fn = push; + WAVEFORMATEX f; + format(&f); + bool ok = true; + if (pull) { + if (waveOutOpen(&wo, WAVE_MAPPER, &f, (DWORD_PTR)win, 0, + CALLBACK_WINDOW) != MMSYSERR_NOERROR) { + wo = NULL; + ok = false; + } + for (int i = 0; wo && i < OUT_BUFS; i++) { + memset(&oh[i], 0, sizeof(oh[i])); + oh[i].lpData = (LPSTR)ob[i]; + oh[i].dwBufferLength = sizeof(ob[i]); + waveOutPrepareHeader(wo, &oh[i], sizeof(oh[i])); + fill(&oh[i]); + waveOutWrite(wo, &oh[i], sizeof(oh[i])); + } + } + if (push) { + if (waveInOpen(&wi, WAVE_MAPPER, &f, (DWORD_PTR)win, 0, + CALLBACK_WINDOW) != MMSYSERR_NOERROR) { + wi = NULL; + ok = false; + } + for (int i = 0; wi && i < IN_BUFS; i++) { + memset(&ih[i], 0, sizeof(ih[i])); + ih[i].lpData = (LPSTR)ib[i]; + ih[i].dwBufferLength = sizeof(ib[i]); + waveInPrepareHeader(wi, &ih[i], sizeof(ih[i])); + waveInAddBuffer(wi, &ih[i], sizeof(ih[i])); + } + if (wi) + waveInStart(wi); + } + return ok; +} + +void audio_stop() +{ + stopping = true; + if (wo) { + waveOutReset(wo); + for (int i = 0; i < OUT_BUFS; i++) + waveOutUnprepareHeader(wo, &oh[i], sizeof(oh[i])); + waveOutClose(wo); + wo = NULL; + } + if (wi) { + waveInReset(wi); + for (int i = 0; i < IN_BUFS; i++) + waveInUnprepareHeader(wi, &ih[i], sizeof(ih[i])); + waveInClose(wi); + wi = NULL; + } + pull_fn = NULL; + push_fn = NULL; + stopping = false; +} diff --git a/windows/src/config.cpp b/windows/src/config.cpp index 371be0e..1c09afe 100644 --- a/windows/src/config.cpp +++ b/windows/src/config.cpp @@ -18,23 +18,31 @@ #define OPENFILENAME_SIZE_VERSION_400 76 #endif -static void ini_path(char *out, int n) +void app_data_dir(char *out, int n) { char dir[MAX_PATH]; DWORD k = GetEnvironmentVariable("APPDATA", dir, sizeof(dir)); - if (k > 0 && k < sizeof(dir)) { + if (k > 0 && k < sizeof(dir) - 10) { strcat(dir, "\\D-Modem"); CreateDirectory(dir, NULL); - _snprintf(out, n, "%s\\dmodem.ini", dir); + _snprintf(out, n, "%s", dir); } else { GetModuleFileName(NULL, out, n); char *slash = strrchr(out, '\\'); if (slash) - strcpy(slash + 1, "dmodem.ini"); + *slash = '\0'; } out[n - 1] = '\0'; } +static void ini_path(char *out, int n) +{ + char dir[MAX_PATH]; + app_data_dir(dir, sizeof(dir)); + _snprintf(out, n, "%s\\dmodem.ini", dir); + out[n - 1] = '\0'; +} + static void get(const char *ini, const char *key, const char *def, char *out, int n) { @@ -84,6 +92,14 @@ void config_load(Config *c) get(ini, "tcp", "127.0.0.1:2323", c->tcp, sizeof(c->tcp)); get(ini, "com", "COM1", c->com, sizeof(c->com)); get(ini, "init", "", c->init, sizeof(c->init)); + /* the answering machine: off until the user turns it on */ + c->voicemail = (int)GetPrivateProfileInt("voice", "voicemail", 0, ini); + c->vm_rings = (int)GetPrivateProfileInt("voice", "rings", 4, ini); + if (c->vm_rings < 1 || c->vm_rings > 15) + c->vm_rings = 4; + c->vm_max = (int)GetPrivateProfileInt("voice", "max-seconds", 120, ini); + if (c->vm_max < 10) + c->vm_max = 120; } void config_save(const Config *c) @@ -104,6 +120,16 @@ void config_save(const Config *c) put(ini, "tcp", c->tcp); put(ini, "com", c->com); put(ini, "init", c->init); + char b[16]; + _snprintf(b, sizeof(b), "%d", c->voicemail); + b[sizeof(b) - 1] = '\0'; + WritePrivateProfileString("voice", "voicemail", b, ini); + _snprintf(b, sizeof(b), "%d", c->vm_rings); + b[sizeof(b) - 1] = '\0'; + WritePrivateProfileString("voice", "rings", b, ini); + _snprintf(b, sizeof(b), "%d", c->vm_max); + b[sizeof(b) - 1] = '\0'; + WritePrivateProfileString("voice", "max-seconds", b, ini); } void config_summary(const Config *c, char *out, int n) diff --git a/windows/src/link.cpp b/windows/src/link.cpp index 7d3a768..d4a6468 100644 --- a/windows/src/link.cpp +++ b/windows/src/link.cpp @@ -543,6 +543,21 @@ void link_type(const char *data, int n) link_pump(); } +void link_wait(int tag, ResponseFn fn, void *data) +{ + if (tag <= 0) + return; + Waiting *w = (Waiting *)calloc(1, sizeof(*w)); + if (!w) + return; + w->tag = tag; + w->fn = fn; + w->data = data; + w->next = waiting; + waiting = w; + link_pump(); +} + int link_command(const char *cmd, int flags, ResponseFn fn, void *data) { int tag = dmc_command(app.s, cmd, flags, 0); diff --git a/windows/src/main.cpp b/windows/src/main.cpp index 72474b5..f3d4d2b 100644 --- a/windows/src/main.cpp +++ b/windows/src/main.cpp @@ -16,9 +16,10 @@ App app; static HWND status_bar; -enum { PAGE_MODEM, PAGE_TERM, PAGE_SETTINGS, PAGE_STATS, PAGE_LOG, PAGES }; +enum { PAGE_MODEM, PAGE_PHONE, PAGE_TERM, PAGE_SETTINGS, PAGE_STATS, + PAGE_LOG, PAGES }; static const char *const page_names[PAGES] = { - "Modem", "Terminal", "Settings", "Call Stats", "Log" + "Modem", "Phone", "Terminal", "Settings", "Call Stats", "Log" }; HWND make_child(const char *cls, const char *text, DWORD style, HWND parent, @@ -117,6 +118,7 @@ void app_state() t[sizeof(t) - 1] = '\0'; SendMessage(status_bar, SB_SETTEXT, 1, (LPARAM)t); modem_page_state(); + voice_state(); term_state(); settings_state(); } @@ -162,6 +164,10 @@ void app_event(const dmc_event *ev) case DMC_EV_CALLER: app_state(); break; + case DMC_EV_VOICE: + case DMC_EV_MESSAGE: + voice_event(ev); + break; } } @@ -191,6 +197,7 @@ static void layout() for (int p = 0; p < PAGES; p++) MoveWindow(app.pages[p], x, y, w, h, TRUE); modem_page_layout(app.pages[PAGE_MODEM], w, h); + voice_page_layout(app.pages[PAGE_PHONE], w, h); term_page_layout(app.pages[PAGE_TERM], w, h); settings_page_layout(app.pages[PAGE_SETTINGS], w, h); stats_page_layout(app.pages[PAGE_STATS], w, h); @@ -224,6 +231,7 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) TabCtrl_InsertItem(app.tabs, p, &it); } app.pages[PAGE_MODEM] = modem_page_new(w); + app.pages[PAGE_PHONE] = voice_page_new(w); app.pages[PAGE_TERM] = term_page_new(w); app.pages[PAGE_SETTINGS] = settings_page_new(w); app.pages[PAGE_STATS] = stats_page_new(w); @@ -274,7 +282,7 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) } break; case WM_TIMER: - if (wp == TIMER_PUMP) + if (wp == TIMER_PUMP || wp == TIMER_VOICE) link_pump(); return 0; case WM_APP_SOCKET: @@ -282,6 +290,8 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) return 0; case WM_DESTROY: KillTimer(w, TIMER_PUMP); + KillTimer(w, TIMER_VOICE); + audio_stop(); if (link_running()) link_stop(); PostQuitMessage(0); diff --git a/windows/src/resource.h b/windows/src/resource.h index af4855c..c31ec32 100644 --- a/windows/src/resource.h +++ b/windows/src/resource.h @@ -57,6 +57,33 @@ /* the Log page */ #define IDC_LOG 800 +/* the Phone page */ +#define IDC_V_STATUS 1000 +#define IDC_V_CALLBOX 1001 +#define IDC_V_NUMLABEL 1002 +#define IDC_V_NUMBER 1003 +#define IDC_V_CALL 1004 +#define IDC_V_ANSWER 1005 +#define IDC_V_MESSAGE 1006 +#define IDC_V_PICKUP 1007 +#define IDC_V_HANGUP 1008 +#define IDC_V_MUTE 1009 +#define IDC_V_LISTEN 1010 +#define IDC_V_VMBOX 1011 +#define IDC_V_VMON 1012 +#define IDC_V_RINGSLABEL 1013 +#define IDC_V_RINGS 1014 +#define IDC_V_GREETING 1015 +#define IDC_V_RECORD 1016 +#define IDC_V_PLAYGREET 1017 +#define IDC_V_CHOOSE 1018 +#define IDC_V_CLEARGREET 1019 +#define IDC_V_MSGBOX 1020 +#define IDC_V_MESSAGES 1021 +#define IDC_V_PLAY 1022 +#define IDC_V_DELETE 1023 +#define IDC_V_KEY 1030 /* 1030 to 1041: 1-9, *, 0, # */ + /* the Line Settings dialog */ #define IDD_LINE 900 #define IDC_L_DMODEMD 901 diff --git a/windows/src/voice.cpp b/windows/src/voice.cpp new file mode 100644 index 0000000..e02a9ef --- /dev/null +++ b/windows/src/voice.cpp @@ -0,0 +1,811 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * voice.cpp - the Phone page: voice calls dialled and answered, their + * sound on the sound card, the keypad's DTMF; the answering + * machine (off until the user turns it on), its greeting + * and the messages it took, kept as WAV files in the app's + * folder (%APPDATA%\D-Modem\Voicemail) + */ +#include +#include +#include + +#include "app.h" +#include +#include "resource.h" + +#ifndef OPENFILENAME_SIZE_VERSION_400 +#define OPENFILENAME_SIZE_VERSION_400 76 +#endif + +/* the longest greeting recorded (s), the messages listed */ +#define GREETING_MAX_S 30 +#define MAX_MESSAGES 200 + +static HWND page; +static int last_state = DMC_CLOSED; +static bool muted, listening, listen_on; +/* what plays (a message, the greeting), and what is recorded */ +static short *play_pcm; +static int play_n, play_pos; +static bool play_done_posted; +static short *rec_pcm; +static int rec_n; +static bool recording; +/* the greeting, 8 kHz */ +static short *greeting; +static int greeting_n; +/* the messages' file names, as the list shows them */ +static char names[MAX_MESSAGES][64]; +static int name_count; + +#define WM_APP_PLAYED (WM_APP + 3) + +/* + * files + */ + +static void messages_dir(char *out, int n) +{ + char d[MAX_PATH]; + app_data_dir(d, sizeof(d)); + _snprintf(out, n, "%s\\Voicemail", d); + out[n - 1] = '\0'; +} + +static void greeting_path(char *out, int n) +{ + char d[MAX_PATH]; + app_data_dir(d, sizeof(d)); + _snprintf(out, n, "%s\\greeting.wav", d); + out[n - 1] = '\0'; +} + +static bool write_wav(const char *path, const short *pcm, int n) +{ + FILE *f = fopen(path, "wb"); + if (!f) + return false; + char h[44]; + dmc_wav_header(h, n); + bool ok = fwrite(h, 1, 44, f) == 44; + for (int i = 0; ok && i < n; i++) { + unsigned char b[2]; + b[0] = (unsigned char)(pcm[i] & 0xff); + b[1] = (unsigned char)((pcm[i] >> 8) & 0xff); + ok = fwrite(b, 1, 2, f) == 2; + } + if (fclose(f)) + ok = false; + return ok; +} + +/* a WAV file's samples at 8 kHz: how many (*pcm to dmc_free()), -1 */ +static int read_wav(const char *path, short **pcm) +{ + *pcm = NULL; + FILE *f = fopen(path, "rb"); + if (!f) + return -1; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + if (len <= 0 || len > 64L * 1024 * 1024) { + fclose(f); + return -1; + } + char *b = (char *)malloc(len); + if (!b) { + fclose(f); + return -1; + } + int n = -1; + if (fread(b, 1, len, f) == (size_t)len) + n = dmc_wav_decode(b, (int)len, (int16_t **)pcm); + fclose(f); + free(b); + return n; +} + +static void load_greeting() +{ + char p[MAX_PATH]; + greeting_path(p, sizeof(p)); + if (greeting) + dmc_free(greeting); + greeting = NULL; + greeting_n = 0; + short *pcm; + int n = read_wav(p, &pcm); + if (n > 0) { + greeting = pcm; + greeting_n = n; + } else if (pcm) { + dmc_free(pcm); + } +} + +void voice_configure() +{ + dmc_voicemail_set(app.s, (const int16_t *)greeting, greeting_n, + app.cfg.vm_max, 0); + dmc_voicemail_auto(app.s, app.cfg.voicemail ? app.cfg.vm_rings : 0); +} + +/* + * sound + */ + +static int call_pull(short *pcm, int n) +{ + return dmc_voice_read(app.s, (int16_t *)pcm, n); +} + +static void call_push(const short *pcm, int n) +{ + if (!muted) + dmc_voice_write(app.s, (const int16_t *)pcm, n); +} + +static int play_pull(short *pcm, int n) +{ + int k = play_n - play_pos; + if (k > n) + k = n; + if (k > 0) { + memcpy(pcm, play_pcm + play_pos, k * sizeof(short)); + play_pos += k; + } + /* (stopped from the message loop, not inside the device's) */ + if (play_pos >= play_n && !play_done_posted) { + play_done_posted = true; + PostMessage(page, WM_APP_PLAYED, 0, 0); + } + return k; +} + +static void record_push(const short *pcm, int n) +{ + int room = GREETING_MAX_S * DMC_VOICE_RATE - rec_n; + if (n > room) + n = room; + if (n > 0 && rec_pcm) { + memcpy(rec_pcm + rec_n, pcm, n * sizeof(short)); + rec_n += n; + } +} + +static void stop_sound() +{ + audio_stop(); + if (play_pcm) + dmc_free(play_pcm); + play_pcm = NULL; + play_n = play_pos = 0; + free(rec_pcm); + rec_pcm = NULL; + rec_n = 0; + recording = false; +} + +/* pcm (taken: dmc_free()d when done) played */ +static void play(short *pcm, int n) +{ + stop_sound(); + play_pcm = pcm; + play_n = n; + play_pos = 0; + play_done_posted = false; + if (!audio_start(play_pull, NULL)) { + app_message("No sound card to play it on"); + stop_sound(); + } + voice_state(); +} + +/* + * the messages + */ + +static void refresh_messages(); + +static void insert_column(HWND lv, int i, const char *t, int w) +{ + LVCOLUMN c; + memset(&c, 0, sizeof(c)); + c.mask = LVCF_TEXT | LVCF_WIDTH; + c.pszText = (char *)t; + c.cx = w; + ListView_InsertColumn(lv, i, &c); +} + +static int newest_first(const void *x, const void *y) +{ + return -strcmp((const char *)x, (const char *)y); +} + +/* the list from the files: 20261111-120501_5551234.wav */ +static void refresh_messages() +{ + HWND lv = GetDlgItem(page, IDC_V_MESSAGES); + ListView_DeleteAllItems(lv); + name_count = 0; + char dir[MAX_PATH], pat[MAX_PATH]; + messages_dir(dir, sizeof(dir)); + _snprintf(pat, sizeof(pat), "%s\\*.wav", dir); + pat[sizeof(pat) - 1] = '\0'; + WIN32_FIND_DATA fd; + HANDLE h = FindFirstFile(pat, &fd); + if (h != INVALID_HANDLE_VALUE) { + do { + if (name_count < MAX_MESSAGES && + strlen(fd.cFileName) < sizeof(names[0])) { + strcpy(names[name_count], fd.cFileName); + name_count++; + } + } while (FindNextFile(h, &fd)); + FindClose(h); + } + qsort(names, name_count, sizeof(names[0]), newest_first); + int row = 0; + for (int i = 0; i < name_count; i++) { + int y, mo, da, hh, mi, se; + char who[64] = ""; + if (sscanf(names[i], "%4d%2d%2d-%2d%2d%2d_%63[^.]", &y, &mo, + &da, &hh, &mi, &se, who) < 6) + continue; + char path[MAX_PATH], when[64], len[32]; + _snprintf(path, sizeof(path), "%s\\%s", dir, names[i]); + path[sizeof(path) - 1] = '\0'; + long secs = 0; + FILE *f = fopen(path, "rb"); + if (f) { + fseek(f, 0, SEEK_END); + long bytes = ftell(f); + fclose(f); + if (bytes > 44) + secs = (bytes - 44) / (2 * DMC_VOICE_RATE); + } + _snprintf(when, sizeof(when), "%04d-%02d-%02d %02d:%02d", y, mo, + da, hh, mi); + when[sizeof(when) - 1] = '\0'; + _snprintf(len, sizeof(len), "%ld:%02ld", secs / 60, secs % 60); + len[sizeof(len) - 1] = '\0'; + LVITEM it; + memset(&it, 0, sizeof(it)); + it.mask = LVIF_TEXT | LVIF_PARAM; + it.iItem = row; + it.pszText = who[0] ? who : (char *)"Unknown caller"; + it.lParam = i; + ListView_InsertItem(lv, &it); + ListView_SetItemText(lv, row, 1, when); + ListView_SetItemText(lv, row, 2, len); + row++; + } +} + +/* the selected message's path: false if none is */ +static bool selected(char *path, int n) +{ + HWND lv = GetDlgItem(page, IDC_V_MESSAGES); + int row = ListView_GetNextItem(lv, -1, LVNI_SELECTED); + if (row < 0) + return false; + LVITEM it; + memset(&it, 0, sizeof(it)); + it.mask = LVIF_PARAM; + it.iItem = row; + if (!ListView_GetItem(lv, &it) || it.lParam < 0 || + it.lParam >= name_count) + return false; + char dir[MAX_PATH]; + messages_dir(dir, sizeof(dir)); + _snprintf(path, n, "%s\\%s", dir, names[it.lParam]); + path[n - 1] = '\0'; + return true; +} + +static void save_message(const char *number) +{ + const int16_t *pcm; + int n = dmc_voice_message(app.s, &pcm); + if (n <= 0) + return; + char who[40]; + int k = 0; + for (const char *p = number; *p && k < 32; p++) + if ((*p >= '0' && *p <= '9') || (*p >= 'A' && *p <= 'Z') || + (*p >= 'a' && *p <= 'z') || *p == '+' || *p == '#') + who[k++] = *p; + who[k] = '\0'; + SYSTEMTIME t; + GetLocalTime(&t); + char dir[MAX_PATH], path[MAX_PATH]; + messages_dir(dir, sizeof(dir)); + CreateDirectory(dir, NULL); + _snprintf(path, sizeof(path), "%s\\%04d%02d%02d-%02d%02d%02d_%s.wav", + dir, t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, + t.wSecond, who); + path[sizeof(path) - 1] = '\0'; + if (!write_wav(path, (const short *)pcm, n)) { + app_message("Can't keep the message"); + return; + } + char m[96]; + _snprintf(m, sizeof(m), "New voice message from %s", + who[0] ? who : "an unknown caller"); + m[sizeof(m) - 1] = '\0'; + app_message(m); + app_log("The answering machine took a message."); + if (GetForegroundWindow() != app.main) + FlashWindow(app.main, TRUE); + refresh_messages(); +} + +/* + * the greeting + */ + +static void record_greeting() +{ + if (recording) { + /* stopped: kept */ + short *pcm = rec_pcm; + int n = rec_n; + rec_pcm = NULL; + stop_sound(); + if (n > DMC_VOICE_RATE / 2) { + char p[MAX_PATH]; + greeting_path(p, sizeof(p)); + if (!write_wav(p, pcm, n)) + app_message("Can't keep the greeting"); + load_greeting(); + voice_configure(); + } + free(pcm); + voice_state(); + return; + } + stop_sound(); + rec_pcm = (short *)malloc(GREETING_MAX_S * DMC_VOICE_RATE * + sizeof(short)); + rec_n = 0; + recording = rec_pcm != NULL; + if (recording && !audio_start(NULL, record_push)) { + app_message("No microphone to record with"); + stop_sound(); + } + voice_state(); +} + +static void choose_greeting() +{ + char file[MAX_PATH] = ""; + OPENFILENAME o; + memset(&o, 0, sizeof(o)); + /* (the size Windows 95 and NT 4 know) */ + o.lStructSize = OPENFILENAME_SIZE_VERSION_400; + o.hwndOwner = app.main; + o.lpstrFilter = "WAV files\0*.wav\0"; + o.lpstrFile = file; + o.nMaxFile = sizeof(file); + o.lpstrTitle = "Greeting"; + o.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; + if (!GetOpenFileName(&o)) + return; + short *pcm; + int n = read_wav(file, &pcm); + if (n <= 0) { + if (pcm) + dmc_free(pcm); + app_message("That isn't a WAV file D-Modem can play"); + return; + } + char p[MAX_PATH]; + greeting_path(p, sizeof(p)); + if (!write_wav(p, pcm, n)) + app_message("Can't keep the greeting"); + dmc_free(pcm); + load_greeting(); + voice_configure(); + voice_state(); +} + +/* + * calls + */ + +static void dialled(const dmc_event *ev, void *data) +{ + (void)data; + if (!ev->ok) + app_message(!strcmp(ev->result, "ERROR") ? + "The modem has no voice mode" : ev->result); +} + +static void voice_command(HWND p, int id, int code) +{ + (void)code; + if (id >= IDC_V_KEY && id < IDC_V_KEY + 12) { + static const char keys[] = "123456789*0#"; + char k = keys[id - IDC_V_KEY]; + if (dmc_state(app.s) == DMC_VOICE) { + dmc_voice_dtmf(app.s, k); + } else { + HWND e = GetDlgItem(p, IDC_V_NUMBER); + char s[2] = { k, 0 }; + int len = GetWindowTextLength(e); + SendMessage(e, EM_SETSEL, len, len); + SendMessage(e, EM_REPLACESEL, FALSE, (LPARAM)s); + } + return; + } + switch (id) { + case IDC_V_CALL: { + char n[128]; + GetDlgItemText(p, IDC_V_NUMBER, n, sizeof(n)); + if (!n[0]) { + app_message("Enter a number to call"); + return; + } + stop_sound(); + int tag = dmc_voice_dial(app.s, n); + if (tag > 0) + link_wait(tag, dialled, NULL); + break; + } + case IDC_V_ANSWER: { + stop_sound(); + int tag = dmc_voice_answer(app.s); + if (tag > 0) + link_wait(tag, dialled, NULL); + break; + } + case IDC_V_MESSAGE: { + stop_sound(); + int tag = dmc_voicemail_answer(app.s); + if (tag > 0) + link_wait(tag, dialled, NULL); + break; + } + case IDC_V_PICKUP: + dmc_voice_pickup(app.s); + link_pump(); + break; + case IDC_V_HANGUP: + dmc_hangup(app.s); + link_pump(); + break; + case IDC_V_MUTE: + muted = IsDlgButtonChecked(p, IDC_V_MUTE) == BST_CHECKED; + break; + case IDC_V_LISTEN: + listening = IsDlgButtonChecked(p, IDC_V_LISTEN) == BST_CHECKED; + voice_state(); + break; + case IDC_V_VMON: + app.cfg.voicemail = IsDlgButtonChecked(p, IDC_V_VMON) == + BST_CHECKED; + config_save(&app.cfg); + voice_configure(); + voice_state(); + break; + case IDC_V_RINGS: + if (code == CBN_SELCHANGE) { + int i = (int)SendDlgItemMessage(p, IDC_V_RINGS, + CB_GETCURSEL, 0, 0); + if (i >= 0) { + app.cfg.vm_rings = i + 1; + config_save(&app.cfg); + voice_configure(); + } + } + break; + case IDC_V_RECORD: + record_greeting(); + break; + case IDC_V_PLAYGREET: + if (play_pcm) { + stop_sound(); + } else if (greeting_n) { + short *c = (short *)malloc(greeting_n * sizeof(short)); + if (c) { + memcpy(c, greeting, greeting_n * sizeof(short)); + play(c, greeting_n); + } + } + voice_state(); + break; + case IDC_V_CHOOSE: + choose_greeting(); + break; + case IDC_V_CLEARGREET: { + char g[MAX_PATH]; + greeting_path(g, sizeof(g)); + DeleteFile(g); + load_greeting(); + voice_configure(); + voice_state(); + break; + } + case IDC_V_PLAY: { + char path[MAX_PATH]; + if (play_pcm) { + stop_sound(); + voice_state(); + break; + } + if (!selected(path, sizeof(path))) { + app_message("Select a message to play"); + break; + } + short *pcm; + int n = read_wav(path, &pcm); + if (n > 0) { + play(pcm, n); + } else { + if (pcm) + dmc_free(pcm); + app_message("Can't read the message"); + } + break; + } + case IDC_V_DELETE: { + char path[MAX_PATH]; + if (!selected(path, sizeof(path))) + break; + stop_sound(); + if (!DeleteFile(path)) + app_message("Can't delete the message"); + refresh_messages(); + voice_state(); + break; + } + } +} + +/* the sound as the call needs it: both ways in a call; the caller (if + listening) while the answering machine has the call; the 20 ms timer + of a call */ +static void call_sound(int st) +{ + int was = last_state; + bool in = st == DMC_VOICE || st == DMC_VOICEMAIL; + bool listen = st == DMC_VOICEMAIL && listening; + if (in) + SetTimer(app.main, TIMER_VOICE, 20, NULL); + else if (st != DMC_HANGING_UP) + KillTimer(app.main, TIMER_VOICE); + if (st == DMC_VOICE && was != DMC_VOICE) { + stop_sound(); + listen_on = false; + if (!audio_start(call_pull, call_push)) + app_message("No sound card: the call has no sound"); + } else if (listen && !listen_on) { + audio_start(call_pull, NULL); + listen_on = true; + } else if (!listen && listen_on) { + audio_stop(); + listen_on = false; + } else if (was == DMC_VOICE && st != DMC_VOICE) { + audio_stop(); + } + last_state = st; +} + +void voice_state() +{ + if (!page) + return; + int st = dmc_state(app.s); + call_sound(st); + char s[160]; + const char *who = dmc_caller_number(app.s); + switch (st) { + case DMC_CLOSED: + strcpy(s, "The modem isn't running"); + break; + case DMC_RINGING: + _snprintf(s, sizeof(s), "Ringing%s%s", who[0] ? ": " : "", who); + break; + case DMC_VOICE: + strcpy(s, "In a call"); + break; + case DMC_VOICEMAIL: + _snprintf(s, sizeof(s), "Taking a message%s%s", + who[0] ? " from " : "", who); + break; + default: + _snprintf(s, sizeof(s), "%s", dmc_state_name(st)); + break; + } + s[sizeof(s) - 1] = '\0'; + char a[200]; + to_ansi(s, a, sizeof(a)); + SetDlgItemText(page, IDC_V_STATUS, a); + bool idle = st == DMC_IDLE; + EnableWindow(GetDlgItem(page, IDC_V_CALL), idle); + EnableWindow(GetDlgItem(page, IDC_V_ANSWER), st == DMC_RINGING); + EnableWindow(GetDlgItem(page, IDC_V_MESSAGE), st == DMC_RINGING); + EnableWindow(GetDlgItem(page, IDC_V_PICKUP), st == DMC_VOICEMAIL); + EnableWindow(GetDlgItem(page, IDC_V_LISTEN), st == DMC_VOICEMAIL); + EnableWindow(GetDlgItem(page, IDC_V_HANGUP), + st == DMC_VOICE || st == DMC_VOICEMAIL || + st == DMC_DIALING || st == DMC_ANSWERING); + EnableWindow(GetDlgItem(page, IDC_V_MUTE), st == DMC_VOICE); + bool keys = st == DMC_VOICE || idle || st == DMC_CLOSED; + for (int i = 0; i < 12; i++) + EnableWindow(GetDlgItem(page, IDC_V_KEY + i), keys); + EnableWindow(GetDlgItem(page, IDC_V_RINGS), app.cfg.voicemail); + bool in = st == DMC_VOICE || st == DMC_VOICEMAIL; + SetDlgItemText(page, IDC_V_RECORD, recording ? "S&top" : "&Record"); + EnableWindow(GetDlgItem(page, IDC_V_RECORD), !play_pcm && !in); + SetDlgItemText(page, IDC_V_PLAYGREET, play_pcm ? "St&op" : "&Play"); + EnableWindow(GetDlgItem(page, IDC_V_PLAYGREET), + (greeting_n > 0 || play_pcm) && !recording && !in); + EnableWindow(GetDlgItem(page, IDC_V_CLEARGREET), + greeting_n > 0 && !recording && !play_pcm); + SetDlgItemText(page, IDC_V_PLAY, play_pcm ? "St&op" : "P&lay"); + EnableWindow(GetDlgItem(page, IDC_V_PLAY), !recording && !in); + char g[96]; + if (recording) + strcpy(g, "Greeting: recording; speak, then Stop"); + else if (greeting_n) + _snprintf(g, sizeof(g), "Greeting: your recording (%d s)", + (greeting_n + DMC_VOICE_RATE / 2) / DMC_VOICE_RATE); + else + strcpy(g, "Greeting: none, callers hear a beep"); + g[sizeof(g) - 1] = '\0'; + SetDlgItemText(page, IDC_V_GREETING, g); +} + +void voice_event(const dmc_event *ev) +{ + if (ev->type == DMC_EV_MESSAGE) { + if (ev->ok) + save_message(ev->text); + } else if (ev->type == DMC_EV_VOICE) { + if (!strcmp(ev->text, "b")) + app_message("Busy"); + else if (!strcmp(ev->text, "l") && + dmc_state(app.s) != DMC_VOICEMAIL) + app_message("The other end hung up"); + } +} + +/* + * the page + */ + +static WNDPROC page_base; + +/* the page's own messages: a message played to its end */ +static LRESULT CALLBACK voice_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) +{ + if (m == WM_APP_PLAYED) { + stop_sound(); + voice_state(); + return 0; + } + return CallWindowProc(page_base, w, m, wp, lp); +} + +HWND voice_page_new(HWND parent) +{ + page = page_new(parent, voice_command); + page_base = (WNDPROC)SetWindowLongPtr(page, GWLP_WNDPROC, + (LONG_PTR)voice_proc); + HWND st = make_child("STATIC", "", SS_LEFT | SS_NOPREFIX, page, + IDC_V_STATUS); + SendMessage(st, WM_SETFONT, (WPARAM)app.bold_font, TRUE); + make_child("BUTTON", "Voice Call", BS_GROUPBOX, page, IDC_V_CALLBOX); + make_child("STATIC", "&Number:", SS_LEFT, page, IDC_V_NUMLABEL); + make_child("EDIT", "", WS_TABSTOP | ES_AUTOHSCROLL, page, IDC_V_NUMBER, + WS_EX_CLIENTEDGE); + make_child("BUTTON", "&Call", WS_TABSTOP | BS_DEFPUSHBUTTON, page, + IDC_V_CALL); + make_child("BUTTON", "&Answer", WS_TABSTOP, page, IDC_V_ANSWER); + make_child("BUTTON", "Take &Message", WS_TABSTOP, page, IDC_V_MESSAGE); + make_child("BUTTON", "Pic&k Up", WS_TABSTOP, page, IDC_V_PICKUP); + make_child("BUTTON", "&Hang Up", WS_TABSTOP, page, IDC_V_HANGUP); + make_child("BUTTON", "M&ute", WS_TABSTOP | BS_AUTOCHECKBOX | + BS_PUSHLIKE, page, IDC_V_MUTE); + make_child("BUTTON", "Li&sten", WS_TABSTOP | BS_AUTOCHECKBOX, page, + IDC_V_LISTEN); + static const char keys[] = "123456789*0#"; + for (int i = 0; i < 12; i++) { + char k[2] = { keys[i], 0 }; + make_child("BUTTON", k, WS_TABSTOP, page, IDC_V_KEY + i); + } + make_child("BUTTON", "Answering Machine", BS_GROUPBOX, page, + IDC_V_VMBOX); + make_child("BUTTON", "&Take messages when nobody answers", + WS_TABSTOP | BS_AUTOCHECKBOX, page, IDC_V_VMON); + make_child("STATIC", "after", SS_RIGHT, page, IDC_V_RINGSLABEL); + HWND rings = make_child("COMBOBOX", "", WS_TABSTOP | CBS_DROPDOWNLIST | + WS_VSCROLL, page, IDC_V_RINGS); + for (int i = 1; i <= 10; i++) { + char r[16]; + _snprintf(r, sizeof(r), i == 1 ? "%d ring" : "%d rings", i); + r[sizeof(r) - 1] = '\0'; + SendMessage(rings, CB_ADDSTRING, 0, (LPARAM)r); + } + int sel = app.cfg.vm_rings >= 1 && app.cfg.vm_rings <= 10 ? + app.cfg.vm_rings - 1 : 3; + SendMessage(rings, CB_SETCURSEL, sel, 0); + CheckDlgButton(page, IDC_V_VMON, + app.cfg.voicemail ? BST_CHECKED : BST_UNCHECKED); + make_child("STATIC", "", SS_LEFT | SS_NOPREFIX, page, IDC_V_GREETING); + make_child("BUTTON", "&Record", WS_TABSTOP, page, IDC_V_RECORD); + make_child("BUTTON", "&Play", WS_TABSTOP, page, IDC_V_PLAYGREET); + make_child("BUTTON", "&File...", WS_TABSTOP, page, IDC_V_CHOOSE); + make_child("BUTTON", "&None", WS_TABSTOP, page, IDC_V_CLEARGREET); + make_child("BUTTON", "Messages", BS_GROUPBOX, page, IDC_V_MSGBOX); + HWND lv = make_child(WC_LISTVIEW, "", WS_TABSTOP | LVS_REPORT | + LVS_SINGLESEL | LVS_SHOWSELALWAYS, page, + IDC_V_MESSAGES, WS_EX_CLIENTEDGE); + ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT); + insert_column(lv, 0, "From", 160); + insert_column(lv, 1, "When", 130); + insert_column(lv, 2, "Length", 60); + make_child("BUTTON", "P&lay", WS_TABSTOP, page, IDC_V_PLAY); + make_child("BUTTON", "&Delete", WS_TABSTOP, page, IDC_V_DELETE); + load_greeting(); + refresh_messages(); + voice_configure(); + return page; +} + +static void place(HWND p, int id, int x, int y, int w, int h) +{ + MoveWindow(GetDlgItem(p, id), x, y, w, h, TRUE); +} + +void voice_page_layout(HWND p, int w, int h) +{ + int m = 12, bw = 90, bh = 24, x = m, y = m; + int inner = w - 2 * m; + if (inner > 640) + inner = 640; + place(p, IDC_V_STATUS, x, y, inner, 20); + y += 28; + /* the call: the number, its buttons, the keypad at the right */ + int kw = 34, kh = 24, pad = 3 * kw + 2 * 4; + int left = inner - pad - 36; + place(p, IDC_V_CALLBOX, x, y, inner, 156); + place(p, IDC_V_NUMLABEL, x + 12, y + 28, 56, 20); + place(p, IDC_V_NUMBER, x + 70, y + 24, left - 70 - bw - 6, bh); + place(p, IDC_V_CALL, x + left - bw, y + 24, bw, bh); + place(p, IDC_V_ANSWER, x + 12, y + 58, bw, bh); + place(p, IDC_V_MESSAGE, x + 18 + bw, y + 58, bw + 10, bh); + place(p, IDC_V_HANGUP, x + left - bw, y + 58, bw, bh); + place(p, IDC_V_PICKUP, x + 12, y + 90, bw, bh); + place(p, IDC_V_LISTEN, x + 18 + bw, y + 92, bw + 10, 20); + place(p, IDC_V_MUTE, x + left - bw, y + 90, bw, bh); + for (int i = 0; i < 12; i++) + place(p, IDC_V_KEY + i, x + inner - pad - 12 + (i % 3) * (kw + 4), + y + 20 + (i / 3) * (kh + 6), kw, kh); + y += 166; + /* the answering machine */ + place(p, IDC_V_VMBOX, x, y, inner, 84); + place(p, IDC_V_VMON, x + 12, y + 24, 230, 20); + place(p, IDC_V_RINGSLABEL, x + 246, y + 26, 34, 20); + place(p, IDC_V_RINGS, x + 284, y + 22, 90, 200); + int gb = 60; + place(p, IDC_V_GREETING, x + 12, y + 56, inner - 4 * (gb + 6) - 24, 20); + place(p, IDC_V_RECORD, x + inner - 4 * (gb + 6) - 6, y + 52, gb, bh); + place(p, IDC_V_PLAYGREET, x + inner - 3 * (gb + 6) - 6, y + 52, gb, bh); + place(p, IDC_V_CHOOSE, x + inner - 2 * (gb + 6) - 6, y + 52, gb, bh); + place(p, IDC_V_CLEARGREET, x + inner - (gb + 6) - 6, y + 52, gb, bh); + y += 94; + /* the messages, the rest */ + int mh = h - y - m; + if (mh < 90) + mh = 90; + place(p, IDC_V_MSGBOX, x, y, inner, mh); + place(p, IDC_V_MESSAGES, x + 12, y + 22, inner - bw - 36, mh - 34); + place(p, IDC_V_PLAY, x + inner - bw - 12, y + 22, bw, bh); + place(p, IDC_V_DELETE, x + inner - bw - 12, y + 52, bw, bh); +}