From 4b672939d6eb1ea3669f28654c52ca5405514b77 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:21:38 +0000 Subject: [PATCH] Add mod_speakingclock for FreeSWITCH The speakingclock dialplan application: the same voices, options and second-accurate timing as Asterisk's SpeakingClock(), including the live synthesiser voices (mode=tts). - core/: the clock itself, ported from app_speakingclock with Asterisk's APIs taken out (libc, libm and pthreads only), and sclock-render, which writes what a caller would hear without a PBX. Its output matches Asterisk's "speakingclock render" sample for sample. - freeswitch/: mod_speakingclock, its Makefile, speakingclock.conf.xml and a dialplan example. API: speakingclock voices | render | reload. - test/render_test.py runs against FreeSWITCH with PBX=freeswitch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRRNr2N8eMYr1uzZqwk --- .gitignore | 2 + README.md | 56 +- core/Makefile | 19 + core/sclock-render.c | 118 +++ core/speakingclock.c | 1589 +++++++++++++++++++++++++++++ core/speakingclock.h | 93 ++ docs/voice-format.md | 10 +- freeswitch/Makefile | 47 + freeswitch/dialplan-example.xml | 34 + freeswitch/mod_speakingclock.c | 337 ++++++ freeswitch/speakingclock.conf.xml | 45 + test/render_test.py | 25 +- 12 files changed, 2362 insertions(+), 13 deletions(-) create mode 100644 core/Makefile create mode 100644 core/sclock-render.c create mode 100644 core/speakingclock.c create mode 100644 core/speakingclock.h create mode 100644 freeswitch/Makefile create mode 100644 freeswitch/dialplan-example.xml create mode 100644 freeswitch/mod_speakingclock.c create mode 100644 freeswitch/speakingclock.conf.xml diff --git a/.gitignore b/.gitignore index 422c15b..e70f7bd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ asterisk/app_speakingclock.so __pycache__/ synth/macintalk/macintalk synth/mssam/mssam +freeswitch/mod_speakingclock.so +core/sclock-render diff --git a/README.md b/README.md index 495a7a3..c3f3843 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # speaking-clock -A telephone speaking clock for Asterisk and FreePBX. Its voices include the +A telephone speaking clock for Asterisk, FreePBX and FreeSWITCH. Its voices include the UK's TIM (Pat Simmons), Australia's Gordon Gow, the whole Steve's Talking Clock library of talking clocks and watches, and classic speech synthesisers (Microsoft Sam and the other SAPI4 voices, DECtalk, SAM, MacInTalk, PlainTalk), each @@ -10,6 +10,10 @@ able to give the time to the second. application, written in C. - **`freepbx/speakingclock/`**: a FreePBX module. Clocks are destinations, with optional numbers to dial. +- **`freeswitch/`**: `mod_speakingclock`, the `speakingclock` dialplan + application for FreeSWITCH, the same clock as `SpeakingClock()`. +- **`core/`**: the clock itself, with no PBX in it (mod_speakingclock is + built on it), and `sclock-render`, which writes what a caller would hear. - **`voices/`**: the voices ([INDEX](voices/INDEX.md), [format](docs/voice-format.md)). - **`tools/`**: fetch the original recordings and rebuild `voices/`. @@ -27,7 +31,8 @@ against the system clock (so keep it on NTP), and the module checks the clock every second, jumping back to it if it drifts by more than 20 ms. Announcements are not queued with `Playback()`, so the clock doesn't drift however long a call is up. Measured on a test call, Pat Simmons' third pip -landed within 10 ms of the second. +landed within 10 ms of the second. mod_speakingclock does the same on +FreeSWITCH. ## Asterisk @@ -98,6 +103,53 @@ builds it and fetches the data). Its setting is `tts_program_mssam`. See [docs/voice-format.md](docs/voice-format.md#live-voices-modetts). +## FreeSWITCH + +```sh +cd freeswitch +make # needs FreeSWITCH's headers (libfreeswitch-dev, or a source install) +sudo make install # module, autoload_configs/speakingclock.conf.xml, voices into sounds/speaking-clock +fs_cli -x 'load mod_speakingclock' +``` + +Add `` to `autoload_configs/modules.conf.xml` +to load it at start. In the dialplan +([dialplan-example.xml](freeswitch/dialplan-example.xml)): + +```xml + + + + + +``` + +`speakingclock [voice] [options]` takes the same voices and options as +`SpeakingClock()` above (`t(zone)`, `d(seconds)`, `h`, `p(seconds)`, +`s(a+b+c)`, `w`, `x`), written after the voice with a space. With `x`, the +key the caller pressed is left in the channel variable `speakingclock_key`. +Time zones are FreeSWITCH's own, from `timezones.conf.xml`. The live voices +work the same way: set `tts_program_*` in +[speakingclock.conf.xml](freeswitch/speakingclock.conf.xml). + +The module sends the clock in 8 kHz signed linear frames the length of the +call's, and FreeSWITCH converts them to the call's codec and rate. Each +frame comes from the clock's position against the system clock, so the +time mark lands on the second whatever the codec. + +API (fs_cli): + +- `speakingclock voices` lists the voices. +- `speakingclock render [zone]` + writes what a caller would hear, as 8 kHz signed linear. +- `speakingclock reload` (or `reloadxml`) rereads the config and the voices. + +`PBX=freeswitch test/render_test.py` runs the timing test against it. + +Without a PBX, `cd core && make` builds `sclock-render`, which does the same +as `speakingclock render`: +`./sclock-render -v ../voices tim-pat-simmons 1762791295 30 out.sln Europe/London`. + ## FreePBX Pack `freepbx/speakingclock` into a tarball and install it with Module Admin diff --git a/core/Makefile b/core/Makefile new file mode 100644 index 0000000..372e84e --- /dev/null +++ b/core/Makefile @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# sclock-render: what a speaking clock caller would hear, without a PBX. +# +# make +# ./sclock-render -v ../voices tim-pat-simmons 1762791295 30 out.sln Europe/London +# ./sclock-render -v ../voices -l + +CFLAGS ?= -g -O2 +CFLAGS += -Wall -pthread + +all: sclock-render + +sclock-render: sclock-render.c speakingclock.c speakingclock.h + $(CC) $(CFLAGS) -o $@ sclock-render.c speakingclock.c -lm + +clean: + rm -f sclock-render + +.PHONY: all clean diff --git a/core/sclock-render.c b/core/sclock-render.c new file mode 100644 index 0000000..6af6d7e --- /dev/null +++ b/core/sclock-render.c @@ -0,0 +1,118 @@ +/* + * sclock-render - write what a speaking clock caller would hear, without a + * PBX: for checking voices and the core (core/speakingclock.c). + * + * Copyright (C) 2026 D-Modem Authors + * SPDX-License-Identifier: GPL-2.0-or-later + * + * sclock-render [-v voicedir] [-o key=value]... [zone] + * sclock-render [-v voicedir] -l + * + * The output is 8 kHz 16-bit signed linear, the same as Asterisk's + * "speakingclock render" and FreeSWITCH's "speakingclock render". -o + * takes any setting speakingclock.conf has (tts_program_dectalk=...). + */ + +#define _GNU_SOURCE +#include "speakingclock.h" + +#include +#include +#include +#include +#include + +static void log_line(enum sc_log_level level, const char *msg) +{ + if (level >= SC_LOG_NOTICE) { + fprintf(stderr, "%s\n", msg); + } +} + +/* single-threaded: TZ is set for each call */ +static int zone_time(long long t, const char *zone, struct sc_tm *tm) +{ + time_t tt = (time_t) t; + struct tm l; + if (zone && *zone) { + setenv("TZ", zone, 1); + } else { + unsetenv("TZ"); + } + tzset(); + localtime_r(&tt, &l); + tm->hour = l.tm_hour; + tm->min = l.tm_min; + tm->sec = l.tm_sec; + return 0; +} + +static void show(void *arg, const char *id, const char *mode, const char *name) +{ + (void) arg; + printf("%-36s %-8s %s\n", id, mode, name); +} + +int main(int argc, char **argv) +{ + static const struct sc_host host = { .log = log_line, .localtime = zone_time }; + const char *voicedir = "voices"; + char *opts[32]; + int nopts = 0, list = 0, c, i, seconds; + sc_clock *clk; + FILE *f; + + while ((c = getopt(argc, argv, "v:o:l")) != -1) { + if (c == 'v') { + voicedir = optarg; + } else if (c == 'o' && nopts < 32 && strchr(optarg, '=')) { + opts[nopts++] = optarg; + } else if (c == 'l') { + list = 1; + } else { + goto usage; + } + } + sc_init(&host); + sc_config_begin(voicedir); + for (i = 0; i < nopts; i++) { + char *eq = strchr(opts[i], '='); + *eq = '\0'; + sc_config_set(opts[i], eq + 1); + } + sc_config_end(); + if (list) { + printf("%-36s %-8s %s\n", "Voice", "Mode", "Name"); + c = sc_voices_list(show, NULL) < 0; + sc_shutdown(); + return c; + } + if (argc - optind < 4) { + goto usage; + } + seconds = atoi(argv[optind + 2]); + if (seconds <= 0 || seconds > 3600 || !(clk = sc_clock_new(argv[optind], NULL))) { + fprintf(stderr, "No voice '%s', or bad seconds\n", argv[optind]); + sc_shutdown(); + return 1; + } + if (!(f = fopen(argv[optind + 3], "wb"))) { + perror(argv[optind + 3]); + return 1; + } + sc_clock_render_from(clk, strtoll(argv[optind + 1], NULL, 10), + argc - optind > 4 ? argv[optind + 4] : NULL); + for (i = 0; i < seconds * 10; i++) { + int16_t out[SC_RATE / 10]; + sc_clock_fill(clk, out, SC_RATE / 10); + fwrite(out, sizeof(out), 1, f); + } + fclose(f); + sc_clock_free(clk); + sc_shutdown(); + return 0; +usage: + fprintf(stderr, "usage: sclock-render [-v voicedir] [-o key=value]... [zone]\n" + " sclock-render [-v voicedir] -l\n"); + return 2; +} diff --git a/core/speakingclock.c b/core/speakingclock.c new file mode 100644 index 0000000..f073eab --- /dev/null +++ b/core/speakingclock.c @@ -0,0 +1,1589 @@ +/* + * speakingclock - the clock itself (see speakingclock.h) + * + * Copyright (C) 2026 D-Modem Authors + * + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See LICENSE. + * + * A port of asterisk/app_speakingclock.c with Asterisk's APIs taken out. + * One announcement every period, placed by sample against the system + * clock, so the time mark (the third pip, the tone) falls exactly on the + * second it announces, however long the call has been up. Callers join + * mid-announcement, as they did on the real thing, unless they ask to wait + * for the next one. + */ + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include "speakingclock.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern char **environ; + +#define RATE SC_RATE +#define MAX_CLIPS 512 +#define MAX_PIECES 32 +#define NREND 4 + +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif +#ifndef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +static const struct sc_host *host; + +static void sc_log(enum sc_log_level level, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static void sc_log(enum sc_log_level level, const char *fmt, ...) +{ + char msg[1024]; + va_list ap; + if (!host || !host->log) { + return; + } + va_start(ap, fmt); + vsnprintf(msg, sizeof(msg), fmt, ap); + va_end(ap); + host->log(level, msg); +} + +static void copy(char *dst, const char *src, size_t len) +{ + if (len) { + snprintf(dst, len, "%s", src ? src : ""); + } +} + +static long long now_us(void) +{ + struct timeval tv; + if (host && host->now_us) { + return host->now_us(); + } + gettimeofday(&tv, NULL); + return (long long) tv.tv_sec * 1000000 + tv.tv_usec; +} + +static void tm_get(long long t, const char *zone, struct sc_tm *tm) +{ + memset(tm, 0, sizeof(*tm)); + if (host && host->localtime && !host->localtime(t, zone, tm)) { + return; + } else { + time_t tt = (time_t) t; + struct tm l; + localtime_r(&tt, &l); + tm->hour = l.tm_hour; + tm->min = l.tm_min; + tm->sec = l.tm_sec; + } +} + +enum mode { MODE_TALKING, MODE_TIM, MODE_CHIME, MODE_HOURLY, MODE_TTS }; + +struct clip { + char name[48]; + int16_t *s; + size_t n; +}; + +struct voice { + struct voice *next; /* in the loaded list */ + int refs; /* under voices_lock */ + char id[96]; + char name[128]; + enum mode mode; + char sequence[256]; + int period; /* seconds */ + double marker; /* seconds into the pips of the time mark, <0: none */ + int int24; /* 24-hour clock */ + char tts_command[512]; /* mode=tts: the program that speaks it */ + char tts_text[512]; /* mode=tts: what to say */ + size_t nclips; + struct clip clips[]; +}; + +/* configuration, under conf_lock */ +static pthread_mutex_t conf_lock = PTHREAD_MUTEX_INITIALIZER; +static char voicedir[PATH_MAX]; +static char default_voice[96] = "tim-pat-simmons"; +static char default_zone[64]; +static int maxduration = 180; +static int tts_timeout = 15; +#define TTS_PROGRAMS 32 +/* tts_program_ */ +static struct { char name[48]; char path[256]; } tts_programs[TTS_PROGRAMS]; +static int ntts_programs; + +/* loaded voices */ +static pthread_mutex_t voices_lock = PTHREAD_MUTEX_INITIALIZER; +static struct voice *voices; + +/* ---- configuration ---------------------------------------------------- */ + +void sc_config_begin(const char *default_voicedir) +{ + pthread_mutex_lock(&conf_lock); + copy(voicedir, default_voicedir, sizeof(voicedir)); + copy(default_voice, "tim-pat-simmons", sizeof(default_voice)); + default_zone[0] = '\0'; + maxduration = 180; + tts_timeout = 15; + ntts_programs = 0; + pthread_mutex_unlock(&conf_lock); +} + +void sc_config_set(const char *key, const char *value) +{ + if (!key || !value) { + return; + } + pthread_mutex_lock(&conf_lock); + if (!strcasecmp(key, "voicedir")) { + copy(voicedir, value, sizeof(voicedir)); + } else if (!strcasecmp(key, "default_voice")) { + copy(default_voice, value, sizeof(default_voice)); + } else if (!strcasecmp(key, "timezone")) { + copy(default_zone, value, sizeof(default_zone)); + } else if (!strcasecmp(key, "maxduration")) { + maxduration = atoi(value); + } else if (!strcasecmp(key, "tts_timeout")) { + if (atoi(value) > 0) { + tts_timeout = atoi(value); + } + } else if (!strncasecmp(key, "tts_program_", 12) && ntts_programs < TTS_PROGRAMS) { + copy(tts_programs[ntts_programs].name, key + 4, sizeof(tts_programs[0].name)); + copy(tts_programs[ntts_programs].path, value, sizeof(tts_programs[0].path)); + ntts_programs++; + } + pthread_mutex_unlock(&conf_lock); +} + +static void voice_unref(struct voice *v); + +void sc_config_end(void) +{ + struct voice *v, *next; + /* voices load again on next use */ + pthread_mutex_lock(&voices_lock); + v = voices; + voices = NULL; + pthread_mutex_unlock(&voices_lock); + for (; v; v = next) { + next = v->next; + voice_unref(v); + } +} + +int sc_maxduration(void) +{ + int d; + pthread_mutex_lock(&conf_lock); + d = maxduration; + pthread_mutex_unlock(&conf_lock); + return d; +} + +void sc_voicedir(char *out, size_t len) +{ + pthread_mutex_lock(&conf_lock); + copy(out, voicedir, len); + pthread_mutex_unlock(&conf_lock); +} + +/* ---- voices ----------------------------------------------------------- */ + +static void voice_free(struct voice *v) +{ + size_t i; + for (i = 0; i < v->nclips; i++) { + free(v->clips[i].s); + } + free(v); +} + +static void voice_unref(struct voice *v) +{ + int last; + if (!v) { + return; + } + pthread_mutex_lock(&voices_lock); + last = --v->refs == 0; + pthread_mutex_unlock(&voices_lock); + if (last) { + voice_free(v); + } +} + +static const struct clip *clip_find(const struct voice *v, const char *name) +{ + size_t i; + for (i = 0; i < v->nclips; i++) { + if (!strcasecmp(v->clips[i].name, name)) { + return &v->clips[i]; + } + } + return NULL; +} + +static uint32_t le32(const unsigned char *p) +{ + return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t) p[3] << 24; +} + +/* An 8 kHz 16-bit mono PCM WAV file (what tools/build_voices.py makes). */ +static int wav_load(const char *path, struct clip *c) +{ + FILE *f = fopen(path, "rb"); + unsigned char h[12], ch[8], fmt[16]; + int have_fmt = 0; + + if (!f) { + return -1; + } + if (fread(h, 1, 12, f) != 12 || memcmp(h, "RIFF", 4) || memcmp(h + 8, "WAVE", 4)) { + goto bad; + } + while (fread(ch, 1, 8, f) == 8) { + uint32_t len = le32(ch + 4); + if (!memcmp(ch, "fmt ", 4) && len >= 16) { + if (fread(fmt, 1, 16, f) != 16) { + goto bad; + } + if (fseek(f, len - 16 + (len & 1), SEEK_CUR)) { + goto bad; + } + /* PCM, mono, 8000 Hz, 16 bits */ + if (fmt[0] != 1 || fmt[1] || fmt[2] != 1 || fmt[3] || + le32(fmt + 4) != RATE || fmt[14] != 16) { + sc_log(SC_LOG_WARNING, "%s: not 8 kHz 16-bit mono PCM, skipped", path); + goto bad; + } + have_fmt = 1; + } else if (!memcmp(ch, "data", 4) && have_fmt) { + size_t i; + unsigned char *raw = malloc(len ? len : 1); + if (!raw) { + goto bad; + } + len = fread(raw, 1, len, f); + c->n = len / 2; + c->s = malloc((c->n ? c->n : 1) * sizeof(int16_t)); + if (!c->s) { + free(raw); + goto bad; + } + for (i = 0; i < c->n; i++) { + c->s[i] = (int16_t) (raw[2 * i] | raw[2 * i + 1] << 8); + } + free(raw); + fclose(f); + return 0; + } else if (fseek(f, len + (len & 1), SEEK_CUR)) { + goto bad; + } + } +bad: + fclose(f); + return -1; +} + +static enum mode mode_parse(const char *s) +{ + if (!strcasecmp(s, "tim")) { + return MODE_TIM; + } else if (!strcasecmp(s, "chime")) { + return MODE_CHIME; + } else if (!strcasecmp(s, "hourly")) { + return MODE_HOURLY; + } else if (!strcasecmp(s, "tts")) { + return MODE_TTS; + } + return MODE_TALKING; +} + +static const char *mode_name(enum mode m) +{ + static const char *names[] = { "talking", "tim", "chime", "hourly", "tts" }; + return names[m]; +} + +/* A voice folder's id is its name: letters, digits, '-', '_' and '.' only, + * so it can't climb out of voicedir. */ +static int id_ok(const char *id) +{ + if (!id || !*id || id[0] == '.') { + return 0; + } + for (; *id; id++) { + if (!isalnum((unsigned char) *id) && !strchr("-_.", *id)) { + return 0; + } + } + return 1; +} + +static char *strip(char *s) +{ + char *e; + while (isspace((unsigned char) *s)) { + s++; + } + e = s + strlen(s); + while (e > s && isspace((unsigned char) e[-1])) { + *--e = '\0'; + } + return s; +} + +/* voice.conf is in Asterisk's config format: [section], key=value (or + * key => value), and ';' to the end of the line a comment ('\;' is a + * semicolon). cb(v, section, key, value) for each setting. */ +static void conf_read(const char *path, struct voice *v, + void (*cb)(struct voice *v, const char *section, const char *key, const char *value)) +{ + char line[1024], section[64] = ""; + FILE *f = fopen(path, "r"); + + if (!f) { + return; + } + while (fgets(line, sizeof(line), f)) { + char *r, *w, *s, *eq; + /* comments out, \; to ; */ + for (r = w = line; *r && *r != '\n'; r++) { + if (*r == '\\' && r[1] == ';') { + *w++ = ';'; + r++; + } else if (*r == ';') { + break; + } else { + *w++ = *r; + } + } + *w = '\0'; + s = strip(line); + if (*s == '[') { + char *close = strchr(s, ']'); + if (close) { + *close = '\0'; + copy(section, strip(s + 1), sizeof(section)); + } + continue; + } + if (!(eq = strchr(s, '='))) { + continue; + } + *eq = '\0'; + if (eq[1] == '>') { + eq++; + } + cb(v, section, strip(s), strip(eq + 1)); + } + fclose(f); +} + +static void voice_setting(struct voice *v, const char *section, const char *key, const char *value) +{ + if (!strcasecmp(section, "voice")) { + if (!strcasecmp(key, "name")) { + copy(v->name, value, sizeof(v->name)); + } else if (!strcasecmp(key, "mode")) { + v->mode = mode_parse(value); + } else if (!strcasecmp(key, "sequence")) { + copy(v->sequence, value, sizeof(v->sequence)); + } else if (!strcasecmp(key, "period")) { + v->period = atoi(value); + } else if (!strcasecmp(key, "marker")) { + v->marker = atof(value); + } else if (!strcasecmp(key, "hours")) { + v->int24 = atoi(value) == 24; + } + } else if (!strcasecmp(section, "tts")) { + if (!strcasecmp(key, "command")) { + copy(v->tts_command, value, sizeof(v->tts_command)); + } else if (!strcasecmp(key, "text")) { + copy(v->tts_text, value, sizeof(v->tts_text)); + } + } +} + +static struct voice *voice_load(const char *dir, const char *id) +{ + char path[PATH_MAX + 512]; + struct voice *v; + struct dirent *de; + DIR *d; + + snprintf(path, sizeof(path), "%s/%s", dir, id); + if (!(d = opendir(path))) { + sc_log(SC_LOG_WARNING, "SpeakingClock: no voice '%s' in %s", id, dir); + return NULL; + } + v = calloc(1, sizeof(*v) + MAX_CLIPS * sizeof(struct clip)); + if (!v) { + closedir(d); + return NULL; + } + copy(v->id, id, sizeof(v->id)); + copy(v->name, id, sizeof(v->name)); + v->marker = -1; + v->period = 0; + + snprintf(path, sizeof(path), "%s/%s/voice.conf", dir, id); + conf_read(path, v, voice_setting); + + while ((de = readdir(d)) && v->nclips < MAX_CLIPS) { + size_t len = strlen(de->d_name); + struct clip *c = &v->clips[v->nclips]; + if (len < 5 || len - 4 >= sizeof(c->name) || strcasecmp(de->d_name + len - 4, ".wav")) { + continue; + } + snprintf(path, sizeof(path), "%s/%s/%s", dir, id, de->d_name); + copy(c->name, de->d_name, len - 3); + if (!wav_load(path, c)) { + v->nclips++; + } + } + closedir(d); + + if (!*v->sequence) { + static const char *seq[] = { + [MODE_TALKING] = "intro+its+hour+minute+ampm", + [MODE_TIM] = "phrase+hour+minute+seconds+pips", + [MODE_CHIME] = "quarter+strikes", + [MODE_HOURLY] = "hourly", + [MODE_TTS] = "speech+pips", + }; + copy(v->sequence, seq[v->mode], sizeof(v->sequence)); + } + if (v->period <= 0) { + v->period = v->mode == MODE_CHIME ? 30 : 10; + } + if (v->mode == MODE_TTS) { + if (!*v->tts_text) { + copy(v->tts_text, "At the third stroke, it will be {hour} {minute} {seconds}.", + sizeof(v->tts_text)); + } + if (!*v->tts_command) { + sc_log(SC_LOG_WARNING, "SpeakingClock: tts voice '%s' has no [tts] command=", id); + voice_free(v); + return NULL; + } + } else if (!v->nclips) { + sc_log(SC_LOG_WARNING, "SpeakingClock: voice '%s' has no usable clips", id); + voice_free(v); + return NULL; + } + return v; +} + +/* The voice, loaded on first use and kept until the config is reloaded. */ +static struct voice *voice_get(const char *id) +{ + struct voice *v; + char dir[PATH_MAX]; + + if (!id_ok(id)) { + sc_log(SC_LOG_WARNING, "SpeakingClock: bad voice name '%s'", id ? id : ""); + return NULL; + } + pthread_mutex_lock(&voices_lock); + for (v = voices; v && strcmp(v->id, id); v = v->next) { + } + if (!v) { + sc_voicedir(dir, sizeof(dir)); + if ((v = voice_load(dir, id))) { + v->refs = 1; /* the list's */ + v->next = voices; + voices = v; + } + } + if (v) { + v->refs++; + } + pthread_mutex_unlock(&voices_lock); + return v; +} + +/* ---- live speech (mode=tts) -------------------------------------------- * + * A tts voice has no number clips. Each announcement's sentence is spoken + * whole by a synthesiser program on this machine (DECtalk, SAM), converted + * to 8 kHz, and cached. A worker thread runs the program, so a call never + * waits on it: the clock asks for an announcement two periods before it is + * due, and one whose speech isn't ready in time plays without it (pips + * only). */ + +#define SPEECH_SLOTS 128 +#define SPEECH_RETRY 30 /* seconds before a failed fetch is tried again */ +#define SPEECH_MAX (8 << 20) /* largest WAV accepted */ + +enum speech_state { SP_EMPTY, SP_WANTED, SP_FETCHING, SP_READY, SP_FAILED }; + +struct speech { + char *key; + enum speech_state state; + int16_t *s; + size_t n; + time_t used, failed; + unsigned long seq; /* order asked for */ +}; + +static pthread_mutex_t speech_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t speech_cond; /* work for the fetcher, or a fetch done */ +static struct speech speech[SPEECH_SLOTS]; +static unsigned long speech_seq; +static pthread_t speech_thread; +static int speech_running; +static int speech_quit; + +/* The tts__ setting, else def. */ +static void tts_setting(const char *kind, const char *name, const char *def, char *out, size_t len) +{ + char key[48]; + int i; + snprintf(key, sizeof(key), "%s_%.30s", kind, name); + copy(out, def, len); + pthread_mutex_lock(&conf_lock); + for (i = 0; i < ntts_programs; i++) { + if (!strcasecmp(tts_programs[i].name, key)) { + copy(out, tts_programs[i].path, len); + } + } + pthread_mutex_unlock(&conf_lock); +} + +/* Windowed-sinc resampling to 8 kHz, with the cut-off below both Nyquists. */ +static int16_t *resample(const float *x, size_t n, unsigned rate, size_t *out_n) +{ + double ratio = (double) rate / RATE, fc = 0.45 * MIN(1.0, 1.0 / ratio); + int w = (int) ceil(12 / fc); + size_t k, m = (size_t) (n / ratio); + int16_t *y = malloc((m ? m : 1) * sizeof(int16_t)); + + if (!y) { + return NULL; + } + for (k = 0; k < m; k++) { + double t = k * ratio, acc = 0; + long i, c = (long) floor(t); + for (i = c - w + 1; i <= c + w; i++) { + double d = t - i, h; + if (i < 0 || i >= (long) n) { + continue; + } + h = d == 0 ? 2 * fc : sin(2 * M_PI * fc * d) / (M_PI * d); + acc += x[i] * h * (0.5 + 0.5 * cos(M_PI * d / w)); + } + acc = acc > 32767 ? 32767 : acc < -32768 ? -32768 : acc; + y[k] = (int16_t) lrint(acc); + } + *out_n = m; + return y; +} + +/* A PCM WAV of any rate, 8 or 16 bits, mono or stereo: to 8 kHz mono, + * with the silence around it trimmed (40 ms left each side) and its peak + * brought to -3 dBFS, the way tools/synth_voices.py makes clips. */ +static int16_t *speech_decode(const unsigned char *d, size_t len, size_t *out_n) +{ + const unsigned char *fmt = NULL, *data = NULL; + size_t dlen = 0, pos = 12, i, frames, a, b, n; + unsigned ch, rate, bits; + float *x; + int16_t *y; + int peak = 0; + + if (len < 12 || memcmp(d, "RIFF", 4) || memcmp(d + 8, "WAVE", 4)) { + return NULL; + } + while (pos + 8 <= len) { + size_t clen = le32(d + pos + 4); + if (!memcmp(d + pos, "fmt ", 4) && clen >= 16 && pos + 8 + 16 <= len) { + fmt = d + pos + 8; + } else if (!memcmp(d + pos, "data", 4)) { + data = d + pos + 8; + dlen = MIN(clen, len - pos - 8); /* streamed WAVs give no length */ + break; + } + pos += 8 + clen + (clen & 1); + } + if (!fmt || !data) { + return NULL; + } + ch = fmt[2] | fmt[3] << 8; + rate = le32(fmt + 4); + bits = fmt[14] | fmt[15] << 8; + if (!((fmt[0] == 1 && !fmt[1]) || (fmt[0] == 0xfe && fmt[1] == 0xff)) || + ch < 1 || ch > 2 || (bits != 8 && bits != 16) || rate < 4000 || rate > 96000) { + return NULL; + } + frames = dlen / (ch * bits / 8); + if (!(x = malloc((frames ? frames : 1) * sizeof(float)))) { + return NULL; + } + for (i = 0; i < frames; i++) { + float v = 0; + unsigned c; + for (c = 0; c < ch; c++) { + const unsigned char *p = data + (i * ch + c) * (bits / 8); + v += bits == 8 ? (p[0] - 128) * 256 : (int16_t) (p[0] | p[1] << 8); + } + x[i] = v / ch; + } + if (rate == RATE) { + n = frames; + y = malloc((n ? n : 1) * sizeof(int16_t)); + for (i = 0; y && i < n; i++) { + y[i] = (int16_t) x[i]; + } + } else { + y = resample(x, frames, rate, &n); + } + free(x); + if (!y) { + return NULL; + } + for (i = 0; i < n; i++) { + peak = MAX(peak, abs(y[i])); + } + if (peak < 100) { + free(y); + return NULL; /* silence */ + } + for (a = 0; a < n && abs(y[a]) < peak / 30; a++) { + } + for (b = n; b > a && abs(y[b - 1]) < peak / 30; b--) { + } + a = a > RATE / 25 ? a - RATE / 25 : 0; + b = MIN(n, b + RATE / 25); + for (i = a; i < b; i++) { + y[i - a] = (int16_t) (y[i] * 23197.0 / peak); + } + *out_n = b - a; + return y; +} + +/* Run a speech program: key is "exec:" and its arguments, split by \x1f. + * It writes the WAV to the file named by the argument "{out}", or else to + * its standard output. No shell: the text is one argument. */ +static int16_t *speech_exec(const char *key, size_t *n) +{ + char tmpl[] = "/tmp/speakingclock-XXXXXX.wav", *args, *argv[64], *a, *dup; + int fd, argc = 0, status = -1, to_file = 0, timeout; + posix_spawn_file_actions_t fa; + unsigned char *d = NULL; + int16_t *s = NULL; + struct stat sb; + time_t until; + pid_t pid; + + if ((fd = mkstemps(tmpl, 4)) < 0) { + return NULL; + } + if (!(dup = args = strdup(key + 5))) { + close(fd); + unlink(tmpl); + return NULL; + } + while ((a = strsep(&args, "\x1f")) && argc < 63) { + if (!strcmp(a, "{out}")) { + argv[argc++] = tmpl; + to_file = 1; + } else { + argv[argc++] = a; + } + } + argv[argc] = NULL; + pthread_mutex_lock(&conf_lock); + timeout = tts_timeout; + pthread_mutex_unlock(&conf_lock); + posix_spawn_file_actions_init(&fa); + posix_spawn_file_actions_addopen(&fa, 0, "/dev/null", O_RDONLY, 0); + if (to_file) { + posix_spawn_file_actions_addopen(&fa, 1, "/dev/null", O_WRONLY, 0); + } else { + posix_spawn_file_actions_adddup2(&fa, fd, 1); + } + posix_spawn_file_actions_addopen(&fa, 2, "/dev/null", O_WRONLY, 0); + if (argc && !posix_spawnp(&pid, argv[0], &fa, NULL, argv, environ)) { + pid_t w; + until = time(NULL) + timeout; + while ((w = waitpid(pid, &status, WNOHANG)) == 0) { + if (time(NULL) > until) { + kill(pid, SIGKILL); + waitpid(pid, &status, 0); + sc_log(SC_LOG_WARNING, "SpeakingClock: %s took too long", argv[0]); + status = -1; + break; + } + usleep(20000); + } + if (w < 0) { + sc_log(SC_LOG_WARNING, "SpeakingClock: can't wait for %s: %s (is SIGCHLD ignored?)", + argv[0], strerror(errno)); + status = -1; + } + } else { + sc_log(SC_LOG_WARNING, "SpeakingClock: can't run %s", argc ? argv[0] : "(nothing)"); + } + posix_spawn_file_actions_destroy(&fa); + if (status == 0 && !stat(tmpl, &sb) && sb.st_size > 0 && sb.st_size < SPEECH_MAX && + (d = malloc(sb.st_size))) { + FILE *f = fopen(tmpl, "rb"); + if (f && fread(d, 1, sb.st_size, f) == (size_t) sb.st_size && + !(s = speech_decode(d, sb.st_size, n))) { + sc_log(SC_LOG_WARNING, "SpeakingClock: %s: not a WAV file it can read", argv[0]); + } + if (f) { + fclose(f); + } + } else if (status > 0) { + sc_log(SC_LOG_WARNING, "SpeakingClock: %s failed (%d)", argv[0], status); + } + free(d); + free(dup); + close(fd); + unlink(tmpl); + return s; +} + +static void *speech_worker(void *unused) +{ + (void) unused; + pthread_mutex_lock(&speech_lock); + while (!speech_quit) { + struct speech *e = NULL; + char *key; + int16_t *s; + size_t i, n = 0; + + for (i = 0; i < SPEECH_SLOTS; i++) { + if (speech[i].state == SP_WANTED && (!e || speech[i].seq < e->seq)) { + e = &speech[i]; + } + } + if (!e) { + pthread_cond_wait(&speech_cond, &speech_lock); + continue; + } + e->state = SP_FETCHING; + key = strdup(e->key); + pthread_mutex_unlock(&speech_lock); + s = key ? speech_exec(key, &n) : NULL; + pthread_mutex_lock(&speech_lock); + /* the slot is never reused while it is fetching */ + e->s = s; + e->n = n; + e->state = s ? SP_READY : SP_FAILED; + e->failed = time(NULL); + free(key); + pthread_cond_broadcast(&speech_cond); + } + pthread_mutex_unlock(&speech_lock); + return NULL; +} + +enum { SPEECH_PEEK, SPEECH_ASK, SPEECH_WAIT }; + +/* The speech for key, copied into *s (the caller frees it): 0 when it's + * here, -1 when it isn't (yet). SPEECH_ASK asks for it if it hasn't been + * asked for, SPEECH_WAIT also waits up to the fetch timeout for it, and + * SPEECH_PEEK only looks. */ +static int speech_get(const char *key, int16_t **s, size_t *n, int how) +{ + struct speech *e = NULL, *victim = NULL; + time_t now = time(NULL); + struct timespec until; + size_t i; + int res = -1, timeout; + + pthread_mutex_lock(&conf_lock); + timeout = tts_timeout; + pthread_mutex_unlock(&conf_lock); + clock_gettime(CLOCK_REALTIME, &until); + until.tv_sec += timeout + 5; + + pthread_mutex_lock(&speech_lock); + for (i = 0; i < SPEECH_SLOTS && !e; i++) { + if (speech[i].state != SP_EMPTY && !strcmp(speech[i].key, key)) { + e = &speech[i]; + } + } + if (!e && how != SPEECH_PEEK) { + /* an empty slot, else the one least recently used */ + for (i = 0; i < SPEECH_SLOTS; i++) { + struct speech *c = &speech[i]; + if (c->state == SP_FETCHING) { + continue; + } + if (c->state == SP_EMPTY) { + victim = c; + break; + } + if (!victim || c->used < victim->used) { + victim = c; + } + } + if (victim) { + free(victim->key); + free(victim->s); + memset(victim, 0, sizeof(*victim)); + if ((victim->key = strdup(key))) { + e = victim; + e->state = SP_WANTED; + e->seq = ++speech_seq; + pthread_cond_broadcast(&speech_cond); + } + } + } else if (e && how != SPEECH_PEEK && e->state == SP_FAILED && now - e->failed >= SPEECH_RETRY) { + e->state = SP_WANTED; + e->seq = ++speech_seq; + pthread_cond_broadcast(&speech_cond); + } + while (e && how == SPEECH_WAIT && speech_running && + (e->state == SP_WANTED || e->state == SP_FETCHING)) { + if (pthread_cond_timedwait(&speech_cond, &speech_lock, &until) == ETIMEDOUT) { + break; + } + } + if (e && e->key && strcmp(e->key, key)) { + e = NULL; /* reused for another while we waited */ + } + if (e) { + e->used = now; + if (e->state == SP_READY && (*s = malloc((e->n ? e->n : 1) * sizeof(int16_t)))) { + memcpy(*s, e->s, e->n * sizeof(int16_t)); + *n = e->n; + res = 0; + } + } + pthread_mutex_unlock(&speech_lock); + return res; +} + +int sc_init(const struct sc_host *h) +{ + host = h; + pthread_cond_init(&speech_cond, NULL); + speech_quit = 0; + if (pthread_create(&speech_thread, NULL, speech_worker, NULL)) { + sc_log(SC_LOG_ERROR, "SpeakingClock: can't start the speech fetcher"); + speech_running = 0; + return -1; + } + speech_running = 1; + return 0; +} + +void sc_shutdown(void) +{ + size_t i; + if (speech_running) { + pthread_mutex_lock(&speech_lock); + speech_quit = 1; + pthread_cond_broadcast(&speech_cond); + pthread_mutex_unlock(&speech_lock); + pthread_join(speech_thread, NULL); + speech_running = 0; + } + for (i = 0; i < SPEECH_SLOTS; i++) { + free(speech[i].key); + free(speech[i].s); + memset(&speech[i], 0, sizeof(speech[i])); + } + pthread_cond_destroy(&speech_cond); + sc_config_end(); +} + +/* ---- what a tts voice says ---- */ + +/* a growing string */ +struct str { + char *s; + size_t len, cap; +}; + +static void str_add(struct str *b, const char *s, size_t n) +{ + if (b->len + n + 1 > b->cap) { + size_t cap = MAX(b->cap * 2, b->len + n + 64); + char *p = realloc(b->s, cap); + if (!p) { + return; + } + b->s = p; + b->cap = cap; + } + memcpy(b->s + b->len, s, n); + b->len += n; + b->s[b->len] = '\0'; +} + +static void str_puts(struct str *b, const char *s) +{ + str_add(b, s, strlen(s)); +} + +static const char *ones[] = { "zero", "one", "two", "three", "four", "five", "six", + "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", + "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; +static const char *tens_w[] = { "", "", "twenty", "thirty", "forty", "fifty" }; + +static void words(int n, char *out, size_t len) +{ + if (n < 20) { + copy(out, ones[n], len); + } else if (n % 10) { + snprintf(out, len, "%s-%s", tens_w[n / 10], ones[n % 10]); + } else { + copy(out, tens_w[n / 10], len); + } +} + +/* The template with {hour} {minute} {seconds} {ampm} {greeting} in words, + * and {H} {HH} {M} {MM} {S} {SS} in digits, filled in. */ +static void tts_text(const char *tpl, const struct sc_tm *tm, int int24, char *out, size_t len) +{ + struct str s = { 0 }; + const char *p; + + for (p = tpl; *p; p++) { + char key[16], w[48]; + const char *close = *p == '{' ? strchr(p, '}') : NULL; + if (!close || close - p - 1 >= (ptrdiff_t) sizeof(key)) { + str_add(&s, p, 1); + continue; + } + copy(key, p + 1, close - p); + p = close; + w[0] = '\0'; + if (!strcmp(key, "hour")) { + words(int24 ? tm->hour : tm->hour % 12 ? tm->hour % 12 : 12, w, sizeof(w)); + } else if (!strcmp(key, "minute")) { + if (!tm->min) { + copy(w, int24 ? "hundred" : "o'clock", sizeof(w)); + } else if (tm->min < 10) { + snprintf(w, sizeof(w), "oh %s", ones[tm->min]); + } else { + words(tm->min, w, sizeof(w)); + } + } else if (!strcmp(key, "seconds")) { + if (!tm->sec) { + copy(w, "precisely", sizeof(w)); + } else { + char n[24]; + words(tm->sec, n, sizeof(n)); + snprintf(w, sizeof(w), "and %s second%s", n, tm->sec == 1 ? "" : "s"); + } + } else if (!strcmp(key, "ampm")) { + copy(w, int24 ? "" : tm->hour < 12 ? "A.M." : "P.M.", sizeof(w)); + } else if (!strcmp(key, "greeting")) { + copy(w, tm->hour < 12 ? "Good morning" : + tm->hour < 18 ? "Good afternoon" : "Good evening", sizeof(w)); + } else if (!strcmp(key, "H") || !strcmp(key, "HH")) { + int h = int24 ? tm->hour : tm->hour % 12 ? tm->hour % 12 : 12; + snprintf(w, sizeof(w), key[1] ? "%02d" : "%d", h); + } else if (!strcmp(key, "M") || !strcmp(key, "MM")) { + snprintf(w, sizeof(w), key[1] ? "%02d" : "%d", tm->min); + } else if (!strcmp(key, "S") || !strcmp(key, "SS")) { + snprintf(w, sizeof(w), key[1] ? "%02d" : "%d", tm->sec); + } else { + snprintf(w, sizeof(w), "{%s}", key); + } + str_puts(&s, w); + } + copy(out, s.s, len); + free(s.s); +} + +/* The key that runs v's command= for text: its words, split like a shell + * would (with "..." and '...'), {program:name} becoming tts_program_ + * (else name), {text} the text and {out} the file to write. */ +static void tts_cmd(const struct voice *v, const char *text, char *out, size_t len) +{ + struct str s = { 0 }; + const char *p = v->tts_command; + int args = 0; + + str_puts(&s, "exec:"); + while (*p) { + char q = 0; + while (*p == ' ' || *p == '\t') { + p++; + } + if (!*p) { + break; + } + if (args++) { + str_puts(&s, "\x1f"); + } + for (; *p && (q || (*p != ' ' && *p != '\t')); p++) { + if (!q && (*p == '"' || *p == '\'')) { + q = *p; + } else if (q && *p == q) { + q = 0; + } else if (!strncmp(p, "{text}", 6)) { + str_puts(&s, text); + p += 5; + } else if (!strncmp(p, "{program:", 9) && strchr(p, '}')) { + const char *close = strchr(p, '}'); + char name[48], prog[256]; + copy(name, p + 9, MIN(sizeof(name), (size_t) (close - p - 8))); + tts_setting("program", name, name, prog, sizeof(prog)); + str_puts(&s, prog); + p = close; + } else { + str_add(&s, p, 1); + } + } + } + copy(out, s.s, len); + free(s.s); +} + +/* ---- composing an announcement ---------------------------------------- */ + +struct piece { + const int16_t *s; + size_t n; + int is_pips; +}; + +struct ann { + long long j; /* announcement index: its time is j * period */ + long long start; /* first sample, counted from the epoch */ + int16_t *s; + size_t n; + int used; + int pending; /* its speech hadn't arrived: render it again */ + long long tried; /* when it was last rendered (st->pos) */ +}; + +struct sc_clock { + struct voice *v; + char zone[64]; + char sequence[256]; + int period; + int int24; + int wait; /* 'w' */ + long long pos; /* next sample to send, counted from the epoch */ + long long min_start; /* 'w': skip announcements starting before this */ + long long last_sync; + int wait_speech; /* rendering: fetch speech before going on */ + struct ann r[NREND]; + int16_t pips[RATE * 3]; /* made-up pips, for voices without a pips clip */ +}; + +struct say { + const struct voice *v; + struct piece p[MAX_PIECES]; + int np; + int16_t *own[MAX_PIECES]; /* speech, freed after rendering */ + int nown; + int pending; /* speech that hasn't arrived yet */ + int how; /* SPEECH_PEEK, _ASK or _WAIT */ +}; + +static int add(struct say *s, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static int add(struct say *s, const char *fmt, ...) +{ + char name[48]; + const struct clip *c; + va_list ap; + + va_start(ap, fmt); + vsnprintf(name, sizeof(name), fmt, ap); + va_end(ap); + if (s->np >= MAX_PIECES || !(c = clip_find(s->v, name))) { + return -1; + } + s->p[s->np].s = c->s; + s->p[s->np].n = c->n; + s->p[s->np].is_pips = !strcasecmp(name, "pips"); + s->np++; + return 0; +} + +static int has(const struct voice *v, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static int has(const struct voice *v, const char *fmt, ...) +{ + char name[48]; + va_list ap; + va_start(ap, fmt); + vsnprintf(name, sizeof(name), fmt, ap); + va_end(ap); + return clip_find(v, name) != NULL; +} + +/* 0..59: a whole-number clip, or built from parts the way Steve's + * Talking Clock voices are ("thir" + "teen", "for" + "ty5", "20" + "5") */ +static void say_number(struct say *s, int n) +{ + static const char *pre[] = { [13] = "thir", [14] = "for", [15] = "fif", + [16] = "six", [17] = "seven", [18] = "eight", [19] = "nine" }; + static const char *tens[] = { [2] = "twen", [3] = "thir", [4] = "for", [5] = "fif" }; + + if (!add(s, "n%d", n)) { + return; + } + if (n >= 13 && n <= 19) { + if (add(s, "f_%s", pre[n])) { + add(s, "n%d", n - 10); + } + add(s, "f_teen"); + } else if (n >= 20 && n < 60) { + int t = n / 10, u = n % 10; + if (has(s->v, "f_ty")) { + add(s, "f_%s", tens[t]); + if (u) { + add(s, "f_ty%d", u); + } else { + add(s, "f_ty"); + } + } else { + add(s, "n%d", t * 10); + if (u) { + add(s, "n%d", u); + } + } + } +} + +static void say_minute(struct say *s, int m) +{ + if (m == 0) { + add(s, "oclock"); + } else if (!add(s, "m%d", m)) { + return; + } else if (m < 10) { + add(s, "oh"); + say_number(s, m); + } else { + say_number(s, m); + } +} + +static void say_hour(struct say *s, int h, int int24) +{ + if (!int24) { + h = h % 12 ? h % 12 : 12; + if (!add(s, "h%d", h)) { + return; + } + } + say_number(s, h); +} + +static void compose(struct say *s, const char *sequence, const struct sc_tm *tm, int int24) +{ + char seq[256], *tok, *rest; + int minute_done = 0; + + copy(seq, sequence, sizeof(seq)); + rest = seq; + while ((tok = strsep(&rest, "+"))) { + tok = strip(tok); + if (!strcasecmp(tok, "greeting")) { + add(s, "greet_%s", tm->hour < 12 ? "morning" : + tm->hour < 18 ? "afternoon" : "evening"); + } else if (!strcasecmp(tok, "hour")) { + int h12 = tm->hour % 12 ? tm->hour % 12 : 12; + if (!tm->min && !int24 && tm->hour == 12 && !add(s, "noon")) { + minute_done = 2; + } else if (!tm->min && !int24 && tm->hour == 0 && !add(s, "midnight")) { + minute_done = 2; + } else if (!tm->min && !int24 && !add(s, "hoc%d", h12)) { + minute_done = 1; + } else { + say_hour(s, tm->hour, int24); + } + } else if (!strcasecmp(tok, "minute")) { + if (!minute_done) { + say_minute(s, tm->min); + } + } else if (!strcasecmp(tok, "seconds")) { + if (tm->sec == 0) { + add(s, "precisely"); + } else { + add(s, "s%d", tm->sec); + } + } else if (!strcasecmp(tok, "ampm")) { + if (!int24 && minute_done != 2) { + add(s, tm->hour < 12 ? "am" : "pm"); + } + } else if (!strcasecmp(tok, "quarter")) { + add(s, "q%02d", tm->min / 15 * 15); + } else if (!strcasecmp(tok, "strikes")) { + int i, h12 = tm->hour % 12 ? tm->hour % 12 : 12; + if (tm->min < 15) { + for (i = 0; i < h12; i++) { + add(s, "chime"); + } + } + } else if (!strcasecmp(tok, "hourly")) { + add(s, "hr%d", tm->hour % 12 ? tm->hour % 12 : 12); + } else if (!strcasecmp(tok, "hourchime")) { + if (tm->min == 0) { + add(s, "hourchime1"); + } + } else if (!strcasecmp(tok, "speech")) { + char text[512], key[2048]; + int16_t *sp; + size_t n; + if (s->v->mode != MODE_TTS || s->np >= MAX_PIECES || s->nown >= MAX_PIECES) { + continue; + } + tts_text(s->v->tts_text, tm, int24, text, sizeof(text)); + tts_cmd(s->v, text, key, sizeof(key)); + if (speech_get(key, &sp, &n, s->how)) { + s->pending = 1; + continue; + } + s->own[s->nown++] = sp; + s->p[s->np].s = sp; + s->p[s->np].n = n; + s->p[s->np].is_pips = 0; + s->np++; + } else if (!strcasecmp(tok, "pips")) { + if (add(s, "pips") && s->np < MAX_PIECES) { + s->p[s->np].s = NULL; /* made-up pips */ + s->p[s->np].n = RATE * 2 + RATE / 10; + s->p[s->np].is_pips = 2; + s->np++; + } + } else if (*tok) { + add(s, "%s", tok); /* any clip by name: its, intro, phrase, ... */ + } + } +} + +/* three 0.1 s 1 kHz pips a second apart; the time mark is the third */ +static void make_pips(int16_t *p) +{ + int i, k; + for (k = 0; k < 3; k++) { + for (i = 0; i < RATE / 10; i++) { + p[k * RATE + i] = (int16_t) (8000 * sin(2 * M_PI * 1000 * i / RATE)); + } + } +} + +static long long floordiv(long long a, long long b) +{ + return a >= 0 ? a / b : -((-a + b - 1) / b); +} + +/* Render announcement j into r: the time it gives is j * period, and it + * starts so that its time mark (the third pip, if the voice has one) falls + * on that second exactly; without a mark it starts on that second. */ +static void render(sc_clock *st, struct ann *r, long long j) +{ + struct say s = { .v = st->v }; + struct sc_tm tm; + size_t i, total = 0, at = 0, mark = 0; + int marked = 0; + + /* speech is fetched only for announcements that can still start in + * time: one whose mark is less than 8 s off (about a sentence and the + * pips) uses it only if it's already here */ + s.how = st->wait_speech ? SPEECH_WAIT : + j * st->period * (long long) RATE < st->pos + 8 * RATE ? SPEECH_PEEK : SPEECH_ASK; + tm_get(j * st->period, st->zone, &tm); + compose(&s, st->sequence, &tm, st->int24); + for (i = 0; i < (size_t) s.np; i++) { + if (s.p[i].is_pips && !marked) { + if (s.p[i].is_pips == 2) { + mark = total + 2 * RATE; + marked = 1; + } else if (st->v->marker >= 0) { + mark = total + (size_t) llround(st->v->marker * RATE); + marked = 1; + } + } + total += s.p[i].n; + } + + free(r->s); + r->j = j; + r->used = 1; + r->pending = s.pending; + r->tried = st->pos; + r->n = total; + r->start = j * st->period * (long long) RATE - (marked ? (long long) mark : 0); + r->s = calloc(total ? total : 1, sizeof(int16_t)); + if (!r->s) { + r->n = 0; + total = 0; + } + for (i = 0; r->s && i < (size_t) s.np; i++) { + const int16_t *src = s.p[i].is_pips == 2 ? st->pips : s.p[i].s; + memcpy(r->s + at, src, s.p[i].n * sizeof(int16_t)); + at += s.p[i].n; + } + for (i = 0; i < (size_t) s.nown; i++) { + free(s.own[i]); + } +} + +static struct ann *ann_get(sc_clock *st, long long j) +{ + int i, oldest = 0; + for (i = 0; i < NREND; i++) { + if (st->r[i].used && st->r[i].j == j) { + struct ann *r = &st->r[i]; + /* speech that was missing may be here now: try again, at most + * every 200 ms, while the announcement hasn't started, and keep + * the new one only if it can still start on time */ + if (r->pending && r->start > st->pos && st->pos - r->tried >= RATE / 5) { + struct ann t = { 0 }; + render(st, &t, j); + if (t.start >= st->pos) { + free(r->s); + *r = t; + } else { + free(t.s); + r->tried = st->pos; + } + } + return r; + } + if (!st->r[i].used || st->r[i].j < st->r[oldest].j) { + oldest = i; + } + } + render(st, &st->r[oldest], j); + return &st->r[oldest]; +} + +/* Fill out[0..n) with the samples from st->pos on: every announcement that + * overlaps them, mixed. */ +void sc_clock_fill(sc_clock *st, int16_t *out, int n) +{ + long long ps = (long long) st->period * RATE, from = st->pos, to; + long long j, j0, j1; + int32_t mix[RATE]; + int i; + + if (n > RATE) { + n = RATE; + } + to = from + n; + j0 = floordiv(from, ps) - 1; + j1 = floordiv(to, ps) + 2; + memset(mix, 0, sizeof(int32_t) * n); + for (j = j0; j <= j1; j++) { + struct ann *r = ann_get(st, j); + long long a = MAX(from, r->start), b = MIN(to, r->start + (long long) r->n); + if (r->start < st->min_start) { + continue; + } + for (; a < b; a++) { + mix[a - from] += r->s[a - r->start]; + } + } + for (i = 0; i < n; i++) { + out[i] = mix[i] > 32767 ? 32767 : mix[i] < -32768 ? -32768 : mix[i]; + } + st->pos += n; +} + +static long long now_samples(void) +{ + long long us = now_us(); + return floordiv(us, 1000000) * RATE + (us - floordiv(us, 1000000) * 1000000) * RATE / 1000000; +} + +void sc_clock_play(sc_clock *st, int16_t *out, int n) +{ + long long now = now_samples(); + /* stay on the system clock: if the channel's timing has drifted more + * than 20 ms, jump (the old machines were run off a master clock too) */ + if (now - st->last_sync > RATE) { + if (llabs(now - st->pos) > RATE / 50) { + sc_log(SC_LOG_DEBUG, "SpeakingClock: %lld samples off, resynced", now - st->pos); + st->pos = now; + } + st->last_sync = now; + } + sc_clock_fill(st, out, n); +} + +void sc_clock_start(sc_clock *st) +{ + st->pos = st->last_sync = now_samples(); + st->min_start = st->wait ? st->pos : LLONG_MIN; +} + +void sc_clock_render_from(sc_clock *st, long long t, const char *zone) +{ + if (zone && *zone) { + copy(st->zone, zone, sizeof(st->zone)); + } + st->pos = st->last_sync = t * RATE; + st->min_start = LLONG_MIN; + st->wait_speech = 1; +} + +void sc_clock_free(sc_clock *st) +{ + int i; + if (!st) { + return; + } + for (i = 0; i < NREND; i++) { + free(st->r[i].s); + } + voice_unref(st->v); + free(st); +} + +sc_clock *sc_clock_new(const char *voice_id, const struct sc_options *o) +{ + sc_clock *st = calloc(1, sizeof(*st)); + char id[96]; + + if (!st) { + return NULL; + } + pthread_mutex_lock(&conf_lock); + copy(id, voice_id && *voice_id ? voice_id : default_voice, sizeof(id)); + copy(st->zone, default_zone, sizeof(st->zone)); + pthread_mutex_unlock(&conf_lock); + if (!(st->v = voice_get(id))) { + free(st); + return NULL; + } + copy(st->sequence, st->v->sequence, sizeof(st->sequence)); + st->period = st->v->period; + st->int24 = st->v->int24; + if (o) { + if (*o->zone) { + copy(st->zone, o->zone, sizeof(st->zone)); + } + if (*o->sequence) { + copy(st->sequence, o->sequence, sizeof(st->sequence)); + } + if (o->period > 0) { + st->period = o->period; + } + if (o->int24) { + st->int24 = 1; + } + st->wait = o->wait; + } + make_pips(st->pips); + sc_clock_start(st); + return st; +} + +/* ---- options ---------------------------------------------------------- */ + +/* "t(Europe/London)d(300)hw": the letters SpeakingClock() takes */ +int sc_options_parse(const char *s, struct sc_options *o) +{ + memset(o, 0, sizeof(*o)); + for (; s && *s; s++) { + char opt = *s, arg[256] = ""; + if (isspace((unsigned char) opt) || opt == ',') { + continue; + } + if (s[1] == '(') { + const char *close = strchr(s + 2, ')'); + if (!close) { + return -1; + } + copy(arg, s + 2, MIN(sizeof(arg), (size_t) (close - s - 1))); + s = close; + } + switch (opt) { + case 'd': + o->has_duration = 1; + o->duration = atoi(arg); + break; + case 'h': + o->int24 = 1; + break; + case 'p': + o->period = atoi(arg); + break; + case 's': + copy(o->sequence, arg, sizeof(o->sequence)); + break; + case 't': + copy(o->zone, arg, sizeof(o->zone)); + break; + case 'w': + o->wait = 1; + break; + case 'x': + o->exit_on_key = 1; + break; + default: + sc_log(SC_LOG_WARNING, "SpeakingClock: unknown option '%c'", opt); + return -1; + } + } + return 0; +} + +/* ---- listing ---------------------------------------------------------- */ + +int sc_voices_list(void (*cb)(void *arg, const char *id, const char *mode, const char *name), + void *arg) +{ + char dir[PATH_MAX]; + struct dirent **list; + int i, n, count = 0; + + sc_voicedir(dir, sizeof(dir)); + if ((n = scandir(dir, &list, NULL, alphasort)) < 0) { + return -1; + } + for (i = 0; i < n; i++) { + struct voice *v; + char p[PATH_MAX + 512]; + struct stat sb; + snprintf(p, sizeof(p), "%s/%s", dir, list[i]->d_name); + if (id_ok(list[i]->d_name) && !stat(p, &sb) && S_ISDIR(sb.st_mode) && + (v = voice_get(list[i]->d_name))) { + cb(arg, v->id, mode_name(v->mode), v->name); + voice_unref(v); + count++; + } + free(list[i]); + } + free(list); + return count; +} diff --git a/core/speakingclock.h b/core/speakingclock.h new file mode 100644 index 0000000..e4da7ea --- /dev/null +++ b/core/speakingclock.h @@ -0,0 +1,93 @@ +/* + * speakingclock - the clock itself, for the FreeSWITCH module (and anything + * else that wants it): voices, announcements placed by sample against the + * system clock, and live speech from a synthesiser program. + * + * Copyright (C) 2026 D-Modem Authors + * + * SPDX-License-Identifier: GPL-2.0-or-later + * + * It works the way app_speakingclock does (asterisk/), and reads the same + * voice folders (docs/voice-format.md). It has no dependencies but libc, + * libm and pthreads: the program it runs in gives it a log and a clock in + * a time zone (struct sc_host). + */ + +#ifndef SPEAKINGCLOCK_H +#define SPEAKINGCLOCK_H + +#include +#include + +#define SC_RATE 8000 /* everything is 8 kHz, 16-bit, mono */ + +enum sc_log_level { SC_LOG_DEBUG, SC_LOG_NOTICE, SC_LOG_WARNING, SC_LOG_ERROR }; + +struct sc_tm { + int hour, min, sec; +}; + +struct sc_host { + /* one line, without a newline */ + void (*log)(enum sc_log_level level, const char *msg); + /* the time t (seconds since the epoch) in zone ("" or NULL: the + * system's); 0 on success */ + int (*localtime)(long long t, const char *zone, struct sc_tm *tm); + /* microseconds since the epoch; NULL: gettimeofday() */ + long long (*now_us)(void); +}; + +/* Start (the speech worker) and stop. sc_init() keeps the pointer. */ +int sc_init(const struct sc_host *host); +void sc_shutdown(void); + +/* Configuration: begin resets every setting to its default, set takes one + * (voicedir, default_voice, timezone, maxduration, tts_timeout, + * tts_program_), and end drops the loaded voices, so they load + * again on next use. Unknown keys are ignored. */ +void sc_config_begin(const char *default_voicedir); +void sc_config_set(const char *key, const char *value); +void sc_config_end(void); +int sc_maxduration(void); + +/* The options SpeakingClock() takes, in the same letters: + * d(seconds) h p(seconds) s(seq) t(zone) w x */ +struct sc_options { + int has_duration; + int duration; + int int24; + int period; /* 0: the voice's */ + char sequence[256]; /* "": the voice's */ + char zone[64]; /* "": timezone= in the config, else the system's */ + int wait; + int exit_on_key; +}; +/* 0, or -1 for options it doesn't know */ +int sc_options_parse(const char *s, struct sc_options *o); + +typedef struct sc_clock sc_clock; + +/* A clock playing voice (NULL or "": default_voice), or NULL if there is + * no such voice. */ +sc_clock *sc_clock_new(const char *voice, const struct sc_options *o); +void sc_clock_free(sc_clock *c); +/* Put the clock on the system's time now (call it when the call is + * answered and audio is about to flow). With the 'w' option, nothing + * that started before now is played. */ +void sc_clock_start(sc_clock *c); +/* The next n samples (n <= SC_RATE) for a call: it stays on the system + * clock, jumping back to it if it drifts by more than 20 ms. */ +void sc_clock_play(sc_clock *c, int16_t *out, int n); +/* Rendering without a call: from t (seconds since the epoch), with live + * speech waited for, so nothing is missing. Then sc_clock_fill(). */ +void sc_clock_render_from(sc_clock *c, long long t, const char *zone); +void sc_clock_fill(sc_clock *c, int16_t *out, int n); + +/* Every voice in voicedir, sorted: cb(arg, id, mode, name). The number + * of voices, or -1 if voicedir can't be read. */ +int sc_voices_list(void (*cb)(void *arg, const char *id, const char *mode, const char *name), + void *arg); +/* The voicedir setting, copied to out. */ +void sc_voicedir(char *out, size_t len); + +#endif diff --git a/docs/voice-format.md b/docs/voice-format.md index 0b2fa39..b6e6bd2 100644 --- a/docs/voice-format.md +++ b/docs/voice-format.md @@ -1,8 +1,10 @@ # Voice format A voice is a folder under `voicedir` (default -`/sounds/speaking-clock`). The folder's name is the voice's id, -the name you pass to `SpeakingClock()`. It holds a `voice.conf` and its clips. +`/sounds/speaking-clock` on Asterisk, `/speaking-clock` +on FreeSWITCH). The folder's name is the voice's id, the name you pass to +`SpeakingClock()` (or FreeSWITCH's `speakingclock`). app_speakingclock and +mod_speakingclock read the same voices. It holds a `voice.conf` and its clips. ## Clips @@ -79,7 +81,7 @@ hours=12 ; or 24 ## Live voices (mode=tts) A live voice has no number clips. Each announcement's sentence is spoken -whole, when it is needed, by a synthesiser program on the Asterisk machine +whole, when it is needed, by a synthesiser program on the Asterisk or FreeSWITCH machine (DECtalk, SAM). ``` @@ -97,7 +99,7 @@ text=At the third stroke, it will be {hour} {minute} {seconds}. - **command**: the program to run, split into words like a shell would (with `"..."` and `'...'`), but run without one, so the text is always a single argument. `{program:name}` becomes `tts_program_name` from - speakingclock.conf (else `name`, found on the PATH), `{text}` the text, + speakingclock.conf or speakingclock.conf.xml (else `name`, found on the PATH), `{text}` the text, and an argument `{out}` a file for it to write the WAV to. Without `{out}` the WAV is read from its standard output. - **text**: what each announcement says. In words: `{hour}`, `{minute}` diff --git a/freeswitch/Makefile b/freeswitch/Makefile new file mode 100644 index 0000000..9e831ac --- /dev/null +++ b/freeswitch/Makefile @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# mod_speakingclock.so, built against an installed FreeSWITCH's headers +# (libfreeswitch-dev, or a source install's include/freeswitch), found with +# pkg-config. +# +# make build mod_speakingclock.so +# make install install the module, speakingclock.conf.xml and the voices +# make FS_INCLUDE=/usr/local/freeswitch/include/freeswitch \ +# MODULES_DIR=... CONF_DIR=... SOUNDS_DIR=... + +PC := $(shell pkg-config --exists freeswitch 2>/dev/null && echo freeswitch) +FS_INCLUDE ?= $(if $(PC),,$(firstword $(wildcard /usr/include/freeswitch \ + /usr/local/freeswitch/include/freeswitch) /usr/include/freeswitch)) +FS_CFLAGS ?= $(if $(PC),$(shell pkg-config --cflags freeswitch),-I$(FS_INCLUDE)) +FS_LIBS ?= $(if $(PC),$(shell pkg-config --libs freeswitch)) +pcvar = $(if $(PC),$(shell pkg-config --variable=$(1) freeswitch)) +MODULES_DIR ?= $(firstword $(call pcvar,modulesdir) $(wildcard /usr/lib/freeswitch/mod \ + /usr/local/freeswitch/mod) /usr/lib/freeswitch/mod) +CONF_DIR ?= $(firstword $(call pcvar,confdir) $(wildcard /etc/freeswitch \ + /usr/local/freeswitch/conf) /etc/freeswitch) +SOUNDS_DIR ?= $(firstword $(call pcvar,soundsdir) $(wildcard /usr/share/freeswitch/sounds \ + /usr/local/freeswitch/sounds) /usr/share/freeswitch/sounds) + +CFLAGS ?= -g -O2 +CFLAGS += -Wall -fPIC -pthread -D_GNU_SOURCE $(FS_CFLAGS) -I../core + +SRC = mod_speakingclock.c ../core/speakingclock.c + +all: mod_speakingclock.so + +mod_speakingclock.so: $(SRC) ../core/speakingclock.h + $(CC) $(CFLAGS) -shared -o $@ $(SRC) $(FS_LIBS) -lm + +install: mod_speakingclock.so + install -d $(DESTDIR)$(MODULES_DIR) $(DESTDIR)$(CONF_DIR)/autoload_configs \ + $(DESTDIR)$(SOUNDS_DIR)/speaking-clock + install -m 755 mod_speakingclock.so $(DESTDIR)$(MODULES_DIR)/ + test -e $(DESTDIR)$(CONF_DIR)/autoload_configs/speakingclock.conf.xml || \ + install -m 644 speakingclock.conf.xml \ + $(DESTDIR)$(CONF_DIR)/autoload_configs/speakingclock.conf.xml + cp -R ../voices/. $(DESTDIR)$(SOUNDS_DIR)/speaking-clock/ + install -m 644 ../NOTICE.md $(DESTDIR)$(SOUNDS_DIR)/speaking-clock/ + +clean: + rm -f mod_speakingclock.so + +.PHONY: all install clean diff --git a/freeswitch/dialplan-example.xml b/freeswitch/dialplan-example.xml new file mode 100644 index 0000000..88e6498 --- /dev/null +++ b/freeswitch/dialplan-example.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/freeswitch/mod_speakingclock.c b/freeswitch/mod_speakingclock.c new file mode 100644 index 0000000..1725d9a --- /dev/null +++ b/freeswitch/mod_speakingclock.c @@ -0,0 +1,337 @@ +/* + * mod_speakingclock - a telephone speaking clock for FreeSWITCH + * + * Copyright (C) 2026 D-Modem Authors + * + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See LICENSE. + * + * The speakingclock dialplan application: the same clock as Asterisk's + * SpeakingClock() (core/speakingclock.c does the work), reading the same + * voice folders. Each announcement is placed by sample against the + * system clock, so the time mark falls exactly on the second it + * announces; live voices (mode=tts) run a synthesiser on this machine. + * + * + * + * API: speakingclock voices | render [zone] | reload + */ + +#include +#include "speakingclock.h" + +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +SWITCH_MODULE_LOAD_FUNCTION(mod_speakingclock_load); +SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_speakingclock_shutdown); +SWITCH_MODULE_DEFINITION(mod_speakingclock, mod_speakingclock_load, mod_speakingclock_shutdown, NULL); + +#define CONF "speakingclock.conf" +#define APP_SYNTAX "[voice] [options: t(zone) d(seconds) h p(seconds) s(a+b+c) w x]" +#define API_SYNTAX "voices | render [zone] | reload" + +static switch_event_node_t *reload_node; + +/* ---- what the core needs ---------------------------------------------- */ + +static void host_log(enum sc_log_level level, const char *msg) +{ + switch_log_level_t l = level == SC_LOG_ERROR ? SWITCH_LOG_ERROR : + level == SC_LOG_WARNING ? SWITCH_LOG_WARNING : + level == SC_LOG_NOTICE ? SWITCH_LOG_NOTICE : SWITCH_LOG_DEBUG; + switch_log_printf(SWITCH_CHANNEL_LOG, l, "%s\n", msg); +} + +/* FreeSWITCH's own time zones (timezones.conf.xml), else the system's */ +static int host_localtime(long long t, const char *zone, struct sc_tm *tm) +{ + switch_time_exp_t e = { 0 }; + switch_time_t when = (switch_time_t) t * 1000000; + + if (zone && *zone) { + if (switch_time_exp_tz_name(zone, &e, when) != SWITCH_STATUS_SUCCESS) { + /* once, not every announcement (a race here only costs a log line) */ + static char last_bad[64]; + if (strncmp(last_bad, zone, sizeof(last_bad) - 1)) { + switch_copy_string(last_bad, zone, sizeof(last_bad)); + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, + "SpeakingClock: unknown time zone '%s' (see timezones.conf.xml), using the system's\n", zone); + } + return -1; + } + } else if (switch_time_exp_lt(&e, when) != SWITCH_STATUS_SUCCESS) { + return -1; + } + tm->hour = e.tm_hour; + tm->min = e.tm_min; + tm->sec = e.tm_sec; + return 0; +} + +static long long host_now_us(void) +{ + return (long long) switch_micro_time_now(); +} + +static const struct sc_host host = { + .log = host_log, + .localtime = host_localtime, + .now_us = host_now_us, +}; + +/* ---- configuration ---------------------------------------------------- */ + +static void load_config(void) +{ + char dir[1024]; + switch_xml_t cfg, xml, settings, param; + + switch_snprintf(dir, sizeof(dir), "%s%sspeaking-clock", SWITCH_GLOBAL_dirs.sounds_dir, SWITCH_PATH_SEPARATOR); + sc_config_begin(dir); + if ((xml = switch_xml_open_cfg(CONF, &cfg, NULL))) { + if ((settings = switch_xml_child(cfg, "settings"))) { + for (param = switch_xml_child(settings, "param"); param; param = param->next) { + const char *name = switch_xml_attr_soft(param, "name"); + const char *value = switch_xml_attr_soft(param, "value"); + sc_config_set(name, value); + } + } + switch_xml_free(xml); + } else { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, + "SpeakingClock: no %s, using the defaults (voices in %s)\n", CONF, dir); + } + /* the voices load again on next use */ + sc_config_end(); +} + +static void on_reloadxml(switch_event_t *event) +{ + load_config(); +} + +/* ---- the application -------------------------------------------------- */ + +/* data: "[voice] [options]", the options in SpeakingClock()'s letters. + * The voice may be left out ("" or a word that starts with an option and + * a parenthesis is taken as options). Asterisk's "voice,options" works + * too. */ +static int parse_args(const char *data, char *voice, size_t vlen, struct sc_options *o) +{ + char *buf = strdup(data ? data : ""), *p = buf, *sep; + int res; + + if (!buf) { + return -1; + } + while (*p == ' ' || *p == '\t') { + p++; + } + voice[0] = '\0'; + sep = p + strcspn(p, " \t,"); + /* a voice name has no parentheses */ + if (!memchr(p, '(', sep - p)) { + switch_copy_string(voice, p, MIN(vlen, (size_t) (sep - p) + 1)); + p = *sep ? sep + 1 : sep; + } + res = sc_options_parse(p, o); + free(buf); + return res; +} + +SWITCH_STANDARD_APP(speakingclock_function) +{ + switch_channel_t *channel = switch_core_session_get_channel(session); + switch_memory_pool_t *pool = switch_core_session_get_pool(session); + switch_codec_implementation_t impl = { 0 }; + switch_codec_t codec = { 0 }; + switch_timer_t timer = { 0 }; + switch_frame_t wf = { 0 }; + struct sc_options o; + char voice[96]; + int16_t buf[SC_RATE / 10]; + int ms, samples, duration; + switch_time_t end = 0; + sc_clock *clk; + + if (parse_args(data, voice, sizeof(voice), &o)) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, + "SpeakingClock: bad options '%s'; usage: speakingclock %s\n", switch_str_nil(data), APP_SYNTAX); + return; + } + duration = o.has_duration ? o.duration : sc_maxduration(); + if (!(clk = sc_clock_new(voice, &o))) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, + "SpeakingClock: no voice '%s'\n", *voice ? voice : "(default)"); + return; + } + if (switch_channel_answer(channel) != SWITCH_STATUS_SUCCESS) { + sc_clock_free(clk); + return; + } + + /* frames as long as the call's, in 8 kHz signed linear: FreeSWITCH + * changes them to the call's codec and rate */ + switch_core_session_get_read_impl(session, &impl); + ms = impl.microseconds_per_packet / 1000; + if (ms < 10 || ms > 100) { + ms = 20; + } + samples = SC_RATE * ms / 1000; + if (switch_core_codec_init(&codec, "L16", NULL, NULL, SC_RATE, ms, 1, + SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, + "SpeakingClock: can't set up L16 at 8 kHz\n"); + sc_clock_free(clk); + return; + } + if (switch_core_timer_init(&timer, "soft", ms, samples, pool) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, + "SpeakingClock: can't start a timer\n"); + switch_core_codec_destroy(&codec); + sc_clock_free(clk); + return; + } + wf.codec = &codec; + wf.data = buf; + wf.buflen = sizeof(buf); + wf.rate = SC_RATE; + wf.channels = 1; + + switch_channel_flush_dtmf(channel); + if (duration > 0) { + end = switch_micro_time_now() + (switch_time_t) duration * 1000000; + } + sc_clock_start(clk); + while (switch_channel_ready(channel)) { + switch_frame_t *rf; + switch_status_t status; + + if (end && switch_micro_time_now() >= end) { + break; + } + /* read what the caller sends (and their keys), without waiting: + * the timer sets the pace, and the clock its position */ + status = switch_core_session_read_frame(session, &rf, SWITCH_IO_FLAG_NOBLOCK, 0); + if (!SWITCH_READ_ACCEPTABLE(status)) { + break; + } + if (switch_channel_has_dtmf(channel)) { + switch_dtmf_t dtmf = { 0 }; + switch_channel_dequeue_dtmf(channel, &dtmf); + if (o.exit_on_key) { + switch_channel_set_variable_printf(channel, "speakingclock_key", "%c", dtmf.digit); + break; + } + } + sc_clock_play(clk, buf, samples); + wf.datalen = samples * sizeof(int16_t); + wf.samples = samples; + if (switch_core_session_write_frame(session, &wf, SWITCH_IO_FLAG_NONE, 0) != SWITCH_STATUS_SUCCESS) { + break; + } + switch_core_timer_next(&timer); + } + switch_core_timer_destroy(&timer); + switch_core_codec_destroy(&codec); + sc_clock_free(clk); +} + +/* ---- the API ---------------------------------------------------------- */ + +static void list_voice(void *arg, const char *id, const char *mode, const char *name) +{ + switch_stream_handle_t *stream = arg; + stream->write_function(stream, "%-36s %-8s %s\n", id, mode, name); +} + +SWITCH_STANDARD_API(speakingclock_api) +{ + char *argv[8] = { 0 }, *mycmd = NULL; + int argc = 0; + + if (!zstr(cmd) && (mycmd = strdup(cmd))) { + argc = switch_separate_string(mycmd, ' ', argv, (sizeof(argv) / sizeof(argv[0]))); + } + if (argc >= 1 && !strcasecmp(argv[0], "voices")) { + char dir[1024]; + stream->write_function(stream, "%-36s %-8s %s\n", "Voice", "Mode", "Name"); + if (sc_voices_list(list_voice, stream) < 0) { + sc_voicedir(dir, sizeof(dir)); + stream->write_function(stream, "-ERR can't read %s\n", dir); + } + } else if (argc >= 5 && !strcasecmp(argv[0], "render")) { + /* what a caller would hear, without a call: for checking a voice */ + int seconds = atoi(argv[3]), i; + sc_clock *clk; + FILE *f; + if (seconds <= 0 || seconds > 3600) { + stream->write_function(stream, "-ERR seconds: 1 to 3600\n"); + } else if (!(clk = sc_clock_new(argv[1], NULL))) { + stream->write_function(stream, "-ERR no voice '%s'\n", argv[1]); + } else if (!(f = fopen(argv[4], "wb"))) { + stream->write_function(stream, "-ERR can't write %s\n", argv[4]); + sc_clock_free(clk); + } else { + sc_clock_render_from(clk, strtoll(argv[2], NULL, 10), argc > 5 ? argv[5] : NULL); + for (i = 0; i < seconds * 10; i++) { + int16_t out[SC_RATE / 10]; + sc_clock_fill(clk, out, SC_RATE / 10); + fwrite(out, sizeof(out), 1, f); + } + fclose(f); + sc_clock_free(clk); + stream->write_function(stream, "+OK wrote %d s to %s\n", seconds, argv[4]); + } + } else if (argc >= 1 && !strcasecmp(argv[0], "reload")) { + load_config(); + stream->write_function(stream, "+OK\n"); + } else { + stream->write_function(stream, "-USAGE: speakingclock %s\n", API_SYNTAX); + } + switch_safe_free(mycmd); + return SWITCH_STATUS_SUCCESS; +} + +/* ---- module ----------------------------------------------------------- */ + +SWITCH_MODULE_LOAD_FUNCTION(mod_speakingclock_load) +{ + switch_application_interface_t *app_interface; + switch_api_interface_t *api_interface; + + *module_interface = switch_loadable_module_create_module_interface(pool, modname); + if (sc_init(&host)) { + return SWITCH_STATUS_FALSE; + } + load_config(); + if (switch_event_bind_removable(modname, SWITCH_EVENT_RELOADXML, NULL, on_reloadxml, NULL, + &reload_node) != SWITCH_STATUS_SUCCESS) { + switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, + "SpeakingClock: reloadxml won't reread %s (speakingclock reload will)\n", CONF); + } + SWITCH_ADD_APP(app_interface, "speakingclock", "Telephone speaking clock", + "Answers and plays the time like a telephone company speaking clock, with the " + "time mark on the exact second, until the caller hangs up or the duration runs out.", + speakingclock_function, APP_SYNTAX, SAF_NONE); + SWITCH_ADD_API(api_interface, "speakingclock", "Speaking clock voices and rendering", + speakingclock_api, API_SYNTAX); + switch_console_set_complete("add speakingclock voices"); + switch_console_set_complete("add speakingclock render"); + switch_console_set_complete("add speakingclock reload"); + return SWITCH_STATUS_SUCCESS; +} + +SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_speakingclock_shutdown) +{ + switch_event_unbind(&reload_node); + switch_console_set_complete("del speakingclock"); + sc_shutdown(); + return SWITCH_STATUS_SUCCESS; +} diff --git a/freeswitch/speakingclock.conf.xml b/freeswitch/speakingclock.conf.xml new file mode 100644 index 0000000..9c5931a --- /dev/null +++ b/freeswitch/speakingclock.conf.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/render_test.py b/test/render_test.py index 2b3097f..03e6030 100755 --- a/test/render_test.py +++ b/test/render_test.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-or-later -"""Checks app_speakingclock in a running Asterisk, through its CLI. +"""Checks app_speakingclock in a running Asterisk, or mod_speakingclock in a +running FreeSWITCH (PBX=freeswitch), through its CLI. - For the tim voices, the third pip starts exactly on the second it announces (to the sample). @@ -11,8 +12,9 @@ synthesiser, tts_program_* in speakingclock.conf) and its made-up third pip lands on the second. Live voices are left out otherwise. -Run as a user that may use `asterisk -rx`, with the module loaded and the -voices installed: test/render_test.py +Run as a user that may use `asterisk -rx` (or `fs_cli -x`), with the module +loaded and the voices installed: test/render_test.py +(PBX=freeswitch test/render_test.py for FreeSWITCH). """ import os import struct @@ -31,9 +33,15 @@ def ok(cond, what): print("FAIL:", what) +FREESWITCH = os.environ.get("PBX", "asterisk").lower() == "freeswitch" + + def cli(cmd): - return subprocess.run(["asterisk", "-rx", cmd], capture_output=True, - text=True, check=True).stdout + if FREESWITCH: + argv = ["fs_cli", "-x", cmd.replace("speakingclock show voices", "speakingclock voices")] + else: + argv = ["asterisk", "-rx", cmd] + return subprocess.run(argv, capture_output=True, text=True, check=True).stdout def render(voice, start, seconds, zone="UTC"): @@ -41,7 +49,7 @@ def render(voice, start, seconds, zone="UTC"): path = f.name try: out = cli("speakingclock render %s %d %d %s %s" % (voice, start, seconds, path, zone)) - if "Wrote" not in out: + if "wrote" not in out.lower(): raise RuntimeError(out.strip()) with open(path, "rb") as f: d = f.read() @@ -116,7 +124,10 @@ if tts: marks.append(list(a[second:second + 80]) == tone) ok(marks and all(marks), "%s: third pip on the second %s" % (tts, marks)) ok(max(abs(x) for x in a[:3 * RATE]) > 1000, "%s: no speech" % tts) -ok("Asterisk" in cli("core show version"), "Asterisk still up") +if FREESWITCH: + ok("FreeSWITCH" in cli("version"), "FreeSWITCH still up") +else: + ok("Asterisk" in cli("core show version"), "Asterisk still up") print("%s" % ("all passed" if not failed else "%d failed" % failed)) sys.exit(1 if failed else 0)