Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

implement camera feed??

PJa4ba29bc8e03
diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rs
index fb8e70cb3..051a13745 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -1,407 +1,3 @@
-use cap_utils::create_named_pipe;
-use cpal::{
- traits::{DeviceTrait, HostTrait, StreamTrait},
- Device, SampleFormat, SizedSample, Stream, StreamConfig, SupportedStreamConfig,
-};
-
-use indexmap::IndexMap;
-use num_traits::ToBytes;
-use std::{fs::File, io::Write, path::PathBuf, sync::Arc, time::Instant};
-use tokio::sync::{
- mpsc::{self, error::TrySendError},
- oneshot, watch,
-};
-
-use crate::{capture::CaptureController, encoder::MP3Encoder};
-
-type SampleReceiver = mpsc::Receiver<Arc<Vec<f32>>>;
-
-pub struct AudioCapturer {
- device: Device,
- pub device_name: String,
- pub supported_config: SupportedStreamConfig,
- pub config: StreamConfig,
- sample_receiver: Option<SampleReceiver>,
- stream: Option<Stream>,
-}
-unsafe impl Send for AudioCapturer {}
-unsafe impl Sync for AudioCapturer {}
-
-const MAX_CHANNELS: u16 = 1;
-
-impl AudioCapturer {
- pub fn init(name: &str) -> Option<Self> {
- println!("Custom device: {}", name);
-
- get_input_devices()
- .swap_remove(name)
- .map(|(device, supported_config)| {
- println!("Using audio device: {}", name);
-
- let mut config = supported_config.config();
-
- config.channels = config.channels.min(MAX_CHANNELS);
-
- Self {
- config,
- supported_config,
- device,
- device_name: name.to_string(),
- sample_receiver: None,
- stream: None,
- }
- })
- }
-
- pub fn log_info(&self) {
- println!("Sample rate: {}", self.sample_rate());
- println!("Channels: {}", self.channels());
- println!("Sample format: {}", self.sample_format());
- }
-
- pub fn start(&mut self, start_time_tx: oneshot::Sender<Instant>) -> Result<(), String> {
- self.log_info();
- tracing::trace!("Building input stream...");
-
- let (receiver, stream) =
- (match self.supported_config.sample_format() {
- SampleFormat::I8 => self
- .build_stream::<i8>(start_time_tx, |n| n as f32 / i8::MAX as f32 * 2.0 - 1.0),
- SampleFormat::I16 => self
- .build_stream::<i16>(start_time_tx, |n| n as f32 / i16::MAX as f32 * 2.0 - 1.0),
- SampleFormat::I32 => self
- .build_stream::<i32>(start_time_tx, |n| n as f32 / i32::MAX as f32 * 2.0 - 1.0),
- SampleFormat::U8 => self
- .build_stream::<u8>(start_time_tx, |n| n as f32 / u8::MAX as f32 * 2.0 - 1.0),
- SampleFormat::U16 => self
- .build_stream::<u16>(start_time_tx, |n| n as f32 / u16::MAX as f32 * 2.0 - 1.0),
- SampleFormat::U32 => self
- .build_stream::<u32>(start_time_tx, |n| n as f32 / u32::MAX as f32 * 2.0 - 1.0),
- SampleFormat::F32 => self.build_stream::<f32>(start_time_tx, |n| n),
- SampleFormat::F64 => self.build_stream::<f64>(start_time_tx, |n| n as f32),
- _ => unreachable!(),
- })?;
-
- stream
- .play()
- .map_err(|_| "Failed to start audio recording")?;
- tracing::info!("Audio recording started.");
-
- self.stream = Some(stream);
- self.sample_receiver = Some(receiver);
- Ok(())
- }
-
- pub fn pause(&mut self) -> Result<(), String> {
- if let Some(ref mut stream) = self.stream {
- stream
- .pause()
- .map_err(|_| "Failed to pause stream".to_string())
- } else {
- Err("Stream not started".to_string())
- }
- }
-
- pub fn resume(&mut self) -> Result<(), String> {
- if let Some(ref mut stream) = self.stream {
- stream
- .play()
- .map_err(|_| "Failed to resume stream".to_string())
- } else {
- Err("Stream not started".to_string())
- }
- }
-
- pub fn stop(&mut self) -> Result<(), String> {
- if let Some(ref mut stream) = self.stream {
- stream.pause().map_err(|_| "Failed to pause stream")?;
- tracing::info!("Audio capturing stopped.");
- Ok(())
- } else {
- Err("Original recording was not started".to_string())
- }
- }
-
- // TODO: Where to add these...?
- pub fn ffmpeg_filters(&self) -> Vec<&str> {
- let mut audio_filters = Vec::new();
-
- if self.channels() > 2 {
- audio_filters.push("pan=stereo|FL=FL+0.5*FC|FR=FR+0.5*FC");
- }
-
- audio_filters.push("loudnorm");
- audio_filters
- }
-
- pub fn sample_rate(&self) -> u32 {
- self.config.sample_rate.0
- }
-
- pub fn channels(&self) -> u16 {
- self.config.channels
- }
-
- // Returns ffmpeg sample format ID and sample size in bytes
- pub fn sample_format(&self) -> &str {
- match self.supported_config.sample_format() {
- SampleFormat::I8 => "s8",
- SampleFormat::I16 => "s16le",
- SampleFormat::I32 => "s32le",
- SampleFormat::U8 => "u8",
- SampleFormat::U16 => "u16le",
- SampleFormat::U32 => "u32le",
- SampleFormat::F32 => "f32le",
- SampleFormat::F64 => "f64le",
- _ => unreachable!(),
- }
- }
-
- fn build_stream<T: SizedSample + 'static>(
- &self,
- start_time_tx: oneshot::Sender<Instant>,
- convert_fn: fn(T) -> f32,
- ) -> Result<(SampleReceiver, Stream), String> {
- let (sender, receiver) = mpsc::channel(2048);
-
- let mut start_time_tx = Some(start_time_tx);
-
- self.device
- .build_input_stream(
- &self.config.clone(),
- move |data: &[T], _| {
- match sender.try_send(Arc::new(
- data.iter().map(|sample| convert_fn(*sample)).collect(),
- )) {
- Ok(_) => {
- if let Some(start_time_option) = start_time_tx.take() {
- start_time_option.send(Instant::now()).ok();
-
- tracing::trace!("Audio start time captured");
- }
- }
- Err(TrySendError::Full(_)) => {
- // TODO: Consider panicking? This should *never* happen
- tracing::error!("Channel buffer is full!");
- }
- _ => {
- tracing::trace!("Recording has been stopped. Dropping data.")
- }
- }
- },
- |err| {
- tracing::error!("An error occurred on the audio stream: {}", err);
- },
- None,
- )
- .map(|stream| (receiver, stream))
- .map_err(|_| "Failed to build audio input stream".into())
- }
-}
-
-pub fn get_input_devices() -> IndexMap<String, (Device, SupportedStreamConfig)> {
- let host = cpal::default_host();
- let mut device_map = IndexMap::new();
-
- let get_usable_microphone = |device: Device| {
- if !device.default_input_config().is_ok() {
- return None;
- }
-
- device
- .supported_input_configs()
- .ok()
- .and_then(|mut configs| {
- configs.find(|c| match c.sample_format() {
- SampleFormat::I8
- | SampleFormat::I16
- | SampleFormat::I32
- | SampleFormat::U8
- | SampleFormat::U16
- | SampleFormat::U32
- | SampleFormat::F32
- | SampleFormat::F64 => true,
- _ => false,
- })
- })
- .and_then(|config| {
- device
- .name()
- .ok()
- .filter(|name| !name.to_lowercase().contains("speaker"))
- .map(|name| (name, device, config.with_max_sample_rate()))
- })
- };
-
- if let Some((name, device, config)) =
- host.default_input_device().and_then(get_usable_microphone)
- {
- device_map.insert(name, (device, config));
- }
-
- match host.input_devices() {
- Ok(devices) => {
- for (name, device, config) in devices.filter_map(get_usable_microphone) {
- device_map.entry(name).or_insert((device, config));
- }
- }
- Err(error) => {
- tracing::warn!("Could not access audio input devices");
- tracing::debug!("{error}");
- }
- }
-
- device_map
-}
-
-pub async fn start_capturing(
- mut capturer: AudioCapturer,
- pipe_path: PathBuf,
- start_writing_rx: watch::Receiver<bool>,
-) -> (CaptureController, AudioCapturer) {
- let controller = CaptureController::new(pipe_path.clone());
-
- let (tx, rx) = oneshot::channel();
-
- capturer.start(tx).unwrap();
-
- create_named_pipe(&pipe_path).unwrap();
-
- println!("Starting audio channel senders...");
- let mut receiver = capturer
- .sample_receiver
- .take()
- .expect("Audio sample collection already started!");
-
- tokio::spawn({
- let controller = controller.clone();
- async move {
- println!("Opening audio pipe...");
- let mut pipe = File::create(&pipe_path).unwrap();
- println!("Audio pipe opened");
-
- while let Some(samples) = receiver.recv().await {
- if controller.is_stopped() {
- println!("Stopping receiving camera frames");
- break;
- }
-
- if !*start_writing_rx.borrow() || controller.is_paused() {
- continue;
- }
-
- pipe.write_all(
- &samples
- .iter()
- .flat_map(|f| f.to_le_bytes())
- .collect::<Vec<_>>(),
- )
- .unwrap();
- }
-
- println!("Done receiving audio frames");
-
- pipe.sync_all().ok();
- }
- });
-
- rx.await.unwrap(); // wait for first frame
-
- (controller, capturer)
-}
-
-// ffmpeg
-// .command
-// .args(["-ac", &capturer.channels().to_string(), "-async", "1"])
-// .args([
-// "-af",
-// "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
-// ])
-// .arg(&output_path);
-
-// pub async fn start_capturing(
-// mut capturer: AudioCapturer,
-// output_path: PathBuf,
-// start_writing_rx: watch::Receiver<bool>,
-// ) -> CaptureController {
-// let controller = CaptureController::new(output_path);
-
-// let (tx, rx) = oneshot::channel();
-
-// capturer.start(tx).unwrap();
-// let sample_rate = capturer.sample_rate();
-
-// tokio::spawn({
-// let controller = controller.clone();
-// async move {
-// let mut receiver = capturer
-// .sample_receiver
-// .take()
-// .expect("Audio sample collection already started!");
-
-// let mut encoder = MP3Encoder::new(&controller.output_path, sample_rate);
-
-// dbg!(encoder.context.frame_size());
-// let mut frame_buffer = Vec::<f32>::with_capacity(encoder.context.frame_size() as usize);
-
-// while let Some(samples) = receiver.recv().await {
-// if controller.is_stopped() {
-// println!("Stopping receiving audio frames");
-// break;
-// }
-
-// if !*start_writing_rx.borrow() {
-// continue;
-// }
-
-// if controller.is_paused() {
-// // Skip writing data to pipe while paused
-// continue;
-// }
-
-// let mut processed_samples = 0;
-// while processed_samples < samples.len() {
-// let buffer_remaining = frame_buffer.capacity() - frame_buffer.len();
-// let src_range = 0..usize::min(samples.len(), buffer_remaining);
-
-// processed_samples += src_range.len();
-
-// frame_buffer.extend_from_slice(&samples[src_range]);
-
-// if frame_buffer.len() < frame_buffer.capacity() {
-// continue;
-// }
-
-// let mut frame = ffmpeg::frame::Audio::new(
-// ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),
-// frame_buffer.len(),
-// ffmpeg::ChannelLayout::MONO,
-// );
-
-// frame.data_mut(0).copy_from_slice(
-// &frame_buffer
-// .iter()
-// .flat_map(|float| float.to_ne_bytes())
-// .collect::<Vec<_>>(),
-// );
-
-// frame_buffer.clear();
-
-// encoder.encode_frame(frame);
-// }
-// }
-
-// capturer.stop().ok();
-
-// println!("Done receiving audio frames");
-// }
-// });
-
-// rx.await.unwrap(); // wait for first frame
-
-// controller
-// }
-
fn play_audio(bytes: &'static [u8]) {
use rodio::{Decoder, OutputStream, Sink};
use std::io::Cursor;
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index ec6253aa4..9c2086baa 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -1,170 +1,9 @@
-use serde::Serialize;
-use specta::Type;
-use std::{
- path::PathBuf,
- sync::Arc,
- time::{Duration, Instant, SystemTime},
-};
-use tokio::sync::{oneshot, watch};
+use std::sync::Arc;
-use tauri::{AppHandle, Manager, WebviewUrl};
+use cap_media::feeds::CameraFrameReceiver;
-use crate::{
- capture::CaptureController,
- encoder::{uyvy422_frame, H264Encoder},
-};
-
-#[tauri::command(async)]
-#[specta::specta]
-pub fn list_cameras() -> Vec<String> {
- nokhwa::query(nokhwa::utils::ApiBackend::Auto)
- .unwrap()
- .into_iter()
- .map(|i| i.human_name().to_string())
- .collect()
-}
-
-pub fn find_camera_by_label(label: &str) -> Option<nokhwa::utils::CameraInfo> {
- nokhwa::query(nokhwa::utils::ApiBackend::Auto)
- .unwrap()
- .into_iter()
- .find(|c| &c.human_name() == label)
-}
-
-#[derive(Serialize, Type)]
-pub struct CameraInfo {
- pub human_name: String,
- pub description: String,
-}
-
-// ffmpeg
-// .command
-// .args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
-// .args(["-codec:v", "libx264", "-preset", "ultrafast"])
-// .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
-// .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
-// .args(["-movflags", "frag_keyframe+empty_moov"])
-// .args(["-g", &keyframe_interval_str])
-// .args(["-keyint_min", &keyframe_interval_str])
-// .args([
-// "-vf",
-// &format!(
-// "fps={},scale=in_range=full:out_range=limited",
-// ffmpeg_input.fps
-// ),
-// ])
-// .arg(&output_path);
-
-pub async fn start_capturing(
- output_path: PathBuf,
- camera_feed: &CameraFeed,
- mut start_writing_rx: watch::Receiver<bool>,
-) -> CaptureController {
- let controller = CaptureController::new(output_path);
-
- let (start_tx, start_rx) = oneshot::channel();
-
- let handle = tokio::runtime::Handle::current();
- let mut frames_rx = camera_feed.frame_rx.clone();
- let format = camera_feed.camera_format.clone();
-
- std::thread::spawn({
- let controller = controller.clone();
- move || {
- let mut encoder = H264Encoder::new(
- &controller.output_path,
- format.resolution().width(),
- format.resolution().height(),
- 30.0,
- );
-
- let mut start_tx = Some(start_tx);
-
- let mut scaler = ffmpeg::software::converter(
- (format.resolution().width(), format.resolution().height()),
- nokhwa_format_to_ffmpeg(format.format()),
- H264Encoder::output_format(),
- )
- .unwrap();
-
- let mut last_frame_time = Instant::now();
- let frame_duration = Duration::from_secs_f64(1.0 / 30.0);
-
- loop {
- if controller.is_stopped() {
- println!("Stopping receiving camera frames");
- break;
- }
-
- // Use a non-blocking approach to check for changes
- if frames_rx.has_changed().unwrap_or(false) {
- let frame = frames_rx.borrow_and_update();
- let Some((frame, timestamp)) = frame.as_ref() else {
- continue;
- };
-
- if controller.is_paused() {
- continue;
- }
-
- if let Some(start_tx) = start_tx.take() {
- start_tx.send(Instant::now()).unwrap();
- }
-
- if !*start_writing_rx.borrow_and_update() {
- continue;
- }
-
- let now = Instant::now();
- if now.duration_since(last_frame_time) < frame_duration {
- std::thread::sleep(frame_duration - now.duration_since(last_frame_time));
- }
- last_frame_time = Instant::now();
-
- let yuyv422_frame = uyvy422_frame(
- frame.buffer(),
- frame.resolution().width(),
- frame.resolution().height(),
- );
-
- let mut yuv_frame = ffmpeg::util::frame::Video::empty();
- if let Err(e) = scaler.run(&yuyv422_frame, &mut yuv_frame) {
- eprintln!("Error scaling frame: {:?}", e);
- continue;
- }
-
- encoder.encode_frame(
- yuv_frame,
- timestamp
- .duration_since(SystemTime::UNIX_EPOCH)
- .unwrap()
- .as_millis() as u64,
- );
- } else {
- // If no new frame, sleep for a short duration to avoid busy-waiting
- std::thread::sleep(Duration::from_millis(1));
- }
- }
-
- encoder.close();
- }
- });
-
- start_rx.await.unwrap(); // wait for first frame
-
- controller
-}
-
-fn nokhwa_format_to_ffmpeg(nokhwa_format: nokhwa::utils::FrameFormat) -> ffmpeg::format::Pixel {
- match nokhwa_format {
- nokhwa::utils::FrameFormat::YUYV => ffmpeg::format::Pixel::UYVY422,
- _ => todo!(),
- }
-}
-
-type CameraFrame = (nokhwa::Buffer, SystemTime);
-
-pub async fn create_camera_ws(frame_rx: watch::Receiver<Option<CameraFrame>>) -> u16 {
+// TODO: Possibly replace this with ffmpeg's network outputs in the pipeline somehow?
+pub async fn create_camera_ws(frame_rx: CameraFrameReceiver) -> u16 {
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
@@ -175,7 +14,7 @@ pub async fn create_camera_ws(frame_rx: watch::Receiver<Option<CameraFrame>>) ->
};
use tokio::sync::Mutex;
- type RouterState = Arc<Mutex<watch::Receiver<Option<CameraFrame>>>>;
+ type RouterState = Arc<Mutex<CameraFrameReceiver>>;
async fn ws_handler(
ws: WebSocketUpgrade,
@@ -185,7 +24,7 @@ pub async fn create_camera_ws(frame_rx: watch::Receiver<Option<CameraFrame>>) ->
}
async fn handle_socket(mut socket: WebSocket, state: RouterState) {
- let mut rx = state.lock().await;
+ let camera_rx = state.lock().await;
println!("socket connection established");
let now = std::time::Instant::now();
@@ -194,49 +33,18 @@ pub async fn create_camera_ws(frame_rx: watch::Receiver<Option<CameraFrame>>) ->
_ = socket.recv() => {
break;
}
- _ = rx.changed() => {
- let data = {
- let msg = rx.borrow_and_update();
-
- let Some((buffer, _)) = msg.as_ref() else {
- continue;
- };
-
- let source_fmt = nokhwa_format_to_ffmpeg(buffer.source_frame_format());
- let out_fmt = ffmpeg::format::Pixel::RGBA;
-
- let out_size = (buffer.resolution().width(), buffer.resolution().height());
-
- let mut scaler = ffmpeg::software::converter(
- (buffer.resolution().width(), buffer.resolution().height()),
- source_fmt,
- out_fmt,
- )
- .unwrap();
-
- let uyvy422_frame = uyvy422_frame(
- buffer.buffer(),
- buffer.resolution().width(),
- buffer.resolution().height(),
- );
-
- let mut frame = ffmpeg::frame::Video::empty();
- scaler.run(&uyvy422_frame, &mut frame).unwrap();
-
- let mut data = frame.data(0).to_vec();
-
- let height_bytes: [u8; 4] = out_size.1.to_le_bytes();
- data.extend_from_slice(height_bytes.as_slice());
- let width_bytes: [u8; 4] = out_size.0.to_le_bytes();
- data.extend_from_slice(width_bytes.as_slice());
-
- data
- };
-
- socket.send(Message::Binary(data)).await.unwrap();
+ incoming_frame = camera_rx.recv_async() => {
+ match incoming_frame {
+ Ok(data) => socket.send(Message::Binary(data)).await.unwrap(),
+ Err(_) => {
+ tracing::warn!("Connection has been lost! Shutting down camera server");
+ break;
+ },
+ }
}
}
}
+
let elapsed = now.elapsed();
println!("Websocket closing after {elapsed:.2?}");
}
@@ -255,82 +63,3 @@ pub async fn create_camera_ws(frame_rx: watch::Receiver<Option<CameraFrame>>) ->
port
}
-
-pub type LatestFrame = Option<(nokhwa::Buffer, SystemTime)>;
-
-pub struct CameraFeed {
- pub camera_info: nokhwa::utils::CameraInfo,
- pub camera_format: nokhwa::utils::CameraFormat,
- pub frame_rx: watch::Receiver<LatestFrame>,
- shutdown_tx: Option<oneshot::Sender<()>>,
-}
-
-impl CameraFeed {
- pub async fn new(label: &str, frame_tx: watch::Sender<LatestFrame>) -> Self {
- let camera_info = find_camera_by_label(&label).unwrap();
-
- use nokhwa::{pixel_format::*, utils::*, *};
-
- let format =
- RequestedFormat::new::<RgbFormat>(RequestedFormatType::Closest(CameraFormat::new(
- Resolution {
- width_x: 1920,
- height_y: 1080,
- },
- FrameFormat::YUYV,
- 30,
- )));
-
- let (shutdown_tx, mut shutdown_rx) = oneshot::channel();
-
- let (setup_tx, setup_rx) = oneshot::channel();
-
- let frame_rx = frame_tx.subscribe();
-
- std::thread::spawn({
- let camera_info = camera_info.clone();
- move || {
- let mut camera =
- Camera::new(camera_info.index().clone(), format).unwrap_or_else(|_| {
- Camera::new(
- camera_info.index().clone(),
- RequestedFormat::new::<RgbFormat>(
- RequestedFormatType::AbsoluteHighestResolution,
- ),
- )
- .expect("Failed to create camera")
- });
-
- camera.open_stream().unwrap();
-
- setup_tx.send(camera.camera_format()).unwrap();
-
- loop {
- if shutdown_rx.try_recv().is_ok() {
- return;
- }
-
- let frame = camera.frame().unwrap();
- let timestamp = SystemTime::now();
-
- frame_tx.send(Some((frame, timestamp))).unwrap();
- }
- }
- });
-
- let camera_format = setup_rx.await.unwrap();
-
- Self {
- camera_info,
- camera_format,
- frame_rx,
- shutdown_tx: Some(shutdown_tx),
- }
- }
-}
-
-impl Drop for CameraFeed {
- fn drop(&mut self) {
- self.shutdown_tx.take().unwrap().send(()).unwrap();
- }
-}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 3c456f250..d1d677eff 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -17,10 +17,13 @@ mod windows;
use audio::AppSounds;
use auth::AuthStore;
-use camera::{list_cameras, CameraFeed};
use cap_editor::{AudioData, EditorState, ProjectRecordings};
use cap_editor::{EditorInstance, FRAMES_WS_PATH};
-use cap_media::{platform::Bounds, sources::ScreenCaptureTarget};
+use cap_media::{
+ feeds::{CameraFeed, CameraFrameSender},
+ platform::Bounds,
+ sources::{AudioInputSource, ScreenCaptureTarget},
+};
use cap_project::{
ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,
};
@@ -32,7 +35,7 @@ use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
use num_traits::ToBytes;
use png::{ColorType, Encoder};
-use recording::{list_capture_windows, InProgressRecording, FPS};
+use recording::{list_cameras, list_capture_windows, InProgressRecording, FPS};
use scap::capturer::Capturer;
use scap::frame::Frame;
use serde::{Deserialize, Serialize};
@@ -51,7 +54,6 @@ use tauri_nspanel::ManagerExt;
use tauri_plugin_notification::PermissionState;
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
-use tokio::sync::watch;
use tokio::task;
use tokio::{
sync::{Mutex, RwLock},
@@ -83,10 +85,10 @@ impl RecordingOptions {
pub struct App {
start_recording_options: RecordingOptions,
#[serde(skip)]
- camera_tx: watch::Sender<camera::LatestFrame>,
+ camera_tx: CameraFrameSender,
camera_ws_port: u16,
#[serde(skip)]
- camera_feed: Option<camera::CameraFeed>,
+ camera_feed: Option<CameraFeed>,
#[serde(skip)]
handle: AppHandle,
#[serde(skip)]
@@ -120,7 +122,7 @@ impl App {
CurrentRecordingChanged(json).emit(&self.handle).ok();
if let ScreenCaptureTarget::Window { .. } = &current_recording.display_source {
- CapWindow::WindowCaptureOccluder.show(&self.handle);
+ let _ = CapWindow::WindowCaptureOccluder.show(&self.handle);
} else {
self.close_occluder_window();
}
@@ -157,14 +159,14 @@ impl App {
match &new_options.camera_label {
Some(camera_label) => {
- if self
- .camera_feed
- .as_ref()
- .map(|f| &f.camera_info.human_name() != camera_label)
- .unwrap_or(true)
- {
- self.camera_feed =
- Some(CameraFeed::new(&camera_label, self.camera_tx.clone()).await);
+ if self.camera_feed.is_none() {
+ self.camera_feed = CameraFeed::init(&camera_label, self.camera_tx.clone())
+ .await
+ .ok();
+ }
+
+ if let Some(camera_feed) = self.camera_feed.as_mut() {
+ camera_feed.switch_cameras(&camera_label).await.ok();
}
}
None => {
@@ -1390,8 +1392,9 @@ async fn list_audio_devices() -> Result<Vec<String>, ()> {
return Ok(vec![]);
}
+ // TODO: Check - is this necessary? `spawn_blocking` is quite a bit of overhead.
tokio::task::spawn_blocking(|| {
- let devices = audio::get_input_devices();
+ let devices = AudioInputSource::get_devices();
devices.keys().cloned().collect()
})
@@ -2142,7 +2145,7 @@ pub async fn run() {
)
.expect("Failed to export typescript bindings");
- let (camera_tx, camera_rx) = watch::channel(None);
+ let (camera_tx, camera_rx) = CameraFeed::create_channel();
let camera_ws_port = camera::create_camera_ws(camera_rx.clone()).await;
tauri::async_runtime::set(tokio::runtime::Handle::current());
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index c15c706c2..af4ac383d 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,33 +1,17 @@
-// use crate::audio::AudioCapturer;
-use crate::camera::CameraFeed;
-// use crate::capture::CaptureController;
use crate::flags;
-// use cap_ffmpeg::{FFmpeg, FFmpegInput, FFmpegProcess, FFmpegRawAudioInput};
-use cap_media::{encoders::*, filters::*, pipeline::*, sources::*, MediaError};
+use cap_media::{encoders::*, feeds::*, filters::*, pipeline::*, sources::*, MediaError};
use device_query::{DeviceQuery, DeviceState};
-use futures::future::OptionFuture;
use serde::Deserialize;
use serde::Serialize;
use specta::Type;
-use std::time::{Instant, SystemTime, UNIX_EPOCH};
-use std::{
- fs::File,
- sync::{Arc, Mutex},
-};
+use std::time::{SystemTime, UNIX_EPOCH};
use std::{path::PathBuf, time::Duration};
-use tauri::AppHandle;
-use tokio::sync::watch;
use objc::rc::autoreleasepool;
use objc::runtime::{Class, Object, Sel, BOOL, NO, YES};
use objc::*;
-use crate::{
- audio,
- camera,
- // display::{self, get_window_bounds, CaptureTarget},
- RecordingOptions,
-};
+use crate::RecordingOptions;
// TODO: Hacky, please fix
pub const FPS: u32 = 30;
@@ -38,6 +22,12 @@ pub fn list_capture_windows() -> Vec<CaptureWindow> {
ScreenCaptureSource::list_targets()
}
+#[tauri::command(async)]
+#[specta::specta]
+pub fn list_cameras() -> Vec<String> {
+ CameraFeed::list_cameras()
+}
+
#[derive(Serialize, Deserialize, Clone, Type)]
pub struct MouseEvent {
pub active_modifiers: Vec<String>,
@@ -185,14 +175,11 @@ pub async fn start(
let screen_source = ScreenCaptureSource::init(&recording_options.capture_target, None, None);
let screen_config = screen_source.info();
- let screen_filter = VideoFilter::init(
- "screen",
- screen_config,
- "scale=in_range=full:out_range=limited",
- )?;
+ let output_config = screen_config.scaled(1920, 30);
+ let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
let screen_encoder = H264Encoder::init(
"screen",
- screen_config,
+ output_config,
Output::File(display_output_path.clone()),
)?;
pipeline_builder = pipeline_builder
@@ -217,18 +204,15 @@ pub async fn start(
.sink("microphone_encoder", mic_encoder);
}
- if let Some(camera_source) = CameraSource::init(recording_options.camera_label.as_ref()) {
+ if let Some(camera_source) = CameraSource::init(camera_feed) {
let camera_config = camera_source.info();
+ let output_config = camera_config.scaled(1920, 30);
camera_output_path = Some(content_dir.join("camera.mp4"));
- let camera_filter = VideoFilter::init(
- "camera",
- camera_config,
- "scale=in_range=full:out_range=limited",
- )?;
+ let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
let camera_encoder = H264Encoder::init(
"camera",
- camera_config,
+ output_config,
Output::File(camera_output_path.clone().unwrap()),
)?;
diff --git a/crates/media/src/data.rs b/crates/media/src/data.rs
index 7aa4c7057..470d087f1 100644
--- a/crates/media/src/data.rs
+++ b/crates/media/src/data.rs
@@ -21,9 +21,11 @@ pub enum RawAudioFormat {
pub enum RawVideoFormat {
Bgra,
+ Mjpeg,
Yuyv,
RawRgb,
Nv12,
+ Gray,
}
impl From<RawAudioFormat> for Sample {
@@ -109,9 +111,11 @@ impl VideoInfo {
Self {
pixel_format: match format {
RawVideoFormat::Bgra => Pixel::BGRA,
+ RawVideoFormat::Mjpeg => Pixel::YUVJ422P,
RawVideoFormat::Yuyv => Pixel::UYVY422,
RawVideoFormat::RawRgb => Pixel::RGB24,
RawVideoFormat::Nv12 => Pixel::NV12,
+ RawVideoFormat::Gray => Pixel::GRAY8,
},
width,
height,
@@ -120,6 +124,27 @@ impl VideoInfo {
}
}
+ pub fn scaled(&self, width: u32, fps: u32) -> Self {
+ let (width, height) = match self.width <= width {
+ true => (self.width, self.height),
+ false => {
+ let new_width = width & !1;
+ let new_height = (((new_width as f32) * (self.height as f32) / (self.width as f32))
+ .round() as u32)
+ & !1;
+ (new_width, new_height)
+ }
+ };
+
+ Self {
+ pixel_format: Pixel::YUV420P,
+ width,
+ height,
+ time_base: self.time_base,
+ frame_rate: FFRational(fps.try_into().unwrap(), 1),
+ }
+ }
+
pub fn pixel_format_int(&self) -> i32 {
// This is necessary because the AVPixelFormat C enum has specific integer values that
// the Rust PixelFormat enum doesn't replicate. But there is a From/Into conversion
diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rs
index b3be5954e..6812812b1 100644
--- a/crates/media/src/encoders/h264.rs
+++ b/crates/media/src/encoders/h264.rs
@@ -35,8 +35,8 @@ impl H264Encoder {
encoder.set_width(config.width);
encoder.set_height(config.height);
- encoder.set_format(Pixel::YUV420P);
- encoder.set_time_base(config.time_base);
+ encoder.set_format(config.pixel_format);
+ encoder.set_time_base(config.frame_rate.invert());
let video_encoder = encoder.open_with(options)?;
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
new file mode 100644
index 000000000..18b9ae046
--- /dev/null
+++ b/crates/media/src/feeds/camera.rs
@@ -0,0 +1,351 @@
+use ffmpeg::software::scaling;
+use flume::{Receiver, Sender, TryRecvError};
+use nokhwa::{pixel_format::*, utils::*, Camera};
+use std::{
+ thread::{self, JoinHandle},
+ time::Instant,
+};
+
+use crate::{
+ data::{FFVideo, RawVideoFormat, VideoInfo},
+ MediaError,
+};
+
+type CameraSwitchResult = Result<(CameraInfo, VideoInfo), MediaError>;
+
+enum CameraControl {
+ Switch(String, Sender<CameraSwitchResult>),
+ AttachRawConsumer(Sender<RawCameraFrame>),
+ Shutdown,
+}
+
+pub type CameraFrameSender = Sender<Vec<u8>>;
+pub type CameraFrameReceiver = Receiver<Vec<u8>>;
+
+pub struct RawCameraFrame {
+ pub(crate) frame: FFVideo,
+ pub(crate) captured_at: Instant,
+}
+
+pub struct CameraConnection {
+ control: Sender<CameraControl>,
+}
+
+impl CameraConnection {
+ pub fn attach(&self) -> Receiver<RawCameraFrame> {
+ let (sender, receiver) = flume::bounded(60);
+ self.control
+ .send(CameraControl::AttachRawConsumer(sender))
+ .unwrap();
+
+ receiver
+ }
+}
+
+pub struct CameraFeed {
+ camera_info: CameraInfo,
+ video_info: VideoInfo,
+ control: Sender<CameraControl>,
+ join_handle: JoinHandle<()>,
+}
+
+impl CameraFeed {
+ pub fn create_channel() -> (CameraFrameSender, CameraFrameReceiver) {
+ flume::bounded(60)
+ }
+
+ pub async fn init(
+ selected_camera: &String,
+ rgba_data: Sender<Vec<u8>>,
+ ) -> Result<CameraFeed, MediaError> {
+ tracing::debug!("Selected camera: {:?}", selected_camera);
+
+ let camera_info = find_camera(&selected_camera)?;
+ let (control, control_receiver) = flume::bounded(1);
+
+ let (video_info, join_handle) =
+ start_capturing(camera_info.clone(), control_receiver, rgba_data).await?;
+
+ let camera_feed = Self {
+ camera_info,
+ video_info,
+ control,
+ join_handle,
+ };
+
+ Ok(camera_feed)
+ }
+
+ pub fn list_cameras() -> Vec<String> {
+ nokhwa::query(ApiBackend::Auto)
+ .unwrap()
+ .into_iter()
+ .map(|i| i.human_name().to_string())
+ .collect()
+ }
+
+ pub fn video_info(&self) -> VideoInfo {
+ self.video_info
+ }
+
+ pub async fn switch_cameras(&mut self, camera_name: &String) -> Result<(), MediaError> {
+ let current_camera_name = self.camera_info.human_name();
+ if camera_name != &current_camera_name {
+ let (result_tx, result_rx) = flume::bounded::<CameraSwitchResult>(1);
+
+ let _ = self
+ .control
+ .send_async(CameraControl::Switch(camera_name.clone(), result_tx))
+ .await;
+
+ let (camera_info, video_info) = result_rx
+ .recv_async()
+ .await
+ .map_err(|_| MediaError::Any("Failed to prepare camera feed"))??;
+
+ self.camera_info = camera_info;
+ self.video_info = video_info;
+ }
+
+ Ok(())
+ }
+
+ pub fn create_connection(&self) -> CameraConnection {
+ CameraConnection {
+ control: self.control.clone(),
+ }
+ }
+}
+
+impl Drop for CameraFeed {
+ fn drop(&mut self) {
+ let _ = self.control.send(CameraControl::Shutdown);
+ }
+}
+
+fn find_camera(selected_camera: &String) -> Result<CameraInfo, MediaError> {
+ let all_cameras = nokhwa::query(ApiBackend::Auto)?;
+
+ all_cameras
+ .into_iter()
+ .find(|c| &c.human_name() == selected_camera)
+ .ok_or(MediaError::DeviceUnreachable(selected_camera.clone()))
+}
+
+fn create_camera(info: &CameraInfo) -> Result<Camera, MediaError> {
+ // TODO: Make selected format more flexible
+ // let format = RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestResolution);
+ let format =
+ RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Closest(CameraFormat::new(
+ Resolution {
+ width_x: 1920,
+ height_y: 1080,
+ },
+ FrameFormat::YUYV,
+ 30,
+ )));
+ let index = info.index().clone();
+ Ok(Camera::new(index, format)?)
+}
+
+fn find_and_create_camera(selected_camera: &String) -> Result<(CameraInfo, Camera), MediaError> {
+ let info = find_camera(selected_camera)?;
+ let camera = create_camera(&info)?;
+
+ Ok((info, camera))
+}
+
+async fn start_capturing(
+ camera_info: CameraInfo,
+ control: Receiver<CameraControl>,
+ rgba_data: Sender<Vec<u8>>,
+) -> Result<(VideoInfo, JoinHandle<()>), MediaError> {
+ let (ready_tx, ready_rx) = flume::bounded::<Result<VideoInfo, MediaError>>(1);
+
+ let join_handle = thread::spawn(move || {
+ run_camera_feed(camera_info, control, rgba_data, ready_tx);
+ });
+
+ let video_info = ready_rx
+ .recv_async()
+ .await
+ .map_err(|_| MediaError::Any("Failed to prepare camera feed"))??;
+
+ Ok((video_info, join_handle))
+}
+
+#[tracing::instrument(skip_all)]
+fn run_camera_feed(
+ camera_info: CameraInfo,
+ control: Receiver<CameraControl>,
+ rgba_data: Sender<Vec<u8>>,
+ ready_signal: Sender<Result<VideoInfo, MediaError>>,
+) {
+ let mut maybe_raw_data: Option<Sender<RawCameraFrame>> = None;
+
+ let mut camera = match create_camera(&camera_info) {
+ Ok(cam) => cam,
+ Err(error) => {
+ ready_signal.send(Err(error)).unwrap();
+ return;
+ }
+ };
+
+ let mut converter = FrameConverter::build(camera.camera_format());
+
+ if let Err(error) = camera.open_stream() {
+ ready_signal.send(Err(error.into())).unwrap();
+ return;
+ }
+
+ ready_signal.send(Ok(converter.video_info)).unwrap();
+ tracing::info!("Launched camera feed");
+
+ loop {
+ match control.try_recv() {
+ Err(TryRecvError::Disconnected) => {
+ tracing::info!("Control receiver is unreachable! Shutting down");
+ break;
+ }
+ Err(TryRecvError::Empty) => {
+ // No signal received, nothing to do
+ }
+ Ok(CameraControl::Shutdown) => {
+ tracing::info!("Shutdown request received.");
+ break;
+ }
+ Ok(CameraControl::AttachRawConsumer(rgba_sender)) => {
+ tracing::warn!("Attaching to a new pipeline consumer. Any previously attached consumer will be dropped");
+ maybe_raw_data = Some(rgba_sender);
+ }
+ Ok(CameraControl::Switch(camera_name, switch_result)) => {
+ if maybe_raw_data.is_some() {
+ switch_result.send(Err(MediaError::Any("Cannot switch cameras while the feed is attached to a running pipeline"))).unwrap();
+ } else {
+ tracing::info!("Switching camera to {camera_name}");
+
+ match find_and_create_camera(&camera_name) {
+ Err(error) => {
+ tracing::error!("{error}");
+ switch_result.send(Err(error)).unwrap();
+ }
+ Ok((new_info, mut new_camera)) => {
+ let new_format = new_camera.camera_format();
+ let new_converter = FrameConverter::build(new_format);
+
+ if new_camera.open_stream().is_ok() {
+ tracing::info!("Now using {camera_name}");
+ let _ = camera.stop_stream();
+ switch_result
+ .send(Ok((new_info, new_converter.video_info)))
+ .unwrap();
+ camera = new_camera;
+ converter = new_converter;
+ } else {
+ tracing::warn!(
+ "Unable to switch to {camera_name}. Still using previous camera"
+ );
+ switch_result
+ .send(Err(MediaError::DeviceUnreachable(camera_name)))
+ .unwrap();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Actual data capture
+ let raw_buffer = camera.frame().unwrap();
+ // TODO: Merge fix in nokhwa lib to use presentation timestamps from the system, like scap does
+ let captured_at = Instant::now();
+
+ let rgba_frame = converter.rgba(&raw_buffer);
+
+ if dropping_send(&rgba_data, rgba_frame).is_err() {
+ // TODO: Also allow changing the connection?
+ tracing::error!("Camera preview has been disconnected. Shutting down feed");
+ break;
+ }
+
+ if let Some(ref raw_data) = maybe_raw_data {
+ let frame = RawCameraFrame {
+ frame: converter.raw(&raw_buffer),
+ captured_at,
+ };
+ if dropping_send(raw_data, frame).is_err() {
+ tracing::warn!("Raw data consumer has been disconnected.");
+ maybe_raw_data = None;
+ }
+ }
+ }
+
+ let _ = camera.stop_stream();
+ tracing::info!("Closed {} stream", camera.info().human_name());
+}
+
+struct FrameConverter {
+ video_info: VideoInfo,
+ context: scaling::Context,
+}
+
+impl FrameConverter {
+ fn build(camera_format: CameraFormat) -> Self {
+ let format = match camera_format.format() {
+ FrameFormat::MJPEG => RawVideoFormat::Mjpeg,
+ FrameFormat::YUYV => RawVideoFormat::Yuyv,
+ FrameFormat::NV12 => RawVideoFormat::Nv12,
+ FrameFormat::GRAY => RawVideoFormat::Gray,
+ FrameFormat::RAWRGB => RawVideoFormat::RawRgb,
+ };
+
+ let video_info = VideoInfo::from_raw(
+ format,
+ camera_format.width(),
+ camera_format.height(),
+ camera_format.frame_rate(),
+ );
+
+ let context = ffmpeg::software::converter(
+ (video_info.width, video_info.height),
+ video_info.pixel_format,
+ ffmpeg::format::Pixel::RGBA,
+ )
+ .unwrap();
+
+ Self {
+ video_info,
+ context,
+ }
+ }
+
+ fn rgba(&mut self, buffer: &nokhwa::Buffer) -> Vec<u8> {
+ let resolution = buffer.resolution();
+
+ let input_frame = self.video_info.wrap_frame(buffer.buffer(), 0);
+ let mut rgba_frame = FFVideo::empty();
+
+ self.context.run(&input_frame, &mut rgba_frame).unwrap();
+
+ let mut data = rgba_frame.data(0).to_vec();
+
+ data.extend_from_slice(&resolution.height().to_le_bytes());
+ data.extend_from_slice(&resolution.width().to_le_bytes());
+
+ data
+ }
+
+ fn raw(&mut self, buffer: &nokhwa::Buffer) -> FFVideo {
+ self.video_info.wrap_frame(buffer.buffer(), 0)
+ }
+}
+
+fn dropping_send<T>(sender: &Sender<T>, value: T) -> Result<(), flume::SendError<T>> {
+ sender.try_send(value).or_else(|error| match error {
+ flume::TrySendError::Full(_) => {
+ tracing::warn!("Channel is full. Dropping camera frame");
+ Ok(())
+ }
+ flume::TrySendError::Disconnected(v) => Err(flume::SendError(v)),
+ })
+}
diff --git a/crates/media/src/feeds/mod.rs b/crates/media/src/feeds/mod.rs
new file mode 100644
index 000000000..68bffd7df
--- /dev/null
+++ b/crates/media/src/feeds/mod.rs
@@ -0,0 +1,3 @@
+mod camera;
+
+pub use camera::*;
diff --git a/crates/media/src/filters/video.rs b/crates/media/src/filters/video.rs
index 9845269fb..5789a893a 100644
--- a/crates/media/src/filters/video.rs
+++ b/crates/media/src/filters/video.rs
@@ -13,27 +13,41 @@ pub struct VideoFilter {
}
impl VideoFilter {
- pub fn init(tag: &'static str, config: VideoInfo, spec: &str) -> Result<Self, MediaError> {
+ pub fn init(
+ tag: &'static str,
+ input_config: VideoInfo,
+ output_config: VideoInfo,
+ ) -> Result<Self, MediaError> {
let mut filter_graph = filter::Graph::new();
let input_args = format!(
"pix_fmt={}:width={}:height={}:time_base={}/{}",
- config.pixel_format_int(),
- config.width,
- config.height,
- config.time_base.numerator(),
- config.time_base.denominator()
+ input_config.pixel_format_int(),
+ input_config.width,
+ input_config.height,
+ input_config.time_base.numerator(),
+ input_config.time_base.denominator()
);
filter_graph.add(&filter::find("buffer").unwrap(), "in", &input_args)?;
filter_graph.add(&filter::find("buffersink").unwrap(), "out", "")?;
let mut input = filter_graph.get("in").unwrap();
- input.set_pixel_format(config.pixel_format);
+ input.set_pixel_format(input_config.pixel_format);
let mut output = filter_graph.get("out").unwrap();
- output.set_pixel_format(Pixel::YUV420P);
-
- filter_graph.output("in", 0)?.input("out", 0)?.parse(spec)?;
+ output.set_pixel_format(output_config.pixel_format);
+
+ // TODO: Remove fps hardcoding?
+ let spec = format!(
+ "scale={}x{}:flags=bilinear,fps=fps={}",
+ output_config.width,
+ output_config.height,
+ output_config.frame_rate.numerator()
+ );
+ filter_graph
+ .output("in", 0)?
+ .input("out", 0)?
+ .parse(&spec)?;
filter_graph.validate()?;
Ok(Self { filter_graph, tag })
diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs
index 6565b06f8..54748b150 100644
--- a/crates/media/src/lib.rs
+++ b/crates/media/src/lib.rs
@@ -8,6 +8,7 @@ use thiserror::Error;
pub mod data;
pub mod encoders;
+pub mod feeds;
pub mod filters;
pub mod pipeline;
pub mod platform;
@@ -36,6 +37,12 @@ pub enum MediaError {
#[error("FFmpeg error: {0}")]
FFmpeg(#[from] ffmpeg::Error),
+ #[error("Camera error: {0}")]
+ Nokhwa(#[from] nokhwa::NokhwaError),
+
#[error("Could not find a suitable codec for {0}")]
MissingCodec(&'static str),
+
+ #[error("Device {0} is unreachable. It may have been disconnected")]
+ DeviceUnreachable(String),
}
diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rs
index 1a89c8bd5..527f2e745 100644
--- a/crates/media/src/sources/camera.rs
+++ b/crates/media/src/sources/camera.rs
@@ -1,71 +1,70 @@
-use flume::Sender;
-use nokhwa::{pixel_format::*, utils::*, Camera};
+use flume::{Receiver, Sender};
use std::time::Instant;
use crate::{
- data::{FFVideo, RawVideoFormat, VideoInfo},
+ data::{FFVideo, VideoInfo},
+ feeds::{CameraConnection, CameraFeed, RawCameraFrame},
pipeline::{clock::SynchronisedClock, control::Control, task::PipelineSourceTask},
MediaError,
};
-fn create_camera(camera_info: &CameraInfo) -> Result<Camera, ()> {
- let format = RequestedFormat::new::<RgbFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
- Camera::new(camera_info.index().clone(), format).map_err(|error| {
- tracing::error!("Error while initializing camera: {error}");
- })
-}
-
pub struct CameraSource {
- info: CameraInfo,
- format: CameraFormat,
+ feed_connection: CameraConnection,
+ video_info: VideoInfo,
}
impl CameraSource {
- pub fn init(selected_camera: Option<&String>) -> Option<Self> {
- tracing::debug!("Selected camera: {:?}", selected_camera);
+ pub fn init(camera_feed: Option<&CameraFeed>) -> Option<Self> {
+ camera_feed.map(|feed| Self {
+ feed_connection: feed.create_connection(),
+ video_info: feed.video_info(),
+ })
+ }
- let cameras = nokhwa::query(ApiBackend::Auto).unwrap();
+ pub fn info(&self) -> VideoInfo {
+ self.video_info
+ }
- selected_camera
- .and_then(|camera_name| cameras.into_iter().find(|c| &c.human_name() == camera_name))
- .and_then(|camera_info| create_camera(&camera_info).ok())
- .and_then(|camera| {
- let format = camera.camera_format();
- if format_for(format.format()).is_some() {
- return Some(Self {
- info: camera.info().clone(),
- format,
- });
+ fn process_frame(
+ &self,
+ clock: &mut SynchronisedClock<Instant>,
+ output: &Sender<FFVideo>,
+ camera_frame: RawCameraFrame,
+ ) -> Result<(), MediaError> {
+ let RawCameraFrame {
+ mut frame,
+ captured_at,
+ } = camera_frame;
+ match clock.timestamp_for(captured_at) {
+ None => {
+ tracing::warn!("Clock is currently stopped. Dropping frames.");
+ }
+ Some(timestamp) => {
+ frame.set_pts(Some(timestamp));
+ if let Err(_) = output.send(frame) {
+ return Err(MediaError::Any("Pipeline is unreachable! Stopping capture"));
}
+ }
+ }
- None
- })
- }
-
- pub fn list_cameras() -> Vec<String> {
- nokhwa::query(ApiBackend::Auto)
- .unwrap()
- .into_iter()
- .map(|i| i.human_name().to_string())
- .collect()
+ Ok(())
}
- pub fn info(&self) -> VideoInfo {
- VideoInfo::from_raw(
- format_for(self.format.format()).unwrap(),
- self.format.width(),
- self.format.height(),
- self.format.frame_rate(),
- )
- }
-}
+ fn pause_and_drain_frames(
+ &self,
+ clock: &mut SynchronisedClock<Instant>,
+ output: &Sender<FFVideo>,
+ frames_rx: Receiver<RawCameraFrame>,
+ ) {
+ let frames: Vec<RawCameraFrame> = frames_rx.drain().collect();
+ drop(frames_rx);
-fn format_for(format: FrameFormat) -> Option<RawVideoFormat> {
- match format {
- FrameFormat::YUYV => Some(RawVideoFormat::Yuyv),
- FrameFormat::RAWRGB => Some(RawVideoFormat::RawRgb),
- FrameFormat::NV12 => Some(RawVideoFormat::Nv12),
- _ => None,
+ for frame in frames {
+ if let Err(error) = self.process_frame(clock, output, frame) {
+ tracing::error!("{error}");
+ break;
+ }
+ }
}
}
@@ -83,76 +82,42 @@ impl PipelineSourceTask for CameraSource {
output: Sender<Self::Output>,
) {
tracing::info!("Preparing camera source thread...");
-
- match create_camera(&self.info) {
- Ok(mut camera) if camera.camera_format() == self.format => {
- ready_signal.send(Ok(())).unwrap();
- let mut capturing = false;
- let info = self.info();
-
- loop {
- match control_signal.last() {
- Some(Control::Play) => {
- if !capturing {
- camera
- .open_stream()
- .expect("Failed to start camera recording");
- capturing = true;
-
- tracing::info!("Camera recording started.");
- }
-
- match camera.frame() {
- // TODO: Set PTS in nokhwa library
- Ok(frame) => match clock.timestamp_for(Instant::now()) {
- None => {
- tracing::warn!(
- "Clock is currently stopped. Dropping frames."
- )
- }
- Some(timestamp) => {
- let buffer = info.wrap_frame(
- frame.buffer(),
- timestamp.try_into().unwrap(),
- );
- if let Err(_) = output.send(buffer) {
- tracing::warn!(
- "Pipeline is unreachable. Dropping samples."
- )
- }
- }
- },
- Err(error) => {
- tracing::error!("Capture error: {error}");
- break;
- }
+ let mut frames_rx: Option<Receiver<RawCameraFrame>> = None;
+ ready_signal.send(Ok(())).unwrap();
+
+ loop {
+ match control_signal.last() {
+ Some(Control::Play) => {
+ let frames = frames_rx.get_or_insert_with(|| self.feed_connection.attach());
+
+ match frames.recv() {
+ Ok(frame) => {
+ if let Err(error) = self.process_frame(&mut clock, &output, frame) {
+ tracing::error!("{error}");
+ break;
}
}
- Some(Control::Pause) => {
- if capturing {
- camera
- .stop_stream()
- .expect("Failed to halt camera recording");
- capturing = false;
- }
- }
- Some(Control::Shutdown) | None => {
- if capturing {
- camera
- .stop_stream()
- .expect("Failed to halt camera recording");
- }
+ Err(_) => {
+ tracing::error!("Lost connection with the camera feed");
break;
}
}
}
+ Some(Control::Pause) => {
+ // TODO: This blocks to process frames in the queue, which may delay resumption
+ // Some way to prevent this from delaying the listen loop?
+ if let Some(rx) = frames_rx.take() {
+ self.pause_and_drain_frames(&mut clock, &output, rx);
+ }
+ }
+ Some(Control::Shutdown) | None => {
+ if let Some(rx) = frames_rx.take() {
+ self.pause_and_drain_frames(&mut clock, &output, rx);
+ }
+ break;
+ }
}
- _ => ready_signal
- .send(Err(MediaError::TaskLaunch(
- "Failed to create camera stream".into(),
- )))
- .unwrap(),
- };
+ }
tracing::info!("Shutting down screen capture source thread.");
}
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index 3071dcc61..fd05de351 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -169,6 +169,7 @@ impl AsyncVideoDecoder {
};
if stream.index() == input_stream_index {
+ let start_offset = stream.start_time();
let packet_frame =
ts_to_frame(packet.pts().unwrap(), time_base, frame_rate);
// println!("sending frame {packet_frame} packet");
@@ -179,7 +180,7 @@ impl AsyncVideoDecoder {
while decoder.receive_frame(&mut temp_frame).is_ok() {
let current_frame = ts_to_frame(
- temp_frame.pts().unwrap(),
+ temp_frame.pts().unwrap() - start_offset,
time_base,
frame_rate,
);