diff --git a/go.mod b/go.mod index 828d378e..46a3bb5b 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module git.stormux.org/storm/fenrir go 1.27.2 require ( - git.stormux.org/storm/screenreader-common v0.3.0 + git.stormux.org/storm/screenreader-common v0.4.0 github.com/jfreymuth/pulse v0.1.3 github.com/leonelquinteros/gotext v1.8.0 github.com/pelletier/go-toml/v2 v2.4.3 diff --git a/go.sum b/go.sum index 6e7d5413..046b767f 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/jfreymuth/pulse v0.1.3 h1:bc5TdxiB8E+2INnFjFWWgyfgXtz2IyNNNCX+Wt/ZD14= github.com/jfreymuth/pulse v0.1.3/go.mod h1:cpYspI6YljhkUf1WLXLLDmeaaPFc3CnGLjDZf9dZ4no= github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU= diff --git a/internal/datetime/datetime.go b/internal/datetime/datetime.go index 941ef90e..e3c4e4fa 100644 --- a/internal/datetime/datetime.go +++ b/internal/datetime/datetime.go @@ -1,141 +1,16 @@ // Copyright (c) 2026 Storm Dragon -// Author: Storm Dragon +// Authors: Storm Dragon, Angus Kola // SPDX-License-Identifier: GPL-3.0-or-later package datetime -/* -#include -#include -#include -*/ -import "C" +import common "git.stormux.org/storm/screenreader-common/datetime" -import ( - "time" - "unsafe" -) +type Option = common.Option -type Option struct { - Value string - Label string -} - -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 init() { - locale := C.CString("") - defer C.free(unsafe.Pointer(locale)) - C.setlocale(C.LC_TIME, locale) -} - -func Time_options(now time.Time) []Option { - return options(timeFormats, now) -} - -func Date_options(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 Format_time(value string, now time.Time) (string, bool) { - return format_value(timeFormats, value, now) -} - -func Format_date(value string, now time.Time) (string, bool) { - return format_value(dateFormats, value, now) -} - -func Valid_time(value string) bool { - return valid(timeFormats, value) -} - -func Valid_date(value string) bool { - return valid(dateFormats, value) -} - -func format_value(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 -} - -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)) -} +var Time_options = common.TimeOptions +var Date_options = common.DateOptions +var Format_time = common.FormatTime +var Format_date = common.FormatDate +var Valid_time = common.ValidTime +var Valid_date = common.ValidDate diff --git a/internal/presentation/phonetic.go b/internal/presentation/phonetic.go index d7d10c99..2e8acb34 100644 --- a/internal/presentation/phonetic.go +++ b/internal/presentation/phonetic.go @@ -3,17 +3,19 @@ package presentation -import "unicode" +import ( + "unicode" -// Phonetic_letter matches Python Fenrir's alphabet, including its capitalization. + "git.stormux.org/storm/screenreader-common/phonetic" +) + +// Phonetic_letter matches the shared spelling alphabet with Fenrir capitalization. // Other runes use the active punctuation profile's character naming instead. func Phonetic_letter(char 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", "whisky", "x ray", "yankee", "zulu"} - upper := unicode.ToUpper(char) - if upper < 'A' || upper > 'Z' { + word := phonetic.Letter(char) + if word == "" { return "" } - word := words[upper-'A'] if unicode.IsUpper(char) { word = string(unicode.ToUpper(rune(word[0]))) + word[1:] } diff --git a/internal/presentation/phonetic_test.go b/internal/presentation/phonetic_test.go index 91acf378..893993cf 100644 --- a/internal/presentation/phonetic_test.go +++ b/internal/presentation/phonetic_test.go @@ -11,7 +11,7 @@ func TestPythonPhoneticNamesAndUnicodeFallback(t *testing.T) { want string }{ {'a', "alpha"}, {'A', "Alpha"}, {'j', "juliet"}, - {'w', "whisky"}, {'W', "Whisky"}, {'x', "x ray"}, {'X', "X ray"}, + {'w', "whiskey"}, {'W', "Whiskey"}, {'x', "x ray"}, {'X', "X ray"}, {'É', ""}, {'界', ""}, {'1', ""}, {'?', ""}, {' ', ""}, } { if got := Phonetic_letter(trial.char); got != trial.want { diff --git a/internal/sound/progress.go b/internal/sound/progress.go index f3715f98..5f1268a8 100644 --- a/internal/sound/progress.go +++ b/internal/sound/progress.go @@ -18,7 +18,11 @@ // Tone synthesis adapted from Cthulhu (Storm Dragon and Angus Kola). package sound -import "math" +import ( + "math" + + "git.stormux.org/storm/screenreader-common/tones" +) // A small gain lift for progress tones, independent of normal cue volume. const progressGain = 1.03 * 1.02 @@ -43,20 +47,11 @@ func progress_tone(percentage float64) *clip { // The triangle variant shares progress's pitch, duration and resampling. func progress_tone_shape(percentage float64, triangle bool) *clip { - const sourceRate = 44100 - frequency := float32(110 * math.Pow(2, percentage/25)) - cycleLength := float64(float32(sourceRate) / frequency) - samplesPerCycle := int(cycleLength) - count := sourceRate * 40 / 1000 - count += samplesPerCycle - count%samplesPerCycle + const sourceRate = tones.SampleRate + native := tones.Samples(tones.ProgressFrequency(percentage), 40, triangle) + count := len(native) source := make([]float32, count) - for index := range source { - phase := float64(index) * 2 * math.Pi / cycleLength - wave := min(1.0, max(-1.0, math.Sin(phase)*2)) - if triangle { - wave = 2 / math.Pi * math.Asin(math.Sin(phase)) - } - value := int16(wave * 7000) + for index, value := range native { source[index] = float32(value) / 32768 } frames := (count*sampleRate + sourceRate - 1) / sourceRate diff --git a/internal/speech/catalog.go b/internal/speech/catalog.go index 58b25d81..16116f9e 100644 --- a/internal/speech/catalog.go +++ b/internal/speech/catalog.go @@ -6,8 +6,6 @@ package speech import ( "context" "fmt" - "os" - "sort" "strings" "time" "unicode" @@ -115,50 +113,8 @@ func parse_voices(rows []string) ([]Voice, error) { return voices, nil } -func Normalize_language(value string) string { - value = strings.Split(strings.Split(value, ".")[0], "@")[0] - return strings.ToLower(strings.ReplaceAll(value, "_", "-")) -} - -// Language_voices follows Cthulhu's eSpeak selection: exact dialect, then base -// language, with unmodified names before '+' variants. Empty means locale. -// Unknown locales retain the full catalog; explicit languages remain exact. -func Language_voices(voices []Voice, language string) []Voice { - explicit := language != "" - if !explicit { - for _, key := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} { - if language = os.Getenv(key); language != "" { - break - } - } - } - language = Normalize_language(language) - if !explicit && (language == "" || language == "c" || language == "posix") { - language = "en-us" - } - languages := []string{language} - if !explicit { - languages = append(languages, strings.SplitN(language, "-", 2)[0]) - } - for _, match := range languages { - var selected []Voice - for _, voice := range voices { - if Normalize_language(voice.Language) == match { - selected = append(selected, voice) - } - } - if len(selected) > 0 { - sort.SliceStable(selected, func(i, j int) bool { - return !strings.Contains(selected[i].Name, "+") && strings.Contains(selected[j].Name, "+") - }) - return selected - } - } - if explicit { - return nil - } - return voices -} +var Normalize_language = sd.NormalizeLanguage +var Language_voices = sd.LanguageVoices // Prepare checks membership because SSIP SET may accept unknown synthesis // names without verifying them. The resulting client has not spoken anything. diff --git a/internal/speech/catalog_test.go b/internal/speech/catalog_test.go index 101d68e3..a7a98464 100644 --- a/internal/speech/catalog_test.go +++ b/internal/speech/catalog_test.go @@ -5,7 +5,6 @@ package speech import ( "fmt" - "reflect" "strings" "testing" ) @@ -58,32 +57,6 @@ func TestBoundedRepliesAndInjection(t *testing.T) { } } -func TestEspeakLocaleDialectBaseAndExplicitLanguage(t *testing.T) { - voices := []Voice{{Name: "US+Variant", Language: "en-US"}, {Name: "German", Language: "de"}, {Name: "US", Language: "en-US"}, {Name: "English", Language: "en"}} - t.Setenv("LC_ALL", "en_US.UTF-8") - got := Language_voices(voices, "") - if !reflect.DeepEqual(got, []Voice{voices[2], voices[0]}) { - t.Fatal(got) - } - t.Setenv("LC_ALL", "en_AU.UTF-8") - if got := Language_voices(voices, ""); !reflect.DeepEqual(got, []Voice{voices[3]}) { - t.Fatal(got) - } - if got := Language_voices(voices, "de"); !reflect.DeepEqual(got, []Voice{voices[1]}) { - t.Fatal(got) - } - if got := Language_voices(voices, "unknown"); len(got) != 0 { - t.Fatal(got) - } - t.Setenv("LC_ALL", "zz_ZZ") - if got := Language_voices(voices, ""); !reflect.DeepEqual(got, voices) { - t.Fatal(got) - } - if voices[0].Name != "US+Variant" { - t.Fatal("catalog reordered in place") - } -} - func TestCandidateRejectionLeavesOriginalClientUsable(t *testing.T) { server := new_fake_server(t, false) original, err := Open(Options{Socket: server.path}) diff --git a/internal/speech/hardware.go b/internal/speech/hardware.go index a6de1f2b..fd172db1 100644 --- a/internal/speech/hardware.go +++ b/internal/speech/hardware.go @@ -6,12 +6,13 @@ package speech import ( "errors" "fmt" - "math" "path/filepath" "slices" "strings" "sync" "sync/atomic" + + "git.stormux.org/storm/screenreader-common/hardware" ) var errHardwareCanceled = errors.New("hardware speech write canceled") @@ -100,25 +101,15 @@ func hardware_parameters(options Options) error { return parameters.Validate() } -// Python's normalized 0..1 values correspond to the shared -100..100 scale. -// RoundToEven matches Python round, including LiteTalk's midpoint volume 4. -func hardware_scale(value, minimum, maximum int) int { - return int(math.RoundToEven(float64(minimum) + float64(value+100)*float64(maximum-minimum)/200)) -} - -func dectalk_scale(value, minimum, normal, maximum int) int { - if value <= 0 { - return hardware_scale(value*2+100, minimum, normal) +func (c *HardwareClient) profile() hardware.Protocol { + if c.usb { + return hardware.DECtalkUSB() } - return hardware_scale(value*2-100, normal, maximum) + return hardware.Serial(c.dectalk) } - func (c *HardwareClient) commands() [3]string { - p := c.parameters - if c.dectalk { - return [3]string{fmt.Sprintf("[:ra %d]", dectalk_scale(p.Rate, 75, 180, 650)), fmt.Sprintf("[:dv ap %d]", dectalk_scale(p.Pitch, 50, 122, 350)), fmt.Sprintf("[:dv g5 %d]", hardware_scale(p.Volume, 60, 86))} - } - return [3]string{fmt.Sprintf("\x01%dS", hardware_scale(p.Rate, 0, 9)), fmt.Sprintf("\x01%dP", hardware_scale(p.Pitch, 0, 99)), fmt.Sprintf("\x01%dV", hardware_scale(p.Volume, 0, 9))} + rate, pitch, volume := float64(c.parameters.Rate), float64(c.parameters.Pitch), float64(c.parameters.Volume) + return c.profile().Commands(hardware.Parameters{Rate: &rate, Pitch: &pitch, Volume: &volume}) } func (c *HardwareClient) write(data []byte, generation uint64) error { @@ -179,20 +170,7 @@ func (c *HardwareClient) Say(text string) error { if err := c.configure(generation); err != nil { return ignore_hardware_cancel(err) } - var clean strings.Builder - for _, char := range text { - if char < 0x20 || char > 0x7e { - char = ' ' - } - clean.WriteRune(char) - } - prepared := clean.String() - if c.dectalk { - prepared = strings.ReplaceAll(prepared, "[:", "[ :") + "\x0b" - } else { - prepared += "\r" - } - return ignore_hardware_cancel(c.write([]byte(prepared), generation)) + return ignore_hardware_cancel(c.write(c.profile().Text(text), generation)) } func (c *HardwareClient) Cancel() error { @@ -200,12 +178,7 @@ func (c *HardwareClient) Cancel() error { if c.closed.Load() { return nil } - command := []byte{0x18} - if c.usb { - command = []byte{0x06} - } else if c.dectalk { - command = []byte{0x03} - } + command := c.profile().Cancel() return c.port.Cancel(command) } @@ -216,12 +189,7 @@ func (c *HardwareClient) Close() { c.generation.Add(1) // Cancel audible device buffers before releasing ownership. Port writes // are bounded, including when the device is disconnected or flow-stopped. - command := []byte{0x18} - if c.usb { - command = []byte{0x06} - } else if c.dectalk { - command = []byte{0x03} - } + command := c.profile().Cancel() _ = c.port.Cancel(command) c.port.Close() }