12#ifdef WIN32_LEAN_AND_MEAN
13# undef WIN32_LEAN_AND_MEAN
33# pragma comment(lib, "ole32.lib")
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')
52 std::vector<WLOOP> wave_loops;
53 std::vector<CONNECTION> articulators;
60 std::vector<CONNECTION> articulators;
61 std::vector<DLSRegion> regions;
69 std::vector<BYTE> data;
72 std::vector<WLOOP> wave_loops;
75 std::vector<DLSInstrument> instruments;
76 std::vector<POOLCUE> pool_cues;
77 std::vector<DLSWave> waves;
84 bool LoadFile(std::string_view file);
156 DMUS_DOWNLOADINFO dlInfo;
157 ULONG ulOffsetTable[2];
159 DMUS_WAVEDATA dmWaveData;
191static IDirectMusicPort *
_port =
nullptr;
203 while (list_length > 0) {
205 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
206 list_length -= chunk.length +
sizeof(chunk);
208 if (chunk.type == FOURCC_ART1) {
209 CONNECTIONLIST conns;
210 if (fread(&conns,
sizeof(conns), 1, f) != 1)
return false;
211 fseek(f, conns.cbSize -
sizeof(conns), SEEK_CUR);
214 for (ULONG i = 0; i < conns.cConnections; i++) {
216 if (fread(&con,
sizeof(con), 1, f) != 1)
return false;
220 fseek(f, chunk.length, SEEK_CUR);
232 region.wave_sample.cbSize = 0;
234 while (list_length > 0) {
236 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
237 list_length -= chunk.length +
sizeof(chunk);
239 if (chunk.type == FOURCC_LIST) {
241 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
242 chunk.length -=
sizeof(chunk.type);
245 switch (chunk.type) {
247 if (fread(®ion.hdr,
sizeof(region.hdr), 1, f) != 1)
return false;
251 if (fread(®ion.wave_sample,
sizeof(region.wave_sample), 1, f) != 1)
return false;
252 fseek(f, region.wave_sample.cbSize -
sizeof(region.wave_sample), SEEK_CUR);
255 for (ULONG i = 0; i < region.wave_sample.cSampleLoops; i++) {
257 if (fread(&loop,
sizeof(loop), 1, f) != 1)
return false;
258 region.wave_loops.push_back(loop);
263 if (fread(®ion.wave,
sizeof(region.wave), 1, f) != 1)
return false;
272 fseek(f, chunk.length, SEEK_CUR);
276 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));
277 fseek(f, chunk.length, SEEK_CUR);
287 while (list_length > 0) {
289 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
290 list_length -= chunk.length +
sizeof(chunk);
292 if (chunk.type == FOURCC_LIST) {
294 if (fread(&list_type,
sizeof(list_type), 1, f) != 1)
return false;
296 if (list_type == FOURCC_RGN) {
297 this->
ReadDLSRegion(f, chunk.length -
sizeof(list_type), instrument.regions);
299 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));
300 fseek(f, chunk.length -
sizeof(list_type), SEEK_CUR);
303 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));
304 fseek(f, chunk.length, SEEK_CUR);
313 DLSInstrument &instrument = this->instruments.emplace_back();
315 while (list_length > 0) {
317 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
318 list_length -= chunk.length +
sizeof(chunk);
320 if (chunk.type == FOURCC_LIST) {
322 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
323 chunk.length -=
sizeof(chunk.type);
326 switch (chunk.type) {
328 if (fread(&instrument.hdr,
sizeof(instrument.hdr), 1, f) != 1)
return false;
341 fseek(f, chunk.length, SEEK_CUR);
345 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));
346 fseek(f, chunk.length, SEEK_CUR);
356 while (list_length > 0) {
358 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
359 list_length -= chunk.length +
sizeof(chunk);
361 if (chunk.type == FOURCC_LIST) {
363 if (fread(&list_type,
sizeof(list_type), 1, f) != 1)
return false;
365 if (list_type == FOURCC_INS) {
366 Debug(driver, 6,
"DLS: Reading instrument {}", (
int)instruments.size());
370 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));
371 fseek(f, chunk.length -
sizeof(list_type), SEEK_CUR);
374 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));
375 fseek(f, chunk.length, SEEK_CUR);
384 DLSWave &wave = this->waves.emplace_back();
387 wave.wave_sample.cbSize =
sizeof(WSMPL);
388 wave.wave_sample.usUnityNote = 60;
389 wave.file_offset = offset;
391 while (list_length > 0) {
393 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
394 list_length -= chunk.length +
sizeof(chunk);
396 if (chunk.type == FOURCC_LIST) {
398 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
399 chunk.length -=
sizeof(chunk.type);
402 switch (chunk.type) {
404 if (fread(&wave.fmt,
sizeof(wave.fmt), 1, f) != 1)
return false;
405 if (chunk.length >
sizeof(wave.fmt)) fseek(f, chunk.length -
sizeof(wave.fmt), SEEK_CUR);
409 if (fread(&wave.wave_sample,
sizeof(wave.wave_sample), 1, f) != 1)
return false;
410 fseek(f, wave.wave_sample.cbSize -
sizeof(wave.wave_sample), SEEK_CUR);
413 for (ULONG i = 0; i < wave.wave_sample.cSampleLoops; i++) {
415 if (fread(&loop,
sizeof(loop), 1, f) != 1)
return false;
416 wave.wave_loops.push_back(loop);
421 wave.data.resize(chunk.length);
422 if (fread(&wave.data[0],
sizeof(BYTE), wave.data.size(), f) != wave.data.size())
return false;
427 fseek(f, chunk.length, SEEK_CUR);
431 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));
432 fseek(f, chunk.length, SEEK_CUR);
442 long base_offset = ftell(f);
444 while (list_length > 0) {
445 long chunk_offset = ftell(f);
448 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
449 list_length -= chunk.length +
sizeof(chunk);
451 if (chunk.type == FOURCC_LIST) {
453 if (fread(&list_type,
sizeof(list_type), 1, f) != 1)
return false;
455 if (list_type == FOURCC_wave) {
456 Debug(driver, 6,
"DLS: Reading wave {}", waves.size());
458 if (!this->
ReadDLSWave(f, chunk.length -
sizeof(list_type), chunk_offset - base_offset))
return false;
460 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));
461 fseek(f, chunk.length -
sizeof(list_type), SEEK_CUR);
464 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));
465 fseek(f, chunk.length, SEEK_CUR);
474 Debug(driver, 2,
"DMusic: Try to load DLS file {}", file);
477 if (!of.has_value())
return false;
483 if (fread(&hdr,
sizeof(hdr), 1, f) != 1)
return false;
484 if (fread(&dls_type,
sizeof(dls_type), 1, f) != 1)
return false;
485 if (hdr.type != FOURCC_RIFF || dls_type != FOURCC_DLS)
return false;
487 hdr.length -=
sizeof(FOURCC);
489 Debug(driver, 2,
"DMusic: Parsing DLS file");
494 while (hdr.length > 0) {
496 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
497 hdr.length -= chunk.length +
sizeof(chunk);
499 if (chunk.type == FOURCC_LIST) {
501 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
502 chunk.length -=
sizeof(chunk.type);
505 switch (chunk.type) {
507 if (fread(&header,
sizeof(header), 1, f) != 1)
return false;
520 if (fread(&ptbl,
sizeof(ptbl), 1, f) != 1)
return false;
521 fseek(f, ptbl.cbSize -
sizeof(ptbl), SEEK_CUR);
524 for (ULONG i = 0; i < ptbl.cCues; i++) {
526 if (fread(&cue,
sizeof(cue), 1, f) != 1)
return false;
527 this->pool_cues.push_back(cue);
533 fseek(f, chunk.length, SEEK_CUR);
537 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));
538 fseek(f, chunk.length, SEEK_CUR);
544 if (header.cInstruments != this->instruments.size())
return false;
547 for (std::vector<POOLCUE>::iterator cue = this->pool_cues.begin(); cue != this->pool_cues.end(); cue++) {
548 std::vector<DLSWave>::iterator w = std::ranges::find(this->waves, cue->ulOffset, &DLSWave::file_offset);
549 if (w != this->waves.end()) {
550 cue->ulOffset = (ULONG)(w - this->waves.begin());
560static uint8_t ScaleVolume(uint8_t original, uint8_t scale)
562 return original * scale / 127;
565static void TransmitChannelMsg(IDirectMusicBuffer *buffer, REFERENCE_TIME rt, uint8_t status, uint8_t p1, uint8_t p2 = 0)
567 if (buffer->PackStructured(rt, 0, status | (p1 << 8) | (p2 << 16)) == E_OUTOFMEMORY) {
569 _port->PlayBuffer(buffer);
572 buffer->PackStructured(rt, 0, status | (p1 << 8) | (p2 << 16));
576static void TransmitSysex(IDirectMusicBuffer *buffer, REFERENCE_TIME rt,
const uint8_t *&msg_start,
size_t &remaining)
579 const uint8_t *msg_end = msg_start;
583 if (buffer->PackUnstructured(rt, 0, msg_end - msg_start,
const_cast<LPBYTE
>(msg_start)) == E_OUTOFMEMORY) {
585 _port->PlayBuffer(buffer);
588 buffer->PackUnstructured(rt, 0, msg_end - msg_start,
const_cast<LPBYTE
>(msg_start));
592 remaining -= msg_end - msg_start;
596static void TransmitStandardSysex(IDirectMusicBuffer *buffer, REFERENCE_TIME rt,
MidiSysexMessage msg)
600 TransmitSysex(buffer, rt, data, length);
609static void TransmitNotesOff(IDirectMusicBuffer *buffer, REFERENCE_TIME block_time, REFERENCE_TIME cur_time)
611 for (
int ch = 0; ch < 16; ch++) {
612 TransmitChannelMsg(buffer, block_time + 10, MIDIST_CONTROLLER | ch, MIDICT_MODE_ALLNOTESOFF, 0);
613 TransmitChannelMsg(buffer, block_time + 10, MIDIST_CONTROLLER | ch, MIDICT_SUSTAINSW, 0);
614 TransmitChannelMsg(buffer, block_time + 10, MIDIST_CONTROLLER | ch, MIDICT_MODE_RESETALLCTRL, 0);
623 _port->PlayBuffer(buffer);
630static void MidiThreadProc()
632 Debug(driver, 2,
"DMusic: Entering playback thread");
634 REFERENCE_TIME last_volume_time = 0;
635 REFERENCE_TIME block_time = 0;
644 IReferenceClock *clock;
645 _port->GetLatencyClock(&clock);
647 REFERENCE_TIME cur_time;
648 clock->GetTime(&cur_time);
653 DWORD next_timeout = 1000;
656 DWORD wfso = WaitForSingleObject(
_thread_event, next_timeout);
658 if (_playback.shutdown) {
659 _playback.playing =
false;
663 if (_playback.do_stop) {
664 Debug(driver, 2,
"DMusic thread: Stopping playback");
667 clock->GetTime(&cur_time);
670 _playback.playing =
false;
671 _playback.do_stop =
false;
677 if (wfso == WAIT_OBJECT_0) {
678 if (_playback.do_start) {
679 Debug(driver, 2,
"DMusic thread: Starting playback");
688 _playback.playing =
true;
689 _playback.do_start =
false;
693 clock->GetTime(&cur_time);
699 last_volume_time = 0;
707 if (_playback.playing) {
713 size_t preload_bytes = 0;
714 for (
size_t bl = 0; bl <
current_file.blocks.size(); bl++) {
716 preload_bytes += block.
data.size();
719 Debug(driver, 2,
"DMusic: timer: loop from block {} (ticktime {}, realtime {:.3f}, bytes {})", bl, block.
ticktime, block.
realtime / 1000.0, preload_bytes);
726 Debug(driver, 2,
"DMusic: timer: start from block {} (ticktime {}, realtime {:.3f}, bytes {})", bl, block.
ticktime, block.
realtime / 1000.0, preload_bytes);
735 REFERENCE_TIME current_time;
736 clock->GetTime(¤t_time);
741 Debug(driver, 2,
"DMusic thread: volume change");
743 last_volume_time = current_time;
744 for (
int ch = 0; ch < 16; ch++) {
746 TransmitChannelMsg(
_buffer, block_time + 1, MIDIST_CONTROLLER | ch, MIDICT_CHANVOLUME, vol);
759 Debug(driver, 2,
"DMusic thread: Looping song");
763 _playback.do_stop =
true;
781 const uint8_t *data = block.
data.data();
782 size_t remaining = block.
data.size();
783 uint8_t last_status = 0;
784 while (remaining > 0) {
787 uint8_t status = data[0];
789 last_status = status;
793 status = last_status;
795 switch (status & 0xF0) {
797 case MIDIST_CHANPRESS:
799 TransmitChannelMsg(
_buffer, block_time, status, data[0]);
805 case MIDIST_POLYPRESS:
806 case MIDIST_PITCHBEND:
808 TransmitChannelMsg(
_buffer, block_time, status, data[0], data[1]);
812 case MIDIST_CONTROLLER:
814 if (data[0] == MIDICT_CHANVOLUME) {
818 TransmitChannelMsg(
_buffer, block_time, status, data[0], vol);
821 TransmitChannelMsg(
_buffer, block_time, status, data[0], data[1]);
830 TransmitSysex(
_buffer, block_time, data, remaining);
832 case MIDIST_TC_QFRAME:
837 case MIDIST_SONGPOSPTR:
852 DWORD used_buffer = 0;
853 _buffer->GetUsedBytes(&used_buffer);
854 if (used_buffer > 0) {
865 _playback.do_stop =
true;
872 Debug(driver, 2,
"DMusic: Exiting playback thread");
875 clock->GetTime(&cur_time);
877 Sleep(_playback.preload_time * 4);
882static void * DownloadArticulationData(
int base_offset,
void *data,
const std::vector<CONNECTION> &artic)
884 DMUS_ARTICULATION2 *art = (DMUS_ARTICULATION2 *)data;
885 art->ulArtIdx = base_offset + 1;
886 art->ulFirstExtCkIdx = 0;
887 art->ulNextArtIdx = 0;
889 CONNECTIONLIST *con_list = (CONNECTIONLIST *)(art + 1);
890 con_list->cbSize =
sizeof(CONNECTIONLIST);
891 con_list->cConnections = (ULONG)artic.size();
893 return std::copy_n(artic.begin(), artic.size(),
reinterpret_cast<CONNECTION *
>(con_list + 1));
896static std::optional<std::string_view> LoadDefaultDLSFile(std::optional<std::string_view> user_dls)
898 DMUS_PORTCAPS caps{};
899 caps.dwSize =
sizeof(DMUS_PORTCAPS);
900 _port->GetCaps(&caps);
903 if ((caps.dwFlags & (DMUS_PC_DLS | DMUS_PC_DLS2)) != 0 && (caps.dwFlags & DMUS_PC_GMINHARDWARE) == 0) {
906 if (!user_dls.has_value()) {
909 if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L
"Software\\Microsoft\\DirectMusic", 0, KEY_READ, &hkDM))) {
910 wchar_t dls_path[MAX_PATH];
911 DWORD buf_size =
sizeof(dls_path);
912 if (SUCCEEDED(RegQueryValueEx(hkDM, L
"GMFilePath",
nullptr,
nullptr, (LPBYTE)dls_path, &buf_size))) {
913 wchar_t expand_path[MAX_PATH * 2];
914 ExpandEnvironmentStrings(dls_path, expand_path,
static_cast<DWORD
>(std::size(expand_path)));
915 if (!dls_file.
LoadFile(
FS2OTTD(expand_path)))
Debug(driver, 1,
"Failed to load default GM DLS file from registry");
921 if (dls_file.instruments.empty()) {
922 static const wchar_t *DLS_GM_FILE = L
"%windir%\\System32\\drivers\\gm.dls";
923 wchar_t path[MAX_PATH];
924 ExpandEnvironmentStrings(DLS_GM_FILE, path,
static_cast<DWORD
>(std::size(path)));
926 if (!dls_file.
LoadFile(
FS2OTTD(path)))
return "Can't load GM DLS collection";
929 if (!dls_file.
LoadFile(*user_dls))
return "Can't load GM DLS collection";
933 IDirectMusicPortDownload *download_port =
nullptr;
934 if (FAILED(
_port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port)))
return "Can't get download port";
936 DWORD dlid_wave = 0, dlid_inst = 0;
937 if (FAILED(download_port->GetDLId(&dlid_wave, (DWORD)dls_file.waves.size())) || FAILED(download_port->GetDLId(&dlid_inst, (DWORD)dls_file.instruments.size()))) {
938 download_port->Release();
939 return "Can't get enough DLS ids";
943 download_port->GetAppend(&dwAppend);
946 for (DWORD i = 0; i < dls_file.waves.size(); i++) {
947 IDirectMusicDownload *dl_wave =
nullptr;
948 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))) {
949 download_port->Release();
950 return "Can't allocate wave download buffer";
955 if (FAILED(dl_wave->GetBuffer((LPVOID *)&wave, &wave_size))) {
957 download_port->Release();
958 return "Can't get wave download buffer";
963 wave->dlInfo.dwDLType = DMUS_DOWNLOADINFO_WAVE;
964 wave->dlInfo.cbSize = wave_size;
965 wave->dlInfo.dwDLId = dlid_wave + i;
966 wave->dlInfo.dwNumOffsetTableEntries = 2;
967 wave->ulOffsetTable[0] = offsetof(WAVE_DOWNLOAD, dmWave);
968 wave->ulOffsetTable[1] = offsetof(WAVE_DOWNLOAD, dmWaveData);
969 wave->dmWave.ulWaveDataIdx = 1;
970 wave->dmWaveData.cbSize = (DWORD)dls_file.waves[i].data.size();
971 reinterpret_cast<PCMWAVEFORMAT &
>(wave->dmWave.WaveformatEx) = dls_file.waves[i].fmt;
972 std::copy_n(dls_file.waves[i].data.begin(), dls_file.waves[i].data.size(), wave->dmWaveData.byData);
975 if (FAILED(download_port->Download(dl_wave))) {
976 download_port->Release();
977 return "Downloading DLS wave failed";
982 for (DWORD i = 0; i < dls_file.instruments.size(); i++) {
983 DWORD offsets = 1 + (DWORD)dls_file.instruments[i].regions.size();
986 size_t i_size =
sizeof(DMUS_DOWNLOADINFO) +
sizeof(DMUS_INSTRUMENT);
987 if (!dls_file.instruments[i].articulators.empty()) {
990 i_size +=
sizeof(DMUS_ARTICULATION2) +
sizeof(CONNECTIONLIST) +
sizeof(CONNECTION) * dls_file.instruments[i].articulators.size();
993 for (std::vector<DLSFile::DLSRegion>::iterator rgn = dls_file.instruments[i].regions.begin(); rgn != dls_file.instruments[i].regions.end(); rgn++) {
994 if (!rgn->articulators.empty()) {
996 i_size +=
sizeof(DMUS_ARTICULATION2) +
sizeof(CONNECTIONLIST) +
sizeof(CONNECTION) * rgn->articulators.size();
1001 if (rgn->wave_sample.cbSize != 0) {
1002 i_size +=
sizeof(DMUS_REGION) -
sizeof(DMUS_REGION::WLOOP) +
sizeof(WLOOP) * rgn->wave_loops.size();
1004 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();
1008 i_size += offsets *
sizeof(ULONG);
1011 IDirectMusicDownload *dl_inst =
nullptr;
1012 if (FAILED(download_port->AllocateBuffer((DWORD)i_size, &dl_inst))) {
1013 download_port->Release();
1014 return "Can't allocate instrument download buffer";
1018 DWORD inst_size = 0;
1019 if (FAILED(dl_inst->GetBuffer((LPVOID *)&instrument, &inst_size))) {
1021 download_port->Release();
1022 return "Can't get instrument download buffer";
1024 const std::byte *inst_base =
reinterpret_cast<const std::byte *
>(instrument);
1027 DMUS_DOWNLOADINFO *d_info = (DMUS_DOWNLOADINFO *)instrument;
1028 d_info->dwDLType = DMUS_DOWNLOADINFO_INSTRUMENT2;
1029 d_info->cbSize = inst_size;
1030 d_info->dwDLId = dlid_inst + i;
1031 d_info->dwNumOffsetTableEntries = offsets;
1032 instrument = d_info + 1;
1035 ULONG *offset_table = (ULONG *)instrument;
1036 instrument = offset_table + offsets;
1037 int last_offset = 0;
1040 DMUS_INSTRUMENT *inst_data = (DMUS_INSTRUMENT *)instrument;
1042 offset_table[last_offset++] =
reinterpret_cast<const std::byte *
>(inst_data) - inst_base;
1043 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);
1044 instrument = inst_data + 1;
1047 if (!dls_file.instruments[i].articulators.empty()) {
1048 inst_data->ulGlobalArtIdx = last_offset;
1049 offset_table[last_offset++] =
reinterpret_cast<const std::byte *
>(instrument) - inst_base;
1050 offset_table[last_offset++] =
reinterpret_cast<const std::byte *
>(instrument) +
sizeof(DMUS_ARTICULATION2) - inst_base;
1052 instrument = DownloadArticulationData(inst_data->ulGlobalArtIdx, instrument, dls_file.instruments[i].articulators);
1053 assert(
reinterpret_cast<const std::byte *
>(instrument) - inst_base <= (ptrdiff_t)inst_size);
1057 inst_data->ulFirstRegionIdx = last_offset;
1058 for (uint j = 0; j < dls_file.instruments[i].regions.size(); j++) {
1061 DMUS_REGION *inst_region = (DMUS_REGION *)instrument;
1062 offset_table[last_offset++] =
reinterpret_cast<const std::byte *
>(inst_region) - inst_base;
1063 inst_region->RangeKey = rgn.hdr.RangeKey;
1064 inst_region->RangeVelocity = rgn.hdr.RangeVelocity;
1065 inst_region->fusOptions = rgn.hdr.fusOptions;
1066 inst_region->usKeyGroup = rgn.hdr.usKeyGroup;
1067 inst_region->ulFirstExtCkIdx = 0;
1069 ULONG wave_id = dls_file.pool_cues[rgn.wave.ulTableIndex].ulOffset;
1070 inst_region->WaveLink = rgn.wave;
1071 inst_region->WaveLink.ulTableIndex = wave_id + dlid_wave;
1074 if (rgn.wave_sample.cbSize != 0) {
1075 inst_region->WSMP = rgn.wave_sample;
1076 instrument = std::copy_n(rgn.wave_loops.begin(), rgn.wave_loops.size(), inst_region->WLOOP);
1078 inst_region->WSMP = rgn.wave_sample;
1079 instrument = std::copy_n(dls_file.waves[wave_id].wave_loops.begin(), dls_file.waves[wave_id].wave_loops.size(), inst_region->WLOOP);
1083 if (!rgn.articulators.empty()) {
1084 inst_region->ulRegionArtIdx = last_offset;
1085 offset_table[last_offset++] =
reinterpret_cast<const std::byte *
>(instrument) - inst_base;
1086 offset_table[last_offset++] =
reinterpret_cast<const std::byte *
>(instrument) +
sizeof(DMUS_ARTICULATION2) - inst_base;
1088 instrument = DownloadArticulationData(inst_region->ulRegionArtIdx, instrument, rgn.articulators);
1090 inst_region->ulRegionArtIdx = 0;
1092 assert(
reinterpret_cast<const std::byte *
>(instrument) - inst_base <= (ptrdiff_t)inst_size);
1095 inst_region->ulNextRegionIdx = j < dls_file.instruments[i].regions.size() - 1 ? last_offset : 0;
1099 if (FAILED(download_port->Download(dl_inst))) {
1100 download_port->Release();
1101 return "Downloading DLS instrument failed";
1105 download_port->Release();
1108 return std::nullopt;
1115 if (FAILED(CoInitializeEx(
nullptr, COINIT_MULTITHREADED)))
return "COM initialization failed";
1118 if (FAILED(CoCreateInstance(
1125 return "Failed to create the music object";
1129 if (FAILED(
_music->SetDirectSound(
nullptr,
nullptr)))
return "Can't set DirectSound interface";
1136 if (_debug_driver_level > 0) {
1138 char desc[DMUS_MAX_DESCRIPTION];
1140 DMUS_PORTCAPS caps{};
1141 caps.dwSize =
sizeof(DMUS_PORTCAPS);
1143 Debug(driver, 1,
"Detected DirectMusic ports:");
1144 for (
int i = 0;
_music->EnumPort(i, &caps) == S_OK; i++) {
1145 if (caps.dwClass == DMUS_PC_OUTPUTCLASS) {
1146 Debug(driver, 1,
" {}: {}{}", i,
convert_from_fs(caps.wszDescription, desc), i == pIdx ?
" (selected)" :
"");
1154 DMUS_PORTCAPS caps{};
1155 caps.dwSize =
sizeof(DMUS_PORTCAPS);
1156 if (FAILED(
_music->EnumPort(pIdx, &caps)))
return "Supplied port parameter is not a valid port";
1157 if (caps.dwClass != DMUS_PC_OUTPUTCLASS)
return "Supplied port parameter is not an output port";
1158 guidPort = caps.guidPort;
1160 if (FAILED(
_music->GetDefaultPort(&guidPort)))
return "Can't query default music port";
1164 DMUS_PORTPARAMS params{};
1165 params.dwSize =
sizeof(DMUS_PORTPARAMS);
1166 params.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
1167 params.dwChannelGroups = 1;
1168 if (FAILED(
_music->CreatePort(guidPort, ¶ms, &
_port,
nullptr)))
return "Failed to create port";
1170 if (FAILED(
_port->Activate(TRUE)))
return "Failed to activate port";
1173 DMUS_BUFFERDESC desc{};
1174 desc.dwSize =
sizeof(DMUS_BUFFERDESC);
1175 desc.guidBufferFormat = KSDATAFORMAT_SUBTYPE_DIRECTMUSIC;
1176 desc.cbBuffer = 1024;
1177 if (FAILED(
_music->CreateMusicBuffer(&desc, &
_buffer,
nullptr)))
return "Failed to create music buffer";
1181 if (dls.has_value())
return dls;
1184 _thread_event = CreateEvent(
nullptr, FALSE, FALSE,
nullptr);
1185 if (
_thread_event ==
nullptr)
return "Can't create thread shutdown event";
1189 return std::nullopt;
1201 if (_dmusic_thread.joinable()) {
1202 _playback.shutdown =
true;
1209 IDirectMusicPortDownload *download_port =
nullptr;
1210 _port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port);
1214 for (std::vector<IDirectMusicDownload *>::reverse_iterator i =
_dls_downloads.rbegin(); download_port !=
nullptr && i !=
_dls_downloads.rend(); i++) {
1215 download_port->Unload(*i);
1220 if (download_port !=
nullptr) download_port->Release();
1228 if (
_port !=
nullptr) {
1229 _port->Activate(FALSE);
1252 if (!_playback.next_file.LoadSong(song))
return;
1256 _playback.next_segment.loop = song.
loop;
1258 _playback.do_start =
true;
1265 _playback.do_stop =
true;
1272 return _playback.playing || _playback.do_start;
1278 _playback.new_volume = vol;
Factory for the DirectX music player.
static std::optional< FileHandle > Open(const std::string &filename, std::string_view mode)
Open an RAII file handle if possible.
void SetVolume(uint8_t vol) override
Set the volume, if possible.
void StopSong() override
Stop playing the current song.
std::optional< std::string_view > Start(const StringList ¶m) override
Start this driver.
bool IsSongPlaying() override
Are we currently playing a song?
void Stop() override
Stop this driver.
~MusicDriver_DMusic() override
Stop the playing of the music.
void PlaySong(const MusicSongInfo &song) override
Play a particular song.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
bool playing
flag indicating that playback is active
uint8_t new_volume
volume setting to change to
bool shutdown
flag to indicate playback thread shutdown
static IDirectMusicBuffer * _buffer
The buffer object collects the data to sent.
bool do_stop
flag for stopping playback at next opportunity
int preload_time
preload time for music blocks.
static std::thread _dmusic_thread
Handle to our worker thread.
static constexpr REFERENCE_TIME MS_TO_REFTIME
DirectMusic time base is 100 ns.
MidiFile next_file
upcoming file to play
static IDirectMusicPort * _port
The port object lets us send MIDI data to the synthesizer.
bool do_start
flag for starting playback of next_file at next opportunity
static std::vector< IDirectMusicDownload * > _dls_downloads
List of downloaded DLS instruments.
static HANDLE _thread_event
Event to signal the thread that it should look at a state change.
PACK_N(struct ChunkHeader { FOURCC type;DWORD length;}, 2)
A RIFF chunk header.
static constexpr REFERENCE_TIME MIDITIME_TO_REFTIME
Time base of the midi file reader is 1 us.
static std::mutex _thread_mutex
Lock access to playback data that is not thread-safe.
static IDirectMusic * _music
The direct music object manages buffers and ports.
PlaybackSegment next_segment
segment info for upcoming file
static void TransmitNotesOff(IDirectMusicBuffer *buffer, REFERENCE_TIME block_time, REFERENCE_TIME cur_time)
Transmit 'Note off' messages to all MIDI channels.
Base of playing music via DirectMusic.
int GetDriverParamInt(const StringList &parm, std::string_view name, int def)
Get an integer parameter the list of parameters.
std::optional< std::string_view > GetDriverParam(const StringList &parm, std::string_view name)
Get a string parameter the list of parameters.
Functions for standard in/out file operations.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Declarations for MIDI data.
const uint8_t * MidiGetStandardSysexMessage(MidiSysexMessage msg, size_t &length)
Retrieve a well-known MIDI system exclusive message.
MidiSysexMessage
Well-known MIDI system exclusive message values for use with the MidiGetStandardSysexMessage function...
@ ResetGM
Reset device to General MIDI defaults.
@ RolandSetReverb
Set up Roland SoundCanvas reverb room as TTD does.
@ MIDIST_ENDSYSEX
only occurs in realtime data
Parser for standard MIDI files.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
std::vector< std::string > StringList
Type for a list of strings.
Instrument definition read from a DLS file.
An instrument region maps a note range to wave data.
Wave data definition from a DLS file.
bool ReadDLSInstrumentList(FileHandle &f, DWORD list_length)
Load a list of instruments from a DLS file.
bool LoadFile(std::string_view file)
Try loading a DLS file into memory.
bool ReadDLSWaveList(FileHandle &f, DWORD list_length)
Load a list of waves from a DLS file.
bool ReadDLSRegionList(FileHandle &f, DWORD list_length, DLSInstrument &instrument)
Load a list of regions from a DLS file.
bool ReadDLSWave(FileHandle &f, DWORD list_length, long offset)
Load a single wave from a DLS file.
bool ReadDLSRegion(FileHandle &f, DWORD list_length, std::vector< DLSRegion > &out)
Load a single region from a DLS file.
bool ReadDLSInstrument(FileHandle &f, DWORD list_length)
Load a single instrument from a DLS file.
bool ReadDLSArticulation(FileHandle &f, DWORD list_length, std::vector< CONNECTION > &out)
Load an articulation structure from a DLS file.
std::vector< uint8_t > data
raw midi data contained in block
uint32_t ticktime
tick number since start of file this block should be triggered at
int64_t realtime
real-time (microseconds) since start of file this block should be triggered at
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, std::string_view name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
std::string_view 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.
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Declarations of functions for MS windows systems.
uint8_t current_volume
current effective volume setting
MidiFile current_file
file currently being played from
PlaybackSegment current_segment
segment info for current playback
size_t current_block
next block index to send
std::array< uint8_t, 16 > channel_volumes
last seen volume controller values in raw data
std::mutex lock
synchronization for playback status fields
DWORD playback_start_time
timestamp current file began playback