Compare commits

..

3 Commits

423 changed files with 28739 additions and 35622 deletions

View File

@@ -1,29 +1,35 @@
![Gradle Build](https://github.com/dsheirer/sdrtrunk/actions/workflows/gradle.yml/badge.svg) ![Gradle Build](https://github.com/dsheirer/sdrtrunk/actions/workflows/gradle.yml/badge.svg)
![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg) ![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg)
[![Latest Release](https://img.shields.io/github/v/release/DSheirer/sdrtrunk?label=release)](https://github.com/DSheirer/sdrtrunk/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/DSheirer/sdrtrunk/total)](https://github.com/DSheirer/sdrtrunk/releases) # MacOS Tahoe 26.1 Users - Attention:
[![License](https://img.shields.io/github/license/DSheirer/sdrtrunk)](LICENSE) 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.
[![Discord](https://img.shields.io/badge/chat-on%20Discord-5865F2?logo=discord&logoColor=white)](https://discord.gg/HJQaKYE)
[![support-google_groups-blue](https://img.shields.io/badge/support-google_groups-blue)](https://groups.google.com/g/sdrtrunk) ```
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
```
# sdrtrunk # sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR). A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
> ## 📖 [Read the sdrtrunk User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
> New to sdrtrunk? Start with the **[Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)** guide,
> then use the **[User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)** and
> **[How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)** to set up tuners, playlists, aliases and streaming.
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki) * [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started) * [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual) * [User's Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)
* [FAQ](https://github.com/DSheirer/sdrtrunk/wiki/FAQ)
* [Download](https://github.com/DSheirer/sdrtrunk/releases) * [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support) * [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk primary application window decoding a P25 trunked radio system](https://github.com/DSheirer/sdrtrunk/wiki/images/application_overview.png) ![sdrtrunk Application](https://github.com/DSheirer/sdrtrunk/wiki/images/sdrtrunk.png)
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system **Figure 1:** sdrtrunk Application Screenshot
## 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.

View File

@@ -138,28 +138,31 @@ dependencies {
//Jitpack imports //Jitpack imports
implementation 'com.github.dnault:libresample4j:master' implementation 'com.github.dnault:libresample4j:master'
implementation 'com.github.DSheirer.jmbe:api:v2.1.1'
implementation 'com.github.nwaldispuehl:java-lame:v3.98.4' implementation 'com.github.nwaldispuehl:java-lame:v3.98.4'
//mavenCentral/jcenter imports //mavenCentral/jcenter imports
implementation 'ch.qos.logback:logback-classic:1.6.6' implementation 'ch.qos.logback:logback-classic:1.6.6'
implementation 'ch.qos.logback:logback-core:1.6.6' implementation 'ch.qos.logback:logback-core:1.6.6'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.23.0' implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.23.0'
implementation 'com.formdev:flatlaf:3.8'
implementation 'com.formdev:flatlaf-intellij-themes:3.8' //Not imported - Theme.java loads these themes by class name
implementation 'com.github.jiconfont:jiconfont-font_awesome:4.7.0.1' implementation 'com.github.jiconfont:jiconfont-font_awesome:4.7.0.1'
implementation 'com.github.jiconfont:jiconfont-javafx:1.0.0' implementation 'com.github.jiconfont:jiconfont-javafx:1.0.0'
implementation 'com.github.jiconfont:jiconfont-swing:1.0.1'
implementation('com.github.wendykierp:JTransforms:3.2') { implementation('com.github.wendykierp:JTransforms:3.2') {
exclude group: 'junit' //JLargeArrays 1.7 declares junit as a compile dependency exclude group: 'junit' //JLargeArrays 1.7 declares junit as a compile dependency
} }
implementation 'com.google.code.gson:gson:2.15.0' implementation 'com.google.code.gson:gson:2.15.0'
implementation 'com.google.guava:guava:33.8.0-jre' implementation 'com.google.guava:guava:33.8.0-jre'
implementation 'com.h2database:h2:2.5.252' //Built-in call database implementation 'com.jidesoft:jide-oss:3.6.18'
implementation 'com.zaxxer:HikariCP:7.1.0' //Database connection pool implementation 'com.miglayout:miglayout-swing:11.5.2'
implementation 'com.mpatric:mp3agic:0.9.1' implementation 'com.mpatric:mp3agic:0.9.1'
implementation 'commons-io:commons-io:2.22.0' implementation 'commons-io:commons-io:2.22.0'
implementation 'io.github.dsheirer:jairspy:1.0.12.1' //Airspy tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jairspy:1.0.12.1' //Airspy tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jairspyhf:1.8.1.1' //Airspy HF+ tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jairspyhf:1.8.1.1' //Airspy HF+ tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jbladerf:2.6.0.1' //bladeRF tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jbladerf:2.6.0.1' //bladeRF tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jhackrf:2026.01.3.1' //HackRF tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jhackrf:2026.01.3.1' //HackRF tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jmbe-api:3.0.0' //JMBE audio codec interfaces - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jlibusb:1.0.30.1' //libusb and USB hotplug for the tuner libraries - GitHub release; not pulled in transitively implementation 'io.github.dsheirer:jlibusb:1.0.30.1' //libusb and USB hotplug for the tuner libraries - GitHub release; not pulled in transitively
implementation 'io.github.dsheirer:jhydrasdr:1.1.4.1' //HydraSDR tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jhydrasdr:1.1.4.1' //HydraSDR tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jlimesdr:25.1.0.2' //LimeSDR tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jlimesdr:25.1.0.2' //LimeSDR tuners - GitHub release, see settings.gradle
@@ -173,8 +176,6 @@ dependencies {
implementation 'org.apache.mina:mina-core:2.2.10' implementation 'org.apache.mina:mina-core:2.2.10'
implementation 'org.apache.mina:mina-http:2.2.10' implementation 'org.apache.mina:mina-http:2.2.10'
implementation 'org.controlsfx:controlsfx:11.2.6' implementation 'org.controlsfx:controlsfx:11.2.6'
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.11' //Optional MariaDB call database
implementation 'org.postgresql:postgresql:42.7.14' //Optional PostgreSQL call database
implementation 'org.rauschig:jarchivelib:1.2.0' implementation 'org.rauschig:jarchivelib:1.2.0'
implementation 'org.slf4j:slf4j-api:2.0.20' implementation 'org.slf4j:slf4j-api:2.0.20'
} }
@@ -194,6 +195,7 @@ tasks.withType(JavaCompile).configureEach {
*/ */
def jvmArgsWindows = def jvmArgsWindows =
['--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED', //Needed for controls-fx.jar ['--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED', //Needed for controls-fx.jar
'--add-exports=java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED', //windows users for JIDE
'--add-modules=jdk.incubator.vector', //Project Panama vector API is still in incubator '--add-modules=jdk.incubator.vector', //Project Panama vector API is still in incubator
'--enable-preview', //Project Panama Vector API is still in incubator '--enable-preview', //Project Panama Vector API is still in incubator
'--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls '--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls
@@ -211,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"
@@ -230,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
@@ -304,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
@@ -313,11 +297,9 @@ def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//jdk.incubator.vector - needed for Project Panama foreign function and vector apis //jdk.incubator.vector - needed for Project Panama foreign function and vector apis
//jdk.accessibility is used with assistive technologies like screen readers //jdk.accessibility is used with assistive technologies like screen readers
//java.management for JVM resource monitoring //java.management for JVM resource monitoring
//java.sql, java.naming, java.security.jgss, jdk.net - call database JDBC drivers and connection pool //java.base, java.logging, java.net.http, java.prefs, javafx.controls, javafx.swing - required by sdrtrunk (jdeps)
//java.base, java.desktop, java.logging, java.net.http, java.prefs, javafx.controls - required by sdrtrunk (jdeps)
rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management', rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management',
'java.base', 'java.desktop', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'java.sql', 'java.base', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'javafx.swing')
'java.naming', 'java.security.jgss', 'jdk.net')
//Use only the modules listed above. The runtime plugin's module auto-detection uses a bundled ASM library that //Use only the modules listed above. The runtime plugin's module auto-detection uses a bundled ASM library that
//can't read Java 27 class files and logs a 'Failed to scan' error for each sdrtrunk class. The jdeps module check //can't read Java 27 class files and logs a 'Failed to scan' error for each sdrtrunk class. The jdeps module check
@@ -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

View File

@@ -83,15 +83,6 @@ dependencyResolutionManagement {
content { includeModule 'io.github.dsheirer', 'jbladerf' } content { includeModule 'io.github.dsheirer', 'jbladerf' }
} }
//JMBE API is published as a GitHub release. It holds only the codec interfaces; users create the JMBE codec
//library itself with the JMBE creator, which sdrtrunk downloads from the release matching the API major version
ivy {
url = 'https://github.com/DSheirer/jmbe/releases/download'
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'jmbe-api' }
}
//radio-reference-api is published as a GitHub release. Its dependencies (jackson-dataformat-xml, slf4j-api) //radio-reference-api is published as a GitHub release. Its dependencies (jackson-dataformat-xml, slf4j-api)
//are not pulled in transitively and are declared directly in build.gradle //are not pulled in transitively and are declared directly in build.gradle
ivy { ivy {

View File

@@ -0,0 +1,81 @@
/*
* *****************************************************************************
* 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 com.sun.java.swing.plaf.windows;
import javax.swing.LookAndFeel;
import javax.swing.UIDefaults;
/**
* No-op stub for the JDK's Windows look-and-feel.
*
* <p>JIDE 3.6.18's {@code LookAndFeelFactory} contains compile-time
* {@code instanceof com.sun.java.swing.plaf.windows.WindowsLookAndFeel} checks throughout its
* dispatch logic. On Linux and macOS JDK builds that class is genuinely absent from
* {@code java.desktop}, so the JVM throws {@link NoClassDefFoundError} the first time JIDE's
* dispatch code executes the {@code instanceof} bytecode. That happens during
* {@link com.jidesoft.swing.JideSplitPane#updateUI()} on every LAF change.
*
* <p>This stub lives in the classpath so the class reference resolves on non-Windows JDKs.
* On Windows JDK builds the real {@code WindowsLookAndFeel} is loaded from the
* {@code java.desktop} module via the boot class loader and shadows this class.
*
* <p>The stub reports itself as not native and not supported - JIDE never instantiates this
* class, it only uses it for {@code instanceof} comparisons against the active LAF. Since
* sdrtrunk never installs this LAF, the {@code instanceof} check always returns false and
* JIDE proceeds to its next branch.
*/
public class WindowsLookAndFeel extends LookAndFeel
{
@Override
public String getName()
{
return "Windows (stub)";
}
@Override
public String getID()
{
return "WindowsStub";
}
@Override
public String getDescription()
{
return "Compatibility stub for JIDE's instanceof checks on non-Windows JDKs.";
}
@Override
public boolean isNativeLookAndFeel()
{
return false;
}
@Override
public boolean isSupportedLookAndFeel()
{
return false;
}
@Override
public UIDefaults getDefaults()
{
return new UIDefaults();
}
}

View File

@@ -530,34 +530,6 @@ public class AliasList
return Collections.emptyList(); return Collections.emptyList();
} }
/**
* Alias for a talkgroup that is identified by its stored values instead of an identifier instance, for example a
* talkgroup from the call database.
* @param protocol of the talkgroup
* @param value of the talkgroup
* @param fullyQualifiedAddress (wacn.system.id) of a fully qualified talkgroup, or null
* @return alias or null
*/
public Alias getTalkgroupAlias(Protocol protocol, int value, String fullyQualifiedAddress)
{
TalkgroupAliasList talkgroupAliasList = protocol != null ? mTalkgroupProtocolMap.get(protocol) : null;
return talkgroupAliasList != null ? talkgroupAliasList.getAlias(value, fullyQualifiedAddress) : null;
}
/**
* Alias for a radio that is identified by its stored values instead of an identifier instance, for example a
* radio from the call database.
* @param protocol of the radio
* @param value of the radio
* @param fullyQualifiedAddress (wacn.system.id) of a fully qualified radio, or null
* @return alias or null
*/
public Alias getRadioAlias(Protocol protocol, int value, String fullyQualifiedAddress)
{
RadioAliasList radioAliasList = protocol != null ? mRadioProtocolMap.get(protocol) : null;
return radioAliasList != null ? radioAliasList.getAlias(value, fullyQualifiedAddress) : null;
}
private static List<Alias> toList(Alias alias) private static List<Alias> toList(Alias alias)
{ {
if(alias != null) if(alias != null)
@@ -698,26 +670,11 @@ public class AliasList
//Attempt to do a fully qualified identifier match only //Attempt to do a fully qualified identifier match only
if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti) if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti)
{ {
return getAlias(fqti.getValue(), fqti.getFullyQualifiedTalkgroupAddress()); return mFullyQualifiedTalkgroupAliasMap.get(fqti.getFullyQualifiedTalkgroupAddress());
}
return getAlias(identifier.getValue(), null);
}
/**
* Alias for a talkgroup value, or for a fully qualified talkgroup address.
* @param value of the talkgroup
* @param fullyQualifiedAddress (wacn.system.id) for a fully qualified talkgroup, which is matched exclusively,
* or null.
*/
public Alias getAlias(int value, String fullyQualifiedAddress)
{
if(fullyQualifiedAddress != null)
{
return mFullyQualifiedTalkgroupAliasMap.get(fullyQualifiedAddress);
} }
//Attempt to match the talkgroup value //Attempt to match the talkgroup value
int value = identifier.getValue();
Alias mapValue = mTalkgroupAliasMap.get(value); Alias mapValue = mTalkgroupAliasMap.get(value);
if (mapValue != null) if (mapValue != null)
@@ -833,26 +790,11 @@ public class AliasList
//Match fully qualified identifier only. //Match fully qualified identifier only.
if(identifier instanceof FullyQualifiedRadioIdentifier fqri) if(identifier instanceof FullyQualifiedRadioIdentifier fqri)
{ {
return getAlias(fqri.getValue(), fqri.getFullyQualifiedRadioAddress()); return mFullyQualifiedRadioAliasMap.get(fqri.getFullyQualifiedRadioAddress());
}
return getAlias(identifier.getValue(), null);
}
/**
* Alias for a radio value, or for a fully qualified radio address.
* @param value of the radio
* @param fullyQualifiedAddress (wacn.system.id) for a fully qualified radio, which is matched exclusively, or
* null.
*/
public Alias getAlias(int value, String fullyQualifiedAddress)
{
if(fullyQualifiedAddress != null)
{
return mFullyQualifiedRadioAliasMap.get(fullyQualifiedAddress);
} }
//Attempt to match against the radio identifier //Attempt to match against the radio identifier
int value = identifier.getValue();
Alias mapValue = mRadioAliasMap.get(value); Alias mapValue = mRadioAliasMap.get(value);
if(mapValue != null) if(mapValue != null)

View File

@@ -1,269 +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.alias;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.util.Callback;
/**
* Persisted settings for an alias list. Alias lists are otherwise identified only by the list name that each alias
* carries, so settings that belong to the list itself, like tracking a Radio Reference system, are stored here and
* saved in the playlist.
*
* Radio Reference tracking uses two timestamps from the Radio Reference system's last updated value: the last updated
* value seen by the most recent check, and the last updated value that the aliases were synchronized to. When the
* seen value is newer than the synchronized value, the system changed on Radio Reference and the aliases haven't
* been updated yet.
*/
public class AliasListConfiguration
{
public static final int NO_SYSTEM = 0;
private StringProperty mName = new SimpleStringProperty();
private IntegerProperty mRadioReferenceSystemId = new SimpleIntegerProperty(NO_SYSTEM);
private StringProperty mRadioReferenceSystemName = new SimpleStringProperty();
private BooleanProperty mAutoUpdate = new SimpleBooleanProperty();
private LongProperty mRadioReferenceLastUpdated = new SimpleLongProperty();
private LongProperty mSynchronizedLastUpdated = new SimpleLongProperty();
private LongProperty mLastChecked = new SimpleLongProperty();
/**
* Jackson constructor
*/
public AliasListConfiguration()
{
}
/**
* Constructs an instance
* @param name of the alias list
*/
public AliasListConfiguration(String name)
{
setName(name);
}
/**
* Extractor so that observable lists of configurations report changes to the persisted properties.
*/
public static Callback<AliasListConfiguration,Observable[]> extractor()
{
return (AliasListConfiguration c) -> new Observable[] {c.mName, c.mRadioReferenceSystemId,
c.mRadioReferenceSystemName, c.mAutoUpdate, c.mRadioReferenceLastUpdated, c.mSynchronizedLastUpdated,
c.mLastChecked};
}
/**
* Alias list name
*/
@JacksonXmlProperty(isAttribute = true, localName = "name")
public String getName()
{
return mName.get();
}
public void setName(String name)
{
mName.set(name);
}
@JsonIgnore
public StringProperty nameProperty()
{
return mName;
}
/**
* Indicates if this alias list tracks a Radio Reference system.
*/
@JsonIgnore
public boolean isTrackingRadioReferenceSystem()
{
return getRadioReferenceSystemId() > NO_SYSTEM;
}
/**
* Indicates if this alias list tracks the specified Radio Reference system.
*/
public boolean isTracking(int systemId)
{
return systemId > NO_SYSTEM && getRadioReferenceSystemId() == systemId;
}
/**
* Radio Reference system ID tracked by this alias list, or NO_SYSTEM (0).
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_system_id")
public int getRadioReferenceSystemId()
{
return mRadioReferenceSystemId.get();
}
public void setRadioReferenceSystemId(int systemId)
{
mRadioReferenceSystemId.set(systemId);
}
@JsonIgnore
public IntegerProperty radioReferenceSystemIdProperty()
{
return mRadioReferenceSystemId;
}
/**
* Radio Reference system name, for display.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_system_name")
public String getRadioReferenceSystemName()
{
return mRadioReferenceSystemName.get();
}
public void setRadioReferenceSystemName(String name)
{
mRadioReferenceSystemName.set(name);
}
@JsonIgnore
public StringProperty radioReferenceSystemNameProperty()
{
return mRadioReferenceSystemName;
}
/**
* Indicates if talkgroups are automatically added or updated as aliases when the system changes on Radio Reference.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_auto_update")
public boolean isAutoUpdate()
{
return mAutoUpdate.get();
}
public void setAutoUpdate(boolean autoUpdate)
{
mAutoUpdate.set(autoUpdate);
}
@JsonIgnore
public BooleanProperty autoUpdateProperty()
{
return mAutoUpdate;
}
/**
* Radio Reference last updated timestamp (ms since epoch) for the system, as seen by the most recent check.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_last_updated")
public long getRadioReferenceLastUpdated()
{
return mRadioReferenceLastUpdated.get();
}
public void setRadioReferenceLastUpdated(long timestamp)
{
mRadioReferenceLastUpdated.set(timestamp);
}
@JsonIgnore
public LongProperty radioReferenceLastUpdatedProperty()
{
return mRadioReferenceLastUpdated;
}
/**
* Radio Reference last updated timestamp (ms since epoch) that the aliases were last synchronized to.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_synchronized")
public long getSynchronizedLastUpdated()
{
return mSynchronizedLastUpdated.get();
}
public void setSynchronizedLastUpdated(long timestamp)
{
mSynchronizedLastUpdated.set(timestamp);
}
@JsonIgnore
public LongProperty synchronizedLastUpdatedProperty()
{
return mSynchronizedLastUpdated;
}
/**
* Time (ms since epoch) of the most recent successful check of the system on Radio Reference.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_last_checked")
public long getLastChecked()
{
return mLastChecked.get();
}
public void setLastChecked(long timestamp)
{
mLastChecked.set(timestamp);
}
@JsonIgnore
public LongProperty lastCheckedProperty()
{
return mLastChecked;
}
/**
* Indicates if the most recent check saw a system change on Radio Reference that the aliases don't include yet.
*/
@JsonIgnore
public boolean isUpdateAvailable()
{
return isTrackingRadioReferenceSystem() && getRadioReferenceLastUpdated() > getSynchronizedLastUpdated();
}
/**
* Starts tracking the Radio Reference system. Clears timestamps so that the next refresh synchronizes.
*/
public void track(int systemId, String systemName)
{
setRadioReferenceSystemId(systemId);
setRadioReferenceSystemName(systemName);
setRadioReferenceLastUpdated(0);
setSynchronizedLastUpdated(0);
setLastChecked(0);
}
/**
* Stops tracking any Radio Reference system.
*/
public void stopTracking()
{
track(NO_SYSTEM, null);
setAutoUpdate(false);
}
}

View File

@@ -46,8 +46,6 @@ public class AliasModel
private ObservableList<Alias> mAliases = FXCollections.observableArrayList(Alias.extractor()); private ObservableList<Alias> mAliases = FXCollections.observableArrayList(Alias.extractor());
private ObservableList<String> mAliasListNames = FXCollections.observableArrayList(); private ObservableList<String> mAliasListNames = FXCollections.observableArrayList();
private Map<String,AliasList> mAliasListMap = new HashMap<>(); private Map<String,AliasList> mAliasListMap = new HashMap<>();
private ObservableList<AliasListConfiguration> mAliasListConfigurations =
FXCollections.observableArrayList(AliasListConfiguration.extractor());
public AliasModel() public AliasModel()
{ {
@@ -65,99 +63,6 @@ public class AliasModel
return mAliasListNames; return mAliasListNames;
} }
/**
* Observable list of persisted alias list configurations. Only alias lists with settings, like Radio Reference
* system tracking, have a configuration.
*/
public ObservableList<AliasListConfiguration> aliasListConfigurations()
{
return mAliasListConfigurations;
}
/**
* Bulk loading of alias list configurations from a playlist. Ignores configurations without a name and
* duplicates of an earlier configuration's name.
*/
public void addAliasListConfigurations(List<AliasListConfiguration> configurations)
{
if(configurations != null)
{
for(AliasListConfiguration configuration: configurations)
{
String name = configuration.getName();
if(name != null && !name.isEmpty() && getAliasListConfiguration(name) == null)
{
mAliasListConfigurations.add(configuration);
addAliasList(name);
}
}
}
}
/**
* Configuration for the named alias list.
* @param aliasListName to find
* @return configuration or null if the alias list doesn't have one
*/
public AliasListConfiguration getAliasListConfiguration(String aliasListName)
{
if(aliasListName != null)
{
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(aliasListName.equals(configuration.getName()))
{
return configuration;
}
}
}
return null;
}
/**
* Configuration for the named alias list, created when the alias list doesn't have one.
* @param aliasListName for the configuration, not null or the (No Alias List) name
* @return configuration
*/
public AliasListConfiguration getOrCreateAliasListConfiguration(String aliasListName)
{
if(aliasListName == null || aliasListName.isEmpty() || aliasListName.equals(NO_ALIAS_LIST))
{
throw new IllegalArgumentException("Invalid alias list name [" + aliasListName + "]");
}
AliasListConfiguration configuration = getAliasListConfiguration(aliasListName);
if(configuration == null)
{
configuration = new AliasListConfiguration(aliasListName);
mAliasListConfigurations.add(configuration);
addAliasList(aliasListName);
}
return configuration;
}
/**
* Name of the first alias list that tracks the Radio Reference system.
* @param systemId of the Radio Reference system
* @return alias list name or null
*/
public String getAliasListNameTracking(int systemId)
{
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(configuration.isTracking(systemId))
{
return configuration.getName();
}
}
return null;
}
/** /**
* Clears and reloads the list of alias list names from the current set of aliases. * Clears and reloads the list of alias list names from the current set of aliases.
*/ */
@@ -174,15 +79,6 @@ public class AliasModel
mAliasListNames.add(aliasListName); mAliasListNames.add(aliasListName);
} }
} }
//Alias lists with a configuration exist even before they have any aliases
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(!mAliasListNames.contains(configuration.getName()))
{
mAliasListNames.add(configuration.getName());
}
}
} }
/** /**
@@ -197,22 +93,7 @@ public class AliasModel
return; return;
} }
mAliases.stream().filter(alias -> oldName.equals(alias.getAliasListName())).forEach(alias -> alias.setAliasListName(newName)); mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName));
AliasListConfiguration configuration = getAliasListConfiguration(oldName);
if(configuration != null)
{
//Merging into an existing list keeps that list's configuration
if(getAliasListConfiguration(newName) == null)
{
configuration.setName(newName);
}
else
{
mAliasListConfigurations.remove(configuration);
}
}
} }
/** /**
@@ -228,7 +109,6 @@ public class AliasModel
mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName)); mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
mAliasListMap.remove(aliasListName); mAliasListMap.remove(aliasListName);
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
} }
/** /**
@@ -266,7 +146,6 @@ public class AliasModel
removeAlias(alias); removeAlias(alias);
} }
mAliasListConfigurations.clear();
mAliasListNames.clear(); mAliasListNames.clear();
} }

View File

@@ -1,571 +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.alias;
import com.google.common.annotations.VisibleForTesting;
import io.github.dsheirer.alias.id.AliasID;
import io.github.dsheirer.alias.id.radio.NXDNTypeDRadio;
import io.github.dsheirer.alias.id.radio.P25FullyQualifiedRadio;
import io.github.dsheirer.alias.id.radio.Radio;
import io.github.dsheirer.identifier.alias.TalkerAliasIdentifier;
import io.github.dsheirer.identifier.radio.FullyQualifiedRadioIdentifier;
import io.github.dsheirer.identifier.radio.RadioIdentifier;
import io.github.dsheirer.module.decode.nxdn.identifier.NXDNRadioIdentifier;
import io.github.dsheirer.protocol.Protocol;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Automatically adds decoded talker aliases to an alias list as radio aliases, using the talker alias as the alias name,
* and renames a stored radio alias when the radio's talker alias changes.
*
* Talker aliases span up to 4 messages, so a decoded talker alias can be a fragment (the leading characters) of the
* full alias, even when the decoder reports it as complete. To avoid replacing a full alias with a fragment:
* <ul>
* <li>A decoded alias that is the start of the stored alias name is a fragment and never replaces it.</li>
* <li>A decoded alias that starts with the stored alias name is a longer version of a stored fragment and
* replaces it.</li>
* <li>Any other decoded alias that differs from the stored alias name replaces it only after it is decoded
* {@link #CONFIRMATIONS_REQUIRED} times in a row for the radio.</li>
* </ul>
*
* Only aliases whose only identifier is the radio are created or renamed. An alias that combines the radio with other
* identifiers (e.g. several radios or talkgroups) is left alone. The exception is a P25 radio's simple and fully
* qualified radio identifiers with the same radio ID: the second form decoded is added to the alias for the first
* form, including a user alias outside the managed group, instead of creating a second alias for the same radio.
*
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
* JavaFX application thread.
*/
public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAliasIdentifier>
{
private static final Logger mLog = LoggerFactory.getLogger(TalkerAliasAutoAdder.class);
/**
* Group assigned to aliases created from talker aliases.
*/
public static final String ALIAS_GROUP = "Talker Alias";
/**
* Number of consecutive times a different talker alias must be decoded for a radio before it replaces the stored
* alias name.
*/
public static final int CONFIRMATIONS_REQUIRED = 2;
/**
* Interval for re-checking the stored alias for a talker alias that was already checked, so that a renamed or
* deleted alias is restored without checking the alias list for every decoded talker alias.
*/
private static final long RECHECK_INTERVAL_MS = 30_000;
/**
* Outcome of comparing a decoded talker alias with the stored alias name.
*/
public enum Decision
{
/**
* The stored alias name matches the talker alias.
*/
UNCHANGED,
/**
* The talker alias is a fragment of the stored alias name.
*/
FRAGMENT,
/**
* The talker alias differs from the stored alias name and is waiting for more decodes.
*/
AWAIT_CONFIRMATION,
/**
* The talker alias replaces the stored alias name.
*/
UPDATE
}
private final AliasModel mAliasModel;
private final String mAliasListName;
//Guarded by this
private final Map<String,Candidate> mCandidates = new HashMap<>();
private final Map<String,Checked> mChecked = new HashMap<>();
/**
* Constructs an instance
* @param aliasModel to add aliases to
* @param aliasListName of the alias list to add aliases to
*/
public TalkerAliasAutoAdder(AliasModel aliasModel, String aliasListName)
{
mAliasModel = aliasModel;
mAliasListName = aliasListName;
}
/**
* Name of the alias list that talker aliases are added to.
*/
public String getAliasListName()
{
return mAliasListName;
}
/**
* Processes a talker alias that is assigned to a radio.
* @param radio that the talker alias belongs to
* @param talkerAlias for the radio
*/
@Override
public void accept(RadioIdentifier radio, TalkerAliasIdentifier talkerAlias)
{
if(radio == null || talkerAlias == null || mAliasListName == null || mAliasListName.isEmpty())
{
return;
}
String value = normalize(talkerAlias.getValue());
Radio aliasId = createAliasId(radio);
if(value == null || aliasId == null || !aliasId.isValid())
{
return;
}
String key = getKey(aliasId);
long now = System.currentTimeMillis();
int confirmations;
synchronized(this)
{
Checked checked = mChecked.get(key);
if(checked != null && checked.value().equals(value) && (now - checked.timestamp()) < RECHECK_INTERVAL_MS)
{
return;
}
confirmations = confirm(key, value);
}
runOnFxThread(() -> apply(radio, aliasId, key, value, confirmations));
}
/**
* Counts the consecutive decodes of the talker alias for the radio. A fragment of the talker alias that is
* waiting for confirmation doesn't interrupt the count, because fragments are decoded while the full alias is
* assembled.
* @return number of consecutive decodes of the value, including this one.
*/
private int confirm(String key, String value)
{
Candidate candidate = mCandidates.get(key);
if(candidate != null && candidate.value().equals(value))
{
candidate = new Candidate(value, candidate.count() + 1);
mCandidates.put(key, candidate);
return candidate.count();
}
if(candidate != null && isFragment(value, candidate.value()))
{
return 1;
}
mCandidates.put(key, new Candidate(value, 1));
return 1;
}
/**
* Creates or updates the alias for the radio. Runs on the JavaFX application thread.
*/
private synchronized void apply(RadioIdentifier radio, Radio aliasId, String key, String value, int confirmations)
{
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
Alias existing = findExactMatch(aliasList.getAliases(radio), aliasId);
if(existing == null)
{
existing = findCompanion(aliasList.aliases(), radio, aliasId);
if(existing != null)
{
//Add the radio to the alias for the same radio's other identifier form, then continue below to
//compare the talker alias with the alias name (only managed aliases are renamed).
existing.addAliasID(aliasId);
aliasList.updateAlias(existing);
mLog.info("Talker alias radio [" + aliasId + "] added to existing alias [" + existing.getName() +
"] in alias list [" + mAliasListName + "]");
}
}
if(existing == null)
{
Alias alias = new Alias(value);
alias.setAliasListName(mAliasListName);
alias.setGroup(ALIAS_GROUP);
alias.addAliasID(aliasId);
mAliasModel.addAlias(alias);
markChecked(key, value);
mLog.info("Talker alias [" + value + "] added for radio [" + aliasId + "] to alias list [" +
mAliasListName + "]");
return;
}
if(!ALIAS_GROUP.equals(existing.getGroup()))
{
//Only maintain aliases in the managed group. Existing user aliases must not be renamed or duplicated.
markChecked(key, value);
return;
}
if(getIdentityCount(existing) > 1)
{
//The alias also identifies other radios or talkgroups - leave it alone.
markChecked(key, value);
return;
}
String stored = normalize(existing.getName());
switch(decide(stored, value, confirmations))
{
case UPDATE:
existing.setName(value);
markChecked(key, value);
mLog.info("Talker alias for radio [" + aliasId + "] in alias list [" + mAliasListName +
"] changed from [" + stored + "] to [" + value + "]");
break;
case UNCHANGED:
case FRAGMENT:
markChecked(key, value);
break;
case AWAIT_CONFIRMATION:
default:
break;
}
}
private void markChecked(String key, String value)
{
mChecked.put(key, new Checked(value, System.currentTimeMillis()));
mCandidates.remove(key);
}
/**
* Compares the decoded talker alias with the stored alias name.
* @param stored alias name, normalized, or null
* @param decoded talker alias, normalized
* @param confirmations number of consecutive decodes of the talker alias
* @return decision
*/
@VisibleForTesting
static Decision decide(String stored, String decoded, int confirmations)
{
if(stored == null || stored.isEmpty())
{
return Decision.UPDATE;
}
if(stored.equals(decoded))
{
return Decision.UNCHANGED;
}
if(isFragment(decoded, stored))
{
return Decision.FRAGMENT;
}
//A longer version of a stored fragment.
if(isFragment(stored, decoded) && !hasUndecodableCharacters(decoded))
{
return Decision.UPDATE;
}
//A different alias that may be a corrupted or mis-assembled alias. It's replaced only once confirmed, and an
//alias that has undecodable characters (e.g. a partial multi-byte character) never replaces a stored alias.
if(confirmations >= CONFIRMATIONS_REQUIRED && !hasUndecodableCharacters(decoded))
{
return Decision.UPDATE;
}
return Decision.AWAIT_CONFIRMATION;
}
/**
* Indicates if the value is a fragment (the leading characters) of the full value.
*/
@VisibleForTesting
static boolean isFragment(String value, String full)
{
return value != null && full != null && value.length() < full.length() && full.startsWith(value);
}
private static boolean hasUndecodableCharacters(String value)
{
return value.indexOf('<27>') >= 0;
}
/**
* Removes padding, control characters and trailing undecodable characters (e.g. from a partial multi-byte
* character at the end of an alias fragment) from the talker alias.
* @param value to normalize
* @return normalized value or null if the value is empty.
*/
@VisibleForTesting
static String normalize(String value)
{
if(value == null)
{
return null;
}
StringBuilder sb = new StringBuilder(value.length());
for(int i = 0; i < value.length(); i++)
{
char c = value.charAt(i);
if(!Character.isISOControl(c))
{
sb.append(c);
}
}
int end = sb.length();
while(end > 0 && (sb.charAt(end - 1) == '<27>' || Character.isWhitespace(sb.charAt(end - 1))))
{
end--;
}
String normalized = sb.substring(0, end).trim();
return normalized.isEmpty() ? null : normalized;
}
/**
* Creates a radio alias identifier that exactly matches the radio.
* @param radio identifier
* @return alias identifier or null if the radio protocol isn't known.
*/
@VisibleForTesting
static Radio createAliasId(RadioIdentifier radio)
{
if(radio instanceof FullyQualifiedRadioIdentifier fqri && fqri.getProtocol() == Protocol.APCO25)
{
return new P25FullyQualifiedRadio(fqri.getWacn(), fqri.getSystem(), fqri.getRadio());
}
if(radio instanceof NXDNRadioIdentifier nxdn && nxdn.isTypeD())
{
return new NXDNTypeDRadio(nxdn.getTypeDHomeRepeater(), nxdn.getTypeDRadio());
}
Protocol protocol = radio.getProtocol();
if(protocol == null || protocol == Protocol.UNKNOWN || radio.getValue() == null)
{
return null;
}
return new Radio(protocol, radio.getValue());
}
/**
* Finds the alias that has an identifier that exactly matches the radio (i.e. not a radio range).
*/
@VisibleForTesting
static Alias findExactMatch(List<Alias> aliases, Radio aliasId)
{
if(aliases != null)
{
for(Alias alias: aliases)
{
for(AliasID id: alias.getAliasIdentifiers())
{
if(isExactMatch(id, aliasId))
{
return alias;
}
}
}
}
return null;
}
private static boolean isExactMatch(AliasID id, Radio aliasId)
{
if(aliasId instanceof P25FullyQualifiedRadio target)
{
return id instanceof P25FullyQualifiedRadio fqr && fqr.getHashKey().equals(target.getHashKey());
}
return id instanceof Radio radio && !(id instanceof P25FullyQualifiedRadio) &&
radio.getProtocol() == aliasId.getProtocol() && radio.getValue() == aliasId.getValue();
}
/**
* Finds the alias for the other identifier form of a P25 radio, so that a radio's simple and fully qualified
* identifiers share one alias instead of creating an alias for each. This includes user aliases outside the
* managed group, so that either identifier maps to the user's alias. The user alias is never renamed.
* <ul>
* <li>Fully qualified radio: the alias whose only identifier is the simple radio with the same radio
* ID. Only when the fully qualified radio isn't using a different local address (e.g. a roaming radio), since
* the radio ID then belongs to the home system and doesn't identify the radio on this system.</li>
* <li>Simple radio: the alias whose only identifier is a fully qualified radio with the same radio ID. None
* when more than one fully qualified radio alias matches.</li>
* </ul>
* @param aliases to search
* @param radio decoded radio identifier
* @param aliasId created from the decoded radio
* @return companion alias or null.
*/
@VisibleForTesting
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
{
if(aliases == null || aliasId.getProtocol() != Protocol.APCO25)
{
return null;
}
boolean fullyQualified = aliasId instanceof P25FullyQualifiedRadio;
if(fullyQualified && !(radio instanceof FullyQualifiedRadioIdentifier fqri &&
fqri.getValue() != null && fqri.getValue() == fqri.getRadio()))
{
return null;
}
Alias match = null;
for(Alias alias: aliases)
{
if(getSoleIdentity(alias) instanceof Radio candidate &&
(candidate instanceof P25FullyQualifiedRadio) != fullyQualified &&
candidate.getProtocol() == Protocol.APCO25 && candidate.getValue() == aliasId.getValue())
{
if(match != null)
{
//Ambiguous - more than one candidate.
return null;
}
match = alias;
}
}
return match;
}
/**
* Identifier of an alias that has exactly one identifier, excluding audio settings.
* @return identifier or null if the alias has none or more than one.
*/
private static AliasID getSoleIdentity(Alias alias)
{
AliasID sole = null;
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isAudioIdentifier())
{
if(sole != null)
{
return null;
}
sole = id;
}
}
return sole;
}
/**
* Number of identities (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming. A P25 radio's simple and fully qualified radio identifiers with the same radio ID count as one
* identity.
*/
private static int getIdentityCount(Alias alias)
{
List<AliasID> ids = alias.getAliasIdentifiers().stream().filter(id -> !id.isAudioIdentifier()).toList();
if(ids.size() == 2 && isRadioPair(ids.get(0), ids.get(1)))
{
return 1;
}
return ids.size();
}
/**
* Indicates if the identifiers are the simple and fully qualified forms of the same P25 radio ID.
*/
private static boolean isRadioPair(AliasID a, AliasID b)
{
if(a instanceof P25FullyQualifiedRadio)
{
AliasID swap = a;
a = b;
b = swap;
}
return a instanceof Radio simple && !(a instanceof P25FullyQualifiedRadio) &&
b instanceof P25FullyQualifiedRadio fqr && simple.getProtocol() == Protocol.APCO25 &&
simple.getValue() == fqr.getValue();
}
private static String getKey(Radio aliasId)
{
if(aliasId instanceof P25FullyQualifiedRadio fqr)
{
return aliasId.getProtocol() + ":" + fqr.getHashKey();
}
return aliasId.getProtocol() + ":" + aliasId.getValue();
}
/**
* Runs on the FX thread, or on this thread when the FX toolkit isn't running (headless).
*/
private static void runOnFxThread(Runnable runnable)
{
if(Platform.isFxApplicationThread())
{
runnable.run();
return;
}
try
{
Platform.runLater(runnable);
}
catch(IllegalStateException ise)
{
runnable.run();
}
}
private record Candidate(String value, int count) {}
private record Checked(String value, long timestamp) {}
}

View File

@@ -19,16 +19,14 @@
package io.github.dsheirer.alias.action; package io.github.dsheirer.alias.action;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.alias.Alias; import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.message.IMessage; import io.github.dsheirer.message.IMessage;
import io.github.dsheirer.util.ThreadPool; import io.github.dsheirer.util.ThreadPool;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@@ -64,28 +62,23 @@ public abstract class RecurringAction extends AliasAction
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate( mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS); new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS);
String text = "Alias [" + alias.getName() + "] is active in message [" + message + "]"; StringBuilder sb = new StringBuilder();
sb.append("<html><div width='250'>Alias [");
sb.append(alias.getName());
sb.append("] is active in message [");
sb.append(message.toString());
sb.append("]</div></html>");
final String text = sb.toString();
EventQueue.invokeLater(() -> {
JOptionPane.showMessageDialog(null, text,
"Alias Alert", JOptionPane.INFORMATION_MESSAGE);
Runnable dismissed = () -> {
dismiss(false); dismiss(false);
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
};
if(FxToolkit.isStarted()) ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
{ });
//The action repeats until the user closes the alert
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION, text);
alert.setTitle("Alias Alert");
alert.setHeaderText(null);
alert.setOnHidden(event -> dismissed.run());
alert.show();
});
}
else
{
dismissed.run();
}
break; break;
default: default:
} }

View File

@@ -31,8 +31,6 @@ public class AudioEvent
AUDIO_STOPPED, AUDIO_STOPPED,
AUDIO_CONTINUATION, AUDIO_CONTINUATION,
AUDIO_CONFIGURATION_CHANGE_STARTED, AUDIO_CONFIGURATION_CHANGE_STARTED,
AUDIO_CONFIGURATION_CHANGE_COMPLETE, AUDIO_CONFIGURATION_CHANGE_COMPLETE;
REPLAY_STARTED,
REPLAY_STOPPED;
} }
} }

View File

@@ -38,7 +38,6 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javafx.beans.property.BooleanProperty; import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty; import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleBooleanProperty;
@@ -68,8 +67,6 @@ import org.slf4j.LoggerFactory;
public class AudioSegment implements Listener<IdentifierUpdateNotification> public class AudioSegment implements Listener<IdentifierUpdateNotification>
{ {
private final static Logger mLog = LoggerFactory.getLogger(AudioSegment.class); private final static Logger mLog = LoggerFactory.getLogger(AudioSegment.class);
private static final AtomicLong ID_GENERATOR = new AtomicLong();
private final long mId = ID_GENERATOR.incrementAndGet();
private BooleanProperty mComplete = new SimpleBooleanProperty(false); private BooleanProperty mComplete = new SimpleBooleanProperty(false);
private BooleanProperty mDuplicate = new SimpleBooleanProperty(false); private BooleanProperty mDuplicate = new SimpleBooleanProperty(false);
private BooleanProperty mEncrypted = new SimpleBooleanProperty(false); private BooleanProperty mEncrypted = new SimpleBooleanProperty(false);
@@ -99,15 +96,6 @@ public class AudioSegment implements Listener<IdentifierUpdateNotification>
mIdentifierCollection.setTimeslot(timeslot); mIdentifierCollection.setTimeslot(timeslot);
} }
/**
* Unique identifier of this audio segment for the current application session. The call manager uses it as the
* call key, which links a call that is playing on an audio channel to the call in the Calls tab.
*/
public long getId()
{
return mId;
}
/** /**
* Timeslot for this audio segment * Timeslot for this audio segment
*/ */

View File

@@ -46,8 +46,9 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel;
public class BroadcastModel implements Listener<AudioRecording> public class BroadcastModel extends AbstractTableModel implements Listener<AudioRecording>
{ {
private final static Logger mLog = LoggerFactory.getLogger(BroadcastModel.class); private final static Logger mLog = LoggerFactory.getLogger(BroadcastModel.class);
@@ -56,6 +57,18 @@ public class BroadcastModel implements Listener<AudioRecording>
private static final String UNIQUE_NAME_REGEX = "(.*)\\((\\d*)\\)"; private static final String UNIQUE_NAME_REGEX = "(.*)\\((\\d*)\\)";
public static final int COLUMN_BROADCAST_SERVER_TYPE = 0;
public static final int COLUMN_STREAM_NAME = 1;
public static final int COLUMN_BROADCASTER_STATUS = 2;
public static final int COLUMN_BROADCASTER_QUEUE_SIZE = 3;
public static final int COLUMN_BROADCASTER_STREAMED_COUNT = 4;
public static final int COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT = 5;
public static final int COLUMN_BROADCASTER_AGED_OFF_COUNT = 6;
public static final int COLUMN_BROADCASTER_ERROR_COUNT = 7;
public static final String[] COLUMN_NAMES = new String[]
{"Stream Type", "Name", "Status", "Queued", "Streamed/Uploaded", "Duplicate Rejected", "Aged Off", "Upload Error"};
private ObservableList<ConfiguredBroadcast> mConfiguredBroadcasts = private ObservableList<ConfiguredBroadcast> mConfiguredBroadcasts =
FXCollections.observableArrayList(ConfiguredBroadcast.extractor()); FXCollections.observableArrayList(ConfiguredBroadcast.extractor());
private List<AudioRecording> mRecordingQueue = new CopyOnWriteArrayList<>(); private List<AudioRecording> mRecordingQueue = new CopyOnWriteArrayList<>();
@@ -158,6 +171,8 @@ public class BroadcastModel implements Listener<AudioRecording>
{ {
configuredBroadcast = new ConfiguredBroadcast(configuration); configuredBroadcast = new ConfiguredBroadcast(configuration);
mConfiguredBroadcasts.add(configuredBroadcast); mConfiguredBroadcasts.add(configuredBroadcast);
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
fireTableRowsInserted(index, index);
process(new BroadcastEvent(configuration, BroadcastEvent.Event.CONFIGURATION_ADD)); process(new BroadcastEvent(configuration, BroadcastEvent.Event.CONFIGURATION_ADD));
return configuredBroadcast; return configuredBroadcast;
} }
@@ -259,6 +274,8 @@ public class BroadcastModel implements Listener<AudioRecording>
if(configuredBroadcast != null) if(configuredBroadcast != null)
{ {
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
mConfiguredBroadcasts.remove(configuredBroadcast); mConfiguredBroadcasts.remove(configuredBroadcast);
if(configuredBroadcast.hasAudioBroadcaster()) if(configuredBroadcast.hasAudioBroadcaster())
@@ -269,6 +286,8 @@ public class BroadcastModel implements Listener<AudioRecording>
} }
process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE)); process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE));
fireTableRowsDeleted(index, index);
} }
} }
@@ -335,6 +354,13 @@ public class BroadcastModel implements Listener<AudioRecording>
audioBroadcaster.setListener(mBroadcastEventListener); audioBroadcaster.setListener(mBroadcastEventListener);
mBroadcasterMap.put(audioBroadcaster.getBroadcastConfiguration().getId(), audioBroadcaster); mBroadcasterMap.put(audioBroadcaster.getBroadcastConfiguration().getId(), audioBroadcaster);
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(audioBroadcaster, BroadcastEvent.Event.BROADCASTER_ADD)); broadcast(new BroadcastEvent(audioBroadcaster, BroadcastEvent.Event.BROADCASTER_ADD));
ThreadPool.CACHED.submit(() -> audioBroadcaster.start()); ThreadPool.CACHED.submit(() -> audioBroadcaster.start());
} }
@@ -357,6 +383,13 @@ public class BroadcastModel implements Listener<AudioRecording>
broadcaster.removeListener(); broadcaster.removeListener();
broadcaster.dispose(); broadcaster.dispose();
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE)); broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE));
} }
} }
@@ -465,17 +498,186 @@ public class BroadcastModel implements Listener<AudioRecording>
ThreadPool.SCHEDULED.schedule(new DelayedBroadcasterStartup(broadcastConfiguration), ThreadPool.SCHEDULED.schedule(new DelayedBroadcasterStartup(broadcastConfiguration),
1, TimeUnit.SECONDS); 1, TimeUnit.SECONDS);
} }
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
fireTableRowsUpdated(index, index);
break; break;
case CONFIGURATION_DELETE: case CONFIGURATION_DELETE:
deleteBroadcaster(getConfiguredBroadcast(broadcastEvent.getBroadcastConfiguration())); deleteBroadcaster(getConfiguredBroadcast(broadcastEvent.getBroadcastConfiguration()));
break; break;
} }
} }
else if(broadcastEvent.isAudioBroadcasterEvent())
{
ConfiguredBroadcast configuredBroadcast = getConfiguredBroadcast(broadcastEvent.getAudioBroadcaster());
int row = mConfiguredBroadcasts.indexOf(configuredBroadcast);
switch(broadcastEvent.getEvent())
{
case BROADCASTER_QUEUE_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_QUEUE_SIZE);
}
break;
case BROADCASTER_STATE_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_STATUS);
}
break;
case BROADCASTER_STREAMED_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_STREAMED_COUNT);
}
break;
case BROADCASTER_DUPLICATE_REJECTED_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT);
}
break;
case BROADCASTER_AGED_OFF_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_AGED_OFF_COUNT);
}
case BROADCASTER_ERROR_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_ERROR_COUNT);
}
break;
}
}
//Rebroadcast the event to any listeners of this model //Rebroadcast the event to any listeners of this model
broadcast(broadcastEvent); broadcast(broadcastEvent);
} }
@Override
public int getRowCount()
{
return mConfiguredBroadcasts.size();
}
@Override
public int getColumnCount()
{
return COLUMN_NAMES.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
try
{
if(rowIndex <= mConfiguredBroadcasts.size())
{
ConfiguredBroadcast configuredBroadcast = mConfiguredBroadcasts.get(rowIndex);
if(configuredBroadcast != null)
{
switch(columnIndex)
{
case COLUMN_BROADCAST_SERVER_TYPE:
return configuredBroadcast.getBroadcastServerType();
case COLUMN_STREAM_NAME:
return configuredBroadcast.getBroadcastConfiguration().getName();
case COLUMN_BROADCASTER_STATUS:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getBroadcastState();
}
else if(!configuredBroadcast.getBroadcastConfiguration().isEnabled())
{
return BroadcastState.DISABLED;
}
else if(!configuredBroadcast.getBroadcastConfiguration().isValid())
{
return BroadcastState.INVALID_SETTINGS;
}
else
{
return BroadcastState.ERROR;
}
case COLUMN_BROADCASTER_QUEUE_SIZE:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getAudioQueueSize();
}
break;
case COLUMN_BROADCASTER_STREAMED_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getStreamedAudioCount();
}
break;
case COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getDuplicateRejectedAudioCount();
}
break;
case COLUMN_BROADCASTER_AGED_OFF_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getAgedOffAudioCount();
}
break;
case COLUMN_BROADCASTER_ERROR_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getAudioErrorCount();
}
break;
default:
break;
}
}
}
}
catch(Exception e)
{
mLog.error("Error accessing data in broadcast model", e);
}
return null;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch(columnIndex)
{
case COLUMN_BROADCASTER_STATUS:
return BroadcastState.class;
case COLUMN_BROADCASTER_AGED_OFF_COUNT:
case COLUMN_BROADCASTER_QUEUE_SIZE:
case COLUMN_BROADCASTER_STREAMED_COUNT:
case COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT:
case COLUMN_BROADCASTER_ERROR_COUNT:
return Integer.class;
case COLUMN_BROADCAST_SERVER_TYPE:
return BroadcastServerType.class;
case COLUMN_STREAM_NAME:
default:
return String.class;
}
}
@Override
public String getColumnName(int column)
{
if(0 <= column && column < COLUMN_NAMES.length)
{
return COLUMN_NAMES[column];
}
return null;
}
/** /**
* Cleanup method to remove a temporary recording file from disk. * Cleanup method to remove a temporary recording file from disk.
* *

View File

@@ -0,0 +1,186 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 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.audio.broadcast;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
import java.awt.Color;
import java.awt.Component;
import net.miginfocom.swing.MigLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
/**
* Table of broadcast streams and statuses.
*/
public class BroadcastStatusPanel extends JPanel
{
private JTable mTable;
private JTableColumnWidthMonitor mColumnWidthMonitor;
private JScrollPane mScrollPane;
private BroadcastModel mBroadcastModel;
private UserPreferences mUserPreferences;
private String mPreferenceKey;
/**
* Constructs an instance
* @param broadcastModel to access the streams
* @param userPreferences for configuring the panel
* @param preferenceKey to store column preferences for this panel.
*/
public BroadcastStatusPanel(BroadcastModel broadcastModel, UserPreferences userPreferences, String preferenceKey)
{
mBroadcastModel = broadcastModel;
mUserPreferences = userPreferences;
mPreferenceKey = preferenceKey;
init();
}
public JTable getTable()
{
return mTable;
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));
mTable = new JTable(mBroadcastModel);
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)mTable.getDefaultRenderer(String.class);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCASTER_STATUS).setCellRenderer(new StatusCellRenderer());
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCAST_SERVER_TYPE).setCellRenderer(new ServerTypeRenderer());
mColumnWidthMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTable, mPreferenceKey);
mScrollPane = new JScrollPane(mTable);
add(mScrollPane);
}
public class ServerTypeRenderer extends DefaultTableCellRenderer
{
public ServerTypeRenderer()
{
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof BroadcastServerType broadcastServerType)
{
component.setText(broadcastServerType.toString());
Icon icon = new Icon("empty", broadcastServerType.getIconPath());
ImageIcon imageIcon = icon.getIcon();
ImageIcon scaledIcon = IconModel.getScaledIcon(imageIcon, 13);
component.setIcon(scaledIcon);
}
else
{
component.setText(null);
component.setIcon(null);
}
return component;
}
}
/**
* Custom cell renderer for the broadcast state column.
*/
public class StatusCellRenderer extends DefaultTableCellRenderer
{
public StatusCellRenderer()
{
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected)
{
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
else
{
if(value instanceof BroadcastState)
{
BroadcastState state = (BroadcastState)value;
if(state == BroadcastState.CONNECTED)
{
setBackground(Color.GREEN);
setForeground(table.getForeground());
}
else if(state == BroadcastState.DISABLED)
{
setBackground(table.getBackground());
//Use the LAF's disabled-foreground so the cell reads correctly on any
//theme - LIGHT_GRAY is invisible on a light background.
Color disabled = javax.swing.UIManager.getColor("Label.disabledForeground");
setForeground(disabled != null ? disabled : table.getForeground());
}
else if(state == BroadcastState.INVALID_SETTINGS ||
state == BroadcastState.NETWORK_UNAVAILABLE)
{
setBackground(Color.YELLOW);
setForeground(table.getForeground());
}
else if(state.isErrorState())
{
setBackground(Color.RED);
setForeground(table.getForeground());
}
else
{
setBackground(table.getBackground());
setForeground(table.getForeground());
}
}
else
{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
return this;
}
}
}

View File

@@ -151,30 +151,6 @@ public class ConfiguredBroadcast
return mAudioBroadcaster != null; return mAudioBroadcaster != null;
} }
/**
* Current status for display: the broadcaster's state when there is a broadcaster, otherwise the reason that
* there isn't one.
*/
public BroadcastState getStatus()
{
AbstractAudioBroadcaster broadcaster = mAudioBroadcaster;
if(broadcaster != null)
{
return broadcaster.getBroadcastState();
}
else if(!mBroadcastConfiguration.isEnabled())
{
return BroadcastState.DISABLED;
}
else if(!mBroadcastConfiguration.isValid())
{
return BroadcastState.INVALID_SETTINGS;
}
return BroadcastState.ERROR;
}
/** /**
* Creates an observable property extractor for use with observable lists to detect changes internal to this object. * Creates an observable property extractor for use with observable lists to detect changes internal to this object.
*/ */

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -37,14 +37,10 @@ import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import jmbe.frame.ICorrectedFrame;
import jmbe.iface.IAudioCodec; import jmbe.iface.IAudioCodec;
import jmbe.iface.IAudioCodecLibrary; import jmbe.iface.IAudioCodecLibrary;
import jmbe.iface.IAudioCodecLibraryV2; import jmbe.iface.IAudioCodecLibraryV2;
import jmbe.iface.IAudioCodecLibraryV3;
import jmbe.iface.IAudioCodecV2; import jmbe.iface.IAudioCodecV2;
import jmbe.iface.IAudioCodecV3;
import jmbe.iface.IAudioWithMetadata;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -56,13 +52,6 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
{ {
private static final Logger LOG = LoggerFactory.getLogger(JmbeAudioModule.class); private static final Logger LOG = LoggerFactory.getLogger(JmbeAudioModule.class);
private static final String JMBE_AUDIO_LIBRARY = "JMBE"; private static final String JMBE_AUDIO_LIBRARY = "JMBE";
/**
* JMBE library entry point class names, newest first. The loader uses the newest version that the library
* provides, falling back to older versions for libraries created by older JMBE releases.
*/
private static final List<String> JMBE_LIBRARY_CLASS_NAMES = List.of("jmbe.JMBEAudioLibraryV3",
"jmbe.JMBEAudioLibraryV2", "jmbe.JMBEAudioLibrary");
private static final List<String> mLibraryLoadStatusLogged = new ArrayList<>(); private static final List<String> mLibraryLoadStatusLogged = new ArrayList<>();
private IAudioCodec mAudioCodec; private IAudioCodec mAudioCodec;
private final UserPreferences mUserPreferences; private final UserPreferences mUserPreferences;
@@ -139,56 +128,6 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
return getAudioCodec() != null; return getAudioCodec() != null;
} }
/**
* Indicates if the loaded audio codec can synthesize audio from a voice frame that sdrtrunk has already error
* corrected. Only JMBE version 3 libraries support this. Version 1 and 2 libraries only accept the raw voice
* frame bytes and perform the error detection and correction themselves.
*
* Callers can use this to skip creating corrected frames when the codec can't use them.
*/
protected boolean isCorrectedFrameSupported()
{
return mAudioCodec instanceof IAudioCodecV3;
}
/**
* Synthesizes audio for the voice frame. When the codec supports it (JMBE version 3), the audio is synthesized
* from the corrected frame so the codec doesn't repeat the error detection and correction. Otherwise, the raw
* frame bytes are passed to the codec (JMBE version 1 and 2).
*
* @param frame bytes for the voice frame as transmitted
* @param correctedFrame for the same voice frame, or null to let the codec perform the error correction
* @return audio samples
*/
protected float[] getAudio(byte[] frame, ICorrectedFrame correctedFrame)
{
if(correctedFrame != null && mAudioCodec instanceof IAudioCodecV3 v3)
{
return v3.getAudio(correctedFrame);
}
return mAudioCodec.getAudio(frame);
}
/**
* Synthesizes audio with optional metadata (tones, DTMF, etc.) for the voice frame. When the codec supports it
* (JMBE version 3), the audio is synthesized from the corrected frame so the codec doesn't repeat the error
* detection and correction. Otherwise, the raw frame bytes are passed to the codec (JMBE version 1 and 2).
*
* @param frame bytes for the voice frame as transmitted
* @param correctedFrame for the same voice frame, or null to let the codec perform the error correction
* @return audio samples with optional metadata
*/
protected IAudioWithMetadata getAudioWithMetadata(byte[] frame, ICorrectedFrame correctedFrame)
{
if(correctedFrame != null && mAudioCodec instanceof IAudioCodecV3 v3)
{
return v3.getAudioWithMetadata(correctedFrame);
}
return mAudioCodec.getAudioWithMetadata(frame);
}
@Override @Override
public Listener<IMessage> getMessageListener() public Listener<IMessage> getMessageListener()
{ {
@@ -238,25 +177,26 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
URLClassLoader childClassLoader = new URLClassLoader(new URL[]{path.toUri().toURL()}, URLClassLoader childClassLoader = new URLClassLoader(new URL[]{path.toUri().toURL()},
this.getClass().getClassLoader()); this.getClass().getClassLoader());
for(String className: JMBE_LIBRARY_CLASS_NAMES) try
{
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibraryV2", true, childClassLoader);
}
catch(ClassNotFoundException legacyLibrary)
{ {
try try
{ {
sLoadedJmbeAudioConverterClass = Class.forName(className, true, childClassLoader); sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibrary", true, childClassLoader);
break;
} }
catch(ClassNotFoundException notFound) catch(ClassNotFoundException missingLibrary)
{ {
//Library doesn't contain this version of the library class - try the next older version if(!mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
{
LOG.error("Couldn't load JMBE audio conversion library from [" + path +
"] - neither V2 nor V1 library class was found");
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
}
} }
} }
if(sLoadedJmbeAudioConverterClass == null && !mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
{
LOG.error("Couldn't load JMBE audio conversion library from [" + path +
"] - none of the library classes " + JMBE_LIBRARY_CLASS_NAMES + " were found");
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
}
} }
catch(IllegalArgumentException iae) catch(IllegalArgumentException iae)
{ {
@@ -289,18 +229,9 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
if((library.getMajorVersion() == 1 && library.getMinorVersion() >= 0 && if((library.getMajorVersion() == 1 && library.getMinorVersion() >= 0 &&
library.getBuildVersion() >= 0) || library.getMajorVersion() >= 1) library.getBuildVersion() >= 0) || library.getMajorVersion() >= 1)
{ {
if(library instanceof IAudioCodecLibraryV3 libraryV3) audioConverter = library instanceof IAudioCodecLibraryV2 libraryV2 ?
{ libraryV2.getAudioConverterV2(getCodecName()) :
audioConverter = libraryV3.getAudioConverterV3(getCodecName()); library.getAudioConverter(getCodecName());
}
else if(library instanceof IAudioCodecLibraryV2 libraryV2)
{
audioConverter = libraryV2.getAudioConverterV2(getCodecName());
}
else
{
audioConverter = library.getAudioConverter(getCodecName());
}
String codecStatusKey = JMBE_AUDIO_LIBRARY + ":codec:" + getCodecName(); String codecStatusKey = JMBE_AUDIO_LIBRARY + ":codec:" + getCodecName();
if(!mLibraryLoadStatusLogged.contains(codecStatusKey)) if(!mLibraryLoadStatusLogged.contains(codecStatusKey))

View File

@@ -36,7 +36,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Collection; import java.util.Collection;
import jmbe.frame.CorrectedIMBEFrame; import jmbe.iface.IAudioCodec;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter;
@@ -111,15 +111,12 @@ public class MBECallSequenceConverter
} }
} }
boolean correctFrames = audioModule.isCorrectedFrameSupported(); IAudioCodec codec = audioModule.getAudioCodec();
for(VoiceFrame voiceFrame: callSequence.getVoiceFrames()) for(VoiceFrame voiceFrame: callSequence.getVoiceFrames())
{ {
byte[] frameBytes = voiceFrame.getFrameBytes(); byte[] frameBytes = voiceFrame.getFrameBytes();
float[] audio = codec.getAudio(frameBytes);
//Only error correct the frame in sdrtrunk when the JMBE library (version 3+) can synthesize from it
float[] audio = audioModule.getAudio(frameBytes,
correctFrames ? CorrectedIMBEFrame.correct(frameBytes) : null);
audioModule.addAudio(audio); audioModule.addAudio(audio);
} }

View File

@@ -97,114 +97,41 @@ public class MP3AudioConverter implements IAudioConverter
audioPackets = mResampler.resample(audioPackets); audioPackets = mResampler.resample(audioPackets);
} }
for(float[] audioPacket: audioPackets) for(int x = 0; x < audioPackets.size(); x++)
{ {
encodePacket(audioPacket, converted); byte[] bytesToEncode = null;
}
int finalChunkSize = mEncoder.encodeFinish(mOutputFramesBuffer); if(mInputAudioFormat.getAudioFormat().getSampleSizeInBits() == 16)
if(finalChunkSize > 0)
{
converted.add(Arrays.copyOf(mOutputFramesBuffer, finalChunkSize));
}
return converted;
}
/**
* Encodes the PCM audio packet (already resampled) and adds any encoded MP3 frames to the list.
*/
private void encodePacket(float[] audioPacket, List<byte[]> converted)
{
byte[] bytesToEncode;
if(mInputAudioFormat.getAudioFormat().getSampleSizeInBits() == 16)
{
bytesToEncode = ConversionUtils.convertToSigned16BitSamples(audioPacket).array();
}
else
{
bytesToEncode = ConversionUtils.convertToSigned32BitSamples(audioPacket).array();
}
int bytesToEncodePointer = 0;
int inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length);
int outputChunkSize = 0;
try
{
while(bytesToEncodePointer < bytesToEncode.length)
{ {
outputChunkSize = mEncoder.encodeBuffer(bytesToEncode, bytesToEncodePointer, inputChunkSize, mOutputFramesBuffer); bytesToEncode = ConversionUtils.convertToSigned16BitSamples(audioPackets.get(x)).array();
bytesToEncodePointer += inputChunkSize; }
inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length - bytesToEncodePointer); else
{
bytesToEncode = ConversionUtils.convertToSigned32BitSamples(audioPackets.get(x)).array();
}
if(outputChunkSize > 0) int bytesToEncodePointer = 0;
int inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length);
int outputChunkSize = 0;
try
{
while(bytesToEncodePointer < bytesToEncode.length)
{ {
converted.add(Arrays.copyOf(mOutputFramesBuffer, outputChunkSize)); outputChunkSize = mEncoder.encodeBuffer(bytesToEncode, bytesToEncodePointer, inputChunkSize, mOutputFramesBuffer);
bytesToEncodePointer += inputChunkSize;
inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length - bytesToEncodePointer);
if(outputChunkSize > 0)
{
converted.add(Arrays.copyOf(mOutputFramesBuffer, outputChunkSize));
}
} }
} }
} catch(Exception e)
catch(Exception e)
{
mLog.error("There was an error converting audio to MP3: " + e.getMessage());
}
}
/**
* Encodes a chunk of a continuing audio stream to MP3. Unlike {@link #convert(List)}, the encoder and resampler
* keep their state between invocations, so the chunks of a call are encoded as one continuous stream. Invoke
* {@link #finishStream()} after the last chunk. Note: audio normalization is not applied.
*
* @param audioPackets of PCM audio sampled at 8 kHz
* @return encoded MP3 frames, possibly empty
*/
public List<byte[]> encodeStream(List<float[]> audioPackets)
{
List<byte[]> converted = new ArrayList<>();
if(mResampler != null)
{
List<float[]> resampled = new ArrayList<>();
mResampler.setListener(resampled::add);
for(float[] audioPacket: audioPackets)
{ {
mResampler.resample(audioPacket); mLog.error("There was an error converting audio to MP3: " + e.getMessage());
}
mResampler.setListener(null);
audioPackets = resampled;
}
for(float[] audioPacket: audioPackets)
{
encodePacket(audioPacket, converted);
}
return converted;
}
/**
* Flushes the resampler and the encoder at the end of a stream encoded with {@link #encodeStream(List)}.
* @return final encoded MP3 frames
*/
public List<byte[]> finishStream()
{
List<byte[]> converted = new ArrayList<>();
if(mResampler != null)
{
List<float[]> resampled = new ArrayList<>();
mResampler.setListener(resampled::add);
mResampler.flush();
mResampler.setListener(null);
for(float[] audioPacket: resampled)
{
encodePacket(audioPacket, converted);
} }
} }

View File

@@ -31,7 +31,6 @@ import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener; import io.github.dsheirer.sample.Listener;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -59,19 +58,13 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>(); private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>();
private final UserPreferences mUserPreferences; private final UserPreferences mUserPreferences;
private final String mChannelName; private final String mChannelName;
private final AtomicInteger mPeakLevelBits = new AtomicInteger();
private volatile AudioSegment mCurrentAudioSegment; private AudioSegment mCurrentAudioSegment;
private Listener<IdentifierCollection> mIdentifierCollectionListener; private Listener<IdentifierCollection> mIdentifierCollectionListener;
private boolean mDropDuplicates; private boolean mDropDuplicates;
private boolean mMetadataSent = false; private boolean mMetadataSent = false;
private boolean mMuted; private boolean mMuted;
private boolean mDisabled; private boolean mDisabled;
private volatile TalkgroupHold mHold;
private Listener<TalkgroupHold> mHoldListener;
private volatile Runnable mPlaybackListener;
private volatile ReplaySource mPendingReplay;
private volatile ReplaySource mReplay;
private float[] mAudioSegmentStartTone; private float[] mAudioSegmentStartTone;
private float[] mAudioSegmentDropTone; private float[] mAudioSegmentDropTone;
private int mCurrentBufferIndex = -1; private int mCurrentBufferIndex = -1;
@@ -112,114 +105,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
} }
} }
/**
* Hold talkgroup for this channel, or null. While a talkgroup is held, only calls to the talkgroup play on this
* channel, including calls that are otherwise flagged as do-not-monitor. The audio playback manager is
* responsible for steering calls to the channel; use {@link AudioPlaybackManager#setHold(int, TalkgroupHold)}.
*/
public TalkgroupHold getHold()
{
return mHold;
}
/**
* Sets or clears (null) the hold talkgroup. A call that is playing and doesn't match the hold talkgroup stops
* at the next audio interval.
*/
void setHold(TalkgroupHold hold)
{
mHold = hold;
Listener<TalkgroupHold> listener = mHoldListener;
if(listener != null)
{
listener.receive(hold);
}
}
/**
* Registers a single listener to be notified when the hold talkgroup is set (non-null) or cleared (null).
*/
public void setHoldListener(Listener<TalkgroupHold> listener)
{
mHoldListener = listener;
}
/**
* Indicates if the audio segment is allowed on this channel by the hold talkgroup.
*/
public boolean isAllowedByHold(AudioSegment audioSegment)
{
TalkgroupHold hold = mHold;
return hold == null || hold.matches(audioSegment);
}
/**
* Indicates if this channel is currently playing (or about to play) a call to its hold talkgroup.
*/
boolean isPlayingHeldTalkgroup()
{
TalkgroupHold hold = mHold;
AudioSegment current = mCurrentAudioSegment;
return hold != null && current != null && hold.matches(current);
}
/**
* Registers a single listener to be notified when this channel starts or stops playing a call audio segment or a
* replay. The listener reads the state from {@link #getCurrentAudioSegment()} and {@link #getReplay()}. Notified
* on the audio playback thread. Used by the audio playback manager.
*/
void setPlaybackListener(Runnable listener)
{
mPlaybackListener = listener;
}
/**
* Replays the recorded call on this channel. The replay takes over the channel at the next audio interval: a
* call that is playing is dropped and a replay that is playing is stopped. Calls queued for the channel play
* after the replay finishes. Use {@link AudioPlaybackManager#replay(ReplaySource)}.
*/
void startReplay(ReplaySource replay)
{
mPendingReplay = replay;
}
/**
* Replay that is playing on this channel, or null.
*/
public ReplaySource getReplay()
{
return mReplay;
}
/**
* Indicates if this channel is replaying (or about to replay) a recorded call.
*/
public boolean isReplaying()
{
ReplaySource replay = mReplay;
return mPendingReplay != null || (replay != null && !replay.isFinished());
}
/**
* Audio segment that this channel is currently playing, or null.
*/
public AudioSegment getCurrentAudioSegment()
{
return mCurrentAudioSegment;
}
private void notifyPlayback()
{
Runnable listener = mPlaybackListener;
if(listener != null)
{
listener.run();
}
}
/** /**
* Indicates if this audio channel is enabled. * Indicates if this audio channel is enabled.
*/ */
@@ -268,7 +153,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/ */
public boolean hasAudioSegment() public boolean hasAudioSegment()
{ {
return mCurrentAudioSegment != null || mReplay != null; return mCurrentAudioSegment != null;
} }
/** /**
@@ -289,75 +174,20 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/ */
public float[] getAudio() public float[] getAudio()
{ {
float[] audio = getNextAudio(); if(mAudioBuffer.isFull())
if(audio != null)
{ {
updatePeakLevel(audio); float[] audio = mAudioBuffer.get();
//Muted channels return silence. The peak level is measured before muting so that the display can still
//show that the muted channel has audio.
if(isMuted()) if(isMuted())
{ {
return new float[SAMPLES_PER_INTERVAL]; return new float[SAMPLES_PER_INTERVAL];
} }
} else
return audio;
}
/**
* Peak absolute sample value of the audio provided by this channel since the last call to this method, measured
* before muting. The audio output pulls audio ahead of playback, so this leads what is heard by the playback
* device buffer latency. Thread safe.
* @return peak level in the range 0.0 to 1.0 (or higher, if the audio is clipping) and resets it to zero.
*/
public float getAndResetPeakLevel()
{
return Float.intBitsToFloat(mPeakLevelBits.getAndSet(0));
}
/**
* Updates the peak level with the maximum absolute sample value of the audio buffer.
*/
private void updatePeakLevel(float[] audio)
{
float peak = 0.0f;
for(float sample: audio)
{
float magnitude = Math.abs(sample);
if(magnitude > peak)
{ {
peak = magnitude; return audio;
} }
} }
final float bufferPeak = peak;
//Non-negative float bit patterns sort the same as the float values
mPeakLevelBits.accumulateAndGet(Float.floatToIntBits(bufferPeak), Math::max);
}
/**
* Next interval of audio from the audio buffer or the current audio segment, before muting.
* @return audio or null
*/
private float[] getNextAudio()
{
float[] replayAudio = getReplayAudio();
if(replayAudio != null)
{
return replayAudio;
}
if(mAudioBuffer.isFull())
{
return mAudioBuffer.get();
}
if(mCurrentAudioSegment == null) if(mCurrentAudioSegment == null)
{ {
loadNextAudioSegment(); loadNextAudioSegment();
@@ -419,54 +249,10 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
audio = mAudioBuffer.flush(); audio = mAudioBuffer.flush();
} }
return audio; //Finally, if we have buffer audio and we're muted, return silence
} if(isMuted() && audio != null)
/**
* Starts a pending replay and provides the next replay audio. Audio thread.
* @return replay audio, or null when no replay is playing (normal call playback continues)
*/
private float[] getReplayAudio()
{
ReplaySource pending = mPendingReplay;
if(pending != null)
{ {
mPendingReplay = null; audio = new float[SAMPLES_PER_INTERVAL];
if(mReplay != null)
{
mReplay.stop();
}
//The replay takes over the channel: drop the buffered audio and the call that is playing
mAudioBuffer.flush();
if(mCurrentAudioSegment != null)
{
disposeCurrentAudioSegment();
clearMetadata();
}
mReplay = pending;
notifyPlayback();
notify(AudioEvent.Type.REPLAY_STARTED);
}
ReplaySource replay = mReplay;
if(replay == null)
{
return null;
}
float[] audio = replay.next();
if(audio == null)
{
mReplay = null;
notifyPlayback();
notify(AudioEvent.Type.REPLAY_STOPPED);
} }
return audio; return audio;
@@ -512,20 +298,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/ */
private boolean isThrowaway(AudioSegment audioSegment) private boolean isThrowaway(AudioSegment audioSegment)
{ {
if(audioSegment == null) return audioSegment != null && (audioSegment.isDoNotMonitor() || mDropDuplicates && (audioSegment.isDuplicate()));
{
return false;
}
TalkgroupHold hold = mHold;
if(hold != null)
{
//A held talkgroup plays even when do-not-monitor, and nothing else plays on a held channel
return !hold.matches(audioSegment) || (mDropDuplicates && audioSegment.isDuplicate());
}
return audioSegment.isDoNotMonitor() || mDropDuplicates && (audioSegment.isDuplicate());
} }
/** /**
@@ -571,18 +344,9 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
{ {
MyEventBus.getGlobalEventBus().unregister(this); MyEventBus.getGlobalEventBus().unregister(this);
ReplaySource replay = mReplay;
if(replay != null)
{
replay.stop();
}
disposeCurrentAudioSegment(); disposeCurrentAudioSegment();
mAudioEventBroadcaster.clear(); mAudioEventBroadcaster.clear();
mIdentifierCollectionListener = null; mIdentifierCollectionListener = null;
mHoldListener = null;
mPlaybackListener = null;
} }
/** /**
@@ -693,7 +457,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
mCurrentAudioSegment.decrementConsumerCount(); mCurrentAudioSegment.decrementConsumerCount();
mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this); mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this);
mCurrentAudioSegment = null; mCurrentAudioSegment = null;
notifyPlayback();
} }
} }
@@ -731,7 +494,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
if(audioSegment != null) if(audioSegment != null)
{ {
notifyPlayback();
mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this); mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this);
broadcast(mCurrentAudioSegment.getIdentifierCollection()); broadcast(mCurrentAudioSegment.getIdentifierCollection());
} }

View File

@@ -0,0 +1,373 @@
/*
* *****************************************************************************
* 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.audio.playback;
import com.google.common.base.Joiner;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.settings.ColorSetting;
import io.github.dsheirer.settings.Setting;
import io.github.dsheirer.settings.SettingChangeListener;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* UI to wrap an audio channel and provide display of metadata and playback state information.
*/
public class AudioChannelPanel extends JPanel implements Listener<AudioEvent>, SettingChangeListener
{
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(AudioChannelPanel.class);
public static final String PROPERTY_PREFIX = "audio.channel.panel.color.";
public static final String PROPERTY_COLOR_BACKGROUND = PROPERTY_PREFIX + "background";
public static final String PROPERTY_COLOR_LABEL = PROPERTY_PREFIX + "label";
public static final String PROPERTY_COLOR_MUTED = PROPERTY_PREFIX + "muted";
public static final String PROPERTY_COLOR_VALUE = PROPERTY_PREFIX + "value";
private final AudioChannel mAudioChannel;
private final AliasModel mAliasModel;
private final IconModel mIconModel;
private final SettingsManager mSettingsManager;
private final UserPreferences mUserPreferences;
private final TalkgroupFormatPreference mTalkgroupFormatPreference;
private Identifier mIdentifier;
private List<Alias> mAliases = Collections.EMPTY_LIST;
private final Lock mLock = new ReentrantLock();
private final Font mFont = new Font(Font.MONOSPACED, Font.PLAIN, 16);
private final Color mBackgroundColor;
private final Color mLabelColor;
private final Color mMutedColor;
private final Color mValueColor;
private final JLabel mMutedLabel = new JLabel("M");
private JLabel mChannelName = new JLabel(" ");
private final JLabel mIconLabel = new JLabel(" ");
private final JLabel mIdentifierLabel = new JLabel("-----");
/**
* Constructs an instance
* @param audioChannel to wrap by this panel
* @param aliasModel for alias lookup
* @param iconModel for icon lookup
* @param settingsManager for monitoring changes to tone insertion
* @param userPreferences for lookup of tone and other preferences
*/
public AudioChannelPanel(AudioChannel audioChannel, AliasModel aliasModel, IconModel iconModel,
SettingsManager settingsManager, UserPreferences userPreferences)
{
mIconModel = iconModel;
mSettingsManager = settingsManager;
mSettingsManager.addListener(this);
mAliasModel = aliasModel;
mUserPreferences = userPreferences;
mTalkgroupFormatPreference = mUserPreferences.getTalkgroupFormatPreference();
mAudioChannel = audioChannel;
if(mAudioChannel != null)
{
mAudioChannel.addAudioEventListener(this);
mAudioChannel.setIdentifierCollectionListener(new AudioMetadataProcessor());
}
mBackgroundColor = SystemProperties.getInstance().get(PROPERTY_COLOR_BACKGROUND, Color.BLACK);
mLabelColor = SystemProperties.getInstance().get(PROPERTY_COLOR_LABEL, Color.LIGHT_GRAY);
mMutedColor = SystemProperties.getInstance().get(PROPERTY_COLOR_MUTED, Color.RED);
mValueColor = SystemProperties.getInstance().get(PROPERTY_COLOR_VALUE, Color.GREEN);
init();
}
/**
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
updateLabels();
}
}
public void dispose()
{
//Deregister from receiving preference update notifications
MyEventBus.getGlobalEventBus().unregister(this);
if(mAudioChannel != null)
{
mAudioChannel.removeAudioEventListener(this);
mAudioChannel.removeAudioMetadataListener();
}
}
private void init()
{
//Register to receive preference updates
MyEventBus.getGlobalEventBus().register(this);
setLayout(new MigLayout("align center center, insets 0 0 0 0",
"[][][align right]0[grow,fill]", ""));
setBackground(mBackgroundColor);
mMutedLabel.setFont(mFont);
mMutedLabel.setForeground(mMutedColor);
mMutedLabel.setVisible(false);
add(mMutedLabel);
mChannelName = new JLabel(mAudioChannel != null ? mAudioChannel.getChannelName() : " ");
mChannelName.setFont(mFont);
mChannelName.setForeground(mLabelColor);
add(mChannelName);
mIconLabel.setFont(mFont);
mIconLabel.setForeground(mValueColor);
add(mIconLabel);
mIdentifierLabel.setFont(mFont);
mIdentifierLabel.setForeground(mValueColor);
add(mIdentifierLabel, "wmin 10lp");
}
@Override
public void receive(final AudioEvent audioEvent)
{
switch(audioEvent.getType())
{
case AUDIO_STOPPED:
EventQueue.invokeLater(this::resetLabels);
break;
case AUDIO_MUTED:
case AUDIO_UNMUTED:
EventQueue.invokeLater(() -> mMutedLabel.setVisible(mAudioChannel.isMuted()));
break;
default:
break;
}
}
/**
* Resets the from and to labels.
*/
private void resetLabels()
{
//Protect access to mIdentifier and mAliases
mLock.lock();
try
{
boolean updated = mIdentifier != null;
mIdentifier = null;
mAliases = Collections.EMPTY_LIST;
//Hold the lock through the label update
if(updated)
{
updateLabels();
}
}
finally
{
mLock.unlock();
}
}
private void updateIdentifiers(IdentifierCollection identifierCollection)
{
if(identifierCollection == null || identifierCollection.isEmpty())
{
resetLabels();
return;
}
List<Identifier> toIds = identifierCollection.getIdentifiers(IdentifierClass.USER, Role.TO);
if(toIds.isEmpty())
{
resetLabels();
return;
}
boolean updated = false;
//Protect access to mIdentifier and mAliases
mLock.lock();
try
{
if(toIds.size() == 1)
{
Identifier currentIdentifier = mIdentifier;
if(currentIdentifier == null || currentIdentifier != toIds.get(0))
{
mIdentifier = toIds.get(0);
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
if(aliasList != null)
{
mAliases = aliasList.getAliases(mIdentifier);
}
updated = true;
}
}
else
{
mIdentifier = toIds.get(0);
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
if(aliasList != null)
{
mAliases = aliasList.getAliases(mIdentifier);
}
updated = true;
}
//Hold the lock through the label update
if(updated)
{
updateLabels();
}
}
finally
{
mLock.unlock();
}
}
/**
* Updates the alias label with text and icon from the alias.
*/
private void updateLabels()
{
String identifier = null;
String iconName = null;
//Protect access to mIdentifier and mAliases
mLock.lock();
try
{
if(mAliases.size() == 1)
{
identifier = mAliases.get(0).getName();
iconName = mAliases.get(0).getIconName();
}
else if(mAliases.size() > 1)
{
identifier = Joiner.on(", ").skipNulls().join(mAliases);
}
if(identifier == null && mIdentifier != null)
{
identifier = mTalkgroupFormatPreference.format(mIdentifier);
}
if(identifier == null)
{
identifier = "-----";
}
final ImageIcon icon = iconName != null ? mIconModel.getIcon(iconName, 18) : null;
final String identifierText = identifier;
EventQueue.invokeLater(() -> {
mIdentifierLabel.setText(identifierText);
mIconLabel.setIcon(icon);
});
}
finally
{
mLock.unlock();
}
}
/**
* Processes audio metadata to update this panel's display values
*/
public class AudioMetadataProcessor implements Listener<IdentifierCollection>
{
@Override
public void receive(final IdentifierCollection identifierCollection)
{
updateIdentifiers(identifierCollection);
}
}
@Override
public void settingChanged(Setting setting)
{
if(setting instanceof ColorSetting)
{
ColorSetting colorSetting = (ColorSetting)setting;
switch(colorSetting.getColorSettingName())
{
case CHANNEL_STATE_LABEL_DECODER:
EventQueue.invokeLater(() -> {
if(mIdentifierLabel != null)
{
mIdentifierLabel.setForeground(mLabelColor);
}
if(mIconLabel != null)
{
mIconLabel.setForeground(mLabelColor);
}
});
break;
default:
break;
}
}
}
@Override
public void settingDeleted(Setting setting)
{
}
}

View File

@@ -0,0 +1,98 @@
/*
* *****************************************************************************
* 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.audio.playback;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.IAudioController;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.Component;
import net.miginfocom.swing.MigLayout;
import javax.swing.JPanel;
import javax.swing.JSeparator;
/**
* Displays one or more audio channel panels.
*/
public class AudioChannelsPanel extends JPanel
{
/**
* Constructs an instance
* @param iconModel for icon access
* @param userPreferences to monitor for audio playback changes
* @param settingsManager for tone insertion settings
* @param controller for the audio channels
* @param aliasModel for accessing aliases
*/
public AudioChannelsPanel(IconModel iconModel, UserPreferences userPreferences, SettingsManager settingsManager,
IAudioController controller, AliasModel aliasModel)
{
setLayout(new MigLayout("insets 0 0 0 0",
"[][sizegroup abc,grow,fill][][sizegroup abc,grow,fill]", "[grow,fill]"));
setBackground(Color.BLACK);
addSeparator();
for(int x = 0; x < controller.getAudioChannels().size(); x++)
{
add(new AudioChannelPanel(controller.getAudioChannels().get(x), aliasModel, iconModel, settingsManager, userPreferences));
if(x < controller.getAudioChannels().size() - 1)
{
addSeparator();
}
}
/* Add an empty channel panel so that the panel is sized appropriately
* for either a single channel or two channels */
if(controller.getAudioChannels().size() == 1)
{
addSeparator();
add(new AudioChannelPanel(null, aliasModel, iconModel, settingsManager, userPreferences), "growx");
}
}
/**
* Prepares for dispose to allow deregistering from services
*/
public void dispose()
{
for(Component component: getComponents())
{
if(component instanceof AudioChannelPanel)
{
((AudioChannelPanel)component).dispose();
}
}
}
/**
* Adds a separator to this panel.
*/
private void addSeparator()
{
JSeparator separator = new JSeparator(JSeparator.VERTICAL);
separator.setBackground(Color.DARK_GRAY);
add(separator);
}
}

View File

@@ -0,0 +1,305 @@
/*
* *****************************************************************************
* 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.audio.playback;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import jiconfont.icons.font_awesome.FontAwesome;
import io.github.dsheirer.gui.theme.ThemedFontIcon;
import net.miginfocom.swing.MigLayout;
import javax.sound.sampled.FloatControl;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
/**
* Audio playback panel
*/
public class AudioPanel extends JPanel implements Listener<AudioEvent>
{
private static final ImageIcon MUTED_ICON = IconModel.getScaledIcon("images/audio_muted.png", 20);
private static final ImageIcon UNMUTED_ICON = IconModel.getScaledIcon("images/audio_unmuted.png", 20);
private final AliasModel mAliasModel;
private final AudioPlaybackManager mAudioPlaybackManager;
private final IconModel mIconModel;
private final SettingsManager mSettingsManager;
private final UserPreferences mUserPreferences;
private AudioChannelsPanel mAudioChannelsPanel;
private JButton mMuteButton;
/**
* Constructs an instance
* @param iconModel for icon lookup
* @param userPreferences for preference lookup
* @param settingsManager to monitor for changes
* @param audioPlaybackManager for accessing the audio output
* @param aliasModel for alias lookup
*/
public AudioPanel(IconModel iconModel, UserPreferences userPreferences, SettingsManager settingsManager,
AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel)
{
mIconModel = iconModel;
mSettingsManager = settingsManager;
mAudioPlaybackManager = audioPlaybackManager;
mAliasModel = aliasModel;
mUserPreferences = userPreferences;
mAudioPlaybackManager.addAudioEventListener(this);
init();
}
/**
* Initialize the display
*/
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[]0[grow,fill]", "[fill]0[]"));
setBackground(Color.BLACK);
mMuteButton = new MuteButton();
mMuteButton.setBackground(getBackground());
add(mMuteButton);
mAudioChannelsPanel = new AudioChannelsPanel(mIconModel, mUserPreferences, mSettingsManager, mAudioPlaybackManager, mAliasModel);
add(mAudioChannelsPanel);
addMouseListener(new MouseSelectionListener());
}
/**
* Receive audio event notifications from the audio playback controller
*/
@Override
public void receive(AudioEvent event)
{
switch(event.getType())
{
case AUDIO_CONFIGURATION_CHANGE_STARTED:
break;
case AUDIO_CONFIGURATION_CHANGE_COMPLETE:
EventQueue.invokeLater(() -> {
remove(mAudioChannelsPanel);
mAudioChannelsPanel.dispose();
mAudioChannelsPanel = new AudioChannelsPanel(mIconModel, mUserPreferences, mSettingsManager, mAudioPlaybackManager, mAliasModel);
add(mAudioChannelsPanel);
mAudioChannelsPanel.repaint();
revalidate();
repaint();
});
break;
default:
break;
}
}
/**
* Audio output mute control menu item.
*/
public static class AudioOutputMuteItem extends JMenuItem
{
private final AudioOutput mAudioOutput;
/**
* Constructs an instance
* @param audioOutput to mute/unmute
*/
public AudioOutputMuteItem(AudioOutput audioOutput)
{
super(audioOutput.isMuted() ? "Unmute" : "Mute");
mAudioOutput = audioOutput;
addActionListener(e -> mAudioOutput.setMuted(!mAudioOutput.isMuted()));
}
}
/**
* Mouse listener
*/
public class MouseSelectionListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent event)
{
if(SwingUtilities.isRightMouseButton(event))
{
JPopupMenu popup = new JPopupMenu();
JMenuItem outputMenu = new JMenuItem("Audio Playback Device ...");
Icon icon = new ThemedFontIcon(FontAwesome.COG, 14);
outputMenu.setIcon(icon);
outputMenu.addActionListener(e -> MyEventBus.getGlobalEventBus()
.post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.AUDIO_OUTPUT)));
popup.add(outputMenu);
//Add optional gain controller for th eaudio output
if(mAudioPlaybackManager.getAudioOutput() != null && mAudioPlaybackManager.getAudioOutput().hasGainControl())
{
popup.add(new JPopupMenu.Separator());
JMenuItem volume = new JMenuItem("Audio Volume");
volume.setEnabled(false);
Icon volumeIcon = new ThemedFontIcon(FontAwesome.VOLUME_UP, 14);
volume.setIcon(volumeIcon);
popup.add(volume);
popup.add(new VolumeSlider(mAudioPlaybackManager.getAudioOutput().getGainControl()));
}
popup.show(event.getComponent(), event.getX(), event.getY());
}
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
}
@Override
public void mouseExited(MouseEvent e)
{
}
}
/**
* Audio volume (gain) adjustment slider control
*/
public static class VolumeSlider extends JSlider
{
private final FloatControl mFloatControl;
/**
* Constructs an instance
* @param control to be controlled
*/
public VolumeSlider(FloatControl control)
{
super(0, 100, 0);
setMajorTickSpacing(25);
setMinorTickSpacing(5);
setPaintTicks(true);
setPaintLabels(true);
mFloatControl = control;
setValue(getIntegerValue(mFloatControl.getValue()));
addChangeListener(event -> mFloatControl.shift(mFloatControl.getValue(),
getFloatValue(VolumeSlider.this.getValue()),
1000));
addMouseListener(new MouseListener()
{
@Override
public void mouseClicked(MouseEvent event)
{
if(event.getClickCount() == 2)
{
VolumeSlider.this.setValue(50);
}
}
public void mouseReleased(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
});
}
/**
* Converts the integer value to a floating point value to use in the
* float control. Assumes an integer value of 50 is the 0.0 dB mid
* point (ie no gain ) value.
*/
private int getIntegerValue(float value)
{
if(value == 0.0f)
{
return 50;
}
else if(value < 0.0f)
{
float ratio = value / mFloatControl.getMinimum();
return 50 - (int) (ratio * 50.0f);
}
else
{
float ratio = value / mFloatControl.getMaximum();
return 50 + (int) (ratio * 50.0f);
}
}
private float getFloatValue(int value)
{
if(value == 50)
{
return 0.0f;
}
else if(value < 50)
{
return (float) (50 - value) / 50.0f * mFloatControl.getMinimum();
}
else
{
return (float) (value - 50) / 50.0f * mFloatControl.getMaximum();
}
}
}
/**
* Mute button to mute all audio output channels exposed by the audio
* controller
*/
public class MuteButton extends JButton
{
private boolean mMuted = false;
public MuteButton()
{
setIcon(UNMUTED_ICON);
setBorderPainted(false);
getAccessibleContext().setAccessibleName("Mute");
addActionListener(e -> {
mMuted = !mMuted;
mAudioPlaybackManager.getAudioOutput().setMuted(mMuted);
EventQueue.invokeLater(() -> {
setIcon(mMuted ? MUTED_ICON : UNMUTED_ICON);
getAccessibleContext().setAccessibleName(mMuted ? "Unmute" : "Mute");
});
});
}
}
}

View File

@@ -53,7 +53,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
private static final Logger mLog = LoggerFactory.getLogger(AudioPlaybackManager.class); private static final Logger mLog = LoggerFactory.getLogger(AudioPlaybackManager.class);
private final AudioSegmentPrioritySorter mAudioSegmentPrioritySorter = new AudioSegmentPrioritySorter(); private final AudioSegmentPrioritySorter mAudioSegmentPrioritySorter = new AudioSegmentPrioritySorter();
private final Broadcaster<AudioEvent> mControllerBroadcaster = new Broadcaster<>(); private final Broadcaster<AudioEvent> mControllerBroadcaster = new Broadcaster<>();
private final Broadcaster<ChannelPlayback> mPlaybackBroadcaster = new Broadcaster<>();
private final List<AudioSegment> mAudioSegments = new ArrayList<>(); private final List<AudioSegment> mAudioSegments = new ArrayList<>();
private final List<AudioSegment> mPendingAudioSegments = new ArrayList<>(); private final List<AudioSegment> mPendingAudioSegments = new ArrayList<>();
private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>(); private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>();
@@ -62,8 +61,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
private AudioPlaybackDeviceDescriptor mAudioPlaybackDevice; private AudioPlaybackDeviceDescriptor mAudioPlaybackDevice;
private AudioOutput mAudioOutput; private AudioOutput mAudioOutput;
private ScheduledFuture<?> mProcessingTask; private ScheduledFuture<?> mProcessingTask;
private final TalkgroupHold[] mHolds = new TalkgroupHold[2];
private final long[] mHoldActivity = new long[2];
/** /**
* Constructs an instance. * Constructs an instance.
@@ -117,8 +114,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
*/ */
private void processAudioSegments() private void processAudioSegments()
{ {
updateHoldActivity();
//Process new audio segments queue. If segment has audio, queue it for replay, otherwise place in pending queue //Process new audio segments queue. If segment has audio, queue it for replay, otherwise place in pending queue
AudioSegment newSegment = mNewAudioSegmentQueue.poll(); AudioSegment newSegment = mNewAudioSegmentQueue.poll();
@@ -187,8 +182,7 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
{ {
audioSegment = it.next(); audioSegment = it.next();
if((audioSegment.isDoNotMonitor() && getHoldingChannelIndex(audioSegment) < 0) || if(audioSegment.isDoNotMonitor() || (audioSegment.isDuplicate() &&
(audioSegment.isDuplicate() &&
mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled())) mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled()))
{ {
it.remove(); it.remove();
@@ -239,7 +233,20 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
try try
{ {
assignAudioSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels()); //Assign empty audio outputs first
for(AudioChannel audioChannel: mAudioOutput.getAudioProvider().getAudioChannels())
{
if(audioChannel.isEmpty())
{
audioChannel.play(mAudioSegments.removeFirst());
if(mAudioSegments.isEmpty())
{
return;
}
}
}
replaceLowerPriorityQueuedSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels());
} }
finally finally
{ {
@@ -263,352 +270,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
} }
} }
/**
* Assigns waiting audio segments, in priority order, to empty audio channels. Calls to a hold talkgroup only go to
* the channel that holds the talkgroup, and other calls only go to channels without a hold talkgroup.
*
* @param waiting audio segments, sorted by playback priority. Assigned segments are removed.
* @param audioChannels to assign to.
*/
static void assignAudioSegments(List<AudioSegment> waiting, List<AudioChannel> audioChannels)
{
Iterator<AudioSegment> it = waiting.iterator();
while(it.hasNext())
{
AudioSegment audioSegment = it.next();
AudioChannel holding = getHoldingChannel(audioSegment, audioChannels);
AudioChannel target = null;
if(holding != null)
{
if(holding.isEmpty())
{
target = holding;
}
}
else
{
for(AudioChannel audioChannel: audioChannels)
{
if(audioChannel.getHold() == null && audioChannel.isEmpty() && !audioChannel.isReplaying())
{
target = audioChannel;
break;
}
}
}
if(target != null)
{
it.remove();
target.play(audioSegment);
}
}
//Priority replacement of queued segments only applies to channels and calls without a hold talkgroup
List<AudioChannel> unheld = new ArrayList<>();
for(AudioChannel audioChannel: audioChannels)
{
if(audioChannel.getHold() == null && !audioChannel.isReplaying())
{
unheld.add(audioChannel);
}
}
if(!unheld.isEmpty() && !waiting.isEmpty())
{
List<AudioSegment> unmatched = new ArrayList<>();
it = waiting.iterator();
while(it.hasNext())
{
AudioSegment audioSegment = it.next();
if(getHoldingChannel(audioSegment, audioChannels) == null)
{
unmatched.add(audioSegment);
it.remove();
}
}
replaceLowerPriorityQueuedSegments(unmatched, unheld);
waiting.addAll(unmatched);
}
}
/**
* Channel that holds the talkgroup of the audio segment, or null.
*/
static AudioChannel getHoldingChannel(AudioSegment audioSegment, List<AudioChannel> audioChannels)
{
for(AudioChannel audioChannel: audioChannels)
{
TalkgroupHold hold = audioChannel.getHold();
if(hold != null && hold.matches(audioSegment))
{
return audioChannel;
}
}
return null;
}
/**
* Index of the channel that holds the talkgroup of the audio segment, or -1.
*/
private int getHoldingChannelIndex(AudioSegment audioSegment)
{
for(int x = 0; x < mHolds.length; x++)
{
TalkgroupHold hold = mHolds[x];
if(hold != null && hold.matches(audioSegment))
{
return x;
}
}
return -1;
}
/**
* Sets (or clears, with null) the hold talkgroup for the audio channel. Setting a talkgroup that another channel
* holds moves the hold to this channel. Queued calls that don't match the hold talkgroup are returned for
* assignment to another channel, and a call that is playing and doesn't match stops.
*
* @param channelIndex of the audio channel (0 = left/mono, 1 = right)
* @param hold talkgroup or null to release the hold
*/
public void setHold(int channelIndex, TalkgroupHold hold)
{
if(channelIndex < 0 || channelIndex >= mHolds.length)
{
return;
}
mAudioChannelsLock.lock();
try
{
if(hold != null)
{
for(int x = 0; x < mHolds.length; x++)
{
if(x != channelIndex && hold.isSameTalkgroup(mHolds[x]))
{
applyHold(x, null);
}
}
}
applyHold(channelIndex, hold);
}
finally
{
mAudioChannelsLock.unlock();
}
mLog.info("Audio channel " + channelIndex + (hold != null ? " hold talkgroup [" + hold + "]" :
" hold talkgroup released"));
}
/**
* Applies the hold to the channel. Audio channels lock must be held.
*/
private void applyHold(int channelIndex, TalkgroupHold hold)
{
mHolds[channelIndex] = hold;
mHoldActivity[channelIndex] = System.currentTimeMillis();
if(mAudioOutput != null)
{
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
if(channelIndex < channels.size())
{
AudioChannel channel = channels.get(channelIndex);
channel.setHold(hold);
if(hold != null)
{
//Return queued calls that can no longer play on this channel
List<AudioSegment> keep = new ArrayList<>();
AudioSegment queued = channel.pollQueuedAudioSegment();
while(queued != null)
{
if(hold.matches(queued))
{
keep.add(queued);
}
else
{
mNewAudioSegmentQueue.add(queued);
}
queued = channel.pollQueuedAudioSegment();
}
for(AudioSegment segment: keep)
{
channel.play(segment);
}
}
}
}
}
/**
* Registers the listener to be notified when an audio channel starts or stops playing a call. Notified on the
* audio playback thread.
*/
public void addPlaybackListener(Listener<ChannelPlayback> listener)
{
mPlaybackBroadcaster.addListener(listener);
}
public void removePlaybackListener(Listener<ChannelPlayback> listener)
{
mPlaybackBroadcaster.removeListener(listener);
}
/**
* Current playback state of each audio channel, for a listener that registers after playback started.
*/
public List<ChannelPlayback> getChannelPlayback()
{
List<ChannelPlayback> playback = new ArrayList<>();
List<AudioChannel> channels = getAudioChannels();
for(int x = 0; x < channels.size(); x++)
{
playback.add(getChannelPlayback(channels.get(x), x, channels.size()));
}
return playback;
}
private static ChannelPlayback getChannelPlayback(AudioChannel channel, int channelIndex, int channelCount)
{
AudioSegment current = channel.getCurrentAudioSegment();
ReplaySource replay = channel.getReplay();
return new ChannelPlayback(channelIndex, channel.getChannelName(), channelCount,
current != null ? current.getId() : 0, replay != null && !replay.isFinished() ? replay.getCallId() : 0);
}
/**
* Replays a recorded call through the audio channels. A channel that is already replaying is reused, otherwise
* an idle channel (left first), otherwise the left (or mono) channel, which drops the call that it is playing.
* Live calls aren't assigned to the channel while it replays.
*
* @param replay to play
* @return index of the channel that replays the call, or -1 if there is no audio output
*/
public int replay(ReplaySource replay)
{
mAudioChannelsLock.lock();
try
{
List<AudioChannel> channels = getAudioChannels();
if(channels.isEmpty())
{
return -1;
}
int selected = -1;
for(int x = 0; x < channels.size() && selected < 0; x++)
{
if(channels.get(x).isReplaying())
{
selected = x;
}
}
for(int x = 0; x < channels.size() && selected < 0; x++)
{
AudioChannel channel = channels.get(x);
if(!channel.hasAudioSegment() && channel.isEmpty())
{
selected = x;
}
}
if(selected < 0)
{
selected = 0;
}
channels.get(selected).startReplay(replay);
return selected;
}
finally
{
mAudioChannelsLock.unlock();
}
}
/**
* Hold talkgroup for the audio channel, or null.
*/
public TalkgroupHold getHold(int channelIndex)
{
return channelIndex >= 0 && channelIndex < mHolds.length ? mHolds[channelIndex] : null;
}
/**
* Updates the last activity time of each hold talkgroup and releases holds that have been idle longer than the
* automatic release time.
*/
private void updateHoldActivity()
{
int minutes = mUserPreferences.getPlaybackPreference().getHoldAutoReleaseMinutes();
long now = System.currentTimeMillis();
for(int x = 0; x < mHolds.length; x++)
{
TalkgroupHold hold = mHolds[x];
if(hold == null)
{
continue;
}
boolean active = false;
for(AudioSegment audioSegment: mAudioSegments)
{
if(hold.matches(audioSegment))
{
active = true;
break;
}
}
if(!active && mAudioOutput != null)
{
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
active = x < channels.size() && channels.get(x).isPlayingHeldTalkgroup();
}
if(active)
{
mHoldActivity[x] = now;
}
else if(minutes > 0 && (now - mHoldActivity[x]) > TimeUnit.MINUTES.toMillis(minutes))
{
mLog.info("Releasing idle hold talkgroup [" + hold + "] after " + minutes + " minutes");
setHold(x, null);
}
}
}
/** /**
* Swaps audio segments queued on the audio channels for waiting audio segments that have a higher playback priority, * Swaps audio segments queued on the audio channels for waiting audio segments that have a higher playback priority,
* so that a segment queued behind the current playback can't hold a higher priority segment out of the channel. * so that a segment queued behind the current playback can't hold a higher priority segment out of the channel.
@@ -736,30 +397,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
//Note: audio output can use an alternate device if the requested device can't be used, so we assign //Note: audio output can use an alternate device if the requested device can't be used, so we assign
//the descriptor that was actually used by the audio output //the descriptor that was actually used by the audio output
mAudioPlaybackDevice = mAudioOutput.getAudioPlaybackDeviceDescriptor(); mAudioPlaybackDevice = mAudioOutput.getAudioPlaybackDeviceDescriptor();
//Re-apply hold talkgroups to the new channels (and drop a right channel hold for a mono device)
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
for(int x = 0; x < channels.size(); x++)
{
final int channelIndex = x;
final AudioChannel channel = channels.get(x);
final int outputChannels = channels.size();
channel.setPlaybackListener(() -> mPlaybackBroadcaster.broadcast(
getChannelPlayback(channel, channelIndex, outputChannels)));
}
for(int x = 0; x < mHolds.length; x++)
{
if(x < channels.size())
{
channels.get(x).setHold(mHolds[x]);
}
else
{
mHolds[x] = null;
}
}
} }
finally finally
{ {

View File

@@ -1,49 +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.audio.playback;
/**
* Notification that an audio channel started playing a call, or stopped playing.
*
* @param channelIndex of the audio channel in the audio output (0 = left/mono, 1 = right)
* @param channelName of the audio channel (LEFT, RIGHT or MONO)
* @param channelCount number of channels in the audio output
* @param audioSegmentId of the live call audio segment that is playing, or 0. This is the call key of the call in
* the call manager.
* @param replayCallId database id of the recorded call that is replaying, or 0.
*/
public record ChannelPlayback(int channelIndex, String channelName, int channelCount, long audioSegmentId,
long replayCallId)
{
/**
* Indicates if the channel is playing a live call or replaying a recorded call
*/
public boolean isPlaying()
{
return audioSegmentId != 0 || replayCallId != 0;
}
/**
* Indicates if the channel is replaying a recorded call
*/
public boolean isReplay()
{
return replayCallId != 0;
}
}

View File

@@ -1,154 +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.audio.playback;
/**
* Audio of a recorded call that is replayed through an audio channel. The audio channel pulls the audio in 20 ms
* intervals on the audio playback thread, and the user interface pauses, seeks and stops it from the FX thread.
*/
public class ReplaySource
{
private final float[] mSamples;
private final long mCallId;
private final String mDescription;
private volatile int mPosition;
private volatile boolean mPaused;
private volatile boolean mStopped;
/**
* Constructs an instance
* @param samples of 8 kHz audio
* @param callId database id of the call that is replayed
* @param description of the call for display (e.g. TO and FROM)
*/
public ReplaySource(float[] samples, long callId, String description)
{
mSamples = samples;
mCallId = callId;
mDescription = description;
}
/**
* Database id of the replayed call
*/
public long getCallId()
{
return mCallId;
}
/**
* Description of the replayed call for display
*/
public String getDescription()
{
return mDescription;
}
/**
* Next 20 ms of audio, silence while paused, or null when the replay is finished or stopped. Audio thread.
*/
float[] next()
{
if(isFinished())
{
return null;
}
float[] audio = new float[AudioChannel.SAMPLES_PER_INTERVAL];
if(mPaused)
{
return audio;
}
int position = mPosition;
int length = Math.min(audio.length, mSamples.length - position);
System.arraycopy(mSamples, position, audio, 0, length);
mPosition = position + length;
return audio;
}
/**
* Indicates if the replay played to the end or was stopped
*/
public boolean isFinished()
{
return mStopped || mPosition >= mSamples.length;
}
/**
* Indicates if the replay played to the end, as opposed to being stopped or replaced
*/
public boolean isCompleted()
{
return !mStopped && mPosition >= mSamples.length;
}
public boolean isPaused()
{
return mPaused;
}
public void setPaused(boolean paused)
{
mPaused = paused;
}
/**
* Stops the replay. The audio channel releases it at the next audio interval.
*/
public void stop()
{
mStopped = true;
}
/**
* Moves the replay position
* @param fraction of the recording, 0.0 to 1.0
*/
public void seek(double fraction)
{
double clamped = Math.max(0.0, Math.min(1.0, fraction));
mPosition = (int)Math.min(mSamples.length, Math.round(mSamples.length * clamped));
}
/**
* Replay position in milliseconds
*/
public long getPositionMillis()
{
return mPosition * 1000L / 8000L;
}
/**
* Recording duration in milliseconds
*/
public long getDurationMillis()
{
return mSamples.length * 1000L / 8000L;
}
/**
* Replay position as a fraction of the recording, 0.0 to 1.0
*/
public double getFraction()
{
return mSamples.length > 0 ? (double)mPosition / mSamples.length : 1.0;
}
}

View File

@@ -1,167 +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.audio.playback;
import io.github.dsheirer.audio.AudioSegment;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.identifier.patch.PatchGroup;
import io.github.dsheirer.identifier.patch.PatchGroupIdentifier;
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
import io.github.dsheirer.protocol.Protocol;
/**
* Hold talkgroup for an audio channel. While a channel holds a talkgroup, only calls to that talkgroup play on the
* channel and calls to the talkgroup are steered to the channel.
*
* A call matches when its TO talkgroup has the same protocol and value, or when its TO patch group is (or includes)
* the talkgroup. APCO-25 phase 1 and phase 2 are treated as the same protocol since a P25 system's talkgroups are
* used on both phase 1 and phase 2 traffic channels.
*
* @param protocol of the talkgroup
* @param talkgroup value
* @param label for display (formatted talkgroup and alias)
*/
public record TalkgroupHold(Protocol protocol, int talkgroup, String label)
{
/**
* Normalizes the protocol for comparison
*/
private static Protocol normalize(Protocol protocol)
{
return protocol == Protocol.APCO25_PHASE2 ? Protocol.APCO25 : protocol;
}
/**
* Indicates if the talkgroup identifier is this hold talkgroup
*/
public boolean matches(TalkgroupIdentifier identifier)
{
return identifier != null && identifier.getValue() != null && identifier.getValue() == talkgroup &&
normalize(identifier.getProtocol()) == normalize(protocol);
}
/**
* Indicates if the call identifiers have this hold talkgroup (or a patch group with it) as the TO identifier.
*/
public boolean matches(IdentifierCollection identifierCollection)
{
if(identifierCollection == null)
{
return false;
}
for(Identifier identifier: identifierCollection.getIdentifiers(Role.TO))
{
if(identifier instanceof TalkgroupIdentifier tg && matches(tg))
{
return true;
}
if(identifier instanceof PatchGroupIdentifier pgi && pgi.getValue() != null)
{
PatchGroup patchGroup = pgi.getValue();
if(matches(patchGroup.getPatchGroup()))
{
return true;
}
for(TalkgroupIdentifier patched: patchGroup.getPatchedTalkgroupIdentifiers())
{
if(matches(patched))
{
return true;
}
}
}
}
return false;
}
/**
* Indicates if the audio segment is a call to this hold talkgroup.
*/
public boolean matches(AudioSegment audioSegment)
{
return audioSegment != null && matches(audioSegment.getIdentifierCollection());
}
/**
* Creates a hold for the TO talkgroup (or patch group) of the call identifiers.
* @param identifierCollection of a call
* @param label for display
* @return hold or null if the call doesn't have a TO talkgroup
*/
public static TalkgroupHold from(IdentifierCollection identifierCollection, String label)
{
if(identifierCollection == null)
{
return null;
}
Identifier to = identifierCollection.getToIdentifier();
if(to instanceof PatchGroupIdentifier pgi && pgi.getValue() != null && pgi.getValue().getPatchGroup() != null)
{
to = pgi.getValue().getPatchGroup();
}
if(to instanceof TalkgroupIdentifier tg && tg.getValue() != null && tg.getValue() > 0)
{
return new TalkgroupHold(tg.getProtocol(), tg.getValue(), label != null ? label : tg.toString());
}
return null;
}
/**
* Creates a hold for the TO talkgroup of a stored call.
* @param call with a TO talkgroup
* @param toAlias current alias name of the TO talkgroup for the label, or null
* @return hold or null if the call doesn't have a TO talkgroup
*/
public static TalkgroupHold from(CallRecord call, String toAlias)
{
if(call == null || !call.hasTalkgroup() || call.getToValue() > Integer.MAX_VALUE)
{
return null;
}
String label = call.getToId() + (toAlias != null ? " " + toAlias : "");
return new TalkgroupHold(call.getProtocolValue(), call.getToValue().intValue(), label);
}
/**
* Indicates if the other hold is for the same talkgroup (ignoring the label).
*/
public boolean isSameTalkgroup(TalkgroupHold other)
{
return other != null && other.talkgroup == talkgroup && normalize(other.protocol) == normalize(protocol);
}
@Override
public String toString()
{
return label;
}
}

View File

@@ -1,412 +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.call;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.audio.AudioSegment;
import io.github.dsheirer.controller.NamingThreadFactory;
import io.github.dsheirer.database.DatabaseManager;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.database.call.CallState;
import io.github.dsheirer.database.call.PatchedTalkgroup;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.identifier.configuration.DecoderTypeConfigurationIdentifier;
import io.github.dsheirer.identifier.configuration.FrequencyConfigurationIdentifier;
import io.github.dsheirer.identifier.integer.IntegerIdentifier;
import io.github.dsheirer.identifier.patch.PatchGroupIdentifier;
import io.github.dsheirer.identifier.radio.FullyQualifiedRadioIdentifier;
import io.github.dsheirer.identifier.talkgroup.FullyQualifiedTalkgroupIdentifier;
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.protocol.Protocol;
import io.github.dsheirer.record.CallRecorder;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Manages the life-cycle of every call: the single audio segment listener for calls.
*
* Each audio segment is a call. The call manager creates the call record as soon as the call has audio (or is
* identified as encrypted), updates it as the call identifiers change and completes it when the call ends. Each
* change is saved to the call database and broadcast to the call listeners (Calls tab, and later external
* subscribers), so they see the same call activity. The {@link CallRecorder} records the call audio and fills in
* the recording details of the call record.
*
* Calls are processed on a single call manager thread every 200 milliseconds.
*/
public class CallManager implements Listener<AudioSegment>
{
private final static Logger mLog = LoggerFactory.getLogger(CallManager.class);
private static final long PROCESSING_INTERVAL_MS = 200;
private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>();
private final List<TrackedCall> mTrackedCalls = new ArrayList<>();
private final Broadcaster<CallRecord> mCallBroadcaster = new Broadcaster<>();
private final ScheduledExecutorService mExecutor =
Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("sdrtrunk call manager"));
private final UserPreferences mUserPreferences;
private final DatabaseManager mDatabaseManager;
private final CallRecorder mCallRecorder;
private ScheduledFuture<?> mProcessorHandle;
/**
* Constructs an instance
* @param userPreferences for call recording and identifier formatting
* @param databaseManager to store the calls, or null to track and record calls without storing them
*/
public CallManager(UserPreferences userPreferences, DatabaseManager databaseManager)
{
mUserPreferences = userPreferences;
mDatabaseManager = databaseManager;
mCallRecorder = new CallRecorder(userPreferences);
}
/**
* Starts the manager and begins call tracking and audio recording.
*/
public void start()
{
if(mProcessorHandle == null)
{
mProcessorHandle = mExecutor.scheduleWithFixedDelay(this::processSafely, 0, PROCESSING_INTERVAL_MS,
TimeUnit.MILLISECONDS);
}
}
/**
* Stops the manager, completing any calls and recordings that are still in progress.
*/
public void stop()
{
if(mProcessorHandle != null)
{
mProcessorHandle.cancel(false);
mProcessorHandle = null;
try
{
mExecutor.submit(() -> {
process();
for(TrackedCall trackedCall: mTrackedCalls)
{
trackedCall.complete();
}
mTrackedCalls.clear();
}).get(10, TimeUnit.SECONDS);
}
catch(Exception e)
{
mLog.error("Error completing calls in progress during shutdown", e);
}
mExecutor.shutdownNow();
}
}
/**
* Registers the listener to receive a snapshot of each call when it starts, changes and completes. Snapshots
* of the same call share the same {@link CallRecord#getCallKey()}, which is the {@link AudioSegment#getId()} of
* the call's audio segment. Notified on the call recorder thread.
*/
public void addCallListener(Listener<CallRecord> listener)
{
mCallBroadcaster.addListener(listener);
}
public void removeCallListener(Listener<CallRecord> listener)
{
mCallBroadcaster.removeListener(listener);
}
/**
* Primary receive method for incoming audio segments. The consumer count of the segment is already incremented
* for this manager.
*/
@Override
public void receive(AudioSegment audioSegment)
{
mNewAudioSegmentQueue.add(audioSegment);
}
private void processSafely()
{
try
{
process();
}
catch(Throwable t)
{
mLog.error("Error while processing calls", t);
}
}
/**
* Processes new and tracked audio segments. Call recorder thread only.
*/
private void process()
{
AudioSegment audioSegment = mNewAudioSegmentQueue.poll();
while(audioSegment != null)
{
mTrackedCalls.add(new TrackedCall(audioSegment, audioSegment.getId()));
audioSegment = mNewAudioSegmentQueue.poll();
}
Iterator<TrackedCall> it = mTrackedCalls.iterator();
while(it.hasNext())
{
TrackedCall trackedCall = it.next();
if(trackedCall.process())
{
it.remove();
}
}
}
/**
* Updates the call record fields from the audio segment.
*/
void update(CallRecord call, AudioSegment audioSegment)
{
IdentifierCollection collection = audioSegment.getIdentifierCollection();
AliasList aliasList = audioSegment.getAliasList();
Identifier to = collection.getToIdentifier();
Identifier from = collection.getFromIdentifier();
Protocol protocol = to != null ? to.getProtocol() : (from != null ? from.getProtocol() : null);
if(protocol == null || protocol == Protocol.UNKNOWN)
{
Identifier decoder = collection.getIdentifier(IdentifierClass.CONFIGURATION, Form.DECODER_TYPE, Role.ANY);
if(decoder instanceof DecoderTypeConfigurationIdentifier dtci && dtci.getValue() != null)
{
protocol = dtci.getValue().getProtocol();
}
}
call.setProtocol(protocol != null ? protocol.name() : null);
call.setSystem(getString(collection, Form.SYSTEM));
call.setSite(getString(collection, Form.SITE));
call.setChannel(getString(collection, Form.CHANNEL));
Identifier frequency = collection.getIdentifier(IdentifierClass.CONFIGURATION, Form.CHANNEL_FREQUENCY, Role.ANY);
if(frequency instanceof FrequencyConfigurationIdentifier fci && fci.getValue() != null)
{
call.setFrequency(fci.getValue());
}
call.setTimeslot(audioSegment.getTimeslot());
var format = mUserPreferences.getTalkgroupFormatPreference();
call.setToId(to != null ? format.format(to) : null);
call.setToValue(getValue(to));
call.setToForm(to != null ? to.getForm().name() : null);
call.setToFullyQualified(to instanceof FullyQualifiedTalkgroupIdentifier fqt ?
fqt.getFullyQualifiedTalkgroupAddress() : null);
call.setFromId(from != null ? format.format(from) : null);
call.setFromValue(getValue(from));
call.setFromForm(from != null ? from.getForm().name() : null);
call.setFromFullyQualified(from instanceof FullyQualifiedRadioIdentifier fqr ?
fqr.getFullyQualifiedRadioAddress() : null);
call.setAliasList(aliasList != null ? aliasList.getName() : null);
call.setPatchedTalkgroups(getPatchedTalkgroups(to));
List<Identifier> talkerAliases = collection.getIdentifiers(Form.TALKER_ALIAS);
call.setTalkerAlias(talkerAliases.isEmpty() ? null : talkerAliases.getFirst().toString());
call.setEncrypted(audioSegment.isEncrypted());
call.setDuplicate(audioSegment.isDuplicate());
call.setPriority(audioSegment.monitorPriorityProperty().get());
call.setAliasRecord(audioSegment.recordAudioProperty().get());
call.setStartTime(audioSegment.getStartTimestamp());
}
/**
* Talkgroups patched into the patch group TO identifier, or an empty list.
*/
static List<PatchedTalkgroup> getPatchedTalkgroups(Identifier to)
{
if(!(to instanceof PatchGroupIdentifier pgi) || pgi.getValue() == null)
{
return List.of();
}
List<PatchedTalkgroup> patched = new ArrayList<>();
for(TalkgroupIdentifier talkgroup: pgi.getValue().getPatchedTalkgroupIdentifiers())
{
if(talkgroup != null && talkgroup.getValue() != null)
{
patched.add(new PatchedTalkgroup(talkgroup.getValue(),
talkgroup instanceof FullyQualifiedTalkgroupIdentifier fqt ?
fqt.getFullyQualifiedTalkgroupAddress() : null));
}
}
return patched;
}
private static String getString(IdentifierCollection collection, Form form)
{
Identifier identifier = collection.getIdentifier(IdentifierClass.CONFIGURATION, form, Role.ANY);
return identifier != null && identifier.getValue() != null ? identifier.getValue().toString() : null;
}
/**
* Numeric value of a talkgroup, patch group (the patch group talkgroup) or radio identifier, or null.
*/
static Long getValue(Identifier identifier)
{
if(identifier instanceof PatchGroupIdentifier pgi && pgi.getValue() != null &&
pgi.getValue().getPatchGroup() != null)
{
return pgi.getValue().getPatchGroup().getValue().longValue();
}
if(identifier instanceof IntegerIdentifier ii && ii.getValue() != null)
{
return ii.getValue().longValue();
}
return null;
}
/**
* Content of a call snapshot that is compared to detect a change that needs to be saved and broadcast.
*/
private static String getSignature(CallRecord call)
{
return call.getStartTime() + "|" + call.getCallState() + "|" + call.getProtocol() + "|" + call.getSystem() +
"|" + call.getSite() + "|" + call.getChannel() + "|" + call.getFrequency() + "|" + call.getToId() + "|" +
call.getToForm() + "|" + call.getFromId() + "|" + call.getFromForm() + "|" + call.getAliasList() + "|" + call.getPatchedTalkgroups() + "|" +
call.getTalkerAlias() + "|" +
call.isEncrypted() + "|" + call.isDuplicate() + "|" + call.getPriority() + "|" + call.isAliasRecord() + "|" +
call.getRecordingState() + "|" + call.getFilePath() + "|" + call.getEndTime();
}
/**
* A call that is being tracked and possibly recorded. Call recorder thread only.
*/
private class TrackedCall
{
private final AudioSegment mAudioSegment;
private final CallRecord mCall = new CallRecord();
private final DatabaseManager.CallHandle mHandle;
private final CallRecorder.Recording mRecording;
private String mLastSignature;
private boolean mPublished;
TrackedCall(AudioSegment audioSegment, long callKey)
{
mAudioSegment = audioSegment;
mRecording = mCallRecorder.createRecording(audioSegment);
mCall.setCallKey(callKey);
mHandle = mDatabaseManager != null ? mDatabaseManager.createHandle() : null;
}
/**
* Processes the call.
* @return true when the call is complete and should no longer be tracked
*/
boolean process()
{
boolean complete = mAudioSegment.isComplete();
boolean hasAudio = mAudioSegment.hasAudio();
if(complete)
{
if(hasAudio || mPublished || mAudioSegment.isEncrypted())
{
complete();
}
mAudioSegment.decrementConsumerCount();
return true;
}
//Wait for audio (or an encrypted call) before creating the call, so that segments that never have audio
//don't create empty calls
if(!hasAudio && !mAudioSegment.isEncrypted())
{
return false;
}
update(mCall, mAudioSegment);
mRecording.update(mCall);
publish();
return false;
}
/**
* Completes the call and its recording.
*/
void complete()
{
update(mCall, mAudioSegment);
mRecording.complete(mCall);
mCall.setEndTime(mAudioSegment.hasAudio() ? mAudioSegment.getEndTimestamp() : System.currentTimeMillis());
mCall.setCallState(CallState.COMPLETE);
publish();
}
/**
* Saves and broadcasts a snapshot of the call when it changed.
*/
private void publish()
{
String signature = getSignature(mCall);
if(!Objects.equals(signature, mLastSignature))
{
mLastSignature = signature;
CallRecord snapshot = mCall.copy();
mPublished = true;
if(mDatabaseManager != null)
{
//The database writer sets the row id on its own copy
mDatabaseManager.save(mHandle, snapshot.copy());
}
mCallBroadcaster.broadcast(snapshot);
}
}
}
}

View File

@@ -49,7 +49,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
{ {
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadata.class); private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadata.class);
private AliasListConfigurationIdentifier mAliasListConfigurationIdentifier;
private SystemConfigurationIdentifier mSystemConfigurationIdentifier; private SystemConfigurationIdentifier mSystemConfigurationIdentifier;
private SiteConfigurationIdentifier mSiteConfigurationIdentifier; private SiteConfigurationIdentifier mSiteConfigurationIdentifier;
private ChannelNameConfigurationIdentifier mChannelNameConfigurationIdentifier; private ChannelNameConfigurationIdentifier mChannelNameConfigurationIdentifier;
@@ -129,19 +128,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
return this; return this;
} }
/**
* Alias list configuration identifier
*/
public AliasListConfigurationIdentifier getAliasListConfigurationIdentifier()
{
return mAliasListConfigurationIdentifier;
}
public boolean hasAliasListConfigurationIdentifier()
{
return mAliasListConfigurationIdentifier != null;
}
/** /**
* System configuration identifier * System configuration identifier
*/ */
@@ -337,15 +323,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
switch(identifier.getForm()) switch(identifier.getForm())
{ {
case ALIAS_LIST: case ALIAS_LIST:
if(identifier instanceof AliasListConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))
{
mAliasListConfigurationIdentifier = (AliasListConfigurationIdentifier)identifier;
}
else
{
mAliasListConfigurationIdentifier = null;
}
if(update.isAdd()) if(update.isAdd())
{ {
mAliasList = mAliasModel.getAliasList((AliasListConfigurationIdentifier)identifier); mAliasList = mAliasModel.getAliasList((AliasListConfigurationIdentifier)identifier);
@@ -362,7 +339,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
} }
} }
} }
broadcastUpdate(ChannelMetadataField.CONFIGURATION_ALIAS_LIST);
break; break;
case CHANNEL: case CHANNEL:
if(identifier instanceof ChannelNameConfigurationIdentifier && (update.isAdd() || update.isSilentAdd())) if(identifier instanceof ChannelNameConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))

View File

@@ -22,7 +22,6 @@ package io.github.dsheirer.channel.metadata;
public enum ChannelMetadataField public enum ChannelMetadataField
{ {
CONFIGURATION_ALIAS_LIST,
CONFIGURATION_CHANNEL, CONFIGURATION_CHANNEL,
CONFIGURATION_FREQUENCY, CONFIGURATION_FREQUENCY,
CONFIGURATION_SITE, CONFIGURATION_SITE,

View File

@@ -0,0 +1,120 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 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.controller;
import com.jidesoft.swing.JideTabbedPane;
import io.github.dsheirer.audio.playback.AudioPanel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.nowplaying.NowPlayingPanel;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.map.MapPanel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerViewPanel;
import java.awt.Dimension;
import jiconfont.icons.font_awesome.FontAwesome;
import io.github.dsheirer.gui.theme.ThemedFontIcon;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ControllerPanel extends JPanel
{
private final static Logger mLog = LoggerFactory.getLogger(ControllerPanel.class);
private static final long serialVersionUID = 1L;
private int mSettingsTabIndex = -1;
private AudioPanel mAudioPanel;
private NowPlayingPanel mNowPlayingPanel;
private MapPanel mMapPanel;
private TunerViewPanel mTunerManagerPanel;
private JideTabbedPane mTabbedPane;
public ControllerPanel(PlaylistManager playlistManager, AudioPlaybackManager audioPlaybackManager,
IconModel iconModel, MapService mapService, SettingsManager settingsManager,
TunerManager tunerManager, UserPreferences userPreferences, boolean detailTabsVisible)
{
mAudioPanel = new AudioPanel(iconModel, userPreferences, settingsManager, audioPlaybackManager,
playlistManager.getAliasModel());
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, detailTabsVisible);
mMapPanel = new MapPanel(mapService, playlistManager.getAliasModel(), iconModel, userPreferences,
playlistManager.getRadioReference() != null ? playlistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(playlistManager));
mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences);
init();
}
/**
* Now playing panel.
*/
public NowPlayingPanel getNowPlayingPanel()
{
return mNowPlayingPanel;
}
private void init()
{
//Disable visual padding. MigLayout otherwise assumes the tabbed pane has native Aqua margins on macOS and
//expands it past the bounds of this panel, clipping the tab content on the left, right and bottom edges.
setLayout(new MigLayout("insets 0 0 0 0, novisualpadding", "[grow,fill]", "[]0[grow,fill]0[]"));
add(mAudioPanel, "wrap");
mTabbedPane = new JideTabbedPane()
{
@Override
public void setSelectedIndex(int index)
{
if(index == mSettingsTabIndex)
{
MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest());
}
else
{
super.setSelectedIndex(index);
}
}
};
mTabbedPane.setFont(this.getFont());
mTabbedPane.addTab("Now Playing", mNowPlayingPanel);
mTabbedPane.addTab("Map", mMapPanel);
mTabbedPane.addTab("Tuners", mTunerManagerPanel);
Icon playIcon = new ThemedFontIcon(FontAwesome.PLAY_CIRCLE_O, 20);
mTabbedPane.addTab("Playlist Editor", playIcon, new JLabel("Show Playlist Manager"));
mSettingsTabIndex = mTabbedPane.getTabCount() - 1;
//Set preferred size to influence the split between these panels
mTabbedPane.setPreferredSize(new Dimension(880, 500));
add(mTabbedPane, "wrap");
}
}

View File

@@ -0,0 +1,105 @@
/*******************************************************************************
* sdr-trunk
* Copyright (C) 2014-2018 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.controller.channel;
import javax.swing.table.AbstractTableModel;
import java.util.List;
/**
* Auto-Start Channel Model
*/
public class AutoStartChannelModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
public static final int COLUMN_ORDER = 0;
public static final int COLUMN_SYSTEM = 1;
public static final int COLUMN_SITE = 2;
public static final int COLUMN_NAME = 3;
public static final int COLUMN_DECODER = 4;
private static final String[] COLUMN_NAMES = new String[] {"Order", "System", "Site", "Name", "Decoder"};
private List<Channel> mChannels;
public AutoStartChannelModel(List<Channel> autoStartChannels)
{
mChannels = autoStartChannels;
}
@Override
public int getRowCount()
{
return mChannels.size();
}
@Override
public int getColumnCount()
{
return COLUMN_NAMES.length;
}
@Override
public String getColumnName(int columnIndex)
{
if(columnIndex < COLUMN_NAMES.length)
{
return COLUMN_NAMES[columnIndex];
}
return null;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
Channel channel = mChannels.get(rowIndex);
switch(columnIndex)
{
case COLUMN_ORDER:
return channel.getAutoStartOrder();
case COLUMN_SYSTEM:
return channel.getSystem();
case COLUMN_SITE:
return channel.getSite();
case COLUMN_NAME:
return channel.getName();
case COLUMN_DECODER:
return channel.getDecodeConfiguration().getDecoderType().getShortDisplayString();
}
return null;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
throw new IllegalArgumentException("Not yet implemented");
}
}

View File

@@ -18,7 +18,6 @@
*/ */
package io.github.dsheirer.controller.channel; package io.github.dsheirer.controller.channel;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@@ -84,8 +83,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
private BooleanProperty mProcessing = new SimpleBooleanProperty(); private BooleanProperty mProcessing = new SimpleBooleanProperty();
private BooleanProperty mAutoStart = new SimpleBooleanProperty(); private BooleanProperty mAutoStart = new SimpleBooleanProperty();
//Enabled for new channels. Channels loaded from a playlist without the setting keep it disabled, see fromXml().
private BooleanProperty mAutoAddTalkerAliases = new SimpleBooleanProperty(true);
private IntegerProperty mAutoStartOrder = new SimpleIntegerProperty(); private IntegerProperty mAutoStartOrder = new SimpleIntegerProperty();
private boolean mSelected; private boolean mSelected;
private List<TunerChannel> mTunerChannels = null; private List<TunerChannel> mTunerChannels = null;
@@ -126,19 +123,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
mChannelID = UNIQUE_ID++; mChannelID = UNIQUE_ID++;
} }
/**
* Creates a channel for deserialization from a playlist. Settings added after a channel was saved take their
* legacy (disabled) value when the playlist doesn't specify them, instead of the default for new channels, so that
* existing channels don't change behavior.
*/
@JsonCreator
private static Channel fromXml()
{
Channel channel = new Channel();
channel.setAutoAddTalkerAliases(false);
return channel;
}
/** /**
* Creates a (new) deep copy of this channel * Creates a (new) deep copy of this channel
*/ */
@@ -150,7 +134,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
channel.setAliasListName(mAliasListName.get()); channel.setAliasListName(mAliasListName.get());
channel.setAutoStart(mAutoStart.get()); channel.setAutoStart(mAutoStart.get());
channel.setAutoStartOrder(mAutoStartOrder.get()); channel.setAutoStartOrder(mAutoStartOrder.get());
channel.setAutoAddTalkerAliases(mAutoAddTalkerAliases.get());
AuxDecodeConfiguration auxCopy = new AuxDecodeConfiguration(); AuxDecodeConfiguration auxCopy = new AuxDecodeConfiguration();
@@ -526,36 +509,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
mAutoStart.set(autoStart); mAutoStart.set(autoStart);
} }
/**
* Auto-add talker aliases property
*/
public BooleanProperty autoAddTalkerAliasesProperty()
{
return mAutoAddTalkerAliases;
}
/**
* Indicates if decoded talker aliases are automatically added to the channel's alias list as radio aliases, using
* the talker alias as the alias name.
*
* @return true if talker aliases are automatically added to the alias list
*/
@JacksonXmlProperty(isAttribute = true, localName = "auto_add_talker_aliases")
public boolean isAutoAddTalkerAliases()
{
return mAutoAddTalkerAliases.get();
}
/**
* Sets automatically adding decoded talker aliases to the channel's alias list.
*
* @param autoAdd true to automatically add talker aliases to the alias list
*/
public void setAutoAddTalkerAliases(boolean autoAdd)
{
mAutoAddTalkerAliases.set(autoAdd);
}
/** /**
* Auto-start order. Specifies an optional ordering for channels so that when the application starts up, * Auto-start order. Specifies an optional ordering for channels so that when the application starts up,
* the channels can be started in a user-specified order. * the channels can be started in a user-specified order.

View File

@@ -0,0 +1,242 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 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.controller.channel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.util.ThreadPool;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class ChannelAutoStartFrame extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelAutoStartFrame.class);
private Listener<ChannelEvent> mChannelEventListener;
private List<Channel> mChannels;
private JLabel mCountdownLabel;
private JButton mStartButton;
private JButton mCancelButton;
private JTable mChannelTable;
private AtomicBoolean mChannelsStarted = new AtomicBoolean();
private int mAutoStartTimeoutSeconds;
private ScheduledFuture<?> mTimerFuture;
/**
* Creates and displays a channel auto-start gui for presenting the user with a list of channels that
* will be automatically started once the countdown timer reaches zero, or the user chooses to start
* now or cancel.
*
* @param listener to receive channel start/enable request(s)
* @param channels to auto-start
*/
public ChannelAutoStartFrame(Listener<ChannelEvent> listener, List<Channel> channels, UserPreferences userPreferences)
{
mChannelEventListener = listener;
mChannels = channels;
mAutoStartTimeoutSeconds = userPreferences.getApplicationPreference().getChannelAutoStartTimeout();
init();
EventQueue.invokeLater(() -> {
setVisible(true);
toFront();
startTimer();
});
}
private void init()
{
setTitle("Auto-Start Channels");
setSize(new Dimension(400, 300));
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent event)
{
mLog.info("Channel auto-start canceled by user - window closed");
stopTimer();
super.windowClosing(event);
}
});
JPanel panel = new JPanel();
panel.setLayout(new MigLayout("", "[grow,fill][grow,fill]",
"[][][grow,fill][]"));
panel.add(new JLabel("The following channels will be automatically"), "span");
mCountdownLabel = new JLabel(getCountdownText(mAutoStartTimeoutSeconds));
panel.add(mCountdownLabel, "span");
panel.add(new JScrollPane(getChannelTable()), "span");
mStartButton = new JButton("Start Now");
mStartButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLog.info("Starting [" + mChannels.size() + "] channels now - user invoked");
startChannels();
stopTimer();
}
});
panel.add(mStartButton);
mCancelButton = new JButton("Cancel");
mCancelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLog.info("Channel auto-start canceled by user");
stopTimer();
}
});
panel.add(mCancelButton);
setContentPane(panel);
}
private String getCountdownText(int value)
{
return "started in: " + value + " seconds.";
}
/**
* Updates the countdown text label on the swing event thread
*
* @param value for the countdown
*/
private void updateCountdownText(final int value)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
mCountdownLabel.setText(getCountdownText(value));
}
});
}
/**
* Creates (once) a table of auto-start channels
*/
private JTable getChannelTable()
{
if(mChannelTable == null)
{
AutoStartChannelModel model = new AutoStartChannelModel(mChannels);
mChannelTable = new JTable(model);
}
return mChannelTable;
}
/**
* Sends an enable (ie start) request for each of the auto start channels.
*
* This method is thread-safe and will only be executed once.
*
* Although the redundant channel-start request would be ignored, this once-only will prevent the chance
* that both the timer and the user would attempt to start the channels at the same time.
*/
private void startChannels()
{
if(mChannelsStarted.compareAndSet(false, true))
{
if(mChannelEventListener != null)
{
for(Channel channel : mChannels)
{
mChannelEventListener.receive(new ChannelEvent(channel, ChannelEvent.Event.REQUEST_ENABLE));
}
}
}
}
/**
* Starts the countdown timer to fire once a second.
*/
private void startTimer()
{
if(mTimerFuture == null)
{
mTimerFuture = ThreadPool.SCHEDULED.scheduleAtFixedRate(new CountdownTimer(), 0, 1, TimeUnit.SECONDS);
}
}
/**
* Stops the countdown timer and disposes this frame
*/
private void stopTimer()
{
if(mTimerFuture != null)
{
mTimerFuture.cancel(true);
mTimerFuture = null;
}
EventQueue.invokeLater(() -> dispose());
}
/**
* Updates the countdown text and auto-starts the channels once the timer falls below zero.
*/
public class CountdownTimer implements Runnable
{
private int mCount = mAutoStartTimeoutSeconds;
@Override
public void run()
{
if(mCount >= 0)
{
updateCountdownText(mCount);
mCount--;
}
else
{
mLog.info("Starting [" + mChannels.size() + "] now - timer invoked");
startChannels();
stopTimer();
}
}
}
}

View File

@@ -1,215 +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.controller.channel;
import io.github.dsheirer.gui.ApplicationIcons;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.util.ThreadPool;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Lists the channels that are set to start automatically and starts them when the countdown ends. The user can
* start them now, or cancel by pressing Cancel or closing the window.
*/
public class ChannelAutoStartWindow
{
private static final Logger mLog = LoggerFactory.getLogger(ChannelAutoStartWindow.class);
private final Listener<ChannelEvent> mChannelEventListener;
private final List<Channel> mChannels;
private final int mTimeoutSeconds;
private final AtomicBoolean mFinished = new AtomicBoolean();
private final Stage mStage = new Stage();
private final Label mCountdownLabel = new Label();
private final ProgressBar mProgressBar = new ProgressBar(1.0);
private final Timeline mTimeline;
private int mRemainingSeconds;
/**
* Constructs an instance. JavaFX thread only.
* @param listener to receive the channel start requests
* @param channels to start, in auto-start order
* @param userPreferences for the countdown length
* @param owner window, or null
*/
public ChannelAutoStartWindow(Listener<ChannelEvent> listener, List<Channel> channels,
UserPreferences userPreferences, Window owner)
{
mChannelEventListener = listener;
mChannels = channels;
mTimeoutSeconds = Math.max(0, userPreferences.getApplicationPreference().getChannelAutoStartTimeout());
mRemainingSeconds = mTimeoutSeconds;
Label title = new Label("Starting " + channels.size() + (channels.size() == 1 ? " channel" : " channels"));
title.setStyle("-fx-font-size: 1.25em; -fx-font-weight: bold;");
mProgressBar.setMaxWidth(Double.MAX_VALUE);
TableView<Channel> table = new TableView<>(FXCollections.observableArrayList(channels));
table.getColumns().addAll(List.of(
column("Order", 60, channel -> String.valueOf(channel.getAutoStartOrder())),
column("System", 140, Channel::getSystem),
column("Site", 120, Channel::getSite),
column("Name", 180, Channel::getName),
column("Decoder", 100, channel -> channel.getDecodeConfiguration().getDecoderType()
.getShortDisplayString())));
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN);
VBox.setVgrow(table, Priority.ALWAYS);
Button startButton = new Button("Start Now");
startButton.setDefaultButton(true);
startButton.setOnAction(event -> {
mLog.info("Starting [" + mChannels.size() + "] channels now - user invoked");
finish(true);
});
Button cancelButton = new Button("Cancel");
cancelButton.setCancelButton(true);
cancelButton.setOnAction(event -> {
mLog.info("Channel auto-start canceled by user");
finish(false);
});
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox buttons = new HBox(8, spacer, cancelButton, startButton);
buttons.setAlignment(Pos.CENTER_RIGHT);
VBox root = new VBox(8, title, mCountdownLabel, mProgressBar, table, buttons);
root.setPadding(new Insets(12));
Scene scene = new Scene(root, 640, 340);
ThemeManager.getInstance().register(scene);
mStage.setScene(scene);
mStage.setTitle("Auto-Start Channels");
ApplicationIcons.apply(mStage);
if(owner != null)
{
mStage.initOwner(owner);
}
mStage.setOnCloseRequest(event -> {
mLog.info("Channel auto-start canceled by user - window closed");
finish(false);
});
mTimeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> tick()));
mTimeline.setCycleCount(Timeline.INDEFINITE);
updateCountdown();
}
/**
* Shows the window and starts the countdown. JavaFX thread only.
*/
public void show()
{
mStage.show();
mStage.toFront();
if(mTimeoutSeconds == 0)
{
mLog.info("Starting [" + mChannels.size() + "] now - no auto-start delay");
finish(true);
}
else
{
mTimeline.play();
}
}
private void tick()
{
mRemainingSeconds--;
if(mRemainingSeconds <= 0)
{
mLog.info("Starting [" + mChannels.size() + "] now - timer invoked");
finish(true);
}
else
{
updateCountdown();
}
}
private void updateCountdown()
{
mCountdownLabel.setText("These channels start automatically in " + mRemainingSeconds +
(mRemainingSeconds == 1 ? " second." : " seconds."));
mProgressBar.setProgress(mTimeoutSeconds > 0 ? (double)mRemainingSeconds / mTimeoutSeconds : 0.0);
}
/**
* Stops the countdown, closes the window and optionally starts the channels. Only the first call has an
* effect, so that the timer and the user can't both start the channels.
*/
private void finish(boolean start)
{
if(!mFinished.compareAndSet(false, true))
{
return;
}
mTimeline.stop();
mStage.close();
if(start && mChannelEventListener != null)
{
//Starting channels can block while tuners start, so start them off the JavaFX thread, in order
ThreadPool.CACHED.submit(() -> {
for(Channel channel: mChannels)
{
mChannelEventListener.receive(new ChannelEvent(channel, ChannelEvent.Event.REQUEST_ENABLE));
}
});
}
}
private static TableColumn<Channel,String> column(String title, double width, Function<Channel,String> value)
{
TableColumn<Channel,String> column = new TableColumn<>(title);
column.setPrefWidth(width);
column.setCellValueFactory(param -> new ReadOnlyStringWrapper(value.apply(param.getValue())));
return column;
}
}

View File

@@ -30,11 +30,13 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.swing.AbstractListModel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ChannelMapModel public class ChannelMapModel extends AbstractListModel<ChannelMap>
{ {
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(ChannelMapModel.class); private final static Logger mLog = LoggerFactory.getLogger(ChannelMapModel.class);
private ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor()); private ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor());
@@ -106,6 +108,17 @@ public class ChannelMapModel
*/ */
public void broadcast(ChannelMapEvent event) public void broadcast(ChannelMapEvent event)
{ {
if(event.getEvent() == ChannelMapEvent.Event.CHANGE ||
event.getEvent() == ChannelMapEvent.Event.RENAME)
{
int index = mChannelMaps.indexOf(event.getChannelMap());
if(index >= 0)
{
fireContentsChanged(this, index, index);
}
}
mEventBroadcaster.broadcast(event); mEventBroadcaster.broadcast(event);
} }
@@ -129,6 +142,10 @@ public class ChannelMapModel
{ {
mChannelMaps.add(channelMap); mChannelMaps.add(channelMap);
int index = mChannelMaps.indexOf(channelMap);
fireIntervalAdded(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.ADD)); broadcast(new ChannelMapEvent(channelMap, Event.ADD));
} }
} }
@@ -140,9 +157,36 @@ public class ChannelMapModel
{ {
if(mChannelMaps.contains(channelMap)) if(mChannelMaps.contains(channelMap))
{ {
int index = mChannelMaps.indexOf(channelMap);
mChannelMaps.remove(channelMap); mChannelMaps.remove(channelMap);
fireIntervalRemoved(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.DELETE)); broadcast(new ChannelMapEvent(channelMap, Event.DELETE));
} }
} }
/**
* Size/Number of channel maps in this model
*/
@Override
public int getSize()
{
return mChannelMaps.size();
}
/**
* Returns the channel map at the specified index
*/
@Override
public ChannelMap getElementAt(int index)
{
if(index <= mChannelMaps.size())
{
return mChannelMaps.get(index);
}
return null;
}
} }

View File

@@ -0,0 +1,295 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2020 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.controller.channel.map;
import javax.swing.table.AbstractTableModel;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ChannelRangeModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private static final int START = 0;
private static final int STOP = 1;
private static final int BASE = 2;
private static final int SIZE = 3;
private static final int ERROR = 4;
protected int[] mColumnWidths = { 110, 110, 110, -1, 80 };
protected String[] mHeaders = new String[] { "Begin",
"End",
"Base",
"Size",
"Error" };
private List<ChannelRange> mRanges = new CopyOnWriteArrayList<>();
private ChannelRangeEventListener mListener;
public ChannelRangeModel()
{
}
public void setListener( ChannelRangeEventListener listener )
{
mListener = listener;
}
private void broadcastChange()
{
if( mListener != null )
{
mListener.channelRangesChanged();
}
}
public void clear()
{
for( ChannelRange range: mRanges )
{
removeRange( range );
}
broadcastChange();
}
public List<ChannelRange> getChannelRanges()
{
return mRanges;
}
public void addRanges( List<ChannelRange> ranges )
{
for( ChannelRange range: ranges )
{
addRange( range );
}
broadcastChange();
}
public void addRange( ChannelRange range )
{
if( range != null && !mRanges.contains( range ) )
{
mRanges.add( range );
int index = mRanges.indexOf( range );
fireTableRowsInserted( index, index );
}
validate();
broadcastChange();
}
public void removeRange( ChannelRange range )
{
if( range != null && mRanges.contains( range ) )
{
int index = mRanges.indexOf( range );
mRanges.remove( range );
fireTableRowsDeleted( index, index );
}
validate();
broadcastChange();
}
public int[] getColumnWidths()
{
return mColumnWidths;
}
public void setColumnWidths( int[] widths )
{
if( widths.length != mHeaders.length )
{
throw new IllegalArgumentException( "ChannelMapRangeModel - "
+ "column widths array should have " +
mHeaders.length + " elements" );
}
else
{
mColumnWidths = widths;
}
}
@Override
public int getRowCount()
{
return mRanges.size();
}
@Override
public int getColumnCount()
{
return mHeaders.length;
}
public String getColumnName( int column )
{
return mHeaders[ column ];
}
public ChannelRange getChannelRange( int index )
{
if( index < mRanges.size() )
{
return mRanges.get( index );
}
return null;
}
@Override
public Object getValueAt( int rowIndex, int columnIndex )
{
ChannelRange range = getChannelRange( rowIndex );
if( range != null )
{
switch( columnIndex )
{
case START:
return range.getFirstChannelNumber();
case STOP:
return range.getLastChannelNumber();
case BASE:
return range.getBaseFrequency();
case SIZE:
return range.getStepSize();
case ERROR:
StringBuilder sb = new StringBuilder();
if( !range.isValid() )
{
sb.append( "Sequence" );
}
if( range.isOverlapping() )
{
if( sb.length() > 0 )
{
sb.append( "," );
}
sb.append( "Overlap" );
}
return sb.toString();
default:
break;
}
}
return null;
}
/**
* Validates each of the channel ranges for overlap
*/
private void validate()
{
for( int x = 0; x < mRanges.size(); x++ )
{
mRanges.get( x ).setOverlapping( false );
fireTableCellUpdated( x, ERROR );
}
for( int x = 0; x < mRanges.size(); x++ )
{
for( int y = x + 1; y < mRanges.size(); y++ )
{
if( mRanges.get( x ).overlaps( mRanges.get( y ) ) )
{
mRanges.get( x ).setOverlapping( true );
fireTableCellUpdated( x, ERROR );
mRanges.get( y ).setOverlapping( true );
fireTableCellUpdated( y, ERROR );
}
}
}
}
public boolean isCellEditable( int row, int column )
{
return row < mRanges.size() && column != ERROR;
}
public void setValueAt( Object value, int row, int column )
{
int parsedValue = -1;
try
{
parsedValue = Integer.parseInt( (String)value );
}
catch( Exception e )
{
//Do nothing ... we'll use 0
}
if( parsedValue >= 0 )
{
ChannelRange range = getChannelRange( row );
if( range != null )
{
switch( column )
{
case START:
range.setFirstChannelNumber( parsedValue );
break;
case STOP:
range.setLastChannelNumber( parsedValue );
break;
case BASE:
range.setBaseFrequency( parsedValue );
break;
case SIZE:
range.setStepSize( parsedValue );
break;
}
validate();
broadcastChange();
}
else
{
throw new IllegalArgumentException( "Invalid channel range row index" );
}
}
}
public interface ChannelRangeEventListener
{
public void channelRangesChanged();
}
}

View File

@@ -1,347 +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.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.github.dsheirer.database.call.CallRepository;
import io.github.dsheirer.database.call.ICallRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* An open connection pool to one database and schema, with the sdrtrunk schema installation logic.
*/
public class CallDatabase implements AutoCloseable
{
private static final Logger LOGGER = LoggerFactory.getLogger(CallDatabase.class);
/**
* Version of the sdrtrunk tables that this release creates. Increment and add an upgrade step to
* {@link #getUpgradeStatements(int)} when the tables change.
*/
public static final int SCHEMA_VERSION = 2;
public static final String SCHEMA_INFO_TABLE = "schema_info";
private final DatabaseConfiguration mConfiguration;
private final HikariDataSource mDataSource;
private final ICallRepository mCallRepository;
/**
* Opens a connection pool for the configuration. The schema isn't created or checked.
* @param configuration for the database
* @param databaseDirectory for the built-in database files
* @throws SQLException if the database can't be reached
*/
public CallDatabase(DatabaseConfiguration configuration, Path databaseDirectory) throws SQLException
{
mConfiguration = configuration;
mCallRepository = new CallRepository(configuration.schema());
if(configuration.type() == DatabaseType.H2)
{
try
{
Files.createDirectories(databaseDirectory);
}
catch(Exception e)
{
throw new SQLException("Unable to create the database directory [" + databaseDirectory + "]", e);
}
}
try
{
Class.forName(configuration.type().getDialect().getDriverClass());
}
catch(ClassNotFoundException cnfe)
{
throw new SQLException("Database driver isn't available: " + configuration.type().getDialect().getDriverClass(), cnfe);
}
HikariConfig config = new HikariConfig();
config.setPoolName("sdrtrunk-db-" + configuration.type().name().toLowerCase(Locale.ROOT));
config.setJdbcUrl(configuration.getJdbcUrl(databaseDirectory));
config.setDriverClassName(configuration.type().getDialect().getDriverClass());
if(configuration.type().isNetwork())
{
config.setUsername(configuration.user());
config.setPassword(configuration.password());
}
else
{
config.setUsername("sa");
config.setPassword("");
}
config.setMaximumPoolSize(4);
config.setMinimumIdle(1);
config.setConnectionTimeout(10_000);
config.setValidationTimeout(5_000);
//Fail immediately when the database can't be reached, so the user gets an answer
config.setInitializationFailTimeout(1);
try
{
mDataSource = new HikariDataSource(config);
}
catch(Exception e)
{
Throwable cause = e.getCause() != null ? e.getCause() : e;
throw new SQLException("Unable to connect to " + configuration.getDescription() + ": " +
cause.getMessage(), cause);
}
}
/**
* Configuration for this database
*/
public DatabaseConfiguration getConfiguration()
{
return mConfiguration;
}
/**
* Repository for the calls table in this schema
*/
public ICallRepository getCallRepository()
{
return mCallRepository;
}
/**
* Pooled connection. Close it to return it to the pool.
*/
public Connection getConnection() throws SQLException
{
return mDataSource.getConnection();
}
/**
* Determines whether the configured schema exists and whether it holds sdrtrunk tables.
*/
public SchemaStatus getSchemaStatus() throws SQLException
{
try(Connection connection = getConnection())
{
return getSchemaStatus(connection, mConfiguration.schema());
}
}
/**
* Determines the status of the named schema.
*/
public static SchemaStatus getSchemaStatus(Connection connection, String schema) throws SQLException
{
boolean schemaExists;
try(PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " +
"information_schema.schemata WHERE LOWER(schema_name) = ?"))
{
statement.setString(1, schema.toLowerCase(Locale.ROOT));
try(ResultSet rs = statement.executeQuery())
{
schemaExists = rs.next() && rs.getLong(1) > 0;
}
}
if(!schemaExists)
{
return SchemaStatus.MISSING;
}
try(PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " +
"information_schema.tables WHERE LOWER(table_schema) = ? AND LOWER(table_name) = ?"))
{
statement.setString(1, schema.toLowerCase(Locale.ROOT));
statement.setString(2, SCHEMA_INFO_TABLE);
try(ResultSet rs = statement.executeQuery())
{
return rs.next() && rs.getLong(1) > 0 ? SchemaStatus.SDRTRUNK : SchemaStatus.EMPTY;
}
}
}
/**
* Number of calls stored in the schema, or 0 if the schema doesn't have sdrtrunk tables.
*/
public long getCallCount() throws SQLException
{
if(getSchemaStatus() != SchemaStatus.SDRTRUNK)
{
return 0;
}
try(Connection connection = getConnection())
{
return mCallRepository.count(connection);
}
}
/**
* Creates the schema and tables when they don't exist and upgrades the tables of an older version.
* @throws SQLException on error, or if the schema was created by a newer version of sdrtrunk
*/
public void install() throws SQLException
{
DatabaseType type = mConfiguration.type();
String schema = mConfiguration.schema();
try(Connection connection = getConnection(); Statement statement = connection.createStatement())
{
statement.execute(type.getDialect().getCreateSchemaStatement(schema));
statement.execute("CREATE TABLE IF NOT EXISTS " + schema + "." + SCHEMA_INFO_TABLE +
" (version INT NOT NULL)");
int version = getVersion(connection);
if(version > SCHEMA_VERSION)
{
throw new SQLException("Schema [" + schema + "] was created by a newer version of sdrtrunk (schema " +
"version " + version + "). This version supports schema version " + SCHEMA_VERSION + ".");
}
if(version < SCHEMA_VERSION)
{
for(String sql: getUpgradeStatements(version))
{
statement.execute(sql);
}
if(version == 0)
{
statement.executeUpdate("INSERT INTO " + schema + "." + SCHEMA_INFO_TABLE +
" (version) VALUES (" + SCHEMA_VERSION + ")");
}
else
{
statement.executeUpdate("UPDATE " + schema + "." + SCHEMA_INFO_TABLE + " SET version = " +
SCHEMA_VERSION);
}
LOGGER.info("Installed sdrtrunk schema version " + SCHEMA_VERSION + " in " +
mConfiguration.getDescription() + (version > 0 ? " (upgraded from version " + version + ")" : ""));
}
}
}
/**
* Statements that bring the tables from the version argument up to the current version.
*/
private List<String> getUpgradeStatements(int fromVersion)
{
List<String> statements = new ArrayList<>();
if(fromVersion < 1)
{
statements.addAll(CallRepository.getCreateStatements(mConfiguration.type().getDialect(), mConfiguration.schema()));
}
//Version 2: talkgroups patched into patch group calls
if(fromVersion < 2)
{
statements.addAll(CallRepository.getPatchedTalkgroupCreateStatements(mConfiguration.schema()));
}
return statements;
}
/**
* Installed schema version, or 0 when nothing is installed.
*/
private int getVersion(Connection connection) throws SQLException
{
try(Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT MAX(version) FROM " + mConfiguration.schema() + "." +
SCHEMA_INFO_TABLE))
{
return rs.next() ? rs.getInt(1) : 0;
}
}
/**
* Drops the schema with all of its tables and then installs an empty sdrtrunk schema.
*/
public void clear() throws SQLException
{
try(Connection connection = getConnection(); Statement statement = connection.createStatement())
{
statement.execute(mConfiguration.type().getDialect().getDropSchemaStatement(mConfiguration.schema()));
}
install();
}
/**
* Suggests an unused schema name derived from the configured schema name (e.g. sdrtrunk_2).
*/
public String suggestSchemaName() throws SQLException
{
try(Connection connection = getConnection())
{
String base = mConfiguration.schema();
for(int x = 2; x < 1000; x++)
{
String candidate = base + "_" + x;
if(candidate.length() <= 63 && getSchemaStatus(connection, candidate) == SchemaStatus.MISSING)
{
return candidate;
}
}
}
return mConfiguration.schema() + "_new";
}
/**
* Indicates if the named schema exists in this database.
*/
public boolean schemaExists(String schema) throws SQLException
{
try(Connection connection = getConnection())
{
return getSchemaStatus(connection, schema) != SchemaStatus.MISSING;
}
}
@Override
public void close()
{
if(!mDataSource.isClosed())
{
mDataSource.close();
}
}
}

View File

@@ -1,158 +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.database;
import java.nio.file.Path;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Connection settings for a call database.
*
* @param type of database engine
* @param host name or address of a network database server (ignored for H2)
* @param port of the network database server (ignored for H2)
* @param database name to connect to (PostgreSQL only)
* @param schema name that holds the sdrtrunk tables
* @param user name for a network database server
* @param password for a network database server
*/
public record DatabaseConfiguration(DatabaseType type, String host, int port, String database, String schema,
String user, String password)
{
public static final String DEFAULT_SCHEMA = "sdrtrunk";
/**
* Schema names are restricted to unquoted SQL identifiers so that they can be used in statements without quoting
* and so that they mean the same thing across all engines (H2 upper-cases unquoted names, the others don't).
*/
private static final Pattern SCHEMA_PATTERN = Pattern.compile("[a-z][a-z0-9_]{0,62}");
public DatabaseConfiguration
{
Objects.requireNonNull(type, "type");
host = host == null ? "" : host.trim();
database = database == null ? "" : database.trim();
schema = schema == null || schema.isBlank() ? DEFAULT_SCHEMA : schema.trim().toLowerCase();
user = user == null ? "" : user;
password = password == null ? "" : password;
}
/**
* Default configuration: the built-in H2 database with the default schema.
*/
public static DatabaseConfiguration getDefault()
{
return new DatabaseConfiguration(DatabaseType.H2, "", 0, "", DEFAULT_SCHEMA, "", "");
}
/**
* Copy of this configuration with a different schema name.
*/
public DatabaseConfiguration withSchema(String schemaName)
{
return new DatabaseConfiguration(type, host, port, database, schemaName, user, password);
}
/**
* Indicates if the schema name is a valid, unquoted identifier.
*/
public static boolean isValidSchemaName(String schema)
{
return schema != null && SCHEMA_PATTERN.matcher(schema).matches();
}
/**
* Validates this configuration.
* @return null if valid, or a description of the problem.
*/
public String validate()
{
if(!isValidSchemaName(schema))
{
return "Schema name must start with a letter and contain only lower case letters, digits and underscores " +
"(max 63 characters)";
}
if(type.isNetwork())
{
if(host.isEmpty())
{
return "Host is required";
}
if(port <= 0 || port > 65535)
{
return "Port must be in the range 1 - 65535";
}
if(user.isEmpty())
{
return "User name is required";
}
}
if(type.requiresDatabaseName() && database.isEmpty())
{
return "Database name is required";
}
return null;
}
/**
* JDBC URL for this configuration.
* @param databaseDirectory for the built-in H2 database files
*/
public String getJdbcUrl(Path databaseDirectory)
{
return type.getDialect().getJdbcUrl(this, databaseDirectory);
}
/**
* Short description for the user, without the password.
*/
public String getDescription()
{
return switch(type)
{
case H2 -> type + " - schema [" + schema + "]";
case MARIADB -> type + " " + user + "@" + host + ":" + port + " - schema [" + schema + "]";
case POSTGRESQL -> type + " " + user + "@" + host + ":" + port + "/" + database + " - schema [" +
schema + "]";
};
}
/**
* Indicates if this configuration refers to the same database and schema as the other configuration (ignoring
* credentials).
*/
public boolean isSameLocation(DatabaseConfiguration other)
{
return other != null && type == other.type && schema.equals(other.schema) &&
(!type.isNetwork() || (host.equalsIgnoreCase(other.host) && port == other.port &&
database.equals(other.database)));
}
@Override
public String toString()
{
return getDescription();
}
}

View File

@@ -1,45 +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.database;
/**
* Call database status change notification
*
* @param type of event
* @param configuration of the current database
* @param errorMessage for an ERROR event, otherwise null
*/
public record DatabaseEvent(Type type, DatabaseConfiguration configuration, String errorMessage)
{
public enum Type
{
/**
* Database opened, or a different database was selected
*/
CONNECTED,
/**
* Database couldn't be opened or the connection was lost
*/
ERROR,
/**
* Stored calls changed outside of the live call updates, for example by an age-off rule
*/
CALLS_CHANGED
}
}

View File

@@ -1,718 +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.database;
import io.github.dsheirer.database.ageoff.AgeOffManager;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.database.call.ICallRepository;
import io.github.dsheirer.database.call.CallSearchCriteria;
import io.github.dsheirer.database.call.CallState;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.controller.NamingThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Manages the call database: opens the selected database at startup, writes call records in the background, runs the
* age-off rules and switches between databases (with optional transfer of the existing calls).
*
* All writes, the age-off rules and database switches run on a single database thread, so they never overlap.
* Searches run on a separate thread so that a long write doesn't block the user interface.
*
* Call recording doesn't depend on the database: when the database is unavailable, call updates are held in memory
* (newest update per call) and written when the database becomes available again.
*/
public class DatabaseManager
{
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseManager.class);
private static final long FLUSH_INTERVAL_MS = 250;
private static final long RETRY_INTERVAL_MS = 30_000;
private static final int MAX_PENDING_CALLS = 20_000;
private static final int TRANSFER_PAGE_SIZE = 1000;
private final UserPreferences mUserPreferences;
private final ScheduledExecutorService mDatabaseExecutor =
Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("sdrtrunk call database"));
private final ExecutorService mQueryExecutor =
Executors.newSingleThreadExecutor(new NamingThreadFactory("sdrtrunk call database query"));
private final Broadcaster<DatabaseEvent> mEventBroadcaster = new Broadcaster<>();
private final Broadcaster<CallRecord> mSavedCallBroadcaster = new Broadcaster<>();
private final Map<CallHandle,CallRecord> mPendingCalls = new LinkedHashMap<>();
private final AgeOffManager mAgeOffManager;
private volatile CallDatabase mDatabase;
private volatile String mErrorMessage;
private volatile int mGeneration = 1;
private long mNextRetry;
private ScheduledFuture<?> mFlushFuture;
/**
* Constructs an instance
* @param userPreferences for the database selection and age-off rules
*/
public DatabaseManager(UserPreferences userPreferences)
{
mUserPreferences = userPreferences;
mAgeOffManager = new AgeOffManager(this, userPreferences);
}
/**
* Opens the selected database, installs or upgrades the sdrtrunk schema and starts the background writer.
* Blocks until the database is open (or failed to open) so that calls from the first channels are stored.
*/
public void start()
{
try
{
mDatabaseExecutor.submit(this::openConfiguredDatabase).get(30, TimeUnit.SECONDS);
}
catch(Exception e)
{
LOGGER.error("Timeout or error while opening the call database", e);
}
mFlushFuture = mDatabaseExecutor.scheduleWithFixedDelay(this::flush, FLUSH_INTERVAL_MS, FLUSH_INTERVAL_MS,
TimeUnit.MILLISECONDS);
mAgeOffManager.start(mDatabaseExecutor);
}
/**
* Writes any remaining call updates and closes the database.
*/
public void stop()
{
mAgeOffManager.stop();
if(mFlushFuture != null)
{
mFlushFuture.cancel(false);
}
try
{
mDatabaseExecutor.submit(() -> {
flush();
closeDatabase();
}).get(15, TimeUnit.SECONDS);
}
catch(Exception e)
{
LOGGER.error("Error while closing the call database", e);
}
mDatabaseExecutor.shutdownNow();
mQueryExecutor.shutdownNow();
}
/**
* Directory for the built-in database files
*/
public Path getDatabaseDirectory()
{
return mUserPreferences.getDirectoryPreference().getDirectoryDatabase();
}
/**
* Opens the database from the user preferences. Database thread only.
*/
private void openConfiguredDatabase()
{
DatabaseConfiguration configuration = mUserPreferences.getDatabasePreference().getDatabaseConfiguration();
try
{
CallDatabase database = new CallDatabase(configuration, getDatabaseDirectory());
try
{
database.install();
try(Connection connection = database.getConnection())
{
int interrupted = database.getCallRepository().markInterrupted(connection);
if(interrupted > 0)
{
LOGGER.info("Marked " + interrupted + " calls from the previous session as interrupted");
}
}
}
catch(SQLException se)
{
database.close();
throw se;
}
mDatabase = database;
mErrorMessage = null;
LOGGER.info("Call database opened: " + configuration.getDescription());
broadcast(DatabaseEvent.Type.CONNECTED);
}
catch(SQLException se)
{
mErrorMessage = se.getMessage();
mNextRetry = System.currentTimeMillis() + RETRY_INTERVAL_MS;
LOGGER.error("Unable to open the call database [" + configuration.getDescription() + "] - " +
se.getMessage());
broadcast(DatabaseEvent.Type.ERROR);
}
}
private void closeDatabase()
{
CallDatabase database = mDatabase;
mDatabase = null;
if(database != null)
{
database.close();
}
}
/**
* Currently open database, or null if the database isn't available.
*/
public CallDatabase getDatabase()
{
return mDatabase;
}
/**
* Current database configuration (from the preferences).
*/
public DatabaseConfiguration getConfiguration()
{
CallDatabase database = mDatabase;
return database != null ? database.getConfiguration() :
mUserPreferences.getDatabasePreference().getDatabaseConfiguration();
}
/**
* Indicates if the database is open
*/
public boolean isConnected()
{
return mDatabase != null;
}
/**
* Description of the last error opening the database, or null.
*/
public String getErrorMessage()
{
return mErrorMessage;
}
/**
* Creates a handle that tracks the database row of one call across updates.
*/
public CallHandle createHandle()
{
return new CallHandle();
}
/**
* Queues a snapshot of the call for insertion (first time) or update. Only the newest snapshot for each call is
* written, so this can be invoked as often as the call changes.
* @param handle for the call
* @param snapshot of the call that is not modified after this call
*/
public void save(CallHandle handle, CallRecord snapshot)
{
synchronized(mPendingCalls)
{
mPendingCalls.put(handle, snapshot);
//Bound memory use if the database is unavailable for a long time. Drop the oldest completed calls first.
if(mPendingCalls.size() > MAX_PENDING_CALLS)
{
Iterator<Map.Entry<CallHandle,CallRecord>> it = mPendingCalls.entrySet().iterator();
while(it.hasNext() && mPendingCalls.size() > MAX_PENDING_CALLS)
{
if(!it.next().getValue().isActive())
{
it.remove();
}
}
LOGGER.warn("Call database is unavailable - discarding the oldest pending call updates");
}
}
}
/**
* Writes the pending call updates. Database thread only.
*/
private void flush()
{
CallDatabase database = mDatabase;
if(database == null)
{
//Retry opening the database periodically
if(mErrorMessage != null && System.currentTimeMillis() > mNextRetry)
{
openConfiguredDatabase();
database = mDatabase;
}
if(database == null)
{
return;
}
}
List<Map.Entry<CallHandle,CallRecord>> batch;
synchronized(mPendingCalls)
{
if(mPendingCalls.isEmpty())
{
return;
}
batch = new ArrayList<>(mPendingCalls.entrySet());
mPendingCalls.clear();
}
ICallRepository repository = database.getCallRepository();
int written = 0;
try(Connection connection = database.getConnection())
{
for(Map.Entry<CallHandle,CallRecord> entry: batch)
{
CallHandle handle = entry.getKey();
CallRecord call = entry.getValue();
if(handle.mGeneration == mGeneration && handle.mId > 0)
{
call.setId(handle.mId);
if(repository.update(connection, call))
{
written++;
mSavedCallBroadcaster.broadcast(call);
continue;
}
}
//New call, a call that started before a database switch, or a row removed by an age-off rule.
call.setId(0);
handle.mId = repository.insert(connection, call);
handle.mGeneration = mGeneration;
written++;
mSavedCallBroadcaster.broadcast(call);
}
}
catch(SQLException se)
{
LOGGER.error("Error writing call updates to the database - " + se.getMessage());
//Put back the updates that weren't written, unless a newer update arrived in the meantime
synchronized(mPendingCalls)
{
Map<CallHandle,CallRecord> newer = new LinkedHashMap<>(mPendingCalls);
mPendingCalls.clear();
for(int x = written; x < batch.size(); x++)
{
mPendingCalls.put(batch.get(x).getKey(), batch.get(x).getValue());
}
mPendingCalls.putAll(newer);
}
if(!isReachable(database))
{
LOGGER.error("Call database connection lost - will retry");
closeDatabase();
mErrorMessage = se.getMessage();
mNextRetry = System.currentTimeMillis() + RETRY_INTERVAL_MS;
broadcast(DatabaseEvent.Type.ERROR);
}
}
}
private static boolean isReachable(CallDatabase database)
{
try(Connection connection = database.getConnection())
{
return connection.isValid(5);
}
catch(SQLException se)
{
return false;
}
}
/**
* Searches the calls table on the query thread.
*/
public CompletableFuture<SearchResult> search(CallSearchCriteria criteria, int offset, int limit)
{
return CompletableFuture.supplyAsync(() -> {
CallDatabase database = mDatabase;
if(database == null)
{
throw new IllegalStateException("Call database is not available" +
(mErrorMessage != null ? ": " + mErrorMessage : ""));
}
try(Connection connection = database.getConnection())
{
List<CallRecord> calls = database.getCallRepository().search(connection, criteria, offset, limit);
long total = database.getCallRepository().count(connection, criteria);
return new SearchResult(calls, total);
}
catch(SQLException se)
{
throw new IllegalStateException(se.getMessage(), se);
}
}, mQueryExecutor);
}
/**
* Search results
* @param calls in the requested page
* @param total count of matching calls
*/
public record SearchResult(List<CallRecord> calls, long total) {}
/**
* Connects to the database configuration and reports the state of its schema. Runs on the query thread.
*/
public CompletableFuture<ProbeResult> probe(DatabaseConfiguration configuration)
{
return CompletableFuture.supplyAsync(() -> {
try(CallDatabase database = new CallDatabase(configuration, getDatabaseDirectory()))
{
SchemaStatus status = database.getSchemaStatus();
long count = status == SchemaStatus.SDRTRUNK ? database.getCallCount() : 0;
String suggestion = status == SchemaStatus.MISSING ? configuration.schema() :
database.suggestSchemaName();
return new ProbeResult(status, count, suggestion);
}
catch(SQLException se)
{
throw new IllegalStateException(se.getMessage(), se);
}
}, mQueryExecutor);
}
/**
* Result of probing a database configuration
* @param status of the configured schema
* @param callCount in the configured schema
* @param suggestedSchema an unused schema name, for the create separate schema option
*/
public record ProbeResult(SchemaStatus status, long callCount, String suggestedSchema) {}
/**
* Checks whether a schema exists in the database of the configuration. Runs on the query thread.
*/
public CompletableFuture<Boolean> schemaExists(DatabaseConfiguration configuration, String schema)
{
return CompletableFuture.supplyAsync(() -> {
try(CallDatabase database = new CallDatabase(configuration, getDatabaseDirectory()))
{
return database.schemaExists(schema);
}
catch(SQLException se)
{
throw new IllegalStateException(se.getMessage(), se);
}
}, mQueryExecutor);
}
/**
* How to treat an existing sdrtrunk schema in the database being switched to
*/
public enum ExistingSchemaOption
{
/**
* Keep the existing calls and add to them
*/
APPEND,
/**
* Remove the existing calls and start empty
*/
CLEAR
}
/**
* Switches to a different database.
*
* @param target configuration, including the schema name to use (a new name for the create separate schema option)
* @param schemaOption for an existing sdrtrunk schema in the target
* @param transfer true to copy the calls from the current database to the target
* @param progress receives status text while the switch runs (on the database thread)
* @return future that completes when the switch is complete, or completes exceptionally on error, in which case
* the current database remains selected
*/
public CompletableFuture<SwitchResult> switchDatabase(DatabaseConfiguration target,
ExistingSchemaOption schemaOption, boolean transfer,
Consumer<String> progress)
{
CompletableFuture<SwitchResult> future = new CompletableFuture<>();
mDatabaseExecutor.execute(() -> {
CallDatabase targetDatabase = null;
try
{
progress.accept("Connecting to " + target.getDescription());
targetDatabase = new CallDatabase(target, getDatabaseDirectory());
SchemaStatus status = targetDatabase.getSchemaStatus();
if(status == SchemaStatus.SDRTRUNK && schemaOption == ExistingSchemaOption.CLEAR)
{
progress.accept("Clearing schema [" + target.schema() + "]");
targetDatabase.clear();
}
else
{
progress.accept("Installing schema [" + target.schema() + "]");
targetDatabase.install();
}
long transferred = 0;
long skipped = 0;
CallDatabase current = mDatabase;
if(transfer && current != null && !current.getConfiguration().isSameLocation(target))
{
//Write pending updates first so that they are included in the transfer
flush();
long[] counts = transfer(current, targetDatabase, progress);
transferred = counts[0];
skipped = counts[1];
}
try(Connection connection = targetDatabase.getConnection())
{
targetDatabase.getCallRepository().markInterrupted(connection);
}
//Write remaining pending updates to the current database before switching, so that active calls
//continue in the new database
flush();
CallDatabase previous = mDatabase;
mDatabase = targetDatabase;
mGeneration++;
mErrorMessage = null;
mUserPreferences.getDatabasePreference().setDatabaseConfiguration(target);
if(previous != null)
{
//Calls in progress continue in the new database, so remove them from the previous database
try(Connection connection = previous.getConnection())
{
previous.getCallRepository().deleteActive(connection);
}
catch(SQLException se)
{
LOGGER.warn("Unable to remove calls in progress from the previous database - " +
se.getMessage());
}
previous.close();
}
LOGGER.info("Switched call database to " + target.getDescription() + " - transferred " +
transferred + " calls" + (skipped > 0 ? ", skipped " + skipped + " existing calls" : ""));
broadcast(DatabaseEvent.Type.CONNECTED);
future.complete(new SwitchResult(transferred, skipped));
}
catch(Exception e)
{
LOGGER.error("Error switching the call database to " + target.getDescription(), e);
if(targetDatabase != null && targetDatabase != mDatabase)
{
targetDatabase.close();
}
future.completeExceptionally(e);
}
});
return future;
}
/**
* Result of a database switch
* @param transferred count of calls copied to the new database
* @param skipped count of calls that already existed in the new database
*/
public record SwitchResult(long transferred, long skipped) {}
/**
* Copies the calls from the source to the target database, skipping calls in progress (they are written to the
* target after the switch) and calls that already exist in the target.
* @return transferred and skipped counts
*/
private long[] transfer(CallDatabase source, CallDatabase target, Consumer<String> progress) throws SQLException
{
ICallRepository sourceRepository = source.getCallRepository();
ICallRepository targetRepository = target.getCallRepository();
long transferred = 0;
long skipped = 0;
try(Connection sourceConnection = source.getConnection(); Connection targetConnection = target.getConnection())
{
long total = sourceRepository.count(sourceConnection);
Set<String> existing = targetRepository.count(targetConnection) > 0 ?
targetRepository.getTransferKeys(targetConnection) : Collections.emptySet();
boolean autoCommit = targetConnection.getAutoCommit();
targetConnection.setAutoCommit(false);
try
{
long afterId = 0;
List<CallRecord> page = sourceRepository.readPage(sourceConnection, afterId, TRANSFER_PAGE_SIZE);
while(!page.isEmpty())
{
List<CallRecord> toInsert = new ArrayList<>();
for(CallRecord call: page)
{
if(call.getCallState() == CallState.ACTIVE || existing.contains(call.getTransferKey()))
{
skipped++;
}
else
{
toInsert.add(call);
}
}
if(!toInsert.isEmpty())
{
targetRepository.insertBatch(targetConnection, toInsert);
targetConnection.commit();
transferred += toInsert.size();
}
afterId = page.getLast().getId();
progress.accept("Transferring calls: " + (transferred + skipped) + " of " + total);
page = sourceRepository.readPage(sourceConnection, afterId, TRANSFER_PAGE_SIZE);
}
}
catch(SQLException se)
{
targetConnection.rollback();
throw se;
}
finally
{
targetConnection.setAutoCommit(autoCommit);
}
}
return new long[]{transferred, skipped};
}
/**
* Age-off rule manager
*/
public AgeOffManager getAgeOffManager()
{
return mAgeOffManager;
}
/**
* Runs the task on the database thread.
*/
public CompletableFuture<Void> runOnDatabaseThread(Runnable runnable)
{
return CompletableFuture.runAsync(runnable, mDatabaseExecutor);
}
/**
* Notifies listeners that the stored calls changed outside of the normal call updates (age-off, switch, delete).
*/
public void notifyCallsChanged()
{
broadcast(DatabaseEvent.Type.CALLS_CHANGED);
}
private void broadcast(DatabaseEvent.Type type)
{
mEventBroadcaster.broadcast(new DatabaseEvent(type, getConfiguration(), mErrorMessage));
}
/**
* Registers the listener to receive database events (on the database thread)
*/
public void addListener(Listener<DatabaseEvent> listener)
{
mEventBroadcaster.addListener(listener);
}
public void removeListener(Listener<DatabaseEvent> listener)
{
mEventBroadcaster.removeListener(listener);
}
/**
* Registers the listener to receive each call after it is written to the database, with its row id assigned.
* Notified on the database thread.
*/
public void addCallSavedListener(Listener<CallRecord> listener)
{
mSavedCallBroadcaster.addListener(listener);
}
public void removeCallSavedListener(Listener<CallRecord> listener)
{
mSavedCallBroadcaster.removeListener(listener);
}
/**
* Tracks the database row of a call. Accessed only on the database thread.
*/
public static class CallHandle
{
private long mId;
private int mGeneration;
}
}

View File

@@ -1,81 +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.database;
import io.github.dsheirer.database.dialect.H2Dialect;
import io.github.dsheirer.database.dialect.IDatabaseDialect;
import io.github.dsheirer.database.dialect.MariaDBDialect;
import io.github.dsheirer.database.dialect.PostgreSQLDialect;
/**
* Supported call database engines. The engine differences are implemented by each type's {@link IDatabaseDialect}.
*/
public enum DatabaseType
{
H2("Built-in (H2)", new H2Dialect()),
MARIADB("MariaDB", new MariaDBDialect()),
POSTGRESQL("PostgreSQL", new PostgreSQLDialect());
private final String mLabel;
private final IDatabaseDialect mDialect;
DatabaseType(String label, IDatabaseDialect dialect)
{
mLabel = label;
mDialect = dialect;
}
/**
* SQL dialect and connection settings for this engine
*/
public IDatabaseDialect getDialect()
{
return mDialect;
}
/**
* Indicates if this is a network database server that needs a host, port and credentials.
*/
public boolean isNetwork()
{
return mDialect.isNetwork();
}
/**
* Indicates if this engine needs a database name in addition to the schema name.
*/
public boolean requiresDatabaseName()
{
return mDialect.requiresDatabaseName();
}
/**
* Default TCP port for a network database, or 0 for the embedded database.
*/
public int getDefaultPort()
{
return mDialect.getDefaultPort();
}
@Override
public String toString()
{
return mLabel;
}
}

View File

@@ -1,329 +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.database.ageoff;
import io.github.dsheirer.database.CallDatabase;
import io.github.dsheirer.database.DatabaseManager;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.database.call.ICallRepository;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.database.DatabasePreference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Applies the call audio age-off rules:
* <ul>
* <li>Retention rule: deletes duplicate calls, and Do Not Monitor calls that no alias marked for recording, with
* their recordings, after the retention period (default 1 hour).</li>
* <li>Age rule: removes calls older than a number of days.</li>
* <li>Size rule: removes the oldest recordings when the total size of the recordings exceeds a limit.</li>
* </ul>
* The age and size rules either delete the call row and its recording file, or delete only the recording file and
* keep the call row.
*
* The rules run a minute after startup, then every 5 minutes, and when the user requests it. Calls in progress are
* never removed. Only recordings tracked in the call database are considered.
*/
public class AgeOffManager
{
private static final Logger LOGGER = LoggerFactory.getLogger(AgeOffManager.class);
private static final long INITIAL_DELAY_SECONDS = 60;
private static final long INTERVAL_SECONDS = 300;
private static final int PAGE_SIZE = 500;
public static final long BYTES_PER_MB = 1024L * 1024L;
private final DatabaseManager mDatabaseManager;
private final DatabasePreference mPreference;
private ScheduledFuture<?> mScheduledFuture;
/**
* Constructs an instance
*/
public AgeOffManager(DatabaseManager databaseManager, UserPreferences userPreferences)
{
mDatabaseManager = databaseManager;
mPreference = userPreferences.getDatabasePreference();
}
/**
* Schedules the periodic age-off on the database thread.
*/
public void start(ScheduledExecutorService databaseExecutor)
{
if(mScheduledFuture == null)
{
mScheduledFuture = databaseExecutor.scheduleWithFixedDelay(this::runSafely, INITIAL_DELAY_SECONDS,
INTERVAL_SECONDS, TimeUnit.SECONDS);
}
}
public void stop()
{
if(mScheduledFuture != null)
{
mScheduledFuture.cancel(false);
mScheduledFuture = null;
}
}
/**
* Runs the enabled rules now.
* @return future with the results
*/
public CompletableFuture<AgeOffResult> runNow()
{
CompletableFuture<AgeOffResult> future = new CompletableFuture<>();
mDatabaseManager.runOnDatabaseThread(() -> {
try
{
future.complete(run());
}
catch(Exception e)
{
future.completeExceptionally(e);
}
});
return future;
}
private void runSafely()
{
try
{
run();
}
catch(Exception e)
{
LOGGER.error("Error applying the call age-off rules", e);
}
}
/**
* Applies the enabled rules. Database thread only.
*/
private AgeOffResult run() throws SQLException
{
CallDatabase database = mDatabaseManager.getDatabase();
RetentionPeriod retention = mPreference.getDuplicateDoNotMonitorRetention();
if(database == null || (!retention.isEnabled() && !mPreference.isAgeRuleEnabled() &&
!mPreference.isSizeRuleEnabled()))
{
return new AgeOffResult(0, 0, 0);
}
AgeOffResult result = new AgeOffResult(0, 0, 0);
try(Connection connection = database.getConnection())
{
ICallRepository repository = database.getCallRepository();
if(retention.isEnabled())
{
long cutoff = System.currentTimeMillis() - retention.getMilliseconds();
result = result.add(applyRetentionRule(connection, repository, cutoff));
}
if(mPreference.isAgeRuleEnabled())
{
long cutoff = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(mPreference.getAgeRuleDays());
result = result.add(applyAgeRule(connection, repository, cutoff, mPreference.getAgeRuleAction()));
}
if(mPreference.isSizeRuleEnabled())
{
long limit = mPreference.getSizeRuleLimitMB() * BYTES_PER_MB;
result = result.add(applySizeRule(connection, repository, limit, mPreference.getSizeRuleAction()));
}
}
if(result.calls() > 0 || result.recordings() > 0)
{
LOGGER.info("Call age-off removed " + result.calls() + " calls and " + result.recordings() +
" recordings (" + (result.bytes() / BYTES_PER_MB) + " MB)");
mDatabaseManager.notifyCallsChanged();
}
return result;
}
/**
* Deletes duplicate calls and Do Not Monitor calls (without an alias record option) that started before the
* cutoff time, with their recordings.
*/
static AgeOffResult applyRetentionRule(Connection connection, ICallRepository repository, long cutoff)
throws SQLException
{
AgeOffResult result = new AgeOffResult(0, 0, 0);
List<CallRecord> page = repository.getDuplicateAndDoNotMonitorCalls(connection, cutoff, PAGE_SIZE);
while(!page.isEmpty())
{
result = result.add(remove(connection, repository, page, AgeOffAction.DELETE_CALL_AND_RECORDING));
page = repository.getDuplicateAndDoNotMonitorCalls(connection, cutoff, PAGE_SIZE);
}
return result;
}
/**
* Removes the calls (or recordings) of calls that started before the cutoff time.
*/
static AgeOffResult applyAgeRule(Connection connection, ICallRepository repository, long cutoff,
AgeOffAction action) throws SQLException
{
AgeOffResult result = new AgeOffResult(0, 0, 0);
List<CallRecord> page = action == AgeOffAction.DELETE_CALL_AND_RECORDING ?
repository.getCallsStartedBefore(connection, cutoff, PAGE_SIZE) :
repository.getRecordedCalls(connection, cutoff, PAGE_SIZE);
while(!page.isEmpty())
{
result = result.add(remove(connection, repository, page, action));
page = action == AgeOffAction.DELETE_CALL_AND_RECORDING ?
repository.getCallsStartedBefore(connection, cutoff, PAGE_SIZE) :
repository.getRecordedCalls(connection, cutoff, PAGE_SIZE);
}
return result;
}
/**
* Removes the oldest recordings until the total size of the recordings is at or below the limit.
*/
static AgeOffResult applySizeRule(Connection connection, ICallRepository repository, long limitBytes,
AgeOffAction action) throws SQLException
{
AgeOffResult result = new AgeOffResult(0, 0, 0);
long total = repository.getRecordedFileSize(connection);
while(total > limitBytes)
{
List<CallRecord> page = repository.getRecordedCalls(connection, 0, PAGE_SIZE);
if(page.isEmpty())
{
break;
}
List<CallRecord> toRemove = new ArrayList<>();
for(CallRecord call: page)
{
if(total <= limitBytes)
{
break;
}
toRemove.add(call);
total -= call.getFileSize();
}
result = result.add(remove(connection, repository, toRemove, action));
}
return result;
}
/**
* Deletes the recording files of the calls and then deletes the call rows or marks their recordings deleted.
*/
private static AgeOffResult remove(Connection connection, ICallRepository repository, List<CallRecord> calls,
AgeOffAction action) throws SQLException
{
long bytes = 0;
int recordings = 0;
List<Long> ids = new ArrayList<>();
for(CallRecord call: calls)
{
ids.add(call.getId());
if(call.getFilePath() != null && deleteRecording(call.getFilePath()))
{
recordings++;
bytes += call.getFileSize();
}
}
if(action == AgeOffAction.DELETE_CALL_AND_RECORDING)
{
repository.delete(connection, ids);
return new AgeOffResult(ids.size(), recordings, bytes);
}
repository.markRecordingsDeleted(connection, ids);
return new AgeOffResult(0, recordings, bytes);
}
/**
* Deletes the audio recording file. Only audio files (.mp3, .wav) are deleted.
* @return true if the file was deleted
*/
static boolean deleteRecording(String filePath)
{
String lower = filePath.toLowerCase(Locale.ROOT);
if(!lower.endsWith(".mp3") && !lower.endsWith(".wav"))
{
LOGGER.warn("Age-off skipped deleting non-audio file [" + filePath + "]");
return false;
}
try
{
return Files.deleteIfExists(Path.of(filePath));
}
catch(IOException | RuntimeException e)
{
LOGGER.warn("Age-off unable to delete recording [" + filePath + "] - " + e.getMessage());
return false;
}
}
/**
* Age-off results
* @param calls deleted
* @param recordings deleted
* @param bytes of recordings deleted
*/
public record AgeOffResult(long calls, long recordings, long bytes)
{
public AgeOffResult add(AgeOffResult other)
{
return new AgeOffResult(calls + other.calls, recordings + other.recordings, bytes + other.bytes);
}
}
}

View File

@@ -1,71 +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.database.ageoff;
import java.util.concurrent.TimeUnit;
/**
* How long duplicate and Do Not Monitor calls (and their recordings) are kept before they are deleted
*/
public enum RetentionPeriod
{
MINUTES_30("30 minutes", TimeUnit.MINUTES.toMillis(30)),
HOUR_1("1 hour", TimeUnit.HOURS.toMillis(1)),
HOURS_2("2 hours", TimeUnit.HOURS.toMillis(2)),
HOURS_4("4 hours", TimeUnit.HOURS.toMillis(4)),
HOURS_8("8 hours", TimeUnit.HOURS.toMillis(8)),
HOURS_12("12 hours", TimeUnit.HOURS.toMillis(12)),
DAY_1("1 day", TimeUnit.DAYS.toMillis(1)),
DAYS_2("2 days", TimeUnit.DAYS.toMillis(2)),
DAYS_7("7 days", TimeUnit.DAYS.toMillis(7)),
NEVER("Never delete", 0);
public static final RetentionPeriod DEFAULT = HOUR_1;
private final String mLabel;
private final long mMilliseconds;
RetentionPeriod(String label, long milliseconds)
{
mLabel = label;
mMilliseconds = milliseconds;
}
/**
* Retention time in milliseconds, or 0 for never
*/
public long getMilliseconds()
{
return mMilliseconds;
}
/**
* Indicates if calls are deleted after this period
*/
public boolean isEnabled()
{
return this != NEVER;
}
@Override
public String toString()
{
return mLabel;
}
}

View File

@@ -1,568 +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.database.call;
import io.github.dsheirer.protocol.Protocol;
import java.util.List;
/**
* A call audio event as stored in the calls table.
*
* Instances are mutable while they are being built, but a record that has been handed to the database writer or to
* the user interface is a snapshot that is never changed afterwards. Use {@link #copy()} to create a new snapshot.
*/
public class CallRecord
{
public static final String FORM_TALKGROUP = "TALKGROUP";
public static final String FORM_PATCH_GROUP = "PATCH_GROUP";
public static final String FORM_RADIO = "RADIO";
private long mId;
private long mCallKey;
private long mStartTime;
private long mEndTime;
private CallState mCallState = CallState.ACTIVE;
private String mProtocol;
private String mSystem;
private String mSite;
private String mChannel;
private long mFrequency;
private int mTimeslot;
private String mToId;
private Long mToValue;
private String mToForm;
private String mToFullyQualified;
private String mFromId;
private Long mFromValue;
private String mFromForm;
private String mFromFullyQualified;
private String mAliasList;
private List<PatchedTalkgroup> mPatchedTalkgroups = List.of();
private String mTalkerAlias;
private boolean mEncrypted;
private boolean mDuplicate;
private int mPriority;
private boolean mAliasRecord;
private String mRecordFormat;
private String mFilePath;
private long mFileSize;
private RecordingState mRecordingState = RecordingState.NONE;
/**
* Creates a copy (snapshot) of this record.
*/
public CallRecord copy()
{
CallRecord copy = new CallRecord();
copy.mId = mId;
copy.mCallKey = mCallKey;
copy.mStartTime = mStartTime;
copy.mEndTime = mEndTime;
copy.mCallState = mCallState;
copy.mProtocol = mProtocol;
copy.mSystem = mSystem;
copy.mSite = mSite;
copy.mChannel = mChannel;
copy.mFrequency = mFrequency;
copy.mTimeslot = mTimeslot;
copy.mToId = mToId;
copy.mToValue = mToValue;
copy.mToForm = mToForm;
copy.mToFullyQualified = mToFullyQualified;
copy.mFromId = mFromId;
copy.mFromValue = mFromValue;
copy.mFromForm = mFromForm;
copy.mFromFullyQualified = mFromFullyQualified;
copy.mAliasList = mAliasList;
copy.mPatchedTalkgroups = mPatchedTalkgroups;
copy.mTalkerAlias = mTalkerAlias;
copy.mEncrypted = mEncrypted;
copy.mDuplicate = mDuplicate;
copy.mPriority = mPriority;
copy.mAliasRecord = mAliasRecord;
copy.mRecordFormat = mRecordFormat;
copy.mFilePath = mFilePath;
copy.mFileSize = mFileSize;
copy.mRecordingState = mRecordingState;
return copy;
}
/**
* Database row identifier, or 0 if this call hasn't been inserted yet.
*/
public long getId()
{
return mId;
}
public void setId(long id)
{
mId = id;
}
/**
* In-memory key that identifies a live call across snapshots, or 0 for records loaded from the database.
*/
public long getCallKey()
{
return mCallKey;
}
public void setCallKey(long callKey)
{
mCallKey = callKey;
}
/**
* Call start time, milliseconds since epoch
*/
public long getStartTime()
{
return mStartTime;
}
public void setStartTime(long startTime)
{
mStartTime = startTime;
}
/**
* Call end time, milliseconds since epoch, or 0 while the call is active.
*/
public long getEndTime()
{
return mEndTime;
}
public void setEndTime(long endTime)
{
mEndTime = endTime;
}
/**
* Call duration in milliseconds. For an active call this is the elapsed time up to now.
*/
public long getDuration()
{
if(mEndTime > 0)
{
return Math.max(0, mEndTime - mStartTime);
}
return isActive() ? Math.max(0, System.currentTimeMillis() - mStartTime) : 0;
}
public CallState getCallState()
{
return mCallState;
}
public void setCallState(CallState callState)
{
mCallState = callState;
}
/**
* Indicates if the call is in progress.
*/
public boolean isActive()
{
return mCallState == CallState.ACTIVE;
}
/**
* Protocol enumeration entry name (e.g. APCO25)
*/
public String getProtocol()
{
return mProtocol;
}
public void setProtocol(String protocol)
{
mProtocol = protocol;
}
/**
* Protocol, or UNKNOWN if the stored value isn't recognized.
*/
public Protocol getProtocolValue()
{
if(mProtocol != null)
{
try
{
return Protocol.valueOf(mProtocol);
}
catch(IllegalArgumentException iae)
{
//Fall through
}
}
return Protocol.UNKNOWN;
}
public String getSystem()
{
return mSystem;
}
public void setSystem(String system)
{
mSystem = system;
}
public String getSite()
{
return mSite;
}
public void setSite(String site)
{
mSite = site;
}
public String getChannel()
{
return mChannel;
}
public void setChannel(String channel)
{
mChannel = channel;
}
/**
* Channel frequency in Hertz, or 0 if unknown.
*/
public long getFrequency()
{
return mFrequency;
}
public void setFrequency(long frequency)
{
mFrequency = frequency;
}
public int getTimeslot()
{
return mTimeslot;
}
public void setTimeslot(int timeslot)
{
mTimeslot = timeslot;
}
/**
* Formatted TO identifier (talkgroup, patch group or radio)
*/
public String getToId()
{
return mToId;
}
public void setToId(String toId)
{
mToId = toId;
}
/**
* Numeric TO identifier value, or null. For a patch group, this is the patch group talkgroup.
*/
public Long getToValue()
{
return mToValue;
}
public void setToValue(Long toValue)
{
mToValue = toValue;
}
/**
* Indicates if the TO identifier of this call is a talkgroup or patch group that can be used as a hold talkgroup.
*/
public boolean hasTalkgroup()
{
return mToValue != null && mToValue > 0 && isToTalkgroup();
}
/**
* Indicates if the TO identifier is a talkgroup or patch group (as opposed to a radio, for a private call).
*/
public boolean isToTalkgroup()
{
return FORM_TALKGROUP.equals(mToForm) || FORM_PATCH_GROUP.equals(mToForm);
}
/**
* Call type (group, patch, private or telephone), derived from the TO and FROM identifier forms.
*/
public CallType getCallType()
{
return CallType.from(mToForm, mFromForm);
}
/**
* Identifier form (Form enumeration name, e.g. TALKGROUP, PATCH_GROUP or RADIO) of the TO identifier, or null.
*/
public String getToForm()
{
return mToForm;
}
public void setToForm(String toForm)
{
mToForm = toForm;
}
/**
* Fully qualified address (wacn.system.id) of a fully qualified (roaming) TO talkgroup, or null.
*/
public String getToFullyQualified()
{
return mToFullyQualified;
}
public void setToFullyQualified(String toFullyQualified)
{
mToFullyQualified = toFullyQualified;
}
/**
* Identifier form (Form enumeration name, e.g. RADIO) of the FROM identifier, or null.
*/
public String getFromForm()
{
return mFromForm;
}
public void setFromForm(String fromForm)
{
mFromForm = fromForm;
}
/**
* Indicates if the FROM identifier is a radio
*/
public boolean isFromRadio()
{
return FORM_RADIO.equals(mFromForm);
}
/**
* Fully qualified address (wacn.system.id) of a fully qualified (roaming) FROM radio, or null.
*/
public String getFromFullyQualified()
{
return mFromFullyQualified;
}
public void setFromFullyQualified(String fromFullyQualified)
{
mFromFullyQualified = fromFullyQualified;
}
/**
* Talkgroups that are patched into the TO patch group of the call, or an empty list. Searching for a talkgroup
* finds the calls that it participated in through a patch.
*/
public List<PatchedTalkgroup> getPatchedTalkgroups()
{
return mPatchedTalkgroups;
}
public void setPatchedTalkgroups(List<PatchedTalkgroup> patchedTalkgroups)
{
mPatchedTalkgroups = patchedTalkgroups == null ? List.of() : List.copyOf(patchedTalkgroups);
}
/**
* Name of the alias list that was assigned to the channel for this call, or null. Aliases for the TO and FROM
* identifiers are looked up in the current version of this alias list when the call is displayed.
*/
public String getAliasList()
{
return mAliasList;
}
public void setAliasList(String aliasList)
{
mAliasList = aliasList;
}
public String getFromId()
{
return mFromId;
}
public void setFromId(String fromId)
{
mFromId = fromId;
}
public Long getFromValue()
{
return mFromValue;
}
public void setFromValue(Long fromValue)
{
mFromValue = fromValue;
}
public String getTalkerAlias()
{
return mTalkerAlias;
}
public void setTalkerAlias(String talkerAlias)
{
mTalkerAlias = talkerAlias;
}
public boolean isEncrypted()
{
return mEncrypted;
}
public void setEncrypted(boolean encrypted)
{
mEncrypted = encrypted;
}
public boolean isDuplicate()
{
return mDuplicate;
}
public void setDuplicate(boolean duplicate)
{
mDuplicate = duplicate;
}
/**
* Alias playback priority
*/
public int getPriority()
{
return mPriority;
}
public void setPriority(int priority)
{
mPriority = priority;
}
/**
* Indicates if an alias of the call has the record option, as opposed to the call being recorded only because
* all calls are recorded. Do Not Monitor calls with an alias record option are kept by the retention rule.
*/
public boolean isAliasRecord()
{
return mAliasRecord;
}
public void setAliasRecord(boolean aliasRecord)
{
mAliasRecord = aliasRecord;
}
/**
* Recording format (MP3 or WAVE), or null when the call isn't recorded.
*/
public String getRecordFormat()
{
return mRecordFormat;
}
public void setRecordFormat(String recordFormat)
{
mRecordFormat = recordFormat;
}
/**
* Absolute path of the audio recording file, or null.
*/
public String getFilePath()
{
return mFilePath;
}
public void setFilePath(String filePath)
{
mFilePath = filePath;
}
/**
* Recording file size in bytes
*/
public long getFileSize()
{
return mFileSize;
}
public void setFileSize(long fileSize)
{
mFileSize = fileSize;
}
public RecordingState getRecordingState()
{
return mRecordingState;
}
public void setRecordingState(RecordingState recordingState)
{
mRecordingState = recordingState;
}
/**
* Indicates if this call has a completed audio recording that can be played.
*/
public boolean isPlayable()
{
return mRecordingState == RecordingState.RECORDED && mFilePath != null;
}
/**
* Key used to detect a call that already exists in a target database during an append transfer. The recording
* file path identifies a call uniquely. Calls without a recording use their start time, channel and TO.
*/
public String getTransferKey()
{
if(mFilePath != null && !mFilePath.isEmpty())
{
return "F:" + mFilePath;
}
return "C:" + mStartTime + "|" + mChannel + "|" + mTimeslot + "|" + mToId + "|" + mFromId;
}
@Override
public String toString()
{
return "Call " + mId + " " + mProtocol + " TO:" + mToId + " FROM:" + mFromId + " " + mCallState + " " +
mRecordingState + (mFilePath != null ? " " + mFilePath : "");
}
}

View File

@@ -1,909 +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.database.call;
import io.github.dsheirer.alias.id.priority.Priority;
import io.github.dsheirer.database.dialect.IDatabaseDialect;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* JDBC implementation of the calls table, using SQL that is portable across all supported database engines. All
* methods take a connection from the caller and qualify the table name with the schema, so this class has no state
* other than the schema name.
*/
public class CallRepository implements ICallRepository
{
public static final String TABLE = "calls";
public static final String PATCHED_TABLE = "patched_talkgroups";
/**
* Columns in insert/select order, excluding the generated id.
*/
private static final String COLUMNS = "start_time, end_time, duration_ms, call_state, protocol, system_name, " +
"site_name, channel_name, frequency, timeslot, to_id, to_value, to_form, to_fq, from_id, from_value, " +
"from_form, from_fq, alias_list, talker_alias, encrypted, duplicate_call, priority, alias_record, " +
"record_format, file_path, file_size, recording_state";
private static final int COLUMN_COUNT = 28;
/**
* Maximum stored lengths of the text columns, so that a long alias or channel name can't fail an insert.
*/
private static final int LENGTH_SHORT = 32;
private static final int LENGTH_ID = 64;
private static final int LENGTH_NAME = 255;
private static final int LENGTH_PATH = 1024;
private final String mSchema;
private final String mTable;
private final String mPatchedTable;
/**
* Constructs an instance
* @param schema that holds the calls table
*/
public CallRepository(String schema)
{
mSchema = schema;
mTable = schema + "." + TABLE;
mPatchedTable = schema + "." + PATCHED_TABLE;
}
/**
* Statements that create the calls table and its indexes.
*/
public static List<String> getCreateStatements(IDatabaseDialect dialect, String schema)
{
String table = schema + "." + TABLE;
List<String> statements = new ArrayList<>();
statements.add("CREATE TABLE IF NOT EXISTS " + table + " (" +
"id " + dialect.getIdentityColumn() + ", " +
"start_time BIGINT NOT NULL, " +
"end_time BIGINT NOT NULL, " +
"duration_ms BIGINT NOT NULL, " +
"call_state VARCHAR(" + LENGTH_SHORT + ") NOT NULL, " +
"protocol VARCHAR(" + LENGTH_SHORT + "), " +
"system_name VARCHAR(" + LENGTH_NAME + "), " +
"site_name VARCHAR(" + LENGTH_NAME + "), " +
"channel_name VARCHAR(" + LENGTH_NAME + "), " +
"frequency BIGINT NOT NULL, " +
"timeslot INT NOT NULL, " +
"to_id VARCHAR(" + LENGTH_ID + "), " +
"to_value BIGINT, " +
"to_form VARCHAR(" + LENGTH_SHORT + "), " +
"to_fq VARCHAR(" + LENGTH_ID + "), " +
"from_id VARCHAR(" + LENGTH_ID + "), " +
"from_value BIGINT, " +
"from_form VARCHAR(" + LENGTH_SHORT + "), " +
"from_fq VARCHAR(" + LENGTH_ID + "), " +
"alias_list VARCHAR(" + LENGTH_NAME + "), " +
"talker_alias VARCHAR(" + LENGTH_NAME + "), " +
"encrypted BOOLEAN NOT NULL, " +
"duplicate_call BOOLEAN NOT NULL, " +
"priority INT NOT NULL, " +
"alias_record BOOLEAN NOT NULL, " +
"record_format VARCHAR(" + LENGTH_SHORT + "), " +
"file_path VARCHAR(" + LENGTH_PATH + "), " +
"file_size BIGINT NOT NULL, " +
"recording_state VARCHAR(" + LENGTH_SHORT + ") NOT NULL)");
//Index names are scoped to the schema (H2, PostgreSQL) or the table (MariaDB), so prefix them with the table
statements.add("CREATE INDEX IF NOT EXISTS calls_start_time_idx ON " + table + " (start_time)");
statements.add("CREATE INDEX IF NOT EXISTS calls_to_value_idx ON " + table + " (to_value)");
statements.add("CREATE INDEX IF NOT EXISTS calls_from_value_idx ON " + table + " (from_value)");
statements.add("CREATE INDEX IF NOT EXISTS calls_recording_state_idx ON " + table +
" (recording_state, start_time)");
return statements;
}
/**
* Statements that create the patched talkgroups table (schema version 2). Rows are deleted with their call.
*/
public static List<String> getPatchedTalkgroupCreateStatements(String schema)
{
String table = schema + "." + PATCHED_TABLE;
List<String> statements = new ArrayList<>();
statements.add("CREATE TABLE IF NOT EXISTS " + table + " (" +
"call_id BIGINT NOT NULL REFERENCES " + schema + "." + TABLE + "(id) ON DELETE CASCADE, " +
"talkgroup BIGINT NOT NULL, " +
"fq VARCHAR(" + LENGTH_ID + "))");
statements.add("CREATE INDEX IF NOT EXISTS patched_talkgroups_call_idx ON " + table + " (call_id)");
statements.add("CREATE INDEX IF NOT EXISTS patched_talkgroups_talkgroup_idx ON " + table + " (talkgroup)");
return statements;
}
/**
* Inserts the call and assigns the generated row id to the call.
* @return generated row id
*/
@Override
public long insert(Connection connection, CallRecord call) throws SQLException
{
String sql = "INSERT INTO " + mTable + " (" + COLUMNS + ") VALUES (" + "?, ".repeat(COLUMN_COUNT - 1) + "?)";
try(PreparedStatement statement = connection.prepareStatement(sql, new String[]{"id"}))
{
bind(statement, call);
statement.executeUpdate();
try(ResultSet keys = statement.getGeneratedKeys())
{
if(keys.next())
{
long id = keys.getLong(1);
call.setId(id);
insertPatchedTalkgroups(connection, id, call.getPatchedTalkgroups());
return id;
}
}
}
throw new SQLException("Database didn't return a generated id for the inserted call");
}
/**
* Inserts the calls in a single batch without retrieving the generated ids.
*/
@Override
public void insertBatch(Connection connection, List<CallRecord> calls) throws SQLException
{
String sql = "INSERT INTO " + mTable + " (" + COLUMNS + ") VALUES (" + "?, ".repeat(COLUMN_COUNT - 1) + "?)";
List<CallRecord> patched = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
for(CallRecord call: calls)
{
//Calls with patched talkgroups need their generated id for the patched talkgroup rows
if(!call.getPatchedTalkgroups().isEmpty())
{
patched.add(call);
continue;
}
bind(statement, call);
statement.addBatch();
}
statement.executeBatch();
}
for(CallRecord call: patched)
{
insert(connection, call);
}
}
/**
* Inserts the patched talkgroup rows of a call
*/
private void insertPatchedTalkgroups(Connection connection, long callId, List<PatchedTalkgroup> talkgroups)
throws SQLException
{
if(talkgroups.isEmpty())
{
return;
}
try(PreparedStatement statement = connection.prepareStatement("INSERT INTO " + mPatchedTable +
" (call_id, talkgroup, fq) VALUES (?, ?, ?)"))
{
for(PatchedTalkgroup talkgroup: talkgroups)
{
statement.setLong(1, callId);
statement.setLong(2, talkgroup.value());
setString(statement, 3, talkgroup.fullyQualified(), LENGTH_ID);
statement.addBatch();
}
statement.executeBatch();
}
}
/**
* Replaces the patched talkgroup rows of a call
*/
private void replacePatchedTalkgroups(Connection connection, long callId, List<PatchedTalkgroup> talkgroups)
throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mPatchedTable +
" WHERE call_id = ?"))
{
statement.setLong(1, callId);
statement.executeUpdate();
}
insertPatchedTalkgroups(connection, callId, talkgroups);
}
/**
* Loads the patched talkgroups of the patch group calls in the list.
*/
private void loadPatchedTalkgroups(Connection connection, List<CallRecord> calls) throws SQLException
{
Map<Long,CallRecord> patchCalls = new HashMap<>();
for(CallRecord call: calls)
{
if(CallRecord.FORM_PATCH_GROUP.equals(call.getToForm()))
{
patchCalls.put(call.getId(), call);
}
}
if(patchCalls.isEmpty())
{
return;
}
Map<Long,List<PatchedTalkgroup>> talkgroups = new HashMap<>();
String placeholders = String.join(", ", Collections.nCopies(patchCalls.size(), "?"));
try(PreparedStatement statement = connection.prepareStatement("SELECT call_id, talkgroup, fq FROM " +
mPatchedTable + " WHERE call_id IN (" + placeholders + ") ORDER BY call_id, talkgroup"))
{
int index = 1;
for(Long id: patchCalls.keySet())
{
statement.setLong(index++, id);
}
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
talkgroups.computeIfAbsent(rs.getLong(1), id -> new ArrayList<>())
.add(new PatchedTalkgroup(rs.getLong(2), rs.getString(3)));
}
}
}
for(Map.Entry<Long,List<PatchedTalkgroup>> entry: talkgroups.entrySet())
{
patchCalls.get(entry.getKey()).setPatchedTalkgroups(entry.getValue());
}
}
/**
* Updates all columns of the existing call row.
* @return true if the row exists and was updated
*/
@Override
public boolean update(Connection connection, CallRecord call) throws SQLException
{
String assignments = String.join(" = ?, ", COLUMNS.split(", ")) + " = ?";
String sql = "UPDATE " + mTable + " SET " + assignments + " WHERE id = ?";
try(PreparedStatement statement = connection.prepareStatement(sql))
{
bind(statement, call);
statement.setLong(COLUMN_COUNT + 1, call.getId());
if(statement.executeUpdate() == 0)
{
return false;
}
}
if(CallRecord.FORM_PATCH_GROUP.equals(call.getToForm()) || !call.getPatchedTalkgroups().isEmpty())
{
replacePatchedTalkgroups(connection, call.getId(), call.getPatchedTalkgroups());
}
return true;
}
/**
* Binds the call column values to statement parameters 1 - COLUMN_COUNT.
*/
private static void bind(PreparedStatement statement, CallRecord call) throws SQLException
{
int index = 1;
statement.setLong(index++, call.getStartTime());
statement.setLong(index++, call.getEndTime());
statement.setLong(index++, call.getEndTime() > 0 ? call.getDuration() : 0);
statement.setString(index++, call.getCallState().name());
setString(statement, index++, call.getProtocol(), LENGTH_SHORT);
setString(statement, index++, call.getSystem(), LENGTH_NAME);
setString(statement, index++, call.getSite(), LENGTH_NAME);
setString(statement, index++, call.getChannel(), LENGTH_NAME);
statement.setLong(index++, call.getFrequency());
statement.setInt(index++, call.getTimeslot());
setString(statement, index++, call.getToId(), LENGTH_ID);
setLong(statement, index++, call.getToValue());
setString(statement, index++, call.getToForm(), LENGTH_SHORT);
setString(statement, index++, call.getToFullyQualified(), LENGTH_ID);
setString(statement, index++, call.getFromId(), LENGTH_ID);
setLong(statement, index++, call.getFromValue());
setString(statement, index++, call.getFromForm(), LENGTH_SHORT);
setString(statement, index++, call.getFromFullyQualified(), LENGTH_ID);
setString(statement, index++, call.getAliasList(), LENGTH_NAME);
setString(statement, index++, call.getTalkerAlias(), LENGTH_NAME);
statement.setBoolean(index++, call.isEncrypted());
statement.setBoolean(index++, call.isDuplicate());
statement.setInt(index++, call.getPriority());
statement.setBoolean(index++, call.isAliasRecord());
setString(statement, index++, call.getRecordFormat(), LENGTH_SHORT);
setString(statement, index++, call.getFilePath(), LENGTH_PATH);
statement.setLong(index++, call.getFileSize());
statement.setString(index, call.getRecordingState().name());
}
private static void setString(PreparedStatement statement, int index, String value, int maxLength)
throws SQLException
{
if(value == null)
{
statement.setNull(index, Types.VARCHAR);
}
else
{
statement.setString(index, value.length() > maxLength ? value.substring(0, maxLength) : value);
}
}
private static void setLong(PreparedStatement statement, int index, Long value) throws SQLException
{
if(value == null)
{
statement.setNull(index, Types.BIGINT);
}
else
{
statement.setLong(index, value);
}
}
/**
* Creates a call record from the current result set row.
*/
private static CallRecord read(ResultSet rs) throws SQLException
{
CallRecord call = new CallRecord();
call.setId(rs.getLong("id"));
call.setStartTime(rs.getLong("start_time"));
call.setEndTime(rs.getLong("end_time"));
call.setCallState(CallState.fromValue(rs.getString("call_state")));
call.setProtocol(rs.getString("protocol"));
call.setSystem(rs.getString("system_name"));
call.setSite(rs.getString("site_name"));
call.setChannel(rs.getString("channel_name"));
call.setFrequency(rs.getLong("frequency"));
call.setTimeslot(rs.getInt("timeslot"));
call.setToId(rs.getString("to_id"));
call.setToValue(getLong(rs, "to_value"));
call.setToForm(rs.getString("to_form"));
call.setToFullyQualified(rs.getString("to_fq"));
call.setFromId(rs.getString("from_id"));
call.setFromValue(getLong(rs, "from_value"));
call.setFromForm(rs.getString("from_form"));
call.setFromFullyQualified(rs.getString("from_fq"));
call.setAliasList(rs.getString("alias_list"));
call.setTalkerAlias(rs.getString("talker_alias"));
call.setEncrypted(rs.getBoolean("encrypted"));
call.setDuplicate(rs.getBoolean("duplicate_call"));
call.setPriority(rs.getInt("priority"));
call.setAliasRecord(rs.getBoolean("alias_record"));
call.setRecordFormat(rs.getString("record_format"));
call.setFilePath(rs.getString("file_path"));
call.setFileSize(rs.getLong("file_size"));
call.setRecordingState(RecordingState.fromValue(rs.getString("recording_state")));
return call;
}
private static Long getLong(ResultSet rs, String column) throws SQLException
{
long value = rs.getLong(column);
return rs.wasNull() ? null : value;
}
/**
* Marks any calls left in the active state, by a previous session that didn't shut down cleanly, as interrupted.
* Recordings that were being written are left as recorded if the file has data.
* @return count of calls updated
*/
@Override
public int markInterrupted(Connection connection) throws SQLException
{
try(Statement statement = connection.createStatement())
{
int count = statement.executeUpdate("UPDATE " + mTable + " SET call_state = '" +
CallState.INTERRUPTED.name() + "' WHERE call_state = '" + CallState.ACTIVE.name() + "'");
statement.executeUpdate("UPDATE " + mTable + " SET recording_state = '" + RecordingState.RECORDED.name() +
"' WHERE recording_state = '" + RecordingState.RECORDING.name() + "' AND file_path IS NOT NULL");
return count;
}
}
@Override
public int deleteActive(Connection connection) throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mTable +
" WHERE call_state = ?"))
{
statement.setString(1, CallState.ACTIVE.name());
return statement.executeUpdate();
}
}
/**
* Searches for calls matching the criteria, newest first.
* @param criteria to filter by
* @param offset of the first row to return
* @param limit maximum rows to return
*/
@Override
public List<CallRecord> search(Connection connection, CallSearchCriteria criteria, int offset, int limit)
throws SQLException
{
List<Object> parameters = new ArrayList<>();
String where = getWhereClause(criteria, parameters);
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " c" + where +
" ORDER BY start_time DESC, id DESC LIMIT ? OFFSET ?";
parameters.add(limit);
parameters.add(offset);
List<CallRecord> calls = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
bindParameters(statement, parameters);
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
calls.add(read(rs));
}
}
}
loadPatchedTalkgroups(connection, calls);
return calls;
}
/**
* Count of calls matching the criteria
*/
@Override
public long count(Connection connection, CallSearchCriteria criteria) throws SQLException
{
List<Object> parameters = new ArrayList<>();
String sql = "SELECT COUNT(*) FROM " + mTable + " c" + getWhereClause(criteria, parameters);
try(PreparedStatement statement = connection.prepareStatement(sql))
{
bindParameters(statement, parameters);
try(ResultSet rs = statement.executeQuery())
{
return rs.next() ? rs.getLong(1) : 0;
}
}
}
/**
* Builds the WHERE clause (with a leading space) for the criteria and adds the parameter values to the list.
*/
private String getWhereClause(CallSearchCriteria criteria, List<Object> parameters)
{
List<String> clauses = new ArrayList<>();
if(!criteria.to().isEmpty())
{
clauses.add(getIdentifierClause("to", criteria.to(), "to_form IN ('" + CallRecord.FORM_TALKGROUP + "', '" +
CallRecord.FORM_PATCH_GROUP + "')", mPatchedTable, parameters));
}
if(!criteria.from().isEmpty())
{
clauses.add(getIdentifierClause("from", criteria.from(), "from_form = '" + CallRecord.FORM_RADIO + "'",
null, parameters));
}
if(!criteria.talkerAlias().isEmpty())
{
clauses.add("LOWER(talker_alias) LIKE ? ESCAPE '!'");
parameters.add(getLikePattern(criteria.talkerAlias()));
}
if(criteria.protocol() != null)
{
clauses.add("protocol = ?");
parameters.add(criteria.protocol().name());
}
if(criteria.callType() != null)
{
clauses.add(criteria.callType().getWhereClause());
}
if(!criteria.system().isEmpty())
{
clauses.add("LOWER(system_name) LIKE ? ESCAPE '!'");
parameters.add(getLikePattern(criteria.system()));
}
if(criteria.startTime() > 0)
{
clauses.add("start_time >= ?");
parameters.add(criteria.startTime());
}
if(criteria.endTime() > 0)
{
clauses.add("start_time <= ?");
parameters.add(criteria.endTime());
}
return clauses.isEmpty() ? "" : " WHERE " + String.join(" AND ", clauses);
}
/**
* WHERE clause for a TO or FROM identifier filter.
* @param prefix of the identifier columns (to or from)
* @param filter to apply
* @param formClause that restricts an alias filter to the identifier forms that the alias identifiers apply to
* @param patchedTable to also match the talkgroups patched into a patch group call (TO filter), or null
* @param parameters to add the parameter values to
*/
private static String getIdentifierClause(String prefix, IdentifierFilter filter, String formClause,
String patchedTable, List<Object> parameters)
{
String valueColumn = prefix + "_value";
String fqColumn = prefix + "_fq";
String patched = patchedTable != null ? "EXISTS (SELECT 1 FROM " + patchedTable + " p WHERE p.call_id = c.id AND " :
null;
if(filter.isAlias())
{
List<String> matches = new ArrayList<>();
List<Object> matchParameters = new ArrayList<>();
for(IdentifierFilter.ValueRange range: filter.ranges())
{
matches.add("(" + fqColumn + " IS NULL AND protocol = ? AND " + valueColumn + " BETWEEN ? AND ?)");
matchParameters.add(range.protocol().name());
matchParameters.add((long)range.min());
matchParameters.add((long)range.max());
if(patched != null)
{
matches.add("(protocol = ? AND " + patched + "p.fq IS NULL AND p.talkgroup BETWEEN ? AND ?))");
matchParameters.add(range.protocol().name());
matchParameters.add((long)range.min());
matchParameters.add((long)range.max());
}
}
for(IdentifierFilter.FullyQualifiedAddress address: filter.fullyQualified())
{
matches.add("(protocol = ? AND " + fqColumn + " = ?)");
matchParameters.add(address.protocol().name());
matchParameters.add(address.address());
if(patched != null)
{
matches.add("(protocol = ? AND " + patched + "p.fq = ?))");
matchParameters.add(address.protocol().name());
matchParameters.add(address.address());
}
}
if(matches.isEmpty())
{
return "1 = 0";
}
parameters.add(filter.aliasList() != null ? filter.aliasList().toLowerCase(Locale.ROOT) : "");
parameters.addAll(matchParameters);
return "(LOWER(alias_list) = ? AND " + formClause + " AND (" + String.join(" OR ", matches) + "))";
}
Long value = CallSearchCriteria.parseValue(filter.text());
parameters.add(getLikePattern(filter.text()));
if(value != null)
{
parameters.add(value);
if(patched != null)
{
parameters.add(value);
return "(LOWER(" + prefix + "_id) LIKE ? ESCAPE '!' OR " + valueColumn + " = ? OR " + patched +
"p.talkgroup = ?))";
}
return "(LOWER(" + prefix + "_id) LIKE ? ESCAPE '!' OR " + valueColumn + " = ?)";
}
return "LOWER(" + prefix + "_id) LIKE ? ESCAPE '!'";
}
/**
* Case-insensitive 'contains' LIKE pattern with the LIKE wildcard characters escaped.
*/
static String getLikePattern(String text)
{
String escaped = text.toLowerCase(Locale.ROOT).replace("!", "!!").replace("%", "!%").replace("_", "!_");
return "%" + escaped + "%";
}
private static void bindParameters(PreparedStatement statement, List<Object> parameters) throws SQLException
{
for(int x = 0; x < parameters.size(); x++)
{
Object parameter = parameters.get(x);
if(parameter instanceof String s)
{
statement.setString(x + 1, s);
}
else if(parameter instanceof Integer i)
{
statement.setInt(x + 1, i);
}
else if(parameter instanceof Long l)
{
statement.setLong(x + 1, l);
}
else
{
throw new IllegalArgumentException("Unsupported parameter type: " + parameter);
}
}
}
/**
* Reads a page of calls in id order, for transferring calls between databases.
* @param afterId only return calls with an id greater than this value
* @param limit maximum number of calls
*/
@Override
public List<CallRecord> readPage(Connection connection, long afterId, int limit) throws SQLException
{
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE id > ? ORDER BY id LIMIT ?";
List<CallRecord> calls = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
statement.setLong(1, afterId);
statement.setInt(2, limit);
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
calls.add(read(rs));
}
}
}
loadPatchedTalkgroups(connection, calls);
return calls;
}
/**
* Total number of call rows
*/
@Override
public long count(Connection connection) throws SQLException
{
return count(connection, CallSearchCriteria.all());
}
/**
* Transfer keys (see {@link CallRecord#getTransferKey()}) of all calls in the table, for skipping calls that
* already exist when appending.
*/
@Override
public Set<String> getTransferKeys(Connection connection) throws SQLException
{
Set<String> keys = new HashSet<>();
long afterId = 0;
List<CallRecord> page = readPage(connection, afterId, 5000);
while(!page.isEmpty())
{
for(CallRecord call: page)
{
keys.add(call.getTransferKey());
}
afterId = page.getLast().getId();
page = readPage(connection, afterId, 5000);
}
return keys;
}
/**
* Calls with a recording, oldest first, for age-off processing.
* @param startedBefore only include calls that started before this time, or 0 for any time
* @param limit maximum number of calls
*/
@Override
public List<CallRecord> getRecordedCalls(Connection connection, long startedBefore, int limit) throws SQLException
{
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE recording_state = ?" +
(startedBefore > 0 ? " AND start_time < ?" : "") + " ORDER BY start_time, id LIMIT ?";
List<CallRecord> calls = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
int index = 1;
statement.setString(index++, RecordingState.RECORDED.name());
if(startedBefore > 0)
{
statement.setLong(index++, startedBefore);
}
statement.setInt(index, limit);
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
calls.add(read(rs));
}
}
}
return calls;
}
/**
* Completed calls that started before the time, oldest first, for age-off processing.
*/
@Override
public List<CallRecord> getCallsStartedBefore(Connection connection, long startedBefore, int limit)
throws SQLException
{
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE start_time < ? AND call_state <> ? " +
"ORDER BY start_time, id LIMIT ?";
List<CallRecord> calls = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
statement.setLong(1, startedBefore);
statement.setString(2, CallState.ACTIVE.name());
statement.setInt(3, limit);
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
calls.add(read(rs));
}
}
}
return calls;
}
@Override
public List<CallRecord> getDuplicateAndDoNotMonitorCalls(Connection connection, long startedBefore, int limit)
throws SQLException
{
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE start_time < ? AND call_state <> ? AND " +
"(duplicate_call = ? OR (priority <= ? AND alias_record = ?)) ORDER BY start_time, id LIMIT ?";
List<CallRecord> calls = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
statement.setLong(1, startedBefore);
statement.setString(2, CallState.ACTIVE.name());
statement.setBoolean(3, true);
statement.setInt(4, Priority.DO_NOT_MONITOR);
statement.setBoolean(5, false);
statement.setInt(6, limit);
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
calls.add(read(rs));
}
}
}
return calls;
}
/**
* Total size of all recordings that are still available.
*/
@Override
public long getRecordedFileSize(Connection connection) throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement("SELECT SUM(file_size) FROM " + mTable +
" WHERE recording_state = ?"))
{
statement.setString(1, RecordingState.RECORDED.name());
try(ResultSet rs = statement.executeQuery())
{
return rs.next() ? rs.getLong(1) : 0;
}
}
}
/**
* Deletes the call rows
*/
@Override
public void delete(Connection connection, List<Long> ids) throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mTable + " WHERE id = ?"))
{
for(Long id: ids)
{
statement.setLong(1, id);
statement.addBatch();
}
statement.executeBatch();
}
}
/**
* Clears the recording file of the calls and marks the recordings as deleted, keeping the call rows.
*/
@Override
public void markRecordingsDeleted(Connection connection, List<Long> ids) throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement("UPDATE " + mTable + " SET recording_state = ?, " +
"file_path = NULL, file_size = 0 WHERE id = ?"))
{
for(Long id: ids)
{
statement.setString(1, RecordingState.DELETED.name());
statement.setLong(2, id);
statement.addBatch();
}
statement.executeBatch();
}
}
/**
* Schema name
*/
@Override
public String getSchema()
{
return mSchema;
}
}

View File

@@ -1,151 +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.database.call;
import io.github.dsheirer.protocol.Protocol;
import java.util.List;
import java.util.Locale;
/**
* Search filter for the calls table. Empty text fields, empty identifier filters and null values don't filter.
*
* @param to filter for the TO identifier (talkgroup, patch group or radio): typed text or a selected talkgroup alias
* @param from filter for the FROM identifier (radio): typed text or a selected radio alias
* @param talkerAlias text matched against the decoded talker alias
* @param protocol to match or null
* @param callType to match or null
* @param system text matched against the system name
* @param startTime earliest call start time (ms since epoch) or 0
* @param endTime latest call start time (ms since epoch) or 0
*/
public record CallSearchCriteria(IdentifierFilter to, IdentifierFilter from, String talkerAlias, Protocol protocol,
CallType callType, String system, long startTime, long endTime)
{
/**
* Criteria without a call type filter
*/
public CallSearchCriteria(IdentifierFilter to, IdentifierFilter from, String talkerAlias, Protocol protocol,
String system, long startTime, long endTime)
{
this(to, from, talkerAlias, protocol, null, system, startTime, endTime);
}
public CallSearchCriteria
{
to = to == null ? IdentifierFilter.none() : to;
from = from == null ? IdentifierFilter.none() : from;
talkerAlias = clean(talkerAlias);
system = clean(system);
}
/**
* Criteria that match every call
*/
public static CallSearchCriteria all()
{
return new CallSearchCriteria(null, null, null, null, null, 0, 0);
}
private static String clean(String value)
{
return value == null ? "" : value.trim();
}
/**
* Indicates if these criteria match every call.
*/
public boolean isEmpty()
{
return to.isEmpty() && from.isEmpty() && talkerAlias.isEmpty() && system.isEmpty() && protocol == null &&
callType == null && startTime == 0 && endTime == 0;
}
/**
* Parses the text as a decimal identifier value, or null if it isn't a number.
*/
static Long parseValue(String text)
{
if(text == null || text.isEmpty() || text.length() > 18)
{
return null;
}
for(int x = 0; x < text.length(); x++)
{
if(!Character.isDigit(text.charAt(x)))
{
return null;
}
}
return Long.parseLong(text);
}
/**
* Evaluates the criteria against a call in memory, using the same rules as the database query. This is used to
* decide whether a live call belongs in the currently displayed search results.
*/
public boolean matches(CallRecord call)
{
if(!to.isEmpty() && !to.matches(call, call.getToId(), call.getToValue(), call.getToFullyQualified(),
call.isToTalkgroup(), call.getPatchedTalkgroups()))
{
return false;
}
if(!from.isEmpty() && !from.matches(call, call.getFromId(), call.getFromValue(),
call.getFromFullyQualified(), call.isFromRadio(), List.of()))
{
return false;
}
if(!talkerAlias.isEmpty() && !contains(call.getTalkerAlias(), talkerAlias))
{
return false;
}
if(protocol != null && !protocol.name().equals(call.getProtocol()))
{
return false;
}
if(callType != null && call.getCallType() != callType)
{
return false;
}
if(!system.isEmpty() && !contains(call.getSystem(), system))
{
return false;
}
if(startTime > 0 && call.getStartTime() < startTime)
{
return false;
}
return endTime <= 0 || call.getStartTime() <= endTime;
}
private static boolean contains(String value, String text)
{
return value != null && value.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT));
}
}

View File

@@ -1,71 +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.database.call;
/**
* Call life-cycle state
*/
public enum CallState
{
/**
* Call is in progress
*/
ACTIVE("Active"),
/**
* Call completed normally
*/
COMPLETE("Complete"),
/**
* Call was in progress when sdrtrunk stopped (e.g. a crash) and never completed
*/
INTERRUPTED("Interrupted");
private final String mLabel;
CallState(String label)
{
mLabel = label;
}
@Override
public String toString()
{
return mLabel;
}
/**
* Parses the stored value, defaulting to COMPLETE for unrecognized values.
*/
public static CallState fromValue(String value)
{
if(value != null)
{
try
{
return CallState.valueOf(value);
}
catch(IllegalArgumentException iae)
{
//Fall through
}
}
return COMPLETE;
}
}

View File

@@ -1,120 +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.database.call;
/**
* Type of call, derived from the stored TO and FROM identifier forms.
*/
public enum CallType
{
/**
* Call to a talkgroup
*/
GROUP("Group"),
/**
* Call to a patch group (talkgroups patched together)
*/
PATCH("Patch"),
/**
* Private (individual) call from one radio to another radio
*/
PRIVATE("Private"),
/**
* Telephone interconnect call between a radio and a telephone
*/
TELEPHONE("Telephone"),
/**
* Call without a TO identifier that identifies the call type (e.g. conventional analog)
*/
UNKNOWN("");
private static final String FORM_TELEPHONE_NUMBER = "TELEPHONE_NUMBER";
private final String mLabel;
CallType(String label)
{
mLabel = label;
}
/**
* Call type for the TO and FROM identifier forms (Form enumeration names).
*/
public static CallType from(String toForm, String fromForm)
{
if(CallRecord.FORM_PATCH_GROUP.equals(toForm))
{
return PATCH;
}
if(CallRecord.FORM_TALKGROUP.equals(toForm))
{
return GROUP;
}
if(FORM_TELEPHONE_NUMBER.equals(toForm) || FORM_TELEPHONE_NUMBER.equals(fromForm))
{
return TELEPHONE;
}
if(CallRecord.FORM_RADIO.equals(toForm))
{
return PRIVATE;
}
return UNKNOWN;
}
/**
* SQL condition on the to_form and from_form columns that selects the calls of this type, using the same rules as
* {@link #from(String, String)}. The values are constants, so the condition has no parameters.
*/
public String getWhereClause()
{
String patch = "'" + CallRecord.FORM_PATCH_GROUP + "'";
String group = "'" + CallRecord.FORM_TALKGROUP + "'";
String radio = "'" + CallRecord.FORM_RADIO + "'";
String telephone = "'" + FORM_TELEPHONE_NUMBER + "'";
String fromNotTelephone = "(from_form IS NULL OR from_form <> " + telephone + ")";
return switch(this)
{
case PATCH -> "to_form = " + patch;
case GROUP -> "to_form = " + group;
case TELEPHONE -> "(to_form = " + telephone + " OR (from_form = " + telephone + " AND (to_form IS NULL " +
"OR to_form NOT IN (" + patch + ", " + group + "))))";
case PRIVATE -> "(to_form = " + radio + " AND " + fromNotTelephone + ")";
case UNKNOWN -> "((to_form IS NULL OR to_form NOT IN (" + patch + ", " + group + ", " + radio + ", " +
telephone + ")) AND " + fromNotTelephone + ")";
};
}
/**
* Label for selecting the type in a search filter (the unknown type is labeled Other)
*/
public String getFilterLabel()
{
return this == UNKNOWN ? "Other" : mLabel;
}
@Override
public String toString()
{
return mLabel;
}
}

View File

@@ -1,125 +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.database.call;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
/**
* Storage operations for call audio events in one database schema. Each method uses the connection from the caller
* so that the caller controls pooling and transactions.
*/
public interface ICallRepository
{
/**
* Inserts the call and assigns the generated row id to the call.
* @return generated row id
*/
long insert(Connection connection, CallRecord call) throws SQLException;
/**
* Inserts the calls in a single batch without retrieving the generated ids.
*/
void insertBatch(Connection connection, List<CallRecord> calls) throws SQLException;
/**
* Updates the existing call row identified by the call's id.
* @return true if the row exists and was updated
*/
boolean update(Connection connection, CallRecord call) throws SQLException;
/**
* Marks calls left in the active state by a previous session as interrupted.
* @return count of calls updated
*/
int markInterrupted(Connection connection) throws SQLException;
/**
* Deletes the calls that are in progress. Used when switching databases: calls in progress continue in the new
* database, so their rows are removed from the old database.
* @return count of calls deleted
*/
int deleteActive(Connection connection) throws SQLException;
/**
* Calls matching the criteria, newest first.
*/
List<CallRecord> search(Connection connection, CallSearchCriteria criteria, int offset, int limit)
throws SQLException;
/**
* Count of calls matching the criteria
*/
long count(Connection connection, CallSearchCriteria criteria) throws SQLException;
/**
* Total number of calls
*/
long count(Connection connection) throws SQLException;
/**
* Page of calls in id order with an id greater than the argument, for transfers between databases.
*/
List<CallRecord> readPage(Connection connection, long afterId, int limit) throws SQLException;
/**
* Transfer keys of all calls (see {@link CallRecord#getTransferKey()})
*/
Set<String> getTransferKeys(Connection connection) throws SQLException;
/**
* Calls with an available recording, oldest first.
* @param startedBefore only calls that started before this time, or 0 for any time
*/
List<CallRecord> getRecordedCalls(Connection connection, long startedBefore, int limit) throws SQLException;
/**
* Calls that are not in progress and started before the time, oldest first.
*/
List<CallRecord> getCallsStartedBefore(Connection connection, long startedBefore, int limit) throws SQLException;
/**
* Completed calls that started before the time and are duplicates, or Do Not Monitor calls without an alias record
* option, oldest first.
*/
List<CallRecord> getDuplicateAndDoNotMonitorCalls(Connection connection, long startedBefore, int limit)
throws SQLException;
/**
* Total size in bytes of all available recordings
*/
long getRecordedFileSize(Connection connection) throws SQLException;
/**
* Deletes the call rows
*/
void delete(Connection connection, List<Long> ids) throws SQLException;
/**
* Clears the recording file of the calls and marks their recordings deleted, keeping the call rows.
*/
void markRecordingsDeleted(Connection connection, List<Long> ids) throws SQLException;
/**
* Schema that holds the calls table
*/
String getSchema();
}

View File

@@ -1,285 +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.database.call;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.id.AliasID;
import io.github.dsheirer.alias.id.radio.P25FullyQualifiedRadio;
import io.github.dsheirer.alias.id.radio.Radio;
import io.github.dsheirer.alias.id.radio.RadioRange;
import io.github.dsheirer.alias.id.talkgroup.P25FullyQualifiedTalkgroup;
import io.github.dsheirer.alias.id.talkgroup.Talkgroup;
import io.github.dsheirer.alias.id.talkgroup.TalkgroupRange;
import io.github.dsheirer.protocol.Protocol;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Search filter for the TO or FROM identifier of a call. The filter either matches typed text against the formatted
* identifier (or the exact identifier value when the text is a number), or matches the identifiers of a selected
* alias: calls of the alias's alias list whose identifier value is one of the alias's values or ranges, or whose fully
* qualified (roaming) address is one of the alias's fully qualified identifiers. This uses the same matching as the
* alias list, so a search for an alias finds the calls that the alias list currently aliases with that alias.
*
* @param text typed text, or empty for no text filter (ignored when an alias is selected)
* @param aliasName of the selected alias, or null
* @param aliasList name of the selected alias, or null
* @param ranges of identifier values for the selected alias
* @param fullyQualified addresses for the selected alias
*/
public record IdentifierFilter(String text, String aliasName, String aliasList, List<ValueRange> ranges,
List<FullyQualifiedAddress> fullyQualified)
{
/**
* Range of identifier values (inclusive) for a protocol
*/
public record ValueRange(Protocol protocol, int min, int max)
{
public boolean contains(Protocol callProtocol, long value)
{
return protocol == callProtocol && min <= value && value <= max;
}
}
/**
* Fully qualified identifier address (wacn.system.id) for a protocol
*/
public record FullyQualifiedAddress(Protocol protocol, String address) {}
public IdentifierFilter
{
text = text == null ? "" : text.trim();
ranges = ranges == null ? List.of() : List.copyOf(ranges);
fullyQualified = fullyQualified == null ? List.of() : List.copyOf(fullyQualified);
}
/**
* Filter that matches every call
*/
public static IdentifierFilter none()
{
return new IdentifierFilter("", null, null, null, null);
}
/**
* Filter for typed text
*/
public static IdentifierFilter text(String text)
{
return new IdentifierFilter(text, null, null, null, null);
}
/**
* Filter for the talkgroup identifiers (talkgroups, ranges, fully qualified talkgroups) of the alias
*/
public static IdentifierFilter talkgroupAlias(Alias alias)
{
List<ValueRange> ranges = new ArrayList<>();
List<FullyQualifiedAddress> fullyQualified = new ArrayList<>();
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isValid())
{
continue;
}
if(id instanceof P25FullyQualifiedTalkgroup fqt)
{
fullyQualified.add(new FullyQualifiedAddress(fqt.getProtocol(), fqt.getHashKey()));
}
else if(id instanceof Talkgroup talkgroup)
{
ranges.add(new ValueRange(talkgroup.getProtocol(), talkgroup.getValue(), talkgroup.getValue()));
}
else if(id instanceof TalkgroupRange range)
{
ranges.add(new ValueRange(range.getProtocol(), range.getMinTalkgroup(), range.getMaxTalkgroup()));
}
}
return new IdentifierFilter("", alias.getName(), alias.getAliasListName(), ranges, fullyQualified);
}
/**
* Filter for the radio identifiers (radios, ranges, fully qualified radios) of the alias
*/
public static IdentifierFilter radioAlias(Alias alias)
{
List<ValueRange> ranges = new ArrayList<>();
List<FullyQualifiedAddress> fullyQualified = new ArrayList<>();
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isValid())
{
continue;
}
if(id instanceof P25FullyQualifiedRadio fqr)
{
fullyQualified.add(new FullyQualifiedAddress(fqr.getProtocol(), fqr.getHashKey()));
}
else if(id instanceof Radio radio)
{
ranges.add(new ValueRange(radio.getProtocol(), radio.getValue(), radio.getValue()));
}
else if(id instanceof RadioRange range)
{
ranges.add(new ValueRange(range.getProtocol(), range.getMinRadio(), range.getMaxRadio()));
}
}
return new IdentifierFilter("", alias.getName(), alias.getAliasListName(), ranges, fullyQualified);
}
/**
* Indicates if the alias has talkgroup identifiers that a talkgroup alias filter can search for
*/
public static boolean hasTalkgroups(Alias alias)
{
IdentifierFilter filter = talkgroupAlias(alias);
return !filter.ranges().isEmpty() || !filter.fullyQualified().isEmpty();
}
/**
* Indicates if the alias has radio identifiers that a radio alias filter can search for
*/
public static boolean hasRadios(Alias alias)
{
IdentifierFilter filter = radioAlias(alias);
return !filter.ranges().isEmpty() || !filter.fullyQualified().isEmpty();
}
/**
* Indicates if this filter is for a selected alias
*/
public boolean isAlias()
{
return aliasName != null;
}
/**
* Indicates if this filter doesn't filter anything. An alias filter always filters: an alias without matching
* identifiers matches no calls.
*/
public boolean isEmpty()
{
return !isAlias() && text.isEmpty();
}
/**
* Evaluates the filter against a call identifier in memory, using the same rules as the database query.
* @param call to evaluate
* @param formatted identifier text
* @param value of the identifier, or null
* @param fullyQualifiedAddress of the identifier, or null
* @param formMatches true if the identifier form is the form that the alias identifiers apply to
* @param patched talkgroups patched into the TO patch group, which also match, or an empty list
*/
boolean matches(CallRecord call, String formatted, Long value, String fullyQualifiedAddress, boolean formMatches,
List<PatchedTalkgroup> patched)
{
if(isAlias())
{
if(!formMatches || call.getAliasList() == null || aliasList == null ||
!call.getAliasList().equalsIgnoreCase(aliasList))
{
return false;
}
Protocol protocol = call.getProtocolValue();
for(PatchedTalkgroup talkgroup: patched)
{
if(matchesAlias(protocol, talkgroup.value(), talkgroup.fullyQualified()))
{
return true;
}
}
return matchesAlias(protocol, value, fullyQualifiedAddress);
}
if(text.isEmpty())
{
return true;
}
Long parsed = CallSearchCriteria.parseValue(text);
if(parsed != null)
{
if(parsed.equals(value))
{
return true;
}
for(PatchedTalkgroup talkgroup: patched)
{
if(talkgroup.value() == parsed)
{
return true;
}
}
}
return formatted != null && formatted.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT));
}
/**
* Indicates if the identifier value or fully qualified address matches the alias identifiers
*/
private boolean matchesAlias(Protocol protocol, Long value, String fullyQualifiedAddress)
{
if(fullyQualifiedAddress != null)
{
for(FullyQualifiedAddress address: fullyQualified)
{
if(address.protocol() == protocol && address.address().equals(fullyQualifiedAddress))
{
return true;
}
}
return false;
}
if(value != null)
{
for(ValueRange range: ranges)
{
if(range.contains(protocol, value))
{
return true;
}
}
}
return false;
}
@Override
public String toString()
{
return isAlias() ? aliasName + " (" + aliasList + ")" : text;
}
}

View File

@@ -1,34 +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.database.call;
/**
* A talkgroup that is patched into the patch group of a call. The protocol is the protocol of the call.
*
* @param value of the talkgroup
* @param fullyQualified address (wacn.system.id) of a fully qualified (roaming) talkgroup, or null
*/
public record PatchedTalkgroup(long value, String fullyQualified)
{
@Override
public String toString()
{
return fullyQualified != null ? value + "(" + fullyQualified + ")" : String.valueOf(value);
}
}

View File

@@ -1,79 +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.database.call;
/**
* State of the audio recording file for a call
*/
public enum RecordingState
{
/**
* Call is not recorded
*/
NONE("Not Recorded"),
/**
* Recording is being written
*/
RECORDING("Recording"),
/**
* Recording is complete and the file is available
*/
RECORDED("Recorded"),
/**
* Recording file was deleted by an age-off rule or by the user
*/
DELETED("Deleted"),
/**
* Recording failed with an error
*/
FAILED("Failed");
private final String mLabel;
RecordingState(String label)
{
mLabel = label;
}
@Override
public String toString()
{
return mLabel;
}
/**
* Parses the stored value, defaulting to NONE for unrecognized values.
*/
public static RecordingState fromValue(String value)
{
if(value != null)
{
try
{
return RecordingState.valueOf(value);
}
catch(IllegalArgumentException iae)
{
//Fall through
}
}
return NONE;
}
}

View File

@@ -1,75 +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.database.dialect;
import io.github.dsheirer.database.DatabaseConfiguration;
import java.nio.file.Path;
/**
* Built-in H2 embedded database, stored in the application 'db' directory.
*/
public class H2Dialect implements IDatabaseDialect
{
public static final String DATABASE_FILE_NAME = "sdrtrunk";
@Override
public String getDriverClass()
{
return "org.h2.Driver";
}
@Override
public int getDefaultPort()
{
return 0;
}
@Override
public boolean isNetwork()
{
return false;
}
@Override
public boolean requiresDatabaseName()
{
return false;
}
@Override
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
{
//DB_CLOSE_ON_EXIT=FALSE: the application closes the pool during shutdown, after the last call update.
return "jdbc:h2:file:" + databaseDirectory.resolve(DATABASE_FILE_NAME).toAbsolutePath() +
";DB_CLOSE_ON_EXIT=FALSE";
}
@Override
public String getIdentityColumn()
{
return "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
}
@Override
public String getDropSchemaStatement(String schema)
{
return "DROP SCHEMA IF EXISTS " + schema + " CASCADE";
}
}

View File

@@ -1,77 +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.database.dialect;
import io.github.dsheirer.database.DatabaseConfiguration;
import java.nio.file.Path;
/**
* Per-engine connection settings and SQL differences for a call database. Everything else that sdrtrunk sends to
* the database is portable SQL shared by all engines.
*
* All supported engines support schemas, so sdrtrunk always qualifies its tables with the configured schema name.
*/
public interface IDatabaseDialect
{
/**
* JDBC driver class name
*/
String getDriverClass();
/**
* Default TCP port for a network database server, or 0 for an embedded database.
*/
int getDefaultPort();
/**
* Indicates if this is a network database server that needs a host, port and credentials.
*/
boolean isNetwork();
/**
* Indicates if the engine needs a database name in addition to the schema name.
*/
boolean requiresDatabaseName();
/**
* JDBC URL for the configuration
* @param configuration with the host, port and database name
* @param databaseDirectory for embedded database files
*/
String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory);
/**
* Column definition for an auto-generated 64-bit primary key.
*/
String getIdentityColumn();
/**
* Statement that creates the schema when it doesn't exist.
*/
default String getCreateSchemaStatement(String schema)
{
return "CREATE SCHEMA IF NOT EXISTS " + schema;
}
/**
* Statement that removes the schema and all of its tables.
*/
String getDropSchemaStatement(String schema);
}

View File

@@ -1,72 +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.database.dialect;
import io.github.dsheirer.database.DatabaseConfiguration;
import java.nio.file.Path;
/**
* MariaDB network database server. In MariaDB a schema is a database.
*/
public class MariaDBDialect implements IDatabaseDialect
{
@Override
public String getDriverClass()
{
return "org.mariadb.jdbc.Driver";
}
@Override
public int getDefaultPort()
{
return 3306;
}
@Override
public boolean isNetwork()
{
return true;
}
@Override
public boolean requiresDatabaseName()
{
return false;
}
@Override
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
{
return "jdbc:mariadb://" + configuration.host() + ":" + configuration.port() + "/";
}
@Override
public String getIdentityColumn()
{
return "BIGINT AUTO_INCREMENT PRIMARY KEY";
}
@Override
public String getDropSchemaStatement(String schema)
{
//Dropping a MariaDB schema (database) drops all of its tables
return "DROP SCHEMA IF EXISTS " + schema;
}
}

View File

@@ -1,72 +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.database.dialect;
import io.github.dsheirer.database.DatabaseConfiguration;
import java.nio.file.Path;
/**
* PostgreSQL network database server. The schema lives inside the database named in the configuration.
*/
public class PostgreSQLDialect implements IDatabaseDialect
{
@Override
public String getDriverClass()
{
return "org.postgresql.Driver";
}
@Override
public int getDefaultPort()
{
return 5432;
}
@Override
public boolean isNetwork()
{
return true;
}
@Override
public boolean requiresDatabaseName()
{
return true;
}
@Override
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
{
return "jdbc:postgresql://" + configuration.host() + ":" + configuration.port() + "/" +
configuration.database();
}
@Override
public String getIdentityColumn()
{
return "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
}
@Override
public String getDropSchemaStatement(String schema)
{
return "DROP SCHEMA IF EXISTS " + schema + " CASCADE";
}
}

View File

@@ -271,26 +271,6 @@ public abstract class C4FMSymbolProcessor
return Integer.MAX_VALUE; return Integer.MAX_VALUE;
} }
/**
* Number of symbols without a sync detection after which syncInactivityTimeout() is invoked. Default is zero,
* which disables the timeout.
* @return timeout as a count of symbols, or zero to disable.
*/
protected int getSyncInactivityTimeoutSymbolCount()
{
return 0;
}
/**
* Notification that no sync was detected for the sync inactivity timeout period (see
* getSyncInactivityTimeoutSymbolCount()). Invoked once per period of inactivity. Subclasses can override this to
* reset protocol specific state that was learned from the signal. Default implementation is a no-op.
*/
protected void syncInactivityTimeout()
{
//No-op default implementation
}
/** /**
* Number of consecutive sync periods (capped at 3) where a sync was detected within the max message length. * Number of consecutive sync periods (capped at 3) where a sync was detected within the max message length.
*/ */
@@ -426,11 +406,6 @@ public abstract class C4FMSymbolProcessor
symbolsSinceLastSync++; symbolsSinceLastSync++;
if(symbolsSinceLastSync == getSyncInactivityTimeoutSymbolCount())
{
syncInactivityTimeout();
}
//Clear synchronized state when we miss a sync period. //Clear synchronized state when we miss a sync period.
if(mSynchronized && symbolsSinceLastSync > getMaxMessageDibitLength()) if(mSynchronized && symbolsSinceLastSync > getMaxMessageDibitLength())
{ {

View File

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

View File

@@ -79,11 +79,9 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
private static final int MAXIMUM_QUEUED_BATCHES = 50; private static final int MAXIMUM_QUEUED_BATCHES = 50;
/** /**
* Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batch being filled and the batch * Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batches queued for channel output.
* being transformed. Channel output processors copy their channels from a batch instead of retaining it, so no
* other batches are held.
*/ */
private static final int MAXIMUM_POOLED_BATCHES = MAXIMUM_QUEUED_BATCHES + 2; private static final int MAXIMUM_POOLED_BATCHES = 2 * MAXIMUM_QUEUED_BATCHES;
//Sized to process 40 times per second //Sized to process 40 times per second
private IFFTProcessorDispatcher mIFFTProcessorDispatcher = new IFFTProcessorDispatcher(25); private IFFTProcessorDispatcher mIFFTProcessorDispatcher = new IFFTProcessorDispatcher(25);

View File

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

View File

@@ -180,8 +180,7 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
/** /**
* Performs the output processor update. This method must be invoked on the channel results calling thread so that * Performs the output processor update. This method must be invoked on the channel results calling thread so that
* replacing the output processor doesn't overlap with delivery of channel results to it. The output processor * replacing the output processor doesn't overlap with delivery of channel results to it. The output processor
* applies channel index changes as it copies the next batch, and applies mixer and filter changes on its own * applies the configuration changes on its own dispatcher thread.
* dispatcher thread at that same batch.
* @param channelCalculator for updates * @param channelCalculator for updates
* @param filterManager for updates * @param filterManager for updates
* @throws IllegalArgumentException if there's an issue. * @throws IllegalArgumentException if there's an issue.

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -24,7 +24,6 @@ import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager; import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import io.github.dsheirer.util.Dispatcher; import io.github.dsheirer.util.Dispatcher;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -35,20 +34,12 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
private final static Logger mLog = LoggerFactory.getLogger(ChannelOutputProcessor.class); private final static Logger mLog = LoggerFactory.getLogger(ChannelOutputProcessor.class);
/** /**
* Maximum queued channel sample batches, about one second of samples. A full batch is dropped when this channel * Maximum queued channel results batches, about one second of samples. A full batch is dropped when this channel
* falls behind, which preserves the even-sized batch block parity that two-channel synthesis relies on. * falls behind, which preserves the even-sized batch block parity that two-channel synthesis relies on.
*/ */
private static final int MAXIMUM_QUEUED_BATCHES = 50; private static final int MAXIMUM_QUEUED_BATCHES = 50;
/** private Dispatcher<QueuedChannelResults> mChannelResultsDispatcher;
* Maximum channel sample arrays held for reuse: the queued batches plus the batch being processed and the batch
* being copied.
*/
private static final int MAXIMUM_POOLED_ARRAYS = MAXIMUM_QUEUED_BATCHES + 2;
private Dispatcher<QueuedChannelSamples> mChannelSamplesDispatcher;
private final Queue<float[]> mSamplePool = new ArrayBlockingQueue<>(MAXIMUM_POOLED_ARRAYS);
private volatile int[] mChannelOffsets = new int[0];
private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>(); private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>();
private final AtomicLong mBatchSequence = new AtomicLong(); private final AtomicLong mBatchSequence = new AtomicLong();
private HeartbeatManager mHeartbeatManager; private HeartbeatManager mHeartbeatManager;
@@ -69,45 +60,25 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
mInputChannelCount = inputChannelCount; mInputChannelCount = inputChannelCount;
//Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate) //Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate)
mHeartbeatManager = heartbeatManager; mHeartbeatManager = heartbeatManager;
mChannelSamplesDispatcher = new Dispatcher<>(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES); mChannelResultsDispatcher = new Dispatcher(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelSamplesDispatcher.setListener(queued -> { mChannelResultsDispatcher.setListener(queued -> {
try try
{ {
applyPendingUpdates(queued.sequence()); applyPendingUpdates(queued.sequence());
mCurrentSampleTimestamp = queued.timestamp(); mCurrentSampleTimestamp = queued.channelResults().getTimestamp();
process(queued.samples(), queued.blockCount()); process(queued.channelResults());
} }
catch(Throwable t) catch(Throwable t)
{ {
mLog.error("Error processing channel samples", t); mLog.error("Error processing channel results", t);
} }
finally finally
{ {
mSamplePool.offer(queued.samples()); queued.channelResults().release();
} }
}); });
} }
/**
* Sets the I/Q offsets within each channel results block for the polyphase channel(s) that this processor copies.
* The offsets take effect at the first channel results batch received after this method is invoked, the same as a
* change queued with enqueueUpdate(), so a change of offsets and of the mixer frequency apply to the same batch.
* This should only be invoked on the thread that delivers channel results, or before results are delivered.
* @param offsets for each polyphase channel, which is twice the channel index.
*/
protected void setChannelOffsets(int... offsets)
{
mChannelOffsets = offsets.clone();
}
/**
* Current I/Q offsets within each channel results block for the polyphase channel(s) that this processor copies.
*/
protected int[] getChannelOffsets()
{
return mChannelOffsets.clone();
}
/** /**
* Queues a configuration change to apply on the dispatcher thread, so that configuration changes don't overlap with * Queues a configuration change to apply on the dispatcher thread, so that configuration changes don't overlap with
* sample processing. The change takes effect at the first channel results batch received after this method is * sample processing. The change takes effect at the first channel results batch received after this method is
@@ -148,13 +119,13 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
@Override @Override
public void start() public void start()
{ {
mChannelSamplesDispatcher.start(); mChannelResultsDispatcher.start();
} }
@Override @Override
public void stop() public void stop()
{ {
mChannelSamplesDispatcher.stop(); mChannelResultsDispatcher.stop();
} }
/** /**
@@ -176,66 +147,22 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
{ {
} }
/**
* Copies this processor's polyphase channel(s) from the channel results batch and queues the copy for processing on
* the dispatcher thread. The copy is small (about 8 kB per polyphase channel for a 1024 block batch), so the batch
* isn't retained beyond this method and its large shared sample array returns to the channelizer's pool as soon as
* the channelizer has dispatched it to every channel. A slow channel then queues only its own samples.
*
* @param channelResults batch to copy from
*/
@Override @Override
public void receiveChannelResults(ChannelResultsBatch channelResults) public void receiveChannelResults(ChannelResultsBatch channelResults)
{ {
long sequence = mBatchSequence.incrementAndGet(); channelResults.retain();
if(!mChannelSamplesDispatcher.isRunning()) if(!mChannelResultsDispatcher.offer(new QueuedChannelResults(channelResults, mBatchSequence.incrementAndGet())))
{ {
return; channelResults.release();
}
int[] offsets = mChannelOffsets;
float[] source = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int blockCount = channelResults.getBlockCount();
float[] samples = getPooledArray(blockCount * offsets.length * 2);
int pointer = 0;
for(int block = 0; block < blockCount; block++)
{
int blockOffset = block * blockLength;
for(int offset : offsets)
{
samples[pointer++] = source[blockOffset + offset];
samples[pointer++] = source[blockOffset + offset + 1];
}
}
if(!mChannelSamplesDispatcher.offer(new QueuedChannelSamples(samples, blockCount, channelResults.getTimestamp(),
sequence)))
{
mSamplePool.offer(samples);
} }
} }
/** /**
* Provides a reused sample array of the requested length when one is available, or a new array. * Sub-class implementation to process one polyphase channelizer results batch.
* @param channelResults to process
*/ */
private float[] getPooledArray(int length) public abstract void process(ChannelResultsBatch channelResults);
{
float[] samples = mSamplePool.poll();
return samples != null && samples.length == length ? samples : new float[length];
}
/**
* Sub-class implementation to process one batch of copied channel samples.
* @param samples for each block in order, with the I/Q pair of each polyphase channel in the order of the channel
* offsets, for example I1,Q1,I2,Q2 per block for two channels.
* @param blockCount number of blocks. Batches start on an even block index, so the index of a block within this
* batch has the same parity as its absolute block index.
*/
public abstract void process(float[] samples, int blockCount);
@Override @Override
public int getInputChannelCount() public int getInputChannelCount()
@@ -244,10 +171,9 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
} }
/** /**
* Copied channel samples with the timestamp of the batch they were copied from and the batch's position in the * Channel results batch and its position in the sequence of received batches.
* sequence of received batches.
*/ */
private record QueuedChannelSamples(float[] samples, int blockCount, long timestamp, long sequence) {} private record QueuedChannelResults(ChannelResultsBatch channelResults, long sequence) {}
/** /**
* Configuration change and the sequence number of the last batch received before the change was requested. * Configuration change and the sequence number of the last batch received before the change was requested.

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -18,9 +18,9 @@
*/ */
package io.github.dsheirer.dsp.filter.channelizer.output; package io.github.dsheirer.dsp.filter.channelizer.output;
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
import io.github.dsheirer.sample.complex.ComplexSamples; import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager; import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -29,6 +29,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{ {
private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class); private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class);
private final OneChannelMixerAssembler mMixerAssembler; private final OneChannelMixerAssembler mMixerAssembler;
private int mChannelOffset;
/** /**
* Processor to extract a single channel from a polyphase channelizer and produce an output I/Q complex sample * Processor to extract a single channel from a polyphase channelizer and produce an output I/Q complex sample
@@ -54,7 +55,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("One Channel Output Processor"); sb.append("One Channel Output Processor");
sb.append("\n\tIndex (doubled) ").append(Arrays.toString(getChannelOffsets())); sb.append("\n\tIndex (doubled) [").append(mChannelOffset).append("]");
sb.append("\n\tMixer Assembler: none"); sb.append("\n\tMixer Assembler: none");
return sb.toString(); return sb.toString();
} }
@@ -80,7 +81,8 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
//Set the channelized output results offset to twice the channel index to account for each channel having //Set the channelized output results offset to twice the channel index to account for each channel having
//an I/Q pair //an I/Q pair
setChannelOffsets(indexes.get(0) * 2); int channelOffset = indexes.get(0) * 2;
enqueueUpdate(() -> mChannelOffset = channelOffset);
} }
@Override @Override
@@ -90,18 +92,19 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
} }
/** /**
* Passes the copied channel samples to the assembler. The assembler will apply frequency translation and gain and * Extract the channel from the channel results array and pass to the assembler. The assembler will
* indicate when a buffer is fully assembled. * apply frequency translation and gain and indicate when a buffer is fully assembled.
* *
* @param samples containing an I/Q pair for each block (I0,Q0,I1,Q1...In,Qn) * @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
* @param blockCount number of blocks
*/ */
@Override @Override
public void process(float[] samples, int blockCount) public void process(ChannelResultsBatch channelResults)
{ {
int length = blockCount * 2; float[] samples = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int channelOffset = mChannelOffset;
for(int index = 0; index < length; index += 2) for(int index = channelOffset; index < samples.length; index += blockLength)
{ {
mMixerAssembler.receive(samples[index], samples[index + 1]); mMixerAssembler.receive(samples[index], samples[index + 1]);

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -18,9 +18,9 @@
*/ */
package io.github.dsheirer.dsp.filter.channelizer.output; package io.github.dsheirer.dsp.filter.channelizer.output;
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
import io.github.dsheirer.sample.complex.ComplexSamples; import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager; import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -29,6 +29,8 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{ {
private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class); private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class);
private TwoChannelMixerAssembler mMixerAssembler; private TwoChannelMixerAssembler mMixerAssembler;
private int mChannelOffset1;
private int mChannelOffset2;
/** /**
* Processor to extract two channels from a polyphase channelizer, synthesize/recombine the channels, apply * Processor to extract two channels from a polyphase channelizer, synthesize/recombine the channels, apply
@@ -58,7 +60,7 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Two Channel Output Processor"); sb.append("Two Channel Output Processor");
sb.append("\n\tIndices (doubled) ").append(Arrays.toString(getChannelOffsets())); sb.append("\n\tIndices (doubled) 1 [").append(mChannelOffset1).append("] 2 [").append(mChannelOffset2).append("]");
sb.append("\n\tMixer Assembler: ").append(mMixerAssembler.getStateDescription()); sb.append("\n\tMixer Assembler: ").append(mMixerAssembler.getStateDescription());
return sb.toString(); return sb.toString();
} }
@@ -96,32 +98,45 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
//Set the channelized output results offsets to twice the channel index to account for each channel having //Set the channelized output results offsets to twice the channel index to account for each channel having
//an I/Q pair //an I/Q pair
setChannelOffsets(indexes.get(0) * 2, indexes.get(1) * 2); int channelOffset1 = indexes.get(0) * 2;
int channelOffset2 = indexes.get(1) * 2;
enqueueUpdate(() -> {
mChannelOffset1 = channelOffset1;
mChannelOffset2 = channelOffset2;
});
} }
/** /**
* Synthesizes the two copied channels, applies frequency translation, and delivers the frequency-corrected channel * Extract the channel from the channel results array, apply frequency translation, and deliver the
* I/Q sample set to the complex sample listener. * extracted frequency-corrected channel I/Q sample set to the complex sample listener.
* *
* @param samples containing an I/Q pair for each of the two channels per block (I1,Q1,I2,Q2 ...) * @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
* @param blockCount number of blocks
*/ */
@Override @Override
public void process(float[] samples, int blockCount) public void process(ChannelResultsBatch channelResults)
{ {
float[] samples = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int blockCount = channelResults.getBlockCount();
int channelOffset1 = mChannelOffset1;
int channelOffset2 = mChannelOffset2;
//Translate channel 2 up by FS/2 (multiply by (-1)^n) so that it sits adjacent to channel 1 for synthesis. The //Translate channel 2 up by FS/2 (multiply by (-1)^n) so that it sits adjacent to channel 1 for synthesis. The
//channelizer dispatches even-sized batches, so the index within the batch carries the absolute block parity. //channelizer dispatches even-sized batches, so the index within the batch carries the absolute block parity.
for(int x = 0; x < blockCount; x++) for(int x = 0; x < blockCount; x++)
{ {
int block = x * 4; int block = x * blockLength;
if((x & 1) == 0) if((x & 1) == 0)
{ {
mMixerAssembler.receive(samples[block], samples[block + 1], samples[block + 2], samples[block + 3]); mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
samples[block + channelOffset2], samples[block + channelOffset2 + 1]);
} }
else else
{ {
mMixerAssembler.receive(samples[block], samples[block + 1], -samples[block + 2], -samples[block + 3]); mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
-samples[block + channelOffset2], -samples[block + channelOffset2 + 1]);
} }
if(mMixerAssembler.hasBuffer()) if(mMixerAssembler.hasBuffer())

View File

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

View File

@@ -1,14 +1,16 @@
package io.github.dsheirer.dsp.filter.design; package io.github.dsheirer.dsp.filter.design;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage; import javafx.stage.Stage;
public class FilterViewerLauncher public class FilterViewerLauncher
{ {
private JFXPanel mJFXPanel;
public FilterViewerLauncher() public FilterViewerLauncher()
{ {
FxToolkit.ensureStarted(); mJFXPanel = new JFXPanel();
Platform.runLater(() -> Platform.runLater(() ->
{ {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -19,191 +19,54 @@
package io.github.dsheirer.filter; package io.github.dsheirer.filter;
import io.github.dsheirer.gui.ApplicationIcons; import java.awt.Component;
import io.github.dsheirer.gui.theme.ThemeManager; import net.miginfocom.swing.MigLayout;
import java.util.ArrayList;
import java.util.Comparator; import javax.swing.JButton;
import java.util.List; import javax.swing.JFrame;
import javafx.geometry.Insets; import javax.swing.JScrollPane;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.StringConverter;
/** /**
* Window for turning filters and filter elements on and off. Each filter shows how many of its elements are * Filter editor
* enabled. Checking a filter turns all of its elements on or off. Changes apply immediately. * @param <T> item type for editing
*
* @param <T> type of item that is filtered
*/ */
public class FilterEditor<T> public class FilterEditor<T> extends JFrame
{ {
private final Stage mStage = new Stage(); private FilterEditorPanel<T> mEditorPanel;
private final TreeView<Object> mTreeView = new TreeView<>();
/** /**
* Constructs an instance. JavaFX thread only. * Constructor
* @param title for the window * @param title for the editor window frame
* @param owner window, or null * @param owner to register the popup location
* @param filterSet to edit * @param filterSet to use initially
*/ */
public FilterEditor(String title, Window owner, FilterSet<T> filterSet) public FilterEditor(String title, Component owner, FilterSet<T> filterSet)
{ {
if(filterSet == null) if(filterSet == null)
{ {
throw new IllegalArgumentException("Unable to construct FilterEditor - FilterSet cannot be null"); throw new IllegalArgumentException("Unable to construct FilterEditor - FilterSet cannot be null");
} }
setTitle(title);
mTreeView.setShowRoot(true); setSize(600, 400);
mTreeView.setCellFactory(CheckBoxTreeCell.forTreeView(item -> ((CheckBoxTreeItem<Object>)item) setLocationRelativeTo(owner);
.selectedProperty(), new LabelConverter())); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
VBox.setVgrow(mTreeView, Priority.ALWAYS); setLayout(new MigLayout("", "[grow,fill]", "[grow,fill][]"));
mEditorPanel = new FilterEditorPanel<>(filterSet);
Button expand = new Button("Expand All"); JScrollPane scroller = new JScrollPane(mEditorPanel);
expand.setOnAction(event -> setExpanded(mTreeView.getRoot(), true)); scroller.getVerticalScrollBar().setUnitIncrement(16);
Button collapse = new Button("Collapse All"); scroller.setViewportView(mEditorPanel);
collapse.setOnAction(event -> { add(scroller, "wrap");
setExpanded(mTreeView.getRoot(), false); JButton close = new JButton("Close");
mTreeView.getRoot().setExpanded(true); close.addActionListener(e -> dispose());
}); add(close);
Button close = new Button("Close");
close.setCancelButton(true);
close.setDefaultButton(true);
close.setOnAction(event -> mStage.close());
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox buttons = new HBox(8, expand, collapse, spacer, close);
buttons.setAlignment(Pos.CENTER_LEFT);
VBox root = new VBox(8, mTreeView, buttons);
root.setPadding(new Insets(10));
Scene scene = new Scene(root, 600, 500);
ThemeManager.getInstance().register(scene);
mStage.setScene(scene);
mStage.setTitle(title);
ApplicationIcons.apply(mStage);
if(owner != null)
{
mStage.initOwner(owner);
}
updateFilterSet(filterSet);
} }
/** /**
* Shows the window and brings it to the front. JavaFX thread only. * Updates this editor with the filterset.
*/ * @param filterSet to use in this editor.
public void show()
{
mStage.show();
mStage.toFront();
}
/**
* Updates this editor with the filter set. JavaFX thread only.
* @param filterSet to edit
*/ */
public void updateFilterSet(FilterSet<T> filterSet) public void updateFilterSet(FilterSet<T> filterSet)
{ {
CheckBoxTreeItem<Object> root = new CheckBoxTreeItem<>(filterSet); mEditorPanel.updateFilterSet(filterSet);
root.setExpanded(true);
addFilterSet(filterSet, root);
mTreeView.setRoot(root);
}
/**
* Tree view, for testing.
*/
TreeView<Object> getTreeView()
{
return mTreeView;
}
private void addFilterSet(FilterSet<?> filterSet, CheckBoxTreeItem<Object> parent)
{
for(IFilter<?> filter: filterSet.getFilters())
{
CheckBoxTreeItem<Object> item = new CheckBoxTreeItem<>(filter);
parent.getChildren().add(item);
if(filter instanceof FilterSet<?> childFilterSet)
{
addFilterSet(childFilterSet, item);
}
else if(filter instanceof Filter<?,?> childFilter)
{
addFilter(childFilter, item);
}
}
}
private void addFilter(Filter<?,?> filter, CheckBoxTreeItem<Object> parent)
{
List<FilterElement<?>> elements = new ArrayList<>(filter.getFilterElements());
elements.sort(Comparator.comparing(FilterElement::getName));
for(FilterElement<?> element: elements)
{
CheckBoxTreeItem<Object> item = new CheckBoxTreeItem<>(element);
parent.getChildren().add(item);
//Set the state after adding the item, so that the parent check boxes follow their elements
item.setSelected(element.isEnabled());
item.selectedProperty().addListener((observable, wasSelected, selected) -> {
element.setEnabled(selected);
//Update the enabled counts shown on the filters
mTreeView.refresh();
});
}
}
private static void setExpanded(TreeItem<Object> item, boolean expanded)
{
if(item != null)
{
item.setExpanded(expanded);
item.getChildren().forEach(child -> setExpanded(child, expanded));
}
}
/**
* Label for each tree item: a filter's name and enabled count, or a filter element's name.
*/
private static class LabelConverter extends StringConverter<TreeItem<Object>>
{
@Override
public String toString(TreeItem<Object> item)
{
Object value = item != null ? item.getValue() : null;
if(value instanceof IFilter<?> filter)
{
return filter.getName() + " (" + filter.getEnabledCount() + "/" + filter.getElementCount() + ")";
}
else if(value instanceof FilterElement<?> element)
{
return element.getName();
}
return value != null ? value.toString() : "";
}
@Override
public TreeItem<Object> fromString(String string)
{
return null;
}
} }
} }

View File

@@ -0,0 +1,444 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 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.filter;
import java.awt.Component;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.CellEditorListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreeSelectionModel;
/**
* Editor panel for managing the state of a filter set.
*
* @param <T> element type for the filter set.
*/
public class FilterEditorPanel<T> extends JPanel
{
private static final long serialVersionUID = 1L;
private JTree mTree;
private DefaultTreeModel mModel;
private FilterSet<T> mFilterSet;
/**
* Constructs an instance
* @param filterSet to manage
*/
public FilterEditorPanel(FilterSet<T> filterSet)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mFilterSet = filterSet;
init();
}
/**
* Initializes the panel and the tree model.
*/
private void init()
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode(mFilterSet);
mModel = new DefaultTreeModel(root);
addFilterSet(mFilterSet, root);
mTree = new JTree(mModel);
mTree.setShowsRootHandles(true);
mTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
mTree.setCellRenderer(new EditorTreeCellRenderer());
mTree.setCellEditor(new FilterTreeCellEditor());
mTree.setEditable(true);
add(mTree);
}
/**
* Updates the filter set for this editor panel
* @param filterSet to use
*/
public void updateFilterSet(FilterSet<T> filterSet)
{
remove(mTree);
mFilterSet = filterSet;
init();
revalidate();
}
/**
* Adds the filter set as a child tree node to the parent.
* @param filterSet to add to the tree
* @param parent node for the filter set child tree node.
*/
private void addFilterSet(FilterSet<T> filterSet, DefaultMutableTreeNode parent)
{
List<IFilter<T>> filters = filterSet.getFilters();
for(IFilter<T> filter : filters)
{
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(filter);
mModel.insertNodeInto(childNode, parent, parent.getChildCount());
if(filter instanceof FilterSet childFilterSet)
{
addFilterSet(childFilterSet, childNode);
}
else if(filter instanceof Filter childFilter)
{
addFilter(childFilter, childNode);
}
}
}
/**
* Adds the filter as a child tree node to the parent.
*
* @param filter to add
* @param parent tree node
*/
private void addFilter(Filter filter, DefaultMutableTreeNode parent)
{
List<FilterElement<?>> elements = filter.getFilterElements();
elements.sort(Comparator.comparing(FilterElement::getName));
for(FilterElement<?> element : elements)
{
DefaultMutableTreeNode child = new DefaultMutableTreeNode(element);
mModel.insertNodeInto(child, parent, parent.getChildCount());
}
}
/**
* Accesses the tree's root tree node.
* @return root node.
*/
private DefaultMutableTreeNode getRoot()
{
if(mTree.getModel().getRoot() instanceof DefaultMutableTreeNode root)
{
return root;
}
return null;
}
/**
* Recursively sets the enabled state on all filter node children below the specified parent node.
*
* @param model - model containing the tree nodes
* @param node - parent node
* @param enabled - true or false to enable or disable the filters
*/
private void setFilterEnabled(DefaultTreeModel model, DefaultMutableTreeNode node, boolean enabled)
{
Object obj = node.getUserObject();
if(obj instanceof FilterElement filterElement)
{
filterElement.setEnabled(enabled);
}
/* Recursively set the children of this node */
Enumeration<?> children = node.children();
while(children.hasMoreElements())
{
Object child = children.nextElement();
if(child instanceof DefaultMutableTreeNode childNode)
{
setFilterEnabled(model, childNode, enabled);
}
}
model.nodeChanged(node);
}
/**
* Recursively searches the tree to find the tree node containing the specified filter element.
*
* @param node to start search
* @param element to find
*/
private DefaultMutableTreeNode findFilterElementNode(DefaultMutableTreeNode node, FilterElement<?> element)
{
if(node != null)
{
if(node.getUserObject() instanceof FilterElement<?> selfFilterElement && selfFilterElement.equals(element))
{
return node;
}
for(int x = 0; x < node.getChildCount(); x++)
{
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
{
DefaultMutableTreeNode found = findFilterElementNode(child, element);
if(found != null)
{
return found;
}
}
}
}
return null;
}
/**
* Updates the display value for the specified node and all parents in the nodes parentage.
* @param node to update
*/
private void updateParentage(DefaultMutableTreeNode node)
{
mModel.nodeChanged(node);
TreeNode parent = node.getParent();
while(parent != null)
{
mModel.nodeChanged(parent);
parent = parent.getParent();
}
}
/**
* Recursively searches the tree to find the tree node containing the specified filter.
*
* @param node to start search
* @param filter to find
*/
private DefaultMutableTreeNode findFilterNode(DefaultMutableTreeNode node, IFilter<?> filter)
{
if(node != null)
{
if(node.getUserObject() instanceof IFilter<?> selfFilter && selfFilter.equals(filter))
{
return node;
}
for(int x = 0; x < node.getChildCount(); x++)
{
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
{
DefaultMutableTreeNode found = findFilterNode(child, filter);
if(found != null)
{
return found;
}
}
}
}
else
{
System.out.println("Can't evaluate - node is null");
}
return null;
}
/**
* Custom cell renderer
*/
public class EditorTreeCellRenderer extends DefaultTreeCellRenderer
{
private static final long serialVersionUID = 1L;
public Component getTreeCellRendererComponent(JTree tree, Object treeNode, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus)
{
if(treeNode instanceof DefaultMutableTreeNode)
{
Object userObject = ((DefaultMutableTreeNode) treeNode).getUserObject();
JCheckBox checkBox = null;
if(userObject instanceof IFilter filter)
{
checkBox = new FilterCheckBox(filter);
checkBox.setSelected(filter.isEnabled());
}
else if(userObject instanceof FilterElement element)
{
checkBox = new FilterElementCheckBox(element);
checkBox.setSelected(element.isEnabled());
}
if(checkBox != null)
{
if(selected)
{
checkBox.setForeground(getTextSelectionColor());
checkBox.setBackground(getBackgroundSelectionColor());
}
else
{
checkBox.setForeground(getTextNonSelectionColor());
checkBox.setBackground(getBackgroundNonSelectionColor());
}
return checkBox;
}
}
return super.getTreeCellRendererComponent(tree, treeNode, selected, expanded, leaf, row, hasFocus);
}
}
/**
* Check box used in filter tree nodes
*/
public class FilterCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private IFilter<?> mFilter;
/**
* Constructs an instance
*
* @param filter
*/
public FilterCheckBox(IFilter<?> filter)
{
mFilter = filter;
setSelected(mFilter.isEnabled());
addItemListener(e -> {
DefaultMutableTreeNode selfNode = findFilterNode(getRoot(), mFilter);
if(selfNode != null)
{
setFilterEnabled(mModel, selfNode, FilterCheckBox.this.isSelected());
updateLabel();
updateParentage(selfNode);
}
});
}
@Override
public void setSelected(boolean b)
{
super.setSelected(b);
updateLabel();
}
public void updateLabel()
{
setText(mFilter.getName() + " (" + mFilter.getEnabledCount() + "/" + mFilter.getElementCount() + ")");
}
}
/**
* Check box used in filter element tree nodes
*/
public class FilterElementCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private FilterElement<?> mFilter;
/**
* Constructs an instance
*
* @param filter element
*/
public FilterElementCheckBox(FilterElement<?> filter)
{
super(filter.getName());
mFilter = filter;
setSelected(mFilter.isEnabled());
addItemListener(arg0 -> {
mFilter.setEnabled(FilterElementCheckBox.this.isSelected());
DefaultMutableTreeNode self = findFilterElementNode(getRoot(), mFilter);
if(self != null)
{
updateParentage(self);
}
});
}
}
/**
* Editor for filter tree nodes
*/
public class FilterTreeCellEditor implements TreeCellEditor
{
@Override
public Component getTreeCellEditorComponent(JTree tree, Object node, boolean isSelected, boolean expanded, boolean leaf, int row)
{
if(node instanceof DefaultMutableTreeNode mutableTreeNode)
{
Object userObject = mutableTreeNode.getUserObject();
if(userObject instanceof IFilter filter)
{
return new FilterCheckBox(filter);
}
else if(userObject instanceof FilterElement filterElement)
{
return new FilterElementCheckBox(filterElement);
}
}
return new JLabel(node.toString());
}
@Override
public void addCellEditorListener(CellEditorListener l) {}
@Override
public void cancelCellEditing() {}
@Override
public Object getCellEditorValue()
{
return null;
}
@Override
public boolean isCellEditable(EventObject anEvent)
{
return true;
}
@Override
public void removeCellEditorListener(CellEditorListener l) {}
@Override
public boolean shouldSelectCell(EventObject anEvent)
{
return false;
}
@Override
public boolean stopCellEditing()
{
return false;
}
}
}

View File

@@ -1,231 +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.Image;
import java.awt.Taskbar;
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 JavaFX stages and the macOS Dock.
*
* Call installJavaFx() once the JavaFX toolkit is running, which also sets the macOS Dock icon. 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 sTaskbarInstalled;
private static boolean sJavaFxInstalled;
private ApplicationIcons()
{
}
/**
* Application icon in each available size, smallest first, as AWT images for the macOS Dock.
* @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 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. Windows and Linux take the icon from each window instead. Safe to call more than
* once. Does nothing in a headless environment.
*/
public static synchronized void installTaskbarIcon()
{
if(sTaskbarInstalled || java.awt.GraphicsEnvironment.isHeadless())
{
return;
}
sTaskbarInstalled = true;
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;
installTaskbarIcon();
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. Popups (menus, tooltips) are other Window types.
if(window instanceof Stage stage)
{
apply(stage);
//A JavaFX window (e.g. an error dialog) that shows before the main window would sit behind the splash.
Splash.close();
}
}
}

View File

@@ -1,131 +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.image.BufferedImage;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
/**
* Starts the JavaFX toolkit, runs work on the JavaFX application thread and converts images for ImageIO.
*/
public class FxToolkit
{
private static boolean sStarted;
private FxToolkit()
{
}
/**
* Starts the JavaFX toolkit if it isn't running. Safe to call more than once and from any thread except the
* JavaFX application thread before the toolkit starts.
*/
public static synchronized void ensureStarted()
{
if(sStarted)
{
return;
}
try
{
Platform.startup(() -> {});
}
catch(IllegalStateException alreadyStarted)
{
//The toolkit is already running
}
Platform.setImplicitExit(false);
ApplicationIcons.installJavaFx();
sStarted = true;
}
/**
* Indicates if the toolkit was started.
*/
public static synchronized boolean isStarted()
{
return sStarted;
}
/**
* Runs the callable on the JavaFX application thread and waits for the result.
* @throws Exception thrown by the callable
*/
public static <T> T callAndWait(Callable<T> callable) throws Exception
{
if(Platform.isFxApplicationThread())
{
return callable.call();
}
CompletableFuture<T> future = new CompletableFuture<>();
Platform.runLater(() -> {
try
{
future.complete(callable.call());
}
catch(Throwable t)
{
future.completeExceptionally(t);
}
});
try
{
return future.get();
}
catch(ExecutionException e)
{
if(e.getCause() instanceof Exception exception)
{
throw exception;
}
throw e;
}
}
/**
* Converts the JavaFX image to an AWT image for writing with ImageIO.
*/
public static BufferedImage toBufferedImage(Image image)
{
int width = (int)image.getWidth();
int height = (int)image.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
PixelReader reader = image.getPixelReader();
int[] row = new int[width];
for(int y = 0; y < height; y++)
{
reader.getPixels(0, y, width, 1, javafx.scene.image.PixelFormat.getIntArgbInstance(), row, 0, width);
bufferedImage.setRGB(0, y, width, 1, row, 0, width);
}
return bufferedImage;
}
}

View File

@@ -20,26 +20,36 @@
package io.github.dsheirer.gui; package io.github.dsheirer.gui;
import com.google.common.eventbus.Subscribe; import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.controller.channel.map.ChannelMap;
import io.github.dsheirer.controller.channel.map.ChannelRange;
import io.github.dsheirer.eventbus.MyEventBus; import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.icon.IconManager; import io.github.dsheirer.gui.icon.IconManager;
import io.github.dsheirer.gui.icon.ViewIconManagerRequest; import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
import io.github.dsheirer.gui.playlist.PlaylistEditor; import io.github.dsheirer.gui.playlist.PlaylistEditor;
import io.github.dsheirer.gui.playlist.PlaylistEditorRequest; import io.github.dsheirer.gui.playlist.PlaylistEditorRequest;
import io.github.dsheirer.database.DatabaseManager; import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.gui.playlist.channelMap.ChannelMapEditor; import io.github.dsheirer.gui.playlist.channelMap.ChannelMapEditor;
import io.github.dsheirer.gui.playlist.channelMap.ViewChannelMapEditorRequest; import io.github.dsheirer.gui.playlist.channelMap.ViewChannelMapEditorRequest;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.UserPreferencesEditor; import io.github.dsheirer.gui.preference.UserPreferencesEditor;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest; import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.gui.preference.calibration.CalibrationDialog; import io.github.dsheirer.gui.preference.calibration.CalibrationDialog;
import io.github.dsheirer.gui.theme.ThemeManager; import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.gui.viewer.MessageRecordingViewer; import io.github.dsheirer.gui.viewer.MessageRecordingViewer;
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest; import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.jmbe.JmbeEditor; import io.github.dsheirer.jmbe.JmbeEditor;
import io.github.dsheirer.jmbe.JmbeEditorRequest; import io.github.dsheirer.jmbe.JmbeEditorRequest;
import io.github.dsheirer.module.log.EventLogManager;
import io.github.dsheirer.monitor.ResourceMonitor;
import io.github.dsheirer.monitor.StatusBox;
import io.github.dsheirer.playlist.PlaylistManager; import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences; import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager; import io.github.dsheirer.source.tuner.manager.TunerManager;
import javafx.application.Application;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.stage.Stage; import javafx.stage.Stage;
import jiconfont.javafx.IconFontFX; import jiconfont.javafx.IconFontFX;
@@ -47,15 +57,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* Opens the application's tool windows (playlist editor, user preferences, icon manager, channel map editor, JMBE * Java FX window manager. Handles all secondary Java FX windows that are used within this primarily
* library editor and message recording viewer) when it receives their request events on the event bus. Each window * Swing application.
* is created once, then restored and brought to the front on later requests, and its size and location are kept
* across sessions.
*/ */
public class WindowManager public class JavaFxWindowManager extends Application
{ {
private final static Logger mLog = LoggerFactory.getLogger(WindowManager.class); private final static Logger mLog = LoggerFactory.getLogger(JavaFxWindowManager.class);
public static final String CHANNEL_MAP_EDITOR = "channelmap";
public static final String ICON_MANAGER = "iconmanager";
public static final String PLAYLIST_EDITOR = "playlist";
public static final String USER_PREFERENCES_EDITOR = "preferences";
public static final String STAGE_MONITOR_KEY_CALIBRATION_DIALOG = "calibration.dialog"; public static final String STAGE_MONITOR_KEY_CALIBRATION_DIALOG = "calibration.dialog";
public static final String STAGE_MONITOR_KEY_CHANNEL_MAP_EDITOR = "channel.map"; public static final String STAGE_MONITOR_KEY_CHANNEL_MAP_EDITOR = "channel.map";
public static final String STAGE_MONITOR_KEY_RECORDING_VIEWER = "recording.viewer"; public static final String STAGE_MONITOR_KEY_RECORDING_VIEWER = "recording.viewer";
@@ -64,6 +76,7 @@ public class WindowManager
public static final String STAGE_MONITOR_KEY_PLAYLIST_EDITOR = "playlist"; public static final String STAGE_MONITOR_KEY_PLAYLIST_EDITOR = "playlist";
public static final String STAGE_MONITOR_KEY_USER_PREFERENCES_EDITOR = "user.preferences"; public static final String STAGE_MONITOR_KEY_USER_PREFERENCES_EDITOR = "user.preferences";
private JFXPanel mJFXPanel;
private ChannelMapEditor mChannelMapEditor; private ChannelMapEditor mChannelMapEditor;
private IconManager mIconManager; private IconManager mIconManager;
private JmbeEditor mJmbeEditor; private JmbeEditor mJmbeEditor;
@@ -71,7 +84,6 @@ public class WindowManager
private PlaylistManager mPlaylistManager; private PlaylistManager mPlaylistManager;
private TunerManager mTunerManager; private TunerManager mTunerManager;
private UserPreferences mUserPreferences; private UserPreferences mUserPreferences;
private final DatabaseManager mDatabaseManager;
private UserPreferencesEditor mUserPreferencesEditor; private UserPreferencesEditor mUserPreferencesEditor;
private MessageRecordingViewer mMessageRecordingViewer; private MessageRecordingViewer mMessageRecordingViewer;
@@ -81,25 +93,57 @@ public class WindowManager
private Stage mPlaylistStage; private Stage mPlaylistStage;
private Stage mUserPreferencesStage; private Stage mUserPreferencesStage;
private Stage mRecordingViewerStage; private Stage mRecordingViewerStage;
private JFXPanel mStatusPanel;
/** /**
* Constructs an instance and registers it to receive window requests on the event bus. * Constructs an instance. Note: this constructor is used for Swing applications.
* @param userPreferences for the windows and their stored locations
* @param tunerManager for the playlist editor
* @param playlistManager for the playlist and channel map editors
* @param databaseManager for the call database preference editor
*/ */
public WindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager, public JavaFxWindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager)
DatabaseManager databaseManager)
{ {
mUserPreferences = userPreferences; mUserPreferences = userPreferences;
mDatabaseManager = databaseManager;
mTunerManager = tunerManager; mTunerManager = tunerManager;
mPlaylistManager = playlistManager; mPlaylistManager = playlistManager;
setup(); setup();
} }
/**
* Constructs an instance. Note: this constructor is used for standalone JavaFX application testing
*/
public JavaFxWindowManager()
{
mUserPreferences = new UserPreferences();
AliasModel aliasModel = new AliasModel();
EventLogManager eventLogManager = new EventLogManager(aliasModel, mUserPreferences);
mTunerManager = new TunerManager(mUserPreferences);
mTunerManager.start();
mPlaylistManager = new PlaylistManager(mUserPreferences, mTunerManager, aliasModel, eventLogManager, new IconModel());
mPlaylistManager.init();
setup();
}
/**
* Creates or accesses the JavaFX status panel, used by the main application GUI.
* @param resourceMonitor for statistics
* @return JFXPanel accessible on Swing thread that delegates JavaFX scene creation to the FX event thread.
*/
public JFXPanel getStatusPanel(ResourceMonitor resourceMonitor)
{
if(mStatusPanel == null)
{
mStatusPanel = new JFXPanel();
//JFXPanel has to be populated on the FX event thread
Platform.runLater(() -> {
Scene scene = new Scene(new StatusBox(resourceMonitor));
ThemeManager.getInstance().register(scene);
mStatusPanel.setScene(scene);
});
}
return mStatusPanel;
}
private void setup() private void setup()
{ {
//Register this class to receive events via each method annotated with @Subscribe //Register this class to receive events via each method annotated with @Subscribe
@@ -108,7 +152,7 @@ public class WindowManager
//Register JavaFX icon fonts //Register JavaFX icon fonts
IconFontFX.register(jiconfont.icons.font_awesome.FontAwesome.getIconFont()); IconFontFX.register(jiconfont.icons.font_awesome.FontAwesome.getIconFont());
startToolkit(); createJFXPanel();
} }
/** /**
@@ -116,7 +160,7 @@ public class WindowManager
*/ */
private void execute(Runnable runnable) private void execute(Runnable runnable)
{ {
startToolkit(); createJFXPanel();
if(Platform.isFxApplicationThread()) if(Platform.isFxApplicationThread())
{ {
@@ -129,11 +173,15 @@ public class WindowManager
} }
/** /**
* Starts the JavaFX toolkit if it is not running * Creates a JavaFX panel for Swing application compatibility
*/ */
private void startToolkit() private void createJFXPanel()
{ {
FxToolkit.ensureStarted(); if(mJFXPanel == null)
{
mJFXPanel = new JFXPanel();
Platform.setImplicitExit(false);
}
} }
/** /**
@@ -148,7 +196,7 @@ public class WindowManager
public CalibrationDialog getCalibrationDialog(UserPreferences userPreferences) public CalibrationDialog getCalibrationDialog(UserPreferences userPreferences)
{ {
startToolkit(); createJFXPanel();
return new CalibrationDialog(userPreferences); return new CalibrationDialog(userPreferences);
} }
@@ -159,7 +207,7 @@ public class WindowManager
{ {
if(mRecordingViewerStage == null) if(mRecordingViewerStage == null)
{ {
startToolkit(); createJFXPanel();
Scene scene = new Scene(getRecordingViewer(), 1100, 800); Scene scene = new Scene(getRecordingViewer(), 1100, 800);
ThemeManager.getInstance().register(scene); ThemeManager.getInstance().register(scene);
mRecordingViewerStage = new Stage(); mRecordingViewerStage = new Stage();
@@ -185,7 +233,7 @@ public class WindowManager
{ {
if(mIconManagerStage == null) if(mIconManagerStage == null)
{ {
startToolkit(); createJFXPanel();
Scene scene = new Scene(getIconManager(), 500, 500); Scene scene = new Scene(getIconManager(), 500, 500);
ThemeManager.getInstance().register(scene); ThemeManager.getInstance().register(scene);
mIconManagerStage = new Stage(); mIconManagerStage = new Stage();
@@ -234,7 +282,7 @@ public class WindowManager
{ {
if(mJmbeEditorStage == null) if(mJmbeEditorStage == null)
{ {
startToolkit(); createJFXPanel();
Scene scene = new Scene(getJmbeEditor(), 650, 650); Scene scene = new Scene(getJmbeEditor(), 650, 650);
ThemeManager.getInstance().register(scene); ThemeManager.getInstance().register(scene);
mJmbeEditorStage = new Stage(); mJmbeEditorStage = new Stage();
@@ -276,7 +324,7 @@ public class WindowManager
{ {
if(mPlaylistStage == null) if(mPlaylistStage == null)
{ {
startToolkit(); createJFXPanel();
Scene scene = new Scene(getPlaylistEditor(), 1000, 750); Scene scene = new Scene(getPlaylistEditor(), 1000, 750);
ThemeManager.getInstance().register(scene); ThemeManager.getInstance().register(scene);
mPlaylistStage = new Stage(); mPlaylistStage = new Stage();
@@ -314,7 +362,7 @@ public class WindowManager
{ {
if(mUserPreferencesEditor == null) if(mUserPreferencesEditor == null)
{ {
mUserPreferencesEditor = new UserPreferencesEditor(mUserPreferences, mDatabaseManager); mUserPreferencesEditor = new UserPreferencesEditor(mUserPreferences);
} }
return mUserPreferencesEditor; return mUserPreferencesEditor;
@@ -327,7 +375,7 @@ public class WindowManager
{ {
if(mUserPreferencesStage == null) if(mUserPreferencesStage == null)
{ {
startToolkit(); createJFXPanel();
Scene scene = new Scene(getUserPreferencesEditor(), 900, 500); Scene scene = new Scene(getUserPreferencesEditor(), 900, 500);
ThemeManager.getInstance().register(scene); ThemeManager.getInstance().register(scene);
mUserPreferencesStage = new Stage(); mUserPreferencesStage = new Stage();
@@ -371,7 +419,7 @@ public class WindowManager
{ {
if(mChannelMapStage == null) if(mChannelMapStage == null)
{ {
startToolkit(); createJFXPanel();
Scene scene = new Scene(getChannelMapEditor(), 500, 500); Scene scene = new Scene(getChannelMapEditor(), 500, 500);
ThemeManager.getInstance().register(scene); ThemeManager.getInstance().register(scene);
mChannelMapStage = new Stage(); mChannelMapStage = new Stage();
@@ -421,4 +469,75 @@ public class WindowManager
stage.requestFocus(); stage.requestFocus();
stage.toFront(); stage.toFront();
} }
@Override
public void start(Stage primaryStage) throws Exception
{
mLog.debug("Starting ...");
Parameters parameters = getParameters();
mLog.debug("Parameters: " + (parameters != null));
boolean valid = false;
if(parameters != null && parameters.getRaw().size() == 1)
{
String window = parameters.getRaw().get(0);
if(window != null)
{
switch(window)
{
case CHANNEL_MAP_EDITOR:
//Generate some test data for the editor
ChannelMap channelMap1 = new ChannelMap("Test Map 1");
channelMap1.addRange(new ChannelRange(1,199,150000000, 12500));
channelMap1.addRange(new ChannelRange(200,299,160000000, 25000));
channelMap1.addRange(new ChannelRange(300,399,170000000, 12500));
channelMap1.addRange(new ChannelRange(400,499,180000000, 25000));
mPlaylistManager.getChannelMapModel().addChannelMap(channelMap1);
ChannelMap channelMap2 = new ChannelMap("Test Map 2");
channelMap2.addRange(new ChannelRange(1,199,450000000, 12500));
channelMap2.addRange(new ChannelRange(200,299,460000000, 25000));
channelMap2.addRange(new ChannelRange(300,399,470000000, 12500));
channelMap2.addRange(new ChannelRange(400,499,480000000, 25000));
mPlaylistManager.getChannelMapModel().addChannelMap(channelMap2);
valid = true;
process(new ViewChannelMapEditorRequest());
break;
case ICON_MANAGER:
valid = true;
process(new ViewIconManagerRequest());
break;
case PLAYLIST_EDITOR:
valid = true;
process(new ViewPlaylistRequest());
break;
case USER_PREFERENCES_EDITOR:
valid = true;
process(new ViewUserPreferenceEditorRequest(PreferenceEditorType.DEFAULT));
break;
default:
break;
}
}
}
if(!valid)
{
StringBuilder sb = new StringBuilder();
sb.append("An argument is required to launch JavaFX windows from this window manager. " +
"Valid options are:\n\tchannelmap\tChannel Map Editor\n\ticonmanager\tIcon Manager\n\tplaylist\tPlaylist Editor\n" +
"\tpreferences\tUser Preferences Editor\n");
sb.append("Supplied Argument(s): ").append(parameters.getRaw());
mLog.error(sb.toString());
}
}
public static void main(String[] args)
{
mLog.info("Application Start - Parameters: " + args);
launch(args);
}
} }

View File

@@ -1,766 +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 io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.call.CallManager;
import io.github.dsheirer.database.DatabaseManager;
import io.github.dsheirer.gui.calls.CallsView;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.audio.AudioView;
import io.github.dsheirer.gui.broadcast.BroadcastStatusView;
import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
import io.github.dsheirer.gui.map.MapView;
import io.github.dsheirer.gui.nowplaying.NowPlayingView;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.gui.spectrum.MainSpectralDisplay;
import io.github.dsheirer.gui.spectrum.TunerSpectralDisplay;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.monitor.DiagnosticMonitor;
import io.github.dsheirer.monitor.ResourceMonitor;
import io.github.dsheirer.monitor.StatusBox;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.util.ThreadPool;
import io.github.dsheirer.util.TimeStamp;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconFontFX;
import jiconfont.javafx.IconNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main application window: menu bar, audio playback display, the spectrum and waterfall, the Now Playing, Map and
* Tuners tabs, the optional streaming status and the optional resource status bar.
*
* The spectrum and waterfall can be hidden from the View menu, the hide button in the display settings panel or a
* keyboard shortcut. A hidden spectrum is disposed so that it uses no processing or memory.
*/
public class MainWindow
{
private static final Logger mLog = LoggerFactory.getLogger(MainWindow.class);
public static final String STAGE_MONITOR_KEY = "main.window";
private static final String PREFERENCE_BROADCAST_STATUS_VISIBLE = "sdrtrunk.broadcast.status.visible";
private static final String PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE = "sdrtrunk.now.playing.details.visible";
private static final String PREFERENCE_RESOURCE_STATUS_VISIBLE = "sdrtrunk.resource.status.visible";
private static final String PREFERENCE_SPECTRAL_DISPLAY_VISIBLE = "sdrtrunk.spectral.display.visible";
private static final String PREFERENCE_SPECTRAL_DIVIDER = "sdrtrunk.main.window.spectral.fraction";
private static final String PREFERENCE_BROADCAST_DIVIDER = "sdrtrunk.main.window.streaming.fraction";
private static final double DEFAULT_SPECTRAL_DIVIDER = 0.38;
private static final double DEFAULT_BROADCAST_FRACTION = 0.18;
static final KeyCombination SPECTRAL_TOGGLE_SHORTCUT = new KeyCodeCombination(KeyCode.S,
KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN);
private final Preferences mPreferences = Preferences.userNodeForPackage(SDRTrunk.class);
private final UserPreferences mUserPreferences;
private final PlaylistManager mPlaylistManager;
private final TunerManager mTunerManager;
private final DiagnosticMonitor mDiagnosticMonitor;
private final ResourceMonitor mResourceMonitor;
private final Runnable mExitHandler;
private final String mTitle;
private final Stage mStage;
private final BorderPane mRoot = new BorderPane();
private final SplitPane mSplitPane = new SplitPane();
private final VBox mCenter = new VBox();
private final AudioView mAudioView;
private final MainSpectralDisplay mSpectralDisplay;
private final HBox mSpectralHiddenBar;
private final NowPlayingView mNowPlayingView;
private final CallsView mCallsView;
private final TabPane mTabPane = new TabPane();
private BroadcastStatusView mBroadcastStatusView;
private StatusBox mStatusBox;
private final CheckMenuItem mSpectralMenuItem = new CheckMenuItem("Show Spectrum & Waterfall");
private final CheckMenuItem mBroadcastMenuItem = new CheckMenuItem("Show Streaming Status");
private final CheckMenuItem mResourceMenuItem = new CheckMenuItem("Show Resource Status");
private final CheckMenuItem mNowPlayingDetailsMenuItem = new CheckMenuItem("Show Now Playing Channel Details");
private double mSpectralDivider;
private double mBroadcastFraction;
private boolean mUpdatingDividers;
static
{
IconFontFX.register(FontAwesome.getIconFont());
}
/**
* Constructs the main window. JavaFX thread only.
* @param userPreferences for the views
* @param playlistManager for the channels, aliases and streams
* @param tunerManager for the tuners
* @param audioPlaybackManager for the audio display
* @param aliasModel for alias lookup
* @param iconModel for alias icons
* @param mapService for the map
* @param resourceMonitor for the status bar
* @param diagnosticMonitor for the reports
* @param databaseManager for the Calls tab
* @param callManager for live call updates in the Calls tab
* @param exitHandler that shuts down the application, invoked on a background thread
*/
public MainWindow(UserPreferences userPreferences, PlaylistManager playlistManager, TunerManager tunerManager,
AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel, IconModel iconModel,
MapService mapService, ResourceMonitor resourceMonitor, DiagnosticMonitor diagnosticMonitor,
DatabaseManager databaseManager, CallManager callManager,
Runnable exitHandler)
{
mUserPreferences = userPreferences;
mPlaylistManager = playlistManager;
mTunerManager = tunerManager;
mResourceMonitor = resourceMonitor;
mDiagnosticMonitor = diagnosticMonitor;
mExitHandler = exitHandler;
mTitle = SystemProperties.getInstance().getApplicationName();
mSpectralDivider = clamp(mPreferences.getDouble(PREFERENCE_SPECTRAL_DIVIDER, DEFAULT_SPECTRAL_DIVIDER));
mBroadcastFraction = clamp(mPreferences.getDouble(PREFERENCE_BROADCAST_DIVIDER, DEFAULT_BROADCAST_FRACTION));
mAudioView = new AudioView(audioPlaybackManager, aliasModel, iconModel, userPreferences);
boolean spectralVisible = mPreferences.getBoolean(PREFERENCE_SPECTRAL_DISPLAY_VISIBLE, true);
mSpectralDisplay = new MainSpectralDisplay(playlistManager, tunerManager.getDiscoveredTunerModel(),
spectralVisible);
mSpectralDisplay.setHideRequestHandler(() -> setSpectralDisplayVisible(false));
mSpectralHiddenBar = createSpectralHiddenBar();
boolean detailsVisible = mPreferences.getBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, true);
mNowPlayingView = new NowPlayingView(playlistManager, iconModel, userPreferences, detailsVisible);
mCallsView = new CallsView(databaseManager, callManager, audioPlaybackManager, aliasModel);
createTabs(mapService, iconModel);
URL stylesheet = MainWindow.class.getResource("/main_window.css");
if(stylesheet != null)
{
mRoot.getStylesheets().add(stylesheet.toExternalForm());
}
mRoot.getStyleClass().add("main-window");
mSplitPane.setOrientation(javafx.geometry.Orientation.VERTICAL);
mSplitPane.getStyleClass().add("main-split-pane");
//The split pane moves its dividers while it lays out, so only store the positions after the user drags one
mSplitPane.addEventFilter(javafx.scene.input.MouseEvent.MOUSE_RELEASED, event -> storeDividers());
mSpectralDisplay.setMinHeight(80);
mTabPane.setMinHeight(150);
VBox.setVgrow(mSplitPane, Priority.ALWAYS);
mCenter.getChildren().addAll(mSpectralHiddenBar, mSplitPane);
mRoot.setTop(new VBox(createMenuBar(), mAudioView));
mRoot.setCenter(mCenter);
mSpectralMenuItem.setSelected(spectralVisible);
mNowPlayingDetailsMenuItem.setSelected(detailsVisible);
mBroadcastMenuItem.setSelected(mPreferences.getBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, false));
mResourceMenuItem.setSelected(mPreferences.getBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, true));
updateSplitPaneItems();
updateStatusBar();
mStage = new Stage();
mStage.setTitle(mTitle);
ApplicationIcons.apply(mStage);
Scene scene = new Scene(mRoot, 1280, 800);
ThemeManager.getInstance().register(scene);
scene.getAccelerators().put(SPECTRAL_TOGGLE_SHORTCUT,
() -> setSpectralDisplayVisible(!mSpectralDisplay.displayVisibleProperty().get()));
mStage.setScene(scene);
mStage.setMinWidth(640);
mStage.setMinHeight(480);
mStage.setOnCloseRequest(event -> {
event.consume();
exit();
});
migrateSwingWindowLocation();
mUserPreferences.getJavaFxPreferences().monitor(mStage, STAGE_MONITOR_KEY);
}
/**
* Main window stage.
*/
public Stage getStage()
{
return mStage;
}
/**
* Spectrum and waterfall display.
*/
public MainSpectralDisplay getSpectralDisplay()
{
return mSpectralDisplay;
}
/**
* Shows the window. JavaFX thread only.
*/
public void show()
{
mStage.show();
//The split pane only applies divider positions once it has a size
Platform.runLater(this::applyDividers);
}
/**
* Shows the stage's title with the tuner name, or the application name when the tuner is null. Any thread.
*/
public void updateTitle(String tunerName)
{
String title = tunerName != null ? mTitle + " - " + tunerName : mTitle;
Platform.runLater(() -> mStage.setTitle(title));
}
/**
* Handles tuner events for the main spectral display. Any thread.
*/
public void receive(TunerEvent event)
{
switch(event.getEvent())
{
case REQUEST_MAIN_SPECTRAL_DISPLAY:
//The user asked to see a tuner, so show the display if it's hidden
Platform.runLater(() -> setSpectralDisplayVisible(true));
updateTitle(event.getTuner().getPreferredName());
break;
case REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY:
updateTitle(null);
break;
case NOTIFICATION_SHUTTING_DOWN:
Tuner currentTuner = mSpectralDisplay.getTuner();
if(currentTuner == null || (event.hasTuner() && event.getTuner().equals(currentTuner)))
{
updateTitle(null);
}
break;
default:
break;
}
}
/**
* Saves the divider positions and stops the views. Called during application shutdown.
*/
public void dispose()
{
mAudioView.dispose();
mCallsView.dispose();
if(mBroadcastStatusView != null)
{
mBroadcastStatusView.dispose();
}
mSpectralDisplay.dispose();
}
/**
* Shows or hides the spectrum and waterfall. A hidden display is disposed. JavaFX thread only.
*/
public void setSpectralDisplayVisible(boolean visible)
{
mSpectralMenuItem.setSelected(visible);
if(visible != mSpectralDisplay.displayVisibleProperty().get())
{
mPreferences.putBoolean(PREFERENCE_SPECTRAL_DISPLAY_VISIBLE, visible);
mSpectralDisplay.setDisplayVisible(visible);
updateSplitPaneItems();
applyDividers();
}
}
private HBox createSpectralHiddenBar()
{
IconNode icon = new IconNode(FontAwesome.EYE_SLASH);
icon.setIconSize(13);
icon.getStyleClass().add("main-hidden-bar-icon");
Label label = new Label("Spectrum and waterfall are hidden and turned off, so they use no processing or memory.");
label.getStyleClass().add("main-hidden-bar-label");
label.setMinWidth(0);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
IconNode showIcon = new IconNode(FontAwesome.EYE);
showIcon.setIconSize(12);
Button show = new Button("Show Spectrum & Waterfall", showIcon);
showIcon.fillProperty().bind(show.textFillProperty());
show.setOnAction(event -> setSpectralDisplayVisible(true));
HBox bar = new HBox(8, icon, label, spacer, show);
bar.getStyleClass().add("main-hidden-bar");
bar.setAlignment(Pos.CENTER_LEFT);
return bar;
}
private void createTabs(MapService mapService, IconModel iconModel)
{
MapView mapView = new MapView(mapService, iconModel, mUserPreferences,
mPlaylistManager.getRadioReference() != null ?
mPlaylistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(mPlaylistManager), true);
Tab nowPlaying = new Tab("Now Playing", mNowPlayingView);
Tab calls = new Tab("Calls", mCallsView);
Tab map = new Tab("Map", mapView);
Tab tuners = new Tab("Tuners", new io.github.dsheirer.source.tuner.ui.TunerView(mTunerManager,
mUserPreferences));
//The playlist editor tab opens the playlist editor window and stays on the current tab
IconNode playIcon = new IconNode(FontAwesome.PLAY_CIRCLE_O);
playIcon.setIconSize(15);
playIcon.getStyleClass().add("main-playlist-tab-icon");
Tab playlist = new Tab("Playlist Editor");
playlist.setGraphic(playIcon);
playlist.setContent(new Region());
mTabPane.getTabs().addAll(nowPlaying, calls, map, tuners, playlist);
mTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
mTabPane.getStyleClass().add("main-tab-pane");
mTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
if(newTab == playlist)
{
MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest());
Platform.runLater(() -> mTabPane.getSelectionModel().select(oldTab != null ? oldTab : nowPlaying));
}
});
}
/**
* Updates the split pane to hold the visible panes: spectrum (optional), tabs and streaming status (optional).
*/
private void updateSplitPaneItems()
{
mUpdatingDividers = true;
List<Node> items = new ArrayList<>();
boolean spectralVisible = mSpectralDisplay.displayVisibleProperty().get();
if(spectralVisible)
{
items.add(mSpectralDisplay);
}
items.add(mTabPane);
if(mBroadcastMenuItem.isSelected())
{
if(mBroadcastStatusView == null)
{
mBroadcastStatusView = new BroadcastStatusView(mPlaylistManager.getBroadcastModel(),
mUserPreferences.getSwingPreference());
mBroadcastStatusView.setMinHeight(70);
}
items.add(mBroadcastStatusView);
}
mSplitPane.getItems().setAll(items);
SplitPane.setResizableWithParent(mTabPane, true);
if(mBroadcastStatusView != null)
{
SplitPane.setResizableWithParent(mBroadcastStatusView, false);
}
mSpectralHiddenBar.setVisible(!spectralVisible);
mSpectralHiddenBar.setManaged(!spectralVisible);
mUpdatingDividers = false;
}
/**
* Applies the stored divider positions to the split pane.
*/
private void applyDividers()
{
mUpdatingDividers = true;
List<SplitPane.Divider> dividers = mSplitPane.getDividers();
int index = 0;
if(mSpectralDisplay.displayVisibleProperty().get() && index < dividers.size())
{
dividers.get(index++).setPosition(mSpectralDivider);
}
if(mBroadcastMenuItem.isSelected() && index < dividers.size())
{
dividers.get(index).setPosition(1.0 - mBroadcastFraction);
}
mUpdatingDividers = false;
}
/**
* Stores the divider positions after the user moves a divider.
*/
private void storeDividers()
{
if(mUpdatingDividers || !mStage.isShowing() || mSplitPane.getDividers().isEmpty())
{
return;
}
List<SplitPane.Divider> dividers = mSplitPane.getDividers();
int index = 0;
if(mSpectralDisplay.displayVisibleProperty().get() && index < dividers.size())
{
mSpectralDivider = clamp(dividers.get(index++).getPosition());
mPreferences.putDouble(PREFERENCE_SPECTRAL_DIVIDER, mSpectralDivider);
}
if(mBroadcastMenuItem.isSelected() && index < dividers.size())
{
mBroadcastFraction = clamp(1.0 - dividers.get(index).getPosition());
mPreferences.putDouble(PREFERENCE_BROADCAST_DIVIDER, mBroadcastFraction);
}
}
private static double clamp(double value)
{
return Double.isNaN(value) ? 0.3 : Math.max(0.05, Math.min(0.6, value));
}
private void updateStatusBar()
{
if(mResourceMenuItem.isSelected())
{
if(mStatusBox == null)
{
mStatusBox = new StatusBox(mResourceMonitor);
}
mRoot.setBottom(mStatusBox);
}
else
{
mRoot.setBottom(null);
}
}
private MenuBar createMenuBar()
{
//File
MenuItem processingReport = new MenuItem("Processing Diagnostic Report");
processingReport.setOnAction(event -> createReport("Processing Status Report",
() -> mDiagnosticMonitor.generateProcessingDiagnosticReport("User initiated diagnostic report")));
MenuItem threadDumpReport = new MenuItem("Thread Dump Report");
threadDumpReport.setOnAction(event -> createReport("Thread Dump Report",
mDiagnosticMonitor::generateThreadDumpReport));
Menu reports = new Menu("Reports", null, processingReport, threadDumpReport);
MenuItem screenCapture = new MenuItem("Screen Capture", icon(FontAwesome.CAMERA));
screenCapture.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN));
screenCapture.setOnAction(event -> captureScreen());
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(event -> exit());
Menu file = new Menu("File", null, reports, screenCapture, new SeparatorMenuItem(), exit);
//View
MenuItem playlistEditor = new MenuItem("Playlist Editor", icon(FontAwesome.PLAY_CIRCLE_O));
playlistEditor.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest()));
MenuItem logs = folderItem("Application Log Files",
() -> mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog());
MenuItem recordings = folderItem("Audio Recordings",
() -> mUserPreferences.getDirectoryPreference().getDirectoryRecording());
MenuItem eventLogs = folderItem("Channel Event Log Files",
() -> mUserPreferences.getDirectoryPreference().getDirectoryEventLog());
MenuItem screenCaptures = folderItem("Screen Captures",
() -> mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture());
MenuItem iconManager = new MenuItem("Icon Manager", icon(FontAwesome.PICTURE_O));
iconManager.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewIconManagerRequest()));
MenuItem recordingViewer = new MenuItem("Message Recording Viewer (.bits)", icon(FontAwesome.BRAILLE));
recordingViewer.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewRecordingViewerRequest()));
MenuItem preferences = new MenuItem("User Preferences", icon(FontAwesome.COG));
preferences.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest()));
Menu tuners = new Menu("Tuners");
tuners.getItems().add(new MenuItem("(none)"));
tuners.setOnShowing(event -> updateTunersMenu(tuners));
mSpectralMenuItem.setAccelerator(SPECTRAL_TOGGLE_SHORTCUT);
mSpectralMenuItem.setOnAction(event -> setSpectralDisplayVisible(mSpectralMenuItem.isSelected()));
mNowPlayingDetailsMenuItem.setOnAction(event -> {
mNowPlayingView.setDetailTabsVisible(mNowPlayingDetailsMenuItem.isSelected());
mPreferences.putBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, mNowPlayingDetailsMenuItem.isSelected());
});
mBroadcastMenuItem.setOnAction(event -> {
mPreferences.putBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, mBroadcastMenuItem.isSelected());
updateSplitPaneItems();
applyDividers();
});
mResourceMenuItem.setOnAction(event -> {
mPreferences.putBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, mResourceMenuItem.isSelected());
updateStatusBar();
});
Menu view = new Menu("View", null, playlistEditor, new SeparatorMenuItem(), logs, recordings, eventLogs,
iconManager, recordingViewer, screenCaptures, preferences, new SeparatorMenuItem(), tuners,
new SeparatorMenuItem(), mSpectralMenuItem, mNowPlayingDetailsMenuItem, mBroadcastMenuItem,
mResourceMenuItem);
MenuBar menuBar = new MenuBar(file, view);
menuBar.setUseSystemMenuBar(true);
return menuBar;
}
/**
* Lists the available tuners, each of which shows the tuner in the main spectral display.
*/
private void updateTunersMenu(Menu menu)
{
menu.getItems().clear();
for(DiscoveredTuner discoveredTuner: mTunerManager.getAvailableTuners())
{
Tuner tuner = discoveredTuner.getTuner();
if(tuner != null)
{
MenuItem item = new MenuItem("Show: " + tuner.getPreferredName());
item.setOnAction(event -> ThreadPool.CACHED.submit(() -> {
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true);
mTunerManager.getDiscoveredTunerModel().broadcast(new TunerEvent(tuner,
TunerEvent.Event.REQUEST_MAIN_SPECTRAL_DISPLAY));
}));
menu.getItems().add(item);
}
}
if(menu.getItems().isEmpty())
{
MenuItem none = new MenuItem("No tuners available");
none.setDisable(true);
menu.getItems().add(none);
}
}
private static IconNode icon(FontAwesome code)
{
IconNode icon = new IconNode(code);
icon.setIconSize(12);
icon.getStyleClass().add("main-menu-icon");
return icon;
}
/**
* Supplies a path that can throw an IO exception.
*/
private interface PathSupplier
{
Path get() throws IOException;
}
private MenuItem folderItem(String title, PathSupplier folder)
{
MenuItem item = new MenuItem(title, icon(FontAwesome.FOLDER_OPEN_O));
item.setOnAction(event -> ThreadPool.CACHED.submit(() -> {
File directory = null;
try
{
directory = folder.get().toFile();
Desktop.getDesktop().open(directory);
}
catch(Exception e)
{
mLog.error("Couldn't open file explorer", e);
String location = directory != null ? directory.toString() : "unknown";
Platform.runLater(() -> showAlert(Alert.AlertType.ERROR, "Can't launch file explorer",
"Can't launch the file explorer. The files are located at:\n\n" + location));
}
}));
return item;
}
private void createReport(String title, PathSupplier report)
{
ThreadPool.CACHED.submit(() -> {
try
{
Path path = report.get();
Platform.runLater(() -> showAlert(Alert.AlertType.INFORMATION, title + " Created",
"Report created:\n\n" + path));
}
catch(IOException ioe)
{
mLog.error("Error creating " + title, ioe);
Platform.runLater(() -> showAlert(Alert.AlertType.ERROR, title + " Failed",
"Unable to create the report file. Please see the application log for details."));
}
});
}
/**
* Shows a message dialog owned by the main window. JavaFX thread only.
*/
public void showAlert(Alert.AlertType type, String title, String message)
{
Alert alert = new Alert(type, message);
alert.setTitle(title);
alert.setHeaderText(null);
alert.initOwner(mStage);
alert.show();
}
/**
* Warns that the library folder holds more than one version of some libraries. JavaFX thread only.
* @param details listing the duplicate libraries
* @param folder holding the libraries
*/
public void showDuplicateLibraries(String details, String folder)
{
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Duplicate Library Versions");
alert.setHeaderText("The sdrtrunk library folder has more than one version of some libraries");
alert.setContentText("This happens when a new version of sdrtrunk is unzipped over an older one. sdrtrunk " +
"can load the older library code, which can cause crashes or errors that the newer version fixed.\n\n" +
"Close sdrtrunk, delete the sdrtrunk folder that contains this library folder and unzip the release " +
"into a new, empty folder:\n\n" + folder + "\n\nYour playlist and settings are stored in your user " +
"folder and won't be affected.");
TextArea libraries = new TextArea(details);
libraries.setEditable(false);
libraries.setPrefRowCount(8);
alert.getDialogPane().setExpandableContent(libraries);
alert.getDialogPane().setExpanded(true);
alert.initOwner(mStage);
alert.show();
}
/**
* Saves an image of the main window to the screen captures folder.
*/
private void captureScreen()
{
WritableImage image = mStage.getScene().snapshot(null);
String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png";
ThreadPool.CACHED.submit(() -> {
Path file = null;
try
{
file = mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture().resolve(filename);
ImageIO.write(FxToolkit.toBufferedImage(image), "png", file.toFile());
}
catch(Exception e)
{
mLog.error("Couldn't write screen capture to file [" + file + "]", e);
}
});
}
/**
* Hides the window and shuts down the application on a background thread, since stopping the tuners can block.
*/
private void exit()
{
mStage.hide();
Thread thread = new Thread(() -> {
try
{
mExitHandler.run();
}
catch(Throwable t)
{
mLog.error("Error during shutdown", t);
}
System.exit(0);
}, "sdrtrunk shutdown");
thread.start();
}
/**
* Moves the main window size and location from the Swing window preferences to the JavaFX stage preferences,
* once, so that users keep their window placement.
*/
private void migrateSwingWindowLocation()
{
if(mUserPreferences.getJavaFxPreferences().hasStoredLocation(STAGE_MONITOR_KEY))
{
return;
}
String swingKey = "sdrtrunk.main.window.frame";
java.awt.Point location = mUserPreferences.getSwingPreference().getLocation(swingKey);
java.awt.Dimension size = mUserPreferences.getSwingPreference().getDimension(swingKey);
if(location != null && size != null)
{
mUserPreferences.getJavaFxPreferences().storeLocation(STAGE_MONITOR_KEY, location.x, location.y,
size.width, size.height, mUserPreferences.getSwingPreference().getMaximized(swingKey, false));
}
else
{
mStage.centerOnScreen();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -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.
}
}
}

View File

@@ -1,698 +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.audio;
import com.google.common.base.Joiner;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.audio.playback.AudioChannel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.audio.playback.ReplaySource;
import io.github.dsheirer.audio.playback.TalkgroupHold;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.sample.Listener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconNode;
/**
* Display for one audio playback channel (mono, or the left/right channel of a stereo output). Shows the call that
* is playing: the TO alias or identifier as the headline with the alias icon and color, the FROM radio, the system,
* site and channel, the elapsed call time and an audio level meter, plus a per-channel mute. When the call ends,
* the last call stays on the display, dimmed, until the next call starts.
*/
public class AudioChannelView extends HBox
{
private static final String NO_CALL = "No audio";
private static final Color DEFAULT_ACCENT = Color.web("#3ddc84");
private static final Color DISPLAY_BACKGROUND = Color.web("#161b22");
private final AudioChannel mAudioChannel;
private final AliasModel mAliasModel;
private final IconModel mIconModel;
private final TalkgroupFormatPreference mTalkgroupFormatPreference;
private final Runnable mMuteChangeListener;
private final Listener<AudioEvent> mAudioEventListener = this::receive;
private final Listener<IdentifierCollection> mMetadataListener = this::receive;
private final Region mAccentStrip = new Region();
private final StackPane mIconPane = new StackPane();
private final ImageView mAliasImage = new ImageView();
private final IconNode mPlaceholderIcon = new IconNode(FontAwesome.HEADPHONES);
private final Label mChannelTag = new Label();
private final Label mStatusLabel = new Label();
private final Label mElapsedLabel = new Label();
private final ToggleButton mMuteButton = new ToggleButton();
private final ToggleButton mHoldButton = new ToggleButton();
private final Label mHoldLabel = new Label();
private final AudioPlaybackManager mAudioPlaybackManager;
private final int mChannelIndex;
private final IconNode mMuteIcon = new IconNode(FontAwesome.VOLUME_UP);
private final Label mToLabel = new Label(NO_CALL);
private final Label mToDetailLabel = new Label();
private final Label mFromLabel = new Label();
private final Label mContextLabel = new Label();
private final HBox mFromBox;
private final LevelMeter mLevelMeter;
private IdentifierCollection mIdentifierCollection;
private Identifier mCallToIdentifier;
private boolean mActive;
private boolean mHasPlayed;
private long mCallStartNanos;
private long mCallEndNanos;
/**
* Constructs an instance
* @param audioChannel to display
* @param aliasModel for alias lookup
* @param iconModel for alias icons
* @param talkgroupFormatPreference for identifier formatting
* @param updatesPerSecond rate that {@link #tick()} is invoked
* @param muteChangeListener notified on the FX thread when this channel's mute state changes
* @param audioPlaybackManager for setting the hold talkgroup, or null to hide the hold button
* @param channelIndex of this channel in the audio output
*/
public AudioChannelView(AudioChannel audioChannel, AliasModel aliasModel, IconModel iconModel,
TalkgroupFormatPreference talkgroupFormatPreference, double updatesPerSecond,
Runnable muteChangeListener, AudioPlaybackManager audioPlaybackManager, int channelIndex)
{
mAudioChannel = audioChannel;
mAudioPlaybackManager = audioPlaybackManager;
mChannelIndex = channelIndex;
mAliasModel = aliasModel;
mIconModel = iconModel;
mTalkgroupFormatPreference = talkgroupFormatPreference;
mMuteChangeListener = muteChangeListener;
mLevelMeter = new LevelMeter(updatesPerSecond);
getStyleClass().add("audio-channel");
setFillHeight(true);
setMinWidth(0);
setPrefWidth(420);
setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(this, Priority.ALWAYS);
mAccentStrip.getStyleClass().add("audio-accent");
mAccentStrip.setMinWidth(5);
mAccentStrip.setPrefWidth(5);
mAccentStrip.setMaxHeight(Double.MAX_VALUE);
mAliasImage.setPreserveRatio(true);
mAliasImage.setFitHeight(36);
mAliasImage.setFitWidth(36);
mAliasImage.setSmooth(true);
mPlaceholderIcon.setIconSize(26);
mPlaceholderIcon.getStyleClass().add("audio-placeholder-icon");
mIconPane.getStyleClass().add("audio-icon-pane");
mIconPane.setMinSize(52, 52);
mIconPane.setPrefSize(52, 52);
mIconPane.setMaxSize(52, 52);
mIconPane.getChildren().addAll(mPlaceholderIcon, mAliasImage);
VBox iconColumn = new VBox(mIconPane);
iconColumn.setAlignment(Pos.CENTER);
mChannelTag.setText(audioChannel.getChannelName());
mChannelTag.getStyleClass().add("audio-channel-tag");
mChannelTag.getStyleClass().add("RIGHT".equals(audioChannel.getChannelName()) ? "audio-channel-tag-right" :
"audio-channel-tag-left");
mStatusLabel.getStyleClass().add("audio-status");
mElapsedLabel.getStyleClass().add("audio-elapsed");
mMuteIcon.setIconSize(15);
mMuteIcon.getStyleClass().add("audio-button-icon");
mMuteButton.setGraphic(mMuteIcon);
mMuteButton.getStyleClass().add("audio-icon-button");
mMuteButton.setFocusTraversable(true);
mMuteButton.setOnAction(event -> {
mAudioChannel.setMuted(mMuteButton.isSelected());
updateMuted();
});
IconNode holdIcon = new IconNode(FontAwesome.THUMB_TACK);
holdIcon.setIconSize(15);
holdIcon.getStyleClass().add("audio-button-icon");
mHoldButton.setGraphic(holdIcon);
mHoldButton.getStyleClass().addAll("audio-icon-button", "audio-hold-button");
mHoldButton.setFocusTraversable(true);
mHoldButton.setOnAction(event -> toggleHold());
mHoldButton.setVisible(audioPlaybackManager != null);
mHoldButton.setManaged(audioPlaybackManager != null);
mHoldLabel.getStyleClass().add("audio-hold-label");
mHoldLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
mHoldLabel.setMinWidth(0);
mHoldLabel.setVisible(false);
mHoldLabel.setManaged(false);
Region headerSpacer = new Region();
HBox.setHgrow(headerSpacer, Priority.ALWAYS);
HBox header = new HBox(8, mChannelTag, mStatusLabel, mHoldLabel, headerSpacer, mElapsedLabel, mHoldButton,
mMuteButton);
header.setAlignment(Pos.CENTER_LEFT);
mToLabel.getStyleClass().add("audio-to");
mToLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
mToLabel.setMinWidth(0);
mToDetailLabel.getStyleClass().add("audio-to-detail");
mToDetailLabel.setMinWidth(Region.USE_PREF_SIZE);
HBox toBox = new HBox(10, mToLabel, mToDetailLabel);
toBox.setAlignment(Pos.BASELINE_LEFT);
IconNode fromIcon = new IconNode(FontAwesome.MICROPHONE);
fromIcon.setIconSize(12);
fromIcon.getStyleClass().add("audio-detail-icon");
mFromLabel.getStyleClass().add("audio-detail");
mFromLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
mFromLabel.setMinWidth(0);
mFromLabel.setMaxWidth(280);
mFromBox = new HBox(5, fromIcon, mFromLabel);
mFromBox.setAlignment(Pos.CENTER_LEFT);
//The FROM radio keeps its width and the system/site/channel text shrinks first
mFromBox.setMinWidth(Region.USE_PREF_SIZE);
mContextLabel.getStyleClass().add("audio-context");
mContextLabel.setTextOverrun(OverrunStyle.LEADING_ELLIPSIS);
mContextLabel.setMinWidth(0);
HBox.setHgrow(mContextLabel, Priority.ALWAYS);
mContextLabel.setMaxWidth(Double.MAX_VALUE);
mContextLabel.setAlignment(Pos.CENTER_RIGHT);
HBox detailBox = new HBox(14, mFromBox, mContextLabel);
detailBox.setAlignment(Pos.CENTER_LEFT);
mLevelMeter.setMaxWidth(Double.MAX_VALUE);
VBox content = new VBox(2, header, toBox, detailBox, mLevelMeter);
content.getStyleClass().add("audio-channel-content");
content.setMinWidth(0);
VBox.setMargin(mLevelMeter, new javafx.geometry.Insets(6, 0, 0, 0));
HBox.setHgrow(content, Priority.ALWAYS);
getChildren().addAll(mAccentStrip, iconColumn, content);
updateDisplay();
updateMuted();
mAudioChannel.addAudioEventListener(mAudioEventListener);
mAudioChannel.setIdentifierCollectionListener(mMetadataListener);
mAudioChannel.setHoldListener(hold -> Platform.runLater(this::updateHold));
updateHold();
}
/**
* Holds the talkgroup of the current (or last) call on this channel, or releases the hold.
*/
private void toggleHold()
{
if(mAudioPlaybackManager == null)
{
return;
}
if(mAudioChannel.getHold() != null)
{
mAudioPlaybackManager.setHold(mChannelIndex, null);
}
else
{
TalkgroupHold hold = getCallHold();
if(hold != null)
{
mAudioPlaybackManager.setHold(mChannelIndex, hold);
}
}
updateHold();
}
/**
* Hold for the TO talkgroup of the current or last call, labeled with the talkgroup and its alias, or null.
*/
private TalkgroupHold getCallHold()
{
IdentifierCollection collection = mIdentifierCollection;
TalkgroupHold hold = TalkgroupHold.from(collection, null);
if(hold == null)
{
return null;
}
Identifier to = collection.getToIdentifier();
AliasList aliasList = mAliasModel != null ? mAliasModel.getAliasList(collection) : null;
List<Alias> aliases = getAliases(aliasList, to);
String label = format(to);
if(!aliases.isEmpty())
{
label = label + " " + Joiner.on(", ").skipNulls().join(aliases);
}
return new TalkgroupHold(hold.protocol(), hold.talkgroup(), label);
}
/**
* Updates the hold button and label from the channel's hold talkgroup. FX thread.
*/
private void updateHold()
{
TalkgroupHold hold = mAudioChannel.getHold();
boolean held = hold != null;
mHoldButton.setSelected(held);
mHoldButton.setDisable(!held && getCallHold() == null);
mHoldButton.setTooltip(new Tooltip(held ? "Release hold on talkgroup " + hold :
"Hold this talkgroup: only play calls to this talkgroup on the " + getChannelDescription()));
mHoldButton.setAccessibleText(held ? "Release hold" : "Hold talkgroup");
mHoldLabel.setText(held ? "HOLD " + hold : "");
mHoldLabel.setVisible(held);
mHoldLabel.setManaged(held);
pseudoClassStateChanged(AudioView.HELD, held);
}
/**
* Deregisters from the audio channel.
*/
public void dispose()
{
mAudioChannel.removeAudioEventListener(mAudioEventListener);
mAudioChannel.removeAudioMetadataListener();
mAudioChannel.setHoldListener(null);
}
/**
* Channel displayed by this view
*/
public AudioChannel getAudioChannel()
{
return mAudioChannel;
}
/**
* Periodic update of the level meter and elapsed time. Invoke on the FX application thread.
*/
public void tick()
{
mLevelMeter.update(mAudioChannel.getAndResetPeakLevel());
if(mActive)
{
updateElapsed();
}
}
/**
* Refreshes the identifier text, for example when the identifier format preference changes.
*/
public void refresh()
{
updateDisplay();
}
/**
* Disables the level meter while the whole audio output (every channel) is muted.
* @param outputMuted true when every channel is muted
*/
public void setOutputMuted(boolean outputMuted)
{
mLevelMeter.setDisable(outputMuted);
}
/**
* Updates the muted display after the channel or the whole output was (un)muted.
*/
public void updateMuted()
{
boolean muted = mAudioChannel.isMuted();
mMuteButton.setSelected(muted);
mMuteIcon.setIconCode(muted ? FontAwesome.VOLUME_OFF : FontAwesome.VOLUME_UP);
mMuteButton.setTooltip(new Tooltip(muted ? "Unmute " + getChannelDescription() : "Mute " +
getChannelDescription()));
mMuteButton.setAccessibleText(muted ? "Unmute" : "Mute");
mLevelMeter.setDimmed(muted);
pseudoClassStateChanged(AudioView.MUTED, muted);
updateStatus();
}
private String getChannelDescription()
{
return switch(mAudioChannel.getChannelName())
{
case "LEFT" -> "left channel";
case "RIGHT" -> "right channel";
default -> "audio";
};
}
/**
* Audio channel events, received on the audio thread.
*/
private void receive(AudioEvent audioEvent)
{
switch(audioEvent.getType())
{
case AUDIO_STOPPED -> Platform.runLater(() -> setIdentifierCollection(null));
case REPLAY_STARTED, REPLAY_STOPPED -> Platform.runLater(this::updateReplay);
case AUDIO_MUTED, AUDIO_UNMUTED -> Platform.runLater(() -> {
updateMuted();
mMuteChangeListener.run();
});
default -> {}
}
}
/**
* Audio metadata for the playing call, received on the audio thread. Null when playback ends.
*/
private void receive(IdentifierCollection identifierCollection)
{
Platform.runLater(() -> setIdentifierCollection(identifierCollection));
}
/**
* Updates the call metadata. FX thread only.
*/
private void setIdentifierCollection(IdentifierCollection identifierCollection)
{
Identifier to = identifierCollection != null ? identifierCollection.getToIdentifier() : null;
if(identifierCollection == null || to == null)
{
if(mActive)
{
mActive = false;
mCallEndNanos = System.nanoTime();
updateElapsed();
mLevelMeter.reset();
}
//Keep the last call's identifiers so that the display shows the last call, dimmed.
updateStatus();
pseudoClassStateChanged(AudioView.ACTIVE, false);
return;
}
if(!mActive || !to.equals(mCallToIdentifier))
{
mCallStartNanos = System.nanoTime();
}
mActive = true;
mHasPlayed = true;
mCallToIdentifier = to;
mIdentifierCollection = identifierCollection;
pseudoClassStateChanged(AudioView.ACTIVE, true);
updateDisplay();
updateElapsed();
updateHold();
}
/**
* Shows the recorded call that is replaying on this channel, or restores the call display when the replay ends.
* FX thread.
*/
private void updateReplay()
{
ReplaySource replay = mAudioChannel.getReplay();
if(replay != null && !replay.isFinished())
{
mActive = false;
mHasPlayed = true;
mCallStartNanos = System.nanoTime();
mToLabel.setText("Replay");
mToDetailLabel.setText("");
mFromBox.setVisible(false);
mContextLabel.setText(replay.getDescription());
setAlias(null);
pseudoClassStateChanged(AudioView.ACTIVE, true);
mStatusLabel.setText(mAudioChannel.isMuted() ? "MUTED" : "REPLAY");
}
else
{
pseudoClassStateChanged(AudioView.ACTIVE, false);
updateDisplay();
}
}
/**
* Updates the status chip text.
*/
private void updateStatus()
{
ReplaySource replay = mAudioChannel.getReplay();
if(replay != null && !replay.isFinished())
{
mStatusLabel.setText(mAudioChannel.isMuted() ? "MUTED" : "REPLAY");
mElapsedLabel.setVisible(false);
return;
}
String status;
if(mActive)
{
status = mAudioChannel.isMuted() ? "MUTED" : "PLAYING";
}
else if(mAudioChannel.isMuted())
{
status = "MUTED";
}
else
{
status = mHasPlayed ? "LAST CALL" : "IDLE";
}
mStatusLabel.setText(status);
mElapsedLabel.setVisible(mHasPlayed);
}
private void updateElapsed()
{
long end = mActive ? System.nanoTime() : mCallEndNanos;
long seconds = Math.max(0, (end - mCallStartNanos) / 1_000_000_000L);
String text = seconds >= 3600 ? String.format("%d:%02d:%02d", seconds / 3600, (seconds / 60) % 60,
seconds % 60) : String.format("%d:%02d", seconds / 60, seconds % 60);
if(!text.equals(mElapsedLabel.getText()))
{
mElapsedLabel.setText(text);
}
}
/**
* Updates the identifiers, alias icon and accent color from the current identifier collection.
*/
private void updateDisplay()
{
updateStatus();
IdentifierCollection collection = mIdentifierCollection;
if(collection == null)
{
mToLabel.setText(NO_CALL);
mToDetailLabel.setText("");
mFromBox.setVisible(false);
mContextLabel.setText("");
setAlias(null);
return;
}
AliasList aliasList = mAliasModel != null ? mAliasModel.getAliasList(collection) : null;
Identifier to = collection.getToIdentifier();
List<Alias> toAliases = getAliases(aliasList, to);
String toId = format(to);
if(toAliases.isEmpty())
{
mToLabel.setText(toId != null ? toId : "Unknown");
mToDetailLabel.setText("");
setAlias(null);
}
else
{
mToLabel.setText(Joiner.on(", ").skipNulls().join(toAliases));
mToDetailLabel.setText(toId != null ? toId : "");
setAlias(toAliases.getFirst());
}
String from = getFromText(collection, aliasList);
mFromLabel.setText(from != null ? from : "");
mFromBox.setVisible(from != null);
mContextLabel.setText(getContextText(collection));
}
/**
* FROM radio alias and/or identifier text, or null when the call has no FROM identifier.
*/
private String getFromText(IdentifierCollection collection, AliasList aliasList)
{
Identifier from = collection.getFromIdentifier();
String fromId = format(from);
String fromName = null;
List<Alias> fromAliases = getAliases(aliasList, from);
if(!fromAliases.isEmpty())
{
fromName = Joiner.on(", ").skipNulls().join(fromAliases);
}
else
{
List<Identifier> talkerAliases = collection.getIdentifiers(Form.TALKER_ALIAS);
if(!talkerAliases.isEmpty())
{
Object value = talkerAliases.getFirst().getValue();
fromName = value != null ? value.toString() : null;
}
}
if(fromName != null && fromId != null)
{
return fromName + " " + fromId;
}
return fromName != null ? fromName : fromId;
}
/**
* System, site, channel name and protocol text.
*/
private static String getContextText(IdentifierCollection collection)
{
List<String> parts = new ArrayList<>();
add(parts, collection, Form.SYSTEM);
add(parts, collection, Form.SITE);
add(parts, collection, Form.CHANNEL_NAME);
add(parts, collection, Form.DECODER_TYPE);
return String.join(" · ", parts);
}
private static void add(List<String> parts, IdentifierCollection collection, Form form)
{
List<Identifier> identifiers = collection.getIdentifiers(IdentifierClass.CONFIGURATION, form);
if(!identifiers.isEmpty())
{
String text = identifiers.getFirst().toString();
if(text != null && !text.isBlank() && !parts.contains(text))
{
parts.add(text);
}
}
}
private static List<Alias> getAliases(AliasList aliasList, Identifier identifier)
{
if(aliasList == null || identifier == null)
{
return Collections.emptyList();
}
List<Alias> aliases = aliasList.getAliases(identifier);
return aliases != null ? aliases : Collections.emptyList();
}
private String format(Identifier identifier)
{
if(identifier == null)
{
return null;
}
return mTalkgroupFormatPreference != null ? mTalkgroupFormatPreference.format(identifier) :
identifier.toString();
}
/**
* Applies the alias icon and color, or the defaults when the alias is null.
*/
private void setAlias(Alias alias)
{
Icon icon = alias != null && alias.getIconName() != null && mIconModel != null ?
mIconModel.getIcon(alias.getIconName()) : null;
mAliasImage.setImage(icon != null ? icon.getFxImage() : null);
mPlaceholderIcon.setVisible(mAliasImage.getImage() == null);
Color accent = alias != null ? toReadable(alias.getColor()) : DEFAULT_ACCENT;
String rgb = toWeb(accent);
setStyle("-audio-accent: " + rgb + ";");
}
/**
* Converts the alias RGB color to a color that stands out against the dark display background.
*/
static Color toReadable(int rgb)
{
Color color = Color.rgb((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);
double luminance = luminance(color);
double background = luminance(DISPLAY_BACKGROUND);
//WCAG contrast ratio of at least 3:1 for the accent against the display background
int steps = 0;
while((luminance + 0.05) / (background + 0.05) < 3.0 && steps++ < 10)
{
color = color.interpolate(Color.WHITE, 0.2);
luminance = luminance(color);
}
return color;
}
private static double luminance(Color color)
{
return 0.2126 * linear(color.getRed()) + 0.7152 * linear(color.getGreen()) + 0.0722 * linear(color.getBlue());
}
private static double linear(double channel)
{
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
}
private static String toWeb(Color color)
{
return String.format("#%02x%02x%02x", (int)Math.round(color.getRed() * 255),
(int)Math.round(color.getGreen() * 255), (int)Math.round(color.getBlue() * 255));
}
}

View File

@@ -1,404 +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.audio;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.audio.playback.AudioChannel;
import io.github.dsheirer.audio.playback.AudioOutput;
import io.github.dsheirer.audio.playback.AudioPlaybackDeviceDescriptor;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Slider;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import javax.sound.sampled.FloatControl;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconFontFX;
import jiconfont.javafx.IconNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Audio playback display. A narrow master column with the output mute, audio device settings and (when the output
* supports it) a vertical volume slider, followed by one
* display per audio channel: a single wide display for a mono output or side by side left and right displays for a
* stereo output. Rebuilds the channel displays when the audio playback device configuration changes.
*/
public class AudioView extends HBox
{
private static final Logger mLog = LoggerFactory.getLogger(AudioView.class);
static final PseudoClass ACTIVE = PseudoClass.getPseudoClass("active");
static final PseudoClass MUTED = PseudoClass.getPseudoClass("muted");
static final PseudoClass HELD = PseudoClass.getPseudoClass("held");
private static final double UPDATES_PER_SECOND = 25.0;
private final AudioPlaybackManager mAudioPlaybackManager;
private final AliasModel mAliasModel;
private final IconModel mIconModel;
private final UserPreferences mUserPreferences;
private final Listener<AudioEvent> mAudioEventListener = this::receive;
private final List<AudioChannelView> mChannelViews = new ArrayList<>();
private final HBox mChannelsBox = new HBox(8);
private final ToggleButton mMuteButton = new ToggleButton();
private final IconNode mMuteIcon = new IconNode(FontAwesome.VOLUME_UP);
private final Button mSettingsButton = new Button();
private final VBox mVolumeBox;
private final Slider mVolumeSlider = new Slider(0, 100, 50);
private final Timeline mTimeline;
private FloatControl mGainControl;
static
{
IconFontFX.register(FontAwesome.getIconFont());
}
/**
* Constructs an instance
* @param audioPlaybackManager for the audio output and channels
* @param aliasModel for alias lookup
* @param iconModel for alias icons
* @param userPreferences for identifier formatting
*/
public AudioView(AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel, IconModel iconModel,
UserPreferences userPreferences)
{
mAudioPlaybackManager = audioPlaybackManager;
mAliasModel = aliasModel;
mIconModel = iconModel;
mUserPreferences = userPreferences;
getStyleClass().add("audio-view");
URL stylesheet = AudioView.class.getResource("/audio_panel.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
setSpacing(8);
setFillHeight(true);
//Master controls
Label title = new Label("AUDIO");
title.getStyleClass().add("audio-master-title");
mMuteIcon.setIconSize(22);
mMuteIcon.getStyleClass().add("audio-button-icon");
mMuteButton.setGraphic(mMuteIcon);
mMuteButton.getStyleClass().addAll("audio-icon-button", "audio-master-mute");
mMuteButton.setMaxWidth(Double.MAX_VALUE);
mMuteButton.setOnAction(event -> setOutputMuted(mMuteButton.isSelected()));
IconNode settingsIcon = new IconNode(FontAwesome.COG);
settingsIcon.setIconSize(16);
settingsIcon.getStyleClass().add("audio-button-icon");
mSettingsButton.setGraphic(settingsIcon);
mSettingsButton.getStyleClass().add("audio-icon-button");
mSettingsButton.setMaxWidth(Double.MAX_VALUE);
mSettingsButton.setAccessibleText("Audio settings");
mSettingsButton.setOnAction(event -> showAudioPreferences());
IconNode volumeIcon = new IconNode(FontAwesome.VOLUME_DOWN);
volumeIcon.setIconSize(12);
volumeIcon.getStyleClass().add("audio-detail-icon");
mVolumeSlider.getStyleClass().add("audio-volume");
mVolumeSlider.setOrientation(Orientation.VERTICAL);
mVolumeSlider.setMinHeight(40);
mVolumeSlider.setPrefHeight(60);
VBox.setVgrow(mVolumeSlider, Priority.ALWAYS);
mVolumeSlider.setTooltip(new Tooltip("Volume (double-click to reset)"));
mVolumeSlider.setAccessibleText("Volume");
mVolumeSlider.valueProperty().addListener((observable, oldValue, newValue) -> applyVolume(newValue.intValue()));
mVolumeSlider.setOnMouseClicked(event -> {
if(event.getClickCount() == 2)
{
mVolumeSlider.setValue(50);
}
});
mVolumeBox = new VBox(4, mVolumeSlider, volumeIcon);
mVolumeBox.setAlignment(Pos.TOP_CENTER);
VBox controls = new VBox(6, title, mMuteButton, mSettingsButton);
controls.setAlignment(Pos.TOP_CENTER);
controls.setFillWidth(true);
HBox master = new HBox(4, controls, mVolumeBox);
master.getStyleClass().add("audio-master");
master.setMinWidth(HBox.USE_PREF_SIZE);
HBox.setHgrow(mChannelsBox, Priority.ALWAYS);
mChannelsBox.setFillHeight(true);
mChannelsBox.setMinWidth(0);
getChildren().addAll(master, mChannelsBox);
ContextMenu contextMenu = new ContextMenu();
MenuItem preferences = new MenuItem("Audio Playback Device ...");
IconNode cog = new IconNode(FontAwesome.COG);
cog.setIconSize(14);
preferences.setGraphic(cog);
preferences.setOnAction(event -> showAudioPreferences());
contextMenu.getItems().add(preferences);
setOnMouseClicked(event -> {
if(event.getButton() == MouseButton.SECONDARY)
{
contextMenu.show(this, event.getScreenX(), event.getScreenY());
}
else
{
contextMenu.hide();
}
});
mTimeline = new Timeline(new KeyFrame(Duration.millis(1000.0 / UPDATES_PER_SECOND), event -> tick()));
mTimeline.setCycleCount(Animation.INDEFINITE);
rebuild();
mAudioPlaybackManager.addAudioEventListener(mAudioEventListener);
MyEventBus.getGlobalEventBus().register(this);
mTimeline.play();
}
/**
* Stops updates and deregisters from the audio playback manager.
*/
public void dispose()
{
mTimeline.stop();
mAudioPlaybackManager.removeAudioEventListener(mAudioEventListener);
MyEventBus.getGlobalEventBus().unregister(this);
disposeChannelViews();
}
/**
* Updates the identifier display when the identifier format preference changes.
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
Platform.runLater(() -> mChannelViews.forEach(AudioChannelView::refresh));
}
}
/**
* Audio playback manager events, received on the calling thread.
*/
private void receive(AudioEvent event)
{
if(event.getType() == AudioEvent.Type.AUDIO_CONFIGURATION_CHANGE_COMPLETE)
{
Platform.runLater(this::rebuild);
}
}
private void tick()
{
for(AudioChannelView channelView: mChannelViews)
{
channelView.tick();
}
}
private void disposeChannelViews()
{
mChannelViews.forEach(AudioChannelView::dispose);
mChannelViews.clear();
mChannelsBox.getChildren().clear();
}
/**
* Rebuilds the channel displays and master controls for the current audio output. FX thread only.
*/
private void rebuild()
{
disposeChannelViews();
List<AudioChannel> channels = mAudioPlaybackManager.getAudioChannels();
for(int x = 0; x < channels.size(); x++)
{
AudioChannel channel = channels.get(x);
AudioChannelView view = new AudioChannelView(channel, mAliasModel, mIconModel,
mUserPreferences.getTalkgroupFormatPreference(), UPDATES_PER_SECOND, this::updateMuted,
mAudioPlaybackManager, x);
mChannelViews.add(view);
mChannelsBox.getChildren().add(view);
}
AudioOutput output = mAudioPlaybackManager.getAudioOutput();
mGainControl = output != null && output.hasGainControl() ? output.getGainControl() : null;
mVolumeBox.setVisible(mGainControl != null);
mVolumeBox.setManaged(mGainControl != null);
if(mGainControl != null)
{
mVolumeSlider.setValue(toSliderValue(mGainControl.getValue()));
}
AudioPlaybackDeviceDescriptor device = mAudioPlaybackManager.getAudioPlaybackDevice();
String deviceName = device != null ? device.toString() : "No audio device";
String layout = switch(channels.size())
{
case 0 -> "";
case 1 -> "Mono";
case 2 -> "Stereo";
default -> channels.size() + " channels";
};
String deviceText = layout.isEmpty() ? deviceName : layout + " · " + deviceName;
mSettingsButton.setTooltip(new Tooltip("Audio playback device and preferences\n" + deviceText));
if(channels.isEmpty())
{
Label none = new Label("No audio playback device available");
none.getStyleClass().add("audio-detail");
mChannelsBox.getChildren().add(none);
}
mMuteButton.setDisable(output == null);
updateMuted();
}
/**
* Updates the master mute button and disables the channel level meters when every channel is muted.
*/
private void updateMuted()
{
boolean muted = !mChannelViews.isEmpty();
for(AudioChannelView view: mChannelViews)
{
muted &= view.getAudioChannel().isMuted();
}
for(AudioChannelView view: mChannelViews)
{
view.setOutputMuted(muted);
}
mMuteButton.setSelected(muted);
mMuteIcon.setIconCode(muted ? FontAwesome.VOLUME_OFF : FontAwesome.VOLUME_UP);
mMuteButton.setTooltip(new Tooltip(muted ? "Unmute all audio" : "Mute all audio"));
mMuteButton.setAccessibleText(muted ? "Unmute all audio" : "Mute all audio");
}
private void setOutputMuted(boolean muted)
{
AudioOutput output = mAudioPlaybackManager.getAudioOutput();
if(output != null)
{
output.setMuted(muted);
}
mChannelViews.forEach(AudioChannelView::updateMuted);
updateMuted();
}
private void showAudioPreferences()
{
MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.AUDIO_OUTPUT));
}
private void applyVolume(int value)
{
FloatControl control = mGainControl;
if(control != null)
{
try
{
control.shift(control.getValue(), toGain(control, value), 1000);
}
catch(Exception e)
{
mLog.warn("Unable to set audio output gain", e);
}
}
}
/**
* Converts a gain control value in dB to the slider value, where 50 is the 0 dB (no gain) mid-point.
*/
private int toSliderValue(float gain)
{
FloatControl control = mGainControl;
if(control == null || gain == 0.0f)
{
return 50;
}
else if(gain < 0.0f)
{
return 50 - (int)(gain / control.getMinimum() * 50.0f);
}
else
{
return 50 + (int)(gain / control.getMaximum() * 50.0f);
}
}
/**
* Converts the slider value to a gain control value in dB, where 50 is the 0 dB (no gain) mid-point.
*/
static float toGain(FloatControl control, int value)
{
if(value == 50)
{
return 0.0f;
}
else if(value < 50)
{
return (float)(50 - value) / 50.0f * control.getMinimum();
}
else
{
return (float)(value - 50) / 50.0f * control.getMaximum();
}
}
}

View File

@@ -1,222 +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.audio;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
/**
* Segmented horizontal audio level meter in dBFS with peak hold and level ballistics. Feed it with peak sample
* levels via {@link #update(float)} at a steady rate from the JavaFX application thread. While the meter is
* disabled, for example when the whole audio output is muted, it shows silence and ignores updates.
*/
public class LevelMeter extends Region
{
public static final double MINIMUM_DB = -48.0;
public static final double MAXIMUM_DB = 0.0;
private static final double WARNING_DB = -12.0;
private static final double CLIP_DB = -3.0;
private static final double SEGMENT_WIDTH = 4.0;
private static final double SEGMENT_GAP = 2.0;
private static final double PREFERRED_HEIGHT = 8.0;
private static final Color NORMAL_ON = Color.web("#3ddc84");
private static final Color WARNING_ON = Color.web("#f5c542");
private static final Color CLIP_ON = Color.web("#ff5c5c");
private static final Color NORMAL_OFF = Color.web("#3ddc84", 0.12);
private static final Color WARNING_OFF = Color.web("#f5c542", 0.12);
private static final Color CLIP_OFF = Color.web("#ff5c5c", 0.12);
private final Canvas mCanvas = new Canvas();
private final double mFallPerUpdateDb;
private final int mPeakHoldUpdates;
private double mLevelDb = MINIMUM_DB;
private double mPeakDb = MINIMUM_DB;
private int mPeakHoldCount;
private boolean mDimmed;
private boolean mDirty = true;
private double mDrawnLevelDb = Double.NaN;
private double mDrawnPeakDb = Double.NaN;
/**
* Constructs an instance
* @param updatesPerSecond rate that {@link #update(float)} is invoked, to scale the level fall and peak hold.
*/
public LevelMeter(double updatesPerSecond)
{
mFallPerUpdateDb = 30.0 / updatesPerSecond; //30 dB per second fall
mPeakHoldUpdates = (int)Math.round(1.5 * updatesPerSecond); //1.5 second peak hold
getStyleClass().add("level-meter");
getChildren().add(mCanvas);
setMinHeight(PREFERRED_HEIGHT);
setPrefHeight(PREFERRED_HEIGHT);
setMaxHeight(PREFERRED_HEIGHT);
setMinWidth(40);
disabledProperty().addListener((observable, wasDisabled, disabled) -> {
updateOpacity();
reset();
});
}
/**
* Updates the meter with the peak sample level measured since the previous update.
* @param peak absolute sample peak, where 1.0 is full scale.
*/
public void update(float peak)
{
if(isDisabled())
{
return;
}
double db = peak > 0.0f ? Math.max(MINIMUM_DB, Math.min(MAXIMUM_DB, 20.0 * Math.log10(peak))) : MINIMUM_DB;
double level = Math.max(db, mLevelDb - mFallPerUpdateDb);
if(db >= mPeakDb)
{
mPeakDb = db;
mPeakHoldCount = mPeakHoldUpdates;
}
else if(mPeakHoldCount > 0)
{
mPeakHoldCount--;
}
else
{
mPeakDb = Math.max(MINIMUM_DB, mPeakDb - mFallPerUpdateDb);
}
mLevelDb = level;
if(mDirty || mLevelDb != mDrawnLevelDb || mPeakDb != mDrawnPeakDb)
{
draw();
}
}
/**
* Sets the meter to draw in a dimmed state, for example when the channel is muted.
*/
public void setDimmed(boolean dimmed)
{
if(mDimmed != dimmed)
{
mDimmed = dimmed;
updateOpacity();
}
}
private void updateOpacity()
{
mCanvas.setOpacity(isDisabled() ? 0.3 : mDimmed ? 0.45 : 1.0);
}
/**
* Resets the meter to silence.
*/
public void reset()
{
mLevelDb = MINIMUM_DB;
mPeakDb = MINIMUM_DB;
mPeakHoldCount = 0;
draw();
}
@Override
protected void layoutChildren()
{
double width = snapSizeX(getWidth());
double height = snapSizeY(getHeight());
if(mCanvas.getWidth() != width || mCanvas.getHeight() != height)
{
mCanvas.setWidth(width);
mCanvas.setHeight(height);
draw();
}
}
@Override
protected double computePrefWidth(double height)
{
return 200;
}
/**
* Fraction of the meter span for the dB value.
*/
private static double toFraction(double db)
{
return (db - MINIMUM_DB) / (MAXIMUM_DB - MINIMUM_DB);
}
private void draw()
{
mDirty = false;
mDrawnLevelDb = mLevelDb;
mDrawnPeakDb = mPeakDb;
double width = mCanvas.getWidth();
double height = mCanvas.getHeight();
GraphicsContext gc = mCanvas.getGraphicsContext2D();
gc.clearRect(0, 0, width, height);
if(width <= 0 || height <= 0)
{
return;
}
int segments = (int)Math.floor((width + SEGMENT_GAP) / (SEGMENT_WIDTH + SEGMENT_GAP));
if(segments <= 0)
{
return;
}
//Spread the remainder across the gaps so the meter fills the width
double step = segments > 1 ? (width - SEGMENT_WIDTH) / (segments - 1) : 0;
double levelFraction = toFraction(mLevelDb);
double peakFraction = toFraction(mPeakDb);
int peakSegment = mPeakDb > MINIMUM_DB ? (int)Math.min(segments - 1, Math.floor(peakFraction * segments)) : -1;
for(int x = 0; x < segments; x++)
{
double segmentFraction = (x + 0.5) / segments;
double segmentDb = MINIMUM_DB + segmentFraction * (MAXIMUM_DB - MINIMUM_DB);
boolean on = segmentFraction <= levelFraction || x == peakSegment;
if(segmentDb >= CLIP_DB)
{
gc.setFill(on ? CLIP_ON : CLIP_OFF);
}
else if(segmentDb >= WARNING_DB)
{
gc.setFill(on ? WARNING_ON : WARNING_OFF);
}
else
{
gc.setFill(on ? NORMAL_ON : NORMAL_OFF);
}
gc.fillRoundRect(x * step, 0, SEGMENT_WIDTH, height, 2, 2);
}
}
}

View File

@@ -1,410 +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.broadcast;
import io.github.dsheirer.audio.broadcast.AbstractAudioBroadcaster;
import io.github.dsheirer.audio.broadcast.BroadcastEvent;
import io.github.dsheirer.audio.broadcast.BroadcastModel;
import io.github.dsheirer.audio.broadcast.BroadcastServerType;
import io.github.dsheirer.audio.broadcast.BroadcastState;
import io.github.dsheirer.audio.broadcast.ConfiguredBroadcast;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.streaming.ViewStreamingRequest;
import io.github.dsheirer.gui.table.ColumnConfigurationButton;
import io.github.dsheirer.gui.table.TableColumnMonitor;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.preference.swing.SwingPreference;
import io.github.dsheirer.sample.Listener;
import java.net.URL;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.ToIntFunction;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconFontFX;
import jiconfont.javafx.IconNode;
/**
* Status of the configured audio streams: type, name, connection status and the streamed, queued, rejected, aged
* off and failed audio counts. The column selection, order and widths are kept across sessions.
*/
public class BroadcastStatusView extends VBox
{
static final String TABLE_KEY = "broadcast.status";
static final String SWING_TABLE_KEY = "application.broadcast.status.panel";
private final BroadcastModel mBroadcastModel;
private final ObservableList<ConfiguredBroadcast> mItems = FXCollections.observableArrayList();
private final TableView<ConfiguredBroadcast> mTableView = new TableView<>(mItems);
private final Label mSummaryLabel = new Label();
private final AtomicBoolean mUpdateScheduled = new AtomicBoolean();
private final Map<BroadcastServerType,Image> mServerTypeImages = new EnumMap<>(BroadcastServerType.class);
private final Listener<BroadcastEvent> mBroadcastEventListener = event -> scheduleUpdate();
private final ListChangeListener<ConfiguredBroadcast> mListChangeListener = change -> scheduleUpdate();
static
{
IconFontFX.register(FontAwesome.getIconFont());
}
/**
* Constructs an instance
* @param broadcastModel with the configured streams
* @param swingPreference with the column widths of the Swing version of this table, migrated once
*/
public BroadcastStatusView(BroadcastModel broadcastModel, SwingPreference swingPreference)
{
mBroadcastModel = broadcastModel;
getStyleClass().add("broadcast-status-view");
URL stylesheet = BroadcastStatusView.class.getResource("/broadcast_status.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
mTableView.getColumns().addAll(List.of(
createServerTypeColumn(),
createNameColumn(),
createStatusColumn(),
createCountColumn("queued", "Queued", AbstractAudioBroadcaster::getAudioQueueSize,
"Recordings waiting to be streamed or uploaded"),
createCountColumn("streamed", "Streamed/Uploaded", AbstractAudioBroadcaster::getStreamedAudioCount,
"Recordings streamed or uploaded"),
createCountColumn("duplicate", "Duplicate Rejected",
AbstractAudioBroadcaster::getDuplicateRejectedAudioCount, "Duplicate calls that were not streamed"),
createCountColumn("agedOff", "Aged Off", AbstractAudioBroadcaster::getAgedOffAudioCount,
"Recordings discarded because they waited too long to be streamed"),
createCountColumn("errors", "Upload Error", AbstractAudioBroadcaster::getAudioErrorCount,
"Recordings that failed to stream or upload")));
mTableView.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
mTableView.setTableMenuButtonVisible(false);
mTableView.setFixedCellSize(26);
Label placeholder = new Label("No streams are configured. Use Configure Streams to add a stream.");
placeholder.getStyleClass().add("broadcast-placeholder");
mTableView.setPlaceholder(placeholder);
VBox.setVgrow(mTableView, Priority.ALWAYS);
TableColumnMonitor<ConfiguredBroadcast> monitor = new TableColumnMonitor<>(mTableView, TABLE_KEY,
swingPreference, SWING_TABLE_KEY);
IconNode titleIcon = new IconNode(FontAwesome.PODCAST);
titleIcon.setIconSize(14);
titleIcon.getStyleClass().add("broadcast-title-icon");
Label title = new Label("Streaming", titleIcon);
title.getStyleClass().add("broadcast-title");
mSummaryLabel.getStyleClass().add("broadcast-summary");
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
IconNode configureIcon = new IconNode(FontAwesome.COG);
configureIcon.setIconSize(13);
Button configureButton = new Button("Configure Streams", configureIcon);
configureIcon.fillProperty().bind(configureButton.textFillProperty());
configureButton.setTooltip(new Tooltip("Add and edit streams in the playlist editor"));
configureButton.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewStreamingRequest()));
ColumnConfigurationButton columnsButton = new ColumnConfigurationButton(monitor, "Streaming Status Columns");
HBox toolbar = new HBox(10, title, mSummaryLabel, spacer, configureButton, columnsButton);
toolbar.getStyleClass().add("broadcast-toolbar");
toolbar.setAlignment(Pos.CENTER_LEFT);
getChildren().addAll(toolbar, mTableView);
mBroadcastModel.addListener(mBroadcastEventListener);
mBroadcastModel.getConfiguredBroadcasts().addListener(mListChangeListener);
update();
}
/**
* Deregisters from the broadcast model.
*/
public void dispose()
{
mBroadcastModel.removeListener(mBroadcastEventListener);
mBroadcastModel.getConfiguredBroadcasts().removeListener(mListChangeListener);
}
/**
* Table showing the streams.
*/
public TableView<ConfiguredBroadcast> getTableView()
{
return mTableView;
}
/**
* Schedules an update on the FX thread. Broadcasters report changes on their own threads, often several at a
* time, so the updates are coalesced.
*/
private void scheduleUpdate()
{
if(mUpdateScheduled.compareAndSet(false, true))
{
Platform.runLater(() -> {
mUpdateScheduled.set(false);
update();
});
}
}
/**
* Updates the table rows and summary from the model. FX thread only.
*/
private void update()
{
List<ConfiguredBroadcast> current = new ArrayList<>(mBroadcastModel.getConfiguredBroadcasts());
if(!current.equals(mItems))
{
mItems.setAll(current);
}
else
{
mTableView.refresh();
}
mSummaryLabel.setText(getSummary(current));
}
/**
* Summary of the stream status counts, for example: 3 connected, 1 error.
*/
static String getSummary(List<ConfiguredBroadcast> broadcasts)
{
if(broadcasts.isEmpty())
{
return "";
}
int connected = 0;
int warning = 0;
int error = 0;
int disabled = 0;
for(ConfiguredBroadcast broadcast: broadcasts)
{
switch(getSeverity(broadcast.getStatus()))
{
case OK -> connected++;
case WARNING -> warning++;
case ERROR -> error++;
case DISABLED -> disabled++;
default -> {}
}
}
List<String> parts = new ArrayList<>();
parts.add(connected + " of " + broadcasts.size() + " connected");
if(error > 0)
{
parts.add(error + (error == 1 ? " error" : " errors"));
}
if(warning > 0)
{
parts.add(warning + (warning == 1 ? " warning" : " warnings"));
}
if(disabled > 0)
{
parts.add(disabled + " disabled");
}
return String.join(" · ", parts);
}
/**
* Status severity used to color the status.
*/
enum Severity {OK, NEUTRAL, WARNING, ERROR, DISABLED}
static Severity getSeverity(BroadcastState state)
{
if(state == null)
{
return Severity.NEUTRAL;
}
return switch(state)
{
case CONNECTED -> Severity.OK;
case DISABLED -> Severity.DISABLED;
case INVALID_SETTINGS, NETWORK_UNAVAILABLE -> Severity.WARNING;
default -> state.isWarningState() ? Severity.WARNING :
state.isErrorState() ? Severity.ERROR : Severity.NEUTRAL;
};
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createServerTypeColumn()
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn("type", "Stream Type", 170);
column.setCellFactory(param -> new TableCell<>()
{
private final ImageView mImageView = new ImageView();
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
BroadcastServerType type = empty || item == null ? null : item.getBroadcastServerType();
if(type == null)
{
setText(null);
setGraphic(null);
}
else
{
setText(type.toString());
mImageView.setImage(getImage(type));
mImageView.setFitHeight(14);
mImageView.setPreserveRatio(true);
setGraphic(mImageView.getImage() != null ? mImageView : null);
}
}
});
return column;
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createNameColumn()
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn("name", "Name", 220);
column.setCellFactory(param -> new TableCell<>()
{
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
setText(empty || item == null ? null : item.getBroadcastConfiguration().getName());
}
});
return column;
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createStatusColumn()
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn("status", "Status", 190);
column.setCellFactory(param -> new TableCell<>()
{
private final Label mChip = new Label();
{
mChip.getStyleClass().add("broadcast-status-chip");
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setAlignment(Pos.CENTER_LEFT);
}
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
if(empty || item == null)
{
setGraphic(null);
setTooltip(null);
return;
}
BroadcastState state = item.getStatus();
mChip.setText(state != null ? state.toString() : "Unknown");
mChip.getStyleClass().removeIf(styleClass -> styleClass.startsWith("broadcast-status-severity-"));
mChip.getStyleClass().add("broadcast-status-severity-" +
getSeverity(state).name().toLowerCase());
setGraphic(mChip);
BroadcastState lastBad = item.lastBadBroadcastStateProperty().get();
setTooltip(lastBad != null && lastBad != state ? new Tooltip("Last problem: " + lastBad) : null);
}
});
return column;
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createCountColumn(String id, String title,
ToIntFunction<AbstractAudioBroadcaster> count, String description)
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn(id, title, 130);
Label header = new Label(title);
header.setTooltip(new Tooltip(description));
column.setText(null);
column.setGraphic(header);
TableColumnMonitor.setName(column, title);
column.setCellFactory(param -> new TableCell<>()
{
{
setAlignment(Pos.CENTER_RIGHT);
getStyleClass().add("broadcast-count");
}
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
AbstractAudioBroadcaster broadcaster = empty || item == null ? null : item.getAudioBroadcaster();
setText(broadcaster != null ? String.format("%,d", count.applyAsInt(broadcaster)) : null);
}
});
return column;
}
private static TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createColumn(String id, String title,
double width)
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = new TableColumn<>(title);
column.setId(id);
column.setPrefWidth(width);
column.setSortable(false);
column.setCellValueFactory(param -> new javafx.beans.property.ReadOnlyObjectWrapper<>(param.getValue()));
return column;
}
private Image getImage(BroadcastServerType type)
{
return mServerTypeImages.computeIfAbsent(type, serverType -> {
String path = serverType.getIconPath();
return path != null ? new Icon(serverType.name(), path).getFxImage() : null;
});
}
}

View File

@@ -1,240 +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.calls;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.database.call.IdentifierFilter;
import javafx.css.PseudoClass;
import javafx.geometry.Side;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyCode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/**
* Search field for the TO (talkgroup) or FROM (radio) identifier of a call. As the user types, a list of matching
* aliases from the current alias lists drops down. Selecting an alias filters the calls by the alias's talkgroup or
* radio identifiers. Typing without selecting an alias filters by the identifier text or value.
*/
public class AliasSearchField extends TextField
{
private static final PseudoClass ALIAS_SELECTED = PseudoClass.getPseudoClass("alias-selected");
private static final int MAX_SUGGESTIONS = 25;
/**
* Identifier kind that the field searches
*/
public enum Kind
{
TALKGROUP,
RADIO
}
private final Kind mKind;
private final AliasModel mAliasModel;
private final ContextMenu mSuggestions = new ContextMenu();
private final Runnable mSearchAction;
private IdentifierFilter mAliasFilter;
private boolean mSettingText;
/**
* Constructs an instance
* @param kind of identifier to search
* @param aliasModel for the alias suggestions, or null for text search only
* @param prompt text
* @param searchAction invoked when the user selects an alias or presses enter
*/
public AliasSearchField(Kind kind, AliasModel aliasModel, String prompt, Runnable searchAction)
{
mKind = kind;
mAliasModel = aliasModel;
mSearchAction = searchAction;
setPromptText(prompt);
getStyleClass().add("calls-alias-search");
mSuggestions.setAutoHide(true);
updateTooltip();
textProperty().addListener((observable, oldValue, newValue) -> {
if(!mSettingText)
{
mAliasFilter = null;
pseudoClassStateChanged(ALIAS_SELECTED, false);
updateTooltip();
showSuggestions(newValue);
}
});
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
mSuggestions.hide();
}
});
setOnKeyPressed(event -> {
if(event.getCode() == KeyCode.ESCAPE)
{
mSuggestions.hide();
}
else if(event.getCode() == KeyCode.DOWN && !mSuggestions.getItems().isEmpty())
{
if(!mSuggestions.isShowing())
{
mSuggestions.show(this, Side.BOTTOM, 0, 0);
}
mSuggestions.getSkin().getNode().lookupAll(".menu-item").stream().findFirst()
.ifPresent(node -> node.requestFocus());
event.consume();
}
});
setOnAction(event -> {
mSuggestions.hide();
mSearchAction.run();
});
}
/**
* Current search filter: the selected alias, or the typed text.
*/
public IdentifierFilter getFilter()
{
return mAliasFilter != null ? mAliasFilter : IdentifierFilter.text(getText());
}
/**
* Clears the text and any selected alias
*/
public void reset()
{
mSettingText = true;
setText("");
mSettingText = false;
mAliasFilter = null;
pseudoClassStateChanged(ALIAS_SELECTED, false);
updateTooltip();
mSuggestions.hide();
}
/**
* Selects the alias as the search filter
*/
public void select(Alias alias)
{
mAliasFilter = mKind == Kind.TALKGROUP ? IdentifierFilter.talkgroupAlias(alias) :
IdentifierFilter.radioAlias(alias);
mSettingText = true;
setText(alias.getName());
positionCaret(getText().length());
mSettingText = false;
pseudoClassStateChanged(ALIAS_SELECTED, true);
updateTooltip();
mSuggestions.hide();
mSearchAction.run();
}
private void updateTooltip()
{
String what = mKind == Kind.TALKGROUP ? "talkgroup" : "radio";
if(mAliasFilter != null)
{
setTooltip(new Tooltip("Alias [" + mAliasFilter.aliasName() + "] in alias list [" +
mAliasFilter.aliasList() + "]: calls with the alias " + what + " identifiers"));
}
else
{
setTooltip(new Tooltip("Type a " + what + " alias name and select it from the list, or type part of the " +
what + " identifier or its exact value"));
}
}
/**
* Aliases (with identifiers of this field's kind) whose name contains the text, sorted by name.
*/
List<Alias> getMatchingAliases(String text)
{
List<Alias> matches = new ArrayList<>();
if(mAliasModel == null || text == null || text.isBlank())
{
return matches;
}
String lower = text.trim().toLowerCase(Locale.ROOT);
for(Alias alias: new ArrayList<>(mAliasModel.aliasList()))
{
if(alias.getName() != null && alias.getName().toLowerCase(Locale.ROOT).contains(lower) &&
(mKind == Kind.TALKGROUP ? IdentifierFilter.hasTalkgroups(alias) : IdentifierFilter.hasRadios(alias)))
{
matches.add(alias);
}
}
//Names that start with the text first, then alphabetical
matches.sort(Comparator.comparing((Alias alias) -> !alias.getName().toLowerCase(Locale.ROOT)
.startsWith(lower)).thenComparing(alias -> alias.getName().toLowerCase(Locale.ROOT))
.thenComparing(alias -> alias.getAliasListName() != null ? alias.getAliasListName() : ""));
return matches;
}
private void showSuggestions(String text)
{
List<Alias> matches = getMatchingAliases(text);
mSuggestions.getItems().clear();
if(matches.isEmpty() || !isFocused())
{
mSuggestions.hide();
return;
}
for(Alias alias: matches.subList(0, Math.min(MAX_SUGGESTIONS, matches.size())))
{
Label label = new Label(alias.getName() + " (" + (alias.getAliasListName() != null ?
alias.getAliasListName() : "no list") + ")");
CustomMenuItem item = new CustomMenuItem(label, true);
item.setOnAction(event -> select(alias));
mSuggestions.getItems().add(item);
}
if(matches.size() > MAX_SUGGESTIONS)
{
CustomMenuItem more = new CustomMenuItem(new Label((matches.size() - MAX_SUGGESTIONS) +
" more - keep typing to narrow the list"), false);
more.setDisable(true);
mSuggestions.getItems().add(more);
}
if(!mSuggestions.isShowing())
{
mSuggestions.show(this, Side.BOTTOM, 0, 0);
}
}
}

View File

@@ -1,151 +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.calls;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.database.call.PatchedTalkgroup;
/**
* Looks up the current aliases for the TO and FROM identifiers of a stored call, using the call's alias list from the
* alias model. Calls are aliased with the latest alias values, so historical calls pick up alias changes.
*/
public class CallAliasResolver
{
private final AliasModel mAliasModel;
/**
* Constructs an instance
* @param aliasModel with the current aliases, or null to disable alias lookup
*/
public CallAliasResolver(AliasModel aliasModel)
{
mAliasModel = aliasModel;
}
private AliasList getAliasList(CallRecord call)
{
if(mAliasModel == null || call == null || call.getAliasList() == null || call.getAliasList().isEmpty())
{
return null;
}
return mAliasModel.getAliasList(call.getAliasList());
}
/**
* Current alias for the TO talkgroup, patch group or radio of the call, or null.
*/
public Alias getToAlias(CallRecord call)
{
AliasList aliasList = getAliasList(call);
if(aliasList == null || call.getToValue() == null || call.getToValue() > Integer.MAX_VALUE)
{
return null;
}
int value = call.getToValue().intValue();
if(call.isToTalkgroup())
{
return aliasList.getTalkgroupAlias(call.getProtocolValue(), value, call.getToFullyQualified());
}
if(CallRecord.FORM_RADIO.equals(call.getToForm()))
{
return aliasList.getRadioAlias(call.getProtocolValue(), value, call.getToFullyQualified());
}
return null;
}
/**
* Current alias for the FROM radio of the call, or null.
*/
public Alias getFromAlias(CallRecord call)
{
AliasList aliasList = getAliasList(call);
if(aliasList == null || !call.isFromRadio() || call.getFromValue() == null ||
call.getFromValue() > Integer.MAX_VALUE)
{
return null;
}
return aliasList.getRadioAlias(call.getProtocolValue(), call.getFromValue().intValue(),
call.getFromFullyQualified());
}
/**
* Talkgroups patched into the TO patch group, with their current alias names, e.g. "1001 Fire Dispatch, 1002",
* or null when the call isn't a patch group call.
*/
public String getPatchedTalkgroups(CallRecord call)
{
if(call == null || call.getPatchedTalkgroups().isEmpty())
{
return null;
}
AliasList aliasList = getAliasList(call);
StringBuilder sb = new StringBuilder();
for(PatchedTalkgroup talkgroup: call.getPatchedTalkgroups())
{
if(sb.length() > 0)
{
sb.append(", ");
}
sb.append(talkgroup.value());
Alias alias = aliasList != null && talkgroup.value() <= Integer.MAX_VALUE ?
aliasList.getTalkgroupAlias(call.getProtocolValue(), (int)talkgroup.value(),
talkgroup.fullyQualified()) : null;
if(alias != null)
{
sb.append(" ").append(alias.getName());
}
}
return sb.toString();
}
/**
* Name of the current TO alias, or null
*/
public String getToAliasName(CallRecord call)
{
Alias alias = getToAlias(call);
return alias != null ? alias.getName() : null;
}
/**
* Name of the current FROM alias, or null
*/
public String getFromAliasName(CallRecord call)
{
Alias alias = getFromAlias(call);
return alias != null ? alias.getName() : null;
}
}

View File

@@ -1,370 +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.calls;
import io.github.dsheirer.audio.playback.AudioChannel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.audio.playback.ReplaySource;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.record.RecordingReader;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.util.Duration;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
/**
* Replays call recordings in the Calls tab through the sdrtrunk audio channels (the same audio output, channels,
* mute and level meters as live calls). The audio playback manager chooses the channel: an idle channel, otherwise
* the left (or mono) channel, which drops the live call that it is playing.
*/
public class CallPlayer extends HBox
{
private static final Logger LOGGER = LoggerFactory.getLogger(CallPlayer.class);
private final AudioPlaybackManager mAudioPlaybackManager;
private final Button mPlayButton = new Button();
private final IconNode mPlayIcon = new IconNode(FontAwesome.PLAY);
private final Button mStopButton = new Button();
private final Slider mPositionSlider = new Slider(0, 1, 0);
private final Label mTimeLabel = new Label("0:00 / 0:00");
private final Label mCallLabel = new Label("Double-click a recorded call to replay it");
private final CheckBox mAutoPlayCheckBox = new CheckBox("Auto-play next");
private final ObjectProperty<CallRecord> mCurrentCall = new SimpleObjectProperty<>();
private final Timeline mProgressTimeline;
private CallAliasResolver mAliasResolver = new CallAliasResolver(null);
private Consumer<CallRecord> mFinishedListener;
private ReplaySource mReplay;
private long mLoadSequence;
/**
* Constructs an instance
* @param audioPlaybackManager that replays the calls, or null to disable replay
*/
public CallPlayer(AudioPlaybackManager audioPlaybackManager)
{
super(8);
mAudioPlaybackManager = audioPlaybackManager;
setAlignment(Pos.CENTER_LEFT);
getStyleClass().add("calls-player");
mPlayIcon.setIconSize(14);
mPlayIcon.fillProperty().bind(mPlayButton.textFillProperty());
mPlayButton.setGraphic(mPlayIcon);
mPlayButton.setTooltip(new Tooltip("Pause / resume"));
mPlayButton.setOnAction(event -> togglePause());
IconNode stopIcon = new IconNode(FontAwesome.STOP);
stopIcon.setIconSize(14);
stopIcon.fillProperty().bind(mStopButton.textFillProperty());
mStopButton.setGraphic(stopIcon);
mStopButton.setTooltip(new Tooltip("Stop the replay"));
mStopButton.setOnAction(event -> stop());
mPositionSlider.setPrefWidth(260);
mPositionSlider.setMinWidth(100);
mPositionSlider.valueChangingProperty().addListener((obs, old, changing) -> {
if(!changing)
{
seek();
}
});
mPositionSlider.setOnMouseReleased(event -> seek());
mTimeLabel.setMinWidth(Label.USE_PREF_SIZE);
mCallLabel.setMinWidth(0);
mAutoPlayCheckBox.setTooltip(new Tooltip("When a replay finishes, replay the next newer recorded call"));
mAutoPlayCheckBox.setMinWidth(Label.USE_PREF_SIZE);
HBox.setHgrow(mCallLabel, Priority.ALWAYS);
mCallLabel.setMaxWidth(Double.MAX_VALUE);
getChildren().addAll(mPlayButton, mStopButton, mPositionSlider, mTimeLabel, mCallLabel, mAutoPlayCheckBox);
mProgressTimeline = new Timeline(new KeyFrame(Duration.millis(100), event -> updateProgress()));
mProgressTimeline.setCycleCount(Timeline.INDEFINITE);
updateControls();
}
/**
* Sets the resolver for the current TO and FROM aliases shown for the replayed call
*/
public void setAliasResolver(CallAliasResolver aliasResolver)
{
mAliasResolver = aliasResolver;
}
/**
* Registers a listener for when a replay plays to the end (used for auto-play of the next call)
*/
public void setFinishedListener(Consumer<CallRecord> listener)
{
mFinishedListener = listener;
}
/**
* Indicates if auto-play of the next call is enabled
*/
public boolean isAutoPlay()
{
return mAutoPlayCheckBox.isSelected();
}
/**
* Call that is loaded in the player, or null
*/
public ObjectProperty<CallRecord> currentCallProperty()
{
return mCurrentCall;
}
/**
* Replays the recording of the call. The recording is read on a background thread. FX thread.
* @return true if the replay is starting
*/
public boolean play(CallRecord call)
{
if(call == null || !call.isPlayable())
{
return false;
}
if(mAudioPlaybackManager == null || mAudioPlaybackManager.getAudioChannels().isEmpty())
{
mCallLabel.setText("No audio output is available for replay");
return false;
}
Path path = Path.of(call.getFilePath());
if(!Files.exists(path))
{
mCallLabel.setText("Recording file not found: " + path.getFileName());
return false;
}
stopReplay();
long sequence = ++mLoadSequence;
String description = describe(call);
mCurrentCall.set(call);
mCallLabel.setText("Loading " + description);
updateControls();
CompletableFuture.supplyAsync(() -> {
try
{
return RecordingReader.read(path);
}
catch(Exception e)
{
throw new IllegalStateException(e.getMessage(), e);
}
}).whenComplete((samples, error) -> Platform.runLater(() -> {
if(sequence != mLoadSequence)
{
return; //Another call was selected while this one was loading
}
if(error != null)
{
Throwable cause = error.getCause() != null ? error.getCause() : error;
LOGGER.warn("Unable to replay recording [" + path + "] - " + cause.getMessage());
mCallLabel.setText("Unable to replay " + path.getFileName() + ": " + cause.getMessage());
mCurrentCall.set(null);
updateControls();
return;
}
ReplaySource replay = new ReplaySource(samples, call.getId(), description);
int channelIndex = mAudioPlaybackManager.replay(replay);
if(channelIndex < 0)
{
mCallLabel.setText("No audio output is available for replay");
mCurrentCall.set(null);
updateControls();
return;
}
mReplay = replay;
mCallLabel.setText(getChannelLabel(channelIndex) + description);
mProgressTimeline.play();
updateControls();
}));
return true;
}
private String getChannelLabel(int channelIndex)
{
List<AudioChannel> channels = mAudioPlaybackManager.getAudioChannels();
if(channels.size() > 1 && channelIndex < channels.size())
{
return channels.get(channelIndex).getChannelName() + ": ";
}
return "";
}
private String describe(CallRecord call)
{
StringBuilder sb = new StringBuilder();
sb.append(CallsView.formatTime(call.getStartTime()));
if(call.getToId() != null)
{
sb.append(" TO:").append(call.getToId());
String toAlias = mAliasResolver.getToAliasName(call);
if(toAlias != null)
{
sb.append(" ").append(toAlias);
}
}
if(call.getFromId() != null)
{
sb.append(" FROM:").append(call.getFromId());
String fromAlias = mAliasResolver.getFromAliasName(call);
if(fromAlias != null)
{
sb.append(" ").append(fromAlias);
}
}
return sb.toString();
}
private void togglePause()
{
if(mReplay != null)
{
mReplay.setPaused(!mReplay.isPaused());
updateControls();
}
}
/**
* Stops the replay. FX thread.
*/
public void stop()
{
mLoadSequence++;
stopReplay();
mCurrentCall.set(null);
mCallLabel.setText("Double-click a recorded call to replay it");
mPositionSlider.setValue(0);
mTimeLabel.setText("0:00 / 0:00");
updateControls();
}
private void stopReplay()
{
mProgressTimeline.stop();
if(mReplay != null)
{
mReplay.stop();
mReplay = null;
}
}
private void seek()
{
if(mReplay != null)
{
mReplay.seek(mPositionSlider.getValue());
}
}
/**
* Updates the position display and detects the end of the replay. FX thread.
*/
private void updateProgress()
{
ReplaySource replay = mReplay;
if(replay == null)
{
mProgressTimeline.stop();
return;
}
if(!mPositionSlider.isValueChanging())
{
mPositionSlider.setValue(replay.getFraction());
}
mTimeLabel.setText(format(replay.getPositionMillis()) + " / " + format(replay.getDurationMillis()));
if(replay.isFinished())
{
CallRecord finished = mCurrentCall.get();
boolean completed = replay.isCompleted();
stop();
if(completed && mFinishedListener != null && finished != null)
{
mFinishedListener.accept(finished);
}
}
}
private static String format(long millis)
{
long seconds = Math.max(0, millis / 1000);
return seconds / 60 + ":" + String.format("%02d", seconds % 60);
}
private void updateControls()
{
boolean loaded = mReplay != null;
mPlayButton.setDisable(!loaded);
mStopButton.setDisable(!loaded && mCurrentCall.get() == null);
mPositionSlider.setDisable(!loaded);
mPlayIcon.setIconCode(loaded && !mReplay.isPaused() ? FontAwesome.PAUSE : FontAwesome.PLAY);
}
/**
* Stops the replay and releases resources.
*/
public void dispose()
{
stop();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,573 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 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.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.LoggingTunerErrorListener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import io.github.dsheirer.source.tuner.test.TestTuner;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ChannelizerViewer extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelizerViewer.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private static final int CHANNEL_FFT_FRAME_RATE = 20;
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private JPanel mControlPanel;
private JLabel mToneFrequencyLabel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelArrayPanel mChannelPanel;
private DiscreteIndexChannelArrayPanel mDiscreteIndexChannelPanel;
private int mChannelCount;
private int mChannelsPerRow;
private long mBaseFrequency = 100000000; //100 MHz
private DFTSize mMainPanelDFTSize = DFTSize.FFT32768;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT04096;
private TestTuner mTestTuner;
/**
* GUI Test utility for researching polyphase channelizers.
*
* @param channelsPerRow
*/
public ChannelizerViewer(int channelsPerRow)
{
mTestTuner = new TestTuner(new LoggingTunerErrorListener());
mChannelCount = (int)(mTestTuner.getTunerController().getBandwidth() / CHANNEL_BANDWIDTH);
mChannelsPerRow = channelsPerRow;
init();
}
private void init()
{
setTitle("Polyphase Channelizer Viewer");
setSize(1200, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][][grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "wrap");
mPrimaryPanel.add(getControlPanel(), "wrap");
mPrimaryPanel.add(getChannelArrayPanel(), "wrap");
mPrimaryPanel.add(getDiscreteIndexChannelPanel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager,
mTestTuner.getTunerController().getSampleRate());
mPrimarySpectrumPanel.setPreferredSize(new Dimension(1200, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
mTestTuner.getTunerController().addBufferListener(mPrimarySpectrumPanel);
}
return mPrimarySpectrumPanel;
}
private JPanel getControlPanel()
{
if(mControlPanel == null)
{
mControlPanel = new JPanel();
mControlPanel.setLayout(new MigLayout("insets 0 0 0 0", "", ""));
mControlPanel.add(new JLabel("Tone:"), "align left");
long minimumFrequency = -(long)mTestTuner.getTunerController().getSampleRate() / 2 + 1;
long maximumFrequency = (long)mTestTuner.getTunerController().getSampleRate() / 2 - 1;
long toneFrequency = 0;
SpinnerNumberModel model = new SpinnerNumberModel(toneFrequency, minimumFrequency, maximumFrequency,
100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mTestTuner.getTunerController().setToneFrequency(toneFrequency);
mToneFrequencyLabel.setText(String.valueOf(getToneFrequency()));
}
});
JSpinner spinner = new JSpinner(model);
mControlPanel.add(spinner);
mControlPanel.add(new JLabel("Hz"));
mControlPanel.add(new JLabel("Frequency:"), "push,align right");
mToneFrequencyLabel = new JLabel(String.valueOf(getToneFrequency()));
mControlPanel.add(mToneFrequencyLabel, "push,align left");
mControlPanel.add(new JLabel("Channels: " + mChannelCount), "push,align right");
}
return mControlPanel;
}
private long getToneFrequency()
{
return mTestTuner.getTunerController().getFrequency() + mTestTuner.getTunerController().getToneFrequency();
}
private ChannelArrayPanel getChannelArrayPanel()
{
if(mChannelPanel == null)
{
mChannelPanel = new ChannelArrayPanel();
}
return mChannelPanel;
}
private DiscreteIndexChannelArrayPanel getDiscreteIndexChannelPanel()
{
if(mDiscreteIndexChannelPanel == null)
{
mDiscreteIndexChannelPanel = new DiscreteIndexChannelArrayPanel();
}
return mDiscreteIndexChannelPanel;
}
public class ChannelArrayPanel extends JPanel
{
private final Logger mLog = LoggerFactory.getLogger(ChannelArrayPanel.class);
public ChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
double spectralBandwidth = mTestTuner.getTunerController().getSampleRate();
double halfSpectralBandwidth = spectralBandwidth / 2.0;
int channelToLog = -1;
long baseFrequency = mBaseFrequency + (CHANNEL_BANDWIDTH / 2);
for(int x = 0; x < mChannelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
mLog.debug("Channel " + x + "/" + mChannelCount + " Frequency: " + frequency);
ChannelPanel channelPanel = new ChannelPanel(mSettingsManager, CHANNEL_BANDWIDTH * 2, frequency, CHANNEL_BANDWIDTH, (x == channelToLog));
channelPanel.setDFTSize(mChannelPanelDFTSize);
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
public class DiscreteIndexChannelArrayPanel extends JPanel
{
public DiscreteIndexChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
for(int x = 0; x < mChannelCount; x++)
{
TunerChannel tunerChannel = new TunerChannel(100000000, 12500);
TunerChannelSource source = mTestTuner.getChannelSourceManager().getSource(tunerChannel, null, "test");
DiscreteChannelPanel channelPanel = new DiscreteChannelPanel(mSettingsManager, source, x);
channelPanel.setDFTSize(mChannelPanelDFTSize);
mLog.debug("Testing Channel [" + x + "] is set to [" + source.getTunerChannel().getFrequency() + "]");
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
/**
* Returns a list of tuner channels that will fit within the tuner's bandwidth, minus a half channel each at the
* lower and upper ends of the spectrum.
*
* @param tuner to create channels for
* @return list of contiguous channels filling the tuner bandwidth
*/
public static List<TunerChannel> getTunerChannels(Tuner tuner)
{
List<TunerChannel> tunerChannels = new ArrayList<>();
long baseFrequency = tuner.getTunerController().getFrequency();
baseFrequency -= tuner.getTunerController().getSampleRate() / 2;
baseFrequency += (CHANNEL_BANDWIDTH / 2);
int channelCount = (int)(tuner.getTunerController().getSampleRate() / CHANNEL_BANDWIDTH) - 1;
for(int x = 0; x < channelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
tunerChannels.add(tunerChannel);
}
return tunerChannels;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager, double sampleRate)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(28);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class ChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public ChannelPanel(SettingsManager settingsManager, double sampleRate, long frequency, int bandwidth, boolean enableLogging)
{
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
TunerChannel tunerChannel = new TunerChannel(frequency, bandwidth);
mSource = mTestTuner.getChannelSourceManager().getSource(tunerChannel, null, "test");
if(mSource != null)
{
mSource.setListener(complexSamples -> mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved())));
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for frequency: " + frequency);
}
if(mSource != null)
{
add(new JLabel("Center:" + frequency));
}
else
{
add(new JLabel("NO SRC:" + frequency));
}
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class DiscreteChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private final Logger mLog = LoggerFactory.getLogger(DiscreteChannelPanel.class);
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public DiscreteChannelPanel(SettingsManager settingsManager, TunerChannelSource source, int index)
{
mSource = source;
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
add(new JLabel("Index:" + index));
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
if(mSource != null)
{
mSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
if(mLoggingEnabled)
{
mLog.debug("Samples:" + Arrays.toString(complexSamples.toInterleaved().samples()));
}
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
});
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for index: " + index);
}
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public static void main(String[] args)
{
boolean useGUI = true;
if(useGUI)
{
int channelsPerRow = 16;
final ChannelizerViewer frame = new ChannelizerViewer(channelsPerRow);
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
frame.setVisible(true);
}
});
}
else
{
TestTuner tuner = new TestTuner(new LoggingTunerErrorListener());
List<TunerChannel> tunerChannels = getTunerChannels(tuner);
List<TunerChannelSource> sources = new ArrayList<>();
int maxSourceCount = 30;
int sourceCount = 0;
for(TunerChannel tunerChannel : tunerChannels)
{
if(sourceCount < maxSourceCount)
{
TunerChannelSource source = tuner.getChannelSourceManager().getSource(tunerChannel, null, "test");
if(source != null)
{
sources.add(source);
sourceCount++;
}
else
{
mLog.debug("Couldn't get source for: " + tunerChannel);
}
}
}
mLog.debug("Starting [" + sources.size() + "] tuner channel sources");
for(TunerChannelSource tunerChannelSource : sources)
{
tunerChannelSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
}
});
tunerChannelSource.start();
}
while(true)
{
;
}
}
}
}

View File

@@ -0,0 +1,472 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 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.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.dsp.filter.channelizer.PolyphaseChannelSource;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.LoggingTunerErrorListener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.channel.ChannelSpecification;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import io.github.dsheirer.source.tuner.test.TestTuner;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ChannelizerViewer2 extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelizerViewer2.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private JPanel mControlPanel;
private JButton mTopFrameAddChannelButton;
private JButton mBottomFrameAddChannelButton;
private JLabel mToneFrequencyLabel;
private JLabel mCenterFrequencyLabel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelArrayPanel mTopChannelArrayPanel;
private ChannelArrayPanel mBottomChannelArrayPanel;
private DFTSize mMainPanelDFTSize = DFTSize.FFT32768;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT04096;
private TestTuner mTestTuner = new TestTuner(new LoggingTunerErrorListener());
/**
* GUI Test utility for researching polyphase channelizers.
*/
public ChannelizerViewer2()
{
init();
}
private void init()
{
setTitle("Polyphase Channelizer Viewer");
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][][grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "wrap");
mPrimaryPanel.add(getControlPanel(), "wrap");
mPrimaryPanel.add(getTopChannelArrayPanel(), "wrap");
mPrimaryPanel.add(getBottomChannelArrayPanel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager,
mTestTuner.getTunerController().getSampleRate());
mPrimarySpectrumPanel.setPreferredSize(new Dimension(1200, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
mTestTuner.getTunerController().addBufferListener(mPrimarySpectrumPanel);
}
return mPrimarySpectrumPanel;
}
private JPanel getControlPanel()
{
if(mControlPanel == null)
{
mControlPanel = new JPanel();
mControlPanel.setLayout(new MigLayout("insets 0 0 0 0", "", ""));
mControlPanel.add(new JLabel("Tone:"), "align left");
long minimumFrequency = -(long)mTestTuner.getTunerController().getSampleRate() / 2 + 1;
long maximumFrequency = (long)mTestTuner.getTunerController().getSampleRate() / 2 - 1;
long toneFrequency = 0;
SpinnerNumberModel model = new SpinnerNumberModel(toneFrequency, minimumFrequency, maximumFrequency,
100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mTestTuner.getTunerController().setToneFrequency(toneFrequency);
mToneFrequencyLabel.setText(String.valueOf(getToneFrequency()));
mCenterFrequencyLabel.setText(String.valueOf(getCenterFrequency()));
}
});
JSpinner spinner = new JSpinner(model);
mControlPanel.add(spinner);
mControlPanel.add(new JLabel("Hz"));
mControlPanel.add(new JLabel("Tone Frequency:"), "push,align right");
mToneFrequencyLabel = new JLabel(String.valueOf(getToneFrequency()));
mControlPanel.add(mToneFrequencyLabel, "push,align left");
mControlPanel.add(new JLabel("Center Frequency:"), "push,align right");
mCenterFrequencyLabel = new JLabel(String.valueOf(getCenterFrequency()));
mControlPanel.add(mCenterFrequencyLabel, "push,align left");
mControlPanel.add(getBottomFrameAddChannelButton(), "push,align right");
mControlPanel.add(getTopFrameAddChannelButton(), "push,align right");
}
return mControlPanel;
}
private JButton getTopFrameAddChannelButton()
{
if(mTopFrameAddChannelButton == null)
{
mTopFrameAddChannelButton = new JButton("Top - Add Channel");
mTopFrameAddChannelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String value = JOptionPane.showInputDialog(ChannelizerViewer2.this, "Frequency?");
if(value != null && !value.isEmpty())
{
try
{
int frequency = Integer.parseInt(value);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
getTopChannelArrayPanel().addChannel(tunerChannel);
}
catch(Exception e1)
{
mLog.error("Can't parse frequency from value: " + value, e1);
}
}
}
});
}
return mTopFrameAddChannelButton;
}
private JButton getBottomFrameAddChannelButton()
{
if(mBottomFrameAddChannelButton == null)
{
mBottomFrameAddChannelButton = new JButton("Bottom - Add Channel");
mBottomFrameAddChannelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String value = JOptionPane.showInputDialog(ChannelizerViewer2.this, "Frequency?");
if(value != null && !value.isEmpty())
{
try
{
int frequency = Integer.parseInt(value);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
getBottomChannelArrayPanel().addChannel(tunerChannel);
}
catch(Exception e1)
{
mLog.error("Can't parse frequency from value: " + value, e1);
}
}
}
});
}
return mBottomFrameAddChannelButton;
}
private long getToneFrequency()
{
return mTestTuner.getTunerController().getFrequency() + mTestTuner.getTunerController().getToneFrequency();
}
private long getCenterFrequency()
{
return mTestTuner.getTunerController().getFrequency();
}
private ChannelArrayPanel getTopChannelArrayPanel()
{
if(mTopChannelArrayPanel == null)
{
mTopChannelArrayPanel = new ChannelArrayPanel();
}
return mTopChannelArrayPanel;
}
private ChannelArrayPanel getBottomChannelArrayPanel()
{
if(mBottomChannelArrayPanel == null)
{
mBottomChannelArrayPanel = new ChannelArrayPanel();
}
return mBottomChannelArrayPanel;
}
public class ChannelArrayPanel extends JPanel
{
public ChannelArrayPanel()
{
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
}
public void addChannel(TunerChannel tunerChannel)
{
ChannelPanel channelPanel = new ChannelPanel(mSettingsManager, CHANNEL_BANDWIDTH * 2,
tunerChannel.getFrequency(), CHANNEL_BANDWIDTH);
channelPanel.setDFTSize(mChannelPanelDFTSize);
add(channelPanel, "grow,push");
validate();
repaint();
}
}
/**
* Returns a list of tuner channels that will fit within the tuner's bandwidth, minus a half channel each at the
* lower and upper ends of the spectrum.
*
* @param tuner to create channels for
* @return list of contiguous channels filling the tuner bandwidth
*/
public static List<TunerChannel> getTunerChannels(Tuner tuner)
{
List<TunerChannel> tunerChannels = new ArrayList<>();
long baseFrequency = tuner.getTunerController().getFrequency();
baseFrequency -= tuner.getTunerController().getSampleRate() / 2;
baseFrequency += (CHANNEL_BANDWIDTH / 2);
int channelCount = (int)(tuner.getTunerController().getSampleRate() / CHANNEL_BANDWIDTH) - 1;
for(int x = 0; x < channelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
tunerChannels.add(tunerChannel);
}
return tunerChannels;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager, double sampleRate)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class ChannelPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public ChannelPanel(SettingsManager settingsManager, double sampleRate, long frequency, int bandwidth)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill][grow,fill][grow,fill]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel, "span");
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
TunerChannel tunerChannel = new TunerChannel(frequency, bandwidth);
mSource = mTestTuner.getChannelSourceManager().getSource(tunerChannel,
new ChannelSpecification(50000, 12500, 6000, 7000), "test");
if(mSource != null)
{
mLog.debug("Channel: " + mSource.getTunerChannel() + " Rate:" + mSource.getSampleRate());
mSource.setListener((Listener<ComplexSamples>) complexSamples ->
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
});
if(mSource instanceof PolyphaseChannelSource pcs)
{ List<Integer> indexes = pcs.getOutputProcessorIndexes();
double sRate = pcs.getSampleRate();
long indexCenterFrequency = pcs.getIndexCenterFrequency();
long appliedFrequencyOffset = pcs.getFrequencyOffset();
long requestedCenterFrequency = pcs.getFrequency();
StringBuilder sb = new StringBuilder();
sb.append("Polyphase Channel - Bandwidth: ").append(sRate);
sb.append(" Channel/Requested/Offset: ").append(indexCenterFrequency);
sb.append("/").append(requestedCenterFrequency);
sb.append("/").append(appliedFrequencyOffset);
sb.append(" Indexes: ").append(indexes);
sb.append(" Tuner SR:").append(pcs.getTunerSampleRate());
sb.append(" Tuner CF:").append(pcs.getTunerCenterFrequency());
mLog.info(sb.toString());
}
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for frequency: " + frequency);
}
if(mSource != null)
{
int half = (int)(sampleRate / 2.0f);
add(new JLabel("Min:" + (frequency - half)), "align left");
add(new JLabel("Center:" + frequency));
add(new JLabel("Max:" + (frequency + half)), "align right");
}
else
{
add(new JLabel("NO SRC:" + frequency));
}
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(e -> mLoggingEnabled = mLoggingButton.isSelected());
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public static void main(String[] args)
{
final ChannelizerViewer2 frame = new ChannelizerViewer2();
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
frame.setVisible(true);
}
});
}
}

View File

@@ -0,0 +1,573 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 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.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.LoggingTunerErrorListener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.channel.ChannelSpecification;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import io.github.dsheirer.source.tuner.test.TestTuner;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class HeterodyneChannelizerViewer extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(HeterodyneChannelizerViewer.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private static final int CHANNEL_FFT_FRAME_RATE = 20;
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private JPanel mControlPanel;
private JLabel mToneFrequencyLabel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelArrayPanel mChannelPanel;
private DiscreteIndexChannelArrayPanel mDiscreteIndexChannelPanel;
private int mChannelCount;
private int mChannelsPerRow;
private long mBaseFrequency = 100000000; //100 MHz
private DFTSize mMainPanelDFTSize = DFTSize.FFT04096;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT04096;
private TestTuner mTestTuner;
/**
* GUI Test utility for researching channelizers.
*/
public HeterodyneChannelizerViewer()
{
mTestTuner = new TestTuner(new LoggingTunerErrorListener());
mChannelCount = 5;
mChannelsPerRow = 5;
init();
}
private void init()
{
setTitle("Heterodyne Channelizer Viewer");
setSize(1200, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][][grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "wrap");
mPrimaryPanel.add(getControlPanel(), "wrap");
mPrimaryPanel.add(getChannelArrayPanel(), "wrap");
// mPrimaryPanel.add(getDiscreteIndexChannelPanel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager,
mTestTuner.getTunerController().getSampleRate());
mPrimarySpectrumPanel.setPreferredSize(new Dimension(1200, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
mTestTuner.getTunerController().addBufferListener(mPrimarySpectrumPanel);
}
return mPrimarySpectrumPanel;
}
private JPanel getControlPanel()
{
if(mControlPanel == null)
{
mControlPanel = new JPanel();
mControlPanel.setLayout(new MigLayout("insets 0 0 0 0", "", ""));
mControlPanel.add(new JLabel("Tone:"), "align left");
long minimumFrequency = -(long)mTestTuner.getTunerController().getSampleRate() / 2 + 1;
long maximumFrequency = (long)mTestTuner.getTunerController().getSampleRate() / 2 - 1;
long toneFrequency = 0;
SpinnerNumberModel model = new SpinnerNumberModel(toneFrequency, minimumFrequency, maximumFrequency,
100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mTestTuner.getTunerController().setToneFrequency(toneFrequency);
mToneFrequencyLabel.setText(String.valueOf(getToneFrequency()));
}
});
JSpinner spinner = new JSpinner(model);
mControlPanel.add(spinner);
mControlPanel.add(new JLabel("Hz"));
mControlPanel.add(new JLabel("Frequency:"), "push,align right");
mToneFrequencyLabel = new JLabel(String.valueOf(getToneFrequency()));
mControlPanel.add(mToneFrequencyLabel, "push,align left");
mControlPanel.add(new JLabel("Channels: " + mChannelCount), "push,align right");
}
return mControlPanel;
}
private long getToneFrequency()
{
return mTestTuner.getTunerController().getFrequency() + mTestTuner.getTunerController().getToneFrequency();
}
private ChannelArrayPanel getChannelArrayPanel()
{
if(mChannelPanel == null)
{
mChannelPanel = new ChannelArrayPanel();
}
return mChannelPanel;
}
private DiscreteIndexChannelArrayPanel getDiscreteIndexChannelPanel()
{
if(mDiscreteIndexChannelPanel == null)
{
mDiscreteIndexChannelPanel = new DiscreteIndexChannelArrayPanel();
}
return mDiscreteIndexChannelPanel;
}
public class ChannelArrayPanel extends JPanel
{
private final Logger mLog = LoggerFactory.getLogger(ChannelArrayPanel.class);
public ChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
double spectralBandwidth = mTestTuner.getTunerController().getSampleRate();
double halfSpectralBandwidth = spectralBandwidth / 2.0;
int channelToLog = -1;
long baseFrequency = mBaseFrequency + (CHANNEL_BANDWIDTH / 2);
for(int x = 0; x < mChannelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
mLog.debug("Channel " + x + "/" + mChannelCount + " Frequency: " + frequency);
ChannelPanel channelPanel = new ChannelPanel(mSettingsManager, CHANNEL_BANDWIDTH * 2, frequency, CHANNEL_BANDWIDTH, (x == channelToLog));
channelPanel.setDFTSize(mChannelPanelDFTSize);
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
public class DiscreteIndexChannelArrayPanel extends JPanel
{
public DiscreteIndexChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
ChannelSpecification channelSpecification = new ChannelSpecification(25000.0, 12500, 6000.0, 6250.0);
for(int x = 0; x < mChannelCount; x++)
{
TunerChannel tunerChannel = new TunerChannel(100000000, 12500);
TunerChannelSource source = mTestTuner.getChannelSourceManager().getSource(tunerChannel,
channelSpecification, "test");
DiscreteChannelPanel channelPanel = new DiscreteChannelPanel(mSettingsManager, source, x);
channelPanel.setDFTSize(mChannelPanelDFTSize);
mLog.debug("Testing Channel [" + x + "] is set to [" + source.getTunerChannel().getFrequency() + "]");
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
/**
* Returns a list of tuner channels that will fit within the tuner's bandwidth, minus a half channel each at the
* lower and upper ends of the spectrum.
*
* @param tuner to create channels for
* @return list of contiguous channels filling the tuner bandwidth
*/
public static List<TunerChannel> getTunerChannels(Tuner tuner)
{
List<TunerChannel> tunerChannels = new ArrayList<>();
long baseFrequency = tuner.getTunerController().getFrequency();
baseFrequency -= tuner.getTunerController().getSampleRate() / 2;
baseFrequency += (CHANNEL_BANDWIDTH / 2);
int channelCount = (int)(tuner.getTunerController().getSampleRate() / CHANNEL_BANDWIDTH) - 1;
for(int x = 0; x < channelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
tunerChannels.add(tunerChannel);
}
return tunerChannels;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager, double sampleRate)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(28);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class ChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public ChannelPanel(SettingsManager settingsManager, double sampleRate, long frequency, int bandwidth, boolean enableLogging)
{
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
TunerChannel tunerChannel = new TunerChannel(frequency, bandwidth);
ChannelSpecification channelSpecification = new ChannelSpecification(25000.0, 12500, 6000.0, 6250.0);
mSource = mTestTuner.getChannelSourceManager().getSource(tunerChannel, channelSpecification, "test");
if(mSource != null)
{
mSource.setListener(complexSamples -> mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved())));
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for frequency: " + frequency);
}
if(mSource != null)
{
add(new JLabel("Center:" + frequency));
}
else
{
add(new JLabel("NO SRC:" + frequency));
}
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class DiscreteChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private final Logger mLog = LoggerFactory.getLogger(DiscreteChannelPanel.class);
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public DiscreteChannelPanel(SettingsManager settingsManager, TunerChannelSource source, int index)
{
mSource = source;
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
add(new JLabel("Index:" + index));
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
if(mSource != null)
{
mSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
if(mLoggingEnabled)
{
mLog.debug("Samples:" + Arrays.toString(complexSamples.toInterleaved().samples()));
}
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
});
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for index: " + index);
}
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public static void main(String[] args)
{
boolean useGUI = true;
if(useGUI)
{
final HeterodyneChannelizerViewer frame = new HeterodyneChannelizerViewer();
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
frame.setVisible(true);
}
});
}
else
{
TestTuner tuner = new TestTuner(new LoggingTunerErrorListener());
List<TunerChannel> tunerChannels = getTunerChannels(tuner);
List<TunerChannelSource> sources = new ArrayList<>();
int maxSourceCount = 30;
int sourceCount = 0;
for(TunerChannel tunerChannel : tunerChannels)
{
if(sourceCount < maxSourceCount)
{
TunerChannelSource source = tuner.getChannelSourceManager().getSource(tunerChannel,
null, "test");
if(source != null)
{
sources.add(source);
sourceCount++;
}
else
{
mLog.debug("Couldn't get source for: " + tunerChannel);
}
}
}
mLog.debug("Starting [" + sources.size() + "] tuner channel sources");
for(TunerChannelSource tunerChannelSource : sources)
{
tunerChannelSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
}
});
tunerChannelSource.start();
}
while(true)
{
;
}
}
}
}

View File

@@ -0,0 +1,322 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 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.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.dsp.filter.FilterFactory;
import io.github.dsheirer.dsp.filter.channelizer.TwoChannelSynthesizerM2;
import io.github.dsheirer.dsp.filter.design.FilterDesignException;
import io.github.dsheirer.dsp.oscillator.FS4DownConverter;
import io.github.dsheirer.dsp.oscillator.IComplexOscillator;
import io.github.dsheirer.dsp.oscillator.OscillatorFactory;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import io.github.dsheirer.util.ThreadPool;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.concurrent.TimeUnit;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SynthesizerViewer extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(SynthesizerViewer.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private static final int CHANNEL_SAMPLE_RATE = 25000;
private static final int CHANNEL_FFT_FRAME_RATE = 20; //frames per second
private static final int DATA_GENERATOR_FRAME_RATE = 50; //frames per second
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelPanel mChannel1Panel;
private ChannelPanel mChannel2Panel;
private ChannelControlPanel mChannel1ControlPanel;
private ChannelControlPanel mChannel2ControlPanel;
private DFTSize mMainPanelDFTSize = DFTSize.FFT08192;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT08192;
/**
* GUI Test utility for researching polyphase synthesizers.
*/
public SynthesizerViewer()
{
init();
}
public void start()
{
ThreadPool.SCHEDULED.scheduleAtFixedRate(new DataGenerationManager(), 0, 1000 / DATA_GENERATOR_FRAME_RATE, TimeUnit.MILLISECONDS);
}
private void init()
{
setTitle("Polyphase Synthesizer Viewer");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill][grow,fill]", "[grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "span");
mPrimaryPanel.add(getChannel1Panel());
mPrimaryPanel.add(getChannel2Panel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager);
mPrimarySpectrumPanel.setPreferredSize(new Dimension(500, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
}
return mPrimarySpectrumPanel;
}
private ChannelPanel getChannel1Panel()
{
if(mChannel1Panel == null)
{
mChannel1Panel = new ChannelPanel(mSettingsManager, getChannel1ControlPanel());
mChannel1Panel.setPreferredSize(new Dimension(250, 200));
mChannel1Panel.setDFTSize(mChannelPanelDFTSize);
}
return mChannel1Panel;
}
private ChannelPanel getChannel2Panel()
{
if(mChannel2Panel == null)
{
mChannel2Panel = new ChannelPanel(mSettingsManager, getChannel2ControlPanel());
mChannel2Panel.setPreferredSize(new Dimension(250, 200));
mChannel2Panel.setDFTSize(mChannelPanelDFTSize);
}
return mChannel2Panel;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDftProcessor.setFrameRate(CHANNEL_FFT_FRAME_RATE);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
}
public class ChannelPanel extends JPanel implements Listener<INativeBuffer>
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private boolean mLoggingEnabled = false;
public ChannelPanel(SettingsManager settingsManager, ChannelControlPanel channelControlPanel)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel, "wrap");
add(channelControlPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDftProcessor.setFrameRate(CHANNEL_FFT_FRAME_RATE);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
}
private ChannelControlPanel getChannel1ControlPanel()
{
if(mChannel1ControlPanel == null)
{
mChannel1ControlPanel = new ChannelControlPanel();
}
return mChannel1ControlPanel;
}
private ChannelControlPanel getChannel2ControlPanel()
{
if(mChannel2ControlPanel == null)
{
mChannel2ControlPanel = new ChannelControlPanel();
}
return mChannel2ControlPanel;
}
public class ChannelControlPanel extends JPanel
{
private static final int MIN_FREQUENCY = -6250;
private static final int MAX_FREQUENCY = 6250;
private static final int DEFAULT_FREQUENCY = 50;
private IComplexOscillator mOscillator = OscillatorFactory.getComplexOscillator(DEFAULT_FREQUENCY, CHANNEL_SAMPLE_RATE);
public ChannelControlPanel()
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
add(new JLabel("Tone:"), "align right");
SpinnerNumberModel model = new SpinnerNumberModel(DEFAULT_FREQUENCY, MIN_FREQUENCY, MAX_FREQUENCY, 100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mOscillator.setFrequency(toneFrequency);
}
});
JSpinner spinner = new JSpinner(model);
add(spinner);
add(new JLabel("Hz"));
}
public IComplexOscillator getOscillator()
{
return mOscillator;
}
}
public class DataGenerationManager implements Runnable
{
private TwoChannelSynthesizerM2 mSynthesizer;
private FS4DownConverter mFS4DownConverter = new FS4DownConverter();
private int mSamplesPerCycle = CHANNEL_SAMPLE_RATE / DATA_GENERATOR_FRAME_RATE;
private boolean mOddSample = false;
public DataGenerationManager()
{
try
{
float[] taps = FilterFactory.getSincM2Synthesizer( 25000.0, 12500.0, 2, 24);
mSynthesizer = new TwoChannelSynthesizerM2(taps);
}
catch(FilterDesignException fde)
{
mLog.error("Filter design error", fde);
}
}
@Override
public void run()
{
ComplexSamples channel1Buffer = getChannel1ControlPanel().getOscillator().generateComplexSamples(mSamplesPerCycle, 0l);
ComplexSamples channel2Buffer = getChannel2ControlPanel().getOscillator().generateComplexSamples(mSamplesPerCycle, 0l);
//Translate channel 2 by FS/2 so that it sits adjacent to channel 1 for synthesis
float[] i2 = channel2Buffer.i().clone();
float[] q2 = channel2Buffer.q().clone();
for(int x = 0; x < i2.length; x++)
{
if(mOddSample)
{
i2[x] = -i2[x];
q2[x] = -q2[x];
}
mOddSample = !mOddSample;
}
ComplexSamples synthesizedBuffer = mSynthesizer.process(channel1Buffer,
new ComplexSamples(i2, q2, channel2Buffer.timestamp()));
getChannel1Panel().receive(new FloatNativeBuffer(channel1Buffer));
getChannel2Panel().receive(new FloatNativeBuffer(channel2Buffer));
getSpectrumPanel().receive(new FloatNativeBuffer(synthesizedBuffer));
}
}
public static void main(String[] args)
{
final SynthesizerViewer frame = new SynthesizerViewer();
EventQueue.invokeLater(() -> {
frame.setVisible(true);
frame.start();
});
}
}

View File

@@ -0,0 +1,179 @@
package io.github.dsheirer.gui.control;
import io.github.dsheirer.buffer.CircularBuffer;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.Complex;
import org.apache.commons.math3.util.FastMath;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.util.List;
public class ConstellationViewer extends JPanel implements Listener<Complex>
{
private static final long serialVersionUID = 1L;
private int mSampleRate;
private int mSymbolRate;
private float mSamplesPerSymbol;
private float mCounter = 0;
private float mOffset = 0;
private CircularBuffer<Complex> mBuffer =
new CircularBuffer<Complex>( 5000 );
private Complex mPrevious = new Complex( 1, 1 );
public ConstellationViewer( int sampleRate, int symbolRate )
{
mSampleRate = sampleRate;
mSymbolRate = symbolRate;
mSamplesPerSymbol = (float)mSampleRate / (float)mSymbolRate;
initGui();
}
private void initGui()
{
setPreferredSize( new Dimension( 200,200 ) );
addMouseListener( new MouseListener()
{
@Override
public void mouseClicked( MouseEvent e )
{
if( SwingUtilities.isRightMouseButton( e ) )
{
JPopupMenu menu = new JPopupMenu();
menu.add( new TimingOffsetItem( (int)( mSamplesPerSymbol * 10 ), (int)( mOffset * 10 ) ) );
menu.show( ConstellationViewer.this, e.getX(), e.getY() );
}
}
public void mouseReleased( MouseEvent e ) {}
public void mousePressed( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mouseEntered( MouseEvent e ) {}
} );
}
@Override
public void receive( Complex sample )
{
mBuffer.receive( sample );
Complex angle = Complex.multiply( sample, mPrevious.conjugate() );
repaint();
}
/**
* Sets the timing offset ( 0 <> SamplesPerSymbol ) for selecting which
* sample to plot, within the symbol timeframe. Values greater than the
* samples per symbol value will simply wrap or delay into the next symbol
* period.
*
* @param offset
*/
public void setOffset( float offset )
{
mOffset = offset;
repaint();
}
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D graphics = (Graphics2D) g;
graphics.setColor( Color.BLUE );
List<Complex> samples = mBuffer.getElements();
double centerX = (double)getHeight() / 2.0d;
double centerY = (double)getWidth() / 2.0d;
double scale = 0.5d;
mCounter = 0;
for( Complex sample: samples )
{
if( mCounter > ( mOffset + mSamplesPerSymbol ) )
{
/**
* Multiply the current sample against the complex conjugate of the
* previous sample to derive the phase delta between the two samples
*
* Negating the previous sample quadrature produces the conjugate
*/
double i = ( sample.inphase() * mPrevious.inphase() ) -
( sample.quadrature() * -mPrevious.quadrature() );
double q = ( sample.quadrature() * mPrevious.inphase() ) +
( sample.inphase() * -mPrevious.quadrature() );
double angle;
//Check for divide by zero
if( i == 0 )
{
angle = 0.0;
}
else
{
/**
* Use the arcus tangent of imaginary (q) divided by real (i) to
* get the phase angle (+/-) which was directly manipulated by the
* original message waveform during the modulation. This value now
* serves as the instantaneous amplitude of the demodulated signal
*/
double denominator = 1.0d / i;
angle = FastMath.atan( (double)q * denominator );
}
Ellipse2D.Double ellipse =
new Ellipse2D.Double( centerX - ( i * scale ),
centerY - ( q * scale ), 4, 4 );
graphics.draw( ellipse );
mCounter -= mSamplesPerSymbol;
}
mCounter++;
}
}
public class TimingOffsetItem extends JSlider implements ChangeListener
{
private static final long serialVersionUID = 1L;
public TimingOffsetItem( int maxValue, int currentValue )
{
super( JSlider.HORIZONTAL, 0, maxValue, currentValue );
setMajorTickSpacing( 10 );
setMinorTickSpacing( 5 );
setPaintTicks( true );
setPaintLabels( true );
addChangeListener( this );
}
@Override
public void stateChanged( ChangeEvent event )
{
int value = ((JSlider)event.getSource()).getValue();
setOffset( (float)value / 10.0f );
}
}
}

View File

@@ -1,678 +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.control;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.LongConsumer;
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.AccessibleRole;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Duration;
/**
* Frequency display and tuning control that shows a frequency in MHz with six fractional digits (1 Hz).
*
* Mouse: hover over a digit to reveal its up/down halves. Click the upper half to increment the digit or the lower
* half to decrement it (hold the button to repeat), or use the scroll wheel over the digit. Steps carry into the
* higher digits and stop at the minimum/maximum frequency.
*
* Keyboard: left/right move the digit cursor, up/down (or +/-) step the digit under the cursor. Typing digits
* starts a calculator style entry (e.g. 851.0125) that is applied with Enter and cancelled with Escape. Shortcut-C
* and Shortcut-V copy and paste the frequency.
*
* The control only reports user requested frequencies to the listeners. {@link #setFrequency(long)} updates the
* display without notifying them, which is how the tuner reports its actual frequency back to the control.
*/
public class FrequencyControl extends HBox implements ISourceEventProcessor
{
private static final PseudoClass HOVER_UP = PseudoClass.getPseudoClass("hover-up");
private static final PseudoClass HOVER_DOWN = PseudoClass.getPseudoClass("hover-down");
private static final PseudoClass LEADING = PseudoClass.getPseudoClass("leading");
private static final PseudoClass CURSOR = PseudoClass.getPseudoClass("cursor");
private static final PseudoClass ENTRY = PseudoClass.getPseudoClass("entry");
private static final PseudoClass TYPED = PseudoClass.getPseudoClass("typed");
private static final PseudoClass INVALID = PseudoClass.getPseudoClass("invalid");
private static final Duration REPEAT_DELAY = Duration.millis(400);
private static final Duration REPEAT_INTERVAL = Duration.millis(70);
private final List<LongConsumer> mListeners = new CopyOnWriteArrayList<>();
private final Digit[] mDigits = new Digit[FrequencyEntry.DIGIT_COUNT];
private final FrequencyEntry.TypedEntry mTypedEntry = new FrequencyEntry.TypedEntry();
private final Text mProbe = new Text("0");
private final Label mUnitLabel = new Label("MHz");
private final Tooltip mTooltip = new Tooltip();
private final PauseTransition mInvalidFlash = new PauseTransition(Duration.millis(1200));
private final Timeline mRepeat = new Timeline();
private long mFrequency;
private long mMinimum = 1;
private long mMaximum = FrequencyEntry.MAXIMUM_DISPLAYABLE;
private int mCursorPosition = FrequencyEntry.FRACTION_DIGITS;
private double mScrollAccumulator;
/**
* Constructs an instance
*/
public FrequencyControl()
{
getStyleClass().add("frequency-control");
URL stylesheet = FrequencyControl.class.getResource("/frequency_control.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
setAlignment(Pos.CENTER_LEFT);
setFocusTraversable(true);
setAccessibleRole(AccessibleRole.SPINNER);
setMaxWidth(Region.USE_PREF_SIZE);
//Invisible probe text, styled like the digits, sizes every digit cell to the same width so that a
//proportional font doesn't make the display jitter as the digits change.
mProbe.getStyleClass().add("frequency-digit-text");
mProbe.setManaged(false);
mProbe.setVisible(false);
getChildren().add(mProbe);
for(int position = FrequencyEntry.DIGIT_COUNT - 1; position >= 0; position--)
{
Digit digit = new Digit(position);
mDigits[position] = digit;
getChildren().add(digit);
if(position == FrequencyEntry.FRACTION_DIGITS)
{
Text point = new Text(".");
point.getStyleClass().addAll("frequency-digit-text", "frequency-point");
getChildren().add(point);
}
else if(position % 3 == 0 && position > 0)
{
Region gap = new Region();
gap.getStyleClass().add("frequency-group-gap");
getChildren().add(gap);
}
}
mUnitLabel.getStyleClass().add("frequency-unit");
getChildren().add(mUnitLabel);
Tooltip.install(this, mTooltip);
updateTooltip();
mInvalidFlash.setOnFinished(e -> pseudoClassStateChanged(INVALID, false));
mRepeat.setCycleCount(Timeline.INDEFINITE);
addEventHandler(KeyEvent.KEY_PRESSED, this::keyPressed);
addEventHandler(KeyEvent.KEY_TYPED, this::keyTyped);
addEventHandler(MouseEvent.MOUSE_PRESSED, e -> requestFocus());
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
cancelEntry();
}
updateDigits();
});
disabledProperty().addListener((observable, wasDisabled, disabled) -> {
if(disabled)
{
stopRepeat();
cancelEntry();
}
});
setOnContextMenuRequested(e -> {
buildContextMenu().show(this, e.getScreenX(), e.getScreenY());
e.consume();
});
updateDigits();
}
/**
* Adds a listener to be notified of frequencies requested by the user. Listeners are invoked on the JavaFX
* application thread.
*/
public void addListener(LongConsumer listener)
{
if(listener != null && !mListeners.contains(listener))
{
mListeners.add(listener);
}
}
/**
* Removes the listener.
*/
public void removeListener(LongConsumer listener)
{
mListeners.remove(listener);
}
/**
* Removes all listeners.
*/
public void clearListeners()
{
mListeners.clear();
}
/**
* Current frequency in Hertz.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Sets the displayed frequency without notifying listeners. Safe to call from any thread.
* @param frequency in Hertz
*/
public void setFrequency(long frequency)
{
if(Platform.isFxApplicationThread())
{
mFrequency = Math.max(0, Math.min(FrequencyEntry.MAXIMUM_DISPLAYABLE, frequency));
updateDigits();
}
else
{
Platform.runLater(() -> setFrequency(frequency));
}
}
/**
* Sets the range of frequencies that the user can request.
* @param minimum frequency in Hertz
* @param maximum frequency in Hertz
*/
public void setRange(long minimum, long maximum)
{
mMinimum = Math.max(0, Math.min(minimum, maximum));
mMaximum = Math.min(FrequencyEntry.MAXIMUM_DISPLAYABLE, Math.max(minimum, maximum));
updateTooltip();
}
/**
* Minimum frequency that the user can request.
*/
public long getMinimum()
{
return mMinimum;
}
/**
* Maximum frequency that the user can request.
*/
public long getMaximum()
{
return mMaximum;
}
/**
* Receives tuner frequency change notifications and shows the new frequency. Requests are not re-broadcast.
*/
@Override
public void process(SourceEvent event)
{
if(event.getEvent() == SourceEvent.Event.NOTIFICATION_FREQUENCY_CHANGE && event.getValue() != null)
{
setFrequency(event.getValue().longValue());
}
}
/**
* Digit position under the keyboard cursor.
*/
public int getCursorPosition()
{
return mCursorPosition;
}
/**
* Steps the digit at the position and notifies listeners when the frequency changes.
* @param position of the digit (0 = 1 Hz)
* @param steps positive to increment, negative to decrement
*/
public void step(int position, int steps)
{
if(isDisabled() || steps == 0)
{
return;
}
cancelEntry();
long stepped = FrequencyEntry.step(mFrequency, position, steps, mMinimum, mMaximum);
request(stepped);
}
/**
* Requests the frequency on behalf of the user. An out of range frequency is rejected and flagged.
* @return true if the frequency was accepted.
*/
public boolean request(long frequency)
{
if(frequency < mMinimum || frequency > mMaximum)
{
flagInvalid();
return false;
}
if(frequency != mFrequency)
{
mFrequency = frequency;
updateDigits();
for(LongConsumer listener: mListeners)
{
listener.accept(frequency);
}
}
return true;
}
/**
* Indicates if a typed entry is in progress.
*/
public boolean isEntryActive()
{
return !mTypedEntry.isEmpty();
}
private void keyTyped(KeyEvent event)
{
if(isDisabled() || event.isShortcutDown() || event.isAltDown())
{
return;
}
String character = event.getCharacter();
if(character == null || character.length() != 1)
{
return;
}
char c = character.charAt(0);
if((c >= '0' && c <= '9') || c == '.' || c == ',')
{
mTypedEntry.type(c);
updateDigits();
event.consume();
}
else if(c == '+' || c == '=')
{
step(mCursorPosition, 1);
event.consume();
}
else if(c == '-')
{
step(mCursorPosition, -1);
event.consume();
}
}
private void keyPressed(KeyEvent event)
{
if(isDisabled())
{
return;
}
if(event.isShortcutDown())
{
if(event.getCode() == KeyCode.C)
{
copy();
event.consume();
}
else if(event.getCode() == KeyCode.V)
{
paste();
event.consume();
}
return;
}
switch(event.getCode())
{
case LEFT, KP_LEFT -> moveCursor(1);
case RIGHT, KP_RIGHT -> moveCursor(-1);
case HOME -> setCursorPosition(FrequencyEntry.DIGIT_COUNT - 1);
case END -> setCursorPosition(0);
case UP, KP_UP -> step(mCursorPosition, 1);
case DOWN, KP_DOWN -> step(mCursorPosition, -1);
case PAGE_UP -> step(mCursorPosition, 10);
case PAGE_DOWN -> step(mCursorPosition, -10);
case ENTER ->
{
if(!commitEntry())
{
return;
}
}
case ESCAPE ->
{
if(!isEntryActive())
{
return;
}
cancelEntry();
}
case BACK_SPACE ->
{
if(!isEntryActive())
{
return;
}
mTypedEntry.backspace();
updateDigits();
}
default ->
{
return;
}
}
event.consume();
}
/**
* Applies the typed entry.
* @return true if there was an entry to apply.
*/
private boolean commitEntry()
{
if(!isEntryActive())
{
return false;
}
long frequency = mTypedEntry.getFrequency();
mTypedEntry.clear();
if(!request(frequency))
{
updateDigits();
}
return true;
}
private void cancelEntry()
{
if(isEntryActive())
{
mTypedEntry.clear();
updateDigits();
}
}
private void moveCursor(int direction)
{
cancelEntry();
setCursorPosition(mCursorPosition + direction);
}
private void setCursorPosition(int position)
{
mCursorPosition = Math.max(0, Math.min(FrequencyEntry.DIGIT_COUNT - 1, position));
updateDigits();
}
private void copy()
{
ClipboardContent content = new ClipboardContent();
content.putString(FrequencyEntry.format(mFrequency));
Clipboard.getSystemClipboard().setContent(content);
}
private void paste()
{
Clipboard clipboard = Clipboard.getSystemClipboard();
if(clipboard.hasString())
{
Long frequency = FrequencyEntry.parse(clipboard.getString());
cancelEntry();
if(frequency != null)
{
request(frequency);
}
else
{
flagInvalid();
}
}
}
private ContextMenu buildContextMenu()
{
MenuItem copy = new MenuItem("Copy Frequency");
copy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
copy.setOnAction(e -> copy());
MenuItem paste = new MenuItem("Paste Frequency");
paste.setAccelerator(KeyCombination.keyCombination("Shortcut+V"));
paste.setDisable(isDisabled() || !Clipboard.getSystemClipboard().hasString());
paste.setOnAction(e -> paste());
MenuItem minimum = new MenuItem("Tune to Minimum (" + FrequencyEntry.format(mMinimum) + " MHz)");
minimum.setDisable(isDisabled());
minimum.setOnAction(e -> request(mMinimum));
MenuItem maximum = new MenuItem("Tune to Maximum (" + FrequencyEntry.format(mMaximum) + " MHz)");
maximum.setDisable(isDisabled());
maximum.setOnAction(e -> request(mMaximum));
return new ContextMenu(copy, paste, new SeparatorMenuItem(), minimum, maximum);
}
private void flagInvalid()
{
pseudoClassStateChanged(INVALID, true);
mInvalidFlash.playFromStart();
}
private void updateTooltip()
{
mTooltip.setText("Tuning range " + FrequencyEntry.format(mMinimum) + " - " +
FrequencyEntry.format(mMaximum) + " MHz\n\n" +
"Hover over a digit and use the scroll wheel, or click its upper or lower half, to step it.\n" +
"Or type a frequency in MHz (e.g. 851.0125) and press Enter. Escape cancels.\n" +
"Arrow keys move between digits and step the selected digit.");
}
/**
* Refreshes every digit's value and state.
*/
private void updateDigits()
{
boolean entry = isEntryActive();
long shown = entry ? mTypedEntry.getFrequency() : mFrequency;
boolean focused = isFocused();
pseudoClassStateChanged(ENTRY, entry);
for(Digit digit: mDigits)
{
int position = digit.getPosition();
digit.setValue(FrequencyEntry.getDigit(shown, position));
digit.pseudoClassStateChanged(LEADING, FrequencyEntry.isLeadingZero(shown, position));
digit.pseudoClassStateChanged(TYPED, entry && mTypedEntry.isTyped(position));
digit.pseudoClassStateChanged(CURSOR, focused && !entry && position == mCursorPosition);
}
setAccessibleText(FrequencyEntry.format(mFrequency) + " MHz");
}
private void stopRepeat()
{
mRepeat.stop();
mRepeat.getKeyFrames().clear();
}
/**
* A single digit with up and down halves.
*/
private class Digit extends VBox
{
private final int mPosition;
private final Text mText = new Text("0");
private final Region mUpHalf = new Region();
private final Region mDownHalf = new Region();
Digit(int position)
{
mPosition = position;
getStyleClass().add("frequency-digit");
setAlignment(Pos.CENTER);
Region upArrow = new Region();
upArrow.getStyleClass().addAll("frequency-arrow", "frequency-arrow-up");
Region downArrow = new Region();
downArrow.getStyleClass().addAll("frequency-arrow", "frequency-arrow-down");
mText.getStyleClass().add("frequency-digit-text");
mUpHalf.getStyleClass().addAll("frequency-half", "frequency-half-up");
mDownHalf.getStyleClass().addAll("frequency-half", "frequency-half-down");
StackPane cell = new StackPane(mUpHalf, mDownHalf, mText);
cell.getStyleClass().add("frequency-digit-cell");
StackPane.setAlignment(mUpHalf, Pos.TOP_CENTER);
StackPane.setAlignment(mDownHalf, Pos.BOTTOM_CENTER);
mUpHalf.maxHeightProperty().bind(cell.heightProperty().divide(2));
mDownHalf.maxHeightProperty().bind(cell.heightProperty().divide(2));
cell.minWidthProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getWidth() + 4));
cell.prefWidthProperty().bind(cell.minWidthProperty());
//Arrow size follows the digit font size, so it scales with the user's GUI scale
upArrow.prefWidthProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getWidth() * 0.6));
upArrow.prefHeightProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getHeight() * 0.18));
upArrow.maxWidthProperty().bind(upArrow.prefWidthProperty());
upArrow.maxHeightProperty().bind(upArrow.prefHeightProperty());
downArrow.prefWidthProperty().bind(upArrow.prefWidthProperty());
downArrow.prefHeightProperty().bind(upArrow.prefHeightProperty());
downArrow.maxWidthProperty().bind(upArrow.prefWidthProperty());
downArrow.maxHeightProperty().bind(upArrow.prefHeightProperty());
getChildren().addAll(upArrow, cell, downArrow);
addEventHandler(MouseEvent.MOUSE_MOVED, e -> setHalf(e.getY() < getHeight() / 2 ? 1 : -1));
addEventHandler(MouseEvent.MOUSE_ENTERED, e -> setHalf(e.getY() < getHeight() / 2 ? 1 : -1));
addEventHandler(MouseEvent.MOUSE_EXITED, e -> {
setHalf(0);
stopRepeat();
});
addEventHandler(MouseEvent.MOUSE_PRESSED, this::pressed);
addEventHandler(MouseEvent.MOUSE_RELEASED, e -> stopRepeat());
addEventHandler(ScrollEvent.SCROLL, this::scrolled);
}
int getPosition()
{
return mPosition;
}
void setValue(int value)
{
mText.setText(String.valueOf(value));
}
private void setHalf(int half)
{
pseudoClassStateChanged(HOVER_UP, half > 0);
pseudoClassStateChanged(HOVER_DOWN, half < 0);
}
private void pressed(MouseEvent event)
{
if(event.getButton() != MouseButton.PRIMARY || isDisabled())
{
return;
}
requestFocus();
mCursorPosition = mPosition;
int direction = event.getY() < getHeight() / 2 ? 1 : -1;
setHalf(direction);
step(mPosition, direction);
stopRepeat();
mRepeat.getKeyFrames().add(new KeyFrame(REPEAT_INTERVAL, e -> step(mPosition, direction)));
mRepeat.setDelay(REPEAT_DELAY);
mRepeat.playFromStart();
event.consume();
}
private void scrolled(ScrollEvent event)
{
if(isDisabled() || event.getDeltaY() == 0)
{
return;
}
//Accumulate so that high resolution (touchpad) scrolling steps once per wheel notch
double notch = event.getMultiplierY() > 1 ? event.getMultiplierY() : 40;
mScrollAccumulator += event.getDeltaY() / notch;
int steps = (int)mScrollAccumulator;
if(steps != 0)
{
mScrollAccumulator -= steps;
mCursorPosition = mPosition;
step(mPosition, steps);
}
event.consume();
}
}
}

View File

@@ -1,372 +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.control;
import java.math.BigDecimal;
/**
* Frequency arithmetic for the {@link FrequencyControl}, kept free of JavaFX so that it can be unit tested.
*
* The control shows a frequency in MHz as a fixed number of digits: {@link #INTEGER_DIGITS} MHz digits and
* {@link #FRACTION_DIGITS} fractional digits, so the least significant digit is 1 Hz. Digit positions are
* numbered by their power of ten in Hertz: position 0 is the 1 Hz digit and position 9 is the 1000 MHz digit.
*/
public final class FrequencyEntry
{
/**
* Number of MHz (integer) digits.
*/
public static final int INTEGER_DIGITS = 4;
/**
* Number of fractional MHz digits (precision to 1 Hz).
*/
public static final int FRACTION_DIGITS = 6;
/**
* Total number of displayed digits.
*/
public static final int DIGIT_COUNT = INTEGER_DIGITS + FRACTION_DIGITS;
/**
* Largest frequency that fits the display: 9999.999999 MHz.
*/
public static final long MAXIMUM_DISPLAYABLE = 9_999_999_999L;
private FrequencyEntry()
{
}
/**
* Value of the digit at the position.
* @param frequency in Hertz
* @param position power of ten (0 = 1 Hz)
* @return digit 0-9
*/
public static int getDigit(long frequency, int position)
{
return (int)((Math.abs(frequency) / pow10(position)) % 10);
}
/**
* Indicates if the digit at the position is a leading zero, which the control shows dimmed. The 1 MHz digit is
* never a leading zero.
*/
public static boolean isLeadingZero(long frequency, int position)
{
return position > FRACTION_DIGITS && Math.abs(frequency) < pow10(position);
}
/**
* Steps the frequency by a number of units of the digit position, carrying into the higher digits, and clamps
* the result to the range. A step that would leave the range lands on the range limit.
* @param frequency current value in Hertz
* @param position power of ten for the digit being stepped
* @param steps positive to increment, negative to decrement
* @param minimum allowed frequency
* @param maximum allowed frequency
* @return stepped and clamped frequency
*/
public static long step(long frequency, int position, int steps, long minimum, long maximum)
{
long stepped = frequency + (steps * pow10(position));
return clamp(stepped, minimum, maximum);
}
/**
* Replaces the digit at the position with a new value, without carry.
*/
public static long setDigit(long frequency, int position, int digit)
{
long unit = pow10(position);
int current = getDigit(frequency, position);
return frequency + ((long)(digit - current) * unit);
}
/**
* Clamps the frequency to the range.
*/
public static long clamp(long frequency, long minimum, long maximum)
{
return Math.max(minimum, Math.min(maximum, frequency));
}
/**
* Parses a typed or pasted frequency. A bare number is in MHz (e.g. 851.0125) unless it is too large to be MHz
* for the display, in which case it is read as Hertz (e.g. 851012500). An optional unit suffix of Hz, kHz, MHz
* or GHz (any case, with or without a space) overrides that. Thousands separators (comma, underscore or space)
* are ignored.
* @param text to parse
* @return frequency in Hertz, or null if the text isn't a frequency or has more precision than 1 Hz.
*/
public static Long parse(String text)
{
if(text == null)
{
return null;
}
String value = text.trim().toLowerCase().replace(",", "").replace("_", "").replace(" ", "");
if(value.isEmpty())
{
return null;
}
BigDecimal multiplier = null;
if(value.endsWith("ghz"))
{
multiplier = BigDecimal.valueOf(1_000_000_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("mhz"))
{
multiplier = BigDecimal.valueOf(1_000_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("khz"))
{
multiplier = BigDecimal.valueOf(1_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("hz"))
{
multiplier = BigDecimal.ONE;
value = value.substring(0, value.length() - 2);
}
BigDecimal number;
try
{
number = new BigDecimal(value);
}
catch(NumberFormatException nfe)
{
return null;
}
if(number.signum() < 0)
{
return null;
}
if(multiplier == null)
{
//A whole number too large to be MHz on the display is taken as Hertz
boolean whole = number.stripTrailingZeros().scale() <= 0;
multiplier = (whole && number.compareTo(BigDecimal.valueOf(10_000)) >= 0) ? BigDecimal.ONE :
BigDecimal.valueOf(1_000_000L);
}
BigDecimal hertz = number.multiply(multiplier).stripTrailingZeros();
if(hertz.scale() > 0)
{
return null;
}
try
{
return hertz.longValueExact();
}
catch(ArithmeticException ae)
{
return null;
}
}
/**
* Formats the frequency in MHz with all six fractional digits, e.g. 851.012500
*/
public static String format(long frequency)
{
return BigDecimal.valueOf(frequency, FRACTION_DIGITS).toPlainString();
}
/**
* Ten raised to the power.
*/
public static long pow10(int power)
{
long value = 1;
for(int x = 0; x < power; x++)
{
value *= 10;
}
return value;
}
/**
* Calculator style typed entry. Digits typed before the decimal point fill the MHz digits from the right and
* digits typed after it fill the fractional digits from the left, so typing 851.0125 shows 851.012500.
*/
public static class TypedEntry
{
private final StringBuilder mIntegerPart = new StringBuilder();
private final StringBuilder mFractionPart = new StringBuilder();
private boolean mDecimal = false;
/**
* Adds a typed character.
* @param c digit or decimal point
* @return true if the character was accepted
*/
public boolean type(char c)
{
if(c == '.' || c == ',')
{
if(mDecimal)
{
return false;
}
mDecimal = true;
return true;
}
if(c < '0' || c > '9')
{
return false;
}
if(mDecimal)
{
if(mFractionPart.length() >= FRACTION_DIGITS)
{
return false;
}
mFractionPart.append(c);
return true;
}
//Ignore leading zeros so they don't use up the MHz digits
if(mIntegerPart.isEmpty() && c == '0')
{
return true;
}
if(mIntegerPart.length() >= INTEGER_DIGITS)
{
return false;
}
mIntegerPart.append(c);
return true;
}
/**
* Removes the last typed character.
* @return true if there is still something typed after the removal.
*/
public boolean backspace()
{
if(!mFractionPart.isEmpty())
{
mFractionPart.setLength(mFractionPart.length() - 1);
}
else if(mDecimal)
{
mDecimal = false;
}
else if(!mIntegerPart.isEmpty())
{
mIntegerPart.setLength(mIntegerPart.length() - 1);
}
return !isEmpty();
}
/**
* Indicates if nothing has been typed.
*/
public boolean isEmpty()
{
return mIntegerPart.isEmpty() && mFractionPart.isEmpty() && !mDecimal;
}
/**
* Number of fractional digits typed so far.
*/
public int getFractionDigitsTyped()
{
return mFractionPart.length();
}
/**
* Indicates if the decimal point has been typed.
*/
public boolean hasDecimal()
{
return mDecimal;
}
/**
* Number of MHz digits typed so far.
*/
public int getIntegerDigitsTyped()
{
return mIntegerPart.length();
}
/**
* Frequency for what has been typed so far.
*/
public long getFrequency()
{
long mhz = mIntegerPart.isEmpty() ? 0 : Long.parseLong(mIntegerPart.toString());
long fraction = 0;
if(!mFractionPart.isEmpty())
{
fraction = Long.parseLong(mFractionPart.toString()) * pow10(FRACTION_DIGITS - mFractionPart.length());
}
return (mhz * 1_000_000L) + fraction;
}
/**
* Indicates if the digit at the position has been typed, as opposed to an implied trailing zero.
*/
public boolean isTyped(int position)
{
if(position >= FRACTION_DIGITS)
{
return position - FRACTION_DIGITS < mIntegerPart.length();
}
return (FRACTION_DIGITS - 1 - position) < mFractionPart.length();
}
/**
* Clears the typed entry.
*/
public void clear()
{
mIntegerPart.setLength(0);
mFractionPart.setLength(0);
mDecimal = false;
}
}
}

View File

@@ -1,111 +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.control;
import java.util.function.LongPredicate;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
/**
* Text field for a frequency in MHz (to 1 Hz). The value is committed when the user presses Enter or leaves the
* field. A commit handler can reject the new value, which restores the previous value. Escape reverts the text.
*/
public class FrequencyField extends TextField
{
private long mFrequency;
private LongPredicate mCommitHandler;
/**
* Constructs an instance
* @param frequency initial value in Hertz
*/
public FrequencyField(long frequency)
{
getStyleClass().add("frequency-field");
setPrefColumnCount(11);
setFrequency(frequency);
setOnAction(e -> commit());
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
commit();
}
});
setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ESCAPE)
{
setText(FrequencyEntry.format(mFrequency));
e.consume();
}
});
}
/**
* Sets the handler for committed values. The handler returns false to reject the value.
*/
public void setCommitHandler(LongPredicate handler)
{
mCommitHandler = handler;
}
/**
* Current frequency in Hertz.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Sets the frequency without invoking the commit handler.
*/
public void setFrequency(long frequency)
{
mFrequency = frequency;
setText(FrequencyEntry.format(frequency));
}
private void commit()
{
Long parsed = FrequencyEntry.parse(getText());
if(parsed == null)
{
setText(FrequencyEntry.format(mFrequency));
return;
}
if(parsed == mFrequency)
{
setText(FrequencyEntry.format(mFrequency));
return;
}
long previous = mFrequency;
mFrequency = parsed;
setText(FrequencyEntry.format(parsed));
if(mCommitHandler != null && !mCommitHandler.test(parsed))
{
setFrequency(previous);
}
}
}

View File

@@ -0,0 +1,195 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 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.control;
import java.awt.EventQueue;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
/**
* Swing text field control for entering frequency (MHz) values.
*/
public class FrequencyTextField extends JTextField
{
private static final Logger LOGGER = LoggerFactory.getLogger(FrequencyTextField.class);
//Value range: 0.000001 to 9999.999999
private static final String REGEX = "^[0-9]{0,4}[.]?[0-9]{0,6}$";
//This lets users start typing a really small number like 1 Hertz ... 0.00000
private static final String ZEROS_REGEX = "^0?([.]0{0,5})?$";
private double mMinimum;
private double mMaximum;
/**
* Constructs an instance
*
* @param minimum allowable frequency value in Hertz
* @param maximum allowable frequency value in Hertz
* @param current frequency value in Hertz
*/
public FrequencyTextField(long minimum, long maximum, long current)
{
super(8);
mMinimum = minimum / 1E6d;
mMaximum = maximum / 1E6d;
PlainDocument document = (PlainDocument)this.getDocument();
document.setDocumentFilter(new FrequencyFilter());
setFrequency(current);
}
/**
* Current frequency value
* @return frequency in Hertz
*/
public long getFrequency()
{
String value = getText();
if(value == null || value.isEmpty())
{
return 0;
}
try
{
return (long)(Double.parseDouble(getText()) * 1E6d);
}
catch(Exception e)
{
LOGGER.error("Unable to parse frequency value from text [" + value + "] " + e.getLocalizedMessage());
}
return 0;
}
/**
* Sets the current frequency value
* @param frequency in Hertz
*/
public void setFrequency(long frequency)
{
double frequencyMHz = frequency / 1E6d;
if(isValid(String.valueOf(frequencyMHz)))
{
setText(String.valueOf(frequencyMHz));
}
else
{
LOGGER.warn("Can't set frequency [" + frequency + "Hz / " + frequencyMHz + "MHz] with current minimum [" + mMinimum + "MHz] and maximum [" + mMaximum + "MHz] limits");
}
}
/**
* Indicates if the value is a valid double value that is between the minimum and maximum extents.
* @param value to test
* @return true if it is valid.
*/
private boolean isValid(String value)
{
if(value == null || value.isEmpty() || value.matches(ZEROS_REGEX))
{
return true;
}
if(value.matches(REGEX))
{
try
{
double frequency = Double.parseDouble(value);
return mMinimum <= frequency && frequency <= mMaximum;
}
catch(NumberFormatException e)
{
return false;
}
}
return false;
}
/**
* Input filter for user entered values.
*/
class FrequencyFilter extends DocumentFilter
{
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if(isValid(sb.toString()))
{
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if(isValid(sb.toString()))
{
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
if(isValid(sb.toString()))
{
super.remove(fb, offset, length);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Frequency Control Test");
frame.setSize(300, 200);
FrequencyTextField ftf = new FrequencyTextField(1, 9_999_999_999l, 101_100_000);
frame.setLayout(new MigLayout());
frame.add(ftf);
EventQueue.invokeLater(() -> frame.setVisible(true));
}
}

View File

@@ -0,0 +1,593 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 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.control;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.InvalidFrequencyException;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Custom frequency controller for displaying or editing frequency values in MHz.
*/
public class JFrequencyControl extends JPanel implements ISourceEventProcessor
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(JFrequencyControl.class);
private List<ISourceEventProcessor> mProcessors = new ArrayList<>();
private Color mHighlightColor = Color.YELLOW;
private long mFrequency;
private HashMap<Integer,Digit> mDigits = new HashMap<Integer,Digit>();
/**
* Constructor
*/
public JFrequencyControl()
{
init();
}
/**
* Initializes the control/layout.
*/
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[]0[]", ""));
Font font = new Font(Font.MONOSPACED, Font.BOLD, 30);
for(int x = 9; x >= 0; x--)
{
Digit digit = null;
try
{
digit = new Digit(x);
}
catch(ParseException e)
{
mLog.error("JFrequencyControl - parse exception constructing a digit - " + e);
}
if(digit != null)
{
mDigits.put(x, digit);
add(digit);
digit.setFont(font);
if(x == 6)
{
add(new JLabel(". "));
}
}
}
revalidate();
}
/**
* Enables or disables the control.
* @param enabled true if this component should be enabled, false otherwise
*/
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
for(Digit digit : mDigits.values())
{
digit.setEnabled(enabled);
}
}
/**
* Receives a frequency change event invoked by another control. We don't
* rebroadcast this event, just set the control to indicate the new frequency.
*/
@Override
public void process(SourceEvent event)
{
switch(event.getEvent())
{
case NOTIFICATION_FREQUENCY_CHANGE:
EventQueue.invokeLater(() -> setFrequency(event.getValue().longValue(), false));
break;
}
}
/**
* Loads the frequency into the display and optionally fires a change event
* to all registered listeners
*/
public void setFrequency(long frequency, boolean fireChangeEvent)
{
mFrequency = frequency;
for(Digit digit : mDigits.values())
{
digit.setFrequency(frequency, fireChangeEvent);
}
}
/**
* Current frequency value for the control.
* @return frequency
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Updates the frequency value according to the manually changed digit value.
*/
private void updateFrequency()
{
long frequency = 0;
for(Digit digit : mDigits.values())
{
frequency += digit.getFrequency();
}
mFrequency = frequency;
}
/**
* Fires a source changed event
* @throws SourceException of there's an error
*/
private void fireSourceChanged() throws SourceException
{
updateFrequency();
Iterator<ISourceEventProcessor> it = mProcessors.iterator();
SourceEvent event = SourceEvent.frequencyRequest(mFrequency);
while(it.hasNext())
{
it.next().process(event);
}
}
/**
* Adds the source event listener
* @param processor
*/
public void addListener(ISourceEventProcessor processor)
{
if(!mProcessors.contains(processor))
{
mProcessors.add(processor);
}
}
/**
* Remove all source event processors
*/
public void clearListeners()
{
mProcessors.clear();
}
/**
* Removes the source event processor
* @param processor
*/
public void removeListener(ISourceEventProcessor processor)
{
mProcessors.remove(processor);
}
/**
* Custom single digit value editor.
*/
public class Digit extends JTextField
{
private static final long serialVersionUID = 1L;
private int mPower = 0;
private long mValue = 0;
/**
* Constructor
* @param position of the digit where a position of 1 is the ones unit of MHz and a position of -1 is the tenths
* unit of MHz.
* @throws ParseException if there is an error
*/
private Digit(int position) throws ParseException
{
super("0");
setColumns(1);
mPower = position;
setToolTipText(getTooltip(mPower));
Listener listener = new Listener();
this.addKeyListener(listener);
this.addMouseListener(listener);
this.addMouseWheelListener(listener);
}
/**
* Generates a custom tooltip for the current hover-over digit.
* @param power of the digit in units of 10
* @return custom tooptip.
*/
private static String getTooltip(int power)
{
StringBuilder sb = new StringBuilder();
sb.append("Center frequency ");
switch(power)
{
case 0:
sb.append("1 Hertz");
break;
case 1:
sb.append("10 Hertz");
break;
case 2:
sb.append("100 Hertz");
break;
case 3:
sb.append("1 Kilohertz");
break;
case 4:
sb.append("10 Kilohertz");
break;
case 5:
sb.append("100 Kilohertz");
break;
case 6:
sb.append("1 Megahertz");
break;
case 7:
sb.append("10 Megahertz");
break;
case 8:
sb.append("100 Megahertz");
break;
case 9:
sb.append("1 Gigahertz");
break;
}
sb.append(" units. Type a number, use up/down arrows, or click the upper/lower digit control to adjust");
return sb.toString();
}
/**
* Sets this digit to the value of the column in frequency that corresponds
* to the power (ie column) set for this digit. Optionally, fires a
* value change event to all listeners.
*/
public void setFrequency(long frequency, boolean fireChangeEvent)
{
//Strip the digits higher than this one
long lower = frequency % (long)(FastMath.pow(10, mPower + 1));
//Set the value to int value of dividing by 10 to this power
long value = (long)(lower / (long)(FastMath.pow(10, mPower)));
set(value, fireChangeEvent);
}
/**
* Frequency value.
* @return frequency value.
*/
public long getFrequency()
{
return mValue * (long)FastMath.pow(10, mPower);
}
/**
* Increments the unit value and fires a change event
*/
public void increment()
{
increment(true);
}
/**
* Increments the unit value and fires a change event
* @param fireChangeEvent true to fire an event
*/
public void increment(boolean fireChangeEvent)
{
if(isEnabled())
{
set(mValue + 1, fireChangeEvent);
}
}
/**
* Decrements the unit value and fires a change event.
*/
public void decrement()
{
decrement(true);
}
/**
* Decrements the unit value and optionally fires a change event.
* @param fireChangeEvent set to true to fire an event
*/
public void decrement(boolean fireChangeEvent)
{
if(isEnabled())
{
set(mValue - 1, fireChangeEvent);
}
}
/**
* Convenience wrapper to change amount and fire change event
*/
private void set(long amount)
{
set(amount, true);
}
/**
* Changes the value and optionally fires change event to listeners
*/
private void set(long amount, boolean fireChangeEvent)
{
long previous = mValue;
boolean higherDigitIncremented = false;
boolean higherDigitDecremented = false;
mValue = amount;
while(mValue < 0)
{
mValue += 10;
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.decrement(false);
higherDigitDecremented = true;
}
}
while(mValue > 9)
{
mValue -= 10;
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.increment(false);
higherDigitIncremented = true;
}
}
if(fireChangeEvent)
{
try
{
fireSourceChanged();
}
catch(SourceException se)
{
mValue = previous;
if(higherDigitIncremented)
{
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.decrement(false);
}
}
if(higherDigitDecremented)
{
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.increment(false);
}
}
if(se instanceof InvalidFrequencyException ife)
{
JOptionPane.showMessageDialog(this, ife.getMessage() + " for this tuner.");
}
}
}
setText(String.valueOf(mValue));
repaint();
}
/**
* Multiple Listener interface implementation
*/
private class Listener implements KeyListener, MouseListener, MouseWheelListener
{
@Override
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
switch(key)
{
case KeyEvent.VK_0:
case KeyEvent.VK_NUMPAD0:
set(0);
Digit.this.transferFocus();
break;
case KeyEvent.VK_1:
case KeyEvent.VK_NUMPAD1:
set(1);
Digit.this.transferFocus();
break;
case KeyEvent.VK_2:
case KeyEvent.VK_NUMPAD2:
set(2);
Digit.this.transferFocus();
break;
case KeyEvent.VK_3:
case KeyEvent.VK_NUMPAD3:
set(3);
Digit.this.transferFocus();
break;
case KeyEvent.VK_4:
case KeyEvent.VK_NUMPAD4:
set(4);
Digit.this.transferFocus();
break;
case KeyEvent.VK_5:
case KeyEvent.VK_NUMPAD5:
set(5);
Digit.this.transferFocus();
break;
case KeyEvent.VK_6:
case KeyEvent.VK_NUMPAD6:
set(6);
Digit.this.transferFocus();
break;
case KeyEvent.VK_7:
case KeyEvent.VK_NUMPAD7:
set(7);
Digit.this.transferFocus();
break;
case KeyEvent.VK_8:
case KeyEvent.VK_NUMPAD8:
set(8);
Digit.this.transferFocus();
break;
case KeyEvent.VK_9:
case KeyEvent.VK_NUMPAD9:
set(9);
Digit.this.transferFocus();
break;
case KeyEvent.VK_LEFT:
Digit.this.transferFocusBackward();
break;
case KeyEvent.VK_RIGHT:
Digit.this.transferFocus();
break;
case KeyEvent.VK_UP:
increment();
break;
case KeyEvent.VK_DOWN:
decrement();
break;
case KeyEvent.VK_TAB:
break;
default:
set(mValue);
break;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void mouseClicked(MouseEvent e)
{
switch(e.getButton())
{
case MouseEvent.BUTTON1:
increment();
break;
case MouseEvent.BUTTON2:
break;
case MouseEvent.BUTTON3:
decrement();
break;
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e)
{
Color bg = UIManager.getColor("TextField.selectionBackground");
Color fg = UIManager.getColor("TextField.selectionForeground");
Digit.this.setBackground(bg != null ? bg : Color.YELLOW);
Digit.this.setForeground(fg != null ? fg : Color.BLACK);
repaint(); }
@Override
public void mouseExited(MouseEvent e)
{
Color bg = UIManager.getColor("TextField.background");
Color fg = UIManager.getColor("TextField.foreground");
Digit.this.setBackground(bg != null ? bg : Color.WHITE);
Digit.this.setForeground(fg != null ? fg : Color.BLACK);
repaint(); }
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
//Swing delivers mouse wheel events to disabled components, so check enabled state explicitly so that
//the wheel can't bypass the lock when the tuner is providing channels.
if(isEnabled())
{
set(mValue - e.getWheelRotation());
}
else if(getParent() != null)
{
//Pass the event up so that an enclosing scroll pane can still scroll while this control is locked
getParent().dispatchEvent(SwingUtilities.convertMouseEvent(Digit.this, e, getParent()));
}
}
}
}
}

View File

@@ -0,0 +1,148 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2017 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.editor;
import javax.swing.*;
/**
* Generic editor with change detection, save and reset functions.
*
* This editor supports hierarchical nesting of sub-component editors where changes are detected
* at the lowest editor in the tree and percolated up to the top-level editor for managing the
* configuration set as a whole.
*
* To configure this editor as a collective, register each parent editor as a saveRequestListener
* on each child editor. If no save request listener is registered, the editor will simply invoke
* save when a change is detected and the user opts to save the contents.
*
* The top-level editor can override the saveRequest() method to perform custom save operations
* and validation.
*/
public abstract class Editor<T> extends JPanel
{
private static final long serialVersionUID = 1L;
protected T mItem;
protected boolean mModified = false;
protected Editor<?> mSaveRequestListener;
public Editor()
{
}
/**
* Requests to save the contents of this editor.
*
* If a save request listener is registered, the listener is notified that a save is requested,
* otherwise the save is request is processed by the instance.
*
* This allows for a save event to be percolated up the hierarchical set of editors so that
* a top-level editor can invoke custom operations such as configuration validation.
*/
protected void saveRequest()
{
if(mSaveRequestListener != null)
{
mSaveRequestListener.saveRequest();
}
else
{
save();
}
}
/**
* Registers the editor to be notified when this editor contents have been saved.
*/
public void setSaveRequestListener(Editor<?> listener)
{
mSaveRequestListener = listener;
}
/**
* Sets the object to be edited. If the contents from the previous object have changed, this
* prompts the user to save these changes. A saveRequest() is issued and either this editor
* or the parent editor will respond to the save request and invoke the save() method.
*/
public void setItem(T item)
{
if(isModified())
{
int option = JOptionPane.showConfirmDialog(
Editor.this,
"This item has changed. Do you want to save these changes?",
"Save Changes?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.YES_OPTION)
{
saveRequest();
}
setModified(false);
}
mItem = item;
}
/**
* Current editing item
*/
public T getItem()
{
return mItem;
}
public boolean hasItem()
{
return mItem != null;
}
/**
* Sets the contents modified flag
*/
public void setModified(boolean modified)
{
mModified = modified;
}
/**
* Indicates if this editor contents have been modified
*/
public boolean isModified()
{
return mModified;
}
/**
* Save the contents of the editor
*/
public abstract void save();
/**
* Reset the contents of the editor without saving any changes
*/
public void reset()
{
mModified = false;
setItem(mItem);
}
}

View File

@@ -1,35 +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.map;
import javafx.scene.canvas.GraphicsContext;
/**
* Overlay drawn over the map tiles, in the order the layers were added to the {@link TileMapView}.
*/
public interface MapLayer
{
/**
* Draws the layer. Called on the JavaFX thread.
* @param gc of the map canvas, in screen pixels
* @param map for converting positions to screen pixels
*/
void draw(GraphicsContext gc, TileMapView map);
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More