From 689f14a634c7855249d3bb09cb0e0bf8b5cd0c7a Mon Sep 17 00:00:00 2001 From: hl-valdemar Date: Fri, 9 Oct 2026 22:08:34 +0200 Subject: [PATCH] feat: preview video thumbnails in a floating window --- Cargo.lock | 607 ++++++++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 2 + src/main.rs | 157 ++++++++++-- src/thumbnail.rs | 301 +++++++++++++++++++++++ src/youtube.rs | 121 +++++++++- 5 files changed, 1152 insertions(+), 36 deletions(-) create mode 100644 src/thumbnail.rs diff --git a/Cargo.lock b/Cargo.lock index ccf1c56..27bc8ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "allocator-api2" version = "0.2.21" @@ -44,7 +50,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -55,7 +61,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -73,18 +79,66 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + [[package]] name = "by_address" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "castaway" version = "0.2.4" @@ -169,6 +223,15 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossterm" version = "0.29.0" @@ -181,7 +244,7 @@ dependencies = [ "document-features", "mio", "parking_lot", - "rustix", + "rustix 1.1.5", "signal-hook", "signal-hook-mio", "winapi", @@ -286,7 +349,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", ] [[package]] @@ -295,6 +378,23 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -323,12 +423,37 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "icy_sixel" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bfb5a63225620b59df34a235d1fb56ff7b766909c3212a8ff927511a22b181d" +dependencies = [ + "quantette", + "thiserror 2.0.21", +] + [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -390,7 +515,7 @@ checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899" dependencies = [ "hashbrown 0.16.1", "portable-atomic", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -414,6 +539,12 @@ dependencies = [ "bitflags", ] +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -456,6 +587,26 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -465,7 +616,17 @@ dependencies = [ "libc", "log", "wasi", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", ] [[package]] @@ -481,6 +642,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -498,6 +660,21 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + [[package]] name = "palette" version = "0.7.7" @@ -505,6 +682,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" dependencies = [ "approx", + "bytemuck", "libm", "palette_derive", "palette_math", @@ -554,6 +732,19 @@ dependencies = [ "windows-link", ] +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -566,6 +757,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -575,6 +775,30 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quantette" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5d37e94c17b8870a5b936001d2845a6782a22ebdb1706c84294eca777f6729" +dependencies = [ + "bitvec", + "bytemuck", + "libm", + "num-traits", + "ordered-float", + "palette", + "rand 0.10.3", + "rand_xoshiro", + "ref-cast", + "wide", +] + [[package]] name = "quote" version = "1.0.47" @@ -584,6 +808,66 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xoshiro" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "662effc7698e08ea324d3acccf8d9d7f7bf79b9785e270a174ea36e56900c91d" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "ratatui" version = "0.30.2" @@ -612,7 +896,7 @@ dependencies = [ "palette", "serde", "strum", - "thiserror", + "thiserror 2.0.21", "unicode-segmentation", "unicode-truncate", "unicode-width", @@ -630,6 +914,24 @@ dependencies = [ "ratatui-core", ] +[[package]] +name = "ratatui-image" +version = "11.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9593d10c61ec2007f429d1fafc4f4a19fecdbae4d06b531a2d505227fb82f5ea" +dependencies = [ + "base64-simd", + "flate2", + "icy_sixel", + "image", + "rand 0.8.8", + "ratatui", + "rustix 0.38.44", + "self_cell", + "thiserror 1.0.69", + "windows", +] + [[package]] name = "ratatui-widgets" version = "0.3.2" @@ -659,6 +961,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -668,6 +990,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + [[package]] name = "rustix" version = "1.1.5" @@ -677,8 +1012,8 @@ dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys", - "windows-sys", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", ] [[package]] @@ -693,12 +1028,27 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "safe_arch" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f" +dependencies = [ + "bytemuck", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + [[package]] name = "semver" version = "1.0.28" @@ -779,6 +1129,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "smallvec" version = "1.16.2" @@ -840,13 +1196,39 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -923,8 +1305,10 @@ name = "tubular" version = "0.1.0" dependencies = [ "clap", + "image", "libc", "ratatui", + "ratatui-image", "serde", "serde_json", "toml_edit", @@ -965,12 +1349,28 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wide" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f" +dependencies = [ + "bytemuck", + "safe_arch", +] + [[package]] name = "winapi" version = "0.3.9" @@ -993,12 +1393,85 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-strings", + "windows-targets", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result", + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1008,6 +1481,70 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "1.0.4" @@ -1017,8 +1554,58 @@ dependencies = [ "memchr", ] +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9" + +[[package]] +name = "zune-jpeg" +version = "0.5.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec5f41c76397b7da451efd19915684f727d7e1d516384ca6bd0ec43ec94de23c" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml index e010c38..98d7cd4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,9 @@ description = "A terminal YouTube browser that streams videos to your chosen pla [dependencies] clap = { version = "4.6.7", features = ["derive"] } +image = { version = "0.25.10", default-features = false, features = ["jpeg"] } ratatui = { version = "0.30.2", default-features = false, features = ["crossterm", "unstable-rendered-line-info"] } +ratatui-image = { version = "11.1.0", default-features = false, features = ["crossterm"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" toml_edit = "0.25.17" diff --git a/src/main.rs b/src/main.rs index a134121..2f845fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,9 @@ //! Normal-mode d opens the full description; Up/Down scrolls lines and PgUp/PgDn scrolls pages. //! The centered popup uses up to 70% width and 60% height, capped at 96 by 20 cells. //! Esc closes the popup; j/k loads the selected video's description and i returns to editing. +//! Normal-mode t toggles a thumbnail in the same-sized popup; j/k follows selection, Esc closes. +//! Images use native terminal graphics when supported, otherwise colored half-block characters. +//! curl fetches JPEGs lazily into memory; decoding and image resizing/encoding run off-thread. //! Channel categories live in `$XDG_CONFIG_HOME/tubular/config.toml`, or `~/.config/tubular/config.toml`. //! Under `[categories]`, write `Rust = ["@RustVideos"]`; channel URLs and UC IDs also work. //! Normal-mode c opens the category picker; n there prompts for a new name, Enter saves, Esc cancels. @@ -17,6 +20,7 @@ //! See `--help` for controls; replacing playback or quitting cancels its processes. mod config; +mod thumbnail; mod youtube; use std::{ffi::OsString, io, path::PathBuf, time::Duration}; @@ -36,7 +40,7 @@ use youtube::{Job, Playback, Video}; #[command( version, about = "Search YouTube and stream videos to your chosen player", - after_help = "Requires yt-dlp, FFmpeg, and a player on PATH.\nDefaults to IINA on macOS and mpv elsewhere; --player overrides the default.\nIINA receives '--stdin'; other players receive '-' to read audio/video from standard input.\nWithout a CLI query, start in INSERT; a CLI query is searched automatically in NORMAL.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nNORMAL: j/k or arrows select; Enter streams; i edits the query; d toggles description; c saves a channel; q quits.\nTab/Shift-Tab switch Search/category views; r reloads config and refreshes the current view.\nSubscriptions: $XDG_CONFIG_HOME/tubular/config.toml, or ~/.config/tubular/config.toml when XDG_CONFIG_HOME is unset/empty/relative.\nExample TOML:\n[categories]\nRust = [\"@RustVideos\"]\nChannel entries accept @handles, HTTPS YouTube channel URLs, or canonical UC channel IDs.\nFeeds combine up to 20 videos per channel's /videos tab, newest-first using approximate upload dates.\nCATEGORY PICKER: j/k or arrows choose; Enter saves; n prompts for a new category; Esc cancels.\nNEW CATEGORY: type a name; Enter creates it and saves the channel; Esc returns to the picker; Ctrl-U clears.\nOpening the description fetches full video metadata, preserving paragraphs and caching it for these results.\nThe centered description window uses up to 70% width and 60% height, capped at 96 by 20 cells.\nWhile it is open, Up/Down scroll lines and PgUp/PgDn scroll pages; j/k still selects videos.\nEsc closes the description; i closes it to edit the query. Scrolling stays within the text.\nCtrl-U clears in INSERT; Ctrl-C quits in any mode or popup.\nSelecting another video replaces playback. Quitting stops playback.\nExample: tubular --player mpv --player-arg=--volume=50 \"rust programming\"" + after_help = "Requires yt-dlp, FFmpeg, and a player on PATH; thumbnails also use curl.\nDefaults to IINA on macOS and mpv elsewhere; --player overrides the default.\nIINA receives '--stdin'; other players receive '-' to read audio/video from standard input.\nWithout a CLI query, start in INSERT; a CLI query is searched automatically in NORMAL.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nNORMAL: j/k or arrows select; Enter streams; i edits the query; d toggles description; t toggles thumbnail; c saves a channel; q quits.\nTab/Shift-Tab switch Search/category views; r reloads config and refreshes the current view.\nSubscriptions: $XDG_CONFIG_HOME/tubular/config.toml, or ~/.config/tubular/config.toml when XDG_CONFIG_HOME is unset/empty/relative.\nExample TOML:\n[categories]\nRust = [\"@RustVideos\"]\nChannel entries accept @handles, HTTPS YouTube channel URLs, or canonical UC channel IDs.\nFeeds combine up to 20 videos per channel's /videos tab, newest-first using approximate upload dates.\nCATEGORY PICKER: j/k or arrows choose; Enter saves; n prompts for a new category; Esc cancels.\nNEW CATEGORY: type a name; Enter creates it and saves the channel; Esc returns to the picker; Ctrl-U clears.\nOpening the description fetches full video metadata, preserving paragraphs and caching it for these results.\nPreview windows use up to 70% width and 60% height, capped at 96 by 20 cells.\nIn descriptions, Up/Down scroll lines and PgUp/PgDn scroll pages; j/k still selects videos.\nEsc closes the description; i closes it to edit the query. Scrolling stays within the text.\nTHUMBNAIL: t or Esc closes; j/k or arrows load the selected video's image; d switches to description.\nThumbnails are fetched lazily into memory and fit proportionally inside the popup on resize.\nTerminal graphics are detected at startup, with colored half-block rendering when image protocols are unavailable.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\ni, c, view changes, and refresh dismiss the thumbnail; typing t in INSERT or a category name edits text.\nCtrl-U clears in INSERT; Ctrl-C quits in any mode or popup.\nSelecting another video replaces playback. Quitting stops playback.\nExample: tubular --player mpv --player-arg=--volume=50 \"rust programming\"" )] struct Options { /// Player executable (IINA or a player supporting '-' for standard input). @@ -95,6 +99,8 @@ struct App { views: Vec, view_index: usize, category_dialog: Option, + thumbnail_open: bool, + thumbnail: thumbnail::Thumbnail, description_open: bool, description_job: Option<(usize, Job)>, description_error: Option, @@ -126,6 +132,8 @@ impl App { views, view_index: 0, category_dialog: None, + thumbnail_open: false, + thumbnail: thumbnail::Thumbnail::new(), description_open: false, description_job: None, description_error: None, @@ -157,6 +165,7 @@ impl App { self.job = None; self.view_index = index; } + self.close_thumbnail(); self.description_open = false; self.description_job = None; self.description_viewport = None; @@ -177,6 +186,7 @@ impl App { self.job = None; self.description_open = false; self.description_job = None; + self.close_thumbnail(); let view = &mut self.views[self.view_index]; view.videos.clear(); view.selection = TableState::default(); @@ -237,9 +247,11 @@ impl App { self.job = None; self.description_open = false; self.description_job = None; + self.close_thumbnail(); } fn refresh(&mut self) { + self.close_thumbnail(); match config::load(&self.config_path) { Ok(config) => { self.apply_config(config); @@ -250,6 +262,7 @@ impl App { } fn open_category_picker(&mut self) { + self.close_thumbnail(); let view = &self.views[self.view_index]; let Some(video) = view .selection @@ -368,6 +381,13 @@ impl App { self.category_dialog = Some(dialog); } + fn close_thumbnail(&mut self) { + if self.thumbnail_open { + self.thumbnail_open = false; + self.thumbnail.cancel(); + } + } + fn load_description(&mut self) { self.description_job = None; self.description_error = None; @@ -483,6 +503,7 @@ impl App { } let selected_before = self.views[self.view_index].selection.selected(); let description_was_open = self.description_open; + let thumbnail_was_open = self.thumbnail_open; if self.mode == Mode::Insert { match key.code { KeyCode::Esc => self.mode = Mode::Normal, @@ -510,16 +531,32 @@ impl App { KeyCode::Char('q') => return true, KeyCode::Char('i') => { self.description_open = false; + self.close_thumbnail(); self.mode = Mode::Insert; } KeyCode::Char('d') => { + self.close_thumbnail(); self.description_open = !self.description_open && self.views[self.view_index] .selection .selected() .is_some_and(|index| index < self.views[self.view_index].videos.len()); } - KeyCode::Esc => self.description_open = false, + KeyCode::Char('t') => { + if self.thumbnail_open { + self.close_thumbnail(); + } else { + self.thumbnail_open = self.views[self.view_index] + .selection + .selected() + .is_some_and(|index| index < self.views[self.view_index].videos.len()); + } + self.description_open = false; + } + KeyCode::Esc => { + self.description_open = false; + self.close_thumbnail(); + } KeyCode::Down if self.description_open => { self.description_scroll = self .description_scroll @@ -586,6 +623,16 @@ impl App { { self.load_description(); } + if self.thumbnail_open + && (!thumbnail_was_open + || self.views[self.view_index].selection.selected() != selected_before) + && let Some(video) = self.views[self.view_index] + .selection + .selected() + .and_then(|index| self.views[self.view_index].videos.get(index)) + { + self.thumbnail.select(&video.id); + } false } @@ -656,8 +703,11 @@ impl App { Mode::Normal if self.description_open => { "NORMAL · ↑/↓ PgUp/PgDn scroll · j/k video · d/Esc close · i insert · q quit" } + Mode::Normal if self.thumbnail_open => { + "NORMAL · j/k video · t/Esc close · d description · i insert · q quit" + } Mode::Normal => { - "NORMAL · j/k select · Enter play · i search · d info · c save · Tab views · r refresh · q quit" + "NORMAL · j/k · Enter play · i search · d info · t image · c save · Tab views · r refresh · q quit" } }; frame.render_widget(Paragraph::new(help_text).dim(), help); @@ -667,23 +717,7 @@ impl App { .selected() .and_then(|index| self.views[self.view_index].videos.get(index)) { - let area = frame.area(); - let width = area - .width - .saturating_sub(4) - .min((u32::from(area.width) * 70 / 100) as u16) - .min(96); - let height = area - .height - .saturating_sub(4) - .min((u32::from(area.height) * 60 / 100) as u16) - .min(20); - let popup = Rect::new( - area.x + (area.width - width) / 2, - area.y + (area.height - height) / 2, - width, - height, - ); + let popup = preview_area(frame.area()); frame.render_widget(Clear, popup); let text = match video.description.as_deref() { Some("") => "This video has no description.", @@ -694,7 +728,10 @@ impl App { .unwrap_or("Loading full description..."), }; let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }); - let viewport = (width.saturating_sub(2), height.saturating_sub(2)); + let viewport = ( + popup.width.saturating_sub(2), + popup.height.saturating_sub(2), + ); if self.description_viewport != Some(viewport) { self.description_max_scroll = if viewport.0 == 0 || viewport.1 == 0 { 0 @@ -721,6 +758,26 @@ impl App { popup, ); } + if self.thumbnail_open + && let Some(video) = self.views[self.view_index] + .selection + .selected() + .and_then(|index| self.views[self.view_index].videos.get(index)) + { + let popup = preview_area(frame.area()); + frame.render_widget(Clear, popup); + let block = Block::bordered() + .title(" Thumbnail · t/Esc close ") + .title_bottom(Line::from(vec![ + " ".into(), + video.title.as_str().into(), + " ".into(), + ])) + .border_style(Style::new().fg(Color::Cyan)); + let inner = block.inner(popup); + frame.render_widget(block, popup); + self.thumbnail.draw(frame, inner); + } self.draw_category_dialog(frame); } @@ -804,6 +861,7 @@ impl App { } fn run(mut self, terminal: &mut DefaultTerminal) -> io::Result<()> { + self.thumbnail.query_terminal(); if !self.query.trim().is_empty() { self.search(); } @@ -821,6 +879,25 @@ impl App { } } +fn preview_area(area: Rect) -> Rect { + let width = area + .width + .saturating_sub(4) + .min((u32::from(area.width) * 70 / 100) as u16) + .min(96); + let height = area + .height + .saturating_sub(4) + .min((u32::from(area.height) * 60 / 100) as u16) + .min(20); + Rect::new( + area.x + (area.width - width) / 2, + area.y + (area.height - height) / 2, + width, + height, + ) +} + fn main() -> io::Result<()> { let options = Options::parse(); let config_path = config::config_path()?; @@ -960,4 +1037,42 @@ mod tests { assert!(!app.views[app.view_index].loaded); assert!(app.job.is_none()); } + + #[test] + fn thumbnails_are_normal_mode_only_and_other_popups_dismiss_them() { + let mut app = app(&["tubular"]); + app.key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE)); + assert_eq!(app.query, "t"); + assert!(!app.thumbnail_open); + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + app.key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE)); + assert!(!app.thumbnail_open); + + app.views[0].videos = youtube::search_results( + r#"{"entries":[{"id":"jNQXAC9IVRw","title":"Me at the zoo","channel_id":"UC4QobU6STFB0P71PMvOGN5A"}]}"#, + ).unwrap(); + app.views[0].videos[0].description = Some("A cached full description.".into()); + app.views[0].selection.select(Some(0)); + app.views[0].loaded = true; + app.thumbnail_open = true; + app.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + assert!(app.description_open); + assert!(!app.thumbnail_open); + assert!(app.description_job.is_none()); + + app.thumbnail_open = true; + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(!app.description_open); + assert!(!app.thumbnail_open); + assert_eq!(app.mode, Mode::Normal); + app.thumbnail_open = true; + app.key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)); + assert!(app.category_dialog.is_some()); + assert!(!app.thumbnail_open); + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + app.thumbnail_open = true; + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); + assert_eq!(app.mode, Mode::Insert); + assert!(!app.thumbnail_open); + } } diff --git a/src/thumbnail.rs b/src/thumbnail.rs new file mode 100644 index 0000000..09dcee4 --- /dev/null +++ b/src/thumbnail.rs @@ -0,0 +1,301 @@ +use std::{ + io::Cursor, + sync::mpsc::{self, Receiver, TryRecvError}, + thread, +}; + +use image::{ImageFormat, ImageReader, Limits}; +use ratatui::{ + Frame, + layout::{Alignment, Rect, Size}, + widgets::{Paragraph, Wrap}, +}; +use ratatui_image::{ + FilterType, Resize, StatefulImage, + picker::Picker, + thread::{ResizeRequest, ResizeResponse, ThreadProtocol}, +}; + +use crate::youtube::ThumbnailJob; + +struct ThumbnailImage { + id: String, + protocol: ThreadProtocol, + replies: Receiver>, + complete: bool, +} + +pub struct Thumbnail { + picker: Picker, + selected: Option, + fetch: Option, + decoder: Option>>, + image: Option, + // ponytail: one completed thumbnail plus an in-flight replacement, not a video cache. + cached: Option, + error: Option, +} + +impl Thumbnail { + pub fn new() -> Self { + Self { + picker: Picker::halfblocks(), + selected: None, + fetch: None, + decoder: None, + image: None, + cached: None, + error: None, + } + } + + /// Call once in raw mode/alternate screen, before the event loop reads stdin. + pub fn query_terminal(&mut self) { + self.picker = Picker::from_query_stdio().unwrap_or_else(|_| Picker::halfblocks()); + let font = self.picker.font_size(); + if font.width == 0 || font.height == 0 { + self.picker = Picker::halfblocks(); + } + } + + pub fn select(&mut self, id: &str) { + if self.selected.as_deref() == Some(id) { + return; + } + self.cancel(); + self.selected = Some(id.to_owned()); + if self.cached.as_ref().is_some_and(|image| image.id == id) { + self.image = self.cached.take(); + return; + } + match ThumbnailJob::start(id) { + Ok(job) => self.fetch = Some(job), + Err(error) => self.error = Some(format!("Could not load thumbnail: {error}")), + } + } + + pub fn cancel(&mut self) { + self.fetch = None; + // Each decode has its own receiver: dropping it invalidates even a queued completion. + self.decoder = None; + self.selected = None; + self.error = None; + if let Some(image) = self.image.take() + && image.complete + { + self.cached = Some(image); + } + } + + pub fn draw(&mut self, frame: &mut Frame, area: Rect) { + self.poll(); + if area.width == 0 || area.height == 0 || self.selected.is_none() { + return; + } + + let mut message = self.error.as_deref().unwrap_or("Loading thumbnail..."); + if let Some(image) = self.image.as_mut() { + let resize = Resize::Fit(Some(FilterType::Triangle)); + if let Some(size) = image.protocol.size_for(resize.clone(), area.into()) { + frame.render_stateful_widget( + StatefulImage::new().resize(resize), + centered(area, size), + &mut image.protocol, + ); + if image.protocol.protocol_type().is_some() { + return; + } + } + message = "Preparing thumbnail..."; + } else if self.decoder.is_some() { + message = "Decoding thumbnail..."; + } + frame.render_widget( + Paragraph::new(message) + .alignment(Alignment::Center) + .wrap(Wrap { trim: true }), + Rect::new( + area.x, + area.y + area.height / 2, + area.width, + area.height - area.height / 2, + ), + ); + } + + fn poll(&mut self) { + if let Some(result) = self.fetch.as_mut().and_then(ThumbnailJob::poll) { + self.fetch = None; + match result { + Ok(bytes) => { + let picker = self.picker.clone(); + let id = self.selected.clone().expect("A fetch has a selected video"); + let (tx, rx) = mpsc::channel(); + match thread::Builder::new() + .name("thumbnail-decode".into()) + .spawn(move || { + let _ = tx.send(prepare(id, bytes, picker)); + }) { + Ok(_) => self.decoder = Some(rx), + Err(error) => { + self.error = Some(format!("Could not decode thumbnail: {error}")); + } + } + } + Err(error) => self.error = Some(format!("Could not load thumbnail: {error}")), + } + } + if let Some(result) = self.decoder.as_ref().map(Receiver::try_recv) { + match result { + Ok(result) => { + self.decoder = None; + match result { + Ok(image) => self.image = Some(image), + Err(error) => self.error = Some(error), + } + } + Err(TryRecvError::Disconnected) => { + self.decoder = None; + self.error = Some("Thumbnail decoder stopped before completing.".into()); + } + Err(TryRecvError::Empty) => {} + } + } + if let Some(image) = self.image.as_mut() { + match image.replies.try_recv() { + Ok(Ok(response)) => { + // ThreadProtocol rejects obsolete requests; the widget checks the current + // area again before rendering, so rapid resizes cannot draw an old size. + if image.protocol.update_resized_protocol(response) { + image.complete = true; + self.cached = None; + } + } + Ok(Err(error)) => { + self.image = None; + self.error = Some(format!("Could not render thumbnail: {error}")); + } + Err(TryRecvError::Disconnected) => { + self.image = None; + self.error = Some("Thumbnail renderer stopped before completing.".into()); + } + Err(TryRecvError::Empty) => {} + } + } + } +} + +fn prepare(id: String, bytes: Vec, picker: Picker) -> Result { + let image = decode(bytes)?; + let protocol = picker.new_resize_protocol(image); + let (requests_tx, requests_rx) = mpsc::channel::(); + let (replies_tx, replies_rx) = mpsc::channel(); + thread::Builder::new() + .name("thumbnail-resize".into()) + .spawn(move || { + for request in requests_rx { + if replies_tx + .send(request.resize_encode().map_err(|error| error.to_string())) + .is_err() + { + break; + } + } + }) + .map_err(|error| format!("Could not prepare thumbnail renderer: {error}"))?; + Ok(ThumbnailImage { + id, + protocol: ThreadProtocol::new(requests_tx, Some(protocol)), + replies: replies_rx, + complete: false, + }) +} + +fn decode(bytes: Vec) -> Result { + if bytes.len() > 2 * 1024 * 1024 { + return Err("Thumbnail exceeds the 2 MiB download limit.".into()); + } + let mut reader = ImageReader::with_format(Cursor::new(bytes), ImageFormat::Jpeg); + let mut limits = Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(16 * 1024 * 1024); + reader.limits(limits); + reader + .decode() + .map_err(|error| format!("Could not decode thumbnail JPEG: {error}")) +} + +fn centered(area: Rect, size: Size) -> Rect { + let width = size.width.min(area.width); + let height = size.height.min(area.height); + Rect::new( + area.x + (area.width - width) / 2, + area.y + (area.height - height) / 2, + width, + height, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_corrupt_and_oversized_jpeg_input() { + assert!(decode(b"not a JPEG".to_vec()).is_err()); + assert!(decode(vec![0; 2 * 1024 * 1024 + 1]).is_err()); + } + + #[test] + fn cancellation_discards_queued_decode_completion() { + let mut thumbnail = Thumbnail::new(); + let (tx, rx) = mpsc::channel(); + let (requests_tx, _requests_rx) = mpsc::channel(); + let (_replies_tx, replies_rx) = mpsc::channel(); + let protocol = thumbnail + .picker + .new_resize_protocol(image::DynamicImage::new_rgb8(1, 1)); + thumbnail.selected = Some("old-video".into()); + thumbnail.decoder = Some(rx); + assert!( + tx.send(Ok(ThumbnailImage { + id: "old-video".into(), + protocol: ThreadProtocol::new(requests_tx, Some(protocol)), + replies: replies_rx, + complete: false, + })) + .is_ok() + ); + thumbnail.cancel(); + thumbnail.selected = Some("new-video".into()); + thumbnail.poll(); + assert!(thumbnail.image.is_none()); + assert!(thumbnail.error.is_none()); + } + + #[test] + fn resized_image_preserves_aspect_and_stays_inside_popup() { + let picker = Picker::halfblocks(); + let font = picker.font_size(); + let protocol = picker.new_resize_protocol(image::DynamicImage::new_rgb8(480, 360)); + let area = Rect::new(7, 3, 80, 10); + let size = protocol.size_for(Resize::Fit(None), area.into()); + let image_area = centered(area, size); + assert!(image_area.x >= area.x && image_area.right() <= area.right()); + assert!(image_area.y >= area.y && image_area.bottom() <= area.bottom()); + let left = image_area.x - area.x; + let right = area.right() - image_area.right(); + let top = image_area.y - area.y; + let bottom = area.bottom() - image_area.bottom(); + assert!(left.abs_diff(right) <= 1 && top.abs_diff(bottom) <= 1); + let pixel_width = u32::from(image_area.width) * u32::from(font.width); + let pixel_height = u32::from(image_area.height) * u32::from(font.height); + // Cell rounding may add at most one cell to either fitted pixel dimension. + assert!( + pixel_width.abs_diff(pixel_height * 4 / 3) + <= u32::from(font.width) + u32::from(font.height) * 4 / 3 + ); + assert_eq!(centered(Rect::new(7, 3, 0, 0), size), Rect::new(7, 3, 0, 0)); + } +} diff --git a/src/youtube.rs b/src/youtube.rs index 20bd9db..baef009 100644 --- a/src/youtube.rs +++ b/src/youtube.rs @@ -45,13 +45,15 @@ fn valid_channel_id(id: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') } -fn validate_video(video: &mut Video) -> Result<(), String> { - if video.id.len() != 11 - || !video - .id +fn valid_video_id(id: &str) -> bool { + id.len() == 11 + && id .bytes() .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') - { +} + +fn validate_video(video: &mut Video) -> Result<(), String> { + if !valid_video_id(&video.id) { return Err("an invalid YouTube video ID".into()); } if video @@ -222,6 +224,96 @@ impl Drop for Job { } } +const MAX_THUMBNAIL_BYTES: usize = 2 * 1024 * 1024; + +pub struct ThumbnailJob { + child: Child, + output: Receiver, String)>>, +} + +impl ThumbnailJob { + pub fn start(id: &str) -> io::Result { + if !valid_video_id(id) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Invalid YouTube video ID", + )); + } + let mut child = isolated_command(OsStr::new("curl")) + .args([ + "--disable", + "--silent", + "--show-error", + "--fail", + "--location", + "--proto", + "=https", + "--proto-redir", + "=https", + "--connect-timeout", + "5", + "--max-time", + "15", + "--max-filesize", + "2097152", // 2 MiB; read_thumbnail also enforces the limit. + ]) + .arg(format!("https://i.ytimg.com/vi/{id}/hqdefault.jpg")) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| io::Error::new(error.kind(), format!("Cannot start curl: {error}")))?; + let stdout = child.stdout.take().expect("stdout is piped"); + let errors = read_errors(child.stderr.take().expect("stderr is piped")); + let (sender, output) = mpsc::channel(); + thread::spawn(move || { + let bytes = read_thumbnail(stdout); + let result = errors + .recv() + .unwrap_or_else(|_| Err(io::Error::other("curl error reader disconnected"))) + .and_then(|errors| bytes.map(|bytes| (bytes, errors))); + let _ = sender.send(result); + }); + Ok(Self { child, output }) + } + + pub fn poll(&mut self) -> Option, String>> { + // EOF alone is not success: curl can write a partial body and then fail. + let status = match self.child.try_wait() { + Ok(Some(status)) => status, + Ok(None) => return None, + Err(error) => return Some(Err(format!("Cannot wait for curl: {error}"))), + }; + match self.output.try_recv() { + Ok(Ok((bytes, _))) if status.success() => Some(Ok(bytes)), + Ok(Ok((_, errors))) => Some(Err(if errors.trim().is_empty() { + format!("curl exited with {status}") + } else { + errors.trim().to_owned() + })), + Ok(Err(error)) => Some(Err(format!("Cannot read thumbnail: {error}"))), + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => Some(Err("curl output reader disconnected".into())), + } + } +} + +impl Drop for ThumbnailJob { + fn drop(&mut self) { + stop(&mut self.child); + } +} + +fn read_thumbnail(pipe: impl Read) -> io::Result> { + let mut bytes = Vec::new(); + pipe.take((MAX_THUMBNAIL_BYTES + 1) as u64) + .read_to_end(&mut bytes)?; + if bytes.len() > MAX_THUMBNAIL_BYTES { + return Err(io::Error::other("Thumbnail exceeds 2 MiB")); + } + Ok(bytes) +} + fn isolated_command(program: &OsStr) -> Command { let mut command = Command::new(program); #[cfg(unix)] @@ -371,6 +463,25 @@ impl Drop for Playback { mod tests { use super::*; + #[test] + fn thumbnails_bound_binary_input_and_reject_unsafe_ids() { + let bytes = [0xff, 0xd8, 0x00, 0xfe]; + assert_eq!(read_thumbnail(bytes.as_slice()).unwrap(), bytes); + assert_eq!( + read_thumbnail(io::repeat(0).take(MAX_THUMBNAIL_BYTES as u64)) + .unwrap() + .len(), + MAX_THUMBNAIL_BYTES + ); + assert!(read_thumbnail(io::repeat(0)).is_err()); + for id in ["../secrets", "abcdefghij/", "abcdefghijé", "--bad"] { + assert!(matches!( + ThumbnailJob::start(id), + Err(error) if error.kind() == io::ErrorKind::InvalidInput + )); + } + } + #[test] fn search_handles_unavailable_entries_and_rejects_invalid_ids() { let videos = search_results(