| 1 |
use self::avrt_lib::AvRtLibrary; |
| 2 |
use crate::AudioThreadPriorityError; |
| 3 |
use log::info; |
| 4 |
use std::sync::OnceLock; |
| 5 |
use windows_sys::{ |
| 6 |
w, |
| 7 |
Win32::Foundation::{HANDLE, WIN32_ERROR}, |
| 8 |
}; |
| 9 |
|
| 10 |
#[derive(Debug)] |
| 11 |
pub struct RtPriorityHandleInternal { |
| 12 |
mmcss_task_index: u32, |
| 13 |
task_handle: HANDLE, |
| 14 |
} |
| 15 |
|
| 16 |
impl RtPriorityHandleInternal { |
| 17 |
fn new(mmcss_task_index: u32, task_handle: HANDLE) -> RtPriorityHandleInternal { |
| 18 |
RtPriorityHandleInternal { |
| 19 |
mmcss_task_index, |
| 20 |
task_handle, |
| 21 |
} |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
fn avrt() -> Result<&'static AvRtLibrary, AudioThreadPriorityError> { |
| 26 |
static AV_RT_LIBRARY: OnceLock<Result<AvRtLibrary, WIN32_ERROR>> = OnceLock::new(); |
| 27 |
AV_RT_LIBRARY |
| 28 |
.get_or_init(AvRtLibrary::try_new) |
| 29 |
.as_ref() |
| 30 |
.map_err(|win32_error| { |
| 31 |
AudioThreadPriorityError::new(&format!("Unable to load avrt.dll ({win32_error})")) |
| 32 |
}) |
| 33 |
} |
| 34 |
|
| 35 |
pub fn promote_current_thread_to_real_time_internal( |
| 36 |
_audio_buffer_frames: u32, |
| 37 |
_audio_samplerate_hz: u32, |
| 38 |
) -> Result<RtPriorityHandleInternal, AudioThreadPriorityError> { |
| 39 |
avrt()? |
| 40 |
.set_mm_thread_characteristics(w!("Audio")) |
| 41 |
.map(|(mmcss_task_index, task_handle)| { |
| 42 |
info!("task {mmcss_task_index} bumped to real time priority."); |
| 43 |
RtPriorityHandleInternal::new(mmcss_task_index, task_handle) |
| 44 |
}) |
| 45 |
.map_err(|win32_error| { |
| 46 |
AudioThreadPriorityError::new(&format!( |
| 47 |
"Unable to bump the thread priority ({win32_error})" |
| 48 |
)) |
| 49 |
}) |
| 50 |
} |
| 51 |
|
| 52 |
pub fn demote_current_thread_from_real_time_internal( |
| 53 |
rt_priority_handle: RtPriorityHandleInternal, |
| 54 |
) -> Result<(), AudioThreadPriorityError> { |
| 55 |
let RtPriorityHandleInternal { |
| 56 |
mmcss_task_index, |
| 57 |
task_handle, |
| 58 |
} = rt_priority_handle; |
| 59 |
avrt()? |
| 60 |
.revert_mm_thread_characteristics(task_handle) |
| 61 |
.map(|_| { |
| 62 |
info!("task {mmcss_task_index} priority restored."); |
| 63 |
}) |
| 64 |
.map_err(|win32_error| { |
| 65 |
AudioThreadPriorityError::new(&format!( |
| 66 |
"Unable to restore the thread priority for task {mmcss_task_index} ({win32_error})" |
| 67 |
)) |
| 68 |
}) |
| 69 |
} |
| 70 |
|
| 71 |
mod avrt_lib { |
| 72 |
use super::win32_utils::{win32_error_if, OwnedLibrary}; |
| 73 |
use std::sync::Once; |
| 74 |
use windows_sys::{ |
| 75 |
core::PCWSTR, |
| 76 |
s, w, |
| 77 |
Win32::Foundation::{BOOL, FALSE, HANDLE, WIN32_ERROR}, |
| 78 |
}; |
| 79 |
|
| 80 |
type AvSetMmThreadCharacteristicsWFn = unsafe extern "system" fn(PCWSTR, *mut u32) -> HANDLE; |
| 81 |
type AvRevertMmThreadCharacteristicsFn = unsafe extern "system" fn(HANDLE) -> BOOL; |
| 82 |
|
| 83 |
#[derive(Debug)] |
| 84 |
pub(super) struct AvRtLibrary { |
| 85 |
// This field is never read because only used for its Drop behavior |
| 86 |
#[allow(dead_code)] |
| 87 |
module: OwnedLibrary, |
| 88 |
|
| 89 |
av_set_mm_thread_characteristics_w: AvSetMmThreadCharacteristicsWFn, |
| 90 |
av_revert_mm_thread_characteristics: AvRevertMmThreadCharacteristicsFn, |
| 91 |
} |
| 92 |
|
| 93 |
impl AvRtLibrary { |
| 94 |
pub(super) fn try_new() -> Result<Self, WIN32_ERROR> { |
| 95 |
let module = OwnedLibrary::try_new(w!("avrt.dll"))?; |
| 96 |
let av_set_mm_thread_characteristics_w = unsafe { |
| 97 |
std::mem::transmute::<_, AvSetMmThreadCharacteristicsWFn>( |
| 98 |
module.get_proc(s!("AvSetMmThreadCharacteristicsW"))?, |
| 99 |
) |
| 100 |
}; |
| 101 |
let av_revert_mm_thread_characteristics = unsafe { |
| 102 |
std::mem::transmute::<_, AvRevertMmThreadCharacteristicsFn>( |
| 103 |
module.get_proc(s!("AvRevertMmThreadCharacteristics"))?, |
| 104 |
) |
| 105 |
}; |
| 106 |
Ok(Self { |
| 107 |
module, |
| 108 |
av_set_mm_thread_characteristics_w, |
| 109 |
av_revert_mm_thread_characteristics, |
| 110 |
}) |
| 111 |
} |
| 112 |
|
| 113 |
pub(super) fn set_mm_thread_characteristics( |
| 114 |
&self, |
| 115 |
task_name: PCWSTR, |
| 116 |
) -> Result<(u32, HANDLE), WIN32_ERROR> { |
| 117 |
// Ensure that the first call never runs in parallel with other calls. This |
| 118 |
// seems necessary to guarantee the success of these other calls. We saw them |
| 119 |
// fail with an error code of ERROR_PATH_NOT_FOUND in tests, presumably on a |
| 120 |
// machine where the MMCSS service was initially inactive. |
| 121 |
static FIRST_CALL: Once = Once::new(); |
| 122 |
let mut first_call_result = None; |
| 123 |
FIRST_CALL.call_once(|| { |
| 124 |
first_call_result = Some(self.set_mm_thread_characteristics_internal(task_name)) |
| 125 |
}); |
| 126 |
first_call_result |
| 127 |
.unwrap_or_else(|| self.set_mm_thread_characteristics_internal(task_name)) |
| 128 |
} |
| 129 |
|
| 130 |
fn set_mm_thread_characteristics_internal( |
| 131 |
&self, |
| 132 |
task_name: PCWSTR, |
| 133 |
) -> Result<(u32, HANDLE), WIN32_ERROR> { |
| 134 |
let mut mmcss_task_index = 0u32; |
| 135 |
let task_handle = unsafe { |
| 136 |
(self.av_set_mm_thread_characteristics_w)(task_name, &mut mmcss_task_index) |
| 137 |
}; |
| 138 |
win32_error_if(task_handle == 0)?; |
| 139 |
Ok((mmcss_task_index, task_handle)) |
| 140 |
} |
| 141 |
|
| 142 |
pub(super) fn revert_mm_thread_characteristics( |
| 143 |
&self, |
| 144 |
handle: HANDLE, |
| 145 |
) -> Result<(), WIN32_ERROR> { |
| 146 |
let rv = unsafe { (self.av_revert_mm_thread_characteristics)(handle) }; |
| 147 |
win32_error_if(rv == FALSE) |
| 148 |
} |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
mod win32_utils { |
| 153 |
use windows_sys::{ |
| 154 |
core::{PCSTR, PCWSTR}, |
| 155 |
Win32::{ |
| 156 |
Foundation::{FreeLibrary, GetLastError, HMODULE, WIN32_ERROR}, |
| 157 |
System::LibraryLoader::{GetProcAddress, LoadLibraryW}, |
| 158 |
}, |
| 159 |
}; |
| 160 |
|
| 161 |
pub(super) fn win32_error_if(condition: bool) -> Result<(), WIN32_ERROR> { |
| 162 |
if condition { |
| 163 |
Err(unsafe { GetLastError() }) |
| 164 |
} else { |
| 165 |
Ok(()) |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
#[derive(Debug)] |
| 170 |
pub(super) struct OwnedLibrary(HMODULE); |
| 171 |
|
| 172 |
impl OwnedLibrary { |
| 173 |
pub(super) fn try_new(lib_file_name: PCWSTR) -> Result<Self, WIN32_ERROR> { |
| 174 |
let module = unsafe { LoadLibraryW(lib_file_name) }; |
| 175 |
win32_error_if(module == 0)?; |
| 176 |
Ok(Self(module)) |
| 177 |
} |
| 178 |
|
| 179 |
fn raw(&self) -> HMODULE { |
| 180 |
self.0 |
| 181 |
} |
| 182 |
|
| 183 |
/// SAFETY: The caller must transmute the value wrapped in a Ok(_) to the correct |
| 184 |
/// function type, with the correct extern specifier. |
| 185 |
pub(super) unsafe fn get_proc( |
| 186 |
&self, |
| 187 |
proc_name: PCSTR, |
| 188 |
) -> Result<unsafe extern "system" fn() -> isize, WIN32_ERROR> { |
| 189 |
let proc = unsafe { GetProcAddress(self.raw(), proc_name) }; |
| 190 |
win32_error_if(proc.is_none())?; |
| 191 |
Ok(proc.unwrap()) |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
impl Drop for OwnedLibrary { |
| 196 |
fn drop(&mut self) { |
| 197 |
unsafe { |
| 198 |
FreeLibrary(self.raw()); |
| 199 |
} |
| 200 |
} |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
#[cfg(test)] |
| 205 |
mod tests { |
| 206 |
use super::{ |
| 207 |
avrt, demote_current_thread_from_real_time_internal, |
| 208 |
promote_current_thread_to_real_time_internal, |
| 209 |
}; |
| 210 |
|
| 211 |
#[test] |
| 212 |
fn test_successful_avrt_library_load() { |
| 213 |
assert!(avrt().is_ok()) |
| 214 |
} |
| 215 |
|
| 216 |
#[test] |
| 217 |
fn test_successful_api_use() { |
| 218 |
let handle = promote_current_thread_to_real_time_internal(512, 44100); |
| 219 |
println!("handle: {handle:?}"); |
| 220 |
assert!(handle.is_ok()); |
| 221 |
|
| 222 |
let result = demote_current_thread_from_real_time_internal(handle.unwrap()); |
| 223 |
println!("result: {result:?}"); |
| 224 |
assert!(result.is_ok()); |
| 225 |
} |
| 226 |
} |