Compare commits

..

7 Commits

Author SHA1 Message Date
denny
b0689359d5 #2672 Bounds the polyphase buffer queue by sample duration instead of buffer count
The polyphase buffer processor queue was capped at 500 native buffers, which is
only about 85 ms of samples for an RSP at 6 MSPS (about 1,000 samples per
buffer) versus about 6.8 s for an RTL-SDR (32,768 samples per buffer).  Short
processing stalls overflowed the queue and dropped buffers on RSP tuners.

- Dispatcher: adds a weight-bounded queue option (element weigher plus an
  adjustable maximum queued weight).  Elements count toward the weight until
  the listener has processed them.
- PolyphaseChannelManager: bounds the buffer queue at 1 second of samples and
  updates the bound when the tuner sample rate changes.
- RspNativeBuffer: sampleCount() returned twice the complex sample count.  This
  also corrects the tuner sample drop monitor and the spectral display buffer
  manager for RSP tuners.
2026-11-17 02:55:22 -05:00
Denny Sheirer
6dd06288ac #2669 Adds System & Site columns to Now Playing, hidden by default (#2670)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:34:58 -05:00
Denny Sheirer
5fd469c402 #315 Adds Tuner column to Now Playing channels view (#2668)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:19:28 -05:00
Denny Sheirer
0bc5d6db64 #2620 Fix NPE in headless mode (#2667)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:04:33 -05:00
Denny Sheirer
80754558d6 #2662 Tuners monitor sample rate and log on excessive dropped samples. (#2663)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:02:11 -05:00
Denny Sheirer
2f9d52a56a #2665 Updates the README (#2666)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:01:40 -05:00
Denny Sheirer
5474a5a448 #2660 Now Playing Update With Talker Column & Column Management (#2661)
* #2660 Now Playing panel with events and messages are all recreated as JavaFX panels

* #2660 Talker alias cleanup across the decoders

* #2660 Talker alias cleanup across the decoders

---------

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 07:43:04 -05:00
21 changed files with 744 additions and 26 deletions

View File

@@ -1,7 +1,30 @@
![Gradle Build](https://github.com/dsheirer/sdrtrunk/actions/workflows/gradle.yml/badge.svg)
![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg)
[![Latest Release](https://img.shields.io/github/v/release/DSheirer/sdrtrunk?label=release)](https://github.com/DSheirer/sdrtrunk/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/DSheirer/sdrtrunk/total)](https://github.com/DSheirer/sdrtrunk/releases)
[![License](https://img.shields.io/github/license/DSheirer/sdrtrunk)](LICENSE)
[![Discord](https://img.shields.io/badge/chat-on%20Discord-5865F2?logo=discord&logoColor=white)](https://discord.gg/HJQaKYE)
# MacOS Tahoe 26.1 Users - Attention:
# sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
> ## 📖 [Read the sdrtrunk User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
> New to sdrtrunk? Start with the **[Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)** guide,
> then use the **[User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)** and
> **[How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)** to set up tuners, playlists, aliases and streaming.
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)
* [FAQ](https://github.com/DSheirer/sdrtrunk/wiki/FAQ)
* [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk primary application window decoding a P25 trunked radio system](https://github.com/DSheirer/sdrtrunk/wiki/images/application_overview.png)
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
## MacOS Tahoe 26.1 Users - Attention
Changes to USB support in Tahoe version 26.x cause sdrtrunk to fail to launch. Do the following to install the latest libusb and create a symbolic link and then use the nightly build which includes an updated usb4java native library for Tahoe with ARM processor. There may still be issue(s) with MacOS accessing your USB SDR tuners.
```
@@ -19,18 +42,6 @@ Finally, create a symbolic link from the installed library to the place where us
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
# sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User's Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk Application](https://github.com/DSheirer/sdrtrunk/wiki/images/sdrtrunk.png)
**Figure 1:** sdrtrunk Application Screenshot
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.

View File

@@ -68,7 +68,12 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private final static Logger mLog = LoggerFactory.getLogger(PolyphaseChannelManager.class);
private static final double CHANNEL_OVERSAMPLING = 2.0;
private static final int POLYPHASE_CHANNELIZER_TAPS_PER_CHANNEL = 9;
private static final int MAXIMUM_QUEUED_NATIVE_BUFFERS = 500;
/**
* Maximum duration of queued native buffers awaiting the channelizer. The queue is bounded by sample count instead
* of buffer count because tuner buffer sizes vary widely, for example about 1,000 samples per RSP buffer and 32,768
* samples per RTL-SDR buffer, so that each tuner can absorb a processing delay of the same duration.
*/
private static final double MAXIMUM_QUEUED_SECONDS = 1.0;
private Broadcaster<SourceEvent> mSourceEventBroadcaster = new Broadcaster<>();
private TunerController mTunerController;
@@ -78,7 +83,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private ComplexPolyphaseChannelizerM2 mPolyphaseChannelizer;
private ChannelSourceEventListener mChannelSourceEventListener = new ChannelSourceEventListener();
private NativeBufferReceiver mNativeBufferReceiver = new NativeBufferReceiver();
private Dispatcher mBufferDispatcher;
private Dispatcher<INativeBuffer> mBufferDispatcher;
private boolean mRunning = true;
/**
@@ -99,10 +104,21 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
mChannelCalculator = new ChannelCalculator(tunerController.getSampleRate(), channelCount,
tunerController.getFrequency(), CHANNEL_OVERSAMPLING);
mBufferDispatcher = new Dispatcher("sdrtrunk polyphase buffer processor", 10, MAXIMUM_QUEUED_NATIVE_BUFFERS);
mBufferDispatcher = new Dispatcher<>("sdrtrunk polyphase buffer processor", 10, INativeBuffer::sampleCount,
getMaximumQueuedSamples(tunerController.getSampleRate()));
mBufferDispatcher.setListener(mNativeBufferReceiver);
}
/**
* Calculates the maximum number of queued samples for the buffer dispatcher.
* @param sampleRate of the tuner
* @return maximum queued samples, at least one
*/
private static long getMaximumQueuedSamples(double sampleRate)
{
return Math.max(1, (long)(sampleRate * MAXIMUM_QUEUED_SECONDS));
}
/**
* Provides a description of the state of this manager.
*/
@@ -278,6 +294,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
double sampleRate = sourceEvent.getValue().doubleValue();
int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate);
mChannelCalculator.setRates(sampleRate, channelCount);
mBufferDispatcher.setMaximumQueuedWeight(getMaximumQueuedSamples(sampleRate));
break;
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_LOCKED:
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_UNLOCKED:

View File

@@ -840,11 +840,16 @@ public class SDRTrunk implements Listener<TunerEvent>
}
/**
* Updates the title bar with the tuner name
* Updates the title bar with the tuner name. No-op when running headless (no main window).
* @param tunerName optional
*/
private void updateTitle(String tunerName)
{
if(mMainGui == null)
{
return;
}
if(tunerName != null)
{
mMainGui.setTitle(mTitle + " - " + tunerName);

View File

@@ -40,6 +40,7 @@ import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
@@ -356,6 +357,21 @@ public class ChannelMetadataView extends VBox implements ChannelMetadataModel.Li
frequency.setCellFactory(NowPlayingCells.formatted(value -> frequencyFormat.format(value / 1e6d)));
columns.add(frequency);
//Tuner that sources the channel
columns.add(NowPlayingCells.column("tuner", "Tuner", null, Pos.CENTER,
row -> getTunerName(row.getChannelMetadata()), Row::revisionProperty));
//System and site labels from the channel configuration, hidden by default
TableColumn<Row,String> system = NowPlayingCells.column("system", "System", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getSystemConfigurationIdentifier()), Row::revisionProperty);
system.setVisible(false);
columns.add(system);
TableColumn<Row,String> site = NowPlayingCells.column("site", "Site", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getSiteConfigurationIdentifier()), Row::revisionProperty);
site.setVisible(false);
columns.add(site);
columns.add(NowPlayingCells.column("channel.name", "Channel Name", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getChannelNameConfigurationIdentifier()), Row::revisionProperty));
@@ -365,7 +381,8 @@ public class ChannelMetadataView extends VBox implements ChannelMetadataModel.Li
column.setSortable(false);
}
//Column numbers in the Swing version of the table, for its stored column widths. Talker is a new column.
//Column numbers in the Swing version of the table, for its stored column widths. Talker, Tuner, System and Site are new
//columns.
String[] swingColumns = {"status", "decoder", "from", "from.alias", "to", "to.alias", "channel", "frequency",
"channel.name"};
@@ -382,6 +399,22 @@ public class ChannelMetadataView extends VBox implements ChannelMetadataModel.Li
return columns;
}
/**
* Name of the tuner that sources the channel, or null if the channel isn't sourced by a tuner.
*/
private String getTunerName(ChannelMetadata channelMetadata)
{
Channel channel = mChannelMetadataModel.getChannelFromMetadata(channelMetadata);
ProcessingChain processingChain = channel != null ? mChannelProcessingManager.getProcessingChain(channel) : null;
if(processingChain != null && processingChain.getSource() instanceof TunerChannelSource tunerChannelSource)
{
return tunerChannelSource.getTunerName();
}
return null;
}
/**
* Decoder logical channel name with the timeslot, if any
*/

View File

@@ -57,6 +57,7 @@ public class TableColumnMonitor<S>
public static final String LEGACY_INDEX = "column.legacy.index";
private static final String ORDER = ".column.order";
private static final String HIDDEN = ".column.hidden";
private static final String KNOWN = ".column.known";
private static final String WIDTH = ".column.width.";
private static final String SEPARATOR = ",";
@@ -230,6 +231,7 @@ public class TableColumnMonitor<S>
mPreferences.remove(mKey + ORDER);
mPreferences.remove(mKey + HIDDEN);
mPreferences.remove(mKey + KNOWN);
}
/**
@@ -328,10 +330,13 @@ public class TableColumnMonitor<S>
if(hidden != null)
{
Set<String> hiddenIds = Set.of(hidden.isEmpty() ? new String[0] : hidden.split(SEPARATOR));
Set<String> knownIds = getKnownIds();
for(TableColumn<S,?> column: mDefaultOrder)
{
column.setVisible(!hiddenIds.contains(column.getId()));
//Columns that weren't in the table when the visibility was stored are new, so use the default
column.setVisible(knownIds.contains(column.getId()) ? !hiddenIds.contains(column.getId()) :
mDefaultVisibility.get(column));
}
if(getVisibleColumnCount() == 0)
@@ -375,6 +380,32 @@ public class TableColumnMonitor<S>
}
}
/**
* IDs of the columns that were in the table when the visibility was stored. Settings stored before the known
* columns were stored only had columns that are shown by default.
*/
private Set<String> getKnownIds()
{
String known = mPreferences.get(mKey + KNOWN, null);
if(known != null)
{
return Set.of(known.isEmpty() ? new String[0] : known.split(SEPARATOR));
}
Set<String> ids = new HashSet<>();
for(TableColumn<S,?> column: mDefaultOrder)
{
if(mDefaultVisibility.get(column))
{
ids.add(column.getId());
}
}
return ids;
}
private int getVisibleColumnCount()
{
int count = 0;
@@ -405,9 +436,12 @@ public class TableColumnMonitor<S>
private void storeVisibility()
{
List<String> ids = new ArrayList<>();
List<String> known = new ArrayList<>();
for(TableColumn<S,?> column: mDefaultOrder)
{
known.add(column.getId());
if(!column.isVisible())
{
ids.add(column.getId());
@@ -415,6 +449,7 @@ public class TableColumnMonitor<S>
}
mPreferences.put(mKey + HIDDEN, String.join(SEPARATOR, ids));
mPreferences.put(mKey + KNOWN, String.join(SEPARATOR, known));
}
private String getWidthKey(TableColumn<S,?> column)

View File

@@ -0,0 +1,206 @@
/*
* *****************************************************************************
* 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 java.text.DecimalFormat;
import java.util.function.DoubleSupplier;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Lightweight sample drop detector for tuners that don't provide sample counters or hardware timestamps. Counts the
* samples delivered by the tuner and compares the count against the number of samples expected from the sample rate
* and the elapsed (host) time. Logs a warning when the tuner consistently delivers fewer samples than expected, which
* indicates that samples are being dropped (ie by the USB bus or because the host isn't keeping up).
*
* Detection: each evaluation window (5 seconds) produces a sample deficit (expected minus received). The deficit is
* accumulated with a cumulative sum that subtracts an allowance for the clock difference between the tuner and the
* host, and that never goes below zero. Buffer delivery jitter (ie a delayed buffer) adds a deficit to one window
* that the following window gives back, while dropped samples are never given back. So drops are only declared
* when the accumulated deficit exceeds the threshold at two consecutive evaluations.
*
* The stream is assumed to be stopped (ie no buffer listeners) or restarted when buffers stop arriving for longer than
* the restart gap, and detection restarts with the next buffer. Detection also restarts when the sample rate changes.
*
* Note: process() is invoked on the tuner's sample stream thread and is not thread safe.
*/
public class SampleDropMonitor
{
private static final Logger LOG = LoggerFactory.getLogger(SampleDropMonitor.class);
private static final DecimalFormat PERCENT_FORMAT = new DecimalFormat("0.00");
private static final long NANOS_PER_SECOND = 1_000_000_000L;
//Evaluation window
static final long WINDOW_NANOS = 5 * NANOS_PER_SECOND;
//Buffer arrival gap that indicates the stream was stopped and restarted
static final long RESTART_GAP_NANOS = 2 * NANOS_PER_SECOND;
//Minimum interval between warnings, so that drops are summarized instead of logged every window
static final long LOG_INTERVAL_NANOS = 60 * NANOS_PER_SECOND;
//Allowance for the tuner versus host clock difference and sample rate rounding (parts per million). Drop rates
//below this aren't detected.
static final double CLOCK_ALLOWANCE = 500.0 / 1_000_000.0;
//Accumulated deficit that indicates dropped samples, in milliseconds of samples
static final double THRESHOLD_MILLISECONDS = 20.0;
private final DoubleSupplier mSampleRateSupplier;
private final Supplier<String> mTunerNameSupplier;
private boolean mStarted = false;
private long mWindowStart;
private long mLastBuffer;
private long mLastLog;
private long mWindowSampleCount;
private double mSampleRate;
private double mAccumulatedDeficit;
private boolean mThresholdExceeded;
//Start of the period summarized by the next warning: the detection (re)start or the previous warning.
private long mReportStart;
private double mUnreportedDroppedSamples;
private long mTotalDroppedSamples;
/**
* Constructs an instance
* @param tunerNameSupplier provides the tuner name for log messages.
* @param sampleRateSupplier provides the tuner's current sample rate.
*/
public SampleDropMonitor(Supplier<String> tunerNameSupplier, DoubleSupplier sampleRateSupplier)
{
mTunerNameSupplier = tunerNameSupplier;
mSampleRateSupplier = sampleRateSupplier;
}
/**
* Total number of samples detected as dropped since this monitor was created.
*/
public long getTotalDroppedSamples()
{
return mTotalDroppedSamples;
}
/**
* Processes a buffer of samples received from the tuner.
* @param sampleCount number of (complex) samples in the buffer.
*/
public void process(int sampleCount)
{
process(sampleCount, System.nanoTime());
}
/**
* Processes a buffer of samples received from the tuner.
* @param sampleCount number of (complex) samples in the buffer.
* @param now arrival time in nanoseconds (System.nanoTime()).
*/
void process(int sampleCount, long now)
{
if(!mStarted || now - mLastBuffer > RESTART_GAP_NANOS)
{
restart(now);
return;
}
mLastBuffer = now;
//The samples of each buffer arriving within the window (after the window's starting buffer) were produced during
//the window.
mWindowSampleCount += sampleCount;
long elapsed = now - mWindowStart;
if(elapsed >= WINDOW_NANOS)
{
evaluate(now, elapsed);
}
}
/**
* Restarts detection. The buffer at the restart time starts the window and isn't counted, since its samples were
* produced before the window start.
*/
private void restart(long now)
{
mStarted = true;
mWindowStart = now;
mLastBuffer = now;
mLastLog = now - LOG_INTERVAL_NANOS;
mReportStart = now;
mUnreportedDroppedSamples = 0.0;
mWindowSampleCount = 0;
mSampleRate = mSampleRateSupplier.getAsDouble();
mAccumulatedDeficit = 0.0;
mThresholdExceeded = false;
}
/**
* Evaluates the completed window and starts the next window.
*/
private void evaluate(long now, long elapsed)
{
double sampleRate = mSampleRateSupplier.getAsDouble();
if(sampleRate != mSampleRate || sampleRate <= 0)
{
restart(now);
return;
}
double expected = sampleRate * elapsed / NANOS_PER_SECOND;
double deficit = expected - mWindowSampleCount;
mAccumulatedDeficit = Math.max(0.0, mAccumulatedDeficit + deficit - (expected * CLOCK_ALLOWANCE));
if(mAccumulatedDeficit > sampleRate * THRESHOLD_MILLISECONDS / 1000.0)
{
//Require the deficit to persist across a second window to rule out buffer delivery jitter.
if(mThresholdExceeded)
{
mUnreportedDroppedSamples += mAccumulatedDeficit;
mTotalDroppedSamples += (long)mAccumulatedDeficit;
mAccumulatedDeficit = 0.0;
mThresholdExceeded = false;
}
else
{
mThresholdExceeded = true;
}
}
else
{
mThresholdExceeded = false;
}
if(mUnreportedDroppedSamples > 0 && now - mLastLog >= LOG_INTERVAL_NANOS)
{
double period = (double)(now - mReportStart) / NANOS_PER_SECOND;
double milliseconds = mUnreportedDroppedSamples / sampleRate * 1000.0;
double percent = mUnreportedDroppedSamples / (sampleRate * period) * 100.0;
LOG.warn("Tuner [" + mTunerNameSupplier.get() + "] is dropping samples - approximately [" +
(long)mUnreportedDroppedSamples + "] samples (" + Math.round(milliseconds) + " ms, " +
PERCENT_FORMAT.format(percent) + "% of the sample stream) were lost over the last " +
Math.round(period) + " seconds. The USB bus or the computer isn't keeping up with the tuner's " +
"sample rate. Dropped samples cause decoders to lose sync and cause choppy audio. Try a " +
"different USB port or USB controller, avoid USB hubs and extension cables, don't share the USB " +
"controller with other tuners, or lower the tuner sample rate.");
mLastLog = now;
mReportStart = now;
mUnreportedDroppedSamples = 0.0;
}
mWindowStart = now;
mWindowSampleCount = 0;
}
}

View File

@@ -89,6 +89,7 @@ public abstract class Tuner implements ISourceEventProcessor, ITunerErrorListene
try
{
getTunerController().start();
getTunerController().setSampleDropMonitorTunerName(getPreferredName());
}
catch(SourceException se)
{

View File

@@ -63,6 +63,8 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
private ITunerErrorListener mTunerErrorListener;
private static final DecimalFormat DF = new DecimalFormat("0.000");
protected TunerFrequencyErrorManager mTunerFrequencyErrorManager;
private final SampleDropMonitor mSampleDropMonitor;
private volatile String mSampleDropMonitorTunerName;
/**
* Abstract tuner controller class. The tuner controller manages frequency bandwidth and currently tuned channels
@@ -75,6 +77,39 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
mFrequencyController = new FrequencyController(this);
mSourceEventListener = new SourceEventListenerToProcessorAdapter(this);
mTunerFrequencyErrorManager = new TunerFrequencyErrorManager(this);
mSampleDropMonitor = isSampleDropMonitorSupported() ? new SampleDropMonitor(this::getSampleDropMonitorTunerName,
this::getSampleRate) : null;
}
/**
* Indicates if the tuner's sample stream should be monitored for dropped samples by counting the samples delivered
* against the sample rate. Override to disable for sources that aren't real-time (ie recordings) or for tuners
* that detect dropped samples from hardware sample counters or timestamps.
*
* Note: invoked from this class's constructor, so overrides must not depend on subclass state.
* @return true to monitor (default).
*/
protected boolean isSampleDropMonitorSupported()
{
return true;
}
/**
* Sets the tuner name used when logging dropped sample warnings.
* @param tunerName to log
*/
public void setSampleDropMonitorTunerName(String tunerName)
{
mSampleDropMonitorTunerName = tunerName;
}
/**
* Tuner name for dropped sample warnings: the name set by the tuner, or the tuner type.
*/
private String getSampleDropMonitorTunerName()
{
String name = mSampleDropMonitorTunerName;
return name != null ? name : String.valueOf(getTunerType());
}
/**
@@ -684,6 +719,11 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
*/
protected void broadcast(INativeBuffer complexSamples)
{
if(mSampleDropMonitor != null)
{
mSampleDropMonitor.process(complexSamples.sampleCount());
}
//Note: unprotected access to the broadcaster ... the broadcaster uses thread-save internal list
mNativeBufferBroadcaster.broadcast(complexSamples);
}

View File

@@ -47,7 +47,7 @@ public class MultiFrequencyTunerChannelSource extends TunerChannelSource
private final static Logger mLog = LoggerFactory.getLogger(MultiFrequencyTunerChannelSource.class);
private TunerManager mTunerManager;
private TunerChannelSource mTunerChannelSource;
private volatile TunerChannelSource mTunerChannelSource;
private List<Long> mFrequencies;
private List<Long> mLockedFrequencies = new ArrayList<>();
private int mFrequencyListPointer = 0;
@@ -73,6 +73,17 @@ public class MultiFrequencyTunerChannelSource extends TunerChannelSource
mPreferredTuner = preferredTuner;
}
/**
* Name of the tuner that provides the current frequency's tuner channel source, which can change as the
* frequencies rotate.
*/
@Override
public String getTunerName()
{
TunerChannelSource source = mTunerChannelSource;
return source != null ? source.getTunerName() : null;
}
/**
* Applies the channel decoder requested frequency correction.
* @param correction requested by the downstream processors.

View File

@@ -41,6 +41,7 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
protected String mThreadName;
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
private volatile long mStartTimestamp;
private volatile String mTunerName;
/**
* Tuner Channel Source is a Digital Drop Channel (DDC) abstract class that defines the minimum functionality
@@ -112,6 +113,24 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
return mTunerChannel;
}
/**
* Name of the tuner that provides this channel source.
* @return preferred name of the tuner or null if not set
*/
public String getTunerName()
{
return mTunerName;
}
/**
* Sets the name of the tuner that provides this channel source.
* @param tunerName preferred name of the tuner
*/
public void setTunerName(String tunerName)
{
mTunerName = tunerName;
}
/**
* Sets the timestamp for the oldest samples to provide to this channel when it starts. This only applies to
* sources where the producer incorporates a sample delay buffer.

View File

@@ -99,7 +99,7 @@ public abstract class FCDTunerController extends TunerController
mComplexMixer = new ComplexMixer(mixerTDL, tunerType.getAudioFormat(), tunerType.getDisplayString(),
new ComplexShortAdapter());
mComplexMixer.setBufferSampleCount(getBufferSampleCount());
mComplexMixer.setBufferListener(mNativeBufferBroadcaster);
mComplexMixer.setBufferListener(this);
}
@Override

View File

@@ -151,6 +151,16 @@ public class LimeSdrTunerController extends TunerController
setUsableBandwidthPercentage(USABLE_BANDWIDTH_PERCENT);
}
/**
* Disables the generic sample drop monitor since dropped samples are counted exactly from the hardware sample
* timestamps (see countDroppedSamples()).
*/
@Override
protected boolean isSampleDropMonitorSupported()
{
return false;
}
@Override
public TunerType getTunerType()
{

View File

@@ -655,6 +655,7 @@ public class TunerManager implements IDiscoveredTunerStatusListener
if(source != null)
{
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
return source;
}
}
@@ -680,6 +681,11 @@ public class TunerManager implements IDiscoveredTunerStatusListener
{
source = discoveredTuner.getTuner().getChannelSourceManager().getSource(tunerChannel,
channelSpecification, threadName);
if(source != null)
{
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
}
}
catch(Exception e)
{

View File

@@ -129,6 +129,15 @@ public class RecordingTunerController extends TunerController
}
}
/**
* Disables the generic sample drop monitor since recordings are replayed and not limited to a real-time sample rate.
*/
@Override
protected boolean isSampleDropMonitorSupported()
{
return false;
}
@Override
public TunerType getTunerType()
{

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
* 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
@@ -70,7 +70,7 @@ public class RspNativeBuffer extends AbstractNativeBuffer
@Override
public int sampleCount()
{
return mISamples.length * 2;
return mISamples.length;
}
/**

View File

@@ -130,7 +130,7 @@ public abstract class RspTunerController<I extends IControlRsp> extends TunerCon
for(RspNativeBuffer buffer: buffers)
{
mNativeBufferBroadcaster.broadcast(buffer);
broadcast(buffer);
}
}

View File

@@ -90,6 +90,15 @@ public class TestTunerController extends TunerController
//No-op
}
/**
* Disables the generic sample drop monitor since the generated test sample stream is not a hardware sample stream.
*/
@Override
protected boolean isSampleDropMonitorSupported()
{
return false;
}
@Override
public TunerType getTunerType()
{

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 Dennis Sheirer
* 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
@@ -31,6 +31,8 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.ToLongFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -54,6 +56,9 @@ public class Dispatcher<E> implements Listener<E>
private HeartbeatManager mHeartbeatManager;
private long mDroppedCount = 0;
private long mLastOverflowLogTimestamp = 0;
private final ToLongFunction<E> mWeigher;
private volatile long mMaximumQueuedWeight = Long.MAX_VALUE;
private final AtomicLong mQueuedWeight = new AtomicLong();
/**
* Constructs an instance of a Dispatcher with integrated heartbeat support.
@@ -90,6 +95,7 @@ public class Dispatcher<E> implements Listener<E>
mThreadName = threadName;
mInterval = interval;
mQueue = new LinkedTransferQueue<>();
mWeigher = null;
}
/**
@@ -103,6 +109,46 @@ public class Dispatcher<E> implements Listener<E>
mThreadName = threadName;
mInterval = interval;
mQueue = new LinkedBlockingQueue<>(maximumQueueSize);
mWeigher = null;
}
/**
* Constructs an instance that is bounded by the total weight of the queued elements instead of the element count,
* for when element sizes vary widely, for example sample buffers from different tuners. An element is dropped
* when adding it would exceed the maximum weight, except when nothing is queued, so that an element heavier than
* the maximum is still delivered. Elements count toward the weight until the listener has processed them.
*
* @param threadName to name the dispatcher thread
* @param interval for processing each batch in milliseconds.
* @param weigher to calculate the weight of each element, for example a sample count.
* @param maximumQueuedWeight for the queued elements.
*/
public Dispatcher(String threadName, long interval, ToLongFunction<E> weigher, long maximumQueuedWeight)
{
if(weigher == null)
{
throw new IllegalArgumentException("Weigher cannot be null");
}
mThreadName = threadName;
mInterval = interval;
mQueue = new LinkedTransferQueue<>();
mWeigher = weigher;
setMaximumQueuedWeight(maximumQueuedWeight);
}
/**
* Sets the maximum total weight of the queued elements, for a dispatcher that was constructed with a weigher.
* @param maximumQueuedWeight for the queued elements.
*/
public void setMaximumQueuedWeight(long maximumQueuedWeight)
{
if(maximumQueuedWeight <= 0)
{
throw new IllegalArgumentException("Maximum queued weight must be positive: " + maximumQueuedWeight);
}
mMaximumQueuedWeight = maximumQueuedWeight;
}
/**
@@ -149,7 +195,27 @@ public class Dispatcher<E> implements Listener<E>
return false;
}
boolean queued = mQueue.offer(e);
boolean queued;
if(mWeigher != null)
{
long weight = mWeigher.applyAsLong(e);
long queuedWeight = mQueuedWeight.addAndGet(weight);
if(queuedWeight > mMaximumQueuedWeight && queuedWeight > weight)
{
mQueuedWeight.addAndGet(-weight);
queued = false;
}
else
{
queued = mQueue.offer(e);
}
}
else
{
queued = mQueue.offer(e);
}
if(!queued)
{
@@ -189,6 +255,7 @@ public class Dispatcher<E> implements Listener<E>
}
mQueue.clear();
mQueuedWeight.set(0);
mExecutorService = Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory(mThreadName));
Runnable r = (mHeartbeatManager != null ? new ProcessorWithHeartbeat() : new Processor());
@@ -210,6 +277,7 @@ public class Dispatcher<E> implements Listener<E>
mScheduledFuture.cancel(false);
mScheduledFuture = null;
mQueue.clear();
mQueuedWeight.set(0);
}
if(mExecutorService != null)
@@ -259,6 +327,8 @@ public class Dispatcher<E> implements Listener<E>
mListener.getClass() + "]", t);
}
}
release(element);
}
}
}
@@ -294,6 +364,19 @@ public class Dispatcher<E> implements Listener<E>
mListener.getClass() + "]", t);
}
}
release(element);
}
}
/**
* Removes the weight of a dequeued element from the queued weight, once the element is processed.
*/
private void release(E element)
{
if(mWeigher != null)
{
mQueuedWeight.addAndGet(-mWeigher.applyAsLong(element));
}
}

View File

@@ -212,6 +212,27 @@ public class TableColumnMonitorTest
});
}
@Test
public void newHiddenByDefaultColumnStaysHidden() throws Exception
{
onFx(() -> {
//Stored by a version without the hidden by default 'site' column and without the known columns
mPreferences.put(KEY + ".column.hidden", "a");
TableView<String> table = createTable("a", "b", "site");
table.getColumns().get(2).setVisible(false);
monitor(table);
assertEquals(List.of("b"), visibleIds(table));
//The user shows the column, which is kept in the next session
table.getColumns().get(2).setVisible(true);
TableView<String> restored = createTable("a", "b", "site", "system");
restored.getColumns().get(2).setVisible(false);
restored.getColumns().get(3).setVisible(false);
monitor(restored);
assertEquals(List.of("b", "site"), visibleIds(restored));
});
}
@Test
public void lastVisibleColumnCantBeHidden() throws Exception
{

View File

@@ -0,0 +1,146 @@
/*
* *****************************************************************************
* 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 java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Drives the sample drop monitor with simulated buffer arrival times.
*/
public class SampleDropMonitorTest
{
private static final double SAMPLE_RATE = 10_000_000.0;
private static final int BUFFER = 65_536;
private static final double BUFFER_NANOS = BUFFER / SAMPLE_RATE * 1e9;
/**
* Simulated tuner stream: buffers are produced at the sample rate (scaled by the tuner clock error) and arrive
* with optional delivery jitter.
*/
private static class Stream
{
private final SampleDropMonitor mMonitor = new SampleDropMonitor(() -> "test", () -> SAMPLE_RATE);
private final Random mRandom = new Random(42);
private final double mClockScale;
private final double mJitterNanos;
private double mProduced = 1_000_000_000.0;
Stream(double clockPpm, double jitterNanos)
{
mClockScale = 1.0 + clockPpm / 1e6;
mJitterNanos = jitterNanos;
}
/**
* Produces buffers for the duration, delivering all of them.
*/
void run(double seconds)
{
run(seconds, 0);
}
/**
* Produces buffers for the duration, dropping one of every dropInterval buffers (0 = none).
*/
void run(double seconds, int dropInterval)
{
long count = (long)(seconds * 1e9 / BUFFER_NANOS);
for(long x = 1; x <= count; x++)
{
mProduced += BUFFER_NANOS / mClockScale;
if(dropInterval > 0 && x % dropInterval == 0)
{
continue;
}
double jitter = mJitterNanos > 0 ? mRandom.nextDouble() * mJitterNanos : 0;
mMonitor.process(BUFFER, (long)(mProduced + jitter));
}
}
void pause(double seconds)
{
mProduced += seconds * 1e9;
}
long dropped()
{
return mMonitor.getTotalDroppedSamples();
}
}
@Test
void cleanStreamWithClockErrorAndJitterHasNoDrops()
{
Stream stream = new Stream(-100, 30_000_000);
stream.run(600);
assertEquals(0, stream.dropped());
stream = new Stream(100, 30_000_000);
stream.run(600);
assertEquals(0, stream.dropped());
}
@Test
void singleDeliveryStallIsNotADrop()
{
Stream stream = new Stream(0, 0);
stream.run(30);
//A 500 ms delivery stall: the buffers produced during the stall are all delivered when it ends
double stallEnd = stream.mProduced + 0.5e9;
while(stream.mProduced + BUFFER_NANOS < stallEnd)
{
stream.mProduced += BUFFER_NANOS;
stream.mMonitor.process(BUFFER, (long)stallEnd);
}
stream.run(30);
assertEquals(0, stream.dropped());
}
@Test
void droppedBuffersAreDetected()
{
Stream stream = new Stream(50, 10_000_000);
stream.run(60);
//Drop 1 of every 100 buffers (1%) for 60 seconds = ~0.6 seconds of samples
stream.run(60, 100);
stream.run(30);
double expected = 60.0 * SAMPLE_RATE / 100.0;
double dropped = stream.dropped();
assertTrue(Math.abs(dropped - expected) < expected * 0.1, "Dropped " + dropped + " expected " + expected);
}
@Test
void streamRestartIsNotADrop()
{
Stream stream = new Stream(0, 0);
stream.run(20);
stream.pause(10);
stream.run(20);
assertEquals(0, stream.dropped());
}
}

View File

@@ -125,4 +125,60 @@ public class DispatcherTest
assertEquals(101, received.size());
}
/**
* Test: a weight-bounded queue drops elements that would exceed the maximum weight and keeps lighter ones.
*/
@Test
void weightBoundedQueueDropsElementsOverMaximumWeight() throws Exception
{
//Each element weighs its own value: 1 + 2 + 3 = 6 is queued, then 4 would exceed 6 and is dropped, then 0 fits
Dispatcher<Integer> dispatcher = new Dispatcher<>("test", 1, Integer::longValue, 6);
List<Integer> received = dispatchWhileBlocked(dispatcher, 4);
dispatcher.receive(0);
awaitSize(received, 5);
Thread.sleep(50);
dispatcher.stop();
assertEquals(List.of(0, 1, 2, 3, 0), received);
}
/**
* Test: an element heavier than the maximum weight is delivered when nothing else is queued.
*/
@Test
void weightBoundedQueueAcceptsHeavyElementWhenEmpty() throws Exception
{
Dispatcher<Integer> dispatcher = new Dispatcher<>("test", 1, Integer::longValue, 6);
List<Integer> received = dispatchWhileBlocked(dispatcher, 0);
dispatcher.receive(100);
dispatcher.receive(1);
awaitSize(received, 2);
Thread.sleep(50);
dispatcher.stop();
assertEquals(List.of(0, 100), received);
}
/**
* Test: processed elements release their weight so that the queue accepts new elements after an overflow.
*/
@Test
void weightBoundedQueueRecoversAfterOverflow() throws Exception
{
Dispatcher<Integer> dispatcher = new Dispatcher<>("test", 1, Integer::longValue, 6);
List<Integer> received = dispatchWhileBlocked(dispatcher, 10);
awaitSize(received, 4);
Thread.sleep(50);
for(int x = 0; x < 3; x++)
{
dispatcher.receive(5);
awaitSize(received, 5 + x);
}
dispatcher.stop();
assertEquals(List.of(0, 1, 2, 3, 5, 5, 5), received);
}
}