Debian Codegraph @

BambooTracker/chip/ymfm/ymfm_fm.h

raw
1 // BSD 3-Clause License
2 //
3 // Copyright (c) 2021, Aaron Giles
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are met:
8 //
9 // 1. Redistributions of source code must retain the above copyright notice, this
10 // list of conditions and the following disclaimer.
11 //
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 // 3. Neither the name of the copyright holder nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 #ifndef YMFM_FM_H
32 #define YMFM_FM_H
33
34 #pragma once
35
36 #include <cstdint>
37 #include "ymfm.h"
38
39 #define DEBUG_LOG_WAVFILES (0)
40
41 namespace ymfm
42 {
43
44 //*********************************************************
45 // GLOBAL ENUMERATORS
46 //*********************************************************
47
48 // three different keyon sources; actual keyon is an OR over all of these
49 enum keyon_type : uint32_t
50 {
51 KEYON_NORMAL = 0,
52 KEYON_RHYTHM = 1,
53 KEYON_CSM = 2
54 };
55
56
57
58 //*********************************************************
59 // CORE IMPLEMENTATION
60 //*********************************************************
61
62 // ======================> opdata_cache
63
64 // this class holds data that is computed once at the start of clocking
65 // and remains static during subsequent sound generation
66 struct opdata_cache
67 {
68 // set phase_step to this value to recalculate it each sample; needed
69 // in the case of PM LFO changes
70 static constexpr uint32_t PHASE_STEP_DYNAMIC = 1;
71
72 uint16_t const *waveform; // base of sine table
73 uint32_t phase_step; // phase step, or PHASE_STEP_DYNAMIC if PM is active
74 uint32_t total_level; // total level * 8 + KSL
75 uint32_t block_freq; // raw block frequency value (used to compute phase_step)
76 int32_t detune; // detuning value (used to compute phase_step)
77 uint32_t multiple; // multiple value (x.1, used to compute phase_step)
78 uint32_t eg_sustain; // sustain level, shifted up to envelope values
79 uint8_t eg_rate[EG_STATES]; // envelope rate, including KSR
80 uint8_t eg_shift = 0; // envelope shift amount
81 };
82
83
84 // ======================> fm_registers_base
85
86 // base class for family-specific register classes; this provides a few
87 // constants, common defaults, and helpers, but mostly each derived class is
88 // responsible for defining all commonly-called methods
89 class fm_registers_base
90 {
91 public:
92 // this value is returned from the write() function for rhythm channels
93 static constexpr uint32_t RHYTHM_CHANNEL = 0xff;
94
95 // this is the size of a full sin waveform
96 static constexpr uint32_t WAVEFORM_LENGTH = 0x400;
97
98 //
99 // the following constants need to be defined per family:
100 // uint32_t OUTPUTS: The number of outputs exposed (1-4)
101 // uint32_t CHANNELS: The number of channels on the chip
102 // uint32_t ALL_CHANNELS: A bitmask of all channels
103 // uint32_t OPERATORS: The number of operators on the chip
104 // uint32_t WAVEFORMS: The number of waveforms offered
105 // uint32_t REGISTERS: The number of 8-bit registers allocated
106 // uint32_t DEFAULT_PRESCALE: The starting clock prescale
107 // uint32_t EG_CLOCK_DIVIDER: The clock divider of the envelope generator
108 // uint32_t CSM_TRIGGER_MASK: Mask of channels to trigger in CSM mode
109 // uint32_t REG_MODE: The address of the "mode" register controlling timers
110 // uint8_t STATUS_TIMERA: Status bit to set when timer A fires
111 // uint8_t STATUS_TIMERB: Status bit to set when tiemr B fires
112 // uint8_t STATUS_BUSY: Status bit to set when the chip is busy
113 // uint8_t STATUS_IRQ: Status bit to set when an IRQ is signalled
114 //
115 // the following constants are uncommon:
116 // bool DYNAMIC_OPS: True if ops/channel can be changed at runtime (OPL3+)
117 // bool EG_HAS_DEPRESS: True if the chip has a DP ("depress"?) envelope stage (OPLL)
118 // bool EG_HAS_REVERB: True if the chip has a faux reverb envelope stage (OPQ/OPZ)
119 // bool EG_HAS_SSG: True if the chip has SSG envelope support (OPN)
120 // bool MODULATOR_DELAY: True if the modulator is delayed by 1 sample (OPL pre-OPL3)
121 //
122 static constexpr bool DYNAMIC_OPS = false;
123 static constexpr bool EG_HAS_DEPRESS = false;
124 static constexpr bool EG_HAS_REVERB = false;
125 static constexpr bool EG_HAS_SSG = false;
126 static constexpr bool MODULATOR_DELAY = false;
127
128 // system-wide register defaults
129 uint32_t status_mask() const { return 0; } // OPL only
130 uint32_t irq_reset() const { return 0; } // OPL only
131 uint32_t noise_enable() const { return 0; } // OPM only
132 uint32_t rhythm_enable() const { return 0; } // OPL only
133
134 // per-operator register defaults
135 uint32_t op_ssg_eg_enable(uint32_t /*opoffs*/) const { return 0; } // OPN(A) only
136 uint32_t op_ssg_eg_mode(uint32_t /*opoffs*/) const { return 0; } // OPN(A) only
137
138 protected:
139 // helper to encode four operator numbers into a 32-bit value in the
140 // operator maps for each register class
141 static constexpr uint32_t operator_list(uint8_t o1 = 0xff, uint8_t o2 = 0xff, uint8_t o3 = 0xff, uint8_t o4 = 0xff)
142 {
143 return o1 | (o2 << 8) | (o3 << 16) | (o4 << 24);
144 }
145
146 // helper to apply KSR to the raw ADSR rate, ignoring ksr if the
147 // raw value is 0, and clamping to 63
148 static constexpr uint32_t effective_rate(uint32_t rawrate, uint32_t ksr)
149 {
150 return (rawrate == 0) ? 0 : std::min<uint32_t>(rawrate + ksr, 63);
151 }
152 };
153
154
155
156 //*********************************************************
157 // CORE ENGINE CLASSES
158 //*********************************************************
159
160 // forward declarations
161 template<class RegisterType> class fm_engine_base;
162
163 // ======================> fm_operator
164
165 // fm_operator represents an FM operator (or "slot" in FM parlance), which
166 // produces an output sine wave modulated by an envelope
167 template<class RegisterType>
168 class fm_operator
169 {
170 // "quiet" value, used to optimize when we can skip doing work
171 static constexpr uint32_t EG_QUIET = 0x380;
172
173 public:
174 // constructor
175 fm_operator(fm_engine_base<RegisterType> &owner, uint32_t opoffs);
176
177 // save/restore
178 void save_restore(ymfm_saved_state &state);
179
180 // reset the operator state
181 void reset();
182
183 // return the operator/channel offset
184 uint32_t opoffs() const { return m_opoffs; }
185 uint32_t choffs() const { return m_choffs; }
186
187 // set the current channel
188 void set_choffs(uint32_t choffs) { m_choffs = choffs; }
189
190 // prepare prior to clocking
191 bool prepare();
192
193 // master clocking function
194 void clock(uint32_t env_counter, int32_t lfo_raw_pm);
195
196 // return the current phase value
197 uint32_t phase() const { return m_phase >> 10; }
198
199 // compute operator volume
200 int32_t compute_volume(uint32_t phase, uint32_t am_offset) const;
201
202 // compute volume for the OPM noise channel
203 int32_t compute_noise_volume(uint32_t am_offset) const;
204
205 // key state control
206 void keyonoff(uint32_t on, keyon_type type);
207
208 // return a reference to our registers
209 RegisterType &regs() const { return m_regs; }
210
211 // simple getters for debugging
212 envelope_state debug_eg_state() const { return m_env_state; }
213 uint16_t debug_eg_attenuation() const { return m_env_attenuation; }
214 uint8_t debug_ssg_inverted() const { return m_ssg_inverted; }
215 opdata_cache &debug_cache() { return m_cache; }
216
217 private:
218 // start the attack phase
219 void start_attack(bool is_restart = false);
220
221 // start the release phase
222 void start_release();
223
224 // clock phases
225 void clock_keystate(uint32_t keystate);
226 void clock_ssg_eg_state();
227 void clock_envelope(uint32_t env_counter);
228 void clock_phase(int32_t lfo_raw_pm);
229
230 // return effective attenuation of the envelope
231 uint32_t envelope_attenuation(uint32_t am_offset) const;
232
233 // internal state
234 uint32_t m_choffs; // channel offset in registers
235 uint32_t m_opoffs; // operator offset in registers
236 uint32_t m_phase; // current phase value (10.10 format)
237 uint16_t m_env_attenuation; // computed envelope attenuation (4.6 format)
238 envelope_state m_env_state; // current envelope state
239 uint8_t m_ssg_inverted; // non-zero if the output should be inverted (bit 0)
240 uint8_t m_key_state; // current key state: on or off (bit 0)
241 uint8_t m_keyon_live; // live key on state (bit 0 = direct, bit 1 = rhythm, bit 2 = CSM)
242 opdata_cache m_cache; // cached values for performance
243 RegisterType &m_regs; // direct reference to registers
244 fm_engine_base<RegisterType> &m_owner; // reference to the owning engine
245 };
246
247
248 // ======================> fm_channel
249
250 // fm_channel represents an FM channel which combines the output of 2 or 4
251 // operators into a final result
252 template<class RegisterType>
253 class fm_channel
254 {
255 using output_data = ymfm_output<RegisterType::OUTPUTS>;
256
257 public:
258 // constructor
259 fm_channel(fm_engine_base<RegisterType> &owner, uint32_t choffs);
260
261 // save/restore
262 void save_restore(ymfm_saved_state &state);
263
264 // reset the channel state
265 void reset();
266
267 // return the channel offset
268 uint32_t choffs() const { return m_choffs; }
269
270 // assign operators
271 void assign(uint32_t index, fm_operator<RegisterType> *op)
272 {
273 assert(index < array_size(m_op));
274 m_op[index] = op;
275 if (op != nullptr)
276 op->set_choffs(m_choffs);
277 }
278
279 // signal key on/off to our operators
280 void keyonoff(uint32_t states, keyon_type type, uint32_t chnum);
281
282 // prepare prior to clocking
283 bool prepare();
284
285 // master clocking function
286 void clock(uint32_t env_counter, int32_t lfo_raw_pm);
287
288 // specific 2-operator and 4-operator output handlers
289 void output_2op(output_data &output, uint32_t rshift, int32_t clipmax) const;
290 void output_4op(output_data &output, uint32_t rshift, int32_t clipmax) const;
291
292 // compute the special OPL rhythm channel outputs
293 void output_rhythm_ch6(output_data &output, uint32_t rshift, int32_t clipmax) const;
294 void output_rhythm_ch7(uint32_t phase_select, output_data &output, uint32_t rshift, int32_t clipmax) const;
295 void output_rhythm_ch8(uint32_t phase_select, output_data &output, uint32_t rshift, int32_t clipmax) const;
296
297 // are we a 4-operator channel or a 2-operator one?
298 bool is4op() const
299 {
300 if (RegisterType::DYNAMIC_OPS)
301 return (m_op[2] != nullptr);
302 return (RegisterType::OPERATORS / RegisterType::CHANNELS == 4);
303 }
304
305 // return a reference to our registers
306 RegisterType &regs() const { return m_regs; }
307
308 // simple getters for debugging
309 fm_operator<RegisterType> *debug_operator(uint32_t index) const { return m_op[index]; }
310
311 private:
312 // helper to add values to the outputs based on channel enables
313 void add_to_output(uint32_t choffs, output_data &output, int32_t value) const
314 {
315 // create these constants to appease overzealous compilers checking array
316 // bounds in unreachable code (looking at you, clang)
317 constexpr int out0_index = 0;
318 constexpr int out1_index = 1 % RegisterType::OUTPUTS;
319 constexpr int out2_index = 2 % RegisterType::OUTPUTS;
320 constexpr int out3_index = 3 % RegisterType::OUTPUTS;
321
322 if (RegisterType::OUTPUTS == 1 || m_regs.ch_output_0(choffs))
323 output.data[out0_index] += value;
324 if (RegisterType::OUTPUTS >= 2 && m_regs.ch_output_1(choffs))
325 output.data[out1_index] += value;
326 if (RegisterType::OUTPUTS >= 3 && m_regs.ch_output_2(choffs))
327 output.data[out2_index] += value;
328 if (RegisterType::OUTPUTS >= 4 && m_regs.ch_output_3(choffs))
329 output.data[out3_index] += value;
330 }
331
332 // internal state
333 uint32_t m_choffs; // channel offset in registers
334 int16_t m_feedback[2]; // feedback memory for operator 1
335 mutable int16_t m_feedback_in; // next input value for op 1 feedback (set in output)
336 fm_operator<RegisterType> *m_op[4]; // up to 4 operators
337 RegisterType &m_regs; // direct reference to registers
338 fm_engine_base<RegisterType> &m_owner; // reference to the owning engine
339 };
340
341
342 // ======================> fm_engine_base
343
344 // fm_engine_base represents a set of operators and channels which together
345 // form a Yamaha FM core; chips that implement other engines (ADPCM, wavetable,
346 // etc) take this output and combine it with the others externally
347 template<class RegisterType>
348 class fm_engine_base : public ymfm_engine_callbacks
349 {
350 public:
351 // expose some constants from the registers
352 static constexpr uint32_t OUTPUTS = RegisterType::OUTPUTS;
353 static constexpr uint32_t CHANNELS = RegisterType::CHANNELS;
354 static constexpr uint32_t ALL_CHANNELS = RegisterType::ALL_CHANNELS;
355 static constexpr uint32_t OPERATORS = RegisterType::OPERATORS;
356
357 // also expose status flags for consumers that inject additional bits
358 static constexpr uint8_t STATUS_TIMERA = RegisterType::STATUS_TIMERA;
359 static constexpr uint8_t STATUS_TIMERB = RegisterType::STATUS_TIMERB;
360 static constexpr uint8_t STATUS_BUSY = RegisterType::STATUS_BUSY;
361 static constexpr uint8_t STATUS_IRQ = RegisterType::STATUS_IRQ;
362
363 // expose the correct output class
364 using output_data = ymfm_output<OUTPUTS>;
365
366 // constructor
367 fm_engine_base(ymfm_interface &intf);
368
369 // save/restore
370 void save_restore(ymfm_saved_state &state);
371
372 // reset the overall state
373 void reset();
374
375 // master clocking function
376 uint32_t clock(uint32_t chanmask);
377
378 // compute sum of channel outputs
379 void output(output_data &output, uint32_t rshift, int32_t clipmax, uint32_t chanmask) const;
380
381 // write to the OPN registers
382 void write(uint16_t regnum, uint8_t data);
383
384 // return the current status
385 uint8_t status() const;
386
387 // set/reset bits in the status register, updating the IRQ status
388 uint8_t set_reset_status(uint8_t set, uint8_t reset)
389 {
390 m_status = (m_status | set) & ~(reset | STATUS_BUSY);
391 m_intf.ymfm_sync_check_interrupts();
392 return m_status & ~m_regs.status_mask();
393 }
394
395 // set the IRQ mask
396 void set_irq_mask(uint8_t mask) { m_irq_mask = mask; m_intf.ymfm_sync_check_interrupts(); }
397
398 // return the current clock prescale
399 uint32_t clock_prescale() const { return m_clock_prescale; }
400
401 // set prescale factor (2/3/6)
402 void set_clock_prescale(uint32_t prescale) { m_clock_prescale = prescale; }
403
404 // compute sample rate
405 uint32_t sample_rate(uint32_t baseclock) const
406 {
407 #if (DEBUG_LOG_WAVFILES)
408 for (uint32_t chnum = 0; chnum < CHANNELS; chnum++)
409 m_wavfile[chnum].set_samplerate(baseclock / (m_clock_prescale * OPERATORS));
410 #endif
411 return baseclock / (m_clock_prescale * OPERATORS);
412 }
413
414 // return the owning device
415 ymfm_interface &intf() const { return m_intf; }
416
417 // return a reference to our registers
418 RegisterType &regs() { return m_regs; }
419
420 // invalidate any caches
421 void invalidate_caches() { m_modified_channels = RegisterType::ALL_CHANNELS; }
422
423 // simple getters for debugging
424 fm_channel<RegisterType> *debug_channel(uint32_t index) const { return m_channel[index].get(); }
425 fm_operator<RegisterType> *debug_operator(uint32_t index) const { return m_operator[index].get(); }
426
427 public:
428 // timer callback; called by the interface when a timer fires
429 virtual void engine_timer_expired(uint32_t tnum) override;
430
431 // check interrupts; called by the interface after synchronization
432 virtual void engine_check_interrupts() override;
433
434 // mode register write; called by the interface after synchronization
435 virtual void engine_mode_write(uint8_t data) override;
436
437 protected:
438 // assign the current set of operators to channels
439 void assign_operators();
440
441 // update the state of the given timer
442 void update_timer(uint32_t which, uint32_t enable, int32_t delta_clocks);
443
444 // internal state
445 ymfm_interface &m_intf; // reference to the system interface
446 uint32_t m_env_counter; // envelope counter; low 2 bits are sub-counter
447 uint8_t m_status; // current status register
448 uint8_t m_clock_prescale; // prescale factor (2/3/6)
449 uint8_t m_irq_mask; // mask of which bits signal IRQs
450 uint8_t m_irq_state; // current IRQ state
451 uint8_t m_timer_running[2]; // current timer running state
452 uint8_t m_total_clocks; // low 8 bits of the total number of clocks processed
453 uint32_t m_active_channels; // mask of active channels (computed by prepare)
454 uint32_t m_modified_channels; // mask of channels that have been modified
455 uint32_t m_prepare_count; // counter to do periodic prepare sweeps
456 RegisterType m_regs; // register accessor
457 std::unique_ptr<fm_channel<RegisterType>> m_channel[CHANNELS]; // channel pointers
458 std::unique_ptr<fm_operator<RegisterType>> m_operator[OPERATORS]; // operator pointers
459 #if (DEBUG_LOG_WAVFILES)
460 mutable ymfm_wavfile<1> m_wavfile[CHANNELS]; // for debugging
461 #endif
462 };
463
464 }
465
466 #endif // YMFM_FM_H