RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
P25 voice step 1: record clear calls' radio signal to WAV for the voice decoder
CIS-C0b6579248d871
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Record.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Record.ktnew file mode 100644index 0000000..ac77dff--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Record.kt@@ -0,0 +1,88 @@+package com.rfsentinel.app.sdr++import android.content.Context+import java.io.ByteArrayOutputStream+import java.io.File+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.roundToInt+import kotlin.math.sin++/**+ * P25 voice, first step: saves the radio signal of clear (not encrypted) calls, so the voice decoder can be built and+ * tested on real calls. The voice channel [Baseband.offsetHz] from the tuned centre is mixed down and cut to 48 kS/s the+ * way [P25Demod] does it, and saved as a two-channel (I, Q) 16-bit WAV: the "baseband recording" SDR tools open.+ * Nothing is demodulated or played. Pure except [save] and [files].+ */+object P25Record {++ const val RATE = P25Demod.CHANNEL_RATE+ /** How long each call is recorded: the control channel is away meanwhile. */+ const val SECONDS = 6+ /** Recordings kept; the oldest go first. */+ const val KEEP = 20+ private const val DIR = "p25rec"+ /** 8-bit samples summed [P25Demod.DECIM] at a time reach ±5100: this fills 16 bits without clipping. */+ private const val SCALE = 6.0++ /** Mixes [offsetHz] down to 0 and integrates-and-dumps to [RATE], collecting 16-bit I/Q pairs. */+ class Baseband(val offsetHz: Long, sampleRate: Int = P25Demod.SAMPLE_RATE) {+ private val decim = sampleRate / RATE+ private val stepR: Double; private val stepI: Double+ init { val w = -2 * PI * offsetHz / sampleRate; stepR = cos(w); stepI = sin(w) }+ private var pr = 1.0; private var pi = 0.0+ private var accR = 0.0; private var accI = 0.0; private var accN = 0+ private val out = ByteArrayOutputStream()+ /** Output samples so far. */+ var samples = 0; private set++ /** Unsigned 8-bit I/Q as the dongle delivers it: [count] complex samples from [buf]. */+ fun feed(buf: ByteArray, count: Int) {+ var k = 0+ for (s in 0 until count) {+ val i = (buf[k++].toInt() and 0xff) - 127.5+ val q = (buf[k++].toInt() and 0xff) - 127.5+ accR += i * pr - q * pi+ accI += i * pi + q * pr+ val nr = pr * stepR - pi * stepI+ pi = pr * stepI + pi * stepR; pr = nr+ if (++accN == decim) {+ short(accR); short(accI); samples+++ accN = 0; accR = 0.0; accI = 0.0+ val m = 1.5 - 0.5 * (pr * pr + pi * pi); pr *= m; pi *= m // keeps the phasor on the unit circle+ }+ }+ }++ private fun short(v: Double) {+ val s = (v * SCALE).roundToInt().coerceIn(-32768, 32767)+ out.write(s and 0xff); out.write(s shr 8 and 0xff)+ }++ /** The recording as a WAV file. */+ fun wav(): ByteArray = out.toByteArray().let { header(it.size) + it }+ }++ /** A 44-byte PCM WAV header: 2 channels, 16 bits, [RATE]. */+ internal fun header(dataBytes: Int): ByteArray {+ val b = java.nio.ByteBuffer.allocate(44).order(java.nio.ByteOrder.LITTLE_ENDIAN)+ b.put("RIFF".toByteArray()).putInt(36 + dataBytes).put("WAVE".toByteArray())+ b.put("fmt ".toByteArray()).putInt(16).putShort(1).putShort(2).putInt(RATE).putInt(RATE * 4).putShort(4).putShort(16)+ b.put("data".toByteArray()).putInt(dataBytes)+ return b.array()+ }++ /** Saves a call's recording ("p25_20261102_142233_tg1234.wav") and drops the oldest past [KEEP]. */+ fun save(context: Context, call: P25History.Call, wav: ByteArray): File {+ val dir = File(context.filesDir, DIR).apply { mkdirs() }+ val stamp = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US).format(java.util.Date(call.time))+ val who = call.tg?.let { "tg$it" } ?: call.target?.let { "to$it" } ?: "call"+ val f = File(dir, "p25_${stamp}_$who.wav").apply { writeBytes(wav) }+ files(context).drop(KEEP).forEach { it.delete() }+ return f+ }++ /** The kept recordings, newest first. */+ fun files(context: Context): List<File> =+ File(context.filesDir, DIR).listFiles { f -> f.name.endsWith(".wav") }.orEmpty().sortedByDescending { it.name }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.ktindex 5425f9b..5f43d41 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt@@ -41,6 +41,7 @@ object SdrRadio {private const val INPUT_GAP_MS = 5_000L // at most one input check this often: each costs ~0.2 s of control channelprivate const val INPUT_READS = 16 // ~70 ms of the inputprivate const val INPUT_OFFSET_HZ = 250_000L // the input this far above the tuned centre, clear of the DC spike+ private const val RECORD_GAP_MS = 20_000L // at most one call recording this often: each costs P25Record.SECONDS of control channel@Volatile var status: String = ""; private set/** ADS-B messages decoded since the app started, for the main screen's messages-per-second line. */@@ -92,6 +93,8 @@ object SdrRadio {@Volatile var p25Inputs = false/** A call's radio heard on the input: [snrDb] above the noise, so close to you (the call, its input frequency). */@Volatile var onP25Input: ((P25History.Call, Long, Int) -> Unit)? = null+ /** Settings › RTL-SDR radio: save the radio signal of clear calls ([P25Record]). */+ @Volatile var p25Record = false/*** The waterfall screen zoomed in: hold this frequency instead of sweeping (or receiving ADS-B),* until set back to null. Picked up within a chunk.@@ -439,8 +442,11 @@ object SdrRadio {status = "$deviceLabel · P25 · control channel $where" + turnNote()var messages = 0; var lastStatus = 0Lvar pending: Pair<P25History.Call, Long>? = null; var lastInput = 0L; var inputs = 0; var heard = 0+ var toRecord: P25History.Call? = null; var lastRecord = 0L; var recorded = 0// A call's input: once it's on the air, tune there for a moment and measure it (the control channel comes back after).+ // A call to record goes first: its voice channel, for a few seconds.val detour = detour@{+ toRecord?.let { call -> toRecord = null; if (recordCall(sdr, call)) recorded++; return@detour true }val (call, hz) = pending ?: return@detour falseif (System.currentTimeMillis() - call.time < INPUT_DELAY_MS) return@detour falsepending = null@@ -460,13 +466,39 @@ object SdrRadio {p25Log.inputHz(c.channel!!)?.let { hz -> pending = c to hz; lastInput = now }}}+ if (p25Record && toRecord == null && now - lastRecord >= RECORD_GAP_MS) {+ calls.lastOrNull { !it.encrypted && it.hz != null }?.let { toRecord = it; lastRecord = now }+ }if (now - lastStatus >= 2_000L && !halted) { lastStatus = now; status = "$deviceLabel · P25 · control channel $where · $messages messages" + turnNote() }}if (lost) p25Lock = nullUsbWifi.log("$deviceLabel: P25 ${if (lost) "control channel went quiet" else "turn over or stopped"} after $messages messages (${hunt.blocks} blocks in all), " +p25Log.rows().let { r -> "${r.size} talkgroups / private calls, ${r.sumOf { it.calls }} calls" } +- (if (inputs > 0) ", $inputs input checks, $heard radios heard nearby" else ""))+ (if (inputs > 0) ", $inputs input checks, $heard radios heard nearby" else "") ++ (if (recorded > 0) ", $recorded calls recorded" else ""))+ }+ }++ /** Records [P25Record.SECONDS] of [call]'s voice channel to a file; false when nothing was saved. Frequency kept off the log. */+ private fun recordCall(sdr: SdrDevice, call: P25History.Call): Boolean {+ val ctx = appContext ?: return false+ val hz = call.hz ?: return false+ if (!sdr.tune(hz - INPUT_OFFSET_HZ)) return false+ sdr.resetBuffer()+ val buf = ByteArray(XFER)+ repeat(sdr.settleReads) { sdr.read(buf) }+ val rec = P25Record.Baseband(INPUT_OFFSET_HZ, sdr.sampleRate)+ var fails = 0+ while (rec.samples < P25Record.SECONDS * P25Record.RATE && !halted && fails < STALL_CHUNKS) {+ val n = sdr.read(buf)+ if (n <= 0) { fails++; continue }+ rec.feed(buf, n / 2)}+ if (rec.samples < P25Record.RATE) return false+ val wav = rec.wav()+ runCatching { P25Record.save(ctx, call, wav) }.onFailure { UsbWifi.log("$deviceLabel: P25 recording not saved - ${UsbWifi.describe(it)}"); return false }+ UsbWifi.log("$deviceLabel: P25 call recorded (%.1f s, %d KB)".format(java.util.Locale.US, rec.samples.toDouble() / P25Record.RATE, wav.size / 1024))+ return true}/** A call's input level in dB above the noise, or null when the tuner didn't get there. Frequency kept off the log. */diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex c734c53..bfebeb9 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -425,6 +425,7 @@ class ScanForegroundService : Service() {com.rfsentinel.app.sdr.SdrRadio.turnMs = Prefs.sdrTurnS(this) * 1000Lcom.rfsentinel.app.sdr.SdrRadio.onP25Call = { tg -> pipeline.post { onP25Call(tg) } }com.rfsentinel.app.sdr.SdrRadio.p25Inputs = Prefs.p25Inputs(this)+ com.rfsentinel.app.sdr.SdrRadio.p25Record = Prefs.p25Record(this)com.rfsentinel.app.sdr.SdrRadio.onP25Input = { call, hz, snr -> pipeline.post { onP25Input(call, hz, snr) } }com.rfsentinel.app.sdr.SdrRadio.location = { (lastLocation ?: lastFix)?.let { it.latitude to it.longitude } }com.rfsentinel.app.sdr.SdrRadio.onAircraft = { planes, unlocated -> onlineWatch.localAircraft(planes, unlocated) }diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex ebf79e7..4d1d962 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -370,6 +370,19 @@ class SettingsActivity : AppCompatActivity() {.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Share .pcap recording"))}+ /** RTL-SDR radio › Record P25 voice calls: the kept .wav files, to send. */+ private fun shareP25Recordings() {+ val files = com.rfsentinel.app.sdr.P25Record.files(this)+ if (files.isEmpty()) { Toast.makeText(this, "No P25 calls recorded yet", Toast.LENGTH_SHORT).show(); return }+ val uris = ArrayList(files.mapNotNull {+ runCatching { androidx.core.content.FileProvider.getUriForFile(this, "$packageName.fileprovider", it) }.getOrNull()+ })+ startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND_MULTIPLE).setType("audio/wav")+ .putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)+ .putExtra(Intent.EXTRA_SUBJECT, "RF Sentinel P25 recordings (${files.size})")+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Share P25 recordings"))+ }+/** The recording's size and frame count, refreshed every second while it runs. */private fun updatePcap() {if (isFinishing || isDestroyed) return@@ -1432,7 +1445,18 @@ class SettingsActivity : AppCompatActivity() {"once every few seconds; the control channel misses a few messages each time. Uses the radio sweep's sensitivity.") {Prefs.setP25Inputs(this, it)}- val talkgroupViews = (box.childCount - 6 until box.childCount).map { box.getChildAt(it) }+ scan("Record P25 voice calls", Prefs.p25Record(this),+ "For building P25 voice: when a clear (not encrypted) call starts, the SDR leaves the control channel for " ++ "${com.rfsentinel.app.sdr.P25Record.SECONDS} s and saves that call's radio signal to a file, about 1 MB each. Nothing " ++ "is decoded or played. At most one call every 20 s; the last ${com.rfsentinel.app.sdr.P25Record.KEEP} are kept. " ++ "Share them with the button below. Recording radio calls is not allowed everywhere: check the law where you are.") {+ Prefs.setP25Record(this, it)+ }+ box.addView(com.google.android.material.button.MaterialButton(this, null, android.R.attr.borderlessButtonStyle).apply {+ text = "Share P25 recordings"+ setOnClickListener { shareP25Recordings() }+ })+ val talkgroupViews = (box.childCount - 8 until box.childCount).map { box.getChildAt(it) }var sweepViews = emptyList<View>() // the sweep's own settings, belowshowSdrOptions = {val ticked = listOf(sweepBox, adsbBox, p25Box).count { it.isChecked }diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 285caff..25d1674 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -657,6 +657,9 @@ object Prefs {/** After a call starts, listen for a moment where its radio transmits: strong there, the radio is near you. Off by default. */fun p25Inputs(context: Context): Boolean = bool(context, "p25_inputs", false)fun setP25Inputs(context: Context, v: Boolean) = setBool(context, "p25_inputs", v)+ /** Save the radio signal of clear calls ([com.rfsentinel.app.sdr.P25Record]), for the voice decoder. Off by default. */+ fun p25Record(context: Context): Boolean = bool(context, "p25_record", false)+ fun setP25Record(context: Context, v: Boolean) = setBool(context, "p25_record", v)/** Seconds the SDR gives each ticked scan in turn, 30-300: a first P25 search takes up to about 15 s. */fun sdrTurnS(context: Context): Int = int(context, "sdr_turn_s", 60).coerceIn(30, 300)fun setSdrTurnS(context: Context, v: Int) = setInt(context, "sdr_turn_s", v.coerceIn(30, 300))diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xmlindex 282e644..39f31d6 100644--- a/app/src/main/res/xml/file_paths.xml+++ b/app/src/main/res/xml/file_paths.xml@@ -1,4 +1,5 @@<?xml version="1.0" encoding="utf-8"?><paths><cache-path name="exports" path="exports/" />+ <files-path name="p25rec" path="p25rec/" /></paths>diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25RecordTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25RecordTest.ktnew file mode 100644index 0000000..61ba20f--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25RecordTest.kt@@ -0,0 +1,46 @@+package com.rfsentinel.app.sdr++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.math.PI+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.roundToInt+import kotlin.math.sin++class P25RecordTest {++ @Test+ fun theVoiceChannelIsMixedDownTo48kAsAWav() {+ // 0.1 s of a carrier 1 kHz above the channel, which sits 250 kHz above the tuned centre.+ val rate = P25Demod.SAMPLE_RATE+ val count = rate / 10+ val iq = ByteArray(2 * count)+ val tone = 251_000.0+ for (i in 0 until count) {+ val ph = 2 * PI * tone * i / rate+ iq[2 * i] = (127.5 + 60 * cos(ph)).roundToInt().toByte()+ iq[2 * i + 1] = (127.5 + 60 * sin(ph)).roundToInt().toByte()+ }+ val rec = P25Record.Baseband(250_000L)+ rec.feed(iq, count)+ assertEquals(P25Record.RATE / 10, rec.samples)++ val wav = ByteBuffer.wrap(rec.wav()).order(ByteOrder.LITTLE_ENDIAN)+ assertEquals("RIFF", String(rec.wav(), 0, 4))+ assertEquals(P25Record.RATE, wav.getInt(24))+ assertEquals(rec.samples * 4, wav.getInt(40))+ // What's left after mixing turns 1 kHz: the phase steps 2π · 1000 / 48000 each sample.+ var step = 0.0+ for (k in 100 until 200) {+ val a = atan2(wav.getShort(44 + 4 * k + 2).toDouble(), wav.getShort(44 + 4 * k).toDouble())+ val b = atan2(wav.getShort(44 + 4 * (k + 1) + 2).toDouble(), wav.getShort(44 + 4 * (k + 1)).toDouble())+ step += ((b - a + 3 * PI) % (2 * PI)) - PI+ }+ assertEquals(2 * PI * 1000 / P25Record.RATE, step / 100, 0.01)+ assertTrue(wav.getShort(44 + 400).toInt() != 0)+ }+}