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
This commit is contained in:
@@ -65,6 +65,10 @@ pub fn trace_agent_routes() -> Router<crate::api::types::AppState> {
|
||||
"/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<crate::api::types::AppState>,
|
||||
Path((file_uuid, trace_id)): Path<(String, i32)>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
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<i32>, Option<i32>, Option<f64>)> = 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,
|
||||
|
||||
+49
-25
@@ -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<i32>, Option<i32>)> = 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<Vec<u8>> = 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);
|
||||
|
||||
|
||||
@@ -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![
|
||||
|
||||
Reference in New Issue
Block a user