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