merge: TCI audio — receive, transmit, and the voice keyer over the CAT link

A SunSDR carries its audio on the same WebSocket as its commands, so
OpsLog can take it directly: no virtual cable, no second sound card, no
Windows mixer between the recording and the air. The radio appears as a
device in both audio lists and can be chosen for either direction.

Everything here was settled on real hardware over one evening, and none of
it was guessable from the documentation:

  - The receive stream answers format=3 for four-byte floats, so the
    sample width is derived from the frame rather than trusted from the
    field.
  - The radio asks for transmit audio only when the transmission is the
    CLIENT'S, and only when its transmit audio source is TCI rather than
    the microphone.
  - The chrono is a REQUEST, not a clock: no payload, carrying the size it
    wants, 47 times a second. Audio goes out in answer to it and never on
    a timer of our own — a timer was the first attempt and all 234 frames
    of it were ignored.

Confirmed: a clean test recording, and 80 W out of a 1 kHz tone.
This commit is contained in:
2026-08-26 00:05:40 +02:00
21 changed files with 1768 additions and 11 deletions
+67 -4
View File
@@ -8350,8 +8350,49 @@ type AudioSettings struct {
// ListAudioInputDevices / ListAudioOutputDevices enumerate WASAPI endpoints
// for the device dropdowns.
func (a *App) ListAudioInputDevices() ([]audio.Device, error) { return audio.ListInputDevices() }
func (a *App) ListAudioOutputDevices() ([]audio.Device, error) { return audio.ListOutputDevices() }
// ListAudioInputDevices lists the microphones and line inputs, plus THE RADIO
// when the CAT link carries its receive audio.
//
// Same reasoning as the output list: over TCI there is no sound device for
// Windows to show, so without this the one correct answer to "where does the
// received audio come from" could not be chosen at all.
func (a *App) ListAudioInputDevices() ([]audio.Device, error) {
devs, err := audio.ListInputDevices()
if err != nil {
return devs, err
}
if a.tciAudioAvailable() {
devs = append([]audio.Device{{ID: audio.NetworkDeviceID, Name: "Radio (TCI network audio)"}}, devs...)
}
return devs, nil
}
// tciAudioAvailable says whether the active CAT backend is a radio that streams
// its audio over the CAT link.
func (a *App) tciAudioAvailable() bool {
if a.cat == nil {
return false
}
_, ok := a.cat.TCIAudioState()
return ok
}
// ListAudioOutputDevices lists the sound cards, plus THE RADIO ITSELF when the
// CAT link can carry transmit audio.
//
// Offered only while it is actually available, and named as a radio rather than
// as a protocol: an operator choosing where their voice goes is picking between
// "my sound card" and "the radio", not between WASAPI and TCI.
func (a *App) ListAudioOutputDevices() ([]audio.Device, error) {
devs, err := audio.ListOutputDevices()
if err != nil {
return devs, err
}
if audio.NetworkPlayerReady() {
devs = append([]audio.Device{{ID: audio.NetworkDeviceID, Name: "Radio (TCI network audio)"}}, devs...)
}
return devs, nil
}
// GetAudioSettings returns the stored audio config (preroll defaults to 8s).
func (a *App) GetAudioSettings() (AudioSettings, error) {
@@ -8453,6 +8494,15 @@ func (a *App) SaveAudioSettings(s AudioSettings) error {
return err
}
}
// Choosing the radio as the receive device opens its stream, and choosing
// anything else closes it. Done HERE rather than left to the next restart:
// a device chosen in a dropdown that only takes effect after a relaunch
// reads as a device that does not work.
if s.FromRadio == audio.NetworkDeviceID {
a.startTCIRecording()
} else if a.tciAudioAvailable() && a.settingOr(keyTCIRecAudio, "") != "1" {
_ = a.cat.TCIAudioDo(func(t cat.TCIAudioController) error { return t.StopTCIAudio() })
}
// Apply device/preroll/enable changes to the running recorder.
a.startQSORecorderIfEnabled()
// And to a monitor ALREADY RUNNING: the operator is listening while they
@@ -8497,7 +8547,7 @@ func (a *App) startQSORecorderIfEnabled() {
// nothing right to point at. The stream is pushed into the recorder instead
// — same samples, no sound card in the middle, and no virtual cable to set up.
from := cfg.FromRadio
a.qsoRecPushed = a.icomNetAudioActive()
a.qsoRecPushed = a.icomNetAudioActive() || cfg.FromRadio == audio.NetworkDeviceID
if a.qsoRecPushed {
from = audio.PushedSource
}
@@ -15178,6 +15228,12 @@ func (a *App) reloadCAT() {
} else {
a.catSig = sig
}
// Withdraw the radio as an audio output before deciding anything else. The
// TCI case below puts it back; every other backend, and a CAT link turned
// off entirely, leaves it withdrawn — a voice keyer that still lists a radio
// it can no longer reach would play a message to nowhere, and the operator
// hears their own PTT click and assumes it went out.
a.installTCITXPlayer(false)
if !s.Enabled {
a.cat.Stop()
return
@@ -15300,7 +15356,14 @@ func (a *App) reloadCAT() {
a.cat.Start(cat.NewIcomNet(s.IcomNetHost, s.IcomNetUser, s.IcomNetPass, s.IcomAddr, s.DigitalDefault, audioSink))
case "tci":
// Expert Electronics TCI (WebSocket) — SunSDR / ExpertSDR2, or any
// TCI-compatible server.
// TCI-compatible server. The receive audio rides the same socket, so
// the QSO recorder can take it without a virtual cable — see
// app_tci_rec.go. Armed after the backend is up, since it is the
// backend that carries the stream.
defer a.startTCIRecording()
// And the other direction: the voice keyer can send its messages over
// the same link — see app_tci_dvk.go.
defer a.installTCITXPlayer(true)
tb := cat.NewTCI(s.TCIHost, s.TCIPort, s.DigitalDefault, s.TCISpots)
// Clicking one of our spots on the ExpertSDR panorama fills the entry form.
tb.OnSpotClick = func(call string, hz int64) {
+80
View File
@@ -0,0 +1,80 @@
package main
// TCI receive audio — bindings.
//
// A SunSDR carries its receive audio on the same WebSocket as its commands, so
// OpsLog can take it directly instead of asking the operator to install a
// virtual audio cable and wire ExpertSDR's output into it. This is the first
// half: RECEIVE only, which is what the QSO recorder and the CW decoder need.
// Transmit audio (the voice keyer) is the other half and is not here yet — it
// has to answer the radio's chrono packets at the right pace, and that is worth
// doing once the receive side has proved the format on a real radio.
import (
"fmt"
"hamlog/internal/applog"
"hamlog/internal/cat"
)
// StartTCIAudio opens the receive-audio stream for one receiver.
//
// rate 0 means 48 kHz, which is what ExpertSDR streams by default and what the
// recorder wants anyway.
func (a *App) StartTCIAudio(rx, rate int) error {
if a.cat == nil {
return fmt.Errorf("CAT not initialized")
}
applog.Printf("tci: opening the receive-audio stream (rx %d, %d Hz)", rx, rate)
return a.cat.TCIAudioDo(func(t cat.TCIAudioController) error { return t.StartTCIAudio(rx, rate) })
}
// StopTCIAudio closes it.
func (a *App) StopTCIAudio() error {
if a.cat == nil {
return fmt.Errorf("CAT not initialized")
}
applog.Printf("tci: closing the receive-audio stream")
return a.cat.TCIAudioDo(func(t cat.TCIAudioController) error { return t.StopTCIAudio() })
}
// GetTCIAudioStatus reports what is arriving: the sample rate the radio chose,
// how much has come in, and the peak level of the last second.
//
// The level is the point. "The stream is open" and "audio is arriving" are
// different claims, and only the second one is worth anything to someone
// testing this on a radio for the first time.
func (a *App) GetTCIAudioStatus() cat.TCIAudioStatus {
if a.cat == nil {
return cat.TCIAudioStatus{}
}
st, _ := a.cat.TCIAudioState()
return st
}
// ProbeTCITransmit keys the radio and pushes a tone over TCI, to find out
// whether the transmit half of the stream works at all.
//
// A first real transmission proved that the radio sends nothing extra while the
// OPERATOR keys it — 282 receive frames and no chrono over six seconds — so the
// only way forward is to key it from here and watch. Everything interesting
// lands in the log; see internal/cat/tci_tx_probe.go for what the two possible
// answers mean.
//
// THIS TRANSMITS. The button that calls it says so, and the radio must be on a
// dummy load.
func (a *App) ProbeTCITransmit(seconds int) error {
if a.cat == nil {
return fmt.Errorf("CAT not initialized")
}
return a.cat.TCIAudioDo(func(t cat.TCIAudioController) error {
p, ok := t.(interface {
ProbeTXStream(seconds int, toneHz float64) error
})
if !ok {
return fmt.Errorf("this CAT backend is not a TCI radio")
}
applog.Printf("tci: TX PROBE requested (%d s) — the radio should be on a dummy load", seconds)
return p.ProbeTXStream(seconds, 1000)
})
}
+60
View File
@@ -0,0 +1,60 @@
package main
// The voice keyer, through the radio's own link.
//
// Selecting the radio as the "To radio" output makes the voice keyer hand its
// messages to the CAT backend instead of a sound card. Everything around it is
// unchanged — the same PTT before and after, the same gain, the same files —
// which is the point: the audio takes a different road, not a different route.
import (
"fmt"
"hamlog/internal/applog"
"hamlog/internal/audio"
"hamlog/internal/cat"
)
// tciTXPlayer hands one message to the radio.
//
// The controller is fetched on the CAT goroutine and the message is then played
// OFF it. Playing on it would hold that goroutine for the length of the
// message, and everything else about the rig — frequency, mode, PTT state —
// goes through the same place: a ten-second call would freeze the display and
// the antenna following for ten seconds. The TCI backend serialises its own
// writes, so this is safe to call from here.
func (a *App) tciTXPlayer(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
if a.cat == nil {
return fmt.Errorf("CAT not initialized")
}
type txPlayer interface {
PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error
}
var player txPlayer
err := a.cat.TCIAudioDo(func(t cat.TCIAudioController) error {
p, ok := t.(txPlayer)
if !ok {
return fmt.Errorf("this radio cannot take transmit audio over its CAT link")
}
player = p
return nil
})
if err != nil {
return err
}
return player.PlayTXAudio(pcm, rate, ch, bits, stop)
}
// installTCITXPlayer offers the radio as an audio output, or withdraws it.
//
// Withdrawing matters as much as offering: a radio that has gone away must stop
// being a device the voice keyer will happily "play" to, or a message goes
// nowhere and the operator hears their own PTT click and assumes it worked.
func (a *App) installTCITXPlayer(on bool) {
if !on {
audio.SetNetworkPlayer(nil)
return
}
audio.SetNetworkPlayer(a.tciTXPlayer)
applog.Printf("tci: the radio is available as an audio output — no virtual cable needed for the voice keyer")
}
+128
View File
@@ -0,0 +1,128 @@
package main
// Feeding the QSO recorder from the TCI stream.
//
// The recorder works in 16 kHz mono, which is what its files and its mixing are
// built around; TCI delivers 48 kHz stereo float32. The conversion is the whole
// of this file, and it happens here rather than in internal/cat because the
// radio's job is to hand over what it sent, not to know what the recorder wants.
//
// Confirmed on a SunSDR (ExpertSDR3 1.5): 2048 samples a frame, 8192 bytes,
// four bytes per sample — and a test recording that plays back clean.
import (
"encoding/binary"
"hamlog/internal/applog"
"hamlog/internal/audio"
"hamlog/internal/cat"
)
// tciRecordSink pushes the receive stream into the QSO recorder.
//
// Installed whenever the TCI backend starts, and harmless when nothing is
// recording: PushRX drops what arrives unless a QSO is being captured, so the
// cost while idle is a decimation and a function call.
func (a *App) tciRecordSink(rate int, samples []float32) {
if a.qsoRec == nil || len(samples) == 0 {
return
}
a.qsoRec.PushRX(tciToRecorderPCM(rate, samples))
}
// tciToRecorderPCM converts the stream's mono float samples to the recorder's
// 16-bit PCM at its own rate.
//
// Averaging rather than picking every third sample: dropping samples aliases
// everything above 8 kHz back down into the voice band, and on a receiver that
// is hiss — the one thing a QSO recording has plenty of. A three-tap mean is a
// crude low-pass, but it is a low-pass, and it costs two additions.
func tciToRecorderPCM(rate int, samples []float32) []byte {
if rate <= 0 {
rate = 48000
}
step := rate / audio.RecorderSampleRate
if step < 1 {
step = 1
}
out := make([]byte, 0, (len(samples)/step)*2)
for i := 0; i+step <= len(samples); i += step {
var sum float32
for j := 0; j < step; j++ {
sum += samples[i+j]
}
v := sum / float32(step)
if v > 1 {
v = 1
}
if v < -1 {
v = -1
}
var b [2]byte
binary.LittleEndian.PutUint16(b[:], uint16(int16(v*32767)))
out = append(out, b[0], b[1])
}
return out
}
// startTCIRecording opens the receive stream and routes it to the recorder.
//
// Called when the TCI backend comes up, and only when the operator has asked
// for it: opening a 384 kB/s stream on a station that records nothing is work
// the radio does for nobody.
func (a *App) startTCIRecording() {
if a.cat == nil {
return
}
// Two ways to ask for the same thing: the option in the TCI section, or
// simply choosing the radio as the "From radio" device. The second is where
// an operator looks first — it is the question they are already answering —
// so it has to work as well as the tick box.
cfg, _ := a.GetAudioSettings()
if a.settingOr(keyTCIRecAudio, "") != "1" && cfg.FromRadio != audio.NetworkDeviceID {
return
}
err := a.cat.TCIAudioDo(func(t cat.TCIAudioController) error {
if s, ok := t.(interface {
SetTCIAudioSink(func(int, []float32))
}); ok {
s.SetTCIAudioSink(a.tciRecordSink)
}
return t.StartTCIAudio(0, 48000)
})
if err != nil {
applog.Printf("tci: could not open the receive stream for recording: %v", err)
return
}
applog.Printf("tci: recording the receive audio over TCI — no virtual cable needed")
}
// keyTCIRecAudio turns it on. Off by default: it replaces whatever sound card
// the operator has already wired up, and a setting that changes where a
// recording comes from should be asked for rather than assumed.
const keyTCIRecAudio = "audio.tci_rx"
// GetTCIRecordAudio reports whether the recorder takes its audio from the radio.
func (a *App) GetTCIRecordAudio() bool { return a.settingOr(keyTCIRecAudio, "") == "1" }
// SetTCIRecordAudio turns it on or off, and applies it NOW rather than at the
// next restart: an option that needs the application relaunched to take effect
// reads as an option that does not work.
func (a *App) SetTCIRecordAudio(on bool) error {
a.setSetting(keyTCIRecAudio, boolStr(on))
if on {
a.startTCIRecording()
return nil
}
if a.cat == nil {
return nil
}
return a.cat.TCIAudioDo(func(t cat.TCIAudioController) error {
if s, ok := t.(interface {
SetTCIAudioSink(func(int, []float32))
}); ok {
s.SetTCIAudioSink(nil)
}
return t.StopTCIAudio()
})
}
+47
View File
@@ -0,0 +1,47 @@
package main
import (
"encoding/binary"
"testing"
"hamlog/internal/audio"
)
// The stream is 48 kHz and the recorder works at 16 — three to one. A
// recording that keeps every sample plays back three times too fast, which is
// the fault that gets blamed on the decoding rather than on the rate.
func TestTheStreamIsResampledToTheRecorderRate(t *testing.T) {
const in = 48000
samples := make([]float32, in/10) // a tenth of a second
pcm := tciToRecorderPCM(in, samples)
want := (audio.RecorderSampleRate / 10) * 2 // 16-bit
if len(pcm) != want {
t.Fatalf("a tenth of a second produced %d bytes, want %d", len(pcm), want)
}
}
// Full scale must arrive as full scale: a conversion that quietly halves the
// level turns a recording into evidence of a fault that is not there.
func TestFullScaleSurvivesTheConversion(t *testing.T) {
samples := make([]float32, 12)
for i := range samples {
samples[i] = 1
}
pcm := tciToRecorderPCM(48000, samples)
if len(pcm) < 2 {
t.Fatal("no samples came out")
}
v := int16(binary.LittleEndian.Uint16(pcm[:2]))
if v < 32000 {
t.Fatalf("full scale came out at %d", v)
}
}
// A rate the recorder already works in is passed through rather than mangled by
// a division that would round to nothing.
func TestAStreamAtTheRecorderRateIsNotDecimated(t *testing.T) {
samples := make([]float32, 160)
if got, want := len(tciToRecorderPCM(audio.RecorderSampleRate, samples)), 160*2; got != want {
t.Fatalf("%d bytes, want %d", got, want)
}
}
+175
View File
@@ -0,0 +1,175 @@
package main
// Recording a few seconds of the TCI stream to a WAV file.
//
// Counting frames proves a socket is delivering bytes. It does not prove those
// bytes are the receiver's audio, at the right rate, in the right order — a
// stream decoded with the channels swapped, the width wrong or the samples
// misaligned counts exactly as well as a correct one and sounds like a fan.
//
// So the test is a file the operator can play. It is the same reason the CW
// decoder was validated on the air rather than on a spectrogram.
import (
"encoding/binary"
"fmt"
"math"
"os"
"path/filepath"
"sync"
"time"
"hamlog/internal/applog"
"hamlog/internal/cat"
)
// tciRec collects samples while a test recording is running.
type tciRec struct {
mu sync.Mutex
active bool
rate int
samples []float32
want int // how many samples to collect before stopping
}
var tciRecorder tciRec
// RecordTCIAudio captures seconds of the TCI receive stream and writes a WAV
// next to the QSO recordings. Returns the path.
//
// The stream has to be open already — this listens to what is arriving rather
// than opening anything, so a recording can never leave a stream running that
// the operator did not ask for.
func (a *App) RecordTCIAudio(seconds int) (string, error) {
if a.cat == nil {
return "", fmt.Errorf("CAT not initialized")
}
if seconds <= 0 || seconds > 60 {
seconds = 10
}
// Rate from the radio, not assumed: the file's header has to match what was
// actually streamed or the recording plays at the wrong speed, which is the
// one fault that would be blamed on the decoding.
st := a.GetTCIAudioStatus()
if !st.Running {
return "", fmt.Errorf("open the TCI audio stream first")
}
rate := st.SampleRate
if rate <= 0 {
rate = 48000
}
tciRecorder.mu.Lock()
if tciRecorder.active {
tciRecorder.mu.Unlock()
return "", fmt.Errorf("a test recording is already running")
}
tciRecorder.active = true
tciRecorder.rate = rate
tciRecorder.want = rate * seconds
tciRecorder.samples = make([]float32, 0, tciRecorder.want)
tciRecorder.mu.Unlock()
err := a.cat.TCIAudioDo(func(t cat.TCIAudioController) error {
s, ok := t.(interface{ SetTCIAudioSink(func(int, []float32)) })
if !ok {
return fmt.Errorf("this backend has no audio sink")
}
s.SetTCIAudioSink(func(_ int, samples []float32) {
tciRecorder.mu.Lock()
defer tciRecorder.mu.Unlock()
if !tciRecorder.active {
return
}
tciRecorder.samples = append(tciRecorder.samples, samples...)
})
return nil
})
if err != nil {
tciRecorder.mu.Lock()
tciRecorder.active = false
tciRecorder.mu.Unlock()
return "", err
}
// Wait for the samples rather than for the clock: a stream that stalls
// halfway should produce a short file that says so, not a long one padded
// with silence that hides it.
deadline := time.Now().Add(time.Duration(seconds+5) * time.Second)
for {
tciRecorder.mu.Lock()
got := len(tciRecorder.samples)
want := tciRecorder.want
tciRecorder.mu.Unlock()
if got >= want || time.Now().After(deadline) {
break
}
time.Sleep(100 * time.Millisecond)
}
tciRecorder.mu.Lock()
tciRecorder.active = false
pcm := tciRecorder.samples
tciRecorder.samples = nil
tciRecorder.mu.Unlock()
_ = a.cat.TCIAudioDo(func(t cat.TCIAudioController) error {
if s, ok := t.(interface{ SetTCIAudioSink(func(int, []float32)) }); ok {
s.SetTCIAudioSink(nil)
}
return nil
})
if len(pcm) == 0 {
return "", fmt.Errorf("nothing arrived on the stream")
}
path := filepath.Join(a.qsoRecDir(), fmt.Sprintf("tci-test-%s.wav", time.Now().Format("20060102-150405")))
if err := writeMonoWAV(path, pcm, rate); err != nil {
return "", err
}
applog.Printf("tci: wrote %.1f s of receive audio to %s (%d Hz)", float64(len(pcm))/float64(rate), path, rate)
return path, nil
}
// writeMonoWAV writes float samples as 16-bit mono PCM.
//
// Its own writer rather than internal/audio's: that one is nailed to the voice
// keyer's rate, and a test recording written at the wrong rate would play back
// at the wrong speed — the one fault that looks exactly like a decoding error.
func writeMonoWAV(path string, samples []float32, rate int) error {
data := make([]byte, len(samples)*2)
for i, v := range samples {
s := int(math.Round(float64(v) * 32767))
if s > 32767 {
s = 32767
}
if s < -32768 {
s = -32768
}
binary.LittleEndian.PutUint16(data[i*2:], uint16(int16(s)))
}
var hdr [44]byte
copy(hdr[0:], "RIFF")
binary.LittleEndian.PutUint32(hdr[4:], uint32(36+len(data)))
copy(hdr[8:], "WAVEfmt ")
binary.LittleEndian.PutUint32(hdr[16:], 16) // PCM chunk size
binary.LittleEndian.PutUint16(hdr[20:], 1) // PCM
binary.LittleEndian.PutUint16(hdr[22:], 1) // mono
binary.LittleEndian.PutUint32(hdr[24:], uint32(rate))
binary.LittleEndian.PutUint32(hdr[28:], uint32(rate*2))
binary.LittleEndian.PutUint16(hdr[32:], 2) // block align
binary.LittleEndian.PutUint16(hdr[34:], 16) // bits
copy(hdr[36:], "data")
binary.LittleEndian.PutUint32(hdr[40:], uint32(len(data)))
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
if _, err := f.Write(hdr[:]); err != nil {
return err
}
_, err = f.Write(data)
return err
}
+1 -1
View File
@@ -1 +1 @@
f9b41e192918fa2511f68cd1b361fcd3
704fe1bf370b669665df0606fae8a69d
+89 -1
View File
@@ -58,7 +58,7 @@ import {
GetFolderSync, SaveFolderSync, PickFolderSyncFolder, GetFolderSyncStatus, SyncFolderNow,
GetRelayAuto, SaveRelayAuto, GetStationDevices,
GetAwardDefs, GetTrackedAwards, SaveTrackedAwards,
GetBandOpenSettings, SaveBandOpenSettings, GetGridScopeSettings, SaveGridScopeSettings, GetPSKReporterStatus, GetChaseNewGrids, SetChaseNewGrids, GetChaseNew, SetChaseNew, GetGridCacheStatus, GetLinkedAmps, SetLinkedAmps, GetSpotTTLMinutes, SetSpotTTLMinutes, GetSpotMax, SetSpotMax,
GetBandOpenSettings, SaveBandOpenSettings, GetGridScopeSettings, SaveGridScopeSettings, GetPSKReporterStatus, GetChaseNewGrids, SetChaseNewGrids, GetChaseNew, SetChaseNew, GetGridCacheStatus, GetLinkedAmps, SetLinkedAmps, GetSpotTTLMinutes, SetSpotTTLMinutes, GetSpotMax, SetSpotMax, StartTCIAudio, StopTCIAudio, GetTCIAudioStatus, RecordTCIAudio, GetTCIRecordAudio, SetTCIRecordAudio, ProbeTCITransmit,
} from '../../wailsjs/go/main/App';
import type { profile as profileModels } from '../../wailsjs/go/models';
import type { LookupSettingsForm, StationSettingsForm, ListsSettingsForm, ModePresetForm } from '@/types';
@@ -2035,6 +2035,21 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
const [spotTTL, setSpotTTL] = useState(0);
const [spotTTLText, setSpotTTLText] = useState('0');
const [spotMaxText, setSpotMaxText] = useState('1000');
// TCI receive-audio test bench. Polled only while the stream is open: a panel
// that asks the backend twice a second for a stream nobody started is work
// done for nothing.
const [tciAudio, setTciAudio] = useState<any>({ running: false, sample_rate: 0, frames: 0, peak_db: -99 });
const [tciRecBusy, setTciRecBusy] = useState(false);
const [tciTXBusy, setTciTXBusy] = useState(false);
// Whether the QSO recorder takes its audio from the radio's own stream.
const [tciRec, setTciRec] = useState(false);
useEffect(() => { GetTCIRecordAudio().then((v: boolean) => setTciRec(!!v)).catch(() => {}); }, []);
const [tciRecPath, setTciRecPath] = useState('');
useEffect(() => {
if (!tciAudio.running) return;
const id = window.setInterval(() => { GetTCIAudioStatus().then(setTciAudio).catch(() => {}); }, 500);
return () => window.clearInterval(id);
}, [tciAudio.running]);
const [gridStat, setGridStat] = useState<any>(null);
const [pskrStatus, setPskrStatus] = useState<any>(null);
const saveBandOpen = async (next: any) => {
@@ -6746,6 +6761,79 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<strong>{t('aud.fromRadioShort')}</strong> {t('aud.explainFrom')}{' '}
<strong>{t('aud.toRadioShort')}</strong> {t('aud.explainTo')}
</p>
{/* TCI receive audio EXPERIMENTAL, and the panel says so.
A SunSDR already carries its receive audio on the WebSocket that
carries its commands, so none of the devices above need to exist
for it: no virtual cable, no second sound card. This is the test
bench for that path it opens the stream and reports what really
arrives, because "the stream is open" and "audio is arriving" are
different claims and only the second one is worth anything. */}
<div className="rounded-md border border-border p-3 space-y-2">
<div className="text-xs font-medium">{t('aud.tciTitle')}</div>
<div className="flex items-center gap-3 flex-wrap">
<Button variant={tciAudio.running ? 'default' : 'outline'} size="sm" className="h-8"
onClick={() => {
const p = tciAudio.running ? StopTCIAudio() : StartTCIAudio(0, 48000);
p.then(() => GetTCIAudioStatus().then(setTciAudio))
.catch((e: any) => setTciAudio((s: any) => ({ ...s, last_err: String(e?.message ?? e) })));
}}>
{tciAudio.running ? t('aud.tciStop') : t('aud.tciStart')}
</Button>
{tciAudio.running && (
<span className="text-[11px] font-mono text-muted-foreground">
{tciAudio.sample_rate || 0} Hz · {tciAudio.frames || 0} frames ·{' '}
{tciAudio.peak_db > -90 ? tciAudio.peak_db.toFixed(1) + ' dBFS' : t('aud.tciSilent')}
</span>
)}
</div>
{/* The test that actually settles it. Frames arriving proves a
socket is delivering bytes; it says nothing about whether those
bytes are the receiver's audio, at the right rate, in the right
order. A file the operator can PLAY says all three at once. */}
{tciAudio.running && (
<div className="flex items-center gap-3 flex-wrap">
<Button variant="outline" size="sm" className="h-8" disabled={tciRecBusy}
onClick={() => {
setTciRecBusy(true); setTciRecPath('');
RecordTCIAudio(10)
.then((p: string) => setTciRecPath(p))
.catch((e: any) => setTciAudio((s: any) => ({ ...s, last_err: String(e?.message ?? e) })))
.finally(() => setTciRecBusy(false));
}}>
{tciRecBusy ? t('aud.tciRecBusy') : t('aud.tciRec')}
</Button>
{!!tciRecPath && <span className="text-[11px] font-mono text-muted-foreground truncate">{tciRecPath}</span>}
</div>
)}
{/* The transmit experiment. It KEYS THE RADIO, which is why it is
worded as a warning and not as another test button: a first pass
on real hardware showed the radio sends nothing extra while the
operator keys it by hand, so the only way to learn what it wants
is to key it from here and push a tone. */}
<div className="rounded border border-caution-border bg-caution-muted p-2 space-y-1.5">
<Button variant="outline" size="sm" className="h-8" disabled={tciTXBusy}
onClick={() => {
setTciTXBusy(true);
ProbeTCITransmit(5)
.catch((e: any) => setTciAudio((s: any) => ({ ...s, last_err: String(e?.message ?? e) })))
.finally(() => setTciTXBusy(false));
}}>
{tciTXBusy ? t('aud.tciTXBusy') : t('aud.tciTX')}
</Button>
<p className="text-[11px] text-caution-muted-foreground">{t('aud.tciTXWarn')}</p>
</div>
{!!tciAudio.last_err && <p className="text-[11px] text-danger">{tciAudio.last_err}</p>}
<label className="flex items-start gap-2 text-xs cursor-pointer">
<Checkbox className="mt-0.5" checked={tciRec}
onCheckedChange={(c) => { setTciRec(!!c); SetTCIRecordAudio(!!c).catch(() => {}); }} />
<span>
{t('aud.tciRecord')}
<span className="block text-muted-foreground">{t('aud.tciRecordHint')}</span>
</span>
</label>
<p className="text-[11px] text-muted-foreground">{t('aud.tciHint')}</p>
</div>
<div className="flex items-center gap-3">
<Button
variant={monitorOn ? 'default' : 'outline'}
+2 -2
View File
@@ -494,7 +494,7 @@ const en: Dict = {
'aud.noneDefault': '— none / system default —', 'aud.defaultTag': '(default)',
'aud.fromRadioShort': 'From Radio', 'aud.toRadioShort': 'To Radio', 'aud.explainFrom': '= what you receive (used by the QSO recorder).', 'aud.explainTo': '= where voice-keyer messages are transmitted.',
'aud.monitorTitle': "Hear the rig's RX audio (From Radio) through your Listening device", 'aud.listenRadio': '▶ Listen to radio', 'aud.stopListening': '■ Stop listening',
'aud.monitorOn': 'RX monitor running — From Radio → Listening device.', 'aud.monitorHint': 'Live-monitor the rig here (USB codec now; network audio later).',
'aud.monitorOn': 'RX monitor running — From Radio → Listening device.', 'aud.tciTitle': 'SunSDR receive audio over TCI (experimental)', 'aud.tciStart': 'Open the stream', 'aud.tciStop': 'Close the stream', 'aud.tciRec': 'Record 10 s to listen', 'aud.tciRecBusy': 'Recording…', 'aud.tciSilent': 'silent', 'aud.tciRecord': 'Record QSOs from this stream', 'aud.tciTX': 'Test transmit — 5 s tone', 'aud.tciTXBusy': 'Transmitting…', 'aud.tciTXWarn': 'THIS TRANSMITS. Put the radio on a dummy load first. It keys the radio and sends a 1 kHz tone over TCI for five seconds, to find out whether the transmit half of the stream works — the log holds the answer.', 'aud.tciRecordHint': 'The QSO recorder takes the receive audio from the radio instead of a sound card — no virtual cable, nothing to select above. Your microphone is still recorded from the device chosen there.', 'aud.tciHint': 'Takes the receive audio straight from the radio over TCI, with no virtual audio cable and no second sound card. Receive only for now — the voice keyer still uses the devices above. Requires the CAT backend to be TCI.', 'aud.monitorHint': 'Live-monitor the rig here (USB codec now; network audio later).',
'aud.txTitle': 'Key PTT and pipe your live mic into the rig (To Radio device)', 'aud.talkRadio': '🎙 Talk to radio (TX)', 'aud.stopTalk': '■ Stop talking (TX)',
'aud.txOn': 'TRANSMITTING — mic → To Radio, PTT keyed. Click to stop.', 'aud.txHint': 'Live mic → rig with PTT (USB now; network TX later).',
'aud.recorder': 'QSO recorder', 'aud.recordEvery': 'Record every QSO to an audio file (From Radio + your mic)', 'aud.recFolder': 'Recordings folder', 'aud.browse': 'Browse…',
@@ -962,7 +962,7 @@ const fr: Dict = {
'aud.noneDefault': '— aucun / défaut système —', 'aud.defaultTag': '(défaut)',
'aud.fromRadioShort': 'Depuis la radio', 'aud.toRadioShort': 'Vers la radio', 'aud.explainFrom': "= ce que vous recevez (utilisé par l'enregistreur de QSO).", 'aud.explainTo': '= où sont émis les messages du manipulateur vocal.',
'aud.monitorTitle': "Écouter l'audio RX du poste (Depuis la radio) sur votre périphérique d'écoute", 'aud.listenRadio': '▶ Écouter la radio', 'aud.stopListening': "■ Arrêter l'écoute",
'aud.monitorOn': "Écoute RX active — Depuis la radio → périphérique d'écoute.", 'aud.monitorHint': "Écoute directe du poste (codec USB pour l'instant ; audio réseau plus tard).",
'aud.monitorOn': "Écoute RX active — Depuis la radio → périphérique d'écoute.", 'aud.tciTitle': 'Audio de réception SunSDR par TCI (expérimental)', 'aud.tciStart': 'Ouvrir le flux', 'aud.tciStop': 'Fermer le flux', 'aud.tciRec': 'Enregistrer 10 s pour écoute', 'aud.tciRecBusy': 'Enregistrement…', 'aud.tciSilent': 'silence', 'aud.tciRecord': 'Enregistrer les QSO depuis ce flux', 'aud.tciTX': "Test d'émission — tonalité 5 s", 'aud.tciTXBusy': 'Émission…', 'aud.tciTXWarn': "CECI ÉMET. Mettre la radio sur charge fictive d'abord. Le poste est passé en émission et une tonalité de 1 kHz est envoyée par TCI pendant cinq secondes, pour savoir si la moitié émission du flux fonctionne — la réponse est dans le journal.", 'aud.tciRecordHint': "L'enregistreur prend l'audio de réception sur la radio au lieu d'une carte son — aucun câble virtuel, rien à choisir au-dessus. Ton micro reste enregistré depuis le périphérique sélectionné là-haut.", 'aud.tciHint': "Prend l'audio de réception directement sur la radio via TCI, sans câble audio virtuel ni seconde carte son. Réception seulement pour l'instant — le manipulateur vocal utilise toujours les périphériques ci-dessus. Nécessite le CAT réglé sur TCI.", 'aud.monitorHint': "Écoute directe du poste (codec USB pour l'instant ; audio réseau plus tard).",
'aud.txTitle': 'Activer le PTT et envoyer votre micro vers le poste (périphérique « Vers la radio »)', 'aud.talkRadio': '🎙 Parler à la radio (TX)', 'aud.stopTalk': '■ Arrêter de parler (TX)',
'aud.txOn': 'ÉMISSION — micro → Vers la radio, PTT activé. Cliquez pour arrêter.', 'aud.txHint': "Micro direct → poste avec PTT (USB pour l'instant ; TX réseau plus tard).",
'aud.recorder': 'Enregistreur de QSO', 'aud.recordEvery': 'Enregistrer chaque QSO dans un fichier audio (Depuis la radio + votre micro)', 'aud.recFolder': 'Dossier des enregistrements', 'aud.browse': 'Parcourir…',
+14
View File
@@ -575,6 +575,10 @@ export function GetStationSettings():Promise<main.StationSettings>;
export function GetStationStatus():Promise<Array<main.StationDeviceStatus>>;
export function GetTCIAudioStatus():Promise<cat.TCIAudioStatus>;
export function GetTCIRecordAudio():Promise<boolean>;
export function GetTelemetryEnabled():Promise<boolean>;
export function GetTrackedAwards():Promise<Array<string>>;
@@ -837,6 +841,8 @@ export function PickSaveDatabase():Promise<string>;
export function PopulateBuiltinReferences(arg1:string):Promise<number>;
export function ProbeTCITransmit(arg1:number):Promise<void>;
export function PublishLogNow():Promise<string>;
export function QSLCopyTemplateToActiveProfile(arg1:number):Promise<number>;
@@ -905,6 +911,8 @@ export function RecomputeAllAwardRefs():Promise<number>;
export function RecomputeAwardRefsForCode(arg1:string):Promise<number>;
export function RecordTCIAudio(arg1:number):Promise<string>;
export function RefreshCtyDat():Promise<main.CtyDatInfo>;
export function RefreshKenwood():Promise<void>;
@@ -1157,6 +1165,8 @@ export function SetSpotMax(arg1:number):Promise<void>;
export function SetSpotTTLMinutes(arg1:number):Promise<void>;
export function SetTCIRecordAudio(arg1:boolean):Promise<void>;
export function SetTelemetryEnabled(arg1:boolean):Promise<void>;
export function SetUIPref(arg1:string,arg2:string):Promise<void>;
@@ -1209,10 +1219,14 @@ export function SetYaesuVOX(arg1:boolean):Promise<void>;
export function StartCWDecoder():Promise<void>;
export function StartTCIAudio(arg1:number,arg2:number):Promise<void>;
export function StationSetRelay(arg1:string,arg2:number,arg3:boolean):Promise<void>;
export function StopCWDecoder():Promise<void>;
export function StopTCIAudio():Promise<void>;
export function SwitchCATRig(arg1:number):Promise<void>;
export function SyncFolderNow():Promise<number>;
+28
View File
@@ -1090,6 +1090,14 @@ export function GetStationStatus() {
return window['go']['main']['App']['GetStationStatus']();
}
export function GetTCIAudioStatus() {
return window['go']['main']['App']['GetTCIAudioStatus']();
}
export function GetTCIRecordAudio() {
return window['go']['main']['App']['GetTCIRecordAudio']();
}
export function GetTelemetryEnabled() {
return window['go']['main']['App']['GetTelemetryEnabled']();
}
@@ -1614,6 +1622,10 @@ export function PopulateBuiltinReferences(arg1) {
return window['go']['main']['App']['PopulateBuiltinReferences'](arg1);
}
export function ProbeTCITransmit(arg1) {
return window['go']['main']['App']['ProbeTCITransmit'](arg1);
}
export function PublishLogNow() {
return window['go']['main']['App']['PublishLogNow']();
}
@@ -1750,6 +1762,10 @@ export function RecomputeAwardRefsForCode(arg1) {
return window['go']['main']['App']['RecomputeAwardRefsForCode'](arg1);
}
export function RecordTCIAudio(arg1) {
return window['go']['main']['App']['RecordTCIAudio'](arg1);
}
export function RefreshCtyDat() {
return window['go']['main']['App']['RefreshCtyDat']();
}
@@ -2254,6 +2270,10 @@ export function SetSpotTTLMinutes(arg1) {
return window['go']['main']['App']['SetSpotTTLMinutes'](arg1);
}
export function SetTCIRecordAudio(arg1) {
return window['go']['main']['App']['SetTCIRecordAudio'](arg1);
}
export function SetTelemetryEnabled(arg1) {
return window['go']['main']['App']['SetTelemetryEnabled'](arg1);
}
@@ -2358,6 +2378,10 @@ export function StartCWDecoder() {
return window['go']['main']['App']['StartCWDecoder']();
}
export function StartTCIAudio(arg1, arg2) {
return window['go']['main']['App']['StartTCIAudio'](arg1, arg2);
}
export function StationSetRelay(arg1, arg2, arg3) {
return window['go']['main']['App']['StationSetRelay'](arg1, arg2, arg3);
}
@@ -2366,6 +2390,10 @@ export function StopCWDecoder() {
return window['go']['main']['App']['StopCWDecoder']();
}
export function StopTCIAudio() {
return window['go']['main']['App']['StopTCIAudio']();
}
export function SwitchCATRig(arg1) {
return window['go']['main']['App']['SwitchCATRig'](arg1);
}
+22
View File
@@ -1210,6 +1210,28 @@ export namespace cat {
this.fixed = source["fixed"];
}
}
export class TCIAudioStatus {
running: boolean;
sample_rate: number;
frames: number;
samples: number;
peak_db: number;
last_err?: string;
static createFrom(source: any = {}) {
return new TCIAudioStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.running = source["running"];
this.sample_rate = source["sample_rate"];
this.frames = source["frames"];
this.samples = source["samples"];
this.peak_db = source["peak_db"];
this.last_err = source["last_err"];
}
}
export class YaesuTXState {
available: boolean;
model?: string;
+15 -1
View File
@@ -157,7 +157,21 @@ func (m *Manager) Play(deviceID, path string, gainPct int) error {
// instantly, the PTT is released 120 ms later, and NOTHING says why —
// which is exactly what a station heard as "it plays once, then never
// again": the call succeeded, the sound did not.
if err := playPCM(deviceID, pcm, rate, ch, bits, stop); err != nil {
play := func() error { return playPCM(deviceID, pcm, rate, ch, bits, stop) }
if deviceID == NetworkDeviceID {
// Straight to the radio over its own link. Decided HERE rather than
// inside playPCM because there is no Windows endpoint to open: asked
// for one, the system complains about a missing device instead of
// saying the true thing, which is that no radio is connected.
fn := networkPlayer()
play = func() error {
if fn == nil {
return errNoNetworkRadio
}
return fn(pcm, rate, ch, bits, stop)
}
}
if err := play(); err != nil {
LogSink("audio: playback on %q failed: %v", DeviceName(deviceID), err)
}
m.mu.Lock()
+67
View File
@@ -0,0 +1,67 @@
package audio
// Playing a message through the RADIO instead of a sound card.
//
// A SunSDR takes its transmit audio over TCI, on the same socket as the
// commands, so the voice keyer can hand it the message directly: no virtual
// cable, no second sound card, no Windows mixer between the recording and the
// air. To everything above, that radio is simply another output device.
//
// The device it presents itself as is a name rather than a WASAPI endpoint id,
// which is why Play checks for it before opening anything: there is no endpoint
// to open, and asking Windows for one produces a confusing error about a device
// that does not exist rather than the truth, which is that nothing is connected
// to the radio.
import (
"errors"
"sync"
)
// NetworkDeviceID is the id the radio-over-network output carries in the
// settings and in the device lists. A fixed string, not a Windows endpoint id:
// it is chosen by us and must survive a radio being switched off and on.
const NetworkDeviceID = "net:radio"
// NetworkPlayer sends already-decoded PCM to the radio, returning when the
// message has been played or when stop is closed.
//
// It carries the same arguments as the sound-card path so that Play can hand
// over whatever it read, and the radio can decide what converting it needs —
// the sample rate a WAV was recorded at is not the radio's business until the
// moment it has to be resampled.
type NetworkPlayer func(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error
var (
netMu sync.RWMutex
netPlayer NetworkPlayer
)
// SetNetworkPlayer installs (or clears, with nil) the radio's transmit path.
//
// Package-level rather than per-Manager: there is one radio, the CAT backend
// owns it, and a Manager that happened to be built before the radio connected
// would otherwise be permanently unable to reach it.
func SetNetworkPlayer(fn NetworkPlayer) {
netMu.Lock()
netPlayer = fn
netMu.Unlock()
}
// networkPlayer returns the installed player, or nil.
func networkPlayer() NetworkPlayer {
netMu.RLock()
defer netMu.RUnlock()
return netPlayer
}
// NetworkPlayerReady says whether a radio is currently able to take transmit
// audio, so the settings panel can offer the option honestly rather than
// listing a device that would fail when used.
func NetworkPlayerReady() bool { return networkPlayer() != nil }
// errNoNetworkRadio is what a message played to a radio that is not there
// comes back with. Named, because "the device could not be opened" would send
// an operator hunting through Windows sound settings for a device that never
// existed.
var errNoNetworkRadio = errors.New("no radio is connected to take the audio — check the CAT link (the radio output only works with a TCI radio)")
+9
View File
@@ -0,0 +1,9 @@
package audio
// RecorderSampleRate is the rate the QSO recorder works in.
//
// Exported because a source that is NOT a sound card — the TCI receive stream,
// the Icom network audio — has to resample into it, and hard-coding 16000 at
// each of those call sites is how one of them ends up at the wrong speed after
// this constant is ever changed.
const RecorderSampleRate = sampleRate
+1
View File
@@ -14,6 +14,7 @@ import (
// any device regardless of its native mix format.
const (
sampleRate = 16000
channels = 1
bitsPerSample = 16
blockAlign = channels * bitsPerSample / 8 // bytes per frame (=2)
+50 -1
View File
@@ -34,6 +34,16 @@ type TCI struct {
OnSpotClick func(callsign string, freqHz int64)
unhandledSeen map[string]bool // log each unknown TCI message type once
// audio holds the receive-audio stream — see tci_audio.go. TCI carries it
// on this same WebSocket, which is what lets a SunSDR record and decode
// without a virtual audio cable in the way.
audio tciAudio
// One writer at a time. send() held the lock only long enough to READ conn,
// which was enough while every command came from the poll loop — a stream of
// audio frames from a second goroutine is not, and gorilla panics on a
// concurrent write rather than corrupting the socket quietly.
wmu sync.Mutex // serialises writes to the socket (text AND binary)
mu sync.Mutex // guards conn + writes + state
conn *websocket.Conn
dialCancel context.CancelFunc // cancels an in-flight Connect dial (Interrupt/Stop)
@@ -57,6 +67,10 @@ type TCI struct {
// never sends TX_ENABLE at all, from being treated as refusing: without a
// word from the radio we key and let it decide.
txAllowed bool
// drive is the radio's transmit drive, 0-100. Kept because a quiet
// transmission has two possible causes — our level or the radio's — and a
// log that names both settles it in one line instead of an evening.
drive int
txAllowedKnown bool
lastSig string // last logged state signature (log only on change)
@@ -341,6 +355,8 @@ func (t *TCI) send(cmd string) error {
if c == nil {
return fmt.Errorf("tci: not connected")
}
t.wmu.Lock()
defer t.wmu.Unlock()
_ = c.SetWriteDeadline(time.Now().Add(3 * time.Second))
if err := c.WriteMessage(websocket.TextMessage, []byte(cmd)); err != nil {
debugLog.Printf("TCI: send %q failed: %v", cmd, err)
@@ -354,10 +370,18 @@ func (t *TCI) send(cmd string) error {
// connection closes.
func (t *TCI) reader(conn *websocket.Conn) {
for {
_, data, err := conn.ReadMessage()
mt, data, err := conn.ReadMessage()
if err != nil {
break
}
// TEXT frames are commands, BINARY frames are streams. The type used to
// be ignored and every frame split on ';' — harmless only for as long as
// no stream was ever opened, since audio bytes would then have been fed
// to the command parser a hundred times a second.
if wsMessageIsBinary(mt) {
t.handleBinary(data)
continue
}
// A frame may carry several ";"-terminated commands.
for _, cmd := range strings.Split(string(data), ";") {
t.handle(strings.TrimSpace(cmd))
@@ -393,6 +417,16 @@ func (t *TCI) handle(msg string) {
switch strings.ToLower(name) {
case "device":
t.device = strings.TrimSpace(args)
// The radio ANNOUNCES its audio format at connect —
// "audio_stream_sample_type:float32" and "audio_stream_channels:2" — which
// is better evidence than anything derived from a frame, and it arrives
// before the first frame does. Both were being logged as unhandled.
case "audio_stream_sample_type":
t.audio.declaredType = strings.TrimSpace(args)
case "audio_stream_channels":
if n, err := strconv.Atoi(strings.TrimSpace(args)); err == nil && n > 0 && n <= 8 {
t.audio.declaredChans = n
}
case "ready", "start":
t.ready = true
case "stop":
@@ -421,7 +455,22 @@ func (t *TCI) handle(msg string) {
}
case "trx":
if get(0) == "0" {
was := t.tx
t.tx = get(1) == "true"
// Said out loud, every time. The transmit side of TCI can only be
// written from a log of a real transmission, and the first one came
// back without a single line to say whether the radio had even been
// keyed — which left the interesting question, why no transmit
// frames, indistinguishable from nobody having pressed anything.
if was != t.tx {
t.noteTXTransition(t.tx)
}
}
case "drive":
if get(0) == "0" {
if v, err := strconv.Atoi(get(1)); err == nil {
t.drive = v
}
}
case "tx_enable":
if get(0) == "0" {
+417
View File
@@ -0,0 +1,417 @@
//go:build windows
package cat
// TCI audio — receiving the radio's audio over the same WebSocket that carries
// the commands, so a SunSDR needs no virtual audio cable.
//
// TCI mixes two kinds of frame on one socket: TEXT frames are the commands
// ("trx:0,true;"), BINARY frames are streams. A binary frame is a fixed header
// followed by float32 samples:
//
// uint32 receiver which receiver the stream belongs to
// uint32 sampleRate Hz
// uint32 format 0 = float32
// uint32 codec 0 = uncompressed
// uint32 crc unused in practice
// uint32 length samples in the payload
// uint32 type which stream this is (see tciStream*)
// uint32 reserved[9]
// float32 payload[…] stereo, interleaved
//
// The stream is asked for with "audio_samplerate:" then "audio_start:<rx>;",
// and stopped with "audio_stop:<rx>;".
//
// NOTHING HERE IS CONFIRMED ON A RADIO YET. The layout above is read from the
// TCI documentation, and the stream-type numbers in particular are the sort of
// detail a document gets right and a memory of it does not — so every header is
// logged for the first few seconds of a session, and the numbers the radio
// actually sends will settle it. Same discipline as the Yaesu meters and the
// Flex spot feed: measure on the real thing, then write the constant down.
import (
"encoding/binary"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
)
// TCI stream types. RX audio is the one this file consumes; the others are
// named so a log line says what arrived rather than "type 3".
const (
tciStreamIQ = 0
tciStreamRXAudio = 1
tciStreamTXAudio = 2
tciStreamTXChrono = 3
)
// tciHeaderWords is the header length in uint32 words (7 named + 9 reserved).
const tciHeaderWords = 16
// tciHeaderBytes is the same in bytes.
const tciHeaderBytes = tciHeaderWords * 4
// tciAudioProbeMax bounds the header logging. Enough frames to see the shape
// and the rate; few enough that an evening of listening does not fill the log.
const tciAudioProbeMax = 40
// TCIAudioStatus is what the panel polls while testing the stream.
type TCIAudioStatus struct {
Running bool `json:"running"`
SampleRate int `json:"sample_rate"`
Frames int64 `json:"frames"` // binary frames accepted
Samples int64 `json:"samples"` // audio samples decoded
// PeakDB is the loudest sample of the last second, in dBFS: the one number
// that says "audio is really arriving" rather than "a socket is open".
PeakDB float64 `json:"peak_db"`
LastErr string `json:"last_err,omitempty"`
}
// tciAudio is the receive-side state, kept on the backend so it lives exactly
// as long as the connection does.
type tciAudio struct {
mu sync.Mutex
want bool // the host asked for audio
rx int // which receiver
rate int
frames int64
samples int64
peak float64
peakAt time.Time
probeByType map[int]int
// countByType counts EVERY frame per stream type, capped by nothing.
// The probe above stops logging after forty frames of a type; these keep
// counting, so a transmission that produced no transmit frames at all can
// be reported as a fact rather than inferred from an absence of lines.
countByType map[int]int64
lastErr string
// widthLogged keeps the one-line note about the sample width to once a
// session — it is a fact about the radio, not an event.
widthLogged bool
// txMark is the per-type frame count when transmission began, so the census
// at the end reports the pass rather than the whole session.
txMark map[int]int64
// txFeed supplies the next frame of transmit audio when the radio asks for
// one, or is nil when nothing is being sent. Set under this same lock, and
// read on the reader goroutine — the radio's request and our answer are two
// halves of one exchange and must not straddle a race.
txFeed func(samples int) []byte
txSent int64
txShort int64 // requests the feed could not fill (it had run out)
// What the radio SAID about its stream at connect (audio_stream_sample_type,
// audio_stream_channels). Its own declaration, and it arrives before the
// first frame — the frame arithmetic below stays as the check on it rather
// than as the only source.
declaredType string
declaredChans int
// OnSamples receives decoded MONO samples (the two channels averaged) at
// the negotiated rate. Mono because everything downstream — the QSO
// recorder, the CW decoder — works on one channel, and a receiver's two
// channels carry the same audio.
OnSamples func(rate int, samples []float32)
}
// StartTCIAudio asks the radio to stream receiver rx's audio.
func (t *TCI) StartTCIAudio(rx, rate int) error {
if rate <= 0 {
rate = 48000
}
t.audio.mu.Lock()
t.audio.want = true
t.audio.rx = rx
t.audio.rate = rate
t.audio.frames, t.audio.samples, t.audio.peak = 0, 0, 0
t.audio.lastErr = ""
t.audio.mu.Unlock()
// Sample rate first: the radio applies it to the stream it is about to
// open, and asking afterwards restarts the stream on some firmware.
if err := t.send(fmt.Sprintf("audio_samplerate:%d;", rate)); err != nil {
return err
}
return t.send(fmt.Sprintf("audio_start:%d;", rx))
}
// SetTCIAudioSink installs (or removes) the consumer of the decoded samples.
//
// One sink, not a list: today it is a test recording, tomorrow the QSO
// recorder, and two consumers of a live stream would need a policy about which
// one wins that nothing yet has an opinion about.
func (t *TCI) SetTCIAudioSink(fn func(rate int, samples []float32)) {
t.audio.mu.Lock()
t.audio.OnSamples = fn
t.audio.mu.Unlock()
}
// StopTCIAudio closes the stream.
func (t *TCI) StopTCIAudio() error {
t.audio.mu.Lock()
t.audio.want = false
rx := t.audio.rx
t.audio.mu.Unlock()
return t.send(fmt.Sprintf("audio_stop:%d;", rx))
}
// TCIAudioStatus reports what has arrived.
func (t *TCI) TCIAudioStatus() TCIAudioStatus {
t.audio.mu.Lock()
defer t.audio.mu.Unlock()
st := TCIAudioStatus{
Running: t.audio.want,
SampleRate: t.audio.rate,
Frames: t.audio.frames,
Samples: t.audio.samples,
LastErr: t.audio.lastErr,
}
// A peak older than a second is not a level, it is a memory. Reported as
// silence rather than left standing, so a stream that has stopped arriving
// looks stopped.
if time.Since(t.audio.peakAt) < time.Second && t.audio.peak > 0 {
st.PeakDB = 20 * math.Log10(t.audio.peak)
} else {
st.PeakDB = -99
}
return st
}
// handleBinary decodes one binary WebSocket frame.
//
// Called from the reader goroutine. Anything malformed is counted and dropped:
// a stream frame is not worth breaking the command connection over, and the
// command connection is what keeps the radio usable.
func (t *TCI) handleBinary(data []byte) {
if len(data) < tciHeaderBytes {
t.audioErr(fmt.Sprintf("binary frame of %d bytes is shorter than a header", len(data)))
return
}
le := binary.LittleEndian
receiver := int(le.Uint32(data[0:]))
rate := int(le.Uint32(data[4:]))
format := le.Uint32(data[8:])
codec := le.Uint32(data[12:])
length := int(le.Uint32(data[20:]))
stype := int(le.Uint32(data[24:]))
// Counted PER STREAM TYPE, not overall.
//
// A single counter was spent on the first forty receive-audio frames, which
// arrive twenty-four times a second — so a transmit-chrono or transmit-audio
// frame, the two this needs to see before the voice keyer can be written,
// would never have been logged at all. They only appear once the operator
// keys the radio, long after any global budget is gone.
t.audio.mu.Lock()
if t.audio.probeByType == nil {
t.audio.probeByType = map[int]int{}
}
if t.audio.countByType == nil {
t.audio.countByType = map[int]int64{}
}
t.audio.countByType[stype]++
probe := t.audio.probeByType[stype]
if probe < tciAudioProbeMax {
t.audio.probeByType[stype]++
}
t.audio.mu.Unlock()
if probe < tciAudioProbeMax {
debugLog.Printf("TCI: binary frame — rx=%d rate=%d format=%d codec=%d length=%d type=%d payload=%d bytes",
receiver, rate, format, codec, length, stype, len(data)-tciHeaderBytes)
}
if stype == tciStreamTXChrono {
// The radio asking for the next frame of transmit audio. It is empty —
// the whole message IS the request — and it carries the size it wants in
// the header's length field, so the answer is written from what it says
// rather than from what we assumed.
t.serveChrono(rate, length)
return
}
if stype != tciStreamRXAudio {
// IQ and transmit audio. The latter is ours to send, not to receive:
// counted above, and dropped.
return
}
if codec != 0 {
t.audioErr(fmt.Sprintf("stream is codec=%d, and nothing here decodes a compressed stream", codec))
return
}
// The FORMAT number is decided by measurement, not by the number itself.
//
// A real SunSDR answered format=3, where the code expected 0 — and 0 was a
// guess from reading the documentation, which is exactly the kind of detail
// a memory of a document gets wrong. Rather than swap one magic number for
// another, the sample width is derived from what arrived: the header says
// how many samples the payload holds, so the bytes per sample follow from
// dividing. That is true whatever number the format field carries, on this
// firmware and the next.
payload := data[tciHeaderBytes:]
if len(payload) == 0 || length <= 0 {
return
}
width := len(payload) / length
var n int
switch width {
case 4:
n = len(payload) / 4 // float32
case 2:
n = len(payload) / 2 // 16-bit PCM
default:
t.audioErr(fmt.Sprintf("frame carries %d bytes for %d samples (format=%d) — not a width this reads",
len(payload), length, format))
return
}
if n == 0 {
return
}
// Under the lock like the rest of the counters: the reader is the only
// writer today, but a fact about the radio that is read from another
// goroutine has no business being the one field left unguarded.
t.audio.mu.Lock()
first := !t.audio.widthLogged
t.audio.widthLogged = true
t.audio.mu.Unlock()
if first {
debugLog.Printf("TCI: audio is %d bytes per sample at %d Hz (format field says %d)", width, rate, format)
}
// Stereo interleaved → mono. Both channels of a receiver carry the same
// audio, and everything downstream works on one.
// How many channels are interleaved. The radio says so at connect; two is
// the fallback, which is what every SunSDR seen so far streams.
t.audio.mu.Lock()
chans := t.audio.declaredChans
t.audio.mu.Unlock()
if chans <= 0 {
chans = 2
}
mono := make([]float32, 0, n/chans+1)
var peak float64
sample := func(i int) float32 {
if width == 2 {
// 16-bit PCM, scaled to the same -1…1 the rest of the audio path
// works in, so a change of format cannot change what a level means.
return float32(int16(le.Uint16(payload[i*2:]))) / 32768
}
return math.Float32frombits(le.Uint32(payload[i*4:]))
}
for i := 0; i+chans-1 < n; i += chans {
var sum float32
for c := 0; c < chans; c++ {
sum += sample(i + c)
}
v := sum / float32(chans)
if a := math.Abs(float64(v)); a > peak {
peak = a
}
mono = append(mono, v)
}
t.audio.mu.Lock()
t.audio.frames++
t.audio.samples += int64(len(mono))
if rate > 0 {
t.audio.rate = rate
}
if peak > t.audio.peak || time.Since(t.audio.peakAt) > time.Second {
t.audio.peak = peak
t.audio.peakAt = time.Now()
}
cb := t.audio.OnSamples
t.audio.mu.Unlock()
if cb != nil {
cb(rate, mono)
}
}
// audioErr records a decoding complaint, once, so the panel can show it without
// the log filling with the same line at fifty frames a second.
func (t *TCI) audioErr(msg string) {
t.audio.mu.Lock()
first := t.audio.lastErr != msg
t.audio.lastErr = msg
t.audio.mu.Unlock()
if first {
debugLog.Printf("TCI: audio: %s", msg)
}
}
// resumeAudio re-opens the stream after a reconnect, if the host had asked for
// it. A dropped WebSocket takes the audio with it, and an operator who switched
// recording on does not expect to switch it on again.
func (t *TCI) resumeAudio() {
t.audio.mu.Lock()
want, rx, rate := t.audio.want, t.audio.rx, t.audio.rate
t.audio.mu.Unlock()
if !want {
return
}
if err := t.StartTCIAudio(rx, rate); err != nil {
debugLog.Printf("TCI: re-opening the audio stream failed: %v", err)
}
}
// wsMessageIsBinary keeps the type test in one place — the reader used to
// ignore the message type entirely and split every frame on ';', which would
// have fed audio bytes to the command parser the moment a stream was opened.
func wsMessageIsBinary(mt int) bool { return mt == websocket.BinaryMessage }
// noteTXTransition reports what the stream did across a transmission.
//
// The voice keyer needs two numbers the documentation does not give: the size
// and the cadence of the frames the radio expects while transmitting. They can
// only be read off a real transmission — and the first attempt came back with a
// log that said nothing at all, which is ambiguous: either no transmit frames
// arrived, or they arrived and went unlogged.
//
// So the boundaries are marked and every stream type is counted. A pass that
// produces "type 1: 240, and nothing else" is a RESULT — it says the radio
// sends no chrono unless something more is asked of it — where a log with no
// transmit lines in it was merely a silence.
func (t *TCI) noteTXTransition(on bool) {
t.audio.mu.Lock()
if t.audio.countByType == nil {
t.audio.countByType = map[int]int64{}
}
if on {
// Let the transmit types speak again on every pass: forty frames is a
// budget spent long before the operator gets round to keying.
if t.audio.probeByType != nil {
delete(t.audio.probeByType, tciStreamTXAudio)
delete(t.audio.probeByType, tciStreamTXChrono)
}
t.audio.txMark = map[int]int64{}
for k, v := range t.audio.countByType {
t.audio.txMark[k] = v
}
streaming := t.audio.want
t.audio.mu.Unlock()
debugLog.Printf("TCI: TRANSMIT started — watching for transmit-audio (type %d) and chrono (type %d) frames; receive stream is %s",
tciStreamTXAudio, tciStreamTXChrono, map[bool]string{true: "open", false: "CLOSED (tick the TCI recording option, or the radio has no reason to stream)"}[streaming])
return
}
names := map[int]string{
tciStreamIQ: "IQ",
tciStreamRXAudio: "receive audio",
tciStreamTXAudio: "transmit audio",
tciStreamTXChrono: "transmit chrono",
}
var parts []string
for _, k := range []int{tciStreamIQ, tciStreamRXAudio, tciStreamTXAudio, tciStreamTXChrono} {
if n := t.audio.countByType[k] - t.audio.txMark[k]; n > 0 {
parts = append(parts, fmt.Sprintf("%s (type %d): %d", names[k], k, n))
}
}
t.audio.mu.Unlock()
if len(parts) == 0 {
debugLog.Printf("TCI: TRANSMIT ended — NO binary frames of any type arrived during it")
return
}
debugLog.Printf("TCI: TRANSMIT ended — frames during the pass: %s", strings.Join(parts, ", "))
}
+39
View File
@@ -0,0 +1,39 @@
//go:build windows
package cat
import "fmt"
// TCIAudioController is the receive-audio capability of the TCI backend, kept
// as an interface for the same reason as the Flex and Yaesu ones: the host asks
// the manager, and a station running something else gets a clear "this backend
// does not do that" instead of a nil dereference.
type TCIAudioController interface {
StartTCIAudio(rx, rate int) error
StopTCIAudio() error
TCIAudioStatus() TCIAudioStatus
}
// TCIAudioState returns the stream's state, or (zero, false) when the active
// backend is not a TCI radio.
func (m *Manager) TCIAudioState() (TCIAudioStatus, bool) {
m.mu.RLock()
b := m.backend
m.mu.RUnlock()
if tc, ok := b.(TCIAudioController); ok {
return tc.TCIAudioStatus(), true
}
return TCIAudioStatus{}, false
}
// TCIAudioDo dispatches an audio command onto the CAT goroutine, like every
// other backend-specific control.
func (m *Manager) TCIAudioDo(fn func(TCIAudioController) error) error {
return m.exec(func(b Backend) error {
tc, ok := b.(TCIAudioController)
if !ok {
return fmt.Errorf("active CAT backend is not a TCI radio")
}
return fn(tc)
})
}
+189
View File
@@ -0,0 +1,189 @@
package cat
// Playing a recorded message to the radio over TCI — the voice keyer's path.
//
// The same exchange the tone probe established, with a WAV in place of the
// sine: the radio asks for a frame, we answer with the next slice of the
// message, and it sets the pace. What is added here is the conversion, because
// a recording is whatever the microphone gave it — 16-bit, often mono, often
// not 48 kHz — and the radio wants interleaved float32 at the stream's rate.
//
// The message is converted ONCE, up front, rather than per frame. A voice
// message is a few hundred kilobytes; resampling it inside the callback would
// put arithmetic on the path that has 21 ms to answer, and a late frame is a
// gap in what goes out.
import (
"encoding/binary"
"fmt"
"math"
"time"
)
// tciTXFirstAskTimeout is how long to wait for the radio to ask for the first
// frame before giving up.
//
// It answers within a frame or two when it is going to answer at all, so this
// is generous. When it stays quiet the cause is always the same — the transmit
// audio source is the microphone rather than TCI — and a fifth of a second of
// carrier is a cheap way to find that out.
const tciTXFirstAskTimeout = 200 * time.Millisecond
// PlayTXAudio sends one message and returns when it has all been handed over,
// or when stop is closed.
//
// The PTT is NOT touched here. The voice keyer keys before calling and unkeys
// after, exactly as it does with a sound card, so the transmission is bracketed
// by the same code whichever way the audio travels.
func (t *TCI) PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
t.mu.Lock()
connected := t.conn != nil
t.mu.Unlock()
if !connected {
return fmt.Errorf("not connected to the radio")
}
t.audio.mu.Lock()
outRate := t.audio.rate
t.audio.mu.Unlock()
if outRate <= 0 {
outRate = 48000
}
mono := decodeToMono(pcm, ch, bits)
if len(mono) == 0 {
return fmt.Errorf("the message is empty")
}
if rate > 0 && rate != outRate {
mono = resampleLinear(mono, rate, outRate)
}
// Served from here on. The callback does nothing but copy and interleave,
// which is what keeps it inside the frame interval.
pos := 0
done := make(chan struct{})
var closed bool
t.setTXFeed(func(samples int) []byte {
if samples <= 0 {
samples = 2048
}
pairs := samples / 2
if pos >= len(mono) {
if !closed {
closed = true
close(done)
}
return nil
}
payload := make([]byte, samples*4)
le := binary.LittleEndian
for i := 0; i < pairs; i++ {
var v float32
if pos < len(mono) {
v = mono[pos]
pos++
}
bits := math.Float32bits(v)
le.PutUint32(payload[(i*2)*4:], bits) // left
le.PutUint32(payload[(i*2+1)*4:], bits) // right
}
return payload
})
defer t.setTXFeed(nil)
// Nothing asked for in a fifth of a second means nothing is listening.
// Reported plainly: the message would otherwise go out as silence, and a
// voice keyer that transmits silence is worse than one that refuses.
deadline := time.Now().Add(tciTXFirstAskTimeout)
for time.Now().Before(deadline) {
t.audio.mu.Lock()
asked := t.audio.txSent > 0
t.audio.mu.Unlock()
if asked {
break
}
select {
case <-stop:
return nil
case <-time.After(10 * time.Millisecond):
}
}
t.audio.mu.Lock()
asked := t.audio.txSent
t.audio.mu.Unlock()
if asked == 0 {
return fmt.Errorf("the radio did not ask for any audio — set its transmit audio source to TCI instead of the microphone")
}
// The radio drains the message at real time, so this waits for the feed to
// run out. The cap is the message's own length with a second to spare: a
// radio that stops asking mid-message must not hold the transmitter up.
limit := time.Duration(float64(len(mono))/float64(outRate)*float64(time.Second)) + time.Second
select {
case <-done:
case <-stop:
case <-time.After(limit):
debugLog.Printf("TCI: the radio stopped asking for audio before the message ended")
}
return nil
}
// decodeToMono turns interleaved PCM into one channel of -1…1 floats.
func decodeToMono(pcm []byte, ch, bits int) []float32 {
if ch <= 0 {
ch = 1
}
switch bits {
case 16:
frame := ch * 2
out := make([]float32, 0, len(pcm)/frame+1)
for i := 0; i+frame <= len(pcm); i += frame {
var sum float32
for c := 0; c < ch; c++ {
v := int16(uint16(pcm[i+c*2]) | uint16(pcm[i+c*2+1])<<8)
sum += float32(v) / 32768
}
out = append(out, sum/float32(ch))
}
return out
case 8:
// Unsigned, centred on 128 — the one format where silence is not zero.
out := make([]float32, 0, len(pcm)/ch+1)
for i := 0; i+ch <= len(pcm); i += ch {
var sum float32
for c := 0; c < ch; c++ {
sum += (float32(pcm[i+c]) - 128) / 128
}
out = append(out, sum/float32(ch))
}
return out
}
return nil
}
// resampleLinear moves samples from one rate to another.
//
// Linear interpolation, which is crude and entirely adequate here: a voice
// recording at 16 kHz going to 48 kHz is being INTERPOLATED, and interpolation
// invents no frequencies to alias. Going the other way would want a filter
// first, but a message recorded above the radio's stream rate is not a case
// that arises — the recorder works at 16 kHz and radios stream at 48.
func resampleLinear(in []float32, from, to int) []float32 {
if from <= 0 || to <= 0 || from == to || len(in) == 0 {
return in
}
ratio := float64(from) / float64(to)
n := int(float64(len(in)) / ratio)
out := make([]float32, n)
for i := 0; i < n; i++ {
src := float64(i) * ratio
j := int(src)
frac := float32(src - float64(j))
if j+1 < len(in) {
out[i] = in[j]*(1-frac) + in[j+1]*frac
} else {
out[i] = in[len(in)-1]
}
}
return out
}
+267
View File
@@ -0,0 +1,267 @@
package cat
// Sending audio TO the radio over TCI.
//
// Three transmissions on a real SunSDR settled how this works, and none of it
// was guessable from the documentation:
//
// 1. The radio asks for audio only when the transmission is the CLIENT'S. With
// the operator keying the microphone it sent 282 receive frames and nothing
// else, over six seconds.
// 2. It asks only when its TRANSMIT AUDIO SOURCE is TCI rather than the
// microphone. This first read as "digital modes only" — SSB produced
// nothing four times over, DIGU answered at once — but the mode was a
// coincidence: ExpertSDR3 keeps that source setting per mode, and it was on
// the microphone in SSB. Which is why nothing is refused on the strength of
// the mode: the radio is asked, and it answers by asking or by staying
// quiet.
// 3. The chrono is a REQUEST, not a clock to follow. It carries no payload —
// the message itself is the ask — and it names the size it wants in the
// header's length field: 2048 samples, two channels interleaved, arriving
// 47 times a second. Which is 1024 sample-pairs at 48 kHz, exactly real
// time, measured rather than assumed.
//
// So audio is sent in ANSWER to chrono, never on a timer of our own. A timer
// was the first attempt and the radio ignored every frame of it: 234 sent, none
// used. Answering the request is what makes the difference, and it also means
// the radio sets the pace — no drift, no buffer to tune.
//
// What remains here is the probe: a tone, on demand, to prove the path end to
// end on real hardware. The voice keyer will use the same feed mechanism with
// WAV samples in place of the sine.
import (
"encoding/binary"
"fmt"
"math"
"time"
"github.com/gorilla/websocket"
)
// tciTXProbeMaxSeconds caps the pass. Long enough to read a power meter, short
// enough that a carrier left running by a defect is a mistake and not an
// incident.
const tciTXProbeMaxSeconds = 10
// sendBinaryFrame writes one TCI binary frame: the 16-word header the radio's
// own frames carry, then the payload.
func (t *TCI) sendBinaryFrame(stype, rx, rate, length int, payload []byte) error {
t.mu.Lock()
c := t.conn
t.mu.Unlock()
if c == nil {
return fmt.Errorf("tci: not connected")
}
buf := make([]byte, tciHeaderBytes+len(payload))
le := binary.LittleEndian
le.PutUint32(buf[0:], uint32(rx))
le.PutUint32(buf[4:], uint32(rate))
// format=3, codec=0: mirrored from what this radio SENDS. The field is
// documented as an enumeration whose numbering did not survive contact with
// the firmware — the receive stream answers 3 for four-byte floats — so the
// only defensible choice is to speak back exactly what was spoken to us.
le.PutUint32(buf[8:], 3)
le.PutUint32(buf[12:], 0)
le.PutUint32(buf[16:], 0) // crc — the radio sends 0 and does not check ours
le.PutUint32(buf[20:], uint32(length))
le.PutUint32(buf[24:], uint32(stype))
copy(buf[tciHeaderBytes:], payload)
t.wmu.Lock()
defer t.wmu.Unlock()
_ = c.SetWriteDeadline(time.Now().Add(3 * time.Second))
return c.WriteMessage(websocket.BinaryMessage, buf)
}
// serveChrono answers one request for transmit audio.
//
// Called from the reader goroutine, so it does the least it can: take the
// frame from whatever is feeding, and write it. A feed that has run out returns
// nil and the request is counted rather than answered with silence — silence
// would be indistinguishable from a working stream on a meter.
func (t *TCI) serveChrono(rate, samples int) {
t.audio.mu.Lock()
feed := t.audio.txFeed
t.audio.mu.Unlock()
if feed == nil {
return
}
if samples <= 0 {
samples = 2048
}
payload := feed(samples)
if payload == nil {
t.audio.mu.Lock()
t.audio.txShort++
t.audio.mu.Unlock()
return
}
if rate <= 0 {
rate = 48000
}
if err := t.sendBinaryFrame(tciStreamTXAudio, 0, rate, samples, payload); err != nil {
debugLog.Printf("TCI: could not send transmit audio: %v", err)
return
}
t.audio.mu.Lock()
t.audio.txSent++
t.audio.mu.Unlock()
}
// setTXFeed installs (or clears) the source of transmit audio.
func (t *TCI) setTXFeed(fn func(samples int) []byte) {
t.audio.mu.Lock()
t.audio.txFeed = fn
t.audio.txSent, t.audio.txShort = 0, 0
t.audio.mu.Unlock()
}
// ProbeTXStream keys the radio, answers its chrono requests with a tone for the
// given number of seconds, unkeys, and reports what happened.
//
// INTO A DUMMY LOAD. Confirmed on a SunSDR: 80 W out of a 1 kHz tone at 70% of
// full scale into 80% drive.
//
// If the radio's transmit audio source is the microphone rather than TCI it
// will not ask for anything, and this stops within a fifth of a second and says
// which setting to change.
func (t *TCI) ProbeTXStream(seconds int, toneHz float64) error {
if seconds <= 0 {
seconds = 5
}
if seconds > tciTXProbeMaxSeconds {
seconds = tciTXProbeMaxSeconds
}
if toneHz <= 0 {
toneHz = 1000
}
t.mu.Lock()
allowed, known, connected := t.txAllowed, t.txAllowedKnown, t.conn != nil
mode := t.mode
drive := t.drive
t.mu.Unlock()
if !connected {
return fmt.Errorf("not connected to the radio")
}
if known && !allowed {
return fmt.Errorf("the radio refuses transmitting (tx_enable is false)")
}
if !tciDigitalMode(mode) {
// A NOTE, not a refusal.
//
// The first experiments said "digital modes only": SSB produced nothing
// four times over, DIGU answered at once. That was a real observation
// and the wrong rule. ExpertSDR3 has a TRANSMIT AUDIO SOURCE — the
// microphone or TCI — and it was simply set to the microphone; the mode
// had nothing to do with it. Refusing SSB would have blocked the one
// thing a voice keyer exists for.
debugLog.Printf("TCI: TX PROBE — mode is %s, not a digital mode. That is fine IF ExpertSDR3's transmit audio source is set to TCI rather than the microphone; if it is not, the radio will not ask for audio and this stops straight away", mode)
}
t.audio.mu.Lock()
rate := t.audio.rate
t.audio.mu.Unlock()
if rate <= 0 {
rate = 48000
}
// The tone, generated on demand: the radio asks for a size and gets exactly
// that, at whatever pace it asks. Phase is carried across the calls, since a
// sine restarted every frame is a click 47 times a second.
phase := 0.0
step := 2 * math.Pi * toneHz / float64(rate)
// Near full scale.
//
// A quarter was the first choice, out of caution, and the first real test
// showed exactly what that produces: a clean signal on the panadapter and a
// wattmeter that never moves. In a digital mode the radio expects a line
// level it can drive to full output — the POWER is set by its own drive
// control, not by how loud we send — so sending quietly just wastes the
// range. Short of 1.0 to leave room for the sine's peaks.
const amp = 0.7
const chans = 2
le := binary.LittleEndian
t.setTXFeed(func(samples int) []byte {
payload := make([]byte, samples*4)
for s := 0; s+chans-1 < samples; s += chans {
v := float32(math.Sin(phase) * amp)
phase += step
if phase > 2*math.Pi {
phase -= 2 * math.Pi
}
bits := math.Float32bits(v)
le.PutUint32(payload[s*4:], bits) // left
le.PutUint32(payload[(s+1)*4:], bits) // right
}
return payload
})
defer t.setTXFeed(nil)
// The drive is in the line because it is half of "how much power came out".
// A tone at full scale into a drive of 15 is still 15% of the radio.
debugLog.Printf("TCI: TX PROBE starting — %d s of a %.0f Hz tone at %.0f%% of full scale, answered to the radio's own requests, mode %s, radio drive %d%%, INTO A DUMMY LOAD",
seconds, toneHz, amp*100, mode, drive)
if err := t.SetPTT(true); err != nil {
return fmt.Errorf("could not key the radio: %w", err)
}
// Every path out unkeys, including the panic that has not happened yet. A
// transmitter left keyed by a defect is the one fault here that would reach
// somebody else's band.
defer func() {
if err := t.SetPTT(false); err != nil {
debugLog.Printf("TCI: TX PROBE — UNKEY FAILED (%v) — stop the transmission at the radio", err)
}
}()
// Wait for the radio to ask, and give up quickly if it does not.
//
// The radio declares what it wants by requesting audio — 47 times a second
// when it wants any at all. So there is no need to decide in advance whether
// this mode or that setting will work: key, listen for one request, and if
// none comes in a fifth of a second, stop. That is a quarter of a second of
// carrier instead of five, and an answer that names the setting to change.
deadline := time.Now().Add(200 * time.Millisecond)
for time.Now().Before(deadline) {
t.audio.mu.Lock()
asked := t.audio.txSent > 0
t.audio.mu.Unlock()
if asked {
break
}
time.Sleep(10 * time.Millisecond)
}
t.audio.mu.Lock()
started := t.audio.txSent
t.audio.mu.Unlock()
if started == 0 {
debugLog.Printf("TCI: TX PROBE — the radio never asked for audio; set ExpertSDR3's transmit audio source to TCI (it is on the microphone)")
return fmt.Errorf("the radio did not ask for any audio — set ExpertSDR3's transmit audio source to TCI instead of the microphone, then try again")
}
time.Sleep(time.Duration(seconds)*time.Second - 200*time.Millisecond)
t.audio.mu.Lock()
sent, short := t.audio.txSent, t.audio.txShort
chrono := t.audio.countByType[tciStreamTXChrono] - t.audio.txMark[tciStreamTXChrono]
t.audio.mu.Unlock()
debugLog.Printf("TCI: TX PROBE finished — the radio asked %d times, %d frames sent, %d requests unanswered",
chrono, sent, short)
if sent == 0 {
debugLog.Printf("TCI: TX PROBE — the radio never asked for audio; in a digital mode it should, so check that ExpertSDR3 takes its transmit audio from TCI")
}
return nil
}
// tciDigitalMode says whether the radio's current mode is one where network
// audio reaches the modulator. Measured on a SunSDR: DIGU asks for audio, SSB
// never does.
func tciDigitalMode(mode string) bool {
switch mode {
case "digu", "digl", "DIGU", "DIGL", "FT8", "ft8", "FT4", "ft4", "DATA", "data", "RTTY", "rtty":
return true
}
return false
}