forked from CapSoftware/Cap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2716 lines (2385 loc) · 88.7 KB
/
lib.rs
File metadata and controls
2716 lines (2385 loc) · 88.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod api;
mod audio;
mod audio_meter;
mod auth;
mod camera;
mod camera_legacy;
mod captions;
mod deeplink_actions;
mod editor_window;
mod export;
mod fake_window;
mod flags;
mod frame_ws;
mod general_settings;
mod hotkeys;
mod http_client;
mod logging;
mod notifications;
mod permissions;
mod platform;
mod posthog;
mod presets;
mod recording;
mod recording_settings;
mod target_select_overlay;
mod thumbnails;
mod tray;
mod update_project_names;
mod upload;
mod web_api;
mod window_exclusion;
mod windows;
use audio::AppSounds;
use auth::{AuthStore, Plan};
use camera::CameraPreviewState;
use cap_editor::{EditorInstance, EditorState};
use cap_project::{
InstantRecordingMeta, ProjectConfiguration, RecordingMeta, RecordingMetaInner, SharingMeta,
StudioRecordingMeta, StudioRecordingStatus, UploadMeta, VideoUploadInfo, XY, ZoomSegment,
};
use cap_recording::{
RecordingMode,
feeds::{
self,
camera::{CameraFeed, DeviceOrModelID},
microphone::{self, MicrophoneFeed},
},
sources::screen_capture::ScreenCaptureTarget,
};
use cap_rendering::{ProjectRecordingsMeta, RenderedFrame};
use clipboard_rs::common::RustImage;
use clipboard_rs::{Clipboard, ClipboardContext};
use editor_window::{EditorInstances, WindowEditorInstance};
use ffmpeg::ffi::AV_TIME_BASE;
use general_settings::GeneralSettingsStore;
use kameo::{Actor, actor::ActorRef};
use notifications::NotificationType;
use recording::InProgressRecording;
use scap_targets::{Display, DisplayId, WindowId, bounds::LogicalBounds};
use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
use std::{
collections::BTreeMap,
future::Future,
marker::PhantomData,
path::{Path, PathBuf},
process::Command,
str::FromStr,
sync::Arc,
};
use tauri::{AppHandle, Manager, State, Window, WindowEvent, ipc::Channel};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_plugin_notification::{NotificationExt, PermissionState};
use tauri_plugin_opener::OpenerExt;
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
use tokio::sync::{RwLock, oneshot};
use tracing::*;
use upload::{create_or_get_video, upload_image, upload_video};
use web_api::AuthedApiError;
use web_api::ManagerExt as WebManagerExt;
use windows::{CapWindowId, EditorWindowIds, ShowCapWindow, set_window_transparent};
use crate::{
camera::CameraPreviewManager,
recording_settings::{RecordingSettingsStore, RecordingTargetMode},
upload::InstantMultipartUpload,
};
use crate::{recording::start_recording, upload::build_video_meta};
#[allow(clippy::large_enum_variant)]
pub enum RecordingState {
None,
Pending {
mode: RecordingMode,
target: ScreenCaptureTarget,
},
Active(InProgressRecording),
}
pub struct App {
#[deprecated = "can be removed when native camera preview is ready"]
camera_ws_port: u16,
camera_preview: CameraPreviewManager,
handle: AppHandle,
recording_state: RecordingState,
recording_logging_handle: LoggingHandle,
mic_feed: ActorRef<feeds::microphone::MicrophoneFeed>,
camera_feed: ActorRef<feeds::camera::CameraFeed>,
server_url: String,
logs_dir: PathBuf,
}
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub enum VideoType {
Screen,
Output,
Camera,
}
#[derive(Serialize, Deserialize, specta::Type, Debug)]
pub enum UploadResult {
Success(String),
NotAuthenticated,
PlanCheckFailed,
UpgradeRequired,
}
#[derive(Serialize, Deserialize, specta::Type, Debug)]
pub struct VideoRecordingMetadata {
pub duration: f64,
pub size: f64,
}
impl App {
pub fn set_pending_recording(&mut self, mode: RecordingMode, target: ScreenCaptureTarget) {
self.recording_state = RecordingState::Pending { mode, target };
CurrentRecordingChanged.emit(&self.handle).ok();
}
pub fn set_current_recording(&mut self, actor: InProgressRecording) {
self.recording_state = RecordingState::Active(actor);
CurrentRecordingChanged.emit(&self.handle).ok();
}
pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {
match std::mem::replace(&mut self.recording_state, RecordingState::None) {
RecordingState::Active(recording) => {
self.close_occluder_windows();
Some(recording)
}
_ => {
self.close_occluder_windows();
None
}
}
}
fn close_occluder_windows(&self) {
for window in self.handle.webview_windows() {
if window.0.starts_with("window-capture-occluder-") {
let _ = window.1.close();
}
}
}
async fn add_recording_logging_handle(&mut self, path: &PathBuf) -> Result<(), String> {
let logfile =
std::fs::File::create(path).map_err(|e| format!("Failed to create logfile: {e}"))?;
self.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}"))?;
Ok(())
}
pub fn current_recording(&self) -> Option<&InProgressRecording> {
match &self.recording_state {
RecordingState::Active(recording) => Some(recording),
_ => None,
}
}
pub fn current_recording_mut(&mut self) -> Option<&mut InProgressRecording> {
match &mut self.recording_state {
RecordingState::Active(recording) => Some(recording),
_ => None,
}
}
pub fn is_recording_active_or_pending(&self) -> bool {
!matches!(self.recording_state, RecordingState::None)
}
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(state))]
async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> Result<(), String> {
let mic_feed = state.read().await.mic_feed.clone();
match label {
None => {
mic_feed
.ask(microphone::RemoveInput)
.await
.map_err(|e| e.to_string())?;
}
Some(label) => {
mic_feed
.ask(feeds::microphone::SetInput { label })
.await
.map_err(|e| e.to_string())?
.await
.map_err(|e| e.to_string())?;
}
}
Ok(())
}
#[tauri::command]
#[specta::specta]
async fn upload_logs(app_handle: AppHandle) -> Result<(), String> {
logging::upload_log_file(&app_handle).await
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(app_handle, state))]
async fn set_camera_input(
app_handle: AppHandle,
state: MutableState<'_, App>,
id: Option<DeviceOrModelID>,
) -> Result<(), String> {
let camera_feed = state.read().await.camera_feed.clone();
match id {
None => {
camera_feed
.ask(feeds::camera::RemoveInput)
.await
.map_err(|e| e.to_string())?;
}
Some(id) => {
ShowCapWindow::Camera
.show(&app_handle)
.await
.map_err(|err| error!("Failed to show camera preview window: {err}"))
.ok();
camera_feed
.ask(feeds::camera::SetInput { id })
.await
.map_err(|e| e.to_string())?
.await
.map_err(|e| e.to_string())?;
}
}
Ok(())
}
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
pub struct RecordingOptionsChanged;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct NewStudioRecordingAdded {
path: PathBuf,
}
#[derive(specta::Type, tauri_specta::Event, Debug, Clone, Serialize)]
pub struct RecordingDeleted {
#[allow(unused)]
path: PathBuf,
}
#[derive(specta::Type, tauri_specta::Event, Serialize)]
pub struct SetCaptureAreaPending(bool);
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct NewScreenshotAdded {
path: PathBuf,
}
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RecordingStarted;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RecordingStopped;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestStartRecording {
pub mode: RecordingMode,
}
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestOpenRecordingPicker {
pub target_mode: Option<RecordingTargetMode>,
}
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestOpenSettings {
page: String,
}
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestScreenCapturePrewarm {
#[serde(default)]
pub force: bool,
}
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct NewNotification {
title: String,
body: String,
is_error: bool,
}
type ArcLock<T> = Arc<RwLock<T>>;
pub type MutableState<'a, T> = State<'a, Arc<RwLock<T>>>;
type SingleTuple<T> = (T,);
#[derive(Serialize, Type)]
struct JsonValue<T>(
#[serde(skip)] PhantomData<T>,
#[specta(type = SingleTuple<T>)] serde_json::Value,
);
impl<T> Clone for JsonValue<T> {
fn clone(&self) -> Self {
Self(PhantomData, self.1.clone())
}
}
impl<T: Serialize> JsonValue<T> {
fn new(value: &T) -> Self {
Self(PhantomData, json!(value))
}
}
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RecordingInfo {
capture_target: ScreenCaptureTarget,
}
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
enum CurrentRecordingTarget {
Window {
id: WindowId,
bounds: LogicalBounds,
},
Screen {
id: DisplayId,
},
Area {
screen: DisplayId,
bounds: LogicalBounds,
},
}
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
struct CurrentRecording {
target: CurrentRecordingTarget,
mode: RecordingMode,
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(state))]
async fn get_current_recording(
state: MutableState<'_, App>,
) -> Result<JsonValue<Option<CurrentRecording>>, ()> {
let state = state.read().await;
let (mode, capture_target) = match &state.recording_state {
RecordingState::None => return Ok(JsonValue::new(&None)),
RecordingState::Pending { mode, target } => (*mode, target),
RecordingState::Active(inner) => (inner.mode(), inner.capture_target()),
};
let target = match capture_target {
ScreenCaptureTarget::Display { id } => CurrentRecordingTarget::Screen { id: id.clone() },
ScreenCaptureTarget::Window { id } => CurrentRecordingTarget::Window {
id: id.clone(),
bounds: scap_targets::Window::from_id(id)
.ok_or(())?
.display_relative_logical_bounds()
.ok_or(())?,
},
ScreenCaptureTarget::Area { screen, bounds } => CurrentRecordingTarget::Area {
screen: screen.clone(),
bounds: *bounds,
},
};
Ok(JsonValue::new(&Some(CurrentRecording { target, mode })))
}
#[derive(Serialize, Type, tauri_specta::Event, Clone)]
pub struct CurrentRecordingChanged;
async fn create_screenshot(
input: PathBuf,
output: PathBuf,
size: Option<(u32, u32)>,
) -> Result<(), String> {
println!("Creating screenshot: input={input:?}, output={output:?}, size={size:?}");
let result: Result<(), String> = tokio::task::spawn_blocking(move || -> Result<(), String> {
let mut ictx = ffmpeg::format::input(&input).map_err(|e| {
eprintln!("Failed to create input context: {e}");
e.to_string()
})?;
let input_stream = ictx
.streams()
.best(ffmpeg::media::Type::Video)
.ok_or("No video stream found")?;
let video_stream_index = input_stream.index();
println!("Found video stream at index {video_stream_index}");
let mut decoder =
ffmpeg::codec::context::Context::from_parameters(input_stream.parameters())
.map_err(|e| {
eprintln!("Failed to create decoder context: {e}");
e.to_string()
})?
.decoder()
.video()
.map_err(|e| {
eprintln!("Failed to create video decoder: {e}");
e.to_string()
})?;
let mut scaler = ffmpeg::software::scaling::context::Context::get(
decoder.format(),
decoder.width(),
decoder.height(),
ffmpeg::format::Pixel::RGB24,
size.map_or(decoder.width(), |s| s.0),
size.map_or(decoder.height(), |s| s.1),
ffmpeg::software::scaling::flag::Flags::BILINEAR,
)
.map_err(|e| {
eprintln!("Failed to create scaler: {e}");
e.to_string()
})?;
println!("Decoder and scaler initialized");
let mut frame = ffmpeg::frame::Video::empty();
for (stream, packet) in ictx.packets() {
if stream.index() == video_stream_index {
decoder.send_packet(&packet).map_err(|e| {
eprintln!("Failed to send packet to decoder: {e}");
e.to_string()
})?;
if decoder.receive_frame(&mut frame).is_ok() {
println!("Frame received, scaling...");
let mut rgb_frame = ffmpeg::frame::Video::empty();
scaler.run(&frame, &mut rgb_frame).map_err(|e| {
eprintln!("Failed to scale frame: {e}");
e.to_string()
})?;
let width = rgb_frame.width() as usize;
let height = rgb_frame.height() as usize;
let bytes_per_pixel = 3;
let src_stride = rgb_frame.stride(0);
let dst_stride = width * bytes_per_pixel;
let mut img_buffer = vec![0u8; height * dst_stride];
for y in 0..height {
let src_slice =
&rgb_frame.data(0)[y * src_stride..y * src_stride + dst_stride];
let dst_slice = &mut img_buffer[y * dst_stride..(y + 1) * dst_stride];
dst_slice.copy_from_slice(src_slice);
}
let img = image::RgbImage::from_raw(width as u32, height as u32, img_buffer)
.ok_or("Failed to create image from frame data")?;
println!("Saving image to {output:?}");
img.save_with_format(&output, image::ImageFormat::Jpeg)
.map_err(|e| {
eprintln!("Failed to save image: {e}");
e.to_string()
})?;
println!("Screenshot created successfully");
return Ok(());
}
}
}
eprintln!("Failed to create screenshot: No suitable frame found");
Err("Failed to create screenshot".to_string())
})
.await
.map_err(|e| format!("Task join error: {e}"))?;
result
}
// async fn create_thumbnail(input: PathBuf, output: PathBuf, size: (u32, u32)) -> Result<(), String> {
// println!("Creating thumbnail: input={input:?}, output={output:?}, size={size:?}");
// tokio::task::spawn_blocking(move || -> Result<(), String> {
// let img = image::open(&input).map_err(|e| {
// eprintln!("Failed to open image: {e}");
// e.to_string()
// })?;
// let width = img.width() as usize;
// let height = img.height() as usize;
// let bytes_per_pixel = 3;
// let src_stride = width * bytes_per_pixel;
// let rgb_img = img.to_rgb8();
// let img_buffer = rgb_img.as_raw();
// let mut corrected_buffer = vec![0u8; height * src_stride];
// for y in 0..height {
// let src_slice = &img_buffer[y * src_stride..(y + 1) * src_stride];
// let dst_slice = &mut corrected_buffer[y * src_stride..(y + 1) * src_stride];
// dst_slice.copy_from_slice(src_slice);
// }
// let corrected_img =
// image::RgbImage::from_raw(width as u32, height as u32, corrected_buffer)
// .ok_or("Failed to create corrected image")?;
// let thumbnail = image::imageops::resize(
// &corrected_img,
// size.0,
// size.1,
// image::imageops::FilterType::Lanczos3,
// );
// thumbnail
// .save_with_format(&output, image::ImageFormat::Png)
// .map_err(|e| {
// eprintln!("Failed to save thumbnail: {e}");
// e.to_string()
// })?;
// println!("Thumbnail created successfully");
// Ok(())
// })
// .await
// .map_err(|e| format!("Task join error: {e}"))?
// }
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(), String> {
println!("Attempting to copy file from {src} to {dst}");
let is_screenshot = src.contains("screenshots/");
let is_gif = src.ends_with(".gif") || dst.ends_with(".gif");
let src_path = std::path::Path::new(&src);
if !src_path.exists() {
return Err(format!("Source file {src} does not exist"));
}
if !is_screenshot && !is_gif && !is_valid_video(src_path) {
let mut attempts = 0;
while attempts < 10 {
std::thread::sleep(std::time::Duration::from_secs(1));
if is_valid_video(src_path) {
break;
}
attempts += 1;
}
if attempts == 10 {
return Err("Source video file is not a valid MP4".to_string());
}
}
if let Some(parent) = std::path::Path::new(&dst).parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e| format!("Failed to create target directory: {e}"))?;
}
let mut attempts = 0;
const MAX_ATTEMPTS: u32 = 3;
let mut last_error = None;
while attempts < MAX_ATTEMPTS {
match tokio::fs::copy(&src, &dst).await {
Ok(bytes) => {
let src_size = match tokio::fs::metadata(&src).await {
Ok(metadata) => metadata.len(),
Err(e) => {
last_error = Some(format!("Failed to get source file metadata: {e}"));
attempts += 1;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
continue;
}
};
if bytes != src_size {
last_error = Some(format!(
"File copy verification failed: copied {bytes} bytes but source is {src_size} bytes"
));
let _ = tokio::fs::remove_file(&dst).await;
attempts += 1;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
continue;
}
if !is_screenshot && !is_gif && !is_valid_video(std::path::Path::new(&dst)) {
last_error = Some("Destination file is not a valid".to_string());
let _ = tokio::fs::remove_file(&dst).await;
attempts += 1;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
continue;
}
println!("Successfully copied {bytes} bytes from {src} to {dst}");
notifications::send_notification(
&app,
if is_screenshot {
notifications::NotificationType::ScreenshotSaved
} else {
notifications::NotificationType::VideoSaved
},
);
return Ok(());
}
Err(e) => {
last_error = Some(e.to_string());
attempts += 1;
if attempts < MAX_ATTEMPTS {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
continue;
}
}
}
}
eprintln!(
"Failed to copy file from {} to {} after {} attempts. Last error: {}",
src,
dst,
MAX_ATTEMPTS,
last_error.as_ref().unwrap()
);
notifications::send_notification(
&app,
if is_screenshot {
notifications::NotificationType::ScreenshotSaveFailed
} else {
notifications::NotificationType::VideoSaveFailed
},
);
Err(last_error.unwrap_or_else(|| "Maximum retry attempts exceeded".to_string()))
}
pub fn is_valid_video(path: &std::path::Path) -> bool {
match ffmpeg::format::input(path) {
Ok(input_context) => {
// Check if we have at least one video stream
input_context
.streams()
.any(|stream| stream.parameters().medium() == ffmpeg::media::Type::Video)
}
Err(_) => false,
}
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(clipboard))]
async fn copy_screenshot_to_clipboard(
clipboard: MutableState<'_, ClipboardContext>,
path: String,
) -> Result<(), String> {
println!("Copying screenshot to clipboard: {path:?}");
let img_data = clipboard_rs::RustImageData::from_path(&path)
.map_err(|e| format!("Failed to copy screenshot to clipboard: {e}"))?;
clipboard
.write()
.await
.set_image(img_data)
.map_err(|err| format!("Failed to copy screenshot to clipboard: {err}"))?;
Ok(())
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(_app))]
async fn open_file_path(_app: AppHandle, path: PathBuf) -> Result<(), String> {
let path_str = path.to_str().ok_or("Invalid path")?;
#[cfg(target_os = "windows")]
{
Command::new("explorer")
.args(["/select,", path_str])
.spawn()
.map_err(|e| format!("Failed to open folder: {}", e))?;
}
#[cfg(target_os = "macos")]
{
Command::new("open")
.arg("-R")
.arg(path_str)
.spawn()
.map_err(|e| format!("Failed to open folder: {e}"))?;
}
#[cfg(target_os = "linux")]
{
Command::new("xdg-open")
.arg(
path.parent()
.ok_or("Invalid path")?
.to_str()
.ok_or("Invalid path")?,
)
.spawn()
.map_err(|e| format!("Failed to open folder: {}", e))?;
}
Ok(())
}
#[derive(Deserialize, specta::Type, tauri_specta::Event, Debug, Clone)]
struct RenderFrameEvent {
frame_number: u32,
fps: u32,
resolution_base: XY<u32>,
}
#[derive(Serialize, specta::Type, tauri_specta::Event, Debug, Clone)]
struct EditorStateChanged {
playhead_position: u32,
}
impl EditorStateChanged {
fn new(s: &EditorState) -> Self {
Self {
playhead_position: s.playhead_position,
}
}
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(editor_instance))]
async fn start_playback(
editor_instance: WindowEditorInstance,
fps: u32,
resolution_base: XY<u32>,
) -> Result<(), String> {
editor_instance.start_playback(fps, resolution_base).await;
Ok(())
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(editor_instance))]
async fn stop_playback(editor_instance: WindowEditorInstance) -> Result<(), String> {
let mut state = editor_instance.state.lock().await;
if let Some(handle) = state.playback_task.take() {
handle.stop();
}
Ok(())
}
#[derive(Serialize, Type, Debug)]
#[serde(rename_all = "camelCase")]
struct SerializedEditorInstance {
frames_socket_url: String,
recording_duration: f64,
saved_project_config: ProjectConfiguration,
recordings: Arc<ProjectRecordingsMeta>,
path: PathBuf,
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(window))]
async fn create_editor_instance(window: Window) -> Result<SerializedEditorInstance, String> {
let CapWindowId::Editor { id } = CapWindowId::from_str(window.label()).unwrap() else {
return Err("Invalid window".to_string());
};
let path = {
let window_ids = EditorWindowIds::get(window.app_handle());
let window_ids = window_ids.ids.lock().unwrap();
let Some((path, _)) = window_ids.iter().find(|(_, _id)| *_id == id) else {
return Err("Editor instance not found".to_string());
};
path.clone()
};
let editor_instance = EditorInstances::get_or_create(&window, path).await?;
let meta = editor_instance.meta();
println!("Pretty name: {}", meta.pretty_name);
Ok(SerializedEditorInstance {
frames_socket_url: format!("ws://localhost:{}", editor_instance.ws_port),
recording_duration: editor_instance.recordings.duration(),
saved_project_config: {
let project_config = editor_instance.project_config.1.borrow();
project_config.clone()
},
recordings: editor_instance.recordings.clone(),
path: editor_instance.project_path.clone(),
})
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(editor))]
async fn get_editor_meta(editor: WindowEditorInstance) -> Result<RecordingMeta, String> {
let path = editor.project_path.clone();
RecordingMeta::load_for_project(&path).map_err(|e| e.to_string())
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(editor))]
async fn set_pretty_name(editor: WindowEditorInstance, pretty_name: String) -> Result<(), String> {
let mut meta = editor.meta().clone();
meta.pretty_name = pretty_name;
meta.save_for_project().map_err(|e| e.to_string())
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(app, clipboard))]
async fn copy_video_to_clipboard(
app: AppHandle,
clipboard: MutableState<'_, ClipboardContext>,
path: String,
) -> Result<(), String> {
println!("copying");
let _ = clipboard.write().await.set_files(vec![path]);
notifications::send_notification(
&app,
notifications::NotificationType::VideoCopiedToClipboard,
);
Ok(())
}
#[tauri::command]
#[specta::specta]
#[instrument]
async fn get_video_metadata(path: PathBuf) -> Result<VideoRecordingMetadata, String> {
let recording_meta = RecordingMeta::load_for_project(&path).map_err(|v| v.to_string())?;
fn get_duration_for_path(path: PathBuf) -> Result<f64, String> {
let input =
ffmpeg::format::input(&path).map_err(|e| format!("Failed to open video file: {e}"))?;
let raw_duration = input.duration();
if raw_duration <= 0 {
return Err(format!(
"Unknown or invalid duration for video file: {path:?}"
));
}
let duration = raw_duration as f64 / AV_TIME_BASE as f64;
Ok(duration)
}
let display_paths = match &recording_meta.inner {
RecordingMetaInner::Instant(_) => {
vec![path.join("content/output.mp4")]
}
RecordingMetaInner::Studio(meta) => {
let status = meta.status();
if let StudioRecordingStatus::Failed { .. } = status {
return Err("Unable to get metadata on failed recording".to_string());
} else if let StudioRecordingStatus::InProgress = status {
return Err("Unable to get metadata on in-progress recording".to_string());
}
match meta {
StudioRecordingMeta::SingleSegment { segment } => {
vec![recording_meta.path(&segment.display.path)]
}
StudioRecordingMeta::MultipleSegments { inner } => inner
.segments
.iter()
.map(|s| recording_meta.path(&s.display.path))
.collect(),
}
}
};
let duration = display_paths
.into_iter()
.map(get_duration_for_path)
.try_fold(0f64, |acc, item| -> Result<f64, String> {
let d = item?;
Ok(acc + d)
})?;
let (width, height) = (1920, 1080);
let fps = 30;
let base_bitrate = if width <= 1280 && height <= 720 {
4_000_000.0
} else if width <= 1920 && height <= 1080 {
8_000_000.0
} else if width <= 2560 && height <= 1440 {
14_000_000.0
} else {
20_000_000.0
};
let fps_factor = (fps as f64) / 30.0;
let video_bitrate = base_bitrate * fps_factor;
let audio_bitrate = 192_000.0;
let total_bitrate = video_bitrate + audio_bitrate;
let estimated_size_mb = (total_bitrate * duration) / (8.0 * 1024.0 * 1024.0);
Ok(VideoRecordingMetadata {
size: estimated_size_mb,
duration,
})
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
fn close_recordings_overlay_window(app: AppHandle) {
#[cfg(target_os = "macos")]
{
use tauri_nspanel::ManagerExt;
if let Ok(panel) = app.get_webview_panel(&CapWindowId::RecordingsOverlay.label()) {
panel.released_when_closed(true);
panel.close();
}
}
if !cfg!(target_os = "macos")
&& let Some(window) = CapWindowId::RecordingsOverlay.get(&app)
{
let _ = window.close();
}
}
#[tauri::command(async)]
#[specta::specta]
#[instrument(skip(_app))]
fn focus_captures_panel(_app: AppHandle) {
#[cfg(target_os = "macos")]
{
use tauri_nspanel::ManagerExt;
if let Ok(panel) = _app.get_webview_panel(&CapWindowId::RecordingsOverlay.label()) {
panel.make_key_window();
}
}
}
#[derive(Serialize, Deserialize, specta::Type, Clone)]
#[serde(tag = "type", rename_all = "camelCase")]
pub struct FramesRendered {
rendered_count: u32,
total_frames: u32,
}
#[tauri::command]
#[specta::specta]
#[instrument(skip(editor_instance))]