diff --git a/.github/workflows/style_checks.yml b/.github/workflows/style_checks.yml index f1f0d1f..27757f6 100644 --- a/.github/workflows/style_checks.yml +++ b/.github/workflows/style_checks.yml @@ -17,10 +17,16 @@ jobs: toolchain: nightly components: clippy override: true - - uses: actions-rs/clippy-check@v1 + - name: Run clippy action to produce annotations + uses: actions-rs/clippy-check@v1 + if: steps.check_permissions.outputs.has-permission with: + toolchain: nightly token: ${{ secrets.GITHUB_TOKEN }} - args: --all-features + args: --workspace --all-targets --all-features + - name: Run clippy manually without annotations + if: ${{ !steps.check_permissions.outputs.has-permission }} + run: cargo +nightly clippy --workspace --all-targets --all-features check_fmt: name: Rust-fmt @@ -34,4 +40,4 @@ jobs: override: true - name: rustfmt run: | - cargo +nightly fmt -- --check + cargo +nightly fmt --all -- --check diff --git a/Cargo.lock b/Cargo.lock index a19cc4e..535f7ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] name = "aes" version = "0.6.0" @@ -51,9 +53,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.40" +version = "1.0.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b2cd92db5cbd74e8e5028f7e27dd7aa3090e89e4f2a197cc7c8dfb69c7063b" +checksum = "595d3cfa7a60d4555cb5067b99f07142a08ea778de5cf993f7b75c7d8fabc486" [[package]] name = "arrayvec" @@ -104,9 +106,15 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.6.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63396b8a4b9de3f4fdfb320ab6080762242f66a8ef174c49d8e19b674db4cdbe" +checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631" + +[[package]] +name = "byte-slice-cast" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c1bf4a04a88c54f589125563643d773f3254b5c38571395e2b591c693bbc81" [[package]] name = "cfb-mode" @@ -117,6 +125,15 @@ dependencies = [ "cipher", ] +[[package]] +name = "cfg-expr" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70a1d12766bbdd5d44caab5df04a9bffec9cd855a1b44b15de5665d70c085f94" +dependencies = [ + "smallvec", +] + [[package]] name = "cfg-if" version = "0.1.10" @@ -155,9 +172,9 @@ dependencies = [ [[package]] name = "const_fn" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "402da840495de3f976eaefc3485b7f5eb5b0bf9761f9a47be27fe975b3b8c2ec" +checksum = "f92cfa0fd5690b3cf8c1ef2cabbd9b7ef22fa53cf5e1f92b05103f6d5d1cf6e7" [[package]] name = "cookie-factory" @@ -191,9 +208,9 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" +checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -251,9 +268,9 @@ checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" [[package]] name = "env_logger" -version = "0.8.3" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17392a012ea30ef05a610aa97dfb49496e71c9f676b27879922ea5bdf60d9d3f" +checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3" dependencies = [ "atty", "humantime", @@ -292,42 +309,26 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fed34cd105917e91daa4da6b3728c47b068749d6a62c59811f06ed2ac71d9da7" -[[package]] -name = "futures" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d5813545e459ad3ca1bff9915e9ad7f1a47dc6a91b627ce321d5863b7dd253" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - [[package]] name = "futures-channel" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce79c6a52a299137a6013061e0cf0e688fce5d7f1bc60125f520912fdb29ec25" +checksum = "74ed2411805f6e4e3d9bc904c95d5d423b89b3b25dc0250aa74729de20629ff9" dependencies = [ "futures-core", - "futures-sink", ] [[package]] name = "futures-core" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "098cd1c6dda6ca01650f1a37a794245eb73181d0d4d4e955e2f3c37db7af1815" +checksum = "af51b1b4a7fdff033703db39de8802c673eb91855f2e0d47dcf3bf2c0ef01f99" [[package]] name = "futures-executor" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f6cb7042eda00f0049b1d2080aa4b93442997ee507eb3828e8bd7577f94c9d" +checksum = "4d0d535a57b87e1ae31437b892713aee90cd2d7b0ee48727cd11fc72ef54761c" dependencies = [ "futures-core", "futures-task", @@ -336,51 +337,33 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "365a1a1fb30ea1c03a830fdb2158f5236833ac81fa0ad12fe35b29cddc35cb04" - -[[package]] -name = "futures-macro" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668c6733a182cd7deb4f1de7ba3bf2120823835b3bcfbeacf7d2c4a773c1bb8b" -dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] +checksum = "0b0e06c393068f3a6ef246c75cdca793d6a46347e75286933e5e75fd2fd11582" [[package]] name = "futures-sink" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5629433c555de3d82861a7a4e3794a4c40040390907cfbfd7143a92a426c23" +checksum = "c0f30aaa67363d119812743aa5f33c201a7a66329f97d1a887022971feea4b53" [[package]] name = "futures-task" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba7aa51095076f3ba6d9a1f702f74bd05ec65f555d70d2033d55ba8d69f581bc" +checksum = "bbe54a98670017f3be909561f6ad13e810d9a51f3f061b902062ca3da80799f2" [[package]] name = "futures-util" -version = "0.3.14" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c144ad54d60f23927f0a6b6d816e4271278b64f005ad65e4e35291d2de9c025" +checksum = "67eb846bfd58e44a8481a00049e82c43e0ccb5d61f8dc071057cb19249dd4d78" dependencies = [ - "futures-channel", + "autocfg", "futures-core", - "futures-io", - "futures-macro", - "futures-sink", "futures-task", - "memchr", "pin-project-lite", "pin-utils", - "proc-macro-hack", - "proc-macro-nested", "slab", ] @@ -396,20 +379,16 @@ dependencies = [ [[package]] name = "gio" -version = "0.9.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb60242bfff700772dae5d9e3a1f7aa2e4ebccf18b89662a16acb2822568561" +checksum = "86c6823b39d46d22cac2466de261f28d7f049ebc18f7b35296a42c7ed8a88325" dependencies = [ "bitflags", - "futures", "futures-channel", "futures-core", "futures-io", - "futures-util", "gio-sys", "glib", - "glib-sys", - "gobject-sys", "libc", "once_cell", "thiserror", @@ -417,9 +396,9 @@ dependencies = [ [[package]] name = "gio-sys" -version = "0.10.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e24fb752f8f5d2cf6bbc2c606fd2bc989c81c5e2fe321ab974d54f8b6344eac" +checksum = "c0a41df66e57fcc287c4bcf74fc26b884f31901ea9792ec75607289b456f48fa" dependencies = [ "glib-sys", "gobject-sys", @@ -430,32 +409,31 @@ dependencies = [ [[package]] name = "glib" -version = "0.10.3" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c685013b7515e668f1b57a165b009d4d28cb139a8a989bbd699c10dad29d0c5" +checksum = "dbecad7a3a898ee749d491ce2ae0decb0bce9e736f9747bc49159b1cea5d37f4" dependencies = [ "bitflags", "futures-channel", "futures-core", "futures-executor", "futures-task", - "futures-util", "glib-macros", "glib-sys", "gobject-sys", "libc", "once_cell", + "smallvec", ] [[package]] name = "glib-macros" -version = "0.10.1" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41486a26d1366a8032b160b59065a59fb528530a46a49f627e7048fb8c064039" +checksum = "2aad66361f66796bfc73f530c51ef123970eb895ffba991a234fcf7bea89e518" dependencies = [ "anyhow", "heck", - "itertools", "proc-macro-crate", "proc-macro-error", "proc-macro2", @@ -465,9 +443,9 @@ dependencies = [ [[package]] name = "glib-sys" -version = "0.10.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e9b997a66e9a23d073f2b1abb4dbfc3925e0b8952f67efd8d9b6e168e4cdc1" +checksum = "1c1d60554a212445e2a858e42a0e48cece1bd57b311a19a9468f70376cf554ae" dependencies = [ "libc", "system-deps", @@ -475,9 +453,9 @@ dependencies = [ [[package]] name = "gobject-sys" -version = "0.10.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "952133b60c318a62bf82ee75b93acc7e84028a093e06b9e27981c2b6fe68218c" +checksum = "aa92cae29759dae34ab5921d73fff5ad54b3d794ab842c117e36cafc7994c3f5" dependencies = [ "glib-sys", "libc", @@ -486,9 +464,9 @@ dependencies = [ [[package]] name = "gstreamer" -version = "0.16.7" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ff5d0f7ff308ae37e6eb47b6ded17785bdea06e438a708cd09e0288c1862f33" +checksum = "1f71e8c163945a3e0140e6b1ed10d1507da7e71196fedec568cbad92db63d762" dependencies = [ "bitflags", "cfg-if 1.0.0", @@ -496,11 +474,10 @@ dependencies = [ "futures-core", "futures-util", "glib", - "glib-sys", - "gobject-sys", "gstreamer-sys", "libc", "muldiv", + "num-integer", "num-rational", "once_cell", "paste", @@ -510,29 +487,26 @@ dependencies = [ [[package]] name = "gstreamer-app" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc80888271338c3ede875d8cafc452eb207476ff5539dcbe0018a8f5b827af0e" +checksum = "d2ed9c3e9ce3a406ea5026c2d4e094acd8efd61084bb107f8ff97d13f739b542" dependencies = [ "bitflags", "futures-core", "futures-sink", "glib", - "glib-sys", - "gobject-sys", "gstreamer", "gstreamer-app-sys", "gstreamer-base", - "gstreamer-sys", "libc", "once_cell", ] [[package]] name = "gstreamer-app-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "813f64275c9e7b33b828b9efcf9dfa64b95996766d4de996e84363ac65b87e3d" +checksum = "41865cfb8a5ddfa1161734a0d068dcd4689da852be0910b40484206408cfeafa" dependencies = [ "glib-sys", "gstreamer-base-sys", @@ -543,25 +517,23 @@ dependencies = [ [[package]] name = "gstreamer-base" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bafd01c56f59cb10f4b5a10f97bb4bdf8c2b2784ae5b04da7e2d400cf6e6afcf" +checksum = "5cf50118e1933d9e9e043036f2306d0b9660182ea61a75f266cd9fb3607b7a19" dependencies = [ "bitflags", + "cfg-if 1.0.0", "glib", - "glib-sys", - "gobject-sys", "gstreamer", "gstreamer-base-sys", - "gstreamer-sys", "libc", ] [[package]] name = "gstreamer-base-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4b7b6dc2d6e160a1ae28612f602bd500b3fa474ce90bf6bb2f08072682beef5" +checksum = "28169a7b58edb93ad8ac766f0fa12dcd36a2af4257a97ee10194c7103baf3e27" dependencies = [ "glib-sys", "gobject-sys", @@ -572,28 +544,24 @@ dependencies = [ [[package]] name = "gstreamer-net" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ff4b9468ce5fc3d366374d6e156f4e66f316ef2580d4e6c6167a5a090f48996" +checksum = "46e71e9301725be01dcb2e260a531ab62fd42f3d4586de3da7060220b4f675a3" dependencies = [ "gio", "glib", - "glib-sys", - "gobject-sys", "gstreamer", "gstreamer-net-sys", - "gstreamer-sys", ] [[package]] name = "gstreamer-net-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5317f292e00d1e7b966a3876ca7568abdab3d0559b2c050d1dd3bbbef9c5b99f" +checksum = "6a36633587f9f1c34d5ed3ba5e7e2b4d89739fea2b9ee5ac101bb0685c35ad6b" dependencies = [ "gio-sys", "glib-sys", - "gobject-sys", "gstreamer-sys", "libc", "system-deps", @@ -601,52 +569,41 @@ dependencies = [ [[package]] name = "gstreamer-rtsp" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46370552813cfdf431f409dd5ffefa24ae80f3189a034ec098123f4cf1286389" +checksum = "398187f5b704e30e90f6bd2b75f0cee537b7c299dd5111d06b6bf7a8bd4305a2" dependencies = [ "bitflags", "glib", - "glib-sys", - "gobject-sys", "gstreamer", "gstreamer-rtsp-sys", "gstreamer-sdp", - "gstreamer-sdp-sys", - "gstreamer-sys", "libc", ] [[package]] name = "gstreamer-rtsp-server" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb39e0061d9aa519948276813e45249ae1cf41d098a04da490b085a1f2180466" +checksum = "2ca2a54cc0094a0d7926c12ae58de190f5883605bbe5ff7fb78b4a3832ca85f6" dependencies = [ "bitflags", "gio", - "gio-sys", "glib", - "glib-sys", - "gobject-sys", "gstreamer", "gstreamer-net", - "gstreamer-net-sys", "gstreamer-rtsp", "gstreamer-rtsp-server-sys", - "gstreamer-rtsp-sys", "gstreamer-sdp", - "gstreamer-sdp-sys", - "gstreamer-sys", "libc", "once_cell", ] [[package]] name = "gstreamer-rtsp-server-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "372f48e74995eb4855bac56210ea97d8cf34ef5b328c225f35bdbf3fdedd0d06" +checksum = "3ac39d406e3e7dd40b9dd6332b6193b1a40d2c9d7f4795579707589c951e32a6" dependencies = [ "gio-sys", "glib-sys", @@ -661,9 +618,9 @@ dependencies = [ [[package]] name = "gstreamer-rtsp-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0938ef76af0226e3d9488957b5bfdd3359d01adc1d3b4792e166bc2cec86f1be" +checksum = "244405aaa835f94f35cffed30bde7f2bc59bef5822ad747109921d429b7fb371" dependencies = [ "gio-sys", "glib-sys", @@ -676,26 +633,22 @@ dependencies = [ [[package]] name = "gstreamer-sdp" -version = "0.16.6" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2583808102240bf3e94b4dc5d099ee0ad36557211279c8b90b82c45c2b76e8" +checksum = "4fb915df42663a982c64d65c36e7de7963c96733ea591338c648cc124fc0b5c9" dependencies = [ "glib", - "glib-sys", - "gobject-sys", "gstreamer", "gstreamer-sdp-sys", - "gstreamer-sys", ] [[package]] name = "gstreamer-sdp-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "405adf64f61c427c1c3cd6d928f0ca891bde2614b7bd31c3b3670ae0da3ac79a" +checksum = "e37750f58494510976ac50e6c2ba1757e2270aca1086239bf02f576d63496201" dependencies = [ "glib-sys", - "gobject-sys", "gstreamer-sys", "libc", "system-deps", @@ -703,9 +656,9 @@ dependencies = [ [[package]] name = "gstreamer-sys" -version = "0.9.1" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1f154082d01af5718c5f8a8eb4f565a4ea5586ad8833a8fc2c2aa6844b601d" +checksum = "8188ba998999a4a16005c3984812807ff882a87f5f3457c3d5bbbfcbdf631ebd" dependencies = [ "glib-sys", "gobject-sys", @@ -715,18 +668,18 @@ dependencies = [ [[package]] name = "heck" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cbf45460356b7deeb5e3415b5563308c0a9b057c85e12b06ad551f98d0a6ac" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" dependencies = [ "unicode-segmentation", ] [[package]] name = "hermit-abi" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "322f4de77956e22ed0e5032c359a0f1273f1f7f0d79bfa3b8ffbc730d7fbcc5c" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" dependencies = [ "libc", ] @@ -786,6 +739,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "0.4.7" @@ -800,9 +762,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "lexical-core" -version = "0.7.5" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21f866863575d0e1d654fbeeabdc927292fdf862873dc3c96c6f753357e13374" +checksum = "6607c62aa161d23d17a9072cc5da0be67cdfc89d3afb1e8d9c842bebc2525ffe" dependencies = [ "arrayvec", "bitflags", @@ -813,9 +775,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.93" +version = "0.2.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9385f66bf6105b241aa65a61cb923ef20efc665cb9f9bb50ac2f0c4b7f378d41" +checksum = "320cfe77175da3a483efed4bc0adc1968ca050b098ce4f2f1c13a56626128790" [[package]] name = "log" @@ -861,31 +823,31 @@ dependencies = [ [[package]] name = "muldiv" -version = "0.2.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0419348c027fa7be448d2ae7ea0e4e04c2334c31dc4e74ab29f00a2a7ca69204" +checksum = "b5136edda114182728ccdedb9f5eda882781f35fa6e80cc360af12a8932507f3" [[package]] name = "neolink" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aes", + "anyhow", + "byte-slice-cast", "cfb-mode", "cookie-factory", "crossbeam", "env_logger", "err-derive", - "gio", - "glib", "gstreamer", "gstreamer-app", "gstreamer-rtsp", "gstreamer-rtsp-server", - "indoc", - "itertools", + "itertools 0.9.0", "lazy_static", "log", "md5", + "neolink_core", "nom", "regex", "serde", @@ -900,11 +862,31 @@ dependencies = [ "yaserde_derive", ] +[[package]] +name = "neolink_core" +version = "0.4.0" +dependencies = [ + "aes", + "cfb-mode", + "cookie-factory", + "env_logger", + "err-derive", + "indoc", + "log", + "md5", + "nom", + "socket2", + "time", + "xml-rs", + "yaserde", + "yaserde_derive", +] + [[package]] name = "nom" -version = "6.1.2" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7413f999671bd4745a7b624bd370a569fb6bc574b23c83a3c5ed2e453f3d5e2" +checksum = "9c5c51b9083a3c620fa67a2a635d1ce7d95b897e957d6b28ff9a5da960a103a6" dependencies = [ "bitvec", "funty", @@ -925,9 +907,9 @@ dependencies = [ [[package]] name = "num-rational" -version = "0.3.2" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" +checksum = "d41702bd167c2df5520b384281bc111a4b5efcf7fbc4c9c222c815b07e0a6a6a" dependencies = [ "autocfg", "num-integer", @@ -945,9 +927,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.7.2" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af8b08b04175473088b46763e51ee54da5f9a164bc162f615b91bc179dbf15a3" +checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" [[package]] name = "opaque-debug" @@ -969,9 +951,9 @@ checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] name = "pin-project-lite" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0e1f259c92177c30a4c9d177246edd0a3568b25756a977d0632cf8fa37e905" +checksum = "8d31d11c69a6b52a174b42bdc0c30e5e11670f90788b2c471c31c1d17d449443" [[package]] name = "pin-utils" @@ -993,10 +975,11 @@ checksum = "bc5c99d529f0d30937f6f4b8a86d988047327bb88d04d2c4afc356de74722131" [[package]] name = "proc-macro-crate" -version = "0.1.5" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" +checksum = "41fdbd1df62156fbc5945f4762632564d7d038153091c3fcf1067f6aef7cff92" dependencies = [ + "thiserror", "toml", ] @@ -1030,17 +1013,11 @@ version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" -[[package]] -name = "proc-macro-nested" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" - [[package]] name = "proc-macro2" -version = "1.0.26" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a152013215dca273577e18d2bf00fa862b89b24169fb78c4c95aeb07992c9cec" +checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612" dependencies = [ "unicode-xid", ] @@ -1062,9 +1039,9 @@ checksum = "941ba9d78d8e2f7ce474c015eea4d9c6d25b6a3327f9832ee29a4de27f91bbb8" [[package]] name = "regex" -version = "1.4.5" +version = "1.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957056ecddbeba1b26965114e191d2e8589ce74db242b6ea25fc4062427a5c19" +checksum = "2a26af418b574bd56588335b3a3659a65725d4e636eb1016c2f9e3b38c7cc759" dependencies = [ "aho-corasick", "memchr", @@ -1073,9 +1050,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.23" +version = "0.6.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5f089152e60f62d28b835fbff2cd2e8dc0baf1ac13343bef92ab7eed84548" +checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" [[package]] name = "rustc_version" @@ -1088,9 +1065,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb5d2a036dc6d2d8fd16fde3498b04306e29bd193bf306a57427019b823d5acd" +checksum = "61b3909d758bb75c79f23d4736fac9433868679d3ad2ea7a61e3c25cfda9a088" [[package]] name = "ryu" @@ -1121,18 +1098,18 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.125" +version = "1.0.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "558dc50e1a5a5fa7112ca2ce4effcb321b0300c0d4ccf0776a9f60cd89031171" +checksum = "f03b9878abf6d14e6779d3f24f07b2cfa90352cfec4acc5aab8f1ac7f146fae8" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.125" +version = "1.0.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b093b7a2bb58203b5da3056c05b4ec1fed827dcfdb37347a8841695263b3d06d" +checksum = "a024926d3432516606328597e0f224a51355a493b49fdd67e9209187cbe55ecc" dependencies = [ "proc-macro2", "quote", @@ -1141,9 +1118,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.64" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" +checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127" dependencies = [ "itoa", "ryu", @@ -1158,9 +1135,15 @@ checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d" [[package]] name = "slab" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" +checksum = "f173ac3d1a7e3b28003f40de0b5ce7fe2710f9b9dc3fc38664cebee46b3b6527" + +[[package]] +name = "smallvec" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" [[package]] name = "socket2" @@ -1245,9 +1228,9 @@ checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" [[package]] name = "structopt" -version = "0.3.21" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5277acd7ee46e63e5168a80734c9f6ee81b1367a7d8772a2d765df2a3705d28c" +checksum = "69b041cdcb67226aca307e6e7be44c8806423d83e018bd662360a93dabce4d71" dependencies = [ "clap", "lazy_static", @@ -1256,9 +1239,9 @@ dependencies = [ [[package]] name = "structopt-derive" -version = "0.4.14" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ba9cdfda491b814720b6b06e0cac513d922fc407582032e8706e9f137976f90" +checksum = "7813934aecf5f51a54775e00068c237de98489463968231a51746bbbc03f9c10" dependencies = [ "heck", "proc-macro-error", @@ -1269,15 +1252,15 @@ dependencies = [ [[package]] name = "strum" -version = "0.18.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57bd81eb48f4c437cadc685403cad539345bf703d78e63707418431cecd4522b" +checksum = "aaf86bbcfd1fa9670b7a129f64fc0c9fcbbfe4f1bc4210e9e98fe71ffc12cde2" [[package]] name = "strum_macros" -version = "0.18.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87c85aa3f8ea653bfd3ddf25f7ee357ee4d204731f6aa9ad04002306f6e2774c" +checksum = "d06aaeeee809dbc59eb4556183dd927df67db1540de5be8d3ec0b6636358a5ec" dependencies = [ "heck", "proc-macro2", @@ -1287,9 +1270,9 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.69" +version = "1.0.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48fe99c6bd8b1cc636890bcc071842de909d902c81ac7dab53ba33c421ab8ffb" +checksum = "1873d832550d4588c3dbc20f01361ab00bfe741048f71e3fecf145a7cc18b29c" dependencies = [ "proc-macro2", "quote", @@ -1298,9 +1281,9 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" +checksum = "474aaa926faa1603c40b7885a9eaea29b444d1cb2850cb7c0e37bb1a4182f4fa" dependencies = [ "proc-macro2", "quote", @@ -1310,11 +1293,14 @@ dependencies = [ [[package]] name = "system-deps" -version = "1.3.2" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3ecc17269a19353b3558b313bba738b25d82993e30d62a18406a24aba4649b" +checksum = "480c269f870722b3b08d2f13053ce0c2ab722839f472863c3e2d61ff3a1c2fa6" dependencies = [ + "anyhow", + "cfg-expr", "heck", + "itertools 0.10.1", "pkg-config", "strum", "strum_macros", @@ -1349,18 +1335,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.24" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0f4a65597094d4483ddaed134f409b2cb7c1beccf25201a9f73c719254fa98e" +checksum = "93119e4feac1cbe6c798c34d3a53ea0026b0b1de6a120deef895137c0529bfe2" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.24" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7765189610d8241a44529806d6fd1f2e0a08734313a35d5b3a556f92b381f3c0" +checksum = "060d69a0afe7796bf42e9e2ff91f5ee691fb15c53d38b4b62a9a53eb23164745" dependencies = [ "proc-macro2", "quote", @@ -1369,9 +1355,9 @@ dependencies = [ [[package]] name = "time" -version = "0.2.26" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08a8cbfbf47955132d0202d1662f49b2423ae35862aee471f3ba4b133358f372" +checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" dependencies = [ "const_fn", "libc", @@ -1394,9 +1380,9 @@ dependencies = [ [[package]] name = "time-macros-impl" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5c3be1edfad6027c69f5491cf4cb310d1a71ecd6af742788c6ff8bced86b8fa" +checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" dependencies = [ "proc-macro-hack", "proc-macro2", @@ -1407,9 +1393,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.2.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b5220f05bb7de7f3f53c7c065e1199b3172696fe2db9f9c4d8ad9b4ee74c342" +checksum = "848a1e1181b9f6753b5e96a092749e29b11d19ede67dfbbd6c7dc7e0f49b5338" dependencies = [ "tinyvec_macros", ] @@ -1446,18 +1432,18 @@ dependencies = [ [[package]] name = "unicode-normalization" -version = "0.1.17" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07fbfce1c8a97d547e8b5334978438d9d6ec8c20e38f56d4a4374d181493eaef" +checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" dependencies = [ "tinyvec", ] [[package]] name = "unicode-segmentation" -version = "1.7.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796" +checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b" [[package]] name = "unicode-width" @@ -1467,9 +1453,9 @@ checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" [[package]] name = "unicode-xid" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" [[package]] name = "unindent" @@ -1479,9 +1465,9 @@ checksum = "f14ee04d9415b52b3aeab06258a3f07093182b88ba0f9b8d203f211a7a7d41c7" [[package]] name = "url" -version = "2.2.1" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ccd964113622c8e9322cfac19eb1004a07e636c545f325da085d5cdde6f1f8b" +checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" dependencies = [ "form_urlencoded", "idna", @@ -1527,9 +1513,9 @@ checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" [[package]] name = "version-compare" -version = "0.0.10" +version = "0.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d63556a25bae6ea31b52e640d7c41d1ab27faba4ccb600013837a3d0b3994ca1" +checksum = "1c18c859eead79d8b95d09e4678566e8d70105c4e7b251f707a03df32442661b" [[package]] name = "version_check" @@ -1539,9 +1525,9 @@ checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" [[package]] name = "wasm-bindgen" -version = "0.2.73" +version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83240549659d187488f91f33c0f8547cbfef0b2088bc470c116d1d260ef623d9" +checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd" dependencies = [ "cfg-if 1.0.0", "wasm-bindgen-macro", @@ -1549,9 +1535,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.73" +version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae70622411ca953215ca6d06d3ebeb1e915f0f6613e3b495122878d7ebec7dae" +checksum = "3b33f6a0694ccfea53d94db8b2ed1c3a8a4c86dd936b13b9f0a15ec4a451b900" dependencies = [ "bumpalo", "lazy_static", @@ -1564,9 +1550,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.73" +version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e734d91443f177bfdb41969de821e15c516931c3c3db3d318fa1b68975d0f6f" +checksum = "088169ca61430fe1e58b8096c24975251700e7b1f6fd91cc9d59b04fb9b18bd4" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1574,9 +1560,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.73" +version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53739ff08c8a68b0fdbcd54c372b8ab800b1449ab3c9d706503bc7dd1621b2c" +checksum = "be2241542ff3d9f241f5e2cb6dd09b37efe786df8851c54957683a49f0987a97" dependencies = [ "proc-macro2", "quote", @@ -1587,9 +1573,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.73" +version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9a543ae66aa233d14bb765ed9af4a33e81b8b58d1584cf1b47ff8cd0b9e4489" +checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" [[package]] name = "winapi" @@ -1630,9 +1616,9 @@ checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214" [[package]] name = "xml-rs" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b07db065a5cf61a7e4ba64f29e67db906fb1787316516c4e6e5ff0fea1efcd8a" +checksum = "d2d7d3948613f75c98fd9328cfdcc45acc4d360655289d0a7d4ec931392200a3" [[package]] name = "yaserde" diff --git a/Cargo.toml b/Cargo.toml index dc2a4ce..3b2de33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,28 +1,29 @@ [package] name = "neolink" description = "A standards-compliant bridge to Reolink IP cameras" -version = "0.3.0" +version = "0.4.0" authors = ["George Hilliard "] edition = "2018" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[workspace] +members = [ + "crates/*", +] [dependencies] +neolink_core = { path = "crates/core", version = "0.4.0" } aes = "0.6" cfb-mode = "0.6" cookie-factory = "0.3" crossbeam = "0.7" -env_logger = "*" err-derive = "0.2" -glib = ">=0.10.3" -gio = "0.9" -gstreamer = "0.16" -gstreamer-app = "0.16" -gstreamer-rtsp = "0.16" -gstreamer-rtsp-server = { version = "0.16", features = ["v1_12", "v1_14"]} +env_logger = "*" +gstreamer = "0.17" +gstreamer-app = "0.17" +gstreamer-rtsp = "0.17" +gstreamer-rtsp-server = { version = "0.17", features = ["v1_12", "v1_14"]} lazy_static = "1.4" log = { version = "0.4" } -indoc = "0.3" itertools = "0.9" md5 = "0.7" nom = "6.1.2" @@ -37,3 +38,5 @@ yaserde_derive = "0.3.16" xml-rs = "0.8" validator = "0.10" validator_derive = "0.10" +byte-slice-cast = "1.0.0" +anyhow = "1.0.42" diff --git a/Dockerfile b/Dockerfile index 2ff879a..33c860c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,6 +42,6 @@ COPY --from=build \ /usr/local/bin/neolink COPY docker/entrypoint.sh /entrypoint.sh -CMD ["/usr/local/bin/neolink", "--config", "/etc/neolink.toml"] +CMD ["/usr/local/bin/neolink", "rtsp", "--config", "/etc/neolink.toml"] ENTRYPOINT ["/entrypoint.sh"] -EXPOSE 8554 +EXPOSE 8554 diff --git a/README.md b/README.md index 23acc2e..e3f239d 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ or your package manager on Linux. 5. Launch Neolink from a shell, passing your configuration file: ```bash - neolink --config my_config.toml + neolink rtsp --config my_config.toml ``` 6. Connect your NVR software to Neolink's RTSP server. @@ -295,6 +295,37 @@ Currently the dissector does not attempt to decode the Baichuan "extension" messages except `binaryData`. This will change in the future as reverse engineering needs require. +## Additional Commands + +Neolink also has some additional command line tools +for controlling the camera. They are all used through neolink subcommands like this: + + +```bash +neolink subcommand --config=... +``` + +The currently supported subcommands are + +- **rtsp**: The standard neolink rtsp bridge +- **status-light**: A command to control the LED status light +- **reboot**: Will reboot a camera +- **talk**: Will enable talk back through either the microphone or by + reading a sound file. + +For a full list of commands please use + +```bash +neolink help +``` + +For further details on the subcommands please use the following +where `` is replaced with the subcommand of interest + +```bash +neolink help +``` + ## License Neolink is free software, released under the GNU Affero General Public License diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 0000000..2728304 --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "neolink_core" +description = "Core services and structure for Reolink IP cameras" +version = "0.4.0" +authors = ["George Hilliard "] +edition = "2018" + +[dependencies] +aes = "0.6" +cfb-mode = "0.6" +cookie-factory = "0.3" +err-derive = "0.2" +log = { version = "0.4" } +md5 = "0.7" +nom = "6.1.2" +socket2 = "0.3" +time = "0.2" +yaserde = "0.3.16" +yaserde_derive = "0.3.16" +xml-rs = "0.8" + +[dev-dependencies] +env_logger = "*" +indoc = "0.3" diff --git a/src/bc/de.rs b/crates/core/src/bc/de.rs similarity index 89% rename from src/bc/de.rs rename to crates/core/src/bc/de.rs index 0d88354..6ce7d6f 100644 --- a/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -2,39 +2,33 @@ use super::model::*; use super::xml::{BcPayloads, BcXml}; use super::xml_crypto; use err_derive::Error; -use log::*; use nom::IResult; use nom::{bytes::streaming::take, combinator::*, number::streaming::*, sequence::*}; use std::io::Read; +/// The error types used during deserialisation #[derive(Debug, Error)] pub enum Error { + /// A Nom parsing error usually a malformed packet #[error(display = "Parsing error")] - NomError(&'static str), + NomError(String), + /// An IO error such as the stream being dropped #[error(display = "I/O error")] IoError(#[error(source)] std::io::Error), } - type NomErrorType<'a> = nom::error::Error<&'a [u8]>; impl<'a> From>> for Error { fn from(k: nom::Err>) -> Self { let reason = match k { - nom::Err::Error(_) => "Nom Error", - nom::Err::Failure(_) => "Nom Failure", - _ => "Unknown Nom error", + nom::Err::Error(e) => format!("Nom Error: {:?}", e), + nom::Err::Failure(e) => format!("Nom Error: {:?}", e), + _ => "Unknown Nom error".to_string(), }; Error::NomError(reason) } } -impl Bc { - pub fn deserialize(context: &mut BcContext, r: R) -> Result { - // Throw away the nom-specific return types - read_from_reader(|reader| bc_msg(context, reader), r) - } -} - fn read_from_reader(mut parser: P, mut rdr: R) -> Result where R: Read, @@ -54,19 +48,38 @@ where Err(e) => return Err(e.into()), }; - if 0 == (&mut rdr) - .take(to_read.get() as u64) - .read_to_end(&mut input)? - { - return Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "Read returned 0 bytes", - ) - .into()); + loop { + match (&mut rdr) + .take(to_read.get() as u64) + .read_to_end(&mut input) + { + Ok(0) => { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } + Ok(_) => break, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + // This is a temporaily unavaliable resource + // We should just wait and try again + } + Err(e) => { + return Err(e.into()); + } + } } } } +impl Bc { + pub(crate) fn deserialize(context: &mut BcContext, r: R) -> Result { + // Throw away the nom-specific return types + read_from_reader(|reader| bc_msg(context, reader), r) + } +} + fn bc_msg<'a, 'b>(context: &'a mut BcContext, buf: &'b [u8]) -> IResult<&'b [u8], Bc> { let (buf, header) = bc_header(buf)?; let (buf, body) = bc_body(context, &header, buf)?; @@ -207,8 +220,8 @@ fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { Ok(( buf, BcHeader { - msg_id, body_len, + msg_id, channel_id, stream_type, msg_num, @@ -245,7 +258,7 @@ fn test_bc_modern_login() { })), .. }) => assert_eq!(encryption.nonce, "9E6D1FCB9E69846D"), - _ => assert!(false), + _ => panic!(), } } @@ -271,7 +284,7 @@ fn test_bc_legacy_login() { assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0"); assert_eq!(password, EMPTY_LEGACY_PASSWORD); } - _ => assert!(false), + _ => panic!(), } } @@ -296,10 +309,8 @@ fn test_bc_modern_login_failed() { BcBody::ModernMsg(ModernMsg { extension: None, payload: None, - }) => { - assert!(true); - } - _ => assert!(false), + }) => {} + _ => panic!(), } } @@ -327,8 +338,8 @@ fn test_bc_modern_login_success() { BcBody::ModernMsg(ModernMsg { extension: None, payload: Some(_), - }) => assert!(true), - _ => assert!(false), + }) => {} + _ => panic!(), } } @@ -353,7 +364,7 @@ fn test_bc_binary_mode() { }) => { assert_eq!(bin.len(), 32); } - _ => assert!(false), + _ => panic!(), } context.in_bin_mode.insert(msg1.meta.msg_num); @@ -365,6 +376,6 @@ fn test_bc_binary_mode() { }) => { assert_eq!(bin.len(), 30344); } - _ => assert!(false), + _ => panic!(), } } diff --git a/crates/core/src/bc/mod.rs b/crates/core/src/bc/mod.rs new file mode 100644 index 0000000..0791328 --- /dev/null +++ b/crates/core/src/bc/mod.rs @@ -0,0 +1,41 @@ +//! The Baichuan message format is a 20 byte header, the contents of which vary between legacy and +//! modern messages: +//! +//! +//! +//! This header is followed by the message body. In legacy messages, the bodies are +//! message-specific binary formats. Currently, we only attempt to interpret the legacy login +//! message, as it is all that is needed to upgrade to the modern XML-based messages. Modern +//! messages are either "encrypted" XML (the encryption is a simple XOR routine or AES) +//! or binary data. +//! +//! --- +//! +//! # Payloads +//! Messages contain one-two payloads seperated by the payload_offset in the header +//! +//! ## Extension Payload +//! The first payload prior to the payload_offset is the extension xml +//! +//! This contains meta data on the following payload such as channel_id or content type +//! (xml or binary) +//! +//! ## Payload +//! The second payload which is the primary payload coming after the payload offset +//! depends on the MsgID. +//! +//! It is usually XML except in the case of video and talk MsgIDs +//! which are binary data in the bc media packet format +//! + +/// Contains the structure of the messages such as headers and payloads +pub mod model; + +/// Contains code related to the deserialisation of the bc packets +pub mod de; +/// `Contains code related to the serialisation of the bc packets +pub mod ser; +/// Contains the structs for the know xmls of payloads and extension +pub mod xml; + +mod xml_crypto; diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs new file mode 100644 index 0000000..588e282 --- /dev/null +++ b/crates/core/src/bc/model.rs @@ -0,0 +1,288 @@ +pub use super::xml::{BcPayloads, BcXml, Extension}; +use std::collections::HashSet; +use std::sync::{Arc, Mutex}; + +pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; + +/// Login messages have this ID +pub const MSG_ID_LOGIN: u32 = 1; +/// Logout messages have this ID +pub const MSG_ID_LOGOUT: u32 = 2; +/// Video and Audio Streams messages have this ID +pub const MSG_ID_VIDEO: u32 = 3; +/// TalkAbility messages have this ID +pub const MSG_ID_TALKABILITY: u32 = 10; +/// TalkReset messages have this ID +pub const MSG_ID_TALKRESET: u32 = 11; +/// Reboot messages have this ID +pub const MSG_ID_REBOOT: u32 = 23; +/// Version messages have this ID +pub const MSG_ID_VERSION: u32 = 80; +/// Ping messages have this ID +pub const MSG_ID_PING: u32 = 93; +/// General system info messages have this ID +pub const MSG_ID_GET_GENERAL: u32 = 104; +/// Setting general system info (clock mostly) messages have this ID +pub const MSG_ID_SET_GENERAL: u32 = 105; +/// Will send the talk config for talk back data to follow this msg +pub const MSG_ID_TALKCONFIG: u32 = 201; +/// Used to send talk back binary data +pub const MSG_ID_TALK: u32 = 202; +/// Getting the LED status is done with this ID +pub const MSG_ID_GET_LED_STATUS: u32 = 208; +/// Setting the LED status is done with this ID +pub const MSG_ID_SET_LED_STATUS: u32 = 209; + +/// An empty password in legacy format +pub const EMPTY_LEGACY_PASSWORD: &str = + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + +/// Top level bc message +#[derive(Debug, PartialEq, Eq)] +pub struct Bc { + /// header part of the message + pub meta: BcMeta, + /// body part of the message which can either be Legacy or Modern + pub body: BcBody, +} + +/// +/// The body of a bc message is either legacy or modern +/// +#[derive(Debug, PartialEq, Eq)] +#[allow(clippy::large_enum_variant)] +pub enum BcBody { + /// Legacy is unsupported except for login where it is used + /// to negociate the initial login and upgrade to modern + LegacyMsg(LegacyMsg), + /// Modern is the current reolink protocol it is mostly + /// xml based + ModernMsg(ModernMsg), +} + +/// Modern messages have two payloads split by the `payload_offset` in the header +/// +/// The first payload is extension which describes the second payload. If the +/// `payload_offset` is `0` then their is no `extension` (usually because it has +/// already been negociated in a previous message) and it is `None` +/// +/// The second payload contains the actual data of interest and is all bytes after +/// the `payload_offset` up to the `body_len`. If `payload_offset` +/// equals `body_len` then there is not payload and it is `None` +/// +/// If `payload_offset` is `0` and equal to `body_len` then there is neither +/// `extension` or `payload` these are header only messages. This usually occurs to acknoledge receipt +/// of a command. In such cases the header `response_code` should be checked. +/// +#[derive(Debug, Default, PartialEq, Eq)] +pub struct ModernMsg { + /// Extension describes the following payload such as which channel id it is for + pub extension: Option, + /// Primary payload which is dependant on MsgID + pub payload: Option, +} + +/// Legacy login formats. Only login is supported +#[derive(Debug, PartialEq, Eq)] +pub enum LegacyMsg { + /// Legacy login data is constructed from username and password + /// that will (usually but not always, depending on camera) be hashed + LoginMsg { + /// Username for a legacy login + username: String, + /// Password for a legacy login + password: String, + }, + /// Any other type of legacy message will be collected here + UnknownMsg, +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) struct BcHeader { + pub body_len: u32, + pub msg_id: u32, + pub channel_id: u8, + pub stream_type: u8, + pub msg_num: u16, + pub response_code: u16, + pub class: u16, + pub payload_offset: Option, +} + +/// The components of the Baichuan TLV header that are not +/// descriptions of the Body (the application dictates these) +#[derive(Debug, PartialEq, Eq)] +pub struct BcMeta { + /// Message ID dictaes the major content of the message + pub msg_id: u32, + /// In most cases 0 but can be other values for NVRs + pub channel_id: u8, + /// In most cases this is unimportant but 0 means Clear Stream while 1 means Fluent stream + /// This is only really used during `[MSG_ID_VIDEO]` streams when the SD `subStreams` are requested + pub stream_type: u8, + /// On modern messages this is the response code + /// When sending a command it is set to `0`. The reply from the camera can be + /// - `200` for OK + /// - `400` for bad request + /// A malformed packet will return a `400` code + pub response_code: u16, + /// A message ID is used to match replies with requests. The camera will parrot back + /// this number in its reply + /// + /// If there a message is too long to fit in one packet it will be split over multiple + /// messages all with the same `msg_num` (this can happing in video streams, talk and when + /// sending a firmware update) + pub msg_num: u16, + /// The class is mostly an unknown quanitiy but does dictate the size of the header + /// know values are + /// + /// - 0x6514: "legacy" 20 bytes + /// - 0x6614: "modern" 20 bytes + /// - 0x6414: "modern" 24 bytes + /// - 0x0000: "modern" 24 bytes + pub class: u16, +} + +/// The components of the Baichuan header that must be filled out after the body is serialized, or +/// is needed for the deserialization of the body (strictly part of the wire format of the message) +#[derive(Debug, PartialEq, Eq)] +pub(super) struct BcSendInfo { + pub body_len: u32, + pub payload_offset: Option, +} + +/// These are the encyption modes supported by the camera +/// +/// The mode is negociated during login +#[derive(Debug, Clone)] +pub enum EncryptionProtocol { + /// Older camera use no encryption + Unencrypted, + /// Camera/Firmwares before 2021 use BCEncrypt which is a simple XOr + BCEncrypt, + /// Latest cameras/firmwares use Aes with the key derived from + /// the camera's password and the negociated NONCE + Aes(Option<[u8; 16]>), +} + +#[derive(Debug)] +pub(crate) struct BcContext { + pub(super) in_bin_mode: HashSet, + // Arc> because it is shared between context + // and connection for deserialisation and serialistion respectivly + pub(super) encryption_protocol: Arc>, +} + +impl Bc { + /// Constructs a xml payload only Bc message + pub fn new_from_xml(meta: BcMeta, xml: BcXml) -> Bc { + Self::new(meta, None, Some(BcPayloads::BcXml(xml))) + } + + /// Constructs an Extension only Bc message + pub fn new_from_ext(meta: BcMeta, ext: Extension) -> Bc { + Self::new(meta, Some(ext), None) + } + + /// Constucts a header only Bc message + pub fn new_from_meta(meta: BcMeta) -> Bc { + Self::new(meta, None, None) + } + + /// Constructs a message with both extension and xml payload + pub fn new_from_ext_xml(meta: BcMeta, ext: Extension, xml: BcXml) -> Bc { + Self::new(meta, Some(ext), Some(BcPayloads::BcXml(xml))) + } + + /// General method to constructs a Bc message + /// + /// Use this if your constructing a binary payload but otherwise the other constructors + /// are better suited to the task + pub fn new(meta: BcMeta, extension: Option, payload: Option) -> Bc { + Bc { + meta, + body: BcBody::ModernMsg(ModernMsg { extension, payload }), + } + } +} + +impl BcContext { + pub(crate) fn new(encryption_protocol: Arc>) -> BcContext { + BcContext { + in_bin_mode: HashSet::new(), + encryption_protocol, + } + } + + pub(crate) fn set_encrypted(&mut self, encryption_protocol: EncryptionProtocol) { + *(self.encryption_protocol.lock().unwrap()) = encryption_protocol; + } + + pub(crate) fn get_encrypted(&self) -> EncryptionProtocol { + (*(self.encryption_protocol.lock().unwrap())).clone() + } +} + +impl BcHeader { + /// Check if this header corresponds to a known modern message class + pub fn is_modern(&self) -> bool { + // Most modern messages have an extra word at the end of the header; this + // serves as the start offset of the appended payload data, if any. + // A notable exception is the encrypted reply to the login message; + // in this case the message is modern (with XML encryption etc), but there is + // no extra word. + // Here are the message classes: + // 0x6514: legacy, no bin offset (initial login message, encrypted or not) + // 0x6614: modern, no bin offset (reply to encrypted 0x6514 login) + // 0x6414: modern, has bin offset, encrypted if supported (re-sent login message) + // 0x0000, modern, has bin offset (most modern messages) + self.class != 0x6514 + } + + /// Converts a header into a `BcMeta` this mostly works by striping aspects that are + /// not desciptions of the data such as `msg_len` + pub fn to_meta(&self) -> BcMeta { + BcMeta { + msg_id: self.msg_id, + msg_num: self.msg_num, + channel_id: self.channel_id, + response_code: self.response_code, + stream_type: self.stream_type, + class: self.class, + } + } + + /// Constuct a [`BcHeader`] from a [`BcMeta`] + /// + /// This requires additional data such as the `body_len` + /// + /// # Parameters + /// + /// * `meta` - the [`BcMeta`] to convert + /// + /// * `body_len` - The length of the body (extension and payload) in bytes + /// + /// * `payload_offset` - The location in bytes where the payload starts and extension ends + /// + /// # Returns + /// + /// returns the new `BcHeader` + /// + pub fn from_meta(meta: &BcMeta, body_len: u32, payload_offset: Option) -> BcHeader { + BcHeader { + payload_offset, + body_len, + msg_id: meta.msg_id, + channel_id: meta.channel_id, + stream_type: meta.stream_type, + response_code: meta.response_code, + msg_num: meta.msg_num, + class: meta.class, + } + } +} + +pub(super) fn has_payload_offset(class: u16) -> bool { + // See BcHeader::is_modern() for a description of which packets have the bin offset + class == 0x6414 || class == 0x0000 +} diff --git a/src/bc/samples/EncryptionProtocol02_login.pcapng b/crates/core/src/bc/samples/EncryptionProtocol02_login.pcapng similarity index 100% rename from src/bc/samples/EncryptionProtocol02_login.pcapng rename to crates/core/src/bc/samples/EncryptionProtocol02_login.pcapng diff --git a/src/bc/samples/e1_firmwareupgrade.pcapng b/crates/core/src/bc/samples/e1_firmwareupgrade.pcapng similarity index 100% rename from src/bc/samples/e1_firmwareupgrade.pcapng rename to crates/core/src/bc/samples/e1_firmwareupgrade.pcapng diff --git a/src/bc/samples/model_sample_legacy_login.bin b/crates/core/src/bc/samples/model_sample_legacy_login.bin similarity index 100% rename from src/bc/samples/model_sample_legacy_login.bin rename to crates/core/src/bc/samples/model_sample_legacy_login.bin diff --git a/src/bc/samples/model_sample_modern_login.bin b/crates/core/src/bc/samples/model_sample_modern_login.bin similarity index 100% rename from src/bc/samples/model_sample_modern_login.bin rename to crates/core/src/bc/samples/model_sample_modern_login.bin diff --git a/src/bc/samples/modern_login_failed.bin b/crates/core/src/bc/samples/modern_login_failed.bin similarity index 100% rename from src/bc/samples/modern_login_failed.bin rename to crates/core/src/bc/samples/modern_login_failed.bin diff --git a/src/bc/samples/modern_login_success.bin b/crates/core/src/bc/samples/modern_login_success.bin similarity index 100% rename from src/bc/samples/modern_login_success.bin rename to crates/core/src/bc/samples/modern_login_success.bin diff --git a/src/bc/samples/modern_video_start1.bin b/crates/core/src/bc/samples/modern_video_start1.bin similarity index 100% rename from src/bc/samples/modern_video_start1.bin rename to crates/core/src/bc/samples/modern_video_start1.bin diff --git a/src/bc/samples/modern_video_start2.bin b/crates/core/src/bc/samples/modern_video_start2.bin similarity index 100% rename from src/bc/samples/modern_video_start2.bin rename to crates/core/src/bc/samples/modern_video_start2.bin diff --git a/src/bc/samples/xml_crypto_sample1.bin b/crates/core/src/bc/samples/xml_crypto_sample1.bin similarity index 100% rename from src/bc/samples/xml_crypto_sample1.bin rename to crates/core/src/bc/samples/xml_crypto_sample1.bin diff --git a/src/bc/samples/xml_crypto_sample1_plaintext.bin b/crates/core/src/bc/samples/xml_crypto_sample1_plaintext.bin similarity index 100% rename from src/bc/samples/xml_crypto_sample1_plaintext.bin rename to crates/core/src/bc/samples/xml_crypto_sample1_plaintext.bin diff --git a/src/bc/ser.rs b/crates/core/src/bc/ser.rs similarity index 97% rename from src/bc/ser.rs rename to crates/core/src/bc/ser.rs index bd33b7d..f2770ff 100644 --- a/src/bc/ser.rs +++ b/crates/core/src/bc/ser.rs @@ -8,10 +8,11 @@ use cookie_factory::{GenError, SerializeFn, WriteContext}; use log::error; use std::io::Write; +/// The error types used during serialisation pub type Error = GenError; impl Bc { - pub fn serialize( + pub(crate) fn serialize( &self, buf: W, encryption_protocol: &EncryptionProtocol, @@ -34,7 +35,7 @@ impl Bc { // Now get the offset of the payload payload_offset = if has_payload_offset(self.meta.class) { // If we're required to put binary length, put 0 if we have no binary - Some(if modern.payload.is_some() { + Some(if modern.extension.is_some() { ext_len as u32 } else { 0 diff --git a/src/bc/xml.rs b/crates/core/src/bc/xml.rs similarity index 52% rename from src/bc/xml.rs rename to crates/core/src/bc/xml.rs index 85f3e27..1aea64a 100644 --- a/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -9,11 +9,15 @@ use yaserde_derive::{YaDeserialize, YaSerialize}; #[cfg(test)] use indoc::indoc; +/// There are two types of payloads xml and binary #[derive(PartialEq, Eq, Debug, YaDeserialize)] #[yaserde(flatten)] pub enum BcPayloads { + /// XML payloads are the more common ones and include payloads for camera controls #[yaserde(rename = "body")] BcXml(BcXml), + /// Binary payloads are received from the camera for streams and sent to the camera + /// for talk-back and firmware updates #[yaserde(flatten)] Binary(Vec), } @@ -25,71 +29,102 @@ impl Default for BcPayloads { } } +/// The top level BC Xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] #[yaserde(rename = "body")] pub struct BcXml { + /// Encryption xml is received during login and contain the NONCE #[yaserde(rename = "Encryption")] pub encryption: Option, + /// LoginUser xml is used during modern login #[yaserde(rename = "LoginUser")] pub login_user: Option, + /// LoginNet xml is used during modern login #[yaserde(rename = "LoginNet")] pub login_net: Option, + /// The final part of a login sequence will return DeviceInfo xml #[yaserde(rename = "DeviceInfo")] pub device_info: Option, + /// The VersionInfo xml is recieved in reply to a version request #[yaserde(rename = "VersionInfo")] pub version_info: Option, + /// Preview xml is used as part of the stream request to set the stream quality and channel #[yaserde(rename = "Preview")] pub preview: Option, #[yaserde(rename = "SystemGeneral")] + /// SystemGeneral xml is sent or recieved as part of the clock get/setting pub system_general: Option, + /// Received as part of the Genral system info request #[yaserde(rename = "Norm")] pub norm: Option, + /// Received as part of the LEDState info request + #[yaserde(rename = "LedState")] + pub led_state: Option, + /// Sent as part of the TalkConfig to prepare the camera for audio talk-back + #[yaserde(rename = "TalkConfig")] + pub talk_config: Option, + /// Revieced as part of the TalkAbility request + #[yaserde(rename = "TalkAbility")] + pub talk_ability: Option, } impl BcXml { - pub fn try_parse(s: impl Read) -> Result { + pub(crate) fn try_parse(s: impl Read) -> Result { yaserde::de::from_reader(s) } - pub fn serialize(&self, w: W) -> Result { + pub(crate) fn serialize(&self, w: W) -> Result { yaserde::ser::serialize_with_writer(self, w, &Config::default()) } } impl Extension { - pub fn try_parse(s: impl Read) -> Result { + pub(crate) fn try_parse(s: impl Read) -> Result { yaserde::de::from_reader(s) } - pub fn serialize(&self, w: W) -> Result { + pub(crate) fn serialize(&self, w: W) -> Result { yaserde::ser::serialize_with_writer(self, w, &Config::default()) } } +/// Encryption xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct Encryption { + /// XML Version #[yaserde(attribute)] pub version: String, #[yaserde(rename = "type")] + /// The hashing algorithm used. Only observed the value of "md5" pub type_: String, + /// The nonce used to negociate the login and to generate the AES key pub nonce: String, } +/// LoginUser xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct LoginUser { + /// XML Version #[yaserde(attribute)] pub version: String, + /// Username to login as #[yaserde(rename = "userName")] pub user_name: String, + /// Password for login in plain text pub password: String, + /// Unknown always `1` #[yaserde(rename = "userVer")] pub user_ver: u32, } +/// LoginNet xml #[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)] pub struct LoginNet { + /// XML Version #[yaserde(attribute)] pub version: String, + /// Type of connection usually LAN (even on wifi) #[yaserde(rename = "type")] pub type_: String, + /// The port for the udp will be `0` for tcp #[yaserde(rename = "udpPort")] pub udp_port: u16, } @@ -104,86 +139,256 @@ impl Default for LoginNet { } } +/// DeviceInfo xml +/// +/// There is more to this xml but we don't deserialize it all #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct DeviceInfo { + /// The resolution xml block pub resolution: Resolution, } +/// VersionInfo xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct VersionInfo { + /// Name assigned to the camera pub name: String, + /// Camera's serial number pub serialNumber: String, + /// The camera build day e.g. `"build 19110800"` pub buildDay: String, + /// The hardware version e.g. `"IPC_517SD5"` pub hardwareVersion: String, + /// The config version e.g. `"v2.0.0.0"` pub cfgVersion: String, + /// Firmware version usually a combination of config and build versions e.g. + /// `"v2.0.0.587_19110800"` pub firmwareVersion: String, + /// Unusure possibly a more detailed hardware version e.g. `"IPC_51716M110000000100000"` pub detail: String, } +/// Resolution xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct Resolution { + /// Resolution name is in the format "width*height" i.e. "2304*1296" #[yaserde(rename = "resolutionName")] pub name: String, + /// Height of the stream in pixels pub width: u32, + /// Width of the stream in pixels pub height: u32, } +/// Preview xml +/// +/// This xml is used to request a stream to start #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct Preview { + /// XML Version #[yaserde(attribute)] pub version: String, + /// Channel id is usually zero unless using a NVR #[yaserde(rename = "channelId")] pub channel_id: u8, + /// Handle usually 0 for mainStream and 1 for subStream pub handle: u32, + /// Either `"mainStream"` or `"subStream"` #[yaserde(rename = "streamType")] pub stream_type: String, } -#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +/// Extension xml +/// +/// This is used to describe the subsequent payload passed the `payload_offset` +#[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)] pub struct Extension { + /// XML Version #[yaserde(attribute)] pub version: String, + /// If the subsequent payload is binary this will be set to 1. Otherwise it is ommited #[yaserde(rename = "binaryData")] pub binary_data: Option, + /// Certain requests such `AbilitySupport` require to know which user this + /// ability support request is for (why camera dosen't know this based on who + /// is logged in is unknown... Possible security hole) #[yaserde(rename = "userName")] pub user_name: Option, + /// Certain requests such as `AbilitySupport` require details such as what type of + /// abilities are you intested in. This is a comma seperated list such as + /// `"system, network, alarm, record, video, image"` pub token: Option, + /// The channel ID. This is usually `0` unless using an NVR #[yaserde(rename = "channelId")] pub channel_id: Option, } +impl Default for Extension { + fn default() -> Extension { + Extension { + version: xml_ver(), + binary_data: None, + user_name: None, + token: None, + channel_id: None, + } + } +} + +/// SystemGeneral xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct SystemGeneral { + /// XML Version #[yaserde(attribute)] pub version: String, + /// Time zone is negative seconds offset from UTC. So +7:00 is -25200 #[yaserde(rename = "timeZone")] pub time_zone: Option, + /// Current year pub year: Option, + /// Current month pub month: Option, + /// Current day pub day: Option, + /// Current hour pub hour: Option, + /// Current minute pub minute: Option, + /// Current second pub second: Option, + /// Format to use for On Screen Display usually `"DMY"` #[yaserde(rename = "osdFormat")] pub osd_format: Option, + /// Unknown usually `0` #[yaserde(rename = "timeFormat")] pub time_format: Option, + /// Language e.g. `English` will set the language on the reolink app pub language: Option, + /// Name assigned to the camera #[yaserde(rename = "deviceName")] pub device_name: Option, } +/// Norm xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct Norm { + /// XML Version #[yaserde(attribute)] pub version: String, + // This is usually just `"NTSC"` norm: String, } +/// LedState xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct LedState { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// Channel ID of camera to get/set its LED state + #[yaserde(rename = "channelId")] + pub channel_id: u8, + /// LED Version, observed value is "2". Should be None when setting the LedState + #[yaserde(rename = "ledVersion")] + pub led_version: Option, + /// State of the IR LEDs values are "auto", "open", "close" + pub state: String, + /// State of the LED status light (blue on light), values are "open", "close" + #[yaserde(rename = "lightState")] + pub light_state: String, +} + +/// TalkConfig xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct TalkConfig { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// Channel ID of camera to set the TalkConfig + #[yaserde(rename = "channelId")] + pub channel_id: u8, + /// Duplex known values `"FDX"` + pub duplex: String, + /// audioStreamMode known values `"followVideoStream"` + #[yaserde(rename = "audioStreamMode")] + pub audio_stream_mode: String, + /// AudioConfig contans the details of the audio to follow + #[yaserde(rename = "audioConfig")] + pub audio_config: AudioConfig, +} + +/// audioConfig xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)] +#[yaserde(rename = "audioConfig")] +pub struct AudioConfig { + /// Unknown only sent during TalkAbility request from the camera + pub priority: Option, + /// Audio type known values are `"adpcm"` + /// + /// Do not expect camera to support anything else. + #[yaserde(rename = "audioType")] + pub audio_type: String, + /// Audio sample rate known values are `16000` + #[yaserde(rename = "sampleRate")] + pub sample_rate: u16, + /// Precision of data known vaues are `16` (i.e. 16bit) + #[yaserde(rename = "samplePrecision")] + pub sample_precision: u16, + /// Number of audio samples this should be twice the block size for adpcm + #[yaserde(rename = "lengthPerEncoder")] + pub length_per_encoder: u16, + /// Sound track is the number of tracks known values are `"mono"` + /// + /// Do not expect camera to support anything else + #[yaserde(rename = "soundTrack")] + pub sound_track: String, +} + +/// TalkAbility xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct TalkAbility { + /// XML Version + #[yaserde(attribute)] + pub version: String, + /// Duplexes known values `"FDX"` + #[yaserde(rename = "duplexList")] + pub duplex_list: Vec, + /// audioStreamModes known values `"followVideoStream"` + #[yaserde(rename = "audioStreamModeList")] + pub audio_stream_mode_list: Vec, + /// AudioConfigs contans the details of the audio to follow + #[yaserde(rename = "audioConfigList")] + pub audio_config_list: Vec, +} + +/// duplexList xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct DuplexList { + /// The supported duplex known values are "FBX" + pub duplex: String, +} + +/// audioStreamModeList xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct AudioStreamModeList { + /// The supported audio stream mode + #[yaserde(rename = "audioStreamMode")] + pub audio_stream_mode: String, +} + +/// audioConfigList xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct AudioConfigList { + /// The supported audio configs + #[yaserde(rename = "audioConfig")] + pub audio_config: AudioConfig, +} + +/// Convience function to return the xml version used throughout the library pub fn xml_ver() -> String { "1.1".to_string() } @@ -209,8 +414,8 @@ fn test_encryption_deser() { let t = BcXml::try_parse(sample.as_bytes()).unwrap(); match t { - top_b if top_b == b => assert!(true), - _ => assert!(false), + top_b if top_b == b => {} + _ => panic!(), } } @@ -327,8 +532,8 @@ fn test_deviceinfo_partial_deser() { .. }), .. - } => assert!(true), - _ => assert!(false), + } => {} + _ => panic!(), } } @@ -349,7 +554,7 @@ fn test_binary_deser() { Extension { binary_data: Some(1), .. - } => assert!(true), - _ => assert!(false), + } => {} + _ => panic!(), } } diff --git a/src/bc/xml_crypto.rs b/crates/core/src/bc/xml_crypto.rs similarity index 100% rename from src/bc/xml_crypto.rs rename to crates/core/src/bc/xml_crypto.rs diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs new file mode 100644 index 0000000..c6dda1c --- /dev/null +++ b/crates/core/src/bc_protocol.rs @@ -0,0 +1,201 @@ +use self::connection::BcConnection; +use crate::{bc, bcmedia}; +use log::*; +use std::convert::TryInto; +use std::net::ToSocketAddrs; +use std::sync::atomic::{AtomicU16, Ordering}; +use std::time::Duration; + +use Md5Trunc::*; + +mod binarysub; +mod connection; +mod errors; +pub(crate) mod filesub; +mod ledstate; +mod login; +mod logout; +mod ping; +mod reboot; +mod stream; +mod talk; +mod time; +mod version; + +pub use binarysub::BinarySubscriber; +pub use errors::Error; +pub use ledstate::LightState; +pub use stream::{StreamOutput, StreamOutputError}; + +type Result = std::result::Result; + +const RX_TIMEOUT: Duration = Duration::from_secs(5); + +impl<'a> From for Error { + fn from(k: std::sync::mpsc::RecvTimeoutError) -> Self { + match k { + std::sync::mpsc::RecvTimeoutError::Timeout => Error::Timeout, + std::sync::mpsc::RecvTimeoutError::Disconnected => Error::TimeoutDisconnected, + } + } +} + +/// +/// This is the primary struct of this library when interacting with the camera +/// +pub struct BcCamera { + channel_id: u8, + connection: Option, + logged_in: bool, + message_num: AtomicU16, + // Certain commands such as logout require the username/pass in plain text.... why....??? + credentials: Option, +} + +// Used for caching the credentials +#[derive(Clone)] +struct Credentials { + username: String, + password: Option, +} + +impl Credentials { + fn new(username: String, password: Option) -> Self { + Self { username, password } + } +} + +impl Drop for BcCamera { + fn drop(&mut self) { + self.disconnect(); + } +} + +impl BcCamera { + /// + /// Create a new camera interface with this address and channel ID + /// + /// # Parameters + /// + /// * `host` - The address of the camera either ip address or hostname string is ok but + /// [`std::net::SocketAddr`] is fine too + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new_with_addr(host: T, channel_id: u8) -> Result { + let addr_iter = match host.to_socket_addrs() { + Ok(iter) => iter, + Err(_) => return Err(Error::AddrResolutionError), + }; + + for addr in addr_iter { + debug!("Trying {}", addr); + let conn = match BcConnection::new(addr, RX_TIMEOUT) { + Ok(conn) => conn, + Err(err) => match err { + connection::Error::Communication(ref err) => { + debug!("Assuming timeout from {}", err); + continue; + } + err => return Err(err.into()), + }, + }; + + debug!("Success: {}", addr); + return Ok(Self { + connection: Some(conn), + message_num: AtomicU16::new(0), + channel_id, + logged_in: false, + credentials: None, + }); + } + + Err(Error::Timeout) + } + + /// This method will get a new message number and increment the message count atomically + pub fn new_message_num(&self) -> u16 { + self.message_num.fetch_add(1, Ordering::Relaxed) + } + + /// This will drop the connection. It will try to send the logout request to the camera + /// first + pub fn disconnect(&mut self) { + // Stop polling now. We don't need it for a disconnect + // and if we don't then another we might get a deserialise + // error from another thread that polls and needs the login. + // + // It will also ensure that when we drop the connection we don't + // get an error for read retrun zero bytes. + if let Some(connection) = &self.connection { + connection.stop_polling(); + if let Err(err) = self.logout() { + warn!("Could not log out, ignoring: {}", err); + } + } + self.connection = None; + } + + // Certains commands like logout need the username and password + // this command will return it as a tuple of (Username, Option) + // This will only work after login + fn get_credentials(&self) -> &Option { + &self.credentials + } + // This is used to store the credentials it is called during login. + fn set_credentials(&mut self, username: String, password: Option) { + self.credentials = Some(Credentials::new(username, password)); + } + // This is used to clear the stored credentials it is called during logout. + fn clear_credentials(&mut self) { + self.credentials = None; + } +} + +/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I +/// believe this is because the MD5'ing of the user/password is a recent retrofit to the code and +/// the original code wanted to prevent a buffer overflow with strcpy. The modern and legacy login +/// messages have a slightly different behavior; the legacy message has a 32-byte buffer and the +/// modern message uses XML. The legacy code copies all 32 bytes with memcpy, and the XML value is +/// copied from a C-style string, so the appended null byte is dropped by the XML library - see the +/// test below. +/// Emulate this behavior by providing a configurable mangling of the last character. +#[derive(PartialEq, Eq)] +enum Md5Trunc { + ZeroLast, + Truncate, +} + +fn md5_string(input: &str, trunc: Md5Trunc) -> String { + let mut md5 = format!("{:X}\0", md5::compute(input)); + md5.replace_range(31.., if trunc == Truncate { "" } else { "\0" }); + md5 +} + +/// This is a convience function to make an AES key from the login password and the NONCE +/// negociated during login +pub fn make_aes_key(nonce: &str, passwd: &str) -> [u8; 16] { + let key_phrase = format!("{}-{}", nonce, passwd); + let key_phrase_hash = format!("{:X}\0", md5::compute(&key_phrase)) + .to_uppercase() + .into_bytes(); + key_phrase_hash[0..16].try_into().unwrap() +} + +#[test] +fn test_md5_string() { + // Note that these literals are only 31 characters long - see explanation above. + assert_eq!( + md5_string("admin", Truncate), + "21232F297A57A5A743894A0E4A801FC" + ); + assert_eq!( + md5_string("admin", ZeroLast), + "21232F297A57A5A743894A0E4A801FC\0" + ); +} diff --git a/crates/core/src/bc_protocol/binarysub.rs b/crates/core/src/bc_protocol/binarysub.rs new file mode 100644 index 0000000..bc4618f --- /dev/null +++ b/crates/core/src/bc_protocol/binarysub.rs @@ -0,0 +1,92 @@ +use super::{connection::BcSubscription, RX_TIMEOUT}; +use crate::bc::model::*; +use std::{ + io::{BufRead, Error, ErrorKind, Read}, + sync::mpsc::RecvTimeoutError, +}; + +type Result = std::result::Result; + +/// A `BinarySubscriber` is a helper util to read the binary stream +/// of a [`BcSubscription`] +/// +/// Some messgaes like video streams contain a substream in their +/// payload that may be broken at any point into multiple bc packets. +/// This subscriber will create a stream reader for these binary streams. +/// +/// This stream should be accessed via the [`BufRead`] and [`Read`] trait +pub struct BinarySubscriber<'a> { + bc_sub: &'a BcSubscription<'a>, + buffer: Vec, + consumed: usize, +} + +impl<'a> BinarySubscriber<'a> { + /// Creates a binary subsciber from a BcSubscrption. + /// When reading the next packet it will skip over multiple + /// Bc packets to fill the binary buffer so ensure you + /// only want binary packets when calling read + pub fn from_bc_sub<'b>(bc_sub: &'b BcSubscription) -> BinarySubscriber<'b> { + BinarySubscriber { + bc_sub, + buffer: vec![], + consumed: 0, + } + } +} + +impl<'a> Read for BinarySubscriber<'a> { + fn read(&mut self, buf: &mut [u8]) -> Result { + let buffer = self.fill_buf()?; + let amt = std::cmp::min(buf.len(), buffer.len()); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if amt == 1 { + buf[0] = buffer[0]; + } else { + buf[..amt].copy_from_slice(&buffer[..amt]); + } + + self.consume(amt); + + Ok(amt) + } +} +impl<'a> BufRead for BinarySubscriber<'a> { + fn fill_buf(&mut self) -> Result<&[u8]> { + const CLEAR_CONSUMED_AT: usize = 1024; + // This is a trade off between caching too much dead memory + // and calling the drain method too often + if self.consumed > CLEAR_CONSUMED_AT { + let _ = self.buffer.drain(0..self.consumed).collect::>(); + self.consumed = 0; + } + while self.buffer.len() <= self.consumed { + let msg = self + .bc_sub + .rx + .recv_timeout(RX_TIMEOUT) + .map_err(|err| match err { + RecvTimeoutError::Timeout => Error::new(ErrorKind::TimedOut, err), + RecvTimeoutError::Disconnected => Error::new(ErrorKind::ConnectionReset, err), + })?; + if let BcBody::ModernMsg(ModernMsg { + payload: Some(BcPayloads::Binary(binary)), + .. + }) = msg.body + { + // Add the new binary to the buffer and return + self.buffer.extend(binary); + } + } + + Ok(&self.buffer.as_slice()[self.consumed..]) + } + + fn consume(&mut self, amt: usize) { + assert!(self.consumed + amt <= self.buffer.len()); + self.consumed += amt; + } +} diff --git a/src/bc_protocol/connection.rs b/crates/core/src/bc_protocol/connection.rs similarity index 84% rename from src/bc_protocol/connection.rs rename to crates/core/src/bc_protocol/connection.rs index 44c30a2..a4a822e 100644 --- a/src/bc_protocol/connection.rs +++ b/crates/core/src/bc_protocol/connection.rs @@ -8,12 +8,12 @@ use std::collections::BTreeMap; use std::error::Error as StdErr; // Just need the traits use std::net::{Shutdown, SocketAddr, TcpStream}; use std::sync::mpsc::{channel, Receiver, Sender}; -use std::sync::{Arc, Mutex}; +use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; use std::thread::JoinHandle; use std::time::Duration; /// A shareable connection to a camera. Handles serialization of messages. To send/receive, call -/// .subscribe() with a message ID. You can use the BcSubscription to send or receive only +/// .[subscribe()] with a message ID. You can use the BcSubscription to send or receive only /// messages with that ID; each incoming message is routed to its appropriate subscriber. /// /// There can be only one subscriber per kind of message at a time. @@ -24,6 +24,7 @@ pub struct BcConnection { // Arc> because it is shared between context // and connection for deserialisation and serialistion respectivly encryption_protocol: Arc>, + poll_abort: Arc, } pub struct BcSubscription<'a> { @@ -37,13 +38,13 @@ type Result = std::result::Result; #[derive(Debug, Error)] pub enum Error { #[error(display = "Communication error")] - CommunicationError(#[error(source)] std::io::Error), + Communication(#[error(source)] std::io::Error), #[error(display = "Deserialization error")] - DeserializationError(#[error(source)] bc::de::Error), + Deserialization(#[error(source)] bc::de::Error), #[error(display = "Serialization error")] - SerializationError(#[error(source)] bc::ser::Error), + Serialization(#[error(source)] bc::ser::Error), #[error(display = "Simultaneous subscription")] SimultaneousSubscription { msg_id: u32 }, @@ -59,19 +60,25 @@ impl BcConnection { let encryption_protocol = Arc::new(Mutex::new(EncryptionProtocol::Unencrypted)); let connections_encryption_protocol = encryption_protocol.clone(); + let poll_abort = Arc::new(AtomicBool::new(false)); + let poll_abort_rx = poll_abort.clone(); let rx_thread = std::thread::spawn(move || { let mut context = BcContext::new(connections_encryption_protocol); let mut result; - while { + loop { result = BcConnection::poll(&mut context, &conn, &mut subs); - result.is_ok() - } {} - let e = result.unwrap_err(); - error!("Deserialization error: {}", e); - let mut cause = e.source(); - while let Some(e) = cause { - error!("caused by: {}", e); - cause = e.source(); + if poll_abort_rx.load(Ordering::Relaxed) { + break; // Poll has been aborted by request usally during disconnect + } + if let Err(e) = result { + error!("Deserialization error: {}", e); + let mut cause = e.source(); + while let Some(e) = cause { + error!("caused by: {}", e); + cause = e.source(); + } + break; + } } }); @@ -80,6 +87,7 @@ impl BcConnection { subscribers, rx_thread: Some(rx_thread), encryption_protocol, + poll_abort, }) } @@ -129,6 +137,10 @@ impl BcConnection { Ok(()) } + pub fn stop_polling(&self) { + self.poll_abort.store(true, Ordering::Relaxed); + } + pub fn set_encrypted(&self, value: EncryptionProtocol) { *(self.encryption_protocol.lock().unwrap()) = value; } diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs new file mode 100644 index 0000000..ef79712 --- /dev/null +++ b/crates/core/src/bc_protocol/errors.rs @@ -0,0 +1,72 @@ +use super::bc::model::Bc; +use err_derive::Error; + +/// This is the primary error type of the library +#[derive(Debug, Error)] +#[allow(clippy::large_enum_variant)] +pub enum Error { + /// Error raised when IO fails such as when the connection is lost + #[error(display = "Communication error")] + Communication(#[error(source)] std::io::Error), + + /// Error raised during deserlization + #[error(display = "Deserialization error")] + Deserialization(#[error(source)] super::bc::de::Error), + + /// Error raised during serlization + #[error(display = "Serialization error")] + Serialization(#[error(source)] super::bc::ser::Error), + + /// Error raised during deserlization + #[error(display = "Media Deserialization error")] + MediaDeserialization(#[error(source)] super::bcmedia::de::Error), + + /// Error raised during serlization + #[error(display = "Media Serialization error")] + MediaSerialization(#[error(source)] super::bcmedia::ser::Error), + + /// A connection error such as Simultaneous subscription + #[error(display = "Connection error")] + ConnectionError(#[error(source)] super::connection::Error), + + /// Raised when a Bc reply was not understood + #[error(display = "Communication error")] + UnintelligibleReply { + /// The Bc packet that was not understood + reply: Bc, + /// The message attached to the error + why: &'static str, + }, + + /// Raised when a connection is dropped. + #[error(display = "Dropped connection")] + DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), + + /// Raised when the RX_TIMEOUT is reach + #[error(display = "Timeout")] + Timeout, + + /// Raised when connection is dropped because the timeout is reach + #[error(display = "Dropped connection")] + TimeoutDisconnected, + + /// Raised when failed to login to the camera + #[error(display = "Credential error")] + AuthFailed, + + /// Raised when the given camera url could not be resolved + #[error(display = "Failed to translate camera address")] + AddrResolutionError, + + /// Raised non adpcm data is sent to the talk command + #[error(display = "Talk data is not ADPCM")] + UnknownTalkEncoding, + + /// A generic catch all error + #[error(display = "Other error")] + Other(&'static str), + + /// A generic catch all error + #[error(display = "Other error")] + OtherString(String), +} diff --git a/crates/core/src/bc_protocol/filesub.rs b/crates/core/src/bc_protocol/filesub.rs new file mode 100644 index 0000000..d27ec86 --- /dev/null +++ b/crates/core/src/bc_protocol/filesub.rs @@ -0,0 +1,92 @@ +// This is a test module so it will appear as unused most of the time +#![allow(dead_code)] +// This module is used to subscribe to raw bytes on disk +// +// It is mostly used for testing +// +use std::{ + fs, + io::{BufRead, Error, Read}, + path::{Path, PathBuf}, +}; + +type Result = std::result::Result; + +/// A `FileSubscriber` is a helper util to read a binary stream +/// from a series of files +/// +/// This stream should be accessed via the [`BufRead`] and [`Read`] trait +#[derive(Debug)] +pub struct FileSubscriber { + files: Vec, + buffer: Vec, + consumed: usize, +} + +impl FileSubscriber { + /// Creates a binary subsciber from a BcSubscrption. + /// When reading the next packet it will skip over multiple + /// Bc packets to fill the binary buffer so ensure you + /// only want binary packets when calling read + pub fn from_files>(paths: Vec

) -> FileSubscriber { + FileSubscriber { + files: paths + .iter() + .rev() + .map(|p| { + let path: &Path = p.as_ref(); + path.to_path_buf() + }) + .collect(), + buffer: vec![], + consumed: 0, + } + } +} + +impl Read for FileSubscriber { + fn read(&mut self, buf: &mut [u8]) -> Result { + let buffer = self.fill_buf()?; + let amt = std::cmp::min(buf.len(), buffer.len()); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if amt == 1 { + buf[0] = buffer[0]; + } else { + buf[..amt].copy_from_slice(&buffer[..amt]); + } + + self.consume(amt); + + Ok(amt) + } +} +impl BufRead for FileSubscriber { + fn fill_buf(&mut self) -> Result<&[u8]> { + const CLEAR_CONSUMED_AT: usize = 1024; + // This is a trade off between caching too much dead memory + // and calling the drain method too often + if self.consumed > CLEAR_CONSUMED_AT { + let _ = self.buffer.drain(0..self.consumed).collect::>(); + self.consumed = 0; + } + while self.buffer.len() <= self.consumed { + let next_file = self.files.pop(); + if let Some(next_file) = next_file { + let bytes = &fs::read(next_file)?; + self.buffer.extend(bytes); + } else { + break; + } + } + + Ok(&self.buffer.as_slice()[self.consumed..]) + } + + fn consume(&mut self, amt: usize) { + assert!(self.consumed + amt <= self.buffer.len()); + self.consumed += amt; + } +} diff --git a/crates/core/src/bc_protocol/ledstate.rs b/crates/core/src/bc_protocol/ledstate.rs new file mode 100644 index 0000000..6be34d8 --- /dev/null +++ b/crates/core/src/bc_protocol/ledstate.rs @@ -0,0 +1,137 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Get the [LedState] xml which contains the LED status of the camera + pub fn get_ledstate(&mut self) -> Result { + let connection = self + .connection + .as_ref() + .expect("Must be connected to get time"); + let sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS)?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_GET_LED_STATUS, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: None, + }), + }; + + sub_get.send(get)?; + let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + led_state: Some(ledstate), + .. + })), + .. + }) = msg.body + { + Ok(ledstate) + } else { + Err(Error::UnintelligibleReply { + reply: msg, + why: "Expected LEDState xml but it was not recieved", + }) + } + } + + /// Set the led lights using the [LedState] xml + pub fn set_ledstate(&mut self, mut led_state: LedState) -> Result<()> { + let connection = self + .connection + .as_ref() + .expect("Must be connected to get time"); + let sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS)?; + + // led_version is a field recieved from the camera but not sent + // we set to None to ensure we don't send it to the camera + led_state.led_version = None; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_SET_LED_STATUS, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: Some(BcPayloads::BcXml(BcXml { + led_state: Some(led_state), + ..Default::default() + })), + }), + }; + + sub_set.send(get)?; + let msg = sub_set.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + Ok(()) + } else { + Err(Error::UnintelligibleReply { + reply: msg, + why: "The camera did not except the LEDState xml", + }) + } + } + + /// This is a convience function to control the IR LED lights + /// + /// This is for the RED IR lights that can come on automaitcally + /// during low light. + pub fn irled_light_set(&mut self, state: LightState) -> Result<()> { + let mut led_state = self.get_ledstate()?; + led_state.state = match state { + LightState::On => "open".to_string(), + LightState::Off => "close".to_string(), + LightState::Auto => "auto".to_string(), + }; + self.set_ledstate(led_state)?; + Ok(()) + } + + /// This is a convience function to control the LED light + /// True is on and false is off + /// + /// This is for the little blue on light of some camera + pub fn led_light_set(&mut self, state: bool) -> Result<()> { + let mut led_state = self.get_ledstate()?; + led_state.light_state = match state { + true => "open".to_string(), + false => "close".to_string(), + }; + self.set_ledstate(led_state)?; + Ok(()) + } +} + +/// This is pased to `irled_light_set` to turn it on, off or set it to light based auto +pub enum LightState { + /// Turn the light on + On, + /// Turn the light off + Off, + /// Set the light to light based auto + Auto, +} diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs new file mode 100644 index 0000000..f8550fd --- /dev/null +++ b/crates/core/src/bc_protocol/login.rs @@ -0,0 +1,144 @@ +use super::{make_aes_key, md5_string, BcCamera, Error, Result, Truncate, ZeroLast, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Login to the camera. + /// + /// This should be called before most other commands + pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { + let device_info; + // This { is here due to the connection and set_credentials both requiring a mutable borrow + { + let connection = self + .connection + .as_ref() + .expect("Must be connected to log in"); + let sub_login = connection.subscribe(MSG_ID_LOGIN)?; + + // Login flow is: Send legacy login message, expect back a modern message with Encryption + // details. Then, re-send the login as a modern login message. Expect back a device info + // congratulating us on logging in. + + // In the legacy scheme, username/password are MD5'd if they are encrypted (which they need + // to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent. + // Note: I suspect there may be a buffer overflow opportunity in the firmware since in the + // Baichuan library, these strings are capped at 32 bytes with a null terminator. This + // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. + let md5_username = md5_string(username, ZeroLast); + let md5_password = password + .map(|p| md5_string(p, ZeroLast)) + .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); + + let legacy_login = Bc { + meta: BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0xdc03, + class: 0x6514, + }, + body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { + username: md5_username, + password: md5_password, + }), + }; + + sub_login.send(legacy_login)?; + + let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + + let nonce; + match legacy_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + encryption: Some(encryption), + .. + })), + .. + }) => { + nonce = encryption.nonce; + } + _ => { + return Err(Error::UnintelligibleReply { + reply: legacy_reply, + why: "Expected an Encryption message back", + }) + } + } + + // In the modern login flow, the username/password are concat'd with the server's nonce + // string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce + // prevents replay attacks if the server were to require modern flow, but not rainbow table + // attacks (since the plain user/password MD5s have already been sent). The upshot is that + // you should use a very strong random password that is not found in a rainbow table and + // not feasibly crackable with John the Ripper. + + let modern_password = password.unwrap_or(""); + let concat_username = format!("{}{}", username, nonce); + let concat_password = format!("{}{}", modern_password, nonce); + let md5_username = md5_string(&concat_username, Truncate); + let md5_password = md5_string(&concat_password, Truncate); + + let modern_login = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + BcXml { + login_user: Some(LoginUser { + version: xml_ver(), + user_name: md5_username, + password: md5_password, + user_ver: 1, + }), + login_net: Some(LoginNet::default()), + ..Default::default() + }, + ); + + sub_login.send(modern_login)?; + let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + + match modern_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + device_info: Some(info), + .. + })), + .. + }) => { + // Login succeeded! + self.logged_in = true; + device_info = info; + } + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: None, + }) => return Err(Error::AuthFailed), + _ => { + return Err(Error::UnintelligibleReply { + reply: modern_reply, + why: "Expected a DeviceInfo message back from login", + }) + } + } + + if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { + // We setup the data for the AES key now + // as all subsequent communications will use it + let passwd = password.unwrap_or(""); + let full_key = make_aes_key(&nonce, passwd); + connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); + } + } + self.set_credentials(username.to_string(), password.map(|s| s.to_string())); + Ok(device_info) + } +} diff --git a/crates/core/src/bc_protocol/logout.rs b/crates/core/src/bc_protocol/logout.rs new file mode 100644 index 0000000..b6f3749 --- /dev/null +++ b/crates/core/src/bc_protocol/logout.rs @@ -0,0 +1,50 @@ +use super::{BcCamera, Result}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Logout from the camera + pub fn logout(&mut self) -> Result<()> { + if self.logged_in { + if let Some(credentials) = self.get_credentials() { + let connection = self + .connection + .as_ref() + .expect("Must be connected to log in"); + let sub_logout = connection.subscribe(MSG_ID_LOGOUT)?; + + let username = credentials.username.clone(); + let password = credentials + .password + .as_ref() + .cloned() + .unwrap_or_else(|| "".to_string()); + + let modern_logout = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_LOGOUT, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + BcXml { + login_user: Some(LoginUser { + version: xml_ver(), + user_name: username, + password, + user_ver: 1, + }), + login_net: Some(LoginNet::default()), + ..Default::default() + }, + ); + + sub_logout.send(modern_logout)?; + } + } + self.clear_credentials(); + self.logged_in = false; + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/ping.rs b/crates/core/src/bc_protocol/ping.rs new file mode 100644 index 0000000..0c63b0e --- /dev/null +++ b/crates/core/src/bc_protocol/ping.rs @@ -0,0 +1,31 @@ +use super::{BcCamera, Result, RX_TIMEOUT}; +use crate::bc::model::*; + +impl BcCamera { + /// Ping the camera will either return Ok(()) which means a sucess reply + /// or error + pub fn ping(&self) -> Result<()> { + let connection = self.connection.as_ref().expect("Must be connected to ping"); + let sub_ping = connection.subscribe(MSG_ID_PING)?; + + let ping = Bc { + meta: BcMeta { + msg_id: MSG_ID_PING, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub_ping.send(ping)?; + + sub_ping.rx.recv_timeout(RX_TIMEOUT)?; + + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/reboot.rs b/crates/core/src/bc_protocol/reboot.rs new file mode 100644 index 0000000..ce6fe47 --- /dev/null +++ b/crates/core/src/bc_protocol/reboot.rs @@ -0,0 +1,39 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::bc::model::*; + +impl BcCamera { + /// Reboot the camera + pub fn reboot(&self) -> Result<()> { + let connection = self.connection.as_ref().expect("Must be connected to ping"); + let sub = connection.subscribe(MSG_ID_REBOOT)?; + + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_REBOOT, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub.send(msg)?; + let msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + Ok(()) + } else { + Err(Error::UnintelligibleReply { + reply: msg, + why: "The camera did not except the TalkConfig xml", + }) + } + } +} diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs new file mode 100644 index 0000000..ba4aebd --- /dev/null +++ b/crates/core/src/bc_protocol/stream.rs @@ -0,0 +1,78 @@ +use super::{BcCamera, BinarySubscriber, Result}; +use crate::{ + bc::{model::*, xml::*}, + bcmedia::model::*, + Never, +}; + +/// Convience type for the error raised by the [StreamOutput] trait +pub type StreamOutputError = Result<()>; + +/// The method [`BcCamera::start_video()`] requires a structure with this trait to pass the +/// audio and video data back to +pub trait StreamOutput { + /// This is the callback raised a complete media packet is received + fn write(&mut self, media: BcMedia) -> StreamOutputError; +} + +impl BcCamera { + /// + /// Starts the video stream + /// + /// # Parameters + /// + /// * `data_outs` - This should be a struct that implements the [`StreamOutput`] trait + /// + /// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD + /// + /// # Returns + /// + /// This will block forever or return an error when the camera connection is dropped + /// + pub fn start_video(&self, data_outs: &mut Outputs, stream_name: &str) -> Result + where + Outputs: StreamOutput, + { + let connection = self + .connection + .as_ref() + .expect("Must be connected to start video"); + let sub_video = connection.subscribe(MSG_ID_VIDEO)?; + + let stream_num = match stream_name { + "mainStream" => 0, + "subStream" => 1, + _ => 0, + }; + + let start_video = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_VIDEO, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: stream_num, + response_code: 0, + class: 0x6414, // IDK why + }, + BcXml { + preview: Some(Preview { + version: xml_ver(), + channel_id: self.channel_id, + handle: 0, + stream_type: stream_name.to_string(), + }), + ..Default::default() + }, + ); + + sub_video.send(start_video)?; + + let mut media_sub = BinarySubscriber::from_bc_sub(&sub_video); + + loop { + let bc_media = BcMedia::deserialize(&mut media_sub)?; + // We now have a complete interesting packet. Send it to on the callback + data_outs.write(bc_media)?; + } + } +} diff --git a/crates/core/src/bc_protocol/talk.rs b/crates/core/src/bc_protocol/talk.rs new file mode 100644 index 0000000..5d2b08a --- /dev/null +++ b/crates/core/src/bc_protocol/talk.rs @@ -0,0 +1,468 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::{bc::model::*, bc::xml::*, bcmedia::model::*}; +use std::io::{BufRead, Error as IoError, ErrorKind, Read}; +use std::sync::mpsc::Receiver; + +type IoResult = std::result::Result; + +impl BcCamera { + /// + /// Finish Talk + /// + /// The send the talk finish to the camera. + /// + /// It is also sent when the request for talk config returns status code 422 + /// + pub fn talk_stop(&self) -> Result<()> { + let connection = self.connection.as_ref().expect("Must be connected"); + + let sub = connection.subscribe(MSG_ID_TALKRESET)?; + + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_TALKRESET, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: None, + }), + }; + + sub.send(msg)?; + let msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + } else { + return Err(Error::UnintelligibleReply { + reply: msg, + why: "The camera did not accept the talk stop command.", + }); + } + + Ok(()) + } + + /// + /// Requests the [`TalkAbility`] xml + /// + pub fn talk_ability(&self) -> Result { + let connection = self + .connection + .as_ref() + .expect("Must be connected to get time"); + let sub_get = connection.subscribe(MSG_ID_TALKABILITY)?; + let get = Bc { + meta: BcMeta { + msg_id: MSG_ID_TALKABILITY, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + response_code: 0, + stream_type: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: None, + }), + }; + + sub_get.send(get)?; + let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; + + if let BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + talk_ability: Some(talk_ability), + .. + })), + .. + }) = msg.body + { + Ok(talk_ability) + } else { + Err(Error::UnintelligibleReply { + reply: msg, + why: "Expected TalkAbility xml but it was not recieved", + }) + } + } + + /// + /// Send sound to the camera + /// + /// The data should be in the format as described in `` xml + /// This method assumes that you have set up the data in the desired format + /// in the `` xml + /// + /// It also checks that it is ADPCM as the code is written to accept only that + /// + /// # Parameters + /// + /// * `adpcm` - Data must be adpcm in DVI-4 format + /// + /// * `talk_config` - The talk config that describes the adpcm data + /// + /// + pub fn talk(&self, adpcm: &[u8], talk_config: TalkConfig) -> Result<()> { + let connection = self.connection.as_ref().expect("Must be connected"); + + let sub = connection.subscribe(MSG_ID_TALKCONFIG)?; + + if &talk_config.audio_config.audio_type != "adpcm" { + return Err(Error::UnknownTalkEncoding); + } + + let block_size = talk_config.audio_config.length_per_encoder / 2; + let sample_rate = talk_config.audio_config.sample_rate; + + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_TALKCONFIG, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: Some(BcPayloads::BcXml(BcXml { + talk_config: Some(talk_config), + ..Default::default() + })), + }), + }; + + sub.send(msg)?; + let mut msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + + // If another client is already talking OR if we crashed before sending + // msgid 11 the camera will reply 422 + // + // The official client in this case just sends msgid 11 and retries so + // we will do that too + if let BcMeta { + response_code: 422, .. + } = msg.meta + { + self.talk_stop()?; + // Retry + sub.send(msg)?; + msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + } + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + } else { + return Err(Error::UnintelligibleReply { + reply: msg, + why: + "The camera did not accept the TalkConfig xml. Audio format is likely incorrect", + }); + } + + let full_block_size = block_size + 4; // Block size + predictor state + let sub = connection.subscribe(MSG_ID_TALK)?; + + const BLOCK_PER_PAYLOAD: usize = 4; + const BLOCK_HEADER_SIZE: usize = 4; + const SAMPLES_PER_BYTE: usize = 2; + + for payload_bytes in adpcm.chunks(full_block_size as usize * BLOCK_PER_PAYLOAD) { + let mut payload = vec![]; + for bytes in payload_bytes.chunks(full_block_size as usize) { + let bcmedia_adpcm = BcMedia::Adpcm(BcMediaAdpcm { + data: bytes.to_vec(), + }); + payload = bcmedia_adpcm.serialize(payload)?; + } + + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_TALK, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + binary_data: Some(1), + ..Default::default() + }), + payload: Some(BcPayloads::Binary(payload)), + }), + }; + + sub.send(msg)?; + + let adpcm_len = payload_bytes.len(); + // There are two samples per byte + // + // To calculate the bytes we subtract the block headers from the len + // + // There is 1 initial sample stored in the block header so we add that in the end + // + let samples_sent = (adpcm_len - BLOCK_HEADER_SIZE * BLOCK_PER_PAYLOAD) + * SAMPLES_PER_BYTE + + BLOCK_PER_PAYLOAD; + + // Time to play the sample in seconds + let play_length = samples_sent as f32 / sample_rate as f32; + std::thread::sleep(std::time::Duration::from_secs_f32(play_length)); + } + + self.talk_stop()?; + + Ok(()) + } + + /// + /// Send sound to the camera through a channel + /// + /// This is similar to [`talk`] except it uses a channel to receive data + /// + /// The data should be in the format as described in `` xml + /// This method assumes that you have set up the data in the desired format + /// in the `` xml + /// + /// It also checks that it is ADPCM as the code is written to accept only that + /// + /// # Parameters + /// + /// * `adpcm` - Data must be adpcm in DVI-4 format + /// + /// * `talk_config` - The talk config that describes the adpcm data + /// + /// + pub fn talk_stream(&self, rx: Receiver>, talk_config: TalkConfig) -> Result<()> { + let connection = self.connection.as_ref().expect("Must be connected"); + + let sub = connection.subscribe(MSG_ID_TALKCONFIG)?; + + if &talk_config.audio_config.audio_type != "adpcm" { + return Err(Error::UnknownTalkEncoding); + } + + let block_size = talk_config.audio_config.length_per_encoder / 2; + let sample_rate = talk_config.audio_config.sample_rate; + + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_TALKCONFIG, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + ..Default::default() + }), + payload: Some(BcPayloads::BcXml(BcXml { + talk_config: Some(talk_config), + ..Default::default() + })), + }), + }; + + sub.send(msg)?; + let mut msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + + // If another client is already talking OR if we crashed before sending + // msgid 11 the camera will reply 422 + // + // The official client in this case just sends msgid 11 and retries so + // we will do that too + if let BcMeta { + response_code: 422, .. + } = msg.meta + { + self.talk_stop()?; + // Retry + sub.send(msg)?; + msg = sub.rx.recv_timeout(RX_TIMEOUT)?; + } + + if let BcMeta { + response_code: 200, .. + } = msg.meta + { + } else { + return Err(Error::UnintelligibleReply { + reply: msg, + why: + "The camera did not accept the TalkConfig xml. Audio format is likely incorrect", + }); + } + + let full_block_size = block_size + 4; // Block size + predictor state + let sub = connection.subscribe(MSG_ID_TALK)?; + + const BLOCK_PER_PAYLOAD: usize = 1; + const BLOCK_HEADER_SIZE: usize = 4; + const SAMPLES_PER_BYTE: usize = 2; + + let mut buffered_recv = BufferedStream::from_rx(rx); + + let target_chunks = full_block_size as usize * BLOCK_PER_PAYLOAD; + + let mut payload_bytes = vec![]; + let mut end_of_stream = false; + while !end_of_stream { + while payload_bytes.len() < target_chunks { + let mut buffer = vec![255; target_chunks - payload_bytes.len()]; + if let Ok(read) = buffered_recv.read(&mut buffer) { + payload_bytes.extend(&buffer[..read]); + } else { + // Error should occur if the channel is dropped + // and all bytes are consumed + end_of_stream = true; + } + if end_of_stream { + break; + } + } + + let mut payload = vec![]; + for block_bytes in payload_bytes.chunks(full_block_size as usize) { + let bytes: Vec = block_bytes.to_vec(); + let bcmedia_adpcm = BcMedia::Adpcm(BcMediaAdpcm { data: bytes }); + payload = bcmedia_adpcm.serialize(payload)?; + } + + let adpcm_len = payload_bytes.len(); + + // There are two samples per byte + // + // To calculate the bytes we subtract the block headers from the len + // + // There is 1 initial sample stored in the block header so we add that in the end + // + let samples_sent = if adpcm_len >= BLOCK_HEADER_SIZE * BLOCK_PER_PAYLOAD { + (adpcm_len - BLOCK_HEADER_SIZE * BLOCK_PER_PAYLOAD) * SAMPLES_PER_BYTE + + BLOCK_PER_PAYLOAD + } else { + // Zero samples in this block + break; + }; + + payload_bytes = vec![]; + + // Time to play the sample in seconds + let play_length = samples_sent as f32 / sample_rate as f32; + + let msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_TALK, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + extension: Some(Extension { + channel_id: Some(self.channel_id), + binary_data: Some(1), + ..Default::default() + }), + payload: Some(BcPayloads::Binary(payload)), + }), + }; + + sub.send(msg)?; + + std::thread::sleep(std::time::Duration::from_secs_f32(play_length * 0.95)); + } + + self.talk_stop()?; + + Ok(()) + } +} + +struct BufferedStream { + rx: Receiver>, + buffer: Vec, + consumed: usize, +} + +impl BufferedStream { + pub fn from_rx(rx: Receiver>) -> BufferedStream { + BufferedStream { + rx, + buffer: vec![], + consumed: 0, + } + } +} + +impl Read for BufferedStream { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + let buffer = self.fill_buf()?; + let amt = std::cmp::min(buf.len(), buffer.len()); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if amt == 1 { + buf[0] = buffer[0]; + } else { + buf[..amt].copy_from_slice(&buffer[..amt]); + } + + self.consume(amt); + + Ok(amt) + } +} + +impl BufRead for BufferedStream { + fn fill_buf(&mut self) -> IoResult<&[u8]> { + const CLEAR_CONSUMED_AT: usize = 1024; + // This is a trade off between caching too much dead memory + // and calling the drain method too often + if self.consumed > CLEAR_CONSUMED_AT { + let _ = self.buffer.drain(0..self.consumed).collect::>(); + self.consumed = 0; + } + while self.buffer.len() <= self.consumed { + let data = self + .rx + .recv() + .map_err(|err| IoError::new(ErrorKind::ConnectionReset, err))?; + self.buffer.extend(data); + } + + Ok(&self.buffer.as_slice()[self.consumed..]) + } + + fn consume(&mut self, amt: usize) { + assert!(self.consumed + amt <= self.buffer.len()); + self.consumed += amt; + } +} diff --git a/src/bc_protocol/time.rs b/crates/core/src/bc_protocol/time.rs similarity index 91% rename from src/bc_protocol/time.rs rename to crates/core/src/bc_protocol/time.rs index 2e1e7d2..bba2cd1 100644 --- a/src/bc_protocol/time.rs +++ b/crates/core/src/bc_protocol/time.rs @@ -3,6 +3,13 @@ use crate::bc::{model::*, xml::*}; use time::{date, Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; impl BcCamera { + /// + /// Get the time from the camera + /// + /// # Returns + /// + /// returns either an error or an option with the offsetted date time + /// pub fn get_time(&self) -> Result> { let connection = self .connection @@ -46,7 +53,7 @@ impl BcCamera { let datetime = match try_build_timestamp(time_zone, year, month, day, hour, minute, second) { Ok(dt) => dt, - Err(e) => { + Err(_) => { return Err(Error::UnintelligibleReply { reply: msg, why: "Could not parse date", @@ -75,6 +82,17 @@ impl BcCamera { } } + /// + /// Sets the time of the camera + /// + /// # Parameters + /// + /// * `timestamp` - The time to set the camera to + /// + /// # Returns + /// + /// returns Ok(()) or error + /// pub fn set_time(&self, timestamp: OffsetDateTime) -> Result<()> { let connection = self .connection @@ -110,7 +128,7 @@ impl BcCamera { ); sub_set_general.send(set)?; - let msg = sub_set_general.rx.recv_timeout(RX_TIMEOUT)?; + let _ = sub_set_general.rx.recv_timeout(RX_TIMEOUT)?; Ok(()) } diff --git a/crates/core/src/bc_protocol/version.rs b/crates/core/src/bc_protocol/version.rs new file mode 100644 index 0000000..2781421 --- /dev/null +++ b/crates/core/src/bc_protocol/version.rs @@ -0,0 +1,52 @@ +use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use crate::bc::{model::*, xml::*}; + +impl BcCamera { + /// Request the [VersionInfo] xml + pub fn version(&self) -> Result { + let connection = self + .connection + .as_ref() + .expect("Must be connected to get version info"); + let sub_version = connection.subscribe(MSG_ID_VERSION)?; + + let version = Bc { + meta: BcMeta { + msg_id: MSG_ID_VERSION, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, // IDK why + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub_version.send(version)?; + + let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?; + let version_info; + match modern_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + version_info: Some(info), + .. + })), + .. + }) => { + version_info = info; + } + _ => { + return Err(Error::UnintelligibleReply { + reply: modern_reply, + why: "Expected a VersionInfo message", + }) + } + } + + Ok(version_info) + } +} diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs new file mode 100644 index 0000000..67de1f9 --- /dev/null +++ b/crates/core/src/bcmedia/de.rs @@ -0,0 +1,459 @@ +use super::model::BcMediaIframe; +use super::model::*; +use err_derive::Error; +use nom::IResult; +use nom::{combinator::*, named, number::streaming::*, take, take_str}; +use std::io::Read; + +// PAD_SIZE: Media packets use 8 byte padding +const PAD_SIZE: u32 = 8; + +/// The error types used during deserialisation +#[derive(Debug, Error)] +pub enum Error { + /// A Nom parsing error usually a malformed packet + #[error(display = "Parsing error")] + NomError(String), + /// An IO error such as the stream being dropped + #[error(display = "I/O error")] + IoError(#[error(source)] std::io::Error), +} +type NomErrorType<'a> = nom::error::Error<&'a [u8]>; + +impl<'a> From>> for Error { + fn from(k: nom::Err>) -> Self { + let reason = match k { + nom::Err::Error(e) => format!("Nom Error: {:?}", e), + nom::Err::Failure(e) => format!("Nom Error: {:?}", e), + _ => "Unknown Nom error".to_string(), + }; + Error::NomError(reason) + } +} + +fn read_from_reader(mut parser: P, mut rdr: R) -> Result +where + R: Read, + E: for<'a> From>> + From, + P: FnMut(&[u8]) -> nom::IResult<&[u8], O>, +{ + let mut input: Vec = Vec::new(); + loop { + let to_read = match parser(&input) { + Ok((_, parsed)) => return Ok(parsed), + Err(nom::Err::Incomplete(needed)) => { + match needed { + nom::Needed::Unknown => std::num::NonZeroUsize::new(1).unwrap(), // read one byte + nom::Needed::Size(len) => len, + } + } + Err(e) => return Err(e.into()), + }; + + if 0 == (&mut rdr) + .take(to_read.get() as u64) + .read_to_end(&mut input)? + { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } + } +} + +impl BcMedia { + pub(crate) fn deserialize(r: R) -> Result { + // Throw away the nom-specific return types + read_from_reader(|reader| bcmedia(reader), r) + } +} + +fn bcmedia(buf: &[u8]) -> IResult<&[u8], BcMedia> { + let (buf, magic) = verify(le_u32, |x| { + matches!( + *x, + MAGIC_HEADER_BCMEDIA_INFO_V1 + | MAGIC_HEADER_BCMEDIA_INFO_V2 + | MAGIC_HEADER_BCMEDIA_IFRAME + | MAGIC_HEADER_BCMEDIA_PFRAME + | MAGIC_HEADER_BCMEDIA_AAC + | MAGIC_HEADER_BCMEDIA_ADPCM + ) + })(buf)?; + + match magic { + MAGIC_HEADER_BCMEDIA_INFO_V1 => { + let (buf, payload) = bcmedia_info_v1(buf)?; + Ok((buf, BcMedia::InfoV1(payload))) + } + MAGIC_HEADER_BCMEDIA_INFO_V2 => { + let (buf, payload) = bcmedia_info_v2(buf)?; + Ok((buf, BcMedia::InfoV2(payload))) + } + MAGIC_HEADER_BCMEDIA_IFRAME => { + let (buf, payload) = bcmedia_iframe(buf)?; + Ok((buf, BcMedia::Iframe(payload))) + } + MAGIC_HEADER_BCMEDIA_PFRAME => { + let (buf, payload) = bcmedia_pframe(buf)?; + Ok((buf, BcMedia::Pframe(payload))) + } + MAGIC_HEADER_BCMEDIA_AAC => { + let (buf, payload) = bcmedia_aac(buf)?; + Ok((buf, BcMedia::Aac(payload))) + } + MAGIC_HEADER_BCMEDIA_ADPCM => { + let (buf, payload) = bcmedia_adpcm(buf)?; + Ok((buf, BcMedia::Adpcm(payload))) + } + _ => unreachable!(), + } +} + +fn bcmedia_info_v1(buf: &[u8]) -> IResult<&[u8], BcMediaInfoV1> { + let (buf, _header_size) = verify(le_u32, |x| *x == 32)(buf)?; + let (buf, video_width) = le_u32(buf)?; + let (buf, video_height) = le_u32(buf)?; + let (buf, _unknown) = le_u8(buf)?; + let (buf, fps) = le_u8(buf)?; + let (buf, start_year) = le_u8(buf)?; + let (buf, start_month) = le_u8(buf)?; + let (buf, start_day) = le_u8(buf)?; + let (buf, start_hour) = le_u8(buf)?; + let (buf, start_min) = le_u8(buf)?; + let (buf, start_seconds) = le_u8(buf)?; + let (buf, end_year) = le_u8(buf)?; + let (buf, end_month) = le_u8(buf)?; + let (buf, end_day) = le_u8(buf)?; + let (buf, end_hour) = le_u8(buf)?; + let (buf, end_min) = le_u8(buf)?; + let (buf, end_seconds) = le_u8(buf)?; + let (buf, _unknown_b) = le_u16(buf)?; + + Ok(( + buf, + BcMediaInfoV1 { + // header_size, + video_width, + video_height, + fps, + start_year, + start_month, + start_day, + start_hour, + start_min, + start_seconds, + end_year, + end_month, + end_day, + end_hour, + end_min, + end_seconds, + }, + )) +} + +fn bcmedia_info_v2(buf: &[u8]) -> IResult<&[u8], BcMediaInfoV2> { + let (buf, _header_size) = verify(le_u32, |x| *x == 32)(buf)?; + let (buf, video_width) = le_u32(buf)?; + let (buf, video_height) = le_u32(buf)?; + let (buf, _unknown) = le_u8(buf)?; + let (buf, fps) = le_u8(buf)?; + let (buf, start_year) = le_u8(buf)?; + let (buf, start_month) = le_u8(buf)?; + let (buf, start_day) = le_u8(buf)?; + let (buf, start_hour) = le_u8(buf)?; + let (buf, start_min) = le_u8(buf)?; + let (buf, start_seconds) = le_u8(buf)?; + let (buf, end_year) = le_u8(buf)?; + let (buf, end_month) = le_u8(buf)?; + let (buf, end_day) = le_u8(buf)?; + let (buf, end_hour) = le_u8(buf)?; + let (buf, end_min) = le_u8(buf)?; + let (buf, end_seconds) = le_u8(buf)?; + let (buf, _unknown_b) = le_u16(buf)?; + + Ok(( + buf, + BcMediaInfoV2 { + // header_size, + video_width, + video_height, + fps, + start_year, + start_month, + start_day, + start_hour, + start_min, + start_seconds, + end_year, + end_month, + end_day, + end_hour, + end_min, + end_seconds, + }, + )) +} + +fn bcmedia_iframe(buf: &[u8]) -> IResult<&[u8], BcMediaIframe> { + named!(take4str( &[u8] ) -> &str, take_str!( 4 ) ); + let (buf, video_type_str) = verify(take4str, |x| matches!(x, "H264" | "H265"))(buf)?; + let (buf, payload_size) = le_u32(buf)?; + let (buf, _unknown_a) = le_u32(buf)?; + let (buf, microseconds) = le_u32(buf)?; + let (buf, _unknown_b) = le_u32(buf)?; + let (buf, time) = le_u32(buf)?; + let (buf, _unknown_c) = le_u32(buf)?; + let (buf, data_slice) = take!(buf, payload_size)?; + let pad_size = match payload_size % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + let (buf, _padding) = take!(buf, pad_size)?; + + let video_type = match video_type_str { + "H264" => VideoType::H264, + "H265" => VideoType::H265, + _ => unreachable!(), + }; + + Ok(( + buf, + BcMediaIframe { + video_type, + // payload_size, + microseconds, + time, + data: data_slice.to_vec(), + }, + )) +} + +fn bcmedia_pframe(buf: &[u8]) -> IResult<&[u8], BcMediaPframe> { + named!(take4str( &[u8] ) -> &str, take_str!( 4 ) ); + let (buf, video_type_str) = verify(take4str, |x| matches!(x, "H264" | "H265"))(buf)?; + let (buf, payload_size) = le_u32(buf)?; + let (buf, _unknown_a) = le_u32(buf)?; + let (buf, microseconds) = le_u32(buf)?; + let (buf, _unknown_b) = le_u32(buf)?; + let (buf, data_slice) = take!(buf, payload_size)?; + let pad_size = match payload_size % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + let (buf, _padding) = take!(buf, pad_size)?; + + let video_type = match video_type_str { + "H264" => VideoType::H264, + "H265" => VideoType::H265, + _ => unreachable!(), + }; + + Ok(( + buf, + BcMediaPframe { + video_type, + // payload_size, + microseconds, + data: data_slice.to_vec(), + }, + )) +} + +fn bcmedia_aac(buf: &[u8]) -> IResult<&[u8], BcMediaAac> { + let (buf, payload_size) = le_u16(buf)?; + let (buf, _payload_size_b) = le_u16(buf)?; + let (buf, data_slice) = take!(buf, payload_size)?; + let pad_size = match payload_size as u32 % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + let (buf, _padding) = take!(buf, pad_size)?; + + Ok(( + buf, + BcMediaAac { + // payload_size, + data: data_slice.to_vec(), + }, + )) +} + +fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> { + const SUB_HEADER_SIZE: u16 = 4; + + let (buf, payload_size) = le_u16(buf)?; + let (buf, _payload_size_b) = le_u16(buf)?; + let (buf, _magic) = verify(le_u16, |x| *x == MAGIC_HEADER_BCMEDIA_ADPCM_DATA)(buf)?; + // On some camera this value is just 2 + // On other cameras is half the block size without the header + let (buf, _half_block_size) = le_u16(buf)?; + let block_size = payload_size - SUB_HEADER_SIZE; + let (buf, data_slice) = take!(buf, block_size)?; + let pad_size = match payload_size as u32 % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + let (buf, _padding) = take!(buf, pad_size)?; + + Ok(( + buf, + BcMediaAdpcm { + // payload_size, + // block_size, + data: data_slice.to_vec(), + }, + )) +} + +#[cfg(test)] +mod tests { + use super::Error; + use crate::bc_protocol::filesub::FileSubscriber; + use crate::bcmedia::model::*; + use env_logger::Env; + use log::*; + use std::io::ErrorKind; + use std::path::PathBuf; + + fn init() { + let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) + .is_test(true) + .try_init(); + } + + fn sample(name: &str) -> PathBuf { + let dir = std::env::current_dir().unwrap(); // This is crate root during cargo test + dir.join("src").join("bcmedia").join("samples").join(name) + } + + #[test] + // This method will test the decoding on swann cameras output + // + // Crucially this contains adpcm + fn test_swan_deser() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![ + sample("video_stream_swan_00.raw"), + sample("video_stream_swan_01.raw"), + sample("video_stream_swan_02.raw"), + sample("video_stream_swan_03.raw"), + sample("video_stream_swan_04.raw"), + sample("video_stream_swan_05.raw"), + sample("video_stream_swan_06.raw"), + sample("video_stream_swan_07.raw"), + sample("video_stream_swan_08.raw"), + sample("video_stream_swan_09.raw"), + ]); + + // Should derealise all of this + loop { + let e = BcMedia::deserialize(&mut subsciber); + match e { + Err(Error::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => { + // Reach end of files + break; + } + Err(e) => { + error!("{:?}", e); + panic!(); + } + Ok(_) => {} + } + } + } + + #[test] + // Tests the decoding of an info v1 + fn test_info_v1() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("info_v1.raw")]); + + let e = BcMedia::deserialize(&mut subsciber); + assert!(matches!( + e, + Ok(BcMedia::InfoV1(BcMediaInfoV1 { + video_width: 2560, + video_height: 1440, + fps: 30, + start_year: 121, + start_month: 8, + start_day: 4, + start_hour: 23, + start_min: 23, + start_seconds: 52, + end_year: 121, + end_month: 8, + end_day: 4, + end_hour: 23, + end_min: 23, + end_seconds: 52, + })) + )); + } + + #[test] + fn test_iframe() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![ + sample("iframe_0.raw"), + sample("iframe_1.raw"), + sample("iframe_2.raw"), + sample("iframe_3.raw"), + sample("iframe_4.raw"), + ]); + + let e = BcMedia::deserialize(&mut subsciber); + if let Ok(BcMedia::Iframe(BcMediaIframe { + video_type: VideoType::H264, + microseconds: 3557705112, + time: 1628085232, + data: d, + })) = e + { + assert_eq!(d.len(), 192881); + } else { + panic!(); + } + } + + #[test] + fn test_pframe() { + init(); + + let mut subsciber = + FileSubscriber::from_files(vec![sample("pframe_0.raw"), sample("pframe_1.raw")]); + + let e = BcMedia::deserialize(&mut subsciber); + if let Ok(BcMedia::Pframe(BcMediaPframe { + video_type: VideoType::H264, + microseconds: 3557767112, + data: d, + })) = e + { + assert_eq!(d.len(), 45108); + } else { + panic!(); + } + } + + #[test] + fn test_adpcm() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("adpcm_0.raw")]); + + let e = BcMedia::deserialize(&mut subsciber); + if let Ok(BcMedia::Adpcm(BcMediaAdpcm { data: d })) = e { + assert_eq!(d.len(), 244); + } else { + panic!(); + } + } +} diff --git a/crates/core/src/bcmedia/mod.rs b/crates/core/src/bcmedia/mod.rs new file mode 100644 index 0000000..7ae23f4 --- /dev/null +++ b/crates/core/src/bcmedia/mod.rs @@ -0,0 +1,6 @@ +/// Deserlizer for BCMedia +pub mod de; +/// Structure model for BCMedia +pub mod model; +/// Serlizer for BCMedia +pub mod ser; diff --git a/crates/core/src/bcmedia/model.rs b/crates/core/src/bcmedia/model.rs new file mode 100644 index 0000000..3edc8a5 --- /dev/null +++ b/crates/core/src/bcmedia/model.rs @@ -0,0 +1,190 @@ +/// Video streams encapsulate a stream of BcMedia +#[derive(Debug)] +pub enum BcMedia { + /// Holds info on the stream + InfoV1(BcMediaInfoV1), + /// Holds info on the stream + InfoV2(BcMediaInfoV2), + /// Holds an IFrame either H264 or H265 + Iframe(BcMediaIframe), + /// Holds a PFrame either H264 or H265 + Pframe(BcMediaPframe), + /// Holds AAC audio + Aac(BcMediaAac), + /// Holds ADPCM audio + Adpcm(BcMediaAdpcm), +} +// +pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031; + +/// The start of a BcMedia stream contains this message +/// which describes the data to follow +#[derive(Debug)] +pub struct BcMediaInfoV1 { + // This is the size of the header so it's actually a fixed value + // The other messages have body size here so maybe that's why + // it's included + // pub header_size: u32, + /// Width of the video + pub video_width: u32, + /// Height of the video + pub video_height: u32, + // pub unknown: u8, + /// Frames per second. On older cameras this seems to be an index of the FPS on a lookup table + pub fps: u8, + /// Start year of the stream + pub start_year: u8, + /// Start month of the stream + pub start_month: u8, + /// Start day of the stream + pub start_day: u8, + /// Start hour of the stream + pub start_hour: u8, + /// Start minute of the stream + pub start_min: u8, + /// Start seconds of the stream + pub start_seconds: u8, + /// End year of the video probably only useful for the recorded files on the SD card + pub end_year: u8, + /// End month of the video probably only useful for the recorded files on the SD card + pub end_month: u8, + /// End day of the video probably only useful for the recorded files on the SD card + pub end_day: u8, + /// End hour of the video probably only useful for the recorded files on the SD card + pub end_hour: u8, + /// End min of the video probably only useful for the recorded files on the SD card + pub end_min: u8, + /// End seconds of the video probably only useful for the recorded files on the SD card + pub end_seconds: u8, + // unknown: u16 +} +// +pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031; + +/// The start of a BcMedia stream contains this message +/// which describes the data to follow +#[derive(Debug)] +pub struct BcMediaInfoV2 { + // This is the size of the header so it's actually a fixed value + // The other messages have body size here so maybe that's why + // it's included + // pub header_size: u32, + /// Width of the video + pub video_width: u32, + /// Height of the video + pub video_height: u32, + // pub unknown: u8, + /// Frames per second. On older cameras this seems to be an index of the FPS on a lookup table + pub fps: u8, + /// Start year of the stream + pub start_year: u8, + /// Start month of the stream + pub start_month: u8, + /// Start day of the stream + pub start_day: u8, + /// Start hour of the stream + pub start_hour: u8, + /// Start minute of the stream + pub start_min: u8, + /// Start seconds of the stream + pub start_seconds: u8, + /// End year of the video probably only useful for the recorded files on the SD card + pub end_year: u8, + /// End month of the video probably only useful for the recorded files on the SD card + pub end_month: u8, + /// End day of the video probably only useful for the recorded files on the SD card + pub end_day: u8, + /// End hour of the video probably only useful for the recorded files on the SD card + pub end_hour: u8, + /// End min of the video probably only useful for the recorded files on the SD card + pub end_min: u8, + /// End seconds of the video probably only useful for the recorded files on the SD card + pub end_seconds: u8, + // unknown: u16 +} + +pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030; + +/// Video Types for I/PFrame +#[derive(Debug)] +pub enum VideoType { + /// H264 video data + H264, + /// H265 video data + H265, +} + +/// This is a BcMedia video IFrame. +#[derive(Debug)] +pub struct BcMediaIframe { + /// "H264", or "H265" + pub video_type: VideoType, + // Size of payload after header in bytes + // pub payload_size: u32, + // unknown: u32, // NVR channel count? Known values 1-00/08 2-00 3-00 4-00 + /// Timestamp in microseconds + pub microseconds: u32, + // unknown: u32, // Known values 1-00/23/5A 2-00 3-00 4-00 + /// POSIX time (seconds since 00:00:00 Jan 1 1970) + pub time: u32, + //unknown: u32, // Known values 1-00/06/29 2-00/01 3-00/C3 4-00 + /// Raw IFrame data + pub data: Vec, +} + +pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130; + +/// This is a BcMedia video PFrame. +#[derive(Debug)] +pub struct BcMediaPframe { + /// "H264", or "H265" + pub video_type: VideoType, + // Size of payload after header in bytes + // pub payload_size: u32, + // unknown: u32, // NVR channel count? Known values 1-00/08 2-00 3-00 4-00 + /// Timestamp in microseconds + pub microseconds: u32, + // unknown: u32, // Known values 1-00/23/5A 2-00 3-00 4-00 + /// Raw PFrame data + pub data: Vec, +} + +pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530; + +/// This contains BcMedia audio data in AAC format +#[derive(Debug)] +pub struct BcMediaAac { + // Size of payload after header in bytes + // pub payload_size: u16, + // Size of payload after header in bytes exactly the same as before + // pub payload_size_b: u16, + /// Raw AAC data + pub data: Vec, +} + +pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130; + +pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100; + +/// This contains BcMedia audio data in ADPCM format +#[derive(Debug)] +pub struct BcMediaAdpcm { + // Size of payload after header in bytes + // pub payload_size: u16, + // Size of payload after header in bytes exactly the same as before + // pub payload_size_b: u16, + // more_magic: MAGIC_HEADER_BCMEDIA_ADPCM_DATA + // Adpcm sample_block_size in bytes + // + // These bytes (and the MAGIC_HEADER_BCMEDIA_ADPCM_DATA) are included as + // part of the payload_size. It may be more prudent to sealise them to + // another structure. + // pub sample_block_size: u16, + /// The raw adpcm data in DVI-4 layout. + /// + /// One `data` should contain 4 bytes of the adpcm predictor state then one block + /// of adpcm samples + /// + /// To calculate the block-align size simply remove 4 from the `len()` + pub data: Vec, +} diff --git a/crates/core/src/bcmedia/samples/adpcm_0.raw b/crates/core/src/bcmedia/samples/adpcm_0.raw new file mode 100644 index 0000000..b46bdbb Binary files /dev/null and b/crates/core/src/bcmedia/samples/adpcm_0.raw differ diff --git a/crates/core/src/bcmedia/samples/iframe_0.raw b/crates/core/src/bcmedia/samples/iframe_0.raw new file mode 100644 index 0000000..394dd04 Binary files /dev/null and b/crates/core/src/bcmedia/samples/iframe_0.raw differ diff --git a/crates/core/src/bcmedia/samples/iframe_1.raw b/crates/core/src/bcmedia/samples/iframe_1.raw new file mode 100644 index 0000000..f1bbca0 Binary files /dev/null and b/crates/core/src/bcmedia/samples/iframe_1.raw differ diff --git a/crates/core/src/bcmedia/samples/iframe_2.raw b/crates/core/src/bcmedia/samples/iframe_2.raw new file mode 100644 index 0000000..cc62b07 Binary files /dev/null and b/crates/core/src/bcmedia/samples/iframe_2.raw differ diff --git a/crates/core/src/bcmedia/samples/iframe_3.raw b/crates/core/src/bcmedia/samples/iframe_3.raw new file mode 100644 index 0000000..4c17574 Binary files /dev/null and b/crates/core/src/bcmedia/samples/iframe_3.raw differ diff --git a/crates/core/src/bcmedia/samples/iframe_4.raw b/crates/core/src/bcmedia/samples/iframe_4.raw new file mode 100644 index 0000000..be592bc Binary files /dev/null and b/crates/core/src/bcmedia/samples/iframe_4.raw differ diff --git a/crates/core/src/bcmedia/samples/info_v1.raw b/crates/core/src/bcmedia/samples/info_v1.raw new file mode 100644 index 0000000..d28bc30 Binary files /dev/null and b/crates/core/src/bcmedia/samples/info_v1.raw differ diff --git a/crates/core/src/bcmedia/samples/pframe_0.raw b/crates/core/src/bcmedia/samples/pframe_0.raw new file mode 100644 index 0000000..57e534d Binary files /dev/null and b/crates/core/src/bcmedia/samples/pframe_0.raw differ diff --git a/crates/core/src/bcmedia/samples/pframe_1.raw b/crates/core/src/bcmedia/samples/pframe_1.raw new file mode 100644 index 0000000..4842c5f Binary files /dev/null and b/crates/core/src/bcmedia/samples/pframe_1.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_00.raw b/crates/core/src/bcmedia/samples/video_stream_swan_00.raw new file mode 100644 index 0000000..394dd04 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_00.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_01.raw b/crates/core/src/bcmedia/samples/video_stream_swan_01.raw new file mode 100644 index 0000000..f1bbca0 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_01.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_02.raw b/crates/core/src/bcmedia/samples/video_stream_swan_02.raw new file mode 100644 index 0000000..cc62b07 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_02.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_03.raw b/crates/core/src/bcmedia/samples/video_stream_swan_03.raw new file mode 100644 index 0000000..4c17574 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_03.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_04.raw b/crates/core/src/bcmedia/samples/video_stream_swan_04.raw new file mode 100644 index 0000000..be592bc Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_04.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_05.raw b/crates/core/src/bcmedia/samples/video_stream_swan_05.raw new file mode 100644 index 0000000..57e534d Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_05.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_06.raw b/crates/core/src/bcmedia/samples/video_stream_swan_06.raw new file mode 100644 index 0000000..4842c5f Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_06.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_07.raw b/crates/core/src/bcmedia/samples/video_stream_swan_07.raw new file mode 100644 index 0000000..b46bdbb Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_07.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_08.raw b/crates/core/src/bcmedia/samples/video_stream_swan_08.raw new file mode 100644 index 0000000..709aa73 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_08.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_09.raw b/crates/core/src/bcmedia/samples/video_stream_swan_09.raw new file mode 100644 index 0000000..52427f5 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_09.raw differ diff --git a/crates/core/src/bcmedia/ser.rs b/crates/core/src/bcmedia/ser.rs new file mode 100644 index 0000000..c5328cc --- /dev/null +++ b/crates/core/src/bcmedia/ser.rs @@ -0,0 +1,188 @@ +use super::model::*; +use cookie_factory::bytes::*; +use cookie_factory::sequence::tuple; +use cookie_factory::{combinator::*, gen}; +use cookie_factory::{GenError, SerializeFn}; +use err_derive::Error; +use log::error; +use std::io::Write; + +// PAD_SIZE: Media packets use 8 byte padding +const PAD_SIZE: u32 = 8; + +/// The error types used during serialisation +#[derive(Debug, Error)] +pub enum Error { + /// A Cookie Factor GenError + #[error(display = "Cookie GenError")] + GenError(#[error(source)] GenError), +} + +impl BcMedia { + pub(crate) fn serialize(&self, buf: W) -> Result { + let (buf, _) = match &self { + BcMedia::InfoV1(payload) => gen(bcmedia_info_v1(payload), buf)?, + BcMedia::InfoV2(payload) => gen(bcmedia_info_v2(payload), buf)?, + BcMedia::Iframe(payload) => { + let pad_size = match payload.data.len() as u32 % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + gen( + tuple(( + bcmedia_iframe(payload), + slice(&payload.data), + slice(&vec![0; pad_size as usize]), + )), + buf, + )? + } + BcMedia::Pframe(payload) => { + let pad_size = match payload.data.len() as u32 % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + gen( + tuple(( + bcmedia_pframe(payload), + slice(&payload.data), + slice(&vec![0; pad_size as usize]), + )), + buf, + )? + } + BcMedia::Aac(payload) => { + let pad_size = match payload.data.len() as u32 % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + gen( + tuple(( + bcmedia_aac(payload), + slice(&payload.data), + slice(&vec![0; pad_size as usize]), + )), + buf, + )? + } + BcMedia::Adpcm(payload) => { + let pad_size = match payload.data.len() as u32 % PAD_SIZE { + 0 => 0, + n => PAD_SIZE - n, + }; + gen( + tuple(( + bcmedia_adpcm(payload), + slice(&payload.data), + slice(&vec![0; pad_size as usize]), + )), + buf, + )? + } + }; + + Ok(buf) + } +} + +fn bcmedia_info_v1(payload: &BcMediaInfoV1) -> impl SerializeFn { + tuple(( + le_u32(MAGIC_HEADER_BCMEDIA_INFO_V1), + le_u32(32), + le_u32(payload.video_width), + le_u32(payload.video_height), + le_u8(0), // unknown. Known values 00/01 + le_u8(payload.fps), + le_u8(payload.start_year), + le_u8(payload.start_month), + le_u8(payload.start_day), + le_u8(payload.start_hour), + le_u8(payload.start_min), + le_u8(payload.start_seconds), + le_u8(payload.end_year), + le_u8(payload.end_month), + le_u8(payload.end_day), + le_u8(payload.end_hour), + le_u8(payload.end_min), + le_u8(payload.end_seconds), + le_u8(0), + le_u8(0), + )) +} + +fn bcmedia_info_v2(payload: &BcMediaInfoV2) -> impl SerializeFn { + tuple(( + le_u32(MAGIC_HEADER_BCMEDIA_INFO_V2), + le_u32(32), + le_u32(payload.video_width), + le_u32(payload.video_height), + le_u8(0), // unknown. Known values 00/01 + le_u8(payload.fps), + le_u8(payload.start_year), + le_u8(payload.start_month), + le_u8(payload.start_day), + le_u8(payload.start_hour), + le_u8(payload.start_min), + le_u8(payload.start_seconds), + le_u8(payload.end_year), + le_u8(payload.end_month), + le_u8(payload.end_day), + le_u8(payload.end_hour), + le_u8(payload.end_min), + le_u8(payload.end_seconds), + le_u8(0), + le_u8(0), + )) +} + +fn bcmedia_iframe(payload: &BcMediaIframe) -> impl SerializeFn { + // Cookie String needs a static lifetime + let vid_string = match payload.video_type { + VideoType::H264 => "H264", + VideoType::H265 => "H265", + }; + tuple(( + le_u32(MAGIC_HEADER_BCMEDIA_IFRAME), + string(vid_string), + le_u32(payload.data.len() as u32), + le_u32(0), // unknown. NVR channel count? Known values 1-00/08 2-00 3-00 4-00 + le_u32(payload.microseconds), + le_u32(0), // unknown. Known values 1-00/23/5A 2-00 3-00 4-00 + le_u32(payload.time), + le_u32(0), // unknown. Known values 1-00/06/29 2-00/01 3-00/C3 4-00 + )) +} + +fn bcmedia_pframe(payload: &BcMediaPframe) -> impl SerializeFn { + // Cookie String needs a static lifetime + let vid_string = match payload.video_type { + VideoType::H264 => "H264", + VideoType::H265 => "H265", + }; + tuple(( + le_u32(MAGIC_HEADER_BCMEDIA_PFRAME), + string(vid_string), + le_u32(payload.data.len() as u32), + le_u32(0), // unknown. NVR channel count? Known values 1-00/08 2-00 3-00 4-00 + le_u32(payload.microseconds), + le_u32(0), // unknown. Known values 1-00/23/5A 2-00 3-00 4-00 + )) +} + +fn bcmedia_aac(payload: &BcMediaAac) -> impl SerializeFn { + tuple(( + le_u32(MAGIC_HEADER_BCMEDIA_AAC), + le_u16(payload.data.len() as u16), + le_u16(payload.data.len() as u16), + )) +} + +fn bcmedia_adpcm(payload: &BcMediaAdpcm) -> impl SerializeFn { + tuple(( + le_u32(MAGIC_HEADER_BCMEDIA_ADPCM), + le_u16((payload.data.len() + 4) as u16), // Payload + 2 byte magic + 2byte block size + le_u16((payload.data.len() + 4) as u16), // Payload + 2 byte magic + 2byte block size + le_u16(MAGIC_HEADER_BCMEDIA_ADPCM_DATA), // magic + le_u16(((payload.data.len() - 4) / 2) as u16), // Block size without the header halved + )) +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 0000000..4b6076a --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,42 @@ +#![warn(missing_docs)] +//! # Neolink-Core +//! +//! Neolink-Core is a rust library for interacting with reolink and family cameras. +//! +//! Most high level camera controls are in the [`bc_protocol`] module +//! +//! A camera can be initialised with +//! +//! ```no_run +//! use neolink_core::bc_protocol::BcCamera; +//! let channel_id = 0; // Usually zero but can be non zero if uses a reolink NVR +//! let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap(); +//! ``` +//! +//! After that login can be conducted with +//! +//! ```no_run +//! # use neolink_core::bc_protocol::BcCamera; +//! # let channel_id = 0; +//! # let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap(); +//! camera.login("username", Some("password")); +//! ``` +//! For further commands see the [`bc_protocol::BcCamera`] struct. +//! + +/// Contains low level BC structures and formats +pub mod bc; +/// Contains high level interfaces for the camera +pub mod bc_protocol; +/// Contains low level structures and formats for the media substream +pub mod bcmedia; + +#[derive(Debug)] +/// Certain method just as `start_video` will block forever or return an error +/// In such a case the return type is `Result` +pub enum Never {} + +/// This is the top level error structure of the library +/// +/// Most commands will either return their `Ok(result)` or this `Err(Error)` +pub use bc_protocol::Error; diff --git a/dissector/mediapacket.md b/dissector/mediapacket.md index 26cf0b5..72adb50 100644 --- a/dissector/mediapacket.md +++ b/dissector/mediapacket.md @@ -98,9 +98,9 @@ Most of this information comes from the work of @twisteddx at his After the ADPCM header is another header of the form - 2 bytes Magic either 0x00 0x01 or 0x00 0x7a -- 2 Bytes DVI-4 Block size +- 2 Bytes DVI-4 Block size divided in bytes. -After this header the adpcm DVI-4 data follows. +After this header the adpcm DVI-4 data follows should be 4+Block size bytes. ## Processing diff --git a/dissector/messages.md b/dissector/messages.md index a2f2a8f..2b33cc2 100644 --- a/dissector/messages.md +++ b/dissector/messages.md @@ -363,6 +363,25 @@ Message have zero to two payloads. |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 12 | 00 00 00 00 | 1e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | +- 23: `Reboot` + + - Client + + - Header + + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| + | 0a bc de f0 | 00 00 00 17 | 00 00 00 00 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | + + + - Camera + + - Header + + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| + | 0a bc de f0 | 00 00 00 17 | 00 00 00 00 | 00 00 00 00 | c8 00 | 64 14 | 00 00 00 00 | + - 25: `` (write) - Client @@ -2085,6 +2104,78 @@ Message have zero to two payloads. ``` +- 201: `` + + - Client + + - Header + + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| + | 0a bc de f0 | 00 00 00 c9 | 00 00 01 f2 | 12 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | + + - Body + ```xml + + + 0 + + ``` + + - Binary + + ```xml + + + + 0 + FDX + followVideoStream + + adpcm + 16000 + 16 + 1024 + mono + + + + ``` + + - Camera + + - Header + + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| + | 0a bc de f0 | 00 00 00 c9 | 00 00 00 00 | 12 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | + +- 202: `Talk` + + - Client + + - Header + + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| + | 0a bc de f0 | 00 00 00 ca | 00 00 08 c3 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 83 | + + - Body + ```xml + + + 1 + 0 + + ``` + + - Binary + + Binary data contains media-packets of adpcm data + + + **Notes**: No reply from camera. After this the client keeps sending this packet with binary in the BcMedia encoded packets of adpcm data + - 208: `` - Client diff --git a/src/bc/mod.rs b/src/bc/mod.rs deleted file mode 100644 index 9a91158..0000000 --- a/src/bc/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! The Baichuan message format is a 20 byte header, the contents of which vary between legacy and -//! modern messages: -//! -//! -//! -//! This header is followed by the message body. In legacy messages, the bodies are -//! message-specific binary formats. Currently, we only attempt to interpret the legacy login -//! message, as it is all that is needed to upgrade to the modern XML-based messages. Modern -//! messages are either "encrypted" XML (the encryption is a simple XOR routine) or binary data. -//! All message IDs start out as XML, but can be statefully switched to binary with a special XML -//! "Extension" message. - -pub mod model; - -pub mod de; -pub mod ser; -pub mod xml; - -mod xml_crypto; diff --git a/src/bc/model.rs b/src/bc/model.rs deleted file mode 100644 index 1dcb6a8..0000000 --- a/src/bc/model.rs +++ /dev/null @@ -1,193 +0,0 @@ -pub use super::xml::{BcPayloads, BcXml, Extension}; -use std::collections::HashSet; -use std::sync::{Arc, Mutex}; - -pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; - -pub const MSG_ID_LOGIN: u32 = 1; -pub const MSG_ID_VIDEO: u32 = 3; -pub const MSG_ID_VERSION: u32 = 80; -pub const MSG_ID_PING: u32 = 93; -pub const MSG_ID_GET_GENERAL: u32 = 104; -pub const MSG_ID_SET_GENERAL: u32 = 105; - -pub const EMPTY_LEGACY_PASSWORD: &str = - "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; - -#[derive(Debug, PartialEq, Eq)] -pub struct Bc { - pub meta: BcMeta, - pub body: BcBody, -} - -#[derive(Debug, PartialEq, Eq)] -#[allow(clippy::large_enum_variant)] -pub enum BcBody { - LegacyMsg(LegacyMsg), - ModernMsg(ModernMsg), -} - -#[derive(Debug, Default, PartialEq, Eq)] -pub struct ModernMsg { - pub extension: Option, - pub payload: Option, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum LegacyMsg { - LoginMsg { username: String, password: String }, - UnknownMsg, -} - -#[derive(Debug, PartialEq, Eq)] -pub(super) struct BcHeader { - pub body_len: u32, - pub msg_id: u32, - pub channel_id: u8, - pub stream_type: u8, - pub msg_num: u16, - pub response_code: u16, - pub class: u16, - pub payload_offset: Option, -} - -/// The components of the Baichuan TLV header that are not -/// descriptions of the Body (the application dictates these) -#[derive(Debug, PartialEq, Eq)] -pub struct BcMeta { - pub msg_id: u32, - pub channel_id: u8, - pub stream_type: u8, - pub response_code: u16, - pub msg_num: u16, - pub class: u16, -} - -/// The components of the Baichuan header that must be filled out after the body is serialized, or -/// is needed for the deserialization of the body (strictly part of the wire format of the message) -#[derive(Debug, PartialEq, Eq)] -pub(super) struct BcSendInfo { - pub body_len: u32, - pub payload_offset: Option, -} - -#[derive(Debug, Clone)] -pub enum EncryptionProtocol { - Unencrypted, - BCEncrypt, - Aes(Option<[u8; 16]>), -} - -#[derive(Debug)] -pub struct BcContext { - pub(super) in_bin_mode: HashSet, - // Arc> because it is shared between context - // and connection for deserialisation and serialistion respectivly - pub(super) encryption_protocol: Arc>, -} - -impl Bc { - /// Convenience function that constructs a modern Bc message from the given meta and XML, with - /// no binary payload. - pub fn new_from_xml(meta: BcMeta, xml: BcXml) -> Bc { - Bc { - meta, - body: BcBody::ModernMsg(ModernMsg { - extension: None, - payload: Some(BcPayloads::BcXml(xml)), - }), - } - } - - pub fn new_from_ext(meta: BcMeta, xml: Extension) -> Bc { - Bc { - meta, - body: BcBody::ModernMsg(ModernMsg { - extension: Some(xml), - payload: None, - }), - } - } - - pub fn new_from_meta(meta: BcMeta) -> Bc { - Bc { - meta, - body: BcBody::ModernMsg(ModernMsg { - extension: None, - payload: None, - }), - } - } - - pub fn new_from_ext_xml(meta: BcMeta, ext: Extension, xml: BcXml) -> Bc { - Bc { - meta, - body: BcBody::ModernMsg(ModernMsg { - extension: Some(ext), - payload: Some(BcPayloads::BcXml(xml)), - }), - } - } -} - -impl BcContext { - pub fn new(encryption_protocol: Arc>) -> BcContext { - BcContext { - in_bin_mode: HashSet::new(), - encryption_protocol, - } - } - - pub fn set_encrypted(&mut self, encryption_protocol: EncryptionProtocol) { - *(self.encryption_protocol.lock().unwrap()) = encryption_protocol; - } - - pub fn get_encrypted(&self) -> EncryptionProtocol { - (*(self.encryption_protocol.lock().unwrap())).clone() - } -} - -impl BcHeader { - pub fn is_modern(&self) -> bool { - // Most modern messages have an extra word at the end of the header; this - // serves as the start offset of the appended payload data, if any. - // A notable exception is the encrypted reply to the login message; - // in this case the message is modern (with XML encryption etc), but there is - // no extra word. - // Here are the message classes: - // 0x6514: legacy, no bin offset (initial login message, encrypted or not) - // 0x6614: modern, no bin offset (reply to encrypted 0x6514 login) - // 0x6414: modern, has bin offset, encrypted if supported (re-sent login message) - // 0x0000, modern, has bin offset (most modern messages) - self.class != 0x6514 - } - - pub fn to_meta(&self) -> BcMeta { - BcMeta { - msg_id: self.msg_id, - msg_num: self.msg_num, - channel_id: self.channel_id, - response_code: self.response_code, - stream_type: self.stream_type, - class: self.class, - } - } - - pub fn from_meta(meta: &BcMeta, body_len: u32, payload_offset: Option) -> BcHeader { - BcHeader { - payload_offset, - body_len, - msg_id: meta.msg_id, - channel_id: meta.channel_id, - stream_type: meta.stream_type, - response_code: meta.response_code, - msg_num: meta.msg_num, - class: meta.class, - } - } -} - -pub(super) fn has_payload_offset(class: u16) -> bool { - // See BcHeader::is_modern() for a description of which packets have the bin offset - class == 0x6414 || class == 0x0000 -} diff --git a/src/bc_protocol.rs b/src/bc_protocol.rs deleted file mode 100644 index 3f60db6..0000000 --- a/src/bc_protocol.rs +++ /dev/null @@ -1,453 +0,0 @@ -use self::connection::BcConnection; -use self::media_packet::{MediaDataKind, MediaDataSubscriber}; -use crate::bc; -use crate::bc::{model::*, xml::*}; -use crate::gst::GstOutputs; -use adpcm::adpcm_to_pcm; -use err_derive::Error; -use log::*; -use std::convert::TryInto; -use std::io::Write; -use std::net::{SocketAddr, ToSocketAddrs}; -use std::sync::atomic::{AtomicU16, Ordering}; -use std::time::Duration; - -use Md5Trunc::*; - -mod adpcm; -mod connection; -mod media_packet; -mod time; - -pub struct BcCamera { - address: SocketAddr, - channel_id: u8, - connection: Option, - logged_in: bool, - message_num: AtomicU16, -} - -use crate::Never; - -type Result = std::result::Result; - -const RX_TIMEOUT: Duration = Duration::from_secs(5); - -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - #[error(display = "Communication error")] - CommunicationError(#[error(source)] std::io::Error), - - #[error(display = "Deserialization error")] - DeserializationError(#[error(source)] bc::de::Error), - - #[error(display = "Serialization error")] - SerializationError(#[error(source)] bc::ser::Error), - - #[error(display = "Connection error")] - ConnectionError(#[error(source)] self::connection::Error), - - #[error(display = "Communication error")] - UnintelligibleReply { reply: Bc, why: &'static str }, - - #[error(display = "Dropped connection")] - DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), - - #[error(display = "Timeout")] - Timeout, - - #[error(display = "Dropped connection")] - TimeoutDisconnected, - - #[error(display = "Credential error")] - AuthFailed, - - #[error(display = "Failed to translate camera address")] - AddrResolutionError, - - #[error(display = "ADPCM Decoding Error")] - AdpcmDecodingError(&'static str), - - #[error(display = "Other error")] - Other(&'static str), -} - -impl<'a> From for Error { - fn from(k: std::sync::mpsc::RecvTimeoutError) -> Self { - match k { - std::sync::mpsc::RecvTimeoutError::Timeout => Error::Timeout, - std::sync::mpsc::RecvTimeoutError::Disconnected => Error::TimeoutDisconnected, - } - } -} - -impl Drop for BcCamera { - fn drop(&mut self) { - self.disconnect(); - } -} - -impl BcCamera { - pub fn new_with_addr(host: T, channel_id: u8) -> Result { - let addr_iter = match host.to_socket_addrs() { - Ok(iter) => iter, - Err(_) => return Err(Error::AddrResolutionError), - }; - - for addr in addr_iter { - debug!("Trying {}", addr); - let conn = match BcConnection::new(addr, RX_TIMEOUT) { - Ok(conn) => conn, - Err(err) => match err { - connection::Error::CommunicationError(ref err) => { - debug!("Assuming timeout from {}", err); - continue; - } - err => return Err(err.into()), - }, - }; - - debug!("Success: {}", addr); - return Ok(Self { - address: addr, - connection: Some(conn), - message_num: AtomicU16::new(0), - channel_id, - logged_in: false, - }); - } - - Err(Error::Timeout) - } - - pub fn new_message_num(&self) -> u16 { - self.message_num.fetch_add(1, Ordering::Relaxed) - } - - pub fn disconnect(&mut self) { - if let Err(err) = self.logout() { - warn!("Could not log out, ignoring: {}", err); - } - self.connection = None; - } - - pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { - let connection = self - .connection - .as_ref() - .expect("Must be connected to log in"); - let sub_login = connection.subscribe(MSG_ID_LOGIN)?; - - // Login flow is: Send legacy login message, expect back a modern message with Encryption - // details. Then, re-send the login as a modern login message. Expect back a device info - // congratulating us on logging in. - - // In the legacy scheme, username/password are MD5'd if they are encrypted (which they need - // to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent. - // Note: I suspect there may be a buffer overflow opportunity in the firmware since in the - // Baichuan library, these strings are capped at 32 bytes with a null terminator. This - // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. - let md5_username = md5_string(username, ZeroLast); - let md5_password = password - .map(|p| md5_string(p, ZeroLast)) - .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); - - let legacy_login = Bc { - meta: BcMeta { - msg_id: MSG_ID_LOGIN, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0xdc03, - class: 0x6514, - }, - body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { - username: md5_username, - password: md5_password, - }), - }; - - sub_login.send(legacy_login)?; - - let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; - - let nonce; - match legacy_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - encryption: Some(encryption), - .. - })), - .. - }) => { - nonce = encryption.nonce; - } - _ => { - return Err(Error::UnintelligibleReply { - reply: legacy_reply, - why: "Expected an Encryption message back", - }) - } - } - - // In the modern login flow, the username/password are concat'd with the server's nonce - // string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce - // prevents replay attacks if the server were to require modern flow, but not rainbow table - // attacks (since the plain user/password MD5s have already been sent). The upshot is that - // you should use a very strong random password that is not found in a rainbow table and - // not feasibly crackable with John the Ripper. - - let modern_password = password.unwrap_or(""); - let concat_username = format!("{}{}", username, nonce); - let concat_password = format!("{}{}", modern_password, nonce); - let md5_username = md5_string(&concat_username, Truncate); - let md5_password = md5_string(&concat_password, Truncate); - - let modern_login = Bc::new_from_xml( - BcMeta { - msg_id: MSG_ID_LOGIN, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - BcXml { - login_user: Some(LoginUser { - version: xml_ver(), - user_name: md5_username, - password: md5_password, - user_ver: 1, - }), - login_net: Some(LoginNet::default()), - ..Default::default() - }, - ); - - sub_login.send(modern_login)?; - let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; - - let device_info; - match modern_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - device_info: Some(info), - .. - })), - .. - }) => { - // Login succeeded! - self.logged_in = true; - device_info = info; - } - BcBody::ModernMsg(ModernMsg { - extension: None, - payload: None, - }) => return Err(Error::AuthFailed), - _ => { - return Err(Error::UnintelligibleReply { - reply: modern_reply, - why: "Expected a DeviceInfo message back from login", - }) - } - } - - if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { - // We setup the data for the AES key now - // as all subsequent communications will use it - let passwd = password.unwrap_or(""); - let full_key = make_aes_key(&nonce, passwd); - connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); - } - - Ok(device_info) - } - - pub fn logout(&mut self) -> Result<()> { - if self.logged_in { - // TODO: Send message ID 2 - } - self.logged_in = false; - Ok(()) - } - - pub fn version(&self) -> Result { - let connection = self - .connection - .as_ref() - .expect("Must be connected to get version info"); - let sub_version = connection.subscribe(MSG_ID_VERSION)?; - - let version = Bc { - meta: BcMeta { - msg_id: MSG_ID_VERSION, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, // IDK why - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - sub_version.send(version)?; - - let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?; - let version_info; - match modern_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - version_info: Some(info), - .. - })), - .. - }) => { - version_info = info; - } - _ => { - return Err(Error::UnintelligibleReply { - reply: modern_reply, - why: "Expected a VersionInfo message", - }) - } - } - - Ok(version_info) - } - - pub fn ping(&self) -> Result<()> { - let connection = self.connection.as_ref().expect("Must be connected to ping"); - let sub_ping = connection.subscribe(MSG_ID_PING)?; - - let ping = Bc { - meta: BcMeta { - msg_id: MSG_ID_PING, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - sub_ping.send(ping)?; - - sub_ping.rx.recv_timeout(RX_TIMEOUT)?; - - Ok(()) - } - - pub fn start_video(&self, data_outs: &mut GstOutputs, stream_name: &str) -> Result { - let connection = self - .connection - .as_ref() - .expect("Must be connected to start video"); - let sub_video = connection.subscribe(MSG_ID_VIDEO)?; - - let stream_num = match stream_name { - "mainStream" => 0, - "subStream" => 1, - _ => 0, - }; - - let start_video = Bc::new_from_xml( - BcMeta { - msg_id: MSG_ID_VIDEO, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: stream_num, - response_code: 0, - class: 0x6414, // IDK why - }, - BcXml { - preview: Some(Preview { - version: xml_ver(), - channel_id: self.channel_id, - handle: 0, - stream_type: stream_name.to_string(), - }), - ..Default::default() - }, - ); - - sub_video.send(start_video)?; - - let mut media_sub = MediaDataSubscriber::from_bc_sub(&sub_video); - - loop { - let binary_data = media_sub.next_media_packet()?; - // We now have a complete interesting packet. Send it to gst. - // Process the packet - match binary_data.kind() { - MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe => { - let media_format = binary_data.media_format(); - data_outs.set_format(media_format); - data_outs.vidsrc.write_all(binary_data.body())?; - } - MediaDataKind::AudioDataAac => { - let media_format = binary_data.media_format(); - data_outs.set_format(media_format); - data_outs.audsrc.write_all(binary_data.body())?; - } - MediaDataKind::AudioDataAdpcm => { - let media_format = binary_data.media_format(); - data_outs.set_format(media_format); - let adpcm = binary_data.body(); - let pcm = adpcm_to_pcm(adpcm)?; - data_outs.audsrc.write_all(&pcm)?; - } - _ => {} - }; - } - } -} - -/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I -/// believe this is because the MD5'ing of the user/password is a recent retrofit to the code and -/// the original code wanted to prevent a buffer overflow with strcpy. The modern and legacy login -/// messages have a slightly different behavior; the legacy message has a 32-byte buffer and the -/// modern message uses XML. The legacy code copies all 32 bytes with memcpy, and the XML value is -/// copied from a C-style string, so the appended null byte is dropped by the XML library - see the -/// test below. -/// Emulate this behavior by providing a configurable mangling of the last character. -#[derive(PartialEq, Eq)] -enum Md5Trunc { - ZeroLast, - Truncate, -} - -fn md5_string(input: &str, trunc: Md5Trunc) -> String { - let mut md5 = format!("{:X}\0", md5::compute(input)); - md5.replace_range(31.., if trunc == Truncate { "" } else { "\0" }); - md5 -} - -pub fn make_aes_key(nonce: &str, passwd: &str) -> [u8; 16] { - let key_phrase = format!("{}-{}", nonce, passwd); - let key_phrase_hash = format!("{:X}\0", md5::compute(&key_phrase)) - .to_uppercase() - .into_bytes(); - key_phrase_hash[0..16].try_into().unwrap() -} - -#[test] -fn test_md5_string() { - // Note that these literals are only 31 characters long - see explanation above. - assert_eq!( - md5_string("admin", Truncate), - "21232F297A57A5A743894A0E4A801FC" - ); - assert_eq!( - md5_string("admin", ZeroLast), - "21232F297A57A5A743894A0E4A801FC\0" - ); -} diff --git a/src/bc_protocol/media_packet.rs b/src/bc_protocol/media_packet.rs deleted file mode 100644 index 09f1d01..0000000 --- a/src/bc_protocol/media_packet.rs +++ /dev/null @@ -1,303 +0,0 @@ -use super::{Error, Result, RX_TIMEOUT}; -use crate::bc::model::*; -use crate::bc_protocol::connection::BcSubscription; -use crate::gst::StreamFormat; -use log::trace; -use log::*; -use std::collections::VecDeque; -use std::convert::TryInto; - -const INVALID_MEDIA_PACKETS: &[MediaDataKind] = &[MediaDataKind::Unknown]; - -// MAGIC_SIZE: Number of bytes needed to get magic header type, represets minimum bytes to pull from the -// stream -const MAGIC_SIZE: usize = 4; -// PAD_SIZE: Media packets use 8 byte padding -const PAD_SIZE: usize = 8; - -#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] -pub enum MediaDataKind { - VideoDataIframe, - VideoDataPframe, - AudioDataAac, - AudioDataAdpcm, - InfoData, - Unknown, -} - -#[derive(Debug, PartialEq, Eq)] -pub struct MediaData { - data: Vec, -} - -impl MediaData { - pub fn body(&self) -> &[u8] { - let lower_limit = self.header_size(); - let upper_limit = self.data_size() + lower_limit; - &self.data[lower_limit..upper_limit] - } - - fn header_size_from_kind(kind: MediaDataKind) -> usize { - match kind { - MediaDataKind::VideoDataIframe => 32, - MediaDataKind::VideoDataPframe => 24, - MediaDataKind::AudioDataAac => 8, - MediaDataKind::AudioDataAdpcm => 8, - MediaDataKind::InfoData => 32, - MediaDataKind::Unknown => 0, - } - } - - fn header_size_from_raw(data: &[u8]) -> usize { - let kind = MediaData::kind_from_raw(data); - MediaData::header_size_from_kind(kind) - } - - pub fn header(&self) -> &[u8] { - &self.data[0..self.header_size()] - } - - pub fn header_dump(&self) { - info!("{:?}-hex: {:02?}", self.kind(), self.header()); - let mut result = vec![]; - for four in self.header().chunks(4) { - result.push(u32::from_le_bytes(four.try_into().unwrap())); - } - info!("{:?}-32: {:?}", self.kind(), result); - let mut result = vec![]; - for two in self.header().chunks(2) { - result.push(u16::from_le_bytes(two.try_into().unwrap())); - } - info!("{:?}-16: {:?}", self.kind(), result); - let mut result = vec![]; - for one in self.header().chunks(1) { - result.push(u8::from_le_bytes(one.try_into().unwrap())); - } - info!("{:?}-8: {:?}", self.kind(), result); - let mut result = vec![]; - for four in self.header().chunks(4) { - result.push(f32::from_le_bytes(four.try_into().unwrap())); - } - info!("{:?}-f32: {:?}", self.kind(), result); - let mut result = vec![]; - for four in self.header().chunks(4) { - result.push(String::from_utf8_lossy(four)); - } - info!("{:?}-utf8: {:?}", self.kind(), result); - } - - fn header_size(&self) -> usize { - MediaData::header_size_from_raw(&self.data) - } - - fn data_size_from_raw(data: &[u8]) -> usize { - let kind = MediaData::kind_from_raw(data); - match kind { - MediaDataKind::VideoDataIframe => MediaData::bytes_to_size(&data[8..12]), - MediaDataKind::VideoDataPframe => MediaData::bytes_to_size(&data[8..12]), - MediaDataKind::AudioDataAac => MediaData::bytes_to_size(&data[4..6]), - MediaDataKind::AudioDataAdpcm => MediaData::bytes_to_size(&data[4..6]), - MediaDataKind::InfoData => 0, // The bytes in MediaData::bytes_to_size(&data[4..8]) seem to be the size of the header - MediaDataKind::Unknown => data.len(), - } - } - - fn data_size(&self) -> usize { - MediaData::data_size_from_raw(&self.data) - } - - fn pad_size_from_raw(data: &[u8]) -> usize { - let data_size = MediaData::data_size_from_raw(data); - match data_size % PAD_SIZE { - 0 => 0, - n => PAD_SIZE - n, - } - } - - fn bytes_to_size(bytes: &[u8]) -> usize { - match bytes.len() { - // 8 Won't fit into usize on a 32-bit machine - 4 => u32::from_le_bytes(bytes.try_into().expect("slice with incorrect length")) - .try_into() - .expect("u32 won't fit into usize"), - 2 => u16::from_le_bytes(bytes.try_into().expect("slice with incorrect length")) - .try_into() - .expect("u16 won't fit into usize"), - 1 => u8::from_le_bytes(bytes.try_into().expect("slice with incorrect length")) - .try_into() - .expect("u8 won't fit into usize"), - _ => unreachable!(), - } - } - - fn kind_from_raw(data: &[u8]) -> MediaDataKind { - // When calling this ensure you have enough data for header_size +2 - // Else full_header_check_from_kind will fail because we check the - // First two bytes after the header for the audio stream - // Since AAC and ADMPC streams start in a predicatble manner - assert!( - data.len() >= MAGIC_SIZE, - "At least four bytes needed to get media packet type" - ); - const MAGIC_VIDEO_INFO_V1: &[u8] = &[0x31, 0x30, 0x30, 0x31]; - const MAGIC_VIDEO_INFO_V2: &[u8] = &[0x31, 0x30, 0x30, 0x32]; - const MAGIC_AAC: &[u8] = &[0x30, 0x35, 0x77, 0x62]; - const MAGIC_ADPCM: &[u8] = &[0x30, 0x31, 0x77, 0x62]; - const MAGIC_IFRAME: &[u8] = &[0x30, 0x30, 0x64, 0x63]; - const MAGIC_PFRAME: &[u8] = &[0x30, 0x31, 0x64, 0x63]; - - let magic = &data[..MAGIC_SIZE]; - match magic { - MAGIC_VIDEO_INFO_V1 | MAGIC_VIDEO_INFO_V2 => MediaDataKind::InfoData, - MAGIC_AAC => MediaDataKind::AudioDataAac, - MAGIC_ADPCM => MediaDataKind::AudioDataAdpcm, - MAGIC_IFRAME => MediaDataKind::VideoDataIframe, - MAGIC_PFRAME => MediaDataKind::VideoDataPframe, - _ => { - //trace!("Unknown magic kind: {:x?}", &magic); - MediaDataKind::Unknown - } - } - } - - pub fn kind(&self) -> MediaDataKind { - MediaData::kind_from_raw(&self.data) - } - - pub fn media_format(&self) -> Option { - let kind = self.kind(); - match kind { - MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe => { - let stream_type = &self.data[4..8]; - const H264_STR_UPPER: &[u8] = &[0x48, 0x32, 0x36, 0x34]; - const H264_STR_LOWER: &[u8] = &[0x68, 0x32, 0x36, 0x34]; - const H265_STR_UPPER: &[u8] = &[0x48, 0x32, 0x36, 0x35]; - const H265_STR_LOWER: &[u8] = &[0x68, 0x32, 0x36, 0x35]; - match stream_type { - H264_STR_UPPER | H264_STR_LOWER => Some(StreamFormat::H264), // Offically it should be "H264" not "h264" but covering all cases - H265_STR_UPPER | H265_STR_LOWER => Some(StreamFormat::H265), - _ => None, - } - } - MediaDataKind::AudioDataAac => Some(StreamFormat::AAC), - MediaDataKind::AudioDataAdpcm => Some(StreamFormat::ADPCM), - _ => None, - } - } - - pub fn timestamp(&self) -> Option { - let kind = self.kind(); - match kind { - MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe => Some( - Self::bytes_to_size(&self.data[16..20]) - .try_into() - .expect("usize wont fit into u64"), - ), - _ => None, - } - } -} - -pub struct MediaDataSubscriber<'a> { - binary_buffer: VecDeque, - bc_sub: &'a BcSubscription<'a>, -} - -impl<'a> MediaDataSubscriber<'a> { - pub fn from_bc_sub<'b>(bc_sub: &'b BcSubscription) -> MediaDataSubscriber<'b> { - MediaDataSubscriber { - binary_buffer: VecDeque::new(), - bc_sub, - } - } - - fn fill_binary_buffer(&mut self) -> Result<()> { - // Loop messages until we get binary add that data and return - loop { - let msg = self.bc_sub.rx.recv_timeout(RX_TIMEOUT)?; - if let BcBody::ModernMsg(ModernMsg { - payload: Some(BcPayloads::Binary(binary)), - .. - }) = msg.body - { - // Add the new binary to the buffer and return - self.binary_buffer.extend(binary); - break; - } - } - Ok(()) - } - - fn advance_to_media_packet(&mut self) -> Result<()> { - // In the event we get an unknown packet we advance by brute force - // reading of bytes to the next valid magic - while self.binary_buffer.len() < MAGIC_SIZE { - self.fill_binary_buffer()?; - } - - // Check the kind, if its invalid use pop a byte and try again - let mut magic = MediaDataSubscriber::get_first_n_deque(&self.binary_buffer, MAGIC_SIZE); - if INVALID_MEDIA_PACKETS.contains(&MediaData::kind_from_raw(&magic)) { - warn!("Possibly truncated packet or unknown magic in stream"); - trace!("Unknown magic was: {:x?}", &magic); - } - while INVALID_MEDIA_PACKETS.contains(&MediaData::kind_from_raw(&magic)) { - self.binary_buffer.pop_front(); - while self.binary_buffer.len() < MAGIC_SIZE { - self.fill_binary_buffer()?; - } - magic = MediaDataSubscriber::get_first_n_deque(&self.binary_buffer, MAGIC_SIZE); - } - - Ok(()) - } - - fn get_first_n_deque(deque: &VecDeque, n: usize) -> Vec { - // NOTE: I want to use make_contiguous - // This will make this func unneeded as we can use - // make_contiguous then as_slices.0 - // We won't need the clone in this case either. - // This is an experimental feature. - // It is about to be moved to stable though - // As can be seen from this PR - // https://github.com/rust-lang/rust/pull/74559 - let slice0 = deque.as_slices().0; - let slice1 = deque.as_slices().1; - if slice0.len() >= n { - slice0[0..n].to_vec() - } else { - let remain = n - slice0.len(); - slice0.iter().chain(&slice1[0..remain]).cloned().collect() - } - } - - pub fn next_media_packet(&mut self) -> std::result::Result { - // Find the first packet (does nothing if already at one) - self.advance_to_media_packet()?; - - // Get the magic bytes (guaranteed by advance_to_media_packet) - let magic = MediaDataSubscriber::get_first_n_deque(&self.binary_buffer, MAGIC_SIZE); - - // Get enough for the full header - let header_size = MediaData::header_size_from_raw(&magic); - while self.binary_buffer.len() < header_size { - self.fill_binary_buffer()?; - } - - // Get enough for the full data + 8 byte buffer - let header = MediaDataSubscriber::get_first_n_deque(&self.binary_buffer, header_size); - let data_size = MediaData::data_size_from_raw(&header); - let pad_size = MediaData::pad_size_from_raw(&header); - let full_size = header_size + data_size + pad_size; - while self.binary_buffer.len() < full_size { - self.fill_binary_buffer()?; - } - - // Pop the full binary buffer - let binary = self.binary_buffer.drain(..full_size); - - Ok(MediaData { - data: binary.collect(), - }) - } -} diff --git a/src/cmdline.rs b/src/cmdline.rs index 5c07494..6136dce 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -1,11 +1,20 @@ use std::path::PathBuf; -use structopt::StructOpt; +use structopt::{clap::AppSettings, StructOpt}; /// A standards-compliant bridge to Reolink IP cameras #[derive(StructOpt, Debug)] -#[structopt(name = "neolink")] +#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))] pub struct Opt { - /// main configuration file #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, + pub config: Option, + #[structopt(subcommand)] + pub cmd: Option, +} + +#[derive(StructOpt, Debug)] +pub enum Command { + Rtsp(super::rtsp::Opt), + StatusLight(super::statusled::Opt), + Reboot(super::reboot::Opt), + Talk(super::talk::Opt), } diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index fe2d620..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -#![allow(dead_code)] -#![allow(unused_variables)] -pub mod bc; -pub mod bc_protocol; -pub mod gst; - -#[derive(Debug)] -pub enum Never {} - -pub use bc_protocol::Error; diff --git a/src/main.rs b/src/main.rs index 811f5b1..64f1f63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,39 +1,26 @@ +#![warn(missing_docs)] +//! +//! # Neolink +//! +//! Neolink is a small program that acts a general contol interface for Reolink IP cameras. +//! +//! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras +//! that do not nativly support RTSP. +//! +use anyhow::Result; use env_logger::Env; -use err_derive::Error; -use gio::TlsAuthenticationMode; use log::*; -use neolink::bc_protocol::BcCamera; -use neolink::gst::{GstOutputs, RtspServer}; -use neolink::Never; -use std::collections::HashSet; -use std::fs; -use std::sync::Arc; -use std::time::Duration; use structopt::StructOpt; -use validator::Validate; mod cmdline; -mod config; +mod reboot; +mod rtsp; +mod statusled; +mod talk; -use cmdline::Opt; -use config::{CameraConfig, Config, UserConfig}; +use cmdline::{Command, Opt}; -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - #[error(display = "Configuration parsing error")] - ConfigError(#[error(source)] toml::de::Error), - #[error(display = "Communication error")] - ProtocolError(#[error(source)] neolink::Error), - #[error(display = "I/O error")] - IoError(#[error(source)] std::io::Error), - #[error(display = "Validation error")] - ValidationError(#[error(source)] validator::ValidationErrors), - #[error(display = "ADPCM Decoding Error")] - AdpcmDecodingError(&'static str), -} - -fn main() -> Result<(), Error> { +fn main() -> Result<()> { env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); info!( @@ -43,239 +30,32 @@ fn main() -> Result<(), Error> { ); let opt = Opt::from_args(); - let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; - config.validate()?; - - let rtsp = &RtspServer::new(); - - set_up_tls(&config, &rtsp); - - set_up_users(&config.users, &rtsp); - - if config.certificate == None && !config.users.is_empty() { - warn!( - "Without a server certificate, usernames and passwords will be exchanged in plaintext!" - ) - } - - crossbeam::scope(|s| { - for camera in config.cameras { - if camera.format.is_some() { - warn!("The format config option of the camera has been removed in favour of auto detection.") - } - // Let subthreads share the camera object; in principle I think they could share - // the object as it sits in the config.cameras block, but I have not figured out the - // syntax for that. - let arc_cam = Arc::new(camera); - - let permitted_users = - get_permitted_users(config.users.as_slice(), &arc_cam.permitted_users); - - // Set up each main and substream according to all the RTSP mount paths we support - if ["both", "mainStream"].iter().any(|&e| e == arc_cam.stream) { - let paths = &[ - &*format!("/{}", arc_cam.name), - &*format!("/{}/mainStream", arc_cam.name), - ]; - let mut outputs = rtsp - .add_stream(paths, &permitted_users) - .unwrap(); - let main_camera = arc_cam.clone(); - s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true)); - } - if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) { - let paths = &[&*format!("/{}/subStream", arc_cam.name)]; - let mut outputs = rtsp - .add_stream(paths, &permitted_users) - .unwrap(); - let sub_camera = arc_cam.clone(); - let manage = arc_cam.stream == "subStream"; - s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage)); - } + match (opt.cmd, opt.config) { + (None, None) => { + // Should be caught at the clap validation + unreachable!(); } - - rtsp.run(&config.bind_addr, config.bind_port); - }) - .unwrap(); - - Ok(()) -} - -fn camera_loop( - camera_config: &CameraConfig, - stream_name: &str, - outputs: &mut GstOutputs, - manage: bool, -) -> Result { - let min_backoff = Duration::from_secs(1); - let max_backoff = Duration::from_secs(15); - let mut current_backoff = min_backoff; - - loop { - let cam_err = camera_main(camera_config, stream_name, outputs, manage).unwrap_err(); - outputs.vidsrc.on_stream_error(); - outputs.audsrc.on_stream_error(); - // Authentication failures are permanent; we retry everything else - if cam_err.connected { - current_backoff = min_backoff; - } - match cam_err.err { - neolink::Error::AuthFailed => { - error!( - "Authentication failed to camera {}, not retrying", - camera_config.name - ); - return Err(cam_err.err.into()); - } - _ => error!( - "Error streaming from camera {}, will retry in {}s: {}", - camera_config.name, - current_backoff.as_secs(), - cam_err.err - ), - } - - std::thread::sleep(current_backoff); - current_backoff = std::cmp::min(max_backoff, current_backoff * 2); - } -} - -struct CameraErr { - connected: bool, - err: neolink::Error, -} - -fn set_up_tls(config: &Config, rtsp: &RtspServer) { - let tls_client_auth = match &config.tls_client_auth as &str { - "request" => TlsAuthenticationMode::Requested, - "require" => TlsAuthenticationMode::Required, - "none" => TlsAuthenticationMode::None, - _ => unreachable!(), - }; - if let Some(cert_path) = &config.certificate { - rtsp.set_tls(&cert_path, tls_client_auth) - .expect("Failed to set up TLS"); - } -} - -fn set_up_users(users: &[UserConfig], rtsp: &RtspServer) { - // Setting up users - let credentials: Vec<_> = users - .iter() - .map(|user| (&*user.name, &*user.pass)) - .collect(); - rtsp.set_credentials(&credentials) - .expect("Failed to set up users"); -} - -fn get_permitted_users<'a>( - users: &'a [UserConfig], - // not idiomatic as a function argument, but this fn translates the config struct directly: - permitted_users: &'a Option>, -) -> HashSet<&'a str> { - // Helper to build hashset of all users in `users`: - let all_users_hash = || users.iter().map(|u| u.name.as_str()).collect(); - - match permitted_users { - // If in the camera config there is the user "anyone", or if none is specified but users - // are defined at all, then we add all users to the camera's allowed list. - Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(), - None if !users.is_empty() => all_users_hash(), - - // The user specified permitted_users - Some(p) => p.iter().map(String::as_str).collect(), - - // The user didn't specify permitted_users, and there are none defined anyway - None => ["anonymous"].iter().cloned().collect(), - } -} - -fn camera_main( - camera_config: &CameraConfig, - stream_name: &str, - outputs: &mut GstOutputs, - manage: bool, -) -> Result { - let mut connected = false; - (|| { - let mut camera = BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; - if camera_config.timeout.is_some() { - warn!("The undocumented `timeout` config option has been removed and is no longer needed."); - warn!("Please update your config file."); - } - - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr - ); - - camera.login(&camera_config.username, camera_config.password.as_deref())?; - - connected = true; - info!("{}: Connected and logged in", camera_config.name); - - if manage { - do_camera_management(&mut camera, camera_config)?; - } - - info!( - "{}: Starting video stream {}", - camera_config.name, stream_name - ); - camera.start_video(outputs, stream_name) - })() - .map_err(|err| CameraErr { connected, err }) -} - -fn do_camera_management( - camera: &mut BcCamera, - camera_config: &CameraConfig, -) -> Result<(), neolink::Error> { - let cam_time = camera.get_time()?; - if let Some(time) = cam_time { - info!( - "{}: Camera time is already set: {}", - camera_config.name, time - ); - } else { - use time::OffsetDateTime; - // We'd like now_local() but it's deprecated - try to get the local time, but if no - // time zone, fall back to UTC. - let new_time = - OffsetDateTime::try_now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()); - - warn!( - "{}: Camera has no time set, setting to {}", - camera_config.name, new_time - ); - camera.set_time(new_time)?; - let cam_time = camera.get_time()?; - if let Some(time) = cam_time { - info!("{}: Camera time is now set: {}", camera_config.name, time); - } else { - error!( - "{}: Camera did not accept new time (is {} an admin?)", - camera_config.name, camera_config.username + (None, Some(config)) => { + warn!( + "Deprecated command line option. Please use: `neolink rtsp --config={:?}`", + config ); + rtsp::main(rtsp::Opt { config })?; + } + (Some(_), Some(_)) => error!("--config should be given after the subcommand"), + (Some(Command::Rtsp(opts)), None) => { + rtsp::main(opts)?; + } + (Some(Command::StatusLight(opts)), None) => { + statusled::main(opts)?; + } + (Some(Command::Reboot(opts)), None) => { + reboot::main(opts)?; + } + (Some(Command::Talk(opts)), None) => { + talk::main(opts)?; } - } - - use neolink::bc::xml::VersionInfo; - if let Ok(VersionInfo { - firmwareVersion: firmware_version, - .. - }) = camera.version() - { - info!( - "{}: Camera reports firmware version {}", - camera_config.name, firmware_version - ); - } else { - info!( - "{}: Could not fetch version information", - camera_config.name - ); } Ok(()) diff --git a/src/reboot/cmdline.rs b/src/reboot/cmdline.rs new file mode 100644 index 0000000..8c94ee1 --- /dev/null +++ b/src/reboot/cmdline.rs @@ -0,0 +1,12 @@ +use std::path::PathBuf; +use structopt::StructOpt; + +/// The reboot command will reboot the camera +#[derive(StructOpt, Debug)] +pub struct Opt { + /// The path to the config file + #[structopt(short, long, parse(from_os_str))] + pub config: PathBuf, + /// The name of the camera to change the lights of. Must be a name in the config + pub camera: String, +} diff --git a/src/reboot/config.rs b/src/reboot/config.rs new file mode 100644 index 0000000..de60ef2 --- /dev/null +++ b/src/reboot/config.rs @@ -0,0 +1,29 @@ +use serde::Deserialize; +use std::clone::Clone; +use validator::Validate; +use validator_derive::Validate; + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct Config { + #[validate] + pub(crate) cameras: Vec, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct CameraConfig { + pub(crate) name: String, + + #[serde(rename = "address")] + pub(crate) camera_addr: String, + + pub(crate) username: String, + pub(crate) password: Option, + + #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] + #[serde(default = "default_channel_id")] + pub(crate) channel_id: u8, +} + +fn default_channel_id() -> u8 { + 0 +} diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs new file mode 100644 index 0000000..9219e45 --- /dev/null +++ b/src/reboot/mod.rs @@ -0,0 +1,80 @@ +/// +/// # Neolink Reboot +/// +/// This module handles the reboot subcommand +/// +/// The subcommand attepts to reboot the camera. +/// +/// # Usage +/// +/// ```bash +/// neolink reboot --config=config.toml CameraName +/// ``` +/// +use anyhow::{anyhow, Context, Result}; +use log::*; +use neolink_core::bc_protocol::BcCamera; +use std::fs; +use validator::Validate; + +mod cmdline; +mod config; + +pub(crate) use cmdline::Opt; +use config::Config; + +/// Entry point for the reboot subcommand +/// +/// Opt is the command line options +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + + let mut cam_found = false; + for camera_config in &config.cameras { + if opt.camera == camera_config.name { + cam_found = true; + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_config.camera_addr + ); + + let mut camera = + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; + + info!("{}: Logging in", camera_config.name); + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; + + info!("{}: Connected and logged in", camera_config.name); + + camera + .reboot() + .context("Could not send reboot command to the camera")?; + } + } + + if !cam_found { + Err(anyhow!( + "Camera {} was not in the config file {:?}", + &opt.camera, + &opt.config + )) + } else { + Ok(()) + } +} diff --git a/src/bc_protocol/adpcm.rs b/src/rtsp/adpcm.rs similarity index 95% rename from src/bc_protocol/adpcm.rs rename to src/rtsp/adpcm.rs index a42b0cd..e7e0282 100644 --- a/src/bc_protocol/adpcm.rs +++ b/src/rtsp/adpcm.rs @@ -1,7 +1,7 @@ /* This is a rust implementation of OKI and DVI/IMA ADPCM. */ -use crate::Error; +use super::errors::Error; use log::error; use std::convert::TryInto; @@ -14,6 +14,7 @@ struct AdpcmSetup { impl AdpcmSetup { // Unused, originally we thought BC might be using OKI but it is actually DVI4 + #[allow(dead_code)] fn new_oki() -> Self { Self { max_step_index: 48, @@ -57,10 +58,12 @@ impl Nibble { (self.data & 0b00001111) as u32 // Mask first 4 bits it just to be sure its in nibble range } + #[allow(dead_code)] fn signed_magnitude(&self) -> u32 { (self.data & 0b00000111) as u32 // Mask of first 3 bits which are the magnitiude bits in signed int } + #[allow(dead_code)] fn signed(&self) -> i32 { match self.data & 0b00001000 { // Sign bit is at the 4th bit @@ -82,7 +85,7 @@ impl Nibble { } } -pub fn adpcm_to_pcm(bytes: &[u8]) -> Result, Error> { +pub(crate) fn adpcm_to_pcm(bytes: &[u8]) -> Result, Error> { let context = AdpcmSetup::new_ima(); let mut result: Vec = vec![]; // Stores the PCM byte array @@ -99,7 +102,7 @@ pub fn adpcm_to_pcm(bytes: &[u8]) -> Result, Error> { if bytes.len() < 4 { error!("ADPCM data is too short for even the magic."); - return Err(Error::AdpcmDecodingError( + return Err(Error::AdpcmDecoding( "ADPCM data is too short for even the magic.", )); } @@ -109,7 +112,7 @@ pub fn adpcm_to_pcm(bytes: &[u8]) -> Result, Error> { const FRAME_TYPE_HISILICON: &[u8] = &[0x00, 0x01]; if frame_type_bytes != FRAME_TYPE_HISILICON { error!("Unexpected ADPCM frame type: {:x?}", frame_type_bytes); - return Err(Error::AdpcmDecodingError("Unexpected ADPCM frame type")); + return Err(Error::AdpcmDecoding("Unexpected ADPCM frame type")); } // Check for valid block size @@ -123,7 +126,7 @@ pub fn adpcm_to_pcm(bytes: &[u8]) -> Result, Error> { let full_block_size = block_size + 4; // block_size + magic (2 bytes) + size (2 bytes) if !bytes.len() % full_block_size as usize == 0 { error!("ADPCM Data is not a multiple of the block size"); - return Err(Error::AdpcmDecodingError( + return Err(Error::AdpcmDecoding( "ADPCM block size does not match data length.", )); } @@ -133,9 +136,7 @@ pub fn adpcm_to_pcm(bytes: &[u8]) -> Result, Error> { // Get predictor state from block header using DVI 4 format. if bytes.len() < 8 { error!("ADPCM Block size is not long enough for header"); - return Err(Error::AdpcmDecodingError( - "ADPCM has insufficent block size", - )); + return Err(Error::AdpcmDecoding("ADPCM has insufficent block size")); } let step_output_bytes = &bytes[4..6]; let mut last_output = i16::from_le_bytes( diff --git a/src/rtsp/cmdline.rs b/src/rtsp/cmdline.rs new file mode 100644 index 0000000..2a7092b --- /dev/null +++ b/src/rtsp/cmdline.rs @@ -0,0 +1,10 @@ +use std::path::PathBuf; +use structopt::StructOpt; + +/// The rtsp command will serve all cameras in the config over the rtsp protocol +#[derive(StructOpt, Debug)] +pub struct Opt { + /// The path to the config file + #[structopt(short, long, parse(from_os_str))] + pub config: PathBuf, +} diff --git a/src/config.rs b/src/rtsp/config.rs similarity index 74% rename from src/config.rs rename to src/rtsp/config.rs index 9942e66..176b434 100644 --- a/src/config.rs +++ b/src/rtsp/config.rs @@ -12,19 +12,19 @@ lazy_static! { } #[derive(Debug, Deserialize, Validate, Clone)] -pub struct Config { +pub(crate) struct Config { #[validate] - pub cameras: Vec, + pub(crate) cameras: Vec, #[serde(rename = "bind", default = "default_bind_addr")] - pub bind_addr: String, + pub(crate) bind_addr: String, #[validate(range(min = 0, max = 65535, message = "Invalid port", code = "bind_port"))] #[serde(default = "default_bind_port")] - pub bind_port: u16, + pub(crate) bind_port: u16, #[serde(default = "default_certificate")] - pub certificate: Option, + pub(crate) certificate: Option, #[validate(regex( path = "RE_TLS_CLIENT_AUTH", @@ -32,28 +32,28 @@ pub struct Config { code = "tls_client_auth" ))] #[serde(default = "default_tls_client_auth")] - pub tls_client_auth: String, + pub(crate) tls_client_auth: String, #[validate] #[serde(default)] - pub users: Vec, + pub(crate) users: Vec, } #[derive(Debug, Deserialize, Validate, Clone)] -pub struct CameraConfig { - pub name: String, +pub(crate) struct CameraConfig { + pub(crate) name: String, #[serde(rename = "address")] - pub camera_addr: String, + pub(crate) camera_addr: String, - pub username: String, - pub password: Option, + pub(crate) username: String, + pub(crate) password: Option, // no longer used, but still here so we can warn users: - pub timeout: Option, + pub(crate) timeout: Option, // no longer used, but still here so we can warn users: - pub format: Option, + pub(crate) format: Option, #[validate(regex( path = "RE_STREAM_SRC", @@ -61,23 +61,23 @@ pub struct CameraConfig { code = "stream" ))] #[serde(default = "default_stream")] - pub stream: String, + pub(crate) stream: String, - pub permitted_users: Option>, + pub(crate) permitted_users: Option>, #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] #[serde(default = "default_channel_id")] - pub channel_id: u8, + pub(crate) channel_id: u8, } #[derive(Debug, Deserialize, Validate, Clone)] -pub struct UserConfig { +pub(crate) struct UserConfig { #[validate(custom = "validate_username")] #[serde(alias = "username")] - pub name: String, + pub(crate) name: String, #[serde(alias = "password")] - pub pass: String, + pub(crate) pass: String, } fn default_bind_addr() -> String { @@ -104,7 +104,7 @@ fn default_channel_id() -> u8 { 0 } -pub static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"]; +pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"]; fn validate_username(name: &str) -> Result<(), ValidationError> { if name.trim().is_empty() { return Err(ValidationError::new("username cannot be empty")); diff --git a/src/gst.rs b/src/rtsp/gst.rs similarity index 74% rename from src/gst.rs rename to src/rtsp/gst.rs index 53fec3b..2955c07 100644 --- a/src/gst.rs +++ b/src/rtsp/gst.rs @@ -1,12 +1,15 @@ //! This module provides an "RtspServer" abstraction that allows consumers of its API to feed it //! data using an ordinary std::io::Write interface. -pub use self::maybe_app_src::MaybeAppSrc; +pub(crate) use self::maybe_app_src::MaybeAppSrc; +// use super::adpcm::adpcm_to_pcm; +// use super::errors::Error; use gstreamer::prelude::Cast; use gstreamer::{Bin, Structure}; use gstreamer_app::AppSrc; //use gstreamer_rtsp::RTSPLowerTrans; -use gio::{TlsAuthenticationMode, TlsCertificate}; use gstreamer_rtsp::RTSPAuthMethod; +pub use gstreamer_rtsp_server::gio::{TlsAuthenticationMode, TlsCertificate}; +use gstreamer_rtsp_server::glib; use gstreamer_rtsp_server::prelude::*; use gstreamer_rtsp_server::{ RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer, RTSPToken, @@ -14,6 +17,10 @@ use gstreamer_rtsp_server::{ RTSP_TOKEN_MEDIA_FACTORY_ROLE, }; use log::*; +use neolink_core::{ + bc_protocol::{StreamOutput, StreamOutputError}, + bcmedia::model::*, +}; use std::collections::HashSet; use std::fs; use std::io; @@ -21,28 +28,72 @@ use std::io::Write; type Result = std::result::Result; -pub struct RtspServer { +pub(crate) struct RtspServer { server: GstRTSPServer, } -#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] -pub enum StreamFormat { - H264, - H265, - AAC, - ADPCM, -} - -pub struct GstOutputs { - pub audsrc: MaybeAppSrc, - pub vidsrc: MaybeAppSrc, +pub(crate) struct GstOutputs { + pub(crate) audsrc: MaybeAppSrc, + pub(crate) vidsrc: MaybeAppSrc, video_format: Option, audio_format: Option, factory: RTSPMediaFactory, } +// The stream from the camera will be using one of these formats +// +// This is used as part of `StreamOutput` to give hints about +// the format of the stream +#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] +enum StreamFormat { + // H264 (AVC) video format + H264, + // H265 (HEVC) video format + H265, + // AAC audio + Aac, + // ADPCM in DVI-4 format + Adpcm(u16), +} + +impl StreamOutput for GstOutputs { + fn write(&mut self, media: BcMedia) -> StreamOutputError { + match media { + BcMedia::Iframe(payload) => { + let video_type = match payload.video_type { + VideoType::H264 => StreamFormat::H264, + VideoType::H265 => StreamFormat::H265, + }; + self.set_format(Some(video_type)); + self.vidsrc.write_all(&payload.data)?; + } + BcMedia::Pframe(payload) => { + let video_type = match payload.video_type { + VideoType::H264 => StreamFormat::H264, + VideoType::H265 => StreamFormat::H265, + }; + self.set_format(Some(video_type)); + self.vidsrc.write_all(&payload.data)?; + } + BcMedia::Aac(payload) => { + self.set_format(Some(StreamFormat::Aac)); + self.audsrc.write_all(&payload.data)?; + } + BcMedia::Adpcm(payload) => { + self.set_format(Some(StreamFormat::Adpcm(payload.data.len() as u16))); + self.audsrc.write_all(&payload.data)?; + } + _ => { + //Ignore other BcMedia like InfoV1 and InfoV2 + } + } + + Ok(()) + } +} + impl GstOutputs { - pub fn from_appsrcs(vidsrc: MaybeAppSrc, audsrc: MaybeAppSrc) -> GstOutputs { + pub(crate) fn from_appsrcs(vidsrc: MaybeAppSrc, audsrc: MaybeAppSrc) -> GstOutputs { let result = GstOutputs { vidsrc, audsrc, @@ -54,7 +105,7 @@ impl GstOutputs { result } - pub fn set_format(&mut self, format: Option) { + fn set_format(&mut self, format: Option) { match format { Some(StreamFormat::H264) | Some(StreamFormat::H265) => { if format != self.video_format { @@ -62,7 +113,7 @@ impl GstOutputs { self.apply_format(); } } - Some(StreamFormat::AAC) | Some(StreamFormat::ADPCM) => { + Some(StreamFormat::Aac) | Some(StreamFormat::Adpcm(_)) => { if format != self.audio_format { self.audio_format = format; self.apply_format(); @@ -84,9 +135,9 @@ impl GstOutputs { }; let launch_aud = match self.audio_format { - Some(StreamFormat::ADPCM) => "! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! rawaudioparse format=pcm pcm-format=s16le sample-rate=8000 num-channels=1 interleaved=true ! audioconvert ! rtpL16pay name=pay1", // DVI4 is converted to pcm in the appsrc - Some(StreamFormat::AAC) => "! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! aacparse ! decodebin ! audioconvert ! rtpL16pay name=pay1 name=pay1", - _ => "! fakesink", + Some(StreamFormat::Adpcm(block_size)) => format!("caps=audio/x-adpcm,layout=dvi,block_align={},channels=1,rate=8000 ! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! adpcmdec ! audioconvert ! rtpL16pay name=pay1", block_size), // DVI4 is converted to pcm in the appsrc + Some(StreamFormat::Aac) => "! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! aacparse ! decodebin ! audioconvert ! rtpL16pay name=pay1 name=pay1".to_string(), + _ => "! fakesink".to_string(), }; self.factory.set_launch( @@ -95,7 +146,7 @@ impl GstOutputs { "appsrc name=vidsrc is-live=true block=true emit-signals=false max-bytes=52428800 do-timestamp=true format=GST_FORMAT_TIME", // 50MB max size so that it won't grow to infinite if the queue blocks launch_vid, "appsrc name=audsrc is-live=true block=true emit-signals=false max-bytes=52428800 do-timestamp=true format=GST_FORMAT_TIME", // 50MB max size so that it won't grow to infinite if the queue blocks - launch_aud, + &launch_aud, ")" ] .join(" "), @@ -110,21 +161,21 @@ impl Default for RtspServer { } impl RtspServer { - pub fn new() -> RtspServer { + pub(crate) fn new() -> RtspServer { gstreamer::init().expect("Gstreamer should not explode"); RtspServer { server: GstRTSPServer::new(), } } - pub fn add_stream( + pub(crate) fn add_stream( &self, paths: &[&str], permitted_users: &HashSet<&str>, ) -> Result { let mounts = self .server - .get_mount_points() + .mount_points() .expect("The server should have mountpoints"); // Create a MaybeAppSrc: Write which we will give the caller. When the backing AppSrc is @@ -152,19 +203,19 @@ impl RtspServer { factory.connect_media_configure(move |_factory, media| { debug!("RTSP: media was configured"); let bin = media - .get_element() + .element() .expect("Media should have an element") .dynamic_cast::() .expect("Media source's element should be a bin"); let app_src = bin - .get_by_name_recurse_up("vidsrc") + .by_name_recurse_up("vidsrc") .expect("write_src must be present in created bin") .dynamic_cast::() .expect("Source element is expected to be an appsrc!"); let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so let app_src_aud = bin - .get_by_name_recurse_up("audsrc") + .by_name_recurse_up("audsrc") .expect("write_src must be present in created bin") .dynamic_cast::() .expect("Source element is expected to be an appsrc!"); @@ -178,7 +229,11 @@ impl RtspServer { Ok(outputs) } - pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &HashSet<&str>) { + pub(crate) fn add_permitted_roles( + &self, + factory: &RTSPMediaFactory, + permitted_roles: &HashSet<&str>, + ) { for permitted_role in permitted_roles { factory.add_role_from_structure(&Structure::new( permitted_role, @@ -210,8 +265,8 @@ impl RtspServer { } } - pub fn set_credentials(&self, credentials: &[(&str, &str)]) -> Result<()> { - let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new); + pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> Result<()> { + let auth = self.server.auth().unwrap_or_else(RTSPAuth::new); auth.set_supported_methods(RTSPAuthMethod::Basic); let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous")]); @@ -229,9 +284,13 @@ impl RtspServer { Ok(()) } - pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { + pub(crate) fn set_tls( + &self, + cert_file: &str, + client_auth: TlsAuthenticationMode, + ) -> Result<()> { debug!("Setting up TLS using {}", cert_file); - let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new); + let auth = self.server.auth().unwrap_or_else(RTSPAuth::new); // We seperate reading the file and changing to a PEM so that we get different error messages. let cert_contents = fs::read_to_string(cert_file).expect("TLS file not found"); @@ -243,11 +302,11 @@ impl RtspServer { Ok(()) } - pub fn run(&self, bind_addr: &str, bind_port: u16) { + pub(crate) fn run(&self, bind_addr: &str, bind_port: u16) { self.server.set_address(bind_addr); self.server.set_service(&format!("{}", bind_port)); // Attach server to default Glib context - self.server.attach(None); + let _ = self.server.attach(None); // Run the Glib main loop. let main_loop = glib::MainLoop::new(None, false); @@ -261,7 +320,7 @@ mod maybe_app_src { /// A Write implementation around AppSrc that also allows delaying the creation of the AppSrc /// until later, discarding written data until the AppSrc is provided. - pub struct MaybeAppSrc { + pub(crate) struct MaybeAppSrc { rx: Receiver, app_src: Option, } @@ -270,13 +329,13 @@ mod maybe_app_src { /// Creates a MaybeAppSrc. Also returns a Sender that you must use to provide an AppSrc as /// soon as one is available. When it is received, the MaybeAppSrc will start pushing data /// into the AppSrc when write() is called. - pub fn new_with_tx() -> (Self, SyncSender) { + pub(crate) fn new_with_tx() -> (Self, SyncSender) { let (tx, rx) = sync_channel(3); // The sender should not send very often (MaybeAppSrc { rx, app_src: None }, tx) } /// Flushes data to Gstreamer on a problem communicating with the underlying video source. - pub fn on_stream_error(&mut self) { + pub(crate) fn on_stream_error(&mut self) { if let Some(src) = self.try_get_src() { // Ignore "errors" from Gstreamer such as FLUSHING, which are not really errors. let _ = src.end_of_stream(); diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs new file mode 100644 index 0000000..ca5a030 --- /dev/null +++ b/src/rtsp/mod.rs @@ -0,0 +1,315 @@ +/// +/// # Neolink RTSP +/// +/// This module serves the rtsp streams for the +/// `neolink rtsp` subcommand +/// +/// All camera specified in the config.toml will be served +/// over rtsp. By default it bind to all local ip addresses +/// on the port 8554. +/// +/// You can view the streams with any rtsp compliement program +/// such as ffmpeg, vlc, blue-iris, home-assistant, zone-minder etc. +/// +/// Each camera has it own endpoint based on its name. For example +/// a camera named `"Garage"` in the config can be found at. +/// +/// `rtsp://my.ip.address:8554/Garage` +/// +/// With the lower resolution stream at +/// +/// `rtsp://my.ip.address:8554/Garage/subStream` +/// +/// # Usage +/// +/// To start the subcommand use the following in a shell. +/// +/// ```bash +/// neolink rtsp --config=config.toml +/// ``` +/// +use anyhow::{Context, Result}; +use log::*; +use neolink_core::bc_protocol::BcCamera; +use neolink_core::Never; +use std::collections::HashSet; +use std::fs; +use std::sync::Arc; +use std::time::Duration; +use validator::Validate; + +// mod adpcm; +/// The command line parameters for this subcommand +mod cmdline; +mod config; +/// The errors this subcommand can raise +mod gst; + +pub(crate) use cmdline::Opt; +use config::{CameraConfig, Config, UserConfig}; +use gst::{GstOutputs, RtspServer, TlsAuthenticationMode}; + +/// Entry point for the rtsp subcommand +/// +/// Opt is the command line options +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + + let rtsp = &RtspServer::new(); + + set_up_tls(&config, rtsp); + + set_up_users(&config.users, rtsp); + + if config.certificate == None && !config.users.is_empty() { + warn!( + "Without a server certificate, usernames and passwords will be exchanged in plaintext!" + ) + } + + crossbeam::scope(|s| { + for camera in config.cameras { + if camera.format.is_some() { + warn!("The format config option of the camera has been removed in favour of auto detection.") + } + // Let subthreads share the camera object; in principle I think they could share + // the object as it sits in the config.cameras block, but I have not figured out the + // syntax for that. + let arc_cam = Arc::new(camera); + + let permitted_users = + get_permitted_users(config.users.as_slice(), &arc_cam.permitted_users); + + // Set up each main and substream according to all the RTSP mount paths we support + if ["both", "mainStream"].iter().any(|&e| e == arc_cam.stream) { + let paths = &[ + &*format!("/{}", arc_cam.name), + &*format!("/{}/mainStream", arc_cam.name), + ]; + let mut outputs = rtsp + .add_stream(paths, &permitted_users) + .unwrap(); + let main_camera = arc_cam.clone(); + s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true)); + } + if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) { + let paths = &[&*format!("/{}/subStream", arc_cam.name)]; + let mut outputs = rtsp + .add_stream(paths, &permitted_users) + .unwrap(); + let sub_camera = arc_cam.clone(); + let manage = arc_cam.stream == "subStream"; + s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage)); + } + } + + rtsp.run(&config.bind_addr, config.bind_port); + }) + .unwrap(); + + Ok(()) +} + +fn camera_loop( + camera_config: &CameraConfig, + stream_name: &str, + outputs: &mut GstOutputs, + manage: bool, +) -> Result { + let min_backoff = Duration::from_secs(1); + let max_backoff = Duration::from_secs(15); + let mut current_backoff = min_backoff; + + loop { + let cam_err = camera_main(camera_config, stream_name, outputs, manage).unwrap_err(); + outputs.vidsrc.on_stream_error(); + outputs.audsrc.on_stream_error(); + // Authentication failures are permanent; we retry everything else + if cam_err.connected { + current_backoff = min_backoff; + } + if cam_err.login_fail { + error!( + "Authentication failed to camera {}, not retrying", + camera_config.name + ); + return Err(cam_err.err); + } else { + error!( + "Error streaming from camera {}, will retry in {}s: {:?}", + camera_config.name, + current_backoff.as_secs(), + cam_err.err + ) + } + + std::thread::sleep(current_backoff); + current_backoff = std::cmp::min(max_backoff, current_backoff * 2); + } +} + +struct CameraErr { + connected: bool, + login_fail: bool, + err: anyhow::Error, +} + +fn set_up_tls(config: &Config, rtsp: &RtspServer) { + let tls_client_auth = match &config.tls_client_auth as &str { + "request" => TlsAuthenticationMode::Requested, + "require" => TlsAuthenticationMode::Required, + "none" => TlsAuthenticationMode::None, + _ => unreachable!(), + }; + if let Some(cert_path) = &config.certificate { + rtsp.set_tls(cert_path, tls_client_auth) + .expect("Failed to set up TLS"); + } +} + +fn set_up_users(users: &[UserConfig], rtsp: &RtspServer) { + // Setting up users + let credentials: Vec<_> = users + .iter() + .map(|user| (&*user.name, &*user.pass)) + .collect(); + rtsp.set_credentials(&credentials) + .expect("Failed to set up users"); +} + +fn get_permitted_users<'a>( + users: &'a [UserConfig], + // not idiomatic as a function argument, but this fn translates the config struct directly: + permitted_users: &'a Option>, +) -> HashSet<&'a str> { + // Helper to build hashset of all users in `users`: + let all_users_hash = || users.iter().map(|u| u.name.as_str()).collect(); + + match permitted_users { + // If in the camera config there is the user "anyone", or if none is specified but users + // are defined at all, then we add all users to the camera's allowed list. + Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(), + None if !users.is_empty() => all_users_hash(), + + // The user specified permitted_users + Some(p) => p.iter().map(String::as_str).collect(), + + // The user didn't specify permitted_users, and there are none defined anyway + None => ["anonymous"].iter().cloned().collect(), + } +} + +fn camera_main( + camera_config: &CameraConfig, + stream_name: &str, + outputs: &mut GstOutputs, + manage: bool, +) -> Result { + let mut connected = false; + let mut login_fail = false; + (|| { + let mut camera = + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; + + if camera_config.timeout.is_some() { + warn!("The undocumented `timeout` config option has been removed and is no longer needed."); + warn!("Please update your config file."); + } + + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_config.camera_addr + ); + + info!("{}: Logging in", camera_config.name); + camera.login(&camera_config.username, camera_config.password.as_deref()).map_err(|e| + { + if let neolink_core::Error::AuthFailed = e { + login_fail = true; + } + e + } + ).with_context(|| format!("Failed to login to {}", camera_config.name))?; + + connected = true; + info!("{}: Connected and logged in", camera_config.name); + + if manage { + do_camera_management(&mut camera, camera_config).context("Failed to manage the camera settings")?; + } + + info!( + "{}: Starting video stream {}", + camera_config.name, stream_name + ); + camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name)) + })().map_err(|e| CameraErr{ + connected, + login_fail, + err: e, + }) +} + +fn do_camera_management(camera: &mut BcCamera, camera_config: &CameraConfig) -> Result<()> { + let cam_time = camera.get_time()?; + if let Some(time) = cam_time { + info!( + "{}: Camera time is already set: {}", + camera_config.name, time + ); + } else { + use time::OffsetDateTime; + // We'd like now_local() but it's deprecated - try to get the local time, but if no + // time zone, fall back to UTC. + let new_time = + OffsetDateTime::try_now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()); + + warn!( + "{}: Camera has no time set, setting to {}", + camera_config.name, new_time + ); + camera.set_time(new_time)?; + let cam_time = camera.get_time()?; + if let Some(time) = cam_time { + info!("{}: Camera time is now set: {}", camera_config.name, time); + } else { + error!( + "{}: Camera did not accept new time (is {} an admin?)", + camera_config.name, camera_config.username + ); + } + } + + use neolink_core::bc::xml::VersionInfo; + if let Ok(VersionInfo { + firmwareVersion: firmware_version, + .. + }) = camera.version() + { + info!( + "{}: Camera reports firmware version {}", + camera_config.name, firmware_version + ); + } else { + info!( + "{}: Could not fetch version information", + camera_config.name + ); + } + + Ok(()) +} diff --git a/src/statusled/cmdline.rs b/src/statusled/cmdline.rs new file mode 100644 index 0000000..e0c448d --- /dev/null +++ b/src/statusled/cmdline.rs @@ -0,0 +1,27 @@ +use anyhow::{anyhow, Result}; +use std::path::PathBuf; +use structopt::StructOpt; + +fn onoff_parse(src: &str) -> Result { + match src { + "true" | "on" | "yes" => Ok(true), + "false" | "off" | "no" => Ok(false), + _ => Err(anyhow!( + "Could not understand {}, check your input, should be true/false, on/off or yes/no", + src + )), + } +} + +/// The status-light command will control the blue status light on the camera +#[derive(StructOpt, Debug)] +pub struct Opt { + /// The path to the config file + #[structopt(short, long, parse(from_os_str))] + pub config: PathBuf, + /// The name of the camera to change the lights of. Must be a name in the config + pub camera: String, + /// Whether to turn the light on or off + #[structopt(parse(try_from_str = onoff_parse), name = "on|off")] + pub on: bool, +} diff --git a/src/statusled/config.rs b/src/statusled/config.rs new file mode 100644 index 0000000..de60ef2 --- /dev/null +++ b/src/statusled/config.rs @@ -0,0 +1,29 @@ +use serde::Deserialize; +use std::clone::Clone; +use validator::Validate; +use validator_derive::Validate; + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct Config { + #[validate] + pub(crate) cameras: Vec, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct CameraConfig { + pub(crate) name: String, + + #[serde(rename = "address")] + pub(crate) camera_addr: String, + + pub(crate) username: String, + pub(crate) password: Option, + + #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] + #[serde(default = "default_channel_id")] + pub(crate) channel_id: u8, +} + +fn default_channel_id() -> u8 { + 0 +} diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs new file mode 100644 index 0000000..6f32b2a --- /dev/null +++ b/src/statusled/mod.rs @@ -0,0 +1,84 @@ +/// +/// # Neolink Status LED +/// +/// This module handles the controls of the blue led status light +/// +/// The subcommand attepts to set the LED status light not the IR +/// lights or the flood lights. +/// +/// # Usage +/// +/// ```bash +/// # To turn the light on +/// neolink status-light --config=config.toml CameraName on +/// # Or off +/// neolink status-light --config=config.toml CameraName off +/// ``` +/// +use anyhow::{anyhow, Context, Result}; +use log::*; +use neolink_core::bc_protocol::BcCamera; +use std::fs; +use validator::Validate; + +mod cmdline; +mod config; + +pub(crate) use cmdline::Opt; +use config::Config; + +/// Entry point for the ledstatus subcommand +/// +/// Opt is the command line options +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + + let mut cam_found = false; + for camera_config in &config.cameras { + if opt.camera == camera_config.name { + cam_found = true; + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_config.camera_addr + ); + + let mut camera = + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; + + info!("{}: Logging in", camera_config.name); + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; + + info!("{}: Connected and logged in", camera_config.name); + + camera + .led_light_set(opt.on) + .context("Unable to set camera light state")?; + } + } + + if !cam_found { + Err(anyhow!( + "Camera {} was not in the config file {:?}", + &opt.camera, + &opt.config + )) + } else { + Ok(()) + } +} diff --git a/src/talk/cmdline.rs b/src/talk/cmdline.rs new file mode 100644 index 0000000..bd16704 --- /dev/null +++ b/src/talk/cmdline.rs @@ -0,0 +1,35 @@ +use std::path::PathBuf; +use structopt::StructOpt; + +/// The talk command will send audio for the camera to say +/// +/// This data should be encoded in a way that gstreamer can understand. +/// This should be ok with most common formats. +/// +/// `gst-launch` can be used to prepare this data +#[derive(StructOpt, Debug)] +pub struct Opt { + /// The path to the config file + #[structopt(short, long, parse(from_os_str))] + pub config: PathBuf, + /// The name of the camera to change the lights of. Must be a name in the config + pub camera: String, + /// The path to the audio file. + #[structopt(short, long, parse(from_os_str), conflicts_with = "microphone")] + pub file_path: Option, + /// Use the microphone as the source. Defaults to autoaudiosrc - Which microphone depends + /// on [gstraemer](https://gstreamer.freedesktop.org/documentation/autodetect/autoaudiosrc.html?gi-language=c#autoaudiosrc-page) + #[structopt(short, long, conflicts_with = "file_path")] + pub microphone: bool, + /// Use a specific microphone like "alsasrc device=hw:1" + #[structopt( + short, + long, + default_value = "autoaudiosrc", + conflicts_with = "file_path" + )] + pub input_src: String, + /// Use to change the volume of the input + #[structopt(short, long, default_value = "1.0")] + pub volume: f32, +} diff --git a/src/talk/config.rs b/src/talk/config.rs new file mode 100644 index 0000000..de60ef2 --- /dev/null +++ b/src/talk/config.rs @@ -0,0 +1,29 @@ +use serde::Deserialize; +use std::clone::Clone; +use validator::Validate; +use validator_derive::Validate; + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct Config { + #[validate] + pub(crate) cameras: Vec, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +pub(crate) struct CameraConfig { + pub(crate) name: String, + + #[serde(rename = "address")] + pub(crate) camera_addr: String, + + pub(crate) username: String, + pub(crate) password: Option, + + #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] + #[serde(default = "default_channel_id")] + pub(crate) channel_id: u8, +} + +fn default_channel_id() -> u8 { + 0 +} diff --git a/src/talk/gst.rs b/src/talk/gst.rs new file mode 100644 index 0000000..f0f9ab7 --- /dev/null +++ b/src/talk/gst.rs @@ -0,0 +1,180 @@ +use anyhow::{anyhow, Context, Result}; +use gstreamer::{ + element_error, parse_launch, prelude::*, Caps, ClockTime, FlowError, FlowSuccess, MessageView, + Pipeline, ResourceError, State, +}; +use gstreamer_app::{AppSink, AppSinkCallbacks}; +use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; + +use byte_slice_cast::*; + +pub(super) fn from_input( + input_src: &str, + volume: f32, + block_align: u16, + sample_rate: u16, +) -> Result>> { + let pipeline = create_pipeline(input_src, volume, block_align, sample_rate)?; + input(pipeline) +} + +fn input(pipeline: Pipeline) -> Result>> { + let appsink = get_sink(&pipeline)?; + let (tx, rx) = sync_channel(30); + + set_data_channel(&appsink, tx); + + std::thread::spawn(move || { + let _ = start_pipeline(pipeline); + }); + + Ok(rx) +} + +fn start_pipeline(pipeline: Pipeline) -> Result<()> { + pipeline.set_state(State::Playing)?; + + let bus = pipeline + .bus() + .expect("Pipeline without bus. Shouldn't happen!"); + + for msg in bus.iter_timed(ClockTime::NONE) { + match msg.view() { + MessageView::Eos(..) => break, + MessageView::Error(err) => { + pipeline + .set_state(State::Null) + .context("Error in gstreamer when setting state to Null")?; + log::warn!( + "Error from gstreamer when setting the play state {:?} setting to Null instead", + err + ); + } + _ => (), + } + } + + pipeline + .set_state(State::Null) + .context("Error in gstreamer when setting state to Null")?; + + Ok(()) +} + +fn get_sink(pipeline: &Pipeline) -> Result { + let sink = pipeline + .by_name("thesink") + .expect("There shoud be a `thesink`"); + sink.dynamic_cast::() + .map_err(|_| anyhow!("Cannot find appsink in gstreamer, check your gstreamer plugins")) +} + +fn set_data_channel(appsink: &AppSink, tx: SyncSender>) { + // Getting data out of the appsink is done by setting callbacks on it. + // The appsink will then call those handlers, as soon as data is available. + appsink.set_callbacks( + AppSinkCallbacks::builder() + // Add a handler to the "new-sample" signal. + .new_sample(move |appsink| { + // Pull the sample in question out of the appsink's buffer. + let sample = appsink.pull_sample().map_err(|_| FlowError::Eos)?; + let buffer = sample.buffer().ok_or_else(|| { + element_error!( + appsink, + ResourceError::Failed, + ("Failed to get buffer from appsink") + ); + + FlowError::Error + })?; + + // At this point, buffer is only a reference to an existing memory region somewhere. + // When we want to access its content, we have to map it while requesting the required + // mode of access (read, read/write). + // This type of abstraction is necessary, because the buffer in question might not be + // on the machine's main memory itself, but rather in the GPU's memory. + // So mapping the buffer makes the underlying memory region accessible to us. + // See: https://gstreamer.freedesktop.org/documentation/plugin-development/advanced/allocation.html + let map = buffer.map_readable().map_err(|_| { + element_error!( + appsink, + ResourceError::Failed, + ("Failed to map buffer readable") + ); + + FlowError::Error + })?; + + // We know what format the data in the memory region has, since we requested + // it by setting the appsink's caps. So what we do here is interpret the + // memory region we mapped as an array of signed 16 bit integers. + let samples = map.as_slice_of::().map_err(|_| { + element_error!( + appsink, + ResourceError::Failed, + ("Failed to interprete buffer as u8 ADPCM") + ); + + FlowError::Error + })?; + + // Ready! + let _ = tx.send(samples.to_vec()); + + Ok(FlowSuccess::Ok) + }) + .build(), + ); +} + +fn create_pipeline( + source: &str, + volume: f32, + block_align: u16, + sample_rate: u16, +) -> Result { + gstreamer::init() + .context("Unable to start gstreamer ensure it and all plugins are installed")?; + + let launch_str = format!( + "{} \ + ! decodebin \ + ! audioconvert \ + ! audioresample \ + ! audio/x-raw,rate={},channels=1 \ + ! volume volume={:.2} \ + ! queue \ + ! adpcmenc blockalign={} layout=dvi \ + ! appsink name=thesink", + source, sample_rate, volume, block_align + ); + + log::info!("{}", launch_str); + + // Parse the pipeline we want to probe from a static in-line string. + // Here we give our audiotestsrc a name, so we can retrieve that element + // from the resulting pipeline. + let pipeline = parse_launch(&launch_str) + .context("Unable to load gstreamer pipeline ensure all gstramer plugins are installed")?; + let pipeline = pipeline.dynamic_cast::().map_err(|_| { + anyhow!("Unable to create gstreamer pipeline ensure all gstramer plugins are installed") + })?; + + let appsink = get_sink(&pipeline)?; + + // Tell the appsink what format we want. It will then be the audiotestsrc's job to + // provide the format we request. + // This can be set after linking the two objects, because format negotiation between + // both elements will happen during pre-rolling of the pipeline. + appsink.set_caps(Some(&Caps::new_simple( + "audio/x-adpcm", + &[ + ("layout", &"dvi"), + ("block_align", &(block_align as i32)), + ("channels", &(1i32)), + ("rate", &(sample_rate as i32)), + ], + ))); + + Ok(pipeline) +} diff --git a/src/talk/mod.rs b/src/talk/mod.rs new file mode 100644 index 0000000..a2a032a --- /dev/null +++ b/src/talk/mod.rs @@ -0,0 +1,135 @@ +/// +/// # Neolink Talk +/// +/// This module can be used to send adpcm data for the camera to play +/// +/// The adpcm data needs to be in DVI-4 layout +/// +/// # Usage +/// +/// ```bash +/// neolink status-light --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName +/// ``` +/// +use anyhow::{anyhow, Context, Result}; +use log::*; +use neolink_core::{bc::xml::TalkConfig, bc_protocol::BcCamera}; +use std::fs; +use validator::Validate; + +mod cmdline; +mod config; +mod gst; + +pub(crate) use cmdline::Opt; +use config::Config; + +/// Entry point for the talk subcommand +/// +/// Opt is the command line options +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + + let mut cam_found = false; + for camera_config in &config.cameras { + if opt.camera == camera_config.name { + cam_found = true; + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_config.camera_addr + ); + + let mut camera = + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; + + info!("{}: Logging in", camera_config.name); + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; + + info!("{}: Connected and logged in", camera_config.name); + + let talk_ability = camera + .talk_ability() + .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; + if talk_ability.duplex_list.is_empty() + || talk_ability.audio_stream_mode_list.is_empty() + || talk_ability.audio_config_list.is_empty() + { + return Err(anyhow!( + "Camera {} does not support talk", + camera_config.name + )); + } + + // Just copy that data from the first talk ability in the config have never seen more + // than one ability + let config = 0; + + let talk_config = TalkConfig { + channel_id: camera_config.channel_id, + duplex: talk_ability.duplex_list[config].duplex.clone(), + audio_stream_mode: talk_ability.audio_stream_mode_list[config] + .audio_stream_mode + .clone(), + audio_config: talk_ability.audio_config_list[config].audio_config.clone(), + ..Default::default() + }; + + let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; + let sample_rate = talk_config.audio_config.sample_rate; + if block_size == 0 || sample_rate == 0 { + return Err(anyhow!( + "The camera {} does not support talk with adpcm", + camera_config.name + )); + } + + let rx = match (&opt.file_path, &opt.microphone) { + (Some(path), false) => gst::from_input( + &format!( + "filesrc location={}", + path.to_str().expect("File path not UTF8 complient") + ), + opt.volume, + block_size, + sample_rate, + ) + .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, + (None, true) => { + gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) + .context("Failed to setup gst using the microphone")? + } + _ => unreachable!(), + }; + + camera + .talk_stream(rx, talk_config) + .context("Talk stream ended early")?; + } + } + + if !cam_found { + Err(anyhow!( + "Camera {} was not in the config file {:?}", + &opt.camera, + &opt.config + )) + } else { + Ok(()) + } +}