Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

surface 'unsupported number of channels' errors

Brendan Allan1264a03be544
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index c5241992b..628c3f9c5 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -177,7 +177,7 @@ jobs:
- name: Upload debug symbols to Sentry
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
- working-directory: target/release
+ working-directory: target
run: |
curl -sL https://sentry.io/get-cli/ | bash
sentry-cli debug-files upload -o ${{ env.SENTRY_ORG }} -p ${{ env.SENTRY_PROJECT }} Cap.dSYM
diff --git a/Cargo.lock b/Cargo.lock
index 2364c0e16..6fd981d7a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1738,7 +1738,7 @@ dependencies = [
[[package]]
name = "desktop"
-version = "0.3.2"
+version = "0.3.3"
dependencies = [
"anyhow",
"axum",
diff --git a/apps/desktop/scripts/stripDebugSymbols.js b/apps/desktop/scripts/stripDebugSymbols.js
index 9760e7bf4..c2030847f 100644
--- a/apps/desktop/scripts/stripDebugSymbols.js
+++ b/apps/desktop/scripts/stripDebugSymbols.js
@@ -32,7 +32,9 @@ async function main() {
const binaryPath = path.join(releaseDir, releaseFile);
- await exec(`dsymutil "${binaryPath}" -o "${binaryPath}.dSYM"`);
+ await exec(
+ `dsymutil "${binaryPath}" -o "${targetDir.join(releaseFile)}.dSYM"`
+ );
await exec(`strip "${binaryPath}"`);
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 3f1cf50ca..d4750ddeb 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -40,13 +40,17 @@ use scap::frame::Frame;
use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
-use std::fs::File;
-use std::future::Future;
-use std::io::BufWriter;
-use std::str::FromStr;
use std::{
- collections::HashMap, io::BufReader, marker::PhantomData, path::PathBuf, process::Command,
+ collections::HashMap,
+ fs::File,
+ future::Future,
+ io::{BufReader, BufWriter},
+ marker::PhantomData,
+ path::PathBuf,
+ process::Command,
+ str::FromStr,
sync::Arc,
+ time::Duration,
};
use tauri::{AppHandle, Emitter, Manager, Runtime, State, WindowEvent};
use tauri_plugin_dialog::DialogExt;
@@ -128,7 +132,10 @@ impl App {
}
}
- async fn set_start_recording_options(&mut self, new_options: RecordingOptions) {
+ async fn set_start_recording_options(
+ &mut self,
+ new_options: RecordingOptions,
+ ) -> Result<(), String> {
let options = new_options.clone();
sentry::configure_scope(move |scope| {
let mut ctx = std::collections::BTreeMap::new();
@@ -175,15 +182,15 @@ impl App {
.await
.switch_cameras(camera_label)
.await
- .map_err(|error| eprintln!("{error}"))
- .ok();
+ .map_err(|e| e.to_string())?;
} else {
- self.camera_feed = CameraFeed::init(camera_label, self.camera_tx.clone())
- .await
- .map(Mutex::new)
- .map(Arc::new)
- .map_err(|error| eprintln!("{error}"))
- .ok();
+ self.camera_feed = Some(
+ CameraFeed::init(camera_label, self.camera_tx.clone())
+ .await
+ .map(Mutex::new)
+ .map(Arc::new)
+ .map_err(|e| e.to_string())?,
+ );
}
}
None => {
@@ -191,37 +198,133 @@ impl App {
}
}
- match new_options.audio_input_name() {
- Some(audio_input_name) => {
- if let Some(audio_input_feed) = self.audio_input_feed.as_mut() {
- audio_input_feed
- .switch_input(audio_input_name)
+ self.audio_input_feed = match new_options.audio_input_name() {
+ Some(audio_input_name) => Some(match self.audio_input_feed.take() {
+ Some(mut feed) => {
+ feed.switch_input(audio_input_name)
.await
- .map_err(|error| eprintln!("{error}"))
- .ok();
- } else {
- self.audio_input_feed = if let Ok(feed) = AudioInputFeed::init(audio_input_name)
+ .map_err(|e| e.to_string())?;
+
+ feed
+ }
+ None => {
+ let feed = AudioInputFeed::init(audio_input_name)
.await
- .map_err(|error| eprintln!("{error}"))
- {
- feed.add_sender(self.audio_input_tx.clone()).await.unwrap();
- Some(feed)
- } else {
- None
- };
+ .map_err(|e| e.to_string())?;
+
+ feed.add_sender(self.audio_input_tx.clone()).await.unwrap();
+
+ feed
}
- }
- None => {
- self.audio_input_feed = None;
- }
- }
+ }),
+ None => None,
+ };
self.start_recording_options = new_options;
RecordingOptionsChanged.emit(&self.handle).ok();
+
+ Ok(())
}
}
+// #[tauri::command]
+// #[specta::specta]
+// async fn set_camera_input(
+// app: AppHandle,
+// state: MutableState<'_, App>,
+// name: Option<String>,
+// ) -> Result<(), String> {
+// let mut state = state.write().await;
+
+// match CapWindowId::Camera.get(&app) {
+// Some(window) if name.is_none() => {
+// println!("closing camera window");
+// window.close().ok();
+// }
+// None if name.is_some() => {
+// println!("creating camera window");
+// ShowCapWindow::Camera {
+// ws_port: state.camera_ws_port,
+// }
+// .show(&app)
+// .ok();
+// }
+// _ => {}
+// }
+
+// match &name {
+// Some(camera_label) => {
+// if let Some(camera_feed) = state.camera_feed.as_ref() {
+// camera_feed
+// .lock()
+// .await
+// .switch_cameras(camera_label)
+// .await
+// .map_err(|error| eprintln!("{error}"))
+// .ok();
+// } else {
+// state.camera_feed = CameraFeed::init(camera_label, state.camera_tx.clone())
+// .await
+// .map(Mutex::new)
+// .map(Arc::new)
+// .map_err(|error| eprintln!("{error}"))
+// .ok();
+// }
+// }
+// None => {
+// state.camera_feed = None;
+// }
+// }
+
+// state.start_recording_options.camera_label = name;
+
+// RecordingOptionsChanged.emit(&app).ok();
+
+// Ok(())
+// }
+
+// #[tauri::command]
+// #[specta::specta]
+// async fn set_mic_input(
+// app: AppHandle,
+// state: MutableState<'_, App>,
+// name: Option<String>,
+// ) -> Result<(), String> {
+// let mut state = state.write().await;
+
+// match &name {
+// Some(audio_input_name) => {
+// if let Some(audio_input_feed) = state.audio_input_feed.as_mut() {
+// audio_input_feed
+// .switch_input(audio_input_name)
+// .await
+// .map_err(|error| eprintln!("{error}"))
+// .ok();
+// } else {
+// state.audio_input_feed = if let Ok(feed) = AudioInputFeed::init(audio_input_name)
+// .await
+// .map_err(|error| eprintln!("{error}"))
+// {
+// feed.add_sender(state.audio_input_tx.clone()).await.unwrap();
+// Some(feed)
+// } else {
+// None
+// };
+// }
+// }
+// None => {
+// state.audio_input_feed = None;
+// }
+// }
+
+// state.start_recording_options.audio_input_name = name;
+
+// RecordingOptionsChanged.emit(&app).ok();
+
+// Ok(())
+// }
+
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
pub struct RecordingOptionsChanged;
@@ -297,12 +400,12 @@ async fn get_recording_options(state: MutableState<'_, App>) -> Result<Recording
async fn set_recording_options(
state: MutableState<'_, App>,
options: RecordingOptions,
-) -> Result<(), ()> {
+) -> Result<(), String> {
state
.write()
.await
.set_start_recording_options(options)
- .await;
+ .await?;
Ok(())
}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index 8773531fe..6aeeea1f7 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -7,6 +7,7 @@
"beforeDevCommand": "node scripts/prepareSidecars.js && pnpm localdev",
"devUrl": "http://localhost:3001",
"beforeBuildCommand": "node scripts/prepareSidecars.js && pnpm turbo build --filter @cap/desktop",
+ "beforeBundleCommand": "node scripts/stripDebugSymbols.js",
"frontendDist": "../.output/public"
},
"app": {
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index 1750a0ed5..edc2634c9 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -96,7 +96,7 @@ export default function () {
if (!cameraWindowActive) {
console.log("cameraWindow not found");
- setOptions({
+ setOptions.mutate({
...options.data,
});
}
@@ -381,17 +381,12 @@ function CameraSelect(props: {
}
if (!props.options) return;
- if (!item || !item.isCamera) {
- props.setOptions({
- ...props.options,
- cameraLabel: null,
- });
- } else {
- props.setOptions({
- ...props.options,
- cameraLabel: item.name,
- });
- }
+ let cameraLabel = !item || !item.isCamera ? null : item.name;
+
+ props.setOptions.mutate({
+ ...props.options,
+ cameraLabel,
+ });
};
const selectOptions = createMemo(() => [
@@ -430,7 +425,10 @@ function CameraSelect(props: {
setOpen(isOpen);
}}
>
- <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 KSelect">
+ <KSelect.Trigger
+ disabled={props.setOptions.isPending}
+ 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 KSelect"
+ >
<IconCapCamera class="text-gray-400 size-[1.25rem]" />
<KSelect.Value<Option | null> class="flex-1 text-left truncate">
{(state) => <span>{state.selectedOption()?.name}</span>}
@@ -441,7 +439,7 @@ function CameraSelect(props: {
requestPermission={() => requestPermission("camera")}
onClear={() => {
if (!props.options) return;
- props.setOptions({
+ props.setOptions.mutate({
...props.options,
cameraLabel: null,
});
@@ -454,7 +452,7 @@ function CameraSelect(props: {
class={topLeftAnimateClasses}
>
<MenuItemList<typeof KSelect.Listbox>
- class="max-h-36 overflow-y-auto"
+ class="max-h-32 overflow-y-auto"
as={KSelect.Listbox}
/>
</PopperContent>
@@ -497,7 +495,7 @@ function MicrophoneSelect(props: {
const handleMicrophoneChange = async (item: Option | null) => {
if (!item || !props.options) return;
- props.setOptions({
+ props.setOptions.mutate({
...props.options,
audioInputName: item.deviceId !== "" ? item.name : null,
});
@@ -566,7 +564,10 @@ function MicrophoneSelect(props: {
setOpen(isOpen);
}}
>
- <KSelect.Trigger class="relative 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 KSelect overflow-hidden z-10">
+ <KSelect.Trigger
+ disabled={props.setOptions.isPending}
+ class="relative 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 KSelect overflow-hidden z-10"
+ >
<Show when={dbs()}>
{(s) => (
<div
@@ -596,7 +597,7 @@ function MicrophoneSelect(props: {
requestPermission={() => requestPermission("microphone")}
onClear={() => {
if (!props.options) return;
- props.setOptions({
+ props.setOptions.mutate({
...props.options,
audioInputName: null,
});
diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts
index 602e33528..72a346f61 100644
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@ -1,4 +1,8 @@
-import { createQuery, queryOptions } from "@tanstack/solid-query";
+import {
+ createMutation,
+ createQuery,
+ queryOptions,
+} from "@tanstack/solid-query";
import { commands, RecordingOptions } from "./tauri";
import { createQueryInvalidate } from "./events";
@@ -76,16 +80,19 @@ export function createOptionsQuery() {
{ name: "recordingOptionsQuery" }
);
- const setOptions = (newOptions: RecordingOptions) => {
- commands.setRecordingOptions(newOptions);
- const { captureTarget: _, ...partialOptions } = newOptions;
- setState(partialOptions);
- };
+ const setOptions = createMutation(() => ({
+ mutationFn: async (newOptions: RecordingOptions) => {
+ await commands.setRecordingOptions(newOptions);
+ const { captureTarget: _, ...partialOptions } = newOptions;
+ setState(partialOptions);
+ },
+ }));
const options = createQuery(() => ({
...getOptions,
select: (data) => {
- return { ...data, ...state };
+ setState(data);
+ return { ...state, ...data };
},
}));
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index f7f8d2fe7..f14e3f844 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -1,7 +1,8 @@
use std::{sync::Arc, time::Duration};
-use cap_media::data::{AudioInfo, FromSampleBytes};
+use cap_media::data::{AudioInfo, AudioInfoError, FromSampleBytes};
use cap_media::feeds::{AudioData, AudioPlaybackBuffer};
+use cap_media::MediaError;
use cap_project::ProjectConfiguration;
use cap_rendering::{ProjectUniforms, RenderVideoConstants};
use cpal::{
@@ -181,7 +182,8 @@ impl AudioPlayback {
SampleFormat::F32 => self.create_stream::<f32>(device, supported_config),
SampleFormat::F64 => self.create_stream::<f64>(device, supported_config),
_ => unimplemented!(),
- };
+ }
+ .unwrap();
stream.play().unwrap();
@@ -196,7 +198,7 @@ impl AudioPlayback {
self,
device: cpal::Device,
supported_config: cpal::SupportedStreamConfig,
- ) -> (watch::Receiver<bool>, cpal::Stream) {
+ ) -> Result<(watch::Receiver<bool>, cpal::Stream), AudioInfoError> {
let AudioPlayback {
stop_rx,
start_frame_number,
@@ -205,7 +207,7 @@ impl AudioPlayback {
..
} = self;
- let mut output_info = AudioInfo::from_stream_config(&supported_config);
+ let mut output_info = AudioInfo::from_stream_config(&supported_config)?;
output_info.sample_format = output_info.sample_format.packed();
// TODO: Get fps and duration from video (once we start supporting other frame rates)
@@ -237,6 +239,6 @@ impl AudioPlayback {
)
.unwrap();
- (stop_rx, stream)
+ Ok((stop_rx, stream))
}
}
diff --git a/crates/media/src/data.rs b/crates/media/src/data.rs
index 0ad0222d8..1c807429c 100644
--- a/crates/media/src/data.rs
+++ b/crates/media/src/data.rs
@@ -74,6 +74,12 @@ impl PlanarData for FFAudio {
}
}
+#[derive(Debug, thiserror::Error)]
+pub enum AudioInfoError {
+ #[error("Unsupported number of channels: {0}")]
+ ChannelLayout(u16),
+}
+
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct AudioInfo {
pub sample_format: Sample,
@@ -84,17 +90,24 @@ pub struct AudioInfo {
}
impl AudioInfo {
- pub fn new(sample_format: Sample, sample_rate: u32, channel_count: u16) -> Self {
- Self {
+ pub fn new(
+ sample_format: Sample,
+ sample_rate: u32,
+ channel_count: u16,
+ ) -> Result<Self, AudioInfoError> {
+ Self::channel_layout_raw(channel_count)
+ .ok_or(AudioInfoError::ChannelLayout(channel_count))?;
+
+ Ok(Self {
sample_format,
sample_rate,
channels: channel_count.into(),
time_base: FFRational(1, 1_000_000),
buffer_size: 1024,
- }
+ })
}
- pub fn from_stream_config(config: &SupportedStreamConfig) -> Self {
+ pub fn from_stream_config(config: &SupportedStreamConfig) -> Result<Self, AudioInfoError> {
let sample_format = ffmpeg_sample_format_for(config.sample_format()).unwrap();
let buffer_size = match config.buffer_size() {
SupportedBufferSize::Range { max, .. } => *max,
@@ -102,24 +115,42 @@ impl AudioInfo {
SupportedBufferSize::Unknown => 1024,
};
- Self {
+ Self::channel_layout_raw(config.channels())
+ .ok_or(AudioInfoError::ChannelLayout(config.channels()))?;
+
+ Ok(Self {
sample_format,
sample_rate: config.sample_rate().0,
channels: config.channels().into(),
time_base: FFRational(1, 1_000_000),
buffer_size,
- }
+ })
}
- pub fn from_decoder(decoder: &ffmpeg::codec::decoder::Audio) -> Self {
- Self {
+ pub fn from_decoder(decoder: &ffmpeg::codec::decoder::Audio) -> Result<Self, AudioInfoError> {
+ Self::channel_layout_raw(decoder.channels())
+ .ok_or(AudioInfoError::ChannelLayout(decoder.channels()))?;
+
+ Ok(Self {
sample_format: decoder.format(),
sample_rate: decoder.rate(),
// TODO: Use channel layout when we support more than just mono/stereo
channels: usize::from(decoder.channels()),
time_base: decoder.time_base(),
buffer_size: decoder.frame_size(),
- }
+ })
+ }
+
+ fn channel_layout_raw(channels: u16) -> Option<ChannelLayout> {
+ Some(match channels {
+ 1 => ChannelLayout::MONO,
+ 2 => ChannelLayout::STEREO,
+ _ => return None,
+ })
+ }
+
+ pub fn channel_layout(&self) -> ChannelLayout {
+ Self::channel_layout_raw(self.channels as u16).unwrap()
}
pub fn sample_size(&self) -> usize {
@@ -130,16 +161,6 @@ impl AudioInfo {
self.sample_rate.try_into().unwrap()
}
- pub fn channel_layout(&self) -> ChannelLayout {
- // TODO: Something other than panic. Pretty much all mics I know are either mono or stereo though.
- // Also need to test the audio data capture with a stereo mic at some point.
- match self.channels {
- 1 => ChannelLayout::MONO,
- 2 => ChannelLayout::STEREO,
- _ => panic!("Unsupported number of audio channels"),
- }
- }
-
pub fn empty_frame(&self, sample_count: usize) -> FFAudio {
let mut frame = FFAudio::new(self.sample_format, sample_count, self.channel_layout());
frame.set_rate(self.sample_rate);
diff --git a/crates/media/src/feeds/audio.rs b/crates/media/src/feeds/audio.rs
index f0bbb12ec..6b7f7818d 100644
--- a/crates/media/src/feeds/audio.rs
+++ b/crates/media/src/feeds/audio.rs
@@ -36,7 +36,7 @@ impl AudioData {
decoder.set_parameters(input_stream.parameters())?;
decoder.set_packet_time_base(input_stream.time_base());
- let input_info = AudioInfo::from_decoder(&decoder);
+ let input_info = AudioInfo::from_decoder(&decoder)?;
let mut output_info = input_info;
output_info.sample_format = Self::FORMAT;
diff --git a/crates/media/src/feeds/audio_input.rs b/crates/media/src/feeds/audio_input.rs
index b58a70113..49b53200f 100644
--- a/crates/media/src/feeds/audio_input.rs
+++ b/crates/media/src/feeds/audio_input.rs
@@ -63,7 +63,7 @@ impl AudioInputFeed {
})
.unwrap();
- let audio_info = AudioInfo::from_stream_config(&config);
+ let audio_info = AudioInfo::from_stream_config(&config)?;
let (control_tx, control_rx) = flume::bounded(1);
std::thread::spawn(|| start_capturing(device, config, control_rx));
@@ -146,7 +146,7 @@ impl AudioInputFeed {
dbg!(&config);
- self.audio_info = AudioInfo::from_stream_config(&config);
+ self.audio_info = AudioInfo::from_stream_config(&config)?;
Ok(())
}
diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs
index 790eb02a7..b602bacc0 100644
--- a/crates/media/src/lib.rs
+++ b/crates/media/src/lib.rs
@@ -4,6 +4,7 @@
//! as well as implementations of pipeline stages for individual tasks (encoding/decoding,
//! editing frames, composition, muxing, etc).
+use data::AudioInfoError;
use thiserror::Error;
pub mod data;
@@ -51,4 +52,7 @@ pub enum MediaError {
#[error("Could not find a suitable {0} stream in this file")]
MissingMedia(&'static str),
+
+ #[error("AudioInfo: {0}")]
+ AudioInfoError(#[from] AudioInfoError),
}