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
feat: add audio
Louis Beaumonte7f27d523dd9
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex d691b9da5..c59901c97 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -83,7 +83,17 @@ jobs:env:MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}run: |- codesign --sign "$MACOS_SIGNING_IDENTITY" --timestamp --options runtime target/release/screenpipe+ codesign --force --deep --options runtime --timestamp --sign "$MACOS_SIGNING_IDENTITY" target/release/screenpipe++ - name: Notarize Binary+ env:+ APPLE_ID: ${{ secrets.APPLE_ID }}+ APPLE_ID_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }}+ TEAM_ID: ${{ secrets.TEAM_ID }}+ run: |+ zip screenpipe.zip target/release/screenpipe+ xcrun notarytool submit screenpipe.zip --apple-id "$APPLE_ID" --password "$APPLE_ID_PASSWORD" --team-id "$TEAM_ID" --wait+ xcrun stapler staple screenpipe.zip- name: Upload Artifactid: upload@@ -124,6 +134,4 @@ jobs:gh release create ${{ env.RELEASE_VERSION }} --title ${{ env.RELEASE_VERSION }} --generate-notesmv ./artifacts/ubuntu/screenpipe ./artifacts/ubuntu/screenpipe-ubuntumv ./artifacts/macos/screenpipe ./artifacts/macos/screenpipe-macos- gh release upload ${{ env.RELEASE_VERSION }} ./artifacts/ubuntu/* ./artifacts/macos/*--\ No newline at end of file+ gh release upload ${{ env.RELEASE_VERSION }} ./artifacts/ubuntu/* ./artifacts/macos/*diff --git a/install.sh b/install.shindex 3dd8dbd6c..bf54a42ee 100755--- a/install.sh+++ b/install.sh@@ -14,15 +14,19 @@ ARCH=$(uname -m)case $OS inLinux*)case $ARCH in- x86_64) BINARY="screenpipe-x86_64-unknown-linux-gnu";;- aarch64) BINARY="screenpipe-aarch64-unknown-linux-gnu";;+ # x86_64) BINARY="screenpipe-x86_64-unknown-linux-gnu";;+ # aarch64) BINARY="screenpipe-aarch64-unknown-linux-gnu";;+ x86_64) BINARY="screenpipe-linux";;+ # aarch64) BINARY="screenpipe-linux";;*) echo "Unsupported architecture: $ARCH"; exit 1;;esac;;Darwin*)case $ARCH in- x86_64) BINARY="screenpipe-x86_64-apple-darwin";;- arm64) BINARY="screenpipe-aarch64-apple-darwin";;+ # x86_64) BINARY="screenpipe-x86_64-apple-darwin";;+ # arm64) BINARY="screenpipe-aarch64-apple-darwin";;+ # x86_64) BINARY="screenpipe-macos";;+ arm64) BINARY="screenpipe-macos";;*) echo "Unsupported architecture: $ARCH"; exit 1;;esac;;@@ -33,6 +37,8 @@ esac# Create the local bin directory if it doesn't existmkdir -p $HOME/.local/bin+echo "Downloading $BINARY"+# Download the latest release binary to the local bin directorycurl -L "https://github.com/$REPO/releases/download/$LATEST_RELEASE/$BINARY" -o $HOME/.local/bin/screenpipediff --git a/screenpipe/Cargo.toml b/screenpipe/Cargo.tomlindex 2ef9d5a4d..03a938f78 100644--- a/screenpipe/Cargo.toml+++ b/screenpipe/Cargo.toml@@ -12,6 +12,12 @@ serde_json = "1.0"# Cross-platform screen capturexcap = "0.0.10"+# Cross-platform audio capture+cpal = "0.15.2"++# Wav encoding+hound = "3.5"+# threadpoolthreadpool = "1.8.1"diff --git a/screenpipe/src/core/audio.rs b/screenpipe/src/core/audio.rsnew file mode 100644index 000000000..13cc8d355--- /dev/null+++ b/screenpipe/src/core/audio.rs@@ -0,0 +1,145 @@+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};+use cpal::Sample;+use cpal::SampleFormat;+use std::fs::File;+use std::io::BufWriter;+use std::sync::mpsc::{self, Sender};+use std::sync::{Arc, Mutex};+pub struct AudioHandle {+ pub is_paused: Arc<Mutex<bool>>,+ pub control_sender: Sender<AudioControl>,+}++pub enum AudioControl {+ Stop,+}++pub fn start_audio_recording(output_file: &str) -> Result<AudioHandle, Box<dyn std::error::Error>> {+ let host = cpal::default_host();+ let device = host+ .default_input_device()+ .ok_or("No input device available")?;+ let config = device.default_input_config()?;++ println!("Default input config: {:?}", config);++ let spec = wav_spec_from_config(&config);+ let writer = hound::WavWriter::create(output_file, spec)?;+ let writer = Arc::new(Mutex::new(Some(writer)));++ let is_paused = Arc::new(Mutex::new(false));+ let is_paused_clone = is_paused.clone();++ let (control_sender, control_receiver) = mpsc::channel();++ let writer_clone = writer.clone();++ std::thread::spawn(move || {+ let err_fn = |err| eprintln!("An error occurred on the input audio stream: {}", err);++ let stream = match config.sample_format() {+ SampleFormat::F32 => device.build_input_stream(+ &config.into(),+ move |data: &[f32], _: &_| write_input_data(data, &writer_clone, &is_paused_clone),+ err_fn,+ None,+ ),+ SampleFormat::I16 => device.build_input_stream(+ &config.into(),+ move |data: &[i16], _: &_| write_input_data(data, &writer_clone, &is_paused_clone),+ err_fn,+ None,+ ),+ SampleFormat::U16 => device.build_input_stream(+ &config.into(),+ move |data: &[u16], _: &_| write_input_data(data, &writer_clone, &is_paused_clone),+ err_fn,+ None,+ ),+ _ => return,+ };++ if let Ok(stream) = stream {+ stream.play().expect("Failed to play the stream");++ while let Ok(control) = control_receiver.recv() {+ match control {+ AudioControl::Stop => break,+ }+ }+ drop(stream); // This will stop the stream+ } else {+ eprintln!("Failed to build input stream");+ }++ // Finalize the WAV file+ if let Ok(mut guard) = writer.lock() {+ if let Some(writer) = guard.take() {+ writer.finalize().expect("Failed to finalize WAV file");+ }+ }+ });++ Ok(AudioHandle {+ is_paused,+ control_sender,+ })+}++fn wav_spec_from_config(config: &cpal::SupportedStreamConfig) -> hound::WavSpec {+ hound::WavSpec {+ channels: config.channels() as _,+ sample_rate: config.sample_rate().0 as _,+ bits_per_sample: 16,+ sample_format: hound::SampleFormat::Int,+ }+}++fn sample_format(format: cpal::SampleFormat) -> hound::SampleFormat {+ if format.is_float() {+ hound::SampleFormat::Float+ } else {+ hound::SampleFormat::Int+ }+}++fn write_input_data<T>(+ input: &[T],+ writer: &Arc<Mutex<Option<hound::WavWriter<BufWriter<File>>>>>,+ is_paused: &Arc<Mutex<bool>>,+) where+ T: Sample + SampleToI16,+{+ if !*is_paused.lock().unwrap() {+ if let Ok(mut guard) = writer.try_lock() {+ if let Some(writer) = guard.as_mut() {+ for &sample in input.iter() {+ let sample_to_write: i16 = sample.to_i16();+ writer.write_sample(sample_to_write).ok();+ }+ }+ }+ }+}++trait SampleToI16 {+ fn to_i16(&self) -> i16;+}++impl SampleToI16 for f32 {+ fn to_i16(&self) -> i16 {+ (self.clamp(-1.0, 1.0) * i16::MAX as f32) as i16+ }+}++impl SampleToI16 for i16 {+ fn to_i16(&self) -> i16 {+ *self+ }+}++impl SampleToI16 for u16 {+ fn to_i16(&self) -> i16 {+ (*self as i32 - i16::MAX as i32) as i16+ }+}diff --git a/screenpipe/src/core/core.rs b/screenpipe/src/core/core.rsindex a3aa74efa..250583e51 100644--- a/screenpipe/src/core/core.rs+++ b/screenpipe/src/core/core.rs@@ -1,5 +1,7 @@+use crate::core::start_audio_recording;use crate::core::DatabaseManager;use chrono::Utc;+use cpal::Stream;use image::DynamicImage;use rusty_tesseract::{image_to_string, Args, Image};use std::io::Cursor;@@ -13,7 +15,9 @@ use std::time::Duration;use threadpool::ThreadPool;use xcap::Monitor;+use super::audio::AudioControl;use super::embed;+use super::AudioHandle;const FRAME_BUFFER_SIZE: usize = 30;const SCREENSHOT_INTERVAL: Duration = Duration::from_secs(2);@@ -29,7 +33,9 @@ enum ControlMessage {pub struct CaptureHandles {pub capture_handle: thread::JoinHandle<()>,pub stream_handle: thread::JoinHandle<()>,+ pub audio_handle: thread::JoinHandle<()>,pub control_sender: mpsc::Sender<ControlMessage>,+ pub audio_stream: Arc<Mutex<Option<AudioHandle>>>,}impl CaptureHandles {@@ -40,6 +46,26 @@ impl CaptureHandles {pub fn stop_recording(&self) {self.control_sender.send(ControlMessage::Stop).unwrap();}++ pub fn pause_audio(&self) {+ if let Some(audio_handle) = self.audio_stream.lock().unwrap().as_ref() {+ *audio_handle.is_paused.lock().unwrap() = true;+ }+ }++ pub fn resume_audio(&self) {+ if let Some(audio_handle) = self.audio_stream.lock().unwrap().as_ref() {+ *audio_handle.is_paused.lock().unwrap() = false;+ }+ }++ pub fn stop_audio(&self) {+ if let Some(audio_handle) = self.audio_stream.lock().unwrap().take() {+ if let Err(e) = audio_handle.control_sender.send(AudioControl::Stop) {+ eprintln!("Failed to send stop signal to audio stream: {}", e);+ }+ }+ }}pub fn start_recording(@@ -47,40 +73,66 @@ pub fn start_recording(db: Arc<Mutex<Option<DatabaseManager>>>,) -> CaptureHandles {println!("starting recording...");- let config_path = "models/gte-small/config.json";- let tokenizer_path = "models/gte-small/tokenizer.json";- let weights_path = "models/gte-small/model.safetensors";+ // Initialize control channelslet (control_sender, control_receiver) = mpsc::channel();- // Initialize the model first- embed::init_model(config_path, tokenizer_path, weights_path, false);-+ // Initialize shared resourceslet frame_buffer = Arc::new((Mutex::new(Vec::new()), Condvar::new()));let ocr_pool = ThreadPool::new(OCR_THREAD_POOL_SIZE);+ let audio_stream = Arc::new(Mutex::new(None));- // Capture thread+ // Clone shared resources for thread uselet buffer_clone = frame_buffer.clone();+ let audio_stream_clone = audio_stream.clone();+ let db_capture_ref = db.clone();+ let db_stream_ref = db.clone();- let local_data_dir_capture_handle = local_data_dir.clone();+ // Clone local_data_dir for different threads+ let local_data_dir_capture = local_data_dir.clone();+ let local_data_dir_stream = local_data_dir.clone();+ let local_data_dir_audio = local_data_dir.clone();- let db_capture_ref = db.clone();+ // Initialize embedding model+ let config_path = "models/gte-small/config.json";+ let tokenizer_path = "models/gte-small/tokenizer.json";+ let weights_path = "models/gte-small/model.safetensors";+ embed::init_model(config_path, tokenizer_path, weights_path, false);++ // Start audio recording+ let audio_handle = thread::spawn(move || {+ let output_file = format!("{}/audio_output.wav", local_data_dir);+ match start_audio_recording(&output_file) {+ Ok(audio_handle) => {+ *audio_stream_clone.lock().unwrap() = Some(audio_handle);+ // Keep the thread alive+ loop {+ thread::sleep(Duration::from_secs(1));+ if let Some(handle) = audio_stream_clone.lock().unwrap().as_ref() {+ if *handle.is_paused.lock().unwrap() {+ break;+ }+ }+ }+ }+ Err(e) => eprintln!("Failed to start audio recording: {}", e),+ }+ });++ // Start screen capturelet capture_handle = thread::spawn(move || {capture_screenshots(buffer_clone,&ocr_pool,control_receiver,- local_data_dir_capture_handle,+ local_data_dir_capture,db_capture_ref,).expect("Error capturing screenshots");});- let local_data_dir_stream_handle = local_data_dir.clone();-- let db_stream_ref = db.clone();+ // Start video processinglet stream_handle = thread::spawn(move || {- // Main thread for processing frameslet (buffer, cvar) = &*frame_buffer;loop {let mut frames = buffer.lock().unwrap();@@ -88,24 +140,23 @@ pub fn start_recording(println!("waiting for frames...");frames = cvar.wait(frames).unwrap();}-- // Drain frames and process with FFmpeglet frames_to_process = frames.drain(..).collect::<Vec<_>>();stream_to_ffmpeg(frames_to_process,- local_data_dir_stream_handle.clone(),+ local_data_dir_stream.clone(),db_stream_ref.clone(),);}});- return CaptureHandles {+ CaptureHandles {capture_handle,stream_handle,+ audio_handle,control_sender,- };+ audio_stream,+ }}-fn capture_screenshots(frame_buffer: Arc<(Mutex<Vec<DynamicImage>>, Condvar)>,ocr_pool: &ThreadPool,@@ -303,3 +354,13 @@ fn process_remaining_frames(stream_to_ffmpeg(frames_to_process, local_data_dir_clone, db.clone());}}++fn process_audio(audio_receiver: mpsc::Receiver<Vec<u8>>, local_data_dir: String) {+ let output_file = format!("{}/audio_output.raw", local_data_dir);+ let mut file = std::fs::File::create(output_file).expect("Failed to create audio file");++ while let Ok(audio_data) = audio_receiver.recv() {+ file.write_all(&audio_data)+ .expect("Failed to write audio data");+ }+}diff --git a/screenpipe/src/core/mod.rs b/screenpipe/src/core/mod.rsindex 0e5cc2c94..be1c5f8f2 100644--- a/screenpipe/src/core/mod.rs+++ b/screenpipe/src/core/mod.rs@@ -1,8 +1,10 @@+mod audio;mod core;mod db;mod embed;mod video;+pub use audio::{start_audio_recording, AudioHandle};pub use core::start_recording;pub use core::CaptureHandles;pub use db::DatabaseManager;