Skip to content

Commit

Permalink
Merge pull request #3 from slerpyyy/main
Browse files Browse the repository at this point in the history
Rollup of multiple commits
  • Loading branch information
sp4ghet authored Aug 2, 2021
2 parents ef04f2d + e4973b1 commit ff5f350
Show file tree
Hide file tree
Showing 9 changed files with 161 additions and 98 deletions.
2 changes: 1 addition & 1 deletion ndi-examples/src/data_lifetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ fn main() {

thread::sleep(std::time::Duration::from_millis(1000));

println!("Frame received: {}x{}", frame.xres(), frame.yres());
println!("Frame received: {}x{}", frame.width(), frame.height());
}
9 changes: 3 additions & 6 deletions ndi-examples/src/multithread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ fn main() {
let sources = find.current_sources(1000).unwrap();

let mut recv = ndi::RecvBuilder::new().build().unwrap();
println!(
"Connecting to the first source: {}",
sources[0].get_name().unwrap_or("[invalid-name]".into())
);
println!("Connecting to the first source: {}", sources[0].get_name());
recv.connect(&sources[0]);

let recv_arc = Arc::new(recv);
Expand Down Expand Up @@ -57,8 +54,8 @@ fn main() {
if let Ok(video_data) = video_rx.recv().map_err(|e| e.to_string()) {
println!(
"Received video on main thread: {}x{}",
video_data.xres(),
video_data.yres()
video_data.width(),
video_data.height()
);
}

Expand Down
12 changes: 4 additions & 8 deletions ndi-examples/src/recv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@ fn main() {

println!("Select device:");
for (i, source) in sources.iter().enumerate() {
println!(
" {}: {}",
i,
source.get_name().unwrap_or("[invalid-name]".into())
);
println!(" {}: {}", i, source.get_name());
}

let stdin = io::stdin();
Expand All @@ -32,7 +28,7 @@ fn main() {
let mut recv = recv_builder.build().unwrap();
recv.connect(&sources[i]);

let name = sources[i].get_name().unwrap();
let name = sources[i].get_name();
println!("Connected to NDI device {}", name);

let start = Instant::now();
Expand All @@ -51,8 +47,8 @@ fn main() {
let video_data = video_data.expect("Failed to get video data from capture");
println!(
"Got video data: {}x{} {:?}",
video_data.xres(),
video_data.yres(),
video_data.width(),
video_data.height(),
video_data.four_cc()
);
}
Expand Down
6 changes: 3 additions & 3 deletions ndi-examples/src/save_recv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ fn main() {

let frame_vec = unsafe {
assert!(!frame.p_data().is_null());
let size = frame.yres() * frame.line_stride_in_bytes().unwrap();
let size = frame.width() * frame.line_stride_in_bytes().unwrap();
std::slice::from_raw_parts(frame.p_data(), size as _)
};
let frame_vec = Vec::from_iter(frame_vec.to_owned());
let buf = image::ImageBuffer::<image::Rgba<u8>, Vec<_>>::from_vec(
frame.xres(),
frame.yres(),
frame.width(),
frame.height(),
frame_vec,
)
.ok_or("Failed to create image")
Expand Down
23 changes: 14 additions & 9 deletions ndi/src/find.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::internal::OnDrop;

use super::*;
use std::{ffi::CString, thread::yield_now, time::Instant};

Expand Down Expand Up @@ -84,7 +86,7 @@ impl FindBuilder {
/// a few seconds to locate all of the sources available, since this requires other running machines to send response
/// messages.)
pub struct Find {
p_instance: NDIlib_find_instance_t,
p_instance: Arc<OnDrop<NDIlib_find_instance_t>>,
}

unsafe impl core::marker::Send for Find {}
Expand All @@ -98,6 +100,9 @@ impl Find {
return Err(FindCreateError);
};

let p_instance = Arc::new(OnDrop::new(p_instance, |s| unsafe {
NDIlib_find_destroy(s)
}));
Ok(Self { p_instance })
}

Expand All @@ -107,6 +112,9 @@ impl Find {
return Err(FindCreateError);
};

let p_instance = Arc::new(OnDrop::new(p_instance, |s| unsafe {
NDIlib_find_destroy(s)
}));
Ok(Self { p_instance })
}

Expand All @@ -121,7 +129,7 @@ impl Find {
}

let p_sources =
unsafe { NDIlib_find_get_current_sources(self.p_instance, &mut no_sources) };
unsafe { NDIlib_find_get_current_sources(**self.p_instance, &mut no_sources) };

if no_sources != 0 {
break p_sources;
Expand All @@ -132,15 +140,12 @@ impl Find {

let mut sources: Vec<Source> = vec![];
for k in 0..no_sources {
sources.push(Source::from_binding(unsafe { *p_sources.offset(k as _) }));
let parent = SourceParent::Find(Arc::clone(&self.p_instance));
sources.push(Source::from_binding(parent, unsafe {
*p_sources.offset(k as _)
}));
}

Ok(sources)
}
}

impl Drop for Find {
fn drop(&mut self) {
unsafe { NDIlib_find_destroy(self.p_instance) };
}
}
54 changes: 52 additions & 2 deletions ndi/src/internal/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
#![allow(deref_nullptr)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(non_upper_case_globals)]

use std::ops::{Deref, DerefMut};

#[cfg(target_os = "windows")]
mod bindings_windows;
Expand All @@ -16,3 +19,50 @@ pub mod bindings {
#[cfg(target_os = "linux")]
pub use super::bindings_linux::*;
}

/// Utility for adding a destructor function to a pointer which is called once the struct is dropped.
pub(crate) struct OnDrop<P: Copy> {
inner: P,
destroy: fn(P),
}

impl<T> OnDrop<*mut T> {
pub(crate) fn new(inner: *mut T, destroy: fn(*mut T)) -> Self {
OnDrop { inner, destroy }
}
}

impl<P: Copy> Deref for OnDrop<P> {
type Target = P;

fn deref(&self) -> &Self::Target {
&self.inner
}
}

impl<P: Copy> DerefMut for OnDrop<P> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}

impl<P: Copy> Drop for OnDrop<P> {
fn drop(&mut self) {
(self.destroy)(self.inner);
}
}

#[test]
fn on_drop_simple() {
fn drop_boxed_i32(b: *mut i32) {
let b = unsafe { Box::from_raw(b) };
assert_eq!(*b, 5);
drop(b);
}

let num = Box::into_raw(Box::new(2));
unsafe { *num += 3 };

let on_drop = OnDrop::new(num, drop_boxed_i32);
drop(on_drop);
}
Loading

0 comments on commit ff5f350

Please sign in to comment.