OpenTTD Source: src/music/dmusic.cpp Source File

OpenTTD Source 15.0-beta1

dmusic.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#define INITGUID
11#include "../stdafx.h"
12#ifdef WIN32_LEAN_AND_MEAN
13# undef WIN32_LEAN_AND_MEAN // Don't exclude rarely-used stuff from Windows headers
14#endif
15#include "../debug.h"
16#include "../os/windows/win32.h"
17#include "../core/mem_func.hpp"
18#include "../thread.h"
19#include "../fileio_func.h"
20#include "../base_media_base.h"
21#include "dmusic.h"
22#include "midifile.hpp"
23#include "midi.h"
24
25#include <windows.h>
26#include <dmksctrl.h>
27#include <dmusicc.h>
28#include <mutex>
29
30#include "../safeguards.h"
31
32#if defined(_MSC_VER)
33# pragma comment(lib, "ole32.lib")
34#endif /* defined(_MSC_VER) */
35
36 static const int MS_TO_REFTIME = 1000 * 10;
37 static const int MIDITIME_TO_REFTIME = 10;
38
39
40#define FOURCC_INFO mmioFOURCC('I', 'N', 'F', 'O')
41#define FOURCC_fmt mmioFOURCC('f', 'm', 't', ' ')
42#define FOURCC_data mmioFOURCC('d', 'a', 't', 'a')
43
45 struct DLSFile {
47 struct DLSRegion {
48 RGNHEADER hdr;
49 WAVELINK wave;
50 WSMPL wave_sample;
51
52 std::vector<WLOOP> wave_loops;
53 std::vector<CONNECTION> articulators;
54 };
55
57 struct DLSInstrument {
58 INSTHEADER hdr;
59
60 std::vector<CONNECTION> articulators;
61 std::vector<DLSRegion> regions;
62 };
63
65 struct DLSWave {
66 long file_offset;
67
68 PCMWAVEFORMAT fmt;
69 std::vector<BYTE> data;
70
71 WSMPL wave_sample;
72 std::vector<WLOOP> wave_loops;
73 };
74
75 std::vector<DLSInstrument> instruments;
76 std::vector<POOLCUE> pool_cues;
77 std::vector<DLSWave> waves;
78
80 bool LoadFile(const std::string &file);
81
82private:
84 bool ReadDLSArticulation(FileHandle &f, DWORD list_length, std::vector<CONNECTION> &out);
86 bool ReadDLSRegionList(FileHandle &f, DWORD list_length, DLSInstrument &instrument);
88 bool ReadDLSRegion(FileHandle &f, DWORD list_length, std::vector<DLSRegion> &out);
90 bool ReadDLSInstrumentList(FileHandle &f, DWORD list_length);
92 bool ReadDLSInstrument(FileHandle &f, DWORD list_length);
94 bool ReadDLSWaveList(FileHandle &f, DWORD list_length);
96 bool ReadDLSWave(FileHandle &f, DWORD list_length, long offset);
97};
98
100PACK_N(struct ChunkHeader {
101 FOURCC type;
102 DWORD length;
103}, 2);
104
106PACK_N(struct WAVE_DOWNLOAD {
107 DMUS_DOWNLOADINFO dlInfo;
108 ULONG ulOffsetTable[2];
109 DMUS_WAVE dmWave;
110 DMUS_WAVEDATA dmWaveData;
111}, 2);
112
113 struct PlaybackSegment {
114 uint32_t start, end;
115 size_t start_block;
116 bool loop;
117};
118
119static struct {
120 bool shutdown;
121 bool playing;
122 bool do_start;
123 bool do_stop;
124
125 int preload_time;
126 uint8_t new_volume;
127
128 MidiFile next_file;
129 PlaybackSegment next_segment;
130} _playback;
131
133 static std::thread _dmusic_thread;
135 static HANDLE _thread_event = nullptr;
137 static std::mutex _thread_mutex;
138
140 static IDirectMusic *_music = nullptr;
142 static IDirectMusicPort *_port = nullptr;
144 static IDirectMusicBuffer *_buffer = nullptr;
146 static std::vector<IDirectMusicDownload *> _dls_downloads;
147
148
149static FMusicDriver_DMusic iFMusicDriver_DMusic;
150
151
152 bool DLSFile::ReadDLSArticulation(FileHandle &f, DWORD list_length, std::vector<CONNECTION> &out)
153{
154 while (list_length > 0) {
155 ChunkHeader chunk;
156 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
157 list_length -= chunk.length + sizeof(chunk);
158
159 if (chunk.type == FOURCC_ART1) {
160 CONNECTIONLIST conns;
161 if (fread(&conns, sizeof(conns), 1, f) != 1) return false;
162 fseek(f, conns.cbSize - sizeof(conns), SEEK_CUR);
163
164 /* Read all defined articulations. */
165 for (ULONG i = 0; i < conns.cConnections; i++) {
166 CONNECTION con;
167 if (fread(&con, sizeof(con), 1, f) != 1) return false;
168 out.push_back(con);
169 }
170 } else {
171 fseek(f, chunk.length, SEEK_CUR);
172 }
173 }
174
175 return true;
176}
177
178 bool DLSFile::ReadDLSRegion(FileHandle &f, DWORD list_length, std::vector<DLSRegion> &out)
179{
180 DLSRegion &region = out.emplace_back();
181
182 /* Set default values. */
183 region.wave_sample.cbSize = 0;
184
185 while (list_length > 0) {
186 ChunkHeader chunk;
187 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
188 list_length -= chunk.length + sizeof(chunk);
189
190 if (chunk.type == FOURCC_LIST) {
191 /* Unwrap list header. */
192 if (fread(&chunk.type, sizeof(chunk.type), 1, f) != 1) return false;
193 chunk.length -= sizeof(chunk.type);
194 }
195
196 switch (chunk.type) {
197 case FOURCC_RGNH:
198 if (fread(&region.hdr, sizeof(region.hdr), 1, f) != 1) return false;
199 break;
200
201 case FOURCC_WSMP:
202 if (fread(&region.wave_sample, sizeof(region.wave_sample), 1, f) != 1) return false;
203 fseek(f, region.wave_sample.cbSize - sizeof(region.wave_sample), SEEK_CUR);
204
205 /* Read all defined sample loops. */
206 for (ULONG i = 0; i < region.wave_sample.cSampleLoops; i++) {
207 WLOOP loop;
208 if (fread(&loop, sizeof(loop), 1, f) != 1) return false;
209 region.wave_loops.push_back(loop);
210 }
211 break;
212
213 case FOURCC_WLNK:
214 if (fread(&region.wave, sizeof(region.wave), 1, f) != 1) return false;
215 break;
216
217 case FOURCC_LART: // List chunk
218 if (!this->ReadDLSArticulation(f, chunk.length, region.articulators)) return false;
219 break;
220
221 case FOURCC_INFO:
222 /* We don't care about info stuff. */
223 fseek(f, chunk.length, SEEK_CUR);
224 break;
225
226 default:
227 Debug(driver, 7, "DLS: Ignoring unknown chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
228 fseek(f, chunk.length, SEEK_CUR);
229 break;
230 }
231 }
232
233 return true;
234}
235
236 bool DLSFile::ReadDLSRegionList(FileHandle &f, DWORD list_length, DLSInstrument &instrument)
237{
238 while (list_length > 0) {
239 ChunkHeader chunk;
240 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
241 list_length -= chunk.length + sizeof(chunk);
242
243 if (chunk.type == FOURCC_LIST) {
244 FOURCC list_type;
245 if (fread(&list_type, sizeof(list_type), 1, f) != 1) return false;
246
247 if (list_type == FOURCC_RGN) {
248 this->ReadDLSRegion(f, chunk.length - sizeof(list_type), instrument.regions);
249 } else {
250 Debug(driver, 7, "DLS: Ignoring unknown list chunk of type {}{}{}{}", (char)(list_type & 0xFF), (char)((list_type >> 8) & 0xFF), (char)((list_type >> 16) & 0xFF), (char)((list_type >> 24) & 0xFF));
251 fseek(f, chunk.length - sizeof(list_type), SEEK_CUR);
252 }
253 } else {
254 Debug(driver, 7, "DLS: Ignoring chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
255 fseek(f, chunk.length, SEEK_CUR);
256 }
257 }
258
259 return true;
260}
261
262 bool DLSFile::ReadDLSInstrument(FileHandle &f, DWORD list_length)
263{
264 DLSInstrument &instrument = this->instruments.emplace_back();
265
266 while (list_length > 0) {
267 ChunkHeader chunk;
268 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
269 list_length -= chunk.length + sizeof(chunk);
270
271 if (chunk.type == FOURCC_LIST) {
272 /* Unwrap list header. */
273 if (fread(&chunk.type, sizeof(chunk.type), 1, f) != 1) return false;
274 chunk.length -= sizeof(chunk.type);
275 }
276
277 switch (chunk.type) {
278 case FOURCC_INSH:
279 if (fread(&instrument.hdr, sizeof(instrument.hdr), 1, f) != 1) return false;
280 break;
281
282 case FOURCC_LART: // List chunk
283 if (!this->ReadDLSArticulation(f, chunk.length, instrument.articulators)) return false;
284 break;
285
286 case FOURCC_LRGN: // List chunk
287 if (!this->ReadDLSRegionList(f, chunk.length, instrument)) return false;
288 break;
289
290 case FOURCC_INFO:
291 /* We don't care about info stuff. */
292 fseek(f, chunk.length, SEEK_CUR);
293 break;
294
295 default:
296 Debug(driver, 7, "DLS: Ignoring unknown chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
297 fseek(f, chunk.length, SEEK_CUR);
298 break;
299 }
300 }
301
302 return true;
303}
304
305 bool DLSFile::ReadDLSInstrumentList(FileHandle &f, DWORD list_length)
306{
307 while (list_length > 0) {
308 ChunkHeader chunk;
309 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
310 list_length -= chunk.length + sizeof(chunk);
311
312 if (chunk.type == FOURCC_LIST) {
313 FOURCC list_type;
314 if (fread(&list_type, sizeof(list_type), 1, f) != 1) return false;
315
316 if (list_type == FOURCC_INS) {
317 Debug(driver, 6, "DLS: Reading instrument {}", (int)instruments.size());
318
319 if (!this->ReadDLSInstrument(f, chunk.length - sizeof(list_type))) return false;
320 } else {
321 Debug(driver, 7, "DLS: Ignoring unknown list chunk of type {}{}{}{}", (char)(list_type & 0xFF), (char)((list_type >> 8) & 0xFF), (char)((list_type >> 16) & 0xFF), (char)((list_type >> 24) & 0xFF));
322 fseek(f, chunk.length - sizeof(list_type), SEEK_CUR);
323 }
324 } else {
325 Debug(driver, 7, "DLS: Ignoring chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
326 fseek(f, chunk.length, SEEK_CUR);
327 }
328 }
329
330 return true;
331}
332
333 bool DLSFile::ReadDLSWave(FileHandle &f, DWORD list_length, long offset)
334{
335 DLSWave &wave = this->waves.emplace_back();
336
337 /* Set default values. */
338 MemSetT(&wave.wave_sample, 0);
339 wave.wave_sample.cbSize = sizeof(WSMPL);
340 wave.wave_sample.usUnityNote = 60;
341 wave.file_offset = offset; // Store file offset so we can resolve the wave pool table later on.
342
343 while (list_length > 0) {
344 ChunkHeader chunk;
345 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
346 list_length -= chunk.length + sizeof(chunk);
347
348 if (chunk.type == FOURCC_LIST) {
349 /* Unwrap list header. */
350 if (fread(&chunk.type, sizeof(chunk.type), 1, f) != 1) return false;
351 chunk.length -= sizeof(chunk.type);
352 }
353
354 switch (chunk.type) {
355 case FOURCC_fmt:
356 if (fread(&wave.fmt, sizeof(wave.fmt), 1, f) != 1) return false;
357 if (chunk.length > sizeof(wave.fmt)) fseek(f, chunk.length - sizeof(wave.fmt), SEEK_CUR);
358 break;
359
360 case FOURCC_WSMP:
361 if (fread(&wave.wave_sample, sizeof(wave.wave_sample), 1, f) != 1) return false;
362 fseek(f, wave.wave_sample.cbSize - sizeof(wave.wave_sample), SEEK_CUR);
363
364 /* Read all defined sample loops. */
365 for (ULONG i = 0; i < wave.wave_sample.cSampleLoops; i++) {
366 WLOOP loop;
367 if (fread(&loop, sizeof(loop), 1, f) != 1) return false;
368 wave.wave_loops.push_back(loop);
369 }
370 break;
371
372 case FOURCC_data:
373 wave.data.resize(chunk.length);
374 if (fread(&wave.data[0], sizeof(BYTE), wave.data.size(), f) != wave.data.size()) return false;
375 break;
376
377 case FOURCC_INFO:
378 /* We don't care about info stuff. */
379 fseek(f, chunk.length, SEEK_CUR);
380 break;
381
382 default:
383 Debug(driver, 7, "DLS: Ignoring unknown chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
384 fseek(f, chunk.length, SEEK_CUR);
385 break;
386 }
387 }
388
389 return true;
390}
391
392 bool DLSFile::ReadDLSWaveList(FileHandle &f, DWORD list_length)
393{
394 long base_offset = ftell(f);
395
396 while (list_length > 0) {
397 long chunk_offset = ftell(f);
398
399 ChunkHeader chunk;
400 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
401 list_length -= chunk.length + sizeof(chunk);
402
403 if (chunk.type == FOURCC_LIST) {
404 FOURCC list_type;
405 if (fread(&list_type, sizeof(list_type), 1, f) != 1) return false;
406
407 if (list_type == FOURCC_wave) {
408 Debug(driver, 6, "DLS: Reading wave {}", waves.size());
409
410 if (!this->ReadDLSWave(f, chunk.length - sizeof(list_type), chunk_offset - base_offset)) return false;
411 } else {
412 Debug(driver, 7, "DLS: Ignoring unknown list chunk of type {}{}{}{}", (char)(list_type & 0xFF), (char)((list_type >> 8) & 0xFF), (char)((list_type >> 16) & 0xFF), (char)((list_type >> 24) & 0xFF));
413 fseek(f, chunk.length - sizeof(list_type), SEEK_CUR);
414 }
415 } else {
416 Debug(driver, 7, "DLS: Ignoring chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
417 fseek(f, chunk.length, SEEK_CUR);
418 }
419 }
420
421 return true;
422}
423
424 bool DLSFile::LoadFile(const std::string &file)
425{
426 Debug(driver, 2, "DMusic: Try to load DLS file {}", file);
427
428 auto of = FileHandle::Open(file, "rb");
429 if (!of.has_value()) return false;
430 auto &f = *of;
431
432 /* Check DLS file header. */
433 ChunkHeader hdr;
434 FOURCC dls_type;
435 if (fread(&hdr, sizeof(hdr), 1, f) != 1) return false;
436 if (fread(&dls_type, sizeof(dls_type), 1, f) != 1) return false;
437 if (hdr.type != FOURCC_RIFF || dls_type != FOURCC_DLS) return false;
438
439 hdr.length -= sizeof(FOURCC);
440
441 Debug(driver, 2, "DMusic: Parsing DLS file");
442
443 DLSHEADER header;
444 MemSetT(&header, 0);
445
446 /* Iterate over all chunks in the file. */
447 while (hdr.length > 0) {
448 ChunkHeader chunk;
449 if (fread(&chunk, sizeof(chunk), 1, f) != 1) return false;
450 hdr.length -= chunk.length + sizeof(chunk);
451
452 if (chunk.type == FOURCC_LIST) {
453 /* Unwrap list header. */
454 if (fread(&chunk.type, sizeof(chunk.type), 1, f) != 1) return false;
455 chunk.length -= sizeof(chunk.type);
456 }
457
458 switch (chunk.type) {
459 case FOURCC_COLH:
460 if (fread(&header, sizeof(header), 1, f) != 1) return false;
461 break;
462
463 case FOURCC_LINS: // List chunk
464 if (!this->ReadDLSInstrumentList(f, chunk.length)) return false;
465 break;
466
467 case FOURCC_WVPL: // List chunk
468 if (!this->ReadDLSWaveList(f, chunk.length)) return false;
469 break;
470
471 case FOURCC_PTBL:
472 POOLTABLE ptbl;
473 if (fread(&ptbl, sizeof(ptbl), 1, f) != 1) return false;
474 fseek(f, ptbl.cbSize - sizeof(ptbl), SEEK_CUR);
475
476 /* Read all defined cues. */
477 for (ULONG i = 0; i < ptbl.cCues; i++) {
478 POOLCUE cue;
479 if (fread(&cue, sizeof(cue), 1, f) != 1) return false;
480 this->pool_cues.push_back(cue);
481 }
482 break;
483
484 case FOURCC_INFO:
485 /* We don't care about info stuff. */
486 fseek(f, chunk.length, SEEK_CUR);
487 break;
488
489 default:
490 Debug(driver, 7, "DLS: Ignoring unknown chunk {}{}{}{}", (char)(chunk.type & 0xFF), (char)((chunk.type >> 8) & 0xFF), (char)((chunk.type >> 16) & 0xFF), (char)((chunk.type >> 24) & 0xFF));
491 fseek(f, chunk.length, SEEK_CUR);
492 break;
493 }
494 }
495
496 /* Have we read as many instruments as indicated? */
497 if (header.cInstruments != this->instruments.size()) return false;
498
499 /* Resolve wave pool table. */
500 for (std::vector<POOLCUE>::iterator cue = this->pool_cues.begin(); cue != this->pool_cues.end(); cue++) {
501 std::vector<DLSWave>::iterator w = std::ranges::find(this->waves, cue->ulOffset, &DLSWave::file_offset);
502 if (w != this->waves.end()) {
503 cue->ulOffset = (ULONG)(w - this->waves.begin());
504 } else {
505 cue->ulOffset = 0;
506 }
507 }
508
509 return true;
510}
511
512
513static uint8_t ScaleVolume(uint8_t original, uint8_t scale)
514{
515 return original * scale / 127;
516}
517
518static void TransmitChannelMsg(IDirectMusicBuffer *buffer, REFERENCE_TIME rt, uint8_t status, uint8_t p1, uint8_t p2 = 0)
519{
520 if (buffer->PackStructured(rt, 0, status | (p1 << 8) | (p2 << 16)) == E_OUTOFMEMORY) {
521 /* Buffer is full, clear it and try again. */
522 _port->PlayBuffer(buffer);
523 buffer->Flush();
524
525 buffer->PackStructured(rt, 0, status | (p1 << 8) | (p2 << 16));
526 }
527}
528
529static void TransmitSysex(IDirectMusicBuffer *buffer, REFERENCE_TIME rt, const uint8_t *&msg_start, size_t &remaining)
530{
531 /* Find end of message. */
532 const uint8_t *msg_end = msg_start;
533 while (*msg_end != MIDIST_ENDSYSEX) msg_end++;
534 msg_end++; // Also include SysEx end byte.
535
536 if (buffer->PackUnstructured(rt, 0, msg_end - msg_start, const_cast<LPBYTE>(msg_start)) == E_OUTOFMEMORY) {
537 /* Buffer is full, clear it and try again. */
538 _port->PlayBuffer(buffer);
539 buffer->Flush();
540
541 buffer->PackUnstructured(rt, 0, msg_end - msg_start, const_cast<LPBYTE>(msg_start));
542 }
543
544 /* Update position in buffer. */
545 remaining -= msg_end - msg_start;
546 msg_start = msg_end;
547}
548
549static void TransmitStandardSysex(IDirectMusicBuffer *buffer, REFERENCE_TIME rt, MidiSysexMessage msg)
550{
551 size_t length = 0;
552 const uint8_t *data = MidiGetStandardSysexMessage(msg, length);
553 TransmitSysex(buffer, rt, data, length);
554}
555
557 static void TransmitNotesOff(IDirectMusicBuffer *buffer, REFERENCE_TIME block_time, REFERENCE_TIME cur_time)
558{
559 for (int ch = 0; ch < 16; ch++) {
560 TransmitChannelMsg(buffer, block_time + 10, MIDIST_CONTROLLER | ch, MIDICT_MODE_ALLNOTESOFF, 0);
561 TransmitChannelMsg(buffer, block_time + 10, MIDIST_CONTROLLER | ch, MIDICT_SUSTAINSW, 0);
562 TransmitChannelMsg(buffer, block_time + 10, MIDIST_CONTROLLER | ch, MIDICT_MODE_RESETALLCTRL, 0);
563 }
564
565 /* Performing a GM reset stops all sound and resets all parameters. */
566 TransmitStandardSysex(buffer, block_time + 20, MidiSysexMessage::ResetGM);
567 TransmitStandardSysex(buffer, block_time + 30, MidiSysexMessage::RolandSetReverb);
568
569 /* Explicitly flush buffer to make sure the messages are processed,
570 * as we want sound to stop immediately. */
571 _port->PlayBuffer(buffer);
572 buffer->Flush();
573
574 /* Wait until message time has passed. */
575 Sleep(Clamp((block_time - cur_time) / MS_TO_REFTIME, 5, 1000));
576}
577
578static void MidiThreadProc()
579{
580 Debug(driver, 2, "DMusic: Entering playback thread");
581
582 REFERENCE_TIME last_volume_time = 0; // timestamp of the last volume change
583 REFERENCE_TIME block_time = 0; // timestamp of the last block sent to the port
584 REFERENCE_TIME playback_start_time; // timestamp current file began playback
585 MidiFile current_file; // file currently being played from
586 PlaybackSegment current_segment; // segment info for current playback
587 size_t current_block = 0; // next block index to send
588 uint8_t current_volume = 0; // current effective volume setting
589 uint8_t channel_volumes[16]; // last seen volume controller values in raw data
590
591 /* Get pointer to the reference clock of our output port. */
592 IReferenceClock *clock;
593 _port->GetLatencyClock(&clock);
594
595 REFERENCE_TIME cur_time;
596 clock->GetTime(&cur_time);
597
598 _port->PlayBuffer(_buffer);
599 _buffer->Flush();
600
601 DWORD next_timeout = 1000;
602 while (true) {
603 /* Wait for a signal from the GUI thread or until the time for the next event has come. */
604 DWORD wfso = WaitForSingleObject(_thread_event, next_timeout);
605
606 if (_playback.shutdown) {
607 _playback.playing = false;
608 break;
609 }
610
611 if (_playback.do_stop) {
612 Debug(driver, 2, "DMusic thread: Stopping playback");
613
614 /* Turn all notes off and wait a bit to allow the messages to be handled. */
615 clock->GetTime(&cur_time);
616 TransmitNotesOff(_buffer, block_time, cur_time);
617
618 _playback.playing = false;
619 _playback.do_stop = false;
620 block_time = 0;
621 next_timeout = 1000;
622 continue;
623 }
624
625 if (wfso == WAIT_OBJECT_0) {
626 if (_playback.do_start) {
627 Debug(driver, 2, "DMusic thread: Starting playback");
628 {
629 /* New scope to limit the time the mutex is locked. */
630 std::lock_guard<std::mutex> lock(_thread_mutex);
631
632 current_file.MoveFrom(_playback.next_file);
633 std::swap(_playback.next_segment, current_segment);
634 current_segment.start_block = 0;
635 current_block = 0;
636 _playback.playing = true;
637 _playback.do_start = false;
638 }
639
640 /* Reset playback device between songs. */
641 clock->GetTime(&cur_time);
642 TransmitNotesOff(_buffer, block_time, cur_time);
643
644 MemSetT<uint8_t>(channel_volumes, 127, lengthof(channel_volumes));
645 /* Invalidate current volume. */
646 current_volume = UINT8_MAX;
647 last_volume_time = 0;
648
649 /* Take the current time plus the preload time as the music start time. */
650 clock->GetTime(&playback_start_time);
651 playback_start_time += _playback.preload_time * MS_TO_REFTIME;
652 }
653 }
654
655 if (_playback.playing) {
656 /* skip beginning of file? */
657 if (current_segment.start > 0 && current_block == 0 && current_segment.start_block == 0) {
658 /* find first block after start time and pretend playback started earlier
659 * this is to allow all blocks prior to the actual start to still affect playback,
660 * as they may contain important controller and program changes */
661 size_t preload_bytes = 0;
662 for (size_t bl = 0; bl < current_file.blocks.size(); bl++) {
663 MidiFile::DataBlock &block = current_file.blocks[bl];
664 preload_bytes += block.data.size();
665 if (block.ticktime >= current_segment.start) {
666 if (current_segment.loop) {
667 Debug(driver, 2, "DMusic: timer: loop from block {} (ticktime {}, realtime {:.3f}, bytes {})", bl, block.ticktime, ((int)block.realtime) / 1000.0, preload_bytes);
668 current_segment.start_block = bl;
669 break;
670 } else {
671 /* Skip the transmission delay compensation performed in the Win32 MIDI driver.
672 * The DMusic driver will most likely be used with the MS softsynth, which is not subject to transmission delays.
673 */
674 Debug(driver, 2, "DMusic: timer: start from block {} (ticktime {}, realtime {:.3f}, bytes {})", bl, block.ticktime, ((int)block.realtime) / 1000.0, preload_bytes);
675 playback_start_time -= block.realtime * MIDITIME_TO_REFTIME;
676 break;
677 }
678 }
679 }
680 }
681
682 /* Get current playback timestamp. */
683 REFERENCE_TIME current_time;
684 clock->GetTime(&current_time);
685
686 /* Check for volume change. */
687 if (current_volume != _playback.new_volume) {
688 if (current_time - last_volume_time > 10 * MS_TO_REFTIME) {
689 Debug(driver, 2, "DMusic thread: volume change");
690 current_volume = _playback.new_volume;
691 last_volume_time = current_time;
692 for (int ch = 0; ch < 16; ch++) {
693 int vol = ScaleVolume(channel_volumes[ch], current_volume);
694 TransmitChannelMsg(_buffer, block_time + 1, MIDIST_CONTROLLER | ch, MIDICT_CHANVOLUME, vol);
695 }
696 _port->PlayBuffer(_buffer);
697 _buffer->Flush();
698 }
699 }
700
701 while (current_block < current_file.blocks.size()) {
702 MidiFile::DataBlock &block = current_file.blocks[current_block];
703
704 /* check that block isn't at end-of-song override */
705 if (current_segment.end > 0 && block.ticktime >= current_segment.end) {
706 if (current_segment.loop) {
707 Debug(driver, 2, "DMusic thread: Looping song");
708 current_block = current_segment.start_block;
709 playback_start_time = current_time - current_file.blocks[current_block].realtime * MIDITIME_TO_REFTIME;
710 } else {
711 _playback.do_stop = true;
712 }
713 next_timeout = 0;
714 break;
715 }
716 /* check that block is not in the future */
717 REFERENCE_TIME playback_time = current_time - playback_start_time;
718 if (block.realtime * MIDITIME_TO_REFTIME > playback_time + 3 *_playback.preload_time * MS_TO_REFTIME) {
719 /* Stop the thread loop until we are at the preload time of the next block. */
720 next_timeout = Clamp(((int64_t)block.realtime * MIDITIME_TO_REFTIME - playback_time) / MS_TO_REFTIME - _playback.preload_time, 0, 1000);
721 Debug(driver, 9, "DMusic thread: Next event in {} ms (music {}, ref {})", next_timeout, block.realtime * MIDITIME_TO_REFTIME, playback_time);
722 break;
723 }
724
725 /* Timestamp of the current block. */
726 block_time = playback_start_time + block.realtime * MIDITIME_TO_REFTIME;
727 Debug(driver, 9, "DMusic thread: Streaming block {} (cur={}, block={})", current_block, (long long)(current_time / MS_TO_REFTIME), (long long)(block_time / MS_TO_REFTIME));
728
729 const uint8_t *data = block.data.data();
730 size_t remaining = block.data.size();
731 uint8_t last_status = 0;
732 while (remaining > 0) {
733 /* MidiFile ought to have converted everything out of running status,
734 * but handle it anyway just to be safe */
735 uint8_t status = data[0];
736 if (status & 0x80) {
737 last_status = status;
738 data++;
739 remaining--;
740 } else {
741 status = last_status;
742 }
743 switch (status & 0xF0) {
744 case MIDIST_PROGCHG:
745 case MIDIST_CHANPRESS:
746 /* 2 byte channel messages */
747 TransmitChannelMsg(_buffer, block_time, status, data[0]);
748 data++;
749 remaining--;
750 break;
751 case MIDIST_NOTEOFF:
752 case MIDIST_NOTEON:
753 case MIDIST_POLYPRESS:
754 case MIDIST_PITCHBEND:
755 /* 3 byte channel messages */
756 TransmitChannelMsg(_buffer, block_time, status, data[0], data[1]);
757 data += 2;
758 remaining -= 2;
759 break;
760 case MIDIST_CONTROLLER:
761 /* controller change */
762 if (data[0] == MIDICT_CHANVOLUME) {
763 /* volume controller, adjust for user volume */
764 channel_volumes[status & 0x0F] = data[1];
765 int vol = ScaleVolume(data[1], current_volume);
766 TransmitChannelMsg(_buffer, block_time, status, data[0], vol);
767 } else {
768 /* handle other controllers normally */
769 TransmitChannelMsg(_buffer, block_time, status, data[0], data[1]);
770 }
771 data += 2;
772 remaining -= 2;
773 break;
774 case 0xF0:
775 /* system messages */
776 switch (status) {
777 case MIDIST_SYSEX: /* system exclusive */
778 TransmitSysex(_buffer, block_time, data, remaining);
779 break;
780 case MIDIST_TC_QFRAME: /* time code quarter frame */
781 case MIDIST_SONGSEL: /* song select */
782 data++;
783 remaining--;
784 break;
785 case MIDIST_SONGPOSPTR: /* song position pointer */
786 data += 2;
787 remaining -= 2;
788 break;
789 default: /* remaining have no data bytes */
790 break;
791 }
792 break;
793 }
794 }
795
796 current_block++;
797 }
798
799 /* Anything in the playback buffer? Send it down the port. */
800 DWORD used_buffer = 0;
801 _buffer->GetUsedBytes(&used_buffer);
802 if (used_buffer > 0) {
803 _port->PlayBuffer(_buffer);
804 _buffer->Flush();
805 }
806
807 /* end? */
808 if (current_block == current_file.blocks.size()) {
809 if (current_segment.loop) {
810 current_block = current_segment.start_block;
811 playback_start_time = block_time - current_file.blocks[current_block].realtime * MIDITIME_TO_REFTIME;
812 } else {
813 _playback.do_stop = true;
814 }
815 next_timeout = 0;
816 }
817 }
818 }
819
820 Debug(driver, 2, "DMusic: Exiting playback thread");
821
822 /* Turn all notes off and wait a bit to allow the messages to be handled by real hardware. */
823 clock->GetTime(&cur_time);
824 TransmitNotesOff(_buffer, block_time, cur_time);
825 Sleep(_playback.preload_time * 4);
826
827 clock->Release();
828}
829
830static void * DownloadArticulationData(int base_offset, void *data, const std::vector<CONNECTION> &artic)
831{
832 DMUS_ARTICULATION2 *art = (DMUS_ARTICULATION2 *)data;
833 art->ulArtIdx = base_offset + 1;
834 art->ulFirstExtCkIdx = 0;
835 art->ulNextArtIdx = 0;
836
837 CONNECTIONLIST *con_list = (CONNECTIONLIST *)(art + 1);
838 con_list->cbSize = sizeof(CONNECTIONLIST);
839 con_list->cConnections = (ULONG)artic.size();
840 MemCpyT((CONNECTION *)(con_list + 1), &artic.front(), artic.size());
841
842 return (CONNECTION *)(con_list + 1) + artic.size();
843}
844
845static const char *LoadDefaultDLSFile(const char *user_dls)
846{
847 DMUS_PORTCAPS caps;
848 MemSetT(&caps, 0);
849 caps.dwSize = sizeof(DMUS_PORTCAPS);
850 _port->GetCaps(&caps);
851
852 /* Nothing to unless it is a synth with instrument download that doesn't come with GM voices by default. */
853 if ((caps.dwFlags & (DMUS_PC_DLS | DMUS_PC_DLS2)) != 0 && (caps.dwFlags & DMUS_PC_GMINHARDWARE) == 0) {
854 DLSFile dls_file;
855
856 if (user_dls == nullptr) {
857 /* Try loading the default GM DLS file stored in the registry. */
858 HKEY hkDM;
859 if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\DirectMusic", 0, KEY_READ, &hkDM))) {
860 wchar_t dls_path[MAX_PATH];
861 DWORD buf_size = sizeof(dls_path); // Buffer size as to be given in bytes!
862 if (SUCCEEDED(RegQueryValueEx(hkDM, L"GMFilePath", nullptr, nullptr, (LPBYTE)dls_path, &buf_size))) {
863 wchar_t expand_path[MAX_PATH * 2];
864 ExpandEnvironmentStrings(dls_path, expand_path, static_cast<DWORD>(std::size(expand_path)));
865 if (!dls_file.LoadFile(FS2OTTD(expand_path))) Debug(driver, 1, "Failed to load default GM DLS file from registry");
866 }
867 RegCloseKey(hkDM);
868 }
869
870 /* If we couldn't load the file from the registry, try again at the default install path of the GM DLS file. */
871 if (dls_file.instruments.empty()) {
872 static const wchar_t *DLS_GM_FILE = L"%windir%\\System32\\drivers\\gm.dls";
873 wchar_t path[MAX_PATH];
874 ExpandEnvironmentStrings(DLS_GM_FILE, path, static_cast<DWORD>(std::size(path)));
875
876 if (!dls_file.LoadFile(FS2OTTD(path))) return "Can't load GM DLS collection";
877 }
878 } else {
879 if (!dls_file.LoadFile(user_dls)) return "Can't load GM DLS collection";
880 }
881
882 /* Get download port and allocate download IDs. */
883 IDirectMusicPortDownload *download_port = nullptr;
884 if (FAILED(_port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port))) return "Can't get download port";
885
886 DWORD dlid_wave = 0, dlid_inst = 0;
887 if (FAILED(download_port->GetDLId(&dlid_wave, (DWORD)dls_file.waves.size())) || FAILED(download_port->GetDLId(&dlid_inst, (DWORD)dls_file.instruments.size()))) {
888 download_port->Release();
889 return "Can't get enough DLS ids";
890 }
891
892 DWORD dwAppend = 0;
893 download_port->GetAppend(&dwAppend);
894
895 /* Download wave data. */
896 for (DWORD i = 0; i < dls_file.waves.size(); i++) {
897 IDirectMusicDownload *dl_wave = nullptr;
898 if (FAILED(download_port->AllocateBuffer((DWORD)(sizeof(WAVE_DOWNLOAD) + dwAppend * dls_file.waves[i].fmt.wf.nBlockAlign + dls_file.waves[i].data.size()), &dl_wave))) {
899 download_port->Release();
900 return "Can't allocate wave download buffer";
901 }
902
903 WAVE_DOWNLOAD *wave;
904 DWORD wave_size = 0;
905 if (FAILED(dl_wave->GetBuffer((LPVOID *)&wave, &wave_size))) {
906 dl_wave->Release();
907 download_port->Release();
908 return "Can't get wave download buffer";
909 }
910
911 /* Fill download data. */
912 MemSetT(wave, 0);
913 wave->dlInfo.dwDLType = DMUS_DOWNLOADINFO_WAVE;
914 wave->dlInfo.cbSize = wave_size;
915 wave->dlInfo.dwDLId = dlid_wave + i;
916 wave->dlInfo.dwNumOffsetTableEntries = 2;
917 wave->ulOffsetTable[0] = offsetof(WAVE_DOWNLOAD, dmWave);
918 wave->ulOffsetTable[1] = offsetof(WAVE_DOWNLOAD, dmWaveData);
919 wave->dmWave.ulWaveDataIdx = 1;
920 MemCpyT((PCMWAVEFORMAT *)&wave->dmWave.WaveformatEx, &dls_file.waves[i].fmt, 1);
921 wave->dmWaveData.cbSize = (DWORD)dls_file.waves[i].data.size();
922 MemCpyT(wave->dmWaveData.byData, &dls_file.waves[i].data[0], dls_file.waves[i].data.size());
923
924 _dls_downloads.push_back(dl_wave);
925 if (FAILED(download_port->Download(dl_wave))) {
926 download_port->Release();
927 return "Downloading DLS wave failed";
928 }
929 }
930
931 /* Download instrument data. */
932 for (DWORD i = 0; i < dls_file.instruments.size(); i++) {
933 DWORD offsets = 1 + (DWORD)dls_file.instruments[i].regions.size();
934
935 /* Calculate download size for the instrument. */
936 size_t i_size = sizeof(DMUS_DOWNLOADINFO) + sizeof(DMUS_INSTRUMENT);
937 if (!dls_file.instruments[i].articulators.empty()) {
938 /* Articulations are stored as two chunks, one containing meta data and one with the actual articulation data. */
939 offsets += 2;
940 i_size += sizeof(DMUS_ARTICULATION2) + sizeof(CONNECTIONLIST) + sizeof(CONNECTION) * dls_file.instruments[i].articulators.size();
941 }
942
943 for (std::vector<DLSFile::DLSRegion>::iterator rgn = dls_file.instruments[i].regions.begin(); rgn != dls_file.instruments[i].regions.end(); rgn++) {
944 if (!rgn->articulators.empty()) {
945 offsets += 2;
946 i_size += sizeof(DMUS_ARTICULATION2) + sizeof(CONNECTIONLIST) + sizeof(CONNECTION) * rgn->articulators.size();
947 }
948
949 /* Region size depends on the number of wave loops. The size of the
950 * declared structure already accounts for one loop. */
951 if (rgn->wave_sample.cbSize != 0) {
952 i_size += sizeof(DMUS_REGION) - sizeof(DMUS_REGION::WLOOP) + sizeof(WLOOP) * rgn->wave_loops.size();
953 } else {
954 i_size += sizeof(DMUS_REGION) - sizeof(DMUS_REGION::WLOOP) + sizeof(WLOOP) * dls_file.waves[dls_file.pool_cues[rgn->wave.ulTableIndex].ulOffset].wave_loops.size();
955 }
956 }
957
958 i_size += offsets * sizeof(ULONG);
959
960 /* Allocate download buffer. */
961 IDirectMusicDownload *dl_inst = nullptr;
962 if (FAILED(download_port->AllocateBuffer((DWORD)i_size, &dl_inst))) {
963 download_port->Release();
964 return "Can't allocate instrument download buffer";
965 }
966
967 void *instrument;
968 DWORD inst_size = 0;
969 if (FAILED(dl_inst->GetBuffer((LPVOID *)&instrument, &inst_size))) {
970 dl_inst->Release();
971 download_port->Release();
972 return "Can't get instrument download buffer";
973 }
974 char *inst_base = (char *)instrument;
975
976 /* Fill download header. */
977 DMUS_DOWNLOADINFO *d_info = (DMUS_DOWNLOADINFO *)instrument;
978 d_info->dwDLType = DMUS_DOWNLOADINFO_INSTRUMENT2;
979 d_info->cbSize = inst_size;
980 d_info->dwDLId = dlid_inst + i;
981 d_info->dwNumOffsetTableEntries = offsets;
982 instrument = d_info + 1;
983
984 /* Download offset table; contains the offsets of all chunks relative to the buffer start. */
985 ULONG *offset_table = (ULONG *)instrument;
986 instrument = offset_table + offsets;
987 int last_offset = 0;
988
989 /* Instrument header. */
990 DMUS_INSTRUMENT *inst_data = (DMUS_INSTRUMENT *)instrument;
991 MemSetT(inst_data, 0);
992 offset_table[last_offset++] = (char *)inst_data - inst_base;
993 inst_data->ulPatch = (dls_file.instruments[i].hdr.Locale.ulBank & F_INSTRUMENT_DRUMS) | ((dls_file.instruments[i].hdr.Locale.ulBank & 0x7F7F) << 8) | (dls_file.instruments[i].hdr.Locale.ulInstrument & 0x7F);
994 instrument = inst_data + 1;
995
996 /* Write global articulations. */
997 if (!dls_file.instruments[i].articulators.empty()) {
998 inst_data->ulGlobalArtIdx = last_offset;
999 offset_table[last_offset++] = (char *)instrument - inst_base;
1000 offset_table[last_offset++] = (char *)instrument + sizeof(DMUS_ARTICULATION2) - inst_base;
1001
1002 instrument = DownloadArticulationData(inst_data->ulGlobalArtIdx, instrument, dls_file.instruments[i].articulators);
1003 assert((char *)instrument - inst_base <= (ptrdiff_t)inst_size);
1004 }
1005
1006 /* Write out regions. */
1007 inst_data->ulFirstRegionIdx = last_offset;
1008 for (uint j = 0; j < dls_file.instruments[i].regions.size(); j++) {
1009 DLSFile::DLSRegion &rgn = dls_file.instruments[i].regions[j];
1010
1011 DMUS_REGION *inst_region = (DMUS_REGION *)instrument;
1012 offset_table[last_offset++] = (char *)inst_region - inst_base;
1013 inst_region->RangeKey = rgn.hdr.RangeKey;
1014 inst_region->RangeVelocity = rgn.hdr.RangeVelocity;
1015 inst_region->fusOptions = rgn.hdr.fusOptions;
1016 inst_region->usKeyGroup = rgn.hdr.usKeyGroup;
1017 inst_region->ulFirstExtCkIdx = 0;
1018
1019 ULONG wave_id = dls_file.pool_cues[rgn.wave.ulTableIndex].ulOffset;
1020 inst_region->WaveLink = rgn.wave;
1021 inst_region->WaveLink.ulTableIndex = wave_id + dlid_wave;
1022
1023 /* The wave sample data will be taken from the region, if defined, otherwise from the wave itself. */
1024 if (rgn.wave_sample.cbSize != 0) {
1025 inst_region->WSMP = rgn.wave_sample;
1026 if (!rgn.wave_loops.empty()) MemCpyT(inst_region->WLOOP, &rgn.wave_loops.front(), rgn.wave_loops.size());
1027
1028 instrument = (char *)(inst_region + 1) - sizeof(DMUS_REGION::WLOOP) + sizeof(WLOOP) * rgn.wave_loops.size();
1029 } else {
1030 inst_region->WSMP = rgn.wave_sample;
1031 if (!dls_file.waves[wave_id].wave_loops.empty()) MemCpyT(inst_region->WLOOP, &dls_file.waves[wave_id].wave_loops.front(), dls_file.waves[wave_id].wave_loops.size());
1032
1033 instrument = (char *)(inst_region + 1) - sizeof(DMUS_REGION::WLOOP) + sizeof(WLOOP) * dls_file.waves[wave_id].wave_loops.size();
1034 }
1035
1036 /* Write local articulator data. */
1037 if (!rgn.articulators.empty()) {
1038 inst_region->ulRegionArtIdx = last_offset;
1039 offset_table[last_offset++] = (char *)instrument - inst_base;
1040 offset_table[last_offset++] = (char *)instrument + sizeof(DMUS_ARTICULATION2) - inst_base;
1041
1042 instrument = DownloadArticulationData(inst_region->ulRegionArtIdx, instrument, rgn.articulators);
1043 } else {
1044 inst_region->ulRegionArtIdx = 0;
1045 }
1046 assert((char *)instrument - inst_base <= (ptrdiff_t)inst_size);
1047
1048 /* Link to the next region unless this was the last one.*/
1049 inst_region->ulNextRegionIdx = j < dls_file.instruments[i].regions.size() - 1 ? last_offset : 0;
1050 }
1051
1052 _dls_downloads.push_back(dl_inst);
1053 if (FAILED(download_port->Download(dl_inst))) {
1054 download_port->Release();
1055 return "Downloading DLS instrument failed";
1056 }
1057 }
1058
1059 download_port->Release();
1060 }
1061
1062 return nullptr;
1063}
1064
1065
1066std::optional<std::string_view> MusicDriver_DMusic::Start(const StringList &parm)
1067{
1068 /* Initialize COM */
1069 if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return "COM initialization failed";
1070
1071 /* Create the DirectMusic object */
1072 if (FAILED(CoCreateInstance(
1073 CLSID_DirectMusic,
1074 nullptr,
1075 CLSCTX_INPROC,
1076 IID_IDirectMusic,
1077 (LPVOID*)&_music
1078 ))) {
1079 return "Failed to create the music object";
1080 }
1081
1082 /* Assign sound output device. */
1083 if (FAILED(_music->SetDirectSound(nullptr, nullptr))) return "Can't set DirectSound interface";
1084
1085 /* MIDI events need to be send to the synth in time before their playback time
1086 * has come. By default, we try send any events at least 50 ms before playback. */
1087 _playback.preload_time = GetDriverParamInt(parm, "preload", 50);
1088
1089 int pIdx = GetDriverParamInt(parm, "port", -1);
1090 if (_debug_driver_level > 0) {
1091 /* Print all valid output ports. */
1092 char desc[DMUS_MAX_DESCRIPTION];
1093
1094 DMUS_PORTCAPS caps;
1095 MemSetT(&caps, 0);
1096 caps.dwSize = sizeof(DMUS_PORTCAPS);
1097
1098 Debug(driver, 1, "Detected DirectMusic ports:");
1099 for (int i = 0; _music->EnumPort(i, &caps) == S_OK; i++) {
1100 if (caps.dwClass == DMUS_PC_OUTPUTCLASS) {
1101 Debug(driver, 1, " {}: {}{}", i, convert_from_fs(caps.wszDescription, desc), i == pIdx ? " (selected)" : "");
1102 }
1103 }
1104 }
1105
1106 GUID guidPort;
1107 if (pIdx >= 0) {
1108 /* Check if the passed port is a valid port. */
1109 DMUS_PORTCAPS caps;
1110 MemSetT(&caps, 0);
1111 caps.dwSize = sizeof(DMUS_PORTCAPS);
1112 if (FAILED(_music->EnumPort(pIdx, &caps))) return "Supplied port parameter is not a valid port";
1113 if (caps.dwClass != DMUS_PC_OUTPUTCLASS) return "Supplied port parameter is not an output port";
1114 guidPort = caps.guidPort;
1115 } else {
1116 if (FAILED(_music->GetDefaultPort(&guidPort))) return "Can't query default music port";
1117 }
1118
1119 /* Create new port. */
1120 DMUS_PORTPARAMS params;
1121 MemSetT(&params, 0);
1122 params.dwSize = sizeof(DMUS_PORTPARAMS);
1123 params.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
1124 params.dwChannelGroups = 1;
1125 if (FAILED(_music->CreatePort(guidPort, &params, &_port, nullptr))) return "Failed to create port";
1126 /* Activate port. */
1127 if (FAILED(_port->Activate(TRUE))) return "Failed to activate port";
1128
1129 /* Create playback buffer. */
1130 DMUS_BUFFERDESC desc;
1131 MemSetT(&desc, 0);
1132 desc.dwSize = sizeof(DMUS_BUFFERDESC);
1133 desc.guidBufferFormat = KSDATAFORMAT_SUBTYPE_DIRECTMUSIC;
1134 desc.cbBuffer = 1024;
1135 if (FAILED(_music->CreateMusicBuffer(&desc, &_buffer, nullptr))) return "Failed to create music buffer";
1136
1137 /* On soft-synths (e.g. the default DirectMusic one), we might need to load a wavetable set to get music. */
1138 const char *dls = LoadDefaultDLSFile(GetDriverParam(parm, "dls"));
1139 if (dls != nullptr) return dls;
1140
1141 /* Create playback thread and synchronization primitives. */
1142 _thread_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
1143 if (_thread_event == nullptr) return "Can't create thread shutdown event";
1144
1145 if (!StartNewThread(&_dmusic_thread, "ottd:dmusic", &MidiThreadProc)) return "Can't create MIDI output thread";
1146
1147 return std::nullopt;
1148}
1149
1150
1151MusicDriver_DMusic::~MusicDriver_DMusic()
1152{
1153 this->Stop();
1154}
1155
1156
1157 void MusicDriver_DMusic::Stop()
1158{
1159 if (_dmusic_thread.joinable()) {
1160 _playback.shutdown = true;
1161 SetEvent(_thread_event);
1162 _dmusic_thread.join();
1163 }
1164
1165 /* Unloaded any instruments we loaded. */
1166 if (!_dls_downloads.empty()) {
1167 IDirectMusicPortDownload *download_port = nullptr;
1168 _port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port);
1169
1170 /* Instruments refer to waves. As the waves are at the beginning of the download list,
1171 * do the unload from the back so that references are cleared properly. */
1172 for (std::vector<IDirectMusicDownload *>::reverse_iterator i = _dls_downloads.rbegin(); download_port != nullptr && i != _dls_downloads.rend(); i++) {
1173 download_port->Unload(*i);
1174 (*i)->Release();
1175 }
1176 _dls_downloads.clear();
1177
1178 if (download_port != nullptr) download_port->Release();
1179 }
1180
1181 if (_buffer != nullptr) {
1182 _buffer->Release();
1183 _buffer = nullptr;
1184 }
1185
1186 if (_port != nullptr) {
1187 _port->Activate(FALSE);
1188 _port->Release();
1189 _port = nullptr;
1190 }
1191
1192 if (_music != nullptr) {
1193 _music->Release();
1194 _music = nullptr;
1195 }
1196
1197 CloseHandle(_thread_event);
1198
1199 CoUninitialize();
1200}
1201
1202
1203 void MusicDriver_DMusic::PlaySong(const MusicSongInfo &song)
1204{
1205 std::lock_guard<std::mutex> lock(_thread_mutex);
1206
1207 if (!_playback.next_file.LoadSong(song)) return;
1208
1209 _playback.next_segment.start = song.override_start;
1210 _playback.next_segment.end = song.override_end;
1211 _playback.next_segment.loop = song.loop;
1212
1213 _playback.do_start = true;
1214 SetEvent(_thread_event);
1215}
1216
1217
1218 void MusicDriver_DMusic::StopSong()
1219{
1220 _playback.do_stop = true;
1221 SetEvent(_thread_event);
1222}
1223
1224
1225 bool MusicDriver_DMusic::IsSongPlaying()
1226{
1227 return _playback.playing || _playback.do_start;
1228}
1229
1230
1231 void MusicDriver_DMusic::SetVolume(uint8_t vol)
1232{
1233 _playback.new_volume = vol;
1234}
FMusicDriver_DMusic
Factory for the DirectX music player.
Definition dmusic.h:35
FileHandle
Definition fileio_type.h:158
FileHandle::Open
static std::optional< FileHandle > Open(const std::string &filename, const std::string &mode)
Open an RAII file handle if possible.
Definition fileio.cpp:1170
MusicDriver_DMusic::SetVolume
void SetVolume(uint8_t vol) override
Set the volume, if possible.
Definition dmusic.cpp:1231
MusicDriver_DMusic::StopSong
void StopSong() override
Stop playing the current song.
Definition dmusic.cpp:1218
MusicDriver_DMusic::Start
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition dmusic.cpp:1066
MusicDriver_DMusic::IsSongPlaying
bool IsSongPlaying() override
Are we currently playing a song?
Definition dmusic.cpp:1225
MusicDriver_DMusic::Stop
void Stop() override
Stop this driver.
Definition dmusic.cpp:1157
MusicDriver_DMusic::PlaySong
void PlaySong(const MusicSongInfo &song) override
Play a particular song.
Definition dmusic.cpp:1203
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition debug.h:37
playing
bool playing
flag indicating that playback is active
Definition dmusic.cpp:121
new_volume
uint8_t new_volume
volume setting to change to
Definition dmusic.cpp:126
shutdown
bool shutdown
flag to indicate playback thread shutdown
Definition dmusic.cpp:120
_buffer
static IDirectMusicBuffer * _buffer
The buffer object collects the data to sent.
Definition dmusic.cpp:144
do_stop
bool do_stop
flag for stopping playback at next opportunity
Definition dmusic.cpp:123
preload_time
int preload_time
preload time for music blocks.
Definition dmusic.cpp:125
MIDITIME_TO_REFTIME
static const int MIDITIME_TO_REFTIME
Time base of the midi file reader is 1 us.
Definition dmusic.cpp:37
_dmusic_thread
static std::thread _dmusic_thread
Handle to our worker thread.
Definition dmusic.cpp:133
next_file
MidiFile next_file
upcoming file to play
Definition dmusic.cpp:128
_port
static IDirectMusicPort * _port
The port object lets us send MIDI data to the synthesizer.
Definition dmusic.cpp:142
do_start
bool do_start
flag for starting playback of next_file at next opportunity
Definition dmusic.cpp:122
_dls_downloads
static std::vector< IDirectMusicDownload * > _dls_downloads
List of downloaded DLS instruments.
Definition dmusic.cpp:146
_thread_event
static HANDLE _thread_event
Event to signal the thread that it should look at a state change.
Definition dmusic.cpp:135
MS_TO_REFTIME
static const int MS_TO_REFTIME
DirectMusic time base is 100 ns.
Definition dmusic.cpp:36
_thread_mutex
static std::mutex _thread_mutex
Lock access to playback data that is not thread-safe.
Definition dmusic.cpp:137
_music
static IDirectMusic * _music
The direct music object manages buffers and ports.
Definition dmusic.cpp:140
next_segment
PlaybackSegment next_segment
segment info for upcoming file
Definition dmusic.cpp:129
TransmitNotesOff
static void TransmitNotesOff(IDirectMusicBuffer *buffer, REFERENCE_TIME block_time, REFERENCE_TIME cur_time)
Transmit 'Note off' messages to all MIDI channels.
Definition dmusic.cpp:557
dmusic.h
Base of playing music via DirectMusic.
GetDriverParam
const char * GetDriverParam(const StringList &parm, const char *name)
Get a string parameter the list of parameters.
Definition driver.cpp:44
GetDriverParamInt
int GetDriverParamInt(const StringList &parm, const char *name, int def)
Get an integer parameter the list of parameters.
Definition driver.cpp:76
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
MemCpyT
void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition mem_func.hpp:23
MemSetT
void MemSetT(T *ptr, uint8_t value, size_t num=1)
Type-safe version of memset().
Definition mem_func.hpp:49
lengthof
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:280
StringList
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
DLSFile::DLSInstrument
Instrument definition read from a DLS file.
Definition dmusic.cpp:57
DLSFile::DLSRegion
An instrument region maps a note range to wave data.
Definition dmusic.cpp:47
DLSFile::DLSWave
Wave data definition from a DLS file.
Definition dmusic.cpp:65
DLSFile
A DLS file.
Definition dmusic.cpp:45
DLSFile::ReadDLSInstrumentList
bool ReadDLSInstrumentList(FileHandle &f, DWORD list_length)
Load a list of instruments from a DLS file.
Definition dmusic.cpp:305
DLSFile::LoadFile
bool LoadFile(const std::string &file)
Try loading a DLS file into memory.
Definition dmusic.cpp:424
DLSFile::ReadDLSWaveList
bool ReadDLSWaveList(FileHandle &f, DWORD list_length)
Load a list of waves from a DLS file.
Definition dmusic.cpp:392
DLSFile::ReadDLSRegionList
bool ReadDLSRegionList(FileHandle &f, DWORD list_length, DLSInstrument &instrument)
Load a list of regions from a DLS file.
Definition dmusic.cpp:236
DLSFile::ReadDLSWave
bool ReadDLSWave(FileHandle &f, DWORD list_length, long offset)
Load a single wave from a DLS file.
Definition dmusic.cpp:333
DLSFile::ReadDLSRegion
bool ReadDLSRegion(FileHandle &f, DWORD list_length, std::vector< DLSRegion > &out)
Load a single region from a DLS file.
Definition dmusic.cpp:178
DLSFile::ReadDLSInstrument
bool ReadDLSInstrument(FileHandle &f, DWORD list_length)
Load a single instrument from a DLS file.
Definition dmusic.cpp:262
DLSFile::ReadDLSArticulation
bool ReadDLSArticulation(FileHandle &f, DWORD list_length, std::vector< CONNECTION > &out)
Load an articulation structure from a DLS file.
Definition dmusic.cpp:152
MidiFile::DataBlock
Definition midifile.hpp:20
MidiFile::DataBlock::data
std::vector< uint8_t > data
raw midi data contained in block
Definition midifile.hpp:23
MidiFile::DataBlock::realtime
uint32_t realtime
real-time (microseconds) since start of file this block should be triggered at
Definition midifile.hpp:22
MidiFile::DataBlock::ticktime
uint32_t ticktime
tick number since start of file this block should be triggered at
Definition midifile.hpp:21
MidiFile
Definition midifile.hpp:19
MidiFile::MoveFrom
void MoveFrom(MidiFile &other)
Move data from other to this, and clears other.
Definition midifile.cpp:854
MidiFile::blocks
std::vector< DataBlock > blocks
sequential time-annotated data of file, merged to a single track
Definition midifile.hpp:32
MusicSongInfo
Metadata about a music track.
Definition base_media_base.h:325
MusicSongInfo::override_start
int override_start
MIDI ticks to skip over in beginning.
Definition base_media_base.h:332
MusicSongInfo::loop
bool loop
song should play in a tight loop if possible, never ending
Definition base_media_base.h:331
MusicSongInfo::override_end
int override_end
MIDI tick to end the song at (0 if no override)
Definition base_media_base.h:333
PlaybackSegment
Definition dmusic.cpp:113
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition thread.h:47
convert_from_fs
char * convert_from_fs(const std::wstring_view src, std::span< char > dst_buf)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
Definition win32.cpp:372
FS2OTTD
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:337
current_volume
uint8_t current_volume
current effective volume setting
Definition win32_m.cpp:40
current_file
MidiFile current_file
file currently being played from
Definition win32_m.cpp:43
current_segment
PlaybackSegment current_segment
segment info for current playback
Definition win32_m.cpp:44
current_block
size_t current_block
next block index to send
Definition win32_m.cpp:46
lock
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35
channel_volumes
uint8_t channel_volumes[16]
last seen volume controller values in raw data
Definition win32_m.cpp:50
playback_start_time
DWORD playback_start_time
timestamp current file began playback
Definition win32_m.cpp:45