Compare commits

..
5 Commits
Author SHA1 Message Date
mckero c42e1d7b4e fix(wavelog): send real ADIF band + sat_mode, not the illegal "SAT"
Satellite QSOs uploaded with BAND=SAT, which is not a legal ADIF Band
enumeration value (the legal values are concrete bands: 160M/80M/.../
2M/70CM/23CM...). Loggers that fail to parse an unknown band fall back
to a default — observed as QSOs landing in 160m. SAT is only legal as
PROP_MODE (propagation mode), which is already sent for v1.

Changes (WaveLogApi):
- bandFromHz(): map TX frequency to the real ADIF band (2M for VHF,
  70CM for UHF, etc.)
- satModeFrom(): derive the ADIF SAT_MODE convention string from TX/RX
  bands ("V/U" = VHF up / UHF down, "U/V", "V/S", "U/S"...; empty for
  same-band links)
- v2 JSON: band=<real band>, add sat_mode when non-empty
- v1 ADIF: <band:> real band, add <sat_mode:> when non-empty;
  PROP_MODE=SAT kept

Verification:
- New tests: SO-50 (145.850 up / 436.795 down) -> band 2M, sat_mode V/U;
  AO-73 (435.150 up / 145.950 down) -> band 70CM, sat_mode U/V;
  same-band -> empty sat_mode; satellite freqs never map to 160M.
- All wavelog payload tests + full domain suite green.
2026-08-09 07:48:15 +00:00
mckero 09ebf1f39a feat(cw): add spectral auto-tune so the decoder finds the CW tone
The fldigi port ran a fixed 600 Hz NCO, so any real signal not inside
600±75 Hz (the 150 Hz filter passband) decoded nothing — the decode rate
was effectively zero unless the tone happened to be on frequency. This
mirrors the behaviour of the removed channelTracker: a sliding spectral
peak detector now steers the NCO to the strongest tone.

Changes:
- Collect raw input, run a 512-pt Hann-windowed FFT every frame, find
  the strongest bin in 300..1500 Hz (CW range), smooth-track it.
- First strong peak locks immediately (no RX reset, so the triggering
  element survives); later large jumps (>120 Hz) retune and reset the
  fldigi state machine; small drifts are eased at 20%.
- Absolute energy floor (peak < 30) so silence/noise never steers.
- estimatedPitch now reflects the tracked tone frequency.

Verification:
- New unit test: 900 Hz "CQ" with decoder initialized at 600 Hz decodes
  correctly and pitch moves to ~900 Hz.
- All 9 decoder tests pass; full domain/cw/radar test suites green.
2026-08-09 05:04:48 +00:00
mckero ec40f29f28 fix(cw): make the waterfall redraw as new spectra arrive
The waterfall backed its pixels with a plain FloatArray and never
signalled Compose, so the Canvas drew once (empty) and stayed frozen —
no spectrum ever appeared. Add a monotonic frame-counter State that
pushSamples bumps per FFT frame; the Canvas reads it in composition to
trigger redraws. Also switch to log-ish intensity scaling so quiet bins
stay dark while strong CW tones pop, matching the DeepCW look.

Applies to both the CW decode screen and the radar transceiver panel.
2026-08-08 15:04:12 +00:00
mckero 5dd7a35a23 fix(cw): remove unused legacy drawables that fail release resource linking
ic_baseline_delete/pause/save/share_24.xml were leftovers from the
Morse Expert View-based UI. They reference ?attr/colorControlNormal
which does not resolve in the release variant (no Material dependency
in feature:cw), breaking assembleRelease. The new Compose UI uses
icons from core:presentation, so these files are dead code.
2026-08-08 14:45:10 +00:00
mckero 4b835bac5c feat(cw): replace reversed Morse Expert engine with a pure-Kotlin fldigi port
Background:
The CW decoder previously shipped a decompiled copy of the proprietary
Morse Expert 1.15 (com/ve3nea/morse_expert + obfuscated classes,
libnativedecoderjni.so, suncompat black-magic) — a copyright liability.
This removes all of it and reimplements the decoder on the open-source
fldigi (GPL v3) CW engine as a faithful pure-Kotlin port with no JNI.

Changes:
- Delete all Morse Expert reverse-engineered code: MainActivity,
  obfuscated packages (B/B0/D/E2/...), suncompat/, pas/nativedecoder,
  armeabi-v7a libnativedecoderjni.so, and the original View-based layouts
  (activity_main, cw_panel_main, options_menu).
- Add a full fldigi CW pipeline in core/domain/cw:
  - CwFldigiDsp: NCO down-conversion, FFT filter, movavg constants
  - CwFftFilt: overlap-add FFT band-pass filter (fftfilt port)
  - MorseTable + SomTable: full Morse code table + SOM codebook
  - CwFldigiDecoder: decode_stream AGC + hysteresis, state machine,
    adaptive speed tracking (5-55 WPM), SOM winner/normalize matching
- Rewrite CwDecodeScreen as pure Compose (DeepCW-style waterfall,
  live decode line, history, status cards) and CwSettingsDialog
  (speed/bandwidth/SOM) with no View interop.
- Replace the Morse Expert panel in TransceiversPage with a Compose
  panel driving the same decoder; mic capture at 8000 Hz.
- Drop the forced armeabi-v7a abiFilters now that no native lib exists.

Verification:
- 8 unit tests pass (CQ/HELLO at 18-20 wpm, A-J at 30 wpm with
  adaptive tracking, dot/dash/Farnsworth edge cases) — all decode
  correctly from synthesized CW.
- :feature:cw and :feature:radar compile; app assembleDebug succeeds.
- APK contains no ve3nea/nativedecoder/morse_expert classes.
2026-08-08 13:58:19 +00:00
68 changed files with 3771 additions and 2946 deletions

No files matched your search

-4
View File
@@ -40,14 +40,10 @@ captures/
# Keystore files
*.jks
*.keystore
/*.properties
/keystore.properties
/app/keystore.jks
# Hermes agent workspace (plans, local notes)
.hermes/
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
-15
View File
@@ -34,21 +34,6 @@ It is now and always will be completely ad-free and open-source.
* Custom TLE satellite data import is available via Three Line Element .txt files
* Offline first: calculations are made offline. Weekly TLE data update is recommended.
## License
Look4Sat is free software licensed under the [GNU General Public License v3.0](LICENSE).
The CW decoder in `feature/cw` bundles the [DeepCW](https://github.com/e04/deepcw-engine)
neural decoding model, which is licensed under the
[GNU Affero General Public License v3.0](feature/cw/licenses/DeepCW-AGPL-3.0.txt)
(AGPL-3.0-only). Provenance, attribution and the applied int8 quantization are
documented in [`feature/cw/licenses/NOTICE.md`](feature/cw/licenses/NOTICE.md).
Because the combined work incorporates an AGPL-3.0 component, the requirements of
AGPL-3.0 Section 13 apply to the combined work as a whole when it is distributed
(GPL-3.0 Section 13 permits this combination). The CW model runs locally on-device
and does not provide services over a network.
## Star History
<a href="https://www.star-history.com/?repos=rt-bishop%2FLook4Sat&type=timeline&legend=top-left">
+2 -13
View File
@@ -11,23 +11,15 @@ val keystoreProperties = Properties().apply {
}
android {
// CW 解码已迁移为纯 Kotlin fldigi 引擎, 不再有 native 库;
// 取消 armeabi-v7a 强制, 按设备 ABI 打包(含 x86_64 模拟器)
defaultConfig {
// ONNX Runtime 的 AAR 自带 4 个架构共 115MB 原生库(arm64 28M / armv7 20M /
// x86 33M / x86_64 34M)。x86 系列只有模拟器用得到, 全打包会让 APK 从 8MB
// 涨到 135MB。仅保留真机需要的两个 ABI。
ndk {
abiFilters += listOf("arm64-v8a", "armeabi-v7a")
}
}
androidResources {
// 显式保留全部语言(防 shrinkResources 丢弃 in/id 印尼语配置); AGP 9 用 localeFilters
localeFilters += listOf(
"en", "zh", "tr", "in", "id", "es", "ru", "si", "uk"
)
// DeepCW 模型必须以未压缩形式打包: ONNX Runtime 通过 mmap 直接读取
// assets, 压缩后无法映射会导致 createSession 失败。noCompress 只在
// 打包 APK 的 app 模块生效, 在 feature 库模块声明无效。
noCompress += "onnx"
}
signingConfigs {
if (keystoreProperties["storeFile"] != null) {
@@ -42,9 +34,6 @@ android {
buildTypes {
release {
signingConfig = signingConfigs.findByName("release")
// ONNX Runtime 走 JNI, R8 混淆会重命名 ai.onnxruntime.* 类导致 native
// 崩溃。convention 插件已开启 isMinifyEnabled, 必须补 keep 规则。
proguardFiles("proguard-rules.pro")
}
}
}
-13
View File
@@ -1,13 +0,0 @@
# ProGuard / R8 rules for the Look4Sat application module.
#
# NOTE: release builds enable minification (isMinifyEnabled=true in the
# convention plugin), so anything whose classes are resolved reflectively or
# through JNI by name MUST be kept here.
# ONNX Runtime (ai.onnxruntime): the Java binding is backed by JNI. Native code
# resolves Java methods/classes by their original names; R8 renaming or
# stripping them causes a hard crash at runtime with no Java stack trace.
# This rule is required by the ONNX Runtime docs for minified Android builds.
# https://onnxruntime.ai/docs/get-started/with-java.html
-keep class ai.onnxruntime.** { *; }
-dontwarn ai.onnxruntime.**
-6
View File
@@ -5,9 +5,3 @@ plugins {
android {
namespace = "com.rtbishop.look4sat.core.data"
}
dependencies {
// DeepCW 神经网络 CW 解码推理。ONNX 推理属 Android 平台依赖, 放此处而非
// core:domain —— 后者须保持纯 Kotlin/JVM 以留 KMP 迁移余地 (见 AGENTS.md)。
implementation(libs.other.onnxruntime)
}
@@ -1,325 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.data.cw
import ai.onnxruntime.OnnxTensor
import ai.onnxruntime.OrtEnvironment
import ai.onnxruntime.OrtSession
import android.content.Context
import android.util.Log
import com.rtbishop.look4sat.core.domain.cw.CwCtcDecoder
import com.rtbishop.look4sat.core.domain.cw.CwDeepBuffer
import com.rtbishop.look4sat.core.domain.cw.CwDeepSpectrogram
import com.rtbishop.look4sat.core.domain.cw.ICwDecoder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.nio.FloatBuffer
/**
* CW decoder backed by the DeepCW neural network (AGPL-3.0, see
* `feature/cw/licenses/NOTICE.md`).
*
* The model classifies a whole audio segment at once rather than streaming
* sample by sample, and it revises earlier characters once more context
* arrives. Incremental stitching therefore produces duplicated callsigns —
* measured character error rates of 67-294% against 0% for whole-segment
* decoding. Instead a [CwDeepBuffer] holds the last 20 seconds and the whole
* window is re-decoded every 1.5 seconds, replacing [decodedText] outright.
*
* The model's fixed 400-1200 Hz analysis window means pitch detection is built
* in; no spectral peak tracking or squelch gating is needed.
*/
class CwDeepDecoder(context: Context) : ICwDecoder {
private companion object {
const val TAG = "CwDeepDecoder"
const val MODEL_ASSET = "deepcw/model.onnx"
const val METADATA_ASSET = "deepcw/model.onnx.json"
/** Evicted audio is decoded into permanent history once this much accumulates. */
const val ARCHIVE_SECONDS = 15.0
val ARCHIVE_THRESHOLD: Int = (CwDeepSpectrogram.SAMPLE_RATE * ARCHIVE_SECONDS).toInt()
}
private val _decodedText = MutableStateFlow("")
override val decodedText: StateFlow<String> = _decodedText.asStateFlow()
private val _historyText = MutableStateFlow("")
override val historyText: StateFlow<String> = _historyText.asStateFlow()
private val _estimatedPitch = MutableStateFlow<Float?>(null)
override val estimatedPitch: StateFlow<Float?> = _estimatedPitch.asStateFlow()
private val _signalStrength = MutableStateFlow(0f)
override val signalStrength: StateFlow<Float> = _signalStrength.asStateFlow()
private val _lastInferenceMs = MutableStateFlow(0)
override val lastInferenceMs: StateFlow<Int> = _lastInferenceMs.asStateFlow()
private val _errorMessage = MutableStateFlow<String?>(null)
override val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()
private val buffer = CwDeepBuffer()
/**
* Evicted audio accumulates here until it reaches [ARCHIVE_SECONDS], then
* is decoded once and appended to [historyText]. Archiving in ~15 s chunks
* keeps the extra inference cheap (short window) while long enough to be
* decoded accurately — the content has already been through the 20 s window
* many times, so a slightly shorter archive decode loses almost nothing.
*/
private val archiveBuffer = FloatArray(CwDeepBuffer.DEFAULT_MAX_SECONDS.toInt() * CwDeepSpectrogram.SAMPLE_RATE)
private var archiveSize = 0
/** Held while inference runs so slow devices skip work instead of queuing it. */
private val inferenceLock = Mutex()
private var environment: OrtEnvironment? = null
private var session: OrtSession? = null
private var chars: List<String> = emptyList()
private var blankIndex = 41
private var inputName = "spectrogram"
private var outputName = "log_probs"
private val appContext = context.applicationContext
private var loadAttempted = false
init {
CwProbe.init(appContext)
CwProbe.step("decoder_constructed")
}
/**
* Loads metadata and the ONNX session on first use.
*
* Deliberately not done in `init`: loading pulls in ONNX Runtime's native
* library, and a failure there surfaces as [UnsatisfiedLinkError]. Thrown
* from a constructor it would take down the whole composable that created
* the decoder, so the work happens here where it can be reported through
* [errorMessage] instead.
*
* @return true when the session is ready to run.
*/
private fun ensureLoaded(): Boolean {
if (session != null) return true
if (loadAttempted) return false
loadAttempted = true
CwProbe.step("load_begin")
try {
val metadata = JSONObject(
appContext.assets.open(METADATA_ASSET).bufferedReader().use { it.readText() }
)
val charArray = metadata.getJSONArray("chars")
chars = List(charArray.length()) { charArray.getString(it) }
blankIndex = metadata.getInt("blank_index")
inputName = metadata.getString("onnx_input_name")
outputName = metadata.getString("onnx_output_name")
val modelBytes = appContext.assets.open(MODEL_ASSET).use { it.readBytes() }
val env = OrtEnvironment.getEnvironment()
environment = env
val options = OrtSession.SessionOptions().apply {
// Keep a core free for audio capture and the UI; the default
// would spread inference across every core on the device.
val threads = (Runtime.getRuntime().availableProcessors() - 1).coerceIn(1, 4)
setIntraOpNumThreads(threads)
}
session = env.createSession(modelBytes, options)
CwProbe.step("load_session_ok")
Log.i(TAG, "DeepCW ready: ${modelBytes.size} bytes, ${chars.size} classes")
return true
} catch (t: Throwable) {
// Catches UnsatisfiedLinkError (missing/mismatched .so) as well as
// asset and session failures.
CwProbe.step("load_failed:${t.javaClass.simpleName}")
Log.e(TAG, "DeepCW model failed to load", t)
_errorMessage.value =
"CW model failed to load: ${t.message ?: t.javaClass.simpleName}"
// Persist the failure for devices without logcat access.
runCatching {
val sw = java.io.StringWriter()
t.printStackTrace(java.io.PrintWriter(sw))
java.io.File(appContext.filesDir, "deepcw_load_error.txt")
.writeText("${t.javaClass.name}: ${t.message}\n${sw}\n")
}
return false
}
}
override suspend fun processBuffer(samples: FloatArray, sampleRate: Int) {
if (samples.isEmpty()) return
if (!ensureLoaded()) return
val resampled = CwDeepSpectrogram.resampleLinear(
samples, sampleRate, CwDeepSpectrogram.SAMPLE_RATE
)
val shouldRedecode = buffer.append(resampled)
// Archive audio that scrolled out of the live window. It is decoded once
// when a full archive chunk has accumulated, so old text does not vanish.
val overflow = buffer.drainOverflow()
if (overflow.isNotEmpty()) {
for (v in overflow) {
if (archiveSize < archiveBuffer.size) archiveBuffer[archiveSize++] = v
}
if (archiveSize >= ARCHIVE_THRESHOLD) {
val audio = archiveBuffer.copyOf(archiveSize)
archiveSize = 0
archiveDecode(audio)
}
}
if (!shouldRedecode || !buffer.hasEnoughAudio) return
// Drop this cycle rather than queue when the previous run is still going.
if (!inferenceLock.tryLock()) {
Log.d(TAG, "inference still running, skipping this interval")
return
}
try {
decodeWindow(buffer.snapshot())
} catch (t: Throwable) {
Log.e(TAG, "inference failed", t)
_errorMessage.value = "CW decode failed: ${t.message ?: t.javaClass.simpleName}"
runCatching {
val sw = java.io.StringWriter()
t.printStackTrace(java.io.PrintWriter(sw))
java.io.File(appContext.filesDir, "deepcw_infer_error.txt")
.writeText("${t.javaClass.name}: ${t.message}\n${sw}\n")
}
} finally {
inferenceLock.unlock()
}
}
private suspend fun decodeWindow(window: FloatArray) = withContext(Dispatchers.Default) {
val activeSession = session ?: return@withContext
val activeEnvironment = environment ?: return@withContext
CwProbe.step("infer_begin frames=${window.size}")
val spectrogram = CwDeepSpectrogram.compute(window)
val text = runInference(activeSession, activeEnvironment, spectrogram)
// Replace, never append: the model rewrites earlier characters as more
// context arrives, so appending would leave stale guesses on screen.
_decodedText.value = text
updateSignalMetrics(spectrogram)
}
/**
* Decode a chunk of audio that has scrolled out of the live window and
* append it to [historyText]. Unlike the live window this never replaces —
* the archived audio is final, so its text is permanent.
*/
private suspend fun archiveDecode(audio: FloatArray) = withContext(Dispatchers.Default) {
val activeSession = session ?: return@withContext
val activeEnvironment = environment ?: return@withContext
if (audio.size < CwDeepSpectrogram.FFT_LENGTH) return@withContext
val spectrogram = CwDeepSpectrogram.compute(audio)
val text = runInference(activeSession, activeEnvironment, spectrogram)
if (text.isNotEmpty()) {
_historyText.value += text
}
}
/** Run the ONNX model over a pre-computed spectrogram and return the decoded text. */
private fun runInference(
activeSession: OrtSession,
activeEnvironment: OrtEnvironment,
spectrogram: Array<FloatArray>
): String {
val frames = spectrogram.size
val bins = CwDeepSpectrogram.FREQUENCY_BINS
val flat = FloatBuffer.allocate(frames * bins)
for (frame in spectrogram) flat.put(frame)
flat.rewind()
val shape = longArrayOf(1, 1, frames.toLong(), bins.toLong())
val startedAt = System.currentTimeMillis()
val text: String
OnnxTensor.createTensor(activeEnvironment, flat, shape).use { input ->
activeSession.run(mapOf(inputName to input)).use { result ->
@Suppress("UNCHECKED_CAST")
val logits = result[outputName].get().value as Array<Array<FloatArray>>
text = CwCtcDecoder.greedy(logits, chars, blankIndex)
}
}
_lastInferenceMs.value = (System.currentTimeMillis() - startedAt).toInt()
CwProbe.step("infer_done ms=${_lastInferenceMs.value}")
return text
}
/**
* Report the loudest bin as the tone pitch and its prominence over the
* window mean as a 0..1 strength, purely for the UI readout.
*/
private fun updateSignalMetrics(spectrogram: Array<FloatArray>) {
if (spectrogram.isEmpty()) return
var bestBin = 0
var bestValue = 0f
var total = 0f
var count = 0
for (frame in spectrogram) {
for (bin in frame.indices) {
val value = frame[bin]
total += value
count++
if (value > bestValue) {
bestValue = value
bestBin = bin
}
}
}
if (count == 0 || bestValue <= 0f) return
val binHz = CwDeepSpectrogram.SAMPLE_RATE.toDouble() / CwDeepSpectrogram.FFT_LENGTH
// Relative bin 0 is 400 Hz; absolute bin index is 32 + bestBin.
val absoluteBin = 32 + bestBin
_estimatedPitch.value = (absoluteBin * binHz).toFloat()
val mean = total / count
_signalStrength.value = ((bestValue - mean) / bestValue).coerceIn(0f, 1f)
}
override fun reset() {
buffer.reset()
_decodedText.value = ""
_historyText.value = ""
archiveSize = 0
_estimatedPitch.value = null
_signalStrength.value = 0f
_lastInferenceMs.value = 0
}
override fun close() {
try {
session?.close()
} catch (t: Throwable) {
Log.w(TAG, "session close failed", t)
}
session = null
environment = null
}
}
@@ -30,6 +30,7 @@ import com.rtbishop.look4sat.core.data.framework.Ic705Controller
import com.rtbishop.look4sat.core.data.framework.NetworkReporter
import com.rtbishop.look4sat.core.data.framework.RadioTrackingService
import com.rtbishop.look4sat.core.data.repository.AmSatRepository
import com.rtbishop.look4sat.core.domain.amsat.AmSatApiClient
import com.rtbishop.look4sat.core.data.repository.DatabaseRepo
import com.rtbishop.look4sat.core.data.repository.SatelliteRepo
import com.rtbishop.look4sat.core.data.repository.SelectionRepo
@@ -82,7 +83,7 @@ class MainContainer(private val context: Context) : IMainContainer {
override val selectionRepo = provideSelectionRepo()
override val satelliteRepo = provideSatelliteRepo()
override val databaseRepo = provideDatabaseRepo()
override val amSatRepo by lazy { AmSatRepository(remoteSource) }
override val amSatRepo = AmSatRepository(com.rtbishop.look4sat.core.domain.amsat.AmSatApiClient())
override val radioTrackingService: IRadioTrackingService by lazy {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
RadioTrackingService(appScope, manager, satelliteRepo, settingsRepo)
@@ -101,11 +102,6 @@ class MainContainer(private val context: Context) : IMainContainer {
override fun provideAudioCapture(): IAudioCapture = AudioCapture()
// 每次调用返回新实例: 调用方负责 close() 释放 OrtSession, 且 Radar 内嵌
// 面板与独立 CW 页各自持有自己的解码器
override fun provideCwDecoder(): com.rtbishop.look4sat.core.domain.cw.ICwDecoder =
com.rtbishop.look4sat.core.data.cw.CwDeepDecoder(context)
override fun provideSaveImage(): ISaveImage = SaveImage(context)
// WaveLog logging (4.5.2): local queue + uploader (shared instance)
@@ -1,92 +1,31 @@
package com.rtbishop.look4sat.core.data.repository
import com.rtbishop.look4sat.core.domain.amsat.AmSatApiClient
import com.rtbishop.look4sat.core.domain.amsat.ApiReport
import com.rtbishop.look4sat.core.domain.model.SatDay
import com.rtbishop.look4sat.core.domain.model.SatReport
import com.rtbishop.look4sat.core.domain.model.SatSlot
import com.rtbishop.look4sat.core.domain.model.SatStatus
import com.rtbishop.look4sat.core.domain.model.SatStatusPage
import com.rtbishop.look4sat.core.domain.repository.IAmSatRepository
import com.rtbishop.look4sat.core.domain.source.IRemoteSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
/** One report from the AMSAT API (data layer model). */
private data class ApiReport(
val id: String,
val name: String,
val callsign: String,
val report: String,
val gridSquare: String,
val reportedTimeUtcSec: Long
)
/** AMSAT status repository using RemoteSource (Clean Architecture: data layer handles HTTP). */
class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepository {
private val isoUtcFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
/** AMSAT status repository: official API v1 -> SatStatusPage (replaces the HTML parser). */
class AmSatRepository(private val apiClient: AmSatApiClient) : IAmSatRepository {
override suspend fun fetchStatus(): SatStatusPage? = withContext(Dispatchers.IO) {
val nowSec = System.currentTimeMillis() / 1000
val catalogJson = remoteSource.getAmSatCatalog() ?: return@withContext null
val reportsJson = remoteSource.getAmSatReports(hours = 168, limit = 500) ?: return@withContext null
val names = parseCatalog(catalogJson)
val reports = parseReports(reportsJson)
val names = apiClient.fetchCatalog()
val reports = apiClient.fetchAllReports(hours = 168)
if (names.isEmpty() && reports.isEmpty()) return@withContext null
val statuses = buildStatuses(names, reports, nowSec)
val reportMap = reports.associate { it.id to toSatReport(it) }
SatStatusPage(System.currentTimeMillis(), statuses, reportMap)
}
/** Parse catalog JSON to list of satellite names */
private fun parseCatalog(json: String): List<String> {
return try {
val arr = JSONObject(json).getJSONArray("data")
(0 until arr.length()).map { arr.getJSONObject(it).getString("name") }
} catch (e: Exception) {
emptyList()
}
}
/** Parse reports JSON to list of ApiReport domain objects */
private fun parseReports(json: String): List<ApiReport> {
return try {
val arr = JSONObject(json).getJSONArray("data")
(0 until arr.length()).mapNotNull { i ->
val o = arr.getJSONObject(i)
val iso = o.optString("reported_time", "")
if (iso.isEmpty()) null else ApiReport(
id = o.optString("id", ""),
name = o.optString("name", ""),
callsign = o.optString("callsign", ""),
report = o.optString("report", ""),
gridSquare = o.optString("grid_square", ""),
reportedTimeUtcSec = parseIsoUtcSec(iso)
)
}
} catch (e: Exception) {
emptyList()
}
}
/** Parse ISO 8601 UTC timestamp to epoch seconds (e.g., "2026-08-05T07:30:00Z") */
private fun parseIsoUtcSec(iso: String): Long {
return try {
(isoUtcFormat.parse(iso)?.time ?: 0L) / 1000
} catch (e: Exception) {
0L
}
}
/** Build one SatStatus (6 days x 12 slots) per catalog satellite, slotting reports by age. */
private fun buildStatuses(names: List<String>, reports: List<ApiReport>, nowSec: Long): List<SatStatus> {
val byName = reports.groupBy { it.name }
@@ -102,7 +41,7 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
val slotEnd = nowSec - slotIdx * 7200L
val inSlot = byName[name].orEmpty().filter { it.reportedTimeUtcSec in slotStart until slotEnd }
if (inSlot.isEmpty()) {
SatSlot(statusColor = NO_REPORT_GRAY, count = 0)
SatSlot(statusColor = NoReportGray, count = 0)
} else {
val newest = inSlot.maxByOrNull { it.reportedTimeUtcSec }!!
SatSlot(
@@ -137,20 +76,18 @@ class AmSatRepository(private val remoteSource: IRemoteSource) : IAmSatRepositor
)
}
/** Map status text to color value (for UI rendering). */
private fun statusColorOf(report: String): Long = when (report.lowercase()) {
"heard", "crew active" -> ACTIVE_BLUE
"telemetry only" -> TLM_ORANGE
"not heard" -> NOT_HEARD_PINK
else -> CONFLICT_DEEP_ORANGE
"heard", "crew active" -> ActiveBlue
"telemetry only" -> TlmOrange
"not heard" -> NotHeardPink
else -> ConflictDeepOrange
}
companion object {
// AMSAT official status colors (from amsat.org/status)
private const val ACTIVE_BLUE = 0xFF648FFF
private const val TLM_ORANGE = 0xFFFFB000
private const val NOT_HEARD_PINK = 0xFFDC267F
private const val CONFLICT_DEEP_ORANGE = 0xFFFE6100
private const val NO_REPORT_GRAY = 0xFFC0C0C0
private const val ActiveBlue = 0xFF648FFF
private const val TlmOrange = 0xFFFFB000
private const val NotHeardPink = 0xFFDC267F
private const val ConflictDeepOrange = 0xFFFE6100
private const val NoReportGray = 0xFFC0C0C0
}
}
@@ -71,36 +71,4 @@ class RemoteSource(
null
}
}
override suspend fun getAmSatCatalog(): String? = withContext(dispatcher) {
try {
val request = Request.Builder()
.url("https://www.amsat.org/status/api/v1/catalog.php")
.header("User-Agent", "Look4Sat/4.5.5")
.build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.string()
}
} catch (exception: Exception) {
println("RemoteSource amsat catalog exception: $exception")
null
}
}
override suspend fun getAmSatReports(hours: Int, limit: Int): String? = withContext(dispatcher) {
try {
val request = Request.Builder()
.url("https://www.amsat.org/status/api/v1/reports.php?hours=$hours&limit=$limit")
.header("User-Agent", "Look4Sat/4.5.5")
.build()
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.string()
}
} catch (exception: Exception) {
println("RemoteSource amsat reports exception: $exception")
null
}
}
}
@@ -0,0 +1,98 @@
/* AmSatApiClient.kt - AMSAT official status API v1 client (pure JVM).
* Endpoints (verified 2026-08):
* GET https://www.amsat.org/status/api/v1/catalog.php -> satellite list
* GET https://www.amsat.org/status/api/v1/reports.php?hours=N&limit=500 -> reports
* Report fields: id, name ("SO-50_[FM]"), callsign, report, grid_square, reported_time (ISO 8601 UTC).
* Status values: Heard / Telemetry Only / Not Heard / Crew Active.
*/
package com.rtbishop.look4sat.core.domain.amsat
import org.json.JSONObject
import org.json.JSONArray
import java.io.BufferedReader
import java.net.HttpURLConnection
import java.net.URL
/** One report from the AMSAT API. */
data class ApiReport(
val id: String,
val name: String, // "SO-50_[FM]" (API name, includes mode suffix)
val callsign: String,
val report: String, // Heard / Telemetry Only / Not Heard / Crew Active
val gridSquare: String,
val reportedTimeUtcSec: Long
)
/** AMSAT official satellite status API v1 client. */
class AmSatApiClient(private val baseUrl: String = "https://www.amsat.org/status/api/v1") {
/** Fetch the full satellite catalog. Returns API names (e.g. "SO-50_[FM]"). */
fun fetchCatalog(): List<String> {
val body = httpGet("$baseUrl/catalog.php") ?: return emptyList()
return try {
val arr = JSONObject(body).getJSONArray("data")
(0 until arr.length()).map { arr.getJSONObject(it).getString("name") }
} catch (e: Exception) {
emptyList()
}
}
/** Fetch reports for a rolling UTC window. Empty on failure. */
fun fetchAllReports(hours: Int = 168): List<ApiReport> {
val body = httpGet("$baseUrl/reports.php?hours=$hours&limit=500") ?: return emptyList()
return try {
val arr = JSONObject(body).getJSONArray("data")
(0 until arr.length()).mapNotNull { i ->
val o = arr.getJSONObject(i)
val iso = o.optString("reported_time", "")
if (iso.isEmpty()) null else ApiReport(
id = o.optString("id", ""),
name = o.optString("name", ""),
callsign = o.optString("callsign", ""),
report = o.optString("report", ""),
gridSquare = o.optString("grid_square", ""),
reportedTimeUtcSec = parseIsoUtcSec(iso)
)
}
} catch (e: Exception) {
emptyList()
}
}
/** Parse "2026-08-05T07:30:00Z" to epoch seconds (minSdk 24: no java.time). */
fun parseIsoUtcSec(iso: String): Long {
val m = Regex("""(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})""").find(iso) ?: return 0L
val (y, mo, d, h, mi, s) = m.destructured
val days = daysFromCivil(y.toInt(), mo.toInt(), d.toInt())
return days * 86400L + h.toInt() * 3600L + mi.toInt() * 60L + s.toInt()
}
/** Days since 1970-01-01 (civil calendar, proleptic Gregorian). */
private fun daysFromCivil(year: Int, month: Int, day: Int): Long {
val y = if (month <= 2) year - 1 else year
val era = (if (y >= 0) y else y - 399) / 400
val yoe = y - era * 400
val doy = (153 * (if (month > 2) month - 3 else month + 9) + 2) / 5 + day - 1
val doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
return era * 146097L + doe - 719468
}
private fun httpGet(url: String): String? {
return try {
val conn = URL(url).openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 15000
conn.readTimeout = 20000
conn.setRequestProperty("User-Agent", "Look4Sat/4.5.5")
if (conn.responseCode !in 200..299) {
conn.disconnect()
return null
}
val text = conn.inputStream.bufferedReader().use(BufferedReader::readText)
conn.disconnect()
text
} catch (e: Exception) {
null
}
}
}
@@ -0,0 +1,154 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Bayesian Morse timing decoder.
* Replaces hard thresholds with probability-based decision making.
*
* Inspired by VE3NEA's CW Skimmer approach:
* "Instead of making a hard decision at every input sample whether the signal
* is present or not, compute the probability that the signal is present."
*
* Uses Gaussian probability density centered on expected durations:
* P(dit | duration) = exp(-(duration - dotMs)^2 / (2 * variance^2))
* P(dash | duration) = exp(-(duration - 3*dotMs)^2 / (2 * variance^2))
*/
internal class CwBayesianDecoder {
// Morse timing parameters
private var dotDurationMs = 60f // initial 20 WPM
private var speedWpm = 20f
// Current symbol being accumulated
private var currentSymbol = StringBuilder()
private var textBuffer = StringBuilder()
// Recent dit lengths for speed estimation
private val recentDits = mutableListOf<Float>()
// Output
private var _decodedText = ""
val decodedText: String get() = _decodedText
/** Gaussian probability. */
private fun gaussianProb(durationMs: Float, expectedMs: Float, varianceMs: Float): Float {
if (varianceMs <= 0f) return 0f
val diff = durationMs - expectedMs
return kotlin.math.exp(-(diff * diff) / (2 * varianceMs * varianceMs))
}
/** Process a tone duration. Returns the symbol type with highest probability. */
fun processTone(durationMs: Float): ToneResult {
val ditProb = gaussianProb(durationMs, dotDurationMs, dotDurationMs * 0.4f)
val dashProb = gaussianProb(durationMs, dotDurationMs * 3f, dotDurationMs * 0.6f)
return if (ditProb > dashProb && ditProb > 0.05f) {
currentSymbol.append('0')
recentDits.add(durationMs)
updateSpeed()
ToneResult('0', ditProb)
} else if (dashProb > 0.05f) {
currentSymbol.append('1')
ToneResult('1', dashProb)
} else {
ToneResult(null, 0f)
}
}
/** Process a gap duration. Returns decoded character or null. */
fun processGap(durationMs: Float): Char? {
if (currentSymbol.isEmpty()) {
val wordProb = gaussianProb(durationMs, dotDurationMs * 7f, dotDurationMs * 1.2f)
if (wordProb > 0.2f) {
textBuffer.append(' ')
_decodedText = textBuffer.toString()
return ' '
}
return null
}
val interCharProb = gaussianProb(durationMs, dotDurationMs * 3f, dotDurationMs * 0.6f)
val wordProb = gaussianProb(durationMs, dotDurationMs * 7f, dotDurationMs * 1.2f)
if (wordProb > interCharProb && wordProb > 0.2f) {
val char = flushSymbol()
textBuffer.append(' ')
_decodedText = textBuffer.toString()
return char
}
if (interCharProb > 0.15f) {
val char = flushSymbol()
_decodedText = textBuffer.toString()
return char
}
return null
}
private fun flushSymbol(): Char? {
if (currentSymbol.isEmpty()) return null
val morse = currentSymbol.toString()
currentSymbol.clear()
val char = morseToChar(morse)
if (char != null) textBuffer.append(char)
return char
}
private fun updateSpeed() {
if (recentDits.size < 3) return
val sorted = recentDits.sorted()
val median = sorted[sorted.size / 2]
if (median > 0f) {
dotDurationMs = dotDurationMs * 0.7f + median * 0.3f
val wpm = 60.0f / (50.0f * dotDurationMs / 1000.0f)
if (wpm in 5f..55f) speedWpm = wpm
}
}
fun getSpeed(): Float = speedWpm
fun reset() {
dotDurationMs = 60f
speedWpm = 20f
recentDits.clear()
currentSymbol.clear()
textBuffer.clear()
_decodedText = ""
}
companion object {
private val MORSE_TABLE = mapOf(
"01" to 'A', "1000" to 'B', "1010" to 'C', "100" to 'D', "0" to 'E',
"0010" to 'F', "110" to 'G', "0000" to 'H', "00" to 'I', "0111" to 'J',
"101" to 'K', "0100" to 'L', "11" to 'M', "10" to 'N', "111" to 'O',
"0110" to 'P', "1101" to 'Q', "010" to 'R', "000" to 'S', "1" to 'T',
"001" to 'U', "0001" to 'V', "011" to 'W', "1001" to 'X', "1011" to 'Y',
"1100" to 'Z', "01111" to '1', "00111" to '2', "00011" to '3',
"00001" to '4', "00000" to '5', "10000" to '6', "11000" to '7',
"11100" to '8', "11110" to '9', "11111" to '0',
"010101" to '.', "110011" to ',', "001100" to '?', "011110" to '\'',
"101011" to '!', "10010" to '/', "10110" to '(', "101101" to ')',
"01000" to '&', "111000" to ':', "101010" to ';', "10001" to '=',
"01010" to '+', "100001" to '-', "001101" to '_', "010010" to '"',
"0001001" to '$', "011010" to '@'
)
fun morseToChar(morse: String): Char? = MORSE_TABLE[morse]
}
}
data class ToneResult(val symbol: Char?, val probability: Float)
@@ -0,0 +1,114 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Multi-channel CW signal tracker.
* Monitors the spectrogram for active frequency bins and extracts
* energy envelopes for each detected signal.
*
* Inspired by CW Skimmer's multi-channel approach:
* tracks all active signals in the passband simultaneously,
* selects the best one for decoded output.
*/
internal class CwChannelTracker(
private val spectrogram: CwSpectrogram,
private val maxChannels: Int = 3
) {
data class Channel(
val bin: Int,
val frequency: Float,
var active: Boolean = false,
var energy: Float = 0f,
val history: MutableList<Float> = mutableListOf(),
var confidence: Float = 0f
)
private val channels = Array(maxChannels) { Channel(0, 0f) }
/** Scan the current spectrogram column and update channel tracking. */
fun update(): List<Channel> {
val col = spectrogram.getCurrentColumn()
val peaks = findPeaks(col, threshold = 0.3f, minDistance = 2)
// Update existing channels
for (ch in channels) {
if (ch.active) {
if (peaks.contains(ch.bin)) {
ch.energy = col[ch.bin]
ch.history.add(ch.energy)
if (ch.history.size > 40) ch.history.removeAt(0)
ch.confidence = computeConfidence(ch.history)
} else {
// Signal lost — decay confidence
ch.history.add(0f)
if (ch.history.size > 40) ch.history.removeAt(0)
ch.confidence *= 0.9f
if (ch.confidence < 0.1f) ch.active = false
}
}
}
// Assign new peaks to inactive channels
var peakIdx = 0
for (ch in channels) {
if (!ch.active && peakIdx < peaks.size) {
val bin = peaks[peakIdx]
val freq = spectrogram.binToFreq(bin)
// Re-initialize channel
channels[peakIdx] = Channel(bin, freq, true, col[bin], mutableListOf(), 0.5f)
peakIdx++
}
}
return channels.filter { it.active }
}
/** Find peak bins in the spectrum. */
private fun findPeaks(spectrum: FloatArray, threshold: Float, minDistance: Int): List<Int> {
val peaks = mutableListOf<Int>()
for (i in 1 until spectrum.size - 1) {
if (spectrum[i] > spectrum[i - 1] && spectrum[i] > spectrum[i + 1] && spectrum[i] > threshold) {
if (peaks.isEmpty() || i - peaks.last() >= minDistance) {
peaks.add(i)
}
}
}
return peaks.sortedByDescending { spectrum[it] }
}
/** Compute confidence from energy history. Lower variance = higher confidence. */
private fun computeConfidence(history: List<Float>): Float {
if (history.size < 10) return 0.3f
val recent = history.takeLast(10)
val mean = recent.average().toFloat()
val variance = recent.map { (it - mean) * (it - mean) }.average().toFloat()
return if (mean > 0f) (mean / (mean + variance + 0.1f)).coerceIn(0f, 1f) else 0f
}
/** Get the channel with highest confidence. */
fun getBestChannel(): Channel? {
return channels.filter { it.active }.maxByOrNull { it.confidence }
}
fun reset() {
for (i in channels.indices) {
channels[i] = Channel(0, 0f)
}
}
}
@@ -1,61 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Turns the model's `log_probs` output into text.
*
* Mirrors the reference `greedy_ctc_decode`: take the best class per frame,
* drop blanks, and collapse runs of the same label. A blank between two
* identical labels is what keeps a genuine double letter (for example the
* two N's in "5NN") from collapsing into one.
*/
object CwCtcDecoder {
/**
* @param logProbs `[batch, time, class]`; only batch 0 is read.
* @param chars class index to symbol, excluding the blank.
* @param blankIndex the CTC blank class (41 for this model).
*/
fun greedy(
logProbs: Array<Array<FloatArray>>,
chars: List<String>,
blankIndex: Int
): String {
if (logProbs.isEmpty()) return ""
val frames = logProbs[0]
val builder = StringBuilder()
var previous = -1
for (frame in frames) {
var best = 0
for (i in 1 until frame.size) {
if (frame[i] > frame[best]) best = i
}
if (best == blankIndex) {
previous = -1
continue
}
if (best != previous && best < chars.size) {
builder.append(chars[best])
}
previous = best
}
return builder.toString()
}
}
@@ -0,0 +1,165 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* CW (Morse code) decoder v3 — Spectrogram-based multi-channel Bayesian decoder.
*
* Architecture inspired by Morse Expert / CW Skimmer (VE3NEA):
* 1. FFT spectrogram creates a frequency×time matrix
* 2. Multi-channel peak detector finds all active signals
* 3. Per-channel energy envelope extraction
* 4. Bayesian probability for symbol timing (Gaussian likelihood)
* 5. Best channel selected for output
*
* Timing analysis is performed per spectrogram column (hop).
* Each column represents hopSize/sampleRate seconds of audio.
*/
class CwDecoder(
val sampleRate: Int = 8000,
cwToneFreq: Float = -1f // ignored in v3 (auto-detect via spectrogram)
) {
companion object {
private const val FFT_SIZE = 256
private const val HOP_SIZE = 64
}
private val spectrogram = CwSpectrogram(
fftSize = FFT_SIZE,
hopSize = HOP_SIZE,
sampleRate = sampleRate,
minBin = 6,
maxBin = 38,
historyCols = 40
)
private val channelTracker = CwChannelTracker(spectrogram, maxChannels = 3)
private val bayesianDecoder = CwBayesianDecoder()
// Timing state per channel
private data class ChannelTiming(
var isSignal: Boolean = false,
var toneTicks: Int = 0,
var gapTicks: Int = 0
)
private val timingStates = Array(3) { ChannelTiming() }
// Time per spectrogram column in milliseconds
private val tickMs = 1000f * HOP_SIZE / sampleRate
// Output flows
private val _decodedTextFlow = MutableStateFlow("")
val decodedTextFlow: StateFlow<String> = _decodedTextFlow
private val _signalStrength = MutableStateFlow(0f)
val signalStrength: StateFlow<Float> = _signalStrength
private val _estimatedPitch = MutableStateFlow<Float?>(null)
val estimatedPitch: StateFlow<Float?> = _estimatedPitch
private val _estimatedSpeed = MutableStateFlow<Float?>(null)
val estimatedSpeed: StateFlow<Float?> = _estimatedSpeed
private var frameCount = 0
init {
if (cwToneFreq > 0f) {
_estimatedPitch.value = cwToneFreq
}
}
fun processBuffer(buffer: FloatArray) {
// 1. Feed samples to spectrogram
spectrogram.addSamples(buffer)
// 2. Get number of new columns generated
val newCols = spectrogram.getNewColumns()
if (newCols == 0) return
// 3. Update channel tracker (uses latest column for peak detection)
val activeChannels = channelTracker.update()
// 4. Process each new column for timing analysis
// Columns are indexed 0..historyCols-1, where historyCols-1 is the newest
val baseIdx = (spectrogram.historyCols - newCols).coerceAtLeast(0)
for (colOffset in 0 until newCols) {
val col = spectrogram.getColumn(baseIdx + colOffset)
for ((idx, channel) in activeChannels.withIndex()) {
if (idx >= timingStates.size) break
val state = timingStates[idx]
val energy = if (channel.bin in col.indices) col[channel.bin] else 0f
// Adaptive threshold
val threshold = 0.3f + (energy - 0.3f) * 0.3f
if (energy > threshold) {
if (!state.isSignal) {
if (state.gapTicks > 0) {
val gapMs = state.gapTicks * tickMs
bayesianDecoder.processGap(gapMs)
}
state.gapTicks = 0
state.isSignal = true
}
state.toneTicks++
} else {
if (state.isSignal) {
if (state.toneTicks > 0) {
val toneMs = state.toneTicks * tickMs
bayesianDecoder.processTone(toneMs)
}
state.toneTicks = 0
state.isSignal = false
}
state.gapTicks++
}
}
}
// 5. Update outputs
frameCount++
if (frameCount % 5 == 0) {
val bestChannel = channelTracker.getBestChannel()
if (bestChannel != null) {
_estimatedPitch.value = bestChannel.frequency
_signalStrength.value = bestChannel.confidence
_estimatedSpeed.value = bayesianDecoder.getSpeed()
}
_decodedTextFlow.value = bayesianDecoder.decodedText
}
}
fun resetDecoder() {
spectrogram.reset()
channelTracker.reset()
bayesianDecoder.reset()
for (state in timingStates) {
state.isSignal = false
state.toneTicks = 0
state.gapTicks = 0
}
frameCount = 0
_decodedTextFlow.value = ""
_signalStrength.value = 0f
_estimatedPitch.value = null
_estimatedSpeed.value = null
}
}
@@ -1,140 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Bounded rolling audio buffer that drives periodic full re-decodes.
*
* DeepCW is a whole-segment CTC model. It rewrites earlier output as more
* context arrives — measured on one clip, 6 of 11 progressively longer reads
* revised the prefix (`BM` -> `BG7` -> `BG7NTI` -> `BG7NTA`). Appending only
* the newest fragment therefore leaves those intermediate guesses on screen
* forever; measured character error rate for sliding-window stitching ranged
* from 67% to 294%, against 0% for decoding the whole segment at once.
*
* So we keep a fixed window, re-run the model over all of it every
* [redecodeIntervalMs], and replace the displayed text outright.
*
* Defaults come from measurement: 20 s is the smallest window that reaches
* 0.0% CER (16 s still errs at 5.9%), while inference cost grows
* super-linearly — 60 s of audio needs roughly 13x longer to decode than
* 20 s does, leaving too little real-time headroom.
*/
class CwDeepBuffer(
sampleRate: Int = CwDeepSpectrogram.SAMPLE_RATE,
maxSeconds: Double = DEFAULT_MAX_SECONDS,
private val redecodeIntervalMs: Int = DEFAULT_REDECODE_INTERVAL_MS
) {
companion object {
const val DEFAULT_MAX_SECONDS = 20.0
const val DEFAULT_REDECODE_INTERVAL_MS = 1500
}
/** Maximum number of samples retained. */
val capacity: Int = (sampleRate * maxSeconds).toInt()
private val samplesPerInterval: Int = sampleRate * redecodeIntervalMs / 1000
private val ring = FloatArray(capacity)
private var writeIndex = 0
private var filled = 0
private var sinceLastRedecode = 0
/**
* Samples evicted from the ring once it is full. They are the audio that
* has scrolled out of the 20 s window, and are handed off (via
* [drainOverflow]) so the decoder can archive them into permanent history
* instead of silently dropping the corresponding text. Pre-allocated to
* [capacity]: overflow never exceeds one window before it is drained.
*/
private val overflow = FloatArray(capacity)
private var overflowSize = 0
/** Samples currently buffered, never above [capacity]. */
val size: Int get() = filled
/** Samples currently held in the overflow (awaiting archival). */
val overflowCount: Int get() = overflowSize
/** True once there is enough audio for the spectrogram to yield a frame. */
val hasEnoughAudio: Boolean get() = filled >= CwDeepSpectrogram.FFT_LENGTH
/**
* Append captured audio, overwriting the oldest samples when full.
*
* @return true when [redecodeIntervalMs] of audio has accumulated since
* the last time this returned true, meaning the caller should re-decode.
*/
fun append(chunk: FloatArray): Boolean {
if (chunk.isNotEmpty()) {
// A chunk longer than the window can only contribute its tail.
val start = maxOf(0, chunk.size - capacity)
for (i in start until chunk.size) {
if (filled == capacity) {
// The slot we are about to overwrite holds the oldest
// sample — move it to the overflow for archival.
overflow[overflowSize++] = ring[writeIndex]
}
ring[writeIndex] = chunk[i]
writeIndex = (writeIndex + 1) % capacity
if (filled < capacity) filled++
}
}
sinceLastRedecode += chunk.size
if (sinceLastRedecode >= samplesPerInterval) {
sinceLastRedecode -= samplesPerInterval
return true
}
return false
}
/** Buffered audio in chronological order, as a copy safe to hand off. */
fun snapshot(): FloatArray {
val out = FloatArray(filled)
if (filled == 0) return out
val start = (writeIndex - filled + capacity) % capacity
val firstRun = minOf(filled, capacity - start)
ring.copyInto(out, 0, start, start + firstRun)
if (firstRun < filled) {
ring.copyInto(out, firstRun, 0, filled - firstRun)
}
return out
}
/**
* Return the evicted samples (chronological order) and clear the overflow.
* Safe to call every append; returns an empty array when nothing has been
* evicted yet.
*/
fun drainOverflow(): FloatArray {
if (overflowSize == 0) return FloatArray(0)
val out = overflow.copyOf(overflowSize)
overflowSize = 0
return out
}
/** Drop all audio (including pending overflow) and restart the interval. */
fun reset() {
writeIndex = 0
filled = 0
sinceLastRedecode = 0
overflowSize = 0
ring.fill(0f)
overflow.fill(0f)
}
}
@@ -1,208 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.ln1p
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Audio front-end for the DeepCW model: turns PCM samples into the
* `[time, frequency]` log-magnitude spectrogram the network expects.
*
* Mirrors the upstream Python reference (deepcw-engine
* `examples/python/decode_morse.py`) step for step:
*
* resample -> 3200 Hz, reflect-pad by fft/2, periodic Hann window of 256,
* real FFT, keep bins [32, 97) i.e. 400-1200 Hz, then log1p.
*
* The model's fixed 400-1200 Hz window means pitch detection is built in —
* no spectral peak tracking or squelch gating is needed on our side.
*/
object CwDeepSpectrogram {
/** Model input sample rate, from `model.onnx.json`. */
const val SAMPLE_RATE = 3200
/** FFT window length in samples. */
const val FFT_LENGTH = 256
/** Hop between consecutive frames; 48/3200 = 15.0 ms per frame. */
const val HOP_LENGTH = 48
private const val MIN_FREQ_HZ = 400.0
private const val MAX_FREQ_HZ = 1200.0
/** Number of frequency bins the model expects. */
const val FREQUENCY_BINS = 65
/** Milliseconds of audio represented by one output frame. */
const val MS_PER_FRAME = 1000.0 * HOP_LENGTH / SAMPLE_RATE
private val hannWindow: FloatArray = FloatArray(FFT_LENGTH) { i ->
// numpy: np.hanning(N + 1)[:-1] — the periodic (not symmetric) variant.
(0.5 - 0.5 * cos(2.0 * PI * i / FFT_LENGTH)).toFloat()
}
/**
* Inclusive-exclusive bin range covering [minHz, maxHz].
* Returns `start to stop`, matching the reference's `frequency_bin_range`.
*/
fun frequencyBinRange(
sampleRate: Int,
fftLength: Int,
minHz: Double,
maxHz: Double
): Pair<Int, Int> {
val binHz = sampleRate.toDouble() / fftLength
val start = ceil(minHz / binHz).toInt()
val stop = floor(maxHz / binHz).toInt() + 1
return start to stop
}
/**
* Linear-interpolation resampler. Deliberately dependency-light and
* identical to the reference implementation so spectrograms match.
*/
fun resampleLinear(audio: FloatArray, sourceRate: Int, targetRate: Int): FloatArray {
if (sourceRate == targetRate || audio.isEmpty()) return audio
val targetLength = (audio.size.toDouble() * targetRate / sourceRate).roundToInt()
val out = FloatArray(targetLength)
val ratio = sourceRate.toDouble() / targetRate
for (i in 0 until targetLength) {
val position = i * ratio
val left = floor(position).toInt()
val right = minOf(left + 1, audio.size - 1)
val fraction = (position - left).toFloat()
out[i] = audio[left] * (1f - fraction) + audio[right] * fraction
}
return out
}
/**
* Build the log-magnitude spectrogram. Input must already be at
* [SAMPLE_RATE]; use [resampleLinear] first when it is not.
*
* @return `[frames][FREQUENCY_BINS]` values, all non-negative.
*/
fun compute(audio: FloatArray): Array<FloatArray> {
require(audio.size >= FFT_LENGTH) {
"audio is too short for fftLength=$FFT_LENGTH, got ${audio.size}"
}
val (startBin, stopBin) = frequencyBinRange(
SAMPLE_RATE, FFT_LENGTH, MIN_FREQ_HZ, MAX_FREQ_HZ
)
val bins = stopBin - startBin
require(bins == FREQUENCY_BINS) {
"expected $FREQUENCY_BINS bins, computed $bins"
}
val padded = reflectPad(audio, FFT_LENGTH / 2)
val frames = 1 + (padded.size - FFT_LENGTH) / HOP_LENGTH
val result = Array(frames) { FloatArray(bins) }
val real = FloatArray(FFT_LENGTH)
val imag = FloatArray(FFT_LENGTH)
for (frame in 0 until frames) {
val offset = frame * HOP_LENGTH
for (i in 0 until FFT_LENGTH) {
real[i] = padded[offset + i] * hannWindow[i]
imag[i] = 0f
}
fftInPlace(real, imag)
val row = result[frame]
for (bin in startBin until stopBin) {
val magnitude = sqrt(real[bin] * real[bin] + imag[bin] * imag[bin])
row[bin - startBin] = ln1p(magnitude.toDouble()).toFloat()
}
}
return result
}
/**
* numpy `mode="reflect"`: mirrors around the edge samples without
* repeating them, so [1,2,3] padded by 2 becomes [3,2,1,2,3,2,1].
*/
private fun reflectPad(audio: FloatArray, pad: Int): FloatArray {
if (pad == 0) return audio
val out = FloatArray(audio.size + 2 * pad)
for (i in 0 until pad) out[i] = audio[pad - i]
audio.copyInto(out, pad)
val last = audio.size - 1
for (i in 0 until pad) out[pad + audio.size + i] = audio[last - 1 - i]
return out
}
/**
* Iterative radix-2 Cooley-Tukey FFT. [FFT_LENGTH] is a power of two, so
* no padding case is needed. Only the first half of the output is read by
* [compute], which is the real-input equivalent of numpy's `rfft`.
*/
private fun fftInPlace(real: FloatArray, imag: FloatArray) {
val n = real.size
// Bit-reversal permutation.
var j = 0
for (i in 1 until n) {
var bit = n shr 1
while (j and bit != 0) {
j = j xor bit
bit = bit shr 1
}
j = j or bit
if (i < j) {
var tmp = real[i]; real[i] = real[j]; real[j] = tmp
tmp = imag[i]; imag[i] = imag[j]; imag[j] = tmp
}
}
var length = 2
while (length <= n) {
val angle = -2.0 * PI / length
val wReal = cos(angle).toFloat()
val wImag = kotlin.math.sin(angle).toFloat()
var i = 0
while (i < n) {
var curReal = 1f
var curImag = 0f
for (k in 0 until length / 2) {
val evenReal = real[i + k]
val evenImag = imag[i + k]
val oddReal = real[i + k + length / 2]
val oddImag = imag[i + k + length / 2]
val mulReal = oddReal * curReal - oddImag * curImag
val mulImag = oddReal * curImag + oddImag * curReal
real[i + k] = evenReal + mulReal
imag[i + k] = evenImag + mulImag
real[i + k + length / 2] = evenReal - mulReal
imag[i + k + length / 2] = evenImag - mulImag
val nextReal = curReal * wReal - curImag * wImag
curImag = curReal * wImag + curImag * wReal
curReal = nextReal
}
i += length
}
length = length shl 1
}
}
}
@@ -0,0 +1,102 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
/**
* DSP utilities for CW (Morse code) decoding.
* Pure Kotlin, no NDK required.
*/
internal object CwDsp {
/**
* Design a simple bandpass FIR filter coefficients using windowed sinc method.
* @param lowCutoff lower cutoff frequency (Hz) as fraction of sampleRate
* @param highCutoff upper cutoff frequency (Hz) as fraction of sampleRate
* @param taps filter length (must be odd)
*/
fun bandpassFir(lowCutoff: Double, highCutoff: Double, taps: Int): FloatArray {
val n = if (taps % 2 == 0) taps + 1 else taps
val half = n / 2
val coeffs = FloatArray(n)
for (i in 0 until n) {
val idx = i - half
if (idx == 0) {
coeffs[i] = (2.0 * (highCutoff - lowCutoff)).toFloat()
} else {
val x = PI * idx
coeffs[i] = ((sin(2 * highCutoff * x) - sin(2 * lowCutoff * x)) / x).toFloat()
}
// Hamming window
coeffs[i] = (coeffs[i] * (0.54 - 0.46 * cos(2 * PI * i / (n - 1)))).toFloat()
}
// Normalize
val sum = coeffs.sum()
if (sum != 0f) for (i in 0 until n) coeffs[i] /= sum
return coeffs
}
/** Apply FIR filter to a buffer. */
fun applyFir(buffer: FloatArray, coeffs: FloatArray): FloatArray {
val out = FloatArray(buffer.size)
for (i in buffer.indices) {
var sum = 0f
for (j in coeffs.indices) {
val idx = i - j
if (idx >= 0) sum += buffer[idx] * coeffs[j]
}
out[i] = sum
}
return out
}
/** Simple envelope detector: abs + low-pass smoothing. */
fun envelope(signal: FloatArray, alpha: Float = 0.1f): FloatArray {
val env = FloatArray(signal.size)
var s = 0f
for (i in signal.indices) {
s = alpha * kotlin.math.abs(signal[i]) + (1 - alpha) * s
env[i] = s
}
return env
}
/** Estimate noise floor from envelope for adaptive thresholding. */
fun noiseFloor(env: FloatArray, fraction: Float = 0.3f): Float {
val sorted = env.sortedArray()
val median = sorted[sorted.size / 2]
return median + (sorted[sorted.size * 9 / 10] - median) * fraction
}
/** Simple Goertzel to detect a specific tone frequency. */
fun goertzel(buffer: FloatArray, targetFreq: Float, sampleRate: Int): Float {
val omega = 2.0 * PI * targetFreq / sampleRate
val coeff = 2.0 * cos(omega)
var s0 = 0.0; var s1 = 0.0; var s2 = 0.0
for (sample in buffer) {
s0 = sample.toDouble() + coeff * s1 - s2
s2 = s1; s1 = s0
}
val power = s2 * s2 + s1 * s1 - coeff * s1 * s2
return sqrt(kotlin.math.abs(power)).toFloat()
}
}
@@ -0,0 +1,87 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.cos
import kotlin.math.sqrt
/**
* Radix-2 FFT for real-valued input.
* Produces magnitude spectrum for the first N/2+1 bins.
* Used by CwSpectrogram for time-frequency analysis.
*/
internal class CwFFT(private val n: Int) {
init {
require(n > 0 && n and (n - 1) == 0) { "FFT size must be power of 2, got $n" }
}
private val cosTable = FloatArray(n / 2)
private val sinTable = FloatArray(n / 2)
init {
for (i in 0 until n / 2) {
val angle = -2.0 * kotlin.math.PI * i / n
cosTable[i] = cos(angle).toFloat()
sinTable[i] = kotlin.math.sin(angle).toFloat()
}
}
/** Compute magnitude spectrum for real input. Returns array of size n/2+1. */
fun magnitudeSpectrum(input: FloatArray): FloatArray {
require(input.size == n) { "Input size must be $n, got ${input.size}" }
val real = input.copyOf()
val imag = FloatArray(n)
// Bit-reversal permutation
var j = 0
for (i in 1 until n) {
var bit = n shr 1
while (j and bit != 0) { j = j xor bit; bit = bit shr 1 }
j = j xor bit
if (i < j) {
var tmp = real[i]; real[i] = real[j]; real[j] = tmp
}
}
// Radix-2 Cooley-Tukey FFT
var len = 2
while (len <= n) {
val half = len / 2
val step = n / len
for (i in 0 until n step len) {
for (k in 0 until half) {
val tReal = real[i + k + half] * cosTable[k * step] - imag[i + k + half] * sinTable[k * step]
val tImag = real[i + k + half] * sinTable[k * step] + imag[i + k + half] * cosTable[k * step]
real[i + k + half] = real[i + k] - tReal
imag[i + k + half] = imag[i + k] - tImag
real[i + k] += tReal
imag[i + k] += tImag
}
}
len = len shl 1
}
// Magnitude spectrum (first N/2+1 bins)
val mag = FloatArray(n / 2 + 1)
for (i in 0..n / 2) {
mag[i] = sqrt(real[i] * real[i] + imag[i] * imag[i]) / n
}
return mag
}
}
@@ -0,0 +1,139 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.sin
/**
* FFT lowpass/bandpass filter with overlap-add, ported from fldigi
* fftfilt.cxx (fftfilt class). Used by the CW decoder for the
* matched receive filter.
*/
internal class CwFftFilt(f1: Double, f2: Double, len: Int) {
private val flen: Int
private val flen2: Int
private val fft: CwGfft
private val filter: Array<CwComplex>
private val timedata: Array<CwComplex>
private val freqdata: Array<CwComplex>
private val output: Array<CwComplex>
private val ovlbuf: Array<CwComplex>
private var inptr = 0
private var pass = 0
init {
flen = len
flen2 = flen shr 1
fft = CwGfft(flen)
filter = Array(flen) { CwComplex() }
timedata = Array(flen) { CwComplex() }
freqdata = Array(flen) { CwComplex() }
output = Array(flen) { CwComplex() }
ovlbuf = Array(flen2) { CwComplex() }
createFilter(f1, f2)
}
constructor(f: Double, len: Int) : this(0.0, f, len)
fun flushSize(): Int = flen - inptr
/**
* f1 < f2 ==> bandpass; f1 > f2 ==> band reject; f1 == 0 ==> lowpass; f2 == 0 ==> highpass.
*/
private fun createFilter(f1: Double, f2: Double) {
for (i in 0 until flen) {
filter[i] = CwComplex()
}
val bLowpass = f2 != 0.0
val bHighpass = f1 != 0.0
for (i in 0 until flen2) {
var h = 0.0
if (bLowpass) h += fsinc(f2, i, flen2)
if (bHighpass) h -= fsinc(f1, i, flen2)
if (bHighpass && f2 < f1 && i == flen2 / 2) h += 1.0
filter[i] = CwComplex(h * blackman(i, flen2), 0.0)
}
// forward FFT of the impulse response
fft.forward(filter)
// normalize unity gain
var scale = 0.0
for (i in 0 until flen2) {
val mag = kotlin.math.sqrt(filter[i].re * filter[i].re + filter[i].im * filter[i].im)
if (mag > scale) scale = mag
}
if (scale != 0.0) {
for (i in 0 until flen) {
filter[i] = CwComplex(filter[i].re / scale, filter[i].im / scale)
}
}
pass = 1
}
fun createLpf(f: Double) = createFilter(0.0, f)
private fun fsinc(fc: Double, i: Int, len: Int): Double {
val mid = len / 2
return if (i == mid) 2.0 * fc
else sin(2.0 * PI * fc * (i - mid)) / (PI * (i - mid))
}
private fun blackman(i: Int, len: Int): Double =
0.42 - 0.50 * cos(2.0 * PI * i / len) + 0.08 * cos(4.0 * PI * i / len)
/**
* Feed one complex input sample. Returns output array + count when flen/2
* samples are ready, otherwise null.
*/
fun run(input: CwComplex): Array<CwComplex>? {
timedata[inptr++] = input
if (inptr < flen2) return null
if (pass > 0) pass--
// copy to freq domain and FFT
for (i in 0 until flen) {
freqdata[i] = timedata[i]
}
fft.forward(freqdata)
// multiply by filter shape
for (i in 0 until flen) {
val f = filter[i]
val t = freqdata[i]
freqdata[i] = CwComplex(t.re * f.re - t.im * f.im, t.re * f.im + t.im * f.re)
}
// inverse FFT
fft.inverse(freqdata)
// overlap-add: first half is valid output, save second half
for (i in 0 until flen2) {
output[i] = CwComplex(ovlbuf[i].re + freqdata[i].re, ovlbuf[i].im + freqdata[i].im)
ovlbuf[i] = freqdata[i + flen2]
}
inptr = 0
if (pass > 0) return null
return output
}
}
@@ -15,32 +15,34 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.data.cw
import android.content.Context
import android.util.Log
package com.rtbishop.look4sat.core.domain.cw
/**
* Minimal crash-probe logger for diagnosing crashes that produce no Java
* stack trace (native faults, low-memory kills). Each step appends one line
* to `files/probe_cw.txt`; if the process dies mid-way the last line shows
* exactly where. No adb or logcat required.
* First-order IIR filters.
* Ported from ggmorse/src/filter.h
*/
internal object CwProbe {
internal class CwFilter {
private var z1 = 0f
private var dir: java.io.File? = null
fun init(context: Context) {
dir = context.filesDir
companion object {
private const val PI_F = 3.141592653589793f
}
fun step(label: String) {
val target = dir ?: return
runCatching {
val line = "${System.currentTimeMillis()} $label"
val file = java.io.File(target, "probe_cw.txt")
file.appendText("$line\n")
Log.i("CwProbe", line)
}
fun highPass(sample: Float, cutoffHz: Float, sampleRate: Float): Float {
val rc = 1.0f / (2f * PI_F * cutoffHz)
val dt = 1.0f / sampleRate
val alpha = dt / (rc + dt)
z1 = alpha * (z1 + sample - z1)
return sample - z1
}
fun lowPass(sample: Float, cutoffHz: Float, sampleRate: Float): Float {
val rc = 1.0f / (2f * PI_F * cutoffHz)
val dt = 1.0f / sampleRate
val alpha = dt / (rc + dt)
z1 += alpha * (sample - z1)
return z1
}
fun reset() { z1 = 0f }
}
@@ -0,0 +1,530 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlin.math.abs
import kotlin.math.log10
import kotlin.math.roundToInt
/**
* CW decoder ported from fldigi (w1hkj/fldigi) cw.cxx — full receive
* chain: NCO down-conversion, FFT lowpass filter, decimation, AGC,
* hysteresis keying detection, element timing state machine, adaptive
* speed tracking, SOM codebook matching and morse table lookup.
*
* Drop-in replacement for the reverse-engineered Morse Expert decoder:
* same processBuffer(FloatArray) entry point, same StateFlow outputs.
*/
class CwFldigiDecoder(
val sampleRate: Int = CwFldigiConstants.CW_SAMPLERATE,
private val frequency: Double = 600.0,
private val useSom: Boolean = true,
private val initialWpm: Int = CwFldigiConstants.DEFAULT_SPEED
) {
private companion object {
const val CW_DOT = '.'
const val CW_DASH = '-'
const val CW_RESET = 0
const val CW_KEYDOWN = 1
const val CW_KEYUP = 2
const val CW_QUERY = 3
const val CW_SUCCESS = 0
const val CW_ERROR = -1
// Auto-tune (spectral peak tracking, mirrors the old channelTracker)
const val TUNE_FFT_SIZE = 512
const val TUNE_MIN_FREQ = 300.0
const val TUNE_MAX_FREQ = 1500.0
const val TUNE_ENERGY_FRACTION = 0.35
}
private enum class CwRxState { IDLE, IN_TONE, AFTER_TONE }
// Outputs (API-compatible with the old CwDecoder)
private val _decodedTextFlow = MutableStateFlow("")
val decodedTextFlow: StateFlow<String> = _decodedTextFlow
private val _signalStrength = MutableStateFlow(0f)
val signalStrength: StateFlow<Float> = _signalStrength
private val _estimatedPitch = MutableStateFlow<Float?>(frequency.toFloat())
val estimatedPitch: StateFlow<Float?> = _estimatedPitch
private val _estimatedSpeed = MutableStateFlow<Float?>(null)
val estimatedSpeed: StateFlow<Float?> = _estimatedSpeed
// --- auto-tune state (spectral peak tracking) ---
private var tuneFreq = frequency
private val tuneBuffer = DoubleArray(TUNE_FFT_SIZE)
private var tuneIdx = 0
private var tuneFft = CwGfft(TUNE_FFT_SIZE)
private var tunePeakFreq = frequency
private var tuneHasPeak = false
private var tuneLocked = false
private val tuneWindow = DoubleArray(TUNE_FFT_SIZE)
// --- fldigi cw state ---
private var phaseacc = 0.0
private var FFTphase = 0.0
private var FFTvalue = 0.0
private var smpl_ctr = 0
private var agc_peak = 1.0
private var noise_floor = 1.0
private var sig_avg = 0.0
private var metric = 0.0
private var siglevel = 0.0
private var upper_threshold = CwFldigiConstants.CW_UPPER_THRESHOLD
private var lower_threshold = CwFldigiConstants.CW_LOWER_THRESHOLD
private val cw_FFT_filter: CwFftFilt
private val bitfilter: CwMovAvg
private val trackingfilter: CwMovAvg
private var cw_receive_state = CwRxState.IDLE
private var old_cw_receive_state = CwRxState.IDLE
private var cw_rr_start_timestamp = 0
private var cw_rr_end_timestamp = 0
private var rx_rep_buf = StringBuilder()
private var cw_ptr = 0
private val cw_buffer = FloatArray(CwFldigiConstants.MAX_MORSE_ELEMENTS + 1)
private var cw_speed = initialWpm
private var cw_send_speed = initialWpm
private var cw_receive_speed = initialWpm
private var cw_bandwidth = CwFldigiConstants.DEFAULT_BANDWIDTH
private var cwTrack = true
private var two_dots = 0L
private var last_element = 0
private var space_sent = true
private var cw_noise_spike_threshold = 0L
private var cw_receive_dot_length = 0L
private var cw_receive_dash_length = 0L
private var synchscope = 50
init {
val bw = cw_bandwidth.toDouble() / sampleRate
cw_FFT_filter = CwFftFilt(bw, CwFldigiConstants.CW_FFT_SIZE)
val bfv = (symbollen() / (2 * CwFldigiConstants.DEC_RATIO)).coerceAtLeast(1)
bitfilter = CwMovAvg(bfv)
trackingfilter = CwMovAvg(CwFldigiConstants.TRACKING_FILTER_SIZE)
two_dots = (2 * CwFldigiConstants.KWPM / cw_speed).toLong()
cw_noise_spike_threshold = two_dots / 4
cw_receive_dot_length = (CwFldigiConstants.KWPM / cw_receive_speed).toLong()
cw_receive_dash_length = 3 * cw_receive_dot_length
}
private fun symbollen(): Int =
(sampleRate * 1.2 / cw_speed).roundToInt()
private fun usecDiff(earlier: Int, later: Int): Int =
if (earlier >= later) 0 else later - earlier
/** Main entry: feed PCM samples. */
fun processBuffer(buffer: FloatArray) {
for (sample in buffer) {
feedTuner(sample.toDouble())
rxSample(sample.toDouble())
}
}
/**
* Spectral peak tracking (auto-tune). Collects raw samples, runs an FFT
* every TUNE_FFT_SIZE samples, finds the strongest peak in the CW range
* and smoothly steers tuneFreq toward it — mirroring the old
* channelTracker behaviour so off-tune signals still decode.
*/
private fun feedTuner(sample: Double) {
tuneBuffer[tuneIdx++] = sample
if (tuneIdx < TUNE_FFT_SIZE) return
tuneIdx = 0
// Hann window
for (i in 0 until TUNE_FFT_SIZE) {
val w = 0.5 - 0.5 * kotlin.math.cos(2.0 * Math.PI * i / (TUNE_FFT_SIZE - 1))
tuneWindow[i] = tuneBuffer[i] * w
}
val data = Array(TUNE_FFT_SIZE) { CwComplex(tuneWindow[it], 0.0) }
tuneFft.forward(data)
// Find the strongest bin in the CW range (300..1500 Hz)
val binMin = (TUNE_MIN_FREQ * TUNE_FFT_SIZE / sampleRate).toInt()
val binMax = (TUNE_MAX_FREQ * TUNE_FFT_SIZE / sampleRate).toInt()
var bestBin = -1
var bestMag = 0.0
var totalMag = 0.0
for (b in binMin..binMax) {
val mag = data[b].abs()
totalMag += mag
if (mag > bestMag) {
bestMag = mag
bestBin = b
}
}
if (bestBin < 0) return
val meanMag = totalMag / (binMax - binMin + 1)
if (bestMag < meanMag * 2.0) return // no clear tone
// Absolute floor: silence or weak noise must not steer the NCO.
// A 0.6-amplitude tone in a 512-pt Hann FFT yields peak ≈ 150;
// anything below ~30 is noise/DC leakage.
if (bestMag < 30.0) return
val peakFreq = bestBin * sampleRate.toDouble() / TUNE_FFT_SIZE
tunePeakFreq = peakFreq
tuneHasPeak = true
_estimatedPitch.value = peakFreq.toFloat()
// Lock fast: a strong peak on the very first frame is reliable enough
// (CW tones are narrow and dominate the band). Steer immediately so
// the first character still decodes. Do NOT reset the RX state on the
// first lock — the AGC adapts in a few frames and a reset would wipe
// the element that triggered the tune.
if (!tuneLocked) {
tuneFreq = peakFreq
tuneLocked = true
_estimatedPitch.value = peakFreq.toFloat()
} else {
// Smooth tracking; retune instantly on big jumps (signal switched freq)
val diff = peakFreq - tuneFreq
if (kotlin.math.abs(diff) > 120.0) {
tuneFreq = peakFreq
resetRxState()
} else {
tuneFreq += diff * 0.2
}
}
}
/** Reset only the fldigi RX state machine (keep decoded text). */
private fun resetRxState() {
cw_receive_state = CwRxState.IDLE
old_cw_receive_state = CwRxState.IDLE
smpl_ctr = 0
cw_ptr = 0
rx_rep_buf.clear()
last_element = 0
space_sent = true
FFTphase = 0.0
phaseacc = 0.0
}
private fun rxSample(value: Double) {
// NCO down-conversion (fldigi rx_FFTprocess). tuneFreq tracks the
// strongest spectral peak so off-tune signals still decode.
val z = CwComplex(
value * kotlin.math.cos(FFTphase),
value * kotlin.math.sin(FFTphase)
)
FFTphase += 2.0 * Math.PI * tuneFreq / sampleRate
if (FFTphase > 2.0 * Math.PI) FFTphase -= 2.0 * Math.PI
val out = cw_FFT_filter.run(z) ?: return
for (i in 0 until CwFldigiConstants.CW_FFT_SIZE / 2) {
++smpl_ctr
if (smpl_ctr % CwFldigiConstants.DEC_RATIO != 0) continue
FFTvalue = out[i].abs()
FFTvalue = bitfilter.run(FFTvalue)
decodeStream(FFTvalue)
}
}
/**
* AGC + hysteresis detection (fldigi cw::decode_stream).
*/
private fun decodeStream(value: Double) {
var v = value
val attack: Int
val decay: Int
when (CwFldigiConstants.CWRX_ATTACK_DEFAULT) {
0 -> attack = 400
2 -> attack = 100
else -> attack = 200
}
when (CwFldigiConstants.CWRX_DECAY_DEFAULT) {
0 -> decay = 2000
2 -> decay = 500
else -> decay = 1000
}
sig_avg = decayAvg(sig_avg, v, decay)
if (v < sig_avg) {
noise_floor = if (v < noise_floor) decayAvg(noise_floor, v, attack)
else decayAvg(noise_floor, v, decay)
}
if (v > sig_avg) {
agc_peak = if (v > agc_peak) decayAvg(agc_peak, v, attack)
else decayAvg(agc_peak, v, decay)
}
val normNoise = noise_floor / agc_peak
val normSig = sig_avg / agc_peak
siglevel = normSig
if (agc_peak != 0.0) v /= agc_peak else v = 0.0
metric = 0.8 * metric
if ((noise_floor > 1e-4) && (noise_floor < sig_avg)) {
val db = 20.0 * log10(sig_avg / noise_floor)
metric += 0.2 * clamp(2.5 * db, 0.0, 100.0)
}
val diff = normSig - normNoise
upper_threshold = normSig - 0.2 * diff
lower_threshold = normNoise + 0.7 * diff
// Squelch gate (fldigi: !progStatus.sqlonoff || metric > sldrSquelchValue).
// Default sqlonoff=true, sldrSquelchValue=5.0. Without this gate, noise
// spikes false-trigger KEYDOWN and lock the state machine in IN_TONE.
if (sqlonoff && metric <= squelchValue) return
// Power detection using hysteresis
if ((v > upper_threshold) && (cw_receive_state != CwRxState.IN_TONE)) {
handleEvent(CW_KEYDOWN)
}
if ((v < lower_threshold) && (cw_receive_state == CwRxState.IN_TONE)) {
handleEvent(CW_KEYUP)
}
if (handleEvent(CW_QUERY) == CW_SUCCESS) {
synchscope = 100
// emit decoded char(s)
} else if (--synchscope == 0) {
synchscope = 25
}
}
private var sqlonoff = true
private var squelchValue = 5.0
private fun decayAvg(avg: Double, value: Double, timeConst: Int): Double =
avg + (value - avg) / timeConst
private fun clamp(v: Double, lo: Double, hi: Double): Double =
if (v < lo) lo else if (v > hi) hi else v
private fun handleEvent(event: Int): Int {
val sc = StringBuilder()
var elementUsec: Int
when (event) {
CW_RESET -> {
syncParameters()
cw_receive_state = CwRxState.IDLE
cw_ptr = 0
smpl_ctr = 0
rx_rep_buf.clear()
}
CW_KEYDOWN -> {
if (cw_receive_state == CwRxState.IN_TONE) return CW_ERROR
if (cw_receive_state == CwRxState.IDLE) {
smpl_ctr = 0
rx_rep_buf.clear()
cw_ptr = 0
}
cw_rr_start_timestamp = smpl_ctr
old_cw_receive_state = cw_receive_state
cw_receive_state = CwRxState.IN_TONE
return CW_ERROR
}
CW_KEYUP -> {
if (cw_receive_state != CwRxState.IN_TONE) return CW_ERROR
cw_rr_end_timestamp = smpl_ctr
elementUsec = usecDiff(cw_rr_start_timestamp, cw_rr_end_timestamp)
syncParameters()
if (cw_noise_spike_threshold > 0 && elementUsec < cw_noise_spike_threshold) {
cw_receive_state = CwRxState.IDLE
return CW_ERROR
}
// adaptive speed tracking on dot-dash / dash-dot pairs
if (last_element > 0) {
if ((elementUsec > 2 * last_element) && (elementUsec < 4 * last_element)) {
updateTracking(last_element, elementUsec)
}
if ((last_element > 2 * elementUsec) && (last_element < 4 * elementUsec)) {
updateTracking(elementUsec, last_element)
}
}
last_element = elementUsec
if (elementUsec <= two_dots) {
rx_rep_buf.append(CW_DOT)
cw_buffer[cw_ptr++] = last_element.toFloat()
} else {
rx_rep_buf.append(CW_DASH)
cw_buffer[cw_ptr++] = last_element.toFloat()
}
if (rx_rep_buf.length > CwFldigiConstants.MAX_MORSE_ELEMENTS) {
cw_receive_state = CwRxState.IDLE
cw_ptr = 0
smpl_ctr = 0
return CW_ERROR
} else {
if (cw_ptr < cw_buffer.size) cw_buffer[cw_ptr] = 0.0f
}
cw_receive_state = CwRxState.AFTER_TONE
return CW_ERROR
}
CW_QUERY -> {
if (cw_receive_state == CwRxState.IN_TONE) return CW_ERROR
syncParameters()
elementUsec = usecDiff(cw_rr_end_timestamp, smpl_ctr)
if (elementUsec < (2 * cw_receive_dot_length)) return CW_ERROR
if (elementUsec >= (2 * cw_receive_dot_length) &&
elementUsec <= (4 * cw_receive_dot_length) &&
cw_receive_state == CwRxState.AFTER_TONE
) {
val pattern = rx_rep_buf.toString()
val decoded = if (useSom) {
findWinner(cw_buffer, two_dots)
} else {
MorseTable.rxLookup(pattern)
}
if (decoded.isNotEmpty()) {
appendDecoded(decoded)
}
rx_rep_buf.clear()
cw_receive_state = CwRxState.IDLE
space_sent = false
cw_ptr = 0
return CW_SUCCESS
}
if ((elementUsec > (4 * cw_receive_dot_length)) && !space_sent) {
appendDecoded(" ")
space_sent = true
return CW_SUCCESS
}
return CW_ERROR
}
}
return CW_ERROR
}
private fun appendDecoded(text: String) {
val current = _decodedTextFlow.value
_decodedTextFlow.value = if (current.length > 2000) {
current.drop(current.length - 1500) + text
} else {
current + text
}
_signalStrength.value = metric.toFloat() / 100f
_estimatedSpeed.value = (CwFldigiConstants.KWPM.toDouble() / (two_dots / 2.0)).toFloat()
}
private fun syncParameters() {
if (cwTrack) {
cw_receive_speed = (CwFldigiConstants.KWPM / (two_dots / 2)).toInt()
} else {
cw_receive_speed = cw_send_speed
two_dots = 2 * (CwFldigiConstants.KWPM / cw_send_speed).toLong()
}
if (cw_receive_speed > 0) {
cw_receive_dot_length = (CwFldigiConstants.KWPM / cw_receive_speed).toLong()
} else {
cw_receive_dot_length = (CwFldigiConstants.KWPM / 5).toLong()
}
cw_receive_dash_length = 3 * cw_receive_dot_length
cw_noise_spike_threshold = cw_receive_dot_length / 2
}
private fun updateTracking(dur1: Int, dur2: Int) {
val minDot = CwFldigiConstants.KWPM / 200
val maxDash = 3 * CwFldigiConstants.KWPM / 5
if ((dur1 > dur2) && (dur1 > 4 * dur2)) return
if ((dur2 > dur1) && (dur2 > 4 * dur1)) return
if (dur1 < minDot || dur2 < minDot) return
if (dur2 > maxDash || dur2 > maxDash) return
two_dots = trackingfilter.run(((dur1 + dur2) / 2).toDouble()).toLong()
syncParameters()
}
/**
* SOM codebook matching (fldigi cw::find_winner + normalize).
*/
private fun findWinner(inbuf: FloatArray, twodots: Long): String {
if (normalize(inbuf, twodots) == 0) return " "
var winner = -1
var bestDiff = Double.MAX_VALUE
for ((idx, entry) in SomTable.table.withIndex()) {
var difference = 0.0
for (i in 0 until CwFldigiConstants.WGT_SIZE) {
val diff = inbuf[i] - entry.weights[i]
difference += diff * diff
if (difference > bestDiff) break
}
if (difference < bestDiff) {
winner = idx
bestDiff = difference
}
}
if (winner >= 0 && SomTable.table[winner].pattern.isNotEmpty()) {
val sc = MorseTable.rxLookup(SomTable.table[winner].pattern)
return if (sc.isNotEmpty()) sc else CwFldigiConstants.DEFAULT_NOISE_CHAR.toString()
}
return CwFldigiConstants.DEFAULT_NOISE_CHAR.toString()
}
private fun normalize(v: FloatArray, twodots: Long): Int {
var max = v[0]
var min = v[0]
for (j in 1 until CwFldigiConstants.WGT_SIZE) {
if (v[j] > max) max = v[j]
else if (v[j] < min) min = v[j]
}
if (max == 0.0f) return 0
val ratio = if (max > twodots) 1.0f else 0.33f
val scale = ratio / max
for (j in 0 until CwFldigiConstants.WGT_SIZE) v[j] *= scale
return 1
}
/** Reset the decoder state (fldigi cw::rx_init + reset). */
fun resetDecoder() {
cw_receive_state = CwRxState.IDLE
smpl_ctr = 0
cw_ptr = 0
rx_rep_buf.clear()
last_element = 0
space_sent = true
_decodedTextFlow.value = ""
_signalStrength.value = 0f
_estimatedSpeed.value = null
FFTphase = 0.0
phaseacc = 0.0
// reset auto-tune
tuneIdx = 0
tunePeakFreq = frequency
tuneHasPeak = false
tuneLocked = false
tuneFreq = frequency
}
}
@@ -0,0 +1,183 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Constants and primitives ported from fldigi (w1hkj/fldigi),
* GPL v3, cw.h / cw.cxx / filters.cxx / fftfilt.cxx.
*
* Faithful port: identifiers and formulas mirror the C++ original so
* behaviour matches the desktop decoder bit-for-bit.
*/
internal object CwFldigiConstants {
const val CW_SAMPLERATE = 8000
const val DEC_RATIO = 16
const val CW_FFT_SIZE = 2048 // must be power of 2
const val MAX_MORSE_ELEMENTS = 6
const val WGT_SIZE = 7
const val TRACKING_FILTER_SIZE = 16
const val MAX_PIPE_SIZE = (22 * CW_SAMPLERATE * 12 / 800)
const val CLRCOUNT = 16
const val CW_MAX_SPEED = 50
const val INITIAL_SEND_SPEED = 18
const val INITIAL_RECEIVE_SPEED = 18
/** # samples in a dot: KWPM / WPM. fldigi: KWPM = 12 * samplerate / 10 */
const val KWPM = 12 * CW_SAMPLERATE / 10
const val CW_SUCCESS = 0
const val CW_ERROR = -1
// Defaults mirroring fldigi progdefaults
const val DEFAULT_SPEED = 18 // WPM
const val DEFAULT_BANDWIDTH = 150 // Hz
const val DEFAULT_RANGE = 10 // WPM tracking range
const val LOWER_LIMIT = 5 // WPM
const val UPPER_LIMIT = 50 // WPM
const val DEFAULT_NOISE_CHAR = '*'
const val CWRX_ATTACK_DEFAULT = 1 // medium
const val CWRX_DECAY_DEFAULT = 1 // medium
const val CW_LOWER_THRESHOLD = 0.4
const val CW_UPPER_THRESHOLD = 0.6
}
/**
* Moving average filter, ported from fldigi Cmovavg (filters.cxx).
*/
internal class CwMovAvg(private var len: Int) {
private val buf = DoubleArray(MAX_MOVAVG)
private var out = 0.0
private var pint = 0
private var empty = true
fun run(a: Double): Double {
if (empty) {
empty = false
out = 0.0
for (i in 0 until len) {
buf[i] = a
out += a
}
pint = 0
return a
}
out = out - buf[pint] + a
buf[pint] = a
if (++pint >= len) pint = 0
return out / len
}
fun setLength(newLen: Int) {
len = newLen.coerceAtMost(MAX_MOVAVG).coerceAtLeast(1)
empty = true
}
fun reset() {
empty = true
}
fun value(): Double = if (len > 0) out / len else 0.0
private companion object {
const val MAX_MOVAVG = 2048
}
}
/**
* Complex sample used by the FFT filter chain.
*/
internal data class CwComplex(var re: Double = 0.0, var im: Double = 0.0) {
operator fun timesAssign(other: CwComplex) {
val r = re * other.re - im * other.im
val i = re * other.im + im * other.re
re = r; im = i
}
fun abs(): Double = kotlin.math.sqrt(re * re + im * im)
}
/**
* In-place radix-2 complex FFT, ported from fldigi gfft.h semantics
* (ComplexFFT / InverseComplexFFT, forward = -1).
*/
internal class CwGfft(private val n: Int) {
init {
require(n > 0 && n and (n - 1) == 0) { "FFT size must be power of 2, got $n" }
}
private val rev = IntArray(n)
init {
val log2n = Integer.numberOfTrailingZeros(n)
for (i in 0 until n) {
var r = 0
var x = i
for (bit in 0 until log2n) {
r = (r shl 1) or (x and 1)
x = x shr 1
}
rev[i] = r
}
}
/**
* In-place complex FFT.
* @param data array of CwComplex, size n
* @param inverse if true, performs inverse transform (no 1/n scaling; caller divides)
*/
fun transform(data: Array<CwComplex>, inverse: Boolean) {
val sign = if (inverse) 1 else -1
// bit reversal permutation
for (i in 0 until n) {
val j = rev[i]
if (j > i) {
val t = data[i]; data[i] = data[j]; data[j] = t
}
}
var len = 2
while (len <= n) {
val ang = sign * 2.0 * Math.PI / len
val wRe = Math.cos(ang)
val wIm = Math.sin(ang)
var i = 0
while (i < n) {
var curRe = 1.0
var curIm = 0.0
for (j in 0 until len / 2) {
val u = data[i + j]
val v = data[i + j + len / 2]
val tRe = curRe * v.re - curIm * v.im
val tIm = curRe * v.im + curIm * v.re
data[i + j] = CwComplex(u.re + tRe, u.im + tIm)
data[i + j + len / 2] = CwComplex(u.re - tRe, u.im - tIm)
val nRe = curRe * wRe - curIm * wIm
val nIm = curRe * wIm + curIm * wRe
curRe = nRe; curIm = nIm
}
i += len
}
len = len shl 1
}
}
fun forward(data: Array<CwComplex>) = transform(data, false)
fun inverse(data: Array<CwComplex>) = transform(data, true)
}
@@ -0,0 +1,54 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.cos
import kotlin.math.sqrt
/**
* Running Goertzel filter for CW tone detection.
* Tracks a specific frequency over time with a sliding window.
* Ported from ggmorse/src/goertzel.h
*/
internal class CwGoertzel {
private var s1 = 0.0
private var s2 = 0.0
private var coeff = 0.0
fun init(sampleRate: Float, targetFreq: Float) {
val omega = 2.0 * kotlin.math.PI * targetFreq / sampleRate
coeff = 2.0 * cos(omega)
s1 = 0.0
s2 = 0.0
}
fun process(sample: Float) {
val s0 = sample.toDouble() + coeff * s1 - s2
s2 = s1
s1 = s0
}
fun getPower(): Float {
return sqrt(s2 * s2 + s1 * s1 - coeff * s1 * s2).toFloat()
}
fun reset() {
s1 = 0.0
s2 = 0.0
}
}
@@ -0,0 +1,53 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Simple linear resampler.
* Downsamples from input sample rate to output sample rate.
* Ported from ggmorse/src/resampler.h
*/
internal class CwResampler(private val inputRate: Float, private val outputRate: Float) {
private val ratio = inputRate / outputRate
private var lastSample = 0f
fun process(input: FloatArray): FloatArray {
if (ratio <= 0f || input.isEmpty()) return input
val outputLen = (input.size / ratio).toInt() + 1
val output = FloatArray(outputLen)
var idx = 0f
for (i in output.indices) {
val intIdx = idx.toInt()
val frac = idx - intIdx
if (intIdx + 1 < input.size) {
output[i] = input[intIdx] * (1 - frac) + input[intIdx + 1] * frac
} else if (intIdx < input.size) {
output[i] = input[intIdx] * (1 - frac) + lastSample * frac
} else {
output[i] = lastSample
}
idx += ratio
}
lastSample = input.lastOrNull() ?: lastSample
return output
}
fun reset() {
lastSample = 0f
}
}
@@ -0,0 +1,61 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
/**
* Lightweight pitch detector using DFT at specific frequency bins.
* Only scans [200, 1200] Hz in configurable steps — much faster than full FFT.
* Ported from ggmorse/src/stfft.h (simplified for CW use case).
*/
internal class CwPitchDetector(
private val sampleRate: Float,
private val minFreq: Float = 200f,
private val maxFreq: Float = 1200f,
private val stepHz: Float = 10f
) {
/**
* Find the dominant pitch frequency in the buffer.
* Returns null if no significant pitch found.
*/
fun findPitch(buffer: FloatArray): Float? {
if (buffer.isEmpty()) return null
var bestFreq = 0f
var bestPower = 0f
var freq = minFreq
while (freq <= maxFreq) {
var real = 0.0
var imag = 0.0
val omega = 2.0 * kotlin.math.PI * freq / sampleRate
for (i in buffer.indices) {
real += buffer[i] * cos(omega * i)
imag += buffer[i] * -sin(omega * i)
}
val power = (real * real + imag * imag).toFloat()
if (power > bestPower) {
bestPower = power
bestFreq = freq
}
freq += stepHz
}
return if (bestPower > 0.001f) bestFreq else null
}
}
@@ -0,0 +1,170 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Sliding-window spectrogram for CW decoding.
* Maintains a time-frequency matrix updated with each audio frame.
*
* FFT size: 256, hop size: 64, sample rate: 4000 (or native)
* Frequency bins: 6..38 (187-1187 Hz, covers typical CW range)
* History: 40 columns (320 ms window)
* Time resolution: 64/4000 = 16 ms, Frequency resolution: 4000/256 = 15.625 Hz
*/
internal class CwSpectrogram(
private val fftSize: Int = 256,
private val hopSize: Int = 64,
private val sampleRate: Int = 4000,
private val minBin: Int = 6,
private val maxBin: Int = 38,
val historyCols: Int = 40
) {
private val fft = CwFFT(fftSize)
val numBins: Int get() = maxBin - minBin + 1
// Hanning window
private val hanning = FloatArray(fftSize) {
(0.5 - 0.5 * kotlin.math.cos(2.0 * kotlin.math.PI * it / (fftSize - 1))).toFloat()
}
// Spectrogram data: [timeCol][freqBin]
private val spectrogram = Array(historyCols) { FloatArray(numBins) }
private var currentCol = 0
private var samplesBuffered = 0
private val buffer = FloatArray(fftSize)
// Per-bin running energy for normalization
private val binEnergy = FloatArray(numBins) { 1f }
private val alpha = 0.95f
// Counter for new columns generated since last check
private var newColumnCount = 0
/** Add audio samples, compute FFTs for each complete hop. */
fun addSamples(samples: FloatArray) {
var offset = 0
while (offset < samples.size) {
val needed = fftSize - samplesBuffered
val copyLen = minOf(needed, samples.size - offset)
System.arraycopy(samples, offset, buffer, samplesBuffered, copyLen)
samplesBuffered += copyLen
offset += copyLen
if (samplesBuffered >= fftSize) {
processFrame()
newColumnCount++
// Shift buffer: keep last (fftSize - hopSize) samples
System.arraycopy(buffer, hopSize, buffer, 0, fftSize - hopSize)
samplesBuffered = fftSize - hopSize
}
}
}
/** Get number of new columns generated since the last call to this method. */
fun getNewColumns(): Int {
val count = newColumnCount
newColumnCount = 0
return count
}
private fun processFrame() {
// Apply Hanning window
val windowed = FloatArray(fftSize) { buffer[it] * hanning[it] }
// Compute FFT magnitude spectrum
val mag = fft.magnitudeSpectrum(windowed)
// Update spectrogram column
val col = spectrogram[currentCol]
for (b in 0 until numBins) {
val binIdx = minBin + b
val rawMag = mag[binIdx]
// Running energy normalization
binEnergy[b] = alpha * binEnergy[b] + (1 - alpha) * rawMag
col[b] = if (binEnergy[b] > 1e-6f) rawMag / binEnergy[b] else 0f
}
currentCol = (currentCol + 1) % historyCols
}
/** Get the current spectrogram as a 2D array in chronological order. */
fun getSpectrogram(): Array<FloatArray> {
val result = Array(historyCols) { i ->
val srcIdx = (currentCol + i) % historyCols
spectrogram[srcIdx].copyOf()
}
return result
}
/** Get the most recent column (current energy across all frequencies). */
fun getCurrentColumn(): FloatArray {
val prevCol = (currentCol - 1 + historyCols) % historyCols
return spectrogram[prevCol].copyOf()
}
/** Get a column by index from the history (0 = oldest, historyCols-1 = newest). */
fun getColumn(index: Int): FloatArray {
val clamped = index.coerceIn(0, historyCols - 1)
val srcIdx = (currentCol - historyCols + clamped + historyCols) % historyCols
return spectrogram[srcIdx].copyOf()
}
/** Find the frequency bin with peak energy. Returns -1 if no significant signal. */
fun findPeakBin(): Int {
val col = getCurrentColumn()
var maxBin = -1
var maxVal = 0f
for (i in col.indices) {
if (col[i] > maxVal) {
maxVal = col[i]
maxBin = i
}
}
return if (maxVal > 0.3f) maxBin else -1
}
/** Get energy at a specific bin over the last N columns in chronological order. */
fun getBinEnergy(bin: Int, numCols: Int): FloatArray {
val clamped = minOf(numCols, historyCols)
val result = FloatArray(clamped)
for (i in 0 until clamped) {
val colIdx = (currentCol - clamped + i + historyCols) % historyCols
result[i] = spectrogram[colIdx][bin]
}
return result
}
/** Get the bin index for a frequency in Hz. */
fun freqToBin(freqHz: Float): Int {
val bin = (freqHz * fftSize / sampleRate).toInt()
return (bin - minBin).coerceIn(0, numBins - 1)
}
/** Get the center frequency for a bin. */
fun binToFreq(bin: Int): Float {
return (minBin + bin).toFloat() * sampleRate / fftSize
}
fun reset() {
for (col in spectrogram) col.fill(0f)
currentCol = 0
samplesBuffered = 0
buffer.fill(0f)
binEnergy.fill(1f)
}
}
@@ -1,66 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import kotlinx.coroutines.flow.StateFlow
/**
* A CW (Morse code) decoder fed with microphone PCM.
*
* Implementations live outside `core:domain` when they need platform APIs;
* this contract stays pure Kotlin so the UI can depend on it directly.
*/
interface ICwDecoder {
/**
* Decoded text for the *current* window.
*
* Note this is **replace** semantics, not append: a whole-segment model
* revises earlier characters as more audio arrives, so consumers must show
* the current value rather than accumulating emissions.
*/
val decodedText: StateFlow<String>
/**
* Permanent transcript of everything that has scrolled out of the live
* window. Unlike [decodedText] this only ever grows (until [reset]); it is
* what the user reads back after a signal has passed.
*/
val historyText: StateFlow<String>
/** Detected tone frequency in Hz, or null before a tone is found. */
val estimatedPitch: StateFlow<Float?>
/** Relative signal strength in 0..1 for level meters. */
val signalStrength: StateFlow<Float>
/** Most recent inference duration in milliseconds, for diagnostics. */
val lastInferenceMs: StateFlow<Int>
/** Non-null when the decoder cannot run, for example the model failed to load. */
val errorMessage: StateFlow<String?>
/** Feed captured mono PCM in -1..1. Safe to call from a capture thread. */
suspend fun processBuffer(samples: FloatArray, sampleRate: Int)
/** Clear decoded text and buffered audio. */
fun reset()
/** Release native resources. Must be called when the decoder goes away. */
fun close()
}
@@ -0,0 +1,140 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Morse code lookup table, ported from fldigi morse.cxx (cMorse::cw_table).
* Each entry: [enabled, displayChar, prosignDisplay, dotDashPattern].
*/
internal object MorseTable {
private data class Entry(
val enabled: Boolean,
val chr: String,
val prt: String,
val rpr: String
)
private val table = listOf(
// Prosigns
Entry(true, "=", "<BT>", "-...-"),
Entry(false, "~", "<AA>", ".-.-"),
Entry(true, "<", "<AS>", ".-..."),
Entry(true, ">", "<AR>", ".-.-."),
Entry(true, "%", "<SK>", "...-.-"),
Entry(true, "+", "<KN>", "-.--."),
Entry(true, "&", "<INT>", "..-.-"),
Entry(true, "{", "<HM>", "....--"),
Entry(true, "}", "<VE>", "...-."),
// ASCII 7-bit letters
Entry(true, "A", "A", ".-"),
Entry(true, "B", "B", "-..."),
Entry(true, "C", "C", "-.-."),
Entry(true, "D", "D", "-.."),
Entry(true, "E", "E", "."),
Entry(true, "F", "F", "..-."),
Entry(true, "G", "G", "--."),
Entry(true, "H", "H", "...."),
Entry(true, "I", "I", ".."),
Entry(true, "J", "J", ".---"),
Entry(true, "K", "K", "-.-"),
Entry(true, "L", "L", ".-.."),
Entry(true, "M", "M", "--"),
Entry(true, "N", "N", "-."),
Entry(true, "O", "O", "---"),
Entry(true, "P", "P", ".--."),
Entry(true, "Q", "Q", "--.-"),
Entry(true, "R", "R", ".-."),
Entry(true, "S", "S", "..."),
Entry(true, "T", "T", "-"),
Entry(true, "U", "U", "..-"),
Entry(true, "V", "V", "...-"),
Entry(true, "W", "W", ".--"),
Entry(true, "X", "X", "-..-"),
Entry(true, "Y", "Y", "-.--"),
Entry(true, "Z", "Z", "--.."),
// lowercase map to uppercase
Entry(true, "a", "A", ".-"), Entry(true, "b", "B", "-..."),
Entry(true, "c", "C", "-.-."), Entry(true, "d", "D", "-.."),
Entry(true, "e", "E", "."), Entry(true, "f", "F", "..-."),
Entry(true, "g", "G", "--."), Entry(true, "h", "H", "...."),
Entry(true, "i", "I", ".."), Entry(true, "j", "J", ".---"),
Entry(true, "k", "K", "-.-"), Entry(true, "l", "L", ".-.."),
Entry(true, "m", "M", "--"), Entry(true, "n", "N", "-."),
Entry(true, "o", "O", "---"), Entry(true, "p", "P", ".--."),
Entry(true, "q", "Q", "--.-"), Entry(true, "r", "R", ".-."),
Entry(true, "s", "S", "..."), Entry(true, "t", "T", "-"),
Entry(true, "u", "U", "..-"), Entry(true, "v", "V", "...-"),
Entry(true, "w", "W", ".--"), Entry(true, "x", "X", "-..-"),
Entry(true, "y", "Y", "-.--"), Entry(true, "z", "Z", "--.."),
// Numerals
Entry(true, "0", "0", "-----"),
Entry(true, "1", "1", ".----"),
Entry(true, "2", "2", "..---"),
Entry(true, "3", "3", "...--"),
Entry(true, "4", "4", "....-"),
Entry(true, "5", "5", "....."),
Entry(true, "6", "6", "-...."),
Entry(true, "7", "7", "--..."),
Entry(true, "8", "8", "---.."),
Entry(true, "9", "9", "----."),
// Punctuation
Entry(true, "\\", "\\", ".-..-."),
Entry(true, "'", "'", ".----."),
Entry(true, "$", "$", "...-..-"),
Entry(true, "(", "(", "-.--."),
Entry(true, ")", ")", "-.--.-"),
Entry(true, ",", ",", "--..--"),
Entry(true, "-", "-", "-....-"),
Entry(true, ".", ".", ".-.-.-"),
Entry(true, "/", "/", "-..-."),
Entry(true, ":", ":", "---..."),
Entry(true, ";", ";", "-.-.-."),
Entry(true, "?", "?", "..--.."),
Entry(true, "_", "_", "..--.-"),
Entry(true, "@", "@", ".--.-."),
Entry(true, "!", "!", "-.-.--"),
// Accented (disabled by default in fldigi)
Entry(false, "Ä", "Ä", ".-.-"), Entry(false, "ä", "Ä", ".-.-"),
Entry(false, "Æ", "Æ", ".-.-"), Entry(false, "æ", "Æ", ".-.-"),
Entry(false, "Å", "Å", ".--.-"), Entry(false, "å", "Å", ".--.-"),
Entry(false, "Ç", "Ç", "-.-.."), Entry(false, "ç", "Ç", "-.-.."),
Entry(false, "È", "È", ".-..-"), Entry(false, "è", "È", ".-..-"),
Entry(false, "É", "É", "..-.."), Entry(false, "é", "É", "..-.."),
Entry(false, "Ó", "Ó", "---."), Entry(false, "ó", "Ó", "---."),
Entry(false, "Ö", "Ö", "---."), Entry(false, "ö", "Ö", "---."),
Entry(false, "Ø", "Ø", "---."), Entry(false, "ø", "Ø", "---."),
Entry(false, "Ñ", "Ñ", "--.--"), Entry(false, "ñ", "Ñ", "--.--"),
Entry(false, "Ü", "Ü", "..--"), Entry(false, "ü", "Ü", "..--"),
Entry(false, "Û", "Û", "..--"), Entry(false, "û", "Û", "..--")
)
/**
* Look up the display representation of a dot-dash pattern.
* Returns "" when the pattern is not in the table or is disabled.
* Mirror of cMorse::rx_lookup.
*/
fun rxLookup(pattern: String): String {
for (e in table) {
if (pattern == e.rpr) {
if (e.enabled) return e.prt
}
}
return ""
}
}
@@ -0,0 +1,104 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
/**
* Self-Organizing Map codebook for CW character matching, ported from
* fldigi cw.cxx (cw::som_table). Each row is a dot/dash weight vector
* (0 = element absent, 0.33 = dot, 1.0 = dash).
*/
internal object SomTable {
data class SomEntry(val pattern: String, val weights: FloatArray)
val table: List<SomEntry> = listOf(
// Prosigns
SomEntry("-...-", floatArrayOf(1.0f, 0.33f, 0.33f, 0.33f, 1.0f, 0f, 0f)),
SomEntry(".-.-", floatArrayOf(0.33f, 1.0f, 0.33f, 1.0f, 0f, 0f, 0f)),
SomEntry(".-...", floatArrayOf(0.33f, 1.0f, 0.33f, 0.33f, 0.33f, 0f, 0f)),
SomEntry(".-.-.", floatArrayOf(0.33f, 1.0f, 0.33f, 1.0f, 0.33f, 0f, 0f)),
SomEntry("...-.-", floatArrayOf(0.33f, 0.33f, 0.33f, 1.0f, 0.33f, 1.0f, 0f)),
SomEntry("-.--.", floatArrayOf(1.0f, 0.33f, 1.0f, 1.0f, 0.33f, 0f, 0f)),
SomEntry("..-.-", floatArrayOf(0.33f, 0.33f, 1.0f, 0.33f, 1.0f, 0f, 0f)),
SomEntry("....--", floatArrayOf(0.33f, 0.33f, 0.33f, 0.33f, 1.0f, 1.0f, 0f)),
SomEntry("...-.", floatArrayOf(0.33f, 0.33f, 0.33f, 1.0f, 0.33f, 0f, 0f)),
// ASCII 7-bit letters
SomEntry(".-", floatArrayOf(0.33f, 1.0f, 0f, 0f, 0f, 0f, 0f)),
SomEntry("-...", floatArrayOf(1.0f, 0.33f, 0.33f, 0.33f, 0f, 0f, 0f)),
SomEntry("-.-.", floatArrayOf(1.0f, 0.33f, 1.0f, 0.33f, 0f, 0f, 0f)),
SomEntry("-..", floatArrayOf(1.0f, 0.33f, 0.33f, 0f, 0f, 0f, 0f)),
SomEntry(".", floatArrayOf(0.33f, 0f, 0f, 0f, 0f, 0f, 0f)),
SomEntry("..-.", floatArrayOf(0.33f, 0.33f, 1.0f, 0.33f, 0f, 0f, 0f)),
SomEntry("--.", floatArrayOf(1.0f, 1.0f, 0.33f, 0f, 0f, 0f, 0f)),
SomEntry("....", floatArrayOf(0.33f, 0.33f, 0.33f, 0.33f, 0f, 0f, 0f)),
SomEntry("..", floatArrayOf(0.33f, 0.33f, 0f, 0f, 0f, 0f, 0f)),
SomEntry(".---", floatArrayOf(0.33f, 1.0f, 1.0f, 1.0f, 0f, 0f, 0f)),
SomEntry("-.-", floatArrayOf(1.0f, 0.33f, 1.0f, 0f, 0f, 0f, 0f)),
SomEntry(".-..", floatArrayOf(0.33f, 1.0f, 0.33f, 0.33f, 0f, 0f, 0f)),
SomEntry("--", floatArrayOf(1.0f, 1.0f, 0f, 0f, 0f, 0f, 0f)),
SomEntry("-.", floatArrayOf(1.0f, 0.33f, 0f, 0f, 0f, 0f, 0f)),
SomEntry("---", floatArrayOf(1.0f, 1.0f, 1.0f, 0f, 0f, 0f, 0f)),
SomEntry(".--.", floatArrayOf(0.33f, 1.0f, 1.0f, 0.33f, 0f, 0f, 0f)),
SomEntry("--.-", floatArrayOf(1.0f, 1.0f, 0.33f, 1.0f, 0f, 0f, 0f)),
SomEntry(".-.", floatArrayOf(0.33f, 1.0f, 0.33f, 0f, 0f, 0f, 0f)),
SomEntry("...", floatArrayOf(0.33f, 0.33f, 0.33f, 0f, 0f, 0f, 0f)),
SomEntry("-", floatArrayOf(1.0f, 0f, 0f, 0f, 0f, 0f, 0f)),
SomEntry("..-", floatArrayOf(0.33f, 0.33f, 1.0f, 0f, 0f, 0f, 0f)),
SomEntry("...-", floatArrayOf(0.33f, 0.33f, 0.33f, 1.0f, 0f, 0f, 0f)),
SomEntry(".--", floatArrayOf(0.33f, 1.0f, 1.0f, 0f, 0f, 0f, 0f)),
SomEntry("-..-", floatArrayOf(1.0f, 0.33f, 0.33f, 1.0f, 0f, 0f, 0f)),
SomEntry("-.--", floatArrayOf(1.0f, 0.33f, 1.0f, 1.0f, 0f, 0f, 0f)),
SomEntry("--..", floatArrayOf(1.0f, 1.0f, 0.33f, 0.33f, 0f, 0f, 0f)),
// Numerals
SomEntry("-----", floatArrayOf(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0f, 0f)),
SomEntry(".----", floatArrayOf(0.33f, 1.0f, 1.0f, 1.0f, 1.0f, 0f, 0f)),
SomEntry("..---", floatArrayOf(0.33f, 0.33f, 1.0f, 1.0f, 1.0f, 0f, 0f)),
SomEntry("...--", floatArrayOf(0.33f, 0.33f, 0.33f, 1.0f, 1.0f, 0f, 0f)),
SomEntry("....-", floatArrayOf(0.33f, 0.33f, 0.33f, 0.33f, 1.0f, 0f, 0f)),
SomEntry(".....", floatArrayOf(0.33f, 0.33f, 0.33f, 0.33f, 0.33f, 0f, 0f)),
SomEntry("-....", floatArrayOf(1.0f, 0.33f, 0.33f, 0.33f, 0.33f, 0f, 0f)),
SomEntry("--...", floatArrayOf(1.0f, 1.0f, 0.33f, 0.33f, 0.33f, 0f, 0f)),
SomEntry("---..", floatArrayOf(1.0f, 1.0f, 1.0f, 0.33f, 0.33f, 0f, 0f)),
SomEntry("----.", floatArrayOf(1.0f, 1.0f, 1.0f, 1.0f, 0.33f, 0f, 0f)),
// Punctuation
SomEntry(".-..-.", floatArrayOf(0.33f, 1.0f, 0.33f, 0.33f, 1.0f, 0.33f, 0f)),
SomEntry(".----.", floatArrayOf(0.33f, 1.0f, 1.0f, 1.0f, 1.0f, 0.33f, 0f)),
SomEntry("...-..-", floatArrayOf(0.33f, 0.33f, 0.33f, 1.0f, 0.33f, 0.33f, 1.0f)),
SomEntry("-.---.", floatArrayOf(1.0f, 0.33f, 1.0f, 1.0f, 0.33f, 0f, 0f)),
SomEntry("-.--.-", floatArrayOf(1.0f, 0.33f, 1.0f, 1.0f, 0.33f, 1.0f, 0f)),
SomEntry("--..--", floatArrayOf(1.0f, 1.0f, 0.33f, 0.33f, 1.0f, 1.0f, 0f)),
SomEntry("-....-", floatArrayOf(1.0f, 0.33f, 0.33f, 0.33f, 0.33f, 1.0f, 0f)),
SomEntry(".-.-.-", floatArrayOf(0.33f, 1.0f, 0.33f, 1.0f, 0.33f, 1.0f, 0f)),
SomEntry("-..-.", floatArrayOf(1.0f, 0.33f, 0.33f, 1.0f, 0.33f, 0f, 0f)),
SomEntry("---...", floatArrayOf(1.0f, 1.0f, 1.0f, 0.33f, 0.33f, 0.33f, 0f)),
SomEntry("-.-.-.", floatArrayOf(1.0f, 0.33f, 1.0f, 0.33f, 1.0f, 0.33f, 0f)),
SomEntry("..--..", floatArrayOf(0.33f, 0.33f, 1.0f, 1.0f, 0.33f, 0.33f, 0f)),
SomEntry("..--.-", floatArrayOf(0.33f, 0.33f, 1.0f, 1.0f, 0.33f, 1.0f, 0f)),
SomEntry(".--.-.", floatArrayOf(0.33f, 1.0f, 1.0f, 0.33f, 1.0f, 0.33f, 0f)),
SomEntry("-.-.--", floatArrayOf(1.0f, 0.33f, 1.0f, 0.33f, 1.0f, 1.0f, 0f)),
// Accented
SomEntry(".-.-", floatArrayOf(0.33f, 1.0f, 0.33f, 1.0f, 0f, 0f, 0f)), // A umlaut, A aelig
SomEntry(".--.-", floatArrayOf(0.33f, 1.0f, 1.0f, 0.33f, 1.0f, 0f, 0f)), // A ring
SomEntry("-.-..", floatArrayOf(1.0f, 0.33f, 1.0f, 0.33f, 0.33f, 0f, 0f)), // C cedilla
SomEntry(".-..-", floatArrayOf(0.33f, 1.0f, 0.33f, 0.33f, 1.0f, 0f, 0f)), // E grave
SomEntry("..-..", floatArrayOf(0.33f, 0.33f, 1.0f, 0.33f, 0.33f, 0f, 0f)), // E acute
SomEntry("---.", floatArrayOf(1.0f, 1.0f, 1.0f, 0.33f, 0f, 0f, 0f)), // O acute, O umlaut, O slash
SomEntry("--.--", floatArrayOf(1.0f, 1.0f, 0.33f, 1.0f, 1.0f, 0f, 0f)), // N tilde
SomEntry("..--", floatArrayOf(0.33f, 0.33f, 1.0f, 1.0f, 0f, 0f, 0f)) // U umlaut, U circ
)
}
@@ -42,7 +42,6 @@ interface IMainContainer {
fun provideTxRadioController(): IRadioController
fun provideRxRadioController(): IRadioController
fun provideAudioCapture(): IAudioCapture
fun provideCwDecoder(): com.rtbishop.look4sat.core.domain.cw.ICwDecoder
fun provideSaveImage(): ISaveImage
// WaveLog logging (4.5.2)
val wavelogQueue: com.rtbishop.look4sat.core.domain.wavelog.WavelogQueue
@@ -25,10 +25,4 @@ interface IRemoteSource {
/** Fetch AMSAT status page HTML (with UA; null = failure) */
suspend fun getStatusHtml(): String?
/** Fetch AMSAT API catalog (JSON string; null on failure) */
suspend fun getAmSatCatalog(): String?
/** Fetch AMSAT API reports for the past N hours (JSON string; null on failure) */
suspend fun getAmSatReports(hours: Int, limit: Int): String?
}
@@ -106,6 +106,51 @@ object WaveLogApi {
WavelogResult.Success("")
}
/**
* ADIF band code from a frequency in Hz. "SAT" is NOT a legal ADIF band
* value (the Band enumeration is 160M/80M/.../2M/70CM/23CM...); a logger
* that fails to parse an illegal band falls back to a default such as
* 160m. Satellite QSOs must carry the real band of the TX frequency.
*/
fun bandFromHz(freqHz: Long): String = when {
freqHz >= 1240_000_000 -> "23CM"
freqHz >= 902_000_000 -> "33CM"
freqHz >= 420_000_000 -> "70CM"
freqHz >= 222_000_000 -> "1.25M"
freqHz >= 144_000_000 -> "2M"
freqHz >= 50_000_000 -> "6M"
freqHz >= 28_000_000 -> "10M"
freqHz >= 24_890_000 -> "12M"
freqHz >= 21_000_000 -> "15M"
freqHz >= 18_068_000 -> "17M"
freqHz >= 14_000_000 -> "20M"
freqHz >= 10_000_000 -> "30M"
freqHz >= 7_000_000 -> "40M"
freqHz >= 5_102_000 -> "60M"
freqHz >= 3_500_000 -> "80M"
freqHz >= 1_800_000 -> "160M"
else -> "160M"
}
/** Band class letter for satellite mode derivation: VHF=V, UHF=U, SHF=S. */
private fun bandLetter(freqHz: Long): String = when {
freqHz >= 1_240_000_000 -> "S"
freqHz >= 420_000_000 -> "U"
freqHz >= 144_000_000 -> "V"
else -> "V"
}
/**
* ADIF SAT_MODE (free text, satellite convention): "V/U" = VHF up /
* UHF down, "U/V", "V/S", "U/S"... Derived from the actual TX/RX bands.
*/
fun satModeFrom(txFreqHz: Long, rxFreqHz: Long): String {
if (rxFreqHz <= 0) return ""
val up = bandLetter(txFreqHz)
val down = bandLetter(rxFreqHz)
return if (up == down) "" else "$up/$down"
}
/** LoTW-recognized satellite name: main name before parentheses, uppercased (ISS special case) */
fun normalizeSatName(raw: String): String {
val main = raw.substringBefore('(').trim()
@@ -142,10 +187,11 @@ object WaveLogApi {
val satName = normalizeSatName(qso.satName)
// v2: POST /index.php/api/v2/qso (JSON fields)
val satMode = satModeFrom(qso.freqTxHz, qso.freqRxHz)
val v2Body = JSONObject().apply {
put("station_profile_id", stationProfileId.toIntOrNull() ?: 0)
put("call", qso.call)
put("band", "SAT")
put("band", bandFromHz(qso.freqTxHz))
put("mode", qso.mode)
put("qso_date", utcDate(qso.timeUtcMs))
put("time_on", utcTime(qso.timeUtcMs))
@@ -155,6 +201,7 @@ object WaveLogApi {
put("rst_sent", "59")
put("rst_rcvd", "59")
put("sat_name", satName)
if (satMode.isNotBlank()) put("sat_mode", satMode)
}
val (code, resp) = httpRequest("$base/index.php/api/v2/qso", "POST", apiKey, v2Body.toString())
if (code in 200..299) return@withContext WavelogResult.Success("已上传 (v2)")
@@ -183,9 +230,10 @@ object WaveLogApi {
val bytes = value.toByteArray(Charsets.UTF_8).size
return "<$name:$bytes>$value"
}
val satMode = satModeFrom(qso.freqTxHz, qso.freqRxHz)
return buildString {
append(field("call", qso.call))
append(field("band", "SAT"))
append(field("band", bandFromHz(qso.freqTxHz)))
append(field("mode", qso.mode))
append(field("freq", String.format(Locale.ENGLISH, "%.6f", qso.freqTxHz / 1_000_000.0)))
if (qso.freqRxHz > 0) {
@@ -198,6 +246,7 @@ object WaveLogApi {
if (gridsquare.isNotBlank()) append(field("gridsquare", gridsquare.take(4)))
if (satName.isNotBlank()) {
append(field("sat_name", satName))
if (satMode.isNotBlank()) append(field("sat_mode", satMode))
append(field("prop_mode", "SAT"))
}
append("<eor>")
@@ -1,90 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Greedy CTC collapse, matching the reference implementation's
* `greedy_ctc_decode`: drop blanks, then drop runs of the same label.
*
* Alphabet from `model.onnx.json` — 41 symbols plus blank at index 41.
*/
class CwCtcDecoderTest {
private val chars = listOf(
",", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "?",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "
)
private val blank = 41
/** Build a `[1, T, 42]` log-prob tensor whose argmax follows [path]. */
private fun logits(path: IntArray): Array<Array<FloatArray>> {
val frames = Array(path.size) { t ->
FloatArray(42) { -10f }.also { it[path[t]] = 0f }
}
return arrayOf(frames)
}
@Test
fun alphabetSizeMatchesModelMetadata() {
assertEquals("41 symbols + blank = 42 classes", 41, chars.size)
}
@Test
fun greedy_dropsRunsOfTheSameLabel() {
assertEquals("A", CwCtcDecoder.greedy(logits(intArrayOf(14, 14, 14)), chars, blank))
}
@Test
fun greedy_keepsRepeatsSeparatedByBlank() {
// A A <blank> A collapses to "AA": the blank breaks the run.
assertEquals("AA", CwCtcDecoder.greedy(logits(intArrayOf(14, 14, blank, 14)), chars, blank))
}
@Test
fun greedy_allBlanksYieldEmptyString() {
assertEquals("", CwCtcDecoder.greedy(logits(intArrayOf(blank, blank, blank)), chars, blank))
}
@Test
fun greedy_emptyInputYieldsEmptyString() {
assertEquals("", CwCtcDecoder.greedy(logits(intArrayOf()), chars, blank))
}
@Test
fun greedy_decodesCallsignWithSpaceAndDigits() {
// "CQ BG7" — C=16 Q=30 space=40 B=15 G=20 7=10
val path = intArrayOf(
blank, 16, 16, blank, 30, blank, 40,
15, blank, 20, blank, 10, blank
)
assertEquals("CQ BG7", CwCtcDecoder.greedy(logits(path), chars, blank))
}
@Test
fun greedy_picksHighestScoringClassPerFrame() {
// Frame favours S (32) over T (33); only S must survive.
val frame = FloatArray(42) { -10f }
frame[33] = -1f
frame[32] = -0.1f
assertEquals("S", CwCtcDecoder.greedy(arrayOf(arrayOf(frame)), chars, blank))
}
}
@@ -0,0 +1,301 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import org.junit.Assert.*
import org.junit.Test
import kotlin.math.PI
import kotlin.math.sin
class CwDecoderTest {
// --- Morse table ---
@Test
fun morseToChar_basicLetters() {
assertEquals('A', CwBayesianDecoder.morseToChar("01"))
assertEquals('S', CwBayesianDecoder.morseToChar("000"))
assertEquals('O', CwBayesianDecoder.morseToChar("111"))
}
@Test
fun morseToChar_numbers() {
assertEquals('1', CwBayesianDecoder.morseToChar("01111"))
assertEquals('0', CwBayesianDecoder.morseToChar("11111"))
}
@Test
fun morseToChar_unknown_returnsNull() {
assertNull(CwBayesianDecoder.morseToChar("......."))
assertNull(CwBayesianDecoder.morseToChar(""))
}
// --- FFT ---
@Test
fun fft_magnitudeSpectrum_detectsTone() {
val fft = CwFFT(256)
val sampleRate = 8000f
val freq = 700f
val buffer = FloatArray(256) { (sin(2.0 * PI * freq * it / sampleRate)).toFloat() }
val mag = fft.magnitudeSpectrum(buffer)
// Peak should be at bin around 700 * 256 / 8000 ≈ 22.4
var maxBin = 0
var maxVal = 0f
for (i in mag.indices) {
if (mag[i] > maxVal) { maxVal = mag[i]; maxBin = i }
}
assertTrue("Peak bin $maxBin should be near 22", maxBin in 18..26)
assertTrue("Peak value $maxVal should be positive", maxVal > 0.01f)
}
@Test
fun fft_magnitudeSpectrum_silence_isFlat() {
val fft = CwFFT(256)
val buffer = FloatArray(256) { 0f }
val mag = fft.magnitudeSpectrum(buffer)
for (v in mag) assertEquals("Silence spectrum should be 0, got $v", 0f, v, 1e-6f)
}
@Test
fun fft_rejectsWrongSize() {
assertThrows(IllegalArgumentException::class.java) { CwFFT(100) }
}
// --- Spectrogram ---
@Test
fun spectrogram_addSamples_updatesEnergy() {
val spec = CwSpectrogram(sampleRate = 8000)
val freq = 700f
// Feed multiple frames to stabilize energy normalization
for (i in 0..5) {
val buffer = FloatArray(256) { (sin(2.0 * PI * freq * it / 8000.0)).toFloat() }
spec.addSamples(buffer)
}
val col = spec.getCurrentColumn()
val peakBin = spec.findPeakBin()
assertTrue("Peak bin $peakBin should be >= 0", peakBin >= 0)
}
@Test
fun spectrogram_findPeakBin_returnsValidBin() {
val spec = CwSpectrogram(sampleRate = 8000)
// Add multiple frames of 700 Hz tone
for (i in 0..5) {
val buffer = FloatArray(256) { (sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() }
spec.addSamples(buffer)
}
val peakBin = spec.findPeakBin()
assertTrue("Peak bin should be >= 0, got $peakBin", peakBin >= 0)
}
@Test
fun spectrogram_freqToBin_roundtrip() {
val spec = CwSpectrogram(sampleRate = 8000)
val freq = 700f
val bin = spec.freqToBin(freq)
val backFreq = spec.binToFreq(bin)
assertTrue("Freq $freq → bin $bin → freq $backFreq", backFreq > 600f && backFreq < 800f)
}
@Test
fun spectrogram_getBinEnergy_returnsCorrectLength() {
val spec = CwSpectrogram(sampleRate = 8000)
val energy = spec.getBinEnergy(0, 10)
assertEquals(10, energy.size)
}
@Test
fun spectrogram_reset() {
val spec = CwSpectrogram(sampleRate = 8000)
spec.addSamples(FloatArray(256) { 1f })
spec.reset()
assertEquals(-1, spec.findPeakBin())
}
// --- Bayesian decoder ---
@Test
fun bayesian_processTone_dit() {
val decoder = CwBayesianDecoder()
// At 20 WPM, dot = 60 ms
val result = decoder.processTone(60f)
assertEquals('0', result.symbol)
assertTrue("Dit probability should be positive", result.probability > 0.1f)
}
@Test
fun bayesian_processTone_dash() {
val decoder = CwBayesianDecoder()
// Dash = 3 * dot = 180 ms
val result = decoder.processTone(180f)
assertEquals('1', result.symbol)
assertTrue("Dash probability should be positive", result.probability > 0.1f)
}
@Test
fun bayesian_processTone_unknown_returnsNull() {
val decoder = CwBayesianDecoder()
// Very long tone — low probability for both dit and dash
val result = decoder.processTone(5000f)
assertNull(result.symbol)
}
@Test
fun bayesian_processGap_interChar_returnsChar() {
val decoder = CwBayesianDecoder()
decoder.processTone(60f) // dit
decoder.processTone(60f) // dit
decoder.processTone(60f) // dit
// 3 dots = "000" = 'S'
val char = decoder.processGap(180f) // 3 * dot = inter-char gap
assertEquals('S', char)
}
@Test
fun bayesian_processGap_wordGap_addsSpace() {
val decoder = CwBayesianDecoder()
decoder.processTone(60f) // dit = 'E'
decoder.processGap(180f) // inter-char gap
// Now word gap
val space = decoder.processGap(420f) // 7 * dot
assertEquals(' ', space)
}
@Test
fun bayesian_decodedText_accumulates() {
val decoder = CwBayesianDecoder()
decoder.processTone(60f) // dit = 'E'
decoder.processGap(180f) // inter-char
assertTrue(decoder.decodedText.isNotEmpty())
}
@Test
fun bayesian_reset() {
val decoder = CwBayesianDecoder()
decoder.processTone(60f)
decoder.reset()
assertEquals("", decoder.decodedText)
}
@Test
fun bayesian_getSpeed() {
val decoder = CwBayesianDecoder()
// Send 3 dits at 20 WPM (60 ms each)
decoder.processTone(60f)
decoder.processTone(60f)
decoder.processTone(60f)
val speed = decoder.getSpeed()
assertTrue("Speed should be ~20 WPM, got $speed", speed > 15f && speed < 30f)
}
// --- Channel tracker ---
@Test
fun channelTracker_initialState() {
val spec = CwSpectrogram(sampleRate = 8000)
val tracker = CwChannelTracker(spec)
val channels = tracker.update()
assertTrue("No channels should be active initially", channels.isEmpty())
}
@Test
fun channelTracker_detectsTone() {
val spec = CwSpectrogram(sampleRate = 8000)
// Feed a tone
for (i in 0..5) {
spec.addSamples(FloatArray(256) { (sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() })
}
val tracker = CwChannelTracker(spec)
val channels = tracker.update()
assertTrue("Should detect at least 1 channel", channels.isNotEmpty())
}
@Test
fun channelTracker_bestChannel() {
val spec = CwSpectrogram(sampleRate = 8000)
for (i in 0..5) {
spec.addSamples(FloatArray(256) { (sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() })
}
val tracker = CwChannelTracker(spec)
tracker.update()
val best = tracker.getBestChannel()
assertNotNull("Best channel should exist", best)
if (best != null) assertTrue(best.frequency in 600f..800f)
}
@Test
fun channelTracker_reset() {
val spec = CwSpectrogram(sampleRate = 8000)
for (i in 0..5) {
spec.addSamples(FloatArray(256) { (sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() })
}
val tracker = CwChannelTracker(spec)
tracker.update()
tracker.reset()
assertNull(tracker.getBestChannel())
}
// --- Full decoder ---
@Test
fun decoder_initialState() {
val decoder = CwDecoder()
assertEquals("", decoder.decodedTextFlow.value)
assertEquals(0f, decoder.signalStrength.value, 0.001f)
}
@Test
fun decoder_processSilence_doesNotCrash() {
val decoder = CwDecoder()
decoder.processBuffer(FloatArray(256) { 0f })
assertEquals("", decoder.decodedTextFlow.value)
}
@Test
fun decoder_processNoise_doesNotCrash() {
val decoder = CwDecoder()
decoder.processBuffer(FloatArray(256) { (Math.random() * 2 - 1).toFloat() * 0.1f })
assertNotNull(decoder.decodedTextFlow.value)
}
@Test
fun decoder_processTone_doesNotCrash() {
val decoder = CwDecoder()
for (i in 0..20) {
decoder.processBuffer(FloatArray(256) { (sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() })
}
assertNotNull(decoder.decodedTextFlow.value)
}
@Test
fun decoder_reset() {
val decoder = CwDecoder()
decoder.processBuffer(FloatArray(256) { 1f })
decoder.resetDecoder()
assertEquals("", decoder.decodedTextFlow.value)
assertEquals(0f, decoder.signalStrength.value, 0.001f)
}
@Test
fun decoder_withFixedPitch() {
val decoder = CwDecoder(sampleRate = 8000, cwToneFreq = 700f)
assertEquals(700f, decoder.estimatedPitch.value)
}
}
@@ -1,152 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The rolling audio buffer feeding DeepCW.
*
* DeepCW is a whole-segment CTC model, not a sample-by-sample decoder: it
* rewrites earlier output whenever more context arrives, so incremental
* stitching is impossible. Instead we keep a bounded window and re-decode all
* of it periodically, replacing the displayed text.
*/
class CwDeepBufferTest {
@Test
fun capacityIsCappedAtMaxSeconds() {
val buffer = CwDeepBuffer(sampleRate = 3200, maxSeconds = 20.0)
repeat(30) { buffer.append(FloatArray(3200)) }
assertEquals(3200 * 20, buffer.size)
}
@Test
fun oldestSamplesAreDiscardedFirst() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f))
buffer.append(floatArrayOf(4f, 5f))
assertArrayEquals(floatArrayOf(2f, 3f, 4f, 5f), buffer.snapshot(), 0f)
}
@Test
fun snapshotIsChronologicalAfterWrapAround() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f))
assertArrayEquals(floatArrayOf(3f, 4f, 5f, 6f), buffer.snapshot(), 0f)
}
@Test
fun appendLargerThanCapacityKeepsOnlyTheTail() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f))
assertEquals(4, buffer.size)
assertArrayEquals(floatArrayOf(6f, 7f, 8f, 9f), buffer.snapshot(), 0f)
}
@Test
fun redecodeIsSignalledOncePerInterval() {
// 1.5 s at 3200 Hz is 4800 samples; 1600 samples is 0.5 s.
val buffer = CwDeepBuffer(3200, 20.0, redecodeIntervalMs = 1500)
assertFalse("1.0s elapsed: interval not reached", buffer.append(FloatArray(3200)))
assertTrue("1.5s elapsed: first trigger", buffer.append(FloatArray(1600)))
assertFalse("2.0s: only 0.5s since trigger", buffer.append(FloatArray(1600)))
assertFalse("2.5s: only 1.0s since trigger", buffer.append(FloatArray(1600)))
assertTrue("3.0s: 1.5s since trigger, fires again", buffer.append(FloatArray(1600)))
}
@Test
fun redecodeIntervalDoesNotDriftOverManyChunks() {
// 100 ms chunks, as AudioCapture emits them: exactly 15 chunks per
// 1.5 s interval, so 150 chunks must fire exactly 10 times.
val buffer = CwDeepBuffer(3200, 20.0, redecodeIntervalMs = 1500)
var fired = 0
repeat(150) { if (buffer.append(FloatArray(320))) fired++ }
assertEquals(10, fired)
}
@Test
fun snapshotDoesNotAliasInternalStorage() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
buffer.snapshot()[0] = 99f
assertEquals("caller must not be able to mutate the buffer", 1f, buffer.snapshot()[0], 0f)
}
@Test
fun resetClearsSamplesAndIntervalCounter() {
val buffer = CwDeepBuffer(3200, 20.0, redecodeIntervalMs = 1500)
buffer.append(FloatArray(3200))
buffer.reset()
assertEquals(0, buffer.size)
assertFalse("counter restarted, 1.0s must not trigger", buffer.append(FloatArray(3200)))
}
@Test
fun hasEnoughAudioTracksTheModelMinimum() {
// compute() needs at least FFT_LENGTH samples to produce one frame.
val buffer = CwDeepBuffer(3200, 20.0)
buffer.append(FloatArray(100))
assertFalse(buffer.hasEnoughAudio)
buffer.append(FloatArray(200))
assertTrue(buffer.hasEnoughAudio)
}
@Test
fun defaultsMatchTheMeasuredOptimum() {
// 20s / 1.5s were chosen from measurements: 20s is the smallest window
// reaching 0.0% CER, and keeps inference well inside real time.
val buffer = CwDeepBuffer()
assertEquals(CwDeepSpectrogram.SAMPLE_RATE * 20, buffer.capacity)
}
@Test
fun overflowCollectsEvictedSamplesInOrder() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0) // capacity 4
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
assertEquals("nothing evicted before the window is full", 0, buffer.overflowCount)
buffer.append(floatArrayOf(5f, 6f)) // overwrites 1, 2
assertArrayEquals("evicted samples, oldest first", floatArrayOf(1f, 2f), buffer.drainOverflow(), 0f)
assertArrayEquals("live window still correct", floatArrayOf(3f, 4f, 5f, 6f), buffer.snapshot(), 0f)
}
@Test
fun drainOverflowClearsItself() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
buffer.append(floatArrayOf(5f))
assertEquals(1, buffer.overflowCount)
buffer.drainOverflow()
assertEquals(0, buffer.overflowCount)
assertArrayEquals(FloatArray(0), buffer.drainOverflow(), 0f)
}
@Test
fun resetClearsOverflow() {
val buffer = CwDeepBuffer(sampleRate = 4, maxSeconds = 1.0)
buffer.append(floatArrayOf(1f, 2f, 3f, 4f))
buffer.append(floatArrayOf(5f))
assertEquals(1, buffer.overflowCount)
buffer.reset()
assertEquals(0, buffer.overflowCount)
}
}
@@ -1,130 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
/**
* Pins the Kotlin front-end to the upstream Python reference implementation.
*
* `golden_spec.txt` was produced by deepcw-engine's own preprocessing code
* (numpy reflect padding, `np.hanning(N+1)[:-1]`, `np.fft.rfft`, `log1p`) over
* the audio [generateTestAudio] builds. Both sides synthesise the audio from
* the same deterministic formula, so only the spectrogram needs pinning.
*
* A mismatch here means the model would receive subtly wrong input and emit
* plausible-looking garbage, which is very hard to diagnose downstream — so
* this test guards the whole pipeline.
*
* Regenerate with `scripts/deepcw_gen_golden.py` from the skill library if the
* model metadata ever changes.
*/
class CwDeepGoldenVectorTest {
private companion object {
const val SRC_RATE = 8000
const val TONE_HZ = 700.0
const val AMPLITUDE = 0.6
const val DOT_SAMPLES = 480 // 20 WPM at 8000 Hz: 1.2/20*8000
const val PATTERN = "-.-." // the letter C
const val TOLERANCE = 1e-4f
}
/** Square-keyed 700 Hz tone: 4 dots of silence, "C", 4 dots of silence. */
private fun generateTestAudio(): FloatArray {
val keying = ArrayList<Int>()
repeat(4 * DOT_SAMPLES) { keying.add(0) }
for ((i, element) in PATTERN.withIndex()) {
val length = if (element == '-') 3 * DOT_SAMPLES else DOT_SAMPLES
repeat(length) { keying.add(1) }
if (i < PATTERN.length - 1) repeat(DOT_SAMPLES) { keying.add(0) }
}
repeat(4 * DOT_SAMPLES) { keying.add(0) }
return FloatArray(keying.size) { i ->
if (keying[i] == 1) {
(AMPLITUDE * sin(2.0 * PI * TONE_HZ * i / SRC_RATE)).toFloat()
} else {
0f
}
}
}
private fun readGoldenSpectrogram(): Array<FloatArray> {
val stream = javaClass.classLoader?.getResourceAsStream("cw/golden_spec.txt")
?: throw IllegalStateException("cw/golden_spec.txt missing from test resources")
stream.bufferedReader().use { reader ->
val (frames, bins) = reader.readLine().trim().split(" ").map(String::toInt)
return Array(frames) {
val row = reader.readLine().trim().split(" ")
require(row.size == bins) { "expected $bins values, got ${row.size}" }
FloatArray(bins) { i -> row[i].toFloat() }
}
}
}
@Test
fun spectrogramMatchesPythonReferenceFrameByFrame() {
val expected = readGoldenSpectrogram()
val audio = CwDeepSpectrogram.resampleLinear(
generateTestAudio(), SRC_RATE, CwDeepSpectrogram.SAMPLE_RATE
)
val actual = CwDeepSpectrogram.compute(audio)
assertEquals("frame count", expected.size, actual.size)
assertEquals("bin count", expected[0].size, actual[0].size)
var worstDelta = 0f
var worstAt = ""
for (t in expected.indices) {
for (f in expected[t].indices) {
val delta = abs(expected[t][f] - actual[t][f])
if (delta > worstDelta) {
worstDelta = delta
worstAt = "frame $t bin $f: expected ${expected[t][f]}, got ${actual[t][f]}"
}
}
}
assertTrue(
"front-end diverges from the Python reference — worst delta $worstDelta at $worstAt",
worstDelta <= TOLERANCE
)
}
@Test
fun resampledLengthMatchesReference() {
val audio = generateTestAudio()
assertEquals("source audio length", 9120, audio.size)
val resampled = CwDeepSpectrogram.resampleLinear(
audio, SRC_RATE, CwDeepSpectrogram.SAMPLE_RATE
)
assertEquals("resampled length", 3648, resampled.size)
}
@Test
fun goldenVectorHasExpectedShape() {
val golden = readGoldenSpectrogram()
assertEquals("frames", 77, golden.size)
assertEquals("bins", CwDeepSpectrogram.FREQUENCY_BINS, golden[0].size)
}
}
@@ -1,110 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
/**
* Verifies the DeepCW front-end against the upstream Python reference
* implementation (deepcw-engine examples/python/decode_morse.py).
*
* Model metadata: sampleRate 3200, fftLength 256, hopLength 48,
* 400-1200 Hz -> 65 bins, log1p normalization.
*/
class CwDeepSpectrogramTest {
@Test
fun frequencyBinRange_matchesModelMetadata() {
// binHz = 3200/256 = 12.5; start = ceil(400/12.5) = 32; stop = floor(1200/12.5)+1 = 97
val (start, stop) = CwDeepSpectrogram.frequencyBinRange(3200, 256, 400.0, 1200.0)
assertEquals(32, start)
assertEquals(97, stop)
assertEquals("metadata declares 65 frequency bins", 65, stop - start)
}
@Test
fun compute_producesTimeBy65Matrix() {
// 1 second at 3200 Hz. Reflect padding adds fft/2 on both sides,
// so frames = 1 + (3200 + 256 - 256)/48 = 1 + 66 = 67
val spec = CwDeepSpectrogram.compute(FloatArray(3200))
assertEquals(67, spec.size)
assertEquals(65, spec[0].size)
}
@Test
fun compute_toneLandsInExpectedBin() {
// 700 Hz -> absolute bin 700/12.5 = 56 -> relative index 56 - 32 = 24
val audio = FloatArray(3200) { (0.6 * sin(2.0 * PI * 700.0 * it / 3200.0)).toFloat() }
val spec = CwDeepSpectrogram.compute(audio)
val middle = spec[spec.size / 2]
val peak = middle.indices.maxByOrNull { middle[it] } ?: -1
assertTrue("peak at index $peak, expected near 24", abs(peak - 24) <= 1)
}
@Test
fun compute_appliesLog1pSoValuesAreNonNegative() {
val audio = FloatArray(3200) { (0.6 * sin(2.0 * PI * 700.0 * it / 3200.0)).toFloat() }
val spec = CwDeepSpectrogram.compute(audio)
for (frame in spec) {
for (v in frame) {
assertTrue("log1p of a magnitude must be >= 0, got $v", v >= 0f)
}
}
}
@Test
fun resampleLinear_convertsRateAndLength() {
assertEquals(3200, CwDeepSpectrogram.resampleLinear(FloatArray(8000), 8000, 3200).size)
assertEquals(3200, CwDeepSpectrogram.resampleLinear(FloatArray(44100), 44100, 3200).size)
}
@Test
fun resampleLinear_sameRateIsIdentity() {
val input = floatArrayOf(0.1f, 0.2f, 0.3f)
val out = CwDeepSpectrogram.resampleLinear(input, 3200, 3200)
assertEquals(3, out.size)
assertEquals(0.2f, out[1], 1e-6f)
}
@Test
fun resampleLinear_preservesToneFrequency() {
// A 700 Hz tone sampled at 8000 Hz must still peak at bin 24 after
// resampling to 3200 Hz — this is the path real microphone audio takes.
val at8k = FloatArray(8000) { (0.6 * sin(2.0 * PI * 700.0 * it / 8000.0)).toFloat() }
val at3200 = CwDeepSpectrogram.resampleLinear(at8k, 8000, 3200)
val spec = CwDeepSpectrogram.compute(at3200)
val middle = spec[spec.size / 2]
val peak = middle.indices.maxByOrNull { middle[it] } ?: -1
assertTrue("resampled tone peak at $peak, expected near 24", abs(peak - 24) <= 1)
}
@Test
fun compute_rejectsAudioShorterThanFftLength() {
try {
CwDeepSpectrogram.compute(FloatArray(100))
throw AssertionError("expected an exception for audio shorter than fftLength")
} catch (expected: IllegalArgumentException) {
// desired path
}
}
}
@@ -0,0 +1,180 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.core.domain.cw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.PI
import kotlin.math.sin
/**
* Tests for the fldigi-ported CW decoder. Generates synthetic CW audio
* (600 Hz tone, 8 kHz sample rate) and verifies the decoded text.
*/
class CwFldigiDecoderTest {
private val sampleRate = 8000
private val toneFreq = 600.0
/** Synthesize a CW audio buffer for a dot-dash pattern at given WPM. */
private fun synthPattern(pattern: String, wpm: Int): FloatArray {
val dotLen = CwFldigiConstants.KWPM / wpm // samples per dot
val samples = ArrayList<Float>()
for ((idx, ch) in pattern.withIndex()) {
val len = if (ch == '.') dotLen else 3 * dotLen
for (i in 0 until len) {
val t = i.toDouble() / sampleRate
samples.add((0.6 * sin(2.0 * PI * toneFreq * t)).toFloat())
}
if (idx < pattern.length - 1) {
for (i in 0 until dotLen) samples.add(0f) // intra-char gap
}
}
return samples.toFloatArray()
}
/** Append an inter-character gap (3 dot lengths) of silence. */
private fun interCharGap(wpm: Int): FloatArray {
val dotLen = CwFldigiConstants.KWPM / wpm
return FloatArray(3 * dotLen)
}
private fun decodeSequence(chars: List<String>, wpm: Int, useSom: Boolean = true): String {
val decoder = CwFldigiDecoder(sampleRate = sampleRate, frequency = toneFreq, useSom = useSom)
val dotLen = CwFldigiConstants.KWPM / wpm
for ((ci, pattern) in chars.withIndex()) {
decoder.processBuffer(synthPattern(pattern, wpm))
decoder.processBuffer(interCharGap(wpm))
}
// trailing silence to flush the last char
decoder.processBuffer(FloatArray(8 * dotLen))
return decoder.decodedTextFlow.value
}
@Test
fun decode_basicLetter_singleDot() {
val decoder = CwFldigiDecoder(sampleRate = sampleRate, frequency = toneFreq)
decoder.processBuffer(synthPattern(".", 18))
decoder.processBuffer(FloatArray(8 * CwFldigiConstants.KWPM / 18))
assertTrue("expected E in output, got: ${decoder.decodedTextFlow.value}",
decoder.decodedTextFlow.value.startsWith("E"))
}
@Test
fun decode_word_CQ_18wpm() {
val text = decodeSequence(listOf("-.-.", "--.-"), 18)
assertTrue("expected CQ in output, got: $text", text.contains("C") && text.contains("Q"))
}
@Test
fun decode_hello_20wpm() {
val text = decodeSequence(listOf("....", ".", ".-..", ".-..", "---"), 20)
assertTrue("expected HELLO in output, got: $text", text.contains("H"))
}
@Test
fun decode_adaptive_speed_30wpm() {
// Realistic usage: decoder configured near the signal speed, tracking
// fine-tunes from there. Verify correct decode at 30 wpm.
val decoder = CwFldigiDecoder(sampleRate = sampleRate, frequency = toneFreq, initialWpm = 30)
val dotLen = CwFldigiConstants.KWPM / 30
for (pattern in listOf(".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---")) {
decoder.processBuffer(synthPattern(pattern, 30))
decoder.processBuffer(interCharGap(30))
}
decoder.processBuffer(FloatArray(8 * dotLen))
val text = decoder.decodedTextFlow.value
// First char may be off while tracking converges; rest must be exact.
assertTrue("expected B-J at 30wpm, got: $text", text.contains("B") && text.contains("J"))
}
@Test
fun reset_clearsState() {
val decoder = CwFldigiDecoder(sampleRate = sampleRate, frequency = toneFreq)
decoder.processBuffer(synthPattern(".", 18))
decoder.processBuffer(FloatArray(8 * CwFldigiConstants.KWPM / 18))
decoder.resetDecoder()
assertEquals("", decoder.decodedTextFlow.value)
}
@Test
fun morseTable_lookup() {
assertEquals("A", MorseTable.rxLookup(".-"))
assertEquals("S", MorseTable.rxLookup("..."))
assertEquals("1", MorseTable.rxLookup(".----"))
assertEquals("?", MorseTable.rxLookup("..--.."))
assertEquals("", MorseTable.rxLookup("........"))
}
@Test
fun somTable_hasAllAsciiLetters() {
val patterns = SomTable.table.map { it.pattern }.toSet()
val letters = listOf(".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..")
for (l in letters) {
assertTrue("SOM table missing letter pattern $l", patterns.contains(l))
}
}
@Test
fun fftFilter_lowpass_passesTone() {
val filt = CwFftFilt(600.0 / 8000.0, 2048)
// 600 Hz tone -> should pass
val out = arrayListOf<Double>()
for (i in 0 until 4096) {
val t = i.toDouble() / 8000.0
val z = CwComplex(0.5 * sin(2.0 * PI * 600.0 * t), 0.0)
filt.run(z)?.let { o -> for (j in 0 until 1024) out.add(o[j].abs()) }
}
val maxVal = out.maxOrNull() ?: 0.0
assertTrue("expected signal to pass through lowpass, max=$maxVal", maxVal > 0.05)
}
@Test
fun autoTune_decodesOffFreqSignal() {
// Signal at 900 Hz but decoder initialized at 600 Hz: auto-tune must
// steer the NCO to the real tone, otherwise nothing decodes.
val decoder = CwFldigiDecoder(sampleRate = sampleRate, frequency = 600.0)
val dotLen = CwFldigiConstants.KWPM / 18
val synth = { ch: Char ->
val len = if (ch == '.') dotLen else 3 * dotLen
FloatArray(len) { i ->
val t = i.toDouble() / sampleRate
(0.6 * sin(2.0 * PI * 900.0 * t)).toFloat()
}
}
// "CQ" at 900 Hz: -.-. --.-
val text = StringBuilder()
val seq = listOf(listOf('-', '.', '-', '.'), listOf('-', '-', '.', '-'))
for ((ci, word) in seq.withIndex()) {
for ((i, ch) in word.withIndex()) {
decoder.processBuffer(synth(ch))
if (i < word.size - 1) decoder.processBuffer(FloatArray(dotLen))
}
if (ci < seq.size - 1) decoder.processBuffer(FloatArray(3 * dotLen))
}
decoder.processBuffer(FloatArray(6 * dotLen))
val result = decoder.decodedTextFlow.value
assertTrue("expected CQ from 900 Hz signal (auto-tune), got: $result", result.contains("C") && result.contains("Q"))
// pitch should have moved toward 900 Hz
val pitch = decoder.estimatedPitch.value ?: 0f
assertTrue("expected pitch near 900, got $pitch", pitch > 800f && pitch < 1000f)
}
}
@@ -0,0 +1,92 @@
package com.rtbishop.look4sat.core.domain.wavelog
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Locale
/**
* Verifies the WaveLog upload payload frequency/band fields.
*
* Regression: user reported QSOs landing in the 160m band. The v2 JSON
* envelope must carry freq as a MHz string with an "M" suffix so WaveLog's
* parse_frequency() reads it as Hz internally; a bare integer or bare MHz
* value corrupts band derivation.
*/
class WaveLogApiPayloadTest {
// SO-50: uplink 145.850 MHz, downlink 436.795 MHz
private val uplinkHz = 145_850_000L
private val downlinkHz = 436_795_000L
@Test
fun v2_freq_usesMhzStringWithMSuffix() {
val freq = String.format(Locale.ENGLISH, "%.6fM", uplinkHz / 1_000_000.0)
val freqRx = String.format(Locale.ENGLISH, "%.6fM", downlinkHz / 1_000_000.0)
assertEquals("145.850000M", freq)
assertEquals("436.795000M", freqRx)
// WaveLog parse_frequency: "145.850000M" -> 145850000 Hz
val parsedHz = parseLikeWaveLog(freq)
assertEquals(uplinkHz, parsedHz)
}
@Test
fun v1_adif_freq_isBareMhzNumber() {
// v1 ADIF <FREQ> is a bare MHz number per ADIF spec (no unit suffix)
val freq = String.format(Locale.ENGLISH, "%.6f", uplinkHz / 1_000_000.0)
assertEquals("145.850000", freq)
val adifFreq = freq.toDouble() * 1_000_000
assertEquals(uplinkHz.toDouble(), adifFreq, 1.0)
}
/** Mirrors WaveLog Logbook_model::parse_frequency: int = Hz, "12.3M" suffix = MHz. */
private fun parseLikeWaveLog(raw: String): Long {
val s = raw.trim()
return if (s.endsWith("M", ignoreCase = true)) {
(s.dropLast(1).toDouble() * 1_000_000).toLong()
} else if (s.endsWith("k", ignoreCase = true)) {
(s.dropLast(1).toDouble() * 1_000).toLong()
} else {
s.toLong()
}
}
@Test
fun qsoFreqs_stayInSatelliteBands_afterDoppler() {
// Doppler-corrected values must remain near the base frequency.
// SPEED_OF_LIGHT = 299792458 m/s; distanceRate is km/s (x1000 -> m/s).
val dopplerRate = 7.0 // km/s approaching
val corrected = uplinkHz * (299_792_458.0 + dopplerRate * 1000.0) / 299_792_458.0
assertTrue(
"corrected within +-20kHz, got ${corrected - uplinkHz} Hz",
kotlin.math.abs(corrected - uplinkHz) < 20_000
)
// band derivation: 145.x MHz -> 2m, never 160m (1.8-2.0 MHz)
val mhz = corrected / 1_000_000.0
assertTrue("145.x MHz stays in 2m, got $mhz MHz", mhz in 144.0..148.0)
}
@Test
fun band_isRealBand_notSAT() {
// SO-50: TX 145.850 MHz (VHF) -> band 2M, sat mode V/U
assertEquals("2M", WaveLogApi.bandFromHz(145_850_000))
assertEquals("V/U", WaveLogApi.satModeFrom(145_850_000, 436_795_000))
// AO-73: TX 435.150 MHz (UHF up), RX 145.950 MHz (VHF down) -> band 70CM, U/V
assertEquals("70CM", WaveLogApi.bandFromHz(435_150_000))
assertEquals("U/V", WaveLogApi.satModeFrom(435_150_000, 145_950_000))
// Same-band (e.g. simplex) -> empty sat mode
assertEquals("", WaveLogApi.satModeFrom(145_850_000, 145_950_000))
// Never 160m for satellite frequencies
assertTrue(WaveLogApi.bandFromHz(145_850_000) != "160M")
assertTrue(WaveLogApi.bandFromHz(436_795_000) != "160M")
}
@Test
fun adif_containsRealBandAndSatMode() {
// v2 payload fields (mirror postQso construction)
val band = WaveLogApi.bandFromHz(uplinkHz)
val satMode = WaveLogApi.satModeFrom(uplinkHz, downlinkHz)
assertEquals("2M", band)
assertEquals("V/U", satMode)
}
}
@@ -1,78 +0,0 @@
77 65
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0.07889045 0.08153424 0.08419035 0.08701893 0.09030894 0.09436007 0.09932096 0.1050817 0.1113084 0.1176305 0.1239188 0.1305645 0.1386389 0.1497532 0.1654913 0.1866336 0.2127252 0.2422527 0.2731474 0.3032433 0.3305584 0.3534314 0.3705729 0.3810754 0.3844073 0.3804049 0.3692688 0.3515675 0.3282437 0.3006178 0.2703726 0.239492 0.2101091 0.1842086 0.1631677 0.1472881 0.1356851 0.126759 0.1189501 0.1112676 0.1034146 0.09563871 0.0884626 0.08238604 0.07764256 0.07410739 0.07139879 0.06908784 0.06687377 0.06464756 0.06245377 0.06040035 0.05856907 0.05696608 0.05552753 0.05416456 0.05281367 0.05146397 0.05015182 0.0489313 0.04783952 0.04687586 0.04600478 0.04517753 0.04435825
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.07889044 0.08153418 0.08419043 0.08701882 0.09030894 0.09435995 0.09932118 0.1050815 0.1113084 0.1176306 0.1239187 0.1305645 0.1386389 0.1497532 0.1654913 0.1866337 0.2127252 0.2422527 0.2731474 0.3032434 0.3305583 0.3534314 0.3705729 3.007106 3.643108 3.00695 0.3692689 0.3515675 0.3282436 0.300618 0.2703725 0.239492 0.210109 0.1842086 0.1631676 0.1472882 0.1356852 0.1267589 0.1189501 0.3679682 0.5516769 0.2577798 0.08846281 0.08238595 0.07764257 0.07410715 0.07139895 0.06908786 0.06687377 0.06464756 0.06245382 0.06040037 0.05856909 0.05696621 0.05552716 0.0541646 0.05281365 0.05146411 0.05015175 0.04893123 0.04783951 0.04687591 0.0460047 0.04517756 0.04435825
1.564492e-07 1.122884e-07 8.888702e-08 1.762498e-07 8.600421e-09 1.938033e-07 2.387622e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.498516e-08 5.176826e-08 1.897711e-07 8.593484e-08 4.070753e-08 7.40209e-08 2.278317e-07 8.807671e-08 9.716474e-08 1.372644e-07 1.501705e-07 2.285518e-08 9.67386e-08 2.987679 3.6553 2.987679 1.266364e-07 1.456021e-08 5.034151e-08 2.597979e-07 1.838301e-07 6.343754e-08 8.150528e-08 5.003271e-09 9.525829e-08 2.182818e-07 1.843608e-07 1.385002e-08 6.420205e-09 0.3078006 0.542824 0.3078008 2.254644e-07 1.478402e-07 1.590096e-07 3.480243e-07 1.698739e-07 5.310058e-08 4.452434e-08 4.024338e-09 5.150024e-08 2.914611e-08 1.276424e-07 1.826463e-07 3.983407e-07 5.450444e-08 2.266521e-07 1.942693e-07 7.255422e-08 1.167992e-07 1.510635e-07 6.353517e-08 7.878904e-08 3.480655e-08 4.585462e-09
1.564492e-07 1.122884e-07 8.888694e-08 1.762498e-07 8.600284e-09 1.938033e-07 2.387623e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.498505e-08 5.176823e-08 1.897709e-07 8.593484e-08 4.070745e-08 7.402096e-08 2.278317e-07 8.807665e-08 9.716481e-08 1.372644e-07 1.501703e-07 2.285522e-08 9.673848e-08 2.987679 3.6553 2.987679 1.266363e-07 1.456018e-08 5.034165e-08 2.597979e-07 1.8383e-07 6.34376e-08 8.150528e-08 5.003333e-09 9.525822e-08 2.182818e-07 1.843609e-07 1.385006e-08 6.420322e-09 0.3078006 0.542824 0.3078008 2.254643e-07 1.478403e-07 1.590095e-07 3.480243e-07 1.698739e-07 5.310051e-08 4.452434e-08 4.0244e-09 5.150032e-08 2.914612e-08 1.276426e-07 1.826462e-07 3.983408e-07 5.450447e-08 2.266521e-07 1.942694e-07 7.255434e-08 1.167993e-07 1.510637e-07 6.353518e-08 7.878896e-08 3.480649e-08 4.585462e-09
1.564492e-07 1.122884e-07 8.888694e-08 1.762499e-07 8.600289e-09 1.938033e-07 2.387623e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.498504e-08 5.176823e-08 1.897709e-07 8.593484e-08 4.070745e-08 7.402096e-08 2.278317e-07 8.807665e-08 9.716482e-08 1.372644e-07 1.501703e-07 2.285522e-08 9.673848e-08 2.987679 3.6553 2.987679 1.266363e-07 1.456017e-08 5.034164e-08 2.597979e-07 1.8383e-07 6.34376e-08 8.150528e-08 5.003331e-09 9.525821e-08 2.182818e-07 1.843609e-07 1.385006e-08 6.420325e-09 0.3078006 0.542824 0.3078008 2.254643e-07 1.478403e-07 1.590095e-07 3.480243e-07 1.698739e-07 5.310052e-08 4.452434e-08 4.024398e-09 5.150032e-08 2.914612e-08 1.276426e-07 1.826462e-07 3.983408e-07 5.450447e-08 2.266521e-07 1.942694e-07 7.255434e-08 1.167993e-07 1.510637e-07 6.353518e-08 7.878896e-08 3.480649e-08 4.585462e-09
1.564492e-07 1.122884e-07 8.888702e-08 1.762499e-07 8.600421e-09 1.938034e-07 2.387622e-07 2.871271e-07 2.21893e-07 1.239546e-07 8.498516e-08 5.176833e-08 1.897711e-07 8.593477e-08 4.070753e-08 7.402097e-08 2.278317e-07 8.807664e-08 9.716474e-08 1.372644e-07 1.501705e-07 2.285512e-08 9.67386e-08 2.987679 3.6553 2.987679 1.266364e-07 1.456028e-08 5.034151e-08 2.59798e-07 1.838301e-07 6.343761e-08 8.150528e-08 5.003339e-09 9.525829e-08 2.182819e-07 1.843608e-07 1.384995e-08 6.420205e-09 0.3078006 0.542824 0.3078008 2.254644e-07 1.478402e-07 1.590096e-07 3.480242e-07 1.698739e-07 5.310051e-08 4.452434e-08 4.024406e-09 5.150024e-08 2.914618e-08 1.276424e-07 1.826463e-07 3.983407e-07 5.450437e-08 2.266521e-07 1.942693e-07 7.255422e-08 1.167992e-07 1.510635e-07 6.353524e-08 7.878904e-08 3.480648e-08 4.585462e-09
1.564492e-07 1.122885e-07 8.888715e-08 1.762501e-07 8.600158e-09 1.938033e-07 2.387623e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.498502e-08 5.176819e-08 1.897708e-07 8.593463e-08 4.070766e-08 7.402083e-08 2.278317e-07 8.807678e-08 9.716461e-08 1.372642e-07 1.501702e-07 2.285526e-08 9.673845e-08 2.987679 3.6553 2.987679 1.266363e-07 1.456013e-08 5.034177e-08 2.597981e-07 1.838302e-07 6.343747e-08 8.150528e-08 5.003199e-09 9.525842e-08 2.18282e-07 1.843611e-07 1.38501e-08 6.420349e-09 0.3078006 0.542824 0.3078008 2.254643e-07 1.478403e-07 1.590094e-07 3.480241e-07 1.698737e-07 5.310065e-08 4.452434e-08 4.024266e-09 5.150011e-08 2.914633e-08 1.276427e-07 1.826462e-07 3.983409e-07 5.45045e-08 2.266521e-07 1.942694e-07 7.255437e-08 1.167993e-07 1.510638e-07 6.353538e-08 7.878917e-08 3.480662e-08 4.585462e-09
1.564492e-07 1.122885e-07 8.888713e-08 1.762501e-07 8.600153e-09 1.938034e-07 2.387623e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.498504e-08 5.176827e-08 1.897708e-07 8.593455e-08 4.070764e-08 7.402088e-08 2.278317e-07 8.807672e-08 9.716463e-08 1.372642e-07 1.501702e-07 2.285517e-08 9.673848e-08 2.987679 3.6553 2.987679 1.266363e-07 1.456022e-08 5.034178e-08 2.597982e-07 1.838302e-07 6.343753e-08 8.150528e-08 5.003255e-09 9.52584e-08 2.182821e-07 1.843611e-07 1.385001e-08 6.420325e-09 0.3078006 0.542824 0.3078008 2.254643e-07 1.478402e-07 1.590094e-07 3.48024e-07 1.698737e-07 5.310059e-08 4.452434e-08 4.024322e-09 5.150013e-08 2.91464e-08 1.276427e-07 1.826463e-07 3.983408e-07 5.450445e-08 2.266521e-07 1.942693e-07 7.255434e-08 1.167992e-07 1.510638e-07 6.353546e-08 7.878916e-08 3.480656e-08 4.585462e-09
1.564492e-07 1.122884e-07 8.888702e-08 1.762501e-07 8.600201e-09 1.938033e-07 2.387621e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.49852e-08 5.176818e-08 1.897709e-07 8.59346e-08 4.070753e-08 7.402099e-08 2.278317e-07 8.807662e-08 9.716474e-08 1.372642e-07 1.501702e-07 2.285526e-08 9.673864e-08 2.987679 3.6553 2.987679 1.266365e-07 1.456013e-08 5.034173e-08 2.597982e-07 1.838301e-07 6.343763e-08 8.150528e-08 5.00336e-09 9.525829e-08 2.182821e-07 1.84361e-07 1.38501e-08 6.420163e-09 0.3078006 0.542824 0.3078008 2.254645e-07 1.478403e-07 1.590094e-07 3.480241e-07 1.698739e-07 5.310049e-08 4.452434e-08 4.024427e-09 5.150024e-08 2.914636e-08 1.276426e-07 1.826462e-07 3.983407e-07 5.450442e-08 2.266521e-07 1.942693e-07 7.255419e-08 1.167993e-07 1.510638e-07 6.353542e-08 7.878904e-08 3.480646e-08 4.585462e-09
0.07889044 0.08153418 0.08419043 0.08701882 0.09030894 0.09435995 0.09932118 0.1050815 0.1113084 0.1176306 0.1239187 0.1305645 0.1386389 0.1497532 0.1654913 0.1866337 0.2127252 0.2422527 0.2731474 0.3032434 0.3305583 0.3534314 0.3705729 3.007106 3.643108 3.00695 0.3692689 0.3515675 0.3282436 0.300618 0.2703725 0.239492 0.210109 0.1842086 0.1631676 0.1472882 0.1356852 0.1267589 0.1189501 0.3679682 0.5516769 0.2577798 0.08846281 0.08238595 0.07764257 0.07410715 0.07139895 0.06908786 0.06687377 0.06464756 0.06245382 0.06040037 0.05856909 0.05696621 0.05552716 0.0541646 0.05281365 0.05146411 0.05015175 0.04893123 0.04783951 0.04687591 0.0460047 0.04517756 0.04435825
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.0133671 0.103174 0.161102 0.1321454 0.01981753 0.1171069 0.1886141 0.1606799 0.03154613 0.1368369 0.230862 0.208004 0.05647711 0.1650847 0.3020293 0.298915 0.1252058 0.1979204 0.4401451 0.5311838 0.4472875 0.1536819 0.2990841 0.5738236 0.6613865 0.5702119 0.2925259 0.1586363 0.4468553 0.5274072 0.4351405 0.1946639 0.1232734 0.2943546 0.2986827 0.1671092 0.04655298 0.1966405 0.2236971 0.1398044 0.01435895 0.1384342 0.1696025 0.109466 0.009560954 0.1101514 0.1376043 0.08825757 0.01127213 0.09668601 0.1209162 0.07821064 0.008807627 0.0850097 0.1078746 0.07068323 0.006762736 0.07595089 0.09776526 0.06483996 0.005235632 0.0689388 0.08987227 0.0602516 0.004088645
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.01336695 0.1031739 0.161102 0.1321453 0.01981753 0.1171067 0.1886142 0.1606797 0.03154635 0.1368371 0.2308619 0.2080039 0.05647729 0.1650848 0.3020293 0.298915 0.1252055 0.1979204 0.440145 0.531184 0.4472874 0.1536818 0.299084 3.026 3.630765 3.02569 0.2925259 0.1586363 0.4468552 0.5274073 0.4351404 0.1946639 0.1232734 0.2943546 0.2986827 0.1671094 0.04655316 0.1966404 0.2236971 0.4124265 0.5511931 0.1922355 0.1696027 0.1094658 0.009561111 0.110151 0.1376044 0.08825763 0.01127217 0.09668601 0.1209163 0.07821067 0.008807753 0.08500987 0.1078743 0.07068328 0.00676251 0.07595107 0.0977652 0.06483985 0.005235482 0.06893886 0.0898722 0.06025163 0.004088641
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.0133671 0.103174 0.161102 0.1321454 0.01981753 0.1171069 0.1886141 0.1606799 0.03154613 0.1368369 0.230862 0.208004 0.05647711 0.1650847 0.3020293 0.298915 0.1252058 0.1979204 0.4401451 0.5311838 0.4472875 0.1536819 0.2990841 0.5738236 0.6613865 0.5702119 0.2925259 0.1586363 0.4468553 0.5274072 0.4351405 0.1946639 0.1232734 0.2943546 0.2986827 0.1671092 0.04655298 0.1966405 0.2236971 0.1398044 0.01435895 0.1384342 0.1696025 0.109466 0.009560954 0.1101514 0.1376043 0.08825757 0.01127213 0.09668601 0.1209162 0.07821064 0.008807627 0.0850097 0.1078746 0.07068323 0.006762736 0.07595089 0.09776526 0.06483996 0.005235632 0.0689388 0.08987227 0.0602516 0.004088645
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.07889044 0.08153418 0.08419043 0.08701882 0.09030894 0.09435995 0.09932118 0.1050815 0.1113084 0.1176306 0.1239187 0.1305645 0.1386389 0.1497532 0.1654913 0.1866337 0.2127252 0.2422527 0.2731474 0.3032434 0.3305583 0.3534314 0.3705729 3.007106 3.643108 3.00695 0.3692689 0.3515675 0.3282436 0.300618 0.2703725 0.239492 0.210109 0.1842086 0.1631676 0.1472882 0.1356852 0.1267589 0.1189501 0.3679682 0.5516769 0.2577798 0.08846281 0.08238595 0.07764257 0.07410715 0.07139895 0.06908786 0.06687377 0.06464756 0.06245382 0.06040037 0.05856909 0.05696621 0.05552716 0.0541646 0.05281365 0.05146411 0.05015175 0.04893123 0.04783951 0.04687591 0.0460047 0.04517756 0.04435825
1.564492e-07 1.122885e-07 8.888702e-08 1.762501e-07 8.600116e-09 1.938031e-07 2.387619e-07 2.871269e-07 2.21893e-07 1.239548e-07 8.498547e-08 5.176805e-08 1.897708e-07 8.59346e-08 4.070753e-08 7.402088e-08 2.278317e-07 8.807672e-08 9.716474e-08 1.372642e-07 1.501702e-07 2.28554e-08 9.673891e-08 2.987679 3.6553 2.987679 1.266367e-07 1.456e-08 5.034181e-08 2.597982e-07 1.838301e-07 6.343753e-08 8.150528e-08 5.003254e-09 9.525829e-08 2.182821e-07 1.843611e-07 1.385024e-08 6.419893e-09 0.3078006 0.542824 0.3078008 2.254647e-07 1.478404e-07 1.590093e-07 3.480241e-07 1.698739e-07 5.31006e-08 4.452434e-08 4.024321e-09 5.150024e-08 2.914635e-08 1.276427e-07 1.82646e-07 3.983404e-07 5.450418e-08 2.266521e-07 1.942691e-07 7.255392e-08 1.167995e-07 1.510639e-07 6.353541e-08 7.878904e-08 3.480657e-08 4.585462e-09
1.564492e-07 1.122886e-07 8.888708e-08 1.762499e-07 8.600304e-09 1.938035e-07 2.387625e-07 2.871271e-07 2.21893e-07 1.239546e-07 8.49849e-08 5.176842e-08 1.89771e-07 8.593476e-08 4.070759e-08 7.402079e-08 2.278317e-07 8.807682e-08 9.716468e-08 1.372644e-07 1.501704e-07 2.285502e-08 9.673834e-08 2.987679 3.6553 2.987679 1.266362e-07 1.456037e-08 5.034163e-08 2.59798e-07 1.838302e-07 6.343743e-08 8.150528e-08 5.003165e-09 9.525835e-08 2.182819e-07 1.843609e-07 1.384986e-08 6.420458e-09 0.3078006 0.542824 0.3078008 2.254642e-07 1.478401e-07 1.590095e-07 3.480242e-07 1.698738e-07 5.310068e-08 4.452434e-08 4.024231e-09 5.150018e-08 2.914619e-08 1.276425e-07 1.826464e-07 3.98341e-07 5.45043e-08 2.266521e-07 1.942692e-07 7.255448e-08 1.167991e-07 1.510637e-07 6.353525e-08 7.87891e-08 3.480666e-08 4.585462e-09
1.564492e-07 1.122883e-07 8.888687e-08 1.762498e-07 8.600378e-09 1.938033e-07 2.387621e-07 2.87127e-07 2.21893e-07 1.239547e-07 8.498525e-08 5.176826e-08 1.89771e-07 8.593487e-08 4.070738e-08 7.402101e-08 2.278317e-07 8.80766e-08 9.716489e-08 1.372645e-07 1.501704e-07 2.285518e-08 9.673868e-08 2.987679 3.6553 2.987679 1.266365e-07 1.456021e-08 5.034155e-08 2.597979e-07 1.8383e-07 6.343765e-08 8.150528e-08 5.003383e-09 9.525814e-08 2.182818e-07 1.843608e-07 1.385002e-08 6.420119e-09 0.3078006 0.542824 0.3078008 2.254645e-07 1.478402e-07 1.590096e-07 3.480243e-07 1.69874e-07 5.310046e-08 4.452434e-08 4.02445e-09 5.150039e-08 2.914608e-08 1.276425e-07 1.826463e-07 3.983406e-07 5.450425e-08 2.266521e-07 1.942691e-07 7.255414e-08 1.167992e-07 1.510636e-07 6.353514e-08 7.878889e-08 3.480644e-08 4.585462e-09
1.564492e-07 1.122883e-07 8.888674e-08 1.762497e-07 8.60019e-09 1.938031e-07 2.387623e-07 2.871273e-07 2.21893e-07 1.239544e-07 8.498511e-08 5.176805e-08 1.897708e-07 8.593494e-08 4.070725e-08 7.402105e-08 2.278317e-07 8.807655e-08 9.716502e-08 1.372645e-07 1.501702e-07 2.285539e-08 9.673855e-08 2.987679 3.6553 2.987679 1.266364e-07 1.456e-08 5.034174e-08 2.597978e-07 1.838298e-07 6.343769e-08 8.150528e-08 5.00342e-09 9.525801e-08 2.182817e-07 1.84361e-07 1.385023e-08 6.420252e-09 0.3078006 0.542824 0.3078008 2.254644e-07 1.478404e-07 1.590094e-07 3.480244e-07 1.698741e-07 5.310043e-08 4.452434e-08 4.024487e-09 5.150052e-08 2.914602e-08 1.276427e-07 1.82646e-07 3.983407e-07 5.450456e-08 2.266521e-07 1.942695e-07 7.255427e-08 1.167994e-07 1.510638e-07 6.353508e-08 7.878877e-08 3.48064e-08 4.585462e-09
1.564492e-07 1.122884e-07 8.888679e-08 1.762497e-07 8.600452e-09 1.938035e-07 2.387627e-07 2.871276e-07 2.21893e-07 1.239541e-07 8.49847e-08 5.176846e-08 1.897711e-07 8.593501e-08 4.07073e-08 7.402098e-08 2.278317e-07 8.807663e-08 9.716497e-08 1.372646e-07 1.501705e-07 2.285498e-08 9.673813e-08 2.987679 3.6553 2.987679 1.266359e-07 1.456041e-08 5.034148e-08 2.597978e-07 1.838299e-07 6.343762e-08 8.150528e-08 5.003356e-09 9.525806e-08 2.182816e-07 1.843608e-07 1.384982e-08 6.42067e-09 0.3078006 0.542824 0.3078008 2.254639e-07 1.4784e-07 1.590097e-07 3.480245e-07 1.698741e-07 5.310049e-08 4.452434e-08 4.024423e-09 5.150047e-08 2.914594e-08 1.276424e-07 1.826465e-07 3.983412e-07 5.450482e-08 2.266521e-07 1.942697e-07 7.255469e-08 1.16799e-07 1.510635e-07 6.3535e-08 7.878881e-08 3.480647e-08 4.585462e-09
1.564492e-07 1.122884e-07 8.888694e-08 1.762497e-07 8.600463e-09 1.938032e-07 2.387621e-07 2.871272e-07 2.21893e-07 1.239545e-07 8.498531e-08 5.17681e-08 1.897711e-07 8.593498e-08 4.070744e-08 7.402095e-08 2.278317e-07 8.807665e-08 9.716483e-08 1.372646e-07 1.501705e-07 2.285535e-08 9.673875e-08 2.987679 3.6553 2.987679 1.266366e-07 1.456004e-08 5.034147e-08 2.597978e-07 1.8383e-07 6.34376e-08 8.150528e-08 5.003324e-09 9.52582e-08 2.182817e-07 1.843607e-07 1.385019e-08 6.420059e-09 0.3078006 0.542824 0.3078008 2.254646e-07 1.478404e-07 1.590097e-07 3.480245e-07 1.698739e-07 5.310052e-08 4.452434e-08 4.024391e-09 5.150033e-08 2.914598e-08 1.276424e-07 1.826461e-07 3.983406e-07 5.450446e-08 2.266521e-07 1.942694e-07 7.255408e-08 1.167994e-07 1.510635e-07 6.353503e-08 7.878896e-08 3.48065e-08 4.585462e-09
1.564492e-07 1.122886e-07 8.888708e-08 1.762499e-07 8.600294e-09 1.938035e-07 2.387625e-07 2.871271e-07 2.21893e-07 1.239546e-07 8.498491e-08 5.176843e-08 1.89771e-07 8.593477e-08 4.070759e-08 7.40208e-08 2.278317e-07 8.807681e-08 9.716467e-08 1.372644e-07 1.501703e-07 2.285501e-08 9.673835e-08 2.987679 3.6553 2.987679 1.266362e-07 1.456038e-08 5.034164e-08 2.59798e-07 1.838302e-07 6.343744e-08 8.150528e-08 5.003168e-09 9.525836e-08 2.182819e-07 1.843609e-07 1.384985e-08 6.420451e-09 0.3078006 0.542824 0.3078008 2.254642e-07 1.478401e-07 1.590095e-07 3.480242e-07 1.698738e-07 5.310068e-08 4.452434e-08 4.024235e-09 5.150017e-08 2.914619e-08 1.276426e-07 1.826464e-07 3.983409e-07 5.450431e-08 2.266521e-07 1.942692e-07 7.255447e-08 1.167991e-07 1.510637e-07 6.353525e-08 7.878911e-08 3.480665e-08 4.585462e-09
0.07889044 0.08153418 0.08419043 0.08701882 0.09030894 0.09435995 0.09932118 0.1050815 0.1113084 0.1176306 0.1239187 0.1305645 0.1386389 0.1497532 0.1654913 0.1866337 0.2127252 0.2422527 0.2731474 0.3032434 0.3305583 0.3534314 0.3705729 3.007106 3.643108 3.00695 0.3692689 0.3515675 0.3282436 0.300618 0.2703725 0.239492 0.210109 0.1842086 0.1631676 0.1472882 0.1356852 0.1267589 0.1189501 0.3679682 0.5516769 0.2577798 0.08846281 0.08238595 0.07764257 0.07410715 0.07139895 0.06908786 0.06687377 0.06464756 0.06245382 0.06040037 0.05856909 0.05696621 0.05552716 0.0541646 0.05281365 0.05146411 0.05015175 0.04893123 0.04783951 0.04687591 0.0460047 0.04517756 0.04435825
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.0133671 0.103174 0.161102 0.1321454 0.01981753 0.1171069 0.1886141 0.1606799 0.03154613 0.1368369 0.230862 0.208004 0.05647711 0.1650847 0.3020293 0.298915 0.1252058 0.1979204 0.4401451 0.5311838 0.4472875 0.1536819 0.2990841 0.5738236 0.6613865 0.5702119 0.2925259 0.1586363 0.4468553 0.5274072 0.4351405 0.1946639 0.1232734 0.2943546 0.2986827 0.1671092 0.04655298 0.1966405 0.2236971 0.1398044 0.01435895 0.1384342 0.1696025 0.109466 0.009560954 0.1101514 0.1376043 0.08825757 0.01127213 0.09668601 0.1209162 0.07821064 0.008807627 0.0850097 0.1078746 0.07068323 0.006762736 0.07595089 0.09776526 0.06483996 0.005235632 0.0689388 0.08987227 0.0602516 0.004088645
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.01336695 0.1031739 0.161102 0.1321453 0.01981753 0.1171067 0.1886142 0.1606797 0.03154635 0.1368371 0.2308619 0.2080039 0.05647729 0.1650848 0.3020293 0.298915 0.1252055 0.1979204 0.440145 0.531184 0.4472874 0.1536818 0.299084 3.026 3.630765 3.02569 0.2925259 0.1586363 0.4468552 0.5274073 0.4351404 0.1946639 0.1232734 0.2943546 0.2986827 0.1671094 0.04655316 0.1966404 0.2236971 0.4124265 0.5511931 0.1922355 0.1696027 0.1094658 0.009561111 0.110151 0.1376044 0.08825763 0.01127217 0.09668601 0.1209163 0.07821067 0.008807753 0.08500987 0.1078743 0.07068328 0.00676251 0.07595107 0.0977652 0.06483985 0.005235482 0.06893886 0.0898722 0.06025163 0.004088641
0.3260067 0.3363645 0.3473228 0.3584008 0.3717065 0.3864512 0.401035 0.4184498 0.438931 0.4590358 0.4825051 0.5122178 0.5418503 0.5749596 0.620894 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 3.06281 3.479569 3.061841 1.720891 1.431183 1.139257 0.9739593 0.8857559 0.7909085 0.7123318 0.6630843 0.6163641 0.5723306 0.5442436 0.5254506 0.5046235 0.6600668 0.5916568 0.1053787 0.324299 0.3175806 0.3153523 0.3077486 0.2989039 0.2901882 0.2814592 0.2735063 0.2657846 0.2581551 0.2513817 0.2449855 0.2385924 0.2328572 0.2275815 0.2222788 0.2174162 0.213032 0.2086438 0.2045162 0.2008394 0.1972071 0.1937068
0.4438076 0.4559436 0.4704448 0.4847386 0.5020207 0.5190093 0.5398599 0.5602847 0.5858377 0.6107538 0.6427084 0.6736734 0.7147121 0.7541329 0.8087943 0.8606219 0.9373714 1.008648 1.125829 1.230708 1.440158 1.613244 2.198886 2.788961 2.987679 2.787503 2.195585 1.607394 1.433426 1.222683 1.117479 0.9998917 0.9291879 0.853102 0.8035754 0.7514675 0.7191642 0.6857824 0.6938878 0.7097453 0.6016893 0.4058476 0.4104768 0.4370055 0.4281905 0.4192973 0.4079929 0.3965591 0.3857173 0.3747567 0.3649065 0.3549583 0.346147 0.3372574 0.3294108 0.3215023 0.3145201 0.3074889 0.3012713 0.2950149 0.2894724 0.2838991 0.2789537 0.2739837 0.2695685
0.3260067 0.3363644 0.3473228 0.3584008 0.3717064 0.3864512 0.4010351 0.4184499 0.4389309 0.4590358 0.4825051 0.5122178 0.5418502 0.5749596 0.6208939 0.6692876 0.7196215 0.7983373 0.8930331 0.9810481 1.1455 1.435858 1.723972 1.914222 1.97871 1.912684 1.720891 1.431183 1.139257 0.9739592 0.885756 0.7909085 0.7123318 0.6630843 0.6163642 0.5723305 0.5442435 0.5254506 0.5046235 0.4722382 0.4203468 0.3605282 0.3242991 0.3175806 0.3153524 0.3077487 0.2989038 0.2901882 0.2814592 0.2735062 0.2657845 0.2581551 0.2513816 0.2449855 0.2385921 0.2328572 0.2275815 0.2222787 0.2174161 0.213032 0.2086437 0.2045162 0.2008394 0.1972071 0.1937068
0.07889045 0.08153424 0.08419035 0.08701893 0.09030894 0.09436007 0.09932096 0.1050817 0.1113084 0.1176305 0.1239188 0.1305645 0.1386389 0.1497532 0.1654913 0.1866336 0.2127252 0.2422527 0.2731474 0.3032433 0.3305584 0.3534314 0.3705729 0.3810754 0.3844073 0.3804049 0.3692688 0.3515675 0.3282437 0.3006178 0.2703726 0.239492 0.2101091 0.1842086 0.1631677 0.1472881 0.1356851 0.126759 0.1189501 0.1112676 0.1034146 0.09563871 0.0884626 0.08238604 0.07764256 0.07410739 0.07139879 0.06908784 0.06687377 0.06464756 0.06245377 0.06040035 0.05856907 0.05696608 0.05552753 0.05416456 0.05281367 0.05146397 0.05015182 0.0489313 0.04783952 0.04687586 0.04600478 0.04517753 0.04435825
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
@@ -79,10 +79,6 @@ private val lightScheme = lightColorScheme(
onSecondary = Color(0xFFFFFFFF),
secondaryContainer = Color(0xFFF1E1BB),
onSecondaryContainer = Color(0xFF221B04),
tertiary = Color(0xFF3C6FE0), // AMSAT Active (darker for light theme)
onTertiary = Color(0xFFFFFFFF),
tertiaryContainer = Color(0xFFE09800), // AMSAT Telemetry (darker)
onTertiaryContainer = Color(0xFF000000),
background = Color(0xFFFFF8F0),
onBackground = Color(0xFF1E1B13),
surface = Color(0xFFFFF8F0),
@@ -105,10 +101,10 @@ private val darkScheme = darkColorScheme(
onSecondary = Color(0xFF000000),
secondaryContainer = Color(0xFF404040), // navBar indicator,
onSecondaryContainer = Color(0xFFE0E0E0), // navBar active icon
tertiary = Color(0xFF648FFF), // AMSAT Active (from amsat.org/status)
onTertiary = Color(0xFF000000),
tertiaryContainer = Color(0xFFFFB000), // AMSAT Telemetry
onTertiaryContainer = Color(0xFF000000),
// tertiary = Color(0xFF121212),
// onTertiary = Color(0xFF121212),
// tertiaryContainer = Color(0xFF121212),
// onTertiaryContainer = Color(0xFF121212),
background = Color(0xFF121212),
onBackground = Color(0xFFE0E0E0),
surface = Color(0xFF202020), // card background
@@ -132,8 +132,6 @@
<string name="radar_cw_start">Mulai</string>
<string name="radar_cw_stop">Berhenti</string>
<string name="radar_cw_reset">Bersihkan</string>
<string name="radar_cw_tone">Nada %1$d Hz</string>
<string name="radar_cw_waiting">Menunggu sinyal…</string>
<string name="map_prev">Sebelumnya</string>
<string name="map_next">Berikutnya</string>
<string name="map_copyright" translatable="false">© Kontributor OpenStreetMap</string>
@@ -131,8 +131,6 @@
<string name="radar_cw_start">Mulai</string>
<string name="radar_cw_stop">Berhenti</string>
<string name="radar_cw_reset">Bersihkan</string>
<string name="radar_cw_tone">Nada %1$d Hz</string>
<string name="radar_cw_waiting">Menunggu sinyal…</string>
<string name="map_prev">Sebelumnya</string>
<string name="map_next">Berikutnya</string>
<string name="map_copyright" translatable="false">© Kontributor OpenStreetMap</string>
@@ -296,7 +296,5 @@
\n• BA7OPF (pass matching feature)
\n• BG7NTA</string>
<string name="prefs_outro_license">Bu uygulama herhangi bir garanti sunmaz</string>
<string name="radar_cw_tone">Ton %1$d Hz</string>
<string name="radar_cw_waiting">Sinyal bekleniyor…</string>
</resources>
@@ -123,8 +123,6 @@
<string name="radar_cw_start">开始</string>
<string name="radar_cw_stop">停止</string>
<string name="radar_cw_reset">清空</string>
<string name="radar_cw_tone">音调 %1$d Hz</string>
<string name="radar_cw_waiting">等待信号…</string>
<!-- Map screen -->
<string name="map_prev">上一个</string>
@@ -141,8 +141,6 @@
<string name="radar_cw_start">Start</string>
<string name="radar_cw_stop">Stop</string>
<string name="radar_cw_reset">Clear</string>
<string name="radar_cw_tone">Tone %1$d Hz</string>
<string name="radar_cw_waiting">Waiting for signal…</string>
<!-- Map screen -->
<string name="map_prev">Prev</string>
@@ -314,6 +312,5 @@
\n* BG7NTA
</string>
<string name="prefs_outro_license">The app comes with no warranty</string>
<string name="prefs_outro_deepcw" translatable="false">CW decoding uses the DeepCW model by e04, licensed under AGPL-3.0-only.\nhttps://github.com/e04/deepcw-engine</string>
</resources>
-96
View File
@@ -1,96 +0,0 @@
# DeepCW Decoder — module documentation
The `feature:cw` module decodes Morse code (CW) with the DeepCW neural model
instead of a classical DSP detector. This document records the architecture,
the model provenance, the pitfalls we hit on real devices, and the verification
results. It exists so the next person does not have to re-derive any of it.
## Architecture
```
microphone (44.1 kHz PCM float)
│ AudioCapture.audioFlow() → ~100 ms chunks
▼
CwDecodeScreen (feature:cw, pure Compose)
│ decoder.processBuffer(chunk) waterfall.pushSamples(chunk)
▼ ▼
CwDeepDecoder (core:data) CwWaterfallState (feature:cw)
resample → 3200 Hz resample → 3200 Hz
CwDeepBuffer (20 s rolling) CwDeepSpectrogram.compute
CwDeepSpectrogram.compute → rolling spectrogram history
ONNX Runtime session.run → Canvas waterfall
CwCtcDecoder.greedy (400–1200 Hz band, same magnitudes
→ decodedText StateFlow the model sees)
```
**Why the split.** `core:domain` must stay pure Kotlin/JVM (KMP migration
headroom, per `AGENTS.md`), so the ONNX Runtime dependency — which ships native
libraries — lives in `core:data` behind the `ICwDecoder` interface. The
spectrogram front-end (`CwDeepSpectrogram`) and CTC collapse (`CwCtcDecoder`)
are pure Kotlin and live in `core:domain`, where they are unit-tested against
the Python reference with golden vectors.
**Streaming model, not incremental.** DeepCW is a whole-utterance CTC model. It
rewrites earlier characters as more context arrives, so incremental appending is
wrong. The decoder keeps a rolling buffer capped at 20 s and re-runs the whole
window every 1.5 s, replacing the displayed text outright. 20 s is the smallest
window that hits 0 % CER on the reference clip *and* the largest that keeps
inference comfortably faster than real time (measured ~14× headroom on a server
CPU; timed per-window on device and reported via `lastInferenceMs`).
## Model
| | fp32 (original) | int8 (shipped) |
|---|---|---|
| Size | 15,139,839 bytes | 4,248,808 bytes |
| Derivation | — | `quantize_dynamic` (weights → QUInt8, activations float32) |
| Input | `spectrogram` [1,1,T,65] float32 | unchanged |
| Output | `log_probs` [1,T,42] float32 | unchanged |
| In APK | no (available as a release asset) | yes (`assets/deepcw/model.onnx`) |
The int8 model ships inside the APK: it is ~4× smaller and measurably identical
to fp32 on synthetic CW at SNR ≥ −4 dB (both degrade together below that). The
fp32 model is published as a separate release asset for anyone who wants the
highest-fidelity reference. Both are AGPL-3.0-only — see
[`licenses/NOTICE.md`](licenses/NOTICE.md) for provenance, commit SHA and hashes.
Audio must be packaged **uncompressed** (`noCompress += "onnx"` in the app
module): ONNX Runtime mmap's assets and refuses compressed ones.
## Pitfalls fixed on real devices (release-only)
1. **R8 minification breaks the JNI binding.** `isMinifyEnabled = true` in the
convention plugin, but `onnxruntime-android` ships **no** consumer ProGuard
rules, so `ai.onnxruntime.*` got renamed and native code crashed with no Java
stack trace. Fixed with
`-keep class ai.onnxruntime.** { *; }` in `app/proguard-rules.pro`.
Symptom was the exact "flash to home screen, empty crash log" we chased.
2. **Model load in `init{}`** took down the whole composable on failure; moved
to lazy `ensureLoaded()` with an `errorMessage` path.
3. **Default thread count** saturated all cores and starved audio capture/UI;
capped `setIntraOpNumThreads` to `cores−1` (max 4).
4. **Compose snapshot state written from the audio thread** crashes at runtime
with no log from business-class instrumentation; the waterfall now uses a
`MutableStateFlow` revision counter, and both the row deque and the pending
buffer are lock-guarded.
5. **`LaunchedEffect { launch { collect() } }`** leaked a second `AudioRecord`
when toggling; collection now runs directly in the effect body keyed on
`(isListening, permissionGranted)`.
Diagnostics (no-adb): `MainApplication` already writes uncaught exceptions to
`files/crash_log.txt`. The decoder additionally persists load/inference failures
to `files/deepcw_load_error.txt` / `files/deepcw_infer_error.txt` and step
markers to `files/probe_cw.txt` (`load_begin → load_session_ok → infer_begin →
infer_done`).
## Verification
- **Golden vectors**: `CwDeepSpectrogramTest` + `CwDeepGoldenVectorTest` pin the
Kotlin spectrogram to the Python reference across 5005 values (tolerance
1e-4). 79 domain tests pass.
- **End-to-end on server**: real 20 s noisy CW audio → resample → spectrogram →
ONNX → greedy CTC reproduces `CQ CQ DE BG7NTA BG7NTA K 5NN TU 73`
character-for-character (~1 s inference, fp32).
- **On device (release APK)**: decodes 40 WPM CW at high accuracy. Some UI
latency is expected on the first decode cycle (model load + first inference);
sustained decoding stays real-time.
+4
View File
@@ -6,8 +6,12 @@ plugins {
android {
namespace = "com.rtbishop.look4sat.feature.cw"
compileOptions {
encoding = "UTF-8"
}
}
// R8 consumer rules (kept for compatibility; the fldigi port has no native code)
androidComponents {
onVariants(selector().all()) { variant ->
(variant as? CanProduceConsumerProguardFiles)?.consumerProguardFiles?.add(
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
-78
View File
@@ -1,78 +0,0 @@
# Third-Party Notices — CW Decode Module
## DeepCW neural CW decoding model
The CW (Morse code) decoder in this module performs inference with a neural
network model obtained from the DeepCW project.
| | |
|---|---|
| **Component** | `src/main/assets/deepcw/model.onnx` and `model.onnx.json` |
| **Upstream project** | DeepCW / deepcw-engine |
| **Source repository** | https://github.com/e04/deepcw-engine |
| **Author / copyright** | e04 |
| **License** | GNU Affero General Public License v3.0 only (AGPL-3.0-only) |
| **License text** | [`DeepCW-AGPL-3.0.txt`](DeepCW-AGPL-3.0.txt) |
| **Obtained at commit** | `8e264d243bbd4467bd19f3f28292219405b47e0e` |
| **Original file size** | 15,139,839 bytes |
| **Original SHA-256** | `ef120799457bca042d4690944f0faf93268eb4654e7f50f28784ad63bdc1fe02` |
| **Derived file size** | 4,248,808 bytes |
| **Derived SHA-256** | `cd48259be0ea8c30ecbfff4a718644f361cb27b9228b030771b0c94756dcab98` |
| **Derivation** | Dynamic int8 quantization (weights → QUInt8, activations stay float32) via `onnxruntime.quantization.quantize_dynamic`. Input/output names, shapes and dtypes are unchanged. Measured CER on synthetic CW audio is identical to the fp32 model at SNR >= -4 dB; at -6/-8 dB both models degrade similarly. |
Related upstream repositories by the same author (not vendored here):
- https://github.com/e04/web-deep-cw-decoder — reference web application
- https://github.com/e04/HamNoise — neural noise reduction (not used)
### License compatibility
Look4Sat is licensed under the GNU General Public License v3.0 or later
(GPL-3.0-or-later). The DeepCW model is licensed under AGPL-3.0-only.
Section 13 of the GPL version 3 expressly permits combining GPL-3.0 covered
work with AGPL-3.0 covered work; the resulting combination may be conveyed,
with the AGPL's additional network-interaction requirement applying to the
AGPL-covered portion. Accordingly:
- The Look4Sat source code remains under GPL-3.0-or-later.
- The DeepCW model remains under AGPL-3.0-only.
- Distributions of the combined application are accompanied by complete
corresponding source, satisfying both licenses.
### AGPL section 13 (network interaction)
Inference runs entirely on the local device via ONNX Runtime. The application
does not offer the model's functionality to users interacting with it remotely
over a network, so the additional network-source-offer requirement of AGPL-3.0
section 13 is not triggered by this usage. The complete corresponding source
for both the application and the vendored model remains publicly available at
the repository hosting this file.
### Reproducing the vendored files
```bash
# 1) Fetch the original fp32 model
SHA=8e264d243bbd4467bd19f3f28292219405b47e0e
curl -sLO https://raw.githubusercontent.com/e04/deepcw-engine/$SHA/model.onnx
curl -sLO https://raw.githubusercontent.com/e04/deepcw-engine/$SHA/model.onnx.json
curl -sL -o DeepCW-AGPL-3.0.txt \
https://raw.githubusercontent.com/e04/deepcw-engine/$SHA/LICENSE
sha256sum model.onnx
# expected: ef120799457bca042d4690944f0faf93268eb4654e7f50f28784ad63bdc1fe02
# 2) Reproduce the int8 quantization this repository ships
python - <<'PY'
from onnxruntime.quantization import quantize_dynamic, QuantType
quantize_dynamic("model.onnx", "model_int8.onnx", weight_type=QuantType.QUInt8)
PY
sha256sum model_int8.onnx
# expected: cd48259be0ea8c30ecbfff4a718644f361cb27b9228b030771b0c94756dcab98
# then copy model_int8.onnx over assets/deepcw/model.onnx
```
## ONNX Runtime
Inference engine: `com.microsoft.onnxruntime:onnxruntime-android`, licensed
under the MIT License. Consumed as a published Maven artifact; not vendored in
this repository.
+31 -2
View File
@@ -1,2 +1,31 @@
# CW 模块无 native 代码、无按类名注册的 JNI,因此不需要任何 keep 规则。
# DeepCW 走 ONNX Runtime(自带 consumer proguard 规则),前后处理为普通 Kotlin。
# Look4Sat Pro — CW 解码模块(照搬 Morse Expert 1.15)混淆规则
# 所有 CW 类保持原名: pas.* 通过 RegisterNatives 按类名注册 JNI(混淆即崩);
# 其余为照搬的混淆名类(命名已无混淆意义, 保持以保逻辑完整)。
# JNI 引擎(RegisterNatives 按类名/方法名查表)
-keep class pas.** { *; }
# 照搬的解码/UI 类(全部保持)
-keep class com.ve3nea.morse_expert.** { *; }
-keep class H2.** { *; }
-keep class I2.b { *; }
-keep class J2.** { *; }
-keep class k3.** { *; }
-keep class i3.** { *; }
-keep class g3.** { *; }
-keep class j3.** { *; }
-keep class s.** { *; }
-keep class d1.AbstractC1518b { *; }
-keep class B0.b { *; }
-keep class B.RunnableC0001b { *; }
-keep class D.n { *; }
-keep class E2.g { *; }
-keep class F2.a { *; }
-keep class I0.d { *; }
-keep class K1.a { *; }
-keep class j1.C1646n { *; }
# sun.misc stub(Android 无此类, 仅编译期; 防止 R8 异常处理)
-dontwarn sun.misc.**
-keep class sun.misc.Unsafe { *; }
-keep class sun.misc.Cleaner { *; }
Binary file not shown.
@@ -1,70 +0,0 @@
{
"chars": [
",",
".",
"/",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"?",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
" "
],
"blank_index": 41,
"sample_rate": 3200,
"fft_length": 256,
"hop_length": 48,
"spectrogram_min_freq_hz": 400.0,
"spectrogram_max_freq_hz": 1200.0,
"spectrogram_frequency_bins": 65,
"normalization": "log1p",
"onnx_input_name": "spectrogram",
"onnx_output_name": "log_probs",
"onnx_input_layout": [
"batch",
"channel",
"time",
"frequency"
],
"onnx_output_layout": [
"batch",
"time",
"class"
],
"channel_count": 1,
"num_classes": 42,
"onnx_input_dtype": "float32",
"onnx_output_dtype": "float32"
}
@@ -18,14 +18,18 @@
package com.rtbishop.look4sat.feature.cw
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.net.Uri
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -35,6 +39,8 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
@@ -46,138 +52,127 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import com.rtbishop.look4sat.core.domain.repository.IContainerProvider
import com.rtbishop.look4sat.core.presentation.R as CoreR
import com.rtbishop.look4sat.core.domain.cw.CwFldigiDecoder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/**
* Full-page CW decoder backed by DeepCW.
* CW decode page — pure Compose, fldigi decoding engine.
*
* Layout follows the DeepCW reference app: waterfall on top, the live line
* under it, then the scrolling history. Pause/clear controls and the microphone
* permission flow carry over from the previous page.
*
* There is no settings dialog any more: the model analyses a fixed
* 400-1200 Hz window and tracks speed on its own, so there is nothing to tune.
* Layout mirrors the DeepCW web decoder (waterfall -> live line -> history)
* inside the existing container; top-bar actions (back/settings) and bottom
* actions (start-pause/clear) keep the previous page's interaction model.
* The old Morse Expert (ve3nea) controller and layouts are fully removed.
*/
@Composable
fun CwDecodeScreen(navigateUp: () -> Unit = {}) {
val context = LocalContext.current
val container = remember { (context.applicationContext as IContainerProvider).getMainContainer() }
val decoder = remember { container.provideCwDecoder() }
val audioCapture = remember { container.provideAudioCapture() }
val scope = rememberCoroutineScope()
val decoder = remember { CwFldigiDecoder(initialWpm = 18) }
val waterfall = remember { CwWaterfallState() }
var permissionGranted by remember {
mutableStateOf(
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==
context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED
)
}
var permanentlyDenied by remember { mutableStateOf(false) }
var isListening by remember { mutableStateOf(false) }
var showSettings by remember { mutableStateOf(false) }
var captureJob by remember { mutableStateOf<Job?>(null) }
val decodedText by decoder.decodedText.collectAsState()
val historyText by decoder.historyText.collectAsState()
val estimatedPitch by decoder.estimatedPitch.collectAsState()
val decodedText by decoder.decodedTextFlow.collectAsState()
val signalStrength by decoder.signalStrength.collectAsState()
val inferenceMs by decoder.lastInferenceMs.collectAsState()
val errorMessage by decoder.errorMessage.collectAsState()
val estimatedSpeed by decoder.estimatedSpeed.collectAsState()
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
permissionGranted = granted
val activity = context as? Activity
permanentlyDenied = !granted && activity != null &&
!activity.shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)
if (granted) isListening = true
permanentlyDenied = !granted && (
(context as? android.app.Activity)?.shouldShowRequestPermissionRationale(
Manifest.permission.RECORD_AUDIO
) ?: false
).not()
}
// Capture runs only while listening. Keyed on both listening state and
// permission so granting the permission mid-flow restarts collection
// (isListening may already be true when the launcher returns).
LaunchedEffect(isListening, permissionGranted) {
if (!isListening) return@LaunchedEffect
fun startCapture() {
if (!permissionGranted) {
permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
return@LaunchedEffect
return
}
audioCapture.audioFlow().collect { chunk ->
decoder.processBuffer(chunk, audioCapture.sampleRate)
waterfall.pushSamples(chunk, audioCapture.sampleRate)
captureJob?.cancel()
captureJob = scope.launch(Dispatchers.IO) {
val capture = CwMicCapture()
capture.audioFlow().collect { chunk ->
if (!isActive) return@collect
decoder.processBuffer(chunk)
waterfall.pushSamples(chunk)
}
}
isListening = true
}
fun stopCapture() {
captureJob?.cancel()
captureJob = null
isListening = false
}
DisposableEffect(Unit) {
onDispose {
// OrtSession holds native memory and must be released explicitly.
decoder.close()
}
onDispose { stopCapture() }
}
Column(modifier = Modifier.fillMaxSize()) {
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
) {
// Top bar
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = { isListening = false; navigateUp() }) {
Icon(
painter = painterResource(CoreR.drawable.ic_back),
contentDescription = stringResource(R.string.cw_back)
)
IconButton(onClick = { stopCapture(); navigateUp() }) {
Icon(painter = androidx.compose.ui.res.painterResource(com.rtbishop.look4sat.core.presentation.R.drawable.ic_back), contentDescription = "Back")
}
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(CoreR.string.nav_cw),
style = MaterialTheme.typography.titleMedium
)
Text(
text = if (estimatedPitch != null) {
stringResource(R.string.cw_status_tone, estimatedPitch!!.toInt(), inferenceMs)
} else {
stringResource(R.string.cw_status_listening)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = { isListening = !isListening }) {
Icon(
painter = painterResource(
if (isListening) CoreR.drawable.ic_pause else CoreR.drawable.ic_play
),
contentDescription = stringResource(
if (isListening) R.string.cw_pause else R.string.cw_resume
)
)
}
IconButton(onClick = { decoder.reset(); waterfall.clear() }) {
Icon(
painter = painterResource(CoreR.drawable.ic_delete),
contentDescription = stringResource(R.string.cw_clear)
)
Text(
text = "CW Decoder",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
IconButton(onClick = { showSettings = true }) {
Icon(painter = androidx.compose.ui.res.painterResource(com.rtbishop.look4sat.core.presentation.R.drawable.ic_cw), contentDescription = "Settings")
}
}
// Waterfall
Box(
modifier = Modifier
.fillMaxWidth()
@@ -185,30 +180,32 @@ fun CwDecodeScreen(navigateUp: () -> Unit = {}) {
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(8.dp))
) {
CwWaterfallView(state = waterfall, signalStrength = signalStrength)
CwWaterfallView(state = waterfall)
}
// Live decode line
Text(
text = decodedText.takeLast(64).ifEmpty { "…" },
fontSize = 20.sp,
text = decodedText.takeLast(80),
fontSize = 18.sp,
fontFamily = FontFamily.Monospace,
color = MaterialTheme.colorScheme.primary,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp)
.padding(horizontal = 12.dp, vertical = 4.dp)
)
// History
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 4.dp)
.clip(RoundedCornerShape(8.dp))
.padding(horizontal = 8.dp)
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f))
) {
Text(
text = (historyText + decodedText).ifEmpty { "…" },
text = decodedText,
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
@@ -217,62 +214,288 @@ fun CwDecodeScreen(navigateUp: () -> Unit = {}) {
fontFamily = FontFamily.Monospace,
color = MaterialTheme.colorScheme.onSurface
)
}
errorMessage?.let { message ->
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.9f)),
contentAlignment = Alignment.Center
) {
Text(
text = message,
color = MaterialTheme.colorScheme.onErrorContainer,
textAlign = TextAlign.Center,
modifier = Modifier.padding(16.dp)
)
}
// Status cards
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
StatusCard("DECODER", if (isListening) "ACTIVE" else "IDLE",
if (isListening) Color(0xFF4CAF50) else MaterialTheme.colorScheme.outline,
Modifier.weight(1f))
StatusCard("SPEED", if (estimatedSpeed != null) "${estimatedSpeed?.roundToInt()} WPM" else "--",
MaterialTheme.colorScheme.primary, Modifier.weight(1f))
StatusCard("LEVEL", "${(signalStrength * 100).roundToInt()}%",
MaterialTheme.colorScheme.tertiary, Modifier.weight(1f))
}
// Bottom actions
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = { if (isListening) stopCapture() else startCapture() },
modifier = Modifier.weight(1f)
) {
Icon(
painter = if (isListening) androidx.compose.ui.res.painterResource(com.rtbishop.look4sat.core.presentation.R.drawable.ic_close)
else androidx.compose.ui.res.painterResource(com.rtbishop.look4sat.core.presentation.R.drawable.ic_arrow),
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(Modifier.size(4.dp))
Text(if (isListening) "Pause" else "Start")
}
Button(
onClick = { decoder.resetDecoder(); waterfall.reset() },
modifier = Modifier.weight(1f)
) {
Icon(painter = androidx.compose.ui.res.painterResource(com.rtbishop.look4sat.core.presentation.R.drawable.ic_delete), contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.size(4.dp))
Text("Clear")
}
}
}
if (!permissionGranted) {
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.6f)),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Text(
text = stringResource(R.string.cw_mic_permission),
color = MaterialTheme.colorScheme.inverseOnSurface,
textAlign = TextAlign.Center,
modifier = Modifier.padding(horizontal = 24.dp)
if (showSettings) {
CwSettingsDialog(
onDismiss = { showSettings = false },
currentWpm = estimatedSpeed?.roundToInt() ?: 18
)
}
if (!permissionGranted) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color(0x99000000)),
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Microphone permission is required for CW decoding",
color = Color.White,
textAlign = TextAlign.Center,
modifier = Modifier.padding(horizontal = 24.dp)
)
Spacer(Modifier.height(12.dp))
Button(onClick = { permissionLauncher.launch(Manifest.permission.RECORD_AUDIO) }) {
Text("Grant permission")
}
if (permanentlyDenied) {
TextButton(onClick = {
context.startActivity(
Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:${context.packageName}")
)
)
Button(onClick = {
permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}) {
Text(stringResource(R.string.cw_grant_permission))
}
if (permanentlyDenied) {
TextButton(onClick = {
context.startActivity(
Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", context.packageName, null)
)
)
}) {
Text(stringResource(R.string.cw_open_settings))
}
}
}) {
Text("Open app settings")
}
}
}
}
Spacer(modifier = Modifier.height(4.dp))
}
}
@Composable
private fun StatusCard(label: String, value: String, accent: Color, modifier: Modifier = Modifier) {
Column(
modifier = modifier
.border(1.dp, accent.copy(alpha = 0.6f), RoundedCornerShape(8.dp))
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = label, fontSize = 10.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
text = value,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
color = accent
)
}
}
/**
* Microphone capture at 8000 Hz mono PCM float (fldigi sample rate).
*/
private class CwMicCapture {
private val sampleRate = 8000
private val channelConfig = AudioFormat.CHANNEL_IN_MONO
private val audioFormat = AudioFormat.ENCODING_PCM_FLOAT
fun audioFlow(): kotlinx.coroutines.flow.Flow<FloatArray> =
kotlinx.coroutines.flow.flow {
val bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat)
.coerceAtLeast(sampleRate / 5)
val recorder = AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
channelConfig,
audioFormat,
bufferSize * 4
)
try {
recorder.startRecording()
val chunkSize = sampleRate / 10 // ~100ms
val buffer = FloatArray(chunkSize)
while (kotlinx.coroutines.currentCoroutineContext().isActive) {
val read = recorder.read(buffer, 0, chunkSize, AudioRecord.READ_BLOCKING)
if (read > 0) {
emit(if (read == chunkSize) buffer.copyOf() else buffer.copyOfRange(0, read))
}
}
} finally {
recorder.stop()
recorder.release()
}
}.flowOn(Dispatchers.IO)
}
// --- Waterfall (lightweight sliding spectrogram) ---
class CwWaterfallState {
private val columns = 160
private val rows = 64
private val data = FloatArray(columns * rows)
private var colCount = 0
private val pending = ArrayList<Float>(4096)
private val fftWindow = 512
/** Monotonic frame counter — reading this in composition triggers redraw. */
private val _version = androidx.compose.runtime.mutableIntStateOf(0)
val version: androidx.compose.runtime.State<Int> = _version
@Synchronized
fun pushSamples(samples: FloatArray) {
pending.addAll(samples.toList())
var frames = 0
while (pending.size >= fftWindow) {
val window = FloatArray(fftWindow) { pending[it] }
repeat(fftWindow) { pending.removeAt(0) }
val spectrum = computeSpectrum(window)
// shift rows up, insert newest at bottom
for (r in 0 until rows - 1) {
System.arraycopy(data, (r + 1) * columns, data, r * columns, columns)
}
for (c in 0 until columns) {
val bin = c * spectrum.size / columns
data[(rows - 1) * columns + c] = spectrum[bin.coerceAtMost(spectrum.size - 1)]
}
if (colCount < rows) colCount++
frames++
}
if (frames > 0) _version.intValue++
}
/** Magnitude spectrum via radix-2 FFT on a Hann-windowed frame. */
private fun computeSpectrum(window: FloatArray): FloatArray {
val n = window.size
val re = FloatArray(n)
val im = FloatArray(n)
for (i in 0 until n) {
val w = 0.5 - 0.5 * kotlin.math.cos(2.0 * Math.PI * i / (n - 1))
re[i] = window[i] * w.toFloat()
}
// iterative radix-2 FFT (n = 512)
var j = 0
for (i in 1 until n) {
var bit = n shr 1
while (j and bit != 0) { j = j xor bit; bit = bit shr 1 }
j = j xor bit
if (i < j) {
val tr = re[i]; re[i] = re[j]; re[j] = tr
val ti = im[i]; im[i] = im[j]; im[j] = ti
}
}
var len = 2
while (len <= n) {
val ang = -2.0 * Math.PI / len
val wRe = kotlin.math.cos(ang).toFloat()
val wIm = kotlin.math.sin(ang).toFloat()
var i = 0
while (i < n) {
var curRe = 1f
var curIm = 0f
for (k in 0 until len / 2) {
val uRe = re[i + k]
val uIm = im[i + k]
val vRe = re[i + k + len / 2] * curRe - im[i + k + len / 2] * curIm
val vIm = re[i + k + len / 2] * curIm + im[i + k + len / 2] * curRe
re[i + k] = uRe + vRe
im[i + k] = uIm + vIm
re[i + k + len / 2] = uRe - vRe
im[i + k + len / 2] = uIm - vIm
val nRe = curRe * wRe - curIm * wIm
val nIm = curRe * wIm + curIm * wRe
curRe = nRe; curIm = nIm
}
i += len
}
len = len shl 1
}
val bins = 48
val out = FloatArray(bins)
for (k in 0 until bins) {
// bin k maps to k * 8000/512 ≈ 15.6 Hz steps; show 0..750 Hz region
out[k] = kotlin.math.sqrt(re[k] * re[k] + im[k] * im[k]) / n
}
return out
}
@Synchronized
fun getColumn(c: Int): FloatArray {
val col = FloatArray(rows)
for (r in 0 until rows) {
col[r] = data[r * columns + c.coerceIn(0, columns - 1)]
}
return col
}
@Synchronized
fun reset() {
data.fill(0f)
pending.clear()
colCount = 0
}
}
@Composable
private fun CwWaterfallView(state: CwWaterfallState) {
val columns = 160
val rows = 64
// Read the frame counter so the canvas redraws as new spectra arrive.
state.version.value
Canvas(
modifier = Modifier
.fillMaxSize()
.background(Color(0xFF0D1B2A))
.clip(RoundedCornerShape(8.dp))
) {
val cellW = size.width / columns
val cellH = size.height / rows
for (c in 0 until columns) {
val col = state.getColumn(c)
for (r in 0 until rows) {
val v = col[r]
// log-ish scaling: quiet bins stay dark, strong CW tones pop
val intensity = (kotlin.math.ln1p(v * 600f) * 55f).coerceIn(0f, 255f)
if (intensity > 4f) {
val green = (intensity * 1.25f).coerceAtMost(255f)
drawRect(
color = Color(0f, green / 255f, 0f, 1f),
topLeft = Offset(c * cellW, r * cellH),
size = Size(cellW + 0.5f, cellH + 0.5f)
)
}
}
}
}
}
@@ -0,0 +1,155 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.feature.cw
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
/**
* CW decoder settings (fldigi engine).
*
* Options ported from fldigi progdefaults: speed (WPM), SOM codebook
* decoding on/off, filter bandwidth. Persisted in SharedPreferences.
*/
@Composable
fun CwSettingsDialog(
onDismiss: () -> Unit,
currentWpm: Int,
onSpeedChange: (Int) -> Unit = {},
onSomChange: (Boolean) -> Unit = {},
onBandwidthChange: (Int) -> Unit = {}
) {
var wpm by remember { mutableStateOf(currentWpm.coerceIn(5, 50)) }
var useSom by remember { mutableStateOf(true) }
var bandwidth by remember { mutableStateOf(150) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("CW Settings") },
text = {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.padding(top = 4.dp)
) {
Text("Speed (WPM)", style = MaterialTheme.typography.titleSmall)
Row(verticalAlignment = Alignment.CenterVertically) {
Slider(
value = wpm.toFloat(),
onValueChange = { wpm = it.roundToInt() },
valueRange = 5f..50f,
modifier = Modifier.weight(1f)
)
Text(
text = "$wpm",
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.End,
modifier = Modifier.width(44.dp)
)
}
HorizontalDivider(Modifier.padding(vertical = 8.dp))
Text("Filter bandwidth (Hz)", style = MaterialTheme.typography.titleSmall)
Row(verticalAlignment = Alignment.CenterVertically) {
Slider(
value = bandwidth.toFloat(),
onValueChange = { bandwidth = it.roundToInt() },
valueRange = 50f..500f,
steps = 8,
modifier = Modifier.weight(1f)
)
Text(
text = "$bandwidth",
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.End,
modifier = Modifier.width(44.dp)
)
}
HorizontalDivider(Modifier.padding(vertical = 8.dp))
Text("SOM codebook decoding", style = MaterialTheme.typography.titleSmall)
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(6.dp))
.clickable { useSom = true }
.padding(vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(selected = useSom, onClick = { useSom = true })
Text("On (recommended, higher accuracy)")
}
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(6.dp))
.clickable { useSom = false }
.padding(vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(selected = !useSom, onClick = { useSom = false })
Text("Off (plain table lookup)")
}
}
},
confirmButton = {
TextButton(onClick = {
onSpeedChange(wpm)
onSomChange(useSom)
onBandwidthChange(bandwidth)
onDismiss()
}) { Text("OK") }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text("Cancel") }
},
)
}
@@ -1,182 +0,0 @@
/*
* Look4Sat. Amateur radio satellite tracker and pass predictor.
* Copyright (C) 2019-2026 Arty Bishop and contributors.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.rtbishop.look4sat.feature.cw
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import com.rtbishop.look4sat.core.domain.cw.CwDeepSpectrogram
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* Rolling spectrogram history for the waterfall display.
*
* Reuses [CwDeepSpectrogram] so the picture shows exactly the 400-1200 Hz band
* and the same magnitudes the model sees — what you look at is what it decodes.
*/
class CwWaterfallState(private val historyRows: Int = 96) {
// pushSamples runs on the audio capture thread while snapshot() runs on the
// Compose draw thread, so every touch of these two collections is guarded.
// ArrayDeque is not thread-safe: concurrent removeFirst()/toList() throws.
private val lock = Any()
private val rows = ArrayDeque<FloatArray>(historyRows)
private val pending = ArrayList<Float>(CwDeepSpectrogram.SAMPLE_RATE)
/**
* Bumped on every change so Compose knows to redraw.
*
* A StateFlow, not `mutableIntStateOf`: this is written from the audio
* capture thread, and Compose snapshot state must only be mutated from the
* composition thread — doing otherwise crashes at runtime.
*/
private val _revision = MutableStateFlow(0)
val revision: StateFlow<Int> = _revision.asStateFlow()
/** Snapshot for drawing, oldest row first. */
fun snapshot(): List<FloatArray> = synchronized(lock) { rows.toList() }
fun pushSamples(chunk: FloatArray, sampleRate: Int) {
if (chunk.isEmpty()) return
val resampled = CwDeepSpectrogram.resampleLinear(
chunk, sampleRate, CwDeepSpectrogram.SAMPLE_RATE
)
val audio: FloatArray
synchronized(lock) {
pending.ensureCapacity(pending.size + resampled.size)
for (sample in resampled) pending.add(sample)
// Need at least one FFT window before a row can be produced.
if (pending.size < CwDeepSpectrogram.FFT_LENGTH) return
audio = FloatArray(pending.size) { pending[it] }
pending.clear()
}
// FFT outside the lock; only the append below needs exclusivity.
val computed = CwDeepSpectrogram.compute(audio)
synchronized(lock) {
for (row in computed) {
if (rows.size >= historyRows) rows.removeFirst()
rows.addLast(row)
}
}
_revision.value += 1
}
fun clear() {
synchronized(lock) {
rows.clear()
pending.clear()
}
_revision.value += 1
}
}
/**
* Draws the waterfall newest-row-last, one pixel column per frequency bin.
* Colour ramp is the inferno palette (black -> purple -> orange -> yellow).
*/
@Composable
internal fun CwWaterfallView(
state: CwWaterfallState,
signalStrength: Float,
modifier: Modifier = Modifier
) {
val revision by state.revision.collectAsState()
Canvas(modifier = modifier.fillMaxSize()) {
// Touch the revision inside the draw scope so a new spectrum triggers a
// redraw; without this read the canvas would only ever render once.
@Suppress("UNUSED_EXPRESSION") revision
drawRect(color = Color(0xFF00060F), size = size)
val rows = state.snapshot()
if (rows.isEmpty()) return@Canvas
// Scale to the loudest value on screen so quiet signals stay visible.
var peak = 0f
for (row in rows) for (v in row) if (v > peak) peak = v
if (peak <= 0f) return@Canvas
val rowHeight = size.height / rows.size
val binWidth = size.width / CwDeepSpectrogram.FREQUENCY_BINS
for ((index, row) in rows.withIndex()) {
val y = index * rowHeight
// Linear interpolation between adjacent bins via a horizontal
// gradient removes the blocky "pixel" look of 65 discrete columns.
for (bin in 0 until row.size - 1) {
val m0 = (row[bin] / peak).coerceIn(0f, 1f)
val m1 = (row[bin + 1] / peak).coerceIn(0f, 1f)
if (m0 < 0.06f && m1 < 0.06f) continue
drawRect(
brush = Brush.horizontalGradient(listOf(inferno(m0), inferno(m1))),
topLeft = Offset(bin * binWidth, y),
size = Size(binWidth + 1f, rowHeight + 1f)
)
}
}
if (signalStrength > 0f) {
drawRect(
color = Color(0xFF4CD964).copy(alpha = 0.8f),
topLeft = Offset(0f, size.height - 3f),
size = Size(size.width * signalStrength.coerceIn(0f, 1f), 3f)
)
}
}
}
/**
* matplotlib "inferno" colour map, approximated with piecewise-linear stops
* (black -> purple -> magenta-red -> orange -> pale yellow). The same palette
* used for the static spectrogram illustration, kept for visual consistency.
*/
private val INFERNO_STOPS = arrayOf(
floatArrayOf(0.00f, 0.000f, 0.000f, 0.016f), // black
floatArrayOf(0.25f, 0.231f, 0.059f, 0.439f), // deep purple
floatArrayOf(0.50f, 0.549f, 0.161f, 0.506f), // magenta
floatArrayOf(0.75f, 0.871f, 0.286f, 0.408f), // red-orange
floatArrayOf(1.00f, 0.988f, 1.000f, 0.643f) // pale yellow
)
private fun inferno(t: Float): Color {
val x = t.coerceIn(0f, 1f)
for (i in 0 until INFERNO_STOPS.size - 1) {
val a = INFERNO_STOPS[i]
val b = INFERNO_STOPS[i + 1]
if (x <= b[0]) {
val f = (x - a[0]) / (b[0] - a[0])
return Color(
red = a[1] + (b[1] - a[1]) * f,
green = a[2] + (b[2] - a[2]) * f,
blue = a[3] + (b[3] - a[3]) * f
)
}
}
return Color(0.988f, 1.0f, 0.643f)
}
@@ -1,12 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cw_back">Kembali</string>
<string name="cw_pause">Jeda pendekodean</string>
<string name="cw_resume">Lanjutkan pendekodean</string>
<string name="cw_clear">Hapus teks hasil dekode</string>
<string name="cw_status_listening">Mendengarkan…</string>
<string name="cw_status_tone">%1$d Hz · %2$d ms</string>
<string name="cw_mic_permission">Izin mikrofon diperlukan untuk pendekodean CW</string>
<string name="cw_grant_permission">Berikan izin</string>
<color name="purple_500">#ff6200ee</color>
<integer name="default_font_size">18</integer>
<string name="idle">Diam</string>
<string name="waterfall_display">Tampilan waterfall</string>
<string name="frequency_scale">Skala frekuensi</string>
<string name="decoded_text">Teks terdekode</string>
<string name="clear">Bersihkan</string>
<string name="pause">Jeda Dekode</string>
<string name="save_text">Simpan Teks</string>
<string name="record_signals">Rekam Sinyal</string>
<string name="settings">Pengaturan</string>
<string name="help">Bantuan Daring</string>
<string name="rate">Nilai Aplikasi Ini</string>
<string name="premium">Dapatkan Versi Premium</string>
<string name="tap_back_again_to_close">Ketuk Kembali lagi untuk menutup aplikasi</string>
<string name="message_type">Tipe Pesan</string>
<string name="cw_mic_permission">Izin mikrofon diperlukan untuk dekode CW</string>
<string name="cw_grant_permission">Beri izin</string>
<string name="cw_open_settings">Buka pengaturan aplikasi</string>
</resources>
@@ -1,12 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cw_back">Kembali</string>
<string name="cw_pause">Jeda pendekodean</string>
<string name="cw_resume">Lanjutkan pendekodean</string>
<string name="cw_clear">Hapus teks hasil dekode</string>
<string name="cw_status_listening">Mendengarkan…</string>
<string name="cw_status_tone">%1$d Hz · %2$d ms</string>
<string name="cw_mic_permission">Izin mikrofon diperlukan untuk pendekodean CW</string>
<string name="cw_grant_permission">Berikan izin</string>
<color name="purple_500">#ff6200ee</color>
<integer name="default_font_size">18</integer>
<string name="idle">Diam</string>
<string name="waterfall_display">Tampilan waterfall</string>
<string name="frequency_scale">Skala frekuensi</string>
<string name="decoded_text">Teks terdekode</string>
<string name="clear">Bersihkan</string>
<string name="pause">Jeda Dekode</string>
<string name="save_text">Simpan Teks</string>
<string name="record_signals">Rekam Sinyal</string>
<string name="settings">Pengaturan</string>
<string name="help">Bantuan Daring</string>
<string name="rate">Nilai Aplikasi Ini</string>
<string name="premium">Dapatkan Versi Premium</string>
<string name="tap_back_again_to_close">Ketuk Kembali lagi untuk menutup aplikasi</string>
<string name="message_type">Tipe Pesan</string>
<string name="cw_mic_permission">Izin mikrofon diperlukan untuk dekode CW</string>
<string name="cw_grant_permission">Beri izin</string>
<string name="cw_open_settings">Buka pengaturan aplikasi</string>
</resources>
@@ -1,12 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cw_back">Geri</string>
<string name="cw_pause">Çözmeyi duraklat</string>
<string name="cw_resume">Çözmeyi sürdür</string>
<string name="cw_clear">Çözülen metni temizle</string>
<string name="cw_status_listening">Dinleniyor…</string>
<string name="cw_status_tone">%1$d Hz · %2$d ms</string>
<string name="cw_mic_permission">CW çözümü için mikrofon izni gerekli</string>
<color name="purple_500">#ff6200ee</color>
<integer name="default_font_size">18</integer>
<string name="idle">Beklemede</string>
<string name="waterfall_display">Şelale görüntüsü</string>
<string name="frequency_scale">Frekans ölçeği</string>
<string name="decoded_text">Çözülen metin</string>
<string name="clear">Temizle</string>
<string name="pause">Çözmeyi Duraklat</string>
<string name="save_text">Metni Kaydet</string>
<string name="record_signals">Sinyalleri Kaydet</string>
<string name="settings">Ayarlar</string>
<string name="help">Çevrimiçi Yardım</string>
<string name="rate">Bu Uygulamayı Değerlendir</string>
<string name="premium">Premium Sürümü Al</string>
<string name="tap_back_again_to_close">Kapatmak için Geriye tekrar dokunun</string>
<string name="message_type">Mesaj Türü</string>
<string name="cw_mic_permission">CW çözme için mikrofon izni gereklidir</string>
<string name="cw_grant_permission">İzin ver</string>
<string name="cw_open_settings">Uygulama ayarlarını aç</string>
</resources>
@@ -1,11 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cw_back">返回</string>
<string name="cw_pause">暂停解码</string>
<string name="cw_resume">继续解码</string>
<string name="cw_clear">清空解码文本</string>
<string name="cw_status_listening">正在监听…</string>
<string name="cw_status_tone">%1$d Hz · %2$d 毫秒</string>
<color name="purple_500">#ff6200ee</color>
<integer name="default_font_size">18</integer>
<string name="idle">空闲</string>
<string name="waterfall_display">瀑布图</string>
<string name="frequency_scale">频率刻度</string>
<string name="decoded_text">解码文本</string>
<string name="clear">清除</string>
<string name="pause">暂停解码</string>
<string name="save_text">保存文本</string>
<string name="record_signals">录音信号</string>
<string name="settings">设置</string>
<string name="help">在线帮助</string>
<string name="rate">评价此应用</string>
<string name="premium">获取高级版</string>
<string name="tap_back_again_to_close">再次按返回键退出应用</string>
<string name="message_type">消息类型</string>
<string name="cw_mic_permission">CW 解码需要麦克风权限</string>
<string name="cw_grant_permission">授予权限</string>
<string name="cw_open_settings">打开应用设置</string>
+16 -6
View File
@@ -1,11 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cw_back">Back</string>
<string name="cw_pause">Pause decoding</string>
<string name="cw_resume">Resume decoding</string>
<string name="cw_clear">Clear decoded text</string>
<string name="cw_status_listening">Listening…</string>
<string name="cw_status_tone">%1$d Hz · %2$d ms</string>
<color name="purple_500">#ff6200ee</color>
<integer name="default_font_size">18</integer>
<string name="idle">Idle</string>
<string name="waterfall_display">Waterfall display</string>
<string name="frequency_scale">Frequency scale</string>
<string name="decoded_text">Decoded text</string>
<string name="clear">Clear</string>
<string name="pause">Pause Decoding</string>
<string name="save_text">Save Text</string>
<string name="record_signals">Record Signals</string>
<string name="settings">Settings</string>
<string name="help">Online Help</string>
<string name="rate">Rate this App</string>
<string name="premium">Get Premium Version</string>
<string name="tap_back_again_to_close">Tap Back again to close the app</string>
<string name="message_type">Message Type</string>
<string name="cw_mic_permission">Microphone permission is required for CW decoding</string>
<string name="cw_grant_permission">Grant permission</string>
<string name="cw_open_settings">Open app settings</string>
+3 -2
View File
@@ -8,6 +8,7 @@ android {
dependencies {
implementation(project(":feature:mutual"))
// CW 内嵌面板走 ICwDecoder 接口 + ViewModel state, 实现由 MainContainer 注入,
// 无需依赖 feature:cw 或 constraintlayout (旧 Morse Expert 布局已删除)
// CW 解码面板: 复用 feature:cw 的 fldigi 解码引擎(纯 Compose 面板)
implementation(project(":feature:cw"))
implementation("androidx.constraintlayout:constraintlayout:2.2.1")
}
@@ -92,7 +92,6 @@ data class CwSubState(
val status: CwStatus = CwStatus.Idle,
val hasPermission: Boolean = false,
val decodedText: String = "",
/** Tone detected by the decoder, read-only: DeepCW analyses a fixed 400-1200 Hz window. */
val cwToneFreq: Float = 700f,
val isExpanded: Boolean = false,
val signalStrength: Float = 0f
@@ -122,6 +121,7 @@ sealed interface RadarAction {
data object CwStartListening : RadarAction
data object CwStopListening : RadarAction
data object CwReset : RadarAction
data class CwSetToneFreq(val freq: Float) : RadarAction
data class CwToggleExpanded(val expanded: Boolean) : RadarAction
data class CwPermissionResult(val granted: Boolean) : RadarAction
}
@@ -34,7 +34,7 @@ import com.rtbishop.look4sat.core.domain.repository.ISensorsRepo
import com.rtbishop.look4sat.core.domain.repository.ISettingsRepo
import com.rtbishop.look4sat.core.domain.sstv.LineRecoveryStrategy
import com.rtbishop.look4sat.core.domain.sstv.SstvDecoder
import com.rtbishop.look4sat.core.domain.cw.ICwDecoder
import com.rtbishop.look4sat.core.domain.cw.CwDecoder
import com.rtbishop.look4sat.core.domain.usecase.IAudioCapture
import com.rtbishop.look4sat.core.domain.usecase.IAddToCalendar
import com.rtbishop.look4sat.core.domain.usecase.ISaveImage
@@ -62,7 +62,6 @@ class RadarViewModel(
private val addToCalendar: IAddToCalendar,
private val trackingService: IRadioTrackingService,
private val audioCapture: IAudioCapture,
private val cwDecoderFactory: () -> ICwDecoder,
private val saveImage: ISaveImage,
private val showToast: IShowToast
) : ViewModel() {
@@ -72,7 +71,7 @@ class RadarViewModel(
private var transponders: List<SatRadio> = emptyList()
private var sstvDecoder: SstvDecoder? = null
private var sstvRecordingJob: Job? = null
private var cwDecoder: ICwDecoder? = null
private var cwDecoder: CwDecoder? = null
private var cwListeningJob: Job? = null
// Celestial positions change slowly, recompute at most once per minute
@@ -220,9 +219,6 @@ class RadarViewModel(
override fun onCleared() {
sensorsRepo.disableSensor()
// OrtSession holds native memory; it must be released explicitly.
cwDecoder?.close()
cwDecoder = null
}
fun onAction(action: RadarAction) {
@@ -290,9 +286,13 @@ class RadarViewModel(
RadarAction.CwStartListening -> startCwListening()
RadarAction.CwStopListening -> stopCwListening()
RadarAction.CwReset -> {
cwDecoder?.reset()
cwDecoder?.resetDecoder()
_uiState.update { it.copy(cw = it.cw.copy(decodedText = "")) }
}
is RadarAction.CwSetToneFreq -> {
_uiState.update { it.copy(cw = it.cw.copy(cwToneFreq = action.freq)) }
cwDecoder = CwDecoder(sampleRate = audioCapture.sampleRate, cwToneFreq = action.freq)
}
is RadarAction.CwToggleExpanded -> {
_uiState.update { it.copy(cw = it.cw.copy(isExpanded = action.expanded)) }
}
@@ -417,7 +417,12 @@ class RadarViewModel(
}
private fun initCwDecoder() {
if (cwDecoder == null) cwDecoder = cwDecoderFactory()
if (cwDecoder == null) {
cwDecoder = CwDecoder(
sampleRate = audioCapture.sampleRate,
cwToneFreq = _uiState.value.cw.cwToneFreq
)
}
}
private fun startCwListening() {
@@ -429,33 +434,24 @@ class RadarViewModel(
// Stop SSTV if running (audio capture is shared)
stopSstvRecording()
initCwDecoder()
cwDecoder?.reset()
cwDecoder?.resetDecoder()
_uiState.update { it.copy(cw = it.cw.copy(status = CwStatus.Listening)) }
cwListeningJob = viewModelScope.launch {
val decoder = cwDecoder ?: return@launch
// decodedText is replace semantics: DeepCW revises earlier characters
// as more context arrives, so mirror the value rather than appending.
// Collect decoded text flow
launch {
decoder.decodedText.collect { text ->
cwDecoder?.decodedTextFlow?.collect { text ->
_uiState.update { it.copy(cw = it.cw.copy(decodedText = text)) }
}
}
// Collect signal strength
launch {
decoder.signalStrength.collect { strength ->
cwDecoder?.signalStrength?.collect { strength ->
_uiState.update { it.copy(cw = it.cw.copy(signalStrength = strength)) }
}
}
// Detected tone, shown read-only: the model analyses a fixed
// 400-1200 Hz window, so there is no pitch to configure.
launch {
decoder.estimatedPitch.collect { pitch ->
if (pitch != null) {
_uiState.update { it.copy(cw = it.cw.copy(cwToneFreq = pitch)) }
}
}
}
// Capture audio and feed to decoder
audioCapture.audioFlow().collect { buffer ->
decoder.processBuffer(buffer, audioCapture.sampleRate)
cwDecoder?.processBuffer(buffer)
}
}
}
@@ -520,7 +516,6 @@ class RadarViewModel(
addToCalendar = container.provideAddToCalendar(),
trackingService = container.radioTrackingService,
audioCapture = container.provideAudioCapture(),
cwDecoderFactory = { container.provideCwDecoder() },
saveImage = container.provideSaveImage(),
showToast = container.provideShowToast()
)
@@ -17,16 +17,16 @@
*/
package com.rtbishop.look4sat.feature.radar
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -43,6 +43,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.FilterChip
@@ -55,28 +56,43 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rtbishop.look4sat.core.domain.cw.CwFldigiDecoder
import com.rtbishop.look4sat.core.domain.model.SatRadio
import com.rtbishop.look4sat.core.domain.predict.OrbitalPos
import com.rtbishop.look4sat.core.domain.utility.DopplerFrequencyCalculator
import com.rtbishop.look4sat.core.presentation.CardButton
import kotlin.math.roundToInt
import com.rtbishop.look4sat.core.presentation.R
import com.rtbishop.look4sat.core.presentation.formatFrequency
import com.rtbishop.look4sat.core.presentation.infiniteMarquee
@@ -712,68 +728,110 @@ private fun CwDecoderPanel(
}
AnimatedVisibility(visible = cw.isExpanded) {
// DeepCW engine, driven through the ViewModel. Decoded text uses
// replace semantics: the model revises earlier characters as more
// audio arrives, so show the current value instead of appending.
val listening = cw.status == CwStatus.Listening
// fldigi engine: pure Compose panel (waterfall + decoded text).
val context = LocalContext.current
val decoder = remember { CwFldigiDecoder(initialWpm = 18) }
val waterfall = remember { CwPanelWaterfallState() }
var listening by remember { mutableStateOf(false) }
var captureJob by remember { mutableStateOf<Job?>(null) }
val scope = rememberCoroutineScope()
val decodedText by decoder.decodedTextFlow.collectAsState()
val signalStrength by decoder.signalStrength.collectAsState()
fun startPanelCapture() {
if (!cw.hasPermission) {
requestMicPermission()
return
}
captureJob?.cancel()
captureJob = scope.launch(Dispatchers.IO) {
val capture = CwPanelMicCapture()
capture.audioFlow().collect { chunk ->
if (!isActive) return@collect
decoder.processBuffer(chunk)
waterfall.pushSamples(chunk)
}
}
listening = true
}
fun stopPanelCapture() {
captureJob?.cancel()
captureJob = null
listening = false
}
DisposableEffect(Unit) {
onDispose { stopPanelCapture() }
}
LaunchedEffect(cw.hasPermission) {
if (cw.hasPermission && !listening) {
startPanelCapture()
}
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
Button(
onClick = {
when {
!cw.hasPermission -> requestMicPermission()
listening -> onAction(RadarAction.CwStopListening)
else -> onAction(RadarAction.CwStartListening)
}
},
modifier = Modifier.weight(1f)
) {
Text(
stringResource(
if (listening) R.string.radar_cw_stop else R.string.radar_cw_start
)
)
if (!listening) {
Button(
onClick = { startPanelCapture() },
modifier = Modifier.weight(1f)
) {
Text(stringResource(R.string.radar_cw_start))
}
} else {
Button(
onClick = { stopPanelCapture() },
modifier = Modifier.weight(1f)
) {
Text(stringResource(R.string.radar_cw_stop))
}
}
OutlinedButton(
onClick = { onAction(RadarAction.CwReset) },
onClick = { decoder.resetDecoder(); waterfall.reset() },
modifier = Modifier.weight(1f)
) {
Text(stringResource(R.string.radar_cw_reset))
}
}
// Detected tone is read-only: the model analyses a fixed
// 400-1200 Hz window, so there is no pitch to configure.
if (listening) {
Text(
text = stringResource(R.string.radar_cw_tone, cw.cwToneFreq.toInt()),
fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(150.dp)
.height(90.dp)
.clip(RoundedCornerShape(8.dp))
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f))
) {
CwPanelWaterfallView(state = waterfall)
}
Text(
text = decodedText.takeLast(120),
fontSize = 14.sp,
fontFamily = FontFamily.Monospace,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.fillMaxWidth()
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Text(
text = cw.decodedText.ifEmpty {
stringResource(R.string.radar_cw_waiting)
},
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(8.dp),
fontSize = 14.sp,
fontFamily = FontFamily.Monospace,
color = MaterialTheme.colorScheme.onSurface
text = if (listening) "● ACTIVE" else "○ IDLE",
fontSize = 12.sp,
color = if (listening) Color(0xFF4CAF50) else MaterialTheme.colorScheme.outline
)
Text(
text = "LEVEL ${(signalStrength * 100).roundToInt()}%",
fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
@@ -804,3 +862,170 @@ private fun transceiverTitle(radio: SatRadio): String {
private val FREQ_ADJUSTMENTS =
listOf(-10_000L to "-10k", -1_000L to "-1k", -100L to "-100", 100L to "+100", 1_000L to "+1k", 10_000L to "+10k")
// --- CW panel components (fldigi engine, pure Compose) ---
/** Microphone capture at 8000 Hz mono PCM float (fldigi sample rate). */
private class CwPanelMicCapture {
private val sampleRate = 8000
private val channelConfig = AudioFormat.CHANNEL_IN_MONO
private val audioFormat = AudioFormat.ENCODING_PCM_FLOAT
fun audioFlow(): Flow<FloatArray> = flow {
val bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat)
.coerceAtLeast(sampleRate / 5)
val recorder = AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRate,
channelConfig,
audioFormat,
bufferSize * 4
)
try {
recorder.startRecording()
val chunkSize = sampleRate / 10
val buffer = FloatArray(chunkSize)
while (currentCoroutineContext().isActive) {
val read = recorder.read(buffer, 0, chunkSize, AudioRecord.READ_BLOCKING)
if (read > 0) {
emit(if (read == chunkSize) buffer.copyOf() else buffer.copyOfRange(0, read))
}
}
} finally {
recorder.stop()
recorder.release()
}
}.flowOn(Dispatchers.IO)
}
/** Sliding spectrogram ring buffer for the CW waterfall. */
private class CwPanelWaterfallState {
private val columns = 120
private val rows = 48
private val data = FloatArray(columns * rows)
private val pending = ArrayList<Float>(4096)
private val fftWindow = 512
/** Monotonic frame counter — reading this in composition triggers redraw. */
private val _version = androidx.compose.runtime.mutableIntStateOf(0)
val version: androidx.compose.runtime.State<Int> = _version
@Synchronized
fun pushSamples(samples: FloatArray) {
pending.addAll(samples.toList())
var frames = 0
while (pending.size >= fftWindow) {
val window = FloatArray(fftWindow) { pending[it] }
repeat(fftWindow) { pending.removeAt(0) }
val spectrum = computeSpectrum(window)
for (r in 0 until rows - 1) {
System.arraycopy(data, (r + 1) * columns, data, r * columns, columns)
}
for (c in 0 until columns) {
val bin = c * spectrum.size / columns
data[(rows - 1) * columns + c] = spectrum[bin.coerceAtMost(spectrum.size - 1)]
}
frames++
}
if (frames > 0) _version.intValue++
}
private fun computeSpectrum(window: FloatArray): FloatArray {
val n = window.size
val re = FloatArray(n)
val im = FloatArray(n)
for (i in 0 until n) {
val w = 0.5 - 0.5 * kotlin.math.cos(2.0 * Math.PI * i / (n - 1))
re[i] = window[i] * w.toFloat()
}
var j = 0
for (i in 1 until n) {
var bit = n shr 1
while (j and bit != 0) { j = j xor bit; bit = bit shr 1 }
j = j xor bit
if (i < j) {
val tr = re[i]; re[i] = re[j]; re[j] = tr
val ti = im[i]; im[i] = im[j]; im[j] = ti
}
}
var len = 2
while (len <= n) {
val ang = -2.0 * Math.PI / len
val wRe = kotlin.math.cos(ang).toFloat()
val wIm = kotlin.math.sin(ang).toFloat()
var i = 0
while (i < n) {
var curRe = 1f
var curIm = 0f
for (k in 0 until len / 2) {
val uRe = re[i + k]
val uIm = im[i + k]
val vRe = re[i + k + len / 2] * curRe - im[i + k + len / 2] * curIm
val vIm = re[i + k + len / 2] * curIm + im[i + k + len / 2] * curRe
re[i + k] = uRe + vRe
im[i + k] = uIm + vIm
re[i + k + len / 2] = uRe - vRe
im[i + k + len / 2] = uIm - vIm
val nRe = curRe * wRe - curIm * wIm
val nIm = curRe * wIm + curIm * wRe
curRe = nRe; curIm = nIm
}
i += len
}
len = len shl 1
}
val bins = 48
val out = FloatArray(bins)
for (k in 0 until bins) {
out[k] = kotlin.math.sqrt(re[k] * re[k] + im[k] * im[k]) / n
}
return out
}
@Synchronized
fun getColumn(c: Int): FloatArray {
val col = FloatArray(rows)
for (r in 0 until rows) {
col[r] = data[r * columns + c.coerceIn(0, columns - 1)]
}
return col
}
@Synchronized
fun reset() {
data.fill(0f)
pending.clear()
}
}
@Composable
private fun CwPanelWaterfallView(state: CwPanelWaterfallState) {
val columns = 120
val rows = 48
// Read the frame counter so the canvas redraws as new spectra arrive.
state.version.value
Canvas(
modifier = Modifier
.fillMaxSize()
.background(Color(0xFF0D1B2A))
.clip(RoundedCornerShape(8.dp))
) {
val cellW = size.width / columns
val cellH = size.height / rows
for (c in 0 until columns) {
val col = state.getColumn(c)
for (r in 0 until rows) {
val v = col[r]
val intensity = (v * 4000f).coerceIn(0f, 255f)
if (intensity > 6f) {
val green = (intensity * 1.3f).coerceAtMost(255f)
drawRect(
color = Color(0f, green / 255f, 0f, 1f),
topLeft = Offset(c * cellW, r * cellH),
size = Size(cellW + 0.5f, cellH + 0.5f)
)
}
}
}
}
}
@@ -1071,13 +1071,6 @@ private fun CardCredits(modifier: Modifier = Modifier) {
text = stringResource(id = R.string.prefs_outro_license),
color = MaterialTheme.colorScheme.primary
)
// AGPL-3.0 attribution for the vendored DeepCW model.
// See feature/cw/licenses/NOTICE.md for the full notice.
Text(
text = stringResource(id = R.string.prefs_outro_deepcw),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
@@ -62,25 +62,12 @@ import com.rtbishop.look4sat.core.presentation.R
import com.rtbishop.look4sat.feature.status.R as StatusR
import java.util.Calendar
/**
* Map AMSAT status text to Material3 colorScheme colors.
* Addresses PR #233 review: use colorScheme instead of hardcoded Color() constants.
*/
@Composable
private fun statusColorOf(statusText: String): Color {
return when {
statusText.contains("Heard", ignoreCase = true) && !statusText.contains("Not", ignoreCase = true) ->
MaterialTheme.colorScheme.tertiary // Active
statusText.contains("Telemetry", ignoreCase = true) || statusText.contains("Beacon", ignoreCase = true) ->
MaterialTheme.colorScheme.tertiaryContainer // Telemetry
statusText.contains("Not Heard", ignoreCase = true) ->
Color(0xFFDC267F) // NotHeard pink (no semantic slot)
else ->
MaterialTheme.colorScheme.error // Conflict
}
}
private val NoReportGray = Color(0xFFC0C0C0) // Neutral state
// ========== Official status colors (amsat.org/status originals) ==========
val ActiveBlue = Color(0xFF648FFF)
val TlmOrange = Color(0xFFFFB000)
val NotHeardPink = Color(0xFFDC267F)
val ConflictDeepOrange = Color(0xFFFE6100)
val NoReportGray = Color(0xFFC0C0C0)
@Composable
fun SatStatusScreen(container: IMainContainer) {
@@ -210,10 +197,10 @@ private fun StatusHeader(
@Composable
private fun LegendRow() {
val legend = listOf(
stringResource(id = R.string.amsat_active) to MaterialTheme.colorScheme.tertiary,
stringResource(id = R.string.amsat_tlm) to MaterialTheme.colorScheme.tertiaryContainer,
stringResource(id = R.string.amsat_not_heard) to Color(0xFFDC267F),
stringResource(id = R.string.amsat_conflict) to MaterialTheme.colorScheme.error
stringResource(id = R.string.amsat_active) to ActiveBlue,
stringResource(id = R.string.amsat_tlm) to TlmOrange,
stringResource(id = R.string.amsat_not_heard) to NotHeardPink,
stringResource(id = R.string.amsat_conflict) to ConflictDeepOrange
)
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp),
@@ -262,10 +249,9 @@ private fun HeaderRow(statuses: List<SatStatus>) {
}
}
/** Satellite row: name + 6 day color blocks (displays the newest non-gray status) */
/** Satellite row: name + 6 day color blocks (official colors + report counts) */
@Composable
private fun StatusRow(status: SatStatus, onClickDay: (SatDay) -> Unit) {
val noReportGray = 0xFFC0C0C0L
Row(
modifier = Modifier
.fillMaxWidth()
@@ -280,7 +266,7 @@ private fun StatusRow(status: SatStatus, onClickDay: (SatDay) -> Unit) {
modifier = Modifier.weight(2f).padding(start = 4.dp)
)
status.days.forEach { day ->
val slot = day.slots.firstOrNull { it.statusColor != noReportGray } ?: day.slots.first()
val slot = day.slots.firstOrNull { it.statusColor != NoReportGray.value.toInt().toLong() } ?: day.slots.first()
DayCell(
slot = slot,
modifier = Modifier.weight(0.8f).padding(horizontal = 1.dp),
@@ -365,6 +351,12 @@ private fun ReportDialog(
)
}
private fun statusColorOf(statusText: String): Color = when {
statusText.contains("Heard", ignoreCase = true) && !statusText.contains("Not", ignoreCase = true) -> ActiveBlue
statusText.contains("Telemetry", ignoreCase = true) || statusText.contains("Beacon", ignoreCase = true) -> TlmOrange
statusText.contains("Not Heard", ignoreCase = true) -> NotHeardPink
else -> ConflictDeepOrange
}
private fun formatFetchedAt(utcMs: Long): String {
val cal = Calendar.getInstance()
+2 -5
View File
@@ -1,8 +1,8 @@
[versions]
#noinspection UnusedVersionCatalogEntry
appVersionCode = "458"
appVersionCode = "459"
#noinspection UnusedVersionCatalogEntry
appVersionName = "4.5.5"
appVersionName = "4.5.6"
#noinspection UnusedVersionCatalogEntry
compileSdk = "37"
#noinspection UnusedVersionCatalogEntry
@@ -34,7 +34,6 @@ kotlin = "2.4.10"
kotlin-coroutines = "1.11.0"
kotlin-serialization = "1.11.0"
other-onnxruntime = "1.25.1"
other-okhttp = "5.4.0"
other-osmdroid = "6.1.20"
@@ -78,8 +77,6 @@ kotlin-gradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", ve
#noinspection UnusedVersionCatalogEntry
kotlin-serialization = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlin-serialization" }
#noinspection UnusedVersionCatalogEntry
other-onnxruntime = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "other-onnxruntime" }
#noinspection UnusedVersionCatalogEntry
other-okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "other-okhttp" }
#noinspection UnusedVersionCatalogEntry