forked from helgoboss/reaper-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reaper.rs
8029 lines (7632 loc) · 250 KB
/
reaper.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
use std::ffi::CString;
use std::os::raw::{c_char, c_void};
use std::ptr::{null, null_mut, NonNull};
use reaper_low::{raw, register_plugin_destroy_hook};
use crate::ProjectContext::CurrentProject;
use crate::{
require_non_null_panic, Accel, ActionValueChange, AddFxBehavior, AudioDeviceAttributeKey,
AutoSeekBehavior, AutomationMode, BookmarkId, BookmarkRef, Bpm, CcShapeKind, ChunkCacheHint,
CommandId, Db, DurationInSeconds, EditMode, EnvChunkName, FxAddByNameBehavior,
FxChainVisibility, FxPresetRef, FxShowInstruction, GangBehavior, GlobalAutomationModeOverride,
HelpMode, Hidden, Hwnd, InitialAction, InputMonitoringMode, InsertMediaFlag, InsertMediaMode,
KbdSectionInfo, MasterTrackBehavior, MeasureMode, MediaItem, MediaItemTake, MediaTrack,
MessageBoxResult, MessageBoxType, MidiImportBehavior, MidiInput, MidiInputDeviceId, MidiOutput,
MidiOutputDeviceId, NativeColor, NormalizedPlayRate, NotificationBehavior, OwnedPcmSource,
OwnedReaperPitchShift, OwnedReaperResample, PanMode, ParamId, PcmSource, PitchShiftMode,
PitchShiftSubMode, PlaybackSpeedFactor, PluginContext, PositionInBeats, PositionInPpq,
PositionInQuarterNotes, PositionInSeconds, Progress, ProjectContext, ProjectRef,
PromptForActionResult, ReaProject, ReaperFunctionError, ReaperFunctionResult,
ReaperNormalizedFxParamValue, ReaperPanLikeValue, ReaperPanValue, ReaperPointer, ReaperStr,
ReaperString, ReaperStringArg, ReaperVersion, ReaperVolumeValue, ReaperWidthValue,
RecordArmMode, RecordingInput, RequiredViewMode, ResampleMode, SectionContext, SectionId,
SendTarget, SetTrackUiFlags, SoloMode, SourceMidiEvent, SourceMidiEventBuilder,
SourceMidiEventConsumer, SourceMidiMessage, StuffMidiMessageTarget, TakeAttributeKey,
TimeModeOverride, TimeRangeType, TrackArea, TrackAttributeKey, TrackDefaultsBehavior,
TrackEnvelope, TrackFxChainType, TrackFxLocation, TrackLocation, TrackMuteOperation,
TrackPolarityOperation, TrackRecArmOperation, TrackSendAttributeKey, TrackSendCategory,
TrackSendDirection, TrackSendRef, TrackSoloOperation, TransferBehavior, UiRefreshBehavior,
UndoBehavior, UndoScope, ValueChange, VolumeSliderValue, WindowContext,
};
use helgoboss_midi::{
Channel, ControllerNumber, RawShortMessage, ShortMessage, ShortMessageFactory,
ShortMessageType, U7,
};
use reaper_low::raw::GUID;
use crate::util::{
create_passing_c_str, with_buffer, with_string_buffer, with_string_buffer_prefilled,
};
use enumflags2::BitFlags;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
/// Represents a privilege to execute functions which are safe to execute from any thread.
pub trait AnyThread: private::Sealed {}
/// Represents a privilege to execute functions which are only safe to execute from the main thread.
pub trait MainThreadOnly: AnyThread + private::Sealed {}
/// Represents a privilege to execute functions which are only safe to execute from the real-time
/// audio thread.
pub trait AudioThreadOnly: AnyThread + private::Sealed {}
/// A usage scope which unlocks all functions that are safe to execute from the main thread.
#[derive(Copy, Clone, Debug, Default)]
pub struct MainThreadScope(pub(crate) ());
impl MainThreadOnly for MainThreadScope {}
impl AnyThread for MainThreadScope {}
/// A usage scope which unlocks all functions that are safe to execute from the real-time audio
/// thread.
#[derive(Copy, Clone, Debug, Default)]
pub struct RealTimeAudioThreadScope(pub(crate) ());
impl AudioThreadOnly for RealTimeAudioThreadScope {}
impl AnyThread for RealTimeAudioThreadScope {}
/// This is the main access point for most REAPER functions.
///
/// # Basics
///
/// You can obtain an instance of this struct by calling [`ReaperSession::reaper()`]. This
/// unlocks all functions which are safe to execute in the main thread. If you want access to the
/// functions which are safe to execute in the real-time audio thread, call
/// [`ReaperSession::create_real_time_reaper()`] instead. REAPER functions which are related to
/// registering/unregistering things are located in [`ReaperSession`].
///
/// Please note that this struct contains nothing but function pointers, so you are free to clone
/// it, e.g. in order to make all functions accessible somewhere else. This is sometimes easier than
/// passing references around. Don't do it too often though. It's just a bitwise copy of all
/// function pointers, but there are around 800 of them, so each copy will occupy about 7 kB of
/// memory on a 64-bit system.
///
/// # Panics
///
/// Don't assume that all REAPER functions exposed here are always available. It's possible that the
/// user runs your plug-in in an older version of REAPER where a function is missing. See the
/// documentation of [low-level `Reaper`] for ways how to deal with this.
///
/// # Work in progress
///
/// Many functions which are available in the low-level API have not been lifted to the medium-level
/// API yet. Unlike the low-level API, the medium-level one is hand-written and probably a perpetual
/// work in progress. If you can't find the function that you need, you can always resort to the
/// low-level API by navigating to [`low()`]. Of course you are welcome to contribute to bring the
/// medium-level API on par with the low-level one.
///
/// # Design
///
/// ## What's the `<MainThreadScope>` in `Reaper<MainThreadScope>` about?
///
/// In REAPER and probably many other DAWs there are at least two important threads:
///
/// 1. The main thread (responsible for things like UI, driven by the UI main loop).
/// 2. The real-time audio thread (responsible for processing audio and MIDI buffers, driven by the
/// audio hardware)
///
/// Most functions offered by REAPER are only safe to be executed in the main thread. If you execute
/// them in another thread, REAPER will crash. Or worse: It will seemingly work on your machine
/// and crash on someone else's. There are also a few functions which are only safe to be executed
/// in the audio thread. And there are also very few functions which are safe to be executed from
/// *any* thread (thread-safe).
///
/// There's currently no way to make sure at compile time that a function is called in the correct
/// thread. Of course that would be the best. In an attempt to still let the compiler help you a
/// bit, the traits [`MainThreadOnly`] and [`RealTimeAudioThreadOnly`] have been introduced. They
/// are marker traits which are used as type bound on each method which is not thread-safe. So
/// depending on the context we can expose an instance of [`Reaper`] which has only
/// functions unlocked which are safe to be executed from e.g. the real-time audio thread. The
/// compiler will complain if you attempt to call a real-time-audio-thread-only method on
/// `Reaper<MainThreadScope>` and vice versa.
///
/// Of course that technique can't prevent anyone from acquiring a main-thread only instance and
/// use it in the audio hook. But still, it adds some extra safety.
///
/// The alternative to tagging functions via marker traits would have been to implement e.g.
/// audio-thread-only functions in a trait `CallableFromRealTimeAudioThread` as default functions
/// and create a struct that inherits those default functions. Disadvantage: Consumer always would
/// have to bring the trait into scope to see the functions. That's confusing. It also would provide
/// less amount of safety.
///
/// ## Why no fail-fast at runtime when calling audio-thread-only functions from wrong thread?
///
/// At the moment, there's a fail fast (panic) when attempting to execute main-thread-only functions
/// from the wrong thread. This prevents "it works on my machine" scenarios. However, this is
/// currently not being done the other way around (when executing real-time-audio-thread-only
/// functions from the wrong thread) because of possible performance implications. Latter scenario
/// should also be much more unlikely. Maybe we can introduce it in future in order to really avoid
/// undefined behavior even for those methods (which the lack of `unsafe` suggests). Checking the
/// thread ID is a very cheap operation (a few nano seconds), maybe even in the real-time audio
/// thread.
///
/// [`ReaperSession`]: struct.ReaperSession.html
/// [`ReaperSession::reaper()`]: struct.ReaperSession.html#method.reaper
/// [`ReaperSession::create_real_time_reaper()`]:
/// struct.ReaperSession.html#method.create_real_time_reaper
/// [`low()`]: #method.low
/// [low-level `Reaper`]: https://docs.rs/reaper-low
/// [`MainThreadOnly`]: trait.MainThreadOnly.html
/// [`RealTimeAudioThreadOnly`]: trait.RealTimeAudioThreadOnly.html
/// [`Reaper`]: struct.Reaper.html
#[derive(Debug, Default)]
pub struct Reaper<UsageScope = MainThreadScope> {
low: reaper_low::Reaper,
p: PhantomData<UsageScope>,
}
impl<UsageScope> Clone for Reaper<UsageScope> {
fn clone(&self) -> Self {
Self {
low: self.low,
p: Default::default(),
}
}
}
// This is safe (see https://doc.rust-lang.org/std/sync/struct.Once.html#examples-1).
static mut INSTANCE: Option<Reaper<MainThreadScope>> = None;
impl Reaper<MainThreadScope> {
/// Makes the given instance available globally.
///
/// After this has been called, the instance can be queried globally using `get()`.
///
/// This can be called once only. Subsequent calls won't have any effect!
pub fn make_available_globally(reaper: Reaper<MainThreadScope>) {
static INIT_INSTANCE: std::sync::Once = std::sync::Once::new();
unsafe {
INIT_INSTANCE.call_once(|| {
INSTANCE = Some(reaper);
register_plugin_destroy_hook(|| INSTANCE = None);
});
}
}
/// Gives access to the instance which you made available globally before.
///
/// # Panics
///
/// This panics if [`make_available_globally()`] has not been called before.
///
/// [`make_available_globally()`]: fn.make_available_globally.html
pub fn get() -> &'static Reaper<MainThreadScope> {
unsafe {
INSTANCE
.as_ref()
.expect("call `make_available_globally()` before using `get()`")
}
}
}
impl<UsageScope> Reaper<UsageScope> {
pub(crate) fn new(low: reaper_low::Reaper) -> Reaper<UsageScope> {
Reaper {
low,
p: PhantomData,
}
}
/// Gives access to the low-level Reaper instance.
pub fn low(&self) -> &reaper_low::Reaper {
&self.low
}
/// Returns the plug-in context.
pub fn plugin_context(&self) -> PluginContext<UsageScope> {
PluginContext::new(self.low.plugin_context())
}
/// Returns the requested project and optionally its file name.
///
/// With `buffer_size` you can tell REAPER how many bytes of the file name you want. If you
/// are not interested in the file name at all, pass 0.
///
/// # Threading
///
/// If `buffer_size > 0`, this must be called from the main thread (panics if not).
///
/// If `buffer_size == 0`, this may also be called from a real-time or worker thread, not from
/// your own thread (this won't be checked!)
///
/// # Example
///
/// ```no_run
/// # let session = reaper_medium::ReaperSession::default();
/// use reaper_medium::ProjectRef::Tab;
///
/// let result = session.reaper().enum_projects(Tab(4), 256).ok_or("No such tab")?;
/// let project_dir = result.file_path.ok_or("Project not saved yet")?.parent();
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn enum_projects(
&self,
project_ref: ProjectRef,
buffer_size: u32,
) -> Option<EnumProjectsResult>
where
UsageScope: AnyThread,
{
if buffer_size > 0 {
assert!(
self.low.plugin_context().is_in_main_thread(),
"enum_projects must only be called from main thread if buffer_size > 0"
);
}
let idx = project_ref.to_raw();
if buffer_size == 0 {
let ptr = unsafe { self.low.EnumProjects(idx, null_mut(), 0) };
let project = NonNull::new(ptr)?;
Some(EnumProjectsResult {
project,
file_path: None,
})
} else {
let (reaper_string, ptr) = with_string_buffer(buffer_size, |buffer, max_size| unsafe {
self.low.EnumProjects(idx, buffer, max_size)
});
let project = NonNull::new(ptr)?;
if reaper_string.is_empty() {
return Some(EnumProjectsResult {
project,
file_path: None,
});
}
let owned_string = reaper_string.into_string();
Some(EnumProjectsResult {
project,
file_path: Some(PathBuf::from(owned_string)),
})
}
}
/// Returns the track at the given index.
///
/// # Panics
///
/// Panics if the given project is not valid anymore.
///
/// # Example
///
/// ```no_run
/// # let session = reaper_medium::ReaperSession::default();
/// use reaper_medium::ProjectContext::CurrentProject;
///
/// let track = session.reaper().get_track(CurrentProject, 3).ok_or("No such track")?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn get_track(&self, project: ProjectContext, track_index: u32) -> Option<MediaTrack>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.require_valid_project(project);
unsafe { self.get_track_unchecked(project, track_index) }
}
/// Like [`get_track()`] but doesn't check if project is valid.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid project.
///
/// [`get_track()`]: #method.get_track
pub unsafe fn get_track_unchecked(
&self,
project: ProjectContext,
track_index: u32,
) -> Option<MediaTrack>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.low.GetTrack(project.to_raw(), track_index as i32);
NonNull::new(ptr)
}
/// Returns the item at the given index.
///
/// # Panics
///
/// Panics if the given project is not valid anymore.
pub fn get_media_item(&self, project: ProjectContext, item_index: u32) -> Option<MediaItem>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.require_valid_project(project);
unsafe { self.get_media_item_unchecked(project, item_index) }
}
/// Like [`get_media_item()`] but doesn't check if project is valid.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid project.
///
/// [`get_media_item()`]: #method.get_media_item
pub unsafe fn get_media_item_unchecked(
&self,
project: ProjectContext,
item_index: u32,
) -> Option<MediaItem>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.low.GetMediaItem(project.to_raw(), item_index as i32);
NonNull::new(ptr)
}
/// Checks if the given pointer is still valid.
///
/// # Example
///
/// ```no_run
/// # let session = reaper_medium::ReaperSession::default();
/// use reaper_medium::ProjectContext::CurrentProject;
///
/// let track = session.reaper().get_track(CurrentProject, 0).ok_or("No track")?;
/// let track_is_valid = session.reaper().validate_ptr_2(CurrentProject, track);
/// assert!(track_is_valid);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
///
/// Returns `true` if the pointer is a valid object of the correct type in the given project.
/// The project is ignored if the pointer itself is a project.
pub fn validate_ptr_2<'a>(
&self,
project: ProjectContext,
pointer: impl Into<ReaperPointer<'a>>,
) -> bool
where
UsageScope: AnyThread,
{
let pointer = pointer.into();
unsafe {
self.low.ValidatePtr2(
project.to_raw(),
pointer.ptr_as_void(),
pointer.key_into_raw().as_ptr(),
)
}
}
/// Checks if the given pointer is still valid.
///
/// Returns `true` if the pointer is a valid object of the correct type in the current project.
pub fn validate_ptr<'a>(&self, pointer: impl Into<ReaperPointer<'a>>) -> bool
where
UsageScope: AnyThread,
{
let pointer = pointer.into();
unsafe {
self.low
.ValidatePtr(pointer.ptr_as_void(), pointer.key_into_raw().as_ptr())
}
}
/// Redraws the arrange view and ruler.
pub fn update_timeline(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.UpdateTimeline();
}
/// Redraws the arrange view.
pub fn update_arrange(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.UpdateArrange();
}
/// Updates the track list after a minor change.
pub fn track_list_adjust_windows_minor(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.TrackList_AdjustWindows(true);
}
/// Updates the track list after a major change.
pub fn track_list_adjust_windows_major(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.TrackList_AdjustWindows(false);
}
/// Shows a message to the user in the ReaScript console.
///
/// This is also useful for debugging. Send "\n" for newline and "" to clear the console.
pub fn show_console_msg<'a>(&self, message: impl Into<ReaperStringArg<'a>>)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
unsafe { self.low.ShowConsoleMsg(message.into().as_ptr()) }
}
/// Gets or sets a track attribute.
///
/// Returns the current value if `new_value` is `null_mut()`.
///
/// It's recommended to use one of the convenience functions instead. They all start with
/// `get_set_media_track_info_` and are more type-safe.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track or invalid new value.
pub unsafe fn get_set_media_track_info(
&self,
track: MediaTrack,
attribute_key: TrackAttributeKey,
new_value: *mut c_void,
) -> *mut c_void
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low
.GetSetMediaTrackInfo(track.as_ptr(), attribute_key.into_raw().as_ptr(), new_value)
}
/// Gets or sets a take attribute.
///
/// Returns the current value if `new_value` is `null_mut()`.
///
/// It's recommended to use one of the convenience functions instead. They all start with
/// `get_set_media_item_take_info_` and are more type-safe.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid take or invalid new value.
pub unsafe fn get_set_media_item_take_info(
&self,
take: MediaItemTake,
attribute_key: TakeAttributeKey,
new_value: *mut c_void,
) -> *mut c_void
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.GetSetMediaItemTakeInfo(
take.as_ptr(),
attribute_key.into_raw().as_ptr(),
new_value,
)
}
/// Sets a take attribute as numerical value.
///
/// # Errors
///
/// Returns an error if an invalid (e.g. non-numerical) track attribute key is passed.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn set_media_item_take_info_value(
&self,
take: MediaItemTake,
attribute_key: TakeAttributeKey,
new_value: f64,
) -> ReaperFunctionResult<()>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let successful = self.low.SetMediaItemTakeInfo_Value(
take.as_ptr(),
attribute_key.into_raw().as_ptr(),
new_value,
);
if !successful {
return Err(ReaperFunctionError::new(
"couldn't set take attribute (maybe attribute key is invalid)",
));
}
Ok(())
}
/// Convenience function which sets the take's source (`P_SOURCE`).
///
/// Returns the previous source in case the take had a source assigned.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid take.
pub unsafe fn get_set_media_item_take_info_set_source(
&self,
take: MediaItemTake,
source: OwnedPcmSource,
) -> Option<OwnedPcmSource>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let previous_source_ptr =
self.get_set_media_item_take_info(take, TakeAttributeKey::Source, null_mut())
as *mut raw::PCM_source;
let new_source_ptr = source.leak().as_ptr();
self.get_set_media_item_take_info(take, TakeAttributeKey::Source, new_source_ptr as _);
NonNull::new(previous_source_ptr).map(|raw| OwnedPcmSource::from_raw(raw))
}
/// Convenience function which returns the given track's parent track (`P_PARTRACK`).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_par_track(
&self,
track: MediaTrack,
) -> Option<MediaTrack>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::ParTrack, null_mut())
as *mut raw::MediaTrack;
NonNull::new(ptr)
}
/// Convenience function which returns the given track's parent project (`P_PROJECT`).
///
/// In REAPER < 5.95 this returns `None`.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_project(
&self,
track: MediaTrack,
) -> Option<ReaProject>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::Project, null_mut())
as *mut raw::ReaProject;
NonNull::new(ptr)
}
/// Convenience function which grants temporary access to the given track's name (`P_NAME`).
///
/// Returns `None` if the given track is the master track.
///
/// # Example
///
/// ```no_run
/// # use reaper_medium::ProjectContext::CurrentProject;
/// let session = reaper_medium::ReaperSession::default();
///
/// let track = session.reaper().get_track(CurrentProject, 0).ok_or("no track")?;
/// let track_name = unsafe {
/// session.reaper().get_set_media_track_info_get_name(
/// track,
/// |name| name.to_owned()
/// )
/// };
/// let track_name = match &track_name {
/// None => "Master track",
/// Some(name) => name.to_str()
/// };
/// session.reaper().show_console_msg(format!("Track name is {}", track_name));
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_name<R>(
&self,
track: MediaTrack,
use_name: impl FnOnce(&ReaperStr) -> R,
) -> Option<R>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::Name, null_mut());
create_passing_c_str(ptr as *const c_char).map(use_name)
}
/// Convenience function which sets the track's name (`P_NAME`).
///
/// # Example
///
/// ```no_run
/// # use reaper_medium::ProjectContext::CurrentProject;
/// let session = reaper_medium::ReaperSession::default();
///
/// let track = session.reaper().get_track(CurrentProject, 0).ok_or("no track")?;
/// unsafe {
/// session.reaper().get_set_media_track_info_set_name(track, "Guitar");
/// }
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_set_name<'a>(
&self,
track: MediaTrack,
message: impl Into<ReaperStringArg<'a>>,
) where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.get_set_media_track_info(track, TrackAttributeKey::Name, message.into().as_ptr() as _);
}
/// Convenience function which returns the given track's input monitoring mode (`I_RECMON`).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_rec_mon(
&self,
track: MediaTrack,
) -> InputMonitoringMode
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::RecMon, null_mut());
let irecmon = deref_as::<i32>(ptr).expect("I_RECMON pointer is null");
InputMonitoringMode::from_raw(irecmon)
}
/// Convenience function which returns the given track's solo mode (`I_SOLO`).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_solo(&self, track: MediaTrack) -> SoloMode
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::Solo, null_mut());
let isolo = deref_as::<i32>(ptr).expect("I_SOLO pointer is null");
SoloMode::from_raw(isolo)
}
/// Convenience function which sets the track's solo state (`I_SOLO`).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_set_solo(&self, track: MediaTrack, mode: SoloMode)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let value = mode.to_raw();
self.get_set_media_track_info(track, TrackAttributeKey::Solo, &value as *const _ as _);
}
/// Convenience function which sets whether the track is shown in the mixer (`B_SHOWINMIXER`).
///
/// Do not use on master track.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_set_show_in_mixer(&self, track: MediaTrack, show: bool)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.get_set_media_track_info(
track,
TrackAttributeKey::ShowInMixer,
&show as *const _ as _,
);
}
/// Convenience function which sets whether the track is shown in the arrange view (`B_SHOWINTCP`).
///
/// Do not use on master track.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_set_show_in_tcp(&self, track: MediaTrack, show: bool)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.get_set_media_track_info(track, TrackAttributeKey::ShowInTcp, &show as *const _ as _);
}
/// Convenience function which returns the given track's pan mode (I_PANMODE).
///
/// Returns `None` if the track uses the project default.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_pan_mode(&self, track: MediaTrack) -> Option<PanMode>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::PanMode, null_mut());
let ipanmode = deref_as::<i32>(ptr).expect("I_PANMODE pointer is null");
if ipanmode == -1 {
return None;
}
Some(PanMode::from_raw(ipanmode))
}
/// Convenience function which returns the given track's pan (D_PAN).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_pan(&self, track: MediaTrack) -> ReaperPanValue
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::Pan, null_mut());
let pan = deref_as::<f64>(ptr).expect("I_PAN pointer is null");
ReaperPanValue::new(pan)
}
/// Convenience function which returns the given track's dual-pan position 1 (D_DUALPANL).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_dual_pan_l(
&self,
track: MediaTrack,
) -> ReaperPanValue
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::DualPanL, null_mut());
let pan = deref_as::<f64>(ptr).expect("D_DUALPANL pointer is null");
ReaperPanValue::new(pan)
}
/// Convenience function which returns the given track's dual-pan position 2 (D_DUALPANR).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_dual_pan_r(
&self,
track: MediaTrack,
) -> ReaperPanValue
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::DualPanR, null_mut());
let pan = deref_as::<f64>(ptr).expect("D_DUALPANR pointer is null");
ReaperPanValue::new(pan)
}
/// Convenience function which returns the given track's width (D_WIDTH).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_width(&self, track: MediaTrack) -> ReaperWidthValue
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::Width, null_mut());
let width = deref_as::<f64>(ptr).expect("I_WIDTH pointer is null");
ReaperWidthValue::new(width)
}
/// Convenience function which returns the given track's recording input (I_RECINPUT).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_rec_input(
&self,
track: MediaTrack,
) -> Option<RecordingInput>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::RecInput, null_mut());
let rec_input_index = deref_as::<i32>(ptr).expect("rec_input_index pointer is null");
RecordingInput::from_raw(rec_input_index)
}
/// Convenience function which returns the type and location of the given track
/// (IP_TRACKNUMBER).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_track_number(
&self,
track: MediaTrack,
) -> Option<TrackLocation>
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
use TrackLocation::*;
match self.get_set_media_track_info(track, TrackAttributeKey::TrackNumber, null_mut())
as i32
{
-1 => Some(MasterTrack),
0 => None,
n if n > 0 => Some(NormalTrack(n as u32 - 1)),
_ => unreachable!(),
}
}
/// Convenience function which returns the given track's GUID (GUID).
///
/// # Safety
///
/// REAPER can crash if you pass an invalid track.
pub unsafe fn get_set_media_track_info_get_guid(&self, track: MediaTrack) -> GUID
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
let ptr = self.get_set_media_track_info(track, TrackAttributeKey::Guid, null_mut());
deref_as::<GUID>(ptr).expect("GUID pointer is null")
}
/// Returns whether we are in the real-time audio thread.
///
/// *Real-time* means somewhere between [`OnAudioBuffer`] calls, not in some worker or
/// anticipative FX thread.
///
/// [`OnAudioBuffer`]: trait.OnAudioBuffer.html#method.call
pub fn is_in_real_time_audio(&self) -> bool
where
UsageScope: AnyThread,
{
self.low.IsInRealTimeAudio() != 0
}
/// Returns whether audio is running at all.
pub fn audio_is_running(&self) -> bool
where
UsageScope: AnyThread,
{
self.low.Audio_IsRunning() != 0
}
/// Starts playing.
pub fn csurf_on_play(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.CSurf_OnPlay();
}
/// Stops playing.
pub fn csurf_on_stop(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.CSurf_OnStop();
}
/// Pauses playing.
pub fn csurf_on_pause(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.CSurf_OnPause();
}
/// Starts recording.
pub fn csurf_on_record(&self)
where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low.CSurf_OnRecord();
}
/// Informs control surfaces that the repeat mode has changed.
///
/// Doesn't actually change the repeat mode.
///
/// # Safety
///
/// REAPER can crash if you pass an invalid control surface.
///
/// # Example
///
/// ```no_run
/// # let session = reaper_medium::ReaperSession::default();
/// use reaper_medium::{NotificationBehavior::NotifyAll, ProjectContext::CurrentProject};
///
/// let track = session.reaper().get_track(CurrentProject, 0).ok_or("no tracks")?;
/// unsafe {
/// session.reaper().csurf_set_repeat_state(true, NotifyAll);
/// }
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub unsafe fn csurf_set_repeat_state(
&self,
repeat_state: bool,
notification_behavior: NotificationBehavior,
) where
UsageScope: MainThreadOnly,
{
self.require_main_thread();
self.low
.CSurf_SetRepeatState(repeat_state, notification_behavior.to_raw());
}
/// Returns `true` if any track in the given project is soloed.
///
/// # Panics
///
/// Panics if the given project is not valid anymore.
pub fn any_track_solo(&self, project: ProjectContext) -> bool
where
UsageScope: MainThreadOnly,
{
self.require_valid_project(project);
unsafe { self.any_track_solo_unchecked(project) }