| 1 |
//! # audio_thread_priority |
| 2 |
//! |
| 3 |
//! Promote the current thread, or another thread (possibly in another process), to real-time |
| 4 |
//! priority, suitable for low-latency audio processing. |
| 5 |
//! |
| 6 |
//! # Example |
| 7 |
//! |
| 8 |
//! ```rust |
| 9 |
//! |
| 10 |
//! use audio_thread_priority::{promote_current_thread_to_real_time, demote_current_thread_from_real_time}; |
| 11 |
//! |
| 12 |
//! // ... on a thread that will compute audio and has to be real-time: |
| 13 |
//! match promote_current_thread_to_real_time(512, 44100) { |
| 14 |
//! Ok(h) => { |
| 15 |
//! println!("this thread is now bumped to real-time priority."); |
| 16 |
//! |
| 17 |
//! // Do some real-time work... |
| 18 |
//! |
| 19 |
//! match demote_current_thread_from_real_time(h) { |
| 20 |
//! Ok(_) => { |
| 21 |
//! println!("this thread is now bumped back to normal.") |
| 22 |
//! } |
| 23 |
//! Err(_) => { |
| 24 |
//! println!("Could not bring the thread back to normal priority.") |
| 25 |
//! } |
| 26 |
//! }; |
| 27 |
//! } |
| 28 |
//! Err(e) => { |
| 29 |
//! eprintln!("Error promoting thread to real-time: {}", e); |
| 30 |
//! } |
| 31 |
//! } |
| 32 |
//! |
| 33 |
//! ``` |
| 34 |
|
| 35 |
#![warn(missing_docs)] |
| 36 |
|
| 37 |
use cfg_if::cfg_if; |
| 38 |
use std::error::Error; |
| 39 |
use std::fmt; |
| 40 |
|
| 41 |
/// The OS-specific issue is available as `inner` |
| 42 |
#[derive(Debug)] |
| 43 |
pub struct AudioThreadPriorityError { |
| 44 |
message: String, |
| 45 |
inner: Option<Box<dyn Error + 'static>>, |
| 46 |
} |
| 47 |
|
| 48 |
impl AudioThreadPriorityError { |
| 49 |
cfg_if! { |
| 50 |
if #[cfg(all(target_os = "linux", feature = "dbus"))] { |
| 51 |
fn new_with_inner(message: &str, inner: Box<dyn Error>) -> AudioThreadPriorityError { |
| 52 |
AudioThreadPriorityError { |
| 53 |
message: message.into(), |
| 54 |
inner: Some(inner), |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
fn new(message: &str) -> AudioThreadPriorityError { |
| 60 |
AudioThreadPriorityError { |
| 61 |
message: message.into(), |
| 62 |
inner: None, |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
impl fmt::Display for AudioThreadPriorityError { |
| 68 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 69 |
let mut rv = write!(f, "AudioThreadPriorityError: {}", &self.message); |
| 70 |
if let Some(inner) = &self.inner { |
| 71 |
rv = write!(f, " ({})", inner); |
| 72 |
} |
| 73 |
rv |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
impl Error for AudioThreadPriorityError { |
| 78 |
fn description(&self) -> &str { |
| 79 |
&self.message |
| 80 |
} |
| 81 |
|
| 82 |
fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 83 |
self.inner.as_ref().map(|e| e.as_ref()) |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
cfg_if! { |
| 88 |
if #[cfg(target_os = "macos")] { |
| 89 |
mod rt_mach; |
| 90 |
#[allow(unused, non_camel_case_types, non_snake_case, non_upper_case_globals)] |
| 91 |
mod mach_sys; |
| 92 |
extern crate mach; |
| 93 |
extern crate libc; |
| 94 |
use rt_mach::promote_current_thread_to_real_time_internal; |
| 95 |
use rt_mach::demote_current_thread_from_real_time_internal; |
| 96 |
use rt_mach::RtPriorityHandleInternal; |
| 97 |
} else if #[cfg(target_os = "windows")] { |
| 98 |
mod rt_win; |
| 99 |
use rt_win::promote_current_thread_to_real_time_internal; |
| 100 |
use rt_win::demote_current_thread_from_real_time_internal; |
| 101 |
use rt_win::RtPriorityHandleInternal; |
| 102 |
} else if #[cfg(all(target_os = "linux", feature = "dbus"))] { |
| 103 |
mod rt_linux; |
| 104 |
extern crate dbus; |
| 105 |
extern crate libc; |
| 106 |
use rt_linux::promote_current_thread_to_real_time_internal; |
| 107 |
use rt_linux::demote_current_thread_from_real_time_internal; |
| 108 |
use rt_linux::set_real_time_hard_limit_internal as set_real_time_hard_limit; |
| 109 |
use rt_linux::get_current_thread_info_internal; |
| 110 |
use rt_linux::promote_thread_to_real_time_internal; |
| 111 |
use rt_linux::demote_thread_from_real_time_internal; |
| 112 |
use rt_linux::RtPriorityThreadInfoInternal; |
| 113 |
use rt_linux::RtPriorityHandleInternal; |
| 114 |
#[no_mangle] |
| 115 |
/// Size of a RtPriorityThreadInfo or atp_thread_info struct, for use in FFI. |
| 116 |
pub static ATP_THREAD_INFO_SIZE: usize = std::mem::size_of::<RtPriorityThreadInfo>(); |
| 117 |
} else { |
| 118 |
// blanket implementations for Android, Linux Desktop without dbus and others |
| 119 |
pub struct RtPriorityHandleInternal {} |
| 120 |
#[derive(Clone, Copy, PartialEq)] |
| 121 |
pub struct RtPriorityThreadInfoInternal { |
| 122 |
_dummy: u8 |
| 123 |
} |
| 124 |
|
| 125 |
cfg_if! { |
| 126 |
if #[cfg(not(target_os = "linux"))] { |
| 127 |
pub type RtPriorityThreadInfo = RtPriorityThreadInfoInternal; |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
impl RtPriorityThreadInfo { |
| 132 |
pub fn serialize(&self) -> [u8; 1] { |
| 133 |
[0] |
| 134 |
} |
| 135 |
pub fn deserialize(_: [u8; 1]) -> Self { |
| 136 |
RtPriorityThreadInfo{_dummy: 0} |
| 137 |
} |
| 138 |
} |
| 139 |
pub fn promote_current_thread_to_real_time_internal(_: u32, audio_samplerate_hz: u32) -> Result<RtPriorityHandle, AudioThreadPriorityError> { |
| 140 |
if audio_samplerate_hz == 0 { |
| 141 |
return Err(AudioThreadPriorityError{message: "sample rate is zero".to_string(), inner: None}); |
| 142 |
} |
| 143 |
// no-op |
| 144 |
Ok(RtPriorityHandle{}) |
| 145 |
} |
| 146 |
pub fn demote_current_thread_from_real_time_internal(_: RtPriorityHandle) -> Result<(), AudioThreadPriorityError> { |
| 147 |
// no-op |
| 148 |
Ok(()) |
| 149 |
} |
| 150 |
pub fn set_real_time_hard_limit( |
| 151 |
_: u32, |
| 152 |
_: u32, |
| 153 |
) -> Result<(), AudioThreadPriorityError> { |
| 154 |
Ok(()) |
| 155 |
} |
| 156 |
pub fn get_current_thread_info_internal() -> Result<RtPriorityThreadInfo, AudioThreadPriorityError> { |
| 157 |
Ok(RtPriorityThreadInfo{_dummy: 0}) |
| 158 |
} |
| 159 |
pub fn promote_thread_to_real_time_internal( |
| 160 |
_: RtPriorityThreadInfo, |
| 161 |
_: u32, |
| 162 |
audio_samplerate_hz: u32, |
| 163 |
) -> Result<RtPriorityHandle, AudioThreadPriorityError> { |
| 164 |
if audio_samplerate_hz == 0 { |
| 165 |
return Err(AudioThreadPriorityError::new("sample rate is zero")); |
| 166 |
} |
| 167 |
return Ok(RtPriorityHandle{}); |
| 168 |
} |
| 169 |
|
| 170 |
pub fn demote_thread_from_real_time_internal(_: RtPriorityThreadInfo) -> Result<(), AudioThreadPriorityError> { |
| 171 |
return Ok(()); |
| 172 |
} |
| 173 |
#[no_mangle] |
| 174 |
/// Size of a RtPriorityThreadInfo or atp_thread_info struct, for use in FFI. |
| 175 |
pub static ATP_THREAD_INFO_SIZE: usize = std::mem::size_of::<RtPriorityThreadInfo>(); |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
/// Opaque handle to a thread handle structure. |
| 180 |
pub type RtPriorityHandle = RtPriorityHandleInternal; |
| 181 |
|
| 182 |
cfg_if! { |
| 183 |
if #[cfg(target_os = "linux")] { |
| 184 |
/// Opaque handle to a thread info. |
| 185 |
/// |
| 186 |
/// This can be serialized to raw bytes to be sent via IPC. |
| 187 |
/// |
| 188 |
/// This call is useful on Linux desktop only, when the process is sandboxed and |
| 189 |
/// cannot promote itself directly. |
| 190 |
pub type RtPriorityThreadInfo = RtPriorityThreadInfoInternal; |
| 191 |
|
| 192 |
|
| 193 |
/// Get the calling thread's information, to be able to promote it to real-time from somewhere |
| 194 |
/// else, later. |
| 195 |
/// |
| 196 |
/// This call is useful on Linux desktop only, when the process is sandboxed and |
| 197 |
/// cannot promote itself directly. |
| 198 |
/// |
| 199 |
/// # Return value |
| 200 |
/// |
| 201 |
/// Ok in case of success, with an opaque structure containing relevant info for the platform, Err |
| 202 |
/// otherwise. |
| 203 |
pub fn get_current_thread_info() -> Result<RtPriorityThreadInfo, AudioThreadPriorityError> { |
| 204 |
get_current_thread_info_internal() |
| 205 |
} |
| 206 |
|
| 207 |
/// Return a byte buffer containing serialized information about a thread, to promote it to |
| 208 |
/// real-time from elsewhere. |
| 209 |
/// |
| 210 |
/// This call is useful on Linux desktop only, when the process is sandboxed and |
| 211 |
/// cannot promote itself directly. |
| 212 |
pub fn thread_info_serialize( |
| 213 |
thread_info: RtPriorityThreadInfo, |
| 214 |
) -> [u8; std::mem::size_of::<RtPriorityThreadInfo>()] { |
| 215 |
thread_info.serialize() |
| 216 |
} |
| 217 |
|
| 218 |
/// From a byte buffer, return a `RtPriorityThreadInfo`. |
| 219 |
/// |
| 220 |
/// This call is useful on Linux desktop only, when the process is sandboxed and |
| 221 |
/// cannot promote itself directly. |
| 222 |
/// |
| 223 |
/// # Arguments |
| 224 |
/// |
| 225 |
/// A byte buffer containing a serializezd `RtPriorityThreadInfo`. |
| 226 |
pub fn thread_info_deserialize( |
| 227 |
bytes: [u8; std::mem::size_of::<RtPriorityThreadInfo>()], |
| 228 |
) -> RtPriorityThreadInfo { |
| 229 |
RtPriorityThreadInfoInternal::deserialize(bytes) |
| 230 |
} |
| 231 |
|
| 232 |
/// Get the calling threads' information, to promote it from another process or thread, with a C |
| 233 |
/// API. |
| 234 |
/// |
| 235 |
/// This is intended to call on the thread that will end up being promoted to real time priority, |
| 236 |
/// but that cannot do it itself (probably because of sandboxing reasons). |
| 237 |
/// |
| 238 |
/// After use, it MUST be freed by calling `atp_free_thread_info`. |
| 239 |
/// |
| 240 |
/// # Return value |
| 241 |
/// |
| 242 |
/// A pointer to a struct that can be serialized and deserialized, and that can be passed to |
| 243 |
/// `atp_promote_thread_to_real_time`, even from another process. |
| 244 |
#[no_mangle] |
| 245 |
pub extern "C" fn atp_get_current_thread_info() -> *mut atp_thread_info { |
| 246 |
match get_current_thread_info() { |
| 247 |
Ok(thread_info) => Box::into_raw(Box::new(atp_thread_info(thread_info))), |
| 248 |
_ => std::ptr::null_mut(), |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
/// Frees a thread info, with a c api. |
| 253 |
/// |
| 254 |
/// # Arguments |
| 255 |
/// |
| 256 |
/// thread_info: the `atp_thread_info` structure to free. |
| 257 |
/// |
| 258 |
/// # Return value |
| 259 |
/// |
| 260 |
/// 0 in case of success, 1 otherwise (if `thread_info` is NULL). |
| 261 |
/// |
| 262 |
/// # Safety |
| 263 |
/// |
| 264 |
/// This function is safe only and only if the pointer comes from this library, of if is null. |
| 265 |
#[no_mangle] |
| 266 |
pub unsafe extern "C" fn atp_free_thread_info(thread_info: *mut atp_thread_info) -> i32 { |
| 267 |
if thread_info.is_null() { |
| 268 |
return 1; |
| 269 |
} |
| 270 |
drop(Box::from_raw(thread_info)); |
| 271 |
0 |
| 272 |
} |
| 273 |
|
| 274 |
/// Return a byte buffer containing serialized information about a thread, to promote it to |
| 275 |
/// real-time from elsewhere, with a C API. |
| 276 |
/// |
| 277 |
/// `bytes` MUST be `std::mem::size_of<RtPriorityThreadInfo>()` bytes long. |
| 278 |
/// |
| 279 |
/// This is exposed in the C API as `ATP_THREAD_INFO_SIZE`. |
| 280 |
/// |
| 281 |
/// This call is useful on Linux desktop only, when the process is sandboxed, cannot promote itself |
| 282 |
/// directly, and the `atp_thread_info` struct must be passed via IPC. |
| 283 |
/// |
| 284 |
/// # Safety |
| 285 |
/// |
| 286 |
/// This function is safe only and only if the first pointer comes from this library, and the |
| 287 |
/// second pointer is at least ATP_THREAD_INFO_SIZE bytes long. |
| 288 |
#[no_mangle] |
| 289 |
pub unsafe extern "C" fn atp_serialize_thread_info( |
| 290 |
thread_info: *mut atp_thread_info, |
| 291 |
bytes: *mut libc::c_void, |
| 292 |
) { |
| 293 |
let thread_info = &mut *thread_info; |
| 294 |
let source = thread_info.0.serialize(); |
| 295 |
std::ptr::copy(source.as_ptr(), bytes as *mut u8, source.len()); |
| 296 |
} |
| 297 |
|
| 298 |
/// From a byte buffer, return a `RtPriorityThreadInfo`, with a C API. |
| 299 |
/// |
| 300 |
/// This call is useful on Linux desktop only, when the process is sandboxed and |
| 301 |
/// cannot promote itself directly. |
| 302 |
/// |
| 303 |
/// # Arguments |
| 304 |
/// |
| 305 |
/// A byte buffer containing a serializezd `RtPriorityThreadInfo`. |
| 306 |
/// |
| 307 |
/// # Safety |
| 308 |
/// |
| 309 |
/// This function is safe only and only if pointer is at least ATP_THREAD_INFO_SIZE bytes long. |
| 310 |
#[no_mangle] |
| 311 |
pub unsafe extern "C" fn atp_deserialize_thread_info( |
| 312 |
in_bytes: *mut u8, |
| 313 |
) -> *mut atp_thread_info { |
| 314 |
let bytes = *(in_bytes as *mut [u8; std::mem::size_of::<RtPriorityThreadInfoInternal>()]); |
| 315 |
let thread_info = RtPriorityThreadInfoInternal::deserialize(bytes); |
| 316 |
Box::into_raw(Box::new(atp_thread_info(thread_info))) |
| 317 |
} |
| 318 |
|
| 319 |
/// Promote a particular thread thread to real-time priority. |
| 320 |
/// |
| 321 |
/// This call is useful on Linux desktop only, when the process is sandboxed and |
| 322 |
/// cannot promote itself directly. |
| 323 |
/// |
| 324 |
/// # Arguments |
| 325 |
/// |
| 326 |
/// * `thread_info` - informations about the thread to promote, gathered using |
| 327 |
/// `get_current_thread_info`. |
| 328 |
/// * `audio_buffer_frames` - the exact or an upper limit on the number of frames that have to be |
| 329 |
/// rendered each callback, or 0 for a sensible default value. |
| 330 |
/// * `audio_samplerate_hz` - the sample-rate for this audio stream, in Hz. |
| 331 |
/// |
| 332 |
/// # Return value |
| 333 |
/// |
| 334 |
/// This function returns a `Result<RtPriorityHandle>`, which is an opaque struct to be passed to |
| 335 |
/// `demote_current_thread_from_real_time` to revert to the previous thread priority. |
| 336 |
pub fn promote_thread_to_real_time( |
| 337 |
thread_info: RtPriorityThreadInfo, |
| 338 |
audio_buffer_frames: u32, |
| 339 |
audio_samplerate_hz: u32, |
| 340 |
) -> Result<RtPriorityHandle, AudioThreadPriorityError> { |
| 341 |
if audio_samplerate_hz == 0 { |
| 342 |
return Err(AudioThreadPriorityError::new("sample rate is zero")); |
| 343 |
} |
| 344 |
promote_thread_to_real_time_internal( |
| 345 |
thread_info, |
| 346 |
audio_buffer_frames, |
| 347 |
audio_samplerate_hz, |
| 348 |
) |
| 349 |
} |
| 350 |
|
| 351 |
/// Demotes a thread from real-time priority. |
| 352 |
/// |
| 353 |
/// # Arguments |
| 354 |
/// |
| 355 |
/// * `thread_info` - An opaque struct returned from a successful call to |
| 356 |
/// `get_current_thread_info`. |
| 357 |
/// |
| 358 |
/// # Return value |
| 359 |
/// |
| 360 |
/// `Ok` in case of success, `Err` otherwise. |
| 361 |
pub fn demote_thread_from_real_time(thread_info: RtPriorityThreadInfo) -> Result<(), AudioThreadPriorityError> { |
| 362 |
demote_thread_from_real_time_internal(thread_info) |
| 363 |
} |
| 364 |
|
| 365 |
/// Opaque info to a particular thread. |
| 366 |
#[allow(non_camel_case_types)] |
| 367 |
pub struct atp_thread_info(RtPriorityThreadInfo); |
| 368 |
|
| 369 |
/// Promote a specific thread to real-time, with a C API. |
| 370 |
/// |
| 371 |
/// This is useful when the thread to promote cannot make some system calls necessary to promote |
| 372 |
/// it. |
| 373 |
/// |
| 374 |
/// # Arguments |
| 375 |
/// |
| 376 |
/// `thread_info` - the information of the thread to promote to real-time, gather from calling |
| 377 |
/// `atp_get_current_thread_info` on the thread to promote. |
| 378 |
/// * `audio_buffer_frames` - the exact or an upper limit on the number of frames that have to be |
| 379 |
/// rendered each callback, or 0 for a sensible default value. |
| 380 |
/// * `audio_samplerate_hz` - the sample-rate for this audio stream, in Hz. |
| 381 |
/// |
| 382 |
/// # Return value |
| 383 |
/// |
| 384 |
/// A pointer to an `atp_handle` in case of success, NULL otherwise. |
| 385 |
/// |
| 386 |
/// # Safety |
| 387 |
/// |
| 388 |
/// This function is safe as long as the first pointer comes from this library. |
| 389 |
#[no_mangle] |
| 390 |
pub unsafe extern "C" fn atp_promote_thread_to_real_time( |
| 391 |
thread_info: *mut atp_thread_info, |
| 392 |
audio_buffer_frames: u32, |
| 393 |
audio_samplerate_hz: u32, |
| 394 |
) -> *mut atp_handle { |
| 395 |
let thread_info = &mut *thread_info; |
| 396 |
match promote_thread_to_real_time(thread_info.0, audio_buffer_frames, audio_samplerate_hz) { |
| 397 |
Ok(handle) => Box::into_raw(Box::new(atp_handle(handle))), |
| 398 |
_ => std::ptr::null_mut(), |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
/// Demote a thread promoted to from real-time, with a C API. |
| 403 |
/// |
| 404 |
/// # Arguments |
| 405 |
/// |
| 406 |
/// `handle` - an opaque struct received from a promoting function. |
| 407 |
/// |
| 408 |
/// # Return value |
| 409 |
/// |
| 410 |
/// 0 in case of success, non-zero otherwise. |
| 411 |
/// |
| 412 |
/// # Safety |
| 413 |
/// |
| 414 |
/// This function is safe as long as the first pointer comes from this library, or is null. |
| 415 |
#[no_mangle] |
| 416 |
pub unsafe extern "C" fn atp_demote_thread_from_real_time(thread_info: *mut atp_thread_info) -> i32 { |
| 417 |
if thread_info.is_null() { |
| 418 |
return 1; |
| 419 |
} |
| 420 |
let thread_info = (*thread_info).0; |
| 421 |
|
| 422 |
match demote_thread_from_real_time(thread_info) { |
| 423 |
Ok(_) => 0, |
| 424 |
_ => 1, |
| 425 |
} |
| 426 |
} |
| 427 |
|
| 428 |
/// Set a real-time limit for the calling thread. |
| 429 |
/// |
| 430 |
/// # Arguments |
| 431 |
/// |
| 432 |
/// `audio_buffer_frames` - the number of frames the audio callback has to render each quantum. 0 |
| 433 |
/// picks a rather high default value. |
| 434 |
/// `audio_samplerate_hz` - the sample-rate of the audio stream. |
| 435 |
/// |
| 436 |
/// # Return value |
| 437 |
/// |
| 438 |
/// 0 in case of success, 1 otherwise. |
| 439 |
#[no_mangle] |
| 440 |
pub extern "C" fn atp_set_real_time_limit(audio_buffer_frames: u32, |
| 441 |
audio_samplerate_hz: u32) -> i32 { |
| 442 |
let r = set_real_time_hard_limit(audio_buffer_frames, audio_samplerate_hz); |
| 443 |
if r.is_err() { |
| 444 |
return 1; |
| 445 |
} |
| 446 |
0 |
| 447 |
} |
| 448 |
|
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
/// Promote the calling thread thread to real-time priority. |
| 453 |
/// |
| 454 |
/// # Arguments |
| 455 |
/// |
| 456 |
/// * `audio_buffer_frames` - the exact or an upper limit on the number of frames that have to be |
| 457 |
/// rendered each callback, or 0 for a sensible default value. |
| 458 |
/// * `audio_samplerate_hz` - the sample-rate for this audio stream, in Hz. |
| 459 |
/// |
| 460 |
/// # Return value |
| 461 |
/// |
| 462 |
/// This function returns a `Result<RtPriorityHandle>`, which is an opaque struct to be passed to |
| 463 |
/// `demote_current_thread_from_real_time` to revert to the previous thread priority. |
| 464 |
pub fn promote_current_thread_to_real_time( |
| 465 |
audio_buffer_frames: u32, |
| 466 |
audio_samplerate_hz: u32, |
| 467 |
) -> Result<RtPriorityHandle, AudioThreadPriorityError> { |
| 468 |
if audio_samplerate_hz == 0 { |
| 469 |
return Err(AudioThreadPriorityError::new("sample rate is zero")); |
| 470 |
} |
| 471 |
promote_current_thread_to_real_time_internal(audio_buffer_frames, audio_samplerate_hz) |
| 472 |
} |
| 473 |
|
| 474 |
/// Demotes the calling thread from real-time priority. |
| 475 |
/// |
| 476 |
/// # Arguments |
| 477 |
/// |
| 478 |
/// * `handle` - An opaque struct returned from a successful call to |
| 479 |
/// `promote_current_thread_to_real_time`. |
| 480 |
/// |
| 481 |
/// # Return value |
| 482 |
/// |
| 483 |
/// `Ok` in scase of success, `Err` otherwise. |
| 484 |
pub fn demote_current_thread_from_real_time( |
| 485 |
handle: RtPriorityHandle, |
| 486 |
) -> Result<(), AudioThreadPriorityError> { |
| 487 |
demote_current_thread_from_real_time_internal(handle) |
| 488 |
} |
| 489 |
|
| 490 |
/// Opaque handle for the C API |
| 491 |
#[allow(non_camel_case_types)] |
| 492 |
pub struct atp_handle(RtPriorityHandle); |
| 493 |
|
| 494 |
/// Promote the calling thread thread to real-time priority, with a C API. |
| 495 |
/// |
| 496 |
/// # Arguments |
| 497 |
/// |
| 498 |
/// * `audio_buffer_frames` - the exact or an upper limit on the number of frames that have to be |
| 499 |
/// rendered each callback, or 0 for a sensible default value. |
| 500 |
/// * `audio_samplerate_hz` - the sample-rate for this audio stream, in Hz. |
| 501 |
/// |
| 502 |
/// # Return value |
| 503 |
/// |
| 504 |
/// This function returns `NULL` in case of error: if it couldn't bump the thread, or if the |
| 505 |
/// `audio_samplerate_hz` is zero. It returns an opaque handle, to be passed to |
| 506 |
/// `atp_demote_current_thread_from_real_time` to demote the thread. |
| 507 |
/// |
| 508 |
/// Additionaly, NULL can be returned in sandboxed processes on Linux, when DBUS cannot be used in |
| 509 |
/// the process (for example because the socket to DBUS cannot be created). If this is the case, |
| 510 |
/// it's necessary to get the information from the thread to promote and ask another process to |
| 511 |
/// promote it (maybe via another privileged process). |
| 512 |
#[no_mangle] |
| 513 |
pub extern "C" fn atp_promote_current_thread_to_real_time( |
| 514 |
audio_buffer_frames: u32, |
| 515 |
audio_samplerate_hz: u32, |
| 516 |
) -> *mut atp_handle { |
| 517 |
match promote_current_thread_to_real_time(audio_buffer_frames, audio_samplerate_hz) { |
| 518 |
Ok(handle) => Box::into_raw(Box::new(atp_handle(handle))), |
| 519 |
_ => std::ptr::null_mut(), |
| 520 |
} |
| 521 |
} |
| 522 |
/// Demotes the calling thread from real-time priority, with a C API. |
| 523 |
/// |
| 524 |
/// # Arguments |
| 525 |
/// |
| 526 |
/// * `atp_handle` - An opaque struct returned from a successful call to |
| 527 |
/// `atp_promote_current_thread_to_real_time`. |
| 528 |
/// |
| 529 |
/// # Return value |
| 530 |
/// |
| 531 |
/// 0 in case of success, non-zero in case of error. |
| 532 |
/// |
| 533 |
/// # Safety |
| 534 |
/// |
| 535 |
/// Only to be used with a valid pointer from this library -- not after having released it via |
| 536 |
/// atp_free_handle. |
| 537 |
#[no_mangle] |
| 538 |
pub unsafe extern "C" fn atp_demote_current_thread_from_real_time(handle: *mut atp_handle) -> i32 { |
| 539 |
assert!(!handle.is_null()); |
| 540 |
let handle = Box::from_raw(handle); |
| 541 |
|
| 542 |
match demote_current_thread_from_real_time(handle.0) { |
| 543 |
Ok(_) => 0, |
| 544 |
_ => 1, |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
/// Frees a handle, with a C API. |
| 549 |
/// |
| 550 |
/// This is useful when it impractical to call `atp_demote_current_thread_from_real_time` on the |
| 551 |
/// right thread. Access to the handle must be synchronized externaly, or the thread that was |
| 552 |
/// promoted to real-time priority must have exited. |
| 553 |
/// |
| 554 |
/// # Arguments |
| 555 |
/// |
| 556 |
/// * `atp_handle` - An opaque struct returned from a successful call to |
| 557 |
/// `atp_promote_current_thread_to_real_time`. |
| 558 |
/// |
| 559 |
/// # Return value |
| 560 |
/// |
| 561 |
/// 0 in case of success, non-zero in case of error. |
| 562 |
/// |
| 563 |
/// # Safety |
| 564 |
/// |
| 565 |
/// Should only be called to free something from this crate. |
| 566 |
#[no_mangle] |
| 567 |
pub unsafe extern "C" fn atp_free_handle(handle: *mut atp_handle) -> i32 { |
| 568 |
if handle.is_null() { |
| 569 |
return 1; |
| 570 |
} |
| 571 |
let _handle = Box::from_raw(handle); |
| 572 |
0 |
| 573 |
} |
| 574 |
|
| 575 |
#[cfg(test)] |
| 576 |
mod tests { |
| 577 |
use super::*; |
| 578 |
#[cfg(feature = "terminal-logging")] |
| 579 |
use simple_logger; |
| 580 |
#[test] |
| 581 |
fn it_works() { |
| 582 |
#[cfg(feature = "terminal-logging")] |
| 583 |
simple_logger::init().unwrap(); |
| 584 |
{ |
| 585 |
assert!(promote_current_thread_to_real_time(0, 0).is_err()); |
| 586 |
} |
| 587 |
{ |
| 588 |
match promote_current_thread_to_real_time(0, 44100) { |
| 589 |
Ok(rt_prio_handle) => { |
| 590 |
demote_current_thread_from_real_time(rt_prio_handle).unwrap(); |
| 591 |
assert!(true); |
| 592 |
} |
| 593 |
Err(e) => { |
| 594 |
eprintln!("{}", e); |
| 595 |
assert!(false); |
| 596 |
} |
| 597 |
} |
| 598 |
} |
| 599 |
{ |
| 600 |
match promote_current_thread_to_real_time(512, 44100) { |
| 601 |
Ok(rt_prio_handle) => { |
| 602 |
demote_current_thread_from_real_time(rt_prio_handle).unwrap(); |
| 603 |
assert!(true); |
| 604 |
} |
| 605 |
Err(e) => { |
| 606 |
eprintln!("{}", e); |
| 607 |
assert!(false); |
| 608 |
} |
| 609 |
} |
| 610 |
} |
| 611 |
{ |
| 612 |
// Try larger values to test https://github.com/mozilla/audio_thread_priority/pull/23 |
| 613 |
match promote_current_thread_to_real_time(0, 192000) { |
| 614 |
Ok(rt_prio_handle) => { |
| 615 |
demote_current_thread_from_real_time(rt_prio_handle).unwrap(); |
| 616 |
assert!(true); |
| 617 |
} |
| 618 |
Err(e) => { |
| 619 |
eprintln!("{}", e); |
| 620 |
assert!(false); |
| 621 |
} |
| 622 |
} |
| 623 |
} |
| 624 |
{ |
| 625 |
// Try larger values to test https://github.com/mozilla/audio_thread_priority/pull/23 |
| 626 |
match promote_current_thread_to_real_time(8192, 48000) { |
| 627 |
Ok(rt_prio_handle) => { |
| 628 |
demote_current_thread_from_real_time(rt_prio_handle).unwrap(); |
| 629 |
assert!(true); |
| 630 |
} |
| 631 |
Err(e) => { |
| 632 |
eprintln!("{}", e); |
| 633 |
assert!(false); |
| 634 |
} |
| 635 |
} |
| 636 |
} |
| 637 |
{ |
| 638 |
match promote_current_thread_to_real_time(512, 44100) { |
| 639 |
Ok(_) => { |
| 640 |
assert!(true); |
| 641 |
} |
| 642 |
Err(e) => { |
| 643 |
eprintln!("{}", e); |
| 644 |
assert!(false); |
| 645 |
} |
| 646 |
} |
| 647 |
// automatically deallocated, but not demoted until the thread exits. |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
#[test] |
| 652 |
fn it_works_in_different_threads() { |
| 653 |
let handles: Vec<_> = (0..32).map(|_| std::thread::spawn(it_works)).collect(); |
| 654 |
for handle in handles { |
| 655 |
handle.join().unwrap() |
| 656 |
} |
| 657 |
} |
| 658 |
|
| 659 |
cfg_if! { |
| 660 |
if #[cfg(target_os = "linux")] { |
| 661 |
use nix::unistd::*; |
| 662 |
use nix::sys::signal::*; |
| 663 |
|
| 664 |
#[test] |
| 665 |
fn test_linux_api() { |
| 666 |
{ |
| 667 |
let info = get_current_thread_info().unwrap(); |
| 668 |
match promote_thread_to_real_time(info, 512, 44100) { |
| 669 |
Ok(_) => { |
| 670 |
assert!(true); |
| 671 |
} |
| 672 |
Err(e) => { |
| 673 |
eprintln!("{}", e); |
| 674 |
assert!(false); |
| 675 |
} |
| 676 |
} |
| 677 |
} |
| 678 |
{ |
| 679 |
let info = get_current_thread_info().unwrap(); |
| 680 |
let bytes = info.serialize(); |
| 681 |
let info2 = RtPriorityThreadInfo::deserialize(bytes); |
| 682 |
assert!(info == info2); |
| 683 |
} |
| 684 |
{ |
| 685 |
let info = get_current_thread_info().unwrap(); |
| 686 |
let bytes = thread_info_serialize(info); |
| 687 |
let info2 = thread_info_deserialize(bytes); |
| 688 |
assert!(info == info2); |
| 689 |
} |
| 690 |
} |
| 691 |
#[test] |
| 692 |
fn test_remote_promotion() { |
| 693 |
let (rd, wr) = pipe().unwrap(); |
| 694 |
|
| 695 |
match unsafe { fork().expect("fork failed") } { |
| 696 |
ForkResult::Parent{ child } => { |
| 697 |
eprintln!("Parent PID: {}", getpid()); |
| 698 |
let mut bytes = [0_u8; std::mem::size_of::<RtPriorityThreadInfo>()]; |
| 699 |
match read(rd, &mut bytes) { |
| 700 |
Ok(_) => { |
| 701 |
let info = RtPriorityThreadInfo::deserialize(bytes); |
| 702 |
match promote_thread_to_real_time(info, 0, 44100) { |
| 703 |
Ok(_) => { |
| 704 |
eprintln!("thread promotion in the child from the parent succeeded"); |
| 705 |
assert!(true); |
| 706 |
} |
| 707 |
Err(_) => { |
| 708 |
eprintln!("promotion Err"); |
| 709 |
kill(child, SIGKILL).expect("Could not kill the child?"); |
| 710 |
assert!(false); |
| 711 |
} |
| 712 |
} |
| 713 |
} |
| 714 |
Err(e) => { |
| 715 |
eprintln!("could not read from the pipe: {}", e); |
| 716 |
} |
| 717 |
} |
| 718 |
kill(child, SIGKILL).expect("Could not kill the child?"); |
| 719 |
} |
| 720 |
ForkResult::Child => { |
| 721 |
let r = set_real_time_hard_limit(0, 44100); |
| 722 |
if r.is_err() { |
| 723 |
eprintln!("Could not set RT limit, the test will fail."); |
| 724 |
} |
| 725 |
eprintln!("Child pid: {}", getpid()); |
| 726 |
let info = get_current_thread_info().unwrap(); |
| 727 |
let bytes = info.serialize(); |
| 728 |
match write(wr, &bytes) { |
| 729 |
Ok(_) => { |
| 730 |
loop { |
| 731 |
std::thread::sleep(std::time::Duration::from_millis(1000)); |
| 732 |
eprintln!("child sleeping, waiting to be promoted..."); |
| 733 |
} |
| 734 |
} |
| 735 |
Err(_) => { |
| 736 |
eprintln!("write error on the pipe."); |
| 737 |
} |
| 738 |
} |
| 739 |
} |
| 740 |
} |
| 741 |
} |
| 742 |
} |
| 743 |
} |
| 744 |
} |