text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```c++ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "resid-fp/sid.h" #include <86box/plat.h> #include <86box/snd_resid.h> #define RESID_FREQ 48000 using reSIDfp::SID; typedef struct psid_t { /* resid sid implementation */ SID *sid; int16_t last_sample; } psid_t; psid_t *psid; void * sid_init(void) { #if 0 psid_t *psid; #endif reSIDfp::SamplingMethod method = reSIDfp::DECIMATE; float cycles_per_sec = 14318180.0 / 16.0; psid = new psid_t; #if 0 psid = (psid_t *) malloc(sizeof(sound_t)); #endif psid->sid = new SID; psid->sid->setChipModel(reSIDfp::MOS8580); psid->sid->enableFilter(true); psid->sid->reset(); for (uint8_t c = 0; c < 32; c++) psid->sid->write(c, 0); try { psid->sid->setSamplingParameters(cycles_per_sec, method, (float) RESID_FREQ, 0.9 * (float) RESID_FREQ / 2.0); } catch (reSIDfp::SIDError) { #if 0 printf("reSID failed!\n"); #endif } psid->sid->setChipModel(reSIDfp::MOS6581); psid->sid->input(0); return (void *) psid; } void sid_close(UNUSED(void *priv)) { #if 0 psid_t *psid = (psid_t *) priv; #endif delete psid->sid; #if 0 free(psid); #endif } void sid_reset(UNUSED(void *priv)) { #if 0 psid_t *psid = (psid_t *) priv; #endif psid->sid->reset(); for (uint8_t c = 0; c < 32; c++) psid->sid->write(c, 0); } uint8_t sid_read(uint16_t addr, UNUSED(void *priv)) { #if 0 psid_t *psid = (psid_t *) priv; #endif return psid->sid->read(addr & 0x1f); #if 0 return 0xFF; #endif } void sid_write(uint16_t addr, uint8_t val, UNUSED(void *priv)) { #if 0 psid_t *psid = (psid_t *) priv; #endif psid->sid->write(addr & 0x1f, val); } #define CLOCK_DELTA(n) (int) (((14318180.0 * n) / 16.0) / (float) RESID_FREQ) static void fillbuf2(int &count, int16_t *buf, int len) { int c; c = psid->sid->clock(count, buf); if (!c) *buf = psid->last_sample; psid->last_sample = *buf; } void sid_fillbuf(int16_t *buf, int len, UNUSED(void *priv)) { #if 0 psid_t *psid = (psid_t *) priv; #endif int x = CLOCK_DELTA(len); fillbuf2(x, buf, len); } ```
/content/code_sandbox/src/sound/snd_resid.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
773
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * VIA AC'97 audio controller emulation. * * * * Authors: RichardG, <richardg867@gmail.com> * */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/mem.h> #include <86box/pci.h> #include <86box/pic.h> #include <86box/snd_ac97.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/plat_unused.h> typedef struct ac97_via_sgd_t { uint8_t id; uint8_t always_run; struct _ac97_via_ *dev; uint32_t entry_ptr; uint32_t sample_ptr; uint32_t fifo_pos; uint32_t fifo_end; int32_t sample_count; uint8_t entry_flags; uint8_t fifo[32]; uint8_t restart; int16_t out_l; int16_t out_r; int vol_l; int vol_r; int pos; int32_t buffer[SOUNDBUFLEN * 2]; uint64_t timer_latch; pc_timer_t dma_timer; pc_timer_t poll_timer; } ac97_via_sgd_t; typedef struct _ac97_via_ { uint16_t audio_sgd_base; uint16_t audio_codec_base; uint16_t modem_sgd_base; uint16_t modem_codec_base; uint8_t sgd_regs[256]; uint8_t pcm_enabled : 1; uint8_t fm_enabled : 1; uint8_t vsr_enabled : 1; struct { union { uint8_t regs_codec[2][128]; uint8_t regs_linear[256]; }; } codec_shadow[2]; uint8_t pci_slot; uint8_t irq_state; int irq_pin; ac97_codec_t *codec[2][2]; ac97_via_sgd_t sgd[6]; int master_vol_l; int master_vol_r; int cd_vol_l; int cd_vol_r; } ac97_via_t; #ifdef ENABLE_AC97_VIA_LOG int ac97_via_do_log = ENABLE_AC97_VIA_LOG; static void ac97_via_log(const char *fmt, ...) { va_list ap; if (ac97_via_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define ac97_via_log(fmt, ...) #endif static void ac97_via_sgd_process(void *priv); static void ac97_via_update_codec(ac97_via_t *dev); static void ac97_via_speed_changed(void *priv); static void ac97_via_filter_cd_audio(int channel, double *buffer, void *priv); void ac97_via_set_slot(void *priv, int slot, int irq_pin) { ac97_via_t *dev = (ac97_via_t *) priv; ac97_via_log("AC97 VIA: set_slot(%d, %d)\n", slot, irq_pin); dev->pci_slot = slot; dev->irq_pin = irq_pin; } uint8_t ac97_via_read_status(void *priv, uint8_t modem) { const ac97_via_t *dev = (ac97_via_t *) priv; uint8_t ret = 0x00; /* Flag each codec as ready if present. */ for (uint8_t i = 0; i <= 1; i++) { if (dev->codec[modem][i]) ret |= 0x01 << (i << 1); } ac97_via_log("AC97 VIA %d: read_status() = %02X\n", modem, ret); return ret; } void ac97_via_write_control(void *priv, uint8_t modem, uint8_t val) { ac97_via_t *dev = (ac97_via_t *) priv; uint8_t i; ac97_via_log("AC97 VIA %d: write_control(%02X)\n", modem, val); /* Reset codecs if requested. */ if (!(val & 0x40)) { for (i = 0; i <= 1; i++) { if (dev->codec[modem][i]) ac97_codec_reset(dev->codec[modem][i]); } } if (!modem) { /* Set the variable sample rate flag. */ dev->vsr_enabled = (val & 0xf8) == 0xc8; /* Start or stop PCM playback. */ i = (val & 0xf4) == 0xc4; if (i && !dev->pcm_enabled) timer_advance_u64(&dev->sgd[0].poll_timer, dev->sgd[0].timer_latch); dev->pcm_enabled = i; /* Start or stop FM playback. */ i = (val & 0xf2) == 0xc2; if (i && !dev->fm_enabled) timer_advance_u64(&dev->sgd[2].poll_timer, dev->sgd[2].timer_latch); dev->fm_enabled = i; /* Update primary audio codec state. */ if (dev->codec[0][0]) ac97_via_update_codec(dev); } } static void ac97_via_update_irqs(ac97_via_t *dev) { /* Check interrupt flags in all SGDs. */ for (uint8_t i = 0x00; i < ((sizeof(dev->sgd) / sizeof(dev->sgd[0])) << 4); i += 0x10) { /* Stop immediately if any flag is set. Doing it this way optimizes rising edges for the playback SGD (0 - first to be checked). */ if (dev->sgd_regs[i] & (dev->sgd_regs[i | 0x2] & 0x03)) { pci_set_irq(dev->pci_slot, dev->irq_pin, &dev->irq_state); return; } } pci_clear_irq(dev->pci_slot, dev->irq_pin, &dev->irq_state); } static void ac97_via_update_codec(ac97_via_t *dev) { /* Get primary audio codec. */ ac97_codec_t *codec = dev->codec[0][0]; /* Update volumes according to codec registers. */ ac97_codec_getattn(codec, 0x02, &dev->master_vol_l, &dev->master_vol_r); ac97_codec_getattn(codec, 0x18, &dev->sgd[0].vol_l, &dev->sgd[0].vol_r); ac97_codec_getattn(codec, 0x18, &dev->sgd[2].vol_l, &dev->sgd[2].vol_r); /* VIAFMTSR sets Master, CD and PCM volumes to 0 dB */ ac97_codec_getattn(codec, 0x12, &dev->cd_vol_l, &dev->cd_vol_r); /* Update sample rate according to codec registers and the variable sample rate flag. */ ac97_via_speed_changed(dev); } uint8_t ac97_via_sgd_read(uint16_t addr, void *priv) { const ac97_via_t *dev = (ac97_via_t *) priv; #ifdef ENABLE_AC97_VIA_LOG uint8_t modem = (addr & 0xff00) == dev->modem_sgd_base; #endif addr &= 0xff; uint8_t ret; if (!(addr & 0x80)) { /* Process SGD channel registers. */ switch (addr & 0xf) { case 0x4: ret = dev->sgd[addr >> 4].entry_ptr; break; case 0x5: ret = dev->sgd[addr >> 4].entry_ptr >> 8; break; case 0x6: ret = dev->sgd[addr >> 4].entry_ptr >> 16; break; case 0x7: ret = dev->sgd[addr >> 4].entry_ptr >> 24; break; case 0xc: ret = dev->sgd[addr >> 4].sample_count; break; case 0xd: ret = dev->sgd[addr >> 4].sample_count >> 8; break; case 0xe: ret = dev->sgd[addr >> 4].sample_count >> 16; break; default: ret = dev->sgd_regs[addr]; break; } } else { /* Process regular registers. */ switch (addr) { case 0x84: ret = (dev->sgd_regs[0x00] & 0x01); ret |= (dev->sgd_regs[0x10] & 0x01) << 1; ret |= (dev->sgd_regs[0x20] & 0x01) << 2; ret |= (dev->sgd_regs[0x00] & 0x02) << 3; ret |= (dev->sgd_regs[0x10] & 0x02) << 4; ret |= (dev->sgd_regs[0x20] & 0x02) << 5; break; case 0x85: ret = (dev->sgd_regs[0x00] & 0x04) >> 2; ret |= (dev->sgd_regs[0x10] & 0x04) >> 1; ret |= (dev->sgd_regs[0x20] & 0x04); ret |= (dev->sgd_regs[0x00] & 0x80) >> 3; ret |= (dev->sgd_regs[0x10] & 0x80) >> 2; ret |= (dev->sgd_regs[0x20] & 0x80) >> 1; break; case 0x86: ret = (dev->sgd_regs[0x40] & 0x01); ret |= (dev->sgd_regs[0x50] & 0x01) << 1; ret |= (dev->sgd_regs[0x40] & 0x02) << 3; ret |= (dev->sgd_regs[0x50] & 0x02) << 4; break; case 0x87: ret = (dev->sgd_regs[0x40] & 0x04) >> 2; ret |= (dev->sgd_regs[0x50] & 0x04) >> 1; ret |= (dev->sgd_regs[0x40] & 0x80) >> 3; ret |= (dev->sgd_regs[0x50] & 0x80) >> 2; break; default: ret = dev->sgd_regs[addr]; break; } } ac97_via_log("AC97 VIA %d: sgd_read(%02X) = %02X\n", modem, addr, ret); return ret; } void ac97_via_sgd_write(uint16_t addr, uint8_t val, void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; uint8_t modem = (addr & 0xff00) == dev->modem_sgd_base; uint8_t i; ac97_codec_t *codec; addr &= 0xff; ac97_via_log("AC97 VIA %d: sgd_write(%02X, %02X)\n", modem, addr, val); /* Check function-specific read only registers. */ if ((addr >= (modem ? 0x00 : 0x40)) && (addr < (modem ? 0x40 : 0x60))) return; if (addr >= (modem ? 0x90 : 0x88)) return; if (!(addr & 0x80)) { /* Process SGD channel registers. */ switch (addr & 0xf) { case 0x0: /* Clear RWC status bits. */ dev->sgd_regs[addr] &= ~(val & 0x07); /* Update status interrupts. */ ac97_via_update_irqs(dev); return; case 0x1: /* Start SGD if requested. */ if (val & 0x80) { if (dev->sgd_regs[addr & 0xf0] & 0x80) { /* Queue SGD trigger if already running. */ dev->sgd_regs[addr & 0xf0] |= 0x08; } else { /* Start SGD immediately. */ dev->sgd_regs[addr & 0xf0] = (dev->sgd_regs[addr & 0xf0] & ~0x47) | 0x80; /* Start at the specified entry pointer. */ dev->sgd[addr >> 4].entry_ptr = *((uint32_t *) &dev->sgd_regs[(addr & 0xf0) | 0x4]) & 0xfffffffe; dev->sgd[addr >> 4].restart = 2; /* Start the actual SGD process. */ ac97_via_sgd_process(&dev->sgd[addr >> 4]); } } /* Stop SGD if requested. */ if (val & 0x40) dev->sgd_regs[addr & 0xf0] &= ~0x88; val &= 0x08; /* (Un)pause SGD if requested. */ if (val & 0x08) dev->sgd_regs[addr & 0xf0] |= 0x40; else dev->sgd_regs[addr & 0xf0] &= ~0x40; break; case 0x2: if (addr & 0x10) val &= 0xf3; break; case 0x3: case 0x8 ... 0xf: /* Read-only registers. */ return; default: break; } } else { /* Process regular registers. */ switch (addr) { case 0x30 ... 0x3f: case 0x60 ... 0x7f: case 0x84 ... 0x87: /* Read-only registers. */ return; case 0x82: /* Determine the selected codec. */ i = !!(dev->sgd_regs[0x83] & 0x40); codec = dev->codec[modem][i]; /* Keep value in register if this codec is not present. */ if (codec) { /* Read from or write to codec. */ if (val & 0x80) { if (val & 1) { /* return 0x0000 on unaligned reads (real 686B behavior) */ dev->sgd_regs[0x80] = dev->sgd_regs[0x81] = 0x00; } else { *((uint16_t *) &dev->codec_shadow[modem].regs_codec[i][val & 0x7f]) = *((uint16_t *) &dev->sgd_regs[0x80]) = ac97_codec_readw(codec, val); } /* Flag data/status/index for this codec as valid. */ dev->sgd_regs[0x83] |= 0x02 << (i << 1); } else if (!(val & 1)) { /* do nothing on unaligned writes */ ac97_codec_writew(codec, val, *((uint16_t *) &dev->codec_shadow[modem].regs_codec[i][val & 0x7f]) = *((uint16_t *) &dev->sgd_regs[0x80])); /* Update primary audio codec state if that codec was written to. */ if (!modem && !i) { ac97_via_update_codec(dev); /* Set up CD audio filter if CD volume was written to. Setting it up at init prevents CD audio from working on other cards, but this works as the CD channel is muted by default per AC97 spec. */ if (val == 0x12) sound_set_cd_audio_filter(ac97_via_filter_cd_audio, dev); } } } break; case 0x83: /* Clear RWC status bits. */ #if 0 /* race condition with Linux accessing a register and clearing status bits on the same dword write */ val = (dev->sgd_regs[addr] & ~(val & 0x0a)) | (val & 0xc0); #else val = dev->sgd_regs[addr] | (val & 0xc0); #endif break; default: break; } } dev->sgd_regs[addr] = val; } void ac97_via_remap_audio_sgd(void *priv, uint16_t new_io_base, uint8_t enable) { ac97_via_t *dev = (ac97_via_t *) priv; if (dev->audio_sgd_base) io_removehandler(dev->audio_sgd_base, 256, ac97_via_sgd_read, NULL, NULL, ac97_via_sgd_write, NULL, NULL, dev); dev->audio_sgd_base = new_io_base; if (dev->audio_sgd_base && enable) io_sethandler(dev->audio_sgd_base, 256, ac97_via_sgd_read, NULL, NULL, ac97_via_sgd_write, NULL, NULL, dev); } void ac97_via_remap_modem_sgd(void *priv, uint16_t new_io_base, uint8_t enable) { ac97_via_t *dev = (ac97_via_t *) priv; if (dev->modem_sgd_base) io_removehandler(dev->modem_sgd_base, 256, ac97_via_sgd_read, NULL, NULL, ac97_via_sgd_write, NULL, NULL, dev); dev->modem_sgd_base = new_io_base; if (dev->modem_sgd_base && enable) io_sethandler(dev->modem_sgd_base, 256, ac97_via_sgd_read, NULL, NULL, ac97_via_sgd_write, NULL, NULL, dev); } uint8_t ac97_via_codec_read(uint16_t addr, void *priv) { const ac97_via_t *dev = (ac97_via_t *) priv; uint8_t modem = (addr & 0xff00) == dev->modem_codec_base; uint8_t ret = 0xff; addr &= 0xff; ret = dev->codec_shadow[modem].regs_linear[addr]; ac97_via_log("AC97 VIA %d: codec_read(%02X) = %02X\n", modem, addr, ret); return ret; } void ac97_via_codec_write(uint16_t addr, uint8_t val, void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; uint8_t modem = (addr & 0xff00) == dev->modem_codec_base; addr &= 0xff; ac97_via_log("AC97 VIA %d: codec_write(%02X, %02X)\n", modem, addr, val); /* Unknown behavior, maybe it does write to the shadow registers? */ dev->codec_shadow[modem].regs_linear[addr] = val; } void ac97_via_remap_audio_codec(void *priv, uint16_t new_io_base, uint8_t enable) { ac97_via_t *dev = (ac97_via_t *) priv; if (dev->audio_codec_base) io_removehandler(dev->audio_codec_base, 256, ac97_via_codec_read, NULL, NULL, ac97_via_codec_write, NULL, NULL, dev); dev->audio_codec_base = new_io_base; if (dev->audio_codec_base && enable) io_sethandler(dev->audio_codec_base, 256, ac97_via_codec_read, NULL, NULL, ac97_via_codec_write, NULL, NULL, dev); } void ac97_via_remap_modem_codec(void *priv, uint16_t new_io_base, uint8_t enable) { ac97_via_t *dev = (ac97_via_t *) priv; if (dev->modem_codec_base) io_removehandler(dev->modem_codec_base, 256, ac97_via_codec_read, NULL, NULL, ac97_via_codec_write, NULL, NULL, dev); dev->modem_codec_base = new_io_base; if (dev->modem_codec_base && enable) io_sethandler(dev->modem_codec_base, 256, ac97_via_codec_read, NULL, NULL, ac97_via_codec_write, NULL, NULL, dev); } static void ac97_via_update_stereo(ac97_via_t *dev, ac97_via_sgd_t *sgd) { int32_t l = (((sgd->out_l * sgd->vol_l) >> 15) * dev->master_vol_l) >> 15; int32_t r = (((sgd->out_r * sgd->vol_r) >> 15) * dev->master_vol_r) >> 15; if (l < -32768) l = -32768; else if (l > 32767) l = 32767; if (r < -32768) r = -32768; else if (r > 32767) r = 32767; for (; sgd->pos < sound_pos_global; sgd->pos++) { sgd->buffer[sgd->pos * 2] = l; sgd->buffer[sgd->pos * 2 + 1] = r; } } static void ac97_via_sgd_process(void *priv) { ac97_via_sgd_t *sgd = (ac97_via_sgd_t *) priv; ac97_via_t *dev = sgd->dev; /* Stop if this SGD is not active. */ uint8_t sgd_status = dev->sgd_regs[sgd->id] & 0xc4; if (!(sgd_status & 0x80)) return; /* Schedule next run. */ timer_on_auto(&sgd->dma_timer, 10.0); /* Process SGD if it's active, and the FIFO has room or is disabled. */ if (((sgd_status & 0xc7) == 0x80) && (sgd->always_run || ((sgd->fifo_end - sgd->fifo_pos) <= (sizeof(sgd->fifo) - 4)))) { /* Move on to the next block if no entry is present. */ if (sgd->restart) { /* (Re)load entry pointer if required. */ if (sgd->restart & 2) sgd->entry_ptr = *((uint32_t *) &dev->sgd_regs[sgd->id | 0x4]) & 0xfffffffe; /* TODO: probe real hardware - does "even addr" actually mean dword aligned? */ sgd->restart = 0; /* Read entry. */ sgd->sample_ptr = mem_readl_phys(sgd->entry_ptr); sgd->entry_ptr += 4; sgd->sample_count = mem_readl_phys(sgd->entry_ptr); sgd->entry_ptr += 4; #ifdef ENABLE_AC97_VIA_LOG if (((sgd->sample_ptr == 0xffffffff) && (sgd->sample_count == 0xffffffff)) || ((sgd->sample_ptr == 0x00000000) && (sgd->sample_count == 0x00000000))) fatal("AC97 VIA: Invalid SGD %d entry %08X%08X at %08X\n", sgd->id >> 4, sgd->sample_ptr, sgd->sample_count, sgd->entry_ptr - 8); #endif /* Extract flags from the most significant byte. */ sgd->entry_flags = sgd->sample_count >> 24; sgd->sample_count &= 0xffffff; ac97_via_log("AC97 VIA: Starting SGD %d block at %08X start %08X len %06X flags %02X\n", sgd->id >> 4, sgd->entry_ptr - 8, sgd->sample_ptr, sgd->sample_count, sgd->entry_flags); } if (sgd->id & 0x10) { /* Write channel: read data from FIFO. */ mem_writel_phys(sgd->sample_ptr, *((uint32_t *) &sgd->fifo[sgd->fifo_end & (sizeof(sgd->fifo) - 1)])); } else { /* Read channel: write data to FIFO. */ *((uint32_t *) &sgd->fifo[sgd->fifo_end & (sizeof(sgd->fifo) - 1)]) = mem_readl_phys(sgd->sample_ptr); } sgd->fifo_end += 4; sgd->sample_ptr += 4; sgd->sample_count -= 4; /* Check if we've hit the end of this block. */ if (sgd->sample_count <= 0) { ac97_via_log("AC97 VIA: Ending SGD %d block", sgd->id >> 4); /* Move on to the next block on the next run, unless overridden below. */ sgd->restart = 1; if (sgd->entry_flags & 0x20) { ac97_via_log(" with STOP"); /* Raise STOP to pause SGD. */ dev->sgd_regs[sgd->id] |= 0x04; } if (sgd->entry_flags & 0x40) { ac97_via_log(" with FLAG"); /* Raise FLAG to pause SGD. */ dev->sgd_regs[sgd->id] |= 0x01; #ifdef ENABLE_AC97_VIA_LOG if (dev->sgd_regs[sgd->id | 0x2] & 0x01) ac97_via_log(" interrupt"); #endif } if (sgd->entry_flags & 0x80) { ac97_via_log(" with EOL"); /* Raise EOL. */ dev->sgd_regs[sgd->id] |= 0x02; #ifdef ENABLE_AC97_VIA_LOG if (dev->sgd_regs[sgd->id | 0x2] & 0x02) ac97_via_log(" interrupt"); #endif /* Restart SGD if a trigger is queued or auto-start is enabled. */ if ((dev->sgd_regs[sgd->id] & 0x08) || (dev->sgd_regs[sgd->id | 0x2] & 0x80)) { ac97_via_log(" restart"); /* Un-queue trigger. */ dev->sgd_regs[sgd->id] &= ~0x08; /* Go back to the starting block on the next run. */ sgd->restart = 2; } else { ac97_via_log(" finish"); /* Terminate SGD. */ dev->sgd_regs[sgd->id] &= ~0x80; } } ac97_via_log("\n"); /* Fire any requested status interrupts. */ ac97_via_update_irqs(dev); } } } static void ac97_via_poll_stereo(void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; ac97_via_sgd_t *sgd = &dev->sgd[0]; /* Audio Read */ /* Schedule next run if PCM playback is enabled. */ if (dev->pcm_enabled) timer_advance_u64(&sgd->poll_timer, sgd->timer_latch); /* Update stereo audio buffer. */ ac97_via_update_stereo(dev, sgd); /* Feed next sample from the FIFO. */ switch (dev->sgd_regs[sgd->id | 0x2] & 0x30) { case 0x00: /* Mono, 8-bit PCM */ if ((sgd->fifo_end - sgd->fifo_pos) >= 1) { sgd->out_l = sgd->out_r = (sgd->fifo[sgd->fifo_pos++ & (sizeof(sgd->fifo) - 1)] ^ 0x80) << 8; return; } break; case 0x10: /* Stereo, 8-bit PCM */ if ((sgd->fifo_end - sgd->fifo_pos) >= 2) { sgd->out_l = (sgd->fifo[sgd->fifo_pos++ & (sizeof(sgd->fifo) - 1)] ^ 0x80) << 8; sgd->out_r = (sgd->fifo[sgd->fifo_pos++ & (sizeof(sgd->fifo) - 1)] ^ 0x80) << 8; return; } break; case 0x20: /* Mono, 16-bit PCM */ if ((sgd->fifo_end - sgd->fifo_pos) >= 2) { sgd->out_l = sgd->out_r = *((uint16_t *) &sgd->fifo[sgd->fifo_pos & (sizeof(sgd->fifo) - 1)]); sgd->fifo_pos += 2; return; } break; case 0x30: /* Stereo, 16-bit PCM */ if ((sgd->fifo_end - sgd->fifo_pos) >= 4) { sgd->out_l = *((uint16_t *) &sgd->fifo[sgd->fifo_pos & (sizeof(sgd->fifo) - 1)]); sgd->fifo_pos += 2; sgd->out_r = *((uint16_t *) &sgd->fifo[sgd->fifo_pos & (sizeof(sgd->fifo) - 1)]); sgd->fifo_pos += 2; return; } break; default: break; } /* Feed silence if the FIFO is empty. */ sgd->out_l = sgd->out_r = 0; } static void ac97_via_poll_fm(void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; ac97_via_sgd_t *sgd = &dev->sgd[2]; /* FM Read */ /* Schedule next run if FM playback is enabled. */ if (dev->fm_enabled) timer_advance_u64(&sgd->poll_timer, sgd->timer_latch); /* Update FM audio buffer. */ ac97_via_update_stereo(dev, sgd); /* Feed next sample from the FIFO. The data format is not documented, but it probes as 16-bit stereo at 24 KHz. */ if ((sgd->fifo_end - sgd->fifo_pos) >= 4) { sgd->out_l = *((uint16_t *) &sgd->fifo[sgd->fifo_pos & (sizeof(sgd->fifo) - 1)]); sgd->fifo_pos += 2; sgd->out_r = *((uint16_t *) &sgd->fifo[sgd->fifo_pos & (sizeof(sgd->fifo) - 1)]); sgd->fifo_pos += 2; return; } /* Feed silence if the FIFO is empty. */ sgd->out_l = sgd->out_r = 0; } static void ac97_via_get_buffer(int32_t *buffer, int len, void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; ac97_via_update_stereo(dev, &dev->sgd[0]); ac97_via_update_stereo(dev, &dev->sgd[2]); for (int c = 0; c < len * 2; c++) { buffer[c] += dev->sgd[0].buffer[c] / 2; buffer[c] += dev->sgd[2].buffer[c] / 2; } dev->sgd[0].pos = dev->sgd[2].pos = 0; } static void ac97_via_filter_cd_audio(int channel, double *buffer, void *priv) { const ac97_via_t *dev = (ac97_via_t *) priv; double c; double volume = channel ? dev->cd_vol_r : dev->cd_vol_l; c = ((*buffer) * volume) / 65536.0; *buffer = c; } static void ac97_via_speed_changed(void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; double freq; /* Get variable sample rate if enabled. */ if (dev->vsr_enabled && dev->codec[0][0]) freq = ac97_codec_getrate(dev->codec[0][0], 0x2c); else freq = (double) SOUND_FREQ; dev->sgd[0].timer_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / freq)); dev->sgd[2].timer_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / 24000.0)); /* FM operates at a fixed 24 KHz */ } static void * ac97_via_init(UNUSED(const device_t *info)) { ac97_via_t *dev = malloc(sizeof(ac97_via_t)); memset(dev, 0, sizeof(ac97_via_t)); ac97_via_log("AC97 VIA: init()\n"); /* Set up codecs. */ ac97_codec = &dev->codec[0][0]; ac97_modem_codec = &dev->codec[1][0]; ac97_codec_count = ac97_modem_codec_count = sizeof(dev->codec[0]) / sizeof(dev->codec[0][0]); ac97_codec_id = ac97_modem_codec_id = 0; /* Set up SGD channels. */ for (uint8_t i = 0; i < (sizeof(dev->sgd) / sizeof(dev->sgd[0])); i++) { dev->sgd[i].id = i << 4; dev->sgd[i].dev = dev; /* Disable the FIFO on SGDs we don't care about. */ if ((i != 0) && (i != 2)) dev->sgd[i].always_run = 1; timer_add(&dev->sgd[i].dma_timer, ac97_via_sgd_process, &dev->sgd[i], 0); } /* Set up playback pollers. */ timer_add(&dev->sgd[0].poll_timer, ac97_via_poll_stereo, dev, 0); timer_add(&dev->sgd[2].poll_timer, ac97_via_poll_fm, dev, 0); ac97_via_speed_changed(dev); /* Set up playback handler. */ sound_add_handler(ac97_via_get_buffer, dev); return dev; } static void ac97_via_close(void *priv) { ac97_via_t *dev = (ac97_via_t *) priv; ac97_via_log("AC97 VIA: close()\n"); free(dev); } const device_t ac97_via_device = { .name = "VIA VT82C686 Integrated AC97 Controller", .internal_name = "ac97_via", .flags = DEVICE_PCI, .local = 0, .init = ac97_via_init, .close = ac97_via_close, .reset = NULL, { .available = NULL }, .speed_changed = ac97_via_speed_changed, .force_redraw = NULL, .config = NULL }; ```
/content/code_sandbox/src/sound/snd_ac97_via.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
8,113
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Sound Blaster emulation. * * * * Authors: Sarah Walker, <path_to_url * Miran Grca, <mgrca8@gmail.com> * TheCollector1995, <mariogplayer@gmail.com> * */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/filters.h> #include <86box/gameport.h> #include <86box/hdc.h> #include <86box/isapnp.h> #include <86box/hdc_ide.h> #include <86box/io.h> #include <86box/mca.h> #include <86box/mem.h> #include <86box/midi.h> #include <86box/pic.h> #include <86box/rom.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/snd_sb.h> #include <86box/plat_unused.h> #define PNP_ROM_SB_16_PNP "roms/sound/creative/CTL0024A.BIN" #define PNP_ROM_SB_VIBRA16XV "roms/sound/creative/CT4170 PnP.BIN" #define PNP_ROM_SB_VIBRA16C "roms/sound/creative/CT4180 PnP.BIN" #define PNP_ROM_SB_32_PNP "roms/sound/creative/CT3600 PnP.BIN" #define PNP_ROM_SB_AWE32_PNP "roms/sound/creative/CT3980 PnP.BIN" #define PNP_ROM_SB_AWE64_VALUE "roms/sound/creative/CT4520 PnP.BIN" #define PNP_ROM_SB_AWE64 "roms/sound/creative/CTL009DA.BIN" #define PNP_ROM_SB_AWE64_GOLD "roms/sound/creative/CT4540 PnP.BIN" /* TODO: Find real ESS PnP ROM dumps. */ #define PNP_ROM_ESS0100 "roms/sound/ess/ESS0100.BIN" #define PNP_ROM_ESS0102 "roms/sound/ess/ESS0102.BIN" #define PNP_ROM_ESS0968 "roms/sound/ess/ESS0968.BIN" /* 0 to 7 -> -14dB to 0dB i 2dB steps. 8 to 15 -> 0 to +14dB in 2dB steps. Note that for positive dB values, this is not amplitude, it is amplitude - 1. */ static const double sb_bass_treble_4bits[] = { 0.199526231, 0.25, 0.316227766, 0.398107170, 0.5, 0.63095734, 0.794328234, 1, 0, 0.25892541, 0.584893192, 1, 1.511886431, 2.16227766, 3, 4.011872336 }; /* Attenuation tables for the mixer. Max volume = 32767 in order to give 6dB of * headroom and avoid integer overflow */ // clang-format off static const double sb_att_2dbstep_5bits[] = { 25.0, 32.0, 41.0, 51.0, 65.0, 82.0, 103.0, 130.0, 164.0, 206.0, 260.0, 327.0, 412.0, 519.0, 653.0, 822.0, 1036.0, 1304.0, 1641.0, 2067.0, 2602.0, 3276.0, 4125.0, 5192.0, 6537.0, 8230.0, 10362.0, 13044.0, 16422.0, 20674.0, 26027.0, 32767.0 }; static const double sb_att_4dbstep_3bits[] = { 164.0, 2067.0, 3276.0, 5193.0, 8230.0, 13045.0, 20675.0, 32767.0 }; static const double sb_att_7dbstep_2bits[] = { 164.0, 6537.0, 14637.0, 32767.0 }; /* Attenuation table for ESS 4-bit microphone volume. * The last step is a jump to -48 dB. */ static const double sb_att_1p4dbstep_4bits[] = { 164.0, 3431.0, 4031.0, 4736.0, 5565.0, 6537.0, 7681.0, 9025.0, 10603.0, 12458.0, 14637.0, 17196.0, 20204.0, 23738.0, 27889.0, 32767.0 }; /* Attenuation table for ESS 4-bit mixer volume. * The last step is a jump to -48 dB. */ static const double sb_att_2dbstep_4bits[] = { 164.0, 1304.0, 1641.0, 2067.0, 2602.0, 3276.0, 4125.0, 5192.0, 6537.0, 8230.0, 10362.0, 13044.0, 16422.0, 20674.0, 26027.0, 32767.0 }; /* Attenuation table for ESS 3-bit PC speaker volume. */ static const double sb_att_3dbstep_3bits[] = { 0.0, 4125.0, 5826.0, 8230.0, 11626.0, 16422.0, 23197.0, 32767.0 }; // clang-format on static const uint16_t sb_mcv_addr[8] = { 0x200, 0x210, 0x220, 0x230, 0x240, 0x250, 0x260, 0x270 }; static const int sb_pro_mcv_irqs[4] = { 7, 5, 3, 3 }; #ifdef ENABLE_SB_LOG int sb_do_log = ENABLE_SB_LOG; static void sb_log(const char *fmt, ...) { va_list ap; if (sb_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define sb_log(fmt, ...) #endif /* SB 1, 1.5, MCV, and 2 do not have a mixer, so signal is hardwired. */ static void sb_get_buffer_sb2(int32_t *buffer, int len, void *priv) { sb_t *sb = (sb_t *) priv; const sb_ct1335_mixer_t *mixer = &sb->mixer_sb2; double out_mono; sb_dsp_update(&sb->dsp); if (sb->cms_enabled) cms_update(&sb->cms); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; if (sb->cms_enabled) { out_l += sb->cms.buffer[c]; out_r += sb->cms.buffer[c + 1]; } if (sb->cms_enabled && sb->mixer_enabled) { out_l *= mixer->fm; out_r *= mixer->fm; } /* TODO: Recording: I assume it has direct mic and line in like SB2. It is unclear from the docs if it has a filter, but it probably does. */ /* TODO: Recording: Mic and line In with AGC. */ if (sb->mixer_enabled) out_mono = (sb_iir(0, 0, (double) sb->dsp.buffer[c]) * mixer->voice) / 3.9; else out_mono = (((sb_iir(0, 0, (double) sb->dsp.buffer[c]) / 1.3) * 65536.0) / 3.0) / 65536.0; out_l += out_mono; out_r += out_mono; if (sb->mixer_enabled) { out_l *= mixer->master; out_r *= mixer->master; } buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } sb->dsp.pos = 0; if (sb->cms_enabled) sb->cms.pos = 0; } static void sb_get_music_buffer_sb2(int32_t *buffer, int len, void *priv) { const sb_t *sb = (const sb_t *) priv; const sb_ct1335_mixer_t *mixer = &sb->mixer_sb2; const int32_t *opl_buf = NULL; opl_buf = sb->opl.update(sb->opl.priv); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; const double out_mono = ((double) opl_buf[c]) * 0.7171630859375; out_l += out_mono; out_r += out_mono; if (sb->mixer_enabled) { out_l *= mixer->fm; out_r *= mixer->fm; } if (sb->mixer_enabled) { out_l *= mixer->master; out_r *= mixer->master; } buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } sb->opl.reset_buffer(sb->opl.priv); } static void sb2_filter_cd_audio(UNUSED(int channel), double *buffer, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1335_mixer_t *mixer = &sb->mixer_sb2; double c; if (sb->mixer_enabled) { c = ((sb_iir(2, 0, *buffer) / 1.3) * mixer->cd) / 3.0; *buffer = c * mixer->master; } else { c = (((sb_iir(2, 0, (*buffer)) / 1.3) * 65536) / 3.0) / 65536.0; *buffer = c; } } void sb_get_buffer_sbpro(int32_t *buffer, const int len, void *priv) { sb_t *sb = (sb_t *) priv; const sb_ct1345_mixer_t *mixer = &sb->mixer_sbpro; sb_dsp_update(&sb->dsp); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; /* TODO: Implement the stereo switch on the mixer instead of on the dsp? */ if (mixer->output_filter) { out_l += (sb_iir(0, 0, (double) sb->dsp.buffer[c]) * mixer->voice_l) / 3.9; out_r += (sb_iir(0, 1, (double) sb->dsp.buffer[c + 1]) * mixer->voice_r) / 3.9; } else { out_l += (sb->dsp.buffer[c] * mixer->voice_l) / 3.0; out_r += (sb->dsp.buffer[c + 1] * mixer->voice_r) / 3.0; } /* TODO: recording CD, Mic with AGC or line in. Note: mic volume does not affect recording. */ out_l *= mixer->master_l; out_r *= mixer->master_r; buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } sb->dsp.pos = 0; } void sb_get_music_buffer_sbpro(int32_t *buffer, int len, void *priv) { sb_t *sb = (sb_t *) priv; const sb_ct1345_mixer_t *mixer = &sb->mixer_sbpro; double out_l = 0.0; double out_r = 0.0; const int32_t *opl_buf = NULL; const int32_t *opl2_buf = NULL; if (!sb->opl_enabled) return; if (sb->dsp.sb_type == SBPRO) { opl_buf = sb->opl.update(sb->opl.priv); opl2_buf = sb->opl2.update(sb->opl2.priv); } else opl_buf = sb->opl.update(sb->opl.priv); sb_dsp_update(&sb->dsp); for (int c = 0; c < len * 2; c += 2) { out_l = 0.0; out_r = 0.0; if (sb->dsp.sb_type == SBPRO) { /* Two chips for LEFT and RIGHT channels. Each chip stores data into the LEFT channel only (no sample alternating.) */ out_l = (((double) opl_buf[c]) * mixer->fm_l) * 0.7171630859375; if (opl2_buf != NULL) out_r = (((double) opl2_buf[c]) * mixer->fm_r) * 0.7171630859375; } else { out_l = (((double) opl_buf[c]) * mixer->fm_l) * 0.7171630859375; out_r = (((double) opl_buf[c + 1]) * mixer->fm_r) * 0.7171630859375; if (sb->opl_mix && sb->opl_mixer) sb->opl_mix(sb->opl_mixer, &out_l, &out_r); } /* TODO: recording CD, Mic with AGC or line in. Note: mic volume does not affect recording. */ out_l *= mixer->master_l; out_r *= mixer->master_r; buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } sb->opl.reset_buffer(sb->opl.priv); if (sb->dsp.sb_type == SBPRO) sb->opl2.reset_buffer(sb->opl2.priv); } void sbpro_filter_cd_audio(int channel, double *buffer, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1345_mixer_t *mixer = &sb->mixer_sbpro; const double cd = channel ? mixer->cd_r : mixer->cd_l; const double master = channel ? mixer->master_r : mixer->master_l; double c = ((*buffer * cd) / 3.0) * master; *buffer = c; } static void sb_get_buffer_sb16_awe32(int32_t *buffer, int len, void *priv) { sb_t *sb = (sb_t *) priv; const sb_ct1745_mixer_t *mixer = &sb->mixer_sb16; double bass_treble; sb_dsp_update(&sb->dsp); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; if (mixer->output_filter) { /* We divide by 3 to get the volume down to normal. */ out_l += (low_fir_sb16(0, 0, (double) sb->dsp.buffer[c]) * mixer->voice_l) / 3.0; out_r += (low_fir_sb16(0, 1, (double) sb->dsp.buffer[c + 1]) * mixer->voice_r) / 3.0; } else { out_l += (((double) sb->dsp.buffer[c]) * mixer->voice_l) / 3.0; out_r += (((double) sb->dsp.buffer[c + 1]) * mixer->voice_r) / 3.0; } out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass_l != 8) { bass_treble = sb_bass_treble_4bits[mixer->bass_l]; if (mixer->bass_l > 8) out_l += (low_iir(0, 0, out_l) * bass_treble); else out_l = (out_l *bass_treble + low_cut_iir(0, 0, out_l) * (1.0 - bass_treble)); } if (mixer->bass_r != 8) { bass_treble = sb_bass_treble_4bits[mixer->bass_r]; if (mixer->bass_r > 8) out_r += (low_iir(0, 1, out_r) * bass_treble); else out_r = (out_r *bass_treble + low_cut_iir(0, 1, out_r) * (1.0 - bass_treble)); } if (mixer->treble_l != 8) { bass_treble = sb_bass_treble_4bits[mixer->treble_l]; if (mixer->treble_l > 8) out_l += (high_iir(0, 0, out_l) * bass_treble); else out_l = (out_l *bass_treble + high_cut_iir(0, 0, out_l) * (1.0 - bass_treble)); } if (mixer->treble_r != 8) { bass_treble = sb_bass_treble_4bits[mixer->treble_r]; if (mixer->treble_r > 8) out_r += (high_iir(0, 1, out_r) * bass_treble); else out_r = (out_l *bass_treble + high_cut_iir(0, 1, out_r) * (1.0 - bass_treble)); } buffer[c] += (int32_t) (out_l * mixer->output_gain_L); buffer[c + 1] += (int32_t) (out_r * mixer->output_gain_R); } sb->dsp.pos = 0; } static void sb_get_music_buffer_sb16_awe32(int32_t *buffer, const int len, void *priv) { sb_t *sb = (sb_t *) priv; const sb_ct1745_mixer_t *mixer = &sb->mixer_sb16; const int dsp_rec_pos = sb->dsp.record_pos_write; double bass_treble; const int32_t *opl_buf = NULL; if (sb->opl_enabled) opl_buf = sb->opl.update(sb->opl.priv); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; if (sb->opl_enabled) { out_l = ((double) opl_buf[c]) * mixer->fm_l * 0.7171630859375; out_r = ((double) opl_buf[c + 1]) * mixer->fm_r * 0.7171630859375; } /* TODO: Multi-recording mic with agc/+20db, CD, and line in with channel inversion */ int32_t in_l = (mixer->input_selector_left & INPUT_MIDI_L) ? ((int32_t) out_l) : 0 + (mixer->input_selector_left & INPUT_MIDI_R) ? ((int32_t) out_r) : 0; int32_t in_r = (mixer->input_selector_right & INPUT_MIDI_L) ? ((int32_t) out_l) : 0 + (mixer->input_selector_right & INPUT_MIDI_R) ? ((int32_t) out_r) : 0; out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass_l != 8) { bass_treble = sb_bass_treble_4bits[mixer->bass_l]; if (mixer->bass_l > 8) out_l += (low_iir(1, 0, out_l) * bass_treble); else out_l = (out_l *bass_treble + low_cut_iir(1, 0, out_l) * (1.0 - bass_treble)); } if (mixer->bass_r != 8) { bass_treble = sb_bass_treble_4bits[mixer->bass_r]; if (mixer->bass_r > 8) out_r += (low_iir(1, 1, out_r) * bass_treble); else out_r = (out_r *bass_treble + low_cut_iir(1, 1, out_r) * (1.0 - bass_treble)); } if (mixer->treble_l != 8) { bass_treble = sb_bass_treble_4bits[mixer->treble_l]; if (mixer->treble_l > 8) out_l += (high_iir(1, 0, out_l) * bass_treble); else out_l = (out_l *bass_treble + high_cut_iir(1, 0, out_l) * (1.0 - bass_treble)); } if (mixer->treble_r != 8) { bass_treble = sb_bass_treble_4bits[mixer->treble_r]; if (mixer->treble_r > 8) out_r += (high_iir(1, 1, out_r) * bass_treble); else out_r = (out_l *bass_treble + high_cut_iir(1, 1, out_r) * (1.0 - bass_treble)); } if (sb->dsp.sb_enable_i) { const int c_record = dsp_rec_pos + ((c * sb->dsp.sb_freq) / MUSIC_FREQ); in_l <<= mixer->input_gain_L; in_r <<= mixer->input_gain_R; /* Clip signal */ if (in_l < -32768) in_l = -32768; else if (in_l > 32767) in_l = 32767; if (in_r < -32768) in_r = -32768; else if (in_r > 32767) in_r = 32767; sb->dsp.record_buffer[c_record & 0xffff] = (int16_t) in_l; sb->dsp.record_buffer[(c_record + 1) & 0xffff] = (int16_t) in_r; } buffer[c] += (int32_t) (out_l * mixer->output_gain_L); buffer[c + 1] += (int32_t) (out_r * mixer->output_gain_R); } sb->dsp.record_pos_write += ((len * sb->dsp.sb_freq) / 24000); sb->dsp.record_pos_write &= 0xffff; if (sb->opl_enabled) sb->opl.reset_buffer(sb->opl.priv); } static void sb_get_wavetable_buffer_sb16_awe32(int32_t *buffer, const int len, void *priv) { sb_t *sb = (sb_t *) priv; const sb_ct1745_mixer_t *mixer = &sb->mixer_sb16; double bass_treble; emu8k_update(&sb->emu8k); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; out_l += (((double) sb->emu8k.buffer[c]) * mixer->fm_l); out_r += (((double) sb->emu8k.buffer[c + 1]) * mixer->fm_r); out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass_l != 8) { bass_treble = sb_bass_treble_4bits[mixer->bass_l]; if (mixer->bass_l > 8) out_l += (low_iir(4, 0, out_l) * bass_treble); else out_l = (out_l *bass_treble + low_cut_iir(4, 0, out_l) * (1.0 - bass_treble)); } if (mixer->bass_r != 8) { bass_treble = sb_bass_treble_4bits[mixer->bass_r]; if (mixer->bass_r > 8) out_r += (low_iir(4, 1, out_r) * bass_treble); else out_r = (out_r *bass_treble + low_cut_iir(4, 1, out_r) * (1.0 - bass_treble)); } if (mixer->treble_l != 8) { bass_treble = sb_bass_treble_4bits[mixer->treble_l]; if (mixer->treble_l > 8) out_l += (high_iir(4, 0, out_l) * bass_treble); else out_l = (out_l *bass_treble + high_cut_iir(4, 0, out_l) * (1.0 - bass_treble)); } if (mixer->treble_r != 8) { bass_treble = sb_bass_treble_4bits[mixer->treble_r]; if (mixer->treble_r > 8) out_r += (high_iir(4, 1, out_r) * bass_treble); else out_r = (out_l *bass_treble + high_cut_iir(4, 1, out_r) * (1.0 - bass_treble)); } buffer[c] += (int32_t) (out_l * mixer->output_gain_L); buffer[c + 1] += (int32_t) (out_r * mixer->output_gain_R); } sb->emu8k.pos = 0; } void sb16_awe32_filter_cd_audio(int channel, double *buffer, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1745_mixer_t *mixer = &sb->mixer_sb16; const double cd = channel ? mixer->cd_r : mixer->cd_l /* / 3.0 */; const double master = channel ? mixer->master_r : mixer->master_l; const int32_t bass = channel ? mixer->bass_r : mixer->bass_l; const int32_t treble = channel ? mixer->treble_r : mixer->treble_l; const double output_gain = (channel ? mixer->output_gain_R : mixer->output_gain_L); double bass_treble; double c = (((*buffer) * cd) / 3.0) * master; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (bass != 8) { bass_treble = sb_bass_treble_4bits[bass]; if (bass > 8) c += (low_iir(2, channel, c) * bass_treble); else c = (c * bass_treble + low_cut_iir(2, channel, c) * (1.0 - bass_treble)); } if (treble != 8) { bass_treble = sb_bass_treble_4bits[treble]; if (treble > 8) c += (high_iir(2, channel, c) * bass_treble); else c = (c * bass_treble + high_cut_iir(2, channel, c) * (1.0 - bass_treble)); } *buffer = c * output_gain; } void sb16_awe32_filter_pc_speaker(int channel, double *buffer, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1745_mixer_t *mixer = &sb->mixer_sb16; const double spk = mixer->speaker; const double master = channel ? mixer->master_r : mixer->master_l; const int32_t bass = channel ? mixer->bass_r : mixer->bass_l; const int32_t treble = channel ? mixer->treble_r : mixer->treble_l; const double output_gain = (channel ? mixer->output_gain_R : mixer->output_gain_L); double bass_treble; double c; if (mixer->output_filter) c = (low_fir_sb16(3, channel, *buffer) * spk) / 3.0; else c = ((*buffer) * spk) / 3.0; c *= master; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (bass != 8) { bass_treble = sb_bass_treble_4bits[bass]; if (bass > 8) c += (low_iir(3, channel, c) * bass_treble); else c = (c * bass_treble + low_cut_iir(3, channel, c) * (1.0 - bass_treble)); } if (treble != 8) { bass_treble = sb_bass_treble_4bits[treble]; if (treble > 8) c += (high_iir(3, channel, c) * bass_treble); else c = (c * bass_treble + high_cut_iir(3, channel, c) * (1.0 - bass_treble)); } *buffer = c * output_gain; } void sb_get_buffer_ess(int32_t *buffer, int len, void *priv) { sb_t *ess = (sb_t *) priv; const ess_mixer_t *mixer = &ess->mixer_ess; sb_dsp_update(&ess->dsp); for (int c = 0; c < len * 2; c += 2) { double out_l = 0.0; double out_r = 0.0; /* TODO: Implement the stereo switch on the mixer instead of on the dsp? */ if (mixer->output_filter) { out_l += (low_fir_sb16(0, 0, (double) ess->dsp.buffer[c]) * mixer->voice_l) / 3.0; out_r += (low_fir_sb16(0, 1, (double) ess->dsp.buffer[c + 1]) * mixer->voice_r) / 3.0; } else { out_l += (ess->dsp.buffer[c] * mixer->voice_l) / 3.0; out_r += (ess->dsp.buffer[c + 1] * mixer->voice_r) / 3.0; } /* TODO: recording from the mixer. */ out_l *= mixer->master_l; out_r *= mixer->master_r; buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } ess->dsp.pos = 0; } void sb_get_music_buffer_ess(int32_t *buffer, int len, void *priv) { sb_t *ess = (sb_t *) priv; const ess_mixer_t *mixer = &ess->mixer_ess; double out_l = 0.0; double out_r = 0.0; const int32_t *opl_buf = NULL; opl_buf = ess->opl.update(ess->opl.priv); for (int c = 0; c < len * 2; c += 2) { out_l = 0.0; out_r = 0.0; out_l = (((double) opl_buf[c]) * mixer->fm_l) * 0.7171630859375; out_r = (((double) opl_buf[c + 1]) * mixer->fm_r) * 0.7171630859375; if (ess->opl_mix && ess->opl_mixer) ess->opl_mix(ess->opl_mixer, &out_l, &out_r); /* TODO: recording from the mixer. */ out_l *= mixer->master_l; out_r *= mixer->master_r; buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } ess->opl.reset_buffer(ess->opl.priv); } void ess_filter_cd_audio(int channel, double *buffer, void *priv) { const sb_t *ess = (sb_t *) priv; const ess_mixer_t *mixer = &ess->mixer_ess; double c; double cd = channel ? mixer->cd_r : mixer->cd_l; double master = channel ? mixer->master_r : mixer->master_l; /* TODO: recording from the mixer. */ c = (*buffer * cd) / 3.0; *buffer = c * master; } void ess_filter_pc_speaker(int channel, double *buffer, void *priv) { const sb_t *ess = (sb_t *) priv; const ess_mixer_t *mixer = &ess->mixer_ess; double c; double spk = mixer->speaker; double master = channel ? mixer->master_r : mixer->master_l; if (mixer->output_filter) c = (low_fir_sb16(3, channel, *buffer) * spk) / 3.0; else c = ((*buffer) * spk) / 3.0; c *= master; *buffer = c; } void sb_ct1335_mixer_write(uint16_t addr, uint8_t val, void *priv) { sb_t *sb = (sb_t *) priv; sb_ct1335_mixer_t *mixer = &sb->mixer_sb2; if (!(addr & 1)) { mixer->index = val; mixer->regs[0x01] = val; } else { if (mixer->index == 0) { /* Reset */ mixer->regs[0x02] = mixer->regs[0x06] = 0x08; mixer->regs[0x08] = 0x00; /* Changed default from -46dB to 0dB*/ mixer->regs[0x0a] = 0x06; } else { mixer->regs[mixer->index] = val; switch (mixer->index) { case 0x00: case 0x02: case 0x06: case 0x08: case 0x0a: break; default: sb_log("sb_ct1335: Unknown register WRITE: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } } mixer->master = sb_att_4dbstep_3bits[(mixer->regs[0x02] >> 1) & 0x7] / 32768.0; mixer->fm = sb_att_4dbstep_3bits[(mixer->regs[0x06] >> 1) & 0x7] / 32768.0; mixer->cd = sb_att_4dbstep_3bits[(mixer->regs[0x08] >> 1) & 0x7] / 32768.0; mixer->voice = sb_att_7dbstep_2bits[(mixer->regs[0x0a] >> 1) & 0x3] / 32768.0; } } uint8_t sb_ct1335_mixer_read(uint16_t addr, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1335_mixer_t *mixer = &sb->mixer_sb2; if (!(addr & 1)) return mixer->index; switch (mixer->index) { case 0x00: case 0x02: case 0x06: case 0x08: case 0x0A: return mixer->regs[mixer->index]; default: sb_log("sb_ct1335: Unknown register READ: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } return 0xff; } void sb_ct1335_mixer_reset(sb_t *sb) { sb_ct1335_mixer_write(0x254, 0, sb); sb_ct1335_mixer_write(0x255, 0, sb); } void sb_ct1345_mixer_write(uint16_t addr, uint8_t val, void *priv) { sb_t *sb = (sb_t *) priv; sb_ct1345_mixer_t *mixer = (sb == NULL) ? NULL : &sb->mixer_sbpro; if (mixer == NULL) return; if (!(addr & 1)) { mixer->index = val; mixer->regs[0x01] = val; } else { if (mixer->index == 0) { /* Reset */ mixer->regs[0x0a] = mixer->regs[0x0c] = 0x00; mixer->regs[0x0e] = 0x00; /* Changed default from -11dB to 0dB */ mixer->regs[0x04] = mixer->regs[0x22] = 0xee; mixer->regs[0x26] = mixer->regs[0x28] = 0xee; mixer->regs[0x2e] = 0x00; sb_dsp_set_stereo(&sb->dsp, mixer->regs[0x0e] & 2); } else { mixer->regs[mixer->index] = val; switch (mixer->index) { /* Compatibility: chain registers 0x02 and 0x22 as well as 0x06 and 0x26 */ case 0x02: case 0x06: case 0x08: mixer->regs[mixer->index + 0x20] = ((val & 0xe) << 4) | (val & 0xe); break; case 0x22: case 0x26: case 0x28: mixer->regs[mixer->index - 0x20] = (val & 0xe); break; /* More compatibility: SoundBlaster Pro selects register 020h for 030h, 022h for 032h, 026h for 036h, and 028h for 038h. */ case 0x30: case 0x32: case 0x36: case 0x38: mixer->regs[mixer->index - 0x10] = (val & 0xee); break; case 0x00: case 0x04: case 0x0a: case 0x0c: case 0x0e: case 0x2e: break; default: sb_log("sb_ct1345: Unknown register WRITE: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } } mixer->voice_l = sb_att_4dbstep_3bits[(mixer->regs[0x04] >> 5) & 0x7] / 32768.0; mixer->voice_r = sb_att_4dbstep_3bits[(mixer->regs[0x04] >> 1) & 0x7] / 32768.0; mixer->master_l = sb_att_4dbstep_3bits[(mixer->regs[0x22] >> 5) & 0x7] / 32768.0; mixer->master_r = sb_att_4dbstep_3bits[(mixer->regs[0x22] >> 1) & 0x7] / 32768.0; mixer->fm_l = sb_att_4dbstep_3bits[(mixer->regs[0x26] >> 5) & 0x7] / 32768.0; mixer->fm_r = sb_att_4dbstep_3bits[(mixer->regs[0x26] >> 1) & 0x7] / 32768.0; mixer->cd_l = sb_att_4dbstep_3bits[(mixer->regs[0x28] >> 5) & 0x7] / 32768.0; mixer->cd_r = sb_att_4dbstep_3bits[(mixer->regs[0x28] >> 1) & 0x7] / 32768.0; mixer->line_l = sb_att_4dbstep_3bits[(mixer->regs[0x2e] >> 5) & 0x7] / 32768.0; mixer->line_r = sb_att_4dbstep_3bits[(mixer->regs[0x2e] >> 1) & 0x7] / 32768.0; mixer->mic = sb_att_7dbstep_2bits[(mixer->regs[0x0a] >> 1) & 0x3] / 32768.0; mixer->output_filter = !(mixer->regs[0xe] & 0x20); mixer->input_filter = !(mixer->regs[0xc] & 0x20); mixer->in_filter_freq = ((mixer->regs[0xc] & 0x8) == 0) ? 3200 : 8800; mixer->stereo = mixer->regs[0xe] & 2; if (mixer->index == 0xe) sb_dsp_set_stereo(&sb->dsp, val & 2); switch (mixer->regs[0xc] & 6) { case 2: mixer->input_selector = INPUT_CD_L | INPUT_CD_R; break; case 6: mixer->input_selector = INPUT_LINE_L | INPUT_LINE_R; break; default: mixer->input_selector = INPUT_MIC; break; } /* TODO: pcspeaker volume? Or is it not worth? */ } } uint8_t sb_ct1345_mixer_read(uint16_t addr, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1345_mixer_t *mixer = &sb->mixer_sbpro; if (!(addr & 1)) return mixer->index; switch (mixer->index) { case 0x00: case 0x04: case 0x0a: case 0x0c: case 0x0e: case 0x22: case 0x26: case 0x28: case 0x2e: case 0x02: case 0x06: case 0x30: case 0x32: case 0x36: case 0x38: return mixer->regs[mixer->index]; default: sb_log("sb_ct1345: Unknown register READ: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } return 0xff; } void sb_ct1345_mixer_reset(sb_t *sb) { sb_ct1345_mixer_write(4, 0, sb); sb_ct1345_mixer_write(5, 0, sb); } void sb_ct1745_mixer_write(uint16_t addr, uint8_t val, void *priv) { sb_t *sb = (sb_t *) priv; sb_ct1745_mixer_t *mixer = (sb == NULL) ? NULL : &sb->mixer_sb16; if (mixer == NULL) return; if (!(addr & 1)) mixer->index = val; else { /* DESCRIPTION: Contains previously selected register value. Mixer Data Register value. NOTES: SoundBlaster 16 sets bit 7 if previous mixer index invalid. Status bytes initially 080h on startup for all but level bytes (SB16). */ sb_log("CT1745: [W] %02X = %02X\n", mixer->index, val); if (mixer->index == 0) { /* Reset: Changed defaults from -14dB to 0dB */ mixer->regs[0x30] = mixer->regs[0x31] = 0xf8; mixer->regs[0x32] = mixer->regs[0x33] = 0xf8; mixer->regs[0x34] = mixer->regs[0x35] = 0xf8; mixer->regs[0x36] = mixer->regs[0x37] = 0xf8; mixer->regs[0x38] = mixer->regs[0x39] = 0x00; mixer->regs[0x3a] = 0x00; /* Speaker control - it appears to be in steps of 64. */ mixer->regs[0x3b] = 0x80; mixer->regs[0x3c] = (OUTPUT_MIC | OUTPUT_CD_R | OUTPUT_CD_L | OUTPUT_LINE_R | OUTPUT_LINE_L); mixer->regs[0x3d] = (INPUT_MIC | INPUT_CD_L | INPUT_LINE_L | INPUT_MIDI_L); mixer->regs[0x3e] = (INPUT_MIC | INPUT_CD_R | INPUT_LINE_R | INPUT_MIDI_R); mixer->regs[0x3f] = mixer->regs[0x40] = 0x00; mixer->regs[0x41] = mixer->regs[0x42] = 0x00; mixer->regs[0x44] = mixer->regs[0x45] = 0x80; mixer->regs[0x46] = mixer->regs[0x47] = 0x80; /* 0x43 = Mic AGC (Automatic Gain Control?) according to Linux's sb.h. NSC LM4560 datasheet: Bit 0: 1 = Enable, 0 = Disable; Another source says this: Bit 0: 0 = AGC on (default), 1 = Fixed gain of 20 dB. */ mixer->regs[0x43] = 0x00; mixer->regs[0x49] = mixer->regs[0x4a] = 0x80; mixer->regs[0x83] = 0xff; sb->dsp.sb_irqm8 = 0; sb->dsp.sb_irqm16 = 0; sb->dsp.sb_irqm401 = 0; mixer->regs[0xfd] = 0x10; mixer->regs[0xfe] = 0x06; mixer->regs[0xff] = sb->dsp.sb_16_dma_supported ? 0x05 : 0x03; sb_dsp_setdma16_enabled(&sb->dsp, 0x01); sb_dsp_setdma16_translate(&sb->dsp, mixer->regs[0xff] & 0x02); } else mixer->regs[mixer->index] = val; switch (mixer->index) { /* SB1/2 compatibility? */ case 0x02: mixer->regs[0x30] = ((mixer->regs[0x02] & 0xf) << 4) | 0x8; mixer->regs[0x31] = ((mixer->regs[0x02] & 0xf) << 4) | 0x8; break; case 0x06: mixer->regs[0x34] = ((mixer->regs[0x06] & 0xf) << 4) | 0x8; mixer->regs[0x35] = ((mixer->regs[0x06] & 0xf) << 4) | 0x8; break; case 0x08: mixer->regs[0x36] = ((mixer->regs[0x08] & 0xf) << 4) | 0x8; mixer->regs[0x37] = ((mixer->regs[0x08] & 0xf) << 4) | 0x8; break; /* SBPro compatibility. Copy values to sb16 registers. */ case 0x22: mixer->regs[0x30] = (mixer->regs[0x22] & 0xf0) | 0x8; mixer->regs[0x31] = ((mixer->regs[0x22] & 0xf) << 4) | 0x8; break; case 0x04: mixer->regs[0x32] = (mixer->regs[0x04] & 0xf0) | 0x8; mixer->regs[0x33] = ((mixer->regs[0x04] & 0xf) << 4) | 0x8; break; case 0x26: mixer->regs[0x34] = (mixer->regs[0x26] & 0xf0) | 0x8; mixer->regs[0x35] = ((mixer->regs[0x26] & 0xf) << 4) | 0x8; break; case 0x28: mixer->regs[0x36] = (mixer->regs[0x28] & 0xf0) | 0x8; mixer->regs[0x37] = ((mixer->regs[0x28] & 0xf) << 4) | 0x8; break; case 0x0A: mixer->regs[0x3a] = (mixer->regs[0x0a] << 5) | 0x18; break; case 0x2e: mixer->regs[0x38] = (mixer->regs[0x2e] & 0xf0) | 0x8; mixer->regs[0x39] = ((mixer->regs[0x2e] & 0xf) << 4) | 0x8; break; /* (DSP 4.xx feature): The Interrupt Setup register, addressed as register 80h on the Mixer register map, is used to configure or determine the Interrupt request line. The DMA setup register, addressed as register 81h on the Mixer register map, is used to configure or determine the DMA channels. Note: Registers 80h and 81h are Read-only for PnP boards. */ case 0x80: if (!sb->pnp) { if (val & 0x01) sb_dsp_setirq(&sb->dsp, 2); if (val & 0x02) sb_dsp_setirq(&sb->dsp, 5); if (val & 0x04) sb_dsp_setirq(&sb->dsp, 7); if (val & 0x08) sb_dsp_setirq(&sb->dsp, 10); } break; case 0x81: /* The documentation is confusing. sounds as if multple dma8 channels could be set. */ if (!sb->pnp) { if (val & 0x01) sb_dsp_setdma8(&sb->dsp, 0); else if (val & 0x02) sb_dsp_setdma8(&sb->dsp, 1); else if (val & 0x08) sb_dsp_setdma8(&sb->dsp, 3); sb_dsp_setdma16(&sb->dsp, 4); if (val & 0x20) sb_dsp_setdma16(&sb->dsp, 5); else if (val & 0x40) sb_dsp_setdma16(&sb->dsp, 6); else if (val & 0x80) sb_dsp_setdma16(&sb->dsp, 7); } break; case 0x83: /* Interrupt mask. */ sb_update_mask(&sb->dsp, !(val & 0x01), !(val & 0x02), !(val & 0x04)); break; case 0x84: /* MPU Control register, per the Linux source code. */ /* Bits 2-1: MPU-401 address: 0, 0 = 330h; 0, 1 = Disabled; 1, 0 = 300h; 1, 1 = ???? (Reserved?) Bit 0: Gameport address: 0, 0 = 200-207h; 0, 1 = Disabled */ if (!sb->pnp) { if (sb->mpu != NULL) { if ((val & 0x06) == 0x00) mpu401_change_addr(sb->mpu, 0x330); else if ((val & 0x06) == 0x04) mpu401_change_addr(sb->mpu, 0x300); else if ((val & 0x06) == 0x02) mpu401_change_addr(sb->mpu, 0); } sb->gameport_addr = 0; gameport_remap(sb->gameport, 0); if (!(val & 0x01)) { sb->gameport_addr = 0x200; gameport_remap(sb->gameport, 0x200); } } break; case 0xff: if ((sb->dsp.sb_type > SBAWE32) && !sb->dsp.sb_16_dma_supported) { /* Bit 5: High DMA channel enabled (0 = yes, 1 = no); Bit 2: ????; Bit 1: ???? (16-bit to 8-bit translation?); Bit 0: ???? Seen values: 20, 05, 04, 03 */ sb_dsp_setdma16_enabled(&sb->dsp, !(val & 0x20)); #ifdef TOGGLABLE_TRANSLATION sb_dsp_setdma16_translate(&sb->dsp, val & 0x02); #endif } break; default: break; } mixer->output_selector = mixer->regs[0x3c]; mixer->input_selector_left = mixer->regs[0x3d]; mixer->input_selector_right = mixer->regs[0x3e]; mixer->master_l = sb_att_2dbstep_5bits[mixer->regs[0x30] >> 3] / 32768.0; mixer->master_r = sb_att_2dbstep_5bits[mixer->regs[0x31] >> 3] / 32768.0; mixer->voice_l = sb_att_2dbstep_5bits[mixer->regs[0x32] >> 3] / 32768.0; mixer->voice_r = sb_att_2dbstep_5bits[mixer->regs[0x33] >> 3] / 32768.0; mixer->fm_l = sb_att_2dbstep_5bits[mixer->regs[0x34] >> 3] / 32768.0; mixer->fm_r = sb_att_2dbstep_5bits[mixer->regs[0x35] >> 3] / 32768.0; mixer->cd_l = (mixer->output_selector & OUTPUT_CD_L) ? (sb_att_2dbstep_5bits[mixer->regs[0x36] >> 3] / 32768.0) : 0.0; mixer->cd_r = (mixer->output_selector & OUTPUT_CD_R) ? (sb_att_2dbstep_5bits[mixer->regs[0x37] >> 3] / 32768.0) : 0.0; mixer->line_l = (mixer->output_selector & OUTPUT_LINE_L) ? (sb_att_2dbstep_5bits[mixer->regs[0x38] >> 3] / 32768.0) : 0.0; mixer->line_r = (mixer->output_selector & OUTPUT_LINE_R) ? (sb_att_2dbstep_5bits[mixer->regs[0x39] >> 3] / 32768.0) : 0.0; mixer->mic = sb_att_2dbstep_5bits[mixer->regs[0x3a] >> 3] / 32768.0; mixer->speaker = sb_att_7dbstep_2bits[(mixer->regs[0x3b] >> 6) & 0x3] / 32768.0; mixer->input_gain_L = (mixer->regs[0x3f] >> 6); mixer->input_gain_R = (mixer->regs[0x40] >> 6); mixer->output_gain_L = (double) (1 << (mixer->regs[0x41] >> 6)); mixer->output_gain_R = (double) (1 << (mixer->regs[0x42] >> 6)); mixer->bass_l = mixer->regs[0x46] >> 4; mixer->bass_r = mixer->regs[0x47] >> 4; mixer->treble_l = mixer->regs[0x44] >> 4; mixer->treble_r = mixer->regs[0x45] >> 4; /* TODO: PC Speaker volume, with "output_selector" check? or better not? */ sb_log("sb_ct1745: Received register WRITE: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); } } uint8_t sb_ct1745_mixer_read(uint16_t addr, void *priv) { const sb_t *sb = (sb_t *) priv; const sb_ct1745_mixer_t *mixer = &sb->mixer_sb16; uint8_t ret = 0xff; if (!(addr & 1)) ret = mixer->index; sb_log("sb_ct1745: received register READ: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); if ((mixer->index >= 0x30) && (mixer->index <= 0x47)) ret = mixer->regs[mixer->index]; else { switch (mixer->index) { case 0x00: ret = mixer->regs[mixer->index]; break; /*SB Pro compatibility*/ case 0x04: ret = ((mixer->regs[0x33] >> 4) & 0x0f) | (mixer->regs[0x32] & 0xf0); break; case 0x0a: ret = (mixer->regs[0x3a] >> 5); break; case 0x02: ret = ((mixer->regs[0x30] >> 4) & 0x0f); break; case 0x06: ret = ((mixer->regs[0x34] >> 4) & 0x0f); break; case 0x08: ret = ((mixer->regs[0x36] >> 4) & 0x0f); break; case 0x0e: ret = 0x02; break; case 0x22: ret = ((mixer->regs[0x31] >> 4) & 0x0f) | (mixer->regs[0x30] & 0xf0); break; case 0x26: ret = ((mixer->regs[0x35] >> 4) & 0x0f) | (mixer->regs[0x34] & 0xf0); break; case 0x28: ret = ((mixer->regs[0x37] >> 4) & 0x0f) | (mixer->regs[0x36] & 0xf0); break; case 0x2e: ret = ((mixer->regs[0x39] >> 4) & 0x0f) | (mixer->regs[0x38] & 0xf0); break; case 0x48: /* Undocumented. The Creative Windows Mixer calls this after calling 3C (input selector), even when writing. Also, the version I have (5.17), does not use the MIDI.L/R input selectors, it uses the volume to mute (Affecting the output, obviously). */ ret = mixer->regs[mixer->index]; break; case 0x80: /* TODO: Unaffected by mixer reset or soft reboot. Enabling multiple bits enables multiple IRQs. */ switch (sb->dsp.sb_irqnum) { case 2: ret = 1; break; case 5: ret = 2; break; case 7: ret = 4; break; case 10: ret = 8; break; default: break; } break; case 0x81: /* TODO: Unaffected by mixer reset or soft reboot. Enabling multiple 8 or 16-bit DMA bits enables multiple DMA channels. Disabling all 8-bit DMA channel bits disables 8-bit DMA requests, including translated 16-bit DMA requests. Disabling all 16-bit DMA channel bits enables translation of 16-bit DMA requests to 8-bit ones, using the selected 8-bit DMA channel. */ ret = 0; switch (sb->dsp.sb_8_dmanum) { case 0: ret |= 1; break; case 1: ret |= 2; break; case 3: ret |= 8; break; default: break; } switch (sb->dsp.sb_16_dmanum) { default: break; case 5: ret |= 0x20; break; case 6: ret |= 0x40; break; case 7: ret |= 0x80; break; } break; case 0x82: ; /* Empty statement to make compilers happy about the following variable declaration. */ /* The Interrupt status register, addressed as register 82h on the Mixer register map, is used by the ISR to determine whether the interrupt is meant for it or for some other ISR, in which case it should chain to the previous routine. */ /* 0 = none, 1 = digital 8bit or SBMIDI, 2 = digital 16bit, 4 = MPU-401 */ /* 0x02000 DSP v4.04, 0x4000 DSP v4.05, 0x8000 DSP v4.12. I haven't seen this making any difference, but I'm keeping it for now. */ /* If QEMU is any indication, then the values are actually 0x20, 0x40, and 0x80. */ /* path_to_url~tfm/oldpage/sb_mixer.html - 0x10, 0x20, 0x80. */ const uint8_t temp = ((sb->dsp.sb_irq8) ? 1 : 0) | ((sb->dsp.sb_irq16) ? 2 : 0) | ((sb->dsp.sb_irq401) ? 4 : 0); if (sb->dsp.sb_type >= SBAWE32) ret = temp | 0x80; else ret = temp | 0x40; break; case 0x83: /* Interrupt mask. */ ret = mixer->regs[mixer->index]; break; case 0x84: /* MPU Control. */ if (sb->mpu == NULL) ret = 0x02; else { if (sb->mpu->addr == 0x330) ret = 0x00; else if (sb->mpu->addr == 0x300) ret = 0x04; else if (sb->mpu->addr == 0) ret = 0x02; else ret = 0x06; /* Should never happen. */ } if (!sb->gameport_addr) ret |= 0x01; break; case 0x49: /* Undocumented register used by some Creative drivers. */ case 0x4a: /* Undocumented register used by some Creative drivers. */ case 0x8c: /* Undocumented register used by some Creative drivers. */ case 0x8e: /* Undocumented register used by some Creative drivers. */ case 0x90: /* 3D Enhancement switch. */ case 0xfd: /* Undocumented register used by some Creative drivers. */ case 0xfe: /* Undocumented register used by some Creative drivers. */ ret = mixer->regs[mixer->index]; break; case 0xff: /* Undocumented register used by some Creative drivers. This and the upper bits of 0x82 seem to affect the playback volume: - Register FF = FF: Volume playback normal. - Register FF = Not FF: Volume playback low unless bit 6 of 82h is set. */ if (sb->dsp.sb_type > SBAWE32) ret = mixer->regs[mixer->index]; break; default: sb_log("sb_ct1745: Unknown register READ: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } sb_log("CT1745: [R] %02X = %02X\n", mixer->index, ret); } sb_log("CT1745: read REG%02X: %02X\n", mixer->index, ret); return ret; } void sb_ct1745_mixer_reset(sb_t *sb) { if (sb != NULL) { sb_ct1745_mixer_write(4, 0, sb); sb_ct1745_mixer_write(5, 0, sb); } } static void ess_base_write(uint16_t addr, uint8_t val, void *priv) { sb_t * ess = (sb_t *) priv; switch (addr & 0x000f) { case 0x0002: case 0x0003: case 0x0006: case 0x000c: ess->dsp.activity &= 0xdf; break; case 0x0008: case 0x0009: ess->dsp.activity &= 0x7f; break; } } static uint8_t ess_base_read(uint16_t addr, void *priv) { sb_t * ess = (sb_t *) priv; switch (addr & 0x000f) { case 0x0002: case 0x0003: case 0x0004: /* Undocumented but tested by the LBA 2 ES688 driver. */ case 0x000a: ess->dsp.activity &= 0xdf; break; case 0x0008: case 0x0009: ess->dsp.activity &= 0x7f; break; case 0x000c: case 0x000e: ess->dsp.activity &= 0xbf; break; } sb_log("ess_base_read(%04X): %04X, activity now: %02X\n", addr, addr & 0x000f, ess->dsp.activity); return 0xff; } static void ess_fm_midi_write(uint16_t addr, uint8_t val, void *priv) { sb_t * ess = (sb_t *) priv; ess->dsp.activity &= 0x7f; } static uint8_t ess_fm_midi_read(uint16_t addr, void *priv) { sb_t * ess = (sb_t *) priv; ess->dsp.activity &= 0x7f; return 0xff; } void ess_mixer_write(uint16_t addr, uint8_t val, void *priv) { sb_t *ess = (sb_t *) priv; ess_mixer_t *mixer = (ess == NULL) ? NULL : &ess->mixer_ess; sb_log("[%04X:%08X] [W] %04X = %02X\n", CS, cpu_state.pc, addr, val); if (mixer == NULL) return; if (!(addr & 1)) { mixer->index = val; mixer->regs[0x01] = val; if (val == 0x40) { mixer->ess_id_str_pos = 0; } } else { if (mixer->index == 0) { /* Reset */ mixer->regs[0x0a] = mixer->regs[0x0c] = 0x00; mixer->regs[0x0e] = 0x00; /* Changed default from -11dB to 0dB */ mixer->regs[0x04] = mixer->regs[0x22] = 0xee; mixer->regs[0x26] = mixer->regs[0x28] = 0xee; mixer->regs[0x2e] = 0x00; /* Initialize ESS regs * Defaulting to 0dB instead of the standard -11dB. */ mixer->regs[0x14] = mixer->regs[0x32] = 0xff; mixer->regs[0x36] = mixer->regs[0x38] = 0xff; mixer->regs[0x3a] = 0x00; mixer->regs[0x3c] = 0x05; mixer->regs[0x3e] = 0x00; sb_dsp_set_stereo(&ess->dsp, mixer->regs[0x0e] & 2); } else { mixer->regs[mixer->index] = val; switch (mixer->index) { /* Compatibility: chain registers 0x02 and 0x22 as well as 0x06 and 0x26 */ case 0x02: case 0x06: case 0x08: mixer->regs[mixer->index + 0x20] = ((val & 0xe) << 4) | (val & 0xe); break; case 0x0A: { uint8_t mic_vol_2bit = (mixer->regs[0x0a] >> 1) & 0x3; mixer->mic_l = mixer->mic_r = sb_att_7dbstep_2bits[mic_vol_2bit] / 32767.0; mixer->regs[0x1A] = mic_vol_2bit | (mic_vol_2bit << 2) | (mic_vol_2bit << 4) | (mic_vol_2bit << 6); break; } case 0x0C: switch (mixer->regs[0x0C] & 6) { case 2: mixer->input_selector = INPUT_CD_L | INPUT_CD_R; break; case 6: mixer->input_selector = INPUT_LINE_L | INPUT_LINE_R; break; default: mixer->input_selector = INPUT_MIC; break; } mixer->input_filter = !(mixer->regs[0xC] & 0x20); mixer->in_filter_freq = ((mixer->regs[0xC] & 0x8) == 0) ? 3200 : 8800; break; case 0x0E: mixer->output_filter = !(mixer->regs[0xE] & 0x20); mixer->stereo = mixer->regs[0xE] & 2; sb_dsp_set_stereo(&ess->dsp, val & 2); break; case 0x14: mixer->regs[0x4] = val & 0xee; break; case 0x1A: mixer->mic_l = sb_att_1p4dbstep_4bits[(mixer->regs[0x1A] >> 4) & 0xF] / 32767.0; mixer->mic_r = sb_att_1p4dbstep_4bits[mixer->regs[0x1A] & 0xF] / 32767.0; break; case 0x1C: if ((mixer->regs[0x1C] & 0x07) == 0x07) { mixer->input_selector = INPUT_MIXER_L | INPUT_MIXER_R; } else if ((mixer->regs[0x1C] & 0x07) == 0x06) { mixer->input_selector = INPUT_LINE_L | INPUT_LINE_R; } else if ((mixer->regs[0x1C] & 0x06) == 0x02) { mixer->input_selector = INPUT_CD_L | INPUT_CD_R; } else if ((mixer->regs[0x1C] & 0x02) == 0) { mixer->input_selector = INPUT_MIC; } break; case 0x22: case 0x26: case 0x28: case 0x2E: mixer->regs[mixer->index - 0x20] = (val & 0xe); mixer->regs[mixer->index + 0x10] = val; break; /* More compatibility: SoundBlaster Pro selects register 020h for 030h, 022h for 032h, 026h for 036h, and 028h for 038h. */ case 0x30: case 0x32: case 0x36: case 0x38: case 0x3e: mixer->regs[mixer->index - 0x10] = (val & 0xee); break; case 0x00: case 0x04: case 0x3a: case 0x3c: break; case 0x64: mixer->regs[mixer->index] = (mixer->regs[mixer->index] & 0xf7) | 0x20; // mixer->regs[mixer->index] &= ~0x8; break; case 0x40: { uint16_t mpu401_base_addr = 0x300 | ((mixer->regs[0x40] << 1) & 0x30); sb_log("mpu401_base_addr = %04X\n", mpu401_base_addr); io_removehandler(ess->midi_addr, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); gameport_remap(ess->gameport, !(mixer->regs[0x40] & 0x2) ? 0x00 : 0x200); if (ess->dsp.sb_subtype != SB_SUBTYPE_ESS_ES1688) { /* Not on ES1688. */ io_removehandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); if ((mixer->regs[0x40] & 0x1) != 0) { io_sethandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); } } switch ((mixer->regs[0x40] >> 5) & 0x7) { default: break; case 0: mpu401_base_addr = 0x0000; mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, -1); break; case 1: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, -1); break; case 2: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, ess->dsp.sb_irqnum); break; case 3: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, 11); break; case 4: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, 9); break; case 5: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, 5); break; case 6: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, 7); break; case 7: mpu401_change_addr(ess->mpu, mpu401_base_addr); mpu401_setirq(ess->mpu, 10); break; } ess->midi_addr = mpu401_base_addr; io_sethandler(addr, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); break; } default: sb_log("ess: Unknown mixer register WRITE: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } } mixer->voice_l = sb_att_2dbstep_4bits[(mixer->regs[0x14] >> 4) & 0x0F] / 32767.0; mixer->voice_r = sb_att_2dbstep_4bits[mixer->regs[0x14] & 0x0F] / 32767.0; mixer->master_l = sb_att_2dbstep_4bits[(mixer->regs[0x32] >> 4) & 0x0F] / 32767.0; mixer->master_r = sb_att_2dbstep_4bits[mixer->regs[0x32] & 0x0F] / 32767.0; mixer->fm_l = sb_att_2dbstep_4bits[(mixer->regs[0x36] >> 4) & 0x0F] / 32767.0; mixer->fm_r = sb_att_2dbstep_4bits[mixer->regs[0x36] & 0x0F] / 32767.0; mixer->cd_l = sb_att_2dbstep_4bits[(mixer->regs[0x38] >> 4) & 0x0F] / 32767.0; mixer->cd_r = sb_att_2dbstep_4bits[mixer->regs[0x38] & 0x0F] / 32767.0; mixer->auxb_l = sb_att_2dbstep_4bits[(mixer->regs[0x3a] >> 4) & 0x0F] / 32767.0; mixer->auxb_r = sb_att_2dbstep_4bits[mixer->regs[0x3a] & 0x0F] / 32767.0; mixer->line_l = sb_att_2dbstep_4bits[(mixer->regs[0x3e] >> 4) & 0x0F] / 32767.0; mixer->line_r = sb_att_2dbstep_4bits[mixer->regs[0x3e] & 0x0F] / 32767.0; mixer->speaker = sb_att_3dbstep_3bits[mixer->regs[0x3c] & 0x07] / 32767.0; } } uint8_t ess_mixer_read(uint16_t addr, void *priv) { const sb_t * ess = (sb_t *) priv; const ess_mixer_t *mixer = &ess->mixer_ess; uint8_t ret = 0x0a; if (!(addr & 1)) ret = mixer->index; else switch (mixer->index) { case 0x00: case 0x0a: case 0x0c: case 0x0e: case 0x14: case 0x02: case 0x06: case 0x30: case 0x32: case 0x36: case 0x38: case 0x3e: ret = mixer->regs[mixer->index]; break; case 0x04: case 0x22: case 0x26: case 0x28: case 0x2e: ret = mixer->regs[mixer->index] | 0x11; break; case 0x40: if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) ret = mixer->regs[mixer->index]; else ret = 0x0a; break; case 0x48: ret = mixer->regs[mixer->index]; break; /* Return 0x00 so it has bit 3 clear, so NT 5.x drivers don't misdetect it as ES1788. */ case 0x64: ret = (mixer->regs[mixer->index] & 0xf7) | 0x20; break; default: sb_log("ess: Unknown mixer register READ: %02X\t%02X\n", mixer->index, mixer->regs[mixer->index]); break; } sb_log("[%04X:%08X] [R] %04X = %02X\n", CS, cpu_state.pc, addr, ret); return ret; } void ess_mixer_reset(sb_t *ess) { ess_mixer_write(4, 0, ess); ess_mixer_write(5, 0, ess); } uint8_t sb_mcv_read(int port, void *priv) { const sb_t *sb = (sb_t *) priv; sb_log("sb_mcv_read: port=%04x\n", port); return sb->pos_regs[port & 7]; } void sb_mcv_write(int port, uint8_t val, void *priv) { uint16_t addr; sb_t *sb = (sb_t *) priv; if (port < 0x102) return; sb_log("sb_mcv_write: port=%04x val=%02x\n", port, val); addr = sb_mcv_addr[sb->pos_regs[4] & 7]; if (sb->opl_enabled) { io_removehandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(0x0388, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&sb->dsp, 0); sb->pos_regs[port & 7] = val; if (sb->pos_regs[2] & 1) { addr = sb_mcv_addr[sb->pos_regs[4] & 7]; if (sb->opl_enabled) { io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&sb->dsp, addr); } } uint8_t sb_mcv_feedb(void *priv) { const sb_t *sb = (sb_t *) priv; return (sb->pos_regs[2] & 1); } static uint8_t sb_pro_mcv_read(int port, void *priv) { const sb_t *sb = (sb_t *) priv; uint8_t ret = sb->pos_regs[port & 7]; sb_log("sb_pro_mcv_read: port=%04x ret=%02x\n", port, ret); return ret; } static void sb_pro_mcv_write(int port, uint8_t val, void *priv) { uint16_t addr; sb_t *sb = (sb_t *) priv; if (port < 0x102) return; sb_log("sb_pro_mcv_write: port=%04x val=%02x\n", port, val); addr = (sb->pos_regs[2] & 0x20) ? 0x220 : 0x240; io_removehandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, sb); /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&sb->dsp, 0); sb->pos_regs[port & 7] = val; if (sb->pos_regs[2] & 1) { addr = (sb->pos_regs[2] & 0x20) ? 0x220 : 0x240; io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, sb); /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&sb->dsp, addr); } sb_dsp_setirq(&sb->dsp, sb_pro_mcv_irqs[(sb->pos_regs[5] >> 4) & 3]); sb_dsp_setdma8(&sb->dsp, sb->pos_regs[4] & 3); } static uint8_t sb_16_reply_mca_read(int port, void *priv) { const sb_t *sb = (sb_t *) priv; uint8_t ret = sb->pos_regs[port & 7]; sb_log("sb_16_reply_mca_read: port=%04x ret=%02x\n", port, ret); return ret; } static void sb_16_reply_mca_write(const int port, const uint8_t val, void *priv) { uint16_t addr; sb_t *sb = (sb_t *) priv; if (port < 0x102) return; sb_log("sb_16_reply_mca_write: port=%04x val=%02x\n", port, val); switch (sb->pos_regs[2] & 0xc4) { case 4: addr = 0x220; break; case 0x44: addr = 0x240; break; case 0x84: addr = 0x260; break; case 0xc4: addr = 0x280; break; case 0: default: addr = 0; break; } if (addr) { io_removehandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&sb->dsp, 0); mpu401_change_addr(sb->mpu, 0); gameport_remap(sb->gameport, 0); sb->pos_regs[port & 7] = val; if (sb->pos_regs[2] & 1) { uint16_t mpu401_addr; switch (sb->pos_regs[2] & 0xc4) { case 4: addr = 0x220; break; case 0x44: addr = 0x240; break; case 0x84: addr = 0x260; break; case 0xc4: addr = 0x280; break; case 0: default: addr = 0; break; } switch (sb->pos_regs[2] & 0x18) { case 8: mpu401_addr = 0x330; break; case 0x18: mpu401_addr = 0x300; break; case 0: default: mpu401_addr = 0; break; } if (addr) { io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&sb->dsp, addr); mpu401_change_addr(sb->mpu, mpu401_addr); gameport_remap(sb->gameport, (sb->pos_regs[2] & 0x20) ? 0x200 : 0); } switch (sb->pos_regs[4] & 0x60) { case 0x20: sb_dsp_setirq(&sb->dsp, 5); break; case 0x40: sb_dsp_setirq(&sb->dsp, 7); break; case 0x60: sb_dsp_setirq(&sb->dsp, 10); break; default: break; } const int low_dma = sb->pos_regs[3] & 3; int high_dma = (sb->pos_regs[3] >> 4) & 7; if (!high_dma) high_dma = low_dma; sb_dsp_setdma8(&sb->dsp, low_dma); sb_dsp_setdma16(&sb->dsp, high_dma); } void sb_vibra16s_onboard_relocate_base(uint16_t new_addr, void *priv) { sb_t *sb = (sb_t *) priv; uint16_t addr = sb->dsp.sb_addr; io_removehandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); sb_dsp_setaddr(&sb->dsp, 0); addr = new_addr; io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); sb_dsp_setaddr(&sb->dsp, addr); } static void sb_16_pnp_config_changed(const uint8_t ld, isapnp_device_config_t *config, void *priv) { sb_t *sb = (sb_t *) priv; uint16_t addr = sb->dsp.sb_addr; switch (ld) { default: case 4: /* StereoEnhance (32) */ break; case 0: /* Audio */ io_removehandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_removehandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); addr = sb->opl_pnp_addr; if (addr) { sb->opl_pnp_addr = 0; io_removehandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } sb_dsp_setaddr(&sb->dsp, 0); sb_dsp_setirq(&sb->dsp, 0); sb_dsp_setdma8(&sb->dsp, ISAPNP_DMA_DISABLED); sb_dsp_setdma16(&sb->dsp, ISAPNP_DMA_DISABLED); mpu401_change_addr(sb->mpu, 0); if (config->activate) { uint8_t val = config->irq[0].irq; addr = config->io[0].base; if (addr != ISAPNP_IO_DISABLED) { io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); sb_dsp_setaddr(&sb->dsp, addr); } addr = config->io[1].base; if (addr != ISAPNP_IO_DISABLED) mpu401_change_addr(sb->mpu, addr); addr = config->io[2].base; if (addr != ISAPNP_IO_DISABLED) { sb->opl_pnp_addr = addr; io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } if (val != ISAPNP_IRQ_DISABLED) sb_dsp_setirq(&sb->dsp, val); val = config->dma[0].dma; if (val != ISAPNP_DMA_DISABLED) sb_dsp_setdma8(&sb->dsp, val); val = config->dma[1].dma; sb_dsp_setdma16_enabled(&sb->dsp, val != ISAPNP_DMA_DISABLED); sb_dsp_setdma16_translate(&sb->dsp, val < ISAPNP_DMA_DISABLED); if (val != ISAPNP_DMA_DISABLED) { if (sb->dsp.sb_16_dma_supported) sb_dsp_setdma16(&sb->dsp, val); else sb_dsp_setdma16_8(&sb->dsp, val); } } break; case 1: /* IDE */ ide_pnp_config_changed(0, config, (void *) 3); break; case 2: /* Reserved (16) / WaveTable (32+) */ if (sb->dsp.sb_type > SB16) emu8k_change_addr(&sb->emu8k, (config->activate && (config->io[0].base != ISAPNP_IO_DISABLED)) ? config->io[0].base : 0); break; case 3: /* Game */ gameport_remap(sb->gameport, (config->activate && (config->io[0].base != ISAPNP_IO_DISABLED)) ? config->io[0].base : 0); break; } } static void sb_vibra16_pnp_config_changed(const uint8_t ld, isapnp_device_config_t *config, void *priv) { sb_t *sb = (sb_t *) priv; switch (ld) { case 0: /* Audio */ case 1: /* Game */ sb_16_pnp_config_changed(ld * 3, config, sb); break; default: break; } } static void sb_awe32_pnp_config_changed(const uint8_t ld, isapnp_device_config_t *config, void *priv) { sb_t *sb = (sb_t *) priv; switch (ld) { case 0: /* Audio */ case 1: /* IDE */ sb_16_pnp_config_changed(ld, config, sb); break; case 2: /* Game */ case 3: /* WaveTable */ sb_16_pnp_config_changed(ld ^ 1, config, sb); break; default: break; } } static void sb_awe64_pnp_config_changed(const uint8_t ld, isapnp_device_config_t *config, void *priv) { sb_t *sb = (sb_t *) priv; switch (ld) { case 0: /* Audio */ case 2: /* WaveTable */ sb_16_pnp_config_changed(ld, config, sb); break; case 1: /* Game */ case 3: /* IDE */ sb_16_pnp_config_changed(ld ^ 2, config, sb); break; default: break; } } static void sb_awe64_gold_pnp_config_changed(const uint8_t ld, isapnp_device_config_t *config, void *priv) { sb_t *sb = (sb_t *) priv; switch (ld) { case 0: /* Audio */ case 2: /* WaveTable */ sb_16_pnp_config_changed(ld, config, sb); break; case 1: /* Game */ sb_16_pnp_config_changed(3, config, sb); break; default: break; } } static void ess_x688_pnp_config_changed(UNUSED(const uint8_t ld), isapnp_device_config_t *config, void *priv) { sb_t *ess = (sb_t *) priv; uint16_t addr = ess->dsp.sb_addr; uint8_t val; switch (ld) { case 0: /* Audio */ io_removehandler(addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_removehandler(addr + 4, 0x0002, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); io_removehandler(addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_removehandler(addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_removehandler(addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); ess->mixer_ess.ess_id_str[2] = 0x00; ess->mixer_ess.ess_id_str[3] = 0x00; addr = ess->opl_pnp_addr; if (addr) { ess->opl_pnp_addr = 0; io_removehandler(addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(addr, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } if (ess->pnp == 3) { addr = ess->midi_addr; if (addr) { ess->midi_addr = 0; mpu401_change_addr(ess->mpu, 0); io_removehandler(addr, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } } sb_dsp_setaddr(&ess->dsp, 0); sb_dsp_setirq(&ess->dsp, 0); if (ess->pnp == 3) mpu401_setirq(ess->mpu, -1); sb_dsp_setdma8(&ess->dsp, ISAPNP_DMA_DISABLED); sb_dsp_setdma16_8(&ess->dsp, ISAPNP_DMA_DISABLED); if (config->activate) { addr = config->io[0].base; if (addr != ISAPNP_IO_DISABLED) { io_sethandler(addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(addr + 4, 0x0002, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); sb_dsp_setaddr(&ess->dsp, addr); io_sethandler(addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); ess->mixer_ess.ess_id_str[2] = (addr >> 8) & 0xff; ess->mixer_ess.ess_id_str[3] = addr & 0xff; } addr = config->io[1].base; if (addr != ISAPNP_IO_DISABLED) { ess->opl_pnp_addr = addr; io_sethandler(addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(addr, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } if (ess->pnp == 3) { addr = config->io[2].base; if (addr != ISAPNP_IO_DISABLED) { mpu401_change_addr(ess->mpu, addr); io_sethandler(addr, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } } val = config->irq[0].irq; if (val != ISAPNP_IRQ_DISABLED) { sb_dsp_setirq(&ess->dsp, val); if (ess->pnp == 3) mpu401_setirq(ess->mpu, val); } val = config->dma[0].dma; if (val != ISAPNP_DMA_DISABLED) { sb_dsp_setdma8(&ess->dsp, val); sb_dsp_setdma16_8(&ess->dsp, val); } } break; case 1: if (ess->pnp == 3) { /* Game */ gameport_remap(ess->gameport, (config->activate && (config->io[0].base != ISAPNP_IO_DISABLED)) ? config->io[0].base : 0); } else { /* MPU-401 */ mpu401_change_addr(ess->mpu, 0); mpu401_setirq(ess->mpu, -1); if (config->activate) { addr = config->io[0].base; if (addr != ISAPNP_IO_DISABLED) mpu401_change_addr(ess->mpu, addr); val = config->irq[0].irq; if (val != ISAPNP_IRQ_DISABLED) mpu401_setirq(ess->mpu, val); } } break; case 2: if (ess->pnp == 3) /* IDE */ ide_pnp_config_changed_1addr(0, config, (void *) 3); else /* Game */ gameport_remap(ess->gameport, (config->activate && (config->io[0].base != ISAPNP_IO_DISABLED)) ? config->io[0].base : 0); break; case 3: if (ess->pnp <= 2) /* IDE */ ide_pnp_config_changed_1addr(0, config, (void *) 3); break; default: break; } } /* This function is common to all the ESS MCA cards. */ static uint8_t ess_x688_mca_read(const int port, void *priv) { const sb_t *ess = (sb_t *) priv; const uint8_t ret = ess->pos_regs[port & 7]; sb_log("ess_mca_read: port=%04x ret=%02x\n", port, ret); return ret; } static void ess_soundpiper_mca_write(const int port, const uint8_t val, void *priv) { sb_t *ess = (sb_t *) priv; if (port < 0x102) return; sb_log("ess_soundpiper_mca_write: port=%04x val=%02x\n", port, val); if (ess->dsp.sb_addr != 0x0000) { io_removehandler(ess->dsp.sb_addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(ess->dsp.sb_addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(ess->dsp.sb_addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_removehandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(0x0388, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 4, 0x0002, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&ess->dsp, 0); gameport_remap(ess->gameport, 0); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) { mpu401_change_addr(ess->mpu, 0); io_removehandler(0x0330, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } ess->pos_regs[port & 7] = val; if (ess->pos_regs[2] & 1) { switch (ess->pos_regs[2] & 0x0e) { default: ess->dsp.sb_addr = 0x0000; break; case 0x08: ess->dsp.sb_addr = 0x0240; break; case 0x0c: ess->dsp.sb_addr = 0x0220; break; } if (ess->dsp.sb_addr != 0x0000) { io_sethandler(ess->dsp.sb_addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(ess->dsp.sb_addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(ess->dsp.sb_addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(0x0388, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 4, 0x0002, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) { mpu401_change_addr(ess->mpu, ess->pos_regs[3] & 0x02 ? 0x0330 : 0); if (ess->pos_regs[3] & 0x02) io_sethandler(0x0330, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&ess->dsp, ess->dsp.sb_addr); gameport_remap(ess->gameport, (ess->pos_regs[3] & 0x01) ? 0x200 : 0); } switch (ess->pos_regs[3] & 0xc0) { default: break; case 0x80: sb_dsp_setirq(&ess->dsp, 9); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) mpu401_setirq(ess->mpu, 9); break; case 0xa0: sb_dsp_setirq(&ess->dsp, 5); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) mpu401_setirq(ess->mpu, 5); break; case 0xc0: sb_dsp_setirq(&ess->dsp, 7); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) mpu401_setirq(ess->mpu, 7); break; case 0xe0: sb_dsp_setirq(&ess->dsp, 10); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) mpu401_setirq(ess->mpu, 10); break; } if (ess->pos_regs[3] & 0x04) { sb_dsp_setdma8(&ess->dsp, ess->pos_regs[2] >> 4); sb_dsp_setdma16_8(&ess->dsp, ess->pos_regs[2] >> 4); } } static void ess_chipchat_mca_write(int port, uint8_t val, void *priv) { sb_t *ess = (sb_t *) priv; if (port < 0x102) return; sb_log("ess_chipchat_mca_write: port=%04x val=%02x\n", port, val); if (ess->dsp.sb_addr != 0x0000) { io_removehandler(ess->dsp.sb_addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(ess->dsp.sb_addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(ess->dsp.sb_addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_removehandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_removehandler(0x0388, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 4, 0x0002, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_removehandler(ess->dsp.sb_addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&ess->dsp, 0); gameport_remap(ess->gameport, 0); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) { mpu401_change_addr(ess->mpu, 0); io_removehandler(0x0330, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } ess->pos_regs[port & 7] = val; if (ess->pos_regs[2] & 1) { ess->dsp.sb_addr = (ess->pos_regs[2] == 0x51) ? 0x0220 : 0x0000; if (ess->dsp.sb_addr != 0x0000) { io_sethandler(ess->dsp.sb_addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(ess->dsp.sb_addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(ess->dsp.sb_addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(0x0388, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 4, 0x0004, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(ess->dsp.sb_addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); if (ess->dsp.sb_subtype == SB_SUBTYPE_ESS_ES1688) { mpu401_change_addr(ess->mpu, (ess->pos_regs[2] == 0x51) ? 0x0330 : 0); if (ess->pos_regs[2] == 0x51) io_sethandler(0x0330, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); } } /* DSP I/O handler is activated in sb_dsp_setaddr */ sb_dsp_setaddr(&ess->dsp, ess->dsp.sb_addr); gameport_remap(ess->gameport, (ess->pos_regs[2] == 0x51) ? 0x200 : 0); } if (ess->pos_regs[2] == 0x51) { sb_dsp_setirq(&ess->dsp, 7); mpu401_setirq(ess->mpu, 7); sb_dsp_setdma8(&ess->dsp, 1); sb_dsp_setdma16_8(&ess->dsp, 1); } } void * sb_1_init(UNUSED(const device_t *info)) { /* SB1/2 port mappings, 210h to 260h in 10h steps 2x0 to 2x3 -> CMS chip 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip */ sb_t * sb = malloc(sizeof(sb_t)); const uint16_t addr = device_get_config_hex16("base"); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get(FM_YM3812, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SB1, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); /* DSP I/O handler is activated in sb_dsp_setaddr */ if (sb->opl_enabled) { io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } sb->cms_enabled = 1; memset(&sb->cms, 0, sizeof(cms_t)); io_sethandler(addr, 0x0004, cms_read, NULL, NULL, cms_write, NULL, NULL, &sb->cms); sb->mixer_enabled = 0; sound_add_handler(sb_get_buffer_sb2, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sb2, sb); sound_set_cd_audio_filter(sb2_filter_cd_audio, sb); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } void * sb_15_init(UNUSED(const device_t *info)) { /* SB1/2 port mappings, 210h to 260h in 10h steps 2x0 to 2x3 -> CMS chip 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip */ sb_t * sb = malloc(sizeof(sb_t)); const uint16_t addr = device_get_config_hex16("base"); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get(FM_YM3812, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SB15, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); /* DSP I/O handler is activated in sb_dsp_setaddr */ if (sb->opl_enabled) { io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } sb->cms_enabled = device_get_config_int("cms"); if (sb->cms_enabled) { memset(&sb->cms, 0, sizeof(cms_t)); io_sethandler(addr, 0x0004, cms_read, NULL, NULL, cms_write, NULL, NULL, &sb->cms); } sb->mixer_enabled = 0; sound_add_handler(sb_get_buffer_sb2, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sb2, sb); sound_set_cd_audio_filter(sb2_filter_cd_audio, sb); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } void * sb_mcv_init(UNUSED(const device_t *info)) { /* SB1/2 port mappings, 210h to 260h in 10h steps 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip */ sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get(FM_YM3812, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SB15, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, 0); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); sb->mixer_enabled = 0; sound_add_handler(sb_get_buffer_sb2, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sb2, sb); sound_set_cd_audio_filter(sb2_filter_cd_audio, sb); /* I/O handlers activated in sb_mcv_write */ mca_add(sb_mcv_read, sb_mcv_write, sb_mcv_feedb, NULL, sb); sb->pos_regs[0] = 0x84; sb->pos_regs[1] = 0x50; if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } void * sb_2_init(UNUSED(const device_t *info)) { /* SB2 port mappings, 220h or 240h. 2x0 to 2x3 -> CMS chip 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip "CD version" also uses 250h or 260h for 2x0 to 2x3 -> CDROM interface 2x4 to 2x5 -> Mixer interface */ /* My SB 2.0 mirrors the OPL2 at ports 2x0/2x1. Presumably this mirror is disabled when the CMS chips are present. This mirror may also exist on SB 1.5 & MCV, however I am unable to test this. It shouldn't exist on SB 1.0 as the CMS chips are always present there. Syndicate requires this mirror for music to play.*/ sb_t *sb = malloc(sizeof(sb_t)); uint16_t addr = device_get_config_hex16("base"); uint16_t mixer_addr = device_get_config_int("mixaddr"); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get(FM_YM3812, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SB2, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); if (mixer_addr > 0x000) sb_ct1335_mixer_reset(sb); sb->cms_enabled = device_get_config_int("cms"); /* DSP I/O handler is activated in sb_dsp_setaddr */ if (sb->opl_enabled) { if (!sb->cms_enabled) { io_sethandler(addr, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } if (sb->cms_enabled) { memset(&sb->cms, 0, sizeof(cms_t)); io_sethandler(addr, 0x0004, cms_read, NULL, NULL, cms_write, NULL, NULL, &sb->cms); } if (mixer_addr > 0x000) { sb->mixer_enabled = 1; io_sethandler(mixer_addr + 4, 0x0002, sb_ct1335_mixer_read, NULL, NULL, sb_ct1335_mixer_write, NULL, NULL, sb); } else sb->mixer_enabled = 0; sound_add_handler(sb_get_buffer_sb2, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sb2, sb); sound_set_cd_audio_filter(sb2_filter_cd_audio, sb); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } static uint8_t sb_pro_v1_opl_read(uint16_t port, void *priv) { sb_t *sb = (sb_t *) priv; cycles -= ((int) (isa_timing * 8)); (void) sb->opl2.read(port, sb->opl2.priv); // read, but ignore return (sb->opl.read(port, sb->opl.priv)); } static void sb_pro_v1_opl_write(uint16_t port, uint8_t val, void *priv) { sb_t *sb = (sb_t *) priv; sb->opl.write(port, val, sb->opl.priv); sb->opl2.write(port, val, sb->opl2.priv); } static void * sb_pro_v1_init(UNUSED(const device_t *info)) { /* SB Pro port mappings, 220h or 240h. 2x0 to 2x3 -> FM chip, Left and Right (9*2 voices) 2x4 to 2x5 -> Mixer interface 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip (9 voices) 2x0+10 to 2x0+13 CDROM interface. */ sb_t *sb = malloc(sizeof(sb_t)); uint16_t addr = device_get_config_hex16("base"); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) { fm_driver_get(FM_YM3812, &sb->opl); sb->opl.set_do_cycles(sb->opl.priv, 0); fm_driver_get(FM_YM3812, &sb->opl2); sb->opl2.set_do_cycles(sb->opl2.priv, 0); } sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SBPRO, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); sb_ct1345_mixer_reset(sb); /* DSP I/O handler is activated in sb_dsp_setaddr */ if (sb->opl_enabled) { io_sethandler(addr, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 2, 0x0002, sb->opl2.read, NULL, NULL, sb->opl2.write, NULL, NULL, sb->opl2.priv); io_sethandler(addr + 8, 0x0002, sb_pro_v1_opl_read, NULL, NULL, sb_pro_v1_opl_write, NULL, NULL, sb); io_sethandler(0x0388, 0x0002, sb_pro_v1_opl_read, NULL, NULL, sb_pro_v1_opl_write, NULL, NULL, sb); } sb->mixer_enabled = 1; io_sethandler(addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, sb); sound_add_handler(sb_get_buffer_sbpro, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sbpro, sb); sound_set_cd_audio_filter(sbpro_filter_cd_audio, sb); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } static void * sb_pro_v2_init(UNUSED(const device_t *info)) { /* SB Pro 2 port mappings, 220h or 240h. 2x0 to 2x3 -> FM chip (18 voices) 2x4 to 2x5 -> Mixer interface 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip (9 voices) 2x0+10 to 2x0+13 CDROM interface. */ sb_t *sb = malloc(sizeof(sb_t)); uint16_t addr = device_get_config_hex16("base"); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SBPRO2, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); sb_ct1345_mixer_reset(sb); /* DSP I/O handler is activated in sb_dsp_setaddr */ if (sb->opl_enabled) { io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } sb->mixer_enabled = 1; io_sethandler(addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, sb); sound_add_handler(sb_get_buffer_sbpro, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sbpro, sb); sound_set_cd_audio_filter(sbpro_filter_cd_audio, sb); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } static void * sb_pro_mcv_init(UNUSED(const device_t *info)) { /* SB Pro MCV port mappings, 220h or 240h. 2x0 to 2x3 -> FM chip, Left and Right (18 voices) 2x4 to 2x5 -> Mixer interface 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip (9 voices) */ sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0, sizeof(sb_t)); sb->opl_enabled = 1; fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SBPRO2, SB_SUBTYPE_DEFAULT, sb); sb_ct1345_mixer_reset(sb); sb->mixer_enabled = 1; sound_add_handler(sb_get_buffer_sbpro, sb); music_add_handler(sb_get_music_buffer_sbpro, sb); sound_set_cd_audio_filter(sbpro_filter_cd_audio, sb); /* I/O handlers activated in sb_pro_mcv_write */ mca_add(sb_pro_mcv_read, sb_pro_mcv_write, sb_mcv_feedb, NULL, sb); sb->pos_regs[0] = 0x03; sb->pos_regs[1] = 0x51; if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); return sb; } static void * sb_pro_compat_init(UNUSED(const device_t *info)) { sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0, sizeof(sb_t)); fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SBPRO2, SB_SUBTYPE_DEFAULT, sb); sb_ct1345_mixer_reset(sb); sb->mixer_enabled = 1; sound_add_handler(sb_get_buffer_sbpro, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sbpro, sb); sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, 0, 0, M_UART, 1); sb_dsp_set_mpu(&sb->dsp, sb->mpu); return sb; } static void * sb_16_init(UNUSED(const device_t *info)) { sb_t *sb = malloc(sizeof(sb_t)); const uint16_t addr = device_get_config_hex16("base"); const uint16_t mpu_addr = device_get_config_hex16("base401"); memset(sb, 0x00, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get((int) (intptr_t) info->local, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, (info->local == FM_YMF289B) ? SBAWE32PNP : SB16, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); sb_dsp_setdma16(&sb->dsp, device_get_config_int("dma16")); sb_dsp_setdma16_supported(&sb->dsp, 1); sb_dsp_setdma16_enabled(&sb->dsp, 1); sb_ct1745_mixer_reset(sb); if (sb->opl_enabled) { io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } sb->mixer_enabled = 1; sb->mixer_sb16.output_filter = 1; io_sethandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); sound_add_handler(sb_get_buffer_sb16_awe32, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sb16_awe32, sb); sound_set_cd_audio_filter(sb16_awe32_filter_cd_audio, sb); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(sb16_awe32_filter_pc_speaker, sb); if (mpu_addr) { sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, device_get_config_hex16("base401"), 0, M_UART, device_get_config_int("receive_input401")); } else sb->mpu = NULL; sb_dsp_set_mpu(&sb->dsp, sb->mpu); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); sb->gameport = gameport_add(&gameport_pnp_device); sb->gameport_addr = 0x200; gameport_remap(sb->gameport, sb->gameport_addr); return sb; } static void * sb_16_reply_mca_init(UNUSED(const device_t *info)) { sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0x00, sizeof(sb_t)); sb->opl_enabled = 1; fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SB16, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setdma16_supported(&sb->dsp, 1); sb_dsp_setdma16_enabled(&sb->dsp, 1); sb_ct1745_mixer_reset(sb); sb->mixer_enabled = 1; sb->mixer_sb16.output_filter = 1; sound_add_handler(sb_get_buffer_sb16_awe32, sb); music_add_handler(sb_get_music_buffer_sb16_awe32, sb); sound_set_cd_audio_filter(sb16_awe32_filter_cd_audio, sb); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(sb16_awe32_filter_pc_speaker, sb); sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, 0, 0, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&sb->dsp, sb->mpu); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); sb->gameport = gameport_add(&gameport_device); /* I/O handlers activated in sb_pro_mcv_write */ mca_add(sb_16_reply_mca_read, sb_16_reply_mca_write, sb_mcv_feedb, NULL, sb); sb->pos_regs[0] = 0x38; sb->pos_regs[1] = 0x51; sb->gameport_addr = 0x200; return sb; } static int sb_16_pnp_available(void) { return rom_present(PNP_ROM_SB_16_PNP); } static void * sb_16_pnp_init(UNUSED(const device_t *info)) { sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0x00, sizeof(sb_t)); sb->pnp = 1; sb->opl_enabled = 1; fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_init(&sb->dsp, SB16, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setdma16_supported(&sb->dsp, 1); sb_ct1745_mixer_reset(sb); sb->mixer_enabled = 1; sb->mixer_sb16.output_filter = 1; sound_add_handler(sb_get_buffer_sb16_awe32, sb); music_add_handler(sb_get_music_buffer_sb16_awe32, sb); sound_set_cd_audio_filter(sb16_awe32_filter_cd_audio, sb); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(sb16_awe32_filter_pc_speaker, sb); sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, 0, 0, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&sb->dsp, sb->mpu); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); sb->gameport = gameport_add(&gameport_pnp_device); device_add(&ide_qua_pnp_device); other_ide_present++; uint8_t *pnp_rom = NULL; FILE *fp = rom_fopen(PNP_ROM_SB_16_PNP, "rb"); if (fp) { if (fread(sb->pnp_rom, 1, 390, fp) == 390) pnp_rom = sb->pnp_rom; fclose(fp); } isapnp_add_card(pnp_rom, 390, sb_16_pnp_config_changed, NULL, NULL, NULL, sb); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_setaddr(&sb->dsp, 0); sb_dsp_setirq(&sb->dsp, 0); sb_dsp_setdma8(&sb->dsp, ISAPNP_DMA_DISABLED); sb_dsp_setdma16(&sb->dsp, ISAPNP_DMA_DISABLED); mpu401_change_addr(sb->mpu, 0); ide_remove_handlers(3); sb->gameport_addr = 0; gameport_remap(sb->gameport, 0); return sb; } static int sb_vibra16xv_available(void) { return rom_present(PNP_ROM_SB_VIBRA16XV); } static int sb_vibra16c_available(void) { return rom_present(PNP_ROM_SB_VIBRA16C); } static void * sb_vibra16_pnp_init(UNUSED(const device_t *info)) { sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0x00, sizeof(sb_t)); sb->pnp = 1; sb->opl_enabled = 1; fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, (info->local == 0) ? SBAWE64 : SBAWE32PNP, SB_SUBTYPE_DEFAULT, sb); /* The ViBRA 16XV does 16-bit DMA through 8-bit DMA. */ sb_dsp_setdma16_supported(&sb->dsp, info->local != 0); sb_ct1745_mixer_reset(sb); sb->mixer_enabled = 1; sb->mixer_sb16.output_filter = 1; sound_add_handler(sb_get_buffer_sb16_awe32, sb); music_add_handler(sb_get_music_buffer_sb16_awe32, sb); sound_set_cd_audio_filter(sb16_awe32_filter_cd_audio, sb); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(sb16_awe32_filter_pc_speaker, sb); sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, 0, 0, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&sb->dsp, sb->mpu); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); sb->gameport = gameport_add(&gameport_pnp_device); const char *pnp_rom_file = NULL; switch (info->local) { case 0: pnp_rom_file = PNP_ROM_SB_VIBRA16XV; break; case 1: pnp_rom_file = PNP_ROM_SB_VIBRA16C; break; default: break; } uint8_t *pnp_rom = NULL; if (pnp_rom_file) { FILE *fp = rom_fopen(pnp_rom_file, "rb"); if (fp) { if (fread(sb->pnp_rom, 1, 512, fp) == 512) pnp_rom = sb->pnp_rom; fclose(fp); } } switch (info->local) { case 0: case 1: isapnp_add_card(pnp_rom, 512, sb_vibra16_pnp_config_changed, NULL, NULL, NULL, sb); break; default: break; } sb_dsp_setaddr(&sb->dsp, 0); sb_dsp_setirq(&sb->dsp, 0); sb_dsp_setdma8(&sb->dsp, ISAPNP_DMA_DISABLED); sb_dsp_setdma16(&sb->dsp, ISAPNP_DMA_DISABLED); mpu401_change_addr(sb->mpu, 0); sb->gameport_addr = 0; gameport_remap(sb->gameport, 0); return sb; } static void * sb_16_compat_init(const device_t *info) { sb_t *sb = malloc(sizeof(sb_t)); memset(sb, 0, sizeof(sb_t)); fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SB16, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setdma16_supported(&sb->dsp, 1); sb_dsp_setdma16_enabled(&sb->dsp, 1); sb_ct1745_mixer_reset(sb); sb->opl_enabled = 1; sb->mixer_enabled = 1; sound_add_handler(sb_get_buffer_sb16_awe32, sb); music_add_handler(sb_get_music_buffer_sb16_awe32, sb); sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, 0, 0, M_UART, (int) (intptr_t) info->local); sb_dsp_set_mpu(&sb->dsp, sb->mpu); sb->gameport = gameport_add(&gameport_pnp_device); sb->gameport_addr = 0x200; gameport_remap(sb->gameport, sb->gameport_addr); return sb; } static int sb_awe32_available(void) { return rom_present(EMU8K_ROM_PATH); } static int sb_32_pnp_available(void) { return sb_awe32_available() && rom_present(PNP_ROM_SB_32_PNP); } static int sb_awe32_pnp_available(void) { return sb_awe32_available() && rom_present(PNP_ROM_SB_AWE32_PNP); } static int sb_awe64_value_available(void) { return sb_awe32_available() && rom_present(PNP_ROM_SB_AWE64_VALUE); } static int sb_awe64_available(void) { return sb_awe32_available() && rom_present(PNP_ROM_SB_AWE64); } static int sb_awe64_gold_available(void) { return sb_awe32_available() && rom_present(PNP_ROM_SB_AWE64_GOLD); } static void * sb_awe32_init(UNUSED(const device_t *info)) { sb_t *sb = malloc(sizeof(sb_t)); uint16_t addr = device_get_config_hex16("base"); uint16_t mpu_addr = device_get_config_hex16("base401"); uint16_t emu_addr = device_get_config_hex16("emu_base"); int onboard_ram = device_get_config_int("onboard_ram"); memset(sb, 0x00, sizeof(sb_t)); sb->opl_enabled = device_get_config_int("opl"); if (sb->opl_enabled) fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_set_real_opl(&sb->dsp, 1); sb_dsp_init(&sb->dsp, SBAWE32, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setaddr(&sb->dsp, addr); sb_dsp_setirq(&sb->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&sb->dsp, device_get_config_int("dma")); sb_dsp_setdma16(&sb->dsp, device_get_config_int("dma16")); sb_dsp_setdma16_supported(&sb->dsp, 1); sb_dsp_setdma16_enabled(&sb->dsp, 1); sb_ct1745_mixer_reset(sb); if (sb->opl_enabled) { io_sethandler(addr, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(addr + 8, 0x0002, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); io_sethandler(0x0388, 0x0004, sb->opl.read, NULL, NULL, sb->opl.write, NULL, NULL, sb->opl.priv); } sb->mixer_enabled = 1; sb->mixer_sb16.output_filter = 1; io_sethandler(addr + 4, 0x0002, sb_ct1745_mixer_read, NULL, NULL, sb_ct1745_mixer_write, NULL, NULL, sb); sound_add_handler(sb_get_buffer_sb16_awe32, sb); if (sb->opl_enabled) music_add_handler(sb_get_music_buffer_sb16_awe32, sb); wavetable_add_handler(sb_get_wavetable_buffer_sb16_awe32, sb); sound_set_cd_audio_filter(sb16_awe32_filter_cd_audio, sb); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(sb16_awe32_filter_pc_speaker, sb); if (mpu_addr) { sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, device_get_config_hex16("base401"), 0, M_UART, device_get_config_int("receive_input401")); } else sb->mpu = NULL; sb_dsp_set_mpu(&sb->dsp, sb->mpu); emu8k_init(&sb->emu8k, emu_addr, onboard_ram); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); sb->gameport = gameport_add(&gameport_pnp_device); sb->gameport_addr = 0x200; gameport_remap(sb->gameport, sb->gameport_addr); return sb; } static void * sb_awe32_pnp_init(const device_t *info) { sb_t *sb = malloc(sizeof(sb_t)); int onboard_ram = device_get_config_int("onboard_ram"); memset(sb, 0x00, sizeof(sb_t)); sb->pnp = 1; sb->opl_enabled = 1; fm_driver_get(FM_YMF262, &sb->opl); sb_dsp_init(&sb->dsp, ((info->local == 2) || (info->local == 3) || (info->local == 4)) ? SBAWE64 : SBAWE32PNP, SB_SUBTYPE_DEFAULT, sb); sb_dsp_setdma16_supported(&sb->dsp, 1); sb_ct1745_mixer_reset(sb); sb_dsp_set_real_opl(&sb->dsp, 1); sb->mixer_enabled = 1; sb->mixer_sb16.output_filter = 1; sound_add_handler(sb_get_buffer_sb16_awe32, sb); music_add_handler(sb_get_music_buffer_sb16_awe32, sb); wavetable_add_handler(sb_get_wavetable_buffer_sb16_awe32, sb); sound_set_cd_audio_filter(sb16_awe32_filter_cd_audio, sb); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(sb16_awe32_filter_pc_speaker, sb); sb->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(sb->mpu, 0, sizeof(mpu_t)); mpu401_init(sb->mpu, 0, 0, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&sb->dsp, sb->mpu); emu8k_init(&sb->emu8k, 0, onboard_ram); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &sb->dsp); sb->gameport = gameport_add(&gameport_pnp_device); if ((info->local != 2) && (info->local != 4)) { device_add(&ide_qua_pnp_device); other_ide_present++; } const char *pnp_rom_file = NULL; switch (info->local) { case 0: pnp_rom_file = PNP_ROM_SB_32_PNP; break; case 1: pnp_rom_file = PNP_ROM_SB_AWE32_PNP; break; case 2: pnp_rom_file = PNP_ROM_SB_AWE64_VALUE; break; case 3: pnp_rom_file = PNP_ROM_SB_AWE64; break; case 4: pnp_rom_file = PNP_ROM_SB_AWE64_GOLD; break; default: break; } uint8_t *pnp_rom = NULL; if (pnp_rom_file) { FILE *fp = rom_fopen(pnp_rom_file, "rb"); if (fp) { if (fread(sb->pnp_rom, 1, 512, fp) == 512) pnp_rom = sb->pnp_rom; fclose(fp); } } switch (info->local) { case 0: isapnp_add_card(pnp_rom, sizeof(sb->pnp_rom), sb_16_pnp_config_changed, NULL, NULL, NULL, sb); break; case 1: isapnp_add_card(pnp_rom, sizeof(sb->pnp_rom), sb_awe32_pnp_config_changed, NULL, NULL, NULL, sb); break; case 3: isapnp_add_card(pnp_rom, sizeof(sb->pnp_rom), sb_awe64_pnp_config_changed, NULL, NULL, NULL, sb); break; case 2: case 4: isapnp_add_card(pnp_rom, sizeof(sb->pnp_rom), sb_awe64_gold_pnp_config_changed, NULL, NULL, NULL, sb); break; default: break; } sb_dsp_setaddr(&sb->dsp, 0); sb_dsp_setirq(&sb->dsp, 0); sb_dsp_setdma8(&sb->dsp, ISAPNP_DMA_DISABLED); sb_dsp_setdma16(&sb->dsp, ISAPNP_DMA_DISABLED); mpu401_change_addr(sb->mpu, 0); if ((info->local != 2) && (info->local != 4)) ide_remove_handlers(3); emu8k_change_addr(&sb->emu8k, 0); sb->gameport_addr = 0; gameport_remap(sb->gameport, 0); return sb; } static void * ess_x688_init(UNUSED(const device_t *info)) { sb_t *ess = calloc(sizeof(sb_t), 1); const uint16_t addr = device_get_config_hex16("base"); const uint16_t ide_ctrl = (const uint16_t) device_get_config_int("ide_ctrl"); const uint16_t ide_base = ide_ctrl & 0x0fff; const uint16_t ide_side = ide_base + 0x0206; const uint16_t ide_irq = ide_ctrl >> 12; fm_driver_get(info->local ? FM_ESFM : FM_YMF262, &ess->opl); sb_dsp_set_real_opl(&ess->dsp, 1); sb_dsp_init(&ess->dsp, SBPRO2, info->local ? SB_SUBTYPE_ESS_ES1688 : SB_SUBTYPE_ESS_ES688, ess); sb_dsp_setaddr(&ess->dsp, addr); sb_dsp_setirq(&ess->dsp, device_get_config_int("irq")); sb_dsp_setdma8(&ess->dsp, device_get_config_int("dma")); sb_dsp_setdma16_8(&ess->dsp, device_get_config_int("dma")); sb_dsp_setdma16_supported(&ess->dsp, 0); ess_mixer_reset(ess); /* DSP I/O handler is activated in sb_dsp_setaddr */ io_sethandler(addr, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(addr + 8, 0x0002, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(addr + 8, 0x0002, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(0x0388, 0x0004, ess->opl.read, NULL, NULL, ess->opl.write, NULL, NULL, ess->opl.priv); io_sethandler(0x0388, 0x0004, ess_fm_midi_read, NULL, NULL, ess_fm_midi_write, NULL, NULL, ess); io_sethandler(addr + 2, 0x0004, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(addr + 6, 0x0001, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); io_sethandler(addr + 0x0a, 0x0006, ess_base_read, NULL, NULL, ess_base_write, NULL, NULL, ess); ess->mixer_enabled = 1; ess->mixer_ess.regs[0x40] = 0x0a; io_sethandler(addr + 4, 0x0002, ess_mixer_read, NULL, NULL, ess_mixer_write, NULL, NULL, ess); sound_add_handler(sb_get_buffer_ess, ess); music_add_handler(sb_get_music_buffer_ess, ess); sound_set_cd_audio_filter(ess_filter_cd_audio, ess); if (info->local && device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(ess_filter_pc_speaker, ess); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &ess->dsp); if (info->local) { ess->mixer_ess.ess_id_str[0] = 0x16; ess->mixer_ess.ess_id_str[1] = 0x88; ess->mixer_ess.ess_id_str[2] = (addr >> 8) & 0xff; ess->mixer_ess.ess_id_str[3] = addr & 0xff; ess->mpu = (mpu_t *) calloc(1, sizeof(mpu_t)); /* NOTE: The MPU is initialized disabled and with no IRQ assigned. * It will be later initialized by the guest OS's drivers. */ mpu401_init(ess->mpu, 0, -1, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&ess->dsp, ess->mpu); } ess->gameport = gameport_add(&gameport_pnp_device); ess->gameport_addr = 0x200; gameport_remap(ess->gameport, ess->gameport_addr); if (ide_base > 0x0000) { device_add(&ide_qua_pnp_device); ide_set_base(4, ide_base); ide_set_side(4, ide_side); ide_set_irq(4, ide_irq); other_ide_present++; } return ess; } static int ess_688_pnp_available(void) { return rom_present(PNP_ROM_ESS0100); } static int ess_1688_pnp_available(void) { return rom_present(PNP_ROM_ESS0102); } static int ess_1688_968_pnp_available(void) { return rom_present(PNP_ROM_ESS0968); } static void * ess_x688_pnp_init(UNUSED(const device_t *info)) { sb_t *ess = calloc(sizeof(sb_t), 1); int len = 512; ess->pnp = 1 + (int) info->local; fm_driver_get(info->local ? FM_ESFM : FM_YMF262, &ess->opl); sb_dsp_set_real_opl(&ess->dsp, 1); sb_dsp_init(&ess->dsp, SBPRO2, info->local ? SB_SUBTYPE_ESS_ES1688 : SB_SUBTYPE_ESS_ES688, ess); sb_dsp_setdma16_supported(&ess->dsp, 0); ess_mixer_reset(ess); ess->mixer_enabled = 1; sound_add_handler(sb_get_buffer_ess, ess); music_add_handler(sb_get_music_buffer_ess, ess); sound_set_cd_audio_filter(ess_filter_cd_audio, ess); if (info->local && device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(ess_filter_pc_speaker, ess); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &ess->dsp); /* Not on ES688. */ ess->mixer_ess.ess_id_str[0] = 0x16; ess->mixer_ess.ess_id_str[1] = 0x88; ess->mixer_ess.ess_id_str[2] = 0x00; ess->mixer_ess.ess_id_str[3] = 0x00; ess->mpu = (mpu_t *) calloc(1, sizeof(mpu_t)); /* NOTE: The MPU is initialized disabled and with no IRQ assigned. * It will be later initialized by the guest OS's drivers. */ mpu401_init(ess->mpu, 0, -1, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&ess->dsp, ess->mpu); ess->gameport = gameport_add(&gameport_pnp_device); device_add(&ide_qua_pnp_device); other_ide_present++; const char *pnp_rom_file = NULL; switch (info->local) { case 0: pnp_rom_file = PNP_ROM_ESS0100; len = 145; break; case 1: pnp_rom_file = PNP_ROM_ESS0102; len = 145; break; case 2: pnp_rom_file = PNP_ROM_ESS0968; len = 135; break; default: break; } uint8_t *pnp_rom = NULL; if (pnp_rom_file) { FILE *fp = rom_fopen(pnp_rom_file, "rb"); if (fp) { if (fread(ess->pnp_rom, 1, len, fp) == len) pnp_rom = ess->pnp_rom; fclose(fp); } } isapnp_add_card(pnp_rom, len, ess_x688_pnp_config_changed, NULL, NULL, NULL, ess); sb_dsp_setaddr(&ess->dsp, 0); sb_dsp_setirq(&ess->dsp, 0); sb_dsp_setdma8(&ess->dsp, ISAPNP_DMA_DISABLED); sb_dsp_setdma16_8(&ess->dsp, ISAPNP_DMA_DISABLED); mpu401_change_addr(ess->mpu, 0); ess->gameport_addr = 0; gameport_remap(ess->gameport, 0); ide_remove_handlers(3); return ess; } static void * ess_x688_mca_init(UNUSED(const device_t *info)) { sb_t *ess = calloc(1, sizeof(sb_t)); ess->opl_enabled = 1; fm_driver_get(info->local ? FM_ESFM : FM_YMF262, &ess->opl); sb_dsp_set_real_opl(&ess->dsp, 1); sb_dsp_init(&ess->dsp, SBPRO2, info->local ? SB_SUBTYPE_ESS_ES1688 : SB_SUBTYPE_ESS_ES688, ess); sb_dsp_setdma16_supported(&ess->dsp, 0); ess_mixer_reset(ess); ess->mixer_enabled = 1; sound_add_handler(sb_get_buffer_ess, ess); music_add_handler(sb_get_music_buffer_ess, ess); sound_set_cd_audio_filter(ess_filter_cd_audio, ess); if (info->local && device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(ess_filter_pc_speaker, ess); if (info->local) { ess->mpu = (mpu_t *) calloc(1, sizeof(mpu_t)); mpu401_init(ess->mpu, 0, -1, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&ess->dsp, ess->mpu); } ess->gameport = gameport_add(&gameport_device); mpu401_change_addr(ess->mpu, 0); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &ess->dsp); ess->gameport_addr = 0; gameport_remap(ess->gameport, 0); /* I/O handlers activated in sb_pro_mcv_write */ if (info->local == 2) { mca_add(ess_x688_mca_read, ess_chipchat_mca_write, sb_mcv_feedb, NULL, ess); ess->pos_regs[0] = 0x50; ess->pos_regs[1] = 0x51; } else { mca_add(ess_x688_mca_read, ess_soundpiper_mca_write, sb_mcv_feedb, NULL, ess); ess->pos_regs[0] = 0x30; ess->pos_regs[1] = 0x51; } return ess; } void sb_close(void *priv) { sb_t *sb = (sb_t *) priv; sb_dsp_close(&sb->dsp); free(sb); } static void sb_awe32_close(void *priv) { sb_t *sb = (sb_t *) priv; emu8k_close(&sb->emu8k); sb_close(sb); } void sb_speed_changed(void *priv) { sb_t *sb = (sb_t *) priv; sb_dsp_speed_changed(&sb->dsp); } // clang-format off static const device_config_t sb_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x210", .value = 0x210 }, { .description = "0x220", .value = 0x220 }, { .description = "0x230", .value = 0x230 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "0x260", .value = 0x260 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 7, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 3", .value = 3 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb15_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x210", .value = 0x210 }, { .description = "0x220", .value = 0x220 }, { .description = "0x230", .value = 0x230 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "0x260", .value = 0x260 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 7, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 3", .value = 3 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "cms", .description = "Enable CMS", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb2_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "0x260", .value = 0x260 }, { .description = "" } } }, { .name = "mixaddr", .description = "Mixer", .type = CONFIG_HEX16, .default_string = "", .default_int = 0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "Disabled", .value = 0 }, { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "0x260", .value = 0x260 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 3", .value = 3 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "cms", .description = "Enable CMS", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_mcv_config[] = { { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 7, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 3", .value = 3 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_pro_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 7, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "IRQ 10", .value = 10 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_pro_mcv_config[] = { { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_16_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "0x260", .value = 0x260 }, { .description = "0x280", .value = 0x280 }, { .description = "" } } }, { .name = "base401", .description = "MPU-401 Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x330, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "Disabled", .value = 0 }, { .description = "0x300", .value = 0x300 }, { .description = "0x330", .value = 0x330 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "IRQ 10", .value = 10 }, { .description = "" } } }, { .name = "dma", .description = "Low DMA channel", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "dma16", .description = "High DMA channel", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 5", .value = 5 }, { .description = "DMA 6", .value = 6 }, { .description = "DMA 7", .value = 7 }, { .description = "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_16_pnp_config[] = { { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_32_pnp_config[] = { { .name = "onboard_ram", .description = "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "None", .value = 0 }, { .description = "512 KB", .value = 512 }, { .description = "2 MB", .value = 2048 }, { .description = "8 MB", .value = 8192 }, { .description = "28 MB", .value = 28672 }, { .description = "" } } }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_awe32_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "0x260", .value = 0x260 }, { .description = "0x280", .value = 0x280 }, { .description = "" } } }, { .name = "emu_base", .description = "EMU8000 Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x620, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x620", .value = 0x620 }, { .description = "0x640", .value = 0x640 }, { .description = "0x660", .value = 0x660 }, { .description = "0x680", .value = 0x680 }, { .description = ""} } }, { .name = "base401", .description = "MPU-401 Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x330, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "Disabled", .value = 0 }, { .description = "0x300", .value = 0x300 }, { .description = "0x330", .value = 0x330 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "IRQ 10", .value = 10 }, { .description = "" } } }, { .name = "dma", .description = "Low DMA channel", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "dma16", .description = "High DMA channel", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 5", .value = 5 }, { .description = "DMA 6", .value = 6 }, { .description = "DMA 7", .value = 7 }, { .description = "" } } }, { .name = "onboard_ram", .description = "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 512, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "None", .value = 0 }, { .description = "512 KB", .value = 512 }, { .description = "2 MB", .value = 2048 }, { .description = "8 MB", .value = 8192 }, { .description = "28 MB", .value = 28672 }, { "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_awe32_pnp_config[] = { { .name = "onboard_ram", .description = "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 512, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "None", .value = 0 }, { .description = "512 KB", .value = 512 }, { .description = "2 MB", .value = 2048 }, { .description = "8 MB", .value = 8192 }, { .description = "28 MB", .value = 28672 }, { .description = "" } } }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_awe64_value_config[] = { { .name = "onboard_ram", .description = "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 512, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "512 KB", .value = 512 }, { .description = "1 MB", .value = 1024 }, { .description = "2 MB", .value = 2048 }, { .description = "4 MB", .value = 4096 }, { .description = "8 MB", .value = 8192 }, { .description = "12 MB", .value = 12288 }, { .description = "16 MB", .value = 16384 }, { .description = "20 MB", .value = 20480 }, { .description = "24 MB", .value = 24576 }, { .description = "28 MB", .value = 28672 }, { .description = "" } } }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_awe64_config[] = { { .name = "onboard_ram", .description = "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1024, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "1 MB", .value = 1024 }, { .description = "2 MB", .value = 2048 }, { .description = "4 MB", .value = 4096 }, { .description = "8 MB", .value = 8192 }, { .description = "12 MB", .value = 12288 }, { .description = "16 MB", .value = 16384 }, { .description = "20 MB", .value = 20480 }, { .description = "24 MB", .value = 24576 }, { .description = "28 MB", .value = 28672 }, { .description = "" } } }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t sb_awe64_gold_config[] = { { .name = "onboard_ram", .description = "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 4096, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "4 MB", .value = 4096 }, { .description = "8 MB", .value = 8192 }, { .description = "12 MB", .value = 12288 }, { .description = "16 MB", .value = 16384 }, { .description = "20 MB", .value = 20480 }, { .description = "24 MB", .value = 24576 }, { .description = "28 MB", .value = 28672 }, { .description = "" } } }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; static const device_config_t ess_688_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x230", .value = 0x230 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "IRQ 10", .value = 10 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "ide_ctrl", .description = "IDE Controller", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x0000, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "Disabled", .value = 0x0000 }, { .description = "0x170, IRQ 15", .value = 0xf170 }, { .description = "0x1E8, IRQ 11", .value = 0xb1e8 }, { .description = "0x168, IRQ 9", .value = 0x9168 }, { .description = "0x168, IRQ 10", .value = 0xa168 }, { .description = "" } } }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; // clang-format on static const device_config_t ess_1688_config[] = { { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x230", .value = 0x230 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "" } } }, { .name = "irq", .description = "IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 5, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 7", .value = 7 }, { .description = "IRQ 10", .value = 10 }, { .description = "" } } }, { .name = "dma", .description = "DMA", .type = CONFIG_SELECTION, .default_string = "", .default_int = 1, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } } }, { .name = "ide_ctrl", .description = "IDE Controller", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x0000, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "Disabled", .value = 0x0000 }, { .description = "0x170, IRQ 15", .value = 0xf170 }, { .description = "0x1E8, IRQ 11", .value = 0xb1e8 }, { .description = "0x168, IRQ 9", .value = 0x9168 }, { .description = "0x168, IRQ 10", .value = 0xa168 }, { .description = "" } } }, { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; // clang-format on static const device_config_t ess_688_pnp_config[] = { { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; // clang-format on static const device_config_t ess_1688_pnp_config[] = { { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (DSP MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } }; // clang-format on const device_t sb_1_device = { .name = "Sound Blaster v1.0", .internal_name = "sb", .flags = DEVICE_ISA, .local = 0, .init = sb_1_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_config }; const device_t sb_15_device = { .name = "Sound Blaster v1.5", .internal_name = "sb1.5", .flags = DEVICE_ISA, .local = 0, .init = sb_15_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb15_config }; const device_t sb_mcv_device = { .name = "Sound Blaster MCV", .internal_name = "sbmcv", .flags = DEVICE_MCA, .local = 0, .init = sb_mcv_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_mcv_config }; const device_t sb_2_device = { .name = "Sound Blaster v2.0", .internal_name = "sb2.0", .flags = DEVICE_ISA, .local = 0, .init = sb_2_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb2_config }; const device_t sb_pro_v1_device = { .name = "Sound Blaster Pro v1", .internal_name = "sbprov1", .flags = DEVICE_ISA, .local = 0, .init = sb_pro_v1_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_pro_config }; const device_t sb_pro_v2_device = { .name = "Sound Blaster Pro v2", .internal_name = "sbprov2", .flags = DEVICE_ISA, .local = 0, .init = sb_pro_v2_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_pro_config }; const device_t sb_pro_mcv_device = { .name = "Sound Blaster Pro MCV", .internal_name = "sbpromcv", .flags = DEVICE_MCA, .local = 0, .init = sb_pro_mcv_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_pro_mcv_config }; const device_t sb_pro_compat_device = { .name = "Sound Blaster Pro (Compatibility)", .internal_name = "sbpro_compat", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = sb_pro_compat_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t sb_16_device = { .name = "Sound Blaster 16", .internal_name = "sb16", .flags = DEVICE_ISA | DEVICE_AT, .local = FM_YMF262, .init = sb_16_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_config }; const device_t sb_vibra16s_onboard_device = { .name = "Sound Blaster ViBRA 16S (On-Board)", .internal_name = "sb_vibra16s_onboard", .flags = DEVICE_ISA | DEVICE_AT, .local = FM_YMF289B, .init = sb_16_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_config }; const device_t sb_vibra16s_device = { .name = "Sound Blaster ViBRA 16S", .internal_name = "sb_vibra16s", .flags = DEVICE_ISA | DEVICE_AT, .local = FM_YMF289B, .init = sb_16_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_config }; const device_t sb_vibra16xv_device = { .name = "Sound Blaster ViBRA 16XV", .internal_name = "sb_vibra16xv", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = sb_vibra16_pnp_init, .close = sb_close, .reset = NULL, { .available = sb_vibra16xv_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_pnp_config }; const device_t sb_vibra16c_onboard_device = { .name = "Sound Blaster ViBRA 16C (On-Board)", .internal_name = "sb_vibra16c_onboard", .flags = DEVICE_ISA | DEVICE_AT, .local = 1, .init = sb_vibra16_pnp_init, .close = sb_close, .reset = NULL, { .available = sb_vibra16c_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_pnp_config }; const device_t sb_vibra16c_device = { .name = "Sound Blaster ViBRA 16C", .internal_name = "sb_vibra16c", .flags = DEVICE_ISA | DEVICE_AT, .local = 1, .init = sb_vibra16_pnp_init, .close = sb_close, .reset = NULL, { .available = sb_vibra16c_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_pnp_config }; const device_t sb_16_reply_mca_device = { .name = "Sound Blaster 16 Reply MCA", .internal_name = "sb16_reply_mca", .flags = DEVICE_MCA, .local = 0, .init = sb_16_reply_mca_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_pnp_config }; const device_t sb_16_pnp_device = { .name = "Sound Blaster 16 PnP", .internal_name = "sb16_pnp", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = sb_16_pnp_init, .close = sb_close, .reset = NULL, { .available = sb_16_pnp_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_16_pnp_config }; const device_t sb_16_compat_device = { .name = "Sound Blaster 16 (Compatibility)", .internal_name = "sb16_compat", .flags = DEVICE_ISA | DEVICE_AT, .local = 1, .init = sb_16_compat_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t sb_16_compat_nompu_device = { .name = "Sound Blaster 16 (Compatibility - MPU-401 Off)", .internal_name = "sb16_compat", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = sb_16_compat_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t sb_32_pnp_device = { .name = "Sound Blaster 32 PnP", .internal_name = "sb32_pnp", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = sb_awe32_pnp_init, .close = sb_awe32_close, .reset = NULL, { .available = sb_32_pnp_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_32_pnp_config }; const device_t sb_awe32_device = { .name = "Sound Blaster AWE32", .internal_name = "sbawe32", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = sb_awe32_init, .close = sb_awe32_close, .reset = NULL, { .available = sb_awe32_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_awe32_config }; const device_t sb_awe32_pnp_device = { .name = "Sound Blaster AWE32 PnP", .internal_name = "sbawe32_pnp", .flags = DEVICE_ISA | DEVICE_AT, .local = 1, .init = sb_awe32_pnp_init, .close = sb_awe32_close, .reset = NULL, { .available = sb_awe32_pnp_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_awe32_pnp_config }; const device_t sb_awe64_value_device = { .name = "Sound Blaster AWE64 Value", .internal_name = "sbawe64_value", .flags = DEVICE_ISA | DEVICE_AT, .local = 2, .init = sb_awe32_pnp_init, .close = sb_awe32_close, .reset = NULL, { .available = sb_awe64_value_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_awe64_value_config }; const device_t sb_awe64_device = { .name = "Sound Blaster AWE64", .internal_name = "sbawe64", .flags = DEVICE_ISA | DEVICE_AT, .local = 3, .init = sb_awe32_pnp_init, .close = sb_awe32_close, .reset = NULL, { .available = sb_awe64_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_awe64_config }; const device_t sb_awe64_gold_device = { .name = "Sound Blaster AWE64 Gold", .internal_name = "sbawe64_gold", .flags = DEVICE_ISA | DEVICE_AT, .local = 4, .init = sb_awe32_pnp_init, .close = sb_awe32_close, .reset = NULL, { .available = sb_awe64_gold_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = sb_awe64_gold_config }; const device_t ess_688_device = { .name = "ESS AudioDrive ES688", .internal_name = "ess_es688", .flags = DEVICE_ISA, .local = 0, .init = ess_x688_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_688_config }; const device_t ess_ess0100_pnp_device = { .name = "ESS AudioDrive ES688 (ESS0100) PnP", .internal_name = "ess_ess0100_pnp", .flags = DEVICE_ISA, .local = 0, .init = ess_x688_pnp_init, .close = sb_close, .reset = NULL, { .available = ess_688_pnp_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_688_pnp_config }; const device_t ess_1688_device = { .name = "ESS AudioDrive ES1688", .internal_name = "ess_es1688", .flags = DEVICE_ISA, .local = 1, .init = ess_x688_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_1688_config }; const device_t ess_ess0102_pnp_device = { .name = "ESS AudioDrive ES1688 (ESS0102) PnP", .internal_name = "ess_ess0102_pnp", .flags = DEVICE_ISA, .local = 1, .init = ess_x688_pnp_init, .close = sb_close, .reset = NULL, { .available = ess_1688_pnp_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_1688_pnp_config }; const device_t ess_ess0968_pnp_device = { .name = "ESS AudioDrive ES1688 (ESS0968) PnP", .internal_name = "ess_ess0968_pnp", .flags = DEVICE_ISA, .local = 2, .init = ess_x688_pnp_init, .close = sb_close, .reset = NULL, { .available = ess_1688_968_pnp_available }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_1688_pnp_config }; const device_t ess_soundpiper_16_mca_device = { .name = "SoundPiper 16 (ESS AudioDrive ES688) MCA", .internal_name = "soundpiper_16_mca", .flags = DEVICE_MCA, .local = 0, .init = ess_x688_mca_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_688_pnp_config }; const device_t ess_soundpiper_32_mca_device = { .name = "SoundPiper 32 (ESS AudioDrive ES1688) MCA", .internal_name = "soundpiper_32_mca", .flags = DEVICE_MCA, .local = 1, .init = ess_x688_mca_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_1688_pnp_config }; const device_t ess_chipchat_16_mca_device = { .name = "ChipChat 16 (ESS AudioDrive ES1688) MCA", .internal_name = "chipchat_16_mca", .flags = DEVICE_MCA, .local = 2, .init = ess_x688_mca_init, .close = sb_close, .reset = NULL, { .available = NULL }, .speed_changed = sb_speed_changed, .force_redraw = NULL, .config = ess_1688_pnp_config }; ```
/content/code_sandbox/src/sound/snd_sb.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
53,137
```c #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/snd_cms.h> #include <86box/sound.h> #include <86box/plat_unused.h> void cms_update(cms_t *cms) { for (; cms->pos < sound_pos_global; cms->pos++) { int16_t out_l = 0; int16_t out_r = 0; for (uint8_t c = 0; c < 4; c++) { switch (cms->noisetype[c >> 1][c & 1]) { case 0: cms->noisefreq[c >> 1][c & 1] = MASTER_CLOCK / 256; break; case 1: cms->noisefreq[c >> 1][c & 1] = MASTER_CLOCK / 512; break; case 2: cms->noisefreq[c >> 1][c & 1] = MASTER_CLOCK / 1024; break; case 3: cms->noisefreq[c >> 1][c & 1] = cms->freq[c >> 1][(c & 1) * 3]; break; default: break; } } for (uint8_t c = 0; c < 2; c++) { if (cms->regs[c][0x1C] & 1) { for (uint8_t d = 0; d < 6; d++) { if (cms->regs[c][0x14] & (1 << d)) { if (cms->stat[c][d]) out_l += (cms->vol[c][d][0] * 90); if (cms->stat[c][d]) out_r += (cms->vol[c][d][1] * 90); cms->count[c][d] += cms->freq[c][d]; if (cms->count[c][d] >= 24000) { cms->count[c][d] -= 24000; cms->stat[c][d] ^= 1; } } else if (cms->regs[c][0x15] & (1 << d)) { if (cms->noise[c][d / 3] & 1) out_l += (cms->vol[c][d][0] * 90); if (cms->noise[c][d / 3] & 1) out_r += (cms->vol[c][d][0] * 90); } } for (uint8_t d = 0; d < 2; d++) { cms->noisecount[c][d] += cms->noisefreq[c][d]; while (cms->noisecount[c][d] >= 24000) { cms->noisecount[c][d] -= 24000; cms->noise[c][d] <<= 1; if (!(((cms->noise[c][d] & 0x4000) >> 8) ^ (cms->noise[c][d] & 0x40))) cms->noise[c][d] |= 1; } } } } cms->buffer[cms->pos << 1] = out_l; cms->buffer[(cms->pos << 1) + 1] = out_r; } } void cms_get_buffer(int32_t *buffer, int len, void *priv) { cms_t *cms = (cms_t *) priv; cms_update(cms); for (int c = 0; c < len * 2; c++) buffer[c] += cms->buffer[c]; cms->pos = 0; } void cms_write(uint16_t addr, uint8_t val, void *priv) { cms_t *cms = (cms_t *) priv; int voice; int chip = (addr & 2) >> 1; switch (addr & 0xf) { case 1: cms->addrs[0] = val & 31; break; case 3: cms->addrs[1] = val & 31; break; case 0: case 2: cms_update(cms); cms->regs[chip][cms->addrs[chip] & 31] = val; switch (cms->addrs[chip] & 31) { case 0x00: case 0x01: case 0x02: /*Volume*/ case 0x03: case 0x04: case 0x05: voice = cms->addrs[chip] & 7; cms->vol[chip][voice][0] = val & 0xf; cms->vol[chip][voice][1] = val >> 4; break; case 0x08: case 0x09: case 0x0A: /*Frequency*/ case 0x0B: case 0x0C: case 0x0D: voice = cms->addrs[chip] & 7; cms->latch[chip][voice] = (cms->latch[chip][voice] & 0x700) | val; cms->freq[chip][voice] = (MASTER_CLOCK / 512 << (cms->latch[chip][voice] >> 8)) / (511 - (cms->latch[chip][voice] & 255)); break; case 0x10: case 0x11: case 0x12: /*Octave*/ voice = (cms->addrs[chip] & 3) << 1; cms->latch[chip][voice] = (cms->latch[chip][voice] & 0xFF) | ((val & 7) << 8); cms->latch[chip][voice + 1] = (cms->latch[chip][voice + 1] & 0xFF) | ((val & 0x70) << 4); cms->freq[chip][voice] = (MASTER_CLOCK / 512 << (cms->latch[chip][voice] >> 8)) / (511 - (cms->latch[chip][voice] & 255)); cms->freq[chip][voice + 1] = (MASTER_CLOCK / 512 << (cms->latch[chip][voice + 1] >> 8)) / (511 - (cms->latch[chip][voice + 1] & 255)); break; case 0x16: /*Noise*/ cms->noisetype[chip][0] = val & 3; cms->noisetype[chip][1] = (val >> 4) & 3; break; default: break; } break; case 0x6: case 0x7: cms->latched_data = val; break; default: break; } } uint8_t cms_read(uint16_t addr, void *priv) { const cms_t *cms = (cms_t *) priv; switch (addr & 0xf) { case 0x1: return cms->addrs[0]; case 0x3: return cms->addrs[1]; case 0x4: return 0x7f; case 0xa: case 0xb: return cms->latched_data; default: break; } return 0xff; } void * cms_init(UNUSED(const device_t *info)) { cms_t *cms = malloc(sizeof(cms_t)); memset(cms, 0, sizeof(cms_t)); uint16_t addr = device_get_config_hex16("base"); io_sethandler(addr, 0x0010, cms_read, NULL, NULL, cms_write, NULL, NULL, cms); sound_add_handler(cms_get_buffer, cms); return cms; } void cms_close(void *priv) { cms_t *cms = (cms_t *) priv; free(cms); } static const device_config_t cms_config[] = { // clang-format off { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x210", .value = 0x210 }, { .description = "0x220", .value = 0x220 }, { .description = "0x230", .value = 0x230 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "0x260", .value = 0x260 }, { .description = "" } } }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t cms_device = { .name = "Creative Music System / Game Blaster", .internal_name = "cms", .flags = DEVICE_ISA, .local = 0, .init = cms_init, .close = cms_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = cms_config }; ```
/content/code_sandbox/src/sound/snd_cms.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,195
```c /* some code borrowed from scummvm */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #ifdef __unix__ # include <unistd.h> #endif #include <fluidsynth.h> #include <86box/86box.h> #include <86box/config.h> #include <86box/device.h> #include <86box/midi.h> #include <86box/thread.h> #include <86box/sound.h> #include <86box/plat_unused.h> #define RENDER_RATE 100 #define BUFFER_SEGMENTS 10 /* Check the FluidSynth version to determine wheteher to use the older reverb/chorus control functions that were deprecated in 2.2.0, or their newer replacements */ #if (FLUIDSYNTH_VERSION_MAJOR < 2) || ((FLUIDSYNTH_VERSION_MAJOR == 2) && (FLUIDSYNTH_VERSION_MINOR < 2)) # define USE_OLD_FLUIDSYNTH_API #endif extern void givealbuffer_midi(void *buf, uint32_t size); extern void al_set_midi(int freq, int buf_size); typedef struct fluidsynth { fluid_settings_t *settings; fluid_synth_t *synth; int samplerate; int sound_font; thread_t *thread_h; event_t *event, *start_event; int buf_size; float *buffer; int16_t *buffer_int16; int midi_pos; int on; } fluidsynth_t; fluidsynth_t fsdev; int fluidsynth_available(void) { return 1; } void fluidsynth_poll(void) { fluidsynth_t *data = &fsdev; data->midi_pos++; if (data->midi_pos == SOUND_FREQ / RENDER_RATE) { data->midi_pos = 0; thread_set_event(data->event); } } static void fluidsynth_thread(void *param) { fluidsynth_t *data = (fluidsynth_t *) param; int buf_pos = 0; int buf_size = data->buf_size / BUFFER_SEGMENTS; thread_set_event(data->start_event); while (data->on) { thread_wait_event(data->event, -1); thread_reset_event(data->event); if (sound_is_float) { float *buf = (float *) ((uint8_t *) data->buffer + buf_pos); memset(buf, 0, buf_size); if (data->synth) fluid_synth_write_float(data->synth, buf_size / (2 * sizeof(float)), buf, 0, 2, buf, 1, 2); buf_pos += buf_size; if (buf_pos >= data->buf_size) { givealbuffer_midi(data->buffer, data->buf_size / sizeof(float)); buf_pos = 0; } } else { int16_t *buf = (int16_t *) ((uint8_t *) data->buffer_int16 + buf_pos); memset(buf, 0, buf_size); if (data->synth) fluid_synth_write_s16(data->synth, buf_size / (2 * sizeof(int16_t)), buf, 0, 2, buf, 1, 2); buf_pos += buf_size; if (buf_pos >= data->buf_size) { givealbuffer_midi(data->buffer_int16, data->buf_size / sizeof(int16_t)); buf_pos = 0; } } } } void fluidsynth_msg(uint8_t *msg) { fluidsynth_t *data = &fsdev; uint32_t val = *((uint32_t *) msg); uint32_t param2 = (uint8_t) ((val >> 16) & 0xFF); uint32_t param1 = (uint8_t) ((val >> 8) & 0xFF); uint8_t cmd = (uint8_t) (val & 0xF0); uint8_t chan = (uint8_t) (val & 0x0F); switch (cmd) { case 0x80: /* Note Off */ fluid_synth_noteoff(data->synth, chan, param1); break; case 0x90: /* Note On */ fluid_synth_noteon(data->synth, chan, param1, param2); break; case 0xA0: /* Aftertouch */ break; case 0xB0: /* Control Change */ fluid_synth_cc(data->synth, chan, param1, param2); break; case 0xC0: /* Program Change */ fluid_synth_program_change(data->synth, chan, param1); break; case 0xD0: /* Channel Pressure */ fluid_synth_channel_pressure(data->synth, chan, param1); break; case 0xE0: /* Pitch Bend */ fluid_synth_pitch_bend(data->synth, chan, (param2 << 7) | param1); break; case 0xF0: /* SysEx */ break; default: break; } } void fluidsynth_sysex(uint8_t *data, unsigned int len) { fluidsynth_t *d = &fsdev; fluid_synth_sysex(d->synth, (const char *) data, len, 0, 0, 0, 0); } void * fluidsynth_init(UNUSED(const device_t *info)) { fluidsynth_t *data = &fsdev; midi_device_t *dev; memset(data, 0, sizeof(fluidsynth_t)); data->settings = new_fluid_settings(); fluid_settings_setnum(data->settings, "synth.sample-rate", 44100); fluid_settings_setnum(data->settings, "synth.gain", device_get_config_int("output_gain") / 100.0f); data->synth = new_fluid_synth(data->settings); const char *sound_font = device_get_config_string("sound_font"); #ifdef __unix__ if (!sound_font || sound_font[0] == 0) sound_font = (access("/usr/share/sounds/sf2/FluidR3_GM.sf2", F_OK) == 0 ? "/usr/share/sounds/sf2/FluidR3_GM.sf2" : (access("/usr/share/soundfonts/default.sf2", F_OK) == 0 ? "/usr/share/soundfonts/default.sf2" : "")); #endif data->sound_font = fluid_synth_sfload(data->synth, sound_font, 1); if (device_get_config_int("chorus")) { #ifndef USE_OLD_FLUIDSYNTH_API fluid_synth_chorus_on(data->synth, -1, 1); #else fluid_synth_set_chorus_on(data->synth, 1); #endif int chorus_voices = device_get_config_int("chorus_voices"); double chorus_level = device_get_config_int("chorus_level") / 100.0; double chorus_speed = device_get_config_int("chorus_speed") / 100.0; double chorus_depth = device_get_config_int("chorus_depth") / 10.0; int chorus_waveform = FLUID_CHORUS_MOD_SINE; if (device_get_config_int("chorus_waveform") == 0) chorus_waveform = FLUID_CHORUS_MOD_SINE; else chorus_waveform = FLUID_CHORUS_MOD_TRIANGLE; #ifndef USE_OLD_FLUIDSYNTH_API fluid_synth_set_chorus_group_nr(data->synth, -1, chorus_voices); fluid_synth_set_chorus_group_level(data->synth, -1, chorus_level); fluid_synth_set_chorus_group_speed(data->synth, -1, chorus_speed); fluid_synth_set_chorus_group_depth(data->synth, -1, chorus_depth); fluid_synth_set_chorus_group_type(data->synth, -1, chorus_waveform); #else fluid_synth_set_chorus(data->synth, chorus_voices, chorus_level, chorus_speed, chorus_depth, chorus_waveform); #endif } else #ifndef USE_OLD_FLUIDSYNTH_API fluid_synth_chorus_on(data->synth, -1, 0); #else fluid_synth_set_chorus_on(data->synth, 0); #endif if (device_get_config_int("reverb")) { #ifndef USE_OLD_FLUIDSYNTH_API fluid_synth_reverb_on(data->synth, -1, 1); #else fluid_synth_set_reverb_on(data->synth, 1); #endif double reverb_room_size = device_get_config_int("reverb_room_size") / 100.0; double reverb_damping = device_get_config_int("reverb_damping") / 100.0; double reverb_width = device_get_config_int("reverb_width") / 10.0; double reverb_level = device_get_config_int("reverb_level") / 100.0; #ifndef USE_OLD_FLUIDSYNTH_API fluid_synth_set_reverb_group_roomsize(data->synth, -1, reverb_room_size); fluid_synth_set_reverb_group_damp(data->synth, -1, reverb_damping); fluid_synth_set_reverb_group_width(data->synth, -1, reverb_width); fluid_synth_set_reverb_group_level(data->synth, -1, reverb_level); #else fluid_synth_set_reverb(data->synth, reverb_room_size, reverb_damping, reverb_width, reverb_level); #endif } else #ifndef USE_OLD_FLUIDSYNTH_API fluid_synth_reverb_on(data->synth, -1, 0); #else fluid_synth_set_reverb_on(data->synth, 0); #endif int interpolation = device_get_config_int("interpolation"); int fs_interpolation = FLUID_INTERP_4THORDER; if (interpolation == 0) fs_interpolation = FLUID_INTERP_NONE; else if (interpolation == 1) fs_interpolation = FLUID_INTERP_LINEAR; else if (interpolation == 2) fs_interpolation = FLUID_INTERP_4THORDER; else if (interpolation == 3) fs_interpolation = FLUID_INTERP_7THORDER; fluid_synth_set_interp_method(data->synth, -1, fs_interpolation); double samplerate; fluid_settings_getnum(data->settings, "synth.sample-rate", &samplerate); data->samplerate = (int) samplerate; if (sound_is_float) { data->buf_size = (data->samplerate / RENDER_RATE) * 2 * sizeof(float) * BUFFER_SEGMENTS; data->buffer = malloc(data->buf_size); data->buffer_int16 = NULL; } else { data->buf_size = (data->samplerate / RENDER_RATE) * 2 * sizeof(int16_t) * BUFFER_SEGMENTS; data->buffer = NULL; data->buffer_int16 = malloc(data->buf_size); } al_set_midi(data->samplerate, data->buf_size); dev = malloc(sizeof(midi_device_t)); memset(dev, 0, sizeof(midi_device_t)); dev->play_msg = fluidsynth_msg; dev->play_sysex = fluidsynth_sysex; dev->poll = fluidsynth_poll; midi_out_init(dev); data->on = 1; data->start_event = thread_create_event(); data->event = thread_create_event(); data->thread_h = thread_create(fluidsynth_thread, data); thread_wait_event(data->start_event, -1); thread_reset_event(data->start_event); return dev; } void fluidsynth_close(void *priv) { if (!priv) return; fluidsynth_t *data = &fsdev; data->on = 0; thread_set_event(data->event); thread_wait(data->thread_h); if (data->synth) { delete_fluid_synth(data->synth); data->synth = NULL; } if (data->settings) { delete_fluid_settings(data->settings); data->settings = NULL; } if (data->buffer) { free(data->buffer); data->buffer = NULL; } if (data->buffer_int16) { free(data->buffer_int16); data->buffer_int16 = NULL; } } static const device_config_t fluidsynth_config[] = { // clang-format off { .name = "sound_font", .description = "Sound Font", .type = CONFIG_FNAME, .default_string = "", .file_filter = "SF2 Sound Fonts (*.sf2)|*.sf2" }, { .name = "output_gain", .description = "Output Gain", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 100 }, { .name = "chorus", .description = "Chorus", .type = CONFIG_BINARY, .default_int = 1 }, { .name = "chorus_voices", .description = "Chorus Voices", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 99 }, .default_int = 3 }, { .name = "chorus_level", .description = "Chorus Level", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 20 }, { .name = "chorus_speed", .description = "Chorus Speed", .type = CONFIG_SPINNER, .spinner = { .min = 10, .max = 500 }, .default_int = 30 }, { .name = "chorus_depth", .description = "Chorus Depth", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 2560 }, .default_int = 80 }, { .name = "chorus_waveform", .description = "Chorus Waveform", .type = CONFIG_SELECTION, .selection = { { .description = "Sine", .value = 0 }, { .description = "Triangle", .value = 1 } }, .default_int = 0 }, { .name = "reverb", .description = "Reverb", .type = CONFIG_BINARY, .default_int = 1 }, { .name = "reverb_room_size", .description = "Reverb Room Size", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 20 }, { .name = "reverb_damping", .description = "Reverb Damping", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 0 }, { .name = "reverb_width", .description = "Reverb Width", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 1000 }, .default_int = 5 }, { .name = "reverb_level", .description = "Reverb Level", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 90 }, { .name = "interpolation", .description = "Interpolation Method", .type = CONFIG_SELECTION, .selection = { { .description = "None", .value = 0 }, { .description = "Linear", .value = 1 }, { .description = "4th Order", .value = 2 }, { .description = "7th Order", .value = 3 } }, .default_int = 2 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t fluidsynth_device = { .name = "FluidSynth", .internal_name = "fluidsynth", .flags = 0, .local = 0, .init = fluidsynth_init, .close = fluidsynth_close, .reset = NULL, { .available = fluidsynth_available }, .speed_changed = NULL, .force_redraw = NULL, .config = fluidsynth_config }; ```
/content/code_sandbox/src/sound/midi_fluidsynth.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,835
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Interface to the XAudio2 audio processing library. * * * * Authors: Cacodemon345 * */ #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #if defined(_WIN32) && !defined(USE_FAUDIO) # define COBJMACROS # include <xaudio2.h> #else # include <FAudio.h> # include <FAudio_compat.h> #endif #include <86box/86box.h> #include <86box/midi.h> #include <86box/plat_dynld.h> #include <86box/sound.h> #include <86box/plat_unused.h> #if defined(_WIN32) && !defined(USE_FAUDIO) static void *xaudio2_handle = NULL; static HRESULT(WINAPI *pXAudio2Create)(IXAudio2 **ppXAudio2, uint32_t Flags, XAUDIO2_PROCESSOR XAudio2Processor); static dllimp_t xaudio2_imports[] = { {"XAudio2Create", &pXAudio2Create}, { NULL, NULL }, }; # define XAudio2Create pXAudio2Create #endif static int midi_freq = FREQ_44100; static int midi_buf_size = 4410; static int initialized = 0; static IXAudio2 *xaudio2 = NULL; static IXAudio2MasteringVoice *mastervoice = NULL; static IXAudio2SourceVoice *srcvoice = NULL; static IXAudio2SourceVoice *srcvoicemusic = NULL; static IXAudio2SourceVoice *srcvoicewt = NULL; static IXAudio2SourceVoice *srcvoicemidi = NULL; static IXAudio2SourceVoice *srcvoicecd = NULL; #define FREQ SOUND_FREQ #define BUFLEN SOUNDBUFLEN static void WINAPI OnVoiceProcessingPassStart(UNUSED(IXAudio2VoiceCallback *callback), UNUSED(uint32_t bytesRequired)) { // } static void WINAPI OnVoiceProcessingPassEnd(UNUSED(IXAudio2VoiceCallback *callback)) { // } static void WINAPI OnStreamEnd(UNUSED(IXAudio2VoiceCallback *callback)) { // } static void WINAPI OnBufferStart(UNUSED(IXAudio2VoiceCallback *callback), UNUSED(void *pBufferContext)) { // } static void WINAPI OnLoopEnd(UNUSED(IXAudio2VoiceCallback *callback), UNUSED(void *pBufferContext)) { // } static void WINAPI OnVoiceError(UNUSED(IXAudio2VoiceCallback *callback), UNUSED(void *pBufferContext), UNUSED(HRESULT error)) { // } static void WINAPI OnBufferEnd(UNUSED(IXAudio2VoiceCallback *callback), UNUSED(void *pBufferContext)) { free(pBufferContext); } #if defined(_WIN32) && !defined(USE_FAUDIO) static IXAudio2VoiceCallbackVtbl callbacksVtbl = #else static FAudioVoiceCallback callbacks = #endif { .OnVoiceProcessingPassStart = OnVoiceProcessingPassStart, .OnVoiceProcessingPassEnd = OnVoiceProcessingPassEnd, .OnStreamEnd = OnStreamEnd, .OnBufferStart = OnBufferStart, .OnBufferEnd = OnBufferEnd, .OnLoopEnd = OnLoopEnd, .OnVoiceError = OnVoiceError }; #if defined(_WIN32) && !defined(USE_FAUDIO) static IXAudio2VoiceCallback callbacks = { &callbacksVtbl }; #endif void inital(void) { #if defined(_WIN32) && !defined(USE_FAUDIO) if (xaudio2_handle == NULL) { xaudio2_handle = dynld_module("xaudio2_9.dll", xaudio2_imports); } if (xaudio2_handle == NULL) { xaudio2_handle = dynld_module("xaudio2_9redist.dll", xaudio2_imports); } if (xaudio2_handle == NULL) { return; } #endif if (XAudio2Create(&xaudio2, 0, XAUDIO2_DEFAULT_PROCESSOR)) { return; } if (IXAudio2_CreateMasteringVoice(xaudio2, &mastervoice, 2, FREQ, 0, 0, NULL, 0)) { IXAudio2_Release(xaudio2); xaudio2 = NULL; return; } WAVEFORMATEX fmt; fmt.nChannels = 2; if (sound_is_float) { fmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; fmt.wBitsPerSample = 32; } else { fmt.wFormatTag = WAVE_FORMAT_PCM; fmt.wBitsPerSample = 16; } fmt.nSamplesPerSec = FREQ; fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; fmt.cbSize = 0; if (IXAudio2_CreateSourceVoice(xaudio2, &srcvoice, &fmt, 0, 2.0f, &callbacks, NULL, NULL)) { IXAudio2MasteringVoice_DestroyVoice(mastervoice); IXAudio2_Release(xaudio2); xaudio2 = NULL; mastervoice = NULL; return; } fmt.nSamplesPerSec = MUSIC_FREQ; fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; (void) IXAudio2_CreateSourceVoice(xaudio2, &srcvoicemusic, &fmt, 0, 2.0f, &callbacks, NULL, NULL); fmt.nSamplesPerSec = WT_FREQ; fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; (void) IXAudio2_CreateSourceVoice(xaudio2, &srcvoicewt, &fmt, 0, 2.0f, &callbacks, NULL, NULL); fmt.nSamplesPerSec = CD_FREQ; fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; (void) IXAudio2_CreateSourceVoice(xaudio2, &srcvoicecd, &fmt, 0, 2.0f, &callbacks, NULL, NULL); (void) IXAudio2SourceVoice_SetVolume(srcvoice, 1, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_Start(srcvoice, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_Start(srcvoicecd, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_Start(srcvoicemusic, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_Start(srcvoicewt, 0, XAUDIO2_COMMIT_NOW); const char *mdn = midi_out_device_get_internal_name(midi_output_device_current); if ((strcmp(mdn, "none") != 0) && (strcmp(mdn, SYSTEM_MIDI_INTERNAL_NAME) != 0)) { fmt.nSamplesPerSec = midi_freq; fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; (void) IXAudio2_CreateSourceVoice(xaudio2, &srcvoicemidi, &fmt, 0, 2.0f, &callbacks, NULL, NULL); (void) IXAudio2SourceVoice_Start(srcvoicemidi, 0, XAUDIO2_COMMIT_NOW); } initialized = 1; atexit(closeal); } void closeal(void) { if (!initialized) return; initialized = 0; (void) IXAudio2SourceVoice_Stop(srcvoice, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_FlushSourceBuffers(srcvoice); (void) IXAudio2SourceVoice_Stop(srcvoicemusic, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_FlushSourceBuffers(srcvoicemusic); (void) IXAudio2SourceVoice_Stop(srcvoicewt, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_FlushSourceBuffers(srcvoicewt); (void) IXAudio2SourceVoice_Stop(srcvoicecd, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_FlushSourceBuffers(srcvoicecd); if (srcvoicemidi) { (void) IXAudio2SourceVoice_Stop(srcvoicemidi, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_FlushSourceBuffers(srcvoicemidi); IXAudio2SourceVoice_DestroyVoice(srcvoicemidi); } IXAudio2SourceVoice_DestroyVoice(srcvoicewt); IXAudio2SourceVoice_DestroyVoice(srcvoicecd); IXAudio2SourceVoice_DestroyVoice(srcvoicemusic); IXAudio2SourceVoice_DestroyVoice(srcvoice); IXAudio2MasteringVoice_DestroyVoice(mastervoice); IXAudio2_Release(xaudio2); srcvoice = srcvoicecd = srcvoicemidi = NULL; mastervoice = NULL; xaudio2 = NULL; #if defined(_WIN32) && !defined(USE_FAUDIO) dynld_close(xaudio2_handle); xaudio2_handle = NULL; #endif } void givealbuffer_common(const void *buf, IXAudio2SourceVoice *sourcevoice, const size_t buflen) { if (!initialized) return; (void) IXAudio2MasteringVoice_SetVolume(mastervoice, pow(10.0, (double) sound_gain / 20.0), XAUDIO2_COMMIT_NOW); XAUDIO2_BUFFER buffer = { 0 }; buffer.Flags = 0; if (sound_is_float) { buffer.pAudioData = calloc(buflen, sizeof(float)); buffer.AudioBytes = buflen * sizeof(float); } else { buffer.pAudioData = calloc(buflen, sizeof(int16_t)); buffer.AudioBytes = buflen * sizeof(int16_t); } if (buffer.pAudioData == NULL) { fatal("xaudio2: Out Of Memory!"); } memcpy((void *) buffer.pAudioData, buf, buffer.AudioBytes); buffer.PlayBegin = buffer.PlayLength = 0; buffer.PlayLength = buflen >> 1; buffer.pContext = (void *) buffer.pAudioData; (void) IXAudio2SourceVoice_SubmitSourceBuffer(sourcevoice, &buffer, NULL); } void givealbuffer(const void *buf) { givealbuffer_common(buf, srcvoice, BUFLEN << 1); } void givealbuffer_music(const void *buf) { givealbuffer_common(buf, srcvoicemusic, MUSICBUFLEN << 1); } void givealbuffer_wt(const void *buf) { givealbuffer_common(buf, srcvoicewt, WTBUFLEN << 1); } void givealbuffer_cd(const void *buf) { if (srcvoicecd) givealbuffer_common(buf, srcvoicecd, CD_BUFLEN << 1); } void al_set_midi(const int freq, const int buf_size) { midi_freq = freq; midi_buf_size = buf_size; if (initialized && srcvoicemidi) { (void) IXAudio2SourceVoice_Stop(srcvoicemidi, 0, XAUDIO2_COMMIT_NOW); (void) IXAudio2SourceVoice_FlushSourceBuffers(srcvoicemidi); IXAudio2SourceVoice_DestroyVoice(srcvoicemidi); srcvoicemidi = NULL; WAVEFORMATEX fmt; fmt.nChannels = 2; if (sound_is_float) { fmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; fmt.wBitsPerSample = 32; } else { fmt.wFormatTag = WAVE_FORMAT_PCM; fmt.wBitsPerSample = 16; } fmt.nSamplesPerSec = midi_freq; fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; fmt.cbSize = 0; (void) IXAudio2_CreateSourceVoice(xaudio2, &srcvoicemidi, &fmt, 0, 2.0f, &callbacks, NULL, NULL); (void) IXAudio2SourceVoice_Start(srcvoicemidi, 0, XAUDIO2_COMMIT_NOW); } } void givealbuffer_midi(const void *buf, const uint32_t size) { givealbuffer_common(buf, srcvoicemidi, size); } ```
/content/code_sandbox/src/sound/xaudio2.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,960
```c #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include "cpu.h" #include <86box/86box.h> #include <86box/filters.h> #include <86box/lpt.h> #include <86box/machine.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/plat_unused.h> typedef struct dss_t { void *lpt; uint8_t fifo[16]; int read_idx; int write_idx; uint8_t dac_val; uint8_t status; pc_timer_t timer; int16_t buffer[SOUNDBUFLEN]; int pos; } dss_t; static void dss_update(dss_t *dss) { for (; dss->pos < sound_pos_global; dss->pos++) dss->buffer[dss->pos] = (int8_t) (dss->dac_val ^ 0x80) * 0x40; } static void dss_update_status(dss_t *dss) { uint8_t old = dss->status; dss->status &= ~0x40; if ((dss->write_idx - dss->read_idx) >= 16) dss->status |= 0x40; if ((old & 0x40) && !(dss->status & 0x40)) lpt_irq(dss->lpt, 1); } static void dss_write_data(uint8_t val, void *priv) { dss_t *dss = (dss_t *) priv; if ((dss->write_idx - dss->read_idx) < 16) { dss->fifo[dss->write_idx & 15] = val; dss->write_idx++; dss_update_status(dss); } } static void dss_write_ctrl(UNUSED(uint8_t val), UNUSED(void *priv)) { // } static uint8_t dss_read_status(void *priv) { const dss_t *dss = (dss_t *) priv; return dss->status | 0x0f; } static void dss_get_buffer(int32_t *buffer, int len, void *priv) { dss_t *dss = (dss_t *) priv; int16_t val; float fval; dss_update(dss); for (int c = 0; c < len * 2; c += 2) { fval = dss_iir((float) dss->buffer[c >> 1]); val = fval; buffer[c] += val; buffer[c + 1] += val; } dss->pos = 0; } static void dss_callback(void *priv) { dss_t *dss = (dss_t *) priv; dss_update(dss); if ((dss->write_idx - dss->read_idx) > 0) { dss->dac_val = dss->fifo[dss->read_idx & 15]; dss->read_idx++; dss_update_status(dss); } timer_advance_u64(&dss->timer, (TIMER_USEC * (1000000.0 / 7000.0))); } static void * dss_init(void *lpt) { dss_t *dss = malloc(sizeof(dss_t)); memset(dss, 0, sizeof(dss_t)); dss->lpt = lpt; sound_add_handler(dss_get_buffer, dss); timer_add(&dss->timer, dss_callback, dss, 1); return dss; } static void dss_close(void *priv) { dss_t *dss = (dss_t *) priv; free(dss); } const lpt_device_t dss_device = { .name = "Disney Sound Source", .internal_name = "dss", .init = dss_init, .close = dss_close, .write_data = dss_write_data, .write_ctrl = dss_write_ctrl, .read_data = NULL, .read_status = dss_read_status, .read_ctrl = NULL }; ```
/content/code_sandbox/src/sound/snd_lpt_dss.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
953
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Interface to the actual OPL emulator. * * TODO: Finish re-working this into a device_t, which requires a * poll-like function for "update" so the sound card can call * that and get a buffer-full of sample data. * * Authors: Fred N. van Kempen, <decwiz@yahoo.com> * Miran Grca, <mgrca8@gmail.com> * */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include "cpu.h" #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/sound.h> #include <86box/snd_opl.h> static uint32_t fm_dev_inst[FM_DRV_MAX][FM_MAX]; uint8_t fm_driver_get(int chip_id, fm_drv_t *drv) { switch (chip_id) { case FM_YM3812: if (fm_driver == FM_DRV_NUKED) { *drv = nuked_opl_drv; drv->priv = device_add_inst(&ym3812_nuked_device, fm_dev_inst[fm_driver][chip_id]++); } else { *drv = ymfm_drv; drv->priv = device_add_inst(&ym3812_ymfm_device, fm_dev_inst[fm_driver][chip_id]++); } break; case FM_YMF262: if (fm_driver == FM_DRV_NUKED) { *drv = nuked_opl_drv; drv->priv = device_add_inst(&ymf262_nuked_device, fm_dev_inst[fm_driver][chip_id]++); } else { *drv = ymfm_drv; drv->priv = device_add_inst(&ymf262_ymfm_device, fm_dev_inst[fm_driver][chip_id]++); } break; case FM_YMF289B: *drv = ymfm_drv; drv->priv = device_add_inst(&ymf289b_ymfm_device, fm_dev_inst[fm_driver][chip_id]++); break; case FM_YMF278B: *drv = ymfm_drv; drv->priv = device_add_inst(&ymf278b_ymfm_device, fm_dev_inst[fm_driver][chip_id]++); break; case FM_ESFM: *drv = esfmu_opl_drv; drv->priv = device_add_inst(&esfm_esfmu_device, fm_dev_inst[fm_driver][chip_id]++); break; default: return 0; } return 1; }; ```
/content/code_sandbox/src/sound/snd_opl.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
663
```c /*Jazz sample rates : 386-33 - 12kHz 486-33 - 20kHz 486-50 - 32kHz Pentium - 45kHz*/ #define _USE_MATH_DEFINES #include <math.h> #include <stdbool.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/dma.h> #include <86box/filters.h> #include <86box/io.h> #include <86box/midi.h> #include <86box/pic.h> #include <86box/snd_azt2316a.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/snd_sb.h> #include <86box/plat_fallthrough.h> #include <86box/plat_unused.h> /* NON-PCM SAMPLE FORMATS */ #define ADPCM_4 1 #define ADPCM_26 2 #define ADPCM_2 3 #define ESPCM_4 4 #define ESPCM_3 5 /* ESPCM_2? */ #define ESPCM_1 7 #define ESPCM_4E 8 /* For differentiating between 4-bit encoding and decoding modes. */ /* The recording safety margin is intended for uneven "len" calls to the get_buffer mixer calls on sound_sb. */ #define SB_DSP_REC_SAFEFTY_MARGIN 4096 enum { DSP_S_NORMAL = 0, DSP_S_RESET, DSP_S_RESET_WAIT }; void pollsb(void *priv); void sb_poll_i(void *priv); static int sbe2dat[4][9] = { { 0x01, -0x02, -0x04, 0x08, -0x10, 0x20, 0x40, -0x80, -106 }, { -0x01, 0x02, -0x04, 0x08, 0x10, -0x20, 0x40, -0x80, 165 }, { -0x01, 0x02, 0x04, -0x08, 0x10, -0x20, -0x40, 0x80, -151 }, { 0x01, -0x02, 0x04, -0x08, -0x10, 0x20, -0x40, 0x80, 90 } }; static int sb_commands[256] = { -1, 2, -1, 0, 1, 2, -1, 0, 1, -1, -1, -1, -1, -1, 2, 1, 1, -1, -1, -1, 2, -1, 2, 2, -1, -1, -1, -1, 0, -1, -1, 0, 0, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 2, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, -1, -1, -1, -1, -1, 0, -1, 0, 2, 2, -1, -1, -1, -1, -1, -1, 2, 2, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, -1, -1, -1, -1, -1, 1, 0, 1, 0, 1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, 1, 2, -1, -1, -1, -1, 0 }; char sb16_copyright[] = "COPYRIGHT (C) CREATIVE TECHNOLOGY LTD, 1992."; uint16_t sb_dsp_versions[] = { 0, 0, 0x105, 0x200, 0x201, 0x300, 0x302, 0x405, 0x40c, 0x40d, 0x410 }; /*These tables were 'borrowed' from DOSBox*/ int8_t scaleMap4[64] = { 0, 1, 2, 3, 4, 5, 6, 7, 0, -1, -2, -3, -4, -5, -6, -7, 1, 3, 5, 7, 9, 11, 13, 15, -1, -3, -5, -7, -9, -11, -13, -15, 2, 6, 10, 14, 18, 22, 26, 30, -2, -6, -10, -14, -18, -22, -26, -30, 4, 12, 20, 28, 36, 44, 52, 60, -4, -12, -20, -28, -36, -44, -52, -60 }; uint8_t adjustMap4[64] = { 0, 0, 0, 0, 0, 16, 16, 16, 0, 0, 0, 0, 0, 16, 16, 16, 240, 0, 0, 0, 0, 16, 16, 16, 240, 0, 0, 0, 0, 16, 16, 16, 240, 0, 0, 0, 0, 16, 16, 16, 240, 0, 0, 0, 0, 16, 16, 16, 240, 0, 0, 0, 0, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0 }; int8_t scaleMap26[40] = { 0, 1, 2, 3, 0, -1, -2, -3, 1, 3, 5, 7, -1, -3, -5, -7, 2, 6, 10, 14, -2, -6, -10, -14, 4, 12, 20, 28, -4, -12, -20, -28, 5, 15, 25, 35, -5, -15, -25, -35 }; uint8_t adjustMap26[40] = { 0, 0, 0, 8, 0, 0, 0, 8, 248, 0, 0, 8, 248, 0, 0, 8, 248, 0, 0, 8, 248, 0, 0, 8, 248, 0, 0, 8, 248, 0, 0, 8, 248, 0, 0, 0, 248, 0, 0, 0 }; int8_t scaleMap2[24] = { 0, 1, 0, -1, 1, 3, -1, -3, 2, 6, -2, -6, 4, 12, -4, -12, 8, 24, -8, -24, 6, 48, -16, -48 }; uint8_t adjustMap2[24] = { 0, 4, 0, 4, 252, 4, 252, 4, 252, 4, 252, 4, 252, 4, 252, 4, 252, 4, 252, 4, 252, 0, 252, 0 }; // clang-format off /* Upper half only used for ESPCM_3 mode. */ /* TODO: Extract actual table (or exact ranges + range interpolation algo, whatever it is) from chip, someday, somehow. * This current table is part software reverse engineering, part guesswork/extrapolation. * It's close enough to what's in the chip to produce acceptable results, but not exact. **/ int8_t espcm_range_map[512] = { -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -10, -8, -7, -5, -4, -3, -2, -1, 0, 2, 3, 4, 5, 6, 8, 9, -12, -11, -9, -8, -6, -5, -3, -2, 0, 2, 3, 5, 6, 8, 10, 11, -14, -12, -11, -9, -7, -5, -4, -2, 0, 2, 4, 5, 7, 9, 11, 13, -16, -14, -12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12, 14, -21, -18, -16, -13, -11, -8, -6, -3, 0, 2, 5, 7, 10, 12, 15, 18, -27, -24, -21, -17, -14, -11, -8, -4, 0, 3, 7, 10, 13, 17, 20, 24, -35, -28, -24, -20, -16, -12, -8, -4, 0, 4, 8, 12, 16, 20, 24, 28, -40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, -48, -42, -36, -30, -24, -18, -12, -6, 0, 6, 12, 18, 24, 30, 36, 43, -56, -49, -42, -35, -28, -21, -14, -7, 0, 7, 14, 21, 28, 35, 42, 49, -72, -63, -54, -45, -36, -27, -18, -9, 0, 9, 18, 27, 36, 45, 54, 63, -85, -74, -64, -53, -43, -32, -22, -11, 0, 11, 22, 33, 43, 54, 64, 75, -102, -98, -85, -71, -58, -45, -31, -14, 0, 13, 26, 39, 52, 65, 78, 90, -127,-112, -96, -80, -64, -48, -32, -16, 0, 16, 32, 48, 64, 80, 96, 112, -128,-127,-109, -91, -73, -54, -36, -18, 0, 18, 36, 54, 73, 91, 109, 127, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -10, -9, -8, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 6, 7, 8, -13, -11, -9, -7, -6, -5, -3, -2, -1, 2, 3, 5, 6, 7, 9, 10, -15, -13, -12, -10, -8, -6, -5, -3, -1, 2, 3, 5, 6, 8, 10, 12, -18, -15, -13, -11, -9, -7, -5, -3, -1, 2, 3, 5, 7, 9, 11, 13, -24, -20, -17, -15, -12, -10, -7, -5, -2, 2, 3, 6, 8, 11, 13, 16, -29, -26, -23, -19, -16, -13, -10, -6, -2, 2, 5, 8, 11, 15, 18, 22, -34, -30, -26, -22, -18, -14, -10, -6, -2, 2, 6, 10, 14, 18, 22, 26, -43, -38, -33, -28, -23, -18, -13, -8, -3, 2, 7, 12, 17, 22, 27, 32, -51, -45, -39, -33, -27, -21, -15, -9, -3, 3, 9, 15, 21, 27, 33, 39, -60, -53, -46, -39, -32, -25, -18, -11, -4, 3, 10, 17, 24, 31, 38, 45, -77, -68, -59, -50, -41, -32, -23, -14, -5, 4, 13, 22, 31, 40, 49, 58, -90, -80, -69, -59, -48, -38, -27, -17, -6, 5, 16, 27, 38, 48, 59, 69, -112,-104, -91, -78, -65, -52, -38, -23, -7, 6, 19, 32, 45, 58, 71, 84, -128,-120,-104, -88, -72, -56, -40, -24, -8, 8, 24, 40, 56, 72, 88, 104, -128,-128,-118,-100, -82, -64, -45, -27, -9, 9, 27, 45, 63, 82, 100, 118 }; /* address = table_index(9:8) | dsp->espcm_last_value(7:3) | codeword(2:0) * the value is a base index into espcm_range_map with bits at (8, 3:0), * to be OR'ed with dsp->espcm_range at (7:4) */ uint16_t espcm3_dpcm_tables[1024] = { /* Table 0 */ 256, 257, 258, 259, 260, 263, 266, 269, 0, 257, 258, 259, 260, 263, 266, 269, 0, 1, 258, 259, 260, 263, 266, 269, 1, 2, 259, 260, 261, 263, 266, 269, 1, 3, 260, 261, 262, 264, 266, 269, 1, 3, 4, 261, 262, 264, 266, 269, 2, 4, 5, 262, 263, 264, 266, 269, 2, 4, 6, 263, 264, 265, 267, 269, 2, 4, 6, 7, 264, 265, 267, 269, 2, 5, 7, 8, 265, 266, 267, 269, 2, 5, 7, 8, 9, 266, 268, 270, 2, 5, 7, 9, 10, 267, 268, 270, 2, 5, 8, 10, 11, 268, 269, 270, 2, 5, 8, 11, 12, 269, 270, 271, 2, 5, 8, 11, 12, 13, 270, 271, 2, 5, 8, 11, 12, 13, 14, 271, 0, 257, 258, 259, 260, 263, 266, 269, 0, 1, 258, 259, 260, 263, 266, 269, 0, 1, 2, 259, 260, 263, 266, 269, 1, 2, 3, 260, 261, 263, 266, 269, 1, 3, 4, 261, 262, 264, 266, 269, 1, 3, 5, 262, 263, 264, 266, 269, 2, 4, 5, 6, 263, 264, 266, 269, 2, 4, 6, 7, 264, 265, 267, 269, 2, 4, 6, 7, 8, 265, 267, 269, 2, 5, 7, 8, 9, 266, 267, 269, 2, 5, 7, 9, 10, 267, 268, 270, 2, 5, 7, 9, 10, 11, 268, 270, 2, 5, 8, 10, 11, 12, 269, 270, 2, 5, 8, 11, 12, 13, 270, 271, 2, 5, 8, 11, 12, 13, 14, 271, 2, 5, 8, 11, 12, 13, 14, 15, /* Table 1 */ 257, 260, 262, 263, 264, 265, 267, 270, 257, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 4, 262, 263, 264, 265, 267, 270, 1, 4, 262, 263, 264, 265, 267, 270, 1, 4, 6, 263, 264, 265, 267, 270, 1, 4, 6, 7, 264, 265, 267, 270, 1, 4, 6, 7, 8, 265, 267, 270, 1, 4, 6, 7, 8, 9, 267, 270, 1, 4, 6, 7, 8, 9, 267, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 14, 257, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 4, 262, 263, 264, 265, 267, 270, 1, 4, 262, 263, 264, 265, 267, 270, 1, 4, 6, 263, 264, 265, 267, 270, 1, 4, 6, 7, 264, 265, 267, 270, 1, 4, 6, 7, 8, 265, 267, 270, 1, 4, 6, 7, 8, 9, 267, 270, 1, 4, 6, 7, 8, 9, 267, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 14, 1, 4, 6, 7, 8, 9, 11, 14, /* Table 2 */ 256, 257, 258, 259, 260, 262, 265, 268, 0, 257, 258, 259, 260, 262, 265, 268, 0, 1, 258, 259, 260, 262, 265, 269, 1, 2, 259, 260, 261, 263, 265, 269, 1, 3, 260, 261, 262, 263, 265, 269, 1, 3, 4, 261, 262, 263, 265, 269, 1, 3, 5, 262, 263, 264, 266, 269, 1, 4, 5, 6, 263, 264, 266, 269, 1, 4, 6, 7, 264, 265, 266, 269, 1, 4, 6, 7, 8, 265, 266, 269, 2, 4, 6, 7, 8, 9, 267, 269, 2, 4, 6, 7, 8, 9, 267, 269, 2, 5, 7, 8, 9, 10, 11, 270, 2, 5, 7, 8, 9, 10, 11, 270, 2, 5, 8, 9, 10, 11, 12, 270, 2, 6, 8, 10, 11, 12, 13, 14, 257, 258, 259, 260, 261, 263, 265, 269, 1, 259, 260, 261, 262, 263, 266, 269, 1, 260, 261, 262, 263, 264, 266, 269, 1, 260, 261, 262, 263, 264, 266, 269, 2, 4, 262, 263, 264, 265, 267, 269, 2, 4, 262, 263, 264, 265, 267, 269, 2, 5, 6, 263, 264, 265, 267, 270, 2, 5, 6, 7, 264, 265, 267, 270, 2, 5, 7, 8, 265, 266, 267, 270, 2, 5, 7, 8, 9, 266, 268, 270, 2, 6, 8, 9, 10, 267, 268, 270, 2, 6, 8, 9, 10, 11, 268, 270, 2, 6, 8, 10, 11, 12, 269, 270, 2, 6, 9, 11, 12, 13, 270, 271, 3, 6, 9, 11, 12, 13, 14, 271, 3, 6, 9, 11, 12, 13, 14, 15, /* Table 3 */ 256, 258, 260, 261, 262, 263, 264, 265, 0, 258, 260, 261, 262, 263, 264, 265, 1, 259, 260, 261, 262, 263, 264, 266, 1, 259, 260, 261, 262, 263, 264, 266, 1, 3, 260, 261, 262, 263, 264, 266, 1, 3, 4, 261, 262, 263, 264, 267, 1, 3, 4, 5, 262, 263, 264, 267, 1, 3, 4, 5, 6, 263, 264, 267, 1, 3, 5, 6, 7, 264, 265, 268, 1, 3, 5, 6, 7, 8, 265, 268, 1, 4, 6, 7, 8, 9, 266, 269, 1, 4, 6, 7, 8, 9, 10, 269, 1, 4, 6, 7, 8, 9, 10, 269, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 270, 1, 4, 6, 7, 8, 9, 11, 14, 257, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 1, 260, 262, 263, 264, 265, 267, 270, 2, 261, 262, 263, 264, 265, 267, 270, 2, 261, 262, 263, 264, 265, 267, 270, 2, 5, 262, 263, 264, 265, 267, 270, 3, 6, 263, 264, 265, 266, 268, 270, 3, 6, 7, 264, 265, 266, 268, 270, 4, 7, 8, 265, 266, 267, 268, 270, 4, 7, 8, 9, 266, 267, 268, 270, 4, 7, 8, 9, 10, 267, 268, 270, 5, 7, 8, 9, 10, 11, 268, 270, 5, 7, 8, 9, 10, 11, 12, 270, 5, 7, 8, 9, 10, 11, 12, 270, 6, 7, 8, 9, 10, 11, 13, 271, 6, 7, 8, 9, 10, 11, 13, 15 }; // clang-format on double low_fir_sb16_coef[5][SB16_NCoef]; #ifdef ENABLE_SB_DSP_LOG int sb_dsp_do_log = ENABLE_SB_DSP_LOG; static void sb_dsp_log(const char *fmt, ...) { va_list ap; if (sb_dsp_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define sb_dsp_log(fmt, ...) #endif #define ESSreg(reg) (dsp)->ess_regs[reg - 0xA0] static __inline double sinc(double x) { return sin(M_PI * x) / (M_PI * x); } static void recalc_sb16_filter(const int c, const int playback_freq) { /* Cutoff frequency = playback / 2 */ int n; const double fC = ((double) playback_freq) / (double) FREQ_96000; for (n = 0; n < SB16_NCoef; n++) { /* Blackman window */ const double w = 0.42 - (0.5 * cos((2.0 * n * M_PI) / (double) (SB16_NCoef - 1))) + (0.08 * cos((4.0 * n * M_PI) / (double) (SB16_NCoef - 1))); /* Sinc filter */ const double h = sinc(2.0 * fC * ((double) n - ((double) (SB16_NCoef - 1) / 2.0))); /* Create windowed-sinc filter */ low_fir_sb16_coef[c][n] = w * h; } low_fir_sb16_coef[c][(SB16_NCoef - 1) / 2] = 1.0; double gain = 0.0; for (n = 0; n < SB16_NCoef; n++) gain += low_fir_sb16_coef[c][n]; /* Normalise filter, to produce unity gain */ for (n = 0; n < SB16_NCoef; n++) low_fir_sb16_coef[c][n] /= gain; } static void recalc_opl_filter(const int playback_freq) { /* Cutoff frequency = playback / 2 */ int n; const double fC = ((double) playback_freq) / (double) (FREQ_49716 * 2); for (n = 0; n < SB16_NCoef; n++) { /* Blackman window */ const double w = 0.42 - (0.5 * cos((2.0 * n * M_PI) / (double) (SB16_NCoef - 1))) + (0.08 * cos((4.0 * n * M_PI) / (double) (SB16_NCoef - 1))); /* Sinc filter */ const double h = sinc(2.0 * fC * ((double) n - ((double) (SB16_NCoef - 1) / 2.0))); /* Create windowed-sinc filter */ low_fir_sb16_coef[1][n] = w * h; } low_fir_sb16_coef[1][(SB16_NCoef - 1) / 2] = 1.0; double gain = 0.0; for (n = 0; n < SB16_NCoef; n++) gain += low_fir_sb16_coef[1][n]; /* Normalise filter, to produce unity gain */ for (n = 0; n < SB16_NCoef; n++) low_fir_sb16_coef[1][n] /= gain; } static void sb_irq_update_pic(void *priv, const int set) { const sb_dsp_t *dsp = (sb_dsp_t *) priv; if (set) picint(1 << dsp->sb_irqnum); else picintc(1 << dsp->sb_irqnum); } void sb_update_mask(sb_dsp_t *dsp, int irqm8, int irqm16, int irqm401) { int clear = 0; if (!dsp->sb_irqm8 && irqm8) clear |= 1; dsp->sb_irqm8 = irqm8; if (!dsp->sb_irqm16 && irqm16) clear |= 1; dsp->sb_irqm16 = irqm16; if (!dsp->sb_irqm401 && irqm401) clear |= 1; dsp->sb_irqm401 = irqm401; if (clear) dsp->irq_update(dsp->irq_priv, 0); } void sb_update_status(sb_dsp_t *dsp, int bit, int set) { int masked = 0; if (dsp->sb_irq8 || dsp->sb_irq16) return; /* NOTE: not on ES1688 or ES1868 */ if (IS_ESS(dsp) && (dsp->sb_subtype != SB_SUBTYPE_ESS_ES1688) && !(ESSreg(0xB1) & 0x10)) /* If ESS playback, and IRQ disabled, do not fire. */ return; switch (bit) { default: case 0: dsp->sb_irq8 = set; masked = dsp->sb_irqm8; break; case 1: dsp->sb_irq16 = set; masked = dsp->sb_irqm16; break; case 2: dsp->sb_irq401 = set; masked = dsp->sb_irqm401; break; } /* NOTE: not on ES1688, apparently; investigate on ES1868 */ if (IS_ESS(dsp) && (dsp->sb_subtype > SB_SUBTYPE_ESS_ES1688)) { /* TODO: Investigate real hardware for this (the ES1887 datasheet documents this bit somewhat oddly.) */ if (dsp->ess_playback_mode && bit <= 1 && set && !masked) { if (!(ESSreg(0xB1) & 0x40)) // if ESS playback, and IRQ disabled, do not fire { return; } } } if (set && !masked) dsp->irq_update(dsp->irq_priv, 1); else if (!set) dsp->irq_update(dsp->irq_priv, 0); } void sb_irq(sb_dsp_t *dsp, int irq8) { sb_update_status(dsp, !irq8, 1); } void sb_irqc(sb_dsp_t *dsp, int irq8) { sb_update_status(dsp, !irq8, 0); } static void sb_dsp_irq_update(void *priv, const int set) { sb_dsp_t *dsp = (sb_dsp_t *) priv; sb_update_status(dsp, 2, set); } static int sb_dsp_irq_pending(void *priv) { const sb_dsp_t *dsp = (sb_dsp_t *) priv; return dsp->sb_irq401; } void sb_dsp_set_mpu(sb_dsp_t *dsp, mpu_t *mpu) { dsp->mpu = mpu; if (IS_NOT_ESS(dsp) && (mpu != NULL)) mpu401_irq_attach(mpu, sb_dsp_irq_update, sb_dsp_irq_pending, dsp); } void sb_dsp_reset(sb_dsp_t *dsp) { midi_clear_buffer(); timer_disable(&dsp->output_timer); timer_disable(&dsp->input_timer); dsp->sb_command = 0; dsp->sb_8_length = 0xffff; dsp->sb_8_autolen = 0xffff; dsp->sb_irq8 = 0; dsp->sb_irq16 = 0; dsp->sb_irq401 = 0; dsp->sb_16_pause = 0; dsp->sb_read_wp = dsp->sb_read_rp = 0; dsp->sb_data_stat = -1; dsp->sb_speaker = 0; dsp->sb_pausetime = -1LL; dsp->sbe2 = 0xAA; dsp->sbe2count = 0; dsp->sbreset = 0; dsp->record_pos_read = 0; dsp->record_pos_write = SB_DSP_REC_SAFEFTY_MARGIN; dsp->irq_update(dsp->irq_priv, 0); dsp->asp_data_len = 0; } void sb_doreset(sb_dsp_t *dsp) { sb_dsp_reset(dsp); if (IS_AZTECH(dsp)) { sb_commands[8] = 1; sb_commands[9] = 1; } else { if (dsp->sb_type >= SB16) sb_commands[8] = 1; else sb_commands[8] = -1; } dsp->sb_asp_mode = 0; dsp->sb_asp_ram_index = 0; for (uint16_t c = 0; c < 256; c++) dsp->sb_asp_regs[c] = 0; dsp->sb_asp_regs[5] = 0x01; dsp->sb_asp_regs[9] = 0xf8; /* Initialize ESS registers */ ESSreg(0xA5) = 0xf8; } void sb_dsp_speed_changed(sb_dsp_t *dsp) { if (dsp->sb_timeo < 256) dsp->sblatcho = (double) (TIMER_USEC * (256 - dsp->sb_timeo)); else dsp->sblatcho = ((double) TIMER_USEC * (1000000.0 / (double) (dsp->sb_timeo - 256))); if (dsp->sb_timei < 256) dsp->sblatchi = (double) (TIMER_USEC * (256 - dsp->sb_timei)); else dsp->sblatchi = ((double) TIMER_USEC * (1000000.0 / (double) (dsp->sb_timei - 256))); } void sb_add_data(sb_dsp_t *dsp, uint8_t v) { dsp->sb_read_data[dsp->sb_read_wp++] = v; dsp->sb_read_wp &= 0xff; } static unsigned int sb_ess_get_dma_counter(const sb_dsp_t *dsp) { unsigned int c = (unsigned int) ESSreg(0xA5) << 8U; c |= (unsigned int) ESSreg(0xA4); return c; } static unsigned int sb_ess_get_dma_len(const sb_dsp_t *dsp) { return 0x10000U - sb_ess_get_dma_counter(dsp); } static void sb_resume_dma(const sb_dsp_t *dsp, const int is_8) { if IS_ESS(dsp) { dma_set_drq(dsp->sb_8_dmanum, 1); dma_set_drq(dsp->sb_16_8_dmanum, 1); } else if (is_8) dma_set_drq(dsp->sb_8_dmanum, 1); else { if (dsp->sb_16_dmanum != 0xff) { if (dsp->sb_16_dmanum == 4) dma_set_drq(dsp->sb_8_dmanum, 1); else dma_set_drq(dsp->sb_16_dmanum, 1); } if (dsp->sb_16_8_dmanum != 0xff) dma_set_drq(dsp->sb_16_8_dmanum, 1); } } static void sb_stop_dma(const sb_dsp_t *dsp) { dma_set_drq(dsp->sb_8_dmanum, 0); if (dsp->sb_16_dmanum != 0xff) { if (dsp->sb_16_dmanum == 4) dma_set_drq(dsp->sb_8_dmanum, 0); else dma_set_drq(dsp->sb_16_dmanum, 0); } if (dsp->sb_16_8_dmanum != 0xff) dma_set_drq(dsp->sb_16_8_dmanum, 0); } void sb_start_dma(sb_dsp_t *dsp, int dma8, int autoinit, uint8_t format, int len) { sb_stop_dma(dsp); dsp->sb_pausetime = -1; if (dma8) { dsp->sb_8_length = dsp->sb_8_origlength = len; dsp->sb_8_format = format; dsp->sb_8_autoinit = autoinit; dsp->sb_8_pause = 0; dsp->sb_8_enable = 1; dsp->dma_ff = 0; if (dsp->sb_16_enable && dsp->sb_16_output) dsp->sb_16_enable = 0; dsp->sb_8_output = 1; if (!timer_is_enabled(&dsp->output_timer)) timer_set_delay_u64(&dsp->output_timer, (uint64_t) dsp->sblatcho); dsp->sbleftright = dsp->sbleftright_default; dsp->sbdacpos = 0; dma_set_drq(dsp->sb_8_dmanum, 1); } else { dsp->sb_16_length = dsp->sb_16_origlength = len; dsp->sb_16_format = format; dsp->sb_16_autoinit = autoinit; dsp->sb_16_pause = 0; dsp->sb_16_enable = 1; if (dsp->sb_8_enable && dsp->sb_8_output) dsp->sb_8_enable = 0; dsp->sb_16_output = 1; if (!timer_is_enabled(&dsp->output_timer)) timer_set_delay_u64(&dsp->output_timer, (uint64_t) dsp->sblatcho); if (dsp->sb_16_dma_supported) { if (dsp->sb_16_dmanum == 4) dma_set_drq(dsp->sb_8_dmanum, 1); else dma_set_drq(dsp->sb_16_dmanum, 1); } else dma_set_drq(dsp->sb_16_8_dmanum, 1); } /* This will be set later for ESS playback/record modes. */ dsp->ess_playback_mode = 0; } void sb_start_dma_i(sb_dsp_t *dsp, int dma8, int autoinit, uint8_t format, int len) { sb_stop_dma(dsp); if (dma8) { dsp->sb_8_length = dsp->sb_8_origlength = len; dsp->sb_8_format = format; dsp->sb_8_autoinit = autoinit; dsp->sb_8_pause = 0; dsp->sb_8_enable = 1; if (dsp->sb_16_enable && !dsp->sb_16_output) dsp->sb_16_enable = 0; dsp->sb_8_output = 0; if (!timer_is_enabled(&dsp->input_timer)) timer_set_delay_u64(&dsp->input_timer, (uint64_t) dsp->sblatchi); dma_set_drq(dsp->sb_8_dmanum, 1); } else { dsp->sb_16_length = dsp->sb_16_origlength = len; dsp->sb_16_format = format; dsp->sb_16_autoinit = autoinit; dsp->sb_16_pause = 0; dsp->sb_16_enable = 1; if (dsp->sb_8_enable && !dsp->sb_8_output) dsp->sb_8_enable = 0; dsp->sb_16_output = 0; if (!timer_is_enabled(&dsp->input_timer)) timer_set_delay_u64(&dsp->input_timer, (uint64_t) dsp->sblatchi); if (dsp->sb_16_dma_supported) { if (dsp->sb_16_dmanum == 4) dma_set_drq(dsp->sb_8_dmanum, 1); else dma_set_drq(dsp->sb_16_dmanum, 1); } else dma_set_drq(dsp->sb_16_8_dmanum, 1); } memset(dsp->record_buffer, 0, sizeof(dsp->record_buffer)); } void sb_start_dma_ess(sb_dsp_t *dsp) { uint8_t real_format = 0; dsp->ess_dma_counter = sb_ess_get_dma_counter(dsp); uint32_t len = sb_ess_get_dma_len(dsp); if (IS_ESS(dsp)) { dma_set_drq(dsp->sb_8_dmanum, 0); dma_set_drq(dsp->sb_16_8_dmanum, 0); } real_format |= !!(ESSreg(0xB7) & 0x20) ? 0x10 : 0; real_format |= !!(ESSreg(0xB7) & 0x8) ? 0x20 : 0; if (!!(ESSreg(0xB8) & 8)) sb_start_dma_i(dsp, !(ESSreg(0xB7) & 4), (ESSreg(0xB8) >> 2) & 1, real_format, (int) len); else sb_start_dma(dsp, !(ESSreg(0xB7) & 4), (ESSreg(0xB8) >> 2) & 1, real_format, (int) len); dsp->ess_playback_mode = 1; dma_set_drq(dsp->sb_8_dmanum, 1); dma_set_drq(dsp->sb_16_8_dmanum, 1); } void sb_stop_dma_ess(sb_dsp_t *dsp) { dsp->sb_8_enable = dsp->sb_16_enable = 0; dma_set_drq(dsp->sb_16_8_dmanum, 0); dma_set_drq(dsp->sb_8_dmanum, 0); } static void sb_ess_update_dma_status(sb_dsp_t *dsp) { bool dma_en = (ESSreg(0xB8) & 1) ? true : false; /* If the DRQ is disabled, do not start. */ if (!(ESSreg(0xB2) & 0x40)) dma_en = false; if (dma_en) { if (!dsp->sb_8_enable && !dsp->sb_16_enable) sb_start_dma_ess(dsp); } else { if (dsp->sb_8_enable || dsp->sb_16_enable) sb_stop_dma_ess(dsp); } } int sb_8_read_dma(void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; int ret; dsp->activity &= 0xdf; if (dsp->sb_8_dmanum >= 4) { if (dsp->dma_ff) { uint32_t temp = (dsp->dma_data & 0xff00) >> 8; temp |= (dsp->dma_data & 0xffff0000); ret = (int) temp; } else { dsp->dma_data = dma_channel_read(dsp->sb_8_dmanum); if (dsp->dma_data == DMA_NODATA) return DMA_NODATA; ret = dsp->dma_data & 0xff; } dsp->dma_ff = !dsp->dma_ff; } else ret = dma_channel_read(dsp->sb_8_dmanum); return ret; } int sb_8_write_dma(void *priv, uint8_t val) { sb_dsp_t *dsp = (sb_dsp_t *) priv; dsp->activity &= 0xdf; return dma_channel_write(dsp->sb_8_dmanum, val) == DMA_NODATA; } /* Supported High DMA Translation Channel ---------------------------------------------------- 0 0 0 First 8-bit 0 0 1 First 8-bit 0 1 0 Second 8-bit 0 1 1 Second 8-bit 1 0 0 First 8-bit 1 0 1 First 8-bit 1 1 0 16-bit 1 1 1 Second 8-bit */ int sb_16_read_dma(void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; int ret; int dma_ch = dsp->sb_16_dmanum; dsp->activity &= 0xdf; if (dsp->sb_16_dma_enabled && dsp->sb_16_dma_supported && !dsp->sb_16_dma_translate && (dma_ch != 4)) ret = dma_channel_read(dma_ch); else { if (dsp->sb_16_dma_enabled) { /* High DMA channel enabled, either translation is enabled or 16-bit transfers are not supported. */ if (dsp->sb_16_dma_supported && !dsp->sb_16_dma_translate && (dma_ch == 4)) dma_ch = dsp->sb_8_dmanum; else dma_ch = dsp->sb_16_8_dmanum; } else /* High DMA channel disabled, always use the first 8-bit channel. */ dma_ch = dsp->sb_8_dmanum; int temp = dma_channel_read(dma_ch); ret = temp; if ((temp != DMA_NODATA) && !(temp & DMA_OVER)) { temp = dma_channel_read(dma_ch); if (temp == DMA_NODATA) ret = DMA_NODATA; else { const int dma_flags = temp & DMA_OVER; temp &= ~DMA_OVER; ret |= (temp << 8) | dma_flags; } } } return ret; } int sb_16_write_dma(void *priv, uint16_t val) { sb_dsp_t *dsp = (sb_dsp_t *) priv; int dma_ch = dsp->sb_16_dmanum; int ret; dsp->activity &= 0xdf; if (dsp->sb_16_dma_enabled && dsp->sb_16_dma_supported && !dsp->sb_16_dma_translate && (dma_ch != 4)) ret = dma_channel_write(dma_ch, val) == DMA_NODATA; else { if (dsp->sb_16_dma_enabled) { /* High DMA channel enabled, either translation is enabled or 16-bit transfers are not supported. */ if (dsp->sb_16_dma_supported && !dsp->sb_16_dma_translate && (dma_ch == 4)) dma_ch = dsp->sb_8_dmanum; else dma_ch = dsp->sb_16_8_dmanum; } else /* High DMA channel disabled, always use the first 8-bit channel. */ dma_ch = dsp->sb_8_dmanum; int temp = dma_channel_write(dma_ch, val & 0xff); ret = temp; if ((temp != DMA_NODATA) && (temp != DMA_OVER)) { temp = dma_channel_write(dma_ch, val >> 8); ret = temp; } } return ret; } void sb_ess_update_irq_drq_readback_regs(sb_dsp_t *dsp, bool legacy) { sb_t *ess = (sb_t *) dsp->parent; ess_mixer_t *mixer = &ess->mixer_ess; uint8_t t = 0x00; /* IRQ control */ if (legacy) { t |= 0x80; } switch (dsp->sb_irqnum) { default: break; case 2: case 9: t |= 0x0; break; case 5: t |= 0x5; break; case 7: t |= 0xA; break; case 10: t |= 0xF; break; } ESSreg(0xB1) = (ESSreg(0xB1) & 0xF0) | t; if ((mixer != NULL) && (ess->mpu != NULL) && (((mixer->regs[0x40] >> 5) & 0x7) == 2)) mpu401_setirq(ess->mpu, ess->dsp.sb_irqnum); /* DRQ control */ t = 0x00; if (legacy) { t |= 0x80; } switch (dsp->sb_8_dmanum) { default: break; case 0: t |= 0x5; break; case 1: t |= 0xA; break; case 3: t |= 0xF; break; } ESSreg(0xB2) = (ESSreg(0xB2) & 0xF0) | t; } void sb_dsp_setirq(sb_dsp_t *dsp, int irq) { sb_dsp_log("IRQ now: %i\n", irq); dsp->sb_irqnum = irq; if (IS_ESS(dsp)) { sb_ess_update_irq_drq_readback_regs(dsp, true); ESSreg(0xB1) = (ESSreg(0xB1) & 0xEF) | 0x10; } } void sb_dsp_setdma8(sb_dsp_t *dsp, int dma) { sb_dsp_log("8-bit DMA now: %i\n", dma); dsp->sb_8_dmanum = dma; if (IS_ESS(dsp)) sb_ess_update_irq_drq_readback_regs(dsp, true); } void sb_dsp_setdma16(sb_dsp_t *dsp, int dma) { sb_dsp_log("16-bit DMA now: %i\n", dma); dsp->sb_16_dmanum = dma; } void sb_dsp_setdma16_8(sb_dsp_t *dsp, int dma) { sb_dsp_log("16-bit to 8-bit translation DMA now: %i\n", dma); dsp->sb_16_8_dmanum = dma; } void sb_dsp_setdma16_enabled(sb_dsp_t *dsp, int enabled) { sb_dsp_log("16-bit DMA now: %sabled\n", enabled ? "en" : "dis"); dsp->sb_16_dma_enabled = enabled; } void sb_dsp_setdma16_supported(sb_dsp_t *dsp, int supported) { sb_dsp_log("16-bit DMA now: %ssupported\n", supported ? "" : "not "); dsp->sb_16_dma_supported = supported; } void sb_dsp_setdma16_translate(sb_dsp_t *dsp, const int translate) { sb_dsp_log("16-bit to 8-bit translation now: %sabled\n", translate ? "en" : "dis"); dsp->sb_16_dma_translate = translate; } static void sb_ess_update_reg_a2(sb_dsp_t *dsp, const uint8_t val) { const double freq = (7160000.0 / (256.0 - ((double) val))) * 41.0; const int temp = (int) freq; ESSreg(0xA2) = val; if (dsp->sb_freq != temp) recalc_sb16_filter(0, temp); dsp->sb_freq = temp; } /* TODO: Investigate ESS cards' filtering on real hardware as well. (DOSBox-X did it purely off some laptop's ESS chip, which isn't a good look.) */ static void sb_ess_update_filter_freq(sb_dsp_t *dsp) { const double temp = (7160000.0 / (((((double) dsp->sb_freq) / 2.0) * 0.80) * 82.0)) - 256.0; if (dsp->sb_freq >= 22050) ESSreg(0xA1) = 256 - (795500UL / dsp->sb_freq); else ESSreg(0xA1) = 128 - (397700UL / dsp->sb_freq); sb_ess_update_reg_a2(dsp, (uint8_t) temp); } static uint8_t sb_ess_read_reg(const sb_dsp_t *dsp, const uint8_t reg) { return ESSreg(reg); } static void sb_ess_update_autolen(sb_dsp_t *dsp) { dsp->sb_8_autolen = dsp->sb_16_autolen = (int) sb_ess_get_dma_len(dsp); } static void sb_ess_write_reg(sb_dsp_t *dsp, const uint8_t reg, uint8_t data) { uint8_t chg; switch (reg) { case 0xA1: /* Extended Mode Sample Rate Generator */ { ESSreg(reg) = data; if (data & 0x80) dsp->sb_freq = (int) (795500UL / (256ul - data)); else dsp->sb_freq = (int) (397700UL / (128ul - data)); const double temp = 1000000.0 / dsp->sb_freq; dsp->sblatchi = dsp->sblatcho = ((double) TIMER_USEC * temp); dsp->sb_timei = dsp->sb_timeo; break; } case 0xA2: /* Filter divider (effectively, a hardware lowpass filter under S/W control) */ sb_ess_update_reg_a2(dsp, data); break; case 0xA4: /* DMA Transfer Count Reload (low) */ case 0xA5: /* DMA Transfer Count Reload (high) */ ESSreg(reg) = data; sb_ess_update_autolen(dsp); if ((dsp->sb_16_length < 0 && !dsp->sb_16_enable) && (dsp->sb_8_length < 0 && !dsp->sb_8_enable)) dsp->ess_reload_len = 1; break; case 0xA8: /* Analog Control */ /* bits 7:5 0 Reserved. Always write 0 * bit 4 1 Reserved. Always write 1 * bit 3 Record monitor 1=Enable record monitor * enable * bit 2 0 Reserved. Always write 0 * bits 1:0 Stereo/mono select 00=Reserved * 01=Stereo * 10=Mono * 11=Reserved */ chg = ESSreg(reg) ^ data; ESSreg(reg) = data; if (chg & 0x3) { if (dsp->sb_16_enable || dsp->sb_8_enable) { uint8_t real_format = 0x00; real_format |= !!(ESSreg(0xB7) & 0x20) ? 0x10 : 0; real_format |= !!(ESSreg(0xB7) & 0x8) ? 0x20 : 0; if (dsp->sb_16_enable) dsp->sb_16_format = real_format; if (dsp->sb_8_enable) dsp->sb_8_format = real_format; } } break; case 0xB1: /* Legacy Audio Interrupt Control */ ESSreg(reg) = (ESSreg(reg) & 0x0F) + (data & 0xF0); // lower 4 bits not writeable switch (data & 0x0C) { default: break; case 0x00: dsp->sb_irqnum = 2; break; case 0x04: dsp->sb_irqnum = 5; break; case 0x08: dsp->sb_irqnum = 7; break; case 0x0C: dsp->sb_irqnum = 10; break; } sb_ess_update_irq_drq_readback_regs(dsp, false); break; case 0xB2: /* DRQ Control */ chg = ESSreg(reg) ^ data; ESSreg(reg) = (ESSreg(reg) & 0x0F) + (data & 0xF0); // lower 4 bits not writeable switch (data & 0x0C) { default: break; case 0x00: dsp->sb_8_dmanum = -1; break; case 0x04: dsp->sb_8_dmanum = 0; break; case 0x08: dsp->sb_8_dmanum = 1; break; case 0x0C: dsp->sb_8_dmanum = 3; break; } sb_ess_update_irq_drq_readback_regs(dsp, false); if (chg & 0x40) sb_ess_update_dma_status(dsp); break; case 0xB5: /* DAC Direct Access Holding (low) */ case 0xB6: /* DAC Direct Access Holding (high) */ ESSreg(reg) = data; break; case 0xB7: /* Audio 1 Control 1 */ /* bit 7 Enable FIFO to/from codec * bit 6 Opposite from bit 3 Must be set opposite to bit 3 * bit 5 FIFO signed mode 1=Data is signed twos-complement 0=Data is unsigned * bit 4 Reserved Always write 1 * bit 3 FIFO stereo mode 1=Data is stereo * bit 2 FIFO 16-bit mode 1=Data is 16-bit * bit 1 Reserved Always write 0 * bit 0 Generate load signal */ chg = ESSreg(reg) ^ data; ESSreg(reg) = data; if (chg & 4) sb_ess_update_autolen(dsp); if (chg & 0x0C) { if (dsp->sb_16_enable || dsp->sb_8_enable) { sb_stop_dma_ess(dsp); sb_start_dma_ess(dsp); } } break; case 0xB8: /* Audio 1 Control 2 */ /* bits 7:4 reserved * bit 3 CODEC mode 1=first DMA converter in ADC mode * 0=first DMA converter in DAC mode * bit 2 DMA mode 1=auto-initialize mode * 0=normal DMA mode * bit 1 DMA read enable 1=first DMA is read (for ADC) * 0=first DMA is write (for DAC) * bit 0 DMA xfer enable 1=DMA is allowed to proceed */ data &= 0xF; chg = ESSreg(reg) ^ data; ESSreg(reg) = data; if (chg & 1) { if (dsp->sb_16_enable || dsp->sb_8_enable) { if (dsp->sb_16_enable) dsp->sb_16_length = (int) sb_ess_get_dma_len(dsp); if (dsp->sb_8_enable) dsp->sb_8_length = (int) sb_ess_get_dma_len(dsp); } else dsp->ess_reload_len = 1; } if (chg & 0x4) { if (dsp->sb_16_enable) { dsp->sb_16_autoinit = (ESSreg(0xB8) & 0x4) != 0; } if (dsp->sb_8_enable) { dsp->sb_8_autoinit = (ESSreg(0xB8) & 0x4) != 0; } } if (chg & 0xB) { if (chg & 0xA) sb_stop_dma_ess(dsp); /* changing capture/playback direction? stop DMA to reinit */ sb_ess_update_dma_status(dsp); } break; case 0xB9: /* Audio 1 Transfer Type */ case 0xBA: /* Left Channel ADC Offset Adjust */ case 0xBB: /* Right Channel ADC Offset Adjust */ case 0xC3: /* Internal state register */ case 0xCF: /* GPO0/1 power management register */ ESSreg(reg) = data; break; default: sb_dsp_log("UNKNOWN ESS register write reg=%02xh val=%02xh\n", reg, data); break; } } void sb_exec_command(sb_dsp_t *dsp) { int temp; int c; sb_dsp_log("sb_exec_command : SB command %02X\n", dsp->sb_command); /* Update 8051 ram with the current DSP command. See path_to_url */ if (dsp->sb_type >= SB16) { dsp->sb_8051_ram[0x20] = dsp->sb_command; } if (IS_ESS(dsp) && dsp->sb_command >= 0xA0 && dsp->sb_command <= 0xCF) { if (dsp->sb_command == 0xC6 || dsp->sb_command == 0xC7) { dsp->ess_extended_mode = !!(dsp->sb_command == 0xC6); return; } else if (dsp->sb_command == 0xC2) { sb_ess_write_reg(dsp, 0xC3, dsp->sb_data[0]); } else if (dsp->sb_command == 0xC3) { sb_add_data(dsp, sb_ess_read_reg(dsp, 0xC3)); } else if (dsp->sb_command == 0xCE) { sb_add_data(dsp, sb_ess_read_reg(dsp, 0xCF)); } else if (dsp->sb_command == 0xCF) { sb_ess_write_reg(dsp, 0xCF, dsp->sb_data[0]); } else if (dsp->sb_command == 0xC0) { sb_add_data(dsp, sb_ess_read_reg(dsp, dsp->sb_data[0])); } else if (dsp->sb_command < 0xC0 && dsp->ess_extended_mode) { sb_ess_write_reg(dsp, dsp->sb_command, dsp->sb_data[0]); } return; } switch (dsp->sb_command) { case 0x01: /* ???? */ if (dsp->sb_type >= SB16) dsp->asp_data_len = dsp->sb_data[0] + (dsp->sb_data[1] << 8) + 1; break; case 0x03: /* ASP status */ if (dsp->sb_type >= SB16) sb_add_data(dsp, 0); break; case 0x04: /* ASP set mode register */ if (dsp->sb_type >= SB16) { dsp->sb_asp_mode = dsp->sb_data[0]; if (dsp->sb_asp_mode & 4) dsp->sb_asp_ram_index = 0; sb_dsp_log("SB16 ASP set mode %02X\n", dsp->sb_asp_mode); } /* else DSP Status (Obsolete) */ break; case 0x05: /* ASP set codec parameter */ if (dsp->sb_type >= SB16) { sb_dsp_log("SB16 ASP unknown codec params %02X, %02X\n", dsp->sb_data[0], dsp->sb_data[1]); } break; case 0x07: break; case 0x08: /* ASP get version / AZTECH type/EEPROM access */ if (IS_AZTECH(dsp)) { if ((dsp->sb_data[0] == 0x05 || dsp->sb_data[0] == 0x55) && dsp->sb_subtype == SB_SUBTYPE_CLONE_AZT2316A_0X11) sb_add_data(dsp, 0x11); /* AZTECH get type, WASHINGTON/latest - according to devkit. E.g.: The one in the Itautec Infoway Multimidia */ else if ((dsp->sb_data[0] == 0x05 || dsp->sb_data[0] == 0x55) && dsp->sb_subtype == SB_SUBTYPE_CLONE_AZT1605_0X0C) sb_add_data(dsp, 0x0C); /* AZTECH get type, CLINTON - according to devkit. E.g.: The one in the Packard Bell Legend 100CD */ else if (dsp->sb_data[0] == 0x08) { /* EEPROM address to write followed by byte */ if (dsp->sb_data[1] < 0 || dsp->sb_data[1] >= AZTECH_EEPROM_SIZE) fatal("AZT EEPROM: out of bounds write to %02X\n", dsp->sb_data[1]); sb_dsp_log("EEPROM write = %02x\n", dsp->sb_data[2]); dsp->azt_eeprom[dsp->sb_data[1]] = dsp->sb_data[2]; break; } else if (dsp->sb_data[0] == 0x07) { /* EEPROM address to read */ if (dsp->sb_data[1] < 0 || dsp->sb_data[1] >= AZTECH_EEPROM_SIZE) fatal("AZT EEPROM: out of bounds read to %02X\n", dsp->sb_data[1]); sb_dsp_log("EEPROM read = %02x\n", dsp->azt_eeprom[dsp->sb_data[1]]); sb_add_data(dsp, dsp->azt_eeprom[dsp->sb_data[1]]); break; } else sb_dsp_log("AZT2316A: UNKNOWN 0x08 COMMAND: %02X\n", dsp->sb_data[0]); /* 0x08 (when shutting down, driver tries to read 1 byte of response), 0x55, 0x0D, 0x08D seen */ break; } if (dsp->sb_type == SBAWE64) /* AWE64 has no ASP or a socket for it */ sb_add_data(dsp, 0xFF); else if (dsp->sb_type >= SB16) sb_add_data(dsp, 0x18); break; case 0x09: /* AZTECH mode set */ if (IS_AZTECH(dsp)) { if (dsp->sb_data[0] == 0x00) { sb_dsp_log("AZT2316A: WSS MODE!\n"); azt2316a_enable_wss(1, dsp->parent); } else if (dsp->sb_data[0] == 0x01) { sb_dsp_log("AZT2316A: SB8PROV2 MODE!\n"); azt2316a_enable_wss(0, dsp->parent); } else sb_dsp_log("AZT2316A: UNKNOWN MODE! = %02x\n", dsp->sb_data[0]); // sequences 0x02->0xFF, 0x04->0xFF seen } break; case 0x0E: /* ASP set register */ if (dsp->sb_type >= SB16) { dsp->sb_asp_regs[dsp->sb_data[0]] = dsp->sb_data[1]; if ((dsp->sb_data[0] == 0x83) && (dsp->sb_asp_mode & 128) && (dsp->sb_asp_mode & 8)) { /* ASP memory write */ if (dsp->sb_asp_mode & 8) dsp->sb_asp_ram_index = 0; dsp->sb_asp_ram[dsp->sb_asp_ram_index] = dsp->sb_data[1]; if (dsp->sb_asp_mode & 2) { dsp->sb_asp_ram_index++; if (dsp->sb_asp_ram_index >= 2048) dsp->sb_asp_ram_index = 0; } } sb_dsp_log("SB16 ASP write reg %02X, val %02X\n", dsp->sb_data[0], dsp->sb_data[1]); } break; case 0x0F: /* ASP get register */ if (dsp->sb_type >= SB16) { if ((dsp->sb_data[0] == 0x83) && (dsp->sb_asp_mode & 128) && (dsp->sb_asp_mode & 8)) { /* ASP memory read */ if (dsp->sb_asp_mode & 8) dsp->sb_asp_ram_index = 0; dsp->sb_asp_regs[0x83] = dsp->sb_asp_ram[dsp->sb_asp_ram_index]; if (dsp->sb_asp_mode & 1) { dsp->sb_asp_ram_index++; if (dsp->sb_asp_ram_index >= 2048) dsp->sb_asp_ram_index = 0; } } else if (dsp->sb_data[0] == 0x83) { dsp->sb_asp_regs[0x83] = 0x18; } sb_add_data(dsp, dsp->sb_asp_regs[dsp->sb_data[0]]); sb_dsp_log("SB16 ASP read reg %02X, val %02X\n", dsp->sb_data[0], dsp->sb_asp_regs[dsp->sb_data[0]]); } break; case 0x10: /* 8-bit direct mode */ sb_dsp_update(dsp); dsp->sbdat = dsp->sbdatl = dsp->sbdatr = (int16_t) ((dsp->sb_data[0] ^ 0x80) << 8); // FIXME: What does the ESS AudioDrive do to its filter/sample rate divider registers when emulating this Sound Blaster command? ESSreg(0xA1) = 128 - (397700 / 22050); ESSreg(0xA2) = 256 - (7160000 / (82 * ((4 * 22050) / 10))); break; case 0x14: /* 8-bit single cycle DMA output */ sb_start_dma(dsp, 1, 0, 0, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); break; case 0x17: /* 2-bit ADPCM output with reference */ dsp->sbref = dsp->dma_readb(dsp->dma_priv); dsp->sbstep = 0; fallthrough; case 0x16: /* 2-bit ADPCM output */ sb_start_dma(dsp, 1, 0, ADPCM_2, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; if (dsp->sb_command == 0x17) { dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x1C: /* 8-bit autoinit DMA output */ if (dsp->sb_type >= SB15) sb_start_dma(dsp, 1, 1, 0, dsp->sb_8_autolen); break; case 0x1F: /* 2-bit ADPCM autoinit output */ if (dsp->sb_type >= SB15) { sb_start_dma(dsp, 1, 1, ADPCM_2, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x20: /* 8-bit direct input */ sb_add_data(dsp, (dsp->record_buffer[dsp->record_pos_read] >> 8) ^ 0x80); /* Due to the current implementation, I need to emulate a samplerate, even if this mode does not imply such samplerate. Position is increased in sb_poll_i(). */ if (!timer_is_enabled(&dsp->input_timer)) { dsp->sb_timei = 256 - 22; dsp->sblatchi = (double) ((double) TIMER_USEC * 22.0); temp = 1000000 / 22; dsp->sb_freq = temp; timer_set_delay_u64(&dsp->input_timer, (uint64_t) dsp->sblatchi); } break; case 0x24: /* 8-bit single cycle DMA input */ sb_start_dma_i(dsp, 1, 0, 0, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); break; case 0x28: /* Direct ADC, 8-bit (Burst) */ break; case 0x2C: /* 8-bit autoinit DMA input */ if (dsp->sb_type >= SB15) sb_start_dma_i(dsp, 1, 1, 0, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); break; case 0x30: /* MIDI Polling mode input */ sb_dsp_log("MIDI polling mode input\n"); dsp->midi_in_poll = 1; dsp->uart_irq = 0; break; case 0x31: /* MIDI Interrupt mode input */ sb_dsp_log("MIDI interrupt mode input\n"); dsp->midi_in_poll = 0; dsp->uart_irq = 1; break; case 0x32: /* MIDI Read Timestamp Poll */ case 0x33: /* MIDI Read Timestamp Interrupt */ break; case 0x34: /* MIDI In poll */ if (dsp->sb_type < SB2) break; sb_dsp_log("MIDI poll in\n"); dsp->midi_in_poll = 1; dsp->uart_midi = 1; dsp->uart_irq = 0; break; case 0x35: /* MIDI In irq */ if (dsp->sb_type < SB2) break; sb_dsp_log("MIDI irq in\n"); dsp->midi_in_poll = 0; dsp->uart_midi = 1; dsp->uart_irq = 1; break; case 0x36: case 0x37: /* MIDI timestamps */ break; case 0x38: /* Write to SB MIDI Output (Raw) */ dsp->onebyte_midi = 1; break; case 0x40: /* Set time constant */ dsp->sb_timei = dsp->sb_timeo = dsp->sb_data[0]; dsp->sblatcho = dsp->sblatchi = (double) (TIMER_USEC * (256 - dsp->sb_data[0])); temp = 256 - dsp->sb_data[0]; temp = 1000000 / temp; sb_dsp_log("Sample rate - %ihz (%f)\n", temp, dsp->sblatcho); if ((dsp->sb_freq != temp) && (dsp->sb_type >= SB16)) recalc_sb16_filter(0, temp); dsp->sb_freq = temp; if (IS_ESS(dsp)) { sb_ess_update_filter_freq(dsp); } break; case 0x41: /* Set output sampling rate */ case 0x42: /* Set input sampling rate */ if (dsp->sb_type >= SB16) { dsp->sblatcho = (double) ((double) TIMER_USEC * (1000000.0 / (double) (dsp->sb_data[1] + (dsp->sb_data[0] << 8)))); sb_dsp_log("Sample rate - %ihz (%f)\n", dsp->sb_data[1] + (dsp->sb_data[0] << 8), dsp->sblatcho); temp = dsp->sb_freq; dsp->sb_freq = dsp->sb_data[1] + (dsp->sb_data[0] << 8); dsp->sb_timeo = 256 + dsp->sb_freq; dsp->sblatchi = dsp->sblatcho; dsp->sb_timei = dsp->sb_timeo; if (dsp->sb_freq != temp) recalc_sb16_filter(0, dsp->sb_freq); dsp->sb_8051_ram[0x13] = dsp->sb_freq & 0xff; dsp->sb_8051_ram[0x14] = (dsp->sb_freq >> 8) & 0xff; } break; case 0x45: /* Continue Auto-Initialize DMA, 8-bit */ case 0x47: /* Continue Auto-Initialize DMA, 16-bit */ break; case 0x48: /* Set DSP block transfer size */ dsp->sb_8_autolen = dsp->sb_data[0] + (dsp->sb_data[1] << 8); break; case 0x65: /* 4-bit ESPCM output with reference */ case 0x64: /* 4-bit ESPCM output */ if (IS_ESS(dsp)) { if (dsp->espcm_mode != ESPCM_4 || (dsp->sb_8_enable && dsp->sb_8_pause)) { fifo_reset(dsp->espcm_fifo); dsp->espcm_sample_idx = 0; } dsp->espcm_mode = ESPCM_4; sb_start_dma(dsp, 1, 0, ESPCM_4, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); } break; case 0x67: /* 3-bit ESPCM output with reference */ case 0x66: /* 3-bit ESPCM output */ if (IS_ESS(dsp)) { if (dsp->espcm_mode != ESPCM_3 || (dsp->sb_8_enable && dsp->sb_8_pause)) { fifo_reset(dsp->espcm_fifo); dsp->espcm_sample_idx = 0; } dsp->espcm_mode = ESPCM_3; sb_start_dma(dsp, 1, 0, ESPCM_3, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); } break; case 0x6D: /* 1-bit ESPCM output with reference */ case 0x6C: /* 1-bit ESPCM output */ if (IS_ESS(dsp)) { if (dsp->espcm_mode != ESPCM_1 || (dsp->sb_8_enable && dsp->sb_8_pause)) { fifo_reset(dsp->espcm_fifo); dsp->espcm_sample_idx = 0; } dsp->espcm_mode = ESPCM_1; sb_start_dma(dsp, 1, 0, ESPCM_1, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); } break; case 0x6F: /* 4-bit ESPCM input with reference */ case 0x6E: /* 4-bit ESPCM input */ if (IS_ESS(dsp)) { if (dsp->espcm_mode != ESPCM_4E || (dsp->sb_8_enable && dsp->sb_8_pause)) { fifo_reset(dsp->espcm_fifo); dsp->espcm_sample_idx = 0; } dsp->espcm_mode = ESPCM_4E; sb_start_dma_i(dsp, 1, 0, ESPCM_4E, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); } break; case 0x75: /* 4-bit ADPCM output with reference */ dsp->sbref = dsp->dma_readb(dsp->dma_priv); dsp->sbstep = 0; fallthrough; case 0x74: /* 4-bit ADPCM output */ sb_start_dma(dsp, 1, 0, ADPCM_4, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; if (dsp->sb_command == 0x75) { dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x77: /* 2.6-bit ADPCM output with reference */ dsp->sbref = dsp->dma_readb(dsp->dma_priv); dsp->sbstep = 0; fallthrough; case 0x76: /* 2.6-bit ADPCM output */ sb_start_dma(dsp, 1, 0, ADPCM_26, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; if (dsp->sb_command == 0x77) { dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x7D: /* 4-bit ADPCM autoinit output */ if (dsp->sb_type >= SB15) { sb_start_dma(dsp, 1, 1, ADPCM_4, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x7F: /* 2.6-bit ADPCM autoinit output */ if (dsp->sb_type >= SB15) { sb_start_dma(dsp, 1, 1, ADPCM_26, dsp->sb_data[0] + (dsp->sb_data[1] << 8)); dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x80: /* Pause DAC */ dsp->sb_pausetime = dsp->sb_data[0] + (dsp->sb_data[1] << 8); if (!timer_is_enabled(&dsp->output_timer)) timer_set_delay_u64(&dsp->output_timer, (uint64_t) trunc(dsp->sblatcho)); break; case 0x90: /* High speed 8-bit autoinit DMA output */ if (dsp->sb_type >= SB2) sb_start_dma(dsp, 1, 1, 0, dsp->sb_8_autolen); break; case 0x91: /* High speed 8-bit single cycle DMA output */ if (dsp->sb_type >= SB2) sb_start_dma(dsp, 1, 0, 0, dsp->sb_8_autolen); break; case 0x98: /* High speed 8-bit autoinit DMA input */ if (dsp->sb_type >= SB2) sb_start_dma_i(dsp, 1, 1, 0, dsp->sb_8_autolen); break; case 0x99: /* High speed 8-bit single cycle DMA input */ if (dsp->sb_type >= SB2) sb_start_dma_i(dsp, 1, 0, 0, dsp->sb_8_autolen); break; case 0xA0: /* Set input mode to mono */ case 0xA8: /* Set input mode to stereo */ if ((dsp->sb_type < SB2) || (dsp->sb_type > SBPRO2)) break; /* TODO: Implement. 3.xx-only command. */ break; case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: /* 16-bit DMA output */ if (dsp->sb_type >= SB16) { sb_start_dma(dsp, 0, dsp->sb_command & 4, dsp->sb_data[0], dsp->sb_data[1] + (dsp->sb_data[2] << 8)); dsp->sb_16_autolen = dsp->sb_data[1] + (dsp->sb_data[2] << 8); } break; case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: /* 16-bit DMA input */ if (dsp->sb_type >= SB16) { sb_start_dma_i(dsp, 0, dsp->sb_command & 4, dsp->sb_data[0], dsp->sb_data[1] + (dsp->sb_data[2] << 8)); dsp->sb_16_autolen = dsp->sb_data[1] + (dsp->sb_data[2] << 8); } break; case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: /* 8-bit DMA output */ if (dsp->sb_type >= SB16) { sb_start_dma(dsp, 1, dsp->sb_command & 4, dsp->sb_data[0], dsp->sb_data[1] + (dsp->sb_data[2] << 8)); dsp->sb_8_autolen = dsp->sb_data[1] + (dsp->sb_data[2] << 8); } break; case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: /* 8-bit DMA input */ if (dsp->sb_type >= SB16) { sb_start_dma_i(dsp, 1, dsp->sb_command & 4, dsp->sb_data[0], dsp->sb_data[1] + (dsp->sb_data[2] << 8)); dsp->sb_8_autolen = dsp->sb_data[1] + (dsp->sb_data[2] << 8); } break; case 0xD0: /* Pause 8-bit DMA */ dsp->sb_8_pause = 1; sb_stop_dma(dsp); break; case 0xD1: /* Speaker on */ if (IS_NOT_ESS(dsp)) { if (dsp->sb_type < SB15) { dsp->sb_8_pause = 1; sb_stop_dma(dsp); } else if (dsp->sb_type < SB16) dsp->muted = 0; } dsp->sb_speaker = 1; break; case 0xD3: /* Speaker off */ if (IS_NOT_ESS(dsp)) { if (dsp->sb_type < SB15) { dsp->sb_8_pause = 1; sb_stop_dma(dsp); } else if (dsp->sb_type < SB16) dsp->muted = 1; } dsp->sb_speaker = 0; break; case 0xD4: /* Continue 8-bit DMA */ dsp->sb_8_pause = 0; sb_resume_dma(dsp, 1); break; case 0xD5: /* Pause 16-bit DMA */ if (dsp->sb_type >= SB16) { dsp->sb_16_pause = 1; sb_stop_dma(dsp); } break; case 0xD6: /* Continue 16-bit DMA */ if (dsp->sb_type >= SB16) { dsp->sb_16_pause = 0; sb_resume_dma(dsp, 1); } break; case 0xD8: /* Get speaker status */ sb_add_data(dsp, dsp->sb_speaker ? 0xff : 0); break; case 0xD9: /* Exit 16-bit auto-init mode */ if (dsp->sb_type >= SB16) dsp->sb_16_autoinit = 0; break; case 0xDA: /* Exit 8-bit auto-init mode */ dsp->sb_8_autoinit = 0; break; case 0xE0: /* DSP identification */ sb_add_data(dsp, ~dsp->sb_data[0]); break; case 0xE1: /* Get DSP version */ if (IS_ESS(dsp)) { sb_add_data(dsp, 0x3); sb_add_data(dsp, 0x1); break; } if (IS_AZTECH(dsp)) { if (dsp->sb_subtype == SB_SUBTYPE_CLONE_AZT2316A_0X11) { sb_add_data(dsp, 0x3); sb_add_data(dsp, 0x1); } else if (dsp->sb_subtype == SB_SUBTYPE_CLONE_AZT1605_0X0C) { sb_add_data(dsp, 0x2); sb_add_data(dsp, 0x1); } break; } sb_add_data(dsp, sb_dsp_versions[dsp->sb_type] >> 8); sb_add_data(dsp, sb_dsp_versions[dsp->sb_type] & 0xff); break; case 0xE2: /* Stupid ID/protection */ for (c = 0; c < 8; c++) { if (dsp->sb_data[0] & (1 << c)) dsp->sbe2 += sbe2dat[dsp->sbe2count & 3][c]; } dsp->sbe2 += sbe2dat[dsp->sbe2count & 3][8]; dsp->sbe2count++; if (dsp->dma_writeb(dsp->dma_priv, dsp->sbe2)) /* Undocumented behavior: If write to DMA fails, the byte is written to the CPU instead. The NT 3.1 Sound Blaster Pro driver relies on this. */ sb_add_data(dsp, dsp->sbe2); break; case 0xE3: /* DSP copyright */ if (dsp->sb_type >= SB16) { c = 0; while (sb16_copyright[c]) sb_add_data(dsp, sb16_copyright[c++]); sb_add_data(dsp, 0); } else if (IS_ESS(dsp)) { sb_add_data(dsp, 0); } break; case 0xE4: /* Write test register */ dsp->sb_test = dsp->sb_data[0]; break; case 0xE7: /* ESS detect/read config on ESS cards */ if (IS_ESS(dsp)) { switch (dsp->sb_subtype) { default: break; case SB_SUBTYPE_ESS_ES688: sb_add_data(dsp, 0x68); sb_add_data(dsp, 0x80 | 0x04); break; case SB_SUBTYPE_ESS_ES1688: // Determined via Windows driver debugging. sb_add_data(dsp, 0x68); sb_add_data(dsp, 0x80 | 0x09); break; } } break; case 0xE8: /* Read test register */ sb_add_data(dsp, dsp->sb_test); break; case 0xF2: /* Trigger 8-bit IRQ */ sb_dsp_log("Trigger 8-bit IRQ\n"); timer_set_delay_u64(&dsp->irq_timer, (10ULL * TIMER_USEC)); break; case 0xF3: /* Trigger 16-bit IRQ */ sb_dsp_log("Trigger 16-bit IRQ\n"); if (IS_ESS(dsp)) dsp->ess_irq_generic = true; else timer_set_delay_u64(&dsp->irq16_timer, (10ULL * TIMER_USEC)); break; case 0xF8: if (dsp->sb_type < SB16) sb_add_data(dsp, 0); break; case 0xF9: /* SB16 8051 RAM read */ if (dsp->sb_type >= SB16) sb_add_data(dsp, dsp->sb_8051_ram[dsp->sb_data[0]]); break; case 0xFA: /* SB16 8051 RAM write */ if (dsp->sb_type >= SB16) dsp->sb_8051_ram[dsp->sb_data[0]] = dsp->sb_data[1]; break; case 0xFF: /* No, that's not how you program auto-init DMA */ break; /* TODO: Some more data about the DSP registeres * path_to_url~tfm/oldpage/sb_dsp.html * path_to_url * path_to_url * 0F0h Sine Generator SB * 0F1h DSP Auxiliary Status (Obsolete) SB-Pro2 * 0F2h IRQ Request, 8-bit SB * 0F3h IRQ Request, 16-bit SB16 * 0FBh DSP Status SB16 * 0FCh DSP Auxiliary Status SB16 * 0FDh DSP Command Status SB16 */ default: sb_dsp_log("Unknown DSP command: %02X\n", dsp->sb_command); break; } /* Update 8051 ram with the last DSP command. See path_to_url */ if (dsp->sb_type >= SB16) dsp->sb_8051_ram[0x30] = dsp->sb_command; } static void sb_do_reset(sb_dsp_t *dsp, const uint8_t v) { if (((v & 1) != 0) && (dsp->state != DSP_S_RESET)) { sb_dsp_reset(dsp); dsp->sb_read_rp = dsp->sb_read_wp = 0; dsp->state = DSP_S_RESET; } else if (((v & 1) == 0) && (dsp->state == DSP_S_RESET)) { dsp->state = DSP_S_RESET_WAIT; dsp->sb_read_rp = dsp->sb_read_wp = 0; sb_add_data(dsp, 0xaa); } } void sb_write(uint16_t a, uint8_t v, void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; sb_dsp_log("[%04X:%08X] DSP: [W] %04X = %02X\n", CS, cpu_state.pc, a, v); /* Sound Blasters prior to Sound Blaster 16 alias the I/O ports. */ if ((dsp->sb_type < SB16) && (IS_NOT_ESS(dsp) || ((a & 0xF) != 0xE))) a &= 0xfffe; switch (a & 0xF) { case 6: /* Reset */ sb_do_reset(dsp, v); if (!(v & 2) && (dsp->espcm_fifo_reset & 2)) { fifo_reset(dsp->espcm_fifo); } dsp->espcm_fifo_reset = v; dsp->uart_midi = 0; dsp->uart_irq = 0; dsp->onebyte_midi = 0; return; case 0xC: /* Command/data write */ if (dsp->uart_midi || dsp->onebyte_midi) { midi_raw_out_byte(v); dsp->onebyte_midi = 0; return; } timer_set_delay_u64(&dsp->wb_timer, TIMER_USEC * 1); if (dsp->asp_data_len) { sb_dsp_log("ASP data %i\n", dsp->asp_data_len); dsp->asp_data_len--; if (!dsp->asp_data_len) sb_add_data(dsp, 0); return; } if (dsp->sb_data_stat == -1) { dsp->sb_command = v; if (v == 0x01) sb_add_data(dsp, 0); dsp->sb_data_stat++; if (IS_AZTECH(dsp)) { /* variable length commands */ if (dsp->sb_command == 0x08 && dsp->sb_data_stat == 1 && dsp->sb_data[0] == 0x08) sb_commands[dsp->sb_command] = 3; else if (dsp->sb_command == 0x08 && dsp->sb_data_stat == 1 && dsp->sb_data[0] == 0x07) sb_commands[dsp->sb_command] = 2; } if (IS_ESS(dsp) && dsp->sb_command >= 0x64 && dsp->sb_command <= 0x6F) { sb_commands[dsp->sb_command] = 2; } else if (IS_ESS(dsp) && dsp->sb_command >= 0xA0 && dsp->sb_command <= 0xCF) { if (dsp->sb_command <= 0xC0 || dsp->sb_command == 0xC2 || dsp->sb_command == 0xCF) { sb_commands[dsp->sb_command] = 1; } else if (dsp->sb_command == 0xC3 || dsp->sb_command == 0xC6 || dsp->sb_command == 0xC7 || dsp->sb_command == 0xCE) { sb_commands[dsp->sb_command] = 0; } else { sb_commands[dsp->sb_command] = -1; } } } else { dsp->sb_data[dsp->sb_data_stat++] = v; } if (dsp->sb_data_stat == sb_commands[dsp->sb_command] || sb_commands[dsp->sb_command] == -1) { sb_exec_command(dsp); dsp->sb_data_stat = -1; if (IS_AZTECH(dsp)) { /* variable length commands */ if (dsp->sb_command == 0x08) sb_commands[dsp->sb_command] = 1; } } break; default: break; } } uint8_t sb_read(uint16_t a, void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; uint8_t ret = 0x00; /* Sound Blasters prior to Sound Blaster 16 alias the I/O ports. */ if ((dsp->sb_type < SB16) && (IS_NOT_ESS(dsp) || ((a & 0xF) != 0xF))) /* Exception: ESS AudioDrive does not alias port base+0xf */ a &= 0xfffe; switch (a & 0xf) { case 0x6: if (IS_ESS(dsp)) { ret = (dsp->espcm_fifo_reset & 0x03) | 0x08 | (dsp->activity & 0xe0); dsp->activity |= 0xe0; } else ret = 0xff; break; case 0xA: /* Read data */ if (dsp->mpu && dsp->uart_midi) ret = MPU401_ReadData(dsp->mpu); else { if (dsp->sb_read_rp != dsp->sb_read_wp) { dsp->sbreaddat = dsp->sb_read_data[dsp->sb_read_rp]; dsp->sb_read_rp++; dsp->sb_read_rp &= 0xff; } ret = dsp->sbreaddat; } /* Advance the state just in case something reads from here without reading the status first. */ if (dsp->state == DSP_S_RESET_WAIT) dsp->state = DSP_S_NORMAL; break; case 0xC: /* Write data ready */ /* Advance the state just in case something reads from here without reading the status first. */ if (dsp->state == DSP_S_RESET_WAIT) dsp->state = DSP_S_NORMAL; if ((dsp->state == DSP_S_NORMAL) || IS_ESS(dsp)) { if (dsp->sb_8_enable || dsp->sb_type >= SB16) dsp->busy_count = (dsp->busy_count + 1) & 3; else dsp->busy_count = 0; if (IS_ESS(dsp)) { if (dsp->wb_full || (dsp->busy_count & 2)) dsp->wb_full = timer_is_enabled(&dsp->wb_timer); const uint8_t busy_flag = dsp->wb_full ? 0x80 : 0x00; const uint8_t data_rdy = (dsp->sb_read_rp == dsp->sb_read_wp) ? 0x00 : 0x40; const uint8_t fifo_full = 0; /* Unimplemented */ const uint8_t fifo_empty = 0; /* (this is for the 256-byte extended mode FIFO, */ const uint8_t fifo_half = 0; /* not the standard 64-byte FIFO) */ const uint8_t irq_generic = dsp->ess_irq_generic ? 0x04 : 0x00; const uint8_t irq_fifohe = 0; /* Unimplemented (ditto) */ const uint8_t irq_dmactr = dsp->ess_irq_dmactr ? 0x01 : 0x00; ret = busy_flag | data_rdy | fifo_full | fifo_empty | fifo_half | irq_generic | irq_fifohe | irq_dmactr; } else if (dsp->wb_full || (dsp->busy_count & 2)) { dsp->wb_full = timer_is_enabled(&dsp->wb_timer); if (IS_AZTECH(dsp)) { sb_dsp_log("SB Write Data Aztech read 0x80\n"); ret = 0x80; } else { sb_dsp_log("SB Write Data Creative read 0xff\n"); if ((dsp->sb_type >= SB2) && (dsp->sb_type < SB16) && IS_NOT_ESS(dsp)) ret = 0xaa; else ret = 0xff; } } else if (IS_AZTECH(dsp)) { sb_dsp_log("SB Write Data Aztech read 0x00\n"); ret = 0x00; } else { sb_dsp_log("SB Write Data Creative read 0x7f\n"); if ((dsp->sb_type >= SB2) && (dsp->sb_type < SB16) && IS_NOT_ESS(dsp)) ret = 0x2a; else ret = 0x7f; } } else ret = 0xff; break; case 0xE: /* Read data ready */ dsp->irq_update(dsp->irq_priv, 0); dsp->sb_irq8 = dsp->sb_irq16 = 0; dsp->ess_irq_generic = dsp->ess_irq_dmactr = false; /* Only bit 7 is defined but aztech diagnostics fail if the others are set. Keep the original behavior to not interfere with what's already working. */ if (IS_AZTECH(dsp)) { sb_dsp_log("SB Read Data Aztech read %02X, Read RP = %d, Read WP = %d\n", (dsp->sb_read_rp == dsp->sb_read_wp) ? 0x00 : 0x80, dsp->sb_read_rp, dsp->sb_read_wp); ret = (dsp->sb_read_rp == dsp->sb_read_wp) ? 0x00 : 0x80; } else { sb_dsp_log("SB Read Data Creative read %02X\n", (dsp->sb_read_rp == dsp->sb_read_wp) ? 0x7f : 0xff); if ((dsp->sb_type < SB16) && IS_NOT_ESS(dsp)) ret = (dsp->sb_read_rp == dsp->sb_read_wp) ? 0x2a : 0xaa; else ret = (dsp->sb_read_rp == dsp->sb_read_wp) ? 0x7f : 0xff; } if (dsp->state == DSP_S_RESET_WAIT) { ret &= 0x7f; dsp->state = DSP_S_NORMAL; } break; case 0xF: /* 16-bit ack */ if (IS_NOT_ESS(dsp)) { dsp->sb_irq16 = 0; if (!dsp->sb_irq8) dsp->irq_update(dsp->irq_priv, 0); sb_dsp_log("SB 16-bit ACK read 0xFF\n"); } ret = 0xff; break; default: break; } sb_dsp_log("[%04X:%08X] DSP: [R] %04X = %02X\n", CS, cpu_state.pc, a, ret); return ret; } void sb_dsp_input_msg(void *priv, uint8_t *msg, uint32_t len) { sb_dsp_t *dsp = (sb_dsp_t *) priv; sb_dsp_log("MIDI in sysex = %d, uart irq = %d, msg = %d\n", dsp->midi_in_sysex, dsp->uart_irq, len); if (!dsp->uart_irq && !dsp->midi_in_poll && (dsp->mpu != NULL)) { MPU401_InputMsg(dsp->mpu, msg, len); return; } if (dsp->midi_in_sysex) return; if (dsp->uart_irq) { for (uint32_t i = 0; i < len; i++) sb_add_data(dsp, msg[i]); sb_irq(dsp, 1); dsp->ess_irq_generic = true; } else if (dsp->midi_in_poll) { for (uint32_t i = 0; i < len; i++) sb_add_data(dsp, msg[i]); } } int sb_dsp_input_sysex(void *priv, uint8_t *buffer, uint32_t len, int abort) { sb_dsp_t *dsp = (sb_dsp_t *) priv; if (!dsp->uart_irq && !dsp->midi_in_poll && (dsp->mpu != NULL)) return MPU401_InputSysex(dsp->mpu, buffer, len, abort); if (abort) { dsp->midi_in_sysex = 0; return 0; } dsp->midi_in_sysex = 1; for (uint32_t i = 0; i < len; i++) { if (dsp->sb_read_rp == dsp->sb_read_wp) { sb_dsp_log("Length sysex SB = %d\n", len - i); return (int) (len - i); } sb_add_data(dsp, buffer[i]); } dsp->midi_in_sysex = 0; return 0; } void sb_dsp_irq_poll(void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; sb_irq(dsp, 1); dsp->ess_irq_generic = true; } void sb_dsp_irq16_poll(void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; sb_irq(dsp, 0); dsp->ess_irq_generic = true; } void sb_dsp_init(sb_dsp_t *dsp, int type, int subtype, void *parent) { dsp->sb_type = type; dsp->sb_subtype = subtype; dsp->parent = parent; dsp->activity = 0xe0; /* Default values. Use sb_dsp_setxxx() methods to change. */ dsp->sb_irqnum = 7; dsp->sb_8_dmanum = 1; if (type >= SB16) dsp->sb_16_dmanum = 5; else dsp->sb_16_dmanum = 0xff; if ((type >= SB16) || IS_ESS(dsp)) dsp->sb_16_8_dmanum = 0x1; dsp->mpu = NULL; dsp->sbleftright_default = 0; dsp->irq_update = sb_irq_update_pic; dsp->irq_priv = dsp; dsp->dma_readb = sb_8_read_dma; dsp->dma_readw = sb_16_read_dma; dsp->dma_writeb = sb_8_write_dma; dsp->dma_writew = sb_16_write_dma; dsp->dma_priv = dsp; sb_doreset(dsp); timer_add(&dsp->output_timer, pollsb, dsp, 0); timer_add(&dsp->input_timer, sb_poll_i, dsp, 0); timer_add(&dsp->wb_timer, NULL, dsp, 0); timer_add(&dsp->irq_timer, sb_dsp_irq_poll, dsp, 0); timer_add(&dsp->irq16_timer, sb_dsp_irq16_poll, dsp, 0); if (IS_ESS(dsp)) /* Initialize ESS filter to 8 kHz. This will be recalculated when a set frequency command is sent. */ recalc_sb16_filter(0, 8000 * 2); else { timer_add(&dsp->irq16_timer, sb_dsp_irq16_poll, dsp, 0); /* Initialise SB16 filter to same cutoff as 8-bit SBs (3.2 kHz). This will be recalculated when a set frequency command is sent. */ recalc_sb16_filter(0, 3200 * 2); } if (IS_ESS(dsp) || (dsp->sb_type >= SBPRO2)) { /* OPL3 or dual OPL2 is stereo. */ if (dsp->sb_has_real_opl) recalc_opl_filter(FREQ_49716 * 2); else recalc_sb16_filter(1, FREQ_48000 * 2); } else { /* OPL2 is mono. */ if (dsp->sb_has_real_opl) recalc_opl_filter(FREQ_49716); else recalc_sb16_filter(1, FREQ_48000); } /* CD Audio is stereo. */ recalc_sb16_filter(2, FREQ_44100 * 2); /* PC speaker is mono. */ recalc_sb16_filter(3, 18939); /* E-MU 8000 is stereo. */ recalc_sb16_filter(4, FREQ_44100 * 2); /* Initialize SB16 8051 RAM and ASP internal RAM */ memset(dsp->sb_8051_ram, 0x00, sizeof(dsp->sb_8051_ram)); dsp->sb_8051_ram[0x0e] = 0xff; dsp->sb_8051_ram[0x0f] = 0x07; dsp->sb_8051_ram[0x37] = 0x38; memset(dsp->sb_asp_ram, 0xff, sizeof(dsp->sb_asp_ram)); dsp->espcm_fifo = fifo64_init(); fifo_set_trigger_len(dsp->espcm_fifo, 1); } void sb_dsp_setaddr(sb_dsp_t *dsp, uint16_t addr) { sb_dsp_log("sb_dsp_setaddr : %04X\n", addr); if (dsp->sb_addr != 0) { io_removehandler(dsp->sb_addr + 6, 0x0002, sb_read, NULL, NULL, sb_write, NULL, NULL, dsp); io_removehandler(dsp->sb_addr + 0xa, 0x0006, sb_read, NULL, NULL, sb_write, NULL, NULL, dsp); } dsp->sb_addr = addr; if (dsp->sb_addr != 0) { io_sethandler(dsp->sb_addr + 6, 0x0002, sb_read, NULL, NULL, sb_write, NULL, NULL, dsp); io_sethandler(dsp->sb_addr + 0xa, 0x0006, sb_read, NULL, NULL, sb_write, NULL, NULL, dsp); } } void sb_dsp_set_real_opl(sb_dsp_t *dsp, uint8_t has_real_opl) { dsp->sb_has_real_opl = has_real_opl; } void sb_dsp_set_stereo(sb_dsp_t *dsp, int stereo) { dsp->stereo = stereo; } void sb_dsp_irq_attach(sb_dsp_t *dsp, void (*irq_update)(void *priv, int set), void *priv) { dsp->irq_update = irq_update; dsp->irq_priv = priv; } void sb_dsp_dma_attach(sb_dsp_t *dsp, int (*dma_readb)(void *priv), int (*dma_readw)(void *priv), int (*dma_writeb)(void *priv, uint8_t val), int (*dma_writew)(void *priv, uint16_t val), void *priv) { dsp->dma_readb = dma_readb; dsp->dma_readw = dma_readw; dsp->dma_writeb = dma_writeb; dsp->dma_writew = dma_writew; dsp->dma_priv = priv; } static void sb_finish_dma(sb_dsp_t *dsp) { if (dsp->ess_playback_mode) { ESSreg(0xB8) &= ~0x01; dma_set_drq(dsp->sb_8_dmanum, 0); } else sb_stop_dma(dsp); } void sb_espcm_fifoctl_run(sb_dsp_t *dsp) { if (fifo_get_empty(dsp->espcm_fifo) && !dsp->sb_8_pause) { while (!fifo_get_full(dsp->espcm_fifo)) { int32_t val; val = dsp->dma_readb(dsp->dma_priv); dsp->ess_dma_counter++; fifo_write(val & 0xff, dsp->espcm_fifo); if (val & DMA_OVER) { break; } } } } void pollsb(void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; int tempi; int ref; int data[2]; timer_advance_u64(&dsp->output_timer, (uint64_t) dsp->sblatcho); if (dsp->sb_8_enable && dsp->sb_pausetime < 0 && dsp->sb_8_output) { sb_dsp_update(dsp); switch (dsp->sb_8_format) { case 0x00: /* Mono unsigned */ if (!dsp->sb_8_pause) { data[0] = dsp->dma_readb(dsp->dma_priv); /* Needed to prevent clicking in Worms, which programs the DSP to auto-init DMA but programs the DMA controller to single cycle */ if (data[0] == DMA_NODATA) break; dsp->sbdat = (int16_t) ((data[0] ^ 0x80) << 8); if (dsp->stereo) { sb_dsp_log("pollsb: Mono unsigned, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x10: /* Mono signed */ if (!dsp->sb_8_pause) { data[0] = dsp->dma_readb(dsp->dma_priv); if (data[0] == DMA_NODATA) break; dsp->sbdat = (int16_t) (data[0] << 8); if (dsp->stereo) { sb_dsp_log("pollsb: Mono signed, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", data[0], dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; dsp->sb_8_length--; dsp->ess_dma_counter++; } break; case 0x20: /* Stereo unsigned */ if (!dsp->sb_8_pause) { data[0] = dsp->dma_readb(dsp->dma_priv); data[1] = dsp->dma_readb(dsp->dma_priv); if ((data[0] == DMA_NODATA) || (data[1] == DMA_NODATA)) break; dsp->sbdatl = (int16_t) ((data[0] ^ 0x80) << 8); dsp->sbdatr = (int16_t) ((data[1] ^ 0x80) << 8); dsp->sb_8_length -= 2; dsp->ess_dma_counter += 2; } break; case 0x30: /* Stereo signed */ if (!dsp->sb_8_pause) { data[0] = dsp->dma_readb(dsp->dma_priv); data[1] = dsp->dma_readb(dsp->dma_priv); if ((data[0] == DMA_NODATA) || (data[1] == DMA_NODATA)) break; dsp->sbdatl = (int16_t) (data[0] << 8); dsp->sbdatr = (int16_t) (data[1] << 8); dsp->sb_8_length -= 2; dsp->ess_dma_counter += 2; } break; case ADPCM_4: if (!dsp->sb_8_pause) { if (dsp->sbdacpos) tempi = (dsp->sbdat2 & 0xF) + dsp->sbstep; else tempi = (dsp->sbdat2 >> 4) + dsp->sbstep; if (tempi < 0) tempi = 0; if (tempi > 63) tempi = 63; ref = dsp->sbref + scaleMap4[tempi]; if (ref > 0xff) dsp->sbref = 0xff; else if (ref < 0x00) dsp->sbref = 0x00; else dsp->sbref = ref; dsp->sbstep = (int8_t) ((dsp->sbstep + adjustMap4[tempi]) & 0xff); dsp->sbdat = (int16_t) ((dsp->sbref ^ 0x80) << 8); dsp->sbdacpos++; if (dsp->sbdacpos >= 2) { dsp->sbdacpos = 0; dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; } if (dsp->stereo) { sb_dsp_log("pollsb: ADPCM 4, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; } break; case ADPCM_26: if (!dsp->sb_8_pause) { if (!dsp->sbdacpos) tempi = (dsp->sbdat2 >> 5) + dsp->sbstep; else if (dsp->sbdacpos == 1) tempi = ((dsp->sbdat2 >> 2) & 7) + dsp->sbstep; else tempi = ((dsp->sbdat2 << 1) & 7) + dsp->sbstep; if (tempi < 0) tempi = 0; if (tempi > 39) tempi = 39; ref = dsp->sbref + scaleMap26[tempi]; if (ref > 0xff) dsp->sbref = 0xff; else if (ref < 0x00) dsp->sbref = 0x00; else dsp->sbref = ref; dsp->sbstep = (int8_t) ((dsp->sbstep + adjustMap26[tempi]) & 0xff); dsp->sbdat = (int16_t) ((dsp->sbref ^ 0x80) << 8); dsp->sbdacpos++; if (dsp->sbdacpos >= 3) { dsp->sbdacpos = 0; dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; } if (dsp->stereo) { sb_dsp_log("pollsb: ADPCM 26, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; } break; case ADPCM_2: if (!dsp->sb_8_pause) { tempi = ((dsp->sbdat2 >> ((3 - dsp->sbdacpos) * 2)) & 3) + dsp->sbstep; if (tempi < 0) tempi = 0; if (tempi > 23) tempi = 23; ref = dsp->sbref + scaleMap2[tempi]; if (ref > 0xff) dsp->sbref = 0xff; else if (ref < 0x00) dsp->sbref = 0x00; else dsp->sbref = ref; dsp->sbstep = (int8_t) ((dsp->sbstep + adjustMap2[tempi]) & 0xff); dsp->sbdat = (int16_t) ((dsp->sbref ^ 0x80) << 8); dsp->sbdacpos++; if (dsp->sbdacpos >= 4) { dsp->sbdacpos = 0; dsp->sbdat2 = dsp->dma_readb(dsp->dma_priv); dsp->sb_8_length--; dsp->ess_dma_counter++; } if (dsp->stereo) { sb_dsp_log("pollsb: ADPCM 2, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; } break; case ESPCM_4: if (dsp->espcm_sample_idx >= 19) dsp->espcm_sample_idx = 0; if (dsp->espcm_sample_idx == 0) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) break; dsp->espcm_byte_buffer[0] = fifo_read(dsp->espcm_fifo); dsp->espcm_range = dsp->espcm_byte_buffer[0] & 0x0F; tempi = dsp->espcm_byte_buffer[0] >> 4; } else if (dsp->espcm_sample_idx & 1) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) break; dsp->espcm_byte_buffer[0] = fifo_read(dsp->espcm_fifo); dsp->sb_8_length--; tempi = dsp->espcm_byte_buffer[0] & 0x0F; } else tempi = dsp->espcm_byte_buffer[0] >> 4; if (dsp->espcm_sample_idx == 18) dsp->sb_8_length--; dsp->espcm_sample_idx++; tempi |= (dsp->espcm_range << 4); data[0] = (int) espcm_range_map[tempi]; dsp->sbdat = (int16_t) (data[0] << 8); if (dsp->stereo) { sb_dsp_log("pollsb: ESPCM 4, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; break; case ESPCM_3: if (dsp->espcm_sample_idx >= 19) dsp->espcm_sample_idx = 0; if (dsp->espcm_sample_idx == 0) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) break; dsp->espcm_byte_buffer[0] = fifo_read(dsp->espcm_fifo); dsp->espcm_range = dsp->espcm_byte_buffer[0] & 0x0F; tempi = dsp->espcm_byte_buffer[0] >> 4; dsp->espcm_last_value = tempi; } else if (dsp->espcm_sample_idx == 1) { for (tempi = 0; tempi < 4; tempi++) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) break; dsp->espcm_byte_buffer[tempi] = fifo_read(dsp->espcm_fifo); dsp->sb_8_length--; } if (tempi < 4) break; dsp->espcm_table_index = dsp->espcm_byte_buffer[0] & 0x03; dsp->espcm_code_buffer[0] = (dsp->espcm_byte_buffer[0] >> 2) & 0x07; dsp->espcm_code_buffer[1] = (dsp->espcm_byte_buffer[0] >> 5) & 0x07; dsp->espcm_code_buffer[2] = (dsp->espcm_byte_buffer[1]) & 0x07; dsp->espcm_code_buffer[3] = (dsp->espcm_byte_buffer[1] >> 3) & 0x07; dsp->espcm_code_buffer[4] = ((dsp->espcm_byte_buffer[1] >> 6) & 0x03) | ((dsp->espcm_byte_buffer[2] & 0x01) << 2); dsp->espcm_code_buffer[5] = (dsp->espcm_byte_buffer[2] >> 1) & 0x07; dsp->espcm_code_buffer[6] = (dsp->espcm_byte_buffer[2] >> 4) & 0x07; dsp->espcm_code_buffer[7] = ((dsp->espcm_byte_buffer[2] >> 7) & 0x01) | ((dsp->espcm_byte_buffer[3] & 0x03) << 1); dsp->espcm_code_buffer[8] = (dsp->espcm_byte_buffer[3] >> 2) & 0x07; dsp->espcm_code_buffer[9] = (dsp->espcm_byte_buffer[3] >> 5) & 0x07; tempi = (dsp->espcm_table_index << 8) | (dsp->espcm_last_value << 3) | dsp->espcm_code_buffer[0]; tempi = espcm3_dpcm_tables[tempi]; dsp->espcm_last_value = tempi; } else if (dsp->espcm_sample_idx == 11) { for (tempi = 1; tempi < 4; tempi++) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) break; dsp->espcm_byte_buffer[tempi] = fifo_read(dsp->espcm_fifo); dsp->sb_8_length--; } if (tempi < 4) break; dsp->espcm_code_buffer[0] = (dsp->espcm_byte_buffer[1]) & 0x07; dsp->espcm_code_buffer[1] = (dsp->espcm_byte_buffer[1] >> 3) & 0x07; dsp->espcm_code_buffer[2] = ((dsp->espcm_byte_buffer[1] >> 6) & 0x03) | ((dsp->espcm_byte_buffer[2] & 0x01) << 2); dsp->espcm_code_buffer[3] = (dsp->espcm_byte_buffer[2] >> 1) & 0x07; dsp->espcm_code_buffer[4] = (dsp->espcm_byte_buffer[2] >> 4) & 0x07; dsp->espcm_code_buffer[5] = ((dsp->espcm_byte_buffer[2] >> 7) & 0x01) | ((dsp->espcm_byte_buffer[3] & 0x03) << 1); dsp->espcm_code_buffer[6] = (dsp->espcm_byte_buffer[3] >> 2) & 0x07; dsp->espcm_code_buffer[7] = (dsp->espcm_byte_buffer[3] >> 5) & 0x07; tempi = (dsp->espcm_table_index << 8) | (dsp->espcm_last_value << 3) | dsp->espcm_code_buffer[0]; tempi = espcm3_dpcm_tables[tempi]; dsp->espcm_last_value = tempi; } else { tempi = (dsp->espcm_table_index << 8) | (dsp->espcm_last_value << 3) | dsp->espcm_code_buffer[(dsp->espcm_sample_idx - 1) % 10]; tempi = espcm3_dpcm_tables[tempi]; dsp->espcm_last_value = tempi; } if (dsp->espcm_sample_idx == 18) { dsp->sb_8_length--; } dsp->espcm_sample_idx++; tempi |= (dsp->espcm_range << 4); data[0] = (int) (espcm_range_map[tempi]); dsp->sbdat = (int16_t) (data[0] << 8); if (dsp->stereo) { sb_dsp_log("pollsb: ESPCM 3, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; break; case ESPCM_1: if (dsp->espcm_sample_idx >= 19) dsp->espcm_sample_idx = 0; if (dsp->espcm_sample_idx == 0) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) break; dsp->espcm_byte_buffer[0] = fifo_read(dsp->espcm_fifo); dsp->espcm_range = dsp->espcm_byte_buffer[0] & 0x0F; dsp->espcm_byte_buffer[0] >>= 5; tempi = dsp->espcm_byte_buffer[0] & 1 ? 0xC : 0x4; dsp->espcm_byte_buffer[0] >>= 1; } else if ((dsp->espcm_sample_idx == 3) | (dsp->espcm_sample_idx == 11)) { sb_espcm_fifoctl_run(dsp); if (fifo_get_empty(dsp->espcm_fifo)) { break; } dsp->espcm_byte_buffer[0] = fifo_read(dsp->espcm_fifo); dsp->sb_8_length--; tempi = dsp->espcm_byte_buffer[0] & 1 ? 0xC : 0x4; dsp->espcm_byte_buffer[0] >>= 1; } else { tempi = dsp->espcm_byte_buffer[0] & 1 ? 0xC : 0x4; dsp->espcm_byte_buffer[0] >>= 1; } if (dsp->espcm_sample_idx == 18) dsp->sb_8_length--; dsp->espcm_sample_idx++; tempi |= (dsp->espcm_range << 4); data[0] = (int) espcm_range_map[tempi]; dsp->sbdat = (int16_t) (data[0] << 8); if (dsp->stereo) { sb_dsp_log("pollsb: ESPCM 1, dsp->stereo, %s channel, %04X\n", dsp->sbleftright ? "left" : "right", dsp->sbdat); if (dsp->sbleftright) dsp->sbdatl = dsp->sbdat; else dsp->sbdatr = dsp->sbdat; dsp->sbleftright = !dsp->sbleftright; } else dsp->sbdatl = dsp->sbdatr = dsp->sbdat; break; default: break; } if (dsp->sb_8_length < 0 && !dsp->ess_playback_mode) { if (dsp->sb_8_autoinit) dsp->sb_8_length = dsp->sb_8_origlength = dsp->sb_8_autolen; else { dsp->sb_8_enable = 0; timer_disable(&dsp->output_timer); sb_finish_dma(dsp); } sb_irq(dsp, 1); dsp->ess_irq_generic = true; } if (dsp->ess_dma_counter > 0xffff) { if (dsp->ess_playback_mode) { if (!dsp->sb_8_autoinit) { dsp->sb_8_enable = 0; timer_disable(&dsp->output_timer); sb_finish_dma(dsp); } if (ESSreg(0xB1) & 0x40) { sb_irq(dsp, 1); dsp->ess_irq_dmactr = true; } } const uint32_t temp = dsp->ess_dma_counter & 0xffff; dsp->ess_dma_counter = sb_ess_get_dma_counter(dsp); dsp->ess_dma_counter += temp; } } if (dsp->sb_16_enable && !dsp->sb_16_pause && (dsp->sb_pausetime < 0LL) && dsp->sb_16_output) { sb_dsp_update(dsp); switch (dsp->sb_16_format) { case 0x00: /* Mono unsigned */ data[0] = dsp->dma_readw(dsp->dma_priv); if (data[0] == DMA_NODATA) break; dsp->sbdatl = dsp->sbdatr = (int16_t) ((data[0] & 0xffff) ^ 0x8000); dsp->sb_16_length--; dsp->ess_dma_counter += 2; break; case 0x10: /* Mono signed */ data[0] = dsp->dma_readw(dsp->dma_priv); if (data[0] == DMA_NODATA) break; dsp->sbdatl = dsp->sbdatr = (int16_t) (data[0] & 0xffff); dsp->sb_16_length--; dsp->ess_dma_counter += 2; break; case 0x20: /* Stereo unsigned */ data[0] = dsp->dma_readw(dsp->dma_priv); data[1] = dsp->dma_readw(dsp->dma_priv); if ((data[0] == DMA_NODATA) || (data[1] == DMA_NODATA)) break; dsp->sbdatl = (int16_t) ((data[0] & 0xffff) ^ 0x8000); dsp->sbdatr = (int16_t) ((data[1] & 0xffff) ^ 0x8000); dsp->sb_16_length -= 2; dsp->ess_dma_counter += 4; break; case 0x30: /* Stereo signed */ data[0] = dsp->dma_readw(dsp->dma_priv); data[1] = dsp->dma_readw(dsp->dma_priv); if ((data[0] == DMA_NODATA) || (data[1] == DMA_NODATA)) break; dsp->sbdatl = (int16_t) (data[0] & 0xffff); dsp->sbdatr = (int16_t) (data[1] & 0xffff); dsp->sb_16_length -= 2; dsp->ess_dma_counter += 4; break; default: break; } if (dsp->sb_16_length < 0 && !dsp->ess_playback_mode) { sb_dsp_log("16DMA over %i\n", dsp->sb_16_autoinit); if (dsp->sb_16_autoinit) dsp->sb_16_length = dsp->sb_16_origlength = dsp->sb_16_autolen; else { dsp->sb_16_enable = 0; timer_disable(&dsp->output_timer); sb_finish_dma(dsp); } sb_irq(dsp, 0); dsp->ess_irq_generic = true; } if (dsp->ess_dma_counter > 0xffff) { if (dsp->ess_playback_mode) { if (!dsp->sb_16_autoinit) { dsp->sb_16_enable = 0; timer_disable(&dsp->output_timer); sb_finish_dma(dsp); } if (ESSreg(0xB1) & 0x40) { sb_irq(dsp, 0); dsp->ess_irq_dmactr = true; } } const uint32_t temp = dsp->ess_dma_counter & 0xffff; dsp->ess_dma_counter = sb_ess_get_dma_counter(dsp); dsp->ess_dma_counter += temp; } } if (dsp->sb_pausetime > -1) { dsp->sb_pausetime--; if (dsp->sb_pausetime < 0) { sb_irq(dsp, 1); dsp->ess_irq_generic = true; if (!dsp->sb_8_enable) timer_disable(&dsp->output_timer); sb_dsp_log("SB pause over\n"); } } } void sb_poll_i(void *priv) { sb_dsp_t *dsp = (sb_dsp_t *) priv; int processed = 0; timer_advance_u64(&dsp->input_timer, (uint64_t) dsp->sblatchi); if (dsp->sb_8_enable && !dsp->sb_8_pause && dsp->sb_pausetime < 0 && !dsp->sb_8_output) { switch (dsp->sb_8_format) { case 0x00: /* Mono unsigned As the manual says, only the left channel is recorded */ dsp->dma_writeb(dsp->dma_priv, (dsp->record_buffer[dsp->record_pos_read] >> 8) ^ 0x80); dsp->sb_8_length--; dsp->ess_dma_counter++; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case 0x10: /* Mono signed As the manual says, only the left channel is recorded */ dsp->dma_writeb(dsp->dma_priv, (dsp->record_buffer[dsp->record_pos_read] >> 8)); dsp->sb_8_length--; dsp->ess_dma_counter++; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case 0x20: /* Stereo unsigned */ dsp->dma_writeb(dsp->dma_priv, (dsp->record_buffer[dsp->record_pos_read] >> 8) ^ 0x80); dsp->dma_writeb(dsp->dma_priv, (dsp->record_buffer[dsp->record_pos_read + 1] >> 8) ^ 0x80); dsp->sb_8_length -= 2; dsp->ess_dma_counter += 2; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case 0x30: /* Stereo signed */ dsp->dma_writeb(dsp->dma_priv, (dsp->record_buffer[dsp->record_pos_read] >> 8)); dsp->dma_writeb(dsp->dma_priv, (dsp->record_buffer[dsp->record_pos_read + 1] >> 8)); dsp->sb_8_length -= 2; dsp->ess_dma_counter += 2; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case ESPCM_4E: /* I assume the real hardware double-buffers the blocks or something like that. We're not gonna do that here. */ dsp->espcm_sample_buffer[dsp->espcm_sample_idx] = (int8_t) (dsp->record_buffer[dsp->record_pos_read] >> 8); dsp->espcm_sample_idx++; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; if (dsp->espcm_sample_idx >= 19) { int i, table_addr; int8_t min_sample = 127, max_sample = -128, s; for (i = 0; i < 19; i++) { s = dsp->espcm_sample_buffer[i]; if (s < min_sample) min_sample = s; if (s > max_sample) max_sample = s; } if (min_sample < 0) { if (min_sample == -128) min_sample = 127; /* Clip it to make it fit into int8_t. */ else min_sample = (int8_t) -min_sample; } if (max_sample < 0) { if (max_sample == -128) max_sample = 127; /* Clip it to make it fit into int8_t. */ else max_sample = (int8_t) -max_sample; } if (min_sample > max_sample) max_sample = min_sample; for (table_addr = 15; table_addr < 256; table_addr += 16) { if (max_sample <= espcm_range_map[table_addr]) break; } dsp->espcm_range = table_addr >> 4; for (i = 0; i < 19; i++) { int last_sigma = 9999; table_addr = dsp->espcm_range << 4; s = dsp->espcm_sample_buffer[i]; for (; (table_addr >> 4) == dsp->espcm_range; table_addr++) { int sigma = espcm_range_map[table_addr] - s; if (sigma < 0) sigma = -sigma; if (sigma > last_sigma) break; last_sigma = sigma; } table_addr--; dsp->espcm_code_buffer[i] = table_addr & 0x0F; } uint8_t b = dsp->espcm_range | (dsp->espcm_code_buffer[0] << 4); dsp->dma_writeb(dsp->dma_priv, b); dsp->sb_8_length--; dsp->ess_dma_counter++; for (i = 1; i < 10; i++) { b = dsp->espcm_code_buffer[i * 2 - 1] | (dsp->espcm_code_buffer[i * 2] << 4); dsp->dma_writeb(dsp->dma_priv, b); dsp->sb_8_length--; dsp->ess_dma_counter++; } dsp->espcm_sample_idx = 0; } default: break; } if (dsp->sb_8_length < 0 && !dsp->ess_playback_mode) { if (dsp->sb_8_autoinit) dsp->sb_8_length = dsp->sb_8_origlength = dsp->sb_8_autolen; else { dsp->sb_8_enable = 0; timer_disable(&dsp->input_timer); sb_finish_dma(dsp); } sb_irq(dsp, 1); dsp->ess_irq_generic = true; } if (dsp->ess_dma_counter > 0xffff) { if (dsp->ess_playback_mode) { if (!dsp->sb_8_autoinit) { dsp->sb_8_enable = 0; timer_disable(&dsp->input_timer); sb_finish_dma(dsp); } if (ESSreg(0xB1) & 0x40) { sb_irq(dsp, 1); dsp->ess_irq_dmactr = true; } } uint32_t temp = dsp->ess_dma_counter & 0xffff; dsp->ess_dma_counter = sb_ess_get_dma_counter(dsp); dsp->ess_dma_counter += temp; } processed = 1; } if (dsp->sb_16_enable && !dsp->sb_16_pause && (dsp->sb_pausetime < 0LL) && !dsp->sb_16_output) { switch (dsp->sb_16_format) { case 0x00: /* Unsigned mono. As the manual says, only the left channel is recorded */ if (dsp->dma_writew(dsp->dma_priv, dsp->record_buffer[dsp->record_pos_read] ^ 0x8000)) return; dsp->sb_16_length--; dsp->ess_dma_counter += 2; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case 0x10: /* Signed mono. As the manual says, only the left channel is recorded */ if (dsp->dma_writew(dsp->dma_priv, dsp->record_buffer[dsp->record_pos_read])) return; dsp->sb_16_length--; dsp->ess_dma_counter += 2; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case 0x20: /* Unsigned stereo */ if (dsp->dma_writew(dsp->dma_priv, dsp->record_buffer[dsp->record_pos_read] ^ 0x8000)) return; dsp->dma_writew(dsp->dma_priv, dsp->record_buffer[dsp->record_pos_read + 1] ^ 0x8000); dsp->sb_16_length -= 2; dsp->ess_dma_counter += 4; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; case 0x30: /* Signed stereo */ if (dsp->dma_writew(dsp->dma_priv, dsp->record_buffer[dsp->record_pos_read])) return; dsp->dma_writew(dsp->dma_priv, dsp->record_buffer[dsp->record_pos_read + 1]); dsp->sb_16_length -= 2; dsp->ess_dma_counter += 4; dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; break; default: break; } if (dsp->sb_16_length < 0 && !dsp->ess_playback_mode) { if (dsp->sb_16_autoinit) dsp->sb_16_length = dsp->sb_16_origlength = dsp->sb_16_autolen; else { dsp->sb_16_enable = 0; timer_disable(&dsp->input_timer); sb_finish_dma(dsp); } sb_irq(dsp, 0); dsp->ess_irq_generic = true; } if (dsp->ess_dma_counter > 0xffff) { if (dsp->ess_playback_mode) { if (!dsp->sb_16_autoinit) { dsp->sb_16_enable = 0; timer_disable(&dsp->input_timer); sb_finish_dma(dsp); } if (ESSreg(0xB1) & 0x40) { sb_irq(dsp, 0); dsp->ess_irq_dmactr = true; } } uint32_t temp = dsp->ess_dma_counter & 0xffff; dsp->ess_dma_counter = sb_ess_get_dma_counter(dsp); dsp->ess_dma_counter += temp; } processed = 1; } /* Assume this is direct mode */ if (!processed) { dsp->record_pos_read += 2; dsp->record_pos_read &= 0xFFFF; } } void sb_dsp_update(sb_dsp_t *dsp) { if (dsp->muted) { dsp->sbdatl = 0; dsp->sbdatr = 0; } for (; dsp->pos < sound_pos_global; dsp->pos++) { dsp->buffer[dsp->pos * 2] = dsp->sbdatl; dsp->buffer[dsp->pos * 2 + 1] = dsp->sbdatr; } } void sb_dsp_close(UNUSED(sb_dsp_t *dsp)) { // } ```
/content/code_sandbox/src/sound/snd_sb_dsp.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
37,045
```c #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/snd_sn76489.h> #include <86box/timer.h> #include <86box/plat_unused.h> typedef struct ps1snd_t { sn76489_t sn76489; uint8_t status; uint8_t ctrl; uint64_t timer_latch; pc_timer_t timer_count; int timer_enable; uint8_t fifo[2048]; int fifo_read_idx; int fifo_write_idx; int fifo_threshold; uint8_t dac_val; int16_t buffer[SOUNDBUFLEN]; int pos; } ps1snd_t; static void ps1snd_update_irq_status(ps1snd_t *snd) { if (((snd->status & snd->ctrl) & 0x12) && (snd->ctrl & 0x01)) picint(1 << 7); else picintc(1 << 7); } static uint8_t ps1snd_read(uint16_t port, void *priv) { ps1snd_t *ps1snd = (ps1snd_t *) priv; uint8_t ret = 0xff; switch (port & 7) { case 0: /* ADC data */ ps1snd->status &= ~0x10; ps1snd_update_irq_status(ps1snd); ret = 0; break; case 2: /* status */ ret = ps1snd->status; ret |= (ps1snd->ctrl & 0x01); if ((ps1snd->fifo_write_idx - ps1snd->fifo_read_idx) >= 2048) ret |= 0x08; /* FIFO full */ if (ps1snd->fifo_read_idx == ps1snd->fifo_write_idx) ret |= 0x04; /* FIFO empty */ break; case 3: /* FIFO timer */ /* * The PS/1 Technical Reference says this should return * thecurrent value, but the PS/1 BIOS and Stunt Island * expect it not to change. */ ret = ps1snd->timer_latch; break; case 4: case 5: case 6: case 7: ret = 0; break; default: break; } return ret; } static void ps1snd_write(uint16_t port, uint8_t val, void *priv) { ps1snd_t *ps1snd = (ps1snd_t *) priv; switch (port & 7) { case 0: /* DAC output */ if ((ps1snd->fifo_write_idx - ps1snd->fifo_read_idx) < 2048) { ps1snd->fifo[ps1snd->fifo_write_idx & 2047] = val; ps1snd->fifo_write_idx++; } break; case 2: /* control */ ps1snd->ctrl = val; if (!(val & 0x02)) ps1snd->status &= ~0x02; ps1snd_update_irq_status(ps1snd); break; case 3: /* timer reload value */ ps1snd->timer_latch = val; if (val) timer_set_delay_u64(&ps1snd->timer_count, ((0xff - val) * TIMER_USEC)); else timer_disable(&ps1snd->timer_count); break; case 4: /* almost empty */ ps1snd->fifo_threshold = val * 4; break; default: break; } } static void ps1snd_update(ps1snd_t *ps1snd) { for (; ps1snd->pos < sound_pos_global; ps1snd->pos++) ps1snd->buffer[ps1snd->pos] = (int8_t) (ps1snd->dac_val ^ 0x80) * 0x20; } static void ps1snd_callback(void *priv) { ps1snd_t *ps1snd = (ps1snd_t *) priv; ps1snd_update(ps1snd); if (ps1snd->fifo_read_idx != ps1snd->fifo_write_idx) { ps1snd->dac_val = ps1snd->fifo[ps1snd->fifo_read_idx & 2047]; ps1snd->fifo_read_idx++; } if ((ps1snd->fifo_write_idx - ps1snd->fifo_read_idx) == ps1snd->fifo_threshold) ps1snd->status |= 0x02; /*FIFO almost empty*/ ps1snd->status |= 0x10; /*ADC data ready*/ ps1snd_update_irq_status(ps1snd); timer_advance_u64(&ps1snd->timer_count, ps1snd->timer_latch * TIMER_USEC); } static void ps1snd_get_buffer(int32_t *buffer, int len, void *priv) { ps1snd_t *ps1snd = (ps1snd_t *) priv; ps1snd_update(ps1snd); for (int c = 0; c < len * 2; c++) buffer[c] += ps1snd->buffer[c >> 1]; ps1snd->pos = 0; } static void * ps1snd_init(UNUSED(const device_t *info)) { ps1snd_t *ps1snd = malloc(sizeof(ps1snd_t)); memset(ps1snd, 0x00, sizeof(ps1snd_t)); sn76489_init(&ps1snd->sn76489, 0x0205, 0x0001, SN76496, 4000000); io_sethandler(0x0200, 1, ps1snd_read, NULL, NULL, ps1snd_write, NULL, NULL, ps1snd); io_sethandler(0x0202, 6, ps1snd_read, NULL, NULL, ps1snd_write, NULL, NULL, ps1snd); timer_add(&ps1snd->timer_count, ps1snd_callback, ps1snd, 0); sound_add_handler(ps1snd_get_buffer, ps1snd); return ps1snd; } static void ps1snd_close(void *priv) { ps1snd_t *ps1snd = (ps1snd_t *) priv; free(ps1snd); } const device_t ps1snd_device = { .name = "IBM PS/1 Audio Card", .internal_name = "ps1snd", .flags = 0, .local = 0, .init = ps1snd_init, .close = ps1snd_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; ```
/content/code_sandbox/src/sound/snd_ps1.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,581
```c #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/mca.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/snd_opl.h> #include <86box/plat_unused.h> #ifdef ENABLE_ADLIB_LOG int adlib_do_log = ENABLE_ADLIB_LOG; static void adlib_log(const char *fmt, ...) { va_list ap; if (adlib_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define adlib_log(fmt, ...) #endif typedef struct adlib_t { fm_drv_t opl; uint8_t pos_regs[8]; } adlib_t; static void adlib_get_buffer(int32_t *buffer, int len, void *priv) { adlib_t *adlib = (adlib_t *) priv; const int32_t *opl_buf = adlib->opl.update(adlib->opl.priv); for (int c = 0; c < len * 2; c++) buffer[c] += opl_buf[c]; adlib->opl.reset_buffer(adlib->opl.priv); } uint8_t adlib_mca_read(int port, void *priv) { const adlib_t *adlib = (adlib_t *) priv; adlib_log("adlib_mca_read: port=%04x\n", port); return adlib->pos_regs[port & 7]; } void adlib_mca_write(int port, uint8_t val, void *priv) { adlib_t *adlib = (adlib_t *) priv; if (port < 0x102) return; adlib_log("adlib_mca_write: port=%04x val=%02x\n", port, val); switch (port) { case 0x102: if ((adlib->pos_regs[2] & 1) && !(val & 1)) io_removehandler(0x0388, 0x0002, adlib->opl.read, NULL, NULL, adlib->opl.write, NULL, NULL, adlib->opl.priv); if (!(adlib->pos_regs[2] & 1) && (val & 1)) io_sethandler(0x0388, 0x0002, adlib->opl.read, NULL, NULL, adlib->opl.write, NULL, NULL, adlib->opl.priv); break; default: break; } adlib->pos_regs[port & 7] = val; } uint8_t adlib_mca_feedb(void *priv) { const adlib_t *adlib = (adlib_t *) priv; return (adlib->pos_regs[2] & 1); } void * adlib_init(UNUSED(const device_t *info)) { adlib_t *adlib = malloc(sizeof(adlib_t)); memset(adlib, 0, sizeof(adlib_t)); adlib_log("adlib_init\n"); fm_driver_get(FM_YM3812, &adlib->opl); io_sethandler(0x0388, 0x0002, adlib->opl.read, NULL, NULL, adlib->opl.write, NULL, NULL, adlib->opl.priv); music_add_handler(adlib_get_buffer, adlib); return adlib; } void * adlib_mca_init(const device_t *info) { adlib_t *adlib = adlib_init(info); io_removehandler(0x0388, 0x0002, adlib->opl.read, NULL, NULL, adlib->opl.write, NULL, NULL, adlib->opl.priv); mca_add(adlib_mca_read, adlib_mca_write, adlib_mca_feedb, NULL, adlib); adlib->pos_regs[0] = 0xd7; adlib->pos_regs[1] = 0x70; return adlib; } void adlib_close(void *priv) { adlib_t *adlib = (adlib_t *) priv; free(adlib); } const device_t adlib_device = { .name = "AdLib", .internal_name = "adlib", .flags = DEVICE_ISA, .local = 0, .init = adlib_init, .close = adlib_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; const device_t adlib_mca_device = { .name = "AdLib (MCA)", .internal_name = "adlib_mca", .flags = DEVICE_MCA, .local = 0, .init = adlib_mca_init, .close = adlib_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; ```
/content/code_sandbox/src/sound/snd_adlib.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,179
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Interface to the OpenAL sound processing library. * * * * Authors: Sarah Walker, <path_to_url * Miran Grca, <mgrca8@gmail.com> * */ #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #undef AL_API #undef ALC_API #define AL_LIBTYPE_STATIC #define ALC_LIBTYPE_STATIC #include "AL/al.h" #include "AL/alc.h" #include "AL/alext.h" #include <86box/86box.h> #include <86box/midi.h> #include <86box/sound.h> #include <86box/plat_unused.h> #define FREQ SOUND_FREQ #define BUFLEN SOUNDBUFLEN ALuint buffers[4]; /* front and back buffers */ ALuint buffers_music[4]; /* front and back buffers */ ALuint buffers_wt[4]; /* front and back buffers */ ALuint buffers_cd[4]; /* front and back buffers */ ALuint buffers_midi[4]; /* front and back buffers */ static ALuint source[5]; /* audio source */ static int midi_freq = 44100; static int midi_buf_size = 4410; static int initialized = 0; static int sources = 2; static ALCcontext *Context; static ALCdevice *Device; void al_set_midi(const int freq, const int buf_size) { midi_freq = freq; midi_buf_size = buf_size; } ALvoid alutInit(UNUSED(ALint *argc), UNUSED(ALbyte **argv)) { /* Open device */ Device = alcOpenDevice((ALCchar *) ""); if (Device != NULL) { /* Create context(s) */ Context = alcCreateContext(Device, NULL); if (Context != NULL) { /* Set active context */ alcMakeContextCurrent(Context); } } } ALvoid alutExit(ALvoid) { if (Context != NULL) { /* Disable context */ alcMakeContextCurrent(NULL); /* Release context(s) */ alcDestroyContext(Context); if (Device != NULL) { /* Close device */ alcCloseDevice(Device); } } } void closeal(void) { if (!initialized) return; alSourceStopv(sources, source); alDeleteSources(sources, source); if (sources == 4) alDeleteBuffers(4, buffers_midi); alDeleteBuffers(4, buffers_cd); alDeleteBuffers(4, buffers_music); alDeleteBuffers(4, buffers); alutExit(); initialized = 0; } void inital(void) { float *buf = NULL; float *music_buf = NULL; float *wt_buf = NULL; float *cd_buf = NULL; float *midi_buf = NULL; int16_t *buf_int16 = NULL; int16_t *music_buf_int16 = NULL; int16_t *wt_buf_int16 = NULL; int16_t *cd_buf_int16 = NULL; int16_t *midi_buf_int16 = NULL; int init_midi = 0; if (initialized) return; alutInit(0, 0); atexit(closeal); const char *mdn = midi_out_device_get_internal_name(midi_output_device_current); if ((strcmp(mdn, "none") != 0) && (strcmp(mdn, SYSTEM_MIDI_INTERNAL_NAME) != 0)) init_midi = 1; /* If the device is neither none, nor system MIDI, initialize the MIDI buffer and source, otherwise, do not. */ sources = 4 + !!init_midi; if (sound_is_float) { buf = (float *) calloc((BUFLEN << 1), sizeof(float)); music_buf = (float *) calloc((MUSICBUFLEN << 1), sizeof(float)); wt_buf = (float *) calloc((WTBUFLEN << 1), sizeof(float)); cd_buf = (float *) calloc((CD_BUFLEN << 1), sizeof(float)); if (init_midi) midi_buf = (float *) calloc(midi_buf_size, sizeof(float)); } else { buf_int16 = (int16_t *) calloc((BUFLEN << 1), sizeof(int16_t)); music_buf_int16 = (int16_t *) calloc((MUSICBUFLEN << 1), sizeof(int16_t)); wt_buf_int16 = (int16_t *) calloc((WTBUFLEN << 1), sizeof(int16_t)); cd_buf_int16 = (int16_t *) calloc((CD_BUFLEN << 1), sizeof(int16_t)); if (init_midi) midi_buf_int16 = (int16_t *) calloc(midi_buf_size, sizeof(int16_t)); } alGenBuffers(4, buffers); alGenBuffers(4, buffers_cd); alGenBuffers(4, buffers_music); alGenBuffers(4, buffers_wt); if (init_midi) alGenBuffers(4, buffers_midi); if (init_midi) alGenSources(5, source); else alGenSources(4, source); alSource3f(source[0], AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(source[0], AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSource3f(source[0], AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSourcef(source[0], AL_ROLLOFF_FACTOR, 0.0f); alSourcei(source[0], AL_SOURCE_RELATIVE, AL_TRUE); alSource3f(source[1], AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(source[1], AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSource3f(source[1], AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSourcef(source[1], AL_ROLLOFF_FACTOR, 0.0f); alSourcei(source[1], AL_SOURCE_RELATIVE, AL_TRUE); alSource3f(source[2], AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(source[2], AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSource3f(source[2], AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSourcef(source[2], AL_ROLLOFF_FACTOR, 0.0f); alSourcei(source[2], AL_SOURCE_RELATIVE, AL_TRUE); alSource3f(source[3], AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(source[3], AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSource3f(source[3], AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSourcef(source[3], AL_ROLLOFF_FACTOR, 0.0f); alSourcei(source[3], AL_SOURCE_RELATIVE, AL_TRUE); if (init_midi) { alSource3f(source[4], AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(source[4], AL_VELOCITY, 0.0f, 0.0f, 0.0f); alSource3f(source[4], AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSourcef(source[4], AL_ROLLOFF_FACTOR, 0.0f); alSourcei(source[4], AL_SOURCE_RELATIVE, AL_TRUE); } if (sound_is_float) { memset(buf, 0, BUFLEN * 2 * sizeof(float)); memset(cd_buf, 0, CD_BUFLEN * 2 * sizeof(float)); memset(music_buf, 0, MUSICBUFLEN * 2 * sizeof(float)); memset(wt_buf, 0, WTBUFLEN * 2 * sizeof(float)); if (init_midi) memset(midi_buf, 0, midi_buf_size * sizeof(float)); } else { memset(buf_int16, 0, BUFLEN * 2 * sizeof(int16_t)); memset(cd_buf_int16, 0, CD_BUFLEN * 2 * sizeof(int16_t)); memset(music_buf_int16, 0, MUSICBUFLEN * 2 * sizeof(int16_t)); memset(wt_buf_int16, 0, WTBUFLEN * 2 * sizeof(int16_t)); if (init_midi) memset(midi_buf_int16, 0, midi_buf_size * sizeof(int16_t)); } for (uint8_t c = 0; c < 4; c++) { if (sound_is_float) { alBufferData(buffers[c], AL_FORMAT_STEREO_FLOAT32, buf, BUFLEN * 2 * sizeof(float), FREQ); alBufferData(buffers_music[c], AL_FORMAT_STEREO_FLOAT32, music_buf, MUSICBUFLEN * 2 * sizeof(float), MUSIC_FREQ); alBufferData(buffers_wt[c], AL_FORMAT_STEREO_FLOAT32, wt_buf, WTBUFLEN * 2 * sizeof(float), WT_FREQ); alBufferData(buffers_cd[c], AL_FORMAT_STEREO_FLOAT32, cd_buf, CD_BUFLEN * 2 * sizeof(float), CD_FREQ); if (init_midi) alBufferData(buffers_midi[c], AL_FORMAT_STEREO_FLOAT32, midi_buf, midi_buf_size * (int) sizeof(float), midi_freq); } else { alBufferData(buffers[c], AL_FORMAT_STEREO16, buf_int16, BUFLEN * 2 * sizeof(int16_t), FREQ); alBufferData(buffers_music[c], AL_FORMAT_STEREO16, music_buf_int16, MUSICBUFLEN * 2 * sizeof(int16_t), MUSIC_FREQ); alBufferData(buffers_wt[c], AL_FORMAT_STEREO16, wt_buf_int16, WTBUFLEN * 2 * sizeof(int16_t), WT_FREQ); alBufferData(buffers_cd[c], AL_FORMAT_STEREO16, cd_buf_int16, CD_BUFLEN * 2 * sizeof(int16_t), CD_FREQ); if (init_midi) alBufferData(buffers_midi[c], AL_FORMAT_STEREO16, midi_buf_int16, midi_buf_size * (int) sizeof(int16_t), midi_freq); } } alSourceQueueBuffers(source[0], 4, buffers); alSourceQueueBuffers(source[1], 4, buffers_music); alSourceQueueBuffers(source[2], 4, buffers_wt); alSourceQueueBuffers(source[3], 4, buffers_cd); if (init_midi) alSourceQueueBuffers(source[4], 4, buffers_midi); alSourcePlay(source[0]); alSourcePlay(source[1]); alSourcePlay(source[2]); alSourcePlay(source[3]); if (init_midi) alSourcePlay(source[4]); if (sound_is_float) { if (init_midi) free(midi_buf); free(cd_buf); free(wt_buf); free(music_buf); free(buf); } else { if (init_midi) free(midi_buf_int16); free(cd_buf_int16); free(wt_buf_int16); free(music_buf_int16); free(buf_int16); } initialized = 1; } void givealbuffer_common(const void *buf, const uint8_t src, const int size, const int freq) { int processed; int state; ALuint buffer; if (!initialized) return; alGetSourcei(source[src], AL_SOURCE_STATE, &state); if (state == 0x1014) { alSourcePlay(source[src]); } alGetSourcei(source[src], AL_BUFFERS_PROCESSED, &processed); if (processed >= 1) { const double gain = pow(10.0, (double) sound_gain / 20.0); alListenerf(AL_GAIN, (float) gain); alSourceUnqueueBuffers(source[src], 1, &buffer); if (sound_is_float) alBufferData(buffer, AL_FORMAT_STEREO_FLOAT32, buf, size * (int) sizeof(float), freq); else alBufferData(buffer, AL_FORMAT_STEREO16, buf, size * (int) sizeof(int16_t), freq); alSourceQueueBuffers(source[src], 1, &buffer); } } void givealbuffer(const void *buf) { givealbuffer_common(buf, 0, BUFLEN << 1, FREQ); } void givealbuffer_music(const void *buf) { givealbuffer_common(buf, 1, MUSICBUFLEN << 1, MUSIC_FREQ); } void givealbuffer_wt(const void *buf) { givealbuffer_common(buf, 2, WTBUFLEN << 1, WT_FREQ); } void givealbuffer_cd(const void *buf) { givealbuffer_common(buf, 3, CD_BUFLEN << 1, CD_FREQ); } void givealbuffer_midi(const void *buf, const uint32_t size) { givealbuffer_common(buf, 4, (int) size, midi_freq); } ```
/content/code_sandbox/src/sound/openal.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,127
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * AD1848 / CS4248 / CS4231 (Windows Sound System) codec emulation. * * * * Authors: Sarah Walker, <path_to_url * TheCollector1995, <mariogplayer@gmail.com> * RichardG, <richardg867@gmail.com> * */ #include <math.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/dma.h> #include <86box/pic.h> #include <86box/timer.h> #include <86box/sound.h> #include <86box/snd_ad1848.h> #include <86box/plat_fallthrough.h> #define CS4231 0x80 #define CS4236 0x03 static int ad1848_vols_7bits[128]; static double ad1848_vols_5bits_aux_gain[32]; /* Borrowed from snd_sb_dsp */ extern int8_t scaleMap4[64]; extern uint8_t adjustMap4[64]; void ad1848_setirq(ad1848_t *ad1848, int irq) { ad1848->irq = irq; } void ad1848_setdma(ad1848_t *ad1848, int newdma) { ad1848->dma = newdma; } void ad1848_updatevolmask(ad1848_t *ad1848) { if ((ad1848->type >= AD1848_TYPE_CS4235) && ((ad1848->xregs[4] & 0x10) || ad1848->wten)) ad1848->wave_vol_mask = 0x3f; else ad1848->wave_vol_mask = 0x7f; } static double ad1848_get_default_freq(ad1848_t *ad1848) { double freq = (ad1848->regs[8] & 1) ? 16934400.0 : 24576000.0; switch ((ad1848->regs[8] >> 1) & 7) { default: break; case 0: freq /= 3072.0; break; case 1: freq /= 1536.0; break; case 2: freq /= 896.0; break; case 3: freq /= 768.0; break; case 4: freq /= 448.0; break; case 5: freq /= 384.0; break; case 6: freq /= 512.0; break; case 7: freq /= 2560.0; break; } return freq; } static void ad1848_updatefreq(ad1848_t *ad1848) { double freq; if (ad1848->type >= AD1848_TYPE_CS4235) { if (ad1848->xregs[11] & 0x20) { freq = 16934400.0; switch (ad1848->xregs[13]) { default: freq /= 16.0 * MAX(ad1848->xregs[13], 21); break; case 1: freq /= 353.0; break; case 2: freq /= 529.0; break; case 3: freq /= 617.0; break; case 4: freq /= 1058.0; break; case 5: freq /= 1764.0; break; case 6: freq /= 2117.0; break; case 7: freq /= 2558.0; break; } } else if (ad1848->regs[22] & 0x80) { const uint8_t set = (ad1848->regs[22] >> 1) & 0x3f; freq = (ad1848->regs[22] & 1) ? 33868800.0 : 49152000.0; switch (ad1848->regs[10] & 0x30) { default: break; case 0x00: freq /= 128 * set; break; case 0x10: freq /= 64 * set; break; case 0x20: freq /= 256 * set; break; } } else freq = ad1848_get_default_freq(ad1848); } else freq = ad1848_get_default_freq(ad1848); ad1848->freq = (int) trunc(freq); ad1848->timer_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / (double) ad1848->freq)); } uint8_t ad1848_read(uint16_t addr, void *priv) { ad1848_t *ad1848 = (ad1848_t *) priv; uint8_t ret = 0xff; switch (addr & 3) { case 0: /* Index */ ret = ad1848->index | ad1848->trd | ad1848->mce; break; case 1: ret = ad1848->regs[ad1848->index]; switch (ad1848->index) { case 11: ret ^= 0x20; ad1848->regs[ad1848->index] = ret; break; case 18: case 19: if (ad1848->type >= AD1848_TYPE_CS4235) { if ((ad1848->xregs[4] & 0x14) == 0x14) /* FM remapping */ ret = ad1848->xregs[ad1848->index - 12]; /* real FM volume on registers 6 and 7 */ else if (ad1848->wten && !(ad1848->xregs[4] & 0x08)) /* wavetable remapping */ ret = ad1848->xregs[ad1848->index - 2]; /* real wavetable volume on registers 16 and 17 */ } break; case 20: case 21: /* Backdoor to the Control/RAM registers on CS4235. */ if ((ad1848->type == AD1848_TYPE_CS4235) && (ad1848->xregs[18] & 0x80)) ret = ad1848->cram_read(ad1848->index - 15, ad1848->cram_priv); break; case 23: if ((ad1848->type >= AD1848_TYPE_CS4235) && (ad1848->regs[23] & 0x08)) { if ((ad1848->xindex & 0xfe) == 0x00) /* remapped line volume */ ret = ad1848->regs[18 + ad1848->xindex]; else ret = ad1848->xregs[ad1848->xindex]; } break; default: break; } break; case 2: ret = ad1848->status; break; default: break; } return ret; } void ad1848_write(uint16_t addr, uint8_t val, void *priv) { ad1848_t *ad1848 = (ad1848_t *) priv; uint8_t temp = 0; uint8_t updatefreq = 0; switch (addr & 3) { case 0: /* Index */ if ((ad1848->regs[12] & 0x40) && (ad1848->type >= AD1848_TYPE_CS4231)) ad1848->index = val & 0x1f; /* cs4231a extended mode enabled */ else ad1848->index = val & 0x0f; /* ad1848/cs4248 mode TODO: some variants/clones DO NOT mirror, just ignore the writes? */ if (ad1848->type >= AD1848_TYPE_CS4235) ad1848->regs[23] &= ~0x08; /* clear XRAE */ ad1848->trd = val & 0x20; ad1848->mce = val & 0x40; break; case 1: switch (ad1848->index) { case 10: if (ad1848->type < AD1848_TYPE_CS4235) break; fallthrough; case 8: updatefreq = 1; break; case 9: if (!ad1848->enable && (val & 0x41) == 0x01) { ad1848->adpcm_pos = 0; ad1848->dma_ff = 0; if (ad1848->timer_latch) timer_set_delay_u64(&ad1848->timer_count, ad1848->timer_latch); else timer_set_delay_u64(&ad1848->timer_count, TIMER_USEC); } ad1848->enable = ((val & 0x41) == 0x01); if (!ad1848->enable) { timer_disable(&ad1848->timer_count); ad1848->out_l = ad1848->out_r = 0; } break; case 11: return; case 12: if (ad1848->type != AD1848_TYPE_DEFAULT) ad1848->regs[12] = ((ad1848->regs[12] & 0x0f) + (val & 0xf0)) | 0x80; return; case 14: ad1848->count = ad1848->regs[15] | (val << 8); break; case 17: /* Enable additional data formats on modes 2 and 3 where supported. */ if ((ad1848->type == AD1848_TYPE_CS4231) || (ad1848->type == AD1848_TYPE_CS4236)) ad1848->fmt_mask = (val & 0x40) ? 0xf0 : 0x70; break; case 18: case 19: if (ad1848->type >= AD1848_TYPE_CS4235) { if ((ad1848->xregs[4] & 0x14) == 0x14) { /* FM remapping */ ad1848->xregs[ad1848->index - 12] = val; /* real FM volume on extended registers 6 and 7 */ temp = 1; if (ad1848->index == 18) { if (val & 0x80) ad1848->fm_vol_l = 0; else ad1848->fm_vol_l = ad1848_vols_7bits[val & 0x3f]; } else { if (val & 0x80) ad1848->fm_vol_r = 0; else ad1848->fm_vol_r = ad1848_vols_7bits[val & 0x3f]; } } if (ad1848->wten && !(ad1848->xregs[4] & 0x08)) { /* wavetable remapping */ ad1848->xregs[ad1848->index - 2] = val; /* real wavetable volume on extended registers 16 and 17 */ temp = 1; } /* Stop here if any remapping is enabled. */ if (temp) return; /* HACK: the Windows 9x driver's "Synth" control writes to this register with no remapping, even if internal FM is enabled. */ if (ad1848->index == 18) { if (val & 0x80) ad1848->fm_vol_l = 0; else ad1848->fm_vol_l = (int) ad1848_vols_5bits_aux_gain[val & 0x1f]; } else { if (val & 0x80) ad1848->fm_vol_r = 0; else ad1848->fm_vol_r = (int) ad1848_vols_5bits_aux_gain[val & 0x1f]; } } break; case 20: case 21: /* Backdoor to the Control/RAM registers on CS4235. */ if ((ad1848->type == AD1848_TYPE_CS4235) && (ad1848->xregs[18] & 0x80)) { ad1848->cram_write(ad1848->index - 15, val, ad1848->cram_priv); val = ad1848->regs[ad1848->index]; } break; case 22: updatefreq = 1; break; case 23: if ((ad1848->type >= AD1848_TYPE_CS4235) && ((ad1848->regs[12] & 0x60) == 0x60)) { if (!(ad1848->regs[23] & 0x08)) { /* existing (not new) XRAE is clear */ ad1848->xindex = ((val & 0x04) << 2) | (val >> 4); break; } switch (ad1848->xindex) { case 0: case 1: /* remapped line volume */ ad1848->regs[18 + ad1848->xindex] = val; return; case 6: if (val & 0x80) ad1848->fm_vol_l = 0; else ad1848->fm_vol_l = ad1848_vols_7bits[val & 0x3f]; break; case 7: if (val & 0x80) ad1848->fm_vol_r = 0; else ad1848->fm_vol_r = ad1848_vols_7bits[val & 0x3f]; break; case 11: case 13: updatefreq = 1; break; case 25: return; default: break; } ad1848->xregs[ad1848->xindex] = val; if (updatefreq) ad1848_updatefreq(ad1848); return; } break; case 24: val = ad1848->regs[24] & ((val & 0x70) | 0x0f); if (!(val & 0x70)) { ad1848->status &= 0xfe; picintc(1 << ad1848->irq); } break; case 25: return; case 27: if (ad1848->type != AD1848_TYPE_DEFAULT) return; break; default: break; } ad1848->regs[ad1848->index] = val; if (updatefreq) ad1848_updatefreq(ad1848); temp = (ad1848->type < AD1848_TYPE_CS4231) ? 2 : ((ad1848->type == AD1848_TYPE_CS4231) ? 18 : 4); if (ad1848->regs[temp] & 0x80) ad1848->cd_vol_l = 0; else ad1848->cd_vol_l = ad1848_vols_5bits_aux_gain[ad1848->regs[temp] & 0x1f]; temp++; if (ad1848->regs[temp] & 0x80) ad1848->cd_vol_r = 0; else ad1848->cd_vol_r = ad1848_vols_5bits_aux_gain[ad1848->regs[temp] & 0x1f]; break; case 2: ad1848->status &= 0xfe; ad1848->regs[24] &= 0x0f; break; default: break; } } void ad1848_speed_changed(ad1848_t *ad1848) { ad1848->timer_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / (double) ad1848->freq)); } void ad1848_update(ad1848_t *ad1848) { for (; ad1848->pos < sound_pos_global; ad1848->pos++) { ad1848->buffer[ad1848->pos * 2] = ad1848->out_l; ad1848->buffer[ad1848->pos * 2 + 1] = ad1848->out_r; } } static int16_t ad1848_process_mulaw(uint8_t byte) { byte = ~byte; int temp = (((byte & 0x0f) << 3) + 0x84); int16_t dec; temp <<= ((byte & 0x70) >> 4); temp = (byte & 0x80) ? (0x84 - temp) : (temp - 0x84); if (temp > 32767) dec = 32767; else if (temp < -32768) dec = -32768; else dec = (int16_t) temp; return dec; } static int16_t ad1848_process_alaw(uint8_t byte) { byte ^= 0x55; int dec = ((byte & 0x0f) << 4);; const int seg = (int) ((byte & 0x70) >> 4); switch (seg) { default: dec |= 0x108; dec <<= seg - 1; break; case 0: dec |= 0x8; break; case 1: dec |= 0x108; break; } dec = (byte & 0x80) ? dec : -dec; return (int16_t) dec; } static uint32_t ad1848_dma_channel_read(ad1848_t *ad1848, int channel) { uint32_t ret; if (channel >= 4) { if (ad1848->dma_ff) { ret = (ad1848->dma_data & 0xff00) >> 8; ret |= (ad1848->dma_data & 0xffff0000); } else { ad1848->dma_data = dma_channel_read(channel); if (ad1848->dma_data == DMA_NODATA) return DMA_NODATA; ret = ad1848->dma_data & 0xff; } ad1848->dma_ff = !ad1848->dma_ff; } else ret = dma_channel_read(channel); return ret; } static int16_t ad1848_process_adpcm(ad1848_t *ad1848) { int temp; if (ad1848->adpcm_pos++ & 1) { temp = (ad1848->adpcm_data & 0x0f) + ad1848->adpcm_step; } else { ad1848->adpcm_data = (int) (ad1848_dma_channel_read(ad1848, ad1848->dma) & 0xffff); temp = (ad1848->adpcm_data >> 4) + ad1848->adpcm_step; } if (temp < 0) temp = 0; else if (temp > 63) temp = 63; ad1848->adpcm_ref += scaleMap4[temp]; if (ad1848->adpcm_ref > 0xff) ad1848->adpcm_ref = 0xff; else if (ad1848->adpcm_ref < 0x00) ad1848->adpcm_ref = 0x00; ad1848->adpcm_step = (int8_t) ((ad1848->adpcm_step + adjustMap4[temp]) & 0xff); return (int16_t) ((ad1848->adpcm_ref ^ 0x80) << 8); } static void ad1848_poll(void *priv) { ad1848_t *ad1848 = (ad1848_t *) priv; if (ad1848->timer_latch) timer_advance_u64(&ad1848->timer_count, ad1848->timer_latch); else timer_advance_u64(&ad1848->timer_count, TIMER_USEC * 1000); ad1848_update(ad1848); if (ad1848->enable) { int32_t temp; switch (ad1848->regs[8] & ad1848->fmt_mask) { case 0x00: /* Mono, 8-bit PCM */ ad1848->out_l = ad1848->out_r = (int16_t) ((ad1848_dma_channel_read(ad1848, ad1848->dma) ^ 0x80) << 8); break; case 0x10: /* Stereo, 8-bit PCM */ ad1848->out_l = (int16_t) ((ad1848_dma_channel_read(ad1848, ad1848->dma) ^ 0x80) << 8); ad1848->out_r = (int16_t) ((ad1848_dma_channel_read(ad1848, ad1848->dma) ^ 0x80) << 8); break; case 0x20: /* Mono, 8-bit Mu-Law */ ad1848->out_l = ad1848->out_r = ad1848_process_mulaw(ad1848_dma_channel_read(ad1848, ad1848->dma)); break; case 0x30: /* Stereo, 8-bit Mu-Law */ ad1848->out_l = ad1848_process_mulaw(ad1848_dma_channel_read(ad1848, ad1848->dma)); ad1848->out_r = ad1848_process_mulaw(ad1848_dma_channel_read(ad1848, ad1848->dma)); break; case 0x40: /* Mono, 16-bit PCM little endian */ temp = (int32_t) ad1848_dma_channel_read(ad1848, ad1848->dma); ad1848->out_l = ad1848->out_r = (int16_t) ((ad1848_dma_channel_read(ad1848, ad1848->dma) << 8) | temp); break; case 0x50: /* Stereo, 16-bit PCM little endian */ temp = (int32_t) ad1848_dma_channel_read(ad1848, ad1848->dma); ad1848->out_l = (int16_t) ((ad1848_dma_channel_read(ad1848, ad1848->dma) << 8) | temp); temp = (int32_t) ad1848_dma_channel_read(ad1848, ad1848->dma); ad1848->out_r = (int16_t) ((ad1848_dma_channel_read(ad1848, ad1848->dma) << 8) | temp); break; case 0x60: /* Mono, 8-bit A-Law */ ad1848->out_l = ad1848->out_r = ad1848_process_alaw(ad1848_dma_channel_read(ad1848, ad1848->dma)); break; case 0x70: /* Stereo, 8-bit A-Law */ ad1848->out_l = ad1848_process_alaw(ad1848_dma_channel_read(ad1848, ad1848->dma)); ad1848->out_r = ad1848_process_alaw(ad1848_dma_channel_read(ad1848, ad1848->dma)); break; /* 0x80 and 0x90 reserved */ case 0xa0: /* Mono, 4-bit ADPCM */ ad1848->out_l = ad1848->out_r = ad1848_process_adpcm(ad1848); break; case 0xb0: /* Stereo, 4-bit ADPCM */ ad1848->out_l = ad1848_process_adpcm(ad1848); ad1848->out_r = ad1848_process_adpcm(ad1848); break; case 0xc0: /* Mono, 16-bit PCM big endian */ temp = (int32_t) ad1848_dma_channel_read(ad1848, ad1848->dma); ad1848->out_l = ad1848->out_r = (int16_t) (ad1848_dma_channel_read(ad1848, ad1848->dma) | (temp << 8)); break; case 0xd0: /* Stereo, 16-bit PCM big endian */ temp = (int32_t) ad1848_dma_channel_read(ad1848, ad1848->dma); ad1848->out_l = (int16_t) (ad1848_dma_channel_read(ad1848, ad1848->dma) | (temp << 8)); temp = (int32_t) ad1848_dma_channel_read(ad1848, ad1848->dma); ad1848->out_r = (int16_t) (ad1848_dma_channel_read(ad1848, ad1848->dma) | (temp << 8)); break; /* 0xe0 and 0xf0 reserved */ default: break; } if (ad1848->regs[6] & 0x80) ad1848->out_l = 0; else ad1848->out_l = (int16_t) ((ad1848->out_l * ad1848_vols_7bits[ad1848->regs[6] & ad1848->wave_vol_mask]) >> 16); if (ad1848->regs[7] & 0x80) ad1848->out_r = 0; else ad1848->out_r = (int16_t) ((ad1848->out_r * ad1848_vols_7bits[ad1848->regs[7] & ad1848->wave_vol_mask]) >> 16); if (ad1848->count < 0) { ad1848->count = ad1848->regs[15] | (ad1848->regs[14] << 8); ad1848->adpcm_pos = 0; if (!(ad1848->status & 0x01)) { ad1848->status |= 0x01; ad1848->regs[24] |= 0x10; if (ad1848->regs[10] & 2) picint(1 << ad1848->irq); } } if (!(ad1848->adpcm_pos & 7)) /* ADPCM counts down every 4 bytes */ ad1848->count--; } else { ad1848->out_l = ad1848->out_r = 0; ad1848->cd_vol_l = ad1848->cd_vol_r = 0; } } void ad1848_filter_cd_audio(int channel, double *buffer, void *priv) { const ad1848_t *ad1848 = (ad1848_t *) priv; double c; double volume = channel ? ad1848->cd_vol_r : ad1848->cd_vol_l; c = ((*buffer) * volume) / 65536.0; *buffer = c; } void ad1848_filter_aux2(void *priv, double *out_l, double *out_r) { const ad1848_t *ad1848 = (ad1848_t *) priv; if (ad1848->regs[4] & 0x80) { *out_l = 0.0; } else { *out_l = ((*out_l) * ad1848_vols_5bits_aux_gain[ad1848->regs[4] & 0x1f]) / 65536.0; } if (ad1848->regs[5] & 0x80) { *out_r = 0.0; } else { *out_r = ((*out_r) * ad1848_vols_5bits_aux_gain[ad1848->regs[5] & 0x1f]) / 65536.0; } } void ad1848_init(ad1848_t *ad1848, uint8_t type) { uint8_t c; double attenuation; ad1848->status = 0xcc; ad1848->index = ad1848->trd = 0; ad1848->mce = 0x40; ad1848->wten = 0; ad1848->regs[0] = ad1848->regs[1] = 0; ad1848->regs[2] = ad1848->regs[3] = 0x80; /* Line-in */ ad1848->regs[4] = ad1848->regs[5] = 0x80; ad1848->regs[6] = ad1848->regs[7] = 0x80; /* Left/right Output */ ad1848->regs[8] = 0; ad1848->regs[9] = 0x08; ad1848->regs[10] = ad1848->regs[11] = 0; if ((type == AD1848_TYPE_CS4248) || (type == AD1848_TYPE_CS4231) || (type >= AD1848_TYPE_CS4235)) ad1848->regs[12] = 0x8a; else ad1848->regs[12] = 0xa; ad1848->regs[13] = 0; ad1848->regs[14] = ad1848->regs[15] = 0; if (type == AD1848_TYPE_CS4231) { ad1848->regs[16] = ad1848->regs[17] = 0; ad1848->regs[18] = ad1848->regs[19] = 0x88; ad1848->regs[22] = 0x80; ad1848->regs[24] = 0; ad1848->regs[25] = CS4231; ad1848->regs[26] = 0x80; ad1848->regs[29] = 0x80; } else if (type >= AD1848_TYPE_CS4235) { ad1848->regs[16] = ad1848->regs[17] = 0; ad1848->regs[18] = ad1848->regs[19] = 0; ad1848->regs[20] = ad1848->regs[21] = 0; ad1848->regs[22] = ad1848->regs[23] = 0; ad1848->regs[24] = 0; ad1848->regs[25] = CS4236; ad1848->regs[26] = 0xa0; ad1848->regs[27] = ad1848->regs[29] = 0; ad1848->regs[30] = ad1848->regs[31] = 0; ad1848->xregs[0] = ad1848->xregs[1] = 0xe8; ad1848->xregs[2] = ad1848->xregs[3] = 0xcf; ad1848->xregs[4] = 0x84; ad1848->xregs[5] = 0; ad1848->xregs[6] = ad1848->xregs[7] = 0x80; ad1848->xregs[8] = ad1848->xregs[9] = 0; ad1848->xregs[10] = 0x3f; ad1848->xregs[11] = 0xc0; ad1848->xregs[14] = ad1848->xregs[15] = 0; ad1848->xregs[16] = ad1848->xregs[17] = 0; } ad1848_updatefreq(ad1848); ad1848->out_l = ad1848->out_r = 0; ad1848->fm_vol_l = ad1848->fm_vol_r = 65536; ad1848_updatevolmask(ad1848); if (type == AD1848_TYPE_CS4235) ad1848->fmt_mask = 0x50; else ad1848->fmt_mask = 0x70; for (c = 0; c < 128; c++) { attenuation = 0.0; if (c & 0x40) { if (c < 72) attenuation = (c - 72) * -1.5; } else { if (c & 0x01) attenuation -= 1.5; if (c & 0x02) attenuation -= 3.0; if (c & 0x04) attenuation -= 6.0; if (c & 0x08) attenuation -= 12.0; if (c & 0x10) attenuation -= 24.0; if (c & 0x20) attenuation -= 48.0; } attenuation = pow(10, attenuation / 10); ad1848_vols_7bits[c] = (int) (attenuation * 65536); } for (c = 0; c < 32; c++) { attenuation = 12.0; if (c & 0x01) attenuation -= 1.5; if (c & 0x02) attenuation -= 3.0; if (c & 0x04) attenuation -= 6.0; if (c & 0x08) attenuation -= 12.0; if (c & 0x10) attenuation -= 24.0; attenuation = pow(10, attenuation / 10); ad1848_vols_5bits_aux_gain[c] = (attenuation * 65536); } ad1848->type = type; timer_add(&ad1848->timer_count, ad1848_poll, ad1848, 0); if ((ad1848->type != AD1848_TYPE_DEFAULT) && (ad1848->type != AD1848_TYPE_CS4248)) sound_set_cd_audio_filter(ad1848_filter_cd_audio, ad1848); } ```
/content/code_sandbox/src/sound/snd_ad1848.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
7,870
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * ESFMu ESFM emulator. * * * Authors: Fred N. van Kempen, <decwiz@yahoo.com> * Miran Grca, <mgrca8@gmail.com> * Alexey Khokholov (Nuke.YKT) * Cacodemon345 * */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "esfmu/esfm.h" #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/sound.h> #include <86box/device.h> #include <86box/timer.h> #include <86box/snd_opl.h> #define RSM_FRAC 10 typedef struct { esfm_chip opl; int8_t flags; int8_t pad; uint8_t status; uint8_t timer_ctrl; uint16_t timer_count[2]; uint16_t timer_cur_count[2]; pc_timer_t timers[2]; int16_t samples[2]; int pos; int32_t buffer[MUSICBUFLEN * 2]; } esfm_drv_t; enum { FLAG_CYCLES = 0x02, FLAG_OPL3 = 0x01 }; enum { STAT_TMR_OVER = 0x60, STAT_TMR1_OVER = 0x40, STAT_TMR2_OVER = 0x20, STAT_TMR_ANY = 0x80 }; enum { CTRL_RESET = 0x80, CTRL_TMR_MASK = 0x60, CTRL_TMR1_MASK = 0x40, CTRL_TMR2_MASK = 0x20, CTRL_TMR2_START = 0x02, CTRL_TMR1_START = 0x01 }; #ifdef ENABLE_OPL_LOG int esfm_do_log = ENABLE_OPL_LOG; static void esfm_log(const char *fmt, ...) { va_list ap; if (esfm_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define esfm_log(fmt, ...) #endif void esfm_generate_raw(esfm_drv_t *dev, int32_t *bufp) { ESFM_generate(&dev->opl, bufp); } void esfm_drv_generate_stream(esfm_drv_t *dev, int32_t *sndptr, uint32_t num) { for (uint32_t i = 0; i < num; i++) { esfm_generate_raw(dev, sndptr); sndptr += 2; } } static void esfm_timer_tick(esfm_drv_t *dev, int tmr) { dev->timer_cur_count[tmr] = (dev->timer_cur_count[tmr] + 1) & 0xff; esfm_log("Ticking timer %i, count now %02X...\n", tmr, dev->timer_cur_count[tmr]); if (dev->timer_cur_count[tmr] == 0x00) { dev->status |= ((STAT_TMR1_OVER >> tmr) & ~dev->timer_ctrl); dev->timer_cur_count[tmr] = dev->timer_count[tmr]; esfm_log("Count wrapped around to zero, reloading timer %i (%02X), status = %02X...\n", tmr, (STAT_TMR1_OVER >> tmr), dev->status); } timer_on_auto(&dev->timers[tmr], (tmr == 1) ? 320.0 : 80.0); } static void esfm_timer_control(esfm_drv_t *dev, int tmr, int start) { timer_on_auto(&dev->timers[tmr], 0.0); if (start) { esfm_log("Loading timer %i count: %02X = %02X\n", tmr, dev->timer_cur_count[tmr], dev->timer_count[tmr]); dev->timer_cur_count[tmr] = dev->timer_count[tmr]; if (dev->flags & FLAG_OPL3) esfm_timer_tick(dev, tmr); /* Per the YMF 262 datasheet, OPL3 starts counting immediately, unlike OPL2. */ else timer_on_auto(&dev->timers[tmr], (tmr == 1) ? 320.0 : 80.0); } else { esfm_log("Timer %i stopped\n", tmr); if (tmr == 1) { dev->status &= ~STAT_TMR2_OVER; } else dev->status &= ~STAT_TMR1_OVER; } } static void esfm_timer_1(void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; esfm_timer_tick(dev, 0); } static void esfm_timer_2(void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; esfm_timer_tick(dev, 1); } static void esfm_drv_set_do_cycles(void *priv, int8_t do_cycles) { esfm_drv_t *dev = (esfm_drv_t *) priv; if (do_cycles) dev->flags |= FLAG_CYCLES; else dev->flags &= ~FLAG_CYCLES; } static void * esfm_drv_init(const device_t *info) { esfm_drv_t *dev = (esfm_drv_t *) calloc(1, sizeof(esfm_drv_t)); dev->flags = FLAG_CYCLES | FLAG_OPL3; /* Initialize the ESFMu object. */ ESFM_init(&dev->opl); timer_add(&dev->timers[0], esfm_timer_1, dev, 0); timer_add(&dev->timers[1], esfm_timer_2, dev, 0); return dev; } static void esfm_drv_close(void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; free(dev); } static int32_t * esfm_drv_update(void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; if (dev->pos >= music_pos_global) return dev->buffer; esfm_drv_generate_stream(dev, &dev->buffer[dev->pos * 2], music_pos_global - dev->pos); for (; dev->pos < music_pos_global; dev->pos++) { dev->buffer[dev->pos * 2] /= 2; dev->buffer[(dev->pos * 2) + 1] /= 2; } return dev->buffer; } static void esfm_drv_reset_buffer(void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; dev->pos = 0; } static uint8_t esfm_drv_read(uint16_t port, void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; if (dev->flags & FLAG_CYCLES) cycles -= ((int) (isa_timing * 8)); esfm_drv_update(dev); uint8_t ret = 0xff; switch (port & 0x0003) { case 0x0000: ret = dev->status; if (dev->status & STAT_TMR_OVER) ret |= STAT_TMR_ANY; break; case 0x0001: ret = ESFM_read_port(&dev->opl, port & 3); switch (dev->opl.addr_latch & 0x5ff) { case 0x402: ret = dev->timer_count[0]; break; case 0x403: ret = dev->timer_count[1]; break; case 0x404: ret = dev->timer_ctrl; break; } break; case 0x0002: case 0x0003: ret = 0xff; break; } return ret; } static void esfm_drv_write_buffered(esfm_drv_t *dev, uint8_t val) { uint16_t p = dev->opl.addr_latch & 0x07ff; if (dev->opl.native_mode) { p -= 0x400; } p &= 0x1ff; switch (p) { case 0x002: /* Timer 1 */ dev->timer_count[0] = val; esfm_log("Timer 0 count now: %i\n", dev->timer_count[0]); break; case 0x003: /* Timer 2 */ dev->timer_count[1] = val; esfm_log("Timer 1 count now: %i\n", dev->timer_count[1]); break; case 0x004: /* Timer control */ if (val & CTRL_RESET) { esfm_log("Resetting timer status...\n"); dev->status &= ~STAT_TMR_OVER; } else { dev->timer_ctrl = val; esfm_timer_control(dev, 0, val & CTRL_TMR1_START); esfm_timer_control(dev, 1, val & CTRL_TMR2_START); esfm_log("Status mask now %02X (val = %02X)\n", (val & ~CTRL_TMR_MASK) & CTRL_TMR_MASK, val); } break; default: break; } ESFM_write_reg_buffered_fast(&dev->opl, dev->opl.addr_latch, val); } static void esfm_drv_write(uint16_t port, uint8_t val, void *priv) { esfm_drv_t *dev = (esfm_drv_t *) priv; if (dev->flags & FLAG_CYCLES) cycles -= ((int) (isa_timing * 8)); esfm_drv_update(dev); if (dev->opl.native_mode) { if ((port & 0x0003) == 0x0001) esfm_drv_write_buffered(dev, val); else { ESFM_write_port(&dev->opl, port & 3, val); } } else { if ((port & 0x0001) == 0x0001) esfm_drv_write_buffered(dev, val); else { ESFM_write_port(&dev->opl, port & 3, val); } } } const device_t esfm_esfmu_device = { .name = "ESS Technology ESFM (ESFMu)", .internal_name = "esfm_esfmu", .flags = 0, .local = FM_ESFM, .init = esfm_drv_init, .close = esfm_drv_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; const fm_drv_t esfmu_opl_drv = { &esfm_drv_read, &esfm_drv_write, &esfm_drv_update, &esfm_drv_reset_buffer, &esfm_drv_set_do_cycles, NULL, NULL, }; ```
/content/code_sandbox/src/sound/snd_opl_esfm.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,555
```c #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/device.h> #include <86box/mem.h> #include <86box/midi.h> #include <86box/plat.h> #include <86box/thread.h> #include <86box/rom.h> #include <86box/sound.h> #include <86box/ui.h> #include <mt32emu/c_interface/c_interface.h> #define MT32_OLD_CTRL_ROM "roms/sound/mt32/MT32_CONTROL.ROM" #define MT32_OLD_PCM_ROM "roms/sound/mt32/MT32_PCM.ROM" #define MT32_NEW_CTRL_ROM "roms/sound/mt32_new/MT32_CONTROL.ROM" #define MT32_NEW_PCM_ROM "roms/sound/mt32_new/MT32_PCM.ROM" #define CM32L_CTRL_ROM "roms/sound/cm32l/CM32L_CONTROL.ROM" #define CM32L_PCM_ROM "roms/sound/cm32l/CM32L_PCM.ROM" #define CM32LN_CTRL_ROM "roms/sound/cm32ln/CM32LN_CONTROL.ROM" #define CM32LN_PCM_ROM "roms/sound/cm32ln/CM32LN_PCM.ROM" extern void givealbuffer_midi(void *buf, uint32_t size); extern void al_set_midi(int freq, int buf_size); static mt32emu_report_handler_version get_mt32_report_handler_version(mt32emu_report_handler_i i); static void display_mt32_message(void *instance_data, const char *message); static const mt32emu_report_handler_i_v0 handler_mt32_v0 = { /** Returns the actual interface version ID */ get_mt32_report_handler_version, // mt32emu_report_handler_version (*getVersionID)(mt32emu_report_handler_i i); /** Callback for debug messages, in vprintf() format */ NULL, // void (*printDebug)(void *instance_data, const char *fmt, va_list list); /** Callbacks for reporting errors */ NULL, // void (*onErrorControlROM)(void *instance_data); NULL, // void (*onErrorPCMROM)(void *instance_data); /** Callback for reporting about displaying a new custom message on LCD */ display_mt32_message, // void (*showLCDMessage)(void *instance_data, const char *message); /** Callback for reporting actual processing of a MIDI message */ NULL, // void (*onMIDIMessagePlayed)(void *instance_data); /** * Callback for reporting an overflow of the input MIDI queue. * Returns MT32EMU_BOOL_TRUE if a recovery action was taken * and yet another attempt to enqueue the MIDI event is desired. */ NULL, // mt32emu_boolean (*onMIDIQueueOverflow)(void *instance_data); /** * Callback invoked when a System Realtime MIDI message is detected in functions * mt32emu_parse_stream and mt32emu_play_short_message and the likes. */ NULL, // void (*onMIDISystemRealtime)(void *instance_data, mt32emu_bit8u system_realtime); /** Callbacks for reporting system events */ NULL, // void (*onDeviceReset)(void *instance_data); NULL, // void (*onDeviceReconfig)(void *instance_data); /** Callbacks for reporting changes of reverb settings */ NULL, // void (*onNewReverbMode)(void *instance_data, mt32emu_bit8u mode); NULL, // void (*onNewReverbTime)(void *instance_data, mt32emu_bit8u time); NULL, // void (*onNewReverbLevel)(void *instance_data, mt32emu_bit8u level); /** Callbacks for reporting various information */ NULL, // void (*onPolyStateChanged)(void *instance_data, mt32emu_bit8u part_num); NULL, // void (*onProgramChanged)(void *instance_data, mt32emu_bit8u part_num, const char *sound_group_name, const char *patch_name); }; /** Alternate report handler for Roland CM-32L/CM-32LN */ static const mt32emu_report_handler_i_v0 handler_cm32l_v0 = { /** Returns the actual interface version ID */ get_mt32_report_handler_version, // mt32emu_report_handler_version (*getVersionID)(mt32emu_report_handler_i i); /** Callback for debug messages, in vprintf() format */ NULL, // void (*printDebug)(void *instance_data, const char *fmt, va_list list); /** Callbacks for reporting errors */ NULL, // void (*onErrorControlROM)(void *instance_data); NULL, // void (*onErrorPCMROM)(void *instance_data); /** Callback for reporting about displaying a new custom message on LCD */ NULL, // void (*showLCDMessage)(void *instance_data, const char *message); /** Callback for reporting actual processing of a MIDI message */ NULL, // void (*onMIDIMessagePlayed)(void *instance_data); /** * Callback for reporting an overflow of the input MIDI queue. * Returns MT32EMU_BOOL_TRUE if a recovery action was taken * and yet another attempt to enqueue the MIDI event is desired. */ NULL, // mt32emu_boolean (*onMIDIQueueOverflow)(void *instance_data); /** * Callback invoked when a System Realtime MIDI message is detected in functions * mt32emu_parse_stream and mt32emu_play_short_message and the likes. */ NULL, // void (*onMIDISystemRealtime)(void *instance_data, mt32emu_bit8u system_realtime); /** Callbacks for reporting system events */ NULL, // void (*onDeviceReset)(void *instance_data); NULL, // void (*onDeviceReconfig)(void *instance_data); /** Callbacks for reporting changes of reverb settings */ NULL, // void (*onNewReverbMode)(void *instance_data, mt32emu_bit8u mode); NULL, // void (*onNewReverbTime)(void *instance_data, mt32emu_bit8u time); NULL, // void (*onNewReverbLevel)(void *instance_data, mt32emu_bit8u level); /** Callbacks for reporting various information */ NULL, // void (*onPolyStateChanged)(void *instance_data, mt32emu_bit8u part_num); NULL, // void (*onProgramChanged)(void *instance_data, mt32emu_bit8u part_num, const char *sound_group_name, const char *patch_name); }; static const mt32emu_report_handler_i handler_mt32 = { &handler_mt32_v0 }; static const mt32emu_report_handler_i handler_cm32l = { &handler_cm32l_v0 }; static mt32emu_context context = NULL; static int roms_present[2] = { -1, -1 }; mt32emu_return_code mt32_check(UNUSED(const char *func), mt32emu_return_code ret, mt32emu_return_code expected) { if (ret != expected) { return 0; } return 1; } int mt32_old_available(void) { if (roms_present[0] < 0) roms_present[0] = (rom_present(MT32_OLD_CTRL_ROM) && rom_present(MT32_OLD_PCM_ROM)); return roms_present[0]; } int mt32_new_available(void) { if (roms_present[0] < 0) roms_present[0] = (rom_present(MT32_NEW_CTRL_ROM) && rom_present(MT32_NEW_PCM_ROM)); return roms_present[0]; } int cm32l_available(void) { if (roms_present[1] < 0) roms_present[1] = (rom_present(CM32L_CTRL_ROM) && rom_present(CM32L_PCM_ROM)); return roms_present[1]; } int cm32ln_available(void) { if (roms_present[1] < 0) roms_present[1] = (rom_present(CM32LN_CTRL_ROM) && rom_present(CM32LN_PCM_ROM)); return roms_present[1]; } static thread_t *thread_h = NULL; static event_t *event = NULL; static event_t *start_event = NULL; static int mt32_on = 0; #define RENDER_RATE 100 #define BUFFER_SEGMENTS 10 static uint32_t samplerate = 44100; static int buf_size = 0; static float *buffer = NULL; static int16_t *buffer_int16 = NULL; static int midi_pos = 0; static mt32emu_report_handler_version get_mt32_report_handler_version(UNUSED(mt32emu_report_handler_i i)) { return MT32EMU_REPORT_HANDLER_VERSION_0; } static void display_mt32_message(UNUSED(void *instance_data), const char *message) { int sz = 0; char *ui_msg = NULL; sz = snprintf(NULL, 0, "MT-32: %s", message); ui_msg = calloc(sz + 1, 1); if (ui_msg) { snprintf(ui_msg, sz, "MT-32: %s", message); ui_sb_mt32lcd(ui_msg); } } void mt32_stream(float *stream, int len) { if (context) mt32emu_render_float(context, stream, len); } void mt32_stream_int16(int16_t *stream, int len) { if (context) mt32emu_render_bit16s(context, stream, len); } void mt32_poll(void) { midi_pos++; if (midi_pos == SOUND_FREQ / RENDER_RATE) { midi_pos = 0; thread_set_event(event); } } static void mt32_thread(UNUSED(void *param)) { int buf_pos = 0; int bsize = buf_size / BUFFER_SEGMENTS; float *buf; int16_t *buf16; thread_set_event(start_event); while (mt32_on) { thread_wait_event(event, -1); thread_reset_event(event); if (sound_is_float) { buf = (float *) ((uint8_t *) buffer + buf_pos); memset(buf, 0, bsize); mt32_stream(buf, bsize / (2 * sizeof(float))); buf_pos += bsize; if (buf_pos >= buf_size) { givealbuffer_midi(buffer, buf_size / sizeof(float)); buf_pos = 0; } } else { buf16 = (int16_t *) ((uint8_t *) buffer_int16 + buf_pos); memset(buf16, 0, bsize); mt32_stream_int16(buf16, bsize / (2 * sizeof(int16_t))); buf_pos += bsize; if (buf_pos >= buf_size) { givealbuffer_midi(buffer_int16, buf_size / sizeof(int16_t)); buf_pos = 0; } } } } void mt32_msg(uint8_t *val) { if (context) mt32_check("mt32emu_play_msg", mt32emu_play_msg(context, *(uint32_t *) val), MT32EMU_RC_OK); } void mt32_sysex(uint8_t *data, unsigned int len) { if (context) mt32_check("mt32emu_play_sysex", mt32emu_play_sysex(context, data, len), MT32EMU_RC_OK); } void * mt32emu_init(char *control_rom, char *pcm_rom) { midi_device_t *dev; char fn[512]; context = mt32emu_create_context(strstr(control_rom, "MT32_CONTROL.ROM") ? handler_mt32 : handler_cm32l, NULL); if (!rom_getfile(control_rom, fn, 512)) return 0; if (!mt32_check("mt32emu_add_rom_file", mt32emu_add_rom_file(context, fn), MT32EMU_RC_ADDED_CONTROL_ROM)) return 0; if (!rom_getfile(pcm_rom, fn, 512)) return 0; if (!mt32_check("mt32emu_add_rom_file", mt32emu_add_rom_file(context, fn), MT32EMU_RC_ADDED_PCM_ROM)) return 0; if (!mt32_check("mt32emu_open_synth", mt32emu_open_synth(context), MT32EMU_RC_OK)) return 0; samplerate = mt32emu_get_actual_stereo_output_samplerate(context); /* buf_size = samplerate/RENDER_RATE*2; */ if (sound_is_float) { buf_size = (samplerate / RENDER_RATE) * 2 * BUFFER_SEGMENTS * sizeof(float); buffer = malloc(buf_size); buffer_int16 = NULL; } else { buf_size = (samplerate / RENDER_RATE) * 2 * BUFFER_SEGMENTS * sizeof(int16_t); buffer = NULL; buffer_int16 = malloc(buf_size); } mt32emu_set_output_gain(context, device_get_config_int("output_gain") / 100.0f); mt32emu_set_reverb_enabled(context, device_get_config_int("reverb")); mt32emu_set_reverb_output_gain(context, device_get_config_int("reverb_output_gain") / 100.0f); mt32emu_set_reversed_stereo_enabled(context, device_get_config_int("reversed_stereo")); mt32emu_set_nice_amp_ramp_enabled(context, device_get_config_int("nice_ramp")); al_set_midi(samplerate, buf_size); dev = malloc(sizeof(midi_device_t)); memset(dev, 0, sizeof(midi_device_t)); dev->play_msg = mt32_msg; dev->play_sysex = mt32_sysex; dev->poll = mt32_poll; midi_out_init(dev); mt32_on = 1; start_event = thread_create_event(); event = thread_create_event(); thread_h = thread_create(mt32_thread, 0); thread_wait_event(start_event, -1); thread_reset_event(start_event); return dev; } void * mt32_old_init(UNUSED(const device_t *info)) { return mt32emu_init(MT32_OLD_CTRL_ROM, MT32_OLD_PCM_ROM); } void * mt32_new_init(UNUSED(const device_t *info)) { return mt32emu_init(MT32_NEW_CTRL_ROM, MT32_NEW_PCM_ROM); } void * cm32l_init(UNUSED(const device_t *info)) { return mt32emu_init(CM32L_CTRL_ROM, CM32L_PCM_ROM); } void * cm32ln_init(UNUSED(const device_t *info)) { return mt32emu_init(CM32LN_CTRL_ROM, CM32LN_PCM_ROM); } void mt32_close(void *priv) { if (!priv) return; mt32_on = 0; thread_set_event(event); thread_wait(thread_h); event = NULL; start_event = NULL; thread_h = NULL; if (context) { mt32emu_close_synth(context); mt32emu_free_context(context); } context = NULL; ui_sb_mt32lcd(""); if (buffer) free(buffer); buffer = NULL; if (buffer_int16) free(buffer_int16); buffer_int16 = NULL; } static const device_config_t mt32_config[] = { // clang-format off { .name = "output_gain", .description = "Output Gain", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 100 }, { .name = "reverb", .description = "Reverb", .type = CONFIG_BINARY, .default_int = 1 }, { .name = "reverb_output_gain", .description = "Reverb Output Gain", .type = CONFIG_SPINNER, .spinner = { .min = 0, .max = 100 }, .default_int = 100 }, { .name = "reversed_stereo", .description = "Reversed stereo", .type = CONFIG_BINARY, .default_int = 0 }, { .name = "nice_ramp", .description = "Nice ramp", .type = CONFIG_BINARY, .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t mt32_old_device = { .name = "Roland MT-32 Emulation", .internal_name = "mt32", .flags = 0, .local = 0, .init = mt32_old_init, .close = mt32_close, .reset = NULL, { .available = mt32_old_available }, .speed_changed = NULL, .force_redraw = NULL, .config = mt32_config }; const device_t mt32_new_device = { .name = "Roland MT-32 (New) Emulation", .internal_name = "mt32_new", .flags = 0, .local = 0, .init = mt32_new_init, .close = mt32_close, .reset = NULL, { .available = mt32_new_available }, .speed_changed = NULL, .force_redraw = NULL, .config = mt32_config }; const device_t cm32l_device = { .name = "Roland CM-32L Emulation", .internal_name = "cm32l", .flags = 0, .local = 0, .init = cm32l_init, .close = mt32_close, .reset = NULL, { .available = cm32l_available }, .speed_changed = NULL, .force_redraw = NULL, .config = mt32_config }; const device_t cm32ln_device = { .name = "Roland CM-32LN Emulation", .internal_name = "cm32ln", .flags = 0, .local = 0, .init = cm32ln_init, .close = mt32_close, .reset = NULL, { .available = cm32ln_available }, .speed_changed = NULL, .force_redraw = NULL, .config = mt32_config }; ```
/content/code_sandbox/src/sound/midi_mt32.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
4,084
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Sound emulation core. * * * * Authors: Sarah Walker, <path_to_url * Miran Grca, <mgrca8@gmail.com> * */ #include <math.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/cdrom.h> #include <86box/device.h> #include <86box/filters.h> #include <86box/machine.h> #include <86box/midi.h> #include <86box/plat.h> #include <86box/thread.h> #include <86box/snd_ac97.h> #include <86box/timer.h> #include <86box/snd_mpu401.h> #include <86box/sound.h> typedef struct { const device_t *device; } SOUND_CARD; typedef struct { void (*get_buffer)(int32_t *buffer, int len, void *priv); void *priv; } sound_handler_t; int sound_card_current[SOUND_CARD_MAX] = { 0, 0, 0, 0 }; int sound_pos_global = 0; int music_pos_global = 0; int wavetable_pos_global = 0; int sound_gain = 0; static sound_handler_t sound_handlers[8]; static sound_handler_t music_handlers[8]; static sound_handler_t wavetable_handlers[8]; static double cd_audio_volume_lut[256]; static thread_t *sound_cd_thread_h; static event_t *sound_cd_event; static event_t *sound_cd_start_event; static int32_t *outbuffer; static float *outbuffer_ex; static int16_t *outbuffer_ex_int16; static int32_t *outbuffer_m; static float *outbuffer_m_ex; static int16_t *outbuffer_m_ex_int16; static int32_t *outbuffer_w; static float *outbuffer_w_ex; static int16_t *outbuffer_w_ex_int16; static int sound_handlers_num; static int music_handlers_num; static int wavetable_handlers_num; static pc_timer_t sound_poll_timer; static uint64_t sound_poll_latch; static pc_timer_t music_poll_timer; static uint64_t music_poll_latch; static pc_timer_t wavetable_poll_timer; static uint64_t wavetable_poll_latch; static int16_t cd_buffer[CDROM_NUM][CD_BUFLEN * 2]; static float cd_out_buffer[CD_BUFLEN * 2]; static int16_t cd_out_buffer_int16[CD_BUFLEN * 2]; static unsigned int cd_vol_l; static unsigned int cd_vol_r; static int cd_buf_update = CD_BUFLEN / SOUNDBUFLEN; static volatile int cdaudioon = 0; static int cd_thread_enable = 0; static void (*filter_cd_audio)(int channel, double *buffer, void *priv) = NULL; static void *filter_cd_audio_p = NULL; void (*filter_pc_speaker)(int channel, double *buffer, void *priv) = NULL; void *filter_pc_speaker_p = NULL; static const SOUND_CARD sound_cards[] = { // clang-format off { &device_none }, { &device_internal }, { &acermagic_s20_device }, { &mirosound_pcm10_device }, { &adlib_device }, { &adgold_device }, { &azt2316a_device }, { &azt1605_device }, { &cms_device }, { &cs4235_device }, { &cs4236b_device }, { &ess_688_device }, { &ess_ess0100_pnp_device }, { &ess_1688_device }, { &ess_ess0102_pnp_device }, { &ess_ess0968_pnp_device }, { &gus_device }, { &sb_1_device }, { &sb_15_device }, { &sb_2_device }, { &sb_pro_v1_device }, { &sb_pro_v2_device }, { &sb_16_device }, { &sb_16_pnp_device }, { &sb_32_pnp_device }, { &sb_awe32_device }, { &sb_awe32_pnp_device }, { &sb_awe64_value_device }, { &sb_awe64_device }, { &sb_awe64_gold_device }, { &sb_vibra16c_device }, { &sb_vibra16s_device }, { &sb_vibra16xv_device }, { &ssi2001_device }, { &pasplus_device }, { &pas16_device }, { &pas16d_device }, { &pssj_isa_device }, { &tndy_device }, { &wss_device }, { &adlib_mca_device }, { &ess_chipchat_16_mca_device }, { &ncr_business_audio_device }, { &sb_mcv_device }, { &sb_pro_mcv_device }, { &sb_16_reply_mca_device }, { &ess_soundpiper_16_mca_device }, { &ess_soundpiper_32_mca_device }, { &cmi8338_device }, { &cmi8738_device }, { &es1371_device }, { &es1373_device }, { &ct5880_device }, { &ad1881_device }, { &cs4297a_device }, { NULL } // clang-format on }; #ifdef ENABLE_SOUND_LOG int sound_do_log = ENABLE_SOUND_LOG; static void sound_log(const char *fmt, ...) { va_list ap; if (sound_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define sound_log(fmt, ...) #endif int sound_card_available(int card) { if (sound_cards[card].device) return device_available(sound_cards[card].device); return 1; } const device_t * sound_card_getdevice(int card) { return sound_cards[card].device; } int sound_card_has_config(int card) { if (sound_cards[card].device == NULL) return 0; return device_has_config(sound_cards[card].device) ? 1 : 0; } const char * sound_card_get_internal_name(int card) { return device_get_internal_name(sound_cards[card].device); } int sound_card_get_from_internal_name(const char *s) { int c = 0; while (sound_cards[c].device != NULL) { if (!strcmp(sound_cards[c].device->internal_name, s)) return c; c++; } return 0; } void sound_card_init(void) { for (uint8_t i = 0; i < SOUND_CARD_MAX; i++) if ((sound_card_current[i] > SOUND_INTERNAL) && (sound_cards[sound_card_current[i]].device)) device_add_inst(sound_cards[sound_card_current[i]].device, i + 1); } void sound_set_cd_volume(unsigned int vol_l, unsigned int vol_r) { cd_vol_l = vol_l; cd_vol_r = vol_r; } static void sound_cd_clean_buffers(void) { if (sound_is_float) memset(cd_out_buffer, 0, (CD_BUFLEN * 2) * sizeof(float)); else memset(cd_out_buffer_int16, 0, (CD_BUFLEN * 2) * sizeof(int16_t)); } static void sound_cd_thread(UNUSED(void *param)) { int temp_buffer[2]; int channel_select[2]; double audio_vol_l; double audio_vol_r; double cd_buffer_temp[2] = { 0.0, 0.0 }; thread_set_event(sound_cd_start_event); while (cdaudioon) { thread_wait_event(sound_cd_event, -1); thread_reset_event(sound_cd_event); if (!cdaudioon) return; sound_cd_clean_buffers(); temp_buffer[0] = temp_buffer[1] = 0; for (uint8_t i = 0; i < CDROM_NUM; i++) { if ((cdrom[i].bus_type == CDROM_BUS_DISABLED) || (cdrom[i].cd_status == CD_STATUS_EMPTY)) continue; const uint32_t lba = cdrom[i].seek_pos; const int r = cdrom_audio_callback(&(cdrom[i]), cd_buffer[i], CD_BUFLEN * 2); if (!cdrom[i].sound_on || !r) continue; const int pre = cdrom_is_pre(&(cdrom[i]), lba); if (cdrom[i].get_volume) { audio_vol_l = cd_audio_volume_lut[cdrom[i].get_volume(cdrom[i].priv, 0)]; audio_vol_r = cd_audio_volume_lut[cdrom[i].get_volume(cdrom[i].priv, 1)]; } else { audio_vol_l = cd_audio_volume_lut[255]; audio_vol_r = cd_audio_volume_lut[255]; } if (cdrom[i].get_channel) { channel_select[0] = (int) cdrom[i].get_channel(cdrom[i].priv, 0); channel_select[1] = (int) cdrom[i].get_channel(cdrom[i].priv, 1); } else { channel_select[0] = 1; channel_select[1] = 2; } for (int c = 0; c < CD_BUFLEN * 2; c += 2) { /*Apply ATAPI channel select*/ cd_buffer_temp[0] = cd_buffer_temp[1] = 0.0; if ((audio_vol_l != 0.0) && (channel_select[0] != 0)) { if (channel_select[0] & 1) cd_buffer_temp[0] += ((double) cd_buffer[i][c]); /* Channel 0 => Port 0 */ if (channel_select[0] & 2) cd_buffer_temp[0] += ((double) cd_buffer[i][c + 1]); /* Channel 1 => Port 0 */ cd_buffer_temp[0] *= audio_vol_l; /* Multiply Port 0 by Port 0 volume */ if (pre) cd_buffer_temp[0] = deemph_iir(0, cd_buffer_temp[0]); /* De-emphasize if necessary */ } if ((audio_vol_r != 0.0) && (channel_select[1] != 0)) { if (channel_select[1] & 1) cd_buffer_temp[1] += ((double) cd_buffer[i][c]); /* Channel 0 => Port 1 */ if (channel_select[1] & 2) cd_buffer_temp[1] += ((double) cd_buffer[i][c + 1]); /* Channel 1 => Port 1 */ cd_buffer_temp[1] *= audio_vol_r; /* Multiply Port 1 by Port 1 volume */ if (pre) cd_buffer_temp[1] = deemph_iir(1, cd_buffer_temp[1]); /* De-emphasize if necessary */ } /* Apply sound card CD volume and filters */ if (filter_cd_audio != NULL) { filter_cd_audio(0, &(cd_buffer_temp[0]), filter_cd_audio_p); filter_cd_audio(1, &(cd_buffer_temp[1]), filter_cd_audio_p); } if (sound_is_float) { cd_out_buffer[c] += (float) (cd_buffer_temp[0] / 32768.0); cd_out_buffer[c + 1] += (float) (cd_buffer_temp[1] / 32768.0); } else { temp_buffer[0] += (int) trunc(cd_buffer_temp[0]); temp_buffer[1] += (int) trunc(cd_buffer_temp[1]); if (temp_buffer[0] > 32767) temp_buffer[0] = 32767; if (temp_buffer[0] < -32768) temp_buffer[0] = -32768; if (temp_buffer[1] > 32767) temp_buffer[1] = 32767; if (temp_buffer[1] < -32768) temp_buffer[1] = -32768; cd_out_buffer_int16[c] = (int16_t) temp_buffer[0]; cd_out_buffer_int16[c + 1] = (int16_t) temp_buffer[1]; } } } if (sound_is_float) givealbuffer_cd(cd_out_buffer); else givealbuffer_cd(cd_out_buffer_int16); } } static void sound_realloc_buffers(void) { if (outbuffer_ex != NULL) { free(outbuffer_ex); outbuffer_ex = NULL; } if (outbuffer_ex_int16 != NULL) { free(outbuffer_ex_int16); outbuffer_ex_int16 = NULL; } if (sound_is_float) { outbuffer_ex = calloc(SOUNDBUFLEN * 2, sizeof(float)); memset(outbuffer_ex, 0x00, SOUNDBUFLEN * 2 * sizeof(float)); } else { outbuffer_ex_int16 = calloc(SOUNDBUFLEN * 2, sizeof(int16_t)); memset(outbuffer_ex_int16, 0x00, SOUNDBUFLEN * 2 * sizeof(int16_t)); } } static void music_realloc_buffers(void) { if (outbuffer_m_ex != NULL) { free(outbuffer_m_ex); outbuffer_m_ex = NULL; } if (outbuffer_m_ex_int16 != NULL) { free(outbuffer_m_ex_int16); outbuffer_m_ex_int16 = NULL; } if (sound_is_float) { outbuffer_m_ex = calloc(MUSICBUFLEN * 2, sizeof(float)); memset(outbuffer_m_ex, 0x00, MUSICBUFLEN * 2 * sizeof(float)); } else { outbuffer_m_ex_int16 = calloc(MUSICBUFLEN * 2, sizeof(int16_t)); memset(outbuffer_m_ex_int16, 0x00, MUSICBUFLEN * 2 * sizeof(int16_t)); } } static void wavetable_realloc_buffers(void) { if (outbuffer_w_ex != NULL) { free(outbuffer_w_ex); outbuffer_w_ex = NULL; } if (outbuffer_w_ex_int16 != NULL) { free(outbuffer_w_ex_int16); outbuffer_w_ex_int16 = NULL; } if (sound_is_float) { outbuffer_w_ex = calloc(WTBUFLEN * 2, sizeof(float)); memset(outbuffer_w_ex, 0x00, WTBUFLEN * 2 * sizeof(float)); } else { outbuffer_w_ex_int16 = calloc(WTBUFLEN * 2, sizeof(int16_t)); memset(outbuffer_w_ex_int16, 0x00, WTBUFLEN * 2 * sizeof(int16_t)); } } void sound_init(void) { int available_cdrom_drives = 0; outbuffer_ex = NULL; outbuffer_ex_int16 = NULL; outbuffer_m_ex = NULL; outbuffer_m_ex_int16 = NULL; outbuffer_w_ex = NULL; outbuffer_w_ex_int16 = NULL; outbuffer = NULL; outbuffer = calloc(SOUNDBUFLEN * 2, sizeof(int32_t)); memset(outbuffer, 0x00, SOUNDBUFLEN * 2 * sizeof(int32_t)); outbuffer_m = NULL; outbuffer_m = calloc(MUSICBUFLEN * 2, sizeof(int32_t)); memset(outbuffer_m, 0x00, MUSICBUFLEN * 2 * sizeof(int32_t)); outbuffer_w = NULL; outbuffer_w = calloc(WTBUFLEN * 2, sizeof(int32_t)); memset(outbuffer_w, 0x00, WTBUFLEN * 2 * sizeof(int32_t)); for (uint16_t i = 0; i < 256; i++) { double di = (double) i; if (di >= 255.0) di = 1.0; else if (di > 0.0) di = (48.0 + (20.0 * log(di / 256.0))) / 48.0; else di = 0.0; cd_audio_volume_lut[i] = di; } for (uint8_t i = 0; i < CDROM_NUM; i++) { if (cdrom[i].bus_type != CDROM_BUS_DISABLED) available_cdrom_drives++; } if (available_cdrom_drives) { cdaudioon = 1; sound_cd_start_event = thread_create_event(); sound_cd_event = thread_create_event(); sound_cd_thread_h = thread_create(sound_cd_thread, NULL); sound_log("Waiting for CD start event...\n"); thread_wait_event(sound_cd_start_event, -1); thread_reset_event(sound_cd_start_event); sound_log("Done!\n"); } else cdaudioon = 0; cd_thread_enable = available_cdrom_drives ? 1 : 0; } void sound_add_handler(void (*get_buffer)(int32_t *buffer, int len, void *priv), void *priv) { sound_handlers[sound_handlers_num].get_buffer = get_buffer; sound_handlers[sound_handlers_num].priv = priv; sound_handlers_num++; } void music_add_handler(void (*get_buffer)(int32_t *buffer, int len, void *priv), void *priv) { music_handlers[music_handlers_num].get_buffer = get_buffer; music_handlers[music_handlers_num].priv = priv; music_handlers_num++; } void wavetable_add_handler(void (*get_buffer)(int32_t *buffer, int len, void *priv), void *priv) { wavetable_handlers[wavetable_handlers_num].get_buffer = get_buffer; wavetable_handlers[wavetable_handlers_num].priv = priv; wavetable_handlers_num++; } void sound_set_cd_audio_filter(void (*filter)(int channel, double *buffer, void *priv), void *priv) { if ((filter_cd_audio == NULL) || (filter == NULL)) { filter_cd_audio = filter; filter_cd_audio_p = priv; } } void sound_set_pc_speaker_filter(void (*filter)(int channel, double *buffer, void *priv), void *priv) { if ((filter_pc_speaker == NULL) || (filter == NULL)) { filter_pc_speaker = filter; filter_pc_speaker_p = priv; } } void sound_poll(UNUSED(void *priv)) { timer_advance_u64(&sound_poll_timer, sound_poll_latch); midi_poll(); sound_pos_global++; if (sound_pos_global == SOUNDBUFLEN) { int c; memset(outbuffer, 0x00, SOUNDBUFLEN * 2 * sizeof(int32_t)); for (c = 0; c < sound_handlers_num; c++) sound_handlers[c].get_buffer(outbuffer, SOUNDBUFLEN, sound_handlers[c].priv); for (c = 0; c < SOUNDBUFLEN * 2; c++) { if (sound_is_float) outbuffer_ex[c] = ((float) outbuffer[c]) / (float) 32768.0; else { if (outbuffer[c] > 32767) outbuffer[c] = 32767; if (outbuffer[c] < -32768) outbuffer[c] = -32768; outbuffer_ex_int16[c] = (int16_t) outbuffer[c]; } } if (sound_is_float) givealbuffer(outbuffer_ex); else givealbuffer(outbuffer_ex_int16); if (cd_thread_enable) { cd_buf_update--; if (!cd_buf_update) { cd_buf_update = (SOUND_FREQ / SOUNDBUFLEN) / (CD_FREQ / CD_BUFLEN); thread_set_event(sound_cd_event); } } sound_pos_global = 0; } } void music_poll(UNUSED(void *priv)) { timer_advance_u64(&music_poll_timer, music_poll_latch); music_pos_global++; if (music_pos_global == MUSICBUFLEN) { int c; memset(outbuffer_m, 0x00, MUSICBUFLEN * 2 * sizeof(int32_t)); for (c = 0; c < music_handlers_num; c++) music_handlers[c].get_buffer(outbuffer_m, MUSICBUFLEN, music_handlers[c].priv); for (c = 0; c < MUSICBUFLEN * 2; c++) { if (sound_is_float) outbuffer_m_ex[c] = ((float) outbuffer_m[c]) / (float) 32768.0; else { if (outbuffer_m[c] > 32767) outbuffer_m[c] = 32767; if (outbuffer_m[c] < -32768) outbuffer_m[c] = -32768; outbuffer_m_ex_int16[c] = (int16_t) outbuffer_m[c]; } } if (sound_is_float) givealbuffer_music(outbuffer_m_ex); else givealbuffer_music(outbuffer_m_ex_int16); music_pos_global = 0; } } void wavetable_poll(UNUSED(void *priv)) { timer_advance_u64(&wavetable_poll_timer, wavetable_poll_latch); wavetable_pos_global++; if (wavetable_pos_global == WTBUFLEN) { int c; memset(outbuffer_w, 0x00, WTBUFLEN * 2 * sizeof(int32_t)); for (c = 0; c < wavetable_handlers_num; c++) wavetable_handlers[c].get_buffer(outbuffer_w, WTBUFLEN, wavetable_handlers[c].priv); for (c = 0; c < WTBUFLEN * 2; c++) { if (sound_is_float) outbuffer_w_ex[c] = ((float) outbuffer_w[c]) / (float) 32768.0; else { if (outbuffer_w[c] > 32767) outbuffer_w[c] = 32767; if (outbuffer_w[c] < -32768) outbuffer_w[c] = -32768; outbuffer_w_ex_int16[c] = (int16_t) outbuffer_w[c]; } } if (sound_is_float) givealbuffer_wt(outbuffer_w_ex); else givealbuffer_wt(outbuffer_w_ex_int16); wavetable_pos_global = 0; } } void sound_speed_changed(void) { sound_poll_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / (double) SOUND_FREQ)); music_poll_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / (double) MUSIC_FREQ)); wavetable_poll_latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / (double) WT_FREQ)); } void sound_reset(void) { sound_realloc_buffers(); music_realloc_buffers(); wavetable_realloc_buffers(); midi_out_device_init(); midi_in_device_init(); inital(); timer_add(&sound_poll_timer, sound_poll, NULL, 1); sound_handlers_num = 0; memset(sound_handlers, 0x00, 8 * sizeof(sound_handler_t)); timer_add(&music_poll_timer, music_poll, NULL, 1); music_handlers_num = 0; memset(music_handlers, 0x00, 8 * sizeof(sound_handler_t)); timer_add(&wavetable_poll_timer, wavetable_poll, NULL, 1); wavetable_handlers_num = 0; memset(wavetable_handlers, 0x00, 8 * sizeof(sound_handler_t)); filter_cd_audio = NULL; filter_cd_audio_p = NULL; filter_pc_speaker = NULL; filter_pc_speaker_p = NULL; sound_set_cd_volume(65535, 65535); /* Reset the MPU-401 already loaded flag and the chain of input/output handlers. */ midi_in_handlers_clear(); } void sound_card_reset(void) { sound_card_init(); if (mpu401_standalone_enable) mpu401_device_add(); } void sound_cd_thread_end(void) { if (cdaudioon) { cdaudioon = 0; sound_log("Waiting for CD Audio thread to terminate...\n"); thread_set_event(sound_cd_event); thread_wait(sound_cd_thread_h); sound_log("CD Audio thread terminated...\n"); if (sound_cd_event) { thread_destroy_event(sound_cd_event); sound_cd_event = NULL; } sound_cd_thread_h = NULL; if (sound_cd_start_event) { thread_destroy_event(sound_cd_start_event); sound_cd_event = NULL; } } } void sound_cd_thread_reset(void) { int available_cdrom_drives = 0; for (uint8_t i = 0; i < CDROM_NUM; i++) { cdrom_stop(&(cdrom[i])); if (cdrom[i].bus_type != CDROM_BUS_DISABLED) available_cdrom_drives++; } if (available_cdrom_drives && !cd_thread_enable) { cdaudioon = 1; sound_cd_start_event = thread_create_event(); sound_cd_event = thread_create_event(); sound_cd_thread_h = thread_create(sound_cd_thread, NULL); thread_wait_event(sound_cd_start_event, -1); thread_reset_event(sound_cd_start_event); } else if (!available_cdrom_drives && cd_thread_enable) sound_cd_thread_end(); cd_thread_enable = available_cdrom_drives ? 1 : 0; } ```
/content/code_sandbox/src/sound/sound.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
5,868
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Roland MPU-401 emulation. * * Authors: DOSBox Team, * Miran Grca, <mgrca8@gmail.com> * TheCollector1995, <mariogplayer@gmail.com> * */ #include <inttypes.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/machine.h> #include <86box/mca.h> #include <86box/midi.h> #include <86box/pic.h> #include <86box/plat.h> #include <86box/timer.h> #include <86box/snd_mpu401.h> #include <86box/sound.h> #include <86box/plat_unused.h> static uint32_t MPUClockBase[8] = { 48, 72, 96, 120, 144, 168, 192 }; static uint8_t cth_data[16] = { 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0 }; enum { STATUS_OUTPUT_NOT_READY = 0x40, STATUS_INPUT_NOT_READY = 0x80 }; int mpu401_standalone_enable = 0; static void MPU401_WriteCommand(mpu_t *mpu, uint8_t val); static void MPU401_WriteData(mpu_t *mpu, uint8_t val); static void MPU401_IntelligentOut(mpu_t *mpu, uint8_t track); static void MPU401_EOIHandler(void *priv); static void MPU401_EOIHandlerDispatch(void *priv); static __inline void MPU401_NotesOff(mpu_t *mpu, unsigned int i); #ifdef ENABLE_MPU401_LOG int mpu401_do_log = ENABLE_MPU401_LOG; static void mpu401_log(const char *fmt, ...) { va_list ap; if (mpu401_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define mpu401_log(fmt, ...) #endif static void MPU401_UpdateIRQ(mpu_t *mpu, int set) { /* Clear IRQ. */ if ((mpu->irq > 0) && (mpu->irq <= 15)) { mpu401_log("MPU401_UpdateIRQ(): Int IRQ %i %s.\n", mpu->irq, set ? "set" : "cleared"); picint_common(1 << mpu->irq, PIC_IRQ_EDGE, set, NULL); } if (mpu->ext_irq_update) { mpu401_log("MPU401_UpdateIRQ(): Ext IRQ %s.\n", set ? "set" : "cleared"); mpu->ext_irq_update(mpu->priv, set); } } static void MPU401_ReCalcClock(mpu_t *mpu) { int32_t mintempo = 16; int32_t maxtempo = 240; int32_t freq; if (mpu->clock.timebase < 72) { maxtempo = 240; mintempo = 32; } else if (mpu->clock.timebase < 120) { maxtempo = 240; mintempo = 16; } else if (mpu->clock.timebase < 168) { maxtempo = 208; mintempo = 8; } else { maxtempo = 179; mintempo = 8; } mpu->clock.freq = ((uint32_t) (mpu->clock.tempo * 2 * mpu->clock.tempo_rel)) >> 6; mpu->clock.freq = mpu->clock.timebase * (mpu->clock.freq < (mintempo * 2) ? mintempo : ((mpu->clock.freq / 2) < maxtempo ? (mpu->clock.freq / 2) : maxtempo)); if (mpu->state.sync_in) { freq = (int32_t) ((double) (mpu->clock.freq) * mpu->clock.freq_mod); if ((freq > (mpu->clock.timebase * mintempo)) && (freq < (mpu->clock.timebase * maxtempo))) mpu->clock.freq = freq; } } static void MPU401_ReStartClock(mpu_t *mpu) { if (mpu->clock.active) { timer_disable(&mpu->mpu401_event_callback); timer_set_delay_u64(&mpu->mpu401_event_callback, (MPU401_TIMECONSTANT / mpu->clock.freq) * 1000 * TIMER_USEC); mpu401_log("MPU-401: Clock restarted\n"); } } static __inline void MPU401_StartClock(mpu_t *mpu) { if (!mpu->clock.active && (mpu->state.playing || mpu->state.clock_to_host || (mpu->state.rec == M_RECON))) { mpu->clock.active = 1; timer_set_delay_u64(&mpu->mpu401_event_callback, (MPU401_TIMECONSTANT / mpu->clock.freq) * 1000 * TIMER_USEC); mpu401_log("MPU-401: Clock started\n"); } } static __inline void MPU401_StopClock(mpu_t *mpu) { if (mpu->clock.active && !mpu->state.playing && !mpu->state.clock_to_host && (mpu->state.rec != M_RECON)) { mpu->clock.active = 0; timer_disable(&mpu->mpu401_event_callback); mpu401_log("MPU-401: Clock stopped\n"); } } static __inline void MPU401_RunClock(mpu_t *mpu) { if (mpu->clock.active) timer_advance_u64(&mpu->mpu401_event_callback, (MPU401_TIMECONSTANT / mpu->clock.freq) * 1000 * TIMER_USEC); else timer_disable(&mpu->mpu401_event_callback); } static void MPU401_QueueByte(mpu_t *mpu, uint8_t data) { if (mpu->state.block_ack) { mpu->state.block_ack = 0; return; } mpu401_log("QueueByte Used=%d.\n", mpu->queue_used); if (!mpu->queue_used) { mpu->state.irq_pending = 1; MPU401_UpdateIRQ(mpu, 1); } if (mpu->queue_used < MPU401_QUEUE) { if (mpu->queue_pos > MPU401_QUEUE) fatal("MPU queue overflow\n"); uint8_t pos = mpu->queue_used + mpu->queue_pos; if (mpu->queue_pos >= MPU401_QUEUE) mpu->queue_pos -= MPU401_QUEUE; if (pos >= MPU401_QUEUE) pos -= MPU401_QUEUE; mpu->queue_used++; if (pos >= MPU401_QUEUE) fatal("MPU position overflow\n"); mpu->queue[pos] = data; } } static void MPU401_RecQueueBuffer(mpu_t *mpu, uint8_t *buf, unsigned int len) { unsigned int cnt = 0; while (cnt < len) { if (mpu->rec_queue_used < MPU401_INPUT_QUEUE) { unsigned int pos = mpu->rec_queue_used + mpu->rec_queue_pos; if (pos >= MPU401_INPUT_QUEUE) pos -= MPU401_INPUT_QUEUE; mpu->rec_queue[pos] = buf[cnt]; mpu->rec_queue_used++; if (!mpu->state.sysex_in_finished && (buf[cnt] == MSG_EOX)) { /* Finish SysEx */ mpu->state.sysex_in_finished = 1; break; } cnt++; } } if (!mpu->queue_used) { if (mpu->state.rec_copy || mpu->state.irq_pending) { if (mpu->state.irq_pending) { mpu->state.irq_pending = 0; MPU401_UpdateIRQ(mpu, 0); } return; } mpu->state.rec_copy = 1; if (mpu->rec_queue_pos >= MPU401_INPUT_QUEUE) mpu->rec_queue_pos -= MPU401_INPUT_QUEUE; MPU401_QueueByte(mpu, mpu->rec_queue[mpu->rec_queue_pos]); mpu->rec_queue_used--; mpu->rec_queue_pos++; } } static void MPU401_ClrQueue(mpu_t *mpu) { mpu->queue_used = 0; mpu->queue_pos = 0; mpu->rec_queue_used = 0; mpu->rec_queue_pos = 0; mpu->state.sysex_in_finished = 1; mpu->state.irq_pending = 0; MPU401_UpdateIRQ(mpu, 0); } static void MPU401_Reset(mpu_t *mpu) { uint8_t i; midi_reset(); /* Clear MIDI buffers, terminate notes. */ midi_clear_buffer(); for (i = 0xb0; i <= 0xbf; i++) { midi_raw_out_byte(i); midi_raw_out_byte(0x7b); midi_raw_out_byte(0); } mpu->state.irq_pending = 0; MPU401_UpdateIRQ(mpu, 0); timer_disable(&mpu->mpu401_event_callback); mpu->mode = M_INTELLIGENT; mpu->midi_thru = 0; mpu->state.rec = M_RECOFF; mpu->state.eoi_scheduled = 0; mpu->state.wsd = 0; mpu->state.wsm = 0; mpu->state.conductor = 0; mpu->state.cond_req = 0; mpu->state.cond_set = 0; mpu->state.playing = 0; mpu->state.run_irq = 0; mpu->state.cmask = 0xff; mpu->state.amask = mpu->state.tmask = 0; mpu->state.midi_mask = 0xffff; mpu->state.command_byte = 0; mpu->state.block_ack = 0; mpu->clock.tempo = mpu->clock.old_tempo = 100; mpu->clock.timebase = mpu->clock.old_timebase = 120; mpu->clock.tempo_rel = mpu->clock.old_tempo_rel = 0x40; mpu->clock.freq_mod = 1.0; mpu->clock.tempo_grad = 0; mpu->state.clock_to_host = 0; MPU401_StopClock(mpu); MPU401_ReCalcClock(mpu); for (i = 0; i < 4; i++) mpu->clock.cth_rate[i] = 60; mpu->clock.cth_counter = 0; mpu->clock.midimetro = 12; mpu->clock.metromeas = 8; mpu->filter.rec_measure_end = 1; mpu->filter.rt_out = 1; mpu->filter.rt_affection = 1; mpu->filter.allnotesoff_out = 1; mpu->filter.all_thru = 1; mpu->filter.midi_thru = 1; mpu->filter.commonmsgs_thru = 1; /* Reset channel reference and input tables. */ for (i = 0; i < 4; i++) { mpu->chanref[i].on = 1; mpu->chanref[i].chan = i; mpu->ch_toref[i] = i; } for (i = 0; i < 16; i++) { mpu->inputref[i].on = 1; mpu->inputref[i].chan = i; if (i > 3) mpu->ch_toref[i] = 4; /* Dummy reftable. */ } MPU401_ClrQueue(mpu); mpu->state.data_onoff = -1; mpu->state.req_mask = 0; mpu->condbuf.counter = 0; mpu->condbuf.type = T_OVERFLOW; for (i = 0; i < 8; i++) { mpu->playbuf[i].type = T_OVERFLOW; mpu->playbuf[i].counter = 0; } /* Clear MIDI buffers, terminate notes. */ midi_clear_buffer(); for (i = 0xb0; i <= 0xbf; i++) { midi_raw_out_byte(i); midi_raw_out_byte(0x7b); midi_raw_out_byte(0); } } static uint8_t MPU401_ReadStatus(mpu_t *mpu) { uint8_t ret = 0x00; if (mpu->state.cmd_pending) ret = STATUS_OUTPUT_NOT_READY; if (!mpu->queue_used) ret = STATUS_INPUT_NOT_READY; ret |= 0x3f; return ret; } static void MPU401_ResetDone(void *priv) { mpu_t *mpu = (mpu_t *) priv; mpu->state.reset = 0; if (mpu->state.cmd_pending) { MPU401_WriteCommand(mpu, mpu->state.cmd_pending - 1); mpu->state.cmd_pending = 0; } } static void MPU401_WriteCommand(mpu_t *mpu, uint8_t val) { uint8_t i; uint8_t j; uint8_t was_uart; uint8_t recmsg[3]; if (mpu->state.reset) mpu->state.cmd_pending = val + 1; /* The only command recognized in UART mode is 0xFF: Reset and return to Intelligent mode. */ if ((val != 0xff) && (mpu->mode == M_UART)) return; /* In Intelligent mode, UART-only variants of the MPU-401 only support commands 0x3F and 0xFF. */ if (!mpu->intelligent && (val != 0x3f) && (val != 0xff)) return; /* Hack: Enable midi through after the first mpu401 command is written. */ mpu->midi_thru = 1; if (val <= 0x2f) { /* Sequencer state */ int send_prchg = 0; if ((val & 0xf) < 0xc) { switch (val & 3) { /* MIDI realtime messages */ case 1: mpu->state.last_rtcmd = 0xfc; if (mpu->filter.rt_out) midi_raw_out_rt_byte(0xfc); mpu->clock.meas_old = mpu->clock.measure_counter; mpu->clock.cth_old = mpu->clock.cth_counter; break; case 2: mpu->state.last_rtcmd = 0xfa; if (mpu->filter.rt_out) midi_raw_out_rt_byte(0xfb); mpu->clock.measure_counter = mpu->clock.meas_old = 0; mpu->clock.cth_counter = mpu->clock.cth_old = 0; break; case 3: mpu->state.last_rtcmd = 0xfc; if (mpu->filter.rt_out) midi_raw_out_rt_byte(0xfa); mpu->clock.measure_counter = mpu->clock.meas_old; mpu->clock.cth_counter = mpu->clock.cth_old; break; default: break; } switch (val & 0xc) { /* Playing */ case 0x4: /* Stop */ mpu->state.playing = 0; MPU401_StopClock(mpu); for (i = 0; i < 16; i++) MPU401_NotesOff(mpu, i); mpu->filter.prchg_mask = 0; break; case 0x8: /* Start */ mpu->state.playing = 1; MPU401_StartClock(mpu); MPU401_ClrQueue(mpu); break; default: break; } switch (val & 0x30) { /* Recording */ case 0: /* check if it waited for MIDI RT command */ if (((val & 3) < 2) || !mpu->filter.rt_affection || (mpu->state.rec != M_RECSTB)) break; mpu->state.rec = M_RECON; MPU401_StartClock(mpu); if (mpu->filter.prchg_mask) send_prchg = 1; break; case 0x10: /* Stop */ mpu->state.rec = M_RECOFF; MPU401_StopClock(mpu); MPU401_QueueByte(mpu, MSG_MPU_ACK); MPU401_QueueByte(mpu, mpu->clock.rec_counter); MPU401_QueueByte(mpu, MSG_MPU_END); mpu->filter.prchg_mask = 0; mpu->clock.rec_counter = 0; return; case 0x20: /* Start */ if (!(mpu->state.rec == M_RECON)) { mpu->clock.rec_counter = 0; mpu->state.rec = M_RECSTB; } if ((mpu->state.last_rtcmd == 0xfa) || (mpu->state.last_rtcmd == 0xfb)) { mpu->clock.rec_counter = 0; mpu->state.rec = M_RECON; if (mpu->filter.prchg_mask) send_prchg = 1; MPU401_StartClock(mpu); } break; default: break; } } MPU401_QueueByte(mpu, MSG_MPU_ACK); /* record counter hack: needed by Prism, but sent only on cmd 0x20/0x26 (or breaks Ballade) */ uint8_t rec_cnt = mpu->clock.rec_counter; if (((val == 0x20) || (val == 0x26)) && (mpu->state.rec == M_RECON)) MPU401_RecQueueBuffer(mpu, &rec_cnt, 1); if (send_prchg) { for (i = 0; i < 16; i++) { if (mpu->filter.prchg_mask & (1 << i)) { recmsg[0] = mpu->clock.rec_counter; recmsg[1] = 0xc0 | i; recmsg[2] = mpu->filter.prchg_buf[i]; MPU401_RecQueueBuffer(mpu, recmsg, 3); mpu->filter.prchg_mask &= ~(1 << i); } } } return; } else if ((val >= 0xa0) && (val <= 0xa7)) /* Request play counter */ MPU401_QueueByte(mpu, mpu->playbuf[val & 7].counter); else if ((val >= 0xd0) && (val <= 0xd7)) { /* Send data */ mpu->state.old_track = mpu->state.track; mpu->state.track = val & 7; mpu->state.wsd = 1; mpu->state.wsm = 0; mpu->state.wsd_start = 1; } else if ((val < 0x80) && (val >= 0x40)) { /* Set reference table channel */ mpu->chanref[(val >> 4) - 4].on = 1; mpu->chanref[(val >> 4) - 4].chan = val & 0x0f; mpu->chanref[(val >> 4) - 4].trmask = 0; for (i = 0; i < 4; i++) mpu->chanref[(val >> 4) - 4].key[i] = 0; for (i = 0; i < 16; i++) { if (mpu->ch_toref[i] == ((val >> 4) - 4)) mpu->ch_toref[i] = 4; } mpu->ch_toref[val & 0x0f] = (val >> 4) - 4; } else switch (val) { case 0x30: /* Configuration 0x30 - 0x39 */ mpu->filter.allnotesoff_out = 0; break; case 0x32: mpu->filter.rt_out = 0; break; case 0x33: mpu->filter.all_thru = 0; mpu->filter.commonmsgs_thru = 0; mpu->filter.midi_thru = 0; for (i = 0; i < 16; i++) { mpu->inputref[i].on = 0; for (j = 0; j < 4; j++) mpu->inputref[i].key[j] = 0; } break; case 0x34: mpu->filter.timing_in_stop = 1; break; case 0x35: mpu->filter.modemsgs_in = 1; break; case 0x37: mpu->filter.sysex_thru = 1; break; case 0x38: mpu->filter.commonmsgs_in = 1; break; case 0x39: mpu->filter.rt_in = 1; break; case 0x3f: /* UART mode */ mpu401_log("MPU-401: Set UART mode %X\n", val); MPU401_QueueByte(mpu, MSG_MPU_ACK); mpu->mode = M_UART; return; case 0x80: /* Internal clock */ if (mpu->clock.active && mpu->state.sync_in) { timer_set_delay_u64(&mpu->mpu401_event_callback, (MPU401_TIMECONSTANT / mpu->clock.freq) * 1000 * TIMER_USEC); mpu->clock.freq_mod = 1.0; } mpu->state.sync_in = 0; break; case 0x81: /* Sync to tape signal */ case 0x82: /* Sync to MIDI */ mpu->clock.ticks_in = 0; mpu->state.sync_in = 1; break; case 0x86: case 0x87: /* Bender */ mpu->filter.bender_in = !!(val & 1); break; case 0x88: case 0x89: /* MIDI through */ mpu->filter.midi_thru = !!(val & 1); for (i = 0; i < 16; i++) { mpu->inputref[i].on = mpu->filter.midi_thru; if (!(val & 1)) { for (j = 0; j < 4; j++) mpu->inputref[i].key[j] = 0; } } break; case 0x8a: case 0x8b: /* Data in stop */ mpu->filter.data_in_stop = !!(val & 1); break; case 0x8c: case 0x8d: /* Send measure end */ mpu->filter.rec_measure_end = !!(val & 1); break; case 0x8e: case 0x8f: /* Conductor */ mpu->state.cond_set = !!(val & 1); break; case 0x90: case 0x91: /* Realtime affection */ mpu->filter.rt_affection = !!(val & 1); break; case 0x94: /* Clock to host */ mpu->state.clock_to_host = 0; MPU401_StopClock(mpu); break; case 0x95: mpu->state.clock_to_host = 1; MPU401_StartClock(mpu); break; case 0x96: case 0x97: /* Sysex input allow */ mpu->filter.sysex_in = !!(val & 1); if (val & 1) mpu->filter.sysex_thru = 0; break; case 0x98: case 0x99: case 0x9a: case 0x9b: /* Reference tables on/off */ case 0x9c: case 0x9d: case 0x9e: case 0x9f: mpu->chanref[(val - 0x98) / 2].on = !!(val & 1); break; /* Commands 0xa# returning data */ case 0xab: /* Request and clear recording counter */ MPU401_QueueByte(mpu, MSG_MPU_ACK); MPU401_QueueByte(mpu, 0); return; case 0xac: /* Request version */ MPU401_QueueByte(mpu, MSG_MPU_ACK); MPU401_QueueByte(mpu, MPU401_VERSION); return; case 0xad: /* Request revision */ MPU401_QueueByte(mpu, MSG_MPU_ACK); MPU401_QueueByte(mpu, MPU401_REVISION); return; case 0xaf: /* Request tempo */ MPU401_QueueByte(mpu, MSG_MPU_ACK); MPU401_QueueByte(mpu, mpu->clock.tempo); return; case 0xb1: /* Reset relative tempo */ mpu->clock.old_tempo_rel = mpu->clock.tempo_rel; mpu->clock.tempo_rel = 0x40; break; case 0xb8: /* Clear play counters */ mpu->state.last_rtcmd = 0; for (i = 0; i < 8; i++) { mpu->playbuf[i].counter = 0; mpu->playbuf[i].type = T_OVERFLOW; } mpu->condbuf.counter = 0; mpu->condbuf.type = T_OVERFLOW; mpu->state.amask = mpu->state.tmask; mpu->state.conductor = mpu->state.cond_set; mpu->clock.cth_counter = mpu->clock.cth_old = 0; mpu->clock.measure_counter = mpu->clock.meas_old = 0; mpu->state.req_mask = 0; mpu->state.irq_pending = 1; break; case 0xb9: /* Clear play map */ for (i = 0; i < 16; i++) MPU401_NotesOff(mpu, i); for (i = 0; i < 8; i++) { mpu->playbuf[i].counter = 0; mpu->playbuf[i].type = T_OVERFLOW; } mpu->state.last_rtcmd = 0; mpu->clock.cth_counter = mpu->clock.cth_old = 0; mpu->clock.measure_counter = mpu->clock.meas_old = 0; mpu->state.req_mask = 0; mpu->state.irq_pending = 1; break; case 0xba: /* Clear record counter */ mpu->clock.rec_counter = 0; break; case 0xc2: case 0xc3: case 0xc4: /* Internal timebase */ case 0xc5: case 0xc6: case 0xc7: case 0xc8: mpu->clock.timebase = MPUClockBase[val - 0xc2]; MPU401_ReCalcClock(mpu); MPU401_ReStartClock(mpu); break; case 0xdf: /* Send system message */ mpu->state.wsd = 0; mpu->state.wsm = 1; mpu->state.wsd_start = 1; break; /* Commands with data byte */ case 0xe0: case 0xe1: case 0xe2: case 0xe4: case 0xe6: case 0xe7: case 0xec: case 0xed: case 0xee: case 0xef: mpu->state.command_byte = val; break; case 0xff: /* Reset MPU-401 */ mpu401_log("MPU-401: Reset %X\n", val); timer_set_delay_u64(&mpu->mpu401_reset_callback, MPU401_RESETBUSY * 33LL * TIMER_USEC); mpu->state.reset = 1; was_uart = (mpu->mode == M_UART); MPU401_Reset(mpu); if (was_uart) return; break; default: #if 0 mpu401_log("MPU-401:Unhandled command %X",val); #endif break; } MPU401_QueueByte(mpu, MSG_MPU_ACK); } void MPU401_ReadRaiseIRQ(mpu_t *mpu) { /* Clear IRQ. */ MPU401_UpdateIRQ(mpu, 0); if (mpu->queue_used) MPU401_UpdateIRQ(mpu, 1); } uint8_t MPU401_ReadData(mpu_t *mpu) { uint8_t ret = MSG_MPU_ACK; if (mpu->queue_used) { mpu->queue_pos -= (mpu->queue_pos >= MPU401_QUEUE) ? MPU401_QUEUE : 0; ret = mpu->queue[mpu->queue_pos]; mpu->queue_pos++; mpu->queue_used--; } /* Shouldn't this check mpu->mode? */ if (!mpu->intelligent || (mpu->mode == M_UART)) { MPU401_ReadRaiseIRQ(mpu); return ret; } mpu401_log("QueueUsed=%d.\n", mpu->queue_used); if (!mpu->queue_used) MPU401_UpdateIRQ(mpu, 0); if (mpu->state.rec_copy && !mpu->rec_queue_used) { MPU401_ReadRaiseIRQ(mpu); mpu->state.rec_copy = 0; MPU401_EOIHandler(mpu); return ret; } /* Copy from recording buffer. */ if (!mpu->queue_used && mpu->rec_queue_used) { mpu->state.rec_copy = 1; if (mpu->rec_queue_pos >= MPU401_INPUT_QUEUE) mpu->rec_queue_pos -= MPU401_INPUT_QUEUE; MPU401_QueueByte(mpu, mpu->rec_queue[mpu->rec_queue_pos]); mpu->rec_queue_pos++; mpu->rec_queue_used--; } MPU401_ReadRaiseIRQ(mpu); if ((ret >= 0xf0) && (ret <= 0xf7)) { /* MIDI data request */ mpu->state.track = ret & 7; mpu->state.data_onoff = 0; mpu->state.cond_req = 0; mpu->state.track_req = 1; } if (ret == MSG_MPU_COMMAND_REQ) { mpu->state.data_onoff = 0; mpu->state.cond_req = 1; if (mpu->condbuf.type != T_OVERFLOW) { mpu->state.block_ack = 1; MPU401_WriteCommand(mpu, mpu->condbuf.value[0]); if (mpu->state.command_byte) MPU401_WriteData(mpu, mpu->condbuf.value[1]); mpu->condbuf.type = T_OVERFLOW; } } if ((ret == MSG_MPU_END) || (ret == MSG_MPU_CLOCK) || (ret == MSG_MPU_ACK) || (ret == MSG_MPU_OVERFLOW)) MPU401_EOIHandlerDispatch(mpu); return ret; } static void MPU401_WriteData(mpu_t *mpu, uint8_t val) { static unsigned int length; static unsigned int cnt; static unsigned int posd; if (!mpu->intelligent || (mpu->mode == M_UART)) { midi_raw_out_byte(val); if (val == 0xff) midi_reset(); return; } switch (mpu->state.command_byte) { /* 0xe# command data */ case 0x00: break; case 0xe0: /* Set tempo */ mpu->state.command_byte = 0; if (mpu->clock.tempo < 8) mpu->clock.tempo = 8; else if (mpu->clock.tempo > 250) mpu->clock.tempo = 250; else mpu->clock.tempo = val; MPU401_ReCalcClock(mpu); MPU401_ReStartClock(mpu); return; case 0xe1: /* Set relative tempo */ mpu->state.command_byte = 0; mpu->clock.old_tempo_rel = mpu->clock.tempo_rel; mpu->clock.tempo_rel = val; MPU401_ReCalcClock(mpu); MPU401_ReStartClock(mpu); return; case 0xe2: /* Set gradation for relative tempo */ mpu->state.command_byte = 0; mpu->clock.tempo_grad = val; MPU401_ReCalcClock(mpu); MPU401_ReStartClock(mpu); return; case 0xe4: /* Set MIDI clocks for metronome ticks */ mpu->state.command_byte = 0; mpu->clock.midimetro = val; return; case 0xe6: /* Set metronome ticks per measure */ mpu->state.command_byte = 0; mpu->clock.metromeas = val; return; case 0xe7: /* Set internal clock to host interval */ mpu->state.command_byte = 0; if (!val) val = 64; for (uint8_t i = 0; i < 4; i++) mpu->clock.cth_rate[i] = (val >> 2) + cth_data[(val & 3) * 4 + i]; mpu->clock.cth_mode = 0; return; case 0xec: /* Set active track mask */ mpu->state.command_byte = 0; mpu->state.tmask = val; return; case 0xed: /* Set play counter mask */ mpu->state.command_byte = 0; mpu->state.cmask = val; return; case 0xee: /* Set 1-8 MIDI channel mask */ mpu->state.command_byte = 0; mpu->state.midi_mask &= 0xff00; mpu->state.midi_mask |= val; return; case 0xef: /* Set 9-16 MIDI channel mask */ mpu->state.command_byte = 0; mpu->state.midi_mask &= 0x00ff; mpu->state.midi_mask |= ((uint16_t) val) << 8; return; default: mpu->state.command_byte = 0; return; } if (mpu->state.wsd && !mpu->state.track_req && !mpu->state.cond_req) { /* Directly send MIDI message */ if (mpu->state.wsd_start) { mpu->state.wsd_start = 0; cnt = 0; switch (val & 0xf0) { case 0xc0: case 0xd0: length = mpu->playbuf[mpu->state.track].length = 2; mpu->playbuf[mpu->state.track].type = T_MIDI_NORM; break; case 0x80: case 0x90: case 0xa0: case 0xb0: case 0xe0: length = mpu->playbuf[mpu->state.track].length = 3; mpu->playbuf[mpu->state.track].type = T_MIDI_NORM; break; case 0xf0: #if 0 mpu401_log("MPU-401:Illegal WSD byte\n"); #endif mpu->state.wsd = 0; mpu->state.track = mpu->state.old_track; return; default: /* MIDI with running status */ cnt++; length = mpu->playbuf[mpu->state.track].length; mpu->playbuf[mpu->state.track].type = T_MIDI_NORM; } } if (cnt < length) { mpu->playbuf[mpu->state.track].value[cnt] = val; cnt++; } if (cnt == length) { mpu->playbuf[mpu->state.track].vlength = cnt; MPU401_IntelligentOut(mpu, mpu->state.track); mpu->state.wsd = 0; mpu->state.track = mpu->state.old_track; } return; } if (mpu->state.wsm && !mpu->state.track_req && !mpu->state.cond_req) { /* Send system message */ if (mpu->state.wsd_start) { mpu->state.wsd_start = 0; cnt = 0; switch (val) { case 0xf2: length = 3; break; case 0xf3: length = 2; break; case 0xf6: length = 1; break; case 0xf0: length = 0; break; default: length = 0; mpu->state.wsm = 0; break; } } else if (val & 0x80) { midi_raw_out_byte(MSG_EOX); mpu->state.wsm = 0; return; } if (!length || (cnt < length)) { midi_raw_out_byte(val); cnt++; } if (cnt == length) mpu->state.wsm = 0; return; } if (mpu->state.cond_req) { /* Command */ switch (mpu->state.data_onoff) { case -1: return; case 0: /* Timing byte */ mpu->condbuf.vlength = 0; if (val < 0xf0) mpu->state.data_onoff++; else { mpu->state.data_onoff = -1; MPU401_EOIHandlerDispatch(mpu); return; } /* A timing value of 0 means send it now! */ mpu->state.send_now = (val == 0); mpu->condbuf.counter = val; break; case 1: /* Command byte #1 */ mpu->condbuf.type = T_COMMAND; if ((val == 0xf8) || (val == 0xf9) || (val == 0xfc)) mpu->condbuf.type = T_OVERFLOW; mpu->condbuf.value[mpu->condbuf.vlength] = val; mpu->condbuf.vlength++; if ((val & 0xf0) != 0xe0) MPU401_EOIHandlerDispatch(mpu); else mpu->state.data_onoff++; break; case 2: /* Command byte #2 */ mpu->condbuf.value[mpu->condbuf.vlength] = val; mpu->condbuf.vlength++; MPU401_EOIHandlerDispatch(mpu); break; default: break; } return; } switch (mpu->state.data_onoff) { /* Data */ case -1: return; case 0: /* Timing byte */ if (val < 0xf0) mpu->state.data_onoff = 1; else { mpu->state.data_onoff = -1; MPU401_EOIHandlerDispatch(mpu); mpu->state.track_req = 0; return; } mpu->state.send_now = (val == 0); mpu->playbuf[mpu->state.track].counter = val; break; case 1: /* MIDI */ mpu->playbuf[mpu->state.track].vlength++; posd = mpu->playbuf[mpu->state.track].vlength; if (posd == 1) { switch (val & 0xf0) { case 0xc0: case 0xd0: /* MIDI Message */ mpu->playbuf[mpu->state.track].type = T_MIDI_NORM; length = mpu->playbuf[mpu->state.track].length = 2; break; case 0x80: case 0x90: case 0xa0: case 0xb0: case 0xe0: mpu->playbuf[mpu->state.track].type = T_MIDI_NORM; length = mpu->playbuf[mpu->state.track].length = 3; break; case 0xf0: /* System message or mark */ mpu->playbuf[mpu->state.track].sys_val = val; if (val > 0xf7) { mpu->playbuf[mpu->state.track].type = T_MARK; if (val == 0xf9) mpu->clock.measure_counter = 0; } else mpu->playbuf[mpu->state.track].type = T_OVERFLOW; length = 1; break; default: /* MIDI with running status */ posd++; length = mpu->playbuf[mpu->state.track].length; mpu->playbuf[mpu->state.track].vlength++; mpu->playbuf[mpu->state.track].type = T_MIDI_NORM; break; } } if (!((posd == 1) && (val >= 0xf0))) mpu->playbuf[mpu->state.track].value[posd - 1] = val; if (posd == length) { MPU401_EOIHandlerDispatch(mpu); mpu->state.track_req = 0; } break; } } static void MPU401_IntelligentOut(mpu_t *mpu, uint8_t track) { unsigned int chan; unsigned int chrefnum; uint8_t key; uint8_t msg; uint8_t val; int send; int retrigger; switch (mpu->playbuf[track].type) { case T_OVERFLOW: break; case T_MARK: val = mpu->playbuf[track].sys_val; if (val == 0xfc) { midi_raw_out_rt_byte(val); mpu->state.amask &= ~(1 << track); mpu->state.req_mask &= ~(1 << track); } break; case T_MIDI_NORM: chan = mpu->playbuf[track].value[0] & 0xf; key = mpu->playbuf[track].value[1] & 0x7f; chrefnum = mpu->ch_toref[chan]; send = 1; retrigger = 0; switch (msg = mpu->playbuf[track].value[0] & 0xf0) { case 0x80: /* Note off */ if (mpu->inputref[chan].on && (mpu->inputref[chan].M_GETKEY)) send = 0; if (mpu->chanref[chrefnum].on && (!(mpu->chanref[chrefnum].M_GETKEY))) send = 0; mpu->chanref[chrefnum].M_DELKEY; break; case 0x90: /* Note on */ if (mpu->inputref[chan].on && (mpu->inputref[chan].M_GETKEY)) retrigger = 1; if (mpu->chanref[chrefnum].on && (!(mpu->chanref[chrefnum].M_GETKEY))) retrigger = 1; mpu->chanref[chrefnum].M_SETKEY; break; case 0xb0: if (mpu->playbuf[track].value[1] == 123) { /* All notes off */ MPU401_NotesOff(mpu, mpu->playbuf[track].value[0] & 0xf); return; } break; default: break; } if (retrigger) { midi_raw_out_byte(0x80 | chan); midi_raw_out_byte(key); midi_raw_out_byte(0); } if (send) { for (uint8_t i = 0; i < mpu->playbuf[track].vlength; ++i) midi_raw_out_byte(mpu->playbuf[track].value[i]); } break; default: break; } } static void UpdateTrack(mpu_t *mpu, uint8_t track) { MPU401_IntelligentOut(mpu, track); if (mpu->state.amask & (1 << track)) { mpu->playbuf[track].vlength = 0; mpu->playbuf[track].type = T_OVERFLOW; mpu->playbuf[track].counter = 0xf0; mpu->state.req_mask |= (1 << track); } else { if ((mpu->state.amask == 0) && !mpu->state.conductor) mpu->state.req_mask |= (1 << 12); } } static void MPU401_Event(void *priv) { mpu_t *mpu = (mpu_t *) priv; if (!mpu->intelligent || (mpu->mode == M_UART)) return; if (mpu->state.irq_pending) goto next_event; if (mpu->state.playing) { /* Decrease counters. */ for (uint8_t i = 0; i < 8; i++) { if (mpu->state.amask & (1 << i)) { if (mpu->playbuf[i].counter) mpu->playbuf[i].counter--; if (!mpu->playbuf[i].counter) UpdateTrack(mpu, i); } } if (mpu->state.conductor) { if (mpu->condbuf.counter) mpu->condbuf.counter--; if (!mpu->condbuf.counter) { mpu->condbuf.vlength = 0; mpu->condbuf.counter = 0xf0; mpu->state.req_mask |= (1 << 9); } } } if (mpu->state.clock_to_host) { mpu->clock.cth_counter++; if (mpu->clock.cth_counter >= mpu->clock.cth_rate[mpu->clock.cth_mode]) { mpu->clock.cth_counter = 0; ++mpu->clock.cth_mode; mpu->clock.cth_mode %= 4; mpu->state.req_mask |= (1 << 13); } } /* Recording */ if (mpu->state.rec == M_RECON) { mpu->clock.rec_counter++; if (mpu->clock.rec_counter >= 240) { mpu->clock.rec_counter = 0; mpu->state.req_mask |= (1 << 8); } } if (mpu->state.playing || (mpu->state.rec == M_RECON)) { int max_meascnt = (mpu->clock.timebase * mpu->clock.midimetro * mpu->clock.metromeas) / 24; if (max_meascnt != 0) { /* Measure end */ if (++mpu->clock.measure_counter >= max_meascnt) { if (mpu->filter.rt_out) midi_raw_out_rt_byte(0xf8); mpu->clock.measure_counter=0; if (mpu->filter.rec_measure_end && (mpu->state.rec == M_RECON)) mpu->state.req_mask |= (1 << 12); } } } if (!mpu->state.irq_pending && mpu->state.req_mask) MPU401_EOIHandler(mpu); next_event: MPU401_RunClock(mpu); if (mpu->state.sync_in) mpu->clock.ticks_in++; } static void MPU401_EOIHandlerDispatch(void *priv) { mpu_t *mpu = (mpu_t *) priv; mpu401_log("EOI handler dispatch\n"); if (mpu->state.send_now) { mpu->state.eoi_scheduled = 1; timer_set_delay_u64(&mpu->mpu401_eoi_callback, 60LL * TIMER_USEC); /* Possibly a bit longer */ } else if (!mpu->state.eoi_scheduled) MPU401_EOIHandler(mpu); } /* Updates counters and requests new data on "End of Input" */ static void MPU401_EOIHandler(void *priv) { mpu_t *mpu = (mpu_t *) priv; mpu401_log("MPU-401 end of input callback\n"); mpu->state.eoi_scheduled = 0; if (mpu->state.send_now) { mpu->state.send_now = 0; if (mpu->state.cond_req) { mpu->condbuf.vlength = 0; mpu->condbuf.counter = 0xf0; mpu->state.req_mask |= (1 << 9); } else UpdateTrack(mpu, mpu->state.track); } if (mpu->state.rec_copy || !mpu->state.sysex_in_finished) return; mpu->state.irq_pending = 0; if (!mpu->state.req_mask || !mpu->clock.active) return; uint8_t i = 0; do { if (mpu->state.req_mask & (1 << i)) { MPU401_QueueByte(mpu, 0xf0 + i); mpu->state.req_mask &= ~(1 << i); break; } } while ((i++) < 16); } static __inline void MPU401_NotesOff(mpu_t *mpu, unsigned int i) { if (mpu->filter.allnotesoff_out && !(mpu->inputref[i].on && (mpu->inputref[i].key[0] | mpu->inputref[i].key[1] | mpu->inputref[i].key[2] | mpu->inputref[i].key[3]))) { for (uint8_t j = 0;j < 4; j++) mpu->chanref[mpu->ch_toref[i]].key[j] = 0; midi_raw_out_byte(0xb0 | i); midi_raw_out_byte(123); midi_raw_out_byte(0); } else if (mpu->chanref[mpu->ch_toref[i]].on) { for (uint8_t key = 0; key < 128; key++) { if ((mpu->chanref[mpu->ch_toref[i]].M_GETKEY) && !(mpu->inputref[i].on && (mpu->inputref[i].M_GETKEY))) { midi_raw_out_byte(0x80 | i); midi_raw_out_byte(key); midi_raw_out_byte(0); } mpu->chanref[mpu->ch_toref[i]].M_DELKEY; } } } static void imf_write(UNUSED(uint16_t addr), UNUSED(uint8_t val), UNUSED(void *priv)) { mpu401_log("IMF:Wr %4X,%X\n", addr, val); } void mpu401_write(uint16_t addr, uint8_t val, void *priv) { mpu_t *mpu = (mpu_t *) priv; /* mpu401_log("MPU401 Write Port %04X, val %x\n", addr, val); */ switch (addr & 1) { case 0: /*Data*/ MPU401_WriteData(mpu, val); mpu401_log("Write Data (0x330) %X\n", val); break; case 1: /*Command*/ MPU401_WriteCommand(mpu, val); mpu401_log("Write Command (0x331) %x\n", val); break; default: break; } } uint8_t mpu401_read(uint16_t addr, void *priv) { mpu_t *mpu = (mpu_t *) priv; uint8_t ret = 0; switch (addr & 1) { case 0: /* Read Data */ ret = MPU401_ReadData(mpu); mpu401_log("Read Data (0x330) %X\n", ret); break; case 1: /* Read Status */ ret = MPU401_ReadStatus(mpu); mpu401_log("Read Status (0x331) %x\n", ret); break; default: break; } /* mpu401_log("MPU401 Read Port %04X, ret %x\n", addr, ret); */ return ret; } /*Input handler for SysEx */ int MPU401_InputSysex(void *priv, uint8_t *buffer, uint32_t len, int abort) { mpu_t *mpu = (mpu_t *) priv; int i; uint8_t val_ff = 0xff; mpu401_log("MPU401 Input Sysex\n"); if (!mpu->intelligent || mpu->mode == M_UART) { /* UART mode input. */ for (i = 0; i < len; i++) MPU401_QueueByte(mpu, buffer[i]); MPU401_ReadRaiseIRQ(mpu); return 0; } if (mpu->filter.sysex_in) { if (abort) { mpu->state.sysex_in_finished = 1; mpu->rec_queue_used = 0; /*reset also the input queue*/ return 0; } if (mpu->state.sysex_in_finished) { if (mpu->rec_queue_used >= MPU401_INPUT_QUEUE) return len; MPU401_RecQueueBuffer(mpu, &val_ff, 1); mpu->state.sysex_in_finished = 0; mpu->clock.rec_counter = 0; } if (mpu->rec_queue_used >= MPU401_INPUT_QUEUE) return len; int available = MPU401_INPUT_QUEUE - mpu->rec_queue_used; if (available >= len) { MPU401_RecQueueBuffer(mpu, buffer, len); return 0; } else { MPU401_RecQueueBuffer(mpu, buffer, available); if (mpu->state.sysex_in_finished) return 0; return (len - available); } } else if (mpu->filter.sysex_thru && mpu->midi_thru) { midi_raw_out_byte(0xf0); for (i = 0; i < len; i++) midi_raw_out_byte(*(buffer + i)); } return 0; } /*Input handler for MIDI*/ void MPU401_InputMsg(void *priv, uint8_t *msg, uint32_t len) { mpu_t *mpu = (mpu_t *) priv; int i; int tick; static uint8_t old_msg = 0; uint8_t key; uint8_t recdata[2]; uint8_t recmsg[4]; int send = 1; int send_thru = 0; int retrigger_thru = 0; int chan; int chrefnum; /* Abort if sysex transfer is in progress. */ if (!mpu->state.sysex_in_finished) { mpu401_log("SYSEX in progress\n"); return; } mpu401_log("MPU401 Input Msg\n"); if (mpu->intelligent && (mpu->mode == M_INTELLIGENT)) { if (msg[0] < 0x80) { /* Expand running status */ msg[2] = msg[1]; msg[1] = msg[0]; msg[0] = old_msg; } old_msg = msg[0]; chan = msg[0] & 0xf; chrefnum = mpu->ch_toref[chan]; key = msg[1] & 0x7f; if (msg[0] < 0xf0) { /* If non-system msg. */ if (!(mpu->state.midi_mask & (1 << chan)) && mpu->filter.all_thru) send_thru = 1; else if (mpu->filter.midi_thru) send_thru = 1; switch (msg[0] & 0xf0) { case 0x80: /* Note off. */ if (send_thru) { if (mpu->chanref[chrefnum].on && (mpu->chanref[chrefnum].M_GETKEY)) send_thru = 0; if (!mpu->filter.midi_thru) break; if (!(mpu->inputref[chan].M_GETKEY)) send_thru = 0; mpu->inputref[chan].M_DELKEY; } break; case 0x90: /* Note on. */ if (send_thru) { if (mpu->chanref[chrefnum].on && (mpu->chanref[chrefnum].M_GETKEY)) retrigger_thru = 1; if (!mpu->filter.midi_thru) break; if (mpu->inputref[chan].M_GETKEY) retrigger_thru = 1; mpu->inputref[chan].M_SETKEY; } break; case 0xb0: if (msg[1] >= 120) { send_thru = 0; if (msg[1] == 123) { /* All notes off. */ for (key = 0; key < 128; key++) { if (!(mpu->chanref[chrefnum].on && (mpu->chanref[chrefnum].M_GETKEY))) { if (mpu->inputref[chan].on && mpu->inputref[chan].M_GETKEY) { midi_raw_out_byte(0x80 | chan); midi_raw_out_byte(key); midi_raw_out_byte(0); } mpu->inputref[chan].M_DELKEY; } } } } break; default: break; } } if ((msg[0] >= 0xf0) || (mpu->state.midi_mask & (1 << chan))) { switch (msg[0] & 0xf0) { case 0xa0: /* Aftertouch. */ if (!mpu->filter.bender_in) send = 0; break; case 0xb0: /* Control change. */ if (!mpu->filter.bender_in && (msg[1] < 64)) send = 0; if (msg[1] >= 120) { if (mpu->filter.modemsgs_in) send = 1; } break; case 0xc0: /* Program change. */ if ((mpu->state.rec != M_RECON) && !mpu->filter.data_in_stop) { mpu->filter.prchg_buf[chan] = msg[1]; mpu->filter.prchg_mask |= 1 << chan; } break; case 0xd0: /* Ch pressure. */ case 0xe0: /* Pitch wheel. */ if (!mpu->filter.bender_in) send = 0; break; case 0xf0: /* System message. */ if (msg[0] == 0xf8) { send = 0; if (mpu->clock.active && mpu->state.sync_in) { send = 0; /* Don't pass to host in this mode? */ tick = mpu->clock.timebase / 24; if (mpu->clock.ticks_in != tick) { if (!mpu->clock.ticks_in || (mpu->clock.ticks_in > (tick * 2))) mpu->clock.freq_mod *= 2.0; else { if (ABS(mpu->clock.ticks_in - tick) == 1) mpu->clock.freq_mod /= mpu->clock.ticks_in / (float) (tick * 2); else mpu->clock.freq_mod /= mpu->clock.ticks_in / (float) (tick); } MPU401_ReCalcClock(mpu); MPU401_ReStartClock(mpu); } mpu->clock.ticks_in = 0; } } else if (msg[0] > 0xf8) { /* Realtime. */ if (!(mpu->filter.rt_in && (msg[0] <= 0xfc) && (msg[0] >= 0xfa))) { recdata[0] = 0xff; recdata[1] = msg[0]; MPU401_RecQueueBuffer(mpu, recdata, 2); send = 0; } } else { /* Common or system. */ send = 0; if ((msg[0] == 0xf2) || (msg[0] == 0xf3) || (msg[0] == 0xf6)) { if (mpu->filter.commonmsgs_in) send = 1; if (mpu->filter.commonmsgs_thru) for (i = 0; i < len; i++) midi_raw_out_byte(msg[i]); } } if (send) { recmsg[0] = 0xff; recmsg[1] = msg[0]; recmsg[2] = msg[1]; recmsg[3] = msg[2]; MPU401_RecQueueBuffer(mpu, recmsg, len + 1); } if (mpu->filter.rt_affection) { switch (msg[0]) { case 0xf2: case 0xf3: mpu->state.block_ack = 1; MPU401_WriteCommand(mpu, 0xb8); /* Clear play counters. */ break; case 0xfa: mpu->state.block_ack = 1; MPU401_WriteCommand(mpu, 0xa); /* Start, play. */ if (mpu->filter.rt_out) midi_raw_out_rt_byte(msg[0]); break; case 0xfb: mpu->state.block_ack = 1; MPU401_WriteCommand(mpu, 0xb); /* Continue, play. */ if (mpu->filter.rt_out) midi_raw_out_rt_byte(msg[0]); break; case 0xfc: mpu->state.block_ack = 1; MPU401_WriteCommand(mpu, 0xd); /* Stop: Play, rec, midi */ if (mpu->filter.rt_out) midi_raw_out_rt_byte(msg[0]); break; default: break; } return; } break; default: break; } } if (send_thru && mpu->midi_thru) { if (retrigger_thru) { midi_raw_out_byte(0x80 | (msg[0] & 0xf)); midi_raw_out_byte(msg[1]); midi_raw_out_byte(msg[2]); } for (i = 0; i < len; i++) midi_raw_out_byte(msg[i]); } if (send) { if (mpu->state.rec == M_RECON) { recmsg[0] = mpu->clock.rec_counter; recmsg[1] = msg[0]; recmsg[2] = msg[1]; recmsg[3] = msg[2]; MPU401_RecQueueBuffer(mpu, recmsg, len + 1); mpu->clock.rec_counter = 0; } else if (mpu->filter.data_in_stop) { if (mpu->filter.timing_in_stop) { recmsg[0] = 0; recmsg[1] = msg[0]; recmsg[2] = msg[1]; recmsg[3] = msg[2]; MPU401_RecQueueBuffer(mpu, recmsg, len + 1); } else { recmsg[0] = msg[0]; recmsg[1] = msg[1]; recmsg[2] = msg[2]; recmsg[3] = 0; MPU401_RecQueueBuffer(mpu, recmsg, len); } } } return; } /* UART mode input. */ for (i = 0; i < len; i++) MPU401_QueueByte(mpu, msg[i]); MPU401_ReadRaiseIRQ(mpu); } void mpu401_setirq(mpu_t *mpu, int irq) { mpu->irq = irq; } void mpu401_change_addr(mpu_t *mpu, uint16_t addr) { if (mpu == NULL) return; if (mpu->addr) io_removehandler(mpu->addr, 2, mpu401_read, NULL, NULL, mpu401_write, NULL, NULL, mpu); mpu->addr = addr; if (mpu->addr) io_sethandler(mpu->addr, 2, mpu401_read, NULL, NULL, mpu401_write, NULL, NULL, mpu); } void mpu401_init(mpu_t *mpu, uint16_t addr, int irq, int mode, int receive_input) { mpu->status = STATUS_INPUT_NOT_READY; mpu->irq = irq; mpu->queue_used = 0; mpu->queue_pos = 0; mpu->mode = M_UART; mpu->addr = addr; /* Expalantion: MPU-401 starting in intelligent mode = Full MPU-401 intelligent mode capability; MPU-401 starting in UART mode = Reduced MPU-401 intelligent mode capability seen on the Sound Blaster 16/AWE32, only supporting commands 3F (set UART mode) and FF (reset). */ mpu->intelligent = (mode == M_INTELLIGENT) ? 1 : 0; mpu401_log("Starting as %s (mode is %s)\n", mpu->intelligent ? "INTELLIGENT" : "UART", (mode == M_INTELLIGENT) ? "INTELLIGENT" : "UART"); if (mpu->addr) io_sethandler(mpu->addr, 2, mpu401_read, NULL, NULL, mpu401_write, NULL, NULL, mpu); io_sethandler(0x2A20, 16, NULL, NULL, NULL, imf_write, NULL, NULL, mpu); timer_add(&mpu->mpu401_event_callback, MPU401_Event, mpu, 0); timer_add(&mpu->mpu401_eoi_callback, MPU401_EOIHandler, mpu, 0); timer_add(&mpu->mpu401_reset_callback, MPU401_ResetDone, mpu, 0); MPU401_Reset(mpu); if (receive_input) midi_in_handler(1, MPU401_InputMsg, MPU401_InputSysex, mpu); } void mpu401_device_add(void) { if (!mpu401_standalone_enable) return; if (machine_has_bus(machine, MACHINE_BUS_MCA)) device_add(&mpu401_mca_device); else device_add(&mpu401_device); } static uint8_t mpu401_mca_read(int port, void *priv) { const mpu_t *mpu = (mpu_t *) priv; return mpu->pos_regs[port & 7]; } static void mpu401_mca_write(int port, uint8_t val, void *priv) { mpu_t *mpu = (mpu_t *) priv; uint16_t addr; if (port < 0x102) return; addr = (mpu->pos_regs[2] & 2) ? 0x0330 : 0x1330; port &= 7; mpu->pos_regs[port] = val; if (port == 2) { io_removehandler(addr, 2, mpu401_read, NULL, NULL, mpu401_write, NULL, NULL, mpu); addr = (mpu->pos_regs[2] & 2) ? 0x1330 : 0x0330; io_sethandler(addr, 2, mpu401_read, NULL, NULL, mpu401_write, NULL, NULL, mpu); } } static uint8_t mpu401_mca_feedb(UNUSED(void *priv)) { return 1; } void mpu401_irq_attach(mpu_t *mpu, void (*ext_irq_update)(void *priv, int set), int (*ext_irq_pending)(void *priv), void *priv) { mpu->ext_irq_update = ext_irq_update; mpu->ext_irq_pending = ext_irq_pending; mpu->priv = priv; } static void * mpu401_standalone_init(const device_t *info) { mpu_t *mpu; int irq; uint16_t base; mpu = calloc(1, sizeof(mpu_t)); mpu401_log("mpu_init\n"); if (info->flags & DEVICE_MCA) { mca_add(mpu401_mca_read, mpu401_mca_write, mpu401_mca_feedb, NULL, mpu); mpu->pos_regs[0] = 0x0F; mpu->pos_regs[1] = 0x6C; base = 0; /* Tell mpu401_init() that this is the MCA variant. */ /* According to @6c0f.adf, the IRQ is supposed to be fixed to 2. This is only true for earlier models. Later ones have selectable IRQ. */ irq = device_get_config_int("irq"); } else { base = device_get_config_hex16("base"); irq = device_get_config_int("irq"); } mpu401_init(mpu, base, irq, M_INTELLIGENT, device_get_config_int("receive_input")); return mpu; } static void mpu401_standalone_close(void *priv) { mpu_t *mpu = (mpu_t *) priv; free(mpu); } static const device_config_t mpu401_standalone_config[] = { // clang-format off { .name = "base", .description = "MPU-401 Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x330, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x230", .value = 0x230 }, { .description = "0x240", .value = 0x240 }, { .description = "0x250", .value = 0x250 }, { .description = "0x300", .value = 0x300 }, { .description = "0x320", .value = 0x320 }, { .description = "0x330", .value = 0x330 }, { .description = "0x332", .value = 0x332 }, { .description = "0x334", .value = 0x334 }, { .description = "0x336", .value = 0x336 }, { .description = "0x340", .value = 0x340 }, { .description = "0x350", .value = 0x350 }, { .description = "" } } }, { .name = "irq", .description = "MPU-401 IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 2, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 2", .value = 2 }, { .description = "IRQ 3", .value = 3 }, { .description = "IRQ 4", .value = 4 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 6", .value = 6 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } } }, { .name = "receive_input", .description = "Receive input", .type = CONFIG_BINARY, .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; static const device_config_t mpu401_standalone_mca_config[] = { // clang-format off { .name = "irq", .description = "MPU-401 IRQ", .type = CONFIG_SELECTION, .default_string = "", .default_int = 9, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "IRQ 3", .value = 3 }, { .description = "IRQ 4", .value = 4 }, { .description = "IRQ 5", .value = 5 }, { .description = "IRQ 6", .value = 6 }, { .description = "IRQ 7", .value = 7 }, { .description = "IRQ 9", .value = 9 }, { .description = "" } } }, { .name = "receive_input", .description = "Receive input", .type = CONFIG_BINARY, .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t mpu401_device = { .name = "Roland MPU-IPC-T", .internal_name = "mpu401", .flags = DEVICE_ISA, .local = 0, .init = mpu401_standalone_init, .close = mpu401_standalone_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = mpu401_standalone_config }; const device_t mpu401_mca_device = { .name = "Roland MPU-IMC", .internal_name = "mpu401_mca", .flags = DEVICE_MCA, .local = 0, .init = mpu401_standalone_init, .close = mpu401_standalone_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = mpu401_standalone_mca_config }; ```
/content/code_sandbox/src/sound/snd_mpu401.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
17,426
```c #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include "cpu.h" #include <86box/86box.h> #include <86box/filters.h> #include <86box/lpt.h> #include <86box/machine.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/plat_unused.h> typedef struct lpt_dac_t { void *lpt; uint8_t dac_val_l; uint8_t dac_val_r; int is_stereo; int channel; int16_t buffer[2][SOUNDBUFLEN]; int pos; } lpt_dac_t; static void dac_update(lpt_dac_t *lpt_dac) { for (; lpt_dac->pos < sound_pos_global; lpt_dac->pos++) { lpt_dac->buffer[0][lpt_dac->pos] = (int8_t) (lpt_dac->dac_val_l ^ 0x80) * 0x40; lpt_dac->buffer[1][lpt_dac->pos] = (int8_t) (lpt_dac->dac_val_r ^ 0x80) * 0x40; } } static void dac_write_data(uint8_t val, void *priv) { lpt_dac_t *lpt_dac = (lpt_dac_t *) priv; if (lpt_dac->is_stereo) { if (lpt_dac->channel) lpt_dac->dac_val_r = val; else lpt_dac->dac_val_l = val; } else lpt_dac->dac_val_l = lpt_dac->dac_val_r = val; dac_update(lpt_dac); } static void dac_write_ctrl(uint8_t val, void *priv) { lpt_dac_t *lpt_dac = (lpt_dac_t *) priv; if (lpt_dac->is_stereo) lpt_dac->channel = val & 0x01; } static uint8_t dac_read_status(UNUSED(void *priv)) { return 0x0f; } static void dac_get_buffer(int32_t *buffer, int len, void *priv) { lpt_dac_t *lpt_dac = (lpt_dac_t *) priv; dac_update(lpt_dac); for (int c = 0; c < len; c++) { buffer[c * 2] += dac_iir(0, lpt_dac->buffer[0][c]); buffer[c * 2 + 1] += dac_iir(1, lpt_dac->buffer[1][c]); } lpt_dac->pos = 0; } static void * dac_init(void *lpt) { lpt_dac_t *lpt_dac = malloc(sizeof(lpt_dac_t)); memset(lpt_dac, 0, sizeof(lpt_dac_t)); lpt_dac->lpt = lpt; sound_add_handler(dac_get_buffer, lpt_dac); return lpt_dac; } static void * dac_stereo_init(void *lpt) { lpt_dac_t *lpt_dac = dac_init(lpt); lpt_dac->is_stereo = 1; return lpt_dac; } static void dac_close(void *priv) { lpt_dac_t *lpt_dac = (lpt_dac_t *) priv; free(lpt_dac); } const lpt_device_t lpt_dac_device = { .name = "LPT DAC / Covox Speech Thing", .internal_name = "lpt_dac", .init = dac_init, .close = dac_close, .write_data = dac_write_data, .write_ctrl = dac_write_ctrl, .read_data = NULL, .read_status = dac_read_status, .read_ctrl = NULL }; const lpt_device_t lpt_dac_stereo_device = { .name = "Stereo LPT DAC", .internal_name = "lpt_dac_stereo", .init = dac_stereo_init, .close = dac_close, .write_data = dac_write_data, .write_ctrl = dac_write_ctrl, .read_data = NULL, .read_status = dac_read_status, .read_ctrl = NULL }; ```
/content/code_sandbox/src/sound/snd_lpt_dac.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,004
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Pro Audio Spectrum Plus and 16 emulation. * * Original PAS uses: * - 2 x OPL2; * - PIT - sample rate/count; * - LMC835N/LMC1982 - mixer; * - YM3802 - MIDI Control System. * * 9A01 - I/O base: * - base >> 2. * * All below + I/O base. * * B89 - Interrupt status / clear: * - Bit 2 - sample rate; * - Bit 3 - PCM; * - Bit 4 - MIDI. * * B88 - Audio mixer control register. * * B8A - Audio filter control: * - Bit 5 - mute?. * * B8B - Interrupt mask / board ID: * - Bits 5-7 - board ID (read only on PAS16). * * F88 - PCM data (low). * * F89 - PCM data (high). * * F8A - PCM control?: * - Bit 4 - input/output select (1 = output); * - Bit 5 - mono/stereo select; * - Bit 6 - PCM enable. * * 1388-138B - PIT clocked at 1193180 Hz: * - 1388 - Sample rate; * - 1389 - Sample count. * * 178B - ????. * 2789 - Board revision. * * 8389: * - Bit 2 - 8/16 bit. * * BF88 - Wait states. * * EF8B: * - Bit 3 - 16 bits okay ?. * * F388: * - Bit 6 - joystick enable. * * F389: * - Bits 0-2 - DMA. * * F38A: * - Bits 0-3 - IRQ. * * F788: * - Bit 1 - SB emulation; * - Bit 0 - MPU401 emulation. * * F789 - SB base address: * - Bits 0-3 - Address bits 4-7. * * FB8A - SB IRQ/DMA: * - Bits 3-5 - IRQ; * - Bits 6-7 - DMA. * * FF88 - board model: * - 3 = PAS16. * * Authors: Sarah Walker, <path_to_url * Miran Grca, <mgrca8@gmail.com> * TheCollector1995, <mariogplayer@gmail.com> * */ #include <math.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define HAVE_STDARG_H #include "cpu.h" #include <86box/86box.h> #include <86box/device.h> #include <86box/dma.h> #include <86box/filters.h> #include <86box/plat_unused.h> #include <86box/io.h> #include <86box/mem.h> #include <86box/midi.h> #include <86box/pic.h> #include <86box/timer.h> #include <86box/pit.h> #include <86box/pit_fast.h> #include <86box/rom.h> #include <86box/scsi_device.h> #include <86box/scsi_ncr5380.h> #include <86box/scsi_t128.h> #include <86box/snd_mpu401.h> #include <86box/sound.h> #include <86box/snd_opl.h> #include <86box/snd_sb.h> #include <86box/snd_sb_dsp.h> typedef struct nsc_mixer_t { double master_l; double master_r; int bass; int treble; double fm_l; double fm_r; double imixer_l; double imixer_r; double line_l; double line_r; double cd_l; double cd_r; double mic_l; double mic_r; double pcm_l; double pcm_r; double speaker_l; double speaker_r; uint8_t lmc1982_regs[8]; uint8_t lmc835_regs[32]; uint8_t im_state; uint16_t im_data[4]; } nsc_mixer_t; typedef struct mv508_mixer_t { double master_l; double master_r; int bass; int treble; double fm_l; double fm_r; double imixer_l; double imixer_r; double line_l; double line_r; double cd_l; double cd_r; double mic_l; double mic_r; double pcm_l; double pcm_r; double speaker_l; double speaker_r; double sb_l; double sb_r; uint8_t index; uint8_t regs[3][128]; } mv508_mixer_t; typedef struct pas16_t { uint8_t this_id; uint8_t board_id; uint8_t master_ff; uint8_t has_scsi; uint8_t dma; uint8_t sb_irqdma; uint8_t type; uint8_t filter; uint8_t audiofilt; uint8_t audio_mixer; uint8_t compat; uint8_t compat_base; uint8_t io_conf_1; uint8_t io_conf_2; uint8_t io_conf_3; uint8_t io_conf_4; uint8_t irq_stat; uint8_t irq_ena; uint8_t pcm_ctrl; uint8_t prescale_div; uint8_t stereo_lr; uint8_t dma8_ff; uint8_t waitstates; uint8_t enhancedscsi; uint8_t sys_conf_1; uint8_t sys_conf_2; uint8_t sys_conf_3; uint8_t sys_conf_4; uint8_t midi_ctrl; uint8_t midi_stat; uint8_t midi_data; uint8_t fifo_stat; uint8_t timeout_count; uint8_t timeout_status; uint8_t pad_array[6]; uint8_t midi_queue[256]; uint16_t base; uint16_t new_base; uint16_t sb_compat_base; uint16_t mpu401_base; uint16_t dma8_dat; uint16_t ticks; uint16_t pcm_dat_l; uint16_t pcm_dat_r; int32_t pcm_buffer[2][SOUNDBUFLEN * 2]; int pos; int midi_r; int midi_w; int midi_uart_out; int midi_uart_in; int sysex; int irq; int scsi_irq; nsc_mixer_t nsc_mixer; mv508_mixer_t mv508_mixer; fm_drv_t opl; sb_dsp_t dsp; mpu_t * mpu; pitf_t * pit; t128_t * scsi; pc_timer_t scsi_timer; } pas16_t; static uint8_t pas16_next = 0; static void pas16_update(pas16_t *pas16); static int pas16_dmas[8] = { 4, 1, 2, 3, 0, 5, 6, 7 }; static int pas16_sb_irqs[8] = { 0, 2, 3, 5, 7, 10, 11, 12 }; static int pas16_sb_dmas[8] = { 0, 1, 2, 3 }; enum { PAS16_INT_SAMP = 0x04, PAS16_INT_PCM = 0x08, PAS16_INT_MIDI = 0x10 }; enum { PAS16_PCM_MONO = 0x20, PAS16_PCM_ENA = 0x40, PAS16_PCM_DMA_ENA = 0x80 }; enum { PAS16_SC2_16BIT = 0x04, PAS16_SC2_MSBINV = 0x10 }; enum { PAS16_FILT_MUTE = 0x20 }; enum { STATE_SM_IDLE = 0x00, STATE_LMC1982_ADDR = 0x10, STATE_LMC1982_ADDR_0 = 0x10, STATE_LMC1982_ADDR_1, STATE_LMC1982_ADDR_2, STATE_LMC1982_ADDR_3, STATE_LMC1982_ADDR_4, STATE_LMC1982_ADDR_5, STATE_LMC1982_ADDR_6, STATE_LMC1982_ADDR_7, STATE_LMC1982_ADDR_OVER, STATE_LMC1982_DATA = 0x10, STATE_LMC1982_DATA_0 = 0x20, STATE_LMC1982_DATA_1, STATE_LMC1982_DATA_2, STATE_LMC1982_DATA_3, STATE_LMC1982_DATA_4, STATE_LMC1982_DATA_5, STATE_LMC1982_DATA_6, STATE_LMC1982_DATA_7, STATE_LMC1982_DATA_8, STATE_LMC1982_DATA_9, STATE_LMC1982_DATA_A, STATE_LMC1982_DATA_B, STATE_LMC1982_DATA_C, STATE_LMC1982_DATA_D, STATE_LMC1982_DATA_E, STATE_LMC1982_DATA_F, STATE_LMC1982_DATA_OVER, STATE_LMC835_DATA = 0x40, STATE_LMC835_DATA_0 = 0x40, STATE_LMC835_DATA_1, STATE_LMC835_DATA_2, STATE_LMC835_DATA_3, STATE_LMC835_DATA_4, STATE_LMC835_DATA_5, STATE_LMC835_DATA_6, STATE_LMC835_DATA_7, STATE_LMC835_DATA_OVER, }; #define STATE_DATA_MASK 0x07 #define STATE_DATA_MASK_W 0x0f #define LMC1982_ADDR 0x00 #define LMC1982_DATA 0x01 #define LMC835_ADDR 0x02 #define LMC835_DATA 0x03 #define LMC835_FLAG_ADDR 0x80 #define SERIAL_MIXER_IDENT 0x10 #define SERIAL_MIXER_STROBE 0x04 #define SERIAL_MIXER_CLOCK 0x02 #define SERIAL_MIXER_DATA 0x01 #define SERIAL_MIXER_RESET_PCM 0x01 #define PAS16_PCM_AND_DMA_ENA (PAS16_PCM_ENA | PAS16_PCM_DMA_ENA) /* LMC1982CIN registers (data bits 7 and 6 are always don't care): - 40 = Mode (0x01 = INPUT2); - 41 = 0 = Loudness (1 = on, 0 = off), 1 = Stereo Enhance (1 = on, 0 = off) (0x00); - 42 = Bass, 00-0c (0x06); - 43 = Treble, 00-0c (0x06); - 45 [L] / 44 [R] = Master, 28-00, counting down (0x28, later 0xa8); - 46 = ???? (0x05 = Stereo). */ #define LMC1982_REG_MASK 0xf8 /* LMC1982CIN: Register Mask */ #define LMC1982_REG_VALID 0x40 /* LMC1982CIN: Register Valid Value */ #define LMC1982_REG_ISELECT 0x00 /* LMC1982CIN: Input Select + Mute */ #define LMC1982_REG_LES 0x01 /* LMC1982CIN: Loudness, Enhanced Stereo */ #define LMC1982_REG_BASS 0x02 /* LMC1982CIN: Bass */ #define LMC1982_REG_TREBLE 0x03 /* LMC1982CIN: Treble */ /* The Windows 95 driver indicates left and right are swapped in the wiring. */ #define LMC1982_REG_VOL_L 0x04 /* LMC1982CIN: Left Volume */ #define LMC1982_REG_VOL_R 0x05 /* LMC1982CIN: Right Volume */ #define LMC1982_REG_MODE 0x06 /* LMC1982CIN: Mode */ #define LMC1982_REG_DINPUT 0x07 /* LMC1982CIN: Digital Input 1 and 2 */ /* Bits 7-2: Don't care. */ #define LMC1982_ISELECT_MASK 0x03 /* LMC1982CIN: Input Select: Mask */ #define LMC1982_ISELECT_I1 0x00 /* LMC1982CIN: Input Select: INPUT1 */ #define LMC1982_ISELECT_I2 0x01 /* LMC1982CIN: Input Select: INPUT2 */ #define LMC1982_ISELECT_NA 0x02 /* LMC1982CIN: Input Select: N/A */ #define LMC1982_ISELECT_MUTE 0x03 /* LMC1982CIN: Input Select: MUTE */ /* Bits 7-2: Don't care. */ #define LMC1982_LES_MASK 0x03 /* LMC1982CIN: Loudness, Enhanced Stereo: Mask */ #define LMC1982_LES_BOTH_OFF 0x00 /* LMC1982CIN: Loudness OFF, Enhanced Stereo OFF */ #define LMC1982_L_ON_ES_OFF 0x01 /* LMC1982CIN: Loudness ON, Enhanced Stereo OFF */ #define LMC1982_L_OFF_ES_ON 0x02 /* LMC1982CIN: Loudness OFF, Enhanced Stereo ON */ #define LMC1982_LES_BOTH_ON 0x03 /* LMC1982CIN: Loudness OFF, Enhanced Stereo ON */ /* Bits 7-3: Don't care. */ #define LMC1982_MODE_MASK 0x07 /* LMC1982CIN: Mode: Mask */ #define LMC1982_MODE_MONO_L 0x04 /* LMC1982CIN: Mode: Left Mono */ #define LMC1982_MODE_STEREO 0x05 /* LMC1982CIN: Mode: Stereo */ #define LMC1982_MODE_MONO_R 0x06 /* LMC1982CIN: Mode: Right Mono */ #define LMC1982_MODE_MONO_R_2 0x07 /* LMC1982CIN: Mode: Right Mono (Alternate value) */ /* Bits 7-2: Don't care. */ #define LMC1982_DINPUT_MASK 0x03 /* LMC1982CIN: Digital Input 1 and 2: Mask */ #define LMC1982_DINPUT_DI1 0x01 /* LMC1982CIN: Digital Input 1 */ #define LMC1982_DINPUT_DI2 0x02 /* LMC1982CIN: Digital Input 2 */ /* LMC835N registers: - 01 [L] / 08 [R] = FM, 00-2f, bit 6 = clear, but the DOS driver sets the bit, indicating a volume boost (0x69); - 02 [L] / 09 [R] = Rec. monitor, 00-2f, bit 6 = clear (0x29); - 03 [L] / 0A [R] = Line in, 00-2f, bit 6 = clear, except for the DOS driver (0x69); - 04 [L] / 0B [R] = CD, 00-2f, bit 6 = clear, except for the DOS driver (0x69); - 05 [L] / 0C [R] = Microphone, 00-2f, bit 6 = clear, except for the DOS driver (0x44); - 06 [L] / 0D [R] = Wave out, 00-2f, bit 6 = set, except for DOS driver, which clears the bit (0x29); - 07 [L] / 0E [R] = PC speaker, 00-2f, bit 6 = clear, except for the DOS drive (0x06). The registers for which the DOS driver sets the boost, also have bit 6 set in the address, despite the fact it should be a don't care - why? Apparently, no Sound Blaster control. */ #define LMC835_REG_MODE 0x00 /* LMC835N: Mode, not an actual register, but our internal register to store the mode for Channels A (1-7) and B (8-e). */ #define LMC835_REG_FM_L 0x01 /* LMC835N: FM Left */ #define LMC835_REG_IMIXER_L 0x02 /* LMC835N: Record Monitor Left */ #define LMC835_REG_LINE_L 0x03 /* LMC835N: Line in Left */ #define LMC835_REG_CDROM_L 0x04 /* LMC835N: CD Left */ #define LMC835_REG_MIC_L 0x05 /* LMC835N: Microphone Left */ #define LMC835_REG_PCM_L 0x06 /* LMC835N: Wave out Left */ #define LMC835_REG_SPEAKER_L 0x07 /* LMC83N5: PC speaker Left */ #define LMC835_REG_FM_R 0x08 /* LMC835N: FM Right */ #define LMC835_REG_IMIXER_R 0x09 /* LMC835N: Record Monitor Right */ #define LMC835_REG_LINE_R 0x0a /* LMC835N: Line in Right */ #define LMC835_REG_CDROM_R 0x0b /* LMC835N: CD Right */ #define LMC835_REG_MIC_R 0x0c /* LMC835N: Microphone Right */ #define LMC835_REG_PCM_R 0x0d /* LMC835N: Wave out Right */ #define LMC835_REG_SPEAKER_R 0x0e /* LMC83N5: PC speaker Right */ #define MV508_ADDRESS 0x80 /* Flag indicating it is the address */ /* I think this may actually operate as such: - Bit 6: Mask left channel; - Bit 5: Mask right channel. */ #define MV508_CHANNEL 0x60 #define MV508_LEFT 0x20 #define MV508_RIGHT 0x40 #define MV508_BOTH 0x00 #define MV508_MIXER 0x10 /* Flag indicating it is a mixer rather than a volume */ #define MV508_INPUT_MIX 0x20 /* Flag indicating the selected mixer is input */ #define MV508_MASTER_A 0x01 /* Volume: Output */ #define MV508_MASTER_B 0x02 /* Volume: DSP input */ #define MV508_BASS 0x03 /* Volume: Bass */ #define MV508_TREBLE 0x04 /* Volume: Treble */ #define MV508_MODE 0x05 /* Volume: Mode */ #define MV508_LOUDNESS 0x04 /* Mode: Loudness */ #define MV508_ENH_MASK 0x03 /* Mode: Stereo enhancement bit mask */ #define MV508_ENH_NONE 0x00 /* Mode: No stereo enhancement */ #define MV508_ENH_40 0x01 /* Mode: 40% stereo enhancement */ #define MV508_ENH_60 0x02 /* Mode: 60% stereo enhancement */ #define MV508_ENH_80 0x03 /* Mode: 80% stereo enhancement */ #define MV508_FM 0x00 /* Mixer: FM */ #define MV508_IMIXER 0x01 /* Mixer: Input mixer (recording monitor) */ #define MV508_LINE 0x02 /* Mixer: Line in */ #define MV508_CDROM 0x03 /* Mixer: CD-ROM */ #define MV508_MIC 0x04 /* Mixer: Microphone */ #define MV508_PCM 0x05 /* Mixer: PCM */ #define MV508_SPEAKER 0x06 /* Mixer: PC Speaker */ #define MV508_SB 0x07 /* Mixer: Sound Blaster DSP */ #define MV508_REG_MASTER_A_L (MV508_MASTER_A | MV508_LEFT) #define MV508_REG_MASTER_A_R (MV508_MASTER_A | MV508_RIGHT) #define MV508_REG_MASTER_B_L (MV508_MASTER_B | MV508_LEFT) #define MV508_REG_MASTER_B_R (MV508_MASTER_B | MV508_RIGHT) #define MV508_REG_BASS (MV508_BASS | MV508_LEFT) #define MV508_REG_TREBLE (MV508_TREBLE | MV508_LEFT) #define MV508_REG_FM_L (MV508_MIXER | MV508_FM | MV508_LEFT) #define MV508_REG_FM_R (MV508_MIXER | MV508_FM | MV508_RIGHT) #define MV508_REG_IMIXER_L (MV508_MIXER | MV508_IMIXER | MV508_LEFT) #define MV508_REG_IMIXER_R (MV508_MIXER | MV508_IMIXER | MV508_RIGHT) #define MV508_REG_LINE_L (MV508_MIXER | MV508_LINE | MV508_LEFT) #define MV508_REG_LINE_R (MV508_MIXER | MV508_LINE | MV508_RIGHT) #define MV508_REG_CDROM_L (MV508_MIXER | MV508_CDROM | MV508_LEFT) #define MV508_REG_CDROM_R (MV508_MIXER | MV508_CDROM | MV508_RIGHT) #define MV508_REG_MIC_L (MV508_MIXER | MV508_MIC | MV508_LEFT) #define MV508_REG_MIC_R (MV508_MIXER | MV508_MIC | MV508_RIGHT) #define MV508_REG_PCM_L (MV508_MIXER | MV508_PCM | MV508_LEFT) #define MV508_REG_PCM_R (MV508_MIXER | MV508_PCM | MV508_RIGHT) #define MV508_REG_SPEAKER_L (MV508_MIXER | MV508_SPEAKER | MV508_LEFT) #define MV508_REG_SPEAKER_R (MV508_MIXER | MV508_SPEAKER | MV508_RIGHT) #define MV508_REG_SB_L (MV508_MIXER | MV508_SB | MV508_LEFT) #define MV508_REG_SB_R (MV508_MIXER | MV508_SB | MV508_RIGHT) double low_fir_pas16_coef[SB16_NCoef]; /* Also used for the MVA508. */ static double lmc1982_bass_treble_4bits[16]; /* Copied from the Sound Blaster code: -62 dB to 0 dB in 2 dB steps. Note that these are voltage dB's, so it corresonds in power dB (formula for conversion to percentage: 10 ^ (dB / 10)) to -31 dB to 0 dB in 1 dB steps. This is used for the MVA508 Volumes. */ static const double mva508_att_2dbstep_5bits[] = { 25.0, 32.0, 41.0, 51.0, 65.0, 82.0, 103.0, 130.0, 164.0, 206.0, 260.0, 327.0, 412.0, 519.0, 653.0, 822.0, 1036.0, 1304.0, 1641.0, 2067.0, 2602.0, 3276.0, 4125.0, 5192.0, 6537.0, 8230.0, 10362.0, 13044.0, 16422.0, 20674.0, 26027.0, 32767.0 }; /* The same but in 1 dB steps, used for the MVA508 Master Volume. */ static const double mva508_att_1dbstep_6bits[] = { 18.0, 25.0, 29.0, 32.0, 36.0, 41.0, 46.0, 51.0, 58.0, 65.0, 73.0, 82.0, 92.0, 103.0, 116.0, 130.0, 146.0, 164.0, 184.0, 206.0, 231.0, 260.0, 292.0, 327.0, 367.0, 412.0, 462.0, 519.0, 582.0, 653.0, 733.0, 822.0, 923.0, 1036.0, 1162.0, 1304.0, 1463.0, 1641.0, 1842.0, 2067.0, 2319.0, 2602.0, 2920.0, 3276.0, 3676.0, 4125.0, 4628.0, 5192.0, 5826.0, 6537.0, 7335.0, 8230.0, 9234.0, 10362.0, 11626.0, 13044.0, 14636.0, 16422.0, 18426.0, 20674.0, 23197.0, 26027.0, 29204.0, 32767.0 }; /* In 2 dB steps again, but to -80 dB and counting down (0 = Flat), used for the LMC1982CIN Master Volume. */ static const double lmc1982_att_2dbstep_6bits[] = { 32767.0, 26027.0, 20674.0, 16422.0, 13044.0, 10362.0, 8230.0, 6537.0, 5192.0, 4125.0, 3276.0, 2602.0, 2067.0, 1641.0, 1304.0, 1036.0, 822.0, 653.0, 519.0, 412.0, 327.0, 260.0, 206.0, 164.0, 130.0, 103.0, 82.0, 65.0, 51.0, 41.0, 32.0, 25.0, 20.0, 16.0, 13.0, 10.0, 8.0, 6.0, 5.0, 4.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0 }; /* LMC385N attenuation, both +/- 12 dB and +/- 6 dB. Since the DOS and Windows 95 driver diverge on boost vs. cut for the various inputs, I think it is best to just do a 12 dB cut on the input, and then apply cut or boost as needed. I have factored in said cut in the below values. */ static const double lmc835_att_1dbstep_7bits[128] = { /* Flat */ [0x40] = 8230.0, /* Flat */ /* Boost */ [0x60] = 9234.0, /* 1 dB Boost */ [0x50] = 10362.0, /* 2 dB Boost */ [0x48] = 11626.0, /* 3 dB Boost */ [0x44] = 13044.0, /* 4 dB Boost */ [0x42] = 14636.0, /* 5 dB Boost */ [0x52] = 16422.0, /* 6 dB Boost */ [0x6a] = 18426.0, /* 7 dB Boost */ [0x56] = 20674.0, /* 8 dB Boost */ [0x41] = 23197.0, /* 9 dB Boost */ [0x69] = 26027.0, /* 10 dB Boost */ [0x6d] = 29204.0, /* 11 dB Boost */ /* The Win95 drivers use D5-D0 = 1D instead of 2D, datasheet erratum? */ [0x5d] = 29204.0, /* 11 dB Boost */ [0x6f] = 32767.0, /* 12 dB Boost */ /* Flat */ /* The datasheet says this should be Flat (1.0) but the Windows 95 drivers use this as basically mute (12 dB Cut). */ [0x00] = 2067.0, /* 12 dB Cut */ /* Cut - D5-D0 = 2F is minimum cut (0 dB) according to Windows 95 */ [0x20] = 2319.0, /* 11 dB Cut */ [0x10] = 2602.0, /* 10 dB Cut */ [0x08] = 2920.0, /* 9 dB Cut */ [0x04] = 3276.0, /* 8 dB Cut */ [0x02] = 3676.0, /* 7 dB Cut */ [0x12] = 4125.0, /* 6 dB Cut */ [0x2a] = 4628.0, /* 5 dB Cut */ [0x16] = 5192.0, /* 4 dB Cut */ [0x01] = 5826.0, /* 3 dB Cut */ [0x29] = 6537.0, /* 2 dB Cut */ [0x2d] = 7335.0, /* 1 dB Cut */ /* The Win95 drivers use D5-D0 = 1D instead of 2D, datasheet erratum? */ [0x1d] = 7335.0, /* 1 dB Cut */ [0x2f] = 8230.0, /* Flat */ 0.0 }; static const double lmc835_att_05dbstep_7bits[128] = { /* Flat */ [0x40] = 8230.0, /* Flat */ /* Boost */ [0x60] = 8718.0, /* 0.5 dB Boost */ [0x50] = 9234.0, /* 1.0 dB Boost */ [0x48] = 9782.0, /* 1.5 dB Boost */ [0x44] = 10362.0, /* 2.0 dB Boost */ [0x42] = 10975.0, /* 2.5 dB Boost */ [0x52] = 11626.0, /* 3.0 dB Boost */ [0x6a] = 12315.0, /* 3.5 dB Boost */ [0x56] = 13044.0, /* 4.0 dB Boost */ [0x41] = 13817.0, /* 4.5 dB Boost */ [0x69] = 14636.0, /* 5.0 dB Boost */ [0x6d] = 15503.0, /* 5.5 dB Boost */ /* The Win95 drivers use D5-D0 = 1D instead of 2D, datasheet erratum? */ [0x5d] = 15503.0, /* 5.5 dB Boost */ [0x6f] = 16422.0, /* 6.0 dB Boost */ /* Flat */ /* The datasheet says this should be Flat (1.0) but the Windows 95 drivers use this as basically mute (12 dB Cut). */ [0x00] = 4125.0, /* 6.0 dB Cut */ /* Cut - D5-D0 = 2F is minimum cut (0 dB) according to Windows 95 */ [0x20] = 4369.0, /* 5.5 dB Cut */ [0x10] = 4628.0, /* 5.0 dB Cut */ [0x08] = 4920.0, /* 4.5 dB Cut */ [0x04] = 5192.0, /* 4.0 dB Cut */ [0x02] = 5500.0, /* 3.5 dB Cut */ [0x12] = 5826.0, /* 3.0 dB Cut */ [0x2a] = 6172.0, /* 2.5 dB Cut */ [0x16] = 6537.0, /* 2.0 dB Cut */ [0x01] = 6925.0, /* 1.5 dB Cut */ [0x29] = 7335.0, /* 1.0 dB Cut */ [0x2d] = 7770.0, /* 0.5 dB Cut */ /* The Win95 drivers use D5-D0 = 1D instead of 2D, datasheet erratum? */ [0x1d] = 7770.0, /* 0.5 dB Cut */ [0x2f] = 8230.0, /* Flat */ 0.0 }; static __inline double sinc(const double x) { return sin(M_PI * x) / (M_PI * x); } static void recalc_pas16_filter(const int playback_freq) { /* Cutoff frequency = playback / 2 */ int n; const double fC = ((double) playback_freq) / (double) FREQ_96000; double gain = 0.0; for (n = 0; n < SB16_NCoef; n++) { /* Blackman window */ const double w = 0.42 - (0.5 * cos((2.0 * n * M_PI) / (double) (SB16_NCoef - 1))) + (0.08 * cos((4.0 * n * M_PI) / (double) (SB16_NCoef - 1))); /* Sinc filter */ const double h = sinc(2.0 * fC * ((double) n - ((double) (SB16_NCoef - 1) / 2.0))); /* Create windowed-sinc filter */ low_fir_pas16_coef[n] = w * h; } low_fir_pas16_coef[(SB16_NCoef - 1) / 2] = 1.0; for (n = 0; n < SB16_NCoef; n++) gain += low_fir_pas16_coef[n]; /* Normalise filter, to produce unity gain */ for (n = 0; n < SB16_NCoef; n++) low_fir_pas16_coef[n] /= gain; } #ifdef ENABLE_PAS16_LOG int pas16_do_log = ENABLE_PAS16_LOG; static void pas16_log(const char *fmt, ...) { va_list ap; if (pas16_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define pas16_log(fmt, ...) #endif static uint8_t pas16_in(uint16_t port, void *priv); static void pas16_out(uint16_t port, uint8_t val, void *priv); static void pas16_update_irq(pas16_t *pas16) { if (pas16->midi_uart_out && (pas16->midi_stat & 0x18)) { pas16->irq_stat |= PAS16_INT_MIDI; if ((pas16->irq != -1) && (pas16->irq_ena & PAS16_INT_MIDI)) picint(1 << pas16->irq); } if (pas16->midi_uart_in && (pas16->midi_stat & 0x04)) { pas16->irq_stat |= PAS16_INT_MIDI; if ((pas16->irq != -1) && (pas16->irq_ena & PAS16_INT_MIDI)) picint(1 << pas16->irq); } } static uint8_t pas16_in(uint16_t port, void *priv) { pas16_t *pas16 = (pas16_t *) priv; uint8_t ret = 0xff; port -= pas16->base; switch (port) { case 0x0000 ... 0x0003: ret = pas16->opl.read(port + 0x0388, pas16->opl.priv); break; case 0x0800: ret = pas16->type ? pas16->audio_mixer : 0xff; break; case 0x0801: ret = pas16->irq_stat & 0xdf; break; case 0x0802: ret = pas16->audiofilt; break; case 0x0803: ret = pas16->irq_ena | 0x20; pas16_log("IRQ Mask read=%02x.\n", ret); break; case 0x0c02: ret = pas16->pcm_ctrl; break; case 0x1401: case 0x1403: ret = pas16->midi_ctrl; break; case 0x1402: case 0x1802: ret = 0; if (pas16->midi_uart_in) { if ((pas16->midi_data == 0xaa) && (pas16->midi_ctrl & 0x04)) ret = pas16->midi_data; else { ret = pas16->midi_queue[pas16->midi_r]; if (pas16->midi_r != pas16->midi_w) { pas16->midi_r++; pas16->midi_r &= 0xff; } } pas16->midi_stat &= ~0x04; pas16_update_irq(pas16); } break; case 0x1800: ret = pas16->midi_stat; break; case 0x1801: ret = pas16->fifo_stat; break; case 0x1c00 ... 0x1c03: /* NCR5380 ports 0 to 3. */ case 0x3c00 ... 0x3c03: /* NCR5380 ports 4 to 7. */ if (pas16->has_scsi) ret = ncr5380_read((port & 0x0003) | ((port & 0x2000) >> 11), &pas16->scsi->ncr); break; case 0x2401: /* Board revision */ ret = 0x00; break; case 0x4000: ret = pas16->timeout_count; break; case 0x4001: ret = pas16->timeout_status; break; case 0x5c00: if (pas16->has_scsi) ret = t128_read(0x1e00, pas16->scsi); break; case 0x5c01: if (pas16->has_scsi) /* Bits 0-6 must absolutely be set for SCSI hard disk drivers to work. */ ret = (((pas16->scsi->ncr.dma_mode != DMA_IDLE) && (pas16->scsi->status & 0x04)) << 7) | 0x7f; break; case 0x5c03: if (pas16->has_scsi) ret = pas16->scsi->ncr.irq_state << 7; break; case 0x7c01: ret = pas16->enhancedscsi & ~0x01; break; case 0x8000: ret = pas16->sys_conf_1; break; case 0x8001: ret = pas16->sys_conf_2; break; case 0x8002: ret = pas16->sys_conf_3; break; case 0x8003: ret = pas16->sys_conf_4; break; case 0xbc00: ret = pas16->waitstates; break; case 0xbc02: ret = pas16->prescale_div; break; case 0xec03: /* Operation mode 1: - 1,0 = CD-ROM (1,1 = SCSI, 1,0 = Sony, 0,0 = N/A); - 2 = FM (1 = stereo, 0 = mono); - 3 = Code (1 = 16-bit, 0 = 8-bit). */ ret = pas16->type ? pas16->type : 0x07; break; case 0xf000: ret = pas16->io_conf_1; break; case 0xf001: ret = pas16->io_conf_2; pas16_log("pas16_in : set PAS DMA %i\n", pas16->dma); break; case 0xf002: ret = pas16->io_conf_3; pas16_log("pas16_in : set PAS IRQ %i\n", pas16->irq); break; case 0xf003: ret = pas16->io_conf_4; break; case 0xf400: ret = (pas16->compat & 0xf3); if (pas16->dsp.sb_irqm8 || pas16->dsp.sb_irqm16 || pas16->dsp.sb_irqm401) ret |= 0x04; if (pas16->mpu->mode == M_UART) ret |= 0x08; break; case 0xf401: ret = pas16->compat_base; break; case 0xf802: ret = pas16->sb_irqdma; break; case 0xfc00: /* Board model */ /* PAS16 or PASPlus */ ret = pas16->type ? 0x0c : 0x01; break; case 0xfc03: /* Master mode read */ /* AT bus, XT/AT timing */ ret = 0x11; if (pas16->type) ret |= 0x20; break; default: break; } pas16_log("[%04X:%08X] PAS16: [R] %04X (%04X) = %02X\n", CS, cpu_state.pc, port + pas16->base, port, ret); return ret; } static void pas16_change_pit_clock_speed(void *priv) { pas16_t *pas16 = (pas16_t *) priv; pitf_t *pit = (pitf_t *) pas16->pit; if (pas16->type && (pas16->sys_conf_1 & 0x02) && pas16->prescale_div) { pit_change_pas16_consts((double) pas16->prescale_div); if (pas16->sys_conf_3 & 0x02) pitf_set_pit_const(pit, PAS16CONST2); else pitf_set_pit_const(pit, PAS16CONST); } else pitf_set_pit_const(pit, PITCONST); } static void pas16_io_handler(pas16_t *pas16, int set) { if (pas16->base != 0x0000) { for (uint32_t addr = 0x0000; addr <= 0xffff; addr += 0x0400) { pas16_log("%04X-%04X: %i\n", pas16->base + addr, pas16->base + addr + 3, set); if (addr != 0x1000) io_handler(set, pas16->base + addr, 0x0004, pas16_in, NULL, NULL, pas16_out, NULL, NULL, pas16); } pitf_handler(set, pas16->base + 0x1000, 0x0004, pas16->pit); } } static void pas16_reset_pcm(void *priv) { pas16_t *pas16 = (pas16_t *) priv; pas16->pcm_ctrl = 0x00; pas16->stereo_lr = 0; pas16->irq_stat &= 0xd7; if ((pas16->irq != -1) && !pas16->irq_stat) picintc(1 << pas16->irq); } static void lmc1982_recalc(nsc_mixer_t *mixer) { /* LMC1982CIN */ /* According to the Windows 95 driver, the two volumes are swapped. */ if ((mixer->lmc1982_regs[LMC1982_REG_ISELECT] & LMC1982_ISELECT_MASK) == LMC1982_ISELECT_I2) { switch (mixer->lmc1982_regs[LMC1982_REG_MODE] & LMC1982_MODE_MASK) { case LMC1982_MODE_MONO_L: mixer->master_l = mixer->master_r = lmc1982_att_2dbstep_6bits[mixer->lmc1982_regs[LMC1982_REG_VOL_R]] / 32767.0; break; case LMC1982_MODE_STEREO: mixer->master_l = lmc1982_att_2dbstep_6bits[mixer->lmc1982_regs[LMC1982_REG_VOL_R]] / 32767.0; mixer->master_r = lmc1982_att_2dbstep_6bits[mixer->lmc1982_regs[LMC1982_REG_VOL_L]] / 32767.0; break; case LMC1982_MODE_MONO_R: case LMC1982_MODE_MONO_R_2: mixer->master_l = mixer->master_r = lmc1982_att_2dbstep_6bits[mixer->lmc1982_regs[LMC1982_REG_VOL_L]] / 32767.0; break; default: mixer->master_l = mixer->master_r = 0.0; break; } mixer->bass = mixer->lmc1982_regs[LMC1982_REG_BASS] & 0x0f; mixer->treble = mixer->lmc1982_regs[LMC1982_REG_TREBLE] & 0x0f; } else { mixer->master_l = mixer->master_r = 0.0; mixer->bass = 0x06; mixer->treble = 0x06; } } static void lmc835_recalc(nsc_mixer_t *mixer) { /* LMC835N */ /* Channel A (1-7) */ const double *lmc835_att = (const double *) ((mixer->lmc835_regs[LMC835_REG_MODE] & 0x20) ? lmc835_att_05dbstep_7bits : lmc835_att_1dbstep_7bits); mixer->fm_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_FM_L] & 0x7f] / 32767.0; mixer->imixer_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_IMIXER_L] & 0x7f] / 32767.0; mixer->line_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_LINE_L] & 0x7f] / 32767.0; mixer->cd_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_CDROM_L] & 0x7f] / 32767.0; mixer->mic_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_MIC_L] & 0x7f] / 32767.0; mixer->pcm_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_PCM_L] & 0x7f] / 32767.0; mixer->speaker_l = lmc835_att[mixer->lmc835_regs[LMC835_REG_SPEAKER_L] & 0x7f] / 32767.0; /* Channel B (8-e) */ lmc835_att = (const double *) ((mixer->lmc835_regs[LMC835_REG_MODE] & 0x08) ? lmc835_att_05dbstep_7bits : lmc835_att_1dbstep_7bits); mixer->fm_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_FM_R] & 0x7f] / 32767.0; mixer->imixer_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_IMIXER_R] & 0x7f] / 32767.0; mixer->line_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_LINE_R] & 0x7f] / 32767.0; mixer->cd_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_CDROM_R] & 0x7f] / 32767.0; mixer->mic_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_MIC_R] & 0x7f] / 32767.0; mixer->pcm_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_PCM_R] & 0x7f] / 32767.0; mixer->speaker_r = lmc835_att[mixer->lmc835_regs[LMC835_REG_SPEAKER_R] & 0x7f] / 32767.0; } static void mv508_mixer_recalc(mv508_mixer_t *mixer) { mixer->fm_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_FM_L]] / 32767.0; mixer->fm_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_FM_R]] / 32767.0; mixer->imixer_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_IMIXER_L]] / 32767.0; mixer->imixer_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_IMIXER_R]] / 32767.0; mixer->line_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_LINE_L]] / 32767.0; mixer->line_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_LINE_R]] / 32767.0; mixer->cd_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_CDROM_L]] / 32767.0; mixer->cd_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_CDROM_R]] / 32767.0; mixer->mic_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_MIC_L]] / 32767.0; mixer->mic_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_MIC_R]] / 32767.0; mixer->pcm_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_PCM_L]] / 32767.0; mixer->pcm_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_PCM_R]] / 32767.0; mixer->speaker_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_SPEAKER_L]] / 32767.0; mixer->speaker_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_SPEAKER_R]] / 32767.0; mixer->sb_l = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_SB_L]] / 32767.0; mixer->sb_r = mva508_att_2dbstep_5bits[mixer->regs[0][MV508_REG_SB_R]] / 32767.0; mixer->master_l = mva508_att_1dbstep_6bits[mixer->regs[2][MV508_REG_MASTER_A_L]] / 32767.0; mixer->master_r = mva508_att_1dbstep_6bits[mixer->regs[2][MV508_REG_MASTER_A_R]] / 32767.0; mixer->bass = mixer->regs[2][MV508_REG_BASS] & 0x0f; mixer->treble = mixer->regs[2][MV508_REG_TREBLE] & 0x0f; } static void pas16_nsc_mixer_reset(nsc_mixer_t *mixer) { mixer->lmc1982_regs[LMC1982_REG_ISELECT] = 0x01; mixer->lmc1982_regs[LMC1982_REG_LES] = 0x00; mixer->lmc1982_regs[LMC1982_REG_BASS] = mixer->lmc1982_regs[LMC1982_REG_TREBLE] = 0x06; mixer->lmc1982_regs[LMC1982_REG_VOL_L] = mixer->lmc1982_regs[LMC1982_REG_VOL_R] = 0x28; mixer->lmc1982_regs[LMC1982_REG_MODE] = 0x05; lmc1982_recalc(mixer); mixer->lmc835_regs[LMC835_REG_MODE] = 0x00; mixer->lmc835_regs[LMC835_REG_FM_L] = mixer->lmc835_regs[LMC835_REG_FM_R] = 0x69; mixer->lmc835_regs[LMC835_REG_IMIXER_L] = mixer->lmc835_regs[LMC835_REG_IMIXER_R] = 0x29; mixer->lmc835_regs[LMC835_REG_LINE_L] = mixer->lmc835_regs[LMC835_REG_LINE_R] = 0x69; mixer->lmc835_regs[LMC835_REG_CDROM_L] = mixer->lmc835_regs[LMC835_REG_CDROM_R] = 0x69; mixer->lmc835_regs[LMC835_REG_MIC_L] = mixer->lmc835_regs[LMC835_REG_MIC_R] = 0x44; mixer->lmc835_regs[LMC835_REG_PCM_L] = mixer->lmc835_regs[LMC835_REG_PCM_R] = 0x29; mixer->lmc835_regs[LMC835_REG_SPEAKER_L] = mixer->lmc835_regs[LMC835_REG_SPEAKER_R] = 0x06; lmc835_recalc(mixer); } static void pas16_mv508_mixer_reset(mv508_mixer_t *mixer) { /* Based on the Linux driver - TODO: The actual card's defaults. */ mixer->regs[0][MV508_REG_FM_L] = mixer->regs[0][MV508_REG_FM_R] = 0x18; mixer->regs[0][MV508_REG_IMIXER_L] = mixer->regs[0][MV508_REG_IMIXER_R] = 0x1f; mixer->regs[0][MV508_REG_LINE_L] = mixer->regs[0][MV508_REG_LINE_R] = 0x17; mixer->regs[0][MV508_REG_CDROM_L] = mixer->regs[0][MV508_REG_CDROM_R] = 0x17; mixer->regs[0][MV508_REG_MIC_L] = mixer->regs[0][MV508_REG_MIC_R] = 0x17; mixer->regs[0][MV508_REG_PCM_L] = mixer->regs[0][MV508_REG_PCM_R] = 0x17; mixer->regs[0][MV508_REG_SPEAKER_L] = mixer->regs[0][MV508_REG_SPEAKER_R] = 0x0f; mixer->regs[0][MV508_REG_SB_L] = mixer->regs[0][MV508_REG_SB_R] = 0x17; mixer->regs[2][MV508_REG_MASTER_A_L] = mixer->regs[2][MV508_REG_MASTER_A_R] = 0x1f; mixer->regs[2][MV508_REG_BASS] = 0x06; mixer->regs[2][MV508_REG_TREBLE] = 0x06; mv508_mixer_recalc(mixer); } static void pas16_reset_regs(void *priv) { pas16_t *pas16 = (pas16_t *) priv; nsc_mixer_t *nsc_mixer = &pas16->nsc_mixer; mv508_mixer_t *mv508_mixer = &pas16->mv508_mixer; pitf_t *pit = (pitf_t *) pas16->pit; if (pas16->irq != -1) picintc(1 << pas16->irq); pas16->sys_conf_1 &= 0xfd; pas16->sys_conf_2 = 0x00; pas16->sys_conf_3 = 0x00; pas16->prescale_div = 0x00; pitf_set_pit_const(pit, PITCONST); pas16->audiofilt = 0x00; pas16->filter = 0; pitf_ctr_set_gate(pit, 0, 0); pitf_ctr_set_gate(pit, 1, 0); pas16_reset_pcm(pas16); pas16->dma8_ff = 0; pas16->irq_ena = 0x00; pas16->irq_stat = 0x00; if (pas16->type) pas16_mv508_mixer_reset(mv508_mixer); else pas16_nsc_mixer_reset(nsc_mixer); } static void pas16_reset_common(void *priv) { pas16_t *pas16 = (pas16_t *) priv; pas16_reset_regs(pas16); if (pas16->irq != -1) picintc(1 << pas16->irq); pas16_io_handler(pas16, 0); pas16->base = 0x0000; } static void pas16_reset(void *priv) { pas16_t *pas16 = (pas16_t *) priv; pas16_reset_common(priv); pas16->board_id = 0; pas16->master_ff = 0; pas16->base = 0x0388; pas16_io_handler(pas16, 1); pas16->new_base = 0x0388; pas16->sb_compat_base = 0x0220; pas16->compat = 0x02; pas16->compat_base = 0x02; sb_dsp_setaddr(&pas16->dsp, pas16->sb_compat_base); } static int pas16_irq_convert(uint8_t val) { int ret = val; if (ret == 0) ret = -1; else if (ret <= 6) ret++; else if (ret < 0x0b) ret += 3; else ret += 4; return ret; } static void lmc1982_update_reg(nsc_mixer_t *mixer) { pas16_log("LMC1982CIN register %02X = %04X\n", mixer->im_data[LMC1982_ADDR], mixer->im_data[LMC1982_DATA]); if ((mixer->im_data[LMC1982_ADDR] & LMC1982_REG_MASK) == LMC1982_REG_VALID) { mixer->im_data[LMC1982_ADDR] &= ~LMC1982_REG_MASK; mixer->lmc1982_regs[mixer->im_data[LMC1982_ADDR]] = mixer->im_data[LMC1982_DATA] & 0xff; lmc1982_recalc(mixer); } mixer->im_state = STATE_SM_IDLE; } static void lmc835_update_reg(nsc_mixer_t *mixer) { pas16_log("LMC835N register %02X = %02X\n", mixer->im_data[LMC835_ADDR], mixer->im_data[LMC835_DATA]); mixer->lmc835_regs[LMC835_REG_MODE] = mixer->im_data[LMC835_ADDR] & 0xf0; mixer->im_data[LMC835_ADDR] &= 0x0f; if ((mixer->im_data[LMC835_ADDR] >= 0x01) && (mixer->im_data[LMC835_ADDR] <= 0x0e)) mixer->lmc835_regs[mixer->im_data[LMC835_ADDR] & 0x0f] = mixer->im_data[LMC835_DATA]; lmc835_recalc(mixer); } static void pas16_scsi_callback(void *priv) { pas16_t * pas16 = (pas16_t *) priv; t128_t * dev = pas16->scsi; t128_callback(pas16->scsi); if ((dev->ncr.dma_mode != DMA_IDLE) && (dev->status & 0x04)) { timer_stop(&pas16->scsi_timer); pas16->timeout_status &= 0x7f; } } static void pas16_timeout_callback(void *priv) { pas16_t * pas16 = (pas16_t *) priv; pas16->timeout_status |= 0x80; if ((pas16->timeout_status & 0x08) && (pas16->irq != -1)) picint(1 << pas16->irq); timer_advance_u64(&pas16->scsi_timer, (pas16->timeout_count & 0x3f) * PASSCSICONST); } static void pas16_out(uint16_t port, uint8_t val, void *priv) { pas16_t * pas16 = (pas16_t *) priv; nsc_mixer_t * nsc_mixer = &pas16->nsc_mixer; mv508_mixer_t *mv508_mixer = &pas16->mv508_mixer; pas16_log("[%04X:%08X] PAS16: [W] %04X (%04X) = %02X\n", CS, cpu_state.pc, port, port - pas16->base, val); port -= pas16->base; switch (port) { case 0x0000 ... 0x0003: pas16->opl.write(port + 0x0388, val, pas16->opl.priv); break; case 0x0400 ... 0x0402: break; case 0x0403: if (val & MV508_ADDRESS) mv508_mixer->index = val & ~MV508_ADDRESS; else { uint8_t bank; uint8_t mask; pas16_log("MVA508 register %02X = %02X\n", mv508_mixer->index, val); if (mv508_mixer->index & MV508_MIXER) { bank = !!(val & MV508_INPUT_MIX); mask = 0x1f; } else { bank = 2; mask = 0x3f; } if (mv508_mixer->index & MV508_CHANNEL) mv508_mixer->regs[bank][mv508_mixer->index] = val & mask; else { mv508_mixer->regs[bank][mv508_mixer->index | MV508_LEFT] = val & mask; mv508_mixer->regs[bank][mv508_mixer->index | MV508_RIGHT] = val & mask; } mv508_mixer_recalc(mv508_mixer); } break; case 0x0800: if (pas16->type && !(val & SERIAL_MIXER_RESET_PCM)) { pas16->audio_mixer = val; pas16_reset_pcm(pas16); } else if (!pas16->type) { switch (nsc_mixer->im_state) { default: break; case STATE_SM_IDLE: /* Transmission initiated. */ if (val & SERIAL_MIXER_IDENT) { if (!(val & SERIAL_MIXER_CLOCK) && (pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { /* Prepare for receiving LMC835N data. */ nsc_mixer->im_data[LMC835_DATA] = 0x0000; nsc_mixer->im_state |= STATE_LMC835_DATA; } } else { if ((pas16->audio_mixer & SERIAL_MIXER_IDENT)) { /* Prepare for receiving the LMC1982CIN address. */ nsc_mixer->im_data[LMC1982_ADDR] = 0x0000; nsc_mixer->im_state |= STATE_LMC1982_ADDR; } if ((val & SERIAL_MIXER_CLOCK) && !(pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { /* Clock the least siginificant bit of the LMC1982CIN address. */ nsc_mixer->im_data[LMC1982_ADDR] |= ((val & SERIAL_MIXER_DATA) << (nsc_mixer->im_state & STATE_DATA_MASK)); nsc_mixer->im_state++; } } break; case STATE_LMC1982_ADDR_0: if (val & SERIAL_MIXER_IDENT) { /* IDENT went high in LM1982CIN address state 0, behave as if we were in the idle state. */ if (!(val & SERIAL_MIXER_CLOCK) && (pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { nsc_mixer->im_data[LMC835_DATA] = 0x0000; nsc_mixer->im_state = STATE_LMC835_DATA_0; } } else if ((val & SERIAL_MIXER_CLOCK) && !(pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { /* Clock the least siginificant bit of the LMC1982CIN address. */ nsc_mixer->im_data[LMC1982_ADDR] |= ((val & SERIAL_MIXER_DATA) << (nsc_mixer->im_state & STATE_DATA_MASK)); nsc_mixer->im_state++; } break; case STATE_LMC1982_ADDR_1 ... STATE_LMC1982_ADDR_7: if ((val & 0x02) && !(pas16->audio_mixer & 0x02)) { /* Clock the next bit of the LMC1982CIN address. */ nsc_mixer->im_data[LMC1982_ADDR] |= ((val & SERIAL_MIXER_DATA) << (nsc_mixer->im_state & STATE_DATA_MASK)); nsc_mixer->im_state++; } break; case STATE_LMC1982_ADDR_OVER: /* Prepare for receiving the LMC1982CIN data. */ nsc_mixer->im_data[LMC1982_DATA] = 0x0000; nsc_mixer->im_state = STATE_LMC1982_DATA_0; break; case STATE_LMC1982_DATA_0 ... STATE_LMC1982_DATA_7: case STATE_LMC1982_DATA_9 ... STATE_LMC1982_DATA_F: if ((val & SERIAL_MIXER_CLOCK) && !(pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { /* Clock the next bit of the LMC1982CIN data. */ nsc_mixer->im_data[LMC1982_DATA] |= ((val & SERIAL_MIXER_DATA) << (nsc_mixer->im_state & STATE_DATA_MASK_W)); nsc_mixer->im_state++; } break; case STATE_LMC1982_DATA_8: if (val & SERIAL_MIXER_IDENT) { if (!(pas16->audio_mixer & SERIAL_MIXER_IDENT)) /* LMC1982CIN data transfer ended after 8 bits, process the data and reset the state back to idle. */ lmc1982_update_reg(nsc_mixer); else if ((val & SERIAL_MIXER_CLOCK) && !(pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { /* Clock the next bit of the LMC1982CIN data. */ nsc_mixer->im_data[LMC1982_DATA] |= ((val & SERIAL_MIXER_DATA) << (nsc_mixer->im_state & STATE_DATA_MASK_W)); nsc_mixer->im_state++; } } break; case STATE_LMC1982_DATA_OVER: if ((val & SERIAL_MIXER_IDENT) && !(pas16->audio_mixer & SERIAL_MIXER_IDENT)) /* LMC1982CIN data transfer ended, process the data and reset the state back to idle. */ lmc1982_update_reg(nsc_mixer); break; case STATE_LMC835_DATA_0 ... STATE_LMC835_DATA_7: if ((val & SERIAL_MIXER_CLOCK) && !(pas16->audio_mixer & SERIAL_MIXER_CLOCK)) { /* Clock the next bit of the LMC835N data. */ nsc_mixer->im_data[LMC835_DATA] |= ((val & SERIAL_MIXER_DATA) << (nsc_mixer->im_state & STATE_DATA_MASK)); nsc_mixer->im_state++; } break; case STATE_LMC835_DATA_OVER: if ((val & SERIAL_MIXER_STROBE) && !(pas16->audio_mixer & SERIAL_MIXER_STROBE)) { if (nsc_mixer->im_data[LMC835_DATA] & LMC835_FLAG_ADDR) /* The LMC835N data is an address, copy it into its own space for usage when processing it at the end and strip bits 7 (it's the address/data indicator) and 6 (it's a "don't care" bit). */ nsc_mixer->im_data[LMC835_ADDR] = nsc_mixer->im_data[LMC835_DATA] & 0x7f; else lmc835_update_reg(nsc_mixer); nsc_mixer->im_state = STATE_SM_IDLE; } break; } pas16->audio_mixer = val; } break; case 0x0801: pas16->irq_stat &= ~val; if ((pas16->irq != -1) && !(pas16->irq_stat & 0x1f)) picintc(1 << pas16->irq); break; case 0x0802: pas16_update(pas16); pitf_ctr_set_gate(pas16->pit, 1, !!(val & 0x80)); pitf_ctr_set_gate(pas16->pit, 0, !!(val & 0x40)); pas16->stereo_lr = 0; pas16->dma8_ff = 0; if ((val & 0x20) && !(pas16->audiofilt & 0x20)) { pas16_log("Reset.\n"); pas16_reset_regs(pas16); } pas16->audiofilt = val; if (val & 0x1f) { pas16->filter = 1; switch (val & 0x1f) { default: pas16->filter = 0; break; case 0x01: recalc_pas16_filter(17897); break; case 0x02: recalc_pas16_filter(15909); break; case 0x04: recalc_pas16_filter(2982); break; case 0x09: recalc_pas16_filter(11931); break; case 0x11: recalc_pas16_filter(8948); break; case 0x19: recalc_pas16_filter(5965); break; } } else pas16->filter = 0; break; case 0x0803: pas16->irq_ena = val & 0x1f; pas16->irq_stat &= ((val & 0x1f) | 0xe0); if ((pas16->irq != -1) && !(pas16->irq_stat & 0x1f)) picintc(1 << pas16->irq); break; case 0x0c00: case 0x0c01: pas16_update(pas16); break; case 0x0c02: if ((val & PAS16_PCM_ENA) && !(pas16->pcm_ctrl & PAS16_PCM_ENA)) { /* Guess */ pas16->stereo_lr = 0; pas16->irq_stat &= 0xd7; /* Needed for 8-bit DMA to work correctly on a 16-bit DMA channel. */ pas16->dma8_ff = 0; } pas16->pcm_ctrl = val; pas16_log("Now in: %s (%02X)\n", (pas16->pcm_ctrl & PAS16_PCM_MONO) ? "Mono" : "Stereo", val); break; case 0x1401: case 0x1403: pas16->midi_ctrl = val; if ((val & 0x60) == 0x60) { pas16->midi_uart_out = 0; pas16->midi_uart_in = 0; } else if ((val & 0x1c) == 0x04) pas16->midi_uart_in = 1; else pas16->midi_uart_out = 1; pas16_update_irq(pas16); break; case 0x1402: case 0x1802: pas16->midi_data = val; pas16_log("UART OUT=%d.\n", pas16->midi_uart_out); if (pas16->midi_uart_out) midi_raw_out_byte(val); break; case 0x1800: pas16->midi_stat = val; pas16_update_irq(pas16); break; case 0x1801: pas16->fifo_stat = val; break; case 0x1c00 ... 0x1c03: /* NCR5380 ports 0 to 3. */ case 0x3c00 ... 0x3c03: /* NCR5380 ports 4 to 7. */ if (pas16->has_scsi) ncr5380_write((port & 0x0003) | ((port & 0x2000) >> 11), val, &pas16->scsi->ncr); break; case 0x4000: if (pas16->has_scsi) { pas16->timeout_count = val; if (timer_is_enabled(&pas16->scsi_timer)) timer_disable(&pas16->scsi_timer); if ((val & 0x3f) > 0x00) timer_set_delay_u64(&pas16->scsi_timer, (val & 0x3f) * PASSCSICONST); } break; case 0x4001: if (pas16->has_scsi) { pas16->timeout_status = val & 0x7f; if (pas16->scsi_irq != -1) picintc(1 << pas16->scsi_irq); } break; case 0x5c00: if (pas16->has_scsi) t128_write(0x1e00, val, pas16->scsi); break; case 0x5c03: if (pas16->has_scsi) { if (val & 0x80) { pas16->scsi->ncr.irq_state = 0; if (pas16->scsi_irq != -1) picintc(1 << pas16->scsi_irq); } } break; case 0x7c01: pas16->enhancedscsi = val; break; case 0x8000: if ((val & 0xc0) && !(pas16->sys_conf_1 & 0xc0)) { pas16_log("Reset.\n"); val = 0x00; pas16_reset_common(pas16); pas16->base = pas16->new_base; pas16_io_handler(pas16, 1); } pas16->sys_conf_1 = val; pas16_change_pit_clock_speed(pas16); pas16_log("Now in: %s mode\n", (pas16->sys_conf_1 & 0x02) ? "native" : "compatibility"); break; case 0x8001: pas16->sys_conf_2 = val; pas16_log("Now in: %i bits (%02X)\n", (pas16->sys_conf_2 & 0x04) ? ((pas16->sys_conf_2 & 0x08) ? 12 : 16) : 8, val); break; case 0x8002: pas16->sys_conf_3 = val; pas16_change_pit_clock_speed(pas16); pas16_log("Use 1.008 MHz clok for PCM: %c\n", (val & 0x02) ? 'Y' : 'N'); break; case 0x8003: pas16->sys_conf_4 = val; if (pas16->has_scsi && (pas16->scsi_irq != -1) && !(val & 0x20)) picintc(1 << pas16->scsi_irq); break; case 0xbc00: pas16->waitstates = val; break; case 0xbc02: pas16->prescale_div = val; pas16_change_pit_clock_speed(pas16); pas16_log("Prescale divider now: %i\n", val); break; case 0xf000: pas16->io_conf_1 = val; break; case 0xf001: pas16->io_conf_2 = val; pas16->dma = pas16_dmas[val & 0x7]; pas16_change_pit_clock_speed(pas16); pas16_log("pas16_out : set PAS DMA %i\n", pas16->dma); break; case 0xf002: pas16->io_conf_3 = val; if (pas16->irq != -1) picintc(1 << pas16->irq); pas16->irq = pas16_irq_convert(val & 0x0f); if (pas16->has_scsi) { if (pas16->scsi_irq != -1) picintc(1 << pas16->scsi_irq); pas16->scsi_irq = pas16_irq_convert(val >> 4); ncr5380_set_irq(&pas16->scsi->ncr, pas16->scsi_irq); } pas16_log("pas16_out : set PAS IRQ %i, val=%02x\n", pas16->irq, val & 0x0f); break; case 0xf003: pas16->io_conf_4 = val; break; case 0xf400: pas16->compat = val & 0xf3; pas16_log("PCM compression is now %sabled\n", (val & 0x10) ? "en" : "dis"); if (pas16->compat & 0x02) sb_dsp_setaddr(&pas16->dsp, pas16->sb_compat_base); else sb_dsp_setaddr(&pas16->dsp, 0); if (pas16->compat & 0x01) mpu401_change_addr(pas16->mpu, ((pas16->compat_base & 0xf0) | 0x300)); else mpu401_change_addr(pas16->mpu, 0); break; case 0xf401: pas16->compat_base = val; pas16->sb_compat_base = ((pas16->compat_base & 0xf) << 4) | 0x200; pas16_log("SB Compatibility base: %04X\n", pas16->sb_compat_base); if (pas16->compat & 0x02) sb_dsp_setaddr(&pas16->dsp, pas16->sb_compat_base); if (pas16->compat & 0x01) mpu401_change_addr(pas16->mpu, ((pas16->compat_base & 0xf0) | 0x300)); break; case 0xf802: pas16->sb_irqdma = val; mpu401_setirq(pas16->mpu, pas16_sb_irqs[val & 7]); sb_dsp_setirq(&pas16->dsp, pas16_sb_irqs[(val >> 3) & 7]); sb_dsp_setdma8(&pas16->dsp, pas16_sb_dmas[(val >> 6) & 3]); pas16_log("pas16_out : set SB IRQ %i DMA %i.\n", pas16_sb_irqs[(val >> 3) & 7], pas16_sb_dmas[(val >> 6) & 3]); break; default: pas16_log("pas16_out : unknown %04X\n", port); } } /* 8-bit mono: - 8-bit DMA : On every timer 0 over, read the 8-bit sample and ctr_clock(); (One ctr_clock() per timer 0 over) - 16-bit DMA: On every even timer 0 over, read two 8-bit samples at once and ctr_clock(); On every odd timer 0 over, read the MSB of the previously read sample word. (One ctr_clock() per two timer 0 overs) 8-bit stereo: - 8-bit DMA : On every timer 0, read two 8-bit samples and ctr_clock() twice; (Two ctr_clock()'s per timer 0 over) - 16-bit DMA: On every timer 0, read two 8-bit samples and ctr_clock() once. (One ctr_clock() per timer 0 over) 16-bit mono (to be verified): - 8-bit DMA : On every timer 0, read one 16-bit sample and ctr_clock() twice; (Two ctr_clock()'s per timer 0 over) - 16-bit DMA: On every timer 0, read one 16-bit sample and ctr_clock() once. (One ctr_clock() per timer 0 over) 16-bit stereo: - 8-bit DMA : On every timer 0, read one 16-bit sample and ctr_clock() twice; (Two ctr_clock()'s per timer 0 over) - 16-bit DMA: On every timer 0, read one 16-bit sample and ctr_clock() twice. (Two ctr_clock()'s per timer 0 over) What we can conclude from this is: - Maximum 16 bits per timer 0 over; - A 8-bit sample always takes one ctr_clock() tick, unless it has been read alongside the previous sample; - A 16-bit sample always takes two ctr_clock() ticks. */ static uint16_t pas16_dma_channel_read(pas16_t *pas16, int channel) { int status; uint16_t ret; if (pas16->pcm_ctrl & PAS16_PCM_DMA_ENA) { if (pas16->dma >= 5) { dma_channel_advance(pas16->dma); status = dma_channel_read_only(pas16->dma); } else status = dma_channel_read(pas16->dma); ret = (status == DMA_NODATA) ? 0x0000 : (status & 0xffff); } else ret = 0x0000; return ret; } static uint16_t pas16_dma_readb(pas16_t *pas16) { const uint16_t ret = pas16_dma_channel_read(pas16, pas16->dma); pas16->ticks++; return ret; } static uint16_t pas16_dma_readw(pas16_t *pas16, const uint8_t timer1_ticks) { uint16_t ret; if (pas16->dma >= 5) ret = pas16_dma_channel_read(pas16, pas16->dma); else { ret = pas16_dma_channel_read(pas16, pas16->dma); ret |= (pas16_dma_channel_read(pas16, pas16->dma) << 8); } pas16->ticks += timer1_ticks; return ret; } static uint16_t pas16_readdmab(pas16_t *pas16) { if (pas16->dma >= 5) { if (pas16->dma8_ff) pas16->dma8_dat >>= 8; else pas16->dma8_dat = pas16_dma_readb(pas16); pas16->dma8_ff = !pas16->dma8_ff; } else pas16->dma8_dat = pas16_dma_readb(pas16); return ((pas16->dma8_dat & 0xff) ^ 0x80) << 8; } static uint16_t pas16_readdmaw_mono(pas16_t *pas16) { const uint16_t ret = pas16_dma_readw(pas16, 1 + (pas16->dma < 5)); return ret; } static uint16_t pas16_readdmaw_stereo(pas16_t *pas16) { uint16_t ret; uint16_t ticks = (pas16->sys_conf_1 & 0x02) ? (1 + (pas16->dma < 5)) : 2; ret = pas16_dma_readw(pas16, ticks); return ret; } static uint16_t pas16_readdma_mono(pas16_t *pas16) { uint16_t ret; if (pas16->sys_conf_2 & 0x04) { ret = pas16_readdmaw_mono(pas16); if (pas16->sys_conf_2 & 0x08) ret &= 0xfff0; } else ret = pas16_readdmab(pas16); if (pas16->sys_conf_2 & PAS16_SC2_MSBINV) ret ^= 0x8000; return ret; } static uint16_t pas16_readdma_stereo(pas16_t *pas16) { uint16_t ret; if (pas16->sys_conf_2 & 0x04) { ret = pas16_readdmaw_stereo(pas16); if (pas16->sys_conf_2 & 0x08) ret &= 0xfff0; } else ret = pas16_readdmab(pas16); if (pas16->sys_conf_2 & PAS16_SC2_MSBINV) ret ^= 0x8000; return ret; } static void pas16_pit_timer0(const int new_out, UNUSED(int old_out), void *priv) { const pitf_t *pit = (const pitf_t *) priv; pas16_t * pas16 = (pas16_t *) pit->dev_priv; if (!pas16->pit->counters[0].gate) return; if (!dma_channel_readable(pas16->dma)) return; pas16_update_irq(pas16); if (((pas16->pcm_ctrl & PAS16_PCM_ENA) == PAS16_PCM_ENA) && (pit->counters[1].m & 2) && new_out) { uint16_t temp; pas16->ticks = 0; if (pas16->pcm_ctrl & PAS16_PCM_MONO) { temp = pas16_readdma_mono(pas16); pas16->pcm_dat_l = pas16->pcm_dat_r = temp; } else { temp = pas16_readdma_stereo(pas16); if (pas16->sys_conf_1 & 0x02) { pas16->pcm_dat_l = temp; temp = pas16_readdma_stereo(pas16); pas16->pcm_dat_r = temp; } else { if (pas16->stereo_lr) pas16->pcm_dat_r = temp; else pas16->pcm_dat_l = temp; pas16->stereo_lr = !pas16->stereo_lr; pas16->irq_stat = (pas16->irq_stat & 0xdf) | (pas16->stereo_lr << 5); } } if (pas16->ticks) { for (uint16_t i = 0; i < pas16->ticks; i++) pitf_ctr_clock(pas16->pit, 1); pas16->ticks = 0; } pas16->irq_stat |= PAS16_INT_SAMP; if (pas16->irq_ena & PAS16_INT_SAMP) { pas16_log("INT SAMP.\n"); if (pas16->irq != -1) picint(1 << pas16->irq); } pas16_update(pas16); } } static void pas16_pit_timer1(const int new_out, UNUSED(int old_out), void *priv) { const pitf_t *pit = (pitf_t * )priv; pas16_t * pas16 = (pas16_t *) pit->dev_priv; if (!pas16->pit->counters[1].gate) return; /* At new_out = 0, it's in the counter reload phase. */ if ((pas16->pcm_ctrl & PAS16_PCM_ENA) && (pit->counters[1].m & 2) && new_out) { if (pas16->irq_ena & PAS16_INT_PCM) { pas16->irq_stat |= PAS16_INT_PCM; pas16_log("pas16_pcm_poll : cause IRQ %i %02X\n", pas16->irq, 1 << pas16->irq); if (pas16->irq != -1) picint(1 << pas16->irq); } } } static void pas16_out_base(UNUSED(uint16_t port), uint8_t val, void *priv) { pas16_t *pas16 = (pas16_t *) priv; pas16_log("[%04X:%08X] PAS16: [W] %04X = %02X\n", CS, cpu_state.pc, port, val); if (pas16->master_ff && (pas16->board_id == pas16->this_id)) pas16->new_base = val << 2; else if (!pas16->master_ff) pas16->board_id = val; pas16->master_ff = !pas16->master_ff; } static void pas16_input_msg(void *priv, uint8_t *msg, uint32_t len) { pas16_t *pas16 = (pas16_t *) priv; if (pas16->sysex) return; if (pas16->midi_uart_in) { pas16->midi_stat |= 0x04; for (uint32_t i = 0; i < len; i++) { pas16->midi_queue[pas16->midi_w++] = msg[i]; pas16->midi_w &= 0xff; } pas16_update_irq(pas16); } } static int pas16_input_sysex(void *priv, uint8_t *buffer, uint32_t len, int abort) { pas16_t *pas16 = (pas16_t *) priv; if (abort) { pas16->sysex = 0; return 0; } pas16->sysex = 1; for (uint32_t i = 0; i < len; i++) { if (pas16->midi_r == pas16->midi_w) return (int) (len - i); pas16->midi_queue[pas16->midi_w++] = buffer[i]; pas16->midi_w &= 0xff; } pas16->sysex = 0; return 0; } static void pas16_update(pas16_t *pas16) { if (!(pas16->audiofilt & PAS16_FILT_MUTE)) { for (; pas16->pos < sound_pos_global; pas16->pos++) { pas16->pcm_buffer[0][pas16->pos] = 0; pas16->pcm_buffer[1][pas16->pos] = 0; } } else { for (; pas16->pos < sound_pos_global; pas16->pos++) { pas16->pcm_buffer[0][pas16->pos] = (int16_t) pas16->pcm_dat_l; pas16->pcm_buffer[1][pas16->pos] = (int16_t) pas16->pcm_dat_r; } } } void pasplus_get_buffer(int32_t *buffer, int len, void *priv) { pas16_t * pas16 = (pas16_t *) priv; const nsc_mixer_t *mixer = &pas16->nsc_mixer; double bass_treble; sb_dsp_update(&pas16->dsp); pas16_update(pas16); for (int c = 0; c < len * 2; c += 2) { double out_l = pas16->dsp.buffer[c]; double out_r = pas16->dsp.buffer[c + 1]; if (pas16->filter) { /* We divide by 3 to get the volume down to normal. */ out_l += low_fir_pas16(0, (double) pas16->pcm_buffer[0][c >> 1]) * mixer->pcm_l; out_r += low_fir_pas16(1, (double) pas16->pcm_buffer[1][c >> 1]) * mixer->pcm_r; } else { out_l += ((double) pas16->pcm_buffer[0][c >> 1]) * mixer->pcm_l; out_r += ((double) pas16->pcm_buffer[1][c >> 1]) * mixer->pcm_r; } out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->bass]; if (mixer->bass > 6) { out_l += (low_iir(0, 0, out_l) * bass_treble); out_r += (low_iir(0, 1, out_r) * bass_treble); } else if (mixer->bass < 6) { out_l = (out_l *bass_treble + low_cut_iir(0, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + low_cut_iir(0, 1, out_r) * (1.0 - bass_treble)); } } if (mixer->treble != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->treble]; if (mixer->treble > 6) { out_l += (high_iir(0, 0, out_l) * bass_treble); out_r += (high_iir(0, 1, out_r) * bass_treble); } else if (mixer->treble < 6) { out_l = (out_l *bass_treble + high_cut_iir(0, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + high_cut_iir(0, 1, out_r) * (1.0 - bass_treble)); } } buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } pas16->pos = 0; pas16->dsp.pos = 0; } void pasplus_get_music_buffer(int32_t *buffer, int len, void *priv) { const pas16_t * pas16 = (const pas16_t *) priv; const nsc_mixer_t *mixer = &pas16->nsc_mixer; const int32_t * opl_buf = pas16->opl.update(pas16->opl.priv); double bass_treble; for (int c = 0; c < len * 2; c += 2) { double out_l = (((double) opl_buf[c]) * mixer->fm_l) * 0.7171630859375; double out_r = (((double) opl_buf[c + 1]) * mixer->fm_r) * 0.7171630859375; /* TODO: recording CD, Mic with AGC or line in. Note: mic volume does not affect recording. */ out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->bass]; if (mixer->bass > 6) { out_l += (low_iir(1, 0, out_l) * bass_treble); out_r += (low_iir(1, 1, out_r) * bass_treble); } else if (mixer->bass < 6) { out_l = (out_l *bass_treble + low_cut_iir(1, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + low_cut_iir(1, 1, out_r) * (1.0 - bass_treble)); } } if (mixer->treble != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->treble]; if (mixer->treble > 6) { out_l += (high_iir(1, 0, out_l) * bass_treble); out_r += (high_iir(1, 1, out_r) * bass_treble); } else if (mixer->treble < 6) { out_l = (out_l *bass_treble + high_cut_iir(1, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + high_cut_iir(1, 1, out_r) * (1.0 - bass_treble)); } } buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } pas16->opl.reset_buffer(pas16->opl.priv); } void pasplus_filter_cd_audio(int channel, double *buffer, void *priv) { const pas16_t * pas16 = (const pas16_t *) priv; const nsc_mixer_t *mixer = &pas16->nsc_mixer; const double cd = channel ? mixer->cd_r : mixer->cd_l; const double master = channel ? mixer->master_r : mixer->master_l; const int32_t bass = mixer->bass; const int32_t treble = mixer->treble; double c = (*buffer) * cd * master; double bass_treble; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (bass != 6) { bass_treble = lmc1982_bass_treble_4bits[bass]; if (bass > 6) c += (low_iir(2, channel, c) * bass_treble); else c = (c * bass_treble + low_cut_iir(2, channel, c) * (1.0 - bass_treble)); } if (treble != 6) { bass_treble = lmc1982_bass_treble_4bits[treble]; if (treble > 6) c += (high_iir(2, channel, c) * bass_treble); else c = (c * bass_treble + high_cut_iir(2, channel, c) * (1.0 - bass_treble)); } *buffer = c; } void pasplus_filter_pc_speaker(int channel, double *buffer, void *priv) { const pas16_t * pas16 = (pas16_t *) priv; const nsc_mixer_t *mixer = &pas16->nsc_mixer; const double spk = channel ? mixer->speaker_r : mixer->speaker_l; const double master = channel ? mixer->master_r : mixer->master_l; const int32_t bass = mixer->bass; const int32_t treble = mixer->treble; double c = (*buffer) * spk * master; double bass_treble; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (bass != 6) { bass_treble = lmc1982_bass_treble_4bits[bass]; if (bass > 6) c += (low_iir(3, channel, c) * bass_treble); else c = (c * bass_treble + low_cut_iir(3, channel, c) * (1.0 - bass_treble)); } if (treble != 6) { bass_treble = lmc1982_bass_treble_4bits[treble]; if (treble > 6) c += (high_iir(3, channel, c) * bass_treble); else c = (c * bass_treble + high_cut_iir(3, channel, c) * (1.0 - bass_treble)); } *buffer = c; } void pas16_get_buffer(int32_t *buffer, int len, void *priv) { pas16_t * pas16 = (pas16_t *) priv; const mv508_mixer_t *mixer = &pas16->mv508_mixer; double bass_treble; sb_dsp_update(&pas16->dsp); pas16_update(pas16); for (int c = 0; c < len * 2; c += 2) { double out_l = (pas16->dsp.buffer[c] * mixer->sb_l) / 3.0; double out_r = (pas16->dsp.buffer[c + 1] * mixer->sb_r) / 3.0; if (pas16->filter) { /* We divide by 3 to get the volume down to normal. */ out_l += (low_fir_pas16(0, (double) pas16->pcm_buffer[0][c >> 1]) * mixer->pcm_l) / 3.0; out_r += (low_fir_pas16(1, (double) pas16->pcm_buffer[1][c >> 1]) * mixer->pcm_r) / 3.0; } else { out_l += (((double) pas16->pcm_buffer[0][c >> 1]) * mixer->pcm_l) / 3.0; out_r += (((double) pas16->pcm_buffer[1][c >> 1]) * mixer->pcm_r) / 3.0; } out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->bass]; if (mixer->bass > 6) { out_l += (low_iir(0, 0, out_l) * bass_treble); out_r += (low_iir(0, 1, out_r) * bass_treble); } else if (mixer->bass < 6) { out_l = (out_l *bass_treble + low_cut_iir(0, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + low_cut_iir(0, 1, out_r) * (1.0 - bass_treble)); } } if (mixer->treble != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->treble]; if (mixer->treble > 6) { out_l += (high_iir(0, 0, out_l) * bass_treble); out_r += (high_iir(0, 1, out_r) * bass_treble); } else if (mixer->treble < 6) { out_l = (out_l *bass_treble + high_cut_iir(0, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + high_cut_iir(0, 1, out_r) * (1.0 - bass_treble)); } } buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } pas16->pos = 0; pas16->dsp.pos = 0; } void pas16_get_music_buffer(int32_t *buffer, int len, void *priv) { const pas16_t * pas16 = (const pas16_t *) priv; const mv508_mixer_t *mixer = &pas16->mv508_mixer; const int32_t * opl_buf = pas16->opl.update(pas16->opl.priv); double bass_treble; for (int c = 0; c < len * 2; c += 2) { double out_l = (((double) opl_buf[c]) * mixer->fm_l) * 0.7171630859375; double out_r = (((double) opl_buf[c + 1]) * mixer->fm_r) * 0.7171630859375; /* TODO: recording CD, Mic with AGC or line in. Note: mic volume does not affect recording. */ out_l *= mixer->master_l; out_r *= mixer->master_r; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (mixer->bass != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->bass]; if (mixer->bass > 6) { out_l += (low_iir(1, 0, out_l) * bass_treble); out_r += (low_iir(1, 1, out_r) * bass_treble); } else if (mixer->bass < 6) { out_l = (out_l *bass_treble + low_cut_iir(1, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + low_cut_iir(1, 1, out_r) * (1.0 - bass_treble)); } } if (mixer->treble != 6) { bass_treble = lmc1982_bass_treble_4bits[mixer->treble]; if (mixer->treble > 6) { out_l += (high_iir(1, 0, out_l) * bass_treble); out_r += (high_iir(1, 1, out_r) * bass_treble); } else if (mixer->treble < 6) { out_l = (out_l *bass_treble + high_cut_iir(1, 0, out_l) * (1.0 - bass_treble)); out_r = (out_r *bass_treble + high_cut_iir(1, 1, out_r) * (1.0 - bass_treble)); } } buffer[c] += (int32_t) out_l; buffer[c + 1] += (int32_t) out_r; } pas16->opl.reset_buffer(pas16->opl.priv); } void pas16_filter_cd_audio(int channel, double *buffer, void *priv) { const pas16_t * pas16 = (const pas16_t *) priv; const mv508_mixer_t *mixer = &pas16->mv508_mixer; const double cd = channel ? mixer->cd_r : mixer->cd_l; const double master = channel ? mixer->master_r : mixer->master_l; const int32_t bass = mixer->bass; const int32_t treble = mixer->treble; double c = (((*buffer) * cd) / 3.0) * master; double bass_treble; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (bass != 6) { bass_treble = lmc1982_bass_treble_4bits[bass]; if (bass > 6) c += (low_iir(2, channel, c) * bass_treble); else c = (c * bass_treble + low_cut_iir(2, channel, c) * (1.0 - bass_treble)); } if (treble != 6) { bass_treble = lmc1982_bass_treble_4bits[treble]; if (treble > 6) c += (high_iir(2, channel, c) * bass_treble); else c = (c * bass_treble + high_cut_iir(2, channel, c) * (1.0 - bass_treble)); } *buffer = c; } void pas16_filter_pc_speaker(int channel, double *buffer, void *priv) { const pas16_t * pas16 = (const pas16_t *) priv; const mv508_mixer_t *mixer = &pas16->mv508_mixer; const double spk = channel ? mixer->speaker_r : mixer->speaker_l; const double master = channel ? mixer->master_r : mixer->master_l; const int32_t bass = mixer->bass; const int32_t treble = mixer->treble; double c = (((*buffer) * spk) / 3.0) * master; double bass_treble; /* This is not exactly how one does bass/treble controls, but the end result is like it. A better implementation would reduce the CPU usage. */ if (bass != 6) { bass_treble = lmc1982_bass_treble_4bits[bass]; if (bass > 6) c += (low_iir(3, channel, c) * bass_treble); else c = (c * bass_treble + low_cut_iir(3, channel, c) * (1.0 - bass_treble)); } if (treble != 6) { bass_treble = lmc1982_bass_treble_4bits[treble]; if (treble > 6) c += (high_iir(3, channel, c) * bass_treble); else c = (c * bass_treble + high_cut_iir(3, channel, c) * (1.0 - bass_treble)); } *buffer = c; } static void pas16_speed_changed(void *priv) { pas16_change_pit_clock_speed(priv); } static void * pas16_init(const device_t *info) { pas16_t *pas16 = calloc(1, sizeof(pas16_t)); if (pas16_next > 3) { fatal("Attempting to add a Pro Audio Spectrum instance beyond the maximum amount\n"); free(pas16); return NULL; } pas16->type = info->local & 0xff; pas16->has_scsi = (!pas16->type) || (pas16->type == 0x0f); fm_driver_get(FM_YMF262, &pas16->opl); sb_dsp_set_real_opl(&pas16->dsp, 1); sb_dsp_init(&pas16->dsp, SB2, SB_SUBTYPE_DEFAULT, pas16); pas16->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(pas16->mpu, 0, sizeof(mpu_t)); mpu401_init(pas16->mpu, 0, 0, M_UART, device_get_config_int("receive_input401")); sb_dsp_set_mpu(&pas16->dsp, pas16->mpu); pas16->sb_compat_base = 0x0000; io_sethandler(0x9a01, 0x0001, NULL, NULL, NULL, pas16_out_base, NULL, NULL, pas16); pas16->this_id = 0xbc + pas16_next; if (pas16->has_scsi) { pas16->scsi = device_add(&scsi_pas_device); timer_add(&pas16->scsi->timer, pas16_scsi_callback, pas16, 0); timer_add(&pas16->scsi_timer, pas16_timeout_callback, pas16, 0); other_scsi_present++; } pas16->pit = device_add(&i8254_ext_io_fast_device); pas16_reset(pas16); pas16->pit->dev_priv = pas16; pas16->irq = pas16->type ? 10 : 5; pas16->io_conf_3 = pas16->type ? 0x07 : 0x04; if (pas16->has_scsi) { pas16->scsi_irq = pas16->type ? 11 : 7; pas16->io_conf_3 |= (pas16->type ? 0x80 : 0x60); ncr5380_set_irq(&pas16->scsi->ncr, pas16->scsi_irq); } pas16->dma = 3; for (uint8_t i = 0; i < 3; i++) pitf_ctr_set_gate(pas16->pit, i, 0); pitf_ctr_set_out_func(pas16->pit, 0, pas16_pit_timer0); pitf_ctr_set_out_func(pas16->pit, 1, pas16_pit_timer1); pitf_ctr_set_using_timer(pas16->pit, 0, 1); pitf_ctr_set_using_timer(pas16->pit, 1, 0); pitf_ctr_set_using_timer(pas16->pit, 2, 0); if (pas16->type) { sound_add_handler(pas16_get_buffer, pas16); music_add_handler(pas16_get_music_buffer, pas16); sound_set_cd_audio_filter(pas16_filter_cd_audio, pas16); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(pas16_filter_pc_speaker, pas16); } else { sound_add_handler(pasplus_get_buffer, pas16); music_add_handler(pasplus_get_music_buffer, pas16); sound_set_cd_audio_filter(pasplus_filter_cd_audio, pas16); if (device_get_config_int("control_pc_speaker")) sound_set_pc_speaker_filter(pasplus_filter_pc_speaker, pas16); } if (device_get_config_int("receive_input")) midi_in_handler(1, pas16_input_msg, pas16_input_sysex, pas16); for (uint8_t i = 0; i < 16; i++) { if (i < 6) lmc1982_bass_treble_4bits[i] = pow(10.0, (-((double) (12 - (i << 1))) / 10.0)); else if (i == 6) lmc1982_bass_treble_4bits[i] = 0.0; else if ((i > 6) && (i <= 12)) lmc1982_bass_treble_4bits[i] = 1.0 - pow(10.0, ((double) ((i - 6) << 1) / 10.0)); else lmc1982_bass_treble_4bits[i] = 1.0 - pow(10.0, 1.2); } pas16_next++; return pas16; } static void pas16_close(void *priv) { pas16_t *pas16 = (pas16_t *) priv; free(pas16); pas16_next = 0; } static const device_config_t pas16_config[] = { { .name = "control_pc_speaker", .description = "Control PC speaker", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "receive_input", .description = "Receive input (PAS MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } }; const device_t pasplus_device = { .name = "Pro Audio Spectrum Plus", .internal_name = "pasplus", .flags = DEVICE_ISA, .local = 0, .init = pas16_init, .close = pas16_close, .reset = pas16_reset, { .available = NULL }, .speed_changed = pas16_speed_changed, .force_redraw = NULL, .config = pas16_config }; const device_t pas16_device = { .name = "Pro Audio Spectrum 16", .internal_name = "pas16", .flags = DEVICE_ISA | DEVICE_AT, .local = 0x0f, .init = pas16_init, .close = pas16_close, .reset = pas16_reset, { .available = NULL }, .speed_changed = pas16_speed_changed, .force_redraw = NULL, .config = pas16_config }; const device_t pas16d_device = { .name = "Pro Audio Spectrum 16D", .internal_name = "pas16d", .flags = DEVICE_ISA | DEVICE_AT, .local = 0x0c, .init = pas16_init, .close = pas16_close, .reset = pas16_reset, { .available = NULL }, .speed_changed = pas16_speed_changed, .force_redraw = NULL, .config = pas16_config }; ```
/content/code_sandbox/src/sound/snd_pas16.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
27,888
```c++ /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * MIDI backend implemented using the RtMidi library. * * Author: Cacodemon345, * Miran Grca, <mgrca8@gmail.com> */ #if defined __has_include # if __has_include(<RtMidi.h>) # include <RtMidi.h> # endif # if __has_include(<rtmidi/RtMidi.h>) # include <rtmidi/RtMidi.h> # endif #endif #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> extern "C" { #include <86box/86box.h> #include <86box/device.h> #include <86box/midi.h> #include <86box/midi_rtmidi.h> #include <86box/ini.h> #include <86box/config.h> #include <86box/plat_unused.h> // Disable c99-designator to avoid the warnings in rtmidi_*_device #ifdef __clang__ # if __has_warning("-Wc99-designator") # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wc99-designator" # endif #endif static RtMidiOut *midiout = nullptr; static RtMidiIn *midiin = nullptr; static int midi_out_id = 0, midi_in_id = 0; static const int midi_lengths[8] = { 3, 3, 3, 3, 2, 2, 3, 1 }; int rtmidi_write(UNUSED(uint8_t val)) { return 0; } void rtmidi_play_msg(uint8_t *msg) { if (midiout) midiout->sendMessage(msg, midi_lengths[(msg[0] >> 4) & 7]); } void rtmidi_play_sysex(uint8_t *sysex, unsigned int len) { if (midiout) midiout->sendMessage(sysex, len); } void * rtmidi_output_init(UNUSED(const device_t *info)) { midi_device_t *dev = (midi_device_t *) malloc(sizeof(midi_device_t)); memset(dev, 0, sizeof(midi_device_t)); dev->play_msg = rtmidi_play_msg; dev->play_sysex = rtmidi_play_sysex; dev->write = rtmidi_write; try { if (!midiout) midiout = new RtMidiOut; } catch (RtMidiError &error) { pclog("Failed to initialize MIDI output: %s\n", error.getMessage().c_str()); return nullptr; } midi_out_id = config_get_int((char *) SYSTEM_MIDI_NAME, (char *) "midi", 0); try { midiout->openPort(midi_out_id); } catch (RtMidiError &error) { pclog("Fallback to default MIDI output port: %s\n", error.getMessage().c_str()); try { midiout->openPort(0); } catch (RtMidiError &error) { pclog("Failed to initialize MIDI output: %s\n", error.getMessage().c_str()); delete midiout; midiout = nullptr; return nullptr; } } midi_out_init(dev); return dev; } void rtmidi_output_close(UNUSED(void *priv)) { if (!midiout) return; midiout->closePort(); delete midiout; midiout = nullptr; midi_out_close(); } int rtmidi_out_get_num_devs(void) { if (!midiout) { try { midiout = new RtMidiOut; } catch (RtMidiError &error) { pclog("Failed to initialize MIDI output: %s\n", error.getMessage().c_str()); } } return midiout ? midiout->getPortCount() : 0; } void rtmidi_out_get_dev_name(int num, char *s) { strcpy(s, midiout->getPortName(num).c_str()); } void rtmidi_input_callback(UNUSED(double timeStamp), std::vector<unsigned char> *message, UNUSED(void *userData)) { if (message->front() == 0xF0) midi_in_sysex(message->data(), message->size()); else midi_in_msg(message->data(), message->size()); } void * rtmidi_input_init(UNUSED(const device_t *info)) { midi_device_t *dev = (midi_device_t *) malloc(sizeof(midi_device_t)); memset(dev, 0, sizeof(midi_device_t)); try { if (!midiin) midiin = new RtMidiIn; } catch (RtMidiError &error) { pclog("Failed to initialize MIDI input: %s\n", error.getMessage().c_str()); return nullptr; } midi_in_id = config_get_int((char *) MIDI_INPUT_NAME, (char *) "midi_input", 0); try { midiin->openPort(midi_in_id); } catch (RtMidiError &error) { pclog("Fallback to default MIDI input port: %s\n", error.getMessage().c_str()); try { midiin->openPort(0); } catch (RtMidiError &error) { pclog("Failed to initialize MIDI input: %s\n", error.getMessage().c_str()); delete midiin; midiin = nullptr; return nullptr; } } midiin->setCallback(&rtmidi_input_callback); // Don't ignore sysex, timing, or active sensing messages. midiin->ignoreTypes(false, false, false); midi_in_init(dev, &midi_in); midi_in->midi_realtime = device_get_config_int("realtime"); midi_in->thruchan = device_get_config_int("thruchan"); midi_in->midi_clockout = device_get_config_int("clockout"); return dev; } void rtmidi_input_close(UNUSED(void *priv)) { midiin->cancelCallback(); midiin->closePort(); delete midiin; midiin = nullptr; midi_out_close(); } int rtmidi_in_get_num_devs(void) { if (!midiin) { try { midiin = new RtMidiIn; } catch (RtMidiError &error) { pclog("Failed to initialize MIDI input: %s\n", error.getMessage().c_str()); } } return midiin ? midiin->getPortCount() : 0; } void rtmidi_in_get_dev_name(int num, char *s) { strcpy(s, midiin->getPortName(num).c_str()); } static const device_config_t system_midi_config[] = { // clang-format off { .name = "midi", .description = "MIDI out device", .type = CONFIG_MIDI_OUT, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; static const device_config_t midi_input_config[] = { // clang-format off { .name = "midi_input", .description = "MIDI in device", .type = CONFIG_MIDI_IN, .default_string = "", .default_int = 0 }, { .name = "realtime", .description = "MIDI Real time", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "thruchan", .description = "MIDI Thru", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "clockout", .description = "MIDI Clockout", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t rtmidi_output_device = { .name = SYSTEM_MIDI_NAME, .internal_name = SYSTEM_MIDI_INTERNAL_NAME, .flags = 0, .local = 0, .init = rtmidi_output_init, .close = rtmidi_output_close, .reset = NULL, { .available = rtmidi_out_get_num_devs }, .speed_changed = NULL, .force_redraw = NULL, .config = system_midi_config }; const device_t rtmidi_input_device = { .name = MIDI_INPUT_NAME, .internal_name = MIDI_INPUT_INTERNAL_NAME, .flags = 0, .local = 0, .init = rtmidi_input_init, .close = rtmidi_input_close, .reset = NULL, { .available = rtmidi_in_get_num_devs }, .speed_changed = NULL, .force_redraw = NULL, .config = midi_input_config }; #ifdef __clang__ # if __has_warning("-Wc99-designator") # pragma clang diagnostic pop # endif #endif } ```
/content/code_sandbox/src/sound/midi_rtmidi.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,084
```c /* * TYPE 0x11: (Washington) * Aztech MMPRO16AB, * Aztech Sound Galaxy Pro 16 AB * Aztech Sound Galaxy Washington 16 * ...and other OEM names * FCC ID I38-MMSN824 and others * * TYPE 0x0C: (Clinton) * Packard Bell FORTE16 * Aztech Sound Galaxy Nova 16 Extra * Aztech Sound Galaxy Clinton 16 * ...and other OEM names * * Also works more or less for drivers of other models with the same chipsets. * * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url * * ============================================================================= * * The CS4248 DSP used is pin and software compatible with the AD1848. * I also have one of these cards with a CS4231. The driver talks to the * emulated card as if it was a CS4231 and I still don't know how to tell the * drivers to see the CS4248. The CS4231 more advanced features are NOT used, * just the new input/output channels. Apparently some drivers are hardcoded * for one or the other, so there is an option for this. * * There is lots more to be learned form the Win95 drivers. The Linux driver is * very straightforward and doesn't do much. * * Recording and voice modes in the windows mixer still do nothing in 86Box, so * this is missing. * * There is a jumper to load the startup configuration from an EEPROM. This is * implemented, so any software-configured parameters will be saved. * * The CD-ROM interface commands are just ignored, along with gameport. * The MPU401 is always enabled. * The OPL3 is always active in some (all?) drivers/cards, so there is no * configuration for this. * * Tested with DOS (driver installation, tools, diagnostics), Win3.1 (driver * installation, tools), Win95 (driver auto-detection), lots of games. * * I consider type 0x11 (Washington) to be very well tested. Type 0x0C (Clinton) * wasn't fully tested, but works well for WSS/Windows. BEWARE that there are * *too many* driver types and OEM versions for each card. Maybe yours isn't * emulated or you have the wrong driver. Some features of each card may work * when using wrong drivers. CODEC selection is also important. * * Any updates to the WSS and SBPROV2 sound cards should be synced here when * appropriate. The WSS was completely cloned here, while the SBPROV2 tends * to call the original functions, except for initialization. * * TODO/Notes: * -Some stuff still not understood on I/O addresses 0x624 and 0x530-0x533. * -Is the CS42xx dither mode used anywhere? Implement. * -What are the voice commands mode in Win95 mixer again? * -Configuration options not present on Aztech's CONFIG.EXE have been commented * out or deleted. Other types of cards with this chipset may need them. * -Sfademo on the Descent CD fails under Win95, works under DOS, see if it * happens on real hardware (and OPL3 stops working after the failure) * -There appears to be some differences in sound volumes bertween MIDI, * SBPROV2, WSS and OPL3? Also check relationship between the SBPROV2 mixer and * the WSS mixer! Are they independent? Current mode selects which mixer? Are * they entangled? * -Check real hardware to see if advanced, mic boost, etc appear in the mixer? * -CD-ROM driver shipped with the card (SGIDECD.SYS) checks for model strings. * I have implemented mine (Aztech CDA 468-02I 4x) in PCem. * -Descent 2 W95 version can't start cd music. Happens on real hardware. * Explanation further below. * -DOSQuake and Descent 2 DOS cd music do not work under Win95. The mode * selects get truncated and send all zeros for output channel selection and * volume, Descent 2 also has excess zeros! This is a PCem bug, happens on all * sound cards. CD audio works in Winquake and Descent 2 DOS setup program. * -DOSQuake CD audio works under DOS with VIDE-CDD.SYS and SGIDECD.SYS. * Descent 2 DOS is still mute but volume selection appears to be working. * Descent 2 fails to launch with SGIDECD.SYS with "Device failed to request * command". SGIDECD.SYS is the CD-ROM driver included with the sound card * drivers. My real CD-ROM drive can't read anything so I can't check the * real behavior of this driver. * -Some cards just have regular IDE ports while other have proprietary ports. * The regular IDE ports just have a option to enable an almost-generic CD-ROM * driver in CONFIG.SYS/AUTOEXEC.BAT (like SGIDECD.SYS) and the onboard port * is enabled/disabled by jumpers. The proprietary ones also have * address/dma/irq settings. Since the configuration options are ignored here, * this behaves like a card with a regular interface disabled by jumper and * the configuration just adds/removes the drivers (which will see other IDE * interfaces present) from the boot process. * -Continue reverse engineering to see if the AZT1605 shares the SB DMA with * WSS or if it is set separately by the TSR loaded on boot. Currently it is * only set by PCem config and then saved to EEPROM (which would make it fixed * if loading from EEPROM too). * -Related to the previous note, part of the SBPROV2 emulation on the CLINTON * family appears to be implemented with a TSR. It's better to remove the TSR * for now. I need to investigate this. Mixer is also weird under DOS (and * wants to save to EEPROM? I don't think the WASHINGTON does this). * -Search for TODO in this file. :-) * * Misc things I use to test for regressions: Windows sounds, Descent under * dos/windows, Descent 2 dos/windows (+ cd music option), Descent 2 W95 + cd * music, Age of Empires (CD + Midi), cd-audio under Windows + volume, * cd-audio under dos + volume, Aztech diagnose.exe, Aztech volset /M:3 then * volset /D, Aztech setmode, mixer (volume + balance) under dos and windows, * DOSQuake under dos and windows (+ cd music and volumes, + Winquake). * * Reason for Descent 2 Win95 CD-Audio not working: * The game calls auxGetNumDevs() to check if any of the AUX devices has * caps.wTechnology == AUXCAPS_CDAUDIO, but this fails because the Aztech * Win95 driver only returns a "Line-In" device. I'm not aware of any other * game that does this and this is completely unnecessary. Other games that * play cd audio correctly have the exact *same* initialization code, minus * this check that only Descent 2 Win95 does. It would work if it just skipped * this check and progressed with calling mciSendCommand() with * mciOpenParms.lpstrDeviceType = "cdaudio", like other games do. There are * some sound cards listed as incompatible in the game's README.TXT file that * are probably due to this. */ #include <math.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/midi.h> #include <86box/timer.h> #include <86box/nvr.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/snd_ad1848.h> #include <86box/snd_azt2316a.h> #include <86box/snd_sb.h> #include <86box/plat_unused.h> /*530, 11, 3 - 530=23*/ /*530, 11, 1 - 530=22*/ /*530, 11, 0 - 530=21*/ /*530, 10, 1 - 530=1a*/ /*530, 10, 0 - 530=19*/ /*530, 9, 1 - 530=12*/ /*530, 7, 1 - 530=0a*/ /*604, 11, 1 - 530=22*/ /*e80, 11, 1 - 530=22*/ /*f40, 11, 1 - 530=22*/ static int azt2316a_wss_dma[4] = { 0, 0, 1, 3 }; static int azt2316a_wss_irq[8] = { 5, 7, 9, 10, 11, 12, 14, 15 }; /* W95 only uses 7-10, others may be wrong */ #if 0 static uint16_t azt2316a_wss_addr[4] = {0x530, 0x604, 0xe80, 0xf40}; #endif typedef struct azt2316a_t { int type; int wss_interrupt_after_config; uint8_t wss_config; uint16_t cur_addr; uint16_t cur_wss_addr; uint16_t cur_mpu401_addr; int cur_irq, cur_dma; int cur_wss_enabled; int cur_wss_irq; int cur_wss_dma; int cur_mpu401_irq; int cur_mpu401_enabled; uint32_t config_word; uint32_t config_word_unlocked; uint8_t cur_mode; ad1848_t ad1848; mpu_t *mpu; sb_t *sb; } azt2316a_t; static uint8_t azt2316a_wss_read(uint16_t addr, void *priv) { const azt2316a_t *azt2316a = (azt2316a_t *) priv; uint8_t temp; /* TODO: when windows is initializing, writing 0x48, 0x58 and 0x60 to 0x530 makes reading from 0x533 return 0x44, but writing 0x50 makes this return 0x04. Why? */ if (addr & 1) temp = 4 | (azt2316a->wss_config & 0x40); else temp = 4 | (azt2316a->wss_config & 0xC0); return temp; } static void azt2316a_wss_write(UNUSED(uint16_t addr), uint8_t val, void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; int interrupt = 0; if (azt2316a->wss_interrupt_after_config) { if ((azt2316a->wss_config & 0x40) && !(val & 0x40)) { // TODO: is this the right edge? interrupt = 1; } } azt2316a->wss_config = val; azt2316a->cur_wss_dma = azt2316a_wss_dma[val & 3]; azt2316a->cur_wss_irq = azt2316a_wss_irq[(val >> 3) & 7]; ad1848_setdma(&azt2316a->ad1848, azt2316a_wss_dma[val & 3]); ad1848_setirq(&azt2316a->ad1848, azt2316a_wss_irq[(val >> 3) & 7]); if (interrupt) picint(1 << azt2316a->cur_wss_irq); } /* generate a config word based on current settings */ static void azt1605_create_config_word(void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; uint32_t temp = 0; /* not implemented / hardcoded */ uint8_t game_enable = 1; uint8_t cd_type = 0; /* TODO: see if the cd-rom was originally connected there on the real machines emulated by 86Box (Packard Bell Legend 100CD, Itautec Infoway Multimidia, etc) */ uint8_t cd_dma8 = -1; uint8_t cd_irq = 0; switch (azt2316a->cur_addr) { case 0x220: // do nothing #if 0 temp += 0 << 0; #endif break; case 0x240: temp += 1 << 0; break; #if 0 case 0x260: // TODO: INVALID? temp += 2 << 0; break; case 0x280: // TODO: INVALID? temp += 3 << 0; break; #endif default: break; } switch (azt2316a->cur_irq) { case 9: temp += 1 << 8; break; case 3: temp += 1 << 9; break; case 5: temp += 1 << 10; break; case 7: temp += 1 << 11; break; default: break; } switch (azt2316a->cur_wss_addr) { case 0x530: // do nothing #if 0 temp += 0 << 16; #endif break; case 0x604: temp += 1 << 16; break; case 0xE80: temp += 2 << 16; break; case 0xF40: temp += 3 << 16; break; default: break; } if (azt2316a->cur_wss_enabled) temp += 1 << 18; if (game_enable) temp += 1 << 4; switch (azt2316a->cur_mpu401_addr) { case 0x300: // do nothing #if 0 temp += 0 << 2; #endif break; case 0x330: temp += 1 << 2; break; default: break; } if (azt2316a->cur_mpu401_enabled) temp += 1 << 3; switch (cd_type) { case 0: /* disabled do nothing temp += 0 << 5; */ break; case 1: // panasonic temp += 1 << 5; break; case 2: // mitsumi/sony/aztech temp += 2 << 5; break; case 3: // all enabled temp += 3 << 5; break; case 4: // unused temp += 4 << 5; break; case 5: // unused temp += 5 << 5; break; case 6: // unused temp += 6 << 5; break; case 7: // unused temp += 7 << 5; break; default: break; } switch (cd_dma8) { case 0xFF: /* -1 do nothing temp += 0 << 22;*/ break; case 0: temp += 1 << 22; break; case 1: temp += 2 << 22; break; case 3: temp += 3 << 22; break; default: break; } switch (azt2316a->cur_mpu401_irq) { case 9: temp += 1 << 12; break; case 3: temp += 1 << 13; break; case 5: temp += 1 << 14; break; case 7: temp += 1 << 15; break; default: break; } switch (cd_irq) { case 0: // disabled // do nothing break; case 11: temp += 1 << 19; break; case 12: temp += 1 << 20; break; case 15: temp += 1 << 21; break; default: break; } azt2316a->config_word = temp; } static void azt2316a_create_config_word(void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; uint32_t temp = 0; /* not implemented / hardcoded */ uint8_t game_enable = 1; uint16_t cd_addr = 0x310; uint8_t cd_type = 0; /* TODO: see if the cd-rom was originally connected there on the real machines emulated by 86Box (Packard Bell Legend 100CD, Itautec Infoway Multimidia, etc) */ uint8_t cd_dma8 = -1; uint8_t cd_dma16 = -1; uint8_t cd_irq = 15; if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { azt1605_create_config_word(priv); return; } switch (azt2316a->cur_addr) { case 0x220: // do nothing #if 0 temp += 0 << 0; #endif break; case 0x240: temp += 1 << 0; break; #if 0 case 0x260: // TODO: INVALID? temp += 2 << 0; break; case 0x280: // TODO: INVALID? temp += 3 << 0; break; #endif default: break; } switch (azt2316a->cur_irq) { case 9: temp += 1 << 2; break; case 5: temp += 1 << 3; break; case 7: temp += 1 << 4; break; case 10: temp += 1 << 5; break; default: break; } switch (azt2316a->cur_dma) { #if 0 // TODO: INVALID? case 0xFF: // -1 // do nothing //temp += 0 << 6; break; #endif case 0: temp += 1 << 6; break; case 1: temp += 2 << 6; break; case 3: temp += 3 << 6; break; default: break; } switch (azt2316a->cur_wss_addr) { case 0x530: // do nothing #if 0 temp += 0 << 8; #endif break; case 0x604: temp += 1 << 8; break; case 0xE80: temp += 2 << 8; break; case 0xF40: temp += 3 << 8; break; default: break; } if (azt2316a->cur_wss_enabled) temp += 1 << 10; if (game_enable) temp += 1 << 11; switch (azt2316a->cur_mpu401_addr) { case 0x300: // do nothing #if 0 temp += 0 << 12; #endif break; case 0x330: temp += 1 << 12; break; default: break; } if (azt2316a->cur_mpu401_enabled) temp += 1 << 13; switch (cd_addr) { case 0x310: // do nothing #if 0 temp += 0 << 14; #endif break; case 0x320: temp += 1 << 14; break; case 0x340: temp += 2 << 14; break; case 0x350: temp += 3 << 14; break; default: break; } switch (cd_type) { case 0: /* disabled */ // do nothing #if 0 temp += 0 << 16; */ #endif break; case 1: /* panasonic */ temp += 1 << 16; break; case 2: /* sony */ temp += 2 << 16; break; case 3: /* mitsumi */ temp += 3 << 16; break; case 4: /* aztech */ temp += 4 << 16; break; case 5: /* unused */ temp += 5 << 16; break; case 6: /* unused */ temp += 6 << 16; break; case 7: /* unused */ temp += 7 << 16; break; default: break; } switch (cd_dma8) { case 0xFF: /* -1 do nothing temp += 0 << 20; */ break; case 0: temp += 1 << 20; break; #if 0 case 1: // TODO: INVALID? temp += 2 << 20; break; #endif case 3: temp += 3 << 20; break; default: break; } switch (cd_dma16) { case 0xFF: /* -1 do nothing temp += 0 << 22; */ break; case 5: temp += 1 << 22; break; case 6: temp += 2 << 22; break; case 7: temp += 3 << 22; break; default: break; } switch (azt2316a->cur_mpu401_irq) { case 9: temp += 1 << 24; break; case 5: temp += 1 << 25; break; case 7: temp += 1 << 26; break; case 10: temp += 1 << 27; break; default: break; } switch (cd_irq) { case 5: temp += 1 << 28; break; case 11: temp += 1 << 29; break; case 12: temp += 1 << 30; break; case 15: temp += 1 << 31; break; default: break; } azt2316a->config_word = temp; } static uint8_t azt2316a_config_read(uint16_t addr, void *priv) { const azt2316a_t *azt2316a = (azt2316a_t *) priv; uint8_t temp = 0; /* Some WSS config here + config change enable bit (setting bit 7 and writing back) */ if (addr == (azt2316a->cur_addr + 0x404)) { /* TODO: what is the real meaning of the read value? I got a mention of bit 0x10 for WSS from disassembling the source code of the driver, and when playing with the I/O ports on real hardware after doing some configuration, but didn't dig into it. Bit 0x08 seems to be a busy flag and generates a timeout (continuous re-reading when initializing windows 98) */ temp = azt2316a->cur_mode ? 0x07 : 0x0F; if (azt2316a->config_word_unlocked) { temp |= 0x80; } } else { // Rest of config. These are documented in the Linux driver. switch (addr & 0x3) { case 0: temp = azt2316a->config_word & 0xFF; break; case 1: temp = (azt2316a->config_word >> 8); break; case 2: temp = (azt2316a->config_word >> 16); break; case 3: temp = (azt2316a->config_word >> 24); break; default: break; } } return temp; } static void azt1605_config_write(uint16_t addr, uint8_t val, void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; uint8_t temp; if (addr == (azt2316a->cur_addr + 0x404)) { if (val & 0x80) azt2316a->config_word_unlocked = 1; else azt2316a->config_word_unlocked = 0; } else if (azt2316a->config_word_unlocked) { if (val == 0xFF) { /* TODO: check if this still happens on eeprom.sys after having more complete emulation! */ return; } switch (addr & 3) { case 0: azt2316a->config_word = (azt2316a->config_word & 0xFFFFFF00) | val; temp = val & 3; if (temp == 0) azt2316a->cur_addr = 0x220; else if (temp == 1) azt2316a->cur_addr = 0x240; #if 0 else if (temp == 2) azt2316a->cur_addr = 0x260; // TODO: INVALID else if (temp == 3) azt2316a->cur_addr = 0x280; // TODO: INVALID #endif if (val & 0x4) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; if (val & 0x8) azt2316a->cur_mpu401_enabled = 1; else azt2316a->cur_mpu401_enabled = 0; break; case 1: azt2316a->config_word = (azt2316a->config_word & 0xFFFF00FF) | (val << 8); if (val & 0x1) azt2316a->cur_irq = 9; else if (val & 0x2) azt2316a->cur_irq = 3; else if (val & 0x4) azt2316a->cur_irq = 5; else if (val & 0x8) azt2316a->cur_irq = 7; /* else undefined? */ if (val & 0x10) azt2316a->cur_mpu401_irq = 9; else if (val & 0x20) azt2316a->cur_mpu401_irq = 3; else if (val & 0x40) azt2316a->cur_mpu401_irq = 5; else if (val & 0x80) azt2316a->cur_mpu401_irq = 7; /* else undefined? */ break; case 2: azt2316a->config_word = (azt2316a->config_word & 0xFF00FFFF) | (val << 16); io_removehandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_removehandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); temp = val & 0x3; if (temp == 0) azt2316a->cur_wss_addr = 0x530; else if (temp == 1) azt2316a->cur_wss_addr = 0x604; else if (temp == 2) azt2316a->cur_wss_addr = 0xE80; else if (temp == 3) azt2316a->cur_wss_addr = 0xF40; io_sethandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); /* no actual effect */ if (val & 0x4) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; break; case 3: break; default: break; } /* update sbprov2 configs */ sb_dsp_setaddr(&azt2316a->sb->dsp, azt2316a->cur_addr); sb_dsp_setirq(&azt2316a->sb->dsp, azt2316a->cur_irq); sb_dsp_setdma8(&azt2316a->sb->dsp, azt2316a->cur_dma); mpu401_change_addr(azt2316a->mpu, azt2316a->cur_mpu401_addr); mpu401_setirq(azt2316a->mpu, azt2316a->cur_mpu401_irq); } } static void azt2316a_config_write(uint16_t addr, uint8_t val, void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; uint8_t temp; if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { azt1605_config_write(addr, val, azt2316a); return; } if (addr == (azt2316a->cur_addr + 0x404)) { if (val & 0x80) azt2316a->config_word_unlocked = 1; else azt2316a->config_word_unlocked = 0; } else if (azt2316a->config_word_unlocked) { if (val == 0xFF) // TODO: check if this still happens on eeprom.sys after having more complete emulation! return; switch (addr & 3) { case 0: azt2316a->config_word = (azt2316a->config_word & 0xFFFFFF00) | val; temp = val & 3; if (temp == 0) azt2316a->cur_addr = 0x220; else if (temp == 1) azt2316a->cur_addr = 0x240; if (val & 0x4) azt2316a->cur_irq = 9; else if (val & 0x8) azt2316a->cur_irq = 5; else if (val & 0x10) azt2316a->cur_irq = 7; else if (val & 0x20) azt2316a->cur_irq = 10; temp = (val >> 6) & 3; if (temp == 1) azt2316a->cur_dma = 0; else if (temp == 2) azt2316a->cur_dma = 1; else if (temp == 3) azt2316a->cur_dma = 3; break; case 1: azt2316a->config_word = (azt2316a->config_word & 0xFFFF00FF) | (val << 8); io_removehandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_removehandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); temp = val & 0x3; if (temp == 0) azt2316a->cur_wss_addr = 0x530; else if (temp == 1) azt2316a->cur_wss_addr = 0x604; else if (temp == 2) azt2316a->cur_wss_addr = 0xE80; else if (temp == 3) azt2316a->cur_wss_addr = 0xF40; io_sethandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); /* no actual effect */ if (val & 0x4) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; if (val & 0x10) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; if (val & 0x20) azt2316a->cur_mpu401_enabled = 1; else azt2316a->cur_mpu401_enabled = 0; break; case 2: azt2316a->config_word = (azt2316a->config_word & 0xFF00FFFF) | (val << 16); break; case 3: azt2316a->config_word = (azt2316a->config_word & 0x00FFFFFF) | (val << 24); if (val & 0x1) azt2316a->cur_mpu401_irq = 9; else if (val & 0x2) azt2316a->cur_mpu401_irq = 5; else if (val & 0x4) azt2316a->cur_mpu401_irq = 7; else if (val & 0x8) azt2316a->cur_mpu401_irq = 10; /* else undefined? */ break; default: break; } /* update sbprov2 configs */ sb_dsp_setaddr(&azt2316a->sb->dsp, azt2316a->cur_addr); sb_dsp_setirq(&azt2316a->sb->dsp, azt2316a->cur_irq); sb_dsp_setdma8(&azt2316a->sb->dsp, azt2316a->cur_dma); mpu401_change_addr(azt2316a->mpu, azt2316a->cur_mpu401_addr); mpu401_setirq(azt2316a->mpu, azt2316a->cur_mpu401_irq); } } /* How it behaves when one or another is activated may affect games auto-detecting (and will also use more of the limited system resources!) */ void azt2316a_enable_wss(uint8_t enable, void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; if (enable) azt2316a->cur_mode = 1; else azt2316a->cur_mode = 0; } static void azt2316a_get_buffer(int32_t *buffer, int len, void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; /* wss part */ ad1848_update(&azt2316a->ad1848); for (int c = 0; c < len * 2; c++) buffer[c] += (azt2316a->ad1848.buffer[c] / 2); azt2316a->ad1848.pos = 0; /* sbprov2 part */ sb_get_buffer_sbpro(buffer, len, azt2316a->sb); } static void * azt_init(const device_t *info) { FILE *fp; char *fn = NULL; int i; int loaded_from_eeprom = 0; uint16_t addr_setting; uint8_t read_eeprom[AZTECH_EEPROM_SIZE]; azt2316a_t *azt2316a = malloc(sizeof(azt2316a_t)); memset(azt2316a, 0, sizeof(azt2316a_t)); azt2316a->type = info->local; if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { fn = "azt1605.nvr"; } else if (azt2316a->type == SB_SUBTYPE_CLONE_AZT2316A_0X11) { fn = "azt2316a.nvr"; } /* config */ fp = nvr_fopen(fn, "rb"); if (fp) { uint8_t checksum = 0x7f; uint8_t saved_checksum; size_t res; res = fread(read_eeprom, AZTECH_EEPROM_SIZE, 1, fp); for (i = 0; i < AZTECH_EEPROM_SIZE; i++) checksum += read_eeprom[i]; res = fread(&saved_checksum, sizeof(saved_checksum), 1, fp); (void) res; fclose(fp); if (checksum == saved_checksum) loaded_from_eeprom = 1; } if (!loaded_from_eeprom) { if (azt2316a->type == SB_SUBTYPE_CLONE_AZT2316A_0X11) { read_eeprom[0] = 0x00; read_eeprom[1] = 0x00; read_eeprom[2] = 0x00; read_eeprom[3] = 0x00; read_eeprom[4] = 0x00; read_eeprom[5] = 0x00; read_eeprom[6] = 0x00; read_eeprom[7] = 0x00; read_eeprom[8] = 0x00; read_eeprom[9] = 0x00; read_eeprom[10] = 0x00; read_eeprom[11] = 0x88; read_eeprom[12] = 0xbc; read_eeprom[13] = 0x00; read_eeprom[14] = 0x01; read_eeprom[15] = 0x00; } else if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { read_eeprom[0] = 0x80; read_eeprom[1] = 0x80; read_eeprom[2] = 0x9F; read_eeprom[3] = 0x13; read_eeprom[4] = 0x16; read_eeprom[5] = 0x13; read_eeprom[6] = 0x00; read_eeprom[7] = 0x00; read_eeprom[8] = 0x16; read_eeprom[9] = 0x0B; read_eeprom[10] = 0x06; read_eeprom[11] = 0x01; read_eeprom[12] = 0x1C; read_eeprom[13] = 0x14; read_eeprom[14] = 0x04; read_eeprom[15] = 0x1C; } } if (azt2316a->type == SB_SUBTYPE_CLONE_AZT2316A_0X11) { azt2316a->config_word = read_eeprom[11] | (read_eeprom[12] << 8) | (read_eeprom[13] << 16) | (read_eeprom[14] << 24); switch (azt2316a->config_word & (3 << 0)) { case 0: azt2316a->cur_addr = 0x220; break; case 1: azt2316a->cur_addr = 0x240; break; default: fatal("AZT2316A: invalid sb addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 2)) azt2316a->cur_irq = 9; else if (azt2316a->config_word & (1 << 3)) azt2316a->cur_irq = 5; else if (azt2316a->config_word & (1 << 4)) azt2316a->cur_irq = 7; else if (azt2316a->config_word & (1 << 5)) azt2316a->cur_irq = 10; else fatal("AZT2316A: invalid sb irq in config word %08X\n", azt2316a->config_word); switch (azt2316a->config_word & (3 << 6)) { case 1 << 6: azt2316a->cur_dma = 0; break; case 2 << 6: azt2316a->cur_dma = 1; break; case 3 << 6: azt2316a->cur_dma = 3; break; default: fatal("AZT2316A: invalid sb dma in config word %08X\n", azt2316a->config_word); } switch (azt2316a->config_word & (3 << 8)) { case 0: azt2316a->cur_wss_addr = 0x530; break; case 1 << 8: azt2316a->cur_wss_addr = 0x604; break; case 2 << 8: azt2316a->cur_wss_addr = 0xE80; break; case 3 << 8: azt2316a->cur_wss_addr = 0xF40; break; default: fatal("AZT2316A: invalid wss addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 10)) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; if (azt2316a->config_word & (1 << 12)) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; if (azt2316a->config_word & (1 << 13)) azt2316a->cur_mpu401_enabled = 1; else azt2316a->cur_mpu401_enabled = 0; if (azt2316a->config_word & (1 << 24)) azt2316a->cur_mpu401_irq = 9; else if (azt2316a->config_word & (1 << 25)) azt2316a->cur_mpu401_irq = 5; else if (azt2316a->config_word & (1 << 26)) azt2316a->cur_mpu401_irq = 7; else if (azt2316a->config_word & (1 << 27)) azt2316a->cur_mpu401_irq = 10; else fatal("AZT2316A: invalid mpu401 irq in config word %08X\n", azt2316a->config_word); /* these are not present on the EEPROM */ azt2316a->cur_wss_irq = device_get_config_int("wss_irq"); azt2316a->cur_wss_dma = device_get_config_int("wss_dma"); azt2316a->cur_mode = 0; } else if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { azt2316a->config_word = read_eeprom[12] + (read_eeprom[13] << 8) + (read_eeprom[14] << 16); switch (azt2316a->config_word & (3 << 0)) { case 0: azt2316a->cur_addr = 0x220; break; case 1: azt2316a->cur_addr = 0x240; break; default: fatal("AZT1605: invalid sb addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 2)) azt2316a->cur_mpu401_addr = 0x330; else azt2316a->cur_mpu401_addr = 0x300; if (azt2316a->config_word & (1 << 3)) azt2316a->cur_mpu401_enabled = 1; else azt2316a->cur_mpu401_enabled = 0; if (azt2316a->config_word & (1 << 8)) azt2316a->cur_irq = 9; else if (azt2316a->config_word & (1 << 9)) azt2316a->cur_irq = 3; else if (azt2316a->config_word & (1 << 10)) azt2316a->cur_irq = 5; else if (azt2316a->config_word & (1 << 11)) azt2316a->cur_irq = 7; else fatal("AZT1605: invalid sb irq in config word %08X\n", azt2316a->config_word); if (azt2316a->config_word & (1 << 12)) azt2316a->cur_mpu401_irq = 9; else if (azt2316a->config_word & (1 << 13)) azt2316a->cur_mpu401_irq = 3; else if (azt2316a->config_word & (1 << 14)) azt2316a->cur_mpu401_irq = 5; else if (azt2316a->config_word & (1 << 15)) azt2316a->cur_mpu401_irq = 7; else fatal("AZT1605: invalid mpu401 irq in config word %08X\n", azt2316a->config_word); switch (azt2316a->config_word & (3 << 16)) { case 0: azt2316a->cur_wss_addr = 0x530; break; case 1 << 16: azt2316a->cur_wss_addr = 0x604; break; case 2 << 16: azt2316a->cur_wss_addr = 0xE80; break; case 3 << 16: azt2316a->cur_wss_addr = 0xF40; break; default: fatal("AZT1605: invalid wss addr in config word %08X\n", azt2316a->config_word); } if (azt2316a->config_word & (1 << 18)) azt2316a->cur_wss_enabled = 1; else azt2316a->cur_wss_enabled = 0; // these are not present on the EEPROM azt2316a->cur_dma = device_get_config_int("sb_dma8"); // TODO: investigate TSR to make this work with it - there is no software configurable DMA8? azt2316a->cur_wss_irq = device_get_config_int("wss_irq"); azt2316a->cur_wss_dma = device_get_config_int("wss_dma"); azt2316a->cur_mode = 0; } addr_setting = device_get_config_hex16("addr"); if (addr_setting) azt2316a->cur_addr = addr_setting; azt2316a->wss_interrupt_after_config = device_get_config_int("wss_interrupt_after_config"); /* wss part */ ad1848_init(&azt2316a->ad1848, device_get_config_int("codec")); ad1848_setirq(&azt2316a->ad1848, azt2316a->cur_wss_irq); ad1848_setdma(&azt2316a->ad1848, azt2316a->cur_wss_dma); io_sethandler(azt2316a->cur_addr + 0x0400, 0x0040, azt2316a_config_read, NULL, NULL, azt2316a_config_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr, 0x0004, azt2316a_wss_read, NULL, NULL, azt2316a_wss_write, NULL, NULL, azt2316a); io_sethandler(azt2316a->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &azt2316a->ad1848); /* sbprov2 part */ /*sbpro port mappings. 220h or 240h. 2x0 to 2x3 -> FM chip (18 voices) 2x4 to 2x5 -> Mixer interface 2x6, 2xA, 2xC, 2xE -> DSP chip 2x8, 2x9, 388 and 389 FM chip (9 voices).*/ azt2316a->sb = malloc(sizeof(sb_t)); memset(azt2316a->sb, 0, sizeof(sb_t)); azt2316a->sb->opl_enabled = device_get_config_int("opl"); for (i = 0; i < AZTECH_EEPROM_SIZE; i++) azt2316a->sb->dsp.azt_eeprom[i] = read_eeprom[i]; if (azt2316a->sb->opl_enabled) fm_driver_get(FM_YMF262, &azt2316a->sb->opl); sb_dsp_set_real_opl(&azt2316a->sb->dsp, 1); sb_dsp_init(&azt2316a->sb->dsp, SBPRO2, azt2316a->type, azt2316a); sb_dsp_setaddr(&azt2316a->sb->dsp, azt2316a->cur_addr); sb_dsp_setirq(&azt2316a->sb->dsp, azt2316a->cur_irq); sb_dsp_setdma8(&azt2316a->sb->dsp, azt2316a->cur_dma); sb_ct1345_mixer_reset(azt2316a->sb); /* DSP I/O handler is activated in sb_dsp_setaddr */ if (azt2316a->sb->opl_enabled) { io_sethandler(azt2316a->cur_addr + 0, 0x0004, azt2316a->sb->opl.read, NULL, NULL, azt2316a->sb->opl.write, NULL, NULL, azt2316a->sb->opl.priv); io_sethandler(azt2316a->cur_addr + 8, 0x0002, azt2316a->sb->opl.read, NULL, NULL, azt2316a->sb->opl.write, NULL, NULL, azt2316a->sb->opl.priv); io_sethandler(0x0388, 0x0004, azt2316a->sb->opl.read, NULL, NULL, azt2316a->sb->opl.write, NULL, NULL, azt2316a->sb->opl.priv); } io_sethandler(azt2316a->cur_addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, azt2316a->sb); azt2316a_create_config_word(azt2316a); sound_add_handler(azt2316a_get_buffer, azt2316a); if (azt2316a->sb->opl_enabled) music_add_handler(sb_get_music_buffer_sbpro, azt2316a->sb); sound_set_cd_audio_filter(sbpro_filter_cd_audio, azt2316a->sb); if (azt2316a->cur_mpu401_enabled) { azt2316a->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(azt2316a->mpu, 0, sizeof(mpu_t)); mpu401_init(azt2316a->mpu, azt2316a->cur_mpu401_addr, azt2316a->cur_mpu401_irq, M_UART, device_get_config_int("receive_input401")); } else azt2316a->mpu = NULL; if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &azt2316a->sb->dsp); return azt2316a; } static void azt_close(void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; char *fn = NULL; FILE *fp; uint8_t checksum = 0x7f; if (azt2316a->type == SB_SUBTYPE_CLONE_AZT1605_0X0C) { fn = "azt1605.nvr"; } else if (azt2316a->type == SB_SUBTYPE_CLONE_AZT2316A_0X11) { fn = "azt2316a.nvr"; } /* always save to eeprom (recover from bad values) */ fp = nvr_fopen(fn, "wb"); if (fp) { for (uint8_t i = 0; i < AZTECH_EEPROM_SIZE; i++) checksum += azt2316a->sb->dsp.azt_eeprom[i]; fwrite(azt2316a->sb->dsp.azt_eeprom, AZTECH_EEPROM_SIZE, 1, fp); // TODO: confirm any models saving mixer settings to EEPROM and implement reading back // TODO: should remember to save wss duplex setting if 86Box has voice recording implemented in the future? Also, default azt2316a->wss_config // TODO: azt2316a->cur_mode is not saved to EEPROM? fwrite(&checksum, sizeof(checksum), 1, fp); fclose(fp); } sb_close(azt2316a->sb); free(azt2316a->mpu); free(azt2316a); } static void azt_speed_changed(void *priv) { azt2316a_t *azt2316a = (azt2316a_t *) priv; ad1848_speed_changed(&azt2316a->ad1848); sb_speed_changed(azt2316a->sb); } static const device_config_t azt1605_config[] = { // clang-format off { .name = "codec", .description = "CODEC", .type = CONFIG_SELECTION, .selection = { { .description = "CS4248", .value = AD1848_TYPE_CS4248 }, { .description = "CS4231", .value = AD1848_TYPE_CS4231 }, }, .default_int = AD1848_TYPE_CS4248 }, { .name = "wss_interrupt_after_config", .description = "Raise CODEC interrupt on CODEC setup (needed by some drivers)", .type = CONFIG_BINARY, .default_int = 0 }, { .name = "addr", .description = "SB Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "Use EEPROM setting", .value = 0 }, { .description = "" } } }, { .name = "sb_dma8", .description = "SB low DMA", .type = CONFIG_SELECTION, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } }, .default_int = 1 }, { .name = "wss_irq", .description = "WSS IRQ", .type = CONFIG_SELECTION, .selection = { { .description = "IRQ 11", .value = 11 }, { .description = "IRQ 10", .value = 10 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } }, .default_int = 10 }, { .name = "wss_dma", .description = "WSS DMA", .type = CONFIG_SELECTION, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } }, .default_int = 0 }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input", .description = "Receive input (SB MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; static const device_config_t azt2316a_config[] = { // clang-format off { .name = "codec", .description = "CODEC", .type = CONFIG_SELECTION, .selection = { { .description = "CS4248", .value = AD1848_TYPE_CS4248 }, { .description = "CS4231", .value = AD1848_TYPE_CS4231 }, }, .default_int = AD1848_TYPE_CS4248 }, { .name = "wss_interrupt_after_config", .description = "Raise CODEC interrupt on CODEC setup (needed by some drivers)", .type = CONFIG_BINARY, .default_int = 0 }, { .name = "addr", .description = "SB Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x220", .value = 0x220 }, { .description = "0x240", .value = 0x240 }, { .description = "Use EEPROM setting", .value = 0 }, { .description = "" } } }, { .name = "wss_irq", .description = "WSS IRQ", .type = CONFIG_SELECTION, .selection = { { .description = "IRQ 11", .value = 11 }, { .description = "IRQ 10", .value = 10 }, { .description = "IRQ 7", .value = 7 }, { .description = "" } }, .default_int = 10 }, { .name = "wss_dma", .description = "WSS DMA", .type = CONFIG_SELECTION, .selection = { { .description = "DMA 0", .value = 0 }, { .description = "DMA 1", .value = 1 }, { .description = "DMA 3", .value = 3 }, { .description = "" } }, .default_int = 0 }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input", .description = "Receive input (SB MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t azt2316a_device = { .name = "Aztech Sound Galaxy Pro 16 AB (Washington)", .internal_name = "azt2316a", .flags = DEVICE_ISA | DEVICE_AT, .local = SB_SUBTYPE_CLONE_AZT2316A_0X11, .init = azt_init, .close = azt_close, .reset = NULL, { .available = NULL }, .speed_changed = azt_speed_changed, .force_redraw = NULL, .config = azt2316a_config }; const device_t azt1605_device = { .name = "Aztech Sound Galaxy Nova 16 Extra (Clinton)", .internal_name = "azt1605", .flags = DEVICE_ISA | DEVICE_AT, .local = SB_SUBTYPE_CLONE_AZT1605_0X0C, .init = azt_init, .close = azt_close, .reset = NULL, { .available = NULL }, .speed_changed = azt_speed_changed, .force_redraw = NULL, .config = azt1605_config }; ```
/content/code_sandbox/src/sound/snd_azt2316a.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
14,599
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Nuked OPL3 emulator. * * Thanks: * MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): * Feedback and Rhythm part calculation information. * forums.submarine.org.uk(carbon14, opl3): * Tremolo and phase generator calculation information. * OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): * OPL2 ROMs. * siliconpr0n.org(John McMaster, digshadow): * YMF262 and VRC VII decaps and die shots. * * Version: 1.8 * * Translation from C++ into C done by Miran Grca. * * **TODO** The OPL3 is a stereo chip, and, thus, always generates * a two-sample stream of data, for the L and R channels, * in that order. The OPL2, however, is mono. What should * we generate for that? * * Version: @(#)snd_opl_nuked.c 1.0.5 2020/07/16 * * Authors: Fred N. van Kempen, <decwiz@yahoo.com> * Miran Grca, <mgrca8@gmail.com> * Alexey Khokholov (Nuke.YKT) * */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/device.h> #include <86box/snd_opl.h> #include <86box/snd_opl_nuked.h> #if OPL_ENABLE_STEREOEXT && !defined OPL_SIN #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES 1 #endif #include <math.h> // input: [0, 256), output: [0, 65536] #define OPL_SIN(x) ((int32_t)(sin((x) * M_PI / 512.0) * 65536.0)) #endif /* Quirk: Some FM channels are output one sample later on the left side than the right. */ #ifndef OPL_QUIRK_CHANNELSAMPLEDELAY #define OPL_QUIRK_CHANNELSAMPLEDELAY (!OPL_ENABLE_STEREOEXT) #endif #define RSM_FRAC 10 // #define OPL_FREQ FREQ_48000 #define OPL_FREQ FREQ_49716 // Channel types enum { ch_2op = 0, ch_4op = 1, ch_4op2 = 2, ch_drum = 3 }; // Envelope key types enum { egk_norm = 0x01, egk_drum = 0x02 }; #ifdef ENABLE_OPL_LOG int nuked_do_log = ENABLE_OPL_LOG; static void nuked_log(const char *fmt, ...) { va_list ap; if (nuked_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define nuked_log(fmt, ...) #endif // logsin table static const uint16_t logsinrom[256] = { 0x859, 0x6c3, 0x607, 0x58b, 0x52e, 0x4e4, 0x4a6, 0x471, 0x443, 0x41a, 0x3f5, 0x3d3, 0x3b5, 0x398, 0x37e, 0x365, 0x34e, 0x339, 0x324, 0x311, 0x2ff, 0x2ed, 0x2dc, 0x2cd, 0x2bd, 0x2af, 0x2a0, 0x293, 0x286, 0x279, 0x26d, 0x261, 0x256, 0x24b, 0x240, 0x236, 0x22c, 0x222, 0x218, 0x20f, 0x206, 0x1fd, 0x1f5, 0x1ec, 0x1e4, 0x1dc, 0x1d4, 0x1cd, 0x1c5, 0x1be, 0x1b7, 0x1b0, 0x1a9, 0x1a2, 0x19b, 0x195, 0x18f, 0x188, 0x182, 0x17c, 0x177, 0x171, 0x16b, 0x166, 0x160, 0x15b, 0x155, 0x150, 0x14b, 0x146, 0x141, 0x13c, 0x137, 0x133, 0x12e, 0x129, 0x125, 0x121, 0x11c, 0x118, 0x114, 0x10f, 0x10b, 0x107, 0x103, 0x0ff, 0x0fb, 0x0f8, 0x0f4, 0x0f0, 0x0ec, 0x0e9, 0x0e5, 0x0e2, 0x0de, 0x0db, 0x0d7, 0x0d4, 0x0d1, 0x0cd, 0x0ca, 0x0c7, 0x0c4, 0x0c1, 0x0be, 0x0bb, 0x0b8, 0x0b5, 0x0b2, 0x0af, 0x0ac, 0x0a9, 0x0a7, 0x0a4, 0x0a1, 0x09f, 0x09c, 0x099, 0x097, 0x094, 0x092, 0x08f, 0x08d, 0x08a, 0x088, 0x086, 0x083, 0x081, 0x07f, 0x07d, 0x07a, 0x078, 0x076, 0x074, 0x072, 0x070, 0x06e, 0x06c, 0x06a, 0x068, 0x066, 0x064, 0x062, 0x060, 0x05e, 0x05c, 0x05b, 0x059, 0x057, 0x055, 0x053, 0x052, 0x050, 0x04e, 0x04d, 0x04b, 0x04a, 0x048, 0x046, 0x045, 0x043, 0x042, 0x040, 0x03f, 0x03e, 0x03c, 0x03b, 0x039, 0x038, 0x037, 0x035, 0x034, 0x033, 0x031, 0x030, 0x02f, 0x02e, 0x02d, 0x02b, 0x02a, 0x029, 0x028, 0x027, 0x026, 0x025, 0x024, 0x023, 0x022, 0x021, 0x020, 0x01f, 0x01e, 0x01d, 0x01c, 0x01b, 0x01a, 0x019, 0x018, 0x017, 0x017, 0x016, 0x015, 0x014, 0x014, 0x013, 0x012, 0x011, 0x011, 0x010, 0x00f, 0x00f, 0x00e, 0x00d, 0x00d, 0x00c, 0x00c, 0x00b, 0x00a, 0x00a, 0x009, 0x009, 0x008, 0x008, 0x007, 0x007, 0x007, 0x006, 0x006, 0x005, 0x005, 0x005, 0x004, 0x004, 0x004, 0x003, 0x003, 0x003, 0x002, 0x002, 0x002, 0x002, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000 }; // exp table static const uint16_t exprom[256] = { 0x7fa, 0x7f5, 0x7ef, 0x7ea, 0x7e4, 0x7df, 0x7da, 0x7d4, 0x7cf, 0x7c9, 0x7c4, 0x7bf, 0x7b9, 0x7b4, 0x7ae, 0x7a9, 0x7a4, 0x79f, 0x799, 0x794, 0x78f, 0x78a, 0x784, 0x77f, 0x77a, 0x775, 0x770, 0x76a, 0x765, 0x760, 0x75b, 0x756, 0x751, 0x74c, 0x747, 0x742, 0x73d, 0x738, 0x733, 0x72e, 0x729, 0x724, 0x71f, 0x71a, 0x715, 0x710, 0x70b, 0x706, 0x702, 0x6fd, 0x6f8, 0x6f3, 0x6ee, 0x6e9, 0x6e5, 0x6e0, 0x6db, 0x6d6, 0x6d2, 0x6cd, 0x6c8, 0x6c4, 0x6bf, 0x6ba, 0x6b5, 0x6b1, 0x6ac, 0x6a8, 0x6a3, 0x69e, 0x69a, 0x695, 0x691, 0x68c, 0x688, 0x683, 0x67f, 0x67a, 0x676, 0x671, 0x66d, 0x668, 0x664, 0x65f, 0x65b, 0x657, 0x652, 0x64e, 0x649, 0x645, 0x641, 0x63c, 0x638, 0x634, 0x630, 0x62b, 0x627, 0x623, 0x61e, 0x61a, 0x616, 0x612, 0x60e, 0x609, 0x605, 0x601, 0x5fd, 0x5f9, 0x5f5, 0x5f0, 0x5ec, 0x5e8, 0x5e4, 0x5e0, 0x5dc, 0x5d8, 0x5d4, 0x5d0, 0x5cc, 0x5c8, 0x5c4, 0x5c0, 0x5bc, 0x5b8, 0x5b4, 0x5b0, 0x5ac, 0x5a8, 0x5a4, 0x5a0, 0x59c, 0x599, 0x595, 0x591, 0x58d, 0x589, 0x585, 0x581, 0x57e, 0x57a, 0x576, 0x572, 0x56f, 0x56b, 0x567, 0x563, 0x560, 0x55c, 0x558, 0x554, 0x551, 0x54d, 0x549, 0x546, 0x542, 0x53e, 0x53b, 0x537, 0x534, 0x530, 0x52c, 0x529, 0x525, 0x522, 0x51e, 0x51b, 0x517, 0x514, 0x510, 0x50c, 0x509, 0x506, 0x502, 0x4ff, 0x4fb, 0x4f8, 0x4f4, 0x4f1, 0x4ed, 0x4ea, 0x4e7, 0x4e3, 0x4e0, 0x4dc, 0x4d9, 0x4d6, 0x4d2, 0x4cf, 0x4cc, 0x4c8, 0x4c5, 0x4c2, 0x4be, 0x4bb, 0x4b8, 0x4b5, 0x4b1, 0x4ae, 0x4ab, 0x4a8, 0x4a4, 0x4a1, 0x49e, 0x49b, 0x498, 0x494, 0x491, 0x48e, 0x48b, 0x488, 0x485, 0x482, 0x47e, 0x47b, 0x478, 0x475, 0x472, 0x46f, 0x46c, 0x469, 0x466, 0x463, 0x460, 0x45d, 0x45a, 0x457, 0x454, 0x451, 0x44e, 0x44b, 0x448, 0x445, 0x442, 0x43f, 0x43c, 0x439, 0x436, 0x433, 0x430, 0x42d, 0x42a, 0x428, 0x425, 0x422, 0x41f, 0x41c, 0x419, 0x416, 0x414, 0x411, 0x40e, 0x40b, 0x408, 0x406, 0x403, 0x400 }; // freq mult table multiplied by 2 // // 1/2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 12, 15, 15 static const uint8_t mt[16] = { 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30 }; // ksl table static const uint8_t kslrom[16] = { 0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64 }; static const uint8_t kslshift[4] = { 8, 1, 2, 0 }; // envelope generator constants static const uint8_t eg_incstep[4][4] = { { 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 } }; // address decoding static const int8_t ad_slot[0x20] = { 0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static const uint8_t ch_slot[18] = { 0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20, 24, 25, 26, 30, 31, 32 }; #if OPL_ENABLE_STEREOEXT /* stereo extension panning table */ static int32_t panpot_lut[256]; static uint8_t panpot_lut_build = 0; #endif // Envelope generator typedef int16_t (*envelope_sinfunc)(uint16_t phase, uint16_t envelope); typedef void (*envelope_genfunc)(opl3_slot *slot); static int16_t OPL3_EnvelopeCalcExp(uint32_t level) { if (level > 0x1fff) level = 0x1fff; return ((exprom[level & 0xffu] << 1) >> (level >> 8)); } static int16_t OPL3_EnvelopeCalcSin0(uint16_t phase, uint16_t envelope) { uint16_t out = 0; uint16_t neg = 0; phase &= 0x3ff; if (phase & 0x0200) neg = 0xffff; if (phase & 0x0100) out = logsinrom[(phase & 0xffu) ^ 0xffu]; else out = logsinrom[phase & 0xffu]; return (OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg); } static int16_t OPL3_EnvelopeCalcSin1(uint16_t phase, uint16_t envelope) { uint16_t out = 0; phase &= 0x3ff; if (phase & 0x0200) out = 0x1000; else if (phase & 0x0100) out = logsinrom[(phase & 0xffu) ^ 0xffu]; else out = logsinrom[phase & 0xffu]; return (OPL3_EnvelopeCalcExp(out + (envelope << 3))); } static int16_t OPL3_EnvelopeCalcSin2(uint16_t phase, uint16_t envelope) { uint16_t out = 0; phase &= 0x03ff; if (phase & 0x0100) out = logsinrom[(phase & 0xffu) ^ 0xffu]; else out = logsinrom[phase & 0xffu]; return (OPL3_EnvelopeCalcExp(out + (envelope << 3))); } static int16_t OPL3_EnvelopeCalcSin3(uint16_t phase, uint16_t envelope) { uint16_t out = 0; phase &= 0x03ff; if (phase & 0x0100) out = 0x1000; else out = logsinrom[phase & 0xffu]; return (OPL3_EnvelopeCalcExp(out + (envelope << 3))); } static int16_t OPL3_EnvelopeCalcSin4(uint16_t phase, uint16_t envelope) { uint16_t out = 0; uint16_t neg = 0; phase &= 0x03ff; if ((phase & 0x0300) == 0x0100) neg = 0xffff; if (phase & 0x0200) out = 0x1000; else if (phase & 0x80) out = logsinrom[((phase ^ 0xffu) << 1u) & 0xffu]; else out = logsinrom[(phase << 1u) & 0xffu]; return (OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg); } static int16_t OPL3_EnvelopeCalcSin5(uint16_t phase, uint16_t envelope) { uint16_t out = 0; phase &= 0x03ff; if (phase & 0x0200) out = 0x1000; else if (phase & 0x80) out = logsinrom[((phase ^ 0xffu) << 1u) & 0xffu]; else out = logsinrom[(phase << 1u) & 0xffu]; return (OPL3_EnvelopeCalcExp(out + (envelope << 3))); } static int16_t OPL3_EnvelopeCalcSin6(uint16_t phase, uint16_t envelope) { uint16_t neg = 0; phase &= 0x03ff; if (phase & 0x0200) neg = 0xffff; return (OPL3_EnvelopeCalcExp(envelope << 3) ^ neg); } static int16_t OPL3_EnvelopeCalcSin7(uint16_t phase, uint16_t envelope) { uint16_t out = 0; uint16_t neg = 0; phase &= 0x03ff; if (phase & 0x0200) { neg = 0xffff; phase = (phase & 0x01ff) ^ 0x01ff; } out = phase << 3; return (OPL3_EnvelopeCalcExp(out + (envelope << 3)) ^ neg); } static const envelope_sinfunc envelope_sin[8] = { OPL3_EnvelopeCalcSin0, OPL3_EnvelopeCalcSin1, OPL3_EnvelopeCalcSin2, OPL3_EnvelopeCalcSin3, OPL3_EnvelopeCalcSin4, OPL3_EnvelopeCalcSin5, OPL3_EnvelopeCalcSin6, OPL3_EnvelopeCalcSin7 }; enum envelope_gen_num { envelope_gen_num_attack = 0, envelope_gen_num_decay = 1, envelope_gen_num_sustain = 2, envelope_gen_num_release = 3 }; static void OPL3_EnvelopeUpdateKSL(opl3_slot *slot) { int16_t ksl = (kslrom[slot->channel->f_num >> 6u] << 2) - ((0x08 - slot->channel->block) << 5); if (ksl < 0) ksl = 0; slot->eg_ksl = (uint8_t) ksl; } static void OPL3_EnvelopeCalc(opl3_slot *slot) { uint8_t nonzero; uint8_t rate; uint8_t rate_hi; uint8_t rate_lo; uint8_t reg_rate = 0; uint8_t ks; uint8_t eg_shift; uint8_t shift; uint16_t eg_rout; int16_t eg_inc; uint8_t eg_off; uint8_t reset = 0; slot->eg_out = slot->eg_rout + (slot->reg_tl << 2) + (slot->eg_ksl >> kslshift[slot->reg_ksl]) + *slot->trem; if (slot->key && slot->eg_gen == envelope_gen_num_release) { reset = 1; reg_rate = slot->reg_ar; } else switch (slot->eg_gen) { case envelope_gen_num_attack: reg_rate = slot->reg_ar; break; case envelope_gen_num_decay: reg_rate = slot->reg_dr; break; case envelope_gen_num_sustain: if (!slot->reg_type) reg_rate = slot->reg_rr; break; case envelope_gen_num_release: reg_rate = slot->reg_rr; break; default: break; } slot->pg_reset = reset; ks = slot->channel->ksv >> ((slot->reg_ksr ^ 1) << 1); nonzero = (reg_rate != 0); rate = ks + (reg_rate << 2); rate_hi = rate >> 2; rate_lo = rate & 0x03; if (rate_hi & 0x10) rate_hi = 0x0f; eg_shift = rate_hi + slot->chip->eg_add; shift = 0; if (nonzero) { if (rate_hi < 12) { if (slot->chip->eg_state) switch (eg_shift) { case 12: shift = 1; break; case 13: shift = (rate_lo >> 1) & 0x01; break; case 14: shift = rate_lo & 0x01; break; default: break; } } else { shift = (rate_hi & 0x03) + eg_incstep[rate_lo][slot->chip->eg_timer_lo]; if (shift & 0x04) shift = 0x03; if (!shift) shift = slot->chip->eg_state; } } eg_rout = slot->eg_rout; eg_inc = 0; eg_off = 0; // Instant attack if (reset && rate_hi == 0x0f) eg_rout = 0x00; // Envelope off if ((slot->eg_rout & 0x1f8) == 0x1f8) eg_off = 1; if (slot->eg_gen != envelope_gen_num_attack && !reset && eg_off) eg_rout = 0x1ff; switch (slot->eg_gen) { case envelope_gen_num_attack: if (!slot->eg_rout) slot->eg_gen = envelope_gen_num_decay; else if (slot->key && shift > 0 && rate_hi != 0x0f) eg_inc = ~slot->eg_rout >> (4 - shift); break; case envelope_gen_num_decay: if ((slot->eg_rout >> 4) == slot->reg_sl) slot->eg_gen = envelope_gen_num_sustain; else if (!eg_off && !reset && shift > 0) eg_inc = 1 << (shift - 1); break; case envelope_gen_num_sustain: case envelope_gen_num_release: if (!eg_off && !reset && shift > 0) eg_inc = 1 << (shift - 1); break; default: break; } slot->eg_rout = (eg_rout + eg_inc) & 0x1ff; // Key off if (reset) slot->eg_gen = envelope_gen_num_attack; if (!slot->key) slot->eg_gen = envelope_gen_num_release; } static void OPL3_EnvelopeKeyOn(opl3_slot *slot, uint8_t type) { slot->key |= type; } static void OPL3_EnvelopeKeyOff(opl3_slot *slot, uint8_t type) { slot->key &= ~type; } // Phase Generator static void OPL3_PhaseGenerate(opl3_slot *slot) { opl3_chip *chip; uint16_t f_num; uint32_t basefreq; uint8_t rm_xor; uint8_t n_bit; uint32_t noise; uint16_t phase; chip = slot->chip; f_num = slot->channel->f_num; if (slot->reg_vib) { int8_t range; uint8_t vibpos; range = (f_num >> 7) & 7; vibpos = chip->vibpos; if (!(vibpos & 3)) range = 0; else if (vibpos & 1) range >>= 1; range >>= chip->vibshift; if (vibpos & 4) range = -range; f_num += range; } basefreq = (f_num << slot->channel->block) >> 1; phase = (uint16_t) (slot->pg_phase >> 9); if (slot->pg_reset) slot->pg_phase = 0; slot->pg_phase += (basefreq * mt[slot->reg_mult]) >> 1; // Rhythm mode noise = chip->noise; slot->pg_phase_out = phase; if (slot->slot_num == 13) { // hh chip->rm_hh_bit2 = (phase >> 2) & 1; chip->rm_hh_bit3 = (phase >> 3) & 1; chip->rm_hh_bit7 = (phase >> 7) & 1; chip->rm_hh_bit8 = (phase >> 8) & 1; } if (slot->slot_num == 17 && (chip->rhy & 0x20)) { // tc chip->rm_tc_bit3 = (phase >> 3) & 1; chip->rm_tc_bit5 = (phase >> 5) & 1; } if (chip->rhy & 0x20) { rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7) | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5) | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5); switch (slot->slot_num) { case 13: // hh slot->pg_phase_out = rm_xor << 9; if (rm_xor ^ (noise & 1)) slot->pg_phase_out |= 0xd0; else slot->pg_phase_out |= 0x34; break; case 16: // sd slot->pg_phase_out = (chip->rm_hh_bit8 << 9) | ((chip->rm_hh_bit8 ^ (noise & 1)) << 8); break; case 17: // tc slot->pg_phase_out = (rm_xor << 9) | 0x80; break; default: break; } } n_bit = ((noise >> 14) ^ noise) & 0x01; chip->noise = (noise >> 1) | (n_bit << 22); } // Slot static void OPL3_SlotWrite20(opl3_slot *slot, uint8_t data) { if ((data >> 7) & 0x01) slot->trem = &slot->chip->tremolo; else slot->trem = (uint8_t *) &slot->chip->zeromod; slot->reg_vib = (data >> 6) & 0x01; slot->reg_type = (data >> 5) & 0x01; slot->reg_ksr = (data >> 4) & 0x01; slot->reg_mult = data & 0x0f; } static void OPL3_SlotWrite40(opl3_slot *slot, uint8_t data) { slot->reg_ksl = (data >> 6) & 0x03; slot->reg_tl = data & 0x3f; OPL3_EnvelopeUpdateKSL(slot); } static void OPL3_SlotWrite60(opl3_slot *slot, uint8_t data) { slot->reg_ar = (data >> 4) & 0x0f; slot->reg_dr = data & 0x0f; } static void OPL3_SlotWrite80(opl3_slot *slot, uint8_t data) { slot->reg_sl = (data >> 4) & 0x0f; if (slot->reg_sl == 0x0f) slot->reg_sl = 0x1f; slot->reg_rr = data & 0x0f; } static void OPL3_SlotWriteE0(opl3_slot *slot, uint8_t data) { slot->reg_wf = data & 0x07; if (slot->chip->newm == 0x00) slot->reg_wf &= 0x03; } static void OPL3_SlotGenerate(opl3_slot *slot) { slot->out = envelope_sin[slot->reg_wf](slot->pg_phase_out + *slot->mod, slot->eg_out); } static void OPL3_SlotCalcFB(opl3_slot *slot) { if (slot->channel->fb != 0x00) slot->fbmod = (slot->prout + slot->out) >> (0x09 - slot->channel->fb); else slot->fbmod = 0; slot->prout = slot->out; } // Channel static void OPL3_ChannelSetupAlg(opl3_channel *channel); static void OPL3_ChannelUpdateRhythm(opl3_chip *chip, uint8_t data) { opl3_channel *channel6; opl3_channel *channel7; opl3_channel *channel8; uint8_t chnum; chip->rhy = data & 0x3f; if (chip->rhy & 0x20) { channel6 = &chip->channel[6]; channel7 = &chip->channel[7]; channel8 = &chip->channel[8]; channel6->out[0] = &channel6->slotz[1]->out; channel6->out[1] = &channel6->slotz[1]->out; channel6->out[2] = &chip->zeromod; channel6->out[3] = &chip->zeromod; channel7->out[0] = &channel7->slotz[0]->out; channel7->out[1] = &channel7->slotz[0]->out; channel7->out[2] = &channel7->slotz[1]->out; channel7->out[3] = &channel7->slotz[1]->out; channel8->out[0] = &channel8->slotz[0]->out; channel8->out[1] = &channel8->slotz[0]->out; channel8->out[2] = &channel8->slotz[1]->out; channel8->out[3] = &channel8->slotz[1]->out; for (chnum = 6; chnum < 9; chnum++) chip->channel[chnum].chtype = ch_drum; OPL3_ChannelSetupAlg(channel6); OPL3_ChannelSetupAlg(channel7); OPL3_ChannelSetupAlg(channel8); // hh if (chip->rhy & 0x01) OPL3_EnvelopeKeyOn(channel7->slotz[0], egk_drum); else OPL3_EnvelopeKeyOff(channel7->slotz[0], egk_drum); // tc if (chip->rhy & 0x02) OPL3_EnvelopeKeyOn(channel8->slotz[1], egk_drum); else OPL3_EnvelopeKeyOff(channel8->slotz[1], egk_drum); // tom if (chip->rhy & 0x04) OPL3_EnvelopeKeyOn(channel8->slotz[0], egk_drum); else OPL3_EnvelopeKeyOff(channel8->slotz[0], egk_drum); // sd if (chip->rhy & 0x08) OPL3_EnvelopeKeyOn(channel7->slotz[1], egk_drum); else OPL3_EnvelopeKeyOff(channel7->slotz[1], egk_drum); // bd if (chip->rhy & 0x10) { OPL3_EnvelopeKeyOn(channel6->slotz[0], egk_drum); OPL3_EnvelopeKeyOn(channel6->slotz[1], egk_drum); } else { OPL3_EnvelopeKeyOff(channel6->slotz[0], egk_drum); OPL3_EnvelopeKeyOff(channel6->slotz[1], egk_drum); } } else { for (chnum = 6; chnum < 9; chnum++) { chip->channel[chnum].chtype = ch_2op; OPL3_ChannelSetupAlg(&chip->channel[chnum]); OPL3_EnvelopeKeyOff(chip->channel[chnum].slotz[0], egk_drum); OPL3_EnvelopeKeyOff(chip->channel[chnum].slotz[1], egk_drum); } } } static void OPL3_ChannelWriteA0(opl3_channel *channel, uint8_t data) { if (channel->chip->newm && channel->chtype == ch_4op2) return; channel->f_num = (channel->f_num & 0x300) | data; channel->ksv = (channel->block << 1) | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); OPL3_EnvelopeUpdateKSL(channel->slotz[0]); OPL3_EnvelopeUpdateKSL(channel->slotz[1]); if (channel->chip->newm && channel->chtype == ch_4op) { channel->pair->f_num = channel->f_num; channel->pair->ksv = channel->ksv; OPL3_EnvelopeUpdateKSL(channel->pair->slotz[0]); OPL3_EnvelopeUpdateKSL(channel->pair->slotz[1]); } } static void OPL3_ChannelWriteB0(opl3_channel *channel, uint8_t data) { if (channel->chip->newm && channel->chtype == ch_4op2) return; channel->f_num = (channel->f_num & 0xff) | ((data & 0x03) << 8); channel->block = (data >> 2) & 0x07; channel->ksv = (channel->block << 1) | ((channel->f_num >> (0x09 - channel->chip->nts)) & 0x01); OPL3_EnvelopeUpdateKSL(channel->slotz[0]); OPL3_EnvelopeUpdateKSL(channel->slotz[1]); if (channel->chip->newm && channel->chtype == ch_4op) { channel->pair->f_num = channel->f_num; channel->pair->block = channel->block; channel->pair->ksv = channel->ksv; OPL3_EnvelopeUpdateKSL(channel->pair->slotz[0]); OPL3_EnvelopeUpdateKSL(channel->pair->slotz[1]); } } static void OPL3_ChannelSetupAlg(opl3_channel *channel) { if (channel->chtype == ch_drum) { if (channel->ch_num == 7 || channel->ch_num == 8) { channel->slotz[0]->mod = &channel->chip->zeromod; channel->slotz[1]->mod = &channel->chip->zeromod; return; } switch (channel->alg & 0x01) { case 0x00: channel->slotz[0]->mod = &channel->slotz[0]->fbmod; channel->slotz[1]->mod = &channel->slotz[0]->out; break; case 0x01: channel->slotz[0]->mod = &channel->slotz[0]->fbmod; channel->slotz[1]->mod = &channel->chip->zeromod; break; default: break; } return; } if (channel->alg & 0x08) return; if (channel->alg & 0x04) { channel->pair->out[0] = &channel->chip->zeromod; channel->pair->out[1] = &channel->chip->zeromod; channel->pair->out[2] = &channel->chip->zeromod; channel->pair->out[3] = &channel->chip->zeromod; switch (channel->alg & 0x03) { case 0x00: channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; channel->pair->slotz[1]->mod = &channel->pair->slotz[0]->out; channel->slotz[0]->mod = &channel->pair->slotz[1]->out; channel->slotz[1]->mod = &channel->slotz[0]->out; channel->out[0] = &channel->slotz[1]->out; channel->out[1] = &channel->chip->zeromod; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x01: channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; channel->pair->slotz[1]->mod = &channel->pair->slotz[0]->out; channel->slotz[0]->mod = &channel->chip->zeromod; channel->slotz[1]->mod = &channel->slotz[0]->out; channel->out[0] = &channel->pair->slotz[1]->out; channel->out[1] = &channel->slotz[1]->out; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x02: channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; channel->pair->slotz[1]->mod = &channel->chip->zeromod; channel->slotz[0]->mod = &channel->pair->slotz[1]->out; channel->slotz[1]->mod = &channel->slotz[0]->out; channel->out[0] = &channel->pair->slotz[0]->out; channel->out[1] = &channel->slotz[1]->out; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x03: channel->pair->slotz[0]->mod = &channel->pair->slotz[0]->fbmod; channel->pair->slotz[1]->mod = &channel->chip->zeromod; channel->slotz[0]->mod = &channel->pair->slotz[1]->out; channel->slotz[1]->mod = &channel->chip->zeromod; channel->out[0] = &channel->pair->slotz[0]->out; channel->out[1] = &channel->slotz[0]->out; channel->out[2] = &channel->slotz[1]->out; channel->out[3] = &channel->chip->zeromod; break; default: break; } } else switch (channel->alg & 0x01) { case 0x00: channel->slotz[0]->mod = &channel->slotz[0]->fbmod; channel->slotz[1]->mod = &channel->slotz[0]->out; channel->out[0] = &channel->slotz[1]->out; channel->out[1] = &channel->chip->zeromod; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; case 0x01: channel->slotz[0]->mod = &channel->slotz[0]->fbmod; channel->slotz[1]->mod = &channel->chip->zeromod; channel->out[0] = &channel->slotz[0]->out; channel->out[1] = &channel->slotz[1]->out; channel->out[2] = &channel->chip->zeromod; channel->out[3] = &channel->chip->zeromod; break; default: break; } } static void OPL3_ChannelUpdateAlg(opl3_channel *channel) { channel->alg = channel->con; if (channel->chip->newm) { if (channel->chtype == ch_4op) { channel->pair->alg = 0x04 | (channel->con << 1) | (channel->pair->con); channel->alg = 0x08; OPL3_ChannelSetupAlg(channel->pair); } else if (channel->chtype == ch_4op2) { channel->alg = 0x04 | (channel->pair->con << 1) | (channel->con); channel->pair->alg = 0x08; OPL3_ChannelSetupAlg(channel); } else OPL3_ChannelSetupAlg(channel); } else OPL3_ChannelSetupAlg(channel); } static void OPL3_ChannelWriteC0(opl3_channel *channel, uint8_t data) { channel->fb = (data & 0x0e) >> 1; channel->con = data & 0x01; OPL3_ChannelUpdateAlg(channel); if (channel->chip->newm) { channel->cha = ((data >> 4) & 0x01) ? ~0 : 0; channel->chb = ((data >> 5) & 0x01) ? ~0 : 0; channel->chc = ((data >> 6) & 0x01) ? ~0 : 0; channel->chd = ((data >> 7) & 0x01) ? ~0 : 0; } else { channel->cha = channel->chb = (uint16_t) ~0; // TODO: Verify on real chip if DAC2 output is disabled in compat mode channel->chc = channel->chd = 0; } #if OPL_ENABLE_STEREOEXT if (!channel->chip->stereoext) { channel->leftpan = channel->cha << 16; channel->rightpan = channel->chb << 16; } #endif } #if OPL_ENABLE_STEREOEXT static void OPL3_ChannelWriteD0(opl3_channel *channel, uint8_t data) { if (channel->chip->stereoext) { channel->leftpan = panpot_lut[data ^ 0xffu]; channel->rightpan = panpot_lut[data]; } } #endif static void OPL3_ChannelKeyOn(opl3_channel *channel) { if (channel->chip->newm) { if (channel->chtype == ch_4op) { OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm); OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm); OPL3_EnvelopeKeyOn(channel->pair->slotz[0], egk_norm); OPL3_EnvelopeKeyOn(channel->pair->slotz[1], egk_norm); } else if (channel->chtype == ch_2op || channel->chtype == ch_drum) { OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm); OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm); } } else { OPL3_EnvelopeKeyOn(channel->slotz[0], egk_norm); OPL3_EnvelopeKeyOn(channel->slotz[1], egk_norm); } } static void OPL3_ChannelKeyOff(opl3_channel *channel) { if (channel->chip->newm) { if (channel->chtype == ch_4op) { OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm); OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm); OPL3_EnvelopeKeyOff(channel->pair->slotz[0], egk_norm); OPL3_EnvelopeKeyOff(channel->pair->slotz[1], egk_norm); } else if (channel->chtype == ch_2op || channel->chtype == ch_drum) { OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm); OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm); } } else { OPL3_EnvelopeKeyOff(channel->slotz[0], egk_norm); OPL3_EnvelopeKeyOff(channel->slotz[1], egk_norm); } } static void OPL3_ChannelSet4Op(opl3_chip *chip, uint8_t data) { uint8_t chnum; for (uint8_t bit = 0; bit < 6; bit++) { chnum = bit; if (bit >= 3) chnum += 9 - 3; if ((data >> bit) & 0x01) { chip->channel[chnum].chtype = ch_4op; chip->channel[chnum + 3u].chtype = ch_4op2; OPL3_ChannelUpdateAlg(&chip->channel[chnum]); } else { chip->channel[chnum].chtype = ch_2op; chip->channel[chnum + 3u].chtype = ch_2op; OPL3_ChannelUpdateAlg(&chip->channel[chnum]); OPL3_ChannelUpdateAlg(&chip->channel[chnum + 3u]); } } } static void OPL3_ProcessSlot(opl3_slot *slot) { OPL3_SlotCalcFB(slot); OPL3_EnvelopeCalc(slot); OPL3_PhaseGenerate(slot); OPL3_SlotGenerate(slot); } static inline void OPL3_Generate4Ch(void *priv, int32_t *buf4) { opl3_chip *chip = (opl3_chip *) priv; opl3_channel *channel; opl3_writebuf *writebuf; int16_t **out; int32_t mix[2]; uint8_t i; int16_t accm; uint8_t shift = 0; buf4[1] = chip->mixbuff[1]; buf4[3] = chip->mixbuff[3]; #if OPL_QUIRK_CHANNELSAMPLEDELAY for (i = 0; i < 15; i++) #else for (i = 0; i < 36; i++) #endif OPL3_ProcessSlot(&chip->slot[i]); mix[0] = mix[1] = 0; for (i = 0; i < 18; i++) { channel = &chip->channel[i]; out = channel->out; accm = *out[0] + *out[1] + *out[2] + *out[3]; #if OPL_ENABLE_STEREOEXT mix[0] += (int16_t) ((accm * channel->leftpan) >> 16); #else mix[0] += (int16_t) (accm & channel->cha); #endif mix[1] += (int16_t) (accm & channel->chc); } chip->mixbuff[0] = mix[0]; chip->mixbuff[2] = mix[1]; #if OPL_QUIRK_CHANNELSAMPLEDELAY for (i = 15; i < 18; i++) OPL3_ProcessSlot(&chip->slot[i]); #endif buf4[0] = chip->mixbuff[0]; buf4[2] = chip->mixbuff[2]; #if OPL_QUIRK_CHANNELSAMPLEDELAY for (i = 18; i < 33; i++) OPL3_ProcessSlot(&chip->slot[i]); #endif mix[0] = mix[1] = 0; for (i = 0; i < 18; i++) { channel = &chip->channel[i]; out = channel->out; accm = *out[0] + *out[1] + *out[2] + *out[3]; #if OPL_ENABLE_STEREOEXT mix[0] += (int16_t) ((accm * channel->rightpan) >> 16); #else mix[0] += (int16_t) (accm & channel->chb); #endif mix[1] += (int16_t) (accm & channel->chd); } chip->mixbuff[1] = mix[0]; chip->mixbuff[3] = mix[1]; #if OPL_QUIRK_CHANNELSAMPLEDELAY for (i = 33; i < 36; i++) OPL3_ProcessSlot(&chip->slot[i]); #endif if ((chip->timer & 0x3f) == 0x3f) chip->tremolopos = (chip->tremolopos + 1) % 210; if (chip->tremolopos < 105) chip->tremolo = chip->tremolopos >> chip->tremoloshift; else chip->tremolo = (210 - chip->tremolopos) >> chip->tremoloshift; if ((chip->timer & 0x03ff) == 0x03ff) chip->vibpos = (chip->vibpos + 1) & 7; chip->timer++; if (chip->eg_state) { while (shift < 13 && ((chip->eg_timer >> shift) & 1) == 0) shift++; if (shift > 12) chip->eg_add = 0; else chip->eg_add = shift + 1; chip->eg_timer_lo = (uint8_t) (chip->eg_timer & 0x3u); } if (chip->eg_timerrem || chip->eg_state) { if (chip->eg_timer == UINT64_C(0xfffffffff)) { chip->eg_timer = 0; chip->eg_timerrem = 1; } else { chip->eg_timer++; chip->eg_timerrem = 0; } } chip->eg_state ^= 1; while ((writebuf = &chip->writebuf[chip->writebuf_cur]), writebuf->time <= chip->writebuf_samplecnt) { if (!(writebuf->reg & 0x200)) break; writebuf->reg &= 0x01ff; OPL3_WriteReg(chip, writebuf->reg, writebuf->data); chip->writebuf_cur = (chip->writebuf_cur + 1) % OPL_WRITEBUF_SIZE; } chip->writebuf_samplecnt++; } void OPL3_Generate(opl3_chip *chip, int32_t *buf) { int32_t samples[4]; OPL3_Generate4Ch(chip, samples); buf[0] = samples[0]; buf[1] = samples[1]; } void OPL3_Generate4ChResampled(opl3_chip *chip, int32_t *buf4) { while (chip->samplecnt >= chip->rateratio) { chip->oldsamples[0] = chip->samples[0]; chip->oldsamples[1] = chip->samples[1]; chip->oldsamples[2] = chip->samples[2]; chip->oldsamples[3] = chip->samples[3]; OPL3_Generate4Ch(chip, chip->samples); chip->samplecnt -= chip->rateratio; } buf4[0] = (int32_t) ((chip->oldsamples[0] * (chip->rateratio - chip->samplecnt) + chip->samples[0] * chip->samplecnt) / chip->rateratio); buf4[1] = (int32_t) ((chip->oldsamples[1] * (chip->rateratio - chip->samplecnt) + chip->samples[1] * chip->samplecnt) / chip->rateratio); buf4[2] = (int32_t) ((chip->oldsamples[2] * (chip->rateratio - chip->samplecnt) + chip->samples[2] * chip->samplecnt) / chip->rateratio); buf4[3] = (int32_t) ((chip->oldsamples[3] * (chip->rateratio - chip->samplecnt) + chip->samples[3] * chip->samplecnt) / chip->rateratio); chip->samplecnt += 1 << RSM_FRAC; } void OPL3_GenerateResampled(opl3_chip *chip, int32_t *buf) { int32_t samples[4]; OPL3_Generate4ChResampled(chip, samples); buf[0] = samples[0]; buf[1] = samples[1]; } void OPL3_Reset(opl3_chip *chip, uint32_t samplerate) { opl3_slot *slot; opl3_channel *channel; uint8_t local_ch_slot; memset(chip, 0x00, sizeof(opl3_chip)); for (uint8_t slotnum = 0; slotnum < 36; slotnum++) { slot = &chip->slot[slotnum]; slot->chip = chip; slot->mod = &chip->zeromod; slot->eg_rout = 0x01ff; slot->eg_out = 0x01ff; slot->eg_gen = envelope_gen_num_release; slot->trem = (uint8_t *) &chip->zeromod; slot->slot_num = slotnum; } for (uint8_t channum = 0; channum < 18; channum++) { channel = &chip->channel[channum]; local_ch_slot = ch_slot[channum]; channel->slotz[0] = &chip->slot[local_ch_slot]; channel->slotz[1] = &chip->slot[local_ch_slot + 3u]; chip->slot[local_ch_slot].channel = channel; chip->slot[local_ch_slot + 3u].channel = channel; if ((channum % 9) < 3) channel->pair = &chip->channel[channum + 3u]; else if ((channum % 9) < 6) channel->pair = &chip->channel[channum - 3u]; channel->chip = chip; channel->out[0] = &chip->zeromod; channel->out[1] = &chip->zeromod; channel->out[2] = &chip->zeromod; channel->out[3] = &chip->zeromod; channel->chtype = ch_2op; channel->cha = 0xffff; channel->chb = 0xffff; #if OPL_ENABLE_STEREOEXT channel->leftpan = 0x10000; channel->rightpan = 0x10000; #endif channel->ch_num = channum; OPL3_ChannelSetupAlg(channel); } chip->noise = 1; chip->rateratio = (samplerate << RSM_FRAC) / 49716; chip->tremoloshift = 4; chip->vibshift = 1; #if OPL_ENABLE_STEREOEXT if (!panpot_lut_build) { for (int32_t i = 0; i < 256; i++) panpot_lut[i] = OPL_SIN(i); panpot_lut_build = 1; } #endif } uint16_t nuked_write_addr(void *priv, uint16_t port, uint8_t val) { const opl3_chip *chip = (opl3_chip *) priv; uint16_t addr; addr = val; if ((port & 0x0002) && ((addr == 0x0005) || chip->newm)) addr |= 0x0100; return addr; } void OPL3_WriteReg(void *priv, uint16_t reg, uint8_t val) { opl3_chip *chip = (opl3_chip *) priv; uint8_t high = (reg >> 8) & 0x01; uint8_t regm = reg & 0xff; switch (regm & 0xf0) { case 0x00: if (high) switch (regm & 0x0f) { case 0x04: OPL3_ChannelSet4Op(chip, val); break; case 0x05: chip->newm = val & 0x01; #if OPL_ENABLE_STEREOEXT chip->stereoext = (val >> 1) & 0x01; #endif break; default: break; } else switch (regm & 0x0f) { case 0x08: chip->nts = (val >> 6) & 0x01; break; default: break; } break; case 0x20: case 0x30: if (ad_slot[regm & 0x1fu] >= 0) OPL3_SlotWrite20(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], val); break; case 0x40: case 0x50: if (ad_slot[regm & 0x1fu] >= 0) OPL3_SlotWrite40(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], val); break; case 0x60: case 0x70: if (ad_slot[regm & 0x1fu] >= 0) OPL3_SlotWrite60(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], val); break; case 0x80: case 0x90: if (ad_slot[regm & 0x1fu] >= 0) OPL3_SlotWrite80(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], val); break; case 0xe0: case 0xf0: if (ad_slot[regm & 0x1fu] >= 0) OPL3_SlotWriteE0(&chip->slot[18u * high + ad_slot[regm & 0x1fu]], val); break; case 0xa0: if ((regm & 0x0f) < 9) OPL3_ChannelWriteA0(&chip->channel[9u * high + (regm & 0x0fu)], val); break; case 0xb0: if (regm == 0xbd && !high) { chip->tremoloshift = (((val >> 7) ^ 1) << 1) + 2; chip->vibshift = ((val >> 6) & 0x01) ^ 1; OPL3_ChannelUpdateRhythm(chip, val); } else if ((regm & 0x0f) < 9) { OPL3_ChannelWriteB0(&chip->channel[9u * high + (regm & 0x0fu)], val); if (val & 0x20) OPL3_ChannelKeyOn(&chip->channel[9u * high + (regm & 0x0fu)]); else OPL3_ChannelKeyOff(&chip->channel[9u * high + (regm & 0x0fu)]); } break; case 0xc0: if ((regm & 0x0f) < 9) OPL3_ChannelWriteC0(&chip->channel[9u * high + (regm & 0x0fu)], val); break; #if OPL_ENABLE_STEREOEXT case 0xd0: if ((regm & 0x0f) < 9) OPL3_ChannelWriteD0(&chip->channel[9u * high + (regm & 0x0fu)], val); break; #endif default: break; } } void OPL3_WriteRegBuffered(void *priv, uint16_t reg, uint8_t val) { opl3_chip *chip = (opl3_chip *) priv; uint64_t time1; uint64_t time2; opl3_writebuf *writebuf; uint32_t writebuf_last; writebuf_last = chip->writebuf_last; writebuf = &chip->writebuf[writebuf_last]; if (writebuf->reg & 0x0200) { OPL3_WriteReg(chip, writebuf->reg & 0x01ff, writebuf->data); chip->writebuf_cur = (writebuf_last + 1) % OPL_WRITEBUF_SIZE; chip->writebuf_samplecnt = writebuf->time; } writebuf->reg = reg | 0x0200; writebuf->data = val; time1 = chip->writebuf_lasttime + OPL_WRITEBUF_DELAY; time2 = chip->writebuf_samplecnt; if (time1 < time2) time1 = time2; writebuf->time = time1; chip->writebuf_lasttime = time1; chip->writebuf_last = (writebuf_last + 1) % OPL_WRITEBUF_SIZE; } void OPL3_Generate4ChStream(opl3_chip *chip, int32_t *sndptr1, int32_t *sndptr2, uint32_t numsamples) { int32_t samples[4]; for (uint_fast32_t i = 0; i < numsamples; i++) { OPL3_Generate4Ch(chip, samples); sndptr1[0] = samples[0]; sndptr1[1] = samples[1]; sndptr2[0] = samples[2]; sndptr2[1] = samples[3]; sndptr1 += 2; sndptr2 += 2; } } void OPL3_GenerateStream(opl3_chip *chip, int32_t *sndptr, uint32_t numsamples) { for (uint_fast32_t i = 0; i < numsamples; i++) { OPL3_Generate(chip, sndptr); sndptr += 2; } } static void nuked_timer_tick(nuked_drv_t *dev, int tmr) { dev->timer_cur_count[tmr] = (dev->timer_cur_count[tmr] + 1) & 0xff; nuked_log("Ticking timer %i, count now %02X...\n", tmr, dev->timer_cur_count[tmr]); if (dev->timer_cur_count[tmr] == 0x00) { dev->status |= ((STAT_TMR1_OVER >> tmr) & ~dev->timer_ctrl); dev->timer_cur_count[tmr] = dev->timer_count[tmr]; nuked_log("Count wrapped around to zero, reloading timer %i (%02X), status = %02X...\n", tmr, (STAT_TMR1_OVER >> tmr), dev->status); } timer_on_auto(&dev->timers[tmr], (tmr == 1) ? 320.0 : 80.0); } static void nuked_timer_control(nuked_drv_t *dev, int tmr, int start) { timer_on_auto(&dev->timers[tmr], 0.0); if (start) { nuked_log("Loading timer %i count: %02X = %02X\n", tmr, dev->timer_cur_count[tmr], dev->timer_count[tmr]); dev->timer_cur_count[tmr] = dev->timer_count[tmr]; if (dev->flags & FLAG_OPL3) nuked_timer_tick(dev, tmr); /* Per the YMF 262 datasheet, OPL3 starts counting immediately, unlike OPL2. */ else timer_on_auto(&dev->timers[tmr], (tmr == 1) ? 320.0 : 80.0); } else { nuked_log("Timer %i stopped\n", tmr); if (tmr == 1) { dev->status &= ~STAT_TMR2_OVER; } else dev->status &= ~STAT_TMR1_OVER; } } static void nuked_timer_1(void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; nuked_timer_tick(dev, 0); } static void nuked_timer_2(void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; nuked_timer_tick(dev, 1); } static void nuked_drv_set_do_cycles(void *priv, int8_t do_cycles) { nuked_drv_t *dev = (nuked_drv_t *) priv; if (do_cycles) dev->flags |= FLAG_CYCLES; else dev->flags &= ~FLAG_CYCLES; } static void * nuked_drv_init(const device_t *info) { nuked_drv_t *dev = (nuked_drv_t *) calloc(1, sizeof(nuked_drv_t)); dev->flags = FLAG_CYCLES; if (info->local == FM_YMF262) dev->flags |= FLAG_OPL3; else dev->status = 0x06; /* Initialize the NukedOPL object. */ OPL3_Reset(&dev->opl, OPL_FREQ); timer_add(&dev->timers[0], nuked_timer_1, dev, 0); timer_add(&dev->timers[1], nuked_timer_2, dev, 0); return dev; } static void nuked_drv_close(void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; free(dev); } static int32_t * nuked_drv_update(void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; if (dev->pos >= music_pos_global) return dev->buffer; OPL3_GenerateStream(&dev->opl, &dev->buffer[dev->pos * 2], music_pos_global - dev->pos); for (; dev->pos < music_pos_global; dev->pos++) { dev->buffer[dev->pos * 2] /= 2; dev->buffer[(dev->pos * 2) + 1] /= 2; } return dev->buffer; } static uint8_t nuked_drv_read(uint16_t port, void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; if (dev->flags & FLAG_CYCLES) cycles -= ((int) (isa_timing * 8)); nuked_drv_update(dev); uint8_t ret = 0xff; if ((port & 0x0003) == 0x0000) { ret = dev->status; if (dev->status & STAT_TMR_OVER) ret |= STAT_TMR_ANY; } nuked_log("OPL statret = %02x, status = %02x\n", ret, dev->status); return ret; } static void nuked_drv_write(uint16_t port, uint8_t val, void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; nuked_drv_update(dev); if ((port & 0x0001) == 0x0001) { OPL3_WriteRegBuffered(&dev->opl, dev->port, val); switch (dev->port) { case 0x002: /* Timer 1 */ dev->timer_count[0] = val; nuked_log("Timer 0 count now: %i\n", dev->timer_count[0]); break; case 0x003: /* Timer 2 */ dev->timer_count[1] = val; nuked_log("Timer 1 count now: %i\n", dev->timer_count[1]); break; case 0x004: /* Timer control */ if (val & CTRL_RESET) { nuked_log("Resetting timer status...\n"); dev->status &= ~STAT_TMR_OVER; } else { dev->timer_ctrl = val; nuked_timer_control(dev, 0, val & CTRL_TMR1_START); nuked_timer_control(dev, 1, val & CTRL_TMR2_START); nuked_log("Status mask now %02X (val = %02X)\n", (val & ~CTRL_TMR_MASK) & CTRL_TMR_MASK, val); } break; case 0x105: dev->opl.newm = val & 0x01; break; default: break; } } else { dev->port = nuked_write_addr(&dev->opl, port, val) & 0x01ff; if (!(dev->flags & FLAG_OPL3)) dev->port &= 0x00ff; } } static void nuked_drv_reset_buffer(void *priv) { nuked_drv_t *dev = (nuked_drv_t *) priv; dev->pos = 0; } const device_t ym3812_nuked_device = { .name = "Yamaha YM3812 OPL2 (NUKED)", .internal_name = "ym3812_nuked", .flags = 0, .local = FM_YM3812, .init = nuked_drv_init, .close = nuked_drv_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; const device_t ymf262_nuked_device = { .name = "Yamaha YMF262 OPL3 (NUKED)", .internal_name = "ymf262_nuked", .flags = 0, .local = FM_YMF262, .init = nuked_drv_init, .close = nuked_drv_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; const fm_drv_t nuked_opl_drv = { &nuked_drv_read, &nuked_drv_write, &nuked_drv_update, &nuked_drv_reset_buffer, &nuked_drv_set_do_cycles, NULL, NULL, }; ```
/content/code_sandbox/src/sound/snd_opl_nuked.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
17,749
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Crystal CS423x (SBPro/WSS compatible sound chips) emulation. * * * * Authors: RichardG, <richardg867@gmail.com> * */ #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/device.h> #include <86box/dma.h> #include <86box/gameport.h> #include <86box/i2c.h> #include <86box/io.h> #include <86box/isapnp.h> #include <86box/midi.h> #include <86box/timer.h> #include <86box/mem.h> #include <86box/nvr.h> #include <86box/rom.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/snd_ad1848.h> #include <86box/snd_opl.h> #include <86box/snd_sb.h> #include <86box/plat_fallthrough.h> #include <86box/plat_unused.h> #define PNP_ROM_CS4236B "roms/sound/crystal/PNPISA01.BIN" #define CRYSTAL_NOEEPROM 0x100 enum { CRYSTAL_CS4235 = 0xdd, CRYSTAL_CS4236B = 0xcb, CRYSTAL_CS4237B = 0xc8, CRYSTAL_CS4238B = 0xc9 }; enum { CRYSTAL_SLAM_NONE = 0, CRYSTAL_SLAM_INDEX = 1, CRYSTAL_SLAM_BYTE1 = 2, CRYSTAL_SLAM_BYTE2 = 3 }; static const uint8_t slam_init_key[32] = { 0x96, 0x35, 0x9A, 0xCD, 0xE6, 0xF3, 0x79, 0xBC, 0x5E, 0xAF, 0x57, 0x2B, 0x15, 0x8A, 0xC5, 0xE2, 0xF1, 0xF8, 0x7C, 0x3E, 0x9F, 0x4F, 0x27, 0x13, 0x09, 0x84, 0x42, 0xA1, 0xD0, 0x68, 0x34, 0x1A }; static const uint8_t cs4236b_eeprom[8224] = { // clang-format off /* Chip configuration */ 0x55, 0xbb, /* magic */ 0x00, 0x00, /* length */ 0x00, 0x03, /* CD-ROM and modem decode */ 0x80, /* misc. config */ 0x80, /* global config */ 0x0b, /* chip ID */ 0x20, 0x04, 0x08, 0x10, 0x80, 0x00, 0x00, /* reserved */ 0x00, /* external decode length */ 0x48, /* reserved */ 0x75, 0xb9, 0xfc, /* IRQ routing */ 0x10, 0x03, /* DMA routing */ /* PnP resources */ 0x00 // clang-format on }; typedef struct cs423x_t { void *pnp_card; ad1848_t ad1848; sb_t *sb; void *gameport; void *i2c; void *eeprom; uint16_t wss_base; uint16_t opl_base; uint16_t sb_base; uint16_t ctrl_base; uint16_t ram_addr; uint16_t eeprom_size : 11; uint16_t pnp_offset; uint8_t type; uint8_t ad1848_type; uint8_t regs[8]; uint8_t indirect_regs[16]; uint8_t eeprom_data[2048]; uint8_t ram_data[65536]; uint8_t ram_dl : 2; uint8_t opl_wss : 1; char *nvr_path; uint8_t pnp_enable : 1; uint8_t key_pos : 5; uint8_t slam_enable : 1; uint8_t slam_state : 2; uint8_t slam_ld; uint8_t slam_reg; isapnp_device_config_t *slam_config; } cs423x_t; static void cs423x_slam_enable(cs423x_t *dev, uint8_t enable); static void cs423x_pnp_enable(cs423x_t *dev, uint8_t update_rom, uint8_t update_hwconfig); static void cs423x_pnp_config_changed(uint8_t ld, isapnp_device_config_t *config, void *priv); static void cs423x_nvram(cs423x_t *dev, uint8_t save) { FILE *fp = nvr_fopen(dev->nvr_path, save ? "wb" : "rb"); if (fp) { if (save) fwrite(dev->eeprom_data, sizeof(dev->eeprom_data), 1, fp); else (void) !fread(dev->eeprom_data, sizeof(dev->eeprom_data), 1, fp); fclose(fp); } } static uint8_t cs423x_read(uint16_t addr, void *priv) { cs423x_t *dev = (cs423x_t *) priv; uint8_t reg = addr & 7; uint8_t ret = dev->regs[reg]; switch (reg) { case 1: /* EEPROM Interface */ ret &= ~0x04; if ((dev->regs[1] & 0x04) && i2c_gpio_get_sda(dev->i2c)) ret |= 0x04; break; case 4: /* Control Indirect Data Register */ ret = dev->indirect_regs[dev->regs[3]]; break; case 5: /* Control/RAM Access */ /* Reading RAM is undocumented; the Windows drivers do so. */ if (dev->ram_dl == 3) ret = dev->ram_data[dev->ram_addr++]; break; case 7: /* Global Status */ /* Context switching: take active context and interrupt flag, then clear interrupt flag. */ ret &= 0xc0; dev->regs[7] &= 0x80; if (dev->sb->mpu->state.irq_pending) /* MPU interrupt */ ret |= 0x08; if (dev->ad1848.status & 0x01) /* WSS interrupt */ ret |= 0x10; if (dev->sb->dsp.sb_irq8 || dev->sb->dsp.sb_irq16 || dev->sb->dsp.sb_irq401) /* SBPro interrupt */ ret |= 0x20; break; default: break; } return ret; } static void cs423x_write(uint16_t addr, uint8_t val, void *priv) { cs423x_t *dev = (cs423x_t *) priv; uint8_t reg = addr & 0x07; switch (reg) { case 1: /* EEPROM Interface */ if (val & 0x04) i2c_gpio_set(dev->i2c, val & 0x01, val & 0x02); break; case 3: /* Control Indirect Access Register */ val &= 0x0f; break; case 4: /* Control Indirect Data Register */ switch (dev->regs[3] & 0x0f) { case 0: /* WSS Master Control */ if (val & 0x80) ad1848_init(&dev->ad1848, dev->ad1848_type); val = 0x00; break; case 1: /* Version / Chip ID */ case 7: /* Reserved */ case 9 ... 15: /* unspecified */ return; case 2: /* 3D Space and {Center|Volume} */ case 6: /* Upper Channel Status */ if (dev->type < CRYSTAL_CS4237B) return; break; case 3: /* 3D Enable */ if (dev->type < CRYSTAL_CS4237B) return; val &= 0xe0; break; case 4: /* Consumer Serial Port Enable */ if (dev->type < CRYSTAL_CS4237B) return; val &= 0xf0; break; case 5: /* Lower Channel Status */ if (dev->type < CRYSTAL_CS4237B) return; val &= 0xfe; break; case 8: /* CS9236 Wavetable Control */ val &= 0x0f; cs423x_pnp_enable(dev, 0, 0); /* Update WTEN state on the WSS codec. */ dev->ad1848.wten = !!(val & 0x08); ad1848_updatevolmask(&dev->ad1848); break; default: break; } dev->indirect_regs[dev->regs[3]] = val; break; case 5: /* Control/RAM Access */ switch (dev->ram_dl) { case 0: /* commands */ switch (val) { case 0x55: /* Disable PnP Key */ dev->pnp_enable = 0; fallthrough; case 0x5a: /* Update Hardware Configuration Data */ cs423x_pnp_enable(dev, 0, 1); break; case 0x56: /* Disable Crystal Key */ cs423x_slam_enable(dev, 0); break; case 0x57: /* Jump to ROM */ break; case 0xaa: /* Download RAM */ dev->ram_dl = 1; break; default: break; } break; case 1: /* low address byte */ dev->ram_addr = val; dev->ram_dl++; break; case 2: /* high address byte */ dev->ram_addr |= (val << 8); dev->ram_dl++; break; case 3: /* data */ dev->ram_data[dev->ram_addr++] = val; break; default: break; } break; case 6: /* RAM Access End */ /* TriGem Delhi-III BIOS writes undocumented value 0x40 instead of 0x00. */ if ((val == 0x00) || (val == 0x40)) { dev->ram_dl = 0; /* Update PnP state and resource data. */ cs423x_pnp_enable(dev, 1, 0); } break; case 7: /* Global Status */ return; default: break; } dev->regs[reg] = val; } static void cs423x_slam_write(UNUSED(uint16_t addr), uint8_t val, void *priv) { cs423x_t *dev = (cs423x_t *) priv; uint8_t idx; switch (dev->slam_state) { case CRYSTAL_SLAM_NONE: /* Not in SLAM: read and compare Crystal key. */ if (val == slam_init_key[dev->key_pos]) { dev->key_pos++; /* Was the key successfully written? */ if (!dev->key_pos) { /* Discard any pending logical device configuration, just to be safe. */ if (dev->slam_config) { free(dev->slam_config); dev->slam_config = NULL; } /* Enter SLAM. */ dev->slam_state = CRYSTAL_SLAM_INDEX; } } else { dev->key_pos = 0; } break; case CRYSTAL_SLAM_INDEX: /* Intercept the Activate Audio Device command. */ if (val == 0x79) { /* Apply the last logical device's configuration. */ if (dev->slam_config) { cs423x_pnp_config_changed(dev->slam_ld, dev->slam_config, dev); free(dev->slam_config); dev->slam_config = NULL; } /* Exit out of SLAM. */ dev->slam_state = CRYSTAL_SLAM_NONE; break; } /* Write register index. */ dev->slam_reg = val; dev->slam_state = CRYSTAL_SLAM_BYTE1; break; case CRYSTAL_SLAM_BYTE1: case CRYSTAL_SLAM_BYTE2: /* Write register value: two bytes for I/O ports, single byte otherwise. */ switch (dev->slam_reg) { case 0x06: /* Card Select Number */ isapnp_set_csn(dev->pnp_card, val); break; case 0x15: /* Logical Device ID */ /* Apply the previous logical device's configuration, and reuse its config structure. */ if (dev->slam_config) cs423x_pnp_config_changed(dev->slam_ld, dev->slam_config, dev); else dev->slam_config = (isapnp_device_config_t *) malloc(sizeof(isapnp_device_config_t)); /* Start new logical device. */ memset(dev->slam_config, 0, sizeof(isapnp_device_config_t)); dev->slam_ld = val; break; case 0x47: /* I/O Port Base Address 0 */ case 0x48: /* I/O Port Base Address 1 */ case 0x42: /* I/O Port Base Address 2 */ idx = (dev->slam_reg == 0x42) ? 2 : (dev->slam_reg - 0x47); if (dev->slam_state == CRYSTAL_SLAM_BYTE1) { /* Set high byte, or ignore it if no logical device is selected. */ if (dev->slam_config) dev->slam_config->io[idx].base = val << 8; /* Prepare for the second (low byte) write. */ dev->slam_state = CRYSTAL_SLAM_BYTE2; return; } else if (dev->slam_config) { /* Set low byte, or ignore it if no logical device is selected. */ dev->slam_config->io[idx].base |= val; } break; case 0x22: /* Interrupt Select 0 */ case 0x27: /* Interrupt Select 1 */ /* Stop if no logical device is selected. */ if (!dev->slam_config) break; /* Set IRQ value. */ idx = (dev->slam_reg == 0x22) ? 0 : 1; dev->slam_config->irq[idx].irq = val & 15; break; case 0x2a: /* DMA Select 0 */ case 0x25: /* DMA Select 1 */ /* Stop if no logical device is selected. */ if (!dev->slam_config) break; /* Set DMA value. */ idx = (dev->slam_reg == 0x2a) ? 0 : 1; dev->slam_config->dma[idx].dma = val & 7; break; case 0x33: /* Activate Device */ /* Stop if no logical device is selected. */ if (!dev->slam_config) break; /* Activate or deactivate the device. */ dev->slam_config->activate = val & 0x01; break; default: break; } /* Prepare for the next register, unless a two-byte read returns above. */ dev->slam_state = CRYSTAL_SLAM_INDEX; break; default: break; } } static void cs423x_slam_enable(cs423x_t *dev, uint8_t enable) { /* Disable SLAM. */ if (dev->slam_enable) { dev->slam_state = CRYSTAL_SLAM_NONE; dev->slam_enable = 0; io_removehandler(0x279, 1, NULL, NULL, NULL, cs423x_slam_write, NULL, NULL, dev); } /* Enable SLAM if the CKD bit is not set. */ if (enable && !(dev->ram_data[0x4002] & 0x10)) { dev->slam_enable = 1; io_sethandler(0x279, 1, NULL, NULL, NULL, cs423x_slam_write, NULL, NULL, dev); } } static void cs423x_ctxswitch_write(uint16_t addr, UNUSED(uint8_t val), void *priv) { cs423x_t *dev = (cs423x_t *) priv; uint8_t ctx = (dev->regs[7] & 0x80); uint8_t enable_opl = (dev->ad1848.xregs[4] & 0x10) && !(dev->indirect_regs[2] & 0x85); /* Check if a context switch (WSS=1 <-> SBPro=0) occurred through the address being written. */ if ((dev->regs[7] & 0x80) ? ((addr & 0xfff0) == dev->sb_base) : ((addr & 0xfffc) == dev->wss_base)) { /* Flip context bit. */ dev->regs[7] ^= 0x80; ctx ^= 0x80; /* Update CD audio filter. FIXME: not thread-safe: filter function TOCTTOU in sound_cd_thread! */ sound_set_cd_audio_filter(NULL, NULL); if (ctx) /* WSS */ sound_set_cd_audio_filter(ad1848_filter_cd_audio, &dev->ad1848); else /* SBPro */ sound_set_cd_audio_filter(sbpro_filter_cd_audio, dev->sb); /* Fire a context switch interrupt if enabled. */ if ((dev->regs[0] & 0x20) && (dev->ad1848.irq > 0)) { dev->regs[7] |= 0x40; /* set interrupt flag */ picint(1 << dev->ad1848.irq); /* control device shares IRQ with WSS and SBPro */ } } /* Update OPL ownership and state regardless of context switch, to trap writes to other registers which may disable the OPL. */ dev->sb->opl_enabled = !ctx && enable_opl; dev->opl_wss = ctx && enable_opl; } static void cs423x_get_buffer(int32_t *buffer, int len, void *priv) { cs423x_t *dev = (cs423x_t *) priv; /* Output audio from the WSS codec, and also the OPL if we're in charge of it. */ ad1848_update(&dev->ad1848); /* Don't output anything if the analog section is powered down. */ if (!(dev->indirect_regs[2] & 0xa4)) { for (int c = 0; c < len * 2; c += 2) { buffer[c] += dev->ad1848.buffer[c] / 2; buffer[c + 1] += dev->ad1848.buffer[c + 1] / 2; } } dev->ad1848.pos = 0; } static void cs423x_get_music_buffer(int32_t *buffer, int len, void *priv) { cs423x_t *dev = (cs423x_t *) priv; int opl_wss = dev->opl_wss; const int32_t *opl_buf = NULL; /* Output audio from the WSS codec, and also the OPL if we're in charge of it. */ if (opl_wss) opl_buf = dev->sb->opl.update(dev->sb->opl.priv); /* Don't output anything if the analog section is powered down. */ if (!(dev->indirect_regs[2] & 0xa4)) { for (int c = 0; c < len * 2; c += 2) { if (opl_wss) { buffer[c] += (opl_buf[c] * dev->ad1848.fm_vol_l) >> 16; buffer[c + 1] += (opl_buf[c + 1] * dev->ad1848.fm_vol_r) >> 16; } } } if (opl_wss) dev->sb->opl.reset_buffer(dev->sb->opl.priv); } static void cs423x_pnp_enable(cs423x_t *dev, uint8_t update_rom, uint8_t update_hwconfig) { if (dev->pnp_card) { /* Update PnP resource data if requested. */ if (update_rom) isapnp_update_card_rom(dev->pnp_card, &dev->ram_data[dev->pnp_offset], 384); /* Disable PnP key if the PKD bit is set, or if it was disabled by command 0x55. */ /* But wait! The TriGem Delhi-III BIOS sends command 0x55, and its behavior doesn't line up with real hardware (still listed in the POST summary and seen by software). Disable the PnP key disabling mechanism until someone figures something out. */ #if 0 isapnp_enable_card(dev->pnp_card, ((dev->ram_data[0x4002] & 0x20) || !dev->pnp_enable) ? ISAPNP_CARD_NO_KEY : ISAPNP_CARD_ENABLE); #endif if ((dev->ram_data[0x4002] & 0x20) || !dev->pnp_enable) pclog("CS423x: Attempted to disable PnP key\n"); } /* Update some register bits based on the config data in RAM if requested. */ if (update_hwconfig) { /* Update WTEN. */ if (dev->ram_data[0x4003] & 0x08) { dev->indirect_regs[8] |= 0x08; dev->ad1848.wten = 1; } else { dev->indirect_regs[8] &= ~0x08; dev->ad1848.wten = 0; } /* Update SPS. */ if (dev->type != CRYSTAL_CS4235) { if (dev->ram_data[0x4003] & 0x04) dev->indirect_regs[8] |= 0x04; else dev->indirect_regs[8] &= ~0x04; } /* Update IFM. */ if (dev->ram_data[0x4003] & 0x80) dev->ad1848.xregs[4] |= 0x10; else dev->ad1848.xregs[4] &= ~0x10; /* Inform WSS codec of the changes. */ ad1848_updatevolmask(&dev->ad1848); } } static void cs423x_pnp_config_changed(uint8_t ld, isapnp_device_config_t *config, void *priv) { cs423x_t *dev = (cs423x_t *) priv; switch (ld) { case 0: /* WSS, OPL3 and SBPro */ if (dev->wss_base) { io_removehandler(dev->wss_base, 4, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &dev->ad1848); io_removehandler(dev->wss_base, 4, NULL, NULL, NULL, cs423x_ctxswitch_write, NULL, NULL, dev); dev->wss_base = 0; } if (dev->opl_base) { io_removehandler(dev->opl_base, 4, dev->sb->opl.read, NULL, NULL, dev->sb->opl.write, NULL, NULL, dev->sb->opl.priv); dev->opl_base = 0; } if (dev->sb_base) { sb_dsp_setaddr(&dev->sb->dsp, 0); io_removehandler(dev->sb_base, 4, dev->sb->opl.read, NULL, NULL, dev->sb->opl.write, NULL, NULL, dev->sb->opl.priv); io_removehandler(dev->sb_base + 8, 2, dev->sb->opl.read, NULL, NULL, dev->sb->opl.write, NULL, NULL, dev->sb->opl.priv); io_removehandler(dev->sb_base + 4, 2, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, dev->sb); io_removehandler(dev->sb_base, 16, NULL, NULL, NULL, cs423x_ctxswitch_write, NULL, NULL, dev); dev->sb_base = 0; } ad1848_setirq(&dev->ad1848, 0); sb_dsp_setirq(&dev->sb->dsp, 0); ad1848_setdma(&dev->ad1848, 0); sb_dsp_setdma8(&dev->sb->dsp, 0); if (config->activate) { if (config->io[0].base != ISAPNP_IO_DISABLED) { dev->wss_base = config->io[0].base; io_sethandler(dev->wss_base, 4, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &dev->ad1848); io_sethandler(dev->wss_base, 4, NULL, NULL, NULL, cs423x_ctxswitch_write, NULL, NULL, dev); } if (config->io[1].base != ISAPNP_IO_DISABLED) { dev->opl_base = config->io[1].base; io_sethandler(dev->opl_base, 4, dev->sb->opl.read, NULL, NULL, dev->sb->opl.write, NULL, NULL, dev->sb->opl.priv); } if (config->io[2].base != ISAPNP_IO_DISABLED) { dev->sb_base = config->io[2].base; sb_dsp_setaddr(&dev->sb->dsp, dev->sb_base); io_sethandler(dev->sb_base, 4, dev->sb->opl.read, NULL, NULL, dev->sb->opl.write, NULL, NULL, dev->sb->opl.priv); io_sethandler(dev->sb_base + 8, 2, dev->sb->opl.read, NULL, NULL, dev->sb->opl.write, NULL, NULL, dev->sb->opl.priv); io_sethandler(dev->sb_base + 4, 2, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, dev->sb); io_sethandler(dev->sb_base, 16, NULL, NULL, NULL, cs423x_ctxswitch_write, NULL, NULL, dev); } if (config->irq[0].irq != ISAPNP_IRQ_DISABLED) { ad1848_setirq(&dev->ad1848, config->irq[0].irq); sb_dsp_setirq(&dev->sb->dsp, config->irq[0].irq); } if (config->dma[0].dma != ISAPNP_DMA_DISABLED) { ad1848_setdma(&dev->ad1848, config->dma[0].dma); sb_dsp_setdma8(&dev->sb->dsp, config->dma[0].dma); } } break; case 1: /* Game Port */ if (dev->gameport) gameport_remap(dev->gameport, (config->activate && (config->io[0].base != ISAPNP_IO_DISABLED)) ? config->io[0].base : 0); break; case 2: /* Control Registers */ if (dev->ctrl_base) { io_removehandler(dev->ctrl_base, 8, cs423x_read, NULL, NULL, cs423x_write, NULL, NULL, dev); dev->ctrl_base = 0; } if (config->activate && (config->io[0].base != ISAPNP_IO_DISABLED)) { dev->ctrl_base = config->io[0].base; io_sethandler(dev->ctrl_base, 8, cs423x_read, NULL, NULL, cs423x_write, NULL, NULL, dev); } break; case 3: /* MPU-401 */ mpu401_change_addr(dev->sb->mpu, 0); mpu401_setirq(dev->sb->mpu, 0); if (config->activate) { if (config->io[0].base != ISAPNP_IO_DISABLED) mpu401_change_addr(dev->sb->mpu, config->io[0].base); if (config->irq[0].irq != ISAPNP_IRQ_DISABLED) mpu401_setirq(dev->sb->mpu, config->irq[0].irq); } break; default: break; } } static void cs423x_reset(void *priv) { cs423x_t *dev = (cs423x_t *) priv; /* Clear RAM. */ memset(dev->ram_data, 0, sizeof(dev->ram_data)); if (dev->eeprom) { /* Load EEPROM data to RAM. */ memcpy(&dev->ram_data[0x4000], &dev->eeprom_data[4], MIN(384, ((dev->eeprom_data[2] << 8) | dev->eeprom_data[3]) - 4)); /* Save EEPROM contents to file. */ cs423x_nvram(dev, 1); } /* Reset registers. */ memset(dev->regs, 0, sizeof(dev->regs)); dev->regs[1] = 0x80; memset(dev->indirect_regs, 0, sizeof(dev->indirect_regs)); dev->indirect_regs[1] = dev->type; if (dev->type == CRYSTAL_CS4238B) dev->indirect_regs[2] = 0x20; /* Reset WSS codec. */ ad1848_init(&dev->ad1848, dev->ad1848_type); /* Reset PnP resource data, state and logical devices. */ dev->pnp_enable = 1; cs423x_pnp_enable(dev, 1, 1); if (dev->pnp_card && dev->sb) isapnp_reset_card(dev->pnp_card); /* Reset SLAM. */ cs423x_slam_enable(dev, 1); } static void * cs423x_init(const device_t *info) { cs423x_t *dev = malloc(sizeof(cs423x_t)); memset(dev, 0, sizeof(cs423x_t)); /* Initialize model-specific data. */ dev->type = info->local & 0xff; switch (dev->type) { case CRYSTAL_CS4235: case CRYSTAL_CS4236B: case CRYSTAL_CS4237B: case CRYSTAL_CS4238B: /* Same WSS codec and EEPROM structure. */ dev->ad1848_type = (dev->type == CRYSTAL_CS4235) ? AD1848_TYPE_CS4235 : AD1848_TYPE_CS4236; dev->pnp_offset = 0x4013; /* Different Chip Version and ID registers, which shouldn't be reset by ad1848_init */ dev->ad1848.xregs[25] = dev->type; if (!(info->local & CRYSTAL_NOEEPROM)) { /* Load EEPROM contents from template. */ memcpy(dev->eeprom_data, cs4236b_eeprom, sizeof(cs4236b_eeprom)); FILE *fp = rom_fopen(PNP_ROM_CS4236B, "rb"); if (fp) { (void) !fread(&(dev->eeprom_data[23]), 1, 8201, fp); fclose(fp); } /* Set content size. */ dev->eeprom_data[2] = sizeof(cs4236b_eeprom) >> 8; dev->eeprom_data[3] = sizeof(cs4236b_eeprom) & 0xff; /* Set PnP card ID and EEPROM file name. */ switch (dev->type) { case CRYSTAL_CS4235: dev->eeprom_data[8] = 0x05; dev->eeprom_data[16] = 0x08; dev->eeprom_data[26] = 0x25; dev->eeprom_data[44] = '5'; dev->nvr_path = "cs4235.nvr"; break; case CRYSTAL_CS4236B: dev->nvr_path = "cs4236b.nvr"; break; case CRYSTAL_CS4237B: dev->eeprom_data[26] = 0x37; dev->eeprom_data[44] = '7'; dev->nvr_path = "cs4237b.nvr"; break; case CRYSTAL_CS4238B: dev->eeprom_data[26] = 0x38; dev->eeprom_data[44] = '8'; dev->nvr_path = "cs4238b.nvr"; break; default: break; } /* Load EEPROM contents from file if present. */ cs423x_nvram(dev, 0); } /* Initialize game port. The '7B and '8B game port only responds to 6 I/O ports; the remaining 2 ports are reserved on those chips, and probably connected to the Digital Assist feature. */ dev->gameport = gameport_add(((dev->type == CRYSTAL_CS4235) || (dev->type == CRYSTAL_CS4236B)) ? &gameport_pnp_device : &gameport_pnp_6io_device); break; default: break; } /* Initialize I2C bus for the EEPROM. */ dev->i2c = i2c_gpio_init("nvr_cs423x"); /* Initialize I2C EEPROM if the contents are valid. */ if ((dev->eeprom_data[0] == 0x55) && (dev->eeprom_data[1] == 0xbb)) dev->eeprom = i2c_eeprom_init(i2c_gpio_get_bus(dev->i2c), 0x50, dev->eeprom_data, sizeof(dev->eeprom_data), 1); /* Initialize ISAPnP. */ dev->pnp_card = isapnp_add_card(NULL, 0, cs423x_pnp_config_changed, NULL, NULL, NULL, dev); /* Initialize SBPro codec. The WSS codec is initialized later by cs423x_reset */ dev->sb = device_add_inst(&sb_pro_compat_device, 1); sound_set_cd_audio_filter(sbpro_filter_cd_audio, dev->sb); /* CD audio filter for the default context */ /* Initialize RAM, registers and WSS codec. */ cs423x_reset(dev); sound_add_handler(cs423x_get_buffer, dev); music_add_handler(cs423x_get_music_buffer, dev); /* Add Control/RAM backdoor handlers for CS4235. */ dev->ad1848.cram_priv = dev; dev->ad1848.cram_read = cs423x_read; dev->ad1848.cram_write = cs423x_write; return dev; } static void cs423x_close(void *priv) { cs423x_t *dev = (cs423x_t *) priv; /* Save EEPROM contents to file. */ if (dev->eeprom) { cs423x_nvram(dev, 1); i2c_eeprom_close(dev->eeprom); } i2c_gpio_close(dev->i2c); free(dev); } static int cs423x_available(void) { return rom_present(PNP_ROM_CS4236B); } static void cs423x_speed_changed(void *priv) { cs423x_t *dev = (cs423x_t *) priv; ad1848_speed_changed(&dev->ad1848); } const device_t cs4235_device = { .name = "Crystal CS4235", .internal_name = "cs4235", .flags = DEVICE_ISA | DEVICE_AT, .local = CRYSTAL_CS4235, .init = cs423x_init, .close = cs423x_close, .reset = cs423x_reset, { .available = cs423x_available }, .speed_changed = cs423x_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t cs4235_onboard_device = { .name = "Crystal CS4235 (On-Board)", .internal_name = "cs4235_onboard", .flags = DEVICE_ISA | DEVICE_AT, .local = CRYSTAL_CS4235 | CRYSTAL_NOEEPROM, .init = cs423x_init, .close = cs423x_close, .reset = cs423x_reset, { .available = cs423x_available }, .speed_changed = cs423x_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t cs4236b_device = { .name = "Crystal CS4236B", .internal_name = "cs4236b", .flags = DEVICE_ISA | DEVICE_AT, .local = CRYSTAL_CS4236B, .init = cs423x_init, .close = cs423x_close, .reset = cs423x_reset, { .available = cs423x_available }, .speed_changed = cs423x_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t cs4237b_device = { .name = "Crystal CS4237B", .internal_name = "cs4237b", .flags = DEVICE_ISA | DEVICE_AT, .local = CRYSTAL_CS4237B, .init = cs423x_init, .close = cs423x_close, .reset = cs423x_reset, { .available = cs423x_available }, .speed_changed = cs423x_speed_changed, .force_redraw = NULL, .config = NULL }; const device_t cs4238b_device = { .name = "Crystal CS4238B", .internal_name = "cs4238b", .flags = DEVICE_ISA | DEVICE_AT, .local = CRYSTAL_CS4238B, .init = cs423x_init, .close = cs423x_close, .reset = cs423x_reset, { .available = cs423x_available }, .speed_changed = cs423x_speed_changed, .force_redraw = NULL, .config = NULL }; ```
/content/code_sandbox/src/sound/snd_cs423x.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
8,929
```c #include <stdint.h> #include <stdio.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/snd_ym7128.h> #include <86box/plat_unused.h> static int attenuation[32]; static int tap_position[32]; void ym7128_init(UNUSED(ym7128_t *ym7128)) { int c; double out = 65536.0; for (c = 0; c < 32; c++) tap_position[c] = c * (2400 / 31); for (c = 31; c >= 1; c--) { attenuation[c] = (int) out; out /= 1.25963; /*2 dB steps*/ } attenuation[0] = 0; } #define GET_ATTENUATION(val) (val & 0x20) ? -attenuation[val & 0x1f] : attenuation[val & 0x1f] void ym7128_write(ym7128_t *ym7128, uint8_t val) { int new_dat = val & 1; int new_sci = val & 2; int new_a0 = val & 4; if (!ym7128->sci && new_sci) ym7128->dat = (ym7128->dat << 1) | new_dat; if (ym7128->a0 != new_a0) { if (!ym7128->a0) ym7128->reg_sel = ym7128->dat & 0x1f; else { switch (ym7128->reg_sel) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: ym7128->gl[ym7128->reg_sel & 7] = GET_ATTENUATION(ym7128->dat); break; case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: ym7128->gr[ym7128->reg_sel & 7] = GET_ATTENUATION(ym7128->dat); break; case 0x10: ym7128->vm = GET_ATTENUATION(ym7128->dat); break; case 0x11: ym7128->vc = GET_ATTENUATION(ym7128->dat); break; case 0x12: ym7128->vl = GET_ATTENUATION(ym7128->dat); break; case 0x13: ym7128->vr = GET_ATTENUATION(ym7128->dat); break; case 0x14: ym7128->c0 = (ym7128->dat & 0x3f) << 6; if (ym7128->dat & 0x20) ym7128->c0 |= 0xfffff000; break; case 0x15: ym7128->c1 = (ym7128->dat & 0x3f) << 6; if (ym7128->dat & 0x20) ym7128->c1 |= 0xfffff000; break; case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: ym7128->t[ym7128->reg_sel - 0x16] = tap_position[ym7128->dat & 0x1f]; break; default: break; } ym7128->regs[ym7128->reg_sel] = ym7128->dat; } ym7128->dat = 0; } ym7128->sci = new_sci; ym7128->a0 = new_a0; } #define GET_DELAY_SAMPLE(ym7128, offset) (((ym7128->delay_pos - offset) < 0) ? ym7128->delay_buffer[(ym7128->delay_pos - offset) + 2400] : ym7128->delay_buffer[ym7128->delay_pos - offset]) void ym7128_apply(ym7128_t *ym7128, int16_t *buffer, int len) { for (int c = 0; c < len * 2; c += 4) { /*YM7128 samples a mono stream at ~24 kHz, so downsample*/ int32_t samp = ((int32_t) buffer[c] + (int32_t) buffer[c + 1] + (int32_t) buffer[c + 2] + (int32_t) buffer[c + 3]) / 4; int32_t filter_temp; int32_t filter_out; int32_t samp_l = 0; int32_t samp_r = 0; filter_temp = GET_DELAY_SAMPLE(ym7128, ym7128->t[0]); filter_out = ((filter_temp * ym7128->c0) >> 11) + ((ym7128->filter_dat * ym7128->c1) >> 11); filter_out = (filter_out * ym7128->vc) >> 16; samp = (samp * ym7128->vm) >> 16; samp += filter_out; ym7128->delay_buffer[ym7128->delay_pos] = samp; for (uint8_t d = 0; d < 8; d++) { samp_l += (GET_DELAY_SAMPLE(ym7128, ym7128->t[d + 1]) * ym7128->gl[d]) >> 16; samp_r += (GET_DELAY_SAMPLE(ym7128, ym7128->t[d + 1]) * ym7128->gr[d]) >> 16; } samp_l = (samp_l * ym7128->vl * 2) >> 16; samp_r = (samp_r * ym7128->vr * 2) >> 16; buffer[c] += (samp_l + (int32_t) ym7128->prev_l) / 2; buffer[c + 1] += (samp_r + (int32_t) ym7128->prev_r) / 2; buffer[c + 2] += samp_l; buffer[c + 3] += samp_r; ym7128->delay_pos++; if (ym7128->delay_pos >= 2400) ym7128->delay_pos = 0; ym7128->filter_dat = filter_temp; ym7128->prev_l = samp_l; ym7128->prev_r = samp_r; } } ```
/content/code_sandbox/src/sound/snd_ym7128.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,616
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Ensoniq AudioPCI family emulation. * * * * Authors: Sarah Walker, <path_to_url * RichardG, <richardg867@gmail.com> * Miran Grca, <mgrca8@gmail.com> * */ #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define _USE_MATH_DEFINES #include <math.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/gameport.h> #include <86box/io.h> #include <86box/mem.h> #include <86box/midi.h> #include <86box/nmi.h> #include <86box/pci.h> #include <86box/snd_ac97.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/plat_unused.h> #define N 16 #define ES1371_NCoef 91 static float low_fir_es1371_coef[ES1371_NCoef]; typedef struct es1371_t { uint8_t pci_command; uint8_t pci_serr; uint8_t subsys_lock; uint8_t subsys_id[4]; uint32_t base_addr; uint8_t int_line; uint8_t irq_state; uint16_t pmcsr; uint32_t int_ctrl; uint32_t int_status; uint32_t legacy_ctrl; uint32_t spdif_chstatus; void *gameport; int mem_page; uint32_t si_cr; uint32_t sr_cir; uint16_t sr_ram[128]; uint8_t uart_data; uint8_t uart_ctrl; uint8_t uart_status; uint8_t uart_res; uint32_t uart_fifo[8]; uint8_t read_fifo_pos; uint8_t write_fifo_pos; ac97_codec_t *codec; uint32_t codec_ctrl; struct { uint32_t addr; uint32_t addr_latch; uint16_t count; uint16_t size; uint16_t samp_ct; int curr_samp_ct; pc_timer_t timer; uint64_t latch; uint32_t vf; uint32_t ac; int16_t buffer_l[64]; int16_t buffer_r[64]; int buffer_pos; int buffer_pos_end; int filtered_l[32]; int filtered_r[32]; int f_pos; int16_t out_l; int16_t out_r; int32_t vol_l; int32_t vol_r; } dac[2], adc; int64_t dac_latch; int64_t dac_time; int master_vol_l; int master_vol_r; int pcm_vol_l; int pcm_vol_r; int pcm_rear_vol_l; int pcm_rear_vol_r; int cd_vol_l; int cd_vol_r; uint8_t pci_slot; int pos; int16_t buffer[SOUNDBUFLEN * 2]; uint32_t type; } es1371_t; #define AUDIOPCI_ES1371 0x13710200 #define AUDIOPCI_ES1373 0x13710400 #define AUDIOPCI_CT5880 0x58800400 #define LEGACY_SB_ADDR (1 << 29) #define LEGACY_SSCAPE_ADDR_SHIFT 27 #define LEGACY_CODEC_ADDR_SHIFT 25 #define LEGACY_FORCE_IRQ (1 << 24) #define LEGACY_CAPTURE_SLAVE_DMA (1 << 23) #define LEGACY_CAPTURE_SLAVE_PIC (1 << 22) #define LEGACY_CAPTURE_MASTER_DMA (1 << 21) #define LEGACY_CAPTURE_MASTER_PIC (1 << 20) #define LEGACY_CAPTURE_ADLIB (1 << 19) #define LEGACY_CAPTURE_SB (1 << 18) #define LEGACY_CAPTURE_CODEC (1 << 17) #define LEGACY_CAPTURE_SSCAPE (1 << 16) #define LEGACY_EVENT_SSCAPE (0 << 8) #define LEGACY_EVENT_CODEC (1 << 8) #define LEGACY_EVENT_SB (2 << 8) #define LEGACY_EVENT_ADLIB (3 << 8) #define LEGACY_EVENT_MASTER_PIC (4 << 8) #define LEGACY_EVENT_MASTER_DMA (5 << 8) #define LEGACY_EVENT_SLAVE_PIC (6 << 8) #define LEGACY_EVENT_SLAVE_DMA (7 << 8) #define LEGACY_EVENT_MASK (7 << 8) #define LEGACY_EVENT_ADDR_SHIFT 3 #define LEGACY_EVENT_ADDR_MASK (0x1f << 3) #define LEGACY_EVENT_TYPE_RW (1 << 2) #define LEGACY_INT (1 << 0) #define SRC_RAM_WE (1 << 24) #define CODEC_READ (1 << 23) #define CODEC_READY (1 << 31) #define INT_DAC1_BYPASS (1 << 31) #define INT_DAC2_BYPASS (1 << 30) #define INT_DAC1_EN (1 << 6) #define INT_DAC2_EN (1 << 5) #define INT_UART_EN (1 << 3) #define SI_P2_PAUSE (1 << 12) #define SI_P1_PAUSE (1 << 11) #define SI_P2_INTR_EN (1 << 9) #define SI_P1_INTR_EN (1 << 8) #define INT_STATUS_INTR (1 << 31) #define INT_STATUS_REAR_B27 (1 << 27) #define INT_STATUS_REAR_B26 (1 << 26) #define INT_STATUS_REAR_B24 (1 << 24) #define INT_STATUS_UART (1 << 3) #define INT_STATUS_DAC1 (1 << 2) #define INT_STATUS_DAC2 (1 << 1) #define UART_CTRL_RXINTEN (1 << 7) #define UART_CTRL_TXINTEN (3 << 5) #define UART_STATUS_RXINT (1 << 7) #define UART_STATUS_TXINT (1 << 2) #define UART_STATUS_TXRDY (1 << 1) #define UART_STATUS_RXRDY (1 << 0) #define UART_FIFO_BYTE_VALID 0x00000100 #define FORMAT_MONO_8 0 #define FORMAT_STEREO_8 1 #define FORMAT_MONO_16 2 #define FORMAT_STEREO_16 3 static void es1371_fetch(es1371_t *dev, int dac_nr); static void update_legacy(es1371_t *dev, uint32_t old_legacy_ctrl); #ifdef ENABLE_AUDIOPCI_LOG int audiopci_do_log = ENABLE_AUDIOPCI_LOG; static void audiopci_log(const char *fmt, ...) { va_list ap; if (audiopci_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define audiopci_log(fmt, ...) #endif static void es1371_update_irqs(es1371_t *dev) { int irq = 0; if ((dev->int_status & INT_STATUS_DAC1) && (dev->si_cr & SI_P1_INTR_EN)) irq = 1; if ((dev->int_status & INT_STATUS_DAC2) && (dev->si_cr & SI_P2_INTR_EN)) irq = 1; dev->int_status &= ~INT_STATUS_UART; if ((dev->uart_status & UART_STATUS_TXINT) || (dev->uart_status & UART_STATUS_RXINT)) { dev->int_status |= INT_STATUS_UART; irq = 1; } if (irq) dev->int_status |= INT_STATUS_INTR; else dev->int_status &= ~INT_STATUS_INTR; if (dev->legacy_ctrl & LEGACY_FORCE_IRQ) irq = 1; if (irq) pci_set_irq(dev->pci_slot, PCI_INTA, &dev->irq_state); else pci_clear_irq(dev->pci_slot, PCI_INTA, &dev->irq_state); } static void es1371_update_tx_irq(es1371_t *dev) { dev->uart_status &= ~UART_STATUS_TXINT; if (((dev->uart_ctrl & UART_CTRL_TXINTEN) == 0x20) && (dev->uart_status & UART_STATUS_TXRDY)) dev->uart_status |= UART_STATUS_TXINT; es1371_update_irqs(dev); } static void es1371_set_tx_irq(es1371_t *dev, int set) { dev->uart_status &= ~UART_STATUS_TXRDY; if (set) dev->uart_status |= UART_STATUS_TXRDY; es1371_update_tx_irq(dev); } static void es1371_update_rx_irq(es1371_t *dev) { dev->uart_status &= ~UART_STATUS_RXINT; if ((dev->uart_ctrl & UART_CTRL_RXINTEN) && (dev->uart_status & UART_STATUS_RXRDY)) dev->uart_status |= UART_STATUS_RXINT; es1371_update_irqs(dev); } static void es1371_set_rx_irq(es1371_t *dev, int set) { dev->uart_status &= ~UART_STATUS_RXRDY; if (set) dev->uart_status |= UART_STATUS_RXRDY; es1371_update_rx_irq(dev); } static void es1371_scan_fifo(es1371_t *dev) { if (dev->read_fifo_pos != dev->write_fifo_pos) { dev->uart_data = dev->uart_fifo[dev->read_fifo_pos]; dev->read_fifo_pos = (dev->read_fifo_pos + 1) & 7; es1371_set_rx_irq(dev, 1); } else es1371_set_rx_irq(dev, 0); } static void es1371_write_fifo(es1371_t *dev, uint8_t val) { if (dev->write_fifo_pos < 8) { dev->uart_fifo[dev->write_fifo_pos] = val | UART_FIFO_BYTE_VALID; dev->write_fifo_pos = (dev->write_fifo_pos + 1) & 7; } } static void es1371_reset_fifo(es1371_t *dev) { for (uint8_t i = 0; i < 8; i++) dev->uart_fifo[i] = 0x00000000; dev->read_fifo_pos = dev->write_fifo_pos = 0; es1371_set_rx_irq(dev, 0); } static void es1371_reset(void *priv) { es1371_t *dev = (es1371_t *) priv; nmi = 0; /* Default subsystem ID. */ dev->subsys_lock = 0x00; *((uint16_t *) &dev->subsys_id[0]) = 0x1274; *((uint16_t *) &dev->subsys_id[2]) = 0x1371; /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ dev->int_ctrl = 0xfcff0000; /* Interrupt/Chip Select Status Register, Address 04H Addressable as longword only */ if (dev->type >= AUDIOPCI_CT5880) dev->int_status = 0x52080ec0; else if (dev->type >= AUDIOPCI_ES1373) dev->int_status = 0x7f080ec0; else dev->int_status = 0x7ffffec0; /* UART Status Register, Address 09H Addressable as byte only */ dev->uart_status = 0xff; /* UART Control Register, Address 09H Addressable as byte only */ dev->uart_ctrl = 0x00; /* UART Reserved Register, Address 0AH Addressable as byte only */ dev->uart_res = 0xff; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ dev->mem_page = 0xf0; /* FIXME: hardware reads 0xfffffff0 */ /* Sample Rate Converter Interface Register, Address 10H Addressable as longword only */ dev->sr_cir = 0x00470000; /* CODEC Write Register, Address 14H Addressable as longword only */ dev->codec_ctrl = 0x00000000; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ dev->legacy_ctrl = 0x0000f801; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ dev->spdif_chstatus = 0xc0200004; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ dev->si_cr = 0xff800000; /* DAC1 Channel Sample Count Register, Address 24H Addressable as word, longword */ dev->dac[0].samp_ct = 0x00000000; /* FIXME: hardware reads 0x00010000 */ dev->dac[0].curr_samp_ct = 0x00000000; /* DAC2 Channel Sample Count Register, Address 28H Addressable as word, longword */ dev->dac[1].samp_ct = 0x00000000; /* FIXME: hardware reads 0x00010000 */ dev->dac[1].curr_samp_ct = 0x00000000; /* ADC Channel Sample Count Register, Address 2CH Addressable as word, longword */ dev->adc.samp_ct = 0x00000000; /* FIXME: hardware reads 0x00010000 */ dev->adc.curr_samp_ct = 0x00000000; /* DAC1 Frame Register 1, Address 30H, Memory Page 1100b Addressable as longword only */ dev->dac[0].addr_latch = 0x00000000; /* DAC1 Frame Register 2, Address 34H, Memory Page 1100b Addressable as longword only */ dev->dac[0].size = 0x00000000; dev->dac[0].count = 0x00000000; /* DAC2 Frame Register 1, Address 38H, Memory Page 1100b Addressable as longword only */ dev->dac[1].addr_latch = 0x00000000; /* DAC2 Frame Register 2, Address 3CH, Memory Page 1100b Addressable as longword only */ dev->dac[1].size = 0x00000000; dev->dac[1].count = 0x00000000; /* ADC Frame Register 1, Address 30H, Memory Page 1101b Addressable as longword only */ dev->adc.addr_latch = 0x00000000; /* ADC Frame Register 2, Address 34H, Memory Page 1101b Addressable as longword only */ dev->adc.size = 0x00000000; dev->adc.count = 0x00000000; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ for (uint8_t i = 0; i < 8; i++) dev->uart_fifo[i] = 0xffff0000; /* Reset the UART TX. */ es1371_set_tx_irq(dev, 0); /* Reset the UART (RX) FIFO. */ es1371_reset_fifo(dev); /* Update interrupts to ensure they're all correctly cleared. */ es1371_update_irqs(dev); } static uint32_t es1371_read_frame_reg(es1371_t *dev, int frame, int page) { uint32_t ret = 0xffffffff; switch (frame) { case 0x30: switch (page) { /* DAC1 Frame Register 1, Address 30H, Memory Page 1100b Addressable as longword only */ case 0xc: ret = dev->dac[0].addr_latch; break; /* ADC Frame Register 1, Address 30H, Memory Page 1101b Addressable as longword only */ case 0xd: ret = dev->adc.addr_latch; break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[30:%02X] ret = dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]); ret = dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]; break; default: break; } break; case 0x34: switch (page) { /* DAC1 Frame Register 2, Address 34H, Memory Page 1100b Addressable as longword only */ case 0xc: ret = dev->dac[0].size | (dev->dac[0].count << 16); break; /* ADC Frame Register 2, Address 34H, Memory Page 1101b Addressable as longword only */ case 0xd: ret = dev->adc.size | (dev->adc.count << 16); break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[34:%02X] ret = dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]); ret = dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]; break; default: break; } break; case 0x38: switch (page) { /* DAC2 Frame Register 1, Address 38H, Memory Page 1100b Addressable as longword only */ case 0xc: ret = dev->dac[1].addr_latch; break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[38:%02X] ret = dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]); ret = dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]; break; default: break; } break; case 0x3c: switch (page) { /* DAC2 Frame Register 2, Address 3CH, Memory Page 1100b Addressable as longword only */ case 0xc: ret = dev->dac[1].size | (dev->dac[1].count << 16); break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[3C:%02X] ret = dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]); ret = dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)]; break; default: break; } break; default: break; } return ret; } static void es1371_write_frame_reg(es1371_t *dev, int frame, int page, uint32_t val) { switch (frame) { case 0x30: switch (page) { /* DAC1 Frame Register 1, Address 30H, Memory Page 1100b Addressable as longword only */ case 0xc: dev->dac[0].addr_latch = val; break; /* ADC Frame Register 1, Address 30H, Memory Page 1101b Addressable as longword only */ case 0xd: dev->adc.addr_latch = val; break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[30:%02X] dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), val); dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)] = val; break; default: break; } break; case 0x34: switch (page) { /* DAC1 Frame Register 2, Address 34H, Memory Page 1100b Addressable as longword only */ case 0xc: dev->dac[0].size = val & 0xffff; dev->dac[0].count = val >> 16; break; /* ADC Frame Register 2, Address 34H, Memory Page 1101b Addressable as longword only */ case 0xd: dev->adc.size = val & 0xffff; dev->adc.count = val >> 16; break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[34:%02X] dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), val); dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)] = val; break; default: break; } break; case 0x38: switch (page) { /* DAC2 Frame Register 1, Address 38H, Memory Page 1100b Addressable as longword only */ case 0xc: dev->dac[1].addr_latch = val; break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[38:%02X] dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), val); dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)] = val; break; default: break; } break; case 0x3c: switch (page) { /* DAC2 Frame Register 2, Address 3CH, Memory Page 1100b Addressable as longword only */ case 0xc: dev->dac[1].size = val & 0xffff; dev->dac[1].count = val >> 16; break; /* UART FIFO Register, Address 30H, 34H, 38H, 3CH, Memory Page 1110b, 1111b Addressable as longword only */ case 0xe: case 0xf: audiopci_log("[3C:%02X] dev->uart_fifo[%02X] = %08X\n", page, ((page & 0x01) << 2) + ((frame >> 2) & 0x03), val); dev->uart_fifo[((page & 0x01) << 2) + ((frame >> 2) & 0x03)] = val; break; default: break; } break; default: break; } if (page == 0x0e || page == 0x0f) { audiopci_log("Write frame = %02x, page = %02x, uart fifo = %08x, val = %02x\n", frame, page, dev->uart_fifo, val); } } static uint8_t es1371_inb(uint16_t port, void *priv) { es1371_t *dev = (es1371_t *) priv; uint8_t ret = 0xff; switch (port & 0x3f) { /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ case 0x00: ret = dev->int_ctrl & 0xff; break; case 0x01: ret = (dev->int_ctrl >> 8) & 0xff; break; case 0x02: ret = (dev->int_ctrl >> 16) & 0x0f; break; case 0x03: ret = dev->int_ctrl >> 24; if (dev->type < AUDIOPCI_ES1373) ret |= 0xfc; break; /* Interrupt/Chip Select Status Register, Address 04H Addressable as longword only, but PCem implements byte access, which must be for a reason */ case 0x04: ret = dev->int_status & 0xff; audiopci_log("[R] STATUS 0- 7 = %02X\n", ret); break; case 0x05: ret = (dev->int_status >> 8) & 0xff; audiopci_log("[R] STATUS 8-15 = %02X\n", ret); break; case 0x06: ret = (dev->int_status >> 16) & 0xff; audiopci_log("[R] STATUS 16-23 = %02X\n", ret); break; case 0x07: ret = (dev->int_status >> 24) & 0xff; audiopci_log("[R] STATUS 24-31 = %02X\n", ret); break; /* UART Data Register, Address 08H Addressable as byte only */ case 0x08: ret = dev->uart_data; es1371_set_rx_irq(dev, 0); audiopci_log("[R] UART DATA = %02X\n", ret); break; /* UART Status Register, Address 09H Addressable as byte only */ case 0x09: ret = dev->uart_status & 0x87; audiopci_log("ES1371 UART Status = %02x\n", dev->uart_status); break; /* UART Reserved Register, Address 0AH Addressable as byte only */ case 0x0a: ret = dev->uart_res & 0x01; audiopci_log("[R] UART RES = %02X\n", ret); break; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ case 0x0c: ret = dev->mem_page; break; case 0x0d ... 0x0e: ret = 0x00; break; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ case 0x18: ret = dev->legacy_ctrl & 0xfd; break; case 0x19: ret = ((dev->legacy_ctrl >> 8) & 0x07) | 0xf8; break; case 0x1a: ret = dev->legacy_ctrl >> 16; break; case 0x1b: ret = dev->legacy_ctrl >> 24; break; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ case 0x1c: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus & 0xff; break; case 0x1d: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus >> 8; break; case 0x1e: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus >> 16; break; case 0x1f: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus >> 24; break; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ case 0x20: ret = dev->si_cr & 0xff; break; case 0x21: ret = dev->si_cr >> 8; break; case 0x22: ret = (dev->si_cr >> 16) | 0x80; break; case 0x23: ret = 0xff; break; default: audiopci_log("Bad es1371_inb: port=%04x\n", port); } audiopci_log("es1371_inb: port=%04x ret=%02x\n", port, ret); return ret; } static uint16_t es1371_inw(uint16_t port, void *priv) { es1371_t *dev = (es1371_t *) priv; uint16_t ret = 0xffff; switch (port & 0x3e) { /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ case 0x00: ret = dev->int_ctrl & 0xffff; break; case 0x02: ret = (dev->int_ctrl >> 16) & 0xff0f; if (dev->type < AUDIOPCI_ES1373) ret |= 0xfc00; break; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ case 0x0c: ret = dev->mem_page; break; case 0x0e: ret = 0x0000; break; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ case 0x18: ret = (dev->legacy_ctrl & 0x07fd) | 0xf800; break; case 0x1a: ret = dev->legacy_ctrl >> 16; break; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ case 0x1c: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus & 0xffff; break; case 0x1e: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus >> 16; break; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ case 0x20: ret = dev->si_cr & 0xffff; break; case 0x22: ret = (dev->si_cr >> 16) | 0xff80; break; /* DAC1 Channel Sample Count Register, Address 24H Addressable as word, longword */ case 0x24: ret = dev->dac[0].samp_ct; break; case 0x26: ret = dev->dac[0].curr_samp_ct; break; /* DAC2 Channel Sample Count Register, Address 28H Addressable as word, longword */ case 0x28: ret = dev->dac[1].samp_ct; break; case 0x2a: ret = dev->dac[1].curr_samp_ct; break; /* ADC Channel Sample Count Register, Address 2CH Addressable as word, longword */ case 0x2c: ret = dev->adc.samp_ct; break; case 0x2e: ret = dev->adc.curr_samp_ct; break; case 0x30: case 0x34: case 0x38: case 0x3c: ret = es1371_read_frame_reg(dev, port & 0x3c, dev->mem_page) & 0xffff; break; case 0x32: case 0x36: case 0x3a: case 0x3e: ret = es1371_read_frame_reg(dev, port & 0x3c, dev->mem_page) >> 16; break; default: break; } audiopci_log("es1371_inw: port=%04x ret=%04x\n", port, ret); return ret; } static uint32_t es1371_inl(uint16_t port, void *priv) { es1371_t *dev = (es1371_t *) priv; uint32_t ret = 0xffffffff; switch (port & 0x3c) { /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ case 0x00: ret = dev->int_ctrl & 0xff0fffff; if (ret < AUDIOPCI_ES1373) ret |= 0xfc000000; break; /* Interrupt/Chip Select Status Register, Address 04H Addressable as longword only */ case 0x04: ret = dev->int_status; audiopci_log("[R] STATUS = %08X\n", ret); break; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ case 0x0c: ret = dev->mem_page; break; /* Sample Rate Converter Interface Register, Address 10H Addressable as longword only */ case 0x10: ret = dev->sr_cir & ~0xffff; ret |= dev->sr_ram[dev->sr_cir >> 25]; break; /* CODEC Read Register, Address 14H Addressable as longword only */ case 0x14: ret = dev->codec_ctrl | CODEC_READY; break; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ case 0x18: ret = (dev->legacy_ctrl & 0xffff07fd) | 0x0000f800; break; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ case 0x1c: if (dev->type >= AUDIOPCI_ES1373) ret = dev->spdif_chstatus; break; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ case 0x20: ret = dev->si_cr | 0xff800000; break; /* DAC1 Channel Sample Count Register, Address 24H Addressable as word, longword */ case 0x24: ret = dev->dac[0].samp_ct | (((uint32_t) dev->dac[0].curr_samp_ct) << 16); break; /* DAC2 Channel Sample Count Register, Address 28H Addressable as word, longword */ case 0x28: ret = dev->dac[1].samp_ct | (((uint32_t) dev->dac[1].curr_samp_ct) << 16); break; /* ADC Channel Sample Count Register, Address 2CH Addressable as word, longword */ case 0x2c: ret = dev->adc.samp_ct | (((uint32_t) dev->adc.curr_samp_ct) << 16); break; case 0x30: case 0x34: case 0x38: case 0x3c: ret = es1371_read_frame_reg(dev, port & 0x3c, dev->mem_page); break; default: break; } audiopci_log("es1371_inl: port=%04x ret=%08x\n", port, ret); return ret; } static void es1371_outb(uint16_t port, uint8_t val, void *priv) { es1371_t *dev = (es1371_t *) priv; uint32_t old_legacy_ctrl; audiopci_log("es1371_outb: port=%04x val=%02x\n", port, val); switch (port & 0x3f) { /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ case 0x00: if (!(dev->int_ctrl & INT_DAC1_EN) && (val & INT_DAC1_EN)) { dev->dac[0].addr = dev->dac[0].addr_latch; dev->dac[0].buffer_pos = 0; dev->dac[0].buffer_pos_end = 0; es1371_fetch(dev, 0); } if (!(dev->int_ctrl & INT_DAC2_EN) && (val & INT_DAC2_EN)) { dev->dac[1].addr = dev->dac[1].addr_latch; dev->dac[1].buffer_pos = 0; dev->dac[1].buffer_pos_end = 0; es1371_fetch(dev, 1); } dev->int_ctrl = (dev->int_ctrl & 0xffffff00) | val; break; case 0x01: dev->int_ctrl = (dev->int_ctrl & 0xffff00ff) | (val << 8); break; case 0x02: dev->int_ctrl = (dev->int_ctrl & 0xff00ffff) | (val << 16); break; case 0x03: dev->int_ctrl = (dev->int_ctrl & 0x00ffffff) | (val << 24); gameport_remap(dev->gameport, 0x200 | ((val & 0x03) << 3)); break; /* Interrupt/Chip Select Status Register, Address 04H Addressable as longword only, but PCem implements byte access, which must be for a reason */ case 0x06: if (dev->type >= AUDIOPCI_ES1373) dev->int_status = (dev->int_status & 0xff08ffff) | (val << 16); break; case 0x07: if (dev->type >= AUDIOPCI_CT5880) dev->int_status = (dev->int_status & 0xd2ffffff) | (val << 24); break; /* UART Data Register, Address 08H Addressable as byte only */ case 0x08: audiopci_log("MIDI data = %02x\n", val); /* TX does not use FIFO. */ midi_raw_out_byte(val); es1371_set_tx_irq(dev, 1); break; /* UART Control Register, Address 09H Addressable as byte only */ case 0x09: audiopci_log("[W] UART CTRL = %02X\n", val); dev->uart_ctrl = val & 0xe3; if ((val & 0x03) == 0x03) { /* Reset TX */ es1371_set_tx_irq(dev, 1); /* Software reset */ es1371_reset_fifo(dev); } else { es1371_set_tx_irq(dev, 1); es1371_update_tx_irq(dev); es1371_update_rx_irq(dev); } break; /* UART Reserved Register, Address 0AH Addressable as byte only */ case 0x0a: audiopci_log("[W] UART RES = %02X\n", val); dev->uart_res = val & 0x01; break; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ case 0x0c: dev->mem_page = val & 0xf; break; case 0x0d ... 0x0f: break; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ case 0x18: dev->legacy_ctrl |= LEGACY_INT; break; case 0x1a: old_legacy_ctrl = dev->legacy_ctrl; dev->legacy_ctrl = (dev->legacy_ctrl & 0xff00ffff) | (val << 16); update_legacy(dev, old_legacy_ctrl); break; case 0x1b: old_legacy_ctrl = dev->legacy_ctrl; dev->legacy_ctrl = (dev->legacy_ctrl & 0x00ffffff) | (val << 24); es1371_update_irqs(dev); update_legacy(dev, old_legacy_ctrl); break; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ case 0x1c: dev->spdif_chstatus = (dev->spdif_chstatus & 0xffffff00) | val; break; case 0x1d: dev->spdif_chstatus = (dev->spdif_chstatus & 0xffff00ff) | (val << 8); break; case 0x1e: dev->spdif_chstatus = (dev->spdif_chstatus & 0xff00ffff) | (val << 16); break; case 0x1f: dev->spdif_chstatus = (dev->spdif_chstatus & 0x00ffffff) | (val << 24); break; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ case 0x20: dev->si_cr = (dev->si_cr & 0xffffff00) | val; break; case 0x21: dev->si_cr = (dev->si_cr & 0xffff00ff) | (val << 8); if (!(dev->si_cr & SI_P1_INTR_EN)) dev->int_status &= ~INT_STATUS_DAC1; if (!(dev->si_cr & SI_P2_INTR_EN)) dev->int_status &= ~INT_STATUS_DAC2; es1371_update_irqs(dev); break; case 0x22: dev->si_cr = (dev->si_cr & 0xff80ffff) | ((val & 0x7f) << 16); break; default: audiopci_log("Bad es1371_outb: port=%04x val=%02x\n", port, val); } } static void es1371_outw(uint16_t port, uint16_t val, void *priv) { es1371_t *dev = (es1371_t *) priv; uint32_t old_legacy_ctrl; switch (port & 0x3f) { /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ case 0x00: if (!(dev->int_ctrl & INT_DAC1_EN) && (val & INT_DAC1_EN)) { dev->dac[0].addr = dev->dac[0].addr_latch; dev->dac[0].buffer_pos = 0; dev->dac[0].buffer_pos_end = 0; es1371_fetch(dev, 0); } if (!(dev->int_ctrl & INT_DAC2_EN) && (val & INT_DAC2_EN)) { dev->dac[1].addr = dev->dac[1].addr_latch; dev->dac[1].buffer_pos = 0; dev->dac[1].buffer_pos_end = 0; es1371_fetch(dev, 1); } dev->int_ctrl = (dev->int_ctrl & 0xffff0000) | val; break; case 0x02: dev->int_ctrl = (dev->int_ctrl & 0x0000ffff) | (val << 16); gameport_remap(dev->gameport, 0x200 | ((val & 0x0300) >> 5)); break; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ case 0x0c: dev->mem_page = val & 0xf; break; case 0x0e: break; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ case 0x18: dev->legacy_ctrl |= LEGACY_INT; break; case 0x1a: old_legacy_ctrl = dev->legacy_ctrl; dev->legacy_ctrl = (dev->legacy_ctrl & 0x0000ffff) | (val << 16); es1371_update_irqs(dev); update_legacy(dev, old_legacy_ctrl); break; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ case 0x1c: dev->spdif_chstatus = (dev->spdif_chstatus & 0xffff0000) | val; break; case 0x1e: dev->spdif_chstatus = (dev->spdif_chstatus & 0x0000ffff) | (val << 16); break; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ case 0x20: dev->si_cr = (dev->si_cr & 0xffff0000) | val; if (!(dev->si_cr & SI_P1_INTR_EN)) dev->int_status &= ~INT_STATUS_DAC1; if (!(dev->si_cr & SI_P2_INTR_EN)) dev->int_status &= ~INT_STATUS_DAC2; es1371_update_irqs(dev); break; case 0x22: dev->si_cr = (dev->si_cr & 0xff80ffff) | ((val & 0x007f) << 16); break; /* DAC1 Channel Sample Count Register, Address 24H Addressable as word, longword */ case 0x24: dev->dac[0].samp_ct = val; break; /* DAC2 Channel Sample Count Register, Address 28H Addressable as word, longword */ case 0x28: dev->dac[1].samp_ct = val; break; /* ADC Channel Sample Count Register, Address 2CH Addressable as word, longword */ case 0x2c: dev->adc.samp_ct = val; break; default: break; } } static void es1371_outl(uint16_t port, uint32_t val, void *priv) { es1371_t *dev = (es1371_t *) priv; uint32_t old_legacy_ctrl; audiopci_log("es1371_outl: port=%04x val=%08x\n", port, val); switch (port & 0x3f) { /* Interrupt/Chip Select Control Register, Address 00H Addressable as byte, word, longword */ case 0x00: if (!(dev->int_ctrl & INT_DAC1_EN) && (val & INT_DAC1_EN)) { dev->dac[0].addr = dev->dac[0].addr_latch; dev->dac[0].buffer_pos = 0; dev->dac[0].buffer_pos_end = 0; es1371_fetch(dev, 0); } if (!(dev->int_ctrl & INT_DAC2_EN) && (val & INT_DAC2_EN)) { dev->dac[1].addr = dev->dac[1].addr_latch; dev->dac[1].buffer_pos = 0; dev->dac[1].buffer_pos_end = 0; es1371_fetch(dev, 1); } dev->int_ctrl = val; gameport_remap(dev->gameport, 0x200 | ((val & 0x03000000) >> 21)); break; /* Interrupt/Chip Select Status Register, Address 04H Addressable as longword only */ case 0x04: audiopci_log("[W] STATUS = %08X\n", val); if (dev->type >= AUDIOPCI_CT5880) dev->int_status = (dev->int_status & 0xd208ffff) | (val & 0x2df70000); else if (dev->type >= AUDIOPCI_ES1373) dev->int_status = (dev->int_status & 0xff08ffff) | (val & 0x00f70000); break; /* Memory Page Register, Address 0CH Addressable as byte, word, longword */ case 0x0c: dev->mem_page = val & 0xf; break; /* Sample Rate Converter Interface Register, Address 10H Addressable as longword only */ case 0x10: dev->sr_cir = val & 0xfff8ffff; /*Bits 16 to 18 are undefined*/ if (dev->sr_cir & SRC_RAM_WE) { dev->sr_ram[dev->sr_cir >> 25] = val & 0xffff; switch (dev->sr_cir >> 25) { case 0x71: dev->dac[0].vf = (dev->dac[0].vf & ~0x1f8000) | ((val & 0xfc00) << 5); dev->dac[0].ac = (dev->dac[0].ac & ~0x7f8000) | ((val & 0x00ff) << 15); dev->dac[0].f_pos = 0; break; case 0x72: dev->dac[0].ac = (dev->dac[0].ac & ~0x7fff) | (val & 0x7fff); break; case 0x73: dev->dac[0].vf = (dev->dac[0].vf & ~0x7fff) | (val & 0x7fff); break; case 0x75: dev->dac[1].vf = (dev->dac[1].vf & ~0x1f8000) | ((val & 0xfc00) << 5); dev->dac[1].ac = (dev->dac[1].ac & ~0x7f8000) | ((val & 0x00ff) << 15); dev->dac[1].f_pos = 0; break; case 0x76: dev->dac[1].ac = (dev->dac[1].ac & ~0x7fff) | (val & 0x7fff); break; case 0x77: dev->dac[1].vf = (dev->dac[1].vf & ~0x7fff) | (val & 0x7fff); break; case 0x7c: dev->dac[0].vol_l = (int32_t) (int16_t) (val & 0xffff); break; case 0x7d: dev->dac[0].vol_r = (int32_t) (int16_t) (val & 0xffff); break; case 0x7e: dev->dac[1].vol_l = (int32_t) (int16_t) (val & 0xffff); break; case 0x7f: dev->dac[1].vol_r = (int32_t) (int16_t) (val & 0xffff); break; default: break; } } break; /* CODEC Write Register, Address 14H Addressable as longword only */ case 0x14: if (val & CODEC_READ) { dev->codec_ctrl &= 0x00ff0000; dev->codec_ctrl |= ac97_codec_readw(dev->codec, val >> 16); } else { dev->codec_ctrl = val & 0x00ffffff; ac97_codec_writew(dev->codec, val >> 16, val); ac97_codec_getattn(dev->codec, 0x02, &dev->master_vol_l, &dev->master_vol_r); ac97_codec_getattn(dev->codec, 0x18, &dev->pcm_vol_l, &dev->pcm_vol_r); ac97_codec_getattn(dev->codec, 0x38, &dev->pcm_rear_vol_l, &dev->pcm_rear_vol_r); ac97_codec_getattn(dev->codec, 0x12, &dev->cd_vol_l, &dev->cd_vol_r); } break; /* Legacy Control/Status Register, Address 18H Addressable as byte, word, longword */ case 0x18: old_legacy_ctrl = dev->legacy_ctrl; dev->legacy_ctrl = (dev->legacy_ctrl & 0x0000ffff) | (val & 0xffff0000); dev->legacy_ctrl |= LEGACY_INT; es1371_update_irqs(dev); update_legacy(dev, old_legacy_ctrl); break; /* S/PDIF Channel Status Control Register, Address 1CH Addressable as byte, word, longword */ case 0x1c: dev->spdif_chstatus = val; break; /* Serial Interface Control Register, Address 20H Addressable as byte, word, longword */ case 0x20: dev->si_cr = (val & 0x007fffff) | 0xff800000; if (!(dev->si_cr & SI_P1_INTR_EN)) dev->int_status &= ~INT_STATUS_DAC1; if (!(dev->si_cr & SI_P2_INTR_EN)) dev->int_status &= ~INT_STATUS_DAC2; es1371_update_irqs(dev); break; /* DAC1 Channel Sample Count Register, Address 24H Addressable as word, longword */ case 0x24: dev->dac[0].samp_ct = val & 0xffff; break; /* DAC2 Channel Sample Count Register, Address 28H Addressable as word, longword */ case 0x28: dev->dac[1].samp_ct = val & 0xffff; break; /* ADC Channel Sample Count Register, Address 2CH Addressable as word, longword */ case 0x2c: dev->adc.samp_ct = val & 0xffff; break; case 0x30: case 0x34: case 0x38: case 0x3c: es1371_write_frame_reg(dev, port & 0x3c, dev->mem_page, val); break; default: break; } } static void capture_event(es1371_t *dev, int type, int rw, uint16_t port) { dev->legacy_ctrl &= ~(LEGACY_EVENT_MASK | LEGACY_EVENT_ADDR_MASK); dev->legacy_ctrl |= type; if (rw) dev->legacy_ctrl |= LEGACY_EVENT_TYPE_RW; else dev->legacy_ctrl &= ~LEGACY_EVENT_TYPE_RW; dev->legacy_ctrl |= ((port << LEGACY_EVENT_ADDR_SHIFT) & LEGACY_EVENT_ADDR_MASK); dev->legacy_ctrl &= ~LEGACY_INT; nmi_raise(); } static void capture_write_sscape(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_SSCAPE, 1, port); } static void capture_write_codec(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_CODEC, 1, port); } static void capture_write_sb(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_SB, 1, port); } static void capture_write_adlib(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_ADLIB, 1, port); } static void capture_write_master_pic(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_MASTER_PIC, 1, port); } static void capture_write_master_dma(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_MASTER_DMA, 1, port); } static void capture_write_slave_pic(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_SLAVE_PIC, 1, port); } static void capture_write_slave_dma(uint16_t port, UNUSED(uint8_t val), void *priv) { capture_event(priv, LEGACY_EVENT_SLAVE_DMA, 1, port); } static uint8_t capture_read_sscape(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_SSCAPE, 0, port); return 0xff; } static uint8_t capture_read_codec(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_CODEC, 0, port); return 0xff; } static uint8_t capture_read_sb(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_SB, 0, port); return 0xff; } static uint8_t capture_read_adlib(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_ADLIB, 0, port); return 0xff; } static uint8_t capture_read_master_pic(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_MASTER_PIC, 0, port); return 0xff; } static uint8_t capture_read_master_dma(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_MASTER_DMA, 0, port); return 0xff; } static uint8_t capture_read_slave_pic(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_SLAVE_PIC, 0, port); return 0xff; } static uint8_t capture_read_slave_dma(uint16_t port, void *priv) { capture_event(priv, LEGACY_EVENT_SLAVE_DMA, 0, port); return 0xff; } static void update_legacy(es1371_t *dev, uint32_t old_legacy_ctrl) { if (old_legacy_ctrl & LEGACY_CAPTURE_SSCAPE) { switch ((old_legacy_ctrl >> LEGACY_SSCAPE_ADDR_SHIFT) & 3) { case 0: io_removehandler(0x0320, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; case 1: io_removehandler(0x0330, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; case 2: io_removehandler(0x0340, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; case 3: io_removehandler(0x0350, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; default: break; } } if (old_legacy_ctrl & LEGACY_CAPTURE_CODEC) { switch ((old_legacy_ctrl >> LEGACY_CODEC_ADDR_SHIFT) & 3) { case 0: io_removehandler(0x0530, 0x0008, capture_read_codec, NULL, NULL, capture_write_codec, NULL, NULL, dev); break; case 2: io_removehandler(0x0e80, 0x0008, capture_read_codec, NULL, NULL, capture_write_codec, NULL, NULL, dev); break; case 3: io_removehandler(0x0f40, 0x0008, capture_read_codec, NULL, NULL, capture_write_codec, NULL, NULL, dev); break; default: break; } } if (old_legacy_ctrl & LEGACY_CAPTURE_SB) { if (!(old_legacy_ctrl & LEGACY_SB_ADDR)) { io_removehandler(0x0220, 0x0010, capture_read_sb, NULL, NULL, capture_write_sb, NULL, NULL, dev); } else { io_removehandler(0x0240, 0x0010, capture_read_sb, NULL, NULL, capture_write_sb, NULL, NULL, dev); } } if (old_legacy_ctrl & LEGACY_CAPTURE_ADLIB) { io_removehandler(0x0388, 0x0004, capture_read_adlib, NULL, NULL, capture_write_adlib, NULL, NULL, dev); } if (old_legacy_ctrl & LEGACY_CAPTURE_MASTER_PIC) { io_removehandler(0x0020, 0x0002, capture_read_master_pic, NULL, NULL, capture_write_master_pic, NULL, NULL, dev); } if (old_legacy_ctrl & LEGACY_CAPTURE_MASTER_DMA) { io_removehandler(0x0000, 0x0010, capture_read_master_dma, NULL, NULL, capture_write_master_dma, NULL, NULL, dev); } if (old_legacy_ctrl & LEGACY_CAPTURE_SLAVE_PIC) { io_removehandler(0x00a0, 0x0002, capture_read_slave_pic, NULL, NULL, capture_write_slave_pic, NULL, NULL, dev); } if (old_legacy_ctrl & LEGACY_CAPTURE_SLAVE_DMA) { io_removehandler(0x00c0, 0x0020, capture_read_slave_dma, NULL, NULL, capture_write_slave_dma, NULL, NULL, dev); } if (dev->legacy_ctrl & LEGACY_CAPTURE_SSCAPE) { switch ((dev->legacy_ctrl >> LEGACY_SSCAPE_ADDR_SHIFT) & 3) { case 0: io_sethandler(0x0320, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; case 1: io_sethandler(0x0330, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; case 2: io_sethandler(0x0340, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; case 3: io_sethandler(0x0350, 0x0008, capture_read_sscape, NULL, NULL, capture_write_sscape, NULL, NULL, dev); break; default: break; } } if (dev->legacy_ctrl & LEGACY_CAPTURE_CODEC) { switch ((dev->legacy_ctrl >> LEGACY_CODEC_ADDR_SHIFT) & 3) { case 0: io_sethandler(0x0530, 0x0008, capture_read_codec, NULL, NULL, capture_write_codec, NULL, NULL, dev); break; case 2: io_sethandler(0x0e80, 0x0008, capture_read_codec, NULL, NULL, capture_write_codec, NULL, NULL, dev); break; case 3: io_sethandler(0x0f40, 0x0008, capture_read_codec, NULL, NULL, capture_write_codec, NULL, NULL, dev); break; default: break; } } if (dev->legacy_ctrl & LEGACY_CAPTURE_SB) { if (!(dev->legacy_ctrl & LEGACY_SB_ADDR)) { io_sethandler(0x0220, 0x0010, capture_read_sb, NULL, NULL, capture_write_sb, NULL, NULL, dev); } else { io_sethandler(0x0240, 0x0010, capture_read_sb, NULL, NULL, capture_write_sb, NULL, NULL, dev); } } if (dev->legacy_ctrl & LEGACY_CAPTURE_ADLIB) { io_sethandler(0x0388, 0x0004, capture_read_adlib, NULL, NULL, capture_write_adlib, NULL, NULL, dev); } if (dev->legacy_ctrl & LEGACY_CAPTURE_MASTER_PIC) { io_sethandler(0x0020, 0x0002, capture_read_master_pic, NULL, NULL, capture_write_master_pic, NULL, NULL, dev); } if (dev->legacy_ctrl & LEGACY_CAPTURE_MASTER_DMA) { io_sethandler(0x0000, 0x0010, capture_read_master_dma, NULL, NULL, capture_write_master_dma, NULL, NULL, dev); } if (dev->legacy_ctrl & LEGACY_CAPTURE_SLAVE_PIC) { io_sethandler(0x00a0, 0x0002, capture_read_slave_pic, NULL, NULL, capture_write_slave_pic, NULL, NULL, dev); } if (dev->legacy_ctrl & LEGACY_CAPTURE_SLAVE_DMA) { io_sethandler(0x00c0, 0x0020, capture_read_slave_dma, NULL, NULL, capture_write_slave_dma, NULL, NULL, dev); } } static uint8_t es1371_pci_read(int func, int addr, void *priv) { const es1371_t *dev = (es1371_t *) priv; if (func > 0) return 0xff; if ((addr > 0x3f) && ((addr < 0xdc) || (addr > 0xe1))) return 0x00; switch (addr) { case 0x00: return 0x74; /* Ensoniq */ case 0x01: return 0x12; case 0x02: return dev->type >> 16; /* ES1371 */ case 0x03: return dev->type >> 24; case 0x04: return dev->pci_command; case 0x05: return dev->pci_serr; case 0x06: return 0x10; /* Supports ACPI */ case 0x07: return 0x00; case 0x08: return dev->type >> 8; /* Revision ID */ case 0x09: return 0x00; /* Multimedia audio device */ case 0x0a: return 0x01; case 0x0b: return 0x04; case 0x10: return 0x01 | (dev->base_addr & 0xc0); /* memBaseAddr */ case 0x11: return dev->base_addr >> 8; case 0x12: return dev->base_addr >> 16; case 0x13: return dev->base_addr >> 24; case 0x2c ... 0x2f: return dev->subsys_id[addr & 3]; /* Subsystem vendor ID */ case 0x34: return 0xdc; /* Capabilites pointer */ case 0x3c: return dev->int_line; case 0x3d: return 0x01; /* INTA */ case 0x3e: return 0xc; /* Minimum grant */ case 0x3f: return 0x80; /* Maximum latency */ case 0x40: if (dev->type >= AUDIOPCI_ES1373) return dev->subsys_lock; break; case 0xdc: return 0x01; /* Capabilities identifier */ case 0xdd: return 0x00; /* Next item pointer */ case 0xde: return 0x31; /* Power management capabilities */ case 0xdf: return 0x6c; case 0xe0: return dev->pmcsr & 0xff; case 0xe1: return dev->pmcsr >> 8; default: break; } return 0x00; } static void es1371_io_set(es1371_t *dev, int set) { if (dev->pci_command & PCI_COMMAND_IO) { io_handler(set, dev->base_addr, 0x0040, es1371_inb, es1371_inw, es1371_inl, es1371_outb, es1371_outw, es1371_outl, dev); } } static void es1371_pci_write(int func, int addr, uint8_t val, void *priv) { es1371_t *dev = (es1371_t *) priv; if (func) return; switch (addr) { case 0x04: es1371_io_set(dev, 0); dev->pci_command = val & 0x05; es1371_io_set(dev, 1); break; case 0x05: dev->pci_serr = val & 1; break; case 0x10: es1371_io_set(dev, 0); dev->base_addr = (dev->base_addr & 0xffffff00) | (val & 0xc0); es1371_io_set(dev, 1); break; case 0x11: es1371_io_set(dev, 0); dev->base_addr = (dev->base_addr & 0xffff00c0) | (val << 8); es1371_io_set(dev, 1); break; case 0x12: dev->base_addr = (dev->base_addr & 0xff00ffc0) | (val << 16); break; case 0x13: dev->base_addr = (dev->base_addr & 0x00ffffc0) | (val << 24); break; case 0x2c ... 0x2f: if (dev->subsys_lock == 0xea) dev->subsys_id[addr & 3] = val; break; case 0x3c: dev->int_line = val; break; case 0x40: if (dev->type >= AUDIOPCI_ES1373) dev->subsys_lock = val; break; case 0xe0: dev->pmcsr = (dev->pmcsr & 0xff00) | (val & 0x03); break; case 0xe1: dev->pmcsr = (dev->pmcsr & 0x00ff) | ((val & 0x01) << 8); break; default: break; } } static void es1371_fetch(es1371_t *dev, int dac_nr) { if (dev->si_cr & (dac_nr ? SI_P2_PAUSE : SI_P1_PAUSE)) return; int format = dac_nr ? ((dev->si_cr >> 2) & 3) : (dev->si_cr & 3); int pos = dev->dac[dac_nr].buffer_pos & 63; int c; switch (format) { case FORMAT_MONO_8: for (c = 0; c < 32; c += 4) { dev->dac[dac_nr].buffer_l[(pos + c) & 63] = dev->dac[dac_nr].buffer_r[(pos + c) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr) ^ 0x80) << 8; dev->dac[dac_nr].buffer_l[(pos + c + 1) & 63] = dev->dac[dac_nr].buffer_r[(pos + c + 1) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr + 1) ^ 0x80) << 8; dev->dac[dac_nr].buffer_l[(pos + c + 2) & 63] = dev->dac[dac_nr].buffer_r[(pos + c + 2) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr + 2) ^ 0x80) << 8; dev->dac[dac_nr].buffer_l[(pos + c + 3) & 63] = dev->dac[dac_nr].buffer_r[(pos + c + 3) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr + 3) ^ 0x80) << 8; dev->dac[dac_nr].addr += 4; dev->dac[dac_nr].buffer_pos_end += 4; dev->dac[dac_nr].count++; if (dev->dac[dac_nr].count > dev->dac[dac_nr].size) { dev->dac[dac_nr].count = 0; dev->dac[dac_nr].addr = dev->dac[dac_nr].addr_latch; break; } } break; case FORMAT_STEREO_8: for (c = 0; c < 16; c += 2) { dev->dac[dac_nr].buffer_l[(pos + c) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr) ^ 0x80) << 8; dev->dac[dac_nr].buffer_r[(pos + c) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr + 1) ^ 0x80) << 8; dev->dac[dac_nr].buffer_l[(pos + c + 1) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr + 2) ^ 0x80) << 8; dev->dac[dac_nr].buffer_r[(pos + c + 1) & 63] = (mem_readb_phys(dev->dac[dac_nr].addr + 3) ^ 0x80) << 8; dev->dac[dac_nr].addr += 4; dev->dac[dac_nr].buffer_pos_end += 2; dev->dac[dac_nr].count++; if (dev->dac[dac_nr].count > dev->dac[dac_nr].size) { dev->dac[dac_nr].count = 0; dev->dac[dac_nr].addr = dev->dac[dac_nr].addr_latch; break; } } break; case FORMAT_MONO_16: for (c = 0; c < 16; c += 2) { dev->dac[dac_nr].buffer_l[(pos + c) & 63] = dev->dac[dac_nr].buffer_r[(pos + c) & 63] = mem_readw_phys(dev->dac[dac_nr].addr); dev->dac[dac_nr].buffer_l[(pos + c + 1) & 63] = dev->dac[dac_nr].buffer_r[(pos + c + 1) & 63] = mem_readw_phys(dev->dac[dac_nr].addr + 2); dev->dac[dac_nr].addr += 4; dev->dac[dac_nr].buffer_pos_end += 2; dev->dac[dac_nr].count++; if (dev->dac[dac_nr].count > dev->dac[dac_nr].size) { dev->dac[dac_nr].count = 0; dev->dac[dac_nr].addr = dev->dac[dac_nr].addr_latch; break; } } break; case FORMAT_STEREO_16: for (c = 0; c < 4; c++) { dev->dac[dac_nr].buffer_l[(pos + c) & 63] = mem_readw_phys(dev->dac[dac_nr].addr); dev->dac[dac_nr].buffer_r[(pos + c) & 63] = mem_readw_phys(dev->dac[dac_nr].addr + 2); dev->dac[dac_nr].addr += 4; dev->dac[dac_nr].buffer_pos_end++; dev->dac[dac_nr].count++; if (dev->dac[dac_nr].count > dev->dac[dac_nr].size) { dev->dac[dac_nr].count = 0; dev->dac[dac_nr].addr = dev->dac[dac_nr].addr_latch; break; } } break; default: break; } } static inline float low_fir_es1371(int dac_nr, int i, float NewSample) { static float x[2][2][128]; // input samples static int x_pos[2] = { 0, 0 }; float out = 0.0; int read_pos; int n_coef; int pos = x_pos[dac_nr]; x[dac_nr][i][pos] = NewSample; /* Since only 1/16th of input samples are non-zero, only filter those that are valid.*/ read_pos = (pos + 15) & (127 & ~15); n_coef = (16 - pos) & 15; while (n_coef < ES1371_NCoef) { out += low_fir_es1371_coef[n_coef] * x[dac_nr][i][read_pos]; read_pos = (read_pos + 16) & (127 & ~15); n_coef += 16; } if (i == 1) { x_pos[dac_nr] = (x_pos[dac_nr] + 1) & 127; if (x_pos[dac_nr] > 127) x_pos[dac_nr] = 0; } return out; } static void es1371_next_sample_filtered(es1371_t *dev, int dac_nr, int out_idx) { int out_l; int out_r; if ((dev->dac[dac_nr].buffer_pos - dev->dac[dac_nr].buffer_pos_end) >= 0) es1371_fetch(dev, dac_nr); out_l = dev->dac[dac_nr].buffer_l[dev->dac[dac_nr].buffer_pos & 63]; out_r = dev->dac[dac_nr].buffer_r[dev->dac[dac_nr].buffer_pos & 63]; dev->dac[dac_nr].filtered_l[out_idx] = (int) low_fir_es1371(dac_nr, 0, (float) out_l); dev->dac[dac_nr].filtered_r[out_idx] = (int) low_fir_es1371(dac_nr, 1, (float) out_r); for (uint8_t c = 1; c < 16; c++) { dev->dac[dac_nr].filtered_l[out_idx + c] = (int) low_fir_es1371(dac_nr, 0, 0); dev->dac[dac_nr].filtered_r[out_idx + c] = (int) low_fir_es1371(dac_nr, 1, 0); } dev->dac[dac_nr].buffer_pos++; } static void es1371_update(es1371_t *dev) { int32_t l; int32_t r; l = (dev->dac[0].out_l * dev->dac[0].vol_l) >> 12; l += ((dev->dac[1].out_l * dev->dac[1].vol_l) >> 12); r = (dev->dac[0].out_r * dev->dac[0].vol_r) >> 12; r += ((dev->dac[1].out_r * dev->dac[1].vol_r) >> 12); l >>= 1; r >>= 1; l = (((l * dev->pcm_vol_l) >> 15) * dev->master_vol_l) >> 15; r = (((r * dev->pcm_vol_r) >> 15) * dev->master_vol_r) >> 15; if (l < -32768) l = -32768; else if (l > 32767) l = 32767; if (r < -32768) r = -32768; else if (r > 32767) r = 32767; for (; dev->pos < sound_pos_global; dev->pos++) { dev->buffer[dev->pos * 2] = l; dev->buffer[dev->pos * 2 + 1] = r; } } static void es1371_poll(void *priv) { es1371_t *dev = (es1371_t *) priv; int frac; int idx; int samp1_l; int samp1_r; int samp2_l; int samp2_r; timer_advance_u64(&dev->dac[1].timer, dev->dac[1].latch); es1371_scan_fifo(dev); es1371_update(dev); if (dev->int_ctrl & INT_DAC1_EN) { if ((dev->type >= AUDIOPCI_ES1373) && (dev->int_ctrl & INT_DAC1_BYPASS)) { /* SRC bypass. */ if ((dev->dac[0].buffer_pos - dev->dac[0].buffer_pos_end) >= 0) es1371_fetch(dev, 0); dev->dac[0].out_l = dev->dac[0].buffer_l[dev->dac[0].buffer_pos & 63]; dev->dac[0].out_r = dev->dac[0].buffer_r[dev->dac[0].buffer_pos & 63]; dev->dac[0].buffer_pos++; goto dac0_count; } else { frac = dev->dac[0].ac & 0x7fff; idx = dev->dac[0].ac >> 15; samp1_l = dev->dac[0].filtered_l[idx]; samp1_r = dev->dac[0].filtered_r[idx]; samp2_l = dev->dac[0].filtered_l[(idx + 1) & 31]; samp2_r = dev->dac[0].filtered_r[(idx + 1) & 31]; dev->dac[0].out_l = ((samp1_l * (0x8000 - frac)) + (samp2_l * frac)) >> 15; dev->dac[0].out_r = ((samp1_r * (0x8000 - frac)) + (samp2_r * frac)) >> 15; dev->dac[0].ac += dev->dac[0].vf; dev->dac[0].ac &= ((32 << 15) - 1); if ((dev->dac[0].ac >> (15 + 4)) != dev->dac[0].f_pos) { es1371_next_sample_filtered(dev, 0, dev->dac[0].f_pos ? 16 : 0); dev->dac[0].f_pos = (dev->dac[0].f_pos + 1) & 1; dac0_count: dev->dac[0].curr_samp_ct--; if (dev->dac[0].curr_samp_ct < 0) { dev->int_status |= INT_STATUS_DAC1; es1371_update_irqs(dev); dev->dac[0].curr_samp_ct = dev->dac[0].samp_ct; } } } } if (dev->int_ctrl & INT_DAC2_EN) { if ((dev->type >= AUDIOPCI_ES1373) && (dev->int_ctrl & INT_DAC2_BYPASS)) { /* SRC bypass. */ if ((dev->dac[1].buffer_pos - dev->dac[1].buffer_pos_end) >= 0) es1371_fetch(dev, 1); dev->dac[1].out_l = dev->dac[1].buffer_l[dev->dac[1].buffer_pos & 63]; dev->dac[1].out_r = dev->dac[1].buffer_r[dev->dac[1].buffer_pos & 63]; dev->dac[1].buffer_pos++; goto dac1_count; } else { frac = dev->dac[1].ac & 0x7fff; idx = dev->dac[1].ac >> 15; samp1_l = dev->dac[1].filtered_l[idx]; samp1_r = dev->dac[1].filtered_r[idx]; samp2_l = dev->dac[1].filtered_l[(idx + 1) & 31]; samp2_r = dev->dac[1].filtered_r[(idx + 1) & 31]; dev->dac[1].out_l = ((samp1_l * (0x8000 - frac)) + (samp2_l * frac)) >> 15; dev->dac[1].out_r = ((samp1_r * (0x8000 - frac)) + (samp2_r * frac)) >> 15; dev->dac[1].ac += dev->dac[1].vf; dev->dac[1].ac &= ((32 << 15) - 1); if ((dev->dac[1].ac >> (15 + 4)) != dev->dac[1].f_pos) { es1371_next_sample_filtered(dev, 1, dev->dac[1].f_pos ? 16 : 0); dev->dac[1].f_pos = (dev->dac[1].f_pos + 1) & 1; dac1_count: dev->dac[1].curr_samp_ct--; if (dev->dac[1].curr_samp_ct < 0) { dev->int_status |= INT_STATUS_DAC2; es1371_update_irqs(dev); dev->dac[1].curr_samp_ct = dev->dac[1].samp_ct; } } } } } static void es1371_get_buffer(int32_t *buffer, int len, void *priv) { es1371_t *dev = (es1371_t *) priv; es1371_update(dev); for (int c = 0; c < len * 2; c++) buffer[c] += (dev->buffer[c] / 2); dev->pos = 0; } static void es1371_filter_cd_audio(int channel, double *buffer, void *priv) { const es1371_t *dev = (es1371_t *) priv; double c; int cd = channel ? dev->cd_vol_r : dev->cd_vol_l; int master = channel ? dev->master_vol_r : dev->master_vol_l; c = ((((*buffer) * cd) / 65536.0) * master) / 65536.0; *buffer = c; } static inline double sinc(double x) { return sin(M_PI * x) / (M_PI * x); } static void generate_es1371_filter(void) { /* Cutoff frequency = 1 / 32 */ float fC = 1.0 / 32.0; float gain; int n; for (n = 0; n < ES1371_NCoef; n++) { /* Blackman window */ double w = 0.42 - (0.5 * cos((2.0 * n * M_PI) / (double) (ES1371_NCoef - 1))) + (0.08 * cos((4.0 * n * M_PI) / (double) (ES1371_NCoef - 1))); /* Sinc filter */ double h = sinc(2.0 * fC * ((double) n - ((double) (ES1371_NCoef - 1) / 2.0))); /* Create windowed-sinc filter */ low_fir_es1371_coef[n] = w * h; } low_fir_es1371_coef[(ES1371_NCoef - 1) / 2] = 1.0; gain = 0.0; for (n = 0; n < ES1371_NCoef; n++) gain += low_fir_es1371_coef[n] / (float) N; gain /= 0.65; /* Normalise filter, to produce unity gain */ for (n = 0; n < ES1371_NCoef; n++) low_fir_es1371_coef[n] /= gain; } static void es1371_input_msg(void *priv, uint8_t *msg, uint32_t len) { es1371_t *dev = (es1371_t *) priv; for (uint32_t i = 0; i < len; i++) es1371_write_fifo(dev, msg[i]); } static int es1371_input_sysex(void *priv, uint8_t *buffer, uint32_t len, int abort) { es1371_t *dev = (es1371_t *) priv; uint32_t i = -1; audiopci_log("Abort = %i\n", abort); if (dev->uart_status & UART_STATUS_RXRDY) abort = 1; if (!abort) { for (i = 0; i < len; i++) { es1371_write_fifo(dev, buffer[i]); if (dev->uart_status & UART_STATUS_RXRDY) break; } } /* The last sent position is in i. Return 7 - i. */ return 7 - i; } static void * es1371_init(const device_t *info) { es1371_t *dev = malloc(sizeof(es1371_t)); memset(dev, 0x00, sizeof(es1371_t)); dev->type = info->local & 0xffffff00; if (device_get_config_int("receive_input")) midi_in_handler(1, es1371_input_msg, es1371_input_sysex, dev); sound_add_handler(es1371_get_buffer, dev); sound_set_cd_audio_filter(es1371_filter_cd_audio, dev); dev->gameport = gameport_add(&gameport_pnp_device); gameport_remap(dev->gameport, 0x200); pci_add_card((info->local & 1) ? PCI_ADD_SOUND : PCI_ADD_NORMAL, es1371_pci_read, es1371_pci_write, dev, &dev->pci_slot); timer_add(&dev->dac[1].timer, es1371_poll, dev, 1); generate_es1371_filter(); ac97_codec = &dev->codec; ac97_codec_count = 1; ac97_codec_id = 0; /* Let the machine decide the codec on onboard implementations. */ if (!(info->local & 1)) device_add(ac97_codec_get(device_get_config_int("codec"))); es1371_reset(dev); return dev; } static void es1371_close(void *priv) { es1371_t *dev = (es1371_t *) priv; free(dev); } static void es1371_speed_changed(void *priv) { es1371_t *dev = (es1371_t *) priv; dev->dac[1].latch = (uint64_t) ((double) TIMER_USEC * (1000000.0 / (double) SOUND_FREQ)); } static const device_config_t es1371_config[] = { // clang-format off { .name = "codec", .description = "Codec", .type = CONFIG_SELECTION, .selection = { { .description = "Asahi Kasei AK4540", .value = AC97_CODEC_AK4540 }, { .description = "TriTech TR28023 / Creative CT1297", .value = AC97_CODEC_TR28023 }, { .description = "" } }, .default_int = AC97_CODEC_TR28023 }, { .name = "receive_input", .description = "Receive input (MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; static const device_config_t es1373_config[] = { // clang-format off { .name = "codec", .description = "Codec", .type = CONFIG_SELECTION, .selection = { { .description = "Crystal CS4297A", .value = AC97_CODEC_CS4297A }, { .description = "SigmaTel STAC9721T", .value = AC97_CODEC_STAC9721 }, { .description = "TriTech TR28023 / Creative CT1297", .value = AC97_CODEC_TR28023 }, { .description = "" } }, .default_int = AC97_CODEC_CS4297A }, { .name = "receive_input", .description = "Receive input (MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; static const device_config_t ct5880_config[] = { // clang-format off { .name = "codec", .description = "Codec", .type = CONFIG_SELECTION, .selection = { { .description = "SigmaTel STAC9708T", .value = AC97_CODEC_STAC9708 }, { .description = "SigmaTel STAC9721T (stereo)", .value = AC97_CODEC_STAC9721 }, { .description = "" } }, .default_int = AC97_CODEC_STAC9708 }, { .name = "receive_input", .description = "Receive input (MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; static const device_config_t es1371_onboard_config[] = { // clang-format off { .name = "receive_input", .description = "Receive input (MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t es1371_device = { .name = "Ensoniq AudioPCI (ES1371)", .internal_name = "es1371", .flags = DEVICE_PCI, .local = AUDIOPCI_ES1371, .init = es1371_init, .close = es1371_close, .reset = es1371_reset, { .available = NULL }, .speed_changed = es1371_speed_changed, .force_redraw = NULL, .config = es1371_config }; const device_t es1371_onboard_device = { .name = "Ensoniq AudioPCI (ES1371) (On-Board)", .internal_name = "es1371_onboard", .flags = DEVICE_PCI, .local = AUDIOPCI_ES1371 | 1, .init = es1371_init, .close = es1371_close, .reset = es1371_reset, { .available = NULL }, .speed_changed = es1371_speed_changed, .force_redraw = NULL, .config = es1371_onboard_config }; const device_t es1373_device = { .name = "Sound Blaster PCI 128 (ES1373)", .internal_name = "es1373", .flags = DEVICE_PCI, .local = AUDIOPCI_ES1373, .init = es1371_init, .close = es1371_close, .reset = es1371_reset, { .available = NULL }, .speed_changed = es1371_speed_changed, .force_redraw = NULL, .config = es1373_config }; const device_t es1373_onboard_device = { .name = "Sound Blaster PCI 128 (ES1373) (On-Board)", .internal_name = "es1373_onboard", .flags = DEVICE_PCI, .local = AUDIOPCI_ES1373 | 1, .init = es1371_init, .close = es1371_close, .reset = es1371_reset, { .available = NULL }, .speed_changed = es1371_speed_changed, .force_redraw = NULL, .config = es1371_onboard_config }; const device_t ct5880_device = { .name = "Sound Blaster PCI 4.1 (CT5880)", .internal_name = "ct5880", .flags = DEVICE_PCI, .local = AUDIOPCI_CT5880, .init = es1371_init, .close = es1371_close, .reset = es1371_reset, { .available = NULL }, .speed_changed = es1371_speed_changed, .force_redraw = NULL, .config = ct5880_config }; const device_t ct5880_onboard_device = { .name = "Sound Blaster PCI 4.1 (CT5880) (On-Board)", .internal_name = "ct5880_onboard", .flags = DEVICE_PCI, .local = AUDIOPCI_CT5880 | 1, .init = es1371_init, .close = es1371_close, .reset = es1371_reset, { .available = NULL }, .speed_changed = es1371_speed_changed, .force_redraw = NULL, .config = es1371_onboard_config }; ```
/content/code_sandbox/src/sound/snd_audiopci.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
22,705
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * OPTi MediaCHIPS 82C929A (also known as OPTi MAD16 Pro) audio controller emulation. * * * * Authors: Cacodemon345 * Eluan Costa Miranda <eluancm@gmail.com> * */ #include <math.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/midi.h> #include <86box/timer.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/gameport.h> #include <86box/snd_ad1848.h> #include <86box/snd_sb.h> #include <86box/mem.h> #include <86box/rom.h> #include <86box/plat_unused.h> static int optimc_wss_dma[4] = { 0, 0, 1, 3 }; static int optimc_wss_irq[8] = { 5, 7, 9, 10, 11, 12, 14, 15 }; enum optimc_local_flags { OPTIMC_CS4231 = 0x100, OPTIMC_OPL4 = 0x200, }; typedef struct optimc_t { uint8_t type; uint8_t fm_type; uint8_t wss_config; uint8_t reg_enabled; uint16_t cur_addr; uint16_t cur_wss_addr; uint16_t cur_mpu401_addr; int cur_irq; int cur_dma; int cur_wss_enabled; int cur_wss_irq; int cur_wss_dma; int cur_mpu401_irq; int cur_mpu401_enabled; void *gameport; uint8_t cur_mode; ad1848_t ad1848; mpu_t *mpu; sb_t *sb; uint8_t regs[6]; } optimc_t, opti_82c929a_t; static void optimc_filter_opl(void *priv, double *out_l, double *out_r) { optimc_t *optimc = (optimc_t *) priv; if (optimc->cur_wss_enabled) { *out_l /= optimc->sb->mixer_sbpro.fm_l; *out_r /= optimc->sb->mixer_sbpro.fm_r; ad1848_filter_aux2((void *) &optimc->ad1848, out_l, out_r); } } static uint8_t optimc_wss_read(UNUSED(uint16_t addr), void *priv) { const optimc_t *optimc = (optimc_t *) priv; if (!(optimc->regs[4] & 0x10) && optimc->cur_mode == 0) return 0xFF; return 4 | (optimc->wss_config & 0x40); } static void optimc_wss_write(UNUSED(uint16_t addr), uint8_t val, void *priv) { optimc_t *optimc = (optimc_t *) priv; if (!(optimc->regs[4] & 0x10) && optimc->cur_mode == 0) return; optimc->wss_config = val; ad1848_setdma(&optimc->ad1848, optimc_wss_dma[val & 3]); ad1848_setirq(&optimc->ad1848, optimc_wss_irq[(val >> 3) & 7]); } static void optimc_get_buffer(int32_t *buffer, int len, void *priv) { optimc_t *optimc = (optimc_t *) priv; if (optimc->regs[3] & 0x4) return; /* wss part */ ad1848_update(&optimc->ad1848); for (int c = 0; c < len * 2; c++) buffer[c] += (optimc->ad1848.buffer[c] / 2); optimc->ad1848.pos = 0; /* sbprov2 part */ sb_get_buffer_sbpro(buffer, len, optimc->sb); } static void optimc_remove_opl(optimc_t *optimc) { io_removehandler(optimc->cur_addr + 0, 0x0004, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_removehandler(optimc->cur_addr + 8, 0x0002, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_removehandler(0x0388, 0x0004, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); } static void optimc_add_opl(optimc_t *optimc) { /* DSP I/O handler is activated in sb_dsp_setaddr */ io_sethandler(optimc->cur_addr + 0, 0x0004, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_sethandler(optimc->cur_addr + 8, 0x0002, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_sethandler(0x0388, 0x0004, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); } static void optimc_reg_write(uint16_t addr, uint8_t val, void *priv) { optimc_t *optimc = (optimc_t *) priv; uint16_t idx = addr - 0xF8D; uint8_t old = optimc->regs[idx]; static uint8_t reg_enable_phase = 0; if (optimc->reg_enabled) { switch (idx) { case 0: /* MC1 */ optimc->regs[0] = val; if (val != old) { optimc->cur_mode = optimc->cur_wss_enabled = !!(val & 0x80); sound_set_cd_audio_filter(NULL, NULL); if (optimc->cur_wss_enabled) /* WSS */ sound_set_cd_audio_filter(ad1848_filter_cd_audio, &optimc->ad1848); else /* SBPro */ sound_set_cd_audio_filter(sbpro_filter_cd_audio, optimc->sb); io_removehandler(optimc->cur_wss_addr, 0x0004, optimc_wss_read, NULL, NULL, optimc_wss_write, NULL, NULL, optimc); io_removehandler(optimc->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &optimc->ad1848); switch ((val >> 4) & 0x3) { case 0: /* WSBase = 0x530 */ optimc->cur_wss_addr = 0x530; break; case 1: /* WSBase = 0xE80 */ optimc->cur_wss_addr = 0xE80; break; case 2: /* WSBase = 0xF40 */ optimc->cur_wss_addr = 0xF40; break; case 3: /* WSBase = 0x604 */ optimc->cur_wss_addr = 0x604; break; default: break; } io_sethandler(optimc->cur_wss_addr, 0x0004, optimc_wss_read, NULL, NULL, optimc_wss_write, NULL, NULL, optimc); io_sethandler(optimc->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &optimc->ad1848); gameport_remap(optimc->gameport, (optimc->regs[0] & 0x1) ? 0x00 : 0x200); } break; case 1: /* MC2 */ optimc->regs[1] = val; break; case 2: /* MC3 */ if (val == optimc->type) break; optimc->regs[2] = val; if (old != val) { io_removehandler(optimc->cur_addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, optimc->sb); optimc_remove_opl(optimc); optimc->cur_addr = (val & 0x4) ? 0x240 : 0x220; switch ((val >> 4) & 0x3) { case 0: optimc->cur_dma = 1; break; case 1: optimc->cur_dma = 0; break; case 2: default: optimc->cur_dma = 3; break; } switch ((val >> 6) & 0x3) { case 0: optimc->cur_irq = 7; break; case 1: optimc->cur_irq = 10; break; case 2: default: optimc->cur_irq = 5; break; } sb_dsp_setaddr(&optimc->sb->dsp, optimc->cur_addr); sb_dsp_setirq(&optimc->sb->dsp, optimc->cur_irq); sb_dsp_setdma8(&optimc->sb->dsp, optimc->cur_dma); optimc_add_opl(optimc); io_sethandler(optimc->cur_addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, optimc->sb); } break; case 3: /* MC4 */ optimc->regs[3] = val; break; case 4: /* MC5 */ optimc->regs[4] = val; break; case 5: /* MC6 */ optimc->regs[5] = val; if (old != val) { switch ((val >> 3) & 0x3) { case 0: optimc->cur_mpu401_irq = 9; break; case 1: optimc->cur_mpu401_irq = 10; break; case 2: optimc->cur_mpu401_irq = 5; break; case 3: optimc->cur_mpu401_irq = 7; break; default: break; } switch ((val >> 5) & 0x3) { case 0: optimc->cur_mpu401_addr = 0x330; break; case 1: optimc->cur_mpu401_addr = 0x320; break; case 2: optimc->cur_mpu401_addr = 0x310; break; case 3: optimc->cur_mpu401_addr = 0x300; break; default: break; } mpu401_change_addr(optimc->mpu, optimc->cur_mpu401_addr); mpu401_setirq(optimc->mpu, optimc->cur_mpu401_irq); } break; default: break; } } if (optimc->reg_enabled) optimc->reg_enabled = 0; if ((addr == 0xF8F) && ((val == optimc->type) || (val == 0x00))) { if ((addr == 0xF8F) && (val == optimc->type) && !optimc->reg_enabled) optimc->reg_enabled = 1; if (reg_enable_phase) { switch (reg_enable_phase) { case 1: if (val == optimc->type) { reg_enable_phase++; } break; case 2: if (val == 0x00) { reg_enable_phase++; } break; case 3: if (val == optimc->type) { optimc->regs[2] = 0x2; reg_enable_phase = 1; } break; default: break; } } else reg_enable_phase = 1; return; } } static uint8_t optimc_reg_read(uint16_t addr, void *priv) { optimc_t *optimc = (optimc_t *) priv; uint8_t temp = 0xFF; if (optimc->reg_enabled) { switch (addr - 0xF8D) { case 0: /* MC1 */ case 1: /* MC2 */ case 3: /* MC4 */ case 4: /* MC5 */ case 5: /* MC6 */ temp = optimc->regs[addr - 0xF8D]; break; case 2: /* MC3 */ temp = (optimc->regs[2] & ~0x3) | 0x2; break; default: break; } optimc->reg_enabled = 0; } return temp; } static void * optimc_init(const device_t *info) { optimc_t *optimc = calloc(1, sizeof(optimc_t)); optimc->type = info->local & 0xFF; optimc->cur_wss_addr = 0x530; optimc->cur_mode = 0; optimc->cur_addr = 0x220; optimc->cur_irq = 5; optimc->cur_wss_enabled = 0; optimc->cur_dma = 1; optimc->cur_mpu401_irq = 9; optimc->cur_mpu401_addr = 0x330; optimc->cur_mpu401_enabled = 1; optimc->regs[0] = 0x00; optimc->regs[1] = 0x03; optimc->regs[2] = 0x00; optimc->regs[3] = 0x00; optimc->regs[4] = 0x3F; optimc->regs[5] = 0x83; optimc->gameport = gameport_add(&gameport_pnp_device); gameport_remap(optimc->gameport, (optimc->regs[0] & 0x1) ? 0x00 : 0x200); if (info->local & 0x100) ad1848_init(&optimc->ad1848, AD1848_TYPE_CS4231); else ad1848_init(&optimc->ad1848, AD1848_TYPE_DEFAULT); ad1848_setirq(&optimc->ad1848, optimc->cur_wss_irq); ad1848_setdma(&optimc->ad1848, optimc->cur_wss_dma); io_sethandler(0xF8D, 6, optimc_reg_read, NULL, NULL, optimc_reg_write, NULL, NULL, optimc); io_sethandler(optimc->cur_wss_addr, 0x0004, optimc_wss_read, NULL, NULL, optimc_wss_write, NULL, NULL, optimc); io_sethandler(optimc->cur_wss_addr + 0x0004, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &optimc->ad1848); optimc->sb = calloc(1, sizeof(sb_t)); optimc->sb->opl_enabled = 1; optimc->fm_type = (info->local & OPTIMC_OPL4) ? FM_YMF278B : FM_YMF262; sb_dsp_set_real_opl(&optimc->sb->dsp, optimc->fm_type != FM_YMF278B); sb_dsp_init(&optimc->sb->dsp, SBPRO2, SB_SUBTYPE_DEFAULT, optimc); sb_dsp_setaddr(&optimc->sb->dsp, optimc->cur_addr); sb_dsp_setirq(&optimc->sb->dsp, optimc->cur_irq); sb_dsp_setdma8(&optimc->sb->dsp, optimc->cur_dma); sb_ct1345_mixer_reset(optimc->sb); optimc->sb->opl_mixer = optimc; optimc->sb->opl_mix = optimc_filter_opl; fm_driver_get(optimc->fm_type, &optimc->sb->opl); io_sethandler(optimc->cur_addr + 0, 0x0004, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_sethandler(optimc->cur_addr + 8, 0x0002, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_sethandler(0x0388, 0x0004, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); if (optimc->fm_type == FM_YMF278B) io_sethandler(0x380, 2, optimc->sb->opl.read, NULL, NULL, optimc->sb->opl.write, NULL, NULL, optimc->sb->opl.priv); io_sethandler(optimc->cur_addr + 4, 0x0002, sb_ct1345_mixer_read, NULL, NULL, sb_ct1345_mixer_write, NULL, NULL, optimc->sb); sound_add_handler(optimc_get_buffer, optimc); if (optimc->fm_type == FM_YMF278B) wavetable_add_handler(sb_get_music_buffer_sbpro, optimc->sb); else music_add_handler(sb_get_music_buffer_sbpro, optimc->sb); sound_set_cd_audio_filter(sbpro_filter_cd_audio, optimc->sb); /* CD audio filter for the default context */ optimc->mpu = (mpu_t *) malloc(sizeof(mpu_t)); memset(optimc->mpu, 0, sizeof(mpu_t)); mpu401_init(optimc->mpu, optimc->cur_mpu401_addr, optimc->cur_mpu401_irq, M_UART, device_get_config_int("receive_input401")); if (device_get_config_int("receive_input")) midi_in_handler(1, sb_dsp_input_msg, sb_dsp_input_sysex, &optimc->sb->dsp); return optimc; } static void optimc_close(void *priv) { optimc_t *optimc = (optimc_t *) priv; sb_close(optimc->sb); free(optimc->mpu); free(priv); } static void optimc_speed_changed(void *priv) { optimc_t *optimc = (optimc_t *) priv; ad1848_speed_changed(&optimc->ad1848); sb_speed_changed(optimc->sb); } static int mirosound_pcm10_available(void) { return rom_present("roms/sound/yamaha/yrw801.rom"); } static const device_config_t optimc_config[] = { // clang-format off { .name = "receive_input", .description = "Receive input (SB MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "receive_input401", .description = "Receive input (MPU-401)", .type = CONFIG_BINARY, .default_string = "", .default_int = 0 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t acermagic_s20_device = { .name = "AcerMagic S20", .internal_name = "acermagic_s20", .flags = DEVICE_ISA | DEVICE_AT, .local = 0xE3 | OPTIMC_CS4231, .init = optimc_init, .close = optimc_close, .reset = NULL, { .available = NULL }, .speed_changed = optimc_speed_changed, .force_redraw = NULL, .config = optimc_config }; const device_t mirosound_pcm10_device = { .name = "miroSOUND PCM10", .internal_name = "mirosound_pcm10", .flags = DEVICE_ISA | DEVICE_AT, .local = 0xE3 | OPTIMC_OPL4, .init = optimc_init, .close = optimc_close, .reset = NULL, { .available = mirosound_pcm10_available }, .speed_changed = optimc_speed_changed, .force_redraw = NULL, .config = optimc_config }; ```
/content/code_sandbox/src/sound/snd_optimc.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
4,928
```c #include <inttypes.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define _USE_MATH_DEFINES #include <math.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/io.h> #include <86box/mem.h> #include <86box/rom.h> #include <86box/sound.h> #include <86box/snd_emu8k.h> #include <86box/timer.h> #include <86box/plat_unused.h> #if !defined FILTER_INITIAL && !defined FILTER_MOOG && !defined FILTER_CONSTANT #if 0 #define FILTER_INITIAL #endif # define FILTER_MOOG #if 0 #define FILTER_CONSTANT #endif #endif #if !defined RESAMPLER_LINEAR && !defined RESAMPLER_CUBIC #if 0 #define RESAMPLER_LINEAR #endif # define RESAMPLER_CUBIC #endif #if 0 #define EMU8K_DEBUG_REGISTERS #endif char *PORT_NAMES[][8] = { /* Data 0 ( 0x620/0x622) */ { "AWE_CPF", "AWE_PTRX", "AWE_CVCF", "AWE_VTFT", "Unk-620-4", "Unk-620-5", "AWE_PSST", "AWE_CSL", }, /* Data 1 0xA20 */ { "AWE_CCCA", 0, /* "AWE_HWCF4" "AWE_HWCF5" "AWE_HWCF6" "AWE_HWCF7" "AWE_SMALR" "AWE_SMARR" "AWE_SMALW" "AWE_SMARW" "AWE_SMLD" "AWE_SMRD" "AWE_WC" "AWE_HWCF1" "AWE_HWCF2" "AWE_HWCF3" */ 0, //"AWE_INIT1", 0, //"AWE_INIT3", "AWE_ENVVOL", "AWE_DCYSUSV", "AWE_ENVVAL", "AWE_DCYSUS", }, /* Data 2 0xA22 */ { "AWE_CCCA", 0, 0, //"AWE_INIT2", 0, //"AWE_INIT4", "AWE_ATKHLDV", "AWE_LFO1VAL", "AWE_ATKHLD", "AWE_LFO2VAL", }, /* Data 3 0xE20 */ { "AWE_IP", "AWE_IFATN", "AWE_PEFE", "AWE_FMMOD", "AWE_TREMFRQ", "AWE_FM2FRQ2", 0, 0, }, }; enum { ENV_STOPPED = 0, ENV_DELAY = 1, ENV_ATTACK = 2, ENV_HOLD = 3, // ENV_DECAY = 4, ENV_SUSTAIN = 5, // ENV_RELEASE = 6, ENV_RAMP_DOWN = 7, ENV_RAMP_UP = 8 }; static int random_helper = 0; int dmareadbit = 0; int dmawritebit = 0; /* cubic and linear tables resolution. Note: higher than 10 does not improve the result. */ #define CUBIC_RESOLUTION_LOG 10 #define CUBIC_RESOLUTION (1 << CUBIC_RESOLUTION_LOG) /* cubic_table coefficients. */ static float cubic_table[CUBIC_RESOLUTION * 4]; /* conversion from current pitch to linear frequency change (in 32.32 fixed point). */ static int64_t freqtable[65536]; /* Conversion from initial attenuation to 16 bit unsigned lineal amplitude (currently only a way to update volume target register) */ static int32_t attentable[256]; /* Conversion from envelope dbs (once rigth shifted) (0 = 0dBFS, 65535 = -96dbFS and silence ) to 16 bit unsigned lineal amplitude, * to convert to current volume. (0 to 65536) */ static int32_t env_vol_db_to_vol_target[65537]; /* Same as above, but to convert amplitude (once rigth shifted) (0 to 65536) to db (0 = 0dBFS, 65535 = -96dbFS and silence ). * it is needed so that the delay, attack and hold phase can be added to initial attenuation and tremolo */ static int32_t env_vol_amplitude_to_db[65537]; /* Conversion from envelope herts (once right shifted) to octave . it is needed so that the delay, attack and hold phase can be * added to initial pitch ,lfos pitch , initial filter and lfo filter */ static int32_t env_mod_hertz_to_octave[65537]; /* Conversion from envelope amount to time in samples. */ static int32_t env_attack_to_samples[128]; /* This table has been generated using the following formula: * Get the amount of dBs that have to be added each sample to reach 96dBs in the amount * of time determined by the encoded value "i". * float d = 1.0/((env_decay_to_millis[i]/96.0)*44.1); * int result = round(d*21845); * The multiplication by 21845 gives a minimum value of 1, and a maximum accumulated value of 1<<21 * The accumulated value has to be converted to amplitude, and that can be done with the * env_vol_db_to_vol_target and shifting by 8 * In other words, the unit of the table is the 1/21845th of a dB per sample frame, to be added or * substracted to the accumulating value_db of the envelope. */ static int32_t env_decay_to_dbs_or_oct[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 32, 33, 34, 36, 38, 39, 41, 43, 45, 49, 51, 53, 55, 58, 60, 63, 66, 69, 72, 75, 78, 82, 85, 89, 93, 97, 102, 106, 111, 116, 121, 126, 132, 138, 144, 150, 157, 164, 171, 179, 186, 195, 203, 212, 222, 232, 243, 253, 264, 276, 288, 301, 315, 328, 342, 358, 374, 390, 406, 425, 444, 466, 485, 506, 528, 553, 580, 602, 634, 660, 689, 721, 755, 780, 820, 849, 897, 932, 970, 1012, 1057, 1106, 1160, 1219, 1285, 1321, 1399, 1441, 1534, 1585, 1640, 1698, 1829, 1902, 1981, 2068, 2162 }; /* The table "env_decay_to_millis" is based on the table "decay_time_tbl" found in the freebsd/linux * AWE32 driver. * I tried calculating it using the instructions in awe32p10 from Judge Dredd, but the formula there * is wrong. * */ #if 0 static int32_t env_decay_to_millis[128] = { 0, 45120, 22614, 15990, 11307, 9508, 7995, 6723, 5653, 5184, 4754, 4359, 3997, 3665, 3361, 3082, 2828, 2765, 2648, 2535, 2428, 2325, 2226, 2132, 2042, 1955, 1872, 1793, 1717, 1644, 1574, 1507, 1443, 1382, 1324, 1267, 1214, 1162, 1113, 1066, 978, 936, 897, 859, 822, 787, 754, 722, 691, 662, 634, 607, 581, 557, 533, 510, 489, 468, 448, 429, 411, 393, 377, 361, 345, 331, 317, 303, 290, 278, 266, 255, 244, 234, 224, 214, 205, 196, 188, 180, 172, 165, 158, 151, 145, 139, 133, 127, 122, 117, 112, 107, 102, 98, 94, 90, 86, 82, 79, 75, 72, 69, 66, 63, 61, 58, 56, 53, 51, 49, 47, 45, 43, 41, 39, 37, 36, 34, 33, 31, 30, 29, 28, 26, 25, 24, 23, 22, }; #endif /* Table represeting the LFO waveform (signed 16bits with 32768 max int. >> 15 to move back to +/-1 range). */ static int32_t lfotable[65536]; /* Table to transform the speed parameter to emu8k_mem_internal_t range. */ static int64_t lfofreqtospeed[256]; /* LFO used for the chorus. a sine wave.(signed 16bits with 32768 max int. >> 15 to move back to +/-1 range). */ static double chortable[65536]; static const int REV_BUFSIZE_STEP = 242; /* These lines come from the awe32faq, describing the NRPN control for the initial filter * where it describes a linear increment filter instead of an octave-incremented one. * NRPN LSB 21 (Initial Filter Cutoff) * Range : [0, 127] * Unit : 62Hz * Filter cutoff from 100Hz to 8000Hz * This table comes from the awe32faq, describing the NRPN control for the filter Q. * I don't know if is meant to be interpreted as the actual measured output of the * filter or what. Especially, I don't understand the "low" and "high" ranges. * What is otherwise documented is that the Q ranges from 0dB to 24dB and the attenuation * is half of the Q ( i.e. for 12dB Q, attenuate the input signal with -6dB) Coeff Low Fc(Hz)Low Q(dB)High Fc(kHz)High Q(dB)DC Attenuation(dB) * 0 92 5 Flat Flat -0.0 * 1 93 6 8.5 0.5 -0.5 * 2 94 8 8.3 1 -1.2 * 3 95 10 8.2 2 -1.8 * 4 96 11 8.1 3 -2.5 * 5 97 13 8.0 4 -3.3 * 6 98 14 7.9 5 -4.1 * 7 99 16 7.8 6 -5.5 * 8 100 17 7.7 7 -6.0 * 9 100 19 7.5 9 -6.6 * 10 100 20 7.4 10 -7.2 * 11 100 22 7.3 11 -7.9 * 12 100 23 7.2 13 -8.5 * 13 100 25 7.1 15 -9.3 * 14 100 26 7.1 16 -10.1 * 15 100 28 7.0 18 -11.0 * * Attenuation as above, codified in amplitude.*/ static int32_t filter_atten[16] = { 65536, 61869, 57079, 53269, 49145, 44820, 40877, 34792, 32845, 30653, 28607, 26392, 24630, 22463, 20487, 18470 }; /*Coefficients for the filters for a defined Q and cutoff.*/ static int32_t filt_coeffs[16][256][3]; #define READ16_SWITCH(addr, var) \ switch ((addr) &2) { \ case 0: \ ret = (var) &0xffff; \ break; \ case 2: \ ret = ((var) >> 16) & 0xffff; \ break; \ } #define WRITE16_SWITCH(addr, var, val) \ switch ((addr) &2) { \ case 0: \ var = (var & 0xffff0000) | (val); \ break; \ case 2: \ var = (var & 0x0000ffff) | ((val) << 16); \ break; \ } #ifdef EMU8K_DEBUG_REGISTERS uint32_t dw_value = 0; uint32_t last_read = 0; uint32_t last_write = 0; uint32_t rep_count_r = 0; uint32_t rep_count_w = 0; # define READ16(addr, var) \ READ16_SWITCH(addr, var) \ { \ const char *name = 0; \ switch (addr & 0xF02) { \ case 0x600: \ case 0x602: \ name = PORT_NAMES[0][emu8k->cur_reg]; \ break; \ case 0xA00: \ name = PORT_NAMES[1][emu8k->cur_reg]; \ break; \ case 0xA02: \ name = PORT_NAMES[2][emu8k->cur_reg]; \ break; \ } \ if (name == 0) { \ /*emu8k_log("EMU8K READ %04X-%02X(%d): %04X\n",addr,(emu8k->cur_reg)<<5|emu8k->cur_voice, emu8k->cur_voice,ret);*/ \ } else { \ emu8k_log("EMU8K READ %s(%d) (%d): %04X\n", name, (addr & 0x2), emu8k->cur_voice, ret); \ } \ } # define WRITE16(addr, var, val) \ WRITE16_SWITCH(addr, var, val) \ { \ const char *name = 0; \ switch (addr & 0xF02) { \ case 0x600: \ case 0x602: \ name = PORT_NAMES[0][emu8k->cur_reg]; \ break; \ case 0xA00: \ name = PORT_NAMES[1][emu8k->cur_reg]; \ break; \ case 0xA02: \ name = PORT_NAMES[2][emu8k->cur_reg]; \ break; \ } \ if (name == 0) { \ /*emu8k_log("EMU8K WRITE %04X-%02X(%d): %04X\n",addr,(emu8k->cur_reg)<<5|emu8k->cur_voice,emu8k->cur_voice, val);*/ \ } else { \ emu8k_log("EMU8K WRITE %s(%d) (%d): %04X\n", name, (addr & 0x2), emu8k->cur_voice, val); \ } \ } #else # define READ16(addr, var) READ16_SWITCH(addr, var) # define WRITE16(addr, var, val) WRITE16_SWITCH(addr, var, val) #endif // EMU8K_DEBUG_REGISTERS #ifdef ENABLE_EMU8K_LOG int emu8k_do_log = ENABLE_EMU8K_LOG; static void emu8k_log(const char *fmt, ...) { va_list ap; if (emu8k_do_log) { va_start(ap, fmt); pclog_ex(fmt, ap); va_end(ap); } } #else # define emu8k_log(fmt, ...) #endif static inline int16_t EMU8K_READ(emu8k_t *emu8k, uint32_t addr) { const register emu8k_mem_pointers_t addrmem = { { addr } }; return emu8k->ram_pointers[addrmem.hb_address][addrmem.lw_address]; } #if NOTUSED static inline int16_t EMU8K_READ_INTERP_LINEAR(emu8k_t *emu8k, uint32_t int_addr, uint16_t fract) { /* The interpolation in AWE32 used a so-called patented 3-point interpolation * ( I guess some sort of spline having one point before and one point after). * Also, it has the consequence that the playback is delayed by one sample. * I simulate the "one sample later" than the address with addr+1 and addr+2 * instead of +0 and +1 */ int16_t dat1 = EMU8K_READ(emu8k, int_addr + 1); int32_t dat2 = EMU8K_READ(emu8k, int_addr + 2); dat1 += ((dat2 - (int32_t) dat1) * fract) >> 16; return dat1; } #endif static inline int32_t EMU8K_READ_INTERP_CUBIC(emu8k_t *emu8k, uint32_t int_addr, uint16_t fract) { /*Since there are four floats in the table for each fraction, the position is 16byte aligned. */ fract >>= 16 - CUBIC_RESOLUTION_LOG; fract <<= 2; /* TODO: I still have to verify how this works, but I think that * the card could use two oscillators (usually 31 and 32) where it would * be writing the OPL3 output, and to which, chorus and reverb could be applied to get * those effects for OPL3 sounds.*/ #if 0 if ((addr & EMU8K_FM_MEM_ADDRESS) == EMU8K_FM_MEM_ADDRESS) {} #endif /* This is cubic interpolation. * Not the same than 3-point interpolation, but a better approximation than linear * interpolation. * Also, it takes into account the "Note that the actual audio location is the point * 1 word higher than this value due to interpolation offset". * That's why the pointers are 0, 1, 2, 3 and not -1, 0, 1, 2 */ int32_t dat2 = EMU8K_READ(emu8k, int_addr + 1); const float *table = &cubic_table[fract]; const int32_t dat1 = EMU8K_READ(emu8k, int_addr); const int32_t dat3 = EMU8K_READ(emu8k, int_addr + 2); const int32_t dat4 = EMU8K_READ(emu8k, int_addr + 3); /* Note: I've ended using float for the table values to avoid some cases of integer overflow. */ dat2 = dat1 * table[0] + dat2 * table[1] + dat3 * table[2] + dat4 * table[3]; return dat2; } static inline void EMU8K_WRITE(emu8k_t *emu8k, uint32_t addr, uint16_t val) { addr &= EMU8K_MEM_ADDRESS_MASK; if (!emu8k->ram || addr < EMU8K_RAM_MEM_START || addr >= EMU8K_FM_MEM_ADDRESS) return; /* It looks like if an application writes to a memory part outside of the available * amount on the card, it wraps, and opencubicplayer uses that to detect the amount * of memory, as opposed to simply check at the address that it has just tried to write. */ while (addr >= emu8k->ram_end_addr) addr -= emu8k->ram_end_addr - EMU8K_RAM_MEM_START; emu8k->ram[addr - EMU8K_RAM_MEM_START] = val; } uint16_t emu8k_inw(uint16_t addr, void *priv) { emu8k_t *emu8k = (emu8k_t *) priv; uint16_t ret = 0xffff; #ifdef EMU8K_DEBUG_REGISTERS if (addr == 0xE22) { emu8k_log("EMU8K READ POINTER: %d\n", ((0x80 | ((random_helper + 1) & 0x1F)) << 8) | (emu8k->cur_reg << 5) | emu8k->cur_voice); } else if ((addr & 0xF00) == 0x600) { /* These are automatically reported by READ16 */ if (rep_count_r > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_r); rep_count_r = 0; } last_read = 0; } else if ((addr & 0xF00) == 0xA00 && emu8k->cur_reg == 0) { /* These are automatically reported by READ16 */ if (rep_count_r > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_r); rep_count_r = 0; } last_read = 0; } else if ((addr & 0xF00) == 0xA00 && emu8k->cur_reg == 1) { uint32_t tmpz = ((addr & 0xF00) << 16) | (emu8k->cur_reg << 5); if (tmpz != last_read) { if (rep_count_r > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_r); rep_count_r = 0; } last_read = tmpz; emu8k_log("EMU8K READ RAM I/O or configuration or clock \n"); } // emu8k_log("EMU8K READ %04X-%02X(%d/%d)\n",addr,(emu8k->cur_reg)<<5|emu8k->cur_voice, emu8k->cur_reg, emu8k->cur_voice); } else if ((addr & 0xF00) == 0xA00 && (emu8k->cur_reg == 2 || emu8k->cur_reg == 3)) { uint32_t tmpz = ((addr & 0xF00) << 16); if (tmpz != last_read) { if (rep_count_r > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_r); rep_count_r = 0; } last_read = tmpz; emu8k_log("EMU8K READ INIT \n"); } // emu8k_log("EMU8K READ %04X-%02X(%d/%d)\n",addr,(emu8k->cur_reg)<<5|emu8k->cur_voice, emu8k->cur_reg, emu8k->cur_voice); } else { uint32_t tmpz = (addr << 16) | (emu8k->cur_reg << 5) | emu8k->cur_voice; if (tmpz != last_read) { char *name = 0; uint16_t val = 0xBAAD; if (addr == 0xA20) { name = PORT_NAMES[1][emu8k->cur_reg]; switch (emu8k->cur_reg) { case 2: val = emu8k->init1[emu8k->cur_voice]; break; case 3: val = emu8k->init3[emu8k->cur_voice]; break; case 4: val = emu8k->voice[emu8k->cur_voice].envvol; break; case 5: val = emu8k->voice[emu8k->cur_voice].dcysusv; break; case 6: val = emu8k->voice[emu8k->cur_voice].envval; break; case 7: val = emu8k->voice[emu8k->cur_voice].dcysus; break; } } else if (addr == 0xA22) { name = PORT_NAMES[2][emu8k->cur_reg]; switch (emu8k->cur_reg) { case 2: val = emu8k->init2[emu8k->cur_voice]; break; case 3: val = emu8k->init4[emu8k->cur_voice]; break; case 4: val = emu8k->voice[emu8k->cur_voice].atkhldv; break; case 5: val = emu8k->voice[emu8k->cur_voice].lfo1val; break; case 6: val = emu8k->voice[emu8k->cur_voice].atkhld; break; case 7: val = emu8k->voice[emu8k->cur_voice].lfo2val; break; } } else if (addr == 0xE20) { name = PORT_NAMES[3][emu8k->cur_reg]; switch (emu8k->cur_reg) { case 0: val = emu8k->voice[emu8k->cur_voice].ip; break; case 1: val = emu8k->voice[emu8k->cur_voice].ifatn; break; case 2: val = emu8k->voice[emu8k->cur_voice].pefe; break; case 3: val = emu8k->voice[emu8k->cur_voice].fmmod; break; case 4: val = emu8k->voice[emu8k->cur_voice].tremfrq; break; case 5: val = emu8k->voice[emu8k->cur_voice].fm2frq2; break; case 6: val = 0xffff; break; case 7: val = 0x1c | ((emu8k->id & 0x0002) ? 0xff02 : 0); break; } } if (rep_count_r > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_r); } if (name == 0) { emu8k_log("EMU8K READ %04X-%02X(%d/%d): %04X\n", addr, (emu8k->cur_reg) << 5 | emu8k->cur_voice, emu8k->cur_reg, emu8k->cur_voice, val); } else { emu8k_log("EMU8K READ %s (%d): %04X\n", name, emu8k->cur_voice, val); } rep_count_r = 0; last_read = tmpz; } rep_count_r++; } #endif // EMU8K_DEBUG_REGISTERS switch (addr & 0xF02) { case 0x600: case 0x602: /*Data0. also known as BLASTER+0x400 and EMU+0x000 */ switch (emu8k->cur_reg) { case 0: READ16(addr, emu8k->voice[emu8k->cur_voice].cpf); return ret; case 1: READ16(addr, emu8k->voice[emu8k->cur_voice].ptrx); return ret; case 2: READ16(addr, emu8k->voice[emu8k->cur_voice].cvcf); return ret; case 3: READ16(addr, emu8k->voice[emu8k->cur_voice].vtft); return ret; case 4: READ16(addr, emu8k->voice[emu8k->cur_voice].unknown_data0_4); return ret; case 5: READ16(addr, emu8k->voice[emu8k->cur_voice].unknown_data0_5); return ret; case 6: READ16(addr, emu8k->voice[emu8k->cur_voice].psst); return ret; case 7: READ16(addr, emu8k->voice[emu8k->cur_voice].csl); return ret; default: break; } break; case 0xA00: /*Data1. also known as BLASTER+0x800 and EMU+0x400 */ switch (emu8k->cur_reg) { case 0: READ16(addr, emu8k->voice[emu8k->cur_voice].ccca); return ret; case 1: switch (emu8k->cur_voice) { case 9: READ16(addr, emu8k->hwcf4); return ret; case 10: READ16(addr, emu8k->hwcf5); return ret; /* Actually, these two might be command words rather than registers, or some LFO position/buffer reset.*/ case 13: READ16(addr, emu8k->hwcf6); return ret; case 14: READ16(addr, emu8k->hwcf7); return ret; case 20: READ16(addr, emu8k->smalr); return ret; case 21: READ16(addr, emu8k->smarr); return ret; case 22: READ16(addr, emu8k->smalw); return ret; case 23: READ16(addr, emu8k->smarw); return ret; case 26: { uint16_t val = emu8k->smld_buffer; emu8k->smld_buffer = EMU8K_READ(emu8k, emu8k->smalr); emu8k->smalr = (emu8k->smalr + 1) & EMU8K_MEM_ADDRESS_MASK; return val; } /*The EMU8000 PGM describes the return values of these registers as 'a VLSI error'*/ case 29: /*Configuration Word 1*/ return (emu8k->hwcf1 & 0xfe) | (emu8k->hwcf3 & 0x01); case 30: /*Configuration Word 2*/ return ((emu8k->hwcf2 >> 4) & 0x0e) | (emu8k->hwcf1 & 0x01) | ((emu8k->hwcf3 & 0x02) ? 0x10 : 0) | ((emu8k->hwcf3 & 0x04) ? 0x40 : 0) | ((emu8k->hwcf3 & 0x08) ? 0x20 : 0) | ((emu8k->hwcf3 & 0x10) ? 0x80 : 0); case 31: /*Configuration Word 3*/ return emu8k->hwcf2 & 0x1f; default: break; } break; case 2: return emu8k->init1[emu8k->cur_voice]; case 3: return emu8k->init3[emu8k->cur_voice]; case 4: return emu8k->voice[emu8k->cur_voice].envvol; case 5: return emu8k->voice[emu8k->cur_voice].dcysusv; case 6: return emu8k->voice[emu8k->cur_voice].envval; case 7: return emu8k->voice[emu8k->cur_voice].dcysus; default: break; } break; case 0xA02: /*Data2. also known as BLASTER+0x802 and EMU+0x402 */ switch (emu8k->cur_reg) { case 0: READ16(addr, emu8k->voice[emu8k->cur_voice].ccca); return ret; case 1: switch (emu8k->cur_voice) { case 9: READ16(addr, emu8k->hwcf4); return ret; case 10: READ16(addr, emu8k->hwcf5); return ret; /* Actually, these two might be command words rather than registers, or some LFO position/buffer reset. */ case 13: READ16(addr, emu8k->hwcf6); return ret; case 14: READ16(addr, emu8k->hwcf7); return ret; /* Simulating empty/full bits by unsetting it once read. */ case 20: READ16(addr, emu8k->smalr | dmareadbit); /* xor with itself to set to zero faster. */ dmareadbit ^= dmareadbit; return ret; case 21: READ16(addr, emu8k->smarr | dmareadbit); /* xor with itself to set to zero faster.*/ dmareadbit ^= dmareadbit; return ret; case 22: READ16(addr, emu8k->smalw | dmawritebit); /*xor with itself to set to zero faster.*/ dmawritebit ^= dmawritebit; return ret; case 23: READ16(addr, emu8k->smarw | dmawritebit); /*xor with itself to set to zero faster.*/ dmawritebit ^= dmawritebit; return ret; case 26: { uint16_t val = emu8k->smrd_buffer; emu8k->smrd_buffer = EMU8K_READ(emu8k, emu8k->smarr); emu8k->smarr = (emu8k->smarr + 1) & EMU8K_MEM_ADDRESS_MASK; return val; } /*TODO: We need to improve the precision of this clock, since it is used by programs to wait. Not critical, but should help reduce the amount of calls and wait time */ case 27: /*Sample Counter ( 44Khz clock) */ return emu8k->wc; default: break; } break; case 2: return emu8k->init2[emu8k->cur_voice]; case 3: return emu8k->init4[emu8k->cur_voice]; case 4: return emu8k->voice[emu8k->cur_voice].atkhldv; case 5: return emu8k->voice[emu8k->cur_voice].lfo1val; case 6: return emu8k->voice[emu8k->cur_voice].atkhld; case 7: return emu8k->voice[emu8k->cur_voice].lfo2val; default: break; } break; case 0xE00: /*Data3. also known as BLASTER+0xC00 and EMU+0x800 */ switch (emu8k->cur_reg) { case 0: return emu8k->voice[emu8k->cur_voice].ip; case 1: return emu8k->voice[emu8k->cur_voice].ifatn; case 2: return emu8k->voice[emu8k->cur_voice].pefe; case 3: return emu8k->voice[emu8k->cur_voice].fmmod; case 4: return emu8k->voice[emu8k->cur_voice].tremfrq; case 5: return emu8k->voice[emu8k->cur_voice].fm2frq2; case 6: return 0xffff; case 7: /*ID?*/ return 0x1c | ((emu8k->id & 0x0002) ? 0xff02 : 0); default: break; } break; case 0xE02: /* Pointer. also known as BLASTER+0xC02 and EMU+0x802 */ /* LS five bits = channel number, next 3 bits = register number * and MS 8 bits = VLSI test register. * Impulse tracker tests the non variability of the LS byte that it has set, and the variability * of the MS byte to determine that it really is an AWE32. * cubic player has a similar code, where it waits until value & 0x1000 is nonzero, and then waits again until it changes to zero.*/ random_helper = (random_helper + 1) & 0x1F; return ((0x80 | random_helper) << 8) | (emu8k->cur_reg << 5) | emu8k->cur_voice; default: break; } emu8k_log("EMU8K READ : Unknown register read: %04X-%02X(%d/%d) \n", addr, (emu8k->cur_reg << 5) | emu8k->cur_voice, emu8k->cur_reg, emu8k->cur_voice); return 0xffff; } void emu8k_outw(uint16_t addr, uint16_t val, void *priv) { emu8k_t *emu8k = (emu8k_t *) priv; /*TODO: I would like to not call this here, but i found it was needed or else cubic player would not finish opening (take a looot more of time than usual). * Basically, being here means that the audio is generated in the emulation thread, instead of the audio thread.*/ emu8k_update(emu8k); #ifdef EMU8K_DEBUG_REGISTERS if (addr == 0xE22) { // emu8k_log("EMU8K WRITE POINTER: %d\n", val); } else if ((addr & 0xF00) == 0x600) { /* These are automatically reported by WRITE16 */ if (rep_count_w > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_w); rep_count_w = 0; } last_write = 0; } else if ((addr & 0xF00) == 0xA00 && emu8k->cur_reg == 0) { /* These are automatically reported by WRITE16 */ if (rep_count_w > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_w); rep_count_w = 0; } last_write = 0; } else if ((addr & 0xF00) == 0xA00 && emu8k->cur_reg == 1) { uint32_t tmpz = ((addr & 0xF00) << 16) | (emu8k->cur_reg << 5); if (tmpz != last_write) { if (rep_count_w > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_w); rep_count_w = 0; } last_write = tmpz; emu8k_log("EMU8K WRITE RAM I/O or configuration \n"); } // emu8k_log("EMU8K WRITE %04X-%02X(%d/%d): %04X\n",addr,(emu8k->cur_reg)<<5|emu8k->cur_voice,emu8k->cur_reg,emu8k->cur_voice, val); } else if ((addr & 0xF00) == 0xA00 && (emu8k->cur_reg == 2 || emu8k->cur_reg == 3)) { uint32_t tmpz = ((addr & 0xF00) << 16); if (tmpz != last_write) { if (rep_count_w > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_w); rep_count_w = 0; } last_write = tmpz; emu8k_log("EMU8K WRITE INIT \n"); } // emu8k_log("EMU8K WRITE %04X-%02X(%d/%d): %04X\n",addr,(emu8k->cur_reg)<<5|emu8k->cur_voice,emu8k->cur_reg,emu8k->cur_voice, val); } else if (addr != 0xE22) { uint32_t tmpz = (addr << 16) | (emu8k->cur_reg << 5) | emu8k->cur_voice; // if (tmpz != last_write) if (1) { char *name = 0; if (addr == 0xA20) { name = PORT_NAMES[1][emu8k->cur_reg]; } else if (addr == 0xA22) { name = PORT_NAMES[2][emu8k->cur_reg]; } else if (addr == 0xE20) { name = PORT_NAMES[3][emu8k->cur_reg]; } if (rep_count_w > 1) { emu8k_log("EMU8K ...... for %d times\n", rep_count_w); } if (name == 0) { emu8k_log("EMU8K WRITE %04X-%02X(%d/%d): %04X\n", addr, (emu8k->cur_reg) << 5 | emu8k->cur_voice, emu8k->cur_reg, emu8k->cur_voice, val); } else { emu8k_log("EMU8K WRITE %s (%d): %04X\n", name, emu8k->cur_voice, val); } rep_count_w = 0; last_write = tmpz; } rep_count_w++; } #endif // EMU8K_DEBUG_REGISTERS switch (addr & 0xF02) { case 0x600: case 0x602: /*Data0. also known as BLASTER+0x400 and EMU+0x000 */ switch (emu8k->cur_reg) { case 0: /* The docs says that this value is constantly updating, and it should have no actual effect. Actions should be done over ptrx */ WRITE16(addr, emu8k->voice[emu8k->cur_voice].cpf, val); return; case 1: WRITE16(addr, emu8k->voice[emu8k->cur_voice].ptrx, val); return; case 2: /* The docs says that this value is constantly updating, and it should have no actual effect. Actions should be done over vtft */ WRITE16(addr, emu8k->voice[emu8k->cur_voice].cvcf, val); return; case 3: WRITE16(addr, emu8k->voice[emu8k->cur_voice].vtft, val); return; case 4: WRITE16(addr, emu8k->voice[emu8k->cur_voice].unknown_data0_4, val); return; case 5: WRITE16(addr, emu8k->voice[emu8k->cur_voice].unknown_data0_5, val); return; case 6: { emu8k_voice_t *emu_voice = &emu8k->voice[emu8k->cur_voice]; WRITE16(addr, emu_voice->psst, val); /* TODO: Should we update only on MSB update, or this could be used as some sort of hack by applications? */ emu_voice->loop_start.int_address = emu_voice->psst & EMU8K_MEM_ADDRESS_MASK; if (addr & 2) { emu_voice->vol_l = emu_voice->psst_pan; emu_voice->vol_r = 255 - (emu_voice->psst_pan); } } return; case 7: WRITE16(addr, emu8k->voice[emu8k->cur_voice].csl, val); /* TODO: Should we update only on MSB update, or this could be used as some sort of hack by applications? */ emu8k->voice[emu8k->cur_voice].loop_end.int_address = emu8k->voice[emu8k->cur_voice].csl & EMU8K_MEM_ADDRESS_MASK; return; default: break; } break; case 0xA00: /*Data1. also known as BLASTER+0x800 and EMU+0x400 */ switch (emu8k->cur_reg) { case 0: WRITE16(addr, emu8k->voice[emu8k->cur_voice].ccca, val); /* TODO: Should we update only on MSB update, or this could be used as some sort of hack by applications? */ emu8k->voice[emu8k->cur_voice].addr.int_address = emu8k->voice[emu8k->cur_voice].ccca & EMU8K_MEM_ADDRESS_MASK; return; case 1: switch (emu8k->cur_voice) { case 9: WRITE16(addr, emu8k->hwcf4, val); return; case 10: WRITE16(addr, emu8k->hwcf5, val); return; /* Actually, these two might be command words rather than registers, or some LFO position/buffer reset. */ case 13: WRITE16(addr, emu8k->hwcf6, val); return; case 14: WRITE16(addr, emu8k->hwcf7, val); return; case 20: WRITE16(addr, emu8k->smalr, val); return; case 21: WRITE16(addr, emu8k->smarr, val); return; case 22: WRITE16(addr, emu8k->smalw, val); return; case 23: WRITE16(addr, emu8k->smarw, val); return; case 26: EMU8K_WRITE(emu8k, emu8k->smalw, val); emu8k->smalw = (emu8k->smalw + 1) & EMU8K_MEM_ADDRESS_MASK; return; case 29: emu8k->hwcf1 = val; return; case 30: emu8k->hwcf2 = val; return; case 31: emu8k->hwcf3 = val; return; default: break; } break; case 2: emu8k->init1[emu8k->cur_voice] = val; /* Skip if in first/second initialization step */ if (emu8k->init1[0] != 0x03FF) { switch (emu8k->cur_voice) { case 0x3: emu8k->reverb_engine.out_mix = val & 0xFF; break; case 0x5: { for (uint8_t c = 0; c < 8; c++) { emu8k->reverb_engine.allpass[c].feedback = (val & 0xFF) / ((float) 0xFF); } } break; case 0x7: emu8k->reverb_engine.link_return_type = (val == 0x8474) ? 1 : 0; break; case 0xF: emu8k->reverb_engine.reflections[0].output_gain = ((val & 0xF0) >> 4) / 15.0; break; case 0x17: emu8k->reverb_engine.reflections[1].output_gain = ((val & 0xF0) >> 4) / 15.0; break; case 0x1F: emu8k->reverb_engine.reflections[2].output_gain = ((val & 0xF0) >> 4) / 15.0; break; case 0x9: emu8k->reverb_engine.reflections[0].feedback = (val & 0xF) / 15.0; break; case 0xB: #if 0 emu8k->reverb_engine.reflections[0].feedback_r = (val&0xF)/15.0; #endif break; case 0x11: emu8k->reverb_engine.reflections[1].feedback = (val & 0xF) / 15.0; break; case 0x13: #if 0 emu8k->reverb_engine.reflections[1].feedback_r = (val&0xF)/15.0; #endif break; case 0x19: emu8k->reverb_engine.reflections[2].feedback = (val & 0xF) / 15.0; break; case 0x1B: #if 0 emu8k->reverb_engine.reflections[2].feedback_r = (val&0xF)/15.0; #endif break; default: break; } } return; case 3: emu8k->init3[emu8k->cur_voice] = val; /* Skip if in first/second initialization step */ if (emu8k->init1[0] != 0x03FF) { switch (emu8k->cur_voice) { case 9: emu8k->chorus_engine.feedback = (val & 0xFF); break; case 12: /* Limiting this to a sane value given our buffer. */ emu8k->chorus_engine.delay_samples_central = (val & 0x1FFF); break; case 1: emu8k->reverb_engine.refl_in_amp = val & 0xFF; break; case 3: #if 0 emu8k->reverb_engine.refl_in_amp_r = val&0xFF; #endif break; default: break; } } return; case 4: emu8k->voice[emu8k->cur_voice].envvol = val; emu8k->voice[emu8k->cur_voice].vol_envelope.delay_samples = ENVVOL_TO_EMU_SAMPLES(val); return; case 5: { emu8k->voice[emu8k->cur_voice].dcysusv = val; emu8k_envelope_t *const vol_env = &emu8k->voice[emu8k->cur_voice].vol_envelope; int old_on = emu8k->voice[emu8k->cur_voice].env_engine_on; emu8k->voice[emu8k->cur_voice].env_engine_on = DCYSUSV_GENERATOR_ENGINE_ON(val); if (emu8k->voice[emu8k->cur_voice].env_engine_on && old_on != emu8k->voice[emu8k->cur_voice].env_engine_on) { if (emu8k->hwcf3 != 0x04) { /* This is a hack for some programs like Doom or cubic player 1.7 that don't initialize the hwcfg and init registers (doom does not init the card at all. only tests the cfg registers) */ emu8k->hwcf3 = 0x04; } // reset lfos. emu8k->voice[emu8k->cur_voice].lfo1_count.addr = 0; emu8k->voice[emu8k->cur_voice].lfo2_count.addr = 0; // Trigger envelopes if (ATKHLDV_TRIGGER(emu8k->voice[emu8k->cur_voice].atkhldv)) { vol_env->value_amp_hz = 0; if (vol_env->delay_samples) { vol_env->state = ENV_DELAY; } else if (vol_env->attack_amount_amp_hz == 0) { vol_env->state = ENV_STOPPED; } else { vol_env->state = ENV_ATTACK; /* TODO: Verify if "never attack" means eternal mute, * or it means skip attack, go to hold". if (vol_env->attack_amount == 0) { vol_env->value = (1 << 21); vol_env->state = ENV_HOLD; }*/ } } if (ATKHLD_TRIGGER(emu8k->voice[emu8k->cur_voice].atkhld)) { emu8k_envelope_t *const mod_env = &emu8k->voice[emu8k->cur_voice].mod_envelope; mod_env->value_amp_hz = 0; mod_env->value_db_oct = 0; if (mod_env->delay_samples) { mod_env->state = ENV_DELAY; } else if (mod_env->attack_amount_amp_hz == 0) { mod_env->state = ENV_STOPPED; } else { mod_env->state = ENV_ATTACK; /* TODO: Verify if "never attack" means eternal start, * or it means skip attack, go to hold". if (mod_env->attack_amount == 0) { mod_env->value = (1 << 21); mod_env->state = ENV_HOLD; }*/ } } } /* Converting the input in dBs to envelope value range. */ vol_env->sustain_value_db_oct = DCYSUSV_SUS_TO_ENV_RANGE(DCYSUSV_SUSVALUE_GET(val)); vol_env->ramp_amount_db_oct = env_decay_to_dbs_or_oct[DCYSUSV_DECAYRELEASE_GET(val)]; if (DCYSUSV_IS_RELEASE(val)) { if (vol_env->state == ENV_DELAY || vol_env->state == ENV_ATTACK || vol_env->state == ENV_HOLD) { vol_env->value_db_oct = env_vol_amplitude_to_db[vol_env->value_amp_hz >> 5] << 5; if (vol_env->value_db_oct > (1 << 21)) vol_env->value_db_oct = 1 << 21; } vol_env->state = (vol_env->value_db_oct >= vol_env->sustain_value_db_oct) ? ENV_RAMP_DOWN : ENV_RAMP_UP; } } return; case 6: emu8k->voice[emu8k->cur_voice].envval = val; emu8k->voice[emu8k->cur_voice].mod_envelope.delay_samples = ENVVAL_TO_EMU_SAMPLES(val); return; case 7: { // TODO: Look for a bug on delay (first trigger it works, next trigger it doesn't) emu8k->voice[emu8k->cur_voice].dcysus = val; emu8k_envelope_t *const mod_env = &emu8k->voice[emu8k->cur_voice].mod_envelope; /* Converting the input in octaves to envelope value range. */ mod_env->sustain_value_db_oct = DCYSUS_SUS_TO_ENV_RANGE(DCYSUS_SUSVALUE_GET(val)); mod_env->ramp_amount_db_oct = env_decay_to_dbs_or_oct[DCYSUS_DECAYRELEASE_GET(val)]; if (DCYSUS_IS_RELEASE(val)) { if (mod_env->state == ENV_DELAY || mod_env->state == ENV_ATTACK || mod_env->state == ENV_HOLD) { mod_env->value_db_oct = env_mod_hertz_to_octave[mod_env->value_amp_hz >> 9] << 9; if (mod_env->value_db_oct >= (1 << 21)) mod_env->value_db_oct = (1 << 21) - 1; } mod_env->state = (mod_env->value_db_oct >= mod_env->sustain_value_db_oct) ? ENV_RAMP_DOWN : ENV_RAMP_UP; } } return; default: break; } break; case 0xA02: /*Data2. also known as BLASTER+0x802 and EMU+0x402 */ switch (emu8k->cur_reg) { case 0: { emu8k_voice_t *emu_voice = &emu8k->voice[emu8k->cur_voice]; WRITE16(addr, emu_voice->ccca, val); emu_voice->addr.int_address = emu_voice->ccca & EMU8K_MEM_ADDRESS_MASK; uint32_t paramq = CCCA_FILTQ_GET(emu_voice->ccca); emu_voice->filt_att = filter_atten[paramq]; emu_voice->filterq_idx = paramq; } return; case 1: switch (emu8k->cur_voice) { case 9: WRITE16(addr, emu8k->hwcf4, val); /* Skip if in first/second initialization step */ if (emu8k->init1[0] != 0x03FF) { /*(1/256th of a 44Khz sample) */ /* clip the value to a reasonable value given our buffer */ int32_t tmp = emu8k->hwcf4 & 0x1FFFFF; emu8k->chorus_engine.delay_offset_samples_right = ((double) tmp) / 256.0; } return; case 10: WRITE16(addr, emu8k->hwcf5, val); /* Skip if in first/second initialization step */ if (emu8k->init1[0] != 0x03FF) { /* The scale of this value is unknown. I've taken it as milliHz. * Another interpretation could be periods. (and so, Hz = 1/period)*/ double osc_speed = emu8k->hwcf5; //*1.316; #if 1 // milliHz /*milliHz to lfotable samples.*/ osc_speed *= 65.536 / 44100.0; #elif 0 // periods /* 44.1Khz ticks to lfotable samples.*/ osc_speed = 65.536 / osc_speed; #endif /*left shift 32bits for 32.32 fixed.point*/ osc_speed *= 65536.0 * 65536.0; emu8k->chorus_engine.lfo_inc.addr = (uint64_t) osc_speed; } return; /* Actually, these two might be command words rather than registers, or some LFO position/buffer reset.*/ case 13: WRITE16(addr, emu8k->hwcf6, val); return; case 14: WRITE16(addr, emu8k->hwcf7, val); return; case 20: /*Top 8 bits are for Empty (MT) bit or non-addressable.*/ WRITE16(addr, emu8k->smalr, val & 0xFF); dmareadbit = 0x8000; return; case 21: /*Top 8 bits are for Empty (MT) bit or non-addressable.*/ WRITE16(addr, emu8k->smarr, val & 0xFF); dmareadbit = 0x8000; return; case 22: /*Top 8 bits are for full bit or non-addressable.*/ WRITE16(addr, emu8k->smalw, val & 0xFF); return; case 23: /*Top 8 bits are for full bit or non-addressable.*/ WRITE16(addr, emu8k->smarw, val & 0xFF); return; case 26: dmawritebit = 0x8000; EMU8K_WRITE(emu8k, emu8k->smarw, val); emu8k->smarw++; return; default: break; } break; case 2: emu8k->init2[emu8k->cur_voice] = val; /* Skip if in first/second initialization step */ if (emu8k->init1[0] != 0x03FF) { switch (emu8k->cur_voice) { case 0x14: { int multip = ((val & 0xF00) >> 8) + 18; emu8k->reverb_engine.reflections[5].bufsize = multip * REV_BUFSIZE_STEP; emu8k->reverb_engine.tailL.bufsize = (multip + 1) * REV_BUFSIZE_STEP; if (emu8k->reverb_engine.link_return_type == 0) { emu8k->reverb_engine.tailR.bufsize = (multip + 1) * REV_BUFSIZE_STEP; } } break; case 0x16: if (emu8k->reverb_engine.link_return_type == 1) { int multip = ((val & 0xF00) >> 8) + 18; emu8k->reverb_engine.tailR.bufsize = (multip + 1) * REV_BUFSIZE_STEP; } break; case 0x7: emu8k->reverb_engine.reflections[3].output_gain = ((val & 0xF0) >> 4) / 15.0; break; case 0xf: emu8k->reverb_engine.reflections[4].output_gain = ((val & 0xF0) >> 4) / 15.0; break; case 0x17: emu8k->reverb_engine.reflections[5].output_gain = ((val & 0xF0) >> 4) / 15.0; break; case 0x1d: { for (uint8_t c = 0; c < 6; c++) { emu8k->reverb_engine.reflections[c].damp1 = (val & 0xFF) / 255.0; emu8k->reverb_engine.reflections[c].damp2 = (0xFF - (val & 0xFF)) / 255.0; emu8k->reverb_engine.reflections[c].filterstore = 0; } emu8k->reverb_engine.damper.damp1 = (val & 0xFF) / 255.0; emu8k->reverb_engine.damper.damp2 = (0xFF - (val & 0xFF)) / 255.0; emu8k->reverb_engine.damper.filterstore = 0; } break; case 0x1f: /* filter r */ break; case 0x1: emu8k->reverb_engine.reflections[3].feedback = (val & 0xF) / 15.0; break; case 0x3: #if 0 emu8k->reverb_engine.reflections[3].feedback_r = (val&0xF)/15.0; #endif break; case 0x9: emu8k->reverb_engine.reflections[4].feedback = (val & 0xF) / 15.0; break; case 0xb: #if 0 emu8k->reverb_engine.reflections[4].feedback_r = (val&0xF)/15.0; #endif break; case 0x11: emu8k->reverb_engine.reflections[5].feedback = (val & 0xF) / 15.0; break; case 0x13: #if 0 emu8k->reverb_engine.reflections[5].feedback_r = (val&0xF)/15.0; #endif break; default: break; } } return; case 3: emu8k->init4[emu8k->cur_voice] = val; /* Skip if in first/second initialization step */ if (emu8k->init1[0] != 0x03FF) { switch (emu8k->cur_voice) { case 0x3: { int32_t samples = ((val & 0xFF) * emu8k->chorus_engine.delay_samples_central) >> 8; emu8k->chorus_engine.lfodepth_multip = samples; } break; case 0x1F: emu8k->reverb_engine.link_return_amp = val & 0xFF; break; default: break; } } return; case 4: { emu8k->voice[emu8k->cur_voice].atkhldv = val; emu8k_envelope_t *const vol_env = &emu8k->voice[emu8k->cur_voice].vol_envelope; vol_env->attack_samples = env_attack_to_samples[ATKHLDV_ATTACK(val)]; if (vol_env->attack_samples == 0) { vol_env->attack_amount_amp_hz = 0; } else { /* Linear amplitude increase each sample. */ vol_env->attack_amount_amp_hz = (1 << 21) / vol_env->attack_samples; } vol_env->hold_samples = ATKHLDV_HOLD_TO_EMU_SAMPLES(val); if (ATKHLDV_TRIGGER(val) && emu8k->voice[emu8k->cur_voice].env_engine_on) { /*TODO: I assume that "envelope trigger" is the same as new note * (since changing the IP can be done when modulating pitch too) */ emu8k->voice[emu8k->cur_voice].lfo1_count.addr = 0; emu8k->voice[emu8k->cur_voice].lfo2_count.addr = 0; vol_env->value_amp_hz = 0; if (vol_env->delay_samples) { vol_env->state = ENV_DELAY; } else if (vol_env->attack_amount_amp_hz == 0) { vol_env->state = ENV_STOPPED; } else { vol_env->state = ENV_ATTACK; /* TODO: Verify if "never attack" means eternal mute, * or it means skip attack, go to hold". if (vol_env->attack_amount == 0) { vol_env->value = (1 << 21); vol_env->state = ENV_HOLD; }*/ } } } return; case 5: emu8k->voice[emu8k->cur_voice].lfo1val = val; /* TODO: verify if this is set once, or set every time. */ emu8k->voice[emu8k->cur_voice].lfo1_delay_samples = LFOxVAL_TO_EMU_SAMPLES(val); return; case 6: { emu8k->voice[emu8k->cur_voice].atkhld = val; emu8k_envelope_t *const mod_env = &emu8k->voice[emu8k->cur_voice].mod_envelope; mod_env->attack_samples = env_attack_to_samples[ATKHLD_ATTACK(val)]; if (mod_env->attack_samples == 0) { mod_env->attack_amount_amp_hz = 0; } else { /* Linear amplitude increase each sample. */ mod_env->attack_amount_amp_hz = (1 << 21) / mod_env->attack_samples; } mod_env->hold_samples = ATKHLD_HOLD_TO_EMU_SAMPLES(val); if (ATKHLD_TRIGGER(val) && emu8k->voice[emu8k->cur_voice].env_engine_on) { mod_env->value_amp_hz = 0; mod_env->value_db_oct = 0; if (mod_env->delay_samples) { mod_env->state = ENV_DELAY; } else if (mod_env->attack_amount_amp_hz == 0) { mod_env->state = ENV_STOPPED; } else { mod_env->state = ENV_ATTACK; /* TODO: Verify if "never attack" means eternal start, * or it means skip attack, go to hold". if (mod_env->attack_amount == 0) { mod_env->value = (1 << 21); mod_env->state = ENV_HOLD; }*/ } } } return; case 7: emu8k->voice[emu8k->cur_voice].lfo2val = val; emu8k->voice[emu8k->cur_voice].lfo2_delay_samples = LFOxVAL_TO_EMU_SAMPLES(val); return; default: break; } break; case 0xE00: /*Data3. also known as BLASTER+0xC00 and EMU+0x800 */ switch (emu8k->cur_reg) { case 0: emu8k->voice[emu8k->cur_voice].ip = val; emu8k->voice[emu8k->cur_voice].ptrx_pit_target = freqtable[val] >> 18; return; case 1: { emu8k_voice_t *const the_voice = &emu8k->voice[emu8k->cur_voice]; if ((val & 0xFF) == 0 && the_voice->cvcf_curr_volume == 0 && the_voice->vtft_vol_target == 0 && the_voice->dcysusv == 0x80 && the_voice->ip == 0) { // Patch to avoid some clicking noises with Impulse tracker or other software that sets // different values to 0 to set noteoff, but here, 0 means no attenuation = full volume. return; } the_voice->ifatn = val; the_voice->initial_att = (((int32_t) the_voice->ifatn_attenuation << 21) / 0xFF); the_voice->vtft_vol_target = attentable[the_voice->ifatn_attenuation]; the_voice->initial_filter = (((int32_t) the_voice->ifatn_init_filter << 21) / 0xFF); if (the_voice->ifatn_init_filter == 0xFF) { the_voice->vtft_filter_target = 0xFFFF; } else { the_voice->vtft_filter_target = the_voice->initial_filter >> 5; } } return; case 2: { emu8k_voice_t *const the_voice = &emu8k->voice[emu8k->cur_voice]; the_voice->pefe = val; int divider = (the_voice->pefe_modenv_filter_height < 0) ? 0x80 : 0x7F; the_voice->fixed_modenv_filter_height = ((int32_t) the_voice->pefe_modenv_filter_height) * 0x4000 / divider; divider = (the_voice->pefe_modenv_pitch_height < 0) ? 0x80 : 0x7F; the_voice->fixed_modenv_pitch_height = ((int32_t) the_voice->pefe_modenv_pitch_height) * 0x4000 / divider; } return; case 3: { emu8k_voice_t *const the_voice = &emu8k->voice[emu8k->cur_voice]; the_voice->fmmod = val; int divider = (the_voice->fmmod_lfo1_filt_mod < 0) ? 0x80 : 0x7F; the_voice->fixed_lfo1_filt_mod = ((int32_t) the_voice->fmmod_lfo1_filt_mod) * 0x4000 / divider; divider = (the_voice->fmmod_lfo1_vibrato < 0) ? 0x80 : 0x7F; the_voice->fixed_lfo1_vibrato = ((int32_t) the_voice->fmmod_lfo1_vibrato) * 0x4000 / divider; } return; case 4: { emu8k_voice_t *const the_voice = &emu8k->voice[emu8k->cur_voice]; the_voice->tremfrq = val; the_voice->lfo1_speed = lfofreqtospeed[the_voice->tremfrq_lfo1_freq]; int divider = (the_voice->tremfrq_lfo1_tremolo < 0) ? 0x80 : 0x7F; the_voice->fixed_lfo1_tremolo = ((int32_t) the_voice->tremfrq_lfo1_tremolo) * 0x4000 / divider; } return; case 5: { emu8k_voice_t *const the_voice = &emu8k->voice[emu8k->cur_voice]; the_voice->fm2frq2 = val; the_voice->lfo2_speed = lfofreqtospeed[the_voice->fm2frq2_lfo2_freq]; int divider = (the_voice->fm2frq2_lfo2_vibrato < 0) ? 0x80 : 0x7F; the_voice->fixed_lfo2_vibrato = ((int32_t) the_voice->fm2frq2_lfo2_vibrato) * 0x4000 / divider; } return; case 7: /*ID? I believe that this allows applications to know if the emu is in use by another application */ emu8k->id = val; return; default: break; } break; case 0xE02: /* Pointer. also known as BLASTER+0xC02 and EMU+0x802 */ emu8k->cur_voice = (val & 31); emu8k->cur_reg = ((val >> 5) & 7); return; default: break; } emu8k_log("EMU8K WRITE: Unknown register write: %04X-%02X(%d/%d): %04X \n", addr, (emu8k->cur_reg) << 5 | emu8k->cur_voice, emu8k->cur_reg, emu8k->cur_voice, val); } uint8_t emu8k_inb(uint16_t addr, void *priv) { /* Reading a single byte is a feature that at least Impulse tracker uses, * but only on detection code and not for odd addresses.*/ if (addr & 1) return emu8k_inw(addr & ~1, priv) >> 1; return emu8k_inw(addr, priv) & 0xff; } void emu8k_outb(uint16_t addr, uint8_t val, void *priv) { /* TODO: AWE32 docs says that you cannot write in bytes, but if * an app were to use this implementation, the content of the LS Byte would be lost.*/ if (addr & 1) emu8k_outw(addr & ~1, val << 8, priv); else emu8k_outw(addr, val, priv); } /* TODO: This is not a correct emulation, just a workalike implementation. */ void emu8k_work_chorus(int32_t *inbuf, int32_t *outbuf, emu8k_chorus_eng_t *engine, int count) { for (int pos = 0; pos < count; pos++) { double lfo_inter1 = chortable[engine->lfo_pos.int_address]; #if 0 double lfo_inter2 = chortable[(engine->lfo_pos.int_address+1)&0xFFFF]; #endif double offset_lfo = lfo_inter1; //= lfo_inter1 + ((lfo_inter2-lfo_inter1)*engine->lfo_pos.fract_address/65536.0); offset_lfo *= engine->lfodepth_multip; /* Work left */ double readdouble = (double) engine->write - (double) engine->delay_samples_central - offset_lfo; int read = (int32_t) floor(readdouble); int fraction_part = (readdouble - (double) read) * 65536.0; int next_value = read + 1; if (read < 0) { read += EMU8K_LFOCHORUS_SIZE; if (next_value < 0) next_value += EMU8K_LFOCHORUS_SIZE; } else if (next_value >= EMU8K_LFOCHORUS_SIZE) { next_value -= EMU8K_LFOCHORUS_SIZE; if (read >= EMU8K_LFOCHORUS_SIZE) read -= EMU8K_LFOCHORUS_SIZE; } int32_t dat1 = engine->chorus_left_buffer[read]; int32_t dat2 = engine->chorus_left_buffer[next_value]; dat1 += ((dat2 - dat1) * fraction_part) >> 16; engine->chorus_left_buffer[engine->write] = *inbuf + ((dat1 * engine->feedback) >> 8); /* Work right */ readdouble = (double) engine->write - (double) engine->delay_samples_central - engine->delay_offset_samples_right - offset_lfo; read = (int32_t) floor(readdouble); next_value = read + 1; if (read < 0) { read += EMU8K_LFOCHORUS_SIZE; if (next_value < 0) next_value += EMU8K_LFOCHORUS_SIZE; } else if (next_value >= EMU8K_LFOCHORUS_SIZE) { next_value -= EMU8K_LFOCHORUS_SIZE; if (read >= EMU8K_LFOCHORUS_SIZE) read -= EMU8K_LFOCHORUS_SIZE; } int32_t dat3 = engine->chorus_right_buffer[read]; int32_t dat4 = engine->chorus_right_buffer[next_value]; dat3 += ((dat4 - dat3) * fraction_part) >> 16; engine->chorus_right_buffer[engine->write] = *inbuf + ((dat3 * engine->feedback) >> 8); ++engine->write; engine->write %= EMU8K_LFOCHORUS_SIZE; engine->lfo_pos.addr += engine->lfo_inc.addr; engine->lfo_pos.int_address &= 0xFFFF; (*outbuf++) += dat1; (*outbuf++) += dat3; inbuf++; } } int32_t emu8k_reverb_comb_work(emu8k_reverb_combfilter_t *comb, int32_t in) { int32_t bufin; /* get echo */ int32_t output = comb->reflection[comb->read_pos]; /* apply lowpass */ comb->filterstore = (output * comb->damp2) + (comb->filterstore * comb->damp1); /* appply feedback */ bufin = in - (comb->filterstore * comb->feedback); /* store new value in delayed buffer */ comb->reflection[comb->read_pos] = bufin; if (++comb->read_pos >= comb->bufsize) comb->read_pos = 0; return output * comb->output_gain; } int32_t emu8k_reverb_diffuser_work(emu8k_reverb_combfilter_t *comb, int32_t in) { int32_t bufout = comb->reflection[comb->read_pos]; /*diffuse*/ int32_t bufin = -in + (bufout * comb->feedback); int32_t output = bufout - (bufin * comb->feedback); /* store new value in delayed buffer */ comb->reflection[comb->read_pos] = bufin; if (++comb->read_pos >= comb->bufsize) comb->read_pos = 0; return output; } int32_t emu8k_reverb_tail_work(emu8k_reverb_combfilter_t *comb, emu8k_reverb_combfilter_t *allpasses, int32_t in) { int32_t output = comb->reflection[comb->read_pos]; /* store new value in delayed buffer */ comb->reflection[comb->read_pos] = in; #if 0 output = emu8k_reverb_allpass_work(&allpasses[0],output); #endif output = emu8k_reverb_diffuser_work(&allpasses[1], output); output = emu8k_reverb_diffuser_work(&allpasses[2], output); #if 0 output = emu8k_reverb_allpass_work(&allpasses[3],output); #endif if (++comb->read_pos >= comb->bufsize) comb->read_pos = 0; return output; } int32_t emu8k_reverb_damper_work(emu8k_reverb_combfilter_t *comb, int32_t in) { /* apply lowpass */ comb->filterstore = (in * comb->damp2) + (comb->filterstore * comb->damp1); return comb->filterstore; } /* TODO: This is not a correct emulation, just a workalike implementation. */ void emu8k_work_reverb(int32_t *inbuf, int32_t *outbuf, emu8k_reverb_eng_t *engine, int count) { int pos; if (engine->link_return_type) { for (pos = 0; pos < count; pos++) { int32_t dat1; int32_t dat2; int32_t in; int32_t in2; in = emu8k_reverb_damper_work(&engine->damper, inbuf[pos]); in2 = (in * engine->refl_in_amp) >> 8; dat2 = emu8k_reverb_comb_work(&engine->reflections[0], in2); dat2 += emu8k_reverb_comb_work(&engine->reflections[1], in2); dat1 = emu8k_reverb_comb_work(&engine->reflections[2], in2); dat2 += emu8k_reverb_comb_work(&engine->reflections[3], in2); dat1 += emu8k_reverb_comb_work(&engine->reflections[4], in2); dat2 += emu8k_reverb_comb_work(&engine->reflections[5], in2); dat1 += (emu8k_reverb_tail_work(&engine->tailL, &engine->allpass[0], in + dat1) * engine->link_return_amp) >> 8; dat2 += (emu8k_reverb_tail_work(&engine->tailR, &engine->allpass[4], in + dat2) * engine->link_return_amp) >> 8; (*outbuf++) += (dat1 * engine->out_mix) >> 8; (*outbuf++) += (dat2 * engine->out_mix) >> 8; } } else { for (pos = 0; pos < count; pos++) { int32_t dat1; int32_t dat2; int32_t in; int32_t in2; in = emu8k_reverb_damper_work(&engine->damper, inbuf[pos]); in2 = (in * engine->refl_in_amp) >> 8; dat1 = emu8k_reverb_comb_work(&engine->reflections[0], in2); dat1 += emu8k_reverb_comb_work(&engine->reflections[1], in2); dat1 += emu8k_reverb_comb_work(&engine->reflections[2], in2); dat1 += emu8k_reverb_comb_work(&engine->reflections[3], in2); dat1 += emu8k_reverb_comb_work(&engine->reflections[4], in2); dat1 += emu8k_reverb_comb_work(&engine->reflections[5], in2); dat2 = dat1; dat1 += (emu8k_reverb_tail_work(&engine->tailL, &engine->allpass[0], in + dat1) * engine->link_return_amp) >> 8; dat2 += (emu8k_reverb_tail_work(&engine->tailR, &engine->allpass[4], in + dat2) * engine->link_return_amp) >> 8; (*outbuf++) += (dat1 * engine->out_mix) >> 8; (*outbuf++) += (dat2 * engine->out_mix) >> 8; } } } void emu8k_work_eq(UNUSED(int32_t *inoutbuf), UNUSED(int count)) { // TODO: Work EQ over buf } int32_t emu8k_vol_slide(emu8k_slide_t *slide, int32_t target) { if (slide->last < target) { slide->last += 0x400; if (slide->last > target) slide->last = target; } else if (slide->last > target) { slide->last -= 0x400; if (slide->last < target) slide->last = target; } return slide->last; } #if 0 int32_t old_pitch[32] = { 0 }; int32_t old_cut[32] = { 0 }; int32_t old_vol[32] = { 0 }; #endif void emu8k_update(emu8k_t *emu8k) { if (emu8k->pos >= wavetable_pos_global) return; int32_t *buf; emu8k_voice_t *emu_voice; int pos; /* Clean the buffers since we will accumulate into them. */ buf = &emu8k->buffer[emu8k->pos * 2]; memset(buf, 0, 2 * (wavetable_pos_global - emu8k->pos) * sizeof(emu8k->buffer[0])); memset(&emu8k->chorus_in_buffer[emu8k->pos], 0, (wavetable_pos_global - emu8k->pos) * sizeof(emu8k->chorus_in_buffer[0])); memset(&emu8k->reverb_in_buffer[emu8k->pos], 0, (wavetable_pos_global - emu8k->pos) * sizeof(emu8k->reverb_in_buffer[0])); /* Voices section */ for (uint8_t c = 0; c < 32; c++) { emu_voice = &emu8k->voice[c]; buf = &emu8k->buffer[emu8k->pos * 2]; for (pos = emu8k->pos; pos < wavetable_pos_global; pos++) { int32_t dat; if (emu_voice->cvcf_curr_volume) { /* Waveform oscillator */ #ifdef RESAMPLER_LINEAR dat = EMU8K_READ_INTERP_LINEAR(emu8k, emu_voice->addr.int_address, emu_voice->addr.fract_address); #elif defined RESAMPLER_CUBIC dat = EMU8K_READ_INTERP_CUBIC(emu8k, emu_voice->addr.int_address, emu_voice->addr.fract_address); #endif /* Filter section */ if (emu_voice->filterq_idx || emu_voice->cvcf_curr_filt_ctoff != 0xFFFF) { int cutoff = emu_voice->cvcf_curr_filt_ctoff >> 8; const int64_t coef0 = filt_coeffs[emu_voice->filterq_idx][cutoff][0]; const int64_t coef1 = filt_coeffs[emu_voice->filterq_idx][cutoff][1]; const int64_t coef2 = filt_coeffs[emu_voice->filterq_idx][cutoff][2]; /* clip at twice the range */ #define ClipBuffer(buf) (buf < -16777216) ? -16777216 : (buf > 16777216) ? 16777216 \ : buf #ifdef FILTER_INITIAL # define NOOP(x) (void) x; NOOP(coef1) /* Apply expected attenuation. (FILTER_MOOG does it implicitly, but this one doesn't). * Work in 24bits. */ dat = (dat * emu_voice->filt_att) >> 8; int64_t vhp = ((-emu_voice->filt_buffer[0] * coef2) >> 24) - emu_voice->filt_buffer[1] - dat; emu_voice->filt_buffer[1] += (emu_voice->filt_buffer[0] * coef0) >> 24; emu_voice->filt_buffer[0] += (vhp * coef0) >> 24; dat = (int32_t) (emu_voice->filt_buffer[1] >> 8); if (dat > 32767) { dat = 32767; } else if (dat < -32768) { dat = -32768; } #elif defined FILTER_MOOG /*move to 24bits*/ dat <<= 8; dat -= (coef2 * emu_voice->filt_buffer[4]) >> 24; /*feedback*/ int64_t t1 = emu_voice->filt_buffer[1]; emu_voice->filt_buffer[1] = ((dat + emu_voice->filt_buffer[0]) * coef0 - emu_voice->filt_buffer[1] * coef1) >> 24; emu_voice->filt_buffer[1] = ClipBuffer(emu_voice->filt_buffer[1]); int64_t t2 = emu_voice->filt_buffer[2]; emu_voice->filt_buffer[2] = ((emu_voice->filt_buffer[1] + t1) * coef0 - emu_voice->filt_buffer[2] * coef1) >> 24; emu_voice->filt_buffer[2] = ClipBuffer(emu_voice->filt_buffer[2]); int64_t t3 = emu_voice->filt_buffer[3]; emu_voice->filt_buffer[3] = ((emu_voice->filt_buffer[2] + t2) * coef0 - emu_voice->filt_buffer[3] * coef1) >> 24; emu_voice->filt_buffer[3] = ClipBuffer(emu_voice->filt_buffer[3]); emu_voice->filt_buffer[4] = ((emu_voice->filt_buffer[3] + t3) * coef0 - emu_voice->filt_buffer[4] * coef1) >> 24; emu_voice->filt_buffer[4] = ClipBuffer(emu_voice->filt_buffer[4]); emu_voice->filt_buffer[0] = ClipBuffer(dat); dat = (int32_t) (emu_voice->filt_buffer[4] >> 8); if (dat > 32767) { dat = 32767; } else if (dat < -32768) { dat = -32768; } #elif defined FILTER_CONSTANT /* Apply expected attenuation. (FILTER_MOOG does it implicitly, but this one is constant gain). * Also stay at 24bits.*/ dat = (dat * emu_voice->filt_att) >> 8; emu_voice->filt_buffer[0] = (coef1 * emu_voice->filt_buffer[0] + coef0 * (dat + ((coef2 * (emu_voice->filt_buffer[0] - emu_voice->filt_buffer[1])) >> 24))) >> 24; emu_voice->filt_buffer[1] = (coef1 * emu_voice->filt_buffer[1] + coef0 * emu_voice->filt_buffer[0]) >> 24; emu_voice->filt_buffer[0] = ClipBuffer(emu_voice->filt_buffer[0]); emu_voice->filt_buffer[1] = ClipBuffer(emu_voice->filt_buffer[1]); dat = (int32_t) (emu_voice->filt_buffer[1] >> 8); if (dat > 32767) { dat = 32767; } else if (dat < -32768) { dat = -32768; } #endif } if ((emu8k->hwcf3 & 0x04) && !CCCA_DMA_ACTIVE(emu_voice->ccca)) { /*volume and pan*/ dat = (dat * emu_voice->cvcf_curr_volume) >> 16; (*buf++) += (dat * emu_voice->vol_l) >> 8; (*buf++) += (dat * emu_voice->vol_r) >> 8; /* Effects section */ if (emu_voice->ptrx_revb_send > 0) { emu8k->reverb_in_buffer[pos] += (dat * emu_voice->ptrx_revb_send) >> 8; } if (emu_voice->csl_chor_send > 0) { emu8k->chorus_in_buffer[pos] += (dat * emu_voice->csl_chor_send) >> 8; } } } if (emu_voice->env_engine_on) { int32_t attenuation = emu_voice->initial_att; int32_t filtercut = emu_voice->initial_filter; int32_t currentpitch = emu_voice->ip; /* run envelopes */ emu8k_envelope_t *volenv = &emu_voice->vol_envelope; switch (volenv->state) { case ENV_DELAY: volenv->delay_samples--; if (volenv->delay_samples <= 0) { volenv->state = ENV_ATTACK; volenv->delay_samples = 0; } attenuation = 0x1FFFFF; break; case ENV_ATTACK: /* Attack amount is in linear amplitude */ volenv->value_amp_hz += volenv->attack_amount_amp_hz; if (volenv->value_amp_hz >= (1 << 21)) { volenv->value_amp_hz = 1 << 21; volenv->value_db_oct = 0; if (volenv->hold_samples) { volenv->state = ENV_HOLD; } else { /* RAMP_UP since db value is inverted and it is 0 at this point. */ volenv->state = ENV_RAMP_UP; } } attenuation += env_vol_amplitude_to_db[volenv->value_amp_hz >> 5] << 5; break; case ENV_HOLD: volenv->hold_samples--; if (volenv->hold_samples <= 0) { volenv->state = ENV_RAMP_UP; } attenuation += volenv->value_db_oct; break; case ENV_RAMP_DOWN: /* Decay/release amount is in fraction of dBs and is always positive */ volenv->value_db_oct -= volenv->ramp_amount_db_oct; if (volenv->value_db_oct <= volenv->sustain_value_db_oct) { volenv->value_db_oct = volenv->sustain_value_db_oct; volenv->state = ENV_SUSTAIN; } attenuation += volenv->value_db_oct; break; case ENV_RAMP_UP: /* Decay/release amount is in fraction of dBs and is always positive */ volenv->value_db_oct += volenv->ramp_amount_db_oct; if (volenv->value_db_oct >= volenv->sustain_value_db_oct) { volenv->value_db_oct = volenv->sustain_value_db_oct; volenv->state = ENV_SUSTAIN; } attenuation += volenv->value_db_oct; break; case ENV_SUSTAIN: attenuation += volenv->value_db_oct; break; case ENV_STOPPED: attenuation = 0x1FFFFF; break; default: break; } emu8k_envelope_t *modenv = &emu_voice->mod_envelope; switch (modenv->state) { case ENV_DELAY: modenv->delay_samples--; if (modenv->delay_samples <= 0) { modenv->state = ENV_ATTACK; modenv->delay_samples = 0; } break; case ENV_ATTACK: /* Attack amount is in linear amplitude */ modenv->value_amp_hz += modenv->attack_amount_amp_hz; modenv->value_db_oct = env_mod_hertz_to_octave[modenv->value_amp_hz >> 5] << 5; if (modenv->value_amp_hz >= (1 << 21)) { modenv->value_amp_hz = 1 << 21; modenv->value_db_oct = 1 << 21; if (modenv->hold_samples) { modenv->state = ENV_HOLD; } else { modenv->state = ENV_RAMP_DOWN; } } break; case ENV_HOLD: modenv->hold_samples--; if (modenv->hold_samples <= 0) { modenv->state = ENV_RAMP_UP; } break; case ENV_RAMP_DOWN: /* Decay/release amount is in fraction of octave and is always positive */ modenv->value_db_oct -= modenv->ramp_amount_db_oct; if (modenv->value_db_oct <= modenv->sustain_value_db_oct) { modenv->value_db_oct = modenv->sustain_value_db_oct; modenv->state = ENV_SUSTAIN; } break; case ENV_RAMP_UP: /* Decay/release amount is in fraction of octave and is always positive */ modenv->value_db_oct += modenv->ramp_amount_db_oct; if (modenv->value_db_oct >= modenv->sustain_value_db_oct) { modenv->value_db_oct = modenv->sustain_value_db_oct; modenv->state = ENV_SUSTAIN; } break; default: break; } /* run lfos */ if (emu_voice->lfo1_delay_samples) { emu_voice->lfo1_delay_samples--; } else { emu_voice->lfo1_count.addr += emu_voice->lfo1_speed; emu_voice->lfo1_count.int_address &= 0xFFFF; } if (emu_voice->lfo2_delay_samples) { emu_voice->lfo2_delay_samples--; } else { emu_voice->lfo2_count.addr += emu_voice->lfo2_speed; emu_voice->lfo2_count.int_address &= 0xFFFF; } if (emu_voice->fixed_modenv_pitch_height) { /* modenv range 1<<21, pitch height range 1<<14 desired range 0x1000 (+/-one octave) */ currentpitch += ((modenv->value_db_oct >> 9) * emu_voice->fixed_modenv_pitch_height) >> 14; } if (emu_voice->fixed_lfo1_vibrato) { /* table range 1<<15, pitch mod range 1<<14 desired range 0x1000 (+/-one octave) */ int32_t lfo1_vibrato = (lfotable[emu_voice->lfo1_count.int_address] * emu_voice->fixed_lfo1_vibrato) >> 17; currentpitch += lfo1_vibrato; } if (emu_voice->fixed_lfo2_vibrato) { /* table range 1<<15, pitch mod range 1<<14 desired range 0x1000 (+/-one octave) */ int32_t lfo2_vibrato = (lfotable[emu_voice->lfo2_count.int_address] * emu_voice->fixed_lfo2_vibrato) >> 17; currentpitch += lfo2_vibrato; } if (emu_voice->fixed_modenv_filter_height) { /* modenv range 1<<21, pitch height range 1<<14 desired range 0x200000 (+/-full filter range) */ filtercut += ((modenv->value_db_oct >> 9) * emu_voice->fixed_modenv_filter_height) >> 5; } if (emu_voice->fixed_lfo1_filt_mod) { /* table range 1<<15, pitch mod range 1<<14 desired range 0x100000 (+/-three octaves) */ int32_t lfo1_filtmod = (lfotable[emu_voice->lfo1_count.int_address] * emu_voice->fixed_lfo1_filt_mod) >> 9; filtercut += lfo1_filtmod; } if (emu_voice->fixed_lfo1_tremolo) { /* table range 1<<15, pitch mod range 1<<14 desired range 0x40000 (+/-12dBs). */ int32_t lfo1_tremolo = (lfotable[emu_voice->lfo1_count.int_address] * emu_voice->fixed_lfo1_tremolo) >> 11; attenuation += lfo1_tremolo; } if (currentpitch > 0xFFFF) currentpitch = 0xFFFF; if (currentpitch < 0) currentpitch = 0; if (attenuation > 0x1FFFFF) attenuation = 0x1FFFFF; if (attenuation < 0) attenuation = 0; if (filtercut > 0x1FFFFF) filtercut = 0x1FFFFF; if (filtercut < 0) filtercut = 0; emu_voice->vtft_vol_target = env_vol_db_to_vol_target[attenuation >> 5]; emu_voice->vtft_filter_target = filtercut >> 5; emu_voice->ptrx_pit_target = freqtable[currentpitch] >> 18; } /* I've recopilated these sentences to get an idea of how to loop - Set its PSST register and its CLS register to zero to cause no loops to occur. -Setting the Loop Start Offset and the Loop End Offset to the same value, will cause the oscillator to loop the entire memory. -Setting the PlayPosition greater than the Loop End Offset, will cause the oscillator to play in reverse, back to the Loop End Offset. It's pretty neat, but appears to be uncontrollable (the rate at which the samples are played in reverse). -Note that due to interpolator offset, the actual loop point is one greater than the start address -Note that due to interpolator offset, the actual loop point will end at an address one greater than the loop address -Note that the actual audio location is the point 1 word higher than this value due to interpolation offset -In programs that use the awe, they generally set the loop address as "loopaddress -1" to compensate for the above. (Note: I am already using address+1 in the interpolators so these things are already as they should.) */ emu_voice->addr.addr += ((uint64_t) emu_voice->cpf_curr_pitch) << 18; if (emu_voice->addr.addr >= emu_voice->loop_end.addr) { emu_voice->addr.int_address -= (emu_voice->loop_end.int_address - emu_voice->loop_start.int_address); emu_voice->addr.int_address &= EMU8K_MEM_ADDRESS_MASK; } /* TODO: How and when are the target and current values updated */ emu_voice->cpf_curr_pitch = emu_voice->ptrx_pit_target; emu_voice->cvcf_curr_volume = emu8k_vol_slide(&emu_voice->volumeslide, emu_voice->vtft_vol_target); emu_voice->cvcf_curr_filt_ctoff = emu_voice->vtft_filter_target; } /* Update EMU voice registers. */ emu_voice->ccca = (((uint32_t) emu_voice->ccca_qcontrol) << 24) | emu_voice->addr.int_address; emu_voice->cpf_curr_frac_addr = emu_voice->addr.fract_address; #if 0 if (emu_voice->cvcf_curr_volume != old_vol[c]) { pclog("EMUVOL (%d):%d\n", c, emu_voice->cvcf_curr_volume); old_vol[c]=emu_voice->cvcf_curr_volume; } pclog("EMUFILT :%d\n", emu_voice->cvcf_curr_filt_ctoff); #endif } buf = &emu8k->buffer[emu8k->pos * 2]; emu8k_work_reverb(&emu8k->reverb_in_buffer[emu8k->pos], buf, &emu8k->reverb_engine, wavetable_pos_global - emu8k->pos); emu8k_work_chorus(&emu8k->chorus_in_buffer[emu8k->pos], buf, &emu8k->chorus_engine, wavetable_pos_global - emu8k->pos); emu8k_work_eq(buf, wavetable_pos_global - emu8k->pos); /* Update EMU clock. */ emu8k->wc += (wavetable_pos_global - emu8k->pos); emu8k->pos = wavetable_pos_global; } void emu8k_change_addr(emu8k_t *emu8k, uint16_t emu_addr) { if (emu8k->addr) { io_removehandler(emu8k->addr, 0x0004, emu8k_inb, emu8k_inw, NULL, emu8k_outb, emu8k_outw, NULL, emu8k); io_removehandler(emu8k->addr + 0x400, 0x0004, emu8k_inb, emu8k_inw, NULL, emu8k_outb, emu8k_outw, NULL, emu8k); io_removehandler(emu8k->addr + 0x800, 0x0004, emu8k_inb, emu8k_inw, NULL, emu8k_outb, emu8k_outw, NULL, emu8k); emu8k->addr = 0; } if (emu_addr) { emu8k->addr = emu_addr; io_sethandler(emu8k->addr, 0x0004, emu8k_inb, emu8k_inw, NULL, emu8k_outb, emu8k_outw, NULL, emu8k); io_sethandler(emu8k->addr + 0x400, 0x0004, emu8k_inb, emu8k_inw, NULL, emu8k_outb, emu8k_outw, NULL, emu8k); io_sethandler(emu8k->addr + 0x800, 0x0004, emu8k_inb, emu8k_inw, NULL, emu8k_outb, emu8k_outw, NULL, emu8k); } } /* onboard_ram in kilobytes */ void emu8k_init(emu8k_t *emu8k, uint16_t emu_addr, int onboard_ram) { uint32_t const BLOCK_SIZE_WORDS = 0x10000; FILE *fp; int c; double out; fp = rom_fopen(EMU8K_ROM_PATH, "rb"); if (!fp) fatal("AWE32.RAW not found\n"); emu8k->rom = malloc(1024 * 1024); if (fread(emu8k->rom, 1, 1048576, fp) != 1048576) fatal("emu8k_init(): Error reading data\n"); fclose(fp); /*AWE-DUMP creates ROM images offset by 2 bytes, so if we detect this then correct it*/ if (emu8k->rom[3] == 0x314d && emu8k->rom[4] == 0x474d) { memmove(&emu8k->rom[0], &emu8k->rom[1], (1024 * 1024) - 2); emu8k->rom[0x7ffff] = 0; } emu8k->empty = malloc(2 * BLOCK_SIZE_WORDS); memset(emu8k->empty, 0, 2 * BLOCK_SIZE_WORDS); int j = 0; for (; j < 0x8; j++) { emu8k->ram_pointers[j] = emu8k->rom + (j * BLOCK_SIZE_WORDS); } for (; j < 0x20; j++) { emu8k->ram_pointers[j] = emu8k->empty; } if (onboard_ram) { /*Clip to 28MB, since that's the max that we can address. */ if (onboard_ram > 0x7000) onboard_ram = 0x7000; emu8k->ram = malloc(onboard_ram * 1024); memset(emu8k->ram, 0, onboard_ram * 1024); const int i_end = onboard_ram >> 7; int i = 0; for (; i < i_end; i++, j++) { emu8k->ram_pointers[j] = emu8k->ram + (i * BLOCK_SIZE_WORDS); } emu8k->ram_end_addr = EMU8K_RAM_MEM_START + (onboard_ram << 9); } else { emu8k->ram = 0; emu8k->ram_end_addr = EMU8K_RAM_MEM_START; } for (; j < 0x100; j++) { emu8k->ram_pointers[j] = emu8k->empty; } emu8k_change_addr(emu8k, emu_addr); /*Create frequency table. (Convert initial pitch register value to a linear speed change) * The input is encoded such as 0xe000 is center note (no pitch shift) * and from then on , changing up or down 0x1000 (4096) increments/decrements an octave. * Note that this is in reference to the 44.1Khz clock that the channels play at. * The 65536 * 65536 is in order to left-shift the 32bit value to a 64bit value as a 32.32 fixed point. */ for (c = 0; c < 0x10000; c++) { freqtable[c] = (uint64_t) (exp2((double) (c - 0xe000) / 4096.0) * 65536.0 * 65536.0); } /* Shortcut: minimum pitch equals stopped. I don't really know if this is true, but it's better * since some programs set the pitch to 0 for unused channels. */ freqtable[0] = 0; /* starting at 65535 because it is used for "volume target" register conversion. */ out = 65535.0; for (c = 0; c < 256; c++) { attentable[c] = (int32_t) out; out /= sqrt(1.09018); /*0.375 dB steps*/ } /* Shortcut: max attenuation is silent, not -96dB. */ attentable[255] = 0; /* Note: these two tables have "db" inverted: 0 dB is max volume, 65535 "db" (-96.32dBFS) is silence. * Important: Using 65535 as max output value because this is intended to be used with the volume target register! */ out = 65535.0; for (c = 0; c < 0x10000; c++) { #if 0 double db = -(c*6.0205999/65535.0)*16.0; out = powf(10.f,db/20.f) * 65536.0; #endif env_vol_db_to_vol_target[c] = (int32_t) out; /* calculated from the 65536th root of 65536 */ out /= 1.00016923970; } /* Shortcut: max attenuation is silent, not -96dB. */ env_vol_db_to_vol_target[0x10000 - 1] = 0; /* One more position to accept max value being 65536. */ env_vol_db_to_vol_target[0x10000] = 0; for (c = 1; c < 0x10000; c++) { out = -680.32142884264 * 20.0 * log10(((double) c) / 65535.0); env_vol_amplitude_to_db[c] = (int32_t) out; } /*Shortcut: max attenuation is silent, not -96dB.*/ env_vol_amplitude_to_db[0] = 65535; /* One more position to accept max value being 65536. */ env_vol_amplitude_to_db[0x10000] = 0; for (c = 1; c < 0x10000; c++) { out = log2((((double) c) / 0x10000) + 1.0) * 65536.0; env_mod_hertz_to_octave[c] = (int32_t) out; } /*No hertz change, no octave change. */ env_mod_hertz_to_octave[0] = 0; /* One more position to accept max value being 65536. */ env_mod_hertz_to_octave[0x10000] = 65536; /* This formula comes from vince vu/judge dredd's awe32p10 and corresponds to what the freebsd/linux AWE32 driver has. */ float millis; for (c = 0; c < 128; c++) { if (c == 0) millis = 0; /* This means never attack. */ else if (c < 32) millis = 11878.0 / c; else millis = 360 * exp((c - 32) / (16.0 / log(1.0 / 2.0))); env_attack_to_samples[c] = 44.1 * millis; /* This is an alternate formula with linear increments, but probably incorrect: * millis = (256+4096*(0x7F-c)) */ } /* The LFOs use a triangular waveform starting at zero and going 1/-1/1/-1. * This table is stored in signed 16bits precision, with a period of 65536 samples */ for (c = 0; c < 65536; c++) { int d = (c + 16384) & 65535; if (d >= 32768) lfotable[c] = 32768 + ((32768 - d) * 2); else lfotable[c] = (d * 2) - 32768; } /* The 65536 * 65536 is in order to left-shift the 32bit value to a 64bit value as a 32.32 fixed point. */ out = 0.01; for (c = 0; c < 256; c++) { lfofreqtospeed[c] = (uint64_t) (out * 65536.0 / 44100.0 * 65536.0 * 65536.0); out += 0.042; } for (c = 0; c < 65536; c++) { chortable[c] = sin(c * M_PI / 32768.0); } /* Filter coefficients tables. Note: Values are multiplied by *16777216 to left shift 24 bits. (i.e. 8.24 fixed point) */ for (uint8_t qidx = 0; qidx < 16; qidx++) { out = 125.0; /* Start at 125Hz */ for (c = 0; c < 256; c++) { #ifdef FILTER_INITIAL float w0 = sin(2.0 * M_PI * out / 44100.0); /* The value 102.5f has been selected a bit randomly. Pretends to reach 0.2929 at w0 = 1.0 */ float q = (qidx / 102.5f) * (1.0 + 1.0 / w0); /* Limit max value. Else it would be 470. */ if (q > 200) q = 200; filt_coeffs[qidx][c][0] = (int32_t) (w0 * 16777216.0); filt_coeffs[qidx][c][1] = 16777216.0; filt_coeffs[qidx][c][2] = (int32_t) ((1.0f / (0.7071f + q)) * 16777216.0); #elif defined FILTER_MOOG float w0 = sin(2.0 * M_PI * out / 44100.0); float q_factor = 1.0f - w0; float p = w0 + 0.8f * w0 * q_factor; float f = p + p - 1.0f; float resonance = (1.0 - pow(2.0, -qidx * 24.0 / 90.0)) * 0.8; float q = resonance * (1.0f + 0.5f * q_factor * (w0 + 5.6f * q_factor * q_factor)); filt_coeffs[qidx][c][0] = (int32_t) (p * 16777216.0); filt_coeffs[qidx][c][1] = (int32_t) (f * 16777216.0); filt_coeffs[qidx][c][2] = (int32_t) (q * 16777216.0); #elif defined FILTER_CONSTANT float q = (1.0 - pow(2.0, -qidx * 24.0 / 90.0)) * 0.8; float coef0 = sin(2.0 * M_PI * out / 44100.0); float coef1 = 1.0 - coef0; float coef2 = q * (1.0 + 1.0 / coef1); filt_coeffs[qidx][c][0] = (int32_t) (coef0 * 16777216.0); filt_coeffs[qidx][c][1] = (int32_t) (coef1 * 16777216.0); filt_coeffs[qidx][c][2] = (int32_t) (coef2 * 16777216.0); #endif // FILTER_TYPE /* 42.66 divisions per octave (the doc says quarter seminotes which is 48, but then it would be almost an octave less) */ out *= 1.016378315; /* 42 divisions. This moves the max frequency to 8.5Khz.*/ // out *= 1.0166404394; /* This is a linear increment method, that corresponds to the NRPN table, but contradicts the EMU8KPRM doc: */ // out = 100.0 + (c+1.0)*31.25; //31.25Hz steps */ } } /* NOTE! read_pos and buffer content is implicitly initialized to zero by the sb_t structure memset on sb_awe32_init() */ emu8k->reverb_engine.reflections[0].bufsize = 2 * REV_BUFSIZE_STEP; emu8k->reverb_engine.reflections[1].bufsize = 4 * REV_BUFSIZE_STEP; emu8k->reverb_engine.reflections[2].bufsize = 8 * REV_BUFSIZE_STEP; emu8k->reverb_engine.reflections[3].bufsize = 13 * REV_BUFSIZE_STEP; emu8k->reverb_engine.reflections[4].bufsize = 19 * REV_BUFSIZE_STEP; emu8k->reverb_engine.reflections[5].bufsize = 26 * REV_BUFSIZE_STEP; /*This is a bit random.*/ for (c = 0; c < 4; c++) { emu8k->reverb_engine.allpass[3 - c].feedback = 0.5; emu8k->reverb_engine.allpass[3 - c].bufsize = (4 * c) * REV_BUFSIZE_STEP + 55; emu8k->reverb_engine.allpass[7 - c].feedback = 0.5; emu8k->reverb_engine.allpass[7 - c].bufsize = (4 * c) * REV_BUFSIZE_STEP + 55; } /* Cubic Resampling ( 4point cubic spline) */ double const resdouble = 1.0 / (double) CUBIC_RESOLUTION; for (c = 0; c < CUBIC_RESOLUTION; c++) { double x = (double) c * resdouble; /* Cubic resolution is made of four table, but I've put them all in one table to optimize memory access. */ cubic_table[c * 4] = (-0.5 * x * x * x + x * x - 0.5 * x); cubic_table[c * 4 + 1] = (1.5 * x * x * x - 2.5 * x * x + 1.0); cubic_table[c * 4 + 2] = (-1.5 * x * x * x + 2.0 * x * x + 0.5 * x); cubic_table[c * 4 + 3] = (0.5 * x * x * x - 0.5 * x * x); } /* Even when the documentation says that this has to be written by applications to initialize the card, * several applications and drivers ( aweman on windows, linux oss driver..) read it to detect an AWE card. */ emu8k->hwcf1 = 0x59; emu8k->hwcf2 = 0x20; /* Initial state is muted. 0x04 is unmuted. */ emu8k->hwcf3 = 0x00; } void emu8k_close(emu8k_t *emu8k) { free(emu8k->rom); free(emu8k->ram); } ```
/content/code_sandbox/src/sound/snd_emu8k.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
28,341
```c #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <86box/86box.h> #include <86box/device.h> #include <86box/gameport.h> #include <86box/io.h> #include <86box/snd_resid.h> #include <86box/sound.h> #include <86box/plat_unused.h> typedef struct ssi2001_t { void *psid; int16_t buffer[SOUNDBUFLEN * 2]; int pos; int gameport_enabled; } ssi2001_t; static void ssi2001_update(ssi2001_t *ssi2001) { if (ssi2001->pos >= sound_pos_global) return; sid_fillbuf(&ssi2001->buffer[ssi2001->pos], sound_pos_global - ssi2001->pos, ssi2001->psid); ssi2001->pos = sound_pos_global; } static void ssi2001_get_buffer(int32_t *buffer, int len, void *priv) { ssi2001_t *ssi2001 = (ssi2001_t *) priv; ssi2001_update(ssi2001); for (int c = 0; c < len * 2; c++) buffer[c] += ssi2001->buffer[c >> 1] / 2; ssi2001->pos = 0; } static uint8_t ssi2001_read(uint16_t addr, void *priv) { ssi2001_t *ssi2001 = (ssi2001_t *) priv; ssi2001_update(ssi2001); return sid_read(addr, priv); } static void ssi2001_write(uint16_t addr, uint8_t val, void *priv) { ssi2001_t *ssi2001 = (ssi2001_t *) priv; ssi2001_update(ssi2001); sid_write(addr, val, priv); } void * ssi2001_init(UNUSED(const device_t *info)) { ssi2001_t *ssi2001 = malloc(sizeof(ssi2001_t)); memset(ssi2001, 0, sizeof(ssi2001_t)); ssi2001->psid = sid_init(); sid_reset(ssi2001->psid); uint16_t addr = device_get_config_hex16("base"); ssi2001->gameport_enabled = device_get_config_int("gameport"); io_sethandler(addr, 0x0020, ssi2001_read, NULL, NULL, ssi2001_write, NULL, NULL, ssi2001); if (ssi2001->gameport_enabled) gameport_remap(gameport_add(&gameport_201_device), 0x201); sound_add_handler(ssi2001_get_buffer, ssi2001); return ssi2001; } void ssi2001_close(void *priv) { ssi2001_t *ssi2001 = (ssi2001_t *) priv; sid_close(ssi2001->psid); free(ssi2001); } static const device_config_t ssi2001_config[] = { // clang-format off { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x280, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x280", .value = 0x280 }, { .description = "0x2A0", .value = 0x2A0 }, { .description = "0x2C0", .value = 0x2C0 }, { .description = "0x2E0", .value = 0x2E0 }, { .description = "" } } }, { "gameport", "Enable Game port", CONFIG_BINARY, "", 1 }, { "", "", -1 } // clang-format off }; const device_t ssi2001_device = { .name = "Innovation SSI-2001", .internal_name = "ssi2001", .flags = DEVICE_ISA, .local = 0, .init = ssi2001_init, .close = ssi2001_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = ssi2001_config }; ```
/content/code_sandbox/src/sound/snd_ssi2001.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,027
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Windows Sound System emulation. * * * * Authors: Sarah Walker, <path_to_url * TheCollector1995, <mariogplayer@gmail.com> * */ #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/device.h> #include <86box/dma.h> #include <86box/io.h> #include <86box/mca.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/timer.h> #include <86box/snd_ad1848.h> #include <86box/snd_opl.h> #include <86box/plat_unused.h> /* 530, 11, 3 - 530=23 * 530, 11, 1 - 530=22 * 530, 11, 0 - 530=21 * 530, 10, 1 - 530=1a * 530, 9, 1 - 530=12 * 530, 7, 1 - 530=0a * 604, 11, 1 - 530=22 * e80, 11, 1 - 530=22 * f40, 11, 1 - 530=22 */ static const int wss_dma[4] = { 0, 0, 1, 3 }; static const int wss_irq[8] = { 5, 7, 9, 10, 11, 12, 14, 15 }; /* W95 only uses 7-9, others may be wrong */ typedef struct wss_t { uint8_t config; ad1848_t ad1848; fm_drv_t opl; int opl_enabled; uint8_t pos_regs[8]; } wss_t; uint8_t wss_read(UNUSED(uint16_t addr), void *priv) { const wss_t *wss = (wss_t *) priv; return 4 | (wss->config & 0x40); } void wss_write(UNUSED(uint16_t addr), uint8_t val, void *priv) { wss_t *wss = (wss_t *) priv; wss->config = val; ad1848_setdma(&wss->ad1848, wss_dma[val & 3]); ad1848_setirq(&wss->ad1848, wss_irq[(val >> 3) & 7]); } static void wss_get_buffer(int32_t *buffer, int len, void *priv) { wss_t *wss = (wss_t *) priv; ad1848_update(&wss->ad1848); for (int c = 0; c < len * 2; c++) buffer[c] += wss->ad1848.buffer[c] / 2; wss->ad1848.pos = 0; } static void wss_get_music_buffer(int32_t *buffer, int len, void *priv) { wss_t *wss = (wss_t *) priv; const int32_t *opl_buf = NULL; opl_buf = wss->opl.update(wss->opl.priv); for (int c = 0; c < len * 2; c++) { if (opl_buf) buffer[c] += opl_buf[c]; } wss->opl.reset_buffer(wss->opl.priv); } void * wss_init(UNUSED(const device_t *info)) { wss_t *wss = malloc(sizeof(wss_t)); memset(wss, 0, sizeof(wss_t)); uint16_t addr = device_get_config_hex16("base"); wss->opl_enabled = device_get_config_int("opl"); if (wss->opl_enabled) fm_driver_get(FM_YMF262, &wss->opl); ad1848_init(&wss->ad1848, AD1848_TYPE_DEFAULT); ad1848_setirq(&wss->ad1848, 7); ad1848_setdma(&wss->ad1848, 3); if (wss->opl_enabled) io_sethandler(0x0388, 0x0004, wss->opl.read, NULL, NULL, wss->opl.write, NULL, NULL, wss->opl.priv); io_sethandler(addr, 0x0004, wss_read, NULL, NULL, wss_write, NULL, NULL, wss); io_sethandler(addr + 4, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &wss->ad1848); sound_add_handler(wss_get_buffer, wss); if (wss->opl_enabled) music_add_handler(wss_get_music_buffer, wss); return wss; } static uint8_t ncr_audio_mca_read(int port, void *priv) { const wss_t *wss = (wss_t *) priv; return wss->pos_regs[port & 7]; } static void ncr_audio_mca_write(int port, uint8_t val, void *priv) { wss_t *wss = (wss_t *) priv; uint16_t ports[4] = { 0x530, 0xE80, 0xF40, 0x604 }; uint16_t addr; if (port < 0x102) return; wss->opl_enabled = (wss->pos_regs[2] & 0x20) ? 1 : 0; addr = ports[(wss->pos_regs[2] & 0x18) >> 3]; io_removehandler(0x0388, 0x0004, wss->opl.read, NULL, NULL, wss->opl.write, NULL, NULL, wss->opl.priv); io_removehandler(addr, 0x0004, wss_read, NULL, NULL, wss_write, NULL, NULL, wss); io_removehandler(addr + 4, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &wss->ad1848); wss->pos_regs[port & 7] = val; if (wss->pos_regs[2] & 1) { addr = ports[(wss->pos_regs[2] & 0x18) >> 3]; if (wss->opl_enabled) io_sethandler(0x0388, 0x0004, wss->opl.read, NULL, NULL, wss->opl.write, NULL, NULL, wss->opl.priv); io_sethandler(addr, 0x0004, wss_read, NULL, NULL, wss_write, NULL, NULL, wss); io_sethandler(addr + 4, 0x0004, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &wss->ad1848); } } static uint8_t ncr_audio_mca_feedb(void *priv) { const wss_t *wss = (wss_t *) priv; return (wss->pos_regs[2] & 1); } void * ncr_audio_init(UNUSED(const device_t *info)) { wss_t *wss = malloc(sizeof(wss_t)); memset(wss, 0, sizeof(wss_t)); fm_driver_get(FM_YMF262, &wss->opl); ad1848_init(&wss->ad1848, AD1848_TYPE_DEFAULT); ad1848_setirq(&wss->ad1848, 7); ad1848_setdma(&wss->ad1848, 3); mca_add(ncr_audio_mca_read, ncr_audio_mca_write, ncr_audio_mca_feedb, NULL, wss); wss->pos_regs[0] = 0x16; wss->pos_regs[1] = 0x51; sound_add_handler(wss_get_buffer, wss); if (wss->opl_enabled) music_add_handler(wss_get_music_buffer, wss); return wss; } void wss_close(void *priv) { wss_t *wss = (wss_t *) priv; free(wss); } void wss_speed_changed(void *priv) { wss_t *wss = (wss_t *) priv; ad1848_speed_changed(&wss->ad1848); } static const device_config_t wss_config[] = { // clang-format off { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x530, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x530", .value = 0x530 }, { .description = "0x604", .value = 0x604 }, { .description = "0xe80", .value = 0xe80 }, { .description = "0xf40", .value = 0xf40 }, { .description = "" } } }, { .name = "opl", .description = "Enable OPL", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t wss_device = { .name = "Windows Sound System", .internal_name = "wss", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = wss_init, .close = wss_close, .reset = NULL, { .available = NULL }, .speed_changed = wss_speed_changed, .force_redraw = NULL, .config = wss_config }; const device_t ncr_business_audio_device = { .name = "NCR Business Audio", .internal_name = "ncraudio", .flags = DEVICE_MCA, .local = 0, .init = ncr_audio_init, .close = wss_close, .reset = NULL, { .available = NULL }, .speed_changed = wss_speed_changed, .force_redraw = NULL, .config = NULL }; ```
/content/code_sandbox/src/sound/snd_wss.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,469
```c #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #define HAVE_STDARG_H #include <math.h> #include <86box/86box.h> #include <86box/device.h> #include <86box/dma.h> #include <86box/io.h> #include <86box/midi.h> #include <86box/nmi.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/timer.h> #ifdef USE_GUSMAX # include <86box/snd_ad1848.h> #endif /*USE_GUSMAX */ #include <86box/plat_fallthrough.h> #include <86box/plat_unused.h> enum { MIDI_INT_RECEIVE = 0x01, MIDI_INT_TRANSMIT = 0x02, MIDI_INT_MASTER = 0x80 }; enum { MIDI_CTRL_TRANSMIT_MASK = 0x60, MIDI_CTRL_TRANSMIT = 0x20, MIDI_CTRL_RECEIVE = 0x80 }; enum { GUS_INT_MIDI_TRANSMIT = 0x01, GUS_INT_MIDI_RECEIVE = 0x02 }; enum { GUS_TIMER_CTRL_AUTO = 0x01 }; enum { GUS_CLASSIC = 0, GUS_MAX = 1, }; typedef struct gus_t { int reset; int global; uint32_t addr; uint32_t dmaaddr; int voice; uint32_t start[32]; uint32_t end[32]; uint32_t cur[32]; uint32_t startx[32]; uint32_t endx[32]; uint32_t curx[32]; int rstart[32]; int rend[32]; int rcur[32]; uint16_t freq[32]; uint16_t rfreq[32]; uint8_t ctrl[32]; uint8_t rctrl[32]; int curvol[32]; int pan_l[32]; int pan_r[32]; int t1on; int t2on; uint8_t tctrl; uint16_t t1; uint16_t t2; uint16_t t1l; uint16_t t2l; uint8_t irqstatus; uint8_t irqstatus2; uint8_t adcommand; int waveirqs[32]; int rampirqs[32]; int voices; uint8_t dmactrl; int32_t out_l; int32_t out_r; int16_t buffer[2][SOUNDBUFLEN]; int pos; pc_timer_t samp_timer; uint64_t samp_latch; uint8_t *ram; uint32_t gus_end_ram; int irqnext; uint8_t irq_state; uint8_t midi_irq_state; pc_timer_t timer_1; pc_timer_t timer_2; uint8_t type; int irq; int dma; int irq_midi; int dma2; uint16_t base; int latch_enable; uint8_t sb_2xa; uint8_t sb_2xc; uint8_t sb_2xe; uint8_t sb_ctrl; int sb_nmi; uint8_t reg_ctrl; uint8_t ad_status; uint8_t ad_data; uint8_t ad_timer_ctrl; uint8_t midi_ctrl; uint8_t midi_status; uint8_t midi_queue[64]; uint8_t midi_data; int midi_r; int midi_w; int uart_in; int uart_out; int sysex; uint8_t gp1; uint8_t gp2; uint16_t gp1_addr; uint16_t gp2_addr; uint8_t usrr; #ifdef USE_GUSMAX uint8_t max_ctrl; ad1848_t ad1848; #endif /*USE_GUSMAX */ } gus_t; static int gus_gf1_irqs[8] = { -1, 2, 5, 3, 7, 11, 12, 15 }; static int gus_midi_irqs[8] = { -1, 2, 5, 3, 7, 11, 12, 15 }; static int gus_dmas[8] = { -1, 1, 3, 5, 6, 7, -1, -1 }; int gusfreqs[] = { 44100, 41160, 38587, 36317, 34300, 32494, 30870, 29400, 28063, 26843, 25725, 24696, 23746, 22866, 22050, 21289, 20580, 19916, 19293 }; double vol16bit[4096]; void gus_update_int_status(gus_t *gus) { int irq_pending = 0; int midi_irq_pending = 0; int intr_pending = 0; int midi_intr_pending = 0; gus->irqstatus &= ~0x60; gus->irqstatus2 = 0xE0; for (uint8_t c = 0; c < 32; c++) { if (gus->waveirqs[c]) { gus->irqstatus2 = 0x60 | c; if (gus->rampirqs[c]) gus->irqstatus2 |= 0x80; gus->irqstatus |= 0x20; irq_pending = 1; break; } if (gus->rampirqs[c]) { gus->irqstatus2 = 0xA0 | c; gus->irqstatus |= 0x40; irq_pending = 1; break; } } if ((gus->tctrl & 4) && (gus->irqstatus & 0x04)) irq_pending = 1; /*Timer 1 interrupt pending*/ if ((gus->tctrl & 8) && (gus->irqstatus & 0x08)) irq_pending = 1; /*Timer 2 interrupt pending*/ if ((gus->irqstatus & 0x80) && (gus->dmactrl & 0x20)) irq_pending = 1; /*DMA TC interrupt pending*/ midi_irq_pending = gus->midi_status & MIDI_INT_MASTER; if (gus->irq == gus->irq_midi) { if (irq_pending || midi_irq_pending) intr_pending = 1; else intr_pending = 0; } else { if (irq_pending) intr_pending = 1; else intr_pending = 0; if (midi_irq_pending) midi_intr_pending = 1; else midi_intr_pending = 0; } if (gus->irq != -1) { if (intr_pending) picint(1 << gus->irq); else picintc(1 << gus->irq); } if ((gus->irq_midi != -1) && (gus->irq_midi != gus->irq)) { if (midi_intr_pending) picint(1 << gus->irq_midi); else picintc(1 << gus->irq_midi); } } void gus_midi_update_int_status(gus_t *gus) { gus->midi_status &= ~MIDI_INT_MASTER; if ((gus->midi_ctrl & MIDI_CTRL_TRANSMIT_MASK) == MIDI_CTRL_TRANSMIT && (gus->midi_status & MIDI_INT_TRANSMIT)) { gus->midi_status |= MIDI_INT_MASTER; gus->irqstatus |= GUS_INT_MIDI_TRANSMIT; } else gus->irqstatus &= ~GUS_INT_MIDI_TRANSMIT; if ((gus->midi_ctrl & MIDI_CTRL_RECEIVE) && (gus->midi_status & MIDI_INT_RECEIVE)) { gus->midi_status |= MIDI_INT_MASTER; gus->irqstatus |= GUS_INT_MIDI_RECEIVE; } else gus->irqstatus &= ~GUS_INT_MIDI_RECEIVE; gus_update_int_status(gus); } void writegus(uint16_t addr, uint8_t val, void *priv) { gus_t *gus = (gus_t *) priv; int c; int d; int old; uint16_t port; #ifdef USE_GUSMAX uint16_t csioport; #endif /*USE_GUSMAX */ if ((addr == 0x388) || (addr == 0x389)) port = addr; else port = addr & 0xf0f; switch (port) { case 0x300: /*MIDI control*/ old = gus->midi_ctrl; gus->midi_ctrl = val; gus->uart_out = 1; if ((val & 3) == 3) { /*Master reset*/ gus->uart_in = 0; gus->midi_status = 0; gus->midi_r = 0; gus->midi_w = 0; } else if ((old & 3) == 3) { gus->midi_status |= MIDI_INT_TRANSMIT; } else if (gus->midi_ctrl & MIDI_CTRL_RECEIVE) { gus->uart_in = 1; } gus_midi_update_int_status(gus); break; case 0x301: /*MIDI data*/ gus->midi_data = val; if (gus->uart_out) { midi_raw_out_byte(val); } if (gus->latch_enable & 0x20) { gus->midi_status |= MIDI_INT_RECEIVE; } else gus->midi_status |= MIDI_INT_TRANSMIT; break; case 0x302: /*Voice select*/ gus->voice = val & 31; break; case 0x303: /*Global select*/ gus->global = val; break; case 0x304: /*Global low*/ switch (gus->global) { case 0: /*Voice control*/ gus->ctrl[gus->voice] = val; break; case 1: /*Frequency control*/ gus->freq[gus->voice] = (gus->freq[gus->voice] & 0xFF00) | val; break; case 2: /*Start addr high*/ gus->startx[gus->voice] = (gus->startx[gus->voice] & 0xF807F) | (val << 7); gus->start[gus->voice] = (gus->start[gus->voice] & 0x1F00FFFF) | (val << 16); break; case 3: /*Start addr low*/ gus->start[gus->voice] = (gus->start[gus->voice] & 0x1FFFFF00) | val; break; case 4: /*End addr high*/ gus->endx[gus->voice] = (gus->endx[gus->voice] & 0xF807F) | (val << 7); gus->end[gus->voice] = (gus->end[gus->voice] & 0x1F00FFFF) | (val << 16); break; case 5: /*End addr low*/ gus->end[gus->voice] = (gus->end[gus->voice] & 0x1FFFFF00) | val; break; case 6: /*Ramp frequency*/ gus->rfreq[gus->voice] = (int) ((double) ((val & 63) * 512) / (double) (1 << (3 * (val >> 6)))); break; case 9: /*Current volume*/ gus->curvol[gus->voice] = gus->rcur[gus->voice] = (gus->rcur[gus->voice] & ~(0xff << 6)) | (val << 6); break; case 0xA: /*Current addr high*/ gus->cur[gus->voice] = (gus->cur[gus->voice] & 0x1F00FFFF) | (val << 16); gus->curx[gus->voice] = (gus->curx[gus->voice] & 0xF807F00) | ((val << 7) << 8); break; case 0xB: /*Current addr low*/ gus->cur[gus->voice] = (gus->cur[gus->voice] & 0x1FFFFF00) | val; break; case 0x42: /*DMA address low*/ gus->dmaaddr = (gus->dmaaddr & 0xFF000) | (val << 4); break; case 0x43: /*Address low*/ gus->addr = (gus->addr & 0xFFF00) | val; break; case 0x45: /*Timer control*/ gus->tctrl = val; gus_update_int_status(gus); break; default: break; } break; case 0x305: /*Global high*/ switch (gus->global) { case 0: /*Voice control*/ gus->ctrl[gus->voice] = val & 0x7f; old = gus->waveirqs[gus->voice]; gus->waveirqs[gus->voice] = ((val & 0xa0) == 0xa0) ? 1 : 0; if (gus->waveirqs[gus->voice] != old) gus_update_int_status(gus); break; case 1: /*Frequency control*/ gus->freq[gus->voice] = (gus->freq[gus->voice] & 0xFF) | (val << 8); break; case 2: /*Start addr high*/ gus->startx[gus->voice] = (gus->startx[gus->voice] & 0x07FFF) | (val << 15); gus->start[gus->voice] = (gus->start[gus->voice] & 0x00FFFFFF) | ((val & 0x1F) << 24); break; case 3: /*Start addr low*/ gus->startx[gus->voice] = (gus->startx[gus->voice] & 0xFFF80) | (val & 0x7F); gus->start[gus->voice] = (gus->start[gus->voice] & 0x1FFF00FF) | (val << 8); break; case 4: /*End addr high*/ gus->endx[gus->voice] = (gus->endx[gus->voice] & 0x07FFF) | (val << 15); gus->end[gus->voice] = (gus->end[gus->voice] & 0x00FFFFFF) | ((val & 0x1F) << 24); break; case 5: /*End addr low*/ gus->endx[gus->voice] = (gus->endx[gus->voice] & 0xFFF80) | (val & 0x7F); gus->end[gus->voice] = (gus->end[gus->voice] & 0x1FFF00FF) | (val << 8); break; case 6: /*Ramp frequency*/ gus->rfreq[gus->voice] = (int) ((double) ((val & 63) * (1 << 10)) / (double) (1 << (3 * (val >> 6)))); break; case 7: /*Ramp start*/ gus->rstart[gus->voice] = val << 14; break; case 8: /*Ramp end*/ gus->rend[gus->voice] = val << 14; break; case 9: /*Current volume*/ gus->curvol[gus->voice] = gus->rcur[gus->voice] = (gus->rcur[gus->voice] & ~(0xff << 14)) | (val << 14); break; case 0xA: /*Current addr high*/ gus->cur[gus->voice] = (gus->cur[gus->voice] & 0x00FFFFFF) | ((val & 0x1F) << 24); gus->curx[gus->voice] = (gus->curx[gus->voice] & 0x07FFF00) | ((val << 15) << 8); break; case 0xB: /*Current addr low*/ gus->cur[gus->voice] = (gus->cur[gus->voice] & 0x1FFF00FF) | (val << 8); gus->curx[gus->voice] = (gus->curx[gus->voice] & 0xFFF8000) | ((val & 0x7F) << 8); break; case 0xC: /*Pan*/ gus->pan_l[gus->voice] = 15 - (val & 0xf); gus->pan_r[gus->voice] = (val & 0xf); break; case 0xD: /*Ramp control*/ old = gus->rampirqs[gus->voice]; gus->rctrl[gus->voice] = val & 0x7F; gus->rampirqs[gus->voice] = ((val & 0xa0) == 0xa0) ? 1 : 0; if (gus->rampirqs[gus->voice] != old) gus_update_int_status(gus); break; case 0xE: gus->voices = (val & 63) + 1; if (gus->voices > 32) gus->voices = 32; if (gus->voices < 14) gus->voices = 14; gus->global = val; if (gus->voices < 14) gus->samp_latch = (uint64_t) (TIMER_USEC * (1000000.0 / 44100.0)); else gus->samp_latch = (uint64_t) (TIMER_USEC * (1000000.0 / gusfreqs[gus->voices - 14])); break; case 0x41: /*DMA*/ if (val & 1 && gus->dma != -1) { if (val & 2) { c = 0; while (c < 65536) { int dma_result; if (val & 0x04) { uint32_t gus_addr = (gus->dmaaddr & 0xc0000) | ((gus->dmaaddr & 0x1ffff) << 1); if (gus_addr < gus->gus_end_ram) d = gus->ram[gus_addr]; else d = 0x00; if ((gus_addr + 1) < gus->gus_end_ram) d |= (gus->ram[gus_addr + 1] << 8); if (val & 0x80) d ^= 0x8080; dma_result = dma_channel_write(gus->dma, d); if (dma_result == DMA_NODATA) break; } else { if (gus->dmaaddr < gus->gus_end_ram) d = gus->ram[gus->dmaaddr]; else d = 0x00; if (val & 0x80) d ^= 0x80; dma_result = dma_channel_write(gus->dma, d); if (dma_result == DMA_NODATA) break; } gus->dmaaddr++; gus->dmaaddr &= 0xfffff; c++; if (dma_result & DMA_OVER) break; } gus->dmactrl = val & ~0x40; gus->irqnext = 1; } else { c = 0; while (c < 65536) { d = dma_channel_read(gus->dma); if (d == DMA_NODATA) break; if (val & 0x04) { uint32_t gus_addr = (gus->dmaaddr & 0xc0000) | ((gus->dmaaddr & 0x1ffff) << 1); if (val & 0x80) d ^= 0x8080; if (gus_addr < gus->gus_end_ram) gus->ram[gus_addr] = d & 0xff; if ((gus_addr + 1) < gus->gus_end_ram) gus->ram[gus_addr + 1] = (d >> 8) & 0xff; } else { if (val & 0x80) d ^= 0x80; if (gus->dmaaddr < gus->gus_end_ram) gus->ram[gus->dmaaddr] = d; } gus->dmaaddr++; gus->dmaaddr &= 0xfffff; c++; if (d & DMA_OVER) break; } gus->dmactrl = val & ~0x40; gus->irqnext = 1; } } break; case 0x42: /*DMA address low*/ gus->dmaaddr = (gus->dmaaddr & 0xFF0) | (val << 12); break; case 0x43: /*Address low*/ gus->addr = (gus->addr & 0xf00ff) | (val << 8); break; case 0x44: /*Address high*/ gus->addr = (gus->addr & 0x0ffff) | ((val << 16) & 0xf0000); break; case 0x45: /*Timer control*/ if (!(val & 4)) gus->irqstatus &= ~4; if (!(val & 8)) gus->irqstatus &= ~8; if (!(val & 0x20)) gus->ad_status &= ~0x18; if (!(val & 0x02)) gus->ad_status &= ~0x01; gus->tctrl = val; gus->sb_ctrl = val; gus_update_int_status(gus); break; case 0x46: /*Timer 1*/ gus->t1 = gus->t1l = val; gus->t1on = 1; break; case 0x47: /*Timer 2*/ gus->t2 = gus->t2l = val; gus->t2on = 1; break; case 0x4c: /*Reset*/ gus->reset = val; break; default: break; } break; case 0x307: /*DRAM access*/ if (gus->addr < gus->gus_end_ram) gus->ram[gus->addr] = val; gus->addr &= 0xfffff; break; case 0x208: case 0x388: gus->adcommand = val; break; case 0x389: if ((gus->tctrl & GUS_TIMER_CTRL_AUTO) || gus->adcommand != 4) { gus->ad_data = val; gus->ad_status |= 0x01; if (gus->sb_ctrl & 0x02) { if (gus->sb_nmi) nmi_raise(); else if (gus->irq != -1) picint(1 << gus->irq); } } else if (!(gus->tctrl & GUS_TIMER_CTRL_AUTO) && gus->adcommand == 4) { if (val & 0x80) { gus->ad_status &= ~0x60; } else { gus->ad_timer_ctrl = val; if (val & 0x01) gus->t1on = 1; else gus->t1 = gus->t1l; if (val & 0x02) gus->t2on = 1; else gus->t2 = gus->t2l; } } break; case 0x200: gus->latch_enable = val; break; case 0x20b: switch (gus->reg_ctrl & 0x07) { case 0: if (gus->latch_enable & 0x40) { gus->irq = gus_gf1_irqs[val & 7]; if (val & 0x40) { if (gus->irq == -1) gus->irq = gus->irq_midi = gus_gf1_irqs[(val >> 3) & 7]; else gus->irq_midi = gus->irq; } else gus->irq_midi = gus_midi_irqs[(val >> 3) & 7]; #ifdef USE_GUSMAX if (gus->type == GUS_MAX) ad1848_setirq(&gus->ad1848, gus->irq); #endif /*USE_GUSMAX */ gus->sb_nmi = val & 0x80; } else { gus->dma = gus_dmas[val & 7]; if (val & 0x40) { if (gus->dma == -1) gus->dma = gus->dma2 = gus_dmas[(val >> 3) & 7]; else gus->dma2 = gus->dma; } else gus->dma2 = gus_dmas[(val >> 3) & 7]; #ifdef USE_GUSMAX if (gus->type == GUS_MAX) ad1848_setdma(&gus->ad1848, gus->dma2); #endif /*USE_GUSMAX */ } break; case 1: gus->gp1 = val; break; case 2: gus->gp2 = val; break; case 3: gus->gp1_addr = val; break; case 4: gus->gp2_addr = val; break; case 5: gus->usrr = 0; break; case 6: break; default: break; } break; case 0x206: gus->ad_status |= 0x08; if (gus->sb_ctrl & 0x20) { if (gus->sb_nmi) nmi_raise(); else if (gus->irq != -1) picint(1 << gus->irq); } break; case 0x20a: gus->sb_2xa = val; break; case 0x20c: gus->ad_status |= 0x10; if (gus->sb_ctrl & 0x20) { if (gus->sb_nmi) nmi_raise(); else if (gus->irq != -1) picint(1 << gus->irq); } fallthrough; case 0x20d: gus->sb_2xc = val; break; case 0x20e: gus->sb_2xe = val; break; case 0x20f: gus->reg_ctrl = val; break; case 0x306: case 0x706: #ifdef USE_GUSMAX if (gus->type == GUS_MAX) { if (gus->dma >= 4) val |= 0x10; if (gus->dma2 >= 4) val |= 0x20; gus->max_ctrl = (val >> 6) & 1; if (val & 0x40) { if ((val & 0xF) != ((addr >> 4) & 0xF)) { csioport = 0x30c | ((addr >> 4) & 0xf); io_removehandler(csioport, 4, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &gus->ad1848); csioport = 0x30c | ((val & 0xf) << 4); io_sethandler(csioport, 4, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &gus->ad1848); } } } #endif /*USE_GUSMAX */ break; default: break; } } uint8_t readgus(uint16_t addr, void *priv) { gus_t *gus = (gus_t *) priv; uint8_t val = 0xff; uint16_t port; if ((addr == 0x388) || (addr == 0x389)) port = addr; else port = addr & 0xf0f; switch (port) { case 0x300: /*MIDI status*/ val = gus->midi_status; break; case 0x301: /*MIDI data*/ val = 0; if (gus->uart_in) { if ((gus->midi_data == 0xaa) && (gus->midi_ctrl & MIDI_CTRL_RECEIVE)) /*Handle master reset*/ val = gus->midi_data; else { val = gus->midi_queue[gus->midi_r]; if (gus->midi_r != gus->midi_w) { gus->midi_r++; gus->midi_r &= 63; } } gus->midi_status &= ~MIDI_INT_RECEIVE; gus_midi_update_int_status(gus); } break; case 0x200: return 0; case 0x206: /*IRQ status*/ val = gus->irqstatus & ~0x10; if (gus->ad_status & 0x19) val |= 0x10; return val; case 0x20F: #ifdef USE_GUSMAX if (gus->type == GUS_MAX) val = 0x02; else #endif /*USE_GUSMAX */ val = 0x00; break; case 0x302: return gus->voice; case 0x303: return gus->global; case 0x304: /*Global low*/ switch (gus->global) { case 0x82: /*Start addr high*/ return gus->start[gus->voice] >> 16; case 0x83: /*Start addr low*/ return gus->start[gus->voice] & 0xFF; case 0x89: /*Current volume*/ return gus->rcur[gus->voice] >> 6; case 0x8A: /*Current addr high*/ return gus->cur[gus->voice] >> 16; case 0x8B: /*Current addr low*/ return gus->cur[gus->voice] & 0xFF; case 0x8F: /*IRQ status*/ val = gus->irqstatus2; gus->rampirqs[gus->irqstatus2 & 0x1F] = 0; gus->waveirqs[gus->irqstatus2 & 0x1F] = 0; gus_update_int_status(gus); return val; case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: val = 0xff; break; default: break; } break; case 0x305: /*Global high*/ switch (gus->global) { case 0x80: /*Voice control*/ return gus->ctrl[gus->voice] | (gus->waveirqs[gus->voice] ? 0x80 : 0); case 0x82: /*Start addr high*/ return gus->start[gus->voice] >> 24; case 0x83: /*Start addr low*/ return gus->start[gus->voice] >> 8; case 0x89: /*Current volume*/ return gus->rcur[gus->voice] >> 14; case 0x8A: /*Current addr high*/ return gus->cur[gus->voice] >> 24; case 0x8B: /*Current addr low*/ return gus->cur[gus->voice] >> 8; case 0x8C: /*Pan*/ return gus->pan_r[gus->voice]; case 0x8D: return gus->rctrl[gus->voice] | (gus->rampirqs[gus->voice] ? 0x80 : 0); case 0x8F: /*IRQ status*/ val = gus->irqstatus2; gus->rampirqs[gus->irqstatus2 & 0x1F] = 0; gus->waveirqs[gus->irqstatus2 & 0x1F] = 0; gus_update_int_status(gus); return val; case 0x41: /*DMA control*/ val = gus->dmactrl | ((gus->irqstatus & 0x80) ? 0x40 : 0); gus->irqstatus &= ~0x80; return val; case 0x45: /*Timer control*/ return gus->tctrl; case 0x49: /*Sampling control*/ return 0; case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: val = 0xff; break; default: break; } break; case 0x306: case 0x706: #ifdef USE_GUSMAX if (gus->type == GUS_MAX) val = 0x0a; /* GUS MAX */ else #endif /*USE_GUSMAX */ val = 0xff; /*Pre 3.7 - no mixer*/ break; case 0x307: /*DRAM access*/ gus->addr &= 0xfffff; if (gus->addr < gus->gus_end_ram) val = gus->ram[gus->addr]; else val = 0; return val; case 0x309: return 0; case 0x20b: switch (gus->reg_ctrl & 0x07) { case 1: val = gus->gp1; break; case 2: val = gus->gp2; break; case 3: val = gus->gp1_addr; break; case 4: val = gus->gp2_addr; break; default: break; } break; case 0x20c: val = gus->sb_2xc; if (gus->reg_ctrl & 0x20) gus->sb_2xc &= 0x80; break; case 0x20e: return gus->sb_2xe; case 0x208: case 0x388: if (gus->tctrl & GUS_TIMER_CTRL_AUTO) val = gus->sb_2xa; else { val = gus->ad_status & ~(gus->ad_timer_ctrl & 0x60); if (val & 0x60) val |= 0x80; } break; case 0x209: gus->ad_status &= ~0x01; #ifdef OLD_NMI_BEHAVIOR nmi = 0; #endif /* OLD_NMI_BEHAVIOR */ fallthrough; case 0x389: val = gus->ad_data; break; case 0x20A: val = gus->adcommand; break; default: break; } return val; } void gus_poll_timer_1(void *priv) { gus_t *gus = (gus_t *) priv; timer_advance_u64(&gus->timer_1, (uint64_t) (TIMER_USEC * 80)); if (gus->t1on) { gus->t1++; if (gus->t1 > 0xFF) { gus->t1 = gus->t1l; gus->ad_status |= 0x40; if (gus->tctrl & 4) { gus->ad_status |= 0x04; gus->irqstatus |= 0x04; } } } if (gus->irqnext) { gus->irqnext = 0; gus->irqstatus |= 0x80; } gus_midi_update_int_status(gus); gus_update_int_status(gus); } void gus_poll_timer_2(void *priv) { gus_t *gus = (gus_t *) priv; timer_advance_u64(&gus->timer_2, (uint64_t) (TIMER_USEC * 320)); if (gus->t2on) { gus->t2++; if (gus->t2 > 0xFF) { gus->t2 = gus->t2l; gus->ad_status |= 0x20; if (gus->tctrl & 8) { gus->ad_status |= 0x02; gus->irqstatus |= 0x08; } } } if (gus->irqnext) { gus->irqnext = 0; gus->irqstatus |= 0x80; } gus_update_int_status(gus); } static void gus_update(gus_t *gus) { for (; gus->pos < sound_pos_global; gus->pos++) { if (gus->out_l < -32768) gus->buffer[0][gus->pos] = -32768; else if (gus->out_l > 32767) gus->buffer[0][gus->pos] = 32767; else gus->buffer[0][gus->pos] = gus->out_l; if (gus->out_r < -32768) gus->buffer[1][gus->pos] = -32768; else if (gus->out_r > 32767) gus->buffer[1][gus->pos] = 32767; else gus->buffer[1][gus->pos] = gus->out_r; } } void gus_poll_wave(void *priv) { gus_t *gus = (gus_t *) priv; uint32_t addr; int16_t v; int32_t vl; int update_irqs = 0; gus_update(gus); timer_advance_u64(&gus->samp_timer, gus->samp_latch); gus->out_l = gus->out_r = 0; if ((gus->reset & 3) != 3) return; for (uint8_t d = 0; d < 32; d++) { if (!(gus->ctrl[d] & 3)) { if (gus->ctrl[d] & 4) { addr = gus->cur[d] >> 9; addr = (addr & 0xC0000) | ((addr << 1) & 0x3FFFE); if (!(gus->freq[d] >> 10)) { /* Interpolate */ if (((addr + 1) & 0xfffff) < gus->gus_end_ram) vl = (int16_t) (int8_t) ((gus->ram[(addr + 1) & 0xfffff] ^ 0x80) - 0x80) * (511 - (gus->cur[d] & 511)); else vl = 0; if (((addr + 3) & 0xfffff) < gus->gus_end_ram) vl += (int16_t) (int8_t) ((gus->ram[(addr + 3) & 0xfffff] ^ 0x80) - 0x80) * (gus->cur[d] & 511); v = vl >> 9; } else if (((addr + 1) & 0xfffff) < gus->gus_end_ram) v = (int16_t) (int8_t) ((gus->ram[(addr + 1) & 0xfffff] ^ 0x80) - 0x80); else v = 0x0000; } else { if (!(gus->freq[d] >> 10)) { /* Interpolate */ if (((gus->cur[d] >> 9) & 0xfffff) < gus->gus_end_ram) vl = ((int8_t) ((gus->ram[(gus->cur[d] >> 9) & 0xfffff] ^ 0x80) - 0x80)) * (511 - (gus->cur[d] & 511)); else vl = 0; if ((((gus->cur[d] >> 9) + 1) & 0xfffff) < gus->gus_end_ram) vl += ((int8_t) ((gus->ram[((gus->cur[d] >> 9) + 1) & 0xfffff] ^ 0x80) - 0x80)) * (gus->cur[d] & 511); v = vl >> 9; } else if (((gus->cur[d] >> 9) & 0xfffff) < gus->gus_end_ram) v = (int16_t) (int8_t) ((gus->ram[(gus->cur[d] >> 9) & 0xfffff] ^ 0x80) - 0x80); else v = 0x0000; } if ((gus->rcur[d] >> 14) > 4095) v = (int16_t) (float) (v) *24.0 * vol16bit[4095]; else v = (int16_t) (float) (v) *24.0 * vol16bit[(gus->rcur[d] >> 10) & 4095]; gus->out_l += (v * gus->pan_l[d]) / 7; gus->out_r += (v * gus->pan_r[d]) / 7; if (gus->ctrl[d] & 0x40) { gus->cur[d] -= (gus->freq[d] >> 1); if (gus->cur[d] <= gus->start[d]) { int diff = gus->start[d] - gus->cur[d]; if (gus->ctrl[d] & 8) { if (gus->ctrl[d] & 0x10) gus->ctrl[d] ^= 0x40; gus->cur[d] = (gus->ctrl[d] & 0x40) ? (gus->end[d] - diff) : (gus->start[d] + diff); } else if (!(gus->rctrl[d] & 4)) { gus->ctrl[d] |= 1; gus->cur[d] = (gus->ctrl[d] & 0x40) ? gus->end[d] : gus->start[d]; } if ((gus->ctrl[d] & 0x20) && !gus->waveirqs[d]) { gus->waveirqs[d] = 1; update_irqs = 1; } } } else { gus->cur[d] += (gus->freq[d] >> 1); if (gus->cur[d] >= gus->end[d]) { int diff = gus->cur[d] - gus->end[d]; if (gus->ctrl[d] & 8) { if (gus->ctrl[d] & 0x10) gus->ctrl[d] ^= 0x40; gus->cur[d] = (gus->ctrl[d] & 0x40) ? (gus->end[d] - diff) : (gus->start[d] + diff); } else if (!(gus->rctrl[d] & 4)) { gus->ctrl[d] |= 1; gus->cur[d] = (gus->ctrl[d] & 0x40) ? gus->end[d] : gus->start[d]; } if ((gus->ctrl[d] & 0x20) && !gus->waveirqs[d]) { gus->waveirqs[d] = 1; update_irqs = 1; } } } } if (!(gus->rctrl[d] & 3)) { if (gus->rctrl[d] & 0x40) { gus->rcur[d] -= gus->rfreq[d]; if (gus->rcur[d] <= gus->rstart[d]) { int diff = gus->rstart[d] - gus->rcur[d]; if (!(gus->rctrl[d] & 8)) { gus->rctrl[d] |= 1; gus->rcur[d] = (gus->rctrl[d] & 0x40) ? gus->rstart[d] : gus->rend[d]; } else { if (gus->rctrl[d] & 0x10) gus->rctrl[d] ^= 0x40; gus->rcur[d] = (gus->rctrl[d] & 0x40) ? (gus->rend[d] - diff) : (gus->rstart[d] + diff); } if ((gus->rctrl[d] & 0x20) && !gus->rampirqs[d]) { gus->rampirqs[d] = 1; update_irqs = 1; } } } else { gus->rcur[d] += gus->rfreq[d]; if (gus->rcur[d] >= gus->rend[d]) { int diff = gus->rcur[d] - gus->rend[d]; if (!(gus->rctrl[d] & 8)) { gus->rctrl[d] |= 1; gus->rcur[d] = (gus->rctrl[d] & 0x40) ? gus->rstart[d] : gus->rend[d]; } else { if (gus->rctrl[d] & 0x10) gus->rctrl[d] ^= 0x40; gus->rcur[d] = (gus->rctrl[d] & 0x40) ? (gus->rend[d] - diff) : (gus->rstart[d] + diff); } if ((gus->rctrl[d] & 0x20) && !gus->rampirqs[d]) { gus->rampirqs[d] = 1; update_irqs = 1; } } } } } if (update_irqs) gus_update_int_status(gus); } static void gus_get_buffer(int32_t *buffer, int len, void *priv) { gus_t *gus = (gus_t *) priv; #ifdef USE_GUSMAX if ((gus->type == GUS_MAX) && (gus->max_ctrl)) ad1848_update(&gus->ad1848); #endif /*USE_GUSMAX */ gus_update(gus); for (int c = 0; c < len * 2; c++) { #ifdef USE_GUSMAX if ((gus->type == GUS_MAX) && (gus->max_ctrl)) buffer[c] += (int32_t) (gus->ad1848.buffer[c] / 2); #endif /*USE_GUSMAX */ buffer[c] += (int32_t) gus->buffer[c & 1][c >> 1]; } #ifdef USE_GUSMAX if ((gus->type == GUS_MAX) && (gus->max_ctrl)) gus->ad1848.pos = 0; #endif /*USE_GUSMAX */ gus->pos = 0; } static void gus_input_msg(void *priv, uint8_t *msg, uint32_t len) { gus_t *gus = (gus_t *) priv; if (gus->sysex) return; if (gus->uart_in) { gus->midi_status |= MIDI_INT_RECEIVE; for (uint32_t i = 0; i < len; i++) { gus->midi_queue[gus->midi_w++] = msg[i]; gus->midi_w &= 63; } gus_midi_update_int_status(gus); } } static int gus_input_sysex(void *priv, uint8_t *buffer, uint32_t len, int abort) { gus_t *gus = (gus_t *) priv; if (abort) { gus->sysex = 0; return 0; } gus->sysex = 1; for (uint32_t i = 0; i < len; i++) { if (gus->midi_r == gus->midi_w) return (len - i); gus->midi_queue[gus->midi_w++] = buffer[i]; gus->midi_w &= 63; } gus->sysex = 0; return 0; } static void gus_reset(void *priv) { gus_t *gus = (gus_t *) priv; int c; double out = 1.0; if (gus == NULL) return; memset(gus->ram, 0x00, (gus->gus_end_ram)); for (c = 0; c < 32; c++) { gus->ctrl[c] = 1; gus->rctrl[c] = 1; gus->rfreq[c] = 63 * 512; } for (c = 4095; c >= 0; c--) { vol16bit[c] = out; out /= 1.002709201; /* 0.0235 dB Steps */ } gus->voices = 14; gus->samp_latch = (uint64_t) (TIMER_USEC * (1000000.0 / 44100.0)); gus->t1l = gus->t2l = 0xff; gus->global = 0; gus->addr = 0; gus->dmaaddr = 0; gus->voice = 0; memset(gus->start, 0x00, 32 * sizeof(uint32_t)); memset(gus->end, 0x00, 32 * sizeof(uint32_t)); memset(gus->cur, 0x00, 32 * sizeof(uint32_t)); memset(gus->startx, 0x00, 32 * sizeof(uint32_t)); memset(gus->endx, 0x00, 32 * sizeof(uint32_t)); memset(gus->curx, 0x00, 32 * sizeof(uint32_t)); memset(gus->rstart, 0x00, 32 * sizeof(int)); memset(gus->rend, 0x00, 32 * sizeof(int)); memset(gus->rcur, 0x00, 32 * sizeof(int)); memset(gus->freq, 0x00, 32 * sizeof(uint16_t)); memset(gus->curvol, 0x00, 32 * sizeof(int)); memset(gus->pan_l, 0x00, 32 * sizeof(int)); memset(gus->pan_r, 0x00, 32 * sizeof(int)); gus->t1on = 0; gus->t2on = 0; gus->tctrl = 0; gus->t1 = 0; gus->t2 = 0; gus->irqstatus = 0; gus->irqstatus2 = 0; gus->adcommand = 0; memset(gus->waveirqs, 0x00, 32 * sizeof(int)); memset(gus->rampirqs, 0x00, 32 * sizeof(int)); gus->dmactrl = 0; gus->uart_out = 1; gus->sb_2xa = 0; gus->sb_2xc = 0; gus->sb_2xe = 0; gus->sb_ctrl = 0; gus->sb_nmi = 0; gus->reg_ctrl = 0; gus->ad_status = 0; gus->ad_data = 0; gus->ad_timer_ctrl = 0; gus->midi_ctrl = 0; gus->midi_status = 0; memset(gus->midi_queue, 0x00, 64 * sizeof(uint8_t)); gus->midi_data = 0; gus->midi_r = 0; gus->midi_w = 0; gus->uart_in = 0; gus->uart_out = 0; gus->sysex = 0; gus->gp1 = 0; gus->gp2 = 0; gus->gp1_addr = 0; gus->gp2_addr = 0; gus->usrr = 0; #ifdef USE_GUSMAX gus->max_ctrl = 0; #endif /*USE_GUSMAX */ gus->irq_state = 0; gus->midi_irq_state = 0; gus_update_int_status(gus); } void * gus_init(UNUSED(const device_t *info)) { int c; double out = 1.0; uint8_t gus_ram = device_get_config_int("gus_ram"); gus_t *gus = malloc(sizeof(gus_t)); memset(gus, 0x00, sizeof(gus_t)); gus->gus_end_ram = 1 << (18 + gus_ram); gus->ram = (uint8_t *) malloc(gus->gus_end_ram); memset(gus->ram, 0x00, (gus->gus_end_ram)); for (c = 0; c < 32; c++) { gus->ctrl[c] = 1; gus->rctrl[c] = 1; gus->rfreq[c] = 63 * 512; } for (c = 4095; c >= 0; c--) { vol16bit[c] = out; out /= 1.002709201; /* 0.0235 dB Steps */ } gus->voices = 14; gus->samp_latch = (uint64_t) (TIMER_USEC * (1000000.0 / 44100.0)); gus->t1l = gus->t2l = 0xff; gus->uart_out = 1; gus->type = device_get_config_int("type"); gus->base = device_get_config_hex16("base"); io_sethandler(gus->base, 0x0010, readgus, NULL, NULL, writegus, NULL, NULL, gus); io_sethandler(0x0100 + gus->base, 0x0010, readgus, NULL, NULL, writegus, NULL, NULL, gus); io_sethandler(0x0506 + gus->base, 0x0001, readgus, NULL, NULL, writegus, NULL, NULL, gus); io_sethandler(0x0388, 0x0002, readgus, NULL, NULL, writegus, NULL, NULL, gus); #ifdef USE_GUSMAX if (gus->type == GUS_MAX) { ad1848_init(&gus->ad1848, AD1848_TYPE_CS4231); ad1848_setirq(&gus->ad1848, 5); ad1848_setdma(&gus->ad1848, 3); io_sethandler(0x10C + gus->base, 4, ad1848_read, NULL, NULL, ad1848_write, NULL, NULL, &gus->ad1848); } #endif /*USE_GUSMAX */ timer_add(&gus->samp_timer, gus_poll_wave, gus, 1); timer_add(&gus->timer_1, gus_poll_timer_1, gus, 1); timer_add(&gus->timer_2, gus_poll_timer_2, gus, 1); sound_add_handler(gus_get_buffer, gus); if (device_get_config_int("receive_input")) midi_in_handler(1, gus_input_msg, gus_input_sysex, gus); return gus; } void gus_close(void *priv) { gus_t *gus = (gus_t *) priv; free(gus->ram); free(gus); } void gus_speed_changed(void *priv) { gus_t *gus = (gus_t *) priv; if (gus->voices < 14) gus->samp_latch = (uint64_t) (TIMER_USEC * (1000000.0 / 44100.0)); else gus->samp_latch = (uint64_t) (TIMER_USEC * (1000000.0 / gusfreqs[gus->voices - 14])); #ifdef USE_GUSMAX if ((gus->type == GUS_MAX) && (gus->max_ctrl)) ad1848_speed_changed(&gus->ad1848); #endif /*USE_GUSMAX */ } static const device_config_t gus_config[] = { // clang-format off { .name = "type", .description = "GUS type", .type = CONFIG_SELECTION, .default_string = "", .default_int = 0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "Classic", .value = GUS_CLASSIC }, #ifdef USE_GUSMAX { .description = "MAX", .value = GUS_MAX }, #endif /*USE_GUSMAX */ { NULL } }, }, { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x220, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "210H", .value = 0x210 }, { .description = "220H", .value = 0x220 }, { .description = "230H", .value = 0x230 }, { .description = "240H", .value = 0x240 }, { .description = "250H", .value = 0x250 }, { .description = "260H", .value = 0x260 }, }, }, { .name = "gus_ram", "Onboard RAM", .type = CONFIG_SELECTION, .default_string = "", .default_int = 0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "256 KB", .value = 0 }, { .description = "512 KB", .value = 1 }, { .description = "1 MB", .value = 2 }, { NULL } } }, { .name = "receive_input", .description = "Receive input (SB MIDI)", .type = CONFIG_BINARY, .default_string = "", .default_int = 1 }, { .name = "", .description = "", .type = CONFIG_END } // clang-format off }; const device_t gus_device = { .name = "Gravis UltraSound", .internal_name = "gus", .flags = DEVICE_ISA | DEVICE_AT, .local = 0, .init = gus_init, .close = gus_close, .reset = gus_reset, { .available = NULL }, .speed_changed = gus_speed_changed, .force_redraw = NULL, .config = gus_config }; ```
/content/code_sandbox/src/sound/snd_gus.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
14,314
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * MIDI device core module. * * * * Authors: Miran Grca, <mgrca8@gmail.com> * Bit, * DOSBox Team, * */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/device.h> #include <86box/midi.h> #include <86box/plat.h> int midi_output_device_current = 0; static int midi_output_device_last = 0; int midi_input_device_current = 0; static int midi_input_device_last = 0; midi_t *midi_out = NULL; midi_t *midi_in = NULL; midi_in_handler_t *mih_first = NULL; midi_in_handler_t *mih_last = NULL; midi_in_handler_t *mih_cur = NULL; uint8_t MIDI_InSysexBuf[SYSEX_SIZE]; uint8_t MIDI_evt_len[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x80 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0x90 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xa0 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xb0 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xc0 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xd0 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* 0xe0 */ 0, 2, 3, 2, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0 /* 0xf0 */ }; typedef struct { const device_t *device; } MIDI_OUT_DEVICE, MIDI_IN_DEVICE; static const MIDI_OUT_DEVICE devices[] = { // clang-format off { &device_none }, #ifdef USE_FLUIDSYNTH { &fluidsynth_device }, #endif /* USE_FLUIDSYNTH */ #ifdef USE_MUNT { &mt32_old_device }, { &mt32_new_device }, { &cm32l_device }, { &cm32ln_device }, #endif /*USE_MUNT */ #ifdef USE_RTMIDI { &rtmidi_output_device }, #endif /* USE_RTMIDI */ #ifdef USE_OPL4ML { &opl4_midi_device }, #endif /* USE_OPL4ML */ { NULL } // clang-format on }; static const MIDI_IN_DEVICE midi_in_devices[] = { // clang-format off { &device_none }, #ifdef USE_RTMIDI { &rtmidi_input_device }, #endif /* USE_RTMIDI */ { NULL } // clang-format on }; int midi_out_device_available(int card) { if (devices[card].device) return device_available(devices[card].device); return 1; } const device_t * midi_out_device_getdevice(int card) { return devices[card].device; } int midi_out_device_has_config(int card) { if (!devices[card].device) return 0; return devices[card].device->config ? 1 : 0; } const char * midi_out_device_get_internal_name(int card) { return device_get_internal_name(devices[card].device); } int midi_out_device_get_from_internal_name(char *s) { int c = 0; while (devices[c].device != NULL) { if (!strcmp(devices[c].device->internal_name, s)) return c; c++; } return 0; } void midi_out_device_init(void) { if ((midi_output_device_current > 0) && devices[midi_output_device_current].device) device_add(devices[midi_output_device_current].device); midi_output_device_last = midi_output_device_current; } void midi_out_init(midi_device_t *device) { midi_out = (midi_t *) malloc(sizeof(midi_t)); memset(midi_out, 0, sizeof(midi_t)); midi_out->m_out_device = device; } void midi_in_init(midi_device_t *device, midi_t **mididev) { *mididev = (midi_t *) malloc(sizeof(midi_t)); memset(*mididev, 0, sizeof(midi_t)); (*mididev)->m_in_device = device; } void midi_out_close(void) { if (midi_out && midi_out->m_out_device) { free(midi_out->m_out_device); midi_out->m_out_device = NULL; } if (midi_out) { free(midi_out); midi_out = NULL; } } void midi_in_close(void) { if (midi_in && midi_in->m_in_device) { free(midi_in->m_in_device); midi_in->m_in_device = NULL; } if (midi_in) { free(midi_in); midi_in = NULL; } } void midi_poll(void) { if (midi_out && midi_out->m_out_device && midi_out->m_out_device->poll) midi_out->m_out_device->poll(); } void play_msg(uint8_t *msg) { if (midi_out->m_out_device->play_msg) midi_out->m_out_device->play_msg(msg); } void play_sysex(uint8_t *sysex, unsigned int len) { if (midi_out->m_out_device->play_sysex) midi_out->m_out_device->play_sysex(sysex, len); } int midi_in_device_available(int card) { if (midi_in_devices[card].device) return device_available(midi_in_devices[card].device); return 1; } const device_t * midi_in_device_getdevice(int card) { return midi_in_devices[card].device; } int midi_in_device_has_config(int card) { if (!midi_in_devices[card].device) return 0; return midi_in_devices[card].device->config ? 1 : 0; } const char * midi_in_device_get_internal_name(int card) { return device_get_internal_name(midi_in_devices[card].device); } int midi_in_device_get_from_internal_name(char *s) { int c = 0; while (midi_in_devices[c].device != NULL) { if (!strcmp(midi_in_devices[c].device->internal_name, s)) return c; c++; } return 0; } void midi_in_device_init(void) { if ((midi_input_device_current > 0) && midi_in_devices[midi_input_device_current].device) device_add(midi_in_devices[midi_input_device_current].device); midi_input_device_last = midi_input_device_current; } void midi_raw_out_rt_byte(uint8_t val) { if (!midi_in) return; if (!midi_in->midi_realtime) return; if (!midi_in->midi_clockout && (val == 0xf8)) return; midi_in->midi_cmd_r = val << 24; /* pclog("Play RT Byte msg\n"); */ play_msg((uint8_t *) &midi_in->midi_cmd_r); } void midi_raw_out_thru_rt_byte(uint8_t val) { if (midi_in && midi_in->thruchan) midi_raw_out_rt_byte(val); } void midi_raw_out_byte(uint8_t val) { uint32_t passed_ticks; if (!midi_out || !midi_out->m_out_device) return; if (midi_out->m_out_device->write && midi_out->m_out_device->write(val)) return; if (midi_out->midi_sysex_start) { passed_ticks = plat_get_ticks() - midi_out->midi_sysex_start; if (passed_ticks < midi_out->midi_sysex_delay) plat_delay_ms(midi_out->midi_sysex_delay - passed_ticks); } /* Test for a realtime MIDI message */ if (val >= 0xf8) { midi_out->midi_rt_buf[0] = val; play_msg(midi_out->midi_rt_buf); return; } /* Test for a active sysex transfer */ if (midi_out->midi_status == 0xf0) { if (!(val & 0x80)) { if (midi_out->midi_pos < (SYSEX_SIZE - 1)) midi_out->midi_sysex_data[midi_out->midi_pos++] = val; return; } else { midi_out->midi_sysex_data[midi_out->midi_pos++] = 0xf7; if ((midi_out->midi_sysex_start) && (midi_out->midi_pos >= 4) && (midi_out->midi_pos <= 9) && (midi_out->midi_sysex_data[1] == 0x41) && (midi_out->midi_sysex_data[3] == 0x16)) { /* pclog("MIDI: Skipping invalid MT-32 SysEx MIDI message\n"); */ } else { play_sysex(midi_out->midi_sysex_data, midi_out->midi_pos); if (midi_out->midi_sysex_start) { if (midi_out->midi_sysex_data[5] == 0x7f) midi_out->midi_sysex_delay = 290; /* All parameters reset */ else if ((midi_out->midi_sysex_data[5] == 0x10) && (midi_out->midi_sysex_data[6] == 0x00) && (midi_out->midi_sysex_data[7] == 0x04)) midi_out->midi_sysex_delay = 145; /* Viking Child */ else if ((midi_out->midi_sysex_data[5] == 0x10) && (midi_out->midi_sysex_data[6] == 0x00) && (midi_out->midi_sysex_data[7] == 0x01)) midi_out->midi_sysex_delay = 30; /* Dark Sun 1 */ else midi_out->midi_sysex_delay = (unsigned int) (((double) (midi_out->midi_pos) * 1.25) / 3.125) + 2; midi_out->midi_sysex_start = plat_get_ticks(); } } } } if (val & 0x80) { midi_out->midi_status = val; midi_out->midi_cmd_pos = 0; midi_out->midi_cmd_len = MIDI_evt_len[val]; if (midi_out->midi_status == 0xf0) { midi_out->midi_sysex_data[0] = 0xf0; midi_out->midi_pos = 1; } } if (midi_out->midi_cmd_len) { midi_out->midi_cmd_buf[midi_out->midi_cmd_pos++] = val; if (midi_out->midi_cmd_pos >= midi_out->midi_cmd_len) { play_msg(midi_out->midi_cmd_buf); midi_out->midi_cmd_pos = 1; } } } void midi_clear_buffer(void) { if (!midi_out) return; midi_out->midi_pos = 0; midi_out->midi_status = 0x00; midi_out->midi_cmd_pos = 0; midi_out->midi_cmd_len = 0; } void midi_in_handler(int set, void (*msg)(void *priv, uint8_t *msg, uint32_t len), int (*sysex)(void *priv, uint8_t *buffer, uint32_t len, int abort), void *priv) { midi_in_handler_t *temp = NULL; midi_in_handler_t *next; if (set) { /* Add MIDI IN handler. */ if ((mih_first == NULL) && (mih_last != NULL)) fatal("Last MIDI IN handler present with no first MIDI IN handler\n"); if ((mih_first != NULL) && (mih_last == NULL)) fatal("First MIDI IN handler present with no last MIDI IN handler\n"); temp = (midi_in_handler_t *) malloc(sizeof(midi_in_handler_t)); memset(temp, 0, sizeof(midi_in_handler_t)); temp->msg = msg; temp->sysex = sysex; temp->priv = priv; if (mih_last == NULL) mih_first = mih_last = temp; else { temp->prev = mih_last; mih_last = temp; } } else if ((mih_first != NULL) && (mih_last != NULL)) { temp = mih_first; while (1) { if (temp == NULL) break; if ((temp->msg == msg) && (temp->sysex == sysex) && (temp->priv == priv)) { if (temp->prev != NULL) temp->prev->next = temp->next; if (temp->next != NULL) temp->next->prev = temp->prev; next = temp->next; if (temp == mih_first) { mih_first = NULL; if (next == NULL) mih_last = NULL; } if (temp == mih_last) mih_last = NULL; free(temp); temp = next; if (next == NULL) break; } } } } void midi_in_handlers_clear(void) { midi_in_handler_t *temp = mih_first; midi_in_handler_t *next; while (1) { if (temp == NULL) break; next = temp->next; free(temp); temp = next; if (next == NULL) break; } mih_first = mih_last = NULL; } void midi_in_msg(uint8_t *msg, uint32_t len) { midi_in_handler_t *temp = mih_first; while (1) { if (temp == NULL) break; if (temp->msg) temp->msg(temp->priv, msg, len); temp = temp->next; if (temp == NULL) break; } } static void midi_start_sysex(uint8_t *buffer, uint32_t len) { midi_in_handler_t *temp = mih_first; while (1) { if (temp == NULL) break; temp->cnt = 5; temp->buf = buffer; temp->len = len; temp = temp->next; if (temp == NULL) break; } } /* Returns: 0 = All handlers have returnd 0; 1 = There are still handlers to go. */ static int midi_do_sysex(void) { midi_in_handler_t *temp = mih_first; int ret; int cnt_acc = 0; while (1) { if (temp == NULL) break; /* Do nothing if the handler has a zero count. */ if ((temp->cnt > 0) || (temp->len > 0)) { ret = 0; if (temp->sysex) { if (temp->cnt == 0) ret = temp->sysex(temp->priv, temp->buf, 0, 0); else ret = temp->sysex(temp->priv, temp->buf, temp->len, 0); } /* If count is 0 and length is 0, then this is just a finishing call to temp->sysex(), so skip this entire block. */ if (temp->cnt > 0) { if (ret) { /* Decrease or reset the counter. */ if (temp->len == ret) temp->cnt--; else temp->cnt = 5; /* Advance the buffer pointer and remember the remaining length. */ temp->buf += (temp->len - ret); temp->len = ret; } else { /* Set count to 0 so that this handler will be ignored on the next interation. */ temp->cnt = 0; /* Reset the buffer pointer and length. */ temp->buf = NULL; temp->len = 0; } /* If the remaining count is above zero, add it to the accumulator. */ if (temp->cnt > 0) cnt_acc |= temp->cnt; } } temp = temp->next; if (temp == NULL) break; } /* Return 0 if all handlers have returned 0 or all the counts are otherwise 0. */ if (cnt_acc == 0) return 0; else return 1; } void midi_in_sysex(uint8_t *buffer, uint32_t len) { midi_start_sysex(buffer, len); while (1) { /* This will return 0 if all theh handlers have either timed out or otherwise indicated it is time to stop. */ if (midi_do_sysex()) plat_delay_ms(5); /* msec */ else break; } } void midi_reset(void) { if (midi_out && midi_out->m_out_device && midi_out->m_out_device->reset) midi_out->m_out_device->reset(); } ```
/content/code_sandbox/src/sound/midi.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
4,585
```c /* * 86Box A hypervisor and IBM PC system emulator that specializes in * running old operating systems and software designed for IBM * PC systems and compatibles from 1981 through fairly recent * system designs based on the PCI bus. * * This file is part of the 86Box distribution. * * Emulation of the PC speaker. * * * * Authors: Sarah Walker, <path_to_url * Miran Grca, <mgrca8@gmail.com> * */ #include <stdint.h> #include <stdio.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/timer.h> #include <86box/pit.h> #include <86box/snd_speaker.h> #include <86box/sound.h> #include <86box/plat_unused.h> int speaker_mute = 0; int speaker_gated = 0; int speaker_enable = 0; int was_speaker_enable = 0; int gated; int speakval; int speakon; static int32_t speaker_buffer[SOUNDBUFLEN]; static int speaker_pos = 0; static uint8_t speaker_mode = 0; static double speaker_count = 65535.0; void speaker_set_count(uint8_t new_m, int new_count) { speaker_mode = new_m; speaker_count = (double) new_count; } void speaker_update(void) { int32_t val; double amplitude; amplitude = ((speaker_count / 64.0) * 10240.0) - 5120.0; if (amplitude > 5120.0) amplitude = 5120.0; if (speaker_pos < sound_pos_global) { for (; speaker_pos < sound_pos_global; speaker_pos++) { if (speaker_gated && was_speaker_enable) { if ((speaker_mode == 0) || (speaker_mode == 4)) val = (int32_t) amplitude; else if (speaker_count < 64.0) val = 0xa00; else val = speakon ? 0x1400 : 0; } else { if (speaker_mode == 1) val = was_speaker_enable ? (int32_t) amplitude : 0; else val = was_speaker_enable ? 0x1400 : 0; } if (!speaker_enable) was_speaker_enable = 0; speaker_buffer[speaker_pos] = val; } } } void speaker_get_buffer(int32_t *buffer, int len, UNUSED(void *priv)) { double val_l, val_r; speaker_update(); if (!speaker_mute) { for (int c = 0; c < len * 2; c += 2) { val_l = val_r = (double) speaker_buffer[c >> 1]; /* Apply PC speaker volume and filters */ if (filter_pc_speaker != NULL) { filter_pc_speaker(0, &val_l, filter_pc_speaker_p); filter_pc_speaker(1, &val_r, filter_pc_speaker_p); } buffer[c] += (int32_t) val_l; buffer[c + 1] += (int32_t) val_r; } } speaker_pos = 0; } void speaker_init(void) { memset(speaker_buffer, 0, sizeof(speaker_buffer)); sound_add_handler(speaker_get_buffer, NULL); speaker_mute = 0; } ```
/content/code_sandbox/src/sound/snd_speaker.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
778
```objective-c /* * RoboPlay for MSX * * yrw801.h */ /* Cacodemon345: Added pointer structs from Linux */ #pragma once #include <stdint.h> typedef struct { uint16_t tone; int16_t pitch_offset; uint8_t key_scaling; int8_t panpot; uint8_t vibrato; uint8_t tone_attenuate; uint8_t volume_factor; uint8_t reg_lfo_vibrato; uint8_t reg_attack_decay1; uint8_t reg_level_decay2; uint8_t reg_release_correction; uint8_t reg_tremolo; } YRW801_WAVE_DATA; typedef struct { uint8_t key_min; uint8_t key_max; YRW801_WAVE_DATA wave_data; } YRW801_REGION_DATA; typedef struct { int count; const YRW801_REGION_DATA* regions; } YRW801_REGION_DATA_PTR; extern const YRW801_REGION_DATA_PTR snd_yrw801_regions[0x81]; ```
/content/code_sandbox/src/sound/yrw801.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
238
```c #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include <86box/86box.h> #include <86box/device.h> #include <86box/dma.h> #include <86box/io.h> #include <86box/pic.h> #include <86box/sound.h> #include <86box/snd_sn76489.h> #include <86box/timer.h> #include <86box/plat_unused.h> typedef struct pssj_t { sn76489_t sn76489; uint8_t ctrl; uint8_t wave; uint8_t dac_val; uint16_t freq; int amplitude; int irq; pc_timer_t timer_count; int enable; int wave_pos; int pulse_width; int16_t buffer[SOUNDBUFLEN]; int pos; } pssj_t; static void pssj_update_irq(pssj_t *pssj) { if (pssj->irq && (pssj->ctrl & 0x10) && (pssj->ctrl & 0x08)) picint(1 << 7); } static void pssj_write(uint16_t port, uint8_t val, void *priv) { pssj_t *pssj = (pssj_t *) priv; switch (port & 3) { case 0: pssj->ctrl = val; if (!pssj->enable && ((val & 4) && (pssj->ctrl & 3))) timer_set_delay_u64(&pssj->timer_count, (TIMER_USEC * (1000000.0 / 3579545.0) * (double) (pssj->freq ? pssj->freq : 0x400))); pssj->enable = (val & 4) && (pssj->ctrl & 3); if (!pssj->enable) timer_disable(&pssj->timer_count); sn74689_set_extra_divide(&pssj->sn76489, val & 0x40); if (!(val & 8)) pssj->irq = 0; pssj_update_irq(pssj); break; case 1: switch (pssj->ctrl & 3) { case 1: /*Sound channel*/ pssj->wave = val; pssj->pulse_width = val & 7; break; case 3: /*Direct DAC*/ pssj->dac_val = val; break; default: break; } break; case 2: pssj->freq = (pssj->freq & 0xf00) | val; break; case 3: pssj->freq = (pssj->freq & 0x0ff) | ((val & 0xf) << 8); pssj->amplitude = val >> 4; break; default: break; } } static uint8_t pssj_read(uint16_t port, void *priv) { const pssj_t *pssj = (pssj_t *) priv; switch (port & 3) { case 0: return (pssj->ctrl & ~0x88) | (pssj->irq ? 8 : 0); case 1: switch (pssj->ctrl & 3) { case 0: /*Joystick*/ return 0; case 1: /*Sound channel*/ return pssj->wave; case 2: /*Successive approximation*/ return 0x80; case 3: /*Direct DAC*/ return pssj->dac_val; default: break; } break; case 2: return pssj->freq & 0xff; case 3: return (pssj->freq >> 8) | (pssj->amplitude << 4); default: return 0xff; } return 0xff; } static void pssj_update(pssj_t *pssj) { for (; pssj->pos < sound_pos_global; pssj->pos++) pssj->buffer[pssj->pos] = (((int8_t) (pssj->dac_val ^ 0x80) * 0x20) * pssj->amplitude) / 15; } static void pssj_callback(void *priv) { pssj_t *pssj = (pssj_t *) priv; int data; pssj_update(pssj); if (pssj->ctrl & 2) { if ((pssj->ctrl & 3) == 3) { data = dma_channel_read(1); if (data != DMA_NODATA) { pssj->dac_val = data & 0xff; } } else { data = dma_channel_write(1, 0x80); } if ((data & DMA_OVER) && data != DMA_NODATA) { if (pssj->ctrl & 0x08) { pssj->irq = 1; pssj_update_irq(pssj); } } } else { switch (pssj->wave & 0xc0) { case 0x00: /*Pulse*/ pssj->dac_val = (pssj->wave_pos > (pssj->pulse_width << 1)) ? 0xff : 0; break; case 0x40: /*Ramp*/ pssj->dac_val = pssj->wave_pos << 3; break; case 0x80: /*Triangle*/ if (pssj->wave_pos & 16) pssj->dac_val = (pssj->wave_pos ^ 31) << 4; else pssj->dac_val = pssj->wave_pos << 4; break; case 0xc0: pssj->dac_val = 0x80; break; default: break; } pssj->wave_pos = (pssj->wave_pos + 1) & 31; } timer_advance_u64(&pssj->timer_count, (TIMER_USEC * (1000000.0 / 3579545.0) * (double) (pssj->freq ? pssj->freq : 0x400))); } static void pssj_get_buffer(int32_t *buffer, int len, void *priv) { pssj_t *pssj = (pssj_t *) priv; pssj_update(pssj); for (int c = 0; c < len * 2; c++) buffer[c] += pssj->buffer[c >> 1]; pssj->pos = 0; } void * pssj_init(UNUSED(const device_t *info)) { pssj_t *pssj = malloc(sizeof(pssj_t)); memset(pssj, 0, sizeof(pssj_t)); sn76489_init(&pssj->sn76489, 0x00c0, 0x0004, PSSJ, 3579545); io_sethandler(0x00C4, 0x0004, pssj_read, NULL, NULL, pssj_write, NULL, NULL, pssj); timer_add(&pssj->timer_count, pssj_callback, pssj, pssj->enable); sound_add_handler(pssj_get_buffer, pssj); return pssj; } void * pssj_1e0_init(UNUSED(const device_t *info)) { pssj_t *pssj = malloc(sizeof(pssj_t)); memset(pssj, 0, sizeof(pssj_t)); sn76489_init(&pssj->sn76489, 0x01e0, 0x0004, PSSJ, 3579545); io_sethandler(0x01E4, 0x0004, pssj_read, NULL, NULL, pssj_write, NULL, NULL, pssj); timer_add(&pssj->timer_count, pssj_callback, pssj, pssj->enable); sound_add_handler(pssj_get_buffer, pssj); return pssj; } void * pssj_isa_init(UNUSED(const device_t *info)) { pssj_t *pssj = malloc(sizeof(pssj_t)); memset(pssj, 0, sizeof(pssj_t)); uint16_t addr = device_get_config_hex16("base"); sn76489_init(&pssj->sn76489, addr, 0x0004, PSSJ, 3579545); io_sethandler(addr + 0x04, 0x0004, pssj_read, NULL, NULL, pssj_write, NULL, NULL, pssj); timer_add(&pssj->timer_count, pssj_callback, pssj, pssj->enable); sound_add_handler(pssj_get_buffer, pssj); return pssj; } void pssj_close(void *priv) { pssj_t *pssj = (pssj_t *) priv; free(pssj); } static const device_config_t pssj_isa_config[] = { // clang-format off { .name = "base", .description = "Address", .type = CONFIG_HEX16, .default_string = "", .default_int = 0x2C0, .file_filter = "", .spinner = { 0 }, .selection = { { .description = "0x0C0", .value = 0x0C0 }, { .description = "0x0E0", .value = 0x0E0 }, { .description = "0x1C0", .value = 0x1C0 }, { .description = "0x1E0", .value = 0x1E0 }, { .description = "0x2C0", .value = 0x2C0 }, { .description = "0x2E0", .value = 0x2E0 }, { .description = "" } } }, { .name = "", .description = "", .type = CONFIG_END } // clang-format on }; const device_t pssj_device = { .name = "Tandy PSSJ", .internal_name = "pssj", .flags = 0, .local = 0, .init = pssj_init, .close = pssj_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; const device_t pssj_1e0_device = { .name = "Tandy PSSJ (port 1e0h)", .internal_name = "pssj_1e0", .flags = 0, .local = 0, .init = pssj_1e0_init, .close = pssj_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = NULL }; const device_t pssj_isa_device = { .name = "Tandy PSSJ Clone", .internal_name = "pssj_isa", .flags = DEVICE_ISA, .local = 0, .init = pssj_isa_init, .close = pssj_close, .reset = NULL, { .available = NULL }, .speed_changed = NULL, .force_redraw = NULL, .config = pssj_isa_config }; ```
/content/code_sandbox/src/sound/snd_pssj.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,747
```c /* * ESFMu: emulator for the ESS "ESFM" enhanced OPL3 clone * * This file includes code and data from the Nuked OPL3 project, copyright (C) * 2013-2023 Nuke.YKT. Its usage, modification and redistribution is allowed * later. * * ESFMu is free software: you can redistribute it and/or modify * published by the Free Software Foundation, either version 2.1 * * ESFMu is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with ESFMu. If not, see <path_to_url */ /* * ESFMu wouldn't have been possible without the hard work and dedication of * the retro computer hardware research and preservation community. * * I'd like to thank: * - Nuke.YKT * Developer of Nuked OPL3, which was the basis for ESFMu's code and * also a great learning resource on Yamaha FM synthesis for myself. * Nuke.YKT also gives shoutouts on behalf of Nuked OPL3 to: * - MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): * Feedback and Rhythm part calculation information. * - forums.submarine.org.uk(carbon14, opl3): * Tremolo and phase generator calculation information. * - OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): * OPL2 ROMs. * - siliconpr0n.org(John McMaster, digshadow): * YMF262 and VRC VII decaps and die shots. * - rainwarrior * For performing the initial research on ESFM drivers and documenting * ESS's patent on native mode operator organization. * - jwt27 * For kickstarting the ESFM research project and compiling rainwarrior's * findings and more in an accessible document ("ESFM Demystified"). * - pachuco/CatButts * For documenting ESS's patent on ESFM's feedback implementation, which * was vital in getting ESFMu's sound output to be accurate. * - And everybody who helped out with real hardware testing */ #include "esfm.h" #include <stdlib.h> #include <stddef.h> #include <string.h> #include <stdbool.h> /* * Table of KSL values extracted from OPL3 ROM; taken straight from Nuked OPL3 * source code. * TODO: Check if ESFM uses the same KSL values. */ static const int16 kslrom[16] = { 0, 32, 40, 45, 48, 51, 53, 55, 56, 58, 59, 60, 61, 62, 63, 64 }; /* * This maps the low 5 bits of emulation mode address to an emulation mode * slot; taken straight from Nuked OPL3. Used for decoding certain emulation * mode address ranges. */ static const int8_t ad_slot[0x20] = { 0, 1, 2, 3, 4, 5, -1, -1, 6, 7, 8, 9, 10, 11, -1, -1, 12, 13, 14, 15, 16, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; /* * This maps an emulation mode slot index to a tuple representing the * corresponding native mode channel and slot. */ static const emu_slot_channel_mapping emu_slot_map[36] = { { 0, 0}, { 1, 0}, { 2, 0}, { 0, 1}, { 1, 1}, { 2, 1}, { 3, 0}, { 4, 0}, { 5, 0}, { 3, 1}, { 4, 1}, { 5, 1}, { 6, 0}, { 7, 0}, { 8, 0}, { 6, 1}, { 7, 1}, { 8, 1}, { 9, 0}, {10, 0}, {11, 0}, { 9, 1}, {10, 1}, {11, 1}, {12, 0}, {13, 0}, {14, 0}, {12, 1}, {13, 1}, {14, 1}, {15, 0}, {16, 0}, {17, 0}, {15, 1}, {16, 1}, {17, 1} }; /* * This encodes which emulation mode channels are the secondary channel in a * 4-op channel pair (where the entry is non-negative), and which is the * corresponding primary channel for that secondary channel. */ static const int emu_4op_secondary_to_primary[18] = { -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, 9, 10, 11, -1, -1, -1 }; /* * This encodes the operator outputs to be enabled or disabled for * each 4-op algorithm in emulation mode. * Indices: FM+FM, FM+AM, AM+FM, AM+AM (lower channel MSB, upper channel LSB) * Values: enable OP1, OP2, OP3, OP4 */ static const bool emu_4op_alg_output_enable[4][4] = { {0, 0, 0, 1}, {0, 1, 0, 1}, {1, 0, 0, 1}, {1, 0, 1, 1} }; /* * This encodes the operator interconnections to be enabled or disabled for * each 4-op algorithm in emulation mode. * Indices: FM+FM, FM+AM, AM+FM, AM+AM (lower channel MSB, upper channel LSB) * Values: enable OP1FB, OP1->2, OP2->3, OP3->4 */ static const bool emu_4op_alg_mod_enable[4][4] = { {1, 1, 1, 1}, {1, 1, 0, 1}, {1, 0, 1, 1}, {1, 0, 1, 0} }; /* your_sha256_hash--------- */ static void ESFM_emu_rearrange_connections(esfm_channel *channel) { int secondary_to_primary; secondary_to_primary = emu_4op_secondary_to_primary[channel->channel_idx]; if (secondary_to_primary >= 0) { esfm_channel *pair_primary = &channel->chip->channels[secondary_to_primary]; if (pair_primary->emu_mode_4op_enable) { // always work from primary channel in pair when dealing with 4-op channel = pair_primary; } } if (channel->emu_mode_4op_enable && (channel->channel_idx % 9) < 3 && channel->chip->emu_newmode) { esfm_channel *secondary = &channel->chip->channels[channel->channel_idx + 3]; uint2 algorithm = ((channel->slots[0].emu_connection_typ != 0) << 1) | (secondary->slots[0].emu_connection_typ != 0); int i; secondary->slots[0].in.mod_input = &channel->slots[1].in.output; for (i = 0; i < 2; i++) { channel->slots[i].in.emu_mod_enable = emu_4op_alg_mod_enable[algorithm][i] ? ~((int13) 0) : 0; channel->slots[i].in.emu_output_enable = emu_4op_alg_output_enable[algorithm][i] ? ~((int13) 0) : 0; secondary->slots[i].in.emu_mod_enable = emu_4op_alg_mod_enable[algorithm][i + 2] ? ~((int13) 0) : 0; secondary->slots[i].in.emu_output_enable = emu_4op_alg_output_enable[algorithm][i + 2] ? ~((int13) 0) : 0; } } else if ((channel->chip->emu_rhy_mode_flags & 0x20) != 0 && (channel->channel_idx == 7 || channel->channel_idx == 8)) { channel->slots[0].in.emu_mod_enable = 0; channel->slots[1].in.emu_mod_enable = 0; channel->slots[0].in.emu_output_enable = ~((int13) 0); channel->slots[1].in.emu_output_enable = ~((int13) 0); } else { channel->slots[0].in.mod_input = &channel->slots[0].in.feedback_buf; channel->slots[0].in.emu_mod_enable = ~((int13) 0); channel->slots[0].in.emu_output_enable = (channel->slots[0].emu_connection_typ != 0) ? ~((int13) 0) : 0; channel->slots[1].in.emu_output_enable = ~((int13) 0); channel->slots[1].in.emu_mod_enable = (channel->slots[0].emu_connection_typ != 0) ? 0 : ~((int13) 0); } } /* your_sha256_hash--------- */ static void ESFM_emu_to_native_switch(esfm_chip *chip) { size_t channel_idx, slot_idx; for (channel_idx = 0; channel_idx < 18; channel_idx++) { for (slot_idx = 0; slot_idx < 4; slot_idx++) { esfm_channel *channel = &chip->channels[channel_idx]; esfm_slot *slot = &channel->slots[slot_idx]; if (slot_idx == 0) { slot->in.mod_input = &slot->in.feedback_buf; } else { esfm_slot *prev_slot = &channel->slots[slot_idx - 1]; slot->in.mod_input = &prev_slot->in.output; } } } } /* your_sha256_hash--------- */ static void ESFM_native_to_emu_switch(esfm_chip *chip) { size_t channel_idx; for (channel_idx = 0; channel_idx < 18; channel_idx++) { ESFM_emu_rearrange_connections(&chip->channels[channel_idx]); } } /* your_sha256_hash--------- */ static void ESFM_slot_update_keyscale(esfm_slot *slot) { if (slot->slot_idx > 0 && !slot->chip->native_mode) { return; } int16 ksl = (kslrom[slot->f_num >> 6] << 2) - ((0x08 - slot->block) << 5); if (ksl < 0) { ksl = 0; } slot->in.eg_ksl_offset = ksl; slot->in.keyscale = (slot->block << 1) | ((slot->f_num >> (8 + !slot->chip->keyscale_mode)) & 0x01); } /* your_sha256_hash--------- */ static void ESFM_emu_channel_update_keyscale(esfm_channel *channel) { int secondary_to_primary; secondary_to_primary = emu_4op_secondary_to_primary[channel->channel_idx]; if (secondary_to_primary >= 0) { esfm_channel *pair_primary = &channel->chip->channels[secondary_to_primary]; if (pair_primary->emu_mode_4op_enable) { // always work from primary channel in pair when dealing with 4-op channel = pair_primary; } } ESFM_slot_update_keyscale(&channel->slots[0]); channel->slots[1].in.eg_ksl_offset = channel->slots[0].in.eg_ksl_offset; channel->slots[1].in.keyscale = channel->slots[0].in.keyscale; if (channel->emu_mode_4op_enable && (channel->channel_idx % 9) < 3 && channel->chip->emu_newmode) { int i; esfm_channel *secondary = &channel->chip->channels[channel->channel_idx + 3]; secondary->slots[0].f_num = channel->slots[0].f_num; secondary->slots[0].block = channel->slots[0].block; for (i = 0; i < 2; i++) { secondary->slots[i].in.eg_ksl_offset = channel->slots[0].in.eg_ksl_offset; secondary->slots[i].in.keyscale = channel->slots[0].in.keyscale; } } } /* your_sha256_hash--------- */ static inline uint8_t ESFM_slot_readback (esfm_slot *slot, uint8_t register_idx) { uint8_t data = 0; switch (register_idx & 0x07) { case 0x00: data |= (slot->tremolo_en != 0) << 7; data |= (slot->vibrato_en != 0) << 6; data |= (slot->env_sustaining != 0) << 5; data |= (slot->vibrato_en != 0) << 4; data |= slot->mult & 0x0f; break; case 0x01: data |= slot->ksl << 6; data |= slot->t_level & 0x3f; break; case 0x02: data |= slot->attack_rate << 4; data |= slot->decay_rate & 0x0f; break; case 0x03: data |= slot->sustain_lvl << 4; data |= slot->release_rate & 0x0f; break; case 0x04: data = slot->f_num & 0xff; break; case 0x05: data |= slot->env_delay << 5; data |= (slot->block & 0x07) << 2; data |= (slot->f_num >> 8) & 0x03; break; case 0x06: data |= (slot->tremolo_deep != 0) << 7; data |= (slot->vibrato_deep != 0) << 6; data |= (slot->out_enable[1] != 0) << 5; data |= (slot->out_enable[0] != 0) << 4; data |= (slot->mod_in_level & 0x07) << 1; data |= slot->emu_connection_typ & 0x01; break; case 0x07: data |= slot->output_level << 5; data |= (slot->rhy_noise & 0x03) << 3; data |= slot->waveform & 0x07; break; } return data; } /* your_sha256_hash--------- */ static inline void ESFM_slot_write (esfm_slot *slot, uint8_t register_idx, uint8_t data) { switch (register_idx & 0x07) { case 0x00: slot->tremolo_en = (data & 0x80) != 0; slot->vibrato_en = (data & 0x40) != 0; slot->env_sustaining = (data & 0x20) != 0; slot->ksr = (data & 0x10) != 0; slot->mult = data & 0x0f; break; case 0x01: slot->ksl = data >> 6; slot->t_level = data & 0x3f; ESFM_slot_update_keyscale(slot); break; case 0x02: slot->attack_rate = data >> 4; slot->decay_rate = data & 0x0f; break; case 0x03: slot->sustain_lvl = data >> 4; slot->release_rate = data & 0x0f; break; case 0x04: slot->f_num = (slot->f_num & 0x300) | data; ESFM_slot_update_keyscale(slot); break; case 0x05: if (slot->env_delay < (data >> 5)) { slot->in.eg_delay_transitioned_01 = 1; } else if (slot->env_delay > (data >> 5)) { slot->in.eg_delay_transitioned_10 = 1; } slot->env_delay = data >> 5; slot->emu_key_on = (data >> 5) & 0x01; slot->block = (data >> 2) & 0x07; slot->f_num = (slot->f_num & 0xff) | ((data & 0x03) << 8); ESFM_slot_update_keyscale(slot); break; case 0x06: slot->tremolo_deep = (data & 0x80) != 0; slot->vibrato_deep = (data & 0x40) != 0; slot->out_enable[1] = (data & 0x20) ? ~((int13) 0) : 0; slot->out_enable[0] = (data & 0x10) ? ~((int13) 0) : 0; slot->mod_in_level = (data >> 1) & 0x07; slot->emu_connection_typ = data & 0x01; break; case 0x07: slot->output_level = data >> 5; slot->rhy_noise = (data >> 3) & 0x03; slot->waveform = data & 0x07; break; } } #define KEY_ON_REGS_START (18 * 4 * 8) #define TIMER1_REG (0x402) #define TIMER2_REG (0x403) #define TIMER_SETUP_REG (0x404) #define CONFIG_REG (0x408) #define BASSDRUM_REG (0x4bd) #define TEST_REG (0x501) #define FOUROP_CONN_REG (0x504) #define NATIVE_MODE_REG (0x505) /* your_sha256_hash--------- */ static void ESFM_write_reg_native (esfm_chip *chip, uint16_t address, uint8_t data) { int i; address = address & 0x7ff; if (address < KEY_ON_REGS_START) { // Slot register write size_t channel_idx = address >> 5; size_t slot_idx = (address >> 3) & 0x03; size_t register_idx = address & 0x07; esfm_slot *slot = &chip->channels[channel_idx].slots[slot_idx]; ESFM_slot_write(slot, register_idx, data); } else if (address < KEY_ON_REGS_START + 16) { // Key-on registers size_t channel_idx = (address - KEY_ON_REGS_START); esfm_channel *channel = &chip->channels[channel_idx]; channel->key_on = data & 0x01; channel->emu_mode_4op_enable = (data & 0x02) != 0; } else if (address < KEY_ON_REGS_START + 20) { // Key-on channels 17 and 18 (each half) size_t channel_idx = 16 + ((address & 0x02) >> 1); bool second_half = address & 0x01; esfm_channel *channel = &chip->channels[channel_idx]; if (second_half) { channel->key_on_2 = data & 0x01; channel->emu_mode_4op_enable_2 = (data & 0x02) != 0; } else { channel->key_on = data & 0x01; channel->emu_mode_4op_enable = (data & 0x02) != 0; } } else { switch (address & 0x5ff) { case TIMER1_REG: chip->timer_reload[0] = data; chip->timer_counter[0] = data; break; case TIMER2_REG: chip->timer_reload[1] = data; chip->timer_counter[1] = data; break; case TIMER_SETUP_REG: if (data & 0x80) { chip->irq_bit = 0; chip->timer_overflow[0] = 0; chip->timer_overflow[1] = 0; break; } chip->timer_enable[0] = (data & 0x01) != 0; chip->timer_enable[1] = (data & 0x02) != 0; chip->timer_mask[1] = (data & 0x20) != 0; chip->timer_mask[0] = (data & 0x40) != 0; break; case CONFIG_REG: chip->keyscale_mode = (data & 0x40) != 0; break; case BASSDRUM_REG: chip->emu_rhy_mode_flags = data & 0x3f; chip->emu_vibrato_deep = (data & 0x40) != 0; chip->emu_tremolo_deep = (data & 0x80) != 0; break; case FOUROP_CONN_REG: for (i = 0; i < 3; i++) { chip->channels[i].emu_mode_4op_enable = (data >> i) & 0x01; chip->channels[i + 9].emu_mode_4op_enable = (data >> (i + 3)) & 0x01; } break; case TEST_REG: chip->test_bit_w0_r5_eg_halt = (data & 0x01) | ((data & 0x20) != 0); chip->test_bit_1_distort = (data & 0x02) != 0; chip->test_bit_2 = (data & 0x04) != 0; chip->test_bit_3 = (data & 0x08) != 0; chip->test_bit_4_attenuate = (data & 0x10) != 0; chip->test_bit_w5_r0 = (data & 0x20) != 0; chip->test_bit_6_phase_stop_reset = (data & 0x40) != 0; chip->test_bit_7 = (data & 0x80) != 0; break; } } } /* your_sha256_hash--------- */ static uint8_t ESFM_readback_reg_native (esfm_chip *chip, uint16_t address) { int i; uint8_t data = 0; address = address & 0x7ff; if (address < KEY_ON_REGS_START) { // Slot register read size_t channel_idx = address >> 5; size_t slot_idx = (address >> 3) & 0x03; size_t register_idx = address & 0x07; esfm_slot *slot = &chip->channels[channel_idx].slots[slot_idx]; data = ESFM_slot_readback(slot, register_idx); } else if (address < KEY_ON_REGS_START + 16) { // Key-on registers size_t channel_idx = (address - KEY_ON_REGS_START); esfm_channel *channel = &chip->channels[channel_idx]; data |= channel->key_on != 0; data |= (channel->emu_mode_4op_enable != 0) << 1; } else if (address < KEY_ON_REGS_START + 20) { // Key-on channels 17 and 18 (each half) size_t channel_idx = 16 + ((address & 0x02) >> 1); bool second_half = address & 0x01; esfm_channel *channel = &chip->channels[channel_idx]; if (second_half) { data |= channel->key_on_2 != 0; data |= (channel->emu_mode_4op_enable_2 != 0) << 1; } else { data |= channel->key_on != 0; data |= (channel->emu_mode_4op_enable != 0) << 1; } } else { switch (address & 0x5ff) { case TIMER1_REG: data = chip->timer_counter[0]; break; case TIMER2_REG: data = chip->timer_counter[1]; break; case TIMER_SETUP_REG: data |= chip->timer_enable[0] != 0; data |= (chip->timer_enable[1] != 0) << 1; data |= (chip->timer_mask[1] != 0) << 5; data |= (chip->timer_mask[0] != 0) << 6; break; case CONFIG_REG: data |= (chip->keyscale_mode != 0) << 6; break; case BASSDRUM_REG: data |= chip->emu_rhy_mode_flags; data |= chip->emu_vibrato_deep << 6; data |= chip->emu_tremolo_deep << 7; break; case TEST_REG: data |= chip->test_bit_w5_r0 != 0; data |= (chip->test_bit_1_distort != 0) << 1; data |= (chip->test_bit_2 != 0) << 2; data |= (chip->test_bit_3 != 0) << 3; data |= (chip->test_bit_4_attenuate != 0) << 4; data |= (chip->test_bit_w0_r5_eg_halt != 0) << 5; data |= (chip->test_bit_6_phase_stop_reset != 0) << 6; data |= (chip->test_bit_7 != 0) << 7; break; case FOUROP_CONN_REG: for (i = 0; i < 3; i++) { data |= (chip->channels[i].emu_mode_4op_enable != 0) << i; data |= (chip->channels[i + 9].emu_mode_4op_enable != 0) << (i + 3); } break; case NATIVE_MODE_REG: data |= (chip->emu_newmode != 0); data |= (chip->native_mode != 0) << 7; break; } } return data; } /* your_sha256_hash--------- */ static void ESFM_write_reg_emu (esfm_chip *chip, uint16_t address, uint8_t data) { bool high = (address & 0x100) != 0; uint8_t reg = address & 0xff; int emu_slot_idx = ad_slot[address & 0x1f]; int natv_chan_idx = -1; int natv_slot_idx = -1; int emu_chan_idx = (reg & 0x0f) > 8 ? -1 : ((reg & 0x0f) + high * 9); if (emu_slot_idx >= 0) { if (high) { emu_slot_idx += 18; } natv_chan_idx = emu_slot_map[emu_slot_idx].channel_idx; natv_slot_idx = emu_slot_map[emu_slot_idx].slot_idx; } if (reg == 0xbd) { chip->emu_rhy_mode_flags = data & 0x3f; chip->emu_vibrato_deep = (data & 0x40) != 0; chip->emu_tremolo_deep = (data & 0x80) != 0; if (chip->emu_rhy_mode_flags & 0x20) { // TODO: check if writes to 0xbd actually affect the readable key-on flags at // 0x246, 0x247, 0x248; and if there's any visible effect from the SD and TC flags chip->channels[6].key_on = (data & 0x10) != 0; chip->channels[7].key_on = (data & 0x01) != 0; chip->channels[8].key_on = (data & 0x04) != 0; chip->channels[7].key_on_2 = (data & 0x08) != 0; chip->channels[8].key_on_2 = (data & 0x02) != 0; } ESFM_emu_rearrange_connections(&chip->channels[7]); ESFM_emu_rearrange_connections(&chip->channels[8]); return; } switch(reg & 0xf0) { case 0x00: if (high) { int i; switch(reg & 0x0f) { case 0x01: chip->emu_wavesel_enable = (data & 0x20) != 0; break; case 0x02: chip->timer_reload[0] = data; chip->timer_counter[0] = data; break; case 0x03: chip->timer_reload[1] = data; chip->timer_counter[1] = data; break; case 0x04: for (i = 0; i < 3; i++) { chip->channels[i].emu_mode_4op_enable = (data >> i) & 0x01; chip->channels[i + 9].emu_mode_4op_enable = (data >> (i + 3)) & 0x01; } for (i = 0; i < 6; i++) { ESFM_emu_rearrange_connections(&chip->channels[i]); ESFM_emu_rearrange_connections(&chip->channels[i + 9]); } break; case 0x05: chip->emu_newmode = data & 0x01; if ((data & 0x80) != 0) { chip->native_mode = 1; ESFM_emu_to_native_switch(chip); } break; case 0x08: chip->keyscale_mode = (data & 0x40) != 0; break; } } else { switch(reg & 0x0f) { case 0x01: chip->emu_wavesel_enable = (data & 0x20) != 0; break; case 0x02: chip->timer_reload[0] = data; chip->timer_counter[0] = data; break; case 0x03: chip->timer_reload[1] = data; chip->timer_counter[1] = data; break; case 0x04: if (data & 0x80) { chip->irq_bit = 0; chip->timer_overflow[0] = 0; chip->timer_overflow[1] = 0; break; } chip->timer_enable[0] = data & 0x01; chip->timer_enable[1] = (data & 0x02) != 0; chip->timer_mask[1] = (data & 0x20) != 0; chip->timer_mask[0] = (data & 0x40) != 0; break; case 0x08: chip->keyscale_mode = (data & 0x40) != 0; break; } } break; case 0x20: case 0x30: if (emu_slot_idx >= 0) { ESFM_slot_write(&chip->channels[natv_chan_idx].slots[natv_slot_idx], 0x0, data); } break; case 0x40: case 0x50: if (emu_slot_idx >= 0) { ESFM_slot_write(&chip->channels[natv_chan_idx].slots[natv_slot_idx], 0x1, data); ESFM_emu_channel_update_keyscale(&chip->channels[natv_chan_idx]); } break; case 0x60: case 0x70: if (emu_slot_idx >= 0) { ESFM_slot_write(&chip->channels[natv_chan_idx].slots[natv_slot_idx], 0x2, data); } break; case 0x80: case 0x90: if (emu_slot_idx >= 0) { ESFM_slot_write(&chip->channels[natv_chan_idx].slots[natv_slot_idx], 0x3, data); } break; case 0xa0: if (emu_chan_idx >= 0) { ESFM_slot_write(&chip->channels[emu_chan_idx].slots[0], 0x4, data); ESFM_emu_channel_update_keyscale(&chip->channels[emu_chan_idx]); } break; case 0xb0: if (emu_chan_idx >= 0) { esfm_channel *channel = &chip->channels[emu_chan_idx]; // TODO: check if emulation mode actually writes to the native mode key on registers // it might only use slot 0's emu key on field... channel->key_on = (data & 0x20) != 0; if (channel->channel_idx == 7 || channel->channel_idx == 8) { channel->key_on_2 = (data & 0x20) != 0; } ESFM_slot_write(&channel->slots[0], 0x5, data); ESFM_emu_channel_update_keyscale(&chip->channels[emu_chan_idx]); } break; case 0xc0: if (emu_chan_idx >= 0) { ESFM_slot_write(&chip->channels[emu_chan_idx].slots[0], 0x6, data); ESFM_emu_rearrange_connections(&chip->channels[emu_chan_idx]); } break; case 0xe0: case 0xf0: if (emu_slot_idx >= 0) { ESFM_slot_write(&chip->channels[natv_chan_idx].slots[natv_slot_idx], 0x7, data); } break; } } /* your_sha256_hash--------- */ void ESFM_write_reg (esfm_chip *chip, uint16_t address, uint8_t data) { if (chip->native_mode) { ESFM_write_reg_native(chip, address, data); return; } else { ESFM_write_reg_emu(chip, address, data); return; } } /* your_sha256_hash--------- */ void ESFM_write_reg_buffered (esfm_chip *chip, uint16_t address, uint8_t data) { uint64_t timestamp; esfm_write_buf *new_entry, *last_entry; new_entry = &chip->write_buf[chip->write_buf_end]; last_entry = &chip->write_buf[(chip->write_buf_end - 1) % ESFM_WRITEBUF_SIZE]; if (new_entry->valid) { ESFM_write_reg(chip, new_entry->address, new_entry->data); chip->write_buf_start = (chip->write_buf_end + 1) % ESFM_WRITEBUF_SIZE; } new_entry->valid = 1; new_entry->address = address; new_entry->data = data; timestamp = last_entry->timestamp + ESFM_WRITEBUF_DELAY; if (timestamp < chip->write_buf_timestamp) { timestamp = chip->write_buf_timestamp; } new_entry->timestamp = timestamp; chip->write_buf_end = (chip->write_buf_end + 1) % ESFM_WRITEBUF_SIZE; } /* your_sha256_hash--------- */ void ESFM_write_reg_buffered_fast (esfm_chip *chip, uint16_t address, uint8_t data) { esfm_write_buf *new_entry; new_entry = &chip->write_buf[chip->write_buf_end]; if (new_entry->valid) { ESFM_write_reg(chip, new_entry->address, new_entry->data); chip->write_buf_start = (chip->write_buf_end + 1) % ESFM_WRITEBUF_SIZE; } new_entry->valid = 1; new_entry->address = address; new_entry->data = data; new_entry->timestamp = chip->write_buf_timestamp; chip->write_buf_end = (chip->write_buf_end + 1) % ESFM_WRITEBUF_SIZE; } /* your_sha256_hash--------- */ uint8_t ESFM_readback_reg (esfm_chip *chip, uint16_t address) { if (chip->native_mode) { return ESFM_readback_reg_native(chip, address); } else { return 0; } } /* your_sha256_hash--------- */ void ESFM_write_port (esfm_chip *chip, uint8_t offset, uint8_t data) { if (chip->native_mode) { switch(offset) { case 0: chip->native_mode = 0; ESFM_native_to_emu_switch(chip); // TODO: verify if the address write goes through chip->addr_latch = data; break; case 1: ESFM_write_reg_native(chip, chip->addr_latch, data); break; case 2: chip->addr_latch = (chip->addr_latch & 0xff00) | data; break; case 3: chip->addr_latch = chip->addr_latch & 0xff; chip->addr_latch |= (uint16)data << 8; break; } } else { switch(offset) { case 0: chip->addr_latch = data; break; case 1: case 3: ESFM_write_reg_emu(chip, chip->addr_latch, data); break; case 2: chip->addr_latch = (uint16)data | 0x100; break; } } } /* your_sha256_hash--------- */ uint8_t ESFM_read_port (esfm_chip *chip, uint8_t offset) { uint8_t data = 0; switch(offset) { case 0: data |= (chip->irq_bit != 0) << 7; data |= (chip->timer_overflow[0] != 0) << 6; data |= (chip->timer_overflow[1] != 0) << 5; break; case 1: if (chip->native_mode) { data = ESFM_readback_reg_native(chip, chip->addr_latch); } else { data = 0; } break; case 2: case 3: // This matches OPL3 behavior. data = 0xff; break; } return data; } /* your_sha256_hash--------- */ void ESFM_set_mode (esfm_chip *chip, bool native_mode) { native_mode = native_mode != 0; if (native_mode != (chip->native_mode != 0)) { chip->native_mode = native_mode; if (native_mode) { ESFM_emu_to_native_switch(chip); } else { ESFM_native_to_emu_switch(chip); } } } /* your_sha256_hash--------- */ void ESFM_init (esfm_chip *chip) { esfm_slot *slot; esfm_channel *channel; size_t channel_idx, slot_idx; memset(chip, 0, sizeof(esfm_chip)); for (channel_idx = 0; channel_idx < 18; channel_idx++) { for (slot_idx = 0; slot_idx < 4; slot_idx++) { channel = &chip->channels[channel_idx]; slot = &channel->slots[slot_idx]; channel->chip = chip; channel->channel_idx = channel_idx; slot->channel = channel; slot->chip = chip; slot->slot_idx = slot_idx; slot->in.eg_position = slot->in.eg_output = 0x1ff; slot->in.eg_state = EG_RELEASE; slot->in.emu_mod_enable = ~((int13) 0); if (slot_idx == 0) { slot->in.mod_input = &slot->in.feedback_buf; } else { esfm_slot *prev_slot = &channel->slots[slot_idx - 1]; slot->in.mod_input = &prev_slot->in.output; } if (slot_idx == 1) { slot->in.emu_output_enable = ~((int13) 0); } if (channel_idx > 15 && slot_idx & 0x02) { slot->in.key_on = &channel->key_on_2; } else { slot->in.key_on = &channel->key_on; } slot->out_enable[0] = slot->out_enable[1] = ~((int13) 0); } } chip->lfsr = 1; } ```
/content/code_sandbox/src/sound/esfmu/esfm_registers.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
9,519
```objective-c /* * ESFMu: emulator for the ESS "ESFM" enhanced OPL3 clone * * ESFMu is free software: you can redistribute it and/or modify * published by the Free Software Foundation, either version 2.1 * * ESFMu is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with ESFMu. If not, see <path_to_url */ /* * ESFMu wouldn't have been possible without the hard work and dedication of * the retro computer hardware research and preservation community. * * I'd like to thank: * - Nuke.YKT * Developer of Nuked OPL3, which was the basis for ESFMu's code and * also a great learning resource on Yamaha FM synthesis for myself. * Nuke.YKT also gives shoutouts on behalf of Nuked OPL3 to: * - MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): * Feedback and Rhythm part calculation information. * - forums.submarine.org.uk(carbon14, opl3): * Tremolo and phase generator calculation information. * - OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): * OPL2 ROMs. * - siliconpr0n.org(John McMaster, digshadow): * YMF262 and VRC VII decaps and die shots. * - rainwarrior * For performing the initial research on ESFM drivers and documenting * ESS's patent on native mode operator organization. * - jwt27 * For kickstarting the ESFM research project and compiling rainwarrior's * findings and more in an accessible document ("ESFM Demystified"). * - pachuco/CatButts * For documenting ESS's patent on ESFM's feedback implementation, which * was vital in getting ESFMu's sound output to be accurate. * - akumanatt * For helping out with code optimization. * - And everybody who helped out with real hardware testing */ #include <stddef.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct _esfm_slot esfm_slot; typedef struct _esfm_slot_internal esfm_slot_internal; typedef struct _esfm_channel esfm_channel; typedef struct _esfm_chip esfm_chip; void ESFM_init (esfm_chip *chip); void ESFM_write_reg (esfm_chip *chip, uint16_t address, uint8_t data); void ESFM_write_reg_buffered (esfm_chip *chip, uint16_t address, uint8_t data); void ESFM_write_reg_buffered_fast (esfm_chip *chip, uint16_t address, uint8_t data); void ESFM_write_port (esfm_chip *chip, uint8_t offset, uint8_t data); uint8_t ESFM_readback_reg (esfm_chip *chip, uint16_t address); uint8_t ESFM_read_port (esfm_chip *chip, uint8_t offset); void ESFM_generate(esfm_chip *chip, int32_t *buf); void ESFM_generate_stream(esfm_chip *chip, int16_t *sndptr, uint32_t num_samples); int16_t ESFM_get_channel_output_native(esfm_chip *chip, int channel_idx); // These are fake types just for syntax sugar. // Beware of their underlying types when reading/writing to them. typedef uint8_t ebit; typedef uint8_t uint2; typedef uint8_t uint3; typedef uint8_t uint4; typedef uint8_t uint5; typedef uint8_t uint6; typedef uint8_t uint8; typedef uint16_t uint9; typedef uint16_t uint10; typedef uint16_t uint11; typedef uint16_t uint12; typedef uint16_t uint16; typedef uint32_t uint19; typedef uint32_t uint23; typedef uint32_t uint32; typedef uint64_t uint36; typedef int16_t int13; typedef int16_t int14; typedef int16_t int16; typedef int32_t int32; enum eg_states { EG_ATTACK, EG_DECAY, EG_SUSTAIN, EG_RELEASE }; typedef struct _esfm_write_buf { uint64_t timestamp; uint16_t address; uint8_t data; ebit valid; } esfm_write_buf; typedef struct _emu_slot_channel_mapping { int channel_idx; int slot_idx; } emu_slot_channel_mapping; typedef struct _esfm_slot_internal { uint9 eg_position; uint9 eg_ksl_offset; uint10 eg_output; uint4 keyscale; int13 output; int13 emu_output_enable; int13 emu_mod_enable; int13 feedback_buf; int13 *mod_input; uint19 phase_acc; uint10 phase_out; ebit phase_reset; ebit *key_on; ebit key_on_gate; uint2 eg_state; ebit eg_delay_run; ebit eg_delay_transitioned_10; ebit eg_delay_transitioned_10_gate; ebit eg_delay_transitioned_01; ebit eg_delay_transitioned_01_gate; uint16 eg_delay_counter; uint16 eg_delay_counter_compare; } esfm_slot_internal; struct _esfm_slot { // Metadata esfm_channel *channel; esfm_chip *chip; uint2 slot_idx; // Register data int13 out_enable[2]; uint10 f_num; uint3 block; uint3 output_level; // a.k.a. feedback level in emu mode uint3 mod_in_level; uint6 t_level; uint4 mult; uint3 waveform; // Only for 4th slot uint2 rhy_noise; uint4 attack_rate; uint4 decay_rate; uint4 sustain_lvl; uint4 release_rate; ebit tremolo_en; ebit tremolo_deep; ebit vibrato_en; ebit vibrato_deep; ebit emu_connection_typ; ebit env_sustaining; ebit ksr; uint2 ksl; uint3 env_delay; // overlaps with env_delay bit 0 // TODO: check if emu mode only uses this, or if it actually overwrites the channel field used by native mode ebit emu_key_on; // Internal state esfm_slot_internal in; }; struct _esfm_channel { esfm_chip *chip; esfm_slot slots[4]; uint5 channel_idx; int16 output[2]; ebit key_on; ebit emu_mode_4op_enable; // Only for 17th and 18th channels ebit key_on_2; ebit emu_mode_4op_enable_2; }; #define ESFM_WRITEBUF_SIZE 1024 #define ESFM_WRITEBUF_DELAY 2 struct _esfm_chip { esfm_channel channels[18]; int32 output_accm[2]; uint16 addr_latch; ebit emu_wavesel_enable; ebit emu_newmode; ebit native_mode; ebit keyscale_mode; // Global state uint36 eg_timer; uint10 global_timer; uint8 eg_clocks; ebit eg_tick; ebit eg_timer_overflow; uint8 tremolo; uint8 tremolo_pos; uint8 vibrato_pos; uint23 lfsr; ebit rm_hh_bit2; ebit rm_hh_bit3; ebit rm_hh_bit7; ebit rm_hh_bit8; ebit rm_tc_bit3; ebit rm_tc_bit5; // 0xbd register in emulation mode, exposed in 0x4bd in native mode // ("bass drum" register) uint8 emu_rhy_mode_flags; ebit emu_vibrato_deep; ebit emu_tremolo_deep; double timer_accumulator[2]; uint8 timer_reload[2]; uint8 timer_counter[2]; ebit timer_enable[2]; ebit timer_mask[2]; ebit timer_overflow[2]; ebit irq_bit; // -- Test bits (NOT IMPLEMENTED) -- // Halts the envelope generators from advancing. Written on bit 0, read back from bit 5. ebit test_bit_w0_r5_eg_halt; /* * Activates some sort of waveform test mode that amplifies the output volume greatly * and continuously shifts the waveform table downwards, possibly also outputting the * waveform's derivative? (it's so weird!) */ ebit test_bit_1_distort; // Seems to do nothing. ebit test_bit_2; // Seems to do nothing. ebit test_bit_3; // Appears to attenuate the output by about 3 dB. ebit test_bit_4_attenuate; // Written on bit 5, read back from bit 0. Seems to do nothing. ebit test_bit_w5_r0; // Resets all phase generators and holds them in the reset state while this bit is set. ebit test_bit_6_phase_stop_reset; // Seems to do nothing. ebit test_bit_7; esfm_write_buf write_buf[ESFM_WRITEBUF_SIZE]; size_t write_buf_start; size_t write_buf_end; uint64_t write_buf_timestamp; }; #ifdef __cplusplus } #endif ```
/content/code_sandbox/src/sound/esfmu/esfm.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,046
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "WaveformCalculator.h" #include <cmath> namespace reSIDfp { WaveformCalculator* WaveformCalculator::getInstance() { static WaveformCalculator instance; return &instance; } /** * Parameters derived with the Monte Carlo method based on * samplings by kevtris. Code and data available in the project repository [1]. * * The score here reported is the acoustic error * calculated XORing the estimated and the sampled values. * In parentheses the number of mispredicted bits. * * [1] path_to_url */ const CombinedWaveformConfig config[2][5] = { { /* kevtris chip G (6581 R2) */ {0.862147212f, 0.f, 10.8962431f, 2.50848103f }, // TS error 1941 (327/28672) {0.932746708f, 2.07508397f, 1.03668225f, 1.14876997f }, // PT error 5992 (126/32768) {0.860927045f, 2.43506575f, 0.908603609f, 1.07907593f }, // PS error 3693 (521/28672) {0.741343081f, 0.0452554375f, 1.1439606f, 1.05711341f }, // PTS error 338 ( 29/28672) {0.96f, 2.5f, 1.1f, 1.2f }, // NP guessed }, { /* kevtris chip V (8580 R5) */ {0.715788841f, 0.f, 1.32999945f, 2.2172699f }, // TS error 928 (135/32768) {0.93500334f, 1.05977178f, 1.08629429f, 1.43518543f }, // PT error 7991 (212/32768) {0.920648575f, 0.943601072f, 1.13034654f, 1.41881108f }, // PS error 12566 (394/32768) {0.90921098f, 0.979807794f, 0.942194462f, 1.40958893f }, // PTS error 2092 ( 60/32768) {0.95f, 1.15f, 1.f, 1.45f }, // NP guessed }, }; typedef float (*distance_t)(float, int); // Distance functions static float exponentialDistance(float distance, int i) { return pow(distance, -i); } #if 0 MAYBE_UNUSED static float linearDistance(float distance, int i) { return 1.f / (1.f + i * distance); } #endif #if 0 MAYBE_UNUSED static float quadraticDistance(float distance, int i) { return 1.f / (1.f + (i*i) * distance); } #endif /// Calculate triangle waveform static unsigned int triXor(unsigned int val) { return (((val & 0x800) == 0) ? val : (val ^ 0xfff)) << 1; } /** * Generate bitstate based on emulation of combined waves pulldown. * * @param distancetable * @param pulsestrength * @param threshold * @param accumulator the high bits of the accumulator value */ short calculatePulldown(float distancetable[], float pulsestrength, float threshold, unsigned int accumulator) { unsigned char bit[12]; for (unsigned int i = 0; i < 12; i++) { bit[i] = (accumulator & (1u << i)) != 0 ? 1 : 0; } float pulldown[12]; for (int sb = 0; sb < 12; sb++) { float avg = 0.f; float n = 0.f; for (int cb = 0; cb < 12; cb++) { if (cb == sb) continue; const float weight = distancetable[sb - cb + 12]; avg += static_cast<float>(1 - bit[cb]) * weight; n += weight; } avg -= pulsestrength; pulldown[sb] = avg / n; } // Get the predicted value short value = 0; for (unsigned int i = 0; i < 12; i++) { const float bitValue = bit[i] != 0 ? 1.f - pulldown[i] : 0.f; if (bitValue > threshold) { value |= 1u << i; } } return value; } WaveformCalculator::WaveformCalculator() : wftable(4, 4096) { // Build waveform table. for (unsigned int idx = 0; idx < (1u << 12); idx++) { const short saw = static_cast<short>(idx); const short tri = static_cast<short>(triXor(idx)); wftable[0][idx] = 0xfff; wftable[1][idx] = tri; wftable[2][idx] = saw; wftable[3][idx] = saw & (saw << 1); } } matrix_t* WaveformCalculator::buildPulldownTable(ChipModel model) { const CombinedWaveformConfig* cfgArray = config[model == MOS6581 ? 0 : 1]; cw_cache_t::iterator lb = PULLDOWN_CACHE.lower_bound(cfgArray); if (lb != PULLDOWN_CACHE.end() && !(PULLDOWN_CACHE.key_comp()(cfgArray, lb->first))) { return &(lb->second); } matrix_t pdTable(5, 4096); for (int wav = 0; wav < 5; wav++) { const CombinedWaveformConfig& cfg = cfgArray[wav]; const distance_t distFunc = exponentialDistance; float distancetable[12 * 2 + 1]; distancetable[12] = 1.f; for (int i = 12; i > 0; i--) { distancetable[12-i] = distFunc(cfg.distance1, i); distancetable[12+i] = distFunc(cfg.distance2, i); } for (unsigned int idx = 0; idx < (1u << 12); idx++) { pdTable[wav][idx] = calculatePulldown(distancetable, cfg.pulsestrength, cfg.threshold, idx); } } #ifdef HAVE_CXX11 return &(PULLDOWN_CACHE.emplace_hint(lb, cw_cache_t::value_type(cfgArray, pdTable))->second); #else return &(PULLDOWN_CACHE.insert(lb, cw_cache_t::value_type(cfgArray, pdTable))->second); #endif } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/WaveformCalculator.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,729
```objective-c #define HAVE_CXX14 ```
/content/code_sandbox/src/sound/resid-fp/config.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
7
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef OPAMP_H #define OPAMP_H #include <memory> #include <vector> #include "Spline.h" #include "sidcxx11.h" namespace reSIDfp { /** * Find output voltage in inverting gain and inverting summer SID op-amp * circuits, using a combination of Newton-Raphson and bisection. * * +---R2--+ * | | * vi ---R1--o--[A>--o-- vo * vx * * From Kirchoff's current law it follows that * * IR1f + IR2r = 0 * * Substituting the triode mode transistor model K*W/L*(Vgst^2 - Vgdt^2) * for the currents, we get: * * n*((Vddt - vx)^2 - (Vddt - vi)^2) + (Vddt - vx)^2 - (Vddt - vo)^2 = 0 * * where n is the ratio between R1 and R2. * * Our root function f can thus be written as: * * f = (n + 1)*(Vddt - vx)^2 - n*(Vddt - vi)^2 - (Vddt - vo)^2 = 0 * * Using substitution constants * * a = n + 1 * b = Vddt * c = n*(Vddt - vi)^2 * * the equations for the root function and its derivative can be written as: * * f = a*(b - vx)^2 - c - (b - vo)^2 * df = 2*((b - vo)*dvo - a*(b - vx)) */ class OpAmp { private: /// Current root position (cached as guess to speed up next iteration) mutable double x; const double Vddt; const double vmin; const double vmax; std::unique_ptr<Spline> const opamp; public: /** * Opamp input -> output voltage conversion * * @param opamp opamp mapping table as pairs of points (in -> out) * @param Vddt transistor dt parameter (in volts) * @param vmin * @param vmax */ OpAmp(const std::vector<Spline::Point> &opamp, double Vddt, double vmin, double vmax ) : x(0.), Vddt(Vddt), vmin(vmin), vmax(vmax), opamp(new Spline(opamp)) {} /** * Reset root position */ void reset() const { x = vmin; } /** * Solve the opamp equation for input vi in loading context n * * @param n the ratio of input/output loading * @param vi input voltage * @return vo output voltage */ double solve(double n, double vi) const; }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/OpAmp.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
785
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define WAVEFORMGENERATOR_CPP #include "WaveformGenerator.h" namespace reSIDfp { /** * Number of cycles after which the waveform output fades to 0 when setting * the waveform register to 0. * Values measured on warm chips (6581R3/R4 and 8580R5) * checking OSC3. * Times vary wildly with temperature and may differ * from chip to chip so the numbers here represent * only the big difference between the old and new models. * * See [VICE Bug #290](path_to_url * and [VICE Bug #1128](path_to_url */ // ~95ms const unsigned int FLOATING_OUTPUT_TTL_6581R3 = 54000; const unsigned int FLOATING_OUTPUT_FADE_6581R3 = 1400; // ~1s //const unsigned int FLOATING_OUTPUT_TTL_6581R4 = 1000000; // ~1s const unsigned int FLOATING_OUTPUT_TTL_8580R5 = 800000; const unsigned int FLOATING_OUTPUT_FADE_8580R5 = 50000; /** * Number of cycles after which the shift register is reset * when the test bit is set. * Values measured on warm chips (6581R3/R4 and 8580R5) * checking OSC3. * Times vary wildly with temperature and may differ * from chip to chip so the numbers here represent * only the big difference between the old and new models. */ // ~210ms const unsigned int SHIFT_REGISTER_RESET_6581R3 = 50000; const unsigned int SHIFT_REGISTER_FADE_6581R3 = 15000; // ~2.15s //const unsigned int SHIFT_REGISTER_RESET_6581R4 = 2150000; // ~2.8s const unsigned int SHIFT_REGISTER_RESET_8580R5 = 986000; const unsigned int SHIFT_REGISTER_FADE_8580R5 = 314300; const unsigned int shift_mask = ~( (1u << 2) | // Bit 20 (1u << 4) | // Bit 18 (1u << 8) | // Bit 14 (1u << 11) | // Bit 11 (1u << 13) | // Bit 9 (1u << 17) | // Bit 5 (1u << 20) | // Bit 2 (1u << 22) // Bit 0 ); /* * This is what happens when the lfsr is clocked: * * cycle 0: bit 19 of the accumulator goes from low to high, the noise register acts normally, * the output may pulldown a bit; * * cycle 1: first phase of the shift, the bits are interconnected and the output of each bit * is latched into the following. The output may overwrite the latched value. * * cycle 2: second phase of the shift, the latched value becomes active in the first * half of the clock and from the second half the register returns to normal operation. * * When the test or reset lines are active the first phase is executed at every cyle * until the signal is released triggering the second phase. * * | | bit n | bit n+1 * | bit19 | latch output | latch output * -----+-------+--------------+-------------- * phi1 | 0 | A <-> A | B <-> B * phi2 | 0 | A <-> A | B <-> B * -----+-------+--------------+-------------- * phi1 | 1 | A <-> A | B <-> B <- bit19 raises * phi2 | 1 | A <-> A | B <-> B * -----+-------+--------------+-------------- * phi1 | 1 | X A --|-> A B <- shift phase 1 * phi2 | 1 | X A --|-> A B * -----+-------+--------------+-------------- * phi1 | 1 | X --> X | A --> A <- shift phase 2 * phi2 | 1 | X <-> X | A <-> A */ inline bool do_writeback(unsigned int waveform_old, unsigned int waveform_new, bool is6581) { // no writeback without combined waveforms if (waveform_new <= 8) return false; if (waveform_old <= 8) return false; // fixes SID/noisewriteback/noise_writeback_test2-{old,new} // What's happening here? if (is6581 && ((((waveform_old & 0x3) == 0x1) && ((waveform_new & 0x3) == 0x2)) || (((waveform_old & 0x3) == 0x2) && ((waveform_new & 0x3) == 0x1)))) { // fixes // noise_writeback_check_9_to_A_old // noise_writeback_check_9_to_E_old // noise_writeback_check_A_to_9_old // noise_writeback_check_A_to_D_old // noise_writeback_check_D_to_A_old // noise_writeback_check_E_to_9_old return false; } if (waveform_old == 0xc) { // fixes // noise_writeback_check_C_to_A_new return false; } if (waveform_new == 0xc) { // fixes // noise_writeback_check_9_to_C_old // noise_writeback_check_A_to_C_old return false; } // ok do the writeback return true; } inline unsigned int get_noise_writeback(unsigned int waveform_output) { return ((waveform_output & (1u << 11)) >> 9) | // Bit 11 -> bit 20 ((waveform_output & (1u << 10)) >> 6) | // Bit 10 -> bit 18 ((waveform_output & (1u << 9)) >> 1) | // Bit 9 -> bit 14 ((waveform_output & (1u << 8)) << 3) | // Bit 8 -> bit 11 ((waveform_output & (1u << 7)) << 6) | // Bit 7 -> bit 9 ((waveform_output & (1u << 6)) << 11) | // Bit 6 -> bit 5 ((waveform_output & (1u << 5)) << 15) | // Bit 5 -> bit 2 ((waveform_output & (1u << 4)) << 18); // Bit 4 -> bit 0 } /* * Perform the actual shifting, moving the latched value into following bits. * The XORing for bit0 is done in this cycle using the test bit latched during * the previous phi2 cycle. */ void WaveformGenerator::shift_phase2(unsigned int waveform_old, unsigned int waveform_new) { if (do_writeback(waveform_old, waveform_new, is6581)) { // if noise is combined with another waveform the output drives the SR bits shift_latch = (shift_register & shift_mask) | get_noise_writeback(waveform_output); } // bit0 = (bit22 | test | reset) ^ bit17 = 1 ^ bit17 = ~bit17 const unsigned int bit22 = ((test_or_reset ? 1 : 0) | shift_latch) << 22; const unsigned int bit0 = (bit22 ^ (shift_latch << 17)) & (1 << 22); shift_register = (shift_latch >> 1) | bit0; #ifdef TRACE std::cout << std::hex << shift_latch << " -> " << shift_register << std::endl; #endif set_noise_output(); } void WaveformGenerator::write_shift_register() { if (unlikely(waveform > 0x8)) { if (waveform == 0xc) return; // breaks SID/wf12nsr/wf12nsr // Write changes to the shift register output caused by combined waveforms // back into the shift register. if (likely(shift_pipeline != 1) && !test) { #ifdef TRACE std::cout << "write shift_register" << std::endl; #endif // the output pulls down the SR bits shift_register = shift_register & (shift_mask | get_noise_writeback(waveform_output)); noise_output &= waveform_output; } else { #ifdef TRACE std::cout << "write shift_latch" << std::endl; #endif // shift phase 1: the output drives the SR bits noise_output = waveform_output; } set_no_noise_or_noise_output(); } } void WaveformGenerator::set_noise_output() { noise_output = ((shift_register & (1u << 2)) << 9) | // Bit 20 -> bit 11 ((shift_register & (1u << 4)) << 6) | // Bit 18 -> bit 10 ((shift_register & (1u << 8)) << 1) | // Bit 14 -> bit 9 ((shift_register & (1u << 11)) >> 3) | // Bit 11 -> bit 8 ((shift_register & (1u << 13)) >> 6) | // Bit 9 -> bit 7 ((shift_register & (1u << 17)) >> 11) | // Bit 5 -> bit 6 ((shift_register & (1u << 20)) >> 15) | // Bit 2 -> bit 5 ((shift_register & (1u << 22)) >> 18); // Bit 0 -> bit 4 set_no_noise_or_noise_output(); } void WaveformGenerator::setWaveformModels(matrix_t* models) { model_wave = models; } void WaveformGenerator::setPulldownModels(matrix_t* models) { model_pulldown = models; } void WaveformGenerator::synchronize(WaveformGenerator* syncDest, const WaveformGenerator* syncSource) const { // A special case occurs when a sync source is synced itself on the same // cycle as when its MSB is set high. In this case the destination will // not be synced. This has been verified by sampling OSC3. if (unlikely(msb_rising) && syncDest->sync && !(sync && syncSource->msb_rising)) { syncDest->accumulator = 0; } } void WaveformGenerator::set_no_noise_or_noise_output() { no_noise_or_noise_output = no_noise | noise_output; } void WaveformGenerator::writeCONTROL_REG(unsigned char control) { const unsigned int waveform_prev = waveform; const bool test_prev = test; waveform = (control >> 4) & 0x0f; test = (control & 0x08) != 0; sync = (control & 0x02) != 0; // Substitution of accumulator MSB when sawtooth = 0, ring_mod = 1. ring_msb_mask = ((~control >> 5) & (control >> 2) & 0x1) << 23; if (waveform != waveform_prev) { // Set up waveform tables wave = (*model_wave)[waveform & 0x3]; // We assume tha combinations including noise // behave the same as without switch (waveform & 0x7) { case 3: pulldown = (*model_pulldown)[0]; break; case 4: pulldown = (waveform & 0x8) ? (*model_pulldown)[4] : nullptr; break; case 5: pulldown = (*model_pulldown)[1]; break; case 6: pulldown = (*model_pulldown)[2]; break; case 7: pulldown = (*model_pulldown)[3]; break; default: pulldown = nullptr; break; } // no_noise and no_pulse are used in set_waveform_output() as bitmasks to // only let the noise or pulse influence the output when the noise or pulse // waveforms are selected. no_noise = (waveform & 0x8) != 0 ? 0x000 : 0xfff; set_no_noise_or_noise_output(); no_pulse = (waveform & 0x4) != 0 ? 0x000 : 0xfff; if (waveform == 0) { // Change to floating DAC input. // Reset fading time for floating DAC input. floating_output_ttl = is6581 ? FLOATING_OUTPUT_TTL_6581R3 : FLOATING_OUTPUT_TTL_8580R5; } } if (test != test_prev) { if (test) { // Reset accumulator. accumulator = 0; // Flush shift pipeline. shift_pipeline = 0; // Latch the shift register value. shift_latch = shift_register; #ifdef TRACE std::cout << "shift phase 1 (test)" << std::endl; #endif // Set reset time for shift register. shift_register_reset = is6581 ? SHIFT_REGISTER_RESET_6581R3 : SHIFT_REGISTER_RESET_8580R5; } else { // When the test bit is falling, the second phase of the shift is // completed by enabling SRAM write. shift_phase2(waveform_prev, waveform); } } } void WaveformGenerator::waveBitfade() { waveform_output &= waveform_output >> 1; osc3 = waveform_output; if (waveform_output != 0) floating_output_ttl = is6581 ? FLOATING_OUTPUT_FADE_6581R3 : FLOATING_OUTPUT_FADE_8580R5; } void WaveformGenerator::shiftregBitfade() { shift_register |= shift_register >> 1; shift_register |= 0x400000; if (shift_register != 0x7fffff) shift_register_reset = is6581 ? SHIFT_REGISTER_FADE_6581R3 : SHIFT_REGISTER_FADE_8580R5; } void WaveformGenerator::reset() { // accumulator is not changed on reset freq = 0; pw = 0; msb_rising = false; waveform = 0; osc3 = 0; test = false; sync = false; wave = model_wave ? (*model_wave)[0] : nullptr; pulldown = nullptr; ring_msb_mask = 0; no_noise = 0xfff; no_pulse = 0xfff; pulse_output = 0xfff; shift_register_reset = 0; shift_register = 0x7fffff; // when reset is released the shift register is clocked once // so the lower bit is zeroed out // bit0 = (bit22 | test) ^ bit17 = 1 ^ 1 = 0 test_or_reset = true; shift_latch = shift_register; shift_phase2(0, 0); shift_pipeline = 0; waveform_output = 0; floating_output_ttl = 0; } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/WaveformGenerator.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,657
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "FilterModelConfig8580.h" #include "Integrator8580.h" #include "OpAmp.h" namespace reSIDfp { /* * R1 = 15.3*Ri * R2 = 7.3*Ri * R3 = 4.7*Ri * Rf = 1.4*Ri * R4 = 1.4*Ri * R8 = 2.0*Ri * RC = 2.8*Ri * * res feedback input * --- -------- ----- * 0 Rf Ri * 1 Rf|R1 Ri * 2 Rf|R2 Ri * 3 Rf|R3 Ri * 4 Rf R4 * 5 Rf|R1 R4 * 6 Rf|R2 R4 * 7 Rf|R3 R4 * 8 Rf R8 * 9 Rf|R1 R8 * A Rf|R2 R8 * B Rf|R3 R8 * C Rf RC * D Rf|R1 RC * E Rf|R2 RC * F Rf|R3 RC */ const double resGain[16] = { 1.4/1.0, // Rf/Ri 1.4 ((1.4*15.3)/(1.4+15.3))/1.0, // (Rf|R1)/Ri 1.28263 ((1.4*7.3)/(1.4+7.3))/1.0, // (Rf|R2)/Ri 1.17471 ((1.4*4.7)/(1.4+4.7))/1.0, // (Rf|R3)/Ri 1.07869 1.4/1.4, // Rf/R4 1 ((1.4*15.3)/(1.4+15.3))/1.4, // (Rf|R1)/R4 0.916168 ((1.4*7.3)/(1.4+7.3))/1.4, // (Rf|R2)/R4 0.83908 ((1.4*4.7)/(1.4+4.7))/1.4, // (Rf|R3)/R4 0.770492 1.4/2.0, // Rf/R8 0.7 ((1.4*15.3)/(1.4+15.3))/2.0, // (Rf|R1)/R8 0.641317 ((1.4*7.3)/(1.4+7.3))/2.0, // (Rf|R2)/R8 0.587356 ((1.4*4.7)/(1.4+4.7))/2.0, // (Rf|R3)/R8 0.539344 1.4/2.8, // Rf/RC 0.5 ((1.4*15.3)/(1.4+15.3))/2.8, // (Rf|R1)/RC 0.458084 ((1.4*7.3)/(1.4+7.3))/2.8, // (Rf|R2)/RC 0.41954 ((1.4*4.7)/(1.4+4.7))/2.8, // (Rf|R3)/RC 0.385246 }; const unsigned int OPAMP_SIZE = 21; /** * This is the SID 8580 op-amp voltage transfer function, measured on * CAP1B/CAP1A on a chip marked CSG 8580R5 1690 25. */ const Spline::Point opamp_voltage[OPAMP_SIZE] = { { 1.30, 8.91 }, // Approximate start of actual range { 4.76, 8.91 }, { 4.77, 8.90 }, { 4.78, 8.88 }, { 4.785, 8.86 }, { 4.79, 8.80 }, { 4.795, 8.60 }, { 4.80, 8.25 }, { 4.805, 7.50 }, { 4.81, 6.10 }, { 4.815, 4.05 }, // Change of curvature { 4.82, 2.27 }, { 4.825, 1.65 }, { 4.83, 1.55 }, { 4.84, 1.47 }, { 4.85, 1.43 }, { 4.87, 1.37 }, { 4.90, 1.34 }, { 5.00, 1.30 }, { 5.10, 1.30 }, { 8.91, 1.30 }, // Approximate end of actual range }; std::unique_ptr<FilterModelConfig8580> FilterModelConfig8580::instance(nullptr); FilterModelConfig8580* FilterModelConfig8580::getInstance() { if (!instance.get()) { instance.reset(new FilterModelConfig8580()); } return instance.get(); } FilterModelConfig8580::FilterModelConfig8580() : FilterModelConfig( 0.30, // voice voltage range FIXME measure 4.84, // voice DC voltage FIXME measure 22e-9, // capacitor value 9.09, // Vdd 0.80, // Vth 100e-6, // uCox opamp_voltage, OPAMP_SIZE ) { // Create lookup tables for gains / summers. #ifndef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // #pragma omp parallel sections { // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // The filter summer operates at n ~ 1, and has 5 fundamentally different // input configurations (2 - 6 input "resistors"). // // Note that all "on" transistors are modeled as one. This is not // entirely accurate, since the input for each transistor is different, // and transistors are not linear components. However modeling all // transistors separately would be extremely costly. for (int i = 0; i < 5; i++) { const int idiv = 2 + i; // 2 - 6 input "resistors". const int size = idiv << 16; const double n = idiv; opampModel.reset(); summer[i] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16 / idiv; /* vmin .. vmax */ summer[i][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // The audio mixer operates at n ~ 8/5, and has 8 fundamentally different // input configurations (0 - 7 input "resistors"). // // All "on", transistors are modeled as one - see comments above for // the filter summer. for (int i = 0; i < 8; i++) { const int idiv = (i == 0) ? 1 : i; const int size = (i == 0) ? 1 : i << 16; const double n = i * 8.0 / 5.0; opampModel.reset(); mixer[i] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16 / idiv; /* vmin .. vmax */ mixer[i][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // 4 bit "resistor" ladders in the audio output gain // necessitate 16 gain tables. // From die photographs of the volume "resistor" ladders // it follows that gain ~ vol/16 (assuming ideal // op-amps and ideal "resistors"). for (int n8 = 0; n8 < 16; n8++) { const int size = 1 << 16; const double n = n8 / 16.0; opampModel.reset(); gain_vol[n8] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16; /* vmin .. vmax */ gain_vol[n8][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // 4 bit "resistor" ladders in the bandpass resonance gain // necessitate 16 gain tables. // From die photographs of the bandpass "resistor" ladders // it follows that 1/Q ~ 2^((4 - res)/8) (assuming ideal // op-amps and ideal "resistors"). for (int n8 = 0; n8 < 16; n8++) { const int size = 1 << 16; opampModel.reset(); gain_res[n8] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16; /* vmin .. vmax */ gain_res[n8][vi] = getNormalizedValue(opampModel.solve(resGain[n8], vin)); } } } } } std::unique_ptr<Integrator8580> FilterModelConfig8580::buildIntegrator() { return MAKE_UNIQUE(Integrator8580, this); } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/FilterModelConfig8580.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,723
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILTERMODELCONFIG6581_H #define FILTERMODELCONFIG6581_H #include "FilterModelConfig.h" #include <memory> #include "Dac.h" #include "sidcxx11.h" namespace reSIDfp { class Integrator6581; /** * Calculate parameters for 6581 filter emulation. */ class FilterModelConfig6581 final : public FilterModelConfig { private: static const unsigned int DAC_BITS = 11; private: static std::unique_ptr<FilterModelConfig6581> instance; // This allows access to the private constructor #ifdef HAVE_CXX11 friend std::unique_ptr<FilterModelConfig6581>::deleter_type; #else friend class std::auto_ptr<FilterModelConfig6581>; #endif /// Transistor parameters. //@{ const double WL_vcr; ///< W/L for VCR const double WL_snake; ///< W/L for "snake" //@} /// DAC parameters. //@{ const double dac_zero; const double dac_scale; //@} /// DAC lookup table Dac dac; /// VCR - 6581 only. //@{ unsigned short vcr_nVg[1 << 16]; unsigned short vcr_n_Ids_term[1 << 16]; //@} private: double getDacZero(double adjustment) const { return dac_zero + (1. - adjustment); } FilterModelConfig6581(); ~FilterModelConfig6581() DEFAULT; public: static FilterModelConfig6581* getInstance(); /** * Construct an 11 bit cutoff frequency DAC output voltage table. * Ownership is transferred to the requester which becomes responsible * of freeing the object when done. * * @param adjustment * @return the DAC table */ unsigned short* getDAC(double adjustment) const; /** * Construct an integrator solver. * * @return the integrator */ std::unique_ptr<Integrator6581> buildIntegrator(); inline unsigned short getVcr_nVg(int i) const { return vcr_nVg[i]; } inline unsigned short getVcr_n_Ids_term(int i) const { return vcr_n_Ids_term[i]; } // only used if SLOPE_FACTOR is defined inline double getUt() const { return Ut; } inline double getN16() const { return N16; } }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/FilterModelConfig6581.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
663
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef INTEGRATOR8580_H #define INTEGRATOR8580_H #include "FilterModelConfig8580.h" #include <stdint.h> #include <cassert> #include "siddefs-fp.h" namespace reSIDfp { /** * 8580 integrator * * +---C---+ * | | * vi -----Rfc---o--[A>--o-- vo * vx * * IRfc + ICr = 0 * IRfc + C*(vc - vc0)/dt = 0 * dt/C*(IRfc) + vc - vc0 = 0 * vc = vc0 - n*(IRfc(vi,vx)) * vc = vc0 - n*(IRfc(vi,g(vc))) * * IRfc = K*W/L*(Vgst^2 - Vgdt^2) = n*((Vddt - vx)^2 - (Vddt - vi)^2) * * Rfc gate voltage is generated by an OP Amp and depends on chip temperature. */ class Integrator8580 { private: mutable int vx; mutable int vc; unsigned short nVgt; unsigned short n_dac; const FilterModelConfig8580* fmc; public: Integrator8580(const FilterModelConfig8580* fmc) : vx(0), vc(0), fmc(fmc) { setV(1.5); } /** * Set Filter Cutoff resistor ratio. */ void setFc(double wl) { // Normalized current factor, 1 cycle at 1MHz. // Fit in 5 bits. n_dac = fmc->getNormalizedCurrentFactor(wl); } /** * Set FC gate voltage multiplier. */ void setV(double v) { // Gate voltage is controlled by the switched capacitor voltage divider // Ua = Ue * v = 4.76v 1<v<2 assert(v > 1.0 && v < 2.0); const double Vg = 4.76 * v; const double Vgt = Vg - fmc->getVth(); // Vg - Vth, normalized so that translated values can be subtracted: // Vgt - x = (Vgt - t) - (x - t) nVgt = fmc->getNormalizedValue(Vgt); } int solve(int vi) const; }; } // namespace reSIDfp #if RESID_INLINING || defined(INTEGRATOR8580_CPP) namespace reSIDfp { RESID_INLINE int Integrator8580::solve(int vi) const { // Make sure we're not in subthreshold mode assert(vx < nVgt); // DAC voltages const unsigned int Vgst = nVgt - vx; const unsigned int Vgdt = (vi < nVgt) ? nVgt - vi : 0; // triode/saturation mode const unsigned int Vgst_2 = Vgst * Vgst; const unsigned int Vgdt_2 = Vgdt * Vgdt; // DAC current, scaled by (1/m)*2^13*m*2^16*m*2^16*2^-15 = m*2^30 const int n_I_dac = n_dac * (static_cast<int>(Vgst_2 - Vgdt_2) >> 15); // Change in capacitor charge. vc += n_I_dac; // vx = g(vc) const int tmp = (vc >> 15) + (1 << 15); assert(tmp < (1 << 16)); vx = fmc->getOpampRev(tmp); // Return vo. return vx - (vc >> 14); } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/Integrator8580.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
978
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef WAVEFORMGENERATOR_H #define WAVEFORMGENERATOR_H #include "siddefs-fp.h" #include "array.h" #include "sidcxx11.h" // print SR debugging info //#define TRACE 1 #ifdef TRACE # include <iostream> #endif namespace reSIDfp { /** * A 24 bit accumulator is the basis for waveform generation. * FREQ is added to the lower 16 bits of the accumulator each cycle. * The accumulator is set to zero when TEST is set, and starts counting * when TEST is cleared. * * Waveforms are generated as follows: * * - No waveform: * When no waveform is selected, the DAC input is floating. * * * - Triangle: * The upper 12 bits of the accumulator are used. * The MSB is used to create the falling edge of the triangle by inverting * the lower 11 bits. The MSB is thrown away and the lower 11 bits are * left-shifted (half the resolution, full amplitude). * Ring modulation substitutes the MSB with MSB EOR NOT sync_source MSB. * * * - Sawtooth: * The output is identical to the upper 12 bits of the accumulator. * * * - Pulse: * The upper 12 bits of the accumulator are used. * These bits are compared to the pulse width register by a 12 bit digital * comparator; output is either all one or all zero bits. * The pulse setting is delayed one cycle after the compare. * The test bit, when set to one, holds the pulse waveform output at 0xfff * regardless of the pulse width setting. * * * - Noise: * The noise output is taken from intermediate bits of a 23-bit shift register * which is clocked by bit 19 of the accumulator. * The shift is delayed 2 cycles after bit 19 is set high. * * Operation: Calculate EOR result, shift register, set bit 0 = result. * * reset +--------------------------------------------+ * | | | * test--OR-->EOR<--+ | * | | | * 2 2 2 1 1 1 1 1 1 1 1 1 1 | * Register bits: 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 <---+ * | | | | | | | | * Waveform bits: 1 1 9 8 7 6 5 4 * 1 0 * * The low 4 waveform bits are zero (grounded). */ class WaveformGenerator { private: matrix_t* model_wave; matrix_t* model_pulldown; short* wave; short* pulldown; // PWout = (PWn/40.95)% unsigned int pw; unsigned int shift_register; /// Shift register is latched when transitioning to shift phase 1. unsigned int shift_latch; /// Emulation of pipeline causing bit 19 to clock the shift register. int shift_pipeline; unsigned int ring_msb_mask; unsigned int no_noise; unsigned int noise_output; unsigned int no_noise_or_noise_output; unsigned int no_pulse; unsigned int pulse_output; /// The control register right-shifted 4 bits; used for output function table lookup. unsigned int waveform; unsigned int waveform_output; /// Current accumulator value. unsigned int accumulator; // Fout = (Fn*Fclk/16777216)Hz unsigned int freq; /// 8580 tri/saw pipeline unsigned int tri_saw_pipeline; /// The OSC3 value unsigned int osc3; /// Remaining time to fully reset shift register. unsigned int shift_register_reset; // The wave signal TTL when no waveform is selected. unsigned int floating_output_ttl; /// The control register bits. Gate is handled by EnvelopeGenerator. //@{ bool test; bool sync; //@} /// Test bit is latched at phi2 for the noise XOR. bool test_or_reset; /// Tell whether the accumulator MSB was set high on this cycle. bool msb_rising; bool is6581; //-V730_NOINIT this is initialized in the SID constructor private: void shift_phase2(unsigned int waveform_old, unsigned int waveform_new); void write_shift_register(); void set_noise_output(); void set_no_noise_or_noise_output(); void waveBitfade(); void shiftregBitfade(); public: void setWaveformModels(matrix_t* models); void setPulldownModels(matrix_t* models); /** * Set the chip model. * Must be called before any operation. * * @param is6581 true if MOS6581, false if CSG8580 */ void setModel(bool is6581) { this->is6581 = is6581; } /** * SID clocking. */ void clock(); /** * Synchronize oscillators. * This must be done after all the oscillators have been clock()'ed, * so that they are in the same state. * * @param syncDest The oscillator that will be synced * @param syncSource The sync source oscillator */ void synchronize(WaveformGenerator* syncDest, const WaveformGenerator* syncSource) const; /** * Constructor. */ WaveformGenerator() : model_wave(nullptr), model_pulldown(nullptr), wave(nullptr), pulldown(nullptr), pw(0), shift_register(0), shift_pipeline(0), ring_msb_mask(0), no_noise(0), noise_output(0), no_noise_or_noise_output(0), no_pulse(0), pulse_output(0), waveform(0), waveform_output(0), accumulator(0x555555), // Accumulator's even bits are high on powerup freq(0), tri_saw_pipeline(0x555), osc3(0), shift_register_reset(0), floating_output_ttl(0), test(false), sync(false), msb_rising(false) {} /** * Write FREQ LO register. * * @param freq_lo low 8 bits of frequency */ void writeFREQ_LO(unsigned char freq_lo) { freq = (freq & 0xff00) | (freq_lo & 0xff); } /** * Write FREQ HI register. * * @param freq_hi high 8 bits of frequency */ void writeFREQ_HI(unsigned char freq_hi) { freq = (freq_hi << 8 & 0xff00) | (freq & 0xff); } /** * Write PW LO register. * * @param pw_lo low 8 bits of pulse width */ void writePW_LO(unsigned char pw_lo) { pw = (pw & 0xf00) | (pw_lo & 0x0ff); } /** * Write PW HI register. * * @param pw_hi high 8 bits of pulse width */ void writePW_HI(unsigned char pw_hi) { pw = (pw_hi << 8 & 0xf00) | (pw & 0x0ff); } /** * Write CONTROL REGISTER register. * * @param control control register value */ void writeCONTROL_REG(unsigned char control); /** * SID reset. */ void reset(); /** * 12-bit waveform output. * * @param ringModulator The oscillator ring-modulating current one. * @return the waveform generator digital output */ unsigned int output(const WaveformGenerator* ringModulator); /** * Read OSC3 value. */ unsigned char readOSC() const { return static_cast<unsigned char>(osc3 >> 4); } /** * Read accumulator value. */ unsigned int readAccumulator() const { return accumulator; } /** * Read freq value. */ unsigned int readFreq() const { return freq; } /** * Read test value. */ bool readTest() const { return test; } /** * Read sync value. */ bool readSync() const { return sync; } }; } // namespace reSIDfp #if RESID_INLINING || defined(WAVEFORMGENERATOR_CPP) namespace reSIDfp { RESID_INLINE void WaveformGenerator::clock() { if (unlikely(test)) { if (unlikely(shift_register_reset != 0) && unlikely(--shift_register_reset == 0)) { #ifdef TRACE std::cout << "shiftregBitfade" << std::endl; #endif shiftregBitfade(); shift_latch = shift_register; // New noise waveform output. set_noise_output(); } // Latch the test bit value for shift phase 2. test_or_reset = true; // The test bit sets pulse high. pulse_output = 0xfff; } else { // Calculate new accumulator value; const unsigned int accumulator_old = accumulator; accumulator = (accumulator + freq) & 0xffffff; // Check which bit have changed from low to high const unsigned int accumulator_bits_set = ~accumulator_old & accumulator; // Check whether the MSB is set high. This is used for synchronization. msb_rising = (accumulator_bits_set & 0x800000) != 0; // Shift noise register once for each time accumulator bit 19 is set high. // The shift is delayed 2 cycles. if (unlikely((accumulator_bits_set & 0x080000) != 0)) { // Pipeline: Detect rising bit, shift phase 1, shift phase 2. shift_pipeline = 2; } else if (unlikely(shift_pipeline != 0)) { switch (--shift_pipeline) { case 0: #ifdef TRACE std::cout << "shift phase 2" << std::endl; #endif shift_phase2(waveform, waveform); break; case 1: #ifdef TRACE std::cout << "shift phase 1" << std::endl; #endif // Start shift phase 1. test_or_reset = false; shift_latch = shift_register; break; } } } } RESID_INLINE unsigned int WaveformGenerator::output(const WaveformGenerator* ringModulator) { // Set output value. if (likely(waveform != 0)) { const unsigned int ix = (accumulator ^ (~ringModulator->accumulator & ring_msb_mask)) >> 12; // The bit masks no_pulse and no_noise are used to achieve branch-free // calculation of the output value. waveform_output = wave[ix] & (no_pulse | pulse_output) & no_noise_or_noise_output; if (pulldown != nullptr) waveform_output = pulldown[waveform_output]; // Triangle/Sawtooth output is delayed half cycle on 8580. // This will appear as a one cycle delay on OSC3 as it is latched // in the first phase of the clock. if ((waveform & 3) && !is6581) { osc3 = tri_saw_pipeline & (no_pulse | pulse_output) & no_noise_or_noise_output; if (pulldown != nullptr) osc3 = pulldown[osc3]; tri_saw_pipeline = wave[ix]; } else { osc3 = waveform_output; } // In the 6581 the top bit of the accumulator may be driven low by combined waveforms // when the sawtooth is selected if (is6581 && (waveform & 0x2) && ((waveform_output & 0x800) == 0)) accumulator &= 0x7fffff; write_shift_register(); } else { // Age floating DAC input. if (likely(floating_output_ttl != 0) && unlikely(--floating_output_ttl == 0)) { waveBitfade(); } } // The pulse level is defined as (accumulator >> 12) >= pw ? 0xfff : 0x000. // The expression -((accumulator >> 12) >= pw) & 0xfff yields the same // results without any branching (and thus without any pipeline stalls). // NB! This expression relies on that the result of a boolean expression // is either 0 or 1, and furthermore requires two's complement integer. // A few more cycles may be saved by storing the pulse width left shifted // 12 bits, and dropping the and with 0xfff (this is valid since pulse is // used as a bit mask on 12 bit values), yielding the expression // -(accumulator >= pw24). However this only results in negligible savings. // The result of the pulse width compare is delayed one cycle. // Push next pulse level into pulse level pipeline. pulse_output = ((accumulator >> 12) >= pw) ? 0xfff : 0x000; return waveform_output; } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/WaveformGenerator.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,061
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define FILTER6581_CPP #include "Filter6581.h" #include "Integrator6581.h" namespace reSIDfp { Filter6581::~Filter6581() { delete [] f0_dac; } void Filter6581::updatedCenterFrequency() { const unsigned short Vw = f0_dac[fc]; hpIntegrator->setVw(Vw); bpIntegrator->setVw(Vw); } void Filter6581::updatedMixing() { currentGain = gain_vol[vol]; unsigned int ni = 0; unsigned int no = 0; (filt1 ? ni : no)++; (filt2 ? ni : no)++; if (filt3) ni++; else if (!voice3off) no++; (filtE ? ni : no)++; currentSummer = summer[ni]; if (lp) no++; if (bp) no++; if (hp) no++; currentMixer = mixer[no]; } void Filter6581::setFilterCurve(double curvePosition) { delete [] f0_dac; f0_dac = FilterModelConfig6581::getInstance()->getDAC(curvePosition); updatedCenterFrequency(); } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/Filter6581.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
396
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "FilterModelConfig.h" #include <vector> namespace reSIDfp { FilterModelConfig::FilterModelConfig( double vvr, double vdv, double c, double vdd, double vth, double ucox, const Spline::Point *opamp_voltage, int opamp_size ) : voice_voltage_range(vvr), voice_DC_voltage(vdv), C(c), Vdd(vdd), Vth(vth), Ut(26.0e-3), uCox(ucox), Vddt(Vdd - Vth), vmin(opamp_voltage[0].x), vmax(std::max(Vddt, opamp_voltage[0].y)), denorm(vmax - vmin), norm(1.0 / denorm), N16(norm * ((1 << 16) - 1)), currFactorCoeff(denorm * (uCox / 2. * 1.0e-6 / C)) { // Convert op-amp voltage transfer to 16 bit values. std::vector<Spline::Point> scaled_voltage(opamp_size); for (int i = 0; i < opamp_size; i++) { scaled_voltage[i].x = N16 * (opamp_voltage[i].x - opamp_voltage[i].y) / 2.; // We add 32768 to get a positive number in the range [0-65535] scaled_voltage[i].x += static_cast<double>(1u << 15); scaled_voltage[i].y = N16 * (opamp_voltage[i].x - vmin); } // Create lookup table mapping capacitor voltage to op-amp input voltage: Spline s(scaled_voltage); for (int x = 0; x < (1 << 16); x++) { const Spline::Point out = s.evaluate(x); // When interpolating outside range the first elements may be negative double tmp = out.x > 0. ? out.x : 0.; assert(tmp < 65535.5); opamp_rev[x] = static_cast<unsigned short>(tmp + 0.5); } } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/FilterModelConfig.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
609
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef VOICE_H #define VOICE_H #include <memory> #include "siddefs-fp.h" #include "WaveformGenerator.h" #include "EnvelopeGenerator.h" #include "sidcxx11.h" namespace reSIDfp { /** * Representation of SID voice block. */ class Voice { private: std::unique_ptr<WaveformGenerator> const waveformGenerator; std::unique_ptr<EnvelopeGenerator> const envelopeGenerator; /// The DAC LUT for analog waveform output float* wavDAC; //-V730_NOINIT this is initialized in the SID constructor /// The DAC LUT for analog envelope output float* envDAC; //-V730_NOINIT this is initialized in the SID constructor public: /** * Amplitude modulated waveform output. * * The waveform DAC generates a voltage between virtual ground and Vdd * (5-12 V for the 6581 and 4.75-9 V for the 8580) * corresponding to oscillator state 0 .. 4095. * * The envelope DAC generates a voltage between waveform gen output and * the virtual ground level, corresponding to envelope state 0 .. 255. * * Ideal range [-2048*255, 2047*255]. * * @param ringModulator Ring-modulator for waveform * @return the voice analog output */ RESID_INLINE int output(const WaveformGenerator* ringModulator) const { unsigned int const wav = waveformGenerator->output(ringModulator); unsigned int const env = envelopeGenerator->output(); // DAC imperfections are emulated by using the digital output // as an index into a DAC lookup table. return static_cast<int>(wavDAC[wav] * envDAC[env]); } /** * Constructor. */ Voice() : waveformGenerator(new WaveformGenerator()), envelopeGenerator(new EnvelopeGenerator()) {} /** * Set the analog DAC emulation for waveform generator. * Must be called before any operation. * * @param dac */ void setWavDAC(float* dac) { wavDAC = dac; } /** * Set the analog DAC emulation for envelope. * Must be called before any operation. * * @param dac */ void setEnvDAC(float* dac) { envDAC = dac; } WaveformGenerator* wave() const { return waveformGenerator.get(); } EnvelopeGenerator* envelope() const { return envelopeGenerator.get(); } /** * Write control register. * * @param control Control register value. */ void writeCONTROL_REG(unsigned char control) { waveformGenerator->writeCONTROL_REG(control); envelopeGenerator->writeCONTROL_REG(control); } /** * SID reset. */ void reset() { waveformGenerator->reset(); envelopeGenerator->reset(); } }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/Voice.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
762
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Dac.h" namespace reSIDfp { Dac::Dac(unsigned int bits) : dac(new double[bits]), dacLength(bits) {} Dac::~Dac() { delete [] dac; } double Dac::getOutput(unsigned int input) const { double dacValue = 0.; for (unsigned int i = 0; i < dacLength; i++) { if ((input & (1 << i)) != 0) { dacValue += dac[i]; } } return dacValue; } void Dac::kinkedDac(ChipModel chipModel) { const double R_INFINITY = 1e6; // Non-linearity parameter, 8580 DACs are perfectly linear const double _2R_div_R = chipModel == MOS6581 ? 2.20 : 2.00; // 6581 DACs are not terminated by a 2R resistor const bool term = chipModel == MOS8580; // Calculate voltage contribution by each individual bit in the R-2R ladder. for (unsigned int set_bit = 0; set_bit < dacLength; set_bit++) { double Vn = 1.; // Normalized bit voltage. double R = 1.; // Normalized R const double _2R = _2R_div_R * R; // 2R double Rn = term ? // Rn = 2R for correct termination, _2R : R_INFINITY; // INFINITY for missing termination. unsigned int bit; // Calculate DAC "tail" resistance by repeated parallel substitution. for (bit = 0; bit < set_bit; bit++) { Rn = (Rn == R_INFINITY) ? R + _2R : R + (_2R * Rn) / (_2R + Rn); // R + 2R || Rn } // Source transformation for bit voltage. if (Rn == R_INFINITY) { Rn = _2R; } else { Rn = (_2R * Rn) / (_2R + Rn); // 2R || Rn Vn = Vn * Rn / _2R; } // Calculate DAC output voltage by repeated source transformation from // the "tail". for (++bit; bit < dacLength; bit++) { Rn += R; const double I = Vn / Rn; Rn = (_2R * Rn) / (_2R + Rn); // 2R || Rn Vn = Rn * I; } dac[set_bit] = Vn; } // Normalize to integerish behavior double Vsum = 0.; for (unsigned int i = 0; i < dacLength; i++) { Vsum += dac[i]; } Vsum /= 1 << dacLength; for (unsigned int i = 0; i < dacLength; i++) { dac[i] /= Vsum; } } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/Dac.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
823
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef INTEGRATOR6581_H #define INTEGRATOR6581_H #include "FilterModelConfig6581.h" #include <stdint.h> #include <cassert> // uncomment to enable use of the slope factor // in the EKV model // actually produces worse results, needs investigation //#define SLOPE_FACTOR #ifdef SLOPE_FACTOR # include <cmath> #endif #include "siddefs-fp.h" namespace reSIDfp { /** * Find output voltage in inverting integrator SID op-amp circuits, using a * single fixpoint iteration step. * * A circuit diagram of a MOS 6581 integrator is shown below. * * +---C---+ * | | * vi --o--Rw--o-o--[A>--o-- vo * | | vx * +--Rs--+ * * From Kirchoff's current law it follows that * * IRw + IRs + ICr = 0 * * Using the formula for current through a capacitor, i = C*dv/dt, we get * * IRw + IRs + C*(vc - vc0)/dt = 0 * dt/C*(IRw + IRs) + vc - vc0 = 0 * vc = vc0 - n*(IRw(vi,vx) + IRs(vi,vx)) * * which may be rewritten as the following iterative fixpoint function: * * vc = vc0 - n*(IRw(vi,g(vc)) + IRs(vi,g(vc))) * * To accurately calculate the currents through Rs and Rw, we need to use * transistor models. Rs has a gate voltage of Vdd = 12V, and can be * assumed to always be in triode mode. For Rw, the situation is rather * more complex, as it turns out that this transistor will operate in * both subthreshold, triode, and saturation modes. * * The Shichman-Hodges transistor model routinely used in textbooks may * be written as follows: * * Ids = 0 , Vgst < 0 (subthreshold mode) * Ids = K*W/L*(2*Vgst - Vds)*Vds , Vgst >= 0, Vds < Vgst (triode mode) * Ids = K*W/L*Vgst^2 , Vgst >= 0, Vds >= Vgst (saturation mode) * * where * K = u*Cox/2 (transconductance coefficient) * W/L = ratio between substrate width and length * Vgst = Vg - Vs - Vt (overdrive voltage) * * This transistor model is also called the quadratic model. * * Note that the equation for the triode mode can be reformulated as * independent terms depending on Vgs and Vgd, respectively, by the * following substitution: * * Vds = Vgst - (Vgst - Vds) = Vgst - Vgdt * * Ids = K*W/L*(2*Vgst - Vds)*Vds * = K*W/L*(2*Vgst - (Vgst - Vgdt)*(Vgst - Vgdt) * = K*W/L*(Vgst + Vgdt)*(Vgst - Vgdt) * = K*W/L*(Vgst^2 - Vgdt^2) * * This turns out to be a general equation which covers both the triode * and saturation modes (where the second term is 0 in saturation mode). * The equation is also symmetrical, i.e. it can calculate negative * currents without any change of parameters (since the terms for drain * and source are identical except for the sign). * * FIXME: Subthreshold as function of Vgs, Vgd. * * Ids = I0*W/L*e^(Vgst/(Ut/k)) , Vgst < 0 (subthreshold mode) * * where * I0 = (2 * uCox * Ut^2) / k * * The remaining problem with the textbook model is that the transition * from subthreshold to triode/saturation is not continuous. * * Realizing that the subthreshold and triode/saturation modes may both * be defined by independent (and equal) terms of Vgs and Vds, * respectively, the corresponding terms can be blended into (equal) * continuous functions suitable for table lookup. * * The EKV model (Enz, Krummenacher and Vittoz) essentially performs this * blending using an elegant mathematical formulation: * * Ids = Is * (if - ir) * Is = ((2 * u*Cox * Ut^2)/k) * W/L * if = ln^2(1 + e^((k*(Vg - Vt) - Vs)/(2*Ut)) * ir = ln^2(1 + e^((k*(Vg - Vt) - Vd)/(2*Ut)) * * For our purposes, the EKV model preserves two important properties * discussed above: * * - It consists of two independent terms, which can be represented by * the same lookup table. * - It is symmetrical, i.e. it calculates current in both directions, * facilitating a branch-free implementation. * * Rw in the circuit diagram above is a VCR (voltage controlled resistor), * as shown in the circuit diagram below. * * * Vdd * | * Vdd _|_ * | +---+ +---- Vw * _|_ | * +--+ +---o Vg * | __|__ * | ----- Rw * | | | * vi -----o------+ +-------- vo * * * In order to calculalate the current through the VCR, its gate voltage * must be determined. * * Assuming triode mode and applying Kirchoff's current law, we get the * following equation for Vg: * * u*Cox/2*W/L*((nVddt - Vg)^2 - (nVddt - vi)^2 + (nVddt - Vg)^2 - (nVddt - Vw)^2) = 0 * 2*(nVddt - Vg)^2 - (nVddt - vi)^2 - (nVddt - Vw)^2 = 0 * (nVddt - Vg) = sqrt(((nVddt - vi)^2 + (nVddt - Vw)^2)/2) * * Vg = nVddt - sqrt(((nVddt - vi)^2 + (nVddt - Vw)^2)/2) */ class Integrator6581 { private: unsigned int nVddt_Vw_2; mutable int vx; mutable int vc; #ifdef SLOPE_FACTOR // Slope factor n = 1/k // where k is the gate coupling coefficient // k = Cox/(Cox+Cdep) ~ 0.7 (depends on gate voltage) mutable double n; #endif const unsigned short nVddt; const unsigned short nVt; const unsigned short nVmin; const unsigned short nSnake; const FilterModelConfig6581* fmc; public: Integrator6581(const FilterModelConfig6581* fmc, double WL_snake) : nVddt_Vw_2(0), vx(0), vc(0), #ifdef SLOPE_FACTOR n(1.4), #endif nVddt(fmc->getNormalizedValue(fmc->getVddt())), nVt(fmc->getNormalizedValue(fmc->getVth())), nVmin(fmc->getNVmin()), nSnake(fmc->getNormalizedCurrentFactor(WL_snake)), fmc(fmc) {} void setVw(unsigned short Vw) { nVddt_Vw_2 = ((nVddt - Vw) * (nVddt - Vw)) >> 1; } int solve(int vi) const; }; } // namespace reSIDfp #if RESID_INLINING || defined(INTEGRATOR_CPP) namespace reSIDfp { RESID_INLINE int Integrator6581::solve(int vi) const { // Make sure Vgst>0 so we're not in subthreshold mode assert(vx < nVddt); // Check that transistor is actually in triode mode // Vds < Vgs - Vth assert(vi < nVddt); // "Snake" voltages for triode mode calculation. const unsigned int Vgst = nVddt - vx; const unsigned int Vgdt = nVddt - vi; const unsigned int Vgst_2 = Vgst * Vgst; const unsigned int Vgdt_2 = Vgdt * Vgdt; // "Snake" current, scaled by (1/m)*2^13*m*2^16*m*2^16*2^-15 = m*2^30 const int n_I_snake = nSnake * (static_cast<int>(Vgst_2 - Vgdt_2) >> 15); // VCR gate voltage. // Scaled by m*2^16 // Vg = Vddt - sqrt(((Vddt - Vw)^2 + Vgdt^2)/2) const int nVg = static_cast<int>(fmc->getVcr_nVg((nVddt_Vw_2 + (Vgdt_2 >> 1)) >> 16)); #ifdef SLOPE_FACTOR const double nVp = static_cast<double>(nVg - nVt) / n; // Pinch-off voltage const int kVgt = static_cast<int>(nVp + 0.5) - nVmin; #else const int kVgt = (nVg - nVt) - nVmin; #endif // VCR voltages for EKV model table lookup. const int kVgt_Vs = (vx < kVgt) ? kVgt - vx : 0; assert(kVgt_Vs < (1 << 16)); const int kVgt_Vd = (vi < kVgt) ? kVgt - vi : 0; assert(kVgt_Vd < (1 << 16)); // VCR current, scaled by m*2^15*2^15 = m*2^30 const unsigned int If = static_cast<unsigned int>(fmc->getVcr_n_Ids_term(kVgt_Vs)) << 15; const unsigned int Ir = static_cast<unsigned int>(fmc->getVcr_n_Ids_term(kVgt_Vd)) << 15; #ifdef SLOPE_FACTOR const double iVcr = static_cast<double>(If - Ir); const int n_I_vcr = static_cast<int>(iVcr * n); #else const int n_I_vcr = If - Ir; #endif #ifdef SLOPE_FACTOR // estimate new slope factor based on gate voltage const double gamma = 1.0; // body effect factor const double phi = 0.8; // bulk Fermi potential const double Vp = nVp / fmc->getN16(); n = 1. + (gamma / (2. * sqrt(Vp + phi + 4. * fmc->getUt()))); assert((n > 1.2) && (n < 1.8)); #endif // Change in capacitor charge. vc += n_I_snake + n_I_vcr; // vx = g(vc) const int tmp = (vc >> 15) + (1 << 15); assert(tmp < (1 << 16)); vx = fmc->getOpampRev(tmp); // Return vo. return vx - (vc >> 14); } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/Integrator6581.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,797
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define EXTERNALFILTER_CPP #include "ExternalFilter.h" namespace reSIDfp { /** * Get the 3 dB attenuation point. * * @param res the resistance value in Ohms * @param cap the capacitance value in Farads */ inline double getRC(double res, double cap) { return res * cap; } ExternalFilter::ExternalFilter() : w0lp_1_s7(0), w0hp_1_s17(0) { reset(); } void ExternalFilter::setClockFrequency(double frequency) { const double dt = 1. / frequency; // Low-pass: R = 10kOhm, C = 1000pF; w0l = dt/(dt+RC) = 1e-6/(1e-6+1e4*1e-9) = 0.091 // Cutoff 1/2*PI*RC = 1/2*PI*1e4*1e-9 = 15915.5 Hz w0lp_1_s7 = static_cast<int>((dt / (dt + getRC(10e3, 1000e-12))) * (1 << 7) + 0.5); // High-pass: R = 10kOhm, C = 10uF; w0h = dt/(dt+RC) = 1e-6/(1e-6+1e4*1e-5) = 0.00000999 // Cutoff 1/2*PI*RC = 1/2*PI*1e4*1e-5 = 1.59155 Hz w0hp_1_s17 = static_cast<int>((dt / (dt + getRC(10e3, 10e-6))) * (1 << 17) + 0.5); } void ExternalFilter::reset() { // State of filter. Vlp = 0; //1 << (15 + 11); Vhp = 0; } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/ExternalFilter.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
581
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef DAC_H #define DAC_H #include "siddefs-fp.h" namespace reSIDfp { /** * Estimate DAC nonlinearity. * The SID DACs are built up as R-2R ladder as follows: * * n n-1 2 1 0 VGND * | | | | | | Termination * 2R 2R 2R 2R 2R 2R only for * | | | | | | MOS 8580 * Vo -o-R-o-R-...-o-R-o-R-- --+ * * * All MOS 6581 DACs are missing a termination resistor at bit 0. This causes * pronounced errors for the lower 4 - 5 bits (e.g. the output for bit 0 is * actually equal to the output for bit 1), resulting in DAC discontinuities * for the lower bits. * In addition to this, the 6581 DACs exhibit further severe discontinuities * for higher bits, which may be explained by a less than perfect match between * the R and 2R resistors, or by output impedance in the NMOS transistors * providing the bit voltages. A good approximation of the actual DAC output is * achieved for 2R/R ~ 2.20. * * The MOS 8580 DACs, on the other hand, do not exhibit any discontinuities. * These DACs include the correct termination resistor, and also seem to have * very accurately matched R and 2R resistors (2R/R = 2.00). * * On the 6581 the output of the waveform and envelope DACs go through * a voltage follower built with two NMOS: * * Vdd * * | * |-+ * Vin -------| T1 (enhancement-mode) * |-+ * | * o-------- Vout * | * |-+ * +---| T2 (depletion-mode) * | |-+ * | | * * GND GND */ class Dac { private: /// analog values double * const dac; /// the dac array length const unsigned int dacLength; public: /** * Initialize DAC model. * * @param bits the number of input bits */ Dac(unsigned int bits); ~Dac(); /** * Build DAC model for specific chip. * * @param chipModel 6581 or 8580 */ void kinkedDac(ChipModel chipModel); /** * Get the Vo output for a given combination of input bits. * * @param input the digital input * @return the analog output value */ double getOutput(unsigned int input) const; }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/Dac.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
780
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SIDCXX_H #define SIDCXX_H #ifdef HAVE_CONFIG_H # include "config.h" #endif #define HAVE_CXX11 true #ifdef HAVE_CXX17 # define HAVE_CXX14 # define MAYBE_UNUSED [[ maybe_unused ]] #else # define MAYBE_UNUSED #endif #ifdef HAVE_CXX14 # define HAVE_CXX11 # define MAKE_UNIQUE(type, ...) std::make_unique<type>(__VA_ARGS__) #else # define MAKE_UNIQUE(type, ...) std::unique_ptr<type>(new type(__VA_ARGS__)) #endif #ifndef HAVE_CXX11 # define nullptr 0 # define override # define final # define unique_ptr auto_ptr # define DEFAULT {} # define DELETE {} #else # define DEFAULT = default # define DELETE = delete #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/sidcxx11.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
325
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define INTEGRATOR8580_CPP #include "Integrator8580.h" // This is needed when compiling with --disable-inline ```
/content/code_sandbox/src/sound/resid-fp/Integrator8580.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
156
```c++ // your_sha256_hash----------- // This file is part of reSID, a MOS6581 SID emulator engine. // // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // your_sha256_hash----------- #define __VERSION_CC__ #include "siddefs-fp.h" ```
/content/code_sandbox/src/sound/resid-fp/version.cc
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
162
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILTER8580_H #define FILTER8580_H #include "siddefs-fp.h" #include <memory> #include "Filter.h" #include "FilterModelConfig8580.h" #include "Integrator8580.h" #include "sidcxx11.h" namespace reSIDfp { class Integrator8580; /** * Filter for 8580 chip * -------------------- * The 8580 filter stage had been redesigned to be more linear and robust * against temperature change. It also features real op-amps and a * revisited resonance model. * The filter schematics below are reverse engineered from re-vectorized * and annotated die photographs. Credits to Michael Huth for the microscope * photographs of the die, Tommi Lempinen for re-vectorizating and annotating * the images and ttlworks from forum.6502.org for the circuit analysis. * * ~~~ * * +---------------------------------------------------+ * | $17 +----Rf-+ | * | | | | * | D4&!D5 o- \-R3-o | * | | | $17 | * | !D4&!D5 o- \-R2-o | * | | | +---R8-- \--+ !D6&D7 | * | D4&!D5 o- \-R1-o | | | * | | | o---RC-- \--o D6&D7 | * | +---------o--<A]--o--o | | * | | o---R4-- \--o D6&!D7 | * | | | | | * | | +---Ri-- \--o !D6&!D7 | * | | | | * $17 | | (CAP2B) | (CAP1B) | * 0=to mixer | +--R7--+ +---R7--+ +---C---o +---C---o * 1=to filter | | | | | | | | * +------R7--o--o--[A>--o--Rfc-o--[A>--o--Rfc-o--[A>--o * ve (EXT IN) | | | | * D3 \ --------------R12--o | | (CAP2A) | (CAP1A) * | v3 | | vhp | vbp | vlp * D2 | \ -----------R7--o +-----+ | | * | | v2 | | | | * D1 | | \ -------R7--o | +----------------+ | * | | | v1 | | | | * D0 | | | \ ---R7--+ | | +---------------------------+ * | | | | | | | * R9 R5 R5 R5 R5 R5 R5 * | | | | $18 | | | $18 * | \ | | D7: 1=open \ \ \ D6 - D4: 0=open * | | | | | | | * +---o---o---o-------------o---o---+ * | * | D3 +--/ --1R4--+ * | +---R8--+ | | +---R2--+ * | | | D2 o--/ --2R4--o | | * +---o--[A>--o------o o--o--[A>--o-- vo (AUDIO OUT) * D1 o--/ --4R4--o * $18 | | * 0=open D0 +--/ --8R4--+ * * * * Resonance * --------- * For resonance, we have two tiny DACs that controls both the input * and feedback resistances. * * The "resistors" are switched in as follows by bits in register $17: * * feedback: * R1: bit4&!bit5 * R2: !bit4&bit5 * R3: bit4&bit5 * Rf: always on * * input: * R4: bit6&!bit7 * R8: !bit6&bit7 * RC: bit6&bit7 * Ri: !(R4|R8|RC) = !(bit6|bit7) = !bit6&!bit7 * * * The relative "resistor" values are approximately (using channel length): * * R1 = 15.3*Ri * R2 = 7.3*Ri * R3 = 4.7*Ri * Rf = 1.4*Ri * R4 = 1.4*Ri * R8 = 2.0*Ri * RC = 2.8*Ri * * * Approximate values for 1/Q can now be found as follows (assuming an * ideal op-amp): * * res feedback input -gain (1/Q) * --- -------- ----- ---------- * 0 Rf Ri Rf/Ri = 1/(Ri*(1/Rf)) = 1/0.71 * 1 Rf|R1 Ri (Rf|R1)/Ri = 1/(Ri*(1/Rf+1/R1)) = 1/0.78 * 2 Rf|R2 Ri (Rf|R2)/Ri = 1/(Ri*(1/Rf+1/R2)) = 1/0.85 * 3 Rf|R3 Ri (Rf|R3)/Ri = 1/(Ri*(1/Rf+1/R3)) = 1/0.92 * 4 Rf R4 Rf/R4 = 1/(R4*(1/Rf)) = 1/1.00 * 5 Rf|R1 R4 (Rf|R1)/R4 = 1/(R4*(1/Rf+1/R1)) = 1/1.10 * 6 Rf|R2 R4 (Rf|R2)/R4 = 1/(R4*(1/Rf+1/R2)) = 1/1.20 * 7 Rf|R3 R4 (Rf|R3)/R4 = 1/(R4*(1/Rf+1/R3)) = 1/1.30 * 8 Rf R8 Rf/R8 = 1/(R8*(1/Rf)) = 1/1.43 * 9 Rf|R1 R8 (Rf|R1)/R8 = 1/(R8*(1/Rf+1/R1)) = 1/1.56 * A Rf|R2 R8 (Rf|R2)/R8 = 1/(R8*(1/Rf+1/R2)) = 1/1.70 * B Rf|R3 R8 (Rf|R3)/R8 = 1/(R8*(1/Rf+1/R3)) = 1/1.86 * C Rf RC Rf/RC = 1/(RC*(1/Rf)) = 1/2.00 * D Rf|R1 RC (Rf|R1)/RC = 1/(RC*(1/Rf+1/R1)) = 1/2.18 * E Rf|R2 RC (Rf|R2)/RC = 1/(RC*(1/Rf+1/R2)) = 1/2.38 * F Rf|R3 RC (Rf|R3)/RC = 1/(RC*(1/Rf+1/R3)) = 1/2.60 * * * These data indicate that the following function for 1/Q has been * modeled in the MOS 8580: * * 1/Q = 2^(1/2)*2^(-x/8) = 2^(1/2 - x/8) = 2^((4 - x)/8) * * * * Op-amps * ------- * Unlike the 6581, the 8580 has real OpAmps. * * Temperature compensated differential amplifier: * * 9V * * | * +-------o-o-o-------+ * | | | | * | R R | * +--|| | | ||--+ * ||---o o---|| * +--|| | | ||--+ * | | | | * o-----+ | | o--- Va * | | | | | * +--|| | | | ||--+ * ||-o-+---+---|| * +--|| | | ||--+ * | | | | * | | * GND | | GND * ||--+ +--|| * in- -----|| ||------ in+ * ||----o----|| * | * 8 Current sink * | * * GND * * Inverter + non-inverting output amplifier: * * Va ---o---||-------------------o--------------------+ * | | 9V | * | +----------+----------+ | | * | 9V | | 9V | ||--+ | * | | | 9V | | +-|| | * | R | | | ||--+ ||--+ | * | | | ||--+ +--|| o---o--- Vout * | o---o---|| ||--+ ||--+ * | | ||--+ o-----|| * | ||--+ | ||--+ ||--+ * +-----|| o-----|| | * ||--+ | ||--+ * | R | GND * | * GND GND * GND * * * * Virtual ground * -------------- * A PolySi resitive voltage divider provides the voltage * for the positive input of the filter op-amps. * * 5V * +----------+ * | | |\ | * R1 +---|-\ | * 5V | |A >---o--- Vref * o-------|+/ * | | |/ * R10 R4 * | | * o---+ * | * R10 * | * * GND * * Rn = n*R1 * * * * Rfc - freq control DAC resistance ladder * ---------------------------------------- * The 8580 has 11 bits for frequency control, but 12 bit DACs. * If those 11 bits would be '0', the impedance of the DACs would be "infinitely high". * To get around this, there is an 11 input NOR gate below the DACs sensing those 11 bits. * If all are 0, the NOR gate gives the gate control voltage to the 12 bit DAC LSB. * * ----o---o--...--o---o---o--- * | | | | | * Rb10 Rb9 ... Rb1 Rb0 R0 * | | | | | * ----o---o--...--o---o---o--- * * * * Crystal stabilized precision switched capacitor voltage divider * --------------------------------------------------------------- * There is a FET working as a temperature sensor close to the DACs which changes the gate voltage * of the frequency control DACs according to the temperature of the DACs, * to reduce the effects of temperature on the filter curve. * An asynchronous 3 bit binary counter, running at the speed of PHI2, drives two big capacitors * whose AC resistance is then used as a voltage divider. * This implicates that frequency difference between PAL and NTSC might shift the filter curve by 4% or such. * * |\ OpAmp has a smaller capacitor than the other OPs * Vref ---|+\ * |A >---o--- Vdac * +-------|-/ | * | |/ | * | | * C1 | C2 | * +---||---o---+ +---o-----||-------o * | | | | | | * o----+ | ----- | | * | | | ----- +----+ +-----o * | ----- | | | | * | ----- | ----- | * | | | ----- | * | +-----------+ | | * | /Q Q | +-------+ * GND +-----------+ FET close to DAC * | clk/8 | working as temperature sensor * +-----------+ */ class Filter8580 final : public Filter { private: unsigned short** mixer; unsigned short** summer; unsigned short** gain_res; unsigned short** gain_vol; const int voiceScaleS11; const int voiceDC; double cp; /// VCR + associated capacitor connected to highpass output. std::unique_ptr<Integrator8580> const hpIntegrator; /// VCR + associated capacitor connected to bandpass output. std::unique_ptr<Integrator8580> const bpIntegrator; protected: /** * Set filter cutoff frequency. */ void updatedCenterFrequency() override; /** * Set filter resonance. * * @param res the new resonance value */ void updateResonance(unsigned char res) override { currentResonance = gain_res[res]; } void updatedMixing() override; public: Filter8580() : mixer(FilterModelConfig8580::getInstance()->getMixer()), summer(FilterModelConfig8580::getInstance()->getSummer()), gain_res(FilterModelConfig8580::getInstance()->getGainRes()), gain_vol(FilterModelConfig8580::getInstance()->getGainVol()), voiceScaleS11(FilterModelConfig8580::getInstance()->getVoiceScaleS11()), voiceDC(FilterModelConfig8580::getInstance()->getNormalizedVoiceDC()), cp(0.5), hpIntegrator(FilterModelConfig8580::getInstance()->buildIntegrator()), bpIntegrator(FilterModelConfig8580::getInstance()->buildIntegrator()) { setFilterCurve(cp); input(0); } ~Filter8580(); unsigned short clock(int voice1, int voice2, int voice3) override; void input(int sample) override { ve = (sample * voiceScaleS11 * 3 >> 11) + mixer[0][0]; } /** * Set filter curve type based on single parameter. * * @param curvePosition 0 .. 1, where 0 sets center frequency high ("light") and 1 sets it low ("dark"), default is 0.5 */ void setFilterCurve(double curvePosition); }; } // namespace reSIDfp #if RESID_INLINING || defined(FILTER8580_CPP) namespace reSIDfp { RESID_INLINE unsigned short Filter8580::clock(int voice1, int voice2, int voice3) { voice1 = (voice1 * voiceScaleS11 >> 15) + voiceDC; voice2 = (voice2 * voiceScaleS11 >> 15) + voiceDC; // Voice 3 is silenced by voice3off if it is not routed through the filter. voice3 = (filt3 || !voice3off) ? (voice3 * voiceScaleS11 >> 15) + voiceDC : 0; int Vi = 0; int Vo = 0; (filt1 ? Vi : Vo) += voice1; (filt2 ? Vi : Vo) += voice2; (filt3 ? Vi : Vo) += voice3; (filtE ? Vi : Vo) += ve; Vhp = currentSummer[currentResonance[Vbp] + Vlp + Vi]; Vbp = hpIntegrator->solve(Vhp); Vlp = bpIntegrator->solve(Vbp); if (lp) Vo += Vlp; if (bp) Vo += Vbp; if (hp) Vo += Vhp; return currentGain[currentMixer[Vo]]; } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/Filter8580.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,990
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SPLINE_H #define SPLINE_H #include <cstddef> #include <vector> namespace reSIDfp { /** * Fritsch-Carlson monotone cubic spline interpolation. * * Based on the implementation from the [Monotone cubic interpolation] wikipedia page. * * [Monotone cubic interpolation]: path_to_url */ class Spline { public: typedef struct { double x; double y; } Point; private: typedef struct { double x1; double x2; double a; double b; double c; double d; } Param; typedef std::vector<Param> ParamVector; private: /// Interpolation parameters ParamVector params; /// Last used parameters, cached for speed up mutable ParamVector::const_pointer c; public: Spline(const std::vector<Point> &input); /** * Evaluate y and its derivative at given point x. */ Point evaluate(double x) const; }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/Spline.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
355
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ARRAY_H #define ARRAY_H #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef HAVE_CXX11 # include <atomic> #endif /** * Counter. */ class counter { private: #ifndef HAVE_CXX11 volatile unsigned int c; #else std::atomic<unsigned int> c; #endif public: counter() : c(1) {} void increase() { ++c; } unsigned int decrease() { return --c; } }; /** * Reference counted pointer to matrix wrapper, for use with standard containers. */ template<typename T> class matrix { private: T* data; counter* count; const unsigned int x, y; public: matrix(unsigned int x, unsigned int y) : data(new T[x * y]), count(new counter()), x(x), y(y) {} matrix(const matrix& p) : data(p.data), count(p.count), x(p.x), y(p.y) { count->increase(); } ~matrix() { if (count->decrease() == 0) { delete count; delete [] data; } } unsigned int length() const { return x * y; } T* operator[](unsigned int a) { return &data[a * y]; } T const* operator[](unsigned int a) const { return &data[a * y]; } }; typedef matrix<short> matrix_t; #endif ```
/content/code_sandbox/src/sound/resid-fp/array.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
441
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define FILTER8580_CPP #include "Filter8580.h" #include "Integrator8580.h" namespace reSIDfp { /** * W/L ratio of frequency DAC bit 0, * other bit are proportional. * When no bit are selected a resistance with half * W/L ratio is selected. */ const double DAC_WL0 = 0.00615; Filter8580::~Filter8580() {} void Filter8580::updatedCenterFrequency() { double wl; double dacWL = DAC_WL0; if (fc) { wl = 0.; for (unsigned int i = 0; i < 11; i++) { if (fc & (1 << i)) { wl += dacWL; } dacWL *= 2.; } } else { wl = dacWL/2.; } hpIntegrator->setFc(wl); bpIntegrator->setFc(wl); } void Filter8580::updatedMixing() { currentGain = gain_vol[vol]; unsigned int ni = 0; unsigned int no = 0; (filt1 ? ni : no)++; (filt2 ? ni : no)++; if (filt3) ni++; else if (!voice3off) no++; (filtE ? ni : no)++; currentSummer = summer[ni]; if (lp) no++; if (bp) no++; if (hp) no++; currentMixer = mixer[no]; } void Filter8580::setFilterCurve(double curvePosition) { // Adjust cp // 1.2 <= cp <= 1.8 cp = 1.8 - curvePosition * 3./5.; hpIntegrator->setV(cp); bpIntegrator->setV(cp); } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/Filter8580.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
534
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILTER6581_H #define FILTER6581_H #include "siddefs-fp.h" #include <memory> #include "Filter.h" #include "FilterModelConfig6581.h" #include "sidcxx11.h" namespace reSIDfp { class Integrator6581; /** * The SID filter is modeled with a two-integrator-loop biquadratic filter, * which has been confirmed by Bob Yannes to be the actual circuit used in * the SID chip. * * Measurements show that excellent emulation of the SID filter is achieved, * except when high resonance is combined with high sustain levels. * In this case the SID op-amps are performing less than ideally and are * causing some peculiar behavior of the SID filter. This however seems to * have more effect on the overall amplitude than on the color of the sound. * * The theory for the filter circuit can be found in "Microelectric Circuits" * by Adel S. Sedra and Kenneth C. Smith. * The circuit is modeled based on the explanation found there except that * an additional inverter is used in the feedback from the bandpass output, * allowing the summer op-amp to operate in single-ended mode. This yields * filter outputs with levels independent of Q, which corresponds with the * results obtained from a real SID. * * We have been able to model the summer and the two integrators of the circuit * to form components of an IIR filter. * Vhp is the output of the summer, Vbp is the output of the first integrator, * and Vlp is the output of the second integrator in the filter circuit. * * According to Bob Yannes, the active stages of the SID filter are not really * op-amps. Rather, simple NMOS inverters are used. By biasing an inverter * into its region of quasi-linear operation using a feedback resistor from * input to output, a MOS inverter can be made to act like an op-amp for * small signals centered around the switching threshold. * * In 2008, Michael Huth facilitated closer investigation of the SID 6581 * filter circuit by publishing high quality microscope photographs of the die. * Tommi Lempinen has done an impressive work on re-vectorizing and annotating * the die photographs, substantially simplifying further analysis of the * filter circuit. * * The filter schematics below are reverse engineered from these re-vectorized * and annotated die photographs. While the filter first depicted in reSID 0.9 * is a correct model of the basic filter, the schematics are now completed * with the audio mixer and output stage, including details on intended * relative resistor values. Also included are schematics for the NMOS FET * voltage controlled resistors (VCRs) used to control cutoff frequency, the * DAC which controls the VCRs, the NMOS op-amps, and the output buffer. * * * SID filter / mixer / output * --------------------------- * ~~~ * +---------------------------------------------------+ * | | * | +--1R1-- \--+ D7 | * | +---R1--+ | | | * | | | o--2R1-- \--o D6 | * | +---------o--<A]--o--o | $17 | * | | o--4R1-- \--o D5 1=open | (3.5R1) * | | | | | * | | +--8R1-- \--o D4 | (7.0R1) * | | | | * $17 | | (CAP2B) | (CAP1B) | * 0=to mixer | +--R8--+ +---R8--+ +---C---o +---C---o * 1=to filter | | | | | | | | * ------R8--o--o--[A>--o--Rw--o--[A>--o--Rw--o--[A>--o * ve (EXT IN) | | | | * D3 \ ---------------R8--o | | (CAP2A) | (CAP1A) * | v3 | | vhp | vbp | vlp * D2 | \ -----------R8--o +-----+ | | * | | v2 | | | | * D1 | | \ -------R8--o | +----------------+ | * | | | v1 | | | | * D0 | | | \ ---R8--+ | | +---------------------------+ * | | | | | | | * R6 R6 R6 R6 R6 R6 R6 * | | | | $18 | | | $18 * | \ | | D7: 1=open \ \ \ D6 - D4: 0=open * | | | | | | | * +---o---o---o-------------o---o---+ 12V * | * | D3 +--/ --1R2--+ | * | +---R8--+ | | +---R2--+ | * | | | D2 o--/ --2R2--o | | ||--+ * +---o--[A>--o------o o--o--[A>--o--|| * D1 o--/ --4R2--o (4.25R2) ||--+ * $18 | | | * 0=open D0 +--/ --8R2--+ (8.75R2) | * * vo (AUDIO * OUT) * * * v1 - voice 1 * v2 - voice 2 * v3 - voice 3 * ve - ext in * vhp - highpass output * vbp - bandpass output * vlp - lowpass output * vo - audio out * [A> - single ended inverting op-amp (self-biased NMOS inverter) * Rn - "resistors", implemented with custom NMOS FETs * Rw - cutoff frequency resistor (VCR) * C - capacitor * ~~~ * Notes: * * R2 ~ 2.0*R1 * R6 ~ 6.0*R1 * R8 ~ 8.0*R1 * R24 ~ 24.0*R1 * * The Rn "resistors" in the circuit are implemented with custom NMOS FETs, * probably because of space constraints on the SID die. The silicon substrate * is laid out in a narrow strip or "snake", with a strip length proportional * to the intended resistance. The polysilicon gate electrode covers the entire * silicon substrate and is fixed at 12V in order for the NMOS FET to operate * in triode mode (a.k.a. linear mode or ohmic mode). * * Even in "linear mode", an NMOS FET is only an approximation of a resistor, * as the apparant resistance increases with increasing drain-to-source * voltage. If the drain-to-source voltage should approach the gate voltage * of 12V, the NMOS FET will enter saturation mode (a.k.a. active mode), and * the NMOS FET will not operate anywhere like a resistor. * * * * NMOS FET voltage controlled resistor (VCR) * ------------------------------------------ * ~~~ * Vw * * | * | * R1 * | * +--R1--o * | __|__ * | ----- * | | | * vi -----o----+ +--o----- vo * | | * +----R24----+ * * * vi - input * vo - output * Rn - "resistors", implemented with custom NMOS FETs * Vw - voltage from 11-bit DAC (frequency cutoff control) * ~~~ * Notes: * * An approximate value for R24 can be found by using the formula for the * filter cutoff frequency: * * FCmin = 1/(2*pi*Rmax*C) * * Assuming that a the setting for minimum cutoff frequency in combination with * a low level input signal ensures that only negligible current will flow * through the transistor in the schematics above, values for FCmin and C can * be substituted in this formula to find Rmax. * Using C = 470pF and FCmin = 220Hz (measured value), we get: * * FCmin = 1/(2*pi*Rmax*C) * Rmax = 1/(2*pi*FCmin*C) = 1/(2*pi*220*470e-12) ~ 1.5MOhm * * From this it follows that: * R24 = Rmax ~ 1.5MOhm * R1 ~ R24/24 ~ 64kOhm * R2 ~ 2.0*R1 ~ 128kOhm * R6 ~ 6.0*R1 ~ 384kOhm * R8 ~ 8.0*R1 ~ 512kOhm * * Note that these are only approximate values for one particular SID chip, * due to process variations the values can be substantially different in * other chips. * * * * Filter frequency cutoff DAC * --------------------------- * * ~~~ * 12V 10 9 8 7 6 5 4 3 2 1 0 VGND * | | | | | | | | | | | | | Missing * 2R 2R 2R 2R 2R 2R 2R 2R 2R 2R 2R 2R 2R termination * | | | | | | | | | | | | | * Vw --o-R-o-R-o-R-o-R-o-R-o-R-o-R-o-R-o-R-o-R-o-R-o- -+ * * * Bit on: 12V * Bit off: 5V (VGND) * ~~~ * As is the case with all MOS 6581 DACs, the termination to (virtual) ground * at bit 0 is missing. * * Furthermore, the control of the two VCRs imposes a load on the DAC output * which varies with the input signals to the VCRs. This can be seen from the * VCR figure above. * * * * "Op-amp" (self-biased NMOS inverter) * ------------------------------------ * ~~~ * * 12V * * | * +-----------o * | | * | +------o * | | | * | | ||--+ * | +--|| * | ||--+ * ||--+ | * vi -----|| o---o----- vo * ||--+ | | * | ||--+ | * |-------|| | * | ||--+ | * ||--+ | | * +--|| | | * | ||--+ | | * | | | | * | +-----------o | * | | | * | | * | GND | * | | * +----------------------+ * * * vi - input * vo - output * ~~~ * Notes: * * The schematics above are laid out to show that the "op-amp" logically * consists of two building blocks; a saturated load NMOS inverter (on the * right hand side of the schematics) with a buffer / bias input stage * consisting of a variable saturated load NMOS inverter (on the left hand * side of the schematics). * * Provided a reasonably high input impedance and a reasonably low output * impedance, the "op-amp" can be modeled as a voltage transfer function * mapping input voltage to output voltage. * * * * Output buffer (NMOS voltage follower) * ------------------------------------- * ~~~ * * 12V * * | * | * ||--+ * vi -----|| * ||--+ * | * o------ vo * | (AUDIO * Rext OUT) * | * | * * GND * * vi - input * vo - output * Rext - external resistor, 1kOhm * ~~~ * Notes: * * The external resistor Rext is needed to complete the NMOS voltage follower, * this resistor has a recommended value of 1kOhm. * * Die photographs show that actually, two NMOS transistors are used in the * voltage follower. However the two transistors are coupled in parallel (all * terminals are pairwise common), which implies that we can model the two * transistors as one. */ class Filter6581 final : public Filter { private: const unsigned short* f0_dac; unsigned short** mixer; unsigned short** summer; unsigned short** gain_res; unsigned short** gain_vol; const int voiceScaleS11; const int voiceDC; /// VCR + associated capacitor connected to highpass output. std::unique_ptr<Integrator6581> const hpIntegrator; /// VCR + associated capacitor connected to bandpass output. std::unique_ptr<Integrator6581> const bpIntegrator; protected: /** * Set filter cutoff frequency. */ void updatedCenterFrequency() override; /** * Set filter resonance. * * In the MOS 6581, 1/Q is controlled linearly by res. */ void updateResonance(unsigned char res) override { currentResonance = gain_res[res]; } void updatedMixing() override; public: Filter6581() : f0_dac(FilterModelConfig6581::getInstance()->getDAC(0.5)), mixer(FilterModelConfig6581::getInstance()->getMixer()), summer(FilterModelConfig6581::getInstance()->getSummer()), gain_res(FilterModelConfig6581::getInstance()->getGainRes()), gain_vol(FilterModelConfig6581::getInstance()->getGainVol()), voiceScaleS11(FilterModelConfig6581::getInstance()->getVoiceScaleS11()), voiceDC(FilterModelConfig6581::getInstance()->getNormalizedVoiceDC()), hpIntegrator(FilterModelConfig6581::getInstance()->buildIntegrator()), bpIntegrator(FilterModelConfig6581::getInstance()->buildIntegrator()) { input(0); } ~Filter6581(); unsigned short clock(int voice1, int voice2, int voice3) override; void input(int sample) override { ve = (sample * voiceScaleS11 * 3 >> 11) + mixer[0][0]; } /** * Set filter curve type based on single parameter. * * @param curvePosition 0 .. 1, where 0 sets center frequency high ("light") and 1 sets it low ("dark"), default is 0.5 */ void setFilterCurve(double curvePosition); }; } // namespace reSIDfp #if RESID_INLINING || defined(FILTER6581_CPP) #include "Integrator6581.h" namespace reSIDfp { RESID_INLINE unsigned short Filter6581::clock(int voice1, int voice2, int voice3) { voice1 = (voice1 * voiceScaleS11 >> 15) + voiceDC; voice2 = (voice2 * voiceScaleS11 >> 15) + voiceDC; // Voice 3 is silenced by voice3off if it is not routed through the filter. voice3 = (filt3 || !voice3off) ? (voice3 * voiceScaleS11 >> 15) + voiceDC : 0; int Vi = 0; int Vo = 0; (filt1 ? Vi : Vo) += voice1; (filt2 ? Vi : Vo) += voice2; (filt3 ? Vi : Vo) += voice3; (filtE ? Vi : Vo) += ve; Vhp = currentSummer[currentResonance[Vbp] + Vlp + Vi]; Vbp = hpIntegrator->solve(Vhp); Vlp = bpIntegrator->solve(Vbp); if (lp) Vo += Vlp; if (bp) Vo += Vbp; if (hp) Vo += Vhp; return currentGain[currentMixer[Vo]]; } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/Filter6581.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,982
```c /* * ESFMu: emulator for the ESS "ESFM" enhanced OPL3 clone * * This file includes code and data from the Nuked OPL3 project, copyright (C) * 2013-2023 Nuke.YKT. Its usage, modification and redistribution is allowed * later. * * ESFMu is free software: you can redistribute it and/or modify * published by the Free Software Foundation, either version 2.1 * * ESFMu is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with ESFMu. If not, see <path_to_url */ /* * ESFMu wouldn't have been possible without the hard work and dedication of * the retro computer hardware research and preservation community. * * I'd like to thank: * - Nuke.YKT * Developer of Nuked OPL3, which was the basis for ESFMu's code and * also a great learning resource on Yamaha FM synthesis for myself. * Nuke.YKT also gives shoutouts on behalf of Nuked OPL3 to: * - MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh): * Feedback and Rhythm part calculation information. * - forums.submarine.org.uk(carbon14, opl3): * Tremolo and phase generator calculation information. * - OPLx decapsulated(Matthew Gambrell, Olli Niemitalo): * OPL2 ROMs. * - siliconpr0n.org(John McMaster, digshadow): * YMF262 and VRC VII decaps and die shots. * - rainwarrior * For performing the initial research on ESFM drivers and documenting * ESS's patent on native mode operator organization. * - jwt27 * For kickstarting the ESFM research project and compiling rainwarrior's * findings and more in an accessible document ("ESFM Demystified"). * - pachuco/CatButts * For documenting ESS's patent on ESFM's feedback implementation, which * was vital in getting ESFMu's sound output to be accurate. * - akumanatt * For helping out with code optimization. * - And everybody who helped out with real hardware testing */ #include "esfm.h" #include <stdint.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <stdbool.h> /* * Log-scale quarter sine table extracted from OPL3 ROM; taken straight from * Nuked OPL3 source code. * TODO: Extract sine table from ESFM die scans... does ESFM even use a sine * table? Patent documents give a hint to a possible method of generating sine * waves using some sort of boolean logic wizardry (lol) * Optimization: All 8 waveforms are calculated and unfolded from the actual * data in OPL3's ROM. Negative entries are marked by 0x8000. */ static const uint16_t logsinrom[1024*8] = { // wave 0 0x0859, 0x06c3, 0x0607, 0x058b, 0x052e, 0x04e4, 0x04a6, 0x0471, 0x0443, 0x041a, 0x03f5, 0x03d3, 0x03b5, 0x0398, 0x037e, 0x0365, 0x034e, 0x0339, 0x0324, 0x0311, 0x02ff, 0x02ed, 0x02dc, 0x02cd, 0x02bd, 0x02af, 0x02a0, 0x0293, 0x0286, 0x0279, 0x026d, 0x0261, 0x0256, 0x024b, 0x0240, 0x0236, 0x022c, 0x0222, 0x0218, 0x020f, 0x0206, 0x01fd, 0x01f5, 0x01ec, 0x01e4, 0x01dc, 0x01d4, 0x01cd, 0x01c5, 0x01be, 0x01b7, 0x01b0, 0x01a9, 0x01a2, 0x019b, 0x0195, 0x018f, 0x0188, 0x0182, 0x017c, 0x0177, 0x0171, 0x016b, 0x0166, 0x0160, 0x015b, 0x0155, 0x0150, 0x014b, 0x0146, 0x0141, 0x013c, 0x0137, 0x0133, 0x012e, 0x0129, 0x0125, 0x0121, 0x011c, 0x0118, 0x0114, 0x010f, 0x010b, 0x0107, 0x0103, 0x00ff, 0x00fb, 0x00f8, 0x00f4, 0x00f0, 0x00ec, 0x00e9, 0x00e5, 0x00e2, 0x00de, 0x00db, 0x00d7, 0x00d4, 0x00d1, 0x00cd, 0x00ca, 0x00c7, 0x00c4, 0x00c1, 0x00be, 0x00bb, 0x00b8, 0x00b5, 0x00b2, 0x00af, 0x00ac, 0x00a9, 0x00a7, 0x00a4, 0x00a1, 0x009f, 0x009c, 0x0099, 0x0097, 0x0094, 0x0092, 0x008f, 0x008d, 0x008a, 0x0088, 0x0086, 0x0083, 0x0081, 0x007f, 0x007d, 0x007a, 0x0078, 0x0076, 0x0074, 0x0072, 0x0070, 0x006e, 0x006c, 0x006a, 0x0068, 0x0066, 0x0064, 0x0062, 0x0060, 0x005e, 0x005c, 0x005b, 0x0059, 0x0057, 0x0055, 0x0053, 0x0052, 0x0050, 0x004e, 0x004d, 0x004b, 0x004a, 0x0048, 0x0046, 0x0045, 0x0043, 0x0042, 0x0040, 0x003f, 0x003e, 0x003c, 0x003b, 0x0039, 0x0038, 0x0037, 0x0035, 0x0034, 0x0033, 0x0031, 0x0030, 0x002f, 0x002e, 0x002d, 0x002b, 0x002a, 0x0029, 0x0028, 0x0027, 0x0026, 0x0025, 0x0024, 0x0023, 0x0022, 0x0021, 0x0020, 0x001f, 0x001e, 0x001d, 0x001c, 0x001b, 0x001a, 0x0019, 0x0018, 0x0017, 0x0017, 0x0016, 0x0015, 0x0014, 0x0014, 0x0013, 0x0012, 0x0011, 0x0011, 0x0010, 0x000f, 0x000f, 0x000e, 0x000d, 0x000d, 0x000c, 0x000c, 0x000b, 0x000a, 0x000a, 0x0009, 0x0009, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0002, 0x0002, 0x0003, 0x0003, 0x0003, 0x0004, 0x0004, 0x0004, 0x0005, 0x0005, 0x0005, 0x0006, 0x0006, 0x0007, 0x0007, 0x0007, 0x0008, 0x0008, 0x0009, 0x0009, 0x000a, 0x000a, 0x000b, 0x000c, 0x000c, 0x000d, 0x000d, 0x000e, 0x000f, 0x000f, 0x0010, 0x0011, 0x0011, 0x0012, 0x0013, 0x0014, 0x0014, 0x0015, 0x0016, 0x0017, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0033, 0x0034, 0x0035, 0x0037, 0x0038, 0x0039, 0x003b, 0x003c, 0x003e, 0x003f, 0x0040, 0x0042, 0x0043, 0x0045, 0x0046, 0x0048, 0x004a, 0x004b, 0x004d, 0x004e, 0x0050, 0x0052, 0x0053, 0x0055, 0x0057, 0x0059, 0x005b, 0x005c, 0x005e, 0x0060, 0x0062, 0x0064, 0x0066, 0x0068, 0x006a, 0x006c, 0x006e, 0x0070, 0x0072, 0x0074, 0x0076, 0x0078, 0x007a, 0x007d, 0x007f, 0x0081, 0x0083, 0x0086, 0x0088, 0x008a, 0x008d, 0x008f, 0x0092, 0x0094, 0x0097, 0x0099, 0x009c, 0x009f, 0x00a1, 0x00a4, 0x00a7, 0x00a9, 0x00ac, 0x00af, 0x00b2, 0x00b5, 0x00b8, 0x00bb, 0x00be, 0x00c1, 0x00c4, 0x00c7, 0x00ca, 0x00cd, 0x00d1, 0x00d4, 0x00d7, 0x00db, 0x00de, 0x00e2, 0x00e5, 0x00e9, 0x00ec, 0x00f0, 0x00f4, 0x00f8, 0x00fb, 0x00ff, 0x0103, 0x0107, 0x010b, 0x010f, 0x0114, 0x0118, 0x011c, 0x0121, 0x0125, 0x0129, 0x012e, 0x0133, 0x0137, 0x013c, 0x0141, 0x0146, 0x014b, 0x0150, 0x0155, 0x015b, 0x0160, 0x0166, 0x016b, 0x0171, 0x0177, 0x017c, 0x0182, 0x0188, 0x018f, 0x0195, 0x019b, 0x01a2, 0x01a9, 0x01b0, 0x01b7, 0x01be, 0x01c5, 0x01cd, 0x01d4, 0x01dc, 0x01e4, 0x01ec, 0x01f5, 0x01fd, 0x0206, 0x020f, 0x0218, 0x0222, 0x022c, 0x0236, 0x0240, 0x024b, 0x0256, 0x0261, 0x026d, 0x0279, 0x0286, 0x0293, 0x02a0, 0x02af, 0x02bd, 0x02cd, 0x02dc, 0x02ed, 0x02ff, 0x0311, 0x0324, 0x0339, 0x034e, 0x0365, 0x037e, 0x0398, 0x03b5, 0x03d3, 0x03f5, 0x041a, 0x0443, 0x0471, 0x04a6, 0x04e4, 0x052e, 0x058b, 0x0607, 0x06c3, 0x0859, 0x8859, 0x86c3, 0x8607, 0x858b, 0x852e, 0x84e4, 0x84a6, 0x8471, 0x8443, 0x841a, 0x83f5, 0x83d3, 0x83b5, 0x8398, 0x837e, 0x8365, 0x834e, 0x8339, 0x8324, 0x8311, 0x82ff, 0x82ed, 0x82dc, 0x82cd, 0x82bd, 0x82af, 0x82a0, 0x8293, 0x8286, 0x8279, 0x826d, 0x8261, 0x8256, 0x824b, 0x8240, 0x8236, 0x822c, 0x8222, 0x8218, 0x820f, 0x8206, 0x81fd, 0x81f5, 0x81ec, 0x81e4, 0x81dc, 0x81d4, 0x81cd, 0x81c5, 0x81be, 0x81b7, 0x81b0, 0x81a9, 0x81a2, 0x819b, 0x8195, 0x818f, 0x8188, 0x8182, 0x817c, 0x8177, 0x8171, 0x816b, 0x8166, 0x8160, 0x815b, 0x8155, 0x8150, 0x814b, 0x8146, 0x8141, 0x813c, 0x8137, 0x8133, 0x812e, 0x8129, 0x8125, 0x8121, 0x811c, 0x8118, 0x8114, 0x810f, 0x810b, 0x8107, 0x8103, 0x80ff, 0x80fb, 0x80f8, 0x80f4, 0x80f0, 0x80ec, 0x80e9, 0x80e5, 0x80e2, 0x80de, 0x80db, 0x80d7, 0x80d4, 0x80d1, 0x80cd, 0x80ca, 0x80c7, 0x80c4, 0x80c1, 0x80be, 0x80bb, 0x80b8, 0x80b5, 0x80b2, 0x80af, 0x80ac, 0x80a9, 0x80a7, 0x80a4, 0x80a1, 0x809f, 0x809c, 0x8099, 0x8097, 0x8094, 0x8092, 0x808f, 0x808d, 0x808a, 0x8088, 0x8086, 0x8083, 0x8081, 0x807f, 0x807d, 0x807a, 0x8078, 0x8076, 0x8074, 0x8072, 0x8070, 0x806e, 0x806c, 0x806a, 0x8068, 0x8066, 0x8064, 0x8062, 0x8060, 0x805e, 0x805c, 0x805b, 0x8059, 0x8057, 0x8055, 0x8053, 0x8052, 0x8050, 0x804e, 0x804d, 0x804b, 0x804a, 0x8048, 0x8046, 0x8045, 0x8043, 0x8042, 0x8040, 0x803f, 0x803e, 0x803c, 0x803b, 0x8039, 0x8038, 0x8037, 0x8035, 0x8034, 0x8033, 0x8031, 0x8030, 0x802f, 0x802e, 0x802d, 0x802b, 0x802a, 0x8029, 0x8028, 0x8027, 0x8026, 0x8025, 0x8024, 0x8023, 0x8022, 0x8021, 0x8020, 0x801f, 0x801e, 0x801d, 0x801c, 0x801b, 0x801a, 0x8019, 0x8018, 0x8017, 0x8017, 0x8016, 0x8015, 0x8014, 0x8014, 0x8013, 0x8012, 0x8011, 0x8011, 0x8010, 0x800f, 0x800f, 0x800e, 0x800d, 0x800d, 0x800c, 0x800c, 0x800b, 0x800a, 0x800a, 0x8009, 0x8009, 0x8008, 0x8008, 0x8007, 0x8007, 0x8007, 0x8006, 0x8006, 0x8005, 0x8005, 0x8005, 0x8004, 0x8004, 0x8004, 0x8003, 0x8003, 0x8003, 0x8002, 0x8002, 0x8002, 0x8002, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8002, 0x8002, 0x8002, 0x8002, 0x8003, 0x8003, 0x8003, 0x8004, 0x8004, 0x8004, 0x8005, 0x8005, 0x8005, 0x8006, 0x8006, 0x8007, 0x8007, 0x8007, 0x8008, 0x8008, 0x8009, 0x8009, 0x800a, 0x800a, 0x800b, 0x800c, 0x800c, 0x800d, 0x800d, 0x800e, 0x800f, 0x800f, 0x8010, 0x8011, 0x8011, 0x8012, 0x8013, 0x8014, 0x8014, 0x8015, 0x8016, 0x8017, 0x8017, 0x8018, 0x8019, 0x801a, 0x801b, 0x801c, 0x801d, 0x801e, 0x801f, 0x8020, 0x8021, 0x8022, 0x8023, 0x8024, 0x8025, 0x8026, 0x8027, 0x8028, 0x8029, 0x802a, 0x802b, 0x802d, 0x802e, 0x802f, 0x8030, 0x8031, 0x8033, 0x8034, 0x8035, 0x8037, 0x8038, 0x8039, 0x803b, 0x803c, 0x803e, 0x803f, 0x8040, 0x8042, 0x8043, 0x8045, 0x8046, 0x8048, 0x804a, 0x804b, 0x804d, 0x804e, 0x8050, 0x8052, 0x8053, 0x8055, 0x8057, 0x8059, 0x805b, 0x805c, 0x805e, 0x8060, 0x8062, 0x8064, 0x8066, 0x8068, 0x806a, 0x806c, 0x806e, 0x8070, 0x8072, 0x8074, 0x8076, 0x8078, 0x807a, 0x807d, 0x807f, 0x8081, 0x8083, 0x8086, 0x8088, 0x808a, 0x808d, 0x808f, 0x8092, 0x8094, 0x8097, 0x8099, 0x809c, 0x809f, 0x80a1, 0x80a4, 0x80a7, 0x80a9, 0x80ac, 0x80af, 0x80b2, 0x80b5, 0x80b8, 0x80bb, 0x80be, 0x80c1, 0x80c4, 0x80c7, 0x80ca, 0x80cd, 0x80d1, 0x80d4, 0x80d7, 0x80db, 0x80de, 0x80e2, 0x80e5, 0x80e9, 0x80ec, 0x80f0, 0x80f4, 0x80f8, 0x80fb, 0x80ff, 0x8103, 0x8107, 0x810b, 0x810f, 0x8114, 0x8118, 0x811c, 0x8121, 0x8125, 0x8129, 0x812e, 0x8133, 0x8137, 0x813c, 0x8141, 0x8146, 0x814b, 0x8150, 0x8155, 0x815b, 0x8160, 0x8166, 0x816b, 0x8171, 0x8177, 0x817c, 0x8182, 0x8188, 0x818f, 0x8195, 0x819b, 0x81a2, 0x81a9, 0x81b0, 0x81b7, 0x81be, 0x81c5, 0x81cd, 0x81d4, 0x81dc, 0x81e4, 0x81ec, 0x81f5, 0x81fd, 0x8206, 0x820f, 0x8218, 0x8222, 0x822c, 0x8236, 0x8240, 0x824b, 0x8256, 0x8261, 0x826d, 0x8279, 0x8286, 0x8293, 0x82a0, 0x82af, 0x82bd, 0x82cd, 0x82dc, 0x82ed, 0x82ff, 0x8311, 0x8324, 0x8339, 0x834e, 0x8365, 0x837e, 0x8398, 0x83b5, 0x83d3, 0x83f5, 0x841a, 0x8443, 0x8471, 0x84a6, 0x84e4, 0x852e, 0x858b, 0x8607, 0x86c3, 0x8859, // wave 1 0x0859, 0x06c3, 0x0607, 0x058b, 0x052e, 0x04e4, 0x04a6, 0x0471, 0x0443, 0x041a, 0x03f5, 0x03d3, 0x03b5, 0x0398, 0x037e, 0x0365, 0x034e, 0x0339, 0x0324, 0x0311, 0x02ff, 0x02ed, 0x02dc, 0x02cd, 0x02bd, 0x02af, 0x02a0, 0x0293, 0x0286, 0x0279, 0x026d, 0x0261, 0x0256, 0x024b, 0x0240, 0x0236, 0x022c, 0x0222, 0x0218, 0x020f, 0x0206, 0x01fd, 0x01f5, 0x01ec, 0x01e4, 0x01dc, 0x01d4, 0x01cd, 0x01c5, 0x01be, 0x01b7, 0x01b0, 0x01a9, 0x01a2, 0x019b, 0x0195, 0x018f, 0x0188, 0x0182, 0x017c, 0x0177, 0x0171, 0x016b, 0x0166, 0x0160, 0x015b, 0x0155, 0x0150, 0x014b, 0x0146, 0x0141, 0x013c, 0x0137, 0x0133, 0x012e, 0x0129, 0x0125, 0x0121, 0x011c, 0x0118, 0x0114, 0x010f, 0x010b, 0x0107, 0x0103, 0x00ff, 0x00fb, 0x00f8, 0x00f4, 0x00f0, 0x00ec, 0x00e9, 0x00e5, 0x00e2, 0x00de, 0x00db, 0x00d7, 0x00d4, 0x00d1, 0x00cd, 0x00ca, 0x00c7, 0x00c4, 0x00c1, 0x00be, 0x00bb, 0x00b8, 0x00b5, 0x00b2, 0x00af, 0x00ac, 0x00a9, 0x00a7, 0x00a4, 0x00a1, 0x009f, 0x009c, 0x0099, 0x0097, 0x0094, 0x0092, 0x008f, 0x008d, 0x008a, 0x0088, 0x0086, 0x0083, 0x0081, 0x007f, 0x007d, 0x007a, 0x0078, 0x0076, 0x0074, 0x0072, 0x0070, 0x006e, 0x006c, 0x006a, 0x0068, 0x0066, 0x0064, 0x0062, 0x0060, 0x005e, 0x005c, 0x005b, 0x0059, 0x0057, 0x0055, 0x0053, 0x0052, 0x0050, 0x004e, 0x004d, 0x004b, 0x004a, 0x0048, 0x0046, 0x0045, 0x0043, 0x0042, 0x0040, 0x003f, 0x003e, 0x003c, 0x003b, 0x0039, 0x0038, 0x0037, 0x0035, 0x0034, 0x0033, 0x0031, 0x0030, 0x002f, 0x002e, 0x002d, 0x002b, 0x002a, 0x0029, 0x0028, 0x0027, 0x0026, 0x0025, 0x0024, 0x0023, 0x0022, 0x0021, 0x0020, 0x001f, 0x001e, 0x001d, 0x001c, 0x001b, 0x001a, 0x0019, 0x0018, 0x0017, 0x0017, 0x0016, 0x0015, 0x0014, 0x0014, 0x0013, 0x0012, 0x0011, 0x0011, 0x0010, 0x000f, 0x000f, 0x000e, 0x000d, 0x000d, 0x000c, 0x000c, 0x000b, 0x000a, 0x000a, 0x0009, 0x0009, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0002, 0x0002, 0x0003, 0x0003, 0x0003, 0x0004, 0x0004, 0x0004, 0x0005, 0x0005, 0x0005, 0x0006, 0x0006, 0x0007, 0x0007, 0x0007, 0x0008, 0x0008, 0x0009, 0x0009, 0x000a, 0x000a, 0x000b, 0x000c, 0x000c, 0x000d, 0x000d, 0x000e, 0x000f, 0x000f, 0x0010, 0x0011, 0x0011, 0x0012, 0x0013, 0x0014, 0x0014, 0x0015, 0x0016, 0x0017, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0033, 0x0034, 0x0035, 0x0037, 0x0038, 0x0039, 0x003b, 0x003c, 0x003e, 0x003f, 0x0040, 0x0042, 0x0043, 0x0045, 0x0046, 0x0048, 0x004a, 0x004b, 0x004d, 0x004e, 0x0050, 0x0052, 0x0053, 0x0055, 0x0057, 0x0059, 0x005b, 0x005c, 0x005e, 0x0060, 0x0062, 0x0064, 0x0066, 0x0068, 0x006a, 0x006c, 0x006e, 0x0070, 0x0072, 0x0074, 0x0076, 0x0078, 0x007a, 0x007d, 0x007f, 0x0081, 0x0083, 0x0086, 0x0088, 0x008a, 0x008d, 0x008f, 0x0092, 0x0094, 0x0097, 0x0099, 0x009c, 0x009f, 0x00a1, 0x00a4, 0x00a7, 0x00a9, 0x00ac, 0x00af, 0x00b2, 0x00b5, 0x00b8, 0x00bb, 0x00be, 0x00c1, 0x00c4, 0x00c7, 0x00ca, 0x00cd, 0x00d1, 0x00d4, 0x00d7, 0x00db, 0x00de, 0x00e2, 0x00e5, 0x00e9, 0x00ec, 0x00f0, 0x00f4, 0x00f8, 0x00fb, 0x00ff, 0x0103, 0x0107, 0x010b, 0x010f, 0x0114, 0x0118, 0x011c, 0x0121, 0x0125, 0x0129, 0x012e, 0x0133, 0x0137, 0x013c, 0x0141, 0x0146, 0x014b, 0x0150, 0x0155, 0x015b, 0x0160, 0x0166, 0x016b, 0x0171, 0x0177, 0x017c, 0x0182, 0x0188, 0x018f, 0x0195, 0x019b, 0x01a2, 0x01a9, 0x01b0, 0x01b7, 0x01be, 0x01c5, 0x01cd, 0x01d4, 0x01dc, 0x01e4, 0x01ec, 0x01f5, 0x01fd, 0x0206, 0x020f, 0x0218, 0x0222, 0x022c, 0x0236, 0x0240, 0x024b, 0x0256, 0x0261, 0x026d, 0x0279, 0x0286, 0x0293, 0x02a0, 0x02af, 0x02bd, 0x02cd, 0x02dc, 0x02ed, 0x02ff, 0x0311, 0x0324, 0x0339, 0x034e, 0x0365, 0x037e, 0x0398, 0x03b5, 0x03d3, 0x03f5, 0x041a, 0x0443, 0x0471, 0x04a6, 0x04e4, 0x052e, 0x058b, 0x0607, 0x06c3, 0x0859, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, // wave 2 0x0859, 0x06c3, 0x0607, 0x058b, 0x052e, 0x04e4, 0x04a6, 0x0471, 0x0443, 0x041a, 0x03f5, 0x03d3, 0x03b5, 0x0398, 0x037e, 0x0365, 0x034e, 0x0339, 0x0324, 0x0311, 0x02ff, 0x02ed, 0x02dc, 0x02cd, 0x02bd, 0x02af, 0x02a0, 0x0293, 0x0286, 0x0279, 0x026d, 0x0261, 0x0256, 0x024b, 0x0240, 0x0236, 0x022c, 0x0222, 0x0218, 0x020f, 0x0206, 0x01fd, 0x01f5, 0x01ec, 0x01e4, 0x01dc, 0x01d4, 0x01cd, 0x01c5, 0x01be, 0x01b7, 0x01b0, 0x01a9, 0x01a2, 0x019b, 0x0195, 0x018f, 0x0188, 0x0182, 0x017c, 0x0177, 0x0171, 0x016b, 0x0166, 0x0160, 0x015b, 0x0155, 0x0150, 0x014b, 0x0146, 0x0141, 0x013c, 0x0137, 0x0133, 0x012e, 0x0129, 0x0125, 0x0121, 0x011c, 0x0118, 0x0114, 0x010f, 0x010b, 0x0107, 0x0103, 0x00ff, 0x00fb, 0x00f8, 0x00f4, 0x00f0, 0x00ec, 0x00e9, 0x00e5, 0x00e2, 0x00de, 0x00db, 0x00d7, 0x00d4, 0x00d1, 0x00cd, 0x00ca, 0x00c7, 0x00c4, 0x00c1, 0x00be, 0x00bb, 0x00b8, 0x00b5, 0x00b2, 0x00af, 0x00ac, 0x00a9, 0x00a7, 0x00a4, 0x00a1, 0x009f, 0x009c, 0x0099, 0x0097, 0x0094, 0x0092, 0x008f, 0x008d, 0x008a, 0x0088, 0x0086, 0x0083, 0x0081, 0x007f, 0x007d, 0x007a, 0x0078, 0x0076, 0x0074, 0x0072, 0x0070, 0x006e, 0x006c, 0x006a, 0x0068, 0x0066, 0x0064, 0x0062, 0x0060, 0x005e, 0x005c, 0x005b, 0x0059, 0x0057, 0x0055, 0x0053, 0x0052, 0x0050, 0x004e, 0x004d, 0x004b, 0x004a, 0x0048, 0x0046, 0x0045, 0x0043, 0x0042, 0x0040, 0x003f, 0x003e, 0x003c, 0x003b, 0x0039, 0x0038, 0x0037, 0x0035, 0x0034, 0x0033, 0x0031, 0x0030, 0x002f, 0x002e, 0x002d, 0x002b, 0x002a, 0x0029, 0x0028, 0x0027, 0x0026, 0x0025, 0x0024, 0x0023, 0x0022, 0x0021, 0x0020, 0x001f, 0x001e, 0x001d, 0x001c, 0x001b, 0x001a, 0x0019, 0x0018, 0x0017, 0x0017, 0x0016, 0x0015, 0x0014, 0x0014, 0x0013, 0x0012, 0x0011, 0x0011, 0x0010, 0x000f, 0x000f, 0x000e, 0x000d, 0x000d, 0x000c, 0x000c, 0x000b, 0x000a, 0x000a, 0x0009, 0x0009, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0002, 0x0002, 0x0003, 0x0003, 0x0003, 0x0004, 0x0004, 0x0004, 0x0005, 0x0005, 0x0005, 0x0006, 0x0006, 0x0007, 0x0007, 0x0007, 0x0008, 0x0008, 0x0009, 0x0009, 0x000a, 0x000a, 0x000b, 0x000c, 0x000c, 0x000d, 0x000d, 0x000e, 0x000f, 0x000f, 0x0010, 0x0011, 0x0011, 0x0012, 0x0013, 0x0014, 0x0014, 0x0015, 0x0016, 0x0017, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0033, 0x0034, 0x0035, 0x0037, 0x0038, 0x0039, 0x003b, 0x003c, 0x003e, 0x003f, 0x0040, 0x0042, 0x0043, 0x0045, 0x0046, 0x0048, 0x004a, 0x004b, 0x004d, 0x004e, 0x0050, 0x0052, 0x0053, 0x0055, 0x0057, 0x0059, 0x005b, 0x005c, 0x005e, 0x0060, 0x0062, 0x0064, 0x0066, 0x0068, 0x006a, 0x006c, 0x006e, 0x0070, 0x0072, 0x0074, 0x0076, 0x0078, 0x007a, 0x007d, 0x007f, 0x0081, 0x0083, 0x0086, 0x0088, 0x008a, 0x008d, 0x008f, 0x0092, 0x0094, 0x0097, 0x0099, 0x009c, 0x009f, 0x00a1, 0x00a4, 0x00a7, 0x00a9, 0x00ac, 0x00af, 0x00b2, 0x00b5, 0x00b8, 0x00bb, 0x00be, 0x00c1, 0x00c4, 0x00c7, 0x00ca, 0x00cd, 0x00d1, 0x00d4, 0x00d7, 0x00db, 0x00de, 0x00e2, 0x00e5, 0x00e9, 0x00ec, 0x00f0, 0x00f4, 0x00f8, 0x00fb, 0x00ff, 0x0103, 0x0107, 0x010b, 0x010f, 0x0114, 0x0118, 0x011c, 0x0121, 0x0125, 0x0129, 0x012e, 0x0133, 0x0137, 0x013c, 0x0141, 0x0146, 0x014b, 0x0150, 0x0155, 0x015b, 0x0160, 0x0166, 0x016b, 0x0171, 0x0177, 0x017c, 0x0182, 0x0188, 0x018f, 0x0195, 0x019b, 0x01a2, 0x01a9, 0x01b0, 0x01b7, 0x01be, 0x01c5, 0x01cd, 0x01d4, 0x01dc, 0x01e4, 0x01ec, 0x01f5, 0x01fd, 0x0206, 0x020f, 0x0218, 0x0222, 0x022c, 0x0236, 0x0240, 0x024b, 0x0256, 0x0261, 0x026d, 0x0279, 0x0286, 0x0293, 0x02a0, 0x02af, 0x02bd, 0x02cd, 0x02dc, 0x02ed, 0x02ff, 0x0311, 0x0324, 0x0339, 0x034e, 0x0365, 0x037e, 0x0398, 0x03b5, 0x03d3, 0x03f5, 0x041a, 0x0443, 0x0471, 0x04a6, 0x04e4, 0x052e, 0x058b, 0x0607, 0x06c3, 0x0859, 0x0859, 0x06c3, 0x0607, 0x058b, 0x052e, 0x04e4, 0x04a6, 0x0471, 0x0443, 0x041a, 0x03f5, 0x03d3, 0x03b5, 0x0398, 0x037e, 0x0365, 0x034e, 0x0339, 0x0324, 0x0311, 0x02ff, 0x02ed, 0x02dc, 0x02cd, 0x02bd, 0x02af, 0x02a0, 0x0293, 0x0286, 0x0279, 0x026d, 0x0261, 0x0256, 0x024b, 0x0240, 0x0236, 0x022c, 0x0222, 0x0218, 0x020f, 0x0206, 0x01fd, 0x01f5, 0x01ec, 0x01e4, 0x01dc, 0x01d4, 0x01cd, 0x01c5, 0x01be, 0x01b7, 0x01b0, 0x01a9, 0x01a2, 0x019b, 0x0195, 0x018f, 0x0188, 0x0182, 0x017c, 0x0177, 0x0171, 0x016b, 0x0166, 0x0160, 0x015b, 0x0155, 0x0150, 0x014b, 0x0146, 0x0141, 0x013c, 0x0137, 0x0133, 0x012e, 0x0129, 0x0125, 0x0121, 0x011c, 0x0118, 0x0114, 0x010f, 0x010b, 0x0107, 0x0103, 0x00ff, 0x00fb, 0x00f8, 0x00f4, 0x00f0, 0x00ec, 0x00e9, 0x00e5, 0x00e2, 0x00de, 0x00db, 0x00d7, 0x00d4, 0x00d1, 0x00cd, 0x00ca, 0x00c7, 0x00c4, 0x00c1, 0x00be, 0x00bb, 0x00b8, 0x00b5, 0x00b2, 0x00af, 0x00ac, 0x00a9, 0x00a7, 0x00a4, 0x00a1, 0x009f, 0x009c, 0x0099, 0x0097, 0x0094, 0x0092, 0x008f, 0x008d, 0x008a, 0x0088, 0x0086, 0x0083, 0x0081, 0x007f, 0x007d, 0x007a, 0x0078, 0x0076, 0x0074, 0x0072, 0x0070, 0x006e, 0x006c, 0x006a, 0x0068, 0x0066, 0x0064, 0x0062, 0x0060, 0x005e, 0x005c, 0x005b, 0x0059, 0x0057, 0x0055, 0x0053, 0x0052, 0x0050, 0x004e, 0x004d, 0x004b, 0x004a, 0x0048, 0x0046, 0x0045, 0x0043, 0x0042, 0x0040, 0x003f, 0x003e, 0x003c, 0x003b, 0x0039, 0x0038, 0x0037, 0x0035, 0x0034, 0x0033, 0x0031, 0x0030, 0x002f, 0x002e, 0x002d, 0x002b, 0x002a, 0x0029, 0x0028, 0x0027, 0x0026, 0x0025, 0x0024, 0x0023, 0x0022, 0x0021, 0x0020, 0x001f, 0x001e, 0x001d, 0x001c, 0x001b, 0x001a, 0x0019, 0x0018, 0x0017, 0x0017, 0x0016, 0x0015, 0x0014, 0x0014, 0x0013, 0x0012, 0x0011, 0x0011, 0x0010, 0x000f, 0x000f, 0x000e, 0x000d, 0x000d, 0x000c, 0x000c, 0x000b, 0x000a, 0x000a, 0x0009, 0x0009, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0002, 0x0002, 0x0003, 0x0003, 0x0003, 0x0004, 0x0004, 0x0004, 0x0005, 0x0005, 0x0005, 0x0006, 0x0006, 0x0007, 0x0007, 0x0007, 0x0008, 0x0008, 0x0009, 0x0009, 0x000a, 0x000a, 0x000b, 0x000c, 0x000c, 0x000d, 0x000d, 0x000e, 0x000f, 0x000f, 0x0010, 0x0011, 0x0011, 0x0012, 0x0013, 0x0014, 0x0014, 0x0015, 0x0016, 0x0017, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0033, 0x0034, 0x0035, 0x0037, 0x0038, 0x0039, 0x003b, 0x003c, 0x003e, 0x003f, 0x0040, 0x0042, 0x0043, 0x0045, 0x0046, 0x0048, 0x004a, 0x004b, 0x004d, 0x004e, 0x0050, 0x0052, 0x0053, 0x0055, 0x0057, 0x0059, 0x005b, 0x005c, 0x005e, 0x0060, 0x0062, 0x0064, 0x0066, 0x0068, 0x006a, 0x006c, 0x006e, 0x0070, 0x0072, 0x0074, 0x0076, 0x0078, 0x007a, 0x007d, 0x007f, 0x0081, 0x0083, 0x0086, 0x0088, 0x008a, 0x008d, 0x008f, 0x0092, 0x0094, 0x0097, 0x0099, 0x009c, 0x009f, 0x00a1, 0x00a4, 0x00a7, 0x00a9, 0x00ac, 0x00af, 0x00b2, 0x00b5, 0x00b8, 0x00bb, 0x00be, 0x00c1, 0x00c4, 0x00c7, 0x00ca, 0x00cd, 0x00d1, 0x00d4, 0x00d7, 0x00db, 0x00de, 0x00e2, 0x00e5, 0x00e9, 0x00ec, 0x00f0, 0x00f4, 0x00f8, 0x00fb, 0x00ff, 0x0103, 0x0107, 0x010b, 0x010f, 0x0114, 0x0118, 0x011c, 0x0121, 0x0125, 0x0129, 0x012e, 0x0133, 0x0137, 0x013c, 0x0141, 0x0146, 0x014b, 0x0150, 0x0155, 0x015b, 0x0160, 0x0166, 0x016b, 0x0171, 0x0177, 0x017c, 0x0182, 0x0188, 0x018f, 0x0195, 0x019b, 0x01a2, 0x01a9, 0x01b0, 0x01b7, 0x01be, 0x01c5, 0x01cd, 0x01d4, 0x01dc, 0x01e4, 0x01ec, 0x01f5, 0x01fd, 0x0206, 0x020f, 0x0218, 0x0222, 0x022c, 0x0236, 0x0240, 0x024b, 0x0256, 0x0261, 0x026d, 0x0279, 0x0286, 0x0293, 0x02a0, 0x02af, 0x02bd, 0x02cd, 0x02dc, 0x02ed, 0x02ff, 0x0311, 0x0324, 0x0339, 0x034e, 0x0365, 0x037e, 0x0398, 0x03b5, 0x03d3, 0x03f5, 0x041a, 0x0443, 0x0471, 0x04a6, 0x04e4, 0x052e, 0x058b, 0x0607, 0x06c3, 0x0859, // wave 3 0x0859, 0x06c3, 0x0607, 0x058b, 0x052e, 0x04e4, 0x04a6, 0x0471, 0x0443, 0x041a, 0x03f5, 0x03d3, 0x03b5, 0x0398, 0x037e, 0x0365, 0x034e, 0x0339, 0x0324, 0x0311, 0x02ff, 0x02ed, 0x02dc, 0x02cd, 0x02bd, 0x02af, 0x02a0, 0x0293, 0x0286, 0x0279, 0x026d, 0x0261, 0x0256, 0x024b, 0x0240, 0x0236, 0x022c, 0x0222, 0x0218, 0x020f, 0x0206, 0x01fd, 0x01f5, 0x01ec, 0x01e4, 0x01dc, 0x01d4, 0x01cd, 0x01c5, 0x01be, 0x01b7, 0x01b0, 0x01a9, 0x01a2, 0x019b, 0x0195, 0x018f, 0x0188, 0x0182, 0x017c, 0x0177, 0x0171, 0x016b, 0x0166, 0x0160, 0x015b, 0x0155, 0x0150, 0x014b, 0x0146, 0x0141, 0x013c, 0x0137, 0x0133, 0x012e, 0x0129, 0x0125, 0x0121, 0x011c, 0x0118, 0x0114, 0x010f, 0x010b, 0x0107, 0x0103, 0x00ff, 0x00fb, 0x00f8, 0x00f4, 0x00f0, 0x00ec, 0x00e9, 0x00e5, 0x00e2, 0x00de, 0x00db, 0x00d7, 0x00d4, 0x00d1, 0x00cd, 0x00ca, 0x00c7, 0x00c4, 0x00c1, 0x00be, 0x00bb, 0x00b8, 0x00b5, 0x00b2, 0x00af, 0x00ac, 0x00a9, 0x00a7, 0x00a4, 0x00a1, 0x009f, 0x009c, 0x0099, 0x0097, 0x0094, 0x0092, 0x008f, 0x008d, 0x008a, 0x0088, 0x0086, 0x0083, 0x0081, 0x007f, 0x007d, 0x007a, 0x0078, 0x0076, 0x0074, 0x0072, 0x0070, 0x006e, 0x006c, 0x006a, 0x0068, 0x0066, 0x0064, 0x0062, 0x0060, 0x005e, 0x005c, 0x005b, 0x0059, 0x0057, 0x0055, 0x0053, 0x0052, 0x0050, 0x004e, 0x004d, 0x004b, 0x004a, 0x0048, 0x0046, 0x0045, 0x0043, 0x0042, 0x0040, 0x003f, 0x003e, 0x003c, 0x003b, 0x0039, 0x0038, 0x0037, 0x0035, 0x0034, 0x0033, 0x0031, 0x0030, 0x002f, 0x002e, 0x002d, 0x002b, 0x002a, 0x0029, 0x0028, 0x0027, 0x0026, 0x0025, 0x0024, 0x0023, 0x0022, 0x0021, 0x0020, 0x001f, 0x001e, 0x001d, 0x001c, 0x001b, 0x001a, 0x0019, 0x0018, 0x0017, 0x0017, 0x0016, 0x0015, 0x0014, 0x0014, 0x0013, 0x0012, 0x0011, 0x0011, 0x0010, 0x000f, 0x000f, 0x000e, 0x000d, 0x000d, 0x000c, 0x000c, 0x000b, 0x000a, 0x000a, 0x0009, 0x0009, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x0859, 0x06c3, 0x0607, 0x058b, 0x052e, 0x04e4, 0x04a6, 0x0471, 0x0443, 0x041a, 0x03f5, 0x03d3, 0x03b5, 0x0398, 0x037e, 0x0365, 0x034e, 0x0339, 0x0324, 0x0311, 0x02ff, 0x02ed, 0x02dc, 0x02cd, 0x02bd, 0x02af, 0x02a0, 0x0293, 0x0286, 0x0279, 0x026d, 0x0261, 0x0256, 0x024b, 0x0240, 0x0236, 0x022c, 0x0222, 0x0218, 0x020f, 0x0206, 0x01fd, 0x01f5, 0x01ec, 0x01e4, 0x01dc, 0x01d4, 0x01cd, 0x01c5, 0x01be, 0x01b7, 0x01b0, 0x01a9, 0x01a2, 0x019b, 0x0195, 0x018f, 0x0188, 0x0182, 0x017c, 0x0177, 0x0171, 0x016b, 0x0166, 0x0160, 0x015b, 0x0155, 0x0150, 0x014b, 0x0146, 0x0141, 0x013c, 0x0137, 0x0133, 0x012e, 0x0129, 0x0125, 0x0121, 0x011c, 0x0118, 0x0114, 0x010f, 0x010b, 0x0107, 0x0103, 0x00ff, 0x00fb, 0x00f8, 0x00f4, 0x00f0, 0x00ec, 0x00e9, 0x00e5, 0x00e2, 0x00de, 0x00db, 0x00d7, 0x00d4, 0x00d1, 0x00cd, 0x00ca, 0x00c7, 0x00c4, 0x00c1, 0x00be, 0x00bb, 0x00b8, 0x00b5, 0x00b2, 0x00af, 0x00ac, 0x00a9, 0x00a7, 0x00a4, 0x00a1, 0x009f, 0x009c, 0x0099, 0x0097, 0x0094, 0x0092, 0x008f, 0x008d, 0x008a, 0x0088, 0x0086, 0x0083, 0x0081, 0x007f, 0x007d, 0x007a, 0x0078, 0x0076, 0x0074, 0x0072, 0x0070, 0x006e, 0x006c, 0x006a, 0x0068, 0x0066, 0x0064, 0x0062, 0x0060, 0x005e, 0x005c, 0x005b, 0x0059, 0x0057, 0x0055, 0x0053, 0x0052, 0x0050, 0x004e, 0x004d, 0x004b, 0x004a, 0x0048, 0x0046, 0x0045, 0x0043, 0x0042, 0x0040, 0x003f, 0x003e, 0x003c, 0x003b, 0x0039, 0x0038, 0x0037, 0x0035, 0x0034, 0x0033, 0x0031, 0x0030, 0x002f, 0x002e, 0x002d, 0x002b, 0x002a, 0x0029, 0x0028, 0x0027, 0x0026, 0x0025, 0x0024, 0x0023, 0x0022, 0x0021, 0x0020, 0x001f, 0x001e, 0x001d, 0x001c, 0x001b, 0x001a, 0x0019, 0x0018, 0x0017, 0x0017, 0x0016, 0x0015, 0x0014, 0x0014, 0x0013, 0x0012, 0x0011, 0x0011, 0x0010, 0x000f, 0x000f, 0x000e, 0x000d, 0x000d, 0x000c, 0x000c, 0x000b, 0x000a, 0x000a, 0x0009, 0x0009, 0x0008, 0x0008, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0003, 0x0003, 0x0003, 0x0002, 0x0002, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, // wave 4 0x0859, 0x0607, 0x052e, 0x04a6, 0x0443, 0x03f5, 0x03b5, 0x037e, 0x034e, 0x0324, 0x02ff, 0x02dc, 0x02bd, 0x02a0, 0x0286, 0x026d, 0x0256, 0x0240, 0x022c, 0x0218, 0x0206, 0x01f5, 0x01e4, 0x01d4, 0x01c5, 0x01b7, 0x01a9, 0x019b, 0x018f, 0x0182, 0x0177, 0x016b, 0x0160, 0x0155, 0x014b, 0x0141, 0x0137, 0x012e, 0x0125, 0x011c, 0x0114, 0x010b, 0x0103, 0x00fb, 0x00f4, 0x00ec, 0x00e5, 0x00de, 0x00d7, 0x00d1, 0x00ca, 0x00c4, 0x00be, 0x00b8, 0x00b2, 0x00ac, 0x00a7, 0x00a1, 0x009c, 0x0097, 0x0092, 0x008d, 0x0088, 0x0083, 0x007f, 0x007a, 0x0076, 0x0072, 0x006e, 0x006a, 0x0066, 0x0062, 0x005e, 0x005b, 0x0057, 0x0053, 0x0050, 0x004d, 0x004a, 0x0046, 0x0043, 0x0040, 0x003e, 0x003b, 0x0038, 0x0035, 0x0033, 0x0030, 0x002e, 0x002b, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021, 0x001f, 0x001d, 0x001b, 0x0019, 0x0017, 0x0016, 0x0014, 0x0013, 0x0011, 0x0010, 0x000f, 0x000d, 0x000c, 0x000b, 0x000a, 0x0009, 0x0008, 0x0007, 0x0006, 0x0005, 0x0005, 0x0004, 0x0003, 0x0003, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0003, 0x0003, 0x0004, 0x0005, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000f, 0x0010, 0x0011, 0x0013, 0x0014, 0x0016, 0x0017, 0x0019, 0x001b, 0x001d, 0x001f, 0x0021, 0x0023, 0x0025, 0x0027, 0x0029, 0x002b, 0x002e, 0x0030, 0x0033, 0x0035, 0x0038, 0x003b, 0x003e, 0x0040, 0x0043, 0x0046, 0x004a, 0x004d, 0x0050, 0x0053, 0x0057, 0x005b, 0x005e, 0x0062, 0x0066, 0x006a, 0x006e, 0x0072, 0x0076, 0x007a, 0x007f, 0x0083, 0x0088, 0x008d, 0x0092, 0x0097, 0x009c, 0x00a1, 0x00a7, 0x00ac, 0x00b2, 0x00b8, 0x00be, 0x00c4, 0x00ca, 0x00d1, 0x00d7, 0x00de, 0x00e5, 0x00ec, 0x00f4, 0x00fb, 0x0103, 0x010b, 0x0114, 0x011c, 0x0125, 0x012e, 0x0137, 0x0141, 0x014b, 0x0155, 0x0160, 0x016b, 0x0177, 0x0182, 0x018f, 0x019b, 0x01a9, 0x01b7, 0x01c5, 0x01d4, 0x01e4, 0x01f5, 0x0206, 0x0218, 0x022c, 0x0240, 0x0256, 0x026d, 0x0286, 0x02a0, 0x02bd, 0x02dc, 0x02ff, 0x0324, 0x034e, 0x037e, 0x03b5, 0x03f5, 0x0443, 0x04a6, 0x052e, 0x0607, 0x0859, 0x8859, 0x8607, 0x852e, 0x84a6, 0x8443, 0x83f5, 0x83b5, 0x837e, 0x834e, 0x8324, 0x82ff, 0x82dc, 0x82bd, 0x82a0, 0x8286, 0x826d, 0x8256, 0x8240, 0x822c, 0x8218, 0x8206, 0x81f5, 0x81e4, 0x81d4, 0x81c5, 0x81b7, 0x81a9, 0x819b, 0x818f, 0x8182, 0x8177, 0x816b, 0x8160, 0x8155, 0x814b, 0x8141, 0x8137, 0x812e, 0x8125, 0x811c, 0x8114, 0x810b, 0x8103, 0x80fb, 0x80f4, 0x80ec, 0x80e5, 0x80de, 0x80d7, 0x80d1, 0x80ca, 0x80c4, 0x80be, 0x80b8, 0x80b2, 0x80ac, 0x80a7, 0x80a1, 0x809c, 0x8097, 0x8092, 0x808d, 0x8088, 0x8083, 0x807f, 0x807a, 0x8076, 0x8072, 0x806e, 0x806a, 0x8066, 0x8062, 0x805e, 0x805b, 0x8057, 0x8053, 0x8050, 0x804d, 0x804a, 0x8046, 0x8043, 0x8040, 0x803e, 0x803b, 0x8038, 0x8035, 0x8033, 0x8030, 0x802e, 0x802b, 0x8029, 0x8027, 0x8025, 0x8023, 0x8021, 0x801f, 0x801d, 0x801b, 0x8019, 0x8017, 0x8016, 0x8014, 0x8013, 0x8011, 0x8010, 0x800f, 0x800d, 0x800c, 0x800b, 0x800a, 0x8009, 0x8008, 0x8007, 0x8006, 0x8005, 0x8005, 0x8004, 0x8003, 0x8003, 0x8002, 0x8002, 0x8001, 0x8001, 0x8001, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8001, 0x8001, 0x8001, 0x8002, 0x8002, 0x8003, 0x8003, 0x8004, 0x8005, 0x8005, 0x8006, 0x8007, 0x8008, 0x8009, 0x800a, 0x800b, 0x800c, 0x800d, 0x800f, 0x8010, 0x8011, 0x8013, 0x8014, 0x8016, 0x8017, 0x8019, 0x801b, 0x801d, 0x801f, 0x8021, 0x8023, 0x8025, 0x8027, 0x8029, 0x802b, 0x802e, 0x8030, 0x8033, 0x8035, 0x8038, 0x803b, 0x803e, 0x8040, 0x8043, 0x8046, 0x804a, 0x804d, 0x8050, 0x8053, 0x8057, 0x805b, 0x805e, 0x8062, 0x8066, 0x806a, 0x806e, 0x8072, 0x8076, 0x807a, 0x807f, 0x8083, 0x8088, 0x808d, 0x8092, 0x8097, 0x809c, 0x80a1, 0x80a7, 0x80ac, 0x80b2, 0x80b8, 0x80be, 0x80c4, 0x80ca, 0x80d1, 0x80d7, 0x80de, 0x80e5, 0x80ec, 0x80f4, 0x80fb, 0x8103, 0x810b, 0x8114, 0x811c, 0x8125, 0x812e, 0x8137, 0x8141, 0x814b, 0x8155, 0x8160, 0x816b, 0x8177, 0x8182, 0x818f, 0x819b, 0x81a9, 0x81b7, 0x81c5, 0x81d4, 0x81e4, 0x81f5, 0x8206, 0x8218, 0x822c, 0x8240, 0x8256, 0x826d, 0x8286, 0x82a0, 0x82bd, 0x82dc, 0x82ff, 0x8324, 0x834e, 0x837e, 0x83b5, 0x83f5, 0x8443, 0x84a6, 0x852e, 0x8607, 0x8859, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, // wave 5 0x0859, 0x0607, 0x052e, 0x04a6, 0x0443, 0x03f5, 0x03b5, 0x037e, 0x034e, 0x0324, 0x02ff, 0x02dc, 0x02bd, 0x02a0, 0x0286, 0x026d, 0x0256, 0x0240, 0x022c, 0x0218, 0x0206, 0x01f5, 0x01e4, 0x01d4, 0x01c5, 0x01b7, 0x01a9, 0x019b, 0x018f, 0x0182, 0x0177, 0x016b, 0x0160, 0x0155, 0x014b, 0x0141, 0x0137, 0x012e, 0x0125, 0x011c, 0x0114, 0x010b, 0x0103, 0x00fb, 0x00f4, 0x00ec, 0x00e5, 0x00de, 0x00d7, 0x00d1, 0x00ca, 0x00c4, 0x00be, 0x00b8, 0x00b2, 0x00ac, 0x00a7, 0x00a1, 0x009c, 0x0097, 0x0092, 0x008d, 0x0088, 0x0083, 0x007f, 0x007a, 0x0076, 0x0072, 0x006e, 0x006a, 0x0066, 0x0062, 0x005e, 0x005b, 0x0057, 0x0053, 0x0050, 0x004d, 0x004a, 0x0046, 0x0043, 0x0040, 0x003e, 0x003b, 0x0038, 0x0035, 0x0033, 0x0030, 0x002e, 0x002b, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021, 0x001f, 0x001d, 0x001b, 0x0019, 0x0017, 0x0016, 0x0014, 0x0013, 0x0011, 0x0010, 0x000f, 0x000d, 0x000c, 0x000b, 0x000a, 0x0009, 0x0008, 0x0007, 0x0006, 0x0005, 0x0005, 0x0004, 0x0003, 0x0003, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0003, 0x0003, 0x0004, 0x0005, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000f, 0x0010, 0x0011, 0x0013, 0x0014, 0x0016, 0x0017, 0x0019, 0x001b, 0x001d, 0x001f, 0x0021, 0x0023, 0x0025, 0x0027, 0x0029, 0x002b, 0x002e, 0x0030, 0x0033, 0x0035, 0x0038, 0x003b, 0x003e, 0x0040, 0x0043, 0x0046, 0x004a, 0x004d, 0x0050, 0x0053, 0x0057, 0x005b, 0x005e, 0x0062, 0x0066, 0x006a, 0x006e, 0x0072, 0x0076, 0x007a, 0x007f, 0x0083, 0x0088, 0x008d, 0x0092, 0x0097, 0x009c, 0x00a1, 0x00a7, 0x00ac, 0x00b2, 0x00b8, 0x00be, 0x00c4, 0x00ca, 0x00d1, 0x00d7, 0x00de, 0x00e5, 0x00ec, 0x00f4, 0x00fb, 0x0103, 0x010b, 0x0114, 0x011c, 0x0125, 0x012e, 0x0137, 0x0141, 0x014b, 0x0155, 0x0160, 0x016b, 0x0177, 0x0182, 0x018f, 0x019b, 0x01a9, 0x01b7, 0x01c5, 0x01d4, 0x01e4, 0x01f5, 0x0206, 0x0218, 0x022c, 0x0240, 0x0256, 0x026d, 0x0286, 0x02a0, 0x02bd, 0x02dc, 0x02ff, 0x0324, 0x034e, 0x037e, 0x03b5, 0x03f5, 0x0443, 0x04a6, 0x052e, 0x0607, 0x0859, 0x0859, 0x0607, 0x052e, 0x04a6, 0x0443, 0x03f5, 0x03b5, 0x037e, 0x034e, 0x0324, 0x02ff, 0x02dc, 0x02bd, 0x02a0, 0x0286, 0x026d, 0x0256, 0x0240, 0x022c, 0x0218, 0x0206, 0x01f5, 0x01e4, 0x01d4, 0x01c5, 0x01b7, 0x01a9, 0x019b, 0x018f, 0x0182, 0x0177, 0x016b, 0x0160, 0x0155, 0x014b, 0x0141, 0x0137, 0x012e, 0x0125, 0x011c, 0x0114, 0x010b, 0x0103, 0x00fb, 0x00f4, 0x00ec, 0x00e5, 0x00de, 0x00d7, 0x00d1, 0x00ca, 0x00c4, 0x00be, 0x00b8, 0x00b2, 0x00ac, 0x00a7, 0x00a1, 0x009c, 0x0097, 0x0092, 0x008d, 0x0088, 0x0083, 0x007f, 0x007a, 0x0076, 0x0072, 0x006e, 0x006a, 0x0066, 0x0062, 0x005e, 0x005b, 0x0057, 0x0053, 0x0050, 0x004d, 0x004a, 0x0046, 0x0043, 0x0040, 0x003e, 0x003b, 0x0038, 0x0035, 0x0033, 0x0030, 0x002e, 0x002b, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021, 0x001f, 0x001d, 0x001b, 0x0019, 0x0017, 0x0016, 0x0014, 0x0013, 0x0011, 0x0010, 0x000f, 0x000d, 0x000c, 0x000b, 0x000a, 0x0009, 0x0008, 0x0007, 0x0006, 0x0005, 0x0005, 0x0004, 0x0003, 0x0003, 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0001, 0x0002, 0x0002, 0x0003, 0x0003, 0x0004, 0x0005, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000f, 0x0010, 0x0011, 0x0013, 0x0014, 0x0016, 0x0017, 0x0019, 0x001b, 0x001d, 0x001f, 0x0021, 0x0023, 0x0025, 0x0027, 0x0029, 0x002b, 0x002e, 0x0030, 0x0033, 0x0035, 0x0038, 0x003b, 0x003e, 0x0040, 0x0043, 0x0046, 0x004a, 0x004d, 0x0050, 0x0053, 0x0057, 0x005b, 0x005e, 0x0062, 0x0066, 0x006a, 0x006e, 0x0072, 0x0076, 0x007a, 0x007f, 0x0083, 0x0088, 0x008d, 0x0092, 0x0097, 0x009c, 0x00a1, 0x00a7, 0x00ac, 0x00b2, 0x00b8, 0x00be, 0x00c4, 0x00ca, 0x00d1, 0x00d7, 0x00de, 0x00e5, 0x00ec, 0x00f4, 0x00fb, 0x0103, 0x010b, 0x0114, 0x011c, 0x0125, 0x012e, 0x0137, 0x0141, 0x014b, 0x0155, 0x0160, 0x016b, 0x0177, 0x0182, 0x018f, 0x019b, 0x01a9, 0x01b7, 0x01c5, 0x01d4, 0x01e4, 0x01f5, 0x0206, 0x0218, 0x022c, 0x0240, 0x0256, 0x026d, 0x0286, 0x02a0, 0x02bd, 0x02dc, 0x02ff, 0x0324, 0x034e, 0x037e, 0x03b5, 0x03f5, 0x0443, 0x04a6, 0x052e, 0x0607, 0x0859, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, // wave 6 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, // wave 7 0x0000, 0x0008, 0x0010, 0x0018, 0x0020, 0x0028, 0x0030, 0x0038, 0x0040, 0x0048, 0x0050, 0x0058, 0x0060, 0x0068, 0x0070, 0x0078, 0x0080, 0x0088, 0x0090, 0x0098, 0x00a0, 0x00a8, 0x00b0, 0x00b8, 0x00c0, 0x00c8, 0x00d0, 0x00d8, 0x00e0, 0x00e8, 0x00f0, 0x00f8, 0x0100, 0x0108, 0x0110, 0x0118, 0x0120, 0x0128, 0x0130, 0x0138, 0x0140, 0x0148, 0x0150, 0x0158, 0x0160, 0x0168, 0x0170, 0x0178, 0x0180, 0x0188, 0x0190, 0x0198, 0x01a0, 0x01a8, 0x01b0, 0x01b8, 0x01c0, 0x01c8, 0x01d0, 0x01d8, 0x01e0, 0x01e8, 0x01f0, 0x01f8, 0x0200, 0x0208, 0x0210, 0x0218, 0x0220, 0x0228, 0x0230, 0x0238, 0x0240, 0x0248, 0x0250, 0x0258, 0x0260, 0x0268, 0x0270, 0x0278, 0x0280, 0x0288, 0x0290, 0x0298, 0x02a0, 0x02a8, 0x02b0, 0x02b8, 0x02c0, 0x02c8, 0x02d0, 0x02d8, 0x02e0, 0x02e8, 0x02f0, 0x02f8, 0x0300, 0x0308, 0x0310, 0x0318, 0x0320, 0x0328, 0x0330, 0x0338, 0x0340, 0x0348, 0x0350, 0x0358, 0x0360, 0x0368, 0x0370, 0x0378, 0x0380, 0x0388, 0x0390, 0x0398, 0x03a0, 0x03a8, 0x03b0, 0x03b8, 0x03c0, 0x03c8, 0x03d0, 0x03d8, 0x03e0, 0x03e8, 0x03f0, 0x03f8, 0x0400, 0x0408, 0x0410, 0x0418, 0x0420, 0x0428, 0x0430, 0x0438, 0x0440, 0x0448, 0x0450, 0x0458, 0x0460, 0x0468, 0x0470, 0x0478, 0x0480, 0x0488, 0x0490, 0x0498, 0x04a0, 0x04a8, 0x04b0, 0x04b8, 0x04c0, 0x04c8, 0x04d0, 0x04d8, 0x04e0, 0x04e8, 0x04f0, 0x04f8, 0x0500, 0x0508, 0x0510, 0x0518, 0x0520, 0x0528, 0x0530, 0x0538, 0x0540, 0x0548, 0x0550, 0x0558, 0x0560, 0x0568, 0x0570, 0x0578, 0x0580, 0x0588, 0x0590, 0x0598, 0x05a0, 0x05a8, 0x05b0, 0x05b8, 0x05c0, 0x05c8, 0x05d0, 0x05d8, 0x05e0, 0x05e8, 0x05f0, 0x05f8, 0x0600, 0x0608, 0x0610, 0x0618, 0x0620, 0x0628, 0x0630, 0x0638, 0x0640, 0x0648, 0x0650, 0x0658, 0x0660, 0x0668, 0x0670, 0x0678, 0x0680, 0x0688, 0x0690, 0x0698, 0x06a0, 0x06a8, 0x06b0, 0x06b8, 0x06c0, 0x06c8, 0x06d0, 0x06d8, 0x06e0, 0x06e8, 0x06f0, 0x06f8, 0x0700, 0x0708, 0x0710, 0x0718, 0x0720, 0x0728, 0x0730, 0x0738, 0x0740, 0x0748, 0x0750, 0x0758, 0x0760, 0x0768, 0x0770, 0x0778, 0x0780, 0x0788, 0x0790, 0x0798, 0x07a0, 0x07a8, 0x07b0, 0x07b8, 0x07c0, 0x07c8, 0x07d0, 0x07d8, 0x07e0, 0x07e8, 0x07f0, 0x07f8, 0x0800, 0x0808, 0x0810, 0x0818, 0x0820, 0x0828, 0x0830, 0x0838, 0x0840, 0x0848, 0x0850, 0x0858, 0x0860, 0x0868, 0x0870, 0x0878, 0x0880, 0x0888, 0x0890, 0x0898, 0x08a0, 0x08a8, 0x08b0, 0x08b8, 0x08c0, 0x08c8, 0x08d0, 0x08d8, 0x08e0, 0x08e8, 0x08f0, 0x08f8, 0x0900, 0x0908, 0x0910, 0x0918, 0x0920, 0x0928, 0x0930, 0x0938, 0x0940, 0x0948, 0x0950, 0x0958, 0x0960, 0x0968, 0x0970, 0x0978, 0x0980, 0x0988, 0x0990, 0x0998, 0x09a0, 0x09a8, 0x09b0, 0x09b8, 0x09c0, 0x09c8, 0x09d0, 0x09d8, 0x09e0, 0x09e8, 0x09f0, 0x09f8, 0x0a00, 0x0a08, 0x0a10, 0x0a18, 0x0a20, 0x0a28, 0x0a30, 0x0a38, 0x0a40, 0x0a48, 0x0a50, 0x0a58, 0x0a60, 0x0a68, 0x0a70, 0x0a78, 0x0a80, 0x0a88, 0x0a90, 0x0a98, 0x0aa0, 0x0aa8, 0x0ab0, 0x0ab8, 0x0ac0, 0x0ac8, 0x0ad0, 0x0ad8, 0x0ae0, 0x0ae8, 0x0af0, 0x0af8, 0x0b00, 0x0b08, 0x0b10, 0x0b18, 0x0b20, 0x0b28, 0x0b30, 0x0b38, 0x0b40, 0x0b48, 0x0b50, 0x0b58, 0x0b60, 0x0b68, 0x0b70, 0x0b78, 0x0b80, 0x0b88, 0x0b90, 0x0b98, 0x0ba0, 0x0ba8, 0x0bb0, 0x0bb8, 0x0bc0, 0x0bc8, 0x0bd0, 0x0bd8, 0x0be0, 0x0be8, 0x0bf0, 0x0bf8, 0x0c00, 0x0c08, 0x0c10, 0x0c18, 0x0c20, 0x0c28, 0x0c30, 0x0c38, 0x0c40, 0x0c48, 0x0c50, 0x0c58, 0x0c60, 0x0c68, 0x0c70, 0x0c78, 0x0c80, 0x0c88, 0x0c90, 0x0c98, 0x0ca0, 0x0ca8, 0x0cb0, 0x0cb8, 0x0cc0, 0x0cc8, 0x0cd0, 0x0cd8, 0x0ce0, 0x0ce8, 0x0cf0, 0x0cf8, 0x0d00, 0x0d08, 0x0d10, 0x0d18, 0x0d20, 0x0d28, 0x0d30, 0x0d38, 0x0d40, 0x0d48, 0x0d50, 0x0d58, 0x0d60, 0x0d68, 0x0d70, 0x0d78, 0x0d80, 0x0d88, 0x0d90, 0x0d98, 0x0da0, 0x0da8, 0x0db0, 0x0db8, 0x0dc0, 0x0dc8, 0x0dd0, 0x0dd8, 0x0de0, 0x0de8, 0x0df0, 0x0df8, 0x0e00, 0x0e08, 0x0e10, 0x0e18, 0x0e20, 0x0e28, 0x0e30, 0x0e38, 0x0e40, 0x0e48, 0x0e50, 0x0e58, 0x0e60, 0x0e68, 0x0e70, 0x0e78, 0x0e80, 0x0e88, 0x0e90, 0x0e98, 0x0ea0, 0x0ea8, 0x0eb0, 0x0eb8, 0x0ec0, 0x0ec8, 0x0ed0, 0x0ed8, 0x0ee0, 0x0ee8, 0x0ef0, 0x0ef8, 0x0f00, 0x0f08, 0x0f10, 0x0f18, 0x0f20, 0x0f28, 0x0f30, 0x0f38, 0x0f40, 0x0f48, 0x0f50, 0x0f58, 0x0f60, 0x0f68, 0x0f70, 0x0f78, 0x0f80, 0x0f88, 0x0f90, 0x0f98, 0x0fa0, 0x0fa8, 0x0fb0, 0x0fb8, 0x0fc0, 0x0fc8, 0x0fd0, 0x0fd8, 0x0fe0, 0x0fe8, 0x0ff0, 0x0ff8, 0x8ff8, 0x8ff0, 0x8fe8, 0x8fe0, 0x8fd8, 0x8fd0, 0x8fc8, 0x8fc0, 0x8fb8, 0x8fb0, 0x8fa8, 0x8fa0, 0x8f98, 0x8f90, 0x8f88, 0x8f80, 0x8f78, 0x8f70, 0x8f68, 0x8f60, 0x8f58, 0x8f50, 0x8f48, 0x8f40, 0x8f38, 0x8f30, 0x8f28, 0x8f20, 0x8f18, 0x8f10, 0x8f08, 0x8f00, 0x8ef8, 0x8ef0, 0x8ee8, 0x8ee0, 0x8ed8, 0x8ed0, 0x8ec8, 0x8ec0, 0x8eb8, 0x8eb0, 0x8ea8, 0x8ea0, 0x8e98, 0x8e90, 0x8e88, 0x8e80, 0x8e78, 0x8e70, 0x8e68, 0x8e60, 0x8e58, 0x8e50, 0x8e48, 0x8e40, 0x8e38, 0x8e30, 0x8e28, 0x8e20, 0x8e18, 0x8e10, 0x8e08, 0x8e00, 0x8df8, 0x8df0, 0x8de8, 0x8de0, 0x8dd8, 0x8dd0, 0x8dc8, 0x8dc0, 0x8db8, 0x8db0, 0x8da8, 0x8da0, 0x8d98, 0x8d90, 0x8d88, 0x8d80, 0x8d78, 0x8d70, 0x8d68, 0x8d60, 0x8d58, 0x8d50, 0x8d48, 0x8d40, 0x8d38, 0x8d30, 0x8d28, 0x8d20, 0x8d18, 0x8d10, 0x8d08, 0x8d00, 0x8cf8, 0x8cf0, 0x8ce8, 0x8ce0, 0x8cd8, 0x8cd0, 0x8cc8, 0x8cc0, 0x8cb8, 0x8cb0, 0x8ca8, 0x8ca0, 0x8c98, 0x8c90, 0x8c88, 0x8c80, 0x8c78, 0x8c70, 0x8c68, 0x8c60, 0x8c58, 0x8c50, 0x8c48, 0x8c40, 0x8c38, 0x8c30, 0x8c28, 0x8c20, 0x8c18, 0x8c10, 0x8c08, 0x8c00, 0x8bf8, 0x8bf0, 0x8be8, 0x8be0, 0x8bd8, 0x8bd0, 0x8bc8, 0x8bc0, 0x8bb8, 0x8bb0, 0x8ba8, 0x8ba0, 0x8b98, 0x8b90, 0x8b88, 0x8b80, 0x8b78, 0x8b70, 0x8b68, 0x8b60, 0x8b58, 0x8b50, 0x8b48, 0x8b40, 0x8b38, 0x8b30, 0x8b28, 0x8b20, 0x8b18, 0x8b10, 0x8b08, 0x8b00, 0x8af8, 0x8af0, 0x8ae8, 0x8ae0, 0x8ad8, 0x8ad0, 0x8ac8, 0x8ac0, 0x8ab8, 0x8ab0, 0x8aa8, 0x8aa0, 0x8a98, 0x8a90, 0x8a88, 0x8a80, 0x8a78, 0x8a70, 0x8a68, 0x8a60, 0x8a58, 0x8a50, 0x8a48, 0x8a40, 0x8a38, 0x8a30, 0x8a28, 0x8a20, 0x8a18, 0x8a10, 0x8a08, 0x8a00, 0x89f8, 0x89f0, 0x89e8, 0x89e0, 0x89d8, 0x89d0, 0x89c8, 0x89c0, 0x89b8, 0x89b0, 0x89a8, 0x89a0, 0x8998, 0x8990, 0x8988, 0x8980, 0x8978, 0x8970, 0x8968, 0x8960, 0x8958, 0x8950, 0x8948, 0x8940, 0x8938, 0x8930, 0x8928, 0x8920, 0x8918, 0x8910, 0x8908, 0x8900, 0x88f8, 0x88f0, 0x88e8, 0x88e0, 0x88d8, 0x88d0, 0x88c8, 0x88c0, 0x88b8, 0x88b0, 0x88a8, 0x88a0, 0x8898, 0x8890, 0x8888, 0x8880, 0x8878, 0x8870, 0x8868, 0x8860, 0x8858, 0x8850, 0x8848, 0x8840, 0x8838, 0x8830, 0x8828, 0x8820, 0x8818, 0x8810, 0x8808, 0x8800, 0x87f8, 0x87f0, 0x87e8, 0x87e0, 0x87d8, 0x87d0, 0x87c8, 0x87c0, 0x87b8, 0x87b0, 0x87a8, 0x87a0, 0x8798, 0x8790, 0x8788, 0x8780, 0x8778, 0x8770, 0x8768, 0x8760, 0x8758, 0x8750, 0x8748, 0x8740, 0x8738, 0x8730, 0x8728, 0x8720, 0x8718, 0x8710, 0x8708, 0x8700, 0x86f8, 0x86f0, 0x86e8, 0x86e0, 0x86d8, 0x86d0, 0x86c8, 0x86c0, 0x86b8, 0x86b0, 0x86a8, 0x86a0, 0x8698, 0x8690, 0x8688, 0x8680, 0x8678, 0x8670, 0x8668, 0x8660, 0x8658, 0x8650, 0x8648, 0x8640, 0x8638, 0x8630, 0x8628, 0x8620, 0x8618, 0x8610, 0x8608, 0x8600, 0x85f8, 0x85f0, 0x85e8, 0x85e0, 0x85d8, 0x85d0, 0x85c8, 0x85c0, 0x85b8, 0x85b0, 0x85a8, 0x85a0, 0x8598, 0x8590, 0x8588, 0x8580, 0x8578, 0x8570, 0x8568, 0x8560, 0x8558, 0x8550, 0x8548, 0x8540, 0x8538, 0x8530, 0x8528, 0x8520, 0x8518, 0x8510, 0x8508, 0x8500, 0x84f8, 0x84f0, 0x84e8, 0x84e0, 0x84d8, 0x84d0, 0x84c8, 0x84c0, 0x84b8, 0x84b0, 0x84a8, 0x84a0, 0x8498, 0x8490, 0x8488, 0x8480, 0x8478, 0x8470, 0x8468, 0x8460, 0x8458, 0x8450, 0x8448, 0x8440, 0x8438, 0x8430, 0x8428, 0x8420, 0x8418, 0x8410, 0x8408, 0x8400, 0x83f8, 0x83f0, 0x83e8, 0x83e0, 0x83d8, 0x83d0, 0x83c8, 0x83c0, 0x83b8, 0x83b0, 0x83a8, 0x83a0, 0x8398, 0x8390, 0x8388, 0x8380, 0x8378, 0x8370, 0x8368, 0x8360, 0x8358, 0x8350, 0x8348, 0x8340, 0x8338, 0x8330, 0x8328, 0x8320, 0x8318, 0x8310, 0x8308, 0x8300, 0x82f8, 0x82f0, 0x82e8, 0x82e0, 0x82d8, 0x82d0, 0x82c8, 0x82c0, 0x82b8, 0x82b0, 0x82a8, 0x82a0, 0x8298, 0x8290, 0x8288, 0x8280, 0x8278, 0x8270, 0x8268, 0x8260, 0x8258, 0x8250, 0x8248, 0x8240, 0x8238, 0x8230, 0x8228, 0x8220, 0x8218, 0x8210, 0x8208, 0x8200, 0x81f8, 0x81f0, 0x81e8, 0x81e0, 0x81d8, 0x81d0, 0x81c8, 0x81c0, 0x81b8, 0x81b0, 0x81a8, 0x81a0, 0x8198, 0x8190, 0x8188, 0x8180, 0x8178, 0x8170, 0x8168, 0x8160, 0x8158, 0x8150, 0x8148, 0x8140, 0x8138, 0x8130, 0x8128, 0x8120, 0x8118, 0x8110, 0x8108, 0x8100, 0x80f8, 0x80f0, 0x80e8, 0x80e0, 0x80d8, 0x80d0, 0x80c8, 0x80c0, 0x80b8, 0x80b0, 0x80a8, 0x80a0, 0x8098, 0x8090, 0x8088, 0x8080, 0x8078, 0x8070, 0x8068, 0x8060, 0x8058, 0x8050, 0x8048, 0x8040, 0x8038, 0x8030, 0x8028, 0x8020, 0x8018, 0x8010, 0x8008, 0x8000, }; /* * Inverse exponent table extracted from OPL3 ROM; taken straight from * Nuked OPL3 source code. * TODO: Verify if ESFM uses an exponent table or if it possibly uses another * method to skirt around Yamaha's patents? * Optimization: All entries are shifted left by one from the actual data in * OPL3's ROM. */ static const uint16_t exprom[256] = { 0xff4, 0xfea, 0xfde, 0xfd4, 0xfc8, 0xfbe, 0xfb4, 0xfa8, 0xf9e, 0xf92, 0xf88, 0xf7e, 0xf72, 0xf68, 0xf5c, 0xf52, 0xf48, 0xf3e, 0xf32, 0xf28, 0xf1e, 0xf14, 0xf08, 0xefe, 0xef4, 0xeea, 0xee0, 0xed4, 0xeca, 0xec0, 0xeb6, 0xeac, 0xea2, 0xe98, 0xe8e, 0xe84, 0xe7a, 0xe70, 0xe66, 0xe5c, 0xe52, 0xe48, 0xe3e, 0xe34, 0xe2a, 0xe20, 0xe16, 0xe0c, 0xe04, 0xdfa, 0xdf0, 0xde6, 0xddc, 0xdd2, 0xdca, 0xdc0, 0xdb6, 0xdac, 0xda4, 0xd9a, 0xd90, 0xd88, 0xd7e, 0xd74, 0xd6a, 0xd62, 0xd58, 0xd50, 0xd46, 0xd3c, 0xd34, 0xd2a, 0xd22, 0xd18, 0xd10, 0xd06, 0xcfe, 0xcf4, 0xcec, 0xce2, 0xcda, 0xcd0, 0xcc8, 0xcbe, 0xcb6, 0xcae, 0xca4, 0xc9c, 0xc92, 0xc8a, 0xc82, 0xc78, 0xc70, 0xc68, 0xc60, 0xc56, 0xc4e, 0xc46, 0xc3c, 0xc34, 0xc2c, 0xc24, 0xc1c, 0xc12, 0xc0a, 0xc02, 0xbfa, 0xbf2, 0xbea, 0xbe0, 0xbd8, 0xbd0, 0xbc8, 0xbc0, 0xbb8, 0xbb0, 0xba8, 0xba0, 0xb98, 0xb90, 0xb88, 0xb80, 0xb78, 0xb70, 0xb68, 0xb60, 0xb58, 0xb50, 0xb48, 0xb40, 0xb38, 0xb32, 0xb2a, 0xb22, 0xb1a, 0xb12, 0xb0a, 0xb02, 0xafc, 0xaf4, 0xaec, 0xae4, 0xade, 0xad6, 0xace, 0xac6, 0xac0, 0xab8, 0xab0, 0xaa8, 0xaa2, 0xa9a, 0xa92, 0xa8c, 0xa84, 0xa7c, 0xa76, 0xa6e, 0xa68, 0xa60, 0xa58, 0xa52, 0xa4a, 0xa44, 0xa3c, 0xa36, 0xa2e, 0xa28, 0xa20, 0xa18, 0xa12, 0xa0c, 0xa04, 0x9fe, 0x9f6, 0x9f0, 0x9e8, 0x9e2, 0x9da, 0x9d4, 0x9ce, 0x9c6, 0x9c0, 0x9b8, 0x9b2, 0x9ac, 0x9a4, 0x99e, 0x998, 0x990, 0x98a, 0x984, 0x97c, 0x976, 0x970, 0x96a, 0x962, 0x95c, 0x956, 0x950, 0x948, 0x942, 0x93c, 0x936, 0x930, 0x928, 0x922, 0x91c, 0x916, 0x910, 0x90a, 0x904, 0x8fc, 0x8f6, 0x8f0, 0x8ea, 0x8e4, 0x8de, 0x8d8, 0x8d2, 0x8cc, 0x8c6, 0x8c0, 0x8ba, 0x8b4, 0x8ae, 0x8a8, 0x8a2, 0x89c, 0x896, 0x890, 0x88a, 0x884, 0x87e, 0x878, 0x872, 0x86c, 0x866, 0x860, 0x85a, 0x854, 0x850, 0x84a, 0x844, 0x83e, 0x838, 0x832, 0x82c, 0x828, 0x822, 0x81c, 0x816, 0x810, 0x80c, 0x806, 0x800 }; /* * Frequency multiplier table multiplied by 2; taken straight from Nuked OPL3 * source code. */ static const uint8_t mt[16] = { 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 24, 24, 30, 30 }; /* * This is used during the envelope generation to apply KSL to the envelope by * determining how much to shift right the keyscale attenuation value before * adding it to the envelope level. */ static const uint8_t kslshift[4] = { 8, 1, 2, 0 }; /* * This encodes which emulation mode channels are the secondary channel in a * 4-op channel pair (where the entry is non-negative), and which is the * corresponding primary channel for that secondary channel. */ static const int emu_4op_secondary_to_primary[18] = { -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, 9, 10, 11, -1, -1, -1 }; /* * Envelope generator dither table, taken straight from Nuked OPL3 source code. */ static const uint8_t eg_incstep[4][4] = { { 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 } }; /* your_sha256_hash--------- */ static inline int13 ESFM_envelope_wavegen(uint3 waveform, int16 phase, uint10 envelope) { int13 out; uint16 lookup = logsinrom[((uint16)waveform << 10) | (phase & 0x3ff)]; uint16 level = (lookup & 0x1fff) + (envelope << 3); if (level > 0x1fff) { level = 0x1fff; } out = exprom[level & 0xff] >> (level >> 8); if (lookup & 0x8000) { out = -out; } return out; } /* your_sha256_hash--------- */ static void ESFM_envelope_calc(esfm_slot *slot) { uint8 nonzero; uint8 rate; uint5 rate_hi; uint2 rate_lo; uint4 reg_rate = 0; uint4 ks; uint8 eg_shift, shift; bool eg_off; uint9 eg_rout; int16 eg_inc; bool reset = 0; bool key_on; bool key_on_signal; key_on = *slot->in.key_on; if (!slot->chip->native_mode) { int pair_primary_idx = emu_4op_secondary_to_primary[slot->channel->channel_idx]; if (pair_primary_idx >= 0) { esfm_channel *pair_primary = &slot->channel->chip->channels[pair_primary_idx]; if (pair_primary->emu_mode_4op_enable) { key_on = *pair_primary->slots[0].in.key_on; } } else if ((slot->channel->channel_idx == 7 || slot->channel->channel_idx == 8) && slot->slot_idx == 1) { key_on = slot->channel->key_on_2; } } slot->in.eg_output = slot->in.eg_position + (slot->t_level << 2) + (slot->in.eg_ksl_offset >> kslshift[slot->ksl]); if (slot->tremolo_en) { uint8 tremolo; if (slot->chip->native_mode) { tremolo = slot->channel->chip->tremolo >> ((!slot->tremolo_deep << 1) + 2); } else { tremolo = slot->channel->chip->tremolo >> ((!slot->chip->emu_tremolo_deep << 1) + 2); } slot->in.eg_output += tremolo; } if (slot->in.eg_delay_run && slot->in.eg_delay_counter < 32768) { slot->in.eg_delay_counter++; } // triggers on key-on edge if (key_on && !slot->in.key_on_gate) { slot->in.eg_delay_run = 1; slot->in.eg_delay_counter = 0; slot->in.eg_delay_transitioned_01 = 0; slot->in.eg_delay_transitioned_01_gate = 0; slot->in.eg_delay_transitioned_10 = 0; slot->in.eg_delay_transitioned_10_gate = 0; slot->in.eg_delay_counter_compare = 0; if (slot->env_delay > 0) { slot->in.eg_delay_counter_compare = 256 << slot->env_delay; } } else if (!key_on) { slot->in.eg_delay_run = 0; } // TODO: is this really how the chip behaves? Can it only transition the envelope delay once? Am I implementing this in a sane way? I feel like this is a roundabout hack. if ((slot->in.eg_delay_transitioned_10 && !slot->in.eg_delay_transitioned_10_gate) || (slot->in.eg_delay_transitioned_01 && !slot->in.eg_delay_transitioned_01_gate) ) { slot->in.eg_delay_counter_compare = 0; if (slot->env_delay > 0) { slot->in.eg_delay_counter_compare = 256 << slot->env_delay; } if (slot->in.eg_delay_transitioned_10) { slot->in.eg_delay_transitioned_10_gate = 1; } if (slot->in.eg_delay_transitioned_01) { slot->in.eg_delay_transitioned_01_gate = 1; } } if (key_on && ((slot->in.eg_delay_counter >= slot->in.eg_delay_counter_compare) || !slot->chip->native_mode)) { key_on_signal = 1; } else { key_on_signal = 0; } if (key_on && slot->in.eg_state == EG_RELEASE) { if ((slot->in.eg_delay_counter >= slot->in.eg_delay_counter_compare) || !slot->chip->native_mode) { reset = 1; reg_rate = slot->attack_rate; } else { reg_rate = slot->release_rate; } } else { switch (slot->in.eg_state) { case EG_ATTACK: reg_rate = slot->attack_rate; break; case EG_DECAY: reg_rate = slot->decay_rate; break; case EG_SUSTAIN: if (!slot->env_sustaining) { reg_rate = slot->release_rate; } break; case EG_RELEASE: reg_rate = slot->release_rate; break; } } slot->in.key_on_gate = key_on; slot->in.phase_reset = reset; ks = slot->in.keyscale >> ((!slot->ksr) << 1); nonzero = (reg_rate != 0); rate = ks + (reg_rate << 2); rate_hi = rate >> 2; rate_lo = rate & 0x03; if (rate_hi & 0x10) { rate_hi = 0x0f; } eg_shift = rate_hi + slot->chip->eg_clocks; shift = 0; if (nonzero) { if (rate_hi < 12) { if (slot->chip->eg_tick) { switch (eg_shift) { case 12: shift = 1; break; case 13: shift = (rate_lo >> 1) & 0x01; break; case 14: shift = rate_lo & 0x01; break; default: break; } } } else { shift = (rate_hi & 0x03) + eg_incstep[rate_lo][slot->chip->global_timer & 0x03]; if (shift & 0x04) { shift = 0x03; } if (!shift) { shift = slot->chip->eg_tick; } } } eg_rout = slot->in.eg_position; eg_inc = 0; eg_off = 0; /* Instant attack */ if (reset && rate_hi == 0x0f) { eg_rout = 0x00; } /* Envelope off */ if ((slot->in.eg_position & 0x1f8) == 0x1f8) { eg_off = 1; } if (slot->in.eg_state != EG_ATTACK && !reset && eg_off) { eg_rout = 0x1ff; } switch (slot->in.eg_state) { case EG_ATTACK: if (slot->in.eg_position == 0) { slot->in.eg_state = EG_DECAY; } else if (key_on_signal && shift > 0 && rate_hi != 0x0f) { eg_inc = ~slot->in.eg_position >> (4 - shift); } break; case EG_DECAY: if ((slot->in.eg_position >> 4) == slot->sustain_lvl) { slot->in.eg_state = EG_SUSTAIN; } else if (!eg_off && !reset && shift > 0) { eg_inc = 1 << (shift - 1); } break; case EG_SUSTAIN: case EG_RELEASE: if (!eg_off && !reset && shift > 0) { eg_inc = 1 << (shift - 1); } break; } slot->in.eg_position = (eg_rout + eg_inc) & 0x1ff; /* Key off */ if (reset) { slot->in.eg_state = EG_ATTACK; } if (!key_on_signal) { slot->in.eg_state = EG_RELEASE; } } /* your_sha256_hash--------- */ static void ESFM_phase_generate(esfm_slot *slot) { esfm_chip *chip; uint10 f_num; uint32 basefreq; bool rm_xor, n_bit; uint23 noise; uint10 phase; chip = slot->chip; f_num = slot->f_num; if (slot->vibrato_en) { int8_t range; uint8_t vibpos; range = (f_num >> 7) & 7; vibpos = chip->vibrato_pos; if (!(vibpos & 3)) { range = 0; } else if (vibpos & 1) { range >>= 1; } range >>= !slot->vibrato_deep; if (vibpos & 4) { range = -range; } f_num += range; } basefreq = (f_num << slot->block) >> 1; phase = (uint10)(slot->in.phase_acc >> 9); if (slot->in.phase_reset) { slot->in.phase_acc = 0; } slot->in.phase_acc += (basefreq * mt[slot->mult]) >> 1; slot->in.phase_acc &= (1 << 19) - 1; slot->in.phase_out = phase; /* Noise mode (rhythm) sounds */ noise = chip->lfsr; if (slot->slot_idx == 3 && slot->rhy_noise) { esfm_slot *prev_slot = &slot->channel->slots[2]; chip->rm_hh_bit2 = (phase >> 2) & 1; chip->rm_hh_bit3 = (phase >> 3) & 1; chip->rm_hh_bit7 = (phase >> 7) & 1; chip->rm_hh_bit8 = (phase >> 8) & 1; chip->rm_tc_bit3 = (prev_slot->in.phase_out >> 3) & 1; chip->rm_tc_bit5 = (prev_slot->in.phase_out >> 5) & 1; rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7) | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5) | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5); switch(slot->rhy_noise) { case 1: // SD slot->in.phase_out = (chip->rm_hh_bit8 << 9) | ((chip->rm_hh_bit8 ^ (noise & 1)) << 8); break; case 2: // HH slot->in.phase_out = rm_xor << 9; if (rm_xor ^ (noise & 1)) { slot->in.phase_out |= 0xd0; } else { slot->in.phase_out |= 0x34; } break; case 3: // TC slot->in.phase_out = (rm_xor << 9) | 0x80; break; } } n_bit = ((noise >> 14) ^ noise) & 0x01; chip->lfsr = (noise >> 1) | (n_bit << 22); } /* your_sha256_hash--------- */ static void ESFM_phase_generate_emu(esfm_slot *slot) { esfm_chip *chip; uint3 block; uint10 f_num; uint32 basefreq; bool rm_xor, n_bit; uint23 noise; uint10 phase; int pair_primary_idx; chip = slot->chip; block = slot->channel->slots[0].block; f_num = slot->channel->slots[0].f_num; pair_primary_idx = emu_4op_secondary_to_primary[slot->channel->channel_idx]; if (pair_primary_idx >= 0) { esfm_channel *pair_primary = &slot->channel->chip->channels[pair_primary_idx]; if (pair_primary->emu_mode_4op_enable) { block = pair_primary->slots[0].block; f_num = pair_primary->slots[0].f_num; } } if (slot->vibrato_en) { int8_t range; uint8_t vibpos; range = (f_num >> 7) & 7; vibpos = chip->vibrato_pos; if (!(vibpos & 3)) { range = 0; } else if (vibpos & 1) { range >>= 1; } range >>= !chip->emu_vibrato_deep; if (vibpos & 4) { range = -range; } f_num += range; } basefreq = (f_num << block) >> 1; phase = (uint10)(slot->in.phase_acc >> 9); if (slot->in.phase_reset) { slot->in.phase_acc = 0; } slot->in.phase_acc += (basefreq * mt[slot->mult]) >> 1; slot->in.phase_acc &= (1 << 19) - 1; slot->in.phase_out = phase; /* Noise mode (rhythm) sounds */ noise = chip->lfsr; // HH if (slot->channel->channel_idx == 7 && slot->slot_idx == 0) { chip->rm_hh_bit2 = (phase >> 2) & 1; chip->rm_hh_bit3 = (phase >> 3) & 1; chip->rm_hh_bit7 = (phase >> 7) & 1; chip->rm_hh_bit8 = (phase >> 8) & 1; } // TC if (slot->channel->channel_idx == 8 && slot->slot_idx == 1) { chip->rm_tc_bit3 = (phase >> 3) & 1; chip->rm_tc_bit5 = (phase >> 5) & 1; } if (chip->emu_rhy_mode_flags & 0x20) { rm_xor = (chip->rm_hh_bit2 ^ chip->rm_hh_bit7) | (chip->rm_hh_bit3 ^ chip->rm_tc_bit5) | (chip->rm_tc_bit3 ^ chip->rm_tc_bit5); if (slot->channel->channel_idx == 7) { if (slot->slot_idx == 0) { // HH slot->in.phase_out = rm_xor << 9; if (rm_xor ^ (noise & 1)) { slot->in.phase_out |= 0xd0; } else { slot->in.phase_out |= 0x34; } } else if (slot->slot_idx == 1) { // SD slot->in.phase_out = (chip->rm_hh_bit8 << 9) | ((chip->rm_hh_bit8 ^ (noise & 1)) << 8); } } else if (slot->channel->channel_idx == 8 && slot->slot_idx == 1) { // TC slot->in.phase_out = (rm_xor << 9) | 0x80; } } n_bit = ((noise >> 14) ^ noise) & 0x01; chip->lfsr = (noise >> 1) | (n_bit << 22); } /** * TODO: Figure out what's ACTUALLY going on inside the real chip! * This is not accurate at all, but it's the closest I was able to get with * empirical testing (and it's closer than nothing). */ /* your_sha256_hash--------- */ static int16 ESFM_slot3_noise3_mod_input_calc(esfm_slot *slot) { esfm_channel *channel = slot->channel; int16 phase; int13 output_buf = *channel->slots[1].in.mod_input; int i; // Go through previous slots' partial results and recalculate outputs // (we skip slot 0 because its calculation happens at the end, not at the beginning) for (i = 1; i < 3; i++) { // double the pitch phase = channel->slots[i].in.phase_acc >> 8; if (channel->slots[i].mod_in_level) { phase += output_buf >> (7 - channel->slots[i].mod_in_level); } output_buf = ESFM_envelope_wavegen(channel->slots[2].waveform, phase, channel->slots[i].in.eg_output); } return output_buf >> (8 - slot->mod_in_level); } /* your_sha256_hash--------- */ static void ESFM_slot_generate(esfm_slot *slot) { int16 phase = slot->in.phase_out; if (slot->mod_in_level) { if (slot->slot_idx == 3 && slot->rhy_noise == 3) { phase += ESFM_slot3_noise3_mod_input_calc(slot); } else { phase += *slot->in.mod_input >> (7 - slot->mod_in_level); } } slot->in.output = ESFM_envelope_wavegen(slot->waveform, phase, slot->in.eg_output); if (slot->output_level) { int13 output_value = slot->in.output >> (7 - slot->output_level); slot->channel->output[0] += output_value & slot->out_enable[0]; slot->channel->output[1] += output_value & slot->out_enable[1]; } } /* your_sha256_hash--------- */ static void ESFM_slot_generate_emu(esfm_slot *slot) { const esfm_chip *chip = slot->chip; uint3 waveform = slot->waveform & (chip->emu_newmode != 0 ? 0x07 : 0x03); bool rhythm_slot_double_volume = (slot->chip->emu_rhy_mode_flags & 0x20) != 0 && slot->channel->channel_idx >= 6 && slot->channel->channel_idx < 9; int16 phase = slot->in.phase_out; int14 output_value; phase += *slot->in.mod_input & slot->in.emu_mod_enable; slot->in.output = ESFM_envelope_wavegen(waveform, phase, slot->in.eg_output); output_value = (slot->in.output & slot->in.emu_output_enable) << rhythm_slot_double_volume; if (chip->emu_newmode) { slot->channel->output[0] += output_value & slot->channel->slots[0].out_enable[0]; slot->channel->output[1] += output_value & slot->channel->slots[0].out_enable[1]; } else { slot->channel->output[0] += output_value; slot->channel->output[1] += output_value; } } /* your_sha256_hash--------- */ #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wunused-variable" #pragma clang diagnostic ignored "-Wunknown-pragmas" static void ESFM_process_feedback(esfm_chip *chip) { int channel_idx; for (channel_idx = 0; channel_idx < 18; channel_idx++) { esfm_slot *slot = &chip->channels[channel_idx].slots[0]; uint32 basefreq, phase_offset; uint3 block; uint10 f_num; int32_t wave_out, wave_last; int32_t phase_feedback; uint32_t iter_counter; uint3 waveform; uint3 mod_in_shift; uint32_t phase, phase_acc; uint10 eg_output; if (slot->mod_in_level && (chip->native_mode || (slot->in.mod_input == &slot->in.feedback_buf))) { if (chip->native_mode) { waveform = slot->waveform; } else { waveform = slot->waveform & (0x03 | (0x02 << (chip->emu_newmode != 0))); } f_num = slot->f_num; block = slot->block; basefreq = (f_num << block) >> 1; phase_offset = (basefreq * mt[slot->mult]) >> 1; mod_in_shift = 7 - slot->mod_in_level; phase_acc = (uint32_t)(slot->in.phase_acc - phase_offset * 28); eg_output = slot->in.eg_output; // ASM optimizaions! #if defined(__GNUC__) && defined(__x86_64__) && !defined(_ESFMU_DISABLE_ASM_OPTIMIZATIONS) asm ( "movzbq %[wave], %%r8 \n\t" "shll $11, %%r8d \n\t" "leaq %[sinrom], %%rax \n\t" "addq %%rax, %%r8 \n\t" "leaq %[exprom], %%r9 \n\t" "movzwl %[eg_out], %%r10d \n\t" "shll $3, %%r10d \n\t" "xorl %%r11d, %%r11d \n\t" "movl %%r11d, %[out] \n\t" "movl $29, %%edx \n" "1: \n\t" // phase_feedback = (wave_out + wave_last) >> 2; "movl %[out], %[p_fb] \n\t" "addl %%r11d, %[p_fb] \n\t" "sarl $2, %[p_fb] \n\t" // wave_last = wave_out "movl %[out], %%r11d \n\t" // phase = phase_feedback >> mod_in_shift; "movl %[p_fb], %%eax \n\t" "movb %[mod_in], %%cl \n\t" "sarl %%cl, %%eax \n\t" // phase += phase_acc >> 9; "movl %[p_acc], %%ebx \n\t" "sarl $9, %%ebx \n\t" "addl %%ebx, %%eax \n\t" // lookup = logsinrom[(waveform << 10) | (phase & 0x3ff)]; "andq $0x3ff, %%rax \n\t" "movzwl (%%r8, %%rax, 2), %%ebx \n\t" "movl %%ebx, %%eax \n\t" // level = (lookup & 0x1fff) + (envelope << 3); "movl $0x1fff, %%ecx \n\t" "andl %%ecx, %%eax \n\t" "addl %%r10d, %%eax \n\t" // if (level > 0x1fff) level = 0x1fff; "cmpl %%ecx, %%eax \n\t" "cmoval %%ecx, %%eax \n\t" // wave_out = exprom[level & 0xff] >> (level >> 8); "movb %%ah, %%cl \n\t" "movzbl %%al, %%eax \n\t" "movzwl (%%r9, %%rax, 2), %[out] \n\t" "shrl %%cl, %[out] \n\t" // if (lookup & 0x8000) wave_out = -wave_out; // in other words, lookup is negative "movl %[out], %%ecx \n\t" "negl %%ecx \n\t" "testw %%bx, %%bx \n\t" "cmovsl %%ecx, %[out] \n\t" // phase_acc += phase_offset "addl %[p_off], %[p_acc] \n\t" // loop "decl %%edx \n\t" "jne 1b \n\t" : [p_fb] "=&r" (phase_feedback), [p_acc] "+r" (phase_acc), [out] "=&r" (wave_out) : [p_off] "r" (phase_offset), [mod_in] "r" (mod_in_shift), [wave] "g" (waveform), [eg_out] "g" (eg_output), [sinrom] "m" (logsinrom), [exprom] "m" (exprom) : "cc", "ax", "bx", "cx", "dx", "r8", "r9", "r10", "r11" ); #elif defined(__GNUC__) && defined(__i386__) && !defined(_ESFMU_DISABLE_ASM_OPTIMIZATIONS) size_t logsinrom_addr = (size_t)logsinrom; size_t exprom_addr = (size_t)exprom; asm ( "movzbl %b[wave], %%eax \n\t" "shll $11, %%eax \n\t" "movl %[sinrom], %%edi \n\t" "addl %%eax, %%edi \n\t" "shlw $3, %[eg_out] \n\t" "xorl %[out], %[out] \n\t" "movl %[out], %[last] \n\t" "movl $29, %[i] \n" "1: \n\t" // phase_feedback = (wave_out + wave_last) >> 2; "movl %[out], %%eax \n\t" "addl %[last], %%eax \n\t" "sarl $2, %%eax \n\t" "movl %%eax, %[p_fb] \n\t" // wave_last = wave_out "movl %[out], %[last] \n\t" // phase = phase_feedback >> mod_in_shift; "movb %[mod_in], %%cl \n\t" "sarl %%cl, %%eax \n\t" // phase += phase_acc >> 9; "movl %[p_acc], %%ebx \n\t" "shrl $9, %%ebx \n\t" "addl %%ebx, %%eax \n\t" // lookup = logsinrom[(waveform << 10) | (phase & 0x3ff)]; "andl $0x3ff, %%eax \n\t" "movzwl (%%edi, %%eax, 2), %%ebx \n\t" "movl %%ebx, %%eax \n\t" // level = (lookup & 0x1fff) + (envelope << 3); "movl $0x1fff, %%ecx \n\t" "andl %%ecx, %%eax \n\t" "addw %[eg_out], %%ax \n\t" // if (level > 0x1fff) level = 0x1fff; "cmpl %%ecx, %%eax \n\t" "cmoval %%ecx, %%eax \n\t" // wave_out = exprom[level & 0xff] >> (level >> 8); "movb %%ah, %%cl \n\t" "movzbl %%al, %%eax \n\t" "movl %[exprom], %[out] \n\t" "movzwl (%[out], %%eax, 2), %[out] \n\t" "shrl %%cl, %[out] \n\t" // if (lookup & 0x8000) wave_out = -wave_out; // in other words, lookup is negative "movl %[out], %%ecx \n\t" "negl %%ecx \n\t" "testw %%bx, %%bx \n\t" "cmovsl %%ecx, %[out] \n\t" // phase_acc += phase_offset "addl %[p_off], %[p_acc] \n\t" // loop "decl %[i] \n\t" "jne 1b \n\t" : [p_fb] "=&m" (phase_feedback), [p_acc] "+r" (phase_acc), [out] "=&r" (wave_out), [last] "=&m" (wave_last), [eg_out] "+m" (eg_output) : [p_off] "m" (phase_offset), [mod_in] "m" (mod_in_shift), [wave] "m" (waveform), [sinrom] "m" (logsinrom_addr), [exprom] "m" (exprom_addr), [i] "m" (iter_counter) : "cc", "ax", "bx", "cx", "di" ); #elif defined(__GNUC__) && defined(__arm__) && !defined(_ESFMU_DISABLE_ASM_OPTIMIZATIONS) asm ( "movs r3, #0 \n\t" "movs %[out], #0 \n\t" "ldr r8, =0x1fff \n\t" "movs r2, #29 \n" "1: \n\t" // phase_feedback = (wave_out + wave_last) >> 2; "adds %[p_fb], %[out], r3 \n\t" "asrs %[p_fb], %[p_fb], #2 \n\t" // wave_last = wave_out "mov r3, %[out] \n\t" // phase = phase_feedback >> mod_in_shift; "asr r0, %[p_fb], %[mod_in] \n\t" // phase += phase_acc >> 9; "add r0, r0, %[p_acc], asr #9 \n\t" // lookup = logsinrom[(waveform << 10) | (phase & 0x3ff)]; "lsls r0, r0, #22 \n\t" "lsrs r0, r0, #21 \n\t" "ldrsh r1, [%[sinrom], r0] \n\t" // level = (lookup & 0x1fff) + (envelope << 3); "and r0, r8, r1 \n\t" "add r0, r0, %[eg_out], lsl #3 \n\t" // if (level > 0x1fff) level = 0x1fff; "cmp r0, r8 \n\t" "it hi \n\t" "movhi r0, r8 \n\t" // wave_out = exprom[level & 0xff] >> (level >> 8); "lsrs %[out], r0, #8 \n\t" "ands r0, r0, #255 \n\t" "lsls r0, r0, #1 \n\t" "ldrh r0, [%[exprom], r0] \n\t" "lsr %[out], r0, %[out] \n\t" // if (lookup & 0x8000) wave_out = -wave_out; // in other words, lookup is negative "tst r1, r1 \n\t" "it mi \n\t" "negmi %[out], %[out] \n\t" // phase_acc += phase_offset "adds %[p_acc], %[p_acc], %[p_off]\n\t" // loop "subs r2, r2, #1 \n\t" "bne 1b \n\t" : [p_fb] "=&r" (phase_feedback), [p_acc] "+r" (phase_acc), [out] "=&r" (wave_out) : [p_off] "r" (phase_offset), [mod_in] "r" (mod_in_shift), [eg_out] "r" (eg_output), [sinrom] "r" (logsinrom + waveform * 1024), [exprom] "r" (exprom) : "cc", "r0", "r1", "r2", "r3", "r8" ); #else wave_out = 0; wave_last = 0; for (iter_counter = 0; iter_counter < 29; iter_counter++) { phase_feedback = (wave_out + wave_last) >> 2; wave_last = wave_out; phase = phase_feedback >> mod_in_shift; phase += phase_acc >> 9; wave_out = ESFM_envelope_wavegen(waveform, phase, eg_output); phase_acc += phase_offset; } #endif // TODO: Figure out - is this how the ESFM chip does it, like the // patent literally says? (it's really hacky...) // slot->in.output = wave_out; // This would be the more canonical way to do it, reusing the rest of // the synthesis pipeline to finish the calculation: if (chip->native_mode) { slot->in.feedback_buf = phase_feedback; } else { slot->in.feedback_buf = phase_feedback >> (7 - slot->mod_in_level); } } } } /* your_sha256_hash--------- */ static void ESFM_process_channel(esfm_channel *channel) { int slot_idx; channel->output[0] = channel->output[1] = 0; for (slot_idx = 0; slot_idx < 4; slot_idx++) { esfm_slot *slot = &channel->slots[slot_idx]; ESFM_envelope_calc(slot); ESFM_phase_generate(slot); if(slot_idx > 0) { ESFM_slot_generate(slot); } } // ESFM feedback calculation takes a large number of clock cycles, so // defer slot 0 generation to the end // TODO: verify this behavior on real hardware } /* your_sha256_hash--------- */ static void ESFM_process_channel_emu(esfm_channel *channel) { int slot_idx; channel->output[0] = channel->output[1] = 0; for (slot_idx = 0; slot_idx < 2; slot_idx++) { esfm_slot *slot = &channel->slots[slot_idx]; ESFM_envelope_calc(slot); ESFM_phase_generate_emu(slot); if(slot_idx > 0) { ESFM_slot_generate_emu(slot); } } // ESFM feedback calculation takes a large number of clock cycles, so // defer slot 0 generation to the end // TODO: verify this behavior on real hardware } /* your_sha256_hash--------- */ static int16_t ESFM_clip_sample(int32 sample) { // TODO: Supposedly, the real ESFM chip actually overflows rather than // clipping. Verify that. if (sample > 32767) { sample = 32767; } else if (sample < -32768) { sample = -32768; } return (int16_t)sample; } #define TIMER1_CONST (0.2517482517482517) #define TIMER2_CONST (0.06293706293706293) /* your_sha256_hash--------- */ static void ESFM_update_timers(esfm_chip *chip) { int i; // Tremolo if ((chip->global_timer & 0x3f) == 0x3f) { chip->tremolo_pos = (chip->tremolo_pos + 1) % 210; if (chip->tremolo_pos < 105) { chip->tremolo = chip->tremolo_pos; } else { chip->tremolo = (210 - chip->tremolo_pos); } } // Vibrato if ((chip->global_timer & 0x3ff) == 0x3ff) { chip->vibrato_pos = (chip->vibrato_pos + 1) & 0x07; } chip->global_timer = (chip->global_timer + 1) & 0x3ff; // Envelope generator dither clocks chip->eg_clocks = 0; if (chip->eg_timer) { uint8 shift = 0; while (shift < 36 && ((chip->eg_timer >> shift) & 1) == 0) { shift++; } if (shift <= 12) { chip->eg_clocks = shift + 1; } } if (chip->eg_tick || chip->eg_timer_overflow) { if (chip->eg_timer == (1llu << 36) - 1) { chip->eg_timer = 0; chip->eg_timer_overflow = 1; } else { chip->eg_timer++; chip->eg_timer_overflow = 0; } } for (i = 0; i < 2; i++) { if (chip->timer_enable[i]) { chip->timer_accumulator[i] += (i == 0) ? TIMER1_CONST : TIMER2_CONST; if (chip->timer_accumulator[i] > 1.0) { chip->timer_accumulator[i] -= 1.0; chip->timer_counter[i]++; if (chip->timer_counter[i] == 0) { if (chip->timer_mask[i] == 0) { chip->irq_bit = true; chip->timer_overflow[i] = true; } chip->timer_counter[i] = chip->timer_reload[i]; } } } } chip->eg_tick ^= 1; } #define KEY_ON_REGS_START (18 * 4 * 8) /* your_sha256_hash--------- */ int ESFM_reg_write_chan_idx(esfm_chip *chip, uint16_t reg) { int which_reg = -1; if (chip->native_mode) { bool is_key_on_reg = reg >= KEY_ON_REGS_START && reg < (KEY_ON_REGS_START + 20); if (is_key_on_reg) { which_reg = reg - KEY_ON_REGS_START; } } else { uint8_t reg_low = reg & 0xff; bool high = reg & 0x100; bool is_key_on_reg = reg_low >= 0xb0 && reg_low < 0xb9; if (is_key_on_reg) { which_reg = (reg_low & 0x0f) + high * 9; } } return which_reg; } /* your_sha256_hash--------- */ void ESFM_update_write_buffer(esfm_chip *chip) { esfm_write_buf *write_buf; bool note_off_written[20]; bool bassdrum_written = false; int i; for (i = 0; i < 20; i++) { note_off_written[i] = false; } while((write_buf = &chip->write_buf[chip->write_buf_start]), write_buf->valid && write_buf->timestamp <= chip->write_buf_timestamp) { int is_which_note_on_reg = ESFM_reg_write_chan_idx(chip, write_buf->address); if (is_which_note_on_reg >= 0) { if ((chip->native_mode && (write_buf->data & 0x01) == 0) || (!chip->native_mode && (write_buf->data & 0x20) == 0) ) { // this is a note off command; note down that we got note off for this channel note_off_written[is_which_note_on_reg] = true; } else { // this is a note on command; have we gotten a note off for this channel in this cycle? if (note_off_written[is_which_note_on_reg]) { // we have a conflict; let the note off be processed first and defer the // rest of the buffer to the next cycle break; } } } if ((chip->native_mode && write_buf->address == 0x4bd) || (!chip->native_mode && (write_buf->address & 0xff) == 0xbd) ) { // bassdrum register write (rhythm mode note-on/off control) // have we already written to the bassdrum register in this cycle if (bassdrum_written) { // we have a conflict break; } bassdrum_written = true; } write_buf->valid = 0; ESFM_write_reg(chip, write_buf->address, write_buf->data); chip->write_buf_start = (chip->write_buf_start + 1) % ESFM_WRITEBUF_SIZE; } chip->write_buf_timestamp++; } /* your_sha256_hash--------- */ void ESFM_generate(esfm_chip *chip, int32_t *buf) { int channel_idx; chip->output_accm[0] = chip->output_accm[1] = 0; for (channel_idx = 0; channel_idx < 18; channel_idx++) { esfm_channel *channel = &chip->channels[channel_idx]; if (chip->native_mode) { ESFM_process_channel(channel); } else { ESFM_process_channel_emu(channel); } } ESFM_process_feedback(chip); for (channel_idx = 0; channel_idx < 18; channel_idx++) { esfm_channel *channel = &chip->channels[channel_idx]; if (chip->native_mode) { ESFM_slot_generate(&channel->slots[0]); } else { ESFM_slot_generate_emu(&channel->slots[0]); } chip->output_accm[0] += channel->output[0]; chip->output_accm[1] += channel->output[1]; } buf[0] = chip->output_accm[0]; buf[1] = chip->output_accm[1]; ESFM_update_timers(chip); ESFM_update_write_buffer(chip); } /* your_sha256_hash--------- */ int16_t ESFM_get_channel_output_native(esfm_chip *chip, int channel_idx) { int16_t result; int32_t temp_mix = 0; int i; if (channel_idx < 0 || channel_idx >= 18) { return 0; } for (i = 0; i < 4; i++) { esfm_slot *slot = &chip->channels[channel_idx].slots[i]; if (slot->output_level) { int13 output_value = slot->in.output >> (7 - slot->output_level); temp_mix += output_value & slot->out_enable[0]; temp_mix += output_value & slot->out_enable[1]; } } if (temp_mix > 32767) { temp_mix = 32767; } else if (temp_mix < -32768) { temp_mix = -32768; } result = temp_mix; return result; } /* your_sha256_hash--------- */ void ESFM_generate_stream(esfm_chip *chip, int16_t *sndptr, uint32_t num_samples) { uint32_t i; int32_t buf[2] = { 0 }; for (i = 0; i < num_samples; i++) { ESFM_generate(chip, buf); sndptr[0] = ESFM_clip_sample(buf[0]); sndptr[1] = ESFM_clip_sample(buf[1]); sndptr += 2; } } ```
/content/code_sandbox/src/sound/esfmu/esfm.c
c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
64,457
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef WAVEFORMCALCULATOR_h #define WAVEFORMCALCULATOR_h #include <map> #include "array.h" #include "sidcxx11.h" #include "siddefs-fp.h" namespace reSIDfp { /** * Combined waveform model parameters. */ typedef struct { float threshold; float pulsestrength; float distance1; float distance2; } CombinedWaveformConfig; /** * Combined waveform calculator for WaveformGenerator. * By combining waveforms, the bits of each waveform are effectively short * circuited. A zero bit in one waveform will result in a zero output bit * (thus the infamous claim that the waveforms are AND'ed). * However, a zero bit in one waveform may also affect the neighboring bits * in the output. * * Example: * * 1 1 * Bit # 1 0 9 8 7 6 5 4 3 2 1 0 * ----------------------- * Sawtooth 0 0 0 1 1 1 1 1 1 0 0 0 * * Triangle 0 0 1 1 1 1 1 1 0 0 0 0 * * AND 0 0 0 1 1 1 1 1 0 0 0 0 * * Output 0 0 0 0 1 1 1 0 0 0 0 0 * * * Re-vectorized die photographs reveal the mechanism behind this behavior. * Each waveform selector bit acts as a switch, which directly connects * internal outputs into the waveform DAC inputs as follows: * * - Noise outputs the shift register bits to DAC inputs as described above. * Each output is also used as input to the next bit when the shift register * is shifted. Lower four bits are grounded. * - Pulse connects a single line to all DAC inputs. The line is connected to * either 5V (pulse on) or 0V (pulse off) at bit 11, and ends at bit 0. * - Triangle connects the upper 11 bits of the (MSB EOR'ed) accumulator to the * DAC inputs, so that DAC bit 0 = 0, DAC bit n = accumulator bit n - 1. * - Sawtooth connects the upper 12 bits of the accumulator to the DAC inputs, * so that DAC bit n = accumulator bit n. Sawtooth blocks out the MSB from * the EOR used to generate the triangle waveform. * * We can thus draw the following conclusions: * * - The shift register may be written to by combined waveforms. * - The pulse waveform interconnects all bits in combined waveforms via the * pulse line. * - The combination of triangle and sawtooth interconnects neighboring bits * of the sawtooth waveform. * * Also in the 6581 the MSB of the oscillator, used as input for the * triangle xor logic and the pulse adder's last bit, is connected directly * to the waveform selector, while in the 8580 it is latched at sid_clk2 * before being forwarded to the selector. Thus in the 6581 if the sawtooth MSB * is pulled down it might affect the oscillator's adder * driving the top bit low. * */ class WaveformCalculator { private: typedef std::map<const CombinedWaveformConfig*, matrix_t> cw_cache_t; private: matrix_t wftable; cw_cache_t PULLDOWN_CACHE; private: WaveformCalculator(); public: /** * Get the singleton instance. */ static WaveformCalculator* getInstance(); /** * Get the waveform table for use by WaveformGenerator. * * @return Waveform table */ matrix_t* getWaveTable() { return &wftable; } /** * Build pulldown table for use by WaveformGenerator. * * @param model Chip model to use * @return Pulldown table */ matrix_t* buildPulldownTable(ChipModel model); }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/WaveformCalculator.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,054
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Spline.h" #include <cassert> #include <limits> namespace reSIDfp { Spline::Spline(const std::vector<Point> &input) : params(input.size()), c(&params[0]) { assert(input.size() > 2); const size_t coeffLength = input.size() - 1; std::vector<double> dxs(coeffLength); std::vector<double> ms(coeffLength); // Get consecutive differences and slopes for (size_t i = 0; i < coeffLength; i++) { assert(input[i].x < input[i + 1].x); const double dx = input[i + 1].x - input[i].x; const double dy = input[i + 1].y - input[i].y; dxs[i] = dx; ms[i] = dy/dx; } // Get degree-1 coefficients params[0].c = ms[0]; for (size_t i = 1; i < coeffLength; i++) { const double m = ms[i - 1]; const double mNext = ms[i]; if (m * mNext <= 0) { params[i].c = 0.0; } else { const double dx = dxs[i - 1]; const double dxNext = dxs[i]; const double common = dx + dxNext; params[i].c = 3.0 * common / ((common + dxNext) / m + (common + dx) / mNext); } } params[coeffLength].c = ms[coeffLength - 1]; // Get degree-2 and degree-3 coefficients for (size_t i = 0; i < coeffLength; i++) { params[i].x1 = input[i].x; params[i].x2 = input[i + 1].x; params[i].d = input[i].y; const double c1 = params[i].c; const double m = ms[i]; const double invDx = 1.0 / dxs[i]; const double common = c1 + params[i + 1].c - m - m; params[i].b = (m - c1 - common) * invDx; params[i].a = common * invDx * invDx; } // Fix the upper range, because we interpolate outside original bounds if necessary. params[coeffLength - 1].x2 = std::numeric_limits<double>::max(); } Spline::Point Spline::evaluate(double x) const { if ((x < c->x1) || (x > c->x2)) { for (size_t i = 0; i < params.size(); i++) { if (x <= params[i].x2) { c = &params[i]; break; } } } // Interpolate const double diff = x - c->x1; Point out; // y = a*x^3 + b*x^2 + c*x + d out.x = ((c->a * diff + c->b) * diff + c->c) * diff + c->d; // dy = 3*a*x^2 + 2*b*x + c out.y = (3.0 * c->a * diff + 2.0 * c->b) * diff + c->c; return out; } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/Spline.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
901
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILTERMODELCONFIG_H #define FILTERMODELCONFIG_H #include <algorithm> #include <cassert> #include "Spline.h" #include "sidcxx11.h" namespace reSIDfp { class FilterModelConfig { protected: const double voice_voltage_range; const double voice_DC_voltage; /// Capacitor value. const double C; /// Transistor parameters. //@{ const double Vdd; const double Vth; ///< Threshold voltage const double Ut; ///< Thermal voltage: Ut = kT/q = 8.61734315e-5*T ~ 26mV const double uCox; ///< Transconductance coefficient: u*Cox const double Vddt; ///< Vdd - Vth //@} // Derived stuff const double vmin, vmax; const double denorm, norm; /// Fixed point scaling for 16 bit op-amp output. const double N16; /// Current factor coefficient for op-amp integrators. const double currFactorCoeff; /// Lookup tables for gain and summer op-amps in output stage / filter. //@{ unsigned short* mixer[8]; //-V730_NOINIT this is initialized in the derived class constructor unsigned short* summer[5]; //-V730_NOINIT this is initialized in the derived class constructor unsigned short* gain_vol[16]; //-V730_NOINIT this is initialized in the derived class constructor unsigned short* gain_res[16]; //-V730_NOINIT this is initialized in the derived class constructor //@} /// Reverse op-amp transfer function. unsigned short opamp_rev[1 << 16]; //-V730_NOINIT this is initialized in the derived class constructor private: FilterModelConfig (const FilterModelConfig&) DELETE; FilterModelConfig& operator= (const FilterModelConfig&) DELETE; protected: /** * @param vvr voice voltage range * @param vdv voice DC voltage * @param c capacitor value * @param vdd Vdd * @param vth threshold voltage * @param ucox u*Cox * @param ominv opamp min voltage * @param omaxv opamp max voltage */ FilterModelConfig( double vvr, double vdv, double c, double vdd, double vth, double ucox, const Spline::Point *opamp_voltage, int opamp_size ); ~FilterModelConfig() { for (int i = 0; i < 8; i++) { delete [] mixer[i]; } for (int i = 0; i < 5; i++) { delete [] summer[i]; } for (int i = 0; i < 16; i++) { delete [] gain_vol[i]; delete [] gain_res[i]; } } public: unsigned short** getGainVol() { return gain_vol; } unsigned short** getGainRes() { return gain_res; } unsigned short** getSummer() { return summer; } unsigned short** getMixer() { return mixer; } /** * The digital range of one voice is 20 bits; create a scaling term * for multiplication which fits in 11 bits. */ int getVoiceScaleS11() const { return static_cast<int>((norm * ((1 << 11) - 1)) * voice_voltage_range); } /** * The "zero" output level of the voices. */ int getNormalizedVoiceDC() const { return static_cast<int>(N16 * (voice_DC_voltage - vmin)); } inline unsigned short getOpampRev(int i) const { return opamp_rev[i]; } inline double getVddt() const { return Vddt; } inline double getVth() const { return Vth; } // helper functions inline unsigned short getNormalizedValue(double value) const { const double tmp = N16 * (value - vmin); assert(tmp > -0.5 && tmp < 65535.5); return static_cast<unsigned short>(tmp + 0.5); } inline unsigned short getNormalizedCurrentFactor(double wl) const { const double tmp = (1 << 13) * currFactorCoeff * wl; assert(tmp > -0.5 && tmp < 65535.5); return static_cast<unsigned short>(tmp + 0.5); } inline unsigned short getNVmin() const { const double tmp = N16 * vmin; assert(tmp > -0.5 && tmp < 65535.5); return static_cast<unsigned short>(tmp + 0.5); } }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/FilterModelConfig.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,176
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "FilterModelConfig6581.h" #include <cmath> #include "Integrator6581.h" #include "OpAmp.h" namespace reSIDfp { #ifndef HAVE_CXX11 /** * Compute log(1+x) without losing precision for small values of x * * @note when compiling with -ffastm-math the compiler will * optimize the expression away leaving a plain log(1. + x) */ inline double log1p(double x) { return log(1. + x) - (((1. + x) - 1.) - x) / (1. + x); } #endif const unsigned int OPAMP_SIZE = 33; /** * This is the SID 6581 op-amp voltage transfer function, measured on * CAP1B/CAP1A on a chip marked MOS 6581R4AR 0687 14. * All measured chips have op-amps with output voltages (and thus input * voltages) within the range of 0.81V - 10.31V. */ const Spline::Point opamp_voltage[OPAMP_SIZE] = { { 0.81, 10.31 }, // Approximate start of actual range { 2.40, 10.31 }, { 2.60, 10.30 }, { 2.70, 10.29 }, { 2.80, 10.26 }, { 2.90, 10.17 }, { 3.00, 10.04 }, { 3.10, 9.83 }, { 3.20, 9.58 }, { 3.30, 9.32 }, { 3.50, 8.69 }, { 3.70, 8.00 }, { 4.00, 6.89 }, { 4.40, 5.21 }, { 4.54, 4.54 }, // Working point (vi = vo) { 4.60, 4.19 }, { 4.80, 3.00 }, { 4.90, 2.30 }, // Change of curvature { 4.95, 2.03 }, { 5.00, 1.88 }, { 5.05, 1.77 }, { 5.10, 1.69 }, { 5.20, 1.58 }, { 5.40, 1.44 }, { 5.60, 1.33 }, { 5.80, 1.26 }, { 6.00, 1.21 }, { 6.40, 1.12 }, { 7.00, 1.02 }, { 7.50, 0.97 }, { 8.50, 0.89 }, { 10.00, 0.81 }, { 10.31, 0.81 }, // Approximate end of actual range }; std::unique_ptr<FilterModelConfig6581> FilterModelConfig6581::instance(nullptr); FilterModelConfig6581* FilterModelConfig6581::getInstance() { if (!instance.get()) { instance.reset(new FilterModelConfig6581()); } return instance.get(); } FilterModelConfig6581::FilterModelConfig6581() : FilterModelConfig( 1.5, // voice voltage range 5.075, // voice DC voltage 470e-12, // capacitor value 12.18, // Vdd 1.31, // Vth 20e-6, // uCox opamp_voltage, OPAMP_SIZE ), WL_vcr(9.0 / 1.0), WL_snake(1.0 / 115.0), dac_zero(6.65), dac_scale(2.63), dac(DAC_BITS) { dac.kinkedDac(MOS6581); // Create lookup tables for gains / summers. #ifndef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // #pragma omp parallel sections { // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // The filter summer operates at n ~ 1, and has 5 fundamentally different // input configurations (2 - 6 input "resistors"). // // Note that all "on" transistors are modeled as one. This is not // entirely accurate, since the input for each transistor is different, // and transistors are not linear components. However modeling all // transistors separately would be extremely costly. for (int i = 0; i < 5; i++) { const int idiv = 2 + i; // 2 - 6 input "resistors". const int size = idiv << 16; const double n = idiv; opampModel.reset(); summer[i] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16 / idiv; /* vmin .. vmax */ summer[i][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // The audio mixer operates at n ~ 8/6, and has 8 fundamentally different // input configurations (0 - 7 input "resistors"). // // All "on", transistors are modeled as one - see comments above for // the filter summer. for (int i = 0; i < 8; i++) { const int idiv = (i == 0) ? 1 : i; const int size = (i == 0) ? 1 : i << 16; const double n = i * 8.0 / 6.0; opampModel.reset(); mixer[i] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16 / idiv; /* vmin .. vmax */ mixer[i][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // 4 bit "resistor" ladders in the audio output gain // necessitate 16 gain tables. // From die photographs of the volume "resistor" ladders // it follows that gain ~ vol/12 (assuming ideal // op-amps and ideal "resistors"). for (int n8 = 0; n8 < 16; n8++) { const int size = 1 << 16; const double n = n8 / 12.0; opampModel.reset(); gain_vol[n8] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16; /* vmin .. vmax */ gain_vol[n8][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { #ifdef _OPENMP OpAmp opampModel( std::vector<Spline::Point>( std::begin(opamp_voltage), std::end(opamp_voltage)), Vddt, vmin, vmax); #endif // 4 bit "resistor" ladders in the bandpass resonance gain // necessitate 16 gain tables. // From die photographs of the bandpass "resistor" ladders // it follows that 1/Q ~ ~res/8 (assuming ideal // op-amps and ideal "resistors"). for (int n8 = 0; n8 < 16; n8++) { const int size = 1 << 16; const double n = (~n8 & 0xf) / 8.0; opampModel.reset(); gain_res[n8] = new unsigned short[size]; for (int vi = 0; vi < size; vi++) { const double vin = vmin + vi / N16; /* vmin .. vmax */ gain_res[n8][vi] = getNormalizedValue(opampModel.solve(n, vin)); } } } // #pragma omp section { const double nVddt = N16 * (Vddt - vmin); for (unsigned int i = 0; i < (1 << 16); i++) { // The table index is right-shifted 16 times in order to fit in // 16 bits; the argument to sqrt is thus multiplied by (1 << 16). const double tmp = nVddt - sqrt(static_cast<double>(i << 16)); assert(tmp > -0.5 && tmp < 65535.5); vcr_nVg[i] = static_cast<unsigned short>(tmp + 0.5); } } // #pragma omp section { // EKV model: // // Ids = Is * (if - ir) // Is = (2 * u*Cox * Ut^2)/k * W/L // if = ln^2(1 + e^((k*(Vg - Vt) - Vs)/(2*Ut)) // ir = ln^2(1 + e^((k*(Vg - Vt) - Vd)/(2*Ut)) // moderate inversion characteristic current const double Is = (2. * uCox * Ut * Ut) * WL_vcr; // Normalized current factor for 1 cycle at 1MHz. const double N15 = norm * ((1 << 15) - 1); const double n_Is = N15 * 1.0e-6 / C * Is; // kVgt_Vx = k*(Vg - Vt) - Vx // I.e. if k != 1.0, Vg must be scaled accordingly. for (int kVgt_Vx = 0; kVgt_Vx < (1 << 16); kVgt_Vx++) { const double log_term = log1p(exp((kVgt_Vx / N16) / (2. * Ut))); // Scaled by m*2^15 const double tmp = n_Is * log_term * log_term; assert(tmp > -0.5 && tmp < 65535.5); vcr_n_Ids_term[kVgt_Vx] = static_cast<unsigned short>(tmp + 0.5); } } } } unsigned short* FilterModelConfig6581::getDAC(double adjustment) const { const double dac_zero = getDacZero(adjustment); unsigned short* f0_dac = new unsigned short[1 << DAC_BITS]; for (unsigned int i = 0; i < (1 << DAC_BITS); i++) { const double fcd = dac.getOutput(i); f0_dac[i] = getNormalizedValue(dac_zero + fcd * dac_scale / (1 << DAC_BITS)); } return f0_dac; } std::unique_ptr<Integrator6581> FilterModelConfig6581::buildIntegrator() { return MAKE_UNIQUE(Integrator6581, this, WL_snake); } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/FilterModelConfig6581.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,908
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ENVELOPEGENERATOR_H #define ENVELOPEGENERATOR_H #include "siddefs-fp.h" namespace reSIDfp { /** * A 15 bit [LFSR] is used to implement the envelope rates, in effect dividing * the clock to the envelope counter by the currently selected rate period. * * In addition, another 5 bit counter is used to implement the exponential envelope decay, * in effect further dividing the clock to the envelope counter. * The period of this counter is set to 1, 2, 4, 8, 16, 30 at the envelope counter * values 255, 93, 54, 26, 14, 6, respectively. * * [LFSR]: path_to_url */ class EnvelopeGenerator { private: /** * The envelope state machine's distinct states. In addition to this, * envelope has a hold mode, which freezes envelope counter to zero. */ enum State { ATTACK, DECAY_SUSTAIN, RELEASE }; private: /// XOR shift register for ADSR prescaling. unsigned int lfsr; /// Comparison value (period) of the rate counter before next event. unsigned int rate; /** * During release mode, the SID approximates envelope decay via piecewise * linear decay rate. */ unsigned int exponential_counter; /** * Comparison value (period) of the exponential decay counter before next * decrement. */ unsigned int exponential_counter_period; unsigned int new_exponential_counter_period; unsigned int state_pipeline; /// unsigned int envelope_pipeline; unsigned int exponential_pipeline; /// Current envelope state State state; State next_state; /// Whether counter is enabled. Only switching to ATTACK can release envelope. bool counter_enabled; /// Gate bit bool gate; /// bool resetLfsr; /// The current digital value of envelope output. unsigned char envelope_counter; /// Attack register unsigned char attack; /// Decay register unsigned char decay; /// Sustain register unsigned char sustain; /// Release register unsigned char release; /// The ENV3 value, sampled at the first phase of the clock unsigned char env3; private: static const unsigned int adsrtable[16]; private: void set_exponential_counter(); void state_change(); public: /** * SID clocking. */ void clock(); /** * Get the Envelope Generator digital output. */ unsigned int output() const { return envelope_counter; } /** * Constructor. */ EnvelopeGenerator() : lfsr(0x7fff), rate(0), exponential_counter(0), exponential_counter_period(1), new_exponential_counter_period(0), state_pipeline(0), envelope_pipeline(0), exponential_pipeline(0), state(RELEASE), next_state(RELEASE), counter_enabled(true), gate(false), resetLfsr(false), envelope_counter(0xaa), attack(0), decay(0), sustain(0), release(0), env3(0) {} /** * SID reset. */ void reset(); /** * Write control register. * * @param control * control register value */ void writeCONTROL_REG(unsigned char control); /** * Write Attack/Decay register. * * @param attack_decay * attack/decay value */ void writeATTACK_DECAY(unsigned char attack_decay); /** * Write Sustain/Release register. * * @param sustain_release * sustain/release value */ void writeSUSTAIN_RELEASE(unsigned char sustain_release); /** * Return the envelope current value. * * @return envelope counter value */ unsigned char readENV() const { return env3; } }; } // namespace reSIDfp #if RESID_INLINING || defined(ENVELOPEGENERATOR_CPP) namespace reSIDfp { RESID_INLINE void EnvelopeGenerator::clock() { env3 = envelope_counter; if (unlikely(new_exponential_counter_period > 0)) { exponential_counter_period = new_exponential_counter_period; new_exponential_counter_period = 0; } if (unlikely(state_pipeline)) { state_change(); } if (unlikely(envelope_pipeline != 0) && (--envelope_pipeline == 0)) { if (likely(counter_enabled)) { if (state == ATTACK) { if (++envelope_counter==0xff) { next_state = DECAY_SUSTAIN; state_pipeline = 3; } } else if ((state == DECAY_SUSTAIN) || (state == RELEASE)) { if (--envelope_counter==0x00) { counter_enabled = false; } } set_exponential_counter(); } } else if (unlikely(exponential_pipeline != 0) && (--exponential_pipeline == 0)) { exponential_counter = 0; if (((state == DECAY_SUSTAIN) && (envelope_counter != sustain)) || (state == RELEASE)) { // The envelope counter can flip from 0x00 to 0xff by changing state to // attack, then to release. The envelope counter will then continue // counting down in the release state. // This has been verified by sampling ENV3. envelope_pipeline = 1; } } else if (unlikely(resetLfsr)) { lfsr = 0x7fff; resetLfsr = false; if (state == ATTACK) { // The first envelope step in the attack state also resets the exponential // counter. This has been verified by sampling ENV3. exponential_counter = 0; // NOTE this is actually delayed one cycle, not modeled // The envelope counter can flip from 0xff to 0x00 by changing state to // release, then to attack. The envelope counter is then frozen at // zero; to unlock this situation the state must be changed to release, // then to attack. This has been verified by sampling ENV3. envelope_pipeline = 2; } else { if (counter_enabled && (++exponential_counter == exponential_counter_period)) exponential_pipeline = exponential_counter_period != 1 ? 2 : 1; } } // ADSR delay bug. // If the rate counter comparison value is set below the current value of the // rate counter, the counter will continue counting up until it wraps around // to zero at 2^15 = 0x8000, and then count rate_period - 1 before the // envelope can constly be stepped. // This has been verified by sampling ENV3. // check to see if LFSR matches table value if (likely(lfsr != rate)) { // it wasn't a match, clock the LFSR once // by performing XOR on last 2 bits const unsigned int feedback = ((lfsr << 14) ^ (lfsr << 13)) & 0x4000; lfsr = (lfsr >> 1) | feedback; } else { resetLfsr = true; } } /** * This is what happens on chip during state switching, * based on die reverse engineering and transistor level * emulation. * * Attack * * 0 - Gate on * 1 - Counting direction changes * During this cycle the decay rate is "accidentally" activated * 2 - Counter is being inverted * Now the attack rate is correctly activated * Counter is enabled * 3 - Counter will be counting upward from now on * * Decay * * 0 - Counter == $ff * 1 - Counting direction changes * The attack state is still active * 2 - Counter is being inverted * During this cycle the decay state is activated * 3 - Counter will be counting downward from now on * * Release * * 0 - Gate off * 1 - During this cycle the release state is activated if coming from sustain/decay * *2 - Counter is being inverted, the release state is activated * *3 - Counter will be counting downward from now on * * (* only if coming directly from Attack state) * * Freeze * * 0 - Counter == $00 * 1 - Nothing * 2 - Counter is disabled */ RESID_INLINE void EnvelopeGenerator::state_change() { state_pipeline--; switch (next_state) { case ATTACK: if (state_pipeline == 1) { // The decay rate is "accidentally" enabled during first cycle of attack phase rate = adsrtable[decay]; } else if (state_pipeline == 0) { state = ATTACK; // The attack rate is correctly enabled during second cycle of attack phase rate = adsrtable[attack]; counter_enabled = true; } break; case DECAY_SUSTAIN: if (state_pipeline == 0) { state = DECAY_SUSTAIN; rate = adsrtable[decay]; } break; case RELEASE: if (((state == ATTACK) && (state_pipeline == 0)) || ((state == DECAY_SUSTAIN) && (state_pipeline == 1))) { state = RELEASE; rate = adsrtable[release]; } break; } } RESID_INLINE void EnvelopeGenerator::set_exponential_counter() { // Check for change of exponential counter period. // // For a detailed description see: // path_to_url switch (envelope_counter) { case 0xff: case 0x00: new_exponential_counter_period = 1; break; case 0x5d: new_exponential_counter_period = 2; break; case 0x36: new_exponential_counter_period = 4; break; case 0x1a: new_exponential_counter_period = 8; break; case 0x0e: new_exponential_counter_period = 16; break; case 0x06: new_exponential_counter_period = 30; break; } } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/EnvelopeGenerator.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,437
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Filter.h" namespace reSIDfp { void Filter::enable(bool enable) { enabled = enable; if (enabled) { writeRES_FILT(filt); } else { filt1 = filt2 = filt3 = filtE = false; } } void Filter::reset() { writeFC_LO(0); writeFC_HI(0); writeMODE_VOL(0); writeRES_FILT(0); } void Filter::writeFC_LO(unsigned char fc_lo) { fc = (fc & 0x7f8) | (fc_lo & 0x007); updatedCenterFrequency(); } void Filter::writeFC_HI(unsigned char fc_hi) { fc = (fc_hi << 3 & 0x7f8) | (fc & 0x007); updatedCenterFrequency(); } void Filter::writeRES_FILT(unsigned char res_filt) { filt = res_filt; updateResonance((res_filt >> 4) & 0x0f); if (enabled) { filt1 = (filt & 0x01) != 0; filt2 = (filt & 0x02) != 0; filt3 = (filt & 0x04) != 0; filtE = (filt & 0x08) != 0; } updatedMixing(); } void Filter::writeMODE_VOL(unsigned char mode_vol) { vol = mode_vol & 0x0f; lp = (mode_vol & 0x10) != 0; bp = (mode_vol & 0x20) != 0; hp = (mode_vol & 0x40) != 0; voice3off = (mode_vol & 0x80) != 0; updatedMixing(); } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/Filter.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
534
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef EXTERNALFILTER_H #define EXTERNALFILTER_H #include "siddefs-fp.h" namespace reSIDfp { /** * The audio output stage in a Commodore 64 consists of two STC networks, a * low-pass RC filter with 3 dB frequency 16kHz followed by a DC-blocker which * acts as a high-pass filter with a cutoff dependent on the attached audio * equipment impedance. Here we suppose an impedance of 10kOhm resulting * in a 3 dB attenuation at 1.6Hz. * To operate properly the 6581 audio output needs a pull-down resistor *(1KOhm recommended, not needed on 8580) * * ~~~ * 9/12V * -----+ * audio| 10k | * +---o----R---o--------o-----(K) +----- * out | | | | | |audio * -----+ R 1k C 1000 | | 10 uF | * | | pF +-C----o-----C-----+ 10k * 470 | | * GND GND pF R 1K | amp * * * | +----- * * GND * ~~~ * * The STC networks are connected with a [BJT] based [common collector] * used as a voltage follower (featuring a 2SC1815 NPN transistor). * * The C64c board additionally includes a [bootstrap] condenser to increase * the input impedance of the common collector. * * [BJT]: path_to_url * [common collector]: path_to_url * [bootstrap]: path_to_url */ class ExternalFilter { private: /// Lowpass filter voltage int Vlp; /// Highpass filter voltage int Vhp; int w0lp_1_s7; int w0hp_1_s17; public: /** * SID clocking. * * @param input */ int clock(unsigned short input); /** * Constructor. */ ExternalFilter(); /** * Setup of the external filter sampling parameters. * * @param frequency the main system clock frequency */ void setClockFrequency(double frequency); /** * SID reset. */ void reset(); }; } // namespace reSIDfp #if RESID_INLINING || defined(EXTERNALFILTER_CPP) namespace reSIDfp { RESID_INLINE int ExternalFilter::clock(unsigned short input) { const int Vi = (static_cast<unsigned int>(input)<<11) - (1 << (11+15)); const int dVlp = (w0lp_1_s7 * (Vi - Vlp) >> 7); const int dVhp = (w0hp_1_s17 * (Vlp - Vhp) >> 17); Vlp += dVlp; Vhp += dVhp; return (Vlp - Vhp) >> 11; } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/ExternalFilter.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
815
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SIDFP_H #define SIDFP_H #include <memory> #include "siddefs-fp.h" #include "sidcxx11.h" namespace reSIDfp { class Filter; class Filter6581; class Filter8580; class ExternalFilter; class Potentiometer; class Voice; class Resampler; /** * SID error exception. */ class SIDError { private: const char* message; public: SIDError(const char* msg) : message(msg) {} const char* getMessage() const { return message; } }; /** * MOS6581/MOS8580 emulation. */ class SID { private: /// Currently active filter Filter* filter; /// Filter used, if model is set to 6581 std::unique_ptr<Filter6581> const filter6581; /// Filter used, if model is set to 8580 std::unique_ptr<Filter8580> const filter8580; /** * External filter that provides high-pass and low-pass filtering * to adjust sound tone slightly. */ std::unique_ptr<ExternalFilter> const externalFilter; /// Resampler used by audio generation code. std::unique_ptr<Resampler> resampler; /// Paddle X register support std::unique_ptr<Potentiometer> const potX; /// Paddle Y register support std::unique_ptr<Potentiometer> const potY; /// SID voices std::unique_ptr<Voice> voice[3]; /// Time to live for the last written value int busValueTtl; /// Current chip model's bus value TTL int modelTTL; /// Time until #voiceSync must be run. unsigned int nextVoiceSync; /// Currently active chip model. ChipModel model; /// Last written value unsigned char busValue; /// Flags for muted channels bool muted[3]; /** * Emulated nonlinearity of the envelope DAC. * * @See Dac */ float envDAC[256]; /** * Emulated nonlinearity of the oscillator DAC. * * @See Dac */ float oscDAC[4096]; private: /** * Age the bus value and zero it if it's TTL has expired. * * @param n the number of cycles */ void ageBusValue(unsigned int n); /** * Get output sample. * * @return the output sample */ int output() const; /** * Calculate the numebr of cycles according to current parameters * that it takes to reach sync. * * @param sync whether to do the actual voice synchronization */ void voiceSync(bool sync); public: SID(); ~SID(); /** * Set chip model. * * @param model chip model to use * @throw SIDError */ void setChipModel(ChipModel model); /** * Get currently emulated chip model. */ ChipModel getChipModel() const { return model; } /** * SID reset. */ void reset(); /** * 16-bit input (EXT IN). Write 16-bit sample to audio input. NB! The caller * is responsible for keeping the value within 16 bits. Note that to mix in * an external audio signal, the signal should be resampled to 1MHz first to * avoid sampling noise. * * @param value input level to set */ void input(int value); /** * Read registers. * * Reading a write only register returns the last char written to any SID register. * The individual bits in this value start to fade down towards zero after a few cycles. * All bits reach zero within approximately $2000 - $4000 cycles. * It has been claimed that this fading happens in an orderly fashion, * however sampling of write only registers reveals that this is not the case. * NOTE: This is not correctly modeled. * The actual use of write only registers has largely been made * in the belief that all SID registers are readable. * To support this belief the read would have to be done immediately * after a write to the same register (remember that an intermediate write * to another register would yield that value instead). * With this in mind we return the last value written to any SID register * for $2000 cycles without modeling the bit fading. * * @param offset SID register to read * @return value read from chip */ unsigned char read(int offset); /** * Write registers. * * @param offset chip register to write * @param value value to write */ void write(int offset, unsigned char value); /** * SID voice muting. * * @param channel channel to modify * @param enable is muted? */ void mute(int channel, bool enable) { muted[channel] = enable; } /** * Setting of SID sampling parameters. * * Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64. * The default end of passband frequency is pass_freq = 0.9*sample_freq/2 * for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample frequencies. * * For resampling, the ratio between the clock frequency and the sample frequency * is limited as follows: 125*clock_freq/sample_freq < 16384 * E.g. provided a clock frequency of ~ 1MHz, the sample frequency can not be set * lower than ~ 8kHz. A lower sample frequency would make the resampling code * overfill its 16k sample ring buffer. * * The end of passband frequency is also limited: pass_freq <= 0.9*sample_freq/2 * * E.g. for a 44.1kHz sampling rate the end of passband frequency * is limited to slightly below 20kHz. * This constraint ensures that the FIR table is not overfilled. * * @param clockFrequency System clock frequency at Hz * @param method sampling method to use * @param samplingFrequency Desired output sampling rate * @param highestAccurateFrequency * @throw SIDError */ void setSamplingParameters(double clockFrequency, SamplingMethod method, double samplingFrequency, double highestAccurateFrequency); /** * Clock SID forward using chosen output sampling algorithm. * * @param cycles c64 clocks to clock * @param buf audio output buffer * @return number of samples produced */ int clock(unsigned int cycles, short* buf); /** * Clock SID forward with no audio production. * * _Warning_: * You can't mix this method of clocking with the audio-producing * clock() because components that don't affect OSC3/ENV3 are not * emulated. * * @param cycles c64 clocks to clock. */ void clockSilent(unsigned int cycles); /** * Set filter curve parameter for 6581 model. * * @see Filter6581::setFilterCurve(double) */ void setFilter6581Curve(double filterCurve); /** * Set filter curve parameter for 8580 model. * * @see Filter8580::setFilterCurve(double) */ void setFilter8580Curve(double filterCurve); /** * Enable filter emulation. * * @param enable false to turn off filter emulation */ void enableFilter(bool enable); }; } // namespace reSIDfp #if RESID_INLINING || defined(SID_CPP) #include <algorithm> #include "Filter.h" #include "ExternalFilter.h" #include "Voice.h" #include "resample/Resampler.h" namespace reSIDfp { RESID_INLINE void SID::ageBusValue(unsigned int n) { if (likely(busValueTtl != 0)) { busValueTtl -= n; if (unlikely(busValueTtl <= 0)) { busValue = 0; busValueTtl = 0; } } } RESID_INLINE int SID::output() const { const int v1 = voice[0]->output(voice[2]->wave()); const int v2 = voice[1]->output(voice[0]->wave()); const int v3 = voice[2]->output(voice[1]->wave()); return externalFilter->clock(filter->clock(v1, v2, v3)); } RESID_INLINE int SID::clock(unsigned int cycles, short* buf) { ageBusValue(cycles); int s = 0; while (cycles != 0) { unsigned int delta_t = std::min(nextVoiceSync, cycles); if (likely(delta_t > 0)) { for (unsigned int i = 0; i < delta_t; i++) { // clock waveform generators voice[0]->wave()->clock(); voice[1]->wave()->clock(); voice[2]->wave()->clock(); // clock envelope generators voice[0]->envelope()->clock(); voice[1]->envelope()->clock(); voice[2]->envelope()->clock(); if (unlikely(resampler->input(output()))) { buf[s++] = resampler->getOutput(); } } cycles -= delta_t; nextVoiceSync -= delta_t; } if (unlikely(nextVoiceSync == 0)) { voiceSync(true); } } return s; } } // namespace reSIDfp #endif #endif ```
/content/code_sandbox/src/sound/resid-fp/sid.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,252
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILTERMODELCONFIG8580_H #define FILTERMODELCONFIG8580_H #include "FilterModelConfig.h" #include <memory> #include "sidcxx11.h" namespace reSIDfp { class Integrator8580; /** * Calculate parameters for 8580 filter emulation. */ class FilterModelConfig8580 final : public FilterModelConfig { private: static std::unique_ptr<FilterModelConfig8580> instance; // This allows access to the private constructor #ifdef HAVE_CXX11 friend std::unique_ptr<FilterModelConfig8580>::deleter_type; #else friend class std::auto_ptr<FilterModelConfig8580>; #endif private: FilterModelConfig8580(); ~FilterModelConfig8580() DEFAULT; public: static FilterModelConfig8580* getInstance(); /** * Construct an integrator solver. * * @return the integrator */ std::unique_ptr<Integrator8580> buildIntegrator(); }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/FilterModelConfig8580.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
347
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define SID_CPP #include "sid.h" #include <limits> #include "array.h" #include "Dac.h" #include "Filter6581.h" #include "Filter8580.h" #include "Potentiometer.h" #include "WaveformCalculator.h" #include "resample/TwoPassSincResampler.h" #include "resample/ZeroOrderResampler.h" namespace reSIDfp { const unsigned int ENV_DAC_BITS = 8; const unsigned int OSC_DAC_BITS = 12; /** * The waveform D/A converter introduces a DC offset in the signal * to the envelope multiplying D/A converter. The "zero" level of * the waveform D/A converter can be found as follows: * * Measure the "zero" voltage of voice 3 on the SID audio output * pin, routing only voice 3 to the mixer ($d417 = $0b, $d418 = * $0f, all other registers zeroed). * * Then set the sustain level for voice 3 to maximum and search for * the waveform output value yielding the same voltage as found * above. This is done by trying out different waveform output * values until the correct value is found, e.g. with the following * program: * * lda #$08 * sta $d412 * lda #$0b * sta $d417 * lda #$0f * sta $d418 * lda #$f0 * sta $d414 * lda #$21 * sta $d412 * lda #$01 * sta $d40e * * ldx #$00 * lda #$38 ; Tweak this to find the "zero" level *l cmp $d41b * bne l * stx $d40e ; Stop frequency counter - freeze waveform output * brk * * The waveform output range is 0x000 to 0xfff, so the "zero" * level should ideally have been 0x800. In the measured chip, the * waveform output "zero" level was found to be 0x380 (i.e. $d41b * = 0x38) at an audio output voltage of 5.94V. * * With knowledge of the mixer op-amp characteristics, further estimates * of waveform voltages can be obtained by sampling the EXT IN pin. * From EXT IN samples, the corresponding waveform output can be found by * using the model for the mixer. * * Such measurements have been done on a chip marked MOS 6581R4AR * 0687 14, and the following results have been obtained: * * The full range of one voice is approximately 1.5V. * * The "zero" level rides at approximately 5.0V. * * * zero-x did the measuring on the 8580 (path_to_url#c5b3): * When it sits on basic from powerup it's at 4.72 * Run 1.prg and check the output pin level. * Then run 2.prg and adjust it until the output level is the same... * 0x94-0xA8 gives me the same 4.72 1.prg shows. * On another 8580 it's 0x90-0x9C * Third chip 0x94-0xA8 * Fourth chip 0x90-0xA4 * On the 8580 that plays digis the output is 4.66 and 0x93 is the only value to reach that. * To me that seems as regular 8580s have somewhat wide 0-level range, * whereas that digi-compatible 8580 has it very narrow. * On my 6581R4AR has 0x3A as the only value giving the same output level as 1.prg */ //@{ unsigned int constexpr OFFSET_6581 = 0x380; unsigned int constexpr OFFSET_8580 = 0x9c0; //@} /** * Bus value stays alive for some time after each operation. * Values differs between chip models, the timings used here * are taken from VICE [1]. * See also the discussion "How do I reliably detect 6581/8580 sid?" on CSDb [2]. * * Results from real C64 (testprogs/SID/bitfade/delayfrq0.prg): * * (new SID) (250469/8580R5) (250469/8580R5) * delayfrq0 ~7a000 ~108000 * * (old SID) (250407/6581) * delayfrq0 ~01d00 * * [1]: path_to_url * [2]: path_to_url */ //@{ int constexpr BUS_TTL_6581 = 0x01d00; int constexpr BUS_TTL_8580 = 0xa2000; //@} SID::SID() : filter6581(new Filter6581()), filter8580(new Filter8580()), externalFilter(new ExternalFilter()), resampler(nullptr), potX(new Potentiometer()), potY(new Potentiometer()) { voice[0].reset(new Voice()); voice[1].reset(new Voice()); voice[2].reset(new Voice()); muted[0] = muted[1] = muted[2] = false; reset(); setChipModel(MOS8580); } SID::~SID() { // Needed to delete auto_ptr with complete type } void SID::setFilter6581Curve(double filterCurve) { filter6581->setFilterCurve(filterCurve); } void SID::setFilter8580Curve(double filterCurve) { filter8580->setFilterCurve(filterCurve); } void SID::enableFilter(bool enable) { filter6581->enable(enable); filter8580->enable(enable); } void SID::voiceSync(bool sync) { if (sync) { // Synchronize the 3 waveform generators. for (int i = 0; i < 3; i++) { voice[i]->wave()->synchronize(voice[(i + 1) % 3]->wave(), voice[(i + 2) % 3]->wave()); } } // Calculate the time to next voice sync nextVoiceSync = std::numeric_limits<int>::max(); for (int i = 0; i < 3; i++) { WaveformGenerator* const wave = voice[i]->wave(); const unsigned int freq = wave->readFreq(); if (wave->readTest() || freq == 0 || !voice[(i + 1) % 3]->wave()->readSync()) { continue; } const unsigned int accumulator = wave->readAccumulator(); const unsigned int thisVoiceSync = ((0x7fffff - accumulator) & 0xffffff) / freq + 1; if (thisVoiceSync < nextVoiceSync) { nextVoiceSync = thisVoiceSync; } } } void SID::setChipModel(ChipModel model) { switch (model) { case MOS6581: filter = filter6581.get(); modelTTL = BUS_TTL_6581; break; case MOS8580: filter = filter8580.get(); modelTTL = BUS_TTL_8580; break; default: throw SIDError("Unknown chip type"); } this->model = model; // calculate waveform-related tables matrix_t* wavetables = WaveformCalculator::getInstance()->getWaveTable(); matrix_t* pulldowntables = WaveformCalculator::getInstance()->buildPulldownTable(model); // calculate envelope DAC table { Dac dacBuilder(ENV_DAC_BITS); dacBuilder.kinkedDac(model); for (unsigned int i = 0; i < (1 << ENV_DAC_BITS); i++) { envDAC[i] = static_cast<float>(dacBuilder.getOutput(i)); } } // calculate oscillator DAC table const bool is6581 = model == MOS6581; { Dac dacBuilder(OSC_DAC_BITS); dacBuilder.kinkedDac(model); const double offset = dacBuilder.getOutput(is6581 ? OFFSET_6581 : OFFSET_8580); for (unsigned int i = 0; i < (1 << OSC_DAC_BITS); i++) { const double dacValue = dacBuilder.getOutput(i); oscDAC[i] = static_cast<float>(dacValue - offset); } } // set voice tables for (int i = 0; i < 3; i++) { voice[i]->setEnvDAC(envDAC); voice[i]->setWavDAC(oscDAC); voice[i]->wave()->setModel(is6581); voice[i]->wave()->setWaveformModels(wavetables); voice[i]->wave()->setPulldownModels(pulldowntables); } } void SID::reset() { for (int i = 0; i < 3; i++) { voice[i]->reset(); } filter6581->reset(); filter8580->reset(); externalFilter->reset(); if (resampler.get()) { resampler->reset(); } busValue = 0; busValueTtl = 0; voiceSync(false); } void SID::input(int value) { filter6581->input(value); filter8580->input(value); } unsigned char SID::read(int offset) { switch (offset) { case 0x19: // X value of paddle busValue = potX->readPOT(); busValueTtl = modelTTL; break; case 0x1a: // Y value of paddle busValue = potY->readPOT(); busValueTtl = modelTTL; break; case 0x1b: // Voice #3 waveform output busValue = voice[2]->wave()->readOSC(); busValueTtl = modelTTL; break; case 0x1c: // Voice #3 ADSR output busValue = voice[2]->envelope()->readENV(); busValueTtl = modelTTL; break; default: // Reading from a write-only or non-existing register // makes the bus discharge faster. // Emulate this by halving the residual TTL. busValueTtl /= 2; break; } return busValue; } void SID::write(int offset, unsigned char value) { busValue = value; busValueTtl = modelTTL; switch (offset) { case 0x00: // Voice #1 frequency (Low-byte) voice[0]->wave()->writeFREQ_LO(value); break; case 0x01: // Voice #1 frequency (High-byte) voice[0]->wave()->writeFREQ_HI(value); break; case 0x02: // Voice #1 pulse width (Low-byte) voice[0]->wave()->writePW_LO(value); break; case 0x03: // Voice #1 pulse width (bits #8-#15) voice[0]->wave()->writePW_HI(value); break; case 0x04: // Voice #1 control register voice[0]->writeCONTROL_REG(muted[0] ? 0 : value); break; case 0x05: // Voice #1 Attack and Decay length voice[0]->envelope()->writeATTACK_DECAY(value); break; case 0x06: // Voice #1 Sustain volume and Release length voice[0]->envelope()->writeSUSTAIN_RELEASE(value); break; case 0x07: // Voice #2 frequency (Low-byte) voice[1]->wave()->writeFREQ_LO(value); break; case 0x08: // Voice #2 frequency (High-byte) voice[1]->wave()->writeFREQ_HI(value); break; case 0x09: // Voice #2 pulse width (Low-byte) voice[1]->wave()->writePW_LO(value); break; case 0x0a: // Voice #2 pulse width (bits #8-#15) voice[1]->wave()->writePW_HI(value); break; case 0x0b: // Voice #2 control register voice[1]->writeCONTROL_REG(muted[1] ? 0 : value); break; case 0x0c: // Voice #2 Attack and Decay length voice[1]->envelope()->writeATTACK_DECAY(value); break; case 0x0d: // Voice #2 Sustain volume and Release length voice[1]->envelope()->writeSUSTAIN_RELEASE(value); break; case 0x0e: // Voice #3 frequency (Low-byte) voice[2]->wave()->writeFREQ_LO(value); break; case 0x0f: // Voice #3 frequency (High-byte) voice[2]->wave()->writeFREQ_HI(value); break; case 0x10: // Voice #3 pulse width (Low-byte) voice[2]->wave()->writePW_LO(value); break; case 0x11: // Voice #3 pulse width (bits #8-#15) voice[2]->wave()->writePW_HI(value); break; case 0x12: // Voice #3 control register voice[2]->writeCONTROL_REG(muted[2] ? 0 : value); break; case 0x13: // Voice #3 Attack and Decay length voice[2]->envelope()->writeATTACK_DECAY(value); break; case 0x14: // Voice #3 Sustain volume and Release length voice[2]->envelope()->writeSUSTAIN_RELEASE(value); break; case 0x15: // Filter cut off frequency (bits #0-#2) filter6581->writeFC_LO(value); filter8580->writeFC_LO(value); break; case 0x16: // Filter cut off frequency (bits #3-#10) filter6581->writeFC_HI(value); filter8580->writeFC_HI(value); break; case 0x17: // Filter control filter6581->writeRES_FILT(value); filter8580->writeRES_FILT(value); break; case 0x18: // Volume and filter modes filter6581->writeMODE_VOL(value); filter8580->writeMODE_VOL(value); break; default: break; } // Update voicesync just in case. voiceSync(false); } void SID::setSamplingParameters(double clockFrequency, SamplingMethod method, double samplingFrequency, double highestAccurateFrequency) { externalFilter->setClockFrequency(clockFrequency); switch (method) { case DECIMATE: resampler.reset(new ZeroOrderResampler(clockFrequency, samplingFrequency)); break; case RESAMPLE: resampler.reset(TwoPassSincResampler::create(clockFrequency, samplingFrequency, highestAccurateFrequency)); break; default: throw SIDError("Unknown sampling method"); } } void SID::clockSilent(unsigned int cycles) { ageBusValue(cycles); while (cycles != 0) { int delta_t = std::min(nextVoiceSync, cycles); if (delta_t > 0) { for (int i = 0; i < delta_t; i++) { // clock waveform generators (can affect OSC3) voice[0]->wave()->clock(); voice[1]->wave()->clock(); voice[2]->wave()->clock(); voice[0]->wave()->output(voice[2]->wave()); voice[1]->wave()->output(voice[0]->wave()); voice[2]->wave()->output(voice[1]->wave()); // clock ENV3 only voice[2]->envelope()->clock(); } cycles -= delta_t; nextVoiceSync -= delta_t; } if (nextVoiceSync == 0) { voiceSync(true); } } } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/SID.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,700
```objective-c // your_sha256_hash----------- // This file is part of reSID, a MOS6581 SID emulator engine. // // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // your_sha256_hash----------- #ifndef SIDDEFS_FP_H #define SIDDEFS_FP_H // Compilation configuration. #define RESID_BRANCH_HINTS true // Compiler specifics. #define HAVE_BUILTIN_EXPECT true #ifndef M_PI # define M_PI 3.14159265358979323846 #endif // Branch prediction macros, lifted off the Linux kernel. #if RESID_BRANCH_HINTS && HAVE_BUILTIN_EXPECT # define likely(x) __builtin_expect(!!(x), 1) # define unlikely(x) __builtin_expect(!!(x), 0) #else # define likely(x) (x) # define unlikely(x) (x) #endif namespace reSIDfp { typedef enum { MOS6581=1, MOS8580 } ChipModel; typedef enum { DECIMATE=1, RESAMPLE } SamplingMethod; } extern "C" { #ifndef __VERSION_CC__ extern const char* residfp_version_string; #else const char* residfp_version_string = VERSION; #endif } // Inlining on/off. #define RESID_INLINING true #define RESID_INLINE inline #endif // SIDDEFS_FP_H ```
/content/code_sandbox/src/sound/resid-fp/siddefs-fp.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
390
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define INTEGRATOR_CPP #include "Integrator6581.h" // This is needed when compiling with --disable-inline ```
/content/code_sandbox/src/sound/resid-fp/Integrator6581.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
154
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define ENVELOPEGENERATOR_CPP #include "EnvelopeGenerator.h" namespace reSIDfp { /** * Lookup table to convert from attack, decay, or release value to rate * counter period. * * The rate counter is a 15 bit register which is left shifted each cycle. * When the counter reaches a specific comparison value, * the envelope counter is incremented (attack) or decremented * (decay/release) and the rate counter is resetted. * * see [kevtris.org](path_to_url */ const unsigned int EnvelopeGenerator::adsrtable[16] = { 0x007f, 0x3000, 0x1e00, 0x0660, 0x0182, 0x5573, 0x000e, 0x3805, 0x2424, 0x2220, 0x090c, 0x0ecd, 0x010e, 0x23f7, 0x5237, 0x64a8 }; void EnvelopeGenerator::reset() { // counter is not changed on reset envelope_pipeline = 0; state_pipeline = 0; attack = 0; decay = 0; sustain = 0; release = 0; gate = false; resetLfsr = true; exponential_counter = 0; exponential_counter_period = 1; new_exponential_counter_period = 0; state = RELEASE; counter_enabled = true; rate = adsrtable[release]; } void EnvelopeGenerator::writeCONTROL_REG(unsigned char control) { const bool gate_next = (control & 0x01) != 0; if (gate_next != gate) { gate = gate_next; // The rate counter is never reset, thus there will be a delay before the // envelope counter starts counting up (attack) or down (release). if (gate_next) { // Gate bit on: Start attack, decay, sustain. next_state = ATTACK; state_pipeline = 2; if (resetLfsr || (exponential_pipeline == 2)) { envelope_pipeline = (exponential_counter_period == 1) || (exponential_pipeline == 2) ? 2 : 4; } else if (exponential_pipeline == 1) { state_pipeline = 3; } } else { // Gate bit off: Start release. next_state = RELEASE; state_pipeline = envelope_pipeline > 0 ? 3 : 2; } } } void EnvelopeGenerator::writeATTACK_DECAY(unsigned char attack_decay) { attack = (attack_decay >> 4) & 0x0f; decay = attack_decay & 0x0f; if (state == ATTACK) { rate = adsrtable[attack]; } else if (state == DECAY_SUSTAIN) { rate = adsrtable[decay]; } } void EnvelopeGenerator::writeSUSTAIN_RELEASE(unsigned char sustain_release) { // From the sustain levels it follows that both the low and high 4 bits // of the envelope counter are compared to the 4-bit sustain value. // This has been verified by sampling ENV3. // // For a detailed description see: // path_to_url sustain = (sustain_release & 0xf0) | ((sustain_release >> 4) & 0x0f); release = sustain_release & 0x0f; if (state == RELEASE) { rate = adsrtable[release]; } } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/EnvelopeGenerator.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
950
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef FILTER_H #define FILTER_H namespace reSIDfp { /** * SID filter base class */ class Filter { protected: /// Current volume amplifier setting. unsigned short* currentGain; /// Current filter/voice mixer setting. unsigned short* currentMixer; /// Filter input summer setting. unsigned short* currentSummer; /// Filter resonance value. unsigned short* currentResonance; /// Filter highpass state. int Vhp; /// Filter bandpass state. int Vbp; /// Filter lowpass state. int Vlp; /// Filter external input. int ve; /// Filter cutoff frequency. unsigned int fc; /// Routing to filter or outside filter bool filt1, filt2, filt3, filtE; /// Switch voice 3 off. bool voice3off; /// Highpass, bandpass, and lowpass filter modes. bool hp, bp, lp; /// Current volume. unsigned char vol; private: /// Filter enabled. bool enabled; /// Selects which inputs to route through filter. unsigned char filt; protected: /** * Set filter cutoff frequency. */ virtual void updatedCenterFrequency() = 0; /** * Set filter resonance. */ virtual void updateResonance(unsigned char res) = 0; /** * Mixing configuration modified (offsets change) */ virtual void updatedMixing() = 0; public: Filter() : currentGain(nullptr), currentMixer(nullptr), currentSummer(nullptr), currentResonance(nullptr), Vhp(0), Vbp(0), Vlp(0), ve(0), fc(0), filt1(false), filt2(false), filt3(false), filtE(false), voice3off(false), hp(false), bp(false), lp(false), vol(0), enabled(true), filt(0) {} virtual ~Filter() {} /** * SID clocking - 1 cycle * * @param v1 voice 1 in * @param v2 voice 2 in * @param v3 voice 3 in * @return filtered output */ virtual unsigned short clock(int v1, int v2, int v3) = 0; /** * Enable filter. * * @param enable */ void enable(bool enable); /** * SID reset. */ void reset(); /** * Write Frequency Cutoff Low register. * * @param fc_lo Frequency Cutoff Low-Byte */ void writeFC_LO(unsigned char fc_lo); /** * Write Frequency Cutoff High register. * * @param fc_hi Frequency Cutoff High-Byte */ void writeFC_HI(unsigned char fc_hi); /** * Write Resonance/Filter register. * * @param res_filt Resonance/Filter */ void writeRES_FILT(unsigned char res_filt); /** * Write filter Mode/Volume register. * * @param mode_vol Filter Mode/Volume */ void writeMODE_VOL(unsigned char mode_vol); virtual void input(int input) = 0; }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/Filter.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
845
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef POTENTIOMETER_H #define POTENTIOMETER_H namespace reSIDfp { /** * Potentiometer representation. * * This class will probably never be implemented in any real way. * * @author Ken Hndel * @author Dag Lem */ class Potentiometer { public: /** * Read paddle value. Not modeled. * * @return paddle value (always 0xff) */ unsigned char readPOT() const { return 0xff; } }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/Potentiometer.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
248
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "OpAmp.h" #include <cmath> #include "siddefs-fp.h" namespace reSIDfp { const double EPSILON = 1e-8; double OpAmp::solve(double n, double vi) const { // Start off with an estimate of x and a root bracket [ak, bk]. // f is decreasing, so that f(ak) > 0 and f(bk) < 0. double ak = vmin; double bk = vmax; const double a = n + 1.; const double b = Vddt; const double b_vi = (b > vi) ? (b - vi) : 0.; const double c = n * (b_vi * b_vi); for (;;) { const double xk = x; // Calculate f and df. Spline::Point out = opamp->evaluate(x); const double vo = out.x; const double dvo = out.y; const double b_vx = (b > x) ? b - x : 0.; const double b_vo = (b > vo) ? b - vo : 0.; // f = a*(b - vx)^2 - c - (b - vo)^2 const double f = a * (b_vx * b_vx) - c - (b_vo * b_vo); // df = 2*((b - vo)*dvo - a*(b - vx)) const double df = 2. * (b_vo * dvo - a * b_vx); // Newton-Raphson step: xk1 = xk - f(xk)/f'(xk) x -= f / df; if (unlikely(fabs(x - xk) < EPSILON)) { out = opamp->evaluate(x); return out.x; } // Narrow down root bracket. (f < 0. ? bk : ak) = xk; if (unlikely(x <= ak) || unlikely(x >= bk)) { // Bisection step (ala Dekker's method). x = (ak + bk) * 0.5; } } } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/OpAmp.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
613
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ZEROORDER_RESAMPLER_H #define ZEROORDER_RESAMPLER_H #include "Resampler.h" #include "../sidcxx11.h" namespace reSIDfp { /** * Return sample with linear interpolation. * * @author Antti Lankila */ class ZeroOrderResampler final : public Resampler { private: /// Last sample int cachedSample; /// Number of cycles per sample const int cyclesPerSample; int sampleOffset; /// Calculated sample int outputValue; public: ZeroOrderResampler(double clockFrequency, double samplingFrequency) : cachedSample(0), cyclesPerSample(static_cast<int>(clockFrequency / samplingFrequency * 1024.)), sampleOffset(0), outputValue(0) {} bool input(int sample) override { bool ready = false; if (sampleOffset < 1024) { outputValue = cachedSample + (sampleOffset * (sample - cachedSample) >> 10); ready = true; sampleOffset += cyclesPerSample; } sampleOffset -= 1024; cachedSample = sample; return ready; } int output() const override { return outputValue; } void reset() override { sampleOffset = 0; cachedSample = 0; } }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/resample/ZeroOrderResampler.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
422
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef TWOPASSSINCRESAMPLER_H #define TWOPASSSINCRESAMPLER_H #include <cmath> #include <memory> #include "Resampler.h" #include "SincResampler.h" #include "../sidcxx11.h" namespace reSIDfp { /** * Compose a more efficient SINC from chaining two other SINCs. */ class TwoPassSincResampler final : public Resampler { private: std::unique_ptr<SincResampler> const s1; std::unique_ptr<SincResampler> const s2; private: TwoPassSincResampler(double clockFrequency, double samplingFrequency, double highestAccurateFrequency, double intermediateFrequency) : s1(new SincResampler(clockFrequency, intermediateFrequency, highestAccurateFrequency)), s2(new SincResampler(intermediateFrequency, samplingFrequency, highestAccurateFrequency)) {} public: // Named constructor static TwoPassSincResampler* create(double clockFrequency, double samplingFrequency, double highestAccurateFrequency) { // Calculation according to Laurent Ganier. It evaluates to about 120 kHz at typical settings. // Some testing around the chosen value seems to confirm that this does work. double const intermediateFrequency = 2. * highestAccurateFrequency + sqrt(2. * highestAccurateFrequency * clockFrequency * (samplingFrequency - 2. * highestAccurateFrequency) / samplingFrequency); return new TwoPassSincResampler(clockFrequency, samplingFrequency, highestAccurateFrequency, intermediateFrequency); } bool input(int sample) override { return s1->input(sample) && s2->input(s1->output()); } int output() const override { return s2->output(); } void reset() override { s1->reset(); s2->reset(); } }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/resample/TwoPassSincResampler.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
539
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <map> #include <memory> #include <ctime> #include <iostream> #include <iomanip> #include <cmath> #include "../siddefs-fp.h" #include "Resampler.h" #include "TwoPassSincResampler.h" #if __cplusplus < 201103L # define unique_ptr auto_ptr #endif /** * Simple sin waveform in, power output measurement function. * It would be far better to use FFT. */ int main(int, const char*[]) { const double RATE = 985248.4; const int RINGSIZE = 2048; std::unique_ptr<reSIDfp::TwoPassSincResampler> r(reSIDfp::TwoPassSincResampler::create(RATE, 48000.0, 20000.0)); std::map<double, double> results; clock_t start = clock(); for (double freq = 1000.; freq < RATE / 2.; freq *= 1.01) { /* prefill resampler buffer */ int k = 0; double omega = 2 * M_PI * freq / RATE; for (int j = 0; j < RINGSIZE; j ++) { int signal = static_cast<int>(32768.0 * sin(k++ * omega) * sqrt(2)); r->input(signal); } int n = 0; float pwr = 0; /* Now, during measurement stage, put 100 cycles of waveform through filter. */ for (int j = 0; j < 100000; j ++) { int signal = static_cast<int>(32768.0 * sin(k++ * omega) * sqrt(2)); if (r->input(signal)) { float out = r->output(); pwr += out * out; n += 1; } } results.insert(std::make_pair(freq, 10 * log10(pwr / n))); } clock_t end = clock(); for (std::map<double, double>::iterator it = results.begin(); it != results.end(); ++it) { std::cout << std::fixed << std::setprecision(0) << std::setw(6) << (*it).first << " Hz " << (*it).second << " dB" << std::endl; } std::cout << "Filtering time " << (end - start) * 1000. / CLOCKS_PER_SEC << " ms" << std::endl; } ```
/content/code_sandbox/src/sound/resid-fp/resample/test.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
669
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef RESAMPLER_H #define RESAMPLER_H #include <cmath> #include "../sidcxx11.h" #include "../siddefs-fp.h" namespace reSIDfp { /** * Abstraction of a resampling process. Given enough input, produces output. * Constructors take additional arguments that configure these objects. */ class Resampler { protected: inline short softClip(int x) const { constexpr int threshold = 28000; if (likely(x < threshold)) return x; constexpr double t = threshold / 32768.; constexpr double a = 1. - t; constexpr double b = 1. / a; double value = static_cast<double>(x - threshold) / 32768.; value = t + a * tanh(b * value); return static_cast<short>(value * 32768.); } virtual int output() const = 0; Resampler() {} public: virtual ~Resampler() {} /** * Input a sample into resampler. Output "true" when resampler is ready with new sample. * * @param sample input sample * @return true when a sample is ready */ virtual bool input(int sample) = 0; /** * Output a sample from resampler. * * @return resampled sample */ short getOutput() const { return softClip(output()); } virtual void reset() = 0; }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/resample/Resampler.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
453
```objective-c /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SINCRESAMPLER_H #define SINCRESAMPLER_H #include "Resampler.h" #include <string> #include <map> #include "../array.h" #include "../sidcxx11.h" namespace reSIDfp { /** * This is the theoretically correct (and computationally intensive) audio sample generation. * The samples are generated by resampling to the specified sampling frequency. * The work rate is inversely proportional to the percentage of the bandwidth * allocated to the filter transition band. * * This implementation is based on the paper "A Flexible Sampling-Rate Conversion Method", * by J. O. Smith and P. Gosset, or rather on the expanded tutorial on the * [Digital Audio Resampling Home Page](path_to_url~jos/resample/). * * By building shifted FIR tables with samples according to the sampling frequency, * this implementation dramatically reduces the computational effort in the * filter convolutions, without any loss of accuracy. * The filter convolutions are also vectorizable on current hardware. */ class SincResampler final : public Resampler { private: /// Size of the ring buffer, must be a power of 2 static const int RINGSIZE = 2048; private: /// Table of the fir filter coefficients matrix_t* firTable; int sampleIndex; /// Filter resolution int firRES; /// Filter length int firN; const int cyclesPerSample; int sampleOffset; int outputValue; short sample[RINGSIZE * 2]; private: int fir(int subcycle); public: /** * Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64. * The default end of passband frequency is pass_freq = 0.9*sample_freq/2 * for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample frequencies. * * For resampling, the ratio between the clock frequency and the sample frequency * is limited as follows: 125*clock_freq/sample_freq < 16384 * E.g. provided a clock frequency of ~ 1MHz, the sample frequency * can not be set lower than ~ 8kHz. * A lower sample frequency would make the resampling code overfill its 16k sample ring buffer. * * The end of passband frequency is also limited: pass_freq <= 0.9*sample_freq/2 * * E.g. for a 44.1kHz sampling rate the end of passband frequency is limited * to slightly below 20kHz. This constraint ensures that the FIR table is not overfilled. * * @param clockFrequency System clock frequency at Hz * @param samplingFrequency Desired output sampling rate * @param highestAccurateFrequency */ SincResampler(double clockFrequency, double samplingFrequency, double highestAccurateFrequency); bool input(int input) override; int output() const override { return outputValue; } void reset() override; }; } // namespace reSIDfp #endif ```
/content/code_sandbox/src/sound/resid-fp/resample/SincResampler.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
795
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_MEMORY_REGION_H #define MT32EMU_MEMORY_REGION_H #include <cstddef> #include "globals.h" #include "Types.h" #include "Structures.h" namespace MT32Emu { enum MemoryRegionType { MR_PatchTemp, MR_RhythmTemp, MR_TimbreTemp, MR_Patches, MR_Timbres, MR_System, MR_Display, MR_Reset }; class Synth; class MemoryRegion { private: Synth *synth; Bit8u *realMemory; Bit8u *maxTable; public: MemoryRegionType type; Bit32u startAddr, entrySize, entries; MemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable, MemoryRegionType useType, Bit32u useStartAddr, Bit32u useEntrySize, Bit32u useEntries) { synth = useSynth; realMemory = useRealMemory; maxTable = useMaxTable; type = useType; startAddr = useStartAddr; entrySize = useEntrySize; entries = useEntries; } int lastTouched(Bit32u addr, Bit32u len) const { return (offset(addr) + len - 1) / entrySize; } int firstTouchedOffset(Bit32u addr) const { return offset(addr) % entrySize; } int firstTouched(Bit32u addr) const { return offset(addr) / entrySize; } Bit32u regionEnd() const { return startAddr + entrySize * entries; } bool contains(Bit32u addr) const { return addr >= startAddr && addr < regionEnd(); } int offset(Bit32u addr) const { return addr - startAddr; } Bit32u getClampedLen(Bit32u addr, Bit32u len) const { if (addr + len > regionEnd()) return regionEnd() - addr; return len; } Bit32u next(Bit32u addr, Bit32u len) const { if (addr + len > regionEnd()) { return regionEnd() - addr; } return 0; } Bit8u getMaxValue(int off) const { if (maxTable == NULL) return 0xFF; return maxTable[off % entrySize]; } Bit8u *getRealMemory() const { return realMemory; } bool isReadable() const { return getRealMemory() != NULL; } void read(unsigned int entry, unsigned int off, Bit8u *dst, unsigned int len) const; void write(unsigned int entry, unsigned int off, const Bit8u *src, unsigned int len, bool init = false) const; }; // class MemoryRegion class PatchTempMemoryRegion : public MemoryRegion { public: PatchTempMemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable) : MemoryRegion(useSynth, useRealMemory, useMaxTable, MR_PatchTemp, MT32EMU_MEMADDR(0x030000), sizeof(MemParams::PatchTemp), 9) {} }; class RhythmTempMemoryRegion : public MemoryRegion { public: RhythmTempMemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable) : MemoryRegion(useSynth, useRealMemory, useMaxTable, MR_RhythmTemp, MT32EMU_MEMADDR(0x030110), sizeof(MemParams::RhythmTemp), 85) {} }; class TimbreTempMemoryRegion : public MemoryRegion { public: TimbreTempMemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable) : MemoryRegion(useSynth, useRealMemory, useMaxTable, MR_TimbreTemp, MT32EMU_MEMADDR(0x040000), sizeof(TimbreParam), 8) {} }; class PatchesMemoryRegion : public MemoryRegion { public: PatchesMemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable) : MemoryRegion(useSynth, useRealMemory, useMaxTable, MR_Patches, MT32EMU_MEMADDR(0x050000), sizeof(PatchParam), 128) {} }; class TimbresMemoryRegion : public MemoryRegion { public: TimbresMemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable) : MemoryRegion(useSynth, useRealMemory, useMaxTable, MR_Timbres, MT32EMU_MEMADDR(0x080000), sizeof(MemParams::PaddedTimbre), 64 + 64 + 64 + 64) {} }; class SystemMemoryRegion : public MemoryRegion { public: SystemMemoryRegion(Synth *useSynth, Bit8u *useRealMemory, Bit8u *useMaxTable) : MemoryRegion(useSynth, useRealMemory, useMaxTable, MR_System, MT32EMU_MEMADDR(0x100000), sizeof(MemParams::System), 1) {} }; class DisplayMemoryRegion : public MemoryRegion { public: // Note, we set realMemory to NULL despite the real devices buffer inbound strings. However, it is impossible to retrieve them. // This entrySize permits emulation of handling a 20-byte display message sent to an old-gen device at address 0x207F7F. DisplayMemoryRegion(Synth *useSynth) : MemoryRegion(useSynth, NULL, NULL, MR_Display, MT32EMU_MEMADDR(0x200000), 0x4013, 1) {} }; class ResetMemoryRegion : public MemoryRegion { public: ResetMemoryRegion(Synth *useSynth) : MemoryRegion(useSynth, NULL, NULL, MR_Reset, MT32EMU_MEMADDR(0x7F0000), 0x3FFF, 1) {} }; } // namespace MT32Emu #endif // #ifndef MT32EMU_MEMORY_REGION_H ```
/content/code_sandbox/src/sound/munt/MemoryRegion.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,398
```c++ /* * This file is part of libsidplayfp, a SID player engine. * * * This program is free software; you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "SincResampler.h" #include <cassert> #include <cstring> #include <cmath> #include <iostream> #include <sstream> #include "../siddefs-fp.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef HAVE_EMMINTRIN_H # include <emmintrin.h> #elif defined HAVE_MMINTRIN_H # include <mmintrin.h> #elif defined(HAVE_ARM_NEON_H) # include <arm_neon.h> #endif namespace reSIDfp { typedef std::map<std::string, matrix_t> fir_cache_t; /// Cache for the expensive FIR table computation results. fir_cache_t FIR_CACHE; /// Maximum error acceptable in I0 is 1e-6, or ~96 dB. const double I0E = 1e-6; const int BITS = 16; /** * Compute the 0th order modified Bessel function of the first kind. * This function is originally from resample-1.5/filterkit.c by J. O. Smith. * It is used to build the Kaiser window for resampling. * * @param x evaluate I0 at x * @return value of I0 at x. */ double I0(double x) { double sum = 1.; double u = 1.; double n = 1.; const double halfx = x / 2.; do { const double temp = halfx / n; u *= temp * temp; sum += u; n += 1.; } while (u >= I0E * sum); return sum; } /** * Calculate convolution with sample and sinc. * * @param a sample buffer input * @param b sinc buffer * @param bLength length of the sinc buffer * @return convolved result */ int convolve(const short* a, const short* b, int bLength) { #ifdef HAVE_EMMINTRIN_H int out = 0; const uintptr_t offset = (uintptr_t)(a) & 0x0f; // check for aligned accesses if (offset == ((uintptr_t)(b) & 0x0f)) { if (offset) { const int l = (0x10 - offset)/2; for (int i = 0; i < l; i++) { out += *a++ * *b++; } bLength -= offset; } __m128i acc = _mm_setzero_si128(); const int n = bLength / 8; for (int i = 0; i < n; i++) { const __m128i tmp = _mm_madd_epi16(*(__m128i*)a, *(__m128i*)b); acc = _mm_add_epi16(acc, tmp); a += 8; b += 8; } __m128i vsum = _mm_add_epi32(acc, _mm_srli_si128(acc, 8)); vsum = _mm_add_epi32(vsum, _mm_srli_si128(vsum, 4)); out += _mm_cvtsi128_si32(vsum); bLength &= 7; } #elif defined HAVE_MMINTRIN_H __m64 acc = _mm_setzero_si64(); const int n = bLength / 4; for (int i = 0; i < n; i++) { const __m64 tmp = _mm_madd_pi16(*(__m64*)a, *(__m64*)b); acc = _mm_add_pi16(acc, tmp); a += 4; b += 4; } int out = _mm_cvtsi64_si32(acc) + _mm_cvtsi64_si32(_mm_srli_si64(acc, 32)); _mm_empty(); bLength &= 3; #elif defined(HAVE_ARM_NEON_H) #if (defined(__arm64__) && defined(__APPLE__)) || defined(__aarch64__) int32x4_t acc1Low = vdupq_n_s32(0); int32x4_t acc1High = vdupq_n_s32(0); int32x4_t acc2Low = vdupq_n_s32(0); int32x4_t acc2High = vdupq_n_s32(0); const int n = bLength / 16; for (int i = 0; i < n; i++) { int16x8_t v11 = vld1q_s16(a); int16x8_t v12 = vld1q_s16(a + 8); int16x8_t v21 = vld1q_s16(b); int16x8_t v22 = vld1q_s16(b + 8); acc1Low = vmlal_s16(acc1Low, vget_low_s16(v11), vget_low_s16(v21)); acc1High = vmlal_high_s16(acc1High, v11, v21); acc2Low = vmlal_s16(acc2Low, vget_low_s16(v12), vget_low_s16(v22)); acc2High = vmlal_high_s16(acc2High, v12, v22); a += 16; b += 16; } bLength &= 15; if (bLength >= 8) { int16x8_t v1 = vld1q_s16(a); int16x8_t v2 = vld1q_s16(b); acc1Low = vmlal_s16(acc1Low, vget_low_s16(v1), vget_low_s16(v2)); acc1High = vmlal_high_s16(acc1High, v1, v2); a += 8; b += 8; } bLength &= 7; if (bLength >= 4) { int16x4_t v1 = vld1_s16(a); int16x4_t v2 = vld1_s16(b); acc1Low = vmlal_s16(acc1Low, v1, v2); a += 4; b += 4; } int32x4_t accSumsNeon = vaddq_s32(acc1Low, acc1High); accSumsNeon = vaddq_s32(accSumsNeon, acc2Low); accSumsNeon = vaddq_s32(accSumsNeon, acc2High); int out = vaddvq_s32(accSumsNeon); bLength &= 3; #else int32x4_t acc = vdupq_n_s32(0); const int n = bLength / 4; for (int i = 0; i < n; i++) { const int16x4_t h_vec = vld1_s16(a); const int16x4_t x_vec = vld1_s16(b); acc = vmlal_s16(acc, h_vec, x_vec); a += 4; b += 4; } int out = vgetq_lane_s32(acc, 0) + vgetq_lane_s32(acc, 1) + vgetq_lane_s32(acc, 2) + vgetq_lane_s32(acc, 3); bLength &= 3; #endif #else int out = 0; #endif for (int i = 0; i < bLength; i++) { out += *a++ * *b++; } return (out + (1 << 14)) >> 15; } int SincResampler::fir(int subcycle) { // Find the first of the nearest fir tables close to the phase int firTableFirst = (subcycle * firRES >> 10); const int firTableOffset = (subcycle * firRES) & 0x3ff; // Find firN most recent samples, plus one extra in case the FIR wraps. int sampleStart = sampleIndex - firN + RINGSIZE - 1; const int v1 = convolve(sample + sampleStart, (*firTable)[firTableFirst], firN); // Use next FIR table, wrap around to first FIR table using // previous sample. if (unlikely(++firTableFirst == firRES)) { firTableFirst = 0; ++sampleStart; } const int v2 = convolve(sample + sampleStart, (*firTable)[firTableFirst], firN); // Linear interpolation between the sinc tables yields good // approximation for the exact value. return v1 + (firTableOffset * (v2 - v1) >> 10); } SincResampler::SincResampler(double clockFrequency, double samplingFrequency, double highestAccurateFrequency) : sampleIndex(0), cyclesPerSample(static_cast<int>(clockFrequency / samplingFrequency * 1024.)), sampleOffset(0), outputValue(0) { // 16 bits -> -96dB stopband attenuation. const double A = -20. * log10(1.0 / (1 << BITS)); // A fraction of the bandwidth is allocated to the transition band, which we double // because we design the filter to transition halfway at nyquist. const double dw = (1. - 2.*highestAccurateFrequency / samplingFrequency) * M_PI * 2.; // For calculation of beta and N see the reference for the kaiserord // function in the MATLAB Signal Processing Toolbox: // path_to_url const double beta = 0.1102 * (A - 8.7); const double I0beta = I0(beta); const double cyclesPerSampleD = clockFrequency / samplingFrequency; { // The filter order will maximally be 124 with the current constraints. // N >= (96.33 - 7.95)/(2 * pi * 2.285 * (maxfreq - passbandfreq) >= 123 // The filter order is equal to the number of zero crossings, i.e. // it should be an even number (sinc is symmetric with respect to x = 0). int N = static_cast<int>((A - 7.95) / (2.285 * dw) + 0.5); N += N & 1; // The filter length is equal to the filter order + 1. // The filter length must be an odd number (sinc is symmetric with respect to // x = 0). firN = static_cast<int>(N * cyclesPerSampleD) + 1; firN |= 1; // Check whether the sample ring buffer would overflow. assert(firN < RINGSIZE); // Error is bounded by err < 1.234 / L^2, so L = sqrt(1.234 / (2^-16)) = sqrt(1.234 * 2^16). firRES = static_cast<int>(ceil(sqrt(1.234 * (1 << BITS)) / cyclesPerSampleD)); // firN*firRES represent the total resolution of the sinc sampling. JOS // recommends a length of 2^BITS, but we don't quite use that good a filter. // The filter test program indicates that the filter performs well, though. } // Create the map key std::ostringstream o; o << firN << "," << firRES << "," << cyclesPerSampleD; const std::string firKey = o.str(); fir_cache_t::iterator lb = FIR_CACHE.lower_bound(firKey); // The FIR computation is expensive and we set sampling parameters often, but // from a very small set of choices. Thus, caching is used to speed initialization. if (lb != FIR_CACHE.end() && !(FIR_CACHE.key_comp()(firKey, lb->first))) { firTable = &(lb->second); } else { // Allocate memory for FIR tables. matrix_t tempTable(firRES, firN); #ifdef HAVE_CXX11 firTable = &(FIR_CACHE.emplace_hint(lb, fir_cache_t::value_type(firKey, tempTable))->second); #else firTable = &(FIR_CACHE.insert(lb, fir_cache_t::value_type(firKey, tempTable))->second); #endif // The cutoff frequency is midway through the transition band, in effect the same as nyquist. const double wc = M_PI; // Calculate the sinc tables. const double scale = 32768.0 * wc / cyclesPerSampleD / M_PI; // we're not interested in the fractional part // so use int division before converting to double const int tmp = firN / 2; const double firN_2 = static_cast<double>(tmp); for (int i = 0; i < firRES; i++) { const double jPhase = (double) i / firRES + firN_2; for (int j = 0; j < firN; j++) { const double x = j - jPhase; const double xt = x / firN_2; const double kaiserXt = fabs(xt) < 1. ? I0(beta * sqrt(1. - xt * xt)) / I0beta : 0.; const double wt = wc * x / cyclesPerSampleD; const double sincWt = fabs(wt) >= 1e-8 ? sin(wt) / wt : 1.; (*firTable)[i][j] = static_cast<short>(scale * sincWt * kaiserXt); } } } } bool SincResampler::input(int input) { bool ready = false; /* * Clip the input as it may overflow the 16 bit range. * * Approximate measured input ranges: * 6581: [-24262,+25080] (Kawasaki_Synthesizer_Demo) * 8580: [-21514,+35232] (64_Forever, Drum_Fool) */ sample[sampleIndex] = sample[sampleIndex + RINGSIZE] = softClip(input); sampleIndex = (sampleIndex + 1) & (RINGSIZE - 1); if (sampleOffset < 1024) { outputValue = fir(sampleOffset); ready = true; sampleOffset += cyclesPerSample; } sampleOffset -= 1024; return ready; } void SincResampler::reset() { memset(sample, 0, sizeof(sample)); sampleOffset = 0; } } // namespace reSIDfp ```
/content/code_sandbox/src/sound/resid-fp/resample/SincResampler.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,378
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_LA32_FLOAT_WAVE_GENERATOR_H #define MT32EMU_LA32_FLOAT_WAVE_GENERATOR_H #include "globals.h" #include "internals.h" #include "Types.h" #include "LA32WaveGenerator.h" namespace MT32Emu { /** * LA32WaveGenerator is aimed to represent the exact model of LA32 wave generator. * The output square wave is created by adding high / low linear segments in-between * the rising and falling cosine segments. Basically, it's very similar to the phase distortion synthesis. * Behaviour of a true resonance filter is emulated by adding decaying sine wave. * The beginning and the ending of the resonant sine is multiplied by a cosine window. * To synthesise sawtooth waves, the resulting square wave is multiplied by synchronous cosine wave. */ class LA32FloatWaveGenerator { //*************************************************************************** // The local copy of partial parameters below //*************************************************************************** bool active; // True means the resulting square wave is to be multiplied by the synchronous cosine bool sawtoothWaveform; // Values in range [1..31] // Value 1 correspong to the minimum resonance Bit8u resonance; // Processed value in range [0..255] // Values in range [0..128] have no effect and the resulting wave remains symmetrical // Value 255 corresponds to the maximum possible asymmetric of the resulting wave Bit8u pulseWidth; // Logarithmic PCM sample start address const Bit16s *pcmWaveAddress; // Logarithmic PCM sample length Bit32u pcmWaveLength; // true for looped logarithmic PCM samples bool pcmWaveLooped; // false for slave PCM partials in the structures with the ring modulation bool pcmWaveInterpolated; //*************************************************************************** // Internal variables below //*************************************************************************** float wavePos; float lastFreq; float pcmPosition; float getPCMSample(unsigned int position); public: // Initialise the WG engine for generation of synth partial samples and set up the invariant parameters void initSynth(const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance); // Initialise the WG engine for generation of PCM partial samples and set up the invariant parameters void initPCM(const Bit16s * const pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped, const bool pcmWaveInterpolated); // Update parameters with respect to TVP, TVA and TVF, and generate next sample float generateNextSample(const Bit32u amp, const Bit16u pitch, const Bit32u cutoff); // Deactivate the WG engine void deactivate(); // Return active state of the WG engine bool isActive() const; // Return true if the WG engine generates PCM wave samples bool isPCMWave() const; }; // class LA32FloatWaveGenerator class LA32FloatPartialPair : public LA32PartialPair { LA32FloatWaveGenerator master; LA32FloatWaveGenerator slave; bool ringModulated; bool mixed; float masterOutputSample; float slaveOutputSample; public: // ringModulated should be set to false for the structures with mixing or stereo output // ringModulated should be set to true for the structures with ring modulation // mixed is used for the structures with ring modulation and indicates whether the master partial output is mixed to the ring modulator output void init(const bool ringModulated, const bool mixed); // Initialise the WG engine for generation of synth partial samples and set up the invariant parameters void initSynth(const PairType master, const bool sawtoothWaveform, const Bit8u pulseWidth, const Bit8u resonance); // Initialise the WG engine for generation of PCM partial samples and set up the invariant parameters void initPCM(const PairType master, const Bit16s * const pcmWaveAddress, const Bit32u pcmWaveLength, const bool pcmWaveLooped); // Update parameters with respect to TVP, TVA and TVF, and generate next sample void generateNextSample(const PairType master, const Bit32u amp, const Bit16u pitch, const Bit32u cutoff); // Perform mixing / ring modulation and return the result float nextOutSample(); // Deactivate the WG engine void deactivate(const PairType master); // Return active state of the WG engine bool isActive(const PairType master) const; }; // class LA32FloatPartialPair } // namespace MT32Emu #endif // #ifndef MT32EMU_LA32_FLOAT_WAVE_GENERATOR_H ```
/content/code_sandbox/src/sound/munt/LA32FloatWaveGenerator.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,060
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_CONFIG_H #define MT32EMU_CONFIG_H #define MT32EMU_VERSION "2.7.0" #define MT32EMU_VERSION_MAJOR 2 #define MT32EMU_VERSION_MINOR 7 #define MT32EMU_VERSION_PATCH 0 /* Library Exports Configuration * * This reflects the API types actually provided by the library build. * 0: The full-featured C++ API is only available in this build. The client application may ONLY use MT32EMU_API_TYPE 0. * 1: The C-compatible API is only available. The library is built as a shared object, only C functions are exported, * and thus the client application may NOT use MT32EMU_API_TYPE 0. * 2: The C-compatible API is only available. The library is built as a shared object, only the factory function * is exported, and thus the client application may ONLY use MT32EMU_API_TYPE 2. * 3: All the available API types are provided by the library build. */ #define MT32EMU_EXPORTS_TYPE 3 #define MT32EMU_API_TYPE 0 #define MT32EMU_WITH_LIBSOXR_RESAMPLER 0 #define MT32EMU_WITH_LIBSAMPLERATE_RESAMPLER 0 #define MT32EMU_WITH_INTERNAL_RESAMPLER 1 #endif ```
/content/code_sandbox/src/sound/munt/config.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
372
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_MIDI_STREAM_PARSER_H #define MT32EMU_MIDI_STREAM_PARSER_H #include "globals.h" #include "Types.h" namespace MT32Emu { class Synth; // Interface for a user-supplied class to receive parsed well-formed MIDI messages. class MT32EMU_EXPORT MidiReceiver { public: // Invoked when a complete short MIDI message is parsed in the input MIDI stream. virtual void handleShortMessage(const Bit32u message) = 0; // Invoked when a complete well-formed System Exclusive MIDI message is parsed in the input MIDI stream. virtual void handleSysex(const Bit8u stream[], const Bit32u length) = 0; // Invoked when a System Realtime MIDI message is parsed in the input MIDI stream. virtual void handleSystemRealtimeMessage(const Bit8u realtime) = 0; protected: ~MidiReceiver() {} }; // Interface for a user-supplied class to receive notifications of input MIDI stream parse errors. class MT32EMU_EXPORT MidiReporter { public: // Invoked when an error occurs during processing the input MIDI stream. virtual void printDebug(const char *debugMessage) = 0; protected: ~MidiReporter() {} }; // Provides a context for parsing a stream of MIDI events coming from a single source. // There can be multiple MIDI sources feeding MIDI events to a single Synth object. // NOTE: Calls from multiple threads which feed a single Synth object with data must be explicitly synchronised, // although, no synchronisation is required with the rendering thread. class MT32EMU_EXPORT MidiStreamParserImpl { public: // The first two arguments provide for implementations of essential interfaces needed. // The third argument specifies streamBuffer initial capacity. The buffer capacity should be large enough to fit the longest SysEx expected. // If a longer SysEx occurs, streamBuffer is reallocated to the maximum size of MAX_STREAM_BUFFER_SIZE (32768 bytes). // Default capacity is SYSEX_BUFFER_SIZE (1000 bytes) which is enough to fit SysEx messages in common use. MidiStreamParserImpl(MidiReceiver &, MidiReporter &, Bit32u initialStreamBufferCapacity = SYSEX_BUFFER_SIZE); virtual ~MidiStreamParserImpl(); // Parses a block of raw MIDI bytes. All the parsed MIDI messages are sent in sequence to the user-supplied methods for further processing. // SysEx messages are allowed to be fragmented across several calls to this method. Running status is also handled for short messages. // NOTE: the total length of a SysEx message being fragmented shall not exceed MAX_STREAM_BUFFER_SIZE (32768 bytes). void parseStream(const Bit8u *stream, Bit32u length); // Convenience method which accepts a Bit32u-encoded short MIDI message and sends it to the user-supplied method for further processing. // The short MIDI message may contain no status byte, the running status is used in this case. void processShortMessage(const Bit32u message); private: Bit8u runningStatus; Bit8u *streamBuffer; Bit32u streamBufferCapacity; Bit32u streamBufferSize; MidiReceiver &midiReceiver; MidiReporter &midiReporter; // Binary compatibility helper. void *reserved; bool checkStreamBufferCapacity(const bool preserveContent); bool processStatusByte(Bit8u &status); Bit32u parseShortMessageStatus(const Bit8u stream[]); Bit32u parseShortMessageDataBytes(const Bit8u stream[], Bit32u length); Bit32u parseSysex(const Bit8u stream[], const Bit32u length); Bit32u parseSysexFragment(const Bit8u stream[], const Bit32u length); }; // class MidiStreamParserImpl // An abstract class that provides a context for parsing a stream of MIDI events coming from a single source. class MT32EMU_EXPORT MidiStreamParser : public MidiStreamParserImpl, protected MidiReceiver, protected MidiReporter { public: // The argument specifies streamBuffer initial capacity. The buffer capacity should be large enough to fit the longest SysEx expected. // If a longer SysEx occurs, streamBuffer is reallocated to the maximum size of MAX_STREAM_BUFFER_SIZE (32768 bytes). // Default capacity is SYSEX_BUFFER_SIZE (1000 bytes) which is enough to fit SysEx messages in common use. explicit MidiStreamParser(Bit32u initialStreamBufferCapacity = SYSEX_BUFFER_SIZE); }; class MT32EMU_EXPORT DefaultMidiStreamParser : public MidiStreamParser { public: explicit DefaultMidiStreamParser(Synth &synth, Bit32u initialStreamBufferCapacity = SYSEX_BUFFER_SIZE); void setTimestamp(const Bit32u useTimestamp); void resetTimestamp(); protected: void handleShortMessage(const Bit32u message); void handleSysex(const Bit8u *stream, const Bit32u length); void handleSystemRealtimeMessage(const Bit8u realtime); void printDebug(const char *debugMessage); private: Synth &synth; bool timestampSet; Bit32u timestamp; }; } // namespace MT32Emu #endif // MT32EMU_MIDI_STREAM_PARSER_H ```
/content/code_sandbox/src/sound/munt/MidiStreamParser.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,153
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #include <cstddef> #include "internals.h" #include "Partial.h" #include "Part.h" #include "PartialManager.h" #include "Poly.h" #include "Synth.h" #include "Tables.h" #include "TVA.h" #include "TVF.h" #include "TVP.h" namespace MT32Emu { static const Bit8u PAN_NUMERATOR_MASTER[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7}; static const Bit8u PAN_NUMERATOR_SLAVE[] = {0, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7}; // We assume the pan is applied using the same 13-bit multiplier circuit that is also used for ring modulation // because of the observed sample overflow, so the panSetting values are likely mapped in a similar way via a LUT. // FIXME: Sample analysis suggests that the use of panSetting is linear, but there are some quirks that still need to be resolved. static Bit32s getPanFactor(Bit32s panSetting) { static const Bit32u PAN_FACTORS_COUNT = 15; static Bit32s PAN_FACTORS[PAN_FACTORS_COUNT]; static bool firstRun = true; if (firstRun) { firstRun = false; for (Bit32u i = 1; i < PAN_FACTORS_COUNT; i++) { PAN_FACTORS[i] = Bit32s(0.5 + i * 8192.0 / double(PAN_FACTORS_COUNT - 1)); } } return PAN_FACTORS[panSetting]; } Partial::Partial(Synth *useSynth, int usePartialIndex) : synth(useSynth), partialIndex(usePartialIndex), sampleNum(0), floatMode(useSynth->getSelectedRendererType() == RendererType_FLOAT) { // Initialisation of tva, tvp and tvf uses 'this' pointer // and thus should not be in the initializer list to avoid a compiler warning tva = new TVA(this, &ampRamp); tvp = new TVP(this); tvf = new TVF(this, &cutoffModifierRamp); ownerPart = -1; poly = NULL; pair = NULL; switch (synth->getSelectedRendererType()) { case RendererType_BIT16S: la32Pair = new LA32IntPartialPair; break; case RendererType_FLOAT: la32Pair = new LA32FloatPartialPair; break; default: la32Pair = NULL; } } Partial::~Partial() { delete la32Pair; delete tva; delete tvp; delete tvf; } // Only used for debugging purposes int Partial::debugGetPartialNum() const { return partialIndex; } // Only used for debugging purposes Bit32u Partial::debugGetSampleNum() const { return sampleNum; } int Partial::getOwnerPart() const { return ownerPart; } bool Partial::isActive() const { return ownerPart > -1; } const Poly *Partial::getPoly() const { return poly; } void Partial::activate(int part) { // This just marks the partial as being assigned to a part ownerPart = part; } void Partial::deactivate() { if (!isActive()) { return; } ownerPart = -1; synth->partialManager->partialDeactivated(partialIndex); if (poly != NULL) { poly->partialDeactivated(this); } #if MT32EMU_MONITOR_PARTIALS > 2 synth->printDebug("[+%lu] [Partial %d] Deactivated", sampleNum, partialIndex); synth->printPartialUsage(sampleNum); #endif if (isRingModulatingSlave()) { pair->la32Pair->deactivate(LA32PartialPair::SLAVE); } else { la32Pair->deactivate(LA32PartialPair::MASTER); if (hasRingModulatingSlave()) { pair->deactivate(); pair = NULL; } } if (pair != NULL) { pair->pair = NULL; } } void Partial::startPartial(const Part *part, Poly *usePoly, const PatchCache *usePatchCache, const MemParams::RhythmTemp *rhythmTemp, Partial *pairPartial) { if (usePoly == NULL || usePatchCache == NULL) { synth->printDebug("[Partial %d] *** Error: Starting partial for owner %d, usePoly=%s, usePatchCache=%s", partialIndex, ownerPart, usePoly == NULL ? "*** NULL ***" : "OK", usePatchCache == NULL ? "*** NULL ***" : "OK"); return; } patchCache = usePatchCache; poly = usePoly; mixType = patchCache->structureMix; structurePosition = patchCache->structurePosition; Bit8u panSetting = rhythmTemp != NULL ? rhythmTemp->panpot : part->getPatchTemp()->panpot; if (mixType == 3) { if (structurePosition == 0) { panSetting = PAN_NUMERATOR_MASTER[panSetting] << 1; } else { panSetting = PAN_NUMERATOR_SLAVE[panSetting] << 1; } // Do a normal mix independent of any pair partial. mixType = 0; pairPartial = NULL; } else if (!synth->isNicePanningEnabled()) { // Mok wanted an option for smoother panning, and we love Mok. // CONFIRMED by Mok: exactly bytes like this (right shifted) are sent to the LA32. panSetting &= 0x0E; } leftPanValue = synth->reversedStereoEnabled ? 14 - panSetting : panSetting; rightPanValue = 14 - leftPanValue; if (!floatMode) { leftPanValue = getPanFactor(leftPanValue); rightPanValue = getPanFactor(rightPanValue); } // SEMI-CONFIRMED: From sample analysis: // Found that timbres with 3 or 4 partials (i.e. one using two partial pairs) are mixed in two different ways. // Either partial pairs are added or subtracted, it depends on how the partial pairs are allocated. // It seems that partials are grouped into quarters and if the partial pairs are allocated in different quarters the subtraction happens. // Though, this matters little for the majority of timbres, it becomes crucial for timbres which contain several partials that sound very close. // In this case that timbre can sound totally different depending on the way it is mixed up. // Most easily this effect can be displayed with the help of a special timbre consisting of several identical square wave partials (3 or 4). // Say, it is 3-partial timbre. Just play any two notes simultaneously and the polys very probably are mixed differently. // Moreover, the partial allocator retains the last partial assignment it did and all the subsequent notes will sound the same as the last released one. // The situation is better with 4-partial timbres since then a whole quarter is assigned for each poly. However, if a 3-partial timbre broke the normal // whole-quarter assignment or after some partials got aborted, even 4-partial timbres can be found sounding differently. // This behaviour is also confirmed with two more special timbres: one with identical sawtooth partials, and one with PCM wave 02. // For my personal taste, this behaviour rather enriches the sounding and should be emulated. if (!synth->isNicePartialMixingEnabled() && (partialIndex & 4)) { leftPanValue = -leftPanValue; rightPanValue = -rightPanValue; } if (patchCache->PCMPartial) { pcmNum = patchCache->pcm; if (synth->controlROMMap->pcmCount > 128) { // CM-32L, etc. support two "banks" of PCMs, selectable by waveform type parameter. if (patchCache->waveform > 1) { pcmNum += 128; } } pcmWave = &synth->pcmWaves[pcmNum]; } else { pcmWave = NULL; } // CONFIRMED: pulseWidthVal calculation is based on information from Mok pulseWidthVal = (poly->getVelocity() - 64) * (patchCache->srcPartial.wg.pulseWidthVeloSensitivity - 7) + Tables::getInstance().pulseWidth100To255[patchCache->srcPartial.wg.pulseWidth]; if (pulseWidthVal < 0) { pulseWidthVal = 0; } else if (pulseWidthVal > 255) { pulseWidthVal = 255; } pair = pairPartial; alreadyOutputed = false; tva->reset(part, patchCache->partialParam, rhythmTemp); tvp->reset(part, patchCache->partialParam); tvf->reset(patchCache->partialParam, tvp->getBasePitch()); LA32PartialPair::PairType pairType; LA32PartialPair *useLA32Pair; if (isRingModulatingSlave()) { pairType = LA32PartialPair::SLAVE; useLA32Pair = pair->la32Pair; } else { pairType = LA32PartialPair::MASTER; la32Pair->init(hasRingModulatingSlave(), mixType == 1); useLA32Pair = la32Pair; } if (isPCM()) { useLA32Pair->initPCM(pairType, &synth->pcmROMData[pcmWave->addr], pcmWave->len, pcmWave->loop); } else { useLA32Pair->initSynth(pairType, (patchCache->waveform & 1) != 0, pulseWidthVal, patchCache->srcPartial.tvf.resonance + 1); } if (!hasRingModulatingSlave()) { la32Pair->deactivate(LA32PartialPair::SLAVE); } } Bit32u Partial::getAmpValue() { // SEMI-CONFIRMED: From sample analysis: // (1) Tested with a single partial playing PCM wave 77 with pitchCoarse 36 and no keyfollow, velocity follow, etc. // This gives results within +/- 2 at the output (before any DAC bitshifting) // when sustaining at levels 156 - 255 with no modifiers. // (2) Tested with a special square wave partial (internal capture ID tva5) at TVA envelope levels 155-255. // This gives deltas between -1 and 0 compared to the real output. Note that this special partial only produces // positive amps, so negative still needs to be explored, as well as lower levels. // // Also still partially unconfirmed is the behaviour when ramping between levels, as well as the timing. // TODO: The tests above were performed using the float model, to be refined Bit32u ampRampVal = 67117056 - ampRamp.nextValue(); if (ampRamp.checkInterrupt()) { tva->handleInterrupt(); } return ampRampVal; } Bit32u Partial::getCutoffValue() { if (isPCM()) { return 0; } Bit32u cutoffModifierRampVal = cutoffModifierRamp.nextValue(); if (cutoffModifierRamp.checkInterrupt()) { tvf->handleInterrupt(); } return (tvf->getBaseCutoff() << 18) + cutoffModifierRampVal; } bool Partial::hasRingModulatingSlave() const { return pair != NULL && structurePosition == 0 && (mixType == 1 || mixType == 2); } bool Partial::isRingModulatingSlave() const { return pair != NULL && structurePosition == 1 && (mixType == 1 || mixType == 2); } bool Partial::isRingModulatingNoMix() const { return pair != NULL && ((structurePosition == 1 && mixType == 1) || mixType == 2); } bool Partial::isPCM() const { return pcmWave != NULL; } const ControlROMPCMStruct *Partial::getControlROMPCMStruct() const { if (pcmWave != NULL) { return pcmWave->controlROMPCMStruct; } return NULL; } Synth *Partial::getSynth() const { return synth; } TVA *Partial::getTVA() const { return tva; } void Partial::backupCache(const PatchCache &cache) { if (patchCache == &cache) { cachebackup = cache; patchCache = &cachebackup; } } bool Partial::canProduceOutput() { if (!isActive() || alreadyOutputed || isRingModulatingSlave()) { return false; } if (poly == NULL) { synth->printDebug("[Partial %d] *** ERROR: poly is NULL at Partial::produceOutput()!", partialIndex); return false; } return true; } template <class LA32PairImpl> bool Partial::generateNextSample(LA32PairImpl *la32PairImpl) { if (!tva->isPlaying() || !la32PairImpl->isActive(LA32PartialPair::MASTER)) { deactivate(); return false; } la32PairImpl->generateNextSample(LA32PartialPair::MASTER, getAmpValue(), tvp->nextPitch(), getCutoffValue()); if (hasRingModulatingSlave()) { la32PairImpl->generateNextSample(LA32PartialPair::SLAVE, pair->getAmpValue(), pair->tvp->nextPitch(), pair->getCutoffValue()); if (!pair->tva->isPlaying() || !la32PairImpl->isActive(LA32PartialPair::SLAVE)) { pair->deactivate(); if (mixType == 2) { deactivate(); return false; } } } return true; } void Partial::produceAndMixSample(IntSample *&leftBuf, IntSample *&rightBuf, LA32IntPartialPair *la32IntPair) { IntSampleEx sample = la32IntPair->nextOutSample(); // FIXME: LA32 may produce distorted sound in case if the absolute value of maximal amplitude of the input exceeds 8191 // when the panning value is non-zero. Most probably the distortion occurs in the same way it does with ring modulation, // and it seems to be caused by limited precision of the common multiplication circuit. // From analysis of this overflow, it is obvious that the right channel output is actually found // by subtraction of the left channel output from the input. // Though, it is unknown whether this overflow is exploited somewhere. IntSampleEx leftOut = ((sample * leftPanValue) >> 13) + IntSampleEx(*leftBuf); IntSampleEx rightOut = ((sample * rightPanValue) >> 13) + IntSampleEx(*rightBuf); *(leftBuf++) = Synth::clipSampleEx(leftOut); *(rightBuf++) = Synth::clipSampleEx(rightOut); } void Partial::produceAndMixSample(FloatSample *&leftBuf, FloatSample *&rightBuf, LA32FloatPartialPair *la32FloatPair) { FloatSample sample = la32FloatPair->nextOutSample(); FloatSample leftOut = (sample * leftPanValue) / 14.0f; FloatSample rightOut = (sample * rightPanValue) / 14.0f; *(leftBuf++) += leftOut; *(rightBuf++) += rightOut; } template <class Sample, class LA32PairImpl> bool Partial::doProduceOutput(Sample *leftBuf, Sample *rightBuf, Bit32u length, LA32PairImpl *la32PairImpl) { if (!canProduceOutput()) return false; alreadyOutputed = true; for (sampleNum = 0; sampleNum < length; sampleNum++) { if (!generateNextSample(la32PairImpl)) break; produceAndMixSample(leftBuf, rightBuf, la32PairImpl); } sampleNum = 0; return true; } bool Partial::produceOutput(IntSample *leftBuf, IntSample *rightBuf, Bit32u length) { if (floatMode) { synth->printDebug("Partial: Invalid call to produceOutput()! Renderer = %d\n", synth->getSelectedRendererType()); return false; } return doProduceOutput(leftBuf, rightBuf, length, static_cast<LA32IntPartialPair *>(la32Pair)); } bool Partial::produceOutput(FloatSample *leftBuf, FloatSample *rightBuf, Bit32u length) { if (!floatMode) { synth->printDebug("Partial: Invalid call to produceOutput()! Renderer = %d\n", synth->getSelectedRendererType()); return false; } return doProduceOutput(leftBuf, rightBuf, length, static_cast<LA32FloatPartialPair *>(la32Pair)); } bool Partial::shouldReverb() { if (!isActive()) { return false; } return patchCache->reverb; } void Partial::startAbort() { // This is called when the partial manager needs to terminate partials for re-use by a new Poly. tva->startAbort(); } void Partial::startDecayAll() { tva->startDecay(); tvp->startDecay(); tvf->startDecay(); } } // namespace MT32Emu ```
/content/code_sandbox/src/sound/munt/Partial.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,947
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_TVP_H #define MT32EMU_TVP_H #include "globals.h" #include "Types.h" #include "Structures.h" namespace MT32Emu { class Part; class Partial; class TVP { private: const Partial * const partial; const MemParams::System * const system; // FIXME: Only necessary because masterTune calculation is done in the wrong place atm. const Part *part; const TimbreParam::PartialParam *partialParam; const MemParams::PatchTemp *patchTemp; const int processTimerTicksPerSampleX16; int processTimerIncrement; int counter; Bit32u timeElapsed; int phase; Bit32u basePitch; Bit32s targetPitchOffsetWithoutLFO; Bit32s currentPitchOffset; Bit16s lfoPitchOffset; // In range -12 - 36 Bit8s timeKeyfollowSubtraction; Bit16s pitchOffsetChangePerBigTick; Bit16u targetPitchOffsetReachedBigTick; unsigned int shifts; Bit16u pitch; void updatePitch(); void setupPitchChange(int targetPitchOffset, Bit8u changeDuration); void targetPitchOffsetReached(); void nextPhase(); void process(); public: TVP(const Partial *partial); void reset(const Part *part, const TimbreParam::PartialParam *partialParam); Bit32u getBasePitch() const; Bit16u nextPitch(); void startDecay(); }; // class TVP } // namespace MT32Emu #endif // #ifndef MT32EMU_TVP_H ```
/content/code_sandbox/src/sound/munt/TVP.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
422
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_LA32RAMP_H #define MT32EMU_LA32RAMP_H #include "globals.h" #include "Types.h" namespace MT32Emu { class LA32Ramp { private: Bit32u current; unsigned int largeTarget; unsigned int largeIncrement; bool descending; int interruptCountdown; bool interruptRaised; public: LA32Ramp(); void startRamp(Bit8u target, Bit8u increment); Bit32u nextValue(); bool checkInterrupt(); void reset(); bool isBelowCurrent(Bit8u target) const; }; } // namespace MT32Emu #endif // #ifndef MT32EMU_LA32RAMP_H ```
/content/code_sandbox/src/sound/munt/LA32Ramp.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
233
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #include <cstring> #include "internals.h" #include "Analog.h" #include "Synth.h" namespace MT32Emu { /* FIR approximation of the overall impulse response of the cascade composed of the sample & hold circuit and the low pass filter * of the MT-32 first generation. * The coefficients below are found by windowing the inverse DFT of the 1024 pin frequency response converted to the minimum phase. * The frequency response of the LPF is computed directly, the effect of the S&H is approximated by multiplying the LPF frequency * response by the corresponding sinc. Although, the LPF has DC gain of 3.2, we ignore this in the emulation and use normalised model. * The peak gain of the normalised cascade appears about 1.7 near 11.8 kHz. Relative error doesn't exceed 1% for the frequencies * below 12.5 kHz. In the higher frequency range, the relative error is below 8%. Peak error value is at 16 kHz. */ static const FloatSample COARSE_LPF_FLOAT_TAPS_MT32[] = { 1.272473681f, -0.220267785f, -0.158039905f, 0.179603785f, -0.111484097f, 0.054137498f, -0.023518029f, 0.010997169f, -0.006935698f }; // Similar approximation for new MT-32 and CM-32L/LAPC-I LPF. As the voltage controlled amplifier was introduced, LPF has unity DC gain. // The peak gain value shifted towards higher frequencies and a bit higher about 1.83 near 13 kHz. static const FloatSample COARSE_LPF_FLOAT_TAPS_CM32L[] = { 1.340615635f, -0.403331694f, 0.036005517f, 0.066156844f, -0.069672532f, 0.049563806f, -0.031113416f, 0.019169774f, -0.012421368f }; static const unsigned int COARSE_LPF_INT_FRACTION_BITS = 14; // Integer versions of the FIRs above multiplied by (1 << 14) and rounded. static const IntSampleEx COARSE_LPF_INT_TAPS_MT32[] = { 20848, -3609, -2589, 2943, -1827, 887, -385, 180, -114 }; static const IntSampleEx COARSE_LPF_INT_TAPS_CM32L[] = { 21965, -6608, 590, 1084, -1142, 812, -510, 314, -204 }; /* Combined FIR that both approximates the impulse response of the analogue circuits of sample & hold and the low pass filter * in the audible frequency range (below 20 kHz) and attenuates unwanted mirror spectra above 28 kHz as well. It is a polyphase * filter intended for resampling the signal to 48 kHz yet for applying high frequency boost. * As with the filter above, the analogue LPF frequency response is obtained for 1536 pin grid for range up to 96 kHz and multiplied * by the corresponding sinc. The result is further squared, windowed and passed to generalised Parks-McClellan routine as a desired response. * Finally, the minimum phase factor is found that's essentially the coefficients below. * Relative error in the audible frequency range doesn't exceed 0.0006%, attenuation in the stopband is better than 100 dB. * This level of performance makes it nearly bit-accurate for standard 16-bit sample resolution. */ // FIR version for MT-32 first generation. static const FloatSample ACCURATE_LPF_TAPS_MT32[] = { 0.003429281f, 0.025929869f, 0.096587777f, 0.228884848f, 0.372413431f, 0.412386503f, 0.263980018f, -0.014504962f, -0.237394528f, -0.257043496f, -0.103436603f, 0.063996095f, 0.124562333f, 0.083703206f, 0.013921662f, -0.033475018f, -0.046239712f, -0.029310921f, 0.00126585f, 0.021060961f, 0.017925605f, 0.003559874f, -0.005105248f, -0.005647917f, -0.004157918f, -0.002065664f, 0.00158747f, 0.003762585f, 0.001867137f, -0.001090028f, -0.001433979f, -0.00022367f, 4.34308E-05f, -0.000247827f, 0.000157087f, 0.000605823f, 0.000197317f, -0.000370511f, -0.000261202f, 9.96069E-05f, 9.85073E-05f, -5.28754E-05f, -1.00912E-05f, 7.69943E-05f, 2.03162E-05f, -5.67967E-05f, -3.30637E-05f, 1.61958E-05f, 1.73041E-05f }; // FIR version for new MT-32 and CM-32L/LAPC-I. static const FloatSample ACCURATE_LPF_TAPS_CM32L[] = { 0.003917452f, 0.030693861f, 0.116424199f, 0.275101674f, 0.43217361f, 0.431247894f, 0.183255659f, -0.174955671f, -0.354240244f, -0.212401714f, 0.072259178f, 0.204655344f, 0.108336211f, -0.039099027f, -0.075138174f, -0.026261906f, 0.00582663f, 0.003052193f, 0.00613657f, 0.017017951f, 0.008732535f, -0.011027427f, -0.012933664f, 0.001158097f, 0.006765958f, 0.00046778f, -0.002191106f, 0.001561017f, 0.001842871f, -0.001996876f, -0.002315836f, 0.000980965f, 0.001817454f, -0.000243272f, -0.000972848f, 0.000149941f, 0.000498886f, -0.000204436f, -0.000347415f, 0.000142386f, 0.000249137f, -4.32946E-05f, -0.000131231f, 3.88575E-07f, 4.48813E-05f, -1.31906E-06f, -1.03499E-05f, 7.71971E-06f, 2.86721E-06f }; // According to the CM-64 PCB schematic, there is a difference in the values of the LPF entrance resistors for the reverb and non-reverb channels. // This effectively results in non-unity LPF DC gain for the reverb channel of 0.68 while the LPF has unity DC gain for the LA32 output channels. // In emulation, the reverb output gain is multiplied by this factor to compensate for the LPF gain difference. static const float CM32L_REVERB_TO_LA32_ANALOG_OUTPUT_GAIN_FACTOR = 0.68f; static const unsigned int OUTPUT_GAIN_FRACTION_BITS = 8; static const float OUTPUT_GAIN_MULTIPLIER = float(1 << OUTPUT_GAIN_FRACTION_BITS); static const unsigned int COARSE_LPF_DELAY_LINE_LENGTH = 8; // Must be a power of 2 static const unsigned int ACCURATE_LPF_DELAY_LINE_LENGTH = 16; // Must be a power of 2 static const unsigned int ACCURATE_LPF_NUMBER_OF_PHASES = 3; // Upsampling factor static const unsigned int ACCURATE_LPF_PHASE_INCREMENT_REGULAR = 2; // Downsampling factor static const unsigned int ACCURATE_LPF_PHASE_INCREMENT_OVERSAMPLED = 1; // No downsampling static const Bit32u ACCURATE_LPF_DELTAS_REGULAR[][ACCURATE_LPF_NUMBER_OF_PHASES] = { { 0, 0, 0 }, { 1, 1, 0 }, { 1, 2, 1 } }; static const Bit32u ACCURATE_LPF_DELTAS_OVERSAMPLED[][ACCURATE_LPF_NUMBER_OF_PHASES] = { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 1 } }; template <class SampleEx> class AbstractLowPassFilter { public: static AbstractLowPassFilter<SampleEx> &createLowPassFilter(const AnalogOutputMode mode, const bool oldMT32AnalogLPF); virtual ~AbstractLowPassFilter() {} virtual SampleEx process(const SampleEx sample) = 0; virtual bool hasNextSample() const { return false; } virtual unsigned int getOutputSampleRate() const { return SAMPLE_RATE; } virtual unsigned int estimateInSampleCount(const unsigned int outSamples) const { return outSamples; } virtual void addPositionIncrement(const unsigned int) {} }; template <class SampleEx> class NullLowPassFilter : public AbstractLowPassFilter<SampleEx> { public: SampleEx process(const SampleEx sample) { return sample; } }; template <class SampleEx> class CoarseLowPassFilter : public AbstractLowPassFilter<SampleEx> { private: const SampleEx * const lpfTaps; SampleEx ringBuffer[COARSE_LPF_DELAY_LINE_LENGTH]; unsigned int ringBufferPosition; public: static inline const SampleEx *getLPFTaps(const bool oldMT32AnalogLPF); static inline SampleEx normaliseSample(const SampleEx sample); explicit CoarseLowPassFilter(const bool oldMT32AnalogLPF) : lpfTaps(getLPFTaps(oldMT32AnalogLPF)), ringBufferPosition(0) { Synth::muteSampleBuffer(ringBuffer, COARSE_LPF_DELAY_LINE_LENGTH); } SampleEx process(const SampleEx inSample) { static const unsigned int DELAY_LINE_MASK = COARSE_LPF_DELAY_LINE_LENGTH - 1; SampleEx sample = lpfTaps[COARSE_LPF_DELAY_LINE_LENGTH] * ringBuffer[ringBufferPosition]; ringBuffer[ringBufferPosition] = Synth::clipSampleEx(inSample); for (unsigned int i = 0; i < COARSE_LPF_DELAY_LINE_LENGTH; i++) { sample += lpfTaps[i] * ringBuffer[(i + ringBufferPosition) & DELAY_LINE_MASK]; } ringBufferPosition = (ringBufferPosition - 1) & DELAY_LINE_MASK; return normaliseSample(sample); } }; class AccurateLowPassFilter : public AbstractLowPassFilter<IntSampleEx>, public AbstractLowPassFilter<FloatSample> { private: const FloatSample * const LPF_TAPS; const Bit32u (* const deltas)[ACCURATE_LPF_NUMBER_OF_PHASES]; const unsigned int phaseIncrement; const unsigned int outputSampleRate; FloatSample ringBuffer[ACCURATE_LPF_DELAY_LINE_LENGTH]; unsigned int ringBufferPosition; unsigned int phase; public: AccurateLowPassFilter(const bool oldMT32AnalogLPF, const bool oversample); FloatSample process(const FloatSample sample); IntSampleEx process(const IntSampleEx sample); bool hasNextSample() const; unsigned int getOutputSampleRate() const; unsigned int estimateInSampleCount(const unsigned int outSamples) const; void addPositionIncrement(const unsigned int positionIncrement); }; static inline IntSampleEx normaliseSample(const IntSampleEx sample) { return sample >> OUTPUT_GAIN_FRACTION_BITS; } static inline FloatSample normaliseSample(const FloatSample sample) { return sample; } static inline float getActualReverbOutputGain(const float reverbGain, const bool mt32ReverbCompatibilityMode) { return mt32ReverbCompatibilityMode ? reverbGain : reverbGain * CM32L_REVERB_TO_LA32_ANALOG_OUTPUT_GAIN_FACTOR; } static inline IntSampleEx getIntOutputGain(const float outputGain) { return IntSampleEx(((OUTPUT_GAIN_MULTIPLIER < outputGain) ? OUTPUT_GAIN_MULTIPLIER : outputGain) * OUTPUT_GAIN_MULTIPLIER); } template <class SampleEx> class AnalogImpl : public Analog { public: AbstractLowPassFilter<SampleEx> &leftChannelLPF; AbstractLowPassFilter<SampleEx> &rightChannelLPF; SampleEx synthGain; SampleEx reverbGain; AnalogImpl(const AnalogOutputMode mode, const bool oldMT32AnalogLPF) : leftChannelLPF(AbstractLowPassFilter<SampleEx>::createLowPassFilter(mode, oldMT32AnalogLPF)), rightChannelLPF(AbstractLowPassFilter<SampleEx>::createLowPassFilter(mode, oldMT32AnalogLPF)), synthGain(0), reverbGain(0) {} ~AnalogImpl() { delete &leftChannelLPF; delete &rightChannelLPF; } unsigned int getOutputSampleRate() const { return leftChannelLPF.getOutputSampleRate(); } Bit32u getDACStreamsLength(const Bit32u outputLength) const { return leftChannelLPF.estimateInSampleCount(outputLength); } void setSynthOutputGain(const float synthGain); void setReverbOutputGain(const float reverbGain, const bool mt32ReverbCompatibilityMode); bool process(IntSample *outStream, const IntSample *nonReverbLeft, const IntSample *nonReverbRight, const IntSample *reverbDryLeft, const IntSample *reverbDryRight, const IntSample *reverbWetLeft, const IntSample *reverbWetRight, Bit32u outLength); bool process(FloatSample *outStream, const FloatSample *nonReverbLeft, const FloatSample *nonReverbRight, const FloatSample *reverbDryLeft, const FloatSample *reverbDryRight, const FloatSample *reverbWetLeft, const FloatSample *reverbWetRight, Bit32u outLength); template <class Sample> void produceOutput(Sample *outStream, const Sample *nonReverbLeft, const Sample *nonReverbRight, const Sample *reverbDryLeft, const Sample *reverbDryRight, const Sample *reverbWetLeft, const Sample *reverbWetRight, Bit32u outLength) { if (outStream == NULL) { leftChannelLPF.addPositionIncrement(outLength); rightChannelLPF.addPositionIncrement(outLength); return; } while (0 < (outLength--)) { SampleEx outSampleL; SampleEx outSampleR; if (leftChannelLPF.hasNextSample()) { outSampleL = leftChannelLPF.process(0); outSampleR = rightChannelLPF.process(0); } else { SampleEx inSampleL = (SampleEx(*(nonReverbLeft++)) + SampleEx(*(reverbDryLeft++))) * synthGain + SampleEx(*(reverbWetLeft++)) * reverbGain; SampleEx inSampleR = (SampleEx(*(nonReverbRight++)) + SampleEx(*(reverbDryRight++))) * synthGain + SampleEx(*(reverbWetRight++)) * reverbGain; outSampleL = leftChannelLPF.process(normaliseSample(inSampleL)); outSampleR = rightChannelLPF.process(normaliseSample(inSampleR)); } *(outStream++) = Synth::clipSampleEx(outSampleL); *(outStream++) = Synth::clipSampleEx(outSampleR); } } }; Analog *Analog::createAnalog(const AnalogOutputMode mode, const bool oldMT32AnalogLPF, const RendererType rendererType) { switch (rendererType) { case RendererType_BIT16S: return new AnalogImpl<IntSampleEx>(mode, oldMT32AnalogLPF); case RendererType_FLOAT: return new AnalogImpl<FloatSample>(mode, oldMT32AnalogLPF); default: break; } return NULL; } template<> bool AnalogImpl<IntSampleEx>::process(IntSample *outStream, const IntSample *nonReverbLeft, const IntSample *nonReverbRight, const IntSample *reverbDryLeft, const IntSample *reverbDryRight, const IntSample *reverbWetLeft, const IntSample *reverbWetRight, Bit32u outLength) { produceOutput(outStream, nonReverbLeft, nonReverbRight, reverbDryLeft, reverbDryRight, reverbWetLeft, reverbWetRight, outLength); return true; } template<> bool AnalogImpl<FloatSample>::process(IntSample *, const IntSample *, const IntSample *, const IntSample *, const IntSample *, const IntSample *, const IntSample *, Bit32u) { return false; } template<> bool AnalogImpl<IntSampleEx>::process(FloatSample *, const FloatSample *, const FloatSample *, const FloatSample *, const FloatSample *, const FloatSample *, const FloatSample *, Bit32u) { return false; } template<> bool AnalogImpl<FloatSample>::process(FloatSample *outStream, const FloatSample *nonReverbLeft, const FloatSample *nonReverbRight, const FloatSample *reverbDryLeft, const FloatSample *reverbDryRight, const FloatSample *reverbWetLeft, const FloatSample *reverbWetRight, Bit32u outLength) { produceOutput(outStream, nonReverbLeft, nonReverbRight, reverbDryLeft, reverbDryRight, reverbWetLeft, reverbWetRight, outLength); return true; } template<> void AnalogImpl<IntSampleEx>::setSynthOutputGain(const float useSynthGain) { synthGain = getIntOutputGain(useSynthGain); } template<> void AnalogImpl<IntSampleEx>::setReverbOutputGain(const float useReverbGain, const bool mt32ReverbCompatibilityMode) { reverbGain = getIntOutputGain(getActualReverbOutputGain(useReverbGain, mt32ReverbCompatibilityMode)); } template<> void AnalogImpl<FloatSample>::setSynthOutputGain(const float useSynthGain) { synthGain = useSynthGain; } template<> void AnalogImpl<FloatSample>::setReverbOutputGain(const float useReverbGain, const bool mt32ReverbCompatibilityMode) { reverbGain = getActualReverbOutputGain(useReverbGain, mt32ReverbCompatibilityMode); } template<> AbstractLowPassFilter<IntSampleEx> &AbstractLowPassFilter<IntSampleEx>::createLowPassFilter(AnalogOutputMode mode, bool oldMT32AnalogLPF) { switch (mode) { case AnalogOutputMode_COARSE: return *new CoarseLowPassFilter<IntSampleEx>(oldMT32AnalogLPF); case AnalogOutputMode_ACCURATE: return *new AccurateLowPassFilter(oldMT32AnalogLPF, false); case AnalogOutputMode_OVERSAMPLED: return *new AccurateLowPassFilter(oldMT32AnalogLPF, true); default: return *new NullLowPassFilter<IntSampleEx>; } } template<> AbstractLowPassFilter<FloatSample> &AbstractLowPassFilter<FloatSample>::createLowPassFilter(AnalogOutputMode mode, bool oldMT32AnalogLPF) { switch (mode) { case AnalogOutputMode_COARSE: return *new CoarseLowPassFilter<FloatSample>(oldMT32AnalogLPF); case AnalogOutputMode_ACCURATE: return *new AccurateLowPassFilter(oldMT32AnalogLPF, false); case AnalogOutputMode_OVERSAMPLED: return *new AccurateLowPassFilter(oldMT32AnalogLPF, true); default: return *new NullLowPassFilter<FloatSample>; } } template<> const IntSampleEx *CoarseLowPassFilter<IntSampleEx>::getLPFTaps(const bool oldMT32AnalogLPF) { return oldMT32AnalogLPF ? COARSE_LPF_INT_TAPS_MT32 : COARSE_LPF_INT_TAPS_CM32L; } template<> const FloatSample *CoarseLowPassFilter<FloatSample>::getLPFTaps(const bool oldMT32AnalogLPF) { return oldMT32AnalogLPF ? COARSE_LPF_FLOAT_TAPS_MT32 : COARSE_LPF_FLOAT_TAPS_CM32L; } template<> IntSampleEx CoarseLowPassFilter<IntSampleEx>::normaliseSample(const IntSampleEx sample) { return sample >> COARSE_LPF_INT_FRACTION_BITS; } template<> FloatSample CoarseLowPassFilter<FloatSample>::normaliseSample(const FloatSample sample) { return sample; } AccurateLowPassFilter::AccurateLowPassFilter(const bool oldMT32AnalogLPF, const bool oversample) : LPF_TAPS(oldMT32AnalogLPF ? ACCURATE_LPF_TAPS_MT32 : ACCURATE_LPF_TAPS_CM32L), deltas(oversample ? ACCURATE_LPF_DELTAS_OVERSAMPLED : ACCURATE_LPF_DELTAS_REGULAR), phaseIncrement(oversample ? ACCURATE_LPF_PHASE_INCREMENT_OVERSAMPLED : ACCURATE_LPF_PHASE_INCREMENT_REGULAR), outputSampleRate(SAMPLE_RATE * ACCURATE_LPF_NUMBER_OF_PHASES / phaseIncrement), ringBufferPosition(0), phase(0) { Synth::muteSampleBuffer(ringBuffer, ACCURATE_LPF_DELAY_LINE_LENGTH); } FloatSample AccurateLowPassFilter::process(const FloatSample inSample) { static const unsigned int DELAY_LINE_MASK = ACCURATE_LPF_DELAY_LINE_LENGTH - 1; FloatSample sample = (phase == 0) ? LPF_TAPS[ACCURATE_LPF_DELAY_LINE_LENGTH * ACCURATE_LPF_NUMBER_OF_PHASES] * ringBuffer[ringBufferPosition] : 0.0f; if (!hasNextSample()) { ringBuffer[ringBufferPosition] = inSample; } for (unsigned int tapIx = phase, delaySampleIx = 0; delaySampleIx < ACCURATE_LPF_DELAY_LINE_LENGTH; delaySampleIx++, tapIx += ACCURATE_LPF_NUMBER_OF_PHASES) { sample += LPF_TAPS[tapIx] * ringBuffer[(delaySampleIx + ringBufferPosition) & DELAY_LINE_MASK]; } phase += phaseIncrement; if (ACCURATE_LPF_NUMBER_OF_PHASES <= phase) { phase -= ACCURATE_LPF_NUMBER_OF_PHASES; ringBufferPosition = (ringBufferPosition - 1) & DELAY_LINE_MASK; } return ACCURATE_LPF_NUMBER_OF_PHASES * sample; } IntSampleEx AccurateLowPassFilter::process(const IntSampleEx sample) { return IntSampleEx(process(FloatSample(sample))); } bool AccurateLowPassFilter::hasNextSample() const { return phaseIncrement <= phase; } unsigned int AccurateLowPassFilter::getOutputSampleRate() const { return outputSampleRate; } unsigned int AccurateLowPassFilter::estimateInSampleCount(const unsigned int outSamples) const { Bit32u cycleCount = outSamples / ACCURATE_LPF_NUMBER_OF_PHASES; Bit32u remainder = outSamples - cycleCount * ACCURATE_LPF_NUMBER_OF_PHASES; return cycleCount * phaseIncrement + deltas[remainder][phase]; } void AccurateLowPassFilter::addPositionIncrement(const unsigned int positionIncrement) { phase = (phase + positionIncrement * phaseIncrement) % ACCURATE_LPF_NUMBER_OF_PHASES; } } // namespace MT32Emu ```
/content/code_sandbox/src/sound/munt/Analog.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
5,418
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #include <cstdlib> #include "internals.h" #include "TVP.h" #include "Part.h" #include "Partial.h" #include "Poly.h" #include "Synth.h" #include "TVA.h" namespace MT32Emu { // FIXME: Add Explanation static Bit16u lowerDurationToDivisor[] = {34078, 37162, 40526, 44194, 48194, 52556, 57312, 62499}; // These values represent unique options with no consistent pattern, so we have to use something like a table in any case. // The table matches exactly what the manual claims (when divided by 8192): // -1, -1/2, -1/4, 0, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, 1, 5/4, 3/2, 2, s1, s2 // ...except for the last two entries, which are supposed to be "1 cent above 1" and "2 cents above 1", respectively. They can only be roughly approximated with this integer math. static Bit16s pitchKeyfollowMult[] = {-8192, -4096, -2048, 0, 1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192, 10240, 12288, 16384, 8198, 8226}; // Note: Keys < 60 use keyToPitchTable[60 - key], keys >= 60 use keyToPitchTable[key - 60]. // FIXME: This table could really be shorter, since we never use e.g. key 127. static Bit16u keyToPitchTable[] = { 0, 341, 683, 1024, 1365, 1707, 2048, 2389, 2731, 3072, 3413, 3755, 4096, 4437, 4779, 5120, 5461, 5803, 6144, 6485, 6827, 7168, 7509, 7851, 8192, 8533, 8875, 9216, 9557, 9899, 10240, 10581, 10923, 11264, 11605, 11947, 12288, 12629, 12971, 13312, 13653, 13995, 14336, 14677, 15019, 15360, 15701, 16043, 16384, 16725, 17067, 17408, 17749, 18091, 18432, 18773, 19115, 19456, 19797, 20139, 20480, 20821, 21163, 21504, 21845, 22187, 22528, 22869 }; // We want to do processing 4000 times per second. FIXME: This is pretty arbitrary. static const int NOMINAL_PROCESS_TIMER_PERIOD_SAMPLES = SAMPLE_RATE / 4000; // In all hardware units we emulate, the main clock frequency of the MCU is 12MHz. // However, the MCU used in the 3rd-gen sound modules (like CM-500 and LAPC-N) // is significantly faster. Importantly, the software timer also works faster, // yet this fact has been seemingly missed. To be more specific, the software timer // ticks each 8 "state times", and 1 state time equals to 3 clock periods // for 8095 and 8098 but 2 clock periods for 80C198. That is, on MT-32 and CM-32L, // the software timer tick rate is 12,000,000 / 3 / 8 = 500kHz, but on the 3rd-gen // devices it's 12,000,000 / 2 / 8 = 750kHz instead. // For 1st- and 2nd-gen devices, the timer ticks at 500kHz. This is how much to increment // timeElapsed once 16 samples passes. We multiply by 16 to get rid of the fraction // and deal with just integers. static const int PROCESS_TIMER_TICKS_PER_SAMPLE_X16_1N2_GEN = (500000 << 4) / SAMPLE_RATE; // For 3rd-gen devices, the timer ticks at 750kHz. This is how much to increment // timeElapsed once 16 samples passes. We multiply by 16 to get rid of the fraction // and deal with just integers. static const int PROCESS_TIMER_TICKS_PER_SAMPLE_X16_3_GEN = (750000 << 4) / SAMPLE_RATE; TVP::TVP(const Partial *usePartial) : partial(usePartial), system(&usePartial->getSynth()->mt32ram.system), processTimerTicksPerSampleX16( partial->getSynth()->controlROMFeatures->quirkFastPitchChanges ? PROCESS_TIMER_TICKS_PER_SAMPLE_X16_3_GEN : PROCESS_TIMER_TICKS_PER_SAMPLE_X16_1N2_GEN) {} static Bit16s keyToPitch(unsigned int key) { // We're using a table to do: return round_to_nearest_or_even((key - 60) * (4096.0 / 12.0)) // Banker's rounding is just slightly annoying to do in C++ int k = int(key); Bit16s pitch = keyToPitchTable[abs(k - 60)]; return key < 60 ? -pitch : pitch; } static inline Bit32s coarseToPitch(Bit8u coarse) { return (coarse - 36) * 4096 / 12; // One semitone per coarse offset } static inline Bit32s fineToPitch(Bit8u fine) { return (fine - 50) * 4096 / 1200; // One cent per fine offset } static Bit32u calcBasePitch(const Partial *partial, const TimbreParam::PartialParam *partialParam, const MemParams::PatchTemp *patchTemp, unsigned int key, const ControlROMFeatureSet *controlROMFeatures) { Bit32s basePitch = keyToPitch(key); basePitch = (basePitch * pitchKeyfollowMult[partialParam->wg.pitchKeyfollow]) >> 13; // PORTABILITY NOTE: Assumes arithmetic shift basePitch += coarseToPitch(partialParam->wg.pitchCoarse); basePitch += fineToPitch(partialParam->wg.pitchFine); if (controlROMFeatures->quirkKeyShift) { // NOTE:Mok: This is done on MT-32, but not LAPC-I: basePitch += coarseToPitch(patchTemp->patch.keyShift + 12); } basePitch += fineToPitch(patchTemp->patch.fineTune); const ControlROMPCMStruct *controlROMPCMStruct = partial->getControlROMPCMStruct(); if (controlROMPCMStruct != NULL) { basePitch += (Bit32s(controlROMPCMStruct->pitchMSB) << 8) | Bit32s(controlROMPCMStruct->pitchLSB); } else { if ((partialParam->wg.waveform & 1) == 0) { basePitch += 37133; // This puts Middle C at around 261.64Hz (assuming no other modifications, masterTune of 64, etc.) } else { // Sawtooth waves are effectively double the frequency of square waves. // Thus we add 4096 less than for square waves here, which results in halving the frequency. basePitch += 33037; } } // MT-32 GEN0 does 16-bit calculations here, allowing an integer overflow. // This quirk is observable playing the patch defined for timbre "HIT BOTTOM" in Larry 3. // Note, the upper bound isn't checked either. if (controlROMFeatures->quirkBasePitchOverflow) { basePitch = basePitch & 0xffff; } else if (basePitch < 0) { basePitch = 0; } else if (basePitch > 59392) { basePitch = 59392; } return Bit32u(basePitch); } static Bit32u calcVeloMult(Bit8u veloSensitivity, unsigned int velocity) { if (veloSensitivity == 0) { return 21845; // aka floor(4096 / 12 * 64), aka ~64 semitones } unsigned int reversedVelocity = 127 - velocity; unsigned int scaledReversedVelocity; if (veloSensitivity > 3) { // Note that on CM-32L/LAPC-I veloSensitivity is never > 3, since it's clipped to 3 by the max tables. // MT-32 GEN0 has a bug here that leads to unspecified behaviour. We assume it is as follows. scaledReversedVelocity = (reversedVelocity << 8) >> ((3 - veloSensitivity) & 0x1f); } else { scaledReversedVelocity = reversedVelocity << (5 + veloSensitivity); } // When velocity is 127, the multiplier is 21845, aka ~64 semitones (regardless of veloSensitivity). // The lower the velocity, the lower the multiplier. The veloSensitivity determines the amount decreased per velocity value. // The minimum multiplier on CM-32L/LAPC-I (with velocity 0, veloSensitivity 3) is 170 (~half a semitone). return ((32768 - scaledReversedVelocity) * 21845) >> 15; } static Bit32s calcTargetPitchOffsetWithoutLFO(const TimbreParam::PartialParam *partialParam, int levelIndex, unsigned int velocity) { int veloMult = calcVeloMult(partialParam->pitchEnv.veloSensitivity, velocity); int targetPitchOffsetWithoutLFO = partialParam->pitchEnv.level[levelIndex] - 50; targetPitchOffsetWithoutLFO = (targetPitchOffsetWithoutLFO * veloMult) >> (16 - partialParam->pitchEnv.depth); // PORTABILITY NOTE: Assumes arithmetic shift return targetPitchOffsetWithoutLFO; } void TVP::reset(const Part *usePart, const TimbreParam::PartialParam *usePartialParam) { part = usePart; partialParam = usePartialParam; patchTemp = part->getPatchTemp(); unsigned int key = partial->getPoly()->getKey(); unsigned int velocity = partial->getPoly()->getVelocity(); // FIXME: We're using a per-TVP timer instead of a system-wide one for convenience. timeElapsed = 0; processTimerIncrement = 0; basePitch = calcBasePitch(partial, partialParam, patchTemp, key, partial->getSynth()->controlROMFeatures); currentPitchOffset = calcTargetPitchOffsetWithoutLFO(partialParam, 0, velocity); targetPitchOffsetWithoutLFO = currentPitchOffset; phase = 0; if (partialParam->pitchEnv.timeKeyfollow) { timeKeyfollowSubtraction = Bit32s(key - 60) >> (5 - partialParam->pitchEnv.timeKeyfollow); // PORTABILITY NOTE: Assumes arithmetic shift } else { timeKeyfollowSubtraction = 0; } lfoPitchOffset = 0; counter = 0; pitch = basePitch; // These don't really need to be initialised, but it aids debugging. pitchOffsetChangePerBigTick = 0; targetPitchOffsetReachedBigTick = 0; shifts = 0; } Bit32u TVP::getBasePitch() const { return basePitch; } void TVP::updatePitch() { Bit32s newPitch = basePitch + currentPitchOffset; if (!partial->isPCM() || (partial->getControlROMPCMStruct()->len & 0x01) == 0) { // FIXME: Use !partial->pcmWaveEntry->unaffectedByMasterTune instead // FIXME: There are various bugs not yet emulated // 171 is ~half a semitone. newPitch += partial->getSynth()->getMasterTunePitchDelta(); } if ((partialParam->wg.pitchBenderEnabled & 1) != 0) { newPitch += part->getPitchBend(); } // MT-32 GEN0 does 16-bit calculations here, allowing an integer overflow. // This quirk is exploited e.g. in Colonel's Bequest timbres "Lightning" and "SwmpBackgr". if (partial->getSynth()->controlROMFeatures->quirkPitchEnvelopeOverflow) { newPitch = newPitch & 0xffff; } else if (newPitch < 0) { newPitch = 0; } // This check is present in every unit. if (newPitch > 59392) { newPitch = 59392; } pitch = Bit16u(newPitch); // FIXME: We're doing this here because that's what the CM-32L does - we should probably move this somewhere more appropriate in future. partial->getTVA()->recalcSustain(); } void TVP::targetPitchOffsetReached() { currentPitchOffset = targetPitchOffsetWithoutLFO + lfoPitchOffset; switch (phase) { case 3: case 4: { int newLFOPitchOffset = (part->getModulation() * partialParam->pitchLFO.modSensitivity) >> 7; newLFOPitchOffset = (newLFOPitchOffset + partialParam->pitchLFO.depth) << 1; if (pitchOffsetChangePerBigTick > 0) { // Go in the opposite direction to last time newLFOPitchOffset = -newLFOPitchOffset; } lfoPitchOffset = newLFOPitchOffset; int targetPitchOffset = targetPitchOffsetWithoutLFO + lfoPitchOffset; setupPitchChange(targetPitchOffset, 101 - partialParam->pitchLFO.rate); updatePitch(); break; } case 6: updatePitch(); break; default: nextPhase(); } } void TVP::nextPhase() { phase++; int envIndex = phase == 6 ? 4 : phase; targetPitchOffsetWithoutLFO = calcTargetPitchOffsetWithoutLFO(partialParam, envIndex, partial->getPoly()->getVelocity()); // pitch we'll reach at the end int changeDuration = partialParam->pitchEnv.time[envIndex - 1]; changeDuration -= timeKeyfollowSubtraction; if (changeDuration > 0) { setupPitchChange(targetPitchOffsetWithoutLFO, changeDuration); // changeDuration between 0 and 112 now updatePitch(); } else { targetPitchOffsetReached(); } } // Shifts val to the left until bit 31 is 1 and returns the number of shifts static Bit8u normalise(Bit32u &val) { Bit8u leftShifts; for (leftShifts = 0; leftShifts < 31; leftShifts++) { if ((val & 0x80000000) != 0) { break; } val = val << 1; } return leftShifts; } void TVP::setupPitchChange(int targetPitchOffset, Bit8u changeDuration) { bool negativeDelta = targetPitchOffset < currentPitchOffset; Bit32s pitchOffsetDelta = targetPitchOffset - currentPitchOffset; if (pitchOffsetDelta > 32767 || pitchOffsetDelta < -32768) { pitchOffsetDelta = 32767; } if (negativeDelta) { pitchOffsetDelta = -pitchOffsetDelta; } // We want to maximise the number of bits of the Bit16s "pitchOffsetChangePerBigTick" we use in order to get the best possible precision later Bit32u absPitchOffsetDelta = (pitchOffsetDelta & 0xFFFF) << 16; Bit8u normalisationShifts = normalise(absPitchOffsetDelta); // FIXME: Double-check: normalisationShifts is usually between 0 and 15 here, unless the delta is 0, in which case it's 31 absPitchOffsetDelta = absPitchOffsetDelta >> 1; // Make room for the sign bit changeDuration--; // changeDuration's now between 0 and 111 unsigned int upperDuration = changeDuration >> 3; // upperDuration's now between 0 and 13 shifts = normalisationShifts + upperDuration + 2; Bit16u divisor = lowerDurationToDivisor[changeDuration & 7]; Bit16s newPitchOffsetChangePerBigTick = ((absPitchOffsetDelta & 0xFFFF0000) / divisor) >> 1; // Result now fits within 15 bits. FIXME: Check nothing's getting sign-extended incorrectly if (negativeDelta) { newPitchOffsetChangePerBigTick = -newPitchOffsetChangePerBigTick; } pitchOffsetChangePerBigTick = newPitchOffsetChangePerBigTick; int currentBigTick = timeElapsed >> 8; int durationInBigTicks = divisor >> (12 - upperDuration); if (durationInBigTicks > 32767) { durationInBigTicks = 32767; } // The result of the addition may exceed 16 bits, but wrapping is fine and intended here. targetPitchOffsetReachedBigTick = currentBigTick + durationInBigTicks; } void TVP::startDecay() { phase = 5; lfoPitchOffset = 0; targetPitchOffsetReachedBigTick = timeElapsed >> 8; // FIXME: Afaict there's no good reason for this - check } Bit16u TVP::nextPitch() { // We emulate MCU software timer using these counter and processTimerIncrement variables. // The value of NOMINAL_PROCESS_TIMER_PERIOD_SAMPLES approximates the period in samples // between subsequent firings of the timer that normally occur. // However, accurate emulation is quite complicated because the timer is not guaranteed to fire in time. // This makes pitch variations on real unit non-deterministic and dependent on various factors. if (counter == 0) { timeElapsed = (timeElapsed + processTimerIncrement) & 0x00FFFFFF; // This roughly emulates pitch deviations observed on real units when playing a single partial that uses TVP/LFO. counter = NOMINAL_PROCESS_TIMER_PERIOD_SAMPLES + (rand() & 3); processTimerIncrement = (processTimerTicksPerSampleX16 * counter) >> 4; process(); } counter--; return pitch; } void TVP::process() { if (phase == 0) { targetPitchOffsetReached(); return; } if (phase == 5) { nextPhase(); return; } if (phase > 7) { updatePitch(); return; } Bit16s negativeBigTicksRemaining = (timeElapsed >> 8) - targetPitchOffsetReachedBigTick; if (negativeBigTicksRemaining >= 0) { // We've reached the time for a phase change targetPitchOffsetReached(); return; } // FIXME: Write explanation for this stuff // NOTE: Value of shifts may happily exceed the maximum of 31 specified for the 8095 MCU. // We assume the device performs a shift with the rightmost 5 bits of the counter regardless of argument size, // since shift instructions of any size have the same maximum. int rightShifts = shifts; if (rightShifts > 13) { rightShifts -= 13; negativeBigTicksRemaining = negativeBigTicksRemaining >> (rightShifts & 0x1F); // PORTABILITY NOTE: Assumes arithmetic shift rightShifts = 13; } int newResult = (negativeBigTicksRemaining * pitchOffsetChangePerBigTick) >> (rightShifts & 0x1F); // PORTABILITY NOTE: Assumes arithmetic shift newResult += targetPitchOffsetWithoutLFO + lfoPitchOffset; currentPitchOffset = newResult; updatePitch(); } } // namespace MT32Emu ```
/content/code_sandbox/src/sound/munt/TVP.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
4,518
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #include "globals.h" extern "C" { // Here's a list of all tagged minor library versions through global (potentially versioned) symbols. // An application that's been linked with an older library version will be able to find a matching tag, // while for an application linked with a newer library version there will be no match. MT32EMU_EXPORT_V(2.5) extern const volatile char mt32emu_2_5 = 0; MT32EMU_EXPORT_V(2.6) extern const volatile char mt32emu_2_6 = 0; MT32EMU_EXPORT_V(2.7) extern const volatile char mt32emu_2_7 = 0; #if MT32EMU_VERSION_MAJOR > 2 || MT32EMU_VERSION_MINOR > 7 #error "Missing version tag definition for current library version" #endif } ```
/content/code_sandbox/src/sound/munt/VersionTagging.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
269
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ /* Some notes on this class: This emulates the LA-32's implementation of "ramps". A ramp in this context is a smooth transition from one value to another, handled entirely within the LA-32. The LA-32 provides this feature for amplitude and filter cutoff values. The 8095 starts ramps on the LA-32 by setting two values in memory-mapped registers: (1) The target value (between 0 and 255) for the ramp to end on. This is represented by the "target" argument to startRamp(). (2) The speed at which that value should be approached. This is represented by the "increment" argument to startRamp(). Once the ramp target value has been hit, the LA-32 raises an interrupt. Note that the starting point of the ramp is whatever internal value the LA-32 had when the registers were set. This is usually the end point of a previously completed ramp. Our handling of the "target" and "increment" values is based on sample analysis and a little guesswork. Here's what we're pretty confident about: - The most significant bit of "increment" indicates the direction that the LA32's current internal value ("current" in our emulation) should change in. Set means downward, clear means upward. - The lower 7 bits of "increment" indicate how quickly "current" should be changed. - If "increment" is 0, no change to "current" is made and no interrupt is raised. [SEMI-CONFIRMED by sample analysis] - Otherwise, if the MSb is set: - If "current" already corresponds to a value <= "target", "current" is set immediately to the equivalent of "target" and an interrupt is raised. - Otherwise, "current" is gradually reduced (at a rate determined by the lower 7 bits of "increment"), and once it reaches the equivalent of "target" an interrupt is raised. - Otherwise (the MSb is unset): - If "current" already corresponds to a value >= "target", "current" is set immediately to the equivalent of "target" and an interrupt is raised. - Otherwise, "current" is gradually increased (at a rate determined by the lower 7 bits of "increment"), and once it reaches the equivalent of "target" an interrupt is raised. We haven't fully explored: - Values when ramping between levels (though this is probably correct). - Transition timing (may not be 100% accurate, especially for very fast ramps). */ #include "internals.h" #include "LA32Ramp.h" #include "Tables.h" namespace MT32Emu { // SEMI-CONFIRMED from sample analysis. const unsigned int TARGET_SHIFTS = 18; const unsigned int MAX_CURRENT = 0xFF << TARGET_SHIFTS; // We simulate the delay in handling "target was reached" interrupts by waiting // this many samples before setting interruptRaised. // FIXME: This should vary with the sample rate, but doesn't. // SEMI-CONFIRMED: Since this involves asynchronous activity between the LA32 // and the 8095, a good value is hard to pin down. // This one matches observed behaviour on a few digital captures I had handy, // and should be double-checked. We may also need a more sophisticated delay // scheme eventually. const int INTERRUPT_TIME = 7; LA32Ramp::LA32Ramp() : current(0), largeTarget(0), largeIncrement(0), interruptCountdown(0), interruptRaised(false) { } void LA32Ramp::startRamp(Bit8u target, Bit8u increment) { // CONFIRMED: From sample analysis, this appears to be very accurate. if (increment == 0) { largeIncrement = 0; } else { // Three bits in the fractional part, no need to interpolate // (unsigned int)(EXP2F(((increment & 0x7F) + 24) / 8.0f) + 0.125f) Bit32u expArg = increment & 0x7F; largeIncrement = 8191 - Tables::getInstance().exp9[~(expArg << 6) & 511]; largeIncrement <<= expArg >> 3; largeIncrement += 64; largeIncrement >>= 9; } descending = (increment & 0x80) != 0; if (descending) { // CONFIRMED: From sample analysis, descending increments are slightly faster largeIncrement++; } largeTarget = target << TARGET_SHIFTS; interruptCountdown = 0; interruptRaised = false; } Bit32u LA32Ramp::nextValue() { if (interruptCountdown > 0) { if (--interruptCountdown == 0) { interruptRaised = true; } } else if (largeIncrement != 0) { // CONFIRMED from sample analysis: When increment is 0, the LA32 does *not* change the current value at all (and of course doesn't fire an interrupt). if (descending) { // Lowering current value if (largeIncrement > current) { current = largeTarget; interruptCountdown = INTERRUPT_TIME; } else { current -= largeIncrement; if (current <= largeTarget) { current = largeTarget; interruptCountdown = INTERRUPT_TIME; } } } else { // Raising current value if (MAX_CURRENT - current < largeIncrement) { current = largeTarget; interruptCountdown = INTERRUPT_TIME; } else { current += largeIncrement; if (current >= largeTarget) { current = largeTarget; interruptCountdown = INTERRUPT_TIME; } } } } return current; } bool LA32Ramp::checkInterrupt() { bool wasRaised = interruptRaised; interruptRaised = false; return wasRaised; } void LA32Ramp::reset() { current = 0; largeTarget = 0; largeIncrement = 0; descending = false; interruptCountdown = 0; interruptRaised = false; } // This is actually beyond the LA32 ramp interface. // Instead of polling the current value, MCU receives an interrupt when a ramp completes. // However, this is a simple way to work around the specific behaviour of TVA // when in sustain phase which one normally wants to avoid. // See TVA::recalcSustain() for details. bool LA32Ramp::isBelowCurrent(Bit8u target) const { return Bit32u(target << TARGET_SHIFTS) < current; } } // namespace MT32Emu ```
/content/code_sandbox/src/sound/munt/LA32Ramp.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,544
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_TYPES_H #define MT32EMU_TYPES_H namespace MT32Emu { typedef unsigned int Bit32u; typedef signed int Bit32s; typedef unsigned short int Bit16u; typedef signed short int Bit16s; typedef unsigned char Bit8u; typedef signed char Bit8s; } #endif ```
/content/code_sandbox/src/sound/munt/Types.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
166
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_STRUCTURES_H #define MT32EMU_STRUCTURES_H #include "globals.h" #include "Types.h" namespace MT32Emu { // MT32EMU_MEMADDR() converts from sysex-padded, MT32EMU_SYSEXMEMADDR converts to it // Roland provides documentation using the sysex-padded addresses, so we tend to use that in code and output #define MT32EMU_MEMADDR(x) ((((x) & 0x7f0000) >> 2) | (((x) & 0x7f00) >> 1) | ((x) & 0x7f)) #define MT32EMU_SYSEXMEMADDR(x) ((((x) & 0x1FC000) << 2) | (((x) & 0x3F80) << 1) | ((x) & 0x7f)) #if defined(_MSC_VER) && !defined(__clang__) #define MT32EMU_ALIGN_PACKED __declspec(align(1)) #else #define MT32EMU_ALIGN_PACKED __attribute__((packed)) #endif // The following structures represent the MT-32's memory // Since sysex allows this memory to be written to in blocks of bytes, // we keep this packed so that we can copy data into the various // banks directly #if defined(_MSC_VER) || defined(__MINGW32__) #pragma pack(push, 1) #else #pragma pack(1) #endif struct TimbreParam { struct CommonParam { char name[10]; Bit8u partialStructure12; // 1 & 2 0-12 (1-13) Bit8u partialStructure34; // 3 & 4 0-12 (1-13) Bit8u partialMute; // 0-15 (0000-1111) Bit8u noSustain; // ENV MODE 0-1 (Normal, No sustain) } MT32EMU_ALIGN_PACKED common; struct PartialParam { struct WGParam { Bit8u pitchCoarse; // 0-96 (C1,C#1-C9) Bit8u pitchFine; // 0-100 (-50 to +50 (cents - confirmed by Mok)) Bit8u pitchKeyfollow; // 0-16 (-1, -1/2, -1/4, 0, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, 1, 5/4, 3/2, 2, s1, s2) Bit8u pitchBenderEnabled; // 0-1 (OFF, ON) Bit8u waveform; // MT-32: 0-1 (SQU/SAW); LAPC-I: WG WAVEFORM/PCM BANK 0 - 3 (SQU/1, SAW/1, SQU/2, SAW/2) Bit8u pcmWave; // 0-127 (1-128) Bit8u pulseWidth; // 0-100 Bit8u pulseWidthVeloSensitivity; // 0-14 (-7 - +7) } MT32EMU_ALIGN_PACKED wg; struct PitchEnvParam { Bit8u depth; // 0-10 Bit8u veloSensitivity; // 0-100 Bit8u timeKeyfollow; // 0-4 Bit8u time[4]; // 0-100 Bit8u level[5]; // 0-100 (-50 - +50) // [3]: SUSTAIN LEVEL, [4]: END LEVEL } MT32EMU_ALIGN_PACKED pitchEnv; struct PitchLFOParam { Bit8u rate; // 0-100 Bit8u depth; // 0-100 Bit8u modSensitivity; // 0-100 } MT32EMU_ALIGN_PACKED pitchLFO; struct TVFParam { Bit8u cutoff; // 0-100 Bit8u resonance; // 0-30 Bit8u keyfollow; // -1, -1/2, -1/4, 0, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, 1, 5/4, 3/2, 2 Bit8u biasPoint; // 0-127 (<1A-<7C >1A-7C) Bit8u biasLevel; // 0-14 (-7 - +7) Bit8u envDepth; // 0-100 Bit8u envVeloSensitivity; // 0-100 Bit8u envDepthKeyfollow; // DEPTH KEY FOLL0W 0-4 Bit8u envTimeKeyfollow; // TIME KEY FOLLOW 0-4 Bit8u envTime[5]; // 0-100 Bit8u envLevel[4]; // 0-100 // [3]: SUSTAIN LEVEL } MT32EMU_ALIGN_PACKED tvf; struct TVAParam { Bit8u level; // 0-100 Bit8u veloSensitivity; // 0-100 Bit8u biasPoint1; // 0-127 (<1A-<7C >1A-7C) Bit8u biasLevel1; // 0-12 (-12 - 0) Bit8u biasPoint2; // 0-127 (<1A-<7C >1A-7C) Bit8u biasLevel2; // 0-12 (-12 - 0) Bit8u envTimeKeyfollow; // TIME KEY FOLLOW 0-4 Bit8u envTimeVeloSensitivity; // VELOS KEY FOLL0W 0-4 Bit8u envTime[5]; // 0-100 Bit8u envLevel[4]; // 0-100 // [3]: SUSTAIN LEVEL } MT32EMU_ALIGN_PACKED tva; } MT32EMU_ALIGN_PACKED partial[4]; // struct PartialParam } MT32EMU_ALIGN_PACKED; // struct TimbreParam struct PatchParam { Bit8u timbreGroup; // TIMBRE GROUP 0-3 (group A, group B, Memory, Rhythm) Bit8u timbreNum; // TIMBRE NUMBER 0-63 Bit8u keyShift; // KEY SHIFT 0-48 (-24 - +24 semitones) Bit8u fineTune; // FINE TUNE 0-100 (-50 - +50 cents) Bit8u benderRange; // BENDER RANGE 0-24 Bit8u assignMode; // ASSIGN MODE 0-3 (POLY1, POLY2, POLY3, POLY4) Bit8u reverbSwitch; // REVERB SWITCH 0-1 (OFF,ON) Bit8u dummy; // (DUMMY) } MT32EMU_ALIGN_PACKED; const unsigned int SYSTEM_MASTER_TUNE_OFF = 0; const unsigned int SYSTEM_REVERB_MODE_OFF = 1; const unsigned int SYSTEM_REVERB_TIME_OFF = 2; const unsigned int SYSTEM_REVERB_LEVEL_OFF = 3; const unsigned int SYSTEM_RESERVE_SETTINGS_START_OFF = 4; const unsigned int SYSTEM_RESERVE_SETTINGS_END_OFF = 12; const unsigned int SYSTEM_CHAN_ASSIGN_START_OFF = 13; const unsigned int SYSTEM_CHAN_ASSIGN_END_OFF = 21; const unsigned int SYSTEM_MASTER_VOL_OFF = 22; struct MemParams { // NOTE: The MT-32 documentation only specifies PatchTemp areas for parts 1-8. // The LAPC-I documentation specified an additional area for rhythm at the end, // where all parameters but fine tune, assign mode and output level are ignored struct PatchTemp { PatchParam patch; Bit8u outputLevel; // OUTPUT LEVEL 0-100 Bit8u panpot; // PANPOT 0-14 (R-L) Bit8u dummyv[6]; } MT32EMU_ALIGN_PACKED patchTemp[9]; struct RhythmTemp { Bit8u timbre; // TIMBRE 0-94 (M1-M64,R1-30,OFF); LAPC-I: 0-127 (M01-M64,R01-R63) Bit8u outputLevel; // OUTPUT LEVEL 0-100 Bit8u panpot; // PANPOT 0-14 (R-L) Bit8u reverbSwitch; // REVERB SWITCH 0-1 (OFF,ON) } MT32EMU_ALIGN_PACKED rhythmTemp[85]; TimbreParam timbreTemp[8]; PatchParam patches[128]; // NOTE: There are only 30 timbres in the "rhythm" bank for MT-32; the additional 34 are for LAPC-I and above struct PaddedTimbre { TimbreParam timbre; Bit8u padding[10]; } MT32EMU_ALIGN_PACKED timbres[64 + 64 + 64 + 64]; // Group A, Group B, Memory, Rhythm struct System { Bit8u masterTune; // MASTER TUNE 0-127 432.1-457.6Hz Bit8u reverbMode; // REVERB MODE 0-3 (room, hall, plate, tap delay) Bit8u reverbTime; // REVERB TIME 0-7 (1-8) Bit8u reverbLevel; // REVERB LEVEL 0-7 (1-8) Bit8u reserveSettings[9]; // PARTIAL RESERVE (PART 1) 0-32 Bit8u chanAssign[9]; // MIDI CHANNEL (PART1) 0-16 (1-16,OFF) Bit8u masterVol; // MASTER VOLUME 0-100 } MT32EMU_ALIGN_PACKED system; }; // struct MemParams struct SoundGroup { Bit8u timbreNumberTableAddrLow; Bit8u timbreNumberTableAddrHigh; Bit8u displayPosition; Bit8u name[9]; Bit8u timbreCount; Bit8u pad; } MT32EMU_ALIGN_PACKED; #if defined(_MSC_VER) || defined(__MINGW32__) #pragma pack(pop) #else #pragma pack() #endif struct ControlROMFeatureSet { unsigned int quirkBasePitchOverflow : 1; unsigned int quirkPitchEnvelopeOverflow : 1; unsigned int quirkRingModulationNoMix : 1; unsigned int quirkTVAZeroEnvLevels : 1; unsigned int quirkPanMult : 1; unsigned int quirkKeyShift : 1; unsigned int quirkTVFBaseCutoffLimit : 1; unsigned int quirkFastPitchChanges : 1; unsigned int quirkDisplayCustomMessagePriority : 1; unsigned int oldMT32DisplayFeatures : 1; // Features below don't actually depend on control ROM version, which is used to identify hardware model unsigned int defaultReverbMT32Compatible : 1; unsigned int oldMT32AnalogLPF : 1; }; struct ControlROMMap { const char *shortName; const ControlROMFeatureSet &featureSet; Bit16u pcmTable; // 4 * pcmCount bytes Bit16u pcmCount; Bit16u timbreAMap; // 128 bytes Bit16u timbreAOffset; bool timbreACompressed; Bit16u timbreBMap; // 128 bytes Bit16u timbreBOffset; bool timbreBCompressed; Bit16u timbreRMap; // 2 * timbreRCount bytes Bit16u timbreRCount; Bit16u rhythmSettings; // 4 * rhythmSettingsCount bytes Bit16u rhythmSettingsCount; Bit16u reserveSettings; // 9 bytes Bit16u panSettings; // 8 bytes Bit16u programSettings; // 8 bytes Bit16u rhythmMaxTable; // 4 bytes Bit16u patchMaxTable; // 16 bytes Bit16u systemMaxTable; // 23 bytes Bit16u timbreMaxTable; // 72 bytes Bit16u soundGroupsTable; // 14 bytes each entry Bit16u soundGroupsCount; Bit16u startupMessage; // 20 characters + NULL terminator Bit16u sysexErrorMessage; // 20 characters + NULL terminator }; struct ControlROMPCMStruct { Bit8u pos; Bit8u len; Bit8u pitchLSB; Bit8u pitchMSB; }; struct PCMWaveEntry { Bit32u addr; Bit32u len; bool loop; ControlROMPCMStruct *controlROMPCMStruct; }; // This is basically a per-partial, pre-processed combination of timbre and patch/rhythm settings struct PatchCache { bool playPartial; bool PCMPartial; int pcm; Bit8u waveform; Bit32u structureMix; int structurePosition; int structurePair; // The following fields are actually common to all partials in the timbre bool dirty; Bit32u partialCount; bool sustain; bool reverb; TimbreParam::PartialParam srcPartial; // The following directly points into live sysex-addressable memory const TimbreParam::PartialParam *partialParam; }; } // namespace MT32Emu #endif // #ifndef MT32EMU_STRUCTURES_H ```
/content/code_sandbox/src/sound/munt/Structures.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
3,143
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_SYNTH_H #define MT32EMU_SYNTH_H #include <cstdarg> #include <cstddef> #include <cstring> #include "globals.h" #include "Types.h" #include "Enumerations.h" namespace MT32Emu { class Analog; class BReverbModel; class Extensions; class MemoryRegion; class MidiEventQueue; class Part; class Poly; class Partial; class PartialManager; class Renderer; class ROMImage; class PatchTempMemoryRegion; class RhythmTempMemoryRegion; class TimbreTempMemoryRegion; class PatchesMemoryRegion; class TimbresMemoryRegion; class SystemMemoryRegion; class DisplayMemoryRegion; class ResetMemoryRegion; struct ControlROMFeatureSet; struct ControlROMMap; struct PCMWaveEntry; struct MemParams; const Bit8u SYSEX_MANUFACTURER_ROLAND = 0x41; const Bit8u SYSEX_MDL_MT32 = 0x16; const Bit8u SYSEX_MDL_D50 = 0x14; const Bit8u SYSEX_CMD_RQ1 = 0x11; // Request data #1 const Bit8u SYSEX_CMD_DT1 = 0x12; // Data set 1 const Bit8u SYSEX_CMD_WSD = 0x40; // Want to send data const Bit8u SYSEX_CMD_RQD = 0x41; // Request data const Bit8u SYSEX_CMD_DAT = 0x42; // Data set const Bit8u SYSEX_CMD_ACK = 0x43; // Acknowledge const Bit8u SYSEX_CMD_EOD = 0x45; // End of data const Bit8u SYSEX_CMD_ERR = 0x4E; // Communications error const Bit8u SYSEX_CMD_RJC = 0x4F; // Rejection // This value isn't quite correct: the new-gen MT-32 control ROMs (ver. 2.XX) are twice as big. // Nevertheless, this is still relevant for library internal usage because the higher half // of those ROMs only contains the demo songs in all cases. const Bit32u CONTROL_ROM_SIZE = 64 * 1024; // Set of multiplexed output streams appeared at the DAC entrance. template <class T> struct DACOutputStreams { T *nonReverbLeft; T *nonReverbRight; T *reverbDryLeft; T *reverbDryRight; T *reverbWetLeft; T *reverbWetRight; }; // Class for the client to supply callbacks for reporting various errors and information class MT32EMU_EXPORT ReportHandler { public: virtual ~ReportHandler() {} // Callback for debug messages, in vprintf() format virtual void printDebug(const char *fmt, va_list list); // Callbacks for reporting errors virtual void onErrorControlROM() {} virtual void onErrorPCMROM() {} // Callback for reporting about displaying a new custom message on LCD virtual void showLCDMessage(const char *message); // Callback for reporting actual processing of a MIDI message virtual void onMIDIMessagePlayed() {} // Callback for reporting an overflow of the input MIDI queue. // Returns true if a recovery action was taken and yet another attempt to enqueue the MIDI event is desired. virtual bool onMIDIQueueOverflow() { return false; } // Callback invoked when a System Realtime MIDI message is detected at the input. virtual void onMIDISystemRealtime(Bit8u /* systemRealtime */) {} // Callbacks for reporting system events virtual void onDeviceReset() {} virtual void onDeviceReconfig() {} // Callbacks for reporting changes of reverb settings virtual void onNewReverbMode(Bit8u /* mode */) {} virtual void onNewReverbTime(Bit8u /* time */) {} virtual void onNewReverbLevel(Bit8u /* level */) {} // Callbacks for reporting various information virtual void onPolyStateChanged(Bit8u /* partNum */) {} virtual void onProgramChanged(Bit8u /* partNum */, const char * /* soundGroupName */, const char * /* patchName */) {} }; // Extends ReportHandler, so that the client may supply callbacks for reporting signals about updated display state. class MT32EMU_EXPORT_V(2.6) ReportHandler2 : public ReportHandler { public: virtual ~ReportHandler2() {} // Invoked to signal about a change of the emulated LCD state. Use method Synth::getDisplayState to retrieve the actual data. // This callback will not be invoked on further changes, until the client retrieves the LCD state. virtual void onLCDStateUpdated() {} // Invoked when the emulated MIDI MESSAGE LED changes state. The ledState parameter represents whether the LED is ON. virtual void onMidiMessageLEDStateUpdated(bool /* ledState */) {} }; class Synth { friend class DefaultMidiStreamParser; friend class Display; friend class MemoryRegion; friend class Part; friend class Partial; friend class PartialManager; friend class Poly; friend class Renderer; friend class RhythmPart; friend class SamplerateAdapter; friend class SoxrAdapter; friend class TVA; friend class TVF; friend class TVP; private: // **************************** Implementation fields ************************** PatchTempMemoryRegion *patchTempMemoryRegion; RhythmTempMemoryRegion *rhythmTempMemoryRegion; TimbreTempMemoryRegion *timbreTempMemoryRegion; PatchesMemoryRegion *patchesMemoryRegion; TimbresMemoryRegion *timbresMemoryRegion; SystemMemoryRegion *systemMemoryRegion; DisplayMemoryRegion *displayMemoryRegion; ResetMemoryRegion *resetMemoryRegion; Bit8u *paddedTimbreMaxTable; PCMWaveEntry *pcmWaves; // Array const ControlROMFeatureSet *controlROMFeatures; const ControlROMMap *controlROMMap; Bit8u controlROMData[CONTROL_ROM_SIZE]; Bit16s *pcmROMData; size_t pcmROMSize; // This is in 16-bit samples, therefore half the number of bytes in the ROM Bit8u soundGroupIx[128]; // For each standard timbre const char (*soundGroupNames)[9]; // Array Bit32u partialCount; Bit8u nukeme[16]; // FIXME: Nuke it. For binary compatibility only. MidiEventQueue *midiQueue; volatile Bit32u lastReceivedMIDIEventTimestamp; volatile Bit32u renderedSampleCount; MemParams &mt32ram, &mt32default; BReverbModel *reverbModels[4]; BReverbModel *reverbModel; bool reverbOverridden; MIDIDelayMode midiDelayMode; DACInputMode dacInputMode; float outputGain; float reverbOutputGain; bool reversedStereoEnabled; bool opened; bool activated; bool isDefaultReportHandler; // No longer used, retained for binary compatibility only. ReportHandler *reportHandler; PartialManager *partialManager; Part *parts[9]; // When a partial needs to be aborted to free it up for use by a new Poly, // the controller will busy-loop waiting for the sound to finish. // We emulate this by delaying new MIDI events processing until abortion finishes. Poly *abortingPoly; Analog *analog; Renderer *renderer; // Binary compatibility helper. Extensions &extensions; // **************************** Implementation methods ************************** Bit32u addMIDIInterfaceDelay(Bit32u len, Bit32u timestamp); bool isAbortingPoly() const { return abortingPoly != NULL; } void writeSysexGlobal(Bit32u addr, const Bit8u *sysex, Bit32u len); void readSysex(Bit8u channel, const Bit8u *sysex, Bit32u len) const; void initMemoryRegions(); void deleteMemoryRegions(); MemoryRegion *findMemoryRegion(Bit32u addr); void writeMemoryRegion(const MemoryRegion *region, Bit32u addr, Bit32u len, const Bit8u *data); void readMemoryRegion(const MemoryRegion *region, Bit32u addr, Bit32u len, Bit8u *data); bool loadControlROM(const ROMImage &controlROMImage); bool loadPCMROM(const ROMImage &pcmROMImage); bool initPCMList(Bit16u mapAddress, Bit16u count); bool initTimbres(Bit16u mapAddress, Bit16u offset, Bit16u timbreCount, Bit16u startTimbre, bool compressed); bool initCompressedTimbre(Bit16u drumNum, const Bit8u *mem, Bit32u memLen); void initReverbModels(bool mt32CompatibleMode); void initSoundGroups(char newSoundGroupNames[][9]); void refreshSystemMasterTune(); void refreshSystemReverbParameters(); void refreshSystemReserveSettings(); void refreshSystemChanAssign(Bit8u firstPart, Bit8u lastPart); void refreshSystemMasterVol(); void refreshSystem(); void reset(); void dispose(); void printPartialUsage(Bit32u sampleOffset = 0); void rhythmNotePlayed() const; void voicePartStateChanged(Bit8u partNum, bool activated) const; void newTimbreSet(Bit8u partNum) const; const char *getSoundGroupName(const Part *part) const; const char *getSoundGroupName(Bit8u timbreGroup, Bit8u timbreNumber) const; void printDebug(const char *fmt, ...); // partNum should be 0..7 for Part 1..8, or 8 for Rhythm const Part *getPart(Bit8u partNum) const; void resetMasterTunePitchDelta(); Bit32s getMasterTunePitchDelta() const; public: static inline Bit16s clipSampleEx(Bit32s sampleEx) { // Clamp values above 32767 to 32767, and values below -32768 to -32768 // FIXME: Do we really need this stuff? I think these branches are very well predicted. Instead, this introduces a chain. // The version below is actually a bit faster on my system... //return ((sampleEx + 0x8000) & ~0xFFFF) ? Bit16s((sampleEx >> 31) ^ 0x7FFF) : (Bit16s)sampleEx; return ((-0x8000 <= sampleEx) && (sampleEx <= 0x7FFF)) ? Bit16s(sampleEx) : Bit16s((sampleEx >> 31) ^ 0x7FFF); } static inline float clipSampleEx(float sampleEx) { return sampleEx; } template <class S> static inline void muteSampleBuffer(S *buffer, Bit32u len) { if (buffer == NULL) return; memset(buffer, 0, len * sizeof(S)); } static inline void muteSampleBuffer(float *buffer, Bit32u len) { if (buffer == NULL) return; // FIXME: Use memset() where compatibility is guaranteed (if this turns out to be a win) while (len--) { *(buffer++) = 0.0f; } } static inline Bit16s convertSample(float sample) { return Synth::clipSampleEx(Bit32s(sample * 32768.0f)); // This multiplier corresponds to normalised floats } static inline float convertSample(Bit16s sample) { return float(sample) / 32768.0f; // This multiplier corresponds to normalised floats } // Returns library version as an integer in format: 0x00MMmmpp, where: // MM - major version number // mm - minor version number // pp - patch number MT32EMU_EXPORT static Bit32u getLibraryVersionInt(); // Returns library version as a C-string in format: "MAJOR.MINOR.PATCH" MT32EMU_EXPORT static const char *getLibraryVersionString(); MT32EMU_EXPORT static Bit32u getShortMessageLength(Bit32u msg); MT32EMU_EXPORT static Bit8u calcSysexChecksum(const Bit8u *data, const Bit32u len, const Bit8u initChecksum = 0); // Returns output sample rate used in emulation of stereo analog circuitry of hardware units. // See comment for AnalogOutputMode. MT32EMU_EXPORT static Bit32u getStereoOutputSampleRate(AnalogOutputMode analogOutputMode); // Optionally sets callbacks for reporting various errors, information and debug messages MT32EMU_EXPORT explicit Synth(ReportHandler *useReportHandler = NULL); MT32EMU_EXPORT ~Synth(); // Sets an implementation of ReportHandler2 interface for reporting various errors, information and debug messages. // If the argument is NULL, the default implementation is installed as a fallback. MT32EMU_EXPORT_V(2.6) void setReportHandler2(ReportHandler2 *reportHandler2); // Used to initialise the MT-32. Must be called before any other function. // Returns true if initialization was successful, otherwise returns false. // controlROMImage and pcmROMImage represent full Control and PCM ROM images for use by synth. // usePartialCount sets the maximum number of partials playing simultaneously for this session (optional). // analogOutputMode sets the mode for emulation of analogue circuitry of the hardware units (optional). MT32EMU_EXPORT bool open(const ROMImage &controlROMImage, const ROMImage &pcmROMImage, Bit32u usePartialCount = DEFAULT_MAX_PARTIALS, AnalogOutputMode analogOutputMode = AnalogOutputMode_COARSE); // Overloaded method which opens the synth with default partial count. MT32EMU_EXPORT bool open(const ROMImage &controlROMImage, const ROMImage &pcmROMImage, AnalogOutputMode analogOutputMode); // Closes the MT-32 and deallocates any memory used by the synthesizer MT32EMU_EXPORT void close(); // Returns true if the synth is in completely initialized state, otherwise returns false. MT32EMU_EXPORT bool isOpen() const; // All the enqueued events are processed by the synth immediately. MT32EMU_EXPORT void flushMIDIQueue(); // Sets size of the internal MIDI event queue. The queue size is set to the minimum power of 2 that is greater or equal to the size specified. // The queue is flushed before reallocation. // Returns the actual queue size being used. MT32EMU_EXPORT Bit32u setMIDIEventQueueSize(Bit32u requestedSize); // Configures the SysEx storage of the internal MIDI event queue. // Supplying 0 in the storageBufferSize argument makes the SysEx data stored // in multiple dynamically allocated buffers per MIDI event. These buffers are only disposed // when a new MIDI event replaces the SysEx event in the queue, thus never on the rendering thread. // This is the default behaviour. // In contrast, when a positive value is specified, SysEx data will be stored in a single preallocated buffer, // which makes this kind of storage safe for use in a realtime thread. Additionally, the space retained // by a SysEx event, that has been processed and thus is no longer necessary, is disposed instantly. // Note, the queue is flushed and recreated in the process so that its size remains intact. MT32EMU_EXPORT void configureMIDIEventQueueSysexStorage(Bit32u storageBufferSize); // Returns current value of the global counter of samples rendered since the synth was created (at the native sample rate 32000 Hz). // This method helps to compute accurate timestamp of a MIDI message to use with the methods below. MT32EMU_EXPORT Bit32u getInternalRenderedSampleCount() const; // Enqueues a MIDI event for subsequent playback. // The MIDI event will be processed not before the specified timestamp. // The timestamp is measured as the global rendered sample count since the synth was created (at the native sample rate 32000 Hz). // The minimum delay involves emulation of the delay introduced while the event is transferred via MIDI interface // and emulation of the MCU busy-loop while it frees partials for use by a new Poly. // Calls from multiple threads must be synchronised, although, no synchronisation is required with the rendering thread. // The methods return false if the MIDI event queue is full and the message cannot be enqueued. // Enqueues a single short MIDI message to play at specified time. The message must contain a status byte. MT32EMU_EXPORT bool playMsg(Bit32u msg, Bit32u timestamp); // Enqueues a single well formed System Exclusive MIDI message to play at specified time. MT32EMU_EXPORT bool playSysex(const Bit8u *sysex, Bit32u len, Bit32u timestamp); // Enqueues a single short MIDI message to be processed ASAP. The message must contain a status byte. MT32EMU_EXPORT bool playMsg(Bit32u msg); // Enqueues a single well formed System Exclusive MIDI message to be processed ASAP. MT32EMU_EXPORT bool playSysex(const Bit8u *sysex, Bit32u len); // WARNING: // The methods below don't ensure minimum 1-sample delay between sequential MIDI events, // and a sequence of NoteOn and immediately succeeding NoteOff messages is always silent. // A thread that invokes these methods must be explicitly synchronised with the thread performing sample rendering. // Sends a short MIDI message to the synth for immediate playback. The message must contain a status byte. // See the WARNING above. MT32EMU_EXPORT void playMsgNow(Bit32u msg); // Sends unpacked short MIDI message to the synth for immediate playback. The message must contain a status byte. // See the WARNING above. MT32EMU_EXPORT void playMsgOnPart(Bit8u part, Bit8u code, Bit8u note, Bit8u velocity); // Sends a single well formed System Exclusive MIDI message for immediate processing. The length is in bytes. // See the WARNING above. MT32EMU_EXPORT void playSysexNow(const Bit8u *sysex, Bit32u len); // Sends inner body of a System Exclusive MIDI message for direct processing. The length is in bytes. // See the WARNING above. MT32EMU_EXPORT void playSysexWithoutFraming(const Bit8u *sysex, Bit32u len); // Sends inner body of a System Exclusive MIDI message for direct processing. The length is in bytes. // See the WARNING above. MT32EMU_EXPORT void playSysexWithoutHeader(Bit8u device, Bit8u command, const Bit8u *sysex, Bit32u len); // Sends inner body of a System Exclusive MIDI message for direct processing. The length is in bytes. // See the WARNING above. MT32EMU_EXPORT void writeSysex(Bit8u channel, const Bit8u *sysex, Bit32u len); // Allows to disable wet reverb output altogether. MT32EMU_EXPORT void setReverbEnabled(bool reverbEnabled); // Returns whether wet reverb output is enabled. MT32EMU_EXPORT bool isReverbEnabled() const; // Sets override reverb mode. In this mode, emulation ignores sysexes (or the related part of them) which control the reverb parameters. // This mode is in effect until it is turned off. When the synth is re-opened, the override mode is unchanged but the state // of the reverb model is reset to default. MT32EMU_EXPORT void setReverbOverridden(bool reverbOverridden); // Returns whether reverb settings are overridden. MT32EMU_EXPORT bool isReverbOverridden() const; // Forces reverb model compatibility mode. By default, the compatibility mode corresponds to the used control ROM version. // Invoking this method with the argument set to true forces emulation of old MT-32 reverb circuit. // When the argument is false, emulation of the reverb circuit used in new generation of MT-32 compatible modules is enforced // (these include CM-32L and LAPC-I). MT32EMU_EXPORT void setReverbCompatibilityMode(bool mt32CompatibleMode); // Returns whether reverb is in old MT-32 compatibility mode. MT32EMU_EXPORT bool isMT32ReverbCompatibilityMode() const; // Returns whether default reverb compatibility mode is the old MT-32 compatibility mode. MT32EMU_EXPORT bool isDefaultReverbMT32Compatible() const; // If enabled, reverb buffers for all modes are kept around allocated all the time to avoid memory // allocating/freeing in the rendering thread, which may be required for realtime operation. // Otherwise, reverb buffers that are not in use are deleted to save memory (the default behaviour). MT32EMU_EXPORT void preallocateReverbMemory(bool enabled); // Sets new DAC input mode. See DACInputMode for details. MT32EMU_EXPORT void setDACInputMode(DACInputMode mode); // Returns current DAC input mode. See DACInputMode for details. MT32EMU_EXPORT DACInputMode getDACInputMode() const; // Sets new MIDI delay mode. See MIDIDelayMode for details. MT32EMU_EXPORT void setMIDIDelayMode(MIDIDelayMode mode); // Returns current MIDI delay mode. See MIDIDelayMode for details. MT32EMU_EXPORT MIDIDelayMode getMIDIDelayMode() const; // Sets output gain factor for synth output channels. Applied to all output samples and unrelated with the synth's Master volume, // it rather corresponds to the gain of the output analog circuitry of the hardware units. However, together with setReverbOutputGain() // it offers to the user a capability to control the gain of reverb and non-reverb output channels independently. MT32EMU_EXPORT void setOutputGain(float gain); // Returns current output gain factor for synth output channels. MT32EMU_EXPORT float getOutputGain() const; // Sets output gain factor for the reverb wet output channels. It rather corresponds to the gain of the output // analog circuitry of the hardware units. However, together with setOutputGain() it offers to the user a capability // to control the gain of reverb and non-reverb output channels independently. // // Note: We're currently emulate CM-32L/CM-64 reverb quite accurately and the reverb output level closely // corresponds to the level of digital capture. Although, according to the CM-64 PCB schematic, // there is a difference in the reverb analogue circuit, and the resulting output gain is 0.68 // of that for LA32 analogue output. This factor is applied to the reverb output gain. MT32EMU_EXPORT void setReverbOutputGain(float gain); // Returns current output gain factor for reverb wet output channels. MT32EMU_EXPORT float getReverbOutputGain() const; // Sets (or removes) an override for the current volume (output level) on a specific part. // When the part volume is overridden, the MIDI controller Volume (7) on the MIDI channel this part is assigned to // has no effect on the output level of this part. Similarly, the output level value set on this part via a SysEx that // modifies the Patch temp structure is disregarded. // To enable the override mode, argument volumeOverride should be in range 0..100, setting a value outside this range // disables the previously set override, if any. // Note: Setting volumeOverride to 0 mutes the part completely, meaning no sound is generated at all. // This is unlike the behaviour of real devices - setting 0 volume on a part may leave it still producing // sound at a very low level. // Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm. MT32EMU_EXPORT_V(2.6) void setPartVolumeOverride(Bit8u partNumber, Bit8u volumeOverride); // Returns the overridden volume previously set on a specific part; a value outside the range 0..100 means no override // is currently in effect. // Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm. MT32EMU_EXPORT_V(2.6) Bit8u getPartVolumeOverride(Bit8u partNumber) const; // Swaps left and right output channels. MT32EMU_EXPORT void setReversedStereoEnabled(bool enabled); // Returns whether left and right output channels are swapped. MT32EMU_EXPORT bool isReversedStereoEnabled() const; // Allows to toggle the NiceAmpRamp mode. // In this mode, we want to ensure that amp ramp never jumps to the target // value and always gradually increases or decreases. It seems that real units // do not bother to always check if a newly started ramp leads to a jump. // We also prefer the quality improvement over the emulation accuracy, // so this mode is enabled by default. MT32EMU_EXPORT void setNiceAmpRampEnabled(bool enabled); // Returns whether NiceAmpRamp mode is enabled. MT32EMU_EXPORT bool isNiceAmpRampEnabled() const; // Allows to toggle the NicePanning mode. // Despite the Roland's manual specifies allowed panpot values in range 0-14, // the LA-32 only receives 3-bit pan setting in fact. In particular, this // makes it impossible to set the "middle" panning for a single partial. // In the NicePanning mode, we enlarge the pan setting accuracy to 4 bits // making it smoother thus sacrificing the emulation accuracy. // This mode is disabled by default. MT32EMU_EXPORT void setNicePanningEnabled(bool enabled); // Returns whether NicePanning mode is enabled. MT32EMU_EXPORT bool isNicePanningEnabled() const; // Allows to toggle the NicePartialMixing mode. // LA-32 is known to mix partials either in-phase (so that they are added) // or in counter-phase (so that they are subtracted instead). // In some cases, this quirk isn't highly desired because a pair of closely // sounding partials may occasionally cancel out. // In the NicePartialMixing mode, the mixing is always performed in-phase, // thus making the behaviour more predictable. // This mode is disabled by default. MT32EMU_EXPORT void setNicePartialMixingEnabled(bool enabled); // Returns whether NicePartialMixing mode is enabled. MT32EMU_EXPORT bool isNicePartialMixingEnabled() const; // Selects new type of the wave generator and renderer to be used during subsequent calls to open(). // By default, RendererType_BIT16S is selected. // See RendererType for details. MT32EMU_EXPORT void selectRendererType(RendererType); // Returns previously selected type of the wave generator and renderer. // See RendererType for details. MT32EMU_EXPORT RendererType getSelectedRendererType() const; // Returns actual sample rate used in emulation of stereo analog circuitry of hardware units. // See comment for render() below. MT32EMU_EXPORT Bit32u getStereoOutputSampleRate() const; // Renders samples to the specified output stream as if they were sampled at the analog stereo output. // When AnalogOutputMode is set to ACCURATE (OVERSAMPLED), the output signal is upsampled to 48 (96) kHz in order // to retain emulation accuracy in whole audible frequency spectra. Otherwise, native digital signal sample rate is retained. // getStereoOutputSampleRate() can be used to query actual sample rate of the output signal. // The length is in frames, not bytes (in 16-bit stereo, one frame is 4 bytes). Uses NATIVE byte ordering. MT32EMU_EXPORT void render(Bit16s *stream, Bit32u len); // Same as above but outputs to a float stereo stream. MT32EMU_EXPORT void render(float *stream, Bit32u len); // Renders samples to the specified output streams as if they appeared at the DAC entrance. // No further processing performed in analog circuitry emulation is applied to the signal. // NULL may be specified in place of any or all of the stream buffers to skip it. // The length is in samples, not bytes. Uses NATIVE byte ordering. MT32EMU_EXPORT void renderStreams(Bit16s *nonReverbLeft, Bit16s *nonReverbRight, Bit16s *reverbDryLeft, Bit16s *reverbDryRight, Bit16s *reverbWetLeft, Bit16s *reverbWetRight, Bit32u len); MT32EMU_EXPORT void renderStreams(const DACOutputStreams<Bit16s> &streams, Bit32u len); // Same as above but outputs to float streams. MT32EMU_EXPORT void renderStreams(float *nonReverbLeft, float *nonReverbRight, float *reverbDryLeft, float *reverbDryRight, float *reverbWetLeft, float *reverbWetRight, Bit32u len); MT32EMU_EXPORT void renderStreams(const DACOutputStreams<float> &streams, Bit32u len); // Returns true when there is at least one active partial, otherwise false. MT32EMU_EXPORT bool hasActivePartials() const; // Returns true if the synth is active and subsequent calls to render() may result in non-trivial output (i.e. silence). // The synth is considered active when either there are pending MIDI events in the queue, there is at least one active partial, // or the reverb is (somewhat unreliably) detected as being active. MT32EMU_EXPORT bool isActive(); // Returns the maximum number of partials playing simultaneously. MT32EMU_EXPORT Bit32u getPartialCount() const; // Fills in current states of all the parts into the array provided. The array must have at least 9 entries to fit values for all the parts. // If the value returned for a part is true, there is at least one active non-releasing partial playing on this part. // This info is useful in emulating behaviour of LCD display of the hardware units. MT32EMU_EXPORT void getPartStates(bool *partStates) const; // Returns current states of all the parts as a bit set. The least significant bit corresponds to the state of part 1, // total of 9 bits hold the states of all the parts. If the returned bit for a part is set, there is at least one active // non-releasing partial playing on this part. This info is useful in emulating behaviour of LCD display of the hardware units. MT32EMU_EXPORT Bit32u getPartStates() const; // Fills in current states of all the partials into the array provided. The array must be large enough to accommodate states of all the partials. MT32EMU_EXPORT void getPartialStates(PartialState *partialStates) const; // Fills in current states of all the partials into the array provided. Each byte in the array holds states of 4 partials // starting from the least significant bits. The state of each partial is packed in a pair of bits. // The array must be large enough to accommodate states of all the partials (see getPartialCount()). MT32EMU_EXPORT void getPartialStates(Bit8u *partialStates) const; // Fills in information about currently playing notes on the specified part into the arrays provided. The arrays must be large enough // to accommodate data for all the playing notes. The maximum number of simultaneously playing notes cannot exceed the number of partials. // Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm. // Returns the number of currently playing notes on the specified part. MT32EMU_EXPORT Bit32u getPlayingNotes(Bit8u partNumber, Bit8u *keys, Bit8u *velocities) const; // Returns name of the patch set on the specified part. // Argument partNumber should be 0..7 for Part 1..8, or 8 for Rhythm. // The returned value is a null-terminated string which is guaranteed to remain valid until the next call to one of render methods. MT32EMU_EXPORT const char *getPatchName(Bit8u partNumber) const; // Retrieves the name of the sound group the timbre identified by arguments timbreGroup and timbreNumber is associated with. // Values 0-3 of timbreGroup correspond to the timbre banks GROUP A, GROUP B, MEMORY and RHYTHM. // For all but the RHYTHM timbre bank, allowed values of timbreNumber are in range 0-63. The number of timbres // contained in the RHYTHM bank depends on the used control ROM version. // The argument soundGroupName must point to an array of at least 8 characters. The result is a null-terminated string. // Returns whether the specified timbre has been found and the result written in soundGroupName. MT32EMU_EXPORT_V(2.7) bool getSoundGroupName(char *soundGroupName, Bit8u timbreGroup, Bit8u timbreNumber) const; // Retrieves the name of the timbre identified by arguments timbreGroup and timbreNumber. // Values 0-3 of timbreGroup correspond to the timbre banks GROUP A, GROUP B, MEMORY and RHYTHM. // For all but the RHYTHM timbre bank, allowed values of timbreNumber are in range 0-63. The number of timbres // contained in the RHYTHM bank depends on the used control ROM version. // The argument soundName must point to an array of at least 11 characters. The result is a null-terminated string. // Returns whether the specified timbre has been found and the result written in soundName. MT32EMU_EXPORT_V(2.7) bool getSoundName(char *soundName, Bit8u timbreGroup, Bit8u timbreNumber) const; // Stores internal state of emulated synth into an array provided (as it would be acquired from hardware). MT32EMU_EXPORT void readMemory(Bit32u addr, Bit32u len, Bit8u *data); // Retrieves the current state of the emulated MT-32 display facilities. // Typically, the state is updated during the rendering. When that happens, a related callback from ReportHandler2 is invoked. // However, there might be no need to invoke this method after each update, e.g. when the render buffer is just a few milliseconds // long. // The argument targetBuffer must point to an array of at least 21 characters. The result is a null-terminated string. // The optional argument narrowLCD enables a condensed representation of the displayed information in some cases. This is mainly // intended to route the result to a hardware LCD that is only 16 characters wide. Automatic scrolling of longer strings // is not supported. // Returns whether the MIDI MESSAGE LED is ON and fills the targetBuffer parameter. MT32EMU_EXPORT_V(2.6) bool getDisplayState(char *targetBuffer, bool narrowLCD = false) const; // Resets the emulated LCD to the main mode (Master Volume). This has the same effect as pressing the Master Volume button // while the display shows some other message. Useful for the new-gen devices as those require a special Display Reset SysEx // to return to the main mode e.g. from showing a custom display message or a checksum error. MT32EMU_EXPORT_V(2.6) void setMainDisplayMode(); // Permits to select an arbitrary display emulation model that does not necessarily match the actual behaviour implemented // in the control ROM version being used. // Invoking this method with the argument set to true forces emulation of the old-gen MT-32 display features. // Otherwise, emulation of the new-gen devices is enforced (these include CM-32L and LAPC-I as if these were connected to an LCD). MT32EMU_EXPORT_V(2.6) void setDisplayCompatibility(bool oldMT32CompatibilityEnabled); // Returns whether the currently configured features of the emulated display are compatible with the old-gen MT-32 devices. MT32EMU_EXPORT_V(2.6) bool isDisplayOldMT32Compatible() const; // Returns whether the emulated display features configured by default depending on the actual control ROM version // are compatible with the old-gen MT-32 devices. MT32EMU_EXPORT_V(2.6) bool isDefaultDisplayOldMT32Compatible() const; }; // class Synth } // namespace MT32Emu #endif // #ifndef MT32EMU_SYNTH_H ```
/content/code_sandbox/src/sound/munt/Synth.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
7,967
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_GLOBALS_H #define MT32EMU_GLOBALS_H #include "config.h" /* Support for compiling shared library. * MT32EMU_SHARED and mt32emu_EXPORTS are defined when building a shared library. * MT32EMU_SHARED should also be defined for Windows platforms that provides for a small performance benefit, * and it _must_ be defined along with MT32EMU_RUNTIME_VERSION_CHECK when using MSVC. */ #ifdef MT32EMU_SHARED # if defined _WIN32 || defined __CYGWIN__ || defined __OS2__ # ifdef _MSC_VER # ifdef mt32emu_EXPORTS # define MT32EMU_EXPORT_ATTRIBUTE _declspec(dllexport) # else /* #ifdef mt32emu_EXPORTS */ # define MT32EMU_EXPORT_ATTRIBUTE _declspec(dllimport) # endif /* #ifdef mt32emu_EXPORTS */ # else /* #ifdef _MSC_VER */ # ifdef mt32emu_EXPORTS # define MT32EMU_EXPORT_ATTRIBUTE __attribute__ ((dllexport)) # else /* #ifdef mt32emu_EXPORTS */ # define MT32EMU_EXPORT_ATTRIBUTE __attribute__ ((dllimport)) # endif /* #ifdef mt32emu_EXPORTS */ # endif /* #ifdef _MSC_VER */ # else /* #if defined _WIN32 || defined __CYGWIN__ || defined __OS2__ */ # ifdef mt32emu_EXPORTS # define MT32EMU_EXPORT_ATTRIBUTE __attribute__ ((visibility("default"))) # else /* #ifdef mt32emu_EXPORTS */ # define MT32EMU_EXPORT_ATTRIBUTE # endif /* #ifdef mt32emu_EXPORTS */ # endif /* #if defined _WIN32 || defined __CYGWIN__ || defined __OS2__ */ #else /* #ifdef MT32EMU_SHARED */ # define MT32EMU_EXPORT_ATTRIBUTE #endif /* #ifdef MT32EMU_SHARED */ #if MT32EMU_EXPORTS_TYPE == 1 || MT32EMU_EXPORTS_TYPE == 2 #define MT32EMU_EXPORT #else #define MT32EMU_EXPORT MT32EMU_EXPORT_ATTRIBUTE #endif /* Facilitates easier tracking of the library version when an external symbol was introduced. * Particularly useful for shared library builds on POSIX systems that support symbol versioning, * so that the version map file can be generated automatically. */ #define MT32EMU_EXPORT_V(symbol_version_tag) MT32EMU_EXPORT /* Helpers for compile-time version checks */ /* Encodes the given version components to a single integer value to simplify further checks. */ #define MT32EMU_VERSION_INT(major, minor, patch) ((major << 16) | (minor << 8) | patch) /* The version of this library build, as an integer. */ #define MT32EMU_CURRENT_VERSION_INT MT32EMU_VERSION_INT(MT32EMU_VERSION_MAJOR, MT32EMU_VERSION_MINOR, MT32EMU_VERSION_PATCH) /* Compares the current library version with the given version components. Intended for feature checks. */ #define MT32EMU_VERSION_ATLEAST(major, minor, patch) (MT32EMU_CURRENT_VERSION_INT >= MT32EMU_VERSION_INT(major, minor, patch)) /* Implements a simple version check that ensures full API compatibility of this library build * with the application requirements. The latter can be derived from the versions of used public symbols. * * Note: This macro is intended for a quick compile-time check. To ensure compatibility of an application * linked with a shared library, an automatic version check can be engaged with help of the build option * libmt32emu_WITH_VERSION_TAGGING. For a fine-grained feature checking in run-time, see functions * mt32emu_get_library_version_int and Synth::getLibraryVersionInt. */ #define MT32EMU_IS_COMPATIBLE(major, minor) (MT32EMU_VERSION_MAJOR == major && MT32EMU_VERSION_MINOR >= minor) /* Useful constants */ /* Sample rate to use in mixing. With the progress of development, we've found way too many thing dependent. * In order to achieve further advance in emulation accuracy, sample rate made fixed throughout the emulator, * except the emulation of analogue path. * The output from the synth is supposed to be resampled externally in order to convert to the desired sample rate. */ #define MT32EMU_SAMPLE_RATE 32000 /* The default value for the maximum number of partials playing simultaneously. */ #define MT32EMU_DEFAULT_MAX_PARTIALS 32 /* The higher this number, the more memory will be used, but the more samples can be processed in one run - * various parts of sample generation can be processed more efficiently in a single run. * A run's maximum length is that given to Synth::render(), so giving a value here higher than render() is ever * called with will give no gain (but simply waste the memory). * Note that this value does *not* in any way impose limitations on the length given to render(), and has no effect * on the generated audio. * This value must be >= 1. */ #define MT32EMU_MAX_SAMPLES_PER_RUN 4096 /* The default size of the internal MIDI event queue. * It holds the incoming MIDI events before the rendering engine actually processes them. * The main goal is to fairly emulate the real hardware behaviour which obviously * uses an internal MIDI event queue to gather incoming data as well as the delays * introduced by transferring data via the MIDI interface. * This also facilitates building of an external rendering loop * as the queue stores timestamped MIDI events. */ #define MT32EMU_DEFAULT_MIDI_EVENT_QUEUE_SIZE 1024 /* Maximum allowed size of MIDI parser input stream buffer. * Should suffice for any reasonable bulk dump SysEx, as the h/w units have only 32K of RAM onboard. */ #define MT32EMU_MAX_STREAM_BUFFER_SIZE 32768 /* This should correspond to the MIDI buffer size used in real h/w devices. * CM-32L control ROM is using 1000 bytes, and MT-32 GEN0 is using only 240 bytes (semi-confirmed by now). */ #define MT32EMU_SYSEX_BUFFER_SIZE 1000 #if defined(__cplusplus) && MT32EMU_API_TYPE != 1 namespace MT32Emu { const unsigned int SAMPLE_RATE = MT32EMU_SAMPLE_RATE; #undef MT32EMU_SAMPLE_RATE const unsigned int DEFAULT_MAX_PARTIALS = MT32EMU_DEFAULT_MAX_PARTIALS; #undef MT32EMU_DEFAULT_MAX_PARTIALS const unsigned int MAX_SAMPLES_PER_RUN = MT32EMU_MAX_SAMPLES_PER_RUN; #undef MT32EMU_MAX_SAMPLES_PER_RUN const unsigned int DEFAULT_MIDI_EVENT_QUEUE_SIZE = MT32EMU_DEFAULT_MIDI_EVENT_QUEUE_SIZE; #undef MT32EMU_DEFAULT_MIDI_EVENT_QUEUE_SIZE const unsigned int MAX_STREAM_BUFFER_SIZE = MT32EMU_MAX_STREAM_BUFFER_SIZE; #undef MT32EMU_MAX_STREAM_BUFFER_SIZE const unsigned int SYSEX_BUFFER_SIZE = MT32EMU_SYSEX_BUFFER_SIZE; #undef MT32EMU_SYSEX_BUFFER_SIZE } #endif /* #if defined(__cplusplus) && MT32EMU_API_TYPE != 1 */ #endif /* #ifndef MT32EMU_GLOBALS_H */ ```
/content/code_sandbox/src/sound/munt/globals.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,565
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #include <cstdlib> #include <cstring> #include "internals.h" #include "Display.h" #include "Part.h" #include "Structures.h" #include "Synth.h" namespace MT32Emu { /* Details on the emulation model. * * There are four display modes emulated: * - main (Master Volume), set upon startup after showing the welcoming banner; * - program change notification; * - custom display message received via a SysEx; * - error banner (e.g. the MIDI message checksum error). * Stuff like cursor blinking, patch selection mode, test mode, reaction to the front panel buttons, etc. is out of scope, as more * convenient UI/UX solutions are likely desired in applications, if at all. * * Note, despite the LAPC and CM devices come without the LCD and the front panel buttons, the control ROM does support these, * if connected to the main board. That's intended for running the test mode in a service centre, as documented. * * Within the aforementioned scope, the observable hardware behaviour differs noticeably, depending on the control ROM version. * At least three milestones can be identified: * - with MT-32 control ROM V1.06, custom messages are no longer shown unless the display is in the main (Master Volume) mode; * - with MT-32 control ROM V2.04, new function introduced - Display Reset yet added many other changes (taking the full SysEx * address into account when processing custom messages and special handling of the ASCII control characters are among them); * all the second-gen devices, including LAPC-I and CM-32L, behave very similarly; * - in the third-gen devices, the LCD support was partially cut down in the control ROM (basically, only the status * of the test mode, the ROM version and the checksum warnings are shown) - it's not fun, so this is NOT emulated. * * Features of the old-gen units. * - Any message with the first address byte 0x20 is processed and has some effect on the LCD. Messages with any other first * address byte (e.g. starting with 0x21 or 0x1F7F7F with an overlap) are not considered display-relevant. * - The second and the third address byte are largely irrelevant. Only presence of the second address byte makes an observable * difference, not the data within. * - Any string received in the custom message is normalised - all ASCII control characters are replaced with spaces, messages * shorter than 20 bytes are filled up with spaces to the full supported length. However, should a timbre name contain an ASCII * control character, it is displayed nevertheless, with zero meaning the end-of-string. * - Special message 0x20 (of just 1 address byte) shows the contents of the custom message buffer with either the last received * message or the empty buffer initially filled with spaces. See the note below about the priorities of the display modes. * - Messages containing two or three bytes with just the address are considered empty and fill the custom message buffer with * all spaces. The contents of the empty buffer is then shown, depending on the priority of the current display mode. * - Timing: custom messages are shown until an external event occurs like pressing a front panel button, receiving a new custom * message, program change, etc., and for indefinitely long otherwise. A program change notification is shown for about 1300 * milliseconds; when the timer expires, the display returns to the main mode (irrespective to the current display mode). * When an error occurs, the warning is shown for a limited time only, similarly to the program change notifications. * - The earlier old-gen devices treat all display modes with equal priority, except the main mode, which has a lower one. This * makes it possible e.g. to replace the error banner with a custom message or a program change notification, and so on. * A slightly improved behaviour is observed since the control ROM V1.06, when custom messages were de-prioritised. But still, * a program change beats an error banner even in the later models. * * Features of the second-gen units. * - All three bytes in SysEx address are now relevant. * - It is possible to replace individual characters in the custom message buffer which are addressed individually within * the range 0x200000-0x200013. * - Writes to higher addresses up to 0x20007F simply make the custom message buffer shown, with either the last received message * or the empty buffer initially filled with spaces. * - Writes to address 0x200100 trigger the Display Reset function which resets the display to the main (Master Volume) mode. * Similarly, showing an error banner is ended. If a program change notification is shown, this function does nothing, however. * - Writes to other addresses are not considered display-relevant, albeit writing a long string to lower addresses * (e.g. 0x1F7F7F) that overlaps the display range does result in updating and showing the custom display message. * - Writing a long string that covers the custom message buffer and address 0x200100 does both things, i.e. updates the buffer * and triggers the Display Reset function. * - While the display is not in a user interaction mode, custom messages and error banners have the highest display priority. * As long as these are shown, program change notifications are suppressed. The display only leaves this mode when the Display * Reset function is triggered or a front panel button is pressed. Notably, when the user enters the menu, all custom messages * are ignored, including the Display Reset command, but error banners are shown nevertheless. * - Sending cut down messages with partially specified address rather leads to undefined behaviour, except for a two-byte message * 0x20 0x00 which consistently shows the content of the custom message buffer (if priority permits). Otherwise, the behaviour * depends on the previously submitted address, e.g. the two-byte version of Display Reset may fail depending on the third byte * of the previous message. One-byte message 0x20 seemingly does Display Reset yet writes a zero character to a position derived * from the third byte of the preceding message. * * Some notes on the behaviour that is common to all hardware models. * - The display is DM2011 with LSI SED1200D-0A. This unit supports 4 user-programmable characters stored in CGRAM, all 4 get * loaded at startup. Character #0 is empty (with the cursor underline), #1 is the full block (used to mark active parts), * #2 is the pipe character (identical to #124 from the CGROM) and #3 is a variation on "down arrow". During normal operation, * those duplicated characters #2 and #124 are both used in different places and character #3 can only be made visible by adding * it either to a custom timbre name or a custom message. Character #0 is probably never shown as this code has special meaning * in the processing routines. For simplicity, we only use characters #124 and #1 in this model. * - When the main mode is active, the current state of the first 5 parts and the rhythm part is represented by replacing the part * symbol with the full rectangle character (#1 from the CGRAM). For voice parts, the rectangle is shown as long as at least one * partial is playing in a non-releasing phase on that part. For the rhythm part, the rectangle blinks briefly when a new NoteOn * message is received on that part (sometimes even when that actually produces no sound). */ static const char MASTER_VOLUME_WITH_DELIMITER[] = "| 0"; static const char MASTER_VOLUME_WITH_DELIMITER_AND_PREFIX[] = "|vol: 0"; static const Bit8u RHYTHM_PART_CODE = 'R'; static const Bit8u FIELD_DELIMITER = '|'; static const Bit8u ACTIVE_PART_INDICATOR = 1; static const Bit32u DISPLAYED_VOICE_PARTS_COUNT = 5; static const Bit32u SOUND_GROUP_NAME_WITH_DELIMITER_SIZE = 8; static const Bit32u MASTER_VOLUME_WITH_DELIMITER_SIZE = sizeof(MASTER_VOLUME_WITH_DELIMITER) - 1; static const Bit32u MASTER_VOLUME_WITH_DELIMITER_AND_PREFIX_SIZE = sizeof(MASTER_VOLUME_WITH_DELIMITER_AND_PREFIX) - 1; // This is the period to show those short blinks of MIDI MESSAGE LED and the rhythm part state. // Two related countdowns are initialised to 8 and touched each 10 milliseconds by the software timer 0 interrupt handler. static const Bit32u BLINK_TIME_MILLIS = 80; static const Bit32u BLINK_TIME_FRAMES = BLINK_TIME_MILLIS * SAMPLE_RATE / 1000; // This is based on the (free-running) TIMER1 overflow interrupt. The timer is 16-bit and clocked at 500KHz. // The message is displayed until 10 overflow interrupts occur. At the standard sample rate, it counts // precisely as 41943.04 frame times. static const Bit32u SCHEDULED_DISPLAY_MODE_RESET_FRAMES = 41943; /** * Copies up to lengthLimit characters from possibly null-terminated source to destination. The character of destination located * at the position of the null terminator (if any) in source and the rest of destination are left untouched. */ static void copyNullTerminatedString(Bit8u *destination, const Bit8u *source, Bit32u lengthLimit) { for (Bit32u i = 0; i < lengthLimit; i++) { Bit8u c = source[i]; if (c == 0) break; destination[i] = c; } } Display::Display(Synth &useSynth) : synth(useSynth), lastLEDState(), lcdDirty(), lcdUpdateSignalled(), lastRhythmPartState(), mode(Mode_STARTUP_MESSAGE), midiMessagePlayedSinceLastReset(), rhythmNotePlayedSinceLastReset() { scheduleDisplayReset(); const Bit8u *startupMessage = &synth.controlROMData[synth.controlROMMap->startupMessage]; memcpy(displayBuffer, startupMessage, LCD_TEXT_SIZE); memset(customMessageBuffer, ' ', LCD_TEXT_SIZE); memset(voicePartStates, 0, sizeof voicePartStates); } void Display::checkDisplayStateUpdated(bool &midiMessageLEDState, bool &midiMessageLEDUpdated, bool &lcdUpdated) { midiMessageLEDState = midiMessagePlayedSinceLastReset; maybeResetTimer(midiMessagePlayedSinceLastReset, midiMessageLEDResetTimestamp); // Note, the LED represents activity of the voice parts only. for (Bit32u partIndex = 0; !midiMessageLEDState && partIndex < 8; partIndex++) { midiMessageLEDState = voicePartStates[partIndex]; } midiMessageLEDUpdated = lastLEDState != midiMessageLEDState; lastLEDState = midiMessageLEDState; if (displayResetScheduled && shouldResetTimer(displayResetTimestamp)) setMainDisplayMode(); if (lastRhythmPartState != rhythmNotePlayedSinceLastReset && mode == Mode_MAIN) lcdDirty = true; lastRhythmPartState = rhythmNotePlayedSinceLastReset; maybeResetTimer(rhythmNotePlayedSinceLastReset, rhythmStateResetTimestamp); lcdUpdated = lcdDirty && !lcdUpdateSignalled; if (lcdUpdated) lcdUpdateSignalled = true; } bool Display::getDisplayState(char *targetBuffer, bool narrowLCD) { if (lcdUpdateSignalled) { lcdDirty = false; lcdUpdateSignalled = false; switch (mode) { case Mode_CUSTOM_MESSAGE: if (synth.isDisplayOldMT32Compatible()) { memcpy(displayBuffer, customMessageBuffer, LCD_TEXT_SIZE); } else { copyNullTerminatedString(displayBuffer, customMessageBuffer, LCD_TEXT_SIZE); } break; case Mode_ERROR_MESSAGE: { const Bit8u *sysexErrorMessage = &synth.controlROMData[synth.controlROMMap->sysexErrorMessage]; memcpy(displayBuffer, sysexErrorMessage, LCD_TEXT_SIZE); break; } case Mode_PROGRAM_CHANGE: { Bit8u *writePosition = displayBuffer; *writePosition++ = '1' + lastProgramChangePartIndex; *writePosition++ = FIELD_DELIMITER; if (narrowLCD) { writePosition[TIMBRE_NAME_SIZE] = 0; } else { memcpy(writePosition, lastProgramChangeSoundGroupName, SOUND_GROUP_NAME_WITH_DELIMITER_SIZE); writePosition += SOUND_GROUP_NAME_WITH_DELIMITER_SIZE; } copyNullTerminatedString(writePosition, lastProgramChangeTimbreName, TIMBRE_NAME_SIZE); break; } case Mode_MAIN: { Bit8u *writePosition = displayBuffer; for (Bit32u partIndex = 0; partIndex < DISPLAYED_VOICE_PARTS_COUNT; partIndex++) { *writePosition++ = voicePartStates[partIndex] ? ACTIVE_PART_INDICATOR : '1' + partIndex; *writePosition++ = ' '; } *writePosition++ = lastRhythmPartState ? ACTIVE_PART_INDICATOR : RHYTHM_PART_CODE; *writePosition++ = ' '; if (narrowLCD) { memcpy(writePosition, MASTER_VOLUME_WITH_DELIMITER, MASTER_VOLUME_WITH_DELIMITER_SIZE); writePosition += MASTER_VOLUME_WITH_DELIMITER_SIZE; *writePosition = 0; } else { memcpy(writePosition, MASTER_VOLUME_WITH_DELIMITER_AND_PREFIX, MASTER_VOLUME_WITH_DELIMITER_AND_PREFIX_SIZE); writePosition += MASTER_VOLUME_WITH_DELIMITER_AND_PREFIX_SIZE; } Bit32u masterVol = synth.mt32ram.system.masterVol; while (masterVol > 0) { std::div_t result = std::div(masterVol, 10); *--writePosition = '0' + result.rem; masterVol = result.quot; } break; } default: break; } } memcpy(targetBuffer, displayBuffer, LCD_TEXT_SIZE); targetBuffer[LCD_TEXT_SIZE] = 0; return lastLEDState; } void Display::setMainDisplayMode() { displayResetScheduled = false; mode = Mode_MAIN; lcdDirty = true; } void Display::midiMessagePlayed() { midiMessagePlayedSinceLastReset = true; midiMessageLEDResetTimestamp = synth.renderedSampleCount + BLINK_TIME_FRAMES; } void Display::rhythmNotePlayed() { rhythmNotePlayedSinceLastReset = true; rhythmStateResetTimestamp = synth.renderedSampleCount + BLINK_TIME_FRAMES; midiMessagePlayed(); if (synth.isDisplayOldMT32Compatible() && mode == Mode_CUSTOM_MESSAGE) setMainDisplayMode(); } void Display::voicePartStateChanged(Bit8u partIndex, bool activated) { if (mode == Mode_MAIN) lcdDirty = true; voicePartStates[partIndex] = activated; if (synth.isDisplayOldMT32Compatible() && mode == Mode_CUSTOM_MESSAGE) setMainDisplayMode(); } void Display::masterVolumeChanged() { if (mode == Mode_MAIN) lcdDirty = true; } void Display::programChanged(Bit8u partIndex) { if (!synth.isDisplayOldMT32Compatible() && (mode == Mode_CUSTOM_MESSAGE || mode == Mode_ERROR_MESSAGE)) return; mode = Mode_PROGRAM_CHANGE; lcdDirty = true; scheduleDisplayReset(); lastProgramChangePartIndex = partIndex; const Part *part = synth.getPart(partIndex); lastProgramChangeSoundGroupName = synth.getSoundGroupName(part); memcpy(lastProgramChangeTimbreName, part->getCurrentInstr(), TIMBRE_NAME_SIZE); } void Display::checksumErrorOccurred() { if (mode != Mode_ERROR_MESSAGE) { mode = Mode_ERROR_MESSAGE; lcdDirty = true; } if (synth.isDisplayOldMT32Compatible()) { scheduleDisplayReset(); } else { displayResetScheduled = false; } } bool Display::customDisplayMessageReceived(const Bit8u *message, Bit32u startIndex, Bit32u length) { if (synth.isDisplayOldMT32Compatible()) { for (Bit32u i = 0; i < LCD_TEXT_SIZE; i++) { Bit8u c = i < length ? message[i] : ' '; if (c < 32 || 127 < c) c = ' '; customMessageBuffer[i] = c; } if (!synth.controlROMFeatures->quirkDisplayCustomMessagePriority && (mode == Mode_PROGRAM_CHANGE || mode == Mode_ERROR_MESSAGE)) return false; // Note, real devices keep the display reset timer running. } else { if (startIndex > 0x80) return false; if (startIndex == 0x80) { if (mode != Mode_PROGRAM_CHANGE) setMainDisplayMode(); return false; } displayResetScheduled = false; if (startIndex < LCD_TEXT_SIZE) { if (length > LCD_TEXT_SIZE - startIndex) length = LCD_TEXT_SIZE - startIndex; memcpy(customMessageBuffer + startIndex, message, length); } } mode = Mode_CUSTOM_MESSAGE; lcdDirty = true; return true; } void Display::displayControlMessageReceived(const Bit8u *messageBytes, Bit32u length) { Bit8u emptyMessage[] = { 0 }; if (synth.isDisplayOldMT32Compatible()) { if (length == 1) { customDisplayMessageReceived(customMessageBuffer, 0, LCD_TEXT_SIZE); } else { customDisplayMessageReceived(emptyMessage, 0, 0); } } else { // Always assume the third byte to be zero for simplicity. if (length == 2) { customDisplayMessageReceived(emptyMessage, messageBytes[1] << 7, 0); } else if (length == 1) { customMessageBuffer[0] = 0; customDisplayMessageReceived(emptyMessage, 0x80, 0); } } } void Display::scheduleDisplayReset() { displayResetTimestamp = synth.renderedSampleCount + SCHEDULED_DISPLAY_MODE_RESET_FRAMES; displayResetScheduled = true; } bool Display::shouldResetTimer(Bit32u scheduledResetTimestamp) { // Deals with wrapping of renderedSampleCount. return Bit32s(scheduledResetTimestamp - synth.renderedSampleCount) < 0; } void Display::maybeResetTimer(bool &timerState, Bit32u scheduledResetTimestamp) { if (timerState && shouldResetTimer(scheduledResetTimestamp)) timerState = false; } } // namespace MT32Emu ```
/content/code_sandbox/src/sound/munt/Display.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
4,129
```objective-c * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #ifndef MT32EMU_PART_H #define MT32EMU_PART_H #include "globals.h" #include "internals.h" #include "Types.h" #include "Structures.h" namespace MT32Emu { class Poly; class Synth; class PolyList { private: Poly *firstPoly; Poly *lastPoly; public: PolyList(); bool isEmpty() const; Poly *getFirst() const; Poly *getLast() const; void prepend(Poly *poly); void append(Poly *poly); Poly *takeFirst(); void remove(Poly * const poly); }; class Part { private: // Direct pointer to sysex-addressable memory dedicated to this part (valid for parts 1-8, NULL for rhythm) TimbreParam *timbreTemp; // 0=Part 1, .. 7=Part 8, 8=Rhythm unsigned int partNum; bool holdpedal; unsigned int activePartialCount; unsigned int activeNonReleasingPolyCount; PatchCache patchCache[4]; PolyList activePolys; void setPatch(const PatchParam *patch); unsigned int midiKeyToKey(unsigned int midiKey); bool abortFirstPoly(unsigned int key); protected: Synth *synth; // Direct pointer into sysex-addressable memory MemParams::PatchTemp *patchTemp; char name[8]; // "Part 1".."Part 8", "Rhythm" char currentInstr[11]; // Values outside the valid range 0..100 imply no override. Bit8u volumeOverride; Bit8u modulation; Bit8u expression; Bit32s pitchBend; bool nrpn; Bit16u rpn; Bit16u pitchBenderRange; // (patchTemp->patch.benderRange * 683) at the time of the last MIDI program change or MIDI data entry. void backupCacheToPartials(PatchCache cache[4]); void cacheTimbre(PatchCache cache[4], const TimbreParam *timbre); void playPoly(const PatchCache cache[4], const MemParams::RhythmTemp *rhythmTemp, unsigned int midiKey, unsigned int key, unsigned int velocity); void stopNote(unsigned int key); const char *getName() const; public: Part(Synth *synth, unsigned int usePartNum); virtual ~Part(); void reset(); void setDataEntryMSB(unsigned char midiDataEntryMSB); void setNRPN(); void setRPNLSB(unsigned char midiRPNLSB); void setRPNMSB(unsigned char midiRPNMSB); void resetAllControllers(); virtual void noteOn(unsigned int midiKey, unsigned int velocity); virtual void noteOff(unsigned int midiKey); void allNotesOff(); void allSoundOff(); Bit8u getVolume() const; // Effective output level, valid range 0..100. void setVolume(unsigned int midiVolume); // Valid range 0..127, as defined for MIDI controller 7. Bit8u getVolumeOverride() const; void setVolumeOverride(Bit8u volumeOverride); Bit8u getModulation() const; void setModulation(unsigned int midiModulation); Bit8u getExpression() const; void setExpression(unsigned int midiExpression); virtual void setPan(unsigned int midiPan); Bit32s getPitchBend() const; void setBend(unsigned int midiBend); virtual void setProgram(unsigned int midiProgram); void setHoldPedal(bool pedalval); void stopPedalHold(); void updatePitchBenderRange(); virtual void refresh(); virtual void refreshTimbre(unsigned int absTimbreNum); virtual void setTimbre(TimbreParam *timbre); virtual unsigned int getAbsTimbreNum() const; const char *getCurrentInstr() const; const Poly *getFirstActivePoly() const; unsigned int getActivePartialCount() const; unsigned int getActiveNonReleasingPartialCount() const; Synth *getSynth() const; const MemParams::PatchTemp *getPatchTemp() const; // This should only be called by Poly void partialDeactivated(Poly *poly); virtual void polyStateChanged(PolyState oldState, PolyState newState); // These are rather specialised, and should probably only be used by PartialManager bool abortFirstPoly(PolyState polyState); // Abort the first poly in PolyState_HELD, or if none exists, the first active poly in any state. bool abortFirstPolyPreferHeld(); bool abortFirstPoly(); }; // class Part class RhythmPart: public Part { // Pointer to the area of the MT-32's memory dedicated to rhythm const MemParams::RhythmTemp *rhythmTemp; // This caches the timbres/settings in use by the rhythm part PatchCache drumCache[85][4]; public: RhythmPart(Synth *synth, unsigned int usePartNum); void refresh(); void refreshTimbre(unsigned int timbreNum); void setTimbre(TimbreParam *timbre); void noteOn(unsigned int key, unsigned int velocity); void noteOff(unsigned int midiKey); unsigned int getAbsTimbreNum() const; void setPan(unsigned int midiPan); void setProgram(unsigned int patchNum); void polyStateChanged(PolyState oldState, PolyState newState); }; } // namespace MT32Emu #endif // #ifndef MT32EMU_PART_H ```
/content/code_sandbox/src/sound/munt/Part.h
objective-c
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
1,226
```c++ * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see <path_to_url */ #include "internals.h" #include "TVF.h" #include "LA32Ramp.h" #include "Partial.h" #include "Poly.h" #include "Synth.h" #include "Tables.h" namespace MT32Emu { // Note that when entering nextPhase(), newPhase is set to phase + 1, and the descriptions/names below refer to // newPhase's value. enum { // When this is the target phase, level[0] is targeted within time[0] // Note that this phase is always set up in reset(), not nextPhase() PHASE_ATTACK = 1, // When this is the target phase, level[1] is targeted within time[1] PHASE_2 = 2, // When this is the target phase, level[2] is targeted within time[2] PHASE_3 = 3, // When this is the target phase, level[3] is targeted within time[3] PHASE_4 = 4, // When this is the target phase, immediately goes to PHASE_RELEASE unless the poly is set to sustain. // Otherwise level[3] is continued with increment 0 - no phase change will occur until some external influence (like pedal release) PHASE_SUSTAIN = 5, // 0 is targeted within time[4] (the time calculation is quite different from the other phases) PHASE_RELEASE = 6, // 0 is targeted with increment 0 (thus theoretically staying that way forever) PHASE_DONE = 7 }; static int calcBaseCutoff(const TimbreParam::PartialParam *partialParam, Bit32u basePitch, unsigned int key, bool quirkTVFBaseCutoffLimit) { // This table matches the values used by a real LAPC-I. static const Bit8s biasLevelToBiasMult[] = {85, 42, 21, 16, 10, 5, 2, 0, -2, -5, -10, -16, -21, -74, -85}; // These values represent unique options with no consistent pattern, so we have to use something like a table in any case. // The table entries, when divided by 21, match approximately what the manual claims: // -1, -1/2, -1/4, 0, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, 1, 5/4, 3/2, 2, s1, s2 // Note that the entry for 1/8 is rounded to 2 (from 1/8 * 21 = 2.625), which seems strangely inaccurate compared to the others. static const Bit8s keyfollowMult21[] = {-21, -10, -5, 0, 2, 5, 8, 10, 13, 16, 18, 21, 26, 32, 42, 21, 21}; int baseCutoff = keyfollowMult21[partialParam->tvf.keyfollow] - keyfollowMult21[partialParam->wg.pitchKeyfollow]; // baseCutoff range now: -63 to 63 baseCutoff *= int(key) - 60; // baseCutoff range now: -3024 to 3024 int biasPoint = partialParam->tvf.biasPoint; if ((biasPoint & 0x40) == 0) { // biasPoint range here: 0 to 63 int bias = biasPoint + 33 - key; // bias range here: -75 to 84 if (bias > 0) { bias = -bias; // bias range here: -1 to -84 baseCutoff += bias * biasLevelToBiasMult[partialParam->tvf.biasLevel]; // Calculation range: -7140 to 7140 // baseCutoff range now: -10164 to 10164 } } else { // biasPoint range here: 64 to 127 int bias = biasPoint - 31 - key; // bias range here: -75 to 84 if (bias < 0) { baseCutoff += bias * biasLevelToBiasMult[partialParam->tvf.biasLevel]; // Calculation range: -6375 to 6375 // baseCutoff range now: -9399 to 9399 } } // baseCutoff range now: -10164 to 10164 baseCutoff += ((partialParam->tvf.cutoff << 4) - 800); // baseCutoff range now: -10964 to 10964 if (baseCutoff >= 0) { // FIXME: Potentially bad if baseCutoff ends up below -2056? int pitchDeltaThing = (basePitch >> 4) + baseCutoff - 3584; if (pitchDeltaThing > 0) { baseCutoff -= pitchDeltaThing; } } else if (quirkTVFBaseCutoffLimit) { if (baseCutoff <= -0x400) { baseCutoff = -400; } } else { if (baseCutoff < -2048) { baseCutoff = -2048; } } baseCutoff += 2056; baseCutoff >>= 4; // PORTABILITY NOTE: Hmm... Depends whether it could've been below -2056, but maybe arithmetic shift assumed? if (baseCutoff > 255) { baseCutoff = 255; } return Bit8u(baseCutoff); } TVF::TVF(const Partial *usePartial, LA32Ramp *useCutoffModifierRamp) : partial(usePartial), cutoffModifierRamp(useCutoffModifierRamp) { } void TVF::startRamp(Bit8u newTarget, Bit8u newIncrement, int newPhase) { target = newTarget; phase = newPhase; cutoffModifierRamp->startRamp(newTarget, newIncrement); #if MT32EMU_MONITOR_TVF >= 1 partial->getSynth()->printDebug("[+%lu] [Partial %d] TVF,ramp,%x,%s%x,%d", partial->debugGetSampleNum(), partial->debugGetPartialNum(), newTarget, (newIncrement & 0x80) ? "-" : "+", (newIncrement & 0x7F), newPhase); #endif } void TVF::reset(const TimbreParam::PartialParam *newPartialParam, unsigned int basePitch) { partialParam = newPartialParam; unsigned int key = partial->getPoly()->getKey(); unsigned int velocity = partial->getPoly()->getVelocity(); const Tables *tables = &Tables::getInstance(); baseCutoff = calcBaseCutoff(newPartialParam, basePitch, key, partial->getSynth()->controlROMFeatures->quirkTVFBaseCutoffLimit); #if MT32EMU_MONITOR_TVF >= 1 partial->getSynth()->printDebug("[+%lu] [Partial %d] TVF,base,%d", partial->debugGetSampleNum(), partial->debugGetPartialNum(), baseCutoff); #endif int newLevelMult = velocity * newPartialParam->tvf.envVeloSensitivity; newLevelMult >>= 6; newLevelMult += 109 - newPartialParam->tvf.envVeloSensitivity; newLevelMult += (signed(key) - 60) >> (4 - newPartialParam->tvf.envDepthKeyfollow); if (newLevelMult < 0) { newLevelMult = 0; } newLevelMult *= newPartialParam->tvf.envDepth; newLevelMult >>= 6; if (newLevelMult > 255) { newLevelMult = 255; } levelMult = newLevelMult; if (newPartialParam->tvf.envTimeKeyfollow != 0) { keyTimeSubtraction = (signed(key) - 60) >> (5 - newPartialParam->tvf.envTimeKeyfollow); } else { keyTimeSubtraction = 0; } int newTarget = (newLevelMult * newPartialParam->tvf.envLevel[0]) >> 8; int envTimeSetting = newPartialParam->tvf.envTime[0] - keyTimeSubtraction; int newIncrement; if (envTimeSetting <= 0) { newIncrement = (0x80 | 127); } else { newIncrement = tables->envLogarithmicTime[newTarget] - envTimeSetting; if (newIncrement <= 0) { newIncrement = 1; } } cutoffModifierRamp->reset(); startRamp(newTarget, newIncrement, PHASE_2 - 1); } Bit8u TVF::getBaseCutoff() const { return baseCutoff; } void TVF::handleInterrupt() { nextPhase(); } void TVF::startDecay() { if (phase >= PHASE_RELEASE) { return; } if (partialParam->tvf.envTime[4] == 0) { startRamp(0, 1, PHASE_DONE - 1); } else { startRamp(0, -partialParam->tvf.envTime[4], PHASE_DONE - 1); } } void TVF::nextPhase() { const Tables *tables = &Tables::getInstance(); int newPhase = phase + 1; switch (newPhase) { case PHASE_DONE: startRamp(0, 0, newPhase); return; case PHASE_SUSTAIN: case PHASE_RELEASE: // FIXME: Afaict newPhase should never be PHASE_RELEASE here. And if it were, this is an odd way to handle it. if (!partial->getPoly()->canSustain()) { phase = newPhase; // FIXME: Correct? startDecay(); // FIXME: This should actually start decay even if phase is already 6. Does that matter? return; } startRamp((levelMult * partialParam->tvf.envLevel[3]) >> 8, 0, newPhase); return; default: break; } int envPointIndex = phase; int envTimeSetting = partialParam->tvf.envTime[envPointIndex] - keyTimeSubtraction; int newTarget = (levelMult * partialParam->tvf.envLevel[envPointIndex]) >> 8; int newIncrement; if (envTimeSetting > 0) { int targetDelta = newTarget - target; if (targetDelta == 0) { if (newTarget == 0) { targetDelta = 1; newTarget = 1; } else { targetDelta = -1; newTarget--; } } newIncrement = tables->envLogarithmicTime[targetDelta < 0 ? -targetDelta : targetDelta] - envTimeSetting; if (newIncrement <= 0) { newIncrement = 1; } if (targetDelta < 0) { newIncrement |= 0x80; } } else { newIncrement = newTarget >= target ? (0x80 | 127) : 127; } startRamp(newTarget, newIncrement, newPhase); } } // namespace MT32Emu ```
/content/code_sandbox/src/sound/munt/TVF.cpp
c++
2016-06-25T22:29:10
2024-08-16T19:09:21
86Box
86Box/86Box
2,616
2,585