Merge pull request #4 from D-Modem/claude/project-thread-d9flsk

Add FreeSWITCH support: mod_speakingclock
This commit is contained in:
Neo authored and GitHub committed 2026-11-10 22:53:55 -08:00
commit a01f3f7eda
12 files changed
+2362 -13

No files matched your search

+2
View File
@@ -3,3 +3,5 @@ asterisk/app_speakingclock.so
__pycache__/
synth/macintalk/macintalk
synth/mssam/mssam
freeswitch/mod_speakingclock.so
core/sclock-render
+54 -2
View File
@@ -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 `<load module="mod_speakingclock"/>` to `autoload_configs/modules.conf.xml`
to load it at start. In the dialplan
([dialplan-example.xml](freeswitch/dialplan-example.xml)):
```xml
<extension name="speakingclock_tim">
<condition field="destination_number" expression="^123$">
<action application="speakingclock" data="tim-pat-simmons t(Europe/London)"/>
</condition>
</extension>
```
`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 <voice> <unix time> <seconds> <file.sln> [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
+19
View File
@@ -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
+118
View File
@@ -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]... <voice> <unix time> <seconds> <out.sln> [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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
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]... <voice> <unix time> <seconds> <out.sln> [zone]\n"
" sclock-render [-v voicedir] -l\n");
return 2;
}
+1589
View File
File diff suppressed because it is too large. Load diff
+93
View File
@@ -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 <stddef.h>
#include <stdint.h>
#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_<name>), 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
+6 -4
View File
@@ -1,8 +1,10 @@
# Voice format
A voice is a folder under `voicedir` (default
`<astdatadir>/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.
`<astdatadir>/sounds/speaking-clock` on Asterisk, `<sounds_dir>/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}`
+47
View File
@@ -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
+34
View File
@@ -0,0 +1,34 @@
<!-- Speaking clocks for FreeSWITCH's dialplan: put these in a context,
e.g. as dialplan/default/00_speakingclock.xml for the default context. -->
<include>
<!-- the UK's TIM: "At the third stroke it will be ..." -->
<extension name="speakingclock_tim">
<condition field="destination_number" expression="^123$">
<action application="speakingclock" data="tim-pat-simmons t(Europe/London)"/>
</condition>
</extension>
<!-- Australia's Gordon Gow -->
<extension name="speakingclock_gordon_gow">
<condition field="destination_number" expression="^1194$">
<action application="speakingclock" data="tim-gordon-gow t(Australia/Sydney)"/>
</condition>
</extension>
<!-- POPCORN: five minutes, then hang up -->
<extension name="speakingclock_popcorn">
<condition field="destination_number" expression="^767$">
<action application="speakingclock" data="atandt-mike t(America/Los_Angeles)d(300)"/>
</condition>
</extension>
<!-- Microsoft Sam, spoken live by synth/mssam. A key press ends it and
the dialplan goes on (the channel variable speakingclock_key holds
the key). -->
<extension name="speakingclock_sam">
<condition field="destination_number" expression="^1236$">
<action application="speakingclock" data="live-mssam-sam t(Europe/London)x"/>
<action application="hangup"/>
</condition>
</extension>
</include>
+337
View File
@@ -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.
*
* <action application="speakingclock" data="tim-pat-simmons t(Europe/London)"/>
*
* API: speakingclock voices | render <voice> <unix time> <seconds> <file.sln> [zone] | reload
*/
#include <switch.h>
#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 <voice> <unix time> <seconds> <file.sln> [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;
}
+45
View File
@@ -0,0 +1,45 @@
<!-- speakingclock.conf.xml - mod_speakingclock, the speakingclock application
In the dialplan, for example:
<extension name="tim">
<condition field="destination_number" expression="^123$">
<action application="speakingclock" data="tim-pat-simmons t(Europe/London)"/>
</condition>
</extension>
"speakingclock voices" lists the voices. "speakingclock reload" (or
reloadxml) rereads this file and the voices. -->
<configuration name="speakingclock.conf" description="Telephone speaking clock">
<settings>
<!-- Where the voice folders are. Default: the speaking-clock folder
in FreeSWITCH's sounds directory. -->
<!-- <param name="voicedir" value="/usr/share/freeswitch/sounds/speaking-clock"/> -->
<!-- The voice used when the application is given none. -->
<!-- <param name="default_voice" value="tim-pat-simmons"/> -->
<!-- The time zone used when the t() option is not given, by its name in
timezones.conf.xml. Default: the system's. -->
<!-- <param name="timezone" value="Europe/London"/> -->
<!-- Hang up after this many seconds (0: never). The d() option
overrides it. -->
<!-- <param name="maxduration" value="180"/> -->
<!-- The live DECtalk, SAM and MacInTalk voices run the synthesiser on
this machine, with no server. Default: dectalk, sam and macintalk,
found on the PATH. macintalk is synth/macintalk in this repository
(it speaks the MacInTalk 3 and the PlainTalk voices). -->
<!-- <param name="tts_program_dectalk" value="/opt/dectalk/say"/> -->
<!-- <param name="tts_program_sam" value="/usr/local/bin/sam"/> -->
<!-- <param name="tts_program_macintalk" value="/usr/local/bin/macintalk"/> -->
<!-- The live Microsoft Sam, Mike and Mary voices run synth/mssam
(default: mssam, found on the PATH). -->
<!-- <param name="tts_program_mssam" value="/usr/local/bin/mssam"/> -->
<!-- Seconds a synthesiser program may take before it is stopped. -->
<!-- <param name="tts_timeout" value="15"/> -->
</settings>
</configuration>
+18 -7
View File
@@ -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)