11 #include "../stdafx.h"
12 #ifdef WIN32_LEAN_AND_MEAN
13 # undef WIN32_LEAN_AND_MEAN
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"
22 #include "midifile.hpp"
30 #include "../safeguards.h"
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;
74 bool operator ==(
long offset)
const
76 return this->file_offset == offset;
80 std::vector<DLSInstrument> instruments;
81 std::vector<POOLCUE> pool_cues;
82 std::vector<DLSWave> waves;
85 bool LoadFile(
const std::string &file);
112 DMUS_DOWNLOADINFO dlInfo;
113 ULONG ulOffsetTable[2];
115 DMUS_WAVEDATA dmWaveData;
147 static IDirectMusicPort *
_port =
nullptr;
159 while (list_length > 0) {
161 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
162 list_length -= chunk.length +
sizeof(chunk);
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);
170 for (ULONG i = 0; i < conns.cConnections; i++) {
172 if (fread(&con,
sizeof(con), 1, f) != 1)
return false;
176 fseek(f, chunk.length, SEEK_CUR);
189 region.wave_sample.cbSize = 0;
191 while (list_length > 0) {
193 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
194 list_length -= chunk.length +
sizeof(chunk);
196 if (chunk.type == FOURCC_LIST) {
198 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
199 chunk.length -=
sizeof(chunk.type);
202 switch (chunk.type) {
204 if (fread(®ion.hdr,
sizeof(region.hdr), 1, f) != 1)
return false;
208 if (fread(®ion.wave_sample,
sizeof(region.wave_sample), 1, f) != 1)
return false;
209 fseek(f, region.wave_sample.cbSize -
sizeof(region.wave_sample), SEEK_CUR);
212 for (ULONG i = 0; i < region.wave_sample.cSampleLoops; i++) {
214 if (fread(&loop,
sizeof(loop), 1, f) != 1)
return false;
215 region.wave_loops.push_back(loop);
220 if (fread(®ion.wave,
sizeof(region.wave), 1, f) != 1)
return false;
229 fseek(f, chunk.length, SEEK_CUR);
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);
244 while (list_length > 0) {
246 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
247 list_length -= chunk.length +
sizeof(chunk);
249 if (chunk.type == FOURCC_LIST) {
251 if (fread(&list_type,
sizeof(list_type), 1, f) != 1)
return false;
253 if (list_type == FOURCC_RGN) {
254 this->
ReadDLSRegion(f, chunk.length -
sizeof(list_type), instrument.regions);
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);
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);
273 while (list_length > 0) {
275 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
276 list_length -= chunk.length +
sizeof(chunk);
278 if (chunk.type == FOURCC_LIST) {
280 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
281 chunk.length -=
sizeof(chunk.type);
284 switch (chunk.type) {
286 if (fread(&instrument.hdr,
sizeof(instrument.hdr), 1, f) != 1)
return false;
299 fseek(f, chunk.length, SEEK_CUR);
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);
314 while (list_length > 0) {
316 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
317 list_length -= chunk.length +
sizeof(chunk);
319 if (chunk.type == FOURCC_LIST) {
321 if (fread(&list_type,
sizeof(list_type), 1, f) != 1)
return false;
323 if (list_type == FOURCC_INS) {
324 Debug(driver, 6,
"DLS: Reading instrument {}", (
int)instruments.size());
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);
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);
342 this->waves.push_back(
DLSWave());
343 DLSWave &wave = this->waves.back();
347 wave.wave_sample.cbSize =
sizeof(WSMPL);
348 wave.wave_sample.usUnityNote = 60;
349 wave.file_offset = offset;
351 while (list_length > 0) {
353 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
354 list_length -= chunk.length +
sizeof(chunk);
356 if (chunk.type == FOURCC_LIST) {
358 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
359 chunk.length -=
sizeof(chunk.type);
362 switch (chunk.type) {
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);
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);
373 for (ULONG i = 0; i < wave.wave_sample.cSampleLoops; i++) {
375 if (fread(&loop,
sizeof(loop), 1, f) != 1)
return false;
376 wave.wave_loops.push_back(loop);
381 wave.data.resize(chunk.length);
382 if (fread(&wave.data[0],
sizeof(BYTE), wave.data.size(), f) != wave.data.size())
return false;
387 fseek(f, chunk.length, SEEK_CUR);
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);
402 long base_offset = ftell(f);
404 while (list_length > 0) {
405 long chunk_offset = ftell(f);
408 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
409 list_length -= chunk.length +
sizeof(chunk);
411 if (chunk.type == FOURCC_LIST) {
413 if (fread(&list_type,
sizeof(list_type), 1, f) != 1)
return false;
415 if (list_type == FOURCC_wave) {
416 Debug(driver, 6,
"DLS: Reading wave {}", waves.size());
418 if (!this->
ReadDLSWave(f, chunk.length -
sizeof(list_type), chunk_offset - base_offset))
return false;
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);
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);
434 Debug(driver, 2,
"DMusic: Try to load DLS file {}", file);
437 if (!of.has_value())
return false;
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;
447 hdr.length -=
sizeof(FOURCC);
449 Debug(driver, 2,
"DMusic: Parsing DLS file");
455 while (hdr.length > 0) {
457 if (fread(&chunk,
sizeof(chunk), 1, f) != 1)
return false;
458 hdr.length -= chunk.length +
sizeof(chunk);
460 if (chunk.type == FOURCC_LIST) {
462 if (fread(&chunk.type,
sizeof(chunk.type), 1, f) != 1)
return false;
463 chunk.length -=
sizeof(chunk.type);
466 switch (chunk.type) {
468 if (fread(&header,
sizeof(header), 1, f) != 1)
return false;
481 if (fread(&ptbl,
sizeof(ptbl), 1, f) != 1)
return false;
482 fseek(f, ptbl.cbSize -
sizeof(ptbl), SEEK_CUR);
485 for (ULONG i = 0; i < ptbl.cCues; i++) {
487 if (fread(&cue,
sizeof(cue), 1, f) != 1)
return false;
488 this->pool_cues.push_back(cue);
494 fseek(f, chunk.length, SEEK_CUR);
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);
505 if (header.cInstruments != this->instruments.size())
return false;
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());
521 static uint8_t ScaleVolume(uint8_t original, uint8_t scale)
523 return original * scale / 127;
526 static void TransmitChannelMsg(IDirectMusicBuffer *buffer, REFERENCE_TIME rt, uint8_t status, uint8_t p1, uint8_t p2 = 0)
528 if (buffer->PackStructured(rt, 0, status | (p1 << 8) | (p2 << 16)) == E_OUTOFMEMORY) {
530 _port->PlayBuffer(buffer);
533 buffer->PackStructured(rt, 0, status | (p1 << 8) | (p2 << 16));
537 static void TransmitSysex(IDirectMusicBuffer *buffer, REFERENCE_TIME rt,
const uint8_t *&msg_start,
size_t &remaining)
540 const uint8_t *msg_end = msg_start;
541 while (*msg_end != MIDIST_ENDSYSEX) msg_end++;
544 if (buffer->PackUnstructured(rt, 0, msg_end - msg_start,
const_cast<LPBYTE
>(msg_start)) == E_OUTOFMEMORY) {
546 _port->PlayBuffer(buffer);
549 buffer->PackUnstructured(rt, 0, msg_end - msg_start,
const_cast<LPBYTE
>(msg_start));
553 remaining -= msg_end - msg_start;
557 static void TransmitStandardSysex(IDirectMusicBuffer *buffer, REFERENCE_TIME rt, MidiSysexMessage msg)
560 const uint8_t *data = MidiGetStandardSysexMessage(msg, length);
561 TransmitSysex(buffer, rt, data, length);
565 static void TransmitNotesOff(IDirectMusicBuffer *buffer, REFERENCE_TIME block_time, REFERENCE_TIME cur_time)
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);
574 TransmitStandardSysex(buffer, block_time + 20, MidiSysexMessage::ResetGM);
575 TransmitStandardSysex(buffer, block_time + 30, MidiSysexMessage::RolandSetReverb);
579 _port->PlayBuffer(buffer);
586 static void MidiThreadProc()
588 Debug(driver, 2,
"DMusic: Entering playback thread");
590 REFERENCE_TIME last_volume_time = 0;
591 REFERENCE_TIME block_time = 0;
600 IReferenceClock *clock;
601 _port->GetLatencyClock(&clock);
603 REFERENCE_TIME cur_time;
604 clock->GetTime(&cur_time);
609 DWORD next_timeout = 1000;
612 DWORD wfso = WaitForSingleObject(
_thread_event, next_timeout);
614 if (_playback.shutdown) {
615 _playback.playing =
false;
619 if (_playback.do_stop) {
620 Debug(driver, 2,
"DMusic thread: Stopping playback");
623 clock->GetTime(&cur_time);
626 _playback.playing =
false;
627 _playback.do_stop =
false;
633 if (wfso == WAIT_OBJECT_0) {
634 if (_playback.do_start) {
635 Debug(driver, 2,
"DMusic thread: Starting playback");
644 _playback.playing =
true;
645 _playback.do_start =
false;
649 clock->GetTime(&cur_time);
655 last_volume_time = 0;
663 if (_playback.playing) {
669 size_t preload_bytes = 0;
672 preload_bytes += block.
data.size();
675 Debug(driver, 2,
"DMusic: timer: loop from block {} (ticktime {}, realtime {:.3f}, bytes {})", bl, block.
ticktime, ((
int)block.
realtime) / 1000.0, preload_bytes);
682 Debug(driver, 2,
"DMusic: timer: start from block {} (ticktime {}, realtime {:.3f}, bytes {})", bl, block.
ticktime, ((
int)block.
realtime) / 1000.0, preload_bytes);
691 REFERENCE_TIME current_time;
692 clock->GetTime(¤t_time);
697 Debug(driver, 2,
"DMusic thread: volume change");
699 last_volume_time = current_time;
700 for (
int ch = 0; ch < 16; ch++) {
702 TransmitChannelMsg(
_buffer, block_time + 1, MIDIST_CONTROLLER | ch, MIDICT_CHANVOLUME, vol);
715 Debug(driver, 2,
"DMusic thread: Looping song");
719 _playback.do_stop =
true;
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) {
743 uint8_t status = data[0];
745 last_status = status;
749 status = last_status;
751 switch (status & 0xF0) {
753 case MIDIST_CHANPRESS:
755 TransmitChannelMsg(
_buffer, block_time, status, data[0]);
761 case MIDIST_POLYPRESS:
762 case MIDIST_PITCHBEND:
764 TransmitChannelMsg(
_buffer, block_time, status, data[0], data[1]);
768 case MIDIST_CONTROLLER:
770 if (data[0] == MIDICT_CHANVOLUME) {
774 TransmitChannelMsg(
_buffer, block_time, status, data[0], vol);
777 TransmitChannelMsg(
_buffer, block_time, status, data[0], data[1]);
786 TransmitSysex(
_buffer, block_time, data, remaining);
788 case MIDIST_TC_QFRAME:
793 case MIDIST_SONGPOSPTR:
808 DWORD used_buffer = 0;
809 _buffer->GetUsedBytes(&used_buffer);
810 if (used_buffer > 0) {
821 _playback.do_stop =
true;
828 Debug(driver, 2,
"DMusic: Exiting playback thread");
831 clock->GetTime(&cur_time);
833 Sleep(_playback.preload_time * 4);
838 static void * DownloadArticulationData(
int base_offset,
void *data,
const std::vector<CONNECTION> &artic)
840 DMUS_ARTICULATION2 *art = (DMUS_ARTICULATION2 *)data;
841 art->ulArtIdx = base_offset + 1;
842 art->ulFirstExtCkIdx = 0;
843 art->ulNextArtIdx = 0;
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());
850 return (CONNECTION *)(con_list + 1) + artic.size();
853 static const char *LoadDefaultDLSFile(
const char *user_dls)
857 caps.dwSize =
sizeof(DMUS_PORTCAPS);
858 _port->GetCaps(&caps);
861 if ((caps.dwFlags & (DMUS_PC_DLS | DMUS_PC_DLS2)) != 0 && (caps.dwFlags & DMUS_PC_GMINHARDWARE) == 0) {
864 if (user_dls ==
nullptr) {
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);
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");
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)));
884 if (!dls_file.
LoadFile(
FS2OTTD(path)))
return "Can't load GM DLS collection";
887 if (!dls_file.
LoadFile(user_dls))
return "Can't load GM DLS collection";
891 IDirectMusicPortDownload *download_port =
nullptr;
892 if (FAILED(
_port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port)))
return "Can't get download port";
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";
901 download_port->GetAppend(&dwAppend);
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";
913 if (FAILED(dl_wave->GetBuffer((LPVOID *)&wave, &wave_size))) {
915 download_port->Release();
916 return "Can't get wave download buffer";
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());
933 if (FAILED(download_port->Download(dl_wave))) {
934 download_port->Release();
935 return "Downloading DLS wave failed";
940 for (DWORD i = 0; i < dls_file.instruments.size(); i++) {
941 DWORD offsets = 1 + (DWORD)dls_file.instruments[i].regions.size();
944 size_t i_size =
sizeof(DMUS_DOWNLOADINFO) +
sizeof(DMUS_INSTRUMENT);
945 if (!dls_file.instruments[i].articulators.empty()) {
948 i_size +=
sizeof(DMUS_ARTICULATION2) +
sizeof(CONNECTIONLIST) +
sizeof(CONNECTION) * dls_file.instruments[i].articulators.size();
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()) {
954 i_size +=
sizeof(DMUS_ARTICULATION2) +
sizeof(CONNECTIONLIST) +
sizeof(CONNECTION) * rgn->articulators.size();
959 if (rgn->wave_sample.cbSize != 0) {
960 i_size +=
sizeof(DMUS_REGION) -
sizeof(DMUS_REGION::WLOOP) +
sizeof(WLOOP) * rgn->wave_loops.size();
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();
966 i_size += offsets *
sizeof(ULONG);
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";
977 if (FAILED(dl_inst->GetBuffer((LPVOID *)&instrument, &inst_size))) {
979 download_port->Release();
980 return "Can't get instrument download buffer";
982 char *inst_base = (
char *)instrument;
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;
993 ULONG *offset_table = (ULONG *)instrument;
994 instrument = offset_table + offsets;
998 DMUS_INSTRUMENT *inst_data = (DMUS_INSTRUMENT *)instrument;
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;
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;
1010 instrument = DownloadArticulationData(inst_data->ulGlobalArtIdx, instrument, dls_file.instruments[i].articulators);
1011 assert((
char *)instrument - inst_base <= (ptrdiff_t)inst_size);
1015 inst_data->ulFirstRegionIdx = last_offset;
1016 for (uint j = 0; j < dls_file.instruments[i].regions.size(); j++) {
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;
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;
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());
1036 instrument = (
char *)(inst_region + 1) -
sizeof(DMUS_REGION::WLOOP) +
sizeof(WLOOP) * rgn.wave_loops.size();
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());
1041 instrument = (
char *)(inst_region + 1) -
sizeof(DMUS_REGION::WLOOP) +
sizeof(WLOOP) * dls_file.waves[wave_id].wave_loops.size();
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;
1050 instrument = DownloadArticulationData(inst_region->ulRegionArtIdx, instrument, rgn.articulators);
1052 inst_region->ulRegionArtIdx = 0;
1054 assert((
char *)instrument - inst_base <= (ptrdiff_t)inst_size);
1057 inst_region->ulNextRegionIdx = j < dls_file.instruments[i].regions.size() - 1 ? last_offset : 0;
1061 if (FAILED(download_port->Download(dl_inst))) {
1062 download_port->Release();
1063 return "Downloading DLS instrument failed";
1067 download_port->Release();
1077 if (FAILED(CoInitializeEx(
nullptr, COINIT_MULTITHREADED)))
return "COM initialization failed";
1080 if (FAILED(CoCreateInstance(
1087 return "Failed to create the music object";
1091 if (FAILED(
_music->SetDirectSound(
nullptr,
nullptr)))
return "Can't set DirectSound interface";
1098 if (_debug_driver_level > 0) {
1100 char desc[DMUS_MAX_DESCRIPTION];
1104 caps.dwSize =
sizeof(DMUS_PORTCAPS);
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)" :
"");
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;
1124 if (FAILED(
_music->GetDefaultPort(&guidPort)))
return "Can't query default music port";
1128 DMUS_PORTPARAMS params;
1130 params.dwSize =
sizeof(DMUS_PORTPARAMS);
1131 params.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
1132 params.dwChannelGroups = 1;
1133 if (FAILED(
_music->CreatePort(guidPort, ¶ms, &
_port,
nullptr)))
return "Failed to create port";
1135 if (FAILED(
_port->Activate(TRUE)))
return "Failed to activate port";
1138 DMUS_BUFFERDESC desc;
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";
1146 const char *dls = LoadDefaultDLSFile(
GetDriverParam(parm,
"dls"));
1147 if (dls !=
nullptr)
return dls;
1150 _thread_event = CreateEvent(
nullptr, FALSE, FALSE,
nullptr);
1151 if (
_thread_event ==
nullptr)
return "Can't create thread shutdown event";
1155 return std::nullopt;
1159 MusicDriver_DMusic::~MusicDriver_DMusic()
1167 if (_dmusic_thread.joinable()) {
1168 _playback.shutdown =
true;
1175 IDirectMusicPortDownload *download_port =
nullptr;
1176 _port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port);
1180 for (std::vector<IDirectMusicDownload *>::reverse_iterator i =
_dls_downloads.rbegin(); download_port !=
nullptr && i !=
_dls_downloads.rend(); i++) {
1181 download_port->Unload(*i);
1186 if (download_port !=
nullptr) download_port->Release();
1194 if (
_port !=
nullptr) {
1195 _port->Activate(FALSE);
1215 if (!_playback.next_file.LoadSong(song))
return;
1219 _playback.next_segment.loop = song.
loop;
1221 _playback.do_start =
true;
1228 _playback.do_stop =
true;
1235 return _playback.playing || _playback.do_start;
1241 _playback.new_volume = vol;
Factory for the DirectX music player.
static std::optional< FileHandle > Open(const std::string &filename, const std::string &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.
void PlaySong(const MusicSongInfo &song) override
Play a particular song.
#define Debug(category, level, format_string,...)
Ouptut 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 const int MIDITIME_TO_REFTIME
Time base of the midi file reader is 1 us.
static std::thread _dmusic_thread
Handle to our worker thread.
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 const int MS_TO_REFTIME
DirectMusic time base is 100 ns.
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.
const char * GetDriverParam(const StringList &parm, const char *name)
Get a string parameter the list of parameters.
int GetDriverParamInt(const StringList &parm, const char *name, int def)
Get an integer parameter the list of parameters.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
void MemSetT(T *ptr, uint8_t value, size_t num=1)
Type-safe version of memset().
#define lengthof(array)
Return the length of an fixed size array.
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(const std::string &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 realtime
real-time (microseconds) since start of file this block should be triggered at
uint32_t ticktime
tick number since start of file this block should be triggered at
void MoveFrom(MidiFile &other)
Move data from other to this, and clears other.
std::vector< DataBlock > blocks
sequential time-annotated data of file, merged to a single track
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.
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
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.
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::mutex lock
synchronization for playback status fields
uint8_t channel_volumes[16]
last seen volume controller values in raw data
DWORD playback_start_time
timestamp current file began playback