mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Fax tests: against D-Modem-RE's own T.30, and over SIP with T.38
native-test's t30_line: a class 1 modem on a line to dsp/t30.cpp's fax machine (ECM or not, noise if asked); sip_fax_line: the app's engine dialling a dmodemd over loopback SIP with T.38, each DTE a pty. The tests (T30InteropTest, SipFaxTest) drive our T.30 on them, skipped without the programs; FaxLineProcess and Pbm shared among the fax tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
8 files changed
+736
-30
No files matched your search
@@ -164,34 +164,6 @@ class FaxCallTest {
|
||||
|
||||
private fun efaxThere() = File("/usr/bin/efax").canExecute() && File("/usr/bin/efix").canExecute()
|
||||
|
||||
/** [p] as a PBM file */
|
||||
private fun pbm(p: FaxPage, f: File) {
|
||||
f.outputStream().use { o ->
|
||||
o.write("P4\n${p.width} ${p.rows}\n".toByteArray())
|
||||
o.write(p.bits)
|
||||
}
|
||||
}
|
||||
|
||||
/** a PBM file's page */
|
||||
private fun readPbm(f: File, fine: Boolean): FaxPage {
|
||||
val d = f.readBytes()
|
||||
var i = 0
|
||||
val fields = ArrayList<String>()
|
||||
while (fields.size < 3) {
|
||||
while (d[i].toInt().toChar().isWhitespace()) i++
|
||||
if (d[i].toInt().toChar() == '#') { while (d[i].toInt() != '\n'.code) i++; continue }
|
||||
val s = i
|
||||
while (!d[i].toInt().toChar().isWhitespace()) i++
|
||||
fields.add(String(d, s, i - s))
|
||||
}
|
||||
i++
|
||||
val w = fields[1].toInt()
|
||||
val h = fields[2].toInt()
|
||||
val p = FaxPage(w, h, fine)
|
||||
System.arraycopy(d, i, p.bits, 0, minOf(p.bits.size, d.size - i))
|
||||
return p
|
||||
}
|
||||
|
||||
private fun run(vararg cmd: String, dir: File): Int =
|
||||
ProcessBuilder(*cmd).directory(dir).redirectErrorStream(true).redirectOutput(File(dir, "${File(cmd[0]).name}.out")).start().waitFor()
|
||||
|
||||
@@ -200,7 +172,7 @@ class FaxCallTest {
|
||||
assumeTrue("efax isn't installed", efaxThere())
|
||||
val dir = tmp.newFolder("efax-tx")
|
||||
val page = FaxTestPage.of(true, rows = 500, seed = 3)
|
||||
pbm(page, File(dir, "page.pbm"))
|
||||
Pbm.write(page, File(dir, "page.pbm"))
|
||||
// (a TIFF, as efax reads its documents)
|
||||
assertEquals(0, run("efix", "-i", "pbm", "-R", "204x196", "-o", "tiffg3", "-n", "page.tif", "page.pbm", dir = dir))
|
||||
val rx = PtyEnd(b).apply { setUp(caller = false, maxBps = 9600) }
|
||||
@@ -264,7 +236,7 @@ class FaxCallTest {
|
||||
val f = File(dir, "got.%03d".format(i + 1))
|
||||
assertTrue("$f\n$efaxLog", f.exists())
|
||||
assertEquals(0, run("efix", "-i", "fax", "-o", "pbm", "-n", "got-${i + 1}.pbm", f.name, dir = dir))
|
||||
val back = readPbm(File(dir, "got-${i + 1}.pbm"), false)
|
||||
val back = Pbm.read(File(dir, "got-${i + 1}.pbm"), false)
|
||||
assertEquals("page ${i + 1}'s rows", pages[i].rows, back.rows)
|
||||
assertArrayEquals("page ${i + 1}", pages[i].bits, back.bits)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** a test's line program (native-test's), found as $[env] or in build-host; null if it isn't built */
|
||||
fun nativeTool(env: String, name: String): File? = listOfNotNull(
|
||||
System.getenv(env),
|
||||
"../build-host/$name",
|
||||
"build-host/$name",
|
||||
).map { File(it) }.firstOrNull { it.canExecute() }
|
||||
|
||||
/**
|
||||
* A line program running (its stderr and stdout into [log]), its
|
||||
* modems' ptys as it names them ("created modemA: <pty>"), each a
|
||||
* [Class1] from here.
|
||||
*/
|
||||
class FaxLineProcess(cmd: List<String>) : AutoCloseable {
|
||||
val log = CopyOnWriteArrayList<String>()
|
||||
private val proc: Process = ProcessBuilder(cmd).start()
|
||||
private val closers = ArrayList<() -> Unit>()
|
||||
|
||||
init {
|
||||
Thread { proc.errorStream.bufferedReader().forEachLine { log.add(it) } }.apply { isDaemon = true; start() }
|
||||
Thread { proc.inputStream.bufferedReader().forEachLine { log.add(it) } }.apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
/** the pty of [name] (modemA, modemB), opened raw: our class 1 modem on it */
|
||||
fun modem(name: String, tag: String = name): Class1 {
|
||||
val end = System.currentTimeMillis() + 15_000
|
||||
while (System.currentTimeMillis() < end && log.none { it.startsWith("created $name: ") }) Thread.sleep(20)
|
||||
val pty = log.firstOrNull { it.startsWith("created $name: ") }?.substringAfter(": ")
|
||||
?: throw AssertionError("no $name\n${dump()}")
|
||||
ProcessBuilder("stty", "-F", pty, "raw", "-echo").start().waitFor()
|
||||
val i = FileInputStream(pty)
|
||||
val o = FileOutputStream(pty)
|
||||
closers.add { i.close(); o.close() }
|
||||
val io = TransferIo { b -> o.write(b); o.flush() }
|
||||
Thread {
|
||||
val buf = ByteArray(4096)
|
||||
while (true) {
|
||||
val n = try { i.read(buf) } catch (_: Exception) { -1 }
|
||||
if (n < 0) break
|
||||
io.feed(buf, 0, n)
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
return Class1(io) { line -> log.add("$tag: $line") }
|
||||
}
|
||||
|
||||
fun dump(n: Int = 80) = log.takeLast(n).joinToString("\n")
|
||||
|
||||
override fun close() {
|
||||
closers.forEach { runCatching { it() } }
|
||||
proc.destroy()
|
||||
if (!proc.waitFor(5, TimeUnit.SECONDS)) proc.destroyForcibly()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** fax pages as PBM files (P4), for the tests with other fax programs */
|
||||
object Pbm {
|
||||
/** [p] as a PBM file */
|
||||
fun write(p: FaxPage, f: File) {
|
||||
f.outputStream().use { o ->
|
||||
o.write("P4\n${p.width} ${p.rows}\n".toByteArray())
|
||||
o.write(p.bits)
|
||||
}
|
||||
}
|
||||
|
||||
/** a PBM file's page */
|
||||
fun read(f: File, fine: Boolean): FaxPage {
|
||||
val d = f.readBytes()
|
||||
var i = 0
|
||||
val fields = ArrayList<String>()
|
||||
while (fields.size < 3) {
|
||||
while (d[i].toInt().toChar().isWhitespace()) i++
|
||||
if (d[i].toInt().toChar() == '#') { while (d[i].toInt() != '\n'.code) i++; continue }
|
||||
val s = i
|
||||
while (!d[i].toInt().toChar().isWhitespace()) i++
|
||||
fields.add(String(d, s, i - s))
|
||||
}
|
||||
i++
|
||||
val w = fields[1].toInt()
|
||||
val h = fields[2].toInt()
|
||||
val p = FaxPage(w, h, fine)
|
||||
System.arraycopy(d, i, p.bits, 0, minOf(p.bits.size, d.size - i))
|
||||
return p
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Fax over SIP as the app has it: the app's engine dialling a dmodemd
|
||||
* over loopback SIP (native-test's sip_fax_line, or
|
||||
* DMODEM_SIP_FAX_LINE; skipped without it), our T.30 on both modems.
|
||||
* With T.38 on both, the call goes over to T.38 once the answerer asks
|
||||
* (a second after it answered, in fax mode) and the pages go as IFP
|
||||
* packets in UDPTL; with ECM and without; and on audio when T.38 is off.
|
||||
*/
|
||||
class SipFaxTest {
|
||||
private var line: FaxLineProcess? = null
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
line?.close()
|
||||
}
|
||||
|
||||
private fun call(t38: Boolean, ecm: Boolean) {
|
||||
val bin = nativeTool("DMODEM_SIP_FAX_LINE", "sip_fax_line")
|
||||
assumeTrue("sip_fax_line isn't built (native-test)", bin != null)
|
||||
val l = FaxLineProcess(listOfNotNull(bin!!.path, if (t38) null else "--no-t38"))
|
||||
line = l
|
||||
val tx = l.modem("modemA", "engine dte")
|
||||
val rx = l.modem("modemB", "dmodemd dte")
|
||||
assertEquals(l.dump(), "OK", tx.command("E0X3+FCLASS=1"))
|
||||
assertEquals(l.dump(), "OK", rx.command("E0+FCLASS=1"))
|
||||
val txRates = T30.modemRates(tx)
|
||||
val rxRates = T30.modemRates(rx)
|
||||
val pages = listOf(FaxTestPage.of(true, rows = 600, seed = 1), FaxTestPage.of(true, rows = 300, seed = 2))
|
||||
val got = ArrayList<FaxPage>()
|
||||
var rxDone: FaxProgress? = null
|
||||
var rxError: Throwable? = null
|
||||
tx.send("D5551000")
|
||||
assertEquals(l.dump(), "RING", rx.result(20_000))
|
||||
val receiver = Thread {
|
||||
try {
|
||||
assertEquals("CONNECT", rx.command("A", 20_000))
|
||||
rxDone = T30.receive(rx, "+1 555 0199", rxRates, ecm = ecm) { pg, _ -> got.add(pg) }
|
||||
} catch (e: Throwable) {
|
||||
rxError = e
|
||||
}
|
||||
}
|
||||
receiver.start()
|
||||
assertEquals(l.dump(), "CONNECT", tx.result(30_000))
|
||||
val sent = try {
|
||||
T30.send(tx, pages, "+1 555 0100", txRates, ecm = ecm)
|
||||
} catch (e: Exception) {
|
||||
throw AssertionError("$e\n${l.dump(200)}")
|
||||
}
|
||||
receiver.join(60_000)
|
||||
assertEquals(l.dump(200), null, rxError)
|
||||
assertEquals(2, sent.pages)
|
||||
assertEquals(ecm, sent.ecm)
|
||||
assertEquals("+1 555 0199", sent.remote)
|
||||
assertEquals("+1 555 0100", rxDone?.remote)
|
||||
assertEquals(2, got.size)
|
||||
for (i in pages.indices) {
|
||||
assertEquals(pages[i].rows, got[i].rows)
|
||||
assertArrayEquals("page ${i + 1}", pages[i].bits, got[i].bits)
|
||||
}
|
||||
// T.38 taken (the engine's side told: its modem on UDPTL), or not at all
|
||||
val onT38 = l.log.any { it.startsWith("engine: ") && it.contains("T.38 on") }
|
||||
assertEquals(l.log.filter { it.contains("t38", ignoreCase = true) }.take(30).joinToString("\n"), t38, onT38)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun overT38() = call(t38 = true, ecm = false)
|
||||
|
||||
@Test
|
||||
fun overT38InEcm() = call(t38 = true, ecm = true)
|
||||
|
||||
@Test
|
||||
fun onAudioWithoutT38() = call(t38 = false, ecm = true)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Our fax (its T.30 on a class 1 modem) against another machine's:
|
||||
* D-Modem-RE's own T.30 (dsp/t30.cpp), on the far end of a phone line
|
||||
* from the modem (native-test's t30_line: cmake -S native-test -B
|
||||
* build-host && cmake --build build-host, or DMODEM_T30_LINE; skipped
|
||||
* without it). With error correction mode both ways, on a clean line
|
||||
* and a noisy one (ECM's frames spoilt there sent again), and without.
|
||||
*/
|
||||
class T30InteropTest {
|
||||
|
||||
@get:Rule
|
||||
val tmp = TemporaryFolder()
|
||||
|
||||
private var line: FaxLineProcess? = null
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
line?.close()
|
||||
}
|
||||
|
||||
/** t30_line started: our class 1 modem's DTE */
|
||||
private fun start(vararg args: String): Class1 {
|
||||
val bin = nativeTool("DMODEM_T30_LINE", "t30_line")
|
||||
assumeTrue("t30_line isn't built (native-test)", bin != null)
|
||||
val l = FaxLineProcess(listOf(bin!!.path) + args.toList())
|
||||
line = l
|
||||
val c = l.modem("modemA", "dte")
|
||||
assertEquals("OK", c.command("E0"))
|
||||
return c
|
||||
}
|
||||
|
||||
private fun dump() = line!!.dump()
|
||||
|
||||
/** the machine's RESULT line's fields: ok, pages, bps, ecm */
|
||||
private fun machineResult(): Map<String, String> {
|
||||
val end = System.currentTimeMillis() + 30_000
|
||||
var r: String? = null
|
||||
while (r == null && System.currentTimeMillis() < end) {
|
||||
r = line!!.log.firstOrNull { it.startsWith("RESULT ") }
|
||||
if (r == null) Thread.sleep(50)
|
||||
}
|
||||
if (r == null) throw AssertionError("no RESULT\n${dump()}")
|
||||
val f = r.split(' ')
|
||||
return mapOf("ok" to f[1], "pages" to f[3], "bps" to f[5], "ecm" to f[7], "why" to f.drop(8).joinToString(" "))
|
||||
}
|
||||
|
||||
private fun theyReceive(ecm: Boolean, snr: Double = 0.0) {
|
||||
val dir = tmp.newFolder()
|
||||
val args = mutableListOf("receive", dir.path)
|
||||
if (snr > 0) args += listOf("--snr", snr.toString())
|
||||
val c = start(*args.toTypedArray())
|
||||
assertEquals("OK", c.command("X3+FCLASS=1"))
|
||||
val rates = T30.modemRates(c)
|
||||
val pages = listOf(FaxTestPage.of(true, rows = 600, seed = 1), FaxTestPage.of(true, rows = 300, seed = 2))
|
||||
assertEquals(dump(), "CONNECT", c.command("D", 30_000))
|
||||
val sent = try {
|
||||
T30.send(c, pages, "+1 555 0100", rates, ecm = ecm)
|
||||
} catch (e: Exception) {
|
||||
throw AssertionError("$e\n${dump()}")
|
||||
}
|
||||
val m = machineResult()
|
||||
assertEquals(m.toString(), "1", m["ok"])
|
||||
assertEquals(2, sent.pages)
|
||||
assertEquals(ecm, sent.ecm)
|
||||
assertEquals(if (ecm) "1" else "0", m["ecm"])
|
||||
assertEquals("+1 555 0399", sent.remote)
|
||||
for (i in pages.indices) {
|
||||
val got = Pbm.read(File(dir, "got${i + 1}.pbm"), true)
|
||||
assertEquals(pages[i].rows, got.rows)
|
||||
assertArrayEquals("page ${i + 1}", pages[i].bits, got.bits)
|
||||
}
|
||||
}
|
||||
|
||||
private fun theySend(ecm: Boolean, snr: Double = 0.0): List<FaxPage> {
|
||||
val dir = tmp.newFolder()
|
||||
val args = mutableListOf("send", dir.path)
|
||||
if (snr > 0) args += listOf("--snr", snr.toString())
|
||||
val c = start(*args.toTypedArray())
|
||||
assertEquals("OK", c.command("+FCLASS=1"))
|
||||
val rates = T30.modemRates(c)
|
||||
val got = ArrayList<FaxPage>()
|
||||
// (it calls once the modem is off hook: answered at once)
|
||||
assertEquals(dump(), "CONNECT", c.command("A", 30_000))
|
||||
val rx = try {
|
||||
T30.receive(c, "+1 555 0199", rates, ecm = ecm) { pg, _ -> got.add(pg) }
|
||||
} catch (e: Exception) {
|
||||
throw AssertionError("$e\n${dump()}")
|
||||
}
|
||||
val m = machineResult()
|
||||
assertEquals(m.toString() + "\n" + dump(), "1", m["ok"])
|
||||
assertEquals(ecm, rx.ecm)
|
||||
assertEquals("+1 555 0300", rx.remote)
|
||||
assertEquals(2, got.size)
|
||||
for (i in got.indices) {
|
||||
val sent = Pbm.read(File(dir, "sent${i + 1}.pbm"), true)
|
||||
assertEquals(sent.rows, got[i].rows)
|
||||
assertArrayEquals("page ${i + 1}", sent.bits, got[i].bits)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
@Test
|
||||
fun weSendInEcm() = theyReceive(ecm = true)
|
||||
|
||||
@Test
|
||||
fun weSendWithoutEcm() = theyReceive(ecm = false)
|
||||
|
||||
@Test
|
||||
fun weReceiveInEcm() {
|
||||
theySend(ecm = true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun weReceiveWithoutEcm() {
|
||||
theySend(ecm = false)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun weSendInEcmOnANoisyLine() {
|
||||
theyReceive(ecm = true, snr = 21.0)
|
||||
println("PPRs to us: " + line!!.log.count { it.contains("<- frame ff 13 bc") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun weReceiveInEcmOnANoisyLine() {
|
||||
theySend(ecm = true, snr = 21.0)
|
||||
println("PPRs from us: " + line!!.log.count { it.contains("-> frame ff 13 bc") })
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,22 @@ target_compile_options(fax_line PRIVATE -Wall -Wextra -O2)
|
||||
target_link_libraries(fax_line PRIVATE dmodem_front dmodem_core dmodem_dsp
|
||||
dmodem_link m Threads::Threads)
|
||||
|
||||
# sip_fax_line: the engine and dmodemd on a loopback SIP call with T.38,
|
||||
# each one's DTE a pty: FaxCallTest's fax over T.38
|
||||
add_executable(sip_fax_line sip_fax_line.cpp)
|
||||
target_compile_options(sip_fax_line PRIVATE -Wall -Wextra)
|
||||
target_compile_definitions(sip_fax_line PRIVATE DMODEMD_PATH="$<TARGET_FILE:dmodemd>")
|
||||
target_link_libraries(sip_fax_line PRIVATE dmodem_engine Threads::Threads)
|
||||
add_dependencies(sip_fax_line dmodemd)
|
||||
|
||||
# t30_line: a class 1 modem on a line to D-Modem-RE's own T.30 fax machine
|
||||
# (with or without ECM, noise if asked): FaxCallTest's interop with it
|
||||
add_executable(t30_line t30_line.cpp)
|
||||
target_include_directories(t30_line PRIVATE ${DMODEM_RE_DIR}/dmodemd)
|
||||
target_compile_options(t30_line PRIVATE -Wall -Wextra -O2)
|
||||
target_link_libraries(t30_line PRIVATE dmodem_front dmodem_core dmodem_dsp
|
||||
dmodem_t30 dmodem_link m Threads::Threads)
|
||||
|
||||
# peer_host: the engine on a peer line (two phones' modems through the
|
||||
# app), for the app's PeerLineTest
|
||||
add_executable(peer_host peer_host.cpp)
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*
|
||||
* sip_fax_line.cpp - the app's engine (engine.h) and a dmodemd on a
|
||||
* SIP call over loopback, both with T.38: a fax
|
||||
* call that goes over to T.38 once the answerer
|
||||
* (dmodemd, in fax mode) asks, a second after it
|
||||
* answered. Each modem's DTE a pty, for the app's
|
||||
* fax tests (FaxCallTest) to drive class 1 on.
|
||||
*
|
||||
* sip_fax_line [--no-t38] [<dmodemd>] (the one built with it, else)
|
||||
*
|
||||
* On stderr: "created modemA: <pty>" (the engine's: it dials),
|
||||
* "created modemB: <pty>" (dmodemd's: it answers), then the engine's
|
||||
* log as it comes, "engine: " before each line. It runs until
|
||||
* killed.
|
||||
*/
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/wait.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "engine.h"
|
||||
|
||||
using namespace dmodem_android;
|
||||
|
||||
namespace {
|
||||
|
||||
const int ENGINE_PORT = 5191, DMODEMD_PORT = 5192;
|
||||
|
||||
pid_t dmodemd_pid;
|
||||
|
||||
/* dmodemd on DMODEMD_PORT, its pty's name in *tty */
|
||||
pid_t start_dmodemd(const char *path, bool t38, std::string *tty)
|
||||
{
|
||||
int err[2];
|
||||
pid_t pid;
|
||||
char buf[4096];
|
||||
std::string out;
|
||||
|
||||
if (pipe(err) < 0)
|
||||
return -1;
|
||||
pid = fork();
|
||||
if (pid == 0) {
|
||||
char login[64], port[16];
|
||||
/* (gone with us, however we end) */
|
||||
prctl(PR_SET_PDEATHSIG, SIGTERM);
|
||||
snprintf(login, sizeof(login), "d:x@127.0.0.1:%d", ENGINE_PORT);
|
||||
snprintf(port, sizeof(port), "%d", DMODEMD_PORT);
|
||||
setenv("SIP_LOGIN", login, 1);
|
||||
setenv("SIP_PORT", port, 1);
|
||||
setenv("SIP_LOG_LEVEL", "3", 1);
|
||||
setenv("SIP_T38", t38 ? "yes" : "no", 1);
|
||||
dup2(err[1], 2);
|
||||
close(err[0]);
|
||||
execl(path, path, "-n", "-L", "dmodem72", (char *)nullptr);
|
||||
_exit(127);
|
||||
}
|
||||
close(err[1]);
|
||||
std::smatch m;
|
||||
std::regex re("TTY is `([^']+)'");
|
||||
for (int i = 0; i < 50; i++) {
|
||||
struct pollfd p = { err[0], POLLIN, 0 };
|
||||
if (poll(&p, 1, 200) > 0) {
|
||||
ssize_t n = read(err[0], buf, sizeof(buf));
|
||||
if (n <= 0)
|
||||
break;
|
||||
out.append(buf, n);
|
||||
if (std::regex_search(out, m, re))
|
||||
break;
|
||||
}
|
||||
}
|
||||
/* (its log on from now on, "dmodemd: " before it) */
|
||||
std::thread([fd = err[0]] {
|
||||
char b[4096];
|
||||
ssize_t n;
|
||||
while ((n = read(fd, b, sizeof(b))) > 0)
|
||||
if (write(2, b, n) < 0)
|
||||
break;
|
||||
close(fd);
|
||||
}).detach();
|
||||
if (m.empty())
|
||||
return -1;
|
||||
*tty = m[1].str();
|
||||
return pid;
|
||||
}
|
||||
|
||||
/* a and b joined until either ends */
|
||||
void relay(int a, int b)
|
||||
{
|
||||
char buf[8192];
|
||||
struct pollfd p[2] = { { a, POLLIN, 0 }, { b, POLLIN, 0 } };
|
||||
for (;;) {
|
||||
if (poll(p, 2, -1) < 0)
|
||||
break;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (!(p[i].revents & (POLLIN | POLLHUP | POLLERR)))
|
||||
continue;
|
||||
ssize_t n = read(p[i].fd, buf, sizeof(buf));
|
||||
/* (a pty with nobody on it: EIO until it's opened) */
|
||||
if (n <= 0) {
|
||||
if (i == 0)
|
||||
usleep(20000);
|
||||
else
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
for (ssize_t o = 0; o < n;) {
|
||||
ssize_t w = write(p[1 - i].fd, buf + o, n - o);
|
||||
if (w <= 0)
|
||||
return;
|
||||
o += w;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void on_signal(int)
|
||||
{
|
||||
if (dmodemd_pid > 0)
|
||||
kill(dmodemd_pid, SIGTERM);
|
||||
_exit(0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
bool t38 = true;
|
||||
const char *dmodemd = DMODEMD_PATH;
|
||||
std::string tty;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--no-t38"))
|
||||
t38 = false;
|
||||
else
|
||||
dmodemd = argv[i];
|
||||
}
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
signal(SIGTERM, on_signal);
|
||||
signal(SIGINT, on_signal);
|
||||
dmodemd_pid = start_dmodemd(dmodemd, t38, &tty);
|
||||
if (dmodemd_pid < 0) {
|
||||
fprintf(stderr, "dmodemd didn't start\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
Engine &e = Engine::instance();
|
||||
e.set_log([](const char *line) { fprintf(stderr, "engine: %s", line); });
|
||||
Config c;
|
||||
c.user = "e";
|
||||
c.password = "x";
|
||||
c.domain = "127.0.0.1:" + std::to_string(DMODEMD_PORT);
|
||||
c.sip_port = ENGINE_PORT;
|
||||
c.listen = false;
|
||||
c.dns = "127.0.0.1";
|
||||
c.t38 = t38;
|
||||
c.log_level = 1;
|
||||
c.sip_log_level = 3;
|
||||
int dte = e.start(c, [](const Status &) {}, [](int r) {
|
||||
fprintf(stderr, "engine: exit %d\n", r);
|
||||
});
|
||||
if (dte < 0) {
|
||||
fprintf(stderr, "the engine didn't start\n");
|
||||
on_signal(0);
|
||||
}
|
||||
/* the engine's DTE on a pty of its own */
|
||||
int master = posix_openpt(O_RDWR | O_NOCTTY);
|
||||
if (master < 0 || grantpt(master) < 0 || unlockpt(master) < 0) {
|
||||
perror("pty");
|
||||
on_signal(0);
|
||||
}
|
||||
struct termios t;
|
||||
int slave = open(ptsname(master), O_RDWR | O_NOCTTY);
|
||||
tcgetattr(slave, &t);
|
||||
cfmakeraw(&t);
|
||||
tcsetattr(slave, TCSANOW, &t);
|
||||
fprintf(stderr, "created modemA: %s\ncreated modemB: %s\n", ptsname(master), tty.c_str());
|
||||
fflush(stderr);
|
||||
relay(master, dte);
|
||||
close(slave);
|
||||
on_signal(0);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright (C) 2026 Neo-Desktop
|
||||
*
|
||||
* t30_line.cpp - a class 1 modem (D-Modem-RE's PipeModem, a pty for
|
||||
* its DTE) on a phone line to D-Modem-RE's own T.30
|
||||
* fax machine (dsp/t30.cpp), with or without error
|
||||
* correction mode, noise on the line if asked: the
|
||||
* app's fax (its T.30 on the DTE) against another
|
||||
* machine's (FaxCallTest).
|
||||
*
|
||||
* t30_line send|receive <dir> [--no-ecm] [--snr <dB>] [--bps <max>]
|
||||
* send: the machine calls and sends two pages, written first
|
||||
* as <dir>/sent1.pbm and sent2.pbm; the DTE answers (ATA)
|
||||
* receive: the machine answers and receives, each page as
|
||||
* <dir>/got<n>.pbm; the DTE dials (ATD)
|
||||
*
|
||||
* On stderr "created modemA: <pty>", the log; on stdout, the call
|
||||
* over: "RESULT <ok 1|0> pages <n> bps <rate> ecm <1|0> <why>".
|
||||
*/
|
||||
|
||||
#include <math.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <dsplibs.h>
|
||||
#include <log.h>
|
||||
#include <t30.h>
|
||||
#include <t4.h>
|
||||
|
||||
#include "options.h"
|
||||
#include "pipe_modem.h"
|
||||
|
||||
using namespace dsp;
|
||||
|
||||
namespace {
|
||||
|
||||
const int FRAME = 160;
|
||||
const int WIDTH = 1728;
|
||||
|
||||
std::string dir;
|
||||
int pages_sent = 0;
|
||||
int pages_got = 0;
|
||||
|
||||
/* a page as PBM (P4: rows of 1 = black, the first pel in the top bit) */
|
||||
void write_pbm(const std::string &path, const T4Page *p)
|
||||
{
|
||||
FILE *f = fopen(path.c_str(), "wb");
|
||||
if (!f)
|
||||
return;
|
||||
fprintf(f, "P4\n%d %d\n", p->width, p->rows);
|
||||
fwrite(p->bits, T4_STRIDE(p->width), p->rows, f);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
/* the machine's pages: bars, a frame, and noise (big in MH: blocks) */
|
||||
int next_page(void *, T4Page *p)
|
||||
{
|
||||
if (pages_sent == 2)
|
||||
return 0;
|
||||
int n = ++pages_sent;
|
||||
int rows = n == 1 ? 900 : 400;
|
||||
std::mt19937 r(n);
|
||||
unsigned char row[WIDTH / 8];
|
||||
if (p->init(WIDTH, 1) < 0)
|
||||
return 0;
|
||||
for (int y = 0; y < rows; y++) {
|
||||
memset(row, 0, sizeof(row));
|
||||
for (int x = 0; x < WIDTH; x++) {
|
||||
bool on;
|
||||
if (x < 4 || x >= WIDTH - 4 || y < 4 || y >= rows - 4)
|
||||
on = true;
|
||||
else if (y < 200)
|
||||
on = (x / (y % 9 + 1)) % 2 == 0;
|
||||
else if (n == 1 && y < 700)
|
||||
on = (r() & 3) == 0;
|
||||
else
|
||||
on = (x / 6 + y / 10) % 7 == 0;
|
||||
if (on)
|
||||
row[x >> 3] |= 0x80 >> (x & 7);
|
||||
}
|
||||
p->add_row(row);
|
||||
}
|
||||
write_pbm(dir + "/sent" + std::to_string(n) + ".pbm", p);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void page_received(void *, T4Page *p)
|
||||
{
|
||||
write_pbm(dir + "/got" + std::to_string(++pages_got) + ".pbm", p);
|
||||
}
|
||||
|
||||
/* the machine on the line: each of the modem's samples answered with
|
||||
one of its own (noise added both ways), until the call is over */
|
||||
void machine(int in, int out, struct t30_config cfg, double snr)
|
||||
{
|
||||
T30 *t = t30_create(&cfg);
|
||||
short a[FRAME], b[FRAME];
|
||||
double sigma = snr > 0 ? 3000 / pow(10, snr / 20) : 0;
|
||||
std::mt19937 r(5);
|
||||
std::normal_distribution<double> g(0, 1);
|
||||
struct t30_status s = {};
|
||||
size_t have = 0;
|
||||
for (;;) {
|
||||
ssize_t n = read(in, (char *)a + have, sizeof(a) - have);
|
||||
if (n <= 0)
|
||||
break;
|
||||
have += n;
|
||||
int count = (int)(have / 2);
|
||||
if (count == 0)
|
||||
continue;
|
||||
for (int i = 0; i < count && sigma > 0; i++)
|
||||
a[i] = (short)fmax(-32768, fmin(32767, a[i] + sigma * g(r)));
|
||||
t30_process(t, a, b, count);
|
||||
for (int i = 0; i < count && sigma > 0; i++)
|
||||
b[i] = (short)fmax(-32768, fmin(32767, b[i] + sigma * g(r)));
|
||||
if (write(out, b, 2 * count) != 2 * count)
|
||||
break;
|
||||
/* (an odd octet kept for the next) */
|
||||
if (have & 1)
|
||||
((char *)a)[0] = ((char *)a)[have - 1];
|
||||
have &= 1;
|
||||
t30_get_status(t, &s);
|
||||
if (s.done)
|
||||
break;
|
||||
}
|
||||
t30_get_status(t, &s);
|
||||
printf("RESULT %d pages %d bps %d ecm %d %s\n",
|
||||
s.result == T30_OK || s.complete, s.pages, s.bps, s.ecm,
|
||||
t30_result_text(s.result));
|
||||
fflush(stdout);
|
||||
t30_free(t);
|
||||
/* (the modem stays on the line a while: the DTE sees the end) */
|
||||
sleep(2);
|
||||
dmd::PipeModem::stop();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
dmd::Options opt;
|
||||
int to_modem[2], from_modem[2], ret;
|
||||
struct t30_config cfg = {};
|
||||
double snr = 0;
|
||||
|
||||
if (argc < 3 || (strcmp(argv[1], "send") && strcmp(argv[1], "receive"))) {
|
||||
fprintf(stderr, "t30_line send|receive <dir> [--no-ecm] [--snr <dB>] [--bps <max>]\n");
|
||||
return 2;
|
||||
}
|
||||
dir = argv[2];
|
||||
cfg.sending = !strcmp(argv[1], "send");
|
||||
cfg.ident = cfg.sending ? "+1 555 0300" : "+1 555 0399";
|
||||
cfg.ecm = 1;
|
||||
cfg.max_bps = 14400;
|
||||
cfg.srate = 8000;
|
||||
cfg.next_page = next_page;
|
||||
cfg.page_received = page_received;
|
||||
for (int i = 3; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--no-ecm"))
|
||||
cfg.ecm = 0;
|
||||
else if (!strcmp(argv[i], "--snr") && i + 1 < argc)
|
||||
snr = atof(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--bps") && i + 1 < argc)
|
||||
cfg.max_bps = atoi(argv[++i]);
|
||||
}
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
dcore::log_level = getenv("T30_LINE_LOG") ? atoi(getenv("T30_LINE_LOG")) : 1;
|
||||
if (getenv("DSP_DEBUG"))
|
||||
dsplibs_debug_level = atoi(getenv("DSP_DEBUG"));
|
||||
char *args[] = { argv[0], nullptr };
|
||||
dmd::parse_options(1, args, opt);
|
||||
dcore::log_open("test");
|
||||
prop_dp_init();
|
||||
if (pipe(to_modem) < 0 || pipe(from_modem) < 0) {
|
||||
perror("pipe");
|
||||
return 1;
|
||||
}
|
||||
std::thread(machine, from_modem[0], to_modem[1], cfg, snr).detach();
|
||||
dmd::PipeModem a("modemA", 8000, opt.country, to_modem[0], from_modem[1]);
|
||||
a.set_realtime(!getenv("MODEM_REALTIME") || atoi(getenv("MODEM_REALTIME")));
|
||||
fprintf(stderr, "created modemA: %s\n", a.pty().name());
|
||||
dmd::PipeModem *modems[] = { &a };
|
||||
ret = dmd::PipeModem::run(modems, 1);
|
||||
prop_dp_exit();
|
||||
dcore::log_close();
|
||||
return ret;
|
||||
}
|
||||
Reference in new issue
Block a user