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
use libloading::Symbol;
use crate::buttons::Buttons;
use crate::error::*;
use crate::pixels::*;
use libc::c_char;
use libloading::Library;
use libretro_sys::*;
use std::ffi::{c_void, CStr, CString};
use std::fs::File;
use std::io::Read;
use std::marker::PhantomData;
use std::panic;
use std::path::{Path,PathBuf};
use std::ptr;

type NotSendSync = *const [u8; 0];

static mut EMULATOR: *mut EmulatorCore = ptr::null_mut();
static mut CONTEXT: *mut EmulatorContext = ptr::null_mut();

struct EmulatorCore {
    core_lib: Box<Library>,
    core_path: CString,
    rom_path: CString,
    core: CoreAPI,
    _marker: PhantomData<NotSendSync>,
}

struct EmulatorContext {
    audio_sample: Vec<i16>,
    buttons: [Buttons; 2],
    frame_ptr: *const c_void,
    frame_pitch: usize,
    frame_width: u32,
    frame_height: u32,
    pixfmt: PixelFormat,
    image_depth: usize,
    memory_map: Vec<MemoryDescriptor>,
    _marker: PhantomData<NotSendSync>,
}

// A more pleasant wrapper over MemoryDescriptor
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MemoryRegion {
    which: usize,
    pub flags: u64,
    pub len: usize,
    pub start: usize,
    pub offset: usize,
    pub name: String,
    pub select: usize,
    pub disconnect: usize,
}

// Emulator token must not be send nor sync
pub struct Emulator {
    phantom: PhantomData<NotSendSync>,
}

impl Emulator {
    pub fn create(core_path: &Path, rom_path: &Path) -> Emulator {
        unsafe {
            assert!(EMULATOR.is_null());
            assert!(CONTEXT.is_null());
        }
        let suffix = if cfg!(target_os = "windows") {
            "dll"
        } else if cfg!(target_os = "macos") {
            "dylib"
        } else if cfg!(target_os = "linux") {
            "so"
        } else {
            panic!("Unsupported platform")
        };
        let path:PathBuf = core_path.with_extension(suffix);
        #[cfg(target_os = "linux")]
        let library: Library = {
            // Load library with `RTLD_NOW | RTLD_NODELETE` to fix a SIGSEGV
            ::libloading::os::unix::Library::open(Some(path), 0x2 | 0x1000).unwrap().into()
        };
        #[cfg(not(target_os = "linux"))]
        let library = Library::new(path.as_ref()).unwrap();
        let dll = Box::new(library);
        unsafe {
            let retro_set_environment = *(dll.get(b"retro_set_environment").unwrap());
            let retro_set_video_refresh = *(dll.get(b"retro_set_video_refresh").unwrap());
            let retro_set_audio_sample = *(dll.get(b"retro_set_audio_sample").unwrap());
            let retro_set_audio_sample_batch = *(dll.get(b"retro_set_audio_sample_batch").unwrap());
            let retro_set_input_poll = *(dll.get(b"retro_set_input_poll").unwrap());
            let retro_set_input_state = *(dll.get(b"retro_set_input_state").unwrap());
            let retro_init = *(dll.get(b"retro_init").unwrap());
            let retro_deinit = *(dll.get(b"retro_deinit").unwrap());
            let retro_api_version = *(dll.get(b"retro_api_version").unwrap());
            let retro_get_system_info = *(dll.get(b"retro_get_system_info").unwrap());
            let retro_get_system_av_info = *(dll.get(b"retro_get_system_av_info").unwrap());
            let retro_set_controller_port_device =
                *(dll.get(b"retro_set_controller_port_device").unwrap());
            let retro_reset = *(dll.get(b"retro_reset").unwrap());
            let retro_run = *(dll.get(b"retro_run").unwrap());
            let retro_serialize_size = *(dll.get(b"retro_serialize_size").unwrap());
            let retro_serialize = *(dll.get(b"retro_serialize").unwrap());
            let retro_unserialize = *(dll.get(b"retro_unserialize").unwrap());
            let retro_cheat_reset = *(dll.get(b"retro_cheat_reset").unwrap());
            let retro_cheat_set = *(dll.get(b"retro_cheat_set").unwrap());
            let retro_load_game = *(dll.get(b"retro_load_game").unwrap());
            let retro_load_game_special = *(dll.get(b"retro_load_game_special").unwrap());
            let retro_unload_game = *(dll.get(b"retro_unload_game").unwrap());
            let retro_get_region = *(dll.get(b"retro_get_region").unwrap());
            let retro_get_memory_data = *(dll.get(b"retro_get_memory_data").unwrap());
            let retro_get_memory_size = *(dll.get(b"retro_get_memory_size").unwrap());
            let emu = EmulatorCore {
                core_lib: dll,
                rom_path: CString::new(rom_path.to_str().unwrap()).unwrap(),
                core_path: CString::new(core_path.to_str().unwrap()).unwrap(),
                core: CoreAPI {
                    retro_set_environment,
                    retro_set_video_refresh,
                    retro_set_audio_sample,
                    retro_set_audio_sample_batch,
                    retro_set_input_poll,
                    retro_set_input_state,

                    retro_init,
                    retro_deinit,

                    retro_api_version,

                    retro_get_system_info,
                    retro_get_system_av_info,
                    retro_set_controller_port_device,

                    retro_reset,
                    retro_run,

                    retro_serialize_size,
                    retro_serialize,
                    retro_unserialize,

                    retro_cheat_reset,
                    retro_cheat_set,

                    retro_load_game,
                    retro_load_game_special,
                    retro_unload_game,

                    retro_get_region,
                    retro_get_memory_data,
                    retro_get_memory_size,
                },
                _marker: PhantomData,
            };
            let emup = Box::new(emu);
            // Store a pointer to the data
            EMULATOR = Box::leak(emup);
            // Forget the box so it doesn't drop
            let ctx = EmulatorContext {
                audio_sample: Vec::new(),
                buttons: [Buttons::new(), Buttons::new()],
                frame_ptr: ptr::null(),
                frame_pitch: 0,
                frame_width: 0,
                frame_height: 0,
                pixfmt: PixelFormat::ARGB1555,
                image_depth: 0,
                memory_map: Vec::new(),
                _marker: PhantomData,
            };
            // Ditto here for the context
            let ctxp = Box::new(ctx);
            CONTEXT = Box::leak(ctxp);
            let emu = &(*EMULATOR);
            // Set up callbacks
            (emu.core.retro_set_environment)(callback_environment);
            (emu.core.retro_set_video_refresh)(callback_video_refresh);
            (emu.core.retro_set_audio_sample)(callback_audio_sample);
            (emu.core.retro_set_audio_sample_batch)(callback_audio_sample_batch);
            (emu.core.retro_set_input_poll)(callback_input_poll);
            (emu.core.retro_set_input_state)(callback_input_state);
            // Load the game
            (emu.core.retro_init)();
            let mut sys_info = SystemInfo {
                library_name: ptr::null(),
                library_version: ptr::null(),
                valid_extensions: ptr::null(),
                need_fullpath: false,
                block_extract: false,
            };
            retro_get_system_info(&mut sys_info);
            let rom_cstr = &(*EMULATOR).rom_path;

            let mut rom_file = File::open(rom_path).unwrap();
            let mut buffer = Vec::new();
            rom_file.read_to_end(&mut buffer).unwrap();
            buffer.shrink_to_fit();
            let game_info = GameInfo {
                path: rom_cstr.as_ptr(),
                data: buffer.as_ptr() as *const c_void,
                size: buffer.len(),
                meta: ptr::null(),
            };
            (emu.core.retro_load_game)(&game_info);
            let mut av_info = SystemAvInfo {
                geometry: GameGeometry {
                    base_width: 0,
                    base_height: 0,
                    max_width: 0,
                    max_height: 0,
                    aspect_ratio: 0.0,
                },
                timing: SystemTiming {
                    fps: 0.0,
                    sample_rate: 0.0,
                },
            };
            (retro_get_system_av_info)(&mut av_info);
            Emulator {
                phantom: PhantomData,
            }
        }
    }
    pub fn get_library(&mut self) -> &Library {
        unsafe {
            &(*EMULATOR).core_lib
        }
    }
    pub fn get_symbol<'a, T>(&'a self, symbol:&[u8]) -> Option<Symbol<'a, T>> {
        let dll = unsafe { &(*EMULATOR).core_lib };
        let sym:Result<Symbol<T>,_> = unsafe { dll.get(symbol) };
        if sym.is_err() {
            return None;
        }
        Some(sym.unwrap())
    }
    pub fn run(&mut self, inputs: [Buttons; 2]) {
        unsafe {
            //clear audio buffers and whatever else
            (*CONTEXT).audio_sample.clear();
            //set inputs on CB
            (*CONTEXT).buttons = inputs;
            //run one step
            ((*EMULATOR).core.retro_run)()
        }
    }
    pub fn reset(&mut self) {
        unsafe {
            //clear audio buffers and whatever else
            (*CONTEXT).audio_sample.clear();
            //clear inputs on CB
            (*CONTEXT).buttons = [Buttons::new(), Buttons::new()];
            //clear fb
            (*CONTEXT).frame_ptr = ptr::null();
            ((*EMULATOR).core.retro_reset)()
        }
    }
    fn get_ram_size(&self, rtype: libc::c_uint) -> usize {
        unsafe { ((*EMULATOR).core.retro_get_memory_size)(rtype) as usize }
    }
    pub fn get_video_ram_size(&self) -> usize {
        self.get_ram_size(MEMORY_VIDEO_RAM)
    }
    pub fn get_system_ram_size(&self) -> usize {
        self.get_ram_size(MEMORY_SYSTEM_RAM)
    }
    pub fn get_save_ram_size(&self) -> usize {
        self.get_ram_size(MEMORY_SAVE_RAM)
    }
    pub fn video_ram_ref(
        &self
    ) -> &[u8] {
        self.get_ram(MEMORY_VIDEO_RAM)
    }
    pub fn system_ram_ref(&self) -> &[u8] {
        self.get_ram(MEMORY_SYSTEM_RAM)
    }
    pub fn system_ram_mut(&mut self) -> &mut [u8] {
        self.get_ram_mut(MEMORY_SYSTEM_RAM)
    }
    pub fn save_ram(
        &self
    ) -> &[u8] {
        self.get_ram(MEMORY_SAVE_RAM)
    }

    fn get_ram(&self, ramtype: libc::c_uint) -> &[u8] {
        let len = self.get_ram_size(ramtype);
        unsafe {
            let ptr: *const u8 = ((*EMULATOR).core.retro_get_memory_data)(ramtype).cast();
            std::slice::from_raw_parts(ptr, len)
        }
    }

    fn get_ram_mut(&mut self, ramtype: libc::c_uint) -> &mut [u8] {
        let len = self.get_ram_size(ramtype);
        unsafe {
            let ptr: *mut u8 = ((*EMULATOR).core.retro_get_memory_data)(ramtype).cast();
            std::slice::from_raw_parts_mut(ptr, len)
        }
    }

    pub fn memory_regions(&self) -> Vec<MemoryRegion> {
        let map = unsafe { &((*CONTEXT).memory_map) };
        map.iter()
            .enumerate()
            .map(|(i, mdesc)| MemoryRegion {
                which: i,
                flags: mdesc.flags,
                len: mdesc.len,
                start: mdesc.start,
                offset: mdesc.offset,
                select: mdesc.select,
                disconnect: mdesc.disconnect,
                name: if mdesc.addrspace.is_null() {
                    "".to_owned()
                } else {
                    unsafe { CStr::from_ptr(mdesc.addrspace) }
                        .to_string_lossy()
                        .into_owned()
                },
            })
            .collect()
    }
    pub fn memory_ref(
        &self,
        start: usize,
    ) -> Result<&[u8], RetroRsError> {
        for mr in self.memory_regions() {
            if mr.select != 0 && (start & mr.select) == 0 {
                continue;
            }
            if start >= mr.start && start < mr.start + mr.len {
                return self.memory_ref_mut(mr, start).map(|slice| &*slice);
            }
        }
        Err(RetroRsError::RAMCopyNotMappedIntoMemoryRegionError)
    }
    pub fn memory_ref_mut(
        &self,
        mr: MemoryRegion,
        start: usize,
    ) -> Result<&mut [u8], RetroRsError> {
        let maps = unsafe { &(*CONTEXT).memory_map };
        if mr.which >= maps.len() {
            // TODO more aggressive checking of mr vs map
            return Err(RetroRsError::RAMMapOutOfRangeError);
        }
        if start < mr.start {
            return Err(RetroRsError::RAMCopySrcOutOfBoundsError);
        }
        let start = (start - mr.start) & !mr.disconnect;
        let map = &maps[mr.which];
        //0-based at this point, modulo offset
        let ptr: *mut u8 = map.ptr.cast();
        let slice = unsafe {
            let ptr = ptr.add(start).add(map.offset);
            std::slice::from_raw_parts_mut(ptr, map.len-start)
        };
        Ok(slice)
    }

    pub fn pixel_format(&self) -> PixelFormat {
        unsafe { (*CONTEXT).pixfmt }
    }
    pub fn framebuffer_size(&self) -> (usize, usize) {
        unsafe {
            (
                (*CONTEXT).frame_width as usize,
                (*CONTEXT).frame_height as usize,
            )
        }
    }
    pub fn framebuffer_pitch(&self) -> usize {
        unsafe { (*CONTEXT).frame_pitch }
    }
    fn peek_framebuffer<FBPeek, FBPeekRet>(&self, f: FBPeek) -> Result<FBPeekRet, RetroRsError>
    where
        FBPeek: FnOnce(&[u8]) -> FBPeekRet,
    {
        unsafe {
            if (*CONTEXT).frame_ptr.is_null() {
                Err(RetroRsError::NoFramebufferError)
            } else {
                let frame_slice = std::slice::from_raw_parts(
                    (*CONTEXT).frame_ptr as *const u8,
                    ((*CONTEXT).frame_height * ((*CONTEXT).frame_pitch as u32)) as usize,
                );
                Ok(f(frame_slice))
            }
        }
    }

    pub fn save(&self, bytes: &mut [u8]) {
        let size = self.save_size();
        assert!(bytes.len() >= size);
        unsafe { ((*EMULATOR).core.retro_serialize)(bytes.as_mut_ptr() as *mut c_void, size) }
    }
    pub fn load(&mut self, bytes: &[u8]) -> bool {
        let size = self.save_size();
        assert!(bytes.len() >= size);
        unsafe { ((*EMULATOR).core.retro_unserialize)(bytes.as_ptr() as *const c_void, size) }
    }
    pub fn save_size(&self) -> usize {
        unsafe { ((*EMULATOR).core.retro_serialize_size)() }
    }
    pub fn clear_cheats(&mut self) {
        unsafe { ((*EMULATOR).core.retro_cheat_reset)() }
    }
    pub fn set_cheat(&mut self, index: usize, enabled: bool, code: &str) {
        unsafe {
            // FIXME: Creates a memory leak since the libretro api won't let me from_raw() it back and drop it.  I don't know if libretro guarantees anything about ownership of this str to cores.
            ((*EMULATOR).core.retro_cheat_set)(
                index as u32,
                enabled,
                CString::new(code).unwrap().into_raw(),
            )
        }
    }
    pub fn get_pixel(&self, x:usize, y:usize) -> Result<(u8, u8, u8), RetroRsError> {
        let (w,_h) = self.framebuffer_size();
        self.peek_framebuffer(move |fb| {
            match self.pixel_format() {
                PixelFormat::ARGB1555 => {
                    let start = y * w + x;
                    let gb = fb[start * 2];
                    let arg = fb[start * 2 + 1];
                    let (red, green, blue) = argb555to888(gb, arg);
                    (red, green, blue)
                },
                PixelFormat::ARGB8888 => {
                    let off = (y * w + x) * 4;
                    (fb[off + 1], fb[off + 2], fb[off + 3])
                },
                PixelFormat::RGB565 => {
                    let start = y * w + x;
                    let gb = fb[start * 2];
                    let rg = fb[start * 2 + 1];
                    let (red, green, blue) = rgb565to888(gb, rg);
                    (red, green, blue)
                }
            }
        })
    }
    pub fn for_each_pixel(
        &self,
        mut f: impl FnMut(usize, usize, u8, u8, u8),
    ) -> Result<(), RetroRsError> {
        let (w, h) = self.framebuffer_size();
        let fmt = self.pixel_format();
        self.peek_framebuffer(move |fb| {
            let mut x = 0;
            let mut y = 0;
            match fmt {
                PixelFormat::ARGB1555 => {
                    for components in fb.chunks_exact(2) {
                        let gb = components[0];
                        let arg = components[1];
                        let (red, green, blue) = argb555to888(gb, arg);
                        f(x, y, red, green, blue);
                        x += 1;
                        if x >= w {
                            y += 1;
                            x = 0;
                        }
                    }
                }
                PixelFormat::ARGB8888 => {
                    for components in fb.chunks_exact(4) {
                        let red = components[1];
                        let green = components[2];
                        let blue = components[3];
                        f(x, y, red, green, blue);
                        x += 1;
                        if x >= w {
                            y += 1;
                            x = 0;
                        }
                    }
                }
                PixelFormat::RGB565 => {
                    for components in fb.chunks_exact(2) {
                        let gb = components[0];
                        let rg = components[1];
                        let (red, green, blue) = rgb565to888(gb, rg);
                        f(x, y, red, green, blue);
                        x += 1;
                        if x >= w {
                            y += 1;
                            x = 0;
                        }
                    }
                }
            };
            assert_eq!(y, h);
            assert_eq!(x, 0);
        })
    }
    pub fn copy_framebuffer_rgb888(&self, slice: &mut [u8]) -> Result<(), RetroRsError> {
        let fmt = self.pixel_format();
        self.peek_framebuffer(move |fb| {
            match fmt {
                PixelFormat::ARGB1555 => {
                    for (components,dst) in fb.chunks_exact(2).zip(slice.chunks_exact_mut(3)) {
                        let gb = components[0];
                        let arg = components[1];
                        let (red, green, blue) = argb555to888(gb, arg);
                        dst[0] = red;
                        dst[1] = green;
                        dst[2] = blue;
                    }
                }
                PixelFormat::ARGB8888 => {
                    for (components,dst) in fb.chunks_exact(4).zip(slice.chunks_exact_mut(3)) {
                        let r = components[1];
                        let g = components[2];
                        let b = components[3];
                        dst[0] = r;
                        dst[1] = g;
                        dst[2] = b;
                    }
                }
                PixelFormat::RGB565 => {
                    for (components,dst) in fb.chunks_exact(2).zip(slice.chunks_exact_mut(3)) {
                        let gb = components[0];
                        let rg = components[1];
                        let (red, green, blue) = rgb565to888(gb, rg);
                        dst[0] = red;
                        dst[1] = green;
                        dst[2] = blue;
                    }
                }
            };
        })
    }
    pub fn copy_framebuffer_rgb332(&self, slice: &mut [u8]) -> Result<(), RetroRsError> {
        let fmt = self.pixel_format();
        self.peek_framebuffer(move |fb| {
            match fmt {
                PixelFormat::ARGB1555 => {
                    for (components,dst) in fb.chunks_exact(2).zip(slice.iter_mut()) {
                        let gb = components[0];
                        let arg = components[1];
                        let (red, green, blue) = argb555to888(gb, arg);
                        *dst = rgb888_to_rgb332(red,green,blue);
                    }
                }
                PixelFormat::ARGB8888 => {
                    for (components,dst) in fb.chunks_exact(4).zip(slice.iter_mut()) {
                        let r = components[1];
                        let g = components[2];
                        let b = components[3];
                        *dst = rgb888_to_rgb332(r,g,b);
                    }
                }
                PixelFormat::RGB565 => {
                    for (components,dst) in fb.chunks_exact(2).zip(slice.iter_mut()) {
                        let gb = components[0];
                        let rg = components[1];
                        let (red, green, blue) = rgb565to888(gb, rg);
                        *dst = rgb888_to_rgb332(red,green,blue);
                    }
                }
            };
        })
    }
    pub fn copy_framebuffer_argb32(&self, slice: &mut [u32]) -> Result<(), RetroRsError> {
        let fmt = self.pixel_format();
        self.peek_framebuffer(move |fb| {
            match fmt {
                PixelFormat::ARGB1555 => {
                    for (components,dst) in fb.chunks_exact(2).zip(slice.iter_mut()) {
                        let gb = components[0];
                        let arg = components[1];
                        let (red, green, blue) = argb555to888(gb, arg);
                        *dst = 0xFF00_0000 | (u32::from(red) << 16) | (u32::from(green) << 8) | u32::from(blue);
                    }
                }
                PixelFormat::ARGB8888 => {
                    for (components,dst) in fb.chunks_exact(4).zip(slice.iter_mut()) {
                        *dst = (u32::from(components[0]) << 24) | (u32::from(components[1]) << 16) | (u32::from(components[2]) << 8) | u32::from(components[3]);
                    }
                }
                PixelFormat::RGB565 => {
                    for (components,dst) in fb.chunks_exact(2).zip(slice.iter_mut()) {
                        let gb = components[0];
                        let rg = components[1];
                        let (red, green, blue) = rgb565to888(gb, rg);
                        *dst = 0xFF00_0000 | (u32::from(red) << 16) | (u32::from(green) << 8) | u32::from(blue);
                    }
                }
            };
        })
    }
}

unsafe extern "C" fn callback_environment(cmd: u32, data: *mut c_void) -> bool {
    let result = panic::catch_unwind(|| {
        match cmd {
            ENVIRONMENT_SET_CONTROLLER_INFO => true,
            ENVIRONMENT_SET_PIXEL_FORMAT => {
                let pixfmti = *(data as *const u32);
                let pixfmt = PixelFormat::from_uint(pixfmti);
                if pixfmt.is_none() {
                    return false;
                }
                let pixfmt = pixfmt.unwrap();
                (*CONTEXT).image_depth = match pixfmt {
                    PixelFormat::ARGB1555 => 15,
                    PixelFormat::ARGB8888 => 32,
                    PixelFormat::RGB565 => 16,
                };
                (*CONTEXT).pixfmt = pixfmt;
                true
            }
            ENVIRONMENT_GET_SYSTEM_DIRECTORY => {
                *(data as *mut *const c_char) = (*EMULATOR).core_path.as_ptr();
                true
            }
            ENVIRONMENT_GET_CAN_DUPE => {
                *(data as *mut bool) = true;
                true
            }
            ENVIRONMENT_SET_MEMORY_MAPS => {
                let map = data as *const MemoryMap;
                let desc_slice =
                    std::slice::from_raw_parts((*map).descriptors, (*map).num_descriptors as usize);
                // Don't know who owns map or how long it will last
                (*CONTEXT).memory_map = Vec::new();
                // So we had better copy it
                (*CONTEXT).memory_map.extend_from_slice(desc_slice);
                // (Implicitly we also want to drop the old one, which we did by reassigning)
                true
            }
            _ => false,
        }
    });
    result.unwrap_or(false)
}

extern "C" fn callback_video_refresh(data: *const c_void, width: u32, height: u32, pitch: usize) {
    // Can't panic
    unsafe {
        // context's framebuffer just points to the given data.  Seems to work OK for gym-retro.
        if !data.is_null() {
            (*CONTEXT).frame_ptr = data;
            (*CONTEXT).frame_pitch = pitch;
            (*CONTEXT).frame_width = width;
            (*CONTEXT).frame_height = height;
        }
    }
}
extern "C" fn callback_audio_sample(left: i16, right: i16) {
    // Can't panic
    unsafe {
        let sample_buf = &mut (*CONTEXT).audio_sample;
        sample_buf.push(left);
        sample_buf.push(right);
    }
}
extern "C" fn callback_audio_sample_batch(data: *const i16, frames: usize) -> usize {
    // Can't panic
    unsafe {
        let sample_buf = &mut (*CONTEXT).audio_sample;
        let slice = std::slice::from_raw_parts(data, frames * 2);
        sample_buf.clear();
        sample_buf.extend_from_slice(slice);
        frames
    }
}

extern "C" fn callback_input_poll() {}

extern "C" fn callback_input_state(port: u32, device: u32, index: u32, id: u32) -> i16 {
    // Can't panic
    if port > 1 || device != 1 || index != 0 {
        // Unsupported port/device/index
        println!("Unsupported port/device/index");
        return 0;
    }
    let id = id;
    let port = port as usize;
    if id > 16 {
        println!("Unexpected button id {}", id);
        return 0;
    }
    unsafe {
        if (*CONTEXT).buttons[port].get(id) {
            1
        } else {
            0
        }
    }
}

impl Drop for Emulator {
    fn drop(&mut self) {
        unsafe {
            ((*EMULATOR).core.retro_unload_game)();
            ((*EMULATOR).core.retro_deinit)();
        }
        //TODO drop memory maps etc
        unsafe {
            // "remember" context and emulator we forgot before
            let _ctx = Box::from_raw(CONTEXT);
            let _emu = Box::from_raw(EMULATOR);
            CONTEXT = ptr::null_mut();
            EMULATOR = ptr::null_mut();
        }
        // let them drop naturally
    }
}



#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;
    #[cfg(feature = "use_image")]
    extern crate image;
    #[cfg(feature = "use_image")]
    use crate::fb_to_image::*;

    fn mario_is_dead(emu: &Emulator) -> bool {
        emu.system_ram_ref()[0x0770] == 0x03
    }

    const PPU_BIT:usize = 1 << 31;

    fn get_byte(emu:&Emulator, addr:usize) -> u8 {
        emu.memory_ref(addr).expect("Couldn't read RAM!")[0]
    }

    #[cfg(feature = "use_image")]
    #[test]
    fn it_works() {
        // TODO change to a public domain rom or maybe 2048 core or something
        let mut emu = Emulator::create(
            Path::new("cores/fceumm_libretro"),
            Path::new("roms/mario.nes"),
        );
        for i in 0..250 {
            emu.run([
                Buttons::new()
                    .start(i > 80 && i < 100)
                    .right(i >= 100)
                    .a((i >= 100 && i <= 150) || (i >= 180)),
                Buttons::new(),
            ]);
        }
        let fb = emu.create_imagebuffer();
        fb.unwrap().save("out.png").unwrap();
        let mut died = false;
        for _ in 0..10000 {
            emu.run([Buttons::new().right(true), Buttons::new()]);
            if mario_is_dead(&emu) {
                died = true;
                let fb = emu.create_imagebuffer();
                fb.unwrap().save("out2.png").unwrap();
                break;
            }
        }
        assert!(died);
        emu.reset();
        for i in 0..250 {
            emu.run([
                Buttons::new()
                    .start(i > 80 && i < 100)
                    .right(i >= 100)
                    .a((i >= 100 && i <= 150) || (i >= 180)),
                Buttons::new(),
            ]);
        }

        //emu will drop naturally
    }
}