Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Progressive upload during recording (faster Instant Mode) (#351)

Richie McIlroye1a4391e6d50
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0f7720404..5a2183488 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -54,16 +54,7 @@ jobs:
with:
shared-key: ${{ matrix.settings.target }}
- - name: Setup pnpm
- uses: pnpm/action-setup@v4
- with:
- version: 10.5.2
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version: "20"
- cache: pnpm
+ - uses: ./.github/actions/setup-js
- name: Create .env file in root
run: |
@@ -79,8 +70,7 @@ jobs:
echo "NEXT_PUBLIC_CAP_AWS_REGION=${{ secrets.NEXT_PUBLIC_CAP_AWS_REGION }}" >> .env
echo "NEXT_PUBLIC_CAP_AWS_BUCKET=${{ secrets.NEXT_PUBLIC_CAP_AWS_BUCKET }}" >> .env
- - name: Copy .env to apps/desktop
- run: cp .env apps/desktop/.env
+ cat .env >> $GITHUB_ENV
- name: Run setup
run: |
@@ -116,19 +106,7 @@ jobs:
with:
shared-key: ${{ matrix.settings.target }}
- - name: Setup pnpm
- uses: pnpm/action-setup@v4
- with:
- version: 10.5.2
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version: "20"
- cache: pnpm
-
- - name: Install dependencies
- run: pnpm install
+ - uses: ./.github/actions/setup-js
- name: Create .env file in root
run: |
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
deleted file mode 100644
index 6b9de8035..000000000
--- a/.github/workflows/main.yml
+++ /dev/null
@@ -1,85 +0,0 @@
-name: "publish"
-on:
- push:
- branches:
- - release
-
-jobs:
- cap-desktop-release:
- permissions:
- contents: write
- runs-on: macos-latest
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v3
-
- - name: Create API Key File
- run: echo "${{ secrets.APPLE_API_KEY_FILE }}" > api.p8
-
- - name: Rust setup
- uses: dtolnay/rust-toolchain@stable
- with:
- targets: x86_64-apple-darwin, aarch64-apple-darwin
-
- - name: Rust cache
- uses: swatinem/rust-cache@v2
- with:
- workspaces: "./apps/desktop/src-tauri -> target"
-
- - name: Setup Node.js
- uses: actions/setup-node@v3
- with:
- node-version: "20"
-
- - name: Setup pnpm
- uses: pnpm/action-setup@v2
- with:
- version: latest
-
- - name: Install dependencies
- run: cd apps/desktop && pnpm install
-
- - name: Get app version
- id: get_version
- run: echo "appVersion=$(jq -r '.version' apps/desktop/package.json)" >> $GITHUB_OUTPUT
-
- - name: Create .env file in root
- run: |
- echo "NEXT_PUBLIC_WEB_URL=${{ secrets.NEXT_PUBLIC_WEB_URL }}" > .env
- echo "appVersion=${{ steps.get_version.outputs.appVersion }}" >> .env
- echo "NODE_ENV=production" >> .env
- echo "CAP_DESKTOP_SENTRY_URL=https://6a3b6a09e6ae976c2ad6fff710e88748@o4506859771527168.ingest.us.sentry.io/4508330917101568" >> .env
- echo "NEXT_PUBLIC_CAP_AWS_REGION=${{ secrets.NEXT_PUBLIC_CAP_AWS_REGION }}" >> .env
- echo "NEXT_PUBLIC_CAP_AWS_BUCKET=${{ secrets.NEXT_PUBLIC_CAP_AWS_BUCKET }}" >> .env
-
- - name: Copy .env to apps/desktop
- run: cp .env apps/desktop/.env
-
- - name: Output .env file
- run: cat apps/desktop/.env
-
- - name: Build the app
- uses: tauri-apps/tauri-action@v0
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
- APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
- APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
- TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
- TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
- APPLE_API_KEY_PATH: api.p8
- with:
- projectPath: apps/desktop
- args: --target universal-apple-darwin
- tagName: cap-v__VERSION__
- releaseName: "Cap v__VERSION__"
- releaseBody: "The latest version of Cap."
- releaseDraft: false
- releasePublish: true
- prerelease: false
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 1453e70b8..143ca152c 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -170,19 +170,7 @@ jobs:
with:
shared-key: ${{ matrix.settings.target }}
- - name: Setup pnpm
- uses: pnpm/action-setup@v4
- with:
- version: 10.5.2
-
- - name: Setup Node.js
- uses: actions/setup-node@v4
- with:
- node-version: "20"
- cache: pnpm
-
- - name: Install dependencies
- run: pnpm install
+ - uses: ./.github/actions/setup-js
- name: Create .env file in root
run: |
@@ -200,17 +188,11 @@ jobs:
echo "NEXT_PUBLIC_CAP_AWS_BUCKET=${{ secrets.NEXT_PUBLIC_CAP_AWS_BUCKET }}" >> .env
echo 'RUST_TARGET_TRIPLE=${{ matrix.settings.target }}' >> .env
- - name: Copy .env to apps/desktop
- run: cp .env apps/desktop/.env
-
- - name: Output .env file
- run: cat apps/desktop/.env
-
- name: Build app
working-directory: apps/desktop
run: |
pnpm -w cap-setup
- pnpm tauri build --target ${{ matrix.settings.target }} --config src-tauri/tauri.prod.conf.json
+ pnpm build:tauri --target ${{ matrix.settings.target }} --config src-tauri/tauri.prod.conf.json
env:
# https://github.com/tauri-apps/tauri-action/issues/740
CI: false
diff --git a/Cargo.lock b/Cargo.lock
index 289427699..8f0fdc586 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -948,6 +948,7 @@ dependencies = [
"global-hotkey",
"image 0.25.5",
"keyed_priority_queue",
+ "md5",
"mp4",
"nix 0.29.0",
"objc",
@@ -4096,6 +4097,12 @@ dependencies = [
"rayon",
]
+[[package]]
+name = "md5"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
+
[[package]]
name = "memchr"
version = "2.7.4"
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index a277dada8..0f8619558 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -2,8 +2,8 @@
"name": "@cap/desktop",
"type": "module",
"scripts": {
- "dev": "pnpm -w cap-setup && cross-env RUST_BACKTRACE=1 dotenv -e ../../.env -- pnpm run preparescript && tauri dev",
- "build:tauri": "dotenv -e ../../.env -- pnpm run preparescript && tauri build",
+ "dev": "pnpm -w cap-setup && dotenv -e ../../.env -- pnpm run preparescript && pnpm tauri dev",
+ "build:tauri": "dotenv -e ../../.env -- pnpm run preparescript && dotenv -e ../../.env -- pnpm tauri build",
"preparescript": "node scripts/prepare.js",
"localdev": "dotenv -e ../../.env -- vinxi dev --port 3001",
"build": "vinxi build",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index d35181d6d..5155625f0 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -8,7 +8,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
-name = "desktop_solid_lib"
+name = "cap_desktop"
crate-type = ["lib", "cdylib", "staticlib"]
[build-dependencies]
@@ -44,7 +44,7 @@ tauri-plugin-deep-link = "2.2.0"
tauri-plugin-clipboard-manager = "2.2.1"
serde = { version = "1", features = ["derive"] }
-serde_json = "1"
+serde_json = "1.0.111"
specta.workspace = true
specta-typescript = "0.0.7"
tokio.workspace = true
@@ -57,9 +57,9 @@ anyhow.workspace = true
futures = "0.3"
axum = { version = "0.7.5", features = ["ws"] }
tracing = "0.1.40"
-tempfile = "3.12.0"
+tempfile = "3.9.0"
ffmpeg.workspace = true
-chrono = "0.4.38"
+chrono = { version = "0.4.31", features = ["serde"] }
rodio = "0.19.0"
png = "0.17.13"
device_query = "2.1.0"
@@ -88,6 +88,7 @@ dirs = "6.0.0"
relative-path = "1.9.3"
cap-fail = { version = "0.1.0", path = "../../../crates/fail" }
tokio-stream = { version = "0.1.17", features = ["sync"] }
+md5 = "0.7.0"
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index f883d7804..83ae9d9e4 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -72,7 +72,7 @@ impl EditorInstances {
}
}
- pub async fn remove(window: &Window) {
+ pub async fn remove(window: Window) {
let Some(instances) = window.try_state::<EditorInstances>() else {
return;
};
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 5a32870d3..d712b71f2 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -50,7 +50,7 @@ use mp4::Mp4Reader;
// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use notifications::NotificationType;
use png::{ColorType, Encoder};
-use recording::RecordingActor;
+use recording::InProgressRecording;
use relative_path::RelativePathBuf;
use scap::capturer::Capturer;
use scap::frame::Frame;
@@ -98,9 +98,9 @@ pub struct App {
#[serde(skip)]
handle: AppHandle,
#[serde(skip)]
- current_recording: Option<RecordingActor>,
+ current_recording: Option<InProgressRecording>,
#[serde(skip)]
- pre_created_video: Option<PreCreatedVideo>,
+ recording_logging_handle: LoggingHandle,
}
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
@@ -126,14 +126,14 @@ pub struct VideoRecordingMetadata {
}
#[derive(Clone, Serialize, Deserialize, specta::Type, Debug)]
-pub struct PreCreatedVideo {
+pub struct VideoUploadInfo {
id: String,
link: String,
config: S3UploadMeta,
}
impl App {
- pub fn set_current_recording(&mut self, actor: RecordingActor) {
+ pub fn set_current_recording(&mut self, actor: InProgressRecording) {
let current_recording = self.current_recording.insert(actor);
CurrentRecordingChanged.emit(&self.handle).ok();
@@ -148,7 +148,7 @@ impl App {
}
}
- pub fn clear_current_recording(&mut self) -> Option<RecordingActor> {
+ pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {
self.close_occluder_window();
self.current_recording.take()
@@ -439,7 +439,6 @@ async fn get_recording_options(
#[tauri::command]
#[specta::specta]
async fn set_recording_options(
- app: AppHandle,
state: MutableState<'_, App>,
options: RecordingOptions,
) -> Result<(), String> {
@@ -1160,7 +1159,7 @@ pub struct UploadProgress {
#[derive(Deserialize, Type)]
pub enum UploadMode {
Initial {
- pre_created_video: Option<PreCreatedVideo>,
+ pre_created_video: Option<VideoUploadInfo>,
},
Reupload,
}
@@ -1951,17 +1950,15 @@ async fn update_auth_plan(app: AppHandle) {
AuthStore::update_auth_plan(&app).await.ok();
}
+pub type DynLoggingLayer =
+ Box<dyn tracing_subscriber::Layer<tracing_subscriber::Registry> + Send + Sync>;
+type LoggingHandle =
+ tracing_subscriber::reload::Handle<Option<DynLoggingLayer>, tracing_subscriber::Registry>;
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
-pub async fn run() {
+pub async fn run(recording_logging_handle: LoggingHandle) {
let tauri_context = tauri::generate_context!();
- // let _guard = configure_logging(
- // &dirs::data_dir()
- // .unwrap()
- // .join(&tauri_context.config().identifier)
- // .join("logs"),
- // );
-
let specta_builder = tauri_specta::Builder::new()
.commands(tauri_specta::collect_commands![
get_recording_options,
@@ -2144,7 +2141,7 @@ pub async fn run() {
mode: RecordingMode::Studio,
},
current_recording: None,
- pre_created_video: None,
+ recording_logging_handle,
})));
app.manage(Arc::new(RwLock::new(
@@ -2253,7 +2250,7 @@ pub async fn run() {
}
}
CapWindowId::Editor { .. } => {
- EditorInstances::remove(window);
+ tokio::spawn(EditorInstances::remove(window.clone()));
}
CapWindowId::Settings | CapWindowId::Upgrade => {
// Don't quit the app when settings or upgrade window is closed
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 1326763dd..be6ea3cad 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -3,6 +3,9 @@
use std::sync::Arc;
+use cap_desktop::DynLoggingLayer;
+use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer};
+
fn main() {
// We have to hold onto the ClientInitGuard until the very end
let _guard = if dotenvy_macro::dotenv!("CAP_DESKTOP_SENTRY_URL") != "" {
@@ -37,6 +40,23 @@ fn main() {
None
};
+ let (layer, handle) = tracing_subscriber::reload::Layer::new(None::<DynLoggingLayer>);
+
+ tracing_subscriber::registry()
+ // .with(tracing_subscriber::filter::filter_fn(|v| {
+ // v.target().starts_with("cap_")
+ // }))
+ .with(layer)
+ .with(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(true)
+ .with_target(true)
+ .with_filter(tracing_subscriber::filter::filter_fn(|v| {
+ v.target().starts_with("cap_")
+ })),
+ )
+ .init();
+
#[cfg(debug_assertions)]
sentry::configure_scope(|scope| {
scope.set_user(Some(sentry::User {
@@ -49,5 +69,5 @@ fn main() {
.enable_all()
.build()
.expect("Failed to build multi threaded tokio runtime")
- .block_on(desktop_solid_lib::run());
+ .block_on(cap_desktop::run(handle));
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 6f74fc5d5..000bc3b75 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -4,15 +4,14 @@ use crate::{
audio::AppSounds,
auth::AuthStore,
create_screenshot,
- export::export_video,
general_settings::GeneralSettingsStore,
- notifications, open_editor, open_external_link,
+ open_editor, open_external_link,
presets::PresetsStore,
- upload::get_s3_config,
- upload_exported_video, web_api,
+ upload::{get_s3_config, prepare_screenshot_upload, upload_video, ProgressiveUploadTask},
+ web_api,
windows::{CapWindowId, ShowCapWindow},
- App, CurrentRecordingChanged, MutableState, NewStudioRecordingAdded, PreCreatedVideo,
- RecordingStarted, RecordingStopped, UploadMode,
+ App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded,
+ RecordingStarted, RecordingStopped, VideoUploadInfo,
};
use cap_fail::fail;
use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
@@ -22,7 +21,7 @@ use cap_media::{
};
use cap_project::{
ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta,
- TimelineConfiguration, TimelineSegment, ZoomSegment, XY,
+ TimelineConfiguration, TimelineSegment, ZoomSegment,
};
use cap_recording::{
instant_recording::{CompletedInstantRecording, InstantRecordingHandle},
@@ -30,71 +29,88 @@ use cap_recording::{
StudioRecordingHandle,
};
use cap_rendering::ProjectRecordings;
-use cap_utils::spawn_actor;
-use clipboard_rs::{Clipboard, ClipboardContext};
+use cap_utils::{ensure_dir, spawn_actor};
use tauri::{AppHandle, Manager};
-use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_specta::Event;
-use tracing::info;
-
-pub enum RecordingActor {
- Instant(InstantRecordingHandle),
- Studio(StudioRecordingHandle),
+use tracing::{error, info};
+use tracing_subscriber::Layer;
+
+pub enum InProgressRecording {
+ Instant {
+ handle: InstantRecordingHandle,
+ progressive_upload: Option<ProgressiveUploadTask>,
+ video_upload_info: VideoUploadInfo,
+ },
+ Studio {
+ handle: StudioRecordingHandle,
+ },
}
-impl RecordingActor {
+impl InProgressRecording {
pub fn capture_target(&self) -> &ScreenCaptureTarget {
match self {
- Self::Instant(a) => &a.options.capture_target,
- Self::Studio(a) => &a.options.capture_target,
+ Self::Instant { handle, .. } => &handle.options.capture_target,
+ Self::Studio { handle } => &handle.options.capture_target,
}
}
pub async fn pause(&self) -> Result<(), RecordingError> {
match self {
- Self::Instant(a) => a.pause().await,
- Self::Studio(a) => a.pause().await,
+ Self::Instant { handle, .. } => handle.pause().await,
+ Self::Studio { handle } => handle.pause().await,
}
}
pub async fn resume(&self) -> Result<(), RecordingError> {
match self {
- Self::Instant(a) => a.resume().await,
- Self::Studio(a) => a.resume().await,
+ Self::Instant { handle, .. } => handle.resume().await,
+ Self::Studio { handle } => handle.resume().await,
}
}
- pub async fn stop(&self) -> Result<CompletedRecording, RecordingError> {
+ pub async fn stop(self) -> Result<CompletedRecording, RecordingError> {
Ok(match self {
- Self::Instant(a) => CompletedRecording::Instant(a.stop().await?),
- Self::Studio(a) => CompletedRecording::Studio(a.stop().await?),
+ Self::Instant {
+ handle,
+ progressive_upload,
+ video_upload_info,
+ } => CompletedRecording::Instant {
+ recording: handle.stop().await?,
+ progressive_upload,
+ video_upload_info,
+ },
+ Self::Studio { handle } => CompletedRecording::Studio(handle.stop().await?),
})
}
pub fn bounds(&self) -> &Bounds {
match self {
- Self::Instant(a) => &a.bounds,
- Self::Studio(a) => &a.bounds,
+ Self::Instant { handle, .. } => &handle.bounds,
+ Self::Studio { handle } => &handle.bounds,
}
}
}
pub enum CompletedRecording {
- Instant(CompletedInstantRecording),
+ Instant {
+ recording: CompletedInstantRecording,
+ progressive_upload: Option<ProgressiveUploadTask>,
+ video_upload_info: VideoUploadInfo,
+ },
Studio(CompletedStudioRecording),
}
impl CompletedRecording {
pub fn id(&self) -> &String {
match self {
- Self::Instant(a) => &a.id,
+ Self::Instant { recording, .. } => &recording.id,
Self::Studio(a) => &a.id,
}
}
pub fn project_path(&self) -> &PathBuf {
match self {
- Self::Instant(a) => &a.project_path,
+ Self::Instant { recording, .. } => &recording.project_path,
Self::Studio(a) => &a.project_path,
}
}
@@ -126,16 +142,12 @@ pub fn list_cameras() -> Vec<String> {
#[tauri::command]
#[specta::specta]
+#[tracing::instrument(name = "recording", skip_all)]
pub async fn start_recording(
app: AppHandle,
state_mtx: MutableState<'_, App>,
recording_options: Option<RecordingOptions>,
) -> Result<(), String> {
- let mut state = state_mtx.write().await;
-
- let recording_options = recording_options.unwrap_or(state.recording_options.clone());
- state.recording_options = recording_options.clone();
-
let id = uuid::Uuid::new_v4().to_string();
let recording_dir = app
@@ -145,41 +157,58 @@ pub async fn start_recording(
.join("recordings")
.join(format!("{id}.cap"));
- let camera_window = CapWindowId::Camera.get(&app);
- match recording_options.mode {
+ ensure_dir(&recording_dir).map_err(|e| format!("Failed to create recording directory: {e}"))?;
+ let logfile = std::fs::File::create(recording_dir.join("recording-logs.log"))
+ .map_err(|e| format!("Failed to create logfile: {e}"))?;
+
+ let mut state = state_mtx.write().await;
+
+ state
+ .recording_logging_handle
+ .reload(Some(Box::new(
+ tracing_subscriber::fmt::layer()
+ .with_ansi(false)
+ .with_target(true)
+ .with_writer(logfile),
+ ) as DynLoggingLayer))
+ .map_err(|e| format!("Failed to reload logging layer: {e}"))?;
+
+ let recording_options = recording_options.unwrap_or(state.recording_options.clone());
+ state.recording_options = recording_options.clone();
+
+ if let Some(window) = CapWindowId::Camera.get(&app) {
+ let _ =
+ window.set_content_protected(matches!(recording_options.mode, RecordingMode::Studio));
+ }
+
+ let video_upload_info = match recording_options.mode {
RecordingMode::Instant => {
- match AuthStore::get(&app) {
- Ok(Some(_)) => {
+ match AuthStore::get(&app).ok().flatten() {
+ Some(_) => {
// Pre-create the video and get the shareable link
if let Ok(s3_config) = get_s3_config(&app, false, None).await {
let link = web_api::make_url(format!("/s/{}", s3_config.id()));
+ info!("Pre-created shareable link: {}", link);
- state.pre_created_video = Some(PreCreatedVideo {
+ Some(VideoUploadInfo {
id: s3_config.id().to_string(),
link: link.clone(),
config: s3_config,
- });
- info!("Pre-created shareable link: {}", link);
+ })
+ } else {
+ None
}
}
// Allow the recording to proceed without error for any signed-in user
_ => {
// User is not signed in
ShowCapWindow::SignIn.show(&app).ok();
- Err("Please sign in to use instant recording")?;
+ return Err("Please sign in to use instant recording".to_string());
}
}
-
- if let Some(window) = camera_window {
- let _ = window.set_content_protected(false);
- }
}
- RecordingMode::Studio => {
- if let Some(window) = camera_window {
- let _ = window.set_content_protected(true);
- }
- }
- }
+ RecordingMode::Studio => None,
+ };
if matches!(
recording_options.capture_target,
@@ -188,6 +217,18 @@ pub async fn start_recording(
let _ = ShowCapWindow::WindowCaptureOccluder.show(&app);
}
+ let progressive_upload = video_upload_info
+ .as_ref()
+ .filter(|_| matches!(recording_options.mode, RecordingMode::Instant))
+ .map(|video_upload_info| {
+ ProgressiveUploadTask::spawn(
+ app.clone(),
+ id.clone(),
+ recording_dir.join("content/output.mp4"),
+ video_upload_info.clone(),
+ )
+ });
+
drop(state);
println!("spawning actor");
@@ -201,30 +242,47 @@ pub async fn start_recording(
let (actor, actor_done_rx) = match recording_options.mode {
RecordingMode::Studio => {
- let (actor, actor_done_rx) = cap_recording::spawn_studio_recording_actor(
- id,
- recording_dir,
+ let (handle, actor_done_rx) = cap_recording::spawn_studio_recording_actor(
+ id.clone(),
+ recording_dir.clone(),
recording_options.clone(),
state.camera_feed.clone(),
state.audio_input_feed.clone(),
)
.await
- .map_err(|e| e.to_string())?;
+ .map_err(|e| {
+ error!("Failed to spawn studio recording actor: {e}");
+ e.to_string()
+ })?;
- (RecordingActor::Studio(actor), actor_done_rx)
+ (InProgressRecording::Studio { handle }, actor_done_rx)
}
RecordingMode::Instant => {
- let (actor, actor_done_rx) =
+ let Some(video_upload_info) = video_upload_info.clone() else {
+ return Err("Video upload info not found".to_string());
+ };
+
+ let (handle, actor_done_rx) =
cap_recording::instant_recording::spawn_instant_recording_actor(
- id,
- recording_dir,
+ id.clone(),
+ recording_dir.clone(),
recording_options.clone(),
state.audio_input_feed.clone(),
)
.await
- .map_err(|e| e.to_string())?;
-
- (RecordingActor::Instant(actor), actor_done_rx)
+ .map_err(|e| {
+ error!("Failed to spawn studio recording actor: {e}");
+ e.to_string()
+ })?;
+
+ (
+ InProgressRecording::Instant {
+ handle,
+ progressive_upload,
+ video_upload_info,
+ },
+ actor_done_rx,
+ )
}
};
@@ -311,7 +369,7 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res
// runs when a recording ends, whether from success or failure
async fn handle_recording_end(
app: AppHandle,
- completed_recording: Option<CompletedRecording>,
+ recording: Option<CompletedRecording>,
state: &mut App,
) -> Result<(), String> {
// Clear current recording, just in case :)
@@ -325,12 +383,24 @@ async fn handle_recording_end(
window.unminimize().ok();
}
- if let Some(completed_recording) = completed_recording {
- handle_recording_finish(&app, completed_recording, state).await?;
+ // Store the link for opening later if we have one from an instant recording
+ let mut shareable_link = None;
+
+ if let Some(recording) = recording {
+ shareable_link = handle_recording_finish(&app, recording).await?;
};
+ state.recording_logging_handle.reload(None);
+
+ // Play sound to indicate recording has stopped
AppSounds::StopRecording.play();
+ // Now that recording has fully stopped and sound has played, open the link if available
+ if let Some(link) = shareable_link {
+ // Open link after sound plays, giving user clear indication recording has ended
+ open_external_link(app.clone(), link).ok();
+ }
+
CurrentRecordingChanged.emit(&app).ok();
Ok(())
@@ -340,8 +410,7 @@ async fn handle_recording_end(
async fn handle_recording_finish(
app: &AppHandle,
completed_recording: CompletedRecording,
- state: &mut App,
-) -> Result<(), String> {
+) -> Result<Option<String>, String> {
let recording_dir = completed_recording.project_path().clone();
let id = completed_recording.id().clone();
@@ -357,7 +426,7 @@ async fn handle_recording_finish(
inner.segments[0].display.path.to_path(&recording_dir)
}
},
- CompletedRecording::Instant(recording) => {
+ CompletedRecording::Instant { recording, .. } => {
recording.project_path.join("./content/output.mp4")
}
};
@@ -365,6 +434,8 @@ async fn handle_recording_finish(
let display_screenshot = screenshots_dir.join("display.jpg");
create_screenshot(display_output_path, display_screenshot.clone(), None).await?;
+ let mut shareable_link = None;
+
let meta_inner = match completed_recording {
CompletedRecording::Studio(recording) => {
let recordings = ProjectRecordings::new(&recording_dir, &recording.meta);
@@ -392,69 +463,84 @@ async fn handle_recording_finish(
RecordingMetaInner::Studio(recording.meta)
}
- CompletedRecording::Instant(recording) => {
- if let Some(pre_created_video) = state.pre_created_video.take() {
- spawn_actor({
- let app = app.clone();
- async move {
- // Copy link to clipboard
- let _ = app.clipboard().write_text(pre_created_video.link.clone());
-
- // Send notification for shareable link
- notifications::send_notification(
+ CompletedRecording::Instant {
+ recording,
+ progressive_upload,
+ video_upload_info,
+ } => {
+ shareable_link = Some(video_upload_info.link.clone());
+ let app = app.clone();
+ let output_path = recording_dir.join("content/output.mp4");
+
+ spawn_actor(async move {
+ if let Some(progressive_upload) = progressive_upload {
+ let video_upload_succeeded = match progressive_upload
+ .handle
+ .await
+ .map_err(|e| e.to_string())
+ .and_then(|r| r)
+ {
+ Ok(()) => {
+ info!("Not attempting instant recording upload as progressive upload succeeded");
+ true
+ }
+ Err(e) => {
+ error!("Progressive upload failed: {}", e);
+ false
+ }
+ };
+
+ if video_upload_succeeded {
+ let (screenshot_url, screenshot_form) = match prepare_screenshot_upload(
+ &app,
+ &video_upload_info.config.clone(),
+ display_screenshot,
+ )
+ .await
+ {
+ Ok(v) => v,
+ Err(e) => {
+ error!("Failed to prepare screenshot upload: {e}");
+ return;
+ }
+ };
+
+ let resp = reqwest::Client::new()
+ .post(screenshot_url)
+ .multipart(screenshot_form)
+ .send()
+ .await;
+
+ match resp {
+ Ok(r) if r.status() == 200 => {
+ info!("Screenshot uploaded successfully");
+ }
+ Ok(r) => {
+ error!("Failed to upload screenshot: {}", r.status());
+ }
+ Err(e) => {
+ error!("Failed to upload screenshot: {e}");
+ }
+ }
+ } else {
+ // The upload_video function handles screenshot upload, so we can pass it along
+ match upload_video(
&app,
- notifications::NotificationType::ShareableLinkCopied,
- );
-
- // Open the pre-created shareable link
- open_external_link(app.clone(), pre_created_video.link.clone()).ok();
-
- // Start the upload process in the background with retry mechanism
- let app = app.clone();
-
- tauri::async_runtime::spawn(async move {
- let max_retries = 3;
- let mut retry_count = 0;
-
- while retry_count < max_retries {
- match upload_exported_video(
- app.clone(),
- id.clone(),
- UploadMode::Initial {
- pre_created_video: Some(pre_created_video.clone()),
- },
- )
- .await
- {
- Ok(_) => {
- println!("Video uploaded successfully");
- // Don't send notification here since we already did it above
- break;
- }
- Err(e) => {
- retry_count += 1;
- println!(
- "Error during auto-upload (attempt {}/{}): {}",
- retry_count, max_retries, e
- );
-
- if retry_count < max_retries {
- tokio::time::sleep(std::time::Duration::from_secs(5))
- .await;
- } else {
- println!("Max retries reached. Upload failed.");
- notifications::send_notification(
- &app,
- notifications::NotificationType::UploadFailed,
- );
- }
- }
- }
+ video_upload_info.id.clone(),
+ output_path,
+ Some(video_upload_info.config.clone()),
+ Some(display_screenshot.clone()),
+ )
+ .await
+ {
+ Ok(_) => {
+ info!("Final video upload with screenshot completed successfully")
}
- });
+ Err(e) => error!("Error in final upload with screenshot: {}", e),
+ }
}
- });
- }
+ }
+ });
RecordingMetaInner::Instant(recording.meta)
}
@@ -478,7 +564,7 @@ async fn handle_recording_finish(
meta.save_for_project()
.map_err(|e| format!("Failed to save recording meta: {e}"))?;
- Ok(())
+ Ok(shareable_link)
}
fn generate_zoom_segments_from_clicks(
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 5fefb36be..814a2a415 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -1,17 +1,26 @@
// credit @filleduchaos
+use cap_utils::spawn_actor;
use futures::stream;
use image::codecs::jpeg::JpegEncoder;
use image::ImageReader;
use reqwest::{multipart::Form, StatusCode};
+use std::io::SeekFrom;
use std::path::PathBuf;
-use tauri::AppHandle;
+use std::sync::Arc;
+use std::time::Duration;
+use tauri::{AppHandle, Manager, Runtime};
+use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_specta::Event;
+use tokio::io::{AsyncReadExt, AsyncSeekExt};
+use tokio::sync::mpsc;
+use tokio::sync::RwLock;
use tokio::task;
+use tokio::time::sleep;
use crate::web_api::{self, ManagerExt};
-use crate::UploadProgress;
+use crate::{notifications, App, MutableState, RecordingStopped, UploadProgress, VideoUploadInfo};
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -223,45 +232,14 @@ pub async fn upload_video(
let total_size = file_bytes.len() as f64;
- // Wrap file_bytes in an Arc for shared ownership
- let file_bytes = std::sync::Arc::new(file_bytes);
-
// Create a stream that reports progress
- let file_part =
- {
- let progress_counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
- let app_handle = app.clone();
- let file_bytes = file_bytes.clone();
-
- let stream = stream::iter((0..file_bytes.len()).step_by(1024 * 1024).map(
- move |start| {
- let end = (start + 1024 * 1024).min(file_bytes.len());
- let chunk = file_bytes[start..end].to_vec();
-
- let current = progress_counter
- .fetch_add(chunk.len() as u64, std::sync::atomic::Ordering::SeqCst)
- as f64;
-
- // Emit progress every chunk
- UploadProgress {
- progress: current / total_size,
- message: format!("{:.0}%", (current / total_size * 100.0)),
- }
- .emit(&app_handle)
- .ok();
-
- Ok::<Vec<u8>, std::io::Error>(chunk)
- },
- ));
-
- reqwest::multipart::Part::stream_with_length(
- reqwest::Body::wrap_stream(stream),
- total_size as u64,
- )
- .file_name(file_name.clone())
- .mime_str("video/mp4")
- .map_err(|e| format!("Error setting MIME type: {}", e))?
- };
+ let file_part = reqwest::multipart::Part::stream_with_length(
+ reqwest::Body::from(file_bytes),
+ total_size as u64,
+ )
+ .file_name(file_name.clone())
+ .mime_str("video/mp4")
+ .map_err(|e| format!("Error setting MIME type: {}", e))?;
let form = form.part("file", file_part);
@@ -293,14 +271,6 @@ pub async fn upload_video(
video_upload.map_err(|e| format!("Failed to send upload file request: {}", e))?;
if response.status().is_success() {
- // Final progress update
- UploadProgress {
- progress: 1.0,
- message: "100%".to_string(),
- }
- .emit(app)
- .ok();
-
println!("Video uploaded successfully");
if let Some(Ok(screenshot_response)) = screenshot_result {
@@ -502,6 +472,8 @@ pub async fn get_s3_config(
)
});
+ dbg!(&config_url);
+
let response = app
.authed_api_request(|client| client.get(config_url))
.await
@@ -772,7 +744,7 @@ pub async fn upload_individual_file(
}
}
-async fn prepare_screenshot_upload(
+pub async fn prepare_screenshot_upload(
app: &AppHandle,
s3_config: &S3UploadMeta,
screenshot_path: PathBuf,
@@ -838,3 +810,730 @@ async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {
.await
.map_err(|e| format!("Failed to compress image: {}", e))?
}
+
+// a typical recommended chunk size is 5MB (AWS min part size).
+const CHUNK_SIZE: u64 = 5 * 1024 * 1024; // 5MB
+const MIN_PART_SIZE: u64 = 5 * 1024 * 1024; // For non-final parts
+
+pub struct ProgressiveUploadTask {
+ pub handle: tokio::task::JoinHandle<Result<(), String>>,
+}
+
+impl ProgressiveUploadTask {
+ /// starts a progressive (multipart) upload that runs until recording stops
+ /// and the file has stabilized (no additional data is being written).
+ pub fn spawn(
+ app: AppHandle,
+ video_id: String,
+ file_path: PathBuf,
+ pre_created_video: VideoUploadInfo,
+ ) -> Self {
+ Self {
+ handle: spawn_actor(async move {
+ use std::time::Duration;
+ use tokio::sync::mpsc;
+ use tokio::time::sleep;
+
+ // --------------------------------------------
+ // listen for a "RecordingStopped" signal. We'll
+ // finalize only after we know there's no more
+ // incoming data from the pipeline (plus we do
+ // an extra stabilization check).
+ // --------------------------------------------
+ let (recording_end_tx, mut recording_end_rx) = mpsc::channel::<()>(1);
+
+ RecordingStopped::listen_any(&app.clone(), {
+ let app = app.clone();
+ move |_| {
+ let tx = recording_end_tx.clone();
+ let app = app.clone();
+
+ tokio::spawn(async move {
+ let state = app.state::<Arc<RwLock<App>>>();
+ let app_state = state.read().await;
+ if app_state.current_recording.is_none() {
+ // Recording truly ended
+ let _ = tx.send(()).await;
+ }
+ });
+ }
+ });
+
+ // --------------------------------------------
+ // basic constants and info for chunk approach
+ // --------------------------------------------
+ let file_name = "result.mp4";
+ let client = reqwest::Client::new();
+ let s3_config = pre_created_video.config;
+ let file_key = format!("{}/{}/{}", s3_config.user_id(), s3_config.id(), file_name);
+
+ let mut uploaded_parts = Vec::new();
+ let mut part_number = 1;
+ let mut last_uploaded_position: u64 = 0;
+
+ let mut upload_complete = false;
+ let mut recording_stopped = false;
+
+ println!("Starting multipart upload for {video_id}...");
+
+ // --------------------------------------------
+ // wait until the file hits 5MB or more
+ // before initiating the multipart upload.
+ // --------------------------------------------
+ loop {
+ if !file_path.exists() {
+ println!("File does not exist yet, waiting...");
+ sleep(Duration::from_millis(500)).await;
+ continue;
+ }
+ match tokio::fs::metadata(&file_path).await {
+ Ok(metadata) => {
+ if metadata.len() < MIN_PART_SIZE {
+ println!(
+ "Waiting for file to grow to at least 5MB before starting upload"
+ );
+ sleep(Duration::from_millis(500)).await;
+ continue;
+ } else {
+ break;
+ }
+ }
+ Err(e) => {
+ println!("Failed to get file metadata: {}", e);
+ sleep(Duration::from_millis(500)).await;
+ }
+ }
+ }
+
+ // Copy link to clipboard early
+ let _ = app.clipboard().write_text(pre_created_video.link.clone());
+
+ notifications::send_notification(
+ &app,
+ notifications::NotificationType::ShareableLinkCopied,
+ );
+
+ // --------------------------------------------
+ // initiate the multipart upload
+ // --------------------------------------------
+ println!("Initiating multipart upload for {video_id}...");
+ let initiate_response = match app
+ .authed_api_request(|c| {
+ c.post(web_api::make_url("/api/upload/multipart/initiate"))
+ .header("Content-Type", "application/json")
+ .json(&serde_json::json!({
+ "fileKey": file_key,
+ "contentType": "video/mp4"
+ }))
+ })
+ .await
+ {
+ Ok(r) => r,
+ Err(e) => {
+ return Err(format!("Failed to initiate multipart upload: {}", e));
+ }
+ };
+
+ if !initiate_response.status().is_success() {
+ let status = initiate_response.status();
+ let error_body = initiate_response
+ .text()
+ .await
+ .unwrap_or_else(|_| "<no response body>".to_string());
+ return Err(format!(
+ "Failed to initiate multipart upload. Status: {}. Body: {}",
+ status, error_body
+ ));
+ }
+
+ let initiate_data = match initiate_response.json::<serde_json::Value>().await {
+ Ok(d) => d,
+ Err(e) => {
+ return Err(format!("Failed to parse initiate response: {}", e));
+ }
+ };
+
+ let upload_id = match initiate_data.get("uploadId") {
+ Some(val) => val.as_str().unwrap_or("").to_string(),
+ None => {
+ return Err("No uploadId returned from initiate endpoint".to_string());
+ }
+ };
+ if upload_id.is_empty() {
+ return Err("Empty uploadId returned from initiate endpoint".to_string());
+ }
+
+ println!("Multipart upload initiated with ID: {}", upload_id);
+
+ // --------------------------------------------
+ // Main loop while upload not complete:
+ // - If we have >= CHUNK_SIZE new data, upload.
+ // - If recording hasn't stopped, keep waiting.
+ // - If recording stopped, do leftover final(s).
+ // --------------------------------------------
+ while !upload_complete {
+ if !recording_stopped {
+ // Check if the recording pipeline is done
+ if let Ok(_) = recording_end_rx.try_recv() {
+ println!("Recording end detected, will finalize soon.");
+ recording_stopped = true;
+ }
+ }
+
+ // Check the file's current size
+ if !file_path.exists() {
+ println!("File no longer exists, aborting upload");
+ return Err("File no longer exists".to_string());
+ }
+
+ let file_size = match tokio::fs::metadata(&file_path).await {
+ Ok(md) => md.len(),
+ Err(e) => {
+ println!("Failed to get file metadata: {}", e);
+ sleep(Duration::from_millis(500)).await;
+ continue;
+ }
+ };
+
+ let new_data_size = file_size.saturating_sub(last_uploaded_position);
+
+ if new_data_size >= CHUNK_SIZE {
+ // We have a full chunk to send
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut part_number,
+ &mut last_uploaded_position,
+ CHUNK_SIZE,
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts.push(part);
+ }
+ Err(e) => {
+ println!(
+ "Error uploading chunk (part {}): {}. Retrying in 1s...",
+ part_number, e
+ );
+ sleep(Duration::from_secs(1)).await;
+ }
+ }
+ } else {
+ // If recording is not done, keep waiting a bit
+ if !recording_stopped {
+ sleep(Duration::from_millis(500)).await;
+ continue;
+ }
+
+ // --------------------------------------------
+ // Recording has stopped. We do repeated
+ // checks to ensure the file is stable (not
+ // still growing). Then we keep uploading
+ // leftover chunks until no more data arrives.
+ // --------------------------------------------
+ let max_stabilize_attempts = 8;
+ let mut attempts = 0;
+
+ // We'll loop to catch any last bits that appear
+ // after we do a leftover chunk upload.
+ loop {
+ // Wait for the file to stabilize
+ println!("Waiting for file to stabilize...");
+ let mut stable_count = 0;
+ let stable_required = 3; // e.g. 3 consecutive stable checks
+
+ // Keep track of last known size
+ let mut prev_size = tokio::fs::metadata(&file_path)
+ .await
+ .map(|md| md.len())
+ .unwrap_or(0);
+
+ while stable_count < stable_required {
+ sleep(Duration::from_secs(1)).await;
+ let size_now = match tokio::fs::metadata(&file_path).await {
+ Ok(md) => md.len(),
+ Err(_) => 0,
+ };
+ if size_now == prev_size {
+ stable_count += 1;
+ } else {
+ stable_count = 0;
+ prev_size = size_now;
+ }
+ }
+
+ // At this point, the file has stayed the same size
+ // for ~ stable_required seconds.
+ let final_size = prev_size;
+ let leftover_size = final_size.saturating_sub(last_uploaded_position);
+
+ // Double-check moov if you want
+ // let moov_found = found_moov_atom(&file_path).await;
+
+ if leftover_size > 0 {
+ if leftover_size >= MIN_PART_SIZE {
+ // We still have at least 5MB leftover, treat it like a normal part:
+ println!(
+ "File stabilized, but leftover >= 5MB. Uploading leftover chunk of {} bytes.",
+ leftover_size
+ );
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut part_number,
+ &mut last_uploaded_position,
+ leftover_size, // read leftover
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts.push(part);
+ }
+ Err(e) => {
+ return Err(format!(
+ "Failed uploading leftover chunk: {}",
+ e
+ ));
+ }
+ }
+ } else {
+ // Less than 5 MB leftover -> final chunk
+ println!(
+ "Uploading final leftover chunk of {} bytes before completion",
+ leftover_size
+ );
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut part_number,
+ &mut last_uploaded_position,
+ leftover_size,
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts.push(part);
+ println!(
+ "Successfully uploaded leftover chunk, part {}",
+ part_number - 1
+ );
+ }
+ Err(e) => {
+ return Err(format!(
+ "Failed to upload leftover chunk: {}",
+ e
+ ));
+ }
+ }
+ }
+
+ // We just uploaded a leftover chunk, but let's see
+ // if more data arrives. We'll try again. If no more
+ // new data arrives, we can finalize.
+ attempts += 1;
+ if attempts > max_stabilize_attempts {
+ println!(
+ "Reached maximum leftover attempts, proceeding to finalize."
+ );
+ break;
+ }
+ } else {
+ // No leftover. We have stabilized with no new data.
+ println!("File is stable with no leftover data, finalizing...");
+ break;
+ }
+ }
+
+ match Self::upload_chunk(
+ &app,
+ &client,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &mut 1,
+ &mut 0,
+ uploaded_parts[0].size as u64,
+ )
+ .await
+ {
+ Ok(part) => {
+ uploaded_parts[0] = part;
+ println!("Successfully re-uploaded first chunk",);
+ }
+ Err(e) => {
+ return Err(format!("Failed to re-upload first chunk"));
+ }
+ }
+
+ // All leftover chunks are now uploaded. We finalize.
+ println!(
+ "Completing multipart upload with {} parts",
+ uploaded_parts.len()
+ );
+ Self::finalize_upload(
+ &app,
+ &file_path,
+ &file_key,
+ &upload_id,
+ &uploaded_parts,
+ &video_id,
+ )
+ .await?;
+
+ upload_complete = true;
+ }
+ }
+
+ Ok(())
+ }),
+ }
+ }
+
+ /// Upload a single chunk from the file at `last_uploaded_position` for `chunk_size` bytes.
+ /// Advances `last_uploaded_position` accordingly. Returns JSON { PartNumber, ETag, Size }.
+ async fn upload_chunk(
+ app: &AppHandle,
+ client: &reqwest::Client,
+ file_path: &PathBuf,
+ file_key: &str,
+ upload_id: &str,
+ part_number: &mut i32,
+ last_uploaded_position: &mut u64,
+ chunk_size: u64,
+ ) -> Result<UploadedPart, String> {
+ let file_size = match tokio::fs::metadata(file_path).await {
+ Ok(metadata) => metadata.len(),
+ Err(e) => return Err(format!("Failed to get file metadata: {}", e)),
+ };
+
+ // Check if we're at the end of the file
+ if *last_uploaded_position >= file_size {
+ return Err("No more data to read - already at end of file".to_string());
+ }
+
+ // Calculate how much we can actually read
+ let remaining = file_size - *last_uploaded_position;
+ let bytes_to_read = std::cmp::min(chunk_size, remaining);
+
+ let mut file = tokio::fs::File::open(file_path)
+ .await
+ .map_err(|e| format!("Failed to open file: {}", e))?;
+
+ // Log before seeking
+ println!(
+ "Seeking to offset {} for part {} (file size: {}, remaining: {})",
+ *last_uploaded_position, *part_number, file_size, remaining
+ );
+
+ // Seek to the position we left off
+ if let Err(e) = file
+ .seek(std::io::SeekFrom::Start(*last_uploaded_position))
+ .await
+ {
+ return Err(format!("Failed to seek in file: {}", e));
+ }
+
+ // Read exactly bytes_to_read
+ let mut chunk = vec![0u8; bytes_to_read as usize];
+ let mut total_read = 0;
+
+ while total_read < bytes_to_read as usize {
+ match file.read(&mut chunk[total_read..]).await {
+ Ok(0) => break, // EOF
+ Ok(n) => {
+ total_read += n;
+ println!(
+ "Read {} bytes, total so far: {}/{}",
+ n, total_read, bytes_to_read
+ );
+ }
+ Err(e) => return Err(format!("Failed to read chunk from file: {}", e)),
+ }
+ }
+
+ if total_read == 0 {
+ return Err("No data to upload for this part.".to_string());
+ }
+
+ // Truncate the buffer to the actual bytes read
+ chunk.truncate(total_read);
+
+ // Basic content‑MD5 for data integrity
+ let md5_sum = {
+ let digest = md5::compute(&chunk);
+ base64::encode(digest.0)
+ };
+
+ // Verify file position to ensure we're not experiencing file handle issues
+ let pos_after_read = file
+ .seek(std::io::SeekFrom::Current(0))
+ .await
+ .map_err(|e| format!("Failed to get current file position: {}", e))?;
+
+ let expected_pos = *last_uploaded_position + total_read as u64;
+ if pos_after_read != expected_pos {
+ println!(
+ "WARNING: File position after read ({}) doesn't match expected position ({})",
+ pos_after_read, expected_pos
+ );
+ }
+
+ let file_size = tokio::fs::metadata(file_path)
+ .await
+ .map(|m| m.len())
+ .unwrap_or(0);
+ let remaining = file_size - *last_uploaded_position;
+
+ println!(
+ "File size: {}, Last uploaded: {}, Remaining: {}, chunk_size: {}, part: {}",
+ file_size, *last_uploaded_position, remaining, chunk_size, *part_number
+ );
+ println!(
+ "Uploading part {} ({} bytes), MD5: {}",
+ *part_number, total_read, md5_sum
+ );
+
+ // Request presigned URL for this part
+ let presign_response = match app
+ .authed_api_request(|c| {
+ c.post(web_api::make_url("/api/upload/multipart/presign-part"))
+ .header("Content-Type", "application/json")
+ .json(&serde_json::json!({
+ "fileKey": file_key,
+ "uploadId": upload_id,
+ "partNumber": *part_number
+ }))
+ })
+ .await
+ {
+ Ok(r) => r,
+ Err(e) => {
+ return Err(format!(
+ "Failed to request presigned URL for part {}: {}",
+ *part_number, e
+ ))
+ }
+ };
+
+ if !presign_response.status().is_success() {
+ let status = presign_response.status();
+ let error_body = presign_response
+ .text()
+ .await
+ .unwrap_or_else(|_| "<no response body>".to_string());
+ return Err(format!(
+ "Presign-part failed for part {}: status={}, body={}",
+ *part_number, status, error_body
+ ));
+ }
+
+ let presign_data = match presign_response.json::<serde_json::Value>().await {
+ Ok(d) => d,
+ Err(e) => return Err(format!("Failed to parse presigned URL response: {}", e)),
+ };
+
+ let presigned_url = presign_data
+ .get("presignedUrl")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if presigned_url.is_empty() {
+ return Err(format!("Empty presignedUrl for part {}", *part_number));
+ }
+
+ // Upload the chunk with retry
+ let mut retry_count = 0;
+ let max_retries = 3;
+ let mut etag: Option<String> = None;
+
+ while retry_count < max_retries && etag.is_none() {
+ println!(
+ "Sending part {} (attempt {}/{}): {} bytes",
+ *part_number,
+ retry_count + 1,
+ max_retries,
+ total_read
+ );
+
+ match client
+ .put(&presigned_url)
+ .header("Content-Length", total_read.to_string())
+ .header("Connection", "keep-alive")
+ .header("Content-MD5", &md5_sum)
+ .timeout(Duration::from_secs(120))
+ .body(chunk.clone())
+ .send()
+ .await
+ {
+ Ok(upload_response) => {
+ if upload_response.status().is_success() {
+ if let Some(etag_val) = upload_response.headers().get("ETag") {
+ let e = etag_val
+ .to_str()
+ .unwrap_or("")
+ .trim_matches('"')
+ .to_string();
+ println!("Received ETag {} for part {}", e, *part_number);
+ etag = Some(e);
+ } else {
+ println!("No ETag in response for part {}", *part_number);
+ retry_count += 1;
+ sleep(Duration::from_secs(2)).await;
+ }
+ } else {
+ println!(
+ "Failed part {} (status {}). Will retry if possible.",
+ *part_number,
+ upload_response.status()
+ );
+ if let Ok(body) = upload_response.text().await {
+ println!("Error response: {}", body);
+ }
+ retry_count += 1;
+ sleep(Duration::from_secs(2)).await;
+ }
+ }
+ Err(e) => {
+ println!(
+ "Part {} upload error (attempt {}/{}): {}",
+ *part_number,
+ retry_count + 1,
+ max_retries,
+ e
+ );
+ retry_count += 1;
+ sleep(Duration::from_secs(2)).await;
+ }
+ }
+ }
+
+ let etag = match etag {
+ Some(e) => e,
+ None => {
+ return Err(format!(
+ "Failed to upload part {} after {} attempts",
+ *part_number, max_retries
+ ))
+ }
+ };
+
+ // Advance the global progress
+ *last_uploaded_position += total_read as u64;
+ println!(
+ "After upload: new last_uploaded_position is {} ({}% of file)",
+ *last_uploaded_position,
+ (*last_uploaded_position as f64 / file_size as f64 * 100.0) as u32
+ );
+
+ let part = UploadedPart {
+ part_number: *part_number,
+ etag,
+ size: total_read,
+ };
+ *part_number += 1;
+ Ok(part)
+ }
+
+ /// Completes the multipart upload with the stored parts.
+ /// Logs a final location if the complete call is successful.
+ async fn finalize_upload(
+ app: &AppHandle,
+ file_path: &PathBuf,
+ file_key: &str,
+ upload_id: &str,
+ uploaded_parts: &[UploadedPart],
+ video_id: &str,
+ ) -> Result<(), String> {
+ println!(
+ "Completing multipart upload with {} parts",
+ uploaded_parts.len()
+ );
+
+ if uploaded_parts.is_empty() {
+ return Err("No parts uploaded before finalizing.".to_string());
+ }
+
+ let mut total_bytes_in_parts = 0;
+ for part in uploaded_parts {
+ let pn = part.part_number;
+ let size = part.size;
+ let etag = &part.etag;
+ total_bytes_in_parts += part.size;
+ println!("Part {}: {} bytes (ETag: {})", pn, size, etag);
+ }
+
+ let file_final_size = tokio::fs::metadata(file_path)
+ .await
+ .map(|md| md.len())
+ .unwrap_or(0);
+
+ println!("Sum of all parts: {} bytes", total_bytes_in_parts);
+ println!("File size on disk: {} bytes", file_final_size);
+ println!("Proceeding with multipart upload completion...");
+
+ let complete_response = match app
+ .authed_api_request(|c| {
+ c.post(web_api::make_url("/api/upload/multipart/complete"))
+ .header("Content-Type", "application/json")
+ .json(&serde_json::json!({
+ "fileKey": file_key,
+ "uploadId": upload_id,
+ "parts": uploaded_parts
+ }))
+ })
+ .await
+ {
+ Ok(response) => response,
+ Err(e) => {
+ return Err(format!("Failed to complete multipart upload: {}", e));
+ }
+ };
+
+ if !complete_response.status().is_success() {
+ let status = complete_response.status();
+ let error_body = complete_response
+ .text()
+ .await
+ .unwrap_or_else(|_| "<no response body>".to_string());
+ return Err(format!(
+ "Failed to complete multipart upload. Status: {}. Body: {}",
+ status, error_body
+ ));
+ }
+
+ let complete_data = match complete_response.json::<serde_json::Value>().await {
+ Ok(d) => d,
+ Err(e) => {
+ return Err(format!("Failed to parse completion response: {}", e));
+ }
+ };
+
+ if let Some(location) = complete_data.get("location") {
+ println!("Multipart upload complete. Final S3 location: {location}");
+ } else {
+ println!("Multipart upload complete. No 'location' in response.");
+ }
+
+ println!("Multipart upload complete for {video_id}.");
+ Ok(())
+ }
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct UploadedPart {
+ part_number: i32,
+ etag: String,
+ size: usize,
+}
diff --git a/apps/desktop/src-tauri/src/web_api.rs b/apps/desktop/src-tauri/src/web_api.rs
index 46cb62b81..7e06bd21c 100644
--- a/apps/desktop/src-tauri/src/web_api.rs
+++ b/apps/desktop/src-tauri/src/web_api.rs
@@ -5,7 +5,7 @@ use tauri_specta::Event;
use crate::auth::{AuthStore, AuthenticationInvalid};
pub fn make_url(pathname: impl AsRef<str>) -> String {
- let server_url_base = dotenvy_macro::dotenv!("VITE_SERVER_URL");
+ let server_url_base = std::option_env!("VITE_SERVER_URL").unwrap_or("https://cap.so");
format!("{server_url_base}{}", pathname.as_ref())
}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index d17407537..ffc63bb39 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -273,7 +273,6 @@ export type OSPermission = "screenRecording" | "camera" | "microphone" | "access
export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }
export type Plan = { upgraded: boolean; manual: boolean; last_checked: number }
-export type PreCreatedVideo = { id: string; link: string; config: S3UploadMeta }
export type Preset = { name: string; config: ProjectConfiguration }
export type PresetsStore = { presets: Preset[]; default: number | null }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
@@ -303,12 +302,13 @@ export type SingleSegment = { display: Display; camera?: CameraMeta | null; audi
export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }
-export type UploadMode = { Initial: { pre_created_video: PreCreatedVideo | null } } | "Reupload"
+export type UploadMode = { Initial: { pre_created_video: VideoUploadInfo | null } } | "Reupload"
export type UploadProgress = { progress: number; message: string }
export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
export type Video = { duration: number; width: number; height: number; fps: number }
export type VideoRecordingMetadata = { duration: number; size: number }
export type VideoType = "screen" | "output" | "camera"
+export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }
export type XY<T> = { x: T; y: T }
export type ZoomMode = "auto" | { manual: { x: number; y: number } }
export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode }
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index efa3b836a..6ed96cb94 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -81,7 +81,7 @@ export async function GET(request: NextRequest) {
}
const Bucket = await getS3Bucket(bucket);
- const s3Client = await createS3Client(bucket);
+ const [s3Client] = await createS3Client(bucket);
if (!bucket || video.awsBucket === clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET) {
if (video.source.type === "desktopMP4") {
diff --git a/apps/web/app/api/screenshot/route.ts b/apps/web/app/api/screenshot/route.ts
index 0025e6d58..61c48193c 100644
--- a/apps/web/app/api/screenshot/route.ts
+++ b/apps/web/app/api/screenshot/route.ts
@@ -79,7 +79,7 @@ export async function GET(request: NextRequest) {
const screenshotPrefix = `${userId}/${videoId}/`;
try {
- const s3Client = await createS3Client(bucket);
+ const [s3Client] = await createS3Client(bucket);
const objectsCommand = new ListObjectsV2Command({
Bucket,
diff --git a/apps/web/app/api/upload/multipart/[...route]/route.ts b/apps/web/app/api/upload/multipart/[...route]/route.ts
new file mode 100644
index 000000000..39ccd6e38
--- /dev/null
+++ b/apps/web/app/api/upload/multipart/[...route]/route.ts
@@ -0,0 +1,408 @@
+import { Hono } from "hono";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
+import {
+ CompleteMultipartUploadCommand,
+ CopyObjectCommand,
+ CreateMultipartUploadCommand,
+ HeadObjectCommand,
+ UploadPartCommand,
+} from "@aws-sdk/client-s3";
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { s3Buckets } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+import { zValidator } from "@hono/zod-validator";
+import { z } from "zod";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+import { clientEnv } from "@cap/env";
+import { handle } from "hono/vercel";
+import { cookies } from "next/headers";
+
+const app = new Hono().basePath("/api/upload/multipart").use<{
+ Variables: { user: NonNullable<Awaited<ReturnType<typeof getCurrentUser>>> };
+}>(async (c, next) => {
+ const token = c.req.header("authorization")?.split(" ")[1];
+ if (token) {
+ cookies().set({
+ name: "next-auth.session-token",
+ value: token,
+ path: "/",
+ sameSite: "none",
+ secure: true,
+ httpOnly: true,
+ });
+ }
+
+ const user = await getCurrentUser();
+ if (!user) {
+ return c.json({ error: true }, 401);
+ }
+
+ c.set("user", user);
+
+ await next();
+});
+
+app.post(
+ "/initiate",
+ zValidator(
+ "json",
+ z.object({ fileKey: z.string(), contentType: z.string() })
+ ),
+ async (c) => {
+ const { fileKey, contentType } = c.req.valid("json");
+ const user = c.get("user");
+
+ try {
+ try {
+ const { s3Client, bucketName } = await getUserBucketWithClient(user.id);
+
+ const finalContentType = contentType || "video/mp4";
+ console.log(
+ `Creating multipart upload in bucket: ${bucketName}, content-type: ${finalContentType}, key: ${fileKey}`
+ );
+
+ const command = new CreateMultipartUploadCommand({
+ Bucket: bucketName,
+ Key: fileKey,
+ ContentType: finalContentType,
+ Metadata: {
+ userId: user.id,
+ source: "cap-multipart-upload",
+ },
+ CacheControl: "max-age=31536000",
+ });
+
+ const result = await s3Client.send(command);
+ const { UploadId } = result;
+
+ if (!UploadId) {
+ throw new Error("No UploadId returned from S3");
+ }
+
+ console.log(
+ `Successfully initiated multipart upload with ID: ${UploadId}`
+ );
+ console.log(
+ `Upload details: Bucket=${bucketName}, Key=${fileKey}, ContentType=${finalContentType}`
+ );
+
+ return c.json({ uploadId: UploadId });
+ } catch (s3Error) {
+ console.error("S3 operation failed:", s3Error);
+ throw new Error(
+ `S3 operation failed: ${
+ s3Error instanceof Error ? s3Error.message : "Unknown error"
+ }`
+ );
+ }
+ } catch (error) {
+ console.error("Error initiating multipart upload", error);
+ return c.json(
+ {
+ error: "Error initiating multipart upload",
+ details: error instanceof Error ? error.message : String(error),
+ },
+ 500
+ );
+ }
+ }
+);
+
+app.post(
+ "/presign-part",
+ zValidator(
+ "json",
+ z.object({
+ fileKey: z.string(),
+ uploadId: z.string(),
+ partNumber: z.number(),
+ })
+ ),
+ async (c) => {
+ const { fileKey, uploadId, partNumber } = c.req.valid("json");
+ const user = c.get("user");
+
+ try {
+ try {
+ const { s3Client, s3Config, bucketName } =
+ await getUserBucketWithClient(user.id);
+
+ console.log(
+ `Getting presigned URL for part ${partNumber} of upload ${uploadId}`
+ );
+
+ const command = new UploadPartCommand({
+ Bucket: bucketName,
+ Key: fileKey,
+ UploadId: uploadId,
+ PartNumber: partNumber,
+ });
+
+ const presignedUrl = await getSignedUrl(s3Client, command, {
+ expiresIn: 3600,
+ });
+
+ let finalUrl = presignedUrl;
+
+ if (s3Config.endpoint) {
+ const urlObj = new URL(presignedUrl);
+
+ const queryString = urlObj.search;
+
+ if (
+ s3Config.endpoint.includes("localhost") ||
+ s3Config?.forcePathStyle
+ ) {
+ finalUrl = `${s3Config.endpoint}/${bucketName}/${fileKey}${queryString}`;
+
+ const updatedUrl = new URL(finalUrl);
+ updatedUrl.searchParams.set("partNumber", partNumber.toString());
+ updatedUrl.searchParams.set("uploadId", uploadId);
+ finalUrl = updatedUrl.toString();
+
+ console.log(
+ `Using path-style URL for part ${partNumber}: ${finalUrl}`
+ );
+ } else {
+ finalUrl = presignedUrl;
+ }
+ }
+
+ console.log(
+ `Generated presigned URL for part ${partNumber}: ${finalUrl}`
+ );
+ return c.json({ presignedUrl: finalUrl });
+ } catch (s3Error) {
+ console.error("S3 operation failed:", s3Error);
+ throw new Error(
+ `S3 operation failed: ${
+ s3Error instanceof Error ? s3Error.message : "Unknown error"
+ }`
+ );
+ }
+ } catch (error) {
+ console.error("Error creating presigned URL for part", error);
+ return c.json(
+ {
+ error: "Error creating presigned URL for part",
+ details: error instanceof Error ? error.message : String(error),
+ },
+ 500
+ );
+ }
+ }
+);
+
+app.post(
+ "/complete",
+ zValidator(
+ "json",
+ z.object({
+ fileKey: z.string(),
+ uploadId: z.string(),
+ parts: z.array(
+ z.object({
+ partNumber: z.number(),
+ etag: z.string(),
+ size: z.number(),
+ })
+ ),
+ })
+ ),
+ async (c) => {
+ const { fileKey, uploadId, parts } = c.req.valid("json");
+ const user = c.get("user");
+
+ try {
+ try {
+ const { s3Client, bucketName } = await getUserBucketWithClient(user.id);
+
+ console.log(
+ `Completing multipart upload ${uploadId} with ${parts.length} parts for key: ${fileKey}`
+ );
+
+ const totalSize = parts.reduce((acc, part) => acc + part.size, 0);
+ console.log(`Total size of all parts: ${totalSize} bytes`);
+
+ const sortedParts = [...parts].sort(
+ (a, b) => a.partNumber - b.partNumber
+ );
+
+ const sequentialCheck = sortedParts.every(
+ (part, index) => part.partNumber === index + 1
+ );
+
+ if (!sequentialCheck) {
+ console.warn(
+ "WARNING: Part numbers are not sequential! This may cause issues with the assembled file."
+ );
+ }
+
+ const formattedParts = sortedParts.map((part) => ({
+ PartNumber: part.partNumber,
+ ETag: part.etag,
+ }));
+
+ console.log(
+ "Sending to S3:",
+ JSON.stringify(
+ {
+ Bucket: bucketName,
+ Key: fileKey,
+ UploadId: uploadId,
+ Parts: formattedParts,
+ },
+ null,
+ 2
+ )
+ );
+
+ const command = new CompleteMultipartUploadCommand({
+ Bucket: bucketName,
+ Key: fileKey,
+ UploadId: uploadId,
+ MultipartUpload: {
+ Parts: formattedParts,
+ },
+ });
+
+ try {
+ const result = await s3Client.send(command);
+ console.log(
+ `Multipart upload completed successfully: ${
+ result.Location || "no location"
+ }`
+ );
+ console.log(`Complete response: ${JSON.stringify(result, null, 2)}`);
+
+ try {
+ console.log(
+ "Performing metadata fix by copying the object to itself..."
+ );
+ const copyCommand = new CopyObjectCommand({
+ Bucket: bucketName,
+ CopySource: `${bucketName}/${fileKey}`,
+ Key: fileKey,
+ ContentType: "video/mp4",
+ MetadataDirective: "REPLACE",
+ });
+
+ const copyResult = await s3Client.send(copyCommand);
+ console.log("Copy for metadata fix successful:", copyResult);
+ } catch (copyError) {
+ console.error(
+ "Warning: Failed to copy object to fix metadata:",
+ copyError
+ );
+ }
+
+ try {
+ const headCommand = new HeadObjectCommand({
+ Bucket: bucketName,
+ Key: fileKey,
+ });
+
+ const headResult = await s3Client.send(headCommand);
+ console.log(
+ `Object verification successful: ContentType=${headResult.ContentType}, ContentLength=${headResult.ContentLength}`
+ );
+ } catch (headError) {
+ console.error(`Warning: Unable to verify object: ${headError}`);
+ }
+
+ const videoId = fileKey.split("/")[1];
+ if (videoId) {
+ try {
+ await fetch(`${clientEnv.NEXT_PUBLIC_WEB_URL}/api/revalidate`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ videoId }),
+ });
+ console.log(`Revalidation triggered for videoId: ${videoId}`);
+ } catch (revalidateError) {
+ console.error("Failed to revalidate page:", revalidateError);
+ }
+ }
+
+ return c.json({
+ location: result.Location,
+ success: true,
+ fileKey,
+ bucketName,
+ });
+ } catch (completeError) {
+ console.error("Failed to complete multipart upload:", completeError);
+ return c.json(
+ {
+ error: "Failed to complete multipart upload",
+ details:
+ completeError instanceof Error
+ ? completeError.message
+ : String(completeError),
+ uploadId,
+ fileKey,
+ parts: formattedParts.length,
+ },
+ 500
+ );
+ }
+ } catch (s3Error) {
+ console.error("S3 operation failed:", s3Error);
+ throw new Error(
+ `S3 operation failed: ${
+ s3Error instanceof Error ? s3Error.message : "Unknown error"
+ }`
+ );
+ }
+ } catch (error) {
+ console.error("Error completing multipart upload", error);
+ return c.json(
+ {
+ error: "Error completing multipart upload",
+ details: error instanceof Error ? error.message : String(error),
+ },
+ 500
+ );
+ }
+ }
+);
+
+async function getUserBucketWithClient(userId: string) {
+ const [bucket] = await db
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, userId));
+
+ console.log("S3 bucket configuration:", {
+ hasEndpoint: !!bucket?.endpoint,
+ endpoint: bucket?.endpoint || "N/A",
+ region: bucket?.region || "N/A",
+ hasAccessKey: !!bucket?.accessKeyId,
+ hasSecretKey: !!bucket?.secretAccessKey,
+ });
+
+ const initialS3Config = bucket
+ ? {
+ endpoint: bucket.endpoint || undefined,
+ region: bucket.region,
+ accessKeyId: bucket.accessKeyId,
+ secretAccessKey: bucket.secretAccessKey,
+ forcePathStyle: true,
+ }
+ : null;
+
+ if (!initialS3Config?.endpoint && !initialS3Config?.region) {
+ console.log("Using default S3 configuration");
+ }
+
+ const [s3Client, s3Config] = await createS3Client(initialS3Config);
+ const bucketName = await getS3Bucket(bucket);
+
+ return { s3Client, s3Config, bucketName };
+}
+
+export const GET = handle(app);
+export const POST = handle(app);
diff --git a/apps/web/app/api/upload/mux/create/route.ts b/apps/web/app/api/upload/mux/create/route.ts
index 6d721d6ae..ffa5289d3 100644
--- a/apps/web/app/api/upload/mux/create/route.ts
+++ b/apps/web/app/api/upload/mux/create/route.ts
@@ -128,7 +128,7 @@ export async function GET(request: NextRequest) {
const audioPrefix = `${userId}/${videoId}/audio/`;
try {
- const s3Client = await createS3Client(bucket);
+ const [s3Client] = await createS3Client(bucket);
const videoSegmentCommand = new ListObjectsV2Command({
Bucket,
diff --git a/apps/web/app/api/video/individual/route.ts b/apps/web/app/api/video/individual/route.ts
index 1a14e40f7..5092a545b 100644
--- a/apps/web/app/api/video/individual/route.ts
+++ b/apps/web/app/api/video/individual/route.ts
@@ -73,7 +73,7 @@ export async function GET(request: NextRequest) {
const individualPrefix = `${userId}/${videoId}/individual/`;
try {
- const s3Client = await createS3Client(bucket);
+ const [s3Client] = await createS3Client(bucket);
const objectsCommand = new ListObjectsV2Command({
Bucket,
diff --git a/apps/web/app/api/video/og/route.tsx b/apps/web/app/api/video/og/route.tsx
index 157c7b6e3..6273f71d5 100644
--- a/apps/web/app/api/video/og/route.tsx
+++ b/apps/web/app/api/video/og/route.tsx
@@ -74,7 +74,7 @@ export async function GET(req: NextRequest) {
);
}
- const s3Client = await createS3Client(bucket);
+ const [s3Client] = await createS3Client(bucket);
const Bucket = await getS3Bucket(bucket);
const screenshotKey = `${video.ownerId}/${video.id}/screenshot/screen-capture.jpg`;
diff --git a/apps/web/app/api/video/transcribe/route.ts b/apps/web/app/api/video/transcribe/route.ts
index 5c2f5ac90..d1bbd3706 100644
--- a/apps/web/app/api/video/transcribe/route.ts
+++ b/apps/web/app/api/video/transcribe/route.ts
@@ -131,7 +131,7 @@ export async function GET(request: NextRequest) {
.set({ transcriptionStatus: "PROCESSING" })
.where(eq(videos.id, videoId));
- const s3Client = await createS3Client(bucket);
+ const [s3Client] = await createS3Client(bucket);
try {
const videoKey = `${userId}/${videoId}/result.mp4`;
diff --git a/apps/web/package.json b/apps/web/package.json
index dd61cc9e1..a7b4a012e 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -26,6 +26,7 @@
"@fortawesome/free-solid-svg-icons": "^6.7.2",
"@fortawesome/react-fontawesome": "^0.2.2",
"@headlessui/react": "^1.7.17",
+ "@hono/zod-validator": "^0.4.3",
"@hookform/resolvers": "^3.3.2",
"@intercom/messenger-js-sdk": "^0.0.14",
"@mux/mux-node": "^8.5.1",
@@ -52,6 +53,7 @@
"framer-motion": "^11.13.1",
"geist": "^1.3.1",
"hls.js": "^1.5.3",
+ "hono": "^4.7.1",
"jszip": "^3.10.1",
"lodash": "^4.17.21",
"lucide-react": "^0.294.0",
diff --git a/apps/web/utils/s3.ts b/apps/web/utils/s3.ts
index 925f13627..0a4a6743f 100644
--- a/apps/web/utils/s3.ts
+++ b/apps/web/utils/s3.ts
@@ -9,6 +9,7 @@ type S3Config = {
region?: string;
accessKeyId?: string;
secretAccessKey?: string;
+ forcePathStyle?: boolean;
} | null;
async function tryDecrypt(
@@ -32,15 +33,25 @@ export async function getS3Config(config?: S3Config) {
accessKeyId: serverEnv.CAP_AWS_ACCESS_KEY ?? "",
secretAccessKey: serverEnv.CAP_AWS_SECRET_KEY ?? "",
},
+ forcePathStyle: true,
};
}
+ const endpoint = config.endpoint
+ ? await tryDecrypt(config.endpoint)
+ : clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT;
+
+ const region =
+ (await tryDecrypt(config.region)) ?? clientEnv.NEXT_PUBLIC_CAP_AWS_REGION;
+
+ const finalRegion = endpoint?.includes("localhost") ? "us-east-1" : region;
+
+ const isLocalOrMinio =
+ endpoint?.includes("localhost") || endpoint?.includes("127.0.0.1");
+
return {
- endpoint: config.endpoint
- ? await tryDecrypt(config.endpoint)
- : clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
- region:
- (await tryDecrypt(config.region)) ?? clientEnv.NEXT_PUBLIC_CAP_AWS_REGION,
+ endpoint,
+ region: finalRegion,
credentials: {
accessKeyId:
(await tryDecrypt(config.accessKeyId)) ??
@@ -51,6 +62,13 @@ export async function getS3Config(config?: S3Config) {
serverEnv.CAP_AWS_SECRET_KEY ??
"",
},
+ forcePathStyle: config.forcePathStyle ?? true,
+ useAccelerateEndpoint: isLocalOrMinio ? false : true,
+ useArnRegion: false,
+ requestHandler: {
+ connectionTimeout: isLocalOrMinio ? 5000 : 10000,
+ socketTimeout: isLocalOrMinio ? 30000 : 60000,
+ },
};
}
@@ -69,5 +87,16 @@ export async function getS3Bucket(
}
export async function createS3Client(config?: S3Config) {
- return new S3Client(await getS3Config(config));
+ const s3Config = await getS3Config(config);
+ const isLocalOrMinio =
+ s3Config.endpoint?.includes("localhost") ||
+ s3Config.endpoint?.includes("127.0.0.1");
+
+ return [
+ new S3Client({
+ ...s3Config,
+ maxAttempts: isLocalOrMinio ? 5 : 3,
+ }),
+ s3Config,
+ ] as const;
}
diff --git a/crates/media/src/encoders/mp4_avassetwriter.rs b/crates/media/src/encoders/mp4_avassetwriter.rs
index 3ced458c8..68a499e7d 100644
--- a/crates/media/src/encoders/mp4_avassetwriter.rs
+++ b/crates/media/src/encoders/mp4_avassetwriter.rs
@@ -70,9 +70,8 @@ impl MP4AVAssetWriterEncoder {
ns::Number::with_u32(output_height).as_id_ref(),
);
- let bitrate = video_config.width as f32 * video_config.height as f32
- / (1920.0 * 1080.0)
- * 14_000_000.0
+ let bitrate = output_width as f32 * output_height as f32 / (1920.0 * 1080.0)
+ * 10_000_000.0
+ fps / 30.0 * 6_000_000.0;
output_settings.insert(
diff --git a/crates/media/src/feeds/audio_input.rs b/crates/media/src/feeds/audio_input.rs
index 7ca75c57c..373698c0c 100644
--- a/crates/media/src/feeds/audio_input.rs
+++ b/crates/media/src/feeds/audio_input.rs
@@ -95,7 +95,6 @@ impl AudioInputFeed {
}
pub fn list_devices() -> AudioInputDeviceMap {
- info!("Listing available audio input devices");
let host = cpal::default_host();
let mut device_map = IndexMap::new();
@@ -112,7 +111,6 @@ impl AudioInputFeed {
.ok()
.and_then(|configs| {
let mut configs = configs.collect::<Vec<_>>();
- debug!("Found {} supported configs", configs.len());
configs.sort_by(|a, b| {
b.sample_format()
.sample_size()
@@ -127,17 +125,16 @@ impl AudioInputFeed {
.find(|c| ffmpeg_sample_format_for(c.sample_format()).is_some())
})
.and_then(|config| {
- device.name().ok().map(|name| {
- debug!("Found usable device: {} with config: {:?}", name, config);
- (name, device, config.with_max_sample_rate())
- })
+ 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)
{
- info!("Found default input device: {}", name);
device_map.insert(name, (device, config));
} else {
warn!("No default input device found or it's not usable");
@@ -146,7 +143,6 @@ impl AudioInputFeed {
match host.input_devices() {
Ok(devices) => {
for (name, device, config) in devices.filter_map(get_usable_device) {
- debug!("Found additional device: {}", name);
device_map.entry(name).or_insert((device, config));
}
}
@@ -155,7 +151,6 @@ impl AudioInputFeed {
}
}
- info!("Found {} usable audio input devices", device_map.len());
device_map
}
@@ -213,7 +208,7 @@ fn start_capturing(
mut config: SupportedStreamConfig,
control: Receiver<AudioInputControl>,
) {
- info!(
+ debug!(
"Starting audio capture with device: {:?}, config: {:?}",
device.name(),
config
@@ -222,7 +217,7 @@ fn start_capturing(
loop {
let (tx, rx) = flume::bounded(4);
- info!("Building input stream with config: {:?}", config);
+ debug!("Building input stream with config: {:?}", config);
let stream_config: StreamConfig = config.clone().into();
let stream = match device.build_input_stream_raw(
@@ -269,13 +264,13 @@ fn start_capturing(
continue;
}
- info!("Switching audio device to: {}", name);
+ debug!("Switching audio device to: {}", name);
// list_devices hangs if the stream isn't dropped
drop(stream);
let Some(items) = AudioInputFeed::list_devices().swap_remove_entry(&name).map(
|(device_name, (device, config))| {
info!(
- "Switching to audio device: {} with config: {:?}",
+ "Switched to audio device: {} with config: {:?}",
device_name, config
);
(device, config)
@@ -295,12 +290,12 @@ fn start_capturing(
break;
}
Ok(AudioInputControl::Shutdown) => {
- info!("Received shutdown signal for audio capture");
+ debug!("Received shutdown signal for audio capture");
return;
}
Ok(AudioInputControl::AttachSender(sender)) => {
- info!("New audio sender attached");
senders.push(sender);
+ info!("New audio sender attached");
}
Err(flume::TryRecvError::Disconnected) => {
warn!("Control receiver is unreachable! Shutting down audio capture");
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 45c9b6131..b638a675b 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -77,7 +77,7 @@ impl ScreenCaptureTarget {
}
pub fn get_title(&self) -> Option<String> {
- let target = dbg!(self.get_target());
+ let target = self.get_target();
match target {
None => None,
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index db4ddd6aa..4a1296f09 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -10,7 +10,6 @@ use cap_media::platform::Bounds;
use cap_project::{CursorClickEvent, CursorMoveEvent, XY};
use cap_utils::spawn_actor;
use device_query::{DeviceQuery, DeviceState};
-use image::GenericImageView;
use tokio::sync::oneshot;
use tracing::{debug, error, info};
@@ -59,6 +58,9 @@ pub fn spawn_cursor_recorder(
let device_state = DeviceState::new();
let mut last_mouse_state = device_state.get_mouse();
+ // Create cursors directory if it doesn't exist
+ std::fs::create_dir_all(&cursors_dir).unwrap();
+
let mut response = CursorActorResponse {
cursors: prev_cursors,
next_cursor_id,
@@ -66,9 +68,6 @@ pub fn spawn_cursor_recorder(
clicks: vec![],
};
- // Create cursors directory if it doesn't exist
- std::fs::create_dir_all(&cursors_dir).unwrap();
-
let start_time = Instant::now();
while !stop_signal.load(std::sync::atomic::Ordering::Relaxed) {
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 7bfaffd7f..601e28ed9 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -13,7 +13,7 @@ use cap_media::{
MediaError,
};
use cap_project::InstantRecordingMeta;
-use cap_utils::spawn_actor;
+use cap_utils::{ensure_dir, spawn_actor};
use tokio::sync::oneshot;
use tracing::{debug, error, info, instrument::WithSubscriber, trace, Instrument};
use tracing_subscriber::{layer::SubscriberExt, Layer};
@@ -137,233 +137,188 @@ pub async fn spawn_instant_recording_actor(
audio_input_feed: Option<AudioInputFeed>,
) -> Result<(InstantRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
ensure_dir(&recording_dir)?;
- let logfile = File::create(recording_dir.join("recording-logs.log"))?;
-
- let collector = tracing_subscriber::registry()
- .with(
- tracing_subscriber::fmt::layer()
- .with_ansi(false)
- .with_target(false)
- .with_writer(logfile)
- .with_filter(
- tracing_subscriber::filter::EnvFilter::builder()
- .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
- .from_env_lossy(),
- ),
- )
- .with(
- tracing_subscriber::fmt::layer()
- .with_ansi(true)
- .with_target(false)
- .with_filter(
- tracing_subscriber::filter::EnvFilter::builder()
- .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
- .from_env_lossy(),
- ),
- );
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
- async {
- async {
- let run = async || {
- trace!("creating recording actor");
-
- let content_dir = ensure_dir(&recording_dir.join("content"))?;
-
- let screen_source = create_screen_capture(&options.capture_target, true, true, 30)?;
-
- debug!("screen capture: {screen_source:#?}");
-
- if let Some(audio_feed) = &audio_input_feed {
- debug!("mic audio info: {:#?}", audio_feed.audio_info())
- }
-
- let (pipeline, pipeline_done_rx) = create_pipeline(
- content_dir.join("output.mp4"),
- screen_source.clone(),
- audio_input_feed.as_ref(),
- )
- .await?;
-
- let segment_start_time = current_time_f64();
-
- let (ctrl_tx, ctrl_rx) = flume::bounded(1);
-
- trace!("spawning recording actor");
-
- spawn_actor({
- let options = options.clone();
- let video_info = screen_source.info();
- async move {
- let mut actor = InstantRecordingActor {
- id,
- recording_dir,
- capture_target: options.capture_target,
- video_info,
- audio_input_name: options.audio_input_name,
- };
-
- let mut state = InstantRecordingActorState::Recording {
- pipeline,
- pipeline_done_rx,
- segment_start_time,
- };
-
- 'outer: loop {
- state = match state {
- InstantRecordingActorState::Recording {
- mut pipeline,
- mut pipeline_done_rx,
- segment_start_time,
- } => {
- info!("recording actor recording");
- loop {
- let msg = tokio::select! {
- _ = &mut pipeline_done_rx => {
- break 'outer;
- }
- msg = ctrl_rx.recv_async() => {
- let Ok(msg) = msg else {
- break 'outer;
- };
-
- info!("received control message: {msg:?}");
-
- msg
- }
- };
-
- async fn shutdown(
- mut pipeline: InstantRecordingPipeline,
- actor: &mut InstantRecordingActor,
- segment_start_time: f64,
- ) -> Result<(), RecordingError>
- {
- pipeline.inner.shutdown().await?;
- Ok(())
- }
-
- break match msg {
- InstantRecordingActorControlMessage::Pause(tx) => {
- InstantRecordingActorState::Recording {
- pipeline,
- pipeline_done_rx,
- segment_start_time,
- }
- // let res = shutdown(
- // pipeline,
- // &mut actor,
- // segment_start_time,
- // )
- // .await;
-
- // tx.send(res.map_err(Into::into)).ok();
- // InstantRecordingActorState::Paused
- }
- InstantRecordingActorControlMessage::Stop(tx) => {
- let res = shutdown(
- pipeline,
- &mut actor,
- segment_start_time,
- )
- .await;
- let res = match res {
- Ok(_) => stop_recording(actor).await,
- Err(e) => Err(e),
- };
-
- tx.send(res).ok();
-
- break 'outer;
- }
- _ => continue,
- };
- }
+ trace!("creating recording actor");
+
+ let content_dir = ensure_dir(&recording_dir.join("content"))?;
+
+ let screen_source = create_screen_capture(&options.capture_target, true, true, 30)?;
+
+ debug!("screen capture: {screen_source:#?}");
+
+ if let Some(audio_feed) = &audio_input_feed {
+ debug!("mic audio info: {:#?}", audio_feed.audio_info())
+ }
+
+ let (pipeline, pipeline_done_rx) = create_pipeline(
+ content_dir.join("output.mp4"),
+ screen_source.clone(),
+ audio_input_feed.as_ref(),
+ )
+ .await?;
+
+ let segment_start_time = current_time_f64();
+
+ let (ctrl_tx, ctrl_rx) = flume::bounded(1);
+
+ trace!("spawning recording actor");
+
+ spawn_actor({
+ let options = options.clone();
+ let video_info = screen_source.info();
+ async move {
+ let mut actor = InstantRecordingActor {
+ id,
+ recording_dir,
+ capture_target: options.capture_target,
+ video_info,
+ audio_input_name: options.audio_input_name,
+ };
+
+ let mut state = InstantRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
+ segment_start_time,
+ };
+
+ 'outer: loop {
+ state = match state {
+ InstantRecordingActorState::Recording {
+ mut pipeline,
+ mut pipeline_done_rx,
+ segment_start_time,
+ } => {
+ info!("recording actor recording");
+ loop {
+ let msg = tokio::select! {
+ _ = &mut pipeline_done_rx => {
+ break 'outer;
}
- InstantRecordingActorState::Paused => {
- info!("recording actor paused");
- loop {
- let Ok(msg) = ctrl_rx.recv_async().await else {
- break 'outer;
- };
-
- break match msg {
- InstantRecordingActorControlMessage::Stop(tx) => {
- tx.send(stop_recording(actor).await).ok();
- break 'outer;
- }
- InstantRecordingActorControlMessage::Resume(tx) => {
- // let (state, res) = match create_pipeline(
- // &segments_dir,
- // &cursors_dir,
- // next_index,
- // screen_source.clone(),
- // camera_feed.as_deref(),
- // audio_input_feed.as_ref(),
- // cursors,
- // next_cursor_id,
- // )
- // .await
- // {
- // Ok((pipeline, pipeline_done_rx)) => (
- // InstantRecordingActorState::Recording {
- // pipeline,
- // pipeline_done_rx,
- // index: next_index,
- // segment_start_time: current_time_f64(),
- // },
- // Ok(()),
- // ),
- // Err(e) => (
- // InstantRecordingActorState::Stopped,
- // Err(e.into()),
- // ),
- // };
-
- // tx.send(res).ok();
-
- state
- }
- _ => continue,
- };
+ msg = ctrl_rx.recv_async() => {
+ let Ok(msg) = msg else {
+ break 'outer;
+ };
+
+ info!("received control message: {msg:?}");
+
+ msg
+ }
+ };
+
+ async fn shutdown(
+ mut pipeline: InstantRecordingPipeline,
+ actor: &mut InstantRecordingActor,
+ segment_start_time: f64,
+ ) -> Result<(), RecordingError> {
+ pipeline.inner.shutdown().await?;
+ Ok(())
+ }
+
+ break match msg {
+ InstantRecordingActorControlMessage::Pause(tx) => {
+ InstantRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
+ segment_start_time,
}
+ // let res = shutdown(
+ // pipeline,
+ // &mut actor,
+ // segment_start_time,
+ // )
+ // .await;
+
+ // tx.send(res.map_err(Into::into)).ok();
+ // InstantRecordingActorState::Paused
}
- InstantRecordingActorState::Stopped => {
- info!("recording actor paused");
- break;
+ InstantRecordingActorControlMessage::Stop(tx) => {
+ let res =
+ shutdown(pipeline, &mut actor, segment_start_time).await;
+ let res = match res {
+ Ok(_) => stop_recording(actor).await,
+ Err(e) => Err(e),
+ };
+
+ tx.send(res).ok();
+
+ break 'outer;
}
+ _ => continue,
};
}
-
- info!("recording actor finished");
-
- done_tx.send(()).ok();
}
- .in_current_span()
- });
-
- Ok(InstantRecordingHandle {
- ctrl_tx,
- options,
- bounds: screen_source.get_bounds().clone(),
- })
- };
+ InstantRecordingActorState::Paused => {
+ info!("recording actor paused");
+ loop {
+ let Ok(msg) = ctrl_rx.recv_async().await else {
+ break 'outer;
+ };
- match run().await {
- Ok(a) => Ok(a),
- Err(e) => {
- error!("Failed to start recording actor: {}", e);
- Err(e)
- }
+ break match msg {
+ InstantRecordingActorControlMessage::Stop(tx) => {
+ tx.send(stop_recording(actor).await).ok();
+ break 'outer;
+ }
+ InstantRecordingActorControlMessage::Resume(tx) => {
+ // let (state, res) = match create_pipeline(
+ // &segments_dir,
+ // &cursors_dir,
+ // next_index,
+ // screen_source.clone(),
+ // camera_feed.as_deref(),
+ // audio_input_feed.as_ref(),
+ // cursors,
+ // next_cursor_id,
+ // )
+ // .await
+ // {
+ // Ok((pipeline, pipeline_done_rx)) => (
+ // InstantRecordingActorState::Recording {
+ // pipeline,
+ // pipeline_done_rx,
+ // index: next_index,
+ // segment_start_time: current_time_f64(),
+ // },
+ // Ok(()),
+ // ),
+ // Err(e) => (
+ // InstantRecordingActorState::Stopped,
+ // Err(e.into()),
+ // ),
+ // };
+
+ // tx.send(res).ok();
+
+ state
+ }
+ _ => continue,
+ };
+ }
+ }
+ InstantRecordingActorState::Stopped => {
+ info!("recording actor paused");
+ break;
+ }
+ };
}
+
+ info!("recording actor finished");
+
+ done_tx.send(()).ok();
}
- .instrument(tracing::info_span!("recording"))
- .await
- }
- .with_subscriber(collector)
- .await
- .map(|a| (a, done_rx))
+ .in_current_span()
+ });
+
+ Ok((
+ InstantRecordingHandle {
+ ctrl_tx,
+ options,
+ bounds: screen_source.get_bounds().clone(),
+ },
+ done_rx,
+ ))
}
async fn stop_recording(
@@ -382,11 +337,6 @@ async fn stop_recording(
})
}
-fn ensure_dir(path: &PathBuf) -> Result<PathBuf, MediaError> {
- std::fs::create_dir_all(&path)?;
- Ok(path.clone())
-}
-
fn current_time_f64() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 4f744f568..4e7432997 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -115,289 +115,245 @@ pub async fn spawn_studio_recording_actor(
audio_input_feed: Option<AudioInputFeed>,
) -> Result<(StudioRecordingHandle, tokio::sync::oneshot::Receiver<()>), RecordingError> {
ensure_dir(&recording_dir)?;
- let logfile = File::create(recording_dir.join("recording-logs.log"))?;
-
- let collector = tracing_subscriber::registry()
- .with(
- tracing_subscriber::fmt::layer()
- .with_ansi(false)
- .with_target(false)
- .with_writer(logfile)
- .with_filter(
- tracing_subscriber::filter::EnvFilter::builder()
- .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
- .from_env_lossy(),
- ),
- )
- .with(
- tracing_subscriber::fmt::layer()
- .with_ansi(true)
- .with_target(false)
- .with_filter(
- tracing_subscriber::filter::EnvFilter::builder()
- .with_default_directive(tracing::level_filters::LevelFilter::TRACE.into())
- .from_env_lossy(),
- ),
- );
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
- async {
- let run = async || {
- trace!("creating recording actor");
+ trace!("creating recording actor");
- let content_dir = ensure_dir(&recording_dir.join("content"))?;
+ let content_dir = ensure_dir(&recording_dir.join("content"))?;
- let segments_dir = ensure_dir(&content_dir.join("segments"))?;
- let cursors_dir = ensure_dir(&content_dir.join("cursors"))?;
+ let segments_dir = ensure_dir(&content_dir.join("segments"))?;
+ let cursors_dir = ensure_dir(&content_dir.join("cursors"))?;
- let screen_source = create_screen_capture(&options.capture_target, false, false, 120)?;
- let bounds = screen_source.get_bounds().clone();
+ let screen_source = create_screen_capture(&options.capture_target, false, false, 120)?;
+ let bounds = screen_source.get_bounds().clone();
- debug!("screen capture: {screen_source:#?}");
+ debug!("screen capture: {screen_source:#?}");
- if let Some(camera_feed) = &camera_feed {
- let camera_feed = camera_feed.lock().await;
- debug!("camera device info: {:#?}", camera_feed.camera_info());
- debug!("camera video info: {:#?}", camera_feed.video_info());
- }
+ if let Some(camera_feed) = &camera_feed {
+ let camera_feed = camera_feed.lock().await;
+ debug!("camera device info: {:#?}", camera_feed.camera_info());
+ debug!("camera video info: {:#?}", camera_feed.video_info());
+ }
- if let Some(audio_feed) = &audio_input_feed {
- debug!("mic audio info: {:#?}", audio_feed.audio_info())
- }
+ if let Some(audio_feed) = &audio_input_feed {
+ debug!("mic audio info: {:#?}", audio_feed.audio_info())
+ }
- let index = 0;
- let (pipeline, pipeline_done_rx) = create_segment_pipeline(
- &segments_dir,
- &cursors_dir,
- index,
- screen_source.clone(),
- camera_feed.as_deref(),
- audio_input_feed.as_ref(),
- Default::default(),
+ let index = 0;
+ let (pipeline, pipeline_done_rx) = create_segment_pipeline(
+ &segments_dir,
+ &cursors_dir,
+ index,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ Default::default(),
+ index,
+ )
+ .await?;
+
+ let segment_start_time = current_time_f64();
+
+ let (ctrl_tx, ctrl_rx) = flume::bounded(1);
+
+ trace!("spawning recording actor");
+
+ spawn_actor({
+ let options = options.clone();
+ let fps = screen_source.info().fps();
+ async move {
+ let mut actor = StudioRecordingActor {
+ id,
+ recording_dir,
+ options,
+ fps,
+ segments: Vec::new(),
+ };
+
+ let mut state = StudioRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
index,
- )
- .await?;
-
- let segment_start_time = current_time_f64();
-
- let (ctrl_tx, ctrl_rx) = flume::bounded(1);
-
- trace!("spawning recording actor");
-
- spawn_actor({
- let options = options.clone();
- let fps = screen_source.info().fps();
- async move {
- let mut actor = StudioRecordingActor {
- id,
- recording_dir,
- options,
- fps,
- segments: Vec::new(),
- };
-
- let mut state = StudioRecordingActorState::Recording {
- pipeline,
- pipeline_done_rx,
+ segment_start_time,
+ };
+
+ 'outer: loop {
+ state = match state {
+ StudioRecordingActorState::Recording {
+ mut pipeline,
+ mut pipeline_done_rx,
index,
segment_start_time,
- };
-
- 'outer: loop {
- state = match state {
- StudioRecordingActorState::Recording {
- mut pipeline,
- mut pipeline_done_rx,
- index,
- segment_start_time,
- } => {
- info!("recording actor recording");
- loop {
- let msg = tokio::select! {
- _ = &mut pipeline_done_rx => {
- if let Some(cursor) = &mut pipeline.cursor {
- if let Some(actor) = cursor.actor.take() {
- actor.stop().await;
- }
- }
-
- break 'outer;
+ } => {
+ info!("recording actor recording");
+ loop {
+ let msg = tokio::select! {
+ _ = &mut pipeline_done_rx => {
+ if let Some(cursor) = &mut pipeline.cursor {
+ if let Some(actor) = cursor.actor.take() {
+ actor.stop().await;
}
- msg = ctrl_rx.recv_async() => {
- let Ok(msg) = msg else {
- break 'outer;
- };
+ }
- msg
- }
+ break 'outer;
+ }
+ msg = ctrl_rx.recv_async() => {
+ let Ok(msg) = msg else {
+ break 'outer;
};
- async fn shutdown(
- mut pipeline: StudioRecordingPipeline,
- actor: &mut StudioRecordingActor,
- segment_start_time: f64,
- ) -> Result<(Cursors, u32), RecordingError>
- {
- pipeline.inner.shutdown().await?;
-
- let segment_stop_time = current_time_f64();
+ msg
+ }
+ };
+
+ async fn shutdown(
+ mut pipeline: StudioRecordingPipeline,
+ actor: &mut StudioRecordingActor,
+ segment_start_time: f64,
+ ) -> Result<(Cursors, u32), RecordingError>
+ {
+ pipeline.inner.shutdown().await?;
+
+ let segment_stop_time = current_time_f64();
+
+ let cursors = if let Some(cursor) = &mut pipeline.cursor {
+ if let Some(actor) = cursor.actor.take() {
+ let res = actor.stop().await;
+
+ std::fs::write(
+ &cursor.output_path,
+ serde_json::to_string_pretty(&CursorEvents {
+ clicks: res.clicks,
+ moves: res.moves,
+ })?,
+ )?;
+
+ (res.cursors, res.next_cursor_id)
+ } else {
+ Default::default()
+ }
+ } else {
+ Default::default()
+ };
- let cursors = if let Some(cursor) = &mut pipeline.cursor {
- if let Some(actor) = cursor.actor.take() {
- let res = actor.stop().await;
+ actor.segments.push(StudioRecordingSegment {
+ start: segment_start_time,
+ end: segment_stop_time,
+ pipeline,
+ });
- std::fs::write(
- &cursor.output_path,
- serde_json::to_string_pretty(&CursorEvents {
- clicks: res.clicks,
- moves: res.moves,
- })?,
- )?;
+ Ok(cursors)
+ }
- (res.cursors, res.next_cursor_id)
- } else {
- Default::default()
+ break match msg {
+ StudioRecordingActorControlMessage::Pause(tx) => {
+ let (res, cursors, next_cursor_id) =
+ match shutdown(pipeline, &mut actor, segment_start_time)
+ .await
+ {
+ Ok((cursors, next_cursor_id)) => {
+ (Ok(()), cursors, next_cursor_id)
}
- } else {
- Default::default()
+ Err(e) => (Err(e), Default::default(), 0),
};
- actor.segments.push(StudioRecordingSegment {
- start: segment_start_time,
- end: segment_stop_time,
- pipeline,
- });
-
- Ok(cursors)
+ tx.send(res.map_err(Into::into)).ok();
+ StudioRecordingActorState::Paused {
+ next_index: index + 1,
+ cursors,
+ next_cursor_id,
}
-
- break match msg {
- StudioRecordingActorControlMessage::Pause(tx) => {
- let (res, cursors, next_cursor_id) = match shutdown(
- pipeline,
- &mut actor,
- segment_start_time,
- )
- .await
- {
- Ok((cursors, next_cursor_id)) => {
- (Ok(()), cursors, next_cursor_id)
- }
- Err(e) => (Err(e), Default::default(), 0),
- };
-
- tx.send(res.map_err(Into::into)).ok();
- StudioRecordingActorState::Paused {
- next_index: index + 1,
- cursors,
- next_cursor_id,
- }
- }
- StudioRecordingActorControlMessage::Stop(tx) => {
- let res =
- shutdown(pipeline, &mut actor, segment_start_time)
- .await;
- let res = match res {
- Ok((cursors, _)) => {
- stop_recording(actor, cursors).await
- }
- Err(e) => Err(e),
- };
-
- tx.send(res).ok();
-
- break 'outer;
- }
- _ => continue,
- };
}
- }
- StudioRecordingActorState::Paused {
- next_index,
- cursors,
- next_cursor_id,
- } => {
- info!("recording actor paused");
- loop {
- let Ok(msg) = ctrl_rx.recv_async().await else {
- break 'outer;
+ StudioRecordingActorControlMessage::Stop(tx) => {
+ let res =
+ shutdown(pipeline, &mut actor, segment_start_time).await;
+ let res = match res {
+ Ok((cursors, _)) => stop_recording(actor, cursors).await,
+ Err(e) => Err(e),
};
- break match msg {
- StudioRecordingActorControlMessage::Stop(tx) => {
- tx.send(stop_recording(actor, cursors).await).ok();
- break 'outer;
- }
- StudioRecordingActorControlMessage::Resume(tx) => {
- let (state, res) = match create_segment_pipeline(
- &segments_dir,
- &cursors_dir,
- next_index,
- screen_source.clone(),
- camera_feed.as_deref(),
- audio_input_feed.as_ref(),
- cursors,
- next_cursor_id,
- )
- .await
- {
- Ok((pipeline, pipeline_done_rx)) => (
- StudioRecordingActorState::Recording {
- pipeline,
- pipeline_done_rx,
- index: next_index,
- segment_start_time: current_time_f64(),
- },
- Ok(()),
- ),
- Err(e) => (
- StudioRecordingActorState::Stopped,
- Err(e.into()),
- ),
- };
-
- tx.send(res).ok();
-
- state
+ tx.send(res).ok();
+
+ break 'outer;
+ }
+ _ => continue,
+ };
+ }
+ }
+ StudioRecordingActorState::Paused {
+ next_index,
+ cursors,
+ next_cursor_id,
+ } => {
+ info!("recording actor paused");
+ loop {
+ let Ok(msg) = ctrl_rx.recv_async().await else {
+ break 'outer;
+ };
+
+ break match msg {
+ StudioRecordingActorControlMessage::Stop(tx) => {
+ tx.send(stop_recording(actor, cursors).await).ok();
+ break 'outer;
+ }
+ StudioRecordingActorControlMessage::Resume(tx) => {
+ let (state, res) = match create_segment_pipeline(
+ &segments_dir,
+ &cursors_dir,
+ next_index,
+ screen_source.clone(),
+ camera_feed.as_deref(),
+ audio_input_feed.as_ref(),
+ cursors,
+ next_cursor_id,
+ )
+ .await
+ {
+ Ok((pipeline, pipeline_done_rx)) => (
+ StudioRecordingActorState::Recording {
+ pipeline,
+ pipeline_done_rx,
+ index: next_index,
+ segment_start_time: current_time_f64(),
+ },
+ Ok(()),
+ ),
+ Err(e) => {
+ (StudioRecordingActorState::Stopped, Err(e.into()))
}
- _ => continue,
};
+
+ tx.send(res).ok();
+
+ state
}
- }
- StudioRecordingActorState::Stopped => {
- info!("recording actor paused");
- break;
- }
- };
+ _ => continue,
+ };
+ }
}
+ StudioRecordingActorState::Stopped => {
+ info!("recording actor paused");
+ break;
+ }
+ };
+ }
- info!("recording actor finished");
-
- done_tx.send(()).ok();
- }
- .in_current_span()
- });
+ info!("recording actor finished");
- Ok(StudioRecordingHandle {
- ctrl_tx,
- options,
- bounds,
- })
- };
-
- match run().await {
- Ok(a) => Ok(a),
- Err(e) => {
- error!("Failed to start recording actor: {}", e);
- Err(e)
- }
+ done_tx.send(()).ok();
}
- }
- .instrument(tracing::info_span!("recording"))
- .with_subscriber(collector)
- .await
- .map(|a| (a, done_rx))
+ .in_current_span()
+ });
+
+ Ok((
+ StudioRecordingHandle {
+ ctrl_tx,
+ options,
+ bounds,
+ },
+ done_rx,
+ ))
}
pub struct CompletedStudioRecording {
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index 55fe56adb..de3d38694 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -1,4 +1,4 @@
-use std::future::Future;
+use std::{future::Future, path::PathBuf};
use tracing::Instrument;
@@ -42,3 +42,8 @@ where
use tracing::instrument::WithSubscriber;
tokio::spawn(future.with_current_subscriber().in_current_span())
}
+
+pub fn ensure_dir(path: &PathBuf) -> Result<PathBuf, std::io::Error> {
+ std::fs::create_dir_all(&path)?;
+ Ok(path.clone())
+}
diff --git a/package.json b/package.json
index 8ef2aff9c..9e84ea62f 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,7 @@
"docker:up": "turbo run docker:up",
"docker:stop": "turbo run docker:stop",
"docker:clean": "turbo run docker:clean",
- "cap-setup": "node --env-file .env scripts/setup.js"
+ "cap-setup": "dotenv -e .env -- node scripts/setup.js"
},
"devDependencies": {
"@turbo/gen": "^1.9.7",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e4b831df9..b39837767 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -6,7 +6,7 @@ settings:
patchedDependencies:
'@kobalte/[email protected]':
- hash: kzigaefucz2gzue42hjqb5kxba
+ hash: daf56e70aa12211e66d61eca48f0538cc1963c967982714f3abc09110083cf0d
path: patches/@[email protected]
importers:
@@ -60,7 +60,7 @@ importers:
version: 0.0.14
'@kobalte/core':
specifier: ^0.13.7
- version: 0.13.7(patch_hash=kzigaefucz2gzue42hjqb5kxba)([email protected])
+ version: 0.13.7(patch_hash=daf56e70aa12211e66d61eca48f0538cc1963c967982714f3abc09110083cf0d)([email protected])
'@solid-primitives/bounds':
specifier: ^0.0.122
version: 0.0.122([email protected])
@@ -373,7 +373,7 @@ importers:
version: 8.57.1
eslint-config-airbnb-typescript:
specifier: ^18.0.0
eslint-import-resolver-typescript:
specifier: ^3.6.1
@@ -446,6 +446,9 @@ importers:
'@headlessui/react':
specifier: ^1.7.17
+ '@hono/zod-validator':
+ specifier: ^0.4.3
'@hookform/resolvers':
specifier: ^3.3.2
@@ -524,6 +527,9 @@ importers:
hls.js:
specifier: ^1.5.3
version: 1.5.15
+ hono:
+ specifier: ^4.7.1
+ version: 4.7.1
jszip:
specifier: ^3.10.1
version: 3.10.1
@@ -901,7 +907,7 @@ importers:
dependencies:
'@kobalte/core':
specifier: ^0.13.7
- version: 0.13.7(patch_hash=kzigaefucz2gzue42hjqb5kxba)([email protected])
+ version: 0.13.7(patch_hash=daf56e70aa12211e66d61eca48f0538cc1963c967982714f3abc09110083cf0d)([email protected])
cva:
specifier: npm:class-variance-authority@^0.7.0
@@ -2623,6 +2629,12 @@ packages:
hono: '>=3.9.0'
zod: ^3.19.1
+ resolution: {integrity: sha512-xIgMYXDyJ4Hj6ekm9T9Y27s080Nl9NXHcJkOvkXPhubOLj8hZkOL8pDnnXfvCf5xEE8Q4oMFenQUZZREUY2gqQ==}
+ peerDependencies:
+ hono: '>=3.9.0'
+ zod: ^3.19.1
+
'@hookform/[email protected]':
resolution: {integrity: sha512-bU0Gr4EepJ/EQsH/IwEzYLsT/PEj5C0ynLQ4m+GSHS+xKH4TfSelhluTgOaoc4kA5s7eCsQbM4wvZLzELmWzUg==}
peerDependencies:
@@ -13597,6 +13609,11 @@ snapshots:
hono: 4.7.1
zod: 3.24.1
+ dependencies:
+ hono: 4.7.1
+ zod: 3.24.1
+
dependencies:
react-hook-form: 7.53.0([email protected])
@@ -13960,7 +13977,7 @@ snapshots:
dependencies:
tslib: 2.8.1
- '@kobalte/[email protected](patch_hash=kzigaefucz2gzue42hjqb5kxba)([email protected])':
+ '@kobalte/[email protected](patch_hash=daf56e70aa12211e66d61eca48f0538cc1963c967982714f3abc09110083cf0d)([email protected])':
dependencies:
'@floating-ui/dom': 1.6.12
'@internationalized/date': 3.5.6
@@ -18669,7 +18686,7 @@ snapshots:
optionalDependencies:
source-map: 0.6.1
dependencies:
confusing-browser-globals: 1.0.11
eslint: 8.57.1
@@ -18678,12 +18695,12 @@ snapshots:
object.entries: 1.1.8
semver: 6.3.1
dependencies:
'@typescript-eslint/eslint-plugin': 7.18.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.18.0([email protected])([email protected])
eslint: 8.57.1
+ eslint-config-airbnb-base: 15.0.0([email protected])([email protected])
transitivePeerDependencies:
- eslint-plugin-import
@@ -18748,7 +18765,7 @@ snapshots:
debug: 4.3.7([email protected])
enhanced-resolve: 5.17.1
eslint: 8.57.1
fast-glob: 3.3.2
get-tsconfig: 4.8.1
is-bun-module: 1.2.1
@@ -18767,7 +18784,7 @@ snapshots:
debug: 4.3.7([email protected])
enhanced-resolve: 5.17.1
eslint: 8.57.1
fast-glob: 3.3.2
get-tsconfig: 4.8.1
is-bun-module: 1.2.1
@@ -18786,7 +18803,7 @@ snapshots:
debug: 4.3.7([email protected])
enhanced-resolve: 5.17.1
eslint: 8.57.1
fast-glob: 3.3.2
get-tsconfig: 4.8.1
is-bun-module: 1.2.1
@@ -18799,18 +18816,7 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
- dependencies:
- debug: 3.2.7
- optionalDependencies:
- '@typescript-eslint/parser': 5.62.0([email protected])([email protected])
- eslint: 8.57.1
- eslint-import-resolver-node: 0.3.9
- transitivePeerDependencies:
- - supports-color
-
dependencies:
debug: 3.2.7
optionalDependencies:
@@ -18821,7 +18827,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
@@ -18843,7 +18849,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -18871,7 +18877,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3