Compare commits

..

59 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
Denny Sheirer
a53f6e9d99 #2628 Remove ThumbDV code support. (#2629)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-12 05:18:52 -05:00
Steve Pinkham
e7f4f655e5 C4FM: bounds check the start of the buffer in the sync score (#2622)
A lagging sync detect on the first symbol after a buffer reload, followed by a
coarse timing search that steps all the way left, scores a candidate whose first
sync symbol is one sample before the buffer start. score() only checked the end
of the buffer, so it threw ArrayIndexOutOfBoundsException: Index -1.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:22:44 -05:00
Denny Sheirer
000ac51ff0 #2621 Windows rtl-sdr crashing on retune documented in issue https://github.com/DSheirer/jRTL/issues/4 (#2624)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-11 03:16:02 -05:00
Denny Sheirer
23cee388de #2616 Gradle Runtime plugin configuration and remove local JDK support in the build script (#2617)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-10 03:42:46 -05:00
Denny Sheirer
5c73fb318f #2614 Gradle not including JFXPanel in build artifacts (#2615)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-10 03:09:41 -05:00
Denny Sheirer
066554393f #2612 Strips unused OS/arch tuner libraries from final build artifacts
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-10 02:46:03 -05:00
Denny Sheirer
303c0a98cc #2610 gradle script cleanup (#2611)
* #2610 Gradle 9.9.0 and build script cleanup

---------

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-10 02:15:51 -05:00
Denny Sheirer
02c62d012f #2557 DMR improved error detection in voice frames and voice events. (#2608)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-09 03:49:58 -05:00
624 changed files with 59045 additions and 38556 deletions

View File

@@ -14,6 +14,9 @@ jobs:
steps: steps:
- uses: actions/checkout@v7 - 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 - name: Set up JDK 27
uses: actions/setup-java@v6 uses: actions/setup-java@v6
@@ -34,7 +37,7 @@ jobs:
- name: Create Build Info file - name: Create Build Info file
run: | 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 - name: Add build artifacts to nightly release
uses: softprops/action-gh-release@v3 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 # Publishes a release when a version tag is pushed: v0.6.2 for a final release,
# projectVersion in gradle.properties with a leading 'v': v0.6.2 for a final # or v0.6.2-beta-1 / v0.6.2-alpha-1 for a pre-release. The build derives the
# release, or v0.6.2-beta-1 / v0.6.2-alpha-1 for a pre-release. # version from the tag (see build.gradle).
name: Release name: Release
on: on:
@@ -22,15 +22,6 @@ jobs:
# Full history and tags, to find the previous release tag for the release notes # Full history and tags, to find the previous release tag for the release notes
fetch-depth: 0 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 # 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. # starts from the previous final release, so it covers every alpha and beta in between.
- id: previous - id: previous
@@ -54,6 +45,17 @@ jobs:
- name: Set up Gradle - name: Set up Gradle
uses: gradle/actions/setup-gradle@v6 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 - name: Build and test
run: ./gradlew clean build --console=plain 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) ![Gradle Build](https://github.com/dsheirer/sdrtrunk/actions/workflows/gradle.yml/badge.svg)
![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg) ![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg)
[![Latest Release](https://img.shields.io/github/v/release/DSheirer/sdrtrunk?label=release)](https://github.com/DSheirer/sdrtrunk/releases/latest)
# MacOS Tahoe 26.1 Users - Attention: [![Downloads](https://img.shields.io/github/downloads/DSheirer/sdrtrunk/total)](https://github.com/DSheirer/sdrtrunk/releases)
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. [![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)
brew install libusb --HEAD
cd /opt
sudo mkdir local
cd local
sudo mkdir lib
```
Next, find where brew installed the libusb library, for example: ```/opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib``` Note: the folder "HEAD-9ceaa52" is the version stamp for HEAD when you installed from it.
Finally, create a symbolic link from the installed library to the place where usb4java is expecting to find libusb (/opt/local/lib/libusb-1.0.0.dylib)
```
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
# sdrtrunk # sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR). A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
> ## 📖 [Read the sdrtrunk User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
> New to sdrtrunk? Start with the **[Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)** guide,
> then use the **[User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)** and
> **[How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)** to set up tuners, playlists, aliases and streaming.
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki) * [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started) * [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User'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) * [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support) * [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk Application](https://github.com/DSheirer/sdrtrunk/wiki/images/sdrtrunk.png) ![sdrtrunk primary application window decoding a P25 trunked radio system](https://github.com/DSheirer/sdrtrunk/wiki/images/application_overview.png)
**Figure 1:** sdrtrunk Application Screenshot **Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
## Download the Latest Release ## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab. All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.
@@ -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 Releases are built and published automatically by the [Release](.github/workflows/release.yml) GitHub workflow
whenever a version tag is pushed to the repository. 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 The version is taken from the tag, so there is no version number to update in the code. Create and push a tag
that file (e.g. `0.6.2-alpha-1`, `0.6.2-beta-1` or `0.6.2`). with a leading `v`, following the naming convention described in `gradle.properties` (e.g. `v0.6.2-alpha-1`,
2. Commit and push the change to `master`. `v0.6.2-beta-1` or `v0.6.2`):
3. Create and push a tag that matches the version with a leading `v`:
``` ```
git tag v0.6.2-beta-1 git tag v0.6.2-beta-1
git push origin 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: 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). * 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 * 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 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' 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 27 is required for this version of the Project Panama preview/incubator feature
java { java {
@@ -95,56 +131,52 @@ test {
dependencies { dependencies {
// JUnit Tests // JUnit Tests
testImplementation(platform("org.junit:junit-bom:6.0.1")) testImplementation(platform("org.junit:junit-bom:6.1.3"))
testImplementation 'org.junit.jupiter:junit-jupiter-api:6.0.1' testImplementation 'org.junit.jupiter:junit-jupiter-api'
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:6.0.1") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:6.0.1")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") testRuntimeOnly("org.junit.platform:junit-platform-launcher")
//Jitpack imports //Jitpack imports
implementation 'com.github.dnault:libresample4j:master' implementation 'com.github.dnault:libresample4j:master'
implementation 'com.github.DSheirer.jmbe:api:v2.1.0'
implementation 'com.github.nwaldispuehl:java-lame:v3.98.4' implementation 'com.github.nwaldispuehl:java-lame:v3.98.4'
//mavenCentral/jcenter imports //mavenCentral/jcenter imports
implementation 'ch.qos.logback:logback-classic:1.6.3' implementation 'ch.qos.logback:logback-classic:1.6.6'
implementation 'ch.qos.logback:logback-core:1.5.38' implementation 'ch.qos.logback:logback-core:1.6.6'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.22.4' implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.23.0'
implementation 'com.fazecast:jSerialComm:2.11.4'
implementation 'com.formdev:flatlaf:3.7.2'
implementation 'com.formdev:flatlaf-intellij-themes:3.7.2'
implementation 'com.github.jiconfont:jiconfont-font_awesome:4.7.0.1' implementation 'com.github.jiconfont:jiconfont-font_awesome:4.7.0.1'
implementation 'com.github.jiconfont:jiconfont-javafx:1.0.0' implementation 'com.github.jiconfont:jiconfont-javafx:1.0.0'
implementation 'com.github.jiconfont:jiconfont-swing:1.0.1' implementation('com.github.wendykierp:JTransforms:3.2') {
implementation 'com.github.wendykierp:JTransforms:3.2' exclude group: 'junit' //JLargeArrays 1.7 declares junit as a compile dependency
implementation 'com.google.code.gson:gson:2.14.0' }
implementation 'com.google.guava:guava:33.6.0-jre' implementation 'com.google.code.gson:gson:2.15.0'
implementation 'com.jidesoft:jide-oss:3.6.18' implementation 'com.google.guava:guava:33.8.0-jre'
implementation 'com.miglayout:miglayout-swing:11.4.3' 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 'com.mpatric:mp3agic:0.9.1'
implementation 'commons-io:commons-io:2.22.0' implementation 'commons-io:commons-io:2.22.0'
implementation 'eu.hansolo:charts:1.0.5'
implementation 'io.github.dsheirer:jairspy:1.0.12.1' //Airspy tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jairspy:1.0.12.1' //Airspy tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jairspyhf:1.8.1.1' //Airspy HF+ tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jairspyhf:1.8.1.1' //Airspy HF+ tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jbladerf:2.6.0.1' //bladeRF tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jbladerf:2.6.0.1' //bladeRF tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jhackrf:2026.01.3.1' //HackRF tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jhackrf:2026.01.3.1' //HackRF tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jmbe-api:3.0.0' //JMBE audio codec interfaces - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jlibusb:1.0.30.1' //libusb and USB hotplug for the tuner libraries - GitHub release; not pulled in transitively implementation 'io.github.dsheirer:jlibusb:1.0.30.1' //libusb and USB hotplug for the tuner libraries - GitHub release; not pulled in transitively
implementation 'io.github.dsheirer:jhydrasdr:1.1.4.1' //HydraSDR tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jhydrasdr:1.1.4.1' //HydraSDR tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jlimesdr:25.1.0.2' //LimeSDR tuners - GitHub release, see settings.gradle implementation 'io.github.dsheirer:jlimesdr:25.1.0.2' //LimeSDR tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jrtl:1.4.0.2' //RTL-SDR 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: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 'net.coderazzi:tablefilter-swing:5.5.4' 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-compress:1.28.0' implementation 'org.apache.commons:commons-lang3:3.21.0'
implementation 'org.apache.commons:commons-lang3:3.20.0'
implementation 'org.apache.commons:commons-math3:3.6.1' implementation 'org.apache.commons:commons-math3:3.6.1'
implementation 'org.apache.commons:commons-csv:1.14.1' implementation 'org.apache.commons:commons-csv:1.14.1'
implementation 'org.apache.mina:mina-core:2.2.9' implementation 'org.apache.mina:mina-core:2.2.10'
implementation 'org.apache.mina:mina-http:2.2.9' implementation 'org.apache.mina:mina-http:2.2.10'
implementation 'org.controlsfx:controlsfx:11.2.3' implementation 'org.controlsfx:controlsfx:11.2.6'
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.11' //Optional MariaDB call database
implementation 'org.postgresql:postgresql:42.7.14' //Optional PostgreSQL call database
implementation 'org.rauschig:jarchivelib:1.2.0' implementation 'org.rauschig:jarchivelib:1.2.0'
implementation 'org.slf4j:slf4j-api:2.0.17' implementation 'org.slf4j:slf4j-api:2.0.20'
implementation 'pl.edu.icm:JLargeArrays:1.6'
} }
def os = DefaultNativePlatform.currentOperatingSystem def os = DefaultNativePlatform.currentOperatingSystem
@@ -162,7 +194,6 @@ tasks.withType(JavaCompile).configureEach {
*/ */
def jvmArgsWindows = def jvmArgsWindows =
['--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED', //Needed for controls-fx.jar ['--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED', //Needed for controls-fx.jar
'--add-exports=java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED', //windows users for JIDE
'--add-modules=jdk.incubator.vector', //Project Panama vector API is still in incubator '--add-modules=jdk.incubator.vector', //Project Panama vector API is still in incubator
'--enable-preview', //Project Panama Vector API is still in incubator '--enable-preview', //Project Panama Vector API is still in incubator
'--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls '--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls
@@ -180,6 +211,14 @@ def jvmArgsLinux =
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls '--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries) '--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
/**
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
*/
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
application { application {
mainClass = "io.github.dsheirer.gui.SDRTrunk" mainClass = "io.github.dsheirer.gui.SDRTrunk"
@@ -191,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 { test {
if(os.isWindows()) { if(os.isWindows()) {
jvmArgs = jvmArgsWindows jvmArgs = jvmArgsWindows
@@ -205,6 +254,7 @@ jar {
attributes ( attributes (
'Implementation-Title' : 'sdrtrunk project', 'Implementation-Title' : 'sdrtrunk project',
'Implementation-Version' : archiveVersion, 'Implementation-Version' : archiveVersion,
'Git-Describe' : gitDescribe ?: 'unknown',
'Created-By' : "Gradle ${gradle.gradleVersion}", 'Created-By' : "Gradle ${gradle.gradleVersion}",
'Build-Timestamp' : new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date()), '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']}", 'Build-JDK' : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']}",
@@ -235,18 +285,6 @@ String targetOsxX86_64 = 'osx-x86_64-v' + version
String targetWindowsX86_64 = 'windows-x86_64-v' + version String targetWindowsX86_64 = 'windows-x86_64-v' + version
String targetWindowsAarch64 = 'windows-aarch64-v' + version String targetWindowsAarch64 = 'windows-aarch64-v' + version
/**
* Optional pre-downloaded Java Development Kit (JDK) for each target OS and CPU. These locations are hard-coded to the
* author's development environment, but can be changed to your environment if you want to use this build pattern.
*/
String jdk_base = '/home/denny/java_jdks/'
String jdk_linux_aarch64 = jdk_base + 'linux-arm64/jdk-25.0.1-full'
String jdk_linux_x86_64 = jdk_base + 'linux-x64/jdk-25.0.1-full'
String jdk_osx_x86_64 = jdk_base + 'osx-x64/jdk-25.0.1-full.jdk'
String jdk_osx_aarch64 = jdk_base + 'osx-arm64/jdk-25.0.1-full.jdk'
String jdk_windows_x86_64 = jdk_base + 'windows-x64/jdk-25.0.1-full'
String jdk_windows_aarch64 = jdk_base + 'windows-arm64/jdk-25.0.1-full'
/** /**
* Download URLs to download the JDK as part of the gradle build packaging process * Download URLs to download the JDK as part of the gradle build packaging process
*/ */
@@ -266,8 +304,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
* @return configured task. * @return configured task.
*/ */
def configure(RuntimeZipTask rt, List<String> jvmArgs) { def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//Use the correct set of JVM arguments //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 rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
//Additional modules to include with auto-detected modules. //Additional modules to include with auto-detected modules.
//jdk.charsets - NXDN BIG5 encoding support //jdk.charsets - NXDN BIG5 encoding support
@@ -275,19 +313,156 @@ def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//jdk.incubator.vector - needed for Project Panama foreign function and vector apis //jdk.incubator.vector - needed for Project Panama foreign function and vector apis
//jdk.accessibility is used with assistive technologies like screen readers //jdk.accessibility is used with assistive technologies like screen readers
//java.management for JVM resource monitoring //java.management for JVM resource monitoring
rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management') //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.desktop', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'java.sql',
'java.naming', 'java.security.jgss', 'jdk.net')
//Use auto-detected modules and 'add' any specified modules. //Use only the modules listed above. The runtime plugin's module auto-detection uses a bundled ASM library that
rt.extension.additive.set(true) //can't read Java 27 class files and logs a 'Failed to scan' error for each sdrtrunk class. The jdeps module check
//on the runtime task verifies that this list is complete.
rt.extension.additive.set(false)
//Recommended options for reducing/shrinking runtime target image size //Recommended options for reducing/shrinking runtime target image size
rt.extension.addOptions('--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages') rt.extension.addOptions('--strip-debug', '--compress', 'zip-6', '--no-header-files', '--no-man-pages')
//Runtime images have auto appended version in image zip name. Override to include version in single target image. //Runtime images have auto appended version in image zip name. Override to include version in single target image.
// rt.extension.imageDir=layout.buildDirectory.dir('image') // rt.extension.imageDir=layout.buildDirectory.dir('image')
rt.extension.imageZip.set(file(layout.buildDirectory.dir('image').get().file('sdr-trunk.zip'))) rt.extension.imageZip.set(file(layout.buildDirectory.dir('image').get().file('sdr-trunk.zip')))
} }
/**
* Rewrites the jar file without the native library folders for other operating systems and architectures. Fails the
* build if a jar that contains native libraries doesn't contain the folder for the target.
* @param jar file to rewrite
* @param keep native folder for the target
* @return number of bytes removed from the jar
*/
long stripJar(File jar, String keep) {
def tunerPattern = ~/^[^\/]+\/native\/([^\/]+)\/.*/
def removed = [] as Set
def hadTuner = false, keptTuner = false
File temp = new File(jar.parentFile, jar.name + '.tmp')
new java.util.zip.ZipFile(jar).withCloseable { zip ->
def entries = zip.entries().toList()
entries.each { e ->
def tuner = tunerPattern.matcher(e.name)
if(tuner.matches()) {
hadTuner = true
if(tuner.group(1) == keep) { keptTuner = true } else { removed << e.name }
}
}
if(hadTuner && !keptTuner) {
throw new GradleException("Native strip: ${jar.name} has no native/${keep} folder")
}
if(!removed.isEmpty()) {
new java.util.zip.ZipOutputStream(new FileOutputStream(temp)).withCloseable { out ->
entries.findAll { !removed.contains(it.name) }.each { e ->
def copy = new java.util.zip.ZipEntry(e)
if(copy.method == java.util.zip.ZipEntry.DEFLATED) {
copy.compressedSize = -1
}
out.putNextEntry(copy)
zip.getInputStream(e).withCloseable { out << it }
out.closeEntry()
}
}
}
}
if(removed.isEmpty()) {
return 0
}
long before = jar.length()
java.nio.file.Files.move(temp.toPath(), jar.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
return before - jar.length()
}
/**
* Removes the native libraries for other operating systems and architectures from the jars in each runtime target
* image, before the runtimeZip tasks package the images. The tuner libraries (jRTL, jAirspy, etc.) package their
* native libraries under '<library>/native/<os>-<arch>/', where the folder name matches the runtime target name
* '<os>-<arch>-v<version>' without the version suffix, except that the libraries use 'macos' where the target uses 'osx'.
*/
tasks.named('runtime') {rt ->
rt.doLast {
rt.targetPlatforms.get().keySet().each { target ->
def nativeFolder = (target - "-v${version}").replaceFirst(/^osx-/, 'macos-')
def lib = new File(rt.imageDir.asFile, "${project.name}-${target}/lib")
long total = 0
lib.listFiles({ File f -> f.name.endsWith('.jar') } as FileFilter).each { jar ->
total += stripJar(jar, nativeFolder)
}
logger.lifecycle("Native strip: removed ${String.format('%.1f', total / 1048576)} MB of other " +
"platform native libraries from [${target}]")
}
}
}
/**
* 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
* class files compiled for a newer Java version).
*/
def jdepsHome = javaToolchains.launcherFor(java.toolchain).map { it.metadata.installationPath.asFile }
def mainJar = tasks.named('jar').flatMap { it.archiveFile }
tasks.named('runtime') {rt ->
rt.doLast {
def jdeps = new File(jdepsHome.get(), 'bin/' + (os.isWindows() ? 'jdeps.exe' : 'jdeps')).absolutePath
def process = new ProcessBuilder(jdeps, '--multi-release', java.toolchain.languageVersion.get().toString(),
'--ignore-missing-deps', '--print-module-deps', '-q', mainJar.get().asFile.absolutePath)
.redirectErrorStream(true).start()
def output = process.inputStream.text.trim()
if(process.waitFor() != 0) {
throw new GradleException("Module check: jdeps failed: ${output}")
}
def required = output.split(',')*.trim().findAll { it } as Set
rt.targetPlatforms.get().keySet().each { target ->
def release = new File(rt.imageDir.asFile, "${project.name}-${target}/release")
def match = release.text =~ /(?m)^MODULES="([^"]*)"/
if(!match.find()) {
throw new GradleException("Module check: no MODULES entry in ${release}")
}
def missing = required - (match.group(1).split(' ') as Set)
if(missing) {
throw new GradleException("Module check: runtime image [${target}] is missing required modules " +
"${missing.sort()} - add them to addModules() in build.gradle")
}
}
logger.lifecycle("Module check: runtime images contain all modules required by sdrtrunk: ${required.sort()}")
}
}
/** /**
* Creates a release package for the current operating system. * Creates a release package for the current operating system.
* *
@@ -344,22 +519,12 @@ tasks.register('runtimeZipCurrent', RuntimeZipTask) {rt ->
*/ */
tasks.register('runtimeZipWindows', RuntimeZipTask) {rt -> tasks.register('runtimeZipWindows', RuntimeZipTask) {rt ->
//Windows aarch64 //Windows aarch64
if(file(jdk_windows_aarch64).exists()) { rt.extension.targetPlatform(targetWindowsAarch64) {
rt.extension.targetPlatform(targetWindowsAarch64, jdk_windows_aarch64, []) jdkHome = jdkDownload(jdk_download_windows_aarch64)
}
else {
rt.extension.targetPlatform(targetWindowsAarch64) {
jdkHome = jdkDownload(jdk_download_windows_aarch64)
}
} }
//Windows x86-64 //Windows x86-64
if(file(jdk_windows_x86_64).exists()) { rt.extension.targetPlatform(targetWindowsX86_64) {
rt.extension.targetPlatform(targetWindowsX86_64, jdk_windows_x86_64, []) jdkHome = jdkDownload(jdk_download_windows_x86_64)
}
else {
rt.extension.targetPlatform(targetWindowsX86_64) {
jdkHome = jdkDownload(jdk_download_windows_x86_64)
}
} }
configure(rt, jvmArgsWindows) configure(rt, jvmArgsWindows)
@@ -376,40 +541,20 @@ tasks.register('runtimeZipWindows', RuntimeZipTask) {rt ->
*/ */
tasks.register('runtimeZipOthers', RuntimeZipTask) {rt -> tasks.register('runtimeZipOthers', RuntimeZipTask) {rt ->
//Linux aarch64 //Linux aarch64
if(file(jdk_linux_aarch64).exists()) { rt.extension.targetPlatform(targetLinuxAarch64) {
rt.extension.targetPlatform(targetLinuxAarch64, jdk_linux_aarch64, []) jdkHome = jdkDownload(jdk_download_linux_aarch64)
}
else {
rt.extension.targetPlatform(targetLinuxAarch64) {
jdkHome = jdkDownload(jdk_download_linux_aarch64)
}
} }
//Linux x86-64 //Linux x86-64
if(file(jdk_linux_x86_64).exists()) { rt.extension.targetPlatform(targetLinuxX86_64) {
rt.extension.targetPlatform(targetLinuxX86_64, jdk_linux_x86_64, []) jdkHome = jdkDownload(jdk_download_linux_x86_64)
}
else {
rt.extension.targetPlatform(targetLinuxX86_64) {
jdkHome = jdkDownload(jdk_download_linux_x86_64)
}
} }
//OSX aarch64 //OSX aarch64
if(file(jdk_osx_aarch64).exists()) { rt.extension.targetPlatform(targetOsxAarch64) {
rt.extension.targetPlatform(targetOsxAarch64, jdk_osx_aarch64, []) jdkHome = jdkDownload(jdk_download_osx_aarch64)
}
else {
rt.extension.targetPlatform(targetOsxAarch64) {
jdkHome = jdkDownload(jdk_download_osx_aarch64)
}
} }
//OSX x86-64 //OSX x86-64
if(file(jdk_osx_x86_64).exists()) { rt.extension.targetPlatform(targetOsxX86_64) {
rt.extension.targetPlatform(targetOsxX86_64, jdk_osx_x86_64, []) jdkHome = jdkDownload(jdk_download_osx_x86_64)
}
else {
rt.extension.targetPlatform(targetOsxX86_64) {
jdkHome = jdkDownload(jdk_download_osx_x86_64)
}
} }
configure(rt, jvmArgsLinux) configure(rt, jvmArgsLinux)

View File

@@ -17,15 +17,16 @@
# ***************************************************************************** # *****************************************************************************
# #
# Version naming conventions: # The project version is no longer defined here. It is derived from the most recent 'v<version>' git tag (see
# Alpha: maj.min.patch-alpha-build # build.gradle) and can be overridden with -PprojectVersion=<version>.
# Beta: maj.min.patch-beta-build
# Release: maj.min.patch
# #
# 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. # tag name, specifically the dashes inserted before and after the alpha/beta labels.
# See: https://github.com/DSheirer/sdrtrunk/issues/1651 # See: https://github.com/DSheirer/sdrtrunk/issues/1651
projectVersion=1.0.0-beta-1

Binary file not shown.

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip
networkTimeout=10000 networkTimeout=10000
retries=0 retries=0
retryBackOffMs=500 retryBackOffMs=500

52
gradlew.bat vendored
View File

@@ -26,6 +26,33 @@
@rem Set local scope for the variables, and ensure extensions are enabled @rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions setlocal EnableExtensions
@rem Catch executions from older scripts and ensure they exit cleanly.
@rem This can be removed once we can be reasonably confident that few people
@rem will be migrating directly to this new wrapper.
goto afterSafetyNet
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto exitWithErrorLevel
:afterSafetyNet
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused @rem This is normally unused
@@ -45,13 +72,14 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2 1>&2 echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo. 1>&2 1>&2 echo.
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. 1>&2 1>&2 echo location of your Java installation.
"%COMSPEC%" /c exit 1 "%COMSPEC%" /c exit 1
goto exitWithErrorLevel
:findJavaFromJavaHome :findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
@@ -59,13 +87,14 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. 1>&2 1>&2 echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo. 1>&2 1>&2 echo.
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. 1>&2 1>&2 echo location of your Java installation.
"%COMSPEC%" /c exit 1 "%COMSPEC%" /c exit 1
goto exitWithErrorLevel
:execute :execute
@rem Setup the command line @rem Setup the command line
@@ -75,8 +104,9 @@ echo location of your Java installation. 1>&2
@rem Execute gradlew @rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded @rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command @rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
:exitWithErrorLevel :exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts @rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL% "%COMSPEC%" /c exit %ERRORLEVEL%

2
mise.toml Normal file
View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,7 @@ dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories { repositories {
mavenCentral() mavenCentral()
maven { url 'https://jitpack.io' } maven { url = 'https://jitpack.io' }
//jAirspy is published as a GitHub release, with the native libraries for all platforms in the jar //jAirspy is published as a GitHub release, with the native libraries for all platforms in the jar
ivy { ivy {
@@ -82,5 +82,23 @@ dependencyResolutionManagement {
metadataSources { artifact() } metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'jbladerf' } content { includeModule 'io.github.dsheirer', 'jbladerf' }
} }
//JMBE API is published as a GitHub release. It holds only the codec interfaces; users create the JMBE codec
//library itself with the JMBE creator, which sdrtrunk downloads from the release matching the API major version
ivy {
url = 'https://github.com/DSheirer/jmbe/releases/download'
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'jmbe-api' }
}
//radio-reference-api is published as a GitHub release. Its dependencies (jackson-dataformat-xml, slf4j-api)
//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(); return Collections.emptyList();
} }
/**
* Alias for a talkgroup that is identified by its stored values instead of an identifier instance, for example a
* talkgroup from the call database.
* @param protocol of the talkgroup
* @param value of the talkgroup
* @param fullyQualifiedAddress (wacn.system.id) of a fully qualified talkgroup, or null
* @return alias or null
*/
public Alias getTalkgroupAlias(Protocol protocol, int value, String fullyQualifiedAddress)
{
TalkgroupAliasList talkgroupAliasList = protocol != null ? mTalkgroupProtocolMap.get(protocol) : null;
return talkgroupAliasList != null ? talkgroupAliasList.getAlias(value, fullyQualifiedAddress) : null;
}
/**
* Alias for a radio that is identified by its stored values instead of an identifier instance, for example a
* radio from the call database.
* @param protocol of the radio
* @param value of the radio
* @param fullyQualifiedAddress (wacn.system.id) of a fully qualified radio, or null
* @return alias or null
*/
public Alias getRadioAlias(Protocol protocol, int value, String fullyQualifiedAddress)
{
RadioAliasList radioAliasList = protocol != null ? mRadioProtocolMap.get(protocol) : null;
return radioAliasList != null ? radioAliasList.getAlias(value, fullyQualifiedAddress) : null;
}
private static List<Alias> toList(Alias alias) private static List<Alias> toList(Alias alias)
{ {
if(alias != null) if(alias != null)
@@ -670,11 +698,26 @@ public class AliasList
//Attempt to do a fully qualified identifier match only //Attempt to do a fully qualified identifier match only
if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti) if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti)
{ {
return 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 //Attempt to match the talkgroup value
int value = identifier.getValue();
Alias mapValue = mTalkgroupAliasMap.get(value); Alias mapValue = mTalkgroupAliasMap.get(value);
if (mapValue != null) if (mapValue != null)
@@ -790,11 +833,26 @@ public class AliasList
//Match fully qualified identifier only. //Match fully qualified identifier only.
if(identifier instanceof FullyQualifiedRadioIdentifier fqri) 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 //Attempt to match against the radio identifier
int value = identifier.getValue();
Alias mapValue = mRadioAliasMap.get(value); Alias mapValue = mRadioAliasMap.get(value);
if(mapValue != null) if(mapValue != null)

View File

@@ -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<Alias> mAliases = FXCollections.observableArrayList(Alias.extractor());
private ObservableList<String> mAliasListNames = FXCollections.observableArrayList(); private ObservableList<String> mAliasListNames = FXCollections.observableArrayList();
private Map<String,AliasList> mAliasListMap = new HashMap<>(); private Map<String,AliasList> mAliasListMap = new HashMap<>();
private ObservableList<AliasListConfiguration> mAliasListConfigurations =
FXCollections.observableArrayList(AliasListConfiguration.extractor());
public AliasModel() public AliasModel()
{ {
@@ -63,6 +65,99 @@ public class AliasModel
return mAliasListNames; return mAliasListNames;
} }
/**
* Observable list of persisted alias list configurations. Only alias lists with settings, like Radio Reference
* system tracking, have a configuration.
*/
public ObservableList<AliasListConfiguration> aliasListConfigurations()
{
return mAliasListConfigurations;
}
/**
* Bulk loading of alias list configurations from a playlist. Ignores configurations without a name and
* duplicates of an earlier configuration's name.
*/
public void addAliasListConfigurations(List<AliasListConfiguration> configurations)
{
if(configurations != null)
{
for(AliasListConfiguration configuration: configurations)
{
String name = configuration.getName();
if(name != null && !name.isEmpty() && getAliasListConfiguration(name) == null)
{
mAliasListConfigurations.add(configuration);
addAliasList(name);
}
}
}
}
/**
* Configuration for the named alias list.
* @param aliasListName to find
* @return configuration or null if the alias list doesn't have one
*/
public AliasListConfiguration getAliasListConfiguration(String aliasListName)
{
if(aliasListName != null)
{
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(aliasListName.equals(configuration.getName()))
{
return configuration;
}
}
}
return null;
}
/**
* Configuration for the named alias list, created when the alias list doesn't have one.
* @param aliasListName for the configuration, not null or the (No Alias List) name
* @return configuration
*/
public AliasListConfiguration getOrCreateAliasListConfiguration(String aliasListName)
{
if(aliasListName == null || aliasListName.isEmpty() || aliasListName.equals(NO_ALIAS_LIST))
{
throw new IllegalArgumentException("Invalid alias list name [" + aliasListName + "]");
}
AliasListConfiguration configuration = getAliasListConfiguration(aliasListName);
if(configuration == null)
{
configuration = new AliasListConfiguration(aliasListName);
mAliasListConfigurations.add(configuration);
addAliasList(aliasListName);
}
return configuration;
}
/**
* Name of the first alias list that tracks the Radio Reference system.
* @param systemId of the Radio Reference system
* @return alias list name or null
*/
public String getAliasListNameTracking(int systemId)
{
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(configuration.isTracking(systemId))
{
return configuration.getName();
}
}
return null;
}
/** /**
* Clears and reloads the list of alias list names from the current set of aliases. * Clears and reloads the list of alias list names from the current set of aliases.
*/ */
@@ -79,6 +174,15 @@ public class AliasModel
mAliasListNames.add(aliasListName); mAliasListNames.add(aliasListName);
} }
} }
//Alias lists with a configuration exist even before they have any aliases
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(!mAliasListNames.contains(configuration.getName()))
{
mAliasListNames.add(configuration.getName());
}
}
} }
/** /**
@@ -93,7 +197,22 @@ public class AliasModel
return; 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)); mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
mAliasListMap.remove(aliasListName); mAliasListMap.remove(aliasListName);
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
} }
/** /**
@@ -146,6 +266,7 @@ public class AliasModel
removeAlias(alias); removeAlias(alias);
} }
mAliasListConfigurations.clear();
mAliasListNames.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; package io.github.dsheirer.alias.action;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.alias.Alias; import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.message.IMessage; import io.github.dsheirer.message.IMessage;
import io.github.dsheirer.util.ThreadPool; import io.github.dsheirer.util.ThreadPool;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@@ -62,23 +64,28 @@ public abstract class RecurringAction extends AliasAction
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate( mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS); new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS);
StringBuilder sb = new StringBuilder(); String text = "Alias [" + alias.getName() + "] is active in message [" + message + "]";
sb.append("<html><div width='250'>Alias [");
sb.append(alias.getName());
sb.append("] is active in message [");
sb.append(message.toString());
sb.append("]</div></html>");
final String text = sb.toString();
EventQueue.invokeLater(() -> {
JOptionPane.showMessageDialog(null, text,
"Alias Alert", JOptionPane.INFORMATION_MESSAGE);
Runnable dismissed = () -> {
dismiss(false); dismiss(false);
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS); 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; break;
default: default:
} }

View File

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

View File

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

View File

@@ -25,6 +25,7 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyCallConfiguration; import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyCallConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration; 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.openmhz.OpenMHzConfiguration;
import io.github.dsheirer.audio.broadcast.icecast.IcecastConfiguration; import io.github.dsheirer.audio.broadcast.icecast.IcecastConfiguration;
import io.github.dsheirer.audio.broadcast.shoutcast.v1.ShoutcastV1Configuration; import io.github.dsheirer.audio.broadcast.shoutcast.v1.ShoutcastV1Configuration;
@@ -49,6 +50,7 @@ import java.net.SocketAddress;
@JsonSubTypes({ @JsonSubTypes({
@JsonSubTypes.Type(value = BroadcastifyCallConfiguration.class, name="broadcastifyCallConfiguration"), @JsonSubTypes.Type(value = BroadcastifyCallConfiguration.class, name="broadcastifyCallConfiguration"),
@JsonSubTypes.Type(value = RdioScannerConfiguration.class, name="RdioScannerConfiguration"), @JsonSubTypes.Type(value = RdioScannerConfiguration.class, name="RdioScannerConfiguration"),
@JsonSubTypes.Type(value = ThinlineRadioConfiguration.class, name="ThinlineRadioConfiguration"),
@JsonSubTypes.Type(value = OpenMHzConfiguration.class, name="OpenMHzConfiguration"), @JsonSubTypes.Type(value = OpenMHzConfiguration.class, name="OpenMHzConfiguration"),
@JsonSubTypes.Type(value = IcecastConfiguration.class, name="icecastConfiguration"), @JsonSubTypes.Type(value = IcecastConfiguration.class, name="icecastConfiguration"),
@JsonSubTypes.Type(value = ShoutcastV1Configuration.class, name="shoutcastV1Configuration"), @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.broadcastify.BroadcastifyFeedConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerBroadcaster; import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerBroadcaster;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration; 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.rdioscanner.RdioScannerFeedConfiguration;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzBroadcaster; import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzBroadcaster;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzConfiguration; import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzConfiguration;
@@ -68,6 +69,7 @@ public class BroadcastFactory
return new BroadcastifyCallBroadcaster((BroadcastifyCallConfiguration)configuration, return new BroadcastifyCallBroadcaster((BroadcastifyCallConfiguration)configuration,
inputAudioFormat, mp3Setting, aliasModel); inputAudioFormat, mp3Setting, aliasModel);
case RDIOSCANNER_CALL: case RDIOSCANNER_CALL:
case THINLINE_RADIO:
return new RdioScannerBroadcaster((RdioScannerConfiguration)configuration, return new RdioScannerBroadcaster((RdioScannerConfiguration)configuration,
inputAudioFormat, mp3Setting, aliasModel); inputAudioFormat, mp3Setting, aliasModel);
case OPENMHZ: case OPENMHZ:
@@ -113,6 +115,8 @@ public class BroadcastFactory
return new BroadcastifyCallConfiguration(format); return new BroadcastifyCallConfiguration(format);
case RDIOSCANNER_CALL: case RDIOSCANNER_CALL:
return new RdioScannerConfiguration(format); return new RdioScannerConfiguration(format);
case THINLINE_RADIO:
return new ThinlineRadioConfiguration(format);
case BROADCASTIFY: case BROADCASTIFY:
return new BroadcastifyFeedConfiguration(format); return new BroadcastifyFeedConfiguration(format);
case OPENMHZ: case OPENMHZ:

View File

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

View File

@@ -32,6 +32,7 @@ public enum BroadcastServerType
ICECAST_HTTP("Icecast 2 (v2.4+)", "images/icecast.png"), ICECAST_HTTP("Icecast 2 (v2.4+)", "images/icecast.png"),
RDIOSCANNER_CALL("Rdio Scanner", "images/rdioscanner.png"), RDIOSCANNER_CALL("Rdio Scanner", "images/rdioscanner.png"),
THINLINE_RADIO("Thinline Radio", "images/rdioscanner.png"),
OPENMHZ("OpenMHz", "images/openmhz.png"), OPENMHZ("OpenMHz", "images/openmhz.png"),
ICECAST_TCP("Icecast (v2.3)", "images/icecast.png"), ICECAST_TCP("Icecast (v2.3)", "images/icecast.png"),
SHOUTCAST_V1("Shoutcast v1.x", "images/shoutcast.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; return mAudioBroadcaster != null;
} }
/**
* Current status for display: the broadcaster's state when there is a broadcaster, otherwise the reason that
* there isn't one.
*/
public BroadcastState getStatus()
{
AbstractAudioBroadcaster broadcaster = mAudioBroadcaster;
if(broadcaster != null)
{
return broadcaster.getBroadcastState();
}
else if(!mBroadcastConfiguration.isEnabled())
{
return BroadcastState.DISABLED;
}
else if(!mBroadcastConfiguration.isValid())
{
return BroadcastState.INVALID_SETTINGS;
}
return BroadcastState.ERROR;
}
/** /**
* Creates an observable property extractor for use with observable lists to detect changes internal to this object. * Creates an observable property extractor for use with observable lists to detect changes internal to this object.
*/ */

View File

@@ -113,7 +113,8 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
} }
else 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); setBroadcastState(BroadcastState.ERROR);
} }
@@ -249,7 +250,8 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
} }
catch(IOException e) 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) 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 //We get socket reset exceptions occasionally when the remote server doesn't
//fully read our request and immediately responds. //fully read our request and immediately responds.
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR); 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.statusCode() + "] response [" +
fileResponse.body() + "]"); fileResponse.body() + "]");
} }
else else
{ {
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR); 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.statusCode() + "] response [" +
fileResponse.body() + "]"); fileResponse.body() + "]");
} }
@@ -321,7 +323,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else else
{ {
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR); 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.statusCode() + "] response [" +
fileResponse.body() + "]"); fileResponse.body() + "]");
} }
@@ -334,7 +336,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else else
{ {
//Register an error for the file not found exception //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() + "]"); audioRecording.getPath().toString() + "]");
incrementErrorAudioCount(); incrementErrorAudioCount();
broadcast(new BroadcastEvent(RdioScannerBroadcaster.this, broadcast(new BroadcastEvent(RdioScannerBroadcaster.this,

View File

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

View File

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

View File

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

@@ -1,483 +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.convert.thumbdv;
import com.fazecast.jSerialComm.SerialPort;
import io.github.dsheirer.audio.convert.thumbdv.message.AmbeMessage;
import io.github.dsheirer.audio.convert.thumbdv.message.AmbeMessageFactory;
import io.github.dsheirer.audio.convert.thumbdv.message.VocoderRate;
import io.github.dsheirer.audio.convert.thumbdv.message.request.AmbeRequest;
import io.github.dsheirer.audio.convert.thumbdv.message.request.DecodeSpeechRequest;
import io.github.dsheirer.audio.convert.thumbdv.message.request.EncodeSpeechRequest;
import io.github.dsheirer.audio.convert.thumbdv.message.request.ResetRequest;
import io.github.dsheirer.audio.convert.thumbdv.message.request.SetVocoderParametersRequest;
import io.github.dsheirer.audio.convert.thumbdv.message.request.SetVocoderRequest;
import io.github.dsheirer.audio.convert.thumbdv.message.response.DecodeSpeechResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.ReadyResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetVocoderParameterResponse;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.util.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Northwest Digital Radio (NWDR) ThumbDv dongle.
*
* Note: linux users must allow access to the serial port:
*
* sudo usermod -a -G uucp username
* sudo usermod -a -G dialout username
* sudo usermod -a -G lock username
* sudo usermod -a -G tty username
*/
public class ThumbDv implements AutoCloseable
{
private final static Logger mLog = LoggerFactory.getLogger(ThumbDv.class);
private static final String PORT_DESCRIPTION = "USB-to-Serial Port (ftdi_sio)";
private static final String PORT_DESCRIPTION_FRAGMENT = "USB Serial Port";
private static final int BAUD_RATE = 460800;
private static final byte PACKET_START = (byte) 0x61;
public enum AudioProtocol
{
DMR,
DSTAR,
NXDN,
P25_PHASE2,
}
private SerialPort mSerialPort;
private ScheduledFuture mSerialPortReaderHandle;
private ScheduledFuture mAudioDecodeProcessorHandle;
private LinkedTransferQueue<DecodeSpeechRequest> mDecodeSpeechRequests = new LinkedTransferQueue<>();
private AudioProtocol mAudioProtocol;
private Listener<float[]> mAudioBufferListener;
private boolean mStarted;
public ThumbDv(AudioProtocol audioProtocol, Listener<float[]> listener)
{
mAudioProtocol = audioProtocol;
mAudioBufferListener = listener;
}
/**
* Enqueues the audio code frame for decoding. Decoded PCM speech packet will be sent to the registered
* audio packet listener.
*
* @param codecFrame
*/
public void decode(byte[] codecFrame)
{
if(!mStarted || mSerialPort == null)
{
throw new IllegalStateException("Must invoke start() method and thumbdv serial device must be available");
}
mDecodeSpeechRequests.offer(new DecodeSpeechRequest(codecFrame));
}
public void close() throws IOException
{
if(mSerialPortReaderHandle != null)
{
mSerialPortReaderHandle.cancel(true);
mSerialPortReaderHandle = null;
}
if(mSerialPort != null)
{
mSerialPort.closePort();
}
}
public void start() throws IOException
{
if(mSerialPort == null)
{
SerialPort[] ports = SerialPort.getCommPorts();
for(SerialPort port : ports)
{
mLog.debug("Serial Port Name:" + port.getDescriptivePortName());
if(port.getDescriptivePortName().contentEquals(PORT_DESCRIPTION) ||
port.getDescriptivePortName().contains(PORT_DESCRIPTION_FRAGMENT))
{
mSerialPort = port;
mSerialPort.setBaudRate(BAUD_RATE);
mSerialPort.openPort(0, 5000, 10000);
if(mSerialPort.isOpen())
{
mLog.info("Resetting ThumbDv Device");
send(new ResetRequest());
mLog.info("Creating Serial Port Reader");
final Runnable r = new SerialPortReader(mSerialPort.getInputStream());
mLog.info("Starting Serial Port Reader");
mSerialPortReaderHandle = ThreadPool.SCHEDULED.scheduleAtFixedRate(r, 0,
5, TimeUnit.MILLISECONDS);
mStarted = true;
mLog.info("Startup complete - awaiting reset response");
}
else
{
mLog.warn("Could not open serial port: " + mSerialPort.getSystemPortName());
throw new IOException("Could not open serial port:" + mSerialPort.getSystemPortName());
}
break;
}
}
}
if(mSerialPort == null)
{
throw new IOException("ThumbDV serial port not found");
}
return;
}
public void send(byte[] message) throws IOException
{
if(mSerialPort == null)
{
throw new IOException("ThumbDv must be started before use");
}
int bytesWritten = mSerialPort.writeBytes(message, message.length);
if(bytesWritten < 0)
{
throw new IOException("Unable to write message:" + Arrays.toString(message));
}
else if(bytesWritten != message.length)
{
throw new IOException("Unable to write message:" + Arrays.toString(message) + " Bytes Written:" + bytesWritten);
}
}
/**
* Sends the AMBE request message
*
* @param request message
* @throws IOException if there is an error
*/
public void send(AmbeRequest request) throws IOException
{
send(request.getData());
}
private void receive(byte[] bytes)
{
AmbeMessage message = AmbeMessageFactory.getMessage(bytes);
if(message instanceof DecodeSpeechResponse && mAudioBufferListener != null)
{
float[] samples = ((DecodeSpeechResponse)message).getSamples();
mAudioBufferListener.receive(samples);
}
else if(message instanceof ReadyResponse && mAudioDecodeProcessorHandle == null)
{
if(mAudioDecodeProcessorHandle == null)
{
try
{
switch(mAudioProtocol)
{
case DSTAR:
send(new SetVocoderRequest(VocoderRate.RATE_33));
send(new SetVocoderParametersRequest(0x0130, 0x0763, 0x4000, 0x0000, 0x0000, 0x0048));
break;
case DMR:
case NXDN:
case P25_PHASE2:
send(new SetVocoderRequest(VocoderRate.RATE_33));
send(new SetVocoderParametersRequest(0x0431, 0x0754, 0x2400, 0x0000, 0x0000, 0x6F48));
break;
default:
throw new IllegalStateException("Unrecognized audio protocol:" + mAudioProtocol);
}
}
catch(IOException ioe)
{
mLog.error("Error setting audio protocol vocoder parameters");
}
mLog.info("ThumbDv Reset Complete");
}
else
{
mLog.info("ThumbDv Reset Detected");
}
}
else if(message instanceof SetVocoderParameterResponse)
{
if(((SetVocoderParameterResponse)message).isSuccessful())
{
mLog.info("Audio vocoder parameters configured for " + mAudioProtocol);
//Start the audio frame decode processor
mAudioDecodeProcessorHandle = ThreadPool.SCHEDULED.scheduleAtFixedRate(new AudioDecodeProcessor(), 0,
10, TimeUnit.MILLISECONDS);
}
}
else if(message != null)
{
mLog.debug("RECEIVED:" + message.toString());
}
}
/**
* Logs the current settings of the serial port. Note: you must invoke start() before this method so that
* the serial port can be discovered and opened.
*/
public void logSerialPort()
{
if(mSerialPort != null)
{
StringBuilder sb = new StringBuilder();
sb.append("\nPort:\t\t\t").append(mSerialPort.getSystemPortName()).append("\n");
sb.append("Name:\t\t\t").append(mSerialPort.getDescriptivePortName()).append("\n");
sb.append("Baud Rate:\t\t").append(mSerialPort.getBaudRate()).append("\n");
sb.append("Data Bits:\t\t").append(mSerialPort.getNumDataBits()).append("\n");
sb.append("Parity Bits:\t").append(mSerialPort.getParity()).append("\n");
sb.append("Stop Bits:\t\t").append(mSerialPort.getNumStopBits()).append("\n");
sb.append("Flow Control:\t").append(mSerialPort.getFlowControlSettings()).append("\n");
sb.append("Is Open:\t\t").append(mSerialPort.isOpen()).append("\n");
mLog.info(sb.toString());
}
else
{
mLog.info("No serial port found");
}
}
/**
* Processes the audio frame decode queue
*/
public class AudioDecodeProcessor implements Runnable
{
@Override
public void run()
{
try
{
DecodeSpeechRequest request = mDecodeSpeechRequests.poll();
if(request != null)
{
try
{
send(request);
}
catch(IOException ioe)
{
mLog.error("Error decoding audio frame", ioe);
}
// try
// {
// //Force a 20ms sleep after submitting an audio frame to avoid overflowing the thumbdv
// Thread.sleep(20);
// }
// catch(InterruptedException ie)
// {
// //Do nothing
// }
}
}
catch(Throwable t)
{
mLog.error("Error", t);
}
}
}
public class SerialPortReader implements Runnable
{
private InputStream mInputStream;
public SerialPortReader(InputStream inputStream)
{
mInputStream = inputStream;
}
@Override
public void run()
{
try
{
if(mInputStream != null)
{
try
{
while(mInputStream.available() > 0)
{
byte[] buffer = new byte[400];
int bytesRead = mInputStream.readNBytes(buffer, 0, 1);
if(bytesRead == 1 && buffer[0] == PACKET_START)
{
while(mInputStream.available() < 2)
{
try
{
Thread.sleep(1);
}
catch(InterruptedException ie)
{
}
}
bytesRead = mInputStream.readNBytes(buffer, 1, 2);
if(bytesRead == 2)
{
int length = (0xFF & buffer[1]) << 8;
length += (0xFF & buffer[2]);
if(0 < length && length < 400)
{
length++; //Add a byte for the type byte
while(mInputStream.available() < length)
{
try
{
Thread.sleep(1);
}
catch(InterruptedException ie)
{
}
}
bytesRead = mInputStream.readNBytes(buffer, 3, length);
if(bytesRead == length)
{
receive(Arrays.copyOf(buffer, length + 3));
}
else
{
mLog.debug("Expected [" + length + "] but received [" + bytesRead + "] bytes - " + Arrays.toString(buffer));
}
}
else
{
mLog.error("Received packet with unexpected length: " + length);
//Don't process the buffer ... let the reader read and inspect 1 byte at a time
//to regain sync on the packet start byte
}
}
else
{
mLog.debug("Expected [2] but received [" + bytesRead + "] -- this shouldn't happen");
}
}
else
{
mLog.debug("Unrecognized byte: " + Arrays.toString(buffer));
}
}
}
catch(IOException ioe)
{
mLog.error("Error while reading ThumbDv serial port", ioe);
}
}
}
catch(Throwable t)
{
mLog.error("Error", t);
}
}
}
public static void main(String[] args)
{
mLog.debug("Starting");
String silence = "BEDDEA821EFD660C08";
String[] frames = {"0E46122323067C60F8", "0E469433C1067CF1BC", "0E46122B23067C60F8", "0E67162BE08874E2B4",
"0E46163BE1067CF1BC", "0E46122B23067C60F8", "0A06163BE00A5C303E", "0E46122B23067C60F8", "0E46163BE1847CE1FC",
"0E46122B23067C60F8"};
List<byte[]> frameData = new ArrayList<>();
for(String frame : frames)
{
byte[] bytes = new byte[frame.length() / 2];
for(int x = 0; x < frame.length(); x += 2)
{
String hex = frame.substring(x, x + 2);
bytes[x / 2] = (byte) (0xFF & Integer.parseInt(hex, 16));
}
frameData.add(bytes);
}
mLog.debug("Starting thumb dv thread(s)");
final Listener<float[]> listener = packet -> {
mLog.info("Got an audio packet!");
};
try(ThumbDv thumbDv = new ThumbDv(AudioProtocol.P25_PHASE2, listener))
{
thumbDv.start();
Thread.sleep(6000);
for(int x = 0; x < 20; x++)
{
thumbDv.send(new EncodeSpeechRequest(new short[160]));
Thread.sleep(20);
}
// for(byte[] frame : frameData)
// {
// thumbDv.decode(frame);
// }
while(true);
}
catch(IOException ioe)
{
mLog.error("Error", ioe);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

View File

@@ -1,44 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message;
/**
* AMBE-3000R Message
*/
public abstract class AmbeMessage
{
/**
* Converts the byte array to a hexadecimal string array
*/
public static String toHex(byte[] data)
{
StringBuilder sb = new StringBuilder();
for(byte b: data)
{
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}

View File

@@ -1,95 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message;
import io.github.dsheirer.audio.convert.thumbdv.message.response.DecodeSpeechResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.EncodeSpeechResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.GetConfigResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.InitializeCodecResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.ProductIdResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.ReadyResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetChannelFormatResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetChannelResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetPacketModeResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetSpeechFormatResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetVocoderParameterResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.SetVocoderResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.UnknownResponse;
import io.github.dsheirer.audio.convert.thumbdv.message.response.VersionResponse;
public class AmbeMessageFactory
{
private static final byte CONTROL_PACKET = (byte)0x00;
private static final byte CHANNEL_PACKET = (byte)0x01;
private static final byte SPEECH_PACKET = (byte)0x02;
private static final int INDEX_PACKET_TYPE = 3;
private static final int INDEX_CONTROL_PACKET_TYPE = 4;
public static AmbeMessage getMessage(byte[] data)
{
if(data != null && data.length >= 5)
{
if(data[INDEX_PACKET_TYPE] == CONTROL_PACKET)
{
PacketField packetField = PacketField.fromValue(data[INDEX_CONTROL_PACKET_TYPE]);
switch(packetField)
{
case PKT_CHANNEL_0:
return new SetChannelResponse(data);
case PKT_CHANNEL_FORMAT:
return new SetChannelFormatResponse(data);
case PKT_CODEC_STOP:
return new SetPacketModeResponse(data);
case PKT_GET_CONFIG:
return new GetConfigResponse(data);
case PKT_INIT:
return new InitializeCodecResponse(data);
case PKT_PRODUCT_ID:
return new ProductIdResponse(data);
case PKT_RATE_PARAMETER:
return new SetVocoderParameterResponse(data);
case PKT_RATE_TABLE:
return new SetVocoderResponse(data);
case PKT_READY:
return new ReadyResponse(data);
case PKT_SPEECH_FORMAT:
return new SetSpeechFormatResponse(data);
case PKT_VERSION_STRING:
return new VersionResponse(data);
}
}
else if(data[INDEX_PACKET_TYPE] == CHANNEL_PACKET)
{
return new EncodeSpeechResponse(data);
}
else if(data[INDEX_PACKET_TYPE] == SPEECH_PACKET)
{
return new DecodeSpeechResponse(data);
}
}
return new UnknownResponse(data);
}
}

View File

@@ -1,47 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message;
/**
* AMBE-3000 Initialization Options
*/
public enum InitializeOption
{
ENCODER((byte)0x01),
DECODER((byte)0x02),
ENCODER_AND_DECODER((byte)0x03),
ECHO_CANCELLER((byte)0x04),
ENCODER_DECODER_ECHO_CANCELLER((byte)0x07);
private byte mCode;
InitializeOption(byte code)
{
mCode = code;
}
public byte getCode()
{
return mCode;
}
}

View File

@@ -1,160 +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.convert.thumbdv.message;
/**
* AMBE-3000R Control Packet Field enumeration
*/
public enum PacketField
{
PKT_ENCODER_CMODE((byte)0x05),
PKT_DECODER_CMODE((byte)0x06),
PKT_RATE_TABLE((byte)0x09),
PKT_RATE_PARAMETER((byte)0x0A),
PKT_INIT((byte)0x0B),
PKT_LOW_POWER((byte)0x10),
PKT_CHANNEL_FORMAT((byte)0x15),
PKT_SPEECH_FORMAT((byte)0x16),
PKT_CODEC_START((byte)0x2A),
PKT_CODEC_STOP((byte)0x2B),
PKT_PRODUCT_ID((byte)0x30),
PKT_VERSION_STRING((byte)0x31),
PKT_COMPAND((byte)0x32),
PKT_RESET((byte)0x33),
PKT_RESET_TO_SOFTWARE_CONFIG((byte)0x34),
PKT_HALT((byte)0x35),
PKT_GET_CONFIG((byte)0x36),
PKT_READ_CONFIG((byte)0x37),
PKT_CODEC_CFG((byte)0x38),
PKT_READY((byte)0x39),
PKT_PARITY_MODE((byte)0x3F),
PKT_CHANNEL_0((byte)0x40),
PKT_WRITE_I2C((byte)0x44),
PKT_CLEAR_CODEC_RESET((byte)0x46),
PKT_SET_CODEC_RESET((byte)0x47),
PKT_DISCARD_CODEC_SAMPLES((byte)0x48),
PKT_DELAY_NUMBER_MICRO_SECONDS((byte)0x49),
PKT_DELAY_NUMBER_NANO_SECONDS((byte)0x4A),
PKT_GAIN((byte)0x4B),
PKT_RTS_THRESHOLD((byte)0x4E),
//Speech packet values
SPEECH_DATA((byte)0x00),
CHANNEL_DATA_HARD_SYMBOL((byte)0x01),
CMODE((byte)0x02),
SAMPLE_COUNT((byte)0x03),
TONE((byte)0x08),
CHANNEL_DATA_SOFT_SYMBOL((byte)0x17),
VOCODER((byte)0x40),
//Packet Types
PACKET_TYPE_CONTROL((byte)0x00),
PACKET_TYPE_ENCODE_SPEECH((byte)0x01),
PACKET_TYPE_DECODE_SPEECH((byte)0x02),
UNKNOWN((byte)0x00);
private byte mCode;
PacketField(byte code)
{
mCode = code;
}
/**
* Packet type byte code value
*/
public byte getCode()
{
return mCode;
}
/**
* Lookup a packet type from the code byte value
*/
public static PacketField fromValue(byte value)
{
switch(value)
{
case (byte)0x05:
return PKT_ENCODER_CMODE;
case (byte)0x06:
return PKT_DECODER_CMODE;
case (byte)0x09:
return PKT_RATE_TABLE;
case (byte)0x0A:
return PKT_RATE_PARAMETER;
case (byte)0x0B:
return PKT_INIT;
case (byte)0x10:
return PKT_LOW_POWER;
case (byte)0x15:
return PKT_CHANNEL_FORMAT;
case (byte)0x16:
return PKT_SPEECH_FORMAT;
case (byte)0x2A:
return PKT_CODEC_START;
case (byte)0x2B:
return PKT_CODEC_STOP;
case (byte)0x30:
return PKT_PRODUCT_ID;
case (byte)0x31:
return PKT_VERSION_STRING;
case (byte)0x32:
return PKT_COMPAND;
case (byte)0x33:
return PKT_RESET;
case (byte)0x34:
return PKT_RESET_TO_SOFTWARE_CONFIG;
case (byte)0x35:
return PKT_HALT;
case (byte)0x36:
return PKT_GET_CONFIG;
case (byte)0x37:
return PKT_READ_CONFIG;
case (byte)0x38:
return PKT_CODEC_CFG;
case (byte)0x39:
return PKT_READY;
case (byte)0x3F:
return PKT_PARITY_MODE;
case (byte)0x40:
return PKT_CHANNEL_0;
case (byte)0x44:
return PKT_WRITE_I2C;
case (byte)0x46:
return PKT_CLEAR_CODEC_RESET;
case (byte)0x47:
return PKT_SET_CODEC_RESET;
case (byte)0x48:
return PKT_DISCARD_CODEC_SAMPLES;
case (byte)0x49:
return PKT_DELAY_NUMBER_MICRO_SECONDS;
case (byte)0x4A:
return PKT_DELAY_NUMBER_NANO_SECONDS;
case (byte)0x4B:
return PKT_GAIN;
case (byte)0x4E:
return PKT_RTS_THRESHOLD;
default:
return UNKNOWN;
}
}
}

View File

@@ -1,129 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message;
public enum VocoderRate
{
//AMBE-1000 Standard Rates
RATE_0((byte)0x00, 2400,0),
RATE_1((byte)0x01, 3600,0),
RATE_2((byte)0x02, 3600,1200),
RATE_3((byte)0x03, 4800,0),
RATE_4((byte)0x04, 9600,0),
RATE_5((byte)0x05, 2350,50),
RATE_6((byte)0x06, 4850,4750),
RATE_7((byte)0x07, 4550,250),
RATE_8((byte)0x08, 3100,1700),
RATE_9((byte)0x09, 4400,2800),
RATE_10((byte)0x0A, 4150,2250),
RATE_11((byte)0x0B, 3350,250),
RATE_12((byte)0x0C, 7750,250),
RATE_13((byte)0x0D, 4650,3350),
RATE_14((byte)0x0E, 3750,250),
RATE_15((byte)0x0F, 4000,0),
//AMBE-2000 Standard Rates
RATE_16((byte)0x10, 3600,0),
RATE_17((byte)0x11, 4000,0),
RATE_18((byte)0x12, 4800,0),
RATE_19((byte)0x13, 6400,0),
RATE_20((byte)0x14, 8000,0),
RATE_21((byte)0x15, 9600,0),
RATE_22((byte)0x16, 2400,1600),
RATE_23((byte)0x17, 3600,1200),
RATE_24((byte)0x18, 4000,800),
RATE_25((byte)0x19, 2400,2400),
RATE_26((byte)0x1A, 4000,2400),
RATE_27((byte)0x1B, 4400,2800), //Is this compatible with APCO25 Phase 1?
RATE_28((byte)0x1C, 4000,4000),
RATE_29((byte)0x1D, 2400,7200),
RATE_30((byte)0x1E, 3600,6000),
RATE_31((byte)0x1F, 2000,0),
RATE_32((byte)0x20, 3600,2800),
//AMBE-3000 Standard Rates (AMBE+2)
RATE_33((byte)0x21, 2450,1150), //APCO25 HR (Phase 2), DMR, NXDN, DSTAR
RATE_34((byte)0x22, 2450,0),
RATE_35((byte)0x23, 2250,1150),
RATE_36((byte)0x24, 2250,0),
RATE_37((byte)0x25, 2400,0),
RATE_38((byte)0x26, 3000,0),
RATE_39((byte)0x27, 3600,0),
RATE_40((byte)0x28, 4000,0),
RATE_41((byte)0x29, 4400,0),
RATE_42((byte)0x2A, 4800,0),
RATE_43((byte)0x2B, 6400,0),
RATE_44((byte)0x2C, 7200,0),
RATE_45((byte)0x2D, 8000,0),
RATE_46((byte)0x2E, 9600,0),
RATE_47((byte)0x2F, 2450,250),
RATE_48((byte)0x30, 3350,250),
RATE_49((byte)0x31, 3750,250),
RATE_50((byte)0x32, 4550,250),
RATE_51((byte)0x33, 2450,1950),
RATE_52((byte)0x34, 2450,2350),
RATE_53((byte)0x35, 2450,3550),
RATE_54((byte)0x36, 2450,4750),
RATE_55((byte)0x37, 2600,1400),
RATE_56((byte)0x38, 3600,1200),
RATE_57((byte)0x39, 4000,800),
RATE_58((byte)0x3A, 4000,2400),
RATE_59((byte)0x3B, 4400,2800), //Is this compatible with APCO25 Phase 1?
RATE_60((byte)0x3C, 4000,4000),
RATE_61((byte)0x3D, 3600,6000);
private byte mCode;
private int mSpeechRate;
private int mFecRate;
VocoderRate(byte code, int speechRate, int fecRate)
{
mCode = code;
mSpeechRate = speechRate;
mFecRate = fecRate;
}
/**
* Byte code value for the vocoder rate
*/
public byte getCode()
{
return mCode;
}
/**
* Speech rate in bits per second (bps)
*/
public int getSpeechRate()
{
return mSpeechRate;
}
/**
* Forward Error Correction rate in bits per second (bps)
*/
public int getFecRate()
{
return mFecRate;
}
}

View File

@@ -1,67 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.AmbeMessage;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* AMBE-3000R Request Packet
*/
public abstract class AmbeRequest extends AmbeMessage
{
private static final byte PACKET_START_BYTE = (byte)0x61;
protected static final int PACKET_TYPE_INDEX = 3;
protected static final int PAYLOAD_START_INDEX = 4;
public abstract PacketField getType();
public abstract byte[] getData();
/**
* Creates a byte array of the specified length plus 4 packet header bytes with packet start, length and control
* bytes filled in.
*
* @param length of the message (not including the 4 byte packet header)
* @return byte array with packet header pre-filled.
*/
protected byte[] createMessage(int length, PacketField type)
{
byte[] data = new byte[length + 4];
data[0] = PACKET_START_BYTE;
data[1] = (byte)((length >> 8 & 0xFF));
data[2] = (byte)(length & 0xFF);
if(type == PacketField.PACKET_TYPE_ENCODE_SPEECH || type == PacketField.PACKET_TYPE_DECODE_SPEECH)
{
data[PACKET_TYPE_INDEX] = type.getCode();
}
else
{
data[PACKET_TYPE_INDEX] = PacketField.PACKET_TYPE_CONTROL.getCode();
data[PAYLOAD_START_INDEX] = type.getCode();
}
return data;
}
}

View File

@@ -1,108 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import io.github.dsheirer.audio.convert.thumbdv.message.VocoderRate;
/**
* Decode speech request, used to request decode of an encoded audio frame.
*/
public class DecodeSpeechRequest extends AmbeRequest
{
private static final int CHANNEL_DATA_IDENTIFIER_INDEX = 4;
private static final byte SAMPLE_COUNT = (byte)(0xFF & 160); //8 kHz Audio sample count for 20ms frame
private byte[] mAudioFrame;
private VocoderRate mVocoderRate;
/**
* Constructs an audio frame decode request using the specified vocoder rate.
* @param audioFrame of encoded audio samples
* @param vocoderRate to use when decoding
*/
public DecodeSpeechRequest(byte[] audioFrame, VocoderRate vocoderRate)
{
mAudioFrame = audioFrame;
mVocoderRate = vocoderRate;
}
/**
* Constructs an audio frame decode request using the current vocoder rate.
* @param audioFrame of encoded audio samples
*/
public DecodeSpeechRequest(byte[] audioFrame)
{
this(audioFrame, null);
}
@Override
public PacketField getType()
{
return PacketField.PACKET_TYPE_ENCODE_SPEECH;
}
private boolean hasVocoderRate()
{
return mVocoderRate != null;
}
@Override
public byte[] getData()
{
if(hasVocoderRate())
{
int length = mAudioFrame.length + 9;
byte[] data = createMessage(length, getType());
int offset = CHANNEL_DATA_IDENTIFIER_INDEX;
data[offset++] = PacketField.VOCODER.getCode();
data[offset++] = mVocoderRate.getCode();
data[offset++] = PacketField.CHANNEL_DATA_HARD_SYMBOL.getCode();
data[offset++] = (byte)(0xFF & (mAudioFrame.length * 8));
System.arraycopy(mAudioFrame, 0, data, offset, mAudioFrame.length);
offset += mAudioFrame.length;
data[offset++] = PacketField.SAMPLE_COUNT.getCode();
data[offset++] = (byte)0xA0;
data[offset++] = (byte)0x02;
data[offset++] = (byte)0x00;
data[offset] = (byte)0x00;
return data;
}
else
{
int length = mAudioFrame.length + 2;
byte[] data = createMessage(length, getType());
int offset = CHANNEL_DATA_IDENTIFIER_INDEX;
data[offset++] = PacketField.CHANNEL_DATA_HARD_SYMBOL.getCode();
data[offset++] = (byte)(0xFF & (mAudioFrame.length * 8));
System.arraycopy(mAudioFrame, 0, data, offset, mAudioFrame.length);
return data;
}
}
}

View File

@@ -1,88 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
public class EncodeSpeechRequest extends AmbeRequest
{
private static final int CHANNEL_IDENTIFIER_INDEX = 4;
private static final int SPEECH_DATA_IDENTIFIER_INDEX = 5;
private static final int SAMPLE_COUNT_INDEX = 6;
private static final int SPEECH_DATA_START_INDEX = 7;
private short[] mSamples;
public EncodeSpeechRequest(short[] samples)
{
mSamples = samples;
}
public EncodeSpeechRequest(float[] samples)
{
mSamples = new short[samples.length];
for(int x = 0; x < samples.length; x++)
{
if(samples[x] > 1.0f)
{
mSamples[x] = Short.MAX_VALUE;
}
else if(samples[x] < -1.0f)
{
mSamples[x] = Short.MIN_VALUE;
}
else
{
mSamples[x] = (short)(samples[x] * Short.MAX_VALUE);
}
}
}
@Override
public PacketField getType()
{
return PacketField.PACKET_TYPE_DECODE_SPEECH;
}
@Override
public byte[] getData()
{
int length = (mSamples.length * 2) + 3;
byte[] data = createMessage(length, getType());
data[CHANNEL_IDENTIFIER_INDEX] = PacketField.PKT_CHANNEL_0.getCode();
data[SPEECH_DATA_IDENTIFIER_INDEX] = (byte)0x00;
data[SAMPLE_COUNT_INDEX] = (byte)(0xFF & mSamples.length);
int pointer = SPEECH_DATA_START_INDEX;
for(short sample: mSamples)
{
data[pointer++] = (byte)((sample >> 8 & 0xFF));
data[pointer++] = (byte)(sample & 0xFF);
}
return data;
}
}

View File

@@ -1,43 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Get configuration request packet
*/
public class GetConfigRequest extends AmbeRequest
{
@Override
public PacketField getType()
{
return PacketField.PKT_GET_CONFIG;
}
@Override
public byte[] getData()
{
return createMessage(1, getType());
}
}

View File

@@ -1,54 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.InitializeOption;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Initialize CODEC request packet
*/
public class InitializeCodecRequest extends AmbeRequest
{
private static final int INITIALIZE_OPTION_INDEX = 5;
private InitializeOption mInitializeOption;
public InitializeCodecRequest(InitializeOption option)
{
mInitializeOption = option;
}
@Override
public PacketField getType()
{
return PacketField.PKT_INIT;
}
@Override
public byte[] getData()
{
byte[] data = createMessage(2, getType());
data[INITIALIZE_OPTION_INDEX] = mInitializeOption.getCode();
return data;
}
}

View File

@@ -1,43 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Product ID request packet
*/
public class ProductIdRequest extends AmbeRequest
{
@Override
public PacketField getType()
{
return PacketField.PKT_PRODUCT_ID;
}
@Override
public byte[] getData()
{
return createMessage(1, getType());
}
}

View File

@@ -1,43 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Reset request packet
*/
public class ResetRequest extends AmbeRequest
{
@Override
public PacketField getType()
{
return PacketField.PKT_RESET;
}
@Override
public byte[] getData()
{
return createMessage(1, getType());
}
}

View File

@@ -1,48 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set channel format request packet
*/
public class SetChannelFormatRequest extends AmbeRequest
{
private static final int FORMAT_INDEX = 5;
private static final byte FORMAT = (byte)0x00;
@Override
public PacketField getType()
{
return PacketField.PKT_CHANNEL_FORMAT;
}
@Override
public byte[] getData()
{
byte[] data = createMessage(2, getType());
data[FORMAT_INDEX] = FORMAT;
return data;
}
}

View File

@@ -1,43 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set channel request packet
*/
public class SetChannelRequest extends AmbeRequest
{
@Override
public PacketField getType()
{
return PacketField.PKT_CHANNEL_0;
}
@Override
public byte[] getData()
{
return createMessage(1, getType());
}
}

View File

@@ -1,43 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Packet mode (versus CODEC mode) request packet
*/
public class SetPacketModeRequest extends AmbeRequest
{
@Override
public PacketField getType()
{
return PacketField.PKT_CODEC_STOP;
}
@Override
public byte[] getData()
{
return createMessage(1, getType());
}
}

View File

@@ -1,48 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set speech format request packet
*/
public class SetSpeechFormatRequest extends AmbeRequest
{
private static final int FORMAT_INDEX = 5;
private static final byte FORMAT = (byte)0x00;
@Override
public PacketField getType()
{
return PacketField.PKT_SPEECH_FORMAT;
}
@Override
public byte[] getData()
{
byte[] data = createMessage(2, getType());
data[FORMAT_INDEX] = FORMAT;
return data;
}
}

View File

@@ -1,74 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set Vocoder parameters request packet
*/
public class SetVocoderParametersRequest extends AmbeRequest
{
private int mWord0;
private int mWord1;
private int mWord2;
private int mWord3;
private int mWord4;
private int mWord5;
public SetVocoderParametersRequest(int word0, int word1, int word2, int word3, int word4, int word5)
{
mWord0 = word0;
mWord1 = word1;
mWord2 = word2;
mWord3 = word3;
mWord4 = word4;
mWord5 = word5;
}
@Override
public PacketField getType()
{
return PacketField.PKT_RATE_PARAMETER;
}
@Override
public byte[] getData()
{
byte[] data = createMessage(14, getType());
data[PAYLOAD_START_INDEX + 1] = (byte)(mWord0 >> 8 & 0xFF);
data[PAYLOAD_START_INDEX + 2] = (byte)(mWord0 & 0xFF);
data[PAYLOAD_START_INDEX + 3] = (byte)(mWord1 >> 8 & 0xFF);
data[PAYLOAD_START_INDEX + 4] = (byte)(mWord1 & 0xFF);
data[PAYLOAD_START_INDEX + 5] = (byte)(mWord2 >> 8 & 0xFF);
data[PAYLOAD_START_INDEX + 6] = (byte)(mWord2 & 0xFF);
data[PAYLOAD_START_INDEX + 7] = (byte)(mWord3 >> 8 & 0xFF);
data[PAYLOAD_START_INDEX + 8] = (byte)(mWord3 & 0xFF);
data[PAYLOAD_START_INDEX + 9] = (byte)(mWord4 >> 8 & 0xFF);
data[PAYLOAD_START_INDEX + 10] = (byte)(mWord4 & 0xFF);
data[PAYLOAD_START_INDEX + 11] = (byte)(mWord5 >> 8 & 0xFF);
data[PAYLOAD_START_INDEX + 12] = (byte)(mWord5 & 0xFF);
return data;
}
}

View File

@@ -1,53 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import io.github.dsheirer.audio.convert.thumbdv.message.VocoderRate;
/**
* Set Vocoder Rate request packet
*/
public class SetVocoderRequest extends AmbeRequest
{
private VocoderRate mVocoderRate;
public SetVocoderRequest(VocoderRate rate)
{
mVocoderRate = rate;
}
@Override
public PacketField getType()
{
return PacketField.PKT_RATE_TABLE;
}
@Override
public byte[] getData()
{
byte[] data = createMessage(2, getType());
data[PAYLOAD_START_INDEX + 1] = mVocoderRate.getCode();
return data;
}
}

View File

@@ -1,43 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.request;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Version string request packet
*/
public class VersionRequest extends AmbeRequest
{
@Override
public PacketField getType()
{
return PacketField.PKT_VERSION_STRING;
}
@Override
public byte[] getData()
{
return createMessage(1, getType());
}
}

View File

@@ -1,60 +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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.AmbeMessage;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import java.util.Arrays;
/**
* AMBE-3000R Response Packet
*/
public abstract class AmbeResponse extends AmbeMessage
{
protected static final int PAYLOAD_START_INDEX = 5;
private byte[] mMessage;
protected AmbeResponse(byte[] message)
{
mMessage = message;
}
/**
* Control packet type
*/
public abstract PacketField getType();
/**
* Received message bytes
*/
protected byte[] getMessage()
{
return mMessage;
}
/**
* Payload of the packet (does not include the packet header)
*/
protected byte[] getPayload()
{
return Arrays.copyOfRange(getMessage(), PAYLOAD_START_INDEX, getMessage().length);
}
}

View File

@@ -1,59 +0,0 @@
/*******************************************************************************
* sdr-trunk
* Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import io.github.dsheirer.sample.ConversionUtils;
import java.util.Arrays;
/**
* Decode speech response
*/
public class DecodeSpeechResponse extends AmbeResponse
{
public DecodeSpeechResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PACKET_TYPE_DECODE_SPEECH;
}
/**
* Payload of the packet (does not include the packet header)
*/
protected byte[] getPayload()
{
return Arrays.copyOfRange(getMessage(), PAYLOAD_START_INDEX + 1, getMessage().length);
}
public float[] getSamples()
{
return ConversionUtils.convertFromSigned16BitSamples(getPayload());
}
@Override
public String toString()
{
return "DECODED SPEECH: SAMPLE COUNT:" + getSamples().length + " " + toHex(getPayload());
}
}

View File

@@ -1,59 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import java.util.Arrays;
/**
* Encode speech response
*/
public class EncodeSpeechResponse extends AmbeResponse
{
public EncodeSpeechResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PACKET_TYPE_ENCODE_SPEECH;
}
/**
* Payload of the packet (does not include the packet header)
*/
protected byte[] getPayload()
{
return Arrays.copyOfRange(getMessage(), PAYLOAD_START_INDEX + 1, getMessage().length);
}
@Override
public String toString()
{
return "ENCODED SPEECH: " + toHex(getPayload()) + " " + Arrays.toString(getMessage());
}
}

View File

@@ -1,49 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Get configuration response
*/
public class GetConfigResponse extends AmbeResponse
{
public GetConfigResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_GET_CONFIG;
}
@Override
public String toString()
{
return "CONFIGURATION: " + toHex(getPayload());
}
}

View File

@@ -1,58 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Initialize CODEC response
*/
public class InitializeCodecResponse extends AmbeResponse
{
public InitializeCodecResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_INIT;
}
/**
* Success / fail
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "INITIALIZE CODEC " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,56 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Product ID Response
*/
public class ProductIdResponse extends AmbeResponse
{
public ProductIdResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_PRODUCT_ID;
}
/**
* Product ID string
*/
public String getProductId()
{
return new String(getPayload()).trim();
}
@Override
public String toString()
{
return "PRODUCT ID:" + getProductId();
}
}

View File

@@ -1,50 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import java.util.Arrays;
/**
* Ready response
*/
public class ReadyResponse extends AmbeResponse
{
public ReadyResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_READY;
}
@Override
public String toString()
{
return "READY" + Arrays.toString(getMessage());
}
}

View File

@@ -1,57 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Reset response
*/
public class ResetResponse extends AmbeResponse
{
public ResetResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_RESET;
}
/**
* Success indicator
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "RESET " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,58 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set channel format response
*/
public class SetChannelFormatResponse extends AmbeResponse
{
public SetChannelFormatResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_CHANNEL_FORMAT;
}
/**
* Success or fail
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "SET CHANNEL FORMAT " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,57 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set Vocoder rate response
*/
public class SetChannelResponse extends AmbeResponse
{
public SetChannelResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_CHANNEL_0;
}
/**
* Success indicator
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "SET CHANNEL 0 " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,58 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set packet mode response
*/
public class SetPacketModeResponse extends AmbeResponse
{
public SetPacketModeResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_CODEC_STOP;
}
/**
* Success or fail
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "SET PACKET MODE " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,58 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set speech format response
*/
public class SetSpeechFormatResponse extends AmbeResponse
{
public SetSpeechFormatResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_SPEECH_FORMAT;
}
/**
* Success or fail
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "SET SPEECH FORMAT " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,65 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set Vocoder parameter response
*/
public class SetVocoderParameterResponse extends AmbeResponse
{
public SetVocoderParameterResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_RATE_PARAMETER;
}
/**
* Success indicator
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==3 && payload[0] == 0;
}
@Override
public String toString()
{
if(isSuccessful())
{
return "SET VOCODER RATE SUCCESSFUL";
}
else
{
return "SET VOCODER RATE **FAILED** - RESPONSE:" + toHex(getPayload());
}
}
}

View File

@@ -1,58 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Set Vocoder rate response
*/
public class SetVocoderResponse extends AmbeResponse
{
public SetVocoderResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_RATE_TABLE;
}
/**
* Success indicator
*/
public boolean isSuccessful()
{
byte[] payload = getPayload();
return payload != null && payload.length ==1 && payload[0] == 0;
}
@Override
public String toString()
{
return "SET VOCODER RATE " + (isSuccessful() ? "SUCCESSFUL" : "**FAILED**");
}
}

View File

@@ -1,50 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import java.util.Arrays;
/**
* Unknown Response Message
*/
public class UnknownResponse extends AmbeResponse
{
public UnknownResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.UNKNOWN;
}
@Override
public String toString()
{
return "UNKNOWN MESSAGE:" + Arrays.toString(getMessage());
}
}

View File

@@ -1,56 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 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.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
/**
* Version Response
*/
public class VersionResponse extends AmbeResponse
{
public VersionResponse(byte[] message)
{
super(message);
}
@Override
public PacketField getType()
{
return PacketField.PKT_VERSION_STRING;
}
/**
* Version string
*/
public String getVersion()
{
return new String(getPayload()).trim();
}
@Override
public String toString()
{
return "VERSION:" + getVersion();
}
}

View File

@@ -31,6 +31,7 @@ import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener; import io.github.dsheirer.sample.Listener;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -58,13 +59,19 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>(); private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>();
private final UserPreferences mUserPreferences; private final UserPreferences mUserPreferences;
private final String mChannelName; private final String mChannelName;
private final AtomicInteger mPeakLevelBits = new AtomicInteger();
private AudioSegment mCurrentAudioSegment; private volatile AudioSegment mCurrentAudioSegment;
private Listener<IdentifierCollection> mIdentifierCollectionListener; private Listener<IdentifierCollection> mIdentifierCollectionListener;
private boolean mDropDuplicates; private boolean mDropDuplicates;
private boolean mMetadataSent = false; private boolean mMetadataSent = false;
private boolean mMuted; private boolean mMuted;
private boolean mDisabled; private boolean mDisabled;
private volatile TalkgroupHold mHold;
private Listener<TalkgroupHold> mHoldListener;
private volatile Runnable mPlaybackListener;
private volatile ReplaySource mPendingReplay;
private volatile ReplaySource mReplay;
private float[] mAudioSegmentStartTone; private float[] mAudioSegmentStartTone;
private float[] mAudioSegmentDropTone; private float[] mAudioSegmentDropTone;
private int mCurrentBufferIndex = -1; private int mCurrentBufferIndex = -1;
@@ -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. * Indicates if this audio channel is enabled.
*/ */
@@ -153,7 +268,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/ */
public boolean hasAudioSegment() public boolean hasAudioSegment()
{ {
return mCurrentAudioSegment != null; return mCurrentAudioSegment != null || mReplay != null;
} }
/** /**
@@ -174,20 +289,75 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/ */
public float[] getAudio() public float[] getAudio()
{ {
if(mAudioBuffer.isFull()) float[] audio = getNextAudio();
{
float[] audio = mAudioBuffer.get();
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()) if(isMuted())
{ {
return new float[SAMPLES_PER_INTERVAL]; return new float[SAMPLES_PER_INTERVAL];
} }
else }
return audio;
}
/**
* Peak absolute sample value of the audio provided by this channel since the last call to this method, measured
* before muting. The audio output pulls audio ahead of playback, so this leads what is heard by the playback
* device buffer latency. Thread safe.
* @return peak level in the range 0.0 to 1.0 (or higher, if the audio is clipping) and resets it to zero.
*/
public float getAndResetPeakLevel()
{
return Float.intBitsToFloat(mPeakLevelBits.getAndSet(0));
}
/**
* Updates the peak level with the maximum absolute sample value of the audio buffer.
*/
private void updatePeakLevel(float[] audio)
{
float peak = 0.0f;
for(float sample: audio)
{
float magnitude = Math.abs(sample);
if(magnitude > peak)
{ {
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) if(mCurrentAudioSegment == null)
{ {
loadNextAudioSegment(); loadNextAudioSegment();
@@ -249,10 +419,54 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
audio = mAudioBuffer.flush(); audio = mAudioBuffer.flush();
} }
//Finally, if we have buffer audio and we're muted, return silence return audio;
if(isMuted() && audio != null) }
/**
* Starts a pending replay and provides the next replay audio. Audio thread.
* @return replay audio, or null when no replay is playing (normal call playback continues)
*/
private float[] getReplayAudio()
{
ReplaySource pending = mPendingReplay;
if(pending != null)
{ {
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; return audio;
@@ -298,7 +512,20 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/ */
private boolean isThrowaway(AudioSegment audioSegment) 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); MyEventBus.getGlobalEventBus().unregister(this);
ReplaySource replay = mReplay;
if(replay != null)
{
replay.stop();
}
disposeCurrentAudioSegment(); disposeCurrentAudioSegment();
mAudioEventBroadcaster.clear(); mAudioEventBroadcaster.clear();
mIdentifierCollectionListener = null; mIdentifierCollectionListener = null;
mHoldListener = null;
mPlaybackListener = null;
} }
/** /**
@@ -457,6 +693,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
mCurrentAudioSegment.decrementConsumerCount(); mCurrentAudioSegment.decrementConsumerCount();
mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this); mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this);
mCurrentAudioSegment = null; mCurrentAudioSegment = null;
notifyPlayback();
} }
} }
@@ -494,6 +731,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
if(audioSegment != null) if(audioSegment != null)
{ {
notifyPlayback();
mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this); mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this);
broadcast(mCurrentAudioSegment.getIdentifierCollection()); broadcast(mCurrentAudioSegment.getIdentifierCollection());
} }

View File

@@ -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 static final Logger mLog = LoggerFactory.getLogger(AudioPlaybackManager.class);
private final AudioSegmentPrioritySorter mAudioSegmentPrioritySorter = new AudioSegmentPrioritySorter(); private final AudioSegmentPrioritySorter mAudioSegmentPrioritySorter = new AudioSegmentPrioritySorter();
private final Broadcaster<AudioEvent> mControllerBroadcaster = new Broadcaster<>(); private final Broadcaster<AudioEvent> mControllerBroadcaster = new Broadcaster<>();
private final Broadcaster<ChannelPlayback> mPlaybackBroadcaster = new Broadcaster<>();
private final List<AudioSegment> mAudioSegments = new ArrayList<>(); private final List<AudioSegment> mAudioSegments = new ArrayList<>();
private final List<AudioSegment> mPendingAudioSegments = new ArrayList<>(); private final List<AudioSegment> mPendingAudioSegments = new ArrayList<>();
private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>(); private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>();
@@ -61,6 +62,8 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
private AudioPlaybackDeviceDescriptor mAudioPlaybackDevice; private AudioPlaybackDeviceDescriptor mAudioPlaybackDevice;
private AudioOutput mAudioOutput; private AudioOutput mAudioOutput;
private ScheduledFuture<?> mProcessingTask; private ScheduledFuture<?> mProcessingTask;
private final TalkgroupHold[] mHolds = new TalkgroupHold[2];
private final long[] mHoldActivity = new long[2];
/** /**
* Constructs an instance. * Constructs an instance.
@@ -114,6 +117,8 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
*/ */
private void processAudioSegments() private void processAudioSegments()
{ {
updateHoldActivity();
//Process new audio segments queue. If segment has audio, queue it for replay, otherwise place in pending queue //Process new audio segments queue. If segment has audio, queue it for replay, otherwise place in pending queue
AudioSegment newSegment = mNewAudioSegmentQueue.poll(); AudioSegment newSegment = mNewAudioSegmentQueue.poll();
@@ -182,7 +187,8 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
{ {
audioSegment = it.next(); audioSegment = it.next();
if(audioSegment.isDoNotMonitor() || (audioSegment.isDuplicate() && if((audioSegment.isDoNotMonitor() && getHoldingChannelIndex(audioSegment) < 0) ||
(audioSegment.isDuplicate() &&
mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled())) mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled()))
{ {
it.remove(); it.remove();
@@ -233,20 +239,7 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
try try
{ {
//Assign empty audio outputs first assignAudioSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels());
for(AudioChannel audioChannel: mAudioOutput.getAudioProvider().getAudioChannels())
{
if(audioChannel.isEmpty())
{
audioChannel.play(mAudioSegments.removeFirst());
if(mAudioSegments.isEmpty())
{
return;
}
}
}
replaceLowerPriorityQueuedSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels());
} }
finally 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, * Swaps audio segments queued on the audio channels for waiting audio segments that have a higher playback priority,
* so that a segment queued behind the current playback can't hold a higher priority segment out of the channel. * so that a segment queued behind the current playback can't hold a higher priority segment out of the channel.
@@ -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 //Note: audio output can use an alternate device if the requested device can't be used, so we assign
//the descriptor that was actually used by the audio output //the descriptor that was actually used by the audio output
mAudioPlaybackDevice = mAudioOutput.getAudioPlaybackDeviceDescriptor(); mAudioPlaybackDevice = mAudioOutput.getAudioPlaybackDeviceDescriptor();
//Re-apply hold talkgroups to the new channels (and drop a right channel hold for a mono device)
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
for(int x = 0; x < channels.size(); x++)
{
final int channelIndex = x;
final AudioChannel channel = channels.get(x);
final int outputChannels = channels.size();
channel.setPlaybackListener(() -> mPlaybackBroadcaster.broadcast(
getChannelPlayback(channel, channelIndex, outputChannels)));
}
for(int x = 0; x < mHolds.length; x++)
{
if(x < channels.size())
{
channels.get(x).setHold(mHolds[x]);
}
else
{
mHolds[x] = null;
}
}
} }
finally finally
{ {

View File

@@ -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) public ByteNativeBuffer(byte[] samples, long timestamp, float averageDc, float samplesPerMillisecond)
{ {
super(timestamp, samplesPerMillisecond); super(timestamp, samplesPerMillisecond);
//Ensure we're an even multiple of the fragment size. Typically, this will be 64k or 128k //Ensure we're an even multiple of the fragment size in bytes (2 bytes per I/Q sample). Typically, this
if(samples.length % FRAGMENT_SIZE != 0) //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; 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 final static Logger mLog = LoggerFactory.getLogger(ChannelMetadata.class);
private AliasListConfigurationIdentifier mAliasListConfigurationIdentifier;
private SystemConfigurationIdentifier mSystemConfigurationIdentifier; private SystemConfigurationIdentifier mSystemConfigurationIdentifier;
private SiteConfigurationIdentifier mSiteConfigurationIdentifier; private SiteConfigurationIdentifier mSiteConfigurationIdentifier;
private ChannelNameConfigurationIdentifier mChannelNameConfigurationIdentifier; private ChannelNameConfigurationIdentifier mChannelNameConfigurationIdentifier;
@@ -128,6 +129,19 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
return this; return this;
} }
/**
* Alias list configuration identifier
*/
public AliasListConfigurationIdentifier getAliasListConfigurationIdentifier()
{
return mAliasListConfigurationIdentifier;
}
public boolean hasAliasListConfigurationIdentifier()
{
return mAliasListConfigurationIdentifier != null;
}
/** /**
* System configuration identifier * System configuration identifier
*/ */
@@ -323,6 +337,15 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
switch(identifier.getForm()) switch(identifier.getForm())
{ {
case ALIAS_LIST: case ALIAS_LIST:
if(identifier instanceof AliasListConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))
{
mAliasListConfigurationIdentifier = (AliasListConfigurationIdentifier)identifier;
}
else
{
mAliasListConfigurationIdentifier = null;
}
if(update.isAdd()) if(update.isAdd())
{ {
mAliasList = mAliasModel.getAliasList((AliasListConfigurationIdentifier)identifier); mAliasList = mAliasModel.getAliasList((AliasListConfigurationIdentifier)identifier);
@@ -339,6 +362,7 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
} }
} }
} }
broadcastUpdate(ChannelMetadataField.CONFIGURATION_ALIAS_LIST);
break; break;
case CHANNEL: case CHANNEL:
if(identifier instanceof ChannelNameConfigurationIdentifier && (update.isAdd() || update.isSilentAdd())) if(identifier instanceof ChannelNameConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))

View File

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

View File

@@ -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 * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -18,67 +18,73 @@
*/ */
package io.github.dsheirer.channel.metadata; 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.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.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.slf4j.Logger; import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel; /**
* Model of the channel metadata for the currently processing channels, with a map from each channel metadata to the
public class ChannelMetadataModel extends AbstractTableModel implements IChannelMetadataUpdateListener * 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; * Listener for changes to the channel metadata model. Notifications arrive on the thread that changed the
public static final int COLUMN_USER_FROM = 2; * model, sometimes while the model is locked, so implementations must not block and must not call back into
public static final int COLUMN_USER_FROM_ALIAS = 3; * the model from the notification thread.
public static final int COLUMN_USER_TO = 4; */
public static final int COLUMN_USER_TO_ALIAS = 5; public interface Listener
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()
{ {
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 * Constructs an instance
* @param preferenceType that was updated
*/ */
@Subscribe public ChannelMetadataModel()
public void preferenceUpdated(PreferenceType preferenceType)
{ {
if(preferenceType == PreferenceType.TALKGROUP_FORMAT) }
{
EventQueue.invokeLater(() -> { /**
for(int row = 0; row < mChannelMetadata.size(); row++) * Registers the listener to receive model change notifications.
{ * @param listener to register
fireTableCellUpdated(row, COLUMN_USER_FROM); * @return the channel metadata in the model when the listener is registered, so that the listener starts from
fireTableCellUpdated(row, COLUMN_USER_TO); * 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() public String getDiagnosticInformation()
{ {
StringBuilder sb = new StringBuilder(); Map<ChannelMetadata,Channel> mapCopy;
Map<ChannelMetadata,Channel> mapCopy = new HashMap<>(mMetadataChannelMap); List<ChannelMetadata> metadataCopy;
List<ChannelMetadata> metadataCopy = new ArrayList<>(mChannelMetadata);
synchronized(this)
{
mapCopy = new HashMap<>(mMetadataChannelMap);
metadataCopy = new ArrayList<>(mChannelMetadata);
}
StringBuilder sb = new StringBuilder();
sb.append("Channel Metadata Model Diagnostics\n"); sb.append("Channel Metadata Model Diagnostics\n");
for(ChannelMetadata channelMetadata: metadataCopy) for(ChannelMetadata channelMetadata: metadataCopy)
@@ -122,51 +134,34 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
return sb.toString(); return sb.toString();
} }
/**
* Prepares the model for disposal.
*/
public void dispose() 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); if(!mChannelMetadata.contains(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())
{ {
mChannelMetadata.add(channelMetadata); mChannelMetadata.add(channelMetadata);
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
int index = mChannelMetadata.indexOf(channelMetadata);
fireTableRowsInserted(index, index);
channelMetadata.setUpdateEventListener(ChannelMetadataModel.this);
} }
if(mChannelAddListener != null) mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
{ channelMetadata.setUpdateEventListener(this);
mChannelAddListener.receive(channelAndMetadata); }
}
}); for(Listener listener: mListeners)
{
listener.added(channelAndMetadata);
}
} }
/** /**
@@ -174,7 +169,7 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
* @param channelMetadatas * @param channelMetadatas
* @param channel * @param channel
*/ */
public void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel) public synchronized void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
{ {
for(ChannelMetadata channelMetadata: channelMetadatas) 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 channelMetadata.removeUpdateEventListener();
EventQueue.invokeLater(() -> { mMetadataChannelMap.remove(channelMetadata);
channelMetadata.removeUpdateEventListener();
int index = mChannelMetadata.indexOf(channelMetadata);
mChannelMetadata.remove(channelMetadata);
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 new ArrayList<>(mChannelMetadata);
{
return mChannelMetadata.get(row);
}
return null;
} }
/** /**
* Returns the channel that matches the metadata or null * Returns the channel that matches the metadata or null
*/ */
public Channel getChannelFromMetadata(ChannelMetadata channelMetadata) public synchronized Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
{ {
return mMetadataChannelMap.get(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 @Override
public void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField) public void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField)
{ {
final int rowIndex = mChannelMetadata.indexOf(channelMetadata); for(Listener listener: mListeners)
if(rowIndex >= 0)
{ {
//Execute on the swing thread to avoid threading issues listener.updated(channelMetadata, channelMetadataField);
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
switch(channelMetadataField)
{
case CONFIGURATION_CHANNEL:
fireTableCellUpdated(rowIndex, COLUMN_CONFIGURATION_CHANNEL);
break;
case CONFIGURATION_FREQUENCY:
fireTableCellUpdated(rowIndex, COLUMN_CONFIGURATION_FREQUENCY);
break;
case DECODER_CHANNEL_NAME:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_LOGICAL_CHANNEL_NAME);
break;
case DECODER_TYPE:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_TYPE);
break;
case DECODER_STATE:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_STATE);
break;
case USER_FROM:
fireTableCellUpdated(rowIndex, COLUMN_USER_FROM);
fireTableCellUpdated(rowIndex, COLUMN_USER_FROM_ALIAS);
break;
case USER_TO:
fireTableCellUpdated(rowIndex, COLUMN_USER_TO);
fireTableCellUpdated(rowIndex, COLUMN_USER_TO_ALIAS);
break;
}
}
});
} }
} }
} }

View File

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

View File

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

View File

@@ -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 * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -16,28 +16,23 @@
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
* **************************************************************************** * ****************************************************************************
*/ */
package io.github.dsheirer.database;
package io.github.dsheirer.util;
import java.awt.EventQueue;
/** /**
* 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) MISSING,
{ /**
if(EventQueue.isDispatchThread()) * Schema exists but doesn't have sdrtrunk tables
{ */
r.run(); EMPTY,
} /**
else * Schema has sdrtrunk tables
{ */
EventQueue.invokeLater(r); 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 * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -16,38 +16,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
* **************************************************************************** * ****************************************************************************
*/ */
package io.github.dsheirer.database.ageoff;
package io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token;
import io.github.dsheirer.bits.CorrectedBinaryMessage;
/** /**
* LRRP Trigger on GPIO Token * What an age-off rule removes
*
* Total Length: 1 byte
*/ */
public class TriggerGpio extends Token public enum AgeOffAction
{ {
/** DELETE_CALL_AND_RECORDING("Delete the call and its recording"),
* Constructs an instance of a heading token. DELETE_RECORDING_ONLY("Delete the recording, keep the call");
*
* @param message containing the heading
* @param offset to the start of the token
*/
public TriggerGpio(CorrectedBinaryMessage message, int offset)
{
super(message, offset);
}
@Override private final String mLabel;
public TokenType getTokenType()
AgeOffAction(String label)
{ {
return TokenType.TRIGGER_GPIO; mLabel = label;
} }
@Override @Override
public String toString() 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);
}
}
}

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