diff --git a/Cargo.lock b/Cargo.lock index deb9817..a5292ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,7 +8,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "generic-array", ] @@ -19,10 +19,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -125,6 +136,137 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + [[package]] name = "async-trait" version = "0.1.92" @@ -142,6 +284,39 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "audio-codec-algorithms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1254ebf6529f3763c491acfb5ab6e960809e3c75a38584cc664f8c5667fb7107" + +[[package]] +name = "audioadapter" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1292ef9edf681b7426ed089004b021a42896492f58bd0c909ad44e5faec9ac4" + +[[package]] +name = "audioadapter-buffers" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46289a81a3bfa26d0f8b2415f8ca9decde9a66308a150568af5c102381b3c8ce" +dependencies = [ + "audioadapter", + "audioadapter-sample", + "num-traits", +] + +[[package]] +name = "audioadapter-sample" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5258faecf4edbe35ec483bda9b1f7438e6b391891819269c6b5461aeaa0e8d7d" +dependencies = [ + "audio-codec-algorithms", + "num-traits", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -225,6 +400,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -234,6 +427,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -258,6 +464,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "cc" version = "1.5.0" @@ -326,8 +541,18 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", - "inout", + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.2", ] [[package]] @@ -376,9 +601,9 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8543454e3c3f5126effff9cd44d562af4e31fb8ce1cc0d3dcd8f084515dbc1aa" dependencies = [ - "cipher", + "cipher 0.4.4", "dbl", - "digest", + "digest 0.10.7", ] [[package]] @@ -390,6 +615,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -406,12 +637,27 @@ dependencies = [ "memchr", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "const-oid" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "core-foundation" version = "0.9.4" @@ -488,6 +734,12 @@ dependencies = [ "windows-core", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -621,6 +873,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "csv" version = "1.4.0" @@ -648,7 +909,16 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher", + "cipher 0.4.4", +] + +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", ] [[package]] @@ -705,7 +975,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "pem-rfc7468", "zeroize", ] @@ -725,12 +995,24 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "dirs" version = "6.0.0" @@ -786,7 +1068,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9954fabd903b82b9d7a68f65f97dc96dd9ad368e40ccc907a7c19d53e6bfac28" dependencies = [ "aead", - "cipher", + "cipher 0.4.4", "cmac", "ctr", "subtle", @@ -799,7 +1081,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ "der", - "digest", + "digest 0.10.7", "elliptic-curve", "rfc6979", "signature", @@ -820,11 +1102,11 @@ checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ "base16ct", "crypto-bigint 0.5.5", - "digest", + "digest 0.10.7", "ff", "generic-array", "group", - "hkdf", + "hkdf 0.12.4", "pem-rfc7468", "pkcs8", "rand_core 0.6.4", @@ -847,6 +1129,33 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "env_filter" version = "2.0.0" @@ -883,6 +1192,44 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "ff" version = "0.13.1" @@ -911,6 +1258,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -974,6 +1327,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.34" @@ -1125,11 +1491,32 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] [[package]] name = "heck" @@ -1137,6 +1524,18 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "hickory-net" version = "0.26.3" @@ -1213,7 +1612,16 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ - "hmac", + "hmac 0.12.1", +] + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", ] [[package]] @@ -1222,9 +1630,24 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "hound" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f" + [[package]] name = "http" version = "1.5.0" @@ -1264,6 +1687,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.11.1" @@ -1435,7 +1867,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", ] [[package]] @@ -1447,6 +1879,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipconfig" version = "0.3.4" @@ -1578,6 +2020,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb1e621458ca9c51aa110bd0339d4751a056b9576bf1253aee1aa560dda0fc9d" +dependencies = [ + "log", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1616,6 +2079,23 @@ dependencies = [ "libc", ] +[[package]] +name = "libsqlite3-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" @@ -1664,6 +2144,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "mime" version = "0.3.17" @@ -1758,6 +2247,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -1768,6 +2271,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1794,6 +2306,27 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1967,6 +2500,16 @@ dependencies = [ "libopus_sys", ] +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "p256" version = "0.13.2" @@ -1976,7 +2519,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -1989,6 +2532,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2039,6 +2588,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkcs8" version = "0.10.2" @@ -2083,6 +2643,20 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2124,6 +2698,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "primeorder" version = "0.13.6" @@ -2332,6 +2915,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "realfft" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677" +dependencies = [ + "rustfft", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -2450,7 +3042,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ - "hmac", + "hmac 0.12.1", "subtle", ] @@ -2468,6 +3060,38 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror 2.0.21", +] + +[[package]] +name = "rtrb" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9278fb35b3e730abe136e9b395b5b81b96d06b9f5478a50f0c8430a2237b22de" + +[[package]] +name = "rubato" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7cb1ffaf8738df50aab642a7f6465df81c6ba9e2818268053487165298114be" +dependencies = [ + "audioadapter", + "audioadapter-buffers", + "num-complex", + "num-integer", + "num-traits", + "realfft", + "visibility", + "windowfunctions", +] + [[package]] name = "rug" version = "1.30.0" @@ -2480,6 +3104,21 @@ dependencies = [ "libm", ] +[[package]] +name = "rusqlite" +version = "0.40.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2495,6 +3134,33 @@ dependencies = [ "semver", ] +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.45" @@ -2620,6 +3286,25 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.3", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf 0.13.0", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.0", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -2698,6 +3383,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "serde_spanned" version = "1.1.1" @@ -2715,7 +3411,7 @@ checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -2726,7 +3422,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -2760,7 +3467,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "digest", + "digest 0.10.7", "rand_core 0.6.4", ] @@ -2824,12 +3531,30 @@ dependencies = [ "der", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "strsim" version = "0.11.1" @@ -2923,6 +3648,19 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -3247,6 +3985,16 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -3275,6 +4023,21 @@ dependencies = [ "tsproto-types", ] +[[package]] +name = "tsc-audio" +version = "0.1.0" +dependencies = [ + "cpal", + "hound", + "opus2", + "rtrb", + "rubato", + "thiserror 2.0.21", + "tracing", + "tsclientlib", + "tsproto-packets", +] + [[package]] name = "tsc-model" version = "0.1.0" @@ -3283,6 +4046,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tsc-store" +version = "0.1.0" +dependencies = [ + "keyring", + "rusqlite", + "serde", + "serde_json", + "thiserror 2.0.21", + "tsclientlib", +] + [[package]] name = "tsclientlib" version = "0.2.0" @@ -3330,6 +4105,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "tsc-audio", "tsc-model", "tsclientlib", "tsproto-packets", @@ -3339,7 +4115,7 @@ dependencies = [ name = "tsproto" version = "0.2.0" dependencies = [ - "aes", + "aes 0.8.4", "anyhow", "base64 0.22.1", "clap", @@ -3361,7 +4137,7 @@ dependencies = [ "rug", "serde", "sha-1", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "time", "tokio", @@ -3428,6 +4204,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "unicode-ident" version = "1.0.26" @@ -3472,6 +4259,7 @@ checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" dependencies = [ "getrandom 0.4.3", "js-sys", + "serde_core", "wasm-bindgen", ] @@ -3481,12 +4269,29 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "visibility" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d674d135b4a8c1d7e813e2f8d1c9a58308aee4a680323066025e53132218bd91" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -3634,6 +4439,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windowfunctions" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90628d739333b7c5d2ee0b70210b97b8cddc38440c682c96fd9e2c24c2db5f3a" +dependencies = [ + "num-traits", +] + [[package]] name = "windows" version = "0.62.2" @@ -3707,6 +4521,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -3875,6 +4702,87 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.58" @@ -3960,3 +4868,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.6", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.6", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml index aaa44ae..c675077 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,9 @@ members = [ "crates/proto/tsproto", "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", + "crates/tsc-audio", "crates/tsc-model", + "crates/tsc-store", "tools/tsctl", ] default-members = [ @@ -18,7 +20,9 @@ default-members = [ "crates/proto/tsproto", "crates/proto/ts-bookkeeping", "crates/proto/tsclientlib", + "crates/tsc-audio", "crates/tsc-model", + "crates/tsc-store", "tools/tsctl", ] @@ -39,3 +43,12 @@ all = { level = "warn", priority = -1 } # The Init1 puzzle does a large modular exponentiation on connect; unoptimized # it takes seconds. opt-level = 3 + +[profile.dev] +# Line tables (for backtraces) for workspace crates, no debug info for +# dependencies: keeps target/ several times smaller. Override locally for +# debugging with CARGO_PROFILE_DEV_DEBUG=true. +debug = "line-tables-only" + +[profile.dev.package."*"] +debug = false diff --git a/README.md b/README.md index 971ebfe..79ed1eb 100644 --- a/README.md +++ b/README.md @@ -23,14 +23,20 @@ See [docs/architecture.md](docs/architecture.md) for the design and milestones. ## Status -Milestone **M0 (foundation)**: +Done so far (milestones M0–M2 of [the plan](docs/architecture.md#milestones)): -- `crates/proto/`: vendored tsclientlib (see [UPSTREAM.md](crates/proto/UPSTREAM.md) for the patch log) -- `tools/tsctl`: headless CLI that connects, prints the channel tree, sends and receives chat -- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers for local testing -- CI: build and test on Linux and Windows, `cargo-deny`, smoke test against both servers +- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream + messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes; + see [UPSTREAM.md](crates/proto/UPSTREAM.md)) +- `crates/tsc-model`: server flavor detection (TS3 / TS6) and capabilities +- `crates/tsc-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices +- `crates/tsc-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets +- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events +- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh` + checks tree, server chat, channel chat and a voice tone round-trip on both +- `fuzz/`: cargo-fuzz targets for packets, commands and the license chain -No GUI, voice or screen sharing yet. +No GUI and no screen sharing yet. ## Try it @@ -41,8 +47,10 @@ docker compose -f dev/docker-compose.yml up -d cargo run -p tsctl -- connect 127.0.0.1:9987 tree # TeamSpeak 3 cargo run -p tsctl -- connect 127.0.0.1:9988 tree # TeamSpeak 6 cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat +cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440 +cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav -scripts/it-smoke.sh # tree + server/channel chat round-trips on both servers +scripts/it-smoke.sh # tree, chat and voice round-trips on both servers ``` Other commands: `tsctl identity new`, `tsctl versions`, `tsctl connect listen|chat|raw`. diff --git a/crates/tsc-audio/Cargo.toml b/crates/tsc-audio/Cargo.toml new file mode 100644 index 0000000..6991483 --- /dev/null +++ b/crates/tsc-audio/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "tsc-audio" +version = "0.1.0" +description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[features] +default = ["device"] +# Audio device I/O through cpal (needs ALSA headers on Linux). +device = ["dep:cpal", "dep:rtrb"] + +[dependencies] +cpal = { version = "0.18", optional = true } +hound = "3.5.1" +opus2 = "0.4" +rtrb = { version = "0.4.0", optional = true } +rubato = "5.0.0" +thiserror = "2.0.21" +tracing = "0.1.44" +tsclientlib = { path = "../proto/tsclientlib" } +tsproto-packets = { path = "../proto/tsproto-packets" } + +[lints] +workspace = true diff --git a/crates/tsc-audio/src/device.rs b/crates/tsc-audio/src/device.rs new file mode 100644 index 0000000..5b0ad81 --- /dev/null +++ b/crates/tsc-audio/src/device.rs @@ -0,0 +1,134 @@ +//! Audio capture and playback through cpal. +//! +//! The device callbacks only move samples through lock-free ring buffers; all +//! processing happens on the caller's side. + +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use rtrb::{Consumer, Producer, RingBuffer}; +use tracing::warn; + +use crate::{Error, Result}; + +/// A device as shown in settings. +#[derive(Clone, Debug)] +pub struct DeviceInfo { + pub name: String, + pub input: bool, + pub output: bool, +} + +fn device_error(e: impl std::fmt::Display) -> Error { + Error::Device(e.to_string()) +} + +/// All devices of the default host. +pub fn list_devices() -> Result> { + let host = cpal::default_host(); + let devices = host.devices().map_err(device_error)?; + Ok(devices + .map(|d| DeviceInfo { + name: d.description().map(|d| d.name().to_string()).unwrap_or_default(), + input: d.supports_input(), + output: d.supports_output(), + }) + .collect()) +} + +/// Running capture stream. Samples are interleaved at the device's rate. +pub struct Capture { + _stream: cpal::Stream, + consumer: Consumer, + pub channels: usize, + pub rate: u32, +} + +impl Capture { + /// Open the default input device, buffering up to `buffer_ms` of audio. + pub fn open_default(buffer_ms: u32) -> Result { + let device = cpal::default_host() + .default_input_device() + .ok_or_else(|| Error::Device("no input device".into()))?; + let config = device.default_input_config().map_err(device_error)?.config(); + let channels = config.channels as usize; + let rate = config.sample_rate; + let (mut producer, consumer) = + RingBuffer::new((rate * buffer_ms / 1000) as usize * channels); + let stream = device + .build_input_stream( + config, + move |data: &[f32], _: &cpal::InputCallbackInfo| { + let n = producer.slots().min(data.len()); + if let Ok(chunk) = producer.write_chunk_uninit(n) { + chunk.fill_from_iter(data[..n].iter().copied()); + } + }, + |error| warn!(%error, "capture stream error"), + None, + ) + .map_err(device_error)?; + stream.play().map_err(device_error)?; + Ok(Self { _stream: stream, consumer, channels, rate }) + } + + /// Move everything captured so far into `out`. + pub fn read_available(&mut self, out: &mut Vec) { + let n = self.consumer.slots(); + if let Ok(chunk) = self.consumer.read_chunk(n) { + out.extend(chunk); + } + } +} + +/// Running playback stream. Write interleaved samples at the device's rate. +pub struct Playback { + _stream: cpal::Stream, + producer: Producer, + pub channels: usize, + pub rate: u32, +} + +impl Playback { + pub fn open_default(buffer_ms: u32) -> Result { + let device = cpal::default_host() + .default_output_device() + .ok_or_else(|| Error::Device("no output device".into()))?; + let config = device.default_output_config().map_err(device_error)?.config(); + let channels = config.channels as usize; + let rate = config.sample_rate; + let (producer, mut consumer) = + RingBuffer::::new((rate * buffer_ms / 1000) as usize * channels); + let stream = device + .build_output_stream( + config, + move |data: &mut [f32], _: &cpal::OutputCallbackInfo| { + let n = consumer.slots().min(data.len()); + if let Ok(chunk) = consumer.read_chunk(n) { + for (dst, src) in data.iter_mut().zip(chunk) { + *dst = src; + } + } + // Underrun: play silence. + data[n..].fill(0.0); + }, + |error| warn!(%error, "playback stream error"), + None, + ) + .map_err(device_error)?; + stream.play().map_err(device_error)?; + Ok(Self { _stream: stream, producer, channels, rate }) + } + + /// Queue samples; returns how many fit into the buffer. + pub fn write(&mut self, samples: &[f32]) -> usize { + let n = self.producer.slots().min(samples.len()); + if let Ok(chunk) = self.producer.write_chunk_uninit(n) { + chunk.fill_from_iter(samples[..n].iter().copied()); + } + n + } + + /// Samples that can be written without blocking. + pub fn free(&self) -> usize { + self.producer.slots() + } +} diff --git a/crates/tsc-audio/src/encode.rs b/crates/tsc-audio/src/encode.rs new file mode 100644 index 0000000..ea85746 --- /dev/null +++ b/crates/tsc-audio/src/encode.rs @@ -0,0 +1,140 @@ +//! Opus encoding into TeamSpeak voice packets. + +use opus2::{Application, Bitrate, Channels, Encoder}; +use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket}; + +use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE}; +use crate::{Error, Result}; + +/// Largest possible Opus packet. +const MAX_PACKET: usize = 1275; + +/// The two Opus codecs TeamSpeak channels use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VoiceCodec { + /// Mono, tuned for speech (`CodecType::OpusVoice`). + Voice, + /// Stereo, tuned for music (`CodecType::OpusMusic`). + Music, +} + +impl VoiceCodec { + pub fn channels(self) -> usize { + match self { + VoiceCodec::Voice => 1, + VoiceCodec::Music => 2, + } + } + + pub fn codec_type(self) -> CodecType { + match self { + VoiceCodec::Voice => CodecType::OpusVoice, + VoiceCodec::Music => CodecType::OpusMusic, + } + } + + /// Samples (all channels) in one 20 ms frame. + pub fn frame_len(self) -> usize { + FRAME_SAMPLES * self.channels() + } +} + +/// Encodes 20 ms frames of 48 kHz audio into voice packets. +pub struct VoiceEncoder { + encoder: Encoder, + codec: VoiceCodec, + out: Vec, +} + +impl VoiceEncoder { + pub fn new(codec: VoiceCodec) -> Result { + let (channels, application) = match codec { + VoiceCodec::Voice => (Channels::Mono, Application::Voip), + VoiceCodec::Music => (Channels::Stereo, Application::Audio), + }; + let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?; + // Survive some packet loss: TeamSpeak voice is plain UDP. + encoder.set_inband_fec(true)?; + encoder.set_packet_loss_perc(5)?; + Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] }) + } + + pub fn codec(&self) -> VoiceCodec { + self.codec + } + + /// Target bitrate in bits per second. + pub fn set_bitrate(&mut self, bps: i32) -> Result<()> { + self.encoder.set_bitrate(Bitrate::Bits(bps))?; + Ok(()) + } + + /// Encode one frame of [`VoiceCodec::frame_len`] interleaved samples. + pub fn encode_to_bytes(&mut self, frame: &[f32]) -> Result<&[u8]> { + if frame.len() != self.codec.frame_len() { + return Err(Error::Invalid(format!( + "frame has {} samples, expected {}", + frame.len(), + self.codec.frame_len() + ))); + } + let len = self.encoder.encode_float(frame, &mut self.out)?; + Ok(&self.out[..len]) + } + + /// Encode one frame into a packet ready for `Connection::send_audio`. + /// The connection assigns the packet id. + pub fn encode(&mut self, frame: &[f32]) -> Result { + let codec = self.codec.codec_type(); + let data = self.encode_to_bytes(frame)?; + Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data })) + } + + /// The empty packet that tells listeners the transmission ended. + pub fn end_of_stream(&self) -> OutPacket { + OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] }) + } +} + +#[cfg(test)] +mod tests { + use tsproto_packets::packets::{Direction, InAudioBuf}; + + use super::*; + use crate::pcm; + + /// Encode a tone, feed the packets through the mixer (jitter buffer + + /// decoder), and check the tone comes out. + #[test] + fn roundtrip_through_mixer() { + let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut mixer = crate::Mixer::new(); + let tone = pcm::sine(1000.0, 1.0, 0.5); + let mut decoded = Vec::new(); + for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() { + let data = encoder.encode_to_bytes(frame).unwrap().to_vec(); + let packet = OutAudio::new(&AudioData::S2C { + id: i as u16, + codec: CodecType::OpusVoice, + from: 7, + data: &data, + }); + let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap(); + mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap(); + let mut out = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut out); + decoded.extend(pcm::to_mono(&out, 2)); + } + // Skip the jitter buffer's initial latency and the codec warm-up. + let tail = &decoded[decoded.len() / 2..]; + let ratio = pcm::tone_ratio(tail, 1000.0, SAMPLE_RATE); + assert!(ratio > 0.8, "tone ratio {ratio}"); + } + + #[test] + fn rejects_wrong_frame_size() { + let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap(); + assert!(encoder.encode(&[0.0; FRAME_SAMPLES]).is_err()); + assert!(encoder.encode(&[0.0; FRAME_SAMPLES * 2]).is_ok()); + } +} diff --git a/crates/tsc-audio/src/framer.rs b/crates/tsc-audio/src/framer.rs new file mode 100644 index 0000000..7ba716f --- /dev/null +++ b/crates/tsc-audio/src/framer.rs @@ -0,0 +1,57 @@ +//! Cut a continuous sample stream into fixed-size frames. + +/// Buffers samples until a whole frame is available. +#[derive(Debug)] +pub struct Framer { + frame_len: usize, + buf: Vec, +} + +impl Framer { + /// `frame_len` is in samples (all channels, interleaved). + pub fn new(frame_len: usize) -> Self { + assert!(frame_len > 0); + Self { frame_len, buf: Vec::with_capacity(frame_len * 2) } + } + + /// Append samples and call `f` for every complete frame. + pub fn push(&mut self, samples: &[f32], mut f: impl FnMut(&[f32])) { + self.buf.extend_from_slice(samples); + let whole = self.buf.len() / self.frame_len * self.frame_len; + for frame in self.buf[..whole].chunks_exact(self.frame_len) { + f(frame); + } + self.buf.drain(..whole); + } + + /// Pad the remaining samples with silence into one last frame, if any. + pub fn flush(&mut self, f: impl FnOnce(&[f32])) { + if !self.buf.is_empty() { + self.buf.resize(self.frame_len, 0.0); + f(&self.buf); + self.buf.clear(); + } + } + + pub fn buffered(&self) -> usize { + self.buf.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frames_and_flushes() { + let mut framer = Framer::new(4); + let mut frames = Vec::new(); + framer.push(&[1.0, 2.0, 3.0], |f| frames.push(f.to_vec())); + assert!(frames.is_empty()); + framer.push(&[4.0, 5.0, 6.0, 7.0, 8.0, 9.0], |f| frames.push(f.to_vec())); + assert_eq!(frames, vec![vec![1.0, 2.0, 3.0, 4.0], vec![5.0, 6.0, 7.0, 8.0]]); + assert_eq!(framer.buffered(), 1); + framer.flush(|f| frames.push(f.to_vec())); + assert_eq!(frames[2], vec![9.0, 0.0, 0.0, 0.0]); + } +} diff --git a/crates/tsc-audio/src/lib.rs b/crates/tsc-audio/src/lib.rs new file mode 100644 index 0000000..9d71539 --- /dev/null +++ b/crates/tsc-audio/src/lib.rs @@ -0,0 +1,42 @@ +//! Voice pipeline building blocks. +//! +//! - [`pcm`]: sample-rate constants, tone generation and detection helpers +//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets +//! - [`framer`]: slice an arbitrary sample stream into codec frames +//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses +//! - [`wav`]: WAV file input/output +//! - [`Mixer`]: per-client jitter buffer, decoder and mixer (from the vendored +//! `tsclientlib::audio::AudioHandler`) +//! - `device` (feature `device`): capture and playback through cpal + +pub mod encode; +pub mod framer; +pub mod pcm; +pub mod resample; +pub mod wav; + +#[cfg(feature = "device")] +pub mod device; + +pub use encode::{VoiceCodec, VoiceEncoder}; +pub use framer::Framer; +pub use tsclientlib::audio::AudioHandler; + +/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender. +pub type Mixer = AudioHandler; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("opus: {0}")] + Opus(#[from] opus2::Error), + #[error("wav: {0}")] + Wav(#[from] hound::Error), + #[error("resampling failed: {0}")] + Resample(String), + #[error("audio device: {0}")] + Device(String), + #[error("invalid input: {0}")] + Invalid(String), +} + +pub type Result = std::result::Result; diff --git a/crates/tsc-audio/src/pcm.rs b/crates/tsc-audio/src/pcm.rs new file mode 100644 index 0000000..ade1a22 --- /dev/null +++ b/crates/tsc-audio/src/pcm.rs @@ -0,0 +1,101 @@ +//! PCM constants and helpers. + +use std::f32::consts::TAU; + +/// The sample rate TeamSpeak's Opus codecs run at. +pub const SAMPLE_RATE: u32 = 48_000; +/// Samples per channel in one 20 ms frame. +pub const FRAME_SAMPLES: usize = SAMPLE_RATE as usize / 50; + +/// A sine tone, mono, at [`SAMPLE_RATE`]. +pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec { + let n = (seconds * SAMPLE_RATE as f32) as usize; + (0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect() +} + +/// Average interleaved channels into mono. +pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec { + if channels <= 1 { + return interleaved.to_vec(); + } + interleaved.chunks_exact(channels).map(|f| f.iter().sum::() / channels as f32).collect() +} + +/// Duplicate mono samples into `channels` interleaved channels. +pub fn from_mono(mono: &[f32], channels: usize) -> Vec { + mono.iter().flat_map(|&s| std::iter::repeat_n(s, channels)).collect() +} + +/// Power of one frequency in `samples` (Goertzel algorithm), normalised so a +/// full-scale sine at `freq` gives about 0.25 per sample squared. +pub fn goertzel_power(samples: &[f32], freq: f32, rate: u32) -> f32 { + if samples.is_empty() { + return 0.0; + } + let coeff = 2.0 * (TAU * freq / rate as f32).cos(); + let (mut s1, mut s2) = (0.0f32, 0.0f32); + for &x in samples { + let s = x + coeff * s1 - s2; + s2 = s1; + s1 = s; + } + let power = s1 * s1 + s2 * s2 - coeff * s1 * s2; + power / (samples.len() as f32 * samples.len() as f32) +} + +/// Mean square of the signal. +pub fn energy(samples: &[f32]) -> f32 { + if samples.is_empty() { + return 0.0; + } + samples.iter().map(|s| s * s).sum::() / samples.len() as f32 +} + +/// Fraction of the signal energy at `freq`: close to 1 for a clean tone, +/// close to 0 for silence or noise. +pub fn tone_ratio(samples: &[f32], freq: f32, rate: u32) -> f32 { + let e = energy(samples); + if e < 1e-9 { + return 0.0; + } + // A sine of amplitude a has energy a²/2 and Goertzel power a²/4. + (2.0 * goertzel_power(samples, freq, rate) / e).min(1.0) +} + +/// Like [`tone_ratio`], but only over the 100 ms windows that are not silent, +/// so leading and trailing silence in a recording do not dilute the result. +pub fn voiced_tone_ratio(samples: &[f32], freq: f32, rate: u32) -> f32 { + let window = rate as usize / 10; + let ratios: Vec = samples + .chunks_exact(window) + .filter(|w| energy(w) > 1e-4) + .map(|w| tone_ratio(w, freq, rate)) + .collect(); + if ratios.is_empty() { 0.0 } else { ratios.iter().sum::() / ratios.len() as f32 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_tone() { + let tone = sine(1000.0, 0.5, 0.5); + assert!(tone_ratio(&tone, 1000.0, SAMPLE_RATE) > 0.95); + assert!(tone_ratio(&tone, 440.0, SAMPLE_RATE) < 0.05); + assert_eq!(tone_ratio(&[0.0; 100], 1000.0, SAMPLE_RATE), 0.0); + + let mut padded = vec![0.0; SAMPLE_RATE as usize]; + padded.extend(&tone); + padded.extend(vec![0.0; SAMPLE_RATE as usize]); + assert!(tone_ratio(&padded, 1000.0, SAMPLE_RATE) < 0.5); + assert!(voiced_tone_ratio(&padded, 1000.0, SAMPLE_RATE) > 0.95); + assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0); + } + + #[test] + fn channel_conversion() { + assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]); + assert_eq!(from_mono(&[1.0, 2.0], 2), vec![1.0, 1.0, 2.0, 2.0]); + } +} diff --git a/crates/tsc-audio/src/resample.rs b/crates/tsc-audio/src/resample.rs new file mode 100644 index 0000000..9b46ff9 --- /dev/null +++ b/crates/tsc-audio/src/resample.rs @@ -0,0 +1,49 @@ +//! Sample-rate conversion. + +use rubato::audioadapter_buffers::direct::InterleavedSlice; +use rubato::{Fft, FixedSync, Resampler}; + +use crate::{Error, Result}; + +/// Resample a whole interleaved clip from `from` Hz to `to` Hz. +pub fn resample_all(samples: &[f32], channels: usize, from: u32, to: u32) -> Result> { + if from == to || samples.is_empty() { + return Ok(samples.to_vec()); + } + if channels == 0 || !samples.len().is_multiple_of(channels) { + return Err(Error::Invalid(format!("{} samples for {channels} channels", samples.len()))); + } + let frames = samples.len() / channels; + let mut resampler = + Fft::::new(from as usize, to as usize, 1024, channels, FixedSync::Input) + .map_err(|e| Error::Resample(e.to_string()))?; + let input = InterleavedSlice::new(samples, channels, frames) + .map_err(|e| Error::Resample(e.to_string()))?; + let output = + resampler.process_all(&input, frames, None).map_err(|e| Error::Resample(e.to_string()))?; + Ok(output.take_data()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pcm; + + #[test] + fn keeps_tone_across_rates() { + // 1 kHz at 44.1 kHz, resampled to 48 kHz. + let n = 44_100; + let tone: Vec = (0..n) + .map(|i| 0.5 * (std::f32::consts::TAU * 1000.0 * i as f32 / 44_100.0).sin()) + .collect(); + let out = resample_all(&tone, 1, 44_100, 48_000).unwrap(); + assert!((out.len() as i64 - 48_000).abs() < 100, "len {}", out.len()); + assert!(pcm::tone_ratio(&out, 1000.0, 48_000) > 0.95); + } + + #[test] + fn passthrough_and_errors() { + assert_eq!(resample_all(&[1.0, 2.0], 1, 48_000, 48_000).unwrap(), vec![1.0, 2.0]); + assert!(resample_all(&[1.0, 2.0, 3.0], 2, 44_100, 48_000).is_err()); + } +} diff --git a/crates/tsc-audio/src/wav.rs b/crates/tsc-audio/src/wav.rs new file mode 100644 index 0000000..13cab33 --- /dev/null +++ b/crates/tsc-audio/src/wav.rs @@ -0,0 +1,65 @@ +//! WAV file input and output (float samples in memory). + +use std::path::Path; + +use hound::{SampleFormat, WavReader, WavSpec, WavWriter}; + +use crate::Result; + +/// Interleaved samples plus their format. +#[derive(Clone, Debug, PartialEq)] +pub struct Clip { + pub samples: Vec, + pub channels: usize, + pub rate: u32, +} + +pub fn read(path: &Path) -> Result { + let mut reader = WavReader::open(path)?; + let spec = reader.spec(); + let samples = match spec.sample_format { + SampleFormat::Float => reader.samples::().collect::>()?, + SampleFormat::Int => { + let scale = 1.0 / (1u64 << (spec.bits_per_sample - 1)) as f32; + reader + .samples::() + .map(|s| s.map(|s| s as f32 * scale)) + .collect::>()? + } + }; + Ok(Clip { samples, channels: spec.channels as usize, rate: spec.sample_rate }) +} + +/// Write 16-bit PCM. +pub fn write(path: &Path, clip: &Clip) -> Result<()> { + let spec = WavSpec { + channels: clip.channels as u16, + sample_rate: clip.rate, + bits_per_sample: 16, + sample_format: SampleFormat::Int, + }; + let mut writer = WavWriter::create(path, spec)?; + for &s in &clip.samples { + writer.write_sample((s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16)?; + } + writer.finalize()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip() { + let path = std::env::temp_dir().join(format!("tsc-audio-{}.wav", std::process::id())); + let clip = Clip { samples: vec![0.0, 0.5, -0.5, 0.25], channels: 2, rate: 48_000 }; + write(&path, &clip).unwrap(); + let back = read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!((back.channels, back.rate), (2, 48_000)); + for (a, b) in clip.samples.iter().zip(&back.samples) { + assert!((a - b).abs() < 1e-3); + } + } +} diff --git a/crates/tsc-store/Cargo.toml b/crates/tsc-store/Cargo.toml new file mode 100644 index 0000000..24fb376 --- /dev/null +++ b/crates/tsc-store/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "tsc-store" +version = "0.1.0" +description = "Local persistence: identities, bookmarks, settings, chat cache and secrets." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[features] +default = [] +# Store secrets in the OS keyring (Secret Service, Windows Credential Manager, Keychain). +keyring = ["dep:keyring"] + +[dependencies] +keyring = { version = "4.2.0", optional = true } +rusqlite = { version = "0.40.2", features = ["bundled"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +thiserror = "2.0.21" +tsclientlib = { path = "../proto/tsclientlib" } + +[lints] +workspace = true diff --git a/crates/tsc-store/src/lib.rs b/crates/tsc-store/src/lib.rs new file mode 100644 index 0000000..65be2ea --- /dev/null +++ b/crates/tsc-store/src/lib.rs @@ -0,0 +1,31 @@ +//! Local persistence for the client. +//! +//! One SQLite database holds identities, bookmarks, settings and a chat +//! cache. Passwords and query credentials never go into the database; they +//! live in a [`Secrets`] store (the OS keyring with the `keyring` feature). + +mod secrets; +mod store; + +#[cfg(feature = "keyring")] +pub use secrets::KeyringSecrets; +pub use secrets::{MemorySecrets, Secrets}; +pub use store::{ + Bookmark, ChatTarget, IdentityEntry, QueryConfig, QueryTransport, Store, StoredMessage, +}; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("database: {0}")] + Db(#[from] rusqlite::Error), + #[error("serialization: {0}")] + Json(#[from] serde_json::Error), + #[error("{0} {1} not found")] + NotFound(&'static str, i64), + #[error("secret store: {0}")] + Secrets(String), + #[error("io: {0}")] + Io(#[from] std::io::Error), +} + +pub type Result = std::result::Result; diff --git a/crates/tsc-store/src/secrets.rs b/crates/tsc-store/src/secrets.rs new file mode 100644 index 0000000..5b4f5d5 --- /dev/null +++ b/crates/tsc-store/src/secrets.rs @@ -0,0 +1,91 @@ +//! Storage for passwords and credentials. + +use std::collections::HashMap; +use std::sync::Mutex; + +use crate::Result; + +/// Key-value secret storage. `key` names what the secret is for, e.g. +/// `bookmark/3/server-password` or `bookmark/3/query-password`. +pub trait Secrets: Send + Sync { + fn get(&self, key: &str) -> Result>; + fn set(&self, key: &str, value: &str) -> Result<()>; + fn delete(&self, key: &str) -> Result<()>; +} + +/// In-memory secrets, for tests and platforms without a keyring. +#[derive(Default)] +pub struct MemorySecrets(Mutex>); + +impl Secrets for MemorySecrets { + fn get(&self, key: &str) -> Result> { + Ok(self.0.lock().unwrap().get(key).cloned()) + } + + fn set(&self, key: &str, value: &str) -> Result<()> { + self.0.lock().unwrap().insert(key.to_string(), value.to_string()); + Ok(()) + } + + fn delete(&self, key: &str) -> Result<()> { + self.0.lock().unwrap().remove(key); + Ok(()) + } +} + +/// The platform keyring: Secret Service on Linux, Credential Manager on +/// Windows, Keychain on macOS. +#[cfg(feature = "keyring")] +pub struct KeyringSecrets { + service: String, +} + +#[cfg(feature = "keyring")] +impl KeyringSecrets { + /// `service` distinguishes this application's entries, e.g. the app id. + pub fn new(service: impl Into) -> Self { + Self { service: service.into() } + } + + fn entry(&self, key: &str) -> Result { + keyring::Entry::new(&self.service, key).map_err(|e| crate::Error::Secrets(e.to_string())) + } +} + +#[cfg(feature = "keyring")] +impl Secrets for KeyringSecrets { + fn get(&self, key: &str) -> Result> { + match self.entry(key)?.get_password() { + Ok(v) => Ok(Some(v)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(crate::Error::Secrets(e.to_string())), + } + } + + fn set(&self, key: &str, value: &str) -> Result<()> { + self.entry(key)?.set_password(value).map_err(|e| crate::Error::Secrets(e.to_string())) + } + + fn delete(&self, key: &str) -> Result<()> { + match self.entry(key)?.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(crate::Error::Secrets(e.to_string())), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn memory_secrets() { + let s = MemorySecrets::default(); + assert_eq!(s.get("a").unwrap(), None); + s.set("a", "1").unwrap(); + assert_eq!(s.get("a").unwrap().as_deref(), Some("1")); + s.delete("a").unwrap(); + s.delete("a").unwrap(); + assert_eq!(s.get("a").unwrap(), None); + } +} diff --git a/crates/tsc-store/src/store.rs b/crates/tsc-store/src/store.rs new file mode 100644 index 0000000..8b43bc2 --- /dev/null +++ b/crates/tsc-store/src/store.rs @@ -0,0 +1,446 @@ +//! The SQLite database. + +use std::path::Path; + +use rusqlite::{Connection, OptionalExtension, params}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use tsclientlib::Identity; + +use crate::{Error, Result}; + +/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`. +const MIGRATIONS: &[&str] = &[r#" + CREATE TABLE identities ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + uid TEXT NOT NULL UNIQUE, + data TEXT NOT NULL, + created INTEGER NOT NULL DEFAULT (unixepoch()) + ); + CREATE TABLE bookmarks ( + id INTEGER PRIMARY KEY, + data TEXT NOT NULL, + position INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE messages ( + id INTEGER PRIMARY KEY, + server_uid TEXT NOT NULL, + target TEXT NOT NULL, + ts INTEGER NOT NULL, + author_uid TEXT, + author_name TEXT NOT NULL, + via_relay INTEGER NOT NULL DEFAULT 0, + text TEXT NOT NULL + ); + CREATE INDEX messages_by_target ON messages (server_uid, target, id); +"#]; + +/// A stored identity, without its private key. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityEntry { + pub id: i64, + pub name: String, + pub uid: String, + pub level: u8, +} + +/// How to reach a server's ServerQuery for invisible presence and relay chat. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct QueryConfig { + pub transport: QueryTransport, + pub host: String, + pub port: u16, + pub user: String, + /// Virtual server port to `use` (defaults to the voice port). + pub server_port: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum QueryTransport { + /// Raw TCP (TeamSpeak 3 only, port 10011). + Raw, + /// SSH (port 10022). + #[default] + Ssh, + /// HTTP WebQuery with an API key (TeamSpeak 6, port 10080/10443). No events. + Http, +} + +/// A saved server. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Bookmark { + /// Assigned by the store. + #[serde(skip)] + pub id: i64, + pub name: String, + /// host, host:port, or a server nickname. + pub address: String, + pub nickname: String, + /// Identity to connect with (`IdentityEntry::id`). + pub identity: Option, + pub default_channel: Option, + /// `wss://` URL of a companion gateway, for invisible presence and relay chat. + pub gateway_url: Option, + /// Own ServerQuery credentials (the password is kept in [`crate::Secrets`]). + pub query: Option, + /// Signed client version to present (`tsctl versions` spec), `None` for the default. + pub client_version: Option, +} + +impl Bookmark { + /// Secret key of the server password. + pub fn server_password_key(&self) -> String { + format!("bookmark/{}/server-password", self.id) + } + /// Secret key of the query password or API key. + pub fn query_password_key(&self) -> String { + format!("bookmark/{}/query-password", self.id) + } +} + +/// Where a chat message was posted. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ChatTarget { + Server, + Channel(u64), + /// Private chat with the client of this unique id. + Private(String), +} + +impl ChatTarget { + fn key(&self) -> String { + match self { + ChatTarget::Server => "server".into(), + ChatTarget::Channel(cid) => format!("channel/{cid}"), + ChatTarget::Private(uid) => format!("private/{uid}"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredMessage { + /// Assigned by the store; used for paging. + pub id: i64, + pub server_uid: String, + pub target: ChatTarget, + /// Unix timestamp in seconds. + pub ts: i64, + pub author_uid: Option, + pub author_name: String, + /// Received through a gateway/query relay instead of our own connection. + pub via_relay: bool, + pub text: String, +} + +pub struct Store { + db: Connection, +} + +impl Store { + /// Open or create the database at `path`. + pub fn open(path: &Path) -> Result { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let db = Connection::open(path)?; + // Identities contain private keys: keep the file private. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + db.pragma_update(None, "journal_mode", "WAL")?; + Self::init(db) + } + + pub fn open_in_memory() -> Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(db: Connection) -> Result { + db.pragma_update(None, "foreign_keys", true)?; + let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?; + for (i, migration) in MIGRATIONS.iter().enumerate().skip(version as usize) { + db.execute_batch(migration)?; + db.pragma_update(None, "user_version", i as i64 + 1)?; + } + Ok(Self { db }) + } + + // Identities + + pub fn add_identity(&self, name: &str, identity: &Identity) -> Result { + let uid = identity.key().to_pub().get_uid(); + self.db.execute( + "INSERT INTO identities (name, uid, data) VALUES (?1, ?2, ?3)", + params![name, uid, serde_json::to_string(identity)?], + )?; + Ok(self.db.last_insert_rowid()) + } + + pub fn identities(&self) -> Result> { + let mut stmt = self.db.prepare("SELECT id, name, uid, data FROM identities ORDER BY id")?; + let rows = stmt.query_map([], |r| { + Ok((r.get::<_, i64>(0)?, r.get(1)?, r.get(2)?, r.get::<_, String>(3)?)) + })?; + rows.map(|row| { + let (id, name, uid, data) = row?; + let identity: Identity = serde_json::from_str(&data)?; + Ok(IdentityEntry { id, name, uid, level: identity.level() }) + }) + .collect() + } + + pub fn identity(&self, id: i64) -> Result { + let data: Option = self + .db + .query_row("SELECT data FROM identities WHERE id = ?1", [id], |r| r.get(0)) + .optional()?; + let data = data.ok_or(Error::NotFound("identity", id))?; + Ok(serde_json::from_str(&data)?) + } + + /// Store an identity again, e.g. after its security level was improved. + pub fn update_identity(&self, id: i64, identity: &Identity) -> Result<()> { + let n = self.db.execute( + "UPDATE identities SET data = ?2 WHERE id = ?1", + params![id, serde_json::to_string(identity)?], + )?; + if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) } + } + + pub fn rename_identity(&self, id: i64, name: &str) -> Result<()> { + let n = + self.db.execute("UPDATE identities SET name = ?2 WHERE id = ?1", params![id, name])?; + if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) } + } + + pub fn delete_identity(&self, id: i64) -> Result<()> { + self.db.execute("DELETE FROM identities WHERE id = ?1", [id])?; + Ok(()) + } + + // Bookmarks + + pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result { + self.db.execute( + "INSERT INTO bookmarks (data, position) + VALUES (?1, (SELECT COALESCE(MAX(position), -1) + 1 FROM bookmarks))", + [serde_json::to_string(bookmark)?], + )?; + Ok(self.db.last_insert_rowid()) + } + + pub fn update_bookmark(&self, bookmark: &Bookmark) -> Result<()> { + let n = self.db.execute( + "UPDATE bookmarks SET data = ?2 WHERE id = ?1", + params![bookmark.id, serde_json::to_string(bookmark)?], + )?; + if n == 0 { Err(Error::NotFound("bookmark", bookmark.id)) } else { Ok(()) } + } + + pub fn bookmarks(&self) -> Result> { + let mut stmt = self.db.prepare("SELECT id, data FROM bookmarks ORDER BY position, id")?; + let rows = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))?; + rows.map(|row| { + let (id, data) = row?; + let mut bookmark: Bookmark = serde_json::from_str(&data)?; + bookmark.id = id; + Ok(bookmark) + }) + .collect() + } + + pub fn delete_bookmark(&self, id: i64) -> Result<()> { + self.db.execute("DELETE FROM bookmarks WHERE id = ?1", [id])?; + Ok(()) + } + + // Settings + + pub fn setting(&self, key: &str) -> Result> { + let value: Option = self + .db + .query_row("SELECT value FROM settings WHERE key = ?1", [key], |r| r.get(0)) + .optional()?; + value.map(|v| serde_json::from_str(&v).map_err(Error::from)).transpose() + } + + pub fn set_setting(&self, key: &str, value: &T) -> Result<()> { + self.db.execute( + "INSERT INTO settings (key, value) VALUES (?1, ?2) + ON CONFLICT (key) DO UPDATE SET value = excluded.value", + params![key, serde_json::to_string(value)?], + )?; + Ok(()) + } + + // Chat cache + + pub fn add_message(&self, msg: &StoredMessage) -> Result { + self.db.execute( + "INSERT INTO messages (server_uid, target, ts, author_uid, author_name, via_relay, text) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + msg.server_uid, + msg.target.key(), + msg.ts, + msg.author_uid, + msg.author_name, + msg.via_relay, + msg.text + ], + )?; + Ok(self.db.last_insert_rowid()) + } + + /// Up to `limit` messages older than `before` (message id), oldest first. + pub fn history( + &self, + server_uid: &str, + target: &ChatTarget, + before: Option, + limit: usize, + ) -> Result> { + let mut stmt = self.db.prepare( + "SELECT id, ts, author_uid, author_name, via_relay, text FROM messages + WHERE server_uid = ?1 AND target = ?2 AND id < ?3 + ORDER BY id DESC LIMIT ?4", + )?; + let rows = stmt.query_map( + params![server_uid, target.key(), before.unwrap_or(i64::MAX), limit as i64], + |r| { + Ok(StoredMessage { + id: r.get(0)?, + server_uid: server_uid.to_string(), + target: target.clone(), + ts: r.get(1)?, + author_uid: r.get(2)?, + author_name: r.get(3)?, + via_relay: r.get(4)?, + text: r.get(5)?, + }) + }, + )?; + let mut messages = rows.collect::>>()?; + messages.reverse(); + Ok(messages) + } + + /// Delete cached messages older than `ts` (Unix seconds). + pub fn prune_messages(&self, ts: i64) -> Result { + Ok(self.db.execute("DELETE FROM messages WHERE ts < ?1", [ts])?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identities() { + let store = Store::open_in_memory().unwrap(); + let identity = Identity::create(); + let id = store.add_identity("main", &identity).unwrap(); + let list = store.identities().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].name, "main"); + assert_eq!(list[0].uid, identity.key().to_pub().get_uid()); + assert!(list[0].level >= 8); + let loaded = store.identity(id).unwrap(); + assert_eq!(loaded.counter(), identity.counter()); + // The same key twice is rejected (uid is unique). + assert!(store.add_identity("dup", &identity).is_err()); + store.rename_identity(id, "renamed").unwrap(); + assert_eq!(store.identities().unwrap()[0].name, "renamed"); + store.delete_identity(id).unwrap(); + assert!(matches!(store.identity(id), Err(Error::NotFound(..)))); + } + + #[test] + fn bookmarks_keep_order_and_fields() { + let store = Store::open_in_memory().unwrap(); + let mut b = Bookmark { + name: "Home".into(), + address: "ts.example.org".into(), + nickname: "me".into(), + gateway_url: Some("wss://gw.example.org/v1".into()), + query: Some(QueryConfig { + transport: QueryTransport::Ssh, + host: "ts.example.org".into(), + port: 10022, + user: "me".into(), + server_port: None, + }), + ..Default::default() + }; + b.id = store.add_bookmark(&b).unwrap(); + let second = Bookmark { name: "Other".into(), ..Default::default() }; + store.add_bookmark(&second).unwrap(); + let list = store.bookmarks().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0], b); + assert_eq!(list[1].name, "Other"); + + b.nickname = "renamed".into(); + store.update_bookmark(&b).unwrap(); + assert_eq!(store.bookmarks().unwrap()[0].nickname, "renamed"); + assert_eq!(b.server_password_key(), format!("bookmark/{}/server-password", b.id)); + } + + #[test] + fn settings() { + let store = Store::open_in_memory().unwrap(); + assert_eq!(store.setting::("volume").unwrap(), None); + store.set_setting("volume", &80u32).unwrap(); + store.set_setting("volume", &90u32).unwrap(); + assert_eq!(store.setting::("volume").unwrap(), Some(90)); + } + + #[test] + fn chat_history_pages() { + let store = Store::open_in_memory().unwrap(); + let target = ChatTarget::Channel(5); + for i in 0..10 { + store + .add_message(&StoredMessage { + id: 0, + server_uid: "srv".into(), + target: target.clone(), + ts: 1000 + i, + author_uid: None, + author_name: "a".into(), + via_relay: i % 2 == 0, + text: format!("m{i}"), + }) + .unwrap(); + } + let last = store.history("srv", &target, None, 3).unwrap(); + let texts: Vec<_> = last.iter().map(|m| m.text.as_str()).collect(); + assert_eq!(texts, ["m7", "m8", "m9"]); + let older = store.history("srv", &target, Some(last[0].id), 3).unwrap(); + assert_eq!(older.iter().map(|m| m.text.as_str()).collect::>(), ["m4", "m5", "m6"]); + assert!(store.history("srv", &ChatTarget::Server, None, 3).unwrap().is_empty()); + assert_eq!(store.prune_messages(1005).unwrap(), 5); + } + + #[test] + fn reopen_keeps_data_and_schema() { + let dir = std::env::temp_dir().join(format!("tsc-store-{}", std::process::id())); + let path = dir.join("client.db"); + { + let store = Store::open(&path).unwrap(); + store.set_setting("k", &"v").unwrap(); + } + let store = Store::open(&path).unwrap(); + assert_eq!(store.setting::("k").unwrap().as_deref(), Some("v")); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index c1d8bf1..aa2d7af 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -6,6 +6,7 @@ # 1. connect + channel tree (channelsubscribeall) # 2. server chat between two clients # 3. channel chat between two clients +# 4. voice: a 1 kHz tone sent by one client is recorded by another # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) # Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl) @@ -77,6 +78,21 @@ chat_roundtrip() { grep -F "[$kind] sender" "$out" } +# One client records while another sends a tone; Goertzel checks the result. +voice_roundtrip() { + local addr=$1 out="$STATE_DIR/voice.log" + "$TSCTL" connect "$addr" --nick recorder voice record "$STATE_DIR/voice.wav" \ + --seconds 6 --expect-tone 1000 >"$out" 2>&1 & + local recorder=$! + sleep 2 + "$TSCTL" connect "$addr" --nick talker voice send --tone 1000 --seconds 2 >/dev/null + if ! wait "$recorder"; then + cat "$out" + fail "voice tone not received" + fi + grep "tone ratio" "$out" +} + for svc in "${SERVERS[@]}"; do port=${PORTS[$svc]:?unknown server $svc} addr="127.0.0.1:$port" @@ -91,6 +107,7 @@ for svc in "${SERVERS[@]}"; do # Guests may not use the server chat by default, so the sender is the admin. chat_roundtrip "$addr" server "$admin" chat_roundtrip "$addr" channel "" + voice_roundtrip "$addr" done log "all smoke tests passed" diff --git a/tools/tsctl/Cargo.toml b/tools/tsctl/Cargo.toml index bf0650b..e4f2fbb 100644 --- a/tools/tsctl/Cargo.toml +++ b/tools/tsctl/Cargo.toml @@ -21,6 +21,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } tsclientlib = { path = "../../crates/proto/tsclientlib" } tsproto-packets = { path = "../../crates/proto/tsproto-packets" } tsc-model = { path = "../../crates/tsc-model" } +tsc-audio = { path = "../../crates/tsc-audio", default-features = false } [lints] workspace = true diff --git a/tools/tsctl/src/main.rs b/tools/tsctl/src/main.rs index 104f03e..d40919c 100644 --- a/tools/tsctl/src/main.rs +++ b/tools/tsctl/src/main.rs @@ -4,6 +4,7 @@ mod identity; mod session; mod tree; mod versions; +mod voice; use std::path::PathBuf; use std::time::Duration; @@ -116,10 +117,43 @@ pub enum Action { /// Send a raw, already escaped command (e.g. `serveredit virtualserver_name=Test\\sServer`) /// and wait for the result. Combine with `--log-commands` to see the answer. Raw { command: String }, + /// Send or record voice in the current channel. + Voice { + #[command(subcommand)] + command: VoiceCommand, + }, /// Interactive session. Type `/help` for commands. Repl, } +#[derive(Subcommand, Debug, Clone)] +pub enum VoiceCommand { + /// Talk: send a WAV file or a test tone, in real time. + Send { + /// WAV file to send (any sample rate; resampled to 48 kHz). + file: Option, + /// Send a sine tone of this frequency instead of a file. + #[arg(long, conflicts_with = "file")] + tone: Option, + /// Tone length in seconds. + #[arg(long, default_value_t = 3.0)] + seconds: f32, + /// Use the stereo Opus Music codec instead of mono Opus Voice. + #[arg(long)] + music: bool, + }, + /// Listen: mix everything said in the channel into a stereo 48 kHz WAV file. + Record { + out: PathBuf, + /// Recording length in seconds. + #[arg(long, default_value_t = 5.0)] + seconds: f32, + /// Fail unless the recording contains this tone frequency (for tests). + #[arg(long)] + expect_tone: Option, + }, +} + #[derive(Subcommand, Debug, Clone)] pub enum ChatTarget { /// Send to the server chat (everyone on the server). diff --git a/tools/tsctl/src/session.rs b/tools/tsctl/src/session.rs index 1ca9dfa..b7c1b11 100644 --- a/tools/tsctl/src/session.rs +++ b/tools/tsctl/src/session.rs @@ -57,6 +57,7 @@ pub async fn run(args: ConnectArgs) -> Result<()> { let cmd = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, command); send_and_wait(&mut con, cmd, "command").await.map(|()| println!("ok")) } + Action::Voice { command } => crate::voice::run(&mut con, command).await, Action::Repl => repl(&mut con).await, }; @@ -65,14 +66,14 @@ pub async fn run(args: ConnectArgs) -> Result<()> { } /// What to do after handling one stream item. -enum Flow { +pub(crate) enum Flow { Continue, Stop, } /// How [`pump`] ended. #[derive(Debug, PartialEq, Eq)] -enum PumpEnd { +pub(crate) enum PumpEnd { Stopped, Deadline, Interrupted, @@ -80,7 +81,7 @@ enum PumpEnd { /// Drive the connection, handing every item to `handler` until it returns /// [`Flow::Stop`], the deadline passes, or Ctrl-C is pressed. -async fn pump( +pub(crate) async fn pump( con: &mut Connection, deadline: Option, mut handler: impl FnMut(&mut Connection, StreamItem) -> Result, diff --git a/tools/tsctl/src/voice.rs b/tools/tsctl/src/voice.rs new file mode 100644 index 0000000..aaa9521 --- /dev/null +++ b/tools/tsctl/src/voice.rs @@ -0,0 +1,112 @@ +//! `tsctl connect ... voice send|record`. + +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use tokio::time::Instant; +use tsc_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE}; +use tsc_audio::{Framer, Mixer, VoiceCodec, VoiceEncoder, resample, wav}; +use tsclientlib::{ClientId, Connection, StreamItem}; +use tsproto_packets::packets::AudioData; + +use crate::VoiceCommand; +use crate::session::{Flow, PumpEnd, pump}; + +const FRAME: Duration = Duration::from_millis(20); + +pub async fn run(con: &mut Connection, command: &VoiceCommand) -> Result<()> { + match command { + VoiceCommand::Send { file, tone, seconds, music } => { + let codec = if *music { VoiceCodec::Music } else { VoiceCodec::Voice }; + let samples = match (file, tone) { + (Some(path), _) => load(path, codec.channels())?, + (None, Some(freq)) => { + pcm::from_mono(&pcm::sine(*freq, *seconds, 0.5), codec.channels()) + } + (None, None) => bail!("pass a WAV file or --tone "), + }; + send(con, codec, &samples).await + } + VoiceCommand::Record { out, seconds, expect_tone } => { + let samples = record(con, Duration::from_secs_f32(*seconds)).await?; + let clip = wav::Clip { samples, channels: 2, rate: SAMPLE_RATE }; + wav::write(out, &clip)?; + let mono = pcm::to_mono(&clip.samples, 2); + println!( + "recorded {:.1} s to {} (energy {:.5})", + mono.len() as f32 / SAMPLE_RATE as f32, + out.display(), + pcm::energy(&mono) + ); + if let Some(freq) = expect_tone { + let ratio = pcm::voiced_tone_ratio(&mono, *freq, SAMPLE_RATE); + println!("{freq} Hz tone ratio: {ratio:.3}"); + if ratio < 0.5 { + bail!("expected a {freq} Hz tone, ratio {ratio:.3} < 0.5"); + } + } + Ok(()) + } + } +} + +/// Read a WAV file and convert it to 48 kHz with the codec's channel count. +fn load(path: &std::path::Path, channels: usize) -> Result> { + let clip = wav::read(path).with_context(|| format!("failed to read {}", path.display()))?; + let samples = resample::resample_all(&clip.samples, clip.channels, clip.rate, SAMPLE_RATE)?; + let mono = pcm::to_mono(&samples, clip.channels); + Ok(pcm::from_mono(&mono, channels)) +} + +/// Send in real time: one frame every 20 ms, driving the connection in between. +async fn send(con: &mut Connection, codec: VoiceCodec, samples: &[f32]) -> Result<()> { + let mut encoder = VoiceEncoder::new(codec)?; + let mut frames = Vec::new(); + let mut framer = Framer::new(codec.frame_len()); + framer.push(samples, |f| frames.push(f.to_vec())); + framer.flush(|f| frames.push(f.to_vec())); + + let mut next = Instant::now(); + for frame in &frames { + con.send_audio(encoder.encode(frame)?)?; + next += FRAME; + if pump(con, Some(next), |_, _| Ok(Flow::Continue)).await? == PumpEnd::Interrupted { + break; + } + } + con.send_audio(encoder.end_of_stream())?; + // Let the last packets go out. + pump(con, Some(Instant::now() + Duration::from_millis(200)), |_, _| Ok(Flow::Continue)).await?; + println!("sent {} frames ({:.1} s)", frames.len(), frames.len() as f32 * 0.02); + Ok(()) +} + +/// Collect voice for `length`, mixing all speakers into stereo. +async fn record(con: &mut Connection, length: Duration) -> Result> { + let mut mixer = Mixer::new(); + let mut out = Vec::new(); + let end = Instant::now() + length; + let mut next = Instant::now() + FRAME; + while next <= end { + let end = pump(con, Some(next), |_, item| { + if let StreamItem::Audio(packet) = item { + let from = match packet.data().data() { + AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from, + _ => return Ok(Flow::Continue), + }; + // Late or duplicate packets are expected on UDP; the mixer drops them. + let _ = mixer.handle_packet(ClientId(from), packet); + } + Ok(Flow::Continue) + }) + .await?; + let mut frame = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut frame); + out.extend_from_slice(&frame); + if end == PumpEnd::Interrupted { + break; + } + next += FRAME; + } + Ok(out) +}