├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── atp_test.cpp ├── audio_thread_priority.h ├── generate_osx_bindings.sh └── src ├── lib.rs ├── mach_sys.rs ├── rt_linux.rs ├── rt_mach.rs └── rt_win.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | rust: [stable, nightly] 11 | os: [ubuntu-20.04, windows-2019, macos-10.15] 12 | type: [Release, Debug] 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | 17 | - name: Install Rust 18 | run: rustup toolchain install ${{ matrix.rust }} --profile minimal --component rustfmt clippy 19 | 20 | - name: Install Dependencies (Linux) 21 | run: sudo apt-get update && sudo apt-get install libpulse-dev pulseaudio libdbus-1-dev 22 | if: matrix.os == 'ubuntu-20.04' 23 | 24 | - name: Check format 25 | shell: bash 26 | run: rustup run ${{ matrix.rust }} cargo fmt -- --check 27 | 28 | - name: Clippy 29 | shell: bash 30 | run: rustup run ${{ matrix.rust }} cargo clippy -- -D warnings 31 | 32 | - name: Build 33 | shell: bash 34 | run: rustup run ${{ matrix.rust }} cargo build --all 35 | 36 | - name: Test 37 | shell: bash 38 | run: rustup run ${{ matrix.rust }} cargo test --all 39 | if: matrix.os != 'ubuntu-20.04' # setrlimit64 error in the CI container 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | atp_test 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "audio_thread_priority" 3 | version = "0.33.0" 4 | authors = ["Paul Adenot "] 5 | description = "Bump a thread to real-time priority, for audio work, on Linux, Windows and macOS" 6 | license = "MPL-2.0" 7 | repository = "https://github.com/padenot/audio_thread_priority" 8 | edition = "2018" 9 | 10 | [lib] 11 | crate-type = ["staticlib", "rlib"] 12 | name = "audio_thread_priority" 13 | 14 | [dependencies] 15 | cfg-if = "1.0" 16 | log = "0.4" 17 | simple_logger = { version = "0.4", optional = true } 18 | 19 | [dev-dependencies] 20 | nix = "0.26" 21 | 22 | [features] 23 | terminal-logging = ["simple_logger"] 24 | with_dbus = ["dbus"] 25 | default = ["with_dbus"] 26 | 27 | [target.'cfg(target_os = "macos")'.dependencies] 28 | mach2 = "0.4" 29 | libc = "0.2" 30 | 31 | [target.'cfg(target_os = "windows")'.dependencies.windows-sys] 32 | version = "0.59" 33 | features = [ 34 | "Win32_Foundation", 35 | "Win32_System_LibraryLoader", 36 | ] 37 | 38 | [target.'cfg(target_os = "linux")'.dependencies] 39 | libc = "0.2" 40 | 41 | [target.'cfg(target_os = "linux")'.dependencies.dbus] 42 | version = "0.6.4" 43 | optional = true 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | 375 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: target/debug/libaudio_thread_priority.a 2 | g++ atp_test.cpp target/debug/libaudio_thread_priority.a -I. -lpthread -ldbus-1 -ldl -g -o atp_test 3 | 4 | check: 5 | @./atp_test && echo "test passed" || echo "test failed" 6 | 7 | target/debug/libaudio_thread_priority.a: 8 | cargo build 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # audio_thread_priority 2 | 3 | [![](https://img.shields.io/crates/v/audio_thread_priority.svg)](https://crates.io/crates/audio_thread_priority) 4 | [![](https://docs.rs/audio_thread_priority/badge.svg)](https://docs.rs/audio_thread_priority) 5 | 6 | 7 | Synopsis: 8 | 9 | ```rust 10 | 11 | use audio_thread_priority::{promote_current_thread_to_real_time, demote_current_thread_from_real_time}; 12 | 13 | // ... on a thread that will compute audio and has to be real-time: 14 | match promote_current_thread_to_real_time(512, 44100) { 15 | Ok(h) => { 16 | println!("this thread is now bumped to real-time priority."); 17 | 18 | // Do some real-time work... 19 | 20 | match demote_current_thread_from_real_time(h) { 21 | Ok(_) => { 22 | println!("this thread is now bumped back to normal.") 23 | } 24 | Err(_) => { 25 | println!("Could not bring the thread back to normal priority.") 26 | } 27 | }; 28 | } 29 | Err(e) => { 30 | eprintln!("Error promoting thread to real-time: {}", e); 31 | } 32 | } 33 | 34 | ``` 35 | 36 | This library can also be used from C or C++ using the included header and 37 | compiling the rust code in the application. By default, a `.a` is compiled to 38 | ease linking. 39 | 40 | # License 41 | 42 | MPL-2 43 | 44 | -------------------------------------------------------------------------------- /atp_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "audio_thread_priority.h" 7 | 8 | int main() { 9 | #ifdef __linux__ 10 | atp_thread_info* info = atp_get_current_thread_info(); 11 | atp_thread_info* info2 = nullptr; 12 | 13 | uint8_t buffer[ATP_THREAD_INFO_SIZE]; 14 | atp_serialize_thread_info(info, buffer); 15 | 16 | info2 = atp_deserialize_thread_info(buffer); 17 | 18 | int rv = memcmp(info, info2, ATP_THREAD_INFO_SIZE); 19 | 20 | assert(!rv); 21 | 22 | atp_free_thread_info(info); 23 | atp_free_thread_info(info2); 24 | 25 | rv = atp_set_real_time_limit(0, 44100); 26 | assert(!rv); 27 | #endif 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /audio_thread_priority.h: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 | * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | #ifndef AUDIO_THREAD_PRIORITY_H 6 | #define AUDIO_THREAD_PRIORITY_H 7 | 8 | #include 9 | #include 10 | 11 | /** 12 | * An opaque structure containing information about a thread that was promoted 13 | * to real-time priority. 14 | */ 15 | struct atp_handle; 16 | struct atp_thread_info; 17 | extern size_t ATP_THREAD_INFO_SIZE; 18 | 19 | #ifdef __cplusplus 20 | extern "C" { 21 | #endif // __cplusplus 22 | 23 | /** 24 | * Promotes the current thread to real-time priority. 25 | * 26 | * audio_buffer_frames: number of frames per audio buffer. If unknown, passing 0 27 | * will choose an appropriate number, conservatively. If variable, either pass 0 28 | * or an upper bound. 29 | * audio_samplerate_hz: sample-rate for this audio stream, in Hz 30 | * 31 | * Returns an opaque handle in case of success, NULL otherwise. 32 | */ 33 | atp_handle *atp_promote_current_thread_to_real_time(uint32_t audio_buffer_frames, 34 | uint32_t audio_samplerate_hz); 35 | 36 | 37 | /** 38 | * Demotes the current thread promoted to real-time priority via 39 | * `atp_demote_current_thread_from_real_time` to its previous priority. 40 | * 41 | * Returns 0 in case of success, non-zero otherwise. 42 | */ 43 | int32_t atp_demote_current_thread_from_real_time(atp_handle *handle); 44 | 45 | /** 46 | * Frees an atp_handle. This is useful when it impractical to call 47 | *`atp_demote_current_thread_from_real_time` on the right thread. Access to the 48 | * handle must be synchronized externaly (or the related thread must have 49 | * exited). 50 | * 51 | * Returns 0 in case of success, non-zero otherwise. 52 | */ 53 | int32_t atp_free_handle(atp_handle *handle); 54 | 55 | /* 56 | * Linux-only API. 57 | * 58 | * The Linux backend uses DBUS to promote a thread to real-time priority. In 59 | * environment where this is not possible (due to sandboxing), this set of 60 | * functions allow remoting the call to a process that can make DBUS calls. 61 | * 62 | * To do so: 63 | * - Set the real-time limit from within the process where a 64 | * thread will be promoted. This is a `setrlimit` call, that can be done 65 | * before the sandbox lockdown. 66 | * - Then, gather information on the thread that will be promoted. 67 | * - Serialize this info. 68 | * - Send over the serialized data via an IPC mechanism 69 | * - Deserialize the inf 70 | * - Call `atp_promote_thread_to_real_time` 71 | */ 72 | 73 | #ifdef __linux__ 74 | /** 75 | * Promotes a thread, possibly in another process, to real-time priority. 76 | * 77 | * thread_info: info on the thread to promote, gathered with 78 | * `atp_get_current_thread_info()`, called on the thread itself. 79 | * audio_buffer_frames: number of frames per audio buffer. If unknown, passing 0 80 | * will choose an appropriate number, conservatively. If variable, either pass 0 81 | * or an upper bound. 82 | * audio_samplerate_hz: sample-rate for this audio stream, in Hz 83 | * 84 | * Returns an opaque handle in case of success, NULL otherwise. 85 | * 86 | * This call is useful on Linux desktop only, when the process is sandboxed and 87 | * cannot promote itself directly. 88 | */ 89 | atp_handle *atp_promote_thread_to_real_time(atp_thread_info *thread_info); 90 | 91 | /** 92 | * Demotes a thread promoted to real-time priority via 93 | * `atp_demote_thread_from_real_time` to its previous priority. 94 | * 95 | * Returns 0 in case of success, non-zero otherwise. 96 | * 97 | * This call is useful on Linux desktop only, when the process is sandboxed and 98 | * cannot promote itself directly. 99 | */ 100 | int32_t atp_demote_thread_from_real_time(atp_thread_info* thread_info); 101 | 102 | /** 103 | * Gather informations from the calling thread, to be able to promote it from 104 | * another thread and/or process. 105 | * 106 | * Returns a non-null pointer to an `atp_thread_info` structure in case of 107 | * sucess, to be freed later with `atp_free_thread_info`, and NULL otherwise. 108 | * 109 | * This call is useful on Linux desktop only, when the process is sandboxed and 110 | * cannot promote itself directly. 111 | */ 112 | atp_thread_info *atp_get_current_thread_info(); 113 | 114 | /** 115 | * Free an `atp_thread_info` structure. 116 | * 117 | * Returns 0 in case of success, non-zero in case of error (because thread_info 118 | * was NULL). 119 | */ 120 | int32_t atp_free_thread_info(atp_thread_info *thread_info); 121 | 122 | /** 123 | * Serialize an `atp_thread_info` to a byte buffer that is 124 | * sizeof(atp_thread_info) long. 125 | */ 126 | void atp_serialize_thread_info(atp_thread_info *thread_info, uint8_t *bytes); 127 | 128 | /** 129 | * Deserialize a byte buffer of sizeof(atp_thread_info) to an `atp_thread_info` 130 | * pointer. It can be then freed using atp_free_thread_info. 131 | * */ 132 | atp_thread_info* atp_deserialize_thread_info(uint8_t *bytes); 133 | 134 | /** 135 | * Set real-time limit for the calling process. 136 | * 137 | * This is useful only on Linux desktop, and allows remoting the rtkit DBUS call 138 | * to a process that has access to DBUS. This function has to be called before 139 | * attempting to promote threads from another process. 140 | * 141 | * This sets the real-time computation limit. For actually promoting the thread 142 | * to a real-time scheduling class, see `atp_promote_thread_to_real_time`. 143 | */ 144 | int32_t atp_set_real_time_limit(uint32_t audio_buffer_frames, 145 | uint32_t audio_samplerate_hz); 146 | 147 | #endif // __linux__ 148 | 149 | #ifdef __cplusplus 150 | } // extern "C" 151 | #endif // __cplusplus 152 | 153 | #endif // AUDIO_THREAD_PRIORITY_H 154 | -------------------------------------------------------------------------------- /generate_osx_bindings.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | bindgen /usr/include/mach/thread_policy.h --no-layout-tests --whitelist-type "(thread_policy_flavor_t|thread_policy_t|thread_extended_policy_data_t|thread_time_constraint_policy_data_t|thread_precedence_policy_data_t|thread_t)" --whitelist-var "(THREAD_TIME_CONSTRAINT_POLICY|THREAD_EXTENDED_POLICY|THREAD_PRECEDENCE_POLICY)" > src/mach_sys.rs 4 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 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>, 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) -> 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 mach2; 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::(); 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 { 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 { 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 { 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::(); 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 { 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::()] { 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::()], 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()` 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::()]); 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`, 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 { 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`, 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 { 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::()]; 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 | } 745 | -------------------------------------------------------------------------------- /src/mach_sys.rs: -------------------------------------------------------------------------------- 1 | /* automatically generated by rust-bindgen */ 2 | 3 | pub const THREAD_EXTENDED_POLICY: u32 = 1; 4 | pub const THREAD_TIME_CONSTRAINT_POLICY: u32 = 2; 5 | pub const THREAD_PRECEDENCE_POLICY: u32 = 3; 6 | pub type __darwin_natural_t = ::std::os::raw::c_uint; 7 | pub type __darwin_mach_port_name_t = __darwin_natural_t; 8 | pub type __darwin_mach_port_t = __darwin_mach_port_name_t; 9 | pub type boolean_t = ::std::os::raw::c_uint; 10 | pub type natural_t = __darwin_natural_t; 11 | pub type integer_t = ::std::os::raw::c_int; 12 | pub type mach_port_t = __darwin_mach_port_t; 13 | pub type thread_t = mach_port_t; 14 | pub type thread_policy_flavor_t = natural_t; 15 | pub type thread_policy_t = *mut integer_t; 16 | #[repr(C)] 17 | #[derive(Debug, Copy, Clone)] 18 | pub struct thread_extended_policy { 19 | pub timeshare: boolean_t, 20 | } 21 | pub type thread_extended_policy_data_t = thread_extended_policy; 22 | #[repr(C)] 23 | #[derive(Debug, Copy, Clone)] 24 | pub struct thread_time_constraint_policy { 25 | pub period: u32, 26 | pub computation: u32, 27 | pub constraint: u32, 28 | pub preemptible: boolean_t, 29 | } 30 | pub type thread_time_constraint_policy_data_t = thread_time_constraint_policy; 31 | #[repr(C)] 32 | #[derive(Debug, Copy, Clone)] 33 | pub struct thread_precedence_policy { 34 | pub importance: integer_t, 35 | } 36 | pub type thread_precedence_policy_data_t = thread_precedence_policy; 37 | -------------------------------------------------------------------------------- /src/rt_linux.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 | * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | /* Widely copied from dbus-rs/dbus/examples/rtkit.rs */ 6 | 7 | extern crate dbus; 8 | extern crate libc; 9 | 10 | use std::cmp; 11 | use std::convert::TryInto; 12 | use std::error::Error; 13 | use std::io::Error as OSError; 14 | 15 | use dbus::{BusType, Connection, Message, MessageItem, Props}; 16 | 17 | use crate::AudioThreadPriorityError; 18 | 19 | const DBUS_SOCKET_TIMEOUT: i32 = 10_000; 20 | const RT_PRIO_DEFAULT: u32 = 10; 21 | // This is different from libc::pid_t, which is 32 bits, and is defined in sys/types.h. 22 | #[allow(non_camel_case_types)] 23 | type kernel_pid_t = libc::c_long; 24 | 25 | impl From for AudioThreadPriorityError { 26 | fn from(error: dbus::Error) -> Self { 27 | AudioThreadPriorityError::new(&format!( 28 | "{}:{}", 29 | error.name().unwrap_or("?"), 30 | error.message().unwrap_or("?") 31 | )) 32 | } 33 | } 34 | 35 | impl From> for AudioThreadPriorityError { 36 | fn from(error: Box) -> Self { 37 | AudioThreadPriorityError::new(&error.to_string()) 38 | } 39 | } 40 | 41 | #[repr(C)] 42 | #[derive(Clone, Copy)] 43 | pub struct RtPriorityThreadInfoInternal { 44 | /// System-wise thread id, use to promote the thread via dbus. 45 | thread_id: kernel_pid_t, 46 | /// Process-local thread id, used to restore scheduler characteristics. This information is not 47 | /// useful in another process, but is useful tied to the `thread_id`, when back into the first 48 | /// process. 49 | pthread_id: libc::pthread_t, 50 | /// The PID of the process containing `thread_id` below. 51 | pid: libc::pid_t, 52 | /// ... 53 | policy: libc::c_int, 54 | } 55 | 56 | impl RtPriorityThreadInfoInternal { 57 | /// Serialize a RtPriorityThreadInfoInternal to a byte buffer. 58 | pub fn serialize(&self) -> [u8; std::mem::size_of::()] { 59 | unsafe { std::mem::transmute::()]>(*self) } 60 | } 61 | /// Get an RtPriorityThreadInfoInternal from a byte buffer. 62 | pub fn deserialize(bytes: [u8; std::mem::size_of::()]) -> Self { 63 | unsafe { std::mem::transmute::<[u8; std::mem::size_of::()], Self>(bytes) } 64 | } 65 | } 66 | 67 | impl PartialEq for RtPriorityThreadInfoInternal { 68 | fn eq(&self, other: &Self) -> bool { 69 | self.thread_id == other.thread_id && self.pthread_id == other.pthread_id 70 | } 71 | } 72 | 73 | /*#[derive(Debug)]*/ 74 | pub struct RtPriorityHandleInternal { 75 | thread_info: RtPriorityThreadInfoInternal, 76 | } 77 | 78 | fn item_as_i64(i: MessageItem) -> Result { 79 | match i { 80 | MessageItem::Int32(i) => Ok(i as i64), 81 | MessageItem::Int64(i) => Ok(i), 82 | _ => Err(AudioThreadPriorityError::new(&format!( 83 | "Property is not integer ({:?})", 84 | i 85 | ))), 86 | } 87 | } 88 | 89 | fn rtkit_set_realtime(thread: u64, pid: u64, prio: u32) -> Result<(), Box> { 90 | let m = if unsafe { libc::getpid() as u64 } == pid { 91 | let mut m = Message::new_method_call( 92 | "org.freedesktop.RealtimeKit1", 93 | "/org/freedesktop/RealtimeKit1", 94 | "org.freedesktop.RealtimeKit1", 95 | "MakeThreadRealtime", 96 | )?; 97 | m.append_items(&[thread.into(), prio.into()]); 98 | m 99 | } else { 100 | let mut m = Message::new_method_call( 101 | "org.freedesktop.RealtimeKit1", 102 | "/org/freedesktop/RealtimeKit1", 103 | "org.freedesktop.RealtimeKit1", 104 | "MakeThreadRealtimeWithPID", 105 | )?; 106 | m.append_items(&[pid.into(), thread.into(), prio.into()]); 107 | m 108 | }; 109 | let c = Connection::get_private(BusType::System)?; 110 | c.send_with_reply_and_block(m, DBUS_SOCKET_TIMEOUT)?; 111 | Ok(()) 112 | } 113 | 114 | /// Returns the maximum priority, maximum real-time time slice, and the current real-time time 115 | /// slice for this process. 116 | fn get_limits() -> Result<(i64, u64, libc::rlimit), AudioThreadPriorityError> { 117 | let c = Connection::get_private(BusType::System)?; 118 | 119 | let p = Props::new( 120 | &c, 121 | "org.freedesktop.RealtimeKit1", 122 | "/org/freedesktop/RealtimeKit1", 123 | "org.freedesktop.RealtimeKit1", 124 | DBUS_SOCKET_TIMEOUT, 125 | ); 126 | let mut current_limit = libc::rlimit { 127 | rlim_cur: 0, 128 | rlim_max: 0, 129 | }; 130 | 131 | let max_prio = item_as_i64(p.get("MaxRealtimePriority")?)?; 132 | if max_prio < 0 { 133 | return Err(AudioThreadPriorityError::new( 134 | "invalid negative MaxRealtimePriority", 135 | )); 136 | } 137 | 138 | let max_rttime = item_as_i64(p.get("RTTimeUSecMax")?)?; 139 | if max_rttime < 0 { 140 | return Err(AudioThreadPriorityError::new( 141 | "invalid negative RTTimeUSecMax", 142 | )); 143 | } 144 | 145 | if unsafe { libc::getrlimit(libc::RLIMIT_RTTIME, &mut current_limit) } < 0 { 146 | return Err(AudioThreadPriorityError::new_with_inner( 147 | "getrlimit", 148 | Box::new(OSError::last_os_error()), 149 | )); 150 | } 151 | 152 | Ok((max_prio, (max_rttime as u64), current_limit)) 153 | } 154 | 155 | fn set_limits(request: u64, max: u64) -> Result<(), AudioThreadPriorityError> { 156 | // Set a soft limit to the limit requested, to be able to handle going over the limit using 157 | // SIGXCPU. Set the hard limit to the maximum slice to prevent getting SIGKILL. 158 | #[allow(clippy::useless_conversion)] 159 | let new_limit = libc::rlimit { 160 | rlim_cur: request 161 | .try_into() 162 | .map_err(|_| AudioThreadPriorityError::new("setrlimit"))?, 163 | rlim_max: max 164 | .try_into() 165 | .map_err(|_| AudioThreadPriorityError::new("setrlimit"))?, 166 | }; 167 | if unsafe { libc::setrlimit(libc::RLIMIT_RTTIME, &new_limit) } < 0 { 168 | return Err(AudioThreadPriorityError::new_with_inner( 169 | "setrlimit", 170 | Box::new(OSError::last_os_error()), 171 | )); 172 | } 173 | 174 | Ok(()) 175 | } 176 | 177 | pub fn promote_current_thread_to_real_time_internal( 178 | audio_buffer_frames: u32, 179 | audio_samplerate_hz: u32, 180 | ) -> Result { 181 | let thread_info = get_current_thread_info_internal()?; 182 | promote_thread_to_real_time_internal(thread_info, audio_buffer_frames, audio_samplerate_hz) 183 | } 184 | 185 | pub fn demote_current_thread_from_real_time_internal( 186 | rt_priority_handle: RtPriorityHandleInternal, 187 | ) -> Result<(), AudioThreadPriorityError> { 188 | assert!(unsafe { libc::pthread_self() } == rt_priority_handle.thread_info.pthread_id); 189 | 190 | let param = unsafe { std::mem::zeroed::() }; 191 | 192 | if unsafe { 193 | libc::pthread_setschedparam( 194 | rt_priority_handle.thread_info.pthread_id, 195 | rt_priority_handle.thread_info.policy, 196 | ¶m, 197 | ) 198 | } < 0 199 | { 200 | return Err(AudioThreadPriorityError::new_with_inner( 201 | "could not demote thread", 202 | Box::new(OSError::last_os_error()), 203 | )); 204 | } 205 | Ok(()) 206 | } 207 | 208 | /// This can be called by sandboxed code, it only restores priority to what they were. 209 | pub fn demote_thread_from_real_time_internal( 210 | thread_info: RtPriorityThreadInfoInternal, 211 | ) -> Result<(), AudioThreadPriorityError> { 212 | let param = unsafe { std::mem::zeroed::() }; 213 | 214 | // https://github.com/rust-lang/libc/issues/1511 215 | const SCHED_RESET_ON_FORK: libc::c_int = 0x40000000; 216 | 217 | if unsafe { 218 | libc::pthread_setschedparam( 219 | thread_info.pthread_id, 220 | libc::SCHED_OTHER | SCHED_RESET_ON_FORK, 221 | ¶m, 222 | ) 223 | } < 0 224 | { 225 | return Err(AudioThreadPriorityError::new_with_inner( 226 | "could not demote thread", 227 | Box::new(OSError::last_os_error()), 228 | )); 229 | } 230 | Ok(()) 231 | } 232 | 233 | /// Get the current thread information, as an opaque struct, that can be serialized and sent 234 | /// accross processes. This is enough to capture the current state of the scheduling policy, and 235 | /// an identifier to have another thread promoted to real-time. 236 | pub fn get_current_thread_info_internal( 237 | ) -> Result { 238 | let thread_id = unsafe { libc::syscall(libc::SYS_gettid) }; 239 | let pthread_id = unsafe { libc::pthread_self() }; 240 | let mut param = unsafe { std::mem::zeroed::() }; 241 | let mut policy = 0; 242 | 243 | if unsafe { libc::pthread_getschedparam(pthread_id, &mut policy, &mut param) } < 0 { 244 | return Err(AudioThreadPriorityError::new_with_inner( 245 | "pthread_getschedparam", 246 | Box::new(OSError::last_os_error()), 247 | )); 248 | } 249 | 250 | let pid = unsafe { libc::getpid() }; 251 | 252 | Ok(RtPriorityThreadInfoInternal { 253 | pid, 254 | thread_id, 255 | pthread_id, 256 | policy, 257 | }) 258 | } 259 | 260 | /// This set the RLIMIT_RTTIME resource to something other than "unlimited". It's necessary for the 261 | /// rtkit request to succeed, and needs to hapen in the child. We can't get the real limit here, 262 | /// because we don't have access to DBUS, so it is hardcoded to 200ms, which is the default in the 263 | /// rtkit package. 264 | pub fn set_real_time_hard_limit_internal( 265 | audio_buffer_frames: u32, 266 | audio_samplerate_hz: u32, 267 | ) -> Result<(), AudioThreadPriorityError> { 268 | let buffer_frames = if audio_buffer_frames > 0 { 269 | audio_buffer_frames 270 | } else { 271 | // 50ms slice. This "ought to be enough for anybody". 272 | audio_samplerate_hz / 20 273 | }; 274 | let budget_us = buffer_frames as u64 * 1_000_000 / audio_samplerate_hz as u64; 275 | 276 | // It's only necessary to set RLIMIT_RTTIME to something when in the child, skip it if it's a 277 | // remoting call. 278 | let (_, max_rttime, _) = get_limits()?; 279 | 280 | // Only take what we need, or cap at the system limit, no further. 281 | let rttime_request = cmp::min(budget_us, max_rttime); 282 | set_limits(rttime_request, max_rttime)?; 283 | 284 | Ok(()) 285 | } 286 | 287 | /// Promote a thread (possibly in another process) identified by its tid, to real-time. 288 | pub fn promote_thread_to_real_time_internal( 289 | thread_info: RtPriorityThreadInfoInternal, 290 | audio_buffer_frames: u32, 291 | audio_samplerate_hz: u32, 292 | ) -> Result { 293 | let RtPriorityThreadInfoInternal { pid, thread_id, .. } = thread_info; 294 | 295 | let handle = RtPriorityHandleInternal { thread_info }; 296 | 297 | set_real_time_hard_limit_internal(audio_buffer_frames, audio_samplerate_hz)?; 298 | 299 | let r = rtkit_set_realtime(thread_id as u64, pid as u64, RT_PRIO_DEFAULT); 300 | 301 | match r { 302 | Ok(_) => Ok(handle), 303 | Err(e) => { 304 | let (_, _, limits) = get_limits()?; 305 | if limits.rlim_cur != libc::RLIM_INFINITY 306 | && unsafe { libc::setrlimit(libc::RLIMIT_RTTIME, &limits) } < 0 307 | { 308 | return Err(AudioThreadPriorityError::new_with_inner( 309 | "setrlimit", 310 | Box::new(OSError::last_os_error()), 311 | )); 312 | } 313 | Err(AudioThreadPriorityError::new_with_inner( 314 | "Thread promotion error", 315 | e, 316 | )) 317 | } 318 | } 319 | } 320 | -------------------------------------------------------------------------------- /src/rt_mach.rs: -------------------------------------------------------------------------------- 1 | use crate::mach_sys::*; 2 | use crate::AudioThreadPriorityError; 3 | use libc::{pthread_self, pthread_t}; 4 | use log::info; 5 | use mach2::kern_return::{kern_return_t, KERN_SUCCESS}; 6 | use mach2::mach_time::{mach_timebase_info, mach_timebase_info_data_t}; 7 | use mach2::message::mach_msg_type_number_t; 8 | use mach2::port::mach_port_t; 9 | use std::mem::size_of; 10 | 11 | extern "C" { 12 | fn pthread_mach_thread_np(tid: pthread_t) -> mach_port_t; 13 | // Those functions are commented out in thread_policy.h but somehow it works just fine !? 14 | fn thread_policy_set( 15 | thread: thread_t, 16 | flavor: thread_policy_flavor_t, 17 | policy_info: thread_policy_t, 18 | count: mach_msg_type_number_t, 19 | ) -> kern_return_t; 20 | fn thread_policy_get( 21 | thread: thread_t, 22 | flavor: thread_policy_flavor_t, 23 | policy_info: thread_policy_t, 24 | count: &mut mach_msg_type_number_t, 25 | get_default: &mut boolean_t, 26 | ) -> kern_return_t; 27 | } 28 | 29 | // can't use size_of in const fn just now in stable, use a macro for now. 30 | macro_rules! THREAD_TIME_CONSTRAINT_POLICY_COUNT { 31 | () => { 32 | (size_of::() / size_of::()) as u32 33 | }; 34 | } 35 | 36 | #[derive(Debug)] 37 | pub struct RtPriorityHandleInternal { 38 | tid: mach_port_t, 39 | previous_time_constraint_policy: thread_time_constraint_policy_data_t, 40 | } 41 | 42 | impl Default for RtPriorityHandleInternal { 43 | fn default() -> Self { 44 | Self::new() 45 | } 46 | } 47 | 48 | impl RtPriorityHandleInternal { 49 | pub fn new() -> RtPriorityHandleInternal { 50 | RtPriorityHandleInternal { 51 | tid: 0, 52 | previous_time_constraint_policy: thread_time_constraint_policy_data_t { 53 | period: 0, 54 | computation: 0, 55 | constraint: 0, 56 | preemptible: 0, 57 | }, 58 | } 59 | } 60 | } 61 | 62 | pub fn demote_current_thread_from_real_time_internal( 63 | rt_priority_handle: RtPriorityHandleInternal, 64 | ) -> Result<(), AudioThreadPriorityError> { 65 | unsafe { 66 | let mut h = rt_priority_handle; 67 | let rv: kern_return_t = thread_policy_set( 68 | h.tid, 69 | THREAD_TIME_CONSTRAINT_POLICY, 70 | (&mut h.previous_time_constraint_policy) as *mut _ as thread_policy_t, 71 | THREAD_TIME_CONSTRAINT_POLICY_COUNT!(), 72 | ); 73 | if rv != KERN_SUCCESS { 74 | return Err(AudioThreadPriorityError::new( 75 | "thread demotion error: thread_policy_get: RT", 76 | )); 77 | } 78 | 79 | info!("thread {} priority restored.", h.tid); 80 | } 81 | 82 | Ok(()) 83 | } 84 | 85 | pub fn promote_current_thread_to_real_time_internal( 86 | audio_buffer_frames: u32, 87 | audio_samplerate_hz: u32, 88 | ) -> Result { 89 | let mut rt_priority_handle = RtPriorityHandleInternal::new(); 90 | 91 | let buffer_frames = if audio_buffer_frames > 0 { 92 | audio_buffer_frames 93 | } else { 94 | audio_samplerate_hz / 20 95 | }; 96 | 97 | unsafe { 98 | let tid: mach_port_t = pthread_mach_thread_np(pthread_self()); 99 | let mut time_constraints = thread_time_constraint_policy_data_t { 100 | period: 0, 101 | computation: 0, 102 | constraint: 0, 103 | preemptible: 0, 104 | }; 105 | 106 | // Get current thread attributes, to revert back to the correct setting later if needed. 107 | rt_priority_handle.tid = tid; 108 | 109 | // false: we want to get the current value, not the default value. If this is `false` after 110 | // returning, it means there are no current settings because of other factor, and the 111 | // default was returned instead. 112 | let mut get_default: boolean_t = 0; 113 | let mut count: mach_msg_type_number_t = THREAD_TIME_CONSTRAINT_POLICY_COUNT!(); 114 | let mut rv: kern_return_t = thread_policy_get( 115 | tid, 116 | THREAD_TIME_CONSTRAINT_POLICY, 117 | (&mut time_constraints) as *mut _ as thread_policy_t, 118 | &mut count, 119 | &mut get_default, 120 | ); 121 | 122 | if rv != KERN_SUCCESS { 123 | return Err(AudioThreadPriorityError::new( 124 | "thread promotion error: thread_policy_get: time_constraint", 125 | )); 126 | } 127 | 128 | rt_priority_handle.previous_time_constraint_policy = time_constraints; 129 | 130 | let cb_duration = buffer_frames as f32 / (audio_samplerate_hz as f32) * 1000.; 131 | // The multiplicators are somwhat arbitrary for now. 132 | 133 | let mut timebase_info = mach_timebase_info_data_t { denom: 0, numer: 0 }; 134 | mach_timebase_info(&mut timebase_info); 135 | 136 | let ms2abs: f32 = ((timebase_info.denom as f32) / timebase_info.numer as f32) * 1000000.; 137 | 138 | // Computation time is half of constraint, per macOS 12 behaviour. 139 | time_constraints = thread_time_constraint_policy_data_t { 140 | period: (cb_duration * ms2abs) as u32, 141 | computation: (cb_duration / 2.0 * ms2abs) as u32, 142 | constraint: (cb_duration * ms2abs) as u32, 143 | preemptible: 1, // true 144 | }; 145 | 146 | rv = thread_policy_set( 147 | tid, 148 | THREAD_TIME_CONSTRAINT_POLICY, 149 | (&mut time_constraints) as *mut _ as thread_policy_t, 150 | THREAD_TIME_CONSTRAINT_POLICY_COUNT!(), 151 | ); 152 | if rv != KERN_SUCCESS { 153 | return Err(AudioThreadPriorityError::new( 154 | "thread promotion error: thread_policy_set: time_constraint", 155 | )); 156 | } 157 | 158 | info!("thread {} bumped to real time priority.", tid); 159 | } 160 | 161 | Ok(rt_priority_handle) 162 | } 163 | -------------------------------------------------------------------------------- /src/rt_win.rs: -------------------------------------------------------------------------------- 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> = 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 { 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 { 95 | let module = OwnedLibrary::try_new(w!("avrt.dll"))?; 96 | let av_set_mm_thread_characteristics_w = unsafe { 97 | std::mem::transmute::< 98 | unsafe extern "system" fn() -> isize, 99 | AvSetMmThreadCharacteristicsWFn, 100 | >(module.get_proc(s!("AvSetMmThreadCharacteristicsW"))?) 101 | }; 102 | let av_revert_mm_thread_characteristics = unsafe { 103 | std::mem::transmute::< 104 | unsafe extern "system" fn() -> isize, 105 | AvRevertMmThreadCharacteristicsFn, 106 | >(module.get_proc(s!("AvRevertMmThreadCharacteristics"))?) 107 | }; 108 | Ok(Self { 109 | module, 110 | av_set_mm_thread_characteristics_w, 111 | av_revert_mm_thread_characteristics, 112 | }) 113 | } 114 | 115 | pub(super) fn set_mm_thread_characteristics( 116 | &self, 117 | task_name: PCWSTR, 118 | ) -> Result<(u32, HANDLE), WIN32_ERROR> { 119 | // Ensure that the first call never runs in parallel with other calls. This 120 | // seems necessary to guarantee the success of these other calls. We saw them 121 | // fail with an error code of ERROR_PATH_NOT_FOUND in tests, presumably on a 122 | // machine where the MMCSS service was initially inactive. 123 | static FIRST_CALL: Once = Once::new(); 124 | let mut first_call_result = None; 125 | FIRST_CALL.call_once(|| { 126 | first_call_result = Some(self.set_mm_thread_characteristics_internal(task_name)) 127 | }); 128 | first_call_result 129 | .unwrap_or_else(|| self.set_mm_thread_characteristics_internal(task_name)) 130 | } 131 | 132 | fn set_mm_thread_characteristics_internal( 133 | &self, 134 | task_name: PCWSTR, 135 | ) -> Result<(u32, HANDLE), WIN32_ERROR> { 136 | let mut mmcss_task_index = 0u32; 137 | let task_handle = unsafe { 138 | (self.av_set_mm_thread_characteristics_w)(task_name, &mut mmcss_task_index) 139 | }; 140 | win32_error_if(task_handle.is_null())?; 141 | Ok((mmcss_task_index, task_handle)) 142 | } 143 | 144 | pub(super) fn revert_mm_thread_characteristics( 145 | &self, 146 | handle: HANDLE, 147 | ) -> Result<(), WIN32_ERROR> { 148 | let rv = unsafe { (self.av_revert_mm_thread_characteristics)(handle) }; 149 | win32_error_if(rv == FALSE) 150 | } 151 | } 152 | } 153 | 154 | mod win32_utils { 155 | use windows_sys::{ 156 | core::{PCSTR, PCWSTR}, 157 | Win32::{ 158 | Foundation::{FreeLibrary, GetLastError, HMODULE, WIN32_ERROR}, 159 | System::LibraryLoader::{GetProcAddress, LoadLibraryW}, 160 | }, 161 | }; 162 | 163 | pub(super) fn win32_error_if(condition: bool) -> Result<(), WIN32_ERROR> { 164 | if condition { 165 | Err(unsafe { GetLastError() }) 166 | } else { 167 | Ok(()) 168 | } 169 | } 170 | 171 | #[derive(Debug)] 172 | pub(super) struct OwnedLibrary(HMODULE); 173 | 174 | impl OwnedLibrary { 175 | pub(super) fn try_new(lib_file_name: PCWSTR) -> Result { 176 | let module = unsafe { LoadLibraryW(lib_file_name) }; 177 | win32_error_if(module.is_null())?; 178 | Ok(Self(module)) 179 | } 180 | 181 | fn raw(&self) -> HMODULE { 182 | self.0 183 | } 184 | 185 | /// SAFETY: The caller must transmute the value wrapped in a Ok(_) to the correct 186 | /// function type, with the correct extern specifier. 187 | pub(super) unsafe fn get_proc( 188 | &self, 189 | proc_name: PCSTR, 190 | ) -> Result isize, WIN32_ERROR> { 191 | let proc = unsafe { GetProcAddress(self.raw(), proc_name) }; 192 | win32_error_if(proc.is_none())?; 193 | Ok(proc.unwrap()) 194 | } 195 | } 196 | 197 | impl Drop for OwnedLibrary { 198 | fn drop(&mut self) { 199 | unsafe { 200 | FreeLibrary(self.raw()); 201 | } 202 | } 203 | } 204 | 205 | unsafe impl Send for OwnedLibrary {} 206 | unsafe impl Sync for OwnedLibrary {} 207 | } 208 | 209 | #[cfg(test)] 210 | mod tests { 211 | use super::{ 212 | avrt, demote_current_thread_from_real_time_internal, 213 | promote_current_thread_to_real_time_internal, 214 | }; 215 | 216 | #[test] 217 | fn test_successful_avrt_library_load() { 218 | assert!(avrt().is_ok()) 219 | } 220 | 221 | #[test] 222 | fn test_successful_api_use() { 223 | let handle = promote_current_thread_to_real_time_internal(512, 44100); 224 | println!("handle: {handle:?}"); 225 | assert!(handle.is_ok()); 226 | 227 | let result = demote_current_thread_from_real_time_internal(handle.unwrap()); 228 | println!("result: {result:?}"); 229 | assert!(result.is_ok()); 230 | } 231 | } 232 | --------------------------------------------------------------------------------