mirror of
https://github.com/DSheirer/sdrtrunk.git
synced 2026-11-19 03:57:26 -05:00
#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:
@@ -243,7 +243,8 @@ public class ChannelSpectrumView extends SplitPane implements Listener<Processin
|
|||||||
|
|
||||||
if(source instanceof TunerChannelSource tcs)
|
if(source instanceof TunerChannelSource tcs)
|
||||||
{
|
{
|
||||||
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth);
|
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth,
|
||||||
|
tcs::getNoiseDensity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import io.github.dsheirer.buffer.INativeBuffer;
|
|||||||
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
|
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
|
||||||
import io.github.dsheirer.properties.SystemProperties;
|
import io.github.dsheirer.properties.SystemProperties;
|
||||||
import io.github.dsheirer.sample.Listener;
|
import io.github.dsheirer.sample.Listener;
|
||||||
|
import io.github.dsheirer.spectrum.ChannelSignalMeter;
|
||||||
|
import java.util.function.DoubleSupplier;
|
||||||
import javafx.geometry.Insets;
|
import javafx.geometry.Insets;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import javafx.scene.layout.StackPane;
|
import javafx.scene.layout.StackPane;
|
||||||
@@ -46,9 +48,11 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
|
|
||||||
private final ChannelTuningLayer mTuningLayer;
|
private final ChannelTuningLayer mTuningLayer;
|
||||||
private final EdgeSlider mNoiseFloorSlider;
|
private final EdgeSlider mNoiseFloorSlider;
|
||||||
|
private final ChannelSignalMeter mSignalMeter = new ChannelSignalMeter(this::showReading);
|
||||||
private final Object mLock = new Object();
|
private final Object mLock = new Object();
|
||||||
private boolean mActive;
|
private boolean mActive;
|
||||||
private boolean mHasChannel;
|
private volatile boolean mHasChannel;
|
||||||
|
private volatile boolean mHasNoiseDensity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an instance.
|
* Constructs an instance.
|
||||||
@@ -86,9 +90,46 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
|
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
|
||||||
getChildren().add(mNoiseFloorSlider);
|
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();
|
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.
|
* 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
|
* @param bandwidth of the channel in Hertz, or zero to hide the passband markers
|
||||||
*/
|
*/
|
||||||
public void setChannel(long frequency, int sampleRate, int bandwidth)
|
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)
|
synchronized(mLock)
|
||||||
{
|
{
|
||||||
mHasChannel = sampleRate > 0;
|
mHasChannel = sampleRate > 0;
|
||||||
|
mSignalMeter.setChannel(sampleRate, bandwidth, noiseDensity);
|
||||||
|
mHasNoiseDensity = noiseDensity != null;
|
||||||
updateProcessing();
|
updateProcessing();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +174,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
model.centerFrequencyProperty().set(frequency);
|
model.centerFrequencyProperty().set(frequency);
|
||||||
model.sampleRateProperty().set(sampleRate);
|
model.sampleRateProperty().set(sampleRate);
|
||||||
mTuningLayer.channelBandwidthProperty().set(bandwidth);
|
mTuningLayer.channelBandwidthProperty().set(bandwidth);
|
||||||
|
mTuningLayer.signalReadoutProperty().set(null);
|
||||||
mTuningLayer.carrierOffsetValidProperty().set(false);
|
mTuningLayer.carrierOffsetValidProperty().set(false);
|
||||||
mTuningLayer.carrierOffsetProperty().set(0);
|
mTuningLayer.carrierOffsetProperty().set(0);
|
||||||
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
|
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
|
||||||
@@ -195,6 +252,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
stopDft();
|
stopDft();
|
||||||
|
runOnFxThread(() -> mTuningLayer.signalReadoutProperty().set(null));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import io.github.dsheirer.gui.spectrum.layer.DecibelLayer;
|
|||||||
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
|
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
|
||||||
import io.github.dsheirer.properties.SystemProperties;
|
import io.github.dsheirer.properties.SystemProperties;
|
||||||
import io.github.dsheirer.spectrum.ComplexDftProcessor;
|
import io.github.dsheirer.spectrum.ComplexDftProcessor;
|
||||||
|
import io.github.dsheirer.spectrum.DFTResultsListener;
|
||||||
import io.github.dsheirer.spectrum.DFTSize;
|
import io.github.dsheirer.spectrum.DFTSize;
|
||||||
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
|
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
|
||||||
import javafx.application.Platform;
|
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.
|
* 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()
|
protected ComplexDftProcessor getDftProcessor()
|
||||||
{
|
{
|
||||||
return mDftProcessor;
|
return mDftProcessor;
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ import javafx.beans.property.LongProperty;
|
|||||||
import javafx.beans.property.SimpleBooleanProperty;
|
import javafx.beans.property.SimpleBooleanProperty;
|
||||||
import javafx.beans.property.SimpleIntegerProperty;
|
import javafx.beans.property.SimpleIntegerProperty;
|
||||||
import javafx.beans.property.SimpleLongProperty;
|
import javafx.beans.property.SimpleLongProperty;
|
||||||
|
import javafx.beans.property.SimpleStringProperty;
|
||||||
|
import javafx.beans.property.StringProperty;
|
||||||
import javafx.geometry.VPos;
|
import javafx.geometry.VPos;
|
||||||
import javafx.scene.canvas.GraphicsContext;
|
import javafx.scene.canvas.GraphicsContext;
|
||||||
import javafx.scene.paint.Color;
|
import javafx.scene.paint.Color;
|
||||||
@@ -52,6 +54,7 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
|
|||||||
private final IntegerProperty mChannelBandwidth = new SimpleIntegerProperty(0);
|
private final IntegerProperty mChannelBandwidth = new SimpleIntegerProperty(0);
|
||||||
private final LongProperty mCarrierOffset = new SimpleLongProperty(0);
|
private final LongProperty mCarrierOffset = new SimpleLongProperty(0);
|
||||||
private final BooleanProperty mCarrierOffsetValid = new SimpleBooleanProperty(false);
|
private final BooleanProperty mCarrierOffsetValid = new SimpleBooleanProperty(false);
|
||||||
|
private final StringProperty mSignalReadout = new SimpleStringProperty();
|
||||||
private final Text mMeasure = new Text();
|
private final Text mMeasure = new Text();
|
||||||
private final double mTextHeight;
|
private final double mTextHeight;
|
||||||
|
|
||||||
@@ -66,6 +69,15 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
|
|||||||
mChannelBandwidth.addListener((ob, ov, nv) -> requestRender());
|
mChannelBandwidth.addListener((ob, ov, nv) -> requestRender());
|
||||||
mCarrierOffset.addListener((ob, ov, nv) -> requestRender());
|
mCarrierOffset.addListener((ob, ov, nv) -> requestRender());
|
||||||
mCarrierOffsetValid.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.setTextAlign(TextAlignment.LEFT);
|
||||||
gc.fillText(label, x, y);
|
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
|
@Override
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
|
|||||||
private ReentrantLock mBufferListenerLock = new ReentrantLock();
|
private ReentrantLock mBufferListenerLock = new ReentrantLock();
|
||||||
private ReentrantLock mLock = new ReentrantLock();
|
private ReentrantLock mLock = new ReentrantLock();
|
||||||
protected Broadcaster<INativeBuffer> mNativeBufferBroadcaster = new Broadcaster();
|
protected Broadcaster<INativeBuffer> mNativeBufferBroadcaster = new Broadcaster();
|
||||||
|
private final TunerNoiseFloorEstimator mNoiseFloorEstimator = new TunerNoiseFloorEstimator(this::getFrequency,
|
||||||
|
this::getSampleRate, this::getUsableBandwidth);
|
||||||
protected FrequencyController mFrequencyController;
|
protected FrequencyController mFrequencyController;
|
||||||
private int mMiddleUnusableHalfBandwidth;
|
private int mMiddleUnusableHalfBandwidth;
|
||||||
private int mMeasuredFrequencyError;
|
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
|
//Note: unprotected access to the broadcaster ... the broadcaster uses thread-save internal list
|
||||||
mNativeBufferBroadcaster.broadcast(complexSamples);
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -84,6 +84,16 @@ public class MultiFrequencyTunerChannelSource extends TunerChannelSource
|
|||||||
return source != null ? source.getTunerName() : null;
|
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.
|
* Applies the channel decoder requested frequency correction.
|
||||||
* @param correction requested by the downstream processors.
|
* @param correction requested by the downstream processors.
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import io.github.dsheirer.source.ISourceEventProcessor;
|
|||||||
import io.github.dsheirer.source.SourceEvent;
|
import io.github.dsheirer.source.SourceEvent;
|
||||||
import io.github.dsheirer.source.SourceEventListenerToProcessorAdapter;
|
import io.github.dsheirer.source.SourceEventListenerToProcessorAdapter;
|
||||||
import io.github.dsheirer.source.SourceException;
|
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.ChannelFrequencyErrorManager;
|
||||||
import io.github.dsheirer.source.tuner.frequency.TunerFrequencyErrorManager;
|
import io.github.dsheirer.source.tuner.frequency.TunerFrequencyErrorManager;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -42,6 +43,7 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
|
|||||||
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
|
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
|
||||||
private volatile long mStartTimestamp;
|
private volatile long mStartTimestamp;
|
||||||
private volatile String mTunerName;
|
private volatile String mTunerName;
|
||||||
|
private volatile TunerNoiseFloorEstimator mNoiseFloorEstimator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tuner Channel Source is a Digital Drop Channel (DDC) abstract class that defines the minimum functionality
|
* 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.
|
* sources where the producer incorporates a sample delay buffer.
|
||||||
* @param timestamp in milliseconds since epoch, or 0 to start with current samples.
|
* @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)
|
public void setStartTimestamp(long timestamp)
|
||||||
{
|
{
|
||||||
mStartTimestamp = timestamp;
|
mStartTimestamp = timestamp;
|
||||||
|
|||||||
@@ -656,6 +656,8 @@ public class TunerManager implements IDiscoveredTunerStatusListener
|
|||||||
if(source != null)
|
if(source != null)
|
||||||
{
|
{
|
||||||
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
||||||
|
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
|
||||||
|
.getNoiseFloorEstimator());
|
||||||
return source;
|
return source;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -685,6 +687,8 @@ public class TunerManager implements IDiscoveredTunerStatusListener
|
|||||||
if(source != null)
|
if(source != null)
|
||||||
{
|
{
|
||||||
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
||||||
|
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
|
||||||
|
.getNoiseFloorEstimator());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch(Exception e)
|
catch(Exception e)
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user