├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE.txt ├── LICENSE-MIT.txt ├── README.md └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libretro-backend" 3 | version = "0.2.1" 4 | authors = ["Jan Bujak "] 5 | license = "MIT/Apache-2.0" 6 | readme = "README.md" 7 | repository = "https://github.com/koute/libretro-backend" 8 | homepage = "https://github.com/koute/libretro-backend" 9 | description = """ 10 | Idiomatic Rust API bindings to the libretro API 11 | """ 12 | 13 | [dependencies] 14 | "libc" = "0.2" 15 | "libretro-sys" = "0.1" 16 | 17 | [profile.dev] 18 | panic = "abort" 19 | 20 | [profile.release] 21 | panic = "abort" 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Jan Bujak 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Jan Bujak 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Libretro API bindings for Rust 2 | 3 | [![Documentation](https://docs.rs/libretro-backend/badge.svg)](https://docs.rs/libretro-backend/*/libretro_backend/) 4 | 5 | This crate exposes idiomatic Rust API bindings to the excellent [libretro] API. 6 | 7 | The target audience of this library are emulator authors who want to turn 8 | their emulator into a libretro core, which relieves them from the necessity of 9 | creating a full blown frontend for their emulator and allows them to concentrate 10 | on actual emulation. 11 | 12 | In its current state there is still **a lot** of features missing, nevertheless 13 | it should be useful enough to create a basic emulator. 14 | 15 | As always, contributions are welcome! 16 | 17 | [libretro]: http://www.libretro.com/index.php/api/ 18 | 19 | ## Getting started 20 | 21 | Add this to your `Cargo.toml`: 22 | 23 | ```toml 24 | [lib] 25 | crate-type = ["cdylib"] 26 | 27 | [dependencies] 28 | libretro-backend = "0.2" 29 | ``` 30 | 31 | and this to your crate root: 32 | 33 | ```rust 34 | #[macro_use] 35 | extern crate libretro_backend; 36 | ``` 37 | 38 | then just implement the [Core trait]: 39 | 40 | ```rust 41 | struct Emulator { 42 | // ... 43 | } 44 | 45 | impl libretro_backend::Core for Emulator { 46 | // ... 47 | } 48 | ``` 49 | 50 | and use a macro: 51 | 52 | ```rust 53 | libretro_core!( Emulator ); 54 | ``` 55 | 56 | For a full example you can check out [this file], which is part of my NES 57 | emulator [Pinky]. 58 | 59 | [Core trait]: https://docs.rs/libretro-backend/*/libretro_backend/trait.Core.html 60 | [this file]: https://github.com/koute/pinky/blob/master/pinky-libretro/src/lib.rs 61 | [Pinky]: https://github.com/koute/pinky 62 | 63 | ## License 64 | 65 | Licensed under either of 66 | 67 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 68 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 69 | 70 | at your option. 71 | 72 | ### Contribution 73 | 74 | Unless you explicitly state otherwise, any contribution intentionally submitted 75 | for inclusion in the work by you, as defined in the Apache-2.0 license, 76 | shall be dual licensed as above, without any additional terms or conditions. 77 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[doc(hidden)] 2 | pub extern crate libc; 3 | #[doc(hidden)] 4 | pub extern crate libretro_sys; 5 | 6 | use std::mem; 7 | use std::ptr; 8 | use std::slice; 9 | use std::ffi::{CStr, CString}; 10 | use std::cmp::max; 11 | 12 | pub use libretro_sys::{PixelFormat, Region}; 13 | 14 | pub struct CoreInfo { 15 | library_name: CString, 16 | library_version: CString, 17 | supported_romfile_extensions: CString, 18 | require_path_when_loading_roms: bool, 19 | allow_frontend_to_extract_archives: bool 20 | } 21 | 22 | impl CoreInfo { 23 | pub fn new( name: &str, version: &str ) -> CoreInfo { 24 | CoreInfo { 25 | library_name: CString::new( name ).unwrap(), 26 | library_version: CString::new( version ).unwrap(), 27 | supported_romfile_extensions: CString::new( "" ).unwrap(), 28 | require_path_when_loading_roms: false, 29 | allow_frontend_to_extract_archives: true 30 | } 31 | } 32 | 33 | pub fn supports_roms_with_extension( mut self, mut extension: &str ) -> Self { 34 | if extension.starts_with( "." ) { 35 | extension = &extension[ 1.. ]; 36 | } 37 | 38 | let mut string = CString::new( "" ).unwrap(); 39 | mem::swap( &mut string, &mut self.supported_romfile_extensions ); 40 | 41 | let mut vec = string.into_bytes(); 42 | if vec.is_empty() == false { 43 | vec.push( '|' as u8 ); 44 | } 45 | 46 | vec.extend_from_slice( extension.as_bytes() ); 47 | 48 | match extension { 49 | "gz" | "xz" | 50 | "zip" | "rar" | "7z" | "tar" | "tgz" | "txz" | "bz2" | 51 | "tar.gz" | "tar.bz2"| "tar.xz" => { 52 | self.allow_frontend_to_extract_archives = false; 53 | }, 54 | _ => {} 55 | } 56 | 57 | self.supported_romfile_extensions = CString::new( vec ).unwrap(); 58 | self 59 | } 60 | 61 | pub fn requires_path_when_loading_roms( mut self ) -> Self { 62 | self.require_path_when_loading_roms = true; 63 | self 64 | } 65 | } 66 | 67 | pub struct AudioVideoInfo { 68 | width: u32, 69 | height: u32, 70 | max_width: u32, 71 | max_height: u32, 72 | frames_per_second: f64, 73 | audio_sample_rate: f64, 74 | aspect_ratio: Option< f32 >, 75 | pixel_format: PixelFormat, 76 | game_region: Option< Region > 77 | } 78 | 79 | impl AudioVideoInfo { 80 | pub fn new() -> AudioVideoInfo { 81 | AudioVideoInfo { 82 | width: 0, 83 | height: 0, 84 | max_width: 0, 85 | max_height: 0, 86 | frames_per_second: 0.0, 87 | aspect_ratio: None, 88 | pixel_format: PixelFormat::RGB565, 89 | audio_sample_rate: 0.0, 90 | game_region: None 91 | } 92 | } 93 | 94 | pub fn video( mut self, width: u32, height: u32, frames_per_second: f64, pixel_format: PixelFormat ) -> Self { 95 | self.width = width; 96 | self.height = height; 97 | self.max_width = max( self.max_width, width ); 98 | self.max_height = max( self.max_height, height ); 99 | self.frames_per_second = frames_per_second; 100 | self.pixel_format = pixel_format; 101 | self 102 | } 103 | 104 | pub fn max_video_size( mut self, max_width: u32, max_height: u32 ) -> Self { 105 | self.max_width = max( self.max_width, max_width ); 106 | self.max_height = max( self.max_height, max_height ); 107 | self 108 | } 109 | 110 | pub fn aspect_ratio( mut self, aspect_ratio: f32 ) -> Self { 111 | self.aspect_ratio = Some( aspect_ratio ); 112 | self 113 | } 114 | 115 | pub fn audio( mut self, sample_rate: f64 ) -> Self { 116 | self.audio_sample_rate = sample_rate; 117 | self 118 | } 119 | 120 | pub fn region( mut self, game_region: Region ) -> Self { 121 | self.game_region = Some( game_region ); 122 | self 123 | } 124 | 125 | fn infer_game_region( &self ) -> Region { 126 | self.game_region.unwrap_or_else( || { 127 | if self.frames_per_second > 59.0 { 128 | Region::NTSC 129 | } else { 130 | Region::PAL 131 | } 132 | }) 133 | } 134 | } 135 | 136 | pub struct GameData { 137 | path: Option< String >, 138 | 139 | // The 'static lifetime here is a lie, but it's safe anyway 140 | // since the user doesn't get direct access to this reference, 141 | // and he has to give us a GameData object back in on_unload_game, 142 | // and since we're the only source of those he has to give us 143 | // the one that he got in on_load_game. 144 | data: Option< &'static [u8] > 145 | } 146 | 147 | impl GameData { 148 | pub fn path( &self ) -> Option< &str > { 149 | self.path.as_ref().map( |path| &path[..] ) 150 | } 151 | 152 | pub fn data( &self ) -> Option< &[u8] > { 153 | self.data.map( |data| data as &[u8] ) 154 | } 155 | 156 | pub fn is_empty( &self ) -> bool { 157 | self.path().is_none() && self.data().is_none() 158 | } 159 | } 160 | 161 | pub enum LoadGameResult { 162 | Success( AudioVideoInfo ), 163 | Failed( GameData ) 164 | } 165 | 166 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 167 | pub enum JoypadButton { 168 | A, 169 | B, 170 | X, 171 | Y, 172 | Select, 173 | Start, 174 | Up, 175 | Down, 176 | Left, 177 | Right, 178 | L1, 179 | L2, 180 | L3, 181 | R1, 182 | R2, 183 | R3 184 | } 185 | 186 | pub trait Core: Default { 187 | fn info() -> CoreInfo; 188 | fn on_load_game( &mut self, game_data: GameData ) -> LoadGameResult; 189 | fn on_unload_game( &mut self ) -> GameData; 190 | fn on_run( &mut self, handle: &mut RuntimeHandle ); 191 | fn on_reset( &mut self ); 192 | fn save_memory( &mut self ) -> Option< &mut [u8] > { 193 | None 194 | } 195 | fn rtc_memory( &mut self ) -> Option< &mut [u8] > { 196 | None 197 | } 198 | fn system_memory( &mut self ) -> Option< &mut [u8] > { 199 | None 200 | } 201 | fn video_memory( &mut self ) -> Option< &mut [u8] > { 202 | None 203 | } 204 | } 205 | 206 | static mut ENVIRONMENT_CALLBACK: Option< libretro_sys::EnvironmentFn > = None; 207 | 208 | #[doc(hidden)] 209 | pub struct Retro< B: Core > { 210 | video_refresh_callback: Option< libretro_sys::VideoRefreshFn >, 211 | audio_sample_callback: Option< libretro_sys::AudioSampleFn >, 212 | audio_sample_batch_callback: Option< libretro_sys::AudioSampleBatchFn >, 213 | input_poll_callback: Option< libretro_sys::InputPollFn >, 214 | input_state_callback: Option< libretro_sys::InputStateFn >, 215 | 216 | core: B, 217 | 218 | is_game_loaded: bool, 219 | av_info: AudioVideoInfo, 220 | total_audio_samples_uploaded: usize 221 | } 222 | 223 | macro_rules! set_callback { 224 | ($output: expr, $input: expr) => ( 225 | unsafe { 226 | if $input == mem::transmute( 0 as usize ) { 227 | $output = None; 228 | } else { 229 | $output = Some( $input ); 230 | } 231 | } 232 | ) 233 | } 234 | 235 | impl< B: Core > Retro< B > { 236 | fn new( core: B ) -> Self { 237 | Retro { 238 | video_refresh_callback: None, 239 | audio_sample_callback: None, 240 | audio_sample_batch_callback: None, 241 | input_poll_callback: None, 242 | input_state_callback: None, 243 | 244 | core: core, 245 | 246 | is_game_loaded: false, 247 | av_info: AudioVideoInfo::new(), 248 | total_audio_samples_uploaded: 0 249 | } 250 | } 251 | 252 | #[must_use] 253 | unsafe fn call_environment< T >( &mut self, command: libc::c_uint, pointer: &T ) -> Result< (), () > { 254 | let ok = ENVIRONMENT_CALLBACK.unwrap()( command, mem::transmute( pointer ) ); 255 | if ok { 256 | Ok(()) 257 | } else { 258 | Err(()) 259 | } 260 | } 261 | 262 | pub fn on_get_system_info( info: *mut libretro_sys::SystemInfo ) { 263 | assert_ne!( info, ptr::null_mut() ); 264 | let info = unsafe { &mut *info }; 265 | 266 | // Pointers in SystemInfo have to be statically allocated, 267 | // which is why we do this. 268 | static mut INFO: Option< *const CoreInfo > = None; 269 | let core_info = unsafe { 270 | if INFO.is_none() { 271 | INFO = Some( Box::into_raw( Box::new( B::info() ) ) ); 272 | } 273 | INFO.map( |core_info| &*core_info ).unwrap() 274 | }; 275 | 276 | info.library_name = core_info.library_name.as_ptr(); 277 | info.library_version = core_info.library_version.as_ptr(); 278 | info.valid_extensions = core_info.supported_romfile_extensions.as_ptr(); 279 | info.need_fullpath = core_info.require_path_when_loading_roms; 280 | info.block_extract = core_info.allow_frontend_to_extract_archives == false; 281 | } 282 | 283 | pub fn on_set_environment( callback: libretro_sys::EnvironmentFn ) { 284 | set_callback!( ENVIRONMENT_CALLBACK, callback ); 285 | } 286 | 287 | pub fn on_set_video_refresh( &mut self, callback: libretro_sys::VideoRefreshFn ) { 288 | set_callback!( self.video_refresh_callback, callback ); 289 | } 290 | 291 | pub fn on_set_audio_sample( &mut self, callback: libretro_sys::AudioSampleFn ) { 292 | set_callback!( self.audio_sample_callback, callback ); 293 | } 294 | 295 | pub fn on_set_audio_sample_batch( &mut self, callback: libretro_sys::AudioSampleBatchFn ) { 296 | set_callback!( self.audio_sample_batch_callback, callback ); 297 | } 298 | 299 | pub fn on_set_input_poll( &mut self, callback: libretro_sys::InputPollFn ) { 300 | set_callback!( self.input_poll_callback, callback ); 301 | } 302 | 303 | pub fn on_set_input_state( &mut self, callback: libretro_sys::InputStateFn ) { 304 | set_callback!( self.input_state_callback, callback ); 305 | } 306 | 307 | pub fn on_get_system_av_info( &mut self, info: *mut libretro_sys::SystemAvInfo ) { 308 | assert_ne!( info, ptr::null_mut() ); 309 | let info = unsafe { &mut *info }; 310 | 311 | info.geometry.base_width = self.av_info.width as libc::c_uint; 312 | info.geometry.base_height = self.av_info.height as libc::c_uint; 313 | info.geometry.max_width = self.av_info.max_width as libc::c_uint; 314 | info.geometry.max_height = self.av_info.max_height as libc::c_uint; 315 | info.geometry.aspect_ratio = self.av_info.aspect_ratio.unwrap_or( 0.0 ); 316 | info.timing.fps = self.av_info.frames_per_second; 317 | info.timing.sample_rate = self.av_info.audio_sample_rate; 318 | } 319 | 320 | pub fn on_set_controller_port_device( &mut self, _port: libc::c_uint, _device: libc::c_uint ) { 321 | } 322 | 323 | pub fn on_reset( &mut self ) { 324 | self.core.on_reset(); 325 | } 326 | 327 | pub fn on_load_game( &mut self, game_info: *const libretro_sys::GameInfo ) -> bool { 328 | assert_eq!( self.is_game_loaded, false ); 329 | 330 | let game_info = if game_info == ptr::null() { 331 | None 332 | } else { 333 | Some( unsafe { &*game_info } ) 334 | }; 335 | 336 | let game_data = match game_info { 337 | Some( game_info ) => { 338 | let path = if game_info.path == ptr::null() { 339 | None 340 | } else { 341 | unsafe { 342 | CStr::from_ptr( game_info.path ).to_str().ok().map( |path| path.to_owned() ) 343 | } 344 | }; 345 | 346 | let data = if game_info.data == ptr::null() && game_info.size == 0 { 347 | None 348 | } else { 349 | unsafe { 350 | Some( slice::from_raw_parts( game_info.data as *const u8, game_info.size ) ) 351 | } 352 | }; 353 | 354 | GameData { 355 | path: path, 356 | data: data 357 | } 358 | }, 359 | None => { 360 | GameData { 361 | path: None, 362 | data: None 363 | } 364 | } 365 | }; 366 | 367 | let result = self.core.on_load_game( game_data ); 368 | match result { 369 | LoadGameResult::Success( av_info ) => { 370 | self.av_info = av_info; 371 | unsafe { 372 | let pixel_format = self.av_info.pixel_format; 373 | self.call_environment( libretro_sys::ENVIRONMENT_SET_PIXEL_FORMAT, &pixel_format ).unwrap(); 374 | } 375 | 376 | self.is_game_loaded = true; 377 | true 378 | }, 379 | LoadGameResult::Failed( _ ) => false 380 | } 381 | } 382 | 383 | pub fn on_load_game_special( &mut self, _game_type: libc::c_uint, _info: *const libretro_sys::GameInfo, _num_info: libc::size_t ) -> bool { 384 | false 385 | } 386 | 387 | pub fn on_run( &mut self ) { 388 | let mut handle = RuntimeHandle { 389 | video_refresh_callback: self.video_refresh_callback.unwrap(), 390 | input_state_callback: self.input_state_callback.unwrap(), 391 | audio_sample_batch_callback: self.audio_sample_batch_callback.unwrap(), 392 | upload_video_frame_already_called: false, 393 | audio_samples_uploaded: 0, 394 | 395 | video_width: self.av_info.width, 396 | video_height: self.av_info.height, 397 | video_frame_bytes_per_pixel: match self.av_info.pixel_format { 398 | PixelFormat::ARGB1555 | PixelFormat::RGB565 => 2, 399 | PixelFormat::ARGB8888 => 4 400 | } 401 | }; 402 | 403 | unsafe { 404 | self.input_poll_callback.unwrap()(); 405 | } 406 | 407 | self.core.on_run( &mut handle ); 408 | 409 | self.total_audio_samples_uploaded += handle.audio_samples_uploaded; 410 | let required_audio_sample_count_per_frame = (self.av_info.audio_sample_rate / self.av_info.frames_per_second) * 2.0; 411 | assert!( 412 | self.total_audio_samples_uploaded as f64 >= required_audio_sample_count_per_frame, 413 | format!( "You need to upload at least {} audio samples each frame!", required_audio_sample_count_per_frame ) 414 | ); 415 | 416 | self.total_audio_samples_uploaded -= required_audio_sample_count_per_frame as usize; 417 | } 418 | 419 | pub fn on_serialize_size( &mut self ) -> libc::size_t { 420 | 0 421 | } 422 | 423 | pub fn on_serialize( &mut self, _data: *mut libc::c_void, _size: libc::size_t ) -> bool { 424 | false 425 | } 426 | 427 | pub fn on_unserialize( &mut self, _data: *const libc::c_void, _size: libc::size_t ) -> bool { 428 | false 429 | } 430 | 431 | pub fn on_cheat_reset( &mut self ) { 432 | } 433 | 434 | pub fn on_cheat_set( &mut self, _index: libc::c_uint, _is_enabled: bool, _code: *const libc::c_char ) { 435 | } 436 | 437 | pub fn on_unload_game( &mut self ) { 438 | if self.is_game_loaded == false { 439 | return; 440 | } 441 | 442 | let _ = self.core.on_unload_game(); 443 | } 444 | 445 | pub fn on_get_region( &mut self ) -> libc::c_uint { 446 | self.av_info.infer_game_region().to_uint() 447 | } 448 | 449 | fn memory_data( &mut self, id: libc::c_uint ) -> Option< &mut [u8] > { 450 | match id { 451 | libretro_sys::MEMORY_SAVE_RAM => self.core.save_memory(), 452 | libretro_sys::MEMORY_RTC => self.core.rtc_memory(), 453 | libretro_sys::MEMORY_SYSTEM_RAM => self.core.system_memory(), 454 | libretro_sys::MEMORY_VIDEO_RAM => self.core.video_memory(), 455 | _ => unreachable!(), 456 | } 457 | } 458 | 459 | pub fn on_get_memory_data( &mut self, id: libc::c_uint ) -> *mut libc::c_void { 460 | self.memory_data( id ) 461 | .map( |d| d as *mut _ as *mut libc::c_void ) 462 | .unwrap_or( ptr::null_mut() ) 463 | } 464 | 465 | pub fn on_get_memory_size( &mut self, id: libc::c_uint ) -> libc::size_t { 466 | self.memory_data( id ) 467 | .map( |d| d.len() as libc::size_t ) 468 | .unwrap_or( 0 ) 469 | } 470 | } 471 | 472 | pub struct RuntimeHandle { 473 | video_refresh_callback: libretro_sys::VideoRefreshFn, 474 | input_state_callback: libretro_sys::InputStateFn, 475 | audio_sample_batch_callback: libretro_sys::AudioSampleBatchFn, 476 | upload_video_frame_already_called: bool, 477 | audio_samples_uploaded: usize, 478 | 479 | video_width: u32, 480 | video_height: u32, 481 | video_frame_bytes_per_pixel: u32 482 | } 483 | 484 | impl RuntimeHandle { 485 | pub fn upload_video_frame( &mut self, data: &[u8] ) { 486 | assert!( self.upload_video_frame_already_called == false, "You can only call upload_video_frame() once per frame!" ); 487 | assert!( data.len() as u32 >= self.video_width * self.video_height * self.video_frame_bytes_per_pixel, "Data too small to upload!" ); 488 | 489 | self.upload_video_frame_already_called = true; 490 | let bytes = data.as_ptr() as *const libc::c_void; 491 | let width = self.video_width as libc::c_uint; 492 | let height = self.video_height as libc::c_uint; 493 | let bytes_per_line = (self.video_width * self.video_frame_bytes_per_pixel) as usize; 494 | unsafe { 495 | (self.video_refresh_callback)( bytes, width, height, bytes_per_line ); 496 | } 497 | } 498 | 499 | pub fn upload_audio_frame( &mut self, data: &[i16] ) { 500 | assert!( data.len() % 2 == 0, "Audio data must be in stereo!" ); 501 | 502 | self.audio_samples_uploaded += data.len(); 503 | unsafe { 504 | (self.audio_sample_batch_callback)( data.as_ptr(), data.len() / 2 ); 505 | } 506 | } 507 | 508 | pub fn is_joypad_button_pressed( &mut self, port: u32, button: JoypadButton ) -> bool { 509 | let device_id = match button { 510 | JoypadButton::A => libretro_sys::DEVICE_ID_JOYPAD_A, 511 | JoypadButton::B => libretro_sys::DEVICE_ID_JOYPAD_B, 512 | JoypadButton::X => libretro_sys::DEVICE_ID_JOYPAD_X, 513 | JoypadButton::Y => libretro_sys::DEVICE_ID_JOYPAD_Y, 514 | JoypadButton::Start => libretro_sys::DEVICE_ID_JOYPAD_START, 515 | JoypadButton::Select => libretro_sys::DEVICE_ID_JOYPAD_SELECT, 516 | JoypadButton::Left => libretro_sys::DEVICE_ID_JOYPAD_LEFT, 517 | JoypadButton::Right => libretro_sys::DEVICE_ID_JOYPAD_RIGHT, 518 | JoypadButton::Up => libretro_sys::DEVICE_ID_JOYPAD_UP, 519 | JoypadButton::Down => libretro_sys::DEVICE_ID_JOYPAD_DOWN, 520 | JoypadButton::L1 => libretro_sys::DEVICE_ID_JOYPAD_L, 521 | JoypadButton::L2 => libretro_sys::DEVICE_ID_JOYPAD_L2, 522 | JoypadButton::L3 => libretro_sys::DEVICE_ID_JOYPAD_L3, 523 | JoypadButton::R1 => libretro_sys::DEVICE_ID_JOYPAD_R, 524 | JoypadButton::R2 => libretro_sys::DEVICE_ID_JOYPAD_R2, 525 | JoypadButton::R3 => libretro_sys::DEVICE_ID_JOYPAD_R3 526 | }; 527 | 528 | unsafe { 529 | let value = (self.input_state_callback)( port, libretro_sys::DEVICE_JOYPAD, 0, device_id ); 530 | return value == 1; 531 | } 532 | } 533 | } 534 | 535 | #[doc(hidden)] 536 | pub fn construct< T: 'static + Core >() -> Retro< T > { 537 | Retro::new( T::default() ) 538 | } 539 | 540 | #[macro_export] 541 | macro_rules! libretro_core { 542 | ($core: path) => ( 543 | #[doc(hidden)] 544 | static mut LIBRETRO_INSTANCE: *mut $crate::Retro< $core > = 0 as *mut $crate::Retro< $core >; 545 | 546 | #[doc(hidden)] 547 | #[no_mangle] 548 | pub extern "C" fn retro_api_version() -> $crate::libc::c_uint { 549 | return $crate::libretro_sys::API_VERSION; 550 | } 551 | 552 | #[doc(hidden)] 553 | #[no_mangle] 554 | pub unsafe extern "C" fn retro_init() { 555 | assert_eq!( LIBRETRO_INSTANCE, 0 as *mut _ ); 556 | let retro = $crate::construct::< $core >(); 557 | LIBRETRO_INSTANCE = Box::into_raw( Box::new( retro ) ); 558 | } 559 | 560 | #[doc(hidden)] 561 | #[no_mangle] 562 | pub unsafe extern "C" fn retro_deinit() { 563 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 564 | let instance = Box::from_raw( LIBRETRO_INSTANCE ); 565 | LIBRETRO_INSTANCE = 0 as *mut _; 566 | ::std::mem::drop( instance ); 567 | } 568 | 569 | #[doc(hidden)] 570 | #[no_mangle] 571 | pub unsafe extern "C" fn retro_set_environment( callback: $crate::libretro_sys::EnvironmentFn ) { 572 | $crate::Retro::< $core >::on_set_environment( callback ) 573 | } 574 | 575 | #[doc(hidden)] 576 | #[no_mangle] 577 | pub unsafe extern "C" fn retro_set_video_refresh( callback: $crate::libretro_sys::VideoRefreshFn ) { 578 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 579 | (&mut *LIBRETRO_INSTANCE).on_set_video_refresh( callback ) 580 | } 581 | 582 | #[doc(hidden)] 583 | #[no_mangle] 584 | pub unsafe extern "C" fn retro_set_audio_sample( callback: $crate::libretro_sys::AudioSampleFn ) { 585 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 586 | (&mut *LIBRETRO_INSTANCE).on_set_audio_sample( callback ) 587 | } 588 | 589 | #[doc(hidden)] 590 | #[no_mangle] 591 | pub unsafe extern "C" fn retro_set_audio_sample_batch( callback: $crate::libretro_sys::AudioSampleBatchFn ) { 592 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 593 | (&mut *LIBRETRO_INSTANCE).on_set_audio_sample_batch( callback ) 594 | } 595 | 596 | #[doc(hidden)] 597 | #[no_mangle] 598 | pub unsafe extern "C" fn retro_set_input_poll( callback: $crate::libretro_sys::InputPollFn ) { 599 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 600 | (&mut *LIBRETRO_INSTANCE).on_set_input_poll( callback ) 601 | } 602 | 603 | #[doc(hidden)] 604 | #[no_mangle] 605 | pub unsafe extern "C" fn retro_set_input_state( callback: $crate::libretro_sys::InputStateFn ) { 606 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 607 | (&mut *LIBRETRO_INSTANCE).on_set_input_state( callback ) 608 | } 609 | 610 | #[doc(hidden)] 611 | #[no_mangle] 612 | pub extern "C" fn retro_get_system_info( info: *mut $crate::libretro_sys::SystemInfo ) { 613 | $crate::Retro::< $core >::on_get_system_info( info ) 614 | } 615 | 616 | #[doc(hidden)] 617 | #[no_mangle] 618 | pub unsafe extern "C" fn retro_get_system_av_info( info: *mut $crate::libretro_sys::SystemAvInfo ) { 619 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 620 | (&mut *LIBRETRO_INSTANCE).on_get_system_av_info( info ) 621 | } 622 | 623 | #[doc(hidden)] 624 | #[no_mangle] 625 | pub unsafe extern "C" fn retro_set_controller_port_device( port: $crate::libc::c_uint, device: $crate::libc::c_uint ) { 626 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 627 | (&mut *LIBRETRO_INSTANCE).on_set_controller_port_device( port, device ) 628 | } 629 | 630 | #[doc(hidden)] 631 | #[no_mangle] 632 | pub unsafe extern "C" fn retro_reset() { 633 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 634 | (&mut *LIBRETRO_INSTANCE).on_reset() 635 | } 636 | 637 | #[doc(hidden)] 638 | #[no_mangle] 639 | pub unsafe extern "C" fn retro_run() { 640 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 641 | (&mut *LIBRETRO_INSTANCE).on_run() 642 | } 643 | 644 | #[doc(hidden)] 645 | #[no_mangle] 646 | pub unsafe extern "C" fn retro_serialize_size() -> $crate::libc::size_t { 647 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 648 | (&mut *LIBRETRO_INSTANCE).on_serialize_size() 649 | } 650 | 651 | #[doc(hidden)] 652 | #[no_mangle] 653 | pub unsafe extern "C" fn retro_serialize( data: *mut $crate::libc::c_void, size: $crate::libc::size_t ) -> bool { 654 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 655 | (&mut *LIBRETRO_INSTANCE).on_serialize( data, size ) 656 | } 657 | 658 | #[doc(hidden)] 659 | #[no_mangle] 660 | pub unsafe extern "C" fn retro_unserialize( data: *const $crate::libc::c_void, size: $crate::libc::size_t ) -> bool { 661 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 662 | (&mut *LIBRETRO_INSTANCE).on_unserialize( data, size ) 663 | } 664 | 665 | #[doc(hidden)] 666 | #[no_mangle] 667 | pub unsafe extern "C" fn retro_cheat_reset() { 668 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 669 | (&mut *LIBRETRO_INSTANCE).on_cheat_reset() 670 | } 671 | 672 | #[doc(hidden)] 673 | #[no_mangle] 674 | pub unsafe extern "C" fn retro_cheat_set( index: $crate::libc::c_uint, is_enabled: bool, code: *const $crate::libc::c_char ) { 675 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 676 | (&mut *LIBRETRO_INSTANCE).on_cheat_set( index, is_enabled, code ) 677 | } 678 | 679 | #[doc(hidden)] 680 | #[no_mangle] 681 | pub unsafe extern "C" fn retro_load_game( game: *const $crate::libretro_sys::GameInfo ) -> bool { 682 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 683 | (&mut *LIBRETRO_INSTANCE).on_load_game( game ) 684 | } 685 | 686 | #[doc(hidden)] 687 | #[no_mangle] 688 | pub unsafe extern "C" fn retro_load_game_special( game_type: $crate::libc::c_uint, info: *const $crate::libretro_sys::GameInfo, num_info: $crate::libc::size_t ) -> bool { 689 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 690 | (&mut *LIBRETRO_INSTANCE).on_load_game_special( game_type, info, num_info ) 691 | } 692 | 693 | #[doc(hidden)] 694 | #[no_mangle] 695 | pub unsafe extern "C" fn retro_unload_game() { 696 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 697 | (&mut *LIBRETRO_INSTANCE).on_unload_game() 698 | } 699 | 700 | #[doc(hidden)] 701 | #[no_mangle] 702 | pub unsafe extern "C" fn retro_get_region() -> $crate::libc::c_uint { 703 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 704 | (&mut *LIBRETRO_INSTANCE).on_get_region() 705 | } 706 | 707 | #[doc(hidden)] 708 | #[no_mangle] 709 | pub unsafe extern "C" fn retro_get_memory_data( id: $crate::libc::c_uint ) -> *mut $crate::libc::c_void { 710 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 711 | (&mut *LIBRETRO_INSTANCE).on_get_memory_data( id ) 712 | } 713 | 714 | #[doc(hidden)] 715 | #[no_mangle] 716 | pub unsafe extern "C" fn retro_get_memory_size( id: $crate::libc::c_uint ) -> $crate::libc::size_t { 717 | assert_ne!( LIBRETRO_INSTANCE, 0 as *mut _ ); 718 | (&mut *LIBRETRO_INSTANCE).on_get_memory_size( id ) 719 | } 720 | ) 721 | } 722 | --------------------------------------------------------------------------------