YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Export frames as video (#1471)
shaik-zeeshand471984d9c2b
diff --git a/pipes/rewind/src/app/layout.tsx b/pipes/rewind/src/app/layout.tsxindex e87afd870..988043355 100644--- a/pipes/rewind/src/app/layout.tsx+++ b/pipes/rewind/src/app/layout.tsx@@ -5,6 +5,7 @@ import { SearchCommand } from "@/components/search-command";import { NuqsAdapter } from "nuqs/adapters/next/app";import { getScreenpipeAppSettings } from "@/lib/actions/get-screenpipe-app-settings";import { SettingsProvider } from "@/components/settings-provider";+import { Toaster } from "@/components/ui/toaster";const geistSans = Geist({variable: "--font-geist-sans",@@ -62,6 +63,7 @@ export default async function RootLayout({<NuqsAdapter><SearchCommand />{children}+ <Toaster /></NuqsAdapter></>)}diff --git a/pipes/rewind/src/components/export-button.tsx b/pipes/rewind/src/components/export-button.tsxnew file mode 100644index 000000000..c4c40d349--- /dev/null+++ b/pipes/rewind/src/components/export-button.tsx@@ -0,0 +1,244 @@+import { useState } from "react";+import { Button } from "./ui/button";+import { Loader2, Video } from "lucide-react";+import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";+import { toast } from "./ui/use-toast";+import { getScreenpipeAppSettings } from "@/lib/actions/get-screenpipe-app-settings";+import { Settings } from "@screenpipe/js";+import { parseInt } from "lodash";++export function ExportButton() {+ const [isExporting, setIsExporting] = useState(false);+ const [progress, setProgress] = useState(0);+ const { selectionRange } = useTimelineSelection();++ const handleExport = async () => {+ if (!selectionRange?.frameIds.length) {+ toast({+ title: "No frames selected",+ description: "Please select frames to export",+ variant: "destructive",+ });+ return;+ }+ setIsExporting(true);+ setProgress(0);+ try {+ const settings = (await getScreenpipeAppSettings()) as Settings & {+ fps: number;+ };+ let isClosingManually = false;+ let ws: WebSocket | null = null;++ const sortedFrameIds = selectionRange.frameIds.sort(+ (a, b) => parseInt(a) - parseInt(b),+ );++ // Helper function to safely close the WebSocket+ const closeWebSocket = () => {+ if (+ ws &&+ (ws.readyState === WebSocket.OPEN ||+ ws.readyState === WebSocket.CONNECTING)+ ) {+ isClosingManually = true;+ try {+ ws.close();+ } catch (e) {+ console.error("Error closing WebSocket:", e);+ }+ }+ ws = null;+ };++ // Create WebSocket connection+ ws = new WebSocket(+ `ws://localhost:3030/frames/export?frame_ids=${sortedFrameIds.join(",")}&fps=${settings.fps ?? 0.5}`,+ );++ // Set a timeout to handle connection issues+ const connectionTimeout = setTimeout(() => {+ if (ws && ws.readyState !== WebSocket.OPEN) {+ toast({+ title: "Connection timeout",+ description: "Failed to connect to the server. Please try again.",+ variant: "destructive",+ });+ closeWebSocket();+ setIsExporting(false);+ setProgress(0);+ }+ }, 10000); // 10 seconds timeout++ ws.onopen = () => {+ clearTimeout(connectionTimeout);+ console.log("WebSocket connection established");+ };++ ws.onmessage = async (event) => {+ try {+ const data = JSON.parse(event.data);+ switch (data.status) {+ case "extracting":+ setProgress(data.progress * 100);+ break;+ case "encoding":+ setProgress(50 + data.progress * 50);+ break;+ case "completed":+ if (data.video_data) {+ closeWebSocket();+ const filename = `screenpipe_export_${new Date()+ .toISOString()+ .replace(/[:.]/g, "-")}.mp4`;++ try {+ if ("__TAURI__" in window) {+ const tauri = window.__TAURI__ as any;+ const { save } = tauri.dialog;+ const { writeFile } = tauri.fs;+ const filePath = await save({+ filters: [+ {+ name: "Video",+ extensions: ["mp4"],+ },+ ],+ defaultPath: filename,+ });+ if (filePath) {+ await writeFile(+ filePath,+ new Uint8Array(data.video_data),+ );+ toast({+ title: "Video exported",+ description:+ "Your video has been exported successfully",+ });+ }+ } else {+ // For browser (including Safari), handle the download differently+ const blob = new Blob([new Uint8Array(data.video_data)], {+ type: "video/mp4",+ });++ // Use a more Safari-friendly approach+ const url = window.URL.createObjectURL(blob);++ const a = document.createElement("a");+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ window.URL.revokeObjectURL(url);+ a.remove();++ toast({+ title: "Video exported",+ description: "Your video has been exported successfully",+ });+ }+ } catch (downloadError) {+ console.error("Download error:", downloadError);+ toast({+ title: "Download failed",+ description:+ "Failed to download the video. Please try again.",+ variant: "destructive",+ });+ }+ }+ setIsExporting(false);+ setProgress(0);+ break;+ case "error":+ toast({+ title: "Export failed",+ description: data.error || "Failed to export video",+ variant: "destructive",+ });+ setIsExporting(false);+ setProgress(0);+ closeWebSocket();+ break;+ }+ } catch (parseError) {+ console.error("Error parsing message:", parseError);+ toast({+ title: "Export failed",+ description: "Failed to process server response",+ variant: "destructive",+ });+ setIsExporting(false);+ setProgress(0);+ closeWebSocket();+ }+ };++ ws.onclose = (event) => {+ clearTimeout(connectionTimeout);+ console.log("WebSocket closed:", event);++ if (isExporting && !isClosingManually) {+ toast({+ title: "Connection closed",+ description: "The server connection was closed unexpectedly",+ variant: "destructive",+ });+ setIsExporting(false);+ setProgress(0);+ }+ };++ ws.onerror = (event) => {+ clearTimeout(connectionTimeout);+ // Only handle as a true error if we're not manually closing+ if (isClosingManually) {+ console.log(+ "WebSocket error during manual closure - this is expected",+ );+ return;+ }++ console.error("WebSocket error:", event);+ toast({+ title: "Export failed",+ description: "Connection error. Please try again.",+ variant: "destructive",+ });+ setIsExporting(false);+ setProgress(0);+ closeWebSocket();+ };+ } catch (error) {+ console.error("Export setup error:", error);+ toast({+ title: "Export failed",+ description: "Failed to export video. Please try again.",+ variant: "destructive",+ });+ setIsExporting(false);+ setProgress(0);+ }+ };++ return (+ <Button+ variant="outline"+ onClick={handleExport}+ className="h-auto px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"+ disabled={isExporting || !selectionRange?.frameIds.length}+ >+ {isExporting ? (+ <div className="flex items-center">+ <Loader2 className="h-4 w-4 animate-spin mr-2" />+ {progress > 0 && `${Math.round(progress)}%`}+ </div>+ ) : (+ <Video className="h-4 w-4 mr-2" />+ )}+ Export Video+ </Button>+ );+}diff --git a/pipes/rewind/src/components/timeline/ai-panel.tsx b/pipes/rewind/src/components/timeline/ai-panel.tsxindex b7946ac41..9110bc3cf 100644--- a/pipes/rewind/src/components/timeline/ai-panel.tsx+++ b/pipes/rewind/src/components/timeline/ai-panel.tsx@@ -18,6 +18,7 @@ import {TooltipTrigger,} from "@/components/ui/tooltip";import { useSettings } from "@/lib/hooks/use-settings";+import { ExportButton } from "../export-button";interface AIPanelProps {position: { x: number; y: number };@@ -325,7 +326,7 @@ export function AIPanel({left: position.x,top: position.y,width: chatWindowSize.width,- height: isExpanded ? chatWindowSize.height : 120,+ height: isExpanded ? chatWindowSize.height : "auto",cursor: isDraggingPanel ? "grabbing" : "default",}}>@@ -363,7 +364,7 @@ export function AIPanel({</div>{!isExpanded && (- <div className="p-4">+ <div className="p-4 space-y-2"><buttonclassName="px-3 py-1 bg-background hover:bg-accent border text-foreground text-xs rounded flex items-center gap-2 transition-colors"onClick={(e) => {@@ -379,6 +380,7 @@ export function AIPanel({{osType === "macos" ? "⌘L" : "Ctrl+L"}</span></button>+ <ExportButton /></div>)}</div>diff --git a/pipes/rewind/src/components/timeline/timeline-dock-section.tsx b/pipes/rewind/src/components/timeline/timeline-dock-section.tsxindex f6b6eb804..cf44bb603 100644--- a/pipes/rewind/src/components/timeline/timeline-dock-section.tsx+++ b/pipes/rewind/src/components/timeline/timeline-dock-section.tsx@@ -399,6 +399,7 @@ export function TimelineIconsSection({setSelectionRange({start: selectedApp.timestamp,end: new Date(selectedApp.timestamp.getTime() + 60000),+ frameIds: [],});}}>diff --git a/pipes/rewind/src/components/timeline/timeline-selection.tsx b/pipes/rewind/src/components/timeline/timeline-selection.tsxindex d80ccff13..b606c477a 100644--- a/pipes/rewind/src/components/timeline/timeline-selection.tsx+++ b/pipes/rewind/src/components/timeline/timeline-selection.tsx@@ -33,7 +33,7 @@ export function TimelineSelection({setStartChunk(chunkIndex);setCurrentChunk(chunkIndex);const date = getDateFromChunk(chunkIndex);- setSelectionRange({ start: date, end: date });+ setSelectionRange({ start: date, end: date, frameIds: [] });};const handleMouseMove = (e: MouseEvent, chunkIndex: number) => {@@ -46,6 +46,7 @@ export function TimelineSelection({setSelectionRange({start: getDateFromChunk(start),end: getDateFromChunk(end + 1), // +1 to include the full chunk+ frameIds: [],});};diff --git a/pipes/rewind/src/components/timeline/timeline.tsx b/pipes/rewind/src/components/timeline/timeline.tsxindex 3af1bf2e9..913f96aa4 100644--- a/pipes/rewind/src/components/timeline/timeline.tsx+++ b/pipes/rewind/src/components/timeline/timeline.tsx@@ -159,7 +159,7 @@ export const TimelineSlider = ({setSelectedIndices(new Set([index]));const startDate = new Date(frames[index].timestamp);- setSelectionRange({ start: startDate, end: startDate });+ setSelectionRange({ start: startDate, end: startDate, frameIds: [] });};const handleDragOver = (index: number) => {@@ -174,9 +174,16 @@ export const TimelineSlider = ({setSelectedIndices(newSelection);+ // Get frame IDs for the selection+ const selectedFrameIds = Array.from(newSelection).map(+ (i) => frames[i].devices[0].frame_id,+ );++ // Update selection range with frame IDssetSelectionRange({end: new Date(frames[start].timestamp),start: new Date(frames[end].timestamp),+ frameIds: selectedFrameIds,});if (onSelectionChange) {diff --git a/pipes/rewind/src/lib/hooks/use-timeline-selection.tsx b/pipes/rewind/src/lib/hooks/use-timeline-selection.tsxindex 84918fcad..8f2dea48f 100644--- a/pipes/rewind/src/lib/hooks/use-timeline-selection.tsx+++ b/pipes/rewind/src/lib/hooks/use-timeline-selection.tsx@@ -1,33 +1,35 @@-import { createContext, useContext, ReactNode, useState } from "react";+import { createContext, useContext, useState, ReactNode } from "react";++interface TimelineSelection {+ start: Date;+ end: Date;+ frameIds: string[];+}interface TimelineContextType {- selectionRange: { start: Date; end: Date } | null;- setSelectionRange: (range: { start: Date; end: Date } | null) => void;+ selectionRange: TimelineSelection | null;+ setSelectionRange: (range: TimelineSelection | null) => void;}-const TimelineContext = createContext<TimelineContextType | undefined>(- undefined-);+const TimelineContext = createContext<TimelineContextType | null>(null);export function TimelineProvider({ children }: { children: ReactNode }) {- const [selectionRange, setSelectionRange] = useState<{- start: Date;- end: Date;- } | null>(null);+ const [selectionRange, setSelectionRange] =+ useState<TimelineSelection | null>(null);- return (- <TimelineContext.Provider value={{ selectionRange, setSelectionRange }}>- {children}- </TimelineContext.Provider>- );+ return (+ <TimelineContext.Provider value={{ selectionRange, setSelectionRange }}>+ {children}+ </TimelineContext.Provider>+ );}export function useTimelineSelection() {- const context = useContext(TimelineContext);- if (!context) {- throw new Error(- "useTimelineSelection must be used within a TimelineProvider"- );- }- return context;+ const context = useContext(TimelineContext);+ if (!context) {+ throw new Error(+ "useTimelineSelection must be used within a TimelineProvider",+ );+ }+ return context;}diff --git a/screenpipe-app-tauri/src-tauri/tauri.conf.json b/screenpipe-app-tauri/src-tauri/tauri.conf.jsonindex d19ddb014..665533d55 100644--- a/screenpipe-app-tauri/src-tauri/tauri.conf.json+++ b/screenpipe-app-tauri/src-tauri/tauri.conf.json@@ -98,6 +98,7 @@}},"app": {+ "withGlobalTauri": true,"trayIcon": {"id": "screenpipe_main","iconPath": "icons/screenpipe-logo-tray-black.png",diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 2fb22f81a..13f9b6221 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -27,8 +27,8 @@ use crate::{video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},video_cache::{AudioEntry, DeviceFrame, FrameCache, FrameMetadata, TimeSeriesFrame},video_utils::{- extract_frame_from_video, merge_videos, validate_media, MergeVideosRequest,- MergeVideosResponse, ValidateMediaParams,+ extract_frame_from_video, extract_high_quality_frame, merge_videos, validate_media,+ MergeVideosRequest, MergeVideosResponse, ValidateMediaParams,},DatabaseManager,};@@ -2071,6 +2071,7 @@ pub fn create_router() -> Router<Arc<AppState>> {// .route("/vision/stop", post(stop_vision_device))// .route("/audio/restart", post(restart_audio_devices))// .route("/vision/restart", post(restart_vision_devices))+ .route("/frames/export", get(handle_video_export_ws)).layer(cors);#[cfg(feature = "experimental")]@@ -2080,6 +2081,231 @@ pub fn create_router() -> Router<Arc<AppState>> {router}+#[derive(Debug, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct VideoExportRequest {+ #[serde(deserialize_with = "deserialize_frame_ids")]+ frame_ids: Vec<i64>,+ fps: f64,+}++fn deserialize_frame_ids<'de, D>(deserializer: D) -> Result<Vec<i64>, D::Error>+where+ D: serde::Deserializer<'de>,+{+ let s: String = String::deserialize(deserializer)?;+ Ok(s.split(',').filter_map(|id| id.parse().ok()).collect())+}++#[derive(Debug, Serialize)]+struct ExportProgress {+ status: String,+ progress: f32,+ video_data: Option<Vec<u8>>,+ error: Option<String>,+}++pub async fn handle_video_export_ws(+ ws: WebSocketUpgrade,+ State(state): State<Arc<AppState>>,+ Query(payload): Query<VideoExportRequest>,+) -> impl IntoResponse {+ if payload.frame_ids.is_empty() {+ return (+ StatusCode::BAD_REQUEST,+ Json(json!({ "error": "No valid frame IDs provided" })),+ )+ .into_response();+ }++ ws.on_upgrade(move |socket| async move { handle_video_export(socket, state, payload).await })+}++async fn handle_video_export(+ mut socket: WebSocket,+ state: Arc<AppState>,+ payload: VideoExportRequest,+) {+ let temp_dir = match tempfile::tempdir() {+ Ok(dir) => dir,+ Err(e) => {+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "error".to_string(),+ progress: 0.0,+ video_data: None,+ error: Some(format!("Failed to create temp directory: {}", e)),+ })+ .unwrap(),+ ))+ .await;+ return;+ }+ };++ let frames_dir = temp_dir.path().join("frames");+ if let Err(e) = tokio::fs::create_dir_all(&frames_dir).await {+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "error".to_string(),+ progress: 0.0,+ video_data: None,+ error: Some(format!("Failed to create frames directory: {}", e)),+ })+ .unwrap(),+ ))+ .await;+ return;+ }++ let output_filename = format!(+ "screenpipe_export_{}.mp4",+ chrono::Utc::now().format("%Y%m%d_%H%M%S")+ );+ let output_path = temp_dir.path().join(&output_filename);++ let mut frames = Vec::new();+ let mut skipped_frames = Vec::new();++ // Send initial status+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "extracting".to_string(),+ progress: 0.0,+ video_data: None,+ error: None,+ })+ .unwrap(),+ ))+ .await;++ // Process frames+ for (index, frame_id) in payload.frame_ids.iter().enumerate() {+ let progress = (index as f32 / payload.frame_ids.len() as f32) * 0.5;+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "extracting".to_string(),+ progress,+ video_data: None,+ error: None,+ })+ .unwrap(),+ ))+ .await;++ match state.db.get_frame(*frame_id).await {+ Ok(Some((file_path, offset_index))) => {+ match extract_high_quality_frame(&file_path, offset_index, &frames_dir).await {+ Ok(frame_path) => {+ frames.push(FrameContent {+ file_path: frame_path,+ timestamp: Some(chrono::Utc::now()),+ window_name: None,+ app_name: None,+ ocr_results: None,+ tags: None,+ });+ }+ Err(e) => {+ error!("Failed to extract frame {}: {}", frame_id, e);+ skipped_frames.push(*frame_id);+ }+ }+ }+ Ok(None) => {+ error!("Frame {} not found in database", frame_id);+ skipped_frames.push(*frame_id);+ }+ Err(e) => {+ error!("Database error for frame {}: {}", frame_id, e);+ skipped_frames.push(*frame_id);+ }+ }+ }++ if frames.is_empty() {+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "error".to_string(),+ progress: 0.0,+ video_data: None,+ error: Some("No valid frames to process".to_string()),+ })+ .unwrap(),+ ))+ .await;+ return;+ }++ // Send encoding status+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "encoding".to_string(),+ progress: 0.5,+ video_data: None,+ error: None,+ })+ .unwrap(),+ ))+ .await;++ // Create video+ match write_frames_to_video(&frames, output_path.to_str().unwrap(), payload.fps).await {+ Ok(_) => match tokio::fs::read(&output_path).await {+ Ok(video_data) => {+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "completed".to_string(),+ progress: 1.0,+ video_data: Some(video_data),+ error: None,+ })+ .unwrap(),+ ))+ .await;+ }+ Err(e) => {+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "error".to_string(),+ progress: 1.0,+ video_data: None,+ error: Some(format!("Failed to read video file: {}", e)),+ })+ .unwrap(),+ ))+ .await;+ }+ },+ Err(e) => {+ let _ = socket+ .send(Message::Text(+ serde_json::to_string(&ExportProgress {+ status: "error".to_string(),+ progress: 1.0,+ video_data: None,+ error: Some(format!("Failed to create video: {}", e)),+ })+ .unwrap(),+ ))+ .await;+ }+ }++ // Cleanup+ if let Err(e) = tokio::fs::remove_dir_all(&temp_dir).await {+ error!("Failed to clean up temp directory: {}", e);+ }+}+async fn get_pipe_build_status(Path(pipe_id): Path<String>,State(state): State<Arc<AppState>>,diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rsindex 073dbb3d8..22e2b8dce 100644--- a/screenpipe-server/src/video_utils.rs+++ b/screenpipe-server/src/video_utils.rs@@ -314,25 +314,34 @@ async fn get_video_fps(ffmpeg_path: &PathBuf, video_path: &str) -> Result<f64> {"quiet","-print_format","json",- "-show_format",- "-show_streams",+ "-select_streams",+ "v:0", // Select first video stream+ "-show_entries",+ "stream=r_frame_rate", // Only request frame rate informationvideo_path,]).output().await?;- let stdout = String::from_utf8_lossy(&output.stdout);- let metadata: FFprobeOutput = serde_json::from_str(&stdout)?;+ if !output.status.success() {+ let error = String::from_utf8_lossy(&output.stderr);+ return Err(anyhow::anyhow!("ffprobe failed: {}", error));+ }- let fps = metadata- .streams- .first()- .and_then(|s| {- let parts: Vec<f64> = s- .r_frame_rate- .split('/')- .filter_map(|n| n.parse().ok())- .collect();+ let stdout = String::from_utf8_lossy(&output.stdout);+ debug!("ffprobe output: {}", stdout);++ // Parse the simplified JSON output+ let parsed: serde_json::Value = serde_json::from_str(&stdout)?;++ let fps = parsed+ .get("streams")+ .and_then(|streams| streams.as_array())+ .and_then(|streams| streams.first())+ .and_then(|stream| stream.get("r_frame_rate"))+ .and_then(|rate| rate.as_str())+ .and_then(|rate| {+ let parts: Vec<f64> = rate.split('/').filter_map(|n| n.parse().ok()).collect();if parts.len() == 2 && parts[1] != 0.0 {Some(parts[0] / parts[1])} else {@@ -569,7 +578,7 @@ pub async fn extract_frame_from_video(file_path: &str, offset_index: i64) -> Res"-i",file_path,"-vf",- "scale=iw*0.75:ih*0.75,format=yuvj420p", // Add format conversion+ "scale=iw:ih,format=yuvj420p", // Add format conversion"-vframes","1","-c:v",@@ -630,3 +639,61 @@ async fn cleanup_old_frames(frames_dir: &PathBuf) -> Result<()> {Ok(())}++pub async fn extract_high_quality_frame(+ file_path: &str,+ offset_index: i64,+ output_dir: &Path,+) -> Result<String> {+ let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");++ let source_fps = match get_video_fps(&ffmpeg_path, file_path).await {+ Ok(fps) => fps,+ Err(e) => {+ error!("failed to get video fps, using default 1fps: {}", e);+ 1.0+ }+ };++ let frame_time = offset_index as f64 * source_fps;++ let frame_filename = format!(+ "frame_{}_{}.png",+ chrono::Utc::now().timestamp_micros(),+ offset_index+ );+ let output_path = output_dir.join(frame_filename);++ let mut command = Command::new(&ffmpeg_path);+ command.args([+ "-y",+ "-loglevel",+ "error",+ "-ss",+ &frame_time.to_string(),+ "-i",+ file_path,+ "-vframes",+ "1",+ "-vf",+ "scale=3840:2160:flags=lanczos",+ "-c:v",+ "png",+ "-compression_level",+ "0",+ "-preset",+ "veryslow",+ "-qscale:v",+ "1",+ output_path.to_str().unwrap(),+ ]);++ let output = command.output().await?;+ if !output.status.success() {+ let error_msg = String::from_utf8_lossy(&output.stderr);+ error!("FFmpeg failed: {}", error_msg);+ return Err(anyhow::anyhow!("FFmpeg failed: {}", error_msg));+ }++ Ok(output_path.to_str().unwrap().to_string())+}