diff --git a/AGENTS.md b/AGENTS.md index f2b82db..8fce30a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `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 -shared there. SSIP protocol and recovery tests live in the common -`speechdispatcher` package; reader integration tests remain here. +data or behavior. Shared packages own the emoji catalog, internal interaction +toolkit, Speech Dispatcher client and language matching, date/time formatting, +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` toolkit; core rich forms use `internalUI.OpenUI`. Change control behavior and its model tests in the common module. Keep Cthulhu's picker form, diff --git a/docs/testing/shared-reader-core.md b/docs/testing/shared-reader-core.md new file mode 100644 index 0000000..7c806de --- /dev/null +++ b/docs/testing/shared-reader-core.md @@ -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. diff --git a/docs/testing/shared-speech-dispatcher.md b/docs/testing/shared-speech-dispatcher.md index dbcd73a..8f7ac02 100644 --- a/docs/testing/shared-speech-dispatcher.md +++ b/docs/testing/shared-speech-dispatcher.md @@ -1,6 +1,6 @@ # 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; the sibling Go workspace can also be used for local development. diff --git a/go.mod b/go.mod index 303c6e1..144e203 100644 --- a/go.mod +++ b/go.mod @@ -8,4 +8,4 @@ require github.com/godbus/dbus/v5 v5.1.0 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 diff --git a/go.sum b/go.sum index ac19d6c..9853a65 100644 --- a/go.sum +++ b/go.sum @@ -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.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.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/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= diff --git a/internal/app/review_spelling.go b/internal/app/review_spelling.go index 93eeb46..5c0652e 100644 --- a/internal/app/review_spelling.go +++ b/internal/app/review_spelling.go @@ -11,17 +11,11 @@ import ( "git.stormux.org/storm/cthulhu/internal/input" "git.stormux.org/storm/cthulhu/internal/presentation" "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. -func phoneticLetter(letter rune) string { - 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 phoneticLetter(letter rune) string { return phonetic.Letter(letter) } func flat_review_speech(command input.Command) review.FlatSpeech { switch command { diff --git a/internal/app/review_spelling_test.go b/internal/app/review_spelling_test.go index 8db4f82..753e357 100644 --- a/internal/app/review_spelling_test.go +++ b/internal/app/review_spelling_test.go @@ -30,6 +30,7 @@ func TestFlatReviewSpellingPresentation(t *testing.T) { {input.ReviewCurrentCharacter, "b", nil, true}, {input.ReviewPhoneticCharacter, "B", []string{"bravo"}, false}, {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.ReviewSpellWord, "猫1!", []string{"猫", "1", "!"}, true}, {input.ReviewPhoneticWord, "猫1!", []string{"猫", "1", "!"}, false}, diff --git a/internal/datetime/datetime.go b/internal/datetime/datetime.go index d488f6f..2d2a06b 100644 --- a/internal/datetime/datetime.go +++ b/internal/datetime/datetime.go @@ -4,116 +4,14 @@ package datetime -import "time" +import common "git.stormux.org/storm/screenreader-common/datetime" -type Option struct { - Value string - Label string -} +type Option = common.Option -var timeFormats = []struct { - Value string - Spec string -}{ - {"locale", "%X"}, - {"12-hour", "%I:%M %p"}, - {"12-hour-seconds", "%I:%M:%S %p"}, - {"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 -} +var TimeOptions = common.TimeOptions +var DateOptions = common.DateOptions +var FormatTime = common.FormatTime +var FormatDate = common.FormatDate +var ValidTime = common.ValidTime +var ValidDate = common.ValidDate +var NormalizeDate = common.NormalizeDate diff --git a/internal/datetime/format_cgo.go b/internal/datetime/format_cgo.go deleted file mode 100644 index 1bcd288..0000000 --- a/internal/datetime/format_cgo.go +++ /dev/null @@ -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 -#include -#include -*/ -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)) -} diff --git a/internal/datetime/format_nocgo.go b/internal/datetime/format_nocgo.go deleted file mode 100644 index c92e1c9..0000000 --- a/internal/datetime/format_nocgo.go +++ /dev/null @@ -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() -} diff --git a/internal/datetime/format_nocgo_test.go b/internal/datetime/format_nocgo_test.go deleted file mode 100644 index 7ca9ef3..0000000 --- a/internal/datetime/format_nocgo_test.go +++ /dev/null @@ -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") - } -} diff --git a/internal/sound/progress.go b/internal/sound/progress.go index df75078..55878af 100644 --- a/internal/sound/progress.go +++ b/internal/sound/progress.go @@ -5,11 +5,11 @@ package sound import ( - "bytes" - "encoding/binary" "math" "strconv" "strings" + + "git.stormux.org/storm/screenreader-common/tones" ) 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 } -// Match NVDA's default ProgressBar event_valueChange and generateBeep: -// 110 * 2^(percentage/25) Hz, 40 ms padded to the next integer cycle, -// 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() -} +func progress_tone_wav(percentage float64) []byte { return tones.ProgressWAV(percentage) } +func nvda_tone_wav(hz float64, milliseconds int) []byte { return tones.NVDAWAV(hz, milliseconds) } diff --git a/internal/sound/progress_test.go b/internal/sound/progress_test.go index 4a93c7d..dc94bef 100644 --- a/internal/sound/progress_test.go +++ b/internal/sound/progress_test.go @@ -7,38 +7,11 @@ package sound import ( "bytes" "context" - "crypto/sha256" - "encoding/binary" - "fmt" "log/slog" "testing" "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 { context context.Context data []byte diff --git a/internal/sound/tone.go b/internal/sound/tone.go index 60096a5..1fd856c 100644 --- a/internal/sound/tone.go +++ b/internal/sound/tone.go @@ -5,41 +5,11 @@ package sound import ( - "bytes" - "encoding/binary" - "math" "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 { - const sampleRate = 22050 - 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() + return tones.SineWAV(frequency, duration, amplitude, ramp) } diff --git a/internal/speech/hardware.go b/internal/speech/hardware.go index 8b6c6a2..358f143 100644 --- a/internal/speech/hardware.go +++ b/internal/speech/hardware.go @@ -8,12 +8,13 @@ import ( "context" "errors" "fmt" - "math" "path/filepath" "strings" "sync" "syscall" "time" + + "git.stormux.org/storm/screenreader-common/hardware" ) // 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 { - data := []byte{} + profile := hardware.Serial(synth == "dectalk") + var values [3]*float64 for index, value := range []*float64{voice.Rate, voice.Pitch, voice.Volume} { if value == nil { continue } - limit := 9.0 + maximum := 9.0 if index == 0 { - limit = 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) + maximum = 99 } + normalized := hardware.LegacyValue(*value, maximum) + values[index] = &normalized } - // Devices accept ASCII. Strip control bytes and retain spacing just as - // Python's driver does. - for _, value := range text { - if value < 0x20 || value > 0x7e { - value = ' ' - } - data = append(data, byte(value)) + var data []byte + for _, command := range profile.Commands(hardware.Parameters{Rate: values[0], Pitch: values[1], Volume: values[2]}) { + data = append(data, command...) } - if synth == "dectalk" { - return append(data, 1) - } - return append(data, '\r') + return append(data, profile.Text(text)...) } 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 { 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 { diff --git a/internal/speech/hardware_test.go b/internal/speech/hardware_test.go index f655a01..b30fbbe 100644 --- a/internal/speech/hardware_test.go +++ b/internal/speech/hardware_test.go @@ -6,20 +6,20 @@ package speech import "testing" -func TestHardwareProtocolsMatchPython(t *testing.T) { +func TestHardwareProtocolsUseCommonEncoding(t *testing.T) { rate, pitch, volume := 99.0, 9.0, 9.0 voice := HardwareVoice{Rate: &rate, Pitch: &pitch, Volume: &volume} for _, synth := range []string{"litetalk", "doubletalk", "tripletalk", "dectalk"} { want := "\x019S\x0199P\x019VHello !\r" 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 { t.Fatalf("%s: got %q, want %q", synth, got, want) } } 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) } rate, pitch, volume = 49.5, 4.5, 4.5 @@ -27,3 +27,12 @@ func TestHardwareProtocolsMatchPython(t *testing.T) { 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) + } +} diff --git a/internal/speech/locale_voices.go b/internal/speech/locale_voices.go index e3a6596..fcfb187 100644 --- a/internal/speech/locale_voices.go +++ b/internal/speech/locale_voices.go @@ -4,46 +4,6 @@ package speech -import ( - "os" - "sort" - "strings" -) +import sd "git.stormux.org/storm/screenreader-common/speechdispatcher" -// LocaleVoices prefers the current locale's exact dialect, then its base -// 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 -} +func LocaleVoices(voices []Voice) []Voice { return sd.LanguageVoices(voices, "") } diff --git a/internal/speech/serial_native_test.go b/internal/speech/serial_native_test.go index c655993..d421885 100644 --- a/internal/speech/serial_native_test.go +++ b/internal/speech/serial_native_test.go @@ -60,7 +60,11 @@ func TestHardwareSerialWritesCancelsAndCloses(t *testing.T) { t.Fatal(err) } 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) } if err := client.Close(context.Background()); err != nil {