Browse Source

ATVDemod: Add some colour. Fix WebAPI.

chirpmodem-v8.1.0
Jon Beniston 3 weeks ago
parent
commit
7651091b60
  1. 6
      plugins/channelrx/demodatv/CMakeLists.txt
  2. 673
      plugins/channelrx/demodatv/atvcolourdecoder.cpp
  3. 295
      plugins/channelrx/demodatv/atvcolourdecoder.h
  4. 76
      plugins/channelrx/demodatv/atvdemod.cpp
  5. 24
      plugins/channelrx/demodatv/atvdemod.h
  6. 5
      plugins/channelrx/demodatv/atvdemodbaseband.h
  7. 201
      plugins/channelrx/demodatv/atvdemodgui.cpp
  8. 7
      plugins/channelrx/demodatv/atvdemodgui.h
  9. 285
      plugins/channelrx/demodatv/atvdemodgui.ui
  10. 157
      plugins/channelrx/demodatv/atvdemodsettings.cpp
  11. 31
      plugins/channelrx/demodatv/atvdemodsettings.h
  12. 302
      plugins/channelrx/demodatv/atvdemodsink.cpp
  13. 136
      plugins/channelrx/demodatv/atvdemodsink.h
  14. 62
      plugins/channelrx/demodatv/atvdemodwebapiadapter.cpp
  15. 3
      plugins/channelrx/demodatv/atvdemodwebapiadapter.h
  16. 322
      plugins/channelrx/demodatv/atvghostestimator.cpp
  17. 96
      plugins/channelrx/demodatv/atvghostestimator.h
  18. 142
      plugins/channelrx/demodatv/atvnoisereduction.cpp
  19. 60
      plugins/channelrx/demodatv/atvnoisereduction.h
  20. 90
      plugins/channelrx/demodatv/readme.md
  21. 33
      sdrbase/resources/webapi/doc/swagger/include/ATVDemod.yaml
  22. 32
      sdrgui/gui/tvscreenanalog.cpp
  23. 33
      swagger/sdrangel/api/swagger/include/ATVDemod.yaml
  24. 132
      swagger/sdrangel/code/qt5/client/SWGATVDemodSettings.cpp
  25. 36
      swagger/sdrangel/code/qt5/client/SWGATVDemodSettings.h

6
plugins/channelrx/demodatv/CMakeLists.txt

@ -2,7 +2,10 @@ project(atv) @@ -2,7 +2,10 @@ project(atv)
set(atv_SOURCES
atvdemod.cpp
atvcolourdecoder.cpp
atvdemodbaseband.cpp
atvnoisereduction.cpp
atvghostestimator.cpp
atvdemodsink.cpp
atvdemodsettings.cpp
atvdemodwebapiadapter.cpp
@ -13,7 +16,10 @@ set(atv_SOURCES @@ -13,7 +16,10 @@ set(atv_SOURCES
set(atv_HEADERS
atvdemod.h
atvcolourdecoder.h
atvdemodbaseband.h
atvnoisereduction.h
atvghostestimator.h
atvdemodsink.h
atvdemodsettings.h
atvdemodwebapiadapter.h

673
plugins/channelrx/demodatv/atvcolourdecoder.cpp

@ -0,0 +1,673 @@ @@ -0,0 +1,673 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program 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 as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include "dsp/dspengine.h"
#include "dsp/fftengine.h"
#include "dsp/fftfactory.h"
#include "atvcolourdecoder.h"
ATVVSBFrontEnd::ATVVSBFrontEnd() :
m_upsampling(0),
m_fft(nullptr),
m_fftSequence(0),
m_ifft(nullptr),
m_ifftSequence(0),
m_inCount(0),
m_skipBlocks(0)
{
FFTFactory *fftFactory = DSPEngine::instance()->getFFTFactory();
m_fftSequence = fftFactory->getEngine(m_fftLen, false, &m_fft);
m_fftIn = m_fft->in();
m_response.resize(m_fftLen);
configure(1000000, 0.0f, 3579545.0f, true, 1);
}
ATVVSBFrontEnd::~ATVVSBFrontEnd()
{
FFTFactory *fftFactory = DSPEngine::instance()->getFFTFactory();
fftFactory->releaseEngine(m_fftLen, false, m_fftSequence);
if (m_ifft) {
fftFactory->releaseEngine(m_fftLen * m_upsampling, true, m_ifftSequence);
}
}
void ATVVSBFrontEnd::configure(int sampleRate, float carrierOffset, float videoBandwidth, bool usb, int upsampling)
{
if (upsampling != m_upsampling)
{
FFTFactory *fftFactory = DSPEngine::instance()->getFFTFactory();
if (m_ifft) {
fftFactory->releaseEngine(m_fftLen * m_upsampling, true, m_ifftSequence);
}
m_upsampling = upsampling;
m_ifftSequence = fftFactory->getEngine(m_fftLen * m_upsampling, true, &m_ifft);
m_overlap.resize(m_blockLen * m_upsampling);
m_out.resize(m_blockLen * m_upsampling);
}
const float slope = 0.3e6f; // Half width of the Nyquist slope
const float videoTop = videoBandwidth;
const float stopTop = videoBandwidth + 0.2e6f;
const float guard = 0.02f * sampleRate; // Taper to zero before the band edges, so upsampling has no discontinuity at Nyquist
auto response = [&](float f) -> float
{
float fr = usb ? f - carrierOffset : carrierOffset - f; // Frequency relative to the vision carrier, video side positive
float h;
if (fr <= -slope) {
return 0.0f;
} else if (fr >= slope) {
h = 1.0f;
} else {
h = 0.5f + fr / (2.0f * slope);
}
if (fr >= stopTop) {
return 0.0f;
} else if (fr > videoTop) {
h *= 0.5f * (1.0f + std::cos((float) M_PI * (fr - videoTop) / (stopTop - videoTop)));
}
float edge = 0.5f * sampleRate - std::fabs(f);
if (edge <= 0.0f) {
return 0.0f;
} else if (edge < guard) {
h *= 0.5f * (1.0f - std::cos((float) M_PI * edge / guard));
}
return h;
};
// Frequency sampling design: impulse response of m_blockLen taps, centred and windowed,
// so the linear convolution of a block still fits in the FFT
const int len = m_blockLen;
std::vector<float> desired(len);
for (int k = 0; k < len; k++)
{
float f = (k < len / 2 ? k : k - len) * (float) sampleRate / (float) len;
desired[k] = response(f);
}
std::fill(m_fftIn, m_fftIn + m_fftLen, Complex{0.0f, 0.0f});
for (int n = 0; n < len; n++)
{
std::complex<double> acc = 0.0;
for (int k = 0; k < len; k++) {
acc += (double) desired[k] * std::polar(1.0, 2.0 * M_PI * k * (n - len / 2) / (double) len);
}
// Window, and scale by 1 / m_fftLen so the unnormalised FFT pair has unity gain
double window = 0.42 - 0.5 * std::cos(2.0 * M_PI * n / len) + 0.08 * std::cos(4.0 * M_PI * n / len);
m_fftIn[n] = Complex(acc * (window / ((double) len * m_fftLen)));
}
m_fft->transform();
std::copy(m_fft->out(), m_fft->out() + m_fftLen, m_response.begin());
std::fill(m_fftIn, m_fftIn + m_fftLen, Complex{0.0f, 0.0f});
std::fill(m_overlap.begin(), m_overlap.end(), Complex{0.0f, 0.0f});
m_inCount = 0;
m_skipBlocks = 2;
}
int ATVVSBFrontEnd::processBlock(Complex **out)
{
const int outFFTLen = m_fftLen * m_upsampling;
const int outLen = m_blockLen * m_upsampling;
m_fft->transform();
const Complex *spectrum = m_fft->out();
Complex *upsampled = m_ifft->in();
// Filter, and upsample by zero padding the middle of the spectrum
std::fill(upsampled, upsampled + outFFTLen, Complex{0.0f, 0.0f});
for (int i = 0; i < m_fftLen / 2; i++) {
upsampled[i] = spectrum[i] * m_response[i];
}
for (int i = 1; i < m_fftLen / 2; i++) {
upsampled[outFFTLen - i] = spectrum[m_fftLen - i] * m_response[m_fftLen - i];
}
m_ifft->transform();
const Complex *filtered = m_ifft->out();
// Overlap and add
for (int i = 0; i < outLen; i++)
{
m_out[i] = m_overlap[i] + filtered[i];
m_overlap[i] = filtered[outLen + i];
}
// The second half of the input is zero padding, so it only needs clearing in case the FFT overwrote it
std::fill(m_fftIn + m_blockLen, m_fftIn + m_fftLen, Complex{0.0f, 0.0f});
*out = m_out.data();
return outLen;
}
ATVSynchronousDetector::ATVSynchronousDetector() :
m_ghostOn(false),
m_ghostBuffer(m_ghostBufferSize),
m_ghostIndex(0)
{
configure(10000000.0f, 0.0f, 15625.0f);
}
void ATVSynchronousDetector::configure(float sampleRate, float carrierFrequency, float lineFrequency)
{
m_sampleRate = sampleRate;
m_blockLength = std::max(2, (int) std::round(sampleRate / 1.0e6f));
m_linePeriod = sampleRate / lineFrequency;
m_nominalStep = -2.0 * M_PI * carrierFrequency / sampleRate;
m_frequency = 0.0;
m_rotation = 1.0f;
m_step = std::polar(1.0f, (float) m_nominalStep);
m_phaseCarrier = 0.0f;
m_carrierUnit = 1.0f;
m_phaseLowPassAlpha = 1.0f - std::exp(-2.0f * (float) M_PI * 5.0e3f / sampleRate); // 5 kHz
m_count = 0;
m_block = 0.0f;
m_blockIndex = 0;
m_tipLevel = 0.0f;
m_keyLevel = 0.0f;
m_run.clear();
m_run.reserve(m_maxRunBlocks);
m_runStart = 0;
m_runOverflow = false;
m_prevRunSum = 0.0f;
m_prevRunLength = 0;
m_prevRunStart = 0;
m_coarseSum = 0.0f;
m_coarseCount = 0;
setGhost(1.0f, 0.0f);
m_ghostInput = 0.0f;
}
void ATVSynchronousDetector::setGhost(float delay, std::complex<float> gain)
{
delay = std::max(1.0f, std::min(delay, (float) (m_ghostBufferSize - 2)));
m_ghostDelay = (int) delay;
m_ghostFrac = delay - m_ghostDelay;
m_ghostGain = gain;
if ((gain != 0.0f) != m_ghostOn)
{
m_ghostOn = gain != 0.0f;
std::fill(m_ghostBuffer.begin(), m_ghostBuffer.end(), 0.0f);
m_ghostIndex = 0;
}
}
void ATVSynchronousDetector::update()
{
m_count = 0;
float magnitude = std::abs(m_phaseCarrier);
if (magnitude > 0.0f) {
m_carrierUnit = std::conj(m_phaseCarrier) / magnitude;
}
// Sync tip level: follows the strongest blocks, and decays over ~100 ms so keying
// recovers if the signal level drops
float blockAmplitude = std::abs(m_block) / m_blockLength;
if (blockAmplitude > m_tipLevel) {
m_tipLevel += 0.02f * (blockAmplitude - m_tipLevel);
} else {
m_tipLevel *= 0.99999f;
}
m_keyLevel = 0.85f * 0.85f * m_tipLevel * m_tipLevel;
// Collect runs of blocks within 90% of the sync tip carrier
if ((blockAmplitude > 0.9f * m_tipLevel) && (m_blockIndex > m_settleBlocks))
{
if (m_run.empty()) {
m_runStart = m_blockIndex;
}
if ((int) m_run.size() < m_maxRunBlocks) {
m_run.push_back(m_block);
} else {
m_runOverflow = true;
}
}
else if (!m_run.empty())
{
endRun();
}
m_block = 0.0f;
m_blockIndex++;
m_rotation /= std::abs(m_rotation); // Keep the recursive rotation on the unit circle
}
void ATVSynchronousDetector::endRun()
{
int length = (int) m_run.size();
if (!m_runOverflow)
{
std::complex<float> sum = 0.0f;
for (const auto& block : m_run) {
sum += block;
}
// Coarse: phase change between blocks along the middle of a broad pulse
for (int i = m_runEdgeBlocks + 1; i < length - m_runEdgeBlocks; i++)
{
m_coarseSum += m_run[i] * std::conj(m_run[i - 1]);
m_coarseCount++;
}
// Fine: phase change since the same pulse a line earlier
float spacing = (float) ((m_runStart - m_prevRunStart) * m_blockLength);
if ((length >= 2) && (std::abs(length - m_prevRunLength) <= 1) && (std::fabs(spacing - m_linePeriod) < 2.0f * m_blockLength))
{
float dphi = std::arg(sum * std::conj(m_prevRunSum));
m_frequency -= 0.1 * dphi / m_linePeriod;
}
m_prevRunSum = sum;
m_prevRunLength = length;
m_prevRunStart = m_runStart;
}
m_run.clear();
m_runOverflow = false;
// Once a vertical sync's worth of broad pulses is measured, correct the frequency if it is
// well out, which is when the fine loop could be on the wrong multiple of the line rate.
// The pulses' edges still bias it by ~2 kHz, so small errors are left to the fine loop
if (m_coarseCount >= 40)
{
double error = std::arg(m_coarseSum) / m_blockLength; // radians / sample
if (std::fabs(error) > 2.0 * M_PI * 4000.0 / m_sampleRate) {
m_frequency -= error;
}
m_coarseSum = 0.0f;
m_coarseCount = 0;
}
m_step = std::polar(1.0f, (float) (m_nominalStep + m_frequency));
}
float ATVSynchronousDetector::getFrequencyError() const
{
return (float) (-m_frequency * m_sampleRate / (2.0 * M_PI));
}
ATVColourDecoder::ATVColourDecoder() :
m_carrierReferenced(false),
m_saturation(1.0f),
m_hue(1.0f, 0.0f),
m_delayLine(true)
{
configure(10000000.0f, ATVDemodSettings::ColourNTSC);
}
void ATVColourDecoder::configure(float sampleRate, ATVDemodSettings::ColourSystem colourSystem)
{
m_sampleRate = sampleRate;
m_subcarrierFrequency = ATVDemodSettings::getSubcarrierFrequency(colourSystem);
m_pal = (colourSystem == ATVDemodSettings::ColourPAL)
|| (colourSystem == ATVDemodSettings::ColourPALM)
|| (colourSystem == ATVDemodSettings::ColourPALN);
// Levels in IRE (100 IRE = 700 mV for 625 line systems)
bool system525 = (colourSystem == ATVDemodSettings::ColourNTSC) || (colourSystem == ATVDemodSettings::ColourPALM);
m_syncDepth = system525 ? 40.0f : 300.0f / 7.0f;
m_nominalBurst = system525 ? 20.0f : 150.0f / 7.0f;
m_setup = system525 ? 7.5f : 0.0f;
m_blankCarrier = 0.75f; // Negative modulation, as a fraction of the sync tip carrier
m_whiteCarrier = ATVDemodSettings::getWhiteCarrier(colourSystem);
// Measurement windows from the leading edge of sync: sync tip, and the burst
// (NTSC burst is 5.3 to 7.8 us, PAL 5.6 to 7.85 us)
m_tipStart = (int) (1.0e-6f * sampleRate);
m_tipEnd = (int) (3.5e-6f * sampleRate);
m_burstStart = (int) (5.8e-6f * sampleRate);
m_burstEnd = (int) (7.4e-6f * sampleRate);
// Chroma low pass: 6 dB at 1.5 MHz, stop band from about 2.1 MHz, which rejects
// both the luma (shifted down to -fsc) and the image at -2 fsc
float cutoff = 1.5e6f / sampleRate;
int taps = ((int) std::ceil(5.5f * sampleRate / 1.2e6f)) | 1;
int half = taps / 2;
m_lpfTaps.resize(taps);
float sum = 0.0f;
for (int i = 0; i < taps; i++)
{
int k = i - half;
float sinc = (k == 0) ? 2.0f * cutoff : std::sin(2.0f * (float) M_PI * cutoff * k) / ((float) M_PI * k);
float window = 0.42f + 0.5f * std::cos((float) M_PI * k / (half + 1)) + 0.08f * std::cos(2.0f * (float) M_PI * k / (half + 1));
m_lpfTaps[i] = sinc * window;
sum += m_lpfTaps[i];
}
for (auto& tap : m_lpfTaps) {
tap /= sum;
}
m_chromaDecimation = std::max(1, (int) (sampleRate / 4.5e6f));
// The displayed chroma is narrower again, as a TV's was, which halves its noise:
// two 0.6 us boxcars make a triangle about 0.75 MHz wide at 6 dB. The wider chroma is
// still used to separate it from the luma, so the luma keeps no subcarrier
m_chromaSmoothing = std::max(1, (int) std::round(0.6e-6f * sampleRate));
m_phasor.clear(); // Recalculated for the new rate by resize()
m_prevUV.clear();
m_tipLevel = 0.0f;
m_blankLevel = 0.0f;
m_levelsValid = false;
m_burstRef = 0.0f;
m_prevBurst = 0.0f;
m_burstAmplitude = 0.0f;
m_colourOn = false;
m_missingBursts = 1000;
m_vSign = 1.0f;
}
void ATVColourDecoder::resize(int length)
{
if ((int) m_phasor.size() < length)
{
int oldSize = (int) m_phasor.size();
m_phasor.resize(length);
float w = 2.0f * (float) M_PI * m_subcarrierFrequency / m_sampleRate;
for (int n = oldSize; n < length; n++) {
m_phasor[n] = std::polar(2.0f, -w * n);
}
m_ire.resize(length);
m_mixedRe.resize(length);
m_mixedIm.resize(length);
m_chroma.resize(length);
m_chromaSum.resize(length + 1);
m_chromaDisplay.resize(length);
m_prevUV.resize(length);
}
}
// Centred moving average of m_chromaSmoothing samples (in and out can be the same)
void ATVColourDecoder::smoothChroma(std::vector<std::complex<float>>& in, std::vector<std::complex<float>>& out, int length)
{
const int w = m_chromaSmoothing;
const int before = w / 2;
m_chromaSum[0] = 0.0f;
for (int n = 0; n < length; n++) {
m_chromaSum[n + 1] = m_chromaSum[n] + in[n];
}
for (int n = 0; n < length; n++)
{
int a = std::max(n - before, 0);
int b = std::min(n - before + w, length);
out[n] = (m_chromaSum[b] - m_chromaSum[a]) / (float) (b - a);
}
}
std::complex<float> ATVColourDecoder::filterChroma(int n, int length) const
{
const int taps = (int) m_lpfTaps.size();
const int half = taps / 2;
const float *h = m_lpfTaps.data();
float re = 0.0f;
float im = 0.0f;
if ((n - half >= 0) && (n + half < length))
{
// Separate real and imaginary arrays, so this vectorises
const float *xr = &m_mixedRe[n - half];
const float *xi = &m_mixedIm[n - half];
for (int i = 0; i < taps; i++)
{
re += h[i] * xr[i];
im += h[i] * xi[i];
}
}
else
{
for (int i = 0; i < taps; i++)
{
int j = std::min(std::max(n + i - half, 0), length - 1);
re += h[i] * m_mixedRe[j];
im += h[i] * m_mixedIm[j];
}
}
return {re, im};
}
static inline unsigned int packRGB(float r, float g, float b)
{
int ri = std::min(std::max((int) (r * 255.0f), 0), 255);
int gi = std::min(std::max((int) (g * 255.0f), 0), 255);
int bi = std::min(std::max((int) (b * 255.0f), 0), 255);
return ri | (gi << 8) | (bi << 16);
}
void ATVColourDecoder::decodeLine(const float *line, int length, int firstValid, int64_t lineStart, unsigned int *rgb)
{
resize(length);
// DC restore at the blanking level. The burst averages to zero, so the burst window
// gives the blanking level
if ((firstValid <= m_tipStart) && (length > m_burstEnd))
{
float tip = 0.0f;
float blank = 0.0f;
for (int n = m_tipStart; n < m_tipEnd; n++) {
tip += line[n];
}
for (int n = m_burstStart; n < m_burstEnd; n++) {
blank += line[n];
}
tip /= m_tipEnd - m_tipStart;
blank /= m_burstEnd - m_burstStart;
bool valid = m_carrierReferenced ? (tip - blank > 0.02f * tip) : (blank - tip > 0.02f);
if (valid)
{
if (m_levelsValid)
{
m_tipLevel += 0.2f * (tip - m_tipLevel);
m_blankLevel += 0.2f * (blank - m_blankLevel);
}
else
{
m_tipLevel = tip;
m_blankLevel = blank;
m_levelsValid = true;
}
}
}
if (!m_levelsValid)
{
for (int n = 0; n < length; n++) {
rgb[n] = packRGB(line[n], line[n], line[n]);
}
return;
}
// Scale to IRE. From the depth of sync, unless the carrier level is known, when the sync
// tip carrier is used as a TV's keyed AGC does: sync is often compressed in transmission
// or by fading, which would exaggerate the gain
float scale = m_carrierReferenced
? -100.0f / ((m_blankCarrier - m_whiteCarrier) * m_tipLevel)
: m_syncDepth / (m_blankLevel - m_tipLevel);
for (int n = 0; n < length; n++)
{
m_ire[n] = (line[n] - m_blankLevel) * scale;
m_mixedRe[n] = m_ire[n] * m_phasor[n].real();
m_mixedIm[n] = m_ire[n] * m_phasor[n].imag();
}
// Baseband chroma, filtered every m_chromaDecimation samples and linearly interpolated between
int d = m_chromaDecimation;
int last = 0;
m_chroma[0] = filterChroma(0, length);
for (int n = d; n < length; n += d)
{
m_chroma[n] = filterChroma(n, length);
for (int i = 1; i < d; i++) {
m_chroma[last + i] = m_chroma[last] + (m_chroma[n] - m_chroma[last]) * ((float) i / d);
}
last = n;
}
for (int n = last + 1; n < length; n++) {
m_chroma[n] = m_chroma[last];
}
// m_phasor restarts at each line, but the subcarrier does not (in NTSC its phase is
// inverted on successive lines), so bursts are compared at a phase continuous across lines
double w = 2.0 * M_PI * m_subcarrierFrequency / m_sampleRate;
std::complex<float> lineRotation = std::polar(1.0f, (float) -std::fmod(w * (double) lineStart, 2.0 * M_PI));
// Burst
bool burstValid = (firstValid <= m_burstStart) && (length > m_burstEnd);
bool burstPresent = false;
std::complex<float> burst = 0.0f;
if (burstValid)
{
for (int n = m_burstStart; n < m_burstEnd; n++) {
burst += m_chroma[n];
}
burst *= lineRotation / (float) (m_burstEnd - m_burstStart);
float amplitude = std::abs(burst);
burstPresent = amplitude > 0.25f * m_nominalBurst;
if (burstPresent) {
m_burstAmplitude += 0.1f * (amplitude - m_burstAmplitude);
}
if (m_pal)
{
// Successive bursts swing +/-45 degrees either side of -U, so their sum points along -U
if (burstPresent && (std::abs(m_prevBurst) > 0.0f)) {
m_burstRef += 0.3f * (burst + m_prevBurst - m_burstRef);
}
m_prevBurst = burstPresent ? burst : 0.0f;
}
else if (burstPresent)
{
m_burstRef += 0.3f * (burst - m_burstRef);
}
}
// Colour killer: off when no burst for longer than the vertical blanking interval
m_missingBursts = burstPresent ? 0 : m_missingBursts + 1;
m_colourOn = (m_missingBursts < 50) && (std::abs(m_burstRef) > 0.25f * m_nominalBurst);
float range = 100.0f - m_setup;
if (!m_colourOn)
{
for (int n = 0; n < length; n++)
{
float y = (m_ire[n] - m_setup) / range;
rgb[n] = packRGB(y, y, y);
}
return;
}
// Rotate so the burst reference is at 180 degrees (-U); U is then real and V imaginary
std::complex<float> rot = -std::conj(m_burstRef) / std::abs(m_burstRef);
if (m_pal)
{
// V switch: the burst is at 135 degrees on lines where V is not inverted
if (burstPresent) {
m_vSign = (burst * rot).imag() > 0.0f ? 1.0f : -1.0f;
} else {
m_vSign = -m_vSign;
}
}
else
{
rot *= m_hue;
}
rot *= lineRotation * (m_saturation * m_nominalBurst / std::max(m_burstAmplitude, 1.0f) / range);
smoothChroma(m_chroma, m_chromaDisplay, length);
smoothChroma(m_chromaDisplay, m_chromaDisplay, length);
for (int n = 0; n < length; n++)
{
const std::complex<float>& c = m_chroma[n];
float chroma = 0.5f * (c.real() * m_phasor[n].real() + c.imag() * m_phasor[n].imag()); // Re(c * conj(phasor)) / 2
float y = (m_ire[n] - chroma - m_setup) / range;
std::complex<float> uv = m_chromaDisplay[n] * rot;
if (m_pal) {
uv.imag(uv.imag() * m_vSign);
}
// PAL's delay line cancels phase errors. For NTSC too, averaging with the previous line
// of the field halves the chroma noise, for half the vertical chroma resolution
if (m_delayLine)
{
std::complex<float> current = uv;
uv = 0.5f * (uv + m_prevUV[n]);
m_prevUV[n] = current;
}
float ry = uv.imag() / 0.877f;
float by = uv.real() / 0.492f;
rgb[n] = packRGB(y + ry, y - 0.509f * ry - 0.194f * by, y + by);
}
}

295
plugins/channelrx/demodatv/atvcolourdecoder.h

@ -0,0 +1,295 @@ @@ -0,0 +1,295 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program 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 as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_ATVCOLOURDECODER_H
#define INCLUDE_ATVCOLOURDECODER_H
#include <complex>
#include <cstdint>
#include <vector>
#include "dsp/dsptypes.h"
#include "atvdemodsettings.h"
class FFTEngine;
/**
* Front end for AM / VSB signals.
*
* Applies a Nyquist slope through the vision carrier, as a TV receiver's IF filter does,
* which flattens the response across the vestigial sideband and removes anything below
* the carrier (such as an aliased sound carrier). It also band limits above the video
* (the chroma for colour) and upsamples by an integer factor in the frequency domain, so
* the envelope of the signal can be taken without aliasing.
*
* For colour, input should have the centre of the video band at DC (see
* ATVDemodSettings::getColourBandCentreOffset). For mono without upsampling, it should
* have the vision carrier at DC, so the video is band limited to half the sample rate.
*/
class ATVVSBFrontEnd
{
public:
ATVVSBFrontEnd();
~ATVVSBFrontEnd();
ATVVSBFrontEnd(const ATVVSBFrontEnd&) = delete;
ATVVSBFrontEnd& operator=(const ATVVSBFrontEnd&) = delete;
/**
* @param sampleRate input sample rate
* @param carrierOffset frequency of the vision carrier in the input (Hz)
* @param videoBandwidth top of the video above the vision carrier (Hz)
* @param usb true when the video is above the vision carrier
* @param upsampling integer upsampling factor (1, 2 or 4)
*/
void configure(int sampleRate, float carrierOffset, float videoBandwidth, bool usb, int upsampling);
/** Returns the number of output samples in *out, which is 0 until a block completes */
int process(const Complex& in, Complex **out)
{
m_fftIn[m_inCount++] = in;
if (m_inCount < m_blockLen) {
return 0;
}
m_inCount = 0;
int n = processBlock(out);
// Drop the start-up transient while the overlap fills, as it would upset the AGC
if (m_skipBlocks > 0)
{
m_skipBlocks--;
return 0;
}
return n;
}
private:
static const int m_fftLen = 1024; //!< Input FFT length
static const int m_blockLen = m_fftLen / 2; //!< Input samples per block (and filter length)
int m_upsampling;
FFTEngine *m_fft;
unsigned int m_fftSequence;
FFTEngine *m_ifft;
unsigned int m_ifftSequence;
Complex *m_fftIn; //!< m_fft's input, filled a block at a time
std::vector<Complex> m_response; //!< Filter frequency response, m_fftLen bins, scaled by 1 / m_fftLen
std::vector<Complex> m_overlap;
std::vector<Complex> m_out;
int m_inCount;
int m_skipBlocks;
int processBlock(Complex **out);
};
/**
* Synchronous AM detector for the front end's output.
*
* Envelope detection of a vestigial sideband signal adds a quadrature distortion that
* grows with the square of the chroma, darkening saturated colours, so the vision carrier
* is recovered and the in-phase component taken instead, as a TV does.
*
* Carrier recovery is keyed to the sync tips, where the carrier is not modulated by the
* picture. Transmitters that overmodulate cut the carrier off in white areas and shift its
* phase, and through the Nyquist slope the picture's own detail is lopsided about the
* carrier, which an unkeyed loop reads as a frequency error (+3.5 kHz on a white text page,
* enough to tear the picture). Even within a sync tip the phase ramps, as the filter adds a
* quadrature component at the pulse's edges, so frequency is measured between matching
* points rather than along a pulse:
* - fine: the phase of each line's sync tip against the previous line's. This is unbiased,
* but unambiguous only to half the line rate (+/- 7.8 kHz for 525 lines)
* - coarse: the phase change along the flat middle of the vertical sync's broad pulses,
* away from their edges, which corrects the fine loop when it is a line rate out
* The phase comes from a narrow low pass of the samples within 85% of the sync tip carrier.
*/
class ATVSynchronousDetector
{
public:
ATVSynchronousDetector();
/**
* @param carrierFrequency nominal frequency of the vision carrier in the input (Hz)
* @param lineFrequency lines per second
*/
void configure(float sampleRate, float carrierFrequency, float lineFrequency);
/** Returns the in-phase amplitude, which is the envelope when the carrier is tracked */
float process(const std::complex<float>& in)
{
std::complex<float> mixed = in * m_rotation;
m_rotation *= m_step;
m_ghostInput = mixed;
if (m_ghostOn)
{
// y[n] = x[n] - g y[n - D], which cancels an echo g x[n - D] exactly
int i0 = (m_ghostIndex - m_ghostDelay) & m_ghostMask;
int i1 = (i0 - 1) & m_ghostMask;
mixed -= m_ghostGain * (m_ghostBuffer[i0] + m_ghostFrac * (m_ghostBuffer[i1] - m_ghostBuffer[i0]));
m_ghostBuffer[m_ghostIndex] = mixed;
m_ghostIndex = (m_ghostIndex + 1) & m_ghostMask;
}
if (std::norm(mixed) > m_keyLevel) {
m_phaseCarrier += m_phaseLowPassAlpha * (mixed - m_phaseCarrier);
}
m_block += mixed;
float out = mixed.real() * m_carrierUnit.real() - mixed.imag() * m_carrierUnit.imag(); // Re(mixed * unit)
if (++m_count == m_blockLength) {
update();
}
return out;
}
float getFrequencyError() const; //!< Hz, carrier relative to its nominal frequency
/**
* Cancels an echo (ghost) of the signal, delayed by delay samples (1 or more) with the
* given gain relative to the carrier. 0 gain turns cancellation off
*/
void setGhost(float delay, std::complex<float> gain);
/** The last sample before ghost cancellation, with the carrier's phase removed (real is the in-phase amplitude) */
std::complex<float> getGhostInput() const { return m_ghostInput * m_carrierUnit; }
private:
static const int m_ghostBufferSize = 256; //!< samples, a power of 2
static const int m_ghostMask = m_ghostBufferSize - 1;
static const int m_maxRunBlocks = 64; //!< longer runs (when the blanking is keyed through the vertical interval) are not used
static const int m_runEdgeBlocks = 3; //!< blocks at each end of a broad pulse left out of the coarse estimate
static const int m_settleBlocks = 2000; //!< blocks for the sync tip level to settle before keying
float m_sampleRate;
int m_blockLength; //!< samples per block, ~1 us, so several fit in a sync tip
float m_linePeriod; //!< samples
double m_nominalStep; //!< radians / sample
double m_frequency; //!< FLL correction, radians / sample
std::complex<float> m_rotation;
std::complex<float> m_step;
std::complex<float> m_phaseCarrier; //!< narrow low pass of the keyed samples, for the phase
std::complex<float> m_carrierUnit;
float m_phaseLowPassAlpha;
int m_count;
std::complex<float> m_block; //!< sum of the samples in the current block
int64_t m_blockIndex;
float m_tipLevel; //!< sync tip block amplitude
float m_keyLevel; //!< power above which samples are used for the phase
std::vector<std::complex<float>> m_run; //!< blocks of the current sync tip
int64_t m_runStart; //!< block index
bool m_runOverflow;
std::complex<float> m_prevRunSum;
int m_prevRunLength;
int64_t m_prevRunStart;
std::complex<float> m_coarseSum; //!< phase change per block along broad pulses
int m_coarseCount;
bool m_ghostOn;
int m_ghostDelay; //!< samples, integer part
float m_ghostFrac; //!< samples, fractional part
std::complex<float> m_ghostGain;
std::vector<std::complex<float>> m_ghostBuffer; //!< output, for the cancellation's feedback
int m_ghostIndex;
std::complex<float> m_ghostInput;
void update();
void endRun();
};
/**
* Decodes NTSC and PAL colour, one line at a time.
*
* Works on a whole line of composite video once it is complete, so its filters can be
* zero phase and the burst, which comes before the active video, is known before any
* pixel is decoded.
*/
class ATVColourDecoder
{
public:
ATVColourDecoder();
void configure(float sampleRate, ATVDemodSettings::ColourSystem colourSystem);
void setSaturation(int saturation) { m_saturation = saturation / 100.0f; }
void setHue(int hue) { m_hue = std::polar(1.0f, hue * (float) M_PI / 180.0f); }
void setDelayLine(bool delayLine) { m_delayLine = delayLine; }
/** Line is the envelope of a negatively modulated AM signal, rather than video scaled with sync tip low */
void setCarrierReferenced(bool carrierReferenced) { m_carrierReferenced = carrierReferenced; }
/**
* Decode one line.
*
* @param line composite samples, index 0 at the leading edge of the sync pulse, scaled so sync tip is low,
* or the AM envelope when carrier referenced
* @param length number of samples in the line
* @param firstValid first index written for this line (earlier ones are stale after a sync jump)
* @param lineStart sample count at index 0 of the line, so the subcarrier phase is continuous across lines
* @param rgb output, packed as 0x00BBGGRR (the byte order the TV screen texture uses)
*/
void decodeLine(const float *line, int length, int firstValid, int64_t lineStart, unsigned int *rgb);
bool getColourLocked() const { return m_colourOn; }
float getBurstAmplitude() const { return m_burstAmplitude; } //!< Smoothed burst amplitude, IRE
private:
float m_sampleRate;
float m_subcarrierFrequency;
bool m_pal;
float m_syncDepth; //!< Sync depth below blanking, IRE
float m_nominalBurst; //!< Nominal burst peak amplitude, IRE
float m_setup; //!< Black level above blanking, IRE
float m_blankCarrier; //!< Blanking and white carrier levels, fraction of the sync tip, when carrier referenced
float m_whiteCarrier;
int m_tipStart, m_tipEnd;
int m_burstStart, m_burstEnd;
int m_chromaDecimation; //!< Chroma is band limited, so is only filtered every this many samples
bool m_carrierReferenced;
float m_saturation;
std::complex<float> m_hue;
bool m_delayLine;
std::vector<float> m_lpfTaps; //!< Chroma low pass (zero phase, odd length)
std::vector<std::complex<float>> m_phasor; //!< 2 * exp(-j w n) for the subcarrier, from the start of the line
std::vector<float> m_ire;
std::vector<float> m_mixedRe; //!< Composite mixed down by the subcarrier
std::vector<float> m_mixedIm;
std::vector<std::complex<float>> m_chroma; //!< Baseband chroma, every sample
std::vector<std::complex<float>> m_chromaSum; //!< Running sums for smoothing the displayed chroma
std::vector<std::complex<float>> m_chromaDisplay;
int m_chromaSmoothing; //!< Boxcar length, applied twice
std::vector<std::complex<float>> m_prevUV; //!< Previous line's U + jV for the delay line
float m_tipLevel;
float m_blankLevel;
bool m_levelsValid;
std::complex<float> m_burstRef; //!< Smoothed burst vector (NTSC) or sum of two lines' bursts (PAL)
std::complex<float> m_prevBurst;
float m_burstAmplitude;
bool m_colourOn;
int m_missingBursts; //!< Consecutive lines without a burst
float m_vSign; //!< PAL V switch for the current line
void resize(int length);
void smoothChroma(std::vector<std::complex<float>>& in, std::vector<std::complex<float>>& out, int length);
std::complex<float> filterChroma(int n, int length) const;
};
#endif // INCLUDE_ATVCOLOURDECODER_H

76
plugins/channelrx/demodatv/atvdemod.cpp

@ -23,10 +23,18 @@ @@ -23,10 +23,18 @@
#include <stdio.h>
#include <complex.h>
#include "SWGChannelSettings.h"
#include "SWGWorkspaceInfo.h"
#include "SWGATVDemodSettings.h"
#include "SWGChannelReport.h"
#include "SWGATVDemodReport.h"
#include "device/deviceapi.h"
#include "atvdemod.h"
#include "atvdemodwebapiadapter.h"
#include "dsp/dspcommands.h"
#include "util/db.h"
MESSAGE_CLASS_DEFINITION(ATVDemod::MsgConfigureATVDemod, Message)
@ -215,3 +223,71 @@ int ATVDemod::getChannelSampleRate() const @@ -215,3 +223,71 @@ int ATVDemod::getChannelSampleRate() const
{
return m_basebandSink ? m_basebandSink->getChannelSampleRate() : 0;
}
int ATVDemod::webapiSettingsGet(
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void) errorMessage;
response.setAtvDemodSettings(new SWGSDRangel::SWGATVDemodSettings());
response.getAtvDemodSettings()->init();
ATVDemodWebAPIAdapter::webapiFormatChannelSettings(response, m_settings);
return 200;
}
int ATVDemod::webapiWorkspaceGet(
SWGSDRangel::SWGWorkspaceInfo& response,
QString& errorMessage)
{
(void) errorMessage;
response.setIndex(m_settings.m_workspaceIndex);
return 200;
}
int ATVDemod::webapiSettingsPutPatch(
bool force,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage)
{
(void) errorMessage;
ATVDemodSettings settings = m_settings;
ATVDemodWebAPIAdapter::webapiUpdateChannelSettings(settings, channelSettingsKeys, response);
QStringList settingsKeys = ATVDemodWebAPIAdapter::getSettingsKeys(channelSettingsKeys);
MsgConfigureATVDemod *msg = MsgConfigureATVDemod::create(settingsKeys, settings, force);
m_inputMessageQueue.push(msg);
if (getMessageQueueToGUI()) // forward to GUI if any
{
MsgConfigureATVDemod *msgToGUI = MsgConfigureATVDemod::create(settingsKeys, settings, force);
getMessageQueueToGUI()->push(msgToGUI);
}
ATVDemodWebAPIAdapter::webapiFormatChannelSettings(response, settings);
return 200;
}
int ATVDemod::webapiReportGet(
SWGSDRangel::SWGChannelReport& response,
QString& errorMessage)
{
(void) errorMessage;
response.setAtvDemodReport(new SWGSDRangel::SWGATVDemodReport());
response.getAtvDemodReport()->init();
webapiFormatChannelReport(response);
return 200;
}
void ATVDemod::webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response)
{
response.getAtvDemodReport()->setChannelPowerDb(CalcDb::dbPower(getMagSq() / (SDR_RX_SCALED*SDR_RX_SCALED)));
response.getAtvDemodReport()->setChannelSampleRate(getChannelSampleRate());
response.getAtvDemodReport()->setBfoLocked(getBFOLocked() ? 1 : 0);
response.getAtvDemodReport()->setColourLocked(getColourLocked() ? 1 : 0);
response.getAtvDemodReport()->setBurstAmplitude(getBurstAmplitude());
response.getAtvDemodReport()->setCarrierFrequencyError(getCarrierFrequencyError());
response.getAtvDemodReport()->setGhostDelay(getGhostDelay() * 1e6f);
response.getAtvDemodReport()->setGhostAmplitude(getGhostAmplitude());
}

24
plugins/channelrx/demodatv/atvdemod.h

@ -97,10 +97,33 @@ public: @@ -97,10 +97,33 @@ public:
return m_settings.m_inputFrequencyOffset;
}
virtual int webapiSettingsGet(
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage);
virtual int webapiWorkspaceGet(
SWGSDRangel::SWGWorkspaceInfo& response,
QString& errorMessage);
virtual int webapiSettingsPutPatch(
bool force,
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response,
QString& errorMessage);
virtual int webapiReportGet(
SWGSDRangel::SWGChannelReport& response,
QString& errorMessage);
ScopeVis *getScopeSink() { return m_basebandSink->getScopeSink(); }
void setTVScreen(TVScreenAnalog *tvScreen) { m_basebandSink->setTVScreen(tvScreen); }; //!< set by the GUI
double getMagSq() const { return m_basebandSink->getMagSq(); } //!< Beware this is scaled to 2^30
bool getBFOLocked() { return m_basebandSink->getBFOLocked(); }
bool getColourLocked() const { return m_basebandSink->getColourLocked(); }
float getBurstAmplitude() const { return m_basebandSink->getBurstAmplitude(); }
float getCarrierFrequencyError() const { return m_basebandSink->getCarrierFrequencyError(); } //!< Hz, for AM through the VSB filter
float getGhostDelay() const { return m_basebandSink->getGhostDelay(); } //!< s
float getGhostAmplitude() const { return m_basebandSink->getGhostAmplitude(); } //!< 0 when no echo is being cancelled
void setVideoTabIndex(int videoTabIndex) { m_basebandSink->setVideoTabIndex(videoTabIndex); }
uint32_t getNumberOfDeviceStreams() const;
@ -117,6 +140,7 @@ private: @@ -117,6 +140,7 @@ private:
virtual bool handleMessage(const Message& cmd);
void applySettings(const QStringList& settingsKeys, const ATVDemodSettings& settings, bool force = false);
void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response);
private slots:
void handleIndexInDeviceSetChanged(int index);

5
plugins/channelrx/demodatv/atvdemodbaseband.h

@ -74,6 +74,11 @@ public: @@ -74,6 +74,11 @@ public:
ScopeVis *getScopeSink() { return &m_scopeSink; }
void setTVScreen(TVScreenAnalog *tvScreen) { m_sink.setTVScreen(tvScreen); }
bool getBFOLocked() { return m_sink.getBFOLocked(); }
bool getColourLocked() const { return m_sink.getColourLocked(); }
float getBurstAmplitude() const { return m_sink.getBurstAmplitude(); }
float getCarrierFrequencyError() const { return m_sink.getCarrierFrequencyError(); }
float getGhostDelay() const { return m_sink.getGhostDelay(); }
float getGhostAmplitude() const { return m_sink.getGhostAmplitude(); }
void setVideoTabIndex(int videoTabIndex) { m_sink.setVideoTabIndex(videoTabIndex); }
void setBasebandSampleRate(int sampleRate); //!< To be used when supporting thread is stopped
bool isRunning() const { return m_running; }

201
plugins/channelrx/demodatv/atvdemodgui.cpp

@ -18,6 +18,9 @@ @@ -18,6 +18,9 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include <QDockWidget>
#include <QMainWindow>
@ -112,6 +115,17 @@ void ATVDemodGUI::displaySettings() @@ -112,6 +115,17 @@ void ATVDemodGUI::displaySettings()
lineTimeUpdate();
topTimeUpdate();
//********** Colour values **********
ui->colourSystem->setCurrentIndex((int) m_settings.m_colourSystem);
ui->colourSaturation->setValue(m_settings.m_colourSaturation);
ui->colourSaturationText->setText(QString("%1%").arg(m_settings.m_colourSaturation));
ui->colourHue->setValue(m_settings.m_colourHue);
ui->colourHueText->setText(QString("%1%2").arg(m_settings.m_colourHue).arg(QChar(0xB0)));
ui->palDelayLine->setChecked(m_settings.m_palDelayLine);
ui->noiseReduction->setValue(m_settings.m_noiseReduction);
ui->noiseReductionText->setText(QString("%1%").arg(m_settings.m_noiseReduction));
ui->ghostCancellation->setChecked(m_settings.m_ghostCancellation);
//********** RF values **********
ui->deltaFrequency->setValue(m_settings.m_inputFrequencyOffset);
ui->rfFiltering->setChecked(m_settings.m_fftFiltering);
@ -146,17 +160,20 @@ void ATVDemodGUI::displayRFBandwidths() @@ -146,17 +160,20 @@ void ATVDemodGUI::displayRFBandwidths()
void ATVDemodGUI::applySampleRate()
{
qDebug("ATVDemodGUI::applySampleRate");
unsigned int nbPointsPerLine;
ATVDemodSettings::getBaseValues(m_basebandSampleRate, m_settings.m_fps*m_settings.m_nbLines, nbPointsPerLine);
float samplesPerLineFrac = (float) m_basebandSampleRate / (m_settings.m_nbLines * m_settings.m_fps) - nbPointsPerLine;
ui->tvSampleRateText->setText(tr("%1k").arg(m_basebandSampleRate/1000.0f, 0, 'f', 2));
// Colour AM is upsampled, so the video can be at a higher rate than the channel
int videoSampleRate = m_settings.getVideoSampleRate(m_basebandSampleRate);
float lineFrequency = m_settings.getLineFrequency();
unsigned int nbPointsPerLine = (unsigned int) (videoSampleRate / lineFrequency);
float samplesPerLineFrac = videoSampleRate / lineFrequency - nbPointsPerLine;
ui->tvSampleRateText->setText(tr("%1k").arg(videoSampleRate/1000.0f, 0, 'f', 2));
ui->nbPointsPerLineText->setText(tr("%1p+%2").arg(nbPointsPerLine).arg(samplesPerLineFrac, 0, 'f', 2));
m_scopeVis->setLiveRate(m_basebandSampleRate);
m_scopeVis->setLiveRate(videoSampleRate);
setRFFiltersSlidersRange(m_basebandSampleRate);
displayRFBandwidths();
lineTimeUpdate();
topTimeUpdate();
setChannelMarkerBandwidth();
updateColourStatus();
}
bool ATVDemodGUI::handleMessage(const Message& message)
@ -173,6 +190,20 @@ bool ATVDemodGUI::handleMessage(const Message& message) @@ -173,6 +190,20 @@ bool ATVDemodGUI::handleMessage(const Message& message)
return true;
}
else if (ATVDemod::MsgConfigureATVDemod::match(message))
{
const ATVDemod::MsgConfigureATVDemod& cfg = (const ATVDemod::MsgConfigureATVDemod&) message;
if (cfg.getForce()) {
m_settings = cfg.getSettings();
} else {
m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings());
}
displaySettings();
return true;
}
else
{
return false;
@ -184,6 +215,7 @@ void ATVDemodGUI::channelMarkerChangedByCursor() @@ -184,6 +215,7 @@ void ATVDemodGUI::channelMarkerChangedByCursor()
qDebug("ATVDemodGUI::channelMarkerChangedByCursor");
ui->deltaFrequency->setValue(m_channelMarker.getCenterFrequency());
m_settings.m_inputFrequencyOffset = m_channelMarker.getCenterFrequency();
updateColourStatus();
applySettings(QStringList("inputFrequencyOffset"), false);
}
@ -372,7 +404,19 @@ void ATVDemodGUI::setChannelMarkerBandwidth() @@ -372,7 +404,19 @@ void ATVDemodGUI::setChannelMarkerBandwidth()
ui->rfOppBW->blockSignals(true);
ui->modulation->blockSignals(true);
if (ui->rfFiltering->isChecked()) // FFT filter
if (m_settings.usesVSBFrontEnd()) // VSB filter: Nyquist slope through the carrier to the top of the video (for mono, at most half the sample rate)
{
float videoBandwidth = m_settings.getVideoBandwidth();
if (!m_settings.isColour()) {
videoBandwidth = std::min(videoBandwidth, m_basebandSampleRate / 2.0f);
}
m_channelMarker.setBandwidth(videoBandwidth);
m_channelMarker.setOppositeBandwidth(0.3e6f);
m_channelMarker.setSidebands(m_settings.m_atvModulation == ATVDemodSettings::ATV_LSB ? ChannelMarker::vlsb : ChannelMarker::vusb);
}
else if (ui->rfFiltering->isChecked()) // FFT filter
{
m_channelMarker.setBandwidth(ui->rfBW->value()*m_rfSliderDivisor);
m_channelMarker.setOppositeBandwidth(ui->rfOppBW->value()*m_rfSliderDivisor);
@ -456,6 +500,20 @@ void ATVDemodGUI::tick() @@ -456,6 +500,20 @@ void ATVDemodGUI::tick()
} else {
ui->bfoLockedLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }");
}
if (m_atvDemod->getColourLocked()) {
ui->colourLockedLabel->setStyleSheet("QLabel { background-color : green; }");
} else {
ui->colourLockedLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }");
}
float ghostAmplitude = m_atvDemod->getGhostAmplitude();
if (m_settings.m_ghostCancellation && (ghostAmplitude > 0.0f)) {
ui->ghostText->setText(QString("%1%2s %3%").arg(m_atvDemod->getGhostDelay() * 1e6f, 0, 'f', 1).arg(QChar(0xB5)).arg((int) std::round(ghostAmplitude * 100.0f)));
} else {
ui->ghostText->setText("");
}
}
m_intTickCount = 0;
@ -493,6 +551,7 @@ void ATVDemodGUI::on_vSync_clicked() @@ -493,6 +551,7 @@ void ATVDemodGUI::on_vSync_clicked()
void ATVDemodGUI::on_invertVideo_clicked()
{
m_settings.m_invertVideo = ui->invertVideo->isChecked();
updateColourStatus();
applySettings(QStringList("invertVideo"), false);
}
@ -532,7 +591,7 @@ void ATVDemodGUI::on_modulation_currentIndexChanged(int index) @@ -532,7 +591,7 @@ void ATVDemodGUI::on_modulation_currentIndexChanged(int index)
{
m_settings.m_atvModulation = (ATVDemodSettings::ATVModulation) index;
setRFFiltersSlidersRange(m_basebandSampleRate);
setChannelMarkerBandwidth();
applySampleRate();
applySettings(QStringList("atvModulation"), false);
}
@ -557,6 +616,7 @@ void ATVDemodGUI::on_rfFiltering_toggled(bool checked) @@ -557,6 +616,7 @@ void ATVDemodGUI::on_rfFiltering_toggled(bool checked)
m_settings.m_fftFiltering = checked;
setRFFiltersSlidersRange(m_basebandSampleRate);
setChannelMarkerBandwidth();
updateColourStatus();
applySettings(QStringList("fftFiltering"), false);
}
@ -565,6 +625,7 @@ void ATVDemodGUI::on_deltaFrequency_changed(qint64 value) @@ -565,6 +625,7 @@ void ATVDemodGUI::on_deltaFrequency_changed(qint64 value)
m_settings.m_inputFrequencyOffset = value;
m_channelMarker.setCenterFrequency(value);
updateAbsoluteCenterFrequency();
updateColourStatus();
applySettings(QStringList("inputFrequencyOffset"), false);
}
@ -603,9 +664,125 @@ void ATVDemodGUI::on_screenTabWidget_currentChanged(int index) @@ -603,9 +664,125 @@ void ATVDemodGUI::on_screenTabWidget_currentChanged(int index)
m_atvDemod->setVideoTabIndex(index);
}
void ATVDemodGUI::on_colourSystem_currentIndexChanged(int index)
{
m_settings.m_colourSystem = (ATVDemodSettings::ColourSystem) index;
applySampleRate();
applySettings(QStringList("colourSystem"), false);
}
void ATVDemodGUI::on_colourSaturation_valueChanged(int value)
{
m_settings.m_colourSaturation = value;
ui->colourSaturationText->setText(QString("%1%").arg(value));
applySettings(QStringList("colourSaturation"), false);
}
void ATVDemodGUI::on_colourHue_valueChanged(int value)
{
m_settings.m_colourHue = value;
ui->colourHueText->setText(QString("%1%2").arg(value).arg(QChar(0xB0)));
applySettings(QStringList("colourHue"), false);
}
void ATVDemodGUI::on_palDelayLine_clicked()
{
m_settings.m_palDelayLine = ui->palDelayLine->isChecked();
applySettings(QStringList("palDelayLine"), false);
}
void ATVDemodGUI::on_ghostCancellation_clicked()
{
m_settings.m_ghostCancellation = ui->ghostCancellation->isChecked();
applySettings(QStringList("ghostCancellation"), false);
}
void ATVDemodGUI::on_noiseReduction_valueChanged(int value)
{
m_settings.m_noiseReduction = value;
ui->noiseReductionText->setText(QString("%1%").arg(value));
applySettings(QStringList("noiseReduction"), false);
}
// Shows whether the sample rate and tuning cover the colour subcarrier
void ATVDemodGUI::updateColourStatus()
{
bool colour = m_settings.isColour();
ui->colourSaturation->setEnabled(colour);
ui->colourHue->setEnabled(colour && !m_settings.isPAL());
ui->palDelayLine->setEnabled(colour);
ui->ghostCancellation->setEnabled(m_settings.usesVSBFrontEnd() && m_settings.m_invertVideo);
if (!colour)
{
ui->colourStatusText->setText("");
ui->colourStatusText->setToolTip("");
return;
}
float subcarrier = ATVDemodSettings::getSubcarrierFrequency(m_settings.m_colourSystem);
float halfRate = m_basebandSampleRate / 2.0f;
QString problem;
if (m_settings.usesVSBFrontEnd())
{
// From just below the vision carrier to the top of the chroma, relative to the device centre
float span = ATVDemodSettings::getColourBandwidth(m_settings.m_colourSystem);
float low, high;
if (m_settings.m_atvModulation == ATVDemodSettings::ATV_LSB)
{
low = m_settings.m_inputFrequencyOffset - (subcarrier + 0.6e6f);
high = m_settings.m_inputFrequencyOffset + 0.3e6f;
}
else
{
low = m_settings.m_inputFrequencyOffset - 0.3e6f;
high = m_settings.m_inputFrequencyOffset + subcarrier + 0.6e6f;
}
if (span > m_basebandSampleRate) {
problem = tr("Needs %1 MS/s").arg(span / 1e6f, 0, 'f', 1);
} else if ((low < -halfRate) || (high > halfRate)) {
problem = tr("Chroma outside band");
}
}
else
{
// FM: the demodulated composite must extend to the top of the chroma
float minRate = 2.2f * (subcarrier + 0.6e6f);
if (m_basebandSampleRate < minRate) {
problem = tr("Needs %1 MS/s").arg(minRate / 1e6f, 0, 'f', 1);
}
}
if (problem.isEmpty())
{
ui->colourStatusText->setText(tr("OK"));
ui->colourStatusText->setStyleSheet("");
ui->colourStatusText->setToolTip(tr("The channel covers the colour subcarrier"));
}
else if (m_settings.usesVSBFrontEnd())
{
ui->colourStatusText->setText(problem);
ui->colourStatusText->setStyleSheet("QLabel { color: red; }");
ui->colourStatusText->setToolTip(
tr("The device needs to receive from 0.3 MHz below the vision carrier to %1 MHz above it. "
"Increase the sample rate, or move the device centre frequency towards the subcarrier")
.arg((subcarrier + 0.6e6f) / 1e6f, 0, 'f', 2));
}
else
{
ui->colourStatusText->setText(problem);
ui->colourStatusText->setStyleSheet("QLabel { color: red; }");
ui->colourStatusText->setToolTip(tr("The sample rate is too low for the demodulated video to include the colour subcarrier"));
}
}
void ATVDemodGUI::lineTimeUpdate()
{
float nominalLineTime = ATVDemodSettings::getNominalLineTime(m_settings.m_nbLines, m_settings.m_fps);
float nominalLineTime = 1.0f / m_settings.getLineFrequency();
if (nominalLineTime < 0.0)
ui->lineTimeText->setText("invalid");
@ -621,7 +798,7 @@ void ATVDemodGUI::lineTimeUpdate() @@ -621,7 +798,7 @@ void ATVDemodGUI::lineTimeUpdate()
void ATVDemodGUI::topTimeUpdate()
{
float nominalTopTime = ATVDemodSettings::getNominalLineTime(m_settings.m_nbLines, m_settings.m_fps) * (4.7f / 64.0f);
float nominalTopTime = (1.0f / m_settings.getLineFrequency()) * (4.7f / 64.0f);
if (nominalTopTime < 0.0)
ui->topTimeText->setText("invalid");
@ -657,6 +834,12 @@ void ATVDemodGUI::makeUIConnections() @@ -657,6 +834,12 @@ void ATVDemodGUI::makeUIConnections()
QObject::connect(ui->amScaleFactor, &QDial::valueChanged, this, &ATVDemodGUI::on_amScaleFactor_valueChanged);
QObject::connect(ui->amScaleOffset, &QDial::valueChanged, this, &ATVDemodGUI::on_amScaleOffset_valueChanged);
QObject::connect(ui->screenTabWidget, &QTabWidget::currentChanged, this, &ATVDemodGUI::on_screenTabWidget_currentChanged);
QObject::connect(ui->colourSystem, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ATVDemodGUI::on_colourSystem_currentIndexChanged);
QObject::connect(ui->colourSaturation, &QDial::valueChanged, this, &ATVDemodGUI::on_colourSaturation_valueChanged);
QObject::connect(ui->colourHue, &QDial::valueChanged, this, &ATVDemodGUI::on_colourHue_valueChanged);
QObject::connect(ui->palDelayLine, &QCheckBox::clicked, this, &ATVDemodGUI::on_palDelayLine_clicked);
QObject::connect(ui->ghostCancellation, &QCheckBox::clicked, this, &ATVDemodGUI::on_ghostCancellation_clicked);
QObject::connect(ui->noiseReduction, &QDial::valueChanged, this, &ATVDemodGUI::on_noiseReduction_valueChanged);
}
void ATVDemodGUI::updateAbsoluteCenterFrequency()

7
plugins/channelrx/demodatv/atvdemodgui.h

@ -99,6 +99,7 @@ private: @@ -99,6 +99,7 @@ private:
void setRFFiltersSlidersRange(int sampleRate);
void lineTimeUpdate();
void topTimeUpdate();
void updateColourStatus();
bool handleMessage(const Message& objMessage);
void makeUIConnections();
void updateAbsoluteCenterFrequency();
@ -131,6 +132,12 @@ private slots: @@ -131,6 +132,12 @@ private slots:
void on_amScaleFactor_valueChanged(int value);
void on_amScaleOffset_valueChanged(int value);
void on_screenTabWidget_currentChanged(int index);
void on_colourSystem_currentIndexChanged(int index);
void on_colourSaturation_valueChanged(int value);
void on_colourHue_valueChanged(int value);
void on_palDelayLine_clicked();
void on_noiseReduction_valueChanged(int value);
void on_ghostCancellation_clicked();
};
#endif // INCLUDE_ATVDEMODGUI_H

285
plugins/channelrx/demodatv/atvdemodgui.ui

@ -7,7 +7,7 @@ @@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>700</width>
<height>699</height>
<height>725</height>
</rect>
</property>
<property name="sizePolicy">
@ -575,13 +575,13 @@ @@ -575,13 +575,13 @@
<x>10</x>
<y>570</y>
<width>681</width>
<height>104</height>
<height>130</height>
</rect>
</property>
<property name="windowTitle">
<string>Video Settings</string>
</property>
<layout class="QVBoxLayout" name="tvSettingsLayout" stretch="0,0">
<layout class="QVBoxLayout" name="tvSettingsLayout" stretch="0,0,0">
<property name="spacing">
<number>2</number>
</property>
@ -831,6 +831,32 @@ @@ -831,6 +831,32 @@
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="ghostCancellation">
<property name="toolTip">
<string>Ghost cancellation: estimate an echo from multipath (from 1 to 4 us) from the sync pulses, and cancel it. AM with video inverted only</string>
</property>
<property name="text">
<string>Ghost</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="ghostText">
<property name="minimumSize">
<size>
<width>70</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>Delay and amplitude of the echo being cancelled</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
@ -862,6 +888,259 @@ @@ -862,6 +888,259 @@
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="colourLayout">
<item>
<widget class="QLabel" name="colourSystemLabel">
<property name="text">
<string>C:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="colourSystem">
<property name="toolTip">
<string>Colour system. Mono decodes luminance only and works at any sample rate. Colour needs the sample rate and tuning to cover from just below the vision carrier to above the colour subcarrier.</string>
</property>
<item>
<property name="text">
<string>Mono</string>
</property>
</item>
<item>
<property name="text">
<string>NTSC</string>
</property>
</item>
<item>
<property name="text">
<string>NTSC 4.43</string>
</property>
</item>
<item>
<property name="text">
<string>PAL</string>
</property>
</item>
<item>
<property name="text">
<string>PAL-M</string>
</property>
</item>
<item>
<property name="text">
<string>PAL-N</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLabel" name="colourLockedLabel">
<property name="minimumSize">
<size>
<width>30</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>Green when a colour burst is being received</string>
</property>
<property name="text">
<string>Burst</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="colourSaturationLabel">
<property name="text">
<string>Sat</string>
</property>
</widget>
</item>
<item>
<widget class="QDial" name="colourSaturation">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Colour saturation as % of nominal</string>
</property>
<property name="minimum">
<number>0</number>
</property>
<property name="maximum">
<number>200</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>100</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="colourSaturationText">
<property name="minimumSize">
<size>
<width>30</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>Colour saturation as % of nominal</string>
</property>
<property name="text">
<string>100%</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="colourHueLabel">
<property name="text">
<string>Hue</string>
</property>
</widget>
</item>
<item>
<widget class="QDial" name="colourHue">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Hue (tint) adjustment in degrees (NTSC only)</string>
</property>
<property name="minimum">
<number>-180</number>
</property>
<property name="maximum">
<number>180</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="colourHueText">
<property name="minimumSize">
<size>
<width>30</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>Hue (tint) adjustment in degrees (NTSC only)</string>
</property>
<property name="text">
<string>0°</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="palDelayLine">
<property name="toolTip">
<string>Delay line: average the colour of successive lines. For PAL this cancels phase errors; for both PAL and NTSC it halves the colour noise, for half the vertical colour resolution</string>
</property>
<property name="text">
<string>Delay line</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="noiseReductionLabel">
<property name="text">
<string>NR</string>
</property>
</widget>
</item>
<item>
<widget class="QDial" name="noiseReduction">
<property name="maximumSize">
<size>
<width>24</width>
<height>24</height>
</size>
</property>
<property name="toolTip">
<string>Temporal noise reduction: blends each pixel with the previous frame where the picture is still (0 is off)</string>
</property>
<property name="minimum">
<number>0</number>
</property>
<property name="maximum">
<number>100</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="noiseReductionText">
<property name="minimumSize">
<size>
<width>30</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>Temporal noise reduction strength (%)</string>
</property>
<property name="text">
<string>0%</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="colourStatusText">
<property name="toolTip">
<string>Whether the channel covers the colour subcarrier</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<spacer name="colourSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QGridLayout" name="slidersLayout">
<item row="0" column="1">

157
plugins/channelrx/demodatv/atvdemodsettings.cpp

@ -50,6 +50,12 @@ void ATVDemodSettings::resetToDefaults() @@ -50,6 +50,12 @@ void ATVDemodSettings::resetToDefaults()
m_halfFrames = false; // m_fltRatioOfRowsToDisplay = 1.0
m_levelSynchroTop = 0.15f;
m_levelBlack = 0.3f;
m_colourSystem = ColourMono;
m_colourSaturation = 100;
m_colourHue = 0;
m_palDelayLine = true;
m_noiseReduction = 0;
m_ghostCancellation = false;
m_rgbColor = QColor(255, 255, 255).rgb();
m_title = "ATV Demodulator";
m_udpAddress = "127.0.0.1";
@ -107,6 +113,12 @@ QByteArray ATVDemodSettings::serialize() const @@ -107,6 +113,12 @@ QByteArray ATVDemodSettings::serialize() const
s.writeS32(31, m_workspaceIndex);
s.writeBlob(32, m_geometryBytes);
s.writeBool(33, m_hidden);
s.writeS32(34, (int) m_colourSystem);
s.writeS32(35, m_colourSaturation);
s.writeS32(36, m_colourHue);
s.writeBool(37, m_palDelayLine);
s.writeS32(38, m_noiseReduction);
s.writeBool(39, m_ghostCancellation);
return s.final();
}
@ -187,6 +199,13 @@ bool ATVDemodSettings::deserialize(const QByteArray& arrData) @@ -187,6 +199,13 @@ bool ATVDemodSettings::deserialize(const QByteArray& arrData)
d.readS32(31, &m_workspaceIndex, 0);
d.readBlob(32, &m_geometryBytes);
d.readBool(33, &m_hidden, false);
d.readS32(34, &tmp, (int) ColourMono);
m_colourSystem = (tmp >= (int) ColourMono) && (tmp <= (int) ColourPALN) ? (ColourSystem) tmp : ColourMono;
d.readS32(35, &m_colourSaturation, 100);
d.readS32(36, &m_colourHue, 0);
d.readBool(37, &m_palDelayLine, true);
d.readS32(38, &m_noiseReduction, 0);
d.readBool(39, &m_ghostCancellation, false);
return true;
}
@ -399,6 +418,24 @@ void ATVDemodSettings::applySettings(const QStringList& settingsKeys, const ATVD @@ -399,6 +418,24 @@ void ATVDemodSettings::applySettings(const QStringList& settingsKeys, const ATVD
if (settingsKeys.contains("levelBlack")) {
m_levelBlack = settings.m_levelBlack;
}
if (settingsKeys.contains("colourSystem")) {
m_colourSystem = settings.m_colourSystem;
}
if (settingsKeys.contains("colourSaturation")) {
m_colourSaturation = settings.m_colourSaturation;
}
if (settingsKeys.contains("colourHue")) {
m_colourHue = settings.m_colourHue;
}
if (settingsKeys.contains("palDelayLine")) {
m_palDelayLine = settings.m_palDelayLine;
}
if (settingsKeys.contains("noiseReduction")) {
m_noiseReduction = settings.m_noiseReduction;
}
if (settingsKeys.contains("ghostCancellation")) {
m_ghostCancellation = settings.m_ghostCancellation;
}
if (settingsKeys.contains("rgbColor")) {
m_rgbColor = settings.m_rgbColor;
}
@ -495,6 +532,24 @@ QString ATVDemodSettings::getDebugString(const QStringList& settingsKeys, bool f @@ -495,6 +532,24 @@ QString ATVDemodSettings::getDebugString(const QStringList& settingsKeys, bool f
if (settingsKeys.contains("levelBlack") || force) {
ostr << " m_levelBlack: " << m_levelBlack;
}
if (settingsKeys.contains("colourSystem") || force) {
ostr << " m_colourSystem: " << m_colourSystem;
}
if (settingsKeys.contains("colourSaturation") || force) {
ostr << " m_colourSaturation: " << m_colourSaturation;
}
if (settingsKeys.contains("colourHue") || force) {
ostr << " m_colourHue: " << m_colourHue;
}
if (settingsKeys.contains("palDelayLine") || force) {
ostr << " m_palDelayLine: " << m_palDelayLine;
}
if (settingsKeys.contains("noiseReduction") || force) {
ostr << " m_noiseReduction: " << m_noiseReduction;
}
if (settingsKeys.contains("ghostCancellation") || force) {
ostr << " m_ghostCancellation: " << m_ghostCancellation;
}
if (settingsKeys.contains("rgbColor") || force) {
ostr << " m_rgbColor: " << m_rgbColor;
}
@ -567,3 +622,105 @@ void ATVDemodSettings::getBaseValues(int sampleRate, int linesPerSecond, uint32_ @@ -567,3 +622,105 @@ void ATVDemodSettings::getBaseValues(int sampleRate, int linesPerSecond, uint32_
nbPointsPerLine = sampleRate / linesPerSecond;
nbPointsPerLine = nbPointsPerLine == 0 ? 1 : nbPointsPerLine;
}
bool ATVDemodSettings::usesVSBFrontEnd() const
{
if (isColour()) {
return (m_atvModulation == ATV_AM) || (m_atvModulation == ATV_USB) || (m_atvModulation == ATV_LSB);
} else {
// The FFT filter, when enabled, replaces it (for double sideband AM, for example)
return (m_atvModulation == ATV_AM) && !m_fftFiltering;
}
}
float ATVDemodSettings::getLineFrequency() const
{
// 525 line colour systems run at 59.94 fields/s, which the integer fps setting cannot express
if (isColour() && (m_nbLines == 525)) {
return 4500000.0f / 286.0f;
} else {
return (float) (m_nbLines * m_fps);
}
}
int ATVDemodSettings::getVideoSampleRate(int channelSampleRate) const
{
if (isColour() && usesVSBFrontEnd()) {
return channelSampleRate * getColourUpsampling(channelSampleRate, m_colourSystem);
} else {
return channelSampleRate;
}
}
float ATVDemodSettings::getSubcarrierFrequency(ColourSystem colourSystem)
{
switch (colourSystem)
{
case ColourNTSC:
return 315.0e6f / 88.0f; // 3.579545 MHz
case ColourPALM:
return 3575611.49f;
case ColourPALN:
return 3582056.25f;
case ColourNTSC443:
case ColourPAL:
return 4433618.75f;
case ColourMono:
default:
return 0.0f;
}
}
float ATVDemodSettings::getWhiteCarrier(ColourSystem colourSystem)
{
// 12.5% for 525 line systems, 10% for 625 line systems
if ((colourSystem == ColourNTSC) || (colourSystem == ColourPALM)) {
return 0.125f;
} else {
return 0.1f;
}
}
float ATVDemodSettings::getWhiteCarrier() const
{
if (isColour()) {
return getWhiteCarrier(m_colourSystem);
} else {
return m_nbLines == 525 ? 0.125f : 0.1f;
}
}
float ATVDemodSettings::getVideoBandwidth() const
{
if (isColour()) {
return getSubcarrierFrequency(m_colourSystem) + 0.6e6f; // Top of the upper chroma sideband
} else {
return m_nbLines == 525 ? 4.2e6f : 5.0e6f; // Below the sound carrier
}
}
float ATVDemodSettings::getColourBandwidth(ColourSystem colourSystem)
{
// 0.3 MHz below the vision carrier (Nyquist slope) to 0.6 MHz above the subcarrier (upper chroma sideband)
return getSubcarrierFrequency(colourSystem) + 0.9e6f;
}
float ATVDemodSettings::getColourBandCentreOffset(ColourSystem colourSystem)
{
return (getSubcarrierFrequency(colourSystem) + 0.3e6f) / 2.0f;
}
int ATVDemodSettings::getColourUpsampling(int sampleRate, ColourSystem colourSystem)
{
// The envelope of the VSB signal is real and extends to the top of the chroma,
// so it needs a sample rate a little over twice that
float minRate = 2.2f * (getSubcarrierFrequency(colourSystem) + 0.6e6f);
if (sampleRate >= minRate) {
return 1;
} else if (2 * sampleRate >= minRate) {
return 2;
} else {
return 4;
}
}

31
plugins/channelrx/demodatv/atvdemodsettings.h

@ -46,6 +46,16 @@ struct ATVDemodSettings @@ -46,6 +46,16 @@ struct ATVDemodSettings
ATVStdHSkip
};
enum ColourSystem
{
ColourMono, //!< Luminance only (any sample rate)
ColourNTSC, //!< NTSC-M, 3.579545 MHz subcarrier
ColourNTSC443,//!< NTSC with 4.43361875 MHz subcarrier
ColourPAL, //!< PAL-B/G/D/K/I, 4.43361875 MHz subcarrier
ColourPALM, //!< PAL-M, 3.57561149 MHz subcarrier
ColourPALN //!< PAL-N, 3.58205625 MHz subcarrier
};
// RF settings
qint64 m_inputFrequencyOffset; //!< Offset from baseband center frequency
int m_bfoFrequency; //!< BFO frequency (Hz)
@ -68,6 +78,14 @@ struct ATVDemodSettings @@ -68,6 +78,14 @@ struct ATVDemodSettings
float m_levelSynchroTop; //!< Horizontal synchronization top level (0.0 to 1.0 scale)
float m_levelBlack; //!< Black level (0.0 to 1.0 scale)
// Colour settings
ColourSystem m_colourSystem; //!< Colour decoding (mono decodes luminance only)
int m_colourSaturation; //!< Saturation in % of nominal
int m_colourHue; //!< Hue adjustment in degrees (NTSC only)
bool m_palDelayLine; //!< Average chroma of successive lines (PAL delay line, also used for NTSC)
int m_noiseReduction; //!< Temporal noise reduction strength in % (0 is off)
bool m_ghostCancellation; //!< Estimate and cancel an echo from multipath (AM through the VSB front end)
// common channel settings
quint32 m_rgbColor;
QString m_title;
@ -103,6 +121,19 @@ struct ATVDemodSettings @@ -103,6 +121,19 @@ struct ATVDemodSettings
static float getNominalLineTime(int nbLines, int fps);
static float getRFBandwidthDivisor(ATVModulation modulation);
static void getBaseValues(int sampleRate, int linesPerSecond, uint32_t& nbPointsPerLine);
bool isColour() const { return m_colourSystem != ColourMono; }
bool isPAL() const { return (m_colourSystem == ColourPAL) || (m_colourSystem == ColourPALM) || (m_colourSystem == ColourPALN); }
bool usesVSBFrontEnd() const; //!< AM goes through the VSB filter (and for colour, the upsampler)
float getLineFrequency() const; //!< Lines per second, exact for 525 line colour systems
int getVideoSampleRate(int channelSampleRate) const; //!< Rate the video is processed at
static float getSubcarrierFrequency(ColourSystem colourSystem);
static float getWhiteCarrier(ColourSystem colourSystem); //!< Peak white carrier as a fraction of sync tip (negative modulation)
float getWhiteCarrier() const; //!< As above, from the number of lines for mono
float getVideoBandwidth() const; //!< Top of the video above the vision carrier, for the VSB filter
static float getColourBandwidth(ColourSystem colourSystem); //!< RF span needed from just below the vision carrier to the top of the chroma
static float getColourBandCentreOffset(ColourSystem colourSystem); //!< Offset from the vision carrier to the centre of that span
static int getColourUpsampling(int sampleRate, ColourSystem colourSystem);
};
#endif /* PLUGINS_CHANNELRX_DEMODATV_ATVDEMODSETTINGS_H_ */

302
plugins/channelrx/demodatv/atvdemodsink.cpp

@ -19,6 +19,9 @@ @@ -19,6 +19,9 @@
#include <QTime>
#include <QDebug>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <complex.h>
@ -30,12 +33,14 @@ const int ATVDemodSink::m_ssbFftLen = 1024; @@ -30,12 +33,14 @@ const int ATVDemodSink::m_ssbFftLen = 1024;
ATVDemodSink::ATVDemodSink() :
m_channelSampleRate(1000000),
m_channelFrequencyOffset(0),
m_videoSampleRate(1000000),
m_samplesPerLine(100),
m_samplesPerLineFrac(0.0f),
m_videoTabIndex(0),
m_scopeSink(nullptr),
m_registeredTVScreen(nullptr),
m_numberSamplesPerHTop(0),
m_numberSamplesPerHSyncMin(1),
m_fieldIndex(0),
m_synchroSamples(0),
m_fieldDetectSampleCount(0),
@ -52,13 +57,33 @@ ATVDemodSink::ATVDemodSink() : @@ -52,13 +57,33 @@ ATVDemodSink::ATVDemodSink() :
m_lineIndex(0),
m_hSyncShift(0.0f),
m_hSyncErrorCount(0),
m_hSyncCandidate(false),
m_hSyncCandidateShift(0.0f),
m_hSyncCandidateAge(0),
m_hSyncCandidateBelow(0),
m_hSyncCandidateAbove(0),
prevSample(0.0f),
m_ampAverage(4800),
m_bfoPLL(200/1000000, 100/1000000, 0.01),
m_bfoFilter(200.0, 1000000.0, 0.9),
m_DSBFilter(nullptr),
m_DSBFilterBuffer(nullptr),
m_DSBFilterBufferIndex(0)
m_DSBFilterBufferIndex(0),
m_useNCO(false),
m_vsbFrontEnd(false),
m_carrierReferenced(false),
m_carrierVideoRange(1.0f),
m_envelopeLPAlpha(1.0f),
m_envelopeLP(0.0f),
m_envelopeLineMax(0.0f),
m_syncTipEnvelope(0.0f),
m_colourLineFirst(0),
m_colourLineStart(0),
m_videoSampleCount(0),
m_currentRow(-1),
m_syncFilterIndex(0),
m_syncFilterSum(0.0f),
m_syncFilterScale(1.0f)
{
qDebug("ATVDemodSink::ATVDemodSink");
//*************** ATV PARAMETERS ***************
@ -93,7 +118,7 @@ void ATVDemodSink::feed(const SampleVector::const_iterator& begin, const SampleV @@ -93,7 +118,7 @@ void ATVDemodSink::feed(const SampleVector::const_iterator& begin, const SampleV
{
Complex c(it->real(), it->imag());
if (m_settings.m_inputFrequencyOffset != 0) {
if (m_useNCO) {
c *= m_nco.nextIQ();
}
@ -115,7 +140,44 @@ void ATVDemodSink::demod(Complex& c) @@ -115,7 +140,44 @@ void ATVDemodSink::demod(Complex& c)
float sampleNormQ;
float sampleNorm;
float sample;
int sampleVideo;
//********** AM / VSB **********
if (m_vsbFrontEnd)
{
m_magSqAverage(c.real()*c.real() + c.imag()*c.imag());
Complex *filtered;
int n_out = m_vsbFilter.process(c, &filtered);
for (int i = 0; i < n_out; i++)
{
if (m_carrierReferenced)
{
// Scale from the carrier as a TV does: sync tip 0, peak white 1. The sync tip
// is the peak of the smoothed envelope, tracked line by line
float envelope = m_synchronousDetector.process(filtered[i]);
if (m_settings.m_ghostCancellation && m_ghostEstimator.feed(m_sampleOffset, m_synchronousDetector.getGhostInput())) {
m_synchronousDetector.setGhost(m_ghostEstimator.getDelay(), m_ghostEstimator.getGain());
}
m_envelopeLP += m_envelopeLPAlpha * (envelope - m_envelopeLP);
m_envelopeLineMax = std::max(m_envelopeLineMax, m_envelopeLP);
float video = m_syncTipEnvelope > 0.0f ? (m_syncTipEnvelope - envelope) / (m_syncTipEnvelope * m_carrierVideoRange) : 0.0f;
processVideo(video, envelope);
}
else
{
// Same AGC as AM
float envelope = std::abs(filtered[i]);
float sampleRaw = envelope / SDR_RX_SCALEF;
m_ampAverage(sampleRaw);
processVideo(sampleRaw / (2.0f * (float) m_ampAverage.instantAverage()), envelope);
}
}
return;
}
//********** FFT filtering **********
@ -206,7 +268,7 @@ void ATVDemodSink::demod(Complex& c) @@ -206,7 +268,7 @@ void ATVDemodSink::demod(Complex& c)
sampleNorm = sqrt(magSq);
float sampleRaw = sampleNorm / SDR_RX_SCALEF;
m_ampAverage(sampleRaw);
sample = sampleRaw / (2.0f * m_ampAverage.asFloat()); // AGC
sample = sampleRaw / (2.0f * (float) m_ampAverage.instantAverage()); // AGC (average of what has arrived, while the window fills)
}
else if ((m_settings.m_atvModulation == ATVDemodSettings::ATV_USB) || (m_settings.m_atvModulation == ATVDemodSettings::ATV_LSB))
{
@ -244,11 +306,19 @@ void ATVDemodSink::demod(Complex& c) @@ -244,11 +306,19 @@ void ATVDemodSink::demod(Complex& c)
sample = 0.0f;
}
processVideo(sample, 0.0f);
}
void ATVDemodSink::processVideo(float sample, float envelope)
{
int sampleVideo;
//********** AM sample normalization and coarse scale estimation **********
if ((m_settings.m_atvModulation == ATVDemodSettings::ATV_AM)
if (!m_carrierReferenced &&
((m_settings.m_atvModulation == ATVDemodSettings::ATV_AM)
|| (m_settings.m_atvModulation == ATVDemodSettings::ATV_USB)
|| (m_settings.m_atvModulation == ATVDemodSettings::ATV_LSB))
|| (m_settings.m_atvModulation == ATVDemodSettings::ATV_LSB)))
{
// Mini and Maxi Amplitude tracking
@ -293,7 +363,11 @@ void ATVDemodSink::demod(Complex& c) @@ -293,7 +363,11 @@ void ATVDemodSink::demod(Complex& c)
sample /= m_ampDelta;
}
sample = m_settings.m_invertVideo ? 1.0f - sample : sample;
if (!m_carrierReferenced) { // already scaled with sync tip low
sample = m_settings.m_invertVideo ? 1.0f - sample : sample;
}
float composite = sample; // colour needs the chroma excursions beyond black and white
// 0.0 -> 1.0
sample = (sample < 0.0f) ? 0.0f : (sample > 1.0f) ? 1.0f : sample;
@ -312,7 +386,46 @@ void ATVDemodSink::demod(Complex& c) @@ -312,7 +386,46 @@ void ATVDemodSink::demod(Complex& c)
if (m_registeredTVScreen) // can process only if the screen is available (set via the GUI)
{
processSample(sample, sampleVideo);
if (m_settings.isColour() && (m_sampleOffset >= 0) && (m_sampleOffset < m_samplesPerLine))
{
m_colourLine[m_sampleOffset] = m_carrierReferenced ? envelope : composite;
m_colourLineFirst = std::min(m_colourLineFirst, m_sampleOffset);
m_colourLineStart = m_videoSampleCount - m_sampleOffset;
}
m_videoSampleCount++;
if (m_syncFilter.size() > 1)
{
// Sync is sliced with the colour subcarrier removed, as a TV's sync separator does
m_syncFilterSum += composite - m_syncFilter[m_syncFilterIndex];
m_syncFilter[m_syncFilterIndex] = composite;
m_syncFilterIndex = m_syncFilterIndex + 1 == (int) m_syncFilter.size() ? 0 : m_syncFilterIndex + 1;
float syncSample = m_syncFilterSum * m_syncFilterScale;
processSample(syncSample, sampleVideo);
}
else
{
processSample(sample, sampleVideo);
}
}
}
// Writes a line held in m_lineRGB to the screen: decoding colour first, and reducing noise
void ATVDemodSink::writeLine()
{
if (m_settings.isColour())
{
m_colourDecoder.decodeLine(m_colourLine.data(), m_samplesPerLine, m_colourLineFirst, m_colourLineStart, m_lineRGB.data());
m_colourLineFirst = m_samplesPerLine;
}
if (m_noiseReduction.isEnabled()) {
m_noiseReduction.processRow(m_currentRow, &m_lineRGB[m_numberSamplesPerHSync]);
}
for (int i = std::max(m_numberSamplesPerHSync - 2, 0); i < m_samplesPerLine; i++) {
m_tvScreenBuffer->setSampleValue(i - m_numberSamplesPerHSync, (int) m_lineRGB[i]);
}
}
@ -375,6 +488,7 @@ void ATVDemodSink::applyStandard(int sampleRate, ATVDemodSettings::ATVStd atvStd @@ -375,6 +488,7 @@ void ATVDemodSink::applyStandard(int sampleRate, ATVDemodSettings::ATVStd atvStd
m_numberSamplesPerLineSignals = (int)(lineDuration * sampleRate * 12.0 / 64.0); // "a", Line-blanking interval
m_numberSamplesPerHSync = (int)(lineDuration * sampleRate * 10.5 / 64.0); // "b", Interval between time datum and back edge of line-blanking pulse
m_numberSamplesPerHTop = (int)(lineDuration * sampleRate * 4.7 / 64.0); // "d", Duration of synchronizing pulse
m_numberSamplesPerHSyncMin = std::max(1, (int) std::round(lineDuration * sampleRate * 1.0 / 64.0)); // shorter than an equalizing pulse, longer than ringing
// Table 3. Details of field synchronizing signals
float hl = 32.0f; // half of the line
@ -418,20 +532,10 @@ void ATVDemodSink::applyChannelSettings(int channelSampleRate, int channelFreque @@ -418,20 +532,10 @@ void ATVDemodSink::applyChannelSettings(int channelSampleRate, int channelFreque
return;
}
if ((channelFrequencyOffset != m_channelFrequencyOffset) ||
(channelSampleRate != m_channelSampleRate) || force)
{
m_nco.setFreq(-channelFrequencyOffset, channelSampleRate);
}
if ((channelSampleRate != m_channelSampleRate) || force)
{
unsigned int samplesPerLineNom;
ATVDemodSettings::getBaseValues(channelSampleRate, m_settings.m_nbLines * m_settings.m_fps, samplesPerLineNom);
m_samplesPerLine = samplesPerLineNom;
m_samplesPerLineFrac = (float)channelSampleRate / (m_settings.m_nbLines * m_settings.m_fps) - m_samplesPerLine;
qDebug() << "ATVDemodSink::applyChannelSettings:"
<< " m_channelSampleRate: " << m_channelSampleRate
<< " m_channelSampleRate: " << channelSampleRate
<< " m_fftBandwidth: " << m_settings.m_fftBandwidth
<< " m_fftOppBandwidth:" << m_settings.m_fftOppBandwidth
<< " m_bfoFrequency: " << m_settings.m_bfoFrequency;
@ -451,7 +555,94 @@ void ATVDemodSink::applyChannelSettings(int channelSampleRate, int channelFreque @@ -451,7 +555,94 @@ void ATVDemodSink::applyChannelSettings(int channelSampleRate, int channelFreque
m_bfoFilter.setFrequencies(m_channelSampleRate, m_settings.m_bfoFrequency);
}
applyStandard(m_channelSampleRate, m_settings.m_atvStd, ATVDemodSettings::getNominalLineTime(m_settings.m_nbLines, m_settings.m_fps));
m_channelSampleRate = channelSampleRate;
m_channelFrequencyOffset = channelFrequencyOffset;
applyVideoSettings();
}
void ATVDemodSink::applyVideoSettings()
{
m_vsbFrontEnd = m_settings.usesVSBFrontEnd();
m_videoSampleRate = m_settings.getVideoSampleRate(m_channelSampleRate);
float lineFrequency = m_settings.getLineFrequency();
m_samplesPerLine = (int) (m_videoSampleRate / lineFrequency);
m_samplesPerLine = m_samplesPerLine < 1 ? 1 : m_samplesPerLine;
m_samplesPerLineFrac = m_videoSampleRate / lineFrequency - m_samplesPerLine;
m_ampAverage.resize(m_samplesPerLine * m_settings.m_nbLines * 2); // AGC average in two full images
qDebug() << "ATVDemodSink::applyVideoSettings:"
<< " m_channelSampleRate: " << m_channelSampleRate
<< " m_videoSampleRate: " << m_videoSampleRate
<< " m_samplesPerLine:" << m_samplesPerLine
<< " m_samplesPerLineFrac:" << m_samplesPerLineFrac;
applyStandard(m_videoSampleRate, m_settings.m_atvStd, 1.0f / lineFrequency);
// For colour, the VSB front end needs the centre of the video band, not the vision carrier,
// at DC, or the top of the chroma wraps round when the sample rate is only just wide enough.
// Mono is not upsampled, so keeps the carrier at DC and the video is limited to half the rate
float shift = 0.0f;
if (m_vsbFrontEnd)
{
bool usb = m_settings.m_atvModulation != ATVDemodSettings::ATV_LSB;
if (m_settings.isColour())
{
float centreOffset = ATVDemodSettings::getColourBandCentreOffset(m_settings.m_colourSystem);
shift = usb ? centreOffset : -centreOffset;
}
m_vsbFilter.configure(
m_channelSampleRate,
-shift,
m_settings.getVideoBandwidth(),
usb,
m_videoSampleRate / m_channelSampleRate
);
m_synchronousDetector.configure(m_videoSampleRate, -shift, lineFrequency);
}
m_ghostEstimator.configure(m_videoSampleRate, m_samplesPerLine, std::min(m_settings.getVideoBandwidth(), m_videoSampleRate / 2.0f));
m_nco.setFreq(-(m_channelFrequencyOffset + shift), m_channelSampleRate);
m_useNCO = (m_channelFrequencyOffset != 0) || (shift != 0.0f);
// For negatively modulated AM, levels are taken from the carrier
m_carrierReferenced = m_vsbFrontEnd && m_settings.m_invertVideo;
m_carrierVideoRange = 1.0f - m_settings.getWhiteCarrier();
m_envelopeLPAlpha = 1.0f / (0.5e-6f * m_videoSampleRate); // ~0.5 us, so noise does not set the peak
m_envelopeLP = 0.0f;
m_envelopeLineMax = 0.0f;
m_syncTipEnvelope = 0.0f;
if (m_settings.isColour())
{
m_colourDecoder.configure(m_videoSampleRate, m_settings.m_colourSystem);
m_colourDecoder.setCarrierReferenced(m_carrierReferenced);
m_colourLine.assign(m_samplesPerLine, 0.0f);
m_colourLineFirst = m_samplesPerLine;
}
// The subcarrier is in the video when decoding colour, and in mono when the rate is high enough
if (m_settings.isColour() || m_vsbFrontEnd)
{
float subcarrier = m_settings.isColour() ? ATVDemodSettings::getSubcarrierFrequency(m_settings.m_colourSystem)
: ATVDemodSettings::getSubcarrierFrequency(m_settings.m_nbLines == 525 ? ATVDemodSettings::ColourNTSC : ATVDemodSettings::ColourPAL);
m_syncFilter.assign(std::max(1, (int) std::round(m_videoSampleRate / subcarrier)), 0.0f);
}
else
{
m_syncFilter.assign(1, 0.0f);
}
m_syncFilterIndex = 0;
m_syncFilterSum = 0.0f;
m_syncFilterScale = 1.0f / m_syncFilter.size();
m_lineRGB.assign(m_samplesPerLine, 0);
m_noiseReduction.configure(m_samplesPerLine - m_numberSamplesPerLineSignals, m_settings.m_nbLines - m_numberOfBlackLines);
if (m_registeredTVScreen)
{
@ -459,13 +650,11 @@ void ATVDemodSink::applyChannelSettings(int channelSampleRate, int channelFreque @@ -459,13 +650,11 @@ void ATVDemodSink::applyChannelSettings(int channelSampleRate, int channelFreque
m_samplesPerLine - m_numberSamplesPerLineSignals,
m_settings.m_nbLines - m_numberOfBlackLines
);
m_tvScreenBuffer = m_registeredTVScreen->getBackBuffer();
m_tvScreenBuffer = m_registeredTVScreen->getBackBuffer();
}
m_fieldIndex = 0;
m_channelSampleRate = channelSampleRate;
m_channelFrequencyOffset = channelFrequencyOffset;
m_amSampleIndex = 0;
}
void ATVDemodSink::applySettings(const QStringList& settingsKeys, const ATVDemodSettings& settings, bool force)
@ -490,45 +679,52 @@ void ATVDemodSink::applySettings(const QStringList& settingsKeys, const ATVDemod @@ -490,45 +679,52 @@ void ATVDemodSink::applySettings(const QStringList& settingsKeys, const ATVDemod
m_bfoFilter.setFrequencies(m_channelSampleRate, settings.m_bfoFrequency);
}
if (settingsKeys.contains("nbLines") || settingsKeys.contains("fps") || settingsKeys.contains("atvStd") || force)
{
unsigned int samplesPerLineNom;
ATVDemodSettings::getBaseValues(m_channelSampleRate, settings.m_nbLines * settings.m_fps, samplesPerLineNom);
m_samplesPerLine = samplesPerLineNom;
m_samplesPerLineFrac = (float)m_channelSampleRate / (settings.m_nbLines * settings.m_fps) - m_samplesPerLine;
m_ampAverage.resize(m_samplesPerLine * settings.m_nbLines * 2); // AGC average in two full images
qDebug() << "ATVDemodSink::applySettings:"
<< " m_channelSampleRate: " << m_channelSampleRate
<< " m_samplesPerLine:" << m_samplesPerLine
<< " m_samplesPerLineFrac:" << m_samplesPerLineFrac;
applyStandard(m_channelSampleRate, settings.m_atvStd,
ATVDemodSettings::getNominalLineTime(settings.m_nbLines, settings.m_fps));
if (m_registeredTVScreen)
{
m_registeredTVScreen->resizeTVScreen(
m_samplesPerLine - m_numberSamplesPerLineSignals,
settings.m_nbLines - m_numberOfBlackLines
);
m_tvScreenBuffer = m_registeredTVScreen->getBackBuffer();
}
m_fieldIndex = 0;
}
if (settingsKeys.contains("fmDeviation") || force) {
m_objPhaseDiscri.setFMScaling(1.0f / settings.m_fmDeviation);
}
if (settingsKeys.contains("levelBlack") || force) {
m_sampleRangeCorrection = 255.0f / (1.0f - m_settings.m_levelBlack);
m_sampleRangeCorrection = 255.0f / (1.0f - settings.m_levelBlack);
}
bool videoChanged = settingsKeys.contains("nbLines")
|| settingsKeys.contains("fps")
|| settingsKeys.contains("atvStd")
|| settingsKeys.contains("atvModulation")
|| settingsKeys.contains("colourSystem")
|| settingsKeys.contains("invertVideo")
|| settingsKeys.contains("fftFiltering")
|| force;
if (force) {
m_settings = settings;
} else {
m_settings.applySettings(settingsKeys, settings);
}
if (settingsKeys.contains("colourSaturation") || force) {
m_colourDecoder.setSaturation(m_settings.m_colourSaturation);
}
if (settingsKeys.contains("noiseReduction") || force) {
m_noiseReduction.setStrength(m_settings.m_noiseReduction);
}
if (settingsKeys.contains("colourHue") || force) {
m_colourDecoder.setHue(m_settings.m_colourHue);
}
if (settingsKeys.contains("palDelayLine") || force) {
m_colourDecoder.setDelayLine(m_settings.m_palDelayLine);
}
if ((settingsKeys.contains("ghostCancellation") || force) && !m_settings.m_ghostCancellation)
{
m_synchronousDetector.setGhost(1.0f, 0.0f);
m_ghostEstimator.reset();
}
if (videoChanged) {
applyVideoSettings();
}
}

136
plugins/channelrx/demodatv/atvdemodsink.h

@ -33,6 +33,9 @@ @@ -33,6 +33,9 @@
#include "gui/tvscreenanalog.h"
#include "atvdemodsettings.h"
#include "atvcolourdecoder.h"
#include "atvnoisereduction.h"
#include "atvghostestimator.h"
class ScopeVis;
@ -53,6 +56,12 @@ public: @@ -53,6 +56,12 @@ public:
}
double getMagSq() const { return m_magSqAverage; } //!< Beware this is scaled to 2^30
bool getBFOLocked();
bool getColourLocked() const { return m_settings.isColour() && m_colourDecoder.getColourLocked(); }
float getBurstAmplitude() const { return m_colourDecoder.getBurstAmplitude(); }
float getCarrierFrequencyError() const { return m_synchronousDetector.getFrequencyError(); } //!< Hz, for AM through the VSB filter
float getGhostDelay() const { return m_ghostEstimator.getDelaySeconds(); } //!< s, of the echo being cancelled
float getGhostAmplitude() const { return std::abs(m_ghostEstimator.getGain()); } //!< Relative to the signal, 0 when none
int getVideoSampleRate() const { return m_videoSampleRate; }
void setVideoTabIndex(int videoTabIndex) { m_videoTabIndex = videoTabIndex; }
void applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force = false);
@ -102,6 +111,7 @@ private: @@ -102,6 +111,7 @@ private:
int m_channelSampleRate;
int m_channelFrequencyOffset;
int m_videoSampleRate; //!< rate video is processed at (channel rate, upsampled for colour AM)
int m_samplesPerLine; //!< number of samples per complete line (includes sync signals) - adjusted value
float m_samplesPerLineFrac; //!< number of samples per complete line (includes sync signals), fractional part
ATVDemodSettings m_settings;
@ -118,6 +128,7 @@ private: @@ -118,6 +128,7 @@ private:
//int m_intNumberSamplePerLine;
int m_numberSamplesPerHTop; //!< number of samples per horizontal synchronization pulse (pulse in ultra-black) - integer value
int m_numberSamplesPerHSyncMin; //!< number of samples in sync after a falling edge for it to be taken as horizontal sync
int m_numberOfBlackLines; //!< this is the total number of lines not part of the image and is used for vertical screen size
int m_firstVisibleLine;
@ -163,6 +174,11 @@ private: @@ -163,6 +174,11 @@ private:
float m_hSyncShift;
int m_hSyncErrorCount;
bool m_hSyncCandidate; // a falling edge through the sync level is being checked
float m_hSyncCandidateShift;
int m_hSyncCandidateAge; // samples since the edge
int m_hSyncCandidateBelow; // samples in sync since the edge
int m_hSyncCandidateAbove; // consecutive samples out of sync
float prevSample;
@ -188,20 +204,64 @@ private: @@ -188,20 +204,64 @@ private:
// Used for FM
PhaseDiscriminators m_objPhaseDiscri;
bool m_useNCO;
//*************** COLOUR ***************
bool m_vsbFrontEnd; //!< AM / VSB: VSB filter (and for colour, upsampling) and envelope detection
bool m_carrierReferenced; //!< negative modulation AM through the VSB filter: levels from the carrier, not min / max
float m_carrierVideoRange; //!< 1 - white carrier level as a fraction of the sync tip
float m_envelopeLPAlpha;
float m_envelopeLP;
float m_envelopeLineMax;
float m_syncTipEnvelope; //!< tracked sync tip envelope
ATVVSBFrontEnd m_vsbFilter;
ATVSynchronousDetector m_synchronousDetector;
ATVColourDecoder m_colourDecoder;
std::vector<float> m_colourLine; //!< composite for the current line, index 0 at start of sync pulse
int m_colourLineFirst; //!< first index of m_colourLine written in the current line
int64_t m_colourLineStart; //!< video sample count at index 0 of the current line
int64_t m_videoSampleCount;
std::vector<unsigned int> m_lineRGB; //!< pixels of the current line, when written a whole line at a time
ATVNoiseReduction m_noiseReduction;
ATVGhostEstimator m_ghostEstimator;
int m_currentRow; //!< row of the TV screen being written
std::vector<float> m_syncFilter; //!< boxcar one colour subcarrier period long, so saturated colours do not reach the sync slicer
int m_syncFilterIndex;
float m_syncFilterSum;
float m_syncFilterScale;
void demod(Complex& c);
void processVideo(float sample, float envelope);
void applyStandard(int sampleRate, ATVDemodSettings::ATVStd atvStd, float lineDuration);
void applyVideoSettings();
void writeLine();
inline void processSample(float& sample, int& sampleVideo)
{
// Filling pixel on the current line - reference index 0 at start of sync pulse
m_tvScreenBuffer->setSampleValue(m_sampleOffset - m_numberSamplesPerHSync, sampleVideo);
// (colour is decoded, and noise reduced, a whole line at a time, at the end of the line)
if (!m_settings.isColour())
{
int grey = sampleVideo | (sampleVideo << 8) | (sampleVideo << 16);
if (!m_noiseReduction.isEnabled()) {
m_tvScreenBuffer->setSampleValue(m_sampleOffset - m_numberSamplesPerHSync, grey);
} else if ((m_sampleOffset >= 0) && (m_sampleOffset < m_samplesPerLine)) {
m_lineRGB[m_sampleOffset] = grey;
}
}
if (m_settings.m_hSync)
{
// Horizontal Synchro detection
// Horizontal Synchro detection: a falling edge through the sync level is only taken as sync
// once the signal has been below the level for m_numberSamplesPerHSyncMin samples,
// so the brief undershoot and ringing next to bright picture content are not mistaken for sync.
// Ringing on the pulse's own leading edge can take it back above the level briefly
if ((prevSample >= m_settings.m_levelSynchroTop &&
sample < m_settings.m_levelSynchroTop) // horizontal synchro detected
&& (m_sampleOffsetDetected > m_samplesPerLine - m_numberSamplesPerHTop))
sample < m_settings.m_levelSynchroTop) // horizontal synchro candidate
&& (m_sampleOffsetDetected > m_samplesPerLine - m_numberSamplesPerHTop)
&& !m_hSyncCandidate)
{
float sampleOffsetDetectedFrac =
(sample - m_settings.m_levelSynchroTop) / (prevSample - sample);
@ -211,26 +271,52 @@ private: @@ -211,26 +271,52 @@ private:
else if (hSyncShift < -m_samplesPerLine / 2)
hSyncShift += m_samplesPerLine;
if (fabs(hSyncShift) > m_numberSamplesPerHTop)
m_hSyncCandidate = true;
m_hSyncCandidateShift = hSyncShift;
m_hSyncCandidateAge = 0;
m_hSyncCandidateBelow = 0;
m_hSyncCandidateAbove = 0;
}
m_sampleOffsetDetected++;
if (m_hSyncCandidate)
{
m_hSyncCandidateAge++;
if (sample < m_settings.m_levelSynchroTop)
{
m_hSyncCandidateBelow++;
m_hSyncCandidateAbove = 0;
}
else if (++m_hSyncCandidateAbove > m_numberSamplesPerHSyncMin / 2)
{
m_hSyncCandidate = false; // not a sync pulse
}
if (m_hSyncCandidate && (m_hSyncCandidateBelow >= m_numberSamplesPerHSyncMin)) // horizontal synchro detected
{
m_hSyncErrorCount++;
if (m_hSyncErrorCount >= 4)
m_hSyncCandidate = false;
if (fabs(m_hSyncCandidateShift) > m_numberSamplesPerHTop)
{
// Fast sync: shift is too large, needs to be fixed ASAP
m_hSyncShift = hSyncShift;
m_hSyncErrorCount++;
if (m_hSyncErrorCount >= 4)
{
// Fast sync: shift is too large, needs to be fixed ASAP
m_hSyncShift = m_hSyncCandidateShift;
m_hSyncErrorCount = 0;
}
}
else
{
// Slow sync: slight adjustment is needed
m_hSyncShift = m_hSyncCandidateShift * 0.2f;
m_hSyncErrorCount = 0;
}
m_sampleOffsetDetected = m_hSyncCandidateAge - 1; // counted from the edge
}
else
{
// Slow sync: slight adjustment is needed
m_hSyncShift = hSyncShift * 0.2f;
m_hSyncErrorCount = 0;
}
m_sampleOffsetDetected = 0;
}
else
m_sampleOffsetDetected++;
}
m_sampleOffset++;
@ -245,6 +331,16 @@ private: @@ -245,6 +331,16 @@ private:
// end of line
if (m_sampleOffset >= m_samplesPerLine)
{
if (m_carrierReferenced)
{
m_syncTipEnvelope = m_syncTipEnvelope > 0.0f ? m_syncTipEnvelope + 0.1f * (m_envelopeLineMax - m_syncTipEnvelope) : m_envelopeLineMax;
m_envelopeLineMax = 0.0f;
}
if (m_settings.isColour() || m_noiseReduction.isEnabled()) {
writeLine();
}
float sampleOffsetFloat = m_hSyncShift + m_sampleOffsetFrac - m_samplesPerLineFrac;
m_sampleOffset = sampleOffsetFloat;
m_sampleOffsetFrac = sampleOffsetFloat - m_sampleOffset;
@ -267,6 +363,7 @@ private: @@ -267,6 +363,7 @@ private:
if (m_lineIndex == m_numberOfVSyncLines + 3 && m_fieldIndex == 0)
{
m_tvScreenBuffer = m_registeredTVScreen->swapBuffers();
m_noiseReduction.endFrame();
}
if (m_vSyncDetectSampleCount > m_vSyncDetectThreshold &&
@ -300,6 +397,7 @@ private: @@ -300,6 +397,7 @@ private:
rowIndex = rowIndex * 2 - m_fieldIndex;
m_tvScreenBuffer->selectRow(rowIndex, m_sampleOffsetFrac);
m_currentRow = rowIndex;
}
// Vertical sync is obtained by skipping horizontal sync on the line that triggers vertical sync (new frame)
@ -309,10 +407,12 @@ private: @@ -309,10 +407,12 @@ private:
|| (!m_settings.m_vSync && (m_lineIndex >= m_settings.m_nbLines))) // Vsync ignored and reached nominal number of lines per frame
{
m_tvScreenBuffer = m_registeredTVScreen->swapBuffers();
m_noiseReduction.endFrame();
m_lineIndex = 0;
}
m_tvScreenBuffer->selectRow(m_lineIndex, m_sampleOffsetFrac);
m_currentRow = m_lineIndex;
}
};

62
plugins/channelrx/demodatv/atvdemodwebapiadapter.cpp

@ -15,6 +15,8 @@ @@ -15,6 +15,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <QHash>
#include "SWGChannelSettings.h"
#include "atvdemodwebapiadapter.h"
@ -83,6 +85,12 @@ void ATVDemodWebAPIAdapter::webapiFormatChannelSettings( @@ -83,6 +85,12 @@ void ATVDemodWebAPIAdapter::webapiFormatChannelSettings(
response.getAtvDemodSettings()->setUdpAddress(new QString(settings.m_udpAddress));
}
response.getAtvDemodSettings()->setUdpPort(settings.m_udpPort);
response.getAtvDemodSettings()->setColourSystem((int) settings.m_colourSystem);
response.getAtvDemodSettings()->setColourSaturation(settings.m_colourSaturation);
response.getAtvDemodSettings()->setColourHue(settings.m_colourHue);
response.getAtvDemodSettings()->setPalDelayLine(settings.m_palDelayLine ? 1 : 0);
response.getAtvDemodSettings()->setNoiseReduction(settings.m_noiseReduction);
response.getAtvDemodSettings()->setGhostCancellation(settings.m_ghostCancellation ? 1 : 0);
}
void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings(
@ -114,6 +122,9 @@ void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings( @@ -114,6 +122,9 @@ void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings(
if (channelSettingsKeys.contains("fltFramePerS")) {
settings.m_fps = response.getAtvDemodSettings()->getFltFramePerS();
}
if (channelSettingsKeys.contains("fpsIndex")) {
settings.m_fps = ATVDemodSettings::getFps(response.getAtvDemodSettings()->getFpsIndex());
}
if (channelSettingsKeys.contains("fltRFBandwidth")) {
settings.m_fftBandwidth = response.getAtvDemodSettings()->getFltRfBandwidth();
}
@ -144,6 +155,9 @@ void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings( @@ -144,6 +155,9 @@ void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings(
if (channelSettingsKeys.contains("intNumberOfLines")) {
settings.m_nbLines = response.getAtvDemodSettings()->getIntNumberOfLines();
}
if (channelSettingsKeys.contains("nbLinesIndex")) {
settings.m_nbLines = ATVDemodSettings::getNumberOfLines(response.getAtvDemodSettings()->getNbLinesIndex());
}
if (channelSettingsKeys.contains("rgbColor")) {
settings.m_rgbColor = response.getAtvDemodSettings()->getRgbColor();
}
@ -156,4 +170,52 @@ void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings( @@ -156,4 +170,52 @@ void ATVDemodWebAPIAdapter::webapiUpdateChannelSettings(
if (channelSettingsKeys.contains("udpPort")) {
settings.m_udpPort = response.getAtvDemodSettings()->getUdpPort();
}
if (channelSettingsKeys.contains("colourSystem")) {
settings.m_colourSystem = (ATVDemodSettings::ColourSystem) response.getAtvDemodSettings()->getColourSystem();
}
if (channelSettingsKeys.contains("colourSaturation")) {
settings.m_colourSaturation = response.getAtvDemodSettings()->getColourSaturation();
}
if (channelSettingsKeys.contains("colourHue")) {
settings.m_colourHue = response.getAtvDemodSettings()->getColourHue();
}
if (channelSettingsKeys.contains("palDelayLine")) {
settings.m_palDelayLine = response.getAtvDemodSettings()->getPalDelayLine() != 0;
}
if (channelSettingsKeys.contains("noiseReduction")) {
settings.m_noiseReduction = response.getAtvDemodSettings()->getNoiseReduction();
}
if (channelSettingsKeys.contains("ghostCancellation")) {
settings.m_ghostCancellation = response.getAtvDemodSettings()->getGhostCancellation() != 0;
}
}
QStringList ATVDemodWebAPIAdapter::getSettingsKeys(const QStringList& channelSettingsKeys)
{
static const QHash<QString, QString> settingsKeys = {
{"blnFFTFiltering", "fftFiltering"},
{"blnHSync", "hSync"},
{"blnInvertVideo", "invertVideo"},
{"blnVSync", "vSync"},
{"enmATVStandard", "atvStd"},
{"enmModulation", "atvModulation"},
{"fltBFOFrequency", "bfoFrequency"},
{"fltFramePerS", "fps"},
{"fltRFBandwidth", "fftBandwidth"},
{"fltRFOppBandwidth", "fftOppBandwidth"},
{"fltVoltLevelSynchroBlack", "levelBlack"},
{"fltVoltLevelSynchroTop", "levelSynchroTop"},
{"fpsIndex", "fps"},
{"halfImage", "halfFrames"},
{"intFrequencyOffset", "inputFrequencyOffset"},
{"intNumberOfLines", "nbLines"},
{"nbLinesIndex", "nbLines"}
};
QStringList keys;
for (const auto& key : channelSettingsKeys) {
keys.append(settingsKeys.value(key, key));
}
return keys;
}

3
plugins/channelrx/demodatv/atvdemodwebapiadapter.h

@ -51,6 +51,9 @@ public: @@ -51,6 +51,9 @@ public:
const QStringList& channelSettingsKeys,
SWGSDRangel::SWGChannelSettings& response);
/** The keys of ATVDemodSettings for keys of the Web API, whose names mostly differ */
static QStringList getSettingsKeys(const QStringList& channelSettingsKeys);
private:
ATVDemodSettings m_settings;
};

322
plugins/channelrx/demodatv/atvghostestimator.cpp

@ -0,0 +1,322 @@ @@ -0,0 +1,322 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program 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 as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include "atvghostestimator.h"
namespace {
typedef std::complex<double> Cd;
// Signal delayed by a fractional number of samples: v[k - delay], or v[0] before the start
Cd delayed(const std::vector<Cd>& v, int k, double delay)
{
double x = k - delay;
if (x <= 0.0) {
return v[0];
}
int i = (int) x;
double f = x - i;
return i + 1 < (int) v.size() ? v[i] + f * (v[i + 1] - v[i]) : v[i];
}
// y[k] = a[k] - g y[k - delay], as the detector cancels
std::vector<Cd> cancel(const std::vector<Cd>& a, double delay, Cd gain)
{
std::vector<Cd> y(a);
for (int k = (int) std::ceil(delay) + 1; k < (int) a.size(); k++) {
y[k] = a[k] - gain * delayed(y, k, delay);
}
return y;
}
}
// Keeps the trial cancellations stable
std::complex<double> ATVGhostEstimator::limitGain(std::complex<double> gain)
{
return std::abs(gain) > m_maxGain ? gain * (m_maxGain / std::abs(gain)) : gain;
}
ATVGhostEstimator::ATVGhostEstimator()
{
configure(10000000.0f, 640, 4.2e6f);
}
void ATVGhostEstimator::configure(float sampleRate, int samplesPerLine, float videoBandwidth)
{
auto us = [sampleRate](double t) { return (int) std::round(t * 1e-6 * sampleRate); };
double ringing = 1.25e6 / videoBandwidth; // us, for the edges' own response to settle
m_sampleRate = sampleRate;
m_samplesPerLine = samplesPerLine;
m_pre = us(8.0); // the echo of what is up to 4 us before the tip, and history for its cancellation
m_post = us(9.0);
m_tipStart = us(std::max(0.5, ringing));
m_tipMid = us(2.3);
m_tipEnd = us(4.2);
m_backPorchStart = us(5.3);
m_backPorchEnd = us(8.5);
m_frontPorchStart = -us(1.2);
m_frontPorchEnd = -us(0.3);
m_maxDelay = 4.0e-6 * sampleRate;
// Below 2 MHz, the edges ring for so long that tuning errors look like echoes
m_minDelay = videoBandwidth < 2.0e6f ? m_maxDelay : std::max(1.0, 1e-6 * sampleRate * std::max(1.0, 2.0 * ringing));
m_delayStep = 0.1e-6 * sampleRate;
m_sharpness = 0.5e-6 * sampleRate;
m_line.assign(m_pre + m_post, 0.0f);
m_next.assign(m_pre, 0.0f);
reset();
}
void ATVGhostEstimator::reset()
{
m_sum.assign(m_pre + m_post, 0.0);
m_lines = 0;
m_lastOffset = 0;
m_misses = 0;
m_delay = (float) m_minDelay;
m_gain = 0.0f;
}
bool ATVGhostEstimator::feed(int sampleOffset, std::complex<float> z)
{
if (sampleOffset < m_lastOffset) {
std::copy(m_next.begin(), m_next.end(), m_line.begin()); // a new line has started
}
m_lastOffset = sampleOffset;
int k = sampleOffset - (m_samplesPerLine - m_pre);
if ((k >= 0) && (k < m_pre))
{
m_next[k] = z;
}
else if ((sampleOffset >= 0) && (sampleOffset < m_post))
{
m_line[m_pre + sampleOffset] = z;
if (sampleOffset == m_post - 1) {
return endLine();
}
}
return false;
}
bool ATVGhostEstimator::endLine()
{
auto mean = [this](int start, int end) {
double sum = 0.0;
for (int i = m_pre + start; i < m_pre + end; i++) {
sum += m_line[i].real();
}
return sum / (end - start);
};
// Only ordinary line sync pulses (not the vertical interval's): sync over the whole tip,
// blanking either side. The echo can raise the second half of the tip
double tipA = mean(m_tipStart, m_tipMid);
double tipB = mean(m_tipMid, m_tipEnd);
double backPorch = mean(m_backPorchStart, m_backPorchEnd);
double frontPorch = mean(m_frontPorchStart, m_frontPorchEnd);
double step = tipA - backPorch;
if ((step > 0.1 * tipA) && (tipB - backPorch > 0.5 * step) && (tipA - frontPorch > 0.5 * step))
{
for (int i = 0; i < (int) m_line.size(); i++) {
m_sum[i] += Cd(m_line[i].real(), m_line[i].imag());
}
m_lines++;
}
if (m_lines < m_linesPerEstimate) {
return false;
}
estimate();
std::fill(m_sum.begin(), m_sum.end(), 0.0);
m_lines = 0;
return true;
}
void ATVGhostEstimator::estimate()
{
if (m_minDelay + m_sharpness > m_maxDelay) {
return; // the video bandwidth is too narrow to tell an echo from the edges' ringing
}
std::vector<Cd> a(m_sum.size());
for (int i = 0; i < (int) a.size(); i++) {
a[i] = m_sum[i] / (double) m_lines;
}
const int windows[2][2] = {
{m_pre + m_tipStart, m_pre + m_tipEnd},
{m_pre + m_backPorchStart, m_pre + m_backPorchEnd}
};
// Power of the in-phase signal's variation about its mean, within each window
auto flatness = [&windows](const std::vector<Cd>& y) {
double power = 0.0;
for (const auto& w : windows)
{
double mean = 0.0;
for (int k = w[0]; k < w[1]; k++) {
mean += y[k].real();
}
mean /= w[1] - w[0];
for (int k = w[0]; k < w[1]; k++) {
power += (y[k].real() - mean) * (y[k].real() - mean);
}
}
return power;
};
// Least squares gain of an echo at the given delay in y (the in-phase part of y - g y[k - delay] flattest)
auto fitGain = [&windows](const std::vector<Cd>& y, double delay) {
double uu = 0.0, uv = 0.0, vv = 0.0, ut = 0.0, vt = 0.0;
for (const auto& w : windows)
{
int n = w[1] - w[0];
double mt = 0.0, mu = 0.0, mv = 0.0;
for (int k = w[0]; k < w[1]; k++)
{
Cd d = delayed(y, k, delay);
mt += y[k].real();
mu += d.real();
mv -= d.imag();
}
mt /= n; mu /= n; mv /= n;
for (int k = w[0]; k < w[1]; k++)
{
Cd d = delayed(y, k, delay);
double t = y[k].real() - mt;
double u = d.real() - mu;
double v = -d.imag() - mv;
uu += u * u; uv += u * v; vv += v * v; ut += u * t; vt += v * t;
}
}
double det = uu * vv - uv * uv;
return det > 0.0 ? Cd((vv * ut - uv * vt) / det, (uu * vt - uv * ut) / det) : Cd(0.0);
};
// Gain of an echo at this delay, refined on the cancelled signal, and how flat that leaves it
auto fitEcho = [&](double delay, Cd& gain) {
gain = limitGain(fitGain(a, delay));
for (int i = 0; i < 3; i++) {
gain = limitGain(gain + fitGain(cancel(a, delay, gain), delay));
}
return flatness(cancel(a, delay, gain));
};
double original = flatness(a);
if (original <= 0.0) {
return;
}
// Search in steps of 0.1 us, then refine about the best
std::vector<double> delays, flat;
for (double delay = m_minDelay; delay <= m_maxDelay; delay += m_delayStep)
{
delays.push_back(delay);
flat.push_back(flatness(cancel(a, delay, limitGain(fitGain(a, delay)))) / original);
}
// While an echo is being cancelled, look for it near where it was, and keep it unless it has
// clearly gone, so the cancellation does not come and go as the picture changes
bool tracking = m_gain != 0.0f;
int side = (int) std::round(m_sharpness / m_delayStep);
int first = 0, last = (int) flat.size() - 1;
if (tracking)
{
int centre = (int) std::round((m_delay - m_minDelay) / m_delayStep);
first = std::max(first, centre - side);
last = std::min(last, centre + side);
}
int best = (int) (std::min_element(flat.begin() + first, flat.begin() + last + 1) - flat.begin());
// An echo flattens the sync region at its delay, and clearly less so either side
double worse = 1.0;
if (best - side >= 0) {
worse = std::min(worse, flat[best - side]);
}
if (best + side < (int) flat.size()) {
worse = std::min(worse, flat[best + side]);
}
Cd gain = 0.0;
double delay = delays[best];
double sharpness = tracking ? m_keepSharpness : m_minSharpness;
if ((flat[best] < m_minImprovement) && (worse - flat[best] > sharpness * (1.0 - flat[best])))
{
double f[3];
for (int i = 0; i < 3; i++) {
f[i] = fitEcho(delay + 0.5 * m_delayStep * (i - 1), gain);
}
double curvature = f[0] - 2.0 * f[1] + f[2];
double offset = curvature > 0.0 ? 0.25 * (f[0] - f[2]) / curvature : 0.0;
delay = std::max(m_minDelay, std::min(m_maxDelay, delay + m_delayStep * std::max(-0.5, std::min(0.5, offset))));
if (fitEcho(delay, gain) >= m_minImprovement * original) {
gain = 0.0;
}
}
std::complex<float> g((float) gain.real(), (float) gain.imag());
if (g == 0.0f)
{
// No echo: after several estimates without it, let it fade
if (++m_misses >= m_maxMisses)
{
m_gain *= 1.0f - m_smoothing;
if (std::abs(m_gain) < 0.02f) {
m_gain = 0.0f;
}
}
}
else if (!tracking)
{
m_misses = 0;
m_delay = (float) delay;
m_gain = m_smoothing * g;
}
else
{
m_misses = 0;
m_delay += m_smoothing * ((float) delay - m_delay);
m_gain += m_smoothing * (g - m_gain);
}
}

96
plugins/channelrx/demodatv/atvghostestimator.h

@ -0,0 +1,96 @@ @@ -0,0 +1,96 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program 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 as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_ATVGHOSTESTIMATOR_H
#define INCLUDE_ATVGHOSTESTIMATOR_H
#include <complex>
#include <vector>
/**
* Estimates an echo (ghost) from multipath, for ATVSynchronousDetector to cancel.
*
* An echo is a delayed copy of the whole signal, so it puts a copy of each horizontal sync
* pulse's edges on the sync tip and back porch, which are otherwise flat. The detector's
* complex output, before cancellation and with the carrier's phase removed, is averaged
* around the sync pulses of many lines (which averages out the noise and the picture, and
* for NTSC and PAL, the colour burst). The echo is the delay and complex gain that, cancelled
* from that average, leave the sync tip and back porch flattest. The gain is complex as the
* echo's carrier arrives with a different phase, so part of it is in quadrature: after the
* vestigial sideband filter that is a distorted copy of the picture's detail.
*
* No reference waveform is needed, so the transmitter's filtering, which shapes the pulse
* edges, is not mistaken for an echo. Echoes shorter than 1 us (longer when the video
* bandwidth is narrow, as the edges ring for longer) cannot be told apart from that
* filtering, and only one echo, up to 4 us, is found. Other linear distortion, such as from
* the vestigial sideband filter when mistuned, flattens the tip almost as well over a wide
* range of delays, so only a delay clearly better than those either side is taken as an echo.
*/
class ATVGhostEstimator
{
public:
ATVGhostEstimator();
/** videoBandwidth limits how short an echo can be told apart from the edges' own ringing */
void configure(float sampleRate, int samplesPerLine, float videoBandwidth);
void reset(); //!< Forget the estimate
/**
* Feed the detector's output before ghost cancellation, with the sample's position in the
* line (0 at the sync pulse's leading edge). Returns true when the estimate is updated
*/
bool feed(int sampleOffset, std::complex<float> z);
float getDelay() const { return m_delay; } //!< samples
std::complex<float> getGain() const { return m_gain; } //!< 0 when there is no echo
float getDelaySeconds() const { return m_delay / m_sampleRate; }
private:
static constexpr int m_linesPerEstimate = 500; //!< ~1 frame
static constexpr double m_minImprovement = 0.9; //!< the echo must make the sync region at least 10% flatter (in power)
static constexpr double m_minSharpness = 0.4; //!< and delays 0.5 us either side must leave at least 40% of that improvement
static constexpr double m_keepSharpness = 0.2; //!< or 20%, for an echo already being cancelled
static constexpr int m_maxMisses = 4; //!< estimates without the echo before it fades
static constexpr float m_smoothing = 0.3f; //!< of successive estimates
static constexpr float m_maxGain = 0.7f;
float m_sampleRate;
int m_samplesPerLine;
int m_pre; //!< samples kept before the sync's leading edge
int m_post; //!< samples kept after it
int m_tipStart, m_tipMid, m_tipEnd; //!< sync tip, after the edge (two halves, to recognise sync pulses)
int m_backPorchStart, m_backPorchEnd;
int m_frontPorchStart, m_frontPorchEnd; //!< before the edge (negative)
double m_minDelay, m_maxDelay; //!< samples
double m_delayStep; //!< samples, of the search
double m_sharpness; //!< samples either side of an echo's delay that must flatten the tip less
std::vector<std::complex<float>> m_line; //!< the current line's samples, from -m_pre
std::vector<std::complex<float>> m_next; //!< the end of the current line, which starts the next
std::vector<std::complex<double>> m_sum;
int m_lines;
int m_lastOffset;
int m_misses; //!< successive estimates without the echo
float m_delay;
std::complex<float> m_gain;
bool endLine();
void estimate();
static std::complex<double> limitGain(std::complex<double> gain);
};
#endif // INCLUDE_ATVGHOSTESTIMATOR_H

142
plugins/channelrx/demodatv/atvnoisereduction.cpp

@ -0,0 +1,142 @@ @@ -0,0 +1,142 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program 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 as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cmath>
#include "atvnoisereduction.h"
static const int histogramBinsPerLevel = 4;
ATVNoiseReduction::ATVNoiseReduction() :
m_width(0),
m_height(0),
m_strength(0.0f),
m_histogramCount(0),
m_threshold(0.0f),
m_window(7)
{
m_histogram.resize(256 * histogramBinsPerLevel);
}
void ATVNoiseReduction::configure(int width, int height)
{
m_width = std::max(width, 0);
m_height = std::max(height, 0);
m_frame.assign((size_t) m_width * m_height * 3, 0.0f);
m_rowValid.assign(m_height, false);
m_differenceSum.resize(m_width + 1);
std::fill(m_histogram.begin(), m_histogram.end(), 0);
m_histogramCount = 0;
m_threshold = 0.0f;
}
void ATVNoiseReduction::setStrength(int strength)
{
// At 100%, still frames are blended 90% with the previous output, which reduces the
// noise to about a quarter
m_strength = 0.9f * std::min(std::max(strength, 0), 100) / 100.0f;
}
void ATVNoiseReduction::processRow(int row, unsigned int *rgb)
{
if ((row < 0) || (row >= m_height) || (m_width == 0)) {
return;
}
float *prev = &m_frame[(size_t) row * m_width * 3];
if (!m_rowValid[row])
{
for (int n = 0; n < m_width; n++)
{
prev[3*n] = rgb[n] & 0xff;
prev[3*n+1] = (rgb[n] >> 8) & 0xff;
prev[3*n+2] = (rgb[n] >> 16) & 0xff;
}
m_rowValid[row] = true;
return;
}
// Luminance difference from the previous frame, signed, with running sums
m_differenceSum[0] = 0.0f;
for (int n = 0; n < m_width; n++)
{
float r = rgb[n] & 0xff;
float g = (rgb[n] >> 8) & 0xff;
float b = (rgb[n] >> 16) & 0xff;
float difference = 0.299f * (r - prev[3*n]) + 0.587f * (g - prev[3*n+1]) + 0.114f * (b - prev[3*n+2]);
m_differenceSum[n + 1] = m_differenceSum[n] + difference;
}
for (int n = 0; n < m_width; n++)
{
// The signed difference averaged over a few pixels: noise averages towards zero,
// while motion, a consistent change in brightness, does not
int a = std::max(n - m_window / 2, 0);
int b = std::min(n - m_window / 2 + m_window, m_width);
float d = std::fabs(m_differenceSum[b] - m_differenceSum[a]) / (b - a);
int bin = std::min((int) (d * histogramBinsPerLevel), (int) m_histogram.size() - 1);
m_histogram[bin]++;
m_histogramCount++;
// Full blend below the threshold, none above twice it
float k = m_threshold > 0.0f ? m_strength * std::min(std::max(2.0f - d / m_threshold, 0.0f), 1.0f) : 0.0f;
unsigned int packed = 0;
for (int c = 0; c < 3; c++)
{
float cur = (rgb[n] >> (8 * c)) & 0xff;
float out = cur + k * (prev[3*n+c] - cur);
prev[3*n+c] = out;
packed |= ((unsigned int) std::min(std::max((int) (out + 0.5f), 0), 255)) << (8 * c);
}
rgb[n] = packed;
}
}
void ATVNoiseReduction::endFrame()
{
if (m_histogramCount == 0) {
return;
}
// The lower quartile of the difference: as long as a quarter of the picture is still,
// this measures the noise, even when most of it is moving
int quartile = m_histogramCount / 4;
int sum = 0;
int bin = 0;
for (; bin < (int) m_histogram.size(); bin++)
{
sum += m_histogram[bin];
if (sum >= quartile) {
break;
}
}
// For noise alone, the quartile of |difference| is 0.32 sigma: threshold at about 1.6 sigma
float threshold = std::max(5.0f * (bin + 0.5f) / histogramBinsPerLevel, 1.0f);
m_threshold = m_threshold > 0.0f ? m_threshold + 0.2f * (threshold - m_threshold) : threshold;
std::fill(m_histogram.begin(), m_histogram.end(), 0);
m_histogramCount = 0;
}

60
plugins/channelrx/demodatv/atvnoisereduction.h

@ -0,0 +1,60 @@ @@ -0,0 +1,60 @@
///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2026 Jon Beniston, M7RCE <jon@beniston.com> //
// Some code by AI //
// //
// This program 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 as version 3 of the License, or //
// (at your option) any later version. //
// //
// This program 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 V3 for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_ATVNOISEREDUCTION_H
#define INCLUDE_ATVNOISEREDUCTION_H
#include <vector>
/**
* Motion adaptive temporal noise reduction.
*
* Each pixel is blended with the same pixel of the previous frame (recursively), except
* where its luminance has changed by more than the noise, which is taken to be motion. The
* noise level is estimated each frame from the lower quartile of the frame to frame
* difference, so the threshold follows the signal as long as some of the picture is still.
*/
class ATVNoiseReduction
{
public:
ATVNoiseReduction();
void configure(int width, int height); //!< Pixels per row and rows; clears the frame store
void setStrength(int strength); //!< 0 (off) to 100%
bool isEnabled() const { return m_strength > 0.0f; }
/** Filter one row in place. Pixels are packed 0x00BBGGRR */
void processRow(int row, unsigned int *rgb);
void endFrame(); //!< Update the noise estimate from the frame just finished
float getThreshold() const { return m_threshold; } //!< Motion threshold, 8-bit levels
private:
int m_width;
int m_height;
float m_strength; //!< Maximum blend with the previous frame
std::vector<float> m_frame; //!< Previous output, 3 floats per pixel
std::vector<bool> m_rowValid;
std::vector<float> m_differenceSum; //!< Running sum of the luminance difference along the current row
std::vector<int> m_histogram; //!< Of luminance differences over the frame, for the noise estimate
int m_histogramCount;
float m_threshold;
int m_window; //!< Pixels the difference is averaged over
};
#endif // INCLUDE_ATVNOISEREDUCTION_H

90
plugins/channelrx/demodatv/readme.md

@ -2,9 +2,9 @@ @@ -2,9 +2,9 @@
<h2>Introduction</h2>
This plugin can be used to view amateur analog television transmissions a.k.a ATV. The transmitted video signal can be black and white or color (PAL, NTSC) but only the black and white level (luminance) is retained and hence image is black and white. There is no provision to demodulate the audio subcarrier either. The modulation can be either AM or FM (SSB with carrier is only experimental). A plugin supporting audio can be used in the same baseband to demodulate an audio carrier but this does not work for a subcarrier which excludes FM.
This plugin can be used to view analog television transmissions, both amateur (ATV) and broadcast. NTSC and PAL colour can be decoded (see B.13), when the sample rate is high enough for the colour subcarrier, otherwise only the black and white level (luminance) is retained. There is no provision to demodulate the audio subcarrier. The modulation can be either AM or FM (SSB with carrier is only experimental). A plugin supporting audio can be used in the same baseband to demodulate an audio carrier but this does not work for a subcarrier which excludes FM.
A standard image quality for broadcast standard modes requires a sample rate of at least 4 MS/s. The Airspy Mini 3 MS/s mode may still be acceptable.
A standard image quality for broadcast standard modes requires a sample rate of at least 4 MS/s. The Airspy Mini 3 MS/s mode may still be acceptable. Colour needs more: see [Colour reception](#colour-reception).
Experimental modes with smaller number of lines and FPS values can be used in conjunction with the [ATV Modulator plugin](https://github.com/f4exb/sdrangel/tree/master/plugins/channeltx/modatv) to reduce sample rate and occupied bandwidth. Very low line frequencies and thus small bandwidths are reachable with degraded image quality. This is known as NBTV see: [Wikipedia article](https://en.wikipedia.org/wiki/Narrow-bandwidth_television) and [NBTV.org](http://www.nbtv.org/)
@ -30,9 +30,9 @@ Each part is detailed next @@ -30,9 +30,9 @@ Each part is detailed next
Use the wheels to adjust the frequency shift in Hz from the center frequency of reception. Left click on a digit sets the cursor position at this digit. Right click on a digit sets all digits on the right to zero. This effectively floors value at the digit position. Wheels are moved with the mousewheel while pointing at the wheel or by selecting the wheel with the left mouse click and using the keyboard arrows. Pressing shift simultaneously moves digit by 5 and pressing control moves it by 2.
<h3>2: Channel sample rate</h3>
<h3>2: Video sample rate</h3>
This is the baseband sample rate as no decimation takes place in this channel plugin.
This is the rate the video is processed at. It is the baseband sample rate, as no decimation takes place in this channel plugin, except when decoding colour from an AM signal, when it is upsampled by 2 or 4 so that the video can extend to the top of the colour subcarrier (see [Colour reception](#colour-reception)).
<h3>3: Number of integer points or samples per line and fractional remainder</h3>
@ -45,7 +45,7 @@ This is the number of integer points or samples per complete line including sync @@ -45,7 +45,7 @@ This is the number of integer points or samples per complete line including sync
n = Sb / (l &times; F) (Euclidean division)
Where:
- Sb is the baseband sample rate
- Sb is the video sample rate (2)
- n is the number of integer points
- l is the number of lines
- F is the frame rate in frames/second
@ -84,7 +84,7 @@ Average total power in dB relative to a &#177;1.0 amplitude signal generated in @@ -84,7 +84,7 @@ Average total power in dB relative to a &#177;1.0 amplitude signal generated in
- **FM1**: this is Frequency Modulation with approximative demodulation algorithm not using atan2
- **FM2**: this is Frequency Modulation with less approximative demodulation algorithm still not using atan2
- **FM3**: this is Frequency Modulation with atan2 approximation for phase calculation and then a discrete differentiation is applied
- **AM**: this is Amplitude Modulation. It can be used for vestigial sideband transmissions in conjunction with the asymmetrical filter (11, 12, 13)
- **AM**: this is Amplitude Modulation, as used for broadcast TV with a vestigial lower sideband. Unless the FFT filter (11) is on, it goes through a vestigial sideband filter and synchronous detector (see below)
- **USB**: &#9888; USB demodulation synchronous to the carrier (experimental)
- **LSB**: &#9888; LSB demodulation synchronous to the carrier (experimental)
@ -96,6 +96,14 @@ For FM choose the algorithm that best suits your conditions. @@ -96,6 +96,14 @@ For FM choose the algorithm that best suits your conditions.
&#9888; USB and LSB modes are experimental and do not show good results for sample rates greater than 1 MS/s. Adjusting the BFO can be picky and unstable.
&#9758; In AM without the FFT filter (11), and when decoding colour (B.13) in AM, USB or LSB, the signal goes through a dedicated vestigial sideband filter and synchronous detector, as a TV does:
- A Nyquist slope through the vision carrier flattens the response across the vestigial sideband and removes anything more than 0.3 MHz below the carrier. That is where the sound carrier ends up when it is outside the device's band and aliases, where it would otherwise put a herringbone pattern over the picture.
- The vision carrier is recovered and the video detected synchronously. Tuning errors of up to &#177;50 kHz are tracked. The carrier is recovered from the sync pulses only, as the picture modulates it: transmitters often overmodulate on white, cutting the carrier off, which would otherwise tear the picture.
- With video inversion (B.6), as for the usual negative modulation, the levels are taken from the sync tip carrier, so the AM range corrections (9, 10) are not used.
In black and white, the vision carrier is kept at the centre of the channel, so the video extends to half the sample rate, without aliasing (2.5 MHz at 5 MS/s). For colour the video is upsampled as needed (see [Colour reception](#colour-reception)), and the FFT filter and BFO (5) are not used. USB and AM behave the same in colour; LSB is for spectrum inverted signals, with the video below the vision carrier.
<h3>8: FM deviation adjustment</h3>
Using this button you can adjust the nominal FM deviation as a percentage of the channel bandwidth that is displayed on the right of the button. When a signal with this deviation is received the demodulated signal is in the range -0.5/+0.5 which is shifted to a 0/1 range video signal.
@ -112,7 +120,7 @@ This is a factor in % applied to the signal resulting from the previous correcti @@ -112,7 +120,7 @@ This is a factor in % applied to the signal resulting from the previous correcti
<h3>11: FFT asymmetrical filter toggle</h3>
Use this button to enable/disable the FFT asymmetrical filter. Use this filter when you want to optimize the reception of vestigial sideband AM signals.
Use this button to enable/disable the FFT asymmetrical filter. In black and white AM it replaces the vestigial sideband filter and synchronous detector (see 7) with this filter and an envelope detector. This can be better for double sideband AM, such as some amateur TV, as it uses both sidebands, while the vestigial sideband filter uses only one above 0.3 MHz. It is not used when decoding colour.
<h3>12: FFT asymmetrical filter opposite band cutoff frequency</h3>
@ -262,7 +270,7 @@ Use this slider to adjust the trigger level of the synchronization pulse on a 0 @@ -262,7 +270,7 @@ Use this slider to adjust the trigger level of the synchronization pulse on a 0
This is the line length in time units. The value depends on the line frequency. For example with 625 lines and 12 FPS The line frequency is 625 &times; 12 = 7500 Hz thus the nominal line time is the inverse of this value that is &#8776;133.33 &mu;s
<h3>10: Black level</h3>
<h3>11: Black level</h3>
Use this slider to adjust the black level of the video signal on a 0 to 1V scale. This also triggers the end of horizontal synchronization pulse. The value in mV appears on the right of the slider. Nominal value: 300 mV.
@ -270,6 +278,72 @@ Use this slider to adjust the black level of the video signal on a 0 to 1V scale @@ -270,6 +278,72 @@ Use this slider to adjust the black level of the video signal on a 0 to 1V scale
This is the length in time units of a horizontal or line synchronization pulse. The value depends on the nominal line length as described above. The pulse length is derived from the 4.7 &mu;s pulse of a 625 lines and 25 FPS standard system with a 64 &mu;s line length. For example with a 625 lines &times; 12 FPS transmission that has a line length of &#8776;133.33 &mu;s this is (4.7 &divide; 64) &times; 133.33 &#8776; 9.79 &mu;s.
<h3>13: Colour system</h3>
- **Mono**: luminance only. This works at any sample rate and is the only choice when the sample rate cannot cover the colour subcarrier.
- **NTSC**: NTSC-M, 3.579545 MHz subcarrier
- **NTSC 4.43**: NTSC with a 4.43361875 MHz subcarrier, as played back by some multi-standard video recorders
- **PAL**: PAL-B/G/D/K/I, 4.43361875 MHz subcarrier
- **PAL-M**: 525 lines PAL as used in Brazil, 3.57561149 MHz subcarrier
- **PAL-N**: 625 lines PAL as used in Argentina, Paraguay and Uruguay, 3.58205625 MHz subcarrier
SECAM is not supported.
With a 525 line colour system, the line rate is the exact 15734.26 Hz of 59.94 fields per second, rather than 525 &times; 30.
When colour is selected, the black level slider (11) is not used: levels are taken from the sync tip and the blanking level, as a TV does, and the colour saturation from the amplitude of the colour burst.
<h3>14: Colour burst indicator</h3>
Turns green while a colour burst is being received. When there is no burst for longer than the vertical blanking interval, the colour killer turns colour off and the image is shown in black and white.
<h3>15: Colour saturation</h3>
Saturation as a percentage of nominal, from 0 to 200%.
<h3>16: Hue</h3>
Hue (tint) adjustment in degrees, for NTSC only. PAL corrects phase errors itself.
<h3>17: Delay line</h3>
When checked, the colour of each line is averaged with the previous line of the field. For PAL this is the delay line of a PAL-D receiver, which cancels phase errors from multipath or the transmission path; when unchecked, phase errors show as "Hanover bars" (PAL-S). For both PAL and NTSC it halves the colour noise, for half the vertical colour resolution, which is worth having on weak signals.
<h3>18: Noise reduction</h3>
Temporal noise reduction, from 0 (off) to 100%. Each pixel is blended with the same pixel in the previous frame, except where the picture has changed by more than the noise, which is taken to be movement. The noise level is measured from the picture itself, so there is nothing else to adjust. This works in black and white as well as colour.
On a weak signal, 50 to 70% removes most of the grain without visible smearing. Higher values are cleaner still on still pictures but leave faint trails behind fast movement. With 100% the noise is reduced to about half on a typical weak signal.
<h3>19: Colour status</h3>
Shows OK when the sample rate and tuning cover the colour subcarrier, or what is wrong when they do not. Hover over it for details.
<h3>20: Ghost cancellation</h3>
When checked, an echo from multipath (a ghost: a fainter copy of the picture, shifted to the right) is measured and cancelled. The delay and strength of the echo being cancelled are shown beside the check box.
The echo is measured from the horizontal sync pulses, whose tips and back porches are flat without one, averaged over a frame, and cancelled from the signal before it is detected, so its effect on colour is removed too. One echo, delayed by 1 to 4 &#181;s, is cancelled. It is only available for AM with video inverted, through the Nyquist slope filter (not with the FFT filter, A.11), and needs at least 2 MHz of video bandwidth (a sample rate of 4 MS/s or more for black and white), as with less, the edges of the sync pulses ring for longer than a short echo. Turn it off if the ghost is not steady, for example from an aircraft.
<h2 id="colour-reception">Colour reception</h2>
The colour (chroma) is carried on a subcarrier 3.58 MHz (NTSC, PAL-M, PAL-N) or 4.43 MHz (PAL) above the vision carrier. To decode it, the device must receive from 0.3 MHz below the vision carrier to 0.6 MHz above the subcarrier, a span of about 4.5 MHz for NTSC and 5.3 MHz for PAL. As this span is not centred on the vision carrier, the device centre frequency should be set above the vision carrier, by about half the span, with the channel (A.1) on the vision carrier. For example, for NTSC channel 2 (vision carrier 55.25 MHz) at 5 MS/s, set the device to 57 MHz and the channel to -1.75 MHz. The channel marker shows the band needed, and the colour status (B.19) shows whether it is covered.
For AM, USB and LSB signals, colour decoding:
- Filters the signal with a Nyquist slope through the vision carrier, as a TV's IF filter does (see 7).
- Upsamples the video by 2 or 4 when needed, so it can extend to the top of the chroma (A.2).
- Recovers the vision carrier and detects synchronously, which avoids the distortion of saturated colours that envelope detection of a vestigial sideband signal causes.
- Takes the video levels from the sync tip carrier, so video inversion (B.6) should be checked for the usual negative modulation.
For FM signals, the sample rate must be high enough for the demodulated video to include the subcarrier (about 9 MS/s for NTSC and 11 MS/s for PAL), and the video levels are taken from the depth of the sync pulses.
Sync is detected with the colour subcarrier filtered out, so saturated colours are not mistaken for sync pulses, and a horizontal sync pulse must last at least 1 &#181;s, so the brief undershoot next to bright white is not either. If the transmission has a compressed sync, as long distance reception can, lower the synchronization level (B.9) until the image locks.
The displayed colour is limited to about 0.75 MHz, as TV sets did, which halves its noise compared with the full chroma bandwidth. On weak signals, the delay line (B.17) and noise reduction (B.18) reduce the noise further.
Colour decoding uses more CPU than black and white: about a third of a core for NTSC at 5 MS/s on a recent desktop.
<h2>C: Image</h2>
<h3>Monitor</h3>

33
sdrbase/resources/webapi/doc/swagger/include/ATVDemod.yaml

@ -143,3 +143,36 @@ ATVDemodSettings: @@ -143,3 +143,36 @@ ATVDemodSettings:
description: "UDP port number."
minimum: 1
maximum: 65535
colourSystem:
description: >
Colour decoding
* 0 - Mono (luminance only)
* 1 - NTSC
* 2 - NTSC 4.43
* 3 - PAL
* 4 - PAL-M
* 5 - PAL-N
type: integer
minimum: 0
maximum: 5
colourSaturation:
type: integer
description: "Colour saturation in % of nominal."
colourHue:
type: integer
description: "Hue adjustment in degrees (NTSC only)."
palDelayLine:
description: "Average the chroma of successive lines (the PAL delay line; also reduces chroma noise for NTSC)."
type: integer
minimum: 0
maximum: 1
noiseReduction:
type: integer
description: "Temporal noise reduction strength in % (0 is off)."
minimum: 0
maximum: 100
ghostCancellation:
description: "Estimate and cancel an echo (ghost) from multipath (1 for on). AM through the vestigial sideband filter only."
type: integer
minimum: 0
maximum: 1

32
sdrgui/gui/tvscreenanalog.cpp

@ -66,14 +66,14 @@ static const char* fragmentShaderSource2 = @@ -66,14 +66,14 @@ static const char* fragmentShaderSource2 =
" float p3x = floor(txs3) * tlw - tlhw;\n"
" float p2x = p1x + tlw;\n"
" float p4x = p3x + tlw;\n"
" float p1 = texture2D(tex1, vec2(p1x, p1y)).r;\n"
" float p2 = texture2D(tex1, vec2(p2x, p1y)).r;\n"
" float p3 = texture2D(tex1, vec2(p3x, p3y)).r;\n"
" float p4 = texture2D(tex1, vec2(p4x, p3y)).r;\n"
" float p12 = mix(p1, p2, fract(txs1));\n"
" float p34 = mix(p3, p4, fract(txs3));\n"
" float p = mix(p12, p34, fract(tys));\n"
" gl_FragColor = vec4(p, p, p, 1.0);\n"
" vec3 p1 = texture2D(tex1, vec2(p1x, p1y)).rgb;\n"
" vec3 p2 = texture2D(tex1, vec2(p2x, p1y)).rgb;\n"
" vec3 p3 = texture2D(tex1, vec2(p3x, p3y)).rgb;\n"
" vec3 p4 = texture2D(tex1, vec2(p4x, p3y)).rgb;\n"
" vec3 p12 = mix(p1, p2, fract(txs1));\n"
" vec3 p34 = mix(p3, p4, fract(txs3));\n"
" vec3 p = mix(p12, p34, fract(tys));\n"
" gl_FragColor = vec4(p, 1.0);\n"
"}\n";
static const char* fragmentShaderSource =
@ -102,14 +102,14 @@ static const char* fragmentShaderSource = @@ -102,14 +102,14 @@ static const char* fragmentShaderSource =
" float p3x = floor(txs3) * tlw - tlhw;\n"
" float p2x = p1x + tlw;\n"
" float p4x = p3x + tlw;\n"
" float p1 = texture(tex1, vec2(p1x, p1y)).r;\n"
" float p2 = texture(tex1, vec2(p2x, p1y)).r;\n"
" float p3 = texture(tex1, vec2(p3x, p3y)).r;\n"
" float p4 = texture(tex1, vec2(p4x, p3y)).r;\n"
" float p12 = mix(p1, p2, fract(txs1));\n"
" float p34 = mix(p3, p4, fract(txs3));\n"
" float p = mix(p12, p34, fract(tys));\n"
" fragColor = vec4(p, p, p, 1.0);\n"
" vec3 p1 = texture(tex1, vec2(p1x, p1y)).rgb;\n"
" vec3 p2 = texture(tex1, vec2(p2x, p1y)).rgb;\n"
" vec3 p3 = texture(tex1, vec2(p3x, p3y)).rgb;\n"
" vec3 p4 = texture(tex1, vec2(p4x, p3y)).rgb;\n"
" vec3 p12 = mix(p1, p2, fract(txs1));\n"
" vec3 p34 = mix(p3, p4, fract(txs3));\n"
" vec3 p = mix(p12, p34, fract(tys));\n"
" fragColor = vec4(p, 1.0);\n"
"}\n";
TVScreenAnalog::TVScreenAnalog(QWidget *parent) :

33
swagger/sdrangel/api/swagger/include/ATVDemod.yaml

@ -143,3 +143,36 @@ ATVDemodSettings: @@ -143,3 +143,36 @@ ATVDemodSettings:
description: "UDP port number."
minimum: 1
maximum: 65535
colourSystem:
description: >
Colour decoding
* 0 - Mono (luminance only)
* 1 - NTSC
* 2 - NTSC 4.43
* 3 - PAL
* 4 - PAL-M
* 5 - PAL-N
type: integer
minimum: 0
maximum: 5
colourSaturation:
type: integer
description: "Colour saturation in % of nominal."
colourHue:
type: integer
description: "Hue adjustment in degrees (NTSC only)."
palDelayLine:
description: "Average the chroma of successive lines (the PAL delay line; also reduces chroma noise for NTSC)."
type: integer
minimum: 0
maximum: 1
noiseReduction:
type: integer
description: "Temporal noise reduction strength in % (0 is off)."
minimum: 0
maximum: 100
ghostCancellation:
description: "Estimate and cancel an echo (ghost) from multipath (1 for on). AM through the vestigial sideband filter only."
type: integer
minimum: 0
maximum: 1

132
swagger/sdrangel/code/qt5/client/SWGATVDemodSettings.cpp

@ -94,6 +94,18 @@ SWGATVDemodSettings::SWGATVDemodSettings() { @@ -94,6 +94,18 @@ SWGATVDemodSettings::SWGATVDemodSettings() {
m_udp_address_isSet = false;
udp_port = 0;
m_udp_port_isSet = false;
colour_system = 0;
m_colour_system_isSet = false;
colour_saturation = 0;
m_colour_saturation_isSet = false;
colour_hue = 0;
m_colour_hue_isSet = false;
pal_delay_line = 0;
m_pal_delay_line_isSet = false;
noise_reduction = 0;
m_noise_reduction_isSet = false;
ghost_cancellation = 0;
m_ghost_cancellation_isSet = false;
}
SWGATVDemodSettings::~SWGATVDemodSettings() {
@ -168,6 +180,18 @@ SWGATVDemodSettings::init() { @@ -168,6 +180,18 @@ SWGATVDemodSettings::init() {
m_udp_address_isSet = false;
udp_port = 0;
m_udp_port_isSet = false;
colour_system = 0;
m_colour_system_isSet = false;
colour_saturation = 0;
m_colour_saturation_isSet = false;
colour_hue = 0;
m_colour_hue_isSet = false;
pal_delay_line = 0;
m_pal_delay_line_isSet = false;
noise_reduction = 0;
m_noise_reduction_isSet = false;
ghost_cancellation = 0;
m_ghost_cancellation_isSet = false;
}
void
@ -288,6 +312,18 @@ SWGATVDemodSettings::fromJsonObject(QJsonObject &pJson) { @@ -288,6 +312,18 @@ SWGATVDemodSettings::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&udp_port, pJson["udpPort"], "qint32", "");
::SWGSDRangel::setValue(&colour_system, pJson["colourSystem"], "qint32", "");
::SWGSDRangel::setValue(&colour_saturation, pJson["colourSaturation"], "qint32", "");
::SWGSDRangel::setValue(&colour_hue, pJson["colourHue"], "qint32", "");
::SWGSDRangel::setValue(&pal_delay_line, pJson["palDelayLine"], "qint32", "");
::SWGSDRangel::setValue(&noise_reduction, pJson["noiseReduction"], "qint32", "");
::SWGSDRangel::setValue(&ghost_cancellation, pJson["ghostCancellation"], "qint32", "");
}
QString
@ -403,6 +439,24 @@ SWGATVDemodSettings::asJsonObject() { @@ -403,6 +439,24 @@ SWGATVDemodSettings::asJsonObject() {
if(m_udp_port_isSet){
obj->insert("udpPort", QJsonValue(udp_port));
}
if(m_colour_system_isSet){
obj->insert("colourSystem", QJsonValue(colour_system));
}
if(m_colour_saturation_isSet){
obj->insert("colourSaturation", QJsonValue(colour_saturation));
}
if(m_colour_hue_isSet){
obj->insert("colourHue", QJsonValue(colour_hue));
}
if(m_pal_delay_line_isSet){
obj->insert("palDelayLine", QJsonValue(pal_delay_line));
}
if(m_noise_reduction_isSet){
obj->insert("noiseReduction", QJsonValue(noise_reduction));
}
if(m_ghost_cancellation_isSet){
obj->insert("ghostCancellation", QJsonValue(ghost_cancellation));
}
return obj;
}
@ -737,6 +791,66 @@ SWGATVDemodSettings::setUdpPort(qint32 udp_port) { @@ -737,6 +791,66 @@ SWGATVDemodSettings::setUdpPort(qint32 udp_port) {
this->m_udp_port_isSet = true;
}
qint32
SWGATVDemodSettings::getColourSystem() {
return colour_system;
}
void
SWGATVDemodSettings::setColourSystem(qint32 colour_system) {
this->colour_system = colour_system;
this->m_colour_system_isSet = true;
}
qint32
SWGATVDemodSettings::getColourSaturation() {
return colour_saturation;
}
void
SWGATVDemodSettings::setColourSaturation(qint32 colour_saturation) {
this->colour_saturation = colour_saturation;
this->m_colour_saturation_isSet = true;
}
qint32
SWGATVDemodSettings::getColourHue() {
return colour_hue;
}
void
SWGATVDemodSettings::setColourHue(qint32 colour_hue) {
this->colour_hue = colour_hue;
this->m_colour_hue_isSet = true;
}
qint32
SWGATVDemodSettings::getPalDelayLine() {
return pal_delay_line;
}
void
SWGATVDemodSettings::setPalDelayLine(qint32 pal_delay_line) {
this->pal_delay_line = pal_delay_line;
this->m_pal_delay_line_isSet = true;
}
qint32
SWGATVDemodSettings::getNoiseReduction() {
return noise_reduction;
}
void
SWGATVDemodSettings::setNoiseReduction(qint32 noise_reduction) {
this->noise_reduction = noise_reduction;
this->m_noise_reduction_isSet = true;
}
qint32
SWGATVDemodSettings::getGhostCancellation() {
return ghost_cancellation;
}
void
SWGATVDemodSettings::setGhostCancellation(qint32 ghost_cancellation) {
this->ghost_cancellation = ghost_cancellation;
this->m_ghost_cancellation_isSet = true;
}
bool
SWGATVDemodSettings::isSet(){
@ -841,6 +955,24 @@ SWGATVDemodSettings::isSet(){ @@ -841,6 +955,24 @@ SWGATVDemodSettings::isSet(){
if(m_udp_port_isSet){
isObjectUpdated = true; break;
}
if(m_colour_system_isSet){
isObjectUpdated = true; break;
}
if(m_colour_saturation_isSet){
isObjectUpdated = true; break;
}
if(m_colour_hue_isSet){
isObjectUpdated = true; break;
}
if(m_pal_delay_line_isSet){
isObjectUpdated = true; break;
}
if(m_noise_reduction_isSet){
isObjectUpdated = true; break;
}
if(m_ghost_cancellation_isSet){
isObjectUpdated = true; break;
}
}while(false);
return isObjectUpdated;
}

36
swagger/sdrangel/code/qt5/client/SWGATVDemodSettings.h

@ -141,6 +141,24 @@ public: @@ -141,6 +141,24 @@ public:
qint32 getUdpPort();
void setUdpPort(qint32 udp_port);
qint32 getColourSystem();
void setColourSystem(qint32 colour_system);
qint32 getColourSaturation();
void setColourSaturation(qint32 colour_saturation);
qint32 getColourHue();
void setColourHue(qint32 colour_hue);
qint32 getPalDelayLine();
void setPalDelayLine(qint32 pal_delay_line);
qint32 getNoiseReduction();
void setNoiseReduction(qint32 noise_reduction);
qint32 getGhostCancellation();
void setGhostCancellation(qint32 ghost_cancellation);
virtual bool isSet() override;
@ -244,6 +262,24 @@ private: @@ -244,6 +262,24 @@ private:
qint32 udp_port;
bool m_udp_port_isSet;
qint32 colour_system;
bool m_colour_system_isSet;
qint32 colour_saturation;
bool m_colour_saturation_isSet;
qint32 colour_hue;
bool m_colour_hue_isSet;
qint32 pal_delay_line;
bool m_pal_delay_line_isSet;
qint32 noise_reduction;
bool m_noise_reduction_isSet;
qint32 ghost_cancellation;
bool m_ghost_cancellation_isSet;
};
}

Loading…
Cancel
Save