Compare commits
1 Commits
2721-fix-r
...
2646-chann
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2950f30fa |
18
README.md
@@ -25,6 +25,24 @@ A cross-platform java application for decoding, monitoring, recording and stream
|
|||||||

|

|
||||||
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
|
**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
|
## Download the Latest Release
|
||||||
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.
|
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.
|
||||||
|
|
||||||
|
|||||||
38
build.gradle
@@ -213,14 +213,6 @@ def jvmArgsLinux =
|
|||||||
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
|
'--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)
|
'--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 {
|
application {
|
||||||
mainClass = "io.github.dsheirer.gui.SDRTrunk"
|
mainClass = "io.github.dsheirer.gui.SDRTrunk"
|
||||||
|
|
||||||
@@ -232,16 +224,6 @@ 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 {
|
test {
|
||||||
if(os.isWindows()) {
|
if(os.isWindows()) {
|
||||||
jvmArgs = jvmArgsWindows
|
jvmArgs = jvmArgsWindows
|
||||||
@@ -306,8 +288,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
|
|||||||
* @return configured task.
|
* @return configured task.
|
||||||
*/
|
*/
|
||||||
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
|
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
|
||||||
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
|
//Use the correct set of JVM arguments
|
||||||
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
|
rt.extension.launcherData.get().jvmArgs = jvmArgs
|
||||||
|
|
||||||
//Additional modules to include with auto-detected modules.
|
//Additional modules to include with auto-detected modules.
|
||||||
//jdk.charsets - NXDN BIG5 encoding support
|
//jdk.charsets - NXDN BIG5 encoding support
|
||||||
@@ -406,22 +388,6 @@ 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.
|
* 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
|
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse
|
||||||
|
|||||||
@@ -52,9 +52,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* Only aliases whose only identifier is the radio are created or renamed. An alias that combines the radio with other
|
* 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. The exception is a P25 radio's simple and fully
|
* identifiers (e.g. several radios or talkgroups) is left alone.
|
||||||
* 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
|
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
|
||||||
* JavaFX application thread.
|
* JavaFX application thread.
|
||||||
@@ -202,21 +200,6 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
|
|||||||
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
|
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
|
||||||
Alias existing = findExactMatch(aliasList.getAliases(radio), aliasId);
|
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)
|
if(existing == null)
|
||||||
{
|
{
|
||||||
Alias alias = new Alias(value);
|
Alias alias = new Alias(value);
|
||||||
@@ -425,114 +408,22 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finds the alias for the other identifier form of a P25 radio, so that a radio's simple and fully qualified
|
* Number of identifiers (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
|
||||||
* identifiers share one alias instead of creating an alias for each. This includes user aliases outside the
|
* streaming.
|
||||||
* 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.
|
|
||||||
*/
|
*/
|
||||||
@VisibleForTesting
|
private static int getIdentityCount(Alias alias)
|
||||||
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
|
|
||||||
{
|
{
|
||||||
if(aliases == null || aliasId.getProtocol() != Protocol.APCO25)
|
int count = 0;
|
||||||
{
|
|
||||||
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())
|
for(AliasID id: alias.getAliasIdentifiers())
|
||||||
{
|
{
|
||||||
if(!id.isAudioIdentifier())
|
if(!id.isAudioIdentifier())
|
||||||
{
|
{
|
||||||
if(sole != null)
|
count++;
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
sole = id;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return sole;
|
return count;
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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)
|
private static String getKey(Radio aliasId)
|
||||||
|
|||||||
@@ -1,255 +0,0 @@
|
|||||||
/*
|
|
||||||
* *****************************************************************************
|
|
||||||
* 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -181,7 +181,6 @@ public class JavaFxWindowManager extends Application
|
|||||||
{
|
{
|
||||||
mJFXPanel = new JFXPanel();
|
mJFXPanel = new JFXPanel();
|
||||||
Platform.setImplicitExit(false);
|
Platform.setImplicitExit(false);
|
||||||
ApplicationIcons.installJavaFx();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -144,28 +144,12 @@ public class SDRTrunk implements Listener<TunerEvent>
|
|||||||
private String mTitle;
|
private String mTitle;
|
||||||
|
|
||||||
public SDRTrunk()
|
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())
|
if(!GraphicsEnvironment.isHeadless())
|
||||||
{
|
{
|
||||||
//Initialize the theme manager before any Swing components are realized so the chosen
|
//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.
|
//look-and-feel applies to the very first window that is created.
|
||||||
ThemeManager.getInstance().initialize(mUserPreferences);
|
ThemeManager.getInstance().initialize(mUserPreferences);
|
||||||
ApplicationIcons.installSwing();
|
|
||||||
mMainGui = new JFrame();
|
mMainGui = new JFrame();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,9 +273,6 @@ public class SDRTrunk implements Listener<TunerEvent>
|
|||||||
if(!GraphicsEnvironment.isHeadless())
|
if(!GraphicsEnvironment.isHeadless())
|
||||||
{
|
{
|
||||||
mMainGui.setVisible(true);
|
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();
|
Tuner tuner = tunerSpectralDisplayManager.showFirstTuner();
|
||||||
|
|
||||||
if(tuner != null)
|
if(tuner != null)
|
||||||
@@ -330,15 +311,7 @@ public class SDRTrunk implements Listener<TunerEvent>
|
|||||||
}
|
}
|
||||||
catch(Exception e)
|
catch(Exception e)
|
||||||
{
|
{
|
||||||
if(mMainGui != null && !mMainGui.isVisible())
|
e.printStackTrace();
|
||||||
{
|
|
||||||
//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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -388,7 +361,6 @@ public class SDRTrunk implements Listener<TunerEvent>
|
|||||||
*/
|
*/
|
||||||
mTitle = SystemProperties.getInstance().getApplicationName();
|
mTitle = SystemProperties.getInstance().getApplicationName();
|
||||||
mMainGui.setTitle(mTitle);
|
mMainGui.setTitle(mTitle);
|
||||||
ApplicationIcons.apply(mMainGui);
|
|
||||||
|
|
||||||
Point location = mUserPreferences.getSwingPreference().getLocation(WINDOW_FRAME_IDENTIFIER);
|
Point location = mUserPreferences.getSwingPreference().getLocation(WINDOW_FRAME_IDENTIFIER);
|
||||||
if(location != null)
|
if(location != null)
|
||||||
@@ -995,117 +967,11 @@ public class SDRTrunk implements Listener<TunerEvent>
|
|||||||
JOptionPane.showMessageDialog(mMainGui, message, "Duplicate Library Versions", JOptionPane.WARNING_MESSAGE);
|
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("&", "&").replace("<", "<").replace(">", ">");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Launch the application.
|
* Launch the application.
|
||||||
*/
|
*/
|
||||||
public static void main(String[] args)
|
public static void main(String[] args)
|
||||||
{
|
{
|
||||||
String version = SDRTrunk.class.getPackage().getImplementationVersion();
|
new SDRTrunk();
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
/*
|
|
||||||
* *****************************************************************************
|
|
||||||
* 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.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -243,7 +243,8 @@ public class ChannelSpectrumView extends SplitPane implements Listener<Processin
|
|||||||
|
|
||||||
if(source instanceof TunerChannelSource tcs)
|
if(source instanceof TunerChannelSource tcs)
|
||||||
{
|
{
|
||||||
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth);
|
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth,
|
||||||
|
tcs::getNoiseDensity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -660,7 +660,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
|
|||||||
nameColumn.setPrefWidth(140);
|
nameColumn.setPrefWidth(140);
|
||||||
|
|
||||||
TableColumn groupColumn = new TableColumn();
|
TableColumn groupColumn = new TableColumn();
|
||||||
groupColumn.setText("Category");
|
groupColumn.setText("Group");
|
||||||
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
||||||
groupColumn.setPrefWidth(140);
|
groupColumn.setPrefWidth(140);
|
||||||
|
|
||||||
|
|||||||
@@ -1094,7 +1094,7 @@ public class AliasItemEditor extends Editor<Alias>
|
|||||||
GridPane.setConstraints(getColorPicker(), 7, row);
|
GridPane.setConstraints(getColorPicker(), 7, row);
|
||||||
mTextFieldPane.getChildren().add(getColorPicker());
|
mTextFieldPane.getChildren().add(getColorPicker());
|
||||||
|
|
||||||
Label groupLabel = new Label("Category");
|
Label groupLabel = new Label("Group");
|
||||||
groupLabel.setLabelFor(getGroupField());
|
groupLabel.setLabelFor(getGroupField());
|
||||||
GridPane.setHalignment(groupLabel, HPos.RIGHT);
|
GridPane.setHalignment(groupLabel, HPos.RIGHT);
|
||||||
GridPane.setConstraints(groupLabel, 0, ++row);
|
GridPane.setConstraints(groupLabel, 0, ++row);
|
||||||
|
|||||||
@@ -243,7 +243,7 @@ public class AliasViewByIdentifierEditor extends VBox
|
|||||||
aliasColumn.setPrefWidth(200);
|
aliasColumn.setPrefWidth(200);
|
||||||
|
|
||||||
TableColumn<AliasAndIdentifier, String> groupColumn = new TableColumn<>();
|
TableColumn<AliasAndIdentifier, String> groupColumn = new TableColumn<>();
|
||||||
groupColumn.setText("Category");
|
groupColumn.setText("Group");
|
||||||
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
||||||
groupColumn.setPrefWidth(200);
|
groupColumn.setPrefWidth(200);
|
||||||
|
|
||||||
|
|||||||
@@ -241,7 +241,7 @@ public class AliasViewByRecordingEditor extends VBox
|
|||||||
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
|
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
|
||||||
|
|
||||||
TableColumn groupColumn = new TableColumn();
|
TableColumn groupColumn = new TableColumn();
|
||||||
groupColumn.setText("Category");
|
groupColumn.setText("Group");
|
||||||
groupColumn.setPrefWidth(200);
|
groupColumn.setPrefWidth(200);
|
||||||
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
||||||
|
|
||||||
@@ -280,7 +280,7 @@ public class AliasViewByRecordingEditor extends VBox
|
|||||||
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
|
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
|
||||||
|
|
||||||
TableColumn groupColumn = new TableColumn();
|
TableColumn groupColumn = new TableColumn();
|
||||||
groupColumn.setText("Category");
|
groupColumn.setText("Group");
|
||||||
groupColumn.setPrefWidth(200);
|
groupColumn.setPrefWidth(200);
|
||||||
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
||||||
|
|
||||||
|
|||||||
@@ -694,8 +694,8 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
|
|||||||
mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases");
|
mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases");
|
||||||
mAutoAddTalkerAliasesCheckBox.setDisable(true);
|
mAutoAddTalkerAliasesCheckBox.setDisable(true);
|
||||||
mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds decoded talker aliases as radio aliases in " +
|
mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds decoded talker aliases as radio aliases in " +
|
||||||
"the Talker Alias category. Only radio aliases in that category are automatically renamed; existing " +
|
"the Talker Alias group. Only radio aliases in that group are automatically renamed; existing " +
|
||||||
"radio aliases outside the category are left unchanged. Move an alias out of the Talker Alias category " +
|
"radio aliases outside the group are left unchanged. Move an alias out of the Talker Alias group " +
|
||||||
"to preserve a custom name. Applies when the channel is (re)started."));
|
"to preserve a custom name. Applies when the channel is (re)started."));
|
||||||
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
|
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -225,7 +225,7 @@ public class StreamAliasSelectionEditor extends VBox
|
|||||||
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
|
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
|
||||||
|
|
||||||
TableColumn groupColumn = new TableColumn();
|
TableColumn groupColumn = new TableColumn();
|
||||||
groupColumn.setText("Category");
|
groupColumn.setText("Group");
|
||||||
groupColumn.setPrefWidth(150);
|
groupColumn.setPrefWidth(150);
|
||||||
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
||||||
|
|
||||||
@@ -270,7 +270,7 @@ public class StreamAliasSelectionEditor extends VBox
|
|||||||
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
|
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
|
||||||
|
|
||||||
TableColumn groupColumn = new TableColumn();
|
TableColumn groupColumn = new TableColumn();
|
||||||
groupColumn.setText("Category");
|
groupColumn.setText("Group");
|
||||||
groupColumn.setPrefWidth(150);
|
groupColumn.setPrefWidth(150);
|
||||||
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import io.github.dsheirer.buffer.INativeBuffer;
|
|||||||
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
|
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
|
||||||
import io.github.dsheirer.properties.SystemProperties;
|
import io.github.dsheirer.properties.SystemProperties;
|
||||||
import io.github.dsheirer.sample.Listener;
|
import io.github.dsheirer.sample.Listener;
|
||||||
|
import io.github.dsheirer.spectrum.ChannelSignalMeter;
|
||||||
|
import java.util.function.DoubleSupplier;
|
||||||
import javafx.geometry.Insets;
|
import javafx.geometry.Insets;
|
||||||
import javafx.geometry.Pos;
|
import javafx.geometry.Pos;
|
||||||
import javafx.scene.layout.StackPane;
|
import javafx.scene.layout.StackPane;
|
||||||
@@ -46,9 +48,11 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
|
|
||||||
private final ChannelTuningLayer mTuningLayer;
|
private final ChannelTuningLayer mTuningLayer;
|
||||||
private final EdgeSlider mNoiseFloorSlider;
|
private final EdgeSlider mNoiseFloorSlider;
|
||||||
|
private final ChannelSignalMeter mSignalMeter = new ChannelSignalMeter(this::showReading);
|
||||||
private final Object mLock = new Object();
|
private final Object mLock = new Object();
|
||||||
private boolean mActive;
|
private boolean mActive;
|
||||||
private boolean mHasChannel;
|
private volatile boolean mHasChannel;
|
||||||
|
private volatile boolean mHasNoiseDensity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an instance.
|
* Constructs an instance.
|
||||||
@@ -65,7 +69,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
SpectralDisplayModel model = getSpectralDisplay().getModel();
|
SpectralDisplayModel model = getSpectralDisplay().getModel();
|
||||||
getSpectralDisplay().messageProperty().set(MESSAGE_NO_CHANNEL);
|
getSpectralDisplay().messageProperty().set(MESSAGE_NO_CHANNEL);
|
||||||
|
|
||||||
//Noise floor slider for the spectrum
|
//Noise floor slider along the right edge, below the configuration panel tab
|
||||||
mNoiseFloorSlider = new EdgeSlider("Floor", "Noise floor: moves the bottom of the spectrum's dB range. " +
|
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.",
|
"Higher settings show a deeper range and move the noise floor up the display.",
|
||||||
MINIMUM_SAMPLE_SIZE, MAXIMUM_SAMPLE_SIZE, 1, this::formatPlotBottom);
|
MINIMUM_SAMPLE_SIZE, MAXIMUM_SAMPLE_SIZE, 1, this::formatPlotBottom);
|
||||||
@@ -82,14 +86,50 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
model.binCountProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
|
model.binCountProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
|
||||||
model.noiseBandwidthProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
|
model.noiseBandwidthProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
|
||||||
mNoiseFloorSlider.refreshLabel();
|
mNoiseFloorSlider.refreshLabel();
|
||||||
//Along the right edge of the spectrum section, below the configuration panel tab
|
|
||||||
StackPane.setAlignment(mNoiseFloorSlider, Pos.CENTER_RIGHT);
|
StackPane.setAlignment(mNoiseFloorSlider, Pos.CENTER_RIGHT);
|
||||||
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
|
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
|
||||||
getSpectralDisplay().addSectionOverlay(DisplaySection.SPECTRUM, mNoiseFloorSlider);
|
getChildren().add(mNoiseFloorSlider);
|
||||||
|
|
||||||
|
//Channel power and SNR, measured from the spectrum frames
|
||||||
|
mSignalMeter.setWindowNoiseBandwidth(model.noiseBandwidthProperty().get());
|
||||||
|
model.noiseBandwidthProperty().addListener((ob, ov, nv) ->
|
||||||
|
mSignalMeter.setWindowNoiseBandwidth(nv.doubleValue()));
|
||||||
|
addDecibelListener(mSignalMeter);
|
||||||
|
|
||||||
installConfigPanel();
|
installConfigPanel();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows the channel signal reading in the tuning layer. Called on the DFT processor thread.
|
||||||
|
*/
|
||||||
|
private void showReading(ChannelSignalMeter.Reading reading)
|
||||||
|
{
|
||||||
|
String text = String.format("%.1f dBFS", reading.dbfs());
|
||||||
|
|
||||||
|
//Channels that aren't sourced by a tuner show the channel power without the SNR
|
||||||
|
if(mHasNoiseDensity)
|
||||||
|
{
|
||||||
|
if(!reading.hasSnr())
|
||||||
|
{
|
||||||
|
//Waiting for the tuner noise floor estimate, which restarts after a tuner frequency change
|
||||||
|
text += " SNR --";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
text += Double.isFinite(reading.snr()) && reading.snr() >= 0.0 ?
|
||||||
|
String.format(" SNR %.1f dB", reading.snr()) : " SNR < 0 dB";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String readout = text;
|
||||||
|
runOnFxThread(() -> {
|
||||||
|
if(mHasChannel && isDftRunning())
|
||||||
|
{
|
||||||
|
mTuningLayer.signalReadoutProperty().set(readout);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Listener for the channel's complex sample buffers.
|
* Listener for the channel's complex sample buffers.
|
||||||
*/
|
*/
|
||||||
@@ -105,10 +145,25 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
* @param bandwidth of the channel in Hertz, or zero to hide the passband markers
|
* @param bandwidth of the channel in Hertz, or zero to hide the passband markers
|
||||||
*/
|
*/
|
||||||
public void setChannel(long frequency, int sampleRate, int bandwidth)
|
public void setChannel(long frequency, int sampleRate, int bandwidth)
|
||||||
|
{
|
||||||
|
setChannel(frequency, sampleRate, bandwidth, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the channel to display.
|
||||||
|
* @param frequency of the channel
|
||||||
|
* @param sampleRate of the channel samples, or 0 for no channel
|
||||||
|
* @param bandwidth of the channel in Hertz
|
||||||
|
* @param noiseDensity supplier of the tuner noise density near the channel, in full-scale units per Hertz, for the
|
||||||
|
* signal-to-noise ratio. Null, or a supplier that returns NaN, shows the channel power without the SNR.
|
||||||
|
*/
|
||||||
|
public void setChannel(long frequency, int sampleRate, int bandwidth, DoubleSupplier noiseDensity)
|
||||||
{
|
{
|
||||||
synchronized(mLock)
|
synchronized(mLock)
|
||||||
{
|
{
|
||||||
mHasChannel = sampleRate > 0;
|
mHasChannel = sampleRate > 0;
|
||||||
|
mSignalMeter.setChannel(sampleRate, bandwidth, noiseDensity);
|
||||||
|
mHasNoiseDensity = noiseDensity != null;
|
||||||
updateProcessing();
|
updateProcessing();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,6 +174,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
model.centerFrequencyProperty().set(frequency);
|
model.centerFrequencyProperty().set(frequency);
|
||||||
model.sampleRateProperty().set(sampleRate);
|
model.sampleRateProperty().set(sampleRate);
|
||||||
mTuningLayer.channelBandwidthProperty().set(bandwidth);
|
mTuningLayer.channelBandwidthProperty().set(bandwidth);
|
||||||
|
mTuningLayer.signalReadoutProperty().set(null);
|
||||||
mTuningLayer.carrierOffsetValidProperty().set(false);
|
mTuningLayer.carrierOffsetValidProperty().set(false);
|
||||||
mTuningLayer.carrierOffsetProperty().set(0);
|
mTuningLayer.carrierOffsetProperty().set(0);
|
||||||
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
|
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
|
||||||
@@ -196,6 +252,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
stopDft();
|
stopDft();
|
||||||
|
runOnFxThread(() -> mTuningLayer.signalReadoutProperty().set(null));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import io.github.dsheirer.gui.spectrum.layer.DecibelLayer;
|
|||||||
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
|
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
|
||||||
import io.github.dsheirer.properties.SystemProperties;
|
import io.github.dsheirer.properties.SystemProperties;
|
||||||
import io.github.dsheirer.spectrum.ComplexDftProcessor;
|
import io.github.dsheirer.spectrum.ComplexDftProcessor;
|
||||||
|
import io.github.dsheirer.spectrum.DFTResultsListener;
|
||||||
import io.github.dsheirer.spectrum.DFTSize;
|
import io.github.dsheirer.spectrum.DFTSize;
|
||||||
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
|
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
@@ -55,8 +56,6 @@ public abstract class DftSpectralDisplay extends StackPane
|
|||||||
private static final String PEAK_HOLD = "peak.hold";
|
private static final String PEAK_HOLD = "peak.hold";
|
||||||
private static final String SPECTRUM_ENABLED = "spectrum.enabled";
|
private static final String SPECTRUM_ENABLED = "spectrum.enabled";
|
||||||
private static final String WATERFALL_ENABLED = "waterfall.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 DIVIDER_POSITION = "divider.position";
|
||||||
private static final String DECIBEL_SCALE = "decibel.scale";
|
private static final String DECIBEL_SCALE = "decibel.scale";
|
||||||
private static final String CONFIG_PINNED = "config.pinned";
|
private static final String CONFIG_PINNED = "config.pinned";
|
||||||
@@ -123,9 +122,6 @@ public abstract class DftSpectralDisplay extends StackPane
|
|||||||
});
|
});
|
||||||
mSpectralDisplay.averagingProperty().addListener((ob, ov, nv) -> save(AVERAGING, nv.intValue()));
|
mSpectralDisplay.averagingProperty().addListener((ob, ov, nv) -> save(AVERAGING, nv.intValue()));
|
||||||
mSpectralDisplay.peakHoldProperty().addListener((ob, ov, nv) -> save(PEAK_HOLD, nv));
|
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) ->
|
mSpectralDisplay.dividerPositionProperty().addListener((ob, ov, nv) ->
|
||||||
save(DIVIDER_POSITION, String.valueOf(nv.doubleValue())));
|
save(DIVIDER_POSITION, String.valueOf(nv.doubleValue())));
|
||||||
mDecibelLayer.visibleProperty().addListener((ob, ov, nv) -> save(DECIBEL_SCALE, nv));
|
mDecibelLayer.visibleProperty().addListener((ob, ov, nv) -> save(DECIBEL_SCALE, nv));
|
||||||
@@ -210,12 +206,6 @@ public abstract class DftSpectralDisplay extends StackPane
|
|||||||
mSpectralDisplay.averagingProperty().set(Math.max(SpectralDisplay.AVERAGING_MINIMUM,
|
mSpectralDisplay.averagingProperty().set(Math.max(SpectralDisplay.AVERAGING_MINIMUM,
|
||||||
Math.min(SpectralDisplay.AVERAGING_MAXIMUM, averaging)));
|
Math.min(SpectralDisplay.AVERAGING_MAXIMUM, averaging)));
|
||||||
mSpectralDisplay.peakHoldProperty().set(properties.get(key(PEAK_HOLD), false));
|
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));
|
mDecibelLayer.visibleProperty().set(properties.get(key(DECIBEL_SCALE), true));
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -311,6 +301,14 @@ public abstract class DftSpectralDisplay extends StackPane
|
|||||||
/**
|
/**
|
||||||
* DFT processor. Register it with the sample source to feed the display.
|
* DFT processor. Register it with the sample source to feed the display.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Adds a listener for the dBFS spectrum frames, lowest frequency first. Frames arrive on the DFT processor thread.
|
||||||
|
*/
|
||||||
|
protected void addDecibelListener(DFTResultsListener listener)
|
||||||
|
{
|
||||||
|
mDecibelConverter.addListener(listener);
|
||||||
|
}
|
||||||
|
|
||||||
protected ComplexDftProcessor getDftProcessor()
|
protected ComplexDftProcessor getDftProcessor()
|
||||||
{
|
{
|
||||||
return mDftProcessor;
|
return mDftProcessor;
|
||||||
|
|||||||
@@ -42,8 +42,6 @@ import javafx.beans.property.SimpleIntegerProperty;
|
|||||||
import javafx.beans.property.SimpleObjectProperty;
|
import javafx.beans.property.SimpleObjectProperty;
|
||||||
import javafx.beans.property.SimpleStringProperty;
|
import javafx.beans.property.SimpleStringProperty;
|
||||||
import javafx.beans.property.StringProperty;
|
import javafx.beans.property.StringProperty;
|
||||||
import javafx.geometry.Insets;
|
|
||||||
import javafx.geometry.Pos;
|
|
||||||
import javafx.geometry.Orientation;
|
import javafx.geometry.Orientation;
|
||||||
import javafx.geometry.VPos;
|
import javafx.geometry.VPos;
|
||||||
import javafx.scene.Cursor;
|
import javafx.scene.Cursor;
|
||||||
@@ -106,10 +104,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
private final SplitPane mSplitPane = new SplitPane();
|
private final SplitPane mSplitPane = new SplitPane();
|
||||||
private final CanvasPane mSpectrumPane = new CanvasPane(DisplaySection.SPECTRUM);
|
private final CanvasPane mSpectrumPane = new CanvasPane(DisplaySection.SPECTRUM);
|
||||||
private final CanvasPane mWaterfallPane = new CanvasPane(DisplaySection.WATERFALL);
|
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 StackPane mDisabledPane = new StackPane();
|
||||||
|
|
||||||
private final BooleanProperty mSpectrumEnabled = new SimpleBooleanProperty(true);
|
private final BooleanProperty mSpectrumEnabled = new SimpleBooleanProperty(true);
|
||||||
@@ -118,8 +112,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
private final IntegerProperty mAveraging = new SimpleIntegerProperty(AVERAGING_DEFAULT);
|
private final IntegerProperty mAveraging = new SimpleIntegerProperty(AVERAGING_DEFAULT);
|
||||||
private final BooleanProperty mPeakHold = new SimpleBooleanProperty(false);
|
private final BooleanProperty mPeakHold = new SimpleBooleanProperty(false);
|
||||||
private final DoubleProperty mDividerPosition = new SimpleDoubleProperty(0.5);
|
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();
|
private final StringProperty mMessage = new SimpleStringProperty();
|
||||||
|
|
||||||
//Values read on the DFT results thread
|
//Values read on the DFT results thread
|
||||||
@@ -127,7 +119,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
private volatile boolean mWaterfallActive = true;
|
private volatile boolean mWaterfallActive = true;
|
||||||
private volatile boolean mWaterfallPausedFlag = false;
|
private volatile boolean mWaterfallPausedFlag = false;
|
||||||
private final SpectrumAverager mAverager = new SpectrumAverager();
|
private final SpectrumAverager mAverager = new SpectrumAverager();
|
||||||
private final WaterfallScaler mWaterfallScaler = new WaterfallScaler();
|
|
||||||
|
|
||||||
//Hand off from the DFT results thread to the JavaFX thread
|
//Hand off from the DFT results thread to the JavaFX thread
|
||||||
private final AtomicReference<SpectrumAverager.Frame> mLatestSpectrum = new AtomicReference<>();
|
private final AtomicReference<SpectrumAverager.Frame> mLatestSpectrum = new AtomicReference<>();
|
||||||
@@ -142,10 +133,8 @@ public class SpectralDisplay extends StackPane
|
|||||||
private WritableImage[] mWaterfallTiles;
|
private WritableImage[] mWaterfallTiles;
|
||||||
private int mWaterfallWidth;
|
private int mWaterfallWidth;
|
||||||
private int mWaterfallHeight;
|
private int mWaterfallHeight;
|
||||||
private byte[] mWaterfallLevels;
|
private byte[] mWaterfallIndexes;
|
||||||
private int[] mWaterfallPixels;
|
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 int mWaterfallWriteRow = 0;
|
||||||
private double[] mPolygonX = new double[0];
|
private double[] mPolygonX = new double[0];
|
||||||
private double[] mPolygonY = new double[0];
|
private double[] mPolygonY = new double[0];
|
||||||
@@ -178,37 +167,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
themeChanged(disabledLabel);
|
themeChanged(disabledLabel);
|
||||||
getChildren().addAll(mDisabledPane, mSplitPane);
|
getChildren().addAll(mDisabledPane, mSplitPane);
|
||||||
setMinSize(0, 0);
|
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());
|
mSpectrumEnabled.addListener((ob, ov, nv) -> updateSections());
|
||||||
mWaterfallEnabled.addListener((ob, ov, nv) -> updateSections());
|
mWaterfallEnabled.addListener((ob, ov, nv) -> updateSections());
|
||||||
@@ -303,7 +261,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
SpectralDisplayTheme theme = getTheme();
|
SpectralDisplayTheme theme = getTheme();
|
||||||
mDisabledPane.setBackground(new Background(new BackgroundFill(theme.getBackground(), null, null)));
|
mDisabledPane.setBackground(new Background(new BackgroundFill(theme.getBackground(), null, null)));
|
||||||
disabledLabel.setTextFill(theme.getLine());
|
disabledLabel.setTextFill(theme.getLine());
|
||||||
mWaterfallColors = null;
|
|
||||||
repaintWaterfallImage();
|
repaintWaterfallImage();
|
||||||
requestRender();
|
requestRender();
|
||||||
}
|
}
|
||||||
@@ -400,42 +357,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
return mPeakHold;
|
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.
|
* Divider position (0 - 1.0) between the spectrum and the waterfall when both are showing.
|
||||||
*/
|
*/
|
||||||
@@ -474,7 +395,6 @@ public class SpectralDisplay extends StackPane
|
|||||||
public void clear()
|
public void clear()
|
||||||
{
|
{
|
||||||
mAverager.reset();
|
mAverager.reset();
|
||||||
mWaterfallScaler.reset();
|
|
||||||
|
|
||||||
mLatestSpectrum.set(null);
|
mLatestSpectrum.set(null);
|
||||||
mWaterfallRows.clear();
|
mWaterfallRows.clear();
|
||||||
@@ -492,11 +412,10 @@ public class SpectralDisplay extends StackPane
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
//The first DFT results on startup can be NaN or infinite - drop them. Replacing them with zeros would add
|
//The first DFT results on startup can be NaN or infinite
|
||||||
//full scale (0 dBFS) values to the spectrum averaging and the waterfall floor tracking.
|
|
||||||
if(Float.isNaN(bins[0]) || Float.isInfinite(bins[0]))
|
if(Float.isNaN(bins[0]) || Float.isInfinite(bins[0]))
|
||||||
{
|
{
|
||||||
return;
|
bins = new float[bins.length];
|
||||||
}
|
}
|
||||||
|
|
||||||
if(mSpectrumActive)
|
if(mSpectrumActive)
|
||||||
@@ -506,16 +425,11 @@ public class SpectralDisplay extends StackPane
|
|||||||
|
|
||||||
if(mWaterfallActive && !mWaterfallPausedFlag)
|
if(mWaterfallActive && !mWaterfallPausedFlag)
|
||||||
{
|
{
|
||||||
byte[] row = mWaterfallScaler.process(bins);
|
mWaterfallRows.offer(toWaterfallRow(bins));
|
||||||
|
|
||||||
if(row != null)
|
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
|
||||||
{
|
{
|
||||||
mWaterfallRows.offer(row);
|
mWaterfallRows.poll();
|
||||||
|
|
||||||
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
|
|
||||||
{
|
|
||||||
mWaterfallRows.poll();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -538,7 +452,33 @@ public class SpectralDisplay extends StackPane
|
|||||||
mLatestSpectrum.set(null);
|
mLatestSpectrum.set(null);
|
||||||
mWaterfallRows.clear();
|
mWaterfallRows.clear();
|
||||||
mWaterfallTiles = null;
|
mWaterfallTiles = null;
|
||||||
mWaterfallLevels = 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -551,11 +491,11 @@ public class SpectralDisplay extends StackPane
|
|||||||
mSpectrumActive = spectrum;
|
mSpectrumActive = spectrum;
|
||||||
mWaterfallActive = waterfall;
|
mWaterfallActive = waterfall;
|
||||||
|
|
||||||
List<StackPane> items = new ArrayList<>();
|
List<Pane> items = new ArrayList<>();
|
||||||
|
|
||||||
if(spectrum)
|
if(spectrum)
|
||||||
{
|
{
|
||||||
items.add(mSpectrumSection);
|
items.add(mSpectrumPane);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -565,16 +505,13 @@ public class SpectralDisplay extends StackPane
|
|||||||
|
|
||||||
if(waterfall)
|
if(waterfall)
|
||||||
{
|
{
|
||||||
items.add(mWaterfallSection);
|
items.add(mWaterfallPane);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
mWaterfallRows.clear();
|
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.getItems().setAll(items);
|
||||||
mSplitPane.setVisible(!items.isEmpty());
|
mSplitPane.setVisible(!items.isEmpty());
|
||||||
|
|
||||||
@@ -606,7 +543,7 @@ public class SpectralDisplay extends StackPane
|
|||||||
if(mWaterfallTiles != null)
|
if(mWaterfallTiles != null)
|
||||||
{
|
{
|
||||||
mWaterfallTiles = null;
|
mWaterfallTiles = null;
|
||||||
mWaterfallLevels = null;
|
mWaterfallIndexes = null;
|
||||||
mWaterfallWriteRow = 0;
|
mWaterfallWriteRow = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -644,8 +581,8 @@ public class SpectralDisplay extends StackPane
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Writes the row into the waterfall ring buffer. The newest row is at mWaterfallWriteRow and older rows follow
|
* 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 level codes are kept alongside the image so the history
|
* 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 or the waterfall range changes.
|
* can be recolored when the theme changes.
|
||||||
*/
|
*/
|
||||||
private void writeWaterfallRow(byte[] row)
|
private void writeWaterfallRow(byte[] row)
|
||||||
{
|
{
|
||||||
@@ -653,7 +590,7 @@ public class SpectralDisplay extends StackPane
|
|||||||
|
|
||||||
if(mWaterfallTiles == null || mWaterfallWidth != row.length)
|
if(mWaterfallTiles == null || mWaterfallWidth != row.length)
|
||||||
{
|
{
|
||||||
mWaterfallLevels = new byte[row.length * rows];
|
mWaterfallIndexes = new byte[row.length * rows];
|
||||||
createWaterfallTiles(row.length, rows);
|
createWaterfallTiles(row.length, rows);
|
||||||
mWaterfallWriteRow = 0;
|
mWaterfallWriteRow = 0;
|
||||||
repaintWaterfallImage();
|
repaintWaterfallImage();
|
||||||
@@ -665,7 +602,7 @@ public class SpectralDisplay extends StackPane
|
|||||||
|
|
||||||
int width = row.length;
|
int width = row.length;
|
||||||
mWaterfallWriteRow = (mWaterfallWriteRow - 1 + mWaterfallHeight) % mWaterfallHeight;
|
mWaterfallWriteRow = (mWaterfallWriteRow - 1 + mWaterfallHeight) % mWaterfallHeight;
|
||||||
System.arraycopy(row, 0, mWaterfallLevels, mWaterfallWriteRow * width, width);
|
System.arraycopy(row, 0, mWaterfallIndexes, mWaterfallWriteRow * width, width);
|
||||||
writeWaterfallPixels(mWaterfallWriteRow);
|
writeWaterfallPixels(mWaterfallWriteRow);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -688,7 +625,7 @@ public class SpectralDisplay extends StackPane
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Colors one row of the waterfall image tiles from the stored level codes.
|
* Colors one row of the waterfall image tiles from the stored intensity indexes.
|
||||||
*/
|
*/
|
||||||
private void writeWaterfallPixels(int imageRow)
|
private void writeWaterfallPixels(int imageRow)
|
||||||
{
|
{
|
||||||
@@ -699,12 +636,12 @@ public class SpectralDisplay extends StackPane
|
|||||||
mWaterfallPixels = new int[width];
|
mWaterfallPixels = new int[width];
|
||||||
}
|
}
|
||||||
|
|
||||||
int[] colors = getWaterfallColors();
|
SpectralDisplayTheme theme = getTheme();
|
||||||
int offset = imageRow * width;
|
int offset = imageRow * width;
|
||||||
|
|
||||||
for(int x = 0; x < width; x++)
|
for(int x = 0; x < width; x++)
|
||||||
{
|
{
|
||||||
mWaterfallPixels[x] = colors[mWaterfallLevels[offset + x] & 0xFF];
|
mWaterfallPixels[x] = theme.getWaterfallColor(mWaterfallIndexes[offset + x]);
|
||||||
}
|
}
|
||||||
|
|
||||||
for(int tile = 0; tile < mWaterfallTiles.length; tile++)
|
for(int tile = 0; tile < mWaterfallTiles.length; tile++)
|
||||||
@@ -716,33 +653,11 @@ public class SpectralDisplay extends StackPane
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ARGB color for each waterfall level code, for the current theme and range.
|
* Recolors the whole waterfall image from the stored intensity indexes using the current theme.
|
||||||
*/
|
|
||||||
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()
|
private void repaintWaterfallImage()
|
||||||
{
|
{
|
||||||
if(mWaterfallTiles != null && mWaterfallLevels != null)
|
if(mWaterfallTiles != null && mWaterfallIndexes != null)
|
||||||
{
|
{
|
||||||
for(int y = 0; y < mWaterfallHeight; y++)
|
for(int y = 0; y < mWaterfallHeight; y++)
|
||||||
{
|
{
|
||||||
@@ -774,10 +689,10 @@ public class SpectralDisplay extends StackPane
|
|||||||
for(int y = 0; y < previousHeight; y++)
|
for(int y = 0; y < previousHeight; y++)
|
||||||
{
|
{
|
||||||
int source = (mWaterfallWriteRow + y) % previousHeight;
|
int source = (mWaterfallWriteRow + y) % previousHeight;
|
||||||
System.arraycopy(mWaterfallLevels, source * width, indexes, y * width, width);
|
System.arraycopy(mWaterfallIndexes, source * width, indexes, y * width, width);
|
||||||
}
|
}
|
||||||
|
|
||||||
mWaterfallLevels = indexes;
|
mWaterfallIndexes = indexes;
|
||||||
createWaterfallTiles(width, rows);
|
createWaterfallTiles(width, rows);
|
||||||
mWaterfallWriteRow = 0;
|
mWaterfallWriteRow = 0;
|
||||||
repaintWaterfallImage();
|
repaintWaterfallImage();
|
||||||
|
|||||||
@@ -353,27 +353,6 @@ public class SpectralDisplayConfigPanel extends VBox
|
|||||||
"falling slowly"));
|
"falling slowly"));
|
||||||
row = addRow(grid, row, peakHold.label(), peakHold.control());
|
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
|
//Layer settings
|
||||||
for(SpectralDisplayLayer layer: mSpectralDisplay.getLayers())
|
for(SpectralDisplayLayer layer: mSpectralDisplay.getLayers())
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -33,31 +33,44 @@ public class WaterfallPalette
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Palette based on the original Swing waterfall colors: a dark to bright blue ramp, a blue to yellow ramp, yellow
|
* Palette of the original Swing waterfall: dark blue noise floor, a blue to yellow ramp, yellow fading to orange,
|
||||||
* fading to orange, then red. The blue ramp covers the bottom quarter of the palette, where the waterfall places
|
* then red.
|
||||||
* the noise floor, so the noise stays blue and weak signals stand out from it.
|
|
||||||
*/
|
*/
|
||||||
public static int[] classic()
|
public static int[] classic()
|
||||||
{
|
{
|
||||||
int[] palette = new int[SIZE];
|
int[] palette = new int[SIZE];
|
||||||
|
|
||||||
for(int x = 0; x < 64; x++)
|
for(int x = 0; x < 16; x++)
|
||||||
{
|
{
|
||||||
palette[x] = argb(0, 0, blend(64, 191, x / 63.0));
|
palette[x] = argb(0, 0, 127);
|
||||||
}
|
}
|
||||||
|
|
||||||
for(int x = 64; x < 100; x++)
|
for(int x = 16; x < 32; x++)
|
||||||
{
|
{
|
||||||
double t = (x - 64) / 36.0;
|
palette[x] = argb(0, 0, 191);
|
||||||
palette[x] = argb(blend(0, 255, t), blend(0, 255, t), blend(191, 0, t));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for(int x = 100; x < 220; x++)
|
int r = 0;
|
||||||
|
int g = 0;
|
||||||
|
int b = 191;
|
||||||
|
|
||||||
|
for(int x = 32; x < 60; x++)
|
||||||
{
|
{
|
||||||
palette[x] = argb(255, blend(255, 0, (x - 100) / 120.0), 0);
|
palette[x] = argb(r, g, b);
|
||||||
|
r += 9;
|
||||||
|
g += 9;
|
||||||
|
b -= 6;
|
||||||
}
|
}
|
||||||
|
|
||||||
for(int x = 220; x < SIZE; x++)
|
g = 255;
|
||||||
|
|
||||||
|
for(int x = 60; x < 188; x++)
|
||||||
|
{
|
||||||
|
palette[x] = argb(255, g, 0);
|
||||||
|
g -= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
for(int x = 188; x < SIZE; x++)
|
||||||
{
|
{
|
||||||
palette[x] = argb(255, 0, 0);
|
palette[x] = argb(255, 0, 0);
|
||||||
}
|
}
|
||||||
@@ -65,11 +78,6 @@ public class WaterfallPalette
|
|||||||
return palette;
|
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.
|
* Palette that blends linearly between evenly spaced colors.
|
||||||
* @param colors web color strings (for example #440154), lowest intensity first
|
* @param colors web color strings (for example #440154), lowest intensity first
|
||||||
|
|||||||
@@ -1,289 +0,0 @@
|
|||||||
/*
|
|
||||||
* *****************************************************************************
|
|
||||||
* 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -30,6 +30,8 @@ import javafx.beans.property.LongProperty;
|
|||||||
import javafx.beans.property.SimpleBooleanProperty;
|
import javafx.beans.property.SimpleBooleanProperty;
|
||||||
import javafx.beans.property.SimpleIntegerProperty;
|
import javafx.beans.property.SimpleIntegerProperty;
|
||||||
import javafx.beans.property.SimpleLongProperty;
|
import javafx.beans.property.SimpleLongProperty;
|
||||||
|
import javafx.beans.property.SimpleStringProperty;
|
||||||
|
import javafx.beans.property.StringProperty;
|
||||||
import javafx.geometry.VPos;
|
import javafx.geometry.VPos;
|
||||||
import javafx.scene.canvas.GraphicsContext;
|
import javafx.scene.canvas.GraphicsContext;
|
||||||
import javafx.scene.paint.Color;
|
import javafx.scene.paint.Color;
|
||||||
@@ -52,6 +54,7 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
|
|||||||
private final IntegerProperty mChannelBandwidth = new SimpleIntegerProperty(0);
|
private final IntegerProperty mChannelBandwidth = new SimpleIntegerProperty(0);
|
||||||
private final LongProperty mCarrierOffset = new SimpleLongProperty(0);
|
private final LongProperty mCarrierOffset = new SimpleLongProperty(0);
|
||||||
private final BooleanProperty mCarrierOffsetValid = new SimpleBooleanProperty(false);
|
private final BooleanProperty mCarrierOffsetValid = new SimpleBooleanProperty(false);
|
||||||
|
private final StringProperty mSignalReadout = new SimpleStringProperty();
|
||||||
private final Text mMeasure = new Text();
|
private final Text mMeasure = new Text();
|
||||||
private final double mTextHeight;
|
private final double mTextHeight;
|
||||||
|
|
||||||
@@ -66,6 +69,15 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
|
|||||||
mChannelBandwidth.addListener((ob, ov, nv) -> requestRender());
|
mChannelBandwidth.addListener((ob, ov, nv) -> requestRender());
|
||||||
mCarrierOffset.addListener((ob, ov, nv) -> requestRender());
|
mCarrierOffset.addListener((ob, ov, nv) -> requestRender());
|
||||||
mCarrierOffsetValid.addListener((ob, ov, nv) -> requestRender());
|
mCarrierOffsetValid.addListener((ob, ov, nv) -> requestRender());
|
||||||
|
mSignalReadout.addListener((ob, ov, nv) -> requestRender());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Channel signal level readout shown below the channel bandwidth label, or null for none.
|
||||||
|
*/
|
||||||
|
public StringProperty signalReadoutProperty()
|
||||||
|
{
|
||||||
|
return mSignalReadout;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -163,6 +175,24 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
|
|||||||
gc.setTextAlign(TextAlignment.LEFT);
|
gc.setTextAlign(TextAlignment.LEFT);
|
||||||
gc.fillText(label, x, y);
|
gc.fillText(label, x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Signal readout centered on the channel, on the row below the carrier (PLL) label. Drawn last so that the
|
||||||
|
//carrier line doesn't cross it.
|
||||||
|
String readout = mSignalReadout.get();
|
||||||
|
|
||||||
|
if(edges != null && readout != null && !readout.isEmpty())
|
||||||
|
{
|
||||||
|
mMeasure.setText(readout);
|
||||||
|
double width = mMeasure.getLayoutBounds().getWidth();
|
||||||
|
double x = Math.max(3, Math.min(area.width() - width - 3, (edges[0] + edges[1] - width) / 2.0));
|
||||||
|
double y = 2 * (mTextHeight + 6);
|
||||||
|
//Nearly opaque, since the readout is centered on the channel where the carrier line usually is
|
||||||
|
gc.setFill(theme.getBackground(0.95));
|
||||||
|
gc.fillRoundRect(x - 3, y - 1, width + 6, mTextHeight + 2, 4, 4);
|
||||||
|
gc.setFill(opaque(theme.getChannelProcessing()));
|
||||||
|
gc.setTextAlign(TextAlignment.LEFT);
|
||||||
|
gc.fillText(readout, x, y);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
|
|||||||
private ReentrantLock mBufferListenerLock = new ReentrantLock();
|
private ReentrantLock mBufferListenerLock = new ReentrantLock();
|
||||||
private ReentrantLock mLock = new ReentrantLock();
|
private ReentrantLock mLock = new ReentrantLock();
|
||||||
protected Broadcaster<INativeBuffer> mNativeBufferBroadcaster = new Broadcaster();
|
protected Broadcaster<INativeBuffer> mNativeBufferBroadcaster = new Broadcaster();
|
||||||
|
private final TunerNoiseFloorEstimator mNoiseFloorEstimator = new TunerNoiseFloorEstimator(this::getFrequency,
|
||||||
|
this::getSampleRate, this::getUsableBandwidth);
|
||||||
protected FrequencyController mFrequencyController;
|
protected FrequencyController mFrequencyController;
|
||||||
private int mMiddleUnusableHalfBandwidth;
|
private int mMiddleUnusableHalfBandwidth;
|
||||||
private int mMeasuredFrequencyError;
|
private int mMeasuredFrequencyError;
|
||||||
@@ -726,6 +728,15 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
|
|||||||
|
|
||||||
//Note: unprotected access to the broadcaster ... the broadcaster uses thread-save internal list
|
//Note: unprotected access to the broadcaster ... the broadcaster uses thread-save internal list
|
||||||
mNativeBufferBroadcaster.broadcast(complexSamples);
|
mNativeBufferBroadcaster.broadcast(complexSamples);
|
||||||
|
mNoiseFloorEstimator.receive(complexSamples);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Noise floor estimator for this tuner, which measures on demand from the buffers that this controller delivers.
|
||||||
|
*/
|
||||||
|
public TunerNoiseFloorEstimator getNoiseFloorEstimator()
|
||||||
|
{
|
||||||
|
return mNoiseFloorEstimator;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,463 @@
|
|||||||
|
/*
|
||||||
|
* *****************************************************************************
|
||||||
|
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||||
|
* ****************************************************************************
|
||||||
|
*/
|
||||||
|
|
||||||
|
package io.github.dsheirer.source.tuner;
|
||||||
|
|
||||||
|
import io.github.dsheirer.buffer.INativeBuffer;
|
||||||
|
import io.github.dsheirer.dsp.fft.MixedRadixComplexFFT;
|
||||||
|
import io.github.dsheirer.dsp.window.WindowFactory;
|
||||||
|
import io.github.dsheirer.dsp.window.WindowType;
|
||||||
|
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
|
||||||
|
import io.github.dsheirer.util.ThreadPool;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import java.util.function.DoubleSupplier;
|
||||||
|
import java.util.function.IntSupplier;
|
||||||
|
import java.util.function.LongSupplier;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estimates a tuner's noise floor from the tuner's sample buffers, independent of the channelizer that sources the
|
||||||
|
* tuner's channels. A windowed FFT with bins of about 25 kHz measures the tuner bandwidth and each bin's mean power is
|
||||||
|
* converted to a noise power density once a second.
|
||||||
|
*
|
||||||
|
* A channel's noise floor is the median of the 40 usable bins nearest the channel (about +/- 500 kHz), excluding the
|
||||||
|
* channel's own bins and their immediate neighbors. Near a band edge, the search continues toward the band center so
|
||||||
|
* that channels anywhere in the tuner's usable bandwidth get an estimate. Usable bins are the tuner's usable
|
||||||
|
* bandwidth, which is where the channel source managers place channels, minus the DC spur. Most bins hold only noise, so the median is a robust noise estimate unless more than
|
||||||
|
* half of the neighborhood is occupied. The estimate is local because real tuner noise floors aren't flat: a
|
||||||
|
* HydraSDR airband recording tilts about 6 dB across 8 MHz, which put a tuner-wide median 2 dB above the noise at one
|
||||||
|
* end of the band.
|
||||||
|
*
|
||||||
|
* The noise density is in full-scale units per Hertz, where a complex tone with a magnitude of 1.0 has a power of 1.0
|
||||||
|
* (0 dBFS). The channelizers preserve the tuner's full scale, so the noise density applies directly to channel
|
||||||
|
* samples.
|
||||||
|
*
|
||||||
|
* Measurement is on demand. A noise density request turns it on and it turns itself off when there are no requests
|
||||||
|
* for a few seconds. While it's off, the tuner's buffer delivery thread only checks a flag. While it's on, the
|
||||||
|
* delivery thread keeps a reference to the latest buffer and a scheduled task measures a few FFT blocks from it 20
|
||||||
|
* times a second. The estimator never registers as a buffer listener, since that starts and stops tuner streaming.
|
||||||
|
*/
|
||||||
|
public class TunerNoiseFloorEstimator
|
||||||
|
{
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(TunerNoiseFloorEstimator.class);
|
||||||
|
private static final double BIN_WIDTH = 25000.0;
|
||||||
|
//Minimum size so that low sample rate tuners have enough bins for a channel neighborhood, with narrower bins
|
||||||
|
private static final int MINIMUM_FFT_SIZE = 64;
|
||||||
|
//Window with low sidelobes so that strong signals don't leak into the noise bins
|
||||||
|
private static final WindowType WINDOW_TYPE = WindowType.BLACKMAN_HARRIS_7;
|
||||||
|
private static final long PROCESSING_INTERVAL_MS = 50;
|
||||||
|
private static final int BLOCKS_PER_INTERVAL = 8;
|
||||||
|
private static final long ESTIMATE_INTERVAL_MS = 1000;
|
||||||
|
private static final long REQUEST_TIMEOUT_MS = 3000;
|
||||||
|
//Fraction of the sample rate, centered on DC, that is used when the tuner's usable bandwidth isn't known. The
|
||||||
|
//tuner's anti-alias filter rolls off the edges.
|
||||||
|
private static final double DEFAULT_USABLE_BANDWIDTH_FRACTION = 0.8;
|
||||||
|
//Bins on each side of DC that are skipped to avoid the tuner's DC spur
|
||||||
|
private static final int DC_EXCLUSION_BINS = 1;
|
||||||
|
//Usable bins nearest the channel that form its noise neighborhood (+/- 500 kHz at 25 kHz bins)
|
||||||
|
private static final int NEIGHBORHOOD_BINS = 40;
|
||||||
|
//Bins on each side of a channel's own bins that are excluded since they can hold the channel's signal
|
||||||
|
private static final int GUARD_BINS = 1;
|
||||||
|
//Fewest neighborhood bins for an estimate
|
||||||
|
private static final int MINIMUM_NEIGHBORHOOD_BINS = 8;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Noise density of each bin, with the tuner frequency and sample rate that it was measured at. Bins are in FFT
|
||||||
|
* order: bin 0 is DC and bins above size / 2 are negative frequencies.
|
||||||
|
*/
|
||||||
|
private record Estimate(long frequency, double sampleRate, double[] density, boolean[] usable) {}
|
||||||
|
|
||||||
|
private final LongSupplier mFrequency;
|
||||||
|
private final DoubleSupplier mSampleRate;
|
||||||
|
private final IntSupplier mUsableBandwidth;
|
||||||
|
private final boolean mScheduled;
|
||||||
|
private final AtomicReference<INativeBuffer> mLatestBuffer = new AtomicReference<>();
|
||||||
|
private final Object mLock = new Object();
|
||||||
|
private volatile boolean mActive;
|
||||||
|
private volatile long mLastRequestTimestamp;
|
||||||
|
private volatile Estimate mEstimate;
|
||||||
|
private ScheduledFuture<?> mProcessingTask;
|
||||||
|
|
||||||
|
//Measurement state, accessed only by the processing task
|
||||||
|
private long mMeasurementFrequency;
|
||||||
|
private double mMeasurementSampleRate;
|
||||||
|
private MixedRadixComplexFFT mFFT;
|
||||||
|
private float[] mWindow;
|
||||||
|
private double mWindowPower;
|
||||||
|
private float[] mBlock;
|
||||||
|
private int mBlockPointer;
|
||||||
|
private double[] mBinPowerAccumulator;
|
||||||
|
private int mAccumulatedBlocks;
|
||||||
|
private long mMeasurementStart;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs an instance
|
||||||
|
* @param frequency supplier for the tuner's center frequency
|
||||||
|
* @param sampleRate supplier for the tuner's sample rate
|
||||||
|
* @param usableBandwidth supplier for the tuner's usable bandwidth in Hertz, or 0 or less if unknown
|
||||||
|
*/
|
||||||
|
public TunerNoiseFloorEstimator(LongSupplier frequency, DoubleSupplier sampleRate, IntSupplier usableBandwidth)
|
||||||
|
{
|
||||||
|
this(frequency, sampleRate, usableBandwidth, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs an instance
|
||||||
|
* @param frequency supplier for the tuner's center frequency
|
||||||
|
* @param sampleRate supplier for the tuner's sample rate
|
||||||
|
* @param usableBandwidth supplier for the tuner's usable bandwidth in Hertz, or 0 or less if unknown
|
||||||
|
* @param scheduled true to measure on a scheduled task, or false for tests that call process() directly
|
||||||
|
*/
|
||||||
|
TunerNoiseFloorEstimator(LongSupplier frequency, DoubleSupplier sampleRate, IntSupplier usableBandwidth,
|
||||||
|
boolean scheduled)
|
||||||
|
{
|
||||||
|
mFrequency = frequency;
|
||||||
|
mSampleRate = sampleRate;
|
||||||
|
mUsableBandwidth = usableBandwidth;
|
||||||
|
mScheduled = scheduled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Receives each tuner buffer on the tuner's buffer delivery thread. Keeps the buffer only while measuring.
|
||||||
|
*/
|
||||||
|
public void receive(INativeBuffer buffer)
|
||||||
|
{
|
||||||
|
if(mActive)
|
||||||
|
{
|
||||||
|
mLatestBuffer.set(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Noise power density near a channel, in full-scale units per Hertz. Turns on the measurement. Thread safe.
|
||||||
|
* @param frequency of the channel
|
||||||
|
* @param bandwidth of the channel in Hertz
|
||||||
|
* @return noise density, or NaN when there isn't an estimate yet, the tuner frequency or sample rate changed since
|
||||||
|
* the estimate, or the channel isn't within the usable tuner bandwidth.
|
||||||
|
*/
|
||||||
|
public double getNoiseDensity(long frequency, int bandwidth)
|
||||||
|
{
|
||||||
|
mLastRequestTimestamp = System.currentTimeMillis();
|
||||||
|
|
||||||
|
if(!mActive)
|
||||||
|
{
|
||||||
|
start();
|
||||||
|
}
|
||||||
|
|
||||||
|
Estimate estimate = mEstimate;
|
||||||
|
|
||||||
|
if(estimate == null || estimate.frequency() != mFrequency.getAsLong() ||
|
||||||
|
estimate.sampleRate() != mSampleRate.getAsDouble())
|
||||||
|
{
|
||||||
|
return Double.NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
int size = estimate.density().length;
|
||||||
|
double binWidth = estimate.sampleRate() / size;
|
||||||
|
//Signed bin offsets from DC of the bins that the channel overlaps
|
||||||
|
int low = (int)Math.round((frequency - bandwidth / 2.0 - estimate.frequency()) / binWidth);
|
||||||
|
int high = (int)Math.round((frequency + bandwidth / 2.0 - estimate.frequency()) / binWidth);
|
||||||
|
int center = (int)Math.round((double)(frequency - estimate.frequency()) / binWidth);
|
||||||
|
|
||||||
|
if(Math.abs(center) >= size / 2)
|
||||||
|
{
|
||||||
|
return Double.NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
double[] values = new double[NEIGHBORHOOD_BINS];
|
||||||
|
int count = 0;
|
||||||
|
int below = low - GUARD_BINS - 1;
|
||||||
|
int above = high + GUARD_BINS + 1;
|
||||||
|
|
||||||
|
//Alternate outward on each side of the channel, so that a channel near a band edge continues toward the center
|
||||||
|
while(count < NEIGHBORHOOD_BINS && (below > -size / 2 || above < size / 2))
|
||||||
|
{
|
||||||
|
if(below > -size / 2)
|
||||||
|
{
|
||||||
|
int bin = below < 0 ? below + size : below;
|
||||||
|
|
||||||
|
if(estimate.usable()[bin])
|
||||||
|
{
|
||||||
|
values[count++] = estimate.density()[bin];
|
||||||
|
}
|
||||||
|
|
||||||
|
below--;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(count < NEIGHBORHOOD_BINS && above < size / 2)
|
||||||
|
{
|
||||||
|
int bin = above < 0 ? above + size : above;
|
||||||
|
|
||||||
|
if(estimate.usable()[bin])
|
||||||
|
{
|
||||||
|
values[count++] = estimate.density()[bin];
|
||||||
|
}
|
||||||
|
|
||||||
|
above++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count >= MINIMUM_NEIGHBORHOOD_BINS ? median(values, count) : Double.NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns on the measurement.
|
||||||
|
*/
|
||||||
|
private void start()
|
||||||
|
{
|
||||||
|
synchronized(mLock)
|
||||||
|
{
|
||||||
|
if(!mActive)
|
||||||
|
{
|
||||||
|
mActive = true;
|
||||||
|
|
||||||
|
if(mScheduled)
|
||||||
|
{
|
||||||
|
mProcessingTask = ThreadPool.SCHEDULED.scheduleAtFixedRate(this::processScheduled,
|
||||||
|
PROCESSING_INTERVAL_MS, PROCESSING_INTERVAL_MS, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns off the measurement and discards the estimate, so that a stale estimate isn't used when it turns back on.
|
||||||
|
*/
|
||||||
|
private void stop()
|
||||||
|
{
|
||||||
|
synchronized(mLock)
|
||||||
|
{
|
||||||
|
//A request can arrive between the timeout check and here
|
||||||
|
if(System.currentTimeMillis() - mLastRequestTimestamp <= REQUEST_TIMEOUT_MS)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mActive = false;
|
||||||
|
|
||||||
|
if(mProcessingTask != null)
|
||||||
|
{
|
||||||
|
mProcessingTask.cancel(false);
|
||||||
|
mProcessingTask = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
mLatestBuffer.set(null);
|
||||||
|
mEstimate = null;
|
||||||
|
mBinPowerAccumulator = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processScheduled()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if(System.currentTimeMillis() - mLastRequestTimestamp > REQUEST_TIMEOUT_MS)
|
||||||
|
{
|
||||||
|
stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
process(System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
catch(Throwable t)
|
||||||
|
{
|
||||||
|
LOGGER.error("Error estimating tuner noise floor", t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Measures a few FFT blocks from the latest buffer and updates the estimate once a second. Package private for
|
||||||
|
* tests, which call it directly instead of waiting for the scheduled task.
|
||||||
|
* @param now timestamp in milliseconds
|
||||||
|
*/
|
||||||
|
void process(long now)
|
||||||
|
{
|
||||||
|
INativeBuffer buffer = mLatestBuffer.getAndSet(null);
|
||||||
|
|
||||||
|
if(buffer == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
long frequency = mFrequency.getAsLong();
|
||||||
|
double sampleRate = mSampleRate.getAsDouble();
|
||||||
|
|
||||||
|
if(sampleRate <= 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(mBinPowerAccumulator == null || frequency != mMeasurementFrequency || sampleRate != mMeasurementSampleRate)
|
||||||
|
{
|
||||||
|
configure(frequency, sampleRate, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
int blocks = 0;
|
||||||
|
int size = mWindow.length;
|
||||||
|
mBlockPointer = 0;
|
||||||
|
Iterator<InterleavedComplexSamples> iterator = buffer.iteratorInterleaved();
|
||||||
|
|
||||||
|
while(blocks < BLOCKS_PER_INTERVAL && iterator.hasNext())
|
||||||
|
{
|
||||||
|
float[] samples = iterator.next().samples();
|
||||||
|
int pointer = 0;
|
||||||
|
|
||||||
|
while(blocks < BLOCKS_PER_INTERVAL && pointer < samples.length)
|
||||||
|
{
|
||||||
|
int count = Math.min(samples.length - pointer, 2 * (size - mBlockPointer));
|
||||||
|
System.arraycopy(samples, pointer, mBlock, 2 * mBlockPointer, count);
|
||||||
|
pointer += count;
|
||||||
|
mBlockPointer += count / 2;
|
||||||
|
|
||||||
|
if(mBlockPointer == size)
|
||||||
|
{
|
||||||
|
measureBlock();
|
||||||
|
mBlockPointer = 0;
|
||||||
|
blocks++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(now - mMeasurementStart >= ESTIMATE_INTERVAL_MS && mAccumulatedBlocks > 0)
|
||||||
|
{
|
||||||
|
publish();
|
||||||
|
mMeasurementStart = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets up the FFT for the tuner's sample rate and restarts the measurement.
|
||||||
|
*/
|
||||||
|
private void configure(long frequency, double sampleRate, long now)
|
||||||
|
{
|
||||||
|
mMeasurementFrequency = frequency;
|
||||||
|
mMeasurementSampleRate = sampleRate;
|
||||||
|
mMeasurementStart = now;
|
||||||
|
mEstimate = null;
|
||||||
|
|
||||||
|
int size = getFftSize(sampleRate);
|
||||||
|
|
||||||
|
if(mWindow == null || mWindow.length != size)
|
||||||
|
{
|
||||||
|
mFFT = new MixedRadixComplexFFT(size);
|
||||||
|
mWindow = WindowFactory.getWindow(WINDOW_TYPE, size);
|
||||||
|
mBlock = new float[size * 2];
|
||||||
|
double sumSquares = 0.0;
|
||||||
|
|
||||||
|
for(float coefficient: mWindow)
|
||||||
|
{
|
||||||
|
sumSquares += coefficient * coefficient;
|
||||||
|
}
|
||||||
|
|
||||||
|
mWindowPower = sumSquares;
|
||||||
|
}
|
||||||
|
|
||||||
|
mBinPowerAccumulator = new double[size];
|
||||||
|
mAccumulatedBlocks = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FFT size that gives bins of about 25 kHz, or narrower bins at low sample rates, using a size that the mixed
|
||||||
|
* radix FFT supports.
|
||||||
|
*/
|
||||||
|
static int getFftSize(double sampleRate)
|
||||||
|
{
|
||||||
|
int size = Math.max(MINIMUM_FFT_SIZE, (int)Math.round(sampleRate / BIN_WIDTH));
|
||||||
|
|
||||||
|
while(size > MINIMUM_FFT_SIZE && !MixedRadixComplexFFT.isSupported(size))
|
||||||
|
{
|
||||||
|
size--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Windows the block, runs the FFT and accumulates each bin's power.
|
||||||
|
*/
|
||||||
|
private void measureBlock()
|
||||||
|
{
|
||||||
|
for(int x = 0; x < mWindow.length; x++)
|
||||||
|
{
|
||||||
|
mBlock[2 * x] *= mWindow[x];
|
||||||
|
mBlock[2 * x + 1] *= mWindow[x];
|
||||||
|
}
|
||||||
|
|
||||||
|
mFFT.forward(mBlock, 0);
|
||||||
|
|
||||||
|
for(int bin = 0; bin < mWindow.length; bin++)
|
||||||
|
{
|
||||||
|
float i = mBlock[2 * bin];
|
||||||
|
float q = mBlock[2 * bin + 1];
|
||||||
|
mBinPowerAccumulator[bin] += i * i + q * q;
|
||||||
|
}
|
||||||
|
|
||||||
|
mAccumulatedBlocks++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the accumulated bin powers to noise densities and publishes the estimate. For white noise with variance
|
||||||
|
* s^2 per complex sample, a windowed FFT bin has a mean power of s^2 * sum(w^2), and the noise density is s^2 / fs.
|
||||||
|
*/
|
||||||
|
private void publish()
|
||||||
|
{
|
||||||
|
int size = mBinPowerAccumulator.length;
|
||||||
|
double[] density = new double[size];
|
||||||
|
boolean[] usable = new boolean[size];
|
||||||
|
double scale = 1.0 / (mAccumulatedBlocks * mWindowPower * mMeasurementSampleRate);
|
||||||
|
int usableBandwidth = mUsableBandwidth != null ? mUsableBandwidth.getAsInt() : 0;
|
||||||
|
double usableFraction = usableBandwidth > 0 ? Math.min(1.0, usableBandwidth / mMeasurementSampleRate) :
|
||||||
|
DEFAULT_USABLE_BANDWIDTH_FRACTION;
|
||||||
|
double maximumOffset = size * usableFraction / 2.0;
|
||||||
|
|
||||||
|
for(int bin = 0; bin < size; bin++)
|
||||||
|
{
|
||||||
|
density[bin] = mBinPowerAccumulator[bin] * scale;
|
||||||
|
int offset = bin < (size + 1) / 2 ? bin : bin - size;
|
||||||
|
usable[bin] = Math.abs(offset) > DC_EXCLUSION_BINS && Math.abs(offset) <= maximumOffset;
|
||||||
|
}
|
||||||
|
|
||||||
|
mEstimate = new Estimate(mMeasurementFrequency, mMeasurementSampleRate, density, usable);
|
||||||
|
Arrays.fill(mBinPowerAccumulator, 0.0);
|
||||||
|
mAccumulatedBlocks = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Median of the first count values. Sorts the values.
|
||||||
|
*/
|
||||||
|
private static double median(double[] values, int count)
|
||||||
|
{
|
||||||
|
Arrays.sort(values, 0, count);
|
||||||
|
int middle = count / 2;
|
||||||
|
return (count % 2 == 1) ? values[middle] : (values[middle - 1] + values[middle]) / 2.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if the measurement is turned on.
|
||||||
|
*/
|
||||||
|
public boolean isActive()
|
||||||
|
{
|
||||||
|
return mActive;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -84,6 +84,16 @@ public class MultiFrequencyTunerChannelSource extends TunerChannelSource
|
|||||||
return source != null ? source.getTunerName() : null;
|
return source != null ? source.getTunerName() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Noise density near the current frequency's tuner channel source.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public double getNoiseDensity()
|
||||||
|
{
|
||||||
|
TunerChannelSource source = mTunerChannelSource;
|
||||||
|
return source != null ? source.getNoiseDensity() : Double.NaN;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Applies the channel decoder requested frequency correction.
|
* Applies the channel decoder requested frequency correction.
|
||||||
* @param correction requested by the downstream processors.
|
* @param correction requested by the downstream processors.
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import io.github.dsheirer.source.ISourceEventProcessor;
|
|||||||
import io.github.dsheirer.source.SourceEvent;
|
import io.github.dsheirer.source.SourceEvent;
|
||||||
import io.github.dsheirer.source.SourceEventListenerToProcessorAdapter;
|
import io.github.dsheirer.source.SourceEventListenerToProcessorAdapter;
|
||||||
import io.github.dsheirer.source.SourceException;
|
import io.github.dsheirer.source.SourceException;
|
||||||
|
import io.github.dsheirer.source.tuner.TunerNoiseFloorEstimator;
|
||||||
import io.github.dsheirer.source.tuner.frequency.ChannelFrequencyErrorManager;
|
import io.github.dsheirer.source.tuner.frequency.ChannelFrequencyErrorManager;
|
||||||
import io.github.dsheirer.source.tuner.frequency.TunerFrequencyErrorManager;
|
import io.github.dsheirer.source.tuner.frequency.TunerFrequencyErrorManager;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -42,6 +43,7 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
|
|||||||
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
|
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
|
||||||
private volatile long mStartTimestamp;
|
private volatile long mStartTimestamp;
|
||||||
private volatile String mTunerName;
|
private volatile String mTunerName;
|
||||||
|
private volatile TunerNoiseFloorEstimator mNoiseFloorEstimator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tuner Channel Source is a Digital Drop Channel (DDC) abstract class that defines the minimum functionality
|
* Tuner Channel Source is a Digital Drop Channel (DDC) abstract class that defines the minimum functionality
|
||||||
@@ -136,6 +138,28 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
|
|||||||
* sources where the producer incorporates a sample delay buffer.
|
* sources where the producer incorporates a sample delay buffer.
|
||||||
* @param timestamp in milliseconds since epoch, or 0 to start with current samples.
|
* @param timestamp in milliseconds since epoch, or 0 to start with current samples.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Tuner noise power density near this channel, in full-scale units per Hertz, where a complex tone with a
|
||||||
|
* magnitude of 1.0 at the tuner input has a power of 1.0 (0 dBFS). Requesting the noise density turns on the
|
||||||
|
* tuner's noise floor measurement, which turns itself back off a few seconds after the last request.
|
||||||
|
* @return noise density, or NaN if the tuner channel source doesn't measure it or it isn't measured yet.
|
||||||
|
*/
|
||||||
|
public double getNoiseDensity()
|
||||||
|
{
|
||||||
|
TunerNoiseFloorEstimator estimator = mNoiseFloorEstimator;
|
||||||
|
TunerChannel channel = getTunerChannel();
|
||||||
|
return estimator != null && channel != null ?
|
||||||
|
estimator.getNoiseDensity(channel.getFrequency(), channel.getBandwidth()) : Double.NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the noise floor estimator of the tuner that sources this channel.
|
||||||
|
*/
|
||||||
|
public void setNoiseFloorEstimator(TunerNoiseFloorEstimator noiseFloorEstimator)
|
||||||
|
{
|
||||||
|
mNoiseFloorEstimator = noiseFloorEstimator;
|
||||||
|
}
|
||||||
|
|
||||||
public void setStartTimestamp(long timestamp)
|
public void setStartTimestamp(long timestamp)
|
||||||
{
|
{
|
||||||
mStartTimestamp = timestamp;
|
mStartTimestamp = timestamp;
|
||||||
|
|||||||
@@ -656,6 +656,8 @@ public class TunerManager implements IDiscoveredTunerStatusListener
|
|||||||
if(source != null)
|
if(source != null)
|
||||||
{
|
{
|
||||||
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
||||||
|
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
|
||||||
|
.getNoiseFloorEstimator());
|
||||||
return source;
|
return source;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -685,6 +687,8 @@ public class TunerManager implements IDiscoveredTunerStatusListener
|
|||||||
if(source != null)
|
if(source != null)
|
||||||
{
|
{
|
||||||
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
source.setTunerName(discoveredTuner.getTuner().getPreferredName());
|
||||||
|
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
|
||||||
|
.getNoiseFloorEstimator());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch(Exception e)
|
catch(Exception e)
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
/*
|
||||||
|
* *****************************************************************************
|
||||||
|
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||||
|
* ****************************************************************************
|
||||||
|
*/
|
||||||
|
|
||||||
|
package io.github.dsheirer.spectrum;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.DoubleSupplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Measures a channel's power within the channel bandwidth from dBFS spectrum frames and compares it to the tuner noise
|
||||||
|
* floor to produce the channel's signal level and signal-to-noise ratio.
|
||||||
|
*
|
||||||
|
* Uses the spectrum frames that a channel spectral display already calculates, so the measurement costs only a sum
|
||||||
|
* over the in-band bins of each frame. The frames come from a FullScaleDecibelConverter, lowest frequency first, with
|
||||||
|
* the channel centered in the frame. Each bin's power is the window's noise bandwidth times the noise power per bin
|
||||||
|
* width, so the in-band power is the sum of the in-band bin powers divided by the window noise bandwidth (in bins).
|
||||||
|
* That is also correct for a tone, whose power spreads across the main lobe bins by the same factor.
|
||||||
|
*
|
||||||
|
* Frames are averaged and a reading is produced every 500 milliseconds.
|
||||||
|
*
|
||||||
|
* Receive frames on one thread. The configuration can change from any thread.
|
||||||
|
*/
|
||||||
|
public class ChannelSignalMeter implements DFTResultsListener
|
||||||
|
{
|
||||||
|
private static final long READING_INTERVAL_MS = 500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Channel measurement configuration.
|
||||||
|
* @param sampleRate of the channel samples
|
||||||
|
* @param bandwidth of the channel in Hertz
|
||||||
|
* @param noiseDensity supplier of the tuner noise density in full-scale units per Hertz, or NaN when unknown
|
||||||
|
*/
|
||||||
|
private record Configuration(double sampleRate, int bandwidth, DoubleSupplier noiseDensity) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Channel signal reading.
|
||||||
|
* @param dbfs channel power (signal plus noise) within the channel bandwidth, relative to full scale
|
||||||
|
* @param snr signal-to-noise ratio in dB, or NaN when the noise floor is unknown. Negative infinity when the
|
||||||
|
* channel power doesn't exceed the noise floor.
|
||||||
|
* @param noiseDbfs noise floor within the channel bandwidth, relative to full scale, or NaN when unknown
|
||||||
|
*/
|
||||||
|
public record Reading(double dbfs, double snr, double noiseDbfs)
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Indicates if the signal-to-noise ratio is available
|
||||||
|
*/
|
||||||
|
public boolean hasSnr()
|
||||||
|
{
|
||||||
|
return !Double.isNaN(snr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Consumer<Reading> mListener;
|
||||||
|
private final long mReadingInterval;
|
||||||
|
private volatile Configuration mConfiguration;
|
||||||
|
private volatile double mWindowNoiseBandwidth = 1.0;
|
||||||
|
private Configuration mAccumulatorConfiguration;
|
||||||
|
private double mPowerAccumulator;
|
||||||
|
private int mFrameCount;
|
||||||
|
private double mMeasuredBandwidth;
|
||||||
|
private long mReadingStart;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs an instance
|
||||||
|
* @param listener to receive readings on the frame thread
|
||||||
|
*/
|
||||||
|
public ChannelSignalMeter(Consumer<Reading> listener)
|
||||||
|
{
|
||||||
|
this(listener, READING_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs an instance with a custom reading interval, for tests.
|
||||||
|
* @param listener to receive readings on the frame thread
|
||||||
|
* @param readingInterval in milliseconds, or 0 for a reading from each frame
|
||||||
|
*/
|
||||||
|
ChannelSignalMeter(Consumer<Reading> listener, long readingInterval)
|
||||||
|
{
|
||||||
|
mListener = listener;
|
||||||
|
mReadingInterval = readingInterval;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the channel to measure, or clears it.
|
||||||
|
* @param sampleRate of the channel samples, or 0 to clear the channel
|
||||||
|
* @param bandwidth of the channel in Hertz, or 0 to clear the channel
|
||||||
|
* @param noiseDensity supplier of the tuner noise density in full-scale units per Hertz, or null when unavailable
|
||||||
|
*/
|
||||||
|
public void setChannel(double sampleRate, int bandwidth, DoubleSupplier noiseDensity)
|
||||||
|
{
|
||||||
|
mConfiguration = (sampleRate > 0 && bandwidth > 0) ? new Configuration(sampleRate, bandwidth, noiseDensity) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the noise bandwidth of the DFT window, in bins.
|
||||||
|
*/
|
||||||
|
public void setWindowNoiseBandwidth(double noiseBandwidth)
|
||||||
|
{
|
||||||
|
mWindowNoiseBandwidth = noiseBandwidth > 0 ? noiseBandwidth : 1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Receives a dBFS spectrum frame for the channel.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void receive(float[] frame)
|
||||||
|
{
|
||||||
|
Configuration configuration = mConfiguration;
|
||||||
|
|
||||||
|
if(configuration == null || frame == null || frame.length == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
|
||||||
|
//Restart on a channel change
|
||||||
|
if(configuration != mAccumulatorConfiguration)
|
||||||
|
{
|
||||||
|
mAccumulatorConfiguration = configuration;
|
||||||
|
mPowerAccumulator = 0.0;
|
||||||
|
mFrameCount = 0;
|
||||||
|
mReadingStart = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
int bins = frame.length;
|
||||||
|
double binWidth = configuration.sampleRate() / bins;
|
||||||
|
int halfWidth = Math.min(bins / 2 - 1, (int)Math.floor(configuration.bandwidth() / 2.0 / binWidth));
|
||||||
|
int center = bins / 2;
|
||||||
|
double power = 0.0;
|
||||||
|
|
||||||
|
for(int bin = center - halfWidth; bin <= center + halfWidth; bin++)
|
||||||
|
{
|
||||||
|
power += Math.pow(10.0, frame[bin] / 10.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
mPowerAccumulator += power / mWindowNoiseBandwidth;
|
||||||
|
mMeasuredBandwidth = (2 * halfWidth + 1) * binWidth;
|
||||||
|
mFrameCount++;
|
||||||
|
|
||||||
|
if(now - mReadingStart >= mReadingInterval)
|
||||||
|
{
|
||||||
|
mListener.accept(getReading(mPowerAccumulator / mFrameCount, mMeasuredBandwidth,
|
||||||
|
configuration.noiseDensity()));
|
||||||
|
mPowerAccumulator = 0.0;
|
||||||
|
mFrameCount = 0;
|
||||||
|
mReadingStart = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a reading.
|
||||||
|
* @param power within the measured bandwidth in full-scale units
|
||||||
|
* @param measuredBandwidth in Hertz
|
||||||
|
* @param noiseDensity supplier, or null
|
||||||
|
*/
|
||||||
|
static Reading getReading(double power, double measuredBandwidth, DoubleSupplier noiseDensity)
|
||||||
|
{
|
||||||
|
double dbfs = 10.0 * Math.log10(power);
|
||||||
|
double density = noiseDensity != null ? noiseDensity.getAsDouble() : Double.NaN;
|
||||||
|
|
||||||
|
if(Double.isFinite(density) && density > 0.0)
|
||||||
|
{
|
||||||
|
double noise = density * measuredBandwidth;
|
||||||
|
double snr = power > noise ? 10.0 * Math.log10((power - noise) / noise) : Double.NEGATIVE_INFINITY;
|
||||||
|
return new Reading(dbfs, snr, 10.0 * Math.log10(noise));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Reading(dbfs, Double.NaN, Double.NaN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 663 B |
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 323 KiB |
@@ -255,118 +255,6 @@ public class TalkerAliasAutoAdderTest
|
|||||||
assertNull(alias(RADIO), "local radio with the same value isn't aliased");
|
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
|
@Test
|
||||||
public void decide()
|
public void decide()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -76,11 +76,9 @@ public class HistoryTableViewTest
|
|||||||
table.getSelectionModel().select(0);
|
table.getSelectionModel().select(0);
|
||||||
table.getSelectionModel().select(2);
|
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();
|
Clipboard.getSystemClipboard().clear();
|
||||||
Event.fireEvent(table, new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.C, false,
|
Event.fireEvent(table, new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.C, false,
|
||||||
!mac, false, mac));
|
true, false, false));
|
||||||
copied.complete(Clipboard.getSystemClipboard().getString());
|
copied.complete(Clipboard.getSystemClipboard().getString());
|
||||||
}
|
}
|
||||||
catch(Throwable t)
|
catch(Throwable t)
|
||||||
|
|||||||
@@ -39,25 +39,15 @@ public class SpectralDisplayThemeTest
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void classicPaletteUsesTheOriginalWaterfallColors()
|
void classicPaletteMatchesTheOriginalWaterfall()
|
||||||
{
|
{
|
||||||
int[] palette = WaterfallPalette.classic();
|
int[] palette = WaterfallPalette.classic();
|
||||||
assertEquals(0xFF0000BF, palette[63]);
|
assertEquals(0xFF00007F, palette[0]);
|
||||||
assertEquals(0xFFFFFF00, palette[100]);
|
assertEquals(0xFF0000BF, palette[16]);
|
||||||
|
assertEquals(0xFFFFFF00, palette[60]);
|
||||||
assertEquals(0xFFFF0000, palette[255]);
|
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
|
@Test
|
||||||
void everyThemeHasAnOpaqueWaterfallAndALabel()
|
void everyThemeHasAnOpaqueWaterfallAndALabel()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,312 +0,0 @@
|
|||||||
/*
|
|
||||||
* *****************************************************************************
|
|
||||||
* 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]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
/*
|
||||||
|
* *****************************************************************************
|
||||||
|
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||||
|
* ****************************************************************************
|
||||||
|
*/
|
||||||
|
|
||||||
|
package io.github.dsheirer.source.tuner;
|
||||||
|
|
||||||
|
import io.github.dsheirer.sample.complex.ComplexSamples;
|
||||||
|
import io.github.dsheirer.sample.complex.ComplexSamplesNativeBufferAdapter;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feeds white noise of a known density to the tuner noise floor estimator and checks the channel noise density.
|
||||||
|
*/
|
||||||
|
public class TunerNoiseFloorEstimatorTest
|
||||||
|
{
|
||||||
|
private static final long CENTER = 100_000_000L;
|
||||||
|
private static final double NOISE_VARIANCE = 1E-4;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Noise with optional tones, one buffer per 50 ms processing interval.
|
||||||
|
*/
|
||||||
|
private static class Generator
|
||||||
|
{
|
||||||
|
private final Random mRandom = new Random(1234);
|
||||||
|
private final double mSampleRate;
|
||||||
|
private final double[] mToneOffsets;
|
||||||
|
private final double mToneMagnitude;
|
||||||
|
private long mSample;
|
||||||
|
|
||||||
|
Generator(double sampleRate, double toneMagnitude, double... toneOffsets)
|
||||||
|
{
|
||||||
|
mSampleRate = sampleRate;
|
||||||
|
mToneMagnitude = toneMagnitude;
|
||||||
|
mToneOffsets = toneOffsets;
|
||||||
|
}
|
||||||
|
|
||||||
|
ComplexSamplesNativeBufferAdapter next(int length)
|
||||||
|
{
|
||||||
|
float[] i = new float[length];
|
||||||
|
float[] q = new float[length];
|
||||||
|
double sigma = Math.sqrt(NOISE_VARIANCE / 2.0);
|
||||||
|
|
||||||
|
for(int x = 0; x < length; x++)
|
||||||
|
{
|
||||||
|
double vi = mRandom.nextGaussian() * sigma;
|
||||||
|
double vq = mRandom.nextGaussian() * sigma;
|
||||||
|
|
||||||
|
for(double offset: mToneOffsets)
|
||||||
|
{
|
||||||
|
double phase = 2.0 * Math.PI * offset * (mSample + x) / mSampleRate;
|
||||||
|
vi += mToneMagnitude * Math.cos(phase);
|
||||||
|
vq += mToneMagnitude * Math.sin(phase);
|
||||||
|
}
|
||||||
|
|
||||||
|
i[x] = (float)vi;
|
||||||
|
q[x] = (float)vq;
|
||||||
|
}
|
||||||
|
|
||||||
|
mSample += length;
|
||||||
|
return new ComplexSamplesNativeBufferAdapter(new ComplexSamples(i, q, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs 2 seconds of buffers through the estimator and returns the noise density in dBFS/Hz for the channel.
|
||||||
|
*/
|
||||||
|
private static double run(double sampleRate, Generator generator, long channelFrequency, int bandwidth)
|
||||||
|
{
|
||||||
|
TunerNoiseFloorEstimator estimator = new TunerNoiseFloorEstimator(() -> CENTER, () -> sampleRate,
|
||||||
|
() -> (int)(sampleRate * 0.98), false);
|
||||||
|
assertTrue(Double.isNaN(estimator.getNoiseDensity(channelFrequency, bandwidth)), "no estimate before measuring");
|
||||||
|
assertTrue(estimator.isActive(), "request turns on the measurement");
|
||||||
|
int bufferLength = TunerNoiseFloorEstimator.getFftSize(sampleRate) * 8;
|
||||||
|
|
||||||
|
for(long now = 0; now <= 2000; now += 50)
|
||||||
|
{
|
||||||
|
estimator.receive(generator.next(bufferLength));
|
||||||
|
estimator.process(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 10.0 * Math.log10(estimator.getNoiseDensity(channelFrequency, bandwidth));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double expected(double sampleRate)
|
||||||
|
{
|
||||||
|
return 10.0 * Math.log10(NOISE_VARIANCE / sampleRate);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: noise density matches the injected noise at several tuner sample rates.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void noiseDensity()
|
||||||
|
{
|
||||||
|
for(double sampleRate: new double[]{2_400_000.0, 10_000_000.0, 6_000_000.0, 250_000.0})
|
||||||
|
{
|
||||||
|
long offset = (long)Math.min(150_000, 0.2 * sampleRate);
|
||||||
|
double measured = run(sampleRate, new Generator(sampleRate, 0.0), CENTER + offset, 12500);
|
||||||
|
assertEquals(expected(sampleRate), measured, 0.3, "sample rate " + sampleRate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: strong carriers on the channel and on a few neighbors, including adjacent 12.5 kHz channels, don't move
|
||||||
|
* the noise estimate.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void occupiedNeighbors()
|
||||||
|
{
|
||||||
|
double sampleRate = 2_400_000.0;
|
||||||
|
long channel = CENTER + 150_000;
|
||||||
|
Generator generator = new Generator(sampleRate, 0.03, 150_000, 137_500, 162_500, 250_000, 50_000, 300_000);
|
||||||
|
assertEquals(expected(sampleRate), run(sampleRate, generator, channel, 12500), 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: channels near the tuner band edges, where the channel source managers can place them after a retune for a
|
||||||
|
* traffic channel, still get a noise estimate. Offsets up to 49% of the sample rate (98% of the bandwidth).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void channelNearBandEdge()
|
||||||
|
{
|
||||||
|
for(double sampleRate: new double[]{2_400_000.0, 10_000_000.0})
|
||||||
|
{
|
||||||
|
for(double fraction: new double[]{0.38, 0.42, 0.45, 0.47, 0.49, -0.45, -0.47, -0.49})
|
||||||
|
{
|
||||||
|
long channel = CENTER + (long)(fraction * sampleRate);
|
||||||
|
double measured = run(sampleRate, new Generator(sampleRate, 0.0), channel, 12500);
|
||||||
|
assertEquals(expected(sampleRate), measured, 0.3, "sample rate " + sampleRate + " channel at " +
|
||||||
|
fraction + " of the sample rate");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: a tuner frequency change invalidates the estimate until the next one.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void frequencyChange()
|
||||||
|
{
|
||||||
|
double sampleRate = 2_400_000.0;
|
||||||
|
AtomicLong frequency = new AtomicLong(CENTER);
|
||||||
|
TunerNoiseFloorEstimator estimator = new TunerNoiseFloorEstimator(frequency::get, () -> sampleRate,
|
||||||
|
() -> (int)(sampleRate * 0.98), false);
|
||||||
|
estimator.getNoiseDensity(CENTER, 12500);
|
||||||
|
Generator generator = new Generator(sampleRate, 0.0);
|
||||||
|
|
||||||
|
for(long now = 0; now <= 1100; now += 50)
|
||||||
|
{
|
||||||
|
estimator.receive(generator.next(1024));
|
||||||
|
estimator.process(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertFalse(Double.isNaN(estimator.getNoiseDensity(CENTER + 100_000, 12500)));
|
||||||
|
frequency.set(CENTER + 1_000_000);
|
||||||
|
assertTrue(Double.isNaN(estimator.getNoiseDensity(CENTER + 1_100_000, 12500)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: buffers aren't kept until a request turns on the measurement.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void inactiveUntilRequested()
|
||||||
|
{
|
||||||
|
TunerNoiseFloorEstimator estimator = new TunerNoiseFloorEstimator(() -> CENTER, () -> 2_400_000.0, () -> 0,
|
||||||
|
false);
|
||||||
|
assertFalse(estimator.isActive());
|
||||||
|
estimator.receive(new Generator(2_400_000.0, 0.0).next(1024));
|
||||||
|
estimator.process(2000);
|
||||||
|
assertFalse(estimator.isActive());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: FFT sizes give bins of about 25 kHz, with a minimum size for low sample rates.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void fftSize()
|
||||||
|
{
|
||||||
|
assertEquals(96, TunerNoiseFloorEstimator.getFftSize(2_400_000.0));
|
||||||
|
assertEquals(400, TunerNoiseFloorEstimator.getFftSize(10_000_000.0));
|
||||||
|
assertEquals(64, TunerNoiseFloorEstimator.getFftSize(250_000.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
/*
|
||||||
|
* *****************************************************************************
|
||||||
|
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||||
|
* ****************************************************************************
|
||||||
|
*/
|
||||||
|
|
||||||
|
package io.github.dsheirer.spectrum;
|
||||||
|
|
||||||
|
import io.github.dsheirer.dsp.window.WindowType;
|
||||||
|
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
import org.jtransforms.fft.FloatFFT_1D;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds dBFS spectrum frames the same way as the channel spectral display (unity gain window, JTransforms DFT,
|
||||||
|
* full scale decibel converter) from a tone plus white noise of known levels, and checks the channel power and SNR.
|
||||||
|
*/
|
||||||
|
public class ChannelSignalMeterTest
|
||||||
|
{
|
||||||
|
private static final double SAMPLE_RATE = 50000.0;
|
||||||
|
private static final int BANDWIDTH = 12500;
|
||||||
|
private static final int DFT_SIZE = 4096;
|
||||||
|
private static final double NOISE_VARIANCE = 1E-4;
|
||||||
|
private static final double TOLERANCE_DB = 0.3;
|
||||||
|
private static final WindowType[] WINDOWS = {WindowType.BLACKMAN_HARRIS_7, WindowType.HANN, WindowType.HAMMING,
|
||||||
|
WindowType.NONE, WindowType.FLAT_TOP};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Averages the readings of 50 frames. Each reading is one frame, so this averages the power the same way as the
|
||||||
|
* meter's 500 ms reading interval.
|
||||||
|
*/
|
||||||
|
private static double[] measure(WindowType windowType, double toneMagnitude, double toneOffset)
|
||||||
|
{
|
||||||
|
List<ChannelSignalMeter.Reading> readings = new ArrayList<>();
|
||||||
|
ChannelSignalMeter meter = new ChannelSignalMeter(readings::add, 0);
|
||||||
|
meter.setChannel(SAMPLE_RATE, BANDWIDTH, () -> NOISE_VARIANCE / SAMPLE_RATE);
|
||||||
|
meter.setWindowNoiseBandwidth(ComplexDftProcessor.getNoiseBandwidth(windowType));
|
||||||
|
|
||||||
|
float[] window = ComplexDftProcessor.createWindow(windowType, DFT_SIZE, true);
|
||||||
|
FloatFFT_1D fft = new FloatFFT_1D(DFT_SIZE);
|
||||||
|
Random random = new Random(42);
|
||||||
|
double sigma = Math.sqrt(NOISE_VARIANCE / 2.0);
|
||||||
|
double phase = 0.0;
|
||||||
|
double increment = 2.0 * Math.PI * toneOffset / SAMPLE_RATE;
|
||||||
|
|
||||||
|
for(int frame = 0; frame < 50; frame++)
|
||||||
|
{
|
||||||
|
float[] samples = new float[DFT_SIZE * 2];
|
||||||
|
|
||||||
|
for(int x = 0; x < DFT_SIZE; x++)
|
||||||
|
{
|
||||||
|
samples[2 * x] = (float)((random.nextGaussian() * sigma + toneMagnitude * Math.cos(phase)) * window[x]);
|
||||||
|
samples[2 * x + 1] = (float)((random.nextGaussian() * sigma + toneMagnitude * Math.sin(phase)) * window[x]);
|
||||||
|
phase += increment;
|
||||||
|
}
|
||||||
|
|
||||||
|
fft.complexForward(samples);
|
||||||
|
meter.receive(FullScaleDecibelConverter.convert(samples));
|
||||||
|
}
|
||||||
|
|
||||||
|
double power = 0.0;
|
||||||
|
double noise = 0.0;
|
||||||
|
|
||||||
|
for(ChannelSignalMeter.Reading reading: readings)
|
||||||
|
{
|
||||||
|
power += Math.pow(10.0, reading.dbfs() / 10.0);
|
||||||
|
noise = reading.noiseDbfs();
|
||||||
|
}
|
||||||
|
|
||||||
|
power /= readings.size();
|
||||||
|
double noisePower = Math.pow(10.0, noise / 10.0);
|
||||||
|
return new double[]{10.0 * Math.log10(power), 10.0 * Math.log10((power - noisePower) / noisePower), noise};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double expectedNoiseDb()
|
||||||
|
{
|
||||||
|
return 10.0 * Math.log10(NOISE_VARIANCE / SAMPLE_RATE * BANDWIDTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: noise-only channel power matches the injected noise within the channel bandwidth, for each window.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void noiseOnly()
|
||||||
|
{
|
||||||
|
for(WindowType windowType: WINDOWS)
|
||||||
|
{
|
||||||
|
double[] result = measure(windowType, 0.0, 0.0);
|
||||||
|
assertEquals(expectedNoiseDb(), result[0], TOLERANCE_DB, windowType + " channel dBFS");
|
||||||
|
assertEquals(expectedNoiseDb(), result[2], 0.05, windowType + " noise dBFS");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: tone plus noise power and SNR, with the tone off of a bin center, for each window.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void toneAndNoise()
|
||||||
|
{
|
||||||
|
for(WindowType windowType: WINDOWS)
|
||||||
|
{
|
||||||
|
double magnitude = 0.01;
|
||||||
|
double[] result = measure(windowType, magnitude, 1234.5);
|
||||||
|
double tone = magnitude * magnitude;
|
||||||
|
double noise = NOISE_VARIANCE / SAMPLE_RATE * BANDWIDTH;
|
||||||
|
System.out.printf("%s dBFS %.2f (expected %.2f) SNR %.2f (expected %.2f)%n", windowType, result[0],
|
||||||
|
10.0 * Math.log10(tone + noise), result[1], 10.0 * Math.log10(tone / noise));
|
||||||
|
assertEquals(10.0 * Math.log10(tone + noise), result[0], TOLERANCE_DB, windowType + " channel dBFS");
|
||||||
|
assertEquals(10.0 * Math.log10(tone / noise), result[1], TOLERANCE_DB, windowType + " SNR");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test: no noise density gives the channel power without an SNR.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void unknownNoise()
|
||||||
|
{
|
||||||
|
List<ChannelSignalMeter.Reading> readings = new ArrayList<>();
|
||||||
|
ChannelSignalMeter meter = new ChannelSignalMeter(readings::add, 0);
|
||||||
|
meter.setChannel(SAMPLE_RATE, BANDWIDTH, () -> Double.NaN);
|
||||||
|
float[] frame = new float[DFT_SIZE];
|
||||||
|
java.util.Arrays.fill(frame, -100.0f);
|
||||||
|
meter.receive(frame);
|
||||||
|
assertEquals(1, readings.size());
|
||||||
|
assertFalse(readings.getFirst().hasSnr());
|
||||||
|
}
|
||||||
|
}
|
||||||