Compare commits

..

1 Commits

Author SHA1 Message Date
denny
66c5727145 Initial Signal Hound tuner support. 2026-11-12 07:02:07 -05:00
614 changed files with 37829 additions and 64930 deletions

View File

@@ -14,9 +14,6 @@ jobs:
steps:
- uses: actions/checkout@v7
with:
# Full history and tags, so the build can describe the commit relative to the latest version tag
fetch-depth: 0
- name: Set up JDK 27
uses: actions/setup-java@v6
@@ -37,7 +34,7 @@ jobs:
- name: Create Build Info file
run: |
echo -e "ref: $GITHUB_REF \ncommit: $GITHUB_SHA\ndescribe: $(git describe --tags --match 'v[0-9]*' --dirty)\nbuild: $(date +"%Y-%m-%dT%H:%M:%SZ")" > build/image/build_info.txt
echo -e "ref: $GITHUB_REF \ncommit: $GITHUB_SHA\nbuild: $(date +"%Y-%m-%dT%H:%M:%SZ")" > build/image/build_info.txt
- name: Add build artifacts to nightly release
uses: softprops/action-gh-release@v3

View File

@@ -1,6 +1,6 @@
# Publishes a release when a version tag is pushed: v0.6.2 for a final release,
# or v0.6.2-beta-1 / v0.6.2-alpha-1 for a pre-release. The build derives the
# version from the tag (see build.gradle).
# Publishes a release when a version tag is pushed. The tag has to match
# projectVersion in gradle.properties with a leading 'v': v0.6.2 for a final
# release, or v0.6.2-beta-1 / v0.6.2-alpha-1 for a pre-release.
name: Release
on:
@@ -22,6 +22,15 @@ jobs:
# Full history and tags, to find the previous release tag for the release notes
fetch-depth: 0
- id: version
run: |
expected="v$(sed -n 's/^projectVersion=//p' gradle.properties | tr -d '[:space:]')"
if [ "$GITHUB_REF_NAME" != "$expected" ]; then
echo "::error::Tag $GITHUB_REF_NAME does not match projectVersion in gradle.properties ($expected)"
exit 1
fi
echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
# Release notes list the PRs since the previous version tag (never 'nightly'). A final release
# starts from the previous final release, so it covers every alpha and beta in between.
- id: previous
@@ -45,17 +54,6 @@ jobs:
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v6
# The version comes from 'git describe', which can pick a different tag when more than one
# version tag points at the same commit. Fail rather than publish zips with the wrong version.
- id: version
run: |
version="$(./gradlew -q printVersion --console=plain | tail -n 1)"
if [ "v$version" != "$GITHUB_REF_NAME" ]; then
echo "::error::Build version $version does not match tag $GITHUB_REF_NAME"
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
- name: Build and test
run: ./gradlew clean build --console=plain

View File

@@ -1,29 +1,35 @@
![Gradle Build](https://github.com/dsheirer/sdrtrunk/actions/workflows/gradle.yml/badge.svg)
![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg)
[![Latest Release](https://img.shields.io/github/v/release/DSheirer/sdrtrunk?label=release)](https://github.com/DSheirer/sdrtrunk/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/DSheirer/sdrtrunk/total)](https://github.com/DSheirer/sdrtrunk/releases)
[![License](https://img.shields.io/github/license/DSheirer/sdrtrunk)](LICENSE)
[![Discord](https://img.shields.io/badge/chat-on%20Discord-5865F2?logo=discord&logoColor=white)](https://discord.gg/HJQaKYE)
[![support-google_groups-blue](https://img.shields.io/badge/support-google_groups-blue)](https://groups.google.com/g/sdrtrunk)
# MacOS Tahoe 26.1 Users - Attention:
Changes to USB support in Tahoe version 26.x cause sdrtrunk to fail to launch. Do the following to install the latest libusb and create a symbolic link and then use the nightly build which includes an updated usb4java native library for Tahoe with ARM processor. There may still be issue(s) with MacOS accessing your USB SDR tuners.
```
brew install libusb --HEAD
cd /opt
sudo mkdir local
cd local
sudo mkdir lib
```
Next, find where brew installed the libusb library, for example: ```/opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib``` Note: the folder "HEAD-9ceaa52" is the version stamp for HEAD when you installed from it.
Finally, create a symbolic link from the installed library to the place where usb4java is expecting to find libusb (/opt/local/lib/libusb-1.0.0.dylib)
```
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
# sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
> ## 📖 [Read the sdrtrunk User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
> New to sdrtrunk? Start with the **[Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)** guide,
> then use the **[User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)** and
> **[How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)** to set up tuners, playlists, aliases and streaming.
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)
* [FAQ](https://github.com/DSheirer/sdrtrunk/wiki/FAQ)
* [User's Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk primary application window decoding a P25 trunked radio system](https://github.com/DSheirer/sdrtrunk/wiki/images/application_overview.png)
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
![sdrtrunk Application](https://github.com/DSheirer/sdrtrunk/wiki/images/sdrtrunk.png)
**Figure 1:** sdrtrunk Application Screenshot
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.
@@ -48,19 +54,17 @@ committed to the code base, so it's not really 'nightly' as much as it is 'curre
Releases are built and published automatically by the [Release](.github/workflows/release.yml) GitHub workflow
whenever a version tag is pushed to the repository.
The version is taken from the tag, so there is no version number to update in the code. Create and push a tag
with a leading `v`, following the naming convention described in `gradle.properties` (e.g. `v0.6.2-alpha-1`,
`v0.6.2-beta-1` or `v0.6.2`):
1. Update `projectVersion` in `gradle.properties` to the new version, following the naming convention described in
that file (e.g. `0.6.2-alpha-1`, `0.6.2-beta-1` or `0.6.2`).
2. Commit and push the change to `master`.
3. Create and push a tag that matches the version with a leading `v`:
```
git tag v0.6.2-beta-1
git push origin v0.6.2-beta-1
```
Builds made from an untagged commit get a version like `0.6.2-beta-1-14-g4626d567` (14 commits after the
`v0.6.2-beta-1` tag, at commit `4626d567`), with `-dirty` appended when there are uncommitted changes.
The workflow then:
* Verifies that the version the build derives from git matches the tag and fails if it does not.
* Verifies that the tag matches `projectVersion` in `gradle.properties` and fails if it does not.
* Builds and tests the code, then creates the release zips for Linux, Mac and Windows (x86-64 and aarch64).
* Creates a GitHub release titled `Version <version>` with auto-generated release notes (a "What's Changed" list of
the PRs merged since the previous version tag), and attaches the six zip

View File

@@ -52,44 +52,8 @@ plugins {
id 'org.beryx.runtime' version '2.0.1'
}
/**
* Version is derived from the most recent 'v<version>' git tag (e.g. v1.0.0-beta-1 -> 1.0.0-beta-1). Commits after
* the tag produce a version like 1.0.0-beta-1-14-g4626d567 and uncommitted changes append '-dirty'. The moving
* 'nightly' tag is ignored. Override with -PprojectVersion=<version> (the nightly build uses 'nightly' so that the
* nightly release asset names stay the same). Falls back to 'unknown' when built outside a git checkout.
*/
String gitDescribe = describeGitVersion()
version = project.findProperty('projectVersion') ?: (gitDescribe ? gitDescribe.substring(1) : 'unknown')
String describeGitVersion()
{
try
{
def describe = providers.exec {
commandLine 'git', 'describe', '--tags', '--match', 'v[0-9]*', '--dirty'
ignoreExitValue = true
}
if(describe.result.get().exitValue == 0)
{
return describe.standardOutput.asText.get().trim()
}
}
catch(Exception e)
{
logger.warn("Unable to determine version from git tags: " + e.message)
}
return null
}
tasks.register('printVersion') {
description = 'Prints the project version'
def projectVersion = version
doLast {
println projectVersion
}
}
//Version is defined in gradle.properties so that we can CLI override it for nightly builds.
version = project.findProperty('projectVersion')
//Java 27 is required for this version of the Project Panama preview/incubator feature
java {
@@ -138,34 +102,38 @@ dependencies {
//Jitpack imports
implementation 'com.github.dnault:libresample4j:master'
implementation 'com.github.DSheirer.jmbe:api:v2.1.1'
implementation 'com.github.nwaldispuehl:java-lame:v3.98.4'
//mavenCentral/jcenter imports
implementation 'ch.qos.logback:logback-classic: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.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-javafx:1.0.0'
implementation 'com.github.jiconfont:jiconfont-swing:1.0.1'
implementation('com.github.wendykierp:JTransforms:3.2') {
exclude group: 'junit' //JLargeArrays 1.7 declares junit as a compile dependency
}
implementation 'com.google.code.gson:gson:2.15.0'
implementation 'com.google.guava:guava:33.8.0-jre'
implementation 'com.h2database:h2:2.5.252' //Built-in call database
implementation 'com.zaxxer:HikariCP:7.1.0' //Database connection pool
implementation 'com.jidesoft:jide-oss:3.6.18'
implementation 'com.miglayout:miglayout-swing:11.5.2'
implementation 'com.mpatric:mp3agic:0.9.1'
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: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: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: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:jrtl:1.4.0.3' //RTL-SDR tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jsdrplay:3.15.3' //SDRplay RSP tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:radio-reference-api:18.1.0' //RadioReference SOAP API - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jsignalhound:2026.10.05' //Signal Hound tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:radio-reference-api:18.0.0'
implementation 'org.apache.commons:commons-compress:1.28.0' //Not used directly - overrides the vulnerable 1.21 version from jarchivelib
implementation 'org.apache.commons:commons-lang3:3.21.0'
implementation 'org.apache.commons:commons-math3:3.6.1'
@@ -173,8 +141,6 @@ dependencies {
implementation 'org.apache.mina:mina-core:2.2.10'
implementation 'org.apache.mina:mina-http:2.2.10'
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.slf4j:slf4j-api:2.0.20'
}
@@ -194,6 +160,7 @@ tasks.withType(JavaCompile).configureEach {
*/
def jvmArgsWindows =
['--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
'--enable-preview', //Project Panama Vector API is still in incubator
'--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls
@@ -211,14 +178,6 @@ def jvmArgsLinux =
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
/**
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
*/
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
application {
mainClass = "io.github.dsheirer.gui.SDRTrunk"
@@ -230,16 +189,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 {
if(os.isWindows()) {
jvmArgs = jvmArgsWindows
@@ -254,7 +203,6 @@ jar {
attributes (
'Implementation-Title' : 'sdrtrunk project',
'Implementation-Version' : archiveVersion,
'Git-Describe' : gitDescribe ?: 'unknown',
'Created-By' : "Gradle ${gradle.gradleVersion}",
'Build-Timestamp' : new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date()),
'Build-JDK' : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']}",
@@ -304,8 +252,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
* @return configured task.
*/
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
//Use the correct set of JVM arguments
rt.extension.launcherData.get().jvmArgs = jvmArgs
//Additional modules to include with auto-detected modules.
//jdk.charsets - NXDN BIG5 encoding support
@@ -313,11 +261,9 @@ def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//jdk.incubator.vector - needed for Project Panama foreign function and vector apis
//jdk.accessibility is used with assistive technologies like screen readers
//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.desktop, java.logging, java.net.http, java.prefs, javafx.controls - required by sdrtrunk (jdeps)
//java.base, java.logging, java.net.http, java.prefs, javafx.controls, javafx.swing - required by sdrtrunk (jdeps)
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.naming', 'java.security.jgss', 'jdk.net')
'java.base', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'javafx.swing')
//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
@@ -406,22 +352,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.
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse

View File

@@ -17,16 +17,15 @@
# *****************************************************************************
#
# The project version is no longer defined here. It is derived from the most recent 'v<version>' git tag (see
# build.gradle) and can be overridden with -PprojectVersion=<version>.
# Version naming conventions:
# Alpha: maj.min.patch-alpha-build
# Beta: maj.min.patch-beta-build
# Release: maj.min.patch
#
# Version tag naming conventions:
# Alpha: vmaj.min.patch-alpha-build
# Beta: vmaj.min.patch-beta-build
# Release: vmaj.min.patch
# Example: 0.6.0-beta-5
#
# Example: v0.6.0-beta-5
#
# Note: this is so that the file names for the resultant release build products match the GitHub release asset
# Note: this is so that the file names for the resultant release build products match the GitLab release asset
# tag name, specifically the dashes inserted before and after the alpha/beta labels.
# See: https://github.com/DSheirer/sdrtrunk/issues/1651
projectVersion=1.0.0-beta-1

View File

@@ -1,2 +0,0 @@
[tools]
java = "liberica-javafx-27"

View File

@@ -75,6 +75,15 @@ dependencyResolutionManagement {
content { includeModule 'io.github.dsheirer', 'jsdrplay' }
}
//jSignalHound is published as a GitHub release. The jar does not contain the Signal Hound API native libraries,
//which users install separately from the Signal Hound SDK
ivy {
url = 'https://github.com/DSheirer/jSignalHound/releases/download'
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'jsignalhound' }
}
//jBladeRF is published as a GitHub release, with the native libraries for all platforms in the jar
ivy {
url = 'https://github.com/DSheirer/jBladeRF/releases/download'
@@ -82,23 +91,5 @@ dependencyResolutionManagement {
metadataSources { artifact() }
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)
//are not pulled in transitively and are declared directly in build.gradle
ivy {
url = 'https://github.com/DSheirer/radio-reference-api/releases/download'
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'radio-reference-api' }
}
}
}

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();
}
/**
* 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)
{
if(alias != null)
@@ -698,26 +670,11 @@ public class AliasList
//Attempt to do a fully qualified identifier match only
if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti)
{
return getAlias(fqti.getValue(), 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);
return mFullyQualifiedTalkgroupAliasMap.get(fqti.getFullyQualifiedTalkgroupAddress());
}
//Attempt to match the talkgroup value
int value = identifier.getValue();
Alias mapValue = mTalkgroupAliasMap.get(value);
if (mapValue != null)
@@ -833,26 +790,11 @@ public class AliasList
//Match fully qualified identifier only.
if(identifier instanceof FullyQualifiedRadioIdentifier fqri)
{
return getAlias(fqri.getValue(), 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);
return mFullyQualifiedRadioAliasMap.get(fqri.getFullyQualifiedRadioAddress());
}
//Attempt to match against the radio identifier
int value = identifier.getValue();
Alias mapValue = mRadioAliasMap.get(value);
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<String> mAliasListNames = FXCollections.observableArrayList();
private Map<String,AliasList> mAliasListMap = new HashMap<>();
private ObservableList<AliasListConfiguration> mAliasListConfigurations =
FXCollections.observableArrayList(AliasListConfiguration.extractor());
public AliasModel()
{
@@ -65,99 +63,6 @@ public class AliasModel
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.
*/
@@ -174,15 +79,6 @@ public class AliasModel
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;
}
mAliases.stream().filter(alias -> oldName.equals(alias.getAliasListName())).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);
}
}
mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName));
}
/**
@@ -228,7 +109,6 @@ public class AliasModel
mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
mAliasListMap.remove(aliasListName);
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
}
/**
@@ -266,7 +146,6 @@ public class AliasModel
removeAlias(alias);
}
mAliasListConfigurations.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;
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.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.message.IMessage;
import io.github.dsheirer.util.ThreadPool;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -64,28 +62,23 @@ public abstract class RecurringAction extends AliasAction
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
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);
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
};
if(FxToolkit.isStarted())
{
//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();
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
});
}
else
{
dismissed.run();
}
break;
default:
}

View File

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

View File

@@ -38,7 +38,6 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
@@ -68,8 +67,6 @@ import org.slf4j.LoggerFactory;
public class AudioSegment implements Listener<IdentifierUpdateNotification>
{
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 mDuplicate = new SimpleBooleanProperty(false);
private BooleanProperty mEncrypted = new SimpleBooleanProperty(false);
@@ -99,15 +96,6 @@ public class AudioSegment implements Listener<IdentifierUpdateNotification>
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
*/

View File

@@ -25,7 +25,6 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyCallConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration;
import io.github.dsheirer.audio.broadcast.thinline.ThinlineRadioConfiguration;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzConfiguration;
import io.github.dsheirer.audio.broadcast.icecast.IcecastConfiguration;
import io.github.dsheirer.audio.broadcast.shoutcast.v1.ShoutcastV1Configuration;
@@ -50,7 +49,6 @@ import java.net.SocketAddress;
@JsonSubTypes({
@JsonSubTypes.Type(value = BroadcastifyCallConfiguration.class, name="broadcastifyCallConfiguration"),
@JsonSubTypes.Type(value = RdioScannerConfiguration.class, name="RdioScannerConfiguration"),
@JsonSubTypes.Type(value = ThinlineRadioConfiguration.class, name="ThinlineRadioConfiguration"),
@JsonSubTypes.Type(value = OpenMHzConfiguration.class, name="OpenMHzConfiguration"),
@JsonSubTypes.Type(value = IcecastConfiguration.class, name="icecastConfiguration"),
@JsonSubTypes.Type(value = ShoutcastV1Configuration.class, name="shoutcastV1Configuration"),

View File

@@ -24,7 +24,6 @@ import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyCallConfigura
import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyFeedConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerBroadcaster;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration;
import io.github.dsheirer.audio.broadcast.thinline.ThinlineRadioConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerFeedConfiguration;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzBroadcaster;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzConfiguration;
@@ -69,7 +68,6 @@ public class BroadcastFactory
return new BroadcastifyCallBroadcaster((BroadcastifyCallConfiguration)configuration,
inputAudioFormat, mp3Setting, aliasModel);
case RDIOSCANNER_CALL:
case THINLINE_RADIO:
return new RdioScannerBroadcaster((RdioScannerConfiguration)configuration,
inputAudioFormat, mp3Setting, aliasModel);
case OPENMHZ:
@@ -115,8 +113,6 @@ public class BroadcastFactory
return new BroadcastifyCallConfiguration(format);
case RDIOSCANNER_CALL:
return new RdioScannerConfiguration(format);
case THINLINE_RADIO:
return new ThinlineRadioConfiguration(format);
case BROADCASTIFY:
return new BroadcastifyFeedConfiguration(format);
case OPENMHZ:

View File

@@ -46,8 +46,9 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
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);
@@ -56,6 +57,18 @@ public class BroadcastModel implements Listener<AudioRecording>
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 =
FXCollections.observableArrayList(ConfiguredBroadcast.extractor());
private List<AudioRecording> mRecordingQueue = new CopyOnWriteArrayList<>();
@@ -158,6 +171,8 @@ public class BroadcastModel implements Listener<AudioRecording>
{
configuredBroadcast = new ConfiguredBroadcast(configuration);
mConfiguredBroadcasts.add(configuredBroadcast);
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
fireTableRowsInserted(index, index);
process(new BroadcastEvent(configuration, BroadcastEvent.Event.CONFIGURATION_ADD));
return configuredBroadcast;
}
@@ -259,6 +274,8 @@ public class BroadcastModel implements Listener<AudioRecording>
if(configuredBroadcast != null)
{
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
mConfiguredBroadcasts.remove(configuredBroadcast);
if(configuredBroadcast.hasAudioBroadcaster())
@@ -269,6 +286,8 @@ public class BroadcastModel implements Listener<AudioRecording>
}
process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE));
fireTableRowsDeleted(index, index);
}
}
@@ -335,6 +354,13 @@ public class BroadcastModel implements Listener<AudioRecording>
audioBroadcaster.setListener(mBroadcastEventListener);
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));
ThreadPool.CACHED.submit(() -> audioBroadcaster.start());
}
@@ -357,6 +383,13 @@ public class BroadcastModel implements Listener<AudioRecording>
broadcaster.removeListener();
broadcaster.dispose();
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE));
}
}
@@ -465,17 +498,186 @@ public class BroadcastModel implements Listener<AudioRecording>
ThreadPool.SCHEDULED.schedule(new DelayedBroadcasterStartup(broadcastConfiguration),
1, TimeUnit.SECONDS);
}
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
fireTableRowsUpdated(index, index);
break;
case CONFIGURATION_DELETE:
deleteBroadcaster(getConfiguredBroadcast(broadcastEvent.getBroadcastConfiguration()));
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
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.
*

View File

@@ -32,7 +32,6 @@ public enum BroadcastServerType
ICECAST_HTTP("Icecast 2 (v2.4+)", "images/icecast.png"),
RDIOSCANNER_CALL("Rdio Scanner", "images/rdioscanner.png"),
THINLINE_RADIO("Thinline Radio", "images/rdioscanner.png"),
OPENMHZ("OpenMHz", "images/openmhz.png"),
ICECAST_TCP("Icecast (v2.3)", "images/icecast.png"),
SHOUTCAST_V1("Shoutcast v1.x", "images/shoutcast.png"),

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;
}
/**
* 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.
*/

View File

@@ -113,8 +113,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
}
else
{
mLog.error("Error connecting to " + getBroadcastConfiguration().getServiceName() +
" server on startup [" + response + "]");
mLog.error("Error connecting to Rdio Scanner server on startup [" + response + "]");
setBroadcastState(BroadcastState.ERROR);
}
@@ -250,8 +249,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
}
catch(IOException e)
{
mLog.error(getBroadcastConfiguration().getServiceName() +
" API - audio recording file not found - ignoring upload");
mLog.error("Rdio Scanner API - audio recording file not found - ignoring upload");
}
if(audioBytes != null)
@@ -288,14 +286,14 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
//We get socket reset exceptions occasionally when the remote server doesn't
//fully read our request and immediately responds.
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
mLog.error("Rdio Scanner API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
else
{
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
mLog.error("Rdio Scanner API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
@@ -323,7 +321,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else
{
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
mLog.error("Rdio Scanner API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
@@ -336,7 +334,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else
{
//Register an error for the file not found exception
mLog.error(getBroadcastConfiguration().getServiceName() + " API - upload file not found [" +
mLog.error("Rdio Scanner API - upload file not found [" +
audioRecording.getPath().toString() + "]");
incrementErrorAudioCount();
broadcast(new BroadcastEvent(RdioScannerBroadcaster.this,

View File

@@ -19,7 +19,6 @@
package io.github.dsheirer.audio.broadcast.rdioscanner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.audio.broadcast.BroadcastConfiguration;
import io.github.dsheirer.audio.broadcast.BroadcastFormat;
@@ -126,15 +125,6 @@ public class RdioScannerConfiguration extends BroadcastConfiguration
return BroadcastServerType.RDIOSCANNER_CALL;
}
/**
* Product name written to connection and upload logs.
*/
@JsonIgnore
public String getServiceName()
{
return "Rdio Scanner";
}
@Override
public BroadcastConfiguration copyOf()
{

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.audio.broadcast.thinline;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.audio.broadcast.BroadcastConfiguration;
import io.github.dsheirer.audio.broadcast.BroadcastFormat;
import io.github.dsheirer.audio.broadcast.BroadcastServerType;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration;
/**
* Call upload configuration for Thinline Radio.
*
* Thinline Radio accepts the same completed-call upload used by Rdio Scanner, including the system id, API key,
* and /api/call-upload path.
*/
public class ThinlineRadioConfiguration extends RdioScannerConfiguration
{
/**
* Constructor for Jackson
*/
public ThinlineRadioConfiguration()
{
this(BroadcastFormat.MP3);
}
/**
* Public constructor.
* @param format to use for audio recording (MP3)
*/
public ThinlineRadioConfiguration(BroadcastFormat format)
{
super(format);
}
@JacksonXmlProperty(isAttribute = true, localName = "type", namespace = "http://www.w3.org/2001/XMLSchema-instance")
@Override
public BroadcastServerType getBroadcastServerType()
{
return BroadcastServerType.THINLINE_RADIO;
}
@JsonIgnore
@Override
public String getServiceName()
{
return "Thinline Radio";
}
@Override
public BroadcastConfiguration copyOf()
{
ThinlineRadioConfiguration copy = new ThinlineRadioConfiguration();
copy.setSystemID(getSystemID());
return copy;
}
}

View File

@@ -41,11 +41,11 @@ public abstract class AmbeAudioModule extends JmbeAudioModule
{
if(getAudioCodec() != null)
{
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio can be processed");
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio will be available");
}
else
{
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be processed");
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be available");
}
sLibraryStatusLogged = true;

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
* 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.Collections;
import java.util.List;
import jmbe.frame.ICorrectedFrame;
import jmbe.iface.IAudioCodec;
import jmbe.iface.IAudioCodecLibrary;
import jmbe.iface.IAudioCodecLibraryV2;
import jmbe.iface.IAudioCodecLibraryV3;
import jmbe.iface.IAudioCodecV2;
import jmbe.iface.IAudioCodecV3;
import jmbe.iface.IAudioWithMetadata;
import org.slf4j.Logger;
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 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 IAudioCodec mAudioCodec;
private final UserPreferences mUserPreferences;
@@ -139,56 +128,6 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
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
public Listener<IMessage> getMessageListener()
{
@@ -238,26 +177,27 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
URLClassLoader childClassLoader = new URLClassLoader(new URL[]{path.toUri().toURL()},
this.getClass().getClassLoader());
for(String className: JMBE_LIBRARY_CLASS_NAMES)
try
{
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibraryV2", true, childClassLoader);
}
catch(ClassNotFoundException legacyLibrary)
{
try
{
sLoadedJmbeAudioConverterClass = Class.forName(className, true, childClassLoader);
break;
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibrary", true, childClassLoader);
}
catch(ClassNotFoundException notFound)
catch(ClassNotFoundException missingLibrary)
{
//Library doesn't contain this version of the library class - try the next older version
}
}
if(sLoadedJmbeAudioConverterClass == null && !mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
if(!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");
"] - neither V2 nor V1 library class was found");
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
}
}
}
}
catch(IllegalArgumentException iae)
{
if(!mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY + getCodecName()))
@@ -289,18 +229,9 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
if((library.getMajorVersion() == 1 && library.getMinorVersion() >= 0 &&
library.getBuildVersion() >= 0) || library.getMajorVersion() >= 1)
{
if(library instanceof IAudioCodecLibraryV3 libraryV3)
{
audioConverter = libraryV3.getAudioConverterV3(getCodecName());
}
else if(library instanceof IAudioCodecLibraryV2 libraryV2)
{
audioConverter = libraryV2.getAudioConverterV2(getCodecName());
}
else
{
audioConverter = library.getAudioConverter(getCodecName());
}
audioConverter = library instanceof IAudioCodecLibraryV2 libraryV2 ?
libraryV2.getAudioConverterV2(getCodecName()) :
library.getAudioConverter(getCodecName());
String codecStatusKey = JMBE_AUDIO_LIBRARY + ":codec:" + getCodecName();
if(!mLibraryLoadStatusLogged.contains(codecStatusKey))

View File

@@ -36,7 +36,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import jmbe.frame.CorrectedIMBEFrame;
import jmbe.iface.IAudioCodec;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
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())
{
byte[] frameBytes = voiceFrame.getFrameBytes();
//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);
float[] audio = codec.getAudio(frameBytes);
audioModule.addAudio(audio);
}

View File

@@ -97,35 +97,17 @@ public class MP3AudioConverter implements IAudioConverter
audioPackets = mResampler.resample(audioPackets);
}
for(float[] audioPacket: audioPackets)
for(int x = 0; x < audioPackets.size(); x++)
{
encodePacket(audioPacket, converted);
}
int finalChunkSize = mEncoder.encodeFinish(mOutputFramesBuffer);
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;
byte[] bytesToEncode = null;
if(mInputAudioFormat.getAudioFormat().getSampleSizeInBits() == 16)
{
bytesToEncode = ConversionUtils.convertToSigned16BitSamples(audioPacket).array();
bytesToEncode = ConversionUtils.convertToSigned16BitSamples(audioPackets.get(x)).array();
}
else
{
bytesToEncode = ConversionUtils.convertToSigned32BitSamples(audioPacket).array();
bytesToEncode = ConversionUtils.convertToSigned32BitSamples(audioPackets.get(x)).array();
}
int bytesToEncodePointer = 0;
@@ -153,61 +135,6 @@ public class MP3AudioConverter implements IAudioConverter
}
}
/**
* 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);
}
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);
}
}
int finalChunkSize = mEncoder.encodeFinish(mOutputFramesBuffer);
if(finalChunkSize > 0)

View File

@@ -31,7 +31,6 @@ import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import java.util.Arrays;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
@@ -59,19 +58,13 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>();
private final UserPreferences mUserPreferences;
private final String mChannelName;
private final AtomicInteger mPeakLevelBits = new AtomicInteger();
private volatile AudioSegment mCurrentAudioSegment;
private AudioSegment mCurrentAudioSegment;
private Listener<IdentifierCollection> mIdentifierCollectionListener;
private boolean mDropDuplicates;
private boolean mMetadataSent = false;
private boolean mMuted;
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[] mAudioSegmentDropTone;
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.
*/
@@ -268,7 +153,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
public boolean hasAudioSegment()
{
return mCurrentAudioSegment != null || mReplay != null;
return mCurrentAudioSegment != null;
}
/**
@@ -289,73 +174,18 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
public float[] getAudio()
{
float[] audio = getNextAudio();
if(audio != null)
if(mAudioBuffer.isFull())
{
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())
{
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;
}
}
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)
@@ -419,54 +249,10 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
audio = mAudioBuffer.flush();
}
return audio;
}
/**
* 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()
//Finally, if we have buffer audio and we're muted, return silence
if(isMuted() && audio != null)
{
ReplaySource pending = mPendingReplay;
if(pending != null)
{
mPendingReplay = null;
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);
audio = new float[SAMPLES_PER_INTERVAL];
}
return audio;
@@ -512,20 +298,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
private boolean isThrowaway(AudioSegment audioSegment)
{
if(audioSegment == null)
{
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());
return audioSegment != null && (audioSegment.isDoNotMonitor() || mDropDuplicates && (audioSegment.isDuplicate()));
}
/**
@@ -571,18 +344,9 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
{
MyEventBus.getGlobalEventBus().unregister(this);
ReplaySource replay = mReplay;
if(replay != null)
{
replay.stop();
}
disposeCurrentAudioSegment();
mAudioEventBroadcaster.clear();
mIdentifierCollectionListener = null;
mHoldListener = null;
mPlaybackListener = null;
}
/**
@@ -693,7 +457,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
mCurrentAudioSegment.decrementConsumerCount();
mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this);
mCurrentAudioSegment = null;
notifyPlayback();
}
}
@@ -731,7 +494,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
if(audioSegment != null)
{
notifyPlayback();
mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this);
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 final AudioSegmentPrioritySorter mAudioSegmentPrioritySorter = new AudioSegmentPrioritySorter();
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> mPendingAudioSegments = new ArrayList<>();
private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>();
@@ -62,8 +61,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
private AudioPlaybackDeviceDescriptor mAudioPlaybackDevice;
private AudioOutput mAudioOutput;
private ScheduledFuture<?> mProcessingTask;
private final TalkgroupHold[] mHolds = new TalkgroupHold[2];
private final long[] mHoldActivity = new long[2];
/**
* Constructs an instance.
@@ -117,8 +114,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
*/
private void processAudioSegments()
{
updateHoldActivity();
//Process new audio segments queue. If segment has audio, queue it for replay, otherwise place in pending queue
AudioSegment newSegment = mNewAudioSegmentQueue.poll();
@@ -187,8 +182,7 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
{
audioSegment = it.next();
if((audioSegment.isDoNotMonitor() && getHoldingChannelIndex(audioSegment) < 0) ||
(audioSegment.isDuplicate() &&
if(audioSegment.isDoNotMonitor() || (audioSegment.isDuplicate() &&
mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled()))
{
it.remove();
@@ -239,7 +233,20 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
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
{
@@ -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,
* 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
//the descriptor that was actually used by the audio output
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
{

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.IdentifierRecord;
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(IdentifierRecord 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

@@ -57,11 +57,10 @@ public class ByteNativeBuffer extends AbstractNativeBuffer
public ByteNativeBuffer(byte[] samples, long timestamp, float averageDc, float samplesPerMillisecond)
{
super(timestamp, samplesPerMillisecond);
//Ensure we're an even multiple of the fragment size in bytes (2 bytes per I/Q sample). Typically, this
//will be 64k or 128k
if(samples.length % (FRAGMENT_SIZE * 2) != 0)
//Ensure we're an even multiple of the fragment size. Typically, this will be 64k or 128k
if(samples.length % FRAGMENT_SIZE != 0)
{
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + (FRAGMENT_SIZE * 2));
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + FRAGMENT_SIZE);
}
mSamples = samples;

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.
*/
public 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.
*/
public 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.RowHandle 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

@@ -0,0 +1,137 @@
/*******************************************************************************
* 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.channel.details;
import io.github.dsheirer.channel.state.DecoderState;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.sample.Listener;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChannelDetailPanel extends JPanel implements Listener<ProcessingChain>
{
private static final String EMPTY_DETAILS = "Please select a channel to view details";
private JLabel mSystemLabel;
private JLabel mSiteLabel;
private JLabel mNameLabel;
private JTextArea mDetailTextPane;
private ChannelProcessingManager mChannelProcessingManager;
private ProcessingChain mProcessingChain;
public ChannelDetailPanel(ChannelProcessingManager channelProcessingManager)
{
mChannelProcessingManager = channelProcessingManager;
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[]0[grow,fill]"));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new MigLayout("insets 1 1 1 1", "[][grow,fill][][grow,fill][][grow,fill][]", ""));
buttonPanel.add(new JLabel("System:"));
mSystemLabel = new JLabel(" ");
buttonPanel.add(mSystemLabel);
buttonPanel.add(new JLabel("Site:"));
mSiteLabel = new JLabel(" ");
buttonPanel.add(mSiteLabel);
buttonPanel.add(new JLabel("Channel Name:"));
mNameLabel = new JLabel(" ");
buttonPanel.add(mNameLabel);
JButton refreshButton = new JButton("Refresh");
refreshButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
receive(mProcessingChain);
}
});
buttonPanel.add(refreshButton);
add(buttonPanel, "wrap");
mDetailTextPane = new JTextArea(EMPTY_DETAILS);
DefaultCaret caret = (DefaultCaret)mDetailTextPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
add(new JScrollPane(mDetailTextPane));
}
@Override
public void receive(ProcessingChain processingChain)
{
mProcessingChain = processingChain;
Channel channel = mChannelProcessingManager.getChannel(processingChain);
final String system = channel != null ? channel.getSystem() : null;
final String site = channel != null ? channel.getSite() : null;
final String name = channel != null ?
(channel.getChannelType() == Channel.ChannelType.TRAFFIC ? "Traffic Channel" : channel.getName()) : null;
final String details;
if(processingChain != null)
{
StringBuilder sb = new StringBuilder();
for(DecoderState decoderState : processingChain.getDecoderStates())
{
sb.append(decoderState.getActivitySummary());
}
details = sb.toString();
}
else
{
details = EMPTY_DETAILS;
}
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
mSystemLabel.setText(system);
mSiteLabel.setText(site);
mNameLabel.setText(name);
mDetailTextPane.setText(details);
}
});
}
}

View File

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

View File

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

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
* it under the terms of the GNU General Public License as published by
@@ -18,73 +18,67 @@
*/
package io.github.dsheirer.channel.metadata;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.decoder.DecoderLogicalChannelNameIdentifier;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.sample.Listener;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Model of the channel metadata for the currently processing channels, with a map from each channel metadata to the
* channel that it belongs to. The model is thread-safe and isn't tied to a user interface toolkit: listeners are
* notified on the thread that changes the model and pass the changes to their user interface thread.
*/
public class ChannelMetadataModel implements IChannelMetadataUpdateListener
import javax.swing.table.AbstractTableModel;
public class ChannelMetadataModel extends AbstractTableModel implements IChannelMetadataUpdateListener
{
private final List<ChannelMetadata> mChannelMetadata = new ArrayList<>();
private final Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap<>();
private final List<Listener> mListeners = new CopyOnWriteArrayList<>();
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadataModel.class);
/**
* Listener for changes to the channel metadata model. Notifications arrive on the thread that changed the
* model, sometimes while the model is locked, so implementations must not block and must not call back into
* the model from the notification thread.
*/
public interface Listener
{
/**
* Channel metadata(s) for a channel were added to the model.
*/
void added(ChannelAndMetadata channelAndMetadata);
public static final int COLUMN_DECODER_STATE = 0;
public static final int COLUMN_DECODER_TYPE = 1;
public static final int COLUMN_USER_FROM = 2;
public static final int COLUMN_USER_FROM_ALIAS = 3;
public static final int COLUMN_USER_TO = 4;
public static final int COLUMN_USER_TO_ALIAS = 5;
public static final int COLUMN_DECODER_LOGICAL_CHANNEL_NAME = 6;
public static final int COLUMN_CONFIGURATION_FREQUENCY = 7;
public static final int COLUMN_CONFIGURATION_CHANNEL = 8;
/**
* Channel metadata was removed from the model.
*/
void removed(ChannelMetadata channelMetadata);
private static final String[] COLUMNS = {"Status", "Decoder", "From", "Alias", "To", "Alias", "Channel", "Frequency", "Channel Name"};
/**
* A field of a channel metadata in the model was updated.
*/
void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField);
}
private List<ChannelMetadata> mChannelMetadata = new ArrayList();
private Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap();
private Listener<ChannelAndMetadata> mChannelAddListener;
/**
* Constructs an instance
*/
public ChannelMetadataModel()
{
MyEventBus.getGlobalEventBus().register(this);
}
/**
* Registers the listener to receive model change notifications.
* @param listener to register
* @return the channel metadata in the model when the listener is registered, so that the listener starts from
* the current state and receives the changes that follow.
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
*/
public synchronized List<ChannelMetadata> addListener(Listener listener)
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
mListeners.add(listener);
return new ArrayList<>(mChannelMetadata);
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
EventQueue.invokeLater(() -> {
for(int row = 0; row < mChannelMetadata.size(); row++)
{
fireTableCellUpdated(row, COLUMN_USER_FROM);
fireTableCellUpdated(row, COLUMN_USER_TO);
}
});
}
/**
* Removes the listener from receiving model change notifications.
*/
public void removeListener(Listener listener)
{
mListeners.remove(listener);
}
/**
@@ -93,16 +87,10 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
*/
public String getDiagnosticInformation()
{
Map<ChannelMetadata,Channel> mapCopy;
List<ChannelMetadata> metadataCopy;
synchronized(this)
{
mapCopy = new HashMap<>(mMetadataChannelMap);
metadataCopy = new ArrayList<>(mChannelMetadata);
}
StringBuilder sb = new StringBuilder();
Map<ChannelMetadata,Channel> mapCopy = new HashMap<>(mMetadataChannelMap);
List<ChannelMetadata> metadataCopy = new ArrayList<>(mChannelMetadata);
sb.append("Channel Metadata Model Diagnostics\n");
for(ChannelMetadata channelMetadata: metadataCopy)
@@ -134,34 +122,51 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
return sb.toString();
}
/**
* Prepares the model for disposal.
*/
public void dispose()
{
mListeners.clear();
MyEventBus.getGlobalEventBus().unregister(this);
}
/**
* Adds the channel metadata(s) for a channel to the model.
* Lookup model row for the specified channel metadata
*/
public synchronized void add(ChannelAndMetadata channelAndMetadata)
public int getRow(ChannelMetadata channelMetadata)
{
if(mChannelMetadata.contains(channelMetadata))
{
return mChannelMetadata.indexOf(channelMetadata);
}
return -1;
}
/**
* Registers the listener to be notified when channel metadata(s) are added to the model.
* @param listener to receive channel associated with the channel metadata(s) that were added
*/
public void setChannelAddListener(Listener<ChannelAndMetadata> listener)
{
mChannelAddListener = listener;
}
public void add(ChannelAndMetadata channelAndMetadata)
{
//Execute on the swing thread to avoid threading issues
EventQueue.invokeLater(() -> {
for(ChannelMetadata channelMetadata: channelAndMetadata.getChannelMetadata())
{
if(!mChannelMetadata.contains(channelMetadata))
{
mChannelMetadata.add(channelMetadata);
}
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
channelMetadata.setUpdateEventListener(this);
int index = mChannelMetadata.indexOf(channelMetadata);
fireTableRowsInserted(index, index);
channelMetadata.setUpdateEventListener(ChannelMetadataModel.this);
}
for(Listener listener: mListeners)
if(mChannelAddListener != null)
{
listener.added(channelAndMetadata);
mChannelAddListener.receive(channelAndMetadata);
}
});
}
/**
@@ -169,7 +174,7 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
* @param channelMetadatas
* @param channel
*/
public synchronized void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
public void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
{
for(ChannelMetadata channelMetadata: channelMetadatas)
{
@@ -177,46 +182,178 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
}
}
/**
* Removes the channel metadata from the model.
*/
public synchronized void remove(ChannelMetadata channelMetadata)
public void remove(ChannelMetadata channelMetadata)
{
//Execute on the swing thread to avoid threading issues
EventQueue.invokeLater(() -> {
channelMetadata.removeUpdateEventListener();
int index = mChannelMetadata.indexOf(channelMetadata);
mChannelMetadata.remove(channelMetadata);
mMetadataChannelMap.remove(channelMetadata);
if(mChannelMetadata.remove(channelMetadata))
if(index >= 0)
{
for(Listener listener: mListeners)
{
listener.removed(channelMetadata);
}
fireTableRowsDeleted(index, index);
}
});
}
/**
* Current channel metadata in the model.
* @return copy of the channel metadata list.
* Get the channel metadata at the specified model row index
*/
public synchronized List<ChannelMetadata> getChannelMetadata()
public ChannelMetadata getChannelMetadata(int row)
{
return new ArrayList<>(mChannelMetadata);
if(row < mChannelMetadata.size())
{
return mChannelMetadata.get(row);
}
return null;
}
/**
* Returns the channel that matches the metadata or null
*/
public synchronized Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
public Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
{
return mMetadataChannelMap.get(channelMetadata);
}
@Override
public int getRowCount()
{
return mChannelMetadata.size();
}
@Override
public int getColumnCount()
{
return COLUMNS.length;
}
@Override
public String getColumnName(int column)
{
return COLUMNS[column];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch(columnIndex)
{
case COLUMN_USER_FROM:
case COLUMN_USER_TO:
return ChannelMetadata.class;
case COLUMN_USER_FROM_ALIAS:
case COLUMN_USER_TO_ALIAS:
return Alias.class;
case COLUMN_DECODER_LOGICAL_CHANNEL_NAME:
return String.class;
default:
return Identifier.class;
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if(rowIndex <= mChannelMetadata.size())
{
ChannelMetadata channelMetadata = mChannelMetadata.get(rowIndex);
switch(columnIndex)
{
case COLUMN_DECODER_STATE:
return channelMetadata.getChannelStateIdentifier();
case COLUMN_DECODER_TYPE:
return channelMetadata.getDecoderTypeConfigurationIdentifier();
case COLUMN_DECODER_LOGICAL_CHANNEL_NAME:
DecoderLogicalChannelNameIdentifier id = channelMetadata.getDecoderLogicalChannelNameIdentifier();
if(channelMetadata.hasTimeslot())
{
if(id == null)
{
return "TS:" + channelMetadata.getTimeslot();
}
else
{
String value = id.getValue().replace(" TS1", "")
.replace(" TS2", "");
return value + " TS:" + channelMetadata.getTimeslot();
}
}
else
{
if(id == null)
{
return null;
}
else
{
return id.getValue();
}
}
case COLUMN_CONFIGURATION_FREQUENCY:
return channelMetadata.getFrequencyConfigurationIdentifier();
case COLUMN_CONFIGURATION_CHANNEL:
return channelMetadata.getChannelNameConfigurationIdentifier();
case COLUMN_USER_TO:
return channelMetadata;
case COLUMN_USER_FROM:
return channelMetadata;
case COLUMN_USER_FROM_ALIAS:
return channelMetadata.getFromIdentifierAliases();
case COLUMN_USER_TO_ALIAS:
return channelMetadata.getToIdentifierAliases();
}
}
return null;
}
@Override
public void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField)
{
for(Listener listener: mListeners)
final int rowIndex = mChannelMetadata.indexOf(channelMetadata);
if(rowIndex >= 0)
{
listener.updated(channelMetadata, channelMetadataField);
//Execute on the swing thread to avoid threading issues
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
switch(channelMetadataField)
{
case CONFIGURATION_CHANNEL:
fireTableCellUpdated(rowIndex, COLUMN_CONFIGURATION_CHANNEL);
break;
case CONFIGURATION_FREQUENCY:
fireTableCellUpdated(rowIndex, COLUMN_CONFIGURATION_FREQUENCY);
break;
case DECODER_CHANNEL_NAME:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_LOGICAL_CHANNEL_NAME);
break;
case DECODER_TYPE:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_TYPE);
break;
case DECODER_STATE:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_STATE);
break;
case USER_FROM:
fireTableCellUpdated(rowIndex, COLUMN_USER_FROM);
fireTableCellUpdated(rowIndex, COLUMN_USER_FROM_ALIAS);
break;
case USER_TO:
fireTableCellUpdated(rowIndex, COLUMN_USER_TO);
fireTableCellUpdated(rowIndex, COLUMN_USER_TO_ALIAS);
break;
}
}
});
}
}
}

View File

@@ -0,0 +1,494 @@
/*
* *****************************************************************************
* 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.channel.metadata;
import com.google.common.base.Joiner;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.channel.state.State;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelModel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.channel.ViewChannelRequest;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.configuration.FrequencyConfigurationIdentifier;
import io.github.dsheirer.identifier.decoder.ChannelStateIdentifier;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
public class ChannelMetadataPanel extends JPanel implements ListSelectionListener
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadataPanel.class);
private static final String TABLE_PREFERENCE_KEY = "channel.metadata.panel";
private ChannelModel mChannelModel;
private ChannelProcessingManager mChannelProcessingManager;
private IconModel mIconModel;
private UserPreferences mUserPreferences;
private JTable mTable;
private Broadcaster<ProcessingChain> mSelectedProcessingChainBroadcaster = new Broadcaster<>();
private Map<State,Color> mBackgroundColors = new EnumMap<>(State.class);
private Map<State,Color> mForegroundColors = new EnumMap<>(State.class);
private JTableColumnWidthMonitor mTableColumnMonitor;
private Channel mUserSelectedChannel;
/**
* Table view for currently decoding channel metadata
*/
public ChannelMetadataPanel(PlaylistManager playlistManager, IconModel iconModel, UserPreferences userPreferences)
{
mChannelModel = playlistManager.getChannelModel();
mChannelProcessingManager = playlistManager.getChannelProcessingManager();
mIconModel = iconModel;
mUserPreferences = userPreferences;
init();
}
/**
* Initializes the panel
*/
private void init()
{
setLayout( new MigLayout( "insets 0 0 0 0", "[grow,fill]", "[grow,fill]") );
mTable = new JTable(mChannelProcessingManager.getChannelMetadataModel());
mChannelProcessingManager.getChannelMetadataModel().setChannelAddListener(new ChannelAddListener());
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)mTable.getDefaultRenderer(String.class);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
mTable.getSelectionModel().addListSelectionListener(this);
mTable.addMouseListener(new MouseSupport());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_DECODER_STATE)
.setCellRenderer(new ColoredStateCellRenderer());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_FROM)
.setCellRenderer(new FromCellRenderer(mUserPreferences.getTalkgroupFormatPreference()));
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_TO)
.setCellRenderer(new ToCellRenderer(mUserPreferences.getTalkgroupFormatPreference()));
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_FROM_ALIAS)
.setCellRenderer(new AliasCellRenderer());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_TO_ALIAS)
.setCellRenderer(new AliasCellRenderer());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_CONFIGURATION_FREQUENCY)
.setCellRenderer(new FrequencyCellRenderer());
//Add a table column width monitor to store/restore column widths
mTableColumnMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTable, TABLE_PREFERENCE_KEY);
JScrollPane scrollPane = new JScrollPane(mTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrollPane);
setColors();
}
/**
* Setup the background and foreground color palette for the various channel states.
*/
private void setColors()
{
mBackgroundColors.put(State.ACTIVE, Color.CYAN);
mForegroundColors.put(State.ACTIVE, Color.BLUE);
mBackgroundColors.put(State.CALL, Color.BLUE);
mForegroundColors.put(State.CALL, Color.YELLOW);
mBackgroundColors.put(State.CONTROL, Color.ORANGE);
mForegroundColors.put(State.CONTROL, Color.BLUE);
mBackgroundColors.put(State.DATA, Color.GREEN);
mForegroundColors.put(State.DATA, Color.BLUE);
mBackgroundColors.put(State.ENCRYPTED, Color.MAGENTA);
mForegroundColors.put(State.ENCRYPTED, Color.WHITE);
mBackgroundColors.put(State.FADE, Color.LIGHT_GRAY);
mForegroundColors.put(State.FADE, Color.DARK_GRAY);
mBackgroundColors.put(State.IDLE, Color.WHITE);
mForegroundColors.put(State.IDLE, Color.DARK_GRAY);
mBackgroundColors.put(State.RESET, Color.PINK);
mForegroundColors.put(State.RESET, Color.YELLOW);
mBackgroundColors.put(State.TEARDOWN, Color.DARK_GRAY);
mForegroundColors.put(State.TEARDOWN, Color.WHITE);
}
@Override
public void valueChanged(ListSelectionEvent e)
{
if(!mTable.getSelectionModel().getValueIsAdjusting())
{
ProcessingChain processingChain = null;
int selectedViewRow = mTable.getSelectedRow();
if(selectedViewRow >= 0)
{
int selectedModelRow = mTable.convertRowIndexToModel(selectedViewRow);
ChannelMetadata selectedMetadata = mChannelProcessingManager.getChannelMetadataModel()
.getChannelMetadata(selectedModelRow);
if(selectedMetadata != null)
{
mUserSelectedChannel = mChannelProcessingManager.getChannelMetadataModel()
.getChannelFromMetadata(selectedMetadata);
processingChain = mChannelProcessingManager.getProcessingChain(mUserSelectedChannel);
}
}
mSelectedProcessingChainBroadcaster.broadcast(processingChain);
}
}
/**
* Adds the listener to receive the processing chain associated with the metadata selected in the
* metadata table.
*/
public void addProcessingChainSelectionListener(Listener<ProcessingChain> listener)
{
mSelectedProcessingChainBroadcaster.addListener(listener);
}
/**
* Cell renderer for frequency values
*/
public class FrequencyCellRenderer extends DefaultTableCellRenderer
{
private final DecimalFormat FREQUENCY_FORMATTER = new DecimalFormat( "#.00000" );
public FrequencyCellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof FrequencyConfigurationIdentifier)
{
long frequency = ((FrequencyConfigurationIdentifier)value).getValue();
label.setText(FREQUENCY_FORMATTER.format(frequency / 1e6d));
}
else
{
label.setText(null);
}
return label;
}
}
/**
* Alias cell renderer
*/
public class AliasCellRenderer extends DefaultTableCellRenderer
{
public AliasCellRenderer()
{
setHorizontalAlignment(JLabel.LEFT);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof List<?>)
{
List<Alias> aliases = (List<Alias>)value;
if(!aliases.isEmpty())
{
label.setText(Joiner.on(", ").skipNulls().join(aliases));
label.setIcon(mIconModel.getIcon(aliases.get(0).getIconName(), IconModel.DEFAULT_ICON_SIZE));
label.setForeground(ThemeManager.getInstance().getReadableColor(aliases.get(0).getDisplayColor(),
label.getBackground()));
}
else
{
label.setText(null);
label.setIcon(null);
label.setForeground(table.getForeground());
}
}
else
{
label.setText(null);
label.setIcon(null);
label.setForeground(table.getForeground());
}
return label;
}
}
/**
* Abstract cell renderer for identifiers
*/
public abstract class IdentifierCellRenderer extends DefaultTableCellRenderer
{
private final static String EMPTY_VALUE = "-----";
private TalkgroupFormatPreference mTalkgroupFormatPreference;
public IdentifierCellRenderer(TalkgroupFormatPreference talkgroupFormatPreference)
{
mTalkgroupFormatPreference = talkgroupFormatPreference;
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof ChannelMetadata)
{
ChannelMetadata channelMetadata = (ChannelMetadata)value;
Identifier identifier = getIdentifier(channelMetadata);
String text = mTalkgroupFormatPreference.format(identifier);
if(text == null || text.isEmpty())
{
text = EMPTY_VALUE;
}
else if(hasAdditionalIdentifier(channelMetadata))
{
text = text + " " + getAdditionalIdentifier(channelMetadata);
}
label.setText(text);
}
else
{
label.setText(EMPTY_VALUE);
}
return label;
}
public abstract Identifier getIdentifier(ChannelMetadata channelMetadata);
public abstract boolean hasAdditionalIdentifier(ChannelMetadata channelMetadata);
public abstract Identifier getAdditionalIdentifier(ChannelMetadata channelMetadata);
}
/**
* Cell renderer for the FROM identifier
*/
public class FromCellRenderer extends IdentifierCellRenderer
{
public FromCellRenderer(TalkgroupFormatPreference talkgroupFormatPreference)
{
super(talkgroupFormatPreference);
}
@Override
public Identifier getIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.getFromIdentifier();
}
@Override
public Identifier getAdditionalIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.getTalkerAliasIdentifier();
}
@Override
public boolean hasAdditionalIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.hasTalkerAliasIdentifier();
}
}
/**
* Cell renderer for the TO identifier
*/
public class ToCellRenderer extends IdentifierCellRenderer
{
public ToCellRenderer(TalkgroupFormatPreference talkgroupFormatPreference)
{
super(talkgroupFormatPreference);
}
@Override
public Identifier getIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.getToIdentifier();
}
@Override
public Identifier getAdditionalIdentifier(ChannelMetadata channelMetadata) {return null;}
@Override
public boolean hasAdditionalIdentifier(ChannelMetadata channelMetadata) {return false;}
}
public class ColoredStateCellRenderer extends DefaultTableCellRenderer
{
public ColoredStateCellRenderer()
{
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Color background = table.getBackground();
Color foreground = table.getForeground();
if(value instanceof ChannelStateIdentifier)
{
State state = ((ChannelStateIdentifier)value).getValue();
label.setText(state.getDisplayValue());
if(mBackgroundColors.containsKey(state))
{
background = mBackgroundColors.get(state);
}
if(mForegroundColors.containsKey(state))
{
foreground = mForegroundColors.get(state);
}
}
else
{
setText("----");
}
setBackground(background);
setForeground(foreground);
return label;
}
}
public class MouseSupport extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent e)
{
if(e.getButton() == MouseEvent.BUTTON3) //Right click for context
{
JPopupMenu popupMenu = new JPopupMenu();
boolean populated = false;
int viewRowIndex = mTable.rowAtPoint(e.getPoint());
if(viewRowIndex >= 0)
{
int modelRowIndex = mTable.convertRowIndexToModel(viewRowIndex);
if(modelRowIndex >= 0)
{
ChannelMetadata metadata = mChannelProcessingManager.getChannelMetadataModel().getChannelMetadata(modelRowIndex);
if(metadata != null)
{
Channel channel = mChannelProcessingManager.getChannelMetadataModel()
.getChannelFromMetadata(metadata);
if(channel != null)
{
JMenuItem viewChannel = new JMenuItem("View/Edit: " + channel.getShortTitle());
viewChannel.addActionListener(e2 -> MyEventBus.getGlobalEventBus().post(new ViewChannelRequest(channel)));
popupMenu.add(viewChannel);
populated = true;
}
}
}
}
if(!populated)
{
popupMenu.add(new JMenuItem("No Actions Available"));
}
popupMenu.show(mTable, e.getX(), e.getY());
}
}
}
/**
* Listener to be notified when a channel and associated channel metadata(s) are added to the underlying
* channel metadata model.
*
* When a channel is added, it is compared the the last user selected channel and if they are the same, it
* invokes a selection event on the channel metadata row so that the channel metadata is re-selected. This is
* primarily a hack to counter-act the DMR Capacity+ REST channel rotation where a channel is converted to a
* traffic channel and the previous channel is restarted. The UI effect is that the user selected channel row
* in the Now Playing window continually loses selection over the channel and causes the user to perpetually
* chase the channel row.
*/
public class ChannelAddListener implements Listener<ChannelAndMetadata>
{
@Override
public void receive(ChannelAndMetadata channelAndMetadata)
{
if(mUserSelectedChannel != null &&
mUserSelectedChannel.getChannelID() == channelAndMetadata.getChannel().getChannelID())
{
List<ChannelMetadata> metadata = channelAndMetadata.getChannelMetadata();
if(metadata.size() > 0)
{
int modelRow = mChannelProcessingManager.getChannelMetadataModel().getRow(metadata.get(0));
if(modelRow >= 0)
{
int tableRow = mTable.convertRowIndexToView(modelRow);
mTable.getSelectionModel().setSelectionInterval(tableRow, tableRow);
}
}
}
}
}
}

View File

@@ -0,0 +1,138 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 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.channel.metadata;
import com.jidesoft.swing.JideSplitPane;
import com.jidesoft.swing.JideTabbedPane;
import io.github.dsheirer.channel.details.ChannelDetailPanel;
import io.github.dsheirer.gui.channel.ChannelSpectrumPanel;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.module.decode.event.DecodeEventPanel;
import io.github.dsheirer.module.decode.event.MessageActivityPanel;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.settings.SettingsManager;
import net.miginfocom.swing.MigLayout;
import javax.swing.JPanel;
/**
* Swing panel for Now Playing channels table and channel details tab set.
*/
public class NowPlayingPanel extends JPanel
{
private final ChannelMetadataPanel mChannelMetadataPanel;
private final ChannelDetailPanel mChannelDetailPanel;
private final DecodeEventPanel mDecodeEventPanel;
private final MessageActivityPanel mMessageActivityPanel;
private final ChannelSpectrumPanel mChannelSpectrumSquelchPanel;
private JideTabbedPane mTabbedPane;
private JideSplitPane mSplitPane;
private boolean mDetailTabsVisible;
/**
* GUI panel that combines the currently decoding channels metadata table and viewers for channel details,
* messages, events, and spectral view.
*/
public NowPlayingPanel(PlaylistManager playlistManager, IconModel iconModel, UserPreferences userPreferences,
SettingsManager settingsManager, boolean detailTabsVisible)
{
mChannelDetailPanel = new ChannelDetailPanel(playlistManager.getChannelProcessingManager());
mDecodeEventPanel = new DecodeEventPanel(iconModel, userPreferences, playlistManager.getAliasModel());
mMessageActivityPanel = new MessageActivityPanel(userPreferences);
mChannelMetadataPanel = new ChannelMetadataPanel(playlistManager, iconModel, userPreferences);
mChannelSpectrumSquelchPanel = new ChannelSpectrumPanel(playlistManager, settingsManager);
mDetailTabsVisible = detailTabsVisible;
init();
}
/**
* Change the visibility of the channel details tabs panel.
* @param visible true to show or false to hide.
*/
public void setDetailTabsVisible(boolean visible)
{
//Only adjust if there is a change in state
if(visible ^ mDetailTabsVisible)
{
mDetailTabsVisible = visible;
if(mDetailTabsVisible)
{
getSplitPane().add(getTabbedPane());
}
else
{
getSplitPane().remove(getTabbedPane());
}
revalidate();
}
}
private JideTabbedPane getTabbedPane()
{
if(mTabbedPane == null)
{
mTabbedPane = new JideTabbedPane();
mTabbedPane.addTab("Details", mChannelDetailPanel);
mTabbedPane.addTab("Events", mDecodeEventPanel);
mTabbedPane.addTab("Messages", mMessageActivityPanel);
mTabbedPane.addTab("Channel", mChannelSpectrumSquelchPanel);
mTabbedPane.setFont(this.getFont());
//Register state change listener to toggle visibility state for channel tab to turn-on/off FFT processing
mTabbedPane.addChangeListener(e -> mChannelSpectrumSquelchPanel.setPanelVisible(getTabbedPane().getSelectedIndex() == getTabbedPane()
.indexOfComponent(mChannelSpectrumSquelchPanel)));
}
return mTabbedPane;
}
/**
* Split pane for channels table and channel details tabs.
*/
private JideSplitPane getSplitPane()
{
if(mSplitPane == null)
{
mSplitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT);
mSplitPane.setShowGripper(true);
}
return mSplitPane;
}
private void init()
{
setLayout( new MigLayout( "insets 0 0 0 0", "[grow,fill]", "[grow,fill]") );
getSplitPane().add(mChannelMetadataPanel);
if(mDetailTabsVisible)
{
getSplitPane().add(getTabbedPane());
}
add(getSplitPane());
mChannelMetadataPanel.addProcessingChainSelectionListener(mChannelDetailPanel);
mChannelMetadataPanel.addProcessingChainSelectionListener(mDecodeEventPanel);
mChannelMetadataPanel.addProcessingChainSelectionListener(mMessageActivityPanel);
mChannelMetadataPanel.addProcessingChainSelectionListener(mChannelSpectrumSquelchPanel);
}
}

View File

@@ -0,0 +1,117 @@
/*
* *****************************************************************************
* 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.channel.metadata.NowPlayingPanel;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.icon.IconModel;
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, settingsManager, detailTabsVisible);
mMapPanel = new MapPanel(mapService, playlistManager.getAliasModel(), iconModel, settingsManager);
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;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
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 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 boolean mSelected;
private List<TunerChannel> mTunerChannels = null;
@@ -126,19 +123,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
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
*/
@@ -150,7 +134,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
channel.setAliasListName(mAliasListName.get());
channel.setAutoStart(mAutoStart.get());
channel.setAutoStartOrder(mAutoStartOrder.get());
channel.setAutoAddTalkerAliases(mAutoAddTalkerAliases.get());
AuxDecodeConfiguration auxCopy = new AuxDecodeConfiguration();
@@ -526,36 +509,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
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,
* 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

@@ -153,14 +153,6 @@ public class ChannelProcessingManager implements Listener<ChannelEvent>
return !mProcessingChainsMap.isEmpty();
}
/**
* Channels that currently have a processing chain, including temporary traffic channels.
*/
public List<Channel> getProcessingChannels()
{
return new ArrayList<>(mProcessingChainsMap.keySet());
}
/**
* Returns the current processing chain associated with the channel, or
* null if a processing chain is not currently setup for the channel

View File

@@ -30,11 +30,13 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.AbstractListModel;
import java.util.ArrayList;
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 ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor());
@@ -106,6 +108,17 @@ public class ChannelMapModel
*/
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);
}
@@ -129,6 +142,10 @@ public class ChannelMapModel
{
mChannelMaps.add(channelMap);
int index = mChannelMaps.indexOf(channelMap);
fireIntervalAdded(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.ADD));
}
}
@@ -140,9 +157,36 @@ public class ChannelMapModel
{
if(mChannelMaps.contains(channelMap))
{
int index = mChannelMaps.indexOf(channelMap);
mChannelMaps.remove(channelMap);
fireIntervalRemoved(this, index, index);
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,382 +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 io.github.dsheirer.database.event.EventRepository;
import io.github.dsheirer.database.event.IEventRepository;
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 = 3;
public static final String SCHEMA_INFO_TABLE = "schema_info";
private final DatabaseConfiguration mConfiguration;
private final HikariDataSource mDataSource;
private final ICallRepository mCallRepository;
private final IEventRepository mEventRepository;
/**
* 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());
mEventRepository = new EventRepository(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;
}
/**
* Repository for the events tables in this schema
*/
public IEventRepository getEventRepository()
{
return mEventRepository;
}
/**
* 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);
}
}
/**
* Number of events stored in the schema, or 0 if the schema doesn't have sdrtrunk tables (or no events table yet).
*/
public long getEventCount() throws SQLException
{
if(getSchemaStatus() != SchemaStatus.SDRTRUNK)
{
return 0;
}
try(Connection connection = getConnection())
{
return getVersion(connection) >= 3 ? mEventRepository.count(connection) : 0;
}
}
/**
* 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()));
}
//Version 3: decode events
if(fromVersion < 3)
{
statements.addAll(EventRepository.getCreateStatements(mConfiguration.type().getDialect(),
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,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.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,
/**
* Stored events changed outside of the live event updates, for example by the event age-off rule
*/
EVENTS_CHANGED
}
}

File diff suppressed because it is too large Load Diff

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,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.database;
import io.github.dsheirer.database.call.PatchedTalkgroup;
import io.github.dsheirer.protocol.Protocol;
import java.util.List;
/**
* Base class for a stored record (call or decode event) with the channel details and the TO and FROM identifiers.
*
* The TO and FROM identifiers are stored as the formatted identifier, the numeric value, the identifier form and the
* fully qualified address, together with the alias list name of the channel, so that the aliases can be looked up in
* the current alias list when the record is displayed and so that records can be searched by alias.
*/
public abstract class IdentifierRecord
{
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 mStartTime;
private long mEndTime;
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();
/**
* Copies the fields of this base class to the target, for creating a snapshot.
*/
protected void copyTo(IdentifierRecord target)
{
target.mId = mId;
target.mStartTime = mStartTime;
target.mEndTime = mEndTime;
target.mProtocol = mProtocol;
target.mSystem = mSystem;
target.mSite = mSite;
target.mChannel = mChannel;
target.mFrequency = mFrequency;
target.mTimeslot = mTimeslot;
target.mToId = mToId;
target.mToValue = mToValue;
target.mToForm = mToForm;
target.mToFullyQualified = mToFullyQualified;
target.mFromId = mFromId;
target.mFromValue = mFromValue;
target.mFromForm = mFromForm;
target.mFromFullyQualified = mFromFullyQualified;
target.mAliasList = mAliasList;
target.mPatchedTalkgroups = mPatchedTalkgroups;
}
/**
* Database row identifier, or 0 if this record hasn't been inserted yet.
*/
public long getId()
{
return mId;
}
public void setId(long id)
{
mId = id;
}
/**
* Start time, milliseconds since epoch
*/
public long getStartTime()
{
return mStartTime;
}
public void setStartTime(long startTime)
{
mStartTime = startTime;
}
/**
* End time, milliseconds since epoch, or 0 when there is no end time (yet).
*/
public long getEndTime()
{
return mEndTime;
}
public void setEndTime(long endTime)
{
mEndTime = endTime;
}
/**
* 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;
}
/**
* Channel name from the channel configuration
*/
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 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);
}
/**
* Indicates if the TO identifier is a radio
*/
public boolean isToRadio()
{
return FORM_RADIO.equals(mToForm);
}
/**
* 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 identifier, or null.
*/
public String getToFullyQualified()
{
return mToFullyQualified;
}
public void setToFullyQualified(String toFullyQualified)
{
mToFullyQualified = toFullyQualified;
}
public String getFromId()
{
return mFromId;
}
public void setFromId(String fromId)
{
mFromId = fromId;
}
public Long getFromValue()
{
return mFromValue;
}
public void setFromValue(Long fromValue)
{
mFromValue = fromValue;
}
/**
* 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;
}
/**
* Name of the alias list that was assigned to the channel, or null. Aliases for the TO and FROM identifiers are
* looked up in the current version of this alias list when the record is displayed.
*/
public String getAliasList()
{
return mAliasList;
}
public void setAliasList(String aliasList)
{
mAliasList = aliasList;
}
/**
* Talkgroups that are patched into the TO patch group, or an empty list. Searching for a talkgroup finds the
* records 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);
}
}

View File

@@ -1,187 +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.call.CallSearchCriteria;
import io.github.dsheirer.database.call.IdentifierFilter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Portable SQL helpers shared by the calls and events repositories.
*/
public final class SqlSupport
{
private SqlSupport()
{
}
/**
* 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 (TO filter), or null
* @param patchedKey column of the patched table that references the id of the outer row (alias c)
* @param parameters to add the parameter values to
*/
public static String getIdentifierClause(String prefix, IdentifierFilter filter, String formClause,
String patchedTable, String patchedKey, List<Object> parameters)
{
String valueColumn = prefix + "_value";
String fqColumn = prefix + "_fq";
String patched = patchedTable != null ? "EXISTS (SELECT 1 FROM " + patchedTable + " p WHERE p." + patchedKey + " = 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.
*/
public static String getLikePattern(String text)
{
String escaped = text.toLowerCase(Locale.ROOT).replace("!", "!!").replace("%", "!%").replace("_", "!_");
return "%" + escaped + "%";
}
public 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);
}
}
}
public 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);
}
}
public static void setLong(PreparedStatement statement, int index, Long value) throws SQLException
{
if(value == null)
{
statement.setNull(index, Types.BIGINT);
}
else
{
statement.setLong(index, value);
}
}
public static Long getLong(ResultSet rs, String column) throws SQLException
{
long value = rs.getLong(column);
return rs.wasNull() ? null : value;
}
}

View File

@@ -1,400 +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>
* <li>Event rule: deletes decode events older than a number of days (enabled by default, 30 days).</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 final UserPreferences mUserPreferences;
private ScheduledFuture<?> mScheduledFuture;
/**
* Constructs an instance
*/
public AgeOffManager(DatabaseManager databaseManager, UserPreferences userPreferences)
{
mDatabaseManager = databaseManager;
mUserPreferences = userPreferences;
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() && !mPreference.isEventRuleEnabled()))
{
return new AgeOffResult(0, 0, 0, 0);
}
AgeOffResult result = new AgeOffResult(0, 0, 0, 0);
long events = 0;
Path root = mUserPreferences.getDirectoryPreference().getDirectoryRecording();
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, root));
}
if(mPreference.isAgeRuleEnabled())
{
long cutoff = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(mPreference.getAgeRuleDays());
result = result.add(applyAgeRule(connection, repository, cutoff, mPreference.getAgeRuleAction(),
root));
}
if(mPreference.isSizeRuleEnabled())
{
long limit = mPreference.getSizeRuleLimitMB() * BYTES_PER_MB;
result = result.add(applySizeRule(connection, repository, limit, mPreference.getSizeRuleAction(),
root));
}
if(mPreference.isEventRuleEnabled())
{
long cutoff = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(mPreference.getEventRuleDays());
events = database.getEventRepository().deleteStartedBefore(connection, cutoff);
result = result.add(new AgeOffResult(0, 0, 0, events));
}
}
if(events > 0)
{
LOGGER.info("Event age-off removed " + events + " events");
mDatabaseManager.notifyEventsChanged();
}
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,
Path root)
throws SQLException
{
AgeOffResult result = new AgeOffResult(0, 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,
root));
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, Path root) throws SQLException
{
AgeOffResult result = new AgeOffResult(0, 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, root));
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, Path root) throws SQLException
{
AgeOffResult result = new AgeOffResult(0, 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, root));
}
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, Path root) 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(), root))
{
recordings++;
bytes += call.getFileSize();
}
}
if(action == AgeOffAction.DELETE_CALL_AND_RECORDING)
{
repository.delete(connection, ids);
return new AgeOffResult(ids.size(), recordings, bytes, 0);
}
repository.markRecordingsDeleted(connection, ids);
return new AgeOffResult(0, recordings, bytes, 0);
}
/**
* Deletes the audio recording file. Only audio files (.mp3, .wav) are deleted.
* @return true if the file was deleted
*/
static boolean deleteRecording(String filePath, Path root)
{
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
{
Path path = Path.of(filePath);
boolean deleted = Files.deleteIfExists(path);
deleteEmptyFolders(path.getParent(), root);
return deleted;
}
catch(IOException | RuntimeException e)
{
LOGGER.warn("Age-off unable to delete recording [" + filePath + "] - " + e.getMessage());
return false;
}
}
/**
* Deletes the folder and its parent folders while they are empty, up to (not including) the recordings folder.
* Folders outside the recordings folder are never deleted.
* @param folder of a deleted recording
* @param root recordings folder, or null to not delete any folders
*/
static void deleteEmptyFolders(Path folder, Path root)
{
if(folder == null || root == null)
{
return;
}
Path rootPath = root.toAbsolutePath().normalize();
Path current = folder.toAbsolutePath().normalize();
while(current != null && current.startsWith(rootPath) && !current.equals(rootPath))
{
try(var entries = Files.list(current))
{
if(entries.findAny().isPresent())
{
return;
}
}
catch(IOException | RuntimeException e)
{
return;
}
try
{
Files.delete(current);
}
catch(IOException | RuntimeException e)
{
//Not empty (a new recording was just started in it) or not accessible
return;
}
current = current.getParent();
}
}
/**
* Age-off results
* @param calls deleted
* @param recordings deleted
* @param bytes of recordings deleted
* @param events deleted
*/
public record AgeOffResult(long calls, long recordings, long bytes, long events)
{
public AgeOffResult add(AgeOffResult other)
{
return new AgeOffResult(calls + other.calls, recordings + other.recordings, bytes + other.bytes,
events + other.events);
}
}
}

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,283 +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.backup;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import io.github.dsheirer.database.IdentifierRecord;
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.database.call.RecordingState;
import io.github.dsheirer.database.event.EventRecord;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* JSON form of the call and event records in a backup file. Field names match the database column names, null
* values are omitted and unknown fields are ignored when reading, so that a newer backup format version can add fields.
*/
public final class BackupCodec
{
private BackupCodec()
{
}
public static void write(JsonWriter writer, CallRecord call) throws IOException
{
writer.beginObject();
writeIdentifierFields(writer, call);
writer.name("call_state").value(call.getCallState().name());
string(writer, "talker_alias", call.getTalkerAlias());
writer.name("encrypted").value(call.isEncrypted());
writer.name("duplicate_call").value(call.isDuplicate());
writer.name("priority").value(call.getPriority());
writer.name("alias_record").value(call.isAliasRecord());
string(writer, "record_format", call.getRecordFormat());
string(writer, "file_path", call.getFilePath());
writer.name("file_size").value(call.getFileSize());
writer.name("recording_state").value(call.getRecordingState().name());
writer.endObject();
}
public static void write(JsonWriter writer, EventRecord event) throws IOException
{
writer.beginObject();
writeIdentifierFields(writer, event);
writer.name("duration_ms").value(event.getDuration());
writer.name("event_type").value(event.getEventTypeValue().name());
string(writer, "channel_descriptor", event.getChannelDescriptor());
string(writer, "talker_alias", event.getTalkerAlias());
string(writer, "details", event.getDetails());
writer.endObject();
}
private static void writeIdentifierFields(JsonWriter writer, IdentifierRecord record) throws IOException
{
writer.name("start_time").value(record.getStartTime());
writer.name("end_time").value(record.getEndTime());
string(writer, "protocol", record.getProtocol());
string(writer, "system_name", record.getSystem());
string(writer, "site_name", record.getSite());
string(writer, "channel_name", record.getChannel());
writer.name("frequency").value(record.getFrequency());
writer.name("timeslot").value(record.getTimeslot());
string(writer, "to_id", record.getToId());
number(writer, "to_value", record.getToValue());
string(writer, "to_form", record.getToForm());
string(writer, "to_fq", record.getToFullyQualified());
string(writer, "from_id", record.getFromId());
number(writer, "from_value", record.getFromValue());
string(writer, "from_form", record.getFromForm());
string(writer, "from_fq", record.getFromFullyQualified());
string(writer, "alias_list", record.getAliasList());
if(!record.getPatchedTalkgroups().isEmpty())
{
writer.name("patched_talkgroups").beginArray();
for(PatchedTalkgroup talkgroup: record.getPatchedTalkgroups())
{
writer.beginObject();
writer.name("talkgroup").value(talkgroup.value());
string(writer, "fq", talkgroup.fullyQualified());
writer.endObject();
}
writer.endArray();
}
}
private static void string(JsonWriter writer, String name, String value) throws IOException
{
if(value != null)
{
writer.name(name).value(value);
}
}
private static void number(JsonWriter writer, String name, Long value) throws IOException
{
if(value != null)
{
writer.name(name).value(value);
}
}
/**
* Reads a call record object
*/
public static CallRecord readCall(JsonReader reader) throws IOException
{
CallRecord call = new CallRecord();
reader.beginObject();
while(reader.hasNext())
{
String name = reader.nextName();
if(reader.peek() == JsonToken.NULL)
{
reader.nextNull();
continue;
}
if(readIdentifierField(reader, name, call))
{
continue;
}
switch(name)
{
case "call_state" -> call.setCallState(CallState.fromValue(reader.nextString()));
case "talker_alias" -> call.setTalkerAlias(reader.nextString());
case "encrypted" -> call.setEncrypted(reader.nextBoolean());
case "duplicate_call" -> call.setDuplicate(reader.nextBoolean());
case "priority" -> call.setPriority(reader.nextInt());
case "alias_record" -> call.setAliasRecord(reader.nextBoolean());
case "record_format" -> call.setRecordFormat(reader.nextString());
case "file_path" -> call.setFilePath(reader.nextString());
case "file_size" -> call.setFileSize(reader.nextLong());
case "recording_state" -> call.setRecordingState(RecordingState.fromValue(reader.nextString()));
default -> reader.skipValue();
}
}
reader.endObject();
return call;
}
/**
* Reads an event record object
*/
public static EventRecord readEvent(JsonReader reader) throws IOException
{
EventRecord event = new EventRecord();
reader.beginObject();
while(reader.hasNext())
{
String name = reader.nextName();
if(reader.peek() == JsonToken.NULL)
{
reader.nextNull();
continue;
}
if(readIdentifierField(reader, name, event))
{
continue;
}
switch(name)
{
case "duration_ms" -> event.setDuration(reader.nextLong());
case "event_type" -> event.setEventType(reader.nextString());
case "channel_descriptor" -> event.setChannelDescriptor(reader.nextString());
case "talker_alias" -> event.setTalkerAlias(reader.nextString());
case "details" -> event.setDetails(reader.nextString());
default -> reader.skipValue();
}
}
reader.endObject();
return event;
}
/**
* Reads the value of a common identifier record field.
* @return true if the field is a common field and its value was read
*/
private static boolean readIdentifierField(JsonReader reader, String name, IdentifierRecord record)
throws IOException
{
switch(name)
{
case "start_time" -> record.setStartTime(reader.nextLong());
case "end_time" -> record.setEndTime(reader.nextLong());
case "protocol" -> record.setProtocol(reader.nextString());
case "system_name" -> record.setSystem(reader.nextString());
case "site_name" -> record.setSite(reader.nextString());
case "channel_name" -> record.setChannel(reader.nextString());
case "frequency" -> record.setFrequency(reader.nextLong());
case "timeslot" -> record.setTimeslot(reader.nextInt());
case "to_id" -> record.setToId(reader.nextString());
case "to_value" -> record.setToValue(reader.nextLong());
case "to_form" -> record.setToForm(reader.nextString());
case "to_fq" -> record.setToFullyQualified(reader.nextString());
case "from_id" -> record.setFromId(reader.nextString());
case "from_value" -> record.setFromValue(reader.nextLong());
case "from_form" -> record.setFromForm(reader.nextString());
case "from_fq" -> record.setFromFullyQualified(reader.nextString());
case "alias_list" -> record.setAliasList(reader.nextString());
case "patched_talkgroups" -> record.setPatchedTalkgroups(readPatchedTalkgroups(reader));
default ->
{
return false;
}
}
return true;
}
private static List<PatchedTalkgroup> readPatchedTalkgroups(JsonReader reader) throws IOException
{
List<PatchedTalkgroup> talkgroups = new ArrayList<>();
reader.beginArray();
while(reader.hasNext())
{
long value = 0;
String fq = null;
reader.beginObject();
while(reader.hasNext())
{
String name = reader.nextName();
if(reader.peek() == JsonToken.NULL)
{
reader.nextNull();
}
else if(name.equals("talkgroup"))
{
value = reader.nextLong();
}
else if(name.equals("fq"))
{
fq = reader.nextString();
}
else
{
reader.skipValue();
}
}
reader.endObject();
talkgroups.add(new PatchedTalkgroup(value, fq));
}
reader.endArray();
return talkgroups;
}
}

View File

@@ -1,61 +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.backup;
import java.nio.file.Path;
/**
* A backup file in the backup directory
*
* @param path of the backup file
* @param created time of the backup, milliseconds since epoch (from the file name)
* @param size of the file in bytes
* @param tag optional tag from the file name (e.g. pre-restore), or null
* @param metadata from the file, or null if the file can't be read
*/
public record BackupInfo(Path path, long created, long size, String tag, Metadata metadata)
{
/**
* Backup file contents summary
*
* @param format version of the backup file format
* @param schemaVersion of the database tables the backup was made from
* @param created time of the backup, milliseconds since epoch
* @param source description of the database that was backed up
* @param calls count of calls in the backup
* @param events count of events in the backup
*/
public record Metadata(int format, int schemaVersion, long created, String source, long calls, long events) {}
/**
* Indicates if the file is a readable backup
*/
public boolean isValid()
{
return metadata != null;
}
/**
* Indicates if this backup was made automatically before restoring another backup
*/
public boolean isPreRestore()
{
return BackupManager.TAG_PRE_RESTORE.equals(tag);
}
}

View File

@@ -1,68 +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.backup;
import java.util.concurrent.TimeUnit;
/**
* How often the call database is backed up automatically
*/
public enum BackupInterval
{
NEVER("Never (manual only)", 0),
HOURS_6("Every 6 hours", TimeUnit.HOURS.toMillis(6)),
HOURS_12("Every 12 hours", TimeUnit.HOURS.toMillis(12)),
DAY_1("Daily", TimeUnit.DAYS.toMillis(1)),
DAYS_2("Every 2 days", TimeUnit.DAYS.toMillis(2)),
WEEK_1("Weekly", TimeUnit.DAYS.toMillis(7)),
MONTH_1("Monthly (30 days)", TimeUnit.DAYS.toMillis(30));
public static final BackupInterval DEFAULT = DAY_1;
private final String mLabel;
private final long mMilliseconds;
BackupInterval(String label, long milliseconds)
{
mLabel = label;
mMilliseconds = milliseconds;
}
/**
* Time between automatic backups in milliseconds, or 0 when automatic backups are off
*/
public long getMilliseconds()
{
return mMilliseconds;
}
/**
* Indicates if automatic backups are enabled
*/
public boolean isEnabled()
{
return this != NEVER;
}
@Override
public String toString()
{
return mLabel;
}
}

View File

@@ -1,792 +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.backup;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.github.dsheirer.controller.NamingThreadFactory;
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.database.call.RecordingState;
import io.github.dsheirer.database.event.EventRecord;
import io.github.dsheirer.database.event.IEventRepository;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.database.DatabasePreference;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
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;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Database backups: scheduled and on-demand backups of the calls and events, retention of the newest backups, and
* restore of a backup into the current database.
*
* A backup is a zip file with the calls and events as JSON (see {@link BackupCodec}) and a metadata entry. The format
* doesn't depend on the database engine, so a backup can be restored into any of the supported databases. The
* recording files aren't included - restored calls refer to the recording files that still exist.
*
* Backups and restores run one at a time on the backup thread. A backup reads the database in a single read
* transaction while the database thread continues to write. A restore runs on the database thread (writes are held
* until it's done) and first makes a 'pre-restore' backup of the current contents, so it can be undone.
*/
public class BackupManager
{
private static final Logger LOGGER = LoggerFactory.getLogger(BackupManager.class);
public static final int FORMAT_VERSION = 1;
public static final String TAG_PRE_RESTORE = "pre-restore";
static final String FILE_PREFIX = "sdrtrunk-backup-";
static final String FILE_EXTENSION = ".zip";
static final String ENTRY_METADATA = "metadata.json";
static final String ENTRY_CALLS = "calls.json";
static final String ENTRY_EVENTS = "events.json";
private static final Pattern FILE_PATTERN =
Pattern.compile("sdrtrunk-backup-(\\d{8}-\\d{6})(?:-([a-z][a-z0-9-]*))?\\.zip");
private static final DateTimeFormatter FILE_TIME = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
private static final long INITIAL_DELAY_SECONDS = 120;
private static final long CHECK_INTERVAL_SECONDS = 600;
private static final int PAGE_SIZE = 1000;
private final DatabaseManager mDatabaseManager;
private final DatabasePreference mPreference;
private final Supplier<Path> mDirectory;
private final ScheduledExecutorService mExecutor =
Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("sdrtrunk database backup"));
private final Broadcaster<BackupInfo> mBackupBroadcaster = new Broadcaster<>();
private ScheduledFuture<?> mScheduledFuture;
/**
* Constructs an instance
* @param databaseManager for the current database
* @param userPreferences for the backup schedule, retention and directory
*/
public BackupManager(DatabaseManager databaseManager, UserPreferences userPreferences)
{
mDatabaseManager = databaseManager;
mPreference = userPreferences.getDatabasePreference();
mDirectory = () -> userPreferences.getDirectoryPreference().getDirectoryDatabaseBackup();
}
/**
* Starts the automatic backup schedule. The schedule is checked two minutes after startup and then every 10
* minutes, and a backup is made when the newest backup is older than the backup interval.
*/
public void start()
{
if(mScheduledFuture == null)
{
mScheduledFuture = mExecutor.scheduleWithFixedDelay(this::checkSchedule, INITIAL_DELAY_SECONDS,
CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS);
}
}
/**
* Stops the schedule. A backup in progress is abandoned and its partial file removed.
*/
public void stop()
{
if(mScheduledFuture != null)
{
mScheduledFuture.cancel(false);
mScheduledFuture = null;
}
mExecutor.shutdownNow();
}
/**
* Directory that holds the backup files
*/
public Path getBackupDirectory()
{
return mDirectory.get();
}
/**
* Registers the listener to be notified of each new backup (scheduled, manual or pre-restore). Notified on the
* backup thread.
*/
public void addBackupListener(Listener<BackupInfo> listener)
{
mBackupBroadcaster.addListener(listener);
}
public void removeBackupListener(Listener<BackupInfo> listener)
{
mBackupBroadcaster.removeListener(listener);
}
private void checkSchedule()
{
try
{
BackupInterval interval = mPreference.getBackupInterval();
List<BackupInfo> backups = list(getBackupDirectory());
long last = backups.isEmpty() ? 0 : backups.getFirst().created();
if(isDue(last, interval, System.currentTimeMillis()) && mDatabaseManager.isConnected())
{
LOGGER.info("Starting scheduled database backup (" + interval + ")");
backup(null);
}
}
catch(Exception e)
{
LOGGER.error("Scheduled database backup failed - " + e.getMessage(), e);
}
}
/**
* Indicates if an automatic backup is due.
* @param lastBackup time of the newest backup, or 0 if there are no backups
* @param interval between automatic backups
* @param now current time
*/
static boolean isDue(long lastBackup, BackupInterval interval, long now)
{
return interval.isEnabled() && (lastBackup <= 0 || now - lastBackup >= interval.getMilliseconds());
}
/**
* Backs up the current database now and then deletes the oldest backups beyond the retention count.
*/
public CompletableFuture<BackupInfo> backupNow()
{
return CompletableFuture.supplyAsync(() -> {
try
{
return backup(null);
}
catch(Exception e)
{
throw new IllegalStateException(e.getMessage(), e);
}
}, mExecutor);
}
/**
* Makes a backup and applies the retention count. Backup thread only.
*/
private BackupInfo backup(String tag) throws IOException, SQLException
{
CallDatabase database = mDatabaseManager.getDatabase();
if(database == null)
{
throw new IllegalStateException("The call database is not available");
}
BackupInfo backup = writeBackup(database, getBackupDirectory(), tag, System.currentTimeMillis());
LOGGER.info("Database backup created [" + backup.path() + "] with " + backup.metadata().calls() +
" calls and " + backup.metadata().events() + " events");
if(tag == null)
{
for(Path deleted: applyRetention(getBackupDirectory(), mPreference.getBackupRetain()))
{
LOGGER.info("Deleted old database backup [" + deleted + "]");
}
}
mBackupBroadcaster.broadcast(backup);
return backup;
}
/**
* Lists the backups, newest first. Runs on the backup thread.
*/
public CompletableFuture<List<BackupInfo>> listBackups()
{
return CompletableFuture.supplyAsync(() -> list(getBackupDirectory()), mExecutor);
}
/**
* Deletes the backup file. Runs on the backup thread.
*/
public CompletableFuture<Void> delete(BackupInfo backup)
{
return CompletableFuture.runAsync(() -> {
try
{
Files.deleteIfExists(backup.path());
LOGGER.info("Deleted database backup [" + backup.path() + "]");
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe.getMessage(), ioe);
}
}, mExecutor);
}
/**
* Replaces the calls and events in the current database with the contents of the backup. A pre-restore backup
* of the current contents is made first (when the database isn't empty).
* @param backup to restore
* @param progress receives status text (on the backup or database thread)
*/
public CompletableFuture<RestoreResult> restore(BackupInfo backup, Consumer<String> progress)
{
return CompletableFuture.supplyAsync(() -> {
try
{
BackupInfo.Metadata metadata = readMetadata(backup.path());
checkCompatible(metadata);
CallDatabase database = mDatabaseManager.getDatabase();
if(database == null)
{
throw new IllegalStateException("The call database is not available");
}
BackupInfo preRestore = null;
if(database.getCallCount() > 0 || database.getEventCount() > 0)
{
progress.accept("Backing up the current database before the restore");
preRestore = backup(TAG_PRE_RESTORE);
}
RestoreResult result = mDatabaseManager.restore(backup.path(), progress).get();
LOGGER.info("Restored database backup [" + backup.path() + "] - " + result.calls() + " calls, " +
result.events() + " events, " + result.missingRecordings() + " missing recordings");
return result.withPreRestore(preRestore);
}
catch(Exception e)
{
Throwable cause = e.getCause() != null && e instanceof java.util.concurrent.ExecutionException ?
e.getCause() : e;
throw new IllegalStateException(cause.getMessage(), cause);
}
}, mExecutor);
}
/**
* Result of a restore
* @param calls restored
* @param events restored
* @param missingRecordings count of restored calls whose recording file no longer exists
* @param preRestore backup of the database contents before the restore, or null if the database was empty
*/
public record RestoreResult(long calls, long events, long missingRecordings, BackupInfo preRestore)
{
RestoreResult withPreRestore(BackupInfo backup)
{
return new RestoreResult(calls, events, missingRecordings, backup);
}
}
/**
* Throws if the backup can't be restored by this version of sdrtrunk.
*/
static void checkCompatible(BackupInfo.Metadata metadata) throws IOException
{
if(metadata == null)
{
throw new IOException("The file is not a readable sdrtrunk database backup");
}
if(metadata.format() > FORMAT_VERSION || metadata.schemaVersion() > CallDatabase.SCHEMA_VERSION)
{
throw new IOException("The backup was made by a newer version of sdrtrunk (backup format " +
metadata.format() + ", schema version " + metadata.schemaVersion() + ")");
}
}
/**
* Writes a backup of the calls and events in the database to a new file in the directory. The file is written
* to a temporary name and renamed when complete, so an interrupted backup never leaves a partial backup file.
* @param database to back up
* @param directory for the backup file
* @param tag for the file name, or null
* @param now backup time
* @return the new backup
*/
public static BackupInfo writeBackup(CallDatabase database, Path directory, String tag, long now)
throws IOException, SQLException
{
Files.createDirectories(directory);
long created = now - (now % 1000);
Path target = directory.resolve(getFileName(created, tag));
//Unique name when two backups are made in the same second
while(Files.exists(target))
{
created += 1000;
target = directory.resolve(getFileName(created, tag));
}
Path temp = directory.resolve(target.getFileName() + ".part");
long calls = 0;
long events = 0;
try(ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)));
Connection connection = database.getConnection())
{
boolean autoCommit = connection.getAutoCommit();
int isolation = connection.getTransactionIsolation();
try
{
//One read transaction, so that the calls and events are a consistent snapshot
connection.setAutoCommit(false);
setIsolation(connection, Connection.TRANSACTION_REPEATABLE_READ);
ICallRepository callRepository = database.getCallRepository();
JsonWriter writer = startEntry(zip, ENTRY_CALLS);
writer.beginArray();
List<CallRecord> callPage = callRepository.readPage(connection, 0, PAGE_SIZE);
while(!callPage.isEmpty())
{
for(CallRecord call: callPage)
{
BackupCodec.write(writer, call);
}
calls += callPage.size();
callPage = callRepository.readPage(connection, callPage.getLast().getId(), PAGE_SIZE);
}
writer.endArray();
writer.flush();
zip.closeEntry();
IEventRepository eventRepository = database.getEventRepository();
writer = startEntry(zip, ENTRY_EVENTS);
writer.beginArray();
List<EventRecord> eventPage = eventRepository.readPage(connection, 0, PAGE_SIZE);
while(!eventPage.isEmpty())
{
for(EventRecord event: eventPage)
{
BackupCodec.write(writer, event);
}
events += eventPage.size();
eventPage = eventRepository.readPage(connection, eventPage.getLast().getId(), PAGE_SIZE);
}
writer.endArray();
writer.flush();
zip.closeEntry();
connection.rollback();
}
finally
{
setIsolation(connection, isolation);
connection.setAutoCommit(autoCommit);
}
BackupInfo.Metadata metadata = new BackupInfo.Metadata(FORMAT_VERSION, CallDatabase.SCHEMA_VERSION,
created, database.getConfiguration().getDescription(), calls, events);
JsonWriter writer = startEntry(zip, ENTRY_METADATA);
writer.setIndent(" ");
writer.beginObject();
writer.name("format").value(metadata.format());
writer.name("schema_version").value(metadata.schemaVersion());
writer.name("created").value(metadata.created());
writer.name("source").value(metadata.source());
writer.name("calls").value(metadata.calls());
writer.name("events").value(metadata.events());
writer.endObject();
writer.flush();
zip.closeEntry();
}
catch(IOException | SQLException | RuntimeException e)
{
Files.deleteIfExists(temp);
throw e;
}
try
{
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
}
catch(AtomicMoveNotSupportedException e)
{
Files.move(temp, target);
}
return read(target);
}
private static void setIsolation(Connection connection, int isolation)
{
try
{
connection.setTransactionIsolation(isolation);
}
catch(SQLException se)
{
LOGGER.debug("Transaction isolation level not supported - " + se.getMessage());
}
}
/**
* Starts a zip entry and returns a JSON writer for it. The writer must be flushed, not closed, since closing it
* would close the zip stream.
*/
private static JsonWriter startEntry(ZipOutputStream zip, String name) throws IOException
{
zip.putNextEntry(new ZipEntry(name));
OutputStream entry = new FilterOutputStream(zip)
{
@Override
public void write(byte[] b, int off, int len) throws IOException
{
out.write(b, off, len);
}
@Override
public void close() throws IOException
{
flush();
}
};
return new JsonWriter(new OutputStreamWriter(entry, StandardCharsets.UTF_8));
}
/**
* Backup file name for the time and tag
*/
static String getFileName(long created, String tag)
{
String time = FILE_TIME.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(created), ZoneId.systemDefault()));
return FILE_PREFIX + time + (tag != null ? "-" + tag : "") + FILE_EXTENSION;
}
/**
* Replaces the calls and events in the database with the contents of the backup, in a single transaction, so
* that a failed restore leaves the database unchanged. Calls that were in progress when the backup was made are
* marked interrupted, and calls whose recording file no longer exists are marked as having a deleted recording.
* Invoke on the database thread only.
* @param database to restore into
* @param backup file
* @param progress receives status text
*/
public static RestoreResult restore(CallDatabase database, Path backup, Consumer<String> progress)
throws IOException, SQLException
{
BackupInfo.Metadata metadata = readMetadata(backup);
checkCompatible(metadata);
long calls = 0;
long events = 0;
long missing = 0;
try(ZipFile zip = new ZipFile(backup.toFile()); Connection connection = database.getConnection())
{
ZipEntry callsEntry = zip.getEntry(ENTRY_CALLS);
ZipEntry eventsEntry = zip.getEntry(ENTRY_EVENTS);
if(callsEntry == null || eventsEntry == null)
{
throw new IOException("The backup file is incomplete");
}
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try
{
ICallRepository callRepository = database.getCallRepository();
IEventRepository eventRepository = database.getEventRepository();
progress.accept("Removing the current calls and events");
eventRepository.deleteAll(connection);
callRepository.deleteAll(connection);
try(InputStream in = zip.getInputStream(callsEntry);
JsonReader reader = new JsonReader(new InputStreamReader(in, StandardCharsets.UTF_8)))
{
List<CallRecord> batch = new ArrayList<>();
reader.beginArray();
while(reader.hasNext())
{
CallRecord call = BackupCodec.readCall(reader);
if(clearMissingRecording(call))
{
missing++;
}
batch.add(call);
if(batch.size() >= PAGE_SIZE)
{
callRepository.insertBatch(connection, batch);
calls += batch.size();
batch.clear();
progress.accept("Restoring calls: " + calls + " of " + metadata.calls());
}
}
reader.endArray();
callRepository.insertBatch(connection, batch);
calls += batch.size();
}
try(InputStream in = zip.getInputStream(eventsEntry);
JsonReader reader = new JsonReader(new InputStreamReader(in, StandardCharsets.UTF_8)))
{
List<EventRecord> batch = new ArrayList<>();
reader.beginArray();
while(reader.hasNext())
{
batch.add(BackupCodec.readEvent(reader));
if(batch.size() >= PAGE_SIZE)
{
eventRepository.insertBatch(connection, batch);
events += batch.size();
batch.clear();
progress.accept("Restoring events: " + events + " of " + metadata.events());
}
}
reader.endArray();
eventRepository.insertBatch(connection, batch);
events += batch.size();
}
callRepository.markInterrupted(connection);
progress.accept("Committing the restored calls and events");
connection.commit();
}
catch(IOException | SQLException | RuntimeException e)
{
connection.rollback();
throw e;
}
finally
{
connection.setAutoCommit(autoCommit);
}
}
return new RestoreResult(calls, events, missing, null);
}
/**
* Marks the recording of the call deleted when the recording file no longer exists (e.g. removed by an age-off
* rule after the backup was made).
* @return true if the recording was missing
*/
static boolean clearMissingRecording(CallRecord call)
{
if(call.getFilePath() == null || (call.getRecordingState() != RecordingState.RECORDED &&
call.getRecordingState() != RecordingState.RECORDING))
{
return false;
}
try
{
if(Files.exists(Path.of(call.getFilePath())))
{
return false;
}
}
catch(RuntimeException re)
{
//Invalid path - treat as missing
}
call.setRecordingState(RecordingState.DELETED);
call.setFilePath(null);
call.setFileSize(0);
return true;
}
/**
* Backups in the directory, newest first. Files that match the backup file name but can't be read are included
* with null metadata.
*/
public static List<BackupInfo> list(Path directory)
{
List<BackupInfo> backups = new ArrayList<>();
if(!Files.isDirectory(directory))
{
return backups;
}
try(Stream<Path> files = Files.list(directory))
{
for(Path file: files.toList())
{
BackupInfo backup = read(file);
if(backup != null)
{
backups.add(backup);
}
}
}
catch(IOException ioe)
{
LOGGER.warn("Unable to list database backups in [" + directory + "] - " + ioe.getMessage());
}
backups.sort(Comparator.comparingLong(BackupInfo::created).reversed()
.thenComparing(backup -> backup.path().getFileName().toString(), Comparator.reverseOrder()));
return backups;
}
/**
* Backup details for the file, or null if the file name isn't a backup file name.
*/
static BackupInfo read(Path file)
{
Matcher matcher = FILE_PATTERN.matcher(file.getFileName().toString());
if(!matcher.matches() || !Files.isRegularFile(file))
{
return null;
}
long created;
try
{
created = LocalDateTime.parse(matcher.group(1), FILE_TIME).atZone(ZoneId.systemDefault()).toInstant()
.toEpochMilli();
}
catch(DateTimeParseException e)
{
return null;
}
long size = 0;
try
{
size = Files.size(file);
}
catch(IOException ioe)
{
//Leave as 0
}
BackupInfo.Metadata metadata = null;
try
{
metadata = readMetadata(file);
}
catch(IOException | RuntimeException e)
{
LOGGER.warn("Unable to read database backup [" + file + "] - " + e.getMessage());
}
return new BackupInfo(file, created, size, matcher.group(2), metadata);
}
/**
* Reads the metadata entry of a backup file
*/
static BackupInfo.Metadata readMetadata(Path file) throws IOException
{
try(ZipFile zip = new ZipFile(file.toFile()))
{
ZipEntry entry = zip.getEntry(ENTRY_METADATA);
if(entry == null)
{
return null;
}
try(InputStream in = zip.getInputStream(entry);
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8))
{
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
return new BackupInfo.Metadata(json.get("format").getAsInt(), json.get("schema_version").getAsInt(),
json.get("created").getAsLong(), json.has("source") ? json.get("source").getAsString() : "",
json.get("calls").getAsLong(), json.get("events").getAsLong());
}
}
}
/**
* Deletes the oldest backups so that no more than the retention count remain.
* @return deleted files
*/
public static List<Path> applyRetention(Path directory, int retain)
{
List<Path> deleted = new ArrayList<>();
List<BackupInfo> backups = list(directory);
for(int x = Math.max(1, retain); x < backups.size(); x++)
{
Path path = backups.get(x).path();
try
{
Files.deleteIfExists(path);
deleted.add(path);
}
catch(IOException ioe)
{
LOGGER.warn("Unable to delete old database backup [" + path + "] - " + ioe.getMessage());
}
}
return deleted;
}
}

View File

@@ -1,250 +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.database.IdentifierRecord;
/**
* 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 extends IdentifierRecord
{
private long mCallKey;
private CallState mCallState = CallState.ACTIVE;
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();
copyTo(copy);
copy.mCallKey = mCallKey;
copy.mCallState = mCallState;
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;
}
/**
* 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 duration in milliseconds. For an active call this is the elapsed time up to now.
*/
public long getDuration()
{
if(getEndTime() > 0)
{
return Math.max(0, getEndTime() - getStartTime());
}
return isActive() ? Math.max(0, System.currentTimeMillis() - getStartTime()) : 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;
}
/**
* Call type (group, patch, private or telephone), derived from the TO and FROM identifier forms.
*/
public CallType getCallType()
{
return CallType.from(getToForm(), getFromForm());
}
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:" + getStartTime() + "|" + getChannel() + "|" + getTimeslot() + "|" + getToId() + "|" + getFromId();
}
@Override
public String toString()
{
return "Call " + getId() + " " + getProtocol() + " TO:" + getToId() + " FROM:" + getFromId() + " " + mCallState + " " +
mRecordingState + (mFilePath != null ? " " + mFilePath : "");
}
}

View File

@@ -1,778 +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 static io.github.dsheirer.database.SqlSupport.bindParameters;
import static io.github.dsheirer.database.SqlSupport.getIdentifierClause;
import static io.github.dsheirer.database.SqlSupport.getLikePattern;
import static io.github.dsheirer.database.SqlSupport.getLong;
import static io.github.dsheirer.database.SqlSupport.setLong;
import static io.github.dsheirer.database.SqlSupport.setString;
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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
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());
}
/**
* 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;
}
/**
* 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 deleteAll(Connection connection) throws SQLException
{
try(Statement statement = connection.createStatement())
{
statement.executeUpdate("DELETE FROM " + mPatchedTable);
return statement.executeUpdate("DELETE FROM " + mTable);
}
}
@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, "call_id", parameters));
}
if(!criteria.from().isEmpty())
{
clauses.add(getIdentifierClause("from", criteria.from(), "from_form = '" + CallRecord.FORM_RADIO + "'",
null, 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);
}
/**
* 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.
*/
public 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,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.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;
/**
* Deletes all calls (and their patched talkgroups), for restoring a backup.
* @return count of calls deleted
*/
int deleteAll(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,286 +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.database.IdentifierRecord;
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
*/
public boolean matches(IdentifierRecord 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,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

@@ -1,95 +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.event;
import io.github.dsheirer.module.decode.event.DecodeEventType;
import java.util.EnumSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Event categories for filtering, using the same groupings of decode event types as the Now Playing event filters.
*/
public enum EventCategory
{
VOICE_CALL("Voice Call", DecodeEventType.VOICE_CALLS),
ENCRYPTED_CALL("Encrypted Call", DecodeEventType.VOICE_CALLS_ENCRYPTED),
DATA("Data", DecodeEventType.DATA_CALLS),
COMMAND("Command", DecodeEventType.COMMANDS),
REGISTRATION("Registration", DecodeEventType.REGISTRATION),
OTHER("Other", DecodeEventType.OTHERS);
private final String mLabel;
private final Set<DecodeEventType> mTypes;
EventCategory(String label, EnumSet<DecodeEventType> types)
{
mLabel = label;
mTypes = EnumSet.copyOf(types);
}
/**
* Event types in this category
*/
public Set<DecodeEventType> getTypes()
{
return mTypes;
}
/**
* Indicates if the event type belongs to this category
*/
public boolean contains(DecodeEventType type)
{
return mTypes.contains(type);
}
/**
* Category of the event type
*/
public static EventCategory from(DecodeEventType type)
{
for(EventCategory category: values())
{
if(category.contains(type))
{
return category;
}
}
return OTHER;
}
/**
* SQL condition that matches the events in this category. The values are enumeration names, so they are safe
* to include in the statement.
*/
public String getWhereClause()
{
return "event_type IN (" + mTypes.stream().map(type -> "'" + type.name() + "'").sorted()
.collect(Collectors.joining(", ")) + ")";
}
@Override
public String toString()
{
return mLabel;
}
}

View File

@@ -1,175 +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.event;
import io.github.dsheirer.database.IdentifierRecord;
import io.github.dsheirer.module.decode.event.DecodeEventType;
import java.util.Objects;
/**
* A decode event as stored in the events 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 EventRecord extends IdentifierRecord
{
private long mEventKey;
private long mDuration;
private String mEventType;
private String mChannelDescriptor;
private String mTalkerAlias;
private String mDetails;
/**
* Creates a copy (snapshot) of this record.
*/
public EventRecord copy()
{
EventRecord copy = new EventRecord();
copyTo(copy);
copy.mEventKey = mEventKey;
copy.mDuration = mDuration;
copy.mEventType = mEventType;
copy.mChannelDescriptor = mChannelDescriptor;
copy.mTalkerAlias = mTalkerAlias;
copy.mDetails = mDetails;
return copy;
}
/**
* In-memory key that identifies a live event across snapshots, or 0 for records loaded from the database.
*/
public long getEventKey()
{
return mEventKey;
}
public void setEventKey(long eventKey)
{
mEventKey = eventKey;
}
/**
* Event duration in milliseconds, or 0 when the event has no duration.
*/
public long getDuration()
{
return mDuration;
}
public void setDuration(long duration)
{
mDuration = Math.max(0, duration);
}
/**
* Decode event type enumeration entry name (e.g. CALL_GROUP)
*/
public String getEventType()
{
return mEventType;
}
public void setEventType(String eventType)
{
mEventType = eventType;
}
/**
* Decode event type, or UNKNOWN when the stored value isn't recognized.
*/
public DecodeEventType getEventTypeValue()
{
if(mEventType != null)
{
try
{
return DecodeEventType.valueOf(mEventType);
}
catch(IllegalArgumentException iae)
{
//Fall through
}
}
return DecodeEventType.UNKNOWN;
}
/**
* Event category derived from the event type
*/
public EventCategory getCategory()
{
return EventCategory.from(getEventTypeValue());
}
/**
* Channel descriptor for the event (e.g. the traffic channel number of a call), or null.
*/
public String getChannelDescriptor()
{
return mChannelDescriptor;
}
public void setChannelDescriptor(String channelDescriptor)
{
mChannelDescriptor = channelDescriptor;
}
public String getTalkerAlias()
{
return mTalkerAlias;
}
public void setTalkerAlias(String talkerAlias)
{
mTalkerAlias = talkerAlias;
}
/**
* Decoder supplied details for the event, or null.
*/
public String getDetails()
{
return mDetails;
}
public void setDetails(String details)
{
mDetails = details;
}
/**
* Key used to detect an event that already exists in a target database during an append transfer.
*/
public String getTransferKey()
{
return "E:" + getStartTime() + "|" + mEventType + "|" + getChannel() + "|" + getTimeslot() + "|" + getToId() +
"|" + getFromId() + "|" + Objects.hashCode(mDetails);
}
@Override
public String toString()
{
return "Event " + getId() + " " + mEventType + " " + getProtocol() + " TO:" + getToId() + " FROM:" +
getFromId() + (mDetails != null ? " " + mDetails : "");
}
}

View File

@@ -1,538 +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.event;
import io.github.dsheirer.database.IdentifierRecord;
import io.github.dsheirer.database.call.PatchedTalkgroup;
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.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.github.dsheirer.database.SqlSupport.bindParameters;
import static io.github.dsheirer.database.SqlSupport.getIdentifierClause;
import static io.github.dsheirer.database.SqlSupport.getLikePattern;
import static io.github.dsheirer.database.SqlSupport.getLong;
import static io.github.dsheirer.database.SqlSupport.setLong;
import static io.github.dsheirer.database.SqlSupport.setString;
/**
* JDBC implementation of the events table, using SQL that is portable across all supported database engines. All
* methods take a connection from the caller and qualify the table names with the schema.
*/
public class EventRepository implements IEventRepository
{
public static final String TABLE = "events";
public static final String PATCHED_TABLE = "event_patched_talkgroups";
/**
* Columns in insert/select order, excluding the generated id.
*/
private static final String COLUMNS = "start_time, end_time, duration_ms, event_type, protocol, system_name, " +
"site_name, channel_name, channel_descriptor, frequency, timeslot, to_id, to_value, to_form, to_fq, from_id, " +
"from_value, from_form, from_fq, alias_list, talker_alias, details";
private static final int COLUMN_COUNT = 22;
/**
* Maximum stored lengths of the text columns, so that a long value can't fail an insert. Events can have more
* than one TO or FROM identifier, so the identifier columns are longer than in the calls table.
*/
private static final int LENGTH_SHORT = 48;
private static final int LENGTH_ID = 64;
private static final int LENGTH_NAME = 255;
static final int LENGTH_DETAILS = 2048;
private static final String TO_TALKGROUP_FORMS = "to_form IN ('" + IdentifierRecord.FORM_TALKGROUP + "', '" +
IdentifierRecord.FORM_PATCH_GROUP + "')";
private static final String TO_RADIO_FORM = "to_form = '" + IdentifierRecord.FORM_RADIO + "'";
private static final String FROM_RADIO_FORM = "from_form = '" + IdentifierRecord.FORM_RADIO + "'";
private final String mSchema;
private final String mTable;
private final String mPatchedTable;
/**
* Constructs an instance
* @param schema that holds the events tables
*/
public EventRepository(String schema)
{
mSchema = schema;
mTable = schema + "." + TABLE;
mPatchedTable = schema + "." + PATCHED_TABLE;
}
/**
* Statements that create the events tables and their indexes (schema version 3).
*/
public static List<String> getCreateStatements(IDatabaseDialect dialect, String schema)
{
String table = schema + "." + TABLE;
String patchedTable = schema + "." + PATCHED_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, " +
"event_type VARCHAR(" + LENGTH_SHORT + ") NOT NULL, " +
"protocol VARCHAR(" + LENGTH_SHORT + "), " +
"system_name VARCHAR(" + LENGTH_NAME + "), " +
"site_name VARCHAR(" + LENGTH_NAME + "), " +
"channel_name VARCHAR(" + LENGTH_NAME + "), " +
"channel_descriptor VARCHAR(" + LENGTH_NAME + "), " +
"frequency BIGINT NOT NULL, " +
"timeslot INT NOT NULL, " +
"to_id VARCHAR(" + LENGTH_NAME + "), " +
"to_value BIGINT, " +
"to_form VARCHAR(" + LENGTH_SHORT + "), " +
"to_fq VARCHAR(" + LENGTH_ID + "), " +
"from_id VARCHAR(" + LENGTH_NAME + "), " +
"from_value BIGINT, " +
"from_form VARCHAR(" + LENGTH_SHORT + "), " +
"from_fq VARCHAR(" + LENGTH_ID + "), " +
"alias_list VARCHAR(" + LENGTH_NAME + "), " +
"talker_alias VARCHAR(" + LENGTH_NAME + "), " +
"details VARCHAR(" + LENGTH_DETAILS + "))");
//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 events_start_time_idx ON " + table + " (start_time)");
statements.add("CREATE INDEX IF NOT EXISTS events_to_value_idx ON " + table + " (to_value)");
statements.add("CREATE INDEX IF NOT EXISTS events_from_value_idx ON " + table + " (from_value)");
statements.add("CREATE INDEX IF NOT EXISTS events_event_type_idx ON " + table + " (event_type, start_time)");
statements.add("CREATE TABLE IF NOT EXISTS " + patchedTable + " (" +
"event_id BIGINT NOT NULL REFERENCES " + table + "(id) ON DELETE CASCADE, " +
"talkgroup BIGINT NOT NULL, " +
"fq VARCHAR(" + LENGTH_ID + "))");
statements.add("CREATE INDEX IF NOT EXISTS event_patched_event_idx ON " + patchedTable + " (event_id)");
statements.add("CREATE INDEX IF NOT EXISTS event_patched_talkgroup_idx ON " + patchedTable + " (talkgroup)");
return statements;
}
private String getInsertStatement()
{
return "INSERT INTO " + mTable + " (" + COLUMNS + ") VALUES (" + "?, ".repeat(COLUMN_COUNT - 1) + "?)";
}
@Override
public long insert(Connection connection, EventRecord event) throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement(getInsertStatement(), new String[]{"id"}))
{
bind(statement, event);
statement.executeUpdate();
try(ResultSet keys = statement.getGeneratedKeys())
{
if(keys.next())
{
long id = keys.getLong(1);
event.setId(id);
insertPatchedTalkgroups(connection, id, event.getPatchedTalkgroups());
return id;
}
}
}
throw new SQLException("Database didn't return a generated id for the inserted event");
}
@Override
public void insertBatch(Connection connection, List<EventRecord> events) throws SQLException
{
List<EventRecord> patched = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(getInsertStatement()))
{
for(EventRecord event: events)
{
//Events with patched talkgroups need their generated id for the patched talkgroup rows
if(!event.getPatchedTalkgroups().isEmpty())
{
patched.add(event);
continue;
}
bind(statement, event);
statement.addBatch();
}
statement.executeBatch();
}
for(EventRecord event: patched)
{
insert(connection, event);
}
}
@Override
public boolean update(Connection connection, EventRecord event) throws SQLException
{
String assignments = String.join(" = ?, ", COLUMNS.split(", ")) + " = ?";
try(PreparedStatement statement = connection.prepareStatement("UPDATE " + mTable + " SET " + assignments +
" WHERE id = ?"))
{
bind(statement, event);
statement.setLong(COLUMN_COUNT + 1, event.getId());
if(statement.executeUpdate() == 0)
{
return false;
}
}
if(IdentifierRecord.FORM_PATCH_GROUP.equals(event.getToForm()) || !event.getPatchedTalkgroups().isEmpty())
{
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mPatchedTable +
" WHERE event_id = ?"))
{
statement.setLong(1, event.getId());
statement.executeUpdate();
}
insertPatchedTalkgroups(connection, event.getId(), event.getPatchedTalkgroups());
}
return true;
}
private void insertPatchedTalkgroups(Connection connection, long eventId, List<PatchedTalkgroup> talkgroups)
throws SQLException
{
if(talkgroups.isEmpty())
{
return;
}
try(PreparedStatement statement = connection.prepareStatement("INSERT INTO " + mPatchedTable +
" (event_id, talkgroup, fq) VALUES (?, ?, ?)"))
{
for(PatchedTalkgroup talkgroup: talkgroups)
{
statement.setLong(1, eventId);
statement.setLong(2, talkgroup.value());
setString(statement, 3, talkgroup.fullyQualified(), LENGTH_ID);
statement.addBatch();
}
statement.executeBatch();
}
}
/**
* Loads the patched talkgroups of the patch group events in the list.
*/
private void loadPatchedTalkgroups(Connection connection, List<EventRecord> events) throws SQLException
{
Map<Long,EventRecord> patchEvents = new HashMap<>();
for(EventRecord event: events)
{
if(IdentifierRecord.FORM_PATCH_GROUP.equals(event.getToForm()))
{
patchEvents.put(event.getId(), event);
}
}
if(patchEvents.isEmpty())
{
return;
}
Map<Long,List<PatchedTalkgroup>> talkgroups = new HashMap<>();
String placeholders = String.join(", ", Collections.nCopies(patchEvents.size(), "?"));
try(PreparedStatement statement = connection.prepareStatement("SELECT event_id, talkgroup, fq FROM " +
mPatchedTable + " WHERE event_id IN (" + placeholders + ") ORDER BY event_id, talkgroup"))
{
int index = 1;
for(Long id: patchEvents.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())
{
patchEvents.get(entry.getKey()).setPatchedTalkgroups(entry.getValue());
}
}
/**
* Binds the event column values to statement parameters 1 - COLUMN_COUNT.
*/
private static void bind(PreparedStatement statement, EventRecord event) throws SQLException
{
int index = 1;
statement.setLong(index++, event.getStartTime());
statement.setLong(index++, event.getEndTime());
statement.setLong(index++, event.getDuration());
statement.setString(index++, event.getEventTypeValue().name());
setString(statement, index++, event.getProtocol(), LENGTH_SHORT);
setString(statement, index++, event.getSystem(), LENGTH_NAME);
setString(statement, index++, event.getSite(), LENGTH_NAME);
setString(statement, index++, event.getChannel(), LENGTH_NAME);
setString(statement, index++, event.getChannelDescriptor(), LENGTH_NAME);
statement.setLong(index++, event.getFrequency());
statement.setInt(index++, event.getTimeslot());
setString(statement, index++, event.getToId(), LENGTH_NAME);
setLong(statement, index++, event.getToValue());
setString(statement, index++, event.getToForm(), LENGTH_SHORT);
setString(statement, index++, event.getToFullyQualified(), LENGTH_ID);
setString(statement, index++, event.getFromId(), LENGTH_NAME);
setLong(statement, index++, event.getFromValue());
setString(statement, index++, event.getFromForm(), LENGTH_SHORT);
setString(statement, index++, event.getFromFullyQualified(), LENGTH_ID);
setString(statement, index++, event.getAliasList(), LENGTH_NAME);
setString(statement, index++, event.getTalkerAlias(), LENGTH_NAME);
setString(statement, index, event.getDetails(), LENGTH_DETAILS);
}
/**
* Creates an event record from the current result set row.
*/
private static EventRecord read(ResultSet rs) throws SQLException
{
EventRecord event = new EventRecord();
event.setId(rs.getLong("id"));
event.setStartTime(rs.getLong("start_time"));
event.setEndTime(rs.getLong("end_time"));
event.setDuration(rs.getLong("duration_ms"));
event.setEventType(rs.getString("event_type"));
event.setProtocol(rs.getString("protocol"));
event.setSystem(rs.getString("system_name"));
event.setSite(rs.getString("site_name"));
event.setChannel(rs.getString("channel_name"));
event.setChannelDescriptor(rs.getString("channel_descriptor"));
event.setFrequency(rs.getLong("frequency"));
event.setTimeslot(rs.getInt("timeslot"));
event.setToId(rs.getString("to_id"));
event.setToValue(getLong(rs, "to_value"));
event.setToForm(rs.getString("to_form"));
event.setToFullyQualified(rs.getString("to_fq"));
event.setFromId(rs.getString("from_id"));
event.setFromValue(getLong(rs, "from_value"));
event.setFromForm(rs.getString("from_form"));
event.setFromFullyQualified(rs.getString("from_fq"));
event.setAliasList(rs.getString("alias_list"));
event.setTalkerAlias(rs.getString("talker_alias"));
event.setDetails(rs.getString("details"));
return event;
}
private List<EventRecord> query(Connection connection, String sql, List<Object> parameters) throws SQLException
{
List<EventRecord> events = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement(sql))
{
bindParameters(statement, parameters);
try(ResultSet rs = statement.executeQuery())
{
while(rs.next())
{
events.add(read(rs));
}
}
}
loadPatchedTalkgroups(connection, events);
return events;
}
@Override
public List<EventRecord> search(Connection connection, EventSearchCriteria criteria, int offset, int limit)
throws SQLException
{
List<Object> parameters = new ArrayList<>();
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " c" + getWhereClause(criteria, parameters) +
" ORDER BY start_time DESC, id DESC LIMIT ? OFFSET ?";
parameters.add(limit);
parameters.add(offset);
return query(connection, sql, parameters);
}
@Override
public long count(Connection connection, EventSearchCriteria criteria) throws SQLException
{
List<Object> parameters = new ArrayList<>();
try(PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " + mTable + " c" +
getWhereClause(criteria, parameters)))
{
bindParameters(statement, parameters);
try(ResultSet rs = statement.executeQuery())
{
return rs.next() ? rs.getLong(1) : 0;
}
}
}
@Override
public long count(Connection connection) throws SQLException
{
return count(connection, EventSearchCriteria.all());
}
/**
* Builds the WHERE clause (with a leading space) for the criteria and adds the parameter values to the list.
*/
private String getWhereClause(EventSearchCriteria criteria, List<Object> parameters)
{
List<String> clauses = new ArrayList<>();
if(!criteria.talkgroup().isEmpty())
{
clauses.add(getIdentifierClause("to", criteria.talkgroup(), TO_TALKGROUP_FORMS, mPatchedTable,
"event_id", parameters));
}
if(!criteria.radio().isEmpty())
{
//A radio can be the FROM identifier or the TO identifier (e.g. unit-to-unit call, page, radio check)
String from = getIdentifierClause("from", criteria.radio(), FROM_RADIO_FORM, null, null, parameters);
String to = getIdentifierClause("to", criteria.radio(), TO_RADIO_FORM, null, null, parameters);
clauses.add("(" + from + " OR (" + TO_RADIO_FORM + " AND " + to + "))");
}
if(criteria.category() != null)
{
clauses.add(criteria.category().getWhereClause());
}
if(criteria.eventType() != null)
{
clauses.add("event_type = ?");
parameters.add(criteria.eventType().name());
}
if(criteria.protocol() != null)
{
clauses.add("protocol = ?");
parameters.add(criteria.protocol().name());
}
if(!criteria.system().isEmpty())
{
clauses.add("LOWER(system_name) LIKE ? ESCAPE '!'");
parameters.add(getLikePattern(criteria.system()));
}
if(!criteria.details().isEmpty())
{
clauses.add("LOWER(details) LIKE ? ESCAPE '!'");
parameters.add(getLikePattern(criteria.details()));
}
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);
}
@Override
public List<EventRecord> readPage(Connection connection, long afterId, int limit) throws SQLException
{
List<Object> parameters = new ArrayList<>();
parameters.add(afterId);
parameters.add(limit);
return query(connection, "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE id > ? ORDER BY id LIMIT ?",
parameters);
}
@Override
public Set<String> getTransferKeys(Connection connection) throws SQLException
{
Set<String> keys = new HashSet<>();
List<EventRecord> page = readPage(connection, 0, 5000);
while(!page.isEmpty())
{
for(EventRecord event: page)
{
keys.add(event.getTransferKey());
}
page = readPage(connection, page.getLast().getId(), 5000);
}
return keys;
}
@Override
public int deleteStartedBefore(Connection connection, long startedBefore) throws SQLException
{
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mTable +
" WHERE start_time < ?"))
{
statement.setLong(1, startedBefore);
return statement.executeUpdate();
}
}
@Override
public int deleteAll(Connection connection) throws SQLException
{
try(PreparedStatement patched = connection.prepareStatement("DELETE FROM " + mPatchedTable);
PreparedStatement events = connection.prepareStatement("DELETE FROM " + mTable))
{
patched.executeUpdate();
return events.executeUpdate();
}
}
@Override
public String getSchema()
{
return mSchema;
}
}

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.database.event;
import io.github.dsheirer.database.call.IdentifierFilter;
import io.github.dsheirer.module.decode.event.DecodeEventType;
import io.github.dsheirer.protocol.Protocol;
import java.util.List;
import java.util.Locale;
/**
* Search criteria for the events table. Empty or null values don't filter.
*
* @param talkgroup filter for the TO talkgroup or patch group, including the talkgroups patched into a patch group
* @param radio filter for a radio identifier in either the FROM or the TO role (e.g. a unit-to-unit call or a page)
* @param category of the event type, or null for any category
* @param eventType decode event type, or null for any type
* @param protocol or null for any protocol
* @param system text that the system name contains
* @param details text that the event details contain
* @param startTime earliest event start time, or 0
* @param endTime latest event start time, or 0
*/
public record EventSearchCriteria(IdentifierFilter talkgroup, IdentifierFilter radio, EventCategory category,
DecodeEventType eventType, Protocol protocol, String system, String details,
long startTime, long endTime)
{
public EventSearchCriteria
{
talkgroup = talkgroup == null ? IdentifierFilter.none() : talkgroup;
radio = radio == null ? IdentifierFilter.none() : radio;
system = clean(system);
details = clean(details);
}
/**
* Criteria that match all events
*/
public static EventSearchCriteria all()
{
return new EventSearchCriteria(null, null, null, null, null, null, null, 0, 0);
}
private static String clean(String value)
{
return value == null ? "" : value.trim();
}
/**
* Indicates if these criteria match all events
*/
public boolean isEmpty()
{
return talkgroup.isEmpty() && radio.isEmpty() && category == null && eventType == null && protocol == null &&
system.isEmpty() && details.isEmpty() && startTime == 0 && endTime == 0;
}
/**
* Indicates if the event matches these criteria, for live events that aren't in the database yet. Matches the
* same events as the database search.
*/
public boolean matches(EventRecord event)
{
if(!talkgroup.isEmpty() && !talkgroup.matches(event, event.getToId(), event.getToValue(),
event.getToFullyQualified(), event.isToTalkgroup(), event.getPatchedTalkgroups()))
{
return false;
}
if(!radio.isEmpty() && !radio.matches(event, event.getFromId(), event.getFromValue(),
event.getFromFullyQualified(), event.isFromRadio(), List.of()) && !(event.isToRadio() &&
radio.matches(event, event.getToId(), event.getToValue(), event.getToFullyQualified(), true, List.of())))
{
return false;
}
if(category != null && !category.contains(event.getEventTypeValue()))
{
return false;
}
if(eventType != null && !eventType.name().equals(event.getEventType()))
{
return false;
}
if(protocol != null && !protocol.name().equals(event.getProtocol()))
{
return false;
}
if(!system.isEmpty() && !contains(event.getSystem(), system))
{
return false;
}
if(!details.isEmpty() && !contains(event.getDetails(), details))
{
return false;
}
if(startTime > 0 && event.getStartTime() < startTime)
{
return false;
}
return endTime <= 0 || event.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,96 +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.event;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
/**
* Storage operations for decode events in one database schema. Each method uses the connection from the caller so
* that the caller controls pooling and transactions.
*/
public interface IEventRepository
{
/**
* Inserts the event and assigns the generated row id to the event.
* @return generated row id
*/
long insert(Connection connection, EventRecord event) throws SQLException;
/**
* Inserts the events in a batch without retrieving the generated ids.
*/
void insertBatch(Connection connection, List<EventRecord> events) throws SQLException;
/**
* Updates the existing event row identified by the event's id.
* @return true if the row exists and was updated
*/
boolean update(Connection connection, EventRecord event) throws SQLException;
/**
* Searches for events matching the criteria, newest first.
* @param offset of the first row to return
* @param limit maximum rows to return
*/
List<EventRecord> search(Connection connection, EventSearchCriteria criteria, int offset, int limit)
throws SQLException;
/**
* Count of events matching the criteria
*/
long count(Connection connection, EventSearchCriteria criteria) throws SQLException;
/**
* Total number of event rows
*/
long count(Connection connection) throws SQLException;
/**
* Reads a page of events in id order, for transferring events between databases.
* @param afterId only return events with an id greater than this value
* @param limit maximum number of events
*/
List<EventRecord> readPage(Connection connection, long afterId, int limit) throws SQLException;
/**
* Transfer keys (see {@link EventRecord#getTransferKey()}) of all events, for skipping events that already exist
* when appending.
*/
Set<String> getTransferKeys(Connection connection) throws SQLException;
/**
* Deletes the events that started before the time, for the event age-off rule.
* @return count of events deleted
*/
int deleteStartedBefore(Connection connection, long startedBefore) throws SQLException;
/**
* Deletes all events (and their patched talkgroups), for restoring a backup.
* @return count of events deleted
*/
int deleteAll(Connection connection) throws SQLException;
/**
* Schema name
*/
String getSchema();
}

View File

@@ -271,26 +271,6 @@ public abstract class C4FMSymbolProcessor
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.
*/
@@ -426,11 +406,6 @@ public abstract class C4FMSymbolProcessor
symbolsSinceLastSync++;
if(symbolsSinceLastSync == getSyncInactivityTimeoutSymbolCount())
{
syncInactivityTimeout();
}
//Clear synchronized state when we miss a sync period.
if(mSynchronized && symbolsSinceLastSync > getMaxMessageDibitLength())
{

View File

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

View File

@@ -79,11 +79,9 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
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
* being transformed. Channel output processors copy their channels from a batch instead of retaining it, so no
* other batches are held.
* Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batches queued for channel output.
*/
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
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 static final double CHANNEL_OVERSAMPLING = 2.0;
private static final int POLYPHASE_CHANNELIZER_TAPS_PER_CHANNEL = 9;
/**
* 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 static final int MAXIMUM_QUEUED_NATIVE_BUFFERS = 500;
private Broadcaster<SourceEvent> mSourceEventBroadcaster = new Broadcaster<>();
private TunerController mTunerController;
@@ -83,7 +78,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private ComplexPolyphaseChannelizerM2 mPolyphaseChannelizer;
private ChannelSourceEventListener mChannelSourceEventListener = new ChannelSourceEventListener();
private NativeBufferReceiver mNativeBufferReceiver = new NativeBufferReceiver();
private Dispatcher<INativeBuffer> mBufferDispatcher;
private Dispatcher mBufferDispatcher;
private boolean mRunning = true;
/**
@@ -104,21 +99,10 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
mChannelCalculator = new ChannelCalculator(tunerController.getSampleRate(), channelCount,
tunerController.getFrequency(), CHANNEL_OVERSAMPLING);
mBufferDispatcher = new Dispatcher<>("sdrtrunk polyphase buffer processor", 10, INativeBuffer::sampleCount,
getMaximumQueuedSamples(tunerController.getSampleRate()));
mBufferDispatcher = new Dispatcher("sdrtrunk polyphase buffer processor", 10, MAXIMUM_QUEUED_NATIVE_BUFFERS);
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.
*/
@@ -294,7 +278,6 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
double sampleRate = sourceEvent.getValue().doubleValue();
int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate);
mChannelCalculator.setRates(sampleRate, channelCount);
mBufferDispatcher.setMaximumQueuedWeight(getMaximumQueuedSamples(sampleRate));
break;
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_LOCKED:
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_UNLOCKED:

View File

@@ -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
* 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
* dispatcher thread at that same batch.
* applies the configuration changes on its own dispatcher thread.
* @param channelCalculator for updates
* @param filterManager for updates
* @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
* 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.util.Dispatcher;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
@@ -35,20 +34,12 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
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.
*/
private static final int MAXIMUM_QUEUED_BATCHES = 50;
/**
* 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 Dispatcher<QueuedChannelResults> mChannelResultsDispatcher;
private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>();
private final AtomicLong mBatchSequence = new AtomicLong();
private HeartbeatManager mHeartbeatManager;
@@ -69,45 +60,25 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
mInputChannelCount = inputChannelCount;
//Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate)
mHeartbeatManager = heartbeatManager;
mChannelSamplesDispatcher = new Dispatcher<>(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelSamplesDispatcher.setListener(queued -> {
mChannelResultsDispatcher = new Dispatcher(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelResultsDispatcher.setListener(queued -> {
try
{
applyPendingUpdates(queued.sequence());
mCurrentSampleTimestamp = queued.timestamp();
process(queued.samples(), queued.blockCount());
mCurrentSampleTimestamp = queued.channelResults().getTimestamp();
process(queued.channelResults());
}
catch(Throwable t)
{
mLog.error("Error processing channel samples", t);
mLog.error("Error processing channel results", t);
}
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
* 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
public void start()
{
mChannelSamplesDispatcher.start();
mChannelResultsDispatcher.start();
}
@Override
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
public void receiveChannelResults(ChannelResultsBatch channelResults)
{
long sequence = mBatchSequence.incrementAndGet();
channelResults.retain();
if(!mChannelSamplesDispatcher.isRunning())
if(!mChannelResultsDispatcher.offer(new QueuedChannelResults(channelResults, mBatchSequence.incrementAndGet())))
{
return;
}
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);
channelResults.release();
}
}
/**
* 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)
{
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);
public abstract void process(ChannelResultsBatch channelResults);
@Override
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
* sequence of received batches.
* Channel results batch and its position in the 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.

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
* 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;
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,6 +29,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{
private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class);
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
@@ -54,7 +55,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{
StringBuilder sb = new StringBuilder();
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");
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
//an I/Q pair
setChannelOffsets(indexes.get(0) * 2);
int channelOffset = indexes.get(0) * 2;
enqueueUpdate(() -> mChannelOffset = channelOffset);
}
@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
* indicate when a buffer is fully assembled.
* Extract the channel from the channel results array and pass to the assembler. The assembler will
* 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 blockCount number of blocks
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
*/
@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]);

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
* 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;
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,6 +29,8 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{
private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class);
private TwoChannelMixerAssembler mMixerAssembler;
private int mChannelOffset1;
private int mChannelOffset2;
/**
* 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();
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());
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
//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
* I/Q sample set to the complex sample listener.
* Extract the channel from the channel results array, apply frequency translation, and deliver the
* 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 blockCount number of blocks
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
*/
@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
//channelizer dispatches even-sized batches, so the index within the batch carries the absolute block parity.
for(int x = 0; x < blockCount; x++)
{
int block = x * 4;
int block = x * blockLength;
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
{
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())

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,51 @@
package io.github.dsheirer.dsp.gain;
public class NonClippingGain
{
private float mGain;
private float mMaxValue;
/**
* Applies a fixed gain value to the float samples.
*
* @param gain value
* @param maxValue max absolute value to prevent clipping ( 0.0 to 1.0 )
*/
public NonClippingGain( float gain, float maxValue )
{
mGain = gain;
mMaxValue = maxValue;
}
/**
* Applies gain to the sample
*/
public float apply( float sample )
{
float adjusted = sample * mGain;
if( adjusted > mMaxValue )
{
adjusted = mMaxValue;
}
if( adjusted < -mMaxValue )
{
adjusted = -mMaxValue;
}
return adjusted;
}
/**
* Applies gain to the sample array
*/
public float[] apply( float[] samples )
{
for( int x = 0; x < samples.length; x++ )
{
samples[ x ] = apply( samples[ x ]);
}
return samples;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -68,29 +68,6 @@ public class Golay24
*/
public static int checkAndCorrect(CorrectedBinaryMessage message, int startIndex)
{
//The correction below indexes the word from bit 0 and takes the parity over the whole message, so it is only
//correct for a message that is exactly the 24-bit word. Decode any other word in a 24-bit copy.
if(startIndex != 0 || message.size() != 24)
{
CorrectedBinaryMessage word = new CorrectedBinaryMessage(24);
int original = message.getInt(startIndex, startIndex + 23);
word.load(0, 24, original);
int result = checkAndCorrectWord(word);
int corrected = word.getInt(0, 23);
message.load(startIndex, 24, corrected);
message.incrementCorrectedBitCount(Integer.bitCount(original ^ corrected));
return result;
}
return checkAndCorrectWord(message);
}
/**
* Error detection and correction of a message that is exactly one 24-bit word.
*/
private static int checkAndCorrectWord(CorrectedBinaryMessage message)
{
int startIndex = 0;
boolean parityError = message.cardinality() % 2 != 0;
int syndrome = getSyndrome(message, startIndex);

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