Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: propagate confirmed muxer failure without losing capture ownership

Richie McIlroyd12196a3a574
diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs
index 939506091..d0e1f0f9b 100644
--- a/apps/desktop-gpui/src/recording.rs
+++ b/apps/desktop-gpui/src/recording.rs
@@ -18,7 +18,6 @@ use cap_recording::{
sources::screen_capture::ScreenCaptureTarget,
studio_recording,
};
-#[cfg(any(target_os = "linux", windows))]
use futures_util::FutureExt as _;
use kameo::{Actor, actor::ActorRef};
@@ -478,15 +477,24 @@ where
(true, result)
}
-#[cfg(any(windows, all(target_os = "linux", test)))]
+#[cfg(any(target_os = "macos", windows, test))]
async fn finish_after_capture_stop<T, F>(
- stop: impl Future<Output = anyhow::Result<T>>,
+ stop: impl Future<Output = (bool, anyhow::Result<T>)>,
finalize: impl FnOnce(T) -> F,
) -> (bool, anyhow::Result<PathBuf>)
where
F: Future<Output = anyhow::Result<PathBuf>>,
{
- match stop.await {
+ let (capture_stopped, result) = stop.await;
+ if !capture_stopped {
+ return (
+ false,
+ Err(result.err().unwrap_or_else(|| {
+ anyhow!("Studio capture cleanup is unconfirmed; local files preserved")
+ })),
+ );
+ }
+ match result {
Ok(completed) => {
let result = std::panic::AssertUnwindSafe(finalize(completed))
.catch_unwind()
@@ -498,7 +506,7 @@ where
});
(true, result)
}
- Err(error) => (false, Err(error)),
+ Err(error) => (true, Err(error)),
}
}
@@ -628,23 +636,30 @@ impl ActiveRecording {
}))
}
- #[cfg(windows)]
- pub fn clean_windows_studio_stop_handle(&self) -> Option<CaptureStopFuture> {
+ #[cfg(any(target_os = "macos", windows))]
+ pub fn clean_studio_stop_handle(&self) -> Option<CaptureStopFuture> {
let Handle::Studio(handle) = &self.handle else {
return None;
};
let handle = handle.clone();
Some(Box::pin(async move {
let capture_target = handle.capture_target.clone();
- finish_after_capture_stop(handle.stop(), |completed| {
- finalize_studio(completed, capture_target)
- })
+ finish_after_capture_stop(
+ async move {
+ let outcome = handle.stop_with_outcome().await;
+ (
+ outcome.capture_stopped,
+ outcome.result.map_err(anyhow::Error::msg),
+ )
+ },
+ |completed| finalize_studio(completed, capture_target),
+ )
.await
}))
}
- #[cfg(windows)]
- pub fn windows_studio_delete_handle(&self) -> Option<CaptureStopFuture> {
+ #[cfg(any(target_os = "macos", windows))]
+ pub fn studio_delete_handle(&self) -> Option<CaptureStopFuture> {
let Handle::Studio(handle) = &self.handle else {
return None;
};
@@ -663,7 +678,7 @@ impl ActiveRecording {
);
}
if let Err(error) = report.result {
- return (false, Err(anyhow!(error)));
+ return (true, Err(anyhow!(error)));
}
let output = directory.clone();
let result = tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&directory))
@@ -745,7 +760,15 @@ impl ActiveRecording {
{
Handle::Studio(handle) => {
let handle = handle.clone();
- Box::pin(async move { handle.stop().await.map(|_| ()) })
+ return Box::pin(async move {
+ let outcome = handle.stop_with_outcome().await;
+ (
+ outcome.capture_stopped,
+ outcome.result.map_err(anyhow::Error::msg).and_then(|_| {
+ Err(anyhow!("Recording pipeline failed; local files preserved"))
+ }),
+ )
+ });
}
Handle::Instant(handle) => {
let handle = handle.clone();
@@ -822,7 +845,7 @@ impl ActiveRecording {
let _operation = self.instant_operation.lock().await;
let result = match &self.handle {
Handle::Studio(handle) => {
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
{
let report = handle
.stop_with_intent(studio_recording::StudioStopIntent::Discard)
@@ -834,7 +857,7 @@ impl ActiveRecording {
}
report.result.map(|_| ()).map_err(anyhow::Error::msg)
}
- #[cfg(not(windows))]
+ #[cfg(not(any(target_os = "macos", windows)))]
handle.cancel().await
}
Handle::Instant(handle) => {
@@ -3088,14 +3111,14 @@ mod tests {
}
}
-#[cfg(all(test, target_os = "linux"))]
+#[cfg(test)]
mod capture_stop_contract_tests {
use super::*;
#[tokio::test]
async fn failed_capture_stop_retains_retry_and_never_runs_finalization() {
let (stopped, result) = finish_after_capture_stop(
- async { anyhow::bail!("cleanup unconfirmed") },
+ async { (false, Err(anyhow!("cleanup unconfirmed"))) },
|(): ()| async { panic!("Failed capture must not finalize") },
)
.await;
@@ -3110,7 +3133,7 @@ mod capture_stop_contract_tests {
#[tokio::test]
async fn failed_finalization_after_confirmed_capture_stop_is_safe_to_release() {
- let (stopped, result) = finish_after_capture_stop(async { Ok(()) }, |()| async {
+ let (stopped, result) = finish_after_capture_stop(async { (true, Ok(())) }, |()| async {
anyhow::bail!("remux failed")
})
.await;
@@ -3130,16 +3153,17 @@ mod capture_stop_contract_tests {
.await
.is_err()
);
- stop_tx.send(Ok(())).unwrap();
+ stop_tx.send((true, Ok(()))).unwrap();
let (stopped, result) = future.await;
assert!(stopped);
assert_eq!(result.unwrap(), PathBuf::from("saved-project"));
}
#[tokio::test]
async fn finalization_panic_preserves_the_successful_capture_stop_acknowledgement() {
- let (stopped, result) =
- finish_after_capture_stop(async { Ok(()) }, |()| async { panic!("post-stop failure") })
- .await;
+ let (stopped, result) = finish_after_capture_stop(async { (true, Ok(())) }, |()| async {
+ panic!("post-stop failure")
+ })
+ .await;
assert!(stopped);
assert!(
result
@@ -3148,6 +3172,27 @@ mod capture_stop_contract_tests {
.contains("after capture stopped")
);
}
+
+ #[tokio::test]
+ async fn confirmed_media_failure_releases_capture_without_finalizing() {
+ let (stopped, result) = finish_after_capture_stop(
+ async { (true, Err(anyhow!("encoder exited after truncated media"))) },
+ |(): ()| async { panic!("Failed media must not finalize") },
+ )
+ .await;
+ assert!(stopped);
+ assert!(result.unwrap_err().to_string().contains("truncated media"));
+ }
+
+ #[tokio::test]
+ async fn successful_media_without_capture_acknowledgement_cannot_finalize() {
+ let (stopped, result) = finish_after_capture_stop(async { (false, Ok(())) }, |()| async {
+ panic!("Unconfirmed capture must not finalize")
+ })
+ .await;
+ assert!(!stopped);
+ assert!(result.unwrap_err().to_string().contains("unconfirmed"));
+ }
}
#[cfg(all(test, target_os = "linux"))]
@@ -3562,7 +3607,7 @@ mod windows_studio_stop_tests {
async fn studio_stop_error_never_finalizes_or_acknowledges_cleanup() {
let called = std::sync::atomic::AtomicBool::new(false);
let (acknowledged, result) = finish_after_capture_stop(
- async { Err::<(), _>(anyhow!("encoder join timed out")) },
+ async { (false, Err::<(), _>(anyhow!("encoder join timed out"))) },
|_| async {
called.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(PathBuf::new())
@@ -3581,10 +3626,11 @@ mod windows_studio_stop_tests {
#[tokio::test]
async fn healthy_studio_stop_retains_existing_finalization() {
- let (acknowledged, result) = finish_after_capture_stop(async { Ok(()) }, |_| async {
- Ok(PathBuf::from("preserved.cap"))
- })
- .await;
+ let (acknowledged, result) =
+ finish_after_capture_stop(async { (true, Ok(())) }, |_| async {
+ Ok(PathBuf::from("preserved.cap"))
+ })
+ .await;
assert!(acknowledged);
assert_eq!(result.unwrap(), PathBuf::from("preserved.cap"));
}
diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs
index f4746dd24..4efc87d8c 100644
--- a/apps/desktop-gpui/src/session.rs
+++ b/apps/desktop-gpui/src/session.rs
@@ -852,9 +852,11 @@ impl RecordingSession {
#[cfg(windows)]
let retained_stop = recording_failed
.then(|| active.failed_stop_handle())
- .or_else(|| active.clean_windows_studio_stop_handle());
+ .or_else(|| active.clean_studio_stop_handle());
#[cfg(target_os = "macos")]
- let retained_stop = recording_failed.then(|| active.failed_stop_handle());
+ let retained_stop = recording_failed
+ .then(|| active.failed_stop_handle())
+ .or_else(|| active.clean_studio_stop_handle());
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
let retained_stop: Option<recording::CaptureStopFuture> = None;
let retains_active = retained_stop.is_some();
@@ -901,6 +903,11 @@ impl RecordingSession {
tracing::error!(%error, "Capture cleanup is unconfirmed; retaining Stop control");
this.phase = phase_before_stop;
this.stopped_elapsed = None;
+ if matches!(this.phase, Phase::Recording { .. })
+ && let Some(active) = &this.active
+ {
+ this.monitor_storage(active.project_dir.clone(), cx);
+ }
#[cfg(windows)]
let message = if this.mode() == Some(recording::RecordingMode::Studio) {
format!("{error}. Studio shutdown remains unconfirmed; recording and files retained.")
@@ -1225,9 +1232,9 @@ impl RecordingSession {
self.discard_instant(None, cx);
return;
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
if self.mode() == Some(recording::RecordingMode::Studio) {
- self.discard_windows_studio(None, cx);
+ self.discard_studio_after_stop(None, cx);
return;
}
self.storage_monitor = None;
@@ -1284,9 +1291,9 @@ impl RecordingSession {
self.discard_instant(Some(config), cx);
return;
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
if self.mode() == Some(recording::RecordingMode::Studio) {
- self.discard_windows_studio(Some(config), cx);
+ self.discard_studio_after_stop(Some(config), cx);
return;
}
#[cfg(target_os = "linux")]
@@ -1369,12 +1376,12 @@ impl RecordingSession {
.detach();
}
- #[cfg(windows)]
- fn discard_windows_studio(&mut self, restart: Option<StartConfig>, cx: &mut Context<Self>) {
+ #[cfg(any(target_os = "macos", windows))]
+ fn discard_studio_after_stop(&mut self, restart: Option<StartConfig>, cx: &mut Context<Self>) {
let Some(active) = self.active.as_ref() else {
return;
};
- let Some(future) = active.windows_studio_delete_handle() else {
+ let Some(future) = active.studio_delete_handle() else {
return;
};
let directory = active.project_dir.clone();
@@ -1404,8 +1411,19 @@ impl RecordingSession {
this.start(config, cx);
}
}
+ Ok((true, Err(error))) => {
+ this.active = None;
+ this.finish(cx);
+ this.error = Some(format!(
+ "{error:#}; discard/restart stopped, local recording retained"
+ ));
+ cx.notify();
+ }
result => {
this.phase = phase;
+ if matches!(this.phase, Phase::Recording { .. }) {
+ this.monitor_storage(directory.clone(), cx);
+ }
this.error = Some(match result {
Ok((_, Err(error))) => format!(
"{error:#}; discard/restart stopped, local recording retained"
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index da572f5af..ed1bbf960 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -2538,7 +2538,7 @@ async fn start_recording_prepared(
let app = app.clone();
let state_mtx = Arc::clone(&state_mtx);
let project_file_path = project_file_path.clone();
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
let instant_watch = inputs.mode == RecordingMode::Instant;
async move {
fail!("recording::wait_actor_done");
@@ -2565,7 +2565,7 @@ async fn start_recording_prepared(
return;
}
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
if !instant_watch {
let state = state_mtx.read().await;
if let Some(InProgressRecording::Studio { handle, common, .. }) =
@@ -2602,7 +2602,7 @@ async fn start_recording_prepared(
}
ActorDoneDisposition::UnexpectedStop { error }
| ActorDoneDisposition::Failed { error } => {
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
if !instant_watch {
let _ = control_studio_recording(
&app,
@@ -3257,7 +3257,7 @@ where
finish(report.result).await
}
-#[cfg(any(target_os = "linux", windows))]
+#[cfg(any(target_os = "linux", target_os = "macos", windows))]
#[derive(Clone, Copy, PartialEq, Eq)]
enum StudioTerminalAction {
Stop,
@@ -3362,10 +3362,10 @@ async fn control_studio_recording(
)
}
-#[cfg(windows)]
-async fn after_windows_studio_stop<T, F>(
+#[cfg(any(target_os = "macos", windows))]
+async fn after_studio_capture_stop<T, F>(
stop: impl std::future::Future<Output = studio_recording::WindowsStudioStopReport>,
- finish: impl FnOnce(studio_recording::CompletedRecording) -> F,
+ finish: impl FnOnce(Result<studio_recording::CompletedRecording, String>) -> F,
) -> Result<T, String>
where
F: std::future::Future<Output = Result<T, String>>,
@@ -3383,10 +3383,10 @@ where
.unwrap_or_else(|| "terminal acknowledgement missing".into())
));
}
- finish(report.result?).await
+ finish(report.result).await
}
-#[cfg(windows)]
+#[cfg(any(target_os = "macos", windows))]
async fn control_studio_recording(
app: &AppHandle,
state: &Arc<tokio::sync::RwLock<App>>,
@@ -3420,9 +3420,9 @@ async fn control_studio_recording(
};
let stopping = handle.clone();
let finishing = handle.clone();
- let result = after_windows_studio_stop(
+ let result = after_studio_capture_stop(
async move { stopping.stop_with_intent(intent).await },
- |recording| async move {
+ |result| async move {
let mut state = state.write().await;
let current = match state.current_recording() {
Some(InProgressRecording::Studio {
@@ -3439,29 +3439,50 @@ async fn control_studio_recording(
if !current {
return Err("Studio terminal completion is stale".into());
}
- if let Some(error) = failure {
- return Err(error);
+ let outcome = match (failure, result) {
+ (Some(failure), Err(error)) => Err(format!("{failure}; {error}")),
+ (Some(error), _) => Err(error),
+ (None, result) => result,
+ };
+ let mut error = outcome.as_ref().err().cloned();
+ if discard && error.is_none() {
+ error = remove_recording_dir(&directory).await.err();
}
- if discard {
- remove_recording_dir(&directory).await?;
+ #[cfg(target_os = "macos")]
+ if action == StudioTerminalAction::Restart && error.is_none() {
+ drop(state.clear_current_recording());
+ CurrentRecordingChanged.emit(app).ok();
+ return Ok(());
}
- let completed = if discard {
+ let completed = if let Some(error) = &error {
+ Err(error.clone())
+ } else if discard {
Err("Recording discarded after Studio stop acknowledgement".into())
} else {
- Ok(CompletedRecording::Studio {
+ outcome.map(|recording| CompletedRecording::Studio {
recording,
target_name,
capture_target,
})
};
- handle_recording_end_inner(
+ if let Some(error) = &error {
+ let _ = RecordingEvent::Failed {
+ error: error.clone(),
+ }
+ .emit(app);
+ }
+ let cleanup = handle_recording_end_inner(
app.clone(),
completed,
&mut state,
directory,
- action == StudioTerminalAction::Restart,
+ action == StudioTerminalAction::Restart && error.is_none(),
)
- .await
+ .await;
+ match error {
+ Some(error) => Err(error),
+ None => cleanup,
+ }
},
)
.await;
@@ -3495,7 +3516,7 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res
if crate::clean_capture::queue_stop(&app) {
return Ok(());
}
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
if let Some(result) =
control_studio_recording(&app, &state, None, StudioTerminalAction::Stop, None).await
{
@@ -3572,7 +3593,7 @@ pub async fn restart_recording(
}
return Box::pin(start_recording(app, state, inputs)).await;
}
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
{
let current = {
let state = state.read().await;
@@ -3608,7 +3629,7 @@ pub async fn restart_recording(
if let Some(generation) = generation {
crate::clean_capture::wait_restored(&app, generation).await?;
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
let _ = generation;
Ok(())
},
@@ -3716,7 +3737,7 @@ pub async fn restart_recording(
start_recording(app.clone(), state, inputs).await
}
-#[cfg(any(target_os = "linux", windows, test))]
+#[cfg(any(target_os = "linux", target_os = "macos", windows, test))]
async fn complete_studio_restart(
restart: impl std::future::Future<Output = Result<RecordingAction, String>> + Send + 'static,
) -> Result<RecordingAction, String> {
@@ -3725,7 +3746,7 @@ async fn complete_studio_restart(
.map_err(|error| format!("Recording restart task failed: {error}"))?
}
-#[cfg(any(target_os = "linux", windows, test))]
+#[cfg(any(target_os = "linux", target_os = "macos", windows, test))]
async fn restart_with_editor_target<C, R, S, F>(
target: &EditorRecordingTarget,
cleanup: C,
@@ -3762,7 +3783,7 @@ where
result
}
-#[cfg(any(target_os = "linux", windows, test))]
+#[cfg(any(target_os = "linux", target_os = "macos", windows, test))]
fn take_failed_restart_editor_target(
target: &EditorRecordingTarget,
expected: Option<&Path>,
@@ -3798,7 +3819,7 @@ pub async fn delete_recording(app: AppHandle, state: MutableState<'_, App>) -> R
if let Some(attempt) = linux_instant::current(&app) {
return linux_instant::control(app, attempt, true).await;
}
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
if let Some(result) =
control_studio_recording(&app, &state, None, StudioTerminalAction::Discard, None).await
{
@@ -4106,7 +4127,7 @@ async fn handle_recording_end_inner(
{
return Err("Studio capture cleanup is unconfirmed; active recording retained".into());
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
if let Some(InProgressRecording::Studio {
handle: studio,
common,
@@ -8098,15 +8119,15 @@ mod studio_joined_completion_tests {
}
}
-#[cfg(all(test, windows))]
-mod windows_studio_control_tests {
+#[cfg(all(test, any(target_os = "macos", windows)))]
+mod studio_capture_control_tests {
use super::*;
#[tokio::test]
async fn studio_unconfirmed_or_losing_stop_cannot_restore_or_delete() {
for (accepted_intent, stop_acknowledged) in [(true, false), (false, true), (false, false)] {
let effects = std::sync::atomic::AtomicUsize::new(0);
- let result = after_windows_studio_stop(
+ let result = after_studio_capture_stop(
async {
studio_recording::WindowsStudioStopReport {
accepted_intent,
@@ -8124,4 +8145,53 @@ mod windows_studio_control_tests {
assert_eq!(effects.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+
+ #[tokio::test]
+ async fn acknowledged_media_failure_reaches_cleanup_with_its_error() {
+ let effects = std::sync::atomic::AtomicUsize::new(0);
+ let result = after_studio_capture_stop(
+ async {
+ studio_recording::WindowsStudioStopReport {
+ accepted_intent: true,
+ stop_acknowledged: true,
+ result: Err("encoder exited before completing media".into()),
+ }
+ },
+ |result| async {
+ effects.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ result.map(|_| ())
+ },
+ )
+ .await;
+ assert_eq!(effects.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(
+ result.unwrap_err(),
+ "encoder exited before completing media"
+ );
+ }
+
+ #[tokio::test]
+ async fn pending_stop_does_not_enter_cleanup() {
+ let effects = std::sync::atomic::AtomicUsize::new(0);
+ let (send, receive) = tokio::sync::oneshot::channel();
+ let stop = after_studio_capture_stop(async { receive.await.unwrap() }, |result| async {
+ effects.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ result.map(|_| ())
+ });
+ tokio::pin!(stop);
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), &mut stop)
+ .await
+ .is_err()
+ );
+ assert_eq!(effects.load(std::sync::atomic::Ordering::SeqCst), 0);
+ send.send(studio_recording::WindowsStudioStopReport {
+ accepted_intent: true,
+ stop_acknowledged: true,
+ result: Err("media finalization failed".into()),
+ })
+ .unwrap_or_else(|_| panic!("Stop receiver closed before acknowledgement"));
+ assert!(stop.await.is_err());
+ assert_eq!(effects.load(std::sync::atomic::Ordering::SeqCst), 1);
+ }
}
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index a9ac1ac20..12431b6d7 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -310,6 +310,41 @@ pub(crate) enum BlockingThreadFinish {
TimedOut(anyhow::Error),
}
+#[derive(Debug, thiserror::Error)]
+#[error("out-of-process media finalization failed after the encoder joined: {source:#}")]
+pub(crate) struct OopMediaFailureAfterJoin {
+ #[source]
+ source: anyhow::Error,
+}
+
+impl OopMediaFailureAfterJoin {
+ #[cfg(any(test, target_os = "macos", windows))]
+ pub(crate) fn new(source: anyhow::Error) -> Self {
+ Self { source }
+ }
+}
+
+#[cfg(any(test, target_os = "macos", windows))]
+pub(crate) fn resolve_oop_thread_finish(
+ thread_result: BlockingThreadFinish,
+) -> anyhow::Result<anyhow::Result<()>> {
+ match thread_result {
+ BlockingThreadFinish::Clean => Ok(Ok(())),
+ BlockingThreadFinish::Failed(error)
+ if error.chain().any(|cause| {
+ cause
+ .downcast_ref::<super::oop_muxer::MuxerSubprocessFinishError>()
+ .is_some_and(super::oop_muxer::MuxerSubprocessFinishError::child_reaped)
+ }) =>
+ {
+ Ok(Err(anyhow::Error::new(OopMediaFailureAfterJoin::new(
+ error,
+ ))))
+ }
+ BlockingThreadFinish::Failed(error) | BlockingThreadFinish::TimedOut(error) => Err(error),
+ }
+}
+
#[cfg(any(test, target_os = "macos", windows))]
fn join_blocking_thread(
handle: std::thread::JoinHandle<anyhow::Result<()>>,
@@ -317,7 +352,10 @@ fn join_blocking_thread(
) -> anyhow::Result<()> {
match handle.join() {
Ok(Ok(())) => Ok(()),
- Ok(Err(error)) => Err(anyhow!("{label} returned error: {error:#}")),
+ Ok(Err(error)) => {
+ let message = format!("{label} returned error: {error:#}");
+ Err(error.context(message))
+ }
Err(panic_payload) => Err(anyhow!("{label} panicked during finish: {panic_payload:?}")),
}
}
@@ -2620,7 +2658,10 @@ fn resolve_pipeline_completion(
(Err(error), _) | (_, Err(error)) => Err(error),
(_, Ok(Ok(()))) if stop_signal.user_stopped() => Ok(()),
(_, Ok(Ok(()))) => Ok(()),
- (_, Ok(Err(error))) => Err(anyhow!("Muxer finish failed: {error:#}")),
+ (_, Ok(Err(error))) => {
+ let message = format!("Muxer finish failed: {error:#}");
+ Err(error.context(message))
+ }
}
}
@@ -3889,6 +3930,11 @@ pub struct FinishedOutputPipeline {
pub audio_gap_summary: Option<AudioGapSummary>,
}
+pub(crate) struct OutputPipelineStopOutcome {
+ pub(crate) finished: FinishedOutputPipeline,
+ pub(crate) media_error: Option<anyhow::Error>,
+}
+
#[derive(Clone, Default)]
pub struct PipelineStopSignal {
user_stopped: Arc<AtomicBool>,
@@ -3944,19 +3990,35 @@ impl OutputPipeline {
&self.path
}
- pub async fn stop(mut self) -> anyhow::Result<FinishedOutputPipeline> {
+ pub async fn stop(self) -> anyhow::Result<FinishedOutputPipeline> {
+ let outcome = self.stop_with_outcome().await?;
+ match outcome.media_error {
+ Some(error) => Err(error),
+ None => Ok(outcome.finished),
+ }
+ }
+
+ pub(crate) async fn stop_with_outcome(mut self) -> anyhow::Result<OutputPipelineStopOutcome> {
drop(self.stop_token.take());
- if self.joined_stop {
+ let media_error = if self.joined_stop {
match self.done_fut.clone().await {
- Err(error) if error.is_caused_by::<PipelineStoppedByUser>() => {}
- result => result?,
+ Err(error) if error.is_caused_by::<PipelineStoppedByUser>() => None,
+ Err(error) if error.is_caused_by::<OopMediaFailureAfterJoin>() => {
+ Some(anyhow::Error::new(error))
+ }
+ Err(error) => return Err(error.into()),
+ Ok(()) => None,
}
} else {
const PIPELINE_STOP_TIMEOUT: Duration = Duration::from_secs(10);
match tokio::time::timeout(PIPELINE_STOP_TIMEOUT, self.done_fut.clone()).await {
- Ok(Err(error)) if error.is_caused_by::<PipelineStoppedByUser>() => {}
- Ok(res) => res?,
+ Ok(Err(error)) if error.is_caused_by::<PipelineStoppedByUser>() => None,
+ Ok(Err(error)) if error.is_caused_by::<OopMediaFailureAfterJoin>() => {
+ Some(anyhow::Error::new(error))
+ }
+ Ok(Err(error)) => return Err(error.into()),
+ Ok(Ok(())) => None,
Err(_) => {
return Err(anyhow!(
"Pipeline stop timed out after {}s — tasks may still be running",
@@ -3964,7 +4026,7 @@ impl OutputPipeline {
));
}
}
- }
+ };
let first_timestamp = match tokio::time::timeout(
Duration::from_secs(1),
@@ -3985,13 +4047,16 @@ impl OutputPipeline {
}
};
- Ok(FinishedOutputPipeline {
- path: self.path,
- first_timestamp,
- video_info: self.video_info,
- video_frame_count: self.video_frame_count.load(Ordering::Acquire),
- video_timestamp_span: self.video_timestamp_span.get(),
- audio_gap_summary: self.audio_gap_summary.get().copied(),
+ Ok(OutputPipelineStopOutcome {
+ finished: FinishedOutputPipeline {
+ path: self.path,
+ first_timestamp,
+ video_info: self.video_info,
+ video_frame_count: self.video_frame_count.load(Ordering::Acquire),
+ video_timestamp_span: self.video_timestamp_span.get(),
+ audio_gap_summary: self.audio_gap_summary.get().copied(),
+ },
+ media_error,
})
}
@@ -6808,6 +6873,51 @@ mod tests {
}
}
+ #[test]
+ fn reaped_subprocess_failure_is_media_error_only_after_thread_join() {
+ let handle = std::thread::spawn(|| {
+ Err(anyhow::Error::new(
+ crate::output_pipeline::oop_muxer::MuxerSubprocessFinishError::Reaped(
+ crate::output_pipeline::oop_muxer::MuxerSubprocessError::Crashed(
+ "test subprocess exit".into(),
+ ),
+ ),
+ ))
+ });
+ let thread_result =
+ wait_for_blocking_thread_finish(handle, Duration::from_millis(100), "test-worker");
+ let media_error = resolve_oop_thread_finish(thread_result)
+ .expect("joined worker failure should use the media result")
+ .expect_err("reaped subprocess failure should remain visible");
+
+ assert!(
+ media_error
+ .chain()
+ .any(|cause| cause.downcast_ref::<OopMediaFailureAfterJoin>().is_some())
+ );
+ }
+
+ #[test]
+ fn unconfirmed_subprocess_failure_is_not_joined_media_error() {
+ let handle = std::thread::spawn(|| {
+ Err(anyhow::Error::new(
+ crate::output_pipeline::oop_muxer::MuxerSubprocessFinishError::Unconfirmed(
+ anyhow!("wait failed"),
+ ),
+ ))
+ });
+ let thread_result =
+ wait_for_blocking_thread_finish(handle, Duration::from_millis(100), "test-worker");
+ let error = resolve_oop_thread_finish(thread_result)
+ .expect_err("unconfirmed subprocess must use the outer error");
+
+ assert!(
+ !error
+ .chain()
+ .any(|cause| cause.downcast_ref::<OopMediaFailureAfterJoin>().is_some())
+ );
+ }
+
#[test]
fn returns_timeout_when_thread_does_not_exit_in_time() {
// The worker blocks until released, so it can never beat the
diff --git a/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs b/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs
index f20061843..9afbb6434 100644
--- a/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs
+++ b/crates/recording/src/output_pipeline/oop_fragmented_m4s.rs
@@ -1,6 +1,6 @@
use super::core::{
BlockingThreadFinish, DiskSpaceMonitor, HealthSender, PipelineHealthEvent, SharedHealthSender,
- frame_timing_log_threshold_ms, wait_for_blocking_thread_finish,
+ frame_timing_log_threshold_ms, resolve_oop_thread_finish, wait_for_blocking_thread_finish,
};
use super::macos_frame_convert::{
FramePool, ffmpeg_pixel_format_for_cap, fill_frame_from_sample_buf,
@@ -219,12 +219,10 @@ impl Muxer for OutOfProcessFragmentedM4SMuxer {
}
fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- if let Some(state) = self.state.take()
- && let Err(error) = finish_oop_encoder(state, timestamp)
- {
- return Ok(Err(error));
+ match self.state.take() {
+ Some(state) => finish_oop_encoder(state, timestamp),
+ None => Ok(Ok(())),
}
- Ok(Ok(()))
}
fn set_health_sender(&mut self, tx: HealthSender) {
@@ -233,7 +231,10 @@ impl Muxer for OutOfProcessFragmentedM4SMuxer {
}
}
-fn finish_oop_encoder(mut state: EncoderState, _timestamp: Duration) -> anyhow::Result<()> {
+fn finish_oop_encoder(
+ mut state: EncoderState,
+ _timestamp: Duration,
+) -> anyhow::Result<anyhow::Result<()>> {
if let Err(error) = state.video_tx.send(None) {
trace!("OOP encoder channel already closed during finish: {error}");
}
@@ -246,11 +247,7 @@ fn finish_oop_encoder(mut state: EncoderState, _timestamp: Duration) -> anyhow::
})
.unwrap_or(BlockingThreadFinish::Clean);
- match thread_result {
- BlockingThreadFinish::Clean => Ok(()),
- BlockingThreadFinish::Failed(error) => Err(error),
- BlockingThreadFinish::TimedOut(error) => Err(error),
- }
+ resolve_oop_thread_finish(thread_result)
}
impl OutOfProcessFragmentedM4SMuxer {
@@ -542,17 +539,19 @@ impl OutOfProcessFragmentedM4SMuxer {
}
}
- let subprocess_report = match subprocess.finish() {
- Ok(report) => Some(report),
- Err(e) => {
- warn!("OOP subprocess finish error: {e:#}");
- None
- }
- };
+ let subprocess_result = subprocess.finish();
tracker.flush_pending_segments();
tracker.finalize(final_ts);
+ let subprocess_report = match subprocess_result {
+ Ok(report) => Some(report),
+ Err(error) => {
+ warn!("OOP subprocess finish error: {error:#}");
+ return Err(error.into());
+ }
+ };
+
if total_frames > 0 {
debug!(
total_frames = total_frames,
diff --git a/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs b/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
index 50c5eaa44..4c67f24eb 100644
--- a/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
+++ b/crates/recording/src/output_pipeline/oop_fragmented_m4s_win.rs
@@ -1,6 +1,6 @@
use super::core::{
BlockingThreadFinish, DiskSpaceMonitor, HealthSender, PipelineHealthEvent, SharedHealthSender,
- wait_for_blocking_thread_finish,
+ resolve_oop_thread_finish, wait_for_blocking_thread_finish,
};
use super::oop_muxer::{
MuxerSubprocessConfig, MuxerSubprocessError, RespawningMuxerSubprocess, VideoStreamInit,
@@ -211,12 +211,10 @@ impl Muxer for WindowsOOPFragmentedM4SMuxer {
}
fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {
- if let Some(state) = self.state.take()
- && let Err(error) = finish_oop_encoder(state, timestamp)
- {
- return Ok(Err(error));
+ match self.state.take() {
+ Some(state) => finish_oop_encoder(state, timestamp),
+ None => Ok(Ok(())),
}
- Ok(Ok(()))
}
fn set_health_sender(&mut self, tx: HealthSender) {
@@ -225,7 +223,10 @@ impl Muxer for WindowsOOPFragmentedM4SMuxer {
}
}
-fn finish_oop_encoder(mut state: EncoderState, _timestamp: Duration) -> anyhow::Result<()> {
+fn finish_oop_encoder(
+ mut state: EncoderState,
+ _timestamp: Duration,
+) -> anyhow::Result<anyhow::Result<()>> {
if let Err(error) = state.video_tx.send(None) {
trace!("Windows OOP encoder channel already closed during finish: {error}");
}
@@ -238,11 +239,7 @@ fn finish_oop_encoder(mut state: EncoderState, _timestamp: Duration) -> anyhow::
})
.unwrap_or(BlockingThreadFinish::Clean);
- match thread_result {
- BlockingThreadFinish::Clean => Ok(()),
- BlockingThreadFinish::Failed(error) => Err(error),
- BlockingThreadFinish::TimedOut(error) => Err(error),
- }
+ resolve_oop_thread_finish(thread_result)
}
impl WindowsOOPFragmentedM4SMuxer {
@@ -579,17 +576,19 @@ impl WindowsOOPFragmentedM4SMuxer {
warn!("Windows OOP encoder flush error: {e:?}");
}
- let subprocess_report = match subprocess.finish() {
- Ok(report) => Some(report),
- Err(e) => {
- warn!("Windows OOP subprocess finish error: {e:#}");
- None
- }
- };
+ let subprocess_result = subprocess.finish();
tracker.flush_pending_segments();
tracker.finalize(final_ts);
+ let subprocess_report = match subprocess_result {
+ Ok(report) => Some(report),
+ Err(error) => {
+ warn!("Windows OOP subprocess finish error: {error:#}");
+ return Err(error.into());
+ }
+ };
+
if total_frames > 0 {
debug!(
total_frames = total_frames,
diff --git a/crates/recording/src/output_pipeline/oop_muxer.rs b/crates/recording/src/output_pipeline/oop_muxer.rs
index 9a5675afd..a047101d1 100644
--- a/crates/recording/src/output_pipeline/oop_muxer.rs
+++ b/crates/recording/src/output_pipeline/oop_muxer.rs
@@ -166,6 +166,20 @@ pub enum MuxerSubprocessError {
DiskFull(String),
}
+#[derive(Debug, thiserror::Error)]
+pub enum MuxerSubprocessFinishError {
+ #[error("subprocess was reaped with unusable output: {0}")]
+ Reaped(#[source] MuxerSubprocessError),
+ #[error("subprocess exit is unconfirmed: {0:#}")]
+ Unconfirmed(#[source] anyhow::Error),
+}
+
+impl MuxerSubprocessFinishError {
+ pub fn child_reaped(&self) -> bool {
+ matches!(self, Self::Reaped(_))
+ }
+}
+
impl MuxerSubprocess {
pub fn spawn(
bin_path: PathBuf,
@@ -478,7 +492,7 @@ impl MuxerSubprocess {
Ok(())
}
- pub fn finish(mut self) -> Result<MuxerSubprocessReport, MuxerSubprocessError> {
+ pub fn finish(mut self) -> Result<MuxerSubprocessReport, MuxerSubprocessFinishError> {
if let Some(mut stdin) = self.stdin.take() {
let _ = write_frame(&mut stdin, &Frame::Finish);
let _ = stdin.flush();
@@ -486,15 +500,26 @@ impl MuxerSubprocess {
}
let packets = self.packets_written.load(Ordering::Acquire);
- let mut status = None;
- if let Some(mut child) = self.child.take() {
- match child.wait() {
- Ok(s) => status = Some(s),
- Err(e) => {
- warn!("cap-muxer wait failed: {e}");
+ let status = match self.child.as_mut() {
+ Some(child) => match child.wait() {
+ Ok(status) => {
+ drop(self.child.take());
+ status
+ }
+ Err(error) => {
+ let stderr_tail = self.snapshot_stderr();
+ return Err(MuxerSubprocessFinishError::Unconfirmed(anyhow!(
+ "cap-muxer wait failed: {error}; stderr tail: {:?}",
+ stderr_tail.iter().rev().take(3).collect::<Vec<_>>()
+ )));
}
+ },
+ None => {
+ return Err(MuxerSubprocessFinishError::Unconfirmed(anyhow!(
+ "cap-muxer child missing during finish"
+ )));
}
- }
+ };
let stderr_tail = if let Some(handle) = self.stderr_thread.take() {
handle.join().unwrap_or_default()
@@ -502,7 +527,7 @@ impl MuxerSubprocess {
self.snapshot_stderr()
};
- let exit_code = status.as_ref().and_then(|s| s.code());
+ let exit_code = status.code();
let success = matches!(exit_code, Some(0));
if !success {
let reason = format!(
@@ -516,11 +541,12 @@ impl MuxerSubprocess {
} else {
self.report_crashed(&reason);
}
- return Err(if is_disk_full {
+ let error = if is_disk_full {
MuxerSubprocessError::DiskFull(reason)
} else {
MuxerSubprocessError::Crashed(reason)
- });
+ };
+ return Err(MuxerSubprocessFinishError::Reaped(error));
}
info!(
@@ -540,12 +566,20 @@ impl MuxerSubprocess {
impl Drop for MuxerSubprocess {
fn drop(&mut self) {
- if let Some(mut child) = self.child.take()
- && let Ok(None) = child.try_wait()
- {
- warn!("cap-muxer subprocess being dropped while still running; killing");
- let _ = child.kill();
- let _ = child.wait();
+ if let Some(mut child) = self.child.take() {
+ match child.try_wait() {
+ Ok(Some(_)) => {}
+ Ok(None) => {
+ warn!("cap-muxer subprocess being dropped while still running; killing");
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ Err(error) => {
+ warn!(%error, "cap-muxer subprocess status is unknown during drop; killing");
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
}
}
}
@@ -747,13 +781,13 @@ impl RespawningMuxerSubprocess {
Ok(())
}
- pub fn finish(mut self) -> Result<MuxerSubprocessReport, MuxerSubprocessError> {
+ pub fn finish(mut self) -> Result<MuxerSubprocessReport, MuxerSubprocessFinishError> {
if let Some(current) = self.current.take() {
current.finish()
} else {
- Err(MuxerSubprocessError::Crashed(
- "no active subprocess at finish".to_string(),
- ))
+ Err(MuxerSubprocessFinishError::Unconfirmed(anyhow!(
+ "no active subprocess at finish"
+ )))
}
}
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 9e658240f..2cb5bd5dd 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -49,6 +49,8 @@ use tracing::{Instrument, debug, error_span, info, trace, warn};
const COMPATIBILITY_CAMERA_ACTIVE_MAX_SCREEN_WIDTH: u32 = 1600;
const COMPATIBILITY_CAMERA_ACTIVE_MAX_SCREEN_HEIGHT: u32 = 1000;
+const UNCONFIRMED_CAPTURE_CLEANUP: &str =
+ "Studio capture cleanup is unconfirmed; local recording preserved";
fn camera_active_max_capture_size(
quality: crate::StudioQuality,
@@ -83,6 +85,35 @@ enum ActorState {
},
}
+#[derive(Clone)]
+struct TerminalStopFailure {
+ capture_stopped: bool,
+ error: String,
+}
+
+#[derive(Debug, thiserror::Error)]
+#[error("Studio capture stopped with unusable media: {source:#}")]
+struct StudioCaptureStoppedError {
+ #[source]
+ source: anyhow::Error,
+}
+
+impl StudioCaptureStoppedError {
+ fn new(source: anyhow::Error) -> Self {
+ Self { source }
+ }
+}
+
+fn studio_capture_stopped(error: &anyhow::Error) -> bool {
+ error
+ .chain()
+ .any(|cause| cause.downcast_ref::<StudioCaptureStoppedError>().is_some())
+}
+
+fn minimum_segment_stop_deadline(discard: bool, segment_start: Instant) -> Option<Instant> {
+ (!discard).then(|| segment_start + Duration::from_secs(1))
+}
+
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StudioQuiescence {
@@ -91,7 +122,7 @@ pub enum StudioQuiescence {
Unconfirmed,
}
-#[cfg(any(target_os = "linux", windows))]
+#[cfg(any(target_os = "linux", target_os = "macos", windows))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StudioStopIntent {
Preserve,
@@ -222,7 +253,13 @@ impl Drop for StudioLifetimeOwner {
}
}
-#[cfg(windows)]
+#[derive(Clone)]
+pub struct StudioStopOutcome {
+ pub capture_stopped: bool,
+ pub result: Result<CompletedRecording, String>,
+}
+
+#[cfg(any(target_os = "macos", windows))]
#[derive(Clone)]
pub struct WindowsStudioStopReport {
pub accepted_intent: bool,
@@ -230,7 +267,7 @@ pub struct WindowsStudioStopReport {
pub result: Result<CompletedRecording, String>,
}
-#[cfg(windows)]
+#[cfg(any(target_os = "macos", windows))]
#[derive(Default)]
struct WindowsStudioTerminal {
result: tokio::sync::Mutex<Option<(StudioStopIntent, WindowsStudioStopReport)>>,
@@ -242,9 +279,9 @@ struct WindowsStudioTerminal {
pub struct ActorHandle {
#[cfg(target_os = "linux")]
lifecycle: StudioLifecycle,
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
recording_dir: PathBuf,
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
terminal: Arc<WindowsStudioTerminal>,
actor_ref: kameo::actor::ActorRef<Actor>,
pub capture_target: screen_capture::ScreenCaptureTarget,
@@ -258,6 +295,8 @@ pub struct Actor {
lifetime: StudioLifetimeOwner,
recording_dir: PathBuf,
state: Option<ActorState>,
+ all_tracks_stopped: bool,
+ terminal_stop_failure: Option<TerminalStopFailure>,
#[cfg(windows)]
cancel_error: Option<String>,
segment_factory: SegmentPipelineFactory,
@@ -317,7 +356,11 @@ impl Actor {
let stopped = pipeline.stop().await;
#[cfg(windows)]
let stopped = stopped.map_err(|error| self.preserve_windows_stop_failure(error));
- let mut pipeline = stopped?;
+ let PipelineStopOutcome {
+ mut pipeline,
+ media_error,
+ all_tracks_stopped,
+ } = stopped?;
tracing::info!("pipeline shutdown");
@@ -332,7 +375,13 @@ impl Actor {
"Cursor shutdown acknowledgement failed: {_error}"
)));
#[cfg(not(windows))]
- None
+ if media_error.is_some() {
+ return Err(anyhow!(
+ "Cursor shutdown acknowledgement failed after media finalization error: {_error}"
+ ));
+ } else {
+ None
+ }
}
}
} else {
@@ -374,6 +423,15 @@ impl Actor {
camera_device_id,
mic_device_id,
});
+ self.all_tracks_stopped &= all_tracks_stopped;
+
+ if let Some(error) = media_error {
+ if self.all_tracks_stopped {
+ return Err(anyhow::Error::new(StudioCaptureStoppedError::new(error)));
+ }
+ let message = format!("{UNCONFIRMED_CAPTURE_CLEANUP}: {error:#}");
+ return Err(error.context(message));
+ }
Ok(cursors)
}
@@ -390,30 +448,62 @@ impl Actor {
#[cfg(windows)]
fn preserve_windows_stop_failure(&mut self, error: anyhow::Error) -> anyhow::Error {
+ self.preserve_failure_evidence(error)
+ }
+
+ fn preserve_failure_evidence(&mut self, error: anyhow::Error) -> anyhow::Error {
let error = match persist_failed_recording(&self.recording_dir, &format!("{error:#}")) {
Ok(()) => error,
Err(persist) => error.context(format!(
"Could not persist failed Studio metadata: {persist:#}"
)),
};
+ #[cfg(windows)]
self.cancel_error
.get_or_insert_with(|| format!("{error:#}"));
error
}
+ fn preserve_terminal_stop_failure(
+ &mut self,
+ error: anyhow::Error,
+ capture_stopped: bool,
+ ) -> anyhow::Error {
+ let error = self.preserve_failure_evidence(error);
+ self.terminal_stop_failure = Some(TerminalStopFailure {
+ capture_stopped,
+ error: format!("{error:#}"),
+ });
+ error
+ }
+
fn notify_completion_ok(&self) {
if self.completion_tx.borrow().is_none() {
let _ = self.completion_tx.send(Some(Ok(())));
}
}
-}
-impl Message<Stop> for Actor {
- type Reply = anyhow::Result<CompletedRecording>;
-
- async fn handle(&mut self, _: Stop, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {
+ async fn handle_stop(
+ &mut self,
+ discard: bool,
+ ctx: &mut Context<Self, anyhow::Result<CompletedRecording>>,
+ ) -> anyhow::Result<CompletedRecording> {
#[cfg(target_os = "linux")]
self.cancel_resume().await?;
+ if let Some(failure) = self.terminal_stop_failure.as_ref() {
+ let error = anyhow!(failure.error.clone());
+ if failure.capture_stopped && self.all_tracks_stopped {
+ let error = anyhow::Error::new(StudioCaptureStoppedError::new(error));
+ let error = match ctx.actor_ref().stop_gracefully().await {
+ Ok(()) => error,
+ Err(stop_error) => error.context(format!(
+ "Studio actor stop acknowledgement failed: {stop_error}"
+ )),
+ };
+ return Err(error);
+ }
+ return Err(error);
+ }
let cursors = match self.state.take() {
Some(ActorState::Recording {
pipeline,
@@ -421,19 +511,40 @@ impl Message<Stop> for Actor {
segment_start_instant,
..
}) => {
- // Wait for minimum segment duration
- tokio::time::sleep_until((segment_start_instant + Duration::from_secs(1)).into())
- .await;
-
- let (cursors, _) = self.stop_pipeline(pipeline, segment_start_time).await?;
+ if let Some(deadline) =
+ minimum_segment_stop_deadline(discard, segment_start_instant)
+ {
+ tokio::time::sleep_until(deadline.into()).await;
+ }
- cursors
+ match self.stop_pipeline(pipeline, segment_start_time).await {
+ Ok((cursors, _)) => cursors,
+ Err(error) if studio_capture_stopped(&error) => {
+ let error = self.preserve_failure_evidence(error);
+ let error = match ctx.actor_ref().stop_gracefully().await {
+ Ok(()) => error,
+ Err(stop_error) => error.context(format!(
+ "Studio actor stop acknowledgement failed: {stop_error}"
+ )),
+ };
+ return Err(error);
+ }
+ Err(error) => return Err(error),
+ }
}
Some(ActorState::Paused { cursors, .. }) => cursors,
_ => return Err(anyhow!("Not recording")),
};
- ctx.actor_ref().stop_gracefully().await?;
+ if let Err(stop_error) = ctx.actor_ref().stop_gracefully().await {
+ let error = anyhow!("Studio actor stop acknowledgement failed: {stop_error}");
+ let error = if self.all_tracks_stopped {
+ anyhow::Error::new(StudioCaptureStoppedError::new(error))
+ } else {
+ error
+ };
+ return Err(self.preserve_failure_evidence(error));
+ }
#[cfg(target_os = "linux")]
let known_failure = {
@@ -446,6 +557,14 @@ impl Message<Stop> for Actor {
let known_failure = self.windows_failure();
#[cfg(not(any(target_os = "linux", windows)))]
let known_failure = None;
+ let known_failure = if self.all_tracks_stopped {
+ known_failure
+ } else {
+ Some(match known_failure {
+ Some(error) => format!("{UNCONFIRMED_CAPTURE_CLEANUP}: {error}"),
+ None => UNCONFIRMED_CAPTURE_CLEANUP.to_string(),
+ })
+ };
let recording = stop_recording(
self.recording_dir.clone(),
@@ -455,7 +574,22 @@ impl Message<Stop> for Actor {
self.display_notch,
known_failure,
)
- .await?;
+ .await;
+ let recording = match recording {
+ Ok(recording) => recording,
+ Err(error) => {
+ let error = if self.all_tracks_stopped {
+ anyhow::Error::new(StudioCaptureStoppedError::new(error))
+ } else {
+ error
+ };
+ return Err(self.preserve_failure_evidence(error));
+ }
+ };
+
+ if !self.all_tracks_stopped {
+ return Err(self.preserve_failure_evidence(anyhow!(UNCONFIRMED_CAPTURE_CLEANUP)));
+ }
self.notify_completion_ok();
@@ -463,6 +597,30 @@ impl Message<Stop> for Actor {
}
}
+impl Message<Stop> for Actor {
+ type Reply = anyhow::Result<CompletedRecording>;
+
+ async fn handle(&mut self, _: Stop, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {
+ self.handle_stop(false, ctx).await
+ }
+}
+
+struct StopWithIntent {
+ discard: bool,
+}
+
+impl Message<StopWithIntent> for Actor {
+ type Reply = anyhow::Result<CompletedRecording>;
+
+ async fn handle(
+ &mut self,
+ message: StopWithIntent,
+ ctx: &mut Context<Self, Self::Reply>,
+ ) -> Self::Reply {
+ self.handle_stop(message.discard, ctx).await
+ }
+}
+
struct Pause;
impl Message<Pause> for Actor {
@@ -471,26 +629,38 @@ impl Message<Pause> for Actor {
async fn handle(&mut self, _: Pause, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
#[cfg(target_os = "linux")]
self.cancel_resume().await?;
- self.state = match self.state.take() {
+ match self.state.take() {
Some(ActorState::Recording {
pipeline,
segment_start_time,
index,
..
}) => {
- let (cursors, next_cursor_id) = self
+ let stopped = self
.stop_pipeline(pipeline, segment_start_time)
.await
- .context("stop_pipeline")?;
-
- Some(ActorState::Paused {
- next_index: index + 1,
- cursors,
- next_cursor_id,
- })
+ .context("stop_pipeline");
+ match stopped {
+ Ok((cursors, next_cursor_id)) if self.all_tracks_stopped => {
+ self.state = Some(ActorState::Paused {
+ next_index: index + 1,
+ cursors,
+ next_cursor_id,
+ });
+ }
+ Ok(_) => {
+ let error = anyhow!(UNCONFIRMED_CAPTURE_CLEANUP);
+ return Err(self.preserve_terminal_stop_failure(error, false));
+ }
+ Err(error) => {
+ let capture_stopped = studio_capture_stopped(&error);
+ let error = self.preserve_terminal_stop_failure(error, capture_stopped);
+ return Err(error);
+ }
+ }
}
- state => state,
- };
+ state => self.state = state,
+ }
Ok(())
}
@@ -682,6 +852,9 @@ impl Message<Resume> for Actor {
type Reply = anyhow::Result<futures::future::BoxFuture<'static, anyhow::Result<()>>>;
async fn handle(&mut self, _: Resume, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {
+ if !self.all_tracks_stopped {
+ bail!(UNCONFIRMED_CAPTURE_CLEANUP);
+ }
if self
.completion_tx
.borrow()
@@ -789,6 +962,9 @@ impl Message<Resume> for Actor {
type Reply = anyhow::Result<()>;
async fn handle(&mut self, _: Resume, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
+ if !self.all_tracks_stopped {
+ bail!(UNCONFIRMED_CAPTURE_CLEANUP);
+ }
self.state = match self.state.take() {
Some(ActorState::Paused {
next_index,
@@ -827,18 +1003,40 @@ impl Message<Cancel> for Actor {
async fn handle(&mut self, _: Cancel, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
#[cfg(target_os = "linux")]
self.cancel_resume().await?;
+ if let Some(failure) = self.terminal_stop_failure.as_ref() {
+ bail!("Previous Studio stop failed: {}", failure.error);
+ }
#[cfg(windows)]
if let Some(error) = &self.cancel_error {
bail!("Previous capture cancellation failed: {error}");
}
if let Some(ActorState::Recording { pipeline, .. }) = self.state.take() {
- if let Err(e) = pipeline.stop().await {
- #[cfg(windows)]
- {
- return Err(self.preserve_windows_stop_failure(e));
+ let stopped = match pipeline.stop().await {
+ Ok(stopped) => stopped,
+ Err(error) => {
+ let error = error.context("Pipeline stop failed during Studio cancellation");
+ return Err(self.preserve_terminal_stop_failure(error, false));
}
- #[cfg(not(windows))]
- warn!("Pipeline stop error during cancel: {e:#}");
+ };
+ let PipelineStopOutcome {
+ mut media_error,
+ all_tracks_stopped,
+ ..
+ } = stopped;
+ self.all_tracks_stopped &= all_tracks_stopped;
+ if !self.all_tracks_stopped {
+ let error = match media_error.take() {
+ Some(error) => {
+ let message = format!("{UNCONFIRMED_CAPTURE_CLEANUP}: {error:#}");
+ error.context(message)
+ }
+ None => anyhow!(UNCONFIRMED_CAPTURE_CLEANUP),
+ };
+ return Err(self.preserve_terminal_stop_failure(error, false));
+ }
+ if let Some(error) = media_error {
+ let error = error.context("Studio cancellation found unusable media");
+ return Err(self.preserve_terminal_stop_failure(error, false));
}
#[cfg(windows)]
@@ -962,6 +1160,32 @@ struct FinishedPipeline {
pub track_failures: Vec<TrackFailureRecord>,
}
+struct PipelineStopOutcome {
+ pipeline: FinishedPipeline,
+ media_error: Option<anyhow::Error>,
+ all_tracks_stopped: bool,
+}
+
+fn classify_pipeline_stop_errors(
+ stop_errors: &[String],
+ media_errors: &[String],
+) -> anyhow::Result<Option<anyhow::Error>> {
+ if !media_errors.is_empty() && !stop_errors.is_empty() {
+ bail!(
+ "Studio media failed after one producer stopped, but other capture cleanup is unconfirmed: {}; media errors: {}",
+ stop_errors.join("; "),
+ media_errors.join("; ")
+ );
+ }
+
+ Ok((!media_errors.is_empty()).then(|| {
+ anyhow!(
+ "Studio media finalization failed after all capture producers stopped: {}",
+ media_errors.join("; ")
+ )
+ }))
+}
+
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
enum RecordingTrackKind {
@@ -1125,30 +1349,30 @@ impl Pipeline {
})
}
- pub async fn stop(mut self) -> anyhow::Result<FinishedPipeline> {
+ pub async fn stop(mut self) -> anyhow::Result<PipelineStopOutcome> {
#[cfg(any(target_os = "linux", windows))]
self.stopping
.store(true, std::sync::atomic::Ordering::Release);
#[cfg(target_os = "macos")]
let (screen, microphone, camera, system_audio) = {
let (microphone, camera, (screen, system_audio)) = futures::join!(
- OptionFuture::from(self.microphone.map(|s| s.stop())),
- OptionFuture::from(self.camera.map(|s| s.stop())),
+ OptionFuture::from(self.microphone.map(|s| s.stop_with_outcome())),
+ OptionFuture::from(self.camera.map(|s| s.stop_with_outcome())),
async {
// These sources share a capturer; only the first stop awaits its native acknowledgement.
let system_audio =
- OptionFuture::from(self.system_audio.map(|s| s.stop())).await;
- (self.screen.stop().await, system_audio)
+ OptionFuture::from(self.system_audio.map(|s| s.stop_with_outcome())).await;
+ (self.screen.stop_with_outcome().await, system_audio)
}
);
(screen, microphone, camera, system_audio)
};
#[cfg(not(target_os = "macos"))]
let (screen, microphone, camera, system_audio) = futures::join!(
- self.screen.stop(),
- OptionFuture::from(self.microphone.map(|s| s.stop())),
- OptionFuture::from(self.camera.map(|s| s.stop())),
- OptionFuture::from(self.system_audio.map(|s| s.stop()))
+ self.screen.stop_with_outcome(),
+ OptionFuture::from(self.microphone.map(|s| s.stop_with_outcome())),
+ OptionFuture::from(self.camera.map(|s| s.stop_with_outcome())),
+ OptionFuture::from(self.system_audio.map(|s| s.stop_with_outcome()))
);
if let Some(cursor) = self.cursor.as_mut() {
@@ -1159,62 +1383,110 @@ impl Pipeline {
&& let Err(error) = watcher_task.await
{
warn!(error = %error, "Studio recording watcher task ended unexpectedly");
- #[cfg(any(target_os = "linux", windows))]
return Err(anyhow!(
"Studio recording watcher acknowledgement failed: {error}"
));
}
- #[cfg(windows)]
- {
- let errors = [
- ("display", screen.as_ref().err()),
- (
- "microphone",
- microphone.as_ref().and_then(|result| result.as_ref().err()),
- ),
- (
- "camera",
- camera.as_ref().and_then(|result| result.as_ref().err()),
- ),
- (
- "system audio",
- system_audio
- .as_ref()
- .and_then(|result| result.as_ref().err()),
- ),
- ]
- .into_iter()
- .filter_map(|(track, error)| error.map(|error| format!("{track}: {error:#}")))
- .collect::<Vec<_>>();
- if !errors.is_empty() {
- bail!(
- "Requested Studio track stop failed; capture cleanup is unconfirmed: {}",
- errors.join("; ")
- );
- }
- }
+ let stop_errors = [
+ ("display", screen.as_ref().err()),
+ (
+ "microphone",
+ microphone.as_ref().and_then(|result| result.as_ref().err()),
+ ),
+ (
+ "camera",
+ camera.as_ref().and_then(|result| result.as_ref().err()),
+ ),
+ (
+ "system audio",
+ system_audio
+ .as_ref()
+ .and_then(|result| result.as_ref().err()),
+ ),
+ ]
+ .into_iter()
+ .filter_map(|(track, error)| error.map(|error| format!("{track}: {error:#}")))
+ .collect::<Vec<_>>();
- Ok(FinishedPipeline {
- start_time: self.start_time,
- screen: screen.context("display")?,
- microphone: finalize_optional_track(
- RecordingTrackKind::Microphone,
- microphone.transpose(),
- &self.track_failures,
+ let media_errors = [
+ (
+ "display",
+ screen
+ .as_ref()
+ .ok()
+ .and_then(|outcome| outcome.media_error.as_ref()),
),
- camera: finalize_optional_track(
- RecordingTrackKind::Camera,
- camera.transpose(),
- &self.track_failures,
+ (
+ "microphone",
+ microphone
+ .as_ref()
+ .and_then(|result| result.as_ref().ok())
+ .and_then(|outcome| outcome.media_error.as_ref()),
),
- system_audio: finalize_optional_track(
- RecordingTrackKind::SystemAudio,
- system_audio.transpose(),
- &self.track_failures,
+ (
+ "camera",
+ camera
+ .as_ref()
+ .and_then(|result| result.as_ref().ok())
+ .and_then(|outcome| outcome.media_error.as_ref()),
),
- cursor: self.cursor,
- track_failures: take_track_failures(&self.track_failures),
+ (
+ "system audio",
+ system_audio
+ .as_ref()
+ .and_then(|result| result.as_ref().ok())
+ .and_then(|outcome| outcome.media_error.as_ref()),
+ ),
+ ]
+ .into_iter()
+ .filter_map(|(track, error)| error.map(|error| format!("{track}: {error:#}")))
+ .collect::<Vec<_>>();
+
+ let media_error = classify_pipeline_stop_errors(&stop_errors, &media_errors)?;
+
+ #[cfg(windows)]
+ if !stop_errors.is_empty() {
+ bail!(
+ "Requested Studio track stop failed; capture cleanup is unconfirmed: {}",
+ stop_errors.join("; ")
+ );
+ }
+
+ let microphone = microphone
+ .transpose()
+ .map(|outcome| outcome.map(|outcome| outcome.finished));
+ let camera = camera
+ .transpose()
+ .map(|outcome| outcome.map(|outcome| outcome.finished));
+ let system_audio = system_audio
+ .transpose()
+ .map(|outcome| outcome.map(|outcome| outcome.finished));
+
+ Ok(PipelineStopOutcome {
+ pipeline: FinishedPipeline {
+ start_time: self.start_time,
+ screen: screen.context("display")?.finished,
+ microphone: finalize_optional_track(
+ RecordingTrackKind::Microphone,
+ microphone,
+ &self.track_failures,
+ ),
+ camera: finalize_optional_track(
+ RecordingTrackKind::Camera,
+ camera,
+ &self.track_failures,
+ ),
+ system_audio: finalize_optional_track(
+ RecordingTrackKind::SystemAudio,
+ system_audio,
+ &self.track_failures,
+ ),
+ cursor: self.cursor,
+ track_failures: take_track_failures(&self.track_failures),
+ },
+ media_error,
+ all_tracks_stopped: stop_errors.is_empty(),
})
}
@@ -1351,31 +1623,58 @@ struct CursorPipeline {
impl ActorHandle {
pub async fn stop(&self) -> anyhow::Result<CompletedRecording> {
+ self.stop_with_outcome()
+ .await
+ .result
+ .map_err(anyhow::Error::msg)
+ }
+
+ pub async fn stop_with_outcome(&self) -> StudioStopOutcome {
#[cfg(target_os = "linux")]
{
let report = self.stop_with_report().await;
- if !report.accepted_intent || report.quiescence != StudioQuiescence::Joined {
- bail!("Studio capture cleanup is unconfirmed; local recording preserved");
+ let capture_stopped =
+ report.accepted_intent && report.quiescence == StudioQuiescence::Joined;
+ let result = if capture_stopped {
+ report.result
+ } else {
+ Err(report.result.err().unwrap_or_else(|| {
+ "Studio capture cleanup is unconfirmed; local recording preserved".into()
+ }))
+ };
+ StudioStopOutcome {
+ capture_stopped,
+ result,
}
- report.result.map_err(anyhow::Error::msg)
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
{
let report = self.stop_with_intent(StudioStopIntent::Preserve).await;
- if !report.accepted_intent || !report.stop_acknowledged {
- bail!(
- "Studio stop is unconfirmed: {}",
- report
- .result
- .err()
- .unwrap_or_else(|| "terminal acknowledgement missing".into())
- );
+ let capture_stopped = report.accepted_intent && report.stop_acknowledged;
+ let result = if capture_stopped {
+ report.result
+ } else {
+ Err(report.result.err().unwrap_or_else(|| {
+ "Studio stop is unconfirmed; terminal acknowledgement missing".into()
+ }))
+ };
+ StudioStopOutcome {
+ capture_stopped,
+ result,
}
- report.result.map_err(anyhow::Error::msg)
}
- #[cfg(not(any(target_os = "linux", windows)))]
+ #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
- Ok(self.actor_ref.ask(Stop).await?)
+ let result = self.actor_ref.ask(Stop).await;
+ let capture_stopped = match &result {
+ Ok(_) => true,
+ Err(kameo::error::SendError::HandlerError(error)) => studio_capture_stopped(error),
+ Err(_) => false,
+ };
+ StudioStopOutcome {
+ capture_stopped,
+ result: result.map_err(|error| format!("{error:#}")),
+ }
}
}
@@ -1411,7 +1710,12 @@ impl ActorHandle {
.0
.terminal_started
.store(true, std::sync::atomic::Ordering::Release);
- let result = actor.ask(Stop).await.map_err(|error| format!("{error:#}"));
+ let result = actor
+ .ask(StopWithIntent {
+ discard: intent == StudioStopIntent::Discard,
+ })
+ .await
+ .map_err(|error| format!("{error:#}"));
if let Err(error) = &result {
lifecycle.fail(error.clone());
}
@@ -1448,26 +1752,26 @@ impl ActorHandle {
})
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
pub fn same_attempt(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.terminal, &other.terminal)
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
pub fn terminal_started(&self) -> bool {
self.terminal
.started
.load(std::sync::atomic::Ordering::Acquire)
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
pub fn stop_acknowledged(&self) -> bool {
self.terminal
.acknowledged
.load(std::sync::atomic::Ordering::Acquire)
}
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
pub async fn stop_with_intent(&self, intent: StudioStopIntent) -> WindowsStudioStopReport {
let terminal = self.terminal.clone();
let actor = self.actor_ref.clone();
@@ -1486,7 +1790,19 @@ impl ActorHandle {
terminal
.started
.store(true, std::sync::atomic::Ordering::Release);
- let result = actor.ask(Stop).await.map_err(|error| format!("{error:#}"));
+ let result = actor
+ .ask(StopWithIntent {
+ discard: intent == StudioStopIntent::Discard,
+ })
+ .await;
+ let stop_acknowledged = match &result {
+ Ok(_) => true,
+ Err(kameo::error::SendError::HandlerError(error)) => {
+ studio_capture_stopped(error)
+ }
+ Err(_) => false,
+ };
+ let result = result.map_err(|error| format!("{error:#}"));
let result = match result {
Err(error) => match persist_failed_recording(&recording_dir, &error) {
Ok(()) => Err(error),
@@ -1498,7 +1814,7 @@ impl ActorHandle {
};
let report = WindowsStudioStopReport {
accepted_intent: true,
- stop_acknowledged: result.is_ok(),
+ stop_acknowledged,
result,
};
terminal.acknowledged.store(
@@ -1523,7 +1839,7 @@ impl ActorHandle {
}
pub async fn pause(&self) -> anyhow::Result<()> {
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
if self.terminal_started() {
bail!("Studio terminal cleanup already owns this attempt");
}
@@ -1822,7 +2138,7 @@ async fn spawn_studio_recording_actor(
let base_inputs = base_inputs.clone();
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
let actor_recording_dir = recording_dir.clone();
let actor_ref = Actor::spawn(Actor {
#[cfg(target_os = "linux")]
@@ -1837,6 +2153,8 @@ async fn spawn_studio_recording_actor(
segment_start_time,
segment_start_instant: Instant::now(),
}),
+ all_tracks_stopped: true,
+ terminal_stop_failure: None,
segment_factory: segment_pipeline_factory,
#[cfg(target_os = "linux")]
resume_attempt: None,
@@ -1852,9 +2170,9 @@ async fn spawn_studio_recording_actor(
Ok(ActorHandle {
#[cfg(target_os = "linux")]
lifecycle,
- #[cfg(any(target_os = "linux", windows))]
+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]
recording_dir: actor_recording_dir,
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
terminal: Arc::new(WindowsStudioTerminal::default()),
actor_ref,
capture_target: base_inputs.capture_target,
@@ -2835,7 +3153,6 @@ fn current_time_f64() -> f64 {
.as_secs_f64()
}
-#[cfg(any(target_os = "linux", windows))]
fn persist_failed_recording(recording_dir: &Path, error: &str) -> anyhow::Result<()> {
let mut meta = RecordingMeta::load_for_project(recording_dir)
.map_err(|error| anyhow!("load failed Studio recording metadata: {error}"))?;
@@ -2905,6 +3222,236 @@ mod tests {
ChannelVideoSourceConfig, Muxer, SetupCtx, TaskPool, VideoFrame, VideoMuxer,
};
+ #[test]
+ fn media_failure_requires_every_producer_stop_to_be_confirmed() {
+ let error = classify_pipeline_stop_errors(
+ &["microphone: stop timed out".into()],
+ &["display: subprocess exited".into()],
+ )
+ .expect_err("one stopped producer cannot acknowledge the whole Studio pipeline");
+
+ assert!(error.to_string().contains("cleanup is unconfirmed"));
+ }
+
+ #[test]
+ fn media_failure_remains_visible_after_every_producer_stops() {
+ let error = classify_pipeline_stop_errors(&[], &["display: subprocess exited".into()])
+ .expect("confirmed producer stops should return the media result")
+ .expect("unusable media must remain an error");
+
+ assert!(error.to_string().contains("all capture producers stopped"));
+ }
+
+ #[test]
+ fn discard_skips_the_minimum_segment_deadline() {
+ let segment_start = Instant::now();
+
+ assert_eq!(minimum_segment_stop_deadline(true, segment_start), None);
+ assert_eq!(
+ minimum_segment_stop_deadline(false, segment_start),
+ Some(segment_start + Duration::from_secs(1))
+ );
+ }
+
+ #[cfg(any(target_os = "macos", windows))]
+ fn terminal_failure_handle(path: &Path) -> ActorHandle {
+ let (completion_tx, completion_rx) = watch::channel(None);
+ let target = screen_capture::ScreenCaptureTarget::CameraOnly;
+ let segment_factory = SegmentPipelineFactory::new(
+ path.join("content/segments"),
+ path.join("content/cursors"),
+ RecordingBaseInputs {
+ capture_target: target.clone(),
+ capture_system_audio: false,
+ mic_feed: None,
+ camera_feed: None,
+ #[cfg(target_os = "macos")]
+ shareable_content: None,
+ #[cfg(target_os = "macos")]
+ excluded_windows: Vec::new(),
+ },
+ false,
+ false,
+ false,
+ false,
+ 30,
+ crate::StudioQuality::Balanced,
+ completion_tx.clone(),
+ );
+ let mut actor = Actor {
+ recording_dir: path.to_path_buf(),
+ state: None,
+ all_tracks_stopped: true,
+ terminal_stop_failure: None,
+ #[cfg(windows)]
+ cancel_error: None,
+ segment_factory,
+ segments: Vec::new(),
+ completion_tx,
+ display_notch: None,
+ };
+ let error = anyhow::Error::new(StudioCaptureStoppedError::new(anyhow!(
+ "pause found unusable media"
+ )));
+ let error = actor.preserve_terminal_stop_failure(error, true);
+ assert!(studio_capture_stopped(&error));
+ let actor_ref = Actor::spawn(actor);
+ ActorHandle {
+ recording_dir: path.to_path_buf(),
+ terminal: Arc::new(WindowsStudioTerminal::default()),
+ actor_ref,
+ capture_target: target,
+ done_fut: completion_rx_to_done_fut(completion_rx),
+ }
+ }
+
+ #[cfg(any(target_os = "macos", windows))]
+ #[tokio::test]
+ async fn pause_media_failure_replays_as_acknowledged_terminal_error() {
+ let temp = tempfile::tempdir().unwrap();
+ std::fs::create_dir(temp.path().join("content")).unwrap();
+ write_in_progress_meta(temp.path()).unwrap();
+ std::fs::write(temp.path().join("content/partial.m4s"), b"partial").unwrap();
+ let handle = terminal_failure_handle(temp.path());
+ assert!(matches!(
+ RecordingMeta::load_for_project(temp.path())
+ .unwrap()
+ .studio_meta()
+ .unwrap()
+ .status(),
+ StudioRecordingStatus::Failed { .. }
+ ));
+
+ let report = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(report.accepted_intent);
+ assert!(report.stop_acknowledged);
+ let error = report
+ .result
+ .err()
+ .expect("media failure must remain visible");
+ assert!(handle.stop_acknowledged());
+ assert!(matches!(
+ RecordingMeta::load_for_project(temp.path())
+ .unwrap()
+ .studio_meta()
+ .unwrap()
+ .status(),
+ StudioRecordingStatus::Failed { .. }
+ ));
+ assert_eq!(
+ std::fs::read(temp.path().join("content/partial.m4s")).unwrap(),
+ b"partial"
+ );
+
+ let replay = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(replay.accepted_intent);
+ assert!(replay.stop_acknowledged);
+ assert_eq!(replay.result.err().expect("cached media failure"), error);
+ }
+
+ #[cfg(target_os = "macos")]
+ fn prior_unconfirmed_optional_stop_handle(path: &Path) -> ActorHandle {
+ let (completion_tx, completion_rx) = watch::channel(None);
+ let target = screen_capture::ScreenCaptureTarget::CameraOnly;
+ let segment_factory = SegmentPipelineFactory::new(
+ path.join("content/segments"),
+ path.join("content/cursors"),
+ RecordingBaseInputs {
+ capture_target: target.clone(),
+ capture_system_audio: false,
+ mic_feed: None,
+ camera_feed: None,
+ shareable_content: None,
+ excluded_windows: Vec::new(),
+ },
+ false,
+ false,
+ true,
+ false,
+ 30,
+ crate::StudioQuality::Balanced,
+ completion_tx.clone(),
+ );
+ let timestamps = Timestamps::now();
+ let actor_ref = Actor::spawn(Actor {
+ recording_dir: path.to_path_buf(),
+ state: Some(ActorState::Paused {
+ next_index: 1,
+ cursors: Default::default(),
+ next_cursor_id: 0,
+ }),
+ all_tracks_stopped: false,
+ terminal_stop_failure: None,
+ segment_factory,
+ segments: vec![RecordingSegment {
+ start: 0.0,
+ end: 1.0,
+ pipeline: FinishedPipeline {
+ start_time: timestamps,
+ screen: test_finished_output_pipeline_at(
+ path.join("content/partial.m4s"),
+ Timestamp::Instant(timestamps.instant()),
+ Some(test_video_info()),
+ 1,
+ ),
+ microphone: None,
+ camera: None,
+ system_audio: None,
+ cursor: None,
+ track_failures: vec![TrackFailureRecord {
+ track: RecordingTrackKind::Camera,
+ stage: TrackFailureStage::Stop,
+ error: "camera encoder join timed out".into(),
+ }],
+ },
+ camera_device_id: None,
+ mic_device_id: None,
+ }],
+ completion_tx,
+ display_notch: None,
+ });
+ ActorHandle {
+ recording_dir: path.to_path_buf(),
+ terminal: Arc::new(WindowsStudioTerminal::default()),
+ actor_ref,
+ capture_target: target,
+ done_fut: completion_rx_to_done_fut(completion_rx),
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ async fn prior_optional_join_timeout_cannot_ack_after_final_metadata() {
+ let temp = tempfile::tempdir().unwrap();
+ std::fs::create_dir(temp.path().join("content")).unwrap();
+ write_in_progress_meta(temp.path()).unwrap();
+ std::fs::write(temp.path().join("content/partial.m4s"), b"partial").unwrap();
+ let handle = prior_unconfirmed_optional_stop_handle(temp.path());
+
+ let report = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(report.accepted_intent);
+ assert!(!report.stop_acknowledged);
+ let error = report.result.err().expect("unconfirmed optional stop");
+ assert!(error.contains(UNCONFIRMED_CAPTURE_CLEANUP));
+ assert!(matches!(
+ RecordingMeta::load_for_project(temp.path())
+ .unwrap()
+ .studio_meta()
+ .unwrap()
+ .status(),
+ StudioRecordingStatus::Failed { .. }
+ ));
+ assert_eq!(
+ std::fs::read(temp.path().join("content/partial.m4s")).unwrap(),
+ b"partial"
+ );
+
+ let replay = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(replay.accepted_intent);
+ assert!(!replay.stop_acknowledged);
+ assert_eq!(replay.result.err().expect("cached unconfirmed stop"), error);
+ }
+
#[cfg(target_os = "linux")]
mod resume_transaction_tests {
use super::*;
@@ -3012,6 +3559,8 @@ mod tests {
cursors,
next_cursor_id: 13,
}),
+ all_tracks_stopped: true,
+ terminal_stop_failure: None,
segment_factory: factory,
resume_attempt: None,
resume_generation: 0,
@@ -3589,7 +4138,8 @@ mod tests {
let finished = stopping.await.unwrap().unwrap();
assert!(screen_stopped_while_audio_waited);
- assert!(finished.microphone.is_some());
+ assert!(finished.media_error.is_none());
+ assert!(finished.pipeline.microphone.is_some());
}
#[cfg(target_os = "macos")]
@@ -3719,11 +4269,14 @@ mod tests {
drop(screen_tx);
assert!(!stopping.is_finished());
microphone_release.notify_one();
- let finished = tokio::time::timeout(Duration::from_secs(2), stopping)
+ let stopped = tokio::time::timeout(Duration::from_secs(2), stopping)
.await
.unwrap()
.unwrap()
.unwrap();
+ assert_eq!(stopped.all_tracks_stopped, !fail_system_audio);
+ assert!(stopped.media_error.is_none());
+ let finished = stopped.pipeline;
assert!(finished.microphone.is_some());
assert!(finished.camera.is_some());
finished
@@ -4456,6 +5009,8 @@ mod tests {
.checked_sub(Duration::from_secs(2))
.unwrap(),
}),
+ all_tracks_stopped: true,
+ terminal_stop_failure: None,
segment_factory,
segments: Vec::new(),
completion_tx,
@@ -4623,8 +5178,9 @@ mod tests {
drop(screen_tx);
}
#[cfg(not(windows))]
- let finished =
- stopped.expect("display success should still allow the recording to stop cleanly");
+ let finished = stopped
+ .expect("display success should still allow the recording to stop cleanly")
+ .pipeline;
#[cfg(not(windows))]
drop(screen_tx);
@@ -4688,6 +5244,8 @@ mod windows_cancel_tests {
Actor {
recording_dir: PathBuf::new(),
state: None,
+ all_tracks_stopped: true,
+ terminal_stop_failure: None,
cancel_error: error,
segment_factory,
segments: Vec::new(),