diff --git a/app/src/main/cpp/engine.cpp b/app/src/main/cpp/engine.cpp index a3dd69a..67343d0 100644 --- a/app/src/main/cpp/engine.cpp +++ b/app/src/main/cpp/engine.cpp @@ -119,6 +119,14 @@ void Engine::stop() t.join(); } +/* see engine.h */ +void Engine::set_speaker(SpeakerFn level, SoundFn sound) +{ + std::lock_guard lk(mu_); + speaker_ = std::move(level); + sound_ = std::move(sound); +} + /* see engine.h */ void Engine::peer_event(const char *line) { @@ -173,6 +181,32 @@ void Engine::run(Config cfg, int dte_fd, StatusFn status, ExitFn done, st.rx_rate = s.rx_rate; status(st); }; + /* the speaker: the line as the modem's speaker has it */ + dmd::SipModem::Speaker spk; + { + std::lock_guard lk(mu_); + spk.volume = speaker_; + if (sound_) { + SoundFn sound = sound_; + spk.audio = [sound](const int16_t *rx, const int16_t *tx, + int n) { + int16_t mix[2048]; + while (n > 0) { + int k = n < 2048 ? n : 2048; + for (int i = 0; i < k; i++) { + int v = rx[i] + tx[i] / 2; + mix[i] = (int16_t)(v > 32767 ? 32767 : + v < -32768 ? -32768 : v); + } + sound(mix, k); + rx += k; + tx += k; + n -= k; + } + }; + } + } + /* the modem's data file loaded, the modem run, the file saved */ auto serve = [&](dcore::Modem &m, auto &&run_it) { std::unique_ptr data; @@ -194,6 +228,7 @@ void Engine::run(Config cfg, int dte_fd, StatusFn status, ExitFn done, if (status) pm.on_status(report); pm.on_line(std::move(line_fn)); + pm.on_speaker(spk); { std::lock_guard lk(mu_); peer_ = ± @@ -209,6 +244,7 @@ void Engine::run(Config cfg, int dte_fd, StatusFn status, ExitFn done, if (sm.ok()) { if (status) sm.on_status(report); + sm.on_speaker(spk); { std::lock_guard lk(mu_); modem_ = &sm; diff --git a/app/src/main/cpp/engine.h b/app/src/main/cpp/engine.h index 6e68fde..752de72 100644 --- a/app/src/main/cpp/engine.h +++ b/app/src/main/cpp/engine.h @@ -16,6 +16,8 @@ #ifndef DMODEM_ANDROID_ENGINE_H #define DMODEM_ANDROID_ENGINE_H +#include + #include #include #include @@ -80,6 +82,14 @@ public: fn; NULL: stderr. Before start() */ void set_log(LogFn fn); + /* the modem's speaker (ATM, ATL), from its thread: level(0 off, + 1..3) as it changes, and while it is on the line's sound in + blocks (what came, with the modem's own at half its level, as a + modem's speaker has the line). Before start() */ + using SpeakerFn = std::function; + using SoundFn = std::function; + void set_speaker(SpeakerFn level, SoundFn sound); + /* the modem started in its thread with cfg: the app's end of the DTE's socket pair (the caller's to close), or -1 if it is running already or can't be started. status and done are @@ -104,6 +114,8 @@ private: std::thread thread_; dmd::SipModem *modem_ = nullptr; /* while run() has one */ PeerModem *peer_ = nullptr; /* or this one */ + SpeakerFn speaker_; + SoundFn sound_; bool active_ = false; /* run() hasn't ended */ bool stopping_ = false; }; diff --git a/app/src/main/cpp/jni.cpp b/app/src/main/cpp/jni.cpp index 6ad97f5..b624356 100644 --- a/app/src/main/cpp/jni.cpp +++ b/app/src/main/cpp/jni.cpp @@ -11,6 +11,7 @@ */ #include +#include #include #include @@ -27,7 +28,9 @@ const char CLASS[] = "com/neodesktop/dmodem/NativeModem"; JavaVM *vm; jclass cls; -jmethodID on_log, on_status, on_exit, on_line; +jmethodID on_log, on_status, on_exit, on_line, on_speaker; +/* the speaker's sound: written to [0] (dropped when full), Kotlin reads [1] */ +int speaker_fd[2] = { -1, -1 }; /* this thread's JNIEnv, the thread attached if it wasn't (detached again when it ends) */ @@ -135,6 +138,25 @@ void line_started(bool caller, const char *dial, int fd) env->DeleteLocalRef(d); } +void speaker_level(int level) +{ + JNIEnv *env = env_now(); + if (!env) + return; + env->CallStaticVoidMethod(cls, on_speaker, (jint)level); + clear(env); +} + +/* the sound to Kotlin's player, never waiting (the modem's thread) */ +void speaker_sound(const int16_t *pcm, int n) +{ + if (speaker_fd[0] >= 0 && + send(speaker_fd[0], pcm, 2 * (size_t)n, + MSG_DONTWAIT | MSG_NOSIGNAL) < 0) { + /* (the player behind: this block dropped) */ + } +} + std::string str(JNIEnv *env, jstring s) { if (!s) @@ -182,6 +204,15 @@ void native_peer_event(JNIEnv *env, jclass, jstring line) Engine::instance().peer_event(str(env, line).c_str()); } +/* NativeModem.nativeSpeakerFd(): the speaker sound's end for Kotlin + (one for the process: -1 after the first) */ +jint native_speaker_fd(JNIEnv *, jclass) +{ + int fd = speaker_fd[1]; + speaker_fd[1] = -1; + return fd; +} + jboolean native_running(JNIEnv *, jclass) { return Engine::instance().running(); @@ -194,6 +225,7 @@ const JNINativeMethod methods[] = { reinterpret_cast(native_start) }, { "nativeStop", "()V", reinterpret_cast(native_stop) }, { "nativeRunning", "()Z", reinterpret_cast(native_running) }, + { "nativeSpeakerFd", "()I", reinterpret_cast(native_speaker_fd) }, { "nativePeerEvent", "(Ljava/lang/String;)V", reinterpret_cast(native_peer_event) }, }; @@ -219,11 +251,19 @@ extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *) on_exit = env->GetStaticMethodID(cls, "onExit", "(I)V"); on_line = env->GetStaticMethodID(cls, "onLine", "(ZLjava/lang/String;I)V"); - if (!on_log || !on_status || !on_exit || !on_line) + on_speaker = env->GetStaticMethodID(cls, "onSpeaker", "(I)V"); + if (!on_log || !on_status || !on_exit || !on_line || !on_speaker) return JNI_ERR; if (env->RegisterNatives(cls, methods, sizeof(methods) / sizeof(methods[0])) < 0) return JNI_ERR; Engine::instance().set_log(log_line); + if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, speaker_fd) == 0) { + /* (a second's room: the player keeps up, or blocks go) */ + int size = 32 * 1024; + setsockopt(speaker_fd[0], SOL_SOCKET, SO_SNDBUF, &size, + sizeof(size)); + } + Engine::instance().set_speaker(speaker_level, speaker_sound); return JNI_VERSION_1_6; } diff --git a/app/src/main/cpp/peer_modem.cpp b/app/src/main/cpp/peer_modem.cpp index 9d6df4c..47b01bb 100644 --- a/app/src/main/cpp/peer_modem.cpp +++ b/app/src/main/cpp/peer_modem.cpp @@ -89,8 +89,15 @@ public: return dte_.write(buf, n); } unsigned long now_ms() override { return dcore::monotonic_ms(); } + /* ATM, ATL */ + void speaker(dcore::Modem &, int volume) override { + speaker_level_ = volume; + if (speaker_to.volume) + speaker_to.volume(volume); + } PeerModem::LineFn line_fn; + dmd::SipModem::Speaker speaker_to; int fd() const { return fd_; } /* the ms until the line may take samples again (0: now) */ @@ -110,6 +117,7 @@ private: dmd::Dte &dte_; int lead_ms_; int fd_ = -1; + int speaker_level_ = 0; /* an odd octet of the line's, the next sample's first */ bool have_half_ = false; unsigned char half_ = 0; @@ -210,6 +218,8 @@ int PeerLine::audio(dcore::Modem &m) } samples_ += count; m.process(in, out, count); + if (speaker_level_ > 0 && speaker_to.audio) + speaker_to.audio(in, out, count); if (fd_ < 0) return 0; /* (it hung up on these) */ if (!send_all(fd_, out, 2 * (size_t)count)) { @@ -256,6 +266,11 @@ void PeerModem::on_line(LineFn fn) line_->line_fn = std::move(fn); } +void PeerModem::on_speaker(dmd::SipModem::Speaker s) +{ + line_->speaker_to = std::move(s); +} + /* see peer_modem.h */ void PeerModem::stop() { diff --git a/app/src/main/cpp/peer_modem.h b/app/src/main/cpp/peer_modem.h index c328f0d..6bbac25 100644 --- a/app/src/main/cpp/peer_modem.h +++ b/app/src/main/cpp/peer_modem.h @@ -60,6 +60,8 @@ public: status_fn_ = std::move(fn); } void on_line(LineFn fn); + /* the speaker, as SipModem's (sip_modem.h) */ + void on_speaker(dmd::SipModem::Speaker s); /* served until stop() or the DTE has gone: 0; -1 on an error */ int run(); diff --git a/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt b/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt index 2845966..1eb01a8 100644 --- a/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt +++ b/app/src/main/java/com/neodesktop/dmodem/NativeModem.kt @@ -67,6 +67,8 @@ object NativeModem { fun onExit(result: Int) {} /** A peer line's modem off hook: dialling (caller) [dial], or answering; [line] its samples (ours to close). */ fun onLine(caller: Boolean, dial: String, line: ParcelFileDescriptor) { line.close() } + /** The modem's speaker (ATM, ATL): 0 off, 1..3 its volume. */ + fun onSpeaker(level: Int) {} } @Volatile @@ -92,6 +94,13 @@ object NativeModem { val running: Boolean get() = nativeRunning() + /** + * The modem speaker's sound while it is on (the line, 8000 Hz 16 bit + * mono, in blocks): its socket, for the process's one reader (null + * after the first call). + */ + fun speakerSound(): ParcelFileDescriptor? = nativeSpeakerFd().takeIf { it >= 0 }?.let { ParcelFileDescriptor.adoptFd(it) } + /** A peer line's event to the modem: RING, CANCEL, ANSWERED, FAILED , DROPPED. */ fun peerEvent(line: String) = nativePeerEvent(line) @@ -106,6 +115,9 @@ object NativeModem { @JvmStatic private external fun nativePeerEvent(line: String) + @JvmStatic + private external fun nativeSpeakerFd(): Int + @JvmStatic private external fun nativeStop() @@ -132,6 +144,11 @@ object NativeModem { if (l == null) pfd.close() else l.onLine(caller, dial, pfd) } + @JvmStatic + private fun onSpeaker(level: Int) { + listener?.onSpeaker(level) + } + @JvmStatic private fun onExit(result: Int) { listener?.onExit(result) diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt index 4150f63..0ba7a17 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt @@ -55,6 +55,8 @@ class ModemService : Service() { private const val ACTION_STOP = "com.neodesktop.dmodem.STOP" private const val NOTIFICATION_ID = 1 private const val DATA_FILE = "dsp_data" + /** the speaker's sound socket, kept open for the process's life */ + @Volatile private var speakerSocket: android.os.ParcelFileDescriptor? = null fun start(context: Context) { context.startForegroundService( @@ -200,6 +202,12 @@ class ModemService : Service() { } ModemState.dte.attach(pfd) ModemState.setStatus(ModemState.IDLE) + ModemState.speaker.enabled = settings.speaker + // (the speaker's sound: one socket for the process, read for good once started) + NativeModem.speakerSound()?.let { s -> + speakerSocket = s + ModemState.speaker.start(java.io.FileInputStream(s.fileDescriptor)) + } if (settings.peer) com.neodesktop.dmodem.peer.Peers.start(this, settings, ::log) if (settings.initCommands.isNotBlank()) { ModemState.dte.write(settings.initCommands.trim() + "\r") @@ -210,6 +218,7 @@ class ModemService : Service() { /** the native modem stopped: the call hung up, SIP gone, the DTE's socket closed */ private fun stopNative() { stopping = true + ModemState.speaker.setLevel(0) com.neodesktop.dmodem.peer.Peers.stop() NativeModem.stop() ModemState.dte.detach() @@ -258,6 +267,10 @@ class ModemService : Service() { ModemState.setStatus(status) } + override fun onSpeaker(level: Int) { + ModemState.speaker.setLevel(level) + } + override fun onLine(caller: Boolean, dial: String, line: android.os.ParcelFileDescriptor) { com.neodesktop.dmodem.peer.Peers.lineStarted(caller, dial, line) } diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt new file mode 100644 index 0000000..7f0cc06 --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemSpeaker.kt @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.modem + +import android.media.AudioAttributes +import android.media.AudioFormat +import android.media.AudioTrack +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.io.IOException +import java.io.InputStream + +/** + * The modem's speaker on the phone's: the line as a modem's speaker had + * it (the dial tone, the dialling, the other end ringing, the answer tone + * and the training's hiss), on when the modem says (ATM1, its default: + * from off hook until CONNECT; ATM2 always, ATM0 never) at ATL's volume. + * [enabled] off: silent whatever the modem says. + * + * The sound comes from the native modem's thread on a socket ([start]), + * played here on a thread of its own: the modem never waits for it. + */ +class ModemSpeaker( + /** where the sound goes (an AudioTrack's, or the tests') */ + private val newSink: () -> Sink = { TrackSink() }, +) { + /** a player: 8000 Hz, 16 bit, mono */ + interface Sink { + fun write(pcm: ByteArray, n: Int) + /** 0..1 */ + fun volume(v: Float) + fun close() + } + + @Volatile var enabled = true + private val _level = MutableStateFlow(0) + /** the modem's speaker level now (0 off, 1..3) */ + val level: StateFlow = _level.asStateFlow() + + private var sink: Sink? = null + private val lock = Any() + + /** the modem's word: [level] 0 off, else ATL's */ + fun setLevel(level: Int) { + _level.value = level + synchronized(lock) { + if (level <= 0) { + sink?.close() + sink = null + } else { + sink?.volume(gain(level)) + } + } + } + + /** the sound from [input] until it ends, played while on (a thread of its own) */ + fun start(input: InputStream): Thread = Thread({ + val buf = ByteArray(8192) + while (true) { + val n = try { input.read(buf) } catch (_: IOException) { -1 } + if (n < 0) break + play(buf, n) + } + }, "modem-speaker").apply { isDaemon = true; start() } + + /** a block of the sound: played if the speaker is on, else let go */ + fun play(pcm: ByteArray, n: Int) { + val l = _level.value + val s = synchronized(lock) { + if (l <= 0 || !enabled) { + sink?.close() + sink = null + return + } + sink ?: runCatching { newSink() }.getOrNull()?.also { it.volume(gain(l)); sink = it } + } ?: return + // (outside the lock: a player's write may wait for room) + runCatching { s.write(pcm, n) } + } + + companion object { + /** ATL's levels: low, medium, high */ + fun gain(level: Int): Float = when (level) { + 1 -> 0.3f + 2 -> 0.6f + else -> 1f + } + } + + /** the phone's speaker (media's stream and volume) */ + private class TrackSink : Sink { + private val track: AudioTrack = run { + val min = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) + AudioTrack.Builder() + .setAudioAttributes( + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_MEDIA) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build(), + ) + .setAudioFormat( + AudioFormat.Builder() + .setSampleRate(8000) + .setChannelMask(AudioFormat.CHANNEL_OUT_MONO) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .build(), + ) + .setTransferMode(AudioTrack.MODE_STREAM) + // (a tenth of a second or so: the sound keeps up with the line) + .setBufferSizeInBytes(maxOf(min, 1600)) + .build() + .apply { play() } + } + + override fun write(pcm: ByteArray, n: Int) { + track.write(pcm, 0, n) + } + + override fun volume(v: Float) { + track.setVolume(v) + } + + override fun close() { + runCatching { track.pause(); track.flush() } + track.release() + } + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt index c43cf96..2e3c934 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt @@ -32,6 +32,9 @@ object ModemState { /** The modem's DTE, shared by the console, the terminal and the bridges. */ val dte = DteHub() + /** the modem's speaker on the phone's (ATM, ATL) */ + val speaker = ModemSpeaker() + /** The log's last lines (the modem's and SIP's). */ val log = LineBuffer(MAX_LOG) diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt index bd8b039..361baa9 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt @@ -41,6 +41,8 @@ data class ModemSettings( val peerName: String = "", /** the TCP port phones call each other on */ val peerPort: Int = 5070, + /** the modem's speaker on the phone's: the dialling and the handshake heard (as ATM and ATL have it) */ + val speaker: Boolean = true, ) { /** the line is another phone, not SIP */ val peer: Boolean get() = line != LINE_SIP @@ -89,6 +91,7 @@ class SettingsStore(private val context: Context) { val peerAddress = stringPreferencesKey("peer_address") val peerName = stringPreferencesKey("peer_name") val peerPort = intPreferencesKey("peer_port") + val speaker = booleanPreferencesKey("speaker") } val settings: Flow = context.dataStore.data.map { p -> @@ -108,6 +111,7 @@ class SettingsStore(private val context: Context) { peerAddress = p[Keys.peerAddress] ?: d.peerAddress, peerName = p[Keys.peerName] ?: d.peerName, peerPort = p[Keys.peerPort] ?: d.peerPort, + speaker = p[Keys.speaker] ?: d.speaker, ) } @@ -129,6 +133,7 @@ class SettingsStore(private val context: Context) { p[Keys.peerAddress] = s.peerAddress.trim() p[Keys.peerName] = s.peerName p[Keys.peerPort] = s.peerPort + p[Keys.speaker] = s.speaker } } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt index ae18dd2..2f05ec8 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt @@ -89,6 +89,12 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = { } Text("Modem", style = MaterialTheme.typography.titleMedium) + Toggle("Speaker: hear the dialling and the handshake", s.speaker) { s = s.copy(speaker = it) } + Text( + "As a modem's speaker: on from off hook until CONNECT (ATM1). ATM0 keeps it quiet, ATM2 on all the call; " + + "ATL1-3 its volume, on top of the phone's media volume.", + style = MaterialTheme.typography.bodySmall, + ) Field("Init commands (sent at start)", s.initCommands) { s = s.copy(initCommands = it) } Field("Country (empty: USA)", s.country) { s = s.copy(country = it) } NumberField("Modem log level (0-5)", s.logLevel) { s = s.copy(logLevel = it.coerceIn(0, 5)) } diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/ModemSpeakerTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/ModemSpeakerTest.kt new file mode 100644 index 0000000..d860232 --- /dev/null +++ b/app/src/test/java/com/neodesktop/dmodem/modem/ModemSpeakerTest.kt @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.modem + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.PipedInputStream +import java.io.PipedOutputStream + +/** The speaker: played only while the modem has it on (and the app lets it), at ATL's volume, let go when off. */ +class ModemSpeakerTest { + private class FakeSink : ModemSpeaker.Sink { + var bytes = 0 + var volume = -1f + var closed = false + override fun write(pcm: ByteArray, n: Int) { bytes += n } + override fun volume(v: Float) { volume = v } + override fun close() { closed = true } + } + + @Test + fun onlyWhileOn() { + val sinks = ArrayList() + val spk = ModemSpeaker { FakeSink().also { sinks.add(it) } } + val block = ByteArray(320) + // off: nothing made, nothing played + spk.play(block, block.size) + assertEquals(0, sinks.size) + // ATM1 off hook at ATL2 + spk.setLevel(2) + spk.play(block, block.size) + spk.play(block, block.size) + assertEquals(1, sinks.size) + assertEquals(640, sinks[0].bytes) + assertEquals(0.6f, sinks[0].volume) + // ATL3 meanwhile + spk.setLevel(3) + assertEquals(1f, sinks[0].volume) + // CONNECT: off, the player let go + spk.setLevel(0) + assertTrue(sinks[0].closed) + spk.play(block, block.size) + assertEquals(640, sinks[0].bytes) + assertEquals(1, sinks.size) + // the app's switch off: quiet whatever the modem says + spk.enabled = false + spk.setLevel(3) + spk.play(block, block.size) + assertEquals(1, sinks.size) + spk.enabled = true + spk.play(block, block.size) + assertEquals(2, sinks.size) + } + + @Test + fun fromItsSocket() { + val sink = FakeSink() + val spk = ModemSpeaker { sink } + spk.setLevel(1) + val out = PipedOutputStream() + val t = spk.start(PipedInputStream(out, 65536)) + out.write(ByteArray(8000)) + out.close() + t.join(5000) + assertEquals(8000, sink.bytes) + assertEquals(0.3f, sink.volume) + } +} diff --git a/app/src/test/java/com/neodesktop/dmodem/peer/PeerLineTest.kt b/app/src/test/java/com/neodesktop/dmodem/peer/PeerLineTest.kt index 2df6b0b..171ca92 100644 --- a/app/src/test/java/com/neodesktop/dmodem/peer/PeerLineTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/peer/PeerLineTest.kt @@ -52,7 +52,8 @@ class PeerLineTest { init { val bin = peerHost() assumeTrue("peer_host isn't built (native-test)", bin != null) - proc = ProcessBuilder(bin!!.path, leadMs.toString()).redirectError(File("/tmp/peer_host_$name.log")).start() + proc = ProcessBuilder(bin!!.path, leadMs.toString()).redirectError(File("/tmp/peer_host_$name.log")) + .apply { environment()["PEER_SPEAKER"] = "/tmp/peer_speaker_$name.raw" }.start() closers.add { proc.destroyForcibly() } Thread { proc.inputStream.bufferedReader().forEachLine { l -> out.add(l) } @@ -155,6 +156,11 @@ class PeerLineTest { assertTrue(a.line.state.value is PeerLine.State.Connected) assertTrue(b.line.state.value is PeerLine.State.Connected) assertTrue(a.events.contains("ANSWERED")) + // the caller's speaker (ATM1): on from the dial to CONNECT, the dial tone, ringback and training heard + val spk = a.statuses.filter { it.startsWith("SPEAKER") } + assertTrue(spk.toString(), spk.first().startsWith("SPEAKER 3")) + assertTrue(spk.toString(), spk.last().startsWith("SPEAKER 0")) + assertTrue(spk.toString(), spk.last().split(' ')[2].toLong() > 3 * 8000) // data both ways a.send("hello from A\r\n") b.expect("hello from A") diff --git a/external/d-modem-re b/external/d-modem-re index 0d77922..982b5cf 160000 --- a/external/d-modem-re +++ b/external/d-modem-re @@ -1 +1 @@ -Subproject commit 0d77922b25710251cc2d64b88f17f6f318e6a8c7 +Subproject commit 982b5cf80c7ecb743c8e1f2f591b05a662f58846 diff --git a/native-test/engine_test.cpp b/native-test/engine_test.cpp index c640320..852d2f3 100644 --- a/native-test/engine_test.cpp +++ b/native-test/engine_test.cpp @@ -60,6 +60,10 @@ Status last; bool was_online; unsigned online_tx, online_rx; int exits, exit_result; +/* the speaker: its level now, whether it came on, its samples */ +int spk_level; +bool spk_was_on; +long spk_samples; std::string logs; void on_engine_status(const Status &s) @@ -194,20 +198,38 @@ Config config(bool listen) /* a call from the engine to dmodemd and back: CONNECT, data both ways, the status online, a hangup from the engine's side */ -void call_out(int app, int pty, const char *what) +void call_out(int app, int pty, const char *what, bool speaker) { std::string got; + long heard; { std::lock_guard lk(mu); was_online = false; } - put(app, "ATX3\r"); + { + std::lock_guard lk(mu); + spk_was_on = false; + spk_samples = 0; + } + /* (ATM1, the modem's own: the speaker on until CONNECT; ATM0 off) */ + put(app, speaker ? "ATX3M1\r" : "ATX3M0\r"); CHECK(expect(app, "OK", 5), "%s: ATX3 OK", what); put(app, "ATD1234\r"); CHECK(expect(app, "CONNECT[^\r]*", 90, &got), "%s: the engine: %s", what, got.substr(got.find("CONNECT") == std::string::npos ? 0 : got.find("CONNECT")).c_str()); + { + std::lock_guard lk(mu); + heard = spk_samples; + if (speaker) + CHECK(spk_was_on && spk_level == 0 && heard > 8000, + "%s: the speaker on until CONNECT (%.1f s of the " + "line heard), off then", what, heard / 8000.0); + else + CHECK(!spk_was_on && heard == 0, + "%s: ATM0: the speaker stayed off", what); + } CHECK(expect(pty, "CONNECT", 30), "%s: dmodemd: CONNECT", what); std::this_thread::sleep_for(std::chrono::seconds(1)); std::string msg; @@ -220,6 +242,11 @@ void call_out(int app, int pty, const char *what) put(pty, "an answer from dmodemd"); CHECK(expect(app, "an answer from dmodemd", 20), "%s: dmodemd's data reached the app", what); + { + std::lock_guard lk(mu); + CHECK(spk_samples == heard, + "%s: nothing to the speaker in data mode", what); + } { std::lock_guard lk(mu); CHECK(was_online && online_tx && online_rx, @@ -261,6 +288,18 @@ int main(int argc, char *argv[]) printf(" | %s", line); }); + e.set_speaker( + [](int level) { + std::lock_guard lk(mu); + spk_level = level; + if (level > 0) + spk_was_on = true; + }, + [](const int16_t *, int n) { + std::lock_guard lk(mu); + spk_samples += n; + }); + dm = start_dmodemd(argv[1], &pty); CHECK(dm > 0 && pty >= 0, "dmodemd started"); if (dm <= 0) @@ -274,7 +313,7 @@ int main(int argc, char *argv[]) CHECK(app >= 0 && e.running(), "the engine started"); CHECK(e.start(config(false), on_engine_status, on_engine_exit) < 0, "a second start() refused while it runs"); - call_out(app, pty, "call 1"); + call_out(app, pty, "call 1", true); e.stop(); CHECK(wait_exits(1, 5) && exit_result == 0 && !e.running(), "stop(): the engine ended (%d)", exit_result); @@ -283,7 +322,7 @@ int main(int argc, char *argv[]) /* 2: started again, out again */ app = e.start(config(false), on_engine_status, on_engine_exit); CHECK(app >= 0, "the engine started again"); - call_out(app, pty, "call 2"); + call_out(app, pty, "call 2", false); e.stop(); CHECK(wait_exits(2, 5) && exit_result == 0, "stop() again"); close(app); diff --git a/native-test/peer_host.cpp b/native-test/peer_host.cpp index c0f3b08..a45354a 100644 --- a/native-test/peer_host.cpp +++ b/native-test/peer_host.cpp @@ -15,6 +15,7 @@ * answering): the line's samples on a * connection to 127.0.0.1: * STATUS + * SPEAKER * EXIT * On stdin, the app's lines to the modem (RING, CANCEL, ANSWERED, * FAILED , DROPPED). The log on stderr. @@ -137,6 +138,22 @@ int main(int argc, char *argv[]) cfg.peer = true; cfg.peer_lead_ms = argc > 1 ? atoi(argv[1]) : 100; cfg.log_level = getenv("PEER_LOG") ? atoi(getenv("PEER_LOG")) : 1; + /* the speaker: its level, the samples heard; PEER_SPEAKER=: + the sound too, raw */ + static FILE *sound = getenv("PEER_SPEAKER") ? + fopen(getenv("PEER_SPEAKER"), "wb") : nullptr; + static long heard; + e.set_speaker( + [](int level) { + say("SPEAKER %d %ld\n", level, heard); + }, + [](const int16_t *pcm, int n) { + heard += n; + if (sound) { + fwrite(pcm, 2, n, sound); + fflush(sound); + } + }); int dte = e.start(cfg, [](const Status &s) { say("STATUS %d %d %u %u\n", (int)s.link, s.offhook,