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:
@@ -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()
|
||||
|
||||
@@ -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)")
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
+51
-2
@@ -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)
|
||||
@@ -56,7 +66,11 @@ type TCI struct {
|
||||
// txAllowedKnown keeps an OLDER ExpertSDR, or a TCI-compatible program that
|
||||
// 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
|
||||
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" {
|
||||
|
||||
@@ -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, ", "))
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user