Compare commits

...

8 Commits

Author SHA1 Message Date
denny
7d6fcb50d8 #2721 Gradle run task keeps the default JVM arguments when adding the splash screen
Calling jvmArgs on the run task replaced the applicationDefaultJvmArgs convention, dropping
--add-modules=jdk.incubator.vector, --enable-preview and the other defaults.  The splash argument is now
added through a jvmArgumentProvider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:25:26 -05:00
Denny Sheirer
156dd40bfe #2718 App branding, icons and splash screen. (#2719)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 04:06:12 -05:00
Denny Sheirer
e01dd02b74 #2715 Removes the MacOS Tahoe libusb workaround from the README; usb4java was replaced by jlibusb, which bundles libusb. (#2716)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 03:07:32 -05:00
Denny Sheirer
8324233acb #2704 Waterfall contrast for weak signals relative to the noise floor (#2712)
The waterfall mapped 256 palette indexes over the absolute dBFS level of the
mean bin value, about 2.5 steps per dB at a -100 dBFS floor, so weak signals
were only a few steps above the noise.  WaterfallScaler now tracks the noise
floor as a smoothed 25th percentile of the bins (robust to occupied spans) and
maps a fixed 45 dB span above it, so contrast no longer depends on sample size,
DFT size or tuner gain.  The classic palette's flat blue blocks are replaced
with a blue ramp over the bottom quarter, where the noise floor now sits.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 02:47:57 -05:00
Denny Sheirer
838e7708c0 #2713 HistoryTableViewTest fires the platform copy shortcut (Cmd-C on macOS) (#2714)
The copy handler matches KeyCombination.SHORTCUT_DOWN, which is Meta on
macOS, but the test always fired Ctrl-C, so nothing was copied on the Mac
CI runner.

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:43:38 -05:00
Denny Sheirer
d3a9adc06f #2697 talker alias auto-add only creates one alias for both the radio id and the fully qualified radio id when both are transmitted on the system (#2705)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-19 03:59:44 -05:00
Denny Sheirer
cd098955aa #2696 Change alias 'group' labeling to 'category' to avoid confusing group to mean talkgroup. (#2703)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-19 03:45:05 -05:00
Denny Sheirer
61efb3d299 #2698 SIMD component factories explicitly handle UNCALIBRATED calibration state (#2699)
ComplexMixerFactory logged an unrecognized implementation warning when calibration had not been run (e.g. CI) before falling back to the scalar mixer. All SIMD component factories now map UNCALIBRATED to the scalar implementation explicitly.

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

View File

@@ -25,24 +25,6 @@ A cross-platform java application for decoding, monitoring, recording and stream
![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.
```
brew install libusb --HEAD
cd /opt
sudo mkdir local
cd local
sudo mkdir lib
```
Next, find where brew installed the libusb library, for example: ```/opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib``` Note: the folder "HEAD-9ceaa52" is the version stamp for HEAD when you installed from it.
Finally, create a symbolic link from the installed library to the place where usb4java is expecting to find libusb (/opt/local/lib/libusb-1.0.0.dylib)
```
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.

View File

@@ -213,6 +213,14 @@ def jvmArgsLinux =
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
/**
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
*/
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
application {
mainClass = "io.github.dsheirer.gui.SDRTrunk"
@@ -224,6 +232,16 @@ application {
}
}
/**
* Adds the splash screen to the run task through an argument provider. Calling jvmArgs here would replace the
* applicationDefaultJvmArgs convention (--add-modules=jdk.incubator.vector, --enable-preview, etc.) instead of adding
* to it.
*/
tasks.named('run') {
def splashImage = file(splashResourceDir + '/' + splashImages[0]).absolutePath
jvmArgumentProviders.add({ ["-splash:${splashImage}".toString()] } as CommandLineArgumentProvider)
}
test {
if(os.isWindows()) {
jvmArgs = jvmArgsWindows
@@ -288,8 +306,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
* @return configured task.
*/
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//Use the correct set of JVM arguments
rt.extension.launcherData.get().jvmArgs = jvmArgs
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
//Additional modules to include with auto-detected modules.
//jdk.charsets - NXDN BIG5 encoding support
@@ -388,6 +406,22 @@ tasks.named('runtime') {rt ->
}
}
/**
* Copies the startup splash screen images into the lib folder of each runtime target image, where the launch scripts
* load them from (-splash:{{BIN_DIR}}/../lib/...).
*/
tasks.named('runtime') {rt ->
rt.doLast {
rt.targetPlatforms.get().keySet().each { target ->
def lib = new File(rt.imageDir.asFile, "${project.name}-${target}/lib")
splashImages.each { name ->
java.nio.file.Files.copy(file(splashResourceDir + '/' + name).toPath(), new File(lib, name).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
}
}
}
/**
* Verifies that each runtime target image contains every module that the sdrtrunk jar requires, as reported by jdeps.
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse

View File

@@ -52,7 +52,9 @@ import org.slf4j.LoggerFactory;
* </ul>
*
* Only aliases whose only identifier is the radio are created or renamed. An alias that combines the radio with other
* identifiers (e.g. several radios or talkgroups) is left alone.
* identifiers (e.g. several radios or talkgroups) is left alone. The exception is a P25 radio's simple and fully
* qualified radio identifiers with the same radio ID: the second form decoded is added to the alias for the first
* form, including a user alias outside the managed group, instead of creating a second alias for the same radio.
*
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
* JavaFX application thread.
@@ -200,6 +202,21 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
Alias existing = findExactMatch(aliasList.getAliases(radio), aliasId);
if(existing == null)
{
existing = findCompanion(aliasList.aliases(), radio, aliasId);
if(existing != null)
{
//Add the radio to the alias for the same radio's other identifier form, then continue below to
//compare the talker alias with the alias name (only managed aliases are renamed).
existing.addAliasID(aliasId);
aliasList.updateAlias(existing);
mLog.info("Talker alias radio [" + aliasId + "] added to existing alias [" + existing.getName() +
"] in alias list [" + mAliasListName + "]");
}
}
if(existing == null)
{
Alias alias = new Alias(value);
@@ -408,22 +425,114 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
}
/**
* Number of identifiers (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming.
* Finds the alias for the other identifier form of a P25 radio, so that a radio's simple and fully qualified
* identifiers share one alias instead of creating an alias for each. This includes user aliases outside the
* managed group, so that either identifier maps to the user's alias. The user alias is never renamed.
* <ul>
* <li>Fully qualified radio: the alias whose only identifier is the simple radio with the same radio
* ID. Only when the fully qualified radio isn't using a different local address (e.g. a roaming radio), since
* the radio ID then belongs to the home system and doesn't identify the radio on this system.</li>
* <li>Simple radio: the alias whose only identifier is a fully qualified radio with the same radio ID. None
* when more than one fully qualified radio alias matches.</li>
* </ul>
* @param aliases to search
* @param radio decoded radio identifier
* @param aliasId created from the decoded radio
* @return companion alias or null.
*/
private static int getIdentityCount(Alias alias)
@VisibleForTesting
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
{
int count = 0;
if(aliases == null || aliasId.getProtocol() != Protocol.APCO25)
{
return null;
}
boolean fullyQualified = aliasId instanceof P25FullyQualifiedRadio;
if(fullyQualified && !(radio instanceof FullyQualifiedRadioIdentifier fqri &&
fqri.getValue() != null && fqri.getValue() == fqri.getRadio()))
{
return null;
}
Alias match = null;
for(Alias alias: aliases)
{
if(getSoleIdentity(alias) instanceof Radio candidate &&
(candidate instanceof P25FullyQualifiedRadio) != fullyQualified &&
candidate.getProtocol() == Protocol.APCO25 && candidate.getValue() == aliasId.getValue())
{
if(match != null)
{
//Ambiguous - more than one candidate.
return null;
}
match = alias;
}
}
return match;
}
/**
* Identifier of an alias that has exactly one identifier, excluding audio settings.
* @return identifier or null if the alias has none or more than one.
*/
private static AliasID getSoleIdentity(Alias alias)
{
AliasID sole = null;
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isAudioIdentifier())
{
count++;
if(sole != null)
{
return null;
}
sole = id;
}
}
return count;
return sole;
}
/**
* Number of identities (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming. A P25 radio's simple and fully qualified radio identifiers with the same radio ID count as one
* identity.
*/
private static int getIdentityCount(Alias alias)
{
List<AliasID> ids = alias.getAliasIdentifiers().stream().filter(id -> !id.isAudioIdentifier()).toList();
if(ids.size() == 2 && isRadioPair(ids.get(0), ids.get(1)))
{
return 1;
}
return ids.size();
}
/**
* Indicates if the identifiers are the simple and fully qualified forms of the same P25 radio ID.
*/
private static boolean isRadioPair(AliasID a, AliasID b)
{
if(a instanceof P25FullyQualifiedRadio)
{
AliasID swap = a;
a = b;
b = swap;
}
return a instanceof Radio simple && !(a instanceof P25FullyQualifiedRadio) &&
b instanceof P25FullyQualifiedRadio fqr && simple.getProtocol() == Protocol.APCO25 &&
simple.getValue() == fqr.getValue();
}
private static String getKey(Radio aliasId)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,255 @@
/*
* *****************************************************************************
* 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.gui;
import java.awt.AWTEvent;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Taskbar;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.stage.Stage;
import javafx.stage.Window;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* sdrtrunk application icon for Swing frames and dialogs, JavaFX stages and the macOS Dock.
*
* Call installSwing() once at startup and installJavaFx() once the JavaFX toolkit is running. After that, each
* window that opens without its own icon gets the sdrtrunk icon, so individual windows don't have to set it.
*/
public final class ApplicationIcons
{
private static final Logger mLog = LoggerFactory.getLogger(ApplicationIcons.class);
private static final String RESOURCE_PATTERN = "/images/sdrtrunk/sdrtrunk-icon-%d.png";
private static final int[] SIZES = {16, 24, 32, 48, 64, 128, 256, 512};
private static final int TASKBAR_SIZE = 512;
private static List<Image> sAwtImages;
private static List<javafx.scene.image.Image> sFxImages;
private static boolean sSwingInstalled;
private static boolean sJavaFxInstalled;
private ApplicationIcons()
{
}
/**
* Application icon in each available size, smallest first, for Swing/AWT windows.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<Image> getAwtImages()
{
if(sAwtImages == null)
{
List<Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
Image image = ImageIO.read(in);
if(image != null)
{
images.add(image);
}
}
else
{
mLog.warn("Application icon resource not found [" + path + "]");
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sAwtImages = Collections.unmodifiableList(images);
}
return sAwtImages;
}
/**
* Application icon in each available size, smallest first, for JavaFX stages.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<javafx.scene.image.Image> getFxImages()
{
if(sFxImages == null)
{
List<javafx.scene.image.Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
javafx.scene.image.Image image = new javafx.scene.image.Image(in);
if(!image.isError())
{
images.add(image);
}
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sFxImages = Collections.unmodifiableList(images);
}
return sFxImages;
}
/**
* Sets the application icon on the Swing/AWT window if it doesn't already have one.
*/
public static void apply(java.awt.Window window)
{
if(window != null && window.getIconImages().isEmpty() && !getAwtImages().isEmpty())
{
window.setIconImages(getAwtImages());
}
}
/**
* Sets the application icon on the JavaFX stage if it doesn't already have one. Call on the FX thread.
*/
public static void apply(Stage stage)
{
if(stage != null && stage.getIcons().isEmpty() && !getFxImages().isEmpty())
{
stage.getIcons().setAll(getFxImages());
}
}
/**
* Sets the macOS Dock icon and gives each Swing frame and dialog that opens without an icon the application
* icon. Safe to call more than once. Does nothing in a headless environment.
*/
public static synchronized void installSwing()
{
if(sSwingInstalled || java.awt.GraphicsEnvironment.isHeadless())
{
return;
}
sSwingInstalled = true;
Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
if(event.getID() == WindowEvent.WINDOW_OPENED &&
(event.getSource() instanceof Frame || event.getSource() instanceof Dialog))
{
apply((java.awt.Window)event.getSource());
}
}, AWTEvent.WINDOW_EVENT_MASK);
//The Dock icon on macOS. Windows and Linux take the icon from each window instead.
try
{
if(Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
{
List<Image> images = getAwtImages();
for(int x = 0; x < SIZES.length && x < images.size(); x++)
{
if(SIZES[x] == TASKBAR_SIZE)
{
Taskbar.getTaskbar().setIconImage(images.get(x));
}
}
}
}
catch(Exception e)
{
mLog.debug("Unable to set taskbar icon", e);
}
}
/**
* Gives each JavaFX stage that shows without an icon the application icon, and closes the startup splash screen
* if a JavaFX window opens before the main window does. Safe to call more than once. The JavaFX toolkit must
* already be running.
*/
public static synchronized void installJavaFx()
{
if(sJavaFxInstalled)
{
return;
}
sJavaFxInstalled = true;
Platform.runLater(() -> {
for(Window window: Window.getWindows())
{
onFxWindowShown(window);
}
Window.getWindows().addListener((ListChangeListener<Window>)change -> {
while(change.next())
{
for(Window window: change.getAddedSubList())
{
onFxWindowShown(window);
}
}
});
});
}
/**
* Handles a JavaFX window that is showing.
*/
private static void onFxWindowShown(Window window)
{
//Only stages are top-level windows. JFXPanel content and popups (menus, tooltips) are other Window types.
if(window instanceof Stage stage)
{
apply(stage);
//A JavaFX window (e.g. an error dialog) that shows before the main window would sit behind the splash.
Splash.close();
}
}
}

View File

@@ -181,6 +181,7 @@ public class JavaFxWindowManager extends Application
{
mJFXPanel = new JFXPanel();
Platform.setImplicitExit(false);
ApplicationIcons.installJavaFx();
}
}

View File

@@ -144,12 +144,28 @@ public class SDRTrunk implements Listener<TunerEvent>
private String mTitle;
public SDRTrunk()
{
try
{
initialize();
}
catch(Throwable t)
{
startupFailed(t);
}
}
/**
* Creates and starts the application components and shows the main window.
*/
private void initialize()
{
if(!GraphicsEnvironment.isHeadless())
{
//Initialize the theme manager before any Swing components are realized so the chosen
//look-and-feel applies to the very first window that is created.
ThemeManager.getInstance().initialize(mUserPreferences);
ApplicationIcons.installSwing();
mMainGui = new JFrame();
}
@@ -273,6 +289,9 @@ public class SDRTrunk implements Listener<TunerEvent>
if(!GraphicsEnvironment.isHeadless())
{
mMainGui.setVisible(true);
//The JVM closes the splash when the first window shows. Close it here as well in case it didn't.
Splash.close();
Tuner tuner = tunerSpectralDisplayManager.showFirstTuner();
if(tuner != null)
@@ -311,7 +330,15 @@ public class SDRTrunk implements Listener<TunerEvent>
}
catch(Exception e)
{
e.printStackTrace();
if(mMainGui != null && !mMainGui.isVisible())
{
//The main window didn't open, so the user has no way to close the application.
startupFailed(e);
}
else
{
mLog.error("Error while starting the application", e);
}
}
});
}
@@ -361,6 +388,7 @@ public class SDRTrunk implements Listener<TunerEvent>
*/
mTitle = SystemProperties.getInstance().getApplicationName();
mMainGui.setTitle(mTitle);
ApplicationIcons.apply(mMainGui);
Point location = mUserPreferences.getSwingPreference().getLocation(WINDOW_FRAME_IDENTIFIER);
if(location != null)
@@ -967,11 +995,117 @@ public class SDRTrunk implements Listener<TunerEvent>
JOptionPane.showMessageDialog(mMainGui, message, "Duplicate Library Versions", JOptionPane.WARNING_MESSAGE);
}
/**
* Handles an error that stops the application from starting. Stops the tuners that already started, so that they
* are released for the next start, then reports the error and exits. Without this, the threads that the
* application started before the error keep the JVM running with no main window and the splash screen showing.
* @param t error
*/
private void startupFailed(Throwable t)
{
mLog.error("sdrtrunk failed to start", t);
if(mTunerManager != null)
{
try
{
mTunerManager.stop();
}
catch(Throwable t2)
{
mLog.error("Error stopping tuners after the startup error", t2);
}
}
String logsDirectory = null;
try
{
logsDirectory = mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog().toString();
}
catch(Throwable t2)
{
//Not available - the dialog leaves out the log location
}
if(mApplicationLog != null)
{
mApplicationLog.stop();
}
exitAfterStartupError(t, logsDirectory);
}
/**
* Closes the splash screen, shows the startup error to the user and exits the JVM with a non-zero status.
* @param t error
* @param logsDirectory where the application log is, or null if not known.
*/
private static void exitAfterStartupError(Throwable t, String logsDirectory)
{
//The application log may not be running yet, so also write the error to the console.
System.err.println("sdrtrunk failed to start");
t.printStackTrace();
Splash.close();
if(!GraphicsEnvironment.isHeadless())
{
String message = "<html><body style='width: 450px'>" +
"<p>sdrtrunk couldn't start because of this error:</p><br>" +
"<p><b>" + escapeHtml(String.valueOf(t)) + "</b></p><br>" +
(logsDirectory != null ? "<p>The application log has the details:</p><p>" +
escapeHtml(logsDirectory) + "</p><br>" : "") +
"<p>See Help / Support on the sdrtrunk wiki for help.</p>" +
"</body></html>";
try
{
Runnable dialog = () -> JOptionPane.showMessageDialog(null, message, "sdrtrunk Startup Error",
JOptionPane.ERROR_MESSAGE);
if(EventQueue.isDispatchThread())
{
dialog.run();
}
else
{
EventQueue.invokeAndWait(dialog);
}
}
catch(Throwable t2)
{
t2.printStackTrace();
}
}
System.exit(1);
}
/**
* Escapes text for display in a Swing HTML label.
*/
private static String escapeHtml(String text)
{
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
}
/**
* Launch the application.
*/
public static void main(String[] args)
{
new SDRTrunk();
String version = SDRTrunk.class.getPackage().getImplementationVersion();
Splash.showVersion(version != null ? "v" + version : null);
try
{
new SDRTrunk();
}
catch(Throwable t)
{
//An error creating the SDRTrunk fields, before the constructor's own startup error handling runs.
exitAfterStartupError(t, null);
}
}
}

View File

@@ -0,0 +1,117 @@
/*
* *****************************************************************************
* 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.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.SplashScreen;
/**
* Startup splash screen.
*
* The JVM shows the splash image named by the -splash:path option (set by the launch scripts) before any application
* code runs, and closes it when the main window becomes visible. This class draws the version on the splash and lets
* the application close the splash early, for example when a dialog has to show before the main window.
*
* Headless operation: the java launcher doesn't show the splash when -Djava.awt.headless=true is on the command line
* (for example in JAVA_OPTS or SDR_TRUNK_OPTS), and there is nothing to show it on without a display. This class does
* nothing when headless.
*/
public final class Splash
{
//Splash image layout, in pixels of the 640 x 360 image. The version goes under the tagline.
private static final double IMAGE_WIDTH = 640.0;
private static final double VERSION_X = 214.0;
private static final double VERSION_Y = 232.0;
private static final double VERSION_FONT_SIZE = 13.0;
private static final Color VERSION_COLOR = new Color(0x2E, 0xE6, 0xA6);
private Splash()
{
}
/**
* Draws the version text on the splash screen, if a splash screen is showing.
* @param version to show, for example "v1.0.1", or null to leave the splash unchanged.
*/
public static void showVersion(String version)
{
if(version == null || version.isBlank() || GraphicsEnvironment.isHeadless())
{
return;
}
try
{
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash == null || !splash.isVisible())
{
return;
}
//Overlay coordinates are in the splash's size, which can differ from the image (HiDPI @2x image).
Dimension size = splash.getSize();
double scale = size.width / IMAGE_WIDTH;
Graphics2D g = splash.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(VERSION_COLOR);
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, (int)Math.round(VERSION_FONT_SIZE * scale)));
g.drawString(version, (float)(VERSION_X * scale), (float)(VERSION_Y * scale));
g.dispose();
splash.update();
}
catch(Exception e)
{
//The splash is cosmetic. Never let it stop the application from starting.
}
}
/**
* Closes the splash screen if it is still showing.
*/
public static void close()
{
if(GraphicsEnvironment.isHeadless())
{
return;
}
try
{
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash != null && splash.isVisible())
{
splash.close();
}
}
catch(Exception e)
{
//The splash is cosmetic. Never let it stop the application from starting.
}
}
}

View File

@@ -660,7 +660,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
nameColumn.setPrefWidth(140);
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
groupColumn.setPrefWidth(140);

View File

@@ -1094,7 +1094,7 @@ public class AliasItemEditor extends Editor<Alias>
GridPane.setConstraints(getColorPicker(), 7, row);
mTextFieldPane.getChildren().add(getColorPicker());
Label groupLabel = new Label("Group");
Label groupLabel = new Label("Category");
groupLabel.setLabelFor(getGroupField());
GridPane.setHalignment(groupLabel, HPos.RIGHT);
GridPane.setConstraints(groupLabel, 0, ++row);

View File

@@ -243,7 +243,7 @@ public class AliasViewByIdentifierEditor extends VBox
aliasColumn.setPrefWidth(200);
TableColumn<AliasAndIdentifier, String> groupColumn = new TableColumn<>();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
groupColumn.setPrefWidth(200);

View File

@@ -241,7 +241,7 @@ public class AliasViewByRecordingEditor extends VBox
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(200);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
@@ -280,7 +280,7 @@ public class AliasViewByRecordingEditor extends VBox
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(200);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));

View File

@@ -694,8 +694,8 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases");
mAutoAddTalkerAliasesCheckBox.setDisable(true);
mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds decoded talker aliases as radio aliases in " +
"the Talker Alias group. Only radio aliases in that group are automatically renamed; existing " +
"radio aliases outside the group are left unchanged. Move an alias out of the Talker Alias group " +
"the Talker Alias category. Only radio aliases in that category are automatically renamed; existing " +
"radio aliases outside the category are left unchanged. Move an alias out of the Talker Alias category " +
"to preserve a custom name. Applies when the channel is (re)started."));
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
}

View File

@@ -225,7 +225,7 @@ public class StreamAliasSelectionEditor extends VBox
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(150);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
@@ -270,7 +270,7 @@ public class StreamAliasSelectionEditor extends VBox
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(150);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));

View File

@@ -65,7 +65,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
SpectralDisplayModel model = getSpectralDisplay().getModel();
getSpectralDisplay().messageProperty().set(MESSAGE_NO_CHANNEL);
//Noise floor slider along the right edge, below the configuration panel tab
//Noise floor slider for the spectrum
mNoiseFloorSlider = new EdgeSlider("Floor", "Noise floor: moves the bottom of the spectrum's dB range. " +
"Higher settings show a deeper range and move the noise floor up the display.",
MINIMUM_SAMPLE_SIZE, MAXIMUM_SAMPLE_SIZE, 1, this::formatPlotBottom);
@@ -82,9 +82,10 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
model.binCountProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
model.noiseBandwidthProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
mNoiseFloorSlider.refreshLabel();
//Along the right edge of the spectrum section, below the configuration panel tab
StackPane.setAlignment(mNoiseFloorSlider, Pos.CENTER_RIGHT);
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
getChildren().add(mNoiseFloorSlider);
getSpectralDisplay().addSectionOverlay(DisplaySection.SPECTRUM, mNoiseFloorSlider);
installConfigPanel();
}

View File

@@ -55,6 +55,8 @@ public abstract class DftSpectralDisplay extends StackPane
private static final String PEAK_HOLD = "peak.hold";
private static final String SPECTRUM_ENABLED = "spectrum.enabled";
private static final String WATERFALL_ENABLED = "waterfall.enabled";
private static final String WATERFALL_RANGE = "waterfall.range";
private static final String WATERFALL_AVERAGING = "waterfall.averaging";
private static final String DIVIDER_POSITION = "divider.position";
private static final String DECIBEL_SCALE = "decibel.scale";
private static final String CONFIG_PINNED = "config.pinned";
@@ -121,6 +123,9 @@ public abstract class DftSpectralDisplay extends StackPane
});
mSpectralDisplay.averagingProperty().addListener((ob, ov, nv) -> save(AVERAGING, nv.intValue()));
mSpectralDisplay.peakHoldProperty().addListener((ob, ov, nv) -> save(PEAK_HOLD, nv));
mSpectralDisplay.waterfallRangeProperty().addListener((ob, ov, nv) -> save(WATERFALL_RANGE, nv.intValue()));
mSpectralDisplay.waterfallAveragingProperty().addListener((ob, ov, nv) ->
save(WATERFALL_AVERAGING, nv.intValue()));
mSpectralDisplay.dividerPositionProperty().addListener((ob, ov, nv) ->
save(DIVIDER_POSITION, String.valueOf(nv.doubleValue())));
mDecibelLayer.visibleProperty().addListener((ob, ov, nv) -> save(DECIBEL_SCALE, nv));
@@ -205,6 +210,12 @@ public abstract class DftSpectralDisplay extends StackPane
mSpectralDisplay.averagingProperty().set(Math.max(SpectralDisplay.AVERAGING_MINIMUM,
Math.min(SpectralDisplay.AVERAGING_MAXIMUM, averaging)));
mSpectralDisplay.peakHoldProperty().set(properties.get(key(PEAK_HOLD), false));
mSpectralDisplay.waterfallRangeProperty().set(Math.max(WaterfallScaler.RANGE_MINIMUM,
Math.min(WaterfallScaler.RANGE_MAXIMUM, properties.get(key(WATERFALL_RANGE),
WaterfallScaler.RANGE_DEFAULT))));
mSpectralDisplay.waterfallAveragingProperty().set(Math.max(WaterfallScaler.AVERAGING_MINIMUM,
Math.min(WaterfallScaler.AVERAGING_MAXIMUM, properties.get(key(WATERFALL_AVERAGING),
WaterfallScaler.AVERAGING_DEFAULT))));
mDecibelLayer.visibleProperty().set(properties.get(key(DECIBEL_SCALE), true));
try

View File

@@ -42,6 +42,8 @@ import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Orientation;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
@@ -104,6 +106,10 @@ public class SpectralDisplay extends StackPane
private final SplitPane mSplitPane = new SplitPane();
private final CanvasPane mSpectrumPane = new CanvasPane(DisplaySection.SPECTRUM);
private final CanvasPane mWaterfallPane = new CanvasPane(DisplaySection.WATERFALL);
//Each section's canvas with overlay controls stacked on top
private final StackPane mSpectrumSection = new StackPane(mSpectrumPane);
private final StackPane mWaterfallSection = new StackPane(mWaterfallPane);
private final EdgeSlider mWaterfallRangeSlider;
private final StackPane mDisabledPane = new StackPane();
private final BooleanProperty mSpectrumEnabled = new SimpleBooleanProperty(true);
@@ -112,6 +118,8 @@ public class SpectralDisplay extends StackPane
private final IntegerProperty mAveraging = new SimpleIntegerProperty(AVERAGING_DEFAULT);
private final BooleanProperty mPeakHold = new SimpleBooleanProperty(false);
private final DoubleProperty mDividerPosition = new SimpleDoubleProperty(0.5);
private final IntegerProperty mWaterfallRange = new SimpleIntegerProperty(WaterfallScaler.RANGE_DEFAULT);
private final IntegerProperty mWaterfallAveraging = new SimpleIntegerProperty(WaterfallScaler.AVERAGING_DEFAULT);
private final StringProperty mMessage = new SimpleStringProperty();
//Values read on the DFT results thread
@@ -119,6 +127,7 @@ public class SpectralDisplay extends StackPane
private volatile boolean mWaterfallActive = true;
private volatile boolean mWaterfallPausedFlag = false;
private final SpectrumAverager mAverager = new SpectrumAverager();
private final WaterfallScaler mWaterfallScaler = new WaterfallScaler();
//Hand off from the DFT results thread to the JavaFX thread
private final AtomicReference<SpectrumAverager.Frame> mLatestSpectrum = new AtomicReference<>();
@@ -133,8 +142,10 @@ public class SpectralDisplay extends StackPane
private WritableImage[] mWaterfallTiles;
private int mWaterfallWidth;
private int mWaterfallHeight;
private byte[] mWaterfallIndexes;
private byte[] mWaterfallLevels;
private int[] mWaterfallPixels;
//ARGB color for each waterfall level code, for the current theme and range. Null when it needs to be rebuilt.
private int[] mWaterfallColors;
private int mWaterfallWriteRow = 0;
private double[] mPolygonX = new double[0];
private double[] mPolygonY = new double[0];
@@ -167,6 +178,37 @@ public class SpectralDisplay extends StackPane
themeChanged(disabledLabel);
getChildren().addAll(mDisabledPane, mSplitPane);
setMinSize(0, 0);
mSpectrumSection.setMinSize(0, 0);
mWaterfallSection.setMinSize(0, 0);
//Waterfall gain slider along the right edge of the waterfall. The slider value is inverted so that moving it
//up narrows the dB range, which raises the contrast of weak signals.
int rangeSum = WaterfallScaler.RANGE_MINIMUM + WaterfallScaler.RANGE_MAXIMUM;
mWaterfallRangeSlider = new EdgeSlider("Gain", "Waterfall gain: dB range from the noise floor to the top " +
"of the color palette. Higher settings use a smaller range, which gives weak signals more contrast " +
"against the noise and saturates strong signals sooner.", WaterfallScaler.RANGE_MINIMUM,
WaterfallScaler.RANGE_MAXIMUM, 1, value -> (rangeSum - Math.round(value)) + " dB");
mWaterfallRangeSlider.valueProperty().set(rangeSum - mWaterfallRange.get());
mWaterfallRangeSlider.valueProperty().addListener((ob, ov, nv) ->
mWaterfallRange.set(rangeSum - (int)Math.round(nv.doubleValue())));
mWaterfallRange.addListener((ob, ov, nv) -> {
int range = Math.max(WaterfallScaler.RANGE_MINIMUM, Math.min(WaterfallScaler.RANGE_MAXIMUM,
nv.intValue()));
if(range != nv.intValue())
{
mWaterfallRange.set(range);
return;
}
mWaterfallRangeSlider.valueProperty().set(rangeSum - range);
mWaterfallColors = null;
repaintWaterfallImage();
});
StackPane.setAlignment(mWaterfallRangeSlider, Pos.CENTER_RIGHT);
mWaterfallSection.getChildren().add(mWaterfallRangeSlider);
mWaterfallAveraging.addListener((ob, ov, nv) -> mWaterfallScaler.setAveraging(nv.intValue()));
mSpectrumEnabled.addListener((ob, ov, nv) -> updateSections());
mWaterfallEnabled.addListener((ob, ov, nv) -> updateSections());
@@ -261,6 +303,7 @@ public class SpectralDisplay extends StackPane
SpectralDisplayTheme theme = getTheme();
mDisabledPane.setBackground(new Background(new BackgroundFill(theme.getBackground(), null, null)));
disabledLabel.setTextFill(theme.getLine());
mWaterfallColors = null;
repaintWaterfallImage();
requestRender();
}
@@ -357,6 +400,42 @@ public class SpectralDisplay extends StackPane
return mPeakHold;
}
/**
* Waterfall dB range from the noise floor to the top of the color palette, from WaterfallScaler.RANGE_MINIMUM to
* RANGE_MAXIMUM. Smaller ranges give weak signals more contrast. JavaFX thread only.
*/
public IntegerProperty waterfallRangeProperty()
{
return mWaterfallRange;
}
/**
* Number of DFT frames averaged into each waterfall row, from WaterfallScaler.AVERAGING_MINIMUM to
* AVERAGING_MAXIMUM. Averaging steadies the noise floor so weak signals stand out, but the waterfall scrolls
* more slowly.
*/
public IntegerProperty waterfallAveragingProperty()
{
return mWaterfallAveraging;
}
/**
* Waterfall gain slider along the right edge of the waterfall section.
*/
public EdgeSlider getWaterfallRangeSlider()
{
return mWaterfallRangeSlider;
}
/**
* Adds a control on top of the spectrum or the waterfall section, for example an EdgeSlider. Set its StackPane
* alignment and margin before adding it. The control is hidden with its section.
*/
public void addSectionOverlay(DisplaySection section, javafx.scene.Node node)
{
(section == DisplaySection.SPECTRUM ? mSpectrumSection : mWaterfallSection).getChildren().add(node);
}
/**
* Divider position (0 - 1.0) between the spectrum and the waterfall when both are showing.
*/
@@ -395,6 +474,7 @@ public class SpectralDisplay extends StackPane
public void clear()
{
mAverager.reset();
mWaterfallScaler.reset();
mLatestSpectrum.set(null);
mWaterfallRows.clear();
@@ -412,10 +492,11 @@ public class SpectralDisplay extends StackPane
return;
}
//The first DFT results on startup can be NaN or infinite
//The first DFT results on startup can be NaN or infinite - drop them. Replacing them with zeros would add
//full scale (0 dBFS) values to the spectrum averaging and the waterfall floor tracking.
if(Float.isNaN(bins[0]) || Float.isInfinite(bins[0]))
{
bins = new float[bins.length];
return;
}
if(mSpectrumActive)
@@ -425,11 +506,16 @@ public class SpectralDisplay extends StackPane
if(mWaterfallActive && !mWaterfallPausedFlag)
{
mWaterfallRows.offer(toWaterfallRow(bins));
byte[] row = mWaterfallScaler.process(bins);
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
if(row != null)
{
mWaterfallRows.poll();
mWaterfallRows.offer(row);
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
{
mWaterfallRows.poll();
}
}
}
}
@@ -452,33 +538,7 @@ public class SpectralDisplay extends StackPane
mLatestSpectrum.set(null);
mWaterfallRows.clear();
mWaterfallTiles = null;
mWaterfallIndexes = null;
}
/**
* Converts the DFT results to a row of waterfall intensity indexes (0 - 255). Each bin is scaled relative to the
* average bin value so the noise floor stays at the bottom of the palette regardless of tuner gain.
*/
private static byte[] toWaterfallRow(float[] bins)
{
double sum = 0.0;
for(float bin: bins)
{
sum += bin;
}
float average = (float)(sum / bins.length) - 1.0f;
float scale = 256.0f / average;
byte[] row = new byte[bins.length];
for(int x = 0; x < bins.length; x++)
{
int value = (int)((average - bins[x]) * scale);
row[x] = (byte)Math.max(0, Math.min(255, value));
}
return row;
mWaterfallLevels = null;
}
/**
@@ -491,11 +551,11 @@ public class SpectralDisplay extends StackPane
mSpectrumActive = spectrum;
mWaterfallActive = waterfall;
List<Pane> items = new ArrayList<>();
List<StackPane> items = new ArrayList<>();
if(spectrum)
{
items.add(mSpectrumPane);
items.add(mSpectrumSection);
}
else
{
@@ -505,13 +565,16 @@ public class SpectralDisplay extends StackPane
if(waterfall)
{
items.add(mWaterfallPane);
items.add(mWaterfallSection);
}
else
{
mWaterfallRows.clear();
}
//Keep the waterfall slider below the configuration panel tab when the waterfall is at the top
StackPane.setMargin(mWaterfallRangeSlider, new Insets(spectrum ? 8 : 44, 0, 8, 0));
mSplitPane.getItems().setAll(items);
mSplitPane.setVisible(!items.isEmpty());
@@ -543,7 +606,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallTiles != null)
{
mWaterfallTiles = null;
mWaterfallIndexes = null;
mWaterfallLevels = null;
mWaterfallWriteRow = 0;
}
@@ -581,8 +644,8 @@ public class SpectralDisplay extends StackPane
/**
* Writes the row into the waterfall ring buffer. The newest row is at mWaterfallWriteRow and older rows follow
* it, wrapping around the end of the image. The intensity indexes are kept alongside the image so the history
* can be recolored when the theme changes.
* it, wrapping around the end of the image. The level codes are kept alongside the image so the history
* can be recolored when the theme or the waterfall range changes.
*/
private void writeWaterfallRow(byte[] row)
{
@@ -590,7 +653,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallTiles == null || mWaterfallWidth != row.length)
{
mWaterfallIndexes = new byte[row.length * rows];
mWaterfallLevels = new byte[row.length * rows];
createWaterfallTiles(row.length, rows);
mWaterfallWriteRow = 0;
repaintWaterfallImage();
@@ -602,7 +665,7 @@ public class SpectralDisplay extends StackPane
int width = row.length;
mWaterfallWriteRow = (mWaterfallWriteRow - 1 + mWaterfallHeight) % mWaterfallHeight;
System.arraycopy(row, 0, mWaterfallIndexes, mWaterfallWriteRow * width, width);
System.arraycopy(row, 0, mWaterfallLevels, mWaterfallWriteRow * width, width);
writeWaterfallPixels(mWaterfallWriteRow);
}
@@ -625,7 +688,7 @@ public class SpectralDisplay extends StackPane
}
/**
* Colors one row of the waterfall image tiles from the stored intensity indexes.
* Colors one row of the waterfall image tiles from the stored level codes.
*/
private void writeWaterfallPixels(int imageRow)
{
@@ -636,12 +699,12 @@ public class SpectralDisplay extends StackPane
mWaterfallPixels = new int[width];
}
SpectralDisplayTheme theme = getTheme();
int[] colors = getWaterfallColors();
int offset = imageRow * width;
for(int x = 0; x < width; x++)
{
mWaterfallPixels[x] = theme.getWaterfallColor(mWaterfallIndexes[offset + x]);
mWaterfallPixels[x] = colors[mWaterfallLevels[offset + x] & 0xFF];
}
for(int tile = 0; tile < mWaterfallTiles.length; tile++)
@@ -653,11 +716,33 @@ public class SpectralDisplay extends StackPane
}
/**
* Recolors the whole waterfall image from the stored intensity indexes using the current theme.
* ARGB color for each waterfall level code, for the current theme and range.
*/
private int[] getWaterfallColors()
{
if(mWaterfallColors == null)
{
SpectralDisplayTheme theme = getTheme();
int range = mWaterfallRange.get();
int[] colors = new int[256];
for(int level = 0; level < colors.length; level++)
{
colors[level] = theme.getWaterfallColor(WaterfallScaler.paletteIndex(level, range));
}
mWaterfallColors = colors;
}
return mWaterfallColors;
}
/**
* Recolors the whole waterfall image from the stored level codes using the current theme and range.
*/
private void repaintWaterfallImage()
{
if(mWaterfallTiles != null && mWaterfallIndexes != null)
if(mWaterfallTiles != null && mWaterfallLevels != null)
{
for(int y = 0; y < mWaterfallHeight; y++)
{
@@ -689,10 +774,10 @@ public class SpectralDisplay extends StackPane
for(int y = 0; y < previousHeight; y++)
{
int source = (mWaterfallWriteRow + y) % previousHeight;
System.arraycopy(mWaterfallIndexes, source * width, indexes, y * width, width);
System.arraycopy(mWaterfallLevels, source * width, indexes, y * width, width);
}
mWaterfallIndexes = indexes;
mWaterfallLevels = indexes;
createWaterfallTiles(width, rows);
mWaterfallWriteRow = 0;
repaintWaterfallImage();

View File

@@ -353,6 +353,27 @@ public class SpectralDisplayConfigPanel extends VBox
"falling slowly"));
row = addRow(grid, row, peakHold.label(), peakHold.control());
//Waterfall
grid.add(sectionLabel("Waterfall"), 0, row++, 2, 1);
ComboBox<Integer> waterfallAveraging = new ComboBox<>();
for(int frames = WaterfallScaler.AVERAGING_MINIMUM; frames <= WaterfallScaler.AVERAGING_MAXIMUM; frames++)
{
waterfallAveraging.getItems().add(frames);
}
waterfallAveraging.setMaxWidth(Double.MAX_VALUE);
waterfallAveraging.setConverter(converter(frames -> frames == 1 ? "Off" : frames + " frames"));
waterfallAveraging.setValue(mSpectralDisplay.waterfallAveragingProperty().get());
waterfallAveraging.valueProperty().addListener((ob, ov, nv) -> {
if(nv != null)
{
mSpectralDisplay.waterfallAveragingProperty().set(nv);
}
});
waterfallAveraging.setTooltip(new Tooltip("FFT frames averaged into each waterfall row. Averaging steadies " +
"the noise floor so weak signals stand out, but the waterfall scrolls more slowly."));
trackPopup(waterfallAveraging.showingProperty());
row = addRow(grid, row, "Averaging", waterfallAveraging);
//Layer settings
for(SpectralDisplayLayer layer: mSpectralDisplay.getLayers())
{

View File

@@ -33,44 +33,31 @@ public class WaterfallPalette
}
/**
* Palette of the original Swing waterfall: dark blue noise floor, a blue to yellow ramp, yellow fading to orange,
* then red.
* Palette based on the original Swing waterfall colors: a dark to bright blue ramp, a blue to yellow ramp, yellow
* fading to orange, then red. The blue ramp covers the bottom quarter of the palette, where the waterfall places
* the noise floor, so the noise stays blue and weak signals stand out from it.
*/
public static int[] classic()
{
int[] palette = new int[SIZE];
for(int x = 0; x < 16; x++)
for(int x = 0; x < 64; x++)
{
palette[x] = argb(0, 0, 127);
palette[x] = argb(0, 0, blend(64, 191, x / 63.0));
}
for(int x = 16; x < 32; x++)
for(int x = 64; x < 100; x++)
{
palette[x] = argb(0, 0, 191);
double t = (x - 64) / 36.0;
palette[x] = argb(blend(0, 255, t), blend(0, 255, t), blend(191, 0, t));
}
int r = 0;
int g = 0;
int b = 191;
for(int x = 32; x < 60; x++)
for(int x = 100; x < 220; x++)
{
palette[x] = argb(r, g, b);
r += 9;
g += 9;
b -= 6;
palette[x] = argb(255, blend(255, 0, (x - 100) / 120.0), 0);
}
g = 255;
for(int x = 60; x < 188; x++)
{
palette[x] = argb(255, g, 0);
g -= 2;
}
for(int x = 188; x < SIZE; x++)
for(int x = 220; x < SIZE; x++)
{
palette[x] = argb(255, 0, 0);
}
@@ -78,6 +65,11 @@ public class WaterfallPalette
return palette;
}
private static int blend(int from, int to, double fraction)
{
return (int)Math.round(from + (to - from) * fraction);
}
/**
* Palette that blends linearly between evenly spaced colors.
* @param colors web color strings (for example #440154), lowest intensity first

View File

@@ -0,0 +1,289 @@
/*
* *****************************************************************************
* 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.gui.spectrum;
import java.util.Arrays;
/**
* Converts DFT results in dB to rows of waterfall level codes, and level codes to palette indexes.
*
* Optionally averages several DFT frames (in linear power) into each row. Averaging reduces the random variation of
* the noise bins (about 5.6 dB for a single frame), which is the only thing that makes weak signals statistically
* easier to see, at the cost of fewer rows per second.
*
* The noise floor reference is a low percentile of the bins, so signals that fill much of the span don't raise it,
* smoothed across rows so the waterfall background doesn't flicker.
*
* Each row stores a level code per bin: the bin level relative to the floor reference in LEVEL_STEP_DB steps. The
* level codes are mapped to palette indexes over a dB range above the floor (see paletteIndex()) when the row is
* colored, so the range can change and the waterfall history can be recolored without the original DFT results.
*
* Not thread safe: process() on the DFT results thread only. reset() and setAveraging() are safe from any thread.
*/
public class WaterfallScaler
{
public static final int RANGE_MINIMUM = 20;
public static final int RANGE_MAXIMUM = 80;
public static final int RANGE_DEFAULT = 45;
public static final int AVERAGING_MINIMUM = 1;
public static final int AVERAGING_MAXIMUM = 4;
public static final int AVERAGING_DEFAULT = 2;
//Percentile of the bins used as the noise floor reference. Robust to signals in up to 75% of the bins.
static final double FLOOR_PERCENTILE = 0.25;
//Smoothing applied to the floor reference each row: about 5 rows. The percentile barely varies from row to row,
//so this mostly limits jumps from bursts of signals while still following tuner gain changes quickly.
static final float FLOOR_SMOOTHING = 0.2f;
//Floor reference changes larger than this jump straight to the new level instead of smoothing, for example when
//the first samples arrive after DFT frames of an empty buffer (-196 dB), or after a tuner or gain change.
static final float FLOOR_JUMP_DB = 10.0f;
//Level code resolution and the level code of the floor reference: codes cover -8 dB to +94 dB from the floor,
//which covers the palette at the maximum range.
static final float LEVEL_STEP_DB = 0.4f;
static final int FLOOR_LEVEL = 20;
//Palette index for the floor reference. Noise bins spread above the 25th percentile, so this places the noise in
//the lower part of the palette as texture with only the weakest noise bins at the background color.
static final float FLOOR_INDEX = 16.0f;
private static final float DB_TO_LN_POWER = (float)(Math.log(10.0) / 10.0);
private float mFloor = Float.NaN;
private volatile boolean mResetRequested;
private volatile int mAveraging = AVERAGING_DEFAULT;
private float[] mScratch = new float[0];
private float[] mPowerSum = new float[0];
private float[] mAverage = new float[0];
private int mFrameCount;
/**
* Restarts floor tracking and frame averaging on the next frame, for example after the source changes. Safe to
* call from any thread.
*/
public void reset()
{
mResetRequested = true;
}
/**
* Sets the number of DFT frames averaged into each waterfall row. Safe to call from any thread.
* @param frames from AVERAGING_MINIMUM to AVERAGING_MAXIMUM
*/
public void setAveraging(int frames)
{
mAveraging = Math.max(AVERAGING_MINIMUM, Math.min(AVERAGING_MAXIMUM, frames));
}
/**
* Current noise floor reference in dB, or NaN before the first row.
*/
public float getFloor()
{
return mFloor;
}
/**
* Adds the DFT results to the current row.
* @param bins in dB
* @return the row of level codes (unsigned bytes) when the row is complete, otherwise null
*/
public byte[] process(float[] bins)
{
if(mResetRequested)
{
mResetRequested = false;
mFloor = Float.NaN;
mFrameCount = 0;
}
int frames = mAveraging;
if(frames <= 1 && mFrameCount == 0)
{
return levels(bins);
}
if(mPowerSum.length != bins.length)
{
mPowerSum = new float[bins.length];
mAverage = new float[bins.length];
mFrameCount = 0;
}
if(mFrameCount == 0)
{
Arrays.fill(mPowerSum, 0.0f);
}
for(int x = 0; x < bins.length; x++)
{
mPowerSum[x] += (float)Math.exp(bins[x] * DB_TO_LN_POWER);
}
mFrameCount++;
//The averaging can drop below the frames already summed - complete the row with what has been summed
if(mFrameCount < frames)
{
return null;
}
float scale = 1.0f / mFrameCount;
for(int x = 0; x < bins.length; x++)
{
mAverage[x] = (float)(10.0 * Math.log10(mPowerSum[x] * scale));
}
mFrameCount = 0;
return levels(mAverage);
}
/**
* Updates the floor reference and converts the bins to level codes.
*/
private byte[] levels(float[] bins)
{
float percentile = percentile(bins);
if(Float.isNaN(mFloor) || Float.isInfinite(mFloor) || Math.abs(percentile - mFloor) > FLOOR_JUMP_DB)
{
mFloor = percentile;
}
else
{
mFloor += (percentile - mFloor) * FLOOR_SMOOTHING;
}
byte[] row = new byte[bins.length];
float floor = mFloor;
for(int x = 0; x < bins.length; x++)
{
int level = Math.round((bins[x] - floor) / LEVEL_STEP_DB) + FLOOR_LEVEL;
row[x] = (byte)Math.max(0, Math.min(255, level));
}
return row;
}
/**
* Palette index for a level code.
* @param level code (0 - 255)
* @param range in dB from the noise floor reference to the top of the palette. Smaller ranges give weak signals
* more contrast against the noise and saturate strong signals sooner.
* @return palette index (0 - 255)
*/
public static int paletteIndex(int level, double range)
{
double db = (level - FLOOR_LEVEL) * LEVEL_STEP_DB;
long index = Math.round(db * (WaterfallPalette.SIZE - 1) / range + FLOOR_INDEX);
return (int)Math.max(0, Math.min(WaterfallPalette.SIZE - 1, index));
}
/**
* Floor reference percentile of the bins, using quickselect on a scratch copy.
*/
private float percentile(float[] bins)
{
if(mScratch.length != bins.length)
{
mScratch = new float[bins.length];
}
System.arraycopy(bins, 0, mScratch, 0, bins.length);
return select(mScratch, (int)(FLOOR_PERCENTILE * (bins.length - 1)));
}
/**
* Quickselect: the k-th smallest value, partially reordering the array.
*/
static float select(float[] values, int k)
{
int left = 0;
int right = values.length - 1;
while(left < right)
{
//Median of three pivot
int middle = (left + right) >>> 1;
if(values[middle] < values[left])
{
swap(values, middle, left);
}
if(values[right] < values[left])
{
swap(values, right, left);
}
if(values[right] < values[middle])
{
swap(values, right, middle);
}
float pivot = values[middle];
int i = left;
int j = right;
while(i <= j)
{
while(values[i] < pivot)
{
i++;
}
while(values[j] > pivot)
{
j--;
}
if(i <= j)
{
swap(values, i, j);
i++;
j--;
}
}
if(k <= j)
{
right = j;
}
else if(k >= i)
{
left = i;
}
else
{
return values[k];
}
}
return values[k];
}
private static void swap(float[] values, int a, int b)
{
float temp = values[a];
values[a] = values[b];
values[b] = temp;
}
}

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 663 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

View File

@@ -255,6 +255,118 @@ public class TalkerAliasAutoAdderTest
assertNull(alias(RADIO), "local radio with the same value isn't aliased");
}
/**
* Fully qualified form of RADIO, with a local address that matches the radio ID.
*/
private static final RadioIdentifier QUALIFIED = APCO25FullyQualifiedRadioIdentifier.createFrom(1234, 0xBEE00,
0x123, 1234);
private void assertSingleAliasForBothForms(String name)
{
assertEquals(1, aliases().size(), "one alias for both radio identifier forms");
Alias alias = aliases().get(0);
assertEquals(name, alias.getName());
assertEquals(2, alias.getAliasIdentifiers().size());
AliasList aliasList = mAliasModel.getAliasList(LIST);
assertEquals(List.of(alias), aliasList.getAliases(RADIO), "alias list finds the simple radio");
assertEquals(List.of(alias), aliasList.getAliases(QUALIFIED), "alias list finds the fully qualified radio");
}
@Test
public void fullyQualifiedRadioAddedToSimpleRadioAlias()
{
decode(RADIO, "ENGINE 12");
decode(QUALIFIED, "ENGINE 12");
assertSingleAliasForBothForms("ENGINE 12");
decode(QUALIFIED, "ENGINE 12");
decode(RADIO, "ENGINE 12");
assertSingleAliasForBothForms("ENGINE 12");
}
@Test
public void simpleRadioAddedToFullyQualifiedRadioAlias()
{
decode(QUALIFIED, "ENGINE 12");
decode(RADIO, "ENGINE 12");
assertSingleAliasForBothForms("ENGINE 12");
}
@Test
public void mergedAliasIsStillRenamed()
{
decode(RADIO, "ENGINE 1");
decode(QUALIFIED, "ENGINE 12 OFFICER");
assertSingleAliasForBothForms("ENGINE 12 OFFICER");
decode(RADIO, "LADDER 3");
decode(RADIO, "LADDER 3");
assertSingleAliasForBothForms("LADDER 3");
decode(QUALIFIED, "RESCUE 5");
decode(QUALIFIED, "RESCUE 5");
assertSingleAliasForBothForms("RESCUE 5");
}
@Test
public void roamingRadioIsNotAddedToHomeRadioIdAlias()
{
RadioIdentifier home = APCO25RadioIdentifier.createFrom(777);
decode(home, "LOCAL 777");
decode(APCO25FullyQualifiedRadioIdentifier.createFrom(1234, 0xBEE00, 0x123, 777), "ROAMER");
assertEquals(2, aliases().size());
assertEquals("LOCAL 777", alias(home).getName());
assertEquals(1, alias(home).getAliasIdentifiers().size());
}
@Test
public void simpleRadioIsNotAddedToAmbiguousFullyQualifiedAliases()
{
decode(QUALIFIED, "ENGINE 12");
decode(APCO25FullyQualifiedRadioIdentifier.createFrom(1234, 0xBEE01, 0x456, 1234), "OTHER 12");
decode(RADIO, "ENGINE 12");
assertEquals(3, aliases().size());
assertEquals(1, alias(RADIO).getAliasIdentifiers().size());
}
private Alias userAlias(Radio radio)
{
Alias alias = new Alias("Custom Name");
alias.setAliasListName(LIST);
alias.setGroup("Apparatus");
alias.addAliasID(radio);
mAliasModel.addAlias(alias);
return alias;
}
@Test
public void userAliasIsGivenFullyQualifiedRadio()
{
Alias alias = userAlias(new Radio(Protocol.APCO25, 1234));
decode(QUALIFIED, "ENGINE 12");
decode(QUALIFIED, "ENGINE 12");
assertSingleAliasForBothForms("Custom Name");
assertEquals("Apparatus", alias.getGroup());
}
@Test
public void userAliasIsGivenSimpleRadio()
{
Alias alias = userAlias(new P25FullyQualifiedRadio(0xBEE00, 0x123, 1234));
decode(RADIO, "ENGINE 12");
decode(RADIO, "ENGINE 12");
assertSingleAliasForBothForms("Custom Name");
assertEquals("Apparatus", alias.getGroup());
}
@Test
public void multiIdentifierUserAliasIsNotGivenFullyQualifiedRadio()
{
Alias alias = userAlias(new Radio(Protocol.APCO25, 1234));
alias.addAliasID(new Talkgroup(Protocol.APCO25, 100));
mAliasModel.getAliasList(LIST).updateAlias(alias);
decode(QUALIFIED, "ENGINE 12");
assertEquals(2, aliases().size());
assertEquals(2, alias.getAliasIdentifiers().size());
}
@Test
public void decide()
{

View File

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

View File

@@ -39,15 +39,25 @@ public class SpectralDisplayThemeTest
}
@Test
void classicPaletteMatchesTheOriginalWaterfall()
void classicPaletteUsesTheOriginalWaterfallColors()
{
int[] palette = WaterfallPalette.classic();
assertEquals(0xFF00007F, palette[0]);
assertEquals(0xFF0000BF, palette[16]);
assertEquals(0xFFFFFF00, palette[60]);
assertEquals(0xFF0000BF, palette[63]);
assertEquals(0xFFFFFF00, palette[100]);
assertEquals(0xFFFF0000, palette[255]);
}
@Test
void classicPaletteHasDistinctColorsNearTheNoiseFloor()
{
int[] palette = WaterfallPalette.classic();
for(int index = 1; index < 64; index++)
{
assertTrue((palette[index] & 0xFF) > (palette[index - 1] & 0xFF), "index " + index);
}
}
@Test
void everyThemeHasAnOpaqueWaterfallAndALabel()
{

View File

@@ -0,0 +1,312 @@
/*
* *****************************************************************************
* 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.gui.spectrum;
import java.util.Arrays;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the waterfall noise floor tracking and dB to palette index mapping.
*/
public class WaterfallScalerTest
{
private static final int BINS = 4096;
/**
* Noise bins in dB: exponentially distributed power with the given mean power in dB.
*/
private static float[] noise(Random random, float meanDb)
{
float[] bins = new float[BINS];
for(int x = 0; x < BINS; x++)
{
double power = -Math.log(1.0 - random.nextDouble());
bins[x] = (float)(meanDb + 10.0 * Math.log10(power));
}
return bins;
}
private static int index(byte value)
{
return WaterfallScaler.paletteIndex(value & 0xFF, WaterfallScaler.RANGE_DEFAULT);
}
/**
* Scaler with one DFT frame per row.
*/
private static WaterfallScaler single()
{
WaterfallScaler scaler = new WaterfallScaler();
scaler.setAveraging(1);
return scaler;
}
private static double medianIndex(byte[] row, int from, int to)
{
int[] values = new int[to - from];
for(int x = from; x < to; x++)
{
values[x - from] = index(row[x]);
}
Arrays.sort(values);
return values[values.length / 2];
}
@Test
void selectFindsTheKthSmallestValue()
{
Random random = new Random(1);
float[] values = new float[1001];
for(int x = 0; x < values.length; x++)
{
values[x] = random.nextFloat() * 100 - 50;
}
float[] sorted = values.clone();
Arrays.sort(sorted);
for(int k: new int[]{0, 1, 250, 500, 999, 1000})
{
assertEquals(sorted[k], WaterfallScaler.select(values.clone(), k), "k " + k);
}
}
@Test
void contrastDoesNotDependOnTheAbsoluteNoiseFloorLevel()
{
for(float floor: new float[]{-60, -100, -140})
{
WaterfallScaler scaler = single();
float[] bins = noise(new Random(2), floor);
//A 6 dB signal across bins 1000 - 1199
for(int x = 1000; x < 1200; x++)
{
bins[x] = floor + 6.0f;
}
byte[] row = scaler.process(bins);
double noiseMedian = medianIndex(row, 0, 1000);
double signal = index(row[1100]);
//Noise median sits in the lower part of the palette, above the background
assertTrue(noiseMedian > 25 && noiseMedian < 50, "floor " + floor + " noise median " + noiseMedian);
//6 dB signal is 7.6 dB above the noise median (1.6 dB below mean power): about 43 palette steps
assertEquals(43.0, signal - noiseMedian, 3.0, "floor " + floor);
}
}
/**
* Strong signals in a fraction of the bins move the 25th percentile up the noise distribution: about 1.5 dB at
* 25% occupancy and 3.8 dB (the noise median) at 50% occupancy. A mean of the dB values would move 5 and 10 dB.
*/
@Test
void signalsInMuchOfTheSpanBarelyRaiseTheFloor()
{
float[] noise = noise(new Random(3), -100);
WaterfallScaler empty = single();
empty.process(noise);
assertEquals(1.5, occupiedFloor(noise, 0.25) - empty.getFloor(), 0.5);
assertEquals(3.8, occupiedFloor(noise, 0.5) - empty.getFloor(), 0.5);
}
private static float occupiedFloor(float[] noise, double occupancy)
{
float[] bins = noise.clone();
for(int x = 0; x < (int)(BINS * occupancy); x++)
{
bins[x] += 20.0f;
}
WaterfallScaler scaler = single();
scaler.process(bins);
return scaler.getFloor();
}
@Test
void floorIsSmoothedAcrossRowsJumpsLargeStepsAndResets()
{
WaterfallScaler scaler = single();
Random random = new Random(4);
scaler.process(noise(random, -100));
float initial = scaler.getFloor();
//A 5 dB step moves the floor only part way on the next row
scaler.process(noise(random, -95));
float stepped = scaler.getFloor() - initial;
assertTrue(stepped > 0.5 && stepped < 1.5, "stepped " + stepped);
//A 20 dB step jumps straight to the new level
scaler.process(noise(random, -80));
assertEquals(initial + 20.0, scaler.getFloor(), 1.0);
//Reset restarts from the next row
scaler.reset();
scaler.process(noise(random, -100));
assertEquals(initial, scaler.getFloor(), 1.0);
}
@Test
void averagingCompletesARowEveryNFramesWithTheMeanPower()
{
WaterfallScaler scaler = new WaterfallScaler();
scaler.setAveraging(2);
float[] low = new float[BINS];
float[] high = new float[BINS];
java.util.Arrays.fill(low, -100.0f);
java.util.Arrays.fill(high, -100.0f);
//One bin at -100 dB then -90 dB: mean power is 10 * log10((1 + 10) / 2) = 7.4 dB above -100 dB
low[10] = -100.0f;
high[10] = -90.0f;
assertNull(scaler.process(low));
byte[] row = scaler.process(high);
assertNotNull(row);
float level = ((row[10] & 0xFF) - WaterfallScaler.FLOOR_LEVEL) * WaterfallScaler.LEVEL_STEP_DB;
assertEquals(7.4, level, WaterfallScaler.LEVEL_STEP_DB);
assertNull(scaler.process(low));
assertNotNull(scaler.process(low));
}
/**
* Averaging two frames should cut the noise spread (about 5.6 dB for one frame) to about 3.5 dB, so a weak signal
* stands further out of the noise.
*/
@Test
void averagingSeparatesWeakSignalsFromTheNoise()
{
double single = separation(1);
double averaged = separation(2);
assertTrue(averaged > single * 1.1, "single " + single + " averaged " + averaged);
}
/**
* Mean level difference between a 3 dB signal and the noise, relative to the noise level spread, in level codes.
*/
private static double separation(int frames)
{
WaterfallScaler scaler = new WaterfallScaler();
scaler.setAveraging(frames);
Random random = new Random(6);
byte[] row = null;
while(row == null)
{
float[] bins = noise(random, -100);
for(int x = 0; x < BINS / 2; x++)
{
double power = -Math.log(1.0 - random.nextDouble()) + Math.pow(10, 0.3);
bins[x] = (float)(-100 + 10.0 * Math.log10(power));
}
row = scaler.process(bins);
}
double[] signal = stats(row, 0, BINS / 2);
double[] noise = stats(row, BINS / 2, BINS);
return (signal[0] - noise[0]) / noise[1];
}
private static double[] stats(byte[] row, int from, int to)
{
double sum = 0;
double squares = 0;
for(int x = from; x < to; x++)
{
int level = row[x] & 0xFF;
sum += level;
squares += level * level;
}
double mean = sum / (to - from);
return new double[]{mean, Math.sqrt(squares / (to - from) - mean * mean)};
}
@Test
void smallerRangesGiveMoreContrast()
{
int level6dB = WaterfallScaler.FLOOR_LEVEL + Math.round(6.0f / WaterfallScaler.LEVEL_STEP_DB);
int floor = WaterfallScaler.paletteIndex(WaterfallScaler.FLOOR_LEVEL, WaterfallScaler.RANGE_DEFAULT);
assertEquals(WaterfallScaler.FLOOR_INDEX, floor, 0.5);
int wide = WaterfallScaler.paletteIndex(level6dB, WaterfallScaler.RANGE_MAXIMUM) - floor;
int normal = WaterfallScaler.paletteIndex(level6dB, WaterfallScaler.RANGE_DEFAULT) - floor;
int narrow = WaterfallScaler.paletteIndex(level6dB, WaterfallScaler.RANGE_MINIMUM) - floor;
assertTrue(wide < normal && normal < narrow, wide + " " + normal + " " + narrow);
assertEquals(6.0 * 255 / WaterfallScaler.RANGE_DEFAULT, normal, 1.0);
//The level codes reach the top of the palette at the widest range
assertEquals(255, WaterfallScaler.paletteIndex(255, WaterfallScaler.RANGE_MAXIMUM));
}
/**
* At startup the DFT runs on an empty sample buffer, which converts to -196 dB in every bin. The first rows of
* real noise must not show as strong signals while the floor reference catches up.
*/
@Test
void silentStartupFramesDoNotFlashTheFirstNoiseRows()
{
WaterfallScaler scaler = single();
float[] silence = new float[BINS];
Arrays.fill(silence, -196.0f);
for(int x = 0; x < 3; x++)
{
scaler.process(silence);
}
Random random = new Random(7);
for(int x = 0; x < 3; x++)
{
double median = medianIndex(scaler.process(noise(random, -100)), 0, BINS);
assertTrue(median > 25 && median < 50, "row " + x + " noise median index " + median);
}
}
@Test
void indexesClampToThePalette()
{
WaterfallScaler scaler = single();
float[] bins = noise(new Random(5), -100);
bins[0] = 0.0f;
bins[1] = -300.0f;
byte[] row = scaler.process(bins);
assertEquals(255, index(row[0]));
assertEquals(0, index(row[1]));
}
}