Fax: T.30 and T.4 on the modem's class 1

The fax machine's side in the app, over the modem's class 1 commands
(T.31): T.4's MH coding of the pages, T.30's procedure (DIS/DCS, the
training and its fallback to lower rates, the pages with MPS/EOP and
their MCF/RTN/RTP, DCN), V.17 to V.27ter as the modem has them.
Tested on D-Modem's own modems back to back (native-test's fax_line,
modem_test paced as a phone line): our sender to our receiver, efax
sending to us and receiving from us, the pages exact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
Claude committed 2026-10-17 00:38:49 +00:00
1 parent 0d93f44999
commit 147736235c
7 files changed
+1277

No files matched your search

@@ -0,0 +1,171 @@
// 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.ByteArrayOutputStream
import java.io.IOException
/**
* A class 1 fax modem (T.31) from its DTE: AT commands and their
* results; HDLC frames (V.21, +FTH=3/+FRH=3) and fast data (+FTM/+FRM)
* as <DLE> shielded octets ending in <DLE><ETX>.
*/
class Class1(private val io: TransferIo, private val log: (String) -> Unit = {}) {
/** a frame received: address, control, FCF and its FIF (the FCS off); [ok]: its FCS was good */
class Frame(val bytes: ByteArray, val ok: Boolean) {
val fcf: Int get() = if (bytes.size >= 3) bytes[2].toInt() and 0xff else -1
val final: Boolean get() = bytes.size >= 2 && (bytes[1].toInt() and 0x10) != 0
val fif: ByteArray get() = if (bytes.size > 3) bytes.copyOfRange(3, bytes.size) else ByteArray(0)
}
/** a line from the modem, its CR LF off; null when none came in [ms] */
fun line(ms: Long): String? {
val sb = StringBuilder()
val end = System.currentTimeMillis() + ms
while (true) {
val left = end - System.currentTimeMillis()
if (left <= 0) return null
val c = io.read(left)
if (c < 0) return null
when (c) {
'\n'.code -> if (sb.isNotEmpty()) return sb.toString().also { log("<- $it") }
'\r'.code -> {}
else -> sb.append(c.toChar())
}
}
}
/** a command (without its AT): its result line (OK, CONNECT, ERROR, NO CARRIER, +FCERROR, …), null on a timeout */
fun command(cmd: String, ms: Long = 5000): String? {
log("-> AT$cmd")
io.write("AT$cmd\r".toByteArray())
return result(ms)
}
/** the next result line (the command's echo, and anything else that isn't one, passed over) */
fun result(ms: Long): String? {
val end = System.currentTimeMillis() + ms
while (true) {
val l = line(end - System.currentTimeMillis()) ?: return null
if (l.startsWith("AT", ignoreCase = true)) continue
if (l in RESULTS || l.startsWith("CONNECT") || l.startsWith("+F") && !l.startsWith("+FTM:")) return l
lastInfo = l
}
}
/** the last line that was not a result (AT+FTM=?'s list, say) */
var lastInfo: String? = null
private set
/** octets out, <DLE> doubled, <DLE><ETX> after */
fun sendData(data: ByteArray, end: Boolean = true) {
val o = ByteArrayOutputStream(data.size + data.size / 64 + 4)
for (b in data) {
o.write(b.toInt())
if (b == DLE.toByte()) o.write(DLE)
}
if (end) { o.write(DLE); o.write(ETX) }
io.write(o.toByteArray())
}
/**
* <DLE> shielded octets in until <DLE><ETX>: the octets; null on a
* timeout of [ms] with nothing coming
*/
fun readData(ms: Long, max: Int = 4 * 1024 * 1024): ByteArray? {
val o = ByteArrayOutputStream()
var dle = false
while (true) {
val c = io.read(ms)
if (c < 0) return null
if (dle) {
dle = false
when (c) {
ETX -> return o.toByteArray()
DLE -> o.write(DLE)
// (<DLE><SUB>: two <DLE>s, T.31's; others dropped)
SUB -> { o.write(DLE); o.write(DLE) }
}
} else if (c == DLE) {
dle = true
} else {
o.write(c)
}
if (o.size() > max) throw IOException("too much data")
}
}
/** frames out (+FTH=3 given, its CONNECT seen, or after ATA): each in turn, the last final; true when the modem took them */
fun sendFrames(frames: List<ByteArray>, ms: Long = 10_000): Boolean {
for ((i, f) in frames.withIndex()) {
val last = i == frames.lastIndex
val b = f.copyOf()
b[1] = (if (last) CTRL_FINAL else CTRL) .toByte()
log("-> frame ${hex(b)}")
sendData(b)
val r = result(ms)
if (r != (if (last) "OK" else "CONNECT")) {
log("frame not sent: $r")
return false
}
}
return true
}
/** +FTH=3 and the frames */
fun transmitFrames(frames: List<ByteArray>): Boolean {
val r = command("+FTH=3", 10_000)
if (r != "CONNECT") return false
return sendFrames(frames)
}
/**
* a frame in (+FRH=3 given and its CONNECT seen, or after ATD): its
* octets and whether OK followed; null when the data didn't come
*/
fun readFrame(ms: Long = 10_000): Frame? {
val d = readData(ms) ?: return null
val r = result(3000)
val ok = r == "OK"
// (the two FCS octets the modem passes with it)
val body = if (d.size >= 2) d.copyOf(d.size - 2) else d
log("<- frame ${hex(body)} ${if (ok) "" else "(bad: $r)"}")
return Frame(body, ok)
}
/** +FRH=3 and the frame it gets: null for none (NO CARRIER, +FCERROR, a timeout: the command stopped) */
fun receiveFrame(ms: Long = T2_MS): Frame? {
val r = command("+FRH=3", ms)
if (r == null) {
abort()
return null
}
if (r != "CONNECT") return null
return readFrame()
}
/** a command waiting (+FRH, +FRM) stopped: any character, then its OK */
fun abort() {
io.write(byteArrayOf(CAN.toByte()))
result(2000)
}
companion object {
const val DLE = 0x10
const val ETX = 0x03
const val SUB = 0x1a
const val CAN = 0x18
const val ADDR = 0xff
const val CTRL = 0x03
const val CTRL_FINAL = 0x13
const val T2_MS = 6000L
val RESULTS = setOf("OK", "ERROR", "NO CARRIER", "NO DIALTONE", "NO DIAL TONE", "BUSY", "NO ANSWER", "RING", "FCERROR")
fun hex(b: ByteArray) = b.joinToString(" ") { "%02x".format(it) }
/** a frame: address, control (set when sent), FCF, FIF */
fun frame(fcf: Int, fif: ByteArray = ByteArray(0)) = byteArrayOf(ADDR.toByte(), CTRL.toByte(), fcf.toByte()) + fif
}
}
@@ -0,0 +1,406 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.fax
import java.io.IOException
/** how a fax call went, as it goes */
data class FaxProgress(
val phase: String = "",
/** pages done (sent and confirmed, or received) */
val pages: Int = 0,
val total: Int = 0,
val bps: Int = 0,
val fine: Boolean = false,
/** the other machine's identity (its CSI or TSI) */
val remote: String = "",
)
/** a fax call that didn't work: why */
class FaxException(msg: String) : IOException(msg)
/**
* The T.30 procedure for group 3 fax on a class 1 modem ([Class1]): the
* calling machine sends (no polling), the answering one receives, in
* MH coding, without error correction mode. The frames' octets as the
* class 1 modem has them (the first bit on the line at the bottom).
*/
object T30 {
// the FCFs: the calling machine's (after a DIS) have X, the bottom bit, set
const val DIS = 0x80
const val CSI = 0x40
const val NSF = 0x20
const val DCS = 0x82
const val TSI = 0x42
const val CFR = 0x84
const val FTT = 0x44
const val EOM = 0x8e
const val MPS = 0x4e
const val EOP = 0x2e
const val MCF = 0x8c
const val RTP = 0xcc
const val RTN = 0x4c
const val DCN = 0xfa
const val CRP = 0x1a
const val X = 0x01
/** a rate: its DCS code (bits 11-14), its modulation's class 1 codes (long training, and for the pages) */
data class Rate(val bps: Int, val code: Int, val family: Int, val trainMod: Int, val pageMod: Int)
val RATES = listOf(
Rate(14400, 0x8, 2, 145, 146), Rate(12000, 0xa, 2, 121, 122),
Rate(9600, 0x9, 2, 97, 98), Rate(7200, 0xb, 2, 73, 74),
Rate(9600, 0x1, 1, 96, 96), Rate(7200, 0x3, 1, 72, 72),
Rate(4800, 0x2, 0, 48, 48), Rate(2400, 0x0, 0, 24, 24),
)
fun bit(fif: ByteArray, n: Int): Boolean = (n - 1) / 8 < fif.size && (fif[(n - 1) / 8].toInt() shr ((n - 1) % 8)) and 1 == 1
fun setBit(fif: ByteArray, n: Int) {
fif[(n - 1) / 8] = (fif[(n - 1) / 8].toInt() or (1 shl ((n - 1) % 8))).toByte()
}
private fun rateBits(fif: ByteArray) =
(if (bit(fif, 11)) 1 else 0) or (if (bit(fif, 12)) 2 else 0) or (if (bit(fif, 13)) 4 else 0) or (if (bit(fif, 14)) 8 else 0)
/** the rates a DIS offers */
fun disOffers(fif: ByteArray, r: Rate): Boolean {
val v = rateBits(fif)
return when (r.family) {
2 -> v == 0xb || v == 0xf || (v and 0x8) != 0
1 -> v and 0x1 != 0
else -> r.bps == 2400 || v and 0x2 != 0
}
}
/** the minimum scan line time a DIS asks for (ms) */
fun disMinMs(fif: ByteArray): Int {
val ms = intArrayOf(20, 40, 10, 10, 5, 40, 20, 0)
val c = (if (bit(fif, 21)) 4 else 0) or (if (bit(fif, 22)) 2 else 0) or (if (bit(fif, 23)) 1 else 0)
return ms[c]
}
/** our DIS: a receiver of MH, the [rates], fine, A4, 5 ms minimum scan time */
fun dis(rates: List<Rate>): ByteArray {
val f = ByteArray(3)
setBit(f, 10)
// (V.17 in a DIS is V.17 up to 14400: offered only when that is)
val v17 = rates.any { it.family == 2 && it.bps == 14400 }
val v29 = rates.any { it.family == 1 }
val code = if (v17) 0xb else if (v29) 0x3 else 0x2
if (code and 1 != 0) setBit(f, 11)
if (code and 2 != 0) setBit(f, 12)
if (code and 4 != 0) setBit(f, 13)
if (code and 8 != 0) setBit(f, 14)
setBit(f, 15)
// minimum scan time 5 ms (none would do for us; efax divides by it, crashing on 0)
setBit(f, 21)
return f
}
/** a DCS: the rate, fine or not, the minimum scan time agreed */
fun dcs(r: Rate, fine: Boolean, minMs: Int): ByteArray {
val f = ByteArray(3)
setBit(f, 10)
if (r.code and 1 != 0) setBit(f, 11)
if (r.code and 2 != 0) setBit(f, 12)
if (r.code and 4 != 0) setBit(f, 13)
if (r.code and 8 != 0) setBit(f, 14)
if (fine) setBit(f, 15)
when (minMs) {
40 -> setBit(f, 23)
10 -> setBit(f, 22)
5 -> setBit(f, 21)
0 -> { setBit(f, 21); setBit(f, 22); setBit(f, 23) }
}
return f
}
/** the rate a DCS says, among [RATES] */
fun dcsRate(fif: ByteArray): Rate? {
val v = rateBits(fif)
return RATES.firstOrNull { it.code == v }
}
/** a DCS's minimum scan time (ms) */
fun dcsMinMs(fif: ByteArray): Int {
val c = (if (bit(fif, 21)) 4 else 0) or (if (bit(fif, 22)) 2 else 0) or (if (bit(fif, 23)) 1 else 0)
return when (c) { 1 -> 40; 2 -> 10; 4 -> 5; 7 -> 0; else -> 20 }
}
/** a CSI or TSI's 20 characters: the last first */
fun ident(id: String): ByteArray {
val s = id.filter { it.isDigit() || it == '+' || it == ' ' }.take(20)
return ByteArray(20) { k -> if (k < s.length) s[s.length - 1 - k].code.toByte() else ' '.code.toByte() }
}
fun readIdent(fif: ByteArray): String =
fif.take(20).reversed().map { b -> val c = b.toInt() and 0xff; if (c in 32..126) c.toChar() else ' ' }.joinToString("").trim()
/** the rates the modem has (AT+FTM=?'s list, in fax mode, before a call), up to [maxBps] */
fun modemRates(c: Class1, maxBps: Int = 14400): List<Rate> {
val r = c.command("+FTM=?")
val list = c.lastInfo?.split(',')?.mapNotNull { it.trim().toIntOrNull() }?.toSet().orEmpty()
val all = if (r != "OK" || list.isEmpty()) RATES.filter { it.family < 2 } else RATES.filter { it.trainMod in list && it.pageMod in list }
return all.filter { it.bps <= maxBps }.ifEmpty { RATES.filter { it.bps <= 2400 } }
}
// ------------------------------------------------------------------
/** a training check's (TCF's) octets: 1.5 s of zeros at the rate */
fun tcf(bps: Int) = ByteArray(bps * 3 / 2 / 8)
/** a TCF that came good: most of it, zeros most of the time */
fun tcfGood(d: ByteArray, bps: Int): Boolean {
val want = bps * 3 / 2 / 8
if (d.size < want / 2) return false
// (its start and end let go: the carrier settling, and stopping)
val mid = d.copyOfRange(d.size / 8, d.size - d.size / 8)
val zeros = mid.count { it.toInt() == 0 }
return zeros >= mid.size * 9 / 10
}
// ------------------------------------------------------------------
// sending
/**
* [pages] sent on a call the modem has dialled (its CONNECT seen: it
* is receiving the answerer's frames): DIS, then DCS and training at
* the best rate both have (lower ones if it fails), each page with
* its MPS or EOP and the answer to it
*/
fun send(
c: Class1,
pages: List<FaxPage>,
ident: String,
/** the modem's rates ([modemRates], asked before the call: not during it) */
have: List<Rate>,
progress: (FaxProgress) -> Unit = {},
): FaxProgress {
if (pages.isEmpty()) throw FaxException("no pages")
var p = FaxProgress("Waiting for the fax machine", total = pages.size)
progress(p)
// phase B: the answerer's frames, up to its DIS (as the modem got them since its CONNECT)
var dis: ByteArray? = null
var remote = ""
var first = true
val t1 = System.currentTimeMillis() + 35_000
while (dis == null && System.currentTimeMillis() < t1) {
val f = if (first) c.readFrame(10_000) else c.receiveFrame()
first = false
if (f == null) continue
if (!f.ok) continue
when (f.fcf and X.inv()) {
CSI -> remote = readIdent(f.fif)
DIS -> dis = f.fif
DCN -> throw FaxException("the fax machine hung up")
}
}
val d = dis ?: throw FaxException("no fax machine answered")
val rates = have.filter { disOffers(d, it) }
if (rates.isEmpty()) throw FaxException("no rate in common with the fax machine")
val fine = pages.first().fine && bit(d, 15)
val minMs = disMinMs(d)
p = p.copy(remote = remote, fine = fine)
// training: down the rates until one takes
var ri = 0
fun train(): Rate {
var tries = 0
while (ri < rates.size) {
val r = rates[ri]
p = p.copy(phase = "Training at ${r.bps} bit/s", bps = r.bps)
progress(p)
c.command("+FTS=8")
if (!c.transmitFrames(listOf(Class1.frame(TSI or X, ident(ident)), Class1.frame(DCS or X, dcs(r, fine, minMs))))) {
throw FaxException("the modem didn't send the DCS")
}
c.command("+FTS=8")
if (c.command("+FTM=${r.trainMod}", 10_000) != "CONNECT") throw FaxException("the modem didn't train")
c.sendData(tcf(r.bps))
if (c.result(10_000) != "OK") throw FaxException("the training didn't go out")
val f = c.receiveFrame(4_000)
when (f?.fcf?.and(X.inv())) {
CFR -> return r
FTT -> { ri++; tries = 0 }
DCN -> throw FaxException("the fax machine hung up")
// (no answer: the same again, then a lower rate)
else -> if (++tries >= 3) { ri++; tries = 0 }
}
}
throw FaxException("the training failed at every rate")
}
var rate = train()
var i = 0
var resent = 0
while (i < pages.size) {
val page = pages[i]
p = p.copy(phase = "Sending page ${i + 1} of ${pages.size}", bps = rate.bps)
progress(p)
val data = T4.encode(page, rate.bps * minMs / 1000)
if (c.command("+FTM=${rate.pageMod}", 10_000) != "CONNECT") throw FaxException("the modem didn't send the page")
c.sendData(data)
if (c.result(120_000) != "OK") throw FaxException("the page didn't go out")
val post = if (i == pages.lastIndex) EOP else MPS
var answer: Int? = null
for (attempt in 0 until 3) {
c.command("+FTS=8")
if (!c.transmitFrames(listOf(Class1.frame(post or X)))) throw FaxException("the modem didn't send the end of the page")
val f = c.receiveFrame(4_000) ?: continue
if (!f.ok) continue
answer = f.fcf and X.inv()
break
}
when (answer) {
MCF, RTP -> {
i++
resent = 0
p = p.copy(pages = i)
progress(p)
// (RTP: good, but train again for the next)
if (answer == RTP && i < pages.size) rate = train()
}
RTN -> {
// not good: trained again (lower if that fails), the page again
if (++resent > 2) throw FaxException("page ${i + 1} wasn't received after three tries")
rate = train()
}
DCN -> throw FaxException("the fax machine hung up after page ${i + 1}")
null -> throw FaxException("no answer to page ${i + 1}")
else -> throw FaxException("the fax machine answered page ${i + 1} with %02x".format(answer))
}
}
// phase E
c.command("+FTS=8")
c.transmitFrames(listOf(Class1.frame(DCN or X)))
p = p.copy(phase = "Sent")
progress(p)
return p
}
// ------------------------------------------------------------------
// receiving
/**
* a fax received on a call the modem has answered (its CONNECT seen:
* it is sending frames): CSI and DIS, the sender's DCS and training,
* each page ([page] as it comes) and its MCF, until EOP and DCN
*/
fun receive(
c: Class1,
ident: String,
/** the modem's rates ([modemRates], asked before the call) */
have: List<Rate>,
progress: (FaxProgress) -> Unit = {},
page: (FaxPage, Int) -> Unit,
): FaxProgress {
var p = FaxProgress("Answering")
progress(p)
val ours = listOf(Class1.frame(CSI, ident(ident)), Class1.frame(DIS, dis(have)))
var pages = 0
var firstDis = true
// phase B (again after an EOM): DIS until a DCS and a good training
outer@ while (true) {
var dcs: ByteArray? = null
var tries = 0
while (dcs == null) {
if (++tries > 4) throw FaxException(if (pages == 0) "no fax came" else "the sender stopped")
val sent = if (firstDis) c.sendFrames(ours) else c.transmitFrames(ours)
firstDis = false
if (!sent) throw FaxException("the modem didn't send the DIS")
// the sender's frames, to its final one
while (true) {
val f = c.receiveFrame() ?: break
if (!f.ok) continue
when (f.fcf and X.inv()) {
TSI -> p = p.copy(remote = readIdent(f.fif))
DCS -> dcs = f.fif
DCN -> if (pages > 0) return p.copy(phase = "Received") else throw FaxException("the sender hung up")
}
if (f.final) break
}
}
// its training, its pages
var d = dcs!!
while (true) {
val rate = dcsRate(d) ?: throw FaxException("the sender asked for an unknown rate")
val fine = bit(d, 15)
p = p.copy(phase = "Training at ${rate.bps} bit/s", bps = rate.bps, fine = fine)
progress(p)
val r = c.command("+FRM=${rate.trainMod}", 10_000)
val good = if (r == "CONNECT") {
val t = c.readData(5_000) ?: ByteArray(0)
c.result(3000)
tcfGood(t, rate.bps)
} else {
false
}
if (!good) {
if (r == "+FCERROR") {
// (frames, not the training: a DCS again, say)
val f = c.receiveFrame()
if (f != null && f.fcf and X.inv() == DCS) { d = f.fif; continue }
}
c.transmitFrames(listOf(Class1.frame(FTT)))
val f = c.receiveFrame()
if (f != null && f.ok && f.fcf and X.inv() == DCS) { d = f.fif; continue }
continue@outer
}
c.transmitFrames(listOf(Class1.frame(CFR)))
// the pages at this rate
while (true) {
p = p.copy(phase = "Receiving page ${pages + 1}")
progress(p)
val m = c.command("+FRM=${rate.pageMod}", 15_000)
if (m == "+FCERROR") {
// the sender didn't hear the CFR: its DCS again
val f = c.receiveFrame()
if (f != null && f.fcf and X.inv() == DCS) { d = f.fif; break }
throw FaxException("the page didn't come")
}
if (m != "CONNECT") throw FaxException("the page didn't come ($m)")
val data = c.readData(30_000) ?: throw FaxException("the page stopped coming")
c.result(3000)
val got = T4.decode(data, FaxPage.WIDTH, fine)
// the post-message command (MPS, EOP, EOM)
var post: Int? = null
for (attempt in 0 until 3) {
val f = c.receiveFrame() ?: continue
if (!f.ok) continue
post = f.fcf and X.inv()
break
}
val okPage = got.page.rows > 0 && got.badRows * 10 < got.page.rows.coerceAtLeast(1)
if (post == null) throw FaxException("no end to page ${pages + 1}")
if (okPage) {
pages++
page(got.page, pages)
p = p.copy(pages = pages)
progress(p)
}
c.command("+FTS=8")
c.transmitFrames(listOf(Class1.frame(if (okPage) MCF else RTN)))
if (!okPage) {
// (it trains again: its DCS)
val f = c.receiveFrame()
if (f != null && f.fcf and X.inv() == DCS) { d = f.fif; break }
throw FaxException("page ${pages + 1} was bad and wasn't sent again")
}
when (post) {
MPS -> continue
EOM -> continue@outer
EOP -> {
// its DCN
c.receiveFrame()
return p.copy(phase = "Received")
}
else -> throw FaxException("the sender ended page $pages with %02x".format(post))
}
}
}
}
}
}
@@ -0,0 +1,280 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.fax
import java.io.ByteArrayOutputStream
/**
* A fax page: [rows] rows of [width] pels, 1 = black, packed eight to a
* byte with the first pel in the top bit; [fine]: 196 lines per inch
* (else 98), always 204 pels per inch across.
*/
class FaxPage(val width: Int, val rows: Int, val fine: Boolean, val bits: ByteArray = ByteArray(width / 8 * rows)) {
val stride: Int get() = width / 8
fun black(x: Int, y: Int): Boolean = (bits[y * stride + x / 8].toInt() shr (7 - x % 8)) and 1 == 1
fun set(x: Int, y: Int, on: Boolean) {
val i = y * stride + x / 8
val m = 0x80 shr (x % 8)
bits[i] = (if (on) bits[i].toInt() or m else bits[i].toInt() and m.inv()).toByte()
}
companion object {
const val WIDTH = 1728
/** A4's rows (297 mm) */
fun a4Rows(fine: Boolean) = if (fine) 2287 else 1143
}
}
/**
* T.4's one-dimensional coding (Modified Huffman), as fax sends a page:
* an EOL before each row, each row's runs (white first) in the code
* tables, fill before the EOLs for a receiver's minimum scan line time,
* RTC (six EOLs) at the end. The bits as the line carries them: the
* first one in the bottom bit of a byte (as a class 1 modem takes them).
*/
object T4 {
private class Code(val run: Int, val bits: String)
private val WHITE = codes(
"0:00110101 1:000111 2:0111 3:1000 4:1011 5:1100 6:1110 7:1111 8:10011 9:10100 10:00111 11:01000 " +
"12:001000 13:000011 14:110100 15:110101 16:101010 17:101011 18:0100111 19:0001100 20:0001000 " +
"21:0010111 22:0000011 23:0000100 24:0101000 25:0101011 26:0010011 27:0100100 28:0011000 " +
"29:00000010 30:00000011 31:00011010 32:00011011 33:00010010 34:00010011 35:00010100 36:00010101 " +
"37:00010110 38:00010111 39:00101000 40:00101001 41:00101010 42:00101011 43:00101100 44:00101101 " +
"45:00000100 46:00000101 47:00001010 48:00001011 49:01010010 50:01010011 51:01010100 52:01010101 " +
"53:00100100 54:00100101 55:01011000 56:01011001 57:01011010 58:01011011 59:01001010 60:01001011 " +
"61:00110010 62:00110011 63:00110100 " +
"64:11011 128:10010 192:010111 256:0110111 320:00110110 384:00110111 448:01100100 512:01100101 " +
"576:01101000 640:01100111 704:011001100 768:011001101 832:011010010 896:011010011 960:011010100 " +
"1024:011010101 1088:011010110 1152:011010111 1216:011011000 1280:011011001 1344:011011010 " +
"1408:011011011 1472:010011000 1536:010011001 1600:010011010 1664:011000 1728:010011011",
)
private val BLACK = codes(
"0:0000110111 1:010 2:11 3:10 4:011 5:0011 6:0010 7:00011 8:000101 9:000100 10:0000100 11:0000101 " +
"12:0000111 13:00000100 14:00000111 15:000011000 16:0000010111 17:0000011000 18:0000001000 " +
"19:00001100111 20:00001101000 21:00001101100 22:00000110111 23:00000101000 24:00000010111 " +
"25:00000011000 26:000011001010 27:000011001011 28:000011001100 29:000011001101 30:000001101000 " +
"31:000001101001 32:000001101010 33:000001101011 34:000011010010 35:000011010011 36:000011010100 " +
"37:000011010101 38:000011010110 39:000011010111 40:000001101100 41:000001101101 42:000011011010 " +
"43:000011011011 44:000001010100 45:000001010101 46:000001010110 47:000001010111 48:000001100100 " +
"49:000001100101 50:000001010010 51:000001010011 52:000000100100 53:000000110111 54:000000111000 " +
"55:000000100111 56:000000101000 57:000001011000 58:000001011001 59:000000101011 60:000000101100 " +
"61:000001011010 62:000001100110 63:000001100111 " +
"64:0000001111 128:000011001000 192:000011001001 256:000001011011 320:000000110011 384:000000110100 " +
"448:000000110101 512:0000001101100 576:0000001101101 640:0000001001010 704:0000001001011 " +
"768:0000001001100 832:0000001001101 896:0000001110010 960:0000001110011 1024:0000001110100 " +
"1088:0000001110101 1152:0000001110110 1216:0000001110111 1280:0000001010010 1344:0000001010011 " +
"1408:0000001010100 1472:0000001010101 1536:0000001011010 1600:0000001011011 1664:0000001100100 " +
"1728:0000001100101",
)
/** the make-up codes past 1728, the same for both colours */
private val EXTENDED = codes(
"1792:00000001000 1856:00000001100 1920:00000001101 1984:000000010010 2048:000000010011 " +
"2112:000000010100 2176:000000010101 2240:000000010110 2304:000000010111 2368:000000011100 " +
"2432:000000011101 2496:000000011110 2560:000000011111",
)
private const val EOL = "000000000001"
private fun codes(s: String) = s.trim().split(Regex("\\s+")).map { it.split(':').let { (r, b) -> Code(r.toInt(), b) } }
private val whiteByRun = (WHITE + EXTENDED).associateBy { it.run }
private val blackByRun = (BLACK + EXTENDED).associateBy { it.run }
/** the codes as a binary tree to decode with: [next] pairs, a leaf's run (or -1) */
private class Tree(table: List<Code>) {
var zero = IntArray(256)
var one = IntArray(256)
var leaf = IntArray(256) { -1 }
var n = 1
init {
java.util.Arrays.fill(zero, -1)
java.util.Arrays.fill(one, -1)
for (c in table) {
var at = 0
for (ch in c.bits) {
val next = if (ch == '0') zero else one
if (next[at] < 0) {
if (n == zero.size) grow()
next[at] = n++
}
at = (if (ch == '0') zero else one)[at]
}
leaf[at] = c.run
}
}
private fun grow() {
val s = zero.size * 2
zero = zero.copyOf(s).also { java.util.Arrays.fill(it, s / 2, s, -1) }
one = one.copyOf(s).also { java.util.Arrays.fill(it, s / 2, s, -1) }
leaf = leaf.copyOf(s).also { java.util.Arrays.fill(it, s / 2, s, -1) }
}
}
private val whiteTree = Tree(WHITE + EXTENDED)
private val blackTree = Tree(BLACK + EXTENDED)
/** bits out, the first in the bottom bit of each byte */
private class BitWriter {
val out = ByteArrayOutputStream()
private var cur = 0
private var n = 0
var count = 0L
private set
fun bit(b: Int) {
if (b != 0) cur = cur or (1 shl n)
n++
count++
if (n == 8) { out.write(cur); cur = 0; n = 0 }
}
fun bits(s: String) { for (c in s) bit(if (c == '1') 1 else 0) }
fun bytes(): ByteArray {
if (n > 0) { out.write(cur); cur = 0; n = 0 }
return out.toByteArray()
}
}
/**
* [page] in MH: each row with its EOL at least [minBits] long (fill
* zeros before the EOL: the receiver's minimum scan time at the
* rate), RTC after the last
*/
fun encode(page: FaxPage, minBits: Int = 0): ByteArray {
val w = BitWriter()
for (y in 0 until page.rows) {
val start = w.count
w.bits(EOL)
var x = 0
var black = false
while (x < page.width) {
var run = 0
while (x + run < page.width && page.black(x + run, y) == black) run++
runCode(w, run, black)
x += run
black = !black
}
// (a row's bits with its EOL, at least minBits: the fill before the next EOL)
val used = (w.count - start).toInt()
repeat((minBits - used).coerceAtLeast(0)) { w.bit(0) }
}
repeat(6) { w.bits(EOL) }
return w.bytes()
}
private fun runCode(w: BitWriter, run: Int, black: Boolean) {
val table = if (black) blackByRun else whiteByRun
var left = run
while (left >= 2560) { w.bits(table.getValue(2560).bits); left -= 2560 }
if (left >= 64) { w.bits(table.getValue(left / 64 * 64).bits); left %= 64 }
w.bits(table.getValue(left).bits)
}
/** what [decode] found: the page, and how many rows were damaged (copied from the one before) */
class Decoded(val page: FaxPage, val badRows: Int)
/**
* MH page data (from the line, as [encode] has it) decoded: rows of
* [width] until RTC or the data's end; a row with an error is the one
* before it again (as fax machines show it)
*/
fun decode(data: ByteArray, width: Int = FaxPage.WIDTH, fine: Boolean): Decoded {
val rows = ArrayList<ByteArray>()
var bad = 0
val total = data.size * 8L
var pos = 0L
fun bit(): Int {
if (pos >= total) return -1
val b = (data[(pos / 8).toInt()].toInt() shr (pos % 8).toInt()) and 1
pos++
return b
}
/** to just after the next EOL (eleven zeros or more, then a one); false at the end */
fun syncEol(): Boolean {
var zeros = 0
while (true) {
val b = bit()
if (b < 0) return false
if (b == 0) zeros++ else if (zeros >= 11) return true else zeros = 0
}
}
if (!syncEol()) return Decoded(FaxPage(width, 0, fine), 0)
var emptyEols = 0
val stride = width / 8
while (true) {
val rowStart = pos
val row = ByteArray(stride)
var x = 0
var black = false
var ok = true
var eolNow = false
// runs until the row is full
while (x < width) {
val run = readRun(if (black) blackTree else whiteTree, ::bit)
if (run == EOL_SEEN) { eolNow = true; ok = x == 0; break }
if (run < 0) { ok = false; break }
if (x + run > width) { ok = false; break }
if (black) for (i in x until x + run) row[i / 8] = (row[i / 8].toInt() or (0x80 shr (i % 8))).toByte()
x += run
if (run < 64) black = !black
}
if (eolNow && x == 0) {
// an EOL with no row before it: RTC's (or an empty one)
emptyEols++
if (emptyEols >= 2) break
continue
}
if (ok && x == width) {
emptyEols = 0
rows.add(row)
if (!syncEol()) break
} else {
emptyEols = 0
bad++
rows.add(rows.lastOrNull()?.copyOf() ?: ByteArray(stride))
pos = rowStart
if (!syncEol()) break
}
if (rows.size > 20_000) break
}
val page = FaxPage(width, rows.size, fine)
for ((y, r) in rows.withIndex()) System.arraycopy(r, 0, page.bits, y * stride, stride)
return Decoded(page, bad)
}
private const val EOL_SEEN = -2
/**
* a run's length (a make-up code's, or a terminating one's), EOL_SEEN
* at an EOL, -1 for no code. No code starts with more than seven zeros
* and an EOL with eleven: eight zeros, and it's an EOL if eleven or
* more come before its one
*/
private fun readRun(t: Tree, bit: () -> Int): Int {
var at = 0
var leading = 0
var allZeros = true
while (true) {
val b = bit()
if (b < 0) return -1
if (b == 0 && allZeros) leading++ else allZeros = false
if (allZeros && leading >= 8) {
while (true) {
val c = bit()
if (c < 0) return -1
if (c == 1) return if (leading >= 11) EOL_SEEN else -1
leading++
}
}
val next = if (b == 0) t.zero[at] else t.one[at]
if (next < 0) return -1
at = next
if (t.leaf[at] >= 0) return t.leaf[at]
}
}
}
@@ -0,0 +1,263 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.fax
import com.neodesktop.dmodem.transfer.TransferIo
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.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
/**
* Fax calls on D-Modem's own modems: modem_test's two back to back (an
* audio pipe between them, a pty for each one's DTE), class 1 on each.
* Our sender to our receiver, and efax's both ways (its own T.30), the
* pages as they were sent.
*
* The line is native-test's fax_line (modem_test paced as a phone line:
* cmake -S native-test -B build-host && cmake --build build-host), or
* DMODEM_FAX_LINE's; skipped without it.
*/
class FaxCallTest {
@get:Rule
val tmp = TemporaryFolder()
private var modems: Process? = null
private val log = CopyOnWriteArrayList<String>()
private lateinit var a: String
private lateinit var b: String
private val ends = ArrayList<PtyEnd>()
private fun modemTest(): File? = listOfNotNull(
System.getenv("DMODEM_FAX_LINE"),
"../build-host/fax_line",
"build-host/fax_line",
).map { File(it) }.firstOrNull { it.canExecute() }
@Before
fun setUp() {
val mt = modemTest()
assumeTrue("fax_line isn't built (native-test)", mt != null)
val p = ProcessBuilder(mt!!.path).redirectErrorStream(true).start()
modems = p
Thread {
p.inputStream.bufferedReader().forEachLine { l -> log.add(l) }
}.apply { isDaemon = true; start() }
val end = System.currentTimeMillis() + 10_000
while (System.currentTimeMillis() < end && log.none { it.startsWith("created modemB: ") }) Thread.sleep(20)
a = log.first { it.startsWith("created modemA: ") }.substringAfter(": ")
b = log.first { it.startsWith("created modemB: ") }.substringAfter(": ")
}
@After
fun tearDown() {
ends.forEach { it.close() }
modems?.destroy()
modems?.waitFor(5, TimeUnit.SECONDS)
}
/** a modem's pty from here: raw, its octets into a TransferIo */
private inner class PtyEnd(path: String) {
val input: FileInputStream
val output: FileOutputStream
val io: TransferIo
val c1: Class1
init {
ProcessBuilder("stty", "-F", path, "raw", "-echo").start().waitFor()
input = FileInputStream(path)
output = FileOutputStream(path)
io = TransferIo { bytes -> output.write(bytes); output.flush() }
c1 = Class1(io) { line -> log.add("${path.substringAfterLast('/')}: $line") }
Thread {
val buf = ByteArray(4096)
while (true) {
val n = try { input.read(buf) } catch (_: Exception) { -1 }
if (n < 0) break
io.feed(buf, 0, n)
}
}.apply { isDaemon = true; start() }
ends.add(this)
}
fun close() {
runCatching { input.close() }
runCatching { output.close() }
}
var rates: List<T30.Rate> = emptyList()
fun setUp(caller: Boolean, maxBps: Int = 14400) {
assertEquals("OK", c1.command("E0"))
assertEquals("OK", c1.command(if (caller) "X3+FCLASS=1" else "+FCLASS=1"))
rates = T30.modemRates(c1, maxBps)
}
}
private fun waitLog(what: String, secs: Int = 30): Boolean {
val end = System.currentTimeMillis() + secs * 1000L
while (System.currentTimeMillis() < end) {
if (log.any { it.contains(what) }) return true
Thread.sleep(5)
}
return false
}
private fun dump() = log.takeLast(80).joinToString("\n")
@Test
fun ourSenderToOurReceiver() {
val pages = listOf(T4Test.testPage(true, rows = 600, seed = 1), T4Test.testPage(true, rows = 300, seed = 2))
val tx = PtyEnd(a).apply { setUp(caller = true) }
val rx = PtyEnd(b).apply { setUp(caller = false) }
val got = ArrayList<FaxPage>()
var rxDone: FaxProgress? = null
var rxError: Throwable? = null
// (on this line the answer and the dial go together)
rx.io.write("ATA\r".toByteArray())
tx.io.write("ATD\r".toByteArray())
val receiver = Thread {
try {
assertEquals("CONNECT", rx.c1.result(10_000))
rxDone = T30.receive(rx.c1, "+1 555 0199", rx.rates) { pg, _ -> got.add(pg) }
} catch (e: Throwable) { rxError = e }
}
receiver.start()
assertEquals(dump(), "CONNECT", tx.c1.result(10_000))
val sent = try {
T30.send(tx.c1, pages, "+1 555 0100", tx.rates)
} catch (e: Exception) {
throw AssertionError("$e\n${dump()}")
}
receiver.join(60_000)
assertEquals(null, rxError)
assertEquals(2, sent.pages)
assertEquals("+1 555 0199", sent.remote)
assertEquals("+1 555 0100", rxDone?.remote)
assertTrue("a fast rate: ${sent.bps}", sent.bps >= 9600)
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)
}
}
// efax ---------------------------------------------------------------
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()
@Test
fun efaxSendsToUs() {
assumeTrue("efax isn't installed", efaxThere())
val dir = tmp.newFolder("efax-tx")
val page = T4Test.testPage(true, rows = 500, seed = 3)
pbm(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) }
val got = ArrayList<FaxPage>()
var rxError: Throwable? = null
val efax = ProcessBuilder("efax", "-v", "ewin", "-o1", "-h", "", "-l", "+1 555 0100", "-d", a, "-iX3", "-t", "", "page.tif")
.directory(dir).redirectErrorStream(true).redirectOutput(File(dir, "efax.log")).start()
// efax's dial, and our answer with it
assertTrue(dump(), waitLog("modemA: run cmd: ATD"))
rx.io.write("ATA\r".toByteArray())
val receiver = Thread {
try {
assertEquals("CONNECT", rx.c1.result(10_000))
T30.receive(rx.c1, "+1 555 0199", rx.rates) { pg, _ -> got.add(pg) }
} catch (e: Throwable) { rxError = e }
}
receiver.start()
assertTrue(efax.waitFor(180, TimeUnit.SECONDS))
receiver.join(30_000)
val efaxLog = File(dir, "efax.log").readText()
assertEquals("$efaxLog\n${dump()}", 0, efax.exitValue())
assertEquals("$rxError\n$efaxLog", null, rxError)
assertEquals(1, got.size)
// the page as it was, below the band efax puts at the top of each page (blank: -h '')
val g = got[0]
val band = g.rows - page.rows
assertTrue("$band rows of efax's header ($efaxLog)", band in 0..64)
assertTrue("its header blank", g.bits.copyOf(band * g.stride).all { it.toInt() == 0 })
assertArrayEquals(page.bits, g.bits.copyOfRange(band * g.stride, g.bits.size))
}
@Test
fun weSendToEfax() {
assumeTrue("efax isn't installed", efaxThere())
val dir = tmp.newFolder("efax-rx")
val pages = listOf(T4Test.testPage(false, rows = 300, seed = 4), T4Test.testPage(false, rows = 200, seed = 5))
val tx = PtyEnd(a).apply { setUp(caller = true) }
// efax waiting for the modem's CONNECT (-w): its answer given here with our dial, as this line needs
val efax = ProcessBuilder("efax", "-v", "ewin", "-o1", "-l", "+1 555 0199", "-d", b, "-w", "-r", "got")
.directory(dir).redirectErrorStream(true).redirectOutput(File(dir, "efax.log")).start()
val end = System.currentTimeMillis() + 20_000
while (!File(dir, "efax.log").readText().contains("waiting for activity") && System.currentTimeMillis() < end) Thread.sleep(50)
FileOutputStream(b).use { o ->
o.write("ATA\r".toByteArray())
tx.io.write("ATD\r".toByteArray())
}
assertEquals(dump(), "CONNECT", tx.c1.result(10_000))
val sent = try {
T30.send(tx.c1, pages, "+1 555 0100", tx.rates)
} catch (e: Exception) {
throw AssertionError("$e\n${File(dir, "efax.log").readText()}\n${dump()}")
}
assertTrue(efax.waitFor(60, TimeUnit.SECONDS))
val efaxLog = File(dir, "efax.log").readText()
assertEquals(efaxLog, 0, efax.exitValue())
assertEquals(2, sent.pages)
assertEquals("+1 555 0199", sent.remote)
for (i in pages.indices) {
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)
assertEquals("page ${i + 1}'s rows", pages[i].rows, back.rows)
assertArrayEquals("page ${i + 1}", pages[i].bits, back.bits)
}
}
}
@@ -0,0 +1,98 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.fax
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.random.Random
/** T.4's MH coding both ways; T.30's DIS/DCS bits and identities. */
class T4Test {
companion object {
/** a test page: a frame, bars of every width, text-like dashes, a checkerboard, a black row */
fun testPage(fine: Boolean, rows: Int = 400, seed: Int = 1): FaxPage {
val p = FaxPage(FaxPage.WIDTH, rows, fine)
val r = Random(seed)
for (y in 0 until rows) for (x in 0 until p.width) {
val on = when {
x < 4 || x >= p.width - 4 || y < 4 || y >= rows - 4 -> true
y in 20..60 -> (x / ((y - 19) % 9 + 1)) % 2 == 0
y in 80..200 -> (x / 6 + y / 10) % 7 == 0 || r.nextInt(97) == 0
y in 220..300 -> (x / 3 + y / 3) % 2 == 0
y == 320 -> true
else -> false
}
if (on) p.set(x, y, true)
}
return p
}
}
@Test
fun aPageThereAndBack() {
for (fine in listOf(false, true)) {
val page = testPage(fine)
val data = T4.encode(page)
val back = T4.decode(data, fine = fine)
assertEquals(0, back.badRows)
assertEquals(page.rows, back.page.rows)
assertArrayEquals(page.bits, back.page.bits)
}
}
@Test
fun theMinimumScanTimeAsFill() {
val page = FaxPage(FaxPage.WIDTH, 10, false)
// an all-white row: 1728 (9 bits) + 0 (8 bits) + EOL (12): 29 bits; at least 200 asked
val plain = T4.encode(page)
val filled = T4.encode(page, minBits = 200)
assertTrue(filled.size >= 10 * 200 / 8)
assertTrue(plain.size < filled.size)
assertEquals(10, T4.decode(filled, fine = false).page.rows)
}
@Test
fun aDamagedRowIsTheOneBeforeItAgain() {
val page = testPage(false, rows = 120)
val data = T4.encode(page)
// a byte in the middle spoilt: a row or two lost, the rest still there
data[data.size / 2] = (data[data.size / 2].toInt() xor 0xff).toByte()
val back = T4.decode(data, fine = false)
assertTrue("bad rows: ${back.badRows}", back.badRows in 1..3)
assertEquals(page.rows, back.page.rows)
}
@Test
fun theCodesArePrefixFree() {
// (decoding random data never loops nor reads past the end)
val junk = Random(3).nextBytes(20_000)
T4.decode(junk, fine = false)
}
@Test
fun disAndDcs() {
val dis = T30.dis(T30.RATES)
assertTrue(T30.bit(dis, 10))
assertTrue(T30.bit(dis, 15))
assertFalse(T30.bit(dis, 16))
assertEquals(5, T30.disMinMs(dis))
assertTrue(T30.RATES.all { T30.disOffers(dis, it) })
val v29 = T30.dis(T30.RATES.filter { it.family < 2 })
assertFalse(T30.disOffers(v29, T30.RATES.first()))
assertTrue(T30.disOffers(v29, T30.RATES.first { it.bps == 9600 && it.family == 1 }))
for (r in T30.RATES) {
val d = T30.dcs(r, true, 10)
assertEquals(r, T30.dcsRate(d))
assertEquals(10, T30.dcsMinMs(d))
assertTrue(T30.bit(d, 15))
}
// the identity: last character first, spaces after
val id = T30.ident("+1 555 0100")
assertEquals('0'.code.toByte(), id[0])
assertEquals("+1 555 0100", T30.readIdent(id))
}
}
+9
View File
@@ -18,3 +18,12 @@ target_compile_options(engine_test PRIVATE -Wall -Wextra)
add_test(NAME engine COMMAND engine_test $<TARGET_FILE:dmodemd>)
set_tests_properties(engine PROPERTIES TIMEOUT 600)
# fax_line: modem_test's two modems back to back, paced as a phone line
# (the app's fax tests, FaxCallTest, call over it)
find_package(Threads REQUIRED)
add_executable(fax_line fax_line.cpp)
target_include_directories(fax_line PRIVATE ${DMODEM_RE_DIR}/dmodemd)
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)
+50
View File
@@ -0,0 +1,50 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* fax_line.cpp - D-Modem-RE's modem_test (two modems back to back on
* an audio pipe, a pty for each one's DTE) paced as a
* phone line is: at the sample clock (MODEM_REALTIME,
* as the interop tests have it), so that a fax
* program's T.30 timing meets the line's (modem_test
* runs as fast as it can once off hook). The app's
* fax tests' line.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dsplibs.h>
#include <log.h>
#include "options.h"
#include "pipe_modem.h"
int main(int argc, char *argv[])
{
dmd::Options opt;
int pipe1[2], pipe2[2], ret;
dcore::log_level = 1;
dmd::parse_options(argc, argv, opt);
dcore::log_open("test");
prop_dp_init();
if (pipe(pipe1) < 0 || pipe(pipe2) < 0) {
perror("pipe");
return 1;
}
dmd::PipeModem a("modemA", 9600, opt.country, pipe1[0], pipe2[1]);
dmd::PipeModem b("modemB", 9600, opt.country, pipe2[0], pipe1[1]);
/* (unpaced only when asked: MODEM_REALTIME=0) */
bool realtime = !getenv("MODEM_REALTIME") || atoi(getenv("MODEM_REALTIME"));
a.set_realtime(realtime);
b.set_realtime(realtime);
fprintf(stderr, "created modemA: %s\ncreated modemB: %s\n",
a.pty().name(), b.pty().name());
dmd::PipeModem *modems[] = { &a, &b };
ret = dmd::PipeModem::run(modems, 2);
prop_dp_exit();
dcore::log_close();
return ret;
}