logo
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
#![allow(clippy::missing_safety_doc)]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/max-m/rust-libretro/master/media/logo.png",
    html_favicon_url = "https://raw.githubusercontent.com/max-m/rust-libretro/master/media/favicon.png"
)]

mod core_wrapper;
#[cfg(feature = "log")]
mod logger;

pub mod contexts;
pub mod core;
pub mod environment;
pub mod types;
pub mod util;

pub use rust_libretro_proc as proc;
pub use rust_libretro_sys as sys;

use crate::{contexts::*, core::Core, core_wrapper::CoreWrapper, sys::*, types::*, util::*};
use std::{
    ffi::*,
    os::raw::c_char,
    path::{Path, PathBuf},
    sync::Arc,
};

#[doc(hidden)]
static mut RETRO_INSTANCE: Option<CoreWrapper> = None;

/// This macro must be used to initialize your [`Core`].
///
/// # Examples
/// ```rust
/// # use rust_libretro::{contexts::*, core::{Core, CoreOptions}, sys::*, types::*, retro_core};
/// # use std::ffi::CString;
/// struct ExampleCore {
///     option_1: bool,
///     option_2: bool,
///
///     pixels: [u8; 800 * 600 * 4],
///     timer: i64,
///     even: bool,
/// }
/// retro_core!(ExampleCore {
///     option_1: false,
///     option_2: true,
///
///     pixels: [0; 800 * 600 * 4],
///     timer: 5_000_001,
///     even: true,
/// });
///
/// /// Dummy implementation
/// impl CoreOptions for ExampleCore {}
/// impl Core for ExampleCore {
///     fn get_info(&self) -> SystemInfo {
///         SystemInfo {
///             library_name: CString::new("ExampleCore").unwrap(),
///             library_version: CString::new("1.0.0").unwrap(),
///             valid_extensions: CString::new("").unwrap(),
///             need_fullpath: false,
///             block_extract: false,
///         }
///     }
///     fn on_get_av_info(&mut self, _ctx: &mut GetAvInfoContext) -> retro_system_av_info {
///         retro_system_av_info {
///             geometry: retro_game_geometry {
///                 base_width: 800,
///                 base_height: 600,
///                 max_width: 800,
///                 max_height: 600,
///                 aspect_ratio: 0.0,
///             },
///             timing: retro_system_timing {
///                 fps: 60.0,
///                 sample_rate: 0.0,
///             },
///         }
///     }
///     fn on_init(&mut self, ctx: &mut InitContext) { }
/// }
/// ```
#[macro_export]
macro_rules! retro_core {
    ( $( $definition:tt )+ ) => {
        #[doc(hidden)]
        #[inline(never)]
        #[no_mangle]
        pub unsafe extern "Rust" fn __retro_init_core() {
            $crate::set_core($($definition)+);
        }
    }
}

#[doc(hidden)]
macro_rules! forward {
    ($(#[doc = $doc:tt ], )* $wrapper:ident, $name:ident, $handler:ident $(-> $return_type:ty)?, $($context:tt)+) => {
        #[no_mangle]
        $(#[doc = $doc])*
        pub unsafe extern "C" fn $name() $(-> $return_type)? {
            // Check that the instance has been created
            if let Some($wrapper) = RETRO_INSTANCE.as_mut() {
                // Forward to the Core implementation
                let mut ctx = $($context)+;
                return $wrapper.core.$handler(&mut ctx);
            }

            panic!(concat!(stringify!($name), ": Core has not been initialized yet!"));
        }
    };
}

#[doc(hidden)]
macro_rules! callback {
    ($(#[doc = $doc:tt ], )* $name:ident, $arg:ident, $handler:ident) => {
        #[no_mangle]
        $(#[doc = $doc])*
        pub unsafe extern "C" fn $name(arg1: $arg) {
            // Check that the instance has been created
            if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
                if arg1.is_some() {
                    // We were given a callback, make sure that it’s not a NULL pointer
                    if (arg1.unwrap() as *const c_void).is_null() {
                        panic!(concat!(
                            "Expected ",
                            stringify!($arg),
                            " got NULL pointer instead!"
                        ));
                    }
                }

                // The callback is safe to set. Either it’s None or not a NULL pointer
                return wrapper.$handler(arg1);
            }

            panic!(concat!(
                stringify!($name),
                ": Core has not been initialized yet!"
            ));
        }
    };
}

#[doc(hidden)]
pub fn set_core<C: 'static + Core>(core: C) {
    unsafe {
        if RETRO_INSTANCE.is_some() {
            let core = &RETRO_INSTANCE.as_ref().unwrap().core;
            let info = core.get_info();
            let name = info.library_name.into_string().unwrap();
            let version = info.library_version.into_string().unwrap();

            panic!("Attempted to set a core after the system was already initialized.\nAlready registered core: {} {}", name, version)
        }

        RETRO_INSTANCE.replace(CoreWrapper::new(core));
    }
}

#[cfg(feature = "log")]
#[doc(hidden)]
fn init_log(env_callback: retro_environment_t) {
    let retro_logger = unsafe { environment::get_log_callback(env_callback) };

    let retro_logger = if let Ok(Some(log_callback)) = retro_logger {
        logger::RetroLogger::new(log_callback)
    } else {
        logger::RetroLogger::new(retro_log_callback { log: None })
    };

    log::set_max_level(log::LevelFilter::Trace);
    log::set_boxed_logger(Box::new(retro_logger)).expect("could not set logger");
}

/*****************************************************************************\
|                              CORE API FUNCTIONS                             |
\*****************************************************************************/

forward!(
    #[doc = "Notifies the [`Core`] when all cheats should be unapplied."],
    wrapper,
    retro_cheat_reset,
    on_cheat_reset,
    GenericContext::new(&wrapper.environment_callback, Arc::clone(&wrapper.interfaces))
);
forward!(
    #[doc = "Notifies the [`Core`] when it is being closed and its resources should be freed."],
    wrapper,
    retro_deinit,
    on_deinit,
    GenericContext::new(&wrapper.environment_callback, Arc::clone(&wrapper.interfaces))
);
forward!(
    #[doc = "Called when the frontend needs region information from the [`Core`]."],
    #[doc = ""],
    #[doc = "## Note about RetroArch:"],
    #[doc = "RetroArch doesn’t use this interface anymore, because [`retro_get_system_av_info`] provides similar information."],
    wrapper,
    retro_get_region,
    on_get_region -> std::os::raw::c_uint,
    GenericContext::new(&wrapper.environment_callback, Arc::clone(&wrapper.interfaces))
);
forward!(
    #[doc = "Notifies the [`Core`] when the current game should be reset."],
    wrapper,
    retro_reset,
    on_reset,
    GenericContext::new(&wrapper.environment_callback, Arc::clone(&wrapper.interfaces))
);
forward!(
    #[doc = "Called when the frontend needs to know how large a buffer to allocate for save states."],
    #[doc = ""],
    #[doc = "See also [`rust_libretro_sys::retro_serialize_size`]."],
    wrapper,
    retro_serialize_size,
    get_serialize_size -> size_t,
    GenericContext::new(&wrapper.environment_callback, Arc::clone(&wrapper.interfaces))
);
forward!(
    #[doc = "Notifies the [`Core`] when the currently loaded game should be unloaded. Called before [`retro_deinit`]."],
    wrapper,
    retro_unload_game,
    on_unload_game,
    GenericContext::new(&wrapper.environment_callback, Arc::clone(&wrapper.interfaces))
);

callback!(
    #[doc = "Provides the audio sample callback to the [`Core`]."],
    #[doc = ""],
    #[doc = "Guaranteed to have been called before the first call to [`retro_run`] is made."],
    retro_set_audio_sample,
    retro_audio_sample_t,
    on_set_audio_sample
);
callback!(
    #[doc = "Provides the batched audio sample callback to the [`Core`]."],
    #[doc = ""],
    #[doc = "Guaranteed to have been called before the first call to [`retro_run`] is made."],
    retro_set_audio_sample_batch,
    retro_audio_sample_batch_t,
    on_set_audio_sample_batch
);
callback!(
    #[doc = "Provides the input polling callback to the [`Core`]."],
    #[doc = ""],
    #[doc = "Guaranteed to have been called before the first call to [`retro_run`] is made."],
    retro_set_input_poll,
    retro_input_poll_t,
    on_set_input_poll
);
callback!(
    #[doc = "Provides the input state request callback to the [`Core`]."],
    #[doc = ""],
    #[doc = "Guaranteed to have been called before the first call to [`retro_run`] is made."],
    retro_set_input_state,
    retro_input_state_t,
    on_set_input_state
);
callback!(
    #[doc = "Provides the frame drawing callback to the [`Core`]."],
    #[doc = ""],
    #[doc = "Guaranteed to have been called before the first call to [`retro_run`] is made."],
    retro_set_video_refresh,
    retro_video_refresh_t,
    on_set_video_refresh
);

/// Tells the frontend which API version this [`Core`] implements.
#[no_mangle]
pub unsafe extern "C" fn retro_api_version() -> std::os::raw::c_uint {
    #[cfg(feature = "log")]
    log::trace!("retro_api_version()");

    RETRO_API_VERSION
}

/// Initializes the [`Core`].
///
/// Called after the environment callbacks have been set.
#[no_mangle]
pub unsafe extern "C" fn retro_init() {
    #[cfg(feature = "log")]
    log::trace!("retro_init()");

    if let Some(mut wrapper) = RETRO_INSTANCE.as_mut() {
        wrapper.can_dupe = environment::can_dupe(wrapper.environment_callback);

        let mut ctx = InitContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper.core.on_init(&mut ctx);
    }

    panic!("retro_init: Core has not been initialized yet!");
}

/// Provides _statically known_ system info to the frontend.
///
/// See also [`rust_libretro_sys::retro_get_system_info`].
#[no_mangle]
pub unsafe extern "C" fn retro_get_system_info(info: *mut retro_system_info) {
    #[cfg(feature = "log")]
    log::trace!("retro_get_system_info(info = {info:#?})");

    // Make sure that the pointer we got is plausible
    if info.is_null() {
        panic!("Expected retro_system_info, got NULL pointer instead!");
    }

    // We didn’t get a NULL pointer, so this should be safe
    let info = &mut *info;

    // retro_get_system_info requires statically allocated data
    // This is unsafe because we mutate a static value.
    //
    // TODO: Should this be put behind an Arc<Mutex> or Arc<RwLock>?
    static mut SYS_INFO: Option<*const SystemInfo> = None;

    let sys_info = {
        if SYS_INFO.is_none() {
            extern "Rust" {
                fn __retro_init_core();
            }
            __retro_init_core();

            if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
                SYS_INFO = Some(Box::into_raw(Box::new(wrapper.core.get_info())));
            } else {
                panic!("No core instance found!");
            }
        }

        &*SYS_INFO.unwrap()
    };

    info.library_name = sys_info.library_name.as_ptr();
    info.library_version = sys_info.library_version.as_ptr();
    info.valid_extensions = sys_info.valid_extensions.as_ptr();
    info.need_fullpath = sys_info.need_fullpath;
    info.block_extract = sys_info.block_extract;
}

/// Provides audio/video timings and geometry info to the frontend.
///
/// Guaranteed to be called only after successful invocation of [`retro_load_game`].
///
/// See also [`rust_libretro_sys::retro_get_system_av_info`].
#[no_mangle]
pub unsafe extern "C" fn retro_get_system_av_info(info: *mut retro_system_av_info) {
    #[cfg(feature = "log")]
    log::trace!("retro_get_system_av_info(info = {info:#?})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        // Make sure that the pointer we got is plausible
        if info.is_null() {
            panic!("Expected retro_system_av_info, got NULL pointer instead!");
        }

        // We didn’t get a NULL pointer, so this should be safe
        let info = &mut *info;

        let mut ctx = GetAvInfoContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        let av_info = wrapper.core.on_get_av_info(&mut ctx);

        info.geometry = av_info.geometry;
        info.timing = av_info.timing;

        return;
    }

    panic!("retro_get_system_av_info: Core has not been initialized yet!");
}

/// Provides the environment callback to the [`Core`].
///
/// Guaranteed to have been called before [`retro_init`].
///
/// **TODO:** This method seems to get called multiple times by RetroArch
#[no_mangle]
pub unsafe extern "C" fn retro_set_environment(environment: retro_environment_t) {
    #[cfg(feature = "log")]
    log::trace!("retro_set_environment(environment = {environment:#?})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut initial = false;

        if let Some(callback) = environment {
            if !wrapper.environment_set {
                initial = true;
                wrapper.environment_set = true;

                #[cfg(feature = "log")]
                init_log(Some(callback));

                #[cfg(feature = "unstable-env-commands")]
                {
                    wrapper.supports_bitmasks = environment::get_input_bitmasks(Some(callback));
                }
            }

            wrapper.environment_callback.replace(callback);
        } else {
            wrapper.environment_callback.take();
        }

        let mut ctx = SetEnvironmentContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        // Our default implementation of `set_core_options` uses `RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION`,
        // which seems to only work on the first call to `retro_set_environment`.
        if initial && !wrapper.core.set_core_options(&ctx) {
            #[cfg(feature = "log")]
            log::warn!("Failed to set core options");
        }

        return wrapper.core.on_set_environment(initial, &mut ctx);
    }

    panic!("retro_set_environment: Core has not been initialized yet!");
}

/// Sets the device type to be used for player `port`.
///
/// See also [`rust_libretro_sys::retro_set_controller_port_device`].
#[no_mangle]
pub unsafe extern "C" fn retro_set_controller_port_device(
    port: std::os::raw::c_uint,
    device: std::os::raw::c_uint,
) {
    #[cfg(feature = "log")]
    log::trace!("retro_set_controller_port_device(port = {port}, device = {device})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper
            .core
            .on_set_controller_port_device(port, device, &mut ctx);
    }

    panic!("retro_set_controller_port_device: Core has not been initialized yet!");
}

/// Runs the game for one frame.
///
/// See also [`rust_libretro_sys::retro_run`].
#[no_mangle]
pub unsafe extern "C" fn retro_run() {
    #[cfg(feature = "log")]
    log::trace!("retro_run()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        if environment::get_variable_update(wrapper.environment_callback) {
            let mut ctx = OptionsChangedContext::new(
                &wrapper.environment_callback,
                Arc::clone(&wrapper.interfaces),
            );

            wrapper.core.on_options_changed(&mut ctx);
        }

        if let Some(callback) = wrapper.input_poll_callback {
            (callback)();
        }

        let mut ctx = RunContext {
            environment_callback: &wrapper.environment_callback,
            interfaces: Arc::clone(&wrapper.interfaces),

            video_refresh_callback: &wrapper.video_refresh_callback,
            audio_sample_callback: &wrapper.audio_sample_callback,
            audio_sample_batch_callback: &wrapper.audio_sample_batch_callback,
            input_poll_callback: &wrapper.input_poll_callback,
            input_state_callback: &wrapper.input_state_callback,

            can_dupe: wrapper.can_dupe,
            had_frame: &mut wrapper.had_frame,
            last_width: &mut wrapper.last_width,
            last_height: &mut wrapper.last_height,
            last_pitch: &mut wrapper.last_pitch,

            supports_bitmasks: wrapper.supports_bitmasks,
        };

        return wrapper.core.on_run(&mut ctx, wrapper.frame_delta.take());
    }

    panic!("retro_run: Core has not been initialized yet!");
}

/// Called by the frontend when the [`Core`]s state should be serialized (“save state”).
/// This function should return [`false`] on error.
///
/// This could also be used by a frontend to implement rewind.
#[no_mangle]
pub unsafe extern "C" fn retro_serialize(data: *mut std::os::raw::c_void, size: size_t) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_serialize(data = {data:#?}, size = {size})");

    if data.is_null() {
        #[cfg(feature = "log")]
        log::warn!("retro_serialize: data is null");

        return false;
    }

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        // Convert the given buffer into a proper slice
        let slice = std::slice::from_raw_parts_mut(data as *mut u8, size as usize);

        return wrapper.core.on_serialize(slice, &mut ctx);
    }

    panic!("retro_serialize: Core has not been initialized yet!");
}

/// Called by the frontend when a “save state” should be loaded.
/// This function should return [`false`] on error.
///
/// This could also be used by a frontend to implement rewind.
#[no_mangle]
pub unsafe extern "C" fn retro_unserialize(
    data: *const std::os::raw::c_void,
    size: size_t,
) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_unserialize(data = {data:#?}, size = {size})");

    if data.is_null() {
        #[cfg(feature = "log")]
        log::warn!("retro_unserialize: data is null");

        return false;
    }

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        // Convert the given buffer into a proper slice
        let slice = std::slice::from_raw_parts_mut(data as *mut u8, size as usize);

        return wrapper.core.on_unserialize(slice, &mut ctx);
    }

    panic!("retro_unserialize: Core has not been initialized yet!");
}

/// Called by the frontend whenever a cheat should be applied.
///
/// The format is core-specific but this function lacks a return value,
/// so a [`Core`] can’t tell the frontend if it failed to parse a code.
#[no_mangle]
pub unsafe extern "C" fn retro_cheat_set(
    index: std::os::raw::c_uint,
    enabled: bool,
    code: *const std::os::raw::c_char,
) {
    #[cfg(feature = "log")]
    log::trace!("retro_cheat_set(index = {index}, enabled = {enabled}, code = {code:#?})");

    if code.is_null() {
        #[cfg(feature = "log")]
        log::warn!("retro_cheat_set: code is null");

        return;
    }

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        // Wrap the pointer into a `CStr`.
        // This assumes the pointer is valid and ends on a null byte.
        //
        // For now we’ll let the core handle conversion to Rust `str` or `String`,
        // as the lack of documentation doesn’t make it clear if the returned string
        // is encoded as valid UTF-8.
        let code = CStr::from_ptr(code);

        return wrapper.core.on_cheat_set(index, enabled, code, &mut ctx);
    }

    panic!("retro_cheat_set: Core has not been initialized yet!");
}

/// Called by the frontend when a game should be loaded.
///
/// A return value of [`true`] indicates success.
#[no_mangle]
pub unsafe extern "C" fn retro_load_game(game: *const retro_game_info) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_load_game(game_type = {game:#?})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = OptionsChangedContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        wrapper.core.on_options_changed(&mut ctx);

        let mut ctx = LoadGameContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        let status = if game.is_null() {
            wrapper.core.on_load_game(None, &mut ctx)
        } else {
            wrapper.core.on_load_game(Some(*game), &mut ctx)
        };

        cfg_if::cfg_if! {
            if #[cfg(feature = "log")] {
                match status {
                    Ok(()) => return true,
                    Err(err) => {
                        log::error!("Failed to load game: {:?}", err);
                        return false;
                    }
                }
            }
            else {
                return status.is_ok();
            }
        }
    }

    panic!("retro_load_game: Core has not been initialized yet!");
}

/// See [`rust_libretro_sys::retro_load_game_special`].
#[no_mangle]
pub unsafe extern "C" fn retro_load_game_special(
    game_type: std::os::raw::c_uint,
    info: *const retro_game_info,
    num_info: size_t,
) -> bool {
    #[cfg(feature = "log")]
    log::trace!(
        "retro_load_game_special(game_type = {game_type}, info = {info:#?}, num_info = {num_info})"
    );

    if info.is_null() {
        #[cfg(feature = "log")]
        log::warn!("retro_load_game_special: info is null");

        return false;
    }

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = OptionsChangedContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        wrapper.core.on_options_changed(&mut ctx);

        let mut ctx = LoadGameSpecialContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        let status = wrapper
            .core
            .on_load_game_special(game_type, info, num_info, &mut ctx);

        cfg_if::cfg_if! {
            if #[cfg(feature = "log")] {
                match status {
                    Ok(()) => return true,
                    Err(err) => {
                        log::error!("Failed to load special game: {:?}", err);
                        return false;
                    }
                }
            }
            else {
                return status.is_ok();
            }
        }
    }

    panic!("retro_load_game_special: Core has not been initialized yet!");
}

/// Returns a mutable pointer to queried memory type.
/// Return [`std::ptr::null()`] in case this doesn’t apply to your [`Core`].
///
/// `id` is one of the `RETRO_MEMORY_*` constants.
#[no_mangle]
pub unsafe extern "C" fn retro_get_memory_data(
    id: std::os::raw::c_uint,
) -> *mut std::os::raw::c_void {
    #[cfg(feature = "log")]
    log::trace!("retro_get_memory_data(id = {id})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper.core.get_memory_data(id, &mut ctx);
    }

    panic!("retro_get_memory_data: Core has not been initialized yet!");
}

/// Returns the size (in bytes) of the queried memory type.
/// Return `0` in case this doesn’t apply to your [`Core`].
///
/// `id` is one of the `RETRO_MEMORY_*` constants.
#[no_mangle]
pub unsafe extern "C" fn retro_get_memory_size(id: std::os::raw::c_uint) -> size_t {
    #[cfg(feature = "log")]
    log::trace!("retro_get_memory_size(id = {id})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper.core.get_memory_size(id, &mut ctx);
    }

    panic!("retro_get_memory_size: Core has not been initialized yet!");
}

/*****************************************************************************\
|                            NON CORE API FUNCTIONS                           |
\*****************************************************************************/

/// If enabled by the [`Core`], notifies it when a keyboard button has been pressed or released.
///
/// # Parameters
/// - `down`: `true` if the key has been pressed, `false` if it has been released
/// - `keycode`: `retro_key` value
/// - `character`: The text character of the pressed key, encoded as UTF-32.
/// - `key_modifiers`: `retro_mod` value
#[no_mangle]
pub unsafe extern "C" fn retro_keyboard_callback_fn(
    down: bool,
    keycode: ::std::os::raw::c_uint,
    character: u32,
    key_modifiers: u16,
) {
    #[cfg(feature = "log")]
    log::trace!("retro_keyboard_callback_fn(down = {down}, keycode = {keycode}, character = {character}, key_modifiers = {key_modifiers})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        // Not sure why bindgen uses `c_int32` as value type
        // for the newtype enum on Windows but `c_uint32` on Unix.
        cfg_if::cfg_if! {
            if #[cfg(target_family = "windows")] {
                let keycode = keycode as i32;
            }
        };

        return wrapper.core.on_keyboard_event(
            down,
            retro_key(keycode),
            character,
            retro_mod(key_modifiers.into()),
        );
    }

    panic!("retro_keyboard_callback_fn: Core has not been initialized yet!");
}

/// **TODO:** Documentation.
#[no_mangle]
pub unsafe extern "C" fn retro_hw_context_reset_callback() {
    #[cfg(feature = "log")]
    log::trace!("retro_hw_context_reset_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_hw_context_reset();
    }

    panic!("retro_hw_context_reset_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation.
#[no_mangle]
pub unsafe extern "C" fn retro_hw_context_destroyed_callback() {
    #[cfg(feature = "log")]
    log::trace!("retro_hw_context_destroyed_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_hw_context_destroyed();
    }

    panic!("retro_hw_context_destroyed_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_set_eject_state_callback(ejected: bool) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_set_eject_state_callback(ejected = {ejected})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_set_eject_state(ejected);
    }

    panic!("retro_set_eject_state_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_get_eject_state_callback() -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_get_eject_state_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_get_eject_state();
    }

    panic!("retro_get_eject_state_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_get_image_index_callback() -> ::std::os::raw::c_uint {
    #[cfg(feature = "log")]
    log::trace!("retro_get_image_index_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_get_image_index();
    }

    panic!("retro_get_image_index_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_set_image_index_callback(index: ::std::os::raw::c_uint) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_set_image_index_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_set_image_index(index);
    }

    panic!("retro_set_image_index_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_get_num_images_callback() -> ::std::os::raw::c_uint {
    #[cfg(feature = "log")]
    log::trace!("retro_get_num_images_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_get_num_images();
    }

    panic!("retro_get_num_images_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_replace_image_index_callback(
    index: ::std::os::raw::c_uint,
    info: *const retro_game_info,
) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_replace_image_index_callback(index = {index}, info = {info:#?})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_replace_image_index(index, info);
    }

    panic!("retro_replace_image_index_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_add_image_index_callback() -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_add_image_index_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_add_image_index();
    }

    panic!("retro_add_image_index_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_set_initial_image_callback(
    index: ::std::os::raw::c_uint,
    path: *const ::std::os::raw::c_char,
) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_set_initial_image_callback(index = {index}, path = {path:#?})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper
            .core
            .on_set_initial_image(index, CStr::from_ptr(path));
    }

    panic!("retro_set_initial_image_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_get_image_path_callback(
    index: ::std::os::raw::c_uint,
    path: *mut ::std::os::raw::c_char,
    len: size_t,
) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_get_image_path_callback(index = {index}, path = {path:#?}, len = {len})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        match wrapper.core.on_get_image_path(index) {
            Some(image_path) => {
                let image_path = image_path.as_bytes();
                let buf = std::slice::from_raw_parts_mut(path as *mut u8, len as usize);
                let len = image_path.len().min(buf.len());

                buf[..len].copy_from_slice(&image_path[..len]);
                return true;
            }
            None => return false,
        }
    }

    panic!("retro_get_image_path_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_get_image_label_callback(
    index: ::std::os::raw::c_uint,
    label: *mut ::std::os::raw::c_char,
    len: size_t,
) -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_get_image_label_callback(index = {index}, label = {label:#?}, len = {len})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        match wrapper.core.on_get_image_label(index) {
            Some(image_label) => {
                let image_label = image_label.as_bytes();
                let buf = std::slice::from_raw_parts_mut(label as *mut u8, len as usize);
                let len = image_label.len().min(buf.len());

                buf[..len].copy_from_slice(&image_label[..len]);
                return true;
            }
            None => return false,
        }
    }

    panic!("retro_get_image_label_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_frame_time_callback_fn(usec: retro_usec_t) {
    #[cfg(feature = "log")]
    log::trace!("retro_frame_time_callback_fn(usec = {usec})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        wrapper.frame_delta = Some(usec);
        return;
    }

    panic!("retro_frame_time_callback_fn: Core has not been initialized yet!");
}

/// Notifies the [`Core`] when audio data should be written.
#[no_mangle]
pub unsafe extern "C" fn retro_audio_callback_fn() {
    // This is just too noisy, even for trace logging
    // #[cfg(feature = "log")]
    // log::trace!("retro_audio_callback_fn()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = AudioContext {
            environment_callback: &wrapper.environment_callback,
            interfaces: Arc::clone(&wrapper.interfaces),

            audio_sample_callback: &wrapper.audio_sample_callback,
            audio_sample_batch_callback: &wrapper.audio_sample_batch_callback,
        };

        return wrapper.core.on_write_audio(&mut ctx);
    }

    panic!("retro_audio_callback_fn: Core has not been initialized yet!");
}

/// Notifies the [`Core`] about the state of the frontend’s audio system.
///
/// [`true`]: Audio driver in frontend is active, and callback is
/// expected to be called regularily.
///
/// [`false`]: Audio driver in frontend is paused or inactive.
///
/// Audio callback will not be called until set_state has been
/// called with [`true`].
///
/// Initial state is [`false`] (inactive).
#[no_mangle]
pub unsafe extern "C" fn retro_audio_set_state_callback_fn(enabled: bool) {
    #[cfg(feature = "log")]
    log::trace!("retro_audio_set_state_callback_fn(enabled = {enabled})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_audio_set_state(enabled);
    }

    panic!("retro_audio_set_state_callback_fn: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_camera_frame_raw_framebuffer_callback(
    buffer: *const u32,
    width: ::std::os::raw::c_uint,
    height: ::std::os::raw::c_uint,
    pitch: size_t,
) {
    let buffer_size = height as usize * pitch as usize;
    let buffer = std::slice::from_raw_parts(buffer, buffer_size);

    #[cfg(feature = "log")]
    log::trace!("retro_camera_frame_raw_framebuffer_callback(buffer = &[u32; {}], width = {width}, height = {height}, pitch = {pitch})", buffer.len());

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper
            .core
            .on_camera_raw_framebuffer(buffer, width, height, pitch as usize);
    }

    panic!("retro_camera_frame_raw_framebuffer_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_camera_frame_opengl_texture_callback(
    texture_id: ::std::os::raw::c_uint,
    texture_target: ::std::os::raw::c_uint,
    affine: *const f32,
) {
    #[cfg(feature = "log")]
    log::trace!("retro_camera_frame_opengl_texture_callback(texture_id = {texture_id}, texture_target = {texture_target}, affine = {:#?})", std::slice::from_raw_parts(affine, 3 * 3));

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        // Packed 3x3 column-major matrix
        let matrix = std::slice::from_raw_parts(affine, 3 * 3);
        // Convert to fixed size array; we know it contains 9 elements
        let matrix: &[f32; 3 * 3] = matrix.try_into().unwrap();

        return wrapper
            .core
            .on_camera_gl_texture(texture_id, texture_target, matrix);
    }

    panic!("retro_camera_frame_opengl_texture_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_camera_initialized_callback() {
    #[cfg(feature = "log")]
    log::trace!("retro_camera_initialized_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper.core.on_camera_initialized(&mut ctx);
    }

    panic!("retro_camera_initialized_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_camera_deinitialized_callback() {
    #[cfg(feature = "log")]
    log::trace!("retro_camera_deinitialized_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper.core.on_camera_deinitialized(&mut ctx);
    }

    panic!("retro_camera_deinitialized_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_location_lifetime_status_initialized_callback() {
    #[cfg(feature = "log")]
    log::trace!("retro_location_lifetime_status_initialized_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper
            .core
            .on_location_lifetime_status_initialized(&mut ctx);
    }

    panic!(
        "retro_location_lifetime_status_initialized_callback: Core has not been initialized yet!"
    );
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_location_lifetime_status_deinitialized_callback() {
    #[cfg(feature = "log")]
    log::trace!("retro_location_lifetime_status_deinitialized_callback()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        let mut ctx = GenericContext::new(
            &wrapper.environment_callback,
            Arc::clone(&wrapper.interfaces),
        );

        return wrapper
            .core
            .on_location_lifetime_status_deinitialized(&mut ctx);
    }

    panic!(
        "retro_location_lifetime_status_deinitialized_callback: Core has not been initialized yet!"
    );
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_get_proc_address_callback(
    sym: *const ::std::os::raw::c_char,
) -> retro_proc_address_t {
    #[cfg(feature = "log")]
    log::trace!("retro_get_proc_address_callback({sym:#?})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_get_proc_address(CStr::from_ptr(sym));
    }

    panic!("retro_get_proc_address_callback: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_audio_buffer_status_callback_fn(
    active: bool,
    occupancy: ::std::os::raw::c_uint,
    underrun_likely: bool,
) {
    #[cfg(feature = "log")]
    log::trace!("retro_audio_buffer_status_callback_fn(active = {active}, occupancy = {occupancy}, underrun_likely = {underrun_likely})");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper
            .core
            .on_audio_buffer_status(active, occupancy, underrun_likely);
    }

    panic!("retro_audio_buffer_status_callback_fn: Core has not been initialized yet!");
}

/// **TODO:** Documentation
#[no_mangle]
pub unsafe extern "C" fn retro_core_options_update_display_callback_fn() -> bool {
    #[cfg(feature = "log")]
    log::trace!("retro_core_options_update_display_callback_fn()");

    if let Some(wrapper) = RETRO_INSTANCE.as_mut() {
        return wrapper.core.on_core_options_update_display();
    }

    panic!("retro_core_options_update_display_callback_fn: Core has not been initialized yet!");
}