From 59ca6cdf8361c1685864282e4591cfda5248379d Mon Sep 17 00:00:00 2001 From: Accusys Date: Wed, 12 Aug 2026 03:04:19 +0800 Subject: [PATCH] feat: add regenerate trace thumbnail endpoint with bbox clamping - validator::clamp_crop: clamp crop rect to frame dims (fixes OOB shift) - tkg.rs: use clamp_crop in key_face crop paths (root-cause fix) - trace_agent_api: POST /api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail - docs: 26_trace_thumbnail_regenerate.md for Studio team --- .../modules/26_trace_thumbnail_regenerate.md | 114 +++++++++++ .../26_trace_thumbnail_regenerate.html | 136 +++++++++++++ src/api/trace_agent_api.rs | 190 ++++++++++++++++++ src/core/processor/tkg.rs | 74 ++++--- src/core/thumbnail/validator.rs | 64 ++++++ 5 files changed, 553 insertions(+), 25 deletions(-) create mode 100644 docs_v1.0/API_WORKSPACE/modules/26_trace_thumbnail_regenerate.md create mode 100644 docs_v1.0/doc_developer/26_trace_thumbnail_regenerate.html diff --git a/docs_v1.0/API_WORKSPACE/modules/26_trace_thumbnail_regenerate.md b/docs_v1.0/API_WORKSPACE/modules/26_trace_thumbnail_regenerate.md new file mode 100644 index 00000000..273892db --- /dev/null +++ b/docs_v1.0/API_WORKSPACE/modules/26_trace_thumbnail_regenerate.md @@ -0,0 +1,114 @@ +# Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考 + +**版本**: v1.0 +**日期**: 2026-08-12 +**狀態**: 已實作(Core) + +--- + +## 概述 + +修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。 + +**根因**: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 `key_face.jpg` cache,異常內容被持久化顯示。 + +**修復**: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 `key_face.jpg`,並同步更新 `.faces` cache。 + +--- + +## API 端點 + +### POST `/api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail` + +**功能**: 重新產生單一 trace 的 face thumbnail(覆寫 cache) +**Auth**: Required +**Body**: 可為空。 + +**Response 200**: +```json +{ + "success": true, + "file_uuid": "...", + "trace_id": 355, + "frame": 1835, + "bbox": { "x": 65, "y": 301, "width": 70, "height": 59 } +} +``` +- `frame` / `bbox` 為重新裁切使用的(clamp 後)frame 與 bbox。 + +**Error Responses**: +| Status | 說明 | +|--------|------| +| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) | +| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 | + +--- + +## 行為說明 + +1. 讀取該 trace 最高 confidence 的 frame + bbox(**不**重跑 blur 優化,取既有 best face 復原同一區域) +2. 將 bbox clamp 到影片 width/height 內(`clamp_crop`) +3. ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域 +4. 覆寫 `{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg` +5. 若 `.faces/{file_uuid}/{trace_id}/{frame}.jpg` 已存在則同步覆寫 + +**不影響**: Qdrant、`trace_profiles` DB、`tkg_nodes`、影片檔 — 僅重寫縮圖 cache。 + +--- + +## Studio 整合步驟 + +### 1. apiCall (`src/api/index.ts`) + +新增 case: +```ts +case 'regenerate_trace_thumbnail': { + return { url: `/api/v1/file/${a.fileUuid}/trace/${a.traceId}/regenerate-thumbnail`, method: 'POST' } +} +``` + +### 2. Face detail modal 加「Re-gen」按鈕 (`src/views/PeopleView.vue`) + +於 `ms-face-detail-thumb` 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。 + +### 3. 觸發後 refresh(重要) + +Face detail 縮圖顯示的是 `faceThumbsCache`(key = `${file_uuid}-${trace_id}`)。`loadTraceThumb` 對已有 cache 的 key 會直接 return,**單獨 `bumpThumbCacheBust()` 無法刷新 face detail 縮圖**。正確順序: + +```ts +await apiCall('regenerate_trace_thumbnail', { fileUuid, traceId }) // 1. 呼叫 regenerate +delete faceThumbsCache.value[`${fileUuid}-${traceId}`] // 2. 清除該 key 的 blob cache +bumpThumbCacheBust() // 3. bump 版本(避 HTTP cache) +loadTraceThumb({ file_uuid: fileUuid, trace_id: traceId }) // 4. 重新載入縮圖 +``` + +> `candidateThumbs` 即 `faceThumbsCache` 的 alias(PeopleView.vue:722),delete 後無需額外處理。 +> 若想一次清空全部縮圖可用 `clearFaceThumbs()`(較重,不建議單一 trace 場景)。 + +--- + +## 測試指示 + +```bash +# 使用已知越界案例(trace 355b 一類)驗證: +# 1) regenerate 前:GET thumbnail 顯示位移內容 +# 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox +# 3) 再次 GET thumbnail → 內容正確對齊 bbox +curl -X POST "http://localhost:3002/api/v1/file//trace//regenerate-thumbnail" \ + -H "X-API-Key: " +``` + +--- + +## 參考 + +- 根因 crop 修正:`src/core/thumbnail/validator.rs::clamp_crop`、`src/core/processor/tkg.rs` +- 端點 handler:`src/api/trace_agent_api.rs::regenerate_trace_thumbnail` + +--- + +## 版本歷史 + +| 版本 | 日期 | 變更 | +|------|------|------| +| v1.0 | 2026-08-12 | 初版 | \ No newline at end of file diff --git a/docs_v1.0/doc_developer/26_trace_thumbnail_regenerate.html b/docs_v1.0/doc_developer/26_trace_thumbnail_regenerate.html new file mode 100644 index 00000000..1d981869 --- /dev/null +++ b/docs_v1.0/doc_developer/26_trace_thumbnail_regenerate.html @@ -0,0 +1,136 @@ + + + + +26 Trace Thumbnail Regenerate - Momentry API Docs + + + +
+ +

Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考

+

版本: v1.0 +日期: 2026-08-12 +狀態: 已實作(Core)

+
+

概述

+

修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。

+

根因: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 key_face.jpg cache,異常內容被持久化顯示。

+

修復: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 key_face.jpg,並同步更新 .faces cache。

+
+

API 端點

+

POST /api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail

+

功能: 重新產生單一 trace 的 face thumbnail(覆寫 cache) +Auth: Required +Body: 可為空。

+

Response 200:

+
{
+  "success": true,
+  "file_uuid": "...",
+  "trace_id": 355,
+  "frame": 1835,
+  "bbox": { "x": 65, "y": 301, "width": 70, "height": 59 }
+}
+
+ +
    +
  • frame / bbox 為重新裁切使用的(clamp 後)frame 與 bbox。
  • +
+

Error Responses: +| Status | 說明 | +|--------|------| +| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) | +| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 |

+
+

行為說明

+
    +
  1. 讀取該 trace 最高 confidence 的 frame + bbox(不重跑 blur 優化,取既有 best face 復原同一區域)
  2. +
  3. 將 bbox clamp 到影片 width/height 內(clamp_crop)
  4. +
  5. ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域
  6. +
  7. 覆寫 {OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg
  8. +
  9. 若 .faces/{file_uuid}/{trace_id}/{frame}.jpg 已存在則同步覆寫
  10. +
+

不影響: Qdrant、trace_profiles DB、tkg_nodes、影片檔 — 僅重寫縮圖 cache。

+
+

Studio 整合步驟

+

1. apiCall (src/api/index.ts)

+

新增 case:

+
case 'regenerate_trace_thumbnail': {
+  return { url: `/api/v1/file/${a.fileUuid}/trace/${a.traceId}/regenerate-thumbnail`, method: 'POST' }
+}
+
+ +

2. Face detail modal 加「Re-gen」按鈕 (src/views/PeopleView.vue)

+

於 ms-face-detail-thumb 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。

+

3. 觸發後 refresh(重要)

+

Face detail 縮圖顯示的是 faceThumbsCache(key = ${file_uuid}-${trace_id})。loadTraceThumb 對已有 cache 的 key 會直接 return,單獨 bumpThumbCacheBust() 無法刷新 face detail 縮圖。正確順序:

+
await apiCall('regenerate_trace_thumbnail', { fileUuid, traceId })   // 1. 呼叫 regenerate
+delete faceThumbsCache.value[`${fileUuid}-${traceId}`]                // 2. 清除該 key 的 blob cache
+bumpThumbCacheBust()                                                  // 3. bump 版本(避 HTTP cache)
+loadTraceThumb({ file_uuid: fileUuid, trace_id: traceId })            // 4. 重新載入縮圖
+
+ +
+

candidateThumbs 即 faceThumbsCache 的 alias(PeopleView.vue:722),delete 後無需額外處理。 +若想一次清空全部縮圖可用 clearFaceThumbs()(較重,不建議單一 trace 場景)。

+
+
+

測試指示

+
# 使用已知越界案例(trace 355b 一類)驗證:
+# 1) regenerate 前:GET thumbnail 顯示位移內容
+# 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox
+# 3) 再次 GET thumbnail → 內容正確對齊 bbox
+curl -X POST "http://localhost:3002/api/v1/file/<FILE_UUID>/trace/<TRACE_ID>/regenerate-thumbnail" \
+  -H "X-API-Key: <KEY>"
+
+ +
+

參考

+
    +
  • 根因 crop 修正:src/core/thumbnail/validator.rs::clamp_crop、src/core/processor/tkg.rs
  • +
  • 端點 handler:src/api/trace_agent_api.rs::regenerate_trace_thumbnail
  • +
+
+

版本歷史

+ + + + + + + + + + + + + + + +
版本日期變更
v1.02026-08-12初版
+
+ + \ No newline at end of file diff --git a/src/api/trace_agent_api.rs b/src/api/trace_agent_api.rs index 981bed10..8f6e9b6e 100644 --- a/src/api/trace_agent_api.rs +++ b/src/api/trace_agent_api.rs @@ -65,6 +65,10 @@ pub fn trace_agent_routes() -> Router { "/api/v1/file/:file_uuid/trace/:trace_id/merge/:target_trace_id", post(merge_trace), ) + .route( + "/api/v1/file/:file_uuid/trace/:trace_id/regenerate-thumbnail", + post(regenerate_trace_thumbnail), + ) } #[derive(Debug, Deserialize)] @@ -864,6 +868,192 @@ async fn get_trace_thumbnail_inner( .unwrap()) } +// Regenerate a trace's key_face.jpg by re-cropping the best-confidence face +// from the video with the bbox clamped to the frame dimensions. Fixes the +// "key frame OK, bbox OK, but key_face broken" case where an out-of-bounds +// bbox made ffmpeg silently shift the crop. +async fn regenerate_trace_thumbnail( + State(state): State, + Path((file_uuid, trace_id)): Path<(String, i32)>, +) -> Result, (StatusCode, Json)> { + use serde_json::json; + let videos_table = crate::core::db::schema::table_name("videos"); + + // Query video info: path, dimensions, fps + let row: Option<(String, Option, Option, Option)> = sqlx::query_as(&format!( + "SELECT file_path, width, height, fps FROM {} WHERE file_uuid = $1", + videos_table + )) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + ) + })?; + + let (video_path, video_width, video_height, fps) = row.ok_or_else(|| { + ( + StatusCode::NOT_FOUND, + Json(json!({"error": "Video not found"})), + ) + })?; + + let video_width = video_width.ok_or_else(|| { + ( + StatusCode::BAD_REQUEST, + Json(json!({"error": "Video width unavailable, cannot clamp crop"})), + ) + })?; + let video_height = video_height.ok_or_else(|| { + ( + StatusCode::BAD_REQUEST, + Json(json!({"error": "Video height unavailable, cannot clamp crop"})), + ) + })?; + let fps = fps.unwrap_or(25.0); + + // Scroll Qdrant _faces for this trace and pick the highest-confidence face. + // Unlike select_rep_face, no blur-optimization happens: we reuse the + // existing best-confidence frame + bbox to restore the same region. + use crate::core::db::qdrant_db::QdrantDb; + let qdrant = QdrantDb::new(); + let trace_filter = json!({ + "must": [ + {"key": "file_uuid", "match": {"value": file_uuid}}, + {"key": "trace_id", "match": {"value": trace_id}} + ] + }); + let points = qdrant + .scroll_all_points("_faces", trace_filter, 1000) + .await + .unwrap_or_default(); + + let best = points + .iter() + .filter_map(|p| { + let payload = &p["payload"]; + let bbox = &payload["bbox"]; + let w = bbox["width"].as_f64()? as i32; + let h = bbox["height"].as_f64()? as i32; + let conf = payload["confidence"].as_f64()?; + Some(( + payload["frame"].as_i64().unwrap_or(0), + bbox["x"].as_f64()? as i32, + bbox["y"].as_f64()? as i32, + w, + h, + conf, + )) + }) + .max_by(|a, b| a.5.partial_cmp(&b.5).unwrap_or(std::cmp::Ordering::Equal)); + + let (best_frame, bx, by, bw, bh, _conf) = best.ok_or_else(|| { + ( + StatusCode::NOT_FOUND, + Json(json!({"error": "No face found for this trace"})), + ) + })?; + + // Clamp bbox to frame dimensions + let (cx, cy, cw, ch) = + crate::core::thumbnail::validator::clamp_crop(bx, by, bw, bh, video_width, video_height); + + tracing::info!( + "[regenerate-thumbnail] trace {} frame {} bbox {}x{} at ({},{})", + trace_id, + best_frame, + cw, + ch, + cx, + cy + ); + + // Crop the face region from the video using decoded frame index (VFR-safe) + let tmp = std::env::temp_dir().join(format!("regen_trace_{}_{}.jpg", file_uuid, trace_id)); + let select = format!("select=eq(n\\,{})", best_frame); + let status = tokio::process::Command::new("ffmpeg") + .args([ + "-y", + "-i", + &video_path, + "-vf", + &format!("{},crop={}:{}:{}:{}", select, cw, ch, cx, cy), + "-frames:v", + "1", + "-q:v", + "2", + &tmp.to_string_lossy().to_string(), + ]) + .output() + .await + .map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + ) + })?; + + if !status.status.success() { + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": "FFmpeg failed during regeneration"})), + )); + } + + let bytes = tokio::fs::read(&tmp).await.map_err(|e| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + ) + })?; + + crate::core::thumbnail::validator::validate_jpeg(&bytes).map_err(|e| { + tracing::warn!("[regenerate-thumbnail] JPEG validation failed: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": "Invalid JPEG output"})), + ) + })?; + + let _ = tokio::fs::remove_file(&tmp).await; + + // Overwrite key_face.jpg in the trace profile directory + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let profile_dir = std::path::PathBuf::from(output_dir) + .join(&file_uuid) + .join(format!("trace_{}", trace_id)); + if let Err(e) = tokio::fs::create_dir_all(&profile_dir).await { + tracing::warn!("[regenerate-thumbnail] Failed to create trace dir: {}", e); + } + let _ = tokio::fs::write(profile_dir.join("key_face.jpg"), &bytes).await; + + // Sync .faces cache if the cached crop file exists for the best frame + let trace_dir_name = if trace_id == 0 { + "unbound".to_string() + } else { + trace_id.to_string() + }; + let faces_cached = std::path::PathBuf::from(output_dir) + .join(".faces") + .join(&file_uuid) + .join(trace_dir_name) + .join(format!("{}.jpg", best_frame)); + if faces_cached.exists() { + let _ = tokio::fs::write(&faces_cached, &bytes).await; + } + + Ok(Json(json!({ + "success": true, + "file_uuid": file_uuid, + "trace_id": trace_id, + "frame": best_frame, + "bbox": {"x": cx, "y": cy, "width": cw, "height": ch}, + }))) +} + #[derive(Debug, Serialize)] struct CoOccurIdentity { identity_uuid: String, diff --git a/src/core/processor/tkg.rs b/src/core/processor/tkg.rs index 47481469..4562e556 100644 --- a/src/core/processor/tkg.rs +++ b/src/core/processor/tkg.rs @@ -1245,6 +1245,19 @@ async fn build_face_track_nodes_from_qdrant( .ok() .flatten(); + // Get video frame dimensions for bbox clamping when cropping key_face + let video_dim: Option<(Option, Option)> = sqlx::query_as(&format!( + "SELECT width, height FROM {} WHERE file_uuid = $1", + crate::core::db::schema::table_name("videos") + )) + .bind(file_uuid) + .fetch_optional(pool) + .await + .ok() + .flatten(); + let video_width = video_dim.and_then(|d| d.0).unwrap_or(0); + let video_height = video_dim.and_then(|d| d.1).unwrap_or(0); + // Get actual fps for timestamp calculation let actual_fps: f64 = sqlx::query_scalar(&format!( "SELECT fps FROM {} WHERE file_uuid = $1", @@ -1272,12 +1285,7 @@ async fn build_face_track_nodes_from_qdrant( let key_frame_jpeg: Option> = video_path.as_ref().and_then(|vp| { let select = format!("select=eq(n\\,{})", agg.best_frame); let output = std::process::Command::new("ffmpeg") - .args([ - "-y", - "-v", - "quiet", - "-i", - ]) + .args(["-y", "-v", "quiet", "-i"]) .arg(vp) .args([ "-vf", @@ -1325,13 +1333,15 @@ async fn build_face_track_nodes_from_qdrant( return None; } - let crop_filter = format!( - "crop={}:{}:{}:{}", - (bw as i64).max(1), - (bh as i64).max(1), - (bx as i64).max(0), - (by as i64).max(0), + let (cx, cy, cw, ch) = crate::core::thumbnail::validator::clamp_crop( + bx as i32, + by as i32, + bw as i32, + bh as i32, + video_width, + video_height, ); + let crop_filter = format!("crop={}:{}:{}:{}", cw, ch, cx, cy); let mut cmd = std::process::Command::new("ffmpeg"); cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"]) .args(["-frames:v", "1", "-q:v", "2", "-vf"]) @@ -1410,13 +1420,7 @@ async fn build_face_track_nodes_from_qdrant( // Retry key_frame extraction if !kf_path.exists() { if let Ok(output) = std::process::Command::new("ffmpeg") - .args([ - "-y", - "-v", - "quiet", - "-i", - vp, - ]) + .args(["-y", "-v", "quiet", "-i", vp]) .args([ "-vf", &select, @@ -1464,13 +1468,15 @@ async fn build_face_track_nodes_from_qdrant( bh ); } else { - let crop_filter = format!( - "crop={}:{}:{}:{}", - (bw as i64).max(1), - (bh as i64).max(1), - (bx as i64).max(0), - (by as i64).max(0), + let (cx, cy, cw, ch) = crate::core::thumbnail::validator::clamp_crop( + bx as i32, + by as i32, + bw as i32, + bh as i32, + video_width, + video_height, ); + let crop_filter = format!("crop={}:{}:{}:{}", cw, ch, cx, cy); if let Ok(kf_bytes) = std::fs::read(&kf_path) { let mut cmd = std::process::Command::new("ffmpeg"); cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"]) @@ -3594,6 +3600,8 @@ mod tests { y: 100.0, w: 50.0, h: 50.0, + confidence: 0.9, + point_id: None, }, FacePoint { trace_id: 1, @@ -3602,6 +3610,8 @@ mod tests { y: 200.0, w: 50.0, h: 50.0, + confidence: 0.9, + point_id: None, }, FacePoint { trace_id: 2, @@ -3610,6 +3620,8 @@ mod tests { y: 150.0, w: 50.0, h: 50.0, + confidence: 0.9, + point_id: None, }, FacePoint { trace_id: 1, @@ -3618,6 +3630,8 @@ mod tests { y: 120.0, w: 50.0, h: 50.0, + confidence: 0.9, + point_id: None, }, ]; @@ -3646,6 +3660,8 @@ mod tests { y: 100.0, w: 100.0, h: 100.0, + confidence: 0.9, + point_id: None, }, FacePoint { trace_id: 2, @@ -3654,6 +3670,8 @@ mod tests { y: 300.0, w: 100.0, h: 100.0, + confidence: 0.9, + point_id: None, }, ]; let index = build_frame_index(&points); @@ -3673,6 +3691,8 @@ mod tests { y: 100.0, w: 100.0, h: 100.0, + confidence: 0.9, + point_id: None, }, FacePoint { trace_id: 2, @@ -3681,6 +3701,8 @@ mod tests { y: 500.0, w: 100.0, h: 100.0, + confidence: 0.9, + point_id: None, }, ]; let index = build_frame_index(&points); @@ -3699,6 +3721,8 @@ mod tests { y: 100.0, w: 100.0, h: 100.0, + confidence: 0.9, + point_id: None, }]; let index = build_frame_index(&points); diff --git a/src/core/thumbnail/validator.rs b/src/core/thumbnail/validator.rs index 456104f7..2b646da6 100644 --- a/src/core/thumbnail/validator.rs +++ b/src/core/thumbnail/validator.rs @@ -91,6 +91,31 @@ pub fn validate_crop( Ok(()) } +/// Clamp a crop rectangle so it fully fits inside the frame dimensions. +/// +/// `x`/`y` are clamped into `[0, frame_size)`, and `w`/`h` are reduced so the +/// rectangle never extends past the frame boundary. The result always has +/// positive dimensions. Out-of-bounds bboxes that previously made ffmpeg +/// silently shift the crop (root cause of the "key frame OK, key face broken" +/// bug) now produce a correctly-aligned crop. +pub fn clamp_crop( + x: i32, + y: i32, + w: i32, + h: i32, + video_width: i32, + video_height: i32, +) -> (i32, i32, i32, i32) { + if video_width <= 0 || video_height <= 0 { + return (x.max(0), y.max(0), w.max(1), h.max(1)); + } + let cx = x.clamp(0, video_width - 1); + let cy = y.clamp(0, video_height - 1); + let cw = w.clamp(1, (video_width - cx).max(1)); + let ch = h.clamp(1, (video_height - cy).max(1)); + (cx, cy, cw, ch) +} + #[cfg(test)] mod tests { use super::*; @@ -167,6 +192,45 @@ mod tests { assert!(validate_crop(100, -1, 200, 200, 1920, 1080).is_err()); } + #[test] + fn test_clamp_crop_in_bounds_unchanged() { + assert_eq!( + clamp_crop(100, 100, 200, 200, 1920, 1080), + (100, 100, 200, 200) + ); + assert_eq!(clamp_crop(0, 0, 1920, 1080, 1920, 1080), (0, 0, 1920, 1080)); + } + + #[test] + fn test_clamp_crop_exceeds_right_bottom() { + // Regression for trace 355b: bbox 11px past the frame edge used to + // make ffmpeg silently shift the crop content. + assert_eq!(clamp_crop(65, 301, 70, 70, 1280, 360), (65, 301, 70, 59)); + assert_eq!( + clamp_crop(1800, 900, 200, 200, 1920, 1080), + (1800, 900, 120, 180) + ); + } + + #[test] + fn test_clamp_crop_negative_origin() { + assert_eq!(clamp_crop(-10, -20, 200, 100, 1920, 1080), (0, 0, 200, 100)); + } + + #[test] + fn test_clamp_crop_fully_outside() { + assert_eq!( + clamp_crop(3000, 3000, 50, 50, 1920, 1080), + (1919, 1079, 1, 1) + ); + } + + #[test] + fn test_clamp_crop_zero_frame_dimensions() { + // Unknown frame size: fall back to legacy max(0)/max(1) behavior. + assert_eq!(clamp_crop(-10, -20, 0, 0, 0, 0), (0, 0, 1, 1)); + } + #[test] fn test_is_valid_jpeg() { let valid_jpeg = vec![