Add voice calls and a local answering machine

Calls through D-Modem's V.253 voice mode, on the phone's earpiece or
loudspeaker and microphone: a number called, the ringing call answered,
the keypad (DTMF), mute. The answering machine, off until the user turns
it on, answers after the rings set, plays the greeting and a beep, and
keeps the caller's message as a WAV file on the phone.

The call is the shared Kotlin's VoiceJob (with G.711, tones and WAV
files, tested against a fake V.253 modem). Android has Home's Phone
section, a settings page and the incoming call popup's two new answers;
iOS a Phone tab. D-Modem bumped to main (Rockwell/USR voice, #109).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRTvbHMpudRfQWK4c4H
This commit is contained in:
Claude committed 2026-11-11 12:34:44 +00:00
1 parent 1b37fea6e7
commit 98aa27f9ea
33 files changed
+2966 -11

No files matched your search

+2 -1
View File
@@ -13,6 +13,7 @@ toward another digital modem, V.91 at up to 62667 bit/s both ways.
- A terminal, a dialling directory and the modem's AT console
- Class 1 fax up to 14400 bit/s: PDFs and images sent, faxes received as PDFs, T.38 too
- Voice calls through the modem on the phone's speaker and microphone, and an answering machine that keeps messages on the phone (off until turned on)
- A vintage computer's external modem, on a USB serial adapter, [pico-serial](https://github.com/D-Modem/hardware), Bluetooth serial or TCP
- Real phone lines through USB modems (the pico-serial Line stick among them), a Hayes modem on a serial adapter, or a Bluetooth modem
- Two phones as each other's line over Wi-Fi or Bluetooth, no SIP account needed
@@ -32,7 +33,7 @@ in [docs/building.md](docs/building.md).
The documentation is also a website, [d-modem.github.io/app](https://d-modem.github.io/app/), with reference pages made from the code.
[docs/](docs/README.md) covers the modem's lines, fax, adapters and
[docs/](docs/README.md) covers the modem's lines, fax, voice calls, adapters and
phone lines, every screen of the app, building for Android and iOS, and
the source layout.
@@ -42,6 +42,8 @@ class DModemApp : Application() {
org.dmodem.app.android.fax.Fax.init(this)
// dial-in: callers given the internet when the settings say so (after the fax's watch: its calls first)
org.dmodem.app.android.ppp.DialIn.init(this)
// voice calls: their settings and messages, and the answering machine (when it's turned on)
org.dmodem.app.android.voice.Voice.init(this)
// the log's first lines: which build, when; the USB modems plugged in, and as they're plugged in and out
ModemState.log.add("app: ${BuildInfo.described}, started ${org.dmodem.app.android.modem.LogFormat.now()}")
@@ -108,6 +108,7 @@ object Fax {
private fun busy(): String? = when {
ModemState.run.value != ModemState.Run.RUNNING -> "the modem is off"
running -> "a fax call is going on"
org.dmodem.app.android.voice.Voice.running -> "a voice call is going on"
ModemState.line == ModemSettings.LINE_CELL -> CELL_NO_FAX
ModemState.status.value.offhook -> "the modem is in a call"
Bridges.serial.client.value != null -> "the modem is in use by ${Bridges.serial.client.value?.name}"
@@ -107,6 +107,7 @@ object DialIn {
/** whether a call may be taken now: nothing else has the modem */
private fun free(): Boolean = call == null && !ModemState.dte.claimed && !Internet.running && !Fax.running &&
!org.dmodem.app.android.voice.Voice.running &&
Bridges.serial.client.value == null
/** the modem's line being read (its results come in pieces) */
@@ -76,6 +76,7 @@ object Internet {
ModemState.run.value != ModemState.Run.RUNNING -> "the modem is off"
running -> "it's connected already"
Fax.running -> "a fax call is going on"
org.dmodem.app.android.voice.Voice.running -> "a voice call is going on"
dial && ModemState.status.value.offhook -> "the modem is in a call"
!dial && ModemState.status.value.link != NativeModem.Link.ONLINE -> "no call to start PPP on: dial and log in first"
Bridges.serial.client.value != null -> "the modem is in use by ${Bridges.serial.client.value?.name}"
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.settings
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
/** Voice calls and the answering machine. */
data class VoiceSettings(
/** the answering machine takes the calls nobody answers (off until the user turns it on) */
val voicemail: Boolean = false,
/** after this many rings */
val rings: Int = 4,
/** a message this long at most (s) */
val maxSeconds: Int = 120,
/** a call's sound on the loudspeaker (else the earpiece) */
val speaker: Boolean = true,
)
private val Context.voiceStore: DataStore<Preferences> by preferencesDataStore("voice")
class VoiceSettingsStore(private val context: Context) {
private object K {
val voicemail = booleanPreferencesKey("voicemail")
val rings = intPreferencesKey("rings")
val maxSeconds = intPreferencesKey("max_seconds")
val speaker = booleanPreferencesKey("speaker")
}
/** the settings stored in [p], the defaults for what isn't */
private fun read(p: Preferences): VoiceSettings {
val d = VoiceSettings()
return VoiceSettings(p[K.voicemail] ?: d.voicemail, p[K.rings] ?: d.rings, p[K.maxSeconds] ?: d.maxSeconds, p[K.speaker] ?: d.speaker)
}
val settings: Flow<VoiceSettings> = context.voiceStore.data.map { p -> read(p) }
/** what's stored now */
suspend fun current(): VoiceSettings = settings.first()
/** a change made to what's stored now */
suspend fun update(change: (VoiceSettings) -> VoiceSettings) {
context.voiceStore.edit { p ->
val s = change(read(p))
p[K.voicemail] = s.voicemail
p[K.rings] = s.rings.coerceIn(1, 10)
p[K.maxSeconds] = s.maxSeconds.coerceIn(10, 600)
p[K.speaker] = s.speaker
}
}
}
@@ -169,6 +169,9 @@ fun DashboardScreen(
SectionTitle("Internet")
InternetCard(onSetUp = { SettingsNav.open(SettingsPage.INTERNET); onOpenSettings() })
SectionTitle("Phone")
PhoneSection(onOpenSettings = { SettingsNav.open(SettingsPage.VOICE); onOpenSettings() })
SectionTitle("Fax")
FaxSection()
@@ -25,8 +25,9 @@ import org.dmodem.app.android.modem.IncomingCalls
* ID's name and number, or the line's name for the caller), and what to
* do: answer it (the terminal, ATA: with adaptive answer a fax machine's
* call goes to the fax receiver by itself), answer
* it as a fax (without adaptive answer), or let it ring (out of sight
* until it's over).
* it as a fax (without adaptive answer), as a voice call (to talk, on the
* phone's speaker and microphone), by the answering machine, or let it
* ring (out of sight until it's over).
*/
@Composable
fun IncomingCallDialog(
@@ -35,6 +36,9 @@ fun IncomingCallDialog(
caller: String,
onAnswer: () -> Unit,
onFax: () -> Unit,
/** answered as a voice call (to talk), or by the answering machine */
onVoice: () -> Unit,
onMessage: () -> Unit,
onIgnore: () -> Unit,
/** answer as fax offered (adaptive answer off: a plain answer is a data call's) */
offerFax: Boolean = true,
@@ -60,6 +64,8 @@ fun IncomingCallDialog(
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Button(onClick = onAnswer, Modifier.fillMaxWidth()) { Text("Answer") }
if (offerFax) OutlinedButton(onClick = onFax, Modifier.fillMaxWidth()) { Text("Answer as fax") }
OutlinedButton(onClick = onVoice, Modifier.fillMaxWidth()) { Text("Answer as a voice call") }
OutlinedButton(onClick = onMessage, Modifier.fillMaxWidth()) { Text("Take a message") }
TextButton(
onClick = onIgnore,
Modifier.fillMaxWidth(),
@@ -118,6 +118,7 @@ class MainActivity : ComponentActivity() {
}
}
}
val mic = rememberMicrophone()
// a call ringing in: the popup, over any tab
val call by org.dmodem.app.android.modem.ModemState.incoming.state.collectAsStateWithLifecycle()
call?.takeIf { !it.ignored }?.let { c ->
@@ -129,6 +130,8 @@ class MainActivity : ComponentActivity() {
tab = TAB_TERMINAL
},
onFax = { answerAsFax() },
onVoice = { mic { voice(org.dmodem.app.android.voice.Voice.answer(this@MainActivity)) } },
onMessage = { voice(org.dmodem.app.android.voice.Voice.takeMessage(this@MainActivity)) },
onIgnore = { org.dmodem.app.android.modem.ModemState.incoming.ignore() },
offerFax = !org.dmodem.app.android.modem.ModemState.adaptiveAnswer,
)
@@ -237,6 +240,12 @@ class MainActivity : ComponentActivity() {
goTo.value = TAB_MODEM
}
/** a voice call answered (or why not, in a toast): shown on the modem's tab */
private fun voice(why: String?) {
if (why != null) android.widget.Toast.makeText(this, "Voice: $why", android.widget.Toast.LENGTH_LONG).show()
goTo.value = TAB_MODEM
}
/** the line's word for a caller it doesn't name */
private fun callerOfLine(): String = when (org.dmodem.app.android.modem.ModemState.line) {
org.dmodem.app.android.settings.ModemSettings.LINE_WIFI, org.dmodem.app.android.settings.ModemSettings.LINE_BLUETOOTH -> "The other phone"
@@ -0,0 +1,334 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.ui
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
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.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.dmodem.app.android.modem.ModemState
import org.dmodem.app.android.ppp.DialIn
import org.dmodem.app.android.settings.FaxSettingsStore
import org.dmodem.app.android.settings.VoiceSettingsStore
import org.dmodem.app.android.voice.Voice
import org.dmodem.app.io.monotonicMs
import org.dmodem.app.jobs.VoiceJob
import java.text.DateFormat
import java.util.Date
/** [then] run once the microphone is allowed (asked for if it isn't yet); a toast if it's refused */
@Composable
fun rememberMicrophone(): ((() -> Unit) -> Unit) {
val context = LocalContext.current
var pending by remember { mutableStateOf<(() -> Unit)?>(null) }
val ask = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { ok ->
val p = pending
pending = null
if (ok) p?.invoke() else Toast.makeText(context, "A call needs the microphone", Toast.LENGTH_LONG).show()
}
return { then ->
if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
then()
} else {
pending = then
ask.launch(Manifest.permission.RECORD_AUDIO)
}
}
}
/** [why] (a call that couldn't start) in a toast, if any */
private fun toast(context: Context, why: String?) {
if (why != null) Toast.makeText(context, why, Toast.LENGTH_LONG).show()
}
/** The home screen's phone: call a number, the call as it goes, the answering machine's messages. */
@Composable
fun PhoneSection(onOpenSettings: () -> Unit) {
val context = LocalContext.current
val state by Voice.state.collectAsStateWithLifecycle()
val run by ModemState.run.collectAsStateWithLifecycle()
val ringing by ModemState.incoming.state.collectAsStateWithLifecycle()
val messages by Voice.messages.collectAsStateWithLifecycle()
val store = remember { VoiceSettingsStore(context.applicationContext) }
val settings by store.settings.collectAsStateWithLifecycle(initialValue = null)
val mic = rememberMicrophone()
var callDialog by remember { mutableStateOf(false) }
val on = run == ModemState.Run.RUNNING
val free = on && state?.running != true
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
state?.let { VoiceCallCard(it) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = { callDialog = true }, enabled = free) { Text("Call a number…") }
if (ringing != null && free) {
OutlinedButton(onClick = { mic { toast(context, Voice.answer(context)) } }) { Text("Answer") }
OutlinedButton(onClick = { toast(context, Voice.takeMessage(context)) }) { Text("Take a message") }
}
}
if (!on) Text("The modem is off: start it to call", style = MaterialTheme.typography.bodySmall)
settings?.let { s ->
Text(
if (s.voicemail) "Answering machine on: it answers after ${s.rings} rings" else "Answering machine off",
Modifier.fillMaxWidth(),
style = MaterialTheme.typography.bodySmall,
)
if (!s.voicemail && messages.isEmpty()) {
TextButton(onClick = onOpenSettings) { Text("Set up the answering machine") }
}
}
for (m in messages.take(5)) MessageRow(m)
if (messages.size > 5) {
TextButton(onClick = onOpenSettings) { Text("All ${messages.size} messages") }
}
}
if (callDialog) {
CallDialog(onDismiss = { callDialog = false }) { number ->
callDialog = false
mic { toast(context, Voice.dial(context, number)) }
}
}
}
/** the call now or just ended: who, its phase or outcome, its time; hang up, mute, the loudspeaker, the keypad, or listen and pick up */
@Composable
private fun VoiceCallCard(st: VoiceJob.State) {
val listening by Voice.listening.collectAsStateWithLifecycle()
val muted by Voice.muted.collectAsStateWithLifecycle()
val speaker by Voice.speaker.collectAsStateWithLifecycle()
val mic = rememberMicrophone()
var keypad by remember { mutableStateOf(false) }
var now by remember { mutableLongStateOf(monotonicMs()) }
LaunchedEffect(st.running) {
while (st.running) {
now = monotonicMs()
delay(500)
}
}
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
val who = st.number.ifEmpty { if (st.calling) "the number" else "an unknown caller" }
Text(
when {
st.machine -> "Answering machine: $who"
st.calling -> "Call to $who"
else -> "Call from $who"
},
style = MaterialTheme.typography.titleSmall,
)
val time = if (st.since > 0 && st.running) " · " + clock((now - st.since) / 1000) else ""
Text(
when {
!st.running && st.message.isNotEmpty() -> "Took a message of ${st.messageSeconds} s"
!st.running && st.result == "" -> if (st.machine) "No message left" else "Call ended"
!st.running -> "Stopped: ${st.result}"
else -> when (st.phase) {
VoiceJob.Phase.STARTING -> "Starting"
VoiceJob.Phase.DIALLING -> "Calling…"
VoiceJob.Phase.ANSWERING -> "Answering"
VoiceJob.Phase.TALKING -> "In a call" + if (muted) " (muted)" else ""
VoiceJob.Phase.GREETING -> "Playing the greeting"
VoiceJob.Phase.RECORDING -> "Taking a message"
VoiceJob.Phase.ENDING -> "Hanging up"
} + time
} + if (st.digits.isNotEmpty()) " · keys ${st.digits}" else "",
style = MaterialTheme.typography.bodyMedium,
)
if (st.running) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Button(
onClick = { Voice.hangUp() },
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
) { Text("Hang up") }
if (st.machine) {
FilterChip(selected = listening, onClick = { Voice.listen(!listening) }, label = { Text("Listen") })
OutlinedButton(onClick = { mic { Voice.pickUp() } }) { Text("Pick up") }
} else if (st.phase == VoiceJob.Phase.TALKING) {
FilterChip(selected = muted, onClick = { Voice.mute(!muted) }, label = { Text("Mute") })
FilterChip(selected = speaker, onClick = { Voice.loudspeaker(!speaker) }, label = { Text("Speaker") })
FilterChip(selected = keypad, onClick = { keypad = !keypad }, label = { Text("Keypad") })
}
}
if (keypad && !st.machine && st.phase == VoiceJob.Phase.TALKING) Keypad { Voice.dtmf(it) }
} else {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
TextButton(onClick = { Voice.dismiss() }) { Text("OK") }
}
}
}
}
}
/** the phone's twelve keys: [onKey] for each pressed */
@Composable
private fun Keypad(onKey: (Char) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
for (row in listOf("123", "456", "789", "*0#")) {
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
for (k in row) {
OutlinedButton(onClick = { onKey(k) }, Modifier.weight(1f)) { Text(k.toString(), style = MaterialTheme.typography.titleMedium) }
}
}
}
}
}
/** m:ss */
private fun clock(s: Long) = "%d:%02d".format(s / 60, s % 60)
/** a message: from whom, when, how long; play it, delete it */
@Composable
private fun MessageRow(m: Voice.Message) {
val context = LocalContext.current
val playing by Voice.playing.collectAsStateWithLifecycle()
var confirm by remember { mutableStateOf(false) }
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { Voice.play(m.file) }) {
if (playing == m.file) Text("■", style = MaterialTheme.typography.titleMedium) else Icon(Icons.Filled.PlayArrow, "Play")
}
Column(Modifier.weight(1f)) {
Text(m.caller.ifEmpty { "Unknown caller" }, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(m.time)) + " · " + clock(m.seconds.toLong()),
style = MaterialTheme.typography.bodySmall,
)
}
IconButton(onClick = { confirm = true }) { Icon(Icons.Filled.Delete, "Delete") }
}
if (confirm) {
AlertDialog(
onDismissRequest = { confirm = false },
title = { Text("Delete this message?") },
confirmButton = { TextButton(onClick = { confirm = false; Voice.delete(context, m) }) { Text("Delete") } },
dismissButton = { TextButton(onClick = { confirm = false }) { Text("Cancel") } },
)
}
}
/** the number to call */
@Composable
private fun CallDialog(onDismiss: () -> Unit, onCall: (String) -> Unit) {
var number by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Call a number") },
text = {
OutlinedTextField(
value = number, onValueChange = { number = it }, label = { Text("Number") }, singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), modifier = Modifier.fillMaxWidth(),
)
},
confirmButton = { Button(onClick = { onCall(number) }, enabled = number.isNotBlank()) { Text("Call") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** The settings' phone section: the answering machine (off until turned on), its rings, the greeting, the longest message; all messages. */
@Composable
fun VoiceSettingsSection() {
val context = LocalContext.current
val store = remember { VoiceSettingsStore(context.applicationContext) }
val current by store.settings.collectAsStateWithLifecycle(initialValue = null)
val fax by remember { FaxSettingsStore(context.applicationContext) }.settings.collectAsStateWithLifecycle(initialValue = null)
val greeting by Voice.greeting.collectAsStateWithLifecycle()
val recording by Voice.recording.collectAsStateWithLifecycle()
val messages by Voice.messages.collectAsStateWithLifecycle()
val mic = rememberMicrophone()
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) Voice.chooseGreeting(context, uri)?.let { Toast.makeText(context, "That greeting: $it", Toast.LENGTH_LONG).show() }
}
LaunchedEffect(Unit) { Voice.reload(context) }
val s = current ?: return
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Answering machine")
Text("Takes a message when nobody answers a call. Messages stay on this phone.", style = MaterialTheme.typography.bodySmall)
}
Switch(checked = s.voicemail, onCheckedChange = { v -> SettingsSaving.scope.launch { store.update { it.copy(voicemail = v) } } })
}
if (s.voicemail && (fax?.answer == true || DialIn.enabled)) {
Text(
if (fax?.answer == true) "The fax settings answer every call first: the answering machine waits until that's off"
else "Dial-in answers every call first: the answering machine waits until that's off",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text("Answer after", Modifier.weight(1f))
TextButton(onClick = { SettingsSaving.scope.launch { store.update { it.copy(rings = it.rings - 1) } } }, enabled = s.rings > 1) { Text("−") }
Text("${s.rings} ring${if (s.rings == 1) "" else "s"}")
TextButton(onClick = { SettingsSaving.scope.launch { store.update { it.copy(rings = it.rings + 1) } } }, enabled = s.rings < 10) { Text("+") }
}
Text("Longest message", style = MaterialTheme.typography.bodyMedium)
for ((sec, label) in listOf(60 to "1 minute", 120 to "2 minutes", 300 to "5 minutes")) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
RadioButton(selected = s.maxSeconds == sec, onClick = { SettingsSaving.scope.launch { store.update { it.copy(maxSeconds = sec) } } })
Text(label, Modifier.padding(start = 8.dp))
}
}
Text(
when {
recording -> "Recording the greeting: speak now"
greeting > 0 -> "Greeting: $greeting s"
else -> "Greeting: none, callers hear a beep"
},
style = MaterialTheme.typography.bodyMedium,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (recording) {
Button(onClick = { Voice.stopRecording() }) { Text("Stop") }
} else {
OutlinedButton(onClick = { mic { Voice.recordGreeting(context) } }) { Text("Record") }
OutlinedButton(onClick = { Voice.playGreeting(context) }, enabled = greeting > 0) { Text("Play") }
OutlinedButton(onClick = { pick.launch(arrayOf("audio/wav", "audio/x-wav", "audio/*")) }) { Text("File…") }
TextButton(onClick = { Voice.clearGreeting(context) }, enabled = greeting > 0) { Text("None") }
}
}
Text("Messages", style = MaterialTheme.typography.titleSmall)
if (messages.isEmpty()) Text("None yet", style = MaterialTheme.typography.bodySmall)
for (m in messages) MessageRow(m)
}
}
@@ -52,6 +52,14 @@ object SettingsIcons {
)
}
/** Material Icons' voicemail */
val Voicemail: ImageVector by lazy {
icon(
"voicemail",
"M18.5,6C15.46,6,13,8.46,13,11.5c0,1.33,0.47,2.55,1.26,3.5H9.74C10.53,14.05,11,12.83,11,11.5C11,8.46,8.54,6,5.5,6S0,8.46,0,11.5S2.46,17,5.5,17h13c3.04,0,5.5-2.46,5.5-5.5S21.54,6,18.5,6z M5.5,15C3.57,15,2,13.43,2,11.5S3.57,8,5.5,8S9,9.57,9,11.5S7.43,15,5.5,15z M18.5,15c-1.93,0-3.5-1.57-3.5-3.5S16.57,8,18.5,8S22,9.57,22,11.5S20.43,15,18.5,15z",
)
}
/** Material Icons' language */
val Internet: ImageVector by lazy {
icon(
@@ -58,6 +58,7 @@ enum class SettingsPage(val title: String) {
MODEM("Modem"),
BRIDGES("Serial bridges"),
FAX("Fax"),
VOICE("Phone and answering machine"),
INTERNET("Dial-up internet"),
APPEARANCE("Appearance"),
TERMINAL("Terminal"),
@@ -73,6 +74,7 @@ enum class SettingsPage(val title: String) {
MODEM -> SettingsIcons.Modem
BRIDGES -> SettingsIcons.Bridges
FAX -> SettingsIcons.Fax
VOICE -> SettingsIcons.Voicemail
INTERNET -> SettingsIcons.Internet
APPEARANCE -> SettingsIcons.Appearance
TERMINAL -> SettingsIcons.Terminal
@@ -257,6 +259,7 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {
}
SettingsPage.BRIDGES -> BridgeSection()
SettingsPage.FAX -> FaxSettingsSection()
SettingsPage.VOICE -> VoiceSettingsSection()
SettingsPage.INTERNET -> IspSettingsSection()
SettingsPage.APPEARANCE -> AppearanceSection()
SettingsPage.TERMINAL -> TerminalSettingsSection()
@@ -301,6 +304,7 @@ private fun SettingsMenu(modifier: Modifier, s: ModemSettings) {
(if (s.speaker) "on" else "off") + "; " + (if (s.adaptiveAnswer) "fax or data as calls turn out" else "calls answered as data"),
SettingsPage.BRIDGES to "The modem for another computer: TCP, Bluetooth, USB serial",
SettingsPage.FAX to "This fax's number and name, answering, the rates",
SettingsPage.VOICE to "Voice calls; the answering machine, its greeting and messages",
SettingsPage.INTERNET to "The ISP to dial; dial-in for callers",
SettingsPage.APPEARANCE to "Theme, dark mode, colours",
SettingsPage.TERMINAL to "Emulation, fonts, colours, keys",
@@ -0,0 +1,385 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.voice
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.dmodem.app.android.DModemApp
import org.dmodem.app.android.R
import org.dmodem.app.android.bridge.Bridges
import org.dmodem.app.android.fax.Fax
import org.dmodem.app.android.modem.ModemState
import org.dmodem.app.android.ppp.DialIn
import org.dmodem.app.android.ppp.Internet
import org.dmodem.app.android.settings.FaxSettingsStore
import org.dmodem.app.android.settings.VoiceSettings
import org.dmodem.app.android.settings.VoiceSettingsStore
import org.dmodem.app.android.terminal.TerminalLink
import org.dmodem.app.jobs.VoiceJob
import org.dmodem.app.transfer.FolderIncoming
import org.dmodem.app.voice.VOICE_RATE
import org.dmodem.app.voice.Wav
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Voice calls on the modem (its V.253 voice mode, the shared VoiceJob):
* a number called, or the call ringing answered, with the phone's
* earpiece or loudspeaker and microphone; and the answering machine,
* when the user has turned it on, answering a call nobody has after the
* rings set, its messages kept in the app's own storage (voicemail/, WAV
* files) and nowhere else. A call has the modem's DTE to itself while it
* lasts.
*/
// (it holds the application's context, which lives as long as the process does)
@android.annotation.SuppressLint("StaticFieldLeak")
object Voice {
/** a message the answering machine took */
data class Message(val file: File, val time: Long, val caller: String, val seconds: Int)
private val _state = MutableStateFlow<VoiceJob.State?>(null)
/** the call going, or how the last one ended (null: none) */
val state: StateFlow<VoiceJob.State?> = _state.asStateFlow()
private val _messages = MutableStateFlow<List<Message>>(emptyList())
/** the answering machine's messages, newest first */
val messages: StateFlow<List<Message>> = _messages.asStateFlow()
private val _greeting = MutableStateFlow(0)
/** the greeting's length (s; 0: none, callers hear the beep alone) */
val greeting: StateFlow<Int> = _greeting.asStateFlow()
private val _listening = MutableStateFlow(false)
/** a message being left heard on the loudspeaker */
val listening: StateFlow<Boolean> = _listening.asStateFlow()
private val _muted = MutableStateFlow(false)
val muted: StateFlow<Boolean> = _muted.asStateFlow()
private val _speaker = MutableStateFlow(true)
val speaker: StateFlow<Boolean> = _speaker.asStateFlow()
/** the message or greeting playing (its file), or null */
private val _playing = MutableStateFlow<File?>(null)
val playing: StateFlow<File?> = _playing.asStateFlow()
@Volatile private var job: VoiceJob? = null
@Volatile private var audio: VoiceAudio? = null
@Volatile private var settings = VoiceSettings()
@Volatile private var faxAnswers = false
private var app: Context? = null
private var watching = false
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val running: Boolean get() = _state.value?.running == true
/** the messages' folder */
private fun folder(c: Context) = File(c.filesDir, "voicemail").apply { mkdirs() }
/** the greeting's file */
private fun greetingFile(c: Context) = File(c.filesDir, "voicemail-greeting.wav")
/** why a call can't start now, or null; [answering]: the call ringing is the one */
private fun busy(answering: Boolean): String? = when {
ModemState.run.value != ModemState.Run.RUNNING -> "the modem is off"
running -> "a voice call is going on"
Fax.running -> "a fax call is going on"
Internet.running -> "the modem is connected to the internet"
!answering && ModemState.status.value.offhook -> "the modem is in a call"
Bridges.serial.client.value != null -> "the modem is in use by ${Bridges.serial.client.value?.name}"
ModemState.dte.claimed -> "the modem is in use"
else -> null
}
/** [number] called: null when it's started, else why it can't */
fun dial(context: Context, number: String): String? {
busy(false)?.let { return it }
if (number.isBlank()) return "no number"
return start(context) { it.dial(number) }
}
/** the call ringing answered, to talk: null when it's started, else why it can't */
fun answer(context: Context): String? {
busy(true)?.let { return it }
val caller = callerNumber()
ModemState.incoming.end()
return start(context) { it.answer(caller) }
}
/** the call ringing answered by the answering machine: null when it's started, else why it can't */
fun takeMessage(context: Context): String? {
busy(true)?.let { return it }
val c = context.applicationContext
val caller = callerNumber()
ModemState.incoming.end()
val greeting = runCatching { greetingFile(c).takeIf { it.exists() }?.readBytes()?.let { Wav.decode(it) } }.getOrNull()
val name = VoiceJob.messageName(SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()), caller)
return start(context) { it.takeMessage(greeting, settings.maxSeconds, VoiceJob.MESSAGE_SILENCE_S, FolderIncoming(folder(c)), name, caller) }
}
/** caller ID's number for the call ringing, or "" */
private fun callerNumber(): String =
ModemState.incoming.state.value?.number?.takeIf { it.isNotBlank() && it != "P" && it != "O" } ?: ""
/** the answering machine's call taken: the call on the speaker and microphone */
fun pickUp() {
val j = job ?: return
if (j.pickUp()) {
_listening.value = false
audio?.start(talk = true, speaker = _speaker.value)
}
}
/** a message being left heard (or not) on the loudspeaker */
fun listen(on: Boolean) {
val j = job ?: return
if (j.state?.machine != true) return
_listening.value = on
if (on) audio?.start(talk = false, speaker = true) else stopAudio()
}
/** the call hung up */
fun hangUp() {
job?.hangUp()
}
/** DTMF digit [d] played to the far end */
fun dtmf(d: Char) {
job?.dtmf(d)
}
/** our microphone muted (the far end hears silence) or not */
fun mute(on: Boolean) {
_muted.value = on
job?.muted = on
}
/** the call's sound on the loudspeaker (else the earpiece), kept for the next call */
fun loudspeaker(on: Boolean) {
_speaker.value = on
audio?.setSpeaker(on)
scope.launch { app?.let { a -> VoiceSettingsStore(a).update { it.copy(speaker = on) } } }
}
/** the last call's outcome cleared, once it's over */
fun dismiss() {
if (!running) _state.value = null
}
/** a job on the modem's DTE, [begin] it: null, or why it couldn't */
private fun start(context: Context, begin: (VoiceJob) -> Unit): String? {
val c = context.applicationContext
app = c
val hub = ModemState.dte
lateinit var listener: TerminalLink.Listener
lateinit var j: VoiceJob
j = VoiceJob(
{ s -> hub.writeAs(listener, s.toByteArray(Charsets.ISO_8859_1)) },
{ ModemState.log.add(it) },
{ changed(c, j, listener) },
)
listener = TerminalLink.Listener { d, n -> j.feed(String(d, 0, n, Charsets.ISO_8859_1)) }
if (!hub.claim(listener)) return "the modem is in use"
job = j
_muted.value = false
_listening.value = false
_speaker.value = settings.speaker
audio = VoiceAudio(c, j)
begin(j)
return null
}
/** the job's state changed (on its thread): the sound started or stopped; at its end, the DTE given back */
private fun changed(c: Context, j: VoiceJob, listener: TerminalLink.Listener) {
val s = j.state ?: return
val before = _state.value
_state.value = s
if (s.phase == VoiceJob.Phase.TALKING && before?.phase != VoiceJob.Phase.TALKING) {
audio?.start(talk = true, speaker = _speaker.value)
}
if (s.phase == VoiceJob.Phase.ENDING) stopAudio()
if (!s.running && job === j) {
stopAudio()
audio = null
job = null
_listening.value = false
ModemState.dte.release(listener)
reload(c)
if (s.message.isNotEmpty()) notifyMessage(c, s)
}
}
/** the call's sound stopped */
private fun stopAudio() {
audio?.stop()
}
// ------------------------------------------------------------------
// messages and the greeting
/** the messages read from their folder, the greeting's length */
fun reload(context: Context) {
val c = context.applicationContext
val format = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US)
_messages.value = (folder(c).listFiles { f -> f.name.endsWith(".wav") } ?: emptyArray())
.map { f ->
val t = runCatching { format.parse(f.name.take(15))?.time }.getOrNull() ?: f.lastModified()
Message(f, t, VoiceJob.messageCaller(f.name), Wav.seconds(f.length()))
}
.sortedByDescending { it.time }
val g = greetingFile(c)
_greeting.value = if (g.exists()) maxOf(1, Wav.seconds(g.length())) else 0
}
/** [m] deleted */
fun delete(context: Context, m: Message) {
if (_playing.value == m.file) stopPlaying()
m.file.delete()
reload(context)
}
/** [f] (a WAV) played on the loudspeaker; again, it stops */
fun play(f: File) {
if (_playing.value == f) {
stopPlaying()
return
}
val pcm = runCatching { Wav.decode(f.readBytes()) }.getOrNull() ?: return
_playing.value = f
Sounds.play(pcm) { if (_playing.value == f) _playing.value = null }
}
/** what's playing stopped */
fun stopPlaying() {
_playing.value = null
Sounds.stop()
}
/** the greeting played */
fun playGreeting(context: Context) {
val g = greetingFile(context.applicationContext)
if (g.exists()) play(g)
}
private val _recording = MutableStateFlow(false)
/** the greeting being recorded from the microphone */
val recording: StateFlow<Boolean> = _recording.asStateFlow()
/** the greeting recorded from the microphone (until [stopRecording], 60 s at most): false without one */
fun recordGreeting(context: Context) {
if (_recording.value) return
val c = context.applicationContext
stopPlaying()
_recording.value = true
Thread({
try {
val pcm = Sounds.record(GREETING_MAX_S)
if (pcm == null) {
ModemState.log.add("voice: no microphone for the greeting")
} else if (pcm.size >= VOICE_RATE / 2) {
greetingFile(c).writeBytes(Wav.encode(pcm))
}
} finally {
_recording.value = false
reload(c)
}
}, "voice-greeting").apply { isDaemon = true; start() }
}
/** the greeting's recording ended (it's kept) */
fun stopRecording() = Sounds.stopRecording()
/** the greeting from a WAV file the user chose: null, or why not */
fun chooseGreeting(context: Context, uri: Uri): String? {
val c = context.applicationContext
val data = runCatching { c.contentResolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() ?: return "it can't be read"
val pcm = Wav.decode(data) ?: return "it isn't a WAV file of PCM, A-law or μ-law"
if (pcm.isEmpty()) return "it has no sound"
val n = minOf(pcm.size, GREETING_MAX_S * VOICE_RATE)
greetingFile(c).writeBytes(Wav.encode(pcm, n))
reload(c)
return null
}
/** no greeting: callers hear the beep alone */
fun clearGreeting(context: Context) {
greetingFile(context.applicationContext).delete()
reload(context)
}
/** a new message's notification: from whom, how long; a tap opens the app */
private fun notifyMessage(c: Context, s: VoiceJob.State) {
val open = PendingIntent.getActivity(
c, 3, Intent(c, org.dmodem.app.android.ui.MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val n = NotificationCompat.Builder(c, DModemApp.CHANNEL_MODEM)
.setSmallIcon(R.drawable.ic_modem)
.setContentTitle("New voice message")
.setContentText("From ${s.number.ifEmpty { "an unknown caller" }}, ${s.messageSeconds} s")
.setContentIntent(open)
.setAutoCancel(true)
.build()
runCatching { c.getSystemService(NotificationManager::class.java).notify(MESSAGE_NOTIFICATION_ID, n) }
}
// ------------------------------------------------------------------
/** the settings watched, the messages read, and ringing calls answered by the answering machine when it's on */
fun init(context: Context) {
val c = context.applicationContext
app = c
if (watching) return
watching = true
scope.launch { VoiceSettingsStore(c).settings.collect { settings = it; _speaker.value = it.speaker } }
scope.launch { FaxSettingsStore(c).settings.collect { faxAnswers = it.answer } }
scope.launch { reload(c) }
ModemState.dte.addListener(TerminalLink.Listener { data, n -> ringing(c, String(data, 0, n, Charsets.ISO_8859_1)) })
}
private val line = StringBuilder()
private var rings = 0
private var lastRing = 0L
/**
* the modem's text: its RINGs counted, and after the rings set the call answered by the answering
* machine (when it's on, and nothing else answers calls: the fax settings' answering, dial-in)
*/
@Synchronized
private fun ringing(c: Context, text: String) {
for (ch in text) {
if (ch != '\r' && ch != '\n') {
if (line.length < 64) line.append(ch)
continue
}
val l = line.toString().trim()
line.setLength(0)
if (l != "RING") continue
val now = System.currentTimeMillis()
if (now - lastRing > RING_GAP_MS) rings = 0
lastRing = now
rings++
val s = settings
if (s.voicemail && rings == s.rings && !faxAnswers && !DialIn.enabled && !running) {
rings = 0
Thread { takeMessage(c)?.let { ModemState.log.add("voice: the answering machine didn't answer: $it") } }.start()
}
}
}
private const val RING_GAP_MS = 8000L
private const val GREETING_MAX_S = 60
private const val MESSAGE_NOTIFICATION_ID = 41
}
@@ -0,0 +1,222 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.voice
import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioDeviceInfo
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioTrack
import android.media.MediaRecorder
import android.os.Build
import org.dmodem.app.jobs.VoiceJob
import org.dmodem.app.voice.VOICE_RATE
/**
* A voice call's sound on the phone: the far end's samples to the
* earpiece or the loudspeaker (an AudioTrack, as a call's), the
* microphone's to the line (an AudioRecord with the phone's echo
* cancelling, VOICE_COMMUNICATION); each on a thread of its own, 20 ms
* at a time. The phone in its call mode while it lasts.
*/
class VoiceAudio(private val context: Context, private val job: VoiceJob) {
@Volatile private var running = false
private var play: Thread? = null
private var mic: Thread? = null
private val am = context.getSystemService(AudioManager::class.java)
private var oldMode = AudioManager.MODE_NORMAL
/** the speaker on (the far end heard), and the microphone if [talk] */
@Synchronized
fun start(talk: Boolean, speaker: Boolean) {
if (!running) {
running = true
oldMode = am.mode
runCatching { am.mode = AudioManager.MODE_IN_COMMUNICATION }
setSpeaker(speaker)
play = Thread({ playLoop() }, "voice-speaker").apply { isDaemon = true; start() }
}
if (talk && mic == null) mic = Thread({ micLoop() }, "voice-mic").apply { isDaemon = true; start() }
}
/** the loudspeaker (true) or the earpiece */
fun setSpeaker(on: Boolean) {
runCatching {
if (Build.VERSION.SDK_INT >= 31) {
if (on) {
am.availableCommunicationDevices.firstOrNull { it.type == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER }
?.let { am.setCommunicationDevice(it) }
} else {
am.clearCommunicationDevice()
}
} else {
@Suppress("DEPRECATION")
am.isSpeakerphoneOn = on
}
}
}
/** all stopped, the phone's sound as it was */
@Synchronized
fun stop() {
if (!running) return
running = false
play?.join(500)
mic?.join(500)
play = null
mic = null
runCatching {
if (Build.VERSION.SDK_INT >= 31) am.clearCommunicationDevice()
am.mode = oldMode
}
}
/** the far end's samples to the speaker (silence when none came): about 100 ms behind at most */
private fun playLoop() {
val min = AudioTrack.getMinBufferSize(VOICE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
val t = AudioTrack.Builder()
.setAudioAttributes(
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build(),
)
.setAudioFormat(
AudioFormat.Builder().setSampleRate(VOICE_RATE).setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build(),
)
.setBufferSizeInBytes(maxOf(min, FRAME * 2 * 4))
.setTransferMode(AudioTrack.MODE_STREAM)
.build()
val buf = ShortArray(FRAME)
try {
t.play()
while (running) {
// (the far end ahead of the speaker: its oldest dropped)
if (job.readable > BEHIND_MAX) job.keepReadable(FRAME * 2)
val n = job.read(buf, 0, FRAME)
if (n < FRAME) buf.fill(0, n, FRAME)
t.write(buf, 0, FRAME)
}
} catch (e: RuntimeException) {
org.dmodem.app.android.modem.ModemState.log.add("voice: the speaker: $e")
} finally {
runCatching { t.stop() }
t.release()
}
}
/** the microphone's samples to the line */
@SuppressLint("MissingPermission")
private fun micLoop() {
val min = AudioRecord.getMinBufferSize(VOICE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
val r = try {
AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, VOICE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, maxOf(min, FRAME * 2 * 4))
} catch (e: RuntimeException) {
org.dmodem.app.android.modem.ModemState.log.add("voice: no microphone: $e")
return
}
val buf = ShortArray(FRAME)
try {
if (r.state != AudioRecord.STATE_INITIALIZED) {
org.dmodem.app.android.modem.ModemState.log.add("voice: no microphone (is it allowed?)")
return
}
r.startRecording()
while (running) {
val n = r.read(buf, 0, FRAME)
if (n > 0) job.write(buf, 0, n) else if (n < 0) break
}
} finally {
runCatching { r.stop() }
r.release()
}
}
companion object {
/** 20 ms */
const val FRAME = VOICE_RATE / 50
private const val BEHIND_MAX = VOICE_RATE / 4
}
}
/** A WAV's samples (8000 Hz) played to the loudspeaker, or the microphone recorded: the greeting, the messages. */
object Sounds {
@Volatile private var playing: Thread? = null
@Volatile private var stopPlay = false
@Volatile private var recording = false
/** [pcm] played (what was playing stopped); [done] at its end, on the player's thread */
fun play(pcm: ShortArray, done: () -> Unit = {}) {
stop()
stopPlay = false
playing = Thread({
val min = AudioTrack.getMinBufferSize(VOICE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
val t = AudioTrack.Builder()
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
.setAudioFormat(AudioFormat.Builder().setSampleRate(VOICE_RATE).setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build())
.setBufferSizeInBytes(maxOf(min, VOICE_RATE / 5 * 2))
.setTransferMode(AudioTrack.MODE_STREAM)
.build()
try {
t.play()
var at = 0
while (at < pcm.size && !stopPlay) {
val n = minOf(VoiceAudio.FRAME * 5, pcm.size - at)
t.write(pcm, at, n)
at += n
}
// (what's in its buffer heard out)
if (!stopPlay) Thread.sleep(250)
} catch (_: Exception) {
} finally {
runCatching { t.stop() }
t.release()
done()
}
}, "voice-play").apply { isDaemon = true; start() }
}
/** what's playing stopped */
fun stop() {
stopPlay = true
playing?.join(1000)
playing = null
}
/** the microphone recorded until [stopRecording] or [maxS]: its samples, or null without a microphone (on this thread) */
@SuppressLint("MissingPermission")
fun record(maxS: Int): ShortArray? {
val min = AudioRecord.getMinBufferSize(VOICE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
val r = runCatching {
AudioRecord(MediaRecorder.AudioSource.MIC, VOICE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, 3200))
}.getOrNull() ?: return null
if (r.state != AudioRecord.STATE_INITIALIZED) {
r.release()
return null
}
val out = ShortArray(maxS * VOICE_RATE)
var n = 0
recording = true
try {
r.startRecording()
while (recording && n < out.size) {
val k = r.read(out, n, minOf(VoiceAudio.FRAME, out.size - n))
if (k < 0) break
n += k
}
} finally {
recording = false
runCatching { r.stop() }
r.release()
}
return out.copyOf(n)
}
/** the recording ended */
fun stopRecording() {
recording = false
}
}
+1
View File
@@ -2,6 +2,7 @@
- [The modem's line](lines.md): SIP, the phone's own mobile calls, no line, two phones as each other's line
- [Fax](fax.md)
- [Voice calls and the answering machine](voice.md)
- [Serial adapters and real phone lines](adapters.md): pico-serial, USB modems, a modem on a USB serial adapter, a Bluetooth modem
- [The app, screen by screen](features.md)
- [Terminal types](terminals.md): the DEC line, PETSCII, ATASCII, videotex, ANSI-BBS and the graphics terminals, and how to test them
+4 -2
View File
@@ -5,7 +5,8 @@
its rates down and up and the call's time) and the one thing to do about
it (set up SIP, start, hang up, stop); the line (the SIP account,
incoming calls, the network, fax); quick dial of the systems last
dialled; the terminal and the directory; the modem's console (folded,
dialled; the phone (a voice call made or answered, the answering
machine's messages: [voice.md](voice.md)); the terminal and the directory; the modem's console (folded,
with an AT command line).
- **A call ringing in** (SIP, the other phone, a mobile call): the
phone's incoming call notification (heads-up, over the lock screen,
@@ -13,7 +14,8 @@
line says (the other phone's name): Answer (ATA: a fax machine's call
goes to the fax receiver by itself, a modem's to the terminal), or
Ignore (it rings on, out of sight); Answer as fax too when adaptive
answer is off. Gone when the modem
answer is off; Answer as a voice call, or Take a message (the
answering machine). Gone when the modem
answers (here, a computer on a bridge, S0) or the caller gives up.
- **Settings**: the SIP account (or paste `user:password@host`, as
dmodemd's `SIP_LOGIN`), taking incoming calls, T.38, the AT commands
+5 -2
View File
@@ -12,7 +12,7 @@ The Kotlin the two apps share is `shared/` (Kotlin Multiplatform: the
JVM for Android, iOS's framework `DModemShared`; Linux native for its
tests): the terminal's emulator, the file transfers (X/Y/ZMODEM, Kermit, Intel HEX and S-records, plain text),
PPP (its client and server, the chat scripts), fax (T.4, T.30, class 1,
the PDF) and the line to another phone (PeerLine), on a small common I/O
the PDF), voice calls and the answering machine (V.253, μ-law, WAV) and the line to another phone (PeerLine), on a small common I/O
layer (`shared/.../io`). What stays each app's own: the UI, the modem
service, sockets and Bluetooth, Android's VPN and files. Its tests run on
the JVM and natively: `./gradlew :shared:allTests`.
@@ -28,6 +28,9 @@ offered and found with Bonjour (`_dmodem._tcp`, as Android's NSD). It has:
colours, Esc/Ctrl/Tab/arrows) and its file transfers (ZMODEM, YMODEM,
XMODEM, Kermit, Intel HEX, S-records, plain text; a remote's `sz` or `kermit -s`
starts one by itself)
- Phone: voice calls through the modem (dialled, answered, the keypad);
the answering machine, off until turned on, its greeting and messages
([voice.md](voice.md))
- Fax: PDFs, images and text sent; a ringing call answered as a fax, by
hand or each one; the received faxes as PDFs
- Internet: dial-up to an ISP (its login script if it has one, PPP), the
@@ -45,7 +48,7 @@ no push service, a call can't wake it). Dial-up's VPN needs the Network
Extensions capability on the app's team.
What the screens run is the shared Kotlin's jobs (`shared/.../jobs`: a
fax call, a transfer, dial-up, each lent the modem's DTE while it lasts),
fax call, a voice call, a transfer, dial-up, each lent the modem's DTE while it lasts),
tested on the JVM and natively. The modem apart from the views is the
`ios/DModemKit` Swift package (the engine from Swift, its DTE and who
it's lent to, the settings and their secrets, the session), whose tests
+3
View File
@@ -67,6 +67,9 @@ Every setting the apps keep, from their code. [The app, screen by screen](featur
| `faxMaxBps` | | number | `14400` | As above. |
| `faxFine` | | on/off | `true` | As above. |
| `faxAutoAnswer` | | on/off | `false` | As above. |
| `voicemail` | | on/off | `false` | Voice calls: the answering machine takes calls nobody answers (off until turned on), after this many rings, a message this long at most (s). |
| `voicemailRings` | | number | `4` | As above. |
| `voicemailMaxSeconds` | | number | `120` | As above. |
| `ispNumber` | | text | (empty) | Dial-up internet: the ISP's number, login, its login script (chat, if any), the modem's commands first. |
| `ispUser` | | text | (empty) | As above. |
| `ispPassword` | `isp-password` | text | (empty) | As above. |
+71
View File
@@ -0,0 +1,71 @@
# Voice calls and the answering machine
The modem makes and takes voice calls: a number called, or the call
ringing answered, with the phone's earpiece or loudspeaker and its
microphone. When it's turned on, the answering machine takes the calls
nobody answers and keeps the messages on the phone.
It is D-Modem's V.253 voice mode, as a fax is its class 1: the shared
Kotlin's `VoiceJob` (`shared/.../jobs/VoiceJob.kt`) is lent the modem's
DTE for the call, and sends
| Step | Command | The modem's answer |
| --- | --- | --- |
| Voice mode, G.711 μ-law at 8000 Hz | `AT+FCLASS=8`, `AT+VSM=4` | `OK` |
| A call made | `ATD<number>` | `OK` once the far end answers; `BUSY`, `NO ANSWER` |
| The ringing call answered | `AT+VLS=1` | `OK` |
| The call's sound, both ways | `AT+VTR` | `CONNECT`, then the stream |
| Hung up | `<DLE>^`, then `ATH`, `AT+FCLASS=0` | `<DLE><ETX>`, `OK` |
The stream is μ-law octets both ways, a `<DLE>` doubled. The modem's
`<DLE>` codes say what it heard: `l` the far end hung up, `b` a busy
tone, `d` a dial tone (both: the exchange saying the caller has gone),
the DTMF digits pressed. Our samples go at the line's pace, by the clock,
60 ms ahead; silence when the microphone has none. The keypad's digits
are DTMF tones in our sound.
Any line the modem has carries it: SIP, the line to another phone, a USB
modem's phone line (when that modem has voice mode). A modem without it
answers `ERROR` to `AT+FCLASS=8`, and the call stops with "the modem has
no voice mode".
## The answering machine
Off until it's turned on (Android: Settings › Phone and answering
machine; iOS: the Phone tab). When it's on, after the rings set (4 by
default) it answers the call, plays the greeting (or none) and a beep,
and records the caller until
- they hang up (a busy or dial tone's start is cut from the message),
- they have been quiet for 7 s (half a second of the quiet is kept), or
- the longest message (2 minutes by default) has gone.
A message under a second isn't kept. Each one is a WAV file (16-bit PCM,
8000 Hz, mono) named for its time and the caller's number when caller ID
gave it, `20261111-093000_5551234.wav`: on Android in the app's own
storage (`files/voicemail`), on iOS in Documents/Voicemail (the Files
app shows it). Nothing leaves the phone.
While a message is being left, **Listen** plays it on the loudspeaker
and **Pick up** turns it into a call (the message isn't kept). The
greeting is recorded with the microphone (a minute at most) or chosen
from a WAV file (PCM, A-law or μ-law, any rate: mixed to one channel and
resampled to 8000 Hz).
Calls answered as faxes by the fax settings, or by dial-in, are answered
on the first ring: with either on, the answering machine waits.
## Where it is
- Android: Home's **Phone** (call a number, the call as it goes, the
messages), the incoming call's popup (**Answer as a voice call**,
**Take a message**), Settings › **Phone and answering machine**.
`voice/Voice.kt` runs the call, `voice/VoiceAudio.kt` its sound (an
AudioTrack for the speaker; an AudioRecord with the phone's echo
cancelling, `VOICE_COMMUNICATION`, for the microphone).
- iOS: the **Phone** tab. `JobsModel` runs the call, `VoiceSound.swift`
its sound (AVAudioEngine in the voice chat mode).
The tests (`shared/src/commonTest/.../voice/VoiceTest.kt`) run a call,
a busy number, a modem without voice mode, messages that end by a
hang-up and by quiet, and one picked up, against a fake V.253 modem.
+36 -1
View File
@@ -35,6 +35,9 @@ final class AppModel: ObservableObject {
/// the last of what the modem said, looked at for RING and the caller's number
private var ringScan = ""
private var callerId: String?
/// the ringing call's RINGs so far, and when the last came
private var rings = 0
private var lastRing = Date.distantPast
/// what's typed at the terminal on its line, and the number its last ATD dialled
private var typedLine = ""
private var lastDial = ""
@@ -59,6 +62,7 @@ final class AppModel: ObservableObject {
calls.onAnswer = { [weak self] in self?.session.command("ATA") }
calls.onEnd = { [weak self] in self?.callEndedByUser() }
calls.onAudio = { [audio] on in if on { audio.resume() } }
jobs.voiceEnded = { [audio] in audio.resume() }
}
/// what the modem said (for the terminal): a remote's transfer started, a call ringing
@@ -81,7 +85,36 @@ final class AppModel: ObservableObject {
private func ring() {
if jobs.running { return }
calls.ringing(from: callerId)
if settings.faxAutoAnswer && jobs.answerFax() == nil { calls.answeredHere() }
if Date().timeIntervalSince(lastRing) > 8 { rings = 0 }
lastRing = Date()
rings += 1
if settings.faxAutoAnswer {
if jobs.answerFax() == nil { calls.answeredHere() }
} else if settings.voicemail && rings >= settings.voicemailRings {
// (the answering machine, when it's on and nobody has answered)
rings = 0
if takeMessage() == nil { calls.answeredHere() }
}
}
/// caller ID's number for the call ringing, or ""
private var callerNumber: String {
guard let n = callerId, n != "P", n != "O" else { return "" }
return n
}
/// the ringing call answered to talk (the Phone screen's button)
func answerVoice() -> String? {
let r = jobs.voiceAnswer(caller: callerNumber)
if r == nil { calls.answeredHere() }
return r
}
/// the ringing call answered by the answering machine
func takeMessage() -> String? {
let r = jobs.takeMessage(caller: callerNumber, maxSeconds: settings.voicemailMaxSeconds)
if r == nil { calls.answeredHere() }
return r
}
/// the ringing call answered as a fax (the Fax screen's button)
@@ -113,6 +146,7 @@ final class AppModel: ObservableObject {
if jobs.fax?.running == true { jobs.cancelFax() }
if jobs.internet?.running == true { jobs.disconnectInternet() }
if jobs.transfer?.running == true { jobs.cancelTransfer() }
if jobs.voice?.running == true { jobs.hangUpVoice() }
if status.offHook { hangUp() }
}
@@ -120,6 +154,7 @@ final class AppModel: ObservableObject {
private var dialling: String {
if jobs.fax?.running == true, jobs.fax?.sending == true { return jobs.fax?.number ?? "" }
if jobs.internet?.running == true { return settings.ispNumber }
if jobs.voice?.running == true, jobs.voice?.calling == true { return jobs.voice?.number ?? "" }
return lastDial
}
+4 -1
View File
@@ -3,7 +3,8 @@
import SwiftUI
/// D-Modem for iOS: the modem on a SIP account (or another phone), its
/// terminal and file transfers, faxes, dial-up internet.
/// terminal and file transfers, voice calls and the answering machine,
/// faxes, dial-up internet.
@main
struct DModemApp: App {
@StateObject private var model = AppModel()
@@ -15,6 +16,8 @@ struct DModemApp: App {
.tabItem { Label("Home", systemImage: "house") }
NavigationStack { TerminalTab(model: model, jobs: model.jobs) }
.tabItem { Label("Terminal", systemImage: "terminal") }
NavigationStack { PhoneView(model: model, jobs: model.jobs) }
.tabItem { Label("Phone", systemImage: "phone") }
NavigationStack { FaxView(model: model, jobs: model.jobs) }
.tabItem { Label("Fax", systemImage: "printer") }
NavigationStack { InternetView(model: model, jobs: model.jobs) }
+123 -1
View File
@@ -23,12 +23,23 @@ final class JobsModel: ObservableObject {
@Published private(set) var preparing = false
/// why the last fax couldn't start (its document unreadable)
@Published var faxError: String?
/// the voice call (going, or how the last one ended)
@Published private(set) var voice: VoiceJob.State?
/// a message being left heard on the loudspeaker; the microphone muted; the loudspeaker (else the earpiece)
@Published private(set) var listening = false
@Published private(set) var muted = false
@Published private(set) var loud = true
/// the voice call over: the modem's own sound back (the app's)
var voiceEnded: (() -> Void)?
private let session: ModemSession
private let settings: () -> ModemSettings
private var faxJob: FaxJob?
private var transferJob: TransferJob?
private var dialUp: DialUpJob?
private var voiceJob: VoiceJob?
private let sound = VoiceSound()
private var pump: VoicePump?
private var tunnel: UdpPacketTunnel?
private var sawOnline = false
@@ -38,7 +49,7 @@ final class JobsModel: ObservableObject {
self.settings = settings
}
var running: Bool { faxJob != nil || transferJob != nil || dialUp != nil || preparing }
var running: Bool { faxJob != nil || transferJob != nil || dialUp != nil || voiceJob != nil || preparing }
/// why a job can't start now (a call to make: not while the modem's in one), or nil
private func busy(call: Bool) -> String? {
@@ -130,6 +141,117 @@ final class JobsModel: ObservableObject {
}
}
// MARK: voice calls
/// a voice job lent the DTE, [begin] it: nil, or why not
private func startVoice(call: Bool, _ begin: (VoiceJob) -> Void) -> String? {
if let b = busy(call: call) { return b }
let l = link { $0.refreshVoice() }
let job = VoiceJob(out: l, log: l, changed: l)
guard lend({ job.feed(latin1: $0) }) else { return "the modem is in use" }
voiceJob = job
listening = false
muted = false
pump = VoicePump(job: job, sound: sound)
begin(job)
voice = job.state
return nil
}
/// [number] called, to talk: nil when it's started, else why it can't
func voiceDial(_ number: String) -> String? {
let n = number.trimmingCharacters(in: .whitespaces)
if n.isEmpty { return "no number" }
return startVoice(call: true) { $0.dial(number: n) }
}
/// the call ringing answered, to talk ([caller]: caller ID's number)
func voiceAnswer(caller: String) -> String? {
startVoice(call: false) { $0.answer(caller: caller) }
}
/// the call ringing answered by the answering machine: its greeting played, the message kept in Documents/Voicemail
func takeMessage(caller: String, maxSeconds: Int) -> String? {
let f = DateFormatter()
f.dateFormat = "yyyyMMdd-HHmmss"
f.locale = Locale(identifier: "en_US_POSIX")
let name = VoiceJob.companion.messageName(time: f.string(from: Date()), caller: caller)
let greeting = VoiceFiles.decode(VoiceFiles.greeting)
let dir = VoiceFiles.messages.path
return startVoice(call: false) {
$0.takeMessage(greeting: greeting, maxS: Int32(maxSeconds), silenceS: VoiceJob.companion.MESSAGE_SILENCE_S,
into: PosixFolderIncoming(dir: dir), fileName: name, caller: caller)
}
}
/// the answering machine's call taken, to talk
func pickUp() {
guard let j = voiceJob, j.pickUp() else { return }
listening = false
voiceSound()
}
/// the message being left heard (or not)
func listen(_ on: Bool) {
guard voiceJob?.state?.machine == true else { return }
listening = on
voiceSound()
}
/// the voice call hung up
func hangUpVoice() { voiceJob?.hangUp() }
/// DTMF digit [key] played to the far end
func dtmf(_ key: Character) { _ = voiceJob?.dtmf(d: key.utf16.first ?? 0) }
/// our microphone muted (the far end hears silence) or not
func mute(_ on: Bool) {
muted = on
voiceJob?.muted = on
}
/// the call's sound on the loudspeaker (else the earpiece)
func loudspeaker(_ on: Bool) {
loud = on
sound.loudspeaker(on)
}
/// the last voice call's outcome cleared (not while one's going)
func dismissVoice() { if voiceJob == nil { voice = nil } }
/// the sound as the call needs it: speaker and microphone when talking, the speaker alone when listening, none else
private func voiceSound() {
guard let j = voiceJob, let st = j.state, st.running else { return }
let talking = st.phase == VoiceJob.Phase.talking
let machine = st.machine && st.phase != VoiceJob.Phase.ending
if talking || (machine && listening) {
if !sound.running || talking { _ = sound.start(record: talking, loud: talking ? loud : true) }
pump?.start()
} else if sound.running {
pump?.stop()
sound.stop()
}
}
/// the voice job's state copied in, the sound started or stopped; once it's over, the DTE back
private func refreshVoice() {
guard let job = voiceJob else { return }
let before = voice?.phase
voice = job.state
if let st = job.state, st.phase != before { voiceSound() }
if job.state?.phase == VoiceJob.Phase.ending || job.state?.running == false {
pump?.stop()
sound.stop()
}
if job.state?.running == false {
voiceJob = nil
pump = nil
listening = false
session.release(leftover: Octets.data(job.leftover))
voiceEnded?()
}
}
// MARK: transfers
/// the protocols' names (ZMODEM …), and what each is called
+296
View File
@@ -0,0 +1,296 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import AVFoundation
import DModemKit
import DModemShared
import SwiftUI
import UniformTypeIdentifiers
/// Voice calls through the modem: a number called, the ringing call
/// answered (to talk, or by the answering machine), the call as it goes
/// (mute, the loudspeaker, the keypad; a message being left heard or
/// picked up); the answering machine, off until it's turned on, its
/// greeting and its messages (WAV files in Documents/Voicemail, on this
/// phone only).
struct PhoneView: View {
@ObservedObject var model: AppModel
@ObservedObject var jobs: JobsModel
@State private var number = ""
@State private var error: String?
@State private var messages: [URL] = []
@State private var keypad = false
@State private var choosing = false
@StateObject private var player = VoicePlayer()
@StateObject private var greeting = GreetingRecorder()
var body: some View {
Form {
if let v = jobs.voice { callSection(v) }
Section {
TextField("Number", text: $number).keyboardType(.phonePad)
Button("Call") { ask { error = jobs.voiceDial(number) } }
.disabled(number.isEmpty || jobs.running || model.run != .running)
} header: {
Text("Call")
} footer: {
Text("A voice call through the modem's line, on this phone's speaker and microphone.")
}
Section("Ringing call") {
Button("Answer to talk") { ask { error = model.answerVoice() } }
.disabled(jobs.running || model.run != .running)
Button("Take a message") { error = model.takeMessage() }
.disabled(jobs.running || model.run != .running)
}
if let e = error {
Section { Text(e).foregroundStyle(.red) }
}
Section {
Toggle("Answering machine", isOn: $model.settings.voicemail)
Stepper("After \(model.settings.voicemailRings) ring\(model.settings.voicemailRings == 1 ? "" : "s")",
value: $model.settings.voicemailRings, in: 1...10)
Picker("Longest message", selection: $model.settings.voicemailMaxSeconds) {
Text("1 minute").tag(60)
Text("2 minutes").tag(120)
Text("5 minutes").tag(300)
}
HStack {
Text(greeting.recording ? "Recording: speak now" : greeting.seconds > 0 ? "Greeting: \(greeting.seconds) s" : "Greeting: none, callers hear a beep")
Spacer()
}
HStack(spacing: 16) {
if greeting.recording {
Button("Stop") { greeting.stop() }
} else {
Button("Record") { ask { greeting.record() } }
Button("Play") { player.play(VoiceFiles.greeting) }.disabled(greeting.seconds == 0)
Button("File…") { choosing = true }
Button("None") { greeting.clear() }.disabled(greeting.seconds == 0)
}
}
.buttonStyle(.borderless)
} header: {
Text("Answering machine")
} footer: {
Text(model.settings.faxAutoAnswer
? "Fax answers every call first: the answering machine waits until that's off."
: "It answers the calls nobody does, plays the greeting and a beep, and keeps the message on this phone.")
}
Section("Messages") {
if messages.isEmpty { Text("None yet").foregroundStyle(.secondary) }
ForEach(messages, id: \.self) { u in messageRow(u) }
.onDelete { i in
for k in i { try? FileManager.default.removeItem(at: messages[k]) }
reload()
}
}
}
.navigationTitle("Phone")
.onAppear { reload(); greeting.reload() }
.onChange(of: jobs.voice?.running) { _ in reload() }
.fileImporter(isPresented: $choosing, allowedContentTypes: [UTType.wav]) { r in
if case .success(let u) = r { error = greeting.choose(u) }
}
}
/// the microphone allowed first (asked, if it hasn't been), then [then]
private func ask(_ then: @escaping () -> Void) {
AVAudioSession.sharedInstance().requestRecordPermission { ok in
DispatchQueue.main.async {
if ok { then() } else { error = "A call needs the microphone: allow it in Settings" }
}
}
}
/// the call now or just ended
@ViewBuilder
private func callSection(_ v: VoiceJob.State) -> some View {
Section {
let who = v.number.isEmpty ? (v.calling ? "the number" : "an unknown caller") : v.number
Text(v.machine ? "Answering machine: \(who)" : v.calling ? "Call to \(who)" : "Call from \(who)").font(.headline)
Text(phase(v)).foregroundStyle(.secondary)
if v.running {
HStack(spacing: 16) {
Button("Hang up", role: .destructive) { jobs.hangUpVoice() }
if v.machine {
Button(jobs.listening ? "Stop listening" : "Listen") { jobs.listen(!jobs.listening) }
Button("Pick up") { ask { jobs.pickUp() } }
} else if v.phase == VoiceJob.Phase.talking {
Button(jobs.muted ? "Unmute" : "Mute") { jobs.mute(!jobs.muted) }
Button(jobs.loud ? "Earpiece" : "Speaker") { jobs.loudspeaker(!jobs.loud) }
Button("Keypad") { keypad.toggle() }
}
}
.buttonStyle(.borderless)
if keypad && !v.machine && v.phase == VoiceJob.Phase.talking {
Grid(horizontalSpacing: 8, verticalSpacing: 8) {
ForEach(["123", "456", "789", "*0#"], id: \.self) { row in
GridRow {
ForEach(Array(row), id: \.self) { k in
Button(String(k)) { jobs.dtmf(k) }
.font(.title2)
.frame(maxWidth: .infinity, minHeight: 44)
.buttonStyle(.bordered)
}
}
}
}
}
} else {
Button("OK") { jobs.dismissVoice() }
}
}
}
/// what the call is doing, or how it ended
private func phase(_ v: VoiceJob.State) -> String {
if !v.running {
if !v.message.isEmpty { return "Took a message of \(v.messageSeconds) s" }
if v.result == "" { return v.machine ? "No message left" : "Call ended" }
return "Stopped: \(v.result ?? "")"
}
var s: String
switch v.phase {
case .starting: s = "Starting"
case .dialling: s = "Calling…"
case .answering: s = "Answering"
case .talking: s = jobs.muted ? "In a call (muted)" : "In a call"
case .greeting: s = "Playing the greeting"
case .recording: s = "Taking a message"
default: s = "Hanging up"
}
if !v.digits.isEmpty { s += " · keys \(v.digits)" }
return s
}
/// a message: from whom, when, how long; played with a tap, shared
private func messageRow(_ u: URL) -> some View {
let name = u.deletingPathExtension().lastPathComponent
let caller = VoiceJob.companion.messageCaller(name: u.lastPathComponent)
let f = DateFormatter()
f.dateFormat = "yyyyMMdd-HHmmss"
f.locale = Locale(identifier: "en_US_POSIX")
let when = f.date(from: String(name.prefix(15))).map { DateFormatter.localizedString(from: $0, dateStyle: .short, timeStyle: .short) } ?? ""
let secs = VoiceFiles.seconds(u)
return HStack {
Button {
player.play(u)
} label: {
Image(systemName: player.playing == u ? "stop.fill" : "play.fill")
}
.buttonStyle(.borderless)
VStack(alignment: .leading) {
Text(caller.isEmpty ? "Unknown caller" : caller)
Text("\(when) · \(secs / 60):\(String(format: "%02d", secs % 60))").font(.caption).foregroundStyle(.secondary)
}
Spacer()
ShareLink(item: u) { Image(systemName: "square.and.arrow.up") }.buttonStyle(.borderless)
}
}
/// the messages read from their folder, newest first
private func reload() {
messages = AppFolders.files(VoiceFiles.messages).filter { $0.pathExtension.lowercased() == "wav" }
}
}
/// A message or the greeting played (AVAudioPlayer reads the WAVs as they are)
@MainActor
final class VoicePlayer: NSObject, ObservableObject, AVAudioPlayerDelegate {
@Published private(set) var playing: URL?
private var player: AVAudioPlayer?
/// [u] played; again, it stops
func play(_ u: URL) {
if playing == u {
stop()
return
}
stop()
try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers])
guard let p = try? AVAudioPlayer(contentsOf: u) else { return }
p.delegate = self
p.play()
player = p
playing = u
}
/// what's playing stopped
func stop() {
player?.stop()
player = nil
playing = nil
}
/// its end: nothing playing
nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
Task { @MainActor in self.stop() }
}
}
/// The answering machine's greeting: recorded from the microphone (a minute at most), chosen from a WAV file, or none
@MainActor
final class GreetingRecorder: ObservableObject {
@Published private(set) var recording = false
@Published private(set) var seconds = 0
private let sound = VoiceSound()
private var samples: [Float] = []
private var timer: Timer?
/// the greeting's length read (0: none)
func reload() {
seconds = FileManager.default.fileExists(atPath: VoiceFiles.greeting.path) ? max(1, VoiceFiles.seconds(VoiceFiles.greeting)) : 0
}
/// the microphone recorded (until stop, or a minute)
func record() {
guard !recording, sound.start(record: true, loud: true) else { return }
samples = []
recording = true
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in
Task { @MainActor [weak self] in self?.take() }
}
}
/// what the microphone gave since, kept; a minute, and it stops
private func take() {
var b = [Float](repeating: 0, count: 8000)
let n = b.withUnsafeMutableBufferPointer { sound.mic.pop(into: $0.baseAddress!, 8000) }
samples.append(contentsOf: b[0..<n])
if samples.count >= 60 * 8000 { stop() }
}
/// the recording ended, kept as the greeting if half a second or more
func stop() {
guard recording else { return }
take()
timer?.invalidate()
timer = nil
sound.stop()
recording = false
if samples.count >= 4000 { try? VoiceFiles.write(samples, to: VoiceFiles.greeting) }
samples = []
reload()
}
/// the greeting from the WAV at [u]: nil, or why not
func choose(_ u: URL) -> String? {
let scoped = u.startAccessingSecurityScopedResource()
defer { if scoped { u.stopAccessingSecurityScopedResource() } }
guard let pcm = VoiceFiles.decode(u) else { return "That file isn't a WAV of PCM, A-law or μ-law" }
if pcm.size == 0 { return "That file has no sound" }
let n = min(pcm.size, 60 * 8000)
do {
try VoiceFiles.data(Wav.shared.encode(pcm: pcm, n: n)).write(to: VoiceFiles.greeting)
} catch {
return "The greeting couldn't be saved"
}
reload()
return nil
}
/// no greeting: callers hear the beep alone
func clear() {
try? FileManager.default.removeItem(at: VoiceFiles.greeting)
reload()
}
}
+245
View File
@@ -0,0 +1,245 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import AVFoundation
import DModemShared
import Foundation
/// Samples (as floats) from one thread to another: the oldest dropped
/// when it's full.
final class SampleQueue: @unchecked Sendable {
private var buf: [Float]
private var head = 0
private var count = 0
private let lock = NSLock()
/// room for [capacity] samples
init(capacity: Int) { buf = [Float](repeating: 0, count: capacity) }
/// [x] put in
func push(_ x: UnsafeBufferPointer<Float>) {
lock.lock(); defer { lock.unlock() }
for v in x {
if count == buf.count {
head = (head + 1) % buf.count
count -= 1
}
buf[(head + count) % buf.count] = v
count += 1
}
}
/// up to [n] into [p]: how many
func pop(into p: UnsafeMutablePointer<Float>, _ n: Int) -> Int {
lock.lock(); defer { lock.unlock() }
let k = min(n, count)
for i in 0..<k {
p[i] = buf[head]
head = (head + 1) % buf.count
}
count -= k
return k
}
var available: Int {
lock.lock(); defer { lock.unlock() }
return count
}
/// emptied
func clear() {
lock.lock(); defer { lock.unlock() }
head = 0
count = 0
}
}
/// The phone's speaker and microphone at a voice call's 8000 Hz: the
/// speaker played from [speaker], the microphone (converted) into [mic].
/// The audio session in its voice chat mode (the phone's echo
/// cancelling) while it runs, back to the modem's playback after.
final class VoiceSound: @unchecked Sendable {
let speaker = SampleQueue(capacity: 8000)
let mic = SampleQueue(capacity: 8000)
private var engine: AVAudioEngine?
private var tapped = false
private let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false)!
var running: Bool { engine != nil }
/// the speaker on, and the microphone if [record]; [loud]: the loudspeaker (else the earpiece). False if there's no sound
func start(record: Bool, loud: Bool) -> Bool {
stop()
let s = AVAudioSession.sharedInstance()
do {
try s.setCategory(.playAndRecord, mode: .voiceChat, options: loud ? [.defaultToSpeaker, .allowBluetooth] : [.allowBluetooth])
try s.setActive(true)
} catch {
NSLog("voice sound: \(error)")
}
let e = AVAudioEngine()
let fmt = format
let q = speaker
let src = AVAudioSourceNode(format: fmt) { _, _, frames, abl -> OSStatus in
let list = UnsafeMutableAudioBufferListPointer(abl)
guard let p = list[0].mData?.assumingMemoryBound(to: Float.self) else { return noErr }
let n = Int(frames)
var i = q.pop(into: p, n)
while i < n { p[i] = 0; i += 1 }
return noErr
}
e.attach(src)
e.connect(src, to: e.mainMixerNode, format: fmt)
if record {
let input = e.inputNode
let hw = input.outputFormat(forBus: 0)
if hw.sampleRate > 0, hw.channelCount > 0, let conv = AVAudioConverter(from: hw, to: fmt) {
let m = mic
input.installTap(onBus: 0, bufferSize: 1024, format: hw) { buffer, _ in
let cap = AVAudioFrameCount(Double(buffer.frameLength) * fmt.sampleRate / hw.sampleRate) + 32
guard let out = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: cap) else { return }
var given = false
var err: NSError?
_ = conv.convert(to: out, error: &err) { _, status in
if given { status.pointee = .noDataNow; return nil }
given = true
status.pointee = .haveData
return buffer
}
if let d = out.floatChannelData?[0], out.frameLength > 0 {
m.push(UnsafeBufferPointer(start: d, count: Int(out.frameLength)))
}
}
tapped = true
}
}
do {
e.prepare()
try e.start()
} catch {
if tapped { e.inputNode.removeTap(onBus: 0) }
tapped = false
NSLog("voice sound: \(error)")
return false
}
engine = e
return true
}
/// the loudspeaker (or the earpiece) for the call's sound
func loudspeaker(_ on: Bool) {
try? AVAudioSession.sharedInstance().overrideOutputAudioPort(on ? .speaker : .none)
}
/// stopped; the session back to the modem's playback
func stop() {
guard let e = engine else { return }
if tapped { e.inputNode.removeTap(onBus: 0) }
e.stop()
tapped = false
engine = nil
speaker.clear()
mic.clear()
try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers])
}
}
/// A voice call's sound moved between its job and the phone every 20 ms
/// (the job's Kotlin kept off the audio threads): the far end's samples
/// to the speaker, the microphone's to the line.
final class VoicePump: @unchecked Sendable {
private let job: VoiceJob
private let sound: VoiceSound
private var timer: DispatchSourceTimer?
private let pcm = KotlinShortArray(size: 1600)
private var floats = [Float](repeating: 0, count: 1600)
private let queue = DispatchQueue(label: "voice-pump")
/// [job]'s sound to and from [sound]
init(job: VoiceJob, sound: VoiceSound) {
self.job = job
self.sound = sound
}
/// the pump started, every 20 ms
func start() {
guard timer == nil else { return }
let t = DispatchSource.makeTimerSource(queue: queue)
t.schedule(deadline: .now(), repeating: .milliseconds(20))
t.setEventHandler { [weak self] in self?.pump() }
t.resume()
timer = t
}
/// the pump stopped
func stop() {
timer?.cancel()
timer = nil
}
/// the far end's samples to the speaker's queue, the microphone's to the job
private func pump() {
// the far end's (no more than a quarter second behind)
if sound.speaker.available > 2000 { sound.speaker.clear() }
let n = Int(job.read(pcm: pcm, off: 0, len: 1600))
if n > 0 {
for i in 0..<n { floats[i] = Float(pcm.get(index: Int32(i))) / 32768 }
floats.withUnsafeBufferPointer { sound.speaker.push(UnsafeBufferPointer(rebasing: $0[0..<n])) }
}
// the microphone's
let m = floats.withUnsafeMutableBufferPointer { sound.mic.pop(into: $0.baseAddress!, 1600) }
if m > 0 {
for i in 0..<m { pcm.set(index: Int32(i), value: Int16(max(-32768, min(32767, floats[i] * 32767)))) }
job.write(pcm: pcm, off: 0, len: Int32(m))
}
}
}
/// WAV files and Kotlin's arrays from Swift
enum VoiceFiles {
/// [d]'s octets as Kotlin's
static func bytes(_ d: Data) -> KotlinByteArray {
let b = KotlinByteArray(size: Int32(d.count))
for (i, x) in d.enumerated() { b.set(index: Int32(i), value: Int8(bitPattern: x)) }
return b
}
/// Kotlin's octets as Data
static func data(_ b: KotlinByteArray) -> Data {
var d = Data(count: Int(b.size))
for i in 0..<Int(b.size) { d[i] = UInt8(bitPattern: b.get(index: Int32(i))) }
return d
}
/// a WAV file's samples at 8000 Hz (nil: not one this reads)
static func decode(_ url: URL) -> KotlinShortArray? {
guard let d = try? Data(contentsOf: url) else { return nil }
return Wav.shared.decode(data: bytes(d))
}
/// [samples] (floats at 8000 Hz) written to [url] as a WAV
static func write(_ samples: [Float], to url: URL) throws {
let pcm = KotlinShortArray(size: Int32(samples.count))
for (i, x) in samples.enumerated() { pcm.set(index: Int32(i), value: Int16(max(-32768, min(32767, x * 32767)))) }
try data(Wav.shared.encode(pcm: pcm, n: Int32(samples.count))).write(to: url)
}
/// the folder of the answering machine's messages: Documents/Voicemail (the Files app shows it)
static var messages: URL {
let u = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("Voicemail", isDirectory: true)
try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)
return u
}
/// the greeting's file (Application Support)
static var greeting: URL {
let u = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)
return u.appendingPathComponent("voicemail-greeting.wav")
}
/// a WAV's length (s), from its size
static func seconds(_ url: URL) -> Int {
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
return Int(Wav.shared.seconds(fileSize: Int64(size)))
}
}
+2
View File
@@ -37,6 +37,8 @@ targets:
UIBackgroundModes: [audio]
NSLocalNetworkUsageDescription: "D-Modem calls another phone with the app on this network, and SIP servers on it."
NSBonjourServices: [_dmodem._tcp]
# voice calls through the modem, a greeting recorded for the answering machine
NSMicrophoneUsageDescription: "D-Modem uses the microphone for voice calls through the modem, and to record the answering machine's greeting."
# received files and faxes in the Files app (On My iPhone › D-Modem)
UIFileSharingEnabled: true
LSSupportsOpeningDocumentsInPlace: true
@@ -45,6 +45,12 @@ public struct ModemSettings: Codable, Equatable, Sendable {
public var faxFine = true
public var faxAutoAnswer = false
/// voice calls: the answering machine takes calls nobody answers (off until turned on), after this many
/// rings, a message this long at most (s)
public var voicemail = false
public var voicemailRings = 4
public var voicemailMaxSeconds = 120
/// dial-up internet: the ISP's number, login, its login script (chat, if any), the modem's commands first
public var ispNumber = ""
public var ispUser = ""
@@ -128,6 +134,9 @@ public struct ModemSettings: Codable, Equatable, Sendable {
faxMaxBps = try c.decodeIfPresent(Int.self, forKey: .faxMaxBps) ?? d.faxMaxBps
faxFine = try c.decodeIfPresent(Bool.self, forKey: .faxFine) ?? d.faxFine
faxAutoAnswer = try c.decodeIfPresent(Bool.self, forKey: .faxAutoAnswer) ?? d.faxAutoAnswer
voicemail = try c.decodeIfPresent(Bool.self, forKey: .voicemail) ?? d.voicemail
voicemailRings = try c.decodeIfPresent(Int.self, forKey: .voicemailRings) ?? d.voicemailRings
voicemailMaxSeconds = try c.decodeIfPresent(Int.self, forKey: .voicemailMaxSeconds) ?? d.voicemailMaxSeconds
ispNumber = try c.decodeIfPresent(String.self, forKey: .ispNumber) ?? d.ispNumber
ispUser = try c.decodeIfPresent(String.self, forKey: .ispUser) ?? d.ispUser
ispPassword = try c.decodeIfPresent(String.self, forKey: .ispPassword) ?? d.ispPassword
+1
View File
@@ -15,6 +15,7 @@ nav:
- The app, screen by screen: features.md
- The modem's line: lines.md
- Fax: fax.md
- Voice calls and the answering machine: voice.md
- Serial adapters and phone lines: adapters.md
- Settings reference: settings.md
- Building for Android: building.md
@@ -0,0 +1,457 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.jobs
import org.dmodem.app.io.IOException
import org.dmodem.app.io.background
import org.dmodem.app.io.monotonicMs
import org.dmodem.app.io.sleepMs
import org.dmodem.app.transfer.Incoming
import org.dmodem.app.transfer.TransferCancelled
import org.dmodem.app.voice.G711
import org.dmodem.app.voice.SampleRing
import org.dmodem.app.voice.Tone
import org.dmodem.app.voice.VOICE_RATE
import org.dmodem.app.voice.Wav
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
import kotlin.concurrent.Volatile
/**
* A voice call on the modem (V.253 voice mode), for the Android app and
* the iOS app alike: a number dialled, or the call ringing answered, by a
* person or by the answering machine; the far end's samples to the
* phone's speaker ([read]), its microphone's to the line ([write]).
*
* The modem to voice mode with μ-law (AT+FCLASS=8, AT+VSM=4), then ATD
* or AT+VLS=1, then AT+VTR: a full-duplex stream of octets, a <DLE>
* doubled, <DLE> and a letter for what the modem heard (l the far end
* hung up, b busy, d dial tone, digits). Our samples go at the line's
* pace, by the clock, a little ahead; silence when the microphone has
* none. <DLE>^ ends the stream (the modem: <DLE><ETX>, OK), then ATH and
* back to data mode.
*
* The answering machine plays the greeting, a beep, and records the
* caller until they hang up, are quiet for [silenceS] or [maxS] has gone;
* the message is saved as a WAV file (one under a second isn't).
*/
class VoiceJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, changed) {
enum class Phase {
/** the modem to voice mode */
STARTING,
/** the number dialled, waiting for an answer */
DIALLING,
/** the ringing call being answered */
ANSWERING,
/** a call between people */
TALKING,
/** the answering machine's greeting (and beep) to the caller */
GREETING,
/** the answering machine taking the caller's message */
RECORDING,
/** hanging up */
ENDING,
}
data class State(
/** we dialled (else the call rang here) */
val calling: Boolean,
/** the number dialled, or the caller's (as caller ID had it) */
val number: String,
val phase: Phase,
/** the answering machine has the call (else a person) */
val machine: Boolean,
/** null while it goes; "" when it ended well, else why it ended */
val result: String? = null,
/** the message's file name (the answering machine took one) */
val message: String = "",
/** its length (s) */
val messageSeconds: Int = 0,
/** when the call began talking (monotonicMs), 0 not yet */
val since: Long = 0,
/** the digits the far end pressed */
val digits: String = "",
) {
val running: Boolean get() = result == null
}
@Volatile var state: State? = null
private set
/** our microphone's samples not sent to the line (the far end hears silence) */
@Volatile var muted = false
private val rx = SampleRing(VOICE_RATE)
private val tx = SampleRing(VOICE_RATE)
private val lock = SynchronizedObject()
private val keys = StringBuilder()
@Volatile private var hang = false
// the answering machine's (the call's thread's alone)
private var greeting = ShortArray(0)
private var gpos = 0
private var beep: Tone? = null
private var rec = ShortArray(0)
private var recN = 0
private var quiet = 0
private var maxS = MESSAGE_MAX_S
private var silenceS = MESSAGE_SILENCE_S
private var into: Incoming? = null
private var fileName = ""
@Volatile private var machineDone = false
private var tone: Tone? = null
private var toneGap = 0
/** the state changed by [change], and said so */
private fun update(change: (State) -> State) {
state = state?.let(change)
changed()
}
/** [number] dialled for a call between people */
fun dial(number: String) {
val n = number.filter { it != '\r' && it != '\n' && it != ';' }.trim()
start(State(true, n, Phase.STARTING, machine = false)) {
update { it.copy(phase = Phase.DIALLING) }
val r = command("D$n", CALL_MS)
if (r != "OK") throw IOException(dialResult(r, "no answer"))
}
}
/** the call ringing answered by a person; [caller] its number, if known */
fun answer(caller: String = "") {
start(State(false, caller, Phase.STARTING, machine = false)) { answerCall() }
}
/**
* the call ringing answered by the answering machine: [greeting] (8000 Hz; none: the beep alone)
* played, the message saved to [into] as [fileName], a WAV
*/
fun takeMessage(
greeting: ShortArray?,
maxS: Int,
silenceS: Int,
into: Incoming,
fileName: String,
caller: String = "",
) {
this.greeting = greeting ?: ShortArray(0)
this.maxS = if (maxS > 0) maxS else MESSAGE_MAX_S
this.silenceS = if (silenceS > 0) silenceS else MESSAGE_SILENCE_S
this.into = into
this.fileName = fileName
start(State(false, caller, Phase.STARTING, machine = true)) { answerCall() }
}
/** the answering machine's call taken by a person (a message being left isn't kept): false if it can't be */
fun pickUp(): Boolean {
val s = state ?: return false
if (!s.running || !s.machine || machineDone) return false
machineDone = true
update { it.copy(machine = false, phase = if (it.phase == Phase.GREETING || it.phase == Phase.RECORDING) Phase.TALKING else it.phase) }
return true
}
/** the call hung up */
fun hangUp() {
hang = true
}
/** the call stopped at once (the modem's gone): no goodbyes */
fun cancel() = io.cancel("cancelled")
/** DTMF digit [d] played to the far end: false if it isn't one */
fun dtmf(d: Char): Boolean {
if (Tone.dtmf(d) == null || state?.running != true) return false
synchronized(lock) { if (keys.length < 32) keys.append(d) }
return true
}
/** up to [len] of the far end's samples into [pcm] at [off]: how many (none waiting: 0) */
fun read(pcm: ShortArray, off: Int = 0, len: Int = pcm.size - off): Int = rx.get(pcm, off, len)
/** how many of the far end's samples are waiting */
val readable: Int get() = rx.size
/** the far end's samples waiting cut to the newest [n] (the speaker fell behind) */
fun keepReadable(n: Int) = rx.keep(n)
/** [len] of the microphone's samples from [pcm] at [off], to the line */
fun write(pcm: ShortArray, off: Int = 0, len: Int = pcm.size - off) {
if (state?.phase != Phase.TALKING) return
tx.put(pcm, off, len)
// (the line takes them at its pace: a microphone ahead of it is cut back)
if (tx.size > TX_MAX) tx.keep(TX_KEEP)
}
// ------------------------------------------------------------------
/** AT+VLS=1: the ringing call answered */
private fun answerCall() {
update { it.copy(phase = Phase.ANSWERING) }
val r = command("+VLS=1", 30_000)
if (r != "OK") throw IOException(if (r == null) "the call didn't answer" else "the call didn't answer: ${r.lowercase()}")
}
/** AT[cmd]'s final result, or null if none came within [ms] (lines before it passed over) */
private fun command(cmd: String, ms: Long = 5_000): String? {
io.write(("AT$cmd\r").encodeToByteArray())
val end = monotonicMs() + ms
val line = StringBuilder()
while (true) {
if (hang) return "hung up"
val left = end - monotonicMs()
if (left <= 0) return null
val c = io.read(minOf(left, 200))
if (c < 0) continue
if (c == '\r'.code || c == '\n'.code) {
val l = line.toString().trim()
line.clear()
if (l in RESULTS) return l
} else if (line.length < 256) {
line.append(c.toChar())
}
}
}
/** the call in the background: voice mode, [connect] (the call made or answered), the stream until it ends, back to data */
private fun start(first: State, connect: () -> Unit) {
hang = false
machineDone = !first.machine
state = first
changed()
background("voice") {
var result = ""
var streaming = false
try {
if (command("E0V1") != "OK" || command("+FCLASS=8") != "OK" || command("+VSM=4") != "OK") {
throw IOException("the modem has no voice mode")
}
connect()
if (hang) throw TransferCancelled("")
if (command("+VTR", 10_000) != "CONNECT") throw IOException("the call's sound didn't start")
streaming = true
update { it.copy(phase = if (it.machine) Phase.GREETING else Phase.TALKING, since = monotonicMs()) }
stream()
streaming = false
} catch (e: TransferCancelled) {
result = ""
} catch (e: IOException) {
// (hung up from here while it was being set up: no fault)
result = if (hang) "" else e.message ?: e.toString()
} catch (e: RuntimeException) {
result = e.toString()
} finally {
if (!machineDone) saveMessage(0)
update { it.copy(phase = Phase.ENDING) }
// the call over, the modem on hook and back to data
if (streaming) {
raw("\u0010^")
sleepMs(300)
}
raw("ATH\r")
sleepMs(500)
raw("AT+FCLASS=0\r")
sleepMs(300)
io.purge()
leftover = Latin1.string(io.leftover())
update { it.copy(result = result) }
}
}
}
/** the stream, until either end hangs up: the far end's samples and codes read, ours sent by the clock */
private fun stream() {
rx.clear()
tx.clear()
val t0 = monotonicMs()
var sent = 0L
var dle = false
var packet = false
var ending = false
var endAt = 0L
val out = ByteArray(VOICE_RATE * 2)
while (true) {
val now = monotonicMs()
if (!ending && hang) {
ending = true
endAt = now + END_MS
if (!machineDone) saveMessage(0)
raw("\u0010^")
}
if (ending && now > endAt) return
if (!ending) {
// our samples: as many as the time says, a little ahead (a second behind: we stalled, the line went on)
val due = (now - t0) * VOICE_RATE / 1000 + LEAD
if (due - sent > VOICE_RATE) sent = due - LEAD
var k = 0
while (sent < due && k < out.size - 1) {
val u = G711.ulaw(nextSample())
out[k++] = u.toByte()
if (u == DLE) out[k++] = DLE.toByte()
sent++
}
if (k > 0) io.write(out.copyOf(k))
}
// the modem's octets, for up to 10 ms
val until = monotonicMs() + 10
while (true) {
val c = io.read(maxOf(1, until - monotonicMs()))
if (c < 0) break
if (dle) {
dle = false
when (c) {
DLE -> if (!packet) sample(c)
ETX -> return
'X'.code -> packet = true
'.'.code -> packet = false
else -> if (event(c)) {
ending = true
endAt = monotonicMs() + END_MS
raw("\u0010^")
}
}
} else if (c == DLE) {
dle = true
} else if (!packet) {
sample(c)
}
if (monotonicMs() >= until) break
}
}
}
/** a sample of the far end's: to the speaker, and the message being recorded */
private fun sample(u: Int) {
val x = G711.unulaw(u)
rx.put(x)
if (!machineDone && state?.phase == Phase.RECORDING) record(x)
}
/** a <DLE> code from the modem: true when the far end has gone (hung up, or the exchange's busy or dial tone) */
private fun event(c: Int): Boolean {
val ch = c.toChar()
if (ch in '0'..'9' || ch == '*' || ch == '#' || ch in 'A'..'D') {
update { it.copy(digits = (it.digits + ch).takeLast(32)) }
return false
}
if (ch != 'l' && ch != 'b' && ch != 'd') return false
log("voice: the far end has gone (<DLE>$ch)")
if (!machineDone) saveMessage(if (ch == 'l') 0 else TONE_TRIM)
return true
}
/** a sample of the caller's message: it's over when long enough, or the caller has been quiet long enough */
private fun record(x: Int) {
val max = maxS * VOICE_RATE
if (recN == rec.size) rec = rec.copyOf(minOf(maxOf(rec.size * 2, VOICE_RATE * 8), max))
rec[recN++] = x.toShort()
quiet = if (x > -QUIET_LEVEL && x < QUIET_LEVEL) quiet + 1 else 0
if (recN >= max || quiet >= silenceS * VOICE_RATE) {
saveMessage(0)
hang = true
}
}
/** the message over: [trim] samples of its end cut (a busy tone's), its quiet end but for half a second; saved if a second or more */
private fun saveMessage(trim: Int) {
if (machineDone) return
machineDone = true
var n = recN - trim
if (state?.phase == Phase.RECORDING && quiet > QUIET_KEEP) n = minOf(n, recN - (quiet - QUIET_KEEP))
val dir = into
if (state?.phase != Phase.RECORDING || n < MESSAGE_MIN || dir == null) {
log("voice: no message left")
return
}
try {
val (out, actual) = dir.create(fileName, 44L + n * 2)
try {
out.use { Wav.write(it, rec, n) }
dir.done(actual, 0)
} catch (e: IOException) {
dir.abandon(actual)
throw e
}
log("voice: a message of ${n / VOICE_RATE} s saved as $actual")
update { it.copy(message = actual, messageSeconds = n / VOICE_RATE) }
} catch (e: IOException) {
log("voice: the message couldn't be saved: ${e.message}")
}
}
/** our next sample: the answering machine's greeting and beep, or the microphone's; DTMF over it */
private fun nextSample(): Int {
var x = 0
val s = state
if (s != null && s.machine && !machineDone) {
if (s.phase == Phase.GREETING) {
if (gpos < greeting.size) {
x = greeting[gpos++].toInt()
} else {
val b = beep ?: Tone(BEEP_HZ, 0.0, BEEP_LEN, BEEP_AMP).also { beep = it }
if (b.left > 0) {
x = b.next()
} else {
recN = 0
quiet = 0
update { it.copy(phase = Phase.RECORDING) }
}
}
}
} else if (s?.phase == Phase.TALKING) {
val m = tx.take()
if (m != null && !muted) x = m
}
val t = tone
if (t != null && t.left > 0) {
x += t.next()
} else if (toneGap > 0) {
toneGap--
} else {
val d = synchronized(lock) { if (keys.isEmpty()) null else keys[0].also { keys.deleteAt(0) } }
if (d != null) {
Tone.dtmf(d)?.let { (lo, hi) -> tone = Tone(lo, hi, DTMF_ON, DTMF_AMP) }
toneGap = DTMF_OFF
}
}
return x.coerceIn(-32768, 32767)
}
companion object {
private const val DLE = 0x10
private const val ETX = 0x03
private const val CALL_MS = 120_000L
/** our samples sent this far ahead of the clock */
private const val LEAD = VOICE_RATE * 60 / 1000
private const val TX_MAX = VOICE_RATE / 3
private const val TX_KEEP = VOICE_RATE / 10
/** the stream's end awaited this long after <DLE>^ */
private const val END_MS = 3_000L
private const val DTMF_ON = VOICE_RATE / 10
private const val DTMF_OFF = VOICE_RATE * 6 / 100
private const val DTMF_AMP = 16000.0
private const val BEEP_HZ = 1000.0
private const val BEEP_LEN = VOICE_RATE / 2
private const val BEEP_AMP = 8000.0
/** quieter than this, a sample is silence */
private const val QUIET_LEVEL = 400
const val MESSAGE_MAX_S = 120
const val MESSAGE_SILENCE_S = 7
private const val MESSAGE_MIN = VOICE_RATE
/** a busy or dial tone's start, cut from the message's end */
private const val TONE_TRIM = 2 * VOICE_RATE
/** of the message's quiet end, this much kept */
private const val QUIET_KEEP = VOICE_RATE / 2
private val RESULTS = setOf("OK", "ERROR", "CONNECT", "BUSY", "NO ANSWER", "NO CARRIER", "NO DIALTONE", "NO DIAL TONE")
/** a message's file name: its time (yyyyMMdd-HHmmss, given) and the caller's number, if known */
fun messageName(time: String, caller: String): String {
val n = caller.filter { it.isDigit() || it == '+' }
return if (n.isEmpty()) "$time.wav" else "${time}_$n.wav"
}
/** a message's caller's number from its file name ("" if none) */
fun messageCaller(name: String): String = name.removeSuffix(".wav").substringAfter('_', "")
}
}
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.voice
/** G.711: μ-law, the samples on the DTE in a voice call (AT+VSM=4), and A-law, for WAV files. */
object G711 {
/** [x] as a μ-law octet */
fun ulaw(x: Int): Int {
var v = x
var sign = 0
if (v < 0) {
v = -v
sign = 0x80
}
v += 0x84
if (v > 0x7fff) v = 0x7fff
var exp = 7
while (exp > 0 && v and (0x4000 shr (7 - exp)) == 0) exp--
val mant = (v shr (exp + 3)) and 0x0f
return (sign or (exp shl 4) or mant).inv() and 0xff
}
/** μ-law octet [u] as a sample */
fun unulaw(u: Int): Int {
val b = u.inv() and 0xff
val exp = (b shr 4) and 7
val mant = b and 0x0f
val v = (((mant shl 3) + 0x84) shl exp) - 0x84
return if (b and 0x80 != 0) -v else v
}
/** A-law octet [a] as a sample */
fun unalaw(a: Int): Int {
val b = (a and 0xff) xor 0x55
val exp = (b shr 4) and 7
val mant = b and 0x0f
val v = if (exp != 0) ((mant shl 4) + 0x108) shl (exp - 1) else (mant shl 4) + 8
return if (b and 0x80 != 0) v else -v
}
}
@@ -0,0 +1,127 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.voice
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
/** a voice call's samples: 16 bit, 8000 a second, one channel */
const val VOICE_RATE = 8000
/** A ring of samples that keeps the newest [cap] of them, for two threads (the call's, the sound card's). */
class SampleRing(private val cap: Int) {
private val lock = SynchronizedObject()
private val p = ShortArray(cap)
private var head = 0
private var n = 0
/** how many are in it */
val size: Int get() = synchronized(lock) { n }
/** emptied */
fun clear() = synchronized(lock) { head = 0; n = 0 }
/** [len] of [x] from [off] put in: the oldest dropped when it's full */
fun put(x: ShortArray, off: Int = 0, len: Int = x.size - off) = synchronized(lock) {
for (i in 0 until len) {
p[(head + n) % cap] = x[off + i]
if (n < cap) n++ else head = (head + 1) % cap
}
}
/** the one sample [x] put in */
fun put(x: Int) = synchronized(lock) {
p[(head + n) % cap] = x.toShort()
if (n < cap) n++ else head = (head + 1) % cap
}
/** up to [len] taken out into [out] at [off]: how many */
fun get(out: ShortArray, off: Int = 0, len: Int = out.size - off): Int = synchronized(lock) {
val k = minOf(n, len)
for (i in 0 until k) {
out[off + i] = p[head]
head = (head + 1) % cap
}
n -= k
k
}
/** the next sample, or null when it's empty */
fun take(): Int? = synchronized(lock) {
if (n == 0) return@synchronized null
val x = p[head].toInt()
head = (head + 1) % cap
n--
x
}
/** the oldest taken out until [keep] are left */
fun keep(keep: Int) = synchronized(lock) {
if (n > keep) {
head = (head + n - keep) % cap
n = keep
}
}
}
/** A tone of one or two frequencies (a DTMF digit, the answering machine's beep), [samples] long. */
class Tone(f1: Double, f2: Double, samples: Int, private val amp: Double) {
private val k1 = 2 * PI * f1 / VOICE_RATE
private val k2 = 2 * PI * f2 / VOICE_RATE
private val two = f2 > 0
private var c1 = 1.0
private var s1 = 0.0
private var c2 = 1.0
private var s2 = 0.0
/** samples still to come */
var left = samples
private set
/** its next sample (0 once it has ended) */
fun next(): Int {
if (left <= 0) return 0
left--
var y = turn1()
if (two) y = (y + turn2()) / 2
return (y * amp).toInt()
}
// (each oscillator a unit vector turned by its step each sample, kept on the circle)
private fun turn1(): Double {
val c0 = c1
val s0 = s1
c1 = c0 * cos(k1) - s0 * sin(k1)
s1 = c0 * sin(k1) + s0 * cos(k1)
val m = sqrt(c1 * c1 + s1 * s1)
if (m > 0) { c1 /= m; s1 /= m }
return s0
}
/** the second oscillator turned a step: its last sine */
private fun turn2(): Double {
val c0 = c2
val s0 = s2
c2 = c0 * cos(k2) - s0 * sin(k2)
s2 = c0 * sin(k2) + s0 * cos(k2)
val m = sqrt(c2 * c2 + s2 * s2)
if (m > 0) { c2 /= m; s2 /= m }
return s0
}
companion object {
private const val KEYS = "123A456B789C*0#D"
private val ROW = doubleArrayOf(697.0, 770.0, 852.0, 941.0)
private val COL = doubleArrayOf(1209.0, 1336.0, 1477.0, 1633.0)
/** DTMF digit [d]'s two frequencies, or null if it isn't one */
fun dtmf(d: Char): Pair<Double, Double>? {
val k = KEYS.indexOf(d.uppercaseChar())
return if (k < 0) null else ROW[k / 4] to COL[k % 4]
}
}
}
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.voice
import org.dmodem.app.io.Sink
/**
* WAV files: a voice call's samples written (16 bit PCM, 8000 Hz, mono:
* the answering machine's messages, a recorded greeting), and any PCM,
* A-law or μ-law WAV read as those (a greeting chosen from a file: mixed
* to one channel, resampled to 8000 Hz).
*/
object Wav {
/** the 44-octet header of a WAV of [n] samples */
fun header(n: Int): ByteArray {
val bytes = maxOf(n, 0) * 2
val h = ByteArray(44)
/** [s]'s characters at [at] */
fun tag(at: Int, s: String) = s.forEachIndexed { i, c -> h[at + i] = c.code.toByte() }
/** [v] at [at], little-endian, 16 bits */
fun put16(at: Int, v: Int) { h[at] = v.toByte(); h[at + 1] = (v shr 8).toByte() }
/** [v] at [at], little-endian, 32 bits */
fun put32(at: Int, v: Int) { put16(at, v and 0xffff); put16(at + 2, (v ushr 16) and 0xffff) }
tag(0, "RIFF")
put32(4, 36 + bytes)
tag(8, "WAVEfmt ")
put32(16, 16)
put16(20, 1)
put16(22, 1)
put32(24, VOICE_RATE)
put32(28, VOICE_RATE * 2)
put16(32, 2)
put16(34, 16)
tag(36, "data")
put32(40, bytes)
return h
}
/** [n] of [pcm] as a WAV file's octets */
fun encode(pcm: ShortArray, n: Int = pcm.size): ByteArray {
val out = header(n).copyOf(44 + n * 2)
for (i in 0 until n) {
val v = pcm[i].toInt()
out[44 + 2 * i] = v.toByte()
out[45 + 2 * i] = (v shr 8).toByte()
}
return out
}
/** [n] of [pcm] written to [out] as a WAV file */
fun write(out: Sink, pcm: ShortArray, n: Int = pcm.size) {
val b = encode(pcm, n)
out.write(b, 0, b.size)
out.flush()
}
/** a WAV file's length in seconds, from its size (one written here) */
fun seconds(fileSize: Long): Int = (maxOf(fileSize - 44, 0) / (VOICE_RATE * 2)).toInt()
/** a WAV file's samples at 8000 Hz, one channel; null if it isn't a WAV this reads */
fun decode(data: ByteArray): ShortArray? {
/** the 16 bits at [at], little-endian */
fun u16(at: Int) = (data[at].toInt() and 0xff) or ((data[at + 1].toInt() and 0xff) shl 8)
/** the 32 bits at [at], little-endian */
fun u32(at: Int): Long = u16(at).toLong() or (u16(at + 2).toLong() shl 16)
/** whether [s] is at [at] */
fun tag(at: Int, s: String) = s.indices.all { data[at + it].toInt() == s[it].code }
if (data.size < 12 || !tag(0, "RIFF") || !tag(8, "WAVE")) return null
var format = 0
var channels = 0
var bits = 0
var rate = 0L
var samples = -1
var bytes = 0
var haveFmt = false
var p = 12
while (data.size - p >= 8) {
val len = u32(p + 4)
val body = p + 8
val left = (data.size - body).toLong()
if (tag(p, "fmt ") && len >= 16 && left >= 16) {
format = u16(body)
channels = u16(body + 2)
rate = u32(body + 4)
bits = u16(body + 14)
// (WAVE_FORMAT_EXTENSIBLE: its subformat's code)
if (format == 0xfffe && len >= 26 && left >= 26) format = u16(body + 24)
haveFmt = true
} else if (tag(p, "data")) {
samples = body
bytes = minOf(len, left).toInt()
break
}
if (len > left) break
p = body + len.toInt() + (len and 1).toInt()
}
if (!haveFmt || samples < 0 || channels !in 1..8 || rate !in 1000..192000) return null
val width = when {
format == 1 && (bits == 8 || bits == 16) -> bits / 8
(format == 6 || format == 7) && bits == 8 -> 1
else -> return null
}
val frames = bytes / (width * channels)
if (frames <= 0) return ShortArray(0)
val outN = (frames.toDouble() * VOICE_RATE / rate).toLong().toInt()
/** channel [c] of frame [frame] as a 16-bit sample */
fun sample(frame: Int, c: Int): Int {
val q = samples + (frame * channels + c) * width
return when {
format == 7 -> G711.unulaw(data[q].toInt() and 0xff)
format == 6 -> G711.unalaw(data[q].toInt() and 0xff)
width == 1 -> ((data[q].toInt() and 0xff) - 128) * 256
else -> u16(q).toShort().toInt()
}
}
return ShortArray(outN) { i ->
// (linear between the two frames around it, each the mean of its channels)
val at = i.toDouble() * rate / VOICE_RATE
val f = at.toInt()
val frac = at - f
var y = 0.0
for (k in 0..1) {
val ff = minOf(f + k, frames - 1)
var sum = 0.0
for (c in 0 until channels) sum += sample(ff, c)
sum /= channels
y += if (k == 1) frac * sum else (1 - frac) * sum
}
y.coerceIn(-32768.0, 32767.0).toInt().toShort()
}
}
}
@@ -0,0 +1,370 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.voice
import org.dmodem.app.io.Bytes
import org.dmodem.app.io.Sink
import org.dmodem.app.io.background
import org.dmodem.app.io.monotonicMs
import org.dmodem.app.io.sleepMs
import org.dmodem.app.jobs.Latin1
import org.dmodem.app.jobs.LogOut
import org.dmodem.app.jobs.VoiceJob
import org.dmodem.app.transfer.Incoming
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
import kotlin.concurrent.Volatile
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.sin
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Voice calls on a fake V.253 modem: dialled and hung up, busy, no voice
* mode, the answering machine's message (the far end hanging up, or
* quiet), picked up; G.711, tones and WAV files.
*/
class VoiceTest {
/**
* A modem in voice mode as dmodemd is: commands answered, AT+VTR's
* stream a 440 Hz tone (for [toneMs], then silence, then [then]: a
* <DLE> code, or nothing), our samples counted, <DLE>^ answered
* with <DLE><ETX> and OK.
*/
private class FakeModem(
val dial: String = "OK",
val voice: Boolean = true,
val toneMs: Long = 100_000,
val endMs: Long = 100_000,
val then: Char? = null,
val digits: String = "",
) {
lateinit var job: VoiceJob
private val lock = SynchronizedObject()
val commands = ArrayList<String>()
private val line = StringBuilder()
@Volatile var streaming = false
@Volatile var got = 0
@Volatile var loud = 0
@Volatile var dle = false
@Volatile var stopped = false
private var phase = 0.0
/** octets from the job */
fun write(s: String): Boolean {
for (ch in s) {
val c = ch.code
if (streaming) {
if (dle) {
dle = false
when (c) {
0x10 -> sample(c)
'^'.code -> {
streaming = false
say("\u0010\u0003\r\nOK\r\n")
}
}
} else if (c == 0x10) {
dle = true
} else {
sample(c)
}
continue
}
if (c == '\r'.code) {
command(line.toString())
line.clear()
} else {
line.append(ch)
}
}
return true
}
/** a sample of ours counted (a loud one too) */
private fun sample(u: Int) {
got++
if (abs(G711.unulaw(u)) > 2000) loud++
}
/** [s] to the job, from another thread */
private fun say(s: String) = background("fake") { job.feed(s) }
/** a command answered as dmodemd would */
private fun command(cmd: String) {
synchronized(lock) { commands.add(cmd) }
val c = cmd.removePrefix("AT")
when {
!voice && (c == "+FCLASS=8" || c == "+VSM=4") -> say("\r\nERROR\r\n")
c.startsWith("D") -> background("dial") { sleepMs(100); job.feed("\r\n$dial\r\n") }
c == "+VTR" -> {
streaming = true
job.feed("\r\nCONNECT\r\n")
background("stream") { stream() }
}
else -> say("\r\nOK\r\n")
}
}
/** the far end's sound, 20 ms at a time */
private fun stream() {
val t0 = monotonicMs()
var sent = 0L
var told = false
var pressed = false
while (streaming && !stopped) {
val now = monotonicMs() - t0
val b = StringBuilder()
while (sent < now * 8) {
val x = if (now < toneMs) (sin(phase) * 8000).toInt() else 0
phase += 2 * PI * 440 / 8000
val u = G711.ulaw(x)
b.append(u.toChar())
if (u == 0x10) b.append(u.toChar())
sent++
}
if (!pressed && digits.isNotEmpty() && now > 200) {
pressed = true
for (d in digits) b.append('\u0010').append(d)
}
if (!told && then != null && now > endMs) {
told = true
b.append('\u0010').append(then)
}
job.feed(b.toString())
sleepMs(20)
}
}
/** the commands so far */
fun said(): List<String> = synchronized(lock) { ArrayList(commands) }
}
private class Memory : Incoming {
val files = LinkedHashMap<String, Bytes>()
/** a new file [name] in memory: its stream and that name */
override fun create(name: String, size: Long): Pair<Sink, String> = Bytes().let { b -> files[name] = b; b to name }
/** file [name] forgotten */
override fun abandon(name: String) { files.remove(name) }
}
private val log = LogOut { }
/** waits up to [ms] for [cond], else fails for want of [what] */
private fun waitFor(what: String, ms: Long = 20_000, cond: () -> Boolean) {
val end = monotonicMs() + ms
while (!cond()) {
if (monotonicMs() > end) throw AssertionError("no $what")
sleepMs(20)
}
}
/** a voice job on [m] */
private fun job(m: FakeModem): VoiceJob = VoiceJob({ s -> m.write(s) }, log, { }).also { m.job = it }
/** a call dialled: voice mode, μ-law, ATD, AT+VTR; both ends' sound at the line's pace; hung up and back to data */
@Test
fun aCallBothWays() {
val m = FakeModem()
val j = job(m)
try {
j.dial("555 1234")
waitFor("the call") { j.state?.phase == VoiceJob.Phase.TALKING }
val mic = ShortArray(160) { (sin(2 * PI * 300 * it / 8000) * 10000).toInt().toShort() }
val heard = ShortArray(8000)
var n = 0
val t0 = monotonicMs()
while (monotonicMs() - t0 < 1000) {
j.write(mic)
n += j.read(heard, n % 4000, 160)
sleepMs(20)
}
assertTrue(n > 6000, "heard $n")
assertTrue(heard.take(4000).any { abs(it.toInt()) > 4000 }, "the far end's tone")
// (about 8000 a second, a little ahead)
assertTrue(m.got in 7000..10000, "sent ${m.got}")
assertTrue(m.loud > 3000, "loud ${m.loud}")
j.hangUp()
waitFor("the end") { j.state?.running == false }
} finally {
m.stopped = true
}
assertEquals("", j.state?.result)
assertEquals(listOf("ATE0V1", "AT+FCLASS=8", "AT+VSM=4", "ATD555 1234", "AT+VTR", "ATH", "AT+FCLASS=0"), m.said())
assertEquals("", j.leftover)
}
/** busy: why the call didn't go, and the modem back to data */
@Test
fun busy() {
val m = FakeModem(dial = "BUSY")
val j = job(m)
j.dial("5551234")
waitFor("the end") { j.state?.running == false }
assertEquals("busy", j.state?.result)
assertTrue("AT+FCLASS=0" in m.said())
assertTrue("AT+VTR" !in m.said())
}
/** a modem without voice mode */
@Test
fun noVoiceMode() {
val m = FakeModem(voice = false)
val j = job(m)
j.answer()
waitFor("the end") { j.state?.running == false }
assertEquals("the modem has no voice mode", j.state?.result)
assertTrue("AT+FCLASS=0" in m.said())
}
/** the answering machine: greeting, beep, the caller's message until they hang up, saved as a WAV */
@Test
fun aMessageTaken() {
val m = FakeModem(toneMs = 2500, endMs = 2600, then = 'l', digits = "12#")
val j = job(m)
val into = Memory()
try {
j.takeMessage(ShortArray(1600) { 3000 }, 60, 7, into, VoiceJob.messageName("20261111-120000", "+1 555-1234"), caller = "5551234")
waitFor("the end") { j.state?.running == false }
} finally {
m.stopped = true
}
val s = assertNotNull(j.state)
assertEquals("", s.result)
assertEquals("20261111-120000_+15551234.wav", s.message)
assertEquals("+15551234", VoiceJob.messageCaller(s.message))
assertEquals("12#", s.digits)
assertTrue("AT+VLS=1" in m.said())
// (0.2 s greeting, 0.5 s beep: about 1.8 s of tone left, its end's quiet but half a second)
val pcm = assertNotNull(Wav.decode(assertNotNull(into.files[s.message]).toByteArray()))
assertTrue(pcm.size in 12000..20000, "${pcm.size}")
assertEquals(pcm.size / 8000, s.messageSeconds)
assertTrue(pcm.count { abs(it.toInt()) > 4000 } > 4000)
// (the beep reached the line: loud samples beyond the greeting's)
assertTrue(m.loud > 2000, "loud ${m.loud}")
}
/** the caller quiet for silenceS: the message ends, the machine hangs up itself */
@Test
fun aQuietCallerEnds() {
val m = FakeModem(toneMs = 1800)
val j = job(m)
val into = Memory()
try {
j.takeMessage(null, 60, 1, into, "m.wav")
waitFor("the end") { j.state?.running == false }
} finally {
m.stopped = true
}
assertEquals("m.wav", j.state?.message)
val pcm = assertNotNull(Wav.decode(assertNotNull(into.files["m.wav"]).toByteArray()))
// (1.3 s of tone after the beep, half a second of quiet kept)
assertTrue(pcm.size in 12000..16000, "${pcm.size}")
assertTrue("ATH" in m.said())
}
/** a call picked up from the answering machine: a call between people, no message */
@Test
fun pickedUp() {
val m = FakeModem()
val j = job(m)
val into = Memory()
try {
j.takeMessage(null, 60, 7, into, "m.wav")
waitFor("the recording") { j.state?.phase == VoiceJob.Phase.RECORDING }
assertTrue(j.pickUp())
assertEquals(VoiceJob.Phase.TALKING, j.state?.phase)
sleepMs(300)
j.hangUp()
waitFor("the end") { j.state?.running == false }
} finally {
m.stopped = true
}
assertEquals("", j.state?.message)
assertTrue(into.files.isEmpty())
}
/** μ-law both ways, and A-law's smallest */
@Test
fun g711() {
for (u in 0..255) {
val x = G711.unulaw(u)
// (0x7f and 0xff are both zero)
if (u != 0x7f) assertEquals(u, G711.ulaw(x), "u $u")
}
assertEquals(0, G711.unulaw(0xff))
assertEquals(8, G711.unalaw(0xd5))
assertEquals(-8, G711.unalaw(0x55))
}
/** DTMF's frequencies, and a tone's samples */
@Test
fun dtmf() {
assertEquals(697.0 to 1209.0, Tone.dtmf('1'))
assertEquals(941.0 to 1477.0, Tone.dtmf('#'))
assertEquals(941.0 to 1633.0, Tone.dtmf('d'))
assertEquals(null, Tone.dtmf('x'))
val t = Tone(1000.0, 0.0, 80, 8000.0)
val xs = IntArray(80) { t.next() }
assertEquals(0, t.next())
assertTrue(xs.max() in 7900..8000)
}
/** a message's WAV read back; 16 kHz stereo 16 bit and 8 bit μ-law ones as 8 kHz mono */
@Test
fun wav() {
val pcm = ShortArray(800) { (it * 37 % 20000 - 10000).toShort() }
val w = Wav.encode(pcm)
assertEquals(44 + 1600, w.size)
assertContentEquals(pcm, Wav.decode(w))
assertEquals(0, Wav.seconds(w.size.toLong()))
// 16 kHz stereo: each frame (L, R) = (1000, 3000) -> 2000, half as many
val st = Bytes()
val h = Wav.header(0).copyOf()
h[22] = 2
put32(h, 24, 16000)
put32(h, 40, 1600 * 4)
st.write(h)
repeat(1600) { put16(st, 1000); put16(st, 3000) }
val d = assertNotNull(Wav.decode(st.toByteArray()))
assertEquals(800, d.size)
assertTrue(d.all { it.toInt() == 2000 })
// μ-law, 8 bit
val ul = Wav.header(0).copyOf()
ul[20] = 7
ul[32] = 1
ul[34] = 8
put32(ul, 40, 100)
val b = Bytes()
b.write(ul)
repeat(100) { b.write(G711.ulaw(-5000)) }
val du = assertNotNull(Wav.decode(b.toByteArray()))
assertEquals(100, du.size)
assertTrue(du.all { abs(it + 5000) < 200 })
assertEquals(null, Wav.decode("not a wav file".encodeToByteArray()))
}
/** [v] to [s], little-endian, 16 bits */
private fun put16(s: Sink, v: Int) { s.write(v and 0xff); s.write((v shr 8) and 0xff) }
/** [v] into [h] at [at], little-endian, 32 bits */
private fun put32(h: ByteArray, at: Int, v: Int) { for (i in 0..3) h[at + i] = (v shr (8 * i)).toByte() }
/** a ring keeps the newest, gives the oldest first */
@Test
fun ring() {
val r = SampleRing(4)
r.put(shortArrayOf(1, 2, 3, 4, 5, 6))
val o = ShortArray(4)
assertEquals(4, r.get(o))
assertContentEquals(shortArrayOf(3, 4, 5, 6), o)
r.put(shortArrayOf(7, 8, 9))
r.keep(1)
assertEquals(9, r.take())
assertEquals(null, r.take())
assertEquals("ab", Latin1.string(byteArrayOf(97, 98)))
}
}