Compare commits

..

2 Commits

Author SHA1 Message Date
denny
e2950f30fa #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. 2026-11-19 03:15:56 -05:00
Denny Sheirer
61efb3d299 #2698 SIMD component factories explicitly handle UNCALIBRATED calibration state (#2699)
ComplexMixerFactory logged an unrecognized implementation warning when calibration had not been run (e.g. CI) before falling back to the scalar mixer. All SIMD component factories now map UNCALIBRATED to the scalar implementation explicitly.

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 03:06:50 -05:00
24 changed files with 1165 additions and 6 deletions

View File

@@ -42,6 +42,7 @@ public class ChannelDFTFactory
case VECTOR_SIMD_PREFERRED:
return new VectorChannelDFT(channelCount);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarChannelDFT(channelCount);
}

View File

@@ -42,6 +42,7 @@ public class DcRemovalFilterFactory
case VECTOR_SIMD_PREFERRED:
return new VectorDcRemovalFilter(gain);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarDcRemovalFilter(gain);
}

View File

@@ -52,6 +52,7 @@ public class FmDemodulatorFactory
case VECTOR_SIMD_512:
return new VectorFMDemodulator512();
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarFMDemodulator();
}

View File

@@ -44,6 +44,7 @@ public class ComplexGainFactory
return new VectorComplexGainControl();
}
case SCALAR:
case UNCALIBRATED:
default:
return new ComplexGainControl();
}
@@ -64,6 +65,7 @@ public class ComplexGainFactory
return new VectorComplexGain(gain);
}
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexGain(gain);
}

View File

@@ -52,6 +52,7 @@ public class MagnitudeFactory
case VECTOR_SIMD_512:
return new VectorMagnitudeCalculator512();
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarMagnitudeCalculator();
}

View File

@@ -49,6 +49,7 @@ public class ComplexMixerFactory
return new VectorComplexMixer(frequency, sampleRate);
}
case SCALAR:
case UNCALIBRATED:
{
return new ScalarComplexMixer(frequency, sampleRate);
}

View File

@@ -49,6 +49,7 @@ public class OscillatorFactory
case VECTOR_SIMD_PREFERRED:
return new VectorRealOscillator(frequency, sampleRate);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarRealOscillator(frequency, sampleRate);
}
@@ -69,6 +70,7 @@ public class OscillatorFactory
case VECTOR_SIMD_PREFERRED:
return new VectorComplexOscillator(frequency, sampleRate);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexOscillator(frequency, sampleRate);
}

View File

@@ -45,7 +45,8 @@ public class DifferentialDemodulatorFactory
case VECTOR_SIMD_128 -> new DifferentialDemodulatorFloatVector128(sampleRate, symbolRate);
case VECTOR_SIMD_256 -> new DifferentialDemodulatorFloatVector256(sampleRate, symbolRate);
case VECTOR_SIMD_512 -> new DifferentialDemodulatorFloatVector512(sampleRate, symbolRate);
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate); //Includes SCALAR case
case SCALAR, UNCALIBRATED -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
};
}
}

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

@@ -52,6 +52,7 @@ public class DMRSoftSyncDetectorFactory
case VECTOR_SIMD_512:
return new DMRSoftSyncDetectorVector512();
case SCALAR:
case UNCALIBRATED:
default:
return new DMRSoftSyncDetectorScalar();
}

View File

@@ -51,6 +51,7 @@ public class NXDNSyncDetectorFactory
case VECTOR_SIMD_512:
return new NXDNSoftSyncDetectorVector512();
case SCALAR:
case UNCALIBRATED:
default:
return new NXDNSoftSyncDetectorScalar();
}

View File

@@ -52,6 +52,7 @@ public class P25P1SoftSyncDetectorFactory
case VECTOR_SIMD_512:
return new P25P1SoftSyncDetectorVector512();
case SCALAR:
case UNCALIBRATED:
default:
return new P25P1SoftSyncDetectorScalar();
}

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);
}
}

View File

@@ -76,11 +76,9 @@ public class HistoryTableViewTest
table.getSelectionModel().select(0);
table.getSelectionModel().select(2);
//The copy shortcut is Cmd-C (meta) on macOS and Ctrl-C elsewhere
boolean mac = System.getProperty("os.name", "").toLowerCase().startsWith("mac");
Clipboard.getSystemClipboard().clear();
Event.fireEvent(table, new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.C, false,
!mac, false, mac));
true, false, false));
copied.complete(Clipboard.getSystemClipboard().getString());
}
catch(Throwable t)

View File

@@ -0,0 +1,204 @@
/*
* *****************************************************************************
* 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.sample.complex.ComplexSamples;
import io.github.dsheirer.sample.complex.ComplexSamplesNativeBufferAdapter;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Feeds white noise of a known density to the tuner noise floor estimator and checks the channel noise density.
*/
public class TunerNoiseFloorEstimatorTest
{
private static final long CENTER = 100_000_000L;
private static final double NOISE_VARIANCE = 1E-4;
/**
* Noise with optional tones, one buffer per 50 ms processing interval.
*/
private static class Generator
{
private final Random mRandom = new Random(1234);
private final double mSampleRate;
private final double[] mToneOffsets;
private final double mToneMagnitude;
private long mSample;
Generator(double sampleRate, double toneMagnitude, double... toneOffsets)
{
mSampleRate = sampleRate;
mToneMagnitude = toneMagnitude;
mToneOffsets = toneOffsets;
}
ComplexSamplesNativeBufferAdapter next(int length)
{
float[] i = new float[length];
float[] q = new float[length];
double sigma = Math.sqrt(NOISE_VARIANCE / 2.0);
for(int x = 0; x < length; x++)
{
double vi = mRandom.nextGaussian() * sigma;
double vq = mRandom.nextGaussian() * sigma;
for(double offset: mToneOffsets)
{
double phase = 2.0 * Math.PI * offset * (mSample + x) / mSampleRate;
vi += mToneMagnitude * Math.cos(phase);
vq += mToneMagnitude * Math.sin(phase);
}
i[x] = (float)vi;
q[x] = (float)vq;
}
mSample += length;
return new ComplexSamplesNativeBufferAdapter(new ComplexSamples(i, q, 0));
}
}
/**
* Runs 2 seconds of buffers through the estimator and returns the noise density in dBFS/Hz for the channel.
*/
private static double run(double sampleRate, Generator generator, long channelFrequency, int bandwidth)
{
TunerNoiseFloorEstimator estimator = new TunerNoiseFloorEstimator(() -> CENTER, () -> sampleRate,
() -> (int)(sampleRate * 0.98), false);
assertTrue(Double.isNaN(estimator.getNoiseDensity(channelFrequency, bandwidth)), "no estimate before measuring");
assertTrue(estimator.isActive(), "request turns on the measurement");
int bufferLength = TunerNoiseFloorEstimator.getFftSize(sampleRate) * 8;
for(long now = 0; now <= 2000; now += 50)
{
estimator.receive(generator.next(bufferLength));
estimator.process(now);
}
return 10.0 * Math.log10(estimator.getNoiseDensity(channelFrequency, bandwidth));
}
private static double expected(double sampleRate)
{
return 10.0 * Math.log10(NOISE_VARIANCE / sampleRate);
}
/**
* Test: noise density matches the injected noise at several tuner sample rates.
*/
@Test
void noiseDensity()
{
for(double sampleRate: new double[]{2_400_000.0, 10_000_000.0, 6_000_000.0, 250_000.0})
{
long offset = (long)Math.min(150_000, 0.2 * sampleRate);
double measured = run(sampleRate, new Generator(sampleRate, 0.0), CENTER + offset, 12500);
assertEquals(expected(sampleRate), measured, 0.3, "sample rate " + sampleRate);
}
}
/**
* Test: strong carriers on the channel and on a few neighbors, including adjacent 12.5 kHz channels, don't move
* the noise estimate.
*/
@Test
void occupiedNeighbors()
{
double sampleRate = 2_400_000.0;
long channel = CENTER + 150_000;
Generator generator = new Generator(sampleRate, 0.03, 150_000, 137_500, 162_500, 250_000, 50_000, 300_000);
assertEquals(expected(sampleRate), run(sampleRate, generator, channel, 12500), 0.5);
}
/**
* Test: channels near the tuner band edges, where the channel source managers can place them after a retune for a
* traffic channel, still get a noise estimate. Offsets up to 49% of the sample rate (98% of the bandwidth).
*/
@Test
void channelNearBandEdge()
{
for(double sampleRate: new double[]{2_400_000.0, 10_000_000.0})
{
for(double fraction: new double[]{0.38, 0.42, 0.45, 0.47, 0.49, -0.45, -0.47, -0.49})
{
long channel = CENTER + (long)(fraction * sampleRate);
double measured = run(sampleRate, new Generator(sampleRate, 0.0), channel, 12500);
assertEquals(expected(sampleRate), measured, 0.3, "sample rate " + sampleRate + " channel at " +
fraction + " of the sample rate");
}
}
}
/**
* Test: a tuner frequency change invalidates the estimate until the next one.
*/
@Test
void frequencyChange()
{
double sampleRate = 2_400_000.0;
AtomicLong frequency = new AtomicLong(CENTER);
TunerNoiseFloorEstimator estimator = new TunerNoiseFloorEstimator(frequency::get, () -> sampleRate,
() -> (int)(sampleRate * 0.98), false);
estimator.getNoiseDensity(CENTER, 12500);
Generator generator = new Generator(sampleRate, 0.0);
for(long now = 0; now <= 1100; now += 50)
{
estimator.receive(generator.next(1024));
estimator.process(now);
}
assertFalse(Double.isNaN(estimator.getNoiseDensity(CENTER + 100_000, 12500)));
frequency.set(CENTER + 1_000_000);
assertTrue(Double.isNaN(estimator.getNoiseDensity(CENTER + 1_100_000, 12500)));
}
/**
* Test: buffers aren't kept until a request turns on the measurement.
*/
@Test
void inactiveUntilRequested()
{
TunerNoiseFloorEstimator estimator = new TunerNoiseFloorEstimator(() -> CENTER, () -> 2_400_000.0, () -> 0,
false);
assertFalse(estimator.isActive());
estimator.receive(new Generator(2_400_000.0, 0.0).next(1024));
estimator.process(2000);
assertFalse(estimator.isActive());
}
/**
* Test: FFT sizes give bins of about 25 kHz, with a minimum size for low sample rates.
*/
@Test
void fftSize()
{
assertEquals(96, TunerNoiseFloorEstimator.getFftSize(2_400_000.0));
assertEquals(400, TunerNoiseFloorEstimator.getFftSize(10_000_000.0));
assertEquals(64, TunerNoiseFloorEstimator.getFftSize(250_000.0));
}
}

View File

@@ -0,0 +1,147 @@
/*
* *****************************************************************************
* 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 io.github.dsheirer.dsp.window.WindowType;
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.jtransforms.fft.FloatFFT_1D;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Builds dBFS spectrum frames the same way as the channel spectral display (unity gain window, JTransforms DFT,
* full scale decibel converter) from a tone plus white noise of known levels, and checks the channel power and SNR.
*/
public class ChannelSignalMeterTest
{
private static final double SAMPLE_RATE = 50000.0;
private static final int BANDWIDTH = 12500;
private static final int DFT_SIZE = 4096;
private static final double NOISE_VARIANCE = 1E-4;
private static final double TOLERANCE_DB = 0.3;
private static final WindowType[] WINDOWS = {WindowType.BLACKMAN_HARRIS_7, WindowType.HANN, WindowType.HAMMING,
WindowType.NONE, WindowType.FLAT_TOP};
/**
* Averages the readings of 50 frames. Each reading is one frame, so this averages the power the same way as the
* meter's 500 ms reading interval.
*/
private static double[] measure(WindowType windowType, double toneMagnitude, double toneOffset)
{
List<ChannelSignalMeter.Reading> readings = new ArrayList<>();
ChannelSignalMeter meter = new ChannelSignalMeter(readings::add, 0);
meter.setChannel(SAMPLE_RATE, BANDWIDTH, () -> NOISE_VARIANCE / SAMPLE_RATE);
meter.setWindowNoiseBandwidth(ComplexDftProcessor.getNoiseBandwidth(windowType));
float[] window = ComplexDftProcessor.createWindow(windowType, DFT_SIZE, true);
FloatFFT_1D fft = new FloatFFT_1D(DFT_SIZE);
Random random = new Random(42);
double sigma = Math.sqrt(NOISE_VARIANCE / 2.0);
double phase = 0.0;
double increment = 2.0 * Math.PI * toneOffset / SAMPLE_RATE;
for(int frame = 0; frame < 50; frame++)
{
float[] samples = new float[DFT_SIZE * 2];
for(int x = 0; x < DFT_SIZE; x++)
{
samples[2 * x] = (float)((random.nextGaussian() * sigma + toneMagnitude * Math.cos(phase)) * window[x]);
samples[2 * x + 1] = (float)((random.nextGaussian() * sigma + toneMagnitude * Math.sin(phase)) * window[x]);
phase += increment;
}
fft.complexForward(samples);
meter.receive(FullScaleDecibelConverter.convert(samples));
}
double power = 0.0;
double noise = 0.0;
for(ChannelSignalMeter.Reading reading: readings)
{
power += Math.pow(10.0, reading.dbfs() / 10.0);
noise = reading.noiseDbfs();
}
power /= readings.size();
double noisePower = Math.pow(10.0, noise / 10.0);
return new double[]{10.0 * Math.log10(power), 10.0 * Math.log10((power - noisePower) / noisePower), noise};
}
private static double expectedNoiseDb()
{
return 10.0 * Math.log10(NOISE_VARIANCE / SAMPLE_RATE * BANDWIDTH);
}
/**
* Test: noise-only channel power matches the injected noise within the channel bandwidth, for each window.
*/
@Test
void noiseOnly()
{
for(WindowType windowType: WINDOWS)
{
double[] result = measure(windowType, 0.0, 0.0);
assertEquals(expectedNoiseDb(), result[0], TOLERANCE_DB, windowType + " channel dBFS");
assertEquals(expectedNoiseDb(), result[2], 0.05, windowType + " noise dBFS");
}
}
/**
* Test: tone plus noise power and SNR, with the tone off of a bin center, for each window.
*/
@Test
void toneAndNoise()
{
for(WindowType windowType: WINDOWS)
{
double magnitude = 0.01;
double[] result = measure(windowType, magnitude, 1234.5);
double tone = magnitude * magnitude;
double noise = NOISE_VARIANCE / SAMPLE_RATE * BANDWIDTH;
System.out.printf("%s dBFS %.2f (expected %.2f) SNR %.2f (expected %.2f)%n", windowType, result[0],
10.0 * Math.log10(tone + noise), result[1], 10.0 * Math.log10(tone / noise));
assertEquals(10.0 * Math.log10(tone + noise), result[0], TOLERANCE_DB, windowType + " channel dBFS");
assertEquals(10.0 * Math.log10(tone / noise), result[1], TOLERANCE_DB, windowType + " SNR");
}
}
/**
* Test: no noise density gives the channel power without an SNR.
*/
@Test
void unknownNoise()
{
List<ChannelSignalMeter.Reading> readings = new ArrayList<>();
ChannelSignalMeter meter = new ChannelSignalMeter(readings::add, 0);
meter.setChannel(SAMPLE_RATE, BANDWIDTH, () -> Double.NaN);
float[] frame = new float[DFT_SIZE];
java.util.Arrays.fill(frame, -100.0f);
meter.receive(frame);
assertEquals(1, readings.size());
assertFalse(readings.getFirst().hasSnr());
}
}