Files

754 lines
25 KiB
Go

// Cthulhu screen reader.
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
package speechdispatcher
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
const (
connectTimeout = 2 * time.Second
ioTimeout = 5 * time.Second
)
type Client struct {
socketAddress string
settings Settings
initialized bool
closed bool
background bool
aborted atomic.Bool
sockets atomic.Pointer[connectionPair]
conn net.Conn
reader *bufio.Reader
cancelConn net.Conn
cancelReader *bufio.Reader
clientID int
ioTimeout time.Duration
mutex sync.Mutex
cancelMutex sync.Mutex
settingsMutex sync.Mutex
notification func(reply) // Speaking mutex owns the active completion handler.
}
type connectionPair struct{ data, control net.Conn }
type Settings struct {
ClientName string
SystemFallback bool
OutputModule string
Rate *int
Pitch *int
Volume *int
Language string
SynthesisVoice string
Punctuation string
Capitalization string
}
type reply struct {
code int
text string
data []string
}
func New(socketAddress string) *Client {
return NewWithSettings(socketAddress, Settings{})
}
func NewWithSettings(socketAddress string, settings Settings) *Client {
if settings.ClientName == "" {
settings.ClientName = "screenreader"
}
return &Client{socketAddress: socketAddress, settings: cloneSettings(settings), ioTimeout: ioTimeout}
}
func cloneSettings(settings Settings) Settings {
for _, value := range []**int{&settings.Rate, &settings.Pitch, &settings.Volume} {
if *value != nil {
copy := **value
*value = &copy
}
}
return settings
}
// UpdateSettings replaces the complete speech configuration. A fresh pair of
// connections lets omitted settings regain server defaults and prevents a
// rejected SET command from leaving the active client partially configured.
// Preparation leaves Speak and Cancel available. Commit serializes with Speak,
// cancels the old client's queued speech, and switches the cancellation target.
// Only one update may prepare connections at a time; overlapping calls fail.
// Call this from a settings worker, never from the focus or input event path.
func (client *Client) UpdateSettings(ctx context.Context, settings Settings) error {
if !client.settingsMutex.TryLock() {
return errors.New("speech settings update already in progress")
}
defer client.settingsMutex.Unlock()
ctx, cancel := context.WithTimeout(ctx, ioTimeout)
defer cancel()
client.mutex.Lock()
original := client.conn
identity, fallback, background := client.settings.ClientName, client.settings.SystemFallback, client.background
client.mutex.Unlock()
if original == nil {
return errors.New("speech client is not connected")
}
if settings.ClientName == "" {
settings.ClientName = identity
}
settings.SystemFallback = fallback
candidate := NewWithSettings(client.socketAddress, settings)
candidate.background = background
defer candidate.Close(context.Background())
if err := candidate.Connect(ctx); err != nil {
return fmt.Errorf("prepare speech settings: %w", err)
}
client.mutex.Lock()
defer client.mutex.Unlock()
client.cancelMutex.Lock()
defer client.cancelMutex.Unlock()
if client.conn != original || client.aborted.Load() {
return errors.New("speech connection changed while preparing settings")
}
if err := ctx.Err(); err != nil {
return err
}
if err := client.sendCancelCommand(ctx, "CANCEL "+strconv.Itoa(client.clientID)); err != nil {
return fmt.Errorf("cancel speech before applying settings: %w", err)
}
// Swap ownership so the deferred close releases only the retired pair.
client.conn, candidate.conn = candidate.conn, client.conn
client.reader, candidate.reader = candidate.reader, client.reader
client.cancelConn, candidate.cancelConn = candidate.cancelConn, client.cancelConn
client.cancelReader, candidate.cancelReader = candidate.cancelReader, client.cancelReader
client.clientID, candidate.clientID = candidate.clientID, client.clientID
client.settings = candidate.settings
client.sockets.Store(&connectionPair{client.conn, client.cancelConn})
candidate.sockets.Store(&connectionPair{candidate.conn, candidate.cancelConn})
if client.aborted.Load() {
client.Abort()
return errors.New("speech client is closed")
}
return nil
}
// ErrRetuneNeedsReconnect reports a configuration the current connection
// cannot reach in place: a setting is being cleared and the server does not
// report the default a fresh connection would use. Callers may fall back to
// UpdateSettings, which cancels.
var ErrRetuneNeedsReconnect = errors.New("speech settings require a fresh connection")
// RetuneSettings applies a complete configuration to the current speaking
// connection without cancelling anything. Speech Dispatcher applies SET
// commands only to later SPEAK blocks, so utterances already queued keep the
// voice they were queued with and still finish. Use it for automatic changes,
// such as per-application voices, which must not interrupt speech; UpdateSettings
// remains the cancelling path for explicit user changes.
//
// SSIP cannot unset a value, so a setting being cleared is set to the value a
// fresh connection reports instead, and a cleared synthesis voice returns to
// the server's default voice type. When the server does not report a needed
// default, it fails with ErrRetuneNeedsReconnect before sending anything. A
// rejected SET closes the connection; the next Speak reconnects with the
// previous settings.
func (client *Client) RetuneSettings(ctx context.Context, settings Settings) error {
if !client.settingsMutex.TryLock() {
return errors.New("speech settings update already in progress")
}
defer client.settingsMutex.Unlock()
ctx, cancel := context.WithTimeout(ctx, ioTimeout)
defer cancel()
client.mutex.Lock()
defer client.mutex.Unlock()
settings = cloneSettings(settings)
settings.ClientName = client.settings.ClientName
settings.SystemFallback = client.settings.SystemFallback
if sameSettings(client.settings, settings) {
return nil
}
if err := client.ensureConnected(ctx); err != nil {
return err
}
commands := voiceCommands(settings)
if clearsSetting(client.settings, settings) {
address := client.conn.RemoteAddr()
defaults, err := readServerDefaults(ctx, address.Network(), address.String(), settings.ClientName)
if err != nil {
return fmt.Errorf("%w: read server defaults: %w", ErrRetuneNeedsReconnect, err)
}
applied, voiceType, err := restoreClearedSettings(client.settings, settings, defaults)
if err != nil {
return err
}
commands = voiceCommands(applied)
if voiceType != "" {
// VOICE_TYPE discards the named voice without changing language.
commands = append(commands, []string{"SET", "SELF", "VOICE_TYPE", voiceType})
}
}
for _, command := range commands {
if err := client.sendCommand(ctx, command); err != nil {
return fmt.Errorf("retune Speech Dispatcher %s: %w", command[2], err)
}
}
// Keep the requested form so a reconnection matches a fresh configuration.
client.settings = settings
return nil
}
// restoreClearedSettings fills each setting cleared from current to next with
// the server default. The returned voice type is set when a synthesis voice
// was cleared; it is empty otherwise.
func restoreClearedSettings(current, next Settings, defaults serverDefaults) (Settings, string, error) {
applied := cloneSettings(next)
for _, field := range []struct {
name string
current, def string
target *string
}{
{"output module", current.OutputModule, defaults.OutputModule, &applied.OutputModule},
{"punctuation", current.Punctuation, defaults.Punctuation, &applied.Punctuation},
{"language", current.Language, defaults.Language, &applied.Language},
} {
if field.current != "" && *field.target == "" {
if field.def == "" {
return Settings{}, "", fmt.Errorf("%w: server reports no default %s", ErrRetuneNeedsReconnect, field.name)
}
*field.target = field.def
}
}
// A named voice may have changed the effective language. Returning to an
// unspecified language must also undo language-to-module server routing.
if next.Language == "" && (current.Language != "" || current.SynthesisVoice != "" && next.SynthesisVoice == "") {
if defaults.Language == "" || next.OutputModule == "" && defaults.OutputModule == "" {
return Settings{}, "", fmt.Errorf("%w: server reports no default language or module", ErrRetuneNeedsReconnect)
}
applied.Language = defaults.Language
if next.OutputModule == "" {
applied.OutputModule = defaults.OutputModule
}
}
// The server's capitalization default is configurable but not queryable.
if current.Capitalization != "" && applied.Capitalization == "" {
return Settings{}, "", fmt.Errorf("%w: server cannot report default capitalization", ErrRetuneNeedsReconnect)
}
for _, field := range []struct {
name string
current, def *int
target **int
}{
{"rate", current.Rate, defaults.Rate, &applied.Rate},
{"pitch", current.Pitch, defaults.Pitch, &applied.Pitch},
{"volume", current.Volume, defaults.Volume, &applied.Volume},
} {
if field.current != nil && *field.target == nil {
if field.def == nil {
return Settings{}, "", fmt.Errorf("%w: server reports no default %s", ErrRetuneNeedsReconnect, field.name)
}
value := *field.def
*field.target = &value
}
}
voiceType := ""
if current.SynthesisVoice != "" && applied.SynthesisVoice == "" {
if defaults.VoiceType == "" {
return Settings{}, "", fmt.Errorf("%w: server reports no default voice type", ErrRetuneNeedsReconnect)
}
voiceType = defaults.VoiceType
}
return applied, voiceType, nil
}
func sameSettings(current, next Settings) bool {
return current.OutputModule == next.OutputModule && current.Punctuation == next.Punctuation &&
current.Capitalization == next.Capitalization && current.Language == next.Language &&
current.SynthesisVoice == next.SynthesisVoice && sameNumber(current.Rate, next.Rate) &&
sameNumber(current.Pitch, next.Pitch) && sameNumber(current.Volume, next.Volume)
}
func sameNumber(current, next *int) bool {
if current == nil || next == nil {
return current == next
}
return *current == *next
}
func clearsSetting(current, next Settings) bool {
for _, pair := range [][2]string{
{current.OutputModule, next.OutputModule}, {current.Punctuation, next.Punctuation},
{current.Capitalization, next.Capitalization}, {current.Language, next.Language},
{current.SynthesisVoice, next.SynthesisVoice},
} {
if pair[0] != "" && pair[1] == "" {
return true
}
}
for _, pair := range [][2]*int{{current.Rate, next.Rate}, {current.Pitch, next.Pitch}, {current.Volume, next.Volume}} {
if pair[0] != nil && pair[1] == nil {
return true
}
}
return false
}
func (client *Client) Connect(ctx context.Context) error {
client.mutex.Lock()
defer client.mutex.Unlock()
client.cancelMutex.Lock()
defer client.cancelMutex.Unlock()
if client.conn != nil || client.cancelConn != nil {
return errors.New("speech client already connected")
}
if client.closed || client.aborted.Load() {
return errors.New("speech client is closed")
}
if err := client.connectLocked(ctx); err != nil {
return err
}
client.initialized = true
return nil
}
// connectLocked replaces both channels as one session; both locks are held.
func (client *Client) connectLocked(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, ioTimeout)
defer cancel()
endpoint, err := ResolveAddress(client.socketAddress)
if err != nil {
return err
}
dialer := net.Dialer{Timeout: connectTimeout}
dial := Dialer(dialer.DialContext)
if client.settings.SystemFallback && AutomaticAddress(client.socketAddress) {
dial = WithSystemFallback(dial)
}
conn, err := ConnectWithAutospawn(ctx, endpoint, dial, SpawnServer)
if err != nil {
return fmt.Errorf("connect to Speech Dispatcher at %s: %w", endpoint.Address, err)
}
if endpoint.Network == "unix" {
endpoint.Address = conn.RemoteAddr().String()
}
cancelConn, err := dialer.DialContext(ctx, endpoint.Network, endpoint.Address)
if err != nil {
_ = conn.Close()
return fmt.Errorf("connect cancellation channel to Speech Dispatcher at %s: %w", endpoint.Address, err)
}
client.sockets.Store(&connectionPair{conn, cancelConn})
if client.aborted.Load() {
conn.Close()
cancelConn.Close()
return errors.New("speech client is closed")
}
client.conn = conn
client.reader = bufio.NewReader(conn)
client.cancelConn = cancelConn
client.cancelReader = bufio.NewReader(cancelConn)
if err := client.initialize(ctx); err != nil {
_ = conn.Close()
_ = cancelConn.Close()
client.conn, client.reader = nil, nil
client.cancelConn, client.cancelReader = nil, nil
client.clientID = 0
return err
}
return nil
}
// initialize runs with both connection locks held. Cancellation always targets
// the speaking connection's ID, never the separate control connection or ALL.
func (client *Client) initialize(ctx context.Context) error {
if err := client.applySettings(ctx); err != nil {
return err
}
finish, err := prepareIO(ctx, client.conn, client.ioTimeout)
if err != nil {
return err
}
defer finish()
if _, err := client.conn.Write([]byte("HISTORY GET CLIENT_ID\r\n")); err != nil {
return fmt.Errorf("request speech client ID: %w", err)
}
response, err := client.readReply()
if err != nil {
return err
}
if response.code != 245 || len(response.data) != 1 {
return fmt.Errorf("invalid Speech Dispatcher client ID reply: %d %s (expected code 245 and one ID)", response.code, response.text)
}
clientID, err := strconv.Atoi(response.data[0])
if err != nil || clientID <= 0 {
return errors.New("invalid Speech Dispatcher client ID")
}
client.clientID = clientID
return client.sendCancelCommand(ctx, "SET SELF CLIENT_NAME "+client.settings.ClientName+":"+client.settings.ClientName+":cancel")
}
func (client *Client) applySettings(ctx context.Context) error {
if client.settings.ClientName == "" {
client.settings.ClientName = "screenreader"
}
commands := [][]string{
{"SET", "SELF", "CLIENT_NAME", client.settings.ClientName + ":" + client.settings.ClientName + ":main"},
{"SET", "SELF", "PRIORITY", "MESSAGE"},
}
commands = append(commands, voiceCommands(client.settings)...)
if client.background {
commands = append(commands, []string{"SET", "SELF", "PRIORITY", "TEXT"})
}
for _, command := range commands {
if err := client.sendCommand(ctx, command); err != nil {
return fmt.Errorf("configure Speech Dispatcher %s: %w", command[2], err)
}
}
return nil
}
// voiceCommands lists the SET commands for every configured voice setting in
// the order a fresh connection applies them. Language precedes module because
// server language routing can change the module. The named voice comes last.
func voiceCommands(settings Settings) [][]string {
var commands [][]string
if settings.Punctuation != "" {
commands = append(commands, []string{"SET", "SELF", "PUNCTUATION", settings.Punctuation})
}
if settings.Capitalization != "" {
commands = append(commands, []string{"SET", "SELF", "CAP_LET_RECOGN", settings.Capitalization})
}
for _, setting := range []struct {
name string
value *int
}{
{name: "RATE", value: settings.Rate},
{name: "PITCH", value: settings.Pitch},
{name: "VOLUME", value: settings.Volume},
} {
if setting.value != nil {
commands = append(commands, []string{"SET", "SELF", setting.name, strconv.Itoa(*setting.value)})
}
}
if settings.Language != "" {
commands = append(commands, []string{"SET", "SELF", "LANGUAGE", settings.Language})
}
if settings.OutputModule != "" {
commands = append(commands, []string{"SET", "SELF", "OUTPUT_MODULE", settings.OutputModule})
}
if settings.SynthesisVoice != "" {
commands = append(commands, []string{"SET", "SELF", "SYNTHESIS_VOICE", settings.SynthesisVoice})
}
return commands
}
func (client *Client) sendCommand(ctx context.Context, fields []string) (result error) {
defer func() {
if result != nil && client.conn != nil {
client.conn.Close()
client.conn, client.reader = nil, nil
}
}()
for _, field := range fields {
if strings.ContainsAny(field, "\r\n\x00") {
return errors.New("SSIP command contains a control character")
}
}
finish, err := prepareIO(ctx, client.conn, client.ioTimeout)
if err != nil {
return err
}
defer finish()
if _, err := client.conn.Write([]byte(strings.Join(fields, " ") + "\r\n")); err != nil {
return fmt.Errorf("send SSIP command: %w", err)
}
commandReply, err := client.readReply()
if err != nil {
return err
}
if commandReply.code < 200 || commandReply.code >= 300 {
return fmt.Errorf("SSIP command rejected with %d %s", commandReply.code, commandReply.text)
}
return nil
}
func (client *Client) Speak(ctx context.Context, text string) (result error) {
client.mutex.Lock()
defer client.mutex.Unlock()
if err := client.ensureConnected(ctx); err != nil {
return err
}
return client.speak(ctx, text)
}
// SetBackgroundPriority makes this isolated client yield to ordinary MESSAGE
// output. Call before speaking; relay priorities must never select SSIP priority.
// TEXT waits behind MESSAGE and is cancelled when new MESSAGE output arrives.
// Protocol: https://github.com/brailcom/speechd/blob/master/doc/ssip.texi
func (client *Client) SetBackgroundPriority(ctx context.Context) error {
client.mutex.Lock()
defer client.mutex.Unlock()
if err := client.ensureConnected(ctx); err != nil {
return err
}
if client.conn == nil {
return errors.New("speech client is not connected")
}
if err := client.sendCommand(ctx, []string{"SET", "SELF", "PRIORITY", "TEXT"}); err != nil {
return err
}
client.background = true
return nil
}
// SpeakCharacter gives the synthesizer a single character as a character,
// preserving repeated adjacent letters during caret and flat review. Spoken
// names such as "space" still use normal speech.
func (client *Client) SpeakCharacter(ctx context.Context, text string) error {
client.mutex.Lock()
defer client.mutex.Unlock()
if err := client.ensureConnected(ctx); err != nil {
return err
}
if utf8.RuneCountInString(text) != 1 || strings.ContainsAny(text, "\r\n\x00") {
return client.speak(ctx, text)
}
if client.conn == nil {
return errors.New("speech client is not connected")
}
return client.sendCommand(ctx, []string{"CHAR", text})
}
func (client *Client) speak(ctx context.Context, text string) (result error) {
text, err := normalizeSpeakText(text)
if err != nil {
return err
}
return client.speakBlock(ctx, text)
}
// text is validated by the caller. Dot escaping applies to every data line,
// including lines containing what would otherwise be the SSIP terminator.
func (client *Client) speakBlock(ctx context.Context, text string) (result error) {
if client.conn == nil {
return errors.New("speech client is not connected")
}
finish, err := prepareIO(ctx, client.conn, client.ioTimeout)
if err != nil {
return err
}
defer finish()
defer func() {
if result != nil {
// A partial exchange cannot safely be reused: a late reply could
// otherwise be mistaken for the next command's acknowledgment.
_ = client.conn.Close()
client.conn, client.reader = nil, nil
}
}()
// SSIP doubles a leading dot so it cannot terminate the speech block.
if strings.HasPrefix(text, ".") {
text = "." + text
}
text = strings.ReplaceAll(text, "\r\n.", "\r\n..")
request := "SPEAK\r\n" + text + "\r\n.\r\n"
if _, err := client.conn.Write([]byte(request)); err != nil {
return fmt.Errorf("send speech block: %w", err)
}
accepted, err := client.readReply()
if err != nil {
return err
}
if accepted.code != 230 {
return fmt.Errorf("speech block rejected with %d %s", accepted.code, accepted.text)
}
queued, err := client.readReply()
if err != nil {
return err
}
if queued.code < 200 || queued.code >= 300 {
return fmt.Errorf("speech queue rejected with %d %s", queued.code, queued.text)
}
return nil
}
func (client *Client) Cancel(ctx context.Context) error {
client.cancelMutex.Lock()
defer client.cancelMutex.Unlock()
return client.sendCancelCommand(ctx, "CANCEL "+strconv.Itoa(client.clientID))
}
func (client *Client) Close(context.Context) error {
client.Abort()
client.mutex.Lock()
defer client.mutex.Unlock()
client.cancelMutex.Lock()
defer client.cancelMutex.Unlock()
client.closed = true
conn := client.conn
client.conn = nil
client.reader = nil
cancelConn := client.cancelConn
client.cancelConn = nil
client.cancelReader = nil
client.clientID = 0
if conn == nil && cancelConn == nil {
return nil
}
closeError := error(nil)
if conn != nil {
if err := conn.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
closeError = fmt.Errorf("close Speech Dispatcher connection: %w", err)
}
}
if cancelConn != nil {
if err := cancelConn.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
cancelError := fmt.Errorf("close Speech Dispatcher cancellation connection: %w", err)
closeError = errors.Join(closeError, cancelError)
}
}
return closeError
}
// prepareIO makes cancellation interrupt blocked socket I/O. The cleanup waits
// for a started callback before the next operation can install its deadline.
func prepareIO(ctx context.Context, conn net.Conn, timeout time.Duration) (func(), error) {
if err := ctx.Err(); err != nil {
return nil, err
}
deadline := time.Now().Add(timeout)
if contextDeadline, ok := ctx.Deadline(); ok && contextDeadline.Before(deadline) {
deadline = contextDeadline
}
if err := conn.SetDeadline(deadline); err != nil {
return nil, fmt.Errorf("set Speech Dispatcher deadline: %w", err)
}
done := make(chan struct{})
stop := context.AfterFunc(ctx, func() {
_ = conn.SetDeadline(time.Now())
close(done)
})
return func() {
if !stop() {
<-done
}
}, nil
}
func (client *Client) readReply() (reply, error) {
for {
response, err := readReply(client.reader)
if err != nil || response.code < 700 || response.code >= 800 {
return response, err
}
if client.notification != nil {
client.notification(response)
}
}
}
func (client *Client) sendCancelCommand(ctx context.Context, command string) (result error) {
if client.cancelConn == nil {
return errors.New("speech cancellation channel is not connected")
}
finish, err := prepareIO(ctx, client.cancelConn, client.ioTimeout)
if err != nil {
return err
}
defer finish()
defer func() {
if result != nil {
_ = client.cancelConn.Close()
client.cancelConn, client.cancelReader = nil, nil
}
}()
if _, err := client.cancelConn.Write([]byte(command + "\r\n")); err != nil {
return fmt.Errorf("send Speech Dispatcher cancellation command: %w", err)
}
cancelReply, err := readReply(client.cancelReader)
if err != nil {
return err
}
if cancelReply.code < 200 || cancelReply.code >= 300 {
return fmt.Errorf("Speech Dispatcher cancellation rejected with %d %s", cancelReply.code, cancelReply.text)
}
return nil
}
func readReply(reader *bufio.Reader) (reply, error) {
var final reply
total := 0
for count := 0; count < 65536; count++ {
part, err := reader.ReadSlice('\n')
line := string(part)
total += len(line)
if total > 8<<20 {
return final, errors.New("SSIP reply exceeds byte limit")
}
if err != nil {
return final, fmt.Errorf("read Speech Dispatcher reply: %w", err)
}
line = strings.TrimRight(line, "\r\n")
if len(line) < 4 || line[3] != '-' && line[3] != ' ' {
return final, fmt.Errorf("invalid Speech Dispatcher reply %q", line)
}
code, err := strconv.Atoi(line[:3])
if err != nil {
return final, fmt.Errorf("parse Speech Dispatcher reply %q: %w", line, err)
}
if final.code != 0 && final.code != code {
return final, errors.New("inconsistent SSIP reply codes")
}
final.code = code
final.text = strings.TrimSpace(line[4:])
if line[3] == ' ' {
return final, nil
}
final.data = append(final.data, final.text)
}
return final, errors.New("SSIP reply exceeds line limit")
}
func normalizeSpeakText(text string) (string, error) {
text = strings.ToValidUTF8(text, "�")
text = strings.Join(strings.Fields(text), " ")
if text == "" {
return "", errors.New("speech text is empty")
}
return text, nil
}