Use shared reader core v0.4.0

Use common date/time formatting, locale voice selection, tone synthesis, phonetic spelling, and hardware command encoding. DECtalk now follows the common Fenrir mapping and command filtering; legacy saved settings are converted at the boundary.

Validated affected race-enabled tests and standalone builds with GOWORK=off against the published module. Common PCM hashes, serial cancellation, no-CGO datetime, and speech regression checks passed. Physical hardware, audible synthesis, keyboard, and braille remain separate live checks.
This commit is contained in:
ak47 committed 2026-11-12 23:45:10 -05:00
1 parent 8ab9d3395a
commit d95dc2d00d
18 files changed
+121 -452

No files matched your search

+5 -3
View File
@@ -18,9 +18,11 @@ Cthulhu is a Go Linux screen reader. `cmd/` contains executables; `internal/` ow
Reader-independent Go code shared with Fenrir lives in Reader-independent Go code shared with Fenrir lives in
`git.stormux.org/storm/screenreader-common`; check it before duplicating pure `git.stormux.org/storm/screenreader-common`; check it before duplicating pure
data or behavior. The emoji catalog, internal interaction toolkit, and Speech Dispatcher client are data or behavior. Shared packages own the emoji catalog, internal interaction
shared there. SSIP protocol and recovery tests live in the common toolkit, Speech Dispatcher client and language matching, date/time formatting,
`speechdispatcher` package; reader integration tests remain here. phonetic spelling alphabet, tone generation, and hardware synthesizer protocols.
Change shared behavior and its unit tests in the common module. Reader integration
tests, device ownership, queues, playback, and presentation remain here.
`internal/interaction` is a compatibility adapter to the common `internalui` `internal/interaction` is a compatibility adapter to the common `internalui`
toolkit; core rich forms use `internalUI.OpenUI`. Change control behavior and toolkit; core rich forms use `internalUI.OpenUI`. Change control behavior and
its model tests in the common module. Keep Cthulhu's picker form, its model tests in the common module. Keep Cthulhu's picker form,
+61
View File
@@ -0,0 +1,61 @@
# Shared reader core acceptance
Both readers pin `screenreader-common` v0.4.0 for date/time formatting,
language-based voice selection, progress/tone synthesis, phonetic words, and
hardware protocol encoding. Standalone builds use that published module; the
sibling workspace remains available for local development. Verify standalone
builds with `GOWORK=off`. No machine-local module replacements are committed.
## Cthulhu
1. Quit the running reader with Cthulhu+Q.
2. Press Ctrl+Escape to enter i3 personal mode, then press Shift+G. These are
separate key presses. Shift+G rebuilds Cthulhu and its braille helper and opens
the test terminal using `~/devel/cthulhu-go.sh`.
3. Use the configured date and time commands. Their speech must follow the saved
formats and locale. In preferences, check that date/time examples and selected
formats agree. Tab, Shift+Tab, Apply, and focus announcements must still work;
braille should show the currently focused preference/control.
4. Review the text `WXwx` using phonetic word or line spelling. Expect `whiskey,
x ray, whiskey, x ray`; uppercase letters must retain the configured uppercase
voice behavior. Character review and ordinary text reading must still work.
5. Open speech preferences and inspect language-filtered voices. Locale defaults
prefer the exact dialect, then the base language; explicit language choices
remain exact. Apply a voice and confirm fresh speech uses it. Braille must keep
following the focused control, and keyboard input must remain responsive.
6. Trigger a known progress indicator. Its tones should sound unchanged and retain
interruption/volume behavior. Check an indentation or capitalization cue if
enabled. These audio changes should not move focus or change braille output.
7. If a supported serial synthesizer is connected, use the usual hardware speech
configuration and restart with the same sequence above. Check text, minimum/
midpoint/maximum rate and pitch, volume, and the silence key. DECtalk now uses
the same commands as Fenrir, so its midpoint and volume may audibly differ from
the old Cthulhu mapping. Text resembling `[:dv g5 10]` must be treated as text,
without applying that command. Do not enable a nonexistent hardware device.
8. Report the exact words and order, selected format/voice, control with focus,
braille contents, changed keys, and any differences in pitch/rate or silence.
Retain `~/devel/cthulhu-go.log` for unexpected results.
## Fenrir
Rebuild Fenrir from this workspace with the usual launcher. For a separate
unprivileged terminal-mode test, build with `go build -o /tmp/fenrir-shared-core
./cmd/fenrir` from its checkout (one command), then run
`/tmp/fenrir-shared-core -x --keyboard-layout desktop` in a test terminal.
1. Use the configured date/time commands and inspect their format examples.
Existing format IDs, locale output, and saved selections must still agree.
2. Review `WXwx` phonetically. Expect the shared words `whiskey` and `x ray`;
Fenrir retains capitalization of the words for uppercase input. Verify line,
word, character review, keyboard input, and braille tracking if configured.
3. Check language/voice choices and a known progress indicator. Selection,
progress pitch/volume, indentation tone shape, and silence behavior should
match the previous Fenrir behavior.
4. With a real supported synthesizer, repeat text, rate/pitch/volume adjustments,
and silence checks. DECtalk USB keeps its existing device handling. Report
exact observed speech, review position, settings, braille, and changed keys.
Automated tests exercise common protocol bytes, pseudo-terminal cancellation,
Fenrir's existing serial/USB fixtures, tone PCM hashes, locale matching, and date
formatting with and without CGO. These checks do not establish audible hardware
behavior or physical keyboard/braille acceptance.
+1 -1
View File
@@ -1,6 +1,6 @@
# Shared Speech Dispatcher acceptance # Shared Speech Dispatcher acceptance
Both readers pin `screenreader-common` v0.3.0, which supplies the shared Both readers pin `screenreader-common` v0.4.0, which supplies the shared
`speechdispatcher` package. Standalone builds use the published module; `speechdispatcher` package. Standalone builds use the published module;
the sibling Go workspace can also be used for local development. the sibling Go workspace can also be used for local development.
+1 -1
View File
@@ -8,4 +8,4 @@ require github.com/godbus/dbus/v5 v5.1.0
require github.com/gorilla/websocket v1.5.3 require github.com/gorilla/websocket v1.5.3
require git.stormux.org/storm/screenreader-common v0.3.0 require git.stormux.org/storm/screenreader-common v0.4.0
+2
View File
@@ -4,6 +4,8 @@ git.stormux.org/storm/screenreader-common v0.2.0 h1:PbGwyIi/nT0qwvscje4pvIIsAxDL
git.stormux.org/storm/screenreader-common v0.2.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= git.stormux.org/storm/screenreader-common v0.2.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY=
git.stormux.org/storm/screenreader-common v0.3.0 h1:eWuSMf3lM8fB5RyegnsyHmdz1uP0CzPqMfFP8wonV3k= git.stormux.org/storm/screenreader-common v0.3.0 h1:eWuSMf3lM8fB5RyegnsyHmdz1uP0CzPqMfFP8wonV3k=
git.stormux.org/storm/screenreader-common v0.3.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY= git.stormux.org/storm/screenreader-common v0.3.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY=
git.stormux.org/storm/screenreader-common v0.4.0 h1:iq2BuC/d6EBiMh76WZK09De+sQjGk2TWDNw6p5zGHGE=
git.stormux.org/storm/screenreader-common v0.4.0/go.mod h1:iLmD0KXRvR4ar3U80JMwbaNUOyR82/gY7xHUY+zeIoY=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
+2 -8
View File
@@ -11,17 +11,11 @@ import (
"git.stormux.org/storm/cthulhu/internal/input" "git.stormux.org/storm/cthulhu/internal/input"
"git.stormux.org/storm/cthulhu/internal/presentation" "git.stormux.org/storm/cthulhu/internal/presentation"
"git.stormux.org/storm/cthulhu/internal/review" "git.stormux.org/storm/cthulhu/internal/review"
"git.stormux.org/storm/screenreader-common/phonetic"
) )
// Shared by review spelling and learn mode, matching Python Cthulhu's names. // Shared by review spelling and learn mode, matching Python Cthulhu's names.
func phoneticLetter(letter rune) string { func phoneticLetter(letter rune) string { return phonetic.Letter(letter) }
words := [...]string{"alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"}
letter = unicode.ToLower(letter)
if letter < 'a' || letter > 'z' {
return ""
}
return words[letter-'a']
}
func flat_review_speech(command input.Command) review.FlatSpeech { func flat_review_speech(command input.Command) review.FlatSpeech {
switch command { switch command {
+1
View File
@@ -30,6 +30,7 @@ func TestFlatReviewSpellingPresentation(t *testing.T) {
{input.ReviewCurrentCharacter, "b", nil, true}, {input.ReviewCurrentCharacter, "b", nil, true},
{input.ReviewPhoneticCharacter, "B", []string{"bravo"}, false}, {input.ReviewPhoneticCharacter, "B", []string{"bravo"}, false},
{input.ReviewSpellWord, "Book", []string{"B", "o", "o", "k"}, true}, {input.ReviewSpellWord, "Book", []string{"B", "o", "o", "k"}, true},
{input.ReviewPhoneticWord, "WXwx", []string{"whiskey", "x ray", "whiskey", "x ray"}, false},
{input.ReviewPhoneticWord, "Book", []string{"bravo", "oscar", "oscar", "kilo"}, false}, {input.ReviewPhoneticWord, "Book", []string{"bravo", "oscar", "oscar", "kilo"}, false},
{input.ReviewSpellWord, "猫1!", []string{"猫", "1", "!"}, true}, {input.ReviewSpellWord, "猫1!", []string{"猫", "1", "!"}, true},
{input.ReviewPhoneticWord, "猫1!", []string{"猫", "1", "!"}, false}, {input.ReviewPhoneticWord, "猫1!", []string{"猫", "1", "!"}, false},
+9 -111
View File
@@ -4,116 +4,14 @@
package datetime package datetime
import "time" import common "git.stormux.org/storm/screenreader-common/datetime"
type Option struct { type Option = common.Option
Value string
Label string
}
var timeFormats = []struct { var TimeOptions = common.TimeOptions
Value string var DateOptions = common.DateOptions
Spec string var FormatTime = common.FormatTime
}{ var FormatDate = common.FormatDate
{"locale", "%X"}, var ValidTime = common.ValidTime
{"12-hour", "%I:%M %p"}, var ValidDate = common.ValidDate
{"12-hour-seconds", "%I:%M:%S %p"}, var NormalizeDate = common.NormalizeDate
{"24-hour-seconds", "%H:%M:%S"},
{"24-hour-seconds-words", "%H hours, %M minutes and %S seconds"},
{"24-hour", "%H:%M"},
{"24-hour-words", "%H hours and %M minutes"},
}
var dateFormats = []struct {
Value string
Spec string
}{
{"locale", "%x"},
{"numbers-dm", "%d/%m"},
{"numbers-md", "%m/%d"},
{"numbers-dmy", "%d/%m/%Y"},
{"numbers-mdy", "%m/%d/%Y"},
{"numbers-ymd", "%Y/%m/%d"},
{"full-dm", "%A, %-d %B"},
{"full-md", "%A, %B %-d"},
{"full-dmy", "%A, %-d %B, %Y"},
{"full-mdy", "%A, %B %-d, %Y"},
{"full-ymd", "%Y. %B %-d, %A"},
{"abbreviated-dm", "%a, %-d %b"},
{"abbreviated-md", "%a, %b %-d"},
{"abbreviated-dmy", "%a, %-d %b, %Y"},
{"abbreviated-mdy", "%a, %b %-d, %Y"},
{"abbreviated-ymd", "%Y. %b %-d, %a"},
}
func TimeOptions(now time.Time) []Option {
return options(timeFormats, now)
}
func DateOptions(now time.Time) []Option {
return options(dateFormats, now)
}
func options(formats []struct {
Value string
Spec string
}, now time.Time) []Option {
result := make([]Option, 0, len(formats))
for _, item := range formats {
result = append(result, Option{Value: item.Value, Label: format(now, item.Spec)})
}
return result
}
func FormatTime(value string, now time.Time) (string, bool) {
return formatValue(timeFormats, value, now)
}
func FormatDate(value string, now time.Time) (string, bool) {
return formatValue(dateFormats, value, now)
}
func ValidTime(value string) bool {
return valid(timeFormats, value)
}
func ValidDate(value string) bool {
return valid(dateFormats, value)
}
func NormalizeDate(value string) string {
switch value {
case "ymd":
return "numbers-ymd"
case "mdy":
return "numbers-mdy"
case "dmy":
return "numbers-dmy"
default:
return value
}
}
func formatValue(formats []struct {
Value string
Spec string
}, value string, now time.Time) (string, bool) {
for _, item := range formats {
if item.Value == value {
return format(now, item.Spec), true
}
}
return "", false
}
func valid(formats []struct {
Value string
Spec string
}, value string) bool {
for _, item := range formats {
if item.Value == value {
return true
}
}
return false
}
-44
View File
@@ -1,44 +0,0 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
//go:build cgo
package datetime
/*
#include <locale.h>
#include <stdlib.h>
#include <time.h>
*/
import "C"
import (
"time"
"unsafe"
)
func init() {
locale := C.CString("")
defer C.free(unsafe.Pointer(locale))
C.setlocale(C.LC_TIME, locale)
}
func format(now time.Time, spec string) string {
cSpec := C.CString(spec)
defer C.free(unsafe.Pointer(cSpec))
tm := C.struct_tm{
tm_year: C.int(now.Year() - 1900),
tm_mon: C.int(int(now.Month()) - 1),
tm_mday: C.int(now.Day()),
tm_hour: C.int(now.Hour()),
tm_min: C.int(now.Minute()),
tm_sec: C.int(now.Second()),
tm_wday: C.int(int(now.Weekday())),
tm_yday: C.int(now.YearDay() - 1),
tm_isdst: -1,
}
buffer := make([]C.char, 512)
length := C.strftime(&buffer[0], C.size_t(len(buffer)), cSpec, &tm)
return C.GoStringN(&buffer[0], C.int(length))
}
-80
View File
@@ -1,80 +0,0 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
//go:build !cgo
package datetime
import (
"strconv"
"strings"
"time"
)
// format is a C-locale strftime subset for builds without cgo, such as the
// statically linked Tentacle packages that only validate settings. The reader
// itself is built with cgo and uses the locale-aware implementation.
func format(now time.Time, spec string) string {
var out strings.Builder
for index := 0; index < len(spec); index++ {
if spec[index] != '%' || index+1 == len(spec) {
out.WriteByte(spec[index])
continue
}
index++
pad := true
if spec[index] == '-' && index+1 < len(spec) {
pad = false
index++
}
two := func(value int) string {
if pad && value < 10 {
return "0" + strconv.Itoa(value)
}
return strconv.Itoa(value)
}
switch spec[index] {
case 'H':
out.WriteString(two(now.Hour()))
case 'I':
hour := now.Hour() % 12
if hour == 0 {
hour = 12
}
out.WriteString(two(hour))
case 'M':
out.WriteString(two(now.Minute()))
case 'S':
out.WriteString(two(now.Second()))
case 'p':
out.WriteString(now.Format("PM"))
case 'X':
out.WriteString(now.Format("15:04:05"))
case 'x':
out.WriteString(now.Format("01/02/06"))
case 'd':
out.WriteString(two(now.Day()))
case 'm':
out.WriteString(two(int(now.Month())))
case 'Y':
out.WriteString(strconv.Itoa(now.Year()))
case 'y':
out.WriteString(now.Format("06"))
case 'A':
out.WriteString(now.Weekday().String())
case 'a':
out.WriteString(now.Weekday().String()[:3])
case 'B':
out.WriteString(now.Month().String())
case 'b':
out.WriteString(now.Month().String()[:3])
case '%':
out.WriteByte('%')
default:
out.WriteByte('%')
out.WriteByte(spec[index])
}
}
return out.String()
}
-28
View File
@@ -1,28 +0,0 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
//go:build !cgo
package datetime
import (
"testing"
"time"
)
func TestFormatFallbackMatchesCLocale(t *testing.T) {
now := time.Date(2026, time.March, 5, 7, 4, 9, 0, time.UTC)
for spec, want := range map[string]string{
"%I:%M %p": "07:04 AM", "%H:%M:%S": "07:04:09", "%X": "07:04:09", "%x": "03/05/26",
"%A, %-d %B, %Y": "Thursday, 5 March, 2026", "%a, %b %-d": "Thu, Mar 5", "%d/%m/%Y": "05/03/2026",
"%H hours and %M minutes": "07 hours and 04 minutes", "100%%": "100%",
} {
if got := format(now, spec); got != want {
t.Fatalf("%q = %q, want %q", spec, got, want)
}
}
if !ValidTime("24-hour") || !ValidDate("full-mdy") {
t.Fatal("validation changed without cgo")
}
}
+4 -43
View File
@@ -5,11 +5,11 @@
package sound package sound
import ( import (
"bytes"
"encoding/binary"
"math" "math"
"strconv" "strconv"
"strings" "strings"
"git.stormux.org/storm/screenreader-common/tones"
) )
const progressCuePrefix = "generated-progress-tone:" const progressCuePrefix = "generated-progress-tone:"
@@ -26,44 +26,5 @@ func progress_percentage(cue string) (float64, bool) {
return percentage, err == nil && !math.IsNaN(percentage) && !math.IsInf(percentage, 0) && percentage >= 0 && percentage <= 100 return percentage, err == nil && !math.IsNaN(percentage) && !math.IsInf(percentage, 0) && percentage >= 0 && percentage <= 100
} }
// Match NVDA's default ProgressBar event_valueChange and generateBeep: func progress_tone_wav(percentage float64) []byte { return tones.ProgressWAV(percentage) }
// 110 * 2^(percentage/25) Hz, 40 ms padded to the next integer cycle, func nvda_tone_wav(hz float64, milliseconds int) []byte { return tones.NVDAWAV(hz, milliseconds) }
// 44100 Hz stereo PCM, and a sine clipped after multiplying by two.
// NVDA passes frequency through a C float and defaults each channel to 50%.
// Reference: nvaccess/nvda a4a89720ccbf3973a0e1e50a76dd8bff38db3d15,
// source/NVDAObjects/behaviors.py and nvdaHelper/local/beeps.cpp.
func progress_tone_wav(percentage float64) []byte {
return nvda_tone_wav(110*math.Pow(2, percentage/25), 40)
}
// nvda_tone_wav also supplies the capital-letter beep (2000 Hz, 50 ms).
func nvda_tone_wav(hz float64, milliseconds int) []byte {
const sampleRate = 44100
frequency := float64(float32(hz))
// sampleRate/hz is evaluated as a float in NVDA's C++ generator.
cycleLength := float64(float32(sampleRate) / float32(frequency))
samplesPerCycle := int(cycleLength)
sampleCount := int((float64(milliseconds) / 1000) / (1.0 / sampleRate))
sampleCount += samplesPerCycle - sampleCount%samplesPerCycle
dataSize := sampleCount * 4
buffer := bytes.NewBuffer(make([]byte, 0, 44+dataSize))
buffer.WriteString("RIFF")
_ = binary.Write(buffer, binary.LittleEndian, uint32(36+dataSize))
buffer.WriteString("WAVEfmt ")
_ = binary.Write(buffer, binary.LittleEndian, uint32(16))
_ = binary.Write(buffer, binary.LittleEndian, uint16(1))
_ = binary.Write(buffer, binary.LittleEndian, uint16(2))
_ = binary.Write(buffer, binary.LittleEndian, uint32(sampleRate))
_ = binary.Write(buffer, binary.LittleEndian, uint32(sampleRate*4))
_ = binary.Write(buffer, binary.LittleEndian, uint16(4))
_ = binary.Write(buffer, binary.LittleEndian, uint16(16))
buffer.WriteString("data")
_ = binary.Write(buffer, binary.LittleEndian, uint32(dataSize))
sinFrequency := 2 * math.Pi / cycleLength
for sample := 0; sample < sampleCount; sample++ {
value := int16(min(1.0, max(-1.0, math.Sin(float64(sample%sampleRate)*sinFrequency)*2)) * 7000)
_ = binary.Write(buffer, binary.LittleEndian, value)
_ = binary.Write(buffer, binary.LittleEndian, value)
}
return buffer.Bytes()
}
-27
View File
@@ -7,38 +7,11 @@ package sound
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/sha256"
"encoding/binary"
"fmt"
"log/slog" "log/slog"
"testing" "testing"
"time" "time"
) )
func TestProgressAudioMatchesNVDAGenerator(t *testing.T) {
// PCM digests from the unmodified generateBeep in the reference commit
// named in progress.go, compiled locally with a small output-only harness.
all := sha256.New()
for percentage := 0; percentage <= 100; percentage++ {
data := progress_tone_wav(float64(percentage))
if binary.LittleEndian.Uint32(data[24:]) != 44100 || binary.LittleEndian.Uint16(data[22:]) != 2 {
t.Fatal("progress tone is not 44100 Hz stereo")
}
all.Write(data[44:])
}
if got := fmt.Sprintf("%x", all.Sum(nil)); got != "ef56e46be365269af544e22d94eb1de7d171c5946d1dd5b168cc7e570c0a159f" {
t.Fatalf("0 through 100 percent PCM differs from NVDA: %s", got)
}
for percentage, digest := range map[float64]string{
12.5: "4fc87ad5310038ed281a4516e9431d5dc247b7ce75662e4fe51cb4d2ab616a36",
50.25: "6b4a9a7d254686b2fb52ead07763ff596ccdcbdd30d5e9d4ce956df13cc1bdf5",
} {
if got := fmt.Sprintf("%x", sha256.Sum256(progress_tone_wav(percentage)[44:])); got != digest {
t.Fatalf("%g percent PCM differs from NVDA: %s", percentage, got)
}
}
}
type progressPlayback struct { type progressPlayback struct {
context context.Context context context.Context
data []byte data []byte
+3 -33
View File
@@ -5,41 +5,11 @@
package sound package sound
import ( import (
"bytes"
"encoding/binary"
"math"
"time" "time"
"git.stormux.org/storm/screenreader-common/tones"
) )
// tone_wav generates mono, 16-bit PCM at 22050 Hz for the existing Player.
// Callers supply a positive frequency/duration, amplitude in [0, 1], and a
// nonnegative edge ramp. A zero ramp preserves an unsmoothed sine tone.
// Playback volume, pan, queuing, and cancellation belong to the sound service.
func tone_wav(frequency float64, duration time.Duration, amplitude float64, ramp time.Duration) []byte { func tone_wav(frequency float64, duration time.Duration, amplitude float64, ramp time.Duration) []byte {
const sampleRate = 22050 return tones.SineWAV(frequency, duration, amplitude, ramp)
sampleCount := int(float64(sampleRate) * duration.Seconds())
rampSamples := int(float64(sampleRate) * ramp.Seconds())
dataSize := sampleCount * 2
buffer := bytes.NewBuffer(make([]byte, 0, 44+dataSize))
buffer.WriteString("RIFF")
_ = binary.Write(buffer, binary.LittleEndian, uint32(36+dataSize))
buffer.WriteString("WAVEfmt ")
_ = binary.Write(buffer, binary.LittleEndian, uint32(16))
_ = binary.Write(buffer, binary.LittleEndian, uint16(1))
_ = binary.Write(buffer, binary.LittleEndian, uint16(1))
_ = binary.Write(buffer, binary.LittleEndian, uint32(sampleRate))
_ = binary.Write(buffer, binary.LittleEndian, uint32(sampleRate*2))
_ = binary.Write(buffer, binary.LittleEndian, uint16(2))
_ = binary.Write(buffer, binary.LittleEndian, uint16(16))
buffer.WriteString("data")
_ = binary.Write(buffer, binary.LittleEndian, uint32(dataSize))
for sample := 0; sample < sampleCount; sample++ {
envelope := 1.0
if rampSamples > 0 {
envelope = min(1.0, float64(min(sample, sampleCount-1-sample))/float64(rampSamples))
}
value := int16(math.Sin(2*math.Pi*frequency*float64(sample)/sampleRate) * amplitude * envelope * math.MaxInt16)
_ = binary.Write(buffer, binary.LittleEndian, value)
}
return buffer.Bytes()
} }
+13 -27
View File
@@ -8,12 +8,13 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"math"
"path/filepath" "path/filepath"
"strings" "strings"
"sync" "sync"
"syscall" "syscall"
"time" "time"
"git.stormux.org/storm/screenreader-common/hardware"
) )
// Hardware ports Python Cthulhu's serial protocols. One owner serializes text // Hardware ports Python Cthulhu's serial protocols. One owner serializes text
@@ -45,39 +46,24 @@ func NewHardware(device, synth string, baud int) (*Hardware, error) {
} }
func hardware_bytes(synth, text string, voice HardwareVoice) []byte { func hardware_bytes(synth, text string, voice HardwareVoice) []byte {
data := []byte{} profile := hardware.Serial(synth == "dectalk")
var values [3]*float64
for index, value := range []*float64{voice.Rate, voice.Pitch, voice.Volume} { for index, value := range []*float64{voice.Rate, voice.Pitch, voice.Volume} {
if value == nil { if value == nil {
continue continue
} }
limit := 9.0 maximum := 9.0
if index == 0 { if index == 0 {
limit = 99 maximum = 99
}
normalized := math.Max(0, math.Min(limit, *value)) / limit
if synth == "dectalk" {
minimum := []int{75, 50, 0}[index]
maximum := []int{650, 180, 100}[index]
command := []string{"ra", "dv ap", "vo"}[index]
data = fmt.Appendf(data, "[:%s %d]", command, int(math.RoundToEven(float64(minimum)+normalized*float64(maximum-minimum))))
} else {
maximum := []int{9, 99, 9}[index]
command := []byte{'S', 'P', 'V'}[index]
data = fmt.Appendf(data, "\x01%d%c", int(math.RoundToEven(normalized*float64(maximum))), command)
} }
normalized := hardware.LegacyValue(*value, maximum)
values[index] = &normalized
} }
// Devices accept ASCII. Strip control bytes and retain spacing just as var data []byte
// Python's driver does. for _, command := range profile.Commands(hardware.Parameters{Rate: values[0], Pitch: values[1], Volume: values[2]}) {
for _, value := range text { data = append(data, command...)
if value < 0x20 || value > 0x7e {
value = ' '
}
data = append(data, byte(value))
} }
if synth == "dectalk" { return append(data, profile.Text(text)...)
return append(data, 1)
}
return append(data, '\r')
} }
func (client *Hardware) Speak(ctx context.Context, text string, voice HardwareVoice) error { func (client *Hardware) Speak(ctx context.Context, text string, voice HardwareVoice) error {
@@ -148,7 +134,7 @@ func (client *Hardware) Cancel(ctx context.Context) error {
if err := flush_serial(client.fd); err != nil { if err := flush_serial(client.fd); err != nil {
return err return err
} }
return client.write_serial(ctx, []byte{0x18}, generation) return client.write_serial(ctx, hardware.Serial(client.synth == "dectalk").Cancel(), generation)
} }
func (client *Hardware) Close(ctx context.Context) error { func (client *Hardware) Close(ctx context.Context) error {
+12 -3
View File
@@ -6,20 +6,20 @@ package speech
import "testing" import "testing"
func TestHardwareProtocolsMatchPython(t *testing.T) { func TestHardwareProtocolsUseCommonEncoding(t *testing.T) {
rate, pitch, volume := 99.0, 9.0, 9.0 rate, pitch, volume := 99.0, 9.0, 9.0
voice := HardwareVoice{Rate: &rate, Pitch: &pitch, Volume: &volume} voice := HardwareVoice{Rate: &rate, Pitch: &pitch, Volume: &volume}
for _, synth := range []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} { for _, synth := range []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} {
want := "\x019S\x0199P\x019VHello !\r" want := "\x019S\x0199P\x019VHello !\r"
if synth == "dectalk" { if synth == "dectalk" {
want = "[:ra 650][:dv ap 180][:vo 100]Hello !\x01" want = "[:ra 650][:dv ap 350][:dv g5 86]Hello !\x0b"
} }
if got := string(hardware_bytes(synth, "Hello\n\x01é猫!", voice)); got != want { if got := string(hardware_bytes(synth, "Hello\n\x01é猫!", voice)); got != want {
t.Fatalf("%s: got %q, want %q", synth, got, want) t.Fatalf("%s: got %q, want %q", synth, got, want)
} }
} }
rate, pitch, volume = 0, 0, 0 rate, pitch, volume = 0, 0, 0
if got := string(hardware_bytes("dectalk", "Low", voice)); got != "[:ra 75][:dv ap 50][:vo 0]Low\x01" { if got := string(hardware_bytes("dectalk", "Low", voice)); got != "[:ra 75][:dv ap 50][:dv g5 60]Low\x0b" {
t.Fatal(got) t.Fatal(got)
} }
rate, pitch, volume = 49.5, 4.5, 4.5 rate, pitch, volume = 49.5, 4.5, 4.5
@@ -27,3 +27,12 @@ func TestHardwareProtocolsMatchPython(t *testing.T) {
t.Fatal(got) t.Fatal(got)
} }
} }
func TestDECtalkUsesCommonMidpointAndFiltersCommands(t *testing.T) {
rate, pitch, volume := 49.5, 4.5, 4.5
voice := HardwareVoice{Rate: &rate, Pitch: &pitch, Volume: &volume}
want := "[:ra 180][:dv ap 122][:dv g5 73]Say [ :dv g5 10]\x0b"
if got := string(hardware_bytes("dectalk", "Say [:dv g5 10]", voice)); got != want {
t.Fatalf("%q, want %q", got, want)
}
}
+2 -42
View File
@@ -4,46 +4,6 @@
package speech package speech
import ( import sd "git.stormux.org/storm/screenreader-common/speechdispatcher"
"os"
"sort"
"strings"
)
// LocaleVoices prefers the current locale's exact dialect, then its base func LocaleVoices(voices []Voice) []Voice { return sd.LanguageVoices(voices, "") }
// language. An unknown locale retains the catalog, matching quick settings.
func LocaleVoices(voices []Voice) []Voice {
locale := ""
for _, key := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
if value := os.Getenv(key); value != "" {
locale = value
break
}
}
normalize := func(value string) string {
value = strings.Split(strings.Split(value, ".")[0], "@")[0]
return strings.ToLower(strings.ReplaceAll(value, "_", "-"))
}
locale = normalize(locale)
if locale == "" || locale == "c" || locale == "posix" {
locale = "en-us"
}
for _, language := range []string{locale, strings.SplitN(locale, "-", 2)[0]} {
var selected []Voice
for _, voice := range voices {
if normalize(voice.Language) == language {
selected = append(selected, voice)
}
}
if len(selected) == 0 {
continue
}
// A '+' in the synthesis name denotes an eSpeak variant; Variant
// is gender metadata and cannot identify the unmodified voice.
sort.SliceStable(selected, func(i, j int) bool {
return !strings.Contains(selected[i].Name, "+") && strings.Contains(selected[j].Name, "+")
})
return selected
}
return voices
}
+5 -1
View File
@@ -60,7 +60,11 @@ func TestHardwareSerialWritesCancelsAndCloses(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
n, err = master.Read(buffer) n, err = master.Read(buffer)
if err != nil || !bytes.Equal(buffer[:n], []byte{0x18}) { cancelByte := byte(0x18)
if synth == "dectalk" {
cancelByte = 3
}
if err != nil || !bytes.Equal(buffer[:n], []byte{cancelByte}) {
t.Fatalf("cancel=%q error=%v", buffer[:n], err) t.Fatalf("cancel=%q error=%v", buffer[:n], err)
} }
if err := client.Close(context.Background()); err != nil { if err := client.Close(context.Background()); err != nil {