From bdc72aa15ef739267b93edb60e79914091bc682e Mon Sep 17 00:00:00 2001 From: Andy Taylor Date: Sat, 31 Oct 2026 15:02:11 +0000 Subject: [PATCH 1/2] Upgrade to AMBEd 1.5.0: move to a config file and improved configuration Evens out audio across modes and stations, and moves ambed's settings into a config file so levels can be tuned without a rebuild or restart. Audio chain: - Every path now runs decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode, including M17 <-> P25. - One decode and one encode gain per mode replace the per-path gains. - Signal processing is rebuilt for each stream, so a stream starts clean and doesn't inherit the previous station's gain. - The bandpass filter clamps its output to the short range. AGC: - Levels the speaker, not the syllable. It works like the AGC on an HF receiver: fast down, hold through gaps, then up, faster the further a station is below the target. - Follows speech peaks, moving the gain between syllables and leaving the shape of the speech alone for the vocoders. - Pauses and noise below AGC_GATE leave the gain where it is. - The gain ramps across each frame, so a change can't click. - A peak limiter leaves room for the highest encode gain, so a boost can't clip an encoder. ambed.ini: - The command line is now ambed [ambed.ini], and main.h holds the defaults. The old ambed form is refused, so it can't bind to the wrong address. - Holds the listen IP and port, DSCP marking, stream timeout, logging, gains, AGC and filter settings. USE_AGC and USE_BANDPASSFILTER are now runtime options. - Checked every 3 minutes. Most changes apply from the next stream, DSCP changes at once, and the listen IP and port need a restart. xlxd's TRANSCODER_PORT must match LISTEN_PORT. - A setting left out uses its default. A bad value is logged and the value in use stays. - make install copies the sample only if there is no ambed.ini, and the run script and systemd service pass its path. Tuning log: when a stream closes, ambed logs voice level, peak and clipping after decode, after the decode gain, after the AGC and after each encode gain, plus the speech peaks, AGC gain and limiter activity. With AGC_CLAMPING=0 the audio is untouched and the levels are still logged. TUNING_LOG turns the log on or off. The readme is now README.md, rewritten to cover the audio chain, every setting, how to tune and an example systemd unit. --- ambed/README.md | 245 ++++++++++++++++++++++++++++ ambed/ambed.ini | 88 ++++++++++ ambed/cagc.cpp | 157 +++++++++++++----- ambed/cagc.h | 48 ++++-- ambed/cconfig.cpp | 325 +++++++++++++++++++++++++++++++++++++ ambed/cconfig.h | 95 +++++++++++ ambed/ccontroller.cpp | 7 +- ambed/cfirfilter.cpp | 6 +- ambed/cfixedgain.cpp | 2 +- ambed/cftdidevicedescr.cpp | 64 ++++---- ambed/csignalprocessor.cpp | 224 +++++++++++++++++++++---- ambed/csignalprocessor.h | 58 ++++++- ambed/cstream.cpp | 221 +++++++++---------------- ambed/cstream.h | 16 +- ambed/cudpsocket.cpp | 51 +++--- ambed/cudpsocket.h | 7 - ambed/cvocodecchannel.cpp | 117 +++++++------ ambed/cvocodecchannel.h | 14 +- ambed/main.cpp | 27 ++- ambed/main.h | 76 +++++---- ambed/makefile | 1 + ambed/readme | 197 ---------------------- ambed/run | 2 +- scripts/ambed.service | 2 +- 24 files changed, 1437 insertions(+), 613 deletions(-) create mode 100644 ambed/README.md create mode 100644 ambed/ambed.ini create mode 100644 ambed/cconfig.cpp create mode 100644 ambed/cconfig.h delete mode 100644 ambed/readme diff --git a/ambed/README.md b/ambed/README.md new file mode 100644 index 0000000..5caca40 --- /dev/null +++ b/ambed/README.md @@ -0,0 +1,245 @@ +# AMBEd + +AMBEd is the transcoder daemon for XLXd. It converts voice between the digital +modes on a reflector, using DVSI hardware for AMBE and software vocoders for +Codec2 and IMBE. It also evens out levels, so stations sound alike whichever +mode they use. + +Version 1.5.0 + +## Codecs + +| Codec | Modes | Vocoder | +|---|---|---| +| AMBE+ | D-Star | DVSI hardware | +| AMBE2+ | DMR, YSF, NXDN | DVSI hardware | +| Codec2 3200 bps | M17 | Software | +| IMBE | P25 | Software | + +DMR, YSF and NXDN share a codec, so voice between them isn't transcoded and +AMBEd sees all three as DMR. + +## Transcoding paths + +| From | To | How | +|---|---|---| +| D-Star | DMR/YSF/NXDN | Hardware decode, hardware encode | +| DMR/YSF/NXDN | D-Star | Hardware decode, hardware encode | +| D-Star, DMR/YSF/NXDN | M17, P25 | Hardware decode, software encode | +| M17 | D-Star, DMR/YSF/NXDN | Software decode, hardware encode | +| M17 | P25 | Software decode, software encode | +| P25 | D-Star, DMR/YSF/NXDN | Software decode, hardware encode | +| P25 | M17 | Software decode, software encode | + +An M17 or P25 input uses 2 hardware channels, one for each AMBE encoder. + +## Hardware + +- DF2ET's [AMBE3003USB](https://github.com/phl0/AMBE3003USB) +- LX3JL's [USB-3006](https://github.com/lx3jl/usb-3006) +- DVSI USB-3000, USB-3003 and USB-3012 +- NWDR ThumbDV and ThumbDV-3 +- DVMEGA AMBE3000 and AMBE3003 + +| Device | Hardware channels | Transcoding channels | Software vocoders (IMBE and Codec2) | +|---|---|---|---| +| 3000 (pair) | 2 | 2 | 1 each | +| 3003 (single) | 3 | 2 | 1 each | +| 3003 (pair) | 6 | 6 | 3 each | +| 3003 + 3000 (pair) | 4 | 4 | 2 each | +| 3006 | 6 | 6 | 3 each | +| 3012 | 12 | 12 | 6 each | + +- USB-3000 devices must be used in pairs, or paired with a USB-3003. +- Several devices can be used at once. +- Avoid USB hubs, they can be unreliable. +- The maximum number of concurrent streams is worked out from the hardware. + +## Installation + +1. Install the FTDI D2XX drivers from the FTDI website and follow their + instructions. Tested on 1.4.6. + +2. Install the build tools: + + ```bash + apt-get install build-essential + ``` + +3. Build and install: + + ```bash + git clone https://github.com/LX3JL/xlxd.git + cd xlxd/ambed + make clean + make + make install + ``` + + This installs to `/ambed`. `ambed.ini` is only copied if there isn't one + already, so your tuning is kept. + +Always run `make clean` first after updating. The makefile doesn't track +header changes, so a plain `make` can link old and new code together. + +## Running + +``` +ambed [ambed.ini] +``` + +Everything is set in `ambed.ini`. Set `LISTEN_IP` first: `127.0.0.1` if xlxd is on +the same machine, otherwise the machine's own address. Without the file AMBEd +uses the defaults in `main.h` and listens on `127.0.0.1`. + +AMBEd must run as root because of the FTDI driver, and the `ftdi_sio` and +`usbserial` kernel modules must be unloaded. Plug in at least one device first. + +To run it as a service, copy `../scripts/ambed.service` to +`/etc/systemd/system/`: + +```ini +[Unit] +Description=AMBE Transcoder Daemon +After=network.target + +[Service] +Type=simple +User=root +Group=root +ExecStartPre=-/sbin/rmmod ftdi_sio +ExecStartPre=-/sbin/rmmod usb_serial +ExecStart=/ambed/ambed /ambed/ambed.ini +Restart=on-abnormal + +[Install] +WantedBy=multi-user.target +``` + +Then enable and start it: + +```bash +systemctl daemon-reload +systemctl enable --now ambed +``` + +Or start it by hand with `/ambed/run`. + +At startup AMBEd finds and configures every device, then reports: + +``` +Starting AMBEd 1.5.0 +Codec interfaces initialized successfully : 6 channels available +Software vocoders : 3 IMBE (P25), 3 Codec2 (M17) +Max concurrent streams: 3 (from 6 vocoder channels) +AMBEd started and listening on 127.0.0.1:10100 +Voice packets marked as DSCP 46 +``` + +## Audio processing + +Every path runs through the same chain: + +``` +decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode +``` + +- **`_TO_PCM`** corrects what each mode's decoder does to the level, so + every mode reaches the AGC at about the same level. +- **Bandpass filter** keeps 300-3400 Hz. +- **AGC** corrects what each station does to the level: mic gain, radio and + voice. +- **`PCM_TO_`** sets the level for each encoder. + +### AGC + +The AGC works like the one on an HF receiver: fast down, hold through gaps, then +up, faster the further a station is below the target. + +- It follows the speech peaks, the loud parts of words, so it levels the speaker + and leaves the shape of the speech alone for the vocoders. +- Pauses and noise below `AGC_GATE` leave the gain where it is. +- Each stream starts at 0 dB, so very short transmissions aren't fully levelled. +- A peak limiter leaves room for the highest `PCM_TO_`, so a boost can't + clip an encoder. + +## Tuning + +`ambed.ini` overrides the defaults in `main.h` without a rebuild. AMBEd checks it +every 3 minutes. Most changes apply from the next stream, so a transmission +already running keeps its levels, and DSCP changes apply at once. +`LISTEN_IP` and `LISTEN_PORT` need a restart. A setting left out uses its default. +A bad value is logged and ignored, and the value in use stays. + +| Setting | Default | Meaning | +|---|---|---| +| `LISTEN_IP` | 127.0.0.1 | IP to bind to | +| `LISTEN_PORT` | 10100 | UDP port, xlxd's `TRANSCODER_PORT` must match | +| `DSCP_MARKING_ENABLE` | 1 | Mark voice packets for QoS | +| `DSCP_VALUE` | 46 | DSCP value, 0-63, 46 is EF | +| `STREAM_ACTIVITY_TIMEOUT` | 3 s | Close a stream after this long with no packets | +| `TUNING_LOG` | 1 | Log levels when a stream closes | +| `DSTAR_TO_PCM` | -10 dB | D-Star decode gain | +| `DMR_TO_PCM` | -1.5 dB | DMR, YSF and NXDN decode gain | +| `M17_TO_PCM` | -10.75 dB | M17 decode gain | +| `P25_TO_PCM` | -3.75 dB | P25 decode gain | +| `PCM_TO_DSTAR` | +11.5 dB | D-Star encode gain | +| `PCM_TO_DMR` | 0 dB | DMR, YSF and NXDN encode gain | +| `PCM_TO_M17` | +5.25 dB | M17 encode gain | +| `PCM_TO_P25` | +0.75 dB | P25 encode gain | +| `USE_AGC` | 1 | AGC on or off | +| `AGC_TARGET` | -41 dBFS | Speech peak level to aim for | +| `AGC_CLAMPING` | 9 dB | Most the gain can move either way, 0 leaves the audio alone | +| `AGC_ATTACK` | 150 ms | How fast the gain comes down | +| `AGC_HANG` | 1000 ms | How long the gain holds before it can rise | +| `AGC_RECOVERY` | 2 | How fast the gain rises, dB/s for each dB below the target | +| `AGC_RECOVERY_MIN` | 3 dB/s | Slowest rise | +| `AGC_RECOVERY_MAX` | 20 dB/s | Fastest rise | +| `AGC_GATE` | -60 dBFS | Frames quieter than this don't move the gain | +| `USE_BANDPASSFILTER` | 1 | Bandpass filter on or off | + +### Tuning log + +When a stream closes, AMBEd logs the voice level at each stage. Pauses aren't +counted, and a level is the mean absolute sample value. Set `TUNING_LOG=0` to +turn this off. + +``` +Tuning: stream 1 XLX672 M17 input, 440 voice frames of 540 +Tuning: decoded level -30.5 dBFS peak -8.9 dBFS clipped 0.00% +Tuning: M17_TO_PCM -10.75 level -45.6 dBFS peak -19.9 dBFS clipped 0.00% +Tuning: AGC target -41.0 dBFS speech peaks -43.6 dBFS gain average -3.7 dB, -4.5 to +0.4 dB at limit 0.0% high 0.0% low limiter 0.00% +Tuning: after AGC level -49.3 dBFS peak -23.7 dBFS clipped 0.00% +Tuning: PCM_TO_DSTAR +11.50 level -37.8 dBFS peak -12.2 dBFS clipped 0.00% +Tuning: PCM_TO_DMR +0.00 level -49.3 dBFS peak -23.7 dBFS clipped 0.00% +Tuning: PCM_TO_P25 +0.75 level -48.5 dBFS peak -22.9 dBFS clipped 0.00% +``` + +The callsign shown is the reflector's, as AMBEd isn't told who is talking. + +### How to tune + +1. Look at several stations on each mode, not just your own radio. +2. Set each `_TO_PCM` so typical stations on that mode average near 0 dB + of AGC gain. +3. If most modes sit high or low, move `AGC_TARGET`. +4. A station at one limit for most of a stream is too far off for the AGC to + correct. +5. Use `PCM_TO_` to match how each mode sounds on air, and back one off if + it shows clipping. + +To see levels without changing the audio, set `AGC_CLAMPING=0`. Speech peaks are +still logged. + +## Build-time options + +These are in `main.h`: + +| Setting | Default | Meaning | +|---|---|---| +| `CONFIG_RELOAD_PERIOD` | 180 s | How often `ambed.ini` is checked | + +## License + +Created by Jean-Luc Deltombe (LX3JL). AMBEd is part of xlxd, free software under +the GNU General Public License v3 or later. diff --git a/ambed/ambed.ini b/ambed/ambed.ini new file mode 100644 index 0000000..f2a98ea --- /dev/null +++ b/ambed/ambed.ini @@ -0,0 +1,88 @@ +# ambed.ini - AMBEd settings +# +# Usage: ambed /ambed/ambed.ini +# Reloaded: every 3 minutes, most settings apply from the next stream +# Left out: uses the default in main.h +# Bad value: logged and ignored +# +# Audio path: +# decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode +# +# DMR covers YSF and NXDN too, they share a codec. + +[Network] +# IP to bind to, 127.0.0.1 if xlxd is on this machine. Needs a restart. +LISTEN_IP=127.0.0.1 + +# UDP port, 1 to 65000. xlxd's TRANSCODER_PORT must match. Needs a restart. +LISTEN_PORT=10100 + +# Mark voice packets for QoS: 1 or 0 +DSCP_MARKING_ENABLE=1 + +# DSCP value, 0 to 63. 46 is EF, highest priority voice +DSCP_VALUE=46 + +# Close a stream after this long with no packets, seconds, 1 to 60 +STREAM_ACTIVITY_TIMEOUT=3 + +[Logging] +# Log levels when a stream closes: 1 or 0 +TUNING_LOG=1 + +[Gain] +# Decode gains, in dB, -40 to +40. Bring every mode to the same level. +DSTAR_TO_PCM=-10 +DMR_TO_PCM=-1.5 +M17_TO_PCM=-10.75 +P25_TO_PCM=-3.75 + +# Encode gains, in dB, -40 to +40. Set each mode's level on air. +PCM_TO_DSTAR=11.5 +PCM_TO_DMR=0 +PCM_TO_M17=5.25 +PCM_TO_P25=0.75 + +[AGC] +# ------------------------------------------------------------------------ +# Automatic gain control +# +# Evens out stations: a quiet radio comes up, a loud one comes down. +# It levels the speaker, not the syllable, so it should drift, never pump. +# Works like an HF receiver: fast down, hold through gaps, then up. +# Pauses and noise leave the gain alone. +# ------------------------------------------------------------------------ + +# AGC on or off: 1 or 0 +USE_AGC=1 + +# Speech peak level to aim for, dBFS, -60 to -3 +AGC_TARGET=-41 + +# Most the gain can move either way, dB, 0 to 20 +# 0 leaves the audio alone and still logs speech peaks +AGC_CLAMPING=9 + +# How fast the gain comes down, ms, 10 to 2000 +AGC_ATTACK=150 + +# How long the gain holds before it can rise, ms, 0 to 10000 +AGC_HANG=1000 + +# How fast the gain rises, dB/s per dB below target, 0.1 to 10 +# Far off comes up quickly, close eases in +AGC_RECOVERY=2 + +# Slowest rise, dB/s, 0.5 to 50 +AGC_RECOVERY_MIN=3 + +# Fastest rise, dB/s, 0.5 to 100 +AGC_RECOVERY_MAX=20 + +# Frames quieter than this don't move the gain, dBFS, -80 to -20 +# Keep it above background noise +AGC_GATE=-60 + +[Filter] +# 300-3400 Hz bandpass on or off: 1 or 0 +USE_BANDPASSFILTER=1 diff --git a/ambed/cagc.cpp b/ambed/cagc.cpp index a673f4e..4962326 100644 --- a/ambed/cagc.cpp +++ b/ambed/cagc.cpp @@ -21,34 +21,60 @@ // You should have received a copy of the GNU General Public License // along with Foobar. If not, see . // ---------------------------------------------------------------------------- -// Geoffrey Merck F4FXL / KC3FRA AGC code borrowed from Liquid DSP -// Only took the parts we need qnd recoeded it to be close the XLX coding style -// https://github.com/jgaeddert/liquid-dsp/blob/master/src/agc/src/agc.c +// AGC with hang, replaces the sample by sample loop by Geoffrey Merck +// F4FXL / KC3FRA that was inspired by Liquid DSP +// +// Works like the AGC on an HF receiver: fast down, hold through gaps, then up. +// The further a station is below the target the faster the gain rises, easing +// off as it gets close. +// It follows the peaks of the speech over tens of ms, so the gain moves between +// syllables and the shape of the speech and pitch is left alone for the +// vocoders. Silence doesn't count, so pauses leave the gain where it is. #include #include "cagc.h" #include "main.h" +// Speech peak envelope, falling share per 20 ms frame: about 50 ms +#define AGC_PEAK_DECAY 0.33f +// Voice frames at the start of a stream before the gain may rise +#define AGC_START_HANG 5 +// Recent peak fall per 20 ms frame: 12 dB/s +#define AGC_RECENT_DECAY 0.973f +// Peaks within this of the target still hold the gain, in dB, so ordinary +// softer words don't lift it +#define AGC_HANG_MARGIN 1.5f +// A station this far below the target doesn't wait for the hang, in dB +#define AGC_NO_HANG_ERROR 6.0f +// Limiter recovery: 6 dB in 100 ms at 8 kHz +#define AGC_LIMITER_RECOVERY 1.000867f + //////////////////////////////////////////////////////////////////////////////////////// // constructor -CAGC::CAGC(float initialLeveldB) +CAGC::CAGC(float targetdB, float clampingdB, float attackMs, float hangMs, + float recovery, float recoveryMin, float recoveryMax, float gatedB, float limitdB) { - // set internal gain appropriately - m_Gain = pow(10.0f, initialLeveldB/20.0f); - //+- 10dB Margin, TODO Move margin to constant - m_GainMax = pow(10.0f, (initialLeveldB + AGC_CLAMPING)/20.0f); - m_GainMin = pow(10.0f, (initialLeveldB - AGC_CLAMPING)/20.0f); - - m_EnergyPrime = 1.0f; - - // We do not target full scale to avoid stauration - m_targetEnergy = 32767.0f * pow(10.0f, (initialLeveldB - 25.0)/20.0f);//25 dB below saturation as stated in docs - //we also substract our target gain - - //this is the time constant of our AGC... - m_Bandwidth = 1e-2f;//TODO : Move to parameter ? - m_Alpha = m_Bandwidth; + m_Enabled = (clampingdB > 0.0f); + m_TargetdB = targetdB; + m_ClampingdB = clampingdB; + m_AttackCoef = 1.0f - exp(-20.0f / attackMs); + m_HangFrames = (int)(hangMs / 20.0f); + m_Recovery = recovery * 0.02f; + m_RecoveryMin = recoveryMin * 0.02f; + m_RecoveryMax = recoveryMax * 0.02f; + m_GateLevel = 32768.0f * pow(10.0f, gatedB/20.0f); + m_LimitLevel = 32768.0f * pow(10.0f, limitdB/20.0f); + + m_SpeechPeak = 0.0f; + m_RecentPeak = 0.0f; + m_bVoice = false; + m_HangLeft = AGC_START_HANG; + + m_GaindB = 0.0f; + m_Gain = 1.0f; + m_Limiter = 1.0f; + m_LimitedSamples = 0; } //////////////////////////////////////////////////////////////////////////////////////// @@ -56,36 +82,92 @@ CAGC::CAGC(float initialLeveldB) float CAGC::GetGain() { - return 20.0f*log10(m_Gain); + return m_GaindB; +} + +float CAGC::GetSpeechPeak() +{ + return (m_SpeechPeak > 0.0f) ? 20.0f * log10(m_SpeechPeak / 32768.0f) : -96.0f; } //////////////////////////////////////////////////////////////////////////////////////// // process -inline void CAGC::ProcessSampleBlock(uint8* voice, int length) +void CAGC::ProcessSampleBlock(uint8* voice, int length) { + int samples = length / 2; + if(samples == 0) + { + return; + } + + float sum = 0.0f; for(int i = 0; i < length; i += 2) { - float input = (float)(short)MAKEWORD(voice[i+1], voice[i]); - //apply AGC - // apply gain to input sample - float output = input * m_Gain; + sum += fabs((float)(short)MAKEWORD(voice[i+1], voice[i])); + } + float level = sum / samples; + + // follow the speech peaks, measured even with the gain off for tuning + m_bVoice = (level >= m_GateLevel); + if(m_bVoice) + { + m_SpeechPeak = MAX(level, m_SpeechPeak + (level - m_SpeechPeak) * AGC_PEAK_DECAY); + m_RecentPeak = MAX(m_SpeechPeak, m_RecentPeak * AGC_RECENT_DECAY); + } - // compute output signal energy, scaled to 0 to 1 - float instantEnergy = abs(output) / m_targetEnergy; + if(!m_Enabled) + { + return; + } - // smooth energy estimate using single-pole low-pass filter - m_EnergyPrime = (1.0f - m_Alpha) * m_EnergyPrime + m_Alpha * instantEnergy; + // only voice moves the gain + if(m_bVoice) + { + float wanted = m_TargetdB - 20.0f * log10(m_RecentPeak / 32768.0f); + wanted = MAX(-m_ClampingdB, MIN(m_ClampingdB, wanted)); + float error = wanted - m_GaindB; - // update gain according to output energy - if (m_EnergyPrime > 1e-6f) - m_Gain *= exp( -0.5f * m_Alpha * log(m_EnergyPrime) ); + if(error < 0.0f) + { + m_GaindB += error * m_AttackCoef; + m_HangLeft = MAX(m_HangLeft, m_HangFrames); + } + else if(error < AGC_HANG_MARGIN) + { + m_HangLeft = m_HangFrames; + } + else if(m_HangLeft > 0 && error < AGC_NO_HANG_ERROR) + { + m_HangLeft--; + } + else + { + // quick when far off, easing in as it gets close + float step = MAX(m_RecoveryMin, MIN(m_RecoveryMax, error * m_Recovery)); + m_GaindB = MIN(wanted, m_GaindB + step); + } + } + + // ramp across the frame so a gain change can't click + float gain = m_Gain; + float newGain = pow(10.0f, m_GaindB/20.0f); + float ramp = (newGain - gain) / samples; + + for(int i = 0; i < length; i += 2) + { + gain += ramp; + float output = (float)(short)MAKEWORD(voice[i+1], voice[i]) * gain * m_Limiter; - // clamp gain - if (m_Gain > m_GainMax) - m_Gain = m_GainMax; - else if(m_Gain < m_GainMin) - m_Gain = m_GainMin; + // the limiter pulls a peak down at once and recovers slowly + if(fabs(output) > m_LimitLevel) + { + float reduction = m_LimitLevel / fabs(output); + m_Limiter *= reduction; + output *= reduction; + m_LimitedSamples++; + } + m_Limiter = MIN(1.0f, m_Limiter * AGC_LIMITER_RECOVERY); //write processed sample back, clamp to short range if (output > 32767.0f) output = 32767.0f; @@ -93,4 +175,5 @@ inline void CAGC::ProcessSampleBlock(uint8* voice, int length) voice[i] = HIBYTE((short)output); voice[i+1] = LOBYTE((short)output); } + m_Gain = newGain; } diff --git a/ambed/cagc.h b/ambed/cagc.h index f0ebf75..a5c89ad 100644 --- a/ambed/cagc.h +++ b/ambed/cagc.h @@ -21,9 +21,8 @@ // You should have received a copy of the GNU General Public License // along with Foobar. If not, see . // ---------------------------------------------------------------------------- -// Geoffrey Merck F4FXL / KC3FRA AGC code largely inspired by Liquid DSP -// Only took the parts we need qnd recoeded it to be close the XLX coding style -// https://github.com/jgaeddert/liquid-dsp/blob/master/src/agc/src/agc.c +// AGC with hang, replaces the sample by sample loop by Geoffrey Merck +// F4FXL / KC3FRA that was inspired by Liquid DSP #ifndef cagc_h #define cagc_h @@ -33,24 +32,39 @@ class CAGC : CSampleBlockProcessor { public: - //Constructor - CAGC(float initialLeveldB); + //Constructor, levels in dBFS and gains in dB, attack and hang in ms, + //recovery in dB/s for each dB below the target, between recoveryMin and recoveryMax in dB/s + CAGC(float targetdB, float clampingdB, float attackMs, float hangMs, + float recovery, float recoveryMin, float recoveryMax, float gatedB, float limitdB); //methods - void ProcessSampleBlock(uint8* voice, int length) ; - float GetGain();//gets current gain - + void ProcessSampleBlock(uint8* voice, int length); + float GetGain();//gets current gain in dB + float GetSpeechPeak();//gets the speech peak level in, in dBFS + bool IsVoice() { return m_bVoice; }//did the last frame pass the gate + long GetLimitedSamples() { return m_LimitedSamples; } + private: - float m_Gain; // current gain value - float m_GainMax, m_GainMin; //gain clamping - float m_targetEnergy; // scale value for target energy + bool m_Enabled; // a clamping of 0 measures but leaves the audio alone + float m_TargetdB; // speech peak level to aim for + float m_ClampingdB; + float m_AttackCoef; // share of the way down per frame + int m_HangFrames; + float m_Recovery; // dB per frame, for each dB below the target + float m_RecoveryMin; // dB per frame + float m_RecoveryMax; // dB per frame + float m_GateLevel; // quieter frames aren't voice and leave the gain alone + float m_LimitLevel; // no sample goes above this - // gain control loop filter parameters - float m_Bandwidth; // bandwidth-time constant - float m_Alpha; // feed-back gain + float m_SpeechPeak; // envelope of the frame levels + float m_RecentPeak; // the same, falling slowly so a word's tail isn't a quiet station + bool m_bVoice; + int m_HangLeft; // frames until the gain may rise - // signal level estimate - float m_EnergyPrime; // filtered output signal energy estimate + float m_GaindB; // current gain + float m_Gain; // the same, linear + float m_Limiter; // peak limiter gain, 1.0 when idle + long m_LimitedSamples; }; -#endif /* cgc_h */ \ No newline at end of file +#endif /* cagc_h */ diff --git a/ambed/cconfig.cpp b/ambed/cconfig.cpp new file mode 100644 index 0000000..950344e --- /dev/null +++ b/ambed/cconfig.cpp @@ -0,0 +1,325 @@ +// +// cconfig.cpp +// ambed +// +// Created by Andy Taylor (MW0MWZ) on 31/10/2026. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// xlxd is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Foobar. If not, see . +// ---------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include "cconfig.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// global objects + +CConfig g_Config; + +//////////////////////////////////////////////////////////////////////////////////////// +// keys, the defaults are the values in main.h + +struct SConfigKey +{ + const char *name; + float fDefault; + float fMin; + float fMax; + bool bInteger; +}; + +static const SConfigKey g_ConfigKeys[] = +{ + { "LISTEN_PORT", LISTEN_PORT, 1.0f, 65000.0f, true }, + { "DSCP_MARKING_ENABLE", DSCP_MARKING_ENABLE, 0.0f, 1.0f, true }, + { "DSCP_VALUE", DSCP_VALUE, 0.0f, 63.0f, true }, + { "DSTAR_TO_PCM", DSTAR_TO_PCM, -40.0f, 40.0f, false }, + { "DMR_TO_PCM", DMR_TO_PCM, -40.0f, 40.0f, false }, + { "M17_TO_PCM", M17_TO_PCM, -40.0f, 40.0f, false }, + { "P25_TO_PCM", P25_TO_PCM, -40.0f, 40.0f, false }, + { "PCM_TO_DSTAR", PCM_TO_DSTAR, -40.0f, 40.0f, false }, + { "PCM_TO_DMR", PCM_TO_DMR, -40.0f, 40.0f, false }, + { "PCM_TO_M17", PCM_TO_M17, -40.0f, 40.0f, false }, + { "PCM_TO_P25", PCM_TO_P25, -40.0f, 40.0f, false }, + { "USE_AGC", USE_AGC, 0.0f, 1.0f, true }, + { "AGC_TARGET", AGC_TARGET, -60.0f, -3.0f, false }, + { "AGC_CLAMPING", AGC_CLAMPING, 0.0f, 20.0f, false }, + { "AGC_ATTACK", AGC_ATTACK, 10.0f, 2000.0f, false }, + { "AGC_HANG", AGC_HANG, 0.0f, 10000.0f, false }, + { "AGC_RECOVERY", AGC_RECOVERY, 0.1f, 10.0f, false }, + { "AGC_RECOVERY_MIN", AGC_RECOVERY_MIN, 0.5f, 50.0f, false }, + { "AGC_RECOVERY_MAX", AGC_RECOVERY_MAX, 0.5f, 100.0f, false }, + { "AGC_GATE", AGC_GATE, -80.0f, -20.0f, false }, + { "USE_BANDPASSFILTER", USE_BANDPASSFILTER, 0.0f, 1.0f, true }, + { "STREAM_ACTIVITY_TIMEOUT", STREAM_ACTIVITY_TIMEOUT, 1.0f, 60.0f, true }, + { "TUNING_LOG", TUNING_LOG, 0.0f, 1.0f, true }, +}; + +static const SConfigKey *FindKey(const std::string &name) +{ + for ( const SConfigKey &key : g_ConfigKeys ) + { + if ( name == key.name ) + { + return &key; + } + } + return NULL; +} + +static std::string Trim(const std::string &str) +{ + size_t first = str.find_first_not_of(" \t\r"); + if ( first == std::string::npos ) + { + return ""; + } + return str.substr(first, str.find_last_not_of(" \t\r") - first + 1); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CConfig::CConfig() +{ + for ( const SConfigKey &key : g_ConfigKeys ) + { + m_Values[key.name] = key.fDefault; + } + m_IpValue = LISTEN_IP; + m_ListenIp = LISTEN_IP; + m_ListenPort = LISTEN_PORT; + m_VoiceTos = -1; + m_LastModified = 0; + m_bFileMissing = false; + Apply(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// load + +void CConfig::Load(const char *filename) +{ + std::lock_guard lock(m_Mutex); + m_Filename = filename; + + struct stat st; + if ( ::stat(m_Filename.c_str(), &st) == 0 ) + { + m_LastModified = st.st_mtime; + ReadFile(); + } + else + { + std::cout << "Config: cannot read " << m_Filename << ", using main.h defaults" << std::endl; + m_bFileMissing = true; + } + m_ListenIp = m_IpValue; + m_ListenPort = (uint16)m_Values.at("LISTEN_PORT"); + Apply(); + Report(); +} + +void CConfig::Reload(void) +{ + std::lock_guard lock(m_Mutex); + if ( m_Filename.empty() ) + { + return; + } + + struct stat st; + if ( ::stat(m_Filename.c_str(), &st) != 0 ) + { + if ( !m_bFileMissing ) + { + std::cout << "Config: cannot read " << m_Filename << ", keeping current values" << std::endl; + m_bFileMissing = true; + } + return; + } + + if ( m_bFileMissing || st.st_mtime != m_LastModified ) + { + m_bFileMissing = false; + m_LastModified = st.st_mtime; + std::cout << "Config: reloading " << m_Filename << ", changes apply from the next stream" << std::endl; + ReadFile(); + Apply(); + Report(); + if ( m_IpValue != m_ListenIp || (uint16)m_Values.at("LISTEN_PORT") != m_ListenPort ) + { + std::cout << "Config: LISTEN_IP and LISTEN_PORT changes need a restart" << std::endl; + } + } +} + +// DSCP can follow the file, it is read for every voice packet +void CConfig::Apply(void) +{ + bool enabled = (m_Values.at("DSCP_MARKING_ENABLE") != 0.0f); + m_VoiceTos = enabled ? ((int)m_Values.at("DSCP_VALUE") << 2) : -1; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// parsing + +void CConfig::ReadFile(void) +{ + std::ifstream file(m_Filename); + if ( !file.is_open() ) + { + std::cout << "Config: cannot open " << m_Filename << ", keeping current values" << std::endl; + return; + } + + // a key left out of the file goes back to its default + std::map values; + for ( const SConfigKey &key : g_ConfigKeys ) + { + values[key.name] = key.fDefault; + } + + std::string ip = LISTEN_IP; + + std::string line; + int lineNumber = 0; + while ( std::getline(file, line) ) + { + lineNumber++; + line = Trim(line.substr(0, line.find_first_of("#;"))); + if ( line.empty() || line[0] == '[' ) + { + continue; + } + + size_t equals = line.find('='); + + // the one setting that isn't a number + if ( equals != std::string::npos && Trim(line.substr(0, equals)) == "LISTEN_IP" ) + { + std::string text = Trim(line.substr(equals + 1)); + if ( IsValidIp(text) ) + { + ip = text; + } + else + { + std::cout << "Config: line " << lineNumber << " ignored, bad value for LISTEN_IP: " << text << std::endl; + ip = m_IpValue; + } + continue; + } + + const SConfigKey *key = (equals == std::string::npos) ? NULL : FindKey(Trim(line.substr(0, equals))); + if ( key == NULL ) + { + std::cout << "Config: line " << lineNumber << " ignored, unknown setting: " << line << std::endl; + continue; + } + + // a bad value keeps the value already in use, not the default + values[key->name] = m_Values[key->name]; + + std::string text = Trim(line.substr(equals + 1)); + char *end = NULL; + float value = ::strtof(text.c_str(), &end); + if ( text.empty() || *end != '\0' || !std::isfinite(value) || + value < key->fMin || value > key->fMax || (key->bInteger && value != floorf(value)) ) + { + std::cout << "Config: line " << lineNumber << " ignored, bad value for " << key->name + << " (" << key->fMin << " to " << key->fMax << "): " << text << std::endl; + continue; + } + values[key->name] = value; + } + + m_Values = values; + m_IpValue = ip; +} + +bool CConfig::IsValidIp(const std::string &ip) const +{ + struct in_addr addr; + return ::inet_pton(AF_INET, ip.c_str(), &addr) == 1; +} + +void CConfig::Report(void) const +{ + std::cout << "Config: LISTEN_IP=" << m_IpValue; + for ( const SConfigKey &key : g_ConfigKeys ) + { + std::cout << " " << key.name << "=" << m_Values.at(key.name); + } + std::cout << std::endl; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +CTuning CConfig::GetTuning(void) const +{ + std::lock_guard lock(m_Mutex); + CTuning tuning; + + tuning.fToPcm[CODEC_NONE] = 0.0f; + tuning.fToPcm[CODEC_AMBEPLUS] = m_Values.at("DSTAR_TO_PCM"); + tuning.fToPcm[CODEC_AMBE2PLUS] = m_Values.at("DMR_TO_PCM"); + tuning.fToPcm[CODEC_CODEC2] = m_Values.at("M17_TO_PCM"); + tuning.fToPcm[CODEC_IMBE] = m_Values.at("P25_TO_PCM"); + + tuning.fFromPcm[CODEC_NONE] = 0.0f; + tuning.fFromPcm[CODEC_AMBEPLUS] = m_Values.at("PCM_TO_DSTAR"); + tuning.fFromPcm[CODEC_AMBE2PLUS] = m_Values.at("PCM_TO_DMR"); + tuning.fFromPcm[CODEC_CODEC2] = m_Values.at("PCM_TO_M17"); + tuning.fFromPcm[CODEC_IMBE] = m_Values.at("PCM_TO_P25"); + + tuning.bUseAgc = (m_Values.at("USE_AGC") != 0.0f); + tuning.fAgcTarget = m_Values.at("AGC_TARGET"); + tuning.fAgcClamping = m_Values.at("AGC_CLAMPING"); + tuning.fAgcAttack = m_Values.at("AGC_ATTACK"); + tuning.fAgcHang = m_Values.at("AGC_HANG"); + tuning.fAgcRecovery = m_Values.at("AGC_RECOVERY"); + tuning.fAgcRecoveryMin = m_Values.at("AGC_RECOVERY_MIN"); + tuning.fAgcRecoveryMax = m_Values.at("AGC_RECOVERY_MAX"); + tuning.fAgcGate = m_Values.at("AGC_GATE"); + tuning.bUseFilter = (m_Values.at("USE_BANDPASSFILTER") != 0.0f); + tuning.iStreamTimeout = (int)m_Values.at("STREAM_ACTIVITY_TIMEOUT"); + tuning.bTuningLog = (m_Values.at("TUNING_LOG") != 0.0f); + + return tuning; +} + +std::string CConfig::GetListenIp(void) const +{ + std::lock_guard lock(m_Mutex); + return m_ListenIp; +} + +const char *CConfig::GetModeName(uint8 uiCodec) +{ + switch ( uiCodec ) + { + case CODEC_AMBEPLUS: return "DSTAR"; + case CODEC_AMBE2PLUS: return "DMR"; + case CODEC_CODEC2: return "M17"; + case CODEC_IMBE: return "P25"; + default: return "NONE"; + } +} diff --git a/ambed/cconfig.h b/ambed/cconfig.h new file mode 100644 index 0000000..1e31dd4 --- /dev/null +++ b/ambed/cconfig.h @@ -0,0 +1,95 @@ +// +// cconfig.h +// ambed +// +// Created by Andy Taylor (MW0MWZ) on 31/10/2026. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// xlxd is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Foobar. If not, see . +// ---------------------------------------------------------------------------- +#ifndef cconfig_h +#define cconfig_h + +#include +#include +#include +#include +#include +#include "main.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// tuning values, indexed by codec where they are per codec + +struct CTuning +{ + float fToPcm[NB_OF_CODECS]; // _TO_PCM, in dB + float fFromPcm[NB_OF_CODECS]; // PCM_TO_, in dB + bool bUseAgc; + float fAgcTarget; // in dBFS + float fAgcClamping; // in dB + float fAgcAttack; // in ms + float fAgcHang; // in ms + float fAgcRecovery; // in dB/s for each dB below the target + float fAgcRecoveryMin; // in dB/s + float fAgcRecoveryMax; // in dB/s + float fAgcGate; // in dBFS + bool bUseFilter; + int iStreamTimeout; // in seconds + bool bTuningLog; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CConfig +{ +public: + // constructor + CConfig(); + + // load, Reload does nothing until the file changes + void Load(const char *); + void Reload(void); + + // get, a copy so a stream keeps its values however long it runs + CTuning GetTuning(void) const; + std::string GetListenIp(void) const; + uint16 GetListenPort(void) const { return m_ListenPort; } + int GetVoiceTos(void) const { return m_VoiceTos; } + bool IsValidIp(const std::string &) const; + static const char *GetModeName(uint8); + +protected: + // parsing + void ReadFile(void); + void Report(void) const; + void Apply(void); + +protected: + // data + mutable std::mutex m_Mutex; + std::map m_Values; + std::string m_IpValue; // as read, the socket keeps the one it started with + std::string m_ListenIp; + uint16 m_ListenPort; + std::atomic m_VoiceTos; // TOS byte for voice packets, -1 for no marking + std::string m_Filename; + time_t m_LastModified; + bool m_bFileMissing; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cconfig_h */ diff --git a/ambed/ccontroller.cpp b/ambed/ccontroller.cpp index 85dbcd3..93da3c1 100644 --- a/ambed/ccontroller.cpp +++ b/ambed/ccontroller.cpp @@ -27,6 +27,7 @@ #include "ctimepoint.h" #include "cvocodecs.h" #include "ccontroller.h" +#include "cconfig.h" //////////////////////////////////////////////////////////////////////////////////////// @@ -70,7 +71,7 @@ bool CController::Init(void) std::cout << "Max concurrent streams: " << m_uiMaxStreams << " (from " << nbChannels << " vocoder channels)" << std::endl; // create our socket - ok = m_Socket.Open(m_Ip, TRANSCODER_PORT); + ok = m_Socket.Open(m_Ip, g_Config.GetListenPort()); if ( ok ) { // start thread; @@ -78,7 +79,7 @@ bool CController::Init(void) } else { - std::cout << "Error opening socket on port UDP" << TRANSCODER_PORT << " on ip " << m_Ip << std::endl; + std::cout << "Error opening socket on port UDP" << g_Config.GetListenPort() << " on ip " << m_Ip << std::endl; } // done @@ -224,7 +225,7 @@ CStream *CController::OpenStream(const CCallsign &Callsign, const CIp &Ip, uint8 m_uiLastStreamId = (m_uiLastStreamId + 1); m_uiLastStreamId = (m_uiLastStreamId > m_uiMaxStreams) ? 1 : m_uiLastStreamId; stream = new CStream(m_uiLastStreamId, Callsign, Ip, CodecIn, CodecOut1, CodecOut2, CodecOut3); - if ( stream->Init(TRANSCODER_PORT+m_uiLastStreamId) ) + if ( stream->Init(g_Config.GetListenPort()+m_uiLastStreamId) ) { std::cout << "Opened stream " << m_uiLastStreamId << std::endl; // and store it diff --git a/ambed/cfirfilter.cpp b/ambed/cfirfilter.cpp index 243c51b..8e06c19 100644 --- a/ambed/cfirfilter.cpp +++ b/ambed/cfirfilter.cpp @@ -43,7 +43,7 @@ CFIRFilter::~CFIRFilter() delete[] m_buffer; } -inline void CFIRFilter::ProcessSampleBlock(uint8* voice, int length) +void CFIRFilter::ProcessSampleBlock(uint8* voice, int length) { for(int i = 0; i < length; i += 2) { @@ -66,7 +66,9 @@ inline void CFIRFilter::ProcessSampleBlock(uint8* voice, int length) m_currentBufferPosition = (m_currentBufferPosition + 1) % m_tapsLength; - //write processed sample back + //write processed sample back, clamp to short range + if (output > 32767.0f) output = 32767.0f; + else if (output < -32768.0f) output = -32768.0f; voice[i] = HIBYTE((short)output); voice[i+1] = LOBYTE((short)output); } diff --git a/ambed/cfixedgain.cpp b/ambed/cfixedgain.cpp index 1dd0383..28fa771 100644 --- a/ambed/cfixedgain.cpp +++ b/ambed/cfixedgain.cpp @@ -38,7 +38,7 @@ CFixedGain::CFixedGain(float gaindB) //////////////////////////////////////////////////////////////////////////////////////// // processing -inline void CFixedGain::ProcessSampleBlock(uint8* voice, int length) +void CFixedGain::ProcessSampleBlock(uint8* voice, int length) { for(int i = 0; i < length; i += 2) { diff --git a/ambed/cftdidevicedescr.cpp b/ambed/cftdidevicedescr.cpp index 7d52c46..1bfb330 100644 --- a/ambed/cftdidevicedescr.cpp +++ b/ambed/cftdidevicedescr.cpp @@ -227,54 +227,54 @@ int CFtdiDeviceDescr::CreateUsb3012(CFtdiDeviceDescr *descr, std::vectorpush_back(Channel); Usb3003A->AddChannel(Channel); // ch2 - Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); channels->push_back(Channel); Usb3003A->AddChannel(Channel); // ch3 - Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1); channels->push_back(Channel); Usb3003B->AddChannel(Channel); // ch4 - Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0); channels->push_back(Channel); Usb3003B->AddChannel(Channel); // ch5 - Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3003B->AddChannel(Channel); // ch6 - Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3003B->AddChannel(Channel); // ch7 - Channel = new CVocodecChannel(Usb3003C, 0, Usb3003C, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003C, 0, Usb3003C, 1); channels->push_back(Channel); Usb3003C->AddChannel(Channel); // ch8 - Channel = new CVocodecChannel(Usb3003C, 1, Usb3003C, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003C, 1, Usb3003C, 0); channels->push_back(Channel); Usb3003C->AddChannel(Channel); // ch9 - Channel = new CVocodecChannel(Usb3003D, 0, Usb3003D, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003D, 0, Usb3003D, 1); channels->push_back(Channel); Usb3003D->AddChannel(Channel); // ch10 - Channel = new CVocodecChannel(Usb3003D, 1, Usb3003D, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003D, 1, Usb3003D, 0); channels->push_back(Channel); Usb3003D->AddChannel(Channel); // ch11 - Channel = new CVocodecChannel(Usb3003C, 2, Usb3003D, 2, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003C, 2, Usb3003D, 2); channels->push_back(Channel); Usb3003C->AddChannel(Channel); Usb3003D->AddChannel(Channel); // ch12 - Channel = new CVocodecChannel(Usb3003D, 2, Usb3003C, 2, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003D, 2, Usb3003C, 2); channels->push_back(Channel); Usb3003C->AddChannel(Channel); Usb3003D->AddChannel(Channel); @@ -319,28 +319,28 @@ int CFtdiDeviceDescr::CreateUsb3006(CFtdiDeviceDescr *descr, std::vectorpush_back(Channel); Usb3003A->AddChannel(Channel); // ch2 - Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); channels->push_back(Channel); Usb3003A->AddChannel(Channel); // ch3 - Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1); channels->push_back(Channel); Usb3003B->AddChannel(Channel); // ch4 - Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0); channels->push_back(Channel); Usb3003B->AddChannel(Channel); // ch5 - Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3003B->AddChannel(Channel); // ch6 - Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3003B->AddChannel(Channel); @@ -384,11 +384,11 @@ int CFtdiDeviceDescr::CreateUsb3003(CFtdiDeviceDescr *descr, std::vectorpush_back(Channel); Usb3003->AddChannel(Channel); // ch2 - Channel = new CVocodecChannel(Usb3003, 1, Usb3003, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003, 1, Usb3003, 0); channels->push_back(Channel); Usb3003->AddChannel(Channel); // done @@ -420,12 +420,12 @@ int CFtdiDeviceDescr::CreatePair(CUsb3000Interface *Usb3000A, CUsb3000Interface // create all channels { // ch1 - Channel = new CVocodecChannel(Usb3000A, 0, Usb3000B, 0, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3000A, 0, Usb3000B, 0); channels->push_back(Channel); Usb3000A->AddChannel(Channel); Usb3000B->AddChannel(Channel); // ch2 - Channel = new CVocodecChannel(Usb3000B, 0, Usb3000A, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3000B, 0, Usb3000A, 0); channels->push_back(Channel); Usb3000A->AddChannel(Channel); Usb3000B->AddChannel(Channel); @@ -459,28 +459,28 @@ int CFtdiDeviceDescr::CreatePair(CUsb3003Interface *Usb3003A, CUsb3003Interface // create all channels { // ch1 - Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1); channels->push_back(Channel); Usb3003A->AddChannel(Channel); // ch2 - Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); channels->push_back(Channel); Usb3003A->AddChannel(Channel); // ch3 - Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1); channels->push_back(Channel); Usb3003B->AddChannel(Channel); // ch4 - Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0); channels->push_back(Channel); Usb3003B->AddChannel(Channel); // ch5 - Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3003B->AddChannel(Channel); // ch6 - Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3003B->AddChannel(Channel); @@ -513,20 +513,20 @@ int CFtdiDeviceDescr::CreatePair(CUsb3003Interface *Usb3003A, CUsb3000Interface // create all channels { // ch1 - Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1); channels->push_back(Channel); Usb3003A->AddChannel(Channel); // ch2 - Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); channels->push_back(Channel); Usb3003A->AddChannel(Channel); // ch3 - Channel = new CVocodecChannel(Usb3003A, 2, Usb3000B, 0, CODECGAIN_AMBEPLUS); + Channel = new CVocodecChannel(Usb3003A, 2, Usb3000B, 0); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3000B->AddChannel(Channel); // ch4 - Channel = new CVocodecChannel(Usb3000B, 0, Usb3003A, 2, CODECGAIN_AMBE2PLUS); + Channel = new CVocodecChannel(Usb3000B, 0, Usb3003A, 2); channels->push_back(Channel); Usb3003A->AddChannel(Channel); Usb3000B->AddChannel(Channel); diff --git a/ambed/csignalprocessor.cpp b/ambed/csignalprocessor.cpp index 21fba81..e54e792 100644 --- a/ambed/csignalprocessor.cpp +++ b/ambed/csignalprocessor.cpp @@ -24,32 +24,103 @@ // ---------------------------------------------------------------------------- // Geoffrey Merck F4FXL / KC3FRA AGC +#include +#include +#include #include "main.h" #include "csignalprocessor.h" - -#if USE_AGC == 1 #include "cagc.h" -#else #include "cfixedgain.h" -#endif - -#if USE_BANDPASSFILTER == 1 #include "cfirfilter.h" -#endif + +// within this of the clamp, the AGC is at its limit +#define AGC_LIMIT_MARGIN 0.05f + +static float ToDbfs(double level) +{ + return (level > 0.0) ? (float)(20.0 * log10(level / 32768.0)) : -96.0f; +} + +// a gain in the report, as DMR_TO_PCM -1.50 +static std::string GainLabel(const std::string& name, float gain) +{ + std::ostringstream label; + label << name << " " << std::showpos << std::fixed << std::setprecision(2) << gain; + return label.str(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// level meter + +CLevelMeter::CLevelMeter() +{ + m_Sum = 0.0; + m_Samples = 0; + m_Clipped = 0; + m_Peak = 0; +} + +void CLevelMeter::Add(const uint8* voice, int length) +{ + for(int i = 0; i < length; i += 2) + { + int sample = abs((int)(short)MAKEWORD(voice[i+1], voice[i])); + m_Sum += sample; + m_Samples++; + m_Peak = MAX(m_Peak, sample); + if(sample >= 32767) + { + m_Clipped++; + } + } +} + +void CLevelMeter::Report(const std::string& label) const +{ + if(m_Samples == 0) + { + return; + } + std::cout << "Tuning: " << std::left << std::setw(22) << label << std::right + << "level " << std::setw(6) << std::setprecision(1) << ToDbfs(m_Sum / m_Samples) << " dBFS" + << " peak " << std::setw(6) << ToDbfs(m_Peak) << " dBFS" + << " clipped " << std::setprecision(2) << (100.0 * m_Clipped / m_Samples) << "%" << std::endl; +} //////////////////////////////////////////////////////////////////////////////////////// // constructor -CSignalProcessor::CSignalProcessor(float gaindB) +CSignalProcessor::CSignalProcessor(uint8 uiCodecIn) { -#if USE_BANDPASSFILTER - m_sampleProcessors.push_back((CSampleBlockProcessor*)new CFIRFilter(FILTER_TAPS, FILTER_TAPS_LENGTH)); -#endif -#if USE_AGC == 1 - m_sampleProcessors.push_back((CSampleBlockProcessor*)new CAGC(gaindB)); -#else - m_sampleProcessors.push_back((CSampleBlockProcessor*)new CFixedGain(gaindB)); -#endif + m_uiCodecIn = uiCodecIn; + m_Tuning = g_Config.GetTuning(); + + m_pDecodeGain = new CFixedGain(m_Tuning.fToPcm[uiCodecIn]); + m_pFilter = m_Tuning.bUseFilter ? new CFIRFilter(FILTER_TAPS, FILTER_TAPS_LENGTH) : NULL; + // The encode gains come after the AGC, so leave room for the highest one + float limit = AGC_CEILING; + for(int i = 0; i < NB_OF_CODECS; i++) + { + limit = MIN(limit, AGC_CEILING - m_Tuning.fFromPcm[i]); + } + m_pAgc = m_Tuning.bUseAgc ? new CAGC(m_Tuning.fAgcTarget, m_Tuning.fAgcClamping, m_Tuning.fAgcAttack, m_Tuning.fAgcHang, + m_Tuning.fAgcRecovery, m_Tuning.fAgcRecoveryMin, m_Tuning.fAgcRecoveryMax, + m_Tuning.fAgcGate, limit) : NULL; + for(int i = 0; i < NB_OF_CODECS; i++) + { + m_pEncodeGain[i] = new CFixedGain(m_Tuning.fFromPcm[i]); + } + + m_bVoice = false; + m_Frames = 0; + m_VoiceFrames = 0; + m_AgcSum = 0.0; + m_AgcMin = 0.0f; + m_AgcMax = 0.0f; + m_AgcAtMax = 0; + m_AgcAtMin = 0; + m_SpeechPeakSum = 0.0; + m_SpeechPeakFrames = 0; } //////////////////////////////////////////////////////////////////////////////////////// @@ -57,9 +128,12 @@ CSignalProcessor::CSignalProcessor(float gaindB) CSignalProcessor::~CSignalProcessor() { - for(int i = 0; i < m_sampleProcessors.size(); i++) + delete m_pDecodeGain; + delete m_pFilter; + delete m_pAgc; + for(int i = 0; i < NB_OF_CODECS; i++) { - delete m_sampleProcessors[i]; + delete m_pEncodeGain[i]; } } @@ -68,27 +142,111 @@ CSignalProcessor::~CSignalProcessor() void CSignalProcessor::Process(uint8* voice, int length) { - /*float sample; - int j;*/ - auto processorsSize = m_sampleProcessors.size(); + // Only voice counts towards the report, pauses would pull the levels down + double sum = 0.0; + for(int i = 0; i < length; i += 2) + { + sum += abs((int)(short)MAKEWORD(voice[i+1], voice[i])); + } + m_bVoice = (length > 0) && (ToDbfs(sum / (length / 2)) >= TUNING_SILENCE_LEVEL); - for(int j = 0; j < processorsSize; j++) + m_Frames++; + if(m_bVoice) { - m_sampleProcessors[j]->ProcessSampleBlock(voice, length); + m_VoiceFrames++; + m_Decoded.Add(voice, length); } - /*for(int i = 0; i < length; i += 2) + m_pDecodeGain->ProcessSampleBlock(voice, length); + if(m_pFilter != NULL) { - //Get the sample - sample = (float)(short)MAKEWORD(voice[i+1], voice[i]); + m_pFilter->ProcessSampleBlock(voice, length); + } + + if(m_bVoice) + { + m_ToAgc.Add(voice, length); + } - for(j = 0; j < processorsSize; j++) + if(m_pAgc != NULL) + { + m_pAgc->ProcessSampleBlock(voice, length); + + if(m_bVoice) { - sample = m_sampleProcessors[j]->ProcessSample(sample); + float gain = m_pAgc->GetGain(); + m_AgcMin = (m_VoiceFrames == 1) ? gain : MIN(m_AgcMin, gain); + m_AgcMax = (m_VoiceFrames == 1) ? gain : MAX(m_AgcMax, gain); + m_AgcSum += gain; + if(m_pAgc->IsVoice()) + { + m_SpeechPeakSum += m_pAgc->GetSpeechPeak(); + m_SpeechPeakFrames++; + } + if(m_Tuning.fAgcClamping > 0.0f && gain >= m_Tuning.fAgcClamping - AGC_LIMIT_MARGIN) + { + m_AgcAtMax++; + } + else if(m_Tuning.fAgcClamping > 0.0f && gain <= -m_Tuning.fAgcClamping + AGC_LIMIT_MARGIN) + { + m_AgcAtMin++; + } } + } + + if(m_bVoice) + { + m_FromAgc.Add(voice, length); + } +} + +void CSignalProcessor::ProcessOutput(uint8 uiCodecOut, uint8* voice, int length) +{ + m_pEncodeGain[uiCodecOut]->ProcessSampleBlock(voice, length); + if(m_bVoice) + { + m_Output[uiCodecOut].Add(voice, length); + } +} - //write processed sample back - voice[i] = HIBYTE((short)sample); - voice[i+1] = LOBYTE((short)sample); - }*/ -} \ No newline at end of file +//////////////////////////////////////////////////////////////////////////////////////// +// tuning report + +void CSignalProcessor::Report(uint16 uiStreamId, const std::string& callsign) const +{ + if(!m_Tuning.bTuningLog || m_VoiceFrames == 0) + { + return; + } + + std::ios::fmtflags flags = std::cout.flags(); + std::streamsize precision = std::cout.precision(); + std::cout << std::fixed; + + std::string mode = CConfig::GetModeName(m_uiCodecIn); + std::cout << "Tuning: stream " << uiStreamId << " " << callsign << " " << mode << " input, " + << m_VoiceFrames << " voice frames of " << m_Frames << std::endl; + + m_Decoded.Report("decoded"); + m_ToAgc.Report(GainLabel(mode + "_TO_PCM", m_Tuning.fToPcm[m_uiCodecIn])); + + if(m_pAgc != NULL) + { + std::cout << "Tuning: " << std::left << std::setw(22) << "AGC" << std::right << std::setprecision(1) + << "target " << m_Tuning.fAgcTarget << " dBFS speech peaks " + << ((m_SpeechPeakFrames > 0) ? (float)(m_SpeechPeakSum / m_SpeechPeakFrames) : -96.0f) << " dBFS gain average " << std::showpos << (m_AgcSum / m_VoiceFrames) + << " dB, " << m_AgcMin << " to " << m_AgcMax << " dB" << std::noshowpos + << " at limit " << (100.0 * m_AgcAtMax / m_VoiceFrames) << "% high " + << (100.0 * m_AgcAtMin / m_VoiceFrames) << "% low" + << " limiter " << std::setprecision(2) << (100.0 * m_pAgc->GetLimitedSamples() / (m_Frames * 160)) << "%" << std::endl; + m_FromAgc.Report("after AGC"); + } + + for(int i = 0; i < NB_OF_CODECS; i++) + { + m_Output[i].Report(GainLabel(std::string("PCM_TO_") + CConfig::GetModeName((uint8)i), m_Tuning.fFromPcm[i])); + } + + std::cout.flags(flags); + std::cout.precision(precision); +} diff --git a/ambed/csignalprocessor.h b/ambed/csignalprocessor.h index a1081d7..822f5e1 100644 --- a/ambed/csignalprocessor.h +++ b/ambed/csignalprocessor.h @@ -26,23 +26,69 @@ #ifndef csignalprocessor_h #define csignalprocessor_h -#include +#include +#include "cconfig.h" #include "csampleblockprocessor.h" +class CAGC; +class CFixedGain; +class CFIRFilter; + +// voice level at one point of the chain, for the tuning report +class CLevelMeter +{ +public: + CLevelMeter(); + + void Add(const uint8* voice, int length); + void Report(const std::string& label) const; + +private: + double m_Sum; // sum of absolute sample values + long m_Samples; + long m_Clipped; + int m_Peak; +}; + class CSignalProcessor { public: - //Constructor - CSignalProcessor(float gaindB); + //Constructor, takes the input codec and the current ambed.ini values + CSignalProcessor(uint8 uiCodecIn); //Destructor ~CSignalProcessor(); //Processing - void Process(uint8* voice, int length); + void Process(uint8* voice, int length); //decode gain, filter, AGC + void ProcessOutput(uint8 uiCodecOut, uint8* voice, int length); //encode gain + + //Tuning report, logged when the stream closes + void Report(uint16 uiStreamId, const std::string& callsign) const; private: - std::vector m_sampleProcessors; + uint8 m_uiCodecIn; + CTuning m_Tuning; + CFixedGain *m_pDecodeGain; + CFIRFilter *m_pFilter; + CAGC *m_pAgc; + CFixedGain *m_pEncodeGain[NB_OF_CODECS]; + + // tuning report + bool m_bVoice; //is the current frame voice + long m_Frames; + long m_VoiceFrames; + CLevelMeter m_Decoded; + CLevelMeter m_ToAgc; + CLevelMeter m_FromAgc; + CLevelMeter m_Output[NB_OF_CODECS]; + double m_AgcSum; + float m_AgcMin; + float m_AgcMax; + long m_AgcAtMax; + long m_AgcAtMin; + double m_SpeechPeakSum; + long m_SpeechPeakFrames; }; -#endif /* csignalprocessor_h */ \ No newline at end of file +#endif /* csignalprocessor_h */ diff --git a/ambed/cstream.cpp b/ambed/cstream.cpp index 83d8902..a3fc5f6 100644 --- a/ambed/cstream.cpp +++ b/ambed/cstream.cpp @@ -35,6 +35,24 @@ //////////////////////////////////////////////////////////////////////////////////////// // define +// DVSI hardware expects big-endian PCM, as does the signal processor +static void PcmToBytes(const int16_t *pcm, uint8 *bytes) +{ + for (int i = 0; i < 160; i++) + { + bytes[i*2] = (uint8)(((uint16_t)pcm[i] >> 8) & 0xFF); + bytes[i*2 + 1] = (uint8)((uint16_t)pcm[i] & 0xFF); + } +} + +static void BytesToPcm(const uint8 *bytes, int16_t *pcm) +{ + for (int i = 0; i < 160; i++) + { + pcm[i] = (int16_t)((bytes[i*2] << 8) | bytes[i*2 + 1]); + } +} + //////////////////////////////////////////////////////////////////////////////////////// // constructor @@ -46,20 +64,17 @@ CStream::CStream() m_uiCodecOut1 = CODEC_NONE; m_uiCodecOut2 = CODEC_NONE; m_uiCodecOut3 = CODEC_NONE; + m_iActivityTimeout = g_Config.GetTuning().iStreamTimeout; m_bStopThread = false; m_pThread = NULL; m_VocodecChannel = NULL; m_EncoderChannel1 = NULL; m_EncoderChannel2 = NULL; m_pCodec2Decoder = NULL; - m_pSignalProcessor1 = NULL; - m_pSignalProcessor2 = NULL; + m_pSignalProcessor = NULL; m_pImbeEncoder = NULL; m_pImbeDecoder = NULL; m_pCodec2Encoder = NULL; - m_fCodec2DecodeGain = 1.0f; - m_fImbeGain = 1.0f; - m_fCodec2Gain = 1.0f; m_pStagedPacket = NULL; m_LastActivity.Now(); m_iTotalPackets = 0; @@ -78,20 +93,17 @@ CStream::CStream(uint16 uiId, const CCallsign &Callsign, const CIp &Ip, uint8 ui m_uiCodecOut1 = uiCodecOut1; m_uiCodecOut2 = uiCodecOut2; m_uiCodecOut3 = uiCodecOut3; + m_iActivityTimeout = g_Config.GetTuning().iStreamTimeout; m_bStopThread = false; m_pThread = NULL; m_VocodecChannel = NULL; m_EncoderChannel1 = NULL; m_EncoderChannel2 = NULL; m_pCodec2Decoder = NULL; - m_pSignalProcessor1 = NULL; - m_pSignalProcessor2 = NULL; + m_pSignalProcessor = NULL; m_pImbeEncoder = NULL; m_pImbeDecoder = NULL; m_pCodec2Encoder = NULL; - m_fCodec2DecodeGain = 1.0f; - m_fImbeGain = 1.0f; - m_fCodec2Gain = 1.0f; m_LastActivity.Now(); m_iTotalPackets = 0; m_iLostPackets = 0; @@ -142,20 +154,9 @@ bool CStream::Init(uint16 uiPort) // store port m_uiPort = uiPort; - // Create signal processors for each output encoder - // Apply gain based on output codec - adjusted for Codec2 input levels - // Codec2 encoder gains from main.h - int gain1 = (m_uiCodecOut1 == CODEC_AMBEPLUS) ? CODEC2_TO_AMBEPLUS_GAIN : CODEC2_TO_AMBE2PLUS_GAIN; - int gain2 = (m_uiCodecOut2 == CODEC_AMBEPLUS) ? CODEC2_TO_AMBEPLUS_GAIN : CODEC2_TO_AMBE2PLUS_GAIN; - m_pSignalProcessor1 = new CSignalProcessor((float)gain1); - m_pSignalProcessor2 = new CSignalProcessor((float)gain2); - - // Precompute gain multipliers (avoid pow() per packet) - m_fCodec2DecodeGain = pow(10.0f, CODEC2_DECODE_GAIN / 20.0f); - m_fImbeGain = pow(10.0f, CODEC2_TO_IMBE_GAIN / 20.0f); + m_pSignalProcessor = new CSignalProcessor(CODEC_CODEC2); std::cout << "Codec2 input mode: software decode -> hardware encode (AMBE+ & AMBE2+) + software encode (IMBE)" << std::endl; - std::cout << " Signal processing: gain1=" << gain1 << "dB, gain2=" << gain2 << "dB" << std::endl; // start thread m_pThread = new std::thread(CStream::Thread, this); @@ -175,8 +176,6 @@ bool CStream::Init(uint16 uiPort) m_pCodec2Decoder = NULL; delete m_pImbeEncoder; m_pImbeEncoder = NULL; - if (m_pSignalProcessor1 != NULL) { delete m_pSignalProcessor1; m_pSignalProcessor1 = NULL; } - if (m_pSignalProcessor2 != NULL) { delete m_pSignalProcessor2; m_pSignalProcessor2 = NULL; } } } else if (m_uiCodecIn == CODEC_IMBE) @@ -199,19 +198,9 @@ bool CStream::Init(uint16 uiPort) // store port m_uiPort = uiPort; - // Create signal processors for each output encoder - // IMBE decode gain is applied separately, these are additional encoder gains - int gain1 = IMBE_TO_AMBEPLUS_GAIN; // D-Star encoder gain - int gain2 = IMBE_TO_AMBE2PLUS_GAIN; // DMR encoder gain - m_pSignalProcessor1 = new CSignalProcessor((float)gain1); - m_pSignalProcessor2 = new CSignalProcessor((float)gain2); - - // Precompute gain multipliers (avoid pow() per packet) - m_fImbeGain = pow(10.0f, IMBE_DECODE_GAIN / 20.0f); - m_fCodec2Gain = pow(10.0f, IMBE_TO_CODEC2_GAIN / 20.0f); + m_pSignalProcessor = new CSignalProcessor(CODEC_IMBE); std::cout << "IMBE input mode: software decode -> hardware encode (AMBE+ & AMBE2+) + software encode (Codec2)" << std::endl; - std::cout << " Signal processing: gain1=" << gain1 << "dB (D-Star), gain2=" << gain2 << "dB (DMR)" << std::endl; std::cout << " Encoder ch1 (D-Star): in=" << m_EncoderChannel1->GetChannelIn() << " out=" << m_EncoderChannel1->GetChannelOut() << " codecOut=" << (int)m_EncoderChannel1->GetCodecOut() << std::endl; @@ -237,8 +226,6 @@ bool CStream::Init(uint16 uiPort) m_pImbeDecoder = NULL; delete m_pCodec2Encoder; m_pCodec2Encoder = NULL; - if (m_pSignalProcessor1 != NULL) { delete m_pSignalProcessor1; m_pSignalProcessor1 = NULL; } - if (m_pSignalProcessor2 != NULL) { delete m_pSignalProcessor2; m_pSignalProcessor2 = NULL; } } } else @@ -448,6 +435,17 @@ void CStream::Close(void) totalOverflowDrops += m_EncoderChannel2->GetPidFifoOverflowDrops(); } + // Tuning report, the thread has stopped and the channel is still open + std::string callsign = (const char *)m_Callsign; + if ( m_pSignalProcessor != NULL ) + { + m_pSignalProcessor->Report(m_uiId, callsign); + } + if ( m_VocodecChannel != NULL ) + { + m_VocodecChannel->ReportSignal(m_uiId, callsign); + } + // Close and null vocodec channels if ( m_VocodecChannel != NULL ) { @@ -461,8 +459,7 @@ void CStream::Close(void) // Delete and null software objects if ( m_pCodec2Decoder != NULL ) { delete m_pCodec2Decoder; m_pCodec2Decoder = NULL; } - if ( m_pSignalProcessor1 != NULL ) { delete m_pSignalProcessor1; m_pSignalProcessor1 = NULL; } - if ( m_pSignalProcessor2 != NULL ) { delete m_pSignalProcessor2; m_pSignalProcessor2 = NULL; } + if ( m_pSignalProcessor != NULL ) { delete m_pSignalProcessor; m_pSignalProcessor = NULL; } if ( m_pImbeEncoder != NULL ) { delete m_pImbeEncoder; m_pImbeEncoder = NULL; } if ( m_pImbeDecoder != NULL ) { delete m_pImbeDecoder; m_pImbeDecoder = NULL; } if ( m_pCodec2Encoder != NULL ) { delete m_pCodec2Encoder; m_pCodec2Encoder = NULL; } @@ -632,7 +629,6 @@ void CStream::TaskCodec2Input(void) uint8 Codec2Data[CODEC2_FRAME_SIZE]; int16_t pcmAudio[160]; // 160 samples = 20ms at 8kHz uint8 ImbeData[IMBE_FRAME_SIZE]; - CPacketQueue *queue1, *queue2; // anything coming in from codec client ? if ( m_Socket.Receive(&Buffer, &Ip, 1) != -1 ) @@ -646,26 +642,17 @@ void CStream::TaskCodec2Input(void) // Software decode Codec2 to PCM m_pCodec2Decoder->codec2_decode(pcmAudio, Codec2Data); - // Apply decode gain to Codec2 output (matches IMBE path which applies IMBE_DECODE_GAIN) - for (int i = 0; i < 160; i++) - { - int32_t sample = (int32_t)(pcmAudio[i] * m_fCodec2DecodeGain); - if (sample > 32767) sample = 32767; - else if (sample < -32768) sample = -32768; - pcmAudio[i] = (int16_t)sample; - } + // Big-endian PCM through the decode gain, filter and AGC + uint8 pcmBytes[320]; + PcmToBytes(pcmAudio, pcmBytes); + m_pSignalProcessor->Process(pcmBytes, 320); // Software encode PCM to IMBE for P25 output (3rd codec) - // Apply precomputed gain adjustment for IMBE encoding - int16_t pcmForImbe[160]; - for (int i = 0; i < 160; i++) - { - int32_t sample = (int32_t)(pcmAudio[i] * m_fImbeGain); - if (sample > 32767) sample = 32767; - else if (sample < -32768) sample = -32768; - pcmForImbe[i] = (int16_t)sample; - } - m_pImbeEncoder->encode_4400(pcmForImbe, ImbeData); + uint8 pcmForImbe[320]; + ::memcpy(pcmForImbe, pcmBytes, 320); + m_pSignalProcessor->ProcessOutput(CODEC_IMBE, pcmForImbe, 320); + BytesToPcm(pcmForImbe, pcmAudio); + m_pImbeEncoder->encode_4400(pcmAudio, ImbeData); // Queue the IMBE data for later retrieval when hardware encoders return // Drop oldest if queue exceeds max depth (hardware stall protection) @@ -678,30 +665,6 @@ void CStream::TaskCodec2Input(void) m_ImbeQueue.push(imbeVec); m_nImbeQueueSize++; - // Convert PCM to byte arrays for CVoicePacket (one for each encoder) - // DVSI hardware expects big-endian PCM — use portable byte extraction - uint8 pcmBytes1[320]; - uint8 pcmBytes2[320]; - for (int i = 0; i < 160; i++) - { - pcmBytes1[i*2] = (uint8)(((uint16_t)pcmAudio[i] >> 8) & 0xFF); // high byte first - pcmBytes1[i*2 + 1] = (uint8)((uint16_t)pcmAudio[i] & 0xFF); // low byte second - pcmBytes2[i*2] = pcmBytes1[i*2]; - pcmBytes2[i*2 + 1] = pcmBytes1[i*2 + 1]; - } - - // Apply signal processing (gain adjustment) to each PCM buffer - // This matches the gain normalization used in the AMBE->AMBE path - m_pSignalProcessor1->Process(pcmBytes1, 320); - m_pSignalProcessor2->Process(pcmBytes2, 320); - - // Create voice packets and push to both encoder channels - CVoicePacket *voicePacket1 = new CVoicePacket(pcmBytes1, 320); - voicePacket1->SetChannel(m_EncoderChannel1->GetChannelOut()); - - CVoicePacket *voicePacket2 = new CVoicePacket(pcmBytes2, 320); - voicePacket2->SetChannel(m_EncoderChannel2->GetChannelOut()); - // PID-preservation: push the input packet's PID into both // encoder channels' FIFOs so the matching pops in the USB // interface (when the AMBE responses arrive from hardware) @@ -713,15 +676,9 @@ void CStream::TaskCodec2Input(void) m_EncoderChannel1->PushPid(uiPid); m_EncoderChannel2->PushPid(uiPid); - // Push to encoder channel 1 (AMBE+) - queue1 = m_EncoderChannel1->GetVoiceQueue(); - queue1->push(voicePacket1); - m_EncoderChannel1->ReleaseVoiceQueue(); - - // Push to encoder channel 2 (AMBE2+) - queue2 = m_EncoderChannel2->GetVoiceQueue(); - queue2->push(voicePacket2); - m_EncoderChannel2->ReleaseVoiceQueue(); + // Push to the encoder channels (AMBE+ and AMBE2+) + PushEncoderPcm(m_EncoderChannel1, m_uiCodecOut1, pcmBytes); + PushEncoderPcm(m_EncoderChannel2, m_uiCodecOut2, pcmBytes); } } @@ -784,6 +741,24 @@ void CStream::TaskCodec2Input(void) } while (ready); } +//////////////////////////////////////////////////////////////////////////////////////// +// Codec2 and IMBE input: PCM to the hardware encoders + +void CStream::PushEncoderPcm(CVocodecChannel *Channel, uint8 uiCodecOut, const uint8 *pcmBytes) +{ + // One copy for each encoder, each at its own level + uint8 pcm[320]; + ::memcpy(pcm, pcmBytes, 320); + m_pSignalProcessor->ProcessOutput(uiCodecOut, pcm, 320); + + CVoicePacket *voicePacket = new CVoicePacket(pcm, 320); + voicePacket->SetChannel(Channel->GetChannelOut()); + + CPacketQueue *queue = Channel->GetVoiceQueue(); + queue->push(voicePacket); + Channel->ReleaseVoiceQueue(); +} + //////////////////////////////////////////////////////////////////////////////////////// // IMBE input handling @@ -795,7 +770,6 @@ void CStream::TaskImbeInput(void) uint8 ImbeData[IMBE_FRAME_SIZE]; int16_t pcmAudio[160]; // 160 samples = 20ms at 8kHz uint8 Codec2Data[CODEC2_FRAME_SIZE]; - CPacketQueue *queue1, *queue2; // anything coming in from codec client ? if ( m_Socket.Receive(&Buffer, &Ip, 1) != -1 ) @@ -810,27 +784,17 @@ void CStream::TaskImbeInput(void) // imbe_vocoder::decode_4400(int16_t *snd, uint8_t *imbe) m_pImbeDecoder->decode_4400(pcmAudio, ImbeData); - // Apply precomputed gain to IMBE decoder output - for (int i = 0; i < 160; i++) - { - int32_t sample = (int32_t)(pcmAudio[i] * m_fImbeGain); - // Clip to int16 range - if (sample > 32767) sample = 32767; - else if (sample < -32768) sample = -32768; - pcmAudio[i] = (int16_t)sample; - } + // Big-endian PCM through the decode gain, filter and AGC + uint8 pcmBytes[320]; + PcmToBytes(pcmAudio, pcmBytes); + m_pSignalProcessor->Process(pcmBytes, 320); // Software encode PCM to Codec2 for M17 output (3rd codec) - // Apply precomputed IMBE->Codec2 gain adjustment - int16_t pcmForCodec2[160]; - for (int i = 0; i < 160; i++) - { - int32_t sample = (int32_t)(pcmAudio[i] * m_fCodec2Gain); - if (sample > 32767) sample = 32767; - else if (sample < -32768) sample = -32768; - pcmForCodec2[i] = (int16_t)sample; - } - m_pCodec2Encoder->codec2_encode(Codec2Data, pcmForCodec2); + uint8 pcmForCodec2[320]; + ::memcpy(pcmForCodec2, pcmBytes, 320); + m_pSignalProcessor->ProcessOutput(CODEC_CODEC2, pcmForCodec2, 320); + BytesToPcm(pcmForCodec2, pcmAudio); + m_pCodec2Encoder->codec2_encode(Codec2Data, pcmAudio); // Queue the Codec2 data for later retrieval when hardware encoders return // Drop oldest if queue exceeds max depth (hardware stall protection) @@ -843,29 +807,6 @@ void CStream::TaskImbeInput(void) m_Codec2Queue.push(c2vec); m_nCodec2QueueSize++; - // Convert PCM to byte arrays for CVoicePacket (one for each encoder) - // DVSI hardware expects big-endian PCM — use portable byte extraction - uint8 pcmBytes1[320]; - uint8 pcmBytes2[320]; - for (int i = 0; i < 160; i++) - { - pcmBytes1[i*2] = (uint8)(((uint16_t)pcmAudio[i] >> 8) & 0xFF); // high byte first - pcmBytes1[i*2 + 1] = (uint8)((uint16_t)pcmAudio[i] & 0xFF); // low byte second - pcmBytes2[i*2] = pcmBytes1[i*2]; - pcmBytes2[i*2 + 1] = pcmBytes1[i*2 + 1]; - } - - // Apply signal processing (gain adjustment) to each PCM buffer - m_pSignalProcessor1->Process(pcmBytes1, 320); - m_pSignalProcessor2->Process(pcmBytes2, 320); - - // Create voice packets and push to both encoder channels - CVoicePacket *voicePacket1 = new CVoicePacket(pcmBytes1, 320); - voicePacket1->SetChannel(m_EncoderChannel1->GetChannelOut()); - - CVoicePacket *voicePacket2 = new CVoicePacket(pcmBytes2, 320); - voicePacket2->SetChannel(m_EncoderChannel2->GetChannelOut()); - // PID-preservation: push the input packet's PID into both // encoder channels' FIFOs so the matching pops in the USB // interface (when the AMBE responses arrive from hardware) @@ -874,15 +815,9 @@ void CStream::TaskImbeInput(void) m_EncoderChannel1->PushPid(uiPid); m_EncoderChannel2->PushPid(uiPid); - // Push to encoder channel 1 (AMBE+) - queue1 = m_EncoderChannel1->GetVoiceQueue(); - queue1->push(voicePacket1); - m_EncoderChannel1->ReleaseVoiceQueue(); - - // Push to encoder channel 2 (AMBE2+) - queue2 = m_EncoderChannel2->GetVoiceQueue(); - queue2->push(voicePacket2); - m_EncoderChannel2->ReleaseVoiceQueue(); + // Push to the encoder channels (AMBE+ and AMBE2+) + PushEncoderPcm(m_EncoderChannel1, m_uiCodecOut1, pcmBytes); + PushEncoderPcm(m_EncoderChannel2, m_uiCodecOut2, pcmBytes); } } diff --git a/ambed/cstream.h b/ambed/cstream.h index 4480bf8..f34424d 100644 --- a/ambed/cstream.h +++ b/ambed/cstream.h @@ -62,7 +62,7 @@ public: uint8 GetCodecOut3(void) const { return m_uiCodecOut3; } // activity timer - bool IsActive(void) const { return m_LastActivity.DurationSinceNow() <= STREAM_ACTIVITY_TIMEOUT; } + bool IsActive(void) const { return m_LastActivity.DurationSinceNow() <= m_iActivityTimeout; } // task static void Thread(CStream *); @@ -83,6 +83,9 @@ protected: // IMBE input handling void TaskImbeInput(void); + // Codec2 and IMBE input: PCM to the hardware encoders + void PushEncoderPcm(CVocodecChannel *, uint8 uiCodecOut, const uint8 *pcmBytes); + protected: // data uint16 m_uiId; @@ -98,8 +101,7 @@ protected: CVocodecChannel *m_EncoderChannel1; // AMBE+ encoder CVocodecChannel *m_EncoderChannel2; // AMBE2+ encoder CCodec2 *m_pCodec2Decoder; // Software Codec2 decoder - CSignalProcessor *m_pSignalProcessor1; // Gain for AMBE+ output - CSignalProcessor *m_pSignalProcessor2; // Gain for AMBE2+ output + CSignalProcessor *m_pSignalProcessor; // Decode gain, filter, AGC and encode gains imbe_vocoder *m_pImbeEncoder; // Software IMBE encoder for Codec2 input std::queue> m_ImbeQueue; // Queue for IMBE data in Codec2 input mode @@ -108,15 +110,13 @@ protected: CCodec2 *m_pCodec2Encoder; // Software Codec2 encoder for IMBE input std::queue> m_Codec2Queue; // Queue for Codec2 data in IMBE input mode - // Precomputed gain multipliers (avoid pow() per packet) - float m_fCodec2DecodeGain; // Codec2 decode output gain (Codec2 input mode) - float m_fImbeGain; // IMBE encode/decode gain - float m_fCodec2Gain; // Codec2 encode gain (IMBE input mode) - // Atomic counters for software queue sizes (for thread-safe drain checks in Close()) std::atomic m_nImbeQueueSize; std::atomic m_nCodec2QueueSize; + // activity timeout, in seconds + int m_iActivityTimeout; + // client details CCallsign m_Callsign; CIp m_Ip; diff --git a/ambed/cudpsocket.cpp b/ambed/cudpsocket.cpp index dcafd36..68eed1e 100644 --- a/ambed/cudpsocket.cpp +++ b/ambed/cudpsocket.cpp @@ -26,6 +26,7 @@ #include #include #include "cudpsocket.h" +#include "cconfig.h" //////////////////////////////////////////////////////////////////////////////////////// @@ -173,64 +174,64 @@ int CUdpSocket::Send(const char *Buffer, const CIp &Ip, uint16 destport) //////////////////////////////////////////////////////////////////////////////////////// // write - voice packets with DSCP marking -#if (DSCP_MARKING_ENABLE == 1) -static bool g_bDscpLogged = false; +static void SetTos(int socket, int tos) +{ + setsockopt(socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); +} int CUdpSocket::SendVoice(const CBuffer &Buffer, const CIp &Ip) { - if ( DSCP_VALUE >= 0 && DSCP_VALUE <= 63 ) + int tos = g_Config.GetVoiceTos(); + if ( tos < 0 ) { - int tos = DSCP_VALUE << 2; - setsockopt(m_Socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); + return Send(Buffer, Ip); } + SetTos(m_Socket, tos); + CIp temp(Ip); int result = (int)::sendto(m_Socket, (void *)Buffer.data(), Buffer.size(), 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); // Reset TOS for non-voice packets - int tos = 0; - setsockopt(m_Socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); + SetTos(m_Socket, 0); return result; } int CUdpSocket::SendVoice(const CBuffer &Buffer, const CIp &Ip, uint16 destport) { - if ( DSCP_VALUE >= 0 && DSCP_VALUE <= 63 ) + int tos = g_Config.GetVoiceTos(); + if ( tos < 0 ) { - int tos = DSCP_VALUE << 2; - setsockopt(m_Socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); + return Send(Buffer, Ip, destport); } + SetTos(m_Socket, tos); + CIp temp(Ip); temp.GetSockAddr()->sin_port = htons(destport); int result = (int)::sendto(m_Socket, - (void *)Buffer.data(), Buffer.size(), - 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); + (void *)Buffer.data(), Buffer.size(), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); // Reset TOS for non-voice packets - int tos = 0; - setsockopt(m_Socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); + SetTos(m_Socket, 0); return result; } void CUdpSocket::LogDscpStatus(void) { - if ( !g_bDscpLogged ) + int tos = g_Config.GetVoiceTos(); + if ( tos < 0 ) { - if ( DSCP_VALUE >= 0 && DSCP_VALUE <= 63 ) - { - std::cout << "Voice packets marked as DSCP " << DSCP_VALUE << std::endl; - } - else - { - std::cout << "Error: Invalid DSCP_VALUE " << DSCP_VALUE << " (must be 0-63), QoS disabled" << std::endl; - } - g_bDscpLogged = true; + std::cout << "Voice packets not DSCP marked" << std::endl; + } + else + { + std::cout << "Voice packets marked as DSCP " << (tos >> 2) << std::endl; } } -#endif diff --git a/ambed/cudpsocket.h b/ambed/cudpsocket.h index fbb9457..eba1320 100644 --- a/ambed/cudpsocket.h +++ b/ambed/cudpsocket.h @@ -70,16 +70,9 @@ public: int Send(const char *, const CIp &, uint16); // write - voice packets with DSCP marking -#if (DSCP_MARKING_ENABLE == 1) int SendVoice(const CBuffer &, const CIp &); int SendVoice(const CBuffer &, const CIp &, uint16); static void LogDscpStatus(void); -#else - // When DSCP disabled, SendVoice is just an alias for Send - int SendVoice(const CBuffer &Buffer, const CIp &Ip) { return Send(Buffer, Ip); } - int SendVoice(const CBuffer &Buffer, const CIp &Ip, uint16 port) { return Send(Buffer, Ip, port); } - static void LogDscpStatus(void) {} -#endif protected: // data diff --git a/ambed/cvocodecchannel.cpp b/ambed/cvocodecchannel.cpp index 313bf8f..8f078f6 100644 --- a/ambed/cvocodecchannel.cpp +++ b/ambed/cvocodecchannel.cpp @@ -31,15 +31,14 @@ //////////////////////////////////////////////////////////////////////////////////////// // constructor -CVocodecChannel::CVocodecChannel(CVocodecInterface *InterfaceIn, int iChIn, CVocodecInterface *InterfaceOut, int iChOut, int iSpeechGain) +CVocodecChannel::CVocodecChannel(CVocodecInterface *InterfaceIn, int iChIn, CVocodecInterface *InterfaceOut, int iChOut) { m_bOpen = false; m_InterfaceIn = InterfaceIn; m_iChannelIn = iChIn; m_InterfaceOut = InterfaceOut; m_iChannelOut = iChOut; - m_iSpeechGain = iSpeechGain; - m_signalProcessor = new CSignalProcessor((float)m_iSpeechGain); + m_signalProcessor = NULL; // Codec2 encoder starts disabled, enabled per-stream as needed m_bCodec2Enabled = false; @@ -109,6 +108,12 @@ bool CVocodecChannel::Open(void) m_bOpen = true; ok = true; PurgeAllQueues(); + { + // Each stream starts clean, with the current ambed.ini values + std::lock_guard lock(m_SignalMutex); + delete m_signalProcessor; + m_signalProcessor = new CSignalProcessor(GetCodecIn()); + } std::cout << "Vocodec channel " << m_InterfaceIn->GetName() << ":" << m_InterfaceIn->GetSerial() << ":" << (int)m_iChannelIn << " -> " << m_InterfaceOut->GetName() << ":" << m_InterfaceOut->GetSerial() << ":" << (int)m_iChannelOut << " open" << std::endl; @@ -122,6 +127,11 @@ void CVocodecChannel::Close(void) { m_bOpen = false; PurgeAllQueues(); + { + std::lock_guard lock(m_SignalMutex); + delete m_signalProcessor; + m_signalProcessor = NULL; + } std::cout << "Vocodec channel " << m_InterfaceIn->GetName() << ":" << m_InterfaceIn->GetSerial() << ":" << (int)m_iChannelIn << " -> " << m_InterfaceOut->GetName() << ":" << m_InterfaceOut->GetSerial() << ":" << (int)m_iChannelOut << " closed" << std::endl; @@ -146,64 +156,77 @@ uint8 CVocodecChannel::GetCodecOut(void) const void CVocodecChannel::ProcessSignal(CVoicePacket& voicePacket) { - m_signalProcessor->Process(voicePacket.GetVoice(), voicePacket.GetVoiceSize()); + std::lock_guard signalLock(m_SignalMutex); + if (m_signalProcessor == NULL) + { + return; + } + + uint8 *rawVoice = voicePacket.GetVoice(); + int voiceSize = voicePacket.GetVoiceSize(); + m_signalProcessor->Process(rawVoice, voiceSize); // Codec2 encoding runs in a separate thread to avoid blocking the hardware interface. // Here we just queue the PCM data for async encoding. - if (m_bCodec2Enabled && m_pCodec2Thread != NULL) + if (m_bCodec2Enabled && m_pCodec2Thread != NULL && voiceSize >= 320) // 160 samples * 2 bytes { - int voiceSize = voicePacket.GetVoiceSize(); + std::vector audio = OutputPcm(CODEC_CODEC2, rawVoice); - if (voiceSize >= 320) // 160 samples * 2 bytes + // Push to PCM queue and notify encoder thread (drop oldest if full) { - // Convert big-endian PCM to little-endian and queue for async encoding - uint8 *rawVoice = voicePacket.GetVoice(); - std::vector audio(160); - for (int i = 0; i < 160; i++) - { - audio[i] = (int16_t)((rawVoice[i*2] << 8) | rawVoice[i*2 + 1]); - } - - // Push to PCM queue and notify encoder thread (drop oldest if full) + std::lock_guard lock(m_Codec2PcmMutex); + if ( m_Codec2PcmQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) { - std::lock_guard lock(m_Codec2PcmMutex); - if ( m_Codec2PcmQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) - { - m_Codec2PcmQueue.pop(); - } - m_Codec2PcmQueue.push(audio); + m_Codec2PcmQueue.pop(); } - m_Codec2PcmCondition.notify_one(); + m_Codec2PcmQueue.push(audio); } + m_Codec2PcmCondition.notify_one(); } // IMBE encoding runs in a separate thread to avoid blocking the hardware interface. // Here we just queue the PCM data for async encoding. - if (m_bImbeEnabled && m_pImbeThread != NULL) + if (m_bImbeEnabled && m_pImbeThread != NULL && voiceSize >= 320) // 160 samples * 2 bytes { - int voiceSize = voicePacket.GetVoiceSize(); + std::vector audio = OutputPcm(CODEC_IMBE, rawVoice); - if (voiceSize >= 320) // 160 samples * 2 bytes + // Push to PCM queue and notify encoder thread (drop oldest if full) { - // Convert big-endian PCM to little-endian and queue for async encoding - uint8 *rawVoice = voicePacket.GetVoice(); - std::vector audio(160); - for (int i = 0; i < 160; i++) - { - audio[i] = (int16_t)((rawVoice[i*2] << 8) | rawVoice[i*2 + 1]); - } - - // Push to PCM queue and notify encoder thread (drop oldest if full) + std::lock_guard lock(m_ImbePcmMutex); + if ( m_ImbePcmQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) { - std::lock_guard lock(m_ImbePcmMutex); - if ( m_ImbePcmQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) - { - m_ImbePcmQueue.pop(); - } - m_ImbePcmQueue.push(audio); + m_ImbePcmQueue.pop(); } - m_ImbePcmCondition.notify_one(); + m_ImbePcmQueue.push(audio); } + m_ImbePcmCondition.notify_one(); + } + + // The software encoders above have their copies, the packet goes on to the hardware encoder + m_signalProcessor->ProcessOutput(GetCodecOut(), rawVoice, voiceSize); +} + +// A copy of the frame at the level for this codec, big-endian PCM to native samples +std::vector CVocodecChannel::OutputPcm(uint8 uiCodecOut, const uint8 *voice) +{ + uint8 copy[320]; + ::memcpy(copy, voice, sizeof(copy)); + m_signalProcessor->ProcessOutput(uiCodecOut, copy, sizeof(copy)); + + std::vector audio(160); + for (int i = 0; i < 160; i++) + { + audio[i] = (int16_t)((copy[i*2] << 8) | copy[i*2 + 1]); + } + return audio; +} + +void CVocodecChannel::ReportSignal(uint16 uiStreamId, const std::string& callsign) +{ + std::lock_guard lock(m_SignalMutex); + if (m_signalProcessor != NULL) + { + m_signalProcessor->Report(uiStreamId, callsign); } } @@ -466,16 +489,6 @@ void CVocodecChannel::ImbeEncoderTask(void) // Encode PCM to IMBE (outside the lock) if (!pcmData.empty() && m_pImbe != NULL) { - // Apply IMBE encode gain to PCM before encoding - static const float imbeEncodeGain = pow(10.0f, IMBE_ENCODE_GAIN / 20.0f); - for ( size_t i = 0; i < pcmData.size(); i++ ) - { - int32_t sample = (int32_t)(pcmData[i] * imbeEncodeGain); - if ( sample > 32767 ) sample = 32767; - if ( sample < -32768 ) sample = -32768; - pcmData[i] = (int16_t)sample; - } - uint8 imbe[IMBE_FRAME_SIZE]; m_pImbe->encode_4400(pcmData.data(), imbe); diff --git a/ambed/cvocodecchannel.h b/ambed/cvocodecchannel.h index 6cc4157..aa244ab 100644 --- a/ambed/cvocodecchannel.h +++ b/ambed/cvocodecchannel.h @@ -66,7 +66,7 @@ class CVocodecChannel { public: // constructors - CVocodecChannel(CVocodecInterface *, int, CVocodecInterface *, int, int); + CVocodecChannel(CVocodecInterface *, int, CVocodecInterface *, int); // destructor virtual ~CVocodecChannel(); @@ -81,10 +81,10 @@ public: uint8 GetCodecOut(void) const; int GetChannelIn(void) const { return m_iChannelIn; } int GetChannelOut(void) const { return m_iChannelOut; } - int GetSpeechGain(void) const { return m_iSpeechGain; } //Processing void ProcessSignal(CVoicePacket& voicePacket); + void ReportSignal(uint16 uiStreamId, const std::string& callsign); // interfaces bool IsInterfaceIn(const CVocodecInterface *interface) { return (interface == m_InterfaceIn); } @@ -223,8 +223,13 @@ protected: std::atomic m_PidFifoOrphanDrops; std::atomic m_PidFifoOverflowDrops; - // settings - int m_iSpeechGain; + // signal processing, rebuilt for each stream. Open and Close run on + // the stream's thread, ProcessSignal on the USB interface thread. + CSignalProcessor *m_signalProcessor; + std::mutex m_SignalMutex; + + // a copy of a processed frame at the level for this codec + std::vector OutputPcm(uint8 uiCodecOut, const uint8 *voice); // Codec2 encoding (software) - runs in separate thread to avoid blocking hardware std::atomic m_bCodec2Enabled; @@ -257,7 +262,6 @@ protected: void ImbeEncoderTask(void); private: - CSignalProcessor* m_signalProcessor; }; //////////////////////////////////////////////////////////////////////////////////////// diff --git a/ambed/main.cpp b/ambed/main.cpp index 54c97f0..40674d9 100644 --- a/ambed/main.cpp +++ b/ambed/main.cpp @@ -26,6 +26,7 @@ #include "ctimepoint.h" #include "cambeserver.h" #include "cudpsocket.h" +#include "cconfig.h" #include "syslog.h" #include @@ -86,17 +87,24 @@ int main(int argc, const char * argv[]) #endif - // check arguments - if ( argc != 2 ) + // check arguments, the listen IP used to be an argument and is now in ambed.ini + if ( argc > 2 || (argc == 2 && g_Config.IsValidIp(argv[1])) ) { - std::cout << "Usage: ambed ip" << std::endl; - std::cout << "example: ambed 192.168.178.212" << std::endl; + std::cout << "Usage: ambed [ambed.ini]" << std::endl; + std::cout << "example: ambed /ambed/ambed.ini" << std::endl; + std::cout << "The listen IP is now LISTEN_IP in ambed.ini" << std::endl; return 1; } - + + // load the settings, main.h defaults without an ambed.ini + if ( argc == 2 ) + { + g_Config.Load(argv[1]); + } + // initialize ambeserver - g_AmbeServer.SetListenIp(CIp(argv[1])); - + g_AmbeServer.SetListenIp(CIp(g_Config.GetListenIp().c_str())); + // and let it run std::cout << "Starting AMBEd " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_REVISION << std::endl << std::endl; if ( !g_AmbeServer.Start() ) @@ -104,7 +112,7 @@ int main(int argc, const char * argv[]) std::cout << "Error starting AMBEd" << std::endl; exit(EXIT_FAILURE); } - std::cout << "AMBEd started and listening on " << g_AmbeServer.GetListenIp() << std::endl; + std::cout << "AMBEd started and listening on " << g_AmbeServer.GetListenIp() << ":" << g_Config.GetListenPort() << std::endl; // Log DSCP status once at startup CUdpSocket::LogDscpStatus(); @@ -113,6 +121,7 @@ int main(int argc, const char * argv[]) // (destructors of static objects run on exit) for (;;) { - CTimePoint::TaskSleepFor(60000); + CTimePoint::TaskSleepFor(CONFIG_RELOAD_PERIOD * 1000); + g_Config.Reload(); } } diff --git a/ambed/main.h b/ambed/main.h index ef1fd3c..bf7bd13 100644 --- a/ambed/main.h +++ b/ambed/main.h @@ -48,14 +48,18 @@ // version ----------------------------------------------------- #define VERSION_MAJOR 1 -#define VERSION_MINOR 4 +#define VERSION_MINOR 5 #define VERSION_REVISION 0 // global ------------------------------------------------------ //#define RUN_AS_DAEMON //#define DEBUG_DUMPFILE -// QoS - set DSCP/TOS on outgoing packets for network prioritization +// Network, also overridden by ambed.ini +#define LISTEN_IP "127.0.0.1" // IP to bind to +#define LISTEN_PORT 10100 // UDP port, xlxd's TRANSCODER_PORT must match + +// QoS - set DSCP/TOS on outgoing packets for network prioritization, also overridden by ambed.ini // DSCP values: 0-63 (6 bits). Common choices for voice: // 46 (EF) - Expedited Forwarding, highest priority voice // 34 (AF41)- Assured Forwarding class 4, high priority @@ -64,51 +68,56 @@ #define DSCP_MARKING_ENABLE 1 // 1 = enable, 0 = disable #define DSCP_VALUE 46 // DSCP value (0-63) -// Transcoder server -------------------------------------------- -#define TRANSCODER_PORT 10100 // UDP port - // Codecs ------------------------------------------------------- #define CODEC_NONE 0 #define CODEC_AMBEPLUS 1 #define CODEC_AMBE2PLUS 2 #define CODEC_CODEC2 3 #define CODEC_IMBE 4 +#define NB_OF_CODECS 5 // CODEC_NONE to CODEC_IMBE // Frame sizes -------------------------------------------------- #define AMBE_FRAME_SIZE 9 #define CODEC2_FRAME_SIZE 8 #define IMBE_FRAME_SIZE 11 -// Transcoding speech gains (hardware vocodec channels: AMBE decode -> PCM -> AMBE encode) -#define CODECGAIN_AMBEPLUS -10 // in dB (D-Star) -#define CODECGAIN_AMBE2PLUS +10 // in dB (DMR) - -// IMBE transcoding gains (software IMBE decode -> PCM -> hardware AMBE encode / software Codec2 encode) -#define IMBE_DECODE_GAIN +18 // in dB - IMBE library outputs very quiet PCM -#define IMBE_TO_AMBEPLUS_GAIN +0 // in dB - additional gain for D-Star encode -#define IMBE_TO_AMBE2PLUS_GAIN -13 // in dB - attenuation for DMR encode -#define IMBE_TO_CODEC2_GAIN -7 // in dB - gain for M17 encode - -// Codec2 transcoding gains (software Codec2 decode -> PCM -> hardware AMBE encode / software IMBE encode) -#define CODEC2_DECODE_GAIN +6 // in dB - if Codec2 library needs gain adjustment -#define CODEC2_TO_AMBEPLUS_GAIN -3 // in dB - gain for D-Star encode -#define CODEC2_TO_AMBE2PLUS_GAIN -13 // in dB - gain for DMR encode -#define CODEC2_TO_IMBE_GAIN -13 // in dB - gain for P25 encode - -// IMBE encode gain (applied to PCM from hardware vocoder -> IMBE software encode) -// Note: Codec2 -> IMBE path in cstream.cpp uses CODEC2_TO_IMBE_GAIN separately -#define IMBE_ENCODE_GAIN -4 // in dB - -// Transcoding Tweaks -#define USE_AGC 1 // 1=AGC, 0=fixed gain -#define AGC_CLAMPING 3 // clamps the AGC gain to +- this value in dB -#define USE_BANDPASSFILTER 1 // bandpass filter on PCM (decode path) +// Transcoding gains, in dB. These are the defaults, ambed.ini overrides them at runtime. +// Every path is: decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode +#define DSTAR_TO_PCM -10.0f // D-Star (AMBE+) decode +#define DMR_TO_PCM -1.5f // DMR, YSF and NXDN (AMBE2+) decode +#define M17_TO_PCM -10.75f // M17 (Codec2) decode +#define P25_TO_PCM -3.75f // P25 (IMBE) decode +#define PCM_TO_DSTAR +11.5f // D-Star (AMBE+) encode +#define PCM_TO_DMR 0.0f // DMR, YSF and NXDN (AMBE2+) encode +#define PCM_TO_M17 +5.25f // M17 (Codec2) encode +#define PCM_TO_P25 +0.75f // P25 (IMBE) encode + +// AGC, also overridden by ambed.ini. It levels each speaker: fast down, hold +// through gaps, then up, faster the further a station is below the target +#define USE_AGC 1 // 1=AGC, 0=no AGC +#define AGC_TARGET -41.0f // speech peak level the AGC aims for, in dBFS +#define AGC_CLAMPING 9.0f // most the AGC can move the gain either way in dB, 0=off +#define AGC_ATTACK 150.0f // in ms, how fast the gain comes down +#define AGC_HANG 1000.0f // in ms, how long the gain holds before it can rise +#define AGC_RECOVERY 2.0f // in dB/s for each dB below the target, how fast the gain rises +#define AGC_RECOVERY_MIN 3.0f // in dB/s, slowest rise +#define AGC_RECOVERY_MAX 20.0f // in dB/s, fastest rise +#define AGC_GATE -60.0f // in dBFS, quieter frames don't move the gain +#define AGC_CEILING -1.0f // in dBFS, the limiter keeps the loudest encoder input below this, not in ambed.ini + +// Bandpass filter on PCM, also overridden by ambed.ini +#define USE_BANDPASSFILTER 1 // 1=on, 0=off + +// Tuning ------------------------------------------------------- +#define TUNING_LOG 1 // 1 = log levels when a stream closes, 0 = off, also overridden by ambed.ini +#define CONFIG_RELOAD_PERIOD 180 // in seconds, how often ambed.ini is checked +#define TUNING_SILENCE_LEVEL -55.0f // in dBFS, decoded frames below this aren't voice // Software queue depth limit - prevents unbounded growth if hardware stalls // At 50 frames/sec, 50 = 1 second of buffering #define SOFTWARE_QUEUE_MAX_DEPTH 50 -// Timeouts ----------------------------------------------------- +// Timeouts, also overridden by ambed.ini ------------------------ #define STREAM_ACTIVITY_TIMEOUT 3 // in seconds @@ -156,16 +165,12 @@ disp(hh); grid */ -#if USE_BANDPASSFILTER == 1 - const float FILTER_TAPS[] { -0.05063341f, -0.00060337f, -0.08892498f, -0.02026701f, -0.05940750f, -0.10977641f, 0.03244024f, -0.22304499f, 0.11452865f, 0.72500000f, 0.11452865f, -0.22304499f, 0.03244024f, -0.10977641f, -0.05940750f, -0.02026701f, -0.08892498f, -0.00060337f, -0.05063341f }; #define FILTER_TAPS_LENGTH 19 -#endif - //////////////////////////////////////////////////////////////////////////////////////// // global objects @@ -175,6 +180,9 @@ extern CAmbeServer g_AmbeServer; class CVocodecs; extern CVocodecs g_Vocodecs; +class CConfig; +extern CConfig g_Config; + //////////////////////////////////////////////////////////////////////////////////////// #endif /* main_h */ diff --git a/ambed/makefile b/ambed/makefile index 31e8fd1..ca237be 100644 --- a/ambed/makefile +++ b/ambed/makefile @@ -30,3 +30,4 @@ install: mkdir -p /ambed cp $(EXECUTABLE) /ambed/ cp ./run /ambed/ + test -f /ambed/ambed.ini || cp ./ambed.ini /ambed/ diff --git a/ambed/readme b/ambed/readme deleted file mode 100644 index 32c8798..0000000 --- a/ambed/readme +++ /dev/null @@ -1,197 +0,0 @@ -// -// readme -// ambed -// -// Created by Jean-Luc Deltombe (LX3JL) on 09/07/2017. -// Copyright 2017-2025 Jean-Luc Deltombe (LX3JL). All rights reserved. -// -// ---------------------------------------------------------------------------- -// This file is part of ambed. -// -// xlxd is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// xlxd is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Foobar. If not, see . -// ---------------------------------------------------------------------------- - -VERSION: 1.4.0 - -Overview -======== -ambed is a multi-mode digital voice transcoder daemon that bridges between -different amateur radio digital voice protocols. It uses DVSI hardware -vocoders for AMBE+/AMBE2+ and software vocoders for Codec2 (M17) and -IMBE (P25). - - -Supported Codecs -================ -- AMBE+ (D-Star) - hardware DVSI vocoder -- AMBE2+ (DMR/YSF/NXDN) - hardware DVSI vocoder -- Codec2 (M17) - software vocoder (3200bps mode) -- IMBE (P25) - software vocoder - - -Hardware Compatibility -====================== -This version of ambed is compatible with: -- DF2ET's AMBE3003USB opensource device (https://github.com/phl0/AMBE3003USB) -- LX3JL's USB-3006 opensource device (https://github.com/lx3jl/usb-3006) -- DVSI's USB-3000 device -- DVSI's USB-3003 device -- DVSI's USB-3012 device -- NWDR's ThumbDV device -- NWDR's ThumbDV-3 device -- DVMEGA AMBE3000 device -- DVMEGA AMBE3003 device - -Available transcoding channels per device: - -Device Hardware Transcoding Software Vocoders - Channels Channels (IMBE/Codec2) --------------------------------------------------------------------- -3000 (pair) 2 2 1 each -3003 (single) 3 2 1 each -3003 (pair) 6 6 3 each -3003+3000 (pair) 4 4 2 each -3006 6 6 3 each -3012 12 12 6 each - -Notes: -- USB-3000 devices must be used in pairs or paired with a USB-3003 -- Multiple devices can be used simultaneously -- Avoid USB hubs as they may cause unreliable behaviour -- Max concurrent streams is calculated automatically from hardware -- Software vocoders (Codec2/IMBE) use 2 hardware channels per stream - - -Configuration Options (main.h) -============================== - -QoS/DSCP Marking: - DSCP_MARKING_ENABLE 1 = enable, 0 = disable - DSCP_VALUE DSCP value 0-63 (default: 46/EF for voice) - -Audio Processing: - USE_AGC 1 = AGC enabled, 0 = fixed gain - AGC_CLAMPING AGC gain limit in dB (default: 3) - USE_BANDPASSFILTER 1 = 300-3400Hz bandpass filter enabled - -Transcoding Gains (hardware AMBE<->AMBE): - CODECGAIN_AMBEPLUS D-Star decode/encode gain (default: -10dB) - CODECGAIN_AMBE2PLUS DMR decode/encode gain (default: +10dB) - -IMBE Transcoding Gains (P25 input): - IMBE_DECODE_GAIN IMBE decoder output gain (default: +18dB) - IMBE_TO_AMBEPLUS_GAIN Additional gain for D-Star output (default: 0dB) - IMBE_TO_AMBE2PLUS_GAIN Additional gain for DMR output (default: -13dB) - IMBE_TO_CODEC2_GAIN Gain for M17 output (default: -7dB) - -Codec2 Transcoding Gains (M17 input): - CODEC2_DECODE_GAIN Codec2 decoder output gain (default: +6dB) - CODEC2_TO_AMBEPLUS_GAIN Gain for D-Star output (default: 0dB) - CODEC2_TO_AMBE2PLUS_GAIN Gain for DMR output (default: -16dB) - CODEC2_TO_IMBE_GAIN Gain for P25 output (default: -8dB) - -Timeouts: - STREAM_ACTIVITY_TIMEOUT Stream inactivity timeout in seconds (default: 3) - - -Installation -============ - -1) Install FTDI drivers - -Download from FTDI web site the latest D2XX driver package (tested on 1.4.6). -Follow FTDI provided documentation for installation and testing of the drivers. - - -2) Install build tools - -# apt-get install build-essential -# apt-get install g++ - - -3) Download and compile ambed - -# git clone https://github.com/LX3JL/xlxd.git -# cd xlxd/ambed/ -# make clean -# make -# make install - - -4) Configure ambed startup script - -# nano /ambed/run - -Edit the following line to match your IP: - -sudo /ambed/ambed 127.0.0.1 & - -If ambed is running on the same machine as xlxd, use 127.0.0.1 -Otherwise use the machine's own IP address. - - -5) Running ambed - -Note: -Due to specific FTDI driver implementation, ambed must run with root -privileges and cannot be run as a daemon. ambed will display information -and error messages in the terminal from which it was started. - -Plug in at least one USB-3xxx device, then: - -# cd /ambed -# ./run - -During initialisation, ambed will scan all USB ports to discover, -configure and report the status of all available USB-3xxx devices. - -Example startup output: - Starting AMBEd 1.4.0 - Codec interfaces initialized successfully : 6 channels available - Software vocoders : 3 IMBE (P25), 3 Codec2 (M17) - Max concurrent streams: 3 (from 6 vocoder channels) - Voice packets marked as DSCP 46 - AMBEd started and listening on 127.0.0.1 - - -6) Stopping ambed - -Find the PID of ambed process: - -# ps ax | grep ambed - -And kill the process: - -# kill xxxx - -Where xxxx is the PID found previously. - - -Transcoding Paths -================= - -Hardware (DVSI) paths: - D-Star (AMBE+) <-> DMR/YSF/NXDN (AMBE2+) - -Software codec paths: - M17 (Codec2) -> D-Star (AMBE+) - M17 (Codec2) -> DMR/YSF/NXDN (AMBE2+) - M17 (Codec2) -> P25 (IMBE) - P25 (IMBE) -> D-Star (AMBE+) - P25 (IMBE) -> DMR/YSF/NXDN (AMBE2+) - P25 (IMBE) -> M17 (Codec2) - -Note: M17 and P25 input modes use software decoders paired with -hardware encoders. Each stream uses 2 hardware channels. - diff --git a/ambed/run b/ambed/run index b1d2fe0..5122df1 100644 --- a/ambed/run +++ b/ambed/run @@ -3,4 +3,4 @@ sudo rmmod ftdi_sio sudo rmmod usbserial -sudo /ambed/ambed 127.0.0.1 & \ No newline at end of file +sudo /ambed/ambed /ambed/ambed.ini & \ No newline at end of file diff --git a/scripts/ambed.service b/scripts/ambed.service index 8332fae..34e4e96 100644 --- a/scripts/ambed.service +++ b/scripts/ambed.service @@ -8,7 +8,7 @@ User=root Group=root ExecStartPre=-/sbin/rmmod ftdi_sio ExecStartPre=-/sbin/rmmod usb_serial -ExecStart=/ambed/ambed 127.0.0.1 +ExecStart=/ambed/ambed /ambed/ambed.ini Restart=on-abnormal [Install] From aebd22cf533d6cd7c9863c5fc9eb9c3fe48ad177 Mon Sep 17 00:00:00 2001 From: Andy Taylor Date: Wed, 11 Nov 2026 19:31:13 +0000 Subject: [PATCH 2/2] Upgrade XLXd to 2.6.2 M17: compute the stream packet CRC on outbound frames xlxd rebuilds every M17 stream packet it relays and wrote 0x0000 in the CRC field. Add the M17 CRC-16 (poly 0x5935, init 0xFFFF, no reflection, no final XOR) to CCRC and append it, big-endian, over bytes 0..51 of every voice, last-frame and synthetic EOT packet. M17: accept any unencrypted voice stream TYPE Inbound stream packets were accepted only when the low byte of TYPE was exactly 0x05, so a stream declaring GNSS or extended callsign META, or a non-zero CAN, had every packet dropped without a log line and the whole transmission was lost. Decode the full 16-bit TYPE and accept any stream whose data type is voice (Codec2 3200) with no encryption, whatever its META, CAN or signed bit. Unsupported streams (encrypted, voice+data, data, packet mode) are still dropped, now with one log line per stream. Signed streams carry their signature in the last four frames. xlxd re-encodes every stream, so the signature cannot be passed on: the three signature-only frames are dropped, the final frame is sent as Codec2 silence, and the stream goes out unsigned. M17: number inbound frames from the packet stream counter Inbound M17 frames took their packet ID from the M17 frame number (FN * 2, truncated to 8 bits). The D-Star side numbers frames modulo 21, and 256 is not a multiple of 21, so every 5.12 s D-Star listeners received a 4-frame superframe and an early sync frame, restarting the slow data. Leave the packet ID undefined, as other non-D-Star modes do, so the packet stream numbers frames from its own continuous counter. YSF: reassemble multi-frame Wires-X commands A Wires-X command can span several data frames (FN 1..FT). Each frame was decoded into a buffer local to the call, so the frames were never combined: the final frame was CRC-checked without the earlier frames' bytes, and a non-final frame was decoded as a whole command with no CRC check. Two-frame requests, such as the FT2D's ALL_REQ for Search/All, were dropped and the module list never appeared. Reassemble each command per source (IP:port) in a zeroed buffer, accepting frames only in sequence, with the same FT and no more than 1 s apart. A command is decoded once, on its final frame, after the end marker and CRC check, which now only looks at the bytes received. Frames 3 onwards use the 40-byte layout of G4KLX's YSFGateway; the previous 20-byte stride overwrote frame 2's data. xlxd.interlink: remove the REF030, XRF030 and DCS030 examples. --- config/xlxd.interlink | 3 - src/ccrc.cpp | 15 ++++ src/ccrc.h | 3 + src/cm17protocol.cpp | 203 ++++++++++++++++++++++++++++++++++-------- src/cm17protocol.h | 41 ++++++++- src/cysfprotocol.cpp | 140 ++++++++++++++++++++++------- src/cysfprotocol.h | 21 +++++ src/main.h | 2 +- 8 files changed, 355 insertions(+), 73 deletions(-) diff --git a/config/xlxd.interlink b/config/xlxd.interlink index 57f746e..6a3e215 100644 --- a/config/xlxd.interlink +++ b/config/xlxd.interlink @@ -76,7 +76,6 @@ # REF [:port] # examples: # REF001 ref001.example.com EA -# REF030 ref030.dstargateway.org:20001 AA # REF123 192.168.1.100 BC # # notes: @@ -96,7 +95,6 @@ # XRF [:port] # examples: # XRF001 xrf001.example.com EA -# XRF030 xrf030.dstargateway.org:30001 AA # XRF123 192.168.1.100 BC # # notes: @@ -116,7 +114,6 @@ # DCS [:port] # examples: # DCS001 dcs001.example.com EA -# DCS030 dcs030.xreflector.net:30051 AA # DCS123 192.168.1.100 BC # # notes: diff --git a/src/ccrc.cpp b/src/ccrc.cpp index a69ed8d..407b720 100644 --- a/src/ccrc.cpp +++ b/src/ccrc.cpp @@ -249,3 +249,18 @@ unsigned char CCRC::addCRC(const unsigned char* in, unsigned int length) return crc; } + +unsigned short CCRC::crcM17(const unsigned char* in, unsigned int length) +{ + assert(in != NULL); + + uint16_t crc = 0xFFFFU; + + for (unsigned int i = 0U; i < length; i++) { + crc ^= uint16_t(in[i]) << 8; + for (unsigned int j = 0U; j < 8U; j++) + crc = (crc & 0x8000U) ? uint16_t((crc << 1) ^ 0x5935U) : uint16_t(crc << 1); + } + + return crc; +} diff --git a/src/ccrc.h b/src/ccrc.h index 82730d4..91ca738 100644 --- a/src/ccrc.h +++ b/src/ccrc.h @@ -34,6 +34,9 @@ public: static unsigned char crc8(const unsigned char* in, unsigned int length); static unsigned char addCRC(const unsigned char* in, unsigned int length); + + // M17 CRC-16: poly 0x5935, init 0xFFFF, no reflection, no final XOR + static unsigned short crcM17(const unsigned char* in, unsigned int length); }; #endif diff --git a/src/cm17protocol.cpp b/src/cm17protocol.cpp index 2dbb196..6dee35c 100644 --- a/src/cm17protocol.cpp +++ b/src/cm17protocol.cpp @@ -28,6 +28,10 @@ #include "cm17protocol.h" #include "creflector.h" #include "cgatekeeper.h" +#include "ccrc.h" + +// Codec2 3200bps silence (encoded from 160 zero PCM samples) +static const uint8 M17_CODEC2_SILENCE[8] = { 0xC0, 0x00, 0x6A, 0x43, 0x9C, 0xE4, 0x21, 0x08 }; // Note: Software transcoding removed - M17 <-> AMBE transcoding will be // handled by ambed when Codec2 support is added there @@ -128,17 +132,31 @@ void CM17Protocol::RxTask(void) } } - uint8 m17seq = LastFrame->GetPacketId(); - // Multiply by 2 for 40ms->20ms conversion, mask to uint8 range - uint8 pid1 = (uint8)((m17seq * 2) & 0xFF); - uint8 pid2 = (uint8)((m17seq * 2 + 1) & 0xFF); + // Signed stream: the final frame carries signature bytes, not + // voice. Send silence instead (the signature frames before it + // were dropped). + if ( IsSignatureFrame(Buffer) ) + { + ::memcpy(codec2_frame1, M17_CODEC2_SILENCE, 8); + ::memcpy(codec2_frame2, M17_CODEC2_SILENCE, 8); + + CCallsign csSource; + DecodeCallsign(Buffer.data() + 12, &csSource); + char sid[8]; + ::snprintf(sid, sizeof(sid), "0x%04X", streamId); + std::cout << "M17 stream " << sid << " from " << csSource + << ": signature stripped" << std::endl; + } - // Create regular frame for first codec2 frame - CDvFramePacket *Frame1 = new CDvFramePacket(codec2_frame1, streamId, pid1); + // Create regular frame for first codec2 frame. Packet IDs are + // left undefined (0xFF): the packet stream numbers every frame + // from its own counter, so D-Star frame numbering (mod 21) + // stays continuous whatever the M17 frame number does. + CDvFramePacket *Frame1 = new CDvFramePacket(codec2_frame1, streamId, 0xFF); - // Update last frame with second codec2 frame and correct packet ID + // Update last frame with second codec2 frame delete LastFrame; - LastFrame = new CDvLastFramePacket(codec2_frame2, streamId, pid2); + LastFrame = new CDvLastFramePacket(codec2_frame2, streamId, 0xFF); // Process first frame as regular, then last frame closes stream OnDvFramePacketIn(Frame1, &Ip); @@ -173,6 +191,11 @@ void CM17Protocol::RxTask(void) delete Header; } } + else if ( IsSignatureFrame(Buffer) ) + { + // signed stream: drop the frames carrying the signature, xlxd + // re-encodes the stream so the signature can't be passed on + } else if ( IsValidDvFramePacket(Buffer, &Frame) ) { // check if this is from a listen-only client @@ -197,19 +220,17 @@ void CM17Protocol::RxTask(void) uint8 codec2_frame2[8]; ::memcpy(codec2_frame2, Buffer.data() + 36 + 8, 8); // second codec2 frame - // Create second frame packet with incremented packet ID - // Multiply by 2 for 40ms->20ms conversion, mask to uint8 range - CDvFramePacket *Frame2 = new CDvFramePacket(codec2_frame2, Frame->GetStreamId(), - (uint8)(((Frame->GetPacketId() * 2) + 1) & 0xFF)); + // Rebuild both frames with packet IDs left undefined (0xFF): + // the packet stream numbers every frame from its own counter, + // so D-Star frame numbering (mod 21) stays continuous whatever + // the M17 frame number does. + uint16 streamId = Frame->GetStreamId(); + CDvFramePacket *Frame2 = new CDvFramePacket(codec2_frame2, streamId, 0xFF); - // Update first frame's packet ID to be even (Frame1 = seq*2, Frame2 = seq*2+1) - // We need to recreate Frame with correct packet ID uint8 codec2_frame1[8]; ::memcpy(codec2_frame1, Buffer.data() + 36, 8); // first codec2 frame - uint16 streamId = Frame->GetStreamId(); - uint8 pid1 = (uint8)((Frame->GetPacketId() * 2) & 0xFF); delete Frame; - Frame = new CDvFramePacket(codec2_frame1, streamId, pid1); + Frame = new CDvFramePacket(codec2_frame1, streamId, 0xFF); // Process both frames OnDvFramePacketIn(Frame, &Ip); @@ -298,6 +319,10 @@ void CM17Protocol::RxTask(void) } g_Reflector.ReleaseClients(); } + else if ( IsStreamPacket(Buffer) && !IsSupportedVoiceType(GetStreamType(Buffer)) ) + { + LogUnsupportedStream(Buffer, Ip); + } } // handle end of streaming timeout @@ -576,8 +601,8 @@ void CM17Protocol::SendSyntheticEOT(int iModId) buffer.Append((uint8 *)CODEC2_SILENCE, 8); buffer.Append((uint8 *)CODEC2_SILENCE, 8); - buffer.Append((uint8)0); - buffer.Append((uint8)0); + // CRC over bytes 0..51 + AppendCrc(&buffer); std::cout << "M17 synthetic EOT sent for module " << (char)('A' + iModId) << " sid " << streamId << std::endl; @@ -925,10 +950,8 @@ bool CM17Protocol::IsValidDvHeaderPacket(const CBuffer &Buffer, CDvHeaderPacket if ( (Buffer.size() == 54) && (Buffer.Compare((uint8 *)"M17 ", 4) == 0) ) { - // check frame type - uint8 frameType = Buffer.data()[19]; - - if ( frameType == M17_FRAMETYPE_VOICE ) + // stream, voice 3200, no encryption (any META, CAN or signed bit) + if ( IsSupportedVoiceType(GetStreamType(Buffer)) ) { // get sequence number with EOT flag uint16 sequenceWithEOT = MAKEWORD(Buffer.data()[35], Buffer.data()[34]); @@ -980,10 +1003,8 @@ bool CM17Protocol::IsValidDvFramePacket(const CBuffer &Buffer, CDvFramePacket ** if ( (Buffer.size() == 54) && (Buffer.Compare((uint8 *)"M17 ", 4) == 0) ) { - // check frame type - uint8 frameType = Buffer.data()[19]; - - if ( frameType == M17_FRAMETYPE_VOICE ) + // stream, voice 3200, no encryption (any META, CAN or signed bit) + if ( IsSupportedVoiceType(GetStreamType(Buffer)) ) { // get sequence number with EOT flag uint16 sequenceWithEOT = MAKEWORD(Buffer.data()[35], Buffer.data()[34]); @@ -1016,10 +1037,8 @@ bool CM17Protocol::IsValidDvLastFramePacket(const CBuffer &Buffer, CDvLastFrameP if ( (Buffer.size() == 54) && (Buffer.Compare((uint8 *)"M17 ", 4) == 0) ) { - // check frame type - uint8 frameType = Buffer.data()[19]; - - if ( frameType == M17_FRAMETYPE_VOICE ) + // stream, voice 3200, no encryption (any META, CAN or signed bit) + if ( IsSupportedVoiceType(GetStreamType(Buffer)) ) { // get stream ID uint16 streamId = MAKEWORD(Buffer.data()[5], Buffer.data()[4]); @@ -1045,6 +1064,109 @@ bool CM17Protocol::IsValidDvLastFramePacket(const CBuffer &Buffer, CDvLastFrameP return valid; } +//////////////////////////////////////////////////////////////////////////////////////// +// stream packet TYPE helpers + +bool CM17Protocol::IsStreamPacket(const CBuffer &Buffer) const +{ + return (Buffer.size() == 54) && (Buffer.Compare((uint8 *)"M17 ", 4) == 0); +} + +uint16 CM17Protocol::GetStreamType(const CBuffer &Buffer) const +{ + return MAKEWORD(Buffer.data()[19], Buffer.data()[18]); +} + +uint16 CM17Protocol::GetFrameNumber(const CBuffer &Buffer) const +{ + return MAKEWORD(Buffer.data()[35], Buffer.data()[34]); +} + +// Stream mode, voice only (Codec2 3200), no encryption. The META content +// (text, GNSS, extended callsign), CAN and signed bit don't affect the voice. +bool CM17Protocol::IsSupportedVoiceType(uint16 type) const +{ + return (type & M17_TYPE_STREAM) && + ((type & M17_TYPE_DATA_MASK) == M17_TYPE_DATA_VOICE) && + ((type & M17_TYPE_ENCR_MASK) == 0); +} + +// One of the last four frames of a signed stream, which carry the +// signature instead of voice +bool CM17Protocol::IsSignatureFrame(const CBuffer &Buffer) const +{ + if ( !IsStreamPacket(Buffer) ) + return false; + + uint16 type = GetStreamType(Buffer); + return IsSupportedVoiceType(type) && (type & M17_TYPE_SIGNED) && + ((GetFrameNumber(Buffer) & 0x7FFF) >= M17_FN_SIGNATURE_FIRST); +} + +// Log a dropped stream with an unsupported TYPE, once per stream +void CM17Protocol::LogUnsupportedStream(const CBuffer &Buffer, const CIp &Ip) +{ + uint16 streamId = MAKEWORD(Buffer.data()[5], Buffer.data()[4]); + CM17RxStreamItem *rx = FindRxStream(streamId, Ip, true); + if ( rx->m_bRejectLogged ) + return; + rx->m_bRejectLogged = true; + + uint16 type = GetStreamType(Buffer); + const char *reason; + if ( !(type & M17_TYPE_STREAM) ) + reason = "packet mode"; + else if ( type & M17_TYPE_ENCR_MASK ) + reason = "encrypted"; + else if ( (type & M17_TYPE_DATA_MASK) == M17_TYPE_DATA_VOICEDATA ) + reason = "voice+data, Codec2 1600"; + else if ( (type & M17_TYPE_DATA_MASK) == M17_TYPE_DATA_DATA ) + reason = "data only"; + else + reason = "reserved data type"; + + CCallsign csSource; + DecodeCallsign(Buffer.data() + 12, &csSource); + char ids[32]; + ::snprintf(ids, sizeof(ids), "0x%04X", streamId); + char types[8]; + ::snprintf(types, sizeof(types), "0x%04X", type); + std::cout << "M17 stream " << ids << " from " << csSource << " at " << Ip + << " dropped: TYPE " << types << " (" << reason << ") not supported" << std::endl; +} + +// Find the inbound state for a stream, optionally creating it. Entries +// idle for more than 5 seconds are discarded first. +CM17RxStreamItem *CM17Protocol::FindRxStream(uint16 streamId, const CIp &Ip, bool create) +{ + for ( auto it = m_RxStreams.begin(); it != m_RxStreams.end(); ) + { + if ( it->m_LastSeen.DurationSinceNow() > 5.0 ) + it = m_RxStreams.erase(it); + else + ++it; + } + + for ( auto &rx : m_RxStreams ) + { + if ( (rx.m_uiStreamId == streamId) && (rx.m_Ip == Ip) ) + { + rx.m_LastSeen.Now(); + return ℞ + } + } + + if ( !create ) + return NULL; + + CM17RxStreamItem rx; + rx.m_uiStreamId = streamId; + rx.m_Ip = Ip; + rx.m_LastSeen.Now(); + m_RxStreams.push_back(rx); + return &m_RxStreams.back(); +} + //////////////////////////////////////////////////////////////////////////////////////// // packet encoding helpers @@ -1181,9 +1303,8 @@ bool CM17Protocol::EncodeDvFramePacket(const CDvFramePacket &Packet, uint16 stre Buffer->Append((uint8)0); } - // reserved (2 bytes) - Buffer->Append((uint8)0); - Buffer->Append((uint8)0); + // CRC over bytes 0..51 + AppendCrc(Buffer); // clear the pending flag m_StreamsCache[iModId].m_bHasPendingCodec2 = false; @@ -1266,9 +1387,8 @@ bool CM17Protocol::EncodeDvLastFramePacket(const CDvLastFramePacket &Packet, uin Buffer->Append(CODEC2_SILENCE, 8); } - // reserved (2 bytes) - Buffer->Append((uint8)0); - Buffer->Append((uint8)0); + // CRC over bytes 0..51 + AppendCrc(Buffer); // Reset the cache for next stream m_StreamsCache[iModId].m_bHasPendingCodec2 = false; @@ -1277,6 +1397,15 @@ bool CM17Protocol::EncodeDvLastFramePacket(const CDvLastFramePacket &Packet, uin return true; } +// Append the M17 CRC-16, big-endian, computed over everything already +// in the buffer (bytes 0..51 of a 54-byte stream packet, magic included). +void CM17Protocol::AppendCrc(CBuffer *Buffer) const +{ + uint16 crc = CCRC::crcM17(Buffer->data(), (unsigned int)Buffer->size()); + Buffer->Append((uint8)HIBYTE(crc)); + Buffer->Append((uint8)LOBYTE(crc)); +} + //////////////////////////////////////////////////////////////////////////////////////// // M17 callsign encoding/decoding helpers diff --git a/src/cm17protocol.h b/src/cm17protocol.h index 0e9d5fc..62d5f30 100644 --- a/src/cm17protocol.h +++ b/src/cm17protocol.h @@ -42,9 +42,21 @@ typedef uint64_t uint64; //////////////////////////////////////////////////////////////////////////////////////// // define -// M17 frame type +// M17 frame type (outbound: stream, voice 3200, no encryption, text META) #define M17_FRAMETYPE_VOICE 0x05 +// M17 stream LSF TYPE fields (16-bit, big-endian at bytes 18..19) +#define M17_TYPE_STREAM 0x0001 // packet/stream: 1 = stream +#define M17_TYPE_DATA_MASK 0x0006 // data type +#define M17_TYPE_DATA_DATA 0x0002 // data +#define M17_TYPE_DATA_VOICE 0x0004 // voice (Codec2 3200) +#define M17_TYPE_DATA_VOICEDATA 0x0006 // voice + data (Codec2 1600) +#define M17_TYPE_ENCR_MASK 0x0018 // encryption type: 0 = none +#define M17_TYPE_SIGNED 0x0800 // signed stream + +// M17 frame numbers that carry a stream signature (last four frames) +#define M17_FN_SIGNATURE_FIRST 0x7FFC + // M17 callsign encoding #define M17_CALLSIGN_ALPHABET " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-/." @@ -126,6 +138,18 @@ public: bool m_bInitialized; }; +// Per inbound stream state, touched by the RX thread only +class CM17RxStreamItem +{ +public: + CM17RxStreamItem() : m_uiStreamId(0), m_bRejectLogged(false) {} + + uint16 m_uiStreamId; + CIp m_Ip; + bool m_bRejectLogged; // unsupported TYPE already logged + CTimePoint m_LastSeen; +}; + class CM17Protocol : public CProtocol { public: @@ -170,6 +194,17 @@ protected: bool IsValidDvFramePacket(const CBuffer &, CDvFramePacket **); bool IsValidDvLastFramePacket(const CBuffer &, CDvLastFramePacket **); + // stream packet TYPE helpers + bool IsStreamPacket(const CBuffer &) const; + uint16 GetStreamType(const CBuffer &) const; + uint16 GetFrameNumber(const CBuffer &) const; + bool IsSupportedVoiceType(uint16) const; + bool IsSignatureFrame(const CBuffer &) const; + void LogUnsupportedStream(const CBuffer &, const CIp &); + + // inbound stream state (RX thread only) + CM17RxStreamItem *FindRxStream(uint16, const CIp &, bool); + // packet encoding helpers void EncodeConnectAckPacket(CBuffer *); void EncodeConnectNackPacket(CBuffer *); @@ -178,6 +213,7 @@ protected: void EncodePingPacket(CBuffer *); bool EncodeDvFramePacket(const CDvFramePacket &, uint16, CBuffer *); bool EncodeDvLastFramePacket(const CDvLastFramePacket &, uint16, CBuffer *); + void AppendCrc(CBuffer *) const; // M17 callsign encoding/decoding helpers void EncodeCallsign(const CCallsign &, uint8 *) const; @@ -198,6 +234,9 @@ protected: // active stream count — when 0, CheckForMissedEOT skips all mutex acquisitions std::atomic m_nActiveStreams; + + // inbound stream state (RX thread only, no lock) + std::vector m_RxStreams; }; //////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/cysfprotocol.cpp b/src/cysfprotocol.cpp index 6b91b41..40132b7 100644 --- a/src/cysfprotocol.cpp +++ b/src/cysfprotocol.cpp @@ -1310,6 +1310,46 @@ bool CYsfProtocol::EncodeDvLastPacket(const CDvHeaderPacket &Header, CBuffer *Bu //////////////////////////////////////////////////////////////////////////////////////// // Wires-X packet decoding helpers +// Reassembly state for a source (full IP:port). Entries idle for longer +// than the frame timeout are discarded first. +CYsfWiresxRxItem *CYsfProtocol::GetWiresxRx(const CIp &Ip, bool create) +{ + for ( auto it = m_WiresxRx.begin(); it != m_WiresxRx.end(); ) + { + if ( it->m_LastFrame.DurationSinceNow() > YSF_WIRESX_FRAME_TIMEOUT ) + it = m_WiresxRx.erase(it); + else + ++it; + } + + for ( auto &rx : m_WiresxRx ) + { + if ( rx.m_Ip == Ip ) + return ℞ + } + + if ( !create ) + return NULL; + + m_WiresxRx.emplace_back(); + CYsfWiresxRxItem &rx = m_WiresxRx.back(); + rx.m_Ip = Ip; + rx.m_LastFrame.Now(); + return ℞ +} + +void CYsfProtocol::ReleaseWiresxRx(const CIp &Ip) +{ + for ( auto it = m_WiresxRx.begin(); it != m_WiresxRx.end(); ++it ) + { + if ( it->m_Ip == Ip ) + { + m_WiresxRx.erase(it); + return; + } + } +} + bool CYsfProtocol::IsValidwirexPacket(const CBuffer &Buffer, const CIp &Ip, CYSFFICH *Fich, CCallsign *Callsign, int *Cmd, int *Arg) { uint8 tag[] = { 'Y','S','F','D' }; @@ -1317,7 +1357,7 @@ bool CYsfProtocol::IsValidwirexPacket(const CBuffer &Buffer, const CIp &Ip, CYSF uint8 CONN_REQ[] = {0x5DU, 0x23U, 0x5FU}; uint8 DISC_REQ[] = {0x5DU, 0x2AU, 0x5FU}; uint8 ALL_REQ[] = {0x5DU, 0x66U, 0x5FU}; - uint8 command[300]; + uint8 command[YSF_WIRESX_CMD_SIZE] = { 0 }; CYSFPayload payload; bool valid = false; @@ -1338,35 +1378,78 @@ bool CYsfProtocol::IsValidwirexPacket(const CBuffer &Buffer, const CIp &Ip, CYSF // get callsign Callsign->SetCallsign(&(Buffer.data()[4]), CALLSIGN_LEN, false); Callsign->SetModule(YSF_MODULE_ID); - // decode payload - if ( Fich->getFN() == 0U ) + // Decode the payload into this source's reassembly buffer. + // A command can span several frames; it is complete on the + // frame whose FN equals FT. Frame layout (as G4KLX + // YSFGateway): FN 1 carries command[0..19], FN n >= 2 + // carries 40 bytes at command[(n-2)*40+20]. FN 0 is the + // header frame and carries no command data. + unsigned int fn = Fich->getFN(); + unsigned int ft = Fich->getFT(); + CYsfWiresxRxItem *rx = (fn == 0U) ? NULL : GetWiresxRx(Ip, fn == 1U); + if ( rx == NULL ) { valid = false; } - else if ( Fich->getFN() == 1U ) + else if ( fn == 1U ) + { + // first frame: start a fresh command + ::memset(rx->m_Command, 0, sizeof(rx->m_Command)); + rx->m_uiFT = (uint8)ft; + valid &= payload.readDataFRModeData2(&(Buffer.data()[35]), rx->m_Command + 0U); + } + else if ( (ft != rx->m_uiFT) || (fn != rx->m_uiLastFN + 1U) || + (rx->m_LastFrame.DurationSinceNow() > YSF_WIRESX_FRAME_TIMEOUT) ) { - valid &= payload.readDataFRModeData2(&(Buffer.data()[35]), command + 0U); + // not the next frame of the command in progress + valid = false; } else { - valid &= payload.readDataFRModeData1(&(Buffer.data()[35]), command + (Fich->getFN() - 1U) * 20U + 0U); + uint8 *dst = rx->m_Command + (fn - 2U) * 40U + 20U; + valid &= payload.readDataFRModeData1(&(Buffer.data()[35]), dst); if ( valid ) { - valid &= payload.readDataFRModeData2(&(Buffer.data()[35]), command + (Fich->getFN() - 1U) * 20U + 20U); + valid &= payload.readDataFRModeData2(&(Buffer.data()[35]), dst + 20U); + } + } + + // Copy out a complete command (zero-padded) and drop the + // reassembly state; keep it while more frames are due. + unsigned int cmdLen = 0U; + if ( rx != NULL ) + { + if ( valid && (fn == ft) ) + { + ::memcpy(command, rx->m_Command, sizeof(command)); + cmdLen = (fn == 1U) ? 20U : (fn - 2U) * 40U + 60U; + ReleaseWiresxRx(Ip); + } + else if ( valid ) + { + rx->m_uiLastFN = (uint8)fn; + rx->m_LastFrame.Now(); + valid = false; // wait for the rest + } + else + { + ReleaseWiresxRx(Ip); } } - // check crc if end found. + + // check crc. // endMarkerPos is captured for downstream bounds checks: // the response-code signature match below reads command[4] // and must not run if the end marker is found at a position // that would leave command[4] outside the CRC-validated // region 0..endMarkerPos+1. unsigned int endMarkerPos = 0U; - if ( Fich->getFN() == Fich->getFT() ) + if ( valid ) { valid = false; - // Find the end marker - for (unsigned int i = Fich->getFN() * 20U; i > 0U; i--) + // Find the end marker; it and the CRC byte after it + // must lie within the received data + for (unsigned int i = cmdLen - 2U; i > 0U; i--) { if (command[i] == 0x03U) { @@ -1400,27 +1483,23 @@ bool CYsfProtocol::IsValidwirexPacket(const CBuffer &Buffer, const CIp &Ip, CYSF if ( *Arg > 0 ) (*Arg)--; // ALL_REQ family — sub-code at command[5..6] - // distinguishes the variant for "long form" - // packets: "01" = ALL, "11" = SEARCH. Some Yaesu - // radios also send a SHORT form of this prefix - // with no sub-code at all (end marker lands - // before command[6]). Production observation: - // FTM-100D "LOCAL NEWS" uses the short form. + // distinguishes the variant: "01" = ALL, + // "11" = SEARCH. Radios such as the FT2D send + // this request over two frames; it is only + // decoded here once reassembled and CRC-checked. // - // Approach: try to match known sub-codes only - // when bytes are within the CRC-validated region - // (endMarkerPos >= 6). If no known sub-code - // matches — for either reason (short form OR - // unknown long-form sub-code) — fall into a - // single unified diagnostic block that logs the + // Sub-codes are matched only when they lie + // within the CRC-validated region + // (endMarkerPos >= 6). A validated request that + // ends before the sub-code ("short form"), or + // carries an unknown sub-code, falls into a + // single diagnostic block that logs the // relevant bytes and drops via the UNKNOWN path. // - // Pre-existing concern: the *Arg extraction at - // command[7..9] earlier in this function has - // the same endMarkerPos exposure for - // endMarkerPos < 10. Not addressed here; scope - // limited to closing the UB-on-*Cmd hole and - // giving us diagnostic visibility on variants. + // The *Arg extraction at command[7..9] earlier + // in this function reads past the end marker + // when endMarkerPos < 10; those bytes are + // zero-padded, never uninitialised. bool subCodeRecognised = false; if ( endMarkerPos >= 6U ) { @@ -1452,8 +1531,7 @@ bool CYsfProtocol::IsValidwirexPacket(const CBuffer &Buffer, const CIp &Ip, CYSF // before command[6]). Log shows // "(short form, endMarkerPos=N)" so the // operator can see the exact packet - // shape. FTM-100D "LOCAL NEWS" lives - // here. + // shape. // // Also closes a latent UB: previously *Cmd // could be returned uninitialised when the diff --git a/src/cysfprotocol.h b/src/cysfprotocol.h index 249432f..9ff0579 100644 --- a/src/cysfprotocol.h +++ b/src/cysfprotocol.h @@ -28,6 +28,7 @@ #include +#include #include #include #include "ctimepoint.h" @@ -96,6 +97,23 @@ public: bool m_bInitialized; }; +// Wires-X command reassembly: a command can span several data frames +// (FN 1..FT), each source gets its own buffer. RX thread only. +#define YSF_WIRESX_CMD_SIZE 300 +#define YSF_WIRESX_FRAME_TIMEOUT 1.0 // max gap between frames, seconds + +class CYsfWiresxRxItem +{ +public: + CYsfWiresxRxItem() : m_uiFT(0), m_uiLastFN(0) { ::memset(m_Command, 0, sizeof(m_Command)); } + + CIp m_Ip; + uint8 m_Command[YSF_WIRESX_CMD_SIZE]; + uint8 m_uiFT; // frame total of this command + uint8 m_uiLastFN; // last frame received in sequence + CTimePoint m_LastFrame; +}; + class CYsfProtocol : public CProtocol { public: @@ -157,6 +175,8 @@ protected: // identifies the source so an operator can correlate an unknown // command back to a peer or direct client. bool IsValidwirexPacket(const CBuffer &, const CIp &, CYSFFICH *, CCallsign *, int *, int*); + CYsfWiresxRxItem *GetWiresxRx(const CIp &, bool); + void ReleaseWiresxRx(const CIp &); // server status packet decoding helpers bool IsValidServerStatusPacket(const CBuffer &) const; @@ -218,6 +238,7 @@ protected: // for wires-x CWiresxCmdHandler m_WiresxCmdHandler; unsigned char m_seqNo; + std::vector m_WiresxRx; // command reassembly (RX thread only) // per-source stream-id allocation (see comment above the helpers). // Map key is (addr<<16)|port; value is the active reflector-side sid diff --git a/src/main.h b/src/main.h index 429e199..48b9f7f 100644 --- a/src/main.h +++ b/src/main.h @@ -45,7 +45,7 @@ // version ----------------------------------------------------- #define VERSION_MAJOR 2 #define VERSION_MINOR 6 -#define VERSION_REVISION 1 +#define VERSION_REVISION 2 // global ------------------------------------------------------ #define RUN_AS_DAEMON