Share date, voice, tone, spelling, and hardware behavior

Provide common date/time formatting, locale voice matching, tone synthesis, phonetic spelling, and one hardware synthesizer protocol encoder for both readers. Standardize whiskey and x ray and use the tested Fenrir DECtalk mapping.

Validated the common module with GOWORK=off go test -race ./...; reader integration, serial cancellation, PCM hashes, no-CGO datetime, and speech regression checks passed. Physical keyboard, audible synthesis, and braille acceptance remain separate live checks.
This commit is contained in:
ak47 committed 2026-11-12 23:24:14 -05:00
1 parent b9a33f7578
commit e7bd1d0043
15 files changed
+809 -3

No files matched your search

+34 -3
View File
@@ -121,8 +121,39 @@ Run `go test -race ./speechdispatcher` for protocol and recovery fixtures.
starts and restarts private dummy-output daemons; it does not restart the user's
Speech Dispatcher. The environment variable retains the migrated test's name.
The shared client is available starting with v0.3.0. Both readers pin this
version for standalone builds; the sibling workspace remains useful for local
development. Verify released dependencies with `GOWORK=off`. Existing installed
The shared client is available starting with v0.3.0. Both readers pin released
module versions for standalone builds; the sibling workspace remains useful
for local development. Verify released dependencies with `GOWORK=off`. Existing installed
binaries do not gain fixes until rebuilt. Live audible-speech, keyboard, and
braille acceptance is tracked separately from automated protocol tests.
## Additional shared behavior
The following packages have one implementation used by both readers:
- `datetime`: format presets, validation, option examples, locale-aware `strftime`
formatting, and a non-CGO fallback.
- `speechdispatcher.LanguageVoices`: locale normalization, dialect/base-language
matching, explicit-language selection, and ordering of eSpeak variants.
- `phonetic`: the spelling alphabet, including `whiskey` and `x ray`. Reader
presentation can capitalize the returned words and select uppercase voices.
- `tones`: native progress pitch/waveforms, the indentation triangle variant,
PCM/WAV generation, and the existing sine-tone generator. Playback services,
resampling to an output device, volume, pan, and queue admission stay local.
- `hardware`: one normalized -100..100 settings scale, native command encoding,
ASCII text filtering, DECtalk command escaping, terminators, and per-device
cancellation bytes. Serial DECtalk uses ETX to cancel and VT to submit text;
DECtalk USB uses ACK to cancel. LiteTalk, DoubleTalk and TripleTalk share their
control-A settings, CR terminator, and control-X cancellation.
Hardware commands use the previously tested Fenrir mapping in both readers.
DECtalk rate spans 75/180/650 and pitch spans 50/122/350 at minimum/midpoint/maximum;
volume uses `dv g5` from 60 to 86. Cthulhu converts its legacy saved 0..99 rate
and 0..9 pitch/volume values at the boundary. It no longer has a separate
DECtalk encoding. Port opening, serial/USB I/O, flush timing and cancellation
synchronization remain the responsibility of the device-owning reader.
These additions are available starting with v0.4.0. Both readers pin this
version for standalone builds. Verify pinned dependencies with `GOWORK=off`;
physical keyboard, audible speech, braille, and hardware acceptance remain
separate live checks.
+119
View File
@@ -0,0 +1,119 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package datetime
import "time"
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 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
}
+53
View File
@@ -0,0 +1,53 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package datetime
import (
"testing"
"time"
)
func TestFormatsAndExamples(t *testing.T) {
now := time.Date(2026, 10, 25, 14, 5, 9, 0, time.FixedZone("fixture", -4*3600))
for _, testCase := range []struct {
id, want string
date bool
}{
{"24-hour", "14:05", false},
{"24-hour-seconds", "14:05:09", false},
{"24-hour-words", "14 hours and 05 minutes", false},
{"24-hour-seconds-words", "14 hours, 05 minutes and 09 seconds", false},
{"numbers-dm", "25/10", true},
{"numbers-md", "10/25", true},
{"numbers-dmy", "25/10/2026", true},
{"numbers-mdy", "10/25/2026", true},
{"numbers-ymd", "2026/10/25", true},
} {
format := FormatTime
if testCase.date {
format = FormatDate
}
if got, ok := format(testCase.id, now); !ok || got != testCase.want {
t.Fatal(testCase.id, got, ok)
}
}
for _, date := range []bool{false, true} {
options, format, valid := TimeOptions(now), FormatTime, ValidTime
if date {
options, format, valid = DateOptions(now), FormatDate, ValidDate
}
for _, option := range options {
got, ok := format(option.Value, now)
if !ok || !valid(option.Value) || got == "" || got != option.Label {
t.Fatal(option, got, ok)
}
}
if got, ok := format("%arbitrary", now); ok || got != "" || valid("%arbitrary") {
t.Fatal("invalid preset accepted")
}
}
if got, _ := FormatTime("24-hour-seconds", now.Add(10*time.Hour)); got != "00:05:09" {
t.Fatal(got)
}
}
+44
View File
@@ -0,0 +1,44 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
//go:build cgo
package datetime
/*
#include <locale.h>
#include <stdlib.h>
#include <time.h>
*/
import "C"
import (
"time"
"unsafe"
)
func init() {
locale := C.CString("")
defer C.free(unsafe.Pointer(locale))
C.setlocale(C.LC_TIME, locale)
}
func format(now time.Time, spec string) string {
cSpec := C.CString(spec)
defer C.free(unsafe.Pointer(cSpec))
tm := C.struct_tm{
tm_year: C.int(now.Year() - 1900),
tm_mon: C.int(int(now.Month()) - 1),
tm_mday: C.int(now.Day()),
tm_hour: C.int(now.Hour()),
tm_min: C.int(now.Minute()),
tm_sec: C.int(now.Second()),
tm_wday: C.int(int(now.Weekday())),
tm_yday: C.int(now.YearDay() - 1),
tm_isdst: -1,
}
buffer := make([]C.char, 512)
length := C.strftime(&buffer[0], C.size_t(len(buffer)), cSpec, &tm)
return C.GoStringN(&buffer[0], C.int(length))
}
+80
View File
@@ -0,0 +1,80 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
//go:build !cgo
package datetime
import (
"strconv"
"strings"
"time"
)
// format is a C-locale strftime subset for builds without cgo, such as the
// statically linked Tentacle packages that only validate settings. The reader
// itself is built with cgo and uses the locale-aware implementation.
func format(now time.Time, spec string) string {
var out strings.Builder
for index := 0; index < len(spec); index++ {
if spec[index] != '%' || index+1 == len(spec) {
out.WriteByte(spec[index])
continue
}
index++
pad := true
if spec[index] == '-' && index+1 < len(spec) {
pad = false
index++
}
two := func(value int) string {
if pad && value < 10 {
return "0" + strconv.Itoa(value)
}
return strconv.Itoa(value)
}
switch spec[index] {
case 'H':
out.WriteString(two(now.Hour()))
case 'I':
hour := now.Hour() % 12
if hour == 0 {
hour = 12
}
out.WriteString(two(hour))
case 'M':
out.WriteString(two(now.Minute()))
case 'S':
out.WriteString(two(now.Second()))
case 'p':
out.WriteString(now.Format("PM"))
case 'X':
out.WriteString(now.Format("15:04:05"))
case 'x':
out.WriteString(now.Format("01/02/06"))
case 'd':
out.WriteString(two(now.Day()))
case 'm':
out.WriteString(two(int(now.Month())))
case 'Y':
out.WriteString(strconv.Itoa(now.Year()))
case 'y':
out.WriteString(now.Format("06"))
case 'A':
out.WriteString(now.Weekday().String())
case 'a':
out.WriteString(now.Weekday().String()[:3])
case 'B':
out.WriteString(now.Month().String())
case 'b':
out.WriteString(now.Month().String()[:3])
case '%':
out.WriteByte('%')
default:
out.WriteByte('%')
out.WriteByte(spec[index])
}
}
return out.String()
}
+28
View File
@@ -0,0 +1,28 @@
// 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")
}
}
+89
View File
@@ -0,0 +1,89 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
// Package hardware encodes hardware speech protocols without owning devices.
package hardware
import (
"fmt"
"math"
"strings"
)
// Protocol selects a device, not a reader-specific dialect. The zero value is
// the LiteTalk-compatible protocol used by LiteTalk, DoubleTalk and TripleTalk.
type Protocol struct{ dectalk, usb bool }
func Serial(dectalk bool) Protocol { return Protocol{dectalk: dectalk} }
func DECtalkUSB() Protocol { return Protocol{dectalk: true, usb: true} }
// Parameters uses the same -100..100 scale as Speech Dispatcher. Nil retains
// the device's existing setting. Readers convert legacy saved scales at entry.
type Parameters struct{ Rate, Pitch, Volume *float64 }
func scale(value float64, minimum, maximum int) int {
fraction := (math.Max(-100, math.Min(100, value)) + 100) / 200
return int(math.RoundToEven(float64(minimum) + fraction*float64(maximum-minimum)))
}
func centered(value float64, minimum, normal, maximum int) int {
if value <= 0 {
return scale(value*2+100, minimum, normal)
}
return scale(value*2-100, normal, maximum)
}
// Commands applies one common mapping and encoding for each synthesizer.
func (p Protocol) Commands(parameters Parameters) [3]string {
var commands [3]string
for index, value := range []*float64{parameters.Rate, parameters.Pitch, parameters.Volume} {
if value == nil {
continue
}
native := scale(*value, 0, []int{9, 99, 9}[index])
if p.dectalk {
switch index {
case 0:
native = centered(*value, 75, 180, 650)
case 1:
native = centered(*value, 50, 122, 350)
case 2:
native = scale(*value, 60, 86)
}
commands[index] = fmt.Sprintf("[:%s %d]", []string{"ra", "dv ap", "dv g5"}[index], native)
} else {
commands[index] = fmt.Sprintf("\x01%d%c", native, []byte{'S', 'P', 'V'}[index])
}
}
return commands
}
// Text replaces non-ASCII/control runes and prevents DECtalk command injection.
func (p Protocol) Text(text string) []byte {
var clean strings.Builder
for _, char := range text {
if char < 0x20 || char > 0x7e {
char = ' '
}
clean.WriteRune(char)
}
text = clean.String()
if p.dectalk {
return append([]byte(strings.ReplaceAll(text, "[:", "[ :")), 0x0b)
}
return append([]byte(text), '\r')
}
func (p Protocol) Cancel() []byte {
if p.usb {
return []byte{6}
}
if p.dectalk {
return []byte{3}
}
return []byte{0x18}
}
// LegacyValue converts a saved 0..maximum reader value to the common scale.
func LegacyValue(value, maximum float64) float64 {
return 200*math.Max(0, math.Min(maximum, value))/maximum - 100
}
+55
View File
@@ -0,0 +1,55 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package hardware
import "testing"
func TestDeviceProtocolsAndNormalizedSettings(t *testing.T) {
for _, row := range []struct {
value float64
lite, dectalk [3]string
}{
{-100, [3]string{"\x010S", "\x010P", "\x010V"}, [3]string{"[:ra 75]", "[:dv ap 50]", "[:dv g5 60]"}},
{0, [3]string{"\x014S", "\x0150P", "\x014V"}, [3]string{"[:ra 180]", "[:dv ap 122]", "[:dv g5 73]"}},
{100, [3]string{"\x019S", "\x0199P", "\x019V"}, [3]string{"[:ra 650]", "[:dv ap 350]", "[:dv g5 86]"}},
} {
for _, device := range []struct {
protocol Protocol
want [3]string
}{{Serial(false), row.lite}, {Serial(true), row.dectalk}, {DECtalkUSB(), row.dectalk}} {
value := row.value
if got := device.protocol.Commands(Parameters{&value, &value, &value}); got != device.want {
t.Fatalf("%v: got %q, want %q", value, got, device.want)
}
}
}
for _, row := range []struct {
protocol Protocol
text string
cancel byte
}{
{Serial(false), "A [ :x] [:x]\r", 0x18},
{Serial(true), "A [ :x] [ :x]\x0b", 3},
{DECtalkUSB(), "A [ :x] [ :x]\x0b", 6},
} {
if got := string(row.protocol.Text("A\n猫[ :x] [:x]")); got != row.text {
t.Fatalf("unsafe or changed text: %q", got)
}
if got := row.protocol.Cancel(); len(got) != 1 || got[0] != row.cancel {
t.Fatalf("cancel: %q", got)
}
}
}
func TestLegacySettingsAndOmittedFields(t *testing.T) {
for _, row := range []struct{ value, maximum, want float64 }{{0, 99, -100}, {49.5, 99, 0}, {99, 99, 100}, {4.5, 9, 0}, {1000, 9, 100}, {-3, 9, -100}} {
if got := LegacyValue(row.value, row.maximum); got != row.want {
t.Fatal(row, got)
}
}
value := float64(0)
if got := Serial(true).Commands(Parameters{Pitch: &value}); got != [3]string{"", "[:dv ap 122]", ""} {
t.Fatal(got)
}
}
+18
View File
@@ -0,0 +1,18 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
// Package phonetic supplies the common spelling alphabet.
package phonetic
import "unicode"
// Letter returns a lowercase spelling word, or empty for non-Latin letters.
func 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", "whiskey", "x ray", "yankee", "zulu"}
char = unicode.ToLower(char)
if char < 'a' || char > 'z' {
return ""
}
return words[char-'a']
}
+16
View File
@@ -0,0 +1,16 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package phonetic
import "testing"
func TestSharedSpellingAndFallback(t *testing.T) {
for _, row := range []struct {
char rune
want string
}{{'a', "alpha"}, {'A', "alpha"}, {'w', "whiskey"}, {'W', "whiskey"}, {'x', "x ray"}, {'X', "x ray"}, {'É', ""}, {'界', ""}, {'1', ""}} {
if got := Letter(row.char); got != row.want {
t.Fatal(row, got)
}
}
}
+56
View File
@@ -0,0 +1,56 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package speechdispatcher
import (
"os"
"sort"
"strings"
)
func NormalizeLanguage(value string) string {
value = strings.Split(strings.Split(value, ".")[0], "@")[0]
return strings.ToLower(strings.ReplaceAll(value, "_", "-"))
}
// LanguageVoices 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 LanguageVoices(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 = NormalizeLanguage(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 NormalizeLanguage(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
}
+36
View File
@@ -0,0 +1,36 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package speechdispatcher
import (
"reflect"
"testing"
)
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 := LanguageVoices(voices, "")
if !reflect.DeepEqual(got, []Voice{voices[2], voices[0]}) {
t.Fatal(got)
}
t.Setenv("LC_ALL", "en_AU.UTF-8")
if got := LanguageVoices(voices, ""); !reflect.DeepEqual(got, []Voice{voices[3]}) {
t.Fatal(got)
}
if got := LanguageVoices(voices, "de"); !reflect.DeepEqual(got, []Voice{voices[1]}) {
t.Fatal(got)
}
if got := LanguageVoices(voices, "unknown"); len(got) != 0 {
t.Fatal(got)
}
t.Setenv("LC_ALL", "zz_ZZ")
if got := LanguageVoices(voices, ""); !reflect.DeepEqual(got, voices) {
t.Fatal(got)
}
if voices[0].Name != "US+Variant" {
t.Fatal("catalog reordered in place")
}
}
+79
View File
@@ -0,0 +1,79 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package tones
import (
"bytes"
"encoding/binary"
"math"
)
// 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 ProgressFrequency(percentage float64) float64 { return 110 * math.Pow(2, percentage/25) }
func ProgressWAV(percentage float64) []byte {
return NVDAWAV(ProgressFrequency(percentage), 40)
}
// NVDAWAV also supplies the capital-letter beep (2000 Hz, 50 ms).
func NVDAWAV(hz float64, milliseconds int) []byte {
samples := Samples(hz, milliseconds, false)
const sampleRate = SampleRate
sampleCount := len(samples)
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))
for _, value := range samples {
_ = binary.Write(buffer, binary.LittleEndian, value)
_ = binary.Write(buffer, binary.LittleEndian, value)
}
return buffer.Bytes()
}
// SampleRate is the native synthesis rate; streaming readers may resample it.
const SampleRate = 44100
// Samples generates the common clipped sine, or its indentation triangle variant.
// Invalid frequencies and durations produce no samples.
func Samples(hz float64, milliseconds int, triangle bool) []int16 {
if math.IsNaN(hz) || math.IsInf(hz, 0) || hz < 1 || hz > SampleRate || milliseconds <= 0 || milliseconds > 10000 {
return nil
}
const sampleRate = SampleRate
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
samples := make([]int16, sampleCount)
sinFrequency := 2 * math.Pi / cycleLength
for index := range samples {
phase := float64(index%sampleRate) * sinFrequency
wave := min(1.0, max(-1.0, math.Sin(phase)*2))
if triangle {
wave = 2 / math.Pi * math.Asin(math.Sin(phase))
}
samples[index] = int16(wave * 7000)
}
return samples
}
+57
View File
@@ -0,0 +1,57 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package tones
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"testing"
)
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 := ProgressWAV(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(ProgressWAV(percentage)[44:])); got != digest {
t.Fatalf("%g percent PCM differs from NVDA: %s", percentage, got)
}
}
}
func TestIndentationWaveSharesPitchWithoutChangingShape(t *testing.T) {
sine := Samples(ProgressFrequency(50), 40, false)
triangle := Samples(ProgressFrequency(50), 40, true)
if len(sine) != len(triangle) || len(sine) == 0 {
t.Fatal("waveform durations diverged")
}
different := false
for index, value := range triangle {
if value < -7000 || value > 7000 {
t.Fatal("unbounded triangle amplitude")
}
if (value > 0) != (sine[index] > 0) {
t.Fatal("pitch phase diverged")
}
different = different || value != sine[index]
}
if !different {
t.Fatal("triangle lost its distinct timbre")
}
}
+45
View File
@@ -0,0 +1,45 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package tones
import (
"bytes"
"encoding/binary"
"math"
"time"
)
// SineWAV 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 SineWAV(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()
}