forked from jerry73204/realsense-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.rs
358 lines (321 loc) · 11.9 KB
/
pipeline.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
//! Defines the pipeline type.
use crate::{
base::DEFAULT_TIMEOUT,
common::*,
config::Config,
context::Context,
error::{Error as RsError, ErrorChecker, Result},
frame::{CompositeFrame, Frame, GenericFrameEx},
pipeline_kind::{self, PipelineState},
pipeline_profile::PipelineProfile,
};
/// Represents the data pipeline from a RealSense device.
#[derive(Debug)]
pub struct Pipeline<State>
where
State: pipeline_kind::PipelineState,
{
pub(crate) ptr: NonNull<sys::rs2_pipeline>,
context: Context,
state: State,
}
// type aliases
pub type InactivePipeline = Pipeline<pipeline_kind::Inactive>;
pub type ActivePipeline = Pipeline<pipeline_kind::Active>;
impl InactivePipeline {
/// Creates an instance.
pub fn new() -> Result<Self> {
let context = Context::new()?;
let pipeline = Self::from_context(context)?;
Ok(pipeline)
}
/// Consumes a context and creates an instance.
pub fn from_context(context: Context) -> Result<Self> {
let ptr = {
let mut checker = ErrorChecker::new();
let ptr =
unsafe { sys::rs2_create_pipeline(context.ptr.as_ptr(), checker.inner_mut_ptr()) };
checker.check()?;
ptr
};
let pipeline = Self {
ptr: NonNull::new(ptr).unwrap(),
context,
state: pipeline_kind::Inactive,
};
Ok(pipeline)
}
/// Start the pipeline with an optional config.
///
/// The method consumes inactive pipeline itself, and returns the started pipeine.
pub fn start<'a>(self, config: impl Into<Option<&'a Config>>) -> Result<ActivePipeline> {
let config = config.into();
let ptr = match config {
Some(conf) => unsafe {
let mut checker = ErrorChecker::new();
let ptr = sys::rs2_pipeline_start_with_config(
self.ptr.as_ptr(),
conf.ptr.as_ptr(),
checker.inner_mut_ptr(),
);
checker.check()?;
ptr
},
None => unsafe {
let mut checker = ErrorChecker::new();
let ptr = sys::rs2_pipeline_start(self.ptr.as_ptr(), checker.inner_mut_ptr());
checker.check()?;
ptr
},
};
let profile = unsafe { PipelineProfile::from_raw(ptr) };
let pipeline = {
let (pipeline_ptr, context_ptr) = self.into_raw_parts();
Pipeline {
ptr: NonNull::new(pipeline_ptr).unwrap(),
context: unsafe { Context::from_raw(context_ptr) },
state: pipeline_kind::Active { profile },
}
};
Ok(pipeline)
}
/// Start the pipeline asynchronously. It is analogous to [Pipeline::start].
pub async fn start_async<'a>(
self,
config: impl Into<Option<&'a Config>>,
) -> Result<ActivePipeline> {
let config = config.into();
let pipeline_ptr = AtomicPtr::new(self.ptr.as_ptr());
let config_ptr_opt = config.map(|conf| AtomicPtr::new(conf.ptr.as_ptr()));
let (tx, rx) = futures::channel::oneshot::channel();
// start blocking thread
thread::spawn(move || {
let func = || unsafe {
let profile_ptr = match config_ptr_opt {
Some(config_ptr) => {
let mut checker = ErrorChecker::new();
let ptr = sys::rs2_pipeline_start_with_config(
pipeline_ptr.load(Ordering::SeqCst),
config_ptr.load(Ordering::SeqCst),
checker.inner_mut_ptr(),
);
checker.check()?;
ptr
}
None => {
let mut checker = ErrorChecker::new();
let ptr = sys::rs2_pipeline_start(
pipeline_ptr.load(Ordering::SeqCst),
checker.inner_mut_ptr(),
);
checker.check()?;
ptr
}
};
Ok(AtomicPtr::new(profile_ptr))
};
let result = func();
let _ = tx.send(result);
});
let profile_ptr = rx.await.unwrap()?;
let profile = unsafe { PipelineProfile::from_raw(profile_ptr.load(Ordering::SeqCst)) };
let pipeline = {
let (pipeline_ptr, context_ptr) = self.into_raw_parts();
Pipeline {
ptr: NonNull::new(pipeline_ptr).unwrap(),
context: unsafe { Context::from_raw(context_ptr) },
state: pipeline_kind::Active { profile },
}
};
Ok(pipeline)
}
/// Unpack the pipeline into raw pointers.
///
/// It returns the raw pointer along with the context pointer that the pipeline depends on.
pub fn into_raw_parts(self) -> (*mut sys::rs2_pipeline, *mut sys::rs2_context) {
// take fields without invoking drop()
let ptr = self.ptr;
let context = unsafe { self.context.unsafe_clone().into_raw() };
mem::forget(self);
(ptr.as_ptr(), context)
}
/// Construct an inactive pipeline from raw pointers.
///
/// It assumes the pipeline pointers is built atop from the context pointer.
pub unsafe fn from_raw_parts(
pipeline_ptr: *mut sys::rs2_pipeline,
context_ptr: *mut sys::rs2_context,
) -> Self {
let context = Context::from_raw(context_ptr);
Self {
ptr: NonNull::new(pipeline_ptr).unwrap(),
context,
state: pipeline_kind::Inactive,
}
}
}
impl ActivePipeline {
/// Gets the active profile of pipeline.
pub fn profile(&self) -> &PipelineProfile {
&self.state.profile
}
/// Block until the next frame is available.
///
/// When the timeout is set, it returns `Ok(Some(frame))` if the frame is available,
/// or returns `Ok(None)` when timeout occurs.
///
/// If the timeout is `None`, it waits indefinitely before the next frame.
pub fn wait(&mut self, timeout: impl Into<Option<Duration>>) -> Result<Option<CompositeFrame>> {
let timeout = timeout.into();
let timeout_ms = timeout.unwrap_or(DEFAULT_TIMEOUT).as_millis() as c_uint;
let frame = loop {
let mut checker = ErrorChecker::new();
let ptr = unsafe {
sys::rs2_pipeline_wait_for_frames(
self.ptr.as_ptr(),
timeout_ms,
checker.inner_mut_ptr(),
)
};
match (timeout, checker.check()) {
(None, Err(RsError::Timeout(_))) => continue,
(Some(_), Err(RsError::Timeout(_))) => {
return Ok(None);
}
(_, result) => result?,
}
let frame = unsafe { Frame::from_raw(ptr) };
break frame;
};
Ok(Some(frame))
}
/// Poll if next frame is immediately available.
///
/// Unlike [Pipeline::start], the method does not block and returns None
/// if next from is not available.
pub fn try_wait(&mut self) -> Result<Option<CompositeFrame>> {
unsafe {
let mut checker = ErrorChecker::new();
let mut ptr: *mut sys::rs2_frame = ptr::null_mut();
let ret = sys::rs2_pipeline_poll_for_frames(
self.ptr.as_ptr(),
&mut ptr as *mut _,
checker.inner_mut_ptr(),
);
if let Err(err) = checker.check() {
return Err(err);
}
if ret != 0 {
let frame = Frame::from_raw(ptr);
Ok(Some(frame))
} else {
Ok(None)
}
}
}
/// Wait for the next frame asynchronously.
///
/// The method is analogous to [Pipeline::wait].
///
/// When the timeout is set, it returns `Ok(Some(frame))` if the frame is available,
/// or returns `Ok(None)` when timeout occurs.
///
/// If the timeout is `None`, it waits indefinitely before the next frame.
pub async fn wait_async(
&mut self,
timeout: impl Into<Option<Duration>>,
) -> Result<Option<CompositeFrame>> {
let timeout = timeout.into();
let timeout_ms = timeout
.map(|duration| duration.as_millis() as c_uint)
.unwrap_or(sys::RS2_DEFAULT_TIMEOUT as c_uint);
let (tx, rx) = futures::channel::oneshot::channel();
let pipeline_ptr = AtomicPtr::new(self.ptr.as_ptr());
thread::spawn(move || {
let result = unsafe {
loop {
let mut checker = ErrorChecker::new();
let ptr = sys::rs2_pipeline_wait_for_frames(
pipeline_ptr.load(Ordering::Relaxed),
timeout_ms,
checker.inner_mut_ptr(),
);
let result = match (timeout, checker.check()) {
(None, Err(RsError::Timeout(_))) => continue,
(Some(_), Err(RsError::Timeout(_))) => Ok(None),
(_, result) => result.map(|_| Some(Frame::from_raw(ptr))),
};
break result;
}
};
let _ = tx.send(result);
});
let frame = rx.await.unwrap()?;
Ok(frame)
}
/// Stop the pipeline.
///
/// This method consumes the pipeline instance and returns pipeline markered inactive.
pub fn stop(self) -> Result<InactivePipeline> {
unsafe {
let mut checker = ErrorChecker::new();
sys::rs2_pipeline_stop(self.ptr.as_ptr(), checker.inner_mut_ptr());
checker.check()?;
}
let pipeline = {
let (pipeline_ptr, context_ptr, profile_ptr) = self.into_raw_parts();
mem::drop(unsafe { pipeline_kind::Active::from_raw_parts(profile_ptr) });
Pipeline {
ptr: NonNull::new(pipeline_ptr).unwrap(),
context: unsafe { Context::from_raw(context_ptr) },
state: pipeline_kind::Inactive,
}
};
Ok(pipeline)
}
/// Unpack the pipeline into raw pointers.
///
/// After calling this method, you have to take care of their lifetime manually.
pub fn into_raw_parts(
self,
) -> (
*mut sys::rs2_pipeline,
*mut sys::rs2_context,
*mut sys::rs2_pipeline_profile,
) {
// take fields without invoking drop()
let ptr = self.ptr;
let context = unsafe { self.context.unsafe_clone().into_raw() };
let pipeline_profile = unsafe { self.state.unsafe_clone().into_raw_parts() };
mem::forget(self);
(ptr.as_ptr(), context, pipeline_profile)
}
/// Construct an active pipeline from raw pointers.
///
/// It assumes the pipeline pointer is built from the context pointer, and profile pointer
/// is the active profile of the pipeline.
pub unsafe fn from_raw_parts(
pipeline_ptr: *mut sys::rs2_pipeline,
context_ptr: *mut sys::rs2_context,
profile_ptr: *mut sys::rs2_pipeline_profile,
) -> Self {
let context = Context::from_raw(context_ptr);
let state = pipeline_kind::Active::from_raw_parts(profile_ptr);
Self {
ptr: NonNull::new(pipeline_ptr).unwrap(),
context,
state,
}
}
}
impl<State> Drop for Pipeline<State>
where
State: pipeline_kind::PipelineState,
{
fn drop(&mut self) {
unsafe {
sys::rs2_delete_pipeline(self.ptr.as_ptr());
}
}
}
unsafe impl<State> Send for Pipeline<State> where State: pipeline_kind::PipelineState {}