-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlib.rs
More file actions
1202 lines (1098 loc) · 49 KB
/
Copy pathlib.rs
File metadata and controls
1202 lines (1098 loc) · 49 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
//! # Gyroflow Toolbox: Rust Interface
//!
//! This module allows for communication between the Gyroflow Toolbox Objective-C FxPlug4 code and the `gyroflow_core` Rust library.
//---------------------------------------------------------
// Local name bindings:
//---------------------------------------------------------
use gyroflow_core::{StabilizationManager, stabilization::*};
use gyroflow_core::gpu::{ BufferDescription, BufferSource, Buffers };
use once_cell::sync::OnceCell; // Provides two new cell-like types, unsync::OnceCell and sync::OnceCell
use lazy_static::*; // A macro for declaring lazily evaluated statics
use lru::LruCache; // A LRU cache implementation
use nalgebra::Vector4; // Allows us to use `Vector4`
use std::ffi::CStr; // Allows us to use `CStr`
use std::ffi::CString; // Allows us to use `CString`
use std::os::raw::c_char; // Allows us to use `*const c_uchar`
use std::sync::Arc; // Adds Atomic Reference Count support
use std::sync::atomic::AtomicBool; // The AtomicBool type is a type of atomic variable that can be used in concurrent (multi-threaded) contexts.
use std::sync::Mutex; // A mutual exclusion primitive useful for protecting shared data
//---------------------------------------------------------
// Start writing log files to disk:
//---------------------------------------------------------
#[unsafe(no_mangle)]
pub extern "C" fn startLogger(
log_path: *const c_char,
) {
log_panics::init();
log::error!("[Gyroflow Toolbox Rust] Starting Rust Logger...");
log::error!("[Gyroflow Toolbox Rust] log path: {:?}", log_path);
let log_path_pointer = unsafe { CStr::from_ptr(log_path) };
let log_path_string = log_path_pointer.to_string_lossy();
let log_config = [ "mp4parse", "wgpu", "naga", "akaze", "ureq", "rustls", "ofx" ]
.into_iter()
.fold(simplelog::ConfigBuilder::new(), |mut cfg, x| { cfg.add_filter_ignore_str(x); cfg })
.build();
if let Ok(file_log) = std::fs::File::create(log_path_string.as_ref()) {
let _ = simplelog::WriteLogger::init(log::LevelFilter::Debug, log_config, file_log);
}
//---------------------------------------------------------
// Load the Lens Profiles:
//---------------------------------------------------------
let stab = StabilizationManager::default();
stab.lens_profile_db.write().load_all();
let mut lock = MANAGER_CACHE.lock().unwrap();
lock.put("lens-profiles".into(), Arc::new(stab));
}
// This code block defines a lazy static variable called `MANAGER_CACHE` that is a `Mutex`-protected LRU cache of `StabilizationManager` instances.
//
// The `lazy_static!` macro is used to ensure that the variable is initialized only once, and only when it is first accessed.
//
// The `Mutex` is used to ensure that the cache can be safely accessed from multiple threads.
//
// The `LruCache` is used to limit the size of the cache to 8 items.
//
// # Example
//
// ```rust
// use gyroflow::MANAGER_CACHE;
//
// let cache = MANAGER_CACHE.lock().unwrap();
// let manager = cache.get("my_pixel_format").unwrap();
// ```
lazy_static! {
static ref MANAGER_CACHE: Mutex<LruCache<String, Arc<StabilizationManager>>> = Mutex::new(LruCache::new(std::num::NonZeroUsize::new(8).unwrap()));
}
/// This function retrieves default values from a Gyroflow Project.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to the Gyroflow Project data.
/// * `fov` - A pointer to the field of view value.
/// * `smoothness` - A pointer to the smoothness value.
/// * `lens_correction` - A pointer to the lens correction value.
/// * `horizon_lock` - A pointer to the horizon lock value.
/// * `horizon_roll` - A pointer to the horizon roll value.
/// * `position_offset_x` - A pointer to the position offset x value.
/// * `position_offset_y` - A pointer to the position offset y value.
/// * `video_rotation` - A pointer to the video rotation value.
///
/// # Safety
///
/// This function is marked as unsafe because it takes a raw pointer as an argument.
/// The caller must ensure that the pointer is valid and that the data it points to is valid and correctly aligned.
///
/// # Returns
///
/// A pointer to a C-style string containing either "OK" or a failure string.
///
/// # Example
///
/// ```rust
/// use gyroflow::getDefaultValues;
///
/// let gyroflow_project_data = "Gyroflow Project Data".as_ptr() as *const c_char;
/// let fov: *mut f64 = std::ptr::null_mut();
/// let smoothness: *mut f64 = std::ptr::null_mut();
/// let lens_correction: *mut f64 = std::ptr::null_mut();
/// let horizon_lock: *mut f64 = std::ptr::null_mut();
/// let horizon_roll: *mut f64 = std::ptr::null_mut();
/// let position_offset_x: *mut f64 = std::ptr::null_mut();
/// let position_offset_y: *mut f64 = std::ptr::null_mut();
/// let video_rotation: *mut f64 = std::ptr::null_mut();
///
/// let result = unsafe {
/// getDefaultValues(
/// gyroflow_project_data,
/// fov,
/// smoothness,
/// lens_correction,
/// horizon_lock,
/// horizon_roll,
/// position_offset_x,
/// position_offset_y,
/// video_rotation,
/// )
/// };
///
/// assert_eq!(result, "OK");
/// ```
#[unsafe(no_mangle)]
pub extern "C" fn getDefaultValues(
gyroflow_project_data: *const c_char,
fov: *mut f64,
smoothness: *mut f64,
lens_correction: *mut f64,
horizon_lock: *mut f64,
horizon_roll: *mut f64,
position_offset_x: *mut f64,
position_offset_y: *mut f64,
video_rotation: *mut f64,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
unsafe {
let params = stab.params.read();
let smoothing = stab.smoothing.read();
*fov = params.fov;
*smoothness = smoothing.current().get_parameter("smoothness");
*lens_correction = params.lens_correction_amount * 100.0;
*horizon_lock = smoothing.horizon_lock.horizonlockpercent;
*horizon_roll = smoothing.horizon_lock.horizonroll;
*position_offset_x = params.adaptive_zoom_center_offset.0;
*position_offset_y = params.adaptive_zoom_center_offset.1;
*video_rotation = params.video_rotation;
}
let result = CString::new("OK").unwrap();
return result.into_raw()
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing gyroflow data: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// Gets the lens identifier.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to a C-style string containing the Gyroflow Project data.
///
/// # Returns
///
/// A pointer to a C-style string containing the lens identifier or "FAIL".
///
/// # Safety
///
/// This function is marked as unsafe because it accepts a raw pointer as an argument. It is the caller's responsibility to ensure that the pointer is valid and points to a null-terminated string.
#[unsafe(no_mangle)]
pub extern "C" fn getLensIdentifier(
gyroflow_project_data: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
//---------------------------------------------------------
// Get the Lens Identifier:
//---------------------------------------------------------
let identifier = stab.lens.read().identifier.to_string();
let result = CString::new(identifier).unwrap();
return result.into_raw();
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing gyroflow data: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// Checks if a lens profile is loaded.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to a C-style string containing the Gyroflow Project data.
///
/// # Returns
///
/// A pointer to a C-style string containing "YES" if the official lens is loaded, or a failure string otherwise.
///
/// # Safety
///
/// This function is marked as unsafe because it accepts a raw pointer as an argument. It is the caller's responsibility to ensure that the pointer is valid and points to a null-terminated string.
#[unsafe(no_mangle)]
pub extern "C" fn isLensProfileLoaded(
gyroflow_project_data: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
//---------------------------------------------------------
// Is official lens loaded?
//---------------------------------------------------------
let is_official_lens_loaded = stab.lens.read().calib_dimension.w > 0;
if is_official_lens_loaded {
let result = CString::new("YES").unwrap();
return result.into_raw()
} else {
let result = CString::new("NO").unwrap();
return result.into_raw()
}
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing gyroflow data: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// Determines whether the Gyroflow Project contains Stabilisation Data.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to a C-style string containing the Gyroflow Project data.
///
/// # Returns
///
/// A pointer to a C-style string containing "YES" if the Gyroflow Project contains Stabilisation Data, or a failure string otherwise.
///
/// # Safety
///
/// This function is marked as unsafe because it accepts a raw pointer as an argument. It is the caller's responsibility to ensure that the pointer is valid and points to a null-terminated string.
#[unsafe(no_mangle)]
pub extern "C" fn doesGyroflowProjectContainStabilisationData(
gyroflow_project_data: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
let mut stab: StabilizationManager = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
//---------------------------------------------------------
// Check if gyroflow project contains stabilization data:
//---------------------------------------------------------
let has_motion = {
let gyro = stab.gyro.read();
let metadata = gyro.file_metadata.read();
log::error!("[Gyroflow Toolbox Rust] gyro.file_metadata.raw_imu: {:?}", metadata.raw_imu);
log::error!("[Gyroflow Toolbox Rust] gyro.file_metadata.quaternions: {:?}", metadata.quaternions);
//log::error!("[Gyroflow Toolbox Rust] gyro.raw_imu: {:?}", metadata.raw_imu);
log::error!("[Gyroflow Toolbox Rust] gyro.quaternions: {:?}", gyro.quaternions);
log::error!("[Gyroflow Toolbox Rust] detected_source: {:?}", metadata.detected_source);
log::error!("[Gyroflow Toolbox Rust] imu_orientation: {:?}", metadata.imu_orientation);
log::error!("[Gyroflow Toolbox Rust] integration_method: {:?}", gyro.integration_method);
log::error!("[Gyroflow Toolbox Rust] file_url: {:?}", gyro.file_url);
!metadata.raw_imu.is_empty() || !gyro.quaternions.is_empty()
};
//---------------------------------------------------------
// Return the result as a string:
//---------------------------------------------------------
let result_string = if has_motion {
"YES"
} else {
"NO"
};
let result = CString::new(result_string).unwrap();
return result.into_raw()
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing gyroflow data: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// Determines whether the Gyroflow Project data has accurate timestamps.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to a C-style string containing the Gyroflow Project data.
///
/// # Returns
///
/// * If the project contains accurate timestamps, returns a C-style string containing "YES".
/// * If the project does not contain accurate timestamps, returns a C-style string containing an error message.
#[unsafe(no_mangle)]
pub extern "C" fn hasAccurateTimestamps(
gyroflow_project_data: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
//---------------------------------------------------------
// Check if gyroflow project contains stabilization data:
//---------------------------------------------------------
let has_accurate_timestamps = {
stab.gyro.read().file_metadata.read().has_accurate_timestamps
};
//---------------------------------------------------------
// Return the result as a string:
//---------------------------------------------------------
let result_string = if has_accurate_timestamps {
"YES"
} else {
"NO"
};
let result = CString::new(result_string).unwrap();
return result.into_raw()
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing gyroflow data: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// Load a Lens Profile from a JSON to a supplied Gyroflow Project.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to a C-style string representing the Gyroflow Project data.
/// * `lens_profile_path` - A pointer to a C-style string representing the Lens Profile data.
///
/// # Returns
///
/// A new Gyroflow Project or "FAIL".
#[unsafe(no_mangle)]
pub extern "C" fn loadLensProfile(
gyroflow_project_data: *const c_char,
lens_profile_path: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
//---------------------------------------------------------
// Convert the Lens Profile data to a `&str`:
//---------------------------------------------------------
let lens_profile_path_pointer = unsafe { CStr::from_ptr(lens_profile_path) };
let lens_profile_path_string = lens_profile_path_pointer.to_string_lossy();
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
//---------------------------------------------------------
// Load Lens Profile:
//---------------------------------------------------------
if let Err(e) = stab.load_lens_profile(&lens_profile_path_string) {
log::error!("[Gyroflow Toolbox Rust] Error loading Lens Profile: {:?}", e);
let result = CString::new("FAIL").unwrap();
return result.into_raw()
}
//---------------------------------------------------------
// Export Gyroflow data:
//---------------------------------------------------------
let gyroflow_data: String;
match stab.export_gyroflow_data(gyroflow_core::GyroflowProjectType::WithGyroData, "{}", None) {
Ok(data) => {
gyroflow_data = data;
log::info!("[Gyroflow Toolbox Rust] Gyroflow data exported successfully");
},
Err(e) => {
log::error!("[Gyroflow Toolbox Rust] An error occured: {:?}", e);
gyroflow_data = "FAIL".to_string();
}
}
//---------------------------------------------------------
// Return Gyroflow Project data as string:
//---------------------------------------------------------
let result = CString::new(gyroflow_data).unwrap();
return result.into_raw()
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing Lens Profile: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// Load a Gyroflow Preset to a supplied Gyroflow Project.
///
/// # Arguments
///
/// * `gyroflow_project_data` - A pointer to a C-style string representing the Gyroflow Project data.
/// * `preset_path` - A pointer to a C-style string representing the Profile data.
///
/// # Returns
///
/// A new Gyroflow Project or "FAIL".
#[unsafe(no_mangle)]
pub extern "C" fn loadPreset(
gyroflow_project_data: *const c_char,
preset_path: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the Gyroflow Project data to a `&str`:
//---------------------------------------------------------
let gyroflow_project_data_pointer = unsafe { CStr::from_ptr(gyroflow_project_data) };
let gyroflow_project_data_string = gyroflow_project_data_pointer.to_string_lossy();
//---------------------------------------------------------
// Convert the Lens Profile data to a `&str`:
//---------------------------------------------------------
let preset_path_pointer = unsafe { CStr::from_ptr(preset_path) };
let preset_path_string = preset_path_pointer.to_string_lossy();
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Import the `gyroflow_project_data_string`:
//---------------------------------------------------------
let blocking = true;
let cancel_flag = Arc::new(AtomicBool::new(false));
let mut is_preset = false;
match stab.import_gyroflow_data(
gyroflow_project_data_string.as_bytes(),
blocking,
None,
|_|(),
cancel_flag,
&mut is_preset,
true
) {
Ok(_) => {
//---------------------------------------------------------
// Load Preset:
//---------------------------------------------------------
let mut is_preset = false;
if let Err(e) = stab.import_gyroflow_data(preset_path_string.as_bytes(), true, None, |_|(), Arc::new(AtomicBool::new(false)), &mut is_preset, true) {
log::error!("[Gyroflow Toolbox Rust] Error loading Preset: {:?}", e);
let result = CString::new("FAIL").unwrap();
return result.into_raw()
}
//---------------------------------------------------------
// Export Gyroflow data:
//---------------------------------------------------------
let gyroflow_data: String;
match stab.export_gyroflow_data(gyroflow_core::GyroflowProjectType::WithGyroData, "{}", None) {
Ok(data) => {
gyroflow_data = data;
log::info!("[Gyroflow Toolbox Rust] Gyroflow data exported successfully");
},
Err(e) => {
log::error!("[Gyroflow Toolbox Rust] An error occured: {:?}", e);
gyroflow_data = "FAIL".to_string();
}
}
//---------------------------------------------------------
// Return Gyroflow Project data as string:
//---------------------------------------------------------
let result = CString::new(gyroflow_data).unwrap();
return result.into_raw()
},
Err(e) => {
//---------------------------------------------------------
// An error has occurred:
//---------------------------------------------------------
log::error!("[Gyroflow Toolbox Rust] Error importing Preset: {:?}", e);
let error_msg = format!("{}", e);
let result = CString::new(error_msg).unwrap();
return result.into_raw()
},
}
}
/// This function is called from Objective-C land and is responsible for clearing the cache.
///
/// # Returns
///
/// This function returns the size of the cache as a `u32`.
#[unsafe(no_mangle)]
pub extern "C" fn trashCache() -> u32 {
//---------------------------------------------------------
// Trash the Cache:
//---------------------------------------------------------
let mut cache = MANAGER_CACHE.lock().unwrap();
cache.clear();
//---------------------------------------------------------
// Return the Cache Size:
//---------------------------------------------------------
cache.len() as u32
}
/// The "Import Media File" function that gets triggered from Objective-C Land.
///
/// # Arguments
///
/// * `media_file_path` - A pointer to a C-style string containing the path to the media file.
///
/// # Returns
///
/// This function returns the Gyroflow Project as a string or "FAIL".
#[unsafe(no_mangle)]
pub extern "C" fn importMediaFile(
media_file_path: *const c_char,
) -> *const c_char {
//---------------------------------------------------------
// Convert the file path to a `&str`:
//---------------------------------------------------------
let media_file_path_pointer = unsafe { CStr::from_ptr(media_file_path) };
let media_file_path_string = media_file_path_pointer.to_string_lossy();
//log::info!("[Gyroflow Toolbox Rust] media_file_path_string: {:?}", media_file_path_string);
let mut stab = StabilizationManager::default();
{
//---------------------------------------------------------
// Find first lens profile database with loaded profiles:
//---------------------------------------------------------
let lock = MANAGER_CACHE.lock().unwrap();
for (_, v) in lock.iter() {
if v.lens_profile_db.read().loaded {
stab.lens_profile_db = v.lens_profile_db.clone();
break;
}
}
}
//---------------------------------------------------------
// Load video file:
//---------------------------------------------------------
match gyroflow_core::filesystem::open_file(&media_file_path_string, false, false) {
Ok(mut file) => {
let filesize = file.size;
match stab.load_video_file(file.get_file(), filesize, &media_file_path_string, None, true) {
Ok(_) => {
log::info!("[Gyroflow Toolbox Rust] Video file loaded successfully");
},
Err(e) => {
log::error!("[Gyroflow Toolbox Rust] An error occured: {:?}", e);
}
}
},
Err(e) => {
log::error!("[Gyroflow Toolbox Rust] Failed to open video file: {:?}", e);
}
}
//---------------------------------------------------------
// Export Gyroflow data:
//---------------------------------------------------------
let gyroflow_data: String;
match stab.export_gyroflow_data(gyroflow_core::GyroflowProjectType::WithGyroData, "{}", None) {
Ok(data) => {
gyroflow_data = data;
log::info!("[Gyroflow Toolbox Rust] Gyroflow data exported successfully");
},
Err(e) => {
log::error!("[Gyroflow Toolbox Rust] An error occured: {:?}", e);
gyroflow_data = "FAIL".to_string();
}
}
//---------------------------------------------------------
// Return Gyroflow Project data as string:
//---------------------------------------------------------
let result = CString::new(gyroflow_data).unwrap();
return result.into_raw()
}
/// This function is called from Objective-C land to process a video frame.
///
/// # Arguments
///
/// * `unique_identifier` - A pointer to a C-style string containing a unique identifier for the frame.
/// * `width` - The width of the video frame.
/// * `height` - The height of the video frame.
/// * `pixel_format` - A pointer to a C-style string containing the pixel format of the video frame.
/// * `number_of_bytes` - The number of bytes in the video frame.
/// * `path` - A pointer to a C-style string containing the path to the video frame.
/// * `data` - A pointer to a C-style string containing the video frame data.
/// * `timestamp` - The timestamp of the video frame.
/// * `fov` - The field of view of the video frame.
/// * `smoothness` - The smoothness of the video frame.
/// * `lens_correction` - The lens correction of the video frame.
/// * `horizon_lock` - The horizon lock of the video frame.
/// * `horizon_roll` - The horizon roll of the video frame.
/// * `position_offset_x` - The x position offset of the video frame.
/// * `position_offset_y` - The y position offset of the video frame.
/// * `input_rotation` - The input rotation of the video frame.
/// * `video_rotation` - The video rotation of the video frame.
/// * `fov_overview` - The field of view overview of the video frame.
/// * `disable_gyroflow_stretch` - Whether or not to disable Gyroflow stretch.
/// * `in_mtl_tex` - A pointer to the input Metal texture.
/// * `out_mtl_tex` - A pointer to the output Metal texture.
/// * `command_queue` - A pointer to the Metal command queue.
///
/// # Returns
///
/// This function returns 1 if successful, otherwise 0. If successful, the output Metal Texture is stored in `out_mtl_tex`.
#[unsafe(no_mangle)]
pub extern "C" fn processFrame(
unique_identifier: *const c_char,
width: u32,
height: u32,
pixel_format: *const c_char,
number_of_bytes: std::ffi::c_int,
path: *const c_char,
data: *const c_char,
timestamp: i64,
fov: f64,
smoothness: f64,
lens_correction: f64,
horizon_lock: f64,
horizon_roll: f64,
position_offset_x: f64,
position_offset_y: f64,
input_rotation: f64,
video_rotation: f64,
fov_overview: u8,
disable_gyroflow_stretch: u8,
in_mtl_tex: *mut std::ffi::c_void,
out_mtl_tex: *mut std::ffi::c_void,
command_queue: *mut std::ffi::c_void,
) -> std::ffi::c_int {
//---------------------------------------------------------
// Setting our NSLog Logger (only once):
//---------------------------------------------------------
static LOGGER: OnceCell<Mutex<Option<()>>> = OnceCell::new();
LOGGER.get_or_init(|| {
let logger = oslog::OsLogger::new("com.latenitefilms.GyroflowToolbox")
.level_filter(log::LevelFilter::Debug)
.category_level_filter("Settings", log::LevelFilter::Trace)
.init().ok();
Mutex::new(logger)
});
//---------------------------------------------------------
// Have parameters changed:
//---------------------------------------------------------
let mut params_changed = false;
let mut rotation_changed = false;
//---------------------------------------------------------
// Get the Unique Identifier:
//---------------------------------------------------------
let unique_identifier_pointer = unsafe { CStr::from_ptr(unique_identifier) };
let unique_identifier_string = unique_identifier_pointer.to_string_lossy();
//log::debug!("[Gyroflow Toolbox Rust] unique_identifier_string: {:?}", unique_identifier_string);
//---------------------------------------------------------
// Get Pixel Format:
//---------------------------------------------------------
let pixel_format_pointer = unsafe { CStr::from_ptr(pixel_format) };
let pixel_format_string = pixel_format_pointer.to_string_lossy();
// -------------------------------------------------------------------------------
// You can't use &str across FFI boundary, it's a Rust type.
// You have to use C-compatible char pointer, so path: *const c_char and then
// construct CStr from it https://doc.rust-lang.org/std/ffi/struct.CStr.html - CStr::from_ptr(path);
// and then get &str by calling .to_str().unwrap() or .to_string_lossy()
// -------------------------------------------------------------------------------
let path_pointer = unsafe { CStr::from_ptr(path) };
let path_string = path_pointer.to_string_lossy();
//---------------------------------------------------------
// Convert the output width and height to `usize`:
//---------------------------------------------------------
let output_width: usize = width as usize;
let output_height: usize = height as usize;
//---------------------------------------------------------
// Convert the number of bytes to `usize`:
//---------------------------------------------------------
let number_of_bytes_value: usize = number_of_bytes as usize;
//---------------------------------------------------------
// Cache the manager:
//---------------------------------------------------------
let mut cache = MANAGER_CACHE.lock().unwrap();
let cache_key = format!("{path_string}{output_width}{output_height}{pixel_format_string}{disable_gyroflow_stretch}{unique_identifier_string}");
let manager = if let Some(manager) = cache.get(&cache_key) {
//---------------------------------------------------------
// Already cached:
//---------------------------------------------------------
manager.clone()
} else {
//---------------------------------------------------------
// On first load, always Invalidate & Recompute:
//---------------------------------------------------------
params_changed = true;
//---------------------------------------------------------
// Setup the Gyroflow Manager:
//---------------------------------------------------------
let manager = StabilizationManager::default();
//---------------------------------------------------------
// Import the Gyroflow Data:
//---------------------------------------------------------
let data_slice: &[u8] = unsafe {
CStr::from_ptr(data).to_bytes()
};
let mut is_preset = false;
match manager.import_gyroflow_data(&data_slice, true, None, |_|(), Arc::new(AtomicBool::new(false)), &mut is_preset, true) {
Ok(_) => {
//---------------------------------------------------------
// Disable Gyroflow Stretch:
//---------------------------------------------------------
if disable_gyroflow_stretch != 0 {
// TODO: Do we need to expose this an an option?
manager.disable_lens_stretch(false);
}
//---------------------------------------------------------
// Set the Input Size:
//---------------------------------------------------------
manager.set_size(output_width, output_height);
//---------------------------------------------------------
// Set the Output Size:
//---------------------------------------------------------
manager.set_output_size(output_width, output_height);
//---------------------------------------------------------
// Invert the Frame Buffer:
//---------------------------------------------------------
manager.params.write().framebuffer_inverted = true;
//---------------------------------------------------------