=== lfsr/lfsr.txt
It's again been over a year since my last progress report. I've mostly been
working on figuring out the content of the YM2413 instrument ROM. For most
instruments I've found settings that are close (sometimes very close) to the
[1 hidden]
details wrong in the model that I'm using. I will (slowly) continue working on
this.
But this slow progress is sometimes discouraging. So for some more variety I
started to look at the YM2413 rhythm sounds. This is still very early work, but
I already found something interesting. (Spoiler: strictly speaking it's nothing
new, software YM2413 emulators already got this right, but it's nice to have it
confirmed anyway).
1) Rhythm sound measurements.
So far all my measurements on the real YM2413 captured (only) the output of
channel 0, outputted on the 'MO' analog output pin. But the rhythm sounds are
outputted on various other channel numbers (thus at different relative moments
in time) and on the 'RO' analog output pin.
To be able to measure rhythm sounds I had to make (small) adjustments to the
embedded software on the capturing board. Short summary: before the board
itself located channel 0 (in time), only sampled that channel and send it back
(over USB) to the host. Now I added a mode where the board samples 72x faster,
thus capturing all channel information (both MO and RO pins). And then the host
software must post-process this data to isolate the channel(s) it's interested
in.
Anyway, I was making some initial captures of the 5 rhythm sounds. And by
mistake I captured the 'snare drum' sound with a frequency setting of 0x0
instead of the recommended value of 0x550 (I forgot to update my program to
write the frequency settings to registers 0x17 and 0x27 instead of registers
0x16 and 0x26). This gave the following result:
Notice that the envelope is visible, but all samples have the same sign. If we
zoom in on the tail, where the envelope is fairly flat, we see this:
From what we've reverse-engineered so far this is an unexpected result: if the
frequency is zero, the phase should remain constant. But in this result the
phase is clearly toggling between two values.
2) Noise generator.
Compared to the melodic channels, the rhythm channels use one extra component
[1 hidden]
be the output of the noise generator?
Looking more closely at (120) consecutive samples in this signal gives the
following. I mapped sample value 255 to '0' and all other values to '1':
1, 1, 0, 1, 0, 1, 0, 0, 1, 0,
0, 1, 1, 1, 0, 1, 1, 0, 0, 1,
0, 0, 1, 1, 0, 1, 0, 1, 1, 1,
0, 1, 0, 1, 1, 1, 0, 0, 0, 0,
1, 0, 1, 1, 0, 1, 0, 0, 0, 1,
1, 0, 0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 1, 0, 1, 0, 0, 1, 0, 1,
1, 0, 0, 0, 0, 1, 1, 1, 0, 1,
1, 0, 0, 1, 0, 1, 0, 0, 0, 1,
0, 1, 1, 1, 0, 0, 0, 1, 1, 1,
[2 hidden]
This looks pretty random to me. A very common choice for a random generator is
a Linear Feedback Shift Register (LFSR). It's cheap to implement in hardware
and it has various nice mathematical properties. It's also used is several
other sound chips from the same time period (e.g. AY8910 and SN76489). So it's
likely that the YM2413 (and other chips in the Yamaha family) use it as well.
But how can we know for sure? The Berlekamp-Massey algorithm can help us here.
For a given sequence of 0's and 1's, the BM-algorithm constructs the cheapest
LFSR that fully reproduces that sequence.
[1 hidden]
If I feed the above sequence of 120 bits into the BM-algorithm I get the
following polynomial as result:
[1 hidden]
I'll explain what this means in the next section. If you're interested, you can
check my implementation of BM plus some more analysis code here:
[code: lfsr.cc]
If I sample the noise signal at other time offsets and apply BM, I each time
get the same result. Or if I take only the 60 first samples of the above
sequence, BM still gives the same result. Moreover the resulting LFSR can then
correctly predict the continuation (the last 60 samples) of that sequence.
I repeated this experiment on several different captures and several different
sample sequences, and I always get the same result. Of course given that the
input sequence is long enough (usually 30-40 samples is sufficient). This is a
strong indication that the YM2413 indeed uses a LFSR for it's noise generator,
and specifically the LFSR with this polynomial.
3) Linear Feedback Shift Register (LFSR)
But what is a LFSR exactly? You can find many details and references on
wikipedia. But below I'll also try to explain in an easier (less precise) way.
[url: https://en.wikipedia.org/wiki/Linear-feedback_shift_register]
Very brief the idea is the following:
- Remember the last N output bits.
- Pick a (fixed) selection from those bits (e.g. always pick the 5th- and
6th-to-last output bit).
- XOR the selected bits. The result is the new (pseudo-random) output bit.
This is illustrated in the following image:
For now only look at the 'Fibonacci-configuration'. You see a large rectangle
that contains 23 smaller cells. Each of these cells stores one bit. These
contain the last 23 output bits of the LFSR. Some of these outputs (bits 1, 8,
9 and 23 in this example) are XOR'ed together and the result is feed back to
cell 1. This is the newly generated random bit. When a new output bit is
generated, all existing bits shift one position to the right. So the last bit
becomes the 2nd-to last and so on.
Notice how the 'tap-positions' (1, 8, 9, 23) correspond to the exponents in the
[1 hidden]
mathematical reason why polynomials are used to describe LFSRs, but I won't go
into that. The '+ 1' at the end of the polynomial does not correspond to a
tap-position, it makes sense in the mathematical description (it's related to
the input), but we'll also ignore that here.
This was the 'Fibonacci-configuration' of a LFSR. This description is easy to
understand, but it's usually not how LFSRs are actually implemented. In
practice, both in hardware and in software, often the 'Galois-configuration' is
used instead. This configuration is shown in the lower part of the image.
Both configurations have the same number of shift register bits and the same
number of XOR operations. Only the arrangement differs. (Also note that the
numbering is swapped left-to-right). In the Galois configuration the XOR
operations are located 'in between' the shift register bits. Thus the shifted
bits get modified while they are 'in-flight'. It can mathematically be shown
that both configurations produce the exact same output sequence (in cell '1').
But the full internal state (including the values of the other bits in the
shift register) is NOT the same for both.
Some mathematical properties:
- When all bits in the shift register have value '0', the newly calculated
value will also be '0', thus the LFSR remains stuck in this state forever.
- This specific LFSR (23,9,8,1) has 'maximal length'. This means that, when
iterating this LFSR, every state (except for the all-0 state) is visited
exactly once before we return to the start-state. In this case we have 23
[1 hidden]
8388607 steps.
Applied to the YM2413 this means that:
- The hardware must make sure that after a reset the shift register does not
contain all '0' bits. Any other state is fine. So e.g. it's fine to set one
specific bit to '1' and leave all others uninitialized. Or initializing all
bits to '1' is fine as well of course. I don't know how the real YM2413
initializes the LFSR state.
- The random sequence repeats itself after about 8.3 million steps. Given the
YM2413 sample rate, that's over 160 seconds. That's more than sufficient.
I mentioned that 'Galois' is more often used than 'Fibonacci'. Why is that?
- Mathematically both are equivalent. So purely from a mathematical point of
view neither is better than the other.
- In hardware there's a difference in propagation delay:
- Fibonacci: to calculate the new output bit the signal has to propagate
through 3 XOR ports.
- Galois: the calculation for each bit passes through at most 1 XOR port.
So in theory a Galois LFSR circuit can be clocked higher compared to the
corresponding Fibonacci circuit. (Though I don't believe the LFSR is a
bottleneck in the full YM2413 circuit).
- In software there's a more substantial difference. The Galois variant can
exploit word-level parallelism and therefor typically requires less CPU
operations compared to the Fibonacci variant.
[12 hidden]
4) Comparison to existing hardware/software.
Let's check how the noise function is implemented in the existing YM2413
software emulators. In the openMSX src/sound/YM2413Burczynski.cc code you can
find this code snippet:
[2 hidden]
That's equivalent to the 'lfsr_step_galois()' function above (difference is
whether the XOR operation is applied before or after the shift operation). So
the software emulation was already using the correct LFSR. It's always nice to
confirm such things.
Can we also find this LFSR in the YM2413 die-shot? I already speculated about
this in an earlier article. Here's a (slightly extended) repetition of the
YM2413 die-shot.
In the upper-right corner, near the green colored 'PG' rectangle I marked in
white a shift-register with 14 (or 15?) bits. That's not enough for the full
LFSR (needs 23 bits) but it might correspond to the longest chunk of 14-bits in
the Galois-configuration of the LFSR (see above). The single bit registers
surrounded by XOR gates are hard to see in this die shot (at least for me). And
the remaining 7 bit shift register might be obscured by all the wiring in this
region. Also important: placing the LFSR close to the other circuitry that
handles phase calculations is very logical. All this gives me more confidence
that this white colored shift register is indeed related to the noise
generation.
5) Next steps
I'll probably continue with investigating the rhythm sounds. This article only
looked at the noise generator, but we still need to figure out how exactly this
noise is used to produce the rhythm sounds. After that I'll probably return to
the instrument ROM. As always, help would be appreciated.
UPDATE [2020/01/02]:
I was reading the Nuke.YKT emulation code
https://github.com/nukeykt/Nuked-OPLL/blob/master/opll.c
and was surprised that it uses a different (simpler) LFSR. I had a short
discussion about this with the author and he explained me the following:
In this article I'm assuming that the LFSR updates at a frequency of 49716Hz
(3.5MHz / 72). However in the actual hardware the LFSR update 18x faster: after
every operator instead of only once after all channels.
Nuke.YKT uses the formula
[2 hidden]
This corresponds to the LFSR with polynomial:
[1 hidden]
But if you iterate that formula 18 times you indeed get the LFSR we found in
this article:
[1 hidden]
So for a _single_ channel it doesn't matter whether you use LFSR-B once or
LFSR-A 18 times. But it does matter when _multiple_ channels use the LFSR.
More specially: both the 'High Hat' (HH) and the 'Snare Drum' (SD) rhythm
sounds use the LFSR (see "../rhythm/rhythm.md" for details). HH is calculated
first and 3x4 cycles later SD is calculated. The predictions only match the
measurements when:
- we use LFSR formula A
- repeat every 72 cycles:
* HH uses noise bit
* LFSR iterates 3 times
* SD uses noise bit
* LFSR iterates 15 times
Optimization note:
Naively switching to the 'real' LFSR formula for software emulation make the
calculation also 18x slower. Fortunately there are easy ways to extract both
the current noise-bit and the noise-bit-after-3-iterations from the same 23-bit
LFSR status. The general schema then becomes:
- use LFSR formula B
- repeat every 72 cycles:
* extract current noise bit for HH
* extract future noise bit 3 for SD
* iterate LFSR only once
Note however that there's also some interaction with test register bit 1 (see
Nuke.YKT code).
=== rhythm/rhythm.md
# YM2413 Rhythm mode
Progress is slow, but I have not abandoned this project.
In this post we'll look at the YM2413 percussion sounds.
## Introduction
Most info in this introduction can be found in or deduced from the YM2413 application manual. So feel free to skip this introduction.
The YM2413 can operate in two modes, selected via bit 5 in register 0x0E.
- Melodic mode (bit5 = 0).
- Rhythm mode (bit5 = 1).
In melodic mode there are 9 melody channels. In rhythm mode the 3 last melody channels are replaced with 5 (fixed) percussion sounds. More specifically these percussion sounds are:
- Bass drum (BD)
- Snare drum (SD)
- Tom tom (TOM)
- Top cymbal (TCY)
- High hat (HH)
In melodic mode each channel is controlled by 3 registers (0x1?, 0x2?, 0x3? with '?' 0-8). These select the frequency, volume, instrument and key-on/off. In rhythm mode the same set of 3x3 registers n
[1 hidden]
|:--------:|:------:|
[6 hidden]
So this only leaves registers 0x36-0x38 to control the percussion sounds.
These 'fixed' registers normally control the frequency and the key-on/off behavior of the melodic channels. It turns out that in rhythm mode these still control the frequency (of now 5 percussion soun
[1 hidden]
|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|
[1 hidden]
Detail: it turns out that in rhythm mode _both_ the on/off bits in register 0x0E and the bits in registers 0x26-0x28 are taken into account. It's as-if the 'corresponding' bits are OR'ed together. _TO
In melodic mode registers 0x36-0x38 control the volume and the instrument selection. In rhythm mode we need to control 5 (instead of 3) volumes and there's no need to select an instrument. Therefor th
[1 hidden]
|:------:|:-----:|:-----:|
[3 hidden]
A YM2413 channel consists out of two operators. In melodic mode these two operators acts like a carrier and a modulator. Thus in rhythm mode there are 6 operators available to generate 5 percussion so
[1 hidden]
|:----------:|:-----------:|
[5 hidden]
Notation: _mod6_ refers to the operator that in melodic mode is used as the modulator for channel 6 (with channels numbered from 0 to 8).
For the cases where a percussion sound only has a single operator, that operator always acts like a carrier.
Section "3-4 Operator (OP) and DAC" of the YM2413 application manual states: "Since the level of percussion sounds seems lower, when compared to music sounds, the same percussion sounds are output twi
[1 hidden]
|:------------:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|
[3 hidden]
In this table a _slot_ corresponds to a _time-slot_. Each slot is outputted in sequence over time in a cyclic way. Each slot lasts for 4 clock cycles. Thus when the YM2413 is clocked at the recommende
(After low-pass filtering) the effect of outputting a sound twice is the same as outputting it only once but with twice the amplitude, thus increasing the volume by 6dB.
I verified that the 2nd output of a percussion sound is _always_ identical to the first output (even when in between some parameter values have been changed). I also verified the positions of the orig
So the YM2413 outputs percussion sounds twice. There are two main options for how this can be implemented:
- Recompute that output.
- Remember the previous output.
[1 hidden]
## Percussion waveforms
Most of the above information could be derived from the YM2413 application manual (or sometimes from my previous reverse engineering work). In this section we'll look in more detail at how the percuss
[1 hidden]
I did not reverse engineer the percussion sounds in the same order as they are listed in the YM2413 application manual. Instead I ordered them from, what I thought, easier to more difficult.
### Base Drum (BD)
This sound uses two operators (mod6 + car6). The YM2413 software emulators generate this sound mostly the same as regular melodic sound channels. If this is correct then all we need to do is figure ou
Or in other words: if this is indeed how BD generation works, then it should be possible to perfectly replicate the BD waveform via the custom instrument settings. I verified that the following settin
[1 hidden]
|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|
[1 hidden]
I did an experiment where I used these settings for the custom instrument and then played 'simultaneously' the BD sound and custom sound (detail: I used fnum=0x1ff and block=0, this is lower than the
- The custom instrument seems 1 sample delayed compared to the BD sound.
- The custom instrument has a slightly higher peak amplitude.
The first point (1 sample delay) is fully expected: in my test program I write register 0x0E (set BD key-on) immediately followed by a write to register 0x25 (key-on custom instrument on channel 5). A
The second point (different peak amplitude) could be a consequence of the first. From previous reverse engineering work we know that the envelope is controlled by a _global counter_ (thus shared betwe
I tried many different alterations in these custom instrument settings, but the values shown in the above table gave the best result.
I also tried replicating the BD sound with the emulation model I've developed myself (as opposed to custom instrument captured on real hardware). This leads to the same conclusion: the above settings
### Tom tom (TOM)
[Visually](tom-1c0.png) the TOM waveform looks fairly simple: a simple sine wave that's varying in amplitude. We know that the YM2413 only uses a single operator to generate this wave, so this wavefor
A note about the frequency settings. The YM2413 application manual recommends fixed values for the registers 0x16-0x18 and 0x26-0x28. But that doesn't mean we have to stick to these recommendations fo
We still need to figure out the parameters for this (single) operator. A full instrument (2 operators) is configured via 8x8bit values, for a single operator we need _less_ than halve because the para
After some experimentation I found that these values work well:
[1 hidden]
|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|
[1 hidden]
'/' is "don't care"
Above we saw that TOM uses the 'mod8' operator-slot. So it makes sense that only the setting values that control modulator aspects are relevant. Those are the even registers. Register 2 is also even b
### Snare drum (SD)
[Visually](sd-300.png) the SD waveform is periodically positive and negative. When [zoomed in](sd-300-zoom.png) on the green rectangle, we see that the wave randomly varies between zero and maximum (p
Detail: this waveform was captured with fnum=0x100, block=1 instead of the recommended values fnum=0x150, block=2. This means that the recommended SD waveform alternates faster between positive and ne
#### Phase
In the [previous post](../lfsr/lfsr.txt) I had already reverse engineered the YM2413 pseudo-random generator (in fact it was reverse engineered via capturing this SD waveform (but with fnum=0)). The r
The existing YM2413 emulators agree on the general principle:
- Take the upper bit of the phase-counter and use this to toggle between positive and negative output.
- Take the noise output (single bit) and use this to toggle between zero and maximum amplitude.
Though they differ in detail:
- Burczynski: takes the phase of mod7, but envelope of car7
- Okazaki: takes both phase and envelope of car7.
*TODO design an experiment to test whether phase comes from mod7 or car7. I can't immediately think of something.*
Burczynski combines the information like this:
[1 hidden]
|:-------:|:----------:|:----------:|
[2 hidden]
And Okazaki combines it like this:
[1 hidden]
|:-------:|:----------:|:----------:|
[2 hidden]
But neither was an exact match for my measurements. After some trial and error I found that the following does work (2 possibilities):
[1 hidden]
|:-------:|:----------:|:----------:|-|-|-|-|-|-|:-------:|:----------:|:----------:|
[2 hidden]
Notice:
- Emulators output 4 distinct values +max, -max, +0, -0. But I don't observe the value -0 in my measurements. (Remember +0 and -0 result in a different output on the YM2413 DAC).
**UPDATE:** I measured again (after re-calibration) and now I _do_ see both +0 and -0.
- +max and -max appear diagonally from each other in the table (Burczynski got this detail right).
There are two possibilities (2 columns swapped) because I can't observe the value of the phase counter (*TODO design an experiment for this ... Maybe capture SD soon after melodic->rhythm mode transit
But I also can't directly observe the noise output bit, so how come there are not 4 possibilities (with also the rows swapped)? This is because a LFSR is asymmetric. The period of the YM2413 LFSR is 2
But still, how do we know that we got the LFSR right? Can't there be a different LFSR that does produce the inverted output? I have to admit that I didn't consider this when reverse-engineering the LF
x24 + x23 + x10 + x8 + x2 + 1
I strongly believe this is **not** the LFSR used in the YM2413 because:
- It's more expensive to implement in hardware compared to the other LFSR.
- It's not maximal length. Depending on the start-state it reproduces the original sequence, or the inverted sequence or it's stuck in a state where it constantly outputs 1, or (as always) the zero-st
#### Envelope
Apart from phase (+max, +0, -0, -max) we also have to reverse engineer the envelope. I found that the following gives a pretty good match. (Because SD is produced by 'car7', now only the odd registers
[1 hidden]
|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|
[1 hidden]
### Top cymbal (TCY)
Let's again start by looking at some images of a captured TCY waveform. The [first image](top-300-300.png) is a fully zoomed-out version. This clearly shows the ADSR phases in the envelope. For this c
When we [zoom in](top-300-300-zoom1.png) and [zoom in further](top-300-300-zoom2.png) the phase behavior becomes visible. Notice that (apart from the changing envelope) the amplitude only seems to tak
- The signal periodically stays constant or varies rapidly.
- Within such a period of rapid variation, there are smaller segments where the signal does remain constant.
#### Phase
So the phase only takes on two values. That means we *only* need to figure out a formula for this boolean result: positive or negative. Seems simple enough. *In reality this wasn't easy at all (for me
Let again look at what the existing YM2413 emulators do. (This is not how it's actually implemented in those emulators, I've rewritten the code to make comparisons with each other and with the final s
Common code:
[9 hidden]
Burczynski:
[4 hidden]
Okazaki:
[4 hidden]
Both formulas are very different, but at least they agree on which 5 bits influence the result. Notice how the phase-counters of *two different operators* (mod7 and car8) are used (the YM2413 applicat
Both formulas differ in the amplitude they output (0dB versus -3dB). But measurements show that at the end of the attack phase the signal does span the full -255..+255 range. That means that, for this
Measurements also show that indeed both the frequency settings for channel 7 (0x17, 0x27) and for channel 8 (0x18, 0x28) influence how the TCY waveform looks.
When a to-be-reverse-engineered output is influenced by two different inputs it helps to study the effect on the output by only letting one of the two inputs vary. In this specific case that can be do
This took me quite a long time, but in the end I figured out a simple formula that can explain all measurements. I did this by (in principle) constructing the 225 possible truth-
The solution I found was this:
[4 hidden]
Actually I did not find a single solution but 16 possible solutions:
[16 hidden]
I arbitrarily picked solution 8 because that one has the most elegant software implementation. Obviously the real YM2413 hardware only implements one of these formulas. Then why did my program find 16
TODO *would it be possible to design an experiment that can rule out (some of) these formulas? Perhaps by triggering an attack event in melodic mode (this resets the phase counters) and shortly after
#### Envelope
Again, in addition to the phase, we also need to know how the envelope behaves. The following values make the predicted envelope match pretty well with the measured envelope:
[1 hidden]
|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|
[1 hidden]
### High hat (HH)
As before, let's start with showing some [captured data](hh-L2000-100-300.png) (details: fnum7=0x100, block7=0, fnum8=0x100, block8=1, keyon-duration=2000). This seems like a fairly standard ADSR enve
#### Phase
The phase behavior of HH is the most complex all YM2413 rhythm waveforms. But it turns out to be a combination of stuff we've already reverse engineered for the SD and TCY waveforms. So after that it
[5 hidden]
Notice how the sub-expression for ```pp``` is the same as for TCY and how the ```pp``` and ```noise``` bits are combined in a very similar way as is done for SD.
#### Envelope
These values make the predicted envelope match the measurement:
[1 hidden]
|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|
[1 hidden]
## Other
- TODO move key-on OR behavior from introduction to here?
- TODO What exactly happens when we switch rhythm mode on/off while sounds are playing.
- TODO What with the sustain bit in regs 0x26-0x28?
[91 hidden]
## [2020/01/02] Update regarding noise bit (LFSR)
See also the [updated post about LFSR](../lfsr/lfsr.txt). Nuke.YKT uses a different LFSR formula than the one I had reverse engineerd. Turns out Nuke.YKT was right :-) But the difference is only obser
To double check Nuke's result I did the following test. I captured both HH and SD simultaneously and then (by manually inspecting the waveform) figured out what the value of the noise bit should have
[4 hidden]
- Initially I only figured out the first 30 bits (for both HH and SD).
- Immediately we see that HH and SD use a _different_ noise sequence.
- For now I'm still assuming the LFSR formula we initially found: x23 + x9 + x8 + x + 1.
- From the sequence of 30 HH bits it's possible to calculate the internal state of the LFSR (the state at the start of the sequence).
- We can do the same for the SD sequence. But of course that results in a _different_ start state.
- There doesn't seem to be any (easy) relation between these two start-states.
The Nuke.YKT code use a different, simpler, LFSR: x23 + x9 + 1. But instead of updating that LFSR only once per 72 clock cycles (once after all channels have been processed), the
- With that change we can again calculate the start state for the HH and SD sequences.
- Of course these are still different states.
- But now there _is_ an easy relation between the two: if we iterate the HH-state 3 times we end up in the SD-state.
And this result is very logical if you look back at the table that lists the order in which the sounds are calculated: HH gets calculated in slot 13 and SD in slot 16. So this difference of 3 slots ex
- As extra verification I used the new formula to predict 20 more noise bits (using a single LFSR for both HH and SD).
- I went back to the measurement and found that the next 20 samples matched perfectly with the predictions.