#2646 Channel SNR in the channel spectral display. Shows the selected channel's power in dBFS and its signal-to-noise ratio below the channel bandwidth label. Channel power is summed from the in-band bins of the display's existing dBFS spectrum. Noise comes from a new on-demand tuner noise floor estimator that works with both the polyphase and heterodyne channelizers, using a local median of the bins near the channel.

This commit is contained in:
denny
2026-11-19 03:13:54 -05:00
parent 61efb3d299
commit e2950f30fa
12 changed files with 1150 additions and 2 deletions

View File

@@ -243,7 +243,8 @@ public class ChannelSpectrumView extends SplitPane implements Listener<Processin
if(source instanceof TunerChannelSource tcs)
{
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth);
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth,
tcs::getNoiseDensity);
}
}

View File

@@ -23,6 +23,8 @@ import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.spectrum.ChannelSignalMeter;
import java.util.function.DoubleSupplier;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
@@ -46,9 +48,11 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
private final ChannelTuningLayer mTuningLayer;
private final EdgeSlider mNoiseFloorSlider;
private final ChannelSignalMeter mSignalMeter = new ChannelSignalMeter(this::showReading);
private final Object mLock = new Object();
private boolean mActive;
private boolean mHasChannel;
private volatile boolean mHasChannel;
private volatile boolean mHasNoiseDensity;
/**
* Constructs an instance.
@@ -86,9 +90,46 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
getChildren().add(mNoiseFloorSlider);
//Channel power and SNR, measured from the spectrum frames
mSignalMeter.setWindowNoiseBandwidth(model.noiseBandwidthProperty().get());
model.noiseBandwidthProperty().addListener((ob, ov, nv) ->
mSignalMeter.setWindowNoiseBandwidth(nv.doubleValue()));
addDecibelListener(mSignalMeter);
installConfigPanel();
}
/**
* Shows the channel signal reading in the tuning layer. Called on the DFT processor thread.
*/
private void showReading(ChannelSignalMeter.Reading reading)
{
String text = String.format("%.1f dBFS", reading.dbfs());
//Channels that aren't sourced by a tuner show the channel power without the SNR
if(mHasNoiseDensity)
{
if(!reading.hasSnr())
{
//Waiting for the tuner noise floor estimate, which restarts after a tuner frequency change
text += " SNR --";
}
else
{
text += Double.isFinite(reading.snr()) && reading.snr() >= 0.0 ?
String.format(" SNR %.1f dB", reading.snr()) : " SNR < 0 dB";
}
}
String readout = text;
runOnFxThread(() -> {
if(mHasChannel && isDftRunning())
{
mTuningLayer.signalReadoutProperty().set(readout);
}
});
}
/**
* Listener for the channel's complex sample buffers.
*/
@@ -104,10 +145,25 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
* @param bandwidth of the channel in Hertz, or zero to hide the passband markers
*/
public void setChannel(long frequency, int sampleRate, int bandwidth)
{
setChannel(frequency, sampleRate, bandwidth, null);
}
/**
* Sets the channel to display.
* @param frequency of the channel
* @param sampleRate of the channel samples, or 0 for no channel
* @param bandwidth of the channel in Hertz
* @param noiseDensity supplier of the tuner noise density near the channel, in full-scale units per Hertz, for the
* signal-to-noise ratio. Null, or a supplier that returns NaN, shows the channel power without the SNR.
*/
public void setChannel(long frequency, int sampleRate, int bandwidth, DoubleSupplier noiseDensity)
{
synchronized(mLock)
{
mHasChannel = sampleRate > 0;
mSignalMeter.setChannel(sampleRate, bandwidth, noiseDensity);
mHasNoiseDensity = noiseDensity != null;
updateProcessing();
}
@@ -118,6 +174,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
model.centerFrequencyProperty().set(frequency);
model.sampleRateProperty().set(sampleRate);
mTuningLayer.channelBandwidthProperty().set(bandwidth);
mTuningLayer.signalReadoutProperty().set(null);
mTuningLayer.carrierOffsetValidProperty().set(false);
mTuningLayer.carrierOffsetProperty().set(0);
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
@@ -195,6 +252,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
else
{
stopDft();
runOnFxThread(() -> mTuningLayer.signalReadoutProperty().set(null));
}
}

View File

@@ -24,6 +24,7 @@ import io.github.dsheirer.gui.spectrum.layer.DecibelLayer;
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTResultsListener;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
import javafx.application.Platform;
@@ -300,6 +301,14 @@ public abstract class DftSpectralDisplay extends StackPane
/**
* DFT processor. Register it with the sample source to feed the display.
*/
/**
* Adds a listener for the dBFS spectrum frames, lowest frequency first. Frames arrive on the DFT processor thread.
*/
protected void addDecibelListener(DFTResultsListener listener)
{
mDecibelConverter.addListener(listener);
}
protected ComplexDftProcessor getDftProcessor()
{
return mDftProcessor;

View File

@@ -30,6 +30,8 @@ import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
@@ -52,6 +54,7 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
private final IntegerProperty mChannelBandwidth = new SimpleIntegerProperty(0);
private final LongProperty mCarrierOffset = new SimpleLongProperty(0);
private final BooleanProperty mCarrierOffsetValid = new SimpleBooleanProperty(false);
private final StringProperty mSignalReadout = new SimpleStringProperty();
private final Text mMeasure = new Text();
private final double mTextHeight;
@@ -66,6 +69,15 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
mChannelBandwidth.addListener((ob, ov, nv) -> requestRender());
mCarrierOffset.addListener((ob, ov, nv) -> requestRender());
mCarrierOffsetValid.addListener((ob, ov, nv) -> requestRender());
mSignalReadout.addListener((ob, ov, nv) -> requestRender());
}
/**
* Channel signal level readout shown below the channel bandwidth label, or null for none.
*/
public StringProperty signalReadoutProperty()
{
return mSignalReadout;
}
/**
@@ -163,6 +175,24 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
gc.setTextAlign(TextAlignment.LEFT);
gc.fillText(label, x, y);
}
//Signal readout centered on the channel, on the row below the carrier (PLL) label. Drawn last so that the
//carrier line doesn't cross it.
String readout = mSignalReadout.get();
if(edges != null && readout != null && !readout.isEmpty())
{
mMeasure.setText(readout);
double width = mMeasure.getLayoutBounds().getWidth();
double x = Math.max(3, Math.min(area.width() - width - 3, (edges[0] + edges[1] - width) / 2.0));
double y = 2 * (mTextHeight + 6);
//Nearly opaque, since the readout is centered on the channel where the carrier line usually is
gc.setFill(theme.getBackground(0.95));
gc.fillRoundRect(x - 3, y - 1, width + 6, mTextHeight + 2, 4, 4);
gc.setFill(opaque(theme.getChannelProcessing()));
gc.setTextAlign(TextAlignment.LEFT);
gc.fillText(readout, x, y);
}
}
@Override

View File

@@ -54,6 +54,8 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
private ReentrantLock mBufferListenerLock = new ReentrantLock();
private ReentrantLock mLock = new ReentrantLock();
protected Broadcaster<INativeBuffer> mNativeBufferBroadcaster = new Broadcaster();
private final TunerNoiseFloorEstimator mNoiseFloorEstimator = new TunerNoiseFloorEstimator(this::getFrequency,
this::getSampleRate, this::getUsableBandwidth);
protected FrequencyController mFrequencyController;
private int mMiddleUnusableHalfBandwidth;
private int mMeasuredFrequencyError;
@@ -726,6 +728,15 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
//Note: unprotected access to the broadcaster ... the broadcaster uses thread-save internal list
mNativeBufferBroadcaster.broadcast(complexSamples);
mNoiseFloorEstimator.receive(complexSamples);
}
/**
* Noise floor estimator for this tuner, which measures on demand from the buffers that this controller delivers.
*/
public TunerNoiseFloorEstimator getNoiseFloorEstimator()
{
return mNoiseFloorEstimator;
}
/**

View File

@@ -0,0 +1,463 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* 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, either 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 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/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.dsp.fft.MixedRadixComplexFFT;
import io.github.dsheirer.dsp.window.WindowFactory;
import io.github.dsheirer.dsp.window.WindowType;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
import io.github.dsheirer.util.ThreadPool;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Estimates a tuner's noise floor from the tuner's sample buffers, independent of the channelizer that sources the
* tuner's channels. A windowed FFT with bins of about 25 kHz measures the tuner bandwidth and each bin's mean power is
* converted to a noise power density once a second.
*
* A channel's noise floor is the median of the 40 usable bins nearest the channel (about +/- 500 kHz), excluding the
* channel's own bins and their immediate neighbors. Near a band edge, the search continues toward the band center so
* that channels anywhere in the tuner's usable bandwidth get an estimate. Usable bins are the tuner's usable
* bandwidth, which is where the channel source managers place channels, minus the DC spur. Most bins hold only noise, so the median is a robust noise estimate unless more than
* half of the neighborhood is occupied. The estimate is local because real tuner noise floors aren't flat: a
* HydraSDR airband recording tilts about 6 dB across 8 MHz, which put a tuner-wide median 2 dB above the noise at one
* end of the band.
*
* The noise density is in full-scale units per Hertz, where a complex tone with a magnitude of 1.0 has a power of 1.0
* (0 dBFS). The channelizers preserve the tuner's full scale, so the noise density applies directly to channel
* samples.
*
* Measurement is on demand. A noise density request turns it on and it turns itself off when there are no requests
* for a few seconds. While it's off, the tuner's buffer delivery thread only checks a flag. While it's on, the
* delivery thread keeps a reference to the latest buffer and a scheduled task measures a few FFT blocks from it 20
* times a second. The estimator never registers as a buffer listener, since that starts and stops tuner streaming.
*/
public class TunerNoiseFloorEstimator
{
private static final Logger LOGGER = LoggerFactory.getLogger(TunerNoiseFloorEstimator.class);
private static final double BIN_WIDTH = 25000.0;
//Minimum size so that low sample rate tuners have enough bins for a channel neighborhood, with narrower bins
private static final int MINIMUM_FFT_SIZE = 64;
//Window with low sidelobes so that strong signals don't leak into the noise bins
private static final WindowType WINDOW_TYPE = WindowType.BLACKMAN_HARRIS_7;
private static final long PROCESSING_INTERVAL_MS = 50;
private static final int BLOCKS_PER_INTERVAL = 8;
private static final long ESTIMATE_INTERVAL_MS = 1000;
private static final long REQUEST_TIMEOUT_MS = 3000;
//Fraction of the sample rate, centered on DC, that is used when the tuner's usable bandwidth isn't known. The
//tuner's anti-alias filter rolls off the edges.
private static final double DEFAULT_USABLE_BANDWIDTH_FRACTION = 0.8;
//Bins on each side of DC that are skipped to avoid the tuner's DC spur
private static final int DC_EXCLUSION_BINS = 1;
//Usable bins nearest the channel that form its noise neighborhood (+/- 500 kHz at 25 kHz bins)
private static final int NEIGHBORHOOD_BINS = 40;
//Bins on each side of a channel's own bins that are excluded since they can hold the channel's signal
private static final int GUARD_BINS = 1;
//Fewest neighborhood bins for an estimate
private static final int MINIMUM_NEIGHBORHOOD_BINS = 8;
/**
* Noise density of each bin, with the tuner frequency and sample rate that it was measured at. Bins are in FFT
* order: bin 0 is DC and bins above size / 2 are negative frequencies.
*/
private record Estimate(long frequency, double sampleRate, double[] density, boolean[] usable) {}
private final LongSupplier mFrequency;
private final DoubleSupplier mSampleRate;
private final IntSupplier mUsableBandwidth;
private final boolean mScheduled;
private final AtomicReference<INativeBuffer> mLatestBuffer = new AtomicReference<>();
private final Object mLock = new Object();
private volatile boolean mActive;
private volatile long mLastRequestTimestamp;
private volatile Estimate mEstimate;
private ScheduledFuture<?> mProcessingTask;
//Measurement state, accessed only by the processing task
private long mMeasurementFrequency;
private double mMeasurementSampleRate;
private MixedRadixComplexFFT mFFT;
private float[] mWindow;
private double mWindowPower;
private float[] mBlock;
private int mBlockPointer;
private double[] mBinPowerAccumulator;
private int mAccumulatedBlocks;
private long mMeasurementStart;
/**
* Constructs an instance
* @param frequency supplier for the tuner's center frequency
* @param sampleRate supplier for the tuner's sample rate
* @param usableBandwidth supplier for the tuner's usable bandwidth in Hertz, or 0 or less if unknown
*/
public TunerNoiseFloorEstimator(LongSupplier frequency, DoubleSupplier sampleRate, IntSupplier usableBandwidth)
{
this(frequency, sampleRate, usableBandwidth, true);
}
/**
* Constructs an instance
* @param frequency supplier for the tuner's center frequency
* @param sampleRate supplier for the tuner's sample rate
* @param usableBandwidth supplier for the tuner's usable bandwidth in Hertz, or 0 or less if unknown
* @param scheduled true to measure on a scheduled task, or false for tests that call process() directly
*/
TunerNoiseFloorEstimator(LongSupplier frequency, DoubleSupplier sampleRate, IntSupplier usableBandwidth,
boolean scheduled)
{
mFrequency = frequency;
mSampleRate = sampleRate;
mUsableBandwidth = usableBandwidth;
mScheduled = scheduled;
}
/**
* Receives each tuner buffer on the tuner's buffer delivery thread. Keeps the buffer only while measuring.
*/
public void receive(INativeBuffer buffer)
{
if(mActive)
{
mLatestBuffer.set(buffer);
}
}
/**
* Noise power density near a channel, in full-scale units per Hertz. Turns on the measurement. Thread safe.
* @param frequency of the channel
* @param bandwidth of the channel in Hertz
* @return noise density, or NaN when there isn't an estimate yet, the tuner frequency or sample rate changed since
* the estimate, or the channel isn't within the usable tuner bandwidth.
*/
public double getNoiseDensity(long frequency, int bandwidth)
{
mLastRequestTimestamp = System.currentTimeMillis();
if(!mActive)
{
start();
}
Estimate estimate = mEstimate;
if(estimate == null || estimate.frequency() != mFrequency.getAsLong() ||
estimate.sampleRate() != mSampleRate.getAsDouble())
{
return Double.NaN;
}
int size = estimate.density().length;
double binWidth = estimate.sampleRate() / size;
//Signed bin offsets from DC of the bins that the channel overlaps
int low = (int)Math.round((frequency - bandwidth / 2.0 - estimate.frequency()) / binWidth);
int high = (int)Math.round((frequency + bandwidth / 2.0 - estimate.frequency()) / binWidth);
int center = (int)Math.round((double)(frequency - estimate.frequency()) / binWidth);
if(Math.abs(center) >= size / 2)
{
return Double.NaN;
}
double[] values = new double[NEIGHBORHOOD_BINS];
int count = 0;
int below = low - GUARD_BINS - 1;
int above = high + GUARD_BINS + 1;
//Alternate outward on each side of the channel, so that a channel near a band edge continues toward the center
while(count < NEIGHBORHOOD_BINS && (below > -size / 2 || above < size / 2))
{
if(below > -size / 2)
{
int bin = below < 0 ? below + size : below;
if(estimate.usable()[bin])
{
values[count++] = estimate.density()[bin];
}
below--;
}
if(count < NEIGHBORHOOD_BINS && above < size / 2)
{
int bin = above < 0 ? above + size : above;
if(estimate.usable()[bin])
{
values[count++] = estimate.density()[bin];
}
above++;
}
}
return count >= MINIMUM_NEIGHBORHOOD_BINS ? median(values, count) : Double.NaN;
}
/**
* Turns on the measurement.
*/
private void start()
{
synchronized(mLock)
{
if(!mActive)
{
mActive = true;
if(mScheduled)
{
mProcessingTask = ThreadPool.SCHEDULED.scheduleAtFixedRate(this::processScheduled,
PROCESSING_INTERVAL_MS, PROCESSING_INTERVAL_MS, TimeUnit.MILLISECONDS);
}
}
}
}
/**
* Turns off the measurement and discards the estimate, so that a stale estimate isn't used when it turns back on.
*/
private void stop()
{
synchronized(mLock)
{
//A request can arrive between the timeout check and here
if(System.currentTimeMillis() - mLastRequestTimestamp <= REQUEST_TIMEOUT_MS)
{
return;
}
mActive = false;
if(mProcessingTask != null)
{
mProcessingTask.cancel(false);
mProcessingTask = null;
}
mLatestBuffer.set(null);
mEstimate = null;
mBinPowerAccumulator = null;
}
}
private void processScheduled()
{
try
{
if(System.currentTimeMillis() - mLastRequestTimestamp > REQUEST_TIMEOUT_MS)
{
stop();
return;
}
process(System.currentTimeMillis());
}
catch(Throwable t)
{
LOGGER.error("Error estimating tuner noise floor", t);
}
}
/**
* Measures a few FFT blocks from the latest buffer and updates the estimate once a second. Package private for
* tests, which call it directly instead of waiting for the scheduled task.
* @param now timestamp in milliseconds
*/
void process(long now)
{
INativeBuffer buffer = mLatestBuffer.getAndSet(null);
if(buffer == null)
{
return;
}
long frequency = mFrequency.getAsLong();
double sampleRate = mSampleRate.getAsDouble();
if(sampleRate <= 0)
{
return;
}
if(mBinPowerAccumulator == null || frequency != mMeasurementFrequency || sampleRate != mMeasurementSampleRate)
{
configure(frequency, sampleRate, now);
}
int blocks = 0;
int size = mWindow.length;
mBlockPointer = 0;
Iterator<InterleavedComplexSamples> iterator = buffer.iteratorInterleaved();
while(blocks < BLOCKS_PER_INTERVAL && iterator.hasNext())
{
float[] samples = iterator.next().samples();
int pointer = 0;
while(blocks < BLOCKS_PER_INTERVAL && pointer < samples.length)
{
int count = Math.min(samples.length - pointer, 2 * (size - mBlockPointer));
System.arraycopy(samples, pointer, mBlock, 2 * mBlockPointer, count);
pointer += count;
mBlockPointer += count / 2;
if(mBlockPointer == size)
{
measureBlock();
mBlockPointer = 0;
blocks++;
}
}
}
if(now - mMeasurementStart >= ESTIMATE_INTERVAL_MS && mAccumulatedBlocks > 0)
{
publish();
mMeasurementStart = now;
}
}
/**
* Sets up the FFT for the tuner's sample rate and restarts the measurement.
*/
private void configure(long frequency, double sampleRate, long now)
{
mMeasurementFrequency = frequency;
mMeasurementSampleRate = sampleRate;
mMeasurementStart = now;
mEstimate = null;
int size = getFftSize(sampleRate);
if(mWindow == null || mWindow.length != size)
{
mFFT = new MixedRadixComplexFFT(size);
mWindow = WindowFactory.getWindow(WINDOW_TYPE, size);
mBlock = new float[size * 2];
double sumSquares = 0.0;
for(float coefficient: mWindow)
{
sumSquares += coefficient * coefficient;
}
mWindowPower = sumSquares;
}
mBinPowerAccumulator = new double[size];
mAccumulatedBlocks = 0;
}
/**
* FFT size that gives bins of about 25 kHz, or narrower bins at low sample rates, using a size that the mixed
* radix FFT supports.
*/
static int getFftSize(double sampleRate)
{
int size = Math.max(MINIMUM_FFT_SIZE, (int)Math.round(sampleRate / BIN_WIDTH));
while(size > MINIMUM_FFT_SIZE && !MixedRadixComplexFFT.isSupported(size))
{
size--;
}
return size;
}
/**
* Windows the block, runs the FFT and accumulates each bin's power.
*/
private void measureBlock()
{
for(int x = 0; x < mWindow.length; x++)
{
mBlock[2 * x] *= mWindow[x];
mBlock[2 * x + 1] *= mWindow[x];
}
mFFT.forward(mBlock, 0);
for(int bin = 0; bin < mWindow.length; bin++)
{
float i = mBlock[2 * bin];
float q = mBlock[2 * bin + 1];
mBinPowerAccumulator[bin] += i * i + q * q;
}
mAccumulatedBlocks++;
}
/**
* Converts the accumulated bin powers to noise densities and publishes the estimate. For white noise with variance
* s^2 per complex sample, a windowed FFT bin has a mean power of s^2 * sum(w^2), and the noise density is s^2 / fs.
*/
private void publish()
{
int size = mBinPowerAccumulator.length;
double[] density = new double[size];
boolean[] usable = new boolean[size];
double scale = 1.0 / (mAccumulatedBlocks * mWindowPower * mMeasurementSampleRate);
int usableBandwidth = mUsableBandwidth != null ? mUsableBandwidth.getAsInt() : 0;
double usableFraction = usableBandwidth > 0 ? Math.min(1.0, usableBandwidth / mMeasurementSampleRate) :
DEFAULT_USABLE_BANDWIDTH_FRACTION;
double maximumOffset = size * usableFraction / 2.0;
for(int bin = 0; bin < size; bin++)
{
density[bin] = mBinPowerAccumulator[bin] * scale;
int offset = bin < (size + 1) / 2 ? bin : bin - size;
usable[bin] = Math.abs(offset) > DC_EXCLUSION_BINS && Math.abs(offset) <= maximumOffset;
}
mEstimate = new Estimate(mMeasurementFrequency, mMeasurementSampleRate, density, usable);
Arrays.fill(mBinPowerAccumulator, 0.0);
mAccumulatedBlocks = 0;
}
/**
* Median of the first count values. Sorts the values.
*/
private static double median(double[] values, int count)
{
Arrays.sort(values, 0, count);
int middle = count / 2;
return (count % 2 == 1) ? values[middle] : (values[middle - 1] + values[middle]) / 2.0;
}
/**
* Indicates if the measurement is turned on.
*/
public boolean isActive()
{
return mActive;
}
}

View File

@@ -84,6 +84,16 @@ public class MultiFrequencyTunerChannelSource extends TunerChannelSource
return source != null ? source.getTunerName() : null;
}
/**
* Noise density near the current frequency's tuner channel source.
*/
@Override
public double getNoiseDensity()
{
TunerChannelSource source = mTunerChannelSource;
return source != null ? source.getNoiseDensity() : Double.NaN;
}
/**
* Applies the channel decoder requested frequency correction.
* @param correction requested by the downstream processors.

View File

@@ -25,6 +25,7 @@ import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceEventListenerToProcessorAdapter;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.TunerNoiseFloorEstimator;
import io.github.dsheirer.source.tuner.frequency.ChannelFrequencyErrorManager;
import io.github.dsheirer.source.tuner.frequency.TunerFrequencyErrorManager;
import org.slf4j.Logger;
@@ -42,6 +43,7 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
private volatile long mStartTimestamp;
private volatile String mTunerName;
private volatile TunerNoiseFloorEstimator mNoiseFloorEstimator;
/**
* Tuner Channel Source is a Digital Drop Channel (DDC) abstract class that defines the minimum functionality
@@ -136,6 +138,28 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
* sources where the producer incorporates a sample delay buffer.
* @param timestamp in milliseconds since epoch, or 0 to start with current samples.
*/
/**
* Tuner noise power density near this channel, in full-scale units per Hertz, where a complex tone with a
* magnitude of 1.0 at the tuner input has a power of 1.0 (0 dBFS). Requesting the noise density turns on the
* tuner's noise floor measurement, which turns itself back off a few seconds after the last request.
* @return noise density, or NaN if the tuner channel source doesn't measure it or it isn't measured yet.
*/
public double getNoiseDensity()
{
TunerNoiseFloorEstimator estimator = mNoiseFloorEstimator;
TunerChannel channel = getTunerChannel();
return estimator != null && channel != null ?
estimator.getNoiseDensity(channel.getFrequency(), channel.getBandwidth()) : Double.NaN;
}
/**
* Sets the noise floor estimator of the tuner that sources this channel.
*/
public void setNoiseFloorEstimator(TunerNoiseFloorEstimator noiseFloorEstimator)
{
mNoiseFloorEstimator = noiseFloorEstimator;
}
public void setStartTimestamp(long timestamp)
{
mStartTimestamp = timestamp;

View File

@@ -656,6 +656,8 @@ public class TunerManager implements IDiscoveredTunerStatusListener
if(source != null)
{
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
.getNoiseFloorEstimator());
return source;
}
}
@@ -685,6 +687,8 @@ public class TunerManager implements IDiscoveredTunerStatusListener
if(source != null)
{
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
.getNoiseFloorEstimator());
}
}
catch(Exception e)

View File

@@ -0,0 +1,187 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* 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, either 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 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/>
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
import java.util.function.Consumer;
import java.util.function.DoubleSupplier;
/**
* Measures a channel's power within the channel bandwidth from dBFS spectrum frames and compares it to the tuner noise
* floor to produce the channel's signal level and signal-to-noise ratio.
*
* Uses the spectrum frames that a channel spectral display already calculates, so the measurement costs only a sum
* over the in-band bins of each frame. The frames come from a FullScaleDecibelConverter, lowest frequency first, with
* the channel centered in the frame. Each bin's power is the window's noise bandwidth times the noise power per bin
* width, so the in-band power is the sum of the in-band bin powers divided by the window noise bandwidth (in bins).
* That is also correct for a tone, whose power spreads across the main lobe bins by the same factor.
*
* Frames are averaged and a reading is produced every 500 milliseconds.
*
* Receive frames on one thread. The configuration can change from any thread.
*/
public class ChannelSignalMeter implements DFTResultsListener
{
private static final long READING_INTERVAL_MS = 500;
/**
* Channel measurement configuration.
* @param sampleRate of the channel samples
* @param bandwidth of the channel in Hertz
* @param noiseDensity supplier of the tuner noise density in full-scale units per Hertz, or NaN when unknown
*/
private record Configuration(double sampleRate, int bandwidth, DoubleSupplier noiseDensity) {}
/**
* Channel signal reading.
* @param dbfs channel power (signal plus noise) within the channel bandwidth, relative to full scale
* @param snr signal-to-noise ratio in dB, or NaN when the noise floor is unknown. Negative infinity when the
* channel power doesn't exceed the noise floor.
* @param noiseDbfs noise floor within the channel bandwidth, relative to full scale, or NaN when unknown
*/
public record Reading(double dbfs, double snr, double noiseDbfs)
{
/**
* Indicates if the signal-to-noise ratio is available
*/
public boolean hasSnr()
{
return !Double.isNaN(snr);
}
}
private final Consumer<Reading> mListener;
private final long mReadingInterval;
private volatile Configuration mConfiguration;
private volatile double mWindowNoiseBandwidth = 1.0;
private Configuration mAccumulatorConfiguration;
private double mPowerAccumulator;
private int mFrameCount;
private double mMeasuredBandwidth;
private long mReadingStart;
/**
* Constructs an instance
* @param listener to receive readings on the frame thread
*/
public ChannelSignalMeter(Consumer<Reading> listener)
{
this(listener, READING_INTERVAL_MS);
}
/**
* Constructs an instance with a custom reading interval, for tests.
* @param listener to receive readings on the frame thread
* @param readingInterval in milliseconds, or 0 for a reading from each frame
*/
ChannelSignalMeter(Consumer<Reading> listener, long readingInterval)
{
mListener = listener;
mReadingInterval = readingInterval;
}
/**
* Sets the channel to measure, or clears it.
* @param sampleRate of the channel samples, or 0 to clear the channel
* @param bandwidth of the channel in Hertz, or 0 to clear the channel
* @param noiseDensity supplier of the tuner noise density in full-scale units per Hertz, or null when unavailable
*/
public void setChannel(double sampleRate, int bandwidth, DoubleSupplier noiseDensity)
{
mConfiguration = (sampleRate > 0 && bandwidth > 0) ? new Configuration(sampleRate, bandwidth, noiseDensity) : null;
}
/**
* Sets the noise bandwidth of the DFT window, in bins.
*/
public void setWindowNoiseBandwidth(double noiseBandwidth)
{
mWindowNoiseBandwidth = noiseBandwidth > 0 ? noiseBandwidth : 1.0;
}
/**
* Receives a dBFS spectrum frame for the channel.
*/
@Override
public void receive(float[] frame)
{
Configuration configuration = mConfiguration;
if(configuration == null || frame == null || frame.length == 0)
{
return;
}
long now = System.currentTimeMillis();
//Restart on a channel change
if(configuration != mAccumulatorConfiguration)
{
mAccumulatorConfiguration = configuration;
mPowerAccumulator = 0.0;
mFrameCount = 0;
mReadingStart = now;
}
int bins = frame.length;
double binWidth = configuration.sampleRate() / bins;
int halfWidth = Math.min(bins / 2 - 1, (int)Math.floor(configuration.bandwidth() / 2.0 / binWidth));
int center = bins / 2;
double power = 0.0;
for(int bin = center - halfWidth; bin <= center + halfWidth; bin++)
{
power += Math.pow(10.0, frame[bin] / 10.0);
}
mPowerAccumulator += power / mWindowNoiseBandwidth;
mMeasuredBandwidth = (2 * halfWidth + 1) * binWidth;
mFrameCount++;
if(now - mReadingStart >= mReadingInterval)
{
mListener.accept(getReading(mPowerAccumulator / mFrameCount, mMeasuredBandwidth,
configuration.noiseDensity()));
mPowerAccumulator = 0.0;
mFrameCount = 0;
mReadingStart = now;
}
}
/**
* Creates a reading.
* @param power within the measured bandwidth in full-scale units
* @param measuredBandwidth in Hertz
* @param noiseDensity supplier, or null
*/
static Reading getReading(double power, double measuredBandwidth, DoubleSupplier noiseDensity)
{
double dbfs = 10.0 * Math.log10(power);
double density = noiseDensity != null ? noiseDensity.getAsDouble() : Double.NaN;
if(Double.isFinite(density) && density > 0.0)
{
double noise = density * measuredBandwidth;
double snr = power > noise ? 10.0 * Math.log10((power - noise) / noise) : Double.NEGATIVE_INFINITY;
return new Reading(dbfs, snr, 10.0 * Math.log10(noise));
}
return new Reading(dbfs, Double.NaN, Double.NaN);
}
}