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