Compare commits

...

51 Commits

Author SHA1 Message Date
denny
6dc1f0fdcb #2742 Calls View with database support
Tab page size preference (50, 100, 250, 500; default 500) next to the paging controls.
Calls tab call type search filter.
- Type filter (group, patch, private, telephone, other) in the Calls search bar, applied when selected.
- CallType provides the SQL condition on the stored identifier forms, using the same rules as the Type column.
#2742 Calls tab default column order puts protocol, system, site and channel at the end.
#2742 Call type test.
#2742 Calls tab shows the call type: group, patch, private or telephone.
- CallType is derived from the stored TO and FROM identifier forms, so existing calls have a type without a schema
  change.  Telephone interconnect calls (telephone number TO or FROM) show as Telephone.
- Calls tab: Type column.
#2742 Patch group calls store their patched talkgroups so a talkgroup search finds the calls it was patched into.
- Schema version 2 adds the patched_talkgroups table (call id, talkgroup, fully qualified address), deleted with
  the call.  Existing version 1 databases are upgraded automatically at startup.
- The call manager captures the patched talkgroups (they can change during the call); transfers copy them.
- TO searches by talkgroup value or talkgroup alias match the patch group and its patched talkgroups, in the
  database and for live calls.
- Calls tab: Patched column lists the patched talkgroups with their current aliases.
#2742 Calls tab replays recordings through the audio channels.
- Replay uses the sdrtrunk audio output and channels instead of a separate JavaFX media player: an idle channel
  (left first), otherwise the left (or mono) channel, which drops the live call it is playing.  Live calls aren't
  assigned to a replaying channel and queued calls play after the replay.
- RecordingReader decodes MP3 (LAME decoder; MPEG-2/2.5 frame size fix) and WAVE recordings to 8 kHz audio.
- ReplaySource supports pause, seek and stop; the Calls player keeps its controls and auto-play next.
- Playback events and the Calls tab Playing column show replays (history icon); the audio panel shows REPLAY.
- Playing row channel edge is drawn as a background layer so the row's cells stay aligned with other rows.
- HikariCP and MariaDB driver logging limited to INFO.
- javafx.media removed from the runtime image modules.
#2742 Calls tab shows which calls are playing on each audio channel.
- Audio segments have a unique id, which the call manager uses as the call key.
- Audio channels report the call they start and stop playing; the audio playback manager publishes these as
  ChannelPlayback events (re-wired when the output device changes) with a snapshot for late listeners.
- Calls tab: Playing column with a LEFT/RIGHT/MONO chip and a channel-colored row tint and edge for calls that are
  playing.  Calls reloaded from the database keep their call key so a call that ended but is still playing stays
  marked.
- Audio panel channel tags use the same colors (left/mono blue, right orange).
#2742 Replace AudioRecordingManager with CallManager and CallRecorder.
- CallManager (new call package) is the single audio segment listener for calls.  It manages each call's
  life-cycle: creates and updates the call record, saves it to the call database and broadcasts it to call
  listeners (Calls tab, future external subscribers).
- CallRecorder (record package) holds the streaming recording logic and file naming.  The call manager creates one
  CallRecorder.Recording per call, which fills in the recording details of the call record.
- DatabaseManager remains storage only.  No behavior change.
#2742 Record all calls by default; delete duplicate and Do Not Monitor calls after a retention period.
- Record preferences: 'Record all calls' (default on).  When off, only calls with an alias record option are
  recorded, as before.
- Duplicate calls are no longer discarded immediately.  Duplicate calls, and Do Not Monitor calls that no alias marked
  for recording, are deleted with their recordings after a configurable retention period (30 minutes to 7 days, or
  never; default 1 hour) set in the Call Database preferences.  Calls store whether an alias requested recording.
- The duplicate call 'Recording' suppression switch is replaced by a note pointing to the retention setting.
- Age-off runs every 5 minutes.
#2742 Calls store the alias list name and look up TO/FROM aliases from the current alias list.
- The calls table no longer stores TO/FROM alias names.  It stores the alias list name, the TO/FROM identifier
  forms and the fully qualified (roaming) addresses, and the Calls tab looks up the aliases in the current alias
  list when it displays a call, so historical calls show the latest alias values.
- AliasList lookups by protocol, value and fully qualified address, sharing the identifier matching rules.
- TO and FROM search fields drop down a filtering list of talkgroup or radio aliases.  Selecting an alias filters by
  the alias's alias list and its talkgroup/radio values, ranges and fully qualified identifiers.  Typed text still
  matches the identifier.  The alias search field is replaced by a talker alias search.
#2742 Call database, Calls tab, call audio age-off and talkgroup hold.
- Call database: built-in H2 (application 'db' folder) by default, with optional MariaDB or PostgreSQL.  The
  sdrtrunk schema and tables are installed and versioned automatically.  Engine differences are isolated in
  IDatabaseDialect implementations and call storage behind ICallRepository.
- Switching databases asks whether to transfer the existing calls and, when the target schema already has
  sdrtrunk calls, whether to append, clear, or create a separately named schema.
- Every call gets a database row when it starts, updated as identifiers change and when the call completes.
- Call recordings are written while the call is in progress (streaming MP3/WAVE), so the recording file and its
  name are stored with the call from the start.  MP3 ID3 metadata is rewritten in reserved space at the end.
- Calls tab after Now Playing: search by talkgroup, radio, alias, protocol, system and date range, live
  duration of calls in progress, built-in recording player with auto-play, context menu to hold a talkgroup.
- Call Database preferences: database selection, test connection, and age-off rules (age and total size),
  each deleting the call and recording or only the recording.  The status bar recordings meter uses the size
  rule limit when enabled.
- Talkgroup hold: Hold button on each audio channel steers the held talkgroup (and patch groups that include
  it) to that channel, keeps other calls off it, plays it even when do-not-monitor, with an optional idle
  auto-release in Playback preferences.
2026-11-21 07:48:36 -05:00
Denny Sheirer
164e193ef0 #2740 JMBE version 3.0.0 library with support for EDACS PROVOICE IMBE codec. (#2741)
- JmbeAudioModule synthesizes from host corrected frames (jmbe-api CorrectedIMBEFrame/CorrectedAMBEFrame) when the
  codec is IAudioCodecV3, and falls back to the raw frame bytes for JMBE version 1 and 2 libraries
- LDUMessage, P25P2 AbstractVoiceTimeslot, DMR VoiceMessage and NXDN Audio cache their corrected voice frames
- P25P1, P25P2, DMR, NXDN audio modules and MBECallSequenceConverter only correct frames when the codec supports it
- DMR queued voice frames carry the optional corrected frame
- Error correct MBE voice frames in sdrtrunk and synthesize with JMBE V3 codecs

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-21 05:31:04 -05:00
Denny Sheirer
18f5df142e #2729 Now Playing channel details use a consistent, column-aligned activity summary layout (#2737)
Decoder activity summaries used tab characters in a proportional-font text area, so talker alias and other
listings misaligned when values were shorter or longer.  Adds a shared ActivitySummary builder (title, sections,
aligned label/value fields and auto-sized tables) used by every decoder, and shows the details in a monospace font.

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 03:40:37 -05:00
Denny Sheirer
14c53f2694 #2738 Master mute disables the channel audio level meters (#2739)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-21 02:57:20 -05:00
Denny Sheirer
77e9e97dd1 #2623 DMR decoder resets the detected sync mode after inactivity (#2736)
On sparse channels, noise false syncs accumulated across long idle periods
and permanently locked the sync mode monitor to the wrong mode (ie
DIRECT_ONLY), so the repeater's base station syncs were never detected
again until the channel was restarted.

- Only sync detections that follow a previous sync within the max sync
  interval are counted toward the sync mode.
- Restore AUTOMATIC sync mode after 5 seconds without a sync detection,
  unless the mode is locked (ie BASE_ONLY for traffic channels).

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-21 02:22:39 -05:00
Denny Sheirer
aad36b4463 #2733 Baseband recorder labels show both .wav and .iq formats (#2735)
Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:17:50 -05:00
Denny Sheirer
0298c0fc7e #2731 Audio panel clenup to remove wasted space in left hand side of panel (#2732)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-21 01:37:27 -05:00
Denny Sheirer
cfc9df4318 #2723 Full JavaFX application. (#2725)
* Removes the FlatLaf, JIDE, MigLayout and jiconfont-swing dependencies; the runtime image no longer includes javafx.swing.
* Removes the Swing channelizer developer viewers and the Swing spectrum panel; the symbol, sync and filter debug viewers are plain JavaFX windows.
* ChannelMapModel is no longer a Swing list model; removes unused Swing color menu items and models.
* Removes the Swing image methods from the icon classes; icons load as JavaFX images.
* Themes no longer use FlatLaf: each theme stores its palette and ThemeManager styles JavaFX only.
* The channel auto-start countdown, the event and message filter editor and the alias and deadlock alerts are now JavaFX.  The main window only stores split pane divider positions after the user drags a divider.
* Main window converted to JavaFX, with a spectrum and waterfall display that can be hidden.
* A hidden spectrum and waterfall is disposed so that it uses no processing or memory.  Show or hide it from the View menu, Ctrl+Shift+S, the display settings panel or the bar shown while it is hidden.
* Streaming status panel converted to JavaFX with status chips, a summary, configurable columns and a shortcut to the streaming editor.
* BroadcastModel is no longer a Swing table model.
* Audio panel converted to JavaFX and redesigned as a prominent playback display at the top of the main window.
* Mono and stereo outputs show one display per channel with the TO alias, icon and color, the FROM radio, system/site/channel, elapsed time, a level meter and per-channel mute. The master section has mute all, volume and audio device settings.
* Renames JavaFxWindowManager to WindowManager and removes its standalone launcher and the remaining Swing-era comments.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 07:23:42 -05:00
Denny Sheirer
8431fe66ad #2717 Tuners tab converted to JavaFX with a new frequency control. (#2720)
- New FrequencyControl replaces JFrequencyControl: MHz to 1 Hz, hover a digit and scroll or click its upper/lower half to step it (with carry, clamped to the tuner's range), or type a frequency (e.g. 851.0125) and press Enter.  Arrow keys move between digits and step them.  Copy/paste supported.
- Tuners tab redesigned: tuner list with status pills and configurable columns, Add Tuner menu, and a sectioned editor (header with status, enable switch, spectrum/record/restart; Tuning; Gain; Options; Frequency Correction; collapsible Frequency Limits).
- All tuner editors converted to JavaFX with their full set of controls.  RSP editors share option bindings in RspTunerEditor.
- Add recording and network tuner dialogs converted to JavaFX dialogs.
- DiscoveredTunerModel is no longer a Swing table model.
- Fixes: FCD Pro gain/phase correction loaded swapped; RSPdx saved the FM notch as the DAB notch and never applied the HDR bandwidth; RSP2 external reference output and network tuner PPM weren't saved; Airspy/HydraSDR gain mode changes now apply the mode's gains.

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:36:12 -05:00
Denny Sheirer
d53b2664ef #2721 Gradle run task keeps the default JVM arguments when adding the splash screen (#2722)
Calling jvmArgs on the run task replaced the applicationDefaultJvmArgs convention, dropping
--add-modules=jdk.incubator.vector, --enable-preview and the other defaults.  The splash argument is now
added through a jvmArgumentProvider.

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

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

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

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 03:06:50 -05:00
Wahaj18
6d89a604c3 Copy selected event and message rows with Ctrl-C (#2691)
The JavaFX Now Playing tables lost the Swing JTable copy action, so Ctrl-C
in the Events and Messages tabs did nothing. The history table now allows
selecting several rows and copies them to the clipboard, one line per row
with the visible column values separated by tabs, as the Swing table did.

Fixes #2687
2026-11-19 02:48:03 -05:00
GTR8000
3473150ee9 Preserve user radio aliases outside the Talker Alias group (#2689)
Limit automatic renaming to the existing managed group. Keep exact-match user aliases outside that group unchanged without creating duplicates, while retaining confirmation and multi-identifier protections for managed aliases. Explain moving aliases out of the group in the tooltip and cover custom, ungrouped, managed and moved aliases in regression tests.
2026-11-18 03:47:35 -05:00
Denny Sheirer
ff6e2bd710 #2688 NXDN Type-D audio fixes. New call audio or late call audio correctly handled. Call response (CALL_RESP) now parsed correctly per TS 1-E Figure 6.4-21 to handle multi-system formats. (#2692)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-18 03:30:52 -05:00
Denny Sheirer
f302d46be1 #2672 Polyphase channelizer enhancements to address buffer sizing and management
#2672 Bounds the polyphase buffer queue by sample duration instead of buffer count

The polyphase buffer processor queue was capped at 500 native buffers, which is only about 85 ms of samples for an RSP at 6 MSPS (about 1,000 samples per buffer) versus about 6.8 s for an RTL-SDR (32,768 samples per buffer).  Short processing stalls overflowed the queue and dropped buffers on RSP tuners.

- Dispatcher: adds a weight-bounded queue option (element weigher plus an  adjustable maximum queued weight).  Elements count toward the weight until  the listener has processed them.
- PolyphaseChannelManager: bounds the buffer queue at 1 second of samples and  updates the bound when the tuner sample rate changes.
- RspNativeBuffer: sampleCount() returned twice the complex sample count.  This  also corrects the tuner sample drop monitor and the spectral display buffer manager for RSP tuners.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-18 03:05:39 -05:00
Denny Sheirer
f47479b8d4 #2681 JavaFX Map Redesign
#2681 Map tab as a JavaFX component

Replaces the Swing JXMapViewer map with a pure JavaFX canvas tile map in gui/map:
OpenStreetMap tiles with a memory and disk cache, track, Radio Reference site and
user location layers, the site hover card and context menu, and the map controls.
Removes the bundled SwingX map viewer copy and moves GeoPosition to the map package.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-18 02:29:58 -05:00
Denny Sheirer
bc7dd201ab #2673 User preferences font scaling not working with display styling/theme updates (#2677)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-18 02:12:32 -05:00
Denny Sheirer
c46b80b06b Update README.md (#2686)
Adds badget for google groups
2026-11-17 06:51:15 -05:00
Denny Sheirer
7f1e7d9cd2 #2q683 Now playing channel adds new Alias List column (#2684)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 03:56:36 -05:00
Denny Sheirer
7a7364839b #2680 Alias List optionally auto-adds/upates radio ID to talker alias value. Enable the feature in the playlist editor in the channel config for protocols that produce talker alias (P25, NXDN, DMR). (#2682)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 03:52:59 -05:00
Denny Sheirer
2213544eec #2676 Alias List optionally tracks radio reference system with optional auto-update for talkgroup alias changes. (#2679)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 03:24:29 -05:00
Denny Sheirer
feeedb7c29 #2671 Spectral display right click on signal context menu radio reference options. Unifies the popout card to channels in order: 1) in playlist and enabled, in playlist, in radio reference, ordered by distance from the user's my location (#2675)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 02:25:50 -05:00
Denny Sheirer
6dd06288ac #2669 Adds System & Site columns to Now Playing, hidden by default (#2670)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:34:58 -05:00
Denny Sheirer
5fd469c402 #315 Adds Tuner column to Now Playing channels view (#2668)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:19:28 -05:00
Denny Sheirer
0bc5d6db64 #2620 Fix NPE in headless mode (#2667)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:04:33 -05:00
Denny Sheirer
80754558d6 #2662 Tuners monitor sample rate and log on excessive dropped samples. (#2663)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:02:11 -05:00
Denny Sheirer
2f9d52a56a #2665 Updates the README (#2666)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:01:40 -05:00
Denny Sheirer
5474a5a448 #2660 Now Playing Update With Talker Column & Column Management (#2661)
* #2660 Now Playing panel with events and messages are all recreated as JavaFX panels

* #2660 Talker alias cleanup across the decoders

* #2660 Talker alias cleanup across the decoders

---------

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 07:43:04 -05:00
Denny Sheirer
c93d099742 #2658 DMR additional error detection and correction enhancements (#2659)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 04:04:34 -05:00
Denny Sheirer
be0966653b #2656 DMR Hamming and BPTC error detection and correction algorithm enhancements (#2657)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 03:46:55 -05:00
jpmetal
26a24fc6ad Fix the DMR EMB QR(16,7,6) codeword table (#2645)
All 64 entries with bit 15 set differed by an XOR of 0x0060 from the
codewords derived from the generator matrix in TS 102 361-1 table B.12, so
error-free EMBs for colour codes 8-15 were flagged invalid by the hard
decoder and "corrected" by the soft decoder.  Single bit errors in those
codewords, though within the correction capability, were reported as
uncorrectable for 13 of the 15 bit positions (87 %).

Co-authored-by: modificaz <jpmetal@freemail.gr>
2026-11-15 03:46:24 -05:00
Jared Szechy
9deabd0dcc Network tuner support - rtl_tcp (#2471)
* Add network tuner dialog

* wip: network tuner configs

* wip stash

* working tcp solution

* fix copyright headers

* fix: resolve rebase conflicts from jRTL library changeover

- Drop redundant JFrequencyControl digit-sizing fix now that upstream
  fixes the same issue via setColumns(1)
- Mark SUPPORTED_NETWORK_TUNERS final to match the new EnumSet style
- Replace removed SampleRate.getClosest() with a local nearest-match
  helper in NetworkTunerEditor

* Add mise config
2026-11-15 03:32:02 -05:00
Denny Sheirer
2db41393dc #2654 NXDN Audio Removes Additive Non-Clipping Gain and uses JMBE AGC only (#2655)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 02:15:33 -05:00
Denny Sheirer
29a10edf03 #2652 DMR audio module checks voice messages for at least one CRC-valid audio frame before processing audio and purges any enqueued audio on voice header to prepare for the upcoming call (#2653)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 01:47:46 -05:00
Denny Sheirer
5bce541631 #2641 Enhanced radio reference integration. With a premium subscription and when you set your location on the map, the Spectral display includes radio reference layer that presents popup card in the spectrum that shows candidate systems or frequencies ordered by distance from your location. Background thread builds an offline cache of data to support this. Map plots this cache as tower pins on the map and you can hover and active site frequencies from the map. (#2642)
Updates sdrtrunk to use latest radio reference api jar.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-14 09:37:29 -05:00
Denny Sheirer
9641d2ef59 #736 New JavaFX spectral display and waterfall for both tuner and channel spectrums. (#2637)
* Popout configuration panel (top-left of display)
* Themed color support
* Reworked signal averating/smoothing
* Optional decibel overlay with corrected decibel calculations
* Integrated noise floor slider in  channel view
* Traffic channel overlays
* Popup channel information when hovering over playlist channels.
* Removes legacy swing components.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 07:30:31 -05:00
Denny Sheirer
73fc85aa76 #1045 P25 encrypted call ignore setting. Cleanup several other errors. (#2636)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 05:14:45 -05:00
Thinline Dynamic Solutions
aad971db9c Add Thinline Radio completed-call upload stream type (#2626)
Same /api/call-upload flow as Rdio Scanner, with its own configuration and
playlist editor. Reuses RdioScannerBroadcaster.

Co-authored-by: Michael Chambers <michaelchambers@Michaels-Mac-mini.local>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 04:54:08 -05:00
Denny Sheirer
73d3238644 #2634 Gradle build now uses git tag for versioning (#2635)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 03:32:08 -05:00
farewell-ladmin
4626d56730 #2392 P25P1: trust HDU/LDU2 algorithm ID over LC service options encryption flag (#2477)
Some radios set the encryption flag in the service options of the LDU1 Group
Voice Channel User link control while transmitting clear voice; the HDU and
LDU2 encryption sync parameters report ALGID 0x80 (unencrypted) for the same
call. Example (CoMIRS Boston, TG 2217, valid LCs from several radios):

  HDU   TALKGROUP:2217 UNENCRYPTED
  LDU1  GROUP VOICE CHANNEL USER FM:64008 TO:2217 SERVICE OPTIONS:PRI4 ENCRYPTED CIRCUIT
  LDU2  UNENCRYPTED

P25P1DecoderState broadcast State.ENCRYPTED for each such LDU1 and State.CALL
for each LDU2, so the channel state flapped between CALL and ENCRYPTED (and on
upstream, where ENCRYPTED cannot change back to CALL, the call stays muted).

Track the per-call encryption state from the HDU header and LDU2 algorithm ID
(reset at TDU/TDULC). When it is known to be unencrypted, clear the encryption
flag on the LC service options before using them for the channel state and
traffic channel call event. Genuinely encrypted calls are unaffected, and when
the algorithm ID is not yet known (late entry before the first LDU2) the LC
service options are used as before.

Adds VoiceServiceOptions.createUnencrypted(ServiceOptions) to copy service
options with only the encryption flag cleared.

Verified by driving P25P1DecoderState with HDU/LDU1/LDU2/TDU sequences
reproducing the field logs: state events go from C C C E C E C to all CALL;
encrypted calls (ALGID 0x84) still report ENCRYPTED throughout.


Claude-Session: https://claude.ai/code/session_01FRdfTvgcdBvwkipdfP8qxy
(cherry picked from commit 2ef3c9d02176871577d38f8afd0fa3c32fb92a58)

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-13 02:56:00 -05:00
Christopher Smith
1a90eaf6c6 P25P1: decode unconfirmed data PDUs with a packet data SAP as IP packets (#2506)
PDU header format 0x15 is the generic unconfirmed data header; unconfirmed
multi-block trunking control (UMBTC) is only its trunking control SAP
(61/63) use.  PDUHeaderFactory built a plain PDUHeader for every 0x15
header and PDUMessageFactory sent every such sequence to createUMBTC(), so
outbound unconfirmed IP data (SNDCP RF UNCONFIRMED DATA with SAP 0, 4 or
6) was logged raw as

  PDU HEADER FORMAT:UNCONFIRMED MBTC UNCONFIRMED VENDOR:STANDARD TO LLID:n
  DATA BLOCKS:4 MSG:4100450000...

while the confirmed equivalent (format 0x16) was decoded as IPPKT with
its LRRP / ARS payload.

- PDUHeaderFactory: build a PacketHeader for a 0x15 header whose SAP is
  UNENCRYPTED_USER_DATA, PACKET_DATA or SNDCP_PACKET_DATA_CONTROL.  Other
  SAPs, including trunking control 61/63, keep the plain PDUHeader.
- PDUMessageFactory: route a 0x15 sequence whose header is a PacketHeader
  through createPacketData(); everything else stays on the UMBTC path.

No payload changes are needed: PacketMessage already sizes unconfirmed
data blocks at 12 octets, and the header fields it uses (SAP, pad octet
count, data header offset) sit at the same bit positions in the confirmed
and unconfirmed headers.  The ARS RegistrationAcknowledgement parser only
reads the extension octet, so the 5-octet trailer (0x04 + 32-bit time)
some systems append does not affect it.

Adds PDUMessageFactoryTest, built from two unconfirmed PDUs captured on a
Motorola P25 Phase 1 system (ARS registration acknowledgements to UDP
port 4005, one with the trailer), plus header routing checks for SAP
0/4/6, SAP 61/63 and the confirmed 0x16 header.

Co-authored-by: csmith_ai <carrottop@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 02:42:53 -05:00
Christopher Smith
fbc54a38dd LRRP: decode request token values as 7-bit varints and correct request token names (#2507)
Motorola LRRP request tokens that carry an integer (trigger interval
0x31, trigger distance 0x78 and the unknown parameters 0x42 / 0x44)
encode it as a 7-bit variable length integer: each byte holds seven
value bits, most significant group first, and the high bit of a byte
flags a continuation byte.  The parser read a single byte, so a real
triggered location start request

  09 11 22 03 FF FF EE 52 44 64 42 9C 10 62 57 34 31 84 58

was logged as

  ID:15663103 TRIGGER ON GPIO TRIGGER EVERY:132 SECS REQUESTED TOKENS
  [TIME,REQUEST-64,REQUEST-62,HORIZONTAL DIRECTION,TIMESTAMP,
  UNRECOGNIZED(10,44,58,9C)]

and now decodes to

  ID:FFFFEE PERIODIC INTERVAL:600 SECS PARAM-42:3600 PARAM-44:100
  REQUESTED TOKENS [TIME,HORIZONTAL SPEED,HORIZONTAL DIRECTION]

The encoding and the token names follow node-dmr-lib (LRRP.js
parseLRRPInt/toLRRPInt and its quoted TRBONet captures, DMRConst.js)
and Moto.Net (LRRPPacket.cs "using VLQ for most of the fields").

- Add VarInt, a shared 7-bit varint reader, and VarIntToken, a token
  base class whose byte length is measured from the value and bounded
  by the remaining payload.  Use them for 0x31, 0x78, 0x42 and 0x44.
- Add TokenType.fromRequestValue(): 0x34 is the periodic trigger flag
  in a request and the timestamp in a response.  TokenFactory accepts
  the resolved TokenType so the request path is not re-resolved.
- Rename request tokens: 0x31 TRIGGER_INTERVAL (TriggerInterval),
  0x4A TRIGGER_CONDITION (TriggerCondition: 02 emergency, 42 pin
  status change, 50 PTT, 51 PTT emergency), 0x78 TRIGGER_DISTANCE
  (TriggerDistance), 0x62 HORIZONTAL_SPEED.  0x42 and 0x44 become
  REQUEST_PARAMETER_42/44 (RequestParameter) with an optional varint
  value; their meaning is unknown (observed 3600 and 100).  Remove
  TriggerGpio and TriggerOnMove.
- Identity: assemble the request id big-endian (it was accumulated
  LSB-first), render it in hex, and clamp the read to the message.
- RequestedTokens: keep a list that holds only unrecognized ids; add
  getters for the recognized and unrecognized lists.
- Remove leftover debug locals from LRRPPacket.parseTokens().
- Add LRRPPacketTest (both captured bodies plus two copies with a
  corrupted type byte) and VarIntTest.

Built with the project's Gradle build (JDK 27 toolchain, in Docker);
compileJava, compileTestJava and the 9 new tests pass.

Co-authored-by: csmith_ai <carrottop@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 02:33:52 -05:00
Denny Sheirer
07b61be257 #2632 Detect on startup if multiple versions of any library are on the classpath and warn user to cleanup and reinstall (#2633)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 01:59:38 -05:00
Steve Pinkham
74dc32538f P25 Phase 1: fix typo in HDU Golay word starts (278 -> 378) (#2630)
GOLAY_WORD_STARTS listed 278 where it should list 378. The word at 378 was
never corrected, and the decoder ran a correction over bits 278-295 that
straddle the already corrected words at 270 and 288.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:31:08 -05:00
Steve Pinkham
7fcf035337 edac: correct Golay(24,12) words that are not at the start of the message (#2631)
Golay24.checkAndCorrect indexed the word from bit 0 (getInt(0, 22), xor(12, ...),
flip(index)) and took the parity over the whole message, so it was only right for a
message that is exactly one 24-bit word. P25 TDULC words 2-12 and the DMR voice
superframe words at 24 and 48 were "corrected" in the wrong bits. Decode any other
word in a 24-bit copy and write it back.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:29:50 -05:00
581 changed files with 58359 additions and 34771 deletions

View File

@@ -14,6 +14,9 @@ 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
@@ -34,7 +37,7 @@ jobs:
- name: Create Build Info file
run: |
echo -e "ref: $GITHUB_REF \ncommit: $GITHUB_SHA\nbuild: $(date +"%Y-%m-%dT%H:%M:%SZ")" > build/image/build_info.txt
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
- 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. 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.
# 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).
name: Release
on:
@@ -22,15 +22,6 @@ 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
@@ -54,6 +45,17 @@ 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,35 +1,29 @@
![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)
# 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
```
[![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)
# 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's Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)
* [FAQ](https://github.com/DSheirer/sdrtrunk/wiki/FAQ)
* [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk Application](https://github.com/DSheirer/sdrtrunk/wiki/images/sdrtrunk.png)
**Figure 1:** sdrtrunk Application Screenshot
![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
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.
@@ -54,17 +48,19 @@ 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.
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`:
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`):
```
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 tag matches `projectVersion` in `gradle.properties` and fails if it does not.
* Verifies that the version the build derives from git matches the tag 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,8 +52,44 @@ plugins {
id 'org.beryx.runtime' version '2.0.1'
}
//Version is defined in gradle.properties so that we can CLI override it for nightly builds.
version = project.findProperty('projectVersion')
/**
* 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
}
}
//Java 27 is required for this version of the Project Panama preview/incubator feature
java {
@@ -102,37 +138,34 @@ 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.jidesoft:jide-oss:3.6.18'
implementation 'com.miglayout:miglayout-swing:11.5.2'
implementation 'com.h2database:h2:2.5.252' //Built-in call database
implementation 'com.zaxxer:HikariCP:7.1.0' //Database connection pool
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.0.0'
implementation 'io.github.dsheirer:radio-reference-api:18.1.0' //RadioReference SOAP API - GitHub release, see settings.gradle
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'
@@ -140,6 +173,8 @@ 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'
}
@@ -159,7 +194,6 @@ 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
@@ -177,6 +211,14 @@ def jvmArgsLinux =
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
/**
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
*/
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
application {
mainClass = "io.github.dsheirer.gui.SDRTrunk"
@@ -188,6 +230,16 @@ application {
}
}
/**
* Adds the splash screen to the run task through an argument provider. Calling jvmArgs here would replace the
* applicationDefaultJvmArgs convention (--add-modules=jdk.incubator.vector, --enable-preview, etc.) instead of adding
* to it.
*/
tasks.named('run') {
def splashImage = file(splashResourceDir + '/' + splashImages[0]).absolutePath
jvmArgumentProviders.add({ ["-splash:${splashImage}".toString()] } as CommandLineArgumentProvider)
}
test {
if(os.isWindows()) {
jvmArgs = jvmArgsWindows
@@ -202,6 +254,7 @@ 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']}",
@@ -251,8 +304,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
* @return configured task.
*/
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//Use the correct set of JVM arguments
rt.extension.launcherData.get().jvmArgs = jvmArgs
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
//Additional modules to include with auto-detected modules.
//jdk.charsets - NXDN BIG5 encoding support
@@ -260,9 +313,11 @@ 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.base, java.logging, java.net.http, java.prefs, javafx.controls, javafx.swing - required by sdrtrunk (jdeps)
//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)
rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management',
'java.base', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'javafx.swing')
'java.base', 'java.desktop', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'java.sql',
'java.naming', 'java.security.jgss', 'jdk.net')
//Use only the modules listed above. The runtime plugin's module auto-detection uses a bundled ASM library that
//can't read Java 27 class files and logs a 'Failed to scan' error for each sdrtrunk class. The jdeps module check
@@ -351,6 +406,22 @@ tasks.named('runtime') {rt ->
}
}
/**
* Copies the startup splash screen images into the lib folder of each runtime target image, where the launch scripts
* load them from (-splash:{{BIN_DIR}}/../lib/...).
*/
tasks.named('runtime') {rt ->
rt.doLast {
rt.targetPlatforms.get().keySet().each { target ->
def lib = new File(rt.imageDir.asFile, "${project.name}-${target}/lib")
splashImages.each { name ->
java.nio.file.Files.copy(file(splashResourceDir + '/' + name).toPath(), new File(lib, name).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
}
}
}
/**
* Verifies that each runtime target image contains every module that the sdrtrunk jar requires, as reported by jdeps.
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse

View File

@@ -17,15 +17,16 @@
# *****************************************************************************
#
# Version naming conventions:
# Alpha: maj.min.patch-alpha-build
# Beta: maj.min.patch-beta-build
# Release: maj.min.patch
# 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>.
#
# Example: 0.6.0-beta-5
# Version tag naming conventions:
# Alpha: vmaj.min.patch-alpha-build
# Beta: vmaj.min.patch-beta-build
# Release: vmaj.min.patch
#
# Note: this is so that the file names for the resultant release build products match the GitLab release asset
# 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
# 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

2
mise.toml Normal file
View File

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

View File

@@ -82,5 +82,23 @@ 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

@@ -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 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,6 +530,34 @@ 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)
@@ -670,11 +698,26 @@ public class AliasList
//Attempt to do a fully qualified identifier match only
if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti)
{
return mFullyQualifiedTalkgroupAliasMap.get(fqti.getFullyQualifiedTalkgroupAddress());
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);
}
//Attempt to match the talkgroup value
int value = identifier.getValue();
Alias mapValue = mTalkgroupAliasMap.get(value);
if (mapValue != null)
@@ -790,11 +833,26 @@ public class AliasList
//Match fully qualified identifier only.
if(identifier instanceof FullyQualifiedRadioIdentifier fqri)
{
return mFullyQualifiedRadioAliasMap.get(fqri.getFullyQualifiedRadioAddress());
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);
}
//Attempt to match against the radio identifier
int value = identifier.getValue();
Alias mapValue = mRadioAliasMap.get(value);
if(mapValue != null)

View File

@@ -0,0 +1,269 @@
/*
* *****************************************************************************
* 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,6 +46,8 @@ 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()
{
@@ -63,6 +65,99 @@ 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.
*/
@@ -79,6 +174,15 @@ 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());
}
}
}
/**
@@ -93,7 +197,22 @@ public class AliasModel
return;
}
mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName));
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);
}
}
}
/**
@@ -109,6 +228,7 @@ public class AliasModel
mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
mAliasListMap.remove(aliasListName);
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
}
/**
@@ -146,6 +266,7 @@ public class AliasModel
removeAlias(alias);
}
mAliasListConfigurations.clear();
mAliasListNames.clear();
}

View File

@@ -0,0 +1,571 @@
/*
* *****************************************************************************
* 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,14 +19,16 @@
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;
@@ -62,23 +64,28 @@ public abstract class RecurringAction extends AliasAction
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS);
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);
String text = "Alias [" + alias.getName() + "] is active in message [" + 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();
});
}
else
{
dismissed.run();
}
break;
default:
}

View File

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

View File

@@ -38,6 +38,7 @@ 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;
@@ -67,6 +68,8 @@ 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);
@@ -96,6 +99,15 @@ 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,6 +25,7 @@ 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;
@@ -49,6 +50,7 @@ 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,6 +24,7 @@ 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;
@@ -68,6 +69,7 @@ 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:
@@ -113,6 +115,8 @@ 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,9 +46,8 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel;
public class BroadcastModel extends AbstractTableModel implements Listener<AudioRecording>
public class BroadcastModel implements Listener<AudioRecording>
{
private final static Logger mLog = LoggerFactory.getLogger(BroadcastModel.class);
@@ -57,18 +56,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
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<>();
@@ -171,8 +158,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
{
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;
}
@@ -274,8 +259,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
if(configuredBroadcast != null)
{
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
mConfiguredBroadcasts.remove(configuredBroadcast);
if(configuredBroadcast.hasAudioBroadcaster())
@@ -286,8 +269,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
}
process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE));
fireTableRowsDeleted(index, index);
}
}
@@ -354,13 +335,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
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());
}
@@ -383,13 +357,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
broadcaster.removeListener();
broadcaster.dispose();
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE));
}
}
@@ -498,186 +465,17 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
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,6 +32,7 @@ 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

@@ -1,186 +0,0 @@
/*
* *****************************************************************************
* 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,6 +151,30 @@ 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,7 +113,8 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
}
else
{
mLog.error("Error connecting to Rdio Scanner server on startup [" + response + "]");
mLog.error("Error connecting to " + getBroadcastConfiguration().getServiceName() +
" server on startup [" + response + "]");
setBroadcastState(BroadcastState.ERROR);
}
@@ -249,7 +250,8 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
}
catch(IOException e)
{
mLog.error("Rdio Scanner API - audio recording file not found - ignoring upload");
mLog.error(getBroadcastConfiguration().getServiceName() +
" API - audio recording file not found - ignoring upload");
}
if(audioBytes != null)
@@ -286,14 +288,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("Rdio Scanner API file upload fail [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
else
{
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error("Rdio Scanner API file upload fail [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
@@ -321,7 +323,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else
{
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error("Rdio Scanner API file upload fail [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
@@ -334,7 +336,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else
{
//Register an error for the file not found exception
mLog.error("Rdio Scanner API - upload file not found [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API - upload file not found [" +
audioRecording.getPath().toString() + "]");
incrementErrorAudioCount();
broadcast(new BroadcastEvent(RdioScannerBroadcaster.this,

View File

@@ -19,6 +19,7 @@
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;
@@ -125,6 +126,15 @@ 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

@@ -0,0 +1,75 @@
/*
* *****************************************************************************
* 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 will be available");
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio can be processed");
}
else
{
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be available");
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be processed");
}
sLibraryStatusLogged = true;

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -37,10 +37,14 @@ 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;
@@ -52,6 +56,13 @@ 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;
@@ -128,6 +139,56 @@ 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()
{
@@ -177,26 +238,25 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
URLClassLoader childClassLoader = new URLClassLoader(new URL[]{path.toUri().toURL()},
this.getClass().getClassLoader());
try
{
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibraryV2", true, childClassLoader);
}
catch(ClassNotFoundException legacyLibrary)
for(String className: JMBE_LIBRARY_CLASS_NAMES)
{
try
{
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibrary", true, childClassLoader);
sLoadedJmbeAudioConverterClass = Class.forName(className, true, childClassLoader);
break;
}
catch(ClassNotFoundException missingLibrary)
catch(ClassNotFoundException notFound)
{
if(!mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
{
LOG.error("Couldn't load JMBE audio conversion library from [" + path +
"] - neither V2 nor V1 library class was found");
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
}
//Library doesn't contain this version of the library class - try the next older version
}
}
if(sLoadedJmbeAudioConverterClass == null && !mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
{
LOG.error("Couldn't load JMBE audio conversion library from [" + path +
"] - none of the library classes " + JMBE_LIBRARY_CLASS_NAMES + " were found");
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
}
}
catch(IllegalArgumentException iae)
{
@@ -229,9 +289,18 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
if((library.getMajorVersion() == 1 && library.getMinorVersion() >= 0 &&
library.getBuildVersion() >= 0) || library.getMajorVersion() >= 1)
{
audioConverter = library instanceof IAudioCodecLibraryV2 libraryV2 ?
libraryV2.getAudioConverterV2(getCodecName()) :
library.getAudioConverter(getCodecName());
if(library instanceof IAudioCodecLibraryV3 libraryV3)
{
audioConverter = libraryV3.getAudioConverterV3(getCodecName());
}
else if(library instanceof IAudioCodecLibraryV2 libraryV2)
{
audioConverter = libraryV2.getAudioConverterV2(getCodecName());
}
else
{
audioConverter = 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.iface.IAudioCodec;
import jmbe.frame.CorrectedIMBEFrame;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
@@ -111,12 +111,15 @@ public class MBECallSequenceConverter
}
}
IAudioCodec codec = audioModule.getAudioCodec();
boolean correctFrames = audioModule.isCorrectedFrameSupported();
for(VoiceFrame voiceFrame: callSequence.getVoiceFrames())
{
byte[] frameBytes = voiceFrame.getFrameBytes();
float[] audio = codec.getAudio(frameBytes);
//Only error correct the frame in sdrtrunk when the JMBE library (version 3+) can synthesize from it
float[] audio = audioModule.getAudio(frameBytes,
correctFrames ? CorrectedIMBEFrame.correct(frameBytes) : null);
audioModule.addAudio(audio);
}

View File

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

View File

@@ -31,6 +31,7 @@ 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;
@@ -58,13 +59,19 @@ 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 AudioSegment mCurrentAudioSegment;
private volatile 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;
@@ -105,6 +112,114 @@ 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.
*/
@@ -153,7 +268,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
public boolean hasAudioSegment()
{
return mCurrentAudioSegment != null;
return mCurrentAudioSegment != null || mReplay != null;
}
/**
@@ -174,20 +289,75 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
public float[] getAudio()
{
if(mAudioBuffer.isFull())
{
float[] audio = mAudioBuffer.get();
float[] audio = getNextAudio();
if(audio != null)
{
updatePeakLevel(audio);
//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)
{
return audio;
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)
{
loadNextAudioSegment();
@@ -249,10 +419,54 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
audio = mAudioBuffer.flush();
}
//Finally, if we have buffer audio and we're muted, return silence
if(isMuted() && audio != null)
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()
{
ReplaySource pending = mPendingReplay;
if(pending != null)
{
audio = new float[SAMPLES_PER_INTERVAL];
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);
}
return audio;
@@ -298,7 +512,20 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
private boolean isThrowaway(AudioSegment audioSegment)
{
return audioSegment != null && (audioSegment.isDoNotMonitor() || mDropDuplicates && (audioSegment.isDuplicate()));
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());
}
/**
@@ -344,9 +571,18 @@ 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;
}
/**
@@ -457,6 +693,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
mCurrentAudioSegment.decrementConsumerCount();
mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this);
mCurrentAudioSegment = null;
notifyPlayback();
}
}
@@ -494,6 +731,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
if(audioSegment != null)
{
notifyPlayback();
mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this);
broadcast(mCurrentAudioSegment.getIdentifierCollection());
}

View File

@@ -1,373 +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 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

@@ -1,98 +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.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

@@ -1,305 +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.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,6 +53,7 @@ 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<>();
@@ -61,6 +62,8 @@ 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.
@@ -114,6 +117,8 @@ 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();
@@ -182,7 +187,8 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
{
audioSegment = it.next();
if(audioSegment.isDoNotMonitor() || (audioSegment.isDuplicate() &&
if((audioSegment.isDoNotMonitor() && getHoldingChannelIndex(audioSegment) < 0) ||
(audioSegment.isDuplicate() &&
mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled()))
{
it.remove();
@@ -233,20 +239,7 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
try
{
//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());
assignAudioSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels());
}
finally
{
@@ -270,6 +263,352 @@ 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.
@@ -397,6 +736,30 @@ 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

@@ -0,0 +1,49 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,154 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,167 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.playback;
import io.github.dsheirer.audio.AudioSegment;
import io.github.dsheirer.database.call.CallRecord;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.identifier.patch.PatchGroup;
import io.github.dsheirer.identifier.patch.PatchGroupIdentifier;
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
import io.github.dsheirer.protocol.Protocol;
/**
* Hold talkgroup for an audio channel. While a channel holds a talkgroup, only calls to that talkgroup play on the
* channel and calls to the talkgroup are steered to the channel.
*
* A call matches when its TO talkgroup has the same protocol and value, or when its TO patch group is (or includes)
* the talkgroup. APCO-25 phase 1 and phase 2 are treated as the same protocol since a P25 system's talkgroups are
* used on both phase 1 and phase 2 traffic channels.
*
* @param protocol of the talkgroup
* @param talkgroup value
* @param label for display (formatted talkgroup and alias)
*/
public record TalkgroupHold(Protocol protocol, int talkgroup, String label)
{
/**
* Normalizes the protocol for comparison
*/
private static Protocol normalize(Protocol protocol)
{
return protocol == Protocol.APCO25_PHASE2 ? Protocol.APCO25 : protocol;
}
/**
* Indicates if the talkgroup identifier is this hold talkgroup
*/
public boolean matches(TalkgroupIdentifier identifier)
{
return identifier != null && identifier.getValue() != null && identifier.getValue() == talkgroup &&
normalize(identifier.getProtocol()) == normalize(protocol);
}
/**
* Indicates if the call identifiers have this hold talkgroup (or a patch group with it) as the TO identifier.
*/
public boolean matches(IdentifierCollection identifierCollection)
{
if(identifierCollection == null)
{
return false;
}
for(Identifier identifier: identifierCollection.getIdentifiers(Role.TO))
{
if(identifier instanceof TalkgroupIdentifier tg && matches(tg))
{
return true;
}
if(identifier instanceof PatchGroupIdentifier pgi && pgi.getValue() != null)
{
PatchGroup patchGroup = pgi.getValue();
if(matches(patchGroup.getPatchGroup()))
{
return true;
}
for(TalkgroupIdentifier patched: patchGroup.getPatchedTalkgroupIdentifiers())
{
if(matches(patched))
{
return true;
}
}
}
}
return false;
}
/**
* Indicates if the audio segment is a call to this hold talkgroup.
*/
public boolean matches(AudioSegment audioSegment)
{
return audioSegment != null && matches(audioSegment.getIdentifierCollection());
}
/**
* Creates a hold for the TO talkgroup (or patch group) of the call identifiers.
* @param identifierCollection of a call
* @param label for display
* @return hold or null if the call doesn't have a TO talkgroup
*/
public static TalkgroupHold from(IdentifierCollection identifierCollection, String label)
{
if(identifierCollection == null)
{
return null;
}
Identifier to = identifierCollection.getToIdentifier();
if(to instanceof PatchGroupIdentifier pgi && pgi.getValue() != null && pgi.getValue().getPatchGroup() != null)
{
to = pgi.getValue().getPatchGroup();
}
if(to instanceof TalkgroupIdentifier tg && tg.getValue() != null && tg.getValue() > 0)
{
return new TalkgroupHold(tg.getProtocol(), tg.getValue(), label != null ? label : tg.toString());
}
return null;
}
/**
* Creates a hold for the TO talkgroup of a stored call.
* @param call with a TO talkgroup
* @param toAlias current alias name of the TO talkgroup for the label, or null
* @return hold or null if the call doesn't have a TO talkgroup
*/
public static TalkgroupHold from(CallRecord call, String toAlias)
{
if(call == null || !call.hasTalkgroup() || call.getToValue() > Integer.MAX_VALUE)
{
return null;
}
String label = call.getToId() + (toAlias != null ? " " + toAlias : "");
return new TalkgroupHold(call.getProtocolValue(), call.getToValue().intValue(), label);
}
/**
* Indicates if the other hold is for the same talkgroup (ignoring the label).
*/
public boolean isSameTalkgroup(TalkgroupHold other)
{
return other != null && other.talkgroup == talkgroup && normalize(other.protocol) == normalize(protocol);
}
@Override
public String toString()
{
return label;
}
}

View File

@@ -57,10 +57,11 @@ 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. Typically, this will be 64k or 128k
if(samples.length % FRAGMENT_SIZE != 0)
//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)
{
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + FRAGMENT_SIZE);
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + (FRAGMENT_SIZE * 2));
}
mSamples = samples;

View File

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

View File

@@ -1,137 +0,0 @@
/*******************************************************************************
* 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,6 +49,7 @@ 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;
@@ -128,6 +129,19 @@ 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
*/
@@ -323,6 +337,15 @@ 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);
@@ -339,6 +362,7 @@ 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,6 +22,7 @@ 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-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -18,67 +18,73 @@
*/
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.table.AbstractTableModel;
public class ChannelMetadataModel extends AbstractTableModel implements IChannelMetadataUpdateListener
/**
* 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
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadataModel.class);
private final List<ChannelMetadata> mChannelMetadata = new ArrayList<>();
private final Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap<>();
private final List<Listener> mListeners = new CopyOnWriteArrayList<>();
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;
private static final String[] COLUMNS = {"Status", "Decoder", "From", "Alias", "To", "Alias", "Channel", "Frequency", "Channel Name"};
private List<ChannelMetadata> mChannelMetadata = new ArrayList();
private Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap();
private Listener<ChannelAndMetadata> mChannelAddListener;
public ChannelMetadataModel()
/**
* 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
{
MyEventBus.getGlobalEventBus().register(this);
/**
* Channel metadata(s) for a channel were added to the model.
*/
void added(ChannelAndMetadata channelAndMetadata);
/**
* Channel metadata was removed from the model.
*/
void removed(ChannelMetadata channelMetadata);
/**
* A field of a channel metadata in the model was updated.
*/
void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField);
}
/**
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
* Constructs an instance
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
public ChannelMetadataModel()
{
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);
}
});
}
}
/**
* 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.
*/
public synchronized List<ChannelMetadata> addListener(Listener listener)
{
mListeners.add(listener);
return new ArrayList<>(mChannelMetadata);
}
/**
* Removes the listener from receiving model change notifications.
*/
public void removeListener(Listener listener)
{
mListeners.remove(listener);
}
/**
@@ -87,10 +93,16 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
*/
public String getDiagnosticInformation()
{
StringBuilder sb = new StringBuilder();
Map<ChannelMetadata,Channel> mapCopy = new HashMap<>(mMetadataChannelMap);
List<ChannelMetadata> metadataCopy = new ArrayList<>(mChannelMetadata);
Map<ChannelMetadata,Channel> mapCopy;
List<ChannelMetadata> metadataCopy;
synchronized(this)
{
mapCopy = new HashMap<>(mMetadataChannelMap);
metadataCopy = new ArrayList<>(mChannelMetadata);
}
StringBuilder sb = new StringBuilder();
sb.append("Channel Metadata Model Diagnostics\n");
for(ChannelMetadata channelMetadata: metadataCopy)
@@ -122,51 +134,34 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
return sb.toString();
}
/**
* Prepares the model for disposal.
*/
public void dispose()
{
MyEventBus.getGlobalEventBus().unregister(this);
mListeners.clear();
}
/**
* Lookup model row for the specified channel metadata
* Adds the channel metadata(s) for a channel to the model.
*/
public int getRow(ChannelMetadata channelMetadata)
public synchronized void add(ChannelAndMetadata channelAndMetadata)
{
if(mChannelMetadata.contains(channelMetadata))
for(ChannelMetadata channelMetadata: channelAndMetadata.getChannelMetadata())
{
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());
int index = mChannelMetadata.indexOf(channelMetadata);
fireTableRowsInserted(index, index);
channelMetadata.setUpdateEventListener(ChannelMetadataModel.this);
}
if(mChannelAddListener != null)
{
mChannelAddListener.receive(channelAndMetadata);
}
});
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
channelMetadata.setUpdateEventListener(this);
}
for(Listener listener: mListeners)
{
listener.added(channelAndMetadata);
}
}
/**
@@ -174,7 +169,7 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
* @param channelMetadatas
* @param channel
*/
public void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
public synchronized void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
{
for(ChannelMetadata channelMetadata: channelMetadatas)
{
@@ -182,178 +177,46 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
}
}
public void remove(ChannelMetadata channelMetadata)
/**
* Removes the channel metadata from the model.
*/
public synchronized 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);
channelMetadata.removeUpdateEventListener();
mMetadataChannelMap.remove(channelMetadata);
if(index >= 0)
if(mChannelMetadata.remove(channelMetadata))
{
for(Listener listener: mListeners)
{
fireTableRowsDeleted(index, index);
listener.removed(channelMetadata);
}
});
}
}
/**
* Get the channel metadata at the specified model row index
* Current channel metadata in the model.
* @return copy of the channel metadata list.
*/
public ChannelMetadata getChannelMetadata(int row)
public synchronized List<ChannelMetadata> getChannelMetadata()
{
if(row < mChannelMetadata.size())
{
return mChannelMetadata.get(row);
}
return null;
return new ArrayList<>(mChannelMetadata);
}
/**
* Returns the channel that matches the metadata or null
*/
public Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
public synchronized 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)
{
final int rowIndex = mChannelMetadata.indexOf(channelMetadata);
if(rowIndex >= 0)
for(Listener listener: mListeners)
{
//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;
}
}
});
listener.updated(channelMetadata, channelMetadataField);
}
}
}

View File

@@ -1,494 +0,0 @@
/*
* *****************************************************************************
* 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

@@ -1,138 +0,0 @@
/*
* *****************************************************************************
* 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

@@ -1,117 +0,0 @@
/*
* *****************************************************************************
* 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

@@ -1,105 +0,0 @@
/*******************************************************************************
* 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,6 +18,7 @@
*/
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;
@@ -83,6 +84,8 @@ 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;
@@ -123,6 +126,19 @@ 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
*/
@@ -134,6 +150,7 @@ 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();
@@ -509,6 +526,36 @@ 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

@@ -1,242 +0,0 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,215 @@
/*
* *****************************************************************************
* 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,6 +153,14 @@ 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,13 +30,11 @@ 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 extends AbstractListModel<ChannelMap>
public class ChannelMapModel
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(ChannelMapModel.class);
private ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor());
@@ -108,17 +106,6 @@ public class ChannelMapModel extends AbstractListModel<ChannelMap>
*/
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);
}
@@ -142,10 +129,6 @@ public class ChannelMapModel extends AbstractListModel<ChannelMap>
{
mChannelMaps.add(channelMap);
int index = mChannelMaps.indexOf(channelMap);
fireIntervalAdded(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.ADD));
}
}
@@ -157,36 +140,9 @@ public class ChannelMapModel extends AbstractListModel<ChannelMap>
{
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

@@ -1,295 +0,0 @@
/*
*
* * ******************************************************************************
* * 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

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

View File

@@ -0,0 +1,158 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,45 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.database;
/**
* Call database status change notification
*
* @param type of event
* @param configuration of the current database
* @param errorMessage for an ERROR event, otherwise null
*/
public record DatabaseEvent(Type type, DatabaseConfiguration configuration, String errorMessage)
{
public enum Type
{
/**
* Database opened, or a different database was selected
*/
CONNECTED,
/**
* Database couldn't be opened or the connection was lost
*/
ERROR,
/**
* Stored calls changed outside of the live call updates, for example by an age-off rule
*/
CALLS_CHANGED
}
}

View File

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

View File

@@ -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 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,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,28 +16,23 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.util;
import java.awt.EventQueue;
package io.github.dsheirer.database;
/**
* Swing utilities
* State of a schema in a database
*/
public class SwingUtils
public enum SchemaStatus
{
/**
* Runs the runnable on the swing dispatch thread
* Schema doesn't exist
*/
public static void run(Runnable r)
{
if(EventQueue.isDispatchThread())
{
r.run();
}
else
{
EventQueue.invokeLater(r);
}
}
MISSING,
/**
* Schema exists but doesn't have sdrtrunk tables
*/
EMPTY,
/**
* Schema has sdrtrunk tables
*/
SDRTRUNK
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,38 +16,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token;
import io.github.dsheirer.bits.CorrectedBinaryMessage;
package io.github.dsheirer.database.ageoff;
/**
* LRRP Trigger on GPIO Token
*
* Total Length: 1 byte
* What an age-off rule removes
*/
public class TriggerGpio extends Token
public enum AgeOffAction
{
/**
* Constructs an instance of a heading token.
*
* @param message containing the heading
* @param offset to the start of the token
*/
public TriggerGpio(CorrectedBinaryMessage message, int offset)
{
super(message, offset);
}
DELETE_CALL_AND_RECORDING("Delete the call and its recording"),
DELETE_RECORDING_ONLY("Delete the recording, keep the call");
@Override
public TokenType getTokenType()
private final String mLabel;
AgeOffAction(String label)
{
return TokenType.TRIGGER_GPIO;
mLabel = label;
}
@Override
public String toString()
{
return "TRIGGER ON GPIO";
return mLabel;
}
}

View File

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

View File

@@ -0,0 +1,71 @@
/*
* *****************************************************************************
* 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

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

View File

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

View File

@@ -0,0 +1,151 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.database.call;
import io.github.dsheirer.protocol.Protocol;
import java.util.List;
import java.util.Locale;
/**
* Search filter for the calls table. Empty text fields, empty identifier filters and null values don't filter.
*
* @param to filter for the TO identifier (talkgroup, patch group or radio): typed text or a selected talkgroup alias
* @param from filter for the FROM identifier (radio): typed text or a selected radio alias
* @param talkerAlias text matched against the decoded talker alias
* @param protocol to match or null
* @param callType to match or null
* @param system text matched against the system name
* @param startTime earliest call start time (ms since epoch) or 0
* @param endTime latest call start time (ms since epoch) or 0
*/
public record CallSearchCriteria(IdentifierFilter to, IdentifierFilter from, String talkerAlias, Protocol protocol,
CallType callType, String system, long startTime, long endTime)
{
/**
* Criteria without a call type filter
*/
public CallSearchCriteria(IdentifierFilter to, IdentifierFilter from, String talkerAlias, Protocol protocol,
String system, long startTime, long endTime)
{
this(to, from, talkerAlias, protocol, null, system, startTime, endTime);
}
public CallSearchCriteria
{
to = to == null ? IdentifierFilter.none() : to;
from = from == null ? IdentifierFilter.none() : from;
talkerAlias = clean(talkerAlias);
system = clean(system);
}
/**
* Criteria that match every call
*/
public static CallSearchCriteria all()
{
return new CallSearchCriteria(null, null, null, null, null, 0, 0);
}
private static String clean(String value)
{
return value == null ? "" : value.trim();
}
/**
* Indicates if these criteria match every call.
*/
public boolean isEmpty()
{
return to.isEmpty() && from.isEmpty() && talkerAlias.isEmpty() && system.isEmpty() && protocol == null &&
callType == null && startTime == 0 && endTime == 0;
}
/**
* Parses the text as a decimal identifier value, or null if it isn't a number.
*/
static Long parseValue(String text)
{
if(text == null || text.isEmpty() || text.length() > 18)
{
return null;
}
for(int x = 0; x < text.length(); x++)
{
if(!Character.isDigit(text.charAt(x)))
{
return null;
}
}
return Long.parseLong(text);
}
/**
* Evaluates the criteria against a call in memory, using the same rules as the database query. This is used to
* decide whether a live call belongs in the currently displayed search results.
*/
public boolean matches(CallRecord call)
{
if(!to.isEmpty() && !to.matches(call, call.getToId(), call.getToValue(), call.getToFullyQualified(),
call.isToTalkgroup(), call.getPatchedTalkgroups()))
{
return false;
}
if(!from.isEmpty() && !from.matches(call, call.getFromId(), call.getFromValue(),
call.getFromFullyQualified(), call.isFromRadio(), List.of()))
{
return false;
}
if(!talkerAlias.isEmpty() && !contains(call.getTalkerAlias(), talkerAlias))
{
return false;
}
if(protocol != null && !protocol.name().equals(call.getProtocol()))
{
return false;
}
if(callType != null && call.getCallType() != callType)
{
return false;
}
if(!system.isEmpty() && !contains(call.getSystem(), system))
{
return false;
}
if(startTime > 0 && call.getStartTime() < startTime)
{
return false;
}
return endTime <= 0 || call.getStartTime() <= endTime;
}
private static boolean contains(String value, String text)
{
return value != null && value.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT));
}
}

View File

@@ -0,0 +1,71 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,120 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,125 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.database.call;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
/**
* Storage operations for call audio events in one database schema. Each method uses the connection from the caller
* so that the caller controls pooling and transactions.
*/
public interface ICallRepository
{
/**
* Inserts the call and assigns the generated row id to the call.
* @return generated row id
*/
long insert(Connection connection, CallRecord call) throws SQLException;
/**
* Inserts the calls in a single batch without retrieving the generated ids.
*/
void insertBatch(Connection connection, List<CallRecord> calls) throws SQLException;
/**
* Updates the existing call row identified by the call's id.
* @return true if the row exists and was updated
*/
boolean update(Connection connection, CallRecord call) throws SQLException;
/**
* Marks calls left in the active state by a previous session as interrupted.
* @return count of calls updated
*/
int markInterrupted(Connection connection) throws SQLException;
/**
* Deletes the calls that are in progress. Used when switching databases: calls in progress continue in the new
* database, so their rows are removed from the old database.
* @return count of calls deleted
*/
int deleteActive(Connection connection) throws SQLException;
/**
* Calls matching the criteria, newest first.
*/
List<CallRecord> search(Connection connection, CallSearchCriteria criteria, int offset, int limit)
throws SQLException;
/**
* Count of calls matching the criteria
*/
long count(Connection connection, CallSearchCriteria criteria) throws SQLException;
/**
* Total number of calls
*/
long count(Connection connection) throws SQLException;
/**
* Page of calls in id order with an id greater than the argument, for transfers between databases.
*/
List<CallRecord> readPage(Connection connection, long afterId, int limit) throws SQLException;
/**
* Transfer keys of all calls (see {@link CallRecord#getTransferKey()})
*/
Set<String> getTransferKeys(Connection connection) throws SQLException;
/**
* Calls with an available recording, oldest first.
* @param startedBefore only calls that started before this time, or 0 for any time
*/
List<CallRecord> getRecordedCalls(Connection connection, long startedBefore, int limit) throws SQLException;
/**
* Calls that are not in progress and started before the time, oldest first.
*/
List<CallRecord> getCallsStartedBefore(Connection connection, long startedBefore, int limit) throws SQLException;
/**
* Completed calls that started before the time and are duplicates, or Do Not Monitor calls without an alias record
* option, oldest first.
*/
List<CallRecord> getDuplicateAndDoNotMonitorCalls(Connection connection, long startedBefore, int limit)
throws SQLException;
/**
* Total size in bytes of all available recordings
*/
long getRecordedFileSize(Connection connection) throws SQLException;
/**
* Deletes the call rows
*/
void delete(Connection connection, List<Long> ids) throws SQLException;
/**
* Clears the recording file of the calls and marks their recordings deleted, keeping the call rows.
*/
void markRecordingsDeleted(Connection connection, List<Long> ids) throws SQLException;
/**
* Schema that holds the calls table
*/
String getSchema();
}

View File

@@ -0,0 +1,285 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.database.call;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.id.AliasID;
import io.github.dsheirer.alias.id.radio.P25FullyQualifiedRadio;
import io.github.dsheirer.alias.id.radio.Radio;
import io.github.dsheirer.alias.id.radio.RadioRange;
import io.github.dsheirer.alias.id.talkgroup.P25FullyQualifiedTalkgroup;
import io.github.dsheirer.alias.id.talkgroup.Talkgroup;
import io.github.dsheirer.alias.id.talkgroup.TalkgroupRange;
import io.github.dsheirer.protocol.Protocol;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Search filter for the TO or FROM identifier of a call. The filter either matches typed text against the formatted
* identifier (or the exact identifier value when the text is a number), or matches the identifiers of a selected
* alias: calls of the alias's alias list whose identifier value is one of the alias's values or ranges, or whose fully
* qualified (roaming) address is one of the alias's fully qualified identifiers. This uses the same matching as the
* alias list, so a search for an alias finds the calls that the alias list currently aliases with that alias.
*
* @param text typed text, or empty for no text filter (ignored when an alias is selected)
* @param aliasName of the selected alias, or null
* @param aliasList name of the selected alias, or null
* @param ranges of identifier values for the selected alias
* @param fullyQualified addresses for the selected alias
*/
public record IdentifierFilter(String text, String aliasName, String aliasList, List<ValueRange> ranges,
List<FullyQualifiedAddress> fullyQualified)
{
/**
* Range of identifier values (inclusive) for a protocol
*/
public record ValueRange(Protocol protocol, int min, int max)
{
public boolean contains(Protocol callProtocol, long value)
{
return protocol == callProtocol && min <= value && value <= max;
}
}
/**
* Fully qualified identifier address (wacn.system.id) for a protocol
*/
public record FullyQualifiedAddress(Protocol protocol, String address) {}
public IdentifierFilter
{
text = text == null ? "" : text.trim();
ranges = ranges == null ? List.of() : List.copyOf(ranges);
fullyQualified = fullyQualified == null ? List.of() : List.copyOf(fullyQualified);
}
/**
* Filter that matches every call
*/
public static IdentifierFilter none()
{
return new IdentifierFilter("", null, null, null, null);
}
/**
* Filter for typed text
*/
public static IdentifierFilter text(String text)
{
return new IdentifierFilter(text, null, null, null, null);
}
/**
* Filter for the talkgroup identifiers (talkgroups, ranges, fully qualified talkgroups) of the alias
*/
public static IdentifierFilter talkgroupAlias(Alias alias)
{
List<ValueRange> ranges = new ArrayList<>();
List<FullyQualifiedAddress> fullyQualified = new ArrayList<>();
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isValid())
{
continue;
}
if(id instanceof P25FullyQualifiedTalkgroup fqt)
{
fullyQualified.add(new FullyQualifiedAddress(fqt.getProtocol(), fqt.getHashKey()));
}
else if(id instanceof Talkgroup talkgroup)
{
ranges.add(new ValueRange(talkgroup.getProtocol(), talkgroup.getValue(), talkgroup.getValue()));
}
else if(id instanceof TalkgroupRange range)
{
ranges.add(new ValueRange(range.getProtocol(), range.getMinTalkgroup(), range.getMaxTalkgroup()));
}
}
return new IdentifierFilter("", alias.getName(), alias.getAliasListName(), ranges, fullyQualified);
}
/**
* Filter for the radio identifiers (radios, ranges, fully qualified radios) of the alias
*/
public static IdentifierFilter radioAlias(Alias alias)
{
List<ValueRange> ranges = new ArrayList<>();
List<FullyQualifiedAddress> fullyQualified = new ArrayList<>();
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isValid())
{
continue;
}
if(id instanceof P25FullyQualifiedRadio fqr)
{
fullyQualified.add(new FullyQualifiedAddress(fqr.getProtocol(), fqr.getHashKey()));
}
else if(id instanceof Radio radio)
{
ranges.add(new ValueRange(radio.getProtocol(), radio.getValue(), radio.getValue()));
}
else if(id instanceof RadioRange range)
{
ranges.add(new ValueRange(range.getProtocol(), range.getMinRadio(), range.getMaxRadio()));
}
}
return new IdentifierFilter("", alias.getName(), alias.getAliasListName(), ranges, fullyQualified);
}
/**
* Indicates if the alias has talkgroup identifiers that a talkgroup alias filter can search for
*/
public static boolean hasTalkgroups(Alias alias)
{
IdentifierFilter filter = talkgroupAlias(alias);
return !filter.ranges().isEmpty() || !filter.fullyQualified().isEmpty();
}
/**
* Indicates if the alias has radio identifiers that a radio alias filter can search for
*/
public static boolean hasRadios(Alias alias)
{
IdentifierFilter filter = radioAlias(alias);
return !filter.ranges().isEmpty() || !filter.fullyQualified().isEmpty();
}
/**
* Indicates if this filter is for a selected alias
*/
public boolean isAlias()
{
return aliasName != null;
}
/**
* Indicates if this filter doesn't filter anything. An alias filter always filters: an alias without matching
* identifiers matches no calls.
*/
public boolean isEmpty()
{
return !isAlias() && text.isEmpty();
}
/**
* Evaluates the filter against a call identifier in memory, using the same rules as the database query.
* @param call to evaluate
* @param formatted identifier text
* @param value of the identifier, or null
* @param fullyQualifiedAddress of the identifier, or null
* @param formMatches true if the identifier form is the form that the alias identifiers apply to
* @param patched talkgroups patched into the TO patch group, which also match, or an empty list
*/
boolean matches(CallRecord call, String formatted, Long value, String fullyQualifiedAddress, boolean formMatches,
List<PatchedTalkgroup> patched)
{
if(isAlias())
{
if(!formMatches || call.getAliasList() == null || aliasList == null ||
!call.getAliasList().equalsIgnoreCase(aliasList))
{
return false;
}
Protocol protocol = call.getProtocolValue();
for(PatchedTalkgroup talkgroup: patched)
{
if(matchesAlias(protocol, talkgroup.value(), talkgroup.fullyQualified()))
{
return true;
}
}
return matchesAlias(protocol, value, fullyQualifiedAddress);
}
if(text.isEmpty())
{
return true;
}
Long parsed = CallSearchCriteria.parseValue(text);
if(parsed != null)
{
if(parsed.equals(value))
{
return true;
}
for(PatchedTalkgroup talkgroup: patched)
{
if(talkgroup.value() == parsed)
{
return true;
}
}
}
return formatted != null && formatted.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT));
}
/**
* Indicates if the identifier value or fully qualified address matches the alias identifiers
*/
private boolean matchesAlias(Protocol protocol, Long value, String fullyQualifiedAddress)
{
if(fullyQualifiedAddress != null)
{
for(FullyQualifiedAddress address: fullyQualified)
{
if(address.protocol() == protocol && address.address().equals(fullyQualifiedAddress))
{
return true;
}
}
return false;
}
if(value != null)
{
for(ValueRange range: ranges)
{
if(range.contains(protocol, value))
{
return true;
}
}
}
return false;
}
@Override
public String toString()
{
return isAlias() ? aliasName + " (" + aliasList + ")" : text;
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,38 +16,19 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token;
import io.github.dsheirer.bits.CorrectedBinaryMessage;
package io.github.dsheirer.database.call;
/**
* LRRP Trigger on Move Token
* A talkgroup that is patched into the patch group of a call. The protocol is the protocol of the call.
*
* Total Length: 1 byte
* @param value of the talkgroup
* @param fullyQualified address (wacn.system.id) of a fully qualified (roaming) talkgroup, or null
*/
public class TriggerOnMove extends Token
public record PatchedTalkgroup(long value, String fullyQualified)
{
/**
* Constructs an instance of a heading token.
*
* @param message containing the heading
* @param offset to the start of the token
*/
public TriggerOnMove(CorrectedBinaryMessage message, int offset)
{
super(message, offset);
}
@Override
public TokenType getTokenType()
{
return TokenType.TRIGGER_ON_MOVE;
}
@Override
public String toString()
{
return "TRIGGER ON MOVE";
return fullyQualified != null ? value + "(" + fullyQualified + ")" : String.valueOf(value);
}
}

View File

@@ -0,0 +1,79 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,75 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,77 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,72 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,72 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.database.dialect;
import io.github.dsheirer.database.DatabaseConfiguration;
import java.nio.file.Path;
/**
* PostgreSQL network database server. The schema lives inside the database named in the configuration.
*/
public class PostgreSQLDialect implements IDatabaseDialect
{
@Override
public String getDriverClass()
{
return "org.postgresql.Driver";
}
@Override
public int getDefaultPort()
{
return 5432;
}
@Override
public boolean isNetwork()
{
return true;
}
@Override
public boolean requiresDatabaseName()
{
return true;
}
@Override
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
{
return "jdbc:postgresql://" + configuration.host() + ":" + configuration.port() + "/" +
configuration.database();
}
@Override
public String getIdentityColumn()
{
return "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
}
@Override
public String getDropSchemaStatement(String schema)
{
return "DROP SCHEMA IF EXISTS " + schema + " CASCADE";
}
}

View File

@@ -271,6 +271,26 @@ 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.
*/
@@ -406,6 +426,11 @@ 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,6 +42,7 @@ public class ChannelDFTFactory
case VECTOR_SIMD_PREFERRED:
return new VectorChannelDFT(channelCount);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarChannelDFT(channelCount);
}

View File

@@ -79,9 +79,11 @@ 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 batches queued for channel output.
* 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.
*/
private static final int MAXIMUM_POOLED_BATCHES = 2 * MAXIMUM_QUEUED_BATCHES;
private static final int MAXIMUM_POOLED_BATCHES = MAXIMUM_QUEUED_BATCHES + 2;
//Sized to process 40 times per second
private IFFTProcessorDispatcher mIFFTProcessorDispatcher = new IFFTProcessorDispatcher(25);

View File

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

View File

@@ -180,7 +180,8 @@ 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 the configuration changes on its own dispatcher thread.
* 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.
* @param channelCalculator for updates
* @param filterManager for updates
* @throws IllegalArgumentException if there's an issue.

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -24,6 +24,7 @@ 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;
@@ -34,12 +35,20 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
private final static Logger mLog = LoggerFactory.getLogger(ChannelOutputProcessor.class);
/**
* Maximum queued channel results batches, about one second of samples. A full batch is dropped when this channel
* Maximum queued channel sample 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;
private Dispatcher<QueuedChannelResults> mChannelResultsDispatcher;
/**
* Maximum channel sample arrays held for reuse: the queued batches plus the batch being processed and the batch
* being copied.
*/
private static final int MAXIMUM_POOLED_ARRAYS = MAXIMUM_QUEUED_BATCHES + 2;
private Dispatcher<QueuedChannelSamples> mChannelSamplesDispatcher;
private final Queue<float[]> mSamplePool = new ArrayBlockingQueue<>(MAXIMUM_POOLED_ARRAYS);
private volatile int[] mChannelOffsets = new int[0];
private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>();
private final AtomicLong mBatchSequence = new AtomicLong();
private HeartbeatManager mHeartbeatManager;
@@ -60,25 +69,45 @@ 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;
mChannelResultsDispatcher = new Dispatcher(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelResultsDispatcher.setListener(queued -> {
mChannelSamplesDispatcher = new Dispatcher<>(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelSamplesDispatcher.setListener(queued -> {
try
{
applyPendingUpdates(queued.sequence());
mCurrentSampleTimestamp = queued.channelResults().getTimestamp();
process(queued.channelResults());
mCurrentSampleTimestamp = queued.timestamp();
process(queued.samples(), queued.blockCount());
}
catch(Throwable t)
{
mLog.error("Error processing channel results", t);
mLog.error("Error processing channel samples", t);
}
finally
{
queued.channelResults().release();
mSamplePool.offer(queued.samples());
}
});
}
/**
* 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
@@ -119,13 +148,13 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
@Override
public void start()
{
mChannelResultsDispatcher.start();
mChannelSamplesDispatcher.start();
}
@Override
public void stop()
{
mChannelResultsDispatcher.stop();
mChannelSamplesDispatcher.stop();
}
/**
@@ -147,22 +176,66 @@ 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)
{
channelResults.retain();
long sequence = mBatchSequence.incrementAndGet();
if(!mChannelResultsDispatcher.offer(new QueuedChannelResults(channelResults, mBatchSequence.incrementAndGet())))
if(!mChannelSamplesDispatcher.isRunning())
{
channelResults.release();
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);
}
}
/**
* Sub-class implementation to process one polyphase channelizer results batch.
* @param channelResults to process
* Provides a reused sample array of the requested length when one is available, or a new array.
*/
public abstract void process(ChannelResultsBatch channelResults);
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);
@Override
public int getInputChannelCount()
@@ -171,9 +244,10 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
}
/**
* Channel results batch and its position in the sequence of received batches.
* Copied channel samples with the timestamp of the batch they were copied from and the batch's position in the
* sequence of received batches.
*/
private record QueuedChannelResults(ChannelResultsBatch channelResults, long sequence) {}
private record QueuedChannelSamples(float[] samples, int blockCount, long timestamp, 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-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -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,7 +29,6 @@ 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
@@ -55,7 +54,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{
StringBuilder sb = new StringBuilder();
sb.append("One Channel Output Processor");
sb.append("\n\tIndex (doubled) [").append(mChannelOffset).append("]");
sb.append("\n\tIndex (doubled) ").append(Arrays.toString(getChannelOffsets()));
sb.append("\n\tMixer Assembler: none");
return sb.toString();
}
@@ -81,8 +80,7 @@ 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
int channelOffset = indexes.get(0) * 2;
enqueueUpdate(() -> mChannelOffset = channelOffset);
setChannelOffsets(indexes.get(0) * 2);
}
@Override
@@ -92,19 +90,18 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
}
/**
* 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.
* Passes the copied channel samples to the assembler. The assembler will apply frequency translation and gain and
* indicate when a buffer is fully assembled.
*
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
* @param samples containing an I/Q pair for each block (I0,Q0,I1,Q1...In,Qn)
* @param blockCount number of blocks
*/
@Override
public void process(ChannelResultsBatch channelResults)
public void process(float[] samples, int blockCount)
{
float[] samples = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int channelOffset = mChannelOffset;
int length = blockCount * 2;
for(int index = channelOffset; index < samples.length; index += blockLength)
for(int index = 0; index < length; index += 2)
{
mMixerAssembler.receive(samples[index], samples[index + 1]);

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -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,8 +29,6 @@ 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
@@ -60,7 +58,7 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{
StringBuilder sb = new StringBuilder();
sb.append("Two Channel Output Processor");
sb.append("\n\tIndices (doubled) 1 [").append(mChannelOffset1).append("] 2 [").append(mChannelOffset2).append("]");
sb.append("\n\tIndices (doubled) ").append(Arrays.toString(getChannelOffsets()));
sb.append("\n\tMixer Assembler: ").append(mMixerAssembler.getStateDescription());
return sb.toString();
}
@@ -98,45 +96,32 @@ 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
int channelOffset1 = indexes.get(0) * 2;
int channelOffset2 = indexes.get(1) * 2;
enqueueUpdate(() -> {
mChannelOffset1 = channelOffset1;
mChannelOffset2 = channelOffset2;
});
setChannelOffsets(indexes.get(0) * 2, indexes.get(1) * 2);
}
/**
* 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.
* Synthesizes the two copied channels, applies frequency translation, and delivers the frequency-corrected channel
* I/Q sample set to the complex sample listener.
*
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
* @param samples containing an I/Q pair for each of the two channels per block (I1,Q1,I2,Q2 ...)
* @param blockCount number of blocks
*/
@Override
public void process(ChannelResultsBatch channelResults)
public void process(float[] samples, int blockCount)
{
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 * blockLength;
int block = x * 4;
if((x & 1) == 0)
{
mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
samples[block + channelOffset2], samples[block + channelOffset2 + 1]);
mMixerAssembler.receive(samples[block], samples[block + 1], samples[block + 2], samples[block + 3]);
}
else
{
mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
-samples[block + channelOffset2], -samples[block + channelOffset2 + 1]);
mMixerAssembler.receive(samples[block], samples[block + 1], -samples[block + 2], -samples[block + 3]);
}
if(mMixerAssembler.hasBuffer())

View File

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

View File

@@ -1,16 +1,14 @@
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()
{
mJFXPanel = new JFXPanel();
FxToolkit.ensureStarted();
Platform.runLater(() ->
{

View File

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

View File

@@ -1,51 +0,0 @@
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,6 +44,7 @@ public class ComplexGainFactory
return new VectorComplexGainControl();
}
case SCALAR:
case UNCALIBRATED:
default:
return new ComplexGainControl();
}
@@ -64,6 +65,7 @@ public class ComplexGainFactory
return new VectorComplexGain(gain);
}
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexGain(gain);
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -68,6 +68,29 @@ 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);

View File

@@ -37,7 +37,8 @@ public class Hamming13
*
* @param message containing a Hamming protected word
* @param offset to the start of the protected word
* @return message index for an error bit or -1 if no errors are detected.
* @return message index for an error bit, -1 if no errors are detected, or 1000 if more than one bit error is
* detected.
*/
public static int getErrorIndex(BinaryMessage message, int offset)
{
@@ -45,7 +46,8 @@ public class Hamming13
if(syndrome > 0)
{
return offset + ERROR_INDEX[syndrome];
int errorIndex = ERROR_INDEX[syndrome];
return errorIndex >= 0 ? offset + errorIndex : IHamming.MULTIPLE_ERRORS;
}
return IHamming.NO_ERRORS;

View File

@@ -47,13 +47,6 @@ public class Hamming16 implements IHamming
return NO_ERRORS;
}
//If the syndrome indicates the error is in the final parity bit position, and we already have odd parity, then
//flag it as invalid for multiple errors.
if(syndrome == 1 && message.getSubMessage(offset, offset + 16).cardinality() % 2 == 1) //check final parity bit
{
return MULTIPLE_ERRORS;
}
for(int index = 0; index < CHECKSUMS.length; index++)
{
if(syndrome == CHECKSUMS[index])

View File

@@ -46,13 +46,6 @@ public class Hamming17 implements IHamming
return NO_ERRORS;
}
//If the syndrome indicates the error is in the final parity bit position, and we already have odd parity, then
//flag it as invalid for multiple errors.
if(syndrome == 1 && message.getSubMessage(offset, offset + 17).cardinality() % 2 == 1) //check final parity bit
{
return MULTIPLE_ERRORS;
}
for(int index = 0; index < CHECKSUMS.length; index++)
{
if(syndrome == CHECKSUMS[index])

View File

@@ -0,0 +1,421 @@
/*
* *****************************************************************************
* 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.edac;
import io.github.dsheirer.bits.BinaryMessage;
import java.util.function.ToIntFunction;
/**
* Hard decision minimum distance decoder for binary product codes, where each row is a codeword of a short row code
* and each column is a codeword of a systematic column code with the column parity bits in the final rows.
*
* Finds the minimum weight error pattern that produces the received row and column syndromes, using an iterative
* deepening search over the error patterns (coset) of each information row syndrome. The column parity row errors
* are fully determined by the column syndromes and the information row error choices, and the column parity rows then
* also match their row syndromes, so only the information rows are searched.
*
* Corrects every error pattern up to half the product code minimum distance, and most patterns up to the maximum
* error count. When more than one error pattern has the minimum weight, the received word is equidistant from more
* than one codeword and is treated as uncorrectable.
*
* Row words are integers where bit i (LSB = 0) holds the bit in column i. Instances are thread safe.
*/
public class ProductCodeDecoder
{
public static final int UNCORRECTABLE = -1;
//Bounds the decode time for pathological inputs (~20 ms). Error injection testing with random error patterns of
//each weight: the largest search was 630k nodes (3 ms) for BPTC(196,96) with a maximum error count of 12.
private static final long MAXIMUM_SEARCH_NODES = 4_000_000;
private final int mColumnCount;
private final int mRowCount;
private final int mInformationRowCount;
private final int[] mRowChecks;
private final int[] mColumnChecks;
private final int mColumnCheckBits;
private final long mColumnGroupMask;
private final int mMaximumErrors;
private final int[][] mCosets;
private final int[] mMinimumWeights;
/**
* Constructs an instance.
* @param rowChecks parity check matrix column (syndrome of a single bit error) for each row code bit position, where
* the array length is the column count (maximum 20).
* @param columnChecks parity check matrix column for each column code bit position, where the array length is the
* row count. The column code must be systematic, with distinct single bit parity checks for the final (parity)
* rows. For a single (even) parity check column code, each value is 1.
* @param maximumErrors maximum number of bit errors to correct.
*/
public ProductCodeDecoder(int[] rowChecks, int[] columnChecks, int maximumErrors)
{
mColumnCount = rowChecks.length;
mRowCount = columnChecks.length;
mRowChecks = rowChecks.clone();
mColumnChecks = columnChecks.clone();
mMaximumErrors = maximumErrors;
mColumnCheckBits = bitLength(mColumnChecks);
mInformationRowCount = mRowCount - mColumnCheckBits;
if(mColumnCount < 1 || mColumnCount > 20)
{
throw new IllegalArgumentException("Column count must be in range 1 - 20");
}
if(mColumnCount * mColumnCheckBits > Long.SIZE || mInformationRowCount < 1)
{
throw new IllegalArgumentException("Unsupported column code dimensions");
}
//Verify the final rows are the systematic parity rows
int parityChecks = 0;
for(int row = mInformationRowCount; row < mRowCount; row++)
{
int check = mColumnChecks[row];
if(Integer.bitCount(check) != 1 || (parityChecks & check) != 0)
{
throw new IllegalArgumentException("Column code parity rows must have distinct single bit checks");
}
parityChecks |= check;
}
long groupMask = 0;
for(int column = 0; column < mColumnCount; column++)
{
groupMask |= 1L << (column * mColumnCheckBits);
}
mColumnGroupMask = groupMask;
//Coset lists: the error patterns for each row syndrome, up to the maximum error count, ordered by weight
int syndromeCount = 1 << bitLength(mRowChecks);
int maximumWeight = Math.min(maximumErrors, mColumnCount);
int wordCount = 1 << mColumnCount;
int[] syndromes = new int[wordCount];
int[] sizes = new int[syndromeCount];
for(int word = 0; word < wordCount; word++)
{
syndromes[word] = getSyndrome(word, mRowChecks);
if(Integer.bitCount(word) <= maximumWeight)
{
sizes[syndromes[word]]++;
}
}
mCosets = new int[syndromeCount][];
mMinimumWeights = new int[syndromeCount];
for(int syndrome = 0; syndrome < syndromeCount; syndrome++)
{
mCosets[syndrome] = new int[sizes[syndrome]];
}
int[] filled = new int[syndromeCount];
for(int weight = 0; weight <= maximumWeight; weight++)
{
for(int word = 0; word < wordCount; word++)
{
if(Integer.bitCount(word) == weight)
{
int syndrome = syndromes[word];
mCosets[syndrome][filled[syndrome]++] = word;
}
}
}
for(int syndrome = 0; syndrome < syndromeCount; syndrome++)
{
mMinimumWeights[syndrome] = mCosets[syndrome].length > 0 ? Integer.bitCount(mCosets[syndrome][0]) :
maximumWeight + 1;
}
}
/**
* Number of bits needed to represent the largest value.
*/
private static int bitLength(int[] values)
{
int combined = 0;
for(int value: values)
{
combined |= value;
}
return Integer.SIZE - Integer.numberOfLeadingZeros(combined);
}
/**
* Calculates the parity check matrix columns for a code from a syndrome calculator, as the syndrome of each single
* bit error.
* @param length of the code in bits
* @param syndrome calculator for a binary message of the code length.
* @return parity check matrix column for each bit position.
*/
public static int[] getParityChecks(int length, ToIntFunction<BinaryMessage> syndrome)
{
int[] checks = new int[length];
for(int i = 0; i < length; i++)
{
BinaryMessage message = new BinaryMessage(length);
message.set(i);
checks[i] = syndrome.applyAsInt(message);
}
return checks;
}
/**
* Calculates the syndrome of the word.
* @param word where bit i (LSB = 0) is code bit position i
* @param checks parity check matrix column for each bit position
* @return syndrome, zero for a valid codeword.
*/
public static int getSyndrome(int word, int[] checks)
{
int syndrome = 0;
while(word != 0)
{
syndrome ^= checks[Integer.numberOfTrailingZeros(word)];
word &= word - 1;
}
return syndrome;
}
/**
* Indicates if all rows and columns are valid codewords.
* @param rows to check
* @return true if valid.
*/
public boolean isValid(int[] rows)
{
long columnSyndromes = 0;
for(int row = 0; row < mRowCount; row++)
{
if(getSyndrome(rows[row], mRowChecks) != 0)
{
return false;
}
columnSyndromes ^= getColumnContribution(row, rows[row]);
}
return columnSyndromes == 0;
}
/**
* Corrects the rows to the nearest valid product codeword when the number of bit errors doesn't exceed the
* maximum error count and the nearest codeword is unique.
* @param rows to correct, where bit i of each row is the bit in column i. Unchanged when uncorrectable.
* @return number of corrected bit errors, or UNCORRECTABLE.
*/
public int decode(int[] rows)
{
if(rows.length != mRowCount)
{
throw new IllegalArgumentException("Expected " + mRowCount + " rows");
}
Search search = new Search();
boolean rowErrors = false;
for(int row = 0; row < mRowCount; row++)
{
search.mRowSyndromes[row] = getSyndrome(rows[row], mRowChecks);
rowErrors |= search.mRowSyndromes[row] != 0;
search.mColumnSyndromes ^= getColumnContribution(row, rows[row]);
}
if(!rowErrors && search.mColumnSyndromes == 0)
{
return 0;
}
//Lower bound on the error count of the remaining rows, including the column parity rows, at each search depth
int lowerBound = 0;
for(int row = mInformationRowCount; row < mRowCount; row++)
{
lowerBound += mMinimumWeights[search.mRowSyndromes[row]];
}
search.mLowerBounds[mInformationRowCount] = lowerBound;
for(int row = mInformationRowCount - 1; row >= 0; row--)
{
search.mLowerBounds[row] = search.mLowerBounds[row + 1] + mMinimumWeights[search.mRowSyndromes[row]];
}
int start = Math.max(search.mLowerBounds[0], getErrorColumnCount(search.mColumnSyndromes));
for(search.mBudget = start; search.mBudget <= mMaximumErrors; search.mBudget++)
{
search(search, 0, 0, 0L);
if(search.mAborted || search.mSolutionCount > 1)
{
return UNCORRECTABLE;
}
if(search.mSolutionCount == 1)
{
for(int row = 0; row < mInformationRowCount; row++)
{
rows[row] ^= search.mSolution[row];
}
long residual = search.mColumnSyndromes ^ search.mSolutionContribution;
for(int row = mInformationRowCount; row < mRowCount; row++)
{
int check = mColumnChecks[row];
for(int column = 0; column < mColumnCount; column++)
{
if(((residual >>> (column * mColumnCheckBits)) & check) != 0)
{
rows[row] ^= 1 << column;
}
}
}
return search.mBudget;
}
}
return UNCORRECTABLE;
}
/**
* Depth first search over the information row error patterns, for solutions that don't exceed the error budget.
* @param search state
* @param row to choose an error pattern for
* @param used error count of the error patterns chosen for the preceding rows
* @param contribution to the column syndromes from the error patterns chosen for the preceding rows
*/
private void search(Search search, int row, int used, long contribution)
{
if(++search.mNodes > MAXIMUM_SEARCH_NODES)
{
search.mAborted = true;
return;
}
//The remaining column syndromes must be resolved by the remaining rows
long residual = search.mColumnSyndromes ^ contribution;
if(row == mInformationRowCount)
{
//Each remaining column syndrome bit is a column parity row error
if(used + Long.bitCount(residual) <= search.mBudget && ++search.mSolutionCount == 1)
{
System.arraycopy(search.mChosen, 0, search.mSolution, 0, mInformationRowCount);
search.mSolutionContribution = contribution;
}
return;
}
if(used + Math.max(search.mLowerBounds[row], getErrorColumnCount(residual)) > search.mBudget)
{
return;
}
int remainingLowerBound = search.mLowerBounds[row + 1];
for(int error: mCosets[search.mRowSyndromes[row]])
{
int weight = Integer.bitCount(error);
if(used + weight + remainingLowerBound > search.mBudget)
{
break; //Error patterns are ordered by weight
}
search.mChosen[row] = error;
search(search, row + 1, used + weight, contribution ^ getColumnContribution(row, error));
if(search.mAborted || search.mSolutionCount > 1)
{
return;
}
}
}
/**
* Calculates the contribution of a row word to the column syndromes, where the syndrome for each column occupies
* a group of column check bits, starting with column 0 in the LSBs.
*/
private long getColumnContribution(int row, int word)
{
long contribution = 0;
long check = mColumnChecks[row];
while(word != 0)
{
contribution ^= check << (Integer.numberOfTrailingZeros(word) * mColumnCheckBits);
word &= word - 1;
}
return contribution;
}
/**
* Number of columns with a non-zero syndrome, where each requires at least one more bit error.
*/
private int getErrorColumnCount(long columnSyndromes)
{
long folded = columnSyndromes;
for(int shift = 1; shift < mColumnCheckBits; shift++)
{
folded |= columnSyndromes >>> shift;
}
return Long.bitCount(folded & mColumnGroupMask);
}
/**
* Search state for a single decode.
*/
private final class Search
{
private final int[] mRowSyndromes = new int[mRowCount];
private final int[] mLowerBounds = new int[mInformationRowCount + 1];
private final int[] mChosen = new int[mInformationRowCount];
private final int[] mSolution = new int[mInformationRowCount];
private long mColumnSyndromes;
private long mSolutionContribution;
private int mBudget;
private int mSolutionCount;
private long mNodes;
private boolean mAborted;
}
}

View File

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

View File

@@ -1,444 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.filter;
import java.awt.Component;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.CellEditorListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreeSelectionModel;
/**
* Editor panel for managing the state of a filter set.
*
* @param <T> element type for the filter set.
*/
public class FilterEditorPanel<T> extends JPanel
{
private static final long serialVersionUID = 1L;
private JTree mTree;
private DefaultTreeModel mModel;
private FilterSet<T> mFilterSet;
/**
* Constructs an instance
* @param filterSet to manage
*/
public FilterEditorPanel(FilterSet<T> filterSet)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mFilterSet = filterSet;
init();
}
/**
* Initializes the panel and the tree model.
*/
private void init()
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode(mFilterSet);
mModel = new DefaultTreeModel(root);
addFilterSet(mFilterSet, root);
mTree = new JTree(mModel);
mTree.setShowsRootHandles(true);
mTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
mTree.setCellRenderer(new EditorTreeCellRenderer());
mTree.setCellEditor(new FilterTreeCellEditor());
mTree.setEditable(true);
add(mTree);
}
/**
* Updates the filter set for this editor panel
* @param filterSet to use
*/
public void updateFilterSet(FilterSet<T> filterSet)
{
remove(mTree);
mFilterSet = filterSet;
init();
revalidate();
}
/**
* Adds the filter set as a child tree node to the parent.
* @param filterSet to add to the tree
* @param parent node for the filter set child tree node.
*/
private void addFilterSet(FilterSet<T> filterSet, DefaultMutableTreeNode parent)
{
List<IFilter<T>> filters = filterSet.getFilters();
for(IFilter<T> filter : filters)
{
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(filter);
mModel.insertNodeInto(childNode, parent, parent.getChildCount());
if(filter instanceof FilterSet childFilterSet)
{
addFilterSet(childFilterSet, childNode);
}
else if(filter instanceof Filter childFilter)
{
addFilter(childFilter, childNode);
}
}
}
/**
* Adds the filter as a child tree node to the parent.
*
* @param filter to add
* @param parent tree node
*/
private void addFilter(Filter filter, DefaultMutableTreeNode parent)
{
List<FilterElement<?>> elements = filter.getFilterElements();
elements.sort(Comparator.comparing(FilterElement::getName));
for(FilterElement<?> element : elements)
{
DefaultMutableTreeNode child = new DefaultMutableTreeNode(element);
mModel.insertNodeInto(child, parent, parent.getChildCount());
}
}
/**
* Accesses the tree's root tree node.
* @return root node.
*/
private DefaultMutableTreeNode getRoot()
{
if(mTree.getModel().getRoot() instanceof DefaultMutableTreeNode root)
{
return root;
}
return null;
}
/**
* Recursively sets the enabled state on all filter node children below the specified parent node.
*
* @param model - model containing the tree nodes
* @param node - parent node
* @param enabled - true or false to enable or disable the filters
*/
private void setFilterEnabled(DefaultTreeModel model, DefaultMutableTreeNode node, boolean enabled)
{
Object obj = node.getUserObject();
if(obj instanceof FilterElement filterElement)
{
filterElement.setEnabled(enabled);
}
/* Recursively set the children of this node */
Enumeration<?> children = node.children();
while(children.hasMoreElements())
{
Object child = children.nextElement();
if(child instanceof DefaultMutableTreeNode childNode)
{
setFilterEnabled(model, childNode, enabled);
}
}
model.nodeChanged(node);
}
/**
* Recursively searches the tree to find the tree node containing the specified filter element.
*
* @param node to start search
* @param element to find
*/
private DefaultMutableTreeNode findFilterElementNode(DefaultMutableTreeNode node, FilterElement<?> element)
{
if(node != null)
{
if(node.getUserObject() instanceof FilterElement<?> selfFilterElement && selfFilterElement.equals(element))
{
return node;
}
for(int x = 0; x < node.getChildCount(); x++)
{
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
{
DefaultMutableTreeNode found = findFilterElementNode(child, element);
if(found != null)
{
return found;
}
}
}
}
return null;
}
/**
* Updates the display value for the specified node and all parents in the nodes parentage.
* @param node to update
*/
private void updateParentage(DefaultMutableTreeNode node)
{
mModel.nodeChanged(node);
TreeNode parent = node.getParent();
while(parent != null)
{
mModel.nodeChanged(parent);
parent = parent.getParent();
}
}
/**
* Recursively searches the tree to find the tree node containing the specified filter.
*
* @param node to start search
* @param filter to find
*/
private DefaultMutableTreeNode findFilterNode(DefaultMutableTreeNode node, IFilter<?> filter)
{
if(node != null)
{
if(node.getUserObject() instanceof IFilter<?> selfFilter && selfFilter.equals(filter))
{
return node;
}
for(int x = 0; x < node.getChildCount(); x++)
{
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
{
DefaultMutableTreeNode found = findFilterNode(child, filter);
if(found != null)
{
return found;
}
}
}
}
else
{
System.out.println("Can't evaluate - node is null");
}
return null;
}
/**
* Custom cell renderer
*/
public class EditorTreeCellRenderer extends DefaultTreeCellRenderer
{
private static final long serialVersionUID = 1L;
public Component getTreeCellRendererComponent(JTree tree, Object treeNode, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus)
{
if(treeNode instanceof DefaultMutableTreeNode)
{
Object userObject = ((DefaultMutableTreeNode) treeNode).getUserObject();
JCheckBox checkBox = null;
if(userObject instanceof IFilter filter)
{
checkBox = new FilterCheckBox(filter);
checkBox.setSelected(filter.isEnabled());
}
else if(userObject instanceof FilterElement element)
{
checkBox = new FilterElementCheckBox(element);
checkBox.setSelected(element.isEnabled());
}
if(checkBox != null)
{
if(selected)
{
checkBox.setForeground(getTextSelectionColor());
checkBox.setBackground(getBackgroundSelectionColor());
}
else
{
checkBox.setForeground(getTextNonSelectionColor());
checkBox.setBackground(getBackgroundNonSelectionColor());
}
return checkBox;
}
}
return super.getTreeCellRendererComponent(tree, treeNode, selected, expanded, leaf, row, hasFocus);
}
}
/**
* Check box used in filter tree nodes
*/
public class FilterCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private IFilter<?> mFilter;
/**
* Constructs an instance
*
* @param filter
*/
public FilterCheckBox(IFilter<?> filter)
{
mFilter = filter;
setSelected(mFilter.isEnabled());
addItemListener(e -> {
DefaultMutableTreeNode selfNode = findFilterNode(getRoot(), mFilter);
if(selfNode != null)
{
setFilterEnabled(mModel, selfNode, FilterCheckBox.this.isSelected());
updateLabel();
updateParentage(selfNode);
}
});
}
@Override
public void setSelected(boolean b)
{
super.setSelected(b);
updateLabel();
}
public void updateLabel()
{
setText(mFilter.getName() + " (" + mFilter.getEnabledCount() + "/" + mFilter.getElementCount() + ")");
}
}
/**
* Check box used in filter element tree nodes
*/
public class FilterElementCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private FilterElement<?> mFilter;
/**
* Constructs an instance
*
* @param filter element
*/
public FilterElementCheckBox(FilterElement<?> filter)
{
super(filter.getName());
mFilter = filter;
setSelected(mFilter.isEnabled());
addItemListener(arg0 -> {
mFilter.setEnabled(FilterElementCheckBox.this.isSelected());
DefaultMutableTreeNode self = findFilterElementNode(getRoot(), mFilter);
if(self != null)
{
updateParentage(self);
}
});
}
}
/**
* Editor for filter tree nodes
*/
public class FilterTreeCellEditor implements TreeCellEditor
{
@Override
public Component getTreeCellEditorComponent(JTree tree, Object node, boolean isSelected, boolean expanded, boolean leaf, int row)
{
if(node instanceof DefaultMutableTreeNode mutableTreeNode)
{
Object userObject = mutableTreeNode.getUserObject();
if(userObject instanceof IFilter filter)
{
return new FilterCheckBox(filter);
}
else if(userObject instanceof FilterElement filterElement)
{
return new FilterElementCheckBox(filterElement);
}
}
return new JLabel(node.toString());
}
@Override
public void addCellEditorListener(CellEditorListener l) {}
@Override
public void cancelCellEditing() {}
@Override
public Object getCellEditorValue()
{
return null;
}
@Override
public boolean isCellEditable(EventObject anEvent)
{
return true;
}
@Override
public void removeCellEditorListener(CellEditorListener l) {}
@Override
public boolean shouldSelectCell(EventObject anEvent)
{
return false;
}
@Override
public boolean stopCellEditing()
{
return false;
}
}
}

View File

@@ -0,0 +1,231 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui;
import java.awt.Image;
import java.awt.Taskbar;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.stage.Stage;
import javafx.stage.Window;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* sdrtrunk application icon for JavaFX stages and the macOS Dock.
*
* Call installJavaFx() once the JavaFX toolkit is running, which also sets the macOS Dock icon. After that, each
* window that opens without its own icon gets the sdrtrunk icon, so individual windows don't have to set it.
*/
public final class ApplicationIcons
{
private static final Logger mLog = LoggerFactory.getLogger(ApplicationIcons.class);
private static final String RESOURCE_PATTERN = "/images/sdrtrunk/sdrtrunk-icon-%d.png";
private static final int[] SIZES = {16, 24, 32, 48, 64, 128, 256, 512};
private static final int TASKBAR_SIZE = 512;
private static List<Image> sAwtImages;
private static List<javafx.scene.image.Image> sFxImages;
private static boolean sTaskbarInstalled;
private static boolean sJavaFxInstalled;
private ApplicationIcons()
{
}
/**
* Application icon in each available size, smallest first, as AWT images for the macOS Dock.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<Image> getAwtImages()
{
if(sAwtImages == null)
{
List<Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
Image image = ImageIO.read(in);
if(image != null)
{
images.add(image);
}
}
else
{
mLog.warn("Application icon resource not found [" + path + "]");
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sAwtImages = Collections.unmodifiableList(images);
}
return sAwtImages;
}
/**
* Application icon in each available size, smallest first, for JavaFX stages.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<javafx.scene.image.Image> getFxImages()
{
if(sFxImages == null)
{
List<javafx.scene.image.Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
javafx.scene.image.Image image = new javafx.scene.image.Image(in);
if(!image.isError())
{
images.add(image);
}
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sFxImages = Collections.unmodifiableList(images);
}
return sFxImages;
}
/**
* Sets the application icon on the JavaFX stage if it doesn't already have one. Call on the FX thread.
*/
public static void apply(Stage stage)
{
if(stage != null && stage.getIcons().isEmpty() && !getFxImages().isEmpty())
{
stage.getIcons().setAll(getFxImages());
}
}
/**
* Sets the macOS Dock icon. Windows and Linux take the icon from each window instead. Safe to call more than
* once. Does nothing in a headless environment.
*/
public static synchronized void installTaskbarIcon()
{
if(sTaskbarInstalled || java.awt.GraphicsEnvironment.isHeadless())
{
return;
}
sTaskbarInstalled = true;
try
{
if(Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
{
List<Image> images = getAwtImages();
for(int x = 0; x < SIZES.length && x < images.size(); x++)
{
if(SIZES[x] == TASKBAR_SIZE)
{
Taskbar.getTaskbar().setIconImage(images.get(x));
}
}
}
}
catch(Exception e)
{
mLog.debug("Unable to set taskbar icon", e);
}
}
/**
* Gives each JavaFX stage that shows without an icon the application icon, and closes the startup splash screen
* if a JavaFX window opens before the main window does. Safe to call more than once. The JavaFX toolkit must
* already be running.
*/
public static synchronized void installJavaFx()
{
if(sJavaFxInstalled)
{
return;
}
sJavaFxInstalled = true;
installTaskbarIcon();
Platform.runLater(() -> {
for(Window window: Window.getWindows())
{
onFxWindowShown(window);
}
Window.getWindows().addListener((ListChangeListener<Window>)change -> {
while(change.next())
{
for(Window window: change.getAddedSubList())
{
onFxWindowShown(window);
}
}
});
});
}
/**
* Handles a JavaFX window that is showing.
*/
private static void onFxWindowShown(Window window)
{
//Only stages are top-level windows. Popups (menus, tooltips) are other Window types.
if(window instanceof Stage stage)
{
apply(stage);
//A JavaFX window (e.g. an error dialog) that shows before the main window would sit behind the splash.
Splash.close();
}
}
}

View File

@@ -0,0 +1,131 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui;
import java.awt.image.BufferedImage;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
/**
* Starts the JavaFX toolkit, runs work on the JavaFX application thread and converts images for ImageIO.
*/
public class FxToolkit
{
private static boolean sStarted;
private FxToolkit()
{
}
/**
* Starts the JavaFX toolkit if it isn't running. Safe to call more than once and from any thread except the
* JavaFX application thread before the toolkit starts.
*/
public static synchronized void ensureStarted()
{
if(sStarted)
{
return;
}
try
{
Platform.startup(() -> {});
}
catch(IllegalStateException alreadyStarted)
{
//The toolkit is already running
}
Platform.setImplicitExit(false);
ApplicationIcons.installJavaFx();
sStarted = true;
}
/**
* Indicates if the toolkit was started.
*/
public static synchronized boolean isStarted()
{
return sStarted;
}
/**
* Runs the callable on the JavaFX application thread and waits for the result.
* @throws Exception thrown by the callable
*/
public static <T> T callAndWait(Callable<T> callable) throws Exception
{
if(Platform.isFxApplicationThread())
{
return callable.call();
}
CompletableFuture<T> future = new CompletableFuture<>();
Platform.runLater(() -> {
try
{
future.complete(callable.call());
}
catch(Throwable t)
{
future.completeExceptionally(t);
}
});
try
{
return future.get();
}
catch(ExecutionException e)
{
if(e.getCause() instanceof Exception exception)
{
throw exception;
}
throw e;
}
}
/**
* Converts the JavaFX image to an AWT image for writing with ImageIO.
*/
public static BufferedImage toBufferedImage(Image image)
{
int width = (int)image.getWidth();
int height = (int)image.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
PixelReader reader = image.getPixelReader();
int[] row = new int[width];
for(int y = 0; y < height; y++)
{
reader.getPixels(0, y, width, 1, javafx.scene.image.PixelFormat.getIntArgbInstance(), row, 0, width);
bufferedImage.setRGB(0, y, width, 1, row, 0, width);
}
return bufferedImage;
}
}

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