-
Notifications
You must be signed in to change notification settings - Fork 394
/
Copy pathlib.rs
2446 lines (2076 loc) · 76.1 KB
/
lib.rs
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 audio;
mod auth;
mod camera;
mod capture;
mod encoder;
mod flags;
mod general_settings;
mod hotkeys;
mod macos;
mod notifications;
mod permissions;
mod recording;
mod tray;
mod upload;
mod web_api;
mod windows;
use audio::AppSounds;
use auth::AuthStore;
use cap_editor::{AudioData, EditorState, ProjectRecordings};
use cap_editor::{EditorInstance, FRAMES_WS_PATH};
use cap_media::{
feeds::{CameraFeed, CameraFrameSender},
platform::Bounds,
sources::{AudioInputSource, ScreenCaptureTarget},
};
use cap_project::{
ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,
};
use cap_rendering::ProjectUniforms;
use cap_utils::create_named_pipe;
// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
use num_traits::ToBytes;
use png::{ColorType, Encoder};
use recording::{list_cameras, list_capture_windows, InProgressRecording, FPS};
use scap::capturer::Capturer;
use scap::frame::Frame;
use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
use std::fs::File;
use std::io::BufWriter;
use std::io::{BufReader, Write};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{
collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
time::Duration,
};
use tauri::{AppHandle, Manager, Runtime, State, WindowEvent};
use tauri_nspanel::ManagerExt;
use tauri_plugin_notification::PermissionState;
use tauri_plugin_shell::ShellExt;
use tauri_specta::Event;
use tokio::sync::watch;
use tokio::sync::mpsc;
use tokio::task;
use tokio::{
sync::{Mutex, RwLock},
time::sleep,
};
use upload::{upload_image, upload_individual_file, upload_video};
use windows::CapWindow;
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RecordingOptions {
capture_target: ScreenCaptureTarget,
camera_label: Option<String>,
audio_input_name: Option<String>,
}
impl RecordingOptions {
fn camera_label(&self) -> Option<&str> {
self.camera_label.as_deref()
}
fn audio_input_name(&self) -> Option<&str> {
self.audio_input_name.as_deref()
}
}
#[derive(specta::Type, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct App {
start_recording_options: RecordingOptions,
#[serde(skip)]
camera_tx: CameraFrameSender,
camera_ws_port: u16,
#[serde(skip)]
camera_feed: Option<CameraFeed>,
#[serde(skip)]
handle: AppHandle,
#[serde(skip)]
current_recording: Option<InProgressRecording>,
}
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub enum VideoType {
Screen,
Output,
}
#[derive(Serialize, Deserialize, specta::Type)]
enum UploadResult {
Success(String),
NotAuthenticated,
PlanCheckFailed,
UpgradeRequired,
}
impl App {
pub fn set_current_recording(&mut self, new_value: InProgressRecording) {
let option = Some(new_value);
let json = JsonValue::new(&option);
let new_value = option.unwrap();
let current_recording = self.current_recording.insert(new_value);
CurrentRecordingChanged(json).emit(&self.handle).ok();
if let ScreenCaptureTarget::Window { .. } = ¤t_recording.display_source {
let _ = CapWindow::WindowCaptureOccluder.show(&self.handle);
} else {
self.close_occluder_window();
}
}
pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {
self.close_occluder_window();
self.current_recording.take()
}
fn close_occluder_window(&self) {
if let Some(window) = CapWindow::WindowCaptureOccluder.get(&self.handle) {
window.close().ok();
}
}
async fn set_start_recording_options(&mut self, new_options: RecordingOptions) {
match (CapWindow::Camera { ws_port: 0 }).get(&self.handle) {
Some(window) if new_options.camera_label.is_none() => {
println!("closing camera window");
window.close().ok();
}
None if new_options.camera_label.is_some() => {
println!("creating camera window");
CapWindow::Camera {
ws_port: self.camera_ws_port,
}
.show(&self.handle)
.ok();
}
_ => {}
}
match &new_options.camera_label {
Some(camera_label) => {
if self.camera_feed.is_none() {
self.camera_feed = CameraFeed::init(&camera_label, self.camera_tx.clone())
.await
.ok();
}
if let Some(camera_feed) = self.camera_feed.as_mut() {
camera_feed.switch_cameras(&camera_label).await.ok();
}
}
None => {
self.camera_feed = None;
}
}
self.start_recording_options = new_options;
RecordingOptionsChanged.emit(&self.handle).ok();
}
}
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
pub struct RecordingOptionsChanged;
// dedicated event + command used as panel must be accessed on main thread
#[derive(specta::Type, Serialize, tauri_specta::Event, Clone)]
pub struct ShowCapturesPanel;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct NewRecordingAdded {
path: PathBuf,
}
#[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 {
path: PathBuf,
}
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestStartRecording;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestRestartRecording;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestNewScreenshot;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestStopRecording;
#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]
pub struct RequestOpenSettings {
page: String,
}
type MutableState<'a, T> = State<'a, Arc<RwLock<T>>>;
#[tauri::command]
#[specta::specta]
async fn get_recording_options(state: MutableState<'_, App>) -> Result<RecordingOptions, ()> {
let state = state.read().await;
Ok(state.start_recording_options.clone())
}
#[tauri::command]
#[specta::specta]
async fn set_recording_options(
state: MutableState<'_, App>,
options: RecordingOptions,
) -> Result<(), ()> {
state
.write()
.await
.set_start_recording_options(options)
.await;
Ok(())
}
type Bruh<T> = (T,);
#[derive(Serialize, Type)]
struct JsonValue<T>(
#[serde(skip)] PhantomData<T>,
#[specta(type = Bruh<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))
}
}
#[tauri::command]
#[specta::specta]
async fn get_current_recording(
state: MutableState<'_, App>,
) -> Result<JsonValue<Option<InProgressRecording>>, ()> {
let state = state.read().await;
Ok(JsonValue::new(&state.current_recording))
}
#[derive(Serialize, Type, tauri_specta::Event, Clone)]
pub struct CurrentRecordingChanged(JsonValue<Option<InProgressRecording>>);
#[tauri::command]
#[specta::specta]
async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
let id = uuid::Uuid::new_v4().to_string();
let recording_dir = app
.path()
.app_data_dir()
.unwrap()
.join("recordings")
.join(format!("{id}.cap"));
match recording::start(
recording_dir,
&state.start_recording_options,
state.camera_feed.as_ref(),
)
.await
{
Ok(recording) => state.set_current_recording(recording),
Err(error) => {
eprintln!("{error}");
return Err("Failed to set up recording".into());
}
};
if let Some(window) = CapWindow::Main.get(&app) {
window.minimize().ok();
}
if let Some(window) = (CapWindow::InProgressRecording { position: None }).get(&app) {
window.eval("window.location.reload()").unwrap();
window.show().unwrap();
}
AppSounds::StartRecording.play();
RecordingStarted.emit(&app).ok();
Ok(())
}
#[tauri::command]
#[specta::specta]
async fn pause_recording(state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
if let Some(recording) = &mut state.current_recording {
recording.pause().await?;
recording.segments.push(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs_f64(),
);
}
Ok(())
}
#[tauri::command]
#[specta::specta]
async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
if let Some(recording) = &mut state.current_recording {
recording.play().await?;
recording.segments.push(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs_f64(),
);
}
Ok(())
}
#[tauri::command]
#[specta::specta]
async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
let Some(mut current_recording) = state.write().await.clear_current_recording() else {
return Err("Recording not in progress".to_string());
};
current_recording.segments.push(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs_f64(),
);
current_recording.stop().await;
println!("Recording stopped");
if let Some(window) = (CapWindow::InProgressRecording { position: None }).get(&app) {
window.hide().unwrap();
}
if let Some(window) = CapWindow::Main.get(&app) {
window.unminimize().ok();
}
std::fs::create_dir_all(current_recording.recording_dir.join("screenshots")).ok();
let display_screenshot = current_recording
.recording_dir
.join("screenshots/display.jpg");
create_screenshot(
current_recording.display_output_path.clone(),
display_screenshot.clone(),
None,
)
.await?;
// Create thumbnail
let thumbnail = current_recording
.recording_dir
.join("screenshots/thumbnail.png");
create_thumbnail(display_screenshot, thumbnail, (100, 100)).await?;
let recording_dir = current_recording.recording_dir.clone();
ShowCapturesPanel.emit(&app).ok();
NewRecordingAdded {
path: recording_dir.clone(),
}
.emit(&app)
.ok();
RecordingStopped {
path: recording_dir,
}
.emit(&app)
.ok();
let config = {
let mut segments = vec![];
let mut passed_duration = 0.0;
for i in (0..current_recording.segments.len()).step_by(2) {
let start = passed_duration;
passed_duration += current_recording.segments[i + 1] - current_recording.segments[i];
segments.push(TimelineSegment {
start,
end: passed_duration,
timescale: 1.0,
});
}
ProjectConfiguration {
timeline: Some(TimelineConfiguration { segments }),
..Default::default()
}
};
std::fs::write(
current_recording.recording_dir.join("project-config.json"),
serde_json::to_string_pretty(&json!(&config)).unwrap(),
)
.unwrap();
AppSounds::StopRecording.play();
if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {
if settings.open_editor_after_recording {
let recording_id = current_recording
.recording_dir
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string()
.trim_end_matches(".cap")
.to_string();
open_editor(app.clone(), recording_id);
}
}
CurrentRecordingChanged(JsonValue::new(&None))
.emit(&app)
.ok();
Ok(())
}
async fn create_screenshot(
input: PathBuf,
output: PathBuf,
size: Option<(u32, u32)>,
) -> Result<(), String> {
println!(
"Creating screenshot: input={:?}, output={:?}, size={:?}",
input, output, size
);
let result: Result<(), String> = tokio::task::spawn_blocking(move || -> Result<(), String> {
ffmpeg::init().map_err(|e| {
eprintln!("Failed to initialize ffmpeg: {}", e);
e.to_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()
})?;
// Use image crate to save the frame as an image file
let width = rgb_frame.width() as u32;
let height = rgb_frame.height() as u32;
let data = rgb_frame.data(0);
let img = image::RgbImage::from_raw(width, height, data.to_vec())
.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={:?}, output={:?}, size={:?}",
input, output, 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 thumbnail = img.thumbnail(size.0, size.1);
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]
async fn get_rendered_video(
app: AppHandle,
video_id: String,
project: ProjectConfiguration,
) -> Result<PathBuf, String> {
let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;
get_rendered_video_impl(editor_instance, project).await
}
async fn get_rendered_video_impl(
editor_instance: Arc<EditorInstance>,
project: ProjectConfiguration,
) -> Result<PathBuf, String> {
let output_path = editor_instance.project_path.join("output/result.mp4");
if !output_path.exists() {
render_to_file_impl(&editor_instance, project, output_path.clone(), |_| {}).await?;
}
Ok(output_path)
}
#[tauri::command]
#[specta::specta]
async fn copy_file_to_path(src: String, dst: String) -> Result<(), String> {
println!("Attempting to copy file from {} to {}", src, dst);
match tokio::fs::copy(&src, &dst).await {
Ok(bytes) => {
println!(
"Successfully copied {} bytes from {} to {}",
bytes, src, dst
);
Ok(())
}
Err(e) => {
eprintln!("Failed to copy file from {} to {}: {}", src, dst, e);
Err(e.to_string())
}
}
}
#[tauri::command]
#[specta::specta]
async fn copy_screenshot_to_clipboard(app: AppHandle, path: PathBuf) -> Result<(), String> {
println!("Copying screenshot to clipboard: {:?}", path);
let image_data = match tokio::fs::read(&path).await {
Ok(data) => data,
Err(e) => {
println!("Failed to read screenshot file: {}", e);
return Err(format!("Failed to read screenshot file: {}", e));
}
};
#[cfg(target_os = "macos")]
{
use cocoa::appkit::{NSImage, NSPasteboard};
use cocoa::base::{id, nil};
use cocoa::foundation::{NSArray, NSData};
use objc::rc::autoreleasepool;
unsafe {
autoreleasepool(|| {
let pasteboard: id = NSPasteboard::generalPasteboard(nil);
NSPasteboard::clearContents(pasteboard);
let ns_data = NSData::dataWithBytes_length_(
nil,
image_data.as_ptr() as *const std::os::raw::c_void,
image_data.len() as u64,
);
let image = NSImage::initWithData_(NSImage::alloc(nil), ns_data);
if image != nil {
NSPasteboard::writeObjects(pasteboard, NSArray::arrayWithObject(nil, image));
Ok(())
} else {
Err("Failed to create NSImage from data".to_string())
}
})
}
}
#[cfg(not(target_os = "macos"))]
{
Err("Clipboard operations are only supported on macOS".to_string())
}
}
#[tauri::command]
#[specta::specta]
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(())
}
struct AudioRender {
data: AudioData,
pipe_tx: tokio::sync::mpsc::Sender<Vec<f64>>,
}
async fn render_to_file_impl(
editor_instance: &Arc<EditorInstance>,
project: ProjectConfiguration,
output_path: PathBuf,
on_progress: impl Fn(u32) + Send + 'static,
) -> Result<PathBuf, String> {
let recording_dir = &editor_instance.project_path;
let audio = editor_instance.audio.clone();
let decoders = editor_instance.decoders.clone();
let options = editor_instance.render_constants.options.clone();
// Change this to be whatever is the most ideal for certain processors
let buffer_size = 60 * 3; // 3 seconds at 60 fps, or 6 seconds at 30 fps
let (tx_image_data, mut rx_image_data) = mpsc::channel::<Vec<u8>>(buffer_size);// Adjust buffer size as needed
let output_folder = output_path.parent().unwrap();
std::fs::create_dir_all(output_folder)
.map_err(|e| format!("Failed to create output directory: {:?}", e))?;
let output_size = ProjectUniforms::get_output_size(&options, &project);
let ffmpeg_handle = tokio::spawn({
let project = project.clone();
let output_path = output_path.clone();
let recording_dir = recording_dir.clone();
async move {
println!("Starting FFmpeg output process...");
let mut ffmpeg = cap_ffmpeg::FFmpeg::new();
let audio_dir = tempfile::tempdir().unwrap();
let video_dir = tempfile::tempdir().unwrap();
let video_tx = {
let pipe_path = video_dir.path().join("video.pipe");
create_named_pipe(&pipe_path).unwrap();
ffmpeg.add_input(cap_ffmpeg::FFmpegRawVideoInput {
width: output_size.0,
height: output_size.1,
fps: 30,
pix_fmt: "rgba",
input: pipe_path.clone().into_os_string(),
});
let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);
tokio::spawn(async move {
let mut file = std::fs::File::create(&pipe_path).unwrap();
println!("video pipe opened");
while let Some(bytes) = rx.recv().await {
file.write_all(&bytes).unwrap();
}
println!("done writing to video pipe");
});
tx
};
let audio = if let Some(audio_data) = audio.lock().unwrap().as_ref() {
let pipe_path = audio_dir.path().join("audio.pipe");
create_named_pipe(&pipe_path).unwrap();
ffmpeg.add_input(cap_ffmpeg::FFmpegRawAudioInput {
input: pipe_path.clone().into_os_string(),
sample_format: "f64le".to_string(),
sample_rate: audio_data.sample_rate,
channels: 1,
});
let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<f64>>(30);
tokio::spawn(async move {
let mut file = std::fs::File::create(&pipe_path).unwrap();
println!("audio pipe opened");
while let Some(bytes) = rx.recv().await {
let bytes = bytes
.iter()
.flat_map(|f| f.to_le_bytes())
.collect::<Vec<_>>();
file.write_all(&bytes).unwrap();
}
println!("done writing to audio pipe");
});
Some(AudioRender {
data: audio_data.clone(),
pipe_tx: tx,
})
} else {
None
};
ffmpeg
.command
.args(["-f", "mp4"])
.args(["-codec:v", "libx264", "-codec:a", "aac"])
.args(["-preset", "ultrafast"])
.args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
.arg("-y")
.arg(&output_path);
let mut ffmpeg_process = ffmpeg.start();
let mut frame_count = 0;
let mut first_frame = None;
loop {
match rx_image_data.recv().await {
Some(frame) => {
on_progress(frame_count);
if frame_count == 0 {
first_frame = Some(frame.clone());
}
if let Some(audio) = &audio {
let samples_per_frame = audio.data.sample_rate as f64 / FPS as f64;
let start_samples = match project.timeline() {
Some(timeline) => timeline
.get_recording_time(frame_count as f64 / FPS as f64)
.map(|recording_time| {
recording_time * audio.data.sample_rate as f64
}),
None => Some(frame_count as f64 * samples_per_frame),
};
if let Some(start) = start_samples {
let end = start + samples_per_frame;
let samples = &audio.data.buffer[start as usize..end as usize];
let mut samples_iter = samples.iter().copied();
let mut frame_samples = Vec::new();
for _ in 0..samples_per_frame as usize {
frame_samples.push(samples_iter.next().unwrap_or(0.0));
}
audio.pipe_tx.send(frame_samples).await.unwrap();
}
}
video_tx.send(frame).await.unwrap();
frame_count += 1;
}
None => {
println!("All frames sent to FFmpeg");
break;
}
}
}
ffmpeg_process.stop();
// Save the first frame as a screenshot and thumbnail
if let Some(frame_data) = first_frame {
let width = output_size.0;
let height = output_size.1;
let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
ImageBuffer::from_raw(width, height, frame_data)
.expect("Failed to create image from frame data");
// Convert RGBA to RGB
let rgb_img: ImageBuffer<image::Rgb<u8>, Vec<u8>> =
ImageBuffer::from_fn(width, height, |x, y| {
let rgba = rgba_img.get_pixel(x, y);
image::Rgb([rgba[0], rgba[1], rgba[2]])
});
let screenshots_dir = recording_dir.join("screenshots");
std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
eprintln!("Failed to create screenshots directory: {:?}", e);
});
// Save full-size screenshot
let screenshot_path = screenshots_dir.join("display.jpg");
rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
eprintln!("Failed to save screenshot: {:?}", e);
});
// Create and save thumbnail
let thumbnail = image::imageops::resize(
&rgb_img,
100,
100,
image::imageops::FilterType::Lanczos3,
);
let thumbnail_path = screenshots_dir.join("thumbnail.png");
thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
eprintln!("Failed to save thumbnail: {:?}", e);
});
} else {
eprintln!("No frames were processed, cannot save screenshot or thumbnail");
}
}
});
println!("Rendering video to channel");
cap_rendering::render_video_to_channel(options, project, tx_image_data, decoders).await?;
ffmpeg_handle.await.ok();
println!("Copying file to {:?}", recording_dir);
let result_path = recording_dir.join("output/result.mp4");
// Function to check if the file is a valid MP4
fn is_valid_mp4(path: &std::path::Path) -> bool {
if let Ok(file) = std::fs::File::open(path) {
let file_size = match file.metadata() {
Ok(metadata) => metadata.len(),
Err(_) => return false,
};
let reader = std::io::BufReader::new(file);
Mp4Reader::read_header(reader, file_size).is_ok()
} else {
false
}
}
if output_path != result_path {
println!("Waiting for valid MP4 file at {:?}", output_path);
// Wait for the file to become a valid MP4
let mut attempts = 0;
while attempts < 10 {
// Wait for up to 60 seconds
if is_valid_mp4(&output_path) {
println!("Valid MP4 file detected after {} seconds", attempts);
match std::fs::copy(&output_path, &result_path) {
Ok(bytes) => {
println!("Successfully copied {} bytes to {:?}", bytes, result_path)
}
Err(e) => eprintln!("Failed to copy file: {:?}", e),
}
break;
}
println!("Attempt {}: File not yet valid, waiting...", attempts + 1);
std::thread::sleep(std::time::Duration::from_secs(1));
attempts += 1;
}
if attempts == 10 {
eprintln!("Timeout: Failed to detect a valid MP4 file after 60 seconds");
}
}
Ok(output_path)
}
#[derive(Deserialize, specta::Type, tauri_specta::Event, Debug, Clone)]
struct RenderFrameEvent {
frame_number: 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]