Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Remove todo!() in pause/resume and fix timing on macos (#1153)

Brendan Allanf1e9fa550299
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index aedb3f164..bff295fd2 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -85,20 +85,18 @@ impl InProgressRecording {
}
}
- pub async fn pause(&self) -> Result<(), RecordingError> {
- todo!()
- // match self {
- // Self::Instant { handle, .. } => handle.pause().await,
- // Self::Studio { handle, .. } => handle.pause().await,
- // }
+ pub async fn pause(&self) -> anyhow::Result<()> {
+ match self {
+ Self::Instant { handle, .. } => handle.pause().await,
+ Self::Studio { handle, .. } => handle.pause().await,
+ }
}
- pub async fn resume(&self) -> Result<(), String> {
- todo!()
- // match self {
- // Self::Instant { handle, .. } => handle.resume().await.map_err(|e| e.to_string()),
- // Self::Studio { handle, .. } => handle.resume().await.map_err(|e| e.to_string()),
- // }
+ pub async fn resume(&self) -> anyhow::Result<()> {
+ match self {
+ Self::Instant { handle, .. } => handle.resume().await,
+ Self::Studio { handle, .. } => handle.resume().await,
+ }
}
pub fn recording_dir(&self) -> &PathBuf {
@@ -140,12 +138,11 @@ impl InProgressRecording {
}
}
- pub async fn cancel(self) -> Result<(), RecordingError> {
- todo!()
- // match self {
- // Self::Instant { handle, .. } => handle.cancel().await,
- // Self::Studio { handle, .. } => handle.cancel().await,
- // }
+ pub async fn cancel(self) -> anyhow::Result<()> {
+ match self {
+ Self::Instant { handle, .. } => handle.cancel().await,
+ Self::Studio { handle, .. } => handle.cancel().await,
+ }
}
pub fn mode(&self) -> RecordingMode {
@@ -673,7 +670,7 @@ pub async fn restart_recording(app: AppHandle, state: MutableState<'_, App>) ->
let inputs = recording.inputs().clone();
- // let _ = recording.cancel().await;
+ let _ = recording.cancel().await;
tokio::time::sleep(Duration::from_millis(1000)).await;
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
index 684f339ef..3a9580287 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
@@ -492,7 +492,9 @@ const NavItem = ({
{name}
</p>
{extraText && !sidebarCollapsed && (
- <p className="ml-auto text-xs text-gray-11">{extraText}</p>
+ <p className="ml-auto text-xs font-medium text-gray-11">
+ {extraText}
+ </p>
)}
</Link>
</Tooltip>
diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx
index 4d613cfa6..10869c80a 100644
--- a/apps/web/app/(org)/dashboard/caps/Caps.tsx
+++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx
@@ -232,7 +232,6 @@ export const Caps = ({
data.error === 1 ? "" : "s"
}`;
}
- router.refresh();
return `Successfully deleted ${data.success} cap${
data.success === 1 ? "" : "s"
}`;
@@ -267,7 +266,7 @@ export const Caps = ({
[data, isUploading, uploadingCapId],
);
- if (count === 0 && folders.length === 0) return <EmptyCapState />;
+ if (count === 0) return <EmptyCapState />;
return (
<div className="flex relative flex-col w-full h-full">
diff --git a/apps/web/app/(org)/dashboard/caps/components/Folder.tsx b/apps/web/app/(org)/dashboard/caps/components/Folder.tsx
index 53778178a..51b2b846d 100644
--- a/apps/web/app/(org)/dashboard/caps/components/Folder.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/Folder.tsx
@@ -273,11 +273,9 @@ const FolderCard = ({
<Link
prefetch={false}
href={
- deleteFolder.isPending
- ? "#"
- : spaceId
- ? `/dashboard/spaces/${spaceId}/folder/${id}`
- : `/dashboard/folder/${id}`
+ spaceId
+ ? `/dashboard/spaces/${spaceId}/folder/${id}`
+ : `/dashboard/folder/${id}`
}
>
<div
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 84279a1c8..1401f11b8 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -3,14 +3,13 @@
import type { userSelectProps } from "@cap/database/auth/session";
import type { videos } from "@cap/database/schema";
import { buildEnv, NODE_ENV } from "@cap/env";
-import { Avatar, Button } from "@cap/ui";
+import { Button } from "@cap/ui";
import { userIsPro } from "@cap/utils";
import { faChevronDown, faLock } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { Check, Copy, Globe2 } from "lucide-react";
import moment from "moment";
-import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
@@ -30,10 +29,7 @@ export const ShareHeader = ({
sharedSpaces = [],
spacesData = null,
}: {
- data: typeof videos.$inferSelect & {
- organizationIconUrl?: string | null;
- organizationName?: string | null;
- };
+ data: typeof videos.$inferSelect;
user: typeof userSelectProps | null;
customDomain?: string | null;
domainVerified?: boolean;
@@ -74,11 +70,9 @@ export const ShareHeader = ({
const handleBlur = async () => {
setIsEditing(false);
- const next = title.trim();
- if (next === "" || next === data.name) return;
+
try {
- await editTitle(data.id, next);
- setTitle(next);
+ await editTitle(data.id, title);
toast.success("Video title updated");
refresh();
} catch (error) {
@@ -87,7 +81,6 @@ export const ShareHeader = ({
} else {
toast.error("Failed to update title - please try again.");
}
- setTitle(data.name);
}
};
@@ -143,7 +136,7 @@ export const ShareHeader = ({
const renderSharedStatus = () => {
const baseClassName =
- "text-sm text-gray-10 justify-center lg:justify-start transition-colors duration-200 flex items-center";
+ "text-sm text-gray-10 transition-colors duration-200 flex items-center";
if (isOwner) {
const hasSpaceSharing =
@@ -205,29 +198,9 @@ export const ShareHeader = ({
/>
<div className="mt-8">
<div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between lg:gap-0">
- <div className="justify-center items-center mb-3 w-full md:flex lg:justify-between md:space-x-6 md:mb-0">
- <div className="flex flex-col gap-5 md:gap-10 lg:flex-row">
- <div className="flex flex-col flex-1 justify-center items-center w-full lg:justify-evenly">
- {data.organizationIconUrl ? (
- <Image
- className="rounded-full size-9"
- src={data.organizationIconUrl}
- alt="Organization icon"
- width={36}
- height={36}
- />
- ) : (
- <Avatar
- className="rounded-full size-9"
- name={data.organizationName ?? "Organization"}
- letterClass="text-sm"
- />
- )}
- <p className="text-sm font-medium text-gray-12">
- {data.organizationName}
- </p>
- </div>
- <div className="flex flex-col justify-center text-center lg:text-left lg:justify-start">
+ <div className="items-center md:flex md:justify-between md:space-x-6">
+ <div className="mb-3 md:mb-0">
+ <div className="flex items-center space-x-3 lg:min-w-[400px]">
{isEditing ? (
<input
value={title}
@@ -235,7 +208,7 @@ export const ShareHeader = ({
onBlur={handleBlur}
onKeyDown={handleKeyDown}
autoFocus
- className="w-full text-xl sm:text-2xl"
+ className="w-full text-xl font-semibold sm:text-2xl"
/>
) : (
<h1
@@ -249,16 +222,16 @@ export const ShareHeader = ({
{title}
</h1>
)}
- {user && renderSharedStatus()}
- <p className="mt-1 text-sm text-gray-10">
- {moment(data.createdAt).fromNow()}
- </p>
</div>
+ {user && renderSharedStatus()}
+ <p className="mt-1 text-sm text-gray-10">
+ {moment(data.createdAt).fromNow()}
+ </p>
</div>
</div>
{user !== null && (
- <div className="flex justify-center space-x-2 w-full lg:justify-end">
- <div className="w-fit">
+ <div className="flex space-x-2">
+ <div>
<div className="flex gap-2 items-center">
{data.password && (
<FontAwesomeIcon
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 4f0bea3d3..94a44f097 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -111,8 +111,6 @@ type VideoWithOrganization = typeof videos.$inferSelect & {
hasPassword?: boolean;
ownerIsPro?: boolean;
orgSettings?: OrganizationSettings | null;
- organizationIconUrl?: string | null;
- organizationName?: string | null;
};
const ALLOWED_REFERRERS = [
@@ -295,8 +293,6 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
duration: videos.duration,
fps: videos.fps,
hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean),
- organizationIconUrl: organizations.iconUrl,
- organizationName: organizations.name,
sharedOrganization: {
organizationId: sharedVideos.organizationId,
},
@@ -369,8 +365,6 @@ async function AuthorizedContent({
ownerIsPro?: boolean;
orgSettings?: OrganizationSettings | null;
videoSettings?: OrganizationSettings | null;
- organizationIconUrl?: string | null;
- organizationName?: string | null;
};
searchParams: { [key: string]: string | string[] | undefined };
}) {
@@ -493,8 +487,6 @@ async function AuthorizedContent({
sharedOrganization: {
organizationId: sharedVideos.organizationId,
},
- organizationIconUrl: organizations.iconUrl,
- organizationName: organizations.name,
orgSettings: organizations.settings,
videoSettings: videos.settings,
})
@@ -696,8 +688,6 @@ async function AuthorizedContent({
folderId: null,
orgSettings: video.orgSettings || null,
settings: video.videoSettings || null,
- organizationIconUrl: video.organizationIconUrl ?? undefined,
- organizationName: video.organizationName ?? undefined,
};
return (
diff --git a/apps/web/components/forms/NewOrganization.tsx b/apps/web/components/forms/NewOrganization.tsx
index 25d3af0e6..d48641afe 100644
--- a/apps/web/components/forms/NewOrganization.tsx
+++ b/apps/web/components/forms/NewOrganization.tsx
@@ -25,7 +25,7 @@ export interface NewOrganizationProps {
export const NewOrganization: React.FC<NewOrganizationProps> = (props) => {
const formSchema = z.object({
- name: z.string().min(1).max(25),
+ name: z.string().min(1),
});
const form = useForm<z.infer<typeof formSchema>>({
@@ -77,7 +77,6 @@ export const NewOrganization: React.FC<NewOrganizationProps> = (props) => {
render={({ field }) => (
<FormControl>
<Input
- maxLength={25}
placeholder="Your organization name"
{...field}
onChange={(e) => {
diff --git a/crates/enc-avfoundation/src/mp4.rs b/crates/enc-avfoundation/src/mp4.rs
index eb2f3f178..388b00254 100644
--- a/crates/enc-avfoundation/src/mp4.rs
+++ b/crates/enc-avfoundation/src/mp4.rs
@@ -1,22 +1,27 @@
use cap_media_info::{AudioInfo, VideoInfo};
use cidre::{cm::SampleTimingInfo, objc::Obj, *};
use ffmpeg::frame;
-use std::{path::PathBuf, time::Duration};
+use std::{ops::Sub, path::PathBuf, time::Duration};
use tracing::{debug, info};
+// before pausing at all, subtract 0.
+// on pause, record last frame time.
+// on resume, store last frame time and clear offset timestamp
+// on next frame, set offset timestamp and subtract (offset timestamp - last frame time - previous offset)
+// on next pause, store (offset timestamp - last frame time) into previous offset
+
pub struct MP4Encoder {
#[allow(unused)]
config: VideoInfo,
asset_writer: arc::R<av::AssetWriter>,
video_input: arc::R<av::AssetWriterInput>,
audio_input: Option<arc::R<av::AssetWriterInput>>,
- start_time: cm::Time,
- first_timestamp: Option<cm::Time>,
- segment_first_timestamp: Option<cm::Time>,
- last_pts: Option<cm::Time>,
+ most_recent_timestamp: Option<Duration>,
+ pause_timestamp: Option<Duration>,
+ timestamp_offset: Duration,
is_writing: bool,
is_paused: bool,
- elapsed_duration: cm::Time,
+ // elapsed_duration: cm::Time,
video_frames_appended: usize,
audio_frames_appended: usize,
}
@@ -175,13 +180,11 @@ impl MP4Encoder {
audio_input,
asset_writer,
video_input,
- first_timestamp: None,
- segment_first_timestamp: None,
- last_pts: None,
+ most_recent_timestamp: None,
+ pause_timestamp: None,
+ timestamp_offset: Duration::ZERO,
is_writing: false,
is_paused: false,
- start_time: cm::Time::zero(),
- elapsed_duration: cm::Time::zero(),
video_frames_appended: 0,
audio_frames_appended: 0,
})
@@ -198,20 +201,24 @@ impl MP4Encoder {
return Ok(());
};
- let time = cm::Time::new(timestamp.as_millis() as i64, 1_000);
-
- let new_pts = self
- .elapsed_duration
- .add(time.sub(self.segment_first_timestamp.unwrap_or(time)));
-
if !self.is_writing {
self.is_writing = true;
- self.asset_writer.start_session_at_src_time(new_pts);
- self.start_time = time;
+ self.asset_writer
+ .start_session_at_src_time(cm::Time::new(timestamp.as_millis() as i64, 1_000));
+ }
+
+ self.most_recent_timestamp = Some(timestamp);
+
+ if let Some(pause_timestamp) = self.pause_timestamp {
+ self.timestamp_offset += timestamp - pause_timestamp;
+ self.pause_timestamp = None;
}
let mut timing = frame.timing_info(0).unwrap();
- timing.pts = new_pts;
+ timing.pts = cm::Time::new(
+ timestamp.sub(self.timestamp_offset).as_millis() as i64,
+ 1_000,
+ );
let frame = frame.copy_with_new_timing(&[timing]).unwrap();
self.video_input
@@ -219,10 +226,6 @@ impl MP4Encoder {
.map_err(|e| QueueVideoFrameError::AppendError(e.retained()))
.and_then(|v| v.then_some(()).ok_or(QueueVideoFrameError::Failed))?;
- self.first_timestamp.get_or_insert(time);
- self.segment_first_timestamp.get_or_insert(time);
- self.last_pts = Some(new_pts);
-
self.video_frames_appended += 1;
Ok(())
@@ -247,11 +250,6 @@ impl MP4Encoder {
return Ok(());
}
- let time = cm::Time::new(
- (timestamp.as_secs_f64() * frame.rate() as f64) as i64,
- frame.rate() as i32,
- );
-
let audio_desc = cat::audio::StreamBasicDesc::common_f32(
frame.rate() as f64,
frame.channels() as u32,
@@ -282,10 +280,10 @@ impl MP4Encoder {
let format_desc =
cm::AudioFormatDesc::with_asbd(&audio_desc).map_err(QueueAudioFrameError::Setup)?;
- let pts = self
- .start_time
- .add(self.elapsed_duration)
- .add(time.sub(self.segment_first_timestamp.unwrap()));
+ let pts = cm::Time::new(
+ (timestamp.sub(self.timestamp_offset).as_secs_f64() * frame.rate() as f64) as i64,
+ frame.rate() as i32,
+ );
let buffer = cm::SampleBuf::create(
Some(&block_buf),
@@ -312,18 +310,15 @@ impl MP4Encoder {
}
pub fn pause(&mut self) {
- if self.is_paused {
+ if self.is_paused || !self.is_writing {
return;
}
- let clock = cm::Clock::host_time_clock();
- let time = clock.time();
+ let Some(timestamp) = self.most_recent_timestamp else {
+ return;
+ };
- self.elapsed_duration = self
- .elapsed_duration
- .add(time.sub(self.segment_first_timestamp.unwrap()));
- self.segment_first_timestamp = None;
- self.last_pts = None;
+ self.pause_timestamp = Some(timestamp);
self.is_paused = true;
}
@@ -340,10 +335,16 @@ impl MP4Encoder {
return;
}
+ let Some(most_recent_timestamp) = self.most_recent_timestamp else {
+ return;
+ };
+
self.is_writing = false;
- self.asset_writer
- .end_session_at_src_time(self.last_pts.unwrap_or(cm::Time::zero()));
+ self.asset_writer.end_session_at_src_time(cm::Time::new(
+ most_recent_timestamp.sub(self.timestamp_offset).as_millis() as i64,
+ 1000,
+ ));
self.video_input.mark_as_finished();
if let Some(i) = self.audio_input.as_mut() {
i.mark_as_finished()
@@ -354,8 +355,8 @@ impl MP4Encoder {
debug!("Appended {} video frames", self.video_frames_appended);
debug!("Appended {} audio frames", self.audio_frames_appended);
- debug!("First video timestamp: {:?}", self.first_timestamp);
- debug!("Last video timestamp: {:?}", self.last_pts);
+ // debug!("First video timestamp: {:?}", self.first_timestamp);
+ // debug!("Last video timestamp: {:?}", self.last_pts);
info!("Finished writing");
}
diff --git a/crates/recording/examples/recording-cli.rs b/crates/recording/examples/recording-cli.rs
index 5564530db..3310e5e7b 100644
--- a/crates/recording/examples/recording-cli.rs
+++ b/crates/recording/examples/recording-cli.rs
@@ -63,7 +63,7 @@ pub async fn main() {
id: Display::primary().id(),
},
)
- .with_system_audio(true)
+ // .with_system_audio(true)
// .with_camera_feed(std::sync::Arc::new(
// camera_feed.ask(feeds::camera::Lock).await.unwrap(),
// ))
@@ -74,16 +74,15 @@ pub async fn main() {
.await
.unwrap();
- let _ = tokio::select!(
- _ = tokio::time::sleep(Duration::from_secs(5)) => {
- trace!("Sleep done");
- let _ = handle.stop().await;
- }
- res = handle.done_fut() => {
- debug!("{res:?}");
- }
- );
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ handle.pause().await.unwrap();
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ handle.resume().await.unwrap();
+
+ tokio::time::sleep(Duration::from_secs(3)).await;
+
+ handle.stop().await.unwrap();
info!("Recording finished");
std::mem::forget(dir);
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 028f1ece4..817fb123b 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -432,7 +432,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
})
.await;
- video_source.stop().await?;
+ video_source.stop().await.context("video_source_stop")?;
muxer.lock().await.stop();
diff --git a/crates/recording/src/sources/screen_capture/macos.rs b/crates/recording/src/sources/screen_capture/macos.rs
index 71b4e07e1..4ef009f18 100644
--- a/crates/recording/src/sources/screen_capture/macos.rs
+++ b/crates/recording/src/sources/screen_capture/macos.rs
@@ -6,7 +6,7 @@ use crate::{
SetupCtx,
},
};
-use anyhow::anyhow;
+use anyhow::{Context, anyhow};
use cidre::*;
use futures::{FutureExt, channel::mpsc, future::BoxFuture};
use std::sync::{
@@ -265,7 +265,7 @@ impl Capturer {
async fn stop(&mut self) -> anyhow::Result<()> {
if self.started.fetch_xor(true, atomic::Ordering::Relaxed) {
- self.capturer.stop().await?;
+ self.capturer.stop().await.context("capturer_stop")?;
}
Ok(())