From b534be0dbcdab5c6ffdcbb728d15d2bbe92ee99e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 18:30:42 +0000 Subject: [PATCH] Fax: error correction mode (T.30 Annex A), sending and receiving ECM when both machines have it (DIS/DCS bits 24 and 27): the page in blocks of up to 256 FCD frames of 256 octets on the fast modulation, RCP three times, then PPS; the receiver's MCF, or PPR with a map of the frames that didn't come, sent again; after four PPRs CTC at a rate lower (with the long training), after three CTCs EOR; RR for RNR; a PPS again for an MCF lost. A class 1 modem carries ECM's HDLC as bits, so the framing is ours (EcmHdlc: flags, zero stuffing, FCS-16). A setting (on by default); FaxProgress.ecm. Tests: common Kotlin on two class 1 modems in memory that spoil what they're told (PPR, CTC, EOR, no ECM); the real modems with and without ECM; efax (no ECM) still. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs --- .../java/com/neodesktop/dmodem/fax/Fax.kt | 4 +- .../neodesktop/dmodem/settings/FaxSettings.kt | 13 +- .../java/com/neodesktop/dmodem/ui/FaxUi.kt | 7 + .../com/neodesktop/dmodem/fax/FaxCallTest.kt | 15 +- .../com/neodesktop/dmodem/fax/EcmHdlc.kt | 136 ++++++++ .../kotlin/com/neodesktop/dmodem/fax/T30.kt | 293 +++++++++++++++++- .../com/neodesktop/dmodem/fax/EcmTest.kt | 178 +++++++++++ .../com/neodesktop/dmodem/fax/FakeClass1.kt | 199 ++++++++++++ 8 files changed, 823 insertions(+), 22 deletions(-) create mode 100644 shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/EcmHdlc.kt create mode 100644 shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt create mode 100644 shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt diff --git a/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt b/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt index 498ba03..72aa05d 100644 --- a/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt +++ b/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt @@ -107,7 +107,7 @@ object Fax { update(FaxProgress("Dialling $number", total = pages.size)) val r = c.command("D$number", 120_000) if (r != "CONNECT") throw FaxException(dialResult(r)) - val p = T30.send(c, pages, s.ident, rates) { update(it) } + val p = T30.send(c, pages, s.ident, rates, ecm = s.ecm) { update(it) } record(app, true, number, p, "", "") p to "" } @@ -124,7 +124,7 @@ object Fax { if (r != "CONNECT") throw FaxException(if (r == null) "no fax answered" else "no fax: $r") val got = ArrayList() val p = try { - T30.receive(c, s.ident, rates, { update(it) }) { pg, _ -> got.add(pg) } + T30.receive(c, s.ident, rates, { update(it) }, ecm = s.ecm) { pg, _ -> got.add(pg) } } catch (e: IOException) { // the pages that came are kept if (got.isEmpty()) throw e diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt index d852602..94c5cd1 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/FaxSettings.kt @@ -25,6 +25,8 @@ data class FaxSettings( val maxBps: Int = 14400, /** pages sent at 196 lines to the inch (else 98) */ val fine: Boolean = true, + /** error correction mode (T.30 Annex A) when the other machine has it: what a noisy line spoils, sent again */ + val ecm: Boolean = true, ) private val Context.faxStore: DataStore by preferencesDataStore("fax") @@ -35,19 +37,21 @@ class FaxSettingsStore(private val context: Context) { val answer = booleanPreferencesKey("answer") val maxBps = intPreferencesKey("max_bps") val fine = booleanPreferencesKey("fine") + val ecm = booleanPreferencesKey("ecm") } - val settings: Flow = context.faxStore.data.map { p -> + private fun read(p: Preferences): FaxSettings { val d = FaxSettings() - FaxSettings(p[K.ident] ?: d.ident, p[K.answer] ?: d.answer, p[K.maxBps] ?: d.maxBps, p[K.fine] ?: d.fine) + return FaxSettings(p[K.ident] ?: d.ident, p[K.answer] ?: d.answer, p[K.maxBps] ?: d.maxBps, p[K.fine] ?: d.fine, p[K.ecm] ?: d.ecm) } + val settings: Flow = context.faxStore.data.map { p -> read(p) } + suspend fun current(): FaxSettings = settings.first() suspend fun update(change: (FaxSettings) -> FaxSettings) { context.faxStore.edit { p -> - val d = FaxSettings() - val s = change(FaxSettings(p[K.ident] ?: d.ident, p[K.answer] ?: d.answer, p[K.maxBps] ?: d.maxBps, p[K.fine] ?: d.fine)) + val s = change(read(p)) write(p, s) } } @@ -57,5 +61,6 @@ class FaxSettingsStore(private val context: Context) { p[K.answer] = s.answer p[K.maxBps] = s.maxBps p[K.fine] = s.fine + p[K.ecm] = s.ecm } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt b/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt index d9e4d75..56ef18f 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt @@ -208,6 +208,13 @@ fun FaxSettingsSection() { Text("Fine resolution (196 lines per inch)", Modifier.weight(1f)) Switch(checked = s.fine, onCheckedChange = { v -> scope.launch { store.update { it.copy(fine = v) } } }) } + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text("Error correction (ECM)") + Text("What a noisy line spoils is sent again, when the other machine can", style = MaterialTheme.typography.bodySmall) + } + Switch(checked = s.ecm, onCheckedChange = { v -> scope.launch { store.update { it.copy(ecm = v) } } }) + } Text("Fastest rate", style = MaterialTheme.typography.bodyMedium) for ((bps, label) in listOf(14400 to "14400 (V.17)", 9600 to "9600 (V.29)", 4800 to "4800 (V.27ter: poor lines)")) { Row( diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt index a2d48ef..5252b6a 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt @@ -117,7 +117,12 @@ class FaxCallTest { private fun dump() = log.takeLast(80).joinToString("\n") @Test - fun ourSenderToOurReceiver() { + fun ourSenderToOurReceiver() = ourCall(ecm = true) + + @Test + fun ourSenderToOurReceiverWithoutEcm() = ourCall(ecm = false) + + private fun ourCall(ecm: Boolean) { val pages = listOf(FaxTestPage.of(true, rows = 600, seed = 1), FaxTestPage.of(true, rows = 300, seed = 2)) val tx = PtyEnd(a).apply { setUp(caller = true) } val rx = PtyEnd(b).apply { setUp(caller = false) } @@ -130,19 +135,21 @@ class FaxCallTest { 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) } + rxDone = T30.receive(rx.c1, "+1 555 0199", rx.rates, ecm = ecm) { 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) + T30.send(tx.c1, pages, "+1 555 0100", tx.rates, ecm = ecm) } catch (e: Exception) { throw AssertionError("$e\n${dump()}") } receiver.join(60_000) assertEquals(null, rxError) assertEquals(2, sent.pages) + assertEquals(ecm, sent.ecm) + assertEquals(ecm, rxDone?.ecm) assertEquals("+1 555 0199", sent.remote) assertEquals("+1 555 0100", rxDone?.remote) assertTrue("a fast rate: ${sent.bps}", sent.bps >= 9600) @@ -250,6 +257,8 @@ class FaxCallTest { val efaxLog = File(dir, "efax.log").readText() assertEquals(efaxLog, 0, efax.exitValue()) assertEquals(2, sent.pages) + // (efax has no ECM: without it, though we'd have it) + assertTrue(!sent.ecm) assertEquals("+1 555 0199", sent.remote) for (i in pages.indices) { val f = File(dir, "got.%03d".format(i + 1)) diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/EcmHdlc.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/EcmHdlc.kt new file mode 100644 index 0000000..a54f6dd --- /dev/null +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/EcmHdlc.kt @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.fax + +import com.neodesktop.dmodem.io.* +import com.neodesktop.dmodem.ppp.Hdlc + +/** + * HDLC on the fast modulations, as error correction mode has it (T.4 + * Annex A): a class 1 modem's +FTM and +FRM carry bits, and the fax + * software frames them itself. Flags (0x7e) between the frames, a zero + * stuffed after five ones inside them, the FCS-16 after each; the bits + * in the order they go on the line, the first in an octet's bottom bit + * (as the modem takes them). + */ +object EcmHdlc { + private class BitWriter { + val out = Bytes() + private var cur = 0 + private var n = 0 + var bits = 0L + private set + + fun bit(b: Int) { + if (b != 0) cur = cur or (1 shl n) + bits++ + if (++n == 8) { + out.write(cur) + cur = 0 + n = 0 + } + } + + fun flag() { + for (i in 0 until 8) bit((0x7e shr i) and 1) + } + + /** the last octet filled with ones (the line idle, after a flag) */ + fun finish(): ByteArray { + while (n != 0) bit(1) + return out.toByteArray() + } + } + + /** + * [frames] (address, control, FCF, FIF: their FCS added here) with + * [preambleFlags] flags before (T.30: 200 ms of them), one between + * each, [tailFlags] after + */ + fun encode(frames: List, preambleFlags: Int, tailFlags: Int = 3): ByteArray { + val w = BitWriter() + repeat(maxOf(1, preambleFlags)) { w.flag() } + for (f in frames) { + val fcs = Hdlc.fcs(f) xor 0xffff + var ones = 0 + fun put(octet: Int) { + for (i in 0 until 8) { + val b = (octet shr i) and 1 + w.bit(b) + if (b == 1) { + if (++ones == 5) { w.bit(0); ones = 0 } + } else { + ones = 0 + } + } + } + for (b in f) put(b.toInt() and 0xff) + put(fcs and 0xff) + put(fcs ushr 8) + w.flag() + } + repeat(maxOf(0, tailFlags - 1)) { w.flag() } + return w.finish() + } + + /** the flags at [bps] for [ms] */ + fun flagsFor(bps: Int, ms: Int) = maxOf(1, bps * ms / 1000 / 8) + + /** the frames with a good FCS in [data] (their FCS off), in the order they came */ + fun decode(data: ByteArray): List { + val frames = ArrayList() + val cur = Bytes() + var octet = 0 + var nbits = 0 + var ones = 0 + var inFrame = false + + // (a flag's first bit, its zero, is in the frame's bits when the flag is known: whole octets leave just it) + fun close() { + if (inFrame && nbits == 1 && cur.size >= 5) { + val f = cur.toByteArray() + if (Hdlc.fcs(f) == Hdlc.GOOD_FCS) frames.add(f.copyOf(f.size - 2)) + } + cur.reset() + octet = 0 + nbits = 0 + inFrame = true + } + + fun put(b: Int) { + if (!inFrame) return + if (b != 0) octet = octet or (1 shl nbits) + if (++nbits == 8) { + cur.write(octet) + octet = 0 + nbits = 0 + // (no frame of ECM's is this long: noise, until a flag) + if (cur.size > 1024) { cur.reset(); inFrame = false } + } + } + + for (byte in data) { + val v = byte.toInt() + for (i in 0 until 8) { + if ((v shr i) and 1 == 1) { + if (++ones >= 7) { + // an abort (or the line idle): hunt for a flag + inFrame = false + cur.reset() + nbits = 0 + octet = 0 + } + continue + } + when { + ones == 6 -> close() + ones == 5 -> repeat(5) { put(1) } // (the stuffed zero dropped) + ones < 5 -> { repeat(ones) { put(1) }; put(0) } + // (7 or more: the abort above) + } + ones = 0 + } + } + return frames + } +} diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/T30.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/T30.kt index c6020a5..a561147 100644 --- a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/T30.kt +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/fax/T30.kt @@ -15,6 +15,8 @@ data class FaxProgress( val fine: Boolean = false, /** the other machine's identity (its CSI or TSI) */ val remote: String = "", + /** in error correction mode (T.30 Annex A) */ + val ecm: Boolean = false, ) /** a fax call that didn't work: why */ @@ -23,8 +25,11 @@ 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). + * MH coding, with error correction mode when both have it (T.30 Annex + * A: the page in blocks of numbered HDLC frames on the fast modulation, + * [EcmHdlc], those that didn't come asked for again) or without. 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 @@ -43,8 +48,26 @@ object T30 { const val RTN = 0x4c const val DCN = 0xfa const val CRP = 0x1a + // error correction mode's + const val PPS = 0xbe + const val PPR = 0xbc + const val RR = 0x6e + const val RNR = 0xec + const val CTC = 0x12 + const val CTR = 0xc4 + const val EOR = 0xce + const val ERR = 0x1c + const val FCD = 0x06 + const val RCP = 0x86 const val X = 0x01 + /** an ECM frame's page data (256 octets: DCS bit 28 clear) and a block's frames at most */ + const val ECM_SIZE = 256 + const val ECM_FRAMES = 256 + /** PPRs for a block before CTC, CTCs before EOR */ + private const val ECM_PPRS = 4 + private const val ECM_CTCS = 3 + /** 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) @@ -81,9 +104,9 @@ object T30 { return ms[c] } - /** our DIS: a receiver of MH, the [rates], fine, A4, 5 ms minimum scan time */ - fun dis(rates: List): ByteArray { - val f = ByteArray(3) + /** our DIS: a receiver of MH, the [rates], fine, A4, 5 ms minimum scan time; error correction mode if [ecm] */ + fun dis(rates: List, ecm: Boolean = false): ByteArray { + val f = ByteArray(if (ecm) 4 else 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 } @@ -96,12 +119,13 @@ object T30 { setBit(f, 15) // minimum scan time 5 ms (none would do for us; efax divides by it, crashing on 0) setBit(f, 21) + if (ecm) { setBit(f, 24); setBit(f, 27) } 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) + /** a DCS: the rate, fine or not, the minimum scan time agreed; error correction mode (256 octet frames) if [ecm] */ + fun dcs(r: Rate, fine: Boolean, minMs: Int, ecm: Boolean = false): ByteArray { + val f = ByteArray(if (ecm) 4 else 3) setBit(f, 10) if (r.code and 1 != 0) setBit(f, 11) if (r.code and 2 != 0) setBit(f, 12) @@ -114,9 +138,13 @@ object T30 { 5 -> setBit(f, 21) 0 -> { setBit(f, 21); setBit(f, 22); setBit(f, 23) } } + if (ecm) { setBit(f, 24); setBit(f, 27) } return f } + /** a DIS or DCS with error correction mode */ + fun ecm(fif: ByteArray) = bit(fif, 24) && bit(fif, 27) + /** the rate a DCS says, among [RATES] */ fun dcsRate(fif: ByteArray): Rate? { val v = rateBits(fif) @@ -176,6 +204,8 @@ object T30 { ident: String, /** the modem's rates ([modemRates], asked before the call: not during it) */ have: List, + /** error correction mode when the receiver has it */ + ecm: Boolean = true, progress: (FaxProgress) -> Unit = {}, ): FaxProgress { if (pages.isEmpty()) throw FaxException("no pages") @@ -201,8 +231,10 @@ object T30 { 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) + val useEcm = ecm && ecm(d) + // (ECM has no minimum row time) + val minMs = if (useEcm) 0 else disMinMs(d) + p = p.copy(remote = remote, fine = fine, ecm = useEcm) // training: down the rates until one takes var ri = 0 @@ -213,7 +245,7 @@ object T30 { 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))))) { + if (!c.transmitFrames(listOf(Class1.frame(TSI or X, ident(ident)), Class1.frame(DCS or X, dcs(r, fine, minMs, useEcm))))) { throw FaxException("the modem didn't send the DCS") } c.command("+FTS=8") @@ -233,12 +265,122 @@ object T30 { } var rate = train() + /** a command (a control frame) until a good answer: up to three times, RNR asked again with RR (60 s) */ + fun ask(cmd: ByteArray): Class1.Frame? { + var frame = cmd + var rnrs = 0 + var attempt = 0 + while (attempt < 3) { + c.command("+FTS=8") + if (!c.transmitFrames(listOf(frame))) throw FaxException("the modem didn't send a command") + val f = c.receiveFrame(4_000) + if (f == null || !f.ok || f.fcf and X.inv() == CRP) { attempt++; continue } + if (f.fcf and X.inv() == RNR) { + if (++rnrs > 60) throw FaxException("the fax machine wasn't ready") + sleepMs(1000) + frame = Class1.frame(RR or X) + attempt = 0 + continue + } + return f + } + return null + } + + /** frames on the page's modulation (after CTC, with the long training), RCP three times after */ + fun burst(frames: List, long: Boolean) { + val rcp = Class1.frame(RCP) + val bits = EcmHdlc.encode(frames + listOf(rcp, rcp, rcp), EcmHdlc.flagsFor(rate.bps, 200)) + if (c.command("+FTM=${if (long) rate.trainMod else rate.pageMod}", 10_000) != "CONNECT") { + throw FaxException("the modem didn't send the page") + } + c.sendData(bits) + if (c.result(120_000) != "OK") throw FaxException("the page didn't go out") + } + + /** a page in error correction mode ([pageNo] of the call), its blocks each until all came; its end with [post] */ + fun sendEcm(data: ByteArray, post: Int, pageNo: Int) { + val perBlock = ECM_SIZE * ECM_FRAMES + val blocks = maxOf(1, (data.size + perBlock - 1) / perBlock) + for (blk in 0 until blocks) { + val start = blk * perBlock + val len = minOf(perBlock, data.size - start).coerceAtLeast(0) + val n = maxOf(1, (len + ECM_SIZE - 1) / ECM_SIZE) + // FCD: the frame's number, its 256 octets (the last padded) + val frames = List(n) { k -> + val f = Class1.frame(FCD, ByteArray(1 + ECM_SIZE)) + f[3] = k.toByte() + val from = start + k * ECM_SIZE + val m = minOf(ECM_SIZE, data.size - from).coerceAtLeast(0) + data.copyInto(f, 4, from, from + m) + f + } + val last = blk == blocks - 1 + val pps = Class1.frame(PPS or X, byteArrayOf(if (last) (post or X).toByte() else 0, pageNo.toByte(), blk.toByte(), (n - 1).toByte())) + val send = BooleanArray(n) { true } + var pprs = 0 + var ctcs = 0 + var long = false + block@ while (true) { + burst(frames.filterIndexed { k, _ -> send[k] }, long) + long = false + var f = ask(pps) ?: throw FaxException("no answer to page ${pageNo + 1}'s block ${blk + 1}") + while (true) { + when (f.fcf and X.inv()) { + MCF -> break@block + PPR -> { + val map = f.fif + var any = false + for (k in 0 until n) { + send[k] = k / 8 < map.size && (map[k / 8].toInt() shr (k % 8)) and 1 == 1 + any = any || send[k] + } + if (!any) { + // (nothing missing after all: ask again) + f = ask(pps) ?: throw FaxException("no answer to page ${pageNo + 1}'s block ${blk + 1}") + continue + } + if (++pprs < ECM_PPRS) continue@block + pprs = 0 + if (++ctcs <= ECM_CTCS) { + // continue to correct: a rate lower if there is one, the long training + if (ri + 1 < rates.size) ri++ + rate = rates[ri] + p = p.copy(phase = "Sending page ${pageNo + 1} at ${rate.bps} bit/s", bps = rate.bps) + progress(p) + val ctc = Class1.frame(CTC or X, byteArrayOf(0, (rate.code shl 2).toByte())) + val r = ask(ctc) + if (r?.fcf?.and(X.inv()) != CTR) throw FaxException("the fax machine didn't take CTC") + long = true + continue@block + } + // given up on the block: what came of it stays + val eor = Class1.frame(EOR or X, byteArrayOf(if (last) (post or X).toByte() else 0)) + val r = ask(eor) + if (r?.fcf?.and(X.inv()) != ERR) throw FaxException("page ${pageNo + 1} didn't go through") + break@block + } + DCN -> throw FaxException("the fax machine hung up during page ${pageNo + 1}") + else -> throw FaxException("the fax machine answered page ${pageNo + 1}'s block with ${hex2(f.fcf)}") + } + } + } + } + } + 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) + if (useEcm) { + sendEcm(T4.encode(page, 0), if (i == pages.lastIndex) EOP else MPS, i) + i++ + p = p.copy(pages = i) + progress(p) + continue + } 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) @@ -295,13 +437,118 @@ object T30 { /** the modem's rates ([modemRates], asked before the call) */ have: List, progress: (FaxProgress) -> Unit = {}, + /** error correction mode offered */ + ecm: Boolean = true, page: (FaxPage, Int) -> Unit, ): FaxProgress { var p = FaxProgress("Answering") progress(p) - val ours = listOf(Class1.frame(CSI, ident(ident)), Class1.frame(DIS, dis(have))) + val ours = listOf(Class1.frame(CSI, ident(ident)), Class1.frame(DIS, dis(have, ecm))) var pages = 0 var firstDis = true + // (ECM: the page and block of our last MCF, for a PPS again that missed it) + var lastMcf: Pair? = null + // (ECM: the rate a CTC changed to, until the next DCS) + var ecmRate: Rate? = null + + /** what ended an ECM page: its post command (MPS, EOP, EOM), a DCS (training again), the sender's DCN */ + class EcmEnd(val post: Int = -1, val dcs: ByteArray? = null, val dcn: Boolean = false) + + /** a page in error correction mode at [r0]: its blocks, our PPR for frames missing, MCF; the page to [page] */ + fun receiveEcm(r0: Rate, fine: Boolean): EcmEnd { + var rate = r0 + val doc = Bytes() + val got = arrayOfNulls(ECM_FRAMES) + var count = 0 + var long = false + var last: ByteArray? = null + fun respond(fr: ByteArray) { + last = fr + c.command("+FTS=8") + c.transmitFrames(listOf(fr)) + } + fun pageDone(post: Int): EcmEnd { + val dec = T4.decode(doc.toByteArray(), FaxPage.WIDTH, fine) + if (dec.page.rows > 0 && dec.badRows * 20 < dec.page.rows) { + pages++ + page(dec.page, pages) + p = p.copy(pages = pages) + progress(p) + } + return EcmEnd(post = post) + } + while (true) { + p = p.copy(phase = "Receiving page ${pages + 1}", bps = rate.bps) + progress(p) + val m = c.command("+FRM=${if (long) rate.trainMod else rate.pageMod}", 15_000) + long = false + var ctl: Class1.Frame? = null + when (m) { + "CONNECT" -> { + val data = c.readData(120_000) ?: throw FaxException("the page stopped coming") + c.result(3000) + for (f in EcmHdlc.decode(data)) { + if (f.size < 4 || f[0] != 0xff.toByte() || (f[2].toInt() and 0xfe) != FCD) continue + got[f[3].toInt() and 0xff] = f.copyOfRange(4, f.size) + } + for (attempt in 0 until 3) { + val f = c.receiveFrame() ?: continue + if (f.ok) { ctl = f; break } + } + } + // (V.21 instead: a command again, or the DCS) + "+FCERROR" -> ctl = c.receiveFrame()?.takeIf { it.ok } + else -> throw FaxException("the page didn't come ($m)") + } + val f = ctl ?: throw FaxException("no end to a block of page ${pages + 1}") + val fif = f.fif + when (f.fcf and X.inv()) { + PPS -> { + if (fif.size < 4) continue + val post = fif[0].toInt() and 0xfe + val at = (fif[1].toInt() and 0xff) to (fif[2].toInt() and 0xff) + if (at == lastMcf && got.all { it == null }) { + // our MCF didn't get there + respond(Class1.frame(MCF)) + if (post != 0) return EcmEnd(post = post) + continue + } + count = maxOf(count, (fif[3].toInt() and 0xff) + 1) + val map = ByteArray(32) + var missing = 0 + for (k in 0 until count) if (got[k] == null) { map[k / 8] = (map[k / 8].toInt() or (1 shl (k % 8))).toByte(); missing++ } + if (missing > 0) { + respond(Class1.frame(PPR, map)) + continue + } + for (k in 0 until count) doc.write(got[k]!!) + got.fill(null) + count = 0 + lastMcf = at + respond(Class1.frame(MCF)) + if (post != 0) return pageDone(post) + } + CTC -> { + // continue to correct, maybe at another rate: the long training next + dcsRate(fif)?.let { rate = it; ecmRate = it } + long = true + respond(Class1.frame(CTR)) + } + EOR -> { + // the sender gave up on the block: what came of it lost + got.fill(null) + count = 0 + respond(Class1.frame(ERR)) + val post = if (fif.isNotEmpty()) fif[0].toInt() and 0xfe else 0 + if (post != 0) return pageDone(post) + } + RR -> last?.let { respond(it) } + DCS -> return EcmEnd(dcs = fif) + DCN -> return EcmEnd(dcn = true) + else -> throw FaxException("the sender sent ${hex2(f.fcf)} during page ${pages + 1}") + } + } + } // phase B (again after an EOM): DIS until a DCS and a good training outer@ while (true) { @@ -329,7 +576,9 @@ object T30 { 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) + val inEcm = ecm && ecm(d) + ecmRate = null + p = p.copy(phase = "Training at ${rate.bps} bit/s", bps = rate.bps, fine = fine, ecm = inEcm) progress(p) val r = c.command("+FRM=${rate.trainMod}", 10_000) val good = if (r == "CONNECT") { @@ -351,6 +600,24 @@ object T30 { continue@outer } c.transmitFrames(listOf(Class1.frame(CFR))) + if (inEcm) { + // the pages in error correction mode + var e: EcmEnd + while (true) { + e = receiveEcm(ecmRate ?: rate, fine) + if (e.post != MPS) break + } + when { + e.dcs != null -> { d = e.dcs!!; continue } + e.dcn -> if (pages > 0) return p.copy(phase = "Received") else throw FaxException("the sender hung up") + e.post == EOM -> continue@outer + e.post == EOP -> { + c.receiveFrame() + return p.copy(phase = "Received") + } + else -> throw FaxException("the sender ended page $pages with ${hex2(e.post)}") + } + } // the pages at this rate while (true) { p = p.copy(phase = "Receiving page ${pages + 1}") diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt new file mode 100644 index 0000000..1a72a2e --- /dev/null +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.fax + +import com.neodesktop.dmodem.io.background +import com.neodesktop.dmodem.io.Latch +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Error correction mode (T.30 Annex A): ECM's HDLC on the fast + * modulations ([EcmHdlc]); calls between our sender and our receiver on + * [FakeFaxLine]'s modems, the line damaging what it's told to: the + * frames that didn't come asked for again (PPR), a lower rate after + * four tries (CTC), the block given up (EOR); without ECM when one side + * doesn't have it. + */ +class EcmTest { + + @Test + fun hdlcThereAndBack() { + val r = Random(7) + // (flags and ones in the data: stuffing) + val frames = List(20) { k -> + byteArrayOf(0xff.toByte(), 0x03, 0x06, k.toByte()) + + ByteArray(256) { i -> if (k % 3 == 0) 0x7e else if (k % 3 == 1) 0xff.toByte() else r.nextInt(256).toByte() } + } + val bits = EcmHdlc.encode(frames, preambleFlags = 30) + val back = EcmHdlc.decode(bits) + assertEquals(frames.size, back.size) + for (i in frames.indices) assertContentEquals(frames[i], back[i]) + // a bit wrong in the middle: that frame (or one either side) lost, the rest there + val bad = bits.copyOf() + bad[bad.size / 2] = (bad[bad.size / 2].toInt() xor 0x10).toByte() + val got = EcmHdlc.decode(bad) + assertTrue(got.size in frames.size - 2 until frames.size, "${got.size}") + assertTrue(got.all { g -> frames.any { it.contentEquals(g) } }) + } + + /** a burst with its first frame spoilt (past the 200 ms of flags before it: 360 octets at most) */ + private fun spoil(d: ByteArray) = d.copyOf().also { it[400] = (it[400].toInt() xor 0x55).toByte() } + + /** a page of noise: big in MH (several ECM blocks) */ + private fun noisyPage(rows: Int, seed: Int): FaxPage { + val p = FaxPage(FaxPage.WIDTH, rows, fine = true) + val r = Random(seed) + for (y in 0 until rows) for (x in 0 until p.width step 4) if (r.nextBoolean()) for (k in 0 until 4) p.set(x + k, y, true) + return p + } + + private class Result(val sent: FaxProgress?, val received: FaxProgress?, val pages: List, val txError: Throwable?, val rxError: Throwable?) + + private fun call(line: FakeFaxLine, pages: List, txEcm: Boolean = true, rxEcm: Boolean = true): Result { + val tx = line.a.c1 + val rx = line.b.c1 + val have = T30.modemRates(tx) + T30.modemRates(rx) + val got = ArrayList() + var received: FaxProgress? = null + var rxError: Throwable? = null + val done = Latch() + rx.send("A") + assertEquals("CONNECT", rx.result(5000)) + background("receiver") { + try { + received = T30.receive(rx, "+1 555 0199", have, ecm = rxEcm) { pg, _ -> got.add(pg) } + } catch (e: Throwable) { + rxError = e + } + done.countDown() + } + tx.send("D") + assertEquals("CONNECT", tx.result(5000)) + var sent: FaxProgress? = null + var txError: Throwable? = null + try { + sent = T30.send(tx, pages, "+1 555 0100", have, ecm = txEcm) + } catch (e: Throwable) { + txError = e + } + done.await() + line.stop() + return Result(sent, received, got, txError, rxError) + } + + private fun assertPages(want: List, r: Result) { + assertEquals(null, r.txError) + assertEquals(null, r.rxError) + assertEquals(want.size, r.sent!!.pages) + assertEquals(want.size, r.pages.size) + for (i in want.indices) { + assertEquals(want[i].rows, r.pages[i].rows) + assertContentEquals(want[i].bits, r.pages[i].bits, "page ${i + 1}") + } + } + + @Test + fun aCallInEcm() { + val line = FakeFaxLine() + val pages = listOf(noisyPage(1200, 1), FaxTestPage.of(true, rows = 400, seed = 2)) + val r = call(line, pages) + assertPages(pages, r) + assertTrue(r.sent!!.ecm) + assertTrue(r.received!!.ecm) + val seen = line.seen() + // (no lower rate asked for) + assertTrue(seen.none { it == "A>13" }, "$seen") + // the noisy page in blocks: PPS more than once for it, MCF to each, no PPR + assertTrue(seen.count { it == "A>bf" } >= 3, "$seen") + assertTrue(seen.none { it == "B>bc" }, "$seen") + assertTrue("B>8c" in seen) + } + + @Test + fun theFramesThatDidNotComeAgain() { + val line = FakeFaxLine() + // the first block, the first time: three places spoilt + line.damage = { _, n, d -> + if (n == 1) d.copyOf().also { for (at in listOf(5000, 20000, 40000)) if (at < it.size) it[at] = (it[at].toInt() xor 0x55).toByte() } else d + } + val pages = listOf(noisyPage(300, 3)) + val r = call(line, pages) + assertPages(pages, r) + val seen = line.seen() + assertEquals(1, seen.count { it == "B>bc" }, "$seen") + assertEquals(14400, r.sent!!.bps) + } + + @Test + fun aLowerRateAfterFourTries() { + val line = FakeFaxLine() + // every burst spoilt four times: then the rate down a step (CTC, CTR), with the long training + line.damage = { _, n, d -> + if (n in 1..4) spoil(d) else d + } + val pages = listOf(FaxTestPage.of(true, rows = 400, seed = 4)) + val r = call(line, pages) + assertPages(pages, r) + val seen = line.seen() + assertEquals(4, seen.count { it == "B>bc" }, "$seen") + assertTrue("A>13" in seen, "$seen") + assertTrue("B>c4" in seen, "$seen") + assertEquals(12000, r.sent!!.bps) + } + + @Test + fun aBlockGivenUp() { + val line = FakeFaxLine() + // the first page's first block never gets through: EOR, ERR, and the call goes on + var spoilt = 0 + line.damage = { _, n, d -> + if (spoilt < 16 && n >= 1) { spoilt++; spoil(d) } else d + } + val pages = listOf(FaxTestPage.of(true, rows = 400, seed = 5), FaxTestPage.of(true, rows = 200, seed = 6)) + val r = call(line, pages) + assertEquals(null, r.txError) + assertEquals(null, r.rxError) + val seen = line.seen() + assertTrue("A>cf" in seen, "$seen") + assertTrue("B>1c" in seen, "$seen") + assertEquals(2, r.sent!!.pages) + // (the second page whole) + assertContentEquals(pages[1].bits, r.pages.last().bits) + } + + @Test + fun withoutEcmWhenTheReceiverHasNone() { + val line = FakeFaxLine() + val pages = listOf(FaxTestPage.of(false, rows = 300, seed = 7)) + val r = call(line, pages, rxEcm = false) + assertPages(pages, r) + assertTrue(!r.sent!!.ecm) + assertTrue(line.seen().none { it == "A>bf" }) + } +} diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt new file mode 100644 index 0000000..033afce --- /dev/null +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.fax + +import com.neodesktop.dmodem.io.ByteQueue +import com.neodesktop.dmodem.io.Bytes +import com.neodesktop.dmodem.io.background +import com.neodesktop.dmodem.io.sleepMs +import com.neodesktop.dmodem.transfer.TransferIo +import kotlinx.atomicfu.locks.SynchronizedObject +import kotlinx.atomicfu.locks.synchronized +import kotlin.concurrent.Volatile + +/** + * Two class 1 modems in memory with a line between them, for T.30's + * tests in common Kotlin: what one transmits (V.21 frames, +FTH; data + * on a fast modulation, +FTM) the other receives in turn (+FRH, +FRM), + * at once and without loss, but for what [damage] does to the fast + * data. A fast transmission received at another modulation than it was + * sent with fails (ERROR): the long training and the short one told + * apart, as a real modem's receiver would. + */ +class FakeFaxLine { + sealed class Tx { + class V21(val frames: List) : Tx() + class Fast(val mod: Int, val data: ByteArray) : Tx() + } + + /** the fast data [from] a modem sends (its [n]th transmission there), as the other one gets it */ + @Volatile var damage: (from: String, n: Int, data: ByteArray) -> ByteArray = { _, _, d -> d } + + /** the FCFs of the frames each way, in order ("A>" + hex), for the tests to look at */ + val seen = ArrayList() + private val lock = SynchronizedObject() + + fun seen(): List = synchronized(lock) { seen.toList() } + + inner class Modem(val name: String) { + /** the modem's DTE: our Class1 on it */ + val io = TransferIo { b -> fromDte.put(b) } + val c1 = Class1(io) + lateinit var other: Modem + private val fromDte = ByteQueue() + private var cur = ByteArray(0) + private var at = 0 + private val inbox = ArrayList() + private var fastSent = 0 + /** the V.21 frames being received, those left of them */ + private var receiving: ArrayDeque? = null + @Volatile var stopped = false + + fun deliver(t: Tx) = synchronized(lock) { inbox.add(t) } + + private fun dteWaiting() = at < cur.size || fromDte.isNotEmpty() + + private fun byte(): Int { + while (at >= cur.size) { + if (stopped) throw IllegalStateException("stopped") + cur = fromDte.poll(50) ?: continue + at = 0 + } + return cur[at++].toInt() and 0xff + } + + private fun say(s: String) = io.feed("\r\n$s\r\n".encodeToByteArray()) + + /** shielded data from the DTE, to */ + private fun dteData(): ByteArray { + val o = Bytes() + while (true) { + val c = byte() + if (c != Class1.DLE) { o.write(c); continue } + when (byte()) { + Class1.ETX -> return o.toByteArray() + Class1.DLE -> o.write(Class1.DLE) + } + } + } + + private fun toDte(d: ByteArray) { + val o = Bytes() + for (b in d) { o.write(b.toInt()); if (b.toInt() and 0xff == Class1.DLE) o.write(Class1.DLE) } + o.write(Class1.DLE) + o.write(Class1.ETX) + io.feed(o.toByteArray()) + } + + /** the next transmission come in (left there); null if the DTE stopped the wait (a character) */ + private fun waitTx(): Tx? { + while (true) { + synchronized(lock) { inbox.firstOrNull() }?.let { return it } + if (dteWaiting()) { + byte() + return null + } + if (stopped) throw IllegalStateException("stopped") + sleepMs(2) + } + } + + private fun take() = synchronized(lock) { inbox.removeAt(0) } + + /** +FTH=3 from its CONNECT: frames until the final one (or an empty one) */ + private fun sendFrames() { + val frames = ArrayList() + while (true) { + val f = dteData() + if (f.isEmpty()) break + frames.add(f) + synchronized(lock) { seen.add("$name>" + hex2(f.getOrElse(2) { 0 }.toInt() and 0xff)) } + if (f.size >= 2 && f[1].toInt() and 0x10 != 0) break + say("CONNECT") + } + other.deliver(Tx.V21(frames)) + say("OK") + } + + /** +FRH=3: the next frame (of those coming, else of the next V.21 transmission) */ + private fun receiveFrame(connected: Boolean) { + while (receiving.isNullOrEmpty()) { + val t = waitTx() ?: run { say("OK"); return } + take() + // (fast data while V.21 is listened for: lost) + if (t is Tx.V21) receiving = ArrayDeque(t.frames) + } + if (!connected) say("CONNECT") + // (its FCS: two octets, as a modem passes them) + toDte(receiving!!.removeFirst() + byteArrayOf(0, 0)) + say("OK") + } + + /** +FRM= */ + private fun receiveFast(mod: Int) { + receiving = null + val t = waitTx() ?: run { say("OK"); return } + if (t is Tx.V21) { say("+FCERROR"); return } + take() + t as Tx.Fast + if (t.mod != mod) { say("ERROR"); return } + say("CONNECT") + toDte(t.data) + say("NO CARRIER") + } + + private fun command(cmd: String) { + val c = cmd.uppercase().removePrefix("AT") + when { + c == "+FTM=?" -> { say("24,48,72,73,74,96,97,98,121,122,145,146"); say("OK") } + c == "+FTH=3" -> { say("CONNECT"); sendFrames() } + c == "+FRH=3" -> receiveFrame(false) + c.startsWith("+FTM=") -> { + val mod = c.substring(5).toInt() + say("CONNECT") + var d = dteData() + if (d.isNotEmpty() && d[0].toInt() and 0xff == 0x7e) d = damage(name, fastSent, d) + fastSent++ + other.deliver(Tx.Fast(mod, d)) + say("OK") + } + c.startsWith("+FRM=") -> receiveFast(c.substring(5).toInt()) + // dialled: CONNECT, then as +FRH=3; answered: CONNECT, then as +FTH=3 + c == "D" -> { say("CONNECT"); receiveFrame(true) } + c == "A" -> { say("CONNECT"); sendFrames() } + else -> say("OK") // (E0, +FCLASS=1, +FTS, +FRS, …) + } + } + + fun start() = background("fake modem $name") { + val line = StringBuilder() + try { + while (!stopped) { + val b = byte() + if (b == '\r'.code) { + if (line.isNotEmpty()) command(line.toString()) + line.clear() + } else if (b >= ' '.code) { + line.append(b.toChar()) + } + } + } catch (_: IllegalStateException) { + } + } + } + + val a = Modem("A") + val b = Modem("B") + + init { + a.other = b + b.other = a + a.start() + b.start() + } + + fun stop() { + a.stopped = true + b.stopped = true + } +}