=== 20160210/adsr-transitions.txt It's been a while since my last post. Partly because I took a little break and partly because it took me quite a while to figure this stuff out. Even though, in retrospect, the underlying mechanism isn't too difficult at all. * Introduction In this post I'll investigate the transitions between the attack-decay-sustain- release states in the ADSR-envelope in more detail. Take a look at this image: This shows the attack- and decay-part of the envelope for a waveform with AR=6 and DR=3. Notice that in both the attack and the decay phases there are segments of two different widths, following the pattern 'wide narrow narrow, wide narrow narrow, ...'. Also notice that the segment between attack and decay, encircled in green (more specifically this is the first segment of the decay phase), still has a different width than either of the repeating widths in the attack or decay phase. The same is true for the first segment of the release phase, or for the first segment after any transition: almost always this segment has a different width than the surrounding segments. Before going into more detail, let's first repeat what we already know about the envelope generator from previous investigations: From the (4-bit) AR,DR,RR settings, the channel frequency and the KSR setting, we calculate a 6-bit effective rate. This rate determines how quickly the envelope changes. The upper 4 bits of this rate select a bit in the global counter (this [1 hidden] toggles (in other words, after a selectable power-of-2 number of samples), we execute the stuff in the next paragraph. The lower 2 bits of the effective rate select 1 of 4 possible sequences: 0: 0,1,0,1,0,1,0,1 (4 out of 8) 1: 0,1,0,1,1,1,0,1 (5 out of 8) 2: 0,1,1,1,0,1,1,1 (6 out of 8) 3: 0,1,1,1,1,1,1,1 (7 out of 8) From the global counter we take 3 bits, starting from the selected bit (previous paragraph) and going to the left. Or in other words: take the global counter, shift it down so that the selected bit is in position 0 and take the lower 3 bits of that number. The resulting value (between 0-7) selects a bit from the above sequence. Now only if that selected bit is '1' we advance to the next envelope level. (For very high rates, the rules are more complicated, but I'll refer to the previous posts for those details. They aren't important for this post). * Measurements If we repeat the experiment from the introduction multiple times, we see that the width of the first segments varies. This section is all about measuring that phenomena. If we zoom in on the segment encircled in green in the above image, we get this: As I annotated in this image, I measure the width of a segment from the first peak of the segment to the first peak of the next segment. These peaks are the oscillations of the basis waveform (a sine wave in this case). So choosing a higher frequency allows to more accurately measure the segment width. In the hope of making the analysis simpler, I started measuring with the simplest pattern: "0,1,0,1,0,1,0,1" (4-out-of-8). This gives each segment in steady-state the same width. So all wide segments instead of narrow-narrow-wide like in the above images. Though this 4-out-of-8 pattern is only used for notes with low frequency (first two octaves, the BLOCK channel setting). So that limits the maximum frequency, and thus also the measuring accuracy. If I combine the maximum frequency (0x3ff) with the maximum multiplication factor (car.ML=15), the distance between two peaks is about 37 samples. Only after I already made a large number of measurements, I realized I could improve the accuracy by also measuring the corresponding segment mirrored around the x-axis (roughly speaking: this segment is shifted half a period in time and has 'opposite' amplitude). This allows to derive an upper and lower bound for the actual segment width. In the first set of measurements I looked at the transition between attack and decay [1 hidden] - In the rows AR varies between 1 and 8. In the columns DR varies between 1 and 7. Though I did not exhaustively measure every combination. - Per cell I sorted the measured segment widths from small to big. Some values were obtained multiple times. Sometimes I annotated such duplicates (e.g. I put '2x' in front), sometimes I forgot to annotate the duplicates (IOW I made more measurements than shown in the table, but all uniquely observed values should be present). - For most segments I measured the upper and lower bound. Though for the earlier measurements I didn't do this yet. Those results are marked with '#'. - The results marked with '?' are likely errors (possibly I made some mistakes [1 hidden] in the next section. I also couldn't reproduce those results when I went back to them. (I could have cheated and left out those results ;-) - When AR is equal to DR, the first DR segment was often not visible. I mean normally, at the end of the attack phase, there is a segment with Y=0 and Y=511 (maximum amplitude), but not for this combination. So it's as-if when the condition to transition from the attack to the decay phase triggers, this also immediately triggers the condition to go from one level in the decay phase to the next level. OTOH sometimes there is a single peak visible at amplitude Y=0 or Y=511. These measurements are only accurate to 37 samples. This means very narrow peaks can easily be missed, so for now I wrote '1' for the segment with (and annotated it with '*'). But this needs more investigation. [1 hidden] =====++================+==============+==============+==============+==============+============+============ [1 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [2 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [8 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [4 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [11 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [13 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [11 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [6 hidden] Next I made similar measurements for the decay-to-release transition. But because taking these measurements takes a long time (30-60 seconds per data point) I limited myself to DR=4,5. That should be sufficient because the pattern [1 hidden] (AR/DR). Actually the only difference between the two sets occurs when the row-value is equal to the column-value (AR==DR or DR==RR). Before we had a segment of 0 or 1 sample, but now there's no exception when both rates are equal. It's as-if there's no transition at all. [1 hidden] =====++================+==============+==============+==============+==============+============+============ [5 hidden] -----++----------------+--------------+--------------+--------------+--------------+------------+------------ [4 hidden] * Finding a pattern in the measurements Next I tried to pick nice 'round' numbers that fall within the error margins of all the measurements. E.g. for the combination AR=4/DR=2 such numbers are '0x200, 0x600 and 0xe00'. That seems to match the formula '0x200 + n * 0x400'. And when I made more measurements for this combination, I eventually also found a segment with width 0xa00. This confirms that formula. So in the table below [1 hidden] Actually for all the combinations with DR < AR (or DR < RR) I found a similar pattern: all the observed segment widths seem to match this formula: first-segment-length = (2n + 1) * L [1 hidden] Note that L is also the required number of steps of the global counter described in the introduction. As already mentioned before, when AR == DR, the first segment was often not visible or only 1 sample wide. We still need to investigate this further. On the other hand DR == RR is nothing special. When 'DR > AR' (or RR > DR), the pattern is simple: [1 hidden] Note that this is half of all the later segments in the decay (or release) phase. Or in other words, the first segment is always a narrow segment while all later segments are wide (for these low frequencies (4-out-of-8 pattern) we only have wide segments in steady-state). [1 hidden] =====++===============+=============+=============+=============+=============+======+====== [1 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [1 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [2 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [4 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [4 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [4 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [4 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [5 hidden] =====++===============+=============+=============+=============+=============+======+====== [4 hidden] -----++---------------+-------------+-------------+-------------+-------------+------+------ [4 hidden] * A model to explain the measurements Let's again take AR=4/DR=2 as an example. - AR=4 means that every 0x200 steps there's an 'event' in the attack curve and [1 hidden] 0,1,0,1,0,1,0,1 pattern) we actually advance to the next AR level. - DR=2 means an event every 0x800 samples and with the 4-out-of-8 stuff, it means we advance a DR level every 0x1000 samples. Note that, in general, when the attack phase starts, the value of the global counter is random. In this example, when the attack phase ends we've just processed an AR event with a '1' in the 4-out-8 table and that occurs only every 0x400 samples. On the other hand, in this example, DR only effectively advances every 0x1000 samples. Not 0x10000 _starting_ from the end of attack, but when the global counter reaches the next multiple of 0x10000 (this is not [1 hidden] already have reached 0xc00, so the next multiple of 0x1000 is only 0x400 samples away, But it could also be 0x800, 0xc00 or 0x1000 samples till the next multiple of 0x10000. This already explains why, in this particular example, there are 4 possible initial segment lengths. It does not yet explain why these lengths are actually 0x200, 0x600, 0xa00, 0xe00 rather than 0x400, 0x800, 0xc00, 0x1000. That is '(2n+1) * L' rather than '2n * L'. To explain the '2n+1' stuff we need to take a more detailed look at the 0,1,0,1,0,1,0,1 stuff. I was writing a c++ model for this phenomena and then I realized that there are two possible (evenly-spaced) 4-out-of-8 sequences: - 0,1,0,1,0,1,0,1 -> gives 0x200 0x600 0xa00 0xe00 - 1,0,1,0,1,0,1,0 -> gives 0x400 0x800 0xc00 0x1000 One of these gives 0x200,0x600,0xa00,0xe00, the other gives 0x400,0x800,0xc00, 0x10000. We observed the first segment width, so the first sequence must be the correct one. Looking back this behavior is very logical, but it took me some time to realize this. For reference I've included the c++ code for the model, but I won't discuss it further: [source code: ar-dr.cc] * Extend to higher frequencies So far all measurements/models were done for frequency 0x3ff, those use the 4-out-of-8 '0,1,0,1,0,1,0,1' pattern. Higher frequencies use 5,6,7-out-of-8 patterns. Above I did a lot of (time consuming) measurements for various combinations of AR/DR/RR. But after I understood the underlying model I realized it's probably enough to limit myself to a single AR/DR combination. I choose AR=5/DR=2. - 5-out-of-8 I measured lengths: 0x100 0x300 0x400 0x500 0x700 0x900 0xb00 0xc00 0xd00 0xf00 Side note: I relatively quickly obtained 1,3,4,5,7,9,c,d,f. But it literally took over 50 attempts before I finally also observed length 0xb00, which I suspected should be there. (The c++ model confirms that some lengths are also more likely to be observed than others, and 0xb00 is a less likely length), Possible 5-out-of-8 patterns are: 1,1,0,1,0,1,0,1 0,1,1,1,0,1,0,1 0,1,0,1,1,1,0,1 <-- only this one matches the measurements 0,1,0,1,0,1,1,1 1,1,1,0,1,0,1,0 1,0,1,1,1,0,1,0 1,0,1,0,1,1,1,0 1,0,1,0,1,0,1,1 - 6-out-of-8 I measured these lengths: 0x100 0x200 0x300 0x500 0x600 0x700 0xa00 0xd00 0xe00 The model predicts 0x900 0xb00 0xf00 should also be present (with lower probability), but I didn't keep on measuring until I actually observed those values. The current measurements were already enough to exclude the other possible patterns (see below). Possible 6-out-of-8 patterns are: 1,1,0,1,1,1,0,1 0,1,1,1,0,1,1,1 <-- this one matches the measurements 1,1,1,0,1,1,1,0 1,0,1,1,1,0,1,1 - 7-out-of-8 I measured these lengths: 0x100 0x200 0x300 0x400 0x500 0x600 0x700 0xb00 0xc00 The values 0x{9,a,d,e,f}00 should also be present (only 0x800 and 0x1000 are missing). But these measurements can already exclude the other patterns below. Possible 7-out-of-8 patterns are: 0,1,1,1,1,1,1,1 <-- this one matches the measurements 1,1,0,1,1,1,1,1 1,1,1,1,0,1,1,1 1,1,1,1,1,1,0,1 1,0,1,1,1,1,1,1 1,1,1,0,1,1,1,1 1,1,1,1,1,0,1,1 1,1,1,1,1,1,1,0 * Conclusion We found that the model we had for the envelope steps already could explain the initial segment lengths after a AR->DR or DR->RR transition. And although I didn't measure this, I'm confident it will also correctly model the initial segment after a RR->DP or DP->AR transition. We also found the exact 4,5,6,7-out-of-8 sequences, namely 4-out-of-8: 0,1,0,1,0,1,0,1 5-out-of-8: 0,1,0,1,1,1,0,1 6-out-of-8: 0,1,1,1,0,1,1,1 7-out-of-8: 0,1,1,1,1,1,1,1 Side note: seq-5 OR'ed with seq-6 gives seq-7 OR'ing seq-4 with any other sequence simply give that other sequence This is not relevant for a software implementation, but it might give a clue to how the actual hardware circuit is structured (the 4 patterns are somewhat like a 2-bit binary counter). And if we look at the various emulator cores written by Jarek Burczynski (e.g. YM2413 but also YM2151 and YMF262), they contain exactly these sequences. So kudos to Jarek! So actually, if I hadn't done any of the investigations in this post. The emulation would (probably) have been exactly the same. But still, it's nice to better understand why this weird initial segment length stuff is happening. And even better it's nice to know that the sequences used by Jarek Burczynski are really the same sequences as used by the YM2413. === 20160716/small-signals.txt == Introduction == It's (again) been over half a year since my last post. I'm almost ashamed about how slowly this is progressing. But then better slow progress than abandoning the project. In previous posts we've already fairly well investigated isolated YM2413 components. Now it's time to start putting them together. Though instead of immediately building a model that includes everything we've learned, we'll build the model in smaller steps. This initial partial model will include: - Modulator and carrier operators connected together. - Feedback stuff in the modulator. - Channel volume - Key Scale Level There is partial support for: - Envelope level, the current level is taken into account, but the level does not change over time. - Similar for LFO AM: the level is taken into account, but it remains fixed in time. The most important missing pieces (that we did already investigate) are: - Evolving envelope level. - Evolving LFO AM level. - Selectable waveform (though I'll add it at the end of this post). - Channel frequency and LFO PM. == Initial partial model == The following c++ code is pieced together from code snippets from previous posts. If you (re)read those posts, there shouldn't be any surprises in this code. Remember that this code is more geared towards clarity or to how the hardware (likely) implements the algorithm rather than towards an efficient software implementation. [49 hidden] == Observation + 1st experiment == While creating this model I noticed that in this implementation the output of a channel never stops changing (even when assuming that the envelope level does go to a maximum over time). At the very least (when the envelope reaches a very high attenuation level) the signal keeps toggling between plus and minus zero. Let's measure how the real hardware behaves. I ran the following experiment: [2 hidden] block=0, fnum=256, volume=0 With these settings each sine period takes 1024 samples and every 4096 samples the envelope level increases by one. 1024 samples per sine was chosen because the sine-table has 1024 entries (see previous posts), thus we can see all details of the 'sine shape'. The slow envelope setting was chosen so that each level contains 4 repeated sines and we don't have to worry about transition effects (e.g. we can look at the 'middle two' sine waves). Here are the results. The first image shows the full signal. The second image zooms in on the tail of the signal (the rectangle marked in green in the 1st image). So eventually the real YM2413 signal stops changing. In the c++ model above this is not the case. Let's try to figure out when exactly it stops. From previous results we know that for envelope level 111 the signal varies between +/-2 (6 values, +2, +1, +0, -0, -1, -2). All later envelope levels only vary between +/-1 (4 values, +1, +0, -0, -1). So by only measuring the peak amplitude we cannot distinguish levels 112-127. However, in this experiment, every 4096 samples the envelope level increases by one, and it's relatively easily to locate level 111 (6 instead of 4 distinct output values). From this we can calculate that the signal stops changing at the point where we expect envelope level 124. So in a way we 'counted' the expected envelope level (count from 112 to 124 every 4096 samples). There's an alternative way to obtain the same result (which will also be useful later on in this post): we can look at the 'shape' of the 'sine' wave. The following image zooms in even more on the above signal. In green and red I've indicated to peak-widths of the signal at places where we respectively expect envelope level 112 (the first level with only 4 distinct output values) and envelope level 113 (4096 samples after the green peak). The widths of those peaks are respectively 342 and 332 samples (as expected a higher attenuation level results in a more narrow peak). The waveforms generated by the c++ model for the corresponding envelope levels have the same peak-widths. The following table gives the peak-width for more envelope levels (for all the levels where the output only varies between +/-1). For all these levels the measured width matches exactly with the predicted width by the model. [1 hidden] -------++-------+--------------------- [16 hidden] (*) So far we don't have any measurements yet for levels 124-127, they will come later. So this table allows to derive the envelope level for low-amplitude signals without having to know how the envelope evolves (increases by 1 every 4096 samples in this example) or without to need for a known reference point (level 111 is easy to locate in this example). == 2nd experiment, lower volume == In the above experiment the signal stops changing once the carrier envelope reaches level 124. At that point the signal remains constant at value +0 (not -0, nor alternating between +/-0, nor does it keep the sign of the last output value). But what if we attenuate the signal more, does the signal then sooner take on a constant value? The signal can be attenuated by: - Lowering the volume. - Using LFO amplitude modulation. - Using the Key Scale Level (KSL) feature. I tested all 3, all give the same result, so I'll only (or mostly) discuss the first alternative (lowering the volume) in more detail. The next experiment is the same as the previous one, except that the channel volume is now set to 8 (was 0, higher value means lower volume, 3dB per step). The result is visible in the following graph. Overall the shape of this graph is similar to the one from the previous experiment, but the volume is quite a bit lower (check the range on the y-axis). Before discussing this result in more detail, let's first clarify some terminology. While discussing the previous result I always talked about the envelope level (of the carrier). This corresponds with the 'envC' variable in the c++ model. But what we actually measure is the total attenuation level (the 'attC' variable in the model). Though we have: [1 hidden] and in the previous experiment vol=0, kslC=0, amC=0 so there was no difference between the envelope and the total attenuation level. But now we have vol=8, so I'll be more careful in distinguishing both. The first thing we see in this second experiment is that there is a very long tail where the signal only varies between +/-1. By measuring the total length of the signal (the part where it keeps changing) and dividing that by 4096 (the number of samples per envelope step), we obtain the value '124'. So again it seems that the output remains constant at +0 once the carrier envelope reaches level 124. If we zoom in on this tail (not shown), and compare the widths of the peaks with the values from the above table, we can derive the total attenuation level. This level starts at 112 and increases by one every 4096 samples until it reaches level 127 (so here we can measure the peek-widths for levels 124-127, and they indeed match the predictions). Beyond this point the total attenuation level remains at 127 (until the envelope level reaches 124). So far all experiments used a monotonically increasing total attenuation level. I also did an experiment with LFO AM (not shown). That results in a periodically increasing/decreasing attenuation level. Combined with a low volume it's possible to create a situation where the total attenuation level would periodically go below and above level 127. Though when actually measuring this, we again see that the total attenuation level never goes above 127. An intermediate conclusion: - It seems the total attenuation level is clipped at 127. - For envelope levels 124 or above (easily tested in hardware by (only) checking the top 5 bits) the output is constant +0. Extending the model (the carrier part) with this new information gives: [6 hidden] == 3rd experiment, modulator == The experiments so far only looked at the carrier part. But what about the modulator? We know that the same hardware is used (time multiplexed) for both the carrier and the modulator operator calculations. So it's very likely the clipping of the total attenuation level (at 127) is also done for the modulator (because it's an 'internal' part of the operator calculation). However making the output constant +0 is most easily implemented in hardware as a selection at the end: - The hardware always calculates the intermediate result. - At the end there's a mux that, depending on the envelope level, selects between this intermediate result or the constant value +0. Because this selection is done at the end, it could either be part of the (shared) operator calculation, or it could be on a hardware path that's specific for the carrier. Let's try to figure out which of these two alternatives was chosen by the YM2413 engineers. I designed an experiment with these parameters: [2 hidden] The changes compared to the previous experiments are: - After a (short) initial transition, the carrier envelope remains at a constant level 120. (In the previous experiment it gradually changed from 0 to 123). - The modulator envelope now changes from 0 to max, with 4096 samples per step. - In the previous experiment we wanted to suppress modulation, now we want it to be visible. So we set TL=0 (instead of TL=63). (Actually, with hindsight, the value of TL doesn't really matter). I'm not showing a graph of the full output because it doesn't teach us much: Roughly over the full graph, 570k samples, the signal varies between +/-1. More to the start (low modulator envelope attenuation levels) the signal varies more rapidly, more to the end (high modulator envelope attenuation levels) the signal is *almost* a sine wave (though of course a sine approximated with only integer values between +1 and -1). Instead I'll show a small part of this signal zoomed near the end: There are two transitions visible from +0 to -0, respectively encircled in green and in red. The following two graphs zoom-in on these two regions. In the green region there's a hiccup: the signal goes +0, -0, +0, -0. While in the red region the +0 to -0 transition is clean. What does this mean? To figure this out, let's go back to the c++ model. What does it predict for carrier envelope level 120 and modulator envelope level 127. The prediction is shown in this graph: Even for very high modulation attenuation levels (meaning little modulation) we still get a single 'hiccup' in the +0 to -0 transition. These hiccups are identical for modulation levels 123..127. If we instead keep the output of the modulator constant at +0 the predicted transition is clean. This means that in the green region there still is some modulation, but in the red region there's not. From the shape of the (green) signal we cannot determine the modulator envelope level, but the red region is located near sample 124x4096. So that's a strong indication that also the modulator output is kept at a constant value +0 once the modulator envelope level reaches value 124. == A bit of speculation == Why does the output already stop changing when level 124 is reached instead of going up to 127? One (minor?) reason could be that only testing 5 bits is a little cheaper in hardware compared to testing all 7 bits (though at the cost of some dynamic range). Another (more important?) reason might be that for very fast envelope rates the envelope increases by 2 (instead of just 1) every sample. Thus the envelope level can go 124 -> 126 -> 128 (or 125 -> 127 -> 129). But because the value is stored in only 7 bits, it actually goes 124 -> 126 -> 0. So value 127 is never reached and the 7-bit-stop-condition never triggers. This could be solved by adding clipping logic to the level-increment, but a cheaper solution is to simply not test the lowest bit. Though this doesn't explain why the hardware only tests 5 bits (instead of 6). Even more speculative: YM2413's big brother is the YM3812 (OPL2). In that chip the envelope level can also increase in steps of 4 per sample (there the envelope also has a higher resolution). In that case the above trick only works [1 hidden] from the YM3812 design? == Waveform details == The YM2413 has two different basic shapes for the waveform: 1) A (full) sine-wave. 2) Half a sine-wave; the negative part is replaced with zeros. I've already investigated this half-sine in previous posts. I had measured that indeed the positive part of the sine is kept and the negative part is replaced with zeros. But now I realize I've never checked whether those zeros are +0 or -0. With only small changes to the previous experiments, I could measure this: This only shows 3 distinct output values (ignoring measurement noise). These values are +1, +0 and -0 (remember that in my test-setup lower ADC values correspond to positive YM2413 values). When I measure the lengths of the segments with value -0, they are exactly 512 samples long (exactly half a period in this experiment). This means that for the half-sine waveform, the absolute value of the 2nd part is set to zero, but the sign still toggles. == Updated model == With the refinements discovered in this post, we can now update the (partial) c++ model. It looks like this: [67 hidden] == Next steps == In the next post(s) I'll probably complete this partial model with more and more features (features that have already been investigated in isolation). Though I don't know yet which feature(s) I'll add first. Possibly along the way I'll notice more corner cases that need further investigation. Once the model is reasonably complete we can start comparing it against settings from the instrument ROM.