Debian Codegraph @

BambooTracker/chip/opna.cpp

raw
1 /*
2 * Copyright (C) 2018-2023 Rerrah
3 *
4 * Permission is hereby granted, free of charge, to any person
5 * obtaining a copy of this software and associated documentation
6 * files (the "Software"), to deal in the Software without
7 * restriction, including without limitation the rights to use,
8 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following
11 * conditions:
12 *
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 * OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26 #include "opna.hpp"
27 #include <cstdint>
28 #include <cmath>
29 #include <algorithm>
30 #include "register_write_logger.hpp"
31 #include "mame/mame_2608.hpp"
32 #include "nuked/nuked_2608.hpp"
33 #include "ymfm/ymfm_2608.hpp"
34
35 #ifdef USE_REAL_CHIP
36 #include "scci/scci_wrapper.hpp"
37 #include "c86ctl/c86ctl_wrapper.hpp"
38 #endif
39
40 namespace chip
41 {
42 namespace
43 {
44 constexpr double VOL_REDUC_ = 7.5;
45
46 // 55466Hz: FM internal rate
47 constexpr int DEFAULT_AUTO_RATE = 55466;
48
49 enum SoundSourceIndex : int { FM = 0, SSG = 1 };
50
51 enum WriteMode : int { WAIT_MODE = 0, IMMEDIATE_MODE = 1 };
52
53 inline double clamp(double value, double low, double high)
54 {
55 return std::min<double>(std::max<double>(value, low), high);
56 }
57
58 void gainSamples(sample** samples, size_t nSamples, double gain)
59 {
60 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
61 std::transform(samples[pan], samples[pan] + nSamples, samples[pan],
62 [gain](sample s) { return static_cast<sample>(s * gain); });
63 }
64 }
65 }
66
67 size_t OPNA::count_ = 0;
68
69 OPNA::OPNA(OpnaEmulator emu, int clock, int rate, size_t maxDuration, size_t dramSize,
70 std::unique_ptr<AbstractResampler> fmResampler, std::unique_ptr<AbstractResampler> ssgResampler,
71 std::shared_ptr<AbstractRegisterWriteLogger> logger)
72 : Chip(count_++, clock, rate, DEFAULT_AUTO_RATE, maxDuration,
73 std::move(fmResampler), std::move(ssgResampler),
74 logger),
75 volumeFm_(0),
76 volumeSsg_(0),
77 dramSize_(dramSize),
78 rcIntf_(std::make_unique<SimpleRealChipInterface>()),
79 isForcedRegWrite_(false),
80 waitRestFm_(0),
81 waitRestSsg2_(0),
82 writeFuncs {
83 // Wait mode
84 { &OPNA::enqueueData, &OPNA::storeBufferForWait },
85 // Immediate mode
86 { &OPNA::writeDataImmediately, &OPNA::storeBufferForImmediate }
87 },
88 writeFunc(&writeFuncs[WAIT_MODE])
89 {
90 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
91 tmpBuf_[pan] = new sample[CHIP_SMPL_BUF_SIZE_];
92 }
93
94 switch (emu) {
95 default:
96 fprintf(stderr, "Unknown emulator choice. Using the default.\n");
97 /* fall through */
98 case OpnaEmulator::Mame:
99 fprintf(stderr, "Using emulator: MAME YM2608\n");
100 intf_ = std::make_unique<Mame2608>();
101 break;
102 case OpnaEmulator::Nuked:
103 fprintf(stderr, "Using emulator: Nuked OPN-Mod\n");
104 intf_ = std::make_unique<Nuked2608>();
105 break;
106 case OpnaEmulator::Ymfm:
107 fprintf(stderr, "Using emulator: ymfm\n");
108 intf_ = std::make_unique<Ymfm2608>();
109 break;
110 }
111
112 funcSetRate(rate);
113
114 internalRate_[FM] = intf_->startDevice(clock, internalRate_[SSG], dramSize);
115 rate2_ = static_cast<size_t>((internalRate_[SSG] << 1) / internalRate_[FM]); // Should be "9"
116
117 initResampler();
118
119 setVolumeFM(0);
120 setVolumeSSG(0);
121
122 reset();
123 }
124
125 OPNA::~OPNA()
126 {
127 intf_->stopDevice();
128 --count_;
129
130 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
131 delete[] tmpBuf_[pan];
132 }
133 }
134
135 void OPNA::resetSpecific()
136 {
137 isForcedRegWrite_ = false;
138 regWrites_.clear();
139 forcedRegWrites_.clear();
140 waitRestFm_ = 0;
141 waitRestSsg2_ = 0;
142
143 intf_->resetDevice();
144 rcIntf_->reset();
145 }
146
147 void OPNA::setImmediateWriteMode(bool enabled) noexcept
148 {
149 writeFunc = &writeFuncs[enabled ? IMMEDIATE_MODE : WAIT_MODE];
150 }
151
152 bool OPNA::isImmediateWriteMode() const noexcept
153 {
154 return writeFunc == &writeFuncs[IMMEDIATE_MODE];
155 }
156
157 void OPNA::setRegister(uint32_t offset, uint8_t value)
158 {
159 std::lock_guard<std::mutex> lg(mutex_);
160
161 if (logger_) {
162 logger_->recordRegisterChange(offset, value);
163 }
164 else {
165 (this->*writeFunc->setRegister)(offset, value);
166 }
167
168 rcIntf_->setRegister(offset, value);
169 }
170
171 void OPNA::enqueueData(uint32_t offset, uint8_t value)
172 {
173 if (isForcedRegWrite_) {
174 forcedRegWrites_.push_back({ offset & 0x0ff, value, !(offset & 0x100) });
175 }
176 else {
177 regWrites_.push_back({ offset & 0x0ff, value, !(offset & 0x100) });
178 }
179 }
180
181 void OPNA::writeDataImmediately(uint32_t offset, uint8_t value)
182 {
183 if (offset & 0x100) {
184 intf_->writeAddressToPortB(offset & 0xff);
185 intf_->writeDataToPortB(value & 0xff);
186 }
187 else {
188 intf_->writeAddressToPortA(offset & 0xff);
189 intf_->writeDataToPortA(value & 0xff);
190 }
191 }
192
193 uint8_t OPNA::getRegister(uint32_t offset) const
194 {
195 if (offset & 0x100) intf_->writeAddressToPortB(offset & 0xff);
196 else intf_->writeAddressToPortA(offset & 0xff);
197 return intf_->readData();
198 }
199
200 void OPNA::setVolumeFM(double dB)
201 {
202 std::lock_guard<std::mutex> lg(mutex_);
203 volumeFm_ = dB;
204 busVolumeRatio_[FM] = std::pow(10.0, (dB - VOL_REDUC_) / 20.0) / VOLUME_RATIO_MOD_;
205 updateVolumeRatio(FM);
206 }
207
208 void OPNA::setVolumeSSG(double dB)
209 {
210 std::lock_guard<std::mutex> lg(mutex_);
211 volumeSsg_ = dB;
212 busVolumeRatio_[SSG] = std::pow(10.0, (dB - VOL_REDUC_) / 20.0) / VOLUME_RATIO_MOD_;
213 updateVolumeRatio(SSG);
214
215 rcIntf_->setSSGVolume(dB);
216 }
217
218 size_t OPNA::getDRAMSize() const noexcept
219 {
220 return dramSize_;
221 }
222
223 bool OPNA::mix(int16_t* stream, size_t nSamples)
224 {
225 std::lock_guard<std::mutex> lg(mutex_);
226
227 size_t pointFm = 0;
228 size_t pointSsg = 0;
229
230 // Store samples to internal buffer
231 bool result = (this->*writeFunc->storeBuffer)(nSamples, pointFm, pointSsg);
232 if (!result) return false;
233
234 // Gain volume
235 gainSamples(buffer_[FM], pointFm, volumeRatio_[FM]);
236 gainSamples(buffer_[SSG], pointSsg, volumeRatio_[SSG]);
237
238 // Resampling
239 sample** bufFM = resampler_[FM]->interpolate(buffer_[FM], nSamples, pointFm);
240 sample** bufSSG = resampler_[SSG]->interpolate(buffer_[SSG], nSamples, pointSsg);
241
242 // Mix
243 int16_t* p = stream;
244 for (size_t i = 0; i < nSamples; ++i) {
245 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
246 *p++ = static_cast<int16_t>(clamp((bufFM[pan][i] + bufSSG[pan][i]) * VOLUME_RATIO_MOD_, -32768, 32767));
247 }
248 }
249
250 return true;
251 }
252
253 /**
254 * @brief OPNA::dequeueData
255 * @return wait count as FM internal sample rate
256 */
257 size_t OPNA::dequeueData()
258 {
259 size_t waitCount = 0;
260
261 if (!forcedRegWrites_.empty()) {
262 auto& unit = forcedRegWrites_.front();
263 if (unit.isPortA_) {
264 intf_->writeAddressToPortA(unit.address & 0xff);
265 intf_->writeDataToPortA(unit.data & 0xff);
266 }
267 else {
268 intf_->writeAddressToPortB(unit.address & 0xff);
269 intf_->writeDataToPortB(unit.data & 0xff);
270 }
271 waitCount = unit.address == 0x10 ? 4 : 1;
272 forcedRegWrites_.pop_front();
273 }
274 else if (!regWrites_.empty()) {
275 auto& unit = regWrites_.front();
276 if (unit.isPortA_) {
277 intf_->writeAddressToPortA(unit.address & 0xff);
278 intf_->writeDataToPortA(unit.data & 0xff);
279 }
280 else {
281 intf_->writeAddressToPortB(unit.address & 0xff);
282 intf_->writeDataToPortB(unit.data & 0xff);
283 }
284 waitCount = unit.address == 0x10 ? 4 : 1;
285 regWrites_.pop_front();
286 }
287
288 return waitCount;
289 }
290
291 bool OPNA::storeBufferForImmediate(size_t nSamples, size_t& pointFm, size_t& pointSsg)
292 {
293 bool ok = false;
294 size_t intrSizeFm = resampler_[FM]->calculateInternalSampleSize(nSamples, ok);
295 if (!ok) return false;
296 intf_->updateStream(tmpBuf_, intrSizeFm);
297 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
298 std::copy_n(tmpBuf_[pan], intrSizeFm, buffer_[FM][pan] + pointFm);
299 }
300 pointFm += intrSizeFm;
301
302 size_t intrSizeSsg = resampler_[SSG]->calculateInternalSampleSize(nSamples, ok);
303 if (!ok) return false;
304 intf_->updateSsgStream(tmpBuf_, intrSizeSsg);
305 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
306 std::copy_n(tmpBuf_[pan], intrSizeSsg, buffer_[SSG][pan] + pointSsg);
307 }
308 pointSsg += intrSizeSsg;
309
310 return true;
311 }
312
313 void OPNA::flushWait(size_t& pointFm, size_t maxFm, size_t& pointSsg2, size_t maxSsg2)
314 {
315 size_t sizeFm = std::min(waitRestFm_, maxFm - pointFm);
316 intf_->updateStream(tmpBuf_, sizeFm);
317 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
318 std::copy_n(tmpBuf_[pan], sizeFm, buffer_[FM][pan] + pointFm);
319 }
320 waitRestFm_ -= sizeFm;
321 pointFm += sizeFm;
322
323 size_t pointSsg = pointSsg2 >> 1;
324 size_t endPointSsg2 = std::min(pointSsg2 + waitRestSsg2_, maxSsg2);
325 size_t sizeSsg = (endPointSsg2 >> 1) - pointSsg;
326 intf_->updateSsgStream(tmpBuf_, sizeSsg);
327 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
328 std::copy_n(tmpBuf_[pan], sizeSsg, buffer_[SSG][pan] + pointSsg);
329 }
330 size_t sizeSsg2 = endPointSsg2 - pointSsg2;
331 waitRestSsg2_ -= sizeSsg2;
332 pointSsg2 += sizeSsg2;
333 }
334
335 bool OPNA::storeBufferForWait(size_t nSamples, size_t& pointFm, size_t& pointSsg)
336 {
337 bool ok = false;
338 size_t intrSizeFm = resampler_[FM]->calculateInternalSampleSize(nSamples, ok);
339 if (!ok) return false;
340 size_t intrSizeSsg2 = resampler_[SSG]->calculateInternalSampleSize(nSamples, ok) << 1;
341 if (!ok) return false;
342
343 size_t pointSsg2 = pointSsg << 1;
344
345 // Flush previous wait
346 flushWait(pointFm, intrSizeFm, pointSsg2, intrSizeSsg2);
347
348 // Wait and generate
349 while (pointFm < intrSizeFm || pointSsg2 < intrSizeSsg2) {
350 size_t waitCount = dequeueData();
351 if (!waitCount) break;
352
353 // Add wait count
354 waitRestFm_ += waitCount;
355 waitRestSsg2_ += rate2_ * waitCount;
356 flushWait(pointFm, intrSizeFm, pointSsg2, intrSizeSsg2);
357 }
358
359 // Generate rest samples
360 size_t sizeFm = intrSizeFm - pointFm;
361 intf_->updateStream(tmpBuf_, sizeFm);
362 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
363 std::copy_n(tmpBuf_[pan], sizeFm, buffer_[FM][pan] + pointFm);
364 }
365 if (sizeFm <= waitRestFm_) waitRestFm_ -= sizeFm;
366 pointFm += sizeFm;
367
368 pointSsg = pointSsg2 >> 1;
369 size_t sizeSsg = (intrSizeSsg2 >> 1) - pointSsg;
370 intf_->updateSsgStream(tmpBuf_, sizeSsg);
371 for (int pan = STEREO_LEFT; pan <= STEREO_RIGHT; ++pan) {
372 std::copy_n(tmpBuf_[pan], sizeSsg, buffer_[SSG][pan] + pointSsg);
373 }
374 size_t sizeSsg2 = intrSizeSsg2 - pointSsg2;
375 if (sizeSsg2 <= waitRestSsg2_) waitRestSsg2_ -= sizeSsg2;
376 pointSsg = (pointSsg2 + sizeSsg2) >> 1;
377
378 return true;
379 }
380
381 void OPNA::setFmResampler(std::unique_ptr<AbstractResampler> resampler)
382 {
383 std::lock_guard<std::mutex> lg(mutex_);
384 resampler_[FM] = std::move(resampler);
385 initResampler();
386 }
387
388 void OPNA::setSsgResampler(std::unique_ptr<AbstractResampler> resampler)
389 {
390 std::lock_guard<std::mutex> lg(mutex_);
391 resampler_[SSG] = std::move(resampler);
392 initResampler();
393 }
394
395 void OPNA::connectToRealChip(RealChipInterfaceType type, RealChipInterfaceGeneratorFunc* f)
396 {
397 switch (type) {
398 default: // Fall through
399 case RealChipInterfaceType::NONE:
400 if (rcIntf_->getType() != RealChipInterfaceType::NONE)
401 rcIntf_ = std::make_unique<SimpleRealChipInterface>();
402 rcIntf_->createInstance(f);
403 break;
404 #ifdef USE_REAL_CHIP
405 case RealChipInterfaceType::SCCI:
406 if (rcIntf_->getType() != RealChipInterfaceType::SCCI)
407 rcIntf_ = std::make_unique<Scci>();
408 rcIntf_->createInstance(f);
409 break;
410 case RealChipInterfaceType::C86CTL:
411 if (rcIntf_->getType() != RealChipInterfaceType::C86CTL)
412 rcIntf_ = std::make_unique<C86ctl>();
413 rcIntf_->createInstance(f);
414 break;
415 #endif
416 }
417 }
418
419 RealChipInterfaceType OPNA::getRealChipInterfaceType() const
420 {
421 return rcIntf_->getType();
422 }
423
424 bool OPNA::hasConnectedToRealChip() const
425 {
426 return rcIntf_->hasConnected();
427 }
428 }