From a6a78cca8baec7766c1f04ead1f8ac78552c0b23 Mon Sep 17 00:00:00 2001 From: Accusys Date: Thu, 19 Nov 2026 18:24:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=89=E5=B1=A4=E9=9A=8E=E6=A2=AF?= =?UTF-8?q?=E5=BC=8F=20frame=20=E5=8F=96=E6=A8=A3=20+=20=E7=B4=94=20Rust?= =?UTF-8?q?=20=E9=81=8B=E9=8F=A1=E5=88=86=E6=9E=90=20+=20pHash=20=E5=8E=BB?= =?UTF-8?q?=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase correlation 運鏡分析 (camera_motion.rs): - ffmpeg pipe 抽幀 → 灰階 256x256 → rustfft 相位相關估 pan/tilt - 徑向功率譜估 zoom、極座標相位相關估 rotation - 中位數去噪 + none/low/high 分級 - samples_for_level: none=1, low=2, high=4 pHash 去重 (frame_dedup.rs): - 64-bit pHash (DCT 低頻) + hamming<=8 + 時間間隔去重 - scene extract 後對 jpg 去重: 387 → 317 (移除 70) 三層取樣 (scene_vlm.rs process_interval): - L0 moment=10s 保底 (SCENE_VLM_MOMENT_SEC) - L1 每個 cut 保底 1 張 (不設上限) - L2 運鏡依 level 增採, 運動路徑均勻取樣 + blurdetect 資料結構: - SceneFrame.camera_motion + selection_reason CameraMotion*/CutBaseline - VLM truncated (finish_reason=length) salvage 部分 JSON summary 其他: - face dedup 改用 per-library output dir - max_tokens 2048→4096 - config 5 項 (moment_sec/camera_motion_enabled/phash_hamming/time_gap/k) - Cargo.toml +image/ndarray/rustfft 驗證: 17e230cc force re-run → Selected 387 frames, CAM-MOTION 分析執行, pHash dedup 387→317, RESUME force=true carried over 0 --- Cargo.lock | 640 +++++++++++++++++++++++++++- Cargo.toml | 5 + src/core/config.rs | 48 +++ src/core/file_profile.rs | 70 +++ src/core/processor/camera_motion.rs | 360 ++++++++++++++++ src/core/processor/frame_dedup.rs | 156 +++++++ src/core/processor/mod.rs | 2 + src/core/processor/scene_vlm.rs | 368 +++++++++------- src/worker/job_worker.rs | 55 ++- 9 files changed, 1546 insertions(+), 158 deletions(-) create mode 100644 src/core/processor/camera_motion.rs create mode 100644 src/core/processor/frame_dedup.rs diff --git a/Cargo.lock b/Cargo.lock index ba9b3dd9..2f093ff2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -71,6 +71,24 @@ dependencies = [ "memchr", ] +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -166,6 +184,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "argon2" version = "0.5.3" @@ -178,6 +207,21 @@ dependencies = [ "password-hash", ] +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "async-compression" version = "0.4.42" @@ -266,6 +310,49 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.18", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + [[package]] name = "axum" version = "0.7.9" @@ -375,6 +462,12 @@ dependencies = [ "virtue", ] +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + [[package]] name = "bitflags" version = "1.3.2" @@ -390,6 +483,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + [[package]] name = "bitvec" version = "1.0.1" @@ -444,18 +546,36 @@ dependencies = [ "uuid", ] +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + [[package]] name = "bumpalo" version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.11.1" @@ -593,6 +713,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "colorchoice" version = "1.0.5" @@ -794,6 +920,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -1125,6 +1257,26 @@ dependencies = [ "log", ] +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1179,12 +1331,43 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "fastrand" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "ferrous-opencc" version = "0.3.1" @@ -1476,6 +1659,16 @@ dependencies = [ "polyval", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "h2" version = "0.4.13" @@ -1495,6 +1688,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -1907,6 +2111,46 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + [[package]] name = "include-flate" version = "0.3.3" @@ -2013,6 +2257,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "ipconfig" version = "0.3.4" @@ -2191,6 +2446,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.186" @@ -2221,6 +2482,16 @@ dependencies = [ "rle-decode-fast", ] +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + [[package]] name = "libm" version = "0.2.16" @@ -2289,6 +2560,15 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + [[package]] name = "lru" version = "0.12.5" @@ -2344,6 +2624,26 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + [[package]] name = "md-5" version = "0.10.6" @@ -2473,6 +2773,7 @@ dependencies = [ "flate2", "futures-util", "hex", + "image", "jieba-rs", "jsonwebtoken", "libc", @@ -2480,6 +2781,7 @@ dependencies = [ "md5", "moka", "mongodb", + "ndarray", "notify", "once_cell", "pgvector", @@ -2488,6 +2790,7 @@ dependencies = [ "redis", "regex", "reqwest", + "rustfft", "sdl2", "serde", "serde_json", @@ -2558,6 +2861,16 @@ dependencies = [ "webpki-roots 0.25.4", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multer" version = "3.1.0" @@ -2575,6 +2888,28 @@ dependencies = [ "version_check", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "target-features", +] + [[package]] name = "native-tls" version = "0.2.18" @@ -2592,6 +2927,27 @@ dependencies = [ "tempfile", ] +[[package]] +name = "ndarray" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + [[package]] name = "nix" version = "0.29.0" @@ -2624,6 +2980,21 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + [[package]] name = "notify" version = "6.1.1" @@ -2687,12 +3058,32 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "num-integer" version = "0.1.46" @@ -2713,6 +3104,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2859,6 +3261,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + [[package]] name = "pbkdf2" version = "0.11.0" @@ -3014,6 +3422,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.11.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + [[package]] name = "polyval" version = "0.6.2" @@ -3075,6 +3496,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -3139,6 +3569,25 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.117", +] + [[package]] name = "prost" version = "0.13.5" @@ -3171,6 +3620,12 @@ dependencies = [ "prost", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + [[package]] name = "qdrant-client" version = "1.17.0" @@ -3193,6 +3648,21 @@ dependencies = [ "tonic", ] +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quinn" version = "0.11.9" @@ -3355,6 +3825,62 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.4", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror 2.0.18", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + [[package]] name = "rayon" version = "1.12.0" @@ -3515,6 +4041,12 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + [[package]] name = "ring" version = "0.17.14" @@ -3623,6 +4155,20 @@ dependencies = [ "semver 0.9.0", ] +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + [[package]] name = "rustix" version = "0.38.44" @@ -4059,6 +4605,15 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + [[package]] name = "simple_asn1" version = "0.6.4" @@ -4147,7 +4702,7 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7bba3a93db0cc4f7bdece8bb09e77e2e785c20bfebf79eb8340ed80708048790" dependencies = [ - "nom", + "nom 7.1.3", "unicode_categories", ] @@ -4481,6 +5036,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "stringprep" version = "0.1.5" @@ -4639,6 +5200,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "tempfile" version = "3.27.0" @@ -4701,6 +5268,20 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.47" @@ -5092,6 +5673,16 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "trust-dns-proto" version = "0.21.2" @@ -5336,6 +5927,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -5552,6 +6154,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "whoami" version = "1.6.1" @@ -6059,6 +6667,12 @@ version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3" +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + [[package]] name = "yoke" version = "0.8.2" @@ -6211,3 +6825,27 @@ dependencies = [ "cc", "pkg-config", ] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml index 72669d7c..4eb2bef1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,11 @@ once_cell = "1.19" libc = "0.2" dotenv = "0.15" +# Image processing (camera motion + pHash dedup) +image = "0.25" +ndarray = "0.16" +rustfft = "6" + # CLI clap = { version = "4", features = ["derive"] } diff --git a/src/core/config.rs b/src/core/config.rs index d53ebbcf..8b9995e2 100644 --- a/src/core/config.rs +++ b/src/core/config.rs @@ -212,6 +212,54 @@ pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) { ) } +// ── Frame 三層取樣 + 運鏡分析 configs ─────────────────────────── +/// moment 長度(秒),moment 內保底 1 張。預設 10。 +pub static SCENE_VLM_MOMENT_SEC: Lazy = Lazy::new(|| { + env::var("MOMENTRY_SCENE_VLM_MOMENT_SEC") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10) +}); + +/// 是否啟用運鏡分析(相位相關)。預設 true。 +pub static CAMERA_MOTION_ENABLED: Lazy = Lazy::new(|| { + env::var("MOMENTRY_CAMERA_MOTION_ENABLED") + .map(|v| v == "true" || v == "1") + .unwrap_or(true) +}); + +/// pHash 去重漢明距離閾值。預設 8。 +pub static PHASH_HAMMING_THRESHOLD: Lazy = Lazy::new(|| { + env::var("MOMENTRY_PHASH_HAMMING_THRESHOLD") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(8) +}); + +/// scene frame 去重的時間間隔(幀)。預設約 2 秒 @30fps = 60 幀。 +pub static SCENE_TIME_GAP_FRAMES: Lazy = Lazy::new(|| { + env::var("MOMENTRY_SCENE_TIME_GAP_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(60) +}); + +/// face trace 去重的時間間隔(幀)。預設約 1 秒 @30fps = 30 幀。 +pub static TRACE_TIME_GAP_FRAMES: Lazy = Lazy::new(|| { + env::var("MOMENTRY_TRACE_TIME_GAP_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(30) +}); + +/// 每個 cut 抽取用於運鏡分析的幀數。預設 6。 +pub static CAMERA_MOTION_K: Lazy = Lazy::new(|| { + env::var("MOMENTRY_CAMERA_MOTION_K") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(6) +}); + // ───────────────────────────────────────────────────────────── // JSON-backed configs (paths, concurrency, feature flags) // These read from admin_config.json with ENV fallback diff --git a/src/core/file_profile.rs b/src/core/file_profile.rs index 0cd0d6de..3fa54ef2 100644 --- a/src/core/file_profile.rs +++ b/src/core/file_profile.rs @@ -869,6 +869,72 @@ pub struct SceneFrame { pub vlm_tags: Vec, pub embedding_status: EmbeddingStatus, + + /// Camera-motion analysis for this scene (pan/tilt/zoom/rotation). + /// Absent in legacy scenes.json → treated as static. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub camera_motion: Option, +} + +/// Camera motion analysis result for a scene / cut segment. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct CameraMotion { + /// Dominant motion type. + pub motion_type: MotionType, + /// Severity level — drives how many extra samples to take. + pub level: MotionLevel, + /// Horizontal displacement (pixels, sign = direction). + pub pan_px: f64, + /// Vertical displacement (pixels, sign = direction). + pub tilt_px: f64, + /// Scale change factor (1.0 = no zoom). + pub zoom_factor: f64, + /// Rotation estimate (radians). + pub rotation_rad: f64, + /// Confidence 0.0-1.0 (based on phase-correlation peak consistency). + pub confidence: f64, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum MotionType { + Static, + Pan, + Tilt, + Zoom, + Rotation, + Dolly, + Handheld, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum MotionLevel { + None, + Low, + High, +} + +impl Default for MotionLevel { + fn default() -> Self { + MotionLevel::None + } +} + +impl CameraMotion { + /// A static / no-motion result (used as fallback and for legacy data). + pub fn static_motion() -> Self { + CameraMotion { + motion_type: MotionType::Static, + level: MotionLevel::None, + pan_px: 0.0, + tilt_px: 0.0, + zoom_factor: 1.0, + rotation_rad: 0.0, + confidence: 1.0, + } + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -886,6 +952,10 @@ pub enum SelectionReason { PostCutBestBlur, SceneStart, Default, + CameraMotionStart, + CameraMotionMid, + CameraMotionEnd, + CutBaseline, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] diff --git a/src/core/processor/camera_motion.rs b/src/core/processor/camera_motion.rs new file mode 100644 index 00000000..b13fbdd4 --- /dev/null +++ b/src/core/processor/camera_motion.rs @@ -0,0 +1,360 @@ +//! Camera-motion analysis via pure-Rust phase correlation. +//! +//! Given a video segment, extract K evenly-spaced grayscale frames (via ffmpeg +//! pipe, never written to disk), then estimate global camera motion between +//! consecutive frames: +//! - pan / tilt : phase-correlation peak position +//! - zoom : radial power-spectrum scale change +//! - rotation : phase correlation in polar coordinates +//! +//! A median over all consecutive pairs removes object-motion outliers. The +//! result is classified into MotionLevel::None / Low / High so callers can +//! decide how many extra samples to take inside a cut. + +use anyhow::{Context, Result}; +use image::GrayImage; +use ndarray::{Array2, Axis}; +use rustfft::{num_complex::Complex, FftPlanner}; +use std::process::{Command, Stdio}; +use tracing::{debug, warn}; + +use crate::core::file_profile::{CameraMotion, MotionLevel, MotionType}; + +/// Number of FFT size (power of two) used for phase correlation. +const FFT_SIZE: usize = 256; +/// Number of frames to extract per segment. +const DEFAULT_K: usize = 6; + +/// Analyze camera motion in a video segment [start_frame, end_frame]. +/// `k` = number of evenly-spaced frames to sample (min 2). +pub async fn analyze_camera_motion( + video_path: &str, + start_frame: u32, + end_frame: u32, + fps: f64, + k: usize, +) -> Result { + let k = k.max(2); + if end_frame <= start_frame || fps <= 0.0 { + return Ok(CameraMotion::static_motion()); + } + + let frames = extract_frames(video_path, start_frame, end_frame, fps, k).await?; + if frames.len() < 2 { + return Ok(CameraMotion::static_motion()); + } + + let mut pans = Vec::new(); + let mut tilts = Vec::new(); + let mut zooms = Vec::new(); + let mut rots = Vec::new(); + let mut peaks = Vec::new(); + + for pair in frames.windows(2) { + match phase_correlate(&pair[0], &pair[1]) { + Ok((dx, dy, peak)) => { + pans.push(dx); + tilts.push(dy); + zooms.push(estimate_zoom(&pair[0], &pair[1])); + rots.push(estimate_rotation(&pair[0], &pair[1])); + peaks.push(peak); + } + Err(e) => debug!("[CAM-MOTION] phase correlate failed: {}", e), + } + } + + if pans.is_empty() { + return Ok(CameraMotion::static_motion()); + } + + let pan = median(&mut pans); + let tilt = median(&mut tilts); + let zoom = median(&mut zooms); + let rot = median(&mut rots); + let confidence = median(&mut peaks).clamp(0.0, 1.0); + + // Classify: displacement relative to frame width, zoom/rotation thresholds. + let pan_abs = pan.abs(); + let tilt_abs = tilt.abs(); + let zoom_delta = (zoom - 1.0).abs(); + let rot_abs = rot.abs(); + + let max_shift = pan_abs.max(tilt_abs); + let (level, motion_type) = if max_shift < FFT_SIZE as f64 * 0.05 + && zoom_delta < 0.05 + && rot_abs < 0.02 + { + (MotionLevel::None, MotionType::Static) + } else { + let high = max_shift > FFT_SIZE as f64 * 0.20 + || zoom_delta > 0.30 + || rot_abs > 0.08; + let level = if high { MotionLevel::High } else { MotionLevel::Low }; + + // Dominant type by normalized magnitude. + let mut candidates = vec![ + (pan_abs / (FFT_SIZE as f64 * 0.2), MotionType::Pan), + (tilt_abs / (FFT_SIZE as f64 * 0.2), MotionType::Tilt), + (zoom_delta / 0.3, MotionType::Zoom), + (rot_abs / 0.08, MotionType::Rotation), + ]; + candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)); + let motion_type = candidates.first().map(|x| x.1).unwrap_or(MotionType::Pan); + (level, motion_type) + }; + + Ok(CameraMotion { + motion_type, + level, + pan_px: pan, + tilt_px: tilt, + zoom_factor: zoom, + rotation_rad: rot, + confidence, + }) +} + +/// Map motion level to number of samples to take inside a cut. +pub fn samples_for_level(level: MotionLevel) -> usize { + match level { + MotionLevel::None => 1, + MotionLevel::Low => 2, + MotionLevel::High => 4, + } +} + +/// Extract `k` evenly-spaced grayscale frames from the segment into memory. +async fn extract_frames( + video_path: &str, + start_frame: u32, + end_frame: u32, + fps: f64, + k: usize, +) -> Result> { + let mut frames = Vec::with_capacity(k); + for i in 0..k { + let frame = start_frame + ((end_frame - start_frame) as usize * i / (k - 1)) as u32; + let time_sec = frame as f64 / fps; + let child = Command::new("/opt/homebrew/bin/ffmpeg") + .args([ + "-y", + "-v", + "quiet", + "-ss", + &format!("{:.3}", time_sec), + "-i", + video_path, + "-frames:v", + "1", + "-vf", + &format!("scale={}:{}", FFT_SIZE, FFT_SIZE), + "-f", + "image2pipe", + "-vcodec", + "png", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .context("ffmpeg spawn failed for camera-motion frame extraction")?; + + let output = child + .wait_with_output() + .context("ffmpeg wait failed for camera-motion frame extraction")?; + if !output.status.success() || output.stdout.is_empty() { + warn!("[CAM-MOTION] ffmpeg produced no frame at t={:.2}", time_sec); + continue; + } + let img = image::load_from_memory_with_format(&output.stdout, image::ImageFormat::Png) + .context("failed to decode extracted png")? + .to_luma8(); + frames.push(img); + } + Ok(frames) +} + +/// Phase correlation: returns (dx, dy, peak_confidence) in FFT pixels. +/// dx/dy are wrapped into [-N/2, N/2]. +fn phase_correlate(a: &GrayImage, b: &GrayImage) -> Result<(f64, f64, f64)> { + let n = FFT_SIZE; + let fa = to_fft_array(a); + let fb = to_fft_array(b); + + let mut planner = FftPlanner::::new(); + let fft = planner.plan_fft_forward(n * n); + let ifft = planner.plan_fft_inverse(n * n); + + let mut aa = flatten(&fa); + let mut bb = flatten(&fb); + fft.process(&mut aa); + fft.process(&mut bb); + + // Cross-power spectrum: F(a) * conj(F(b)) / |F(a)F(b)| + let mut cross = Vec::with_capacity(n * n); + for (x, y) in aa.iter().zip(bb.iter()) { + let denom = (x.norm_sqr() * y.norm_sqr()).sqrt(); + if denom < 1e-9 { + cross.push(Complex::new(0.0, 0.0)); + } else { + cross.push(x * y.conj() / denom); + } + } + + ifft.process(&mut cross); + + // Find peak (skip DC). + let mut peak_idx = 0usize; + let mut peak_val = -1.0f64; + let mut second = 0.0f64; + for (i, c) in cross.iter().enumerate() { + let mag = c.norm(); + if i != 0 && mag > peak_val { + second = peak_val.max(second); + peak_val = mag; + peak_idx = i; + } else if mag > second { + second = mag; + } + } + if peak_val <= 0.0 { + return Ok((0.0, 0.0, 0.0)); + } + + let py = peak_idx / n; + let px = peak_idx % n; + let dx = wrap(px as f64, n); + let dy = wrap(py as f64, n); + // Confidence: ratio of peak to second-highest (higher = more reliable). + let confidence = (peak_val / (second + 1e-6)).tanh(); + Ok((dx, dy, confidence)) +} + +/// Estimate zoom by comparing radial power-spectrum bandwidth of two frames. +/// A zoomed-in frame has energy concentrated at lower radial frequencies. +fn estimate_zoom(a: &GrayImage, b: &GrayImage) -> f64 { + let ea = spectral_energy(a); + let eb = spectral_energy(b); + if ea <= 0.0 || eb <= 0.0 { + return 1.0; + } + // Ratio of high-frequency energy indicates scale change. + (eb / ea).sqrt().clamp(0.5, 2.0) +} + +/// Estimate rotation via phase correlation in polar coordinates (coarse). +/// Uses FFT angular power spectrum; returns radians in [-pi, pi]. +fn estimate_rotation(a: &GrayImage, b: &GrayImage) -> f64 { + // Similar to zoom: compare column-sum profiles of the power spectrum. + // A pure rotation shifts the angular profile cyclically. + let pa = angular_profile(a); + let pb = angular_profile(b); + let n = pa.len(); + let mut best_shift = 0usize; + let mut best_score = f64::NEG_INFINITY; + for shift in 0..n { + let mut score = 0.0; + for i in 0..n { + score += pa[i] * pb[(i + shift) % n]; + } + if score > best_score { + best_score = score; + best_shift = shift; + } + } + let shift = wrap(best_shift as f64, n); + shift * std::f64::consts::PI * 2.0 / n as f64 +} + +fn to_fft_array(img: &GrayImage) -> Array2 { + let (w, h) = img.dimensions(); + let mut arr = Array2::::zeros((h as usize, w as usize)); + for (x, y, px) in img.enumerate_pixels() { + // Hann window reduces edge artifacts in phase correlation. + let wx = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * x as f64 / w as f64).cos(); + let wy = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * y as f64 / h as f64).cos(); + arr[[y as usize, x as usize]] = px[0] as f64 * wx * wy; + } + arr +} + +fn flatten(arr: &Array2) -> Vec> { + arr.iter().map(|v| Complex::new(*v, 0.0)).collect() +} + +fn power_spectrum(img: &GrayImage) -> Vec { + let n = FFT_SIZE; + let arr = to_fft_array(img); + let mut data = flatten(&arr); + let mut planner = FftPlanner::::new(); + let fft = planner.plan_fft_forward(n * n); + fft.process(&mut data); + data.iter().map(|c| c.norm_sqr()).collect() +} + +fn spectral_energy(img: &GrayImage) -> f64 { + let spec = power_spectrum(img); + let n = FFT_SIZE; + let center = (n / 2, n / 2); + let mut hi = 0.0; + let mut total = 0.0; + for (i, v) in spec.iter().enumerate() { + let y = i / n; + let x = i % n; + let r = ((x as i32 - center.0 as i32).pow(2) + (y as i32 - center.1 as i32).pow(2)) as f64; + total += v; + if r > (n as f64 / 4.0).powi(2) { + hi += v; + } + } + if total > 0.0 { hi / total } else { 0.0 } +} + +fn angular_profile(img: &GrayImage) -> Vec { + let n = FFT_SIZE; + let spec = power_spectrum(img); + let bins = 64; + let mut profile = vec![0.0; bins]; + let center = (n / 2, n / 2); + for (i, v) in spec.iter().enumerate() { + let y = i / n; + let x = i % n; + let dx = x as f64 - center.0 as f64; + let dy = y as f64 - center.1 as f64; + if dx == 0.0 && dy == 0.0 { + continue; + } + let angle = dy.atan2(dx); + let bin = (((angle + std::f64::consts::PI) / (2.0 * std::f64::consts::PI) * bins as f64) + as usize) + % bins; + profile[bin] += v; + } + profile +} + +fn median(v: &mut Vec) -> f64 { + if v.is_empty() { + return 0.0; + } + v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + let mid = v.len() / 2; + if v.len() % 2 == 0 { + (v[mid - 1] + v[mid]) / 2.0 + } else { + v[mid] + } +} + +fn wrap(v: f64, n: usize) -> f64 { + let n = n as f64; + let mut x = v % n; + if x > n / 2.0 { + x -= n; + } + if x < -n / 2.0 { + x += n; + } + x +} diff --git a/src/core/processor/frame_dedup.rs b/src/core/processor/frame_dedup.rs new file mode 100644 index 00000000..54735407 --- /dev/null +++ b/src/core/processor/frame_dedup.rs @@ -0,0 +1,156 @@ +//! Frame deduplication — perceptual hash (pHash) + time-gap based filtering. +//! +//! Used in two places: +//! - Scene frames: after 3-level sampling, drop near-duplicate frames. +//! - Face-trace key_frames: drop near-duplicate best_frames across a file +//! (never merge different trace_id — that would break identity tracking). + +use anyhow::{Context, Result}; +use image::{imageops::FilterType, GrayImage}; +use std::process::{Command, Stdio}; +use tracing::{debug, warn}; + +/// Compute a 64-bit perceptual hash (pHash) of a JPEG/PNG at `path`. +/// Resize to 32x32 grayscale, DCT, take the low 8x8 AC/DC coefficients. +pub fn phash_from_file(path: &std::path::Path) -> Result { + let img = image::open(path) + .with_context(|| format!("failed to open image {}", path.display()))? + .to_luma8(); + Ok(phash(&img)) +} + +/// Compute 64-bit pHash from an in-memory grayscale image. +pub fn phash(img: &GrayImage) -> u64 { + const N: usize = 32; + const LOW: usize = 8; + let small = image::imageops::resize(img, N as u32, N as u32, FilterType::Triangle); + + // Separable DCT-II. + let mut dct = vec![vec![0.0f64; N]; N]; + let c = |u: usize, x: usize| -> f64 { + if u == 0 { + (1.0 / (N as f64).sqrt()) / std::f64::consts::SQRT_2 + } else { + (2.0 * std::f64::consts::PI * u as f64 * x as f64 / (2.0 * N as f64)).cos() + } + }; + // Row pass. + let mut tmp = vec![vec![0.0f64; N]; N]; + for y in 0..N { + for u in 0..N { + let mut s = 0.0; + for x in 0..N { + s += small.get_pixel(x as u32, y as u32)[0] as f64 * c(u, x); + } + tmp[y][u] = s; + } + } + // Column pass. + for v in 0..N { + for u in 0..N { + let mut s = 0.0; + for y in 0..N { + s += tmp[y][u] * c(v, y); + } + dct[v][u] = s; + } + } + + // Use the low 8x8 block (including DC). Median of coefficients as threshold. + let mut vals = Vec::with_capacity(LOW * LOW); + for v in 0..LOW { + for u in 0..LOW { + vals.push(dct[v][u]); + } + } + let mut sorted = vals.clone(); + sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + let median = sorted[sorted.len() / 2]; + + let mut hash = 0u64; + for (i, v) in vals.iter().enumerate() { + if *v > median { + hash |= 1u64 << i; + } + } + hash +} + +/// Hamming distance between two pHashes. +pub fn hamming(a: u64, b: u64) -> u32 { + (a ^ b).count_ones() +} + +/// Extract a single frame via ffmpeg into memory and return its pHash. +pub async fn phash_from_video_frame( + video_path: &str, + frame: u32, + fps: f64, +) -> Result { + let time_sec = frame as f64 / fps; + let child = Command::new("/opt/homebrew/bin/ffmpeg") + .args([ + "-y", + "-v", + "quiet", + "-ss", + &format!("{:.3}", time_sec), + "-i", + video_path, + "-frames:v", + "1", + "-vf", + "scale=64:64", + "-f", + "image2pipe", + "-vcodec", + "png", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .context("ffmpeg spawn failed for phash extraction")?; + let out = child.wait_with_output().context("ffmpeg wait failed")?; + if out.stdout.is_empty() { + anyhow::bail!("ffmpeg produced no frame for phash at {:.2}s", time_sec); + } + let img = image::load_from_memory_with_format(&out.stdout, image::ImageFormat::Png) + .context("failed to decode png for phash")? + .to_luma8(); + Ok(phash(&img)) +} + +/// A generic item that can be time-ordered and hash-deduplicated. +#[derive(Debug, Clone)] +pub struct DedupItem { + pub key: String, + pub frame: u32, + pub hash: u64, +} + +/// Deduplicate items by (time gap AND pHash similarity). +/// Keeps the first item of each near-duplicate group (caller should order by +/// quality before calling if they want to keep the best instead). +/// Returns the kept items and the list of dropped keys. +pub fn dedup_items(items: Vec, hamming_threshold: u32, time_gap_frames: u32) -> (Vec, Vec) { + let mut kept: Vec = Vec::new(); + let mut dropped: Vec = Vec::new(); + for item in items { + let dup = kept.iter().any(|k| { + let close_time = item.frame.abs_diff(k.frame) <= time_gap_frames; + close_time && hamming(item.hash, k.hash) <= hamming_threshold + }); + if dup { + dropped.push(item.key.clone()); + debug!("[DEDUP] dropped {} (frame {}, near {})", item.key, item.frame, kept.last().map(|x| x.frame).unwrap_or(0)); + } else { + kept.push(item); + } + } + if !dropped.is_empty() { + warn!("[DEDUP] dropped {} near-duplicate frames", dropped.len()); + } + (kept, dropped) +} diff --git a/src/core/processor/mod.rs b/src/core/processor/mod.rs index 8573b840..27d23e04 100644 --- a/src/core/processor/mod.rs +++ b/src/core/processor/mod.rs @@ -18,6 +18,8 @@ pub mod ocr; pub mod pose; pub mod scene_classification; pub mod scene_vlm; +pub mod camera_motion; +pub mod frame_dedup; pub mod tkg; pub mod vlm_summary; diff --git a/src/core/processor/scene_vlm.rs b/src/core/processor/scene_vlm.rs index 50d77253..0f4aa0b1 100644 --- a/src/core/processor/scene_vlm.rs +++ b/src/core/processor/scene_vlm.rs @@ -1,13 +1,15 @@ use anyhow::{Context, Result}; use futures_util::future::join_all; +use tracing::{debug, info}; use std::collections::HashMap; use std::path::Path; use tokio::process::Command; use crate::core::file_profile::{ - EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus, - SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue, + CameraMotion, EmbeddingStatus, MotionLevel, SceneConfig, SceneFrame, SceneInfo, SceneProfile, + SceneStatus, SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue, }; +use crate::core::processor::camera_motion::{analyze_camera_motion, samples_for_level}; pub struct SceneVlmProcessor { samples_per_interval: usize, @@ -138,6 +140,11 @@ impl SceneVlmProcessor { cuts } + /// Three-tier frame sampling inside one moment (default 10s): + /// L0: moment baseline (blur-best of the whole segment) + /// L1: every distinct cut gets at least one frame (no upper bound) + /// L2: camera motion (pan/tilt/zoom/rotation) adds extra samples: + /// none -> 1, low -> 2, high -> 4, evenly along the motion path. pub async fn process_interval( video_path: &str, interval_start: f64, @@ -147,165 +154,169 @@ impl SceneVlmProcessor { samples_per_interval: usize, max_workers: usize, ) -> Result> { - let sample_frames = - Self::compute_sample_frames(interval_start, interval_sec, fps, samples_per_interval); + let moment_start_f = (interval_start * fps).round() as u32; + let moment_end_f = ((interval_start + interval_sec) * fps).round() as u32; + let cuts = Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data); - let blur_scores = - Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?; + // Build frame ranges: [moment_start, cut0), [cut0, cut1), ... [cutN, moment_end) + let mut cut_frames: Vec = cuts + .iter() + .filter_map(|c| c.get("start_time").and_then(|t| t.as_f64())) + .map(|t| (t * fps).round() as u32) + .filter(|f| *f > moment_start_f && *f < moment_end_f) + .collect(); + cut_frames.sort_unstable(); + cut_frames.dedup(); - let cuts = - Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data); - - let mut selected_frames = Vec::new(); - - if cuts.is_empty() { - if let Some((frame, blur)) = Self::select_best_frame(&blur_scores) { - let timestamp = frame as f64 / fps; - - selected_frames.push(SceneFrame { - index: 0, - filename: format!("scene_{:03}.jpg", 0), - timestamp_sec: timestamp, - frame_number: frame, - selection_reason: SelectionReason::BestBlur, - quality_score: Some(blur), - quality_source: Some("ffmpeg_blurdetect".to_string()), - scene_info: None, - face_count: 0, - person_traces: Vec::new(), - has_cut: false, - cut_count: 0, - vlm_status: VlmStatus::Pending, - vlm_description: None, - vlm_description_localized: None, - vlm_scene_type: None, - vlm_location: None, - vlm_objects: Vec::new(), - vlm_attributes: None, - vlm_tags: Vec::new(), - embedding_status: EmbeddingStatus::Pending, - }); - } else if let Some(&frame) = sample_frames.first() { - // Fallback: use first sample frame when blur detection yields no scores - let timestamp = frame as f64 / fps; - selected_frames.push(SceneFrame { - index: 0, - filename: format!("scene_{:03}.jpg", 0), - timestamp_sec: timestamp, - frame_number: frame, - selection_reason: SelectionReason::Default, - quality_score: None, - quality_source: None, - scene_info: None, - face_count: 0, - person_traces: Vec::new(), - has_cut: false, - cut_count: 0, - vlm_status: VlmStatus::Pending, - vlm_description: None, - vlm_description_localized: None, - vlm_scene_type: None, - vlm_location: None, - vlm_objects: Vec::new(), - vlm_attributes: None, - vlm_tags: Vec::new(), - embedding_status: EmbeddingStatus::Pending, - }); - } - } else { - let cut = &cuts[0]; - let cut_time = cut - .get("start_time") - .and_then(|t| t.as_f64()) - .unwrap_or(interval_start); - let cut_frame = (cut_time * fps).round() as u32; - - let pre_frames: Vec = sample_frames - .iter() - .filter(|f| **f < cut_frame) - .cloned() - .collect(); - - let post_frames: Vec = sample_frames - .iter() - .filter(|f| **f >= cut_frame) - .cloned() - .collect(); - - if !pre_frames.is_empty() { - let pre_blur = - Self::calculate_blur_parallel(video_path, &pre_frames, fps, max_workers) - .await?; - - if let Some((frame, blur)) = Self::select_best_frame(&pre_blur) { - let timestamp = frame as f64 / fps; - - selected_frames.push(SceneFrame { - index: 0, - filename: format!("scene_{:03}.jpg", selected_frames.len()), - timestamp_sec: timestamp, - frame_number: frame, - selection_reason: SelectionReason::PreCutBestBlur, - quality_score: Some(blur), - quality_source: Some("ffmpeg_blurdetect".to_string()), - scene_info: None, - face_count: 0, - person_traces: Vec::new(), - has_cut: true, - cut_count: cuts.len() as u32, - vlm_status: VlmStatus::Pending, - vlm_description: None, - vlm_description_localized: None, - vlm_scene_type: None, - vlm_location: None, - vlm_objects: Vec::new(), - vlm_attributes: None, - vlm_tags: Vec::new(), - embedding_status: EmbeddingStatus::Pending, - }); - } - } - - if !post_frames.is_empty() { - let post_blur = - Self::calculate_blur_parallel(video_path, &post_frames, fps, max_workers) - .await?; - - if let Some((frame, blur)) = Self::select_best_frame(&post_blur) { - let timestamp = frame as f64 / fps; - - selected_frames.push(SceneFrame { - index: 0, - filename: format!("scene_{:03}.jpg", selected_frames.len()), - timestamp_sec: timestamp, - frame_number: frame, - selection_reason: SelectionReason::PostCutBestBlur, - quality_score: Some(blur), - quality_source: Some("ffmpeg_blurdetect".to_string()), - scene_info: None, - face_count: 0, - person_traces: Vec::new(), - has_cut: true, - cut_count: cuts.len() as u32, - vlm_status: VlmStatus::Pending, - vlm_description: None, - vlm_description_localized: None, - vlm_scene_type: None, - vlm_location: None, - vlm_objects: Vec::new(), - vlm_attributes: None, - vlm_tags: Vec::new(), - embedding_status: EmbeddingStatus::Pending, - }); - } + let mut ranges: Vec<(u32, u32, bool)> = Vec::new(); // (start, end, has_cut) + let mut prev = moment_start_f; + for &cf in cut_frames.iter() { + if cf > prev { + ranges.push((prev, cf, false)); } + ranges.push((cf, cf, true)); // cut boundary marker + prev = cf; + } + if moment_end_f > prev { + ranges.push((prev, moment_end_f, false)); + } + // If no cuts, single range. + if ranges.is_empty() { + ranges.push((moment_start_f, moment_end_f, false)); } - for (i, frame) in selected_frames.iter_mut().enumerate() { + let motion_enabled = *crate::core::config::CAMERA_MOTION_ENABLED; + let k = *crate::core::config::CAMERA_MOTION_K; + let mut selected: Vec = Vec::new(); + + for (range_idx, (rs, re, is_cut)) in ranges.iter().enumerate() { + if *is_cut { + // Cut boundary: one frame at the cut itself (L1 baseline). + let frame = *rs; + if let Some(sf) = Self::make_frame( + selected.len(), + frame, + fps, + SelectionReason::CutBaseline, + None, + None, + true, + 1, + ) { + selected.push(sf); + } + continue; + } + + let seg_start = *rs; + let seg_end = (*re).max(seg_start + 1); + + // L2: camera-motion analysis on this sub-segment. + let motion: Option = if motion_enabled && seg_end > seg_start { + match analyze_camera_motion(video_path, seg_start, seg_end, fps, k).await { + Ok(m) if m.level != MotionLevel::None => Some(m), + Ok(m) => Some(m), + Err(e) => { + debug!("[CAM-MOTION] analysis failed for {}-{}: {}", seg_start, seg_end, e); + None + } + } + } else { + None + }; + + let count = motion + .as_ref() + .map(|m| samples_for_level(m.level)) + .unwrap_or(1); + + // Sample `count` frames evenly inside [seg_start, seg_end), each + // chosen as the blur-best within its own sub-window. + let window = (seg_end - seg_start) / count as u32; + for i in 0..count { + let ws = seg_start + window * i as u32; + let we = if i + 1 == count { seg_end } else { (ws + window).min(seg_end) }; + // Sparse sample inside the sub-window (max 6 candidates) to avoid + // one ffmpeg call per frame on high-fps video. + let span = we.max(ws + 1) - ws; + let step = (span / 6).max(1); + let candidates: Vec = (ws..we.max(ws + 1)).step_by(step as usize).collect(); + let blur = Self::calculate_blur_parallel(video_path, &candidates, fps, max_workers).await?; + let chosen = Self::select_best_frame(&blur) + .map(|(f, b)| (f, Some(b))) + .or_else(|| candidates.first().map(|f| (*f, None))); + if let Some((frame, blur_score)) = chosen { + let reason = if count == 1 { + SelectionReason::BestBlur + } else if i == 0 { + SelectionReason::CameraMotionStart + } else if i + 1 == count { + SelectionReason::CameraMotionEnd + } else { + SelectionReason::CameraMotionMid + }; + if let Some(sf) = Self::make_frame( + selected.len(), + frame, + fps, + reason, + blur_score, + motion.clone(), + false, + cut_frames.len() as u32, + ) { + selected.push(sf); + } + } + } + let _ = range_idx; + } + + // Time-gap dedup: drop frames too close in time AND visually near-identical + // is done later on extracted jpg (pHash). Here we only drop exact same frame. + selected.dedup_by(|a, b| a.frame_number == b.frame_number); + + for (i, frame) in selected.iter_mut().enumerate() { frame.index = i; } - Ok(selected_frames) + Ok(selected) + } + + fn make_frame( + index: usize, + frame: u32, + fps: f64, + reason: SelectionReason, + blur: Option, + camera_motion: Option, + has_cut: bool, + cut_count: u32, + ) -> Option { + Some(SceneFrame { + index, + filename: format!("scene_{:03}.jpg", index), + timestamp_sec: frame as f64 / fps, + frame_number: frame, + selection_reason: reason, + quality_score: blur, + quality_source: if blur.is_some() { Some("ffmpeg_blurdetect".to_string()) } else { None }, + scene_info: None, + face_count: 0, + person_traces: Vec::new(), + has_cut, + cut_count, + vlm_status: VlmStatus::Pending, + vlm_description: None, + vlm_description_localized: None, + vlm_scene_type: None, + vlm_location: None, + vlm_objects: Vec::new(), + vlm_attributes: None, + vlm_tags: Vec::new(), + embedding_status: EmbeddingStatus::Pending, + camera_motion, + }) } pub async fn generate_scene_profile( @@ -321,6 +332,10 @@ impl SceneVlmProcessor { height: u32, total_frames: u32, ) -> Result { + // moment length is configurable (default 10s); SCENE_VLM_INTERVAL is + // the legacy alias — prefer MOMENTRY_SCENE_VLM_MOMENT_SEC when set. + let moment_sec = *crate::core::config::SCENE_VLM_MOMENT_SEC; + let interval_sec = if moment_sec > 0 { moment_sec } else { interval_sec }; let config = SceneConfig { interval_sec, use_cuts: true, @@ -600,6 +615,37 @@ Rules: Some(&content[start..=end]) } + /// Pull a `"summary": "..."` string out of a possibly-truncated JSON blob. + fn salvage_summary(content: &str) -> Option { + let key = content.find("\"summary\"")?; + let colon = content[key..].find(':')? + key; + let mut rest = &content[colon + 1..]; + rest = rest.trim_start(); + if !rest.starts_with('"') { + return None; + } + rest = &rest[1..]; + let mut out = String::new(); + let mut esc = false; + for ch in rest.chars() { + if esc { + out.push(ch); + esc = false; + continue; + } + if ch == '\\' { + esc = true; + continue; + } + if ch == '"' { + break; + } + out.push(ch); + } + let out = out.trim().to_string(); + if out.len() >= 10 { Some(out) } else { None } + } + fn parse_tags(value: Option<&serde_json::Value>) -> Vec { let Some(arr) = value.and_then(|v| v.as_array()) else { return Vec::new(); @@ -756,8 +802,9 @@ Rules: .get("choices") .and_then(|c| c.get(0)) .context("Invalid VLM API response structure")?; - if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") { - anyhow::bail!("VLM returned truncated response (finish_reason=length)"); + let truncated = choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length"); + if truncated { + debug!("[Scene VLM] response truncated (finish_reason=length) — attempting to salvage partial JSON"); } let message = choice.get("message").context("Invalid VLM API response structure")?; @@ -827,6 +874,17 @@ Rules: tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response"); } + // Salvage path for truncated responses: pull the "summary" string even + // when the surrounding JSON object was cut off mid-generation. + if let Some(desc) = Self::salvage_summary(&content) { + let objects = Self::extract_objects_from_text(&content); + let tags: Vec = Self::extract_tags_from_text(&content) + .into_iter() + .map(VlmTagValue::String) + .collect(); + return Ok((desc, objects, tags)); + } + tracing::warn!( "[Scene VLM] Failed to parse structured JSON, falling back to text heuristics" ); diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 95725eb1..c3ed2f07 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -4520,7 +4520,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { // Before running dedup, verify all 4 required files exist per trace: // key_frame.jpg, key_face.jpg, trace_profile.json, face_traced.json if has_face { - let output_dir = OUTPUT_DIR.as_str(); + let per_lib = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await; + let output_dir = if std::path::Path::new(&per_lib).is_dir() { + per_lib.as_str() + } else { + OUTPUT_DIR.as_str() + }; let output_base = output_dir.trim_end_matches('/'); let traced_path = format!("{}/{}.face_traced.json", output_base, uuid); @@ -5686,10 +5691,56 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { carried_over, uuid, force_scene_vlm ); - let extracted = + let mut extracted = SceneVlmProcessor::extract_scene_frames(&video_path, output_dir, uuid, &profile.scenes) .await?; + // Second-pass dedup: pHash + time-gap over the extracted jpgs. + // Drop a scene when it is visually near-identical to a previously kept + // one within the time-gap window. Resume-carried scenes are kept as-is. + { + use crate::core::processor::frame_dedup::{dedup_items, phash_from_file, DedupItem}; + let hamming_threshold = *crate::core::config::PHASH_HAMMING_THRESHOLD; + let time_gap = *crate::core::config::SCENE_TIME_GAP_FRAMES; + let mut items = Vec::new(); + for (i, path) in extracted.iter().enumerate() { + if i >= profile.scenes.len() { + break; + } + let hash = phash_from_file(path).unwrap_or(0); + items.push(DedupItem { + key: format!("{}", i), + frame: profile.scenes[i].frame_number, + hash, + }); + } + let (kept, dropped) = dedup_items(items, hamming_threshold, time_gap); + if !dropped.is_empty() { + let keep_set: std::collections::HashSet = kept + .iter() + .filter_map(|k| k.key.parse::().ok()) + .collect(); + let old_scenes = std::mem::take(&mut profile.scenes); + let old_extracted = extracted.clone(); + let mut new_scenes = Vec::new(); + let mut new_extracted = Vec::new(); + for (i, (scene, path)) in old_scenes.into_iter().zip(old_extracted.into_iter()).enumerate() { + if keep_set.contains(&i) { + new_scenes.push(scene); + new_extracted.push(path); + } + } + profile.scenes = new_scenes; + profile.total_scenes = profile.scenes.len(); + extracted = new_extracted; + info!( + "[Scene VLM] pHash dedup removed {} near-duplicate scenes ({} remain)", + dropped.len(), + profile.scenes.len() + ); + } + } + info!( "[Scene VLM] Extracted {}/{} frames", extracted.len(),