Debian Codegraph @

common/misc/hmp.cpp

raw
1 /*
2 * This file is part of the DXX-Rebirth project <https://www.dxx-rebirth.com/>.
3 * It is copyright by its individual contributors, as recorded in the
4 * project's Git history. See COPYING.txt at the top level for license
5 * terms and a link to the Git history.
6 */
7 /*
8 * This code handles HMP files. It can:
9 * - Open/read/close HMP files
10 * - Play HMP via Windows MIDI
11 * - Convert HMP to MIDI for further use
12 * Based on work of Arne de Bruijn and the JFFEE project
13 */
14 #include <stdexcept>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18
19 #include "hmp.h"
20 #include "u_mem.h"
21 #include "console.h"
22 #include "timer.h"
23 #include "serial.h"
24
25 #include "dxxsconf.h"
26 #include "dsx-ns.h"
27 #include "compiler-range_for.h"
28 #include "d_range.h"
29 #include "d_underlying_value.h"
30 #include "d_zip.h"
31 #include "partial_range.h"
32
33 namespace dcx {
34
35 #define MIDIINT(x) (words_bigendian ? (x) : (SWAPINT(x)))
36 #define MIDISHORT(x) (words_bigendian ? (x) : (SWAPSHORT(x)))
37
38 #ifdef _WIN32
39 namespace {
40 static int midi_volume;
41 static int channel_volume[16];
42 static void hmp_stop(hmp_file *hmp);
43 }
44 #endif
45
46 // READ/OPEN/CLOSE HMP
47
48 hmp_file::~hmp_file()
49 {
50 #ifdef _WIN32
51 hmp_stop(this);
52 #endif
53 }
54
55 hmp_open_result hmp_open(const char *const filename)
56 {
57 int tempo;
58 const auto fpe = PHYSFSX_openReadBuffered(filename);
59
60 if (!fpe.first)
61 return {nullptr, hmp_open_error::physfs_open, fpe.second};
62 auto &fp = fpe.first;
63
64 char buf[8];
65 const auto physfs_error = [](hmp_open_error e) {
66 return hmp_open_result{nullptr, e, PHYSFS_getLastErrorCode()};
67 };
68 const auto data_error = [](hmp_open_error e) {
69 return hmp_open_result{nullptr, e, PHYSFS_ErrorCode{}};
70 };
71 if (constexpr std::size_t buffer_size{std::size(buf)}; PHYSFSX_readBytes(fp, std::data(buf), buffer_size) != buffer_size)
72 return physfs_error(hmp_open_error::physfs_read_header);
73 if (memcmp(buf, "HMIMIDIP", 8))
74 return data_error(hmp_open_error::content_header);
75
76 if (!PHYSFS_seek(fp, 0x30))
77 return physfs_error(hmp_open_error::physfs_seek0);
78
79 unsigned num_tracks;
80 if (PHYSFSX_readBytes(fp, &num_tracks, 4) != 4)
81 return physfs_error(hmp_open_error::physfs_read_tracks);
82
83 if ((num_tracks < 1) || (num_tracks > HMP_TRACKS))
84 return data_error(hmp_open_error::track_count);
85 std::unique_ptr<hmp_file> hmp(new hmp_file{});
86 hmp->num_trks = num_tracks;
87
88 if (!PHYSFS_seek(fp, 0x38))
89 return physfs_error(hmp_open_error::physfs_seek1);
90 if (PHYSFSX_readBytes(fp, &tempo, 4) != 4)
91 return physfs_error(hmp_open_error::physfs_read_tempo);
92 hmp->tempo = INTEL_INT(tempo);
93
94 if (!PHYSFS_seek(fp, 0x308))
95 return physfs_error(hmp_open_error::physfs_seek2);
96
97 range_for (auto &i, partial_range(hmp->trks, num_tracks))
98 {
99 std::array<int, 3> tdata;
100 /* Discard tdata[0] and tdata[2]. They are read to avoid needing a
101 * seek operation to skip them.
102 */
103 if (constexpr std::size_t buffer_size{std::size(tdata) * sizeof(tdata[0])}; PHYSFSX_readBytes(fp, std::data(tdata), buffer_size) != buffer_size)
104 return physfs_error(hmp_open_error::physfs_read_track_length);
105
106 int data{tdata[1]};
107 data -= 12;
108 i.len = data;
109 i.data = std::make_unique<uint8_t[]>(data);
110 /* finally, read track data */
111 if (PHYSFSX_readBytes(fp, i.data.get(), data) != data)
112 return physfs_error(hmp_open_error::physfs_read_track_data);
113 i.loop_set = 0;
114 }
115 hmp->filesize = PHYSFS_fileLength(fp);
116 return {std::move(hmp), hmp_open_error::None, PHYSFS_ErrorCode{}};
117 }
118
119 #ifdef _WIN32
120 // PLAY HMP AS MIDI
121 namespace {
122
123 void hmp_stop(hmp_file *hmp)
124 {
125 MIDIHDR *mhdr;
126 if (!hmp->stop) {
127 hmp->stop = 1;
128 //PumpMessages();
129 midiStreamStop(hmp->hmidi);
130 while (hmp->bufs_in_mm)
131 timer_delay(1);
132 }
133 while ((mhdr = hmp->evbuf)) {
134 midiOutUnprepareHeader(reinterpret_cast<HMIDIOUT>(hmp->hmidi), mhdr, sizeof(MIDIHDR));
135 hmp->evbuf = mhdr->lpNext;
136 }
137
138 if (hmp->hmidi) {
139 midiStreamClose(hmp->hmidi);
140 hmp->hmidi = NULL;
141 }
142 }
143
144 /*
145 * read a HMI type variable length number
146 */
147 static int get_var_num_hmi(unsigned char *data, int datalen, unsigned long *value) {
148 unsigned char *p;
149 unsigned long v = 0;
150 int shift{0};
151
152 p = data;
153 while ((datalen > 0) && !(*p & 0x80)) {
154 v += *(p++) << shift;
155 shift += 7;
156 datalen --;
157 }
158 if (!datalen)
159 return 0;
160 v += (*(p++) & 0x7f) << shift;
161 if (value) *value = v;
162 return p - data;
163 }
164
165 /*
166 * read a MIDI type variable length number
167 */
168 static int get_var_num(unsigned char *data, int datalen,
169 unsigned *value) {
170 unsigned char *orgdata = data;
171 unsigned long v = 0;
172
173 while ((datalen > 0) && (*data & 0x80))
174 v = (v << 7) + (*(data++) & 0x7f);
175 if (!datalen)
176 return 0;
177 v = (v << 7) + *(data++);
178 if (value) *value = v;
179 return data - orgdata;
180 }
181
182 static int get_event(hmp_file *hmp, event *ev) {
183 static const std::array<int, 7> cmdlen{{3,3,3,3,2,2,3}};
184 unsigned long got;
185 unsigned long mindelta, delta;
186 int ev_num;
187 hmp_track *fndtrk = nullptr;
188
189 mindelta = INT_MAX;
190 range_for (auto &rtrk, partial_range(hmp->trks, static_cast<unsigned>(hmp->num_trks)))
191 {
192 const auto trk = &rtrk;
193 if (!trk->left || (hmp->loop_start && hmp->looping && !trk->loop_set))
194 continue;
195 if (!(got = get_var_num_hmi(trk->cur, trk->left, &delta)))
196 return HMP_INVALID_FILE;
197 if (trk->left > got + 2 && *(trk->cur + got) == 0xff
198 && *(trk->cur + got + 1) == 0x2f) {/* end of track */
199 trk->left = 0;
200 continue;
201 }
202
203 if (hmp->loop_start && hmp->looping)
204 if (trk->cur == trk->loop)
205 delta = trk->loop_start - hmp->loop_start;
206
207 delta += trk->cur_time - hmp->cur_time;
208 if (delta < mindelta) {
209 mindelta = delta;
210 fndtrk = trk;
211 }
212 }
213 const auto trk{fndtrk};
214 if (!trk)
215 return HMP_EOF;
216
217 got = get_var_num_hmi(trk->cur, trk->left, &delta);
218
219 if (hmp->loop_start && hmp->looping)
220 if (trk->cur == trk->loop)
221 delta = trk->loop_start - hmp->loop_start;
222
223 trk->cur_time += delta;
224
225 if (!hmp->loop_start && *(trk->cur + got) >> 4 == MIDI_CONTROL_CHANGE && *(trk->cur + got + 1) == HMP_LOOP_START)
226 {
227 hmp->loop_start = trk->cur_time;
228 if ((hmp->filesize == 86949) && (trk->cur_time == 29)) // special ugly HACK HACK HACK for Descent2-version of descent.hmp where loop at this point causes instruments not being reset properly. No track supporting HMP loop I know of meets the requirements for the condition below and even if so - it only disabled the HMP loop feature.
229 {
230 hmp->loop_start = 0;
231 }
232
233 }
234
235 if (!hmp->loop_end && *(trk->cur + got) >> 4 == MIDI_CONTROL_CHANGE && *(trk->cur + got + 1) == HMP_LOOP_END)
236 hmp->loop_end = trk->cur_time;
237
238 if (hmp->loop_start && !trk->loop_set && trk->cur_time >= hmp->loop_start)
239 {
240 trk->loop_start = trk->cur_time;
241 trk->loop = trk->cur;
242 trk->len = trk->left;
243 trk->loop_set = 1;
244 }
245
246 if (hmp->loop_end && trk->cur_time > hmp->loop_end)
247 return HMP_EOF;
248
249 ev->delta = trk->cur_time - hmp->cur_time;
250 hmp->cur_time = trk->cur_time;
251
252 if ((trk->left -= got) < 3)
253 return HMP_INVALID_FILE;
254 trk->cur += got;
255 /*memset(ev, 0, sizeof(*ev));*/ev->datalen = 0;
256 ev->msg[0] = ev_num = *(trk->cur++);
257 trk->left--;
258 if (ev_num < 0x80)
259 return HMP_INVALID_FILE; /* invalid command */
260 if (ev_num < 0xf0) {
261 ev->msg[1] = *(trk->cur++);
262 trk->left--;
263 if (cmdlen[((ev_num) >> 4) - 8] == 3) {
264 ev->msg[2] = *(trk->cur++);
265 trk->left--;
266
267 if (ev->msg[0] >> 4 == MIDI_CONTROL_CHANGE && ev->msg[1] == MIDI_VOLUME)
268 {
269 channel_volume[ev->msg[0] & 0xf] = ev->msg[2];
270
271 ev->msg[2] = ev->msg[2] * midi_volume / MIDI_VOLUME_SCALE;
272 }
273 }
274 } else if (ev_num == 0xff) {
275 ev->msg[1] = *(trk->cur++);
276 trk->left--;
277 if (!(got = get_var_num(ev->data = trk->cur,
278 trk->left, &ev->datalen)))
279 return HMP_INVALID_FILE;
280 trk->cur += ev->datalen;
281 if (trk->left <= ev->datalen)
282 return HMP_INVALID_FILE;
283 trk->left -= ev->datalen;
284 } else /* sysex -> error */
285 return HMP_INVALID_FILE;
286 return 0;
287 }
288
289 static int fill_buffer(hmp_file *hmp) {
290 MIDIHDR *mhdr = hmp->evbuf;
291 unsigned int *p = reinterpret_cast<unsigned int *>(mhdr->lpData + mhdr->dwBytesRecorded);
292 unsigned int *pend = reinterpret_cast<unsigned int *>(mhdr->lpData + mhdr->dwBufferLength);
293 unsigned int i;
294 event ev{};
295
296 while (p + 4 <= pend) {
297 if (hmp->pending_size) {
298 i = (p - pend) * 4;
299 if (i > hmp->pending_size)
300 i = hmp->pending_size;
301 *(p++) = hmp->pending_event | i;
302 *(p++) = 0;
303 memcpy(reinterpret_cast<uint8_t *>(p), hmp->pending, i);
304 hmp->pending_size -= i;
305 p += (i + 3) / 4;
306 } else {
307 if ((i = get_event(hmp, &ev))) {
308 mhdr->dwBytesRecorded = (reinterpret_cast<uint8_t *>(p)) - (reinterpret_cast<uint8_t *>(mhdr->lpData));
309 return i;
310 }
311 if (ev.datalen) {
312 hmp->pending_size = ev.datalen;
313 hmp->pending = ev.data;
314 hmp->pending_event = ev.msg[0] << 24;
315 } else {
316 *(p++) = ev.delta;
317 *(p++) = 0;
318 *(p++) = (static_cast<DWORD>(MEVT_SHORTMSG) << 24) |
319 static_cast<DWORD>(ev.msg[0]) |
320 (static_cast<DWORD>(ev.msg[1]) << 8) |
321 (static_cast<DWORD>(ev.msg[2]) << 16);
322 }
323 }
324 }
325 mhdr->dwBytesRecorded = (reinterpret_cast<uint8_t *>(p)) - (reinterpret_cast<uint8_t *>(mhdr->lpData));
326 return 0;
327 }
328
329 static void setup_buffers(hmp_file &hmp)
330 {
331 MIDIHDR *lastbuf = nullptr;
332 for (auto &&[header, buffer] : zip(hmp.midi_headers, hmp.midi_buffers))
333 {
334 header = {};
335 header.lpData = buffer.data();
336 header.dwBufferLength = std::size(buffer);
337 header.dwUser = reinterpret_cast<uintptr_t>(std::addressof(hmp));
338 header.lpNext = lastbuf;
339 lastbuf = &header;
340 }
341 hmp.evbuf = lastbuf;
342 }
343
344 static void reset_tracks(struct hmp_file *hmp)
345 {
346 if (hmp->num_trks > 0)
347 range_for (auto &i, partial_range(hmp->trks, static_cast<unsigned>(hmp->num_trks)))
348 {
349 if (i.loop_set)
350 i.cur = i.loop;
351 else
352 i.cur = i.data.get();
353 i.left = i.len;
354 i.cur_time = 0;
355 }
356 hmp->cur_time = 0;
357 }
358
359 static void _stdcall midi_callback(HMIDISTRM, UINT uMsg, DWORD, DWORD_PTR dw1, DWORD)
360 {
361 hmp_file *hmp;
362 int rc;
363
364 if (uMsg != MOM_DONE)
365 return;
366
367 const auto mhdr = reinterpret_cast<MIDIHDR *>(dw1);
368 mhdr->dwBytesRecorded = 0;
369 hmp = reinterpret_cast<hmp_file *>(mhdr->dwUser);
370 mhdr->lpNext = hmp->evbuf;
371 hmp->evbuf = mhdr;
372 hmp->bufs_in_mm--;
373
374 if (!hmp->stop) {
375 while (fill_buffer(hmp) == HMP_EOF) {
376 if (hmp->bLoop)
377 hmp->stop = 0;
378 else
379 hmp->stop = 1;
380
381 hmp->looping = 1;
382
383 reset_tracks(hmp);
384 }
385 if ((rc = midiStreamOut(hmp->hmidi, hmp->evbuf,
386 sizeof(MIDIHDR))) != MMSYSERR_NOERROR) {
387 /* ??? */
388 } else {
389 hmp->evbuf = hmp->evbuf->lpNext;
390 hmp->bufs_in_mm++;
391 }
392 }
393 }
394
395 static void setup_tempo(hmp_file *hmp, unsigned long tempo) {
396 MIDIHDR *mhdr = hmp->evbuf;
397 unsigned int *p = reinterpret_cast<unsigned int *>(mhdr->lpData + mhdr->dwBytesRecorded);
398 *(p++) = 0;
399 *(p++) = 0;
400 *(p++) = ((static_cast<DWORD>(MEVT_TEMPO))<<24) | tempo;
401 mhdr->dwBytesRecorded += 12;
402 }
403
404 }
405
406 void hmp_setvolume(hmp_file *hmp, int volume)
407 {
408 if (hmp)
409 range_for (const int channel, xrange(16u))
410 midiOutShortMsg(reinterpret_cast<HMIDIOUT>(hmp->hmidi), static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_VOLUME << 8 | (channel_volume[channel] * volume / MIDI_VOLUME_SCALE) << 16));
411
412 midi_volume = volume;
413 }
414
415 int hmp_play(hmp_file *hmp, int bLoop)
416 {
417 int rc;
418 MIDIPROPTIMEDIV mptd;
419
420 hmp->bLoop = bLoop;
421 hmp->loop_start = 0;
422 hmp->loop_end = 0;
423 hmp->looping = 0;
424 hmp->devid = MIDI_MAPPER;
425
426 setup_buffers(*hmp);
427 if ((midiStreamOpen(&hmp->hmidi, &hmp->devid, 1, reinterpret_cast<DWORD_PTR>(&midi_callback), 0, CALLBACK_FUNCTION)) != MMSYSERR_NOERROR)
428 {
429 hmp->hmidi = NULL;
430 return HMP_MM_ERR;
431 }
432 mptd.cbStruct = sizeof(mptd);
433 mptd.dwTimeDiv = hmp->tempo;
434 if ((midiStreamProperty(hmp->hmidi, reinterpret_cast<BYTE *>(&mptd), MIDIPROP_SET|MIDIPROP_TIMEDIV)) != MMSYSERR_NOERROR)
435 {
436 return HMP_MM_ERR;
437 }
438
439 reset_tracks(hmp);
440 setup_tempo(hmp, 0x0f4240);
441
442 hmp->stop = 0;
443 while (hmp->evbuf) {
444 if ((rc = fill_buffer(hmp))) {
445 if (rc == HMP_EOF) {
446 reset_tracks(hmp);
447 continue;
448 } else
449 return rc;
450 }
451 if ((rc = midiOutPrepareHeader(reinterpret_cast<HMIDIOUT>(hmp->hmidi), hmp->evbuf,
452 sizeof(MIDIHDR))) != MMSYSERR_NOERROR) {
453 return HMP_MM_ERR;
454 }
455 if ((rc = midiStreamOut(hmp->hmidi, hmp->evbuf,
456 sizeof(MIDIHDR))) != MMSYSERR_NOERROR) {
457 return HMP_MM_ERR;
458 }
459 hmp->evbuf = hmp->evbuf->lpNext;
460 hmp->bufs_in_mm++;
461 }
462 midiStreamRestart(hmp->hmidi);
463 return 0;
464 }
465
466 void hmp_pause(hmp_file *hmp)
467 {
468 if (hmp)
469 midiStreamPause(hmp->hmidi);
470 }
471
472 void hmp_resume(hmp_file *hmp)
473 {
474 if (hmp)
475 midiStreamRestart(hmp->hmidi);
476 }
477
478 void hmp_reset()
479 {
480 HMIDIOUT hmidi;
481 MIDIHDR mhdr;
482 MMRESULT rval;
483 char GS_Reset[] = { 0xF0, 0x41, 0x10, 0x42, 0x12, 0x40, 0x00, 0x7F, 0x00, 0x41, 0xF7 };
484
485
486 if ((rval = midiOutOpen(&hmidi, MIDI_MAPPER, 0, 0, 0)) != MMSYSERR_NOERROR)
487 {
488 switch (rval)
489 {
490 case MIDIERR_NODEVICE:
491 con_printf(CON_DEBUG, "midiOutOpen Error: no MIDI port was found.");
492 break;
493 case MMSYSERR_ALLOCATED:
494 con_printf(CON_DEBUG, "midiOutOpen Error: specified resource is already allocated.");
495 break;
496 case MMSYSERR_BADDEVICEID:
497 con_printf(CON_DEBUG, "midiOutOpen Error: specified device identifier is out of range.");
498 break;
499 case MMSYSERR_INVALPARAM:
500 con_printf(CON_DEBUG, "midiOutOpen Error: specified pointer or structure is invalid.");
501 break;
502 case MMSYSERR_NOMEM:
503 con_printf(CON_DEBUG, "midiOutOpen Error: unable to allocate or lock memory.");
504 break;
505 default:
506 con_printf(CON_DEBUG, "midiOutOpen Error code %i",rval);
507 break;
508 }
509 return;
510 }
511
512 range_for (const int channel, xrange(16u))
513 {
514 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_ALL_SOUNDS_OFF << 8 | 0 << 16));
515 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_RESET_ALL_CONTROLLERS << 8 | 0 << 16));
516 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_ALL_NOTES_OFF << 8 | 0 << 16));
517
518 channel_volume[channel] = 100;
519 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_PANPOT << 8 | 64 << 16));
520 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_REVERB << 8 | 40 << 16));
521 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_CHORUS << 8 | 0 << 16));
522
523 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_BANK_SELECT_MSB << 8 | 0 << 16));
524 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_BANK_SELECT_LSB << 8 | 0 << 16));
525 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_PROGRAM_CHANGE << 4 | 0 << 8));
526 }
527
528 mhdr.lpData = GS_Reset;
529 mhdr.dwBufferLength = sizeof(GS_Reset);
530 mhdr.dwFlags = 0;
531 if ((rval = midiOutPrepareHeader(hmidi, &mhdr, sizeof(MIDIHDR))) == MMSYSERR_NOERROR)
532 {
533 if ((rval = midiOutLongMsg(hmidi, &mhdr, sizeof(MIDIHDR))) == MMSYSERR_NOERROR)
534 {
535 fix64 wait_done = timer_query();
536 while (!(mhdr.dwFlags & MHDR_DONE))
537 {
538 auto timer = timer_update();
539 if (timer >= wait_done + F1_0)
540 {
541 con_printf(CON_DEBUG, "hmp_reset: Timeout waiting for MHDR_DONE");
542 break;
543 }
544 }
545 }
546 else
547 {
548 switch (rval)
549 {
550 case MIDIERR_NOTREADY:
551 con_printf(CON_DEBUG, "midiOutLongMsg Error: the hardware is busy with other data.");
552 break;
553 case MIDIERR_UNPREPARED:
554 con_printf(CON_DEBUG, "midiOutLongMsg Error: the buffer pointed to by lpMidiOutHdr has not been prepared.");
555 break;
556 case MMSYSERR_INVALHANDLE:
557 con_printf(CON_DEBUG, "midiOutLongMsg Error: the specified device handle is invalid.");
558 break;
559 case MMSYSERR_INVALPARAM:
560 con_printf(CON_DEBUG, "midiOutLongMsg Error: the specified pointer or structure is invalid.");
561 break;
562 default:
563 con_printf(CON_DEBUG, "midiOutLongMsg Error code %i",rval);
564 break;
565 }
566 }
567 midiOutUnprepareHeader(hmidi, &mhdr, sizeof(MIDIHDR));
568
569 timer_delay(F1_0/20);
570 }
571 else
572 {
573 switch (rval)
574 {
575 case MMSYSERR_INVALHANDLE:
576 con_printf(CON_DEBUG, "midiOutPrepareHeader Error: The specified device handle is invalid.");
577 break;
578 case MMSYSERR_INVALPARAM:
579 con_printf(CON_DEBUG, "midiOutPrepareHeader Error: The specified address is invalid or the given stream buffer is greater than 64K.");
580 break;
581 case MMSYSERR_NOMEM:
582 con_printf(CON_DEBUG, "midiOutPrepareHeader Error: The system is unable to allocate or lock memory.");
583 break;
584 default:
585 con_printf(CON_DEBUG, "midiOutPrepareHeader Error code %i",rval);
586 break;
587 }
588 }
589
590 range_for (const int channel, xrange(16u))
591 midiOutShortMsg(hmidi, static_cast<DWORD>(channel | MIDI_CONTROL_CHANGE << 4 | MIDI_VOLUME << 8 | (100 * midi_volume / MIDI_VOLUME_SCALE) << 16));
592 midiOutClose(hmidi);
593 }
594 #endif
595
596 namespace {
597
598 // CONVERSION FROM HMP TO MIDI
599
600 static void hmptrk2mid(ubyte* data, int size, std::vector<uint8_t> &midbuf)
601 {
602 uint8_t *dptr = data;
603 ubyte lc1{0},last_com = 0;
604 int n1;
605
606 while (data < dptr + size)
607 {
608 if (data[0] & 0x80) {
609 ubyte b = (data[0] & 0x7F);
610 midbuf.emplace_back(b);
611 }
612 else {
613 n1 = 1;
614 while ((data[n1] & 0x80) == 0) {
615 n1++;
616 if (n1 == 4)
617 throw std::runtime_error("bad HMP");
618 }
619 for(int n2 = 0; n2 <= n1; n2++) {
620 ubyte b = (data[n1 - n2] & 0x7F);
621
622 if (n2 != n1)
623 b |= 0x80;
624 midbuf.emplace_back(b);
625 }
626 data += n1;
627 }
628 data++;
629 if (*data == 0xFF) { //meta?
630 midbuf.insert(midbuf.end(), data, data + 3 + data[2]);
631 if (data[1] == 0x2F)
632 break;
633 }
634 else {
635 lc1=data[0] ;
636 if ((lc1&0x80) == 0)
637 throw std::runtime_error("bad HMP");
638 switch (lc1 & 0xF0) {
639 case 0x80:
640 case 0x90:
641 case 0xA0:
642 case 0xB0:
643 case 0xE0:
644 if (lc1 != last_com)
645 {
646 midbuf.emplace_back(lc1);
647 }
648 midbuf.insert(midbuf.end(), data + 1, data + 3);
649 data += 3;
650 break;
651 case 0xC0:
652 case 0xD0:
653 if (lc1 != last_com)
654 {
655 midbuf.emplace_back(lc1);
656 }
657 midbuf.emplace_back(data[1]);
658 data += 2;
659 break;
660 default:
661 throw std::runtime_error("bad HMP");
662 }
663 last_com = lc1;
664 }
665 }
666 }
667
668 const std::array<uint8_t, 10> magic_header{{
669 'M', 'T', 'h', 'd',
670 0, 0, 0, 6,
671 0, 1,
672 }};
673 const std::array<uint8_t, 19> tempo{{'M','T','r','k',0,0,0,11,0,0xFF,0x51,0x03,0x18,0x80,0x00,0,0xFF,0x2F,0}};
674 const std::array<uint8_t, 8> track_header{{'M', 'T', 'r', 'k', 0, 0, 0, 0}};
675
676 struct midhdr
677 {
678 int16_t num_trks;
679 int16_t time_div;
680 midhdr(hmp_file *hmp) :
681 num_trks(hmp->num_trks), time_div(hmp->tempo*1.6)
682 {
683 }
684 };
685
686 DEFINE_SERIAL_CONST_UDT_TO_MESSAGE(midhdr, m, (magic_header, m.num_trks, m.time_div, tempo));
687
688 }
689
690 hmpmid_result hmp2mid(const char *hmp_name)
691 {
692 auto &&[hmp, hoe, pec] = hmp_open(hmp_name);
693 if (!hmp)
694 {
695 if (underlying_value(hoe) <= static_cast<unsigned>(hmp_open_error::physfs_read_track_data))
696 con_printf(CON_CRITICAL, "Failed to read HMP music %s: hmp_open_error=%u; PHYSFS_ErrorCode=%u/%s", hmp_name, underlying_value(hoe), pec, PHYSFS_getErrorByCode(pec));
697 else
698 con_printf(CON_CRITICAL, "Failed to read HMP music %s: hmp_open_error=%u", hmp_name, underlying_value(hoe));
699 return {std::vector<uint8_t>{}, hoe};
700 }
701
702 const midhdr mh(hmp.get());
703 std::vector<uint8_t> midbuf;
704 // write MIDI-header
705 midbuf.resize(serial::message_type<decltype(mh)>::maximum_size);
706 serial::writer::be_bytebuffer bb{midbuf.data()};
707 serial::process_buffer(bb, mh);
708
709 // tracks
710 for (int i = 1; i < hmp->num_trks; i++)
711 {
712 midbuf.insert(midbuf.end(), track_header.begin(), track_header.end());
713 auto size_before = midbuf.size();
714 auto midtrklenpos = midbuf.size() - 4;
715 hmptrk2mid(hmp->trks[i].data.get(), hmp->trks[i].len, midbuf);
716 auto size_after = midbuf.size();
717 serial::writer::be_bytebuffer bbmi{&midbuf[midtrklenpos]};
718 serial::process_buffer(bbmi, static_cast<int32_t>(size_after - size_before));
719 }
720 return {midbuf, hmp_open_error::None};
721 }
722
723 }