Skip to contentSkip to conversation

Add OPL3 support to SB16

PATCH New ~bboe 1 participant 3 messages May 6 Arm/Amlogic Meson SoC support

lore
Share & tools
lore

~bboe

author
#0 lore raw

PATCH 1/3 Add OPL3 support to SB16

From: Bryce Boe <[email protected]>

The existing SB16 device does not have OPL3 support, and the AdLib device supports only OPL2.

This patch hopes to expand that support by leveraging Nuked OPL3.

The end result of the patch can be verified by the following OPL test. Assemble and run using the instructions below. Observe that on existing Qemu builds no audio is produced with the sb16 device. Similarly observe that adlib is missing sounds which sb16 on this patch produces:

```
; 512-byte boot sector demonstrating OPL3's extra 9 voices.
;
; Phase A: key-on 9 voices in the OPL2-compat first register set
;           (D-F#-A in octaves 2/3/4). Both adlib and OPL3 sb16 hear this.
; Phase B: 1.5 s later, key-on 9 voices in the OPL3 second register set
;           (D-F#-A in octaves 5/6/7). adlib has no second register set, so it
;           hears nothing extra; OPL3 hears the chord double in span.
; Phase C: hold, then release everything and halt.
;
; Build : nasm -f bin opldemo.asm -o opldemo.bin
; Boot  : qemu-system-i386 -fda opldemo.bin -audiodev coreaudio,id=s0 \
          -device sb16,audiodev=s0  ; Replace sb16 with adlib to test OPL2

bits 16
org  0x7C00

%define ADDR_LO 0x388       ; first register set: voices 0..8
%define ADDR_HI 0x38A       ; second register set: OPL3 voices 9..17

start:
    cli
    xor ax, ax
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, ax
    sti

    mov si, message
.print_loop:
    lodsb
    test al, al
    jz  .print_done
    mov ah, 0x0E
    int 0x10
    jmp .print_loop
.print_done:

    ; Enable OPL3 mode (writes register 0x105 = 0x01 via second set)
    mov dx, ADDR_HI
    mov al, 0x05
    out dx, al
    inc dx
    mov al, 0x01
    out dx, al

    ; Program 18 operators in each set with the same simple instrument
    mov bp, ADDR_LO
    call program_voices
    mov bp, ADDR_HI
    call program_voices

    ; Lower chord is always sustained; upper chord pulses on/off so the
    ; OPL3-only voices come and go without any silence between cycles.
    mov bp, ADDR_LO
    mov si, chord_low
    xor dl, dl
    call play_chord

.forever:
    mov cx, 30
    call wait_ticks            ; ~1.6 s, lower chord only

    ; Upper chord on (OPL3 voices 9..17; no-op writes on adlib)
    mov bp, ADDR_HI
    mov si, chord_low
    mov dl, 0x0C
    call play_chord

    mov cx, 30
    call wait_ticks            ; ~1.6 s, both chords on OPL3

    ; Release upper chord
    call silence_chord

    jmp .forever

play_chord:
    mov  cx, 9
    mov  bl, 0
.each:
    mov  al, 0xA0
    add  al, bl
    mov  ah, [si]
    call opl_write
    inc  si

    mov  al, 0xB0
    add  al, bl
    mov  ah, [si]
    add  ah, dl
    call opl_write
    inc  si

    inc  bl
    loop .each
    ret

opl_write:
    push dx
    mov  dx, bp
    out  dx, al
    inc  dx
    mov  al, ah
    out  dx, al
    pop  dx
    ret

program_voices:
    mov si, instrument
.next_register:
    lodsw
    test ax, ax
    jz .program_done
    xchg ax, dx
    mov bx, operator_offsets
    mov cx, 18
.each:
    mov al, dl
    add al, [bx]
    mov ah, dh
    call opl_write
    inc bx
    loop .each
    jmp .next_register
.program_done:

    ; 9 voice-level connection registers: 0xC0..0xC8 = 0x30
    ; (bit 4 = left speaker, bit 5 = right speaker, bit 0 = FM connection)
    mov bl, 8
.connection_loop:
    mov al, 0xC0
    add al, bl
    mov ah, 0x30
    call opl_write
    dec bl
    jns .connection_loop
    ret

silence_chord:
    mov  bl, 8
.each:
    mov  al, 0xB0
    add  al, bl
    mov  ah, 0
    call opl_write
    dec  bl
    jns  .each
    ret

wait_ticks:
    mov  si, cx
    mov  ah, 0
    int  0x1A
    mov  bx, dx
.poll:
    mov  ah, 1
    int  0x16
    jz   .nokey
    mov  dx, 0x604           ; PIIX4 PM1a control (PMBASE 0x600 + 0x04)
    mov  ax, 0x2000          ; SLP_EN=1, SLP_TYP=S5
    out  dx, ax
.nokey:
    mov  ah, 0
    int  0x1A
    sub  dx, bx
    cmp  dx, si
    jb   .poll
    ret

chord_low:
    db 0x81, 0x29        ; D2  (block 2, FNum 0x0181)
    db 0xE5, 0x29        ; F#2 (block 2, FNum 0x01E5)
    db 0x41, 0x2A        ; A2  (block 2, FNum 0x0241 → high 0x02)
    db 0x81, 0x2D        ; D3  (block 3)
    db 0xE5, 0x2D        ; F#3
    db 0x41, 0x2E        ; A3
    db 0x81, 0x31        ; D4  (block 4)
    db 0xE5, 0x31        ; F#4
    db 0x41, 0x32        ; A4

instrument:
    db 0x20, 0x21       ; mult=1, EG=on
    db 0x40, 0x10       ; KSL=0, TL=16
    db 0x60, 0xF0       ; attack=15, decay=0
    db 0x80, 0x77       ; sustain=7, release=7
    db 0xE0, 0x00       ; sine wave
    dw 0                ; terminator

message:
    db 'OPL2 vs OPL3 voice demo', 13, 10
    db 'Press any key to shutdown', 13, 10, 0

operator_offsets:
    db 0,1,2,3,4,5, 8,9,10,11,12,13, 16,17,18,19,20,21


times 510-($-$$) db 0
dw 0xAA55
```

To: [email protected]

Cc Gerd Hoffmann <[email protected]>
Cc Fabiano Rosas <[email protected]>
Cc Laurent Vivier <[email protected]>
Cc Paolo Bonzini <[email protected]>

--- b4-submit-tracking ---
# This section is used internally by b4 prep for tracking purposes. {

  "series": {
    "revision": 1,
    "change-id": "20260505-sd16-opl3-74669607a11c",
    "prefixes": [],
    "presubject": ""

}
}

Signature · 1 line
2.49.1
author
#1 lore raw

PATCH 2/3 Add the Nuked OPL3 emulator

From: Bryce Boe <[email protected]>

I chose this emulator, by Alexey Khokholov, as it appears to be well used among DOS-target emulation software.

Source:
https://github.com/nukeykt/Nuked-OPL3/tree/cfedb09efc03f1d7b5fc1f04dd449d77d8c49d50

Two files were copied verbatim with the following exceptions:

- Added nuked_ prefix to clearly mark the source.
- Modified the header import due to the rename

Please note that I did not adapt the style of these files to make it easier to diff with upstream.

I added the test file under unit tests because it does not depend on a running Qemu instance. There doesn't seem to be precedence for hardware unit tests.

---
 hw/audio/meson.build         |    2 +-
 hw/audio/nuked_opl3.c        | 1530 ++++++++++++++++++++++++++++++++++
 hw/audio/nuked_opl3.h        |  173 ++++
 tests/unit/test-nuked-opl3.c |  109 +++
 4 files changed, 1813 insertions(+), 1 deletion(-)
 create mode 100644 hw/audio/nuked_opl3.c
 create mode 100644 hw/audio/nuked_opl3.h
 create mode 100644 tests/unit/test-nuked-opl3.c
hw/audio/meson.build +1 -1
index 2154cbdb57..5bd0b6e4c2 100644
@@ -10,7 +10,7 @@ system_ss.add(when: 'CONFIG_HDA', if_true: files('intel-hda.c', 'hda-codec.c'))
 system_ss.add(when: 'CONFIG_MARVELL_88W8618', if_true: files('marvell_88w8618.c'))
 system_ss.add(when: 'CONFIG_PCSPK', if_true: files('pcspk.c'))
 system_ss.add(when: 'CONFIG_PL041', if_true: files('pl041.c', 'lm4549.c'))
-system_ss.add(when: 'CONFIG_SB16', if_true: files('sb16.c'))
+system_ss.add(when: 'CONFIG_SB16', if_true: files('sb16.c', 'nuked_opl3.c'))
 system_ss.add(when: 'CONFIG_VT82C686', if_true: files('via-ac97.c'))
 system_ss.add(when: 'CONFIG_WM8750', if_true: files('wm8750.c'))
 system_ss.add(when: ['CONFIG_VIRTIO_SND', 'CONFIG_VIRTIO'], if_true: files('virtio-snd.c'))
hw/audio/nuked_opl3.c new file +1530 -0

1,530 lines not on this page · raw message

hw/audio/nuked_opl3.h new file +173 -0

173 lines not on this page · raw message

tests/unit/test-nuked-opl3.c new file +109 -0

109 lines not on this page · raw message

Signature · 1 line
2.49.1
author
#2 lore raw

PATCH 3/3 Add OPL3 support to SB16

In reply to ~bboe

From: Bryce Boe <[email protected]>

Nuked-OPL3 silently drops writes to bank-0 registers 0x02-0x04, so we maintain the status byte ourselves. sb16_opl3_write updates opl3_status when the guest writes register 0x04 (Timer Control). We use a similar advance-on-write pattern as hw/audio/adlib.c uses with fmopl.

---
 hw/audio/sb16.c              | 176 ++++++++++++++++++++++++++++++++++-
 tests/qtest/meson.build      |   2 +-
 tests/qtest/sb16-opl3-test.c |  45 +++++++++
 3 files changed, 217 insertions(+), 6 deletions(-)
 create mode 100644 tests/qtest/sb16-opl3-test.c
hw/audio/sb16.c +171 -5
index 1838d3ef7b..a05337d9f9 100644
@@ -24,6 +24,7 @@
 
 #include "qemu/osdep.h"
 #include "hw/audio/model.h"
+#include "hw/audio/nuked_opl3.h"
 #include "qemu/audio.h"
 #include "hw/core/irq.h"
 #include "hw/isa/isa.h"
@@ -112,8 +113,22 @@ struct SB16State {
     int mixer_nreg;
     uint8_t mixer_regs[256];
     PortioList portio_list;
+
+    /* OPL3 (FM) integration; see nuked_opl3.h */
+    opl3_chip opl3;
+    bool opl3_active;
+    uint16_t opl3_latched_reg;
+    int16_t *opl3_mix_buffer;
+    PortioList opl3_portio_list_388;
+    PortioList opl3_portio_list_mirror;
+    unsigned int opl3_samples;
+    uint8_t opl3_status;
+    SWVoiceOut *opl3_voice;
 };
 
+/* OPL native sample rate: 14.31818 MHz / 288. */
+#define SB16_OPL3_FREQ 49716
+
 #define SAMPLE_RATE_MIN 5000
 #define SAMPLE_RATE_MAX 45000
 
@@ -1325,6 +1340,30 @@ static int sb16_post_load (void *opaque, int version_id)
     return 0;
 }
 
+static bool sb16_opl3_needed(void *opaque)
+{
+    SB16State *state = opaque;
+    return state->opl3_active;
+}
+
+static const VMStateDescription vmstate_sb16_opl3 = {
+    .name = "sb16/opl3",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .needed = sb16_opl3_needed,
+    /*
+     * FM waveform state does not survive snapshots, so
+     * audio restarts after a snapshot reload until the guest writes
+     * registers again.
+     */
+    .fields = (const VMStateField[]) {
+        VMSTATE_BOOL(opl3_active, SB16State),
+        VMSTATE_UINT16(opl3_latched_reg, SB16State),
+        VMSTATE_UINT8(opl3_status, SB16State),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
 static const VMStateDescription vmstate_sb16 = {
     .name = "sb16",
     .version_id = 1,
@@ -1380,6 +1419,10 @@ static const VMStateDescription vmstate_sb16 = {
         VMSTATE_BUFFER (mixer_regs, SB16State),
 
         VMSTATE_END_OF_LIST ()
+    },
+    .subsections = (const VMStateDescription * const []) {
+        &vmstate_sb16_opl3,
+        NULL
     }
 };
 
@@ -1393,6 +1436,120 @@ static const MemoryRegionPortio sb16_ioport_list[] = {
     PORTIO_END_OF_LIST (),
 };
 
+static void sb16_opl3_callback(void *opaque, int free)
+{
+    unsigned int samples;
+    SB16State *state = opaque;
+
+    if (!state->opl3_active || !state->opl3_voice || free < 4) {
+        return;
+    }
+
+    /* stereo has 4 bytes per frame; cap to mix_buffer capacity */
+    samples = MIN((unsigned int)(free / 4), state->opl3_samples);
+
+    OPL3_GenerateStream(&state->opl3, state->opl3_mix_buffer, samples);
+    audio_be_write(state->audio_be, state->opl3_voice, state->opl3_mix_buffer,
+                   samples * 4);
+}
+
+static uint32_t sb16_opl3_read(void *opaque, uint32_t nport)
+{
+    SB16State *state = opaque;
+    return state->opl3_status;
+}
+
+static void sb16_opl3_write(void *opaque, uint32_t nport, uint32_t val)
+{
+    int port_offset = nport & 3;
+    SB16State *state = opaque;
+
+    if (!state->opl3_active) {
+        state->opl3_active = true;
+        audio_be_set_active_out(state->audio_be, state->opl3_voice, 1);
+    }
+
+    switch (port_offset) {
+    case 0:  /* bank-0 address latch */
+        state->opl3_latched_reg = val & 0xff;
+        break;
+    case 2:  /* bank-1 address latch */
+        state->opl3_latched_reg = (val & 0xff) | 0x100;
+        break;
+    case 1:  /* bank-0 data commit */
+    case 3:  /* bank-1 data commit; bank bit already in opl3_latched_reg */
+        /*
+         * Bank-0 reg 0x04 is OPL Timer Control. Nuked-OPL3 ignores it,
+         * so we synthesize the status byte here. Bit 7 = IRQ reset
+         * (clears status); else status reflects start+mask bits per
+         * AdLib/OPL3 semantics:
+         *   ctrl bit 0: T1 start    ctrl bit 6: T1 mask
+         *   ctrl bit 1: T2 start    ctrl bit 5: T2 mask
+         */
+        if (state->opl3_latched_reg == 0x04) {
+            if (val & 0x80) {
+                state->opl3_status = 0;
+            } else {
+                uint8_t status = 0;
+                if ((val & 0x01) && !(val & 0x40)) {
+                    status |= 0x40;
+                }
+                if ((val & 0x02) && !(val & 0x20)) {
+                    status |= 0x20;
+                }
+                if (status) {
+                    status |= 0x80;
+                }
+                state->opl3_status = status;
+            }
+        }
+        OPL3_WriteRegBuffered(&state->opl3, state->opl3_latched_reg,
+                              val & 0xff);
+        break;
+    default:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "sb16-opl3: invalid port_offset %d\n", port_offset);
+    }
+}
+
+static const MemoryRegionPortio sb16_opl3_portio_list_388[] = {
+    { 0, 4, 1, .read = sb16_opl3_read, .write = sb16_opl3_write },
+    PORTIO_END_OF_LIST(),
+};
+static const MemoryRegionPortio sb16_opl3_portio_list_mirror[] = {
+    { 0, 4, 1, .read = sb16_opl3_read, .write = sb16_opl3_write },
+    PORTIO_END_OF_LIST(),
+};
+
+static void sb16_opl3_realize(SB16State *state, ISADevice *isadev)
+{
+    struct audsettings as = {
+        .freq = SB16_OPL3_FREQ,
+        .nchannels = 2,
+        .fmt = AUDIO_FORMAT_S16,
+        .big_endian = HOST_BIG_ENDIAN,
+    };
+
+    OPL3_Reset(&state->opl3, SB16_OPL3_FREQ);
+
+    state->opl3_voice = audio_be_open_out(state->audio_be, NULL, "sb16-opl3",
+                                          state, sb16_opl3_callback, &as);
+    if (!state->opl3_voice) {
+        warn_report("sb16: OPL3 audio voice open failed; FM disabled");
+        return;
+    }
+
+    state->opl3_samples =
+        audio_be_get_buffer_size_out(state->audio_be, state->opl3_voice) / 4;
+    state->opl3_mix_buffer = g_malloc0(state->opl3_samples * 4);
+    isa_register_portio_list(isadev, &state->opl3_portio_list_388,
+                             0x388, sb16_opl3_portio_list_388,
+                             state, "sb16-opl3-alt");
+    isa_register_portio_list(isadev, &state->opl3_portio_list_mirror,
+                             state->port, sb16_opl3_portio_list_mirror,
+                             state, "sb16-opl3-mirror");
+}
+
 
 static void sb16_initfn (Object *obj)
 {
@@ -1437,6 +1594,8 @@ static void sb16_realizefn (DeviceState *dev, Error **errp)
     isa_register_portio_list(isadev, &s->portio_list, s->port,
                              sb16_ioport_list, s, "sb16");
 
+    sb16_opl3_realize(s, isadev);
+
     k = ISADMA_GET_CLASS(s->isa_hdma);
     k->register_channel(s->isa_hdma, s->hdma, SB_read_DMA, s);
 
@@ -1446,6 +1605,12 @@ static void sb16_realizefn (DeviceState *dev, Error **errp)
     s->can_write = 1;
 }
 
+static void sb16_finalizefn(Object *obj)
+{
+    SB16State *state = SB16(obj);
+    g_free(state->opl3_mix_buffer);
+}
+
 static const Property sb16_properties[] = {
     DEFINE_AUDIO_PROPERTIES(SB16State, audio_be),
     DEFINE_PROP_UINT32 ("version", SB16State, ver,  0x0405), /* 4.5 */
@@ -1467,11 +1632,12 @@ static void sb16_class_initfn(ObjectClass *klass, const void *data)
 }
 
 static const TypeInfo sb16_info = {
-    .name          = TYPE_SB16,
-    .parent        = TYPE_ISA_DEVICE,
-    .instance_size = sizeof (SB16State),
-    .instance_init = sb16_initfn,
-    .class_init    = sb16_class_initfn,
+    .name              = TYPE_SB16,
+    .parent            = TYPE_ISA_DEVICE,
+    .instance_size     = sizeof(SB16State),
+    .instance_init     = sb16_initfn,
+    .instance_finalize = sb16_finalizefn,
+    .class_init        = sb16_class_initfn,
 };
 
 static void sb16_register_types (void)
tests/qtest/meson.build +1 -1
index 43f83ffd3a..734132fb08 100644
@@ -92,7 +92,7 @@ qtests_i386 = \
   (config_all_devices.has_key('CONFIG_VIRTIO_SCSI') ? ['fuzz-virtio-scsi-test'] : []) +     \
   (config_all_devices.has_key('CONFIG_VIRTIO_BALLOON') ? ['virtio-balloon-test'] : []) + \
   (config_all_devices.has_key('CONFIG_Q35') ? ['q35-test'] : []) +                          \
-  (config_all_devices.has_key('CONFIG_SB16') ? ['fuzz-sb16-test'] : []) +                   \
+  (config_all_devices.has_key('CONFIG_SB16') ? ['fuzz-sb16-test','sb16-opl3-test'] : []) +                   \
   (config_all_devices.has_key('CONFIG_SDHCI_PCI') ? ['fuzz-sdcard-test'] : []) +            \
   (config_all_devices.has_key('CONFIG_ESP_PCI') ? ['am53c974-test'] : []) +                 \
   (config_all_devices.has_key('CONFIG_VTD') ? ['intel-iommu-test'] : []) +                 \
tests/qtest/sb16-opl3-test.c new file +45 -0

45 lines not on this page · raw message

Signature · 1 line
2.49.1