1 /* FIXME: move ugly-ass legalese somewhere where it won't be seen
2 // by anyone other than lawyers. (/dev/null would be ideal but sadly
3 // we live in an imperfect world). */
4 /* Copyright (c) 2012/2013, Peter Barfuss
5 All rights reserved.
6 
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9 
10 1. Redistributions of source code must retain the above copyright notice, this
11    list of conditions and the following disclaimer.
12 2. Redistributions in binary form must reproduce the above copyright notice,
13    this list of conditions and the following disclaimer in the documentation
14    and/or other materials provided with the distribution.
15 
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
26 
27 #include <stdint.h>
28 #include <stdarg.h>
29 #include <math.h>
30 #include <assert.h>
31 #include "op.h"
32 #include "psg.h"
33 #include "opna.h"
34 
35 static const uint8_t notetab[128] =
36 {
37      0,  0,  0,  0,  0,  0,  0,  1,  2,  3,  3,  3,  3,  3,  3,  3,
38      4,  4,  4,  4,  4,  4,  4,  5,  6,  7,  7,  7,  7,  7,  7,  7,
39      8,  8,  8,  8,  8,  8,  8,  9, 10, 11, 11, 11, 11, 11, 11, 11,
40     12, 12, 12, 12, 12, 12, 12, 13, 14, 15, 15, 15, 15, 15, 15, 15,
41     16, 16, 16, 16, 16, 16, 16, 17, 18, 19, 19, 19, 19, 19, 19, 19,
42     20, 20, 20, 20, 20, 20, 20, 21, 22, 23, 23, 23, 23, 23, 23, 23,
43     24, 24, 24, 24, 24, 24, 24, 25, 26, 27, 27, 27, 27, 27, 27, 27,
44     28, 28, 28, 28, 28, 28, 28, 29, 30, 31, 31, 31, 31, 31, 31, 31,
45 };
46 
47 static const int8_t dttab[256] =
48 {
49       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
50       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
51       0,  0,  0,  0,  2,  2,  2,  2,  2,  2,  2,  2,  4,  4,  4,  4,
52       4,  6,  6,  6,  8,  8,  8, 10, 10, 12, 12, 14, 16, 16, 16, 16,
53       2,  2,  2,  2,  4,  4,  4,  4,  4,  6,  6,  6,  8,  8,  8, 10,
54      10, 12, 12, 14, 16, 16, 18, 20, 22, 24, 26, 28, 32, 32, 32, 32,
55       4,  4,  4,  4,  4,  6,  6,  6,  8,  8,  8, 10, 10, 12, 12, 14,
56      16, 16, 18, 20, 22, 24, 26, 28, 32, 34, 38, 40, 44, 44, 44, 44,
57       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
58       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
59       0,  0,  0,  0, -2, -2, -2, -2, -2, -2, -2, -2, -4, -4, -4, -4,
60      -4, -6, -6, -6, -8, -8, -8,-10,-10,-12,-12,-14,-16,-16,-16,-16,
61      -2, -2, -2, -2, -4, -4, -4, -4, -4, -6, -6, -6, -8, -8, -8,-10,
62     -10,-12,-12,-14,-16,-16,-18,-20,-22,-24,-26,-28,-32,-32,-32,-32,
63      -4, -4, -4, -4, -4, -6, -6, -6, -8, -8, -8,-10,-10,-12,-12,-14,
64     -16,-16,-18,-20,-22,-24,-26,-28,-32,-34,-38,-40,-44,-44,-44,-44,
65 };
66 
67 static const uint8_t gaintab[64] = {
68     0xff, 0xea, 0xd7, 0xc5, 0xb5, 0xa6, 0x98, 0x8b, 0x80, 0x75, 0x6c, 0x63, 0x5a, 0x53, 0x4c, 0x46,
69     0x40, 0x3b, 0x36, 0x31, 0x2d, 0x2a, 0x26, 0x23, 0x20, 0x1d, 0x1b, 0x19, 0x17, 0x15, 0x13, 0x12,
70     0x10, 0x0f, 0x0e, 0x0c, 0x0b, 0x0a, 0x0a, 0x09, 0x08, 0x07, 0x07, 0x06, 0x06, 0x05, 0x05, 0x04,
71     0x04, 0x04, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01,
72 };
73 
74 /* sinf(M_PI*(2*i+1)/1024.0f), i=0,...,511.
75 // Should make this twice as large (so a duplicate of the top 512, but with the other half of the
76 // interval [0,2*M_PI], therefore the negative of the first half), and then get rid of the
77 // silly hack in Sinetable(). However, I'm not actually sure which will use less gates on an FPGA,
78 // and there's really no speed difference on any machine newer than a 6502, probably. */
79 static const int16_t sinetable[1024] = {
80      1,  2,  4,  5,  7,  9,  10,  12,  13,  15,  16,  18,  20,  21,  23,  24,
81      26,  27,  29,  31,  32,  34,  35,  37,  38,  40,  41,  43,  45,  46,  48,  49,
82      51,  52,  54,  55,  57,  58,  60,  61,  63,  64,  66,  68,  69,  71,  72,  74,
83      75,  77,  78,  80,  81,  83,  84,  86,  87,  88,  90,  91,  93,  94,  96,  97,
84      99,  100,  102,  103,  104,  106,  107,  109,  110,  112,  113,  114,  116,  117,  119,  120,
85      121,  123,  124,  125,  127,  128,  130,  131,  132,  134,  135,  136,  138,  139,  140,  142,
86      143,  144,  145,  147,  148,  149,  151,  152,  153,  154,  156,  157,  158,  159,  161,  162,
87      163,  164,  165,  167,  168,  169,  170,  171,  173,  174,  175,  176,  177,  178,  179,  180,
88      182,  183,  184,  185,  186,  187,  188,  189,  190,  191,  192,  193,  194,  195,  196,  197,
89      198,  199,  200,  201,  202,  203,  204,  205,  206,  207,  208,  209,  210,  211,  212,  212,
90      213,  214,  215,  216,  217,  218,  218,  219,  220,  221,  222,  222,  223,  224,  225,  225,
91      226,  227,  228,  228,  229,  230,  230,  231,  232,  232,  233,  234,  234,  235,  236,  236,
92      237,  237,  238,  239,  239,  240,  240,  241,  241,  242,  242,  243,  243,  244,  244,  245,
93      245,  246,  246,  247,  247,  247,  248,  248,  249,  249,  249,  250,  250,  250,  251,  251,
94      251,  252,  252,  252,  252,  253,  253,  253,  253,  254,  254,  254,  254,  254,  255,  255,
95      255,  255,  255,  255,  255,  255,  256,  256,  256,  256,  256,  256,  256,  256,  256,  256,
96      256,  256,  256,  256,  256,  256,  256,  256,  256,  256,  255,  255,  255,  255,  255,  255,
97      255,  255,  254,  254,  254,  254,  254,  253,  253,  253,  253,  252,  252,  252,  252,  251,
98      251,  251,  250,  250,  250,  249,  249,  249,  248,  248,  247,  247,  247,  246,  246,  245,
99      245,  244,  244,  243,  243,  242,  242,  241,  241,  240,  240,  239,  239,  238,  237,  237,
100      236,  236,  235,  234,  234,  233,  232,  232,  231,  230,  230,  229,  228,  228,  227,  226,
101      225,  225,  224,  223,  222,  222,  221,  220,  219,  218,  218,  217,  216,  215,  214,  213,
102      212,  212,  211,  210,  209,  208,  207,  206,  205,  204,  203,  202,  201,  200,  199,  198,
103      197,  196,  195,  194,  193,  192,  191,  190,  189,  188,  187,  186,  185,  184,  183,  182,
104      180,  179,  178,  177,  176,  175,  174,  173,  171,  170,  169,  168,  167,  165,  164,  163,
105      162,  161,  159,  158,  157,  156,  154,  153,  152,  151,  149,  148,  147,  145,  144,  143,
106      142,  140,  139,  138,  136,  135,  134,  132,  131,  130,  128,  127,  125,  124,  123,  121,
107      120,  119,  117,  116,  114,  113,  112,  110,  109,  107,  106,  104,  103,  102,  100,  99,
108      97,  96,  94,  93,  91,  90,  88,  87,  86,  84,  83,  81,  80,  78,  77,  75,
109      74,  72,  71,  69,  68,  66,  64,  63,  61,  60,  58,  57,  55,  54,  52,  51,
110      49,  48,  46,  45,  43,  41,  40,  38,  37,  35,  34,  32,  31,  29,  27,  26,
111      24,  23,  21,  20,  18,  16,  15,  13,  12,  10,  9,  7,  6,  4,  2,  1,
112     -1, -2, -4, -5, -7, -9, -10, -12, -13, -15, -16, -18, -20, -21, -23, -24,
113     -26, -27, -29, -31, -32, -34, -35, -37, -38, -40, -41, -43, -45, -46, -48, -49,
114     -51, -52, -54, -55, -57, -58, -60, -61, -63, -64, -66, -68, -69, -71, -72, -74,
115     -75, -77, -78, -80, -81, -83, -84, -86, -87, -88, -90, -91, -93, -94, -96, -97,
116     -99, -100, -102, -103, -104, -106, -107, -109, -110, -112, -113, -114, -116, -117, -119, -120,
117     -121, -123, -124, -125, -127, -128, -130, -131, -132, -134, -135, -136, -138, -139, -140, -142,
118     -143, -144, -145, -147, -148, -149, -151, -152, -153, -154, -156, -157, -158, -159, -161, -162,
119     -163, -164, -165, -167, -168, -169, -170, -171, -173, -174, -175, -176, -177, -178, -179, -180,
120     -182, -183, -184, -185, -186, -187, -188, -189, -190, -191, -192, -193, -194, -195, -196, -197,
121     -198, -199, -200, -201, -202, -203, -204, -205, -206, -207, -208, -209, -210, -211, -212, -212,
122     -213, -214, -215, -216, -217, -218, -218, -219, -220, -221, -222, -222, -223, -224, -225, -225,
123     -226, -227, -228, -228, -229, -230, -230, -231, -232, -232, -233, -234, -234, -235, -236, -236,
124     -237, -237, -238, -239, -239, -240, -240, -241, -241, -242, -242, -243, -243, -244, -244, -245,
125     -245, -246, -246, -247, -247, -247, -248, -248, -249, -249, -249, -250, -250, -250, -251, -251,
126     -251, -252, -252, -252, -252, -253, -253, -253, -253, -254, -254, -254, -254, -254, -255, -255,
127     -255, -255, -255, -255, -255, -255, -256, -256, -256, -256, -256, -256, -256, -256, -256, -256,
128     -256, -256, -256, -256, -256, -256, -256, -256, -256, -256, -255, -255, -255, -255, -255, -255,
129     -255, -255, -254, -254, -254, -254, -254, -253, -253, -253, -253, -252, -252, -252, -252, -251,
130     -251, -251, -250, -250, -250, -249, -249, -249, -248, -248, -247, -247, -247, -246, -246, -245,
131     -245, -244, -244, -243, -243, -242, -242, -241, -241, -240, -240, -239, -239, -238, -237, -237,
132     -236, -236, -235, -234, -234, -233, -232, -232, -231, -230, -230, -229, -228, -228, -227, -226,
133     -225, -225, -224, -223, -222, -222, -221, -220, -219, -218, -218, -217, -216, -215, -214, -213,
134     -212, -212, -211, -210, -209, -208, -207, -206, -205, -204, -203, -202, -201, -200, -199, -198,
135     -197, -196, -195, -194, -193, -192, -191, -190, -189, -188, -187, -186, -185, -184, -183, -182,
136     -180, -179, -178, -177, -176, -175, -174, -173, -171, -170, -169, -168, -167, -165, -164, -163,
137     -162, -161, -159, -158, -157, -156, -154, -153, -152, -151, -149, -148, -147, -145, -144, -143,
138     -142, -140, -139, -138, -136, -135, -134, -132, -131, -130, -128, -127, -125, -124, -123, -121,
139     -120, -119, -117, -116, -114, -113, -112, -110, -109, -107, -106, -104, -103, -102, -100, -99,
140     -97, -96, -94, -93, -91, -90, -88, -87, -86, -84, -83, -81, -80, -78, -77, -75,
141     -74, -72, -71, -69, -68, -66, -64, -63, -61, -60, -58, -57, -55, -54, -52, -51,
142     -49, -48, -46, -45, -43, -41, -40, -38, -37, -35, -34, -32, -31, -29, -27, -26,
143     -24, -23, -21, -20, -18, -16, -15, -13, -12, -10, -9, -7, -6, -4, -2, -1,
144 };
145 
146 static const uint8_t cltab[512] = {
147    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
148    0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6, 0xd6,
149    0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4, 0xb4,
150    0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97, 0x97,
151    0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
152    0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b, 0x6b,
153    0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,
154    0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b, 0x4b,
155    0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x3f,
156    0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
157    0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d,
158    0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25, 0x25,
159    0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f,
160    0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a,
161    0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16,
162    0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
163    0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f,
164    0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d,
165    0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
166    0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,
167    0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
168    0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
169    0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
170    0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
171    0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
172    0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
173    0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
174    0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
175    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
176    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
177    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
178    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
179 };
180 
181 static const uint8_t fbtab[8] = { 31, 7, 6, 5, 4, 3, 2, 1 };
182 
183 /* Amplitude/Phase modulation tables. */
184 static const uint8_t amt[4] = { 29, 4, 2, 1 }; /* OPNA */
185 
186 /* libOPNMIDI: pan law table */
187 static const uint16_t panlawtable[] = {
188   65535, 65529, 65514, 65489, 65454, 65409, 65354, 65289,
189   65214, 65129, 65034, 64929, 64814, 64689, 64554, 64410,
190   64255, 64091, 63917, 63733, 63540, 63336, 63123, 62901,
191   62668, 62426, 62175, 61914, 61644, 61364, 61075, 60776,
192   60468, 60151, 59825, 59489, 59145, 58791, 58428, 58057,
193   57676, 57287, 56889, 56482, 56067, 55643, 55211, 54770,
194   54320, 53863, 53397, 52923, 52441, 51951, 51453, 50947,
195   50433, 49912, 49383, 48846, 48302, 47750, 47191,
196   46340, /* Center left */
197   46340, /* Center right */
198   45472, 44885, 44291, 43690, 43083, 42469, 41848, 41221,
199   40588, 39948, 39303, 38651, 37994, 37330, 36661, 35986,
200   35306, 34621, 33930, 33234, 32533, 31827, 31116, 30400,
201   29680, 28955, 28225, 27492, 26754, 26012, 25266, 24516,
202   23762, 23005, 22244, 21480, 20713, 19942, 19169, 18392,
203   17613, 16831, 16046, 15259, 14469, 13678, 12884, 12088,
204   11291, 10492, 9691, 8888, 8085, 7280, 6473, 5666,
205   4858, 4050, 3240, 2431, 1620, 810, 0
206 };
207 
208 /* --------------------------------------------------------------------------- */
LFO(OPNA * opna)209 static inline void LFO(OPNA *opna)
210 {
211     uint8_t c = (opna->lfocount >> FM_LFOCBITS) & 0xff;
212     opna->lfocount += opna->lfodcount;
213     if (c < 0x80)       opna->aml = (c << 1);
214     else                opna->aml = ~(c << 1);
215 }
216 
217 /* ---------------------------------------------------------------------------
218 // Magic. No, really.
219 // In reality this just initialises some tables used by everything else,
220 // that are dependent on both the chip clock and the "DAC" samplerate.
221 // The hilarious thing though is that this is really the only place where
222 // the chip clock value gets actually *used*, and even then it's indirectly
223 // via the ratio parameter.
224 */
MakeTimeTable(OPNA * opna,uint32_t ratio)225 static void MakeTimeTable(OPNA *opna, uint32_t ratio)
226 {
227     int h, l;
228     uint32_t *ratetable = opna->ratetable;
229 
230     if (ratio != opna->currentratio)
231     {
232         opna->currentratio = ratio;
233 
234         /* EG */
235         for (h=1; h<16; h++)
236         {
237             for (l=0; l<4; l++)
238             {
239                 int m = h == 15 ? 8 : l+4;
240                 ratetable[h*4+l] =
241                     ((ratio << (FM_EGBITS - 3 - FM_RATIOBITS)) << Min(h, 11)) * m;
242             }
243         }
244         ratetable[0] = ratetable[1] = ratetable[2] = ratetable[3] = 0;
245         ratetable[5] = ratetable[4],  ratetable[7] = ratetable[6];
246     }
247 }
248 
SetEGRate(FMOperator * op,uint32_t r)249 static void SetEGRate(FMOperator *op, uint32_t r)
250 {
251     Channel4 *ch = op->master;
252     OPNA *opna = ch->master;
253     op->egstepd = opna->ratetable[r];
254     op->egtransa = Limit(15 - (r>>2), 4, 1);
255     op->egtransd = 16 >> op->egtransa;
256 }
257 
258 /* Standard operator init routine. Zeros out some more stuff
259 // than OperatorReset() does, then calls OperatorReset().
260 */
OperatorInit(Channel4 * ch4,FMOperator * op)261 void OperatorInit(Channel4 *ch4, FMOperator *op)
262 {
263     op->master = ch4;
264 
265     /* EG Part */
266     op->ar = op->dr = op->sr = op->rr = op->ksr = 0;
267     op->ams = 0;
268     op->mute = 0;
269     op->keyon = 0;
270 
271     /* PG Part */
272     op->multiple = 0;
273     op->detune = 0;
274 
275     /* LFO */
276     op->ms = 0;
277 
278     OperatorReset(op);
279 }
280 
281 /* Standard operator reset routine. Init EG/PG to defaults,
282 // clear any stored samples, then force a reinit of EG/PG
283 // in OperatorPrepare() below by setting paramchanged to 1.
284 */
OperatorReset(FMOperator * op)285 void OperatorReset(FMOperator *op)
286 {
287     /* EG part */
288     op->tl = op->tll = 127;
289     op->eglevel = 0xff;
290     op->eglvnext = 0x100;
291     SetEGRate(op, 0);
292     op->phase = off;
293     op->egstep = 0;
294 
295     /* PG part */
296     op->pgcount = 0;
297 
298     /* OP part */
299     op->out = op->out2 = 0;
300     op->paramchanged = 1;
301 }
302 
303 /* Init EG, PG.
304 // PG init is trivial, simply set pgdcount (phase counter increment)
305 // based on multiple, detune and bn.
306 // See Pages 24-26 of the OPNA manual for details.
307 // EG init is your standard ADSR state machine. Should (hopefully!)
308 // be self-explanatory, especially if you've ever seen a software implementation
309 // of ADSR before (seriously, they're all the damn same).
310 */
OperatorPrepare(FMOperator * op)311 void OperatorPrepare(FMOperator *op)
312 {
313     Channel4 *ch = op->master;
314     OPNA *opna = ch->master;
315 
316     if (op->paramchanged)
317     {
318         uint8_t l = ((op->multiple) ? 2*op->multiple : 1);
319         op->paramchanged = 0;
320         /*  PG Part */
321         op->pgdcount = (op->dp + dttab[op->detune + op->bn]) * (uint32_t)(l * opna->rr);
322         op->pgdcountl = op->pgdcount >> 11;
323 
324         /* EG Part */
325         op->ksr = op->bn >> (3-op->ks);
326 
327         switch (op->phase)
328         {
329         case attack:
330             SetEGRate(op, op->ar ? Min(63, op->ar+op->ksr) : 0);
331             break;
332         case decay:
333             SetEGRate(op, op->dr ? Min(63, op->dr+op->ksr) : 0);
334             op->eglvnext = op->sl * 8;
335             break;
336         case sustain:
337             SetEGRate(op, op->sr ? Min(63, op->sr+op->ksr) : 0);
338             break;
339         case release:
340             SetEGRate(op, Min(63, op->rr+op->ksr));
341             break;
342         case next: /* temporal */
343             break;
344         case off:  /* temporal */
345             break;
346         }
347         /* LFO */
348         op->ams = (op->amon ? (op->ms >> 4) & 3 : 0);
349     }
350 }
351 
352 /* FIXME: Rename. "Phase" here refers to ADSR DFA state,
353 // not PG/sine table phase. Also, yeah, this does the
354 // ADSR DFA state transitions.
355 */
ShiftPhase(FMOperator * op,EGPhase nextphase)356 static void ShiftPhase(FMOperator *op, EGPhase nextphase)
357 {
358     switch (nextphase)
359     {
360     case attack:        /* Attack Phase */
361         op->tl = op->tll;
362         if ((op->ar+op->ksr) < 62) {
363             SetEGRate(op, op->ar ? Min(63, op->ar+op->ksr) : 0);
364             op->phase = attack;
365             break;
366         }
367         /* fall through */
368     case decay:         /* Decay Phase */
369         if (op->sl) {
370             op->eglevel = 0;
371             op->eglvnext = op->sl*8;
372             SetEGRate(op, op->dr ? Min(63, op->dr+op->ksr) : 0);
373             op->phase = decay;
374             break;
375         }
376         /* fall through */
377     case sustain:       /* Sustain Phase */
378         op->eglevel = op->sl*8;
379         op->eglvnext = 0x100;
380         SetEGRate(op, op->sr ? Min(63, op->sr+op->ksr) : 0);
381         op->phase = sustain;
382         break;
383 
384     case release:       /* Release Phase */
385         if (op->phase == attack || (op->eglevel < 0x100/* && phase != off*/)) {
386             op->eglvnext = 0x100;
387             SetEGRate(op, Min(63, op->rr+op->ksr));
388             op->phase = release;
389             break;
390         }
391         /* fall through */
392     case off:           /* off */
393     default:
394         op->eglevel = 0xff;
395         op->eglvnext = 0x100;
396         SetEGRate(op, 0);
397         op->phase = off;
398         break;
399     }
400 }
401 
402 /*  Block/F-Num */
SetFNum(FMOperator * op,uint32_t f)403 static inline void SetFNum(FMOperator *op, uint32_t f)
404 {
405     op->dp = (f & 2047) << ((f >> 11) & 7);
406     op->bn = notetab[(f >> 7) & 127];
407     op->paramchanged = 1;
408 }
409 
410 /* Clock the EG for one operator.
411 // Essentially just a call to ShiftPhase,
412 // but decrements the output EG level if starting
413 // from the attack phase, otherwise incrementing it.
414 // Should probably integrate the special case for attack
415 // from ShiftPhase() directly into here at some point. */
EGCalc(FMOperator * op)416 void EGCalc(FMOperator *op)
417 {
418     op->egstep += 3L << (11 + FM_EGBITS);
419     if (op->phase == attack)
420     {
421         op->eglevel -= 1 + (op->eglevel >> op->egtransa);
422         if (op->eglevel <= 0)
423             ShiftPhase(op, decay);
424     }
425     else
426     {
427         op->eglevel += op->egtransd;
428         if (op->eglevel >= op->eglvnext)
429             ShiftPhase(op, (EGPhase)(op->phase+1));
430     }
431 }
432 
433 /* KeyOn, hopefully obvious. */
KeyOn(FMOperator * op)434 static void KeyOn(FMOperator *op)
435 {
436     /*if (!op->keyon && ((op->ar = 31) || (op->ar == 62))) {*/
437     if (!op->keyon) {
438         op->keyon = 1;
439         if (!op->sl) {
440             ShiftPhase(op, sustain);
441             op->out = op->out2 = 0;
442             op->pgcount = 0;
443         } else {
444             if (op->phase == off || op->phase == release) {
445                 ShiftPhase(op, attack);
446                 op->out = op->out2 = 0;
447                 op->pgcount = 0;
448             }
449         }
450     }
451 }
452 
453 /* KeyOff, hopefully obvious. */
KeyOff(FMOperator * op)454 static void KeyOff(FMOperator *op)
455 {
456     if (op->keyon) {
457         op->keyon = 0;
458         ShiftPhase(op, release);
459     }
460 }
461 
462 /* PG uses 9 bits, with the table itsself using another 10 bits.
463 // The top bits are the actually relevant ones, given that the PG increment will basically set
464 // the lowest few bits to nonsense.
465 // The hack there that checks for bit 10 in the right place and if yes, does some strange xor magic
466 // makes the value of Sine() negative if we're in the top half of the [0,2*M_PI] interval.
467 // It is, of course, one/two's complement specific, but I have yet to hear of an integer arithmetic implementation
468 // on any modern machine that isn't at least one of those two. (In fact, I think they're all two's complement, even). */
469 /*#define Sine(s) sinetable[((s) >> (20+FM_PGBITS-FM_OPSINBITS))&(FM_OPSINENTS/2-1)]^(-(((s) & 0x10000000) >> 27))*/
470 #define Sine(s) sinetable[((s) >> (20+FM_PGBITS-FM_OPSINBITS))&(FM_OPSINENTS-1)]
471 
LogToLin(uint32_t x)472 static inline uint32_t LogToLin(uint32_t x) {
473     if(x >= 0xff) {
474         return 0;
475     }
476     return cltab[x];
477 }
478 
479 /*  PG clock routine.
480 //  Does this really need to be in its own function anymore?
481 //  It's literally just a trivial increment of a counter now, nothing more.
482 //  Its output, btw, is 2^(20+PGBITS) / cycle, with PGBITS=9 in this implementation. */
PGCalc(FMOperator * op)483 static inline uint32_t PGCalc(FMOperator *op)
484 {
485     uint32_t ret = op->pgcount;
486     op->pgcount += op->pgdcount;
487     return ret;
488 }
489 
490 /* Clock one FM operator. Does a lookup in the sine table
491 // for the waveform to output, possibly frequency-modulating
492 // that with the contents of in, then clocks the Phase Generator
493 // for that operator, stores the output sample and returns.
494 // Should probably integrate PGCalc() into this function,
495 // at some point at least. */
Calc(FMOperator * op,int32_t in)496 static inline int32_t Calc(FMOperator *op, int32_t in)
497 {
498     int32_t tmp = Sine(op->pgcount + (in << 7));
499     op->out = op->egout*tmp;
500     PGCalc(op);
501     return op->out;
502 }
503 
504 /* Clock operator 0. OP0 is special as it does not take an input from
505 // another operator, rather it can frequency-modulate itsself via the
506 // fb parameter (which specifies feedback amount). This is incredibly
507 // useful, and makes it possible to define a lot more instruments
508 // for the OPNA than you'd be able to otherwise. */
509 #define FM_PRECISEFEEDBACK 1
CalcFB(FMOperator * op,uint32_t fb)510 static inline void CalcFB(FMOperator *op, uint32_t fb)
511 {
512     int32_t tmp;
513     int32_t in = op->out + op->out2;
514     op->out2 = op->out;
515     if (FM_PRECISEFEEDBACK && fb == 31)
516         tmp = Sine(op->pgcount);
517     else
518         tmp = Sine(op->pgcount + ((in << 6) >> fb));
519 
520     op->out = op->egout*tmp;
521     PGCalc(op);
522 }
523 
524 /* ---------------------------------------------------------------------------
525 //  4-op Channel
526 //  Sets the "algorithm", i.e. the connections between individual operators
527 //  in a channel. See Page 22 of the manual for pretty drawings of all of the
528 //  different algorithms supported by the OPNA.
529 */
SetAlgorithm(Channel4 * ch4,uint32_t algo)530 static void SetAlgorithm(Channel4 *ch4, uint32_t algo)
531 {
532     static const uint8_t table1[8][6] =
533     {
534         { 0, 1, 1, 2, 2, 3 },   { 1, 0, 0, 1, 1, 2 },
535         { 1, 1, 1, 0, 0, 2 },   { 0, 1, 2, 1, 1, 2 },
536         { 0, 1, 2, 2, 2, 1 },   { 0, 1, 0, 1, 0, 1 },
537         { 0, 1, 2, 1, 2, 1 },   { 1, 0, 1, 0, 1, 0 },
538     };
539 
540     ch4->idx[0] = table1[algo][0]; /* in[0]; */
541     ch4->idx[1] = table1[algo][2]; /* in[1]; */
542     ch4->idx[2] = table1[algo][4]; /* in[2]; */
543     ch4->idx[3] = table1[algo][1]; /* out[0]; */
544     ch4->idx[4] = table1[algo][3]; /* out[1]; */
545     ch4->idx[5] = table1[algo][5]; /* out[2]; */
546     ch4->op[0].out2 = ch4->op[0].out = 0;
547 }
548 
Ch4Init(OPNA * opna,Channel4 * ch4)549 static inline void Ch4Init(OPNA *opna, Channel4 *ch4)
550 {
551     int i;
552     ch4->master = opna;
553     for(i=0; i<4; i++) {
554         OperatorInit(ch4, &ch4->op[i]);
555     }
556     SetAlgorithm(ch4, 0);
557 }
558 
559 /* Reinit all operators on a given channel if paramchanged=1
560 // for that channel, set the PM table for that channel, then determine
561 // if there is any output from this channel, based on:
562 // - mute state of each operator
563 // - keyon state of each operator
564 // - AM (Tremolo) enable for each operator.
565 // Bit 0 of the return value is set if there is any output,
566 // Bit 1 is set if tremolo is enabled for any of the operators on this
567 // channel. */
Ch4Prepare(Channel4 * ch4)568 static inline int Ch4Prepare(Channel4 *ch4)
569 {
570     OperatorPrepare(&ch4->op[0]);
571     OperatorPrepare(&ch4->op[1]);
572     OperatorPrepare(&ch4->op[2]);
573     OperatorPrepare(&ch4->op[3]);
574 
575     if(ch4->op[0].mute && ch4->op[1].mute && ch4->op[2].mute && ch4->op[3].mute)
576         return 0;
577     else {
578         int key = (IsOn(&ch4->op[0]) | IsOn(&ch4->op[1]) | IsOn(&ch4->op[2]) | IsOn(&ch4->op[3])) ? 1 : 0;
579         int lfo = ch4->op[0].ms & (ch4->op[0].amon | ch4->op[1].amon | ch4->op[2].amon | ch4->op[3].amon ? 0x37 : 7) ? 2 : 0;
580         return key | lfo;
581     }
582 }
583 
584 /* Clock one channel. Clocks all the Envelope Generators in parallel
585 // (well, okay, in sequence, but a hardware implementation *should*
586 //  clock them in parallel as they are completely independent tasks,
587 //  all that is important is that you don't execute Calc{L,FB,FBL}
588 //  until all of the EGs are done clocking - but that should be, again,
589 //  straightforward to implement in hardware).
590 */
Ch4Calc(Channel4 * ch4)591 int32_t Ch4Calc(Channel4 *ch4)
592 {
593     int i, o;
594     OPNA *opna = ch4->master;
595     ch4->buf[1] = ch4->buf[2] = ch4->buf[3] = 0;
596     for(i=0; i<4; i++) {
597         if ((ch4->op[i].egstep -= ch4->op[i].egstepd) < 0)
598             EGCalc(&ch4->op[i]);
599         ch4->op[i].egout = (LogToLin(ch4->op[i].eglevel + (opna->aml >> amt[ch4->op[i].ams]))*gaintab[ch4->op[i].tl]);
600     }
601 
602     ch4->buf[0] = ch4->op[0].out; CalcFB(&ch4->op[0], ch4->fb);
603     if (!(ch4->idx[0] | ch4->idx[2] | ch4->idx[4])) {
604         o  = Calc(&ch4->op[1], ch4->buf[0]);
605         o += Calc(&ch4->op[2], ch4->buf[0]);
606         o += Calc(&ch4->op[3], ch4->buf[0]);
607         return (o >> 8);
608     } else {
609         ch4->buf[ch4->idx[3]] += Calc(&ch4->op[1], ch4->buf[ch4->idx[0]]);
610         ch4->buf[ch4->idx[4]] += Calc(&ch4->op[2], ch4->buf[ch4->idx[1]]);
611         o = ch4->op[3].out;
612         Calc(&ch4->op[3], ch4->buf[ch4->idx[2]]);
613         return ((ch4->buf[ch4->idx[5]] + o) >> 8);
614     }
615 }
616 
617 /* This essentially initializes a couple constant tables
618 // and chip-specific parameters based on what the chip clock and "DAC" samplerate
619 // were set to in OPNAInit(). psgrate is always equal to the user-requested samplerate,
620 // whereas rate is only equal to that in the interpolation=0 case, otherwise
621 // it's set to whatever value is needed to downsample 55466Hz to the user-requested
622 // samplerate, which will (almost?) always be either 44100Hz or 48000Hz.
623 // TODO: better-quality resampling may be of use here, possibly.
624 */
SetPrescaler(OPNA * opna,uint32_t p)625 static void SetPrescaler(OPNA *opna, uint32_t p)
626 {
627     static const char table[3][2] = { { 6, 4 }, { 3, 2 }, { 2, 1 } };
628     static const uint8_t table2[8] = { 109,  78,  72,  68,  63,  45,  9,  6 };
629     /* 512 */
630     if (opna->prescale != p)
631     {
632         uint32_t i, fmclock;
633         uint32_t ratio;
634 
635         opna->prescale = p;
636         fmclock = opna->clock / table[p][0] / 12;
637 
638         if (opna->interpolation) {
639             opna->rate = fmclock * 2;
640             do {
641                 opna->rate >>= 1;
642                 opna->mpratio = opna->psgrate * 16384 / opna->rate;
643             } while (opna->mpratio <= 8192);
644         } else {
645             opna->rate = opna->psgrate;
646         }
647         ratio = ((fmclock << FM_RATIOBITS) + opna->rate/2) / opna->rate;
648         opna->timer_step = (int32_t)(1000000.0f * 65536.0f/fmclock);
649         /* PG Part */
650         opna->rr = (float)ratio / (1 << (2 + FM_RATIOBITS - FM_PGBITS));
651         MakeTimeTable(opna, ratio);
652         PSGSetClock(&opna->psg, opna->clock / table[p][1], opna->psgrate);
653 
654         for (i=0; i<8; i++) {
655             opna->lfotab[i] = (ratio << (1+FM_LFOCBITS-FM_RATIOBITS)) / table2[i];
656         }
657     }
658 }
659 
RebuildTimeTable(OPNA * opna)660 static inline void RebuildTimeTable(OPNA *opna)
661 {
662     int p = opna->prescale;
663     opna->prescale = -1;
664     SetPrescaler(opna, p);
665 }
666 
667 /* Chip-internal TimerA() handler. All it does is implement CSM, i.e.
668 // channel 3 will get keyed on and off whenever the TimerA() interrupt fires.
669 // To the best of my knowledge, CSM was intended to be used to implement
670 // primitive formant synthesis (which Yamaha later repackaged in a much more
671 // elaborate and featured implementation in their FS1R), and used by
672 // approximately nobody. It's also been removed from the YMF288/OPN3.
673 */
TimerA(OPNA * opna)674 static void TimerA(OPNA *opna)
675 {
676     int i;
677     if (opna->regtc & 0x80)
678     {
679         for(i=0; i<4; i++)
680             KeyOn(&opna->csmch->op[i]);
681         for(i=0; i<4; i++)
682             KeyOff(&opna->csmch->op[i]);
683     }
684 }
685 
686 /* ---------------------------------------------------------------------------
687 // Clock timers. TimerA has a resolution of 9 microseconds (assuming standard
688 // chip clockspeed of 8MHz, which all of this code of course does), and
689 // on the Speak Board for the PC-9801 is used only for the purpose of sound effects.
690 // TimerB, on the other hand, has a resolution of 144 microseconds, and is basically
691 // used as the main chip clock. Also, binding "sound-effects" to TimerB (needed as
692 // ZUN uses the sound-effects feature to implement PSG percussion) results in tiny
693 // changes to the output file, precisely none of them audible, making TimerA
694 // all but useless in this case. Note that TimerA is also used internally in the chip
695 // to implement CSM-mode (see comment above).
696 */
OPNATimerCount(OPNA * opna,int32_t us)697 uint8_t OPNATimerCount(OPNA *opna, int32_t us)
698 {
699     uint8_t event = 0;
700 
701     if (opna->timera_count) {
702         opna->timera_count -= us << 16;
703         if (opna->timera_count <= 0) {
704             event = 1;
705             TimerA(opna);
706 
707             while (opna->timera_count <= 0)
708                 opna->timera_count += opna->timera;
709 
710             if (opna->regtc & 4) {
711                 if (!(opna->status & 1)) {
712                     opna->status |= 1;
713                 }
714             }
715         }
716     }
717     if (opna->timerb_count) {
718         opna->timerb_count -= us << 12;
719         if (opna->timerb_count <= 0) {
720             event = 1;
721             while (opna->timerb_count <= 0)
722                 opna->timerb_count += opna->timerb;
723 
724             if (opna->regtc & 8) {
725                 if (!(opna->status & 2)) {
726                     opna->status |= 2;
727                 }
728             }
729         }
730     }
731     return event;
732 }
733 
734 /* Rhythm source samples. pcm_s8 (*not* u8!), and found in rhythmdata.h,
735 // which is included in rhythmdata.c in order to keep the size of the
736 // object file that you get from compiling this file at a reasonable size,
737 // for debugging/testing/sanity purposes.
738 */
739 extern const unsigned char* rhythmdata[6];
740 static const unsigned int rhythmdatalen[6] = {
741     9013, 10674, 66610, 7259, 18562, 3042
742 };
743 
744 /* ---------------------------------------------------------------------------
745 // Main chip init routine.
746 // c is the chip clock, which should never be set to anything other than 8MHz.
747 // r is the chip samplerate, set to 44100 typically.
748 // ipflag - if 1, ignore the value of r, clock the "DAC" at the OPNA-internal
749 // samplerate of 55466Hz, then downsample to whatever the actual value of r is.
750 */
OPNAInit(OPNA * opna,uint32_t c,uint32_t r,uint8_t ipflag)751 uint8_t OPNAInit(OPNA *opna, uint32_t c, uint32_t r, uint8_t ipflag)
752 {
753     int i;
754     opna->devmask = 0x7;
755     opna->prescale = 0;
756     opna->rate = 44100;
757     opna->mixl = 0;
758     opna->mixr = 0;
759     opna->mixdelta = 16383;
760     opna->interpolation = 0;
761 
762     for (i=0; i<8; i++)
763         opna->lfotab[i] = 0;
764 
765     opna->aml = 0;
766 
767     opna->currentratio = ~0;
768     opna->rr = 0;
769     for (i=0; i<64; i++)
770         opna->ratetable[i] = 0;
771 
772     for (i=0; i<6; i++) {
773         Ch4Init(opna, &opna->ch[i]);
774         opna->rhythm[i].sample = 0;
775         opna->rhythm[i].pos = 0;
776         opna->rhythm[i].size = 0;
777         opna->rhythm[i].volume = 0;
778     }
779     opna->rhythmtvol = 0;
780     opna->csmch = &opna->ch[2];
781     for (i=0; i<6; i++)
782         opna->rhythm[i].pos = ~0;
783 
784     for (i=0; i<6; i++)
785     {
786         uint8_t *file_buf = (uint8_t*)0;
787         uint32_t fsize;
788         file_buf = (uint8_t*)rhythmdata[i];
789         fsize = rhythmdatalen[i];
790         file_buf += 44;
791         fsize -= 44;
792         fsize /= 2;
793         opna->rhythm[i].sample = (int8_t*)file_buf;
794         opna->rhythm[i].rate = 44100;
795         opna->rhythm[i].step = opna->rhythm[i].rate * 1024 / opna->rate;
796         opna->rhythm[i].pos = opna->rhythm[i].size = fsize * 1024;
797     }
798 
799     c /= 2;
800     opna->clock = c;
801     if (!OPNASetRate(opna, r, ipflag))
802         return 0;
803     RebuildTimeTable(opna);
804     OPNAReset(opna);
805     PSGInit(&opna->psg);
806 
807     OPNASetChannelMask(opna, ~0);
808     return 1;
809 }
810 
811 /* ---------------------------------------------------------------------------
812 // Reset chip. Your standard routine, basically zeros everything in sight.
813 */
OPNAReset(OPNA * opna)814 void OPNAReset(OPNA *opna)
815 {
816     int i, j;
817 
818     opna->status = 0;
819     SetPrescaler(opna, 0);
820     opna->timera_count = 0;
821     opna->timerb_count = 0;
822     PSGReset(&opna->psg);
823     opna->reg29 = 0x1f;
824     opna->rhythmkey = 0;
825     for (i=0x20; i<0x28; i++) OPNASetReg(opna, i, 0);
826     for (i=0x30; i<0xc0; i++) OPNASetReg(opna, i, 0);
827     for (i=0x130; i<0x1c0; i++) OPNASetReg(opna, i, 0);
828     for (i=0x100; i<0x110; i++) OPNASetReg(opna, i, 0);
829     for (i=0x10; i<0x20; i++) OPNASetReg(opna, i, 0);
830     for (i=0; i<6; i++) {
831         Channel4 *ch = &opna->ch[i];
832         ch->panl = 46340;
833         ch->panr = 46340;
834         for(j=0; j<4; j++) {
835             FMOperator *op = &opna->ch[i].op[j];
836             OperatorReset(op);
837         }
838     }
839 
840     opna->statusnext = 0;
841     opna->lfocount = 0;
842     opna->status = 0;
843 }
844 
845 /* ---------------------------------------------------------------------------
846 // Change OPNA "DAC" samplerate.
847 // r and ipflag are as in OPNAInit(), above.
848 */
OPNASetRate(OPNA * opna,uint32_t r,uint8_t ipflag)849 uint8_t OPNASetRate(OPNA *opna, uint32_t r, uint8_t ipflag)
850 {
851     int i, j;
852     opna->interpolation = ipflag;
853     opna->psgrate = r;
854     RebuildTimeTable(opna);
855     opna->lfodcount = opna->reg22 & 0x08 ? opna->lfotab[opna->reg22 & 7] : 0;
856 
857     for (i=0; i<6; i++) {
858         for (j=0; j<4; j++)
859             opna->ch[i].op[j].paramchanged = 1;
860     }
861     for (i=0; i<6; i++) {
862         opna->rhythm[i].step = opna->rhythm[i].rate * 1024 / r;
863     }
864     return 1;
865 }
866 
SetVolumeRhythm(OPNA * opna,unsigned int index,int db)867 void SetVolumeRhythm(OPNA *opna, unsigned int index, int db)
868 {
869     db = Min(db, 20);
870     opna->rhythm[index].volume = 16-(db * 2 / 3);
871 }
872 
873 /* ---------------------------------------------------------------------------
874 // Set OPNA channel mask. The 6 LSBs of mask are 0 to disable that FM channel,
875 // and 1 to enable it. The next 3 LSBs are passed to PSGSetChannelMask() to,
876 // well, set the PSG channel mask (which behaves the same way: 0 disables
877 // a given channel and 1 enables it).
878 */
OPNASetChannelMask(OPNA * opna,uint32_t mask)879 void OPNASetChannelMask(OPNA *opna, uint32_t mask)
880 {
881     int i, j;
882     for (i=0; i<6; i++) {
883         for (j=0; j<4; j++) {
884             opna->ch[i].op[j].mute = (!(mask & (1 << i)));
885             opna->ch[i].op[j].paramchanged = 1;
886         }
887     }
888     PSGSetChannelMask(&opna->psg, (mask >> 6));
889     /*if (!(mask & 0x200)) opna->devmask = 3;*/
890 }
891 
892 #include <stdio.h>
893 
894 /* libOPNMIDI: allow to disable the console messages */
895 #if defined(OPNA_VERBOSE)
message(const char * fmt,...)896 static void message(const char *fmt, ...)
897 {
898     va_list ap;
899     va_start(ap, fmt);
900     vfprintf(stderr, fmt, ap);
901     va_end(ap);
902 }
903 #else
message(const char * fmt,...)904 static void message(const char *fmt, ...)
905 {
906     (void)fmt;
907 }
908 #endif
909 
910 /* ---------------------------------------------------------------------------
911 // Main OPNA register-set routine. Really long and boring switch-case.
912 // Basically taken directly from the manual - the only parts of the spec
913 // that were even the least bit tricky to implement were the f-number tables,
914 // everything else is basically obvious.
915 */
OPNASetReg(OPNA * opna,uint32_t addr,uint32_t data)916 void OPNASetReg(OPNA *opna, uint32_t addr, uint32_t data)
917 {
918     uint32_t j, _dp = 0;
919     int c = addr & 3;
920     switch (addr)
921     {
922         uint32_t modified;
923         uint32_t tmp;
924 
925     /* Timer ----------------------------------------------------------------- */
926         case 0x24: case 0x25:
927             opna->regta[addr & 1] = (uint8_t)data;
928             tmp = (opna->regta[0] << 2) + (opna->regta[1] & 3);
929             opna->timera = (1024-tmp) * opna->timer_step;
930             break;
931 
932         case 0x26:
933             opna->timerb = (256-data) * opna->timer_step;
934             break;
935 
936         case 0x27:
937             tmp = opna->regtc ^ data;
938             opna->regtc = (uint8_t)data;
939             if (data & 0x10)
940                 opna->status &= ~1;
941             if (data & 0x20)
942                 opna->status &= ~2;
943             if (tmp & 0x01)
944                 opna->timera_count = (data & 1) ? opna->timera : 0;
945             if (tmp & 0x02)
946                 opna->timerb_count = (data & 2) ? opna->timerb : 0;
947             break;
948 
949     /* Misc ------------------------------------------------------------------ */
950     case 0x28:      /* Key On/Off */
951         if ((data & 3) < 3)
952         {
953             uint32_t key = (data >> 4);
954             c = (data & 3) + (data & 4 ? 3 : 0);
955             if (key & 0x1) KeyOn(&opna->ch[c].op[0]); else KeyOff(&opna->ch[c].op[0]);
956             if (key & 0x2) KeyOn(&opna->ch[c].op[1]); else KeyOff(&opna->ch[c].op[1]);
957             if (key & 0x4) KeyOn(&opna->ch[c].op[2]); else KeyOff(&opna->ch[c].op[2]);
958             if (key & 0x8) KeyOn(&opna->ch[c].op[3]); else KeyOff(&opna->ch[c].op[3]);
959         }
960         break;
961 
962     /* Status Mask ----------------------------------------------------------- */
963     case 0x29:
964         opna->reg29 = data;
965         break;
966 
967     /* Prescaler ------------------------------------------------------------- */
968     case 0x2d: case 0x2e: case 0x2f:
969         SetPrescaler(opna, (addr-0x2d));
970         break;
971 
972     /* F-Number -------------------------------------------------------------- */
973     case 0x1a0: case 0x1a1: case 0x1a2:
974         c += 3;
975         /* fall through */
976     case 0xa0:  case 0xa1: case 0xa2:
977         opna->fnum[c] = data + opna->fnum2[c] * 0x100;
978         _dp = (opna->fnum[c] & 2047) << ((opna->fnum[c] >> 11) & 7);
979         for(j=0; j<4; j++) {
980             opna->ch[c].op[j].dp = _dp;
981             opna->ch[c].op[j].bn = notetab[(opna->fnum[c] >> 7) & 127];
982             opna->ch[c].op[j].paramchanged = 1;
983         }
984         break;
985 
986     case 0x1a4: case 0x1a5: case 0x1a6:
987         c += 3;
988         /* fall through */
989     case 0xa4 : case 0xa5: case 0xa6:
990         opna->fnum2[c] = (uint8_t)data;
991         break;
992 
993     case 0xa8:  case 0xa9: case 0xaa:
994         opna->fnum3[c] = data + opna->fnum2[c+6] * 0x100;
995         break;
996 
997     case 0xac : case 0xad: case 0xae:
998         opna->fnum2[c+6] = (uint8_t)data;
999         break;
1000 
1001     /* Algorithm ------------------------------------------------------------- */
1002     case 0x1b0: case 0x1b1:  case 0x1b2:
1003         c += 3;
1004         /* fall through */
1005     case 0xb0:  case 0xb1:  case 0xb2:
1006         opna->ch[c].fb = fbtab[((data >> 3) & 7)];
1007         SetAlgorithm(&opna->ch[c], data & 7);
1008         message("OP%u: Algorithm: %u, FB: %u\n", c, data & 7, opna->ch[c].fb);
1009         break;
1010 
1011     case 0x1b4: case 0x1b5: case 0x1b6:
1012         c += 3;
1013         /* fall through */
1014     case 0xb4: case 0xb5: case 0xb6:
1015         /*opna->pan[c] = (data >> 6) & 3;*/
1016         for(j=0; j<4; j++) {
1017             opna->ch[c].op[j].ms = data;
1018             opna->ch[c].op[j].paramchanged = 1;
1019         }
1020         break;
1021 
1022     /* Rhythm ---------------------------------------------------------------- */
1023     case 0x10:          /* DM/KEYON */
1024         if (!(data & 0x80))  /* KEY ON */
1025         {
1026             opna->rhythmkey |= data & 0x3f;
1027             if (data & 0x01) opna->rhythm[0].pos = 0;
1028             if (data & 0x02) opna->rhythm[1].pos = 0;
1029             if (data & 0x04) opna->rhythm[2].pos = 0;
1030             if (data & 0x08) opna->rhythm[3].pos = 0;
1031             if (data & 0x10) opna->rhythm[4].pos = 0;
1032             if (data & 0x20) opna->rhythm[5].pos = 0;
1033         }
1034         else
1035         {                   /* DUMP */
1036             opna->rhythmkey &= ~data;
1037         }
1038         break;
1039 
1040     case 0x11:
1041         opna->rhythmtl = ~data & 63;
1042         break;
1043 
1044     case 0x1a:      /* Top Cymbal */
1045         break;
1046     case 0x18:      /* Bass Drum */
1047     case 0x19:      /* Snare Drum */
1048     case 0x1b:      /* Hihat */
1049     case 0x1c:      /* Tom-tom */
1050     case 0x1d:      /* Rim shot */
1051         opna->rhythm[addr & 7].pan   = (data >> 6) & 3;
1052         opna->rhythm[addr & 7].level = ~data & 31;
1053         break;
1054 
1055     /* LFO ------------------------------------------------------------------- */
1056     case 0x22:
1057         modified = opna->reg22 ^ data;
1058         opna->reg22 = data;
1059         if (modified & 0x8)
1060             opna->lfocount = 0;
1061         opna->lfodcount = opna->reg22 & 8 ? opna->lfotab[opna->reg22 & 7] : 0;
1062         message("LFO: reg22: %u, lfodcount: %u\n", opna->reg22, opna->lfodcount);
1063         break;
1064 
1065     /* PSG ------------------------------------------------------------------- */
1066     case  0: case  1: case  2: case  3: case  4: case  5: case  6: case  7:
1067     case  8: case  9: case 10: case 11: case 12: case 13: case 14: case 15:
1068         PSGSetReg(&opna->psg, addr, data);
1069         break;
1070 
1071     /* ADSR ------------------------------------------------------------------ */
1072     default:
1073         if (c < 3)
1074         {
1075             if (addr & 0x100)
1076                 c += 3;
1077             {
1078                 /*uint8_t slottable[4] = { 0, 2, 1, 3 };*/
1079                 /*uint32_t slot = slottable[(addr >> 2) & 3];*/
1080                 uint32_t slottable = 216;
1081                 uint32_t l, slot = ((slottable >> (((addr >> 2) & 3) << 1)) & 3);
1082                 FMOperator* op = &opna->ch[c].op[slot];
1083 
1084                 switch ((addr >> 4) & 15)
1085                 {
1086                 case 3: /* 30-3E DT/MULTI */
1087                     op->detune = (((data >> 4) & 0x07) * 0x20);
1088                     op->multiple = (data & 0x0f);
1089                     l = ((op->multiple) ? 2*op->multiple : 1);
1090                     /*  PG Part */
1091                     op->pgdcount = (op->dp + dttab[op->detune + op->bn]) * (uint32_t)(l * opna->rr);
1092                     op->pgdcountl = op->pgdcount >> 11;
1093                     /*op->paramchanged = 1;*/
1094                     if(!op->mute)
1095                     message("OP%u DT: %u, Mult: %u\n", c, op->detune, op->multiple);
1096                     break;
1097 
1098                 case 4: /* 40-4E TL */
1099                     if(!((opna->regtc & 0x80) && (opna->csmch == &opna->ch[c]))) {
1100                         op->tl = (data & 0x7f);
1101                         op->paramchanged = 1;
1102                     }
1103                     op->tll = (data & 0x7f);
1104                     break;
1105 
1106                 case 5: /* 50-5E KS/AR */
1107                     op->ks = ((data >> 6) & 3);
1108                     op->ar = ((data & 0x1f) * 2);
1109                     op->paramchanged = 1;
1110                     if(!op->mute)
1111                     message("OP%u KS: %u, AR: %u\n", c, op->ks, op->ar);
1112                     break;
1113 
1114                 case 6: /* 60-6E DR/AMON */
1115                     op->dr = ((data & 0x1f) * 2);
1116                     op->amon = ((data & 0x80) != 0);
1117                     op->paramchanged = 1;
1118                     if(!op->mute)
1119                     message("OP%u DR: %u, AM: %u\n", c, op->dr, op->amon);
1120                     break;
1121 
1122                 case 7: /* 70-7E SR */
1123                     op->sr = ((data & 0x1f) * 2);
1124                     op->paramchanged = 1;
1125                     if(!op->mute)
1126                     message("OP%u SR: %u\n", c, op->sr);
1127                     break;
1128 
1129                 case 8: /* 80-8E SL/RR */
1130                     op->sl = (((data >> 4) & 15) * 4);
1131                     op->rr = ((data & 0x0f) * 4 + 2);
1132                     op->paramchanged = 1;
1133                     if(!op->mute)
1134                     message("OP%u SL: %u, RR: %u\n", c, op->sl, op->rr);
1135                     break;
1136 
1137                 case 9: /* 90-9E SSG-EC */
1138                     op->ssgtype = (data & 0x0f);
1139                     message("OP%u SSG-EG: %u\n", c, op->ssgtype);
1140                     break;
1141                 }
1142             }
1143         }
1144         break;
1145     }
1146 }
1147 
1148 /* libOPNMIDI: soft panning */
OPNASetPan(OPNA * opna,uint32_t chan,uint32_t data)1149 void OPNASetPan(OPNA *opna, uint32_t chan, uint32_t data)
1150 {
1151     assert(chan < 6);
1152     assert(data < 128);
1153     opna->ch[chan].panl = panlawtable[data & 0x7F];
1154     opna->ch[chan].panr = panlawtable[0x7F - (data & 0x7F)];
1155 }
1156 
1157 /* ---------------------------------------------------------------------------
1158 // Read OPNA register. Pointless. Only SSG registers can be read, and of those
1159 // the only one anyone seems to be interested in reading is register 7,
1160 // which as I explain in detail in psg.c, is completely superfluous.
1161 */
OPNAGetReg(OPNA * opna,uint32_t addr)1162 uint32_t OPNAGetReg(OPNA *opna, uint32_t addr)
1163 {
1164     if (addr < 0x10)
1165         return PSGGetReg(&opna->psg, addr);
1166     if (addr == 0xff)
1167         return 1;
1168     return 0;
1169 }
1170 
1171 /* --------------------------------------------------------------------------- */
1172 
MixSubS(Channel4 ch[6],int activech,int32_t * dest)1173 static inline void MixSubS(Channel4 ch[6], int activech, int32_t *dest)
1174 {
1175     unsigned int c;
1176     int32_t l = 0;
1177     int32_t r = 0;
1178 
1179     for (c = 0; c < 6; ++c) {
1180         if (activech & (1 << (c << 1))) {
1181             int32_t s = Ch4Calc(&ch[c]);
1182             s >>= 2; /* libOPNMIDI: prevent FM channel clipping (TODO: also adjust PSG and rhythm) */
1183             l += s * ch[c].panl / 65536;
1184             r += s * ch[c].panr / 65536;
1185         }
1186     }
1187 
1188     dest[0] = l;
1189     dest[1] = r;
1190 }
1191 
1192 /* ---------------------------------------------------------------------------
1193 // Mix FM channels and output. Mix6 runs at user-specified samplerate,
1194 // Mix6I runs at the chip samplerate of 55466Hz and then downsamples
1195 // to the user-specified samplerate. It is an open problem as to determining
1196 // if one of these sounds better than the other.
1197 */
1198 #define IStoSample(s)   (Limit16((s)))
1199 
Mix6(OPNA * opna,int32_t * buffer,uint32_t nsamples,int activech)1200 static void Mix6(OPNA *opna, int32_t *buffer, uint32_t nsamples, int activech)
1201 {
1202     /* Mix */
1203     int32_t ibuf[2];
1204     unsigned int i;
1205 
1206     for (i = 0; i < nsamples; i++) {
1207         ibuf[0] = 0;
1208         ibuf[1] = 0;
1209         if (activech & 0xaaa)
1210             LFO(opna), MixSubS(opna->ch, activech, ibuf);
1211         else
1212             MixSubS(opna->ch, activech, ibuf);
1213         buffer[i * 2 + 0] += IStoSample(ibuf[0]);
1214         buffer[i * 2 + 1] += IStoSample(ibuf[1]);
1215     }
1216 }
1217 
1218 /* ---------------------------------------------------------------------------
1219 // See comment above Mix6(), above.
1220 */
Mix6I(OPNA * opna,int32_t * buffer,uint32_t nsamples,int activech)1221 static void Mix6I(OPNA *opna, int32_t *buffer, uint32_t nsamples, int activech)
1222 {
1223     /* Mix */
1224     int32_t ibuf[2], delta = opna->mixdelta;
1225     unsigned int i;
1226 
1227     if (opna->mpratio < 16384) {
1228         for (i = 0; i < nsamples; i++) {
1229             int32_t l = 0, r = 0, d = 0;
1230             while (delta > 0) {
1231                 ibuf[0] = 0;
1232                 ibuf[1] = 0;
1233                 if (activech & 0xaaa)
1234                     LFO(opna), MixSubS(opna->ch, activech, ibuf);
1235                 else
1236                     MixSubS(opna->ch, activech, ibuf);
1237 
1238                 l = IStoSample(ibuf[0]);
1239                 r = IStoSample(ibuf[1]);
1240                 d = Min(opna->mpratio, delta);
1241                 opna->mixl += l * d;
1242                 opna->mixr += r * d;
1243                 delta -= opna->mpratio;
1244             }
1245             buffer[i * 2 + 0] += opna->mixl >> 14;
1246             buffer[i * 2 + 1] += opna->mixr >> 14;
1247             opna->mixl = l * (16384-d);
1248             opna->mixr = r * (16384-d);
1249             delta += 16384;
1250         }
1251     } else {
1252         int impr = 16384 * 16384 / opna->mpratio;
1253         for (i = 0; i < nsamples; i++) {
1254             int32_t l, r;
1255             if (delta < 0) {
1256                 delta += 16384;
1257                 opna->mixl = opna->mixl1;
1258                 opna->mixr = opna->mixr1;
1259 
1260                 ibuf[0] = 0;
1261                 ibuf[1] = 0;
1262                 if (activech & 0xaaa)
1263                     LFO(opna), MixSubS(opna->ch, activech, ibuf);
1264                 else
1265                     MixSubS(opna->ch, activech, ibuf);
1266 
1267                 opna->mixl1 = IStoSample(ibuf[0]);
1268                 opna->mixr1 = IStoSample(ibuf[1]);
1269             }
1270             l = (delta * opna->mixl + (16384 - delta) * opna->mixl1) / 16384;
1271             r = (delta * opna->mixr + (16384 - delta) * opna->mixr1) / 16384;
1272             buffer[i * 2 + 0] += l;
1273             buffer[i * 2 + 1] += r;
1274             delta -= impr;
1275         }
1276     }
1277     opna->mixdelta = delta;
1278 }
1279 
1280 /* ---------------------------------------------------------------------------
1281 // Main FM output routine. Clocks all of the operators on the chip, then mixes
1282 // together the output using one of Mix6() or Mix6I() above, and then outputs
1283 // the result to OPNAMix, which is what the calling routine will actually use.
1284 // buffer should be a pointer to a buffer of type Sample (int32_t in this
1285 // implementation, though another used float and in principle int16_t *should*
1286 // be sufficient), and be of size at least equal to nsamples.
1287 */
FMMix(OPNA * opna,int32_t * buffer,uint32_t nsamples)1288 static void FMMix(OPNA *opna, int32_t *buffer, uint32_t nsamples)
1289 {
1290     uint32_t j;
1291     {
1292         /* Set F-Number */
1293         if (!(opna->regtc & 0xc0)) {
1294             uint32_t _dp = (opna->fnum[opna->csmch-opna->ch] & 2047) << ((opna->fnum[opna->csmch-opna->ch] >> 11) & 7);
1295             for(j=0; j<4; j++) {
1296                 opna->csmch->op[j].dp = _dp;
1297                 opna->csmch->op[j].bn = notetab[(opna->fnum[opna->csmch-opna->ch] >> 7) & 127];
1298                 opna->csmch->op[j].paramchanged = 1;
1299             }
1300         } else {
1301             SetFNum(&opna->csmch->op[0], opna->fnum3[1]); SetFNum(&opna->csmch->op[1], opna->fnum3[2]);
1302             SetFNum(&opna->csmch->op[2], opna->fnum3[0]); SetFNum(&opna->csmch->op[3], opna->fnum[2]);
1303         }
1304     }
1305 
1306     {
1307         int act = (((Ch4Prepare(&opna->ch[2]) << 2) | Ch4Prepare(&opna->ch[1])) << 2) | Ch4Prepare(&opna->ch[0]);
1308         if (opna->reg29 & 0x80)
1309             act |= (Ch4Prepare(&opna->ch[3]) | ((Ch4Prepare(&opna->ch[4]) | (Ch4Prepare(&opna->ch[5]) << 2)) << 2)) << 6;
1310         if (!(opna->reg22 & 0x08))
1311             act &= 0x555;
1312 
1313         if (act & 0x555) {
1314             if (opna->interpolation)
1315                 Mix6I(opna, buffer, nsamples, act);
1316             else
1317                 Mix6(opna, buffer, nsamples, act);
1318         } else {
1319             opna->mixl = 0, opna->mixr = 0, opna->mixdelta = 16383;
1320         }
1321     }
1322 }
1323 
1324 /* ---------------------------------------------------------------------------
1325 // Mix Rhythm generator output. Boring, just takes the PCM samples,
1326 // multiplies them by the volume set for that rhythm sample, and then outputs
1327 // the appropriate length of sample for that given samplerate to buffer.
1328 // The same restrictions on buffer as in FMMix() above apply.
1329 */
RhythmMix(OPNA * opna,int32_t * buffer,uint32_t count)1330 static void RhythmMix(OPNA *opna, int32_t *buffer, uint32_t count)
1331 {
1332     unsigned int i, j;
1333     if (opna->rhythmtvol < 128 && opna->rhythm[0].sample && (opna->rhythmkey & 0x3f)) {
1334         for (i=0; i<6; i++) {
1335             Rhythm *r = &opna->rhythm[i];
1336             if ((opna->rhythmkey & (1 << i)) && r->level >= 0) {
1337                 int db = Limit(opna->rhythmtl+r->level+r->volume, 127, 0);
1338                 int vol = cltab[db];
1339 
1340                 for (j = 0; j < count && r->pos < r->size; j++) {
1341                     int sample = Limit16(((r->sample[r->pos >> 10] << 8) * vol) >> 10);
1342                     r->pos += r->step;
1343                     buffer[j * 2 + 0] += sample;
1344                     buffer[j * 2 + 1] += sample;
1345                 }
1346             }
1347         }
1348     }
1349 }
1350 
1351 /* ---------------------------------------------------------------------------
1352 // Main OPNA output routine. See FMMix(), RhythmMix() above and PSGMix()
1353 // in psg.c for details.
1354 */
OPNAMix(OPNA * opna,int16_t * buf,uint32_t nframes)1355 void OPNAMix(OPNA *opna, int16_t *buf, uint32_t nframes)
1356 {
1357     int32_t buffer[16384];
1358     unsigned int i, clips = 0;
1359     for (i = 0; i < 2 * nframes; i++) buffer[i] = 0;
1360     if(opna->devmask & 1) FMMix(opna, buffer, nframes);
1361     if(opna->devmask & 2) PSGMix(&opna->psg, buffer, nframes);
1362     if(opna->devmask & 4) RhythmMix(opna, buffer, nframes);
1363     for (i = 0; i < 2 * nframes; i++) {
1364         int32_t k = (buffer[i] >> 2);
1365         if (k > 32767 || k < -32767) clips++;
1366         buf[i] = Limit16(k);
1367     }
1368     if (clips) message("clipped %u samples\n", clips);
1369 }
1370