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
#![allow(non_upper_case_globals)]

use paste::item;

pub mod audio;
pub mod context;
mod ffi;
pub mod media;
pub mod traits;
pub mod video;

pub use context::*;
pub use media::*;
pub use traits::*;

use obs_sys::{
    obs_filter_get_target, obs_source_active, obs_source_enabled, obs_source_get_base_height,
    obs_source_get_base_width, obs_source_get_height, obs_source_get_id, obs_source_get_name,
    obs_source_get_type, obs_source_get_width, obs_source_info, obs_source_media_ended,
    obs_source_media_get_duration, obs_source_media_get_state, obs_source_media_get_time,
    obs_source_media_next, obs_source_media_play_pause, obs_source_media_previous,
    obs_source_media_restart, obs_source_media_set_time, obs_source_media_started,
    obs_source_media_stop, obs_source_process_filter_begin, obs_source_process_filter_end,
    obs_source_process_filter_tech_end, obs_source_set_enabled, obs_source_set_name,
    obs_source_showing, obs_source_skip_video_filter, obs_source_t, obs_source_type,
    obs_source_type_OBS_SOURCE_TYPE_FILTER, obs_source_type_OBS_SOURCE_TYPE_INPUT,
    obs_source_type_OBS_SOURCE_TYPE_SCENE, obs_source_type_OBS_SOURCE_TYPE_TRANSITION,
    obs_source_update, OBS_SOURCE_AUDIO, OBS_SOURCE_CONTROLLABLE_MEDIA, OBS_SOURCE_VIDEO, obs_source_get_ref, obs_source_release,
};

use super::{
    graphics::{
        GraphicsAllowDirectRendering, GraphicsColorFormat, GraphicsEffect, GraphicsEffectContext,
    },
    string::ObsString,
};
use crate::{data::DataObj, wrapper::PtrWrapper};

use std::{
    ffi::{CStr, CString},
    marker::PhantomData,
};

/// OBS source type
///
/// See [OBS documentation](https://obsproject.com/docs/reference-sources.html#c.obs_source_get_type)
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SourceType {
    INPUT,
    SCENE,
    FILTER,
    TRANSITION,
}

impl SourceType {
    pub(crate) fn from_native(source_type: obs_source_type) -> Option<SourceType> {
        match source_type {
            obs_source_type_OBS_SOURCE_TYPE_INPUT => Some(SourceType::INPUT),
            obs_source_type_OBS_SOURCE_TYPE_SCENE => Some(SourceType::SCENE),
            obs_source_type_OBS_SOURCE_TYPE_FILTER => Some(SourceType::FILTER),
            obs_source_type_OBS_SOURCE_TYPE_TRANSITION => Some(SourceType::TRANSITION),
            _ => None,
        }
    }

    pub(crate) fn to_native(self) -> obs_source_type {
        match self {
            SourceType::INPUT => obs_source_type_OBS_SOURCE_TYPE_INPUT,
            SourceType::SCENE => obs_source_type_OBS_SOURCE_TYPE_SCENE,
            SourceType::FILTER => obs_source_type_OBS_SOURCE_TYPE_FILTER,
            SourceType::TRANSITION => obs_source_type_OBS_SOURCE_TYPE_TRANSITION,
        }
    }
}

/// Context wrapping an OBS source - video / audio elements which are displayed to the screen.
///
/// See [OBS documentation](https://obsproject.com/docs/reference-sources.html#c.obs_source_t)
pub struct SourceContext {
    inner: *mut obs_source_t,
}

impl SourceContext {
    pub fn from_raw(source: *mut obs_source_t) -> Self {
        Self {
            inner: unsafe { obs_source_get_ref(source) }
        }
    }
}

impl Clone for SourceContext {
    fn clone(&self) -> Self {
        Self::from_raw(self.inner)
    }
}

impl Drop for SourceContext {
    fn drop(&mut self) {
        unsafe {
            obs_source_release(self.inner)
        }
    }
}

impl SourceContext {
    /// Run a function on the next source in the filter chain.
    ///
    /// Note: only works with sources that are filters.
    pub fn do_with_target<F: FnOnce(&mut SourceContext)>(&mut self, func: F) {
        unsafe {
            if let Some(SourceType::FILTER) =
                SourceType::from_native(obs_source_get_type(self.inner))
            {
                let target = obs_filter_get_target(self.inner);
                let mut context = SourceContext::from_raw(target);
                func(&mut context);
            }
        }
    }

    /// Return a unique id for the filter
    pub fn id(&self) -> usize {
        self.inner as usize
    }

    pub fn get_base_width(&self) -> u32 {
        unsafe { obs_source_get_base_width(self.inner) }
    }

    pub fn get_base_height(&self) -> u32 {
        unsafe { obs_source_get_base_height(self.inner) }
    }

    pub fn showing(&self) -> bool {
        unsafe { obs_source_showing(self.inner) }
    }

    pub fn active(&self) -> bool {
        unsafe { obs_source_active(self.inner) }
    }

    pub fn enabled(&self) -> bool {
        unsafe { obs_source_enabled(self.inner) }
    }

    pub fn set_enabled(&mut self, enabled: bool) {
        unsafe { obs_source_set_enabled(self.inner, enabled) }
    }

    pub fn source_id(&self) -> Option<&str> {
        unsafe {
            let ptr = obs_source_get_id(self.inner);
            if ptr.is_null() {
                None
            } else {
                Some(CStr::from_ptr(ptr).to_str().unwrap())
            }
        }
    }

    pub fn name(&self) -> Option<&str> {
        unsafe {
            let ptr = obs_source_get_name(self.inner);
            if ptr.is_null() {
                None
            } else {
                Some(CStr::from_ptr(ptr).to_str().unwrap())
            }
        }
    }

    pub fn set_name(&mut self, name: &str) {
        let cstr = CString::new(name).unwrap();
        unsafe {
            obs_source_set_name(self.inner, cstr.as_ptr());
        }
    }

    pub fn width(&self) -> u32 {
        unsafe { obs_source_get_width(self.inner) }
    }

    pub fn height(&self) -> u32 {
        unsafe { obs_source_get_height(self.inner) }
    }

    pub fn media_play_pause(&mut self, pause: bool) {
        unsafe {
            obs_source_media_play_pause(self.inner, pause);
        }
    }

    pub fn media_restart(&mut self) {
        unsafe {
            obs_source_media_restart(self.inner);
        }
    }

    pub fn media_stop(&mut self) {
        unsafe {
            obs_source_media_stop(self.inner);
        }
    }

    pub fn media_next(&mut self) {
        unsafe {
            obs_source_media_next(self.inner);
        }
    }

    pub fn media_previous(&mut self) {
        unsafe {
            obs_source_media_previous(self.inner);
        }
    }

    pub fn media_duration(&self) -> i64 {
        unsafe { obs_source_media_get_duration(self.inner) }
    }

    pub fn media_time(&self) -> i64 {
        unsafe { obs_source_media_get_time(self.inner) }
    }

    pub fn media_set_time(&mut self, ms: i64) {
        unsafe { obs_source_media_set_time(self.inner, ms) }
    }

    pub fn media_state(&self) -> MediaState {
        let ret = unsafe { obs_source_media_get_state(self.inner) };
        MediaState::from_native(ret).expect("Invalid media state value")
    }

    pub fn media_started(&mut self) {
        unsafe {
            obs_source_media_started(self.inner);
        }
    }

    pub fn media_ended(&mut self) {
        unsafe {
            obs_source_media_ended(self.inner);
        }
    }

    /// Skips the video filter if it's invalid
    pub fn skip_video_filter(&mut self) {
        unsafe {
            obs_source_skip_video_filter(self.inner);
        }
    }

    /// Run a function to do drawing - if the source is a filter.
    /// This function is wrapped by calls that automatically handle effect-based filter processing.
    ///
    /// See [OBS documentation](https://obsproject.com/docs/reference-sources.html#c.obs_source_process_filter_begin)
    ///
    /// Note: only works with sources that are filters.
    pub fn process_filter<F: FnOnce(&mut GraphicsEffectContext, &mut GraphicsEffect)>(
        &mut self,
        _render: &mut VideoRenderContext,
        effect: &mut GraphicsEffect,
        (cx, cy): (u32, u32),
        format: GraphicsColorFormat,
        direct: GraphicsAllowDirectRendering,
        func: F,
    ) {
        unsafe {
            if let Some(SourceType::FILTER) =
                SourceType::from_native(obs_source_get_type(self.inner))
            {
                if obs_source_process_filter_begin(self.inner, format.as_raw(), direct.as_raw()) {
                    let mut context = GraphicsEffectContext::new();
                    func(&mut context, effect);
                    obs_source_process_filter_end(self.inner, effect.as_ptr(), cx, cy);
                }
            }
        }
    }

    pub fn process_filter_tech<F: FnOnce(&mut GraphicsEffectContext, &mut GraphicsEffect)>(
        &mut self,
        _render: &mut VideoRenderContext,
        effect: &mut GraphicsEffect,
        (cx, cy): (u32, u32),
        format: GraphicsColorFormat,
        direct: GraphicsAllowDirectRendering,
        technique: ObsString,
        func: F,
    ) {
        unsafe {
            if let Some(SourceType::FILTER) =
                SourceType::from_native(obs_source_get_type(self.inner))
            {
                if obs_source_process_filter_begin(self.inner, format.as_raw(), direct.as_raw()) {
                    let mut context = GraphicsEffectContext::new();
                    func(&mut context, effect);
                    obs_source_process_filter_tech_end(
                        self.inner,
                        effect.as_ptr(),
                        cx,
                        cy,
                        technique.as_ptr(),
                    );
                }
            }
        }
    }

    /// Update the source settings based on a settings context.
    pub fn update_source_settings(&mut self, settings: &mut DataObj) {
        unsafe {
            obs_source_update(self.inner, settings.as_ptr_mut());
        }
    }
}

pub struct EnumActiveContext {}

pub struct EnumAllContext {}

pub struct SourceInfo {
    info: Box<obs_source_info>,
}

impl SourceInfo {
    /// # Safety
    /// Creates a raw pointer from a box and could cause UB is misused.
    pub unsafe fn into_raw(self) -> *mut obs_source_info {
        Box::into_raw(self.info)
    }
}

impl AsRef<obs_source_info> for SourceInfo {
    fn as_ref(&self) -> &obs_source_info {
        self.info.as_ref()
    }
}

/// The SourceInfoBuilder that handles creating the [SourceInfo](https://obsproject.com/docs/reference-sources.html#c.obs_source_info) object.
///
/// For each trait that is implemented for the Source, it needs to be enabled using this builder.
/// If an struct called `FocusFilter` implements `CreateSource` and `GetNameSource` it would need
/// to enable those features.
///
/// ```rs
/// let source = load_context
///  .create_source_builder::<FocusFilter, ()>()
///  .enable_get_name()
///  .enable_create()
///  .build();
/// ```
///
pub struct SourceInfoBuilder<D: Sourceable> {
    __data: PhantomData<D>,
    info: obs_source_info,
}

impl<D: Sourceable> SourceInfoBuilder<D> {
    pub(crate) fn new() -> Self {
        Self {
            __data: PhantomData,
            info: obs_source_info {
                id: D::get_id().as_ptr(),
                type_: D::get_type().to_native(),
                create: Some(ffi::create::<D>),
                destroy: Some(ffi::destroy::<D>),
                type_data: std::ptr::null_mut(),
                ..Default::default()
            },
        }
    }

    pub fn build(mut self) -> SourceInfo {
        if self.info.video_render.is_some() {
            self.info.output_flags |= OBS_SOURCE_VIDEO;
        }

        if self.info.audio_render.is_some() || self.info.filter_audio.is_some() {
            self.info.output_flags |= OBS_SOURCE_AUDIO;
        }

        if self.info.media_get_state.is_some() || self.info.media_play_pause.is_some() {
            self.info.output_flags |= OBS_SOURCE_CONTROLLABLE_MEDIA;
        }

        SourceInfo {
            info: Box::new(self.info),
        }
    }
}

macro_rules! impl_source_builder {
    ($($f:ident => $t:ident)*) => ($(
        item! {
            impl<D: Sourceable + [<$t>]> SourceInfoBuilder<D> {
                pub fn [<enable_$f>](mut self) -> Self {
                    self.info.[<$f>] = Some(ffi::[<$f>]::<D>);
                    self
                }
            }
        }
    )*)
}

impl_source_builder! {
    get_name => GetNameSource
    get_width => GetWidthSource
    get_height => GetHeightSource
    activate => ActivateSource
    deactivate => DeactivateSource
    update => UpdateSource
    video_render => VideoRenderSource
    audio_render => AudioRenderSource
    get_properties => GetPropertiesSource
    enum_active_sources => EnumActiveSource
    enum_all_sources => EnumAllSource
    transition_start => TransitionStartSource
    transition_stop => TransitionStopSource
    video_tick => VideoTickSource
    filter_audio => FilterAudioSource
    filter_video => FilterVideoSource
    get_defaults => GetDefaultsSource
    media_play_pause => MediaPlayPauseSource
    media_restart => MediaRestartSource
    media_stop => MediaStopSource
    media_next => MediaNextSource
    media_previous => MediaPreviousSource
    media_get_duration => MediaGetDurationSource
    media_get_time => MediaGetTimeSource
    media_set_time => MediaSetTimeSource
    media_get_state => MediaGetStateSource
}