Skip to content

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

fix: issue with video saving

Louis Beaumont0883e6e6ca2a
diff --git a/.DS_Store b/.DS_Store
deleted file mode 100644
index bc7eb51f2..000000000
Binary files a/.DS_Store and /dev/null differ
diff --git a/screenpipe-server/src/.DS_Store b/screenpipe-server/src/.DS_Store
deleted file mode 100644
index a7460367e..000000000
Binary files a/screenpipe-server/src/.DS_Store and /dev/null differ
diff --git a/screenpipe-server/src/bin/screenpipe-video.rs b/screenpipe-server/src/bin/screenpipe-video.rs
index bf2f56372..145170759 100644
--- a/screenpipe-server/src/bin/screenpipe-video.rs
+++ b/screenpipe-server/src/bin/screenpipe-video.rs
@@ -1,21 +1,32 @@
use chrono::Utc;
+use env_logger::Env;
use image::GenericImageView;
+use log::info;
use screenpipe_server::VideoCapture;
use serde_json::{json, Value};
-use std::fs::File;
-use std::io::Write;
+use std::fs::{File, OpenOptions};
+use std::io::{BufWriter, Write};
use std::sync::mpsc::channel;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
+fn write_json_frame(writer: &mut BufWriter<File>, frame_data: &Value) -> std::io::Result<()> {
+ serde_json::to_writer(writer.by_ref(), frame_data)?;
+ writeln!(writer)?;
+ writer.flush()
+}
+
fn main() {
+ env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
+
let time = Utc::now();
- let output_path = format!("data/{}.mp4", time);
+ let output_path = "data";
let json_output_path = format!("data/{}.json", time);
// create dir if not exists
std::fs::create_dir_all("data").unwrap_or_default();
+ info!("Created data directory {}", output_path);
let fps = 10.0;
let video_capture = VideoCapture::new(&output_path, fps);
@@ -32,21 +43,28 @@ fn main() {
println!("Press Ctrl+C to stop recording...");
- let mut json_data = Vec::new();
+ let json_file = OpenOptions::new()
+ .create(true)
+ .write(true)
+ .append(true)
+ .open(&json_output_path)
+ .expect("Failed to create JSON file");
+ let mut json_writer = BufWriter::new(json_file);
+
let mut frame_count = 0;
loop {
if let Some(frame) = video_capture.get_latest_frame() {
- println!("Captured frame size: {:?}", frame.image.dimensions());
- println!("OCR Text: {}", frame.text);
+ info!("Captured frame size: {:?}", frame.image.dimensions());
+ info!("OCR Text len: {}", frame.text.len());
- // Add frame data to JSON
let frame_data = json!({
"frame": frame_count,
"timestamp": frame_count as f64 / fps,
"ocr_text": frame.text
});
- json_data.push(frame_data);
+
+ write_json_frame(&mut json_writer, &frame_data).expect("Failed to write JSON frame");
frame_count += 1;
}
@@ -62,21 +80,5 @@ fn main() {
video_capture.stop();
println!("Video capture completed. Output saved to: {}", output_path);
-
- // Save JSON data
- let json_output = json!({
- "video_path": output_path,
- "fps": fps,
- "frames": json_data
- });
-
- let mut file = File::create(json_output_path.clone()).expect("Failed to create JSON file");
- file.write_all(
- serde_json::to_string_pretty(&json_output)
- .unwrap()
- .as_bytes(),
- )
- .expect("Failed to write JSON data");
-
println!("JSON data saved to: {}", json_output_path);
}
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index b90ce3a27..9ae5b8cb9 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -1,8 +1,10 @@
+use chrono::Utc;
use ffmpeg_next as ffmpeg;
use ffmpeg_next::sys::AVSEEK_FLAG_FRAME;
use ffmpeg_next::{format, format::Pixel, media, software::scaling, util::frame::video::Video};
use image::ImageFormat::{self, Png};
use image::{DynamicImage, ImageBuffer, Rgb};
+use log::{error, info};
use screenpipe_vision::{continuous_capture, CaptureResult, ControlMessage};
use std::collections::{BTreeSet, VecDeque};
use std::io::BufRead;
@@ -170,6 +172,7 @@ pub struct VideoCapture {
impl VideoCapture {
pub fn new(output_path: &str, fps: f64) -> Self {
+ info!("Starting new video capture");
let (control_tx, control_rx) = channel();
let frame_queue = Arc::new(Mutex::new(VecDeque::new()));
let ffmpeg_handle = Arc::new(Mutex::new(None));
@@ -186,6 +189,8 @@ impl VideoCapture {
);
});
+ info!("Started capture thread");
+
// Spawn another thread to handle receiving and queueing the results
let queue_thread = thread::spawn(move || {
while *capture_thread_is_running.lock().unwrap() {
@@ -237,7 +242,6 @@ impl VideoCapture {
self.frame_queue.lock().unwrap().pop_front()
}
}
-
fn save_frames_as_video(
frame_queue: &Arc<Mutex<VecDeque<CaptureResult>>>,
output_path: &str,
@@ -245,63 +249,66 @@ fn save_frames_as_video(
is_running: Arc<Mutex<bool>>,
ffmpeg_handle: Arc<Mutex<Option<std::process::Child>>>,
) {
- let mut child = Command::new("ffmpeg")
- .args([
- "-f",
- "image2pipe",
- "-vcodec",
- "png",
- "-r",
- &fps.to_string(),
- "-i",
- "-",
- "-vcodec",
- "libx264",
- "-preset",
- "ultrafast",
- "-pix_fmt",
- "yuv420p",
- "-crf",
- "25",
- output_path,
- ])
- .stdin(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .expect("Failed to spawn ffmpeg process");
-
- let mut stdin = child.stdin.take().expect("Failed to open stdin");
- let stderr = child.stderr.take().expect("Failed to open stderr");
+ let frames_per_video = 30; // Adjust this value as needed
let mut frame_count = 0;
- let mut last_flush = std::time::Instant::now();
-
- ffmpeg_handle.lock().unwrap().replace(child);
-
- // Spawn a thread to log FFmpeg's stderr
- thread::spawn(move || {
- let reader = std::io::BufReader::new(stderr);
- for line in reader.lines() {
- if let Ok(line) = line {
- eprintln!("FFmpeg: {}", line);
- }
- }
- });
-
let cpu_count = num_cpus::get();
- // let pool_size = match task_type {
- // TaskType::CPUBound => cpu_count,
- // TaskType::IOBound => cpu_count * 2,
- // TaskType::Mixed => (cpu_count as f32 * 1.5) as usize,
- // };
- // primarily CPU-bound with some I/O components. Here's why:
- // 1. PNG encoding is computationally expensive.
- // 2. Writing to FFmpeg's stdin is I/O, but likely not the bottleneck.
- // 3. The main performance gain comes from parallelizing the encoding.
let pool_size = (cpu_count as f32 * 1.2) as usize;
- let pool = ThreadPool::new(pool_size); // Adjust the number of threads as needed
+ let pool = ThreadPool::new(pool_size);
let (sender, receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) = channel();
+ let mut current_ffmpeg: Option<std::process::Child> = None;
+ let mut current_stdin: Option<std::process::ChildStdin> = None;
+
while *is_running.lock().unwrap() {
+ if frame_count % frames_per_video == 0 || current_ffmpeg.is_none() {
+ // Close previous FFmpeg process if exists
+ if let Some(mut child) = current_ffmpeg.take() {
+ drop(current_stdin.take()); // Ensure stdin is closed
+ child.wait().expect("ffmpeg process failed");
+ }
+
+ // Wait for at least one frame before starting a new FFmpeg process
+ let first_frame = loop {
+ if let Some(result) = frame_queue.lock().unwrap().pop_front() {
+ break result;
+ }
+ thread::sleep(Duration::from_millis(10));
+ };
+
+ // Encode the first frame
+ let mut buffer = Vec::new();
+ first_frame
+ .image
+ .write_to(&mut std::io::Cursor::new(&mut buffer), ImageFormat::Png)
+ .expect("Failed to encode first frame");
+
+ let time = Utc::now();
+ // Start new FFmpeg process with a new output file
+ let output_file = format!("{}/{}.mp4", output_path, time);
+ let mut child = start_ffmpeg_process(&output_file, fps);
+ let mut stdin = child.stdin.take().expect("Failed to open stdin");
+ let stderr = child.stderr.take().expect("Failed to open stderr");
+
+ // Write the first frame to FFmpeg
+ stdin
+ .write_all(&buffer)
+ .expect("Failed to write first frame to ffmpeg");
+ frame_count += 1;
+
+ // Spawn a thread to log FFmpeg's stderr
+ thread::spawn(move || {
+ let reader = std::io::BufReader::new(stderr);
+ for line in reader.lines() {
+ if let Ok(line) = line {
+ info!("FFmpeg: {}", line);
+ }
+ }
+ });
+
+ current_ffmpeg = Some(child);
+ current_stdin = Some(stdin);
+ }
+
if let Some(result) = frame_queue.lock().unwrap().pop_front() {
let sender = sender.clone();
pool.execute(move || {
@@ -313,7 +320,7 @@ fn save_frames_as_video(
Ok(_) => {
sender.send(buffer).expect("Failed to send encoded frame");
}
- Err(e) => eprintln!("Failed to encode image as PNG: {}", e),
+ Err(e) => error!("Failed to encode image as PNG: {}", e),
}
});
} else {
@@ -322,24 +329,55 @@ fn save_frames_as_video(
// Write encoded frames to FFmpeg
for buffer in receiver.try_iter() {
- if let Err(e) = stdin.write_all(&buffer) {
- eprintln!("Failed to write frame to ffmpeg: {}", e);
- break;
- }
- frame_count += 1;
- println!("Wrote frame {} to FFmpeg", frame_count);
+ if let Some(stdin) = current_stdin.as_mut() {
+ if let Err(e) = stdin.write_all(&buffer) {
+ error!("Failed to write frame to ffmpeg: {}", e);
+ break;
+ }
+ frame_count += 1;
+ info!("Wrote frame {} to FFmpeg", frame_count);
- // Flush every second
- if last_flush.elapsed() > std::time::Duration::from_secs(1) {
- if let Err(e) = stdin.flush() {
- eprintln!("Failed to flush FFmpeg input: {}", e);
+ // Flush every second
+ if frame_count % fps as usize == 0 {
+ if let Err(e) = stdin.flush() {
+ error!("Failed to flush FFmpeg input: {}", e);
+ }
}
- last_flush = std::time::Instant::now();
}
}
}
- drop(stdin);
- if let Some(mut child) = ffmpeg_handle.lock().unwrap().take() {
+
+ // Close the final FFmpeg process
+ if let Some(mut child) = current_ffmpeg.take() {
+ drop(current_stdin.take()); // Ensure stdin is closed
child.wait().expect("ffmpeg process failed");
}
}
+
+fn start_ffmpeg_process(output_file: &str, fps: f64) -> std::process::Child {
+ info!("Starting FFmpeg process for file: {}", output_file);
+ Command::new("ffmpeg")
+ .args([
+ "-f",
+ "image2pipe",
+ "-vcodec",
+ "png",
+ "-r",
+ &fps.to_string(),
+ "-i",
+ "-",
+ "-vcodec",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-pix_fmt",
+ "yuv420p",
+ "-crf",
+ "25",
+ output_file,
+ ])
+ .stdin(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("Failed to spawn ffmpeg process")
+}
diff --git a/screenpipe-vision/src/bin/screenpipe-vision.rs b/screenpipe-vision/src/bin/screenpipe-vision.rs
index 011ca3d9f..61bfad473 100644
--- a/screenpipe-vision/src/bin/screenpipe-vision.rs
+++ b/screenpipe-vision/src/bin/screenpipe-vision.rs
@@ -19,7 +19,7 @@ fn main() {
loop {
if let Ok(result) = result_rx.try_recv() {
println!("Captured image size: {:?}", result.image.dimensions());
- println!("OCR Text: {}", result.text);
+ println!("OCR Text length: {}", result.text.len());
}
let elapsed = start_time.elapsed();
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 5ff445c04..5dbbbd1e6 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -26,15 +26,6 @@ pub fn continuous_capture(
) {
let monitor = Monitor::all().unwrap().first().unwrap().clone();
let cpu_count = num_cpus::get();
- // let pool_size = match task_type {
- // TaskType::CPUBound => cpu_count,
- // TaskType::IOBound => cpu_count * 2,
- // TaskType::Mixed => (cpu_count as f32 * 1.5) as usize,
- // };
- // primarily CPU-bound with some I/O components. Here's why:
- // 1. PNG encoding is computationally expensive.
- // 2. Writing to FFmpeg's stdin is I/O, but likely not the bottleneck.
- // 3. The main performance gain comes from parallelizing the encoding.
let pool_size = (cpu_count as f32 * 1.2) as usize;
let ocr_pool = ThreadPool::new(pool_size);
let is_paused = Arc::new(Mutex::new(false));