Debian Codegraph @

thirdparty/ymfm/src/ymfm.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_H
32 #define YMFM_H
33
34 #pragma once
35
36 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
37 #define _CRT_SECURE_NO_WARNINGS
38 #endif
39
40 #include <cassert>
41 #include <cstdint>
42 #include <cstdio>
43 #include <cstring>
44 #include <algorithm>
45 #include <array>
46 #include <memory>
47 #include <string>
48 #include <vector>
49
50 namespace ymfm
51 {
52
53 //*********************************************************
54 // DEBUGGING
55 //*********************************************************
56
57 class debug
58 {
59 public:
60 // masks to help isolate specific channels
61 static constexpr uint32_t GLOBAL_FM_CHANNEL_MASK = 0xffffffff;
62 static constexpr uint32_t GLOBAL_ADPCM_A_CHANNEL_MASK = 0xffffffff;
63 static constexpr uint32_t GLOBAL_ADPCM_B_CHANNEL_MASK = 0xffffffff;
64 static constexpr uint32_t GLOBAL_PCM_CHANNEL_MASK = 0xffffffff;
65
66 // types of logging
67 static constexpr bool LOG_FM_WRITES = false;
68 static constexpr bool LOG_KEYON_EVENTS = false;
69 static constexpr bool LOG_UNEXPECTED_READ_WRITES = false;
70
71 // helpers to write based on the log type
72 template<typename... Params> static void log_fm_write(Params &&... args) { if (LOG_FM_WRITES) log(args...); }
73 template<typename... Params> static void log_keyon(Params &&... args) { if (LOG_KEYON_EVENTS) log(args...); }
74 template<typename... Params> static void log_unexpected_read_write(Params &&... args) { if (LOG_UNEXPECTED_READ_WRITES) log(args...); }
75
76 // downstream helper to output log data; defaults to printf
77 template<typename... Params> static void log(Params &&... args) { printf(args...); }
78 };
79
80
81
82 //*********************************************************
83 // GLOBAL HELPERS
84 //*********************************************************
85
86 //-------------------------------------------------
87 // bitfield - extract a bitfield from the given
88 // value, starting at bit 'start' for a length of
89 // 'length' bits
90 //-------------------------------------------------
91
92 inline uint32_t bitfield(uint32_t value, int start, int length = 1)
93 {
94 return (value >> start) & ((1 << length) - 1);
95 }
96
97
98 //-------------------------------------------------
99 // clamp - clamp between the minimum and maximum
100 // values provided
101 //-------------------------------------------------
102
103 inline int32_t clamp(int32_t value, int32_t minval, int32_t maxval)
104 {
105 if (value < minval)
106 return minval;
107 if (value > maxval)
108 return maxval;
109 return value;
110 }
111
112
113 //-------------------------------------------------
114 // count_leading_zeros - return the number of
115 // leading zeros in a 32-bit value; CPU-optimized
116 // versions for various architectures are included
117 // below
118 //-------------------------------------------------
119
120 #if defined(__GNUC__)
121
122 inline uint8_t count_leading_zeros(uint32_t value)
123 {
124 if (value == 0)
125 return 32;
126 return __builtin_clz(value);
127 }
128
129 #elif defined(_MSC_VER)
130
131 inline uint8_t count_leading_zeros(uint32_t value)
132 {
133 unsigned long index;
134 return _BitScanReverse(&index, value) ? uint8_t(31U - index) : 32U;
135 }
136
137 #else
138
139 inline uint8_t count_leading_zeros(uint32_t value)
140 {
141 if (value == 0)
142 return 32;
143 uint8_t count;
144 for (count = 0; int32_t(value) >= 0; count++)
145 value <<= 1;
146 return count;
147 }
148
149 #endif
150
151
152 // Many of the Yamaha FM chips emit a floating-point value, which is sent to
153 // a DAC for processing. The exact format of this floating-point value is
154 // documented below. This description only makes sense if the "internal"
155 // format treats sign as 1=positive and 0=negative, so the helpers below
156 // presume that.
157 //
158 // Internal OPx data 16-bit signed data Exp Sign Mantissa
159 // ================= ================= === ==== ========
160 // 1 1xxxxxxxx------ -> 0 1xxxxxxxx------ -> 111 1 1xxxxxxx
161 // 1 01xxxxxxxx----- -> 0 01xxxxxxxx----- -> 110 1 1xxxxxxx
162 // 1 001xxxxxxxx---- -> 0 001xxxxxxxx---- -> 101 1 1xxxxxxx
163 // 1 0001xxxxxxxx--- -> 0 0001xxxxxxxx--- -> 100 1 1xxxxxxx
164 // 1 00001xxxxxxxx-- -> 0 00001xxxxxxxx-- -> 011 1 1xxxxxxx
165 // 1 000001xxxxxxxx- -> 0 000001xxxxxxxx- -> 010 1 1xxxxxxx
166 // 1 000000xxxxxxxxx -> 0 000000xxxxxxxxx -> 001 1 xxxxxxxx
167 // 0 111111xxxxxxxxx -> 1 111111xxxxxxxxx -> 001 0 xxxxxxxx
168 // 0 111110xxxxxxxx- -> 1 111110xxxxxxxx- -> 010 0 0xxxxxxx
169 // 0 11110xxxxxxxx-- -> 1 11110xxxxxxxx-- -> 011 0 0xxxxxxx
170 // 0 1110xxxxxxxx--- -> 1 1110xxxxxxxx--- -> 100 0 0xxxxxxx
171 // 0 110xxxxxxxx---- -> 1 110xxxxxxxx---- -> 101 0 0xxxxxxx
172 // 0 10xxxxxxxx----- -> 1 10xxxxxxxx----- -> 110 0 0xxxxxxx
173 // 0 0xxxxxxxx------ -> 1 0xxxxxxxx------ -> 111 0 0xxxxxxx
174
175 //-------------------------------------------------
176 // encode_fp - given a 32-bit signed input value
177 // convert it to a signed 3.10 floating-point
178 // value
179 //-------------------------------------------------
180
181 inline int16_t encode_fp(int32_t value)
182 {
183 // handle overflows first
184 if (value < -32768)
185 return (7 << 10) | 0x000;
186 if (value > 32767)
187 return (7 << 10) | 0x3ff;
188
189 // we need to count the number of leading sign bits after the sign
190 // we can use count_leading_zeros if we invert negative values
191 int32_t scanvalue = value ^ (int32_t(value) >> 31);
192
193 // exponent is related to the number of leading bits starting from bit 14
194 int exponent = 7 - count_leading_zeros(scanvalue << 17);
195
196 // smallest exponent value allowed is 1
197 exponent = std::max(exponent, 1);
198
199 // mantissa
200 int32_t mantissa = value >> (exponent - 1);
201
202 // assemble into final form, inverting the sign
203 return ((exponent << 10) | (mantissa & 0x3ff)) ^ 0x200;
204 }
205
206
207 //-------------------------------------------------
208 // decode_fp - given a 3.10 floating-point value,
209 // convert it to a signed 16-bit value
210 //-------------------------------------------------
211
212 inline int16_t decode_fp(int16_t value)
213 {
214 // invert the sign and the exponent
215 value ^= 0x1e00;
216
217 // shift mantissa up to 16 bits then apply inverted exponent
218 return int16_t(value << 6) >> bitfield(value, 10, 3);
219 }
220
221
222 //-------------------------------------------------
223 // roundtrip_fp - compute the result of a round
224 // trip through the encode/decode process above
225 //-------------------------------------------------
226
227 inline int16_t roundtrip_fp(int32_t value)
228 {
229 // handle overflows first
230 if (value < -32768)
231 return -32768;
232 if (value > 32767)
233 return 32767;
234
235 // we need to count the number of leading sign bits after the sign
236 // we can use count_leading_zeros if we invert negative values
237 int32_t scanvalue = value ^ (int32_t(value) >> 31);
238
239 // exponent is related to the number of leading bits starting from bit 14
240 int exponent = 7 - count_leading_zeros(scanvalue << 17);
241
242 // smallest exponent value allowed is 1
243 exponent = std::max(exponent, 1);
244
245 // apply the shift back and forth to zero out bits that are lost
246 exponent -= 1;
247 int32_t mask = (1 << exponent) - 1;
248 return value & ~mask;
249 }
250
251
252
253 //*********************************************************
254 // HELPER CLASSES
255 //*********************************************************
256
257 // various envelope states
258 enum envelope_state : uint32_t
259 {
260 EG_DEPRESS = 0, // OPLL only; set EG_HAS_DEPRESS to enable
261 EG_ATTACK = 1,
262 EG_DECAY = 2,
263 EG_SUSTAIN = 3,
264 EG_RELEASE = 4,
265 EG_REVERB = 5, // OPQ/OPZ only; set EG_HAS_REVERB to enable
266 EG_STATES = 6
267 };
268
269 // external I/O access classes
270 enum access_class : uint32_t
271 {
272 ACCESS_IO = 0,
273 ACCESS_ADPCM_A,
274 ACCESS_ADPCM_B,
275 ACCESS_PCM,
276 ACCESS_CLASSES
277 };
278
279
280
281 //*********************************************************
282 // HELPER CLASSES
283 //*********************************************************
284
285 // ======================> ymfm_output
286
287 // struct containing an array of output values
288 template<int NumOutputs>
289 struct ymfm_output
290 {
291 // clear all outputs to 0
292 ymfm_output &clear()
293 {
294 for (uint32_t index = 0; index < NumOutputs; index++)
295 data[index] = 0;
296 return *this;
297 }
298
299 // clamp all outputs to a 16-bit signed value
300 ymfm_output &clamp16()
301 {
302 for (uint32_t index = 0; index < NumOutputs; index++)
303 data[index] = clamp(data[index], -32768, 32767);
304 return *this;
305 }
306
307 // run each output value through the floating-point processor
308 ymfm_output &roundtrip_fp()
309 {
310 for (uint32_t index = 0; index < NumOutputs; index++)
311 data[index] = ymfm::roundtrip_fp(data[index]);
312 return *this;
313 }
314
315 // internal state
316 int32_t data[NumOutputs];
317 };
318
319
320 // ======================> ymfm_wavfile
321
322 // this class is a debugging helper that accumulates data and writes it to wav files
323 template<int Channels>
324 class ymfm_wavfile
325 {
326 public:
327 // construction
328 ymfm_wavfile(uint32_t samplerate = 44100) :
329 m_samplerate(samplerate)
330 {
331 }
332
333 // configuration
334 ymfm_wavfile &set_index(uint32_t index) { m_index = index; return *this; }
335 ymfm_wavfile &set_samplerate(uint32_t samplerate) { m_samplerate = samplerate; return *this; }
336
337 // destruction
338 ~ymfm_wavfile()
339 {
340 if (!m_buffer.empty())
341 {
342 // create file
343 char name[20];
344 snprintf(&name[0], sizeof(name), "wavlog-%02d.wav", m_index);
345 FILE *out = fopen(name, "wb");
346
347 // make the wav file header
348 uint8_t header[44];
349 memcpy(&header[0], "RIFF", 4);
350 *(uint32_t *)&header[4] = m_buffer.size() * 2 + 44 - 8;
351 memcpy(&header[8], "WAVE", 4);
352 memcpy(&header[12], "fmt ", 4);
353 *(uint32_t *)&header[16] = 16;
354 *(uint16_t *)&header[20] = 1;
355 *(uint16_t *)&header[22] = Channels;
356 *(uint32_t *)&header[24] = m_samplerate;
357 *(uint32_t *)&header[28] = m_samplerate * 2 * Channels;
358 *(uint16_t *)&header[32] = 2 * Channels;
359 *(uint16_t *)&header[34] = 16;
360 memcpy(&header[36], "data", 4);
361 *(uint32_t *)&header[40] = m_buffer.size() * 2 + 44 - 44;
362
363 // write header then data
364 fwrite(&header[0], 1, sizeof(header), out);
365 fwrite(&m_buffer[0], 2, m_buffer.size(), out);
366 fclose(out);
367 }
368 }
369
370 // add data to the file
371 template<int Outputs>
372 void add(ymfm_output<Outputs> output)
373 {
374 int16_t sum[Channels] = { 0 };
375 for (int index = 0; index < Outputs; index++)
376 sum[index % Channels] += output.data[index];
377 for (int index = 0; index < Channels; index++)
378 m_buffer.push_back(sum[index]);
379 }
380
381 // add data to the file, using a reference
382 template<int Outputs>
383 void add(ymfm_output<Outputs> output, ymfm_output<Outputs> const &ref)
384 {
385 int16_t sum[Channels] = { 0 };
386 for (int index = 0; index < Outputs; index++)
387 sum[index % Channels] += output.data[index] - ref.data[index];
388 for (int index = 0; index < Channels; index++)
389 m_buffer.push_back(sum[index]);
390 }
391
392 private:
393 // internal state
394 uint32_t m_index;
395 uint32_t m_samplerate;
396 std::vector<int16_t> m_buffer;
397 };
398
399
400 // ======================> ymfm_saved_state
401
402 // this class contains a managed vector of bytes that is used to save and
403 // restore state
404 class ymfm_saved_state
405 {
406 public:
407 // construction
408 ymfm_saved_state(std::vector<uint8_t> &buffer, bool saving) :
409 m_buffer(buffer),
410 m_offset(saving ? -1 : 0)
411 {
412 if (saving)
413 buffer.resize(0);
414 }
415
416 // are we saving or restoring?
417 bool saving() const { return (m_offset < 0); }
418
419 // generic save/restore
420 template<typename DataType>
421 void save_restore(DataType &data)
422 {
423 if (saving())
424 save(data);
425 else
426 restore(data);
427 }
428
429 public:
430 // save data to the buffer
431 void save(bool &data) { write(data ? 1 : 0); }
432 void save(int8_t &data) { write(data); }
433 void save(uint8_t &data) { write(data); }
434 void save(int16_t &data) { write(uint8_t(data)).write(data >> 8); }
435 void save(uint16_t &data) { write(uint8_t(data)).write(data >> 8); }
436 void save(int32_t &data) { write(data).write(data >> 8).write(data >> 16).write(data >> 24); }
437 void save(uint32_t &data) { write(data).write(data >> 8).write(data >> 16).write(data >> 24); }
438 void save(envelope_state &data) { write(uint8_t(data)); }
439 template<typename DataType, int Count>
440 void save(DataType (&data)[Count]) { for (uint32_t index = 0; index < Count; index++) save(data[index]); }
441
442 // restore data from the buffer
443 void restore(bool &data) { data = read() ? true : false; }
444 void restore(int8_t &data) { data = read(); }
445 void restore(uint8_t &data) { data = read(); }
446 void restore(int16_t &data) { data = read(); data |= read() << 8; }
447 void restore(uint16_t &data) { data = read(); data |= read() << 8; }
448 void restore(int32_t &data) { data = read(); data |= read() << 8; data |= read() << 16; data |= read() << 24; }
449 void restore(uint32_t &data) { data = read(); data |= read() << 8; data |= read() << 16; data |= read() << 24; }
450 void restore(envelope_state &data) { data = envelope_state(read()); }
451 template<typename DataType, int Count>
452 void restore(DataType (&data)[Count]) { for (uint32_t index = 0; index < Count; index++) restore(data[index]); }
453
454 // internal helper
455 ymfm_saved_state &write(uint8_t data) { m_buffer.push_back(data); return *this; }
456 uint8_t read() { return (m_offset < int32_t(m_buffer.size())) ? m_buffer[m_offset++] : 0; }
457
458 // internal state
459 std::vector<uint8_t> &m_buffer;
460 int32_t m_offset;
461 };
462
463
464
465 //*********************************************************
466 // INTERFACE CLASSES
467 //*********************************************************
468
469 // ======================> ymfm_engine_callbacks
470
471 // this class represents functions in the engine that the ymfm_interface
472 // needs to be able to call; it is represented here as a separate interface
473 // that is independent of the actual engine implementation
474 class ymfm_engine_callbacks
475 {
476 public:
477 virtual ~ymfm_engine_callbacks() = default;
478
479 // timer callback; called by the interface when a timer fires
480 virtual void engine_timer_expired(uint32_t tnum) = 0;
481
482 // check interrupts; called by the interface after synchronization
483 virtual void engine_check_interrupts() = 0;
484
485 // mode register write; called by the interface after synchronization
486 virtual void engine_mode_write(uint8_t data) = 0;
487 };
488
489
490 // ======================> ymfm_interface
491
492 // this class represents the interface between the fm_engine and the outside
493 // world; it provides hooks for timers, synchronization, and I/O
494 class ymfm_interface
495 {
496 // the engine is our friend
497 template<typename RegisterType> friend class fm_engine_base;
498
499 public:
500 virtual ~ymfm_interface() = default;
501
502 // the following functions must be implemented by any derived classes; the
503 // default implementations are sufficient for some minimal operation, but will
504 // likely need to be overridden to integrate with the outside world; they are
505 // all prefixed with ymfm_ to reduce the likelihood of namespace collisions
506
507 //
508 // timing and synchronizaton
509 //
510
511 // the chip implementation calls this when a write happens to the mode
512 // register, which could affect timers and interrupts; our responsibility
513 // is to ensure the system is up to date before calling the engine's
514 // engine_mode_write() method
515 virtual void ymfm_sync_mode_write(uint8_t data) { m_engine->engine_mode_write(data); }
516
517 // the chip implementation calls this when the chip's status has changed,
518 // which may affect the interrupt state; our responsibility is to ensure
519 // the system is up to date before calling the engine's
520 // engine_check_interrupts() method
521 virtual void ymfm_sync_check_interrupts() { m_engine->engine_check_interrupts(); }
522
523 // the chip implementation calls this when one of the two internal timers
524 // has changed state; our responsibility is to arrange to call the engine's
525 // engine_timer_expired() method after the provided number of clocks; if
526 // duration_in_clocks is negative, we should cancel any outstanding timers
527 virtual void ymfm_set_timer(uint32_t tnum, int32_t duration_in_clocks) { }
528
529 // the chip implementation calls this to indicate that the chip should be
530 // considered in a busy state until the given number of clocks has passed;
531 // our responsibility is to compute and remember the ending time based on
532 // the chip's clock for later checking
533 virtual void ymfm_set_busy_end(uint32_t clocks) { }
534
535 // the chip implementation calls this to see if the chip is still currently
536 // is a busy state, as specified by a previous call to ymfm_set_busy_end();
537 // our responsibility is to compare the current time against the previously
538 // noted busy end time and return true if we haven't yet passed it
539 virtual bool ymfm_is_busy() { return false; }
540
541 //
542 // I/O functions
543 //
544
545 // the chip implementation calls this when the state of the IRQ signal has
546 // changed due to a status change; our responsibility is to respond as
547 // needed to the change in IRQ state, signaling any consumers
548 virtual void ymfm_update_irq(bool asserted) { }
549
550 // the chip implementation calls this whenever data is read from outside
551 // of the chip; our responsibility is to provide the data requested
552 virtual uint8_t ymfm_external_read(access_class type, uint32_t address) { return 0; }
553
554 // the chip implementation calls this whenever data is written outside
555 // of the chip; our responsibility is to pass the written data on to any consumers
556 virtual void ymfm_external_write(access_class type, uint32_t address, uint8_t data) { }
557
558 protected:
559 // pointer to engine callbacks -- this is set directly by the engine at
560 // construction time
561 ymfm_engine_callbacks *m_engine;
562 };
563
564 }
565
566 #endif // YMFM_H