Debian Codegraph @

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