Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Changelog

## SimBridge 2.6.0

Update both apps. Pairing is kept.

- **SimBridge voicemail:** when you don't answer, the SIM phone takes the call, plays your greeting
and a tone, and records the message (up to 2 minutes). It arrives as a message from the caller
with the recording (play it in the chat) and its words written out (cloud or on-device speech,
as set for call translation). Turn it on in Dashboard > Controls > Calls; it rings for the
no-answer time first (25 s if that is off).
- **Call screening:** for unknown or hidden numbers the SIM phone answers, asks who is calling and
why, and shows you what they said in a notification just before your phone rings. The caller
hears a waiting tone meanwhile. Note: a screened call counts as answered for the caller.
- Both spoken texts can be changed (Dashboard > Controls > Calls > Edit what callers hear).

## SimBridge 2.5.0

Update both apps. Pairing is kept.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ main phone only ever uses Wi-Fi. See the [disclaimer](DISCLAIMER.md).
| 🎧 **HD voice** | 16 kHz wideband audio between the phones (L16), falling back to normal phone quality (G.711) when needed. |
| 🔒 **Encrypted and paired** | Pair once by scanning a QR code. Signalling runs over **TLS** pinned to the SIM phone's key, audio over **SRTP**, and every call or text needs the paired password. Mobile-data and internet addresses are refused. |
| 💬 **Texts, pictures and group chats** | A Google Messages-style app: conversations, contact photos, bubbles, notifications with **Reply** and **Mark as read**, **Sent / Delivered** reports, picture messages (MMS) and **group texts**. |
| 📼 **Voicemail and call screening** | Unanswered calls leave a message that arrives written out; unknown callers can be asked who they are before your phone rings. |
| 🧹 **Rules, spam filter, quiet hours** | Choose who always alerts, stays silent, is archived or blocked; promotions go to Archived; quiet hours let only VIP contacts through. |
| 🔔 **App notifications from the SIM phone** | Your bank or carrier app on the SIM phone? Its notifications arrive as messages on the main phone. |
| 🛡️ **Watchdog, daily report, charge limit** | The gateway restarts itself after a crash, sends a morning health text, and can stop charging at 80–95 %. |
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ android {
applicationId = "io.github.simbridge.gateway"
minSdk = 30
targetSdk = 36
versionCode = 460
versionName = "2.5.0"
versionCode = 470
versionName = "2.6.0"
// Filter all transitive JNI libraries as well as PJSIP's own module outputs.
ndk {
//abiFilters += listOf("arm64-v8a", "x86_64")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import org.json.JSONObject
* persistent queue while no phone is registered.
*/
/** Control operations that change something on this phone; each is written to the [Audit] log. */
private val AUDITED = setOf("control", "ussd", "ussd-reply", "screen-start", "network-mode", "apn-select", "apn-add", "sms-app",
private val AUDITED = setOf("machine", "control", "ussd", "ussd-reply", "screen-start", "network-mode", "apn-select", "apn-add", "sms-app",
"at-place", "charge-limit", "locate", "block-rules", "voicemail")

/** Who changed what on this phone, and when (the last 200 entries). */
Expand Down Expand Up @@ -64,6 +64,16 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
if (set.isNotEmpty()) privilegedRaw("notif-access", AppNotifications.COMPONENT)
send(JSONObject().put("op", "control-result").put("action", "notif-apps").put("ok", true), from)
}
"machine" -> {
prefs.edit().apply {
if (o.has("voicemail")) putBoolean("vm_on", o.optBoolean("voicemail"))
if (o.has("screen")) putInt("screen_mode", o.optInt("screen").coerceIn(0, 2))
o.optString("greeting").takeIf { it.isNotBlank() }?.let { putString("vm_greeting", it.take(300)) }
o.optString("screenPrompt").takeIf { it.isNotBlank() }?.let { putString("screen_prompt", it.take(300)) }
}.apply()
prompts.prepare(greeting); prompts.prepare(screenPrompt)
send(status(), from)
}
"audit" -> send(JSONObject().put("op", "audit").put("list", Audit.recent(app)), from)
"charge-limit" -> rt.worker {
privileged("charge-limit", o.optString("value", "off"))
Expand Down Expand Up @@ -255,6 +265,7 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
o.put("hotspot", hotspotOn())
privilegedRaw("charge-limit-get", "").takeUnless { it.startsWith("error") }?.let { o.put("chargeLimit", it) }
o.put("dailyReport", prefs.getBoolean("daily_report", true))
o.put("vmOn", voicemailOn).put("screenMode", screenMode).put("greeting", greeting).put("screenPrompt", screenPrompt)
o.put("smsApp", MmsGateway.isDefaultSmsApp(app))
o.put("noAnswerSec", noAnswerSec)
if (hasPhoneState()) runCatching { app.getSystemService(TelephonyManager::class.java).voiceMailNumber }.getOrNull()?.let { o.put("voicemail", it) }
Expand Down Expand Up @@ -513,8 +524,40 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {

private var wifiWatch: android.net.ConnectivityManager.NetworkCallback? = null

// ------------------------------------------------------------ voicemail and call screening

val prompts = Prompts(app)
val voicemailOn: Boolean get() = prefs.getBoolean("vm_on", false)
/** 0 off, 1 numbers not in contacts (and hidden ones), 2 hidden numbers only. */
val screenMode: Int get() = prefs.getInt("screen_mode", 0)
val greeting: String get() = prefs.getString("vm_greeting", null)
?: "Hello. I can't take your call right now. Please leave a message after the tone."
val screenPrompt: String get() = prefs.getString("screen_prompt", null)
?: "Hello. Please say your name and why you are calling, then wait a moment."

fun shouldScreen(number: String?): Boolean = when (screenMode) {
1 -> number.isNullOrBlank() || (ContactNames.lookup(app, number) == null && !isBlocked(number))
2 -> number.isNullOrBlank()
else -> false
}

/** A message left after no answer; kept until the main phone has it. */
fun voicemailMessage(p: io.github.sparkcyf.voicesipagent.voice.Party, audio: ShortArray, rate: Int, at: Long) {
AppLog.i("voicemail message: ${audio.size * 1000L / rate} ms")
deliver(JSONObject().put("op", "voicemail-msg").put("from", p.number ?: "").put("name", ContactNames.lookup(app, p.number) ?: "")
.put("sim", p.sim ?: 0).put("at", at).put("rate", rate)
.put("wav", android.util.Base64.encodeToString(Wav.encode(audio, rate), android.util.Base64.NO_WRAP)))
}

/** What a screened caller said; only useful right now, so not kept. */
fun screened(p: io.github.sparkcyf.voicesipagent.voice.Party, audio: ShortArray, rate: Int) {
send(JSONObject().put("op", "screened").put("from", p.number ?: "").put("rate", rate)
.put("wav", android.util.Base64.encodeToString(Wav.encode(audio, rate), android.util.Base64.NO_WRAP)))
}

/** Called once when the gateway starts. */
fun start() {
prompts.prepare(greeting); prompts.prepare(screenPrompt)
scheduleReport()
if (prefs.getBoolean("crashed", false)) {
prefs.edit().putBoolean("crashed", false).apply()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -707,7 +707,12 @@ class GatewayRuntime private constructor(context: Context) {
// to be non-empty; "phone" is a readable placeholder when no DID/username is configured.
val inboundTarget = s.inboundTarget.ifBlank { s.username.ifBlank { if (s.serverMode) "phone" else "" } }
val b = CallBridge(
sideA = cellular,
// Some calls are answered and screened first (control.screenMode).
sideA = io.github.sparkcyf.voicesipagent.gateway.ScreeningEndpoint(cellular,
shouldScreen = { leg -> control.shouldScreen(leg.remote.number) },
prompt = { f -> control.prompts.get(control.screenPrompt, f) },
onScreened = { leg, audio, f -> control.screened(leg.remote, audio, f.sampleRate) },
log = { AppLog.i("bridge: $it") }),
sideB = sideB,
routeAtoB = { leg ->
if (control.isBlocked(leg.remote.number)) {
Expand Down Expand Up @@ -750,12 +755,25 @@ class GatewayRuntime private constructor(context: Context) {
val st = s.outbound?.state
// "Voicemail": an unanswered call is rejected after N seconds, so the carrier's
// forwarding (busy / no answer) takes it to voicemail.
val sec = control.noAnswerSec
val sec = control.noAnswerSec.takeIf { it > 0 } ?: if (control.voicemailOn) 25 else 0
if (sec > 0 && st == LegState.RINGING && s.connectedAtMs == null && s.endedAtMs == null && !noAnswer.containsKey(s.id)) {
val r = Runnable {
if (s.connectedAtMs == null && s.endedAtMs == null) {
AppLog.i("no answer after ${sec}s: handing the call to the carrier (voicemail)")
s.inbound.hangup(io.github.sparkcyf.voicesipagent.voice.HangupCause.BUSY)
val b = bridge
if (control.voicemailOn && b != null) {
// SimBridge's own voicemail: answer, record, send the message to the main phone.
AppLog.i("no answer after ${sec}s: taking a message")
b.takeOver(s) { leg ->
io.github.sparkcyf.voicesipagent.gateway.Voicemail.record(leg,
greeting = { f -> control.prompts.get(control.greeting, f) ?: ShortArray(0) },
maxMs = 120_000,
onMessage = { party, audio, f, at -> control.voicemailMessage(party, audio, f.sampleRate, at) },
log = { AppLog.i("bridge: $it") })
}
} else {
AppLog.i("no answer after ${sec}s: handing the call to the carrier (voicemail)")
s.inbound.hangup(io.github.sparkcyf.voicesipagent.voice.HangupCause.BUSY)
}
}
}
noAnswer[s.id] = r
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package io.github.sparkcyf.voicesipagent.app

import android.content.Context
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import io.github.sparkcyf.voicesipagent.voice.PcmFormat
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

/**
* Spoken prompts for the answering machine and call screening, made with this phone's
* text-to-speech and kept in memory per text and rate. [get] never waits on the call path:
* it returns null until [prepare] has made the prompt.
*/
class Prompts(private val app: Context) {
private val cache = ConcurrentHashMap<String, ShortArray>()

fun get(text: String, f: PcmFormat): ShortArray? = cache["${f.sampleRate}|$text"]

/** Makes both rates of [text] in the background (a few seconds the first time). */
fun prepare(text: String) {
if (text.isBlank() || listOf(8000, 16000).all { cache.containsKey("$it|$text") }) return
Thread({
val pcm = synchronized(this) { synth(text) } ?: return@Thread
listOf(PcmFormat.NARROWBAND, PcmFormat.WIDEBAND).forEach { f -> cache["${f.sampleRate}|$text"] = Wav.resample(pcm.first, pcm.second, f.sampleRate) }
AppLog.i("prompt ready (${pcm.first.size * 1000L / pcm.second} ms)")
}, "prompts").start()
}

private fun synth(text: String): Pair<ShortArray, Int>? {
val ready = CountDownLatch(1)
var ok = false
val tts = TextToSpeech(app) { ok = it == TextToSpeech.SUCCESS; ready.countDown() }
try {
if (!ready.await(10, TimeUnit.SECONDS) || !ok) return null
val out = File(app.cacheDir, "prompt-${text.hashCode()}.wav")
val done = CountDownLatch(1)
tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(id: String?) {}
override fun onDone(id: String?) = done.countDown()
@Deprecated("old API") override fun onError(id: String?) = done.countDown()
})
tts.synthesizeToFile(text, null, out, "p")
if (!done.await(20, TimeUnit.SECONDS)) return null
return Wav.read(out.readBytes()).also { out.delete() }
} finally {
tts.shutdown()
}
}
}

/** 16-bit mono WAV in and out, and a simple resampler. */
object Wav {
fun encode(pcm: ShortArray, rate: Int): ByteArray {
val b = java.nio.ByteBuffer.allocate(44 + pcm.size * 2).order(java.nio.ByteOrder.LITTLE_ENDIAN)
b.put("RIFF".toByteArray()).putInt(36 + pcm.size * 2).put("WAVE".toByteArray())
b.put("fmt ".toByteArray()).putInt(16).putShort(1).putShort(1).putInt(rate).putInt(rate * 2).putShort(2).putShort(16)
b.put("data".toByteArray()).putInt(pcm.size * 2)
pcm.forEach { b.putShort(it) }
return b.array()
}

/** First channel of a 16-bit PCM WAV, with its rate. */
fun read(bytes: ByteArray): Pair<ShortArray, Int>? {
val b = java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN)
if (bytes.size < 44) return null
b.position(12)
var rate = 0; var channels = 1
while (b.remaining() >= 8) {
val id = String(ByteArray(4).also { b.get(it) }); val len = b.int
when (id) {
"fmt " -> { b.short; channels = b.short.toInt(); rate = b.int; b.position(b.position() + len - 8) }
"data" -> {
val n = minOf(len, b.remaining()) / 2 / channels
return ShortArray(n) { val v = b.short; repeat(channels - 1) { b.short }; v } to rate
}
else -> b.position(minOf(b.limit(), b.position() + len))
}
}
return null
}

fun resample(x: ShortArray, from: Int, to: Int): ShortArray {
if (from == to || x.isEmpty() || from <= 0) return x
val ratio = from.toDouble() / to
return ShortArray((x.size / ratio).toInt()) { i ->
val p = i * ratio; val j = p.toInt(); val t = p - j
val a = x[minOf(j, x.size - 1)]; val c = x[minOf(j + 1, x.size - 1)]
(a + (c - a) * t).toInt().toShort()
}
}
}
Loading
Loading