-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDOSMID.C
1512 lines (1382 loc) · 52.4 KB
/
DOSMID.C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DOSMID - a low-requirement MIDI and MUS player for DOS
*
* Copyright (C) 2014-2018, Mateusz Viste
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <dos.h> /* REGS */
#include <stdio.h> /* printf() */
#include <limits.h> /* ULONG_MAX */
#include <stdlib.h> /* rand() */
#include <string.h> /* memset(), strcpy(), strncat(), memcpy() */
#include "bitfield.h"
#include "fio.h"
#include "gus.h"
#include "mem.h"
#include "midi.h"
#include "mus.h"
#include "outdev.h"
#include "rs232.h"
#include "syx.h"
#include "timer.h"
#include "ui.h"
#include "version.h"
#define MAXTRACKS 64
#define EVENTSCACHESIZE 64 /* *must* be a power of 2 !!! */
#define EVENTSCACHEMASK 63 /* used by the circular events buffer */
/* define a work buffer that will be used instead of malloc() calls whenever a temporary buffer is required */
unsigned char wbuff[8192];
enum playactions {
ACTION_NONE = 0,
ACTION_NEXT = 1,
ACTION_PREV = 2,
ACTION_ERR_SOFT = 3,
ACTION_ERR_HARD = 4,
ACTION_EXIT = 64
};
struct clioptions {
int memmode; /* type of memory to use: MEM_XMS or MEM_MALLOC */
unsigned short devport;
unsigned short port_mpu;
unsigned short port_awe;
unsigned short port_opl;
unsigned short port_sb;
enum outdev_types device;
int devicesubtype;
char *devname; /* the human name of the out device (MPU, AWE..) */
char *midifile; /* MIDI filename to play */
char *syxrst; /* syx file to use for MIDI resets */
int delay; /* additional delay to apply before playing a file */
char *playlist; /* the playlist to read files from */
char *sbnk; /* optional sound bank to use (IBK file or so) */
#ifdef DBGFILE
FILE *logfd; /* an open file descriptor to the debug log file */
#endif
/* 'flags' */
unsigned char xmsdelay;
unsigned char nopowersave;
unsigned char dontstop;
unsigned char random; /* randomize playlist order */
};
/* fetch directory where the program resides, and return its length. result
* string is never longer than 128 (incl. the null terminator), and it is
* always terminated with a backslash separator, unless it is an empty string */
static int exepath(char *result) {
char far *psp, far *env;
unsigned int envseg, pspseg, x, i;
int lastsep;
union REGS regs;
/* get the PSP segment */
regs.h.ah = 0x62;
int86(0x21, ®s, ®s),
pspseg = regs.x.bx;
/* compute a far pointer that points to the top of PSP */
psp = MK_FP(pspseg, 0);
/* fetch the segment address of the environment */
envseg = psp[0x2D];
envseg <<= 8;
envseg |= psp[0x2C];
/* compute the env pointer */
env = MK_FP(envseg, 0);
/* skip all environment variables */
x = 0;
for (;;) {
x++;
if (env[x] == 0) { /* end of variable */
x++;
if (env[x] == 0) break; /* end of list */
}
}
x++;
/* read the WORD that indicates string that follow */
if (env[x] < 1) {
result[0] = 0;
return(0);
}
x += 2;
/* else copy the EXEPATH to our return variable, and truncate after last '\' */
lastsep = -1;
for (i = 0;; i++) {
result[i] = env[x++];
if (result[i] == '\\') lastsep = i;
if (result[i] == 0) break; /* end of string */
if (i >= 126) break; /* this DOS string should never go beyond 127 chars! */
}
result[lastsep + 1] = 0;
return(lastsep + 1);
}
static void dos_puts(char *s) {
/* DOS 1+ - WRITE STRING TO STANDARD OUTPUT
AH = 09h
DS:DX -> '$'-terminated string */
unsigned short segm, offs;
segm = FP_SEG(s);
offs = FP_OFF(s);
__asm {
mov ah, 9
push ds
mov cx, segm
push cx
pop ds
mov dx, offs
int 21h
pop ds /* restore DS */
/* print out a CR/LF using INT21h AH=2 */
mov ah, 2
mov dl, 0dh
int 21h
mov ah, 2
mov dl, 0ah
int 21h
}
}
/* returns a pseudo-random number, based on the DOS system timer */
static unsigned long rnd(void) {
unsigned long res;
union REGS regs;
regs.h.ah = 0;
int86(0x1A, ®s, ®s);
res = regs.x.cx; /* number of clock ticks since midnight (high word) */
res <<= 16;
res |= regs.x.dx; /* number of clock ticks since midnight (low word) */
return(res);
}
/* copies the base name of a file (ie without directory path) into a string */
static void filename2basename(char *fromname, char *tobasename, char *todirname, int maxlen) {
int x, x2, firstchar = 0;
/* find the first character of the base name */
for (x = 0; fromname[x] != 0; x++) {
switch (fromname[x]) {
case '/':
case '\\':
case ':':
firstchar = x + 1;
break;
}
}
/* copy basename to tobasename */
if (tobasename != NULL) {
x2 = 0;
for (x = firstchar; fromname[x] != 0; x++) {
if ((fromname[x] == 0) || (x2+1 >= maxlen)) break;
tobasename[x2++] = fromname[x];
}
tobasename[x2] = 0;
}
/* copy dirname to todirname */
if (todirname != NULL) {
x2 = 0;
for (x = 0; x < firstchar; x++) {
if ((fromname[x] == 0) || (x2+1 >= maxlen)) break;
todirname[x2++] = fromname[x];
}
todirname[x2] = 0;
}
}
/* switch a string to upper case */
static void ucasestr(char *s) {
for (; *s != 0; s++) if ((*s >= 'a') && (*s <= 'z')) *s -= 32;
}
/* returns the lower-case version of c char, if applicable */
static int lcase(char c) {
if ((c >= 'A') && (c <= 'Z')) return(c + 32);
return(c);
}
/* a case-insensitive version of strcmp() */
static int strucmp(char *s1, char *s2) {
for (;;) {
if (lcase(*s1) != lcase(*s2)) return(1);
if (*s1 == 0) return(0);
s1++;
s2++;
}
}
/* checks whether str starts with start or not. returns 0 if so, non-zero
* otherwise - this function is case insensitive */
static int stringstartswith(char *str, char *start) {
if ((str == NULL) || (start == NULL)) return(-1);
while (*start != 0) {
if (lcase(*start) != lcase(*str)) return(-1);
str++;
start++;
}
return(0);
}
static int hexchar2int(char c) {
if ((c >= '0') && (c <= '9')) return(c - '0');
if ((c >= 'a') && (c <= 'f')) return(10 + c - 'a');
if ((c >= 'A') && (c <= 'F')) return(10 + c - 'A');
return(-1);
}
/* converts a hex string to unsigned int. stops at first null terminator or
* space. returns zero on error. */
static unsigned int hexstr2uint(char *hexstr) {
unsigned int v = 0;
while ((*hexstr != 0) && (*hexstr != ' ')) {
int c;
c = hexchar2int(*hexstr);
if (c < 0) return(0);
v <<= 4;
v |= c;
hexstr++;
}
return(v);
}
static char *devtoname(enum outdev_types device, int devicesubtype) {
switch (device) {
case DEV_NONE: return("NONE");
case DEV_MPU401: return("MPU");
case DEV_AWE: return("AWE");
case DEV_OPL: return("OPL");
case DEV_OPL2: return("OPL2");
case DEV_OPL3: return("OPL3");
case DEV_RS232:
if (devicesubtype == 1) return("COM1");
if (devicesubtype == 2) return("COM2");
if (devicesubtype == 3) return("COM3");
if (devicesubtype == 4) return("COM4");
return("COM");
case DEV_SBMIDI: return("SB");
case DEV_GUS: return("GUS");
case DEV_CMS: return("CMS");
default: return("UNK");
}
}
/* analyzes a 16 bytes file header and guess the file format */
static enum fileformats header2fileformat(unsigned char *hdr) {
/* Classic MIDI */
if ((hdr[0] == 'M') && (hdr[1] == 'T') && (hdr[2] == 'h') && (hdr[3] == 'd')) {
return(FORMAT_MIDI);
}
/* RMID inside a RIFF container */
if ((hdr[0] == 'R') && (hdr[1] == 'I') && (hdr[2] == 'F') && (hdr[3] == 'F')
&& (hdr[8] == 'R') && (hdr[9] == 'M') && (hdr[10] == 'I') && (hdr[11] == 'D')) {
return(FORMAT_RMID);
}
/* MUS (as used in Doom, from Id Software) */
if ((hdr[0] == 'M') && (hdr[1] == 'U') && (hdr[2] == 'S') && (hdr[3] == 0x1A)) {
return(FORMAT_MUS);
}
/* else I don't know */
return(FORMAT_UNKNOWN);
}
/* loads the file's extension into ext (limited to limit characters) */
static void getfileext(char *ext, char *filename, int limit) {
int x;
char *extptr = NULL;
ext[0] = 0;
/* find the last dot first */
while (*filename != 0) {
if (*filename == '.') {
extptr = filename + 1;
}
filename++;
}
if (extptr == NULL) return;
/* copy the extension to ext, up to limit bytes */
limit--; /* make room for the null char */
for (x = 0; extptr[x] != 0; x++) {
if (x >= limit) break;
/* make sure the extension is all-lowercase */
if ((extptr[x] >= 'A') && (extptr[x] <= 'Z')) {
ext[x] = extptr[x] + 32;
} else {
ext[x] = extptr[x];
}
}
ext[x] = 0; /* terminate the ext string */
}
/* interpret a single config argument, returns NULL on succes, or a pointer to
* an error string otherwise */
static char *feedarg(char *arg, struct clioptions *params, int fileallowed) {
if (strucmp(arg, "/noxms") == 0) {
params->memmode = MEM_MALLOC;
} else if (strucmp(arg, "/xmsdelay") == 0) {
params->xmsdelay = 1;
} else if (strucmp(arg, "/fullcpu") == 0) {
params->nopowersave = 1;
} else if (strucmp(arg, "/dontstop") == 0) {
params->dontstop = 1;
} else if (strucmp(arg, "/random") == 0) {
params->random = 1;
} else if (strucmp(arg, "/nosound") == 0) {
params->device = DEV_NONE;
params->devport = 0;
#ifdef SBAWE
} else if (strucmp(arg, "/awe") == 0) {
params->device = DEV_AWE;
params->devport = params->port_awe;
/* if AWE port not found in BLASTER, use the default 0x620 */
if (params->devport == 0) params->devport = 0x620;
} else if (stringstartswith(arg, "/awe=") == 0) {
params->device = DEV_AWE;
params->devport = hexstr2uint(arg + 5);
if (params->devport < 1) return("Invalid AWE port provided. Example: /awe=620$");
#endif
} else if (strucmp(arg, "/mpu") == 0) {
params->device = DEV_MPU401;
params->devport = params->port_mpu;
/* if MPU port not found in BLASTER, use the default 0x330 */
if (params->devport == 0) params->devport = 0x330;
} else if (strucmp(arg, "/gus") == 0) {
params->device = DEV_GUS;
params->devport = gus_find();
if (params->devport < 1) return("GUS error: No ULTRAMID driver found$");
#ifdef OPL
} else if (strucmp(arg, "/opl") == 0) {
params->device = DEV_OPL;
params->devport = 0x388;
} else if (stringstartswith(arg, "/opl=") == 0) {
params->device = DEV_OPL;
params->devport = hexstr2uint(arg + 5);
if (params->devport < 1) return("Invalid OPL port provided. Example: /opl=388$");
#endif
#ifdef CMS
} else if (strucmp(arg, "/cms") == 0) {
params->device = DEV_CMS;
params->devport = 0x220;
} else if (stringstartswith(arg, "/cms=") == 0) {
params->device = DEV_CMS;
params->devport = hexstr2uint(arg + 5);
if (params->devport < 1) return("Invalid CMS port provided. Example: /cms=220$");
#endif
} else if (stringstartswith(arg, "/sbnk=") == 0) {
if (params->sbnk != NULL) free(params->sbnk); /* drop last sbnk if already present, so a CLI sbnk would take precedence over a config-file sbnk */
params->sbnk = strdup(arg + 6);
} else if (stringstartswith(arg, "/mpu=") == 0) {
params->device = DEV_MPU401;
params->devport = hexstr2uint(arg + 5);
if (params->devport < 1) return("Invalid MPU port provided. Example: /mpu=330$");
} else if (stringstartswith(arg, "/com=") == 0) {
params->device = DEV_RS232;
params->devport = hexstr2uint(arg + 5);
if (params->devport < 10) return("Invalid COM port provided. Example: /com=3f8$");
} else if (stringstartswith(arg, "/com") == 0) { /* must be compared AFTER "/com=" */
params->device = DEV_RS232;
params->devicesubtype = arg[4] - '0';
if ((params->devicesubtype < 1) || (params->devicesubtype > 4)) return("Invalid COM port provided. Example: /com1$");
params->devport = rs232_getport(params->devicesubtype);
if (params->devport < 1) return("Failed to autodetect the I/O address of this COM port. Try using the /com=XXX option.$");
} else if (strucmp(arg, "/sbmidi") == 0) {
params->device = DEV_SBMIDI;
params->devport = params->port_sb;
/* if SB port not found in BLASTER, use the default 0x220 */
if (params->devport == 0) params->devport = 0x220;
} else if (stringstartswith(arg, "/sbmidi=") == 0) {
params->device = DEV_SBMIDI;
params->devport = hexstr2uint(arg + 8);
if (params->devport < 1) return("Invalid SBMIDI port provided. Example: /sbmidi=220$");
#ifdef DBGFILE
} else if (stringstartswith(arg, "/log=") == 0) {
if (params->logfd == NULL) {
params->logfd = fopen(arg + 5, "wb");
if (params->logfd == NULL) {
return("Failed to open the debug log file.$");
}
}
#endif
} else if (stringstartswith(arg, "/syx=") == 0) {
params->syxrst = strdup(arg + 5);
} else if (stringstartswith(arg, "/delay=") == 0) {
params->delay = atoi(arg + 7);
if ((params->delay < 1) || (params->delay > 9000)) {
return("Invalid delay value: must be in the range 1..9000$");
}
} else if ((strucmp(arg, "/?") == 0) || (strucmp(arg, "/h") == 0) || (strucmp(arg, "/help") == 0)) {
return("");
} else if ((fileallowed != 0) && (arg[0] != '/') && (params->midifile == NULL) && (params->playlist == NULL)) {
char ext[4];
getfileext(ext, arg, 4);
if (strucmp(ext, "m3u") == 0) {
params->playlist = arg;
} else {
params->midifile = arg;
}
} else {
return("Unknown option.$");
}
return(NULL);
}
/* trims any white-space and line feeds occuring at the right of the string */
static void rtrim(char *s) {
char *lastchar = s;
while (*s != 0) {
switch (*s) {
case ' ':
case '\t':
case '\r':
case '\n':
s++;
break;
default:
lastchar = ++s;
}
}
*lastchar = 0;
}
static char *loadconfigfile(struct clioptions *params) {
char buff[128 + 12]; /* 128 for exepath plus 8+3 for the config file */
int r;
char *res = NULL;
struct fiofile_t f;
/* prepare config file's full path */
r = exepath(buff);
if (r < 1) return(NULL);
/* append the config file itself */
sprintf(buff + r, "dosmid.cfg");
/* open file */
if (fio_open(buff, FIO_OPEN_RD, &f) != 0) return(NULL);
for (;;) {
/* read line & trim */
r = fio_getline(&f, buff, sizeof(buff));
if (r < 0) break; /* stop on EOF */
if (*buff == '#') continue; /* skip comments */
rtrim(buff);
if (*buff == 0) continue; /* skip empty lines */
/* push arg to feedarg() (files not allowed because filename not allocated in persistent memory) */
res = feedarg(buff, params, 0);
if (res != NULL) break;
}
/* close file */
fio_close(&f);
return(res);
}
/* parse command line params and fills the params struct accordingly. returns
NULL on sucess, or a pointer to an error string otherwise. */
static char *parseargv(int argc, char **argv, struct clioptions *params) {
int i;
/* if no params at all, don't waste time */
if (argc == 0) return("");
/* now read params */
for (i = 1; i < argc; i++) {
char *r;
r = feedarg(argv[i], params, 1);
if (r != NULL) return(r);
}
/* check if at least a MIDI filename have been provided */
if ((params->midifile == NULL) && (params->playlist == NULL)) {
return("You have to provide the path to a MIDI file or a playlist to play.$");
}
/* all good */
return(NULL);
}
/* computes the time elapsed since the song started (in secs). Returns 0 if
* elapsed time didn't changed since last time, non-zero otherwise */
static int compute_elapsed_time(unsigned long starttime, unsigned long *elapsed) {
unsigned long curtime, res;
timer_read(&curtime);
if (curtime < starttime) { /* wraparound detected */
res = (ULONG_MAX - starttime) + curtime;
} else {
res = curtime - starttime;
}
res /= 1000000lu; /* microseconds to seconds */
if (res == *elapsed) return(0);
*elapsed = res;
return(1);
}
/* check the event cache for a given event. to reset the cache, issue a single
* call with trackpos < 0. */
static struct midi_event_t *getnexteventfromcache(struct midi_event_t *eventscache, long trackpos, int xmsdelay) {
static unsigned int itemsincache = 0;
static unsigned int curcachepos = 0;
struct midi_event_t *res = NULL;
long nextevent;
/* if trackpos < 0 then this is only about flushing cache */
if (trackpos < 0) {
memset(eventscache, 0, sizeof(*eventscache));
itemsincache = 0;
curcachepos = 0;
return(NULL);
}
/* if we have available cache */
if (itemsincache > 0) {
curcachepos++;
curcachepos &= EVENTSCACHEMASK;
itemsincache--;
res = &eventscache[curcachepos];
/* if we have some free time, refill the cache proactively */
if (res->deltatime > 0) {
int nextslot, pullres;
/* sleep 2ms after a MIDI OUT write, and before accessing XMS.
This is especially important for SoundBlaster "AWE" cards with the
AWEUTIL TSR midi emulation enabled, without this AWEUTIL crashes. */
if (xmsdelay != 0) udelay(2000);
nextslot = curcachepos + itemsincache;
nextevent = eventscache[nextslot & EVENTSCACHEMASK].next;
while ((itemsincache < EVENTSCACHESIZE - 1) && (nextevent >= 0)) {
nextslot++;
nextslot &= EVENTSCACHEMASK;
pullres = mem_pull(nextevent, &eventscache[nextslot], sizeof(struct midi_event_t));
if (pullres != 0) {
/* printf("pullevent() ERROR: %u (eventid = %ld)\n", pullres, trackpos); */
return(NULL);
}
nextevent = eventscache[nextslot].next;
itemsincache++;
}
}
} else { /* need to refill the cache NOW */
int refillcount, pullres;
/* sleep 2ms after a MIDI OUT write, and before accessing XMS.
this is especially important for SoundBlaster "AWE" cards with the
AWEUTIL TSR midi emulation enabled, without this AWEUTIL crashes. */
if (xmsdelay != 0) udelay(2000);
nextevent = trackpos;
curcachepos = 0;
for (refillcount = 0; refillcount < EVENTSCACHESIZE; refillcount++) {
pullres = mem_pull(nextevent, &eventscache[refillcount], sizeof(struct midi_event_t));
if (pullres != 0) {
/* printf("pullevent() ERROR: %u (eventid = %ld)\n", pullres, trackpos); */
return(NULL);
}
nextevent = eventscache[refillcount].next;
itemsincache++;
if (nextevent < 0) break;
}
itemsincache--;
res = eventscache;
}
return(res);
}
/* reads the BLASTER variable for best guessing of current hardware and port.
* If nothing found, fallbacks to MPU and 0x330 */
static void preload_outdev(struct clioptions *params) {
char *blaster;
params->port_mpu = 0;
params->port_awe = 0;
params->port_opl = 0;
params->port_sb = 0;
/* check if a blaster variable is present */
blaster = getenv("BLASTER");
/* if so, read it looking for 'P' and 'E' parameters */
if (blaster != NULL) {
char *blasterptr[16];
int blastercount = 0;
/* read the variable in a first pass to collect all starting points */
if (*blaster != 0) {
blasterptr[blastercount++] = blaster++;
}
for (;;) {
if (*blaster == ' ') {
blasterptr[blastercount++] = ++blaster;
} else if ((*blaster == 0) || (blastercount >= 16)) {
break;
} else {
blaster++;
}
}
while (blastercount-- > 0) {
unsigned short p;
unsigned short *portptr;
blaster = blasterptr[blastercount];
/* have we found an interesting param? */
if ((*blaster != 'P') && (*blaster != 'E') && (*blaster != 'A')) continue;
if (*blaster == 'E') {
portptr = &(params->port_awe);
} else if (*blaster == 'P') {
portptr = &(params->port_mpu);
} else {
portptr = &(params->port_sb);
}
/* read the param value into a variable */
p = hexstr2uint(blaster + 1);
/* if what we have read looks sane, keep it */
if (p > 0) *portptr = p;
}
}
/* look at what we got, and choose in order of preference */
/* set NONE, just so we have anything set */
params->device = DEV_NONE;
params->devport = 0;
/* use OPL on port 0x388, if OPL output is compiled in */
#ifdef OPL
params->device = DEV_OPL;
params->devport = 0x388;
#endif
/* never try using SBMIDI: it's unlikely anything's connected to it anyway */
/* is there an MPU? if so, take it */
if (params->port_mpu > 0) {
params->device = DEV_MPU401;
params->devport = params->port_mpu;
}
/* if a GUS seems to be installed, let's try it */
if (getenv("ULTRADIR") != 0) {
int gusp = gus_find();
if (gusp > 0) {
params->device = DEV_GUS;
params->devport = gusp;
}
}
/* AWE is the most desirable, if present (and compiled in) */
#ifdef SBAWE
if (params->port_awe > 0) { /* AWE is the most desirable, if present */
params->device = DEV_AWE;
params->devport = params->port_awe;
}
#endif
}
enum direction_t {
DIR_FWD,
DIR_REV,
DIR_RND
};
/* reads a position from an M3U file and returns a ptr from static mem */
static char *getnextm3uitem(char *playlist, enum direction_t dir) {
static char fnamebuf[256];
char tempstr[256];
long fsize;
static long pos = 0;
int slen;
struct fiofile_t f;
/* open the playlist and read its size */
if (fio_open(playlist, FIO_OPEN_RD, &f) != 0) return(NULL);
fsize = fio_seek(&f, FIO_SEEK_END, 0);
if (fsize < 3) { /* a one-entry m3u would be at least 3 bytes long */
fio_close(&f);
return(NULL);
}
if (dir == DIR_RND) {
/* go to a random position (avoid last bytes, could be an empty \r\n record) */
pos = (rnd() << 1) % (fsize - 2); /* mul rnd by 2 to speed up 'randomness' at the cost of getting only even offsets */
}
if (dir == DIR_REV) pos -= 3;
GOHEREFORPREV:
if (pos < 0) pos = 0;
fio_seek(&f, FIO_SEEK_START, pos);
/* rewind back to nearest \n or 0 position */
while (pos > 0) {
fio_read(&f, tempstr, 1);
if (tempstr[0] != '\n') {
fio_seek(&f, FIO_SEEK_CUR, -2);
pos--;
} else {
pos++;
break;
}
}
if (dir == DIR_REV) {
pos -= 3;
dir = DIR_FWD;
goto GOHEREFORPREV;
}
/* read the string into fnamebuf */
slen = 0;
fnamebuf[0] = 0;
for (;;) {
char c;
if ((fio_read(&f, &c, 1) != 1) || (c == '\r') || (c == '\n')) break;
pos++;
fnamebuf[slen++] = c;
if (slen == sizeof(fnamebuf)) { /* overflow! */
fnamebuf[0] = 0;
break;
}
fnamebuf[slen] = 0;
}
/* if sequential reading of the playlist, then jump to next entry */
if (dir == DIR_FWD) {
for (;;) {
char c;
if (fio_read(&f, &c, 1) != 1) {
pos = 0;
break;
} else if ((c == '\r') || (c == '\n')) {
pos++;
} else {
break;
}
}
}
/* close the file descriptor */
fio_close(&f);
/* trim any leading spaces, if any */
rtrim(fnamebuf);
/* if empty, something went wrong */
if (fnamebuf[0] == 0) return(NULL);
/* if the file is a relative path, then prepend it with the path of the playlist */
if (fnamebuf[1] != ':') {
strcpy(tempstr, fnamebuf);
filename2basename(playlist, NULL, fnamebuf, sizeof(fnamebuf) - 1);
strncat(fnamebuf, tempstr, sizeof(fnamebuf) - 1);
}
/* return the result */
return(fnamebuf);
}
/* returns a pointer to the next line of s, or NULL if no more lines */
static char *nextlinefrombuf(char *s) {
for (;; s++) {
if (*s == 0) return(NULL);
if (*s == '\n') {
s++;
if (*s == 0) return(NULL);
return(s);
}
}
}
/* copy the first line of s into d, up to l characters (incl. null term.) */
static void copyline(char *d, int l, char *s) {
for (;;) {
*d = *s;
if (*d == 0) return;
if ((*d == '\r') || (*d == '\n') || (--l == 0)) {
*d = 0;
return;
}
d++;
s++;
}
}
static enum playactions loadfile_midi(struct fiofile_t *f, struct clioptions *params, struct trackinfodata *trackinfo, long *trackpos) {
static unsigned long trackmap[MAXTRACKS];
int miditracks;
int i;
long newtrack;
char copystring[UI_TITLEMAXLEN];
char text[256];
*trackpos = -1;
miditracks = midi_readhdr(f, &(trackinfo->midiformat), &(trackinfo->miditimeunitdiv), trackmap, MAXTRACKS);
if (miditracks < 1) {
char errstr[64];
sprintf(errstr, "Error: Invalid MIDI file format (ERR %d)", miditracks);
ui_puterrmsg(params->midifile, errstr);
return(ACTION_ERR_SOFT);
}
trackinfo->trackscount = miditracks;
#ifdef DBGFILE
if (params->logfd != NULL) fprintf(params->logfd, "LOADED FILE '%s': format=%d tracks=%d timeunitdiv=%u\n", params->midifile, trackinfo->midiformat, miditracks, trackinfo->miditimeunitdiv);
#endif
if ((trackinfo->midiformat != 0) && (trackinfo->midiformat != 1)) {
char errstr[64];
sprintf(errstr, "Error: Unsupported MIDI format (%d)", trackinfo->midiformat);
ui_puterrmsg(params->midifile, errstr);
return(ACTION_ERR_SOFT);
}
if (miditracks > MAXTRACKS) {
char errstr[64];
sprintf(errstr, "Error: Too many tracks (%d, max: %d)", miditracks, MAXTRACKS);
ui_puterrmsg(params->midifile, errstr);
return(ACTION_ERR_SOFT);
}
for (i = 0; i < miditracks; i++) {
char tracktitle[UI_TITLEMAXLEN];
unsigned long tracklen;
#ifdef DBGFILE
if (params->logfd != NULL) fprintf(params->logfd, "LOADING TRACK %d FROM OFFSET 0x%04X\n", i, trackmap[i]);
#endif
fio_seek(f, FIO_SEEK_START, trackmap[i]);
if (i == 0) { /* copyright and text events are fetched from track 0 only */
newtrack = midi_track2events(f, tracktitle, UI_TITLEMAXLEN, copystring,
UI_TITLEMAXLEN, text, sizeof(text),
&(trackinfo->channelsusage),
#ifdef DBGFILE
params->logfd,
#endif
&tracklen, trackinfo->reqpatches);
} else {
newtrack = midi_track2events(f, tracktitle, UI_TITLEMAXLEN, NULL, 0,
NULL, 0, &(trackinfo->channelsusage),
#ifdef DBGFILE
params->logfd,
#endif
&tracklen, trackinfo->reqpatches);
}
/* look for error conditions */
if (newtrack == MIDI_OUTOFMEM) {
ui_puterrmsg(params->midifile, "Error: Out of memory");
return(ACTION_ERR_SOFT);
} else if (newtrack == MIDI_TRACKERROR) {
ui_puterrmsg(params->midifile, "Error: Malformed MIDI file");
return(ACTION_ERR_SOFT);
}
/* there is a non-written rule saying that useful text is written into
* titles of empty tracks - push data into next available title node */
if (((tracklen == 0) || (i == 0)) && (trackinfo->titlescount < UI_TITLENODES) && (tracktitle[0] != 0)) {
/* ignore empty titles, though, if no valid title was found before */
rtrim(tracktitle);
if ((trackinfo->titlescount > 0) || (tracktitle[0] != 0)) {
memcpy(trackinfo->title[trackinfo->titlescount++], tracktitle, UI_TITLEMAXLEN);
}
}
/* merge the track now */
if (newtrack >= 0) {
*trackpos = midi_mergetrack(*trackpos, newtrack, &(trackinfo->totlen), trackinfo->miditimeunitdiv);
#ifdef DBGFILE
if (params->logfd != NULL) fprintf(params->logfd, "TRACK %d MERGED (start id=%ld) -> TOTAL TIME: %ld\n", i, *trackpos, trackinfo->totlen);
#endif
}
}
/* if we got any 'text', but no 'titles', then push the text into titles */
if ((text[0] != 0) && (trackinfo->titlescount == 0)) {
char *l;
for (l = text; (l != NULL) && (trackinfo->titlescount < UI_TITLENODES); l = nextlinefrombuf(l)) {
copyline(trackinfo->title[trackinfo->titlescount++], UI_TITLEMAXLEN, l);
}
}
/* if we have room in title nodes, copy the copyright string there */
if ((trackinfo->titlescount < UI_TITLENODES) && (copystring[0] != 0)) {
memcpy(trackinfo->title[trackinfo->titlescount++], copystring, UI_TITLEMAXLEN);
}
return(ACTION_NONE);
}
static enum playactions loadfile(struct clioptions *params, struct trackinfodata *trackinfo, long *trackpos) {
struct fiofile_t f;
unsigned char hdr[16];
enum playactions res;
/* (try to) open the music file */
if (fio_open(params->midifile, FIO_OPEN_RD, &f) != 0) {
ui_puterrmsg(params->midifile, "Error: Failed to open the file");
return(ACTION_ERR_SOFT);
}
/* read first few bytes of the file to detect its format, and rewind */
if (fio_read(&f, hdr, 16) != 16) {
fio_close(&f);
ui_puterrmsg(params->midifile, "Error: Unknown file format");
return(ACTION_ERR_SOFT);
}
fio_seek(&f, FIO_SEEK_START, 0);
/* analyze the header to guess the format of the file */
trackinfo->fileformat = header2fileformat(hdr);
/* load file if format recognized */
switch (trackinfo->fileformat) {
case FORMAT_MIDI:
case FORMAT_RMID:
res = loadfile_midi(&f, params, trackinfo, trackpos);
break;
case FORMAT_MUS:
*trackpos = mus_load(&f, &(trackinfo->totlen), &(trackinfo->miditimeunitdiv), &(trackinfo->channelsusage), trackinfo->reqpatches);
if (*trackpos == MUS_OUTOFMEM) { /* detect out of memory */
res = ACTION_ERR_SOFT;
ui_puterrmsg(params->midifile, "Error: Out of memory");
} else if (*trackpos < 0) { /* detect any other problems */
char msg[64];
res = ACTION_ERR_SOFT;
snprintf(msg, 64, "Error: Failed to load the MUS file (%ld)", *trackpos);
ui_puterrmsg(params->midifile, msg);
} else { /* all right, now we're talking */
trackinfo->trackscount = 1;
res = ACTION_NONE;
}
break;
default:
res = ACTION_ERR_SOFT;
ui_puterrmsg(params->midifile, "Error: Unknown file format");
break;
}
fio_close(&f);
/* if no text data could be found at all, add a note about that */
if ((res == ACTION_NONE) && (trackinfo->titlescount == 0)) {
strcpy(trackinfo->title[trackinfo->titlescount++], "<no title>");
}
return(res);
}
static void pauseplay(unsigned long *starttime, unsigned long *nexteventtime, struct trackinfodata *trackinfo) {
unsigned long beforepause, afterpause, deltaremainder;
int i;
/* save timing information */
timer_read(&beforepause);
deltaremainder = *nexteventtime - beforepause;
/* print a pause message on screen */
ui_puterrmsg("PAUSE", "[ Press any key ]");
/* turn off all notes before pausing */
for (i = 0; i < 128; i++) {
if (trackinfo->notestates[i] != 0) {
int c;
for (c = 0; c < 16; c++) {
if (trackinfo->notestates[i] & (1 << c)) {
/* printf("note #%d is still playing on channel %d\n", i, c); */
dev_noteoff(c, i);
}
}
}
}
/* wait for a key press */
getkey();
/* restore play timing */