Add mssam, our own synthesiser for the Microsoft Sam, Mike and Mary voices

synth/mssam reads the voice data of Microsoft's Speech API 4 voices and
speaks with it: the voice's context trees pick a recorded unit for each
sound, and the units are joined with new pitch (from the voice's tone
table) and timing. No Microsoft code is used or run. tools/fetch-mssam.py
downloads msttsl.exe at build time and keeps only the voice data.
docs/mssam-format.md describes the data. Adds live-mssam-sam, -mike and
-mary, and an mssam engine in tools/synth_voices.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRVXG9MBYPxmcs9cFxs
This commit is contained in:
Claude committed 2026-11-11 01:22:39 +00:00
1 parent ada00bab6c
commit 494ef8f23c
15 files changed
+1611 -6

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
asterisk/app_speakingclock.so
/sources/
__pycache__/
synth/mssam/mssam
+11
View File
@@ -77,6 +77,17 @@ voices, belong to their owners:
voice is TruVoice Adult Male #2 at the pitch and speed BonziBUDDY used.
The live voices (`live-*`) hold no recordings: each sentence is spoken
when it is needed, by DECtalk or SAM on the Asterisk machine.
- **Microsoft Sam, Mike and Mary, live** (`live-mssam-*`): no recordings.
Each sentence is spoken on the Asterisk machine by `synth/mssam`, our own
synthesiser (GPL-2.0-or-later, like the rest of this repository), which
reads the voice data of Microsoft's Speech API 4 voices. That data is
Microsoft's and is not in this repository: `tools/fetch-mssam.py`
downloads Microsoft's package (msttsl.exe) from the Internet Archive and
keeps only the voice data, none of Microsoft's programs. Microsoft is a
trademark of Microsoft Corporation. The word list in
`synth/mssam/lexicon.h`, and the `cmudict.dict` the fetch script
downloads, are from the CMU Pronouncing Dictionary, © 1993-2015 Carnegie
Mellon University, under its BSD-style licence (in `lexicon.h`).
- **DECtalk** (`dectalk-*`): DECtalk 4.x, made by Digital Equipment
Corporation and later Fonix. Built from the source at
<https://github.com/dectalk/dectalk>.
+6
View File
@@ -82,6 +82,11 @@ tts_program_dectalk=/opt/dectalk/say
tts_program_sam=/usr/local/bin/sam
```
The `live-mssam-*` voices (Microsoft Sam, Mike and Mary) run
[synth/mssam](synth/mssam), our own synthesiser, which reads Microsoft's
voice data (`cd synth/mssam && make && make voices && sudo make install`
builds it and fetches the data). Its setting is `tts_program_mssam`.
See [docs/voice-format.md](docs/voice-format.md#live-voices-modetts).
## FreePBX
@@ -110,6 +115,7 @@ tools/synth_voices.py --list # the voices it knows
tools/synth_voices.py voices sapi4:microsoft-sam # SAPI4, via tetyys.com
DECTALK_SAY=~/dectalk/dist/say tools/synth_voices.py voices dectalk:paul
SAM=~/SAM/sam tools/synth_voices.py voices sam:sam
MSSAM=synth/mssam/mssam tools/synth_voices.py --live voices mssam:sam # live-mssam-sam
tools/synth_voices.py voices mac:Fred # MacInTalk, on a Mac
tools/synth_voices.py voices mac:Victoria # PlainTalk, on a Mac
```
+4
View File
@@ -30,3 +30,7 @@
; Seconds a synthesiser program may take before it is stopped.
;tts_timeout=15
; The live Microsoft Sam, Mike and Mary voices run synth/mssam (default:
; mssam, found on the PATH).
;tts_program_mssam=/usr/local/bin/mssam
+89
View File
@@ -0,0 +1,89 @@
# Microsoft Sam, Mike and Mary voice data
What synth/mssam reads, as we decoded it from the data alone. The voices
come in Microsoft's Speech API 4 TTS package `msttsl.exe` (SHA-1
d988cbb3e99bc9dd850defda939c06b81d9d4544), a cabinet holding `sam.vce`,
`male.vce` (Mike) and `female.vce` (Mary). Each `.vce` is an OLE compound
file with these streams: `Inventory`, `TreeImage`, `PhoneFile`, `Senone`,
`Cdb`, `VcHeader` (and `AltUnits` in Sam's). `tools/fetch-mssam.py`
writes `Inventory` as `<voice>.inv`, `Cdb` as `<voice>.tones`, and
`TreeImage` rewritten as `<voice>.tree`.
## Inventory (`.inv`, little-endian)
u32 rate (22050), order (20), nlsf (6), na (11), nb (13), 2 more
nlsf tables, then na tables, then nb tables; each:
u32 count, u32 dim, count*dim float32
u32 nunits, u32 size, (nunits+1) u32 offsets, then the units
The 6 line-spectrum codebooks have 256 entries of 3, 3, 3, 3, 4 and 4
values: one entry from each makes the 20 line spectral frequencies of a
frame (in cycles per sample). The excitation codebooks have 128 entries;
family A's 11 dims and family B's 13 dims each add up to 510, the points
of one pitch period scaled to a fixed length.
A unit:
u32 n frames
n frame headers voiced: 0x7f bytes (127 each) then a
byte < 0x7f, adding up to the pitch
period in samples; unvoiced: 0x80
bytes then a byte > 0x80, the length
is 128*(number of 0x80 - 1) + that byte
n x 6 bytes line-spectrum codebook indices
n float32 gains (the RMS of the frame's excitation)
for each voiced frame the first frame of a voiced run: 11
family A indices, the whole period;
each later one: 13 family B indices,
the change from the previous period
Unvoiced frames are noise. Unit 0 is empty; unit k+1 is senone k.
## TreeImage (big-endian)
A header with the path of the question file, then the questions (u32
count, then name\0 and a 64-bit mask each), then `\\...\TREE2\0`,
`tree\0`, u32 number of sounds n, n bytes (1: one state per sound), u32 n,
n u32 (where each sound's senones end, counted from n), u32 the number of
senones, then u32 total, 0, 18, 0xffffffff, the number of composite
questions q, then q pairs of 64-bit masks, 8 more bytes, and one tree per
sound.
A mask holds sound i at bit (i + 36) mod 64, and the four word positions at
bits 32-35: begins a word, ends one, is a whole word, is inside one. A
composite question (left, right) is true when the sound before is in
`left`, this sound's word position is in `left`, and the sound after is in
`right`.
A tree is u16 nodes, u16 leaves (nodes = 2*leaves - 1), then the nodes in
order, node 0 first:
inner node u16 yes, u16 no, 0xffff, u16 question..., 0xffff
leaf 0xffff, u16 k, u16 k
An inner node goes to `yes` when any of its questions is true. Leaf k of
sound s is senone (the senones of the sounds before s) + k.
PhoneFile lists the sounds in order, one per line (Sam: 52, Mike and
Mary: 58, with SILb and SILe for silence before and after).
`<voice>.tree` is the same in our own little-endian layout:
"MSSAMTR1", u32 sounds, u32 questions, u32 senones, u32 1
questions x (u64 left, u64 right) sound i at bit i, positions at 60-63
sounds x (char name[8], u32 first senone, u32 nodes, u32 first node)
u32 nodes, u32 question refs
nodes x (i32 yes, i32 no, u32 first ref, u32 refs) leaf: yes = -1, no = k
refs x u16 question index
## Senone
u32 count, then 28-byte records: the sound's name (4 bytes), u32 0, u32
the leaf number + 1, and four float32: the unit's mean length in ms, its
spread, and two energies.
## Cdb (`.tones`)
Text: pitch per tone, as `H (179) on: m=129= sd=34=; off: m=141= ...`, the
mean pitch in Hz where a vowel starts and ends. mssam uses `H` (accented),
`_` (plain), `h]` and `_]` (the last vowel of a phrase).
+36
View File
@@ -0,0 +1,36 @@
# SPDX-License-Identifier: GPL-2.0-or-later
# make build mssam
# make voices fetch the Microsoft Sam, Mike and Mary voice data (an 8 MB download)
# make install install the program and the voices
# make test speak a sentence with every voice
PREFIX ?= /usr/local
VOICEDIR ?= $(PREFIX)/share/mssam
CC ?= cc
CFLAGS ?= -O2 -Wall -Wextra
SOURCES ?= ../../sources/mssam
mssam: mssam.c lexicon.h
$(CC) $(CFLAGS) -DVOICEDIR='"$(VOICEDIR)"' -o $@ mssam.c -lm
voices: $(SOURCES)/sam.inv
$(SOURCES)/sam.inv:
python3 ../../tools/fetch-mssam.py $(SOURCES)
install: mssam voices
install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(VOICEDIR)
install -m 755 mssam $(DESTDIR)$(PREFIX)/bin/mssam
install -m 644 $(SOURCES)/*.inv $(SOURCES)/*.tree $(SOURCES)/*.tones $(DESTDIR)$(VOICEDIR)/
if [ -f $(SOURCES)/cmudict.dict ]; then install -m 644 $(SOURCES)/cmudict.dict $(DESTDIR)$(VOICEDIR)/; fi
test: mssam voices
@for v in sam mike mary; do \
./mssam -d $(SOURCES) -v $$v -o /tmp/mssam-$$v.wav \
"At the third stroke, it will be ten oh five and twenty seconds." && \
echo "/tmp/mssam-$$v.wav"; \
done
clean:
rm -f mssam
.PHONY: voices install test clean
+42
View File
@@ -0,0 +1,42 @@
# mssam
Our own synthesiser for the Microsoft Sam, Mike and Mary voices (Microsoft
Speech API 4, 1998). It reads the voices' data and speaks with it. No
Microsoft code is used or run, and none of Microsoft's files are in this
repository: `tools/fetch-mssam.py` downloads Microsoft's package at build
time and keeps only the voice data.
```sh
make # build mssam
make voices # fetch the voice data into ../../sources/mssam (8 MB download, needs cabextract or 7z)
make test # speak a sentence with each voice
sudo make install # /usr/local/bin/mssam and /usr/local/share/mssam
```
```
mssam [-d DIR] [-v sam|mike|mary] [-r RATE] [-p PITCH] [-o OUT.wav] TEXT...
```
`-d` is the folder with the voice data (default `/usr/local/share/mssam`,
or `$MSSAM_DIR`). `-r` and `-p` multiply the speed and pitch. Without `-o`
the WAV (22050 Hz, 16-bit mono) goes to standard output.
## How it speaks
1. The text becomes words (numbers and times like `11:05` are spelled out,
`a.m.` is two letters), and the words become sounds from the CMU
Pronouncing Dictionary: the clock's own words are built in
(`lexicon.h`), and `cmudict.dict` in the voice folder covers the rest.
Unknown words are spelled.
2. Each sound gets one of the voice's recorded units. The voice has a
decision tree for each sound, whose questions are about the sounds
either side and where the sound is in its word; the leaf it reaches is
the unit.
3. Each unit is a run of frames: a 20th-order spectrum (line spectral
frequencies) and a gain, with a pitch pulse for voiced frames and noise
for the others. The frames are played through the filter at a new pace
and with a new pitch: each vowel follows a tone from the voice's own
tone table (accented, plain, or falling at the end of a phrase), and the
sounds between vowels glide from one to the next.
docs/mssam-format.md describes the voice data.
+221
View File
@@ -0,0 +1,221 @@
/* Pronunciations for the words a speaking clock says, so that synth/mssam
* works without a dictionary file. Taken from the CMU Pronouncing
* Dictionary (cmudict.dict), whose licence follows:
*
* Copyright (C) 1993-2015 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* The contents of this file are deemed to be source code.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
* NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* sorted by word, for bsearch */
static const struct { const char *word, *phones; } lexicon[] = {
{"a", "AH0"},
{"accurate", "AE1 K Y ER0 AH0 T"},
{"after", "AE1 F T ER0"},
{"afternoon", "AE2 F T ER0 N UW1 N"},
{"am", "AE1 M"},
{"an", "AE1 N"},
{"and", "AH0 N D"},
{"april", "EY1 P R AH0 L"},
{"at", "AE1 T"},
{"august", "AA1 G AH0 S T"},
{"b", "B IY1"},
{"be", "B IY1"},
{"beep", "B IY1 P"},
{"by", "B AY1"},
{"c", "S IY1"},
{"calling", "K AO1 L IH0 NG"},
{"clock", "K L AA1 K"},
{"computer", "K AH0 M P Y UW1 T ER0"},
{"coordinated", "K OW0 AO1 R D AH0 N EY0 T IH0 D"},
{"d", "D IY1"},
{"daylight", "D EY1 L AY2 T"},
{"december", "D IH0 S EH1 M B ER0"},
{"e", "IY1"},
{"eight", "EY1 T"},
{"eighteen", "EY0 T IY1 N"},
{"eighteenth", "EY0 T IY1 N TH"},
{"eighth", "EY1 T TH"},
{"eighty", "EY1 T IY0"},
{"eleven", "IH0 L EH1 V AH0 N"},
{"eleventh", "IH0 L EH1 V AH0 N TH"},
{"evening", "IY1 V N IH0 NG"},
{"exactly", "IH0 G Z AE1 K T L IY0"},
{"f", "EH1 F"},
{"february", "F EH1 B Y AH0 W EH2 R IY0"},
{"fifteen", "F IH0 F T IY1 N"},
{"fifteenth", "F IH0 F T IY1 N TH"},
{"fifth", "F IH1 F TH"},
{"fifty", "F IH1 F T IY0"},
{"first", "F ER1 S T"},
{"five", "F AY1 V"},
{"for", "F AO1 R"},
{"forty", "F AO1 R T IY0"},
{"four", "F AO1 R"},
{"fourteen", "F AO1 R T IY1 N"},
{"fourteenth", "F AO1 R T IY1 N TH"},
{"fourth", "F AO1 R TH"},
{"friday", "F R AY1 D IY0"},
{"g", "JH IY1"},
{"good", "G UH1 D"},
{"greenwich", "G R EH1 N IH0 CH"},
{"h", "EY1 CH"},
{"half", "HH AE1 F"},
{"hear", "HH IY1 R"},
{"hello", "HH AH0 L OW1"},
{"here", "HH IY1 R"},
{"hour", "AW1 ER0"},
{"hours", "AW1 ER0 Z"},
{"how", "HH AW1"},
{"hundred", "HH AH1 N D R AH0 D"},
{"i", "AY1"},
{"is", "IH1 Z"},
{"it", "IH1 T"},
{"it's", "IH1 T S"},
{"its", "IH1 T S"},
{"j", "JH EY1"},
{"january", "JH AE1 N Y UW0 EH2 R IY0"},
{"july", "JH UW2 L AY1"},
{"june", "JH UW1 N"},
{"k", "K EY1"},
{"l", "EH1 L"},
{"local", "L OW1 K AH0 L"},
{"m", "EH1 M"},
{"march", "M AA1 R CH"},
{"mary", "M EH1 R IY0"},
{"may", "M EY1"},
{"me", "M IY1"},
{"mean", "M IY1 N"},
{"microsoft", "M AY1 K R OW2 S AO1 F T"},
{"midnight", "M IH1 D N AY2 T"},
{"mike", "M AY1 K"},
{"million", "M IH1 L Y AH0 N"},
{"minute", "M IH1 N AH0 T"},
{"minutes", "M IH1 N AH0 T S"},
{"monday", "M AH1 N D IY0"},
{"morning", "M AO1 R N IH0 NG"},
{"my", "M AY1"},
{"n", "EH1 N"},
{"name", "N EY1 M"},
{"next", "N EH1 K S T"},
{"night", "N AY1 T"},
{"nine", "N AY1 N"},
{"nineteen", "N AY1 N T IY1 N"},
{"nineteenth", "N AY1 N T IY1 N TH"},
{"ninety", "N AY1 N T IY0"},
{"ninth", "N AY1 N TH"},
{"no", "N OW1"},
{"noon", "N UW1 N"},
{"not", "N AA1 T"},
{"november", "N OW0 V EH1 M B ER0"},
{"now", "N AW1"},
{"o", "OW1"},
{"o'clock", "AH0 K L AA1 K"},
{"october", "AA0 K T OW1 B ER0"},
{"of", "AH1 V"},
{"oh", "OW1"},
{"on", "AA1 N"},
{"one", "W AH1 N"},
{"p", "P IY1"},
{"past", "P AE1 S T"},
{"please", "P L IY1 Z"},
{"pm", "P IY1 EH1 M"},
{"precisely", "P R IH0 S AY1 S L IY0"},
{"q", "K Y UW1"},
{"quarter", "K W AO1 R T ER0"},
{"r", "AA1 R"},
{"s", "EH1 S"},
{"sam", "S AE1 M"},
{"saturday", "S AE1 T ER0 D IY0"},
{"second", "S EH1 K AH0 N D"},
{"seconds", "S EH1 K AH0 N D Z"},
{"september", "S EH0 P T EH1 M B ER0"},
{"seven", "S EH1 V AH0 N"},
{"seventeen", "S EH1 V AH0 N T IY1 N"},
{"seventeenth", "S EH1 V AH0 N T IY1 N TH"},
{"seventh", "S EH1 V AH0 N TH"},
{"seventy", "S EH1 V AH0 N T IY0"},
{"signal", "S IH1 G N AH0 L"},
{"six", "S IH1 K S"},
{"sixteen", "S IH0 K S T IY1 N"},
{"sixteenth", "S IH0 K S T IY1 N TH"},
{"sixth", "S IH1 K S TH"},
{"sixty", "S IH1 K S T IY0"},
{"speaking", "S P IY1 K IH0 NG"},
{"speech", "S P IY1 CH"},
{"sponsored", "S P AA1 N S ER0 D"},
{"standard", "S T AE1 N D ER0 D"},
{"stroke", "S T R OW1 K"},
{"sunday", "S AH1 N D EY2"},
{"t", "T IY1"},
{"talking", "T AO1 K IH0 NG"},
{"ten", "T EH1 N"},
{"tenth", "T EH1 N TH"},
{"thank", "TH AE1 NG K"},
{"thanks", "TH AE1 NG K S"},
{"the", "DH AH0"},
{"there", "DH EH1 R"},
{"third", "TH ER1 D"},
{"thirteen", "TH ER1 T IY1 N"},
{"thirteenth", "TH ER1 T IY1 N TH"},
{"thirtieth", "TH ER1 T IY0 AH0 TH"},
{"thirty", "TH ER1 D IY2"},
{"this", "DH IH1 S"},
{"thousand", "TH AW1 Z AH0 N D"},
{"three", "TH R IY1"},
{"thursday", "TH ER1 Z D EY2"},
{"time", "T AY1 M"},
{"to", "T UW1"},
{"today", "T AH0 D EY1"},
{"tomorrow", "T AH0 M AA1 R OW2"},
{"tone", "T OW1 N"},
{"tuesday", "T UW1 Z D IY0"},
{"twelfth", "T W EH1 L F TH"},
{"twelve", "T W EH1 L V"},
{"twentieth", "T W EH1 N T IY0 AH0 TH"},
{"twenty", "T W EH1 N T IY0"},
{"two", "T UW1"},
{"u", "Y UW1"},
{"universal", "Y UW2 N AH0 V ER1 S AH0 L"},
{"v", "V IY1"},
{"voice", "V OY1 S"},
{"w", "D AH1 B AH0 L Y UW0"},
{"wednesday", "W EH1 N Z D IY0"},
{"welcome", "W EH1 L K AH0 M"},
{"what", "W AH1 T"},
{"when", "W EH1 N"},
{"where", "W EH1 R"},
{"who", "HH UW1"},
{"why", "W AY1"},
{"will", "W IH1 L"},
{"x", "EH1 K S"},
{"y", "W AY1"},
{"yes", "Y EH1 S"},
{"you", "Y UW1"},
{"z", "Z IY1"},
{"zero", "Z IH1 R OW0"},
{"zulu", "Z UW1 L UW2"},
};
+863
View File
@@ -0,0 +1,863 @@
/* SPDX-License-Identifier: GPL-2.0-or-later
*
* mssam: our own synthesiser for the Microsoft Sam, Mike and Mary voices.
*
* It reads the voice data (fetched by tools/fetch-mssam.py) and speaks with
* it: each sound of the text is given a recorded unit of the voice, picked
* by the voice's own context trees, and the units are joined with new pitch
* and timing. No Microsoft code is used or run. docs/mssam-format.md
* describes the data.
*
* mssam [-d DIR] [-v sam|mike|mary] [-r RATE] [-p PITCH] [-o OUT.wav] TEXT...
*
* RATE and PITCH are multipliers (1 is the voice's own). Without -o the
* WAV goes to standard output.
*/
#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lexicon.h"
#ifndef VOICEDIR
#define VOICEDIR "/usr/local/share/mssam"
#endif
#define ORDER 20 /* LPC order of all three voices */
#define MAXCB 16
#define MAXPH 64
static void die(const char *fmt, const char *arg)
{
fprintf(stderr, "mssam: ");
fprintf(stderr, fmt, arg);
fputc('\n', stderr);
exit(1);
}
static void *xmalloc(size_t n)
{
void *p = calloc(1, n ? n : 1);
if (!p)
die("%s", "out of memory");
return p;
}
static uint8_t *slurp(const char *path, size_t *len)
{
FILE *f = fopen(path, "rb");
uint8_t *d;
long n;
if (!f)
die("cannot open %s (run tools/fetch-mssam.py)", path);
fseek(f, 0, SEEK_END);
n = ftell(f);
fseek(f, 0, SEEK_SET);
d = xmalloc(n + 1);
if (fread(d, 1, n, f) != (size_t)n)
die("cannot read %s", path);
fclose(f);
*len = n;
return d;
}
static uint32_t le32(const uint8_t *p)
{
return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24;
}
static uint64_t le64(const uint8_t *p)
{
return le32(p) | (uint64_t)le32(p + 4) << 32;
}
static float lef(const uint8_t *p)
{
uint32_t u = le32(p);
float f;
memcpy(&f, &u, 4);
return f;
}
/* ---- the voice ---------------------------------------------------- */
struct table { int cnt, dim; const uint8_t *v; }; /* cnt vectors of dim floats */
struct node { int32_t yes, no; uint32_t q0, nq; };
struct phone { char name[9]; uint32_t first, nnodes, node0; };
static struct {
int rate, period; /* sample rate, points in a stored pitch period */
int nlsf, na, nb;
struct table lsf[MAXCB], cba[MAXCB], cbb[MAXCB];
uint32_t nunits;
const uint8_t *units; /* nunits+1 offsets, then the units */
const uint8_t *ubase;
size_t invlen;
int nph, nq;
struct phone ph[MAXPH];
const uint8_t *q; /* nq pairs of masks */
const uint8_t *nodes;
const uint8_t *qlist;
float tone[4][2]; /* pitch at the start and end of a vowel */
} V;
enum { T_ACCENT, T_PLAIN, T_LASTACCENT, T_LAST };
static const uint8_t *read_table(const uint8_t *p, struct table *t)
{
t->cnt = le32(p);
t->dim = le32(p + 4);
t->v = p + 8;
return p + 8 + 4 * t->cnt * t->dim;
}
static void load_inventory(const char *path)
{
const uint8_t *d = slurp(path, &V.invlen), *p;
int i, s;
V.rate = le32(d);
if (le32(d + 4) != ORDER)
die("%s: not a voice with 20 LPC coefficients", path);
V.nlsf = le32(d + 8);
V.na = le32(d + 12);
V.nb = le32(d + 16);
if (V.nlsf > MAXCB || V.na > MAXCB || V.nb > MAXCB)
die("%s: too many codebooks", path);
p = d + 28;
for (i = 0, s = 0; i < V.nlsf; i++) {
p = read_table(p, &V.lsf[i]);
s += V.lsf[i].dim;
}
if (s != ORDER)
die("%s: line spectrum codebooks do not add up", path);
for (i = 0, s = 0; i < V.na; i++) {
p = read_table(p, &V.cba[i]);
s += V.cba[i].dim;
}
V.period = s;
for (i = 0, s = 0; i < V.nb; i++) {
p = read_table(p, &V.cbb[i]);
s += V.cbb[i].dim;
}
if (s != V.period)
die("%s: excitation codebooks do not add up", path);
V.nunits = le32(p);
V.units = p + 8;
V.ubase = V.units + 4 * (V.nunits + 1);
}
static void load_tree(const char *path)
{
size_t len;
const uint8_t *d = slurp(path, &len), *p;
int i;
if (len < 24 || memcmp(d, "MSSAMTR1", 8))
die("%s: not a tree file from tools/fetch-mssam.py", path);
V.nph = le32(d + 8);
V.nq = le32(d + 12);
if (V.nph > MAXPH)
die("%s: too many sounds", path);
V.q = d + 24;
p = V.q + 16 * V.nq;
for (i = 0; i < V.nph; i++, p += 20) {
memcpy(V.ph[i].name, p, 8);
V.ph[i].first = le32(p + 8);
V.ph[i].nnodes = le32(p + 12);
V.ph[i].node0 = le32(p + 16);
}
V.nodes = p + 8;
V.qlist = V.nodes + 16 * le32(p);
}
/* The tone table: lines like "H (179) on: m=129= sd=34=; off: m=141= sd=21=" */
static void load_tones(const char *path)
{
static const char *names[4] = { "H", "_", "h]", "_]" };
static const float dflt[4][2] = { { 129, 141 }, { 112, 109 }, { 104, 86 }, { 92, 81 } };
FILE *f = fopen(path, "r");
char line[256], name[16];
float on, off;
int i;
memcpy(V.tone, dflt, sizeof(V.tone));
if (!f)
return;
while (fgets(line, sizeof(line), f))
if (sscanf(line, "%15s (%*d) on: m=%f= sd=%*f=; off: m=%f=", name, &on, &off) == 3)
for (i = 0; i < 4; i++)
if (!strcmp(name, names[i])) {
V.tone[i][0] = on;
V.tone[i][1] = off;
}
fclose(f);
}
static int phone_index(const char *name)
{
int i;
for (i = 0; i < V.nph; i++)
if (!strcmp(V.ph[i].name, name))
return i;
return -1;
}
/* ---- picking units ------------------------------------------------ */
enum { POS_BEGIN, POS_END, POS_SINGLE, POS_INSIDE };
/* the unit for sound p, at word position pos, between sounds l and r */
static int pick_unit(int p, int pos, int l, int r)
{
const struct phone *ph = &V.ph[p];
uint32_t k = 0, i;
if (!ph->nnodes)
return -1;
for (;;) {
const uint8_t *n = V.nodes + 16 * (ph->node0 + k);
int32_t yes = (int32_t)le32(n), no = (int32_t)le32(n + 4);
uint32_t q0 = le32(n + 8), nq = le32(n + 12);
int hit = 0;
if (yes < 0)
return ph->first + no + 1; /* unit 0 is not a sound */
for (i = 0; i < nq && !hit; i++) {
const uint8_t *q = V.q + 16 * (V.qlist[2 * (q0 + i)] | V.qlist[2 * (q0 + i) + 1] << 8);
uint64_t left = le64(q), right = le64(q + 8);
hit = (left >> l & 1) && (left >> (60 + pos) & 1) && (right >> r & 1);
}
k = hit ? (uint32_t)yes : (uint32_t)no;
if (k >= ph->nnodes)
return -1;
}
}
/* ---- decoding units ----------------------------------------------- */
struct frame {
int voiced, len, orig;
float gain, lsf[ORDER];
float *period; /* V.period points, for voiced frames */
};
/* Decode unit k into *out (a malloc'd array); returns the frame count. */
static int decode_unit(uint32_t k, struct frame **out)
{
uint32_t a, b, n, i, j, c;
const uint8_t *u, *end;
struct frame *f;
float *cur = NULL;
*out = NULL;
if (k >= V.nunits)
return 0;
a = le32(V.units + 4 * k);
b = le32(V.units + 4 * (k + 1));
if (b < a + 4 || V.ubase + b > (const uint8_t *)V.units + V.invlen)
return 0;
u = V.ubase + a;
end = V.ubase + b;
n = le32(u);
u += 4;
f = xmalloc(n * sizeof(*f));
/* frame headers: a voiced frame is its pitch period in samples, as
* 0x7f bytes (127 each) and a last byte below 0x7f; an unvoiced frame
* is 0x80 bytes and a last byte above 0x80, its length */
for (i = 0; i < n; i++) {
if (u >= end)
goto bad;
if (*u <= 0x7f) {
for (c = 0; *u == 0x7f; u++)
c++;
f[i].voiced = 1;
f[i].len = 127 * c + *u++;
} else {
for (c = 0; *u == 0x80; u++)
c++;
f[i].len = 128 * (c ? c - 1 : 0) + *u++;
}
}
/* then six line spectrum codebook indices per frame */
if (u + 10 * n > end)
goto bad;
for (i = 0; i < n; i++) {
int o = 0;
for (j = 0; j < (uint32_t)V.nlsf; j++) {
const struct table *t = &V.lsf[j];
int idx = u[6 * i + j] % t->cnt, d;
for (d = 0; d < t->dim; d++)
f[i].lsf[o++] = lef(t->v + 4 * (idx * t->dim + d));
}
}
u += 6 * n;
for (i = 0; i < n; i++)
f[i].gain = lef(u + 4 * i);
u += 4 * n;
/* then the excitation of each voiced frame: the first frame of a voiced
* run holds a whole pitch period (codebooks A), each later one holds the
* change from the frame before (codebooks B) */
for (i = 0; i < n; i++) {
const struct table *cb;
int ncb, o = 0, d;
float *per;
if (!f[i].voiced) {
cur = NULL;
continue;
}
cb = cur ? V.cbb : V.cba;
ncb = cur ? V.nb : V.na;
if (u + ncb > end)
goto bad;
per = xmalloc(V.period * sizeof(float));
if (cur)
memcpy(per, cur, V.period * sizeof(float));
for (j = 0; j < (uint32_t)ncb; j++) {
int idx = u[j] % cb[j].cnt;
for (d = 0; d < cb[j].dim; d++, o++)
per[o] += lef(cb[j].v + 4 * (idx * cb[j].dim + d));
}
u += ncb;
f[i].period = cur = per;
}
*out = f;
return n;
bad:
for (i = 0; i < n; i++)
free(f[i].period);
free(f);
return 0;
}
/* ---- text to sounds ----------------------------------------------- */
struct sound {
int ph, pos, vowel; /* vowel: 0, or 1 + the tone */
int pause; /* > 0: a pause of this many ms instead of a sound */
};
static struct sound snd[4096];
static int nsnd;
/* cmudict.dict, if there is one: its lines, sorted by word */
static char **dict;
static size_t ndict;
static int wordcmp(const char *a, const char *b)
{
for (; *a && *a != ' ' && *a == *b; a++, b++)
;
return (unsigned char)(*a == ' ' ? 0 : *a) - (unsigned char)(*b == ' ' ? 0 : *b);
}
static int linecmp(const void *a, const void *b)
{
return wordcmp(*(char *const *)a, *(char *const *)b);
}
static void load_dict(const char *path)
{
size_t len, i, n = 0;
char *d = (char *)slurp(path, &len), *p;
for (i = 0; i < len; i++)
n += d[i] == '\n';
dict = xmalloc((n + 1) * sizeof(char *));
for (p = strtok(d, "\n"); p; p = strtok(NULL, "\n")) {
char *sp = strchr(p, ' '), *hash = strchr(p, '#');
if (!sp || p[0] == ';' || ndict > n)
continue;
if (hash)
*hash = 0; /* a comment */
if (sp > p && sp[-1] == ')')
continue; /* other pronunciations: word(2) */
dict[ndict++] = p;
}
qsort(dict, ndict, sizeof(char *), linecmp);
}
static const char *dict_lookup(const char *w)
{
size_t lo = 0, hi = ndict;
while (lo < hi) {
size_t mid = (lo + hi) / 2;
int c = wordcmp(dict[mid], w);
if (!c)
return strchr(dict[mid], ' ') + 1;
if (c < 0)
lo = mid + 1;
else
hi = mid;
}
return NULL;
}
static int lexcmp(const void *a, const void *b)
{
return strcmp(a, *(const char *const *)b);
}
static const char *letters[26] = {
"EY1", "B IY1", "S IY1", "D IY1", "IY1", "EH1 F", "JH IY1", "EY1 CH", "AY1",
"JH EY1", "K EY1", "EH1 L", "EH1 M", "EH1 N", "OW1", "P IY1", "K Y UW1",
"AA1 R", "EH1 S", "T IY1", "Y UW1", "V IY1", "D AH1 B AH0 L Y UW0",
"EH1 K S", "W AY1", "Z IY1",
};
static const char *pronounce(const char *w)
{
const void *e = bsearch(w, lexicon, sizeof(lexicon) / sizeof(lexicon[0]),
sizeof(lexicon[0]), lexcmp);
if (e)
return ((const char *const *)e)[1];
return dict_lookup(w);
}
static int content_word(const char *w)
{
static const char *fn[] = { "a", "an", "and", "at", "be", "by", "for", "in", "is", "it",
"it's", "its", "of", "on", "or", "the", "to", "will", NULL };
int i;
for (i = 0; fn[i]; i++)
if (!strcmp(w, fn[i]))
return 0;
return 1;
}
static void add_pause(int ms)
{
if (nsnd && snd[nsnd - 1].pause)
snd[nsnd - 1].pause = ms > snd[nsnd - 1].pause ? ms : snd[nsnd - 1].pause;
else if (nsnd < (int)(sizeof(snd) / sizeof(snd[0])))
snd[nsnd++] = (struct sound){ .ph = -1, .pause = ms };
}
/* The sounds of one word, from its phones ("AE1 T"). */
static void add_word(const char *w, const char *phones, int content)
{
char buf[256], *t, *save;
int first = nsnd;
snprintf(buf, sizeof(buf), "%s", phones);
for (t = strtok_r(buf, " \t\r\n", &save); t; t = strtok_r(NULL, " \t\r\n", &save)) {
char name[16];
size_t l = strlen(t);
int stress = -1, p;
if (l >= sizeof(name) - 2 || nsnd >= (int)(sizeof(snd) / sizeof(snd[0])))
break;
memcpy(name, t, l + 1);
if (isdigit((unsigned char)name[l - 1])) {
stress = name[l - 1] - '0';
name[l - 1] = stress ? '1' : '0'; /* the voices have stress 1 and 0 */
}
p = phone_index(name);
if (p < 0 && stress >= 0) {
name[l - 1] = '1';
p = phone_index(name);
}
if (p < 0)
continue;
snd[nsnd++] = (struct sound){ .ph = p,
.vowel = stress < 0 ? 0 : 1 + (stress && content ? T_ACCENT : T_PLAIN) };
}
(void)w;
for (int i = first; i < nsnd; i++)
snd[i].pos = nsnd - first == 1 ? POS_SINGLE : i == first ? POS_BEGIN :
i == nsnd - 1 ? POS_END : POS_INSIDE;
}
static void say_word(const char *w)
{
const char *ph = pronounce(w);
char one[2] = { 0, 0 };
if (ph) {
add_word(w, ph, content_word(w));
return;
}
/* not known: spell it */
for (; *w; w++)
if (*w >= 'a' && *w <= 'z') {
one[0] = *w;
add_word(one, letters[*w - 'a'], 1);
}
}
static void say_number(long n, char *out, size_t sz);
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[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety" };
static void say_number(long n, char *out, size_t sz)
{
size_t l = strlen(out);
if (n >= 1000000) {
say_number(n / 1000000, out, sz);
l = strlen(out);
snprintf(out + l, sz - l, " million");
if (n % 1000000)
say_number(n % 1000000, out, sz);
} else if (n >= 1000) {
say_number(n / 1000, out, sz);
l = strlen(out);
snprintf(out + l, sz - l, " thousand");
if (n % 1000)
say_number(n % 1000, out, sz);
} else if (n >= 100) {
snprintf(out + l, sz - l, " %s hundred", ones[n / 100]);
if (n % 100) {
l = strlen(out);
snprintf(out + l, sz - l, " and");
say_number(n % 100, out, sz);
}
} else if (n >= 20) {
snprintf(out + l, sz - l, " %s", tens[n / 10]);
if (n % 10)
say_number(n % 10, out, sz);
} else {
snprintf(out + l, sz - l, " %s", ones[n]);
}
}
/* Mark the end of a phrase: its last vowel falls. */
static void end_phrase(int from)
{
int i;
for (i = nsnd - 1; i >= from; i--)
if (snd[i].vowel) {
snd[i].vowel = 1 + (snd[i].vowel == 1 + T_ACCENT ? T_LASTACCENT : T_LAST);
break;
}
}
static void parse_text(const char *text)
{
char word[64], words[512];
const char *s = text;
int phrase = 0;
add_pause(120);
while (*s) {
size_t l = 0;
if (isdigit((unsigned char)*s)) {
/* a number; after a ':' a minute ("05" is "oh five") */
long n = 0;
int digits = 0, minute = s > text && s[-1] == ':';
while (isdigit((unsigned char)*s) && digits < 9)
n = n * 10 + (*s++ - '0'), digits++;
words[0] = 0;
if (minute && n == 0)
snprintf(words, sizeof(words), " hundred");
else if (minute && n < 10)
snprintf(words, sizeof(words), " oh %s", ones[n]);
else
say_number(n, words, sizeof(words));
for (char *t = strtok(words, " "); t; t = strtok(NULL, " "))
say_word(t);
continue;
}
if (isalpha((unsigned char)*s)) {
while ((isalpha((unsigned char)*s) || *s == '\'') && l < sizeof(word) - 1)
word[l++] = tolower((unsigned char)*s++);
word[l] = 0;
/* "a.m.", "p.m." and the like: letters */
if (l == 1 && *s == '.' && isalpha((unsigned char)s[1]) && s[2] == '.') {
say_word(word);
word[0] = tolower((unsigned char)s[1]);
s += 3;
add_word(word, letters[word[0] - 'a'], 1);
continue;
}
if (l == 1 && word[0] != 'a' && word[0] != 'i')
add_word(word, letters[word[0] - 'a'], 1);
else
say_word(word);
continue;
}
if (strchr(",;:", *s) && !(*s == ':' && isdigit((unsigned char)s[1]))) {
end_phrase(phrase);
add_pause(180);
phrase = nsnd;
} else if (strchr(".!?", *s)) {
end_phrase(phrase);
add_pause(350);
phrase = nsnd;
}
s++;
}
end_phrase(phrase);
add_pause(120);
}
/* ---- speaking ----------------------------------------------------- */
static void lsf_to_lpc(const float *lsf, double *a)
{
double p[ORDER + 2] = { 1 }, q[ORDER + 2] = { 1 };
int np = 1, nq = 1, i, j;
for (i = 0; i < ORDER; i++) {
double c = -2 * cos(2 * M_PI * lsf[i]), *v = i % 2 ? q : p;
int *n = i % 2 ? &nq : &np;
for (j = *n + 1; j >= 1; j--)
v[j] += c * v[j - 1] + (j >= 2 ? v[j - 2] : 0);
*n += 2;
}
/* p *= (1 + z^-1), q *= (1 - z^-1) */
for (j = np; j >= 1; j--)
p[j] += p[j - 1];
for (j = nq; j >= 1; j--)
q[j] -= q[j - 1];
for (i = 0; i <= ORDER; i++)
a[i] = 0.5 * (p[i] + q[i]);
}
static unsigned rng = 1;
static double noise(void)
{
/* sum of uniforms: near enough to Gaussian for frication */
double s = 0;
int i;
for (i = 0; i < 4; i++) {
rng = rng * 1103515245 + 12345;
s += (rng >> 8 & 0xffff) / 65536.0 - 0.5;
}
return s * 1.732;
}
static float *out;
static size_t nout, aout;
static void emit(double v)
{
if (nout == aout) {
aout = aout ? 2 * aout : 1 << 16;
out = realloc(out, aout * sizeof(*out));
if (!out)
die("%s", "out of memory");
}
out[nout++] = v;
}
static void render(double rate, double pitch)
{
static double mem[ORDER];
double a[ORDER + 1], *e = NULL;
int i, j, k, ne = 0;
for (i = 0; i < nsnd; i++) {
struct frame *f;
double f0a, f0b, total, t, *src;
int n, l, r, unit, prev, next;
if (snd[i].pause) {
for (k = 0; k < snd[i].pause * V.rate / 1000; k++)
emit(0);
memset(mem, 0, sizeof(mem));
continue;
}
/* the sounds either side; a pause counts as silence */
l = i > 0 && !snd[i - 1].pause ? snd[i - 1].ph : -1;
r = i + 1 < nsnd && !snd[i + 1].pause ? snd[i + 1].ph : -1;
if (l < 0)
l = phone_index("SILb") >= 0 ? phone_index("SILb") : phone_index("SIL");
if (r < 0)
r = phone_index("SILe") >= 0 ? phone_index("SILe") : phone_index("SIL");
unit = pick_unit(snd[i].ph, snd[i].pos, l < 0 ? 0 : l, r < 0 ? 0 : r);
n = unit < 0 ? 0 : decode_unit(unit, &f);
if (!n)
continue;
/* pitch: a vowel goes from its tone's start to its end; the
* sounds between vowels glide from one to the next */
for (prev = i - 1; prev >= 0 && !snd[prev].pause && !snd[prev].vowel; prev--)
;
for (next = i + 1; next < nsnd && !snd[next].pause && !snd[next].vowel; next++)
;
if (snd[i].vowel) {
f0a = V.tone[snd[i].vowel - 1][0];
f0b = V.tone[snd[i].vowel - 1][1];
} else {
int pv = prev >= 0 && snd[prev].vowel, nv = next < nsnd && snd[next].vowel;
f0a = pv ? V.tone[snd[prev].vowel - 1][1] : nv ? V.tone[snd[next].vowel - 1][0] : 110;
f0b = nv ? V.tone[snd[next].vowel - 1][0] : f0a;
}
/* new timing: step through the unit's frames at the new rate */
src = xmalloc((n + 1) * sizeof(double));
for (k = 0; k < n; k++)
src[k + 1] = src[k] + f[k].len;
total = src[n] / rate;
for (t = 0; t < total;) {
struct frame *s;
int len, L0;
double g, sum = 0;
for (k = 0; k < n - 1 && src[k + 1] <= t * rate; k++)
;
s = &f[k];
L0 = s->len;
len = s->voiced ? (int)lrint(V.rate / ((f0a + (f0b - f0a) * t / total) * pitch)) : L0;
if (len < 20)
len = 20;
if (ne < (L0 > len ? L0 : len)) {
ne = L0 > len ? L0 : len;
e = realloc(e, ne * sizeof(double));
}
if (s->voiced && s->period) {
/* the stored period is scaled to V.period points:
* stretch it back to its recorded length, then cut
* or pad it to the new period */
for (k = 0; k < L0; k++) {
double x = L0 > 1 ? (double)k * (V.period - 1) / (L0 - 1) : 0;
int x0 = (int)x;
double fr = x - x0;
e[k] = s->period[x0] * (1 - fr) + (x0 + 1 < V.period ? s->period[x0 + 1] * fr : 0);
sum += e[k] * e[k];
}
for (; k < len; k++)
e[k] = 0;
g = s->gain / (sqrt(sum / L0) + 1e-9);
} else {
for (k = 0; k < len; k++) {
e[k] = noise();
sum += e[k] * e[k];
}
g = s->gain / (sqrt(sum / len) + 1e-9);
}
lsf_to_lpc(s->lsf, a);
for (k = 0; k < len; k++) {
double y = e[k] * g;
for (j = 0; j < ORDER; j++)
y -= a[j + 1] * mem[j];
memmove(mem + 1, mem, (ORDER - 1) * sizeof(double));
mem[0] = y;
emit(y);
}
t += len;
}
free(src);
for (k = 0; k < n; k++)
free(f[k].period);
free(f);
}
free(e);
}
static void put32(FILE *f, uint32_t v)
{
uint8_t b[4] = { v, v >> 8, v >> 16, v >> 24 };
fwrite(b, 1, 4, f);
}
static void put16(FILE *f, uint16_t v)
{
uint8_t b[2] = { v, v >> 8 };
fwrite(b, 1, 2, f);
}
static void write_wav(FILE *f)
{
double peak = 1e-9;
size_t i;
for (i = 0; i < nout; i++)
if (fabs(out[i]) > peak)
peak = fabs(out[i]);
fwrite("RIFF", 1, 4, f);
put32(f, 36 + 2 * nout);
fwrite("WAVEfmt ", 1, 8, f);
put32(f, 16);
put16(f, 1);
put16(f, 1);
put32(f, V.rate);
put32(f, 2 * V.rate);
put16(f, 2);
put16(f, 16);
fwrite("data", 1, 4, f);
put32(f, 2 * nout);
for (i = 0; i < nout; i++)
put16(f, (uint16_t)(int16_t)lrint(out[i] / peak * 26000));
}
static void usage(void)
{
fprintf(stderr, "usage: mssam [-d DIR] [-v sam|mike|mary] [-r RATE] [-p PITCH] [-o OUT.wav] TEXT...\n"
" DIR holds the voice data from tools/fetch-mssam.py (default %s)\n", VOICEDIR);
exit(2);
}
int main(int argc, char **argv)
{
const char *dir = getenv("MSSAM_DIR") ? getenv("MSSAM_DIR") : VOICEDIR;
const char *voice = "sam", *outp = NULL;
double rate = 0.82, pitch = 0.93; /* Sam's pace and pitch */
char path[4096], text[8192] = "";
int i;
FILE *f;
for (i = 1; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
char opt = argv[i][1];
if (opt == '-') {
i++;
break;
}
if (strchr("dvrpo", opt) && i + 1 >= argc)
usage();
switch (opt) {
case 'd': dir = argv[++i]; break;
case 'v': voice = argv[++i]; break;
case 'r': rate *= atof(argv[++i]); break;
case 'p': pitch *= atof(argv[++i]); break;
case 'o': outp = argv[++i]; break;
default: usage();
}
}
if (i >= argc || rate <= 0.05 || pitch <= 0.05)
usage();
for (; i < argc; i++) {
strncat(text, argv[i], sizeof(text) - strlen(text) - 2);
strcat(text, " ");
}
if (strcmp(voice, "sam") && strcmp(voice, "mike") && strcmp(voice, "mary"))
die("unknown voice %s (sam, mike or mary)", voice);
if (strcmp(voice, "sam"))
rate /= 0.82, pitch /= 0.93;
snprintf(path, sizeof(path), "%s/%s.inv", dir, voice);
load_inventory(path);
snprintf(path, sizeof(path), "%s/%s.tree", dir, voice);
load_tree(path);
snprintf(path, sizeof(path), "%s/%s.tones", dir, voice);
load_tones(path);
snprintf(path, sizeof(path), "%s/cmudict.dict", dir);
if ((f = fopen(path, "rb"))) {
fclose(f);
load_dict(path);
}
parse_text(text);
render(rate, pitch);
f = outp ? fopen(outp, "wb") : stdout;
if (!f)
die("cannot write %s", outp);
write_wav(f);
if (outp && fclose(f))
die("cannot write %s", outp);
return 0;
}
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""SPDX-License-Identifier: GPL-2.0-or-later
Fetch the Microsoft Sam, Mike and Mary voice data for synth/mssam at build
time.
Microsoft's files are not in this repository. This script downloads the
Microsoft Speech API 4 text-to-speech package (msttsl.exe) from the
Internet Archive, checks its SHA-256, unpacks its cabinet with cabextract
or 7z, reads each voice file (an OLE compound file) and writes the parts
synth/mssam uses as plain files:
OUT/<voice>.inv the voice's recorded sound units, as stored
OUT/<voice>.tree the trees that pick a unit for each sound in its
context, rewritten in our own simple layout
OUT/<voice>.tones the voice's pitch table (plain text)
OUT/cmudict.dict the CMU Pronouncing Dictionary, so that words a
clock does not usually say can be spoken too
(optional: synth/mssam knows the clock's words)
The voices are sam, mike and mary (the files sam.vce, male.vce and
female.vce). The layouts are described in docs/mssam-format.md.
Only data is read. Nothing from the package is run, and Microsoft's
programs in it (msttssyn.dll and the rest) are not kept.
Usage: tools/fetch-mssam.py [OUT] (default: sources/mssam)
tools/fetch-mssam.py --exe msttsl.exe [OUT]
Needs Python 3 and cabextract or 7z.
"""
import hashlib
import os
import shutil
import struct
import subprocess
import sys
import tempfile
import urllib.request
URL = "https://archive.org/download/msttsl/msttsl.exe"
SHA1 = "d988cbb3e99bc9dd850defda939c06b81d9d4544"
CMUDICT = "https://raw.githubusercontent.com/cmusphinx/cmudict/master/cmudict.dict"
VOICES = {"sam": "sam.vce", "mike": "male.vce", "mary": "female.vce"}
POSITIONS = 4 # word positions: begins, ends, single, inside
class Compound:
"""Just enough of an OLE compound file reader to get streams out."""
def __init__(self, data):
if data[:8] != bytes.fromhex("d0cf11e0a1b11ae1"):
raise ValueError("not an OLE compound file")
self.d = data
self.ss = 1 << struct.unpack("<H", data[30:32])[0]
self.mss = 1 << struct.unpack("<H", data[32:34])[0]
nfat, dir0 = struct.unpack("<II", data[44:52])
self.cutoff, mfat0, nmfat, difat0, ndifat = struct.unpack("<5I", data[56:76])
difat = list(struct.unpack("<109I", data[76:512]))
s = difat0
for _ in range(ndifat):
v = struct.unpack("<%dI" % (self.ss // 4), self.sector(s))
difat += v[:-1]
s = v[-1]
self.fat = []
for s in difat[:nfat]:
self.fat += struct.unpack("<%dI" % (self.ss // 4), self.sector(s))
self.minifat = []
if nmfat:
m = self.chain(mfat0)
self.minifat = list(struct.unpack("<%dI" % (len(m) // 4), m))
dirs = self.chain(dir0)
self.entries = {}
for i in range(0, len(dirs), 128):
e = dirs[i:i + 128]
nlen = struct.unpack("<H", e[64:66])[0]
if nlen < 2:
continue
name = e[:nlen - 2].decode("utf-16-le")
start, size = struct.unpack("<II", e[116:124])
self.entries[name] = (e[66], start, size)
if e[66] == 5:
self.ministream = self.chain(start)[:size]
def sector(self, s):
o = (s + 1) * self.ss
return self.d[o:o + self.ss]
def chain(self, s):
out = []
while s < 0xFFFFFFFA:
out.append(self.sector(s))
s = self.fat[s]
return b"".join(out)
def stream(self, name):
typ, start, size = self.entries[name]
if size >= self.cutoff:
return self.chain(start)[:size]
out = []
s = start
while s < 0xFFFFFFFA:
out.append(self.ministream[s * self.mss:(s + 1) * self.mss])
s = self.minifat[s]
return b"".join(out)[:size]
def rotate(m):
"""The voice stores a set of sounds as a 64-bit mask with sound i at bit
(i + 36) mod 64 and the four word positions at bits 32-35. Ours has
sound i at bit i and the word positions at bits 60-63."""
return ((m >> 36) | (m << 28)) & 0xFFFFFFFFFFFFFFFF
def u32(d, o):
return struct.unpack(">I", d[o:o + 4])[0]
def u16(d, o):
return struct.unpack(">H", d[o:o + 2])[0]
def parse_trees(d, o, count):
"""count trees of nodes; returns [(leaves, nodes)] and the end offset.
Node: yes, no, 0xffff, then the indices of its questions, 0xffff.
Leaf: 0xffff, n, n."""
out = []
for _ in range(count):
nn, nl = u16(d, o), u16(d, o + 2)
o += 4
if nn != max(2 * nl - 1, 0):
raise ValueError("tree header")
nodes = []
for _ in range(nn):
x = u16(d, o)
if x == 0xFFFF:
a, b = u16(d, o + 2), u16(d, o + 4)
o += 6
if a != b or a >= nl:
raise ValueError("leaf")
nodes.append((-1, a, []))
else:
y = u16(d, o + 2)
if u16(d, o + 4) != 0xFFFF or x >= nn or y >= nn:
raise ValueError("node")
o += 6
q = []
while u16(d, o) != 0xFFFF:
q.append(u16(d, o))
o += 2
o += 2
nodes.append((x, y, q))
out.append((nl, nodes))
return out, o
def convert_tree(tree, phonefile):
phones = [l.split()[0] for l in phonefile.decode("latin-1").splitlines() if l.strip()]
n = len(phones)
o = tree.index(b"tree\0") + 5
if u32(tree, o) != n:
raise ValueError("phone count")
o += 4 + n # one byte per sound: its number of states (always 1)
o += 4 + 4 * n # sound count again, then where each sound's senones end
total = u32(tree, o)
# then: total, 0, 18, 0xffffffff, the number of questions
o += 4
while u32(tree, o) != 0xFFFFFFFF:
o += 4
nq = u32(tree, o + 4)
o += 8
questions = [struct.unpack(">QQ", tree[o + 16 * i:o + 16 * i + 16]) for i in range(nq)]
o += 16 * nq + 8
trees, end = parse_trees(tree, o, n)
if end != len(tree) or sum(t[0] for t in trees) != total:
raise ValueError("trees do not add up")
out = [b"MSSAMTR1", struct.pack("<4I", n, nq, total, 1)]
for left, right in questions:
out.append(struct.pack("<QQ", rotate(left), rotate(right)))
first = 0
nodes = []
qlist = []
for name, (nl, tn) in zip(phones, trees):
out.append(struct.pack("<8sIII", name.encode()[:8], first, len(tn), len(nodes)))
for yes, no, q in tn:
nodes.append(struct.pack("<iiII", yes, no, len(qlist), len(q)))
qlist += q
first += nl
out.append(struct.pack("<II", len(nodes), len(qlist)))
out += nodes
out.append(struct.pack("<%dH" % len(qlist), *qlist))
return b"".join(out)
def unpack(exe, tmp):
for cmd in (["cabextract", "-q", "-d", tmp, exe], ["7z", "x", "-y", "-o" + tmp, exe]):
if shutil.which(cmd[0]):
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
return
sys.exit("fetch-mssam: needs cabextract or 7z to unpack msttsl.exe")
def main():
args = sys.argv[1:]
exe = None
if args[:1] == ["--exe"]:
exe, args = args[1], args[2:]
out = args[0] if args else "sources/mssam"
os.makedirs(out, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
if not exe:
exe = os.path.join(tmp, "msttsl.exe")
print("fetch-mssam: downloading", URL)
urllib.request.urlretrieve(URL, exe)
if hashlib.sha1(open(exe, "rb").read()).hexdigest() != SHA1:
sys.exit("fetch-mssam: msttsl.exe does not match the expected checksum")
unpack(exe, tmp)
files = {f.lower(): os.path.join(tmp, f) for f in os.listdir(tmp)}
for voice, vce in VOICES.items():
c = Compound(open(files[vce], "rb").read())
with open(os.path.join(out, voice + ".inv"), "wb") as f:
f.write(c.stream("Inventory"))
with open(os.path.join(out, voice + ".tree"), "wb") as f:
f.write(convert_tree(c.stream("TreeImage"), c.stream("PhoneFile")))
with open(os.path.join(out, voice + ".tones"), "wb") as f:
f.write(c.stream("Cdb"))
print("fetch-mssam: wrote", voice)
dic = os.path.join(out, "cmudict.dict")
if not os.path.exists(dic):
try:
urllib.request.urlretrieve(CMUDICT, dic + ".tmp")
os.replace(dic + ".tmp", dic)
print("fetch-mssam: wrote cmudict.dict")
except OSError as e:
print("fetch-mssam: no cmudict.dict (%s); only the clock's own words will be known" % e)
if __name__ == "__main__":
main()
+32 -6
View File
@@ -12,8 +12,9 @@ Usage: tools/synth_voices.py OUT VOICE... (OUT is normally ./voices)
--live writes a live voice instead (mode=tts, live-<engine>-<voice>): no
clips, the module runs the synthesiser on the Asterisk machine for each
sentence as it is needed (dectalk and sam only; tts_program_dectalk and
tts_program_sam in speakingclock.conf say where they are).
sentence as it is needed (dectalk, sam and mssam only; tts_program_dectalk,
tts_program_sam and tts_program_mssam in speakingclock.conf say where they
are).
Engines (a VOICE is engine:name, see --list):
sapi4 Microsoft Speech API 4 voices (Microsoft Sam, Mike, Mary,
@@ -24,6 +25,9 @@ Engines (a VOICE is engine:name, see --list):
branch). $DECTALK_SAY is its `say` program.
sam Software Automatic Mouth (C64, 1982), the C port at
https://github.com/s-macke/SAM. $SAM is its `sam` program.
mssam Microsoft Sam, Mike and Mary, spoken by our own synthesiser
(synth/mssam) from the voice data that tools/fetch-mssam.py
fetches. $MSSAM is its `mssam` program.
mac MacInTalk / PlainTalk voices, with macOS's own `say` (run this
on a Mac).
@@ -181,6 +185,18 @@ def sam(vid, text, out):
check=True, stdout=subprocess.DEVNULL)
MSSAM = {
"sam": ("Microsoft Sam", "Microsoft Speech API 4 voice Sam"),
"mike": ("Microsoft Mike", "Microsoft Speech API 4 voice Mike"),
"mary": ("Microsoft Mary", "Microsoft Speech API 4 voice Mary"),
}
def mssam(vid, text, out):
prog = os.environ.get("MSSAM", "mssam")
subprocess.run([prog, "-v", vid, "-o", out, text], check=True)
def mac_check(vid):
have = subprocess.run(["say", "-v", "?"], capture_output=True, text=True).stdout
if not any(line.split(" ")[0].strip() == vid for line in have.splitlines()):
@@ -201,6 +217,9 @@ ENGINES = {
"DECtalk (Digital Equipment Corp.), https://github.com/dectalk/dectalk"),
"sam": (sam, SAM, lambda v: (SAM[v][4], "Software Automatic Mouth (Commodore 64, 1982)"),
"SAM, Don't Ask Software (now SoftVoice, Inc.), C port https://github.com/s-macke/SAM"),
"mssam": (mssam, MSSAM, lambda v: (MSSAM[v][0], "%s, by our own synthesiser" % MSSAM[v][1]),
"synth/mssam (this repository, clean-room) reading Microsoft's Speech API 4 voice data "
"(msttsl.exe), fetched by tools/fetch-mssam.py"),
"mac": (mac, MAC, lambda v: ("%s %s" % (MAC[v], v),
"Apple PlainTalk (MacinTalk Pro) voice" if MAC[v] == "PlainTalk"
else "Apple MacInTalk 3 voice"),
@@ -245,6 +264,9 @@ def build_live(out_dir, engine, vid):
if engine == "dectalk":
how = 'command={program:dectalk} -fo {out} -a "[:%s] {text}"' % DECTALK[vid][0]
by = "DECtalk's say, run here (tts_program_dectalk)"
elif engine == "mssam":
how = 'command={program:mssam} -v %s -o {out} "{text}"' % vid
by = "synth/mssam, run here (tts_program_mssam)"
else:
speed, pitch, mouth, throat = SAM[vid][:4]
how = ("command={program:sam} -wav {out} -speed %d -pitch %d -mouth %d -throat %d \"{text}\""
@@ -257,11 +279,15 @@ def build_live(out_dir, engine, vid):
f.write("; Live voice for app_speakingclock (docs/voice-format.md), made by\n"
"; tools/synth_voices.py --live %s:%s. Each sentence is spoken when\n"
"; it is needed, by %s.\n"
"; The synthesiser belongs to its owners; see NOTICE.md.\n\n"
"%s\n\n"
"[voice]\nname=%s, live\ndescription=%s, spoken live\n"
"mode=tts\nsequence=speech+pips\nperiod=10\n\n[tts]\n%s\ntext=%s\n"
"\n[source]\nengine=%s\nvoice=%s\nsynthesiser=%s\n"
% (engine, vid, by, name, desc, how, text, engine, vid, ENGINES[engine][3]))
% (engine, vid, by,
"; The synthesiser is ours; the voice data it reads is Microsoft's and is\n"
"; not in this repository (tools/fetch-mssam.py downloads it); see NOTICE.md."
if engine == "mssam" else "; The synthesiser belongs to its owners; see NOTICE.md.",
name, desc, how, text, engine, vid, ENGINES[engine][3]))
assert vid in table
print(d)
@@ -270,8 +296,8 @@ def main():
if len(sys.argv) > 2 and sys.argv[1] == "--live":
for spec in sys.argv[3:]:
engine, _, vid = spec.partition(":")
if engine not in ("dectalk", "sam") or vid not in ENGINES[engine][1]:
sys.exit("--live takes dectalk and sam voices (see --list)")
if engine not in ("dectalk", "sam", "mssam") or vid not in ENGINES[engine][1]:
sys.exit("--live takes dectalk, sam and mssam voices (see --list)")
build_live(sys.argv[2], engine, vid)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from voice_index import write_index
+3
View File
@@ -50,6 +50,9 @@ Written by tools/voice_index.py. Every recording belongs to its original owner (
| `live-dectalk-rita` | DECtalk Rough Rita, live | tts | dectalk synthesiser |
| `live-dectalk-ursula` | DECtalk Uppity Ursula, live | tts | dectalk synthesiser |
| `live-dectalk-wendy` | DECtalk Whispering Wendy, live | tts | dectalk synthesiser |
| `live-mssam-mary` | Microsoft Mary, live | tts | mssam synthesiser |
| `live-mssam-mike` | Microsoft Mike, live | tts | mssam synthesiser |
| `live-mssam-sam` | Microsoft Sam, live | tts | mssam synthesiser |
| `live-sam-elf` | SAM Elf, live | tts | sam synthesiser |
| `live-sam-extra-terrestrial` | SAM Extra-Terrestrial, live | tts | sam synthesiser |
| `live-sam-little-old-lady` | SAM Little Old Lady, live | tts | sam synthesiser |
+21
View File
@@ -0,0 +1,21 @@
; Live voice for app_speakingclock (docs/voice-format.md), made by
; tools/synth_voices.py --live mssam:mary. Each sentence is spoken when
; it is needed, by synth/mssam, run here (tts_program_mssam).
; The synthesiser is ours; the voice data it reads is Microsoft's and is
; not in this repository (tools/fetch-mssam.py downloads it); see NOTICE.md.
[voice]
name=Microsoft Mary, live
description=Microsoft Speech API 4 voice Mary, by our own synthesiser, spoken live
mode=tts
sequence=speech+pips
period=10
[tts]
command={program:mssam} -v mary -o {out} "{text}"
text=At the third stroke, it will be {hour} {minute} {seconds}.
[source]
engine=mssam
voice=mary
synthesiser=synth/mssam (this repository, clean-room) reading Microsoft's Speech API 4 voice data (msttsl.exe), fetched by tools/fetch-mssam.py
+21
View File
@@ -0,0 +1,21 @@
; Live voice for app_speakingclock (docs/voice-format.md), made by
; tools/synth_voices.py --live mssam:mike. Each sentence is spoken when
; it is needed, by synth/mssam, run here (tts_program_mssam).
; The synthesiser is ours; the voice data it reads is Microsoft's and is
; not in this repository (tools/fetch-mssam.py downloads it); see NOTICE.md.
[voice]
name=Microsoft Mike, live
description=Microsoft Speech API 4 voice Mike, by our own synthesiser, spoken live
mode=tts
sequence=speech+pips
period=10
[tts]
command={program:mssam} -v mike -o {out} "{text}"
text=At the third stroke, it will be {hour} {minute} {seconds}.
[source]
engine=mssam
voice=mike
synthesiser=synth/mssam (this repository, clean-room) reading Microsoft's Speech API 4 voice data (msttsl.exe), fetched by tools/fetch-mssam.py
+21
View File
@@ -0,0 +1,21 @@
; Live voice for app_speakingclock (docs/voice-format.md), made by
; tools/synth_voices.py --live mssam:sam. Each sentence is spoken when
; it is needed, by synth/mssam, run here (tts_program_mssam).
; The synthesiser is ours; the voice data it reads is Microsoft's and is
; not in this repository (tools/fetch-mssam.py downloads it); see NOTICE.md.
[voice]
name=Microsoft Sam, live
description=Microsoft Speech API 4 voice Sam, by our own synthesiser, spoken live
mode=tts
sequence=speech+pips
period=10
[tts]
command={program:mssam} -v sam -o {out} "{text}"
text=At the third stroke, it will be {hour} {minute} {seconds}.
[source]
engine=mssam
voice=sam
synthesiser=synth/mssam (this repository, clean-room) reading Microsoft's Speech API 4 voice data (msttsl.exe), fetched by tools/fetch-mssam.py