Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

microphone recording

Brendan Allanaea9a10eb56c
diff --git a/Cargo.lock b/Cargo.lock
index b055b21d2..909533788 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -856,7 +856,7 @@ dependencies = [
"fix-path-env",
"futures",
"image 0.24.9",
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"jpeg-encoder",
"keyboard-types",
"nix 0.20.2",
@@ -1693,14 +1693,17 @@ dependencies = [
"cocoa 0.26.0",
"core-foundation 0.10.0",
"core-graphics 0.24.0",
+ "cpal",
"ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)",
"futures",
"futures-intrusive",
"image 0.25.2",
+ "indexmap 2.5.0",
"mp4",
"nix 0.29.0",
"nokhwa",
"nokhwa-bindings-macos",
+ "num-traits",
"objc",
"objc2-app-kit",
"scap",
@@ -1718,6 +1721,7 @@ dependencies = [
"tauri-plugin-shell",
"tauri-specta",
"tokio",
+ "tracing",
"uuid",
"wgpu",
]
@@ -2741,7 +2745,7 @@ dependencies = [
"futures-sink",
"futures-util",
"http 0.2.12",
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"slab",
"tokio",
"tokio-util",
@@ -3156,9 +3160,9 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.4.0"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93ead53efc7ea8ed3cfb0c79fc8023fbb782a5432b52830b6518941cebe6505c"
+checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5"
dependencies = [
"equivalent",
"hashbrown 0.14.5",
@@ -3819,7 +3823,7 @@ dependencies = [
"cfg_aliases 0.1.1",
"codespan-reporting",
"hexf-parse",
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"log",
"rustc-hash",
"spirv",
@@ -4758,7 +4762,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42cf17e9a1800f5f396bc67d193dc9411b59012a5876445ef450d449881e1016"
dependencies = [
"base64 0.22.1",
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"quick-xml 0.32.0",
"serde",
"time",
@@ -5813,7 +5817,7 @@ dependencies = [
"chrono",
"hex",
"indexmap 1.9.3",
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"serde",
"serde_derive",
"serde_json",
@@ -7037,7 +7041,7 @@ version = "0.19.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
dependencies = [
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"serde",
"serde_spanned",
"toml_datetime 0.6.3",
@@ -7050,7 +7054,7 @@ version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"
dependencies = [
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"serde",
"serde_spanned",
"toml_datetime 0.6.3",
@@ -7834,7 +7838,7 @@ dependencies = [
"bitflags 2.6.0",
"cfg_aliases 0.1.1",
"document-features",
- "indexmap 2.4.0",
+ "indexmap 2.5.0",
"log",
"naga",
"once_cell",
diff --git a/apps/desktop-solid/src-tauri/Cargo.toml b/apps/desktop-solid/src-tauri/Cargo.toml
index 3d2bbd8fd..db0d72fa1 100644
--- a/apps/desktop-solid/src-tauri/Cargo.toml
+++ b/apps/desktop-solid/src-tauri/Cargo.toml
@@ -59,3 +59,7 @@ cap-rendering = { path = "../../../crates/rendering" }
cap-ffmpeg = { path = "../../../crates/ffmpeg" }
axum = { version = "0.7.5", features = ["ws"] }
tauri-plugin-dialog = "2.0.0-rc.0"
+tracing = "0.1.40"
+cpal = "0.15.3"
+indexmap = "2.5.0"
+num-traits = "0.2.19"
diff --git a/apps/desktop-solid/src-tauri/src/audio.rs b/apps/desktop-solid/src-tauri/src/audio.rs
new file mode 100644
index 000000000..8c515730e
--- /dev/null
+++ b/apps/desktop-solid/src-tauri/src/audio.rs
@@ -0,0 +1,257 @@
+use cap_ffmpeg::NamedPipeCapture;
+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
+use cpal::{Device, SampleFormat, SizedSample, Stream, SupportedStreamConfig};
+use indexmap::IndexMap;
+use num_traits::ToBytes;
+use std::sync::atomic::Ordering;
+use std::time::Instant;
+use std::{path::PathBuf, sync::Arc};
+use tokio::sync::mpsc::error::TrySendError;
+use tokio::sync::oneshot;
+use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};
+
+type SampleReceiver = mpsc::Receiver<Arc<Vec<u8>>>;
+
+pub struct AudioCapturer {
+ device: Device,
+ pub device_name: String,
+ config: SupportedStreamConfig,
+ sample_receiver: Option<SampleReceiver>,
+ stream: Option<Stream>,
+ // event_rx: Option<mpsc::Receiver<()>>,
+}
+unsafe impl Send for AudioCapturer {}
+unsafe impl Sync for AudioCapturer {}
+
+impl AudioCapturer {
+ pub fn init(custom_device: &str) -> Option<Self> {
+ tracing::debug!("Custom device: {:?}", custom_device);
+
+ let mut devices = get_input_devices();
+
+ let maybe_device = {
+ let maybe_name = devices.first().map(|(name, _)| name.clone());
+ maybe_name.and_then(|device_name| devices.swap_remove_entry(&device_name))
+ };
+
+ maybe_device.map(|(name, (device, config))| {
+ tracing::info!("Using audio device: {}", name);
+
+ Self {
+ config,
+ device,
+ device_name: name,
+ sample_receiver: None,
+ stream: None,
+ }
+ })
+ }
+
+ pub fn log_info(&self) {
+ tracing::info!("Sample rate: {}", self.sample_rate());
+ tracing::info!("Channels: {}", self.channels());
+ tracing::info!("Sample format: {}", self.sample_format());
+ }
+
+ pub fn start(&mut self, start_time_tx: oneshot::Sender<Instant>) -> Result<(), String> {
+ tracing::trace!("Building input stream...");
+
+ let (receiver, stream) = (match self.config.sample_format() {
+ SampleFormat::I8 => self.build_stream::<i8>(start_time_tx),
+ SampleFormat::I16 => self.build_stream::<i16>(start_time_tx),
+ SampleFormat::I32 => self.build_stream::<i32>(start_time_tx),
+ SampleFormat::U8 => self.build_stream::<u8>(start_time_tx),
+ SampleFormat::U16 => self.build_stream::<u16>(start_time_tx),
+ SampleFormat::U32 => self.build_stream::<u32>(start_time_tx),
+ SampleFormat::F32 => self.build_stream::<f32>(start_time_tx),
+ SampleFormat::F64 => self.build_stream::<f64>(start_time_tx),
+ _ => 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 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.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>(
+ &self,
+ start_time_tx: oneshot::Sender<Instant>,
+ ) -> Result<(SampleReceiver, Stream), String>
+ where
+ T: SizedSample + ToBytes<Bytes: AsRef<[u8]>>,
+ {
+ let (sender, receiver) = mpsc::channel(2048);
+
+ let mut start_time_tx = Some(start_time_tx);
+
+ self.device
+ .build_input_stream(
+ &self.config.clone().into(),
+ move |data: &[T], _| {
+ let sample_size = std::mem::size_of::<T>();
+ let mut bytes = vec![0; std::mem::size_of_val(data)];
+ let size = bytes.len();
+ for (dest, source) in bytes.chunks_exact_mut(sample_size).zip(data.iter()) {
+ dest.copy_from_slice(source.to_le_bytes().as_ref());
+ }
+
+ let sample_data = Arc::new(bytes);
+ match sender.try_send(sample_data) {
+ Ok(_) => {
+ if let Some(start_time_option) = start_time_tx.take() {
+ start_time_option.send(Instant::now());
+
+ tracing::info!("Audio sample size: {size}");
+ 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_device = |device: Device| {
+ device
+ .supported_input_configs()
+ // .map_err(utils::log_debug_error)
+ .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()
+ .map(|name| (name, device, config.with_max_sample_rate()))
+ })
+ };
+
+ if let Some((name, device, config)) = host.default_input_device().and_then(get_usable_device) {
+ device_map.insert(name, (device, config));
+ }
+
+ match host.input_devices() {
+ Ok(devices) => {
+ for (name, device, config) in devices.filter_map(get_usable_device) {
+ device_map.entry(name).or_insert((device, config));
+ }
+ }
+ Err(error) => {
+ tracing::warn!("Could not access audio input devices");
+ tracing::debug!("{error}");
+ }
+ }
+
+ device_map
+}
+
+pub fn start_capturing(capturer: &mut AudioCapturer, pipe_path: PathBuf) -> NamedPipeCapture {
+ let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
+
+ let (tx, _) = oneshot::channel();
+
+ capturer.start(tx).unwrap();
+
+ println!("Starting audio channel senders...");
+ let mut receiver = capturer
+ .sample_receiver
+ .take()
+ .expect("Audio sample collection already started!");
+
+ tokio::spawn(async move {
+ let mut pipe = File::create(&pipe_path).await.unwrap();
+
+ while let Some(bytes) = receiver.recv().await {
+ if is_stopped.load(Ordering::Relaxed) {
+ println!("Stopping receiving camera frames");
+ return;
+ }
+
+ pipe.write_all(&bytes).await.unwrap();
+ }
+
+ println!("Done receiving audio frames");
+
+ let _ = pipe.sync_all().await;
+ });
+
+ capture
+}
diff --git a/apps/desktop-solid/src-tauri/src/camera.rs b/apps/desktop-solid/src-tauri/src/camera.rs
index dbafe097e..85b86e99a 100644
--- a/apps/desktop-solid/src-tauri/src/camera.rs
+++ b/apps/desktop-solid/src-tauri/src/camera.rs
@@ -54,7 +54,7 @@ pub fn create_camera_window(app: AppHandle) {
#[tauri::command]
#[specta::specta]
-pub fn get_cameras() -> Vec<String> {
+pub fn list_cameras() -> Vec<String> {
nokhwa::query(nokhwa::utils::ApiBackend::Auto)
.unwrap()
.into_iter()
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rs
index 3514cb2f5..b2d1f678d 100644
--- a/apps/desktop-solid/src-tauri/src/display.rs
+++ b/apps/desktop-solid/src-tauri/src/display.rs
@@ -34,7 +34,7 @@ pub enum CaptureTarget {
#[tauri::command]
#[specta::specta]
-pub fn get_capture_windows() -> Vec<CaptureWindow> {
+pub fn list_capture_windows() -> Vec<CaptureWindow> {
let targets = scap::get_all_targets();
let windows = macos::get_on_screen_windows();
diff --git a/apps/desktop-solid/src-tauri/src/editor.rs b/apps/desktop-solid/src-tauri/src/editor.rs
index 6f1c99266..81214f1e5 100644
--- a/apps/desktop-solid/src-tauri/src/editor.rs
+++ b/apps/desktop-solid/src-tauri/src/editor.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use cap_project::ProjectConfiguration;
use cap_rendering::{produce_frame, RenderVideoConstants};
use tokio::{
- sync::{mpsc, oneshot, watch},
+ sync::{mpsc, oneshot},
task::JoinHandle,
};
@@ -73,7 +73,6 @@ impl Editor {
}
EditorMessage::PreviewFrame(frame_number) => {
if self.playing {
- return;
}
}
}
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index 51e1be71c..07077e1e9 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -1,17 +1,18 @@
+mod audio;
mod camera;
mod display;
mod editor;
mod macos;
mod recording;
-use camera::{create_camera_window, get_cameras};
+use camera::{create_camera_window, list_cameras};
use cap_ffmpeg::ffmpeg_path_as_str;
use cap_project::ProjectConfiguration;
use cap_rendering::{
create_uniforms_buffers, render_video_to_file, RenderOptions, RenderVideoConstants,
VideoDecoderActor,
};
-use display::{get_capture_windows, Bounds, CaptureTarget};
+use display::{list_capture_windows, Bounds, CaptureTarget};
use ffmpeg_sidecar::{
command::ffmpeg_is_installed,
download::{check_latest_version, download_ffmpeg_package, ffmpeg_download_url, unpack_ffmpeg},
@@ -36,7 +37,6 @@ use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};
use tauri_plugin_decorum::WebviewWindowExt;
use tauri_specta::Event;
use tokio::{
- join,
sync::{Mutex, RwLock},
task::JoinHandle,
time::{sleep, Instant},
@@ -47,6 +47,7 @@ use tokio::{
pub struct RecordingOptions {
capture_target: CaptureTarget,
camera_label: Option<String>,
+ audio_input_name: Option<String>,
}
#[derive(specta::Type, Serialize)]
@@ -938,6 +939,14 @@ fn open_in_finder(path: PathBuf) {
.expect("Failed to open in Finder");
}
+#[tauri::command]
+#[specta::specta]
+fn list_audio_devices() -> Vec<String> {
+ let devices = audio::get_input_devices();
+
+ devices.keys().cloned().collect()
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let specta_builder = tauri_specta::Builder::new()
@@ -947,8 +956,9 @@ pub fn run() {
create_camera_window,
start_recording,
stop_recording,
- get_cameras,
- get_capture_windows,
+ list_cameras,
+ list_capture_windows,
+ list_audio_devices,
get_prev_recordings,
show_previous_recordings_window,
close_previous_recordings_window,
@@ -1001,6 +1011,7 @@ pub fn run() {
start_recording_options: RecordingOptions {
capture_target: CaptureTarget::Screen,
camera_label: None,
+ audio_input_name: None
},
current_recording: None,
prev_recordings: std::fs::read_dir(
diff --git a/apps/desktop-solid/src-tauri/src/recording.rs b/apps/desktop-solid/src-tauri/src/recording.rs
index f962b48c9..e75720374 100644
--- a/apps/desktop-solid/src-tauri/src/recording.rs
+++ b/apps/desktop-solid/src-tauri/src/recording.rs
@@ -3,6 +3,7 @@ use specta::Type;
use std::path::PathBuf;
use crate::{
+ audio::{self, AudioCapturer},
camera,
display::{self, get_window_bounds, CaptureTarget},
Bounds, RecordingOptions,
@@ -28,8 +29,13 @@ pub struct InProgressRecording {
pub display_source: DisplaySource,
#[serde(skip)]
pub camera: Option<FFmpegCaptureOutput<FFmpegRawVideoInput>>,
+ #[serde(skip)]
+ pub audio: Option<(FFmpegCaptureOutput<FFmpegRawAudioInput>, AudioCapturer)>,
}
+unsafe impl Send for InProgressRecording {}
+unsafe impl Sync for InProgressRecording {}
+
impl InProgressRecording {
pub async fn stop(&mut self) {
self.ffmpeg_process.stop();
@@ -42,28 +48,9 @@ impl InProgressRecording {
if let Some(camera) = &self.camera {
camera.capture.stop();
}
-
- // let render_options = RenderOptions {
- // screen_recording_path: self.display.output_path.clone(),
- // webcam_recording_path: self
- // .camera
- // .as_ref()
- // .map_or(PathBuf::new(), |c| c.output_path.clone()),
- // webcam_size: (320, 240),
- // // webcam_style: WebcamStyle {
- // // border_radius: 10.0,
- // // shadow_color: [0.0, 0.0, 0.0, 0.5],
- // // shadow_blur: 5.0,
- // // shadow_offset: (2.0, 2.0),
- // // },
- // output_size: (1280, 720),
- // // background: Background::Color([0.0, 0.0, 0.0, 1.0]),
- // };
-
- // Call render_video
- // if let Err(e) = render_video(render_options).await {
- // eprintln!("Error rendering video: {:?}", e);
- // }
+ if let Some(audio) = &mut self.audio {
+ audio.1.stop().ok();
+ }
}
}
@@ -85,6 +72,7 @@ pub async fn start(
let camera = start_camera_recording(&content_dir, recording_options, &mut ffmpeg).await;
let display = start_display_recording(&content_dir, recording_options, &mut ffmpeg).await;
+ let audio = start_audio_recording(&content_dir, recording_options, &mut ffmpeg).await;
let ffmpeg_process = ffmpeg.start();
@@ -117,6 +105,7 @@ pub async fn start(
},
},
camera,
+ audio,
}
}
@@ -217,3 +206,48 @@ async fn start_display_recording(
output_path,
}
}
+
+async fn start_audio_recording(
+ content_path: &PathBuf,
+ recording_options: &RecordingOptions,
+ ffmpeg: &mut FFmpeg,
+) -> Option<(FFmpegCaptureOutput<FFmpegRawAudioInput>, AudioCapturer)> {
+ let Some(mut capturer) = recording_options
+ .audio_input_name
+ .as_ref()
+ .and_then(|name| audio::AudioCapturer::init(name))
+ else {
+ return None;
+ };
+
+ let pipe_path = content_path.join("audio-input.pipe");
+ let output_path = content_path.join("audio-input.mp3");
+
+ let capture = audio::start_capturing(&mut capturer, pipe_path.clone());
+
+ let ffmpeg_input = ffmpeg.add_input(FFmpegRawAudioInput {
+ input: pipe_path.into_os_string(),
+ sample_format: capturer.sample_format().to_string(),
+ sample_rate: capturer.sample_rate(),
+ channels: capturer.channels(),
+ });
+
+ ffmpeg
+ .command
+ .args(["-f", "mp3", "-map", &format!("{}:a", ffmpeg_input.index)])
+ .args(["-b:a", "128k", "-async", "1", "-vn"])
+ .args([
+ "-af",
+ "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+ ])
+ .arg(&output_path);
+
+ Some((
+ FFmpegCaptureOutput {
+ input: ffmpeg_input,
+ capture,
+ output_path,
+ },
+ capturer,
+ ))
+}
diff --git a/apps/desktop-solid/src/routes/index.tsx b/apps/desktop-solid/src/routes/index.tsx
index 8ef979db5..e207f7222 100644
--- a/apps/desktop-solid/src/routes/index.tsx
+++ b/apps/desktop-solid/src/routes/index.tsx
@@ -12,7 +12,11 @@ import { Select as KSelect } from "@kobalte/core/select";
import { SwitchTab, Button } from "@cap/ui-solid";
import { createCameraForLabel, createCameras } from "../utils/media";
-import { createOptionsQuery, createWindowsQuery } from "../utils/queries";
+import {
+ createAudioDevicesQuery,
+ createOptionsQuery,
+ createWindowsQuery,
+} from "../utils/queries";
import { type CaptureWindow, commands, events } from "../utils/tauri";
import Header from "../components/Header";
import {
@@ -28,6 +32,7 @@ export default function () {
const cameras = createCameras();
const options = createOptionsQuery();
const windows = createWindowsQuery();
+ const audioDevices = createAudioDevicesQuery();
const camera = createCameraForLabel(() => options.data?.cameraLabel ?? "");
@@ -67,6 +72,13 @@ export default function () {
return (windows.data ?? []).find((data) => data.id === d.id);
});
+ const audioDevice = () =>
+ audioDevices.data?.find(
+ (d) => d.name === options().audioInputName
+ );
+
+ createEffect(() => console.log(audioDevice()));
+
return (
<>
<KSelect<CaptureWindow | null>
@@ -228,76 +240,64 @@ export default function () {
</div>
<div class="flex flex-col gap-[0.25rem] items-stretch">
<label class="text-gray-400">Microphone</label>
- <KSelect<MediaDeviceInfo>
- options={cameras()}
- optionValue="deviceId"
- optionTextValue="label"
+ <KSelect<{ name: string }>
+ options={audioDevices.data ?? []}
+ optionValue="name"
+ optionTextValue="name"
placeholder="No Audio"
+ value={audioDevice()}
disabled={isRecording()}
+ onChange={(item) => {
+ if (!item) return;
+ commands.setRecordingOptions({
+ ...options(),
+ audioInputName: item.name,
+ });
+ }}
itemComponent={(props) => (
<MenuItem<typeof KSelect.Item>
as={KSelect.Item}
item={props.item}
>
<KSelect.ItemLabel class="flex-1">
- {props.item.rawValue.label}
+ {props.item.rawValue.name}
</KSelect.ItemLabel>
</MenuItem>
)}
>
<KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors">
<IconCapMicrophone class="text-gray-400 size-[1.25rem]" />
- <KSelect.Value<MediaDeviceInfo> class="flex-1 text-left">
- {(state) => (
- <>
- No Audio
- {/* {state.selectedOption().label} */}
- </>
- )}
+ <KSelect.Value<{
+ name: string;
+ }> class="flex-1 text-left truncate">
+ {(state) => <>{state.selectedOption().name}</>}
</KSelect.Value>
<button
type="button"
class={cx(
"px-[0.375rem] rounded-full text-[0.75rem]",
- false
+ options().audioInputName
? "bg-blue-50 text-blue-300"
: "bg-red-50 text-red-300"
)}
onPointerDown={(e) => {
- if (!camera()) return;
+ if (!options().audioInputName) return;
e.stopPropagation();
e.preventDefault();
}}
onClick={(e) => {
- if (!camera()) return;
+ if (!options().audioInputName) return;
e.stopPropagation();
e.preventDefault();
commands.setRecordingOptions({
...options(),
- cameraLabel: null,
+ audioInputName: null,
});
}}
>
- Off
+ {options().audioInputName ? "On" : "Off"}
</button>
-
- {false && (
- <button
- type="button"
- class="px-[0.375rem] bg-blue-50 text-blue-300 rounded-full text-[0.75rem]"
- onPointerDown={(e) => {
- e.stopPropagation();
- e.preventDefault();
- }}
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- }}
- >
- On
- </button>
- )}
</KSelect.Trigger>
<KSelect.Portal>
<PopperContent<typeof KSelect.Content>
diff --git a/apps/desktop-solid/src/utils/media.ts b/apps/desktop-solid/src/utils/media.ts
index d93d5ad5e..413ba4944 100644
--- a/apps/desktop-solid/src/utils/media.ts
+++ b/apps/desktop-solid/src/utils/media.ts
@@ -29,7 +29,7 @@ export function createCameras() {
const devices = createDevices();
const [rustCameras, { refetch }] = createResource(() =>
- commands.getCameras()
+ commands.listCameras()
);
// createTimer(refetch, 5 * 1000, setInterval);
diff --git a/apps/desktop-solid/src/utils/queries.ts b/apps/desktop-solid/src/utils/queries.ts
index ff5342ff9..1dc39b9ec 100644
--- a/apps/desktop-solid/src/utils/queries.ts
+++ b/apps/desktop-solid/src/utils/queries.ts
@@ -6,7 +6,7 @@ import { reconcile } from "solid-js/store";
export const getWindows = queryOptions({
queryKey: ["capture", "windows"] as const,
- queryFn: () => commands.getCaptureWindows(),
+ queryFn: () => commands.listCaptureWindows(),
reconcile: "id",
});
@@ -26,6 +26,14 @@ export const getCurrentRecording = queryOptions({
},
});
+export const listAudioDevices = queryOptions({
+ queryKey: ["audioDevices"] as const,
+ queryFn: async () => {
+ return (await commands.listAudioDevices()).map((name) => ({ name }));
+ },
+ reconcile: "name",
+});
+
export function createOptionsQuery() {
const options = createQuery(() => getOptions);
createQueryInvalidate(options, "recordingOptionsChanged");
@@ -39,3 +47,10 @@ export function createWindowsQuery() {
return windows;
}
+
+export function createAudioDevicesQuery() {
+ const devices = createQuery(() => listAudioDevices);
+ createTimer(() => devices.refetch(), 1000, setInterval);
+
+ return devices;
+}
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index 959b4f10e..e020b9ba4 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -40,11 +40,14 @@ async stopRecording() : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
-async getCameras() : Promise<string[]> {
- return await TAURI_INVOKE("get_cameras");
+async listCameras() : Promise<string[]> {
+ return await TAURI_INVOKE("list_cameras");
},
-async getCaptureWindows() : Promise<CaptureWindow[]> {
- return await TAURI_INVOKE("get_capture_windows");
+async listCaptureWindows() : Promise<CaptureWindow[]> {
+ return await TAURI_INVOKE("list_capture_windows");
+},
+async listAudioDevices() : Promise<string[]> {
+ return await TAURI_INVOKE("list_audio_devices");
},
async getPrevRecordings() : Promise<Result<string[], null>> {
try {
@@ -176,7 +179,7 @@ export type HotkeysConfiguration = { show: boolean }
export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource }
export type JsonValue<T> = [T]
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration }
-export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null }
+export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null; audioInputName: string | null }
export type RecordingOptionsChanged = null
export type RenderFrameEvent = { frame_number: number; project: ProjectConfiguration }
export type RenderProgress = { type: "Starting"; total_frames: number } | { type: "FrameRendered"; current_frame: number }
diff --git a/apps/desktop/src-tauri/src/media/audio.rs b/apps/desktop/src-tauri/src/media/audio.rs
index b016e8c14..498a3b496 100644
--- a/apps/desktop/src-tauri/src/media/audio.rs
+++ b/apps/desktop/src-tauri/src/media/audio.rs
@@ -20,6 +20,9 @@ pub struct AudioCapturer {
stream: Option<Stream>,
}
+unsafe impl Send for AudioCapturer {}
+unsafe impl Sync for AudioCapturer {}
+
impl AudioCapturer {
pub fn init(custom_device: Option<&str>, should_stop: SharedFlag) -> Option<Self> {
tracing::debug!("Custom device: {:?}", custom_device);
diff --git a/crates/ffmpeg/src/lib.rs b/crates/ffmpeg/src/lib.rs
index 598c062e1..09f80d275 100644
--- a/crates/ffmpeg/src/lib.rs
+++ b/crates/ffmpeg/src/lib.rs
@@ -198,14 +198,14 @@ impl ApplyFFmpegArgs for FFmpegRawVideoInput {
}
}
-pub struct FFmpegRawAudioSource {
+pub struct FFmpegRawAudioInput {
pub sample_format: String,
pub sample_rate: u32,
pub channels: u16,
pub input: OsString,
}
-impl ApplyFFmpegArgs for FFmpegRawAudioSource {
+impl ApplyFFmpegArgs for FFmpegRawAudioInput {
fn apply_ffmpeg_args(&self, command: &mut Command) {
command
.args(["-f", &self.sample_format])
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index cc2cd1898..0672a43f3 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -5,7 +5,7 @@ use futures_intrusive::channel::shared::oneshot_channel;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use std::sync::mpsc::{channel, Sender};
use std::thread;
use wgpu::util::DeviceExt;
@@ -342,7 +342,7 @@ pub async fn render_video_to_channel(
let mut camera_rx = camera_recording_decoder.map(|camera_recording_decoder| {
println!("Setting up FFmpeg input for webcam recording...");
- let (camera_tx, mut camera_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
+ let (camera_tx, camera_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
tokio::spawn(async move {
let now = Instant::now();
@@ -434,25 +434,6 @@ pub async fn render_video_to_channel(
Ok(())
}
-pub async fn get_frame_cli(ffmpeg: &str, path: &Path, frame: u32) -> Vec<u8> {
- let mut cmd = tokio::process::Command::new(ffmpeg);
- let cmd = cmd
- .arg("-i")
- .arg(path)
- .args(["-f", "rawvideo", "-pix_fmt", "rgba", "-c:v", "rawvideo"])
- .args(["-vf", &format!(r#"select=eq(n\,{frame})"#), "-vframes", "1"])
- .arg("pipe:1");
-
- let output = cmd
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped())
- .output()
- .await
- .unwrap();
-
- output.stdout
-}
-
pub struct RenderVideoConstants {
pub _instance: wgpu::Instance,
pub _adapter: wgpu::Adapter,