Consolidate shared UI, hardware transport, and translation tooling
This commit is contained in:
1 parent
ed6951f4cd
commit
2c612de63b
61 files changed
+2417
-1573
No files matched your search
@@ -0,0 +1,205 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//go:build linux && cgo
|
||||
|
||||
#include "native.h"
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/types.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct SrcommonSerial {
|
||||
int fd;
|
||||
struct termios original;
|
||||
};
|
||||
|
||||
SrcommonSerial *srcommon_serial_open(const char *path, int baud, int xon, int *status) {
|
||||
SrcommonSerial *port = calloc(1, sizeof(*port));
|
||||
*status = -ENOMEM;
|
||||
if (!port) return NULL;
|
||||
port->fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
|
||||
if (port->fd < 0) goto failed;
|
||||
// A short-lived candidate must never configure another reader's device.
|
||||
if (flock(port->fd, LOCK_EX | LOCK_NB) < 0) goto failed;
|
||||
if (tcgetattr(port->fd, &port->original) < 0) goto failed;
|
||||
struct termios options = port->original;
|
||||
cfmakeraw(&options);
|
||||
options.c_cflag |= CLOCAL | CREAD;
|
||||
options.c_cflag &= ~(CRTSCTS | CSTOPB);
|
||||
options.c_iflag &= ~(IXON | IXOFF | IXANY);
|
||||
if (xon) options.c_iflag |= IXON;
|
||||
options.c_cc[VSTART] = 0x11;
|
||||
options.c_cc[VSTOP] = 0x13;
|
||||
speed_t speed;
|
||||
switch (baud) {
|
||||
case 1200: speed = B1200; break;
|
||||
case 2400: speed = B2400; break;
|
||||
case 4800: speed = B4800; break;
|
||||
case 9600: speed = B9600; break;
|
||||
case 19200: speed = B19200; break;
|
||||
case 38400: speed = B38400; break;
|
||||
case 57600: speed = B57600; break;
|
||||
case 115200: speed = B115200; break;
|
||||
default: errno = EINVAL; goto failed;
|
||||
}
|
||||
cfsetispeed(&options, speed);
|
||||
cfsetospeed(&options, speed);
|
||||
options.c_cc[VMIN] = 0;
|
||||
options.c_cc[VTIME] = 0;
|
||||
if (tcsetattr(port->fd, TCSANOW, &options) < 0) goto failed;
|
||||
*status = 0;
|
||||
return port;
|
||||
failed:
|
||||
*status = -errno;
|
||||
if (port->fd >= 0) close(port->fd);
|
||||
free(port);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int srcommon_serial_write(SrcommonSerial *port, const void *data, size_t length) {
|
||||
ssize_t result = write(port->fd, data, length);
|
||||
return result < 0 ? -errno : (int)result;
|
||||
}
|
||||
|
||||
int srcommon_serial_cancel(SrcommonSerial *port, unsigned char command) {
|
||||
if (tcflush(port->fd, TCOFLUSH) < 0) return -errno;
|
||||
if (tcflow(port->fd, TCOON) < 0) return -errno;
|
||||
// TCOON clears an explicit tcflow stop, but not a received XOFF in Linux's
|
||||
// N_TTY discipline. Temporarily clearing IXON restarts that output path.
|
||||
// Restore software flow control immediately after submitting the cancel.
|
||||
struct termios options;
|
||||
if (tcgetattr(port->fd, &options) < 0) return -errno;
|
||||
int xon = (options.c_iflag & IXON) != 0;
|
||||
if (xon) {
|
||||
struct termios resumed = options;
|
||||
resumed.c_iflag &= ~IXON;
|
||||
if (tcsetattr(port->fd, TCSANOW, &resumed) < 0) return -errno;
|
||||
}
|
||||
int result = srcommon_serial_write(port, &command, 1);
|
||||
if (xon && tcsetattr(port->fd, TCSANOW, &options) < 0) return -errno;
|
||||
return result;
|
||||
}
|
||||
|
||||
void srcommon_serial_close(SrcommonSerial *port) {
|
||||
tcsetattr(port->fd, TCSANOW, &port->original);
|
||||
close(port->fd);
|
||||
free(port);
|
||||
}
|
||||
|
||||
// Optional libusb 1.0 ABI, resolved at runtime like Enchant. Neither headers
|
||||
// nor a link-time libusb dependency are required for other speech drivers.
|
||||
typedef struct libusb_context USBContext;
|
||||
typedef struct libusb_device USBDevice;
|
||||
typedef struct libusb_device_handle USBHandle;
|
||||
struct USBDescriptor {
|
||||
uint8_t length, type;
|
||||
uint16_t usb;
|
||||
uint8_t device_class, subclass, protocol, packet_size;
|
||||
uint16_t vendor, product, device;
|
||||
uint8_t manufacturer, product_name, serial, configurations;
|
||||
};
|
||||
|
||||
struct SrcommonUSB {
|
||||
void *library;
|
||||
USBContext *context;
|
||||
USBHandle *handle;
|
||||
int claimed;
|
||||
int (*init)(USBContext **);
|
||||
void (*exit)(USBContext *);
|
||||
ssize_t (*get_device_list)(USBContext *, USBDevice ***);
|
||||
void (*free_device_list)(USBDevice **, int);
|
||||
int (*get_device_descriptor)(USBDevice *, struct USBDescriptor *);
|
||||
int (*open)(USBDevice *, USBHandle **);
|
||||
void (*close)(USBHandle *);
|
||||
int (*get_configuration)(USBHandle *, int *);
|
||||
int (*set_configuration)(USBHandle *, int);
|
||||
int (*claim_interface)(USBHandle *, int);
|
||||
int (*release_interface)(USBHandle *, int);
|
||||
int (*bulk_transfer)(USBHandle *, unsigned char, unsigned char *, int, int *, unsigned int);
|
||||
};
|
||||
|
||||
void srcommon_usb_close(SrcommonUSB *port) {
|
||||
if (!port) return;
|
||||
if (port->claimed) port->release_interface(port->handle, 0);
|
||||
if (port->handle) port->close(port->handle);
|
||||
if (port->context) port->exit(port->context);
|
||||
if (port->library) dlclose(port->library);
|
||||
free(port);
|
||||
}
|
||||
|
||||
static SrcommonUSB *load_usb(void) {
|
||||
SrcommonUSB *port = calloc(1, sizeof(*port));
|
||||
if (!port) return NULL;
|
||||
port->library = dlopen("libusb-1.0.so.0", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!port->library) goto failed;
|
||||
#define LOAD(field) port->field = dlsym(port->library, "libusb_" #field); if (!port->field) goto failed
|
||||
LOAD(init); LOAD(exit); LOAD(get_device_list); LOAD(free_device_list);
|
||||
LOAD(get_device_descriptor); LOAD(open); LOAD(close);
|
||||
LOAD(get_configuration); LOAD(set_configuration);
|
||||
LOAD(claim_interface); LOAD(release_interface); LOAD(bulk_transfer);
|
||||
#undef LOAD
|
||||
return port;
|
||||
failed:
|
||||
srcommon_usb_close(port);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int srcommon_usb_available(void) {
|
||||
SrcommonUSB *port = load_usb();
|
||||
if (!port) return 0;
|
||||
srcommon_usb_close(port);
|
||||
return 1;
|
||||
}
|
||||
|
||||
SrcommonUSB *srcommon_usb_open(int *status) {
|
||||
*status = -100;
|
||||
SrcommonUSB *port = load_usb();
|
||||
if (!port) return NULL;
|
||||
*status = port->init(&port->context);
|
||||
if (*status < 0) goto failed;
|
||||
USBDevice **devices = NULL;
|
||||
ssize_t count = port->get_device_list(port->context, &devices);
|
||||
if (count < 0) { *status = (int)count; goto failed; }
|
||||
USBDevice *selected = NULL;
|
||||
int matches = 0;
|
||||
for (ssize_t index = 0; index < count; index++) {
|
||||
struct USBDescriptor descriptor;
|
||||
if (port->get_device_descriptor(devices[index], &descriptor) == 0 &&
|
||||
descriptor.vendor == 0x0dd0 && descriptor.product == 0x2001) {
|
||||
selected = devices[index];
|
||||
matches++;
|
||||
}
|
||||
}
|
||||
*status = matches == 0 ? -4 : -101;
|
||||
if (matches == 1) *status = port->open(selected, &port->handle);
|
||||
port->free_device_list(devices, 1);
|
||||
if (*status < 0) goto failed;
|
||||
int configuration = 0;
|
||||
*status = port->get_configuration(port->handle, &configuration);
|
||||
if (*status < 0) goto failed;
|
||||
if (configuration == 0) {
|
||||
*status = port->set_configuration(port->handle, 1);
|
||||
if (*status < 0) goto failed;
|
||||
}
|
||||
*status = port->claim_interface(port->handle, 0);
|
||||
if (*status < 0) goto failed;
|
||||
port->claimed = 1;
|
||||
return port;
|
||||
failed:
|
||||
srcommon_usb_close(port);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int srcommon_usb_write(SrcommonUSB *port, unsigned char endpoint, void *data, int length) {
|
||||
int transferred = 0;
|
||||
int result = port->bulk_transfer(port->handle, endpoint, data, length, &transferred, 1000);
|
||||
// Never replay a partial failed transfer: it may already be on the wire.
|
||||
if (result < 0) return result;
|
||||
return transferred == length ? 0 : -102;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef SRCOMMON_HARDWARE_TRANSPORT_H
|
||||
#define SRCOMMON_HARDWARE_TRANSPORT_H
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct SrcommonSerial SrcommonSerial;
|
||||
SrcommonSerial *srcommon_serial_open(const char *path, int baud, int xon, int *status);
|
||||
int srcommon_serial_write(SrcommonSerial *port, const void *data, size_t length);
|
||||
int srcommon_serial_cancel(SrcommonSerial *port, unsigned char command);
|
||||
void srcommon_serial_close(SrcommonSerial *port);
|
||||
|
||||
typedef struct SrcommonUSB SrcommonUSB;
|
||||
int srcommon_usb_available(void);
|
||||
SrcommonUSB *srcommon_usb_open(int *status);
|
||||
int srcommon_usb_write(SrcommonUSB *port, unsigned char endpoint, void *data, int length);
|
||||
void srcommon_usb_close(SrcommonUSB *port);
|
||||
#endif
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//go:build linux && cgo
|
||||
|
||||
package transport
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: -ldl
|
||||
#include <stdlib.h>
|
||||
#include "native.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const serialPacketSize = 64
|
||||
|
||||
type serialPort struct {
|
||||
mu sync.Mutex
|
||||
native *C.SrcommonSerial
|
||||
}
|
||||
|
||||
func openSerial(path string, baud int, xon bool) (Port, error) {
|
||||
cPath := C.CString(path)
|
||||
defer C.free(unsafe.Pointer(cPath))
|
||||
flow := C.int(0)
|
||||
if xon {
|
||||
flow = 1
|
||||
}
|
||||
var status C.int
|
||||
native := C.srcommon_serial_open(cPath, C.int(baud), flow, &status)
|
||||
if native == nil {
|
||||
return nil, fmt.Errorf("open hardware speech %s: %w", path, syscall.Errno(-status))
|
||||
}
|
||||
return &serialPort{native: native}, nil
|
||||
}
|
||||
|
||||
func (p *serialPort) Write(data []byte, canceled func() bool) error {
|
||||
for len(data) > 0 {
|
||||
p.mu.Lock()
|
||||
if canceled() {
|
||||
p.mu.Unlock()
|
||||
return ErrCanceled
|
||||
}
|
||||
if p.native == nil {
|
||||
p.mu.Unlock()
|
||||
return errors.New("serial speech closed")
|
||||
}
|
||||
count := int(C.srcommon_serial_write(p.native, unsafe.Pointer(&data[0]), C.size_t(min(len(data), serialPacketSize))))
|
||||
p.mu.Unlock()
|
||||
if count > 0 {
|
||||
data = data[count:]
|
||||
continue
|
||||
}
|
||||
if count == 0 {
|
||||
return io.ErrNoProgress
|
||||
}
|
||||
err := syscall.Errno(-count)
|
||||
if !errors.Is(err, syscall.EAGAIN) && !errors.Is(err, syscall.EINTR) {
|
||||
return fmt.Errorf("write serial speech: %w", err)
|
||||
}
|
||||
// XOFF can legitimately last while buffered speech is being spoken.
|
||||
// Each write is nonblocking; only this caller waits, and cancellation
|
||||
// or shutdown breaks the retry loop without waiting for XON.
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *serialPort) Cancel(command []byte) error {
|
||||
if len(command) == 0 {
|
||||
return errors.New("empty hardware speech cancel command")
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.native == nil {
|
||||
return nil
|
||||
}
|
||||
deadline := time.Now().Add(cancelTimeout)
|
||||
for {
|
||||
count := int(C.srcommon_serial_cancel(p.native, C.uchar(command[0])))
|
||||
if count == 1 {
|
||||
return nil
|
||||
}
|
||||
if count == 0 {
|
||||
return io.ErrNoProgress
|
||||
}
|
||||
err := syscall.Errno(-count)
|
||||
if (!errors.Is(err, syscall.EAGAIN) && !errors.Is(err, syscall.EINTR)) || time.Now().After(deadline) {
|
||||
return fmt.Errorf("cancel serial speech: %w", err)
|
||||
}
|
||||
// Resuming terminal output can complete asynchronously. Retry the
|
||||
// immediate byte within a bounded interval, rather than treating the
|
||||
// first EAGAIN after TCOON as a device failure.
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *serialPort) Close() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.native != nil {
|
||||
C.srcommon_serial_close(p.native)
|
||||
p.native = nil
|
||||
}
|
||||
}
|
||||
|
||||
func openUSB() (*usbPort, error) {
|
||||
var status C.int
|
||||
native := C.srcommon_usb_open(&status)
|
||||
if native == nil {
|
||||
return nil, usbError(int(status))
|
||||
}
|
||||
return &usbPort{
|
||||
send: func(endpoint byte, data []byte) error {
|
||||
status := C.srcommon_usb_write(native, C.uchar(endpoint), unsafe.Pointer(&data[0]), C.int(len(data)))
|
||||
if status != 0 {
|
||||
return usbError(int(status))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
close: func() { C.srcommon_usb_close(native) },
|
||||
}, nil
|
||||
}
|
||||
|
||||
func usbAvailable() error {
|
||||
if C.srcommon_usb_available() == 0 {
|
||||
return usbError(-100)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//go:build linux && cgo
|
||||
|
||||
package transport
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func never() bool { return false }
|
||||
|
||||
func serialPty(t *testing.T) (*os.File, string) {
|
||||
t.Helper()
|
||||
fd, err := syscall.Open("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
master := os.NewFile(uintptr(fd), "serial fixture")
|
||||
t.Cleanup(func() { _ = master.Close() })
|
||||
var unlock int32
|
||||
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&unlock))); err != 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var number uint32
|
||||
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&number))); err != 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return master, fmt.Sprintf("/dev/pts/%d", number)
|
||||
}
|
||||
|
||||
func readSerial(t *testing.T, master *os.File, count int) []byte {
|
||||
t.Helper()
|
||||
var result []byte
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for len(result) < count && time.Now().Before(deadline) {
|
||||
buffer := make([]byte, count-len(result))
|
||||
n, err := syscall.Read(int(master.Fd()), buffer)
|
||||
if n > 0 {
|
||||
result = append(result, buffer[:n]...)
|
||||
}
|
||||
if err != nil && !errors.Is(err, syscall.EAGAIN) && !errors.Is(err, syscall.EINTR) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n <= 0 {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
if len(result) != count {
|
||||
t.Fatalf("read %q (%d of %d)", result, len(result), count)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func drainSerial(t *testing.T, master *os.File) {
|
||||
t.Helper()
|
||||
var buffer [32768]byte
|
||||
for {
|
||||
_, err := syscall.Read(int(master.Fd()), buffer[:])
|
||||
if errors.Is(err, syscall.EAGAIN) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertSerialIdle(t *testing.T, master *os.File) {
|
||||
t.Helper()
|
||||
var buffer [128]byte
|
||||
if n, err := syscall.Read(int(master.Fd()), buffer[:]); n > 0 || !errors.Is(err, syscall.EAGAIN) {
|
||||
t.Fatalf("unexpected bytes %q, %v", buffer[:max(n, 0)], err)
|
||||
}
|
||||
}
|
||||
|
||||
func serialTermios(t *testing.T, fd int) syscall.Termios {
|
||||
t.Helper()
|
||||
var value syscall.Termios
|
||||
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TCGETS, uintptr(unsafe.Pointer(&value))); err != 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func TestSerialLifecycleLockAndTermiosRestore(t *testing.T) {
|
||||
for _, xon := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint("xon=", xon), func(t *testing.T) {
|
||||
master, path := serialPty(t)
|
||||
slave, err := syscall.Open(path, syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = syscall.Close(slave) }()
|
||||
original := serialTermios(t, slave)
|
||||
port, err := OpenSerial(path, 19200, xon)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer port.Close()
|
||||
configured := serialTermios(t, slave)
|
||||
if configured.Cflag&syscall.CS8 == 0 || configured.Lflag&(syscall.ICANON|syscall.ECHO) != 0 || configured.Iflag&(syscall.IXOFF|syscall.IXANY) != 0 || (configured.Iflag&syscall.IXON != 0) != xon {
|
||||
t.Fatal("serial mode", configured)
|
||||
}
|
||||
assertSerialIdle(t, master) // Opening never speaks.
|
||||
if other, err := OpenSerial(path, 19200, xon); err == nil {
|
||||
other.Close()
|
||||
t.Fatal("a second owner acquired a locked serial device")
|
||||
}
|
||||
if err := port.Write([]byte("hello\r"), never); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(readSerial(t, master, 6)); got != "hello\r" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if err := port.Cancel([]byte{0x18}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(readSerial(t, master, 1)); got != "\x18" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
port.Close()
|
||||
port.Close()
|
||||
if restored := serialTermios(t, slave); restored != original {
|
||||
t.Fatal("termios not restored", restored, original)
|
||||
}
|
||||
reopened, err := OpenSerial(path, 0, xon)
|
||||
if err != nil {
|
||||
t.Fatal("serial lock survived close", err)
|
||||
}
|
||||
reopened.Close()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerialCancellationStopsLargeWrite(t *testing.T) {
|
||||
master, path := serialPty(t)
|
||||
port, err := Open("dectalk", path, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer port.Close()
|
||||
var stale atomic.Bool
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- port.Write([]byte(strings.Repeat("x", 1<<20)), stale.Load) }()
|
||||
if string(readSerial(t, master, 1)) != "x" {
|
||||
t.Fatal("write did not start")
|
||||
}
|
||||
stale.Store(true)
|
||||
if err := port.Cancel([]byte{0x03}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrCanceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cancellation waited behind the write")
|
||||
}
|
||||
drainSerial(t, master)
|
||||
if err := port.Write([]byte("fresh"), never); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(readSerial(t, master, 5)); got != "fresh" {
|
||||
t.Fatalf("stale output %q", got)
|
||||
}
|
||||
assertSerialIdle(t, master)
|
||||
}
|
||||
|
||||
func TestSerialDisconnectReturnsError(t *testing.T) {
|
||||
master, path := serialPty(t)
|
||||
port, err := Open("litetalk", path, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer port.Close()
|
||||
_ = master.Close()
|
||||
if err := port.Write([]byte("after disconnect"), never); err == nil {
|
||||
t.Fatal("disconnected serial device accepted a write")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSerialXoffPauseRemainsCancelable(t *testing.T) {
|
||||
master, path := serialPty(t)
|
||||
port, err := Open("dectalk", path, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer port.Close()
|
||||
// Packet mode acknowledges that the terminal processed XOFF before the
|
||||
// write starts; this does not rely on a sleep or on filling a PTY buffer.
|
||||
packetMode := int32(1)
|
||||
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, master.Fd(), syscall.TIOCPKT, uintptr(unsafe.Pointer(&packetMode))); err != 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := syscall.Write(int(master.Fd()), []byte{0x13}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := readSerial(t, master, 1)[0]; got&syscall.TIOCPKT_STOP == 0 {
|
||||
t.Fatal("XOFF was not processed", got)
|
||||
}
|
||||
packetMode = 0
|
||||
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, master.Fd(), syscall.TIOCPKT, uintptr(unsafe.Pointer(&packetMode))); err != 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stale atomic.Bool
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- port.Write([]byte("paused"), stale.Load) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatal("a normal flow pause ended the write", err)
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
stale.Store(true)
|
||||
if err := port.Cancel([]byte{0x03}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
slave, err := syscall.Open(path, syscall.O_RDWR|syscall.O_NOCTTY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
configured := serialTermios(t, slave)
|
||||
_ = syscall.Close(slave)
|
||||
if configured.Iflag&syscall.IXON == 0 {
|
||||
t.Fatal("cancellation did not restore XON/XOFF")
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrCanceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cancel failed during flow pause")
|
||||
}
|
||||
if got := string(readSerial(t, master, 1)); got != "\x03" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if err := port.Write([]byte("resumed"), never); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := string(readSerial(t, master, 7)); got != "resumed" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
// The fixture is a private libusb-1.0.so.0 built from testdata; it never
|
||||
// touches real USB devices, so this runs without DECtalk hardware.
|
||||
func TestNativeUSBUsesOptionalABIAndReleasesResources(t *testing.T) {
|
||||
if _, err := exec.LookPath("cc"); err != nil {
|
||||
t.Skip("needs a C compiler for the libusb fixture")
|
||||
}
|
||||
root := t.TempDir()
|
||||
library := filepath.Join(root, "libusb-1.0.so.0")
|
||||
if output, err := exec.Command("cc", "-shared", "-fPIC", "-Wall", "-Wextra", "-Werror", "-o", library, "testdata/usb_fixture.c").CombinedOutput(); err != nil {
|
||||
t.Fatalf("build USB fixture: %v: %s", err, output)
|
||||
}
|
||||
for _, mode := range []string{"ok", "unconfigured", "missing", "multiple", "denied", "busy", "short", "timeout"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
log := filepath.Join(t.TempDir(), "usb.log")
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestNativeUSBFixtureProcess$")
|
||||
cmd.Env = append(os.Environ(), "LD_LIBRARY_PATH="+root, "SRCOMMON_USB_FIXTURE=1", "USB_FIXTURE_MODE="+mode, "USB_FIXTURE_LOG="+log)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("fixture process: %v: %s", err, output)
|
||||
}
|
||||
data, err := os.ReadFile(log)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(data)
|
||||
if !strings.HasPrefix(text, "init\nlist\n") || !strings.Contains(text, "free-list\n") || !strings.HasSuffix(text, "exit\n") {
|
||||
t.Fatal("USB cleanup", text)
|
||||
}
|
||||
opened := mode != "missing" && mode != "multiple" && mode != "denied"
|
||||
if strings.Contains(text, "\nclose\n") != opened {
|
||||
t.Fatal("handle cleanup", text)
|
||||
}
|
||||
claimed := opened && mode != "busy"
|
||||
if strings.Contains(text, "\nrelease\n") != claimed {
|
||||
t.Fatal("interface cleanup", text)
|
||||
}
|
||||
if mode == "ok" || mode == "unconfigured" {
|
||||
for _, want := range []string{"write-02:" + hex.EncodeToString([]byte("[:timeout 1]")), "write-02:" + hex.EncodeToString([]byte("hello\x0b")), "write-04:06"} {
|
||||
if !strings.Contains(text, want+"\n") {
|
||||
t.Fatal("missing transfer", want, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
if strings.Contains(text, "set-configuration\n") != (mode == "unconfigured") {
|
||||
t.Fatal("unexpected USB configuration change", text)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeUSBFixtureProcess(t *testing.T) {
|
||||
if os.Getenv("SRCOMMON_USB_FIXTURE") != "1" {
|
||||
return
|
||||
}
|
||||
port, err := Open("dectalk-usb", "", 0)
|
||||
mode := os.Getenv("USB_FIXTURE_MODE")
|
||||
if mode != "ok" && mode != "unconfigured" {
|
||||
if err == nil {
|
||||
port.Close()
|
||||
t.Fatal("USB failure accepted", mode)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer port.Close()
|
||||
if err := port.Write([]byte("hello\x0b"), never); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := port.Cancel([]byte{0x06}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Private libusb ABI fixture. It never enumerates or opens real USB devices.
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
typedef struct { int unused; } Context;
|
||||
typedef struct { int unused; } Device;
|
||||
typedef struct { int unused; } Handle;
|
||||
typedef struct {
|
||||
uint8_t length, type;
|
||||
uint16_t usb;
|
||||
uint8_t device_class, subclass, protocol, packet_size;
|
||||
uint16_t vendor, product, device;
|
||||
uint8_t manufacturer, product_name, serial, configurations;
|
||||
} Descriptor;
|
||||
static Context context;
|
||||
static Device device;
|
||||
static Handle handle;
|
||||
static Device *devices[] = {&device, &device, NULL};
|
||||
|
||||
static int mode(const char *value) { return strcmp(getenv("USB_FIXTURE_MODE"), value) == 0; }
|
||||
static void record(const char *message) {
|
||||
FILE *log = fopen(getenv("USB_FIXTURE_LOG"), "a");
|
||||
if (!log) abort();
|
||||
fprintf(log, "%s\n", message);
|
||||
fclose(log);
|
||||
}
|
||||
int libusb_init(Context **result) { record("init"); *result = &context; return 0; }
|
||||
void libusb_exit(Context *value) { (void)value; record("exit"); }
|
||||
ssize_t libusb_get_device_list(Context *value, Device ***result) { (void)value; record("list"); *result = devices; return mode("multiple") ? 2 : 1; }
|
||||
void libusb_free_device_list(Device **value, int unref) { (void)value; (void)unref; record("free-list"); }
|
||||
int libusb_get_device_descriptor(Device *value, Descriptor *result) {
|
||||
(void)value;
|
||||
memset(result, 0, sizeof(*result));
|
||||
result->vendor = 0x0dd0;
|
||||
result->product = mode("missing") ? 0x1002 : 0x2001;
|
||||
return 0;
|
||||
}
|
||||
int libusb_open(Device *value, Handle **result) { (void)value; record("open"); if (mode("denied")) return -3; *result = &handle; return 0; }
|
||||
void libusb_close(Handle *value) { (void)value; record("close"); }
|
||||
int libusb_get_configuration(Handle *value, int *result) { (void)value; record("configuration"); *result = mode("unconfigured") ? 0 : 1; return 0; }
|
||||
int libusb_set_configuration(Handle *value, int configuration) { (void)value; if (configuration != 1) abort(); record("set-configuration"); return 0; }
|
||||
int libusb_claim_interface(Handle *value, int interface) { (void)value; if (interface != 0) abort(); record("claim"); return mode("busy") ? -6 : 0; }
|
||||
int libusb_release_interface(Handle *value, int interface) { (void)value; if (interface != 0) abort(); record("release"); return 0; }
|
||||
int libusb_bulk_transfer(Handle *value, unsigned char endpoint, unsigned char *data, int length, int *transferred, unsigned int timeout) {
|
||||
(void)value;
|
||||
if (length > 64 || timeout != 1000) abort();
|
||||
char message[256];
|
||||
int offset = snprintf(message, sizeof(message), "write-%02x:", endpoint);
|
||||
for (int index = 0; index < length; index++) offset += snprintf(message + offset, sizeof(message) - offset, "%02x", data[index]);
|
||||
record(message);
|
||||
*transferred = mode("short") ? length - 1 : length;
|
||||
return mode("timeout") ? -7 : 0;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Package transport opens and drives hardware speech synthesizers over serial
|
||||
// ports and DECtalk USB. It owns device I/O, flow control and bounded
|
||||
// cancellation; protocol encoding stays in the parent hardware package, and
|
||||
// speech queues, settings caches and admission stay in each reader.
|
||||
//
|
||||
// The native implementation needs Linux and cgo. libusb is loaded at runtime
|
||||
// with dlopen, so the only link flag is -ldl and no USB headers are needed.
|
||||
// Other builds compile, and every open returns ErrUnsupported.
|
||||
package transport
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrCanceled reports that Write stopped because its canceled callback
|
||||
// returned true. Bytes already handed to the device may still be spoken.
|
||||
var ErrCanceled = errors.New("hardware speech write canceled")
|
||||
|
||||
// ErrUnsupported is returned by every open on builds without Linux and cgo.
|
||||
var ErrUnsupported = errors.New("hardware speech requires Linux and cgo")
|
||||
|
||||
// DefaultBaudRate is used when a serial open asks for baud rate 0.
|
||||
const DefaultBaudRate = 9600
|
||||
|
||||
// cancelTimeout bounds how long Cancel retries a busy serial port.
|
||||
const cancelTimeout = 5 * time.Second
|
||||
|
||||
// BaudRates lists the serial speeds the native transport can set.
|
||||
func BaudRates() []int { return []int{1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200} }
|
||||
|
||||
// Port is an open synthesizer connection.
|
||||
//
|
||||
// Write sends data in bounded packets and checks canceled between them,
|
||||
// returning ErrCanceled when it reports true. Cancel sends an immediate
|
||||
// command and must not wait behind a blocked Write, including a serial
|
||||
// device paused by XOFF. Close releases the device after in-flight native
|
||||
// calls return; it is safe to call more than once.
|
||||
type Port interface {
|
||||
Write(data []byte, canceled func() bool) error
|
||||
Cancel(command []byte) error
|
||||
Close()
|
||||
}
|
||||
|
||||
// Open opens the transport for a hardware driver ID: "dectalk" (serial with
|
||||
// XON/XOFF), "dectalk-usb", "litetalk", "doubletalk" or "tripletalk". Serial
|
||||
// drivers need an absolute device path; baud 0 selects DefaultBaudRate.
|
||||
// The device is locked exclusively, and opening never sends speech.
|
||||
func Open(driverID, device string, baud int) (Port, error) {
|
||||
switch driverID {
|
||||
case "dectalk-usb":
|
||||
return OpenDECtalkUSB()
|
||||
case "dectalk", "litetalk", "doubletalk", "tripletalk":
|
||||
return OpenSerial(device, baud, driverID == "dectalk")
|
||||
}
|
||||
return nil, fmt.Errorf("unsupported hardware speech driver %q", driverID)
|
||||
}
|
||||
|
||||
// OpenSerial opens path in raw mode and takes an exclusive lock on it, so a
|
||||
// second reader cannot configure a device that is already in use. xon
|
||||
// enables XON/XOFF output flow control. Close restores the original
|
||||
// terminal settings.
|
||||
func OpenSerial(path string, baud int, xon bool) (Port, error) {
|
||||
if err := ValidateDevice(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if baud == 0 {
|
||||
baud = DefaultBaudRate
|
||||
}
|
||||
if !slices.Contains(BaudRates(), baud) {
|
||||
return nil, fmt.Errorf("unsupported hardware speech baud rate %d", baud)
|
||||
}
|
||||
return openSerial(path, baud, xon)
|
||||
}
|
||||
|
||||
// OpenDECtalkUSB opens the single connected DECtalk USB device (0dd0:2001)
|
||||
// through libusb and sets its idle timeout. It fails when none or several
|
||||
// are connected.
|
||||
func OpenDECtalkUSB() (Port, error) {
|
||||
port, err := openUSB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := port.Write([]byte("[:timeout 1]"), func() bool { return false }); err != nil {
|
||||
port.Close()
|
||||
return nil, err
|
||||
}
|
||||
return port, nil
|
||||
}
|
||||
|
||||
// USBAvailable reports whether libusb can be loaded for DECtalk USB.
|
||||
func USBAvailable() error { return usbAvailable() }
|
||||
|
||||
// ValidateDevice accepts an absolute serial device path without control
|
||||
// characters.
|
||||
func ValidateDevice(path string) error {
|
||||
if path == "" || !filepath.IsAbs(path) || strings.ContainsAny(path, "\x00\r\n") {
|
||||
return errors.New("hardware speech requires an explicit absolute serial device path")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// usbPort sends packets through native bulk transfers. Different endpoints
|
||||
// can transfer concurrently; only Close takes exclusive ownership, after
|
||||
// each bounded native call has returned.
|
||||
type usbPort struct {
|
||||
mu sync.RWMutex
|
||||
send func(endpoint byte, data []byte) error
|
||||
close func()
|
||||
}
|
||||
|
||||
const (
|
||||
usbNormalEndpoint = 0x02
|
||||
usbImmediateEndpoint = 0x04
|
||||
usbPacketSize = 64
|
||||
)
|
||||
|
||||
func (p *usbPort) transfer(endpoint byte, data []byte, canceled func() bool) error {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
if p.send == nil {
|
||||
return errors.New("USB speech closed")
|
||||
}
|
||||
for len(data) > 0 {
|
||||
if canceled() {
|
||||
return ErrCanceled
|
||||
}
|
||||
count := min(usbPacketSize, len(data))
|
||||
if err := p.send(endpoint, data[:count]); err != nil {
|
||||
if canceled() {
|
||||
return ErrCanceled
|
||||
}
|
||||
return err
|
||||
}
|
||||
data = data[count:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *usbPort) Write(data []byte, canceled func() bool) error {
|
||||
return p.transfer(usbNormalEndpoint, data, canceled)
|
||||
}
|
||||
|
||||
func (p *usbPort) Cancel(command []byte) error {
|
||||
return p.transfer(usbImmediateEndpoint, command, func() bool { return false })
|
||||
}
|
||||
|
||||
func (p *usbPort) Close() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.send != nil {
|
||||
if p.close != nil {
|
||||
p.close()
|
||||
}
|
||||
p.send, p.close = nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// usbError maps native libusb and fixture statuses to user-facing errors.
|
||||
func usbError(status int) error {
|
||||
switch status {
|
||||
case -100:
|
||||
return errors.New("DECtalk USB requires libusb-1.0.so.0")
|
||||
case -101:
|
||||
return errors.New("multiple DECtalk USB devices found; connect one for this reader")
|
||||
case -102:
|
||||
return errors.New("short DECtalk USB write")
|
||||
case -4:
|
||||
return errors.New("DECtalk USB device 0dd0:2001 unavailable or disconnected")
|
||||
case -3:
|
||||
return errors.New("DECtalk USB access denied")
|
||||
case -6:
|
||||
return errors.New("DECtalk USB interface is busy")
|
||||
case -7:
|
||||
return errors.New("DECtalk USB write timed out")
|
||||
}
|
||||
return fmt.Errorf("DECtalk USB error %d", status)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestOpenRejectsInvalidRequestsWithoutDevices(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
driver, device string
|
||||
baud int
|
||||
}{
|
||||
{"espeak", "/dev/ttyS0", 9600},
|
||||
{"litetalk", "", 9600},
|
||||
{"litetalk", "ttyS0", 9600},
|
||||
{"dectalk", "/dev/tty\nS0", 9600},
|
||||
{"doubletalk", "/dev/ttyS0", 300},
|
||||
} {
|
||||
if port, err := Open(testCase.driver, testCase.device, testCase.baud); err == nil {
|
||||
port.Close()
|
||||
t.Fatal("accepted", testCase)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUSBCancelBypassesBlockedPacket(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
unblock := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
defer unblock()
|
||||
var normal, immediate atomic.Int32
|
||||
var stale atomic.Bool
|
||||
port := &usbPort{send: func(endpoint byte, data []byte) error {
|
||||
if endpoint == usbImmediateEndpoint {
|
||||
if !bytes.Equal(data, []byte{0x06}) {
|
||||
return fmt.Errorf("bad cancellation %x", data)
|
||||
}
|
||||
immediate.Add(1)
|
||||
stale.Store(true)
|
||||
} else if normal.Add(1) == 1 {
|
||||
close(started)
|
||||
<-release
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- port.Write([]byte(strings.Repeat("x", 200)), stale.Load) }()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("packet not started")
|
||||
}
|
||||
if err := port.Cancel([]byte{0x06}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if immediate.Load() != 1 {
|
||||
t.Fatal("immediate endpoint was blocked")
|
||||
}
|
||||
unblock()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrCanceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("stale send stuck")
|
||||
}
|
||||
if normal.Load() != 1 {
|
||||
t.Fatal("more stale packets transmitted", normal.Load())
|
||||
}
|
||||
port.Close()
|
||||
}
|
||||
|
||||
func TestUSBPacketLimitsFailureAndCleanup(t *testing.T) {
|
||||
var sizes []int
|
||||
closed := 0
|
||||
port := &usbPort{send: func(endpoint byte, data []byte) error {
|
||||
if endpoint != usbNormalEndpoint {
|
||||
t.Fatal(endpoint)
|
||||
}
|
||||
sizes = append(sizes, len(data))
|
||||
return nil
|
||||
}, close: func() { closed++ }}
|
||||
if err := port.Write(make([]byte, 130), func() bool { return false }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(sizes, []int{64, 64, 2}) {
|
||||
t.Fatal(sizes)
|
||||
}
|
||||
failure := errors.New("short transfer")
|
||||
port.send = func(byte, []byte) error { return failure }
|
||||
if err := port.Write(make([]byte, 70), func() bool { return false }); !errors.Is(err, failure) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port.Close()
|
||||
port.Close()
|
||||
if closed != 1 {
|
||||
t.Fatal(closed)
|
||||
}
|
||||
if err := port.Write([]byte{1}, func() bool { return false }); err == nil {
|
||||
t.Fatal("closed USB device accepted write")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//go:build !linux || !cgo
|
||||
|
||||
package transport
|
||||
|
||||
func openSerial(string, int, bool) (Port, error) { return nil, ErrUnsupported }
|
||||
func openUSB() (*usbPort, error) { return nil, ErrUnsupported }
|
||||
func usbAvailable() error { return ErrUnsupported }
|
||||
Reference in new issue
Block a user