don't click here

Utility clownmdemu - The Greatest Mega Drive Emulator Ever (Someday)

Discussion in 'Technical Discussion' started by Clownacy, Jun 23, 2022.

  1. nineko

    nineko

    I am the Holy Cat Tech Member
    6,268
    469
    63
    italy
    Yeah, given the formula I posted above, what you said makes perfect sense. It makes a huge difference because the "off by one" error is at the denominator. So, even if higher frequencies have more leeway from a musical point of view, the results are so off that it sounds wrong anyway.

    All I wanted was to amend the information in Devon's post, really.
     
  2. Devon

    Devon

    Powered by a malfunctioning Motorola 68000 Tech Member
    1,088
    1,168
    93
    your mom
    @nineko Oh huh, I was thinking in terms of just the PSG, so yeah, that's my bad.
     
  3. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    frontend v0.4.2 & libretro v0.2.2
    This update's on the smaller side: it's mainly just for native file dialogs on Unix-like OSs.

    The emulator itself has been lightly optimised, as I've started using my 3DS as an ultra-low-end benchmark. Hopefully I can make my emulator fast enough to run at full speed on the 3DS someday.

    I've also fixed the bug where, if you play Sonic 1, pause, and then reset the emulator, the Sega chant won't be audible. The fix was to make the YM2612 reset when the Z80 is reset, which is what happens on a real Mega Drive.

    The main reason for this update is that the standalone frontend on Linux and the BSDs now has native file dialogs, instead of relying on the barebones fallback that was added in v0.4. These particular file dialogs leverage Zenity, meaning that they're GTK-based. In the future, I'll also add support for kdialog, to provide a Qt-based alternative. The usage of Zenity means that there is no hard dependency on GTK: if Zenity is not installed, then the frontend will harmlessly fall-back on the barebones file dialog instead.

    Standalone: https://github.com/Clownacy/clownmdemu-frontend/releases/tag/v0.4.2
    libretro: https://github.com/Clownacy/clownmdemu-libretro/releases/tag/v0.2.2
     
    Last edited: Mar 16, 2023
  4. rata

    rata

    Member
    666
    55
    28
    Argentina
    Trying to be useful somehow.
    I just gave it a go simply for regular end-user scenario, it ended up playing Columns 3 smoother than Kega. This is great.
     
  5. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    frontend v0.4.3 & libretro v0.2.3
    Another small update:

    The plane debugger was broken back in v0.4. Thanks to Brainulator pointing this out, it has been fixed in this update.

    A new Qt-based file dialog has been added for Linux and the BSDs, which leverages the 'kdialog' tool. Like the Zenity-powered GTK file dialog, this is a soft dependency: it is not required to build or run the emulator, and the emulator will instead fall-back on the default Dear ImGui-based dialog if neither are available.

    I've also attempted to fix a curious hang that would occur when resuming the PC after leaving it asleep overnight. From what I can tell, it's the result of an overflow in the millisecond tick counter. To avoid this, the tick counter has been made 64-bit. Now it will only overflow after 2,000,000 years.

    An optimisation has been made to the Z80 interpreter which gives it a massive speed boost, improving the performance of the emulator overall. It's still not enough to get the emulator running at full-speed on the 3DS, but it's a big step towards it.

    Standalone: https://github.com/Clownacy/clownmdemu-frontend/releases/tag/v0.4.3
    libretro: https://github.com/Clownacy/clownmdemu-libretro/releases/tag/v0.2.3
     
  6. JGMR

    JGMR

    Member
    5
    0
    1
    So I’m assuming that the counter was 32-bit in previous versions before this one, whic caused a possible overflow issue after waking the computer up from sleep mode.
     
  7. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    frontend v0.4.4
    Another small update that mainly fixes bugs in the frontend, with one bugfix in the emulator itself.

    The emulator also got a logo and icon at long last:
    [​IMG]
    It's meant to mimic the look of Windows 11's icons, like those of Notepad and Calculator.

    Support for Linux and macOS has been fixed: SDL2's unreliable DPI detection was throwing the scaling off. Unfortunately, this means that high-DPI support is currently Windows-only. I blame SDL2 for this one: its entire purpose is to be a platform abstraction layer, and it completely fails at this when it comes to managing DPI scaling.

    I also fixed the barebones 'save file' dialog, which has been broken since I first added it. Whoops. Now macOS users can save things properly.

    Games that are dropped onto the emulator window are now added to the 'Recent Software' list.

    Alt+Enter will now toggle full-screen. This is a fairly standard keyboard shortcut, so it may come more naturally than the default F11 key binding.

    Various instances of stuck inputs have been fixed. No more infinite rewinding!

    Finally, there's the emulator bugfix: sprites were being culled while they were still on-screen by one column of pixels at the right side of the screen. At first I mistook this for a bug in Sonic 2, which led me on a wild goose chase.

    https://github.com/Clownacy/clownmdemu-frontend/releases/tag/v0.4.4
     
  8. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    [Blog post]

    I've been thinking of expanding my Mega Drive emulator with support for the Mega Drive's add-on - the Mega CD. On paper, this should be simple enough to do: while the Mega CD adds a second 68000 CPU, communications ports, a lot of extra RAM, hardware for graphics-transformation, a sound chip, the titular CD drive, and a BIOS to manage it all, many of these can be skipped or implemented in a quick and easy way to at least get some games booting.

    As of writing, I have achieved my first milestone, which is to get a couple of Sonic hacks to boot. These hacks are special because they make minimal use of the Mega CD hardware, making them the easiest software to add support for. One hack (Sonic Winter Adventures) can be seen below, declaring its detection and usage of the Mega CD:

    [​IMG]

    Sonic Winter Adventures exclusively uses the Mega CD for playing music from a CD. The other hack, my old Super Sonic & Hyper Sonic in Sonic 1 hack, uses the Mega CD for playing PCM samples using the extra sound chip.

    Unlike typical Mega CD games, these two hacks store their data on a cartridge instead of a CD. This bypasses the need for me to implement the Mega CD's boot-up process of reading the IP and SP binaries from the disc, and also the need to implement the various BIOS calls that are related to reading CD sectors.

    Games that utilise the Mega CD hardware, but run from a cartridge, are called 'Mode 1' games. This is because of Sega's official Mega CD developer documents, which dub the cartridge-booting process 'Mode 1' and the CD-booting process 'Mode 2'.

    Out of all of the Mega CD's hardware, the only things that these hacks rely on are the extra CPU, the communication ports, the extra RAM (and the bus logic that allows it to be accessed), the BIOS, and, in my Super Sonic hack's case, the extra sound chip. The sound chip and most of the BIOS can be stubbed-out to at least get the hacks to boot, leaving only the extra CPU, communication ports, RAM, bus logic, and some parts of the BIOS.

    The screenshot seen above is the result of implementing these essential features. So, how did I do it?

    The CPU (dubbed the 'SUB-CPU') is a 68000, just like the Mega Drive's main CPU (appropriately dubbed the 'MAIN-CPU'). Because of the modular design of my emulator's internals, the 68000 interpreter supports multiple states, allowing it to emulate two CPUs simultaneously. I just had to allocate a second state struct for this second CPU, and then add an additional call loop to invoke the interpreter using this struct for the duration of the emulated frame.

    However, for this CPU to do much of anything, it needs some RAM. The Mega CD adds two sets of memory: WORD-RAM and PRG-RAM. PRG-RAM essentially belongs to the sub-CPU, and is intended to hold its BIOS and other code. WORD-RAM is shared between the main-CPU and the sub-CPU, typically being used to ferry data between the Mega CD's CD drive or graphics-transformation hardware and the Mega Drive. Because PRG-RAM is 'owned' by the sub-CPU, the main-CPU must request the sub-CPU's bus to be able to access PRG-RAM. This freezes the sub-CPU. This is not the case for WORD-RAM, which can be exchanged between the two CPUs freely without freezing either of them. WORD-RAM and PRG-RAM are massive: the Mega Drive has 64 KiB of RAM, while WORD-RAM and PRG-RAM add a further 768 KiB. Implementing this all is just a matter of adding the appropriate logic to the sub-CPU's bus event call-backs, accessing an array that represents either WORD-RAM or PRG-RAM based on the specified address, just like a real bus.

    To allow the two 68000 CPUs to communicate, a couple of words are made available to both CPUs. Half of the words can be read and written by the main-CPU, but are read-only for the sub-CPU, and the other half are the other way around. No bus-requesting or exchanging is needed to access these.

    That leaves the final part of the puzzle: to manage the complicated CD drive hardware (among other things), the Mega CD comes equipped with an elaborate BIOS. Notably, this BIOS features system calls for reading sectors from the CD and playing CDDA music. Software that runs on the sub-CPU is intended to be managed by this BIOS, meaning that a partial BIOS implementation is needed for the sub-CPU programs of these ROM-hacks to run at all. Without the sub-CPU program running, Sonic Winter Adventures will refuse to boot, as it will infinitely wait for a response from the sub-CPU to be sent through the communication ports.

    Sub-CPU programs are loaded at address 0x6000 and come with a small header. This header features a magic number (string), a flag, and a couple of offset tables. One offset table specifies functions that will be called by the BIOS on start-up, after start-up, every vertical interrupt, and in response to a user-raised event. Without a functional BIOS, these functions will never be called.

    An additional requirement for the BIOS is exclusive to Mode 1 games: because these games boot directly from a cartridge rather than the Mega CD's BIOS, the sub-CPU's portion of the BIOS is not automatically loaded, and instead must be loaded manually. The typical method for doing this is to locate a magic number, then decompress a nearby Kosinski-compressed payload which contains the sub-CPU BIOS. For these games to correctly boot in my emulator, this magic number needs to be present, and a dummy Kosinski-compressed archive needs to be at the expected location. Without the magic number, the hack may not think that a Mega CD is attached at all, and, without the the Kosinski-compressed archive, the hack would crash as the decompressor would go haywire.

    To meet these various needs, I created my own stub BIOS in 68000 assembly, compressed it in the Kosinski format, and had the sub-CPU's bus logic place it at the same location as the original BIOS's payload. This way, the hacks' Mode 1 initialisation logic and sub-CPU programs all run correctly.

    With this done, Sonic Winter Adventures is able to detect the Mega CD, request the sub-CPU's bus, decompress the sub-CPU BIOS into PRG-RAM, release the sub-CPU's bus, reset the sub-CPU, run the sub-CPU program, and finally communicate with the sub-CPU program to complete its boot process, resulting in the above screenshot. It's not much, but it's a start!
     
    Last edited: Sep 27, 2023
  9. Devon

    Devon

    Powered by a malfunctioning Motorola 68000 Tech Member
    1,088
    1,168
    93
    your mom
    If you ever wanted to see how the CDC and CDD work for lower level emulation, these resources can definitely help.
    Also would be worth looking into how redbook works, especially for subcode reading, since that's a thing that can be done on the MCD. It should also be noted that some models have an slightly different version of the CDC that has 5-bit registers instead of 4-bit.
     
  10. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    Awesome, thanks! I just hope that I won't need it, and that high-level emulation will be good enough.
     
  11. Devon

    Devon

    Powered by a malfunctioning Motorola 68000 Tech Member
    1,088
    1,168
    93
    your mom
    In that case, I can at least give you some info about some of the CD reading BIOS commands that I have documented after digging through the BIOS a bit.
    • CDCSTART - Tells the CDC to start reading from the disc at the current sector. It queues up to 5 sectors
    • CDCSTARTP - Same as CDCSTART, except you can setup some flags for reading (see cdbios.inc for more info)
    • CDCSETMODE - Just sets the read flags
    • CDCSTOP - Tells the CDC to stop reading data
    • CDCSTAT - Checks if the sector read queue is empty of not
    • CDCREAD - Tells the CDC to begin transferring 1 sector into memory
      • In manual transfer mode (MAIN CPU READ or SUB CPU READ), it gets sent to the host data register, where it is expected to be read word by word.
      • In DMA mode, it automatically transfers the data into the destination address (PRG-RAM, Word RAM, and PCM wave RAM can be set for copying into)
    • CDCTRN - If in SUB CPU READ mode, it handles copying from the host data register for you
    • CDCACK - Tells the CDC that the sector has been copied over into memory
    When implementing these, it's basically a must to at least look into how the CDD and CDC get data transferred, how header data is handled, and to know the different read modes so that you know how to account for them. The manual read modes involve reading the host data register one word at a time (of course, CDCTRN takes care of that for you for the Sub CPU side).

    The CD-ROM read BIOS commands (prefixed with "ROM") seems to just involve seeking to the designated sector you want for reading from, where it then automatically calls CDCSTART, and also pausing and unpausing reading. The CD drive also cannot play music and read data at the same time, it can only do one or the other, so keep that in mind.

    Hope this helps!
     
    • Informative Informative x 1
    • List
  12. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    That's great: I was worried that I'd have to rely solely on the Mega CD BIOS Manual and the macros in the DDK's 'SEGADTS\32X\DEMO\CD_V2A\INC\CDBIOS.INC' to figure this stuff out, so the insight helps!
     
  13. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    [Blog post]

    If you've been keeping up with the development of my Mega Drive emulator, you'll know that I've recently been trying to add support for the console's addon - the Mega CD. Last time, I was able to get a cartridge-based Sonic ROM-hack to boot. This hack made fairly-minimal use of the Mega CD, making it easy to at least get to boot. Now, I've reached the next milestone by getting an actual commercial Mega CD game to boot! That game, of course, being Sonic CD!

    The most immediate hurdle to getting a proper Mega CD game to boot is the CD itself: my emulator was designed around reading data from a cartridge dump, so I had to add an entire new mechanism for fetching data from a CD image. While a cartridge is 'flat mapped' into the 68000's memory, allowing the CPU to see and access all of its data at once (like an array), a CD must have its data copied into a RAM buffer before the 68000 can read it. The CD is far larger than the Mega CD's RAM (700MiB vs 768KiB), so only small portions of the disc's data can be loaded at once. Data is read from the disc by making various calls to the console's BIOS.

    To test my emulator's ability to emulate said BIOS calls and correctly read data from a CD dump, I created my own Mega CD port of my Visual Sound Test homebrew. In the process of making this port, I learned about the Mega CD's start-up process, as well as which combination of BIOS calls is required to load data from the CD. In a day or two, I had a port that would run in Genesis Plus GX (another emulator that supports the Mega CD), and I began expanding my emulator to be able to run it.

    This led to the second obstacle which needed to be overcome: the Mega CD's boot process.

    The Mega Drive's boot process is incredibly simple: in the first 0x100 bytes of the ROM is a 'vector table', which is a standard data structure that the 68000 uses to initialise itself: it initialises the stack pointer and tells the 68000 where to begin executing code. Once the 68000 begins executing code, the game's code can go about initialising the rest of the Mega Drive hardware and begin playing the game.

    The Mega CD's boot process is far more complicated: there is a small header at the very start of the CD's data which details the location and size of two blobs of code: the Initial Program (IP) and System Program (SP). The IP is loaded into the Mega Drive's WORK-RAM, to be executed by the Mega Drive's CPU, while the SP is loaded into the Mega CD's PRG-RAM, to be executed by the Mega CD's CPU. The SP has a header that contains offsets to various call-backs: one for initialisation, one for the 'main' function, and one for the vertical interrupt (V-Int).

    The way the CD header works is oddly complicated, having fields that either do nothing or do not function in the way that you would expect. The data from this header is read by the Mega CD's BIOS, which it then uses to load the CD sectors that contain the IP and SP blobs into their respective parts of memory. The SP header is parsed in order to install the proper call-backs, which the BIOS then proceeds to call. The IP and SP programs both run, taking over from the BIOS and running the game. It's extremely unlikely that an entire game can be fit in the IP and SP blobs, so instead these often act as a 'chain-loader', communicating with the BIOS to load more sectors from the CD which contain more code and data. Sonic CD in particular has files on its CD that are called 'IPX' and 'SPX', which contain code that is responsible for loading and running the actual game.

    To handle all of this complicated initialisation logic, the Mega CD relies on its BIOS. However, my emulator does not use the Mega CD's BIOS, instead favouring the 'High-Level Emulation' approach. Because of this, my emulator can't simply run the BIOS - it has to be the BIOS, doing all of its tasks in its absence. This is comparable to playing Sonic 1, not by emulating the Mega Drive, but by just making your own Sonic 1 from scratch. Because of this, my emulator has to manually perform the entire Mega CD boot process itself, reading the first CD sector, parsing the header, loading the IP and SP programs, parsing the SP's header, and finally running them.

    My Visual Sound Test port's IP will colour the screen red to show that it is running. If the SP is also running, then the IP will detect it and colour the screen green. After that, the SP will load the Visual Sound Test as one big binary blob into WORD-RAM, pass WORD-RAM to the MAIN-CPU, and IP will jump into it, completing the initialisation process and running the Visual Sound Test.

    With proper implementation of the boot process, the IP and SP were working together to colour the screen green. One thing was stopping the Visual Sound Test from running: the lack of BIOS calls.

    As said before, games load data from the CD by calling the BIOS. The BIOS is given a value that denotes an operation to be performed, and the BIOS does it. Without an actual BIOS, my emulator has to fill its role, receiving these values and performing the task that the BIOS would have done in response. This is fairly simple to do: to run a BIOS call, the SUB-CPU jumps to address 0x5F22, causing the 68000 to read a word of machine code from address 0x5F22. By detecting reads from address 0x5F22 in my 68000 emulator's bus event call-back, I can perform the requested BIOS task and then return the machine code of an 'rts' (return) instruction to the 68000, causing it to exit the BIOS call and resume the game code.

    By analysing Sega's official BIOS documentation, sample code provided with the so-called 'DDK' (an SDK from the 90s), and disassemblies of Sonic CD and the Mega CD BIOS, I was able to implement rough approximations of several BIOS calls related to reading the CD. With this done, my Visual Sound Test homebrew was able to boot and run perfectly!

    [​IMG]
    (This is an old screenshot, so just pretend that this is running in my emulator and that it's the Mega CD port.)

    There was one small issue that's worth mentioning here: Mega CD games are required to insert some "security code" (a Sega logo splash screen) at the start of their IP. For whatever reason, this code would crash in my emulator, so I made my emulator simply skip it for now. This code is not essential in any way, to my knowledge.

    With my ported homebrew booting, I moved onto finally getting Sonic CD to boot! There was much debugging, as various mistakes in my emulator were causing the boot process to fail very early on, but eventually files were finally being properly chain-loaded: from IP to IPX to MDINIT to BURAMINIT... which would indefinitely hang.

    BURAM (Back-Up RAM) is where save data is stored. BURAM has its own series of related BIOS calls which needed implementing (notably, they use address 0x5F16 instead of 0x5F22), but upon stubbing these out (all returning an error code), I was greeted by this:

    [​IMG]

    Finally, a sign of life from Sonic CD! I don't know a lick of Japanese, but I assume that this is an error screen of some sort. It won't let you proceed past it, so I made some of the BURAM BIOS calls pretend to run successfully to bypass it. Unfortunately, the game would freeze between this stage of initialisation and running the title screen. This was hard to debug, and had me stumped for a few days. Confused and demotivated, I forced myself to spend a few hours today trying to find the problem, only to discover that it was the result of an interrupt handler in my stub SUB-CPU BIOS not preserving the registers! This caused a loop that was intended to clear a data buffer to begin clearing the code buffer, including itself. Upon fixing this, I ran the emulator one more time and was blown away to see this:

    [​IMG]

    Victory! Sonic CD boots! Unfortunately, it crashes when I try to start a new game, but still, this is a great milestone!

    It's a strange thought that one of my emulator's first milestones was reaching the title screen of Sonic 1, and now, after all this time, the latest milestone is reaching the title screen of Sonic CD. Things sure have come a long way from this emulator being a 68000 interpreter and VDP renderer held together by a little bus logic. Soon, I hope to have Sonic running around Palmtree Panic Zone!
     
    Last edited: Oct 11, 2023
  14. Chimes

    Chimes

    The One SSG-EG Maniac Member
    456
    359
    63
    I'm pretty sure I've never seen that Sonic CD graphic before. Are there more error messages?
     
  15. Devon

    Devon

    Powered by a malfunctioning Motorola 68000 Tech Member
    1,088
    1,168
    93
    your mom

    Corrupt BuRAM (English, Japanese)
    [​IMG] [​IMG]

    Internal BuRAM unformatted (USA, Europe, Japan)
    [​IMG] [​IMG] [​IMG]

    Cartridge BuRAM unformatted (English, Japanese)
    [​IMG] [​IMG]

    BuRAM full (English, Japanese)
    [​IMG] [​IMG]

    The first 3 errors cannot be advanced past. The last one, as it says, will allow you to play the game without saving.

    (Added to the wiki btw)
     
    Last edited: Oct 12, 2023
    • Informative Informative x 4
    • List
  16. OrionNavattan

    OrionNavattan

    Member
    127
    114
    43
    Oregon
    If I’m not mistaken, you’re the first to attempt Mega CD emulation without the use of a dumped BIOS bootrom, which is significant to put it lightly (though the option to use a dumped bootrom would be a nice feature to have). I’ll definitely want to test my Mode 1 Template ROM once you release the Mega CD features (I doubt it’ll work at this time since it does use some of the more obscure features of the gate array).
     
  17. Clownacy

    Clownacy

    Tech Member
    1,006
    464
    63
    In the last post, I mentioned that my emulator does not use the Mega CD's BIOS program because it favours the 'High-Level Emulation' approach. In this post, I'll go over what that means and how it will affect my emulator.

    Other emulators, such as Genesis Plus GX and Kega Fusion, require that the user provide their own copy of the Mega CD's BIOS, which has to be extracted from a Mega CD. Without this, the emulator will be unable to play Mega CD games. I cannot bundle this BIOS with my emulator because of copyright limitations (Sega owns the BIOS and I don't have the legal right to distribute it). However, expecting the user to provide their own copy of the BIOS is not an acceptable solution to me, as it creates busywork for the user: good software should be as easy to use as possible, and expecting the user to buy a Mega CD, extract its BIOS, and then configure the emulator to use it, is the furthest thing from easy. Likewise, expecting the user to download the BIOS from some random website is also unnecessary busywork (though, legal or not, a person certainly has a moral right to download software that they already own a physical copy of).

    This means that the most user-friendly option is to forgo requiring the original BIOS entirely. This leaves me with two options: make my own open-source BIOS, or make my emulator not need a BIOS at all.

    Making my own BIOS should not require much explanation: I just have to create my own BIOS that implements the same API. If I am able to do so without copying any copyrighted material (code, graphics, or sound) from the original BIOS, then my BIOS will legally be my property, and I can freely distribute it with my emulator.

    Making my emulator not require a BIOS at all is a bit more complicated: typically, an emulator recreates the behaviour of a console's hardware, and then runs the console's software on top of it. This is known as Low-Level Emulation (LLE), because the 'lower layer' (the hardware) is the part that is being recreated by the emulator. However, it is possible for an emulator to instead recreate the 'higher layer' (the software), performing what is called High-Level Emulation (HLE). This is how an emulator can be made to not require a BIOS: instead of recreating the behaviour of the underlying hardware, and then running the original BIOS, which interacts with said hardware, the emulator can instead recreate the behaviour of the BIOS itself, making the original BIOS (as well as its underlying hardware) redundant.

    There are various trade-offs between using the original BIOS, making my own BIOS, and making my emulator not need a BIOS:

    Using the original BIOS is the most accurate solution, as it is the same software that is used by a real Mega CD. This means that all of the behaviours and bugs will be the same. However, the original BIOS is burdened by copyright issues, making it the most awkward option for the user. In addition, it is an awkward solution for me, the emulator developer, as I have to make my emulator emulate parts of the Mega CD hardware that are used by the BIOS. This includes the CDC, CDD, and BuRAM. The final downside of this approach is that the BIOS remains a 'black box' - obscure, obfuscated software. This makes it difficult for the user to understand what the BIOS is doing and how to make modifications to it. If a person is given software, then they deserve to be able to understand and modify it as easily as is feasible, and relying on a binary blob completely undermines that.

    Making my own BIOS rids the user of the difficulty of obtaining a copy of the original BIOS, but places a burden on me by requiring that I program an entire BIOS from scratch. The new BIOS may be inaccurate to the original one, differing in intended behaviour, suffering from bugs that the original did not, and missing bugs that the original had. For the new BIOS to act as a true replacement for the original, it should provide all of the same features and interact with the same underlying hardware. Because of the latter requirement, I would still have to make my emulator emulate the CDC, CDD, and BuRAM hardware, among others. On the upside, my new BIOS would be open-source, fully documented, and deobfuscated, allowing the user to understand, modify, and even distribute it with relative ease. However, I say only 'relative' ease because the BIOS would be at least partly written in Motorola 68000 assembly language, which is a fairly unknown language in today's world. The rest of the emulator is written in ANSI C, so it may be too much to expect the average person browsing the emulator's source code to comprehend the BIOS's code. One last upside of creating my own BIOS is that it could be used outside of my emulator: it could be used with other emulators, or even with a real Mega CD!

    Making my emulator not need a BIOS at all also rids the user of the burden of sourcing a copy of the original BIOS, and has the same downside of having questionable accuracy. However, it bypasses the need for my emulator to emulate the CDC, CDD, and BuRAM hardware, as it is (at least mostly) encapsulated by the BIOS. No BIOS; no hardware. This is similar to how WINE doesn't need to emulate a whole PC just to run a Windows program. I think some of the CDC's registers are interacted with directly by games' SUB-CPU programs, but that shouldn't require emulating the entire CDC. Code related to replacing the functionality of the BIOS would be part of the emulator itself, and therefore would be written in the same language as the rest of the emulator - ANSI C. That would make this the best option when it comes to users being able to read and modify the code. However, naturally, this code is tied to my emulator and cannot be used with other emulators nor a real Mega CD. To some extent, there may be a performance upside to this approach, as my emulator would be running native code instead of running emulated code in a CPU interpreter and emulating a variety of additional hardware components. HLE code is also significantly easier to write than a custom BIOS, as HLE code does not need to interact with the underlying hardware that a true BIOS would, making me to free to implement functionality as I see fit.

    I hope that this comparison has made it clear why I have opted for High-Level Emulation.

    Performing Low-Level Emulation of either an original or custom BIOS is straightforward enough: just emulate the underlying hardware as with any other part of the Mega Drive and Mega CD hardware and then run the BIOS just like it were a game. While it is not simple in execution, it is simple in concept. High-Level Emulation is more complicated, due to it crossing the line between software and hardware. So, how exactly does one make a Mega CD emulator not require a Mega CD BIOS?

    First, let's go over the boot process: using a real BIOS, this would be very simple: just boot the BIOS by resetting the Mega Drive's 68000 CPU with the BIOS's vector table mapped to address 0x000000, and the BIOS will handle communicating with the CDC and other hardware to load and execute the Initial Program (IP) and System Program (SP) from the CD. With HLE, however, the emulator must do this manually: when an attempt is made to reset the Mega Drive's 68000 CPU, the emulator must intercept this and load the IP and SP on its own, configure the Mega Drive and Mega CD to the expected state, and then allow the 68000 CPU to resume execution.

    The BIOS is also responsible for interrupt handling, however it appears to mostly just bounce the interrupts to a secondary interrupt table in RAM, which can be modified by the game in order for it to install its own interrupt handlers. This can be recreated by simply populating the vector table and secondary table in RAM with the expected values on boot.

    Next is the BIOS call process: when a SUB-CPU program wants the BIOS to do something, it stores a value into data register 0 and then jumps to address 0x5F22. In the original BIOS, the code at 0x5F22 is the start of a function which uses the value in data register 0 to select an action, which it then performs. These actions include lighting-up the LEDs on the front of the Mega CD, opening and closing the disc drive, playing music from the CD, and reading data from the CD. To recreate this with High-Level Emulation, I have to detect when the SUB-CPU has jumped to address 0x5F22. The way I do this is by exploiting the emulated 68000 CPU's bus mechanism. As a real 68000 CPU runs, it is constantly fetching code through 'bus events', which involves the CPU essentially pausing itself, signalling that it wants some data from an address, signalling that address, and then waiting for it to be given that data. This is very similar to a function call, and that is exactly what my emulator uses to emulate bus events. In the function, my emulator will check if the address and the CPU's program counter (the address of the code currently being executed) are both 0x5F22, and if so, it performs the action that corresponds to the value inside data register 0. The function will then return the machine code for an 'rts' instruction, causing the emulated 68000 CPU to immediately return to the code that it came from, as if it had ran a proper BIOS function.

    Under-the-hood, my emulator is free to perform its actions however it wants, regardless of how the original BIOS did it, so long as it provides the same API. This allows me to make certain quality-of-life improvements that would not be possible if the emulator were using the original BIOS. For instance, Genesis Plus GX stores all of its Mega CD save data in a single file, which contains the contents of BuRAM. Because my emulator does not emulate BuRAM, however, it is free to deviate from what a real Mega CD does: notably, because the BIOS's BuRAM API is file-oriented, I can make each game's save data its own file on the user's PC!

    And that's everything I can think of to say about High-Level Emulation: its upsides, its downsides, how it differs from Low-Level Emulation, and how it is done. I hope that this has been interesting. I realised that I really skimmed over this in my last post, which is unfortunate because the nitty-gritty technical stuff is my favourite part of the Dolphin, Citra, and Yuzu progress reports, and it's what I hoped to provide by starting a blog in the first place.
     
    • Informative Informative x 4
    • Like Like x 2
    • List
  18. Chimes

    Chimes

    The One SSG-EG Maniac Member
    456
    359
    63
    Holy fuck uhhhh I think youre the first person ever to document these, especially that Robotonic error. Nice!
     
  19. Brainulator

    Brainulator

    Regular garden-variety member Member
    I do wonder if there's any appetite to letting users provide a BIOS should they wish to... then again, I'm not sure what good this would do besides letting you listen to CDs or the BIOS music itself.
     
  20. OrionNavattan

    OrionNavattan

    Member
    127
    114
    43
    Oregon
    As someone who loves the technical explanations on Dolphin's development blog, I deeply appreciate this in-depth explanation. It makes a lot of sense now as to why you went with the HLE approach (though writing a replacement BIOS would be an interesting project, given how badly written some parts of the original BIOS are).

    Code (ASM):
    1. sendInt2ToSubCpu:
    2.        ; Why do it in one instruction when you can use four?
    3.        move.l  a5,-(sp)
    4.  
    5.        lea  (mcd_reset).l,a5
    6.        bset #mcd_int_bit,mcd_md_interrupt-mcd_reset(a5) ; bset #0,-1(a5)
    7.  
    8.        movea.l (sp)+,a5
    9.        rts
    10.  

    The concern I have is there are a couple of edge cases that HLE will need to account for. It is possible for a Mode 1 program to completely skip the sub CPU BIOS and instead control the hardware directly (and in fact I believe the MSU-MD driver actually does so). Additionally, the bootrom has a jump table of function entry points at $280 that, while meant to be used by the bootrom itself, can be called by user programs. @RyogaMasaki discovered a while back that at least one game, Keio Flying Squadron, actually uses some of those functions, and that many of them, including slightly modified copies of the standard Nemesis and Enigma decompressors (both take the source and destination in a1 and a2), also work in Mode 1!
     
    • Informative Informative x 2
    • List