-
Notifications
You must be signed in to change notification settings - Fork 1
/
ethermidi.c
1993 lines (1567 loc) · 48.8 KB
/
ethermidi.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
//////////////////////////////////////////////////////////////////////////////
// //
// _ _ _ _ _ //
// ___ | |_ | |__ ___ _ __ _ __ ___ (_) __| |(_) ___ //
// / _ \| __|| '_ \ / _ \| '__|| '_ ` _ \ | | / _` || | / __| //
// | __/| |_ | | | || __/| | | | | | | || || (_| || | _| (__ //
// \___| \__||_| |_| \___||_| |_| |_| |_||_| \__,_||_|(_)\___| //
// //
// //
//////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2018 by S.F.T. Inc. - All rights reserved //
// Use, copying, and distribution of this software are licensed according //
// to the GPLv2, LGPLv2, or BSD license, as appropriate (see COPYING) //
// //
//////////////////////////////////////////////////////////////////////////////
// This program uses libfluidsynth to generate MIDI output based on UDP packets
// received on a listening interface (default 0.0.0.0 on port 9000).
//
// The MIDI packets are in a format as generated by the 'EthernetMIDI' application,
// written by Benno Senoner - http://linuxsampler.org/ethernetmidi/
//
// The intent is to allow a Linux or BSD computer to act as a soundfont synth
// without additional MIDI cables, from a windows computer using an application
// like 'Cakewalk' that requires Windows.
//
// To make this work, you have to be able to run the 'EthernetMIDI' application
// on the windows computer, using a 'midi loopback' device (similar to LoopBE;
// for more information on LoopBE see http://www.nerds.de/en/loopbe30.html )
//
// Other windows midi loopback driver software also exists.
//
// Additional links: http://www.copperlan.org/index.php/download
// https://www.tobias-erichsen.de/software/loopmidi.html
// http://www.midiox.com/myoke.htm
//
// Then, the MIDI application (let's say cakewalk) will be configured to use
// the MIDI loopback device, which will then cause 'EthernetMIDI' to send UDP
// packets to a Linux or FreeBSD machine running this program. Then, the
// 'EtherMIDI' application (this one) invokes fluidsynth to play the MIDI content.
// Alternately, this program sets up an instance of 'fluidsynth', either listening
// on a character device that was created by 'cuse4bsd', or a FIFO, for incoming
// MIDI traffic via UDP on a specified port. See pre-defined constants, below
#define USE_LIBFLUIDSYNTH /* do the deed using libfluidsynth - best method */
//#define USE_CUSE /* use CUSE to create a device driver for fluidsynth to listen on in lieu of a FIFO */
//#define USE_LIBFLUIDSYNTH_PARSER /* use the undocumented 'parser' for libfluidsynth */
#define DEFAULT_FREEBSD_OUT_DEVICE "oss"
#define DEFAULT_LINUX_OUT_DEVICE "pulseaudio"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <memory.h>
#include <signal.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/soundcard.h> // use this to get soundcard IOCTL definitions
// need to include 'cuse4bsd' header - compile with -lcuse4bsd -lthr and -I /usr/local/include -L /usr/local/lib
#ifdef USE_CUSE
#ifndef __FreeBSD__
#error this only works for FreeBSD
#endif // __FreeBSD__
#include <cuse4bsd.h> // in /usr/local/include
#endif // USE_CUSE
#ifdef USE_LIBFLUIDSYNTH
#include <fluidsynth.h>
#ifdef USE_LIBFLUIDSYNTH_PARSER
#ifndef _FLUID_MIDI_H /* these definitions are actually in a private file that builds the lib */
// TODO: this only works if /usr/local/lib/libfluidsynth.so has the exports for these 3 functions
// maybe have autoconf use objdump -T and look for them?
struct _fluid_midi_parser_t
{
void *pDummy;
};
typedef struct _fluid_midi_parser_t fluid_midi_parser_t;
fluid_midi_parser_t* new_fluid_midi_parser(void);
int delete_fluid_midi_parser(fluid_midi_parser_t* parser);
fluid_midi_event_t* fluid_midi_parser_parse(fluid_midi_parser_t* parser, unsigned char c);
#endif // _FLUID_MIDI_H
#else // USE_LIBFLUIDSYNTH_PARSER
void do_midi_command(unsigned int nBytes, unsigned char *pData, fluid_synth_t *pS);
#endif // USE_LIBFLUIDSYNTH_PARSER
#endif // USE_LIBFLUIDSYNTH
void hup_handler(int iSig); // call 'signal(SIGHUP, hup_handler)' to enable it
// also might handle SIGQUIT, SIGKILL, SIGTERM
int do_main(int iListen, const char *szSoundFont);
unsigned int MyGetTickCount();
void MySleep(unsigned int dwMsec);
int TimeIntervalExceeds(unsigned int dwStart, unsigned int dwMSec);
typedef struct __my_buf__
{
int cbBuf;
int nHead, nTail;
unsigned char buffer[4];
} MY_BUF;
#define MY_BUF_SIZE 65536
typedef void *(the_thread_proc)(void *pArg);
pthread_t MyCreateThread(the_thread_proc *pProc, void *pParam);
int my_buf_len(const MY_BUF *pBuf);
int my_buf_remaining(const MY_BUF *pBuf);
void my_buf_write(MY_BUF *pBuf, const char *pData, int cbLen);
int my_buf_read(MY_BUF *pBuf, char *pData, int cbLen);
// these borrowed from X11workbench, 'platform_helper.c'
#define WB_INVALID_FILE_HANDLE -1
#define WB_PROCESS_ID pid_t
#define WB_FILE_HANDLE int
WB_PROCESS_ID WBRunAsync(const char *szAppName, ...);
void usage(void)
{
fputs("Usage: ethermidi [-d][-Fwavetable.sf2][-o output][-V vol] [[ip][:port]]\n"
"where '-F' specifies a wavetable that immediately follows '-F'\n"
" and '-d' runs the application as a daemon\n"
" and '-o' specifies the output device [default is "
#ifdef __FreeBSD__
DEFAULT_FREEBSD_OUT_DEVICE
#else // linux
DEFAULT_LINUX_OUT_DEVICE
#endif // __FreeBSD__ or linux
"]\n"
" and '-V' specifies the output volume in percent [default is 75%]\n"
" (this value will be divided by 100 and passed as '-g' to fluidsynth)\n"
" and 'ip:port specifies an optional ip address and/or port to listen on\n"
" the default port is 9000; specifying blank IP listens on all.\n"
" NOTE: IPv6 addresses should be expressed as '[ip:ad:dr:es:s]:port'\n",
stderr);
}
// NOTE: Ethernet MIDI driver on windows generates UDP packets (default port 9000) with the following format:
//
// low endian long integer: 00000000H byte sequence 00,00,00,00 [unknown purpose, always 0]
// low endian long integer: 00000003H byte sequence 03,00,00,00 [length of MIDI data?]
// 3 bytes of data (MIDI sequence)
char szWaveTable[PATH_MAX * 2 + 2] = "";
char szOutDev[PATH_MAX * 2 + 2] = "";
int iVolume = 75; // default volume = 75 (use -g with this value / 100.0)
int DoListenSocket(const char *szIPPort)
{
struct sockaddr_storage sa; // sufficiently large enough to handle IPv4 or IPv6
struct sockaddr_in *pSA4 = NULL;
struct sockaddr_in6 *pSA6 = NULL;
int iRval;
short sPort;
const char *pTemp, *pIPPort;
char *pTemp2;
memset(&sa, 0, sizeof(sa));
pIPPort = szIPPort;
pTemp = NULL; // initially, make sure
if(*pIPPort == '[') // required for ipv6 as "[ip:ad:dre:ss]:port"
{
pSA6 = (struct sockaddr_in6 *)&sa;
pSA6->sin6_family = AF_INET6;
#ifdef __FreeBSD__ /* Linux doesn't have this data member */
pSA6->sin6_len = sizeof(*pSA6);
#endif // __FreeBSD__
pTemp = strchr(pIPPort, ']');
// zero-byte the ']' at the end by copying to a buffer, first
if(pTemp && (!pTemp[1] || pTemp[1] == ':')) // should be
{
pTemp2 = malloc((pTemp - pIPPort) + 2);
if(!pTemp2)
{
fprintf(stderr, "Not enough memory to evaluate IPv6 address - errno=%d\n", errno);
return -1;
}
memcpy(pTemp2, pIPPort + 1, (pTemp - pIPPort) - 1);
pTemp2[pTemp - pIPPort - 1] = 0;
pTemp++; // points to end of string or ':' now
}
else
{
fprintf(stderr, "Invalid ipv6 '%s'\n (must be '[IPv6]' or '[IPv6]:port')\n", pIPPort);
return -1;
}
// passing sin6_addr was determined by experimentation, hopefully consistent across platforms
if(0 >= inet_pton(AF_INET6, pTemp2, &(pSA6->sin6_addr)))
{
fprintf(stderr, "Invalid ipv6 '[%s]%s'\n (must be '[IPv6]:port' or '[IPv6]')\n", pTemp2, pTemp);
free(pTemp2);
usage();
return -1;
}
pIPPort = pTemp; // point to the ':' (or end of string)
free(pTemp2);
}
else if(*pIPPort)
{
pSA4 = (struct sockaddr_in *)&sa;
pSA4->sin_family = AF_INET;
#ifdef __FreeBSD__ /* Linux doesn't have this data member */
pSA4->sin_len = sizeof(*pSA4);
#endif // __FreeBSD__
// assume ipv4 address for now, ':' is port separator
pTemp = strrchr(pIPPort, ':'); // reverse look for ':'
if(!pTemp)
{
pTemp = pIPPort + strlen(pIPPort);
}
if((pTemp - pIPPort) == 9 && !strncmp(pIPPort, "localhost", 9))
{
uint32_t ulTemp = htonl(INADDR_LOOPBACK); // localhost, 127.0.0.1
// this assigns 'sin_addr' assuming it's a uint32_t
*((uint32_t *)&(pSA4->sin_addr)) = ulTemp;
}
else if(pTemp > pIPPort)
{
pTemp2 = malloc((pTemp - pIPPort) + 2);
if(!pTemp2)
{
fprintf(stderr, "Not enough memory to evaluate IPv6 address - errno=%d\n", errno);
return -1;
}
memcpy(pTemp2, pIPPort, pTemp - pIPPort);
pTemp2[pTemp - pIPPort] = 0;
if(0 >= inet_pton(AF_INET, pTemp2, &(pSA4->sin_addr)))
{
fprintf(stderr, "Invalid ip '%s'\n (must be '[IPv6]' '[IPv6]:port' 'IP' 'IP:port' or ':port')\n", pIPPort);
free(pTemp2);
usage();
return -1;
}
free(pTemp2);
}
// TODO: if IPv6 not supported, use the old method *((uint32_t *)&(pSA4->sin_addr)) = 0;
else // bind to '0' using IPv6 - this way it's a 'udp46' socket, accepting either protocol
{
// *((uint32_t *)&(pSA4->sin_addr)) = 0;
pSA4 = NULL;
pSA6 = (struct sockaddr_in6 *)&sa;
pSA6->sin6_family = AF_INET6;
#ifdef __FreeBSD__ /* Linux doesn't have this data member */
pSA6->sin6_len = sizeof(*pSA6);
#endif // __FreeBSD__
}
}
if(pTemp && pTemp[1])
{
sPort = atoi(pTemp + 1);
}
else
{
sPort = 9000; // default
}
if(pSA6)
{
pSA6->sin6_port = htons(sPort);
}
else
{
pSA4->sin_port = htons(sPort);
}
// if(pSA6 || pSA4)
// {
// char tbuf[256];
//
// fprintf(stderr, "TEMPORARY: inet_ntop() returns \"%s\"\n",
// inet_ntop(pSA6 ? AF_INET6 : AF_INET,
// (struct in_addr *)(pSA6 ? (void *)&(pSA6->sin6_addr) : (void *)&(pSA4->sin_addr)),
// tbuf, sizeof(tbuf)));
// }
iRval = socket((pSA6 ? PF_INET6 : PF_INET), SOCK_DGRAM, IPPROTO_UDP);
if(iRval != -1)
{
int i2;
if(pSA6)
{
i2 = bind(iRval, (const struct sockaddr *)pSA6, sizeof(*pSA6));
}
else // pSA4
{
i2 = bind(iRval, (const struct sockaddr *)pSA4, sizeof(*pSA4));
}
if(i2 < 0)
{
char tbuf[256];
fprintf(stderr, "Unable to bind socket for '%s', errno=%d\n", szIPPort, errno);
close(iRval);
fprintf(stderr, " inet_ntop() returns \"%s\"\n",
inet_ntop(pSA6 ? AF_INET6 : AF_INET,
pSA6 ? (struct in_addr *)&(pSA6->sin6_addr) : &(pSA4->sin_addr),
tbuf, sizeof(tbuf)));
iRval = -1;
}
}
else
{
fprintf(stderr, "Unable to create socket for '%s', errno=%d\n", szIPPort, errno);
return -1;
}
return iRval;
}
// invoke fluidsynth with these parameters
// fluidsynth -m [alsa_seq? coremidi?] -p /dev/[cuse-device-name] [soundfontfile]
// possibly use ' -m oss -o "midi.oss.device /dev/[cuse-device-name]" '
int main(int argc, char *argv[])
{
int i1, iSocket = -1;
int bDaemon = 0; // boolean flags, actually
while((i1 = getopt(argc, argv, "vhdF:o:V:" )) != -1)
{
switch(i1)
{
case 'h':
usage();
return 0;
case 'v':
fputs("ethermidi version 1.0\n", stdout);
return 0;
case 'd':
bDaemon = 1;
break;
case 'V':
iVolume = atoi(optarg);
if(iVolume <= 0)
iVolume = 75; // default
break;
case 'F':
strncpy(szWaveTable, optarg, sizeof(szWaveTable));
break;
case 'o':
strncpy(szOutDev, optarg, sizeof(szOutDev));
break;
default:
usage();
return 1;
}
}
argc -= optind;
argv += optind;
if(bDaemon)
{
i1 = fork();
if(i1 < 0)
{
fprintf(stderr, "Unable to fork to daemon process, errno=%d\n", errno);
return 2;
}
if(i1 > 0)
{
fprintf(stderr, "Daemonizing as process %d (%xH)\n", i1, i1);
return 0;
}
close(0); // close stdin - I don't want it - but keep stdout just in case...
// TODO: do I re-direct stderr and stdout to something that logs it?
}
if(argc < 1) // remaining args [argv[0] already stripped away]
{
iSocket = DoListenSocket(":9000"); // assume 'bind to all' with default port
}
else
{
// TODO: do I want to listen to multiple sockets?
iSocket = DoListenSocket(argv[0]);
}
if(iSocket == -1)
{
fprintf(stderr, "ERROR: %d while creating socket\n", errno);
return 1;
}
do_main(iSocket, szWaveTable);
close(iSocket);
return 0;
}
// thread utilities
pthread_t MyCreateThread(the_thread_proc *pProc, void *pParam)
{
pthread_t thr;
if(!pthread_create(&thr, NULL, pProc, pParam))
{
return thr;
}
return 0; // return -1 instead?
}
#ifdef USE_CUSE
int my_cm_open(struct cuse_dev *, int fflags);
int my_cm_close(struct cuse_dev *, int fflags);
int my_cm_read(struct cuse_dev *, int fflags, void *user_ptr, int len);
int my_cm_write(struct cuse_dev *, int fflags, const void *user_ptr, int len);
int my_cm_ioctl(struct cuse_dev *, int fflags, unsigned long cmd, void *user_data);
int my_cm_poll(struct cuse_dev *, int fflags, int events);
static struct cuse_methods sCM =
{
.cm_open = my_cm_open,
.cm_close = my_cm_close,
.cm_read = my_cm_read,
.cm_write = my_cm_write,
.cm_ioctl = my_cm_ioctl,
.cm_poll = my_cm_poll
};
#endif // USE_CUSE
int my_buf_len(const MY_BUF *pBuf)
{
if(pBuf->nHead < pBuf->nTail)
{
return (pBuf->nHead + pBuf->cbBuf) - pBuf->nTail;
}
return pBuf->nHead - pBuf->nTail;
}
int my_buf_remaining(const MY_BUF *pBuf)
{
int iLen = my_buf_len(pBuf);
return pBuf->cbBuf - 1 - iLen;
}
void my_buf_write(MY_BUF *pBuf, const char *pData, int cbLen)
{
int iTemp;
// fprintf(stderr, "TEMP2 enter %d %d %d - %d\n", cbLen, pBuf->nHead, pBuf->nTail, my_buf_remaining(pBuf)); // TEMPORARY
// assumes 'cbLen' less than 'my_buf_remaining()' return value
// otherwise the head/tail pointers may crash
iTemp = pBuf->nHead + cbLen;
if(iTemp > pBuf->cbBuf)
{
iTemp = pBuf->cbBuf - pBuf->nHead; // # of bytes to the end
}
else
{
iTemp = cbLen;
}
// note: iTemp won't exceed 'cbLen'
if(iTemp > 0)
{
memcpy(&(pBuf->buffer[pBuf->nHead]), pData, iTemp);
pBuf->nHead += iTemp; // update head pointer
}
if(pBuf->nHead >= pBuf->cbBuf) // this means I wrote to "the end"
{
cbLen -= iTemp; // maybe more left to write
if(cbLen) // more to copy
{
pData += iTemp;
memcpy(pBuf->buffer, pData, cbLen);
}
pBuf->nHead = cbLen; // regardless, do this
}
else
{
// won't get here unless I completed writing the data, *AND* the pointer's not at the end
}
// fprintf(stderr, "TEMP2 exit %d %d %d %d\n", iTemp, pBuf->nHead, pBuf->nTail, cbLen); // TEMPORARY
}
int my_buf_read(MY_BUF *pBuf, char *pData, int cbLen)
{
int iTemp, iRval;
// fprintf(stderr, "TEMP enter %d %d %d\n", cbLen, pBuf->nHead, pBuf->nTail); // TEMPORARY
iTemp = pBuf->nHead - pBuf->nTail; // I write to 'head', read from 'tail'
if(cbLen <= 0 || !iTemp) // nothing to read
{
return 0; // nothing to read
}
else if(iTemp > 0) // head preceeds tail in circular buffer
{
if(iTemp > cbLen)
{
iTemp = cbLen;
}
memcpy(pData, &(pBuf->buffer[pBuf->nTail]), iTemp);
pBuf->nTail += iTemp; // move the 'tail' pointer
pData += iTemp;
cbLen -= iTemp;
if(!cbLen || pBuf->nTail == pBuf->nHead) // I am done
{
// fprintf(stderr, "TEMP exit1 %d %d %d %d\n", iTemp, pBuf->nHead, pBuf->nTail, cbLen); // TEMPORARY
return iTemp; // byte count
}
iRval = iTemp; // what I've sent so far
}
else
{
iRval = 0; // nothing sent so far
}
// at this point, iHead < iTail which means it wraps around
iTemp = pBuf->nTail + cbLen; // how much before the end of the buffer?
if(iTemp > pBuf->cbBuf)
{
iTemp = pBuf->cbBuf - pBuf->nTail; // # of bytes to the end
}
else
{
iTemp = cbLen;
}
// note: iTemp won't exceed 'cbLen'
memcpy(pData, &(pBuf->buffer[pBuf->nTail]), iTemp);
pBuf->nTail += iTemp; // update tail pointer
iRval += iTemp;
if(pBuf->nTail >= pBuf->cbBuf) // this means I read to "the end", so wrap around
{
cbLen -= iTemp; // anything left to read?
if(cbLen) // more to read (could cheat and recurse)
{
pData += iTemp;
iTemp = pBuf->nHead; // - pBuf->nTail; it will be zero right now
if(iTemp > cbLen)
{
iTemp = cbLen; // only read "that much"
}
if(iTemp > 0)
{
memcpy(pData, pBuf->buffer, iTemp);
iRval += iTemp;
}
pBuf->nTail = iTemp; // up to but not including 'nHead'
}
else
{
pBuf->nTail = 0; // wrap around
}
}
// fprintf(stderr, "TEMP exit2 %d %d %d %d\n", iTemp, pBuf->nHead, pBuf->nTail, cbLen); // TEMPORARY
return iRval; // total # of bytes read
}
volatile int bDying = 0; // set to 1 to stop threads
volatile pthread_t xThread = 0; // the thread
#ifdef USE_CUSE
void * cuse_thread(void *pArg)
{
signal(SIGHUP, SIG_DFL); // allow 'HUP' to interrupt me
while(!bDying && !cuse_wait_and_process())
{
usleep(100);
}
fputs("TEMPORARY - thread dying\n", stderr);
fflush(stderr);
usleep(20000); // give things a chance to catch up (simple synchronization, TODO fix it later)
xThread = 0; // I'm dying anyway
return NULL;
}
#endif // USE_CUSE
void hup_handler(int iSig) // call 'signal(SIGHUP, hup_handler)' to enable it
{
bDying = 1;
fprintf(stderr, "\nSOFT Terminating on signal %d\n", iSig);
// signal(SIGHUP, SIG_DFL); let this one stay, so I can HUP the thread
signal(SIGKILL, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGINT, SIG_DFL);
if(xThread == pthread_self())
{
pthread_cancel(xThread);
}
}
int ProcessHasExited(int pid)
{
int iTemp, iTemp2;
iTemp2 = waitpid(pid, &iTemp, WNOHANG);
if(iTemp2 < 0 || // assume it does not exist
(iTemp2 > 0 && WIFEXITED(iTemp))) // process has exited?
{
return 1;
}
return 0; // it's still running
}
int do_main(int iListen, const char *szSoundFont)
{
#ifdef USE_CUSE
int iCuseUnit, iDev, iDev2;
struct cuse_dev *pDev = NULL;
#elif defined(USE_LIBFLUIDSYNTH)
fluid_settings_t * settings = NULL;
fluid_synth_t * synth = NULL;
fluid_audio_driver_t * adriver = NULL;
#ifdef USE_LIBFLUIDSYNTH_PARSER
fluid_midi_router_t* router = NULL;
fluid_midi_parser_t * parser = NULL;
fluid_midi_event_t * event = NULL;
#endif // USE_LIBFLUIDSYNTH_PARSER
int fluid_res;
#else // !USE_CUSE, !USE_LIBFLUIDSYNTH
int iDev, iDev2;
#endif // USE_CUSE, USE_LIBFLUIDSYNTH
#ifndef USE_LIBFLUIDSYNTH
pid_t pidFluidSynth = -1;
#endif // !USE_LIBFLUIDSYNTH
int iTemp, iTemp2;
unsigned long dwStart;
MY_BUF *pBuf1, *pBuf2;
void *pTemp;
char szDevName[32];
char tbuf[256];
struct sockaddr_storage saFrom; // sufficiently large enough to handle IPv4 or IPv6
socklen_t nSA;
signal(SIGHUP, hup_handler);
signal(SIGKILL, hup_handler); // may not work
signal(SIGTERM, hup_handler); // should work
signal(SIGINT, hup_handler); // might work
pBuf1 = (MY_BUF *)malloc(MY_BUF_SIZE * 2 + 2 * sizeof(*pBuf1));
if(!pBuf1)
{
fprintf(stderr, "Not enough memory - errno=%d\n", errno);
return -1;
}
pBuf1->cbBuf = MY_BUF_SIZE;
pBuf1->nHead = pBuf1->nTail = 0;
pBuf2 = (MY_BUF *)((unsigned char *)pBuf1 + MY_BUF_SIZE + sizeof(*pBuf1));
pBuf2->cbBuf = MY_BUF_SIZE;
pBuf2->nHead = pBuf2->nTail = 0;
#ifdef USE_CUSE
iTemp = cuse_init(); // fails if you're not root
if(iTemp)
{
fprintf(stderr, "cuse_init() returns %d - are you running as 'root'?\n", iTemp);
return -1;
}
iCuseUnit = 0;
iTemp = cuse_alloc_unit_number(&iCuseUnit);
if(iTemp)
{
fprintf(stderr, "cuse_alloc_unit_number() returns %d\n", iTemp);
iCuseUnit = -1; // an error flag
goto error_exit;
}
pDev = cuse_dev_create(&sCM, (void *)pBuf1, (void *)pBuf2, 0, 0, 0666, "ethermidi%d", iCuseUnit);
snprintf(szDevName, sizeof(szDevName)-1, "/dev/ethermidi%d", iCuseUnit);
if(!pDev)
{
fprintf(stderr, "cuse_dev_create() returns NULL, errno=%d\n", errno);
goto error_exit;
}
fputs("Creating thread\n", stderr);
fflush(stderr);
xThread = MyCreateThread(cuse_thread, NULL);
if(!xThread)
{
fprintf(stderr, "Unable to create thread - errno=%d\n", errno);
goto error_exit;
}
#elif defined(USE_LIBFLUIDSYNTH)
settings = new_fluid_settings();
if(!settings)
{
fprintf(stderr, "Unable to create fluidsynth settings - errno=%d\n", errno);
goto error_exit;
}
#else // !USE_CUSE, !USE_LIBFLUIDSYNTH
// create a FIFO to do this with
bDying = 0; // initially must be zero
snprintf(szDevName, sizeof(szDevName), "/tmp/EtherMIDI.%08x.fifo", (uint32_t)getpid());
if(mkfifo(szDevName, 0664) < 0)
{
fprintf(stderr, "mkfifi() returns error, errno=%d\n", errno);
goto error_exit;
}
#endif // USE_CUSE
#ifdef USE_CUSE
usleep(5000); // to help synchronize
fprintf(stderr, "Opening device \"%s\"\n", szDevName);
fflush(stderr);
iDev = open(szDevName, O_WRONLY); // the thing I'm writing to
if(iDev == -1)
{
fprintf(stderr, "ERROR: errno=%d opening %s\n", errno, szDevName);
bDying = 1; // to shut things down
pthread_kill(xThread, SIGHUP); // so I can kill it
usleep(50000); // to help synchronize
pthread_kill(xThread, SIGHUP); // so I can kill it
usleep(50000); // to help synchronize
goto error_exit;
}
#elif !defined(USE_LIBFLUIDSYNTH)
fprintf(stderr, "Opening FIFO \"%s\"\n", szDevName);
fflush(stderr);
iDev2= open(szDevName, O_RDONLY | O_NONBLOCK);
if(iDev2 == -1)
{
fprintf(stderr, "ERROR: errno=%d opening %s\n", errno, szDevName);
iDev = -1; // not open yet
goto error_exit;
}
iDev = open(szDevName, O_WRONLY | O_NONBLOCK);
if(iDev == -1)
{
fprintf(stderr, "ERROR: errno=%d opening %s\n", errno, szDevName);
unlink(szDevName); // clean up, too
goto error_exit;
}
iTemp = 1;
if(ioctl(iDev, FIONBIO, &iTemp) < 0)
{
fprintf(stderr, "Unable to set non-blocking I/O, errno=%d\n", errno);
}
else
{
fprintf(stderr, "Assigned non-blocking I/O\n");
}
iTemp = 1;
if(ioctl(iDev, FIOASYNC, &iTemp) < 0)
{
fprintf(stderr, "Unable to set async I/O, errno=%d\n", errno);
}
else
{
fprintf(stderr, "Assigned async I/O\n");
}
bDying = 0;
fflush(stderr);
#endif // USE_CUSE
fputs("Starting fluidsynth\n", stderr);
fflush(stderr);
#ifdef USE_LIBFLUIDSYNTH
fluid_settings_setnum(settings, "synth.gain", (double)(iVolume / 100.0) /*0.5*/);
fprintf(stderr, " synth.gain set to %0.2f\n", (double)(iVolume / 100.0));
fflush(stderr);
synth = new_fluid_synth(settings);
if(!synth)
{
fprintf(stderr, "Unable to create fluidsynth - errno=%d\n", errno);
goto error_exit;
}
if(*szSoundFont)
{
fluid_res = fluid_synth_sfload(synth, szSoundFont, 1); // TODO: check result
}
else
{
fputs("WARNING: no sound font file specified\n", stderr);
fflush(stderr);
}
if(!szOutDev[0]) // use default output device
{
#ifdef __FreeBSD__
strcpy(szOutDev, DEFAULT_FREEBSD_OUT_DEVICE);
#else // linux
strcpy(szOutDev, DEFAULT_LINUX_OUT_DEVICE);
#endif // __FreeBSD__ or linux
}
fluid_settings_setstr(settings, "audio.driver", szOutDev);
adriver = new_fluid_audio_driver(settings, synth);
if(!adriver)
{
fprintf(stderr, "Unable to create fluidsynth audio driver - errno=%d\n", errno);
goto error_exit;
}
#ifdef USE_LIBFLUIDSYNTH_PARSER
router = new_fluid_midi_router(settings, fluid_synth_handle_midi_event, synth); // routes midi events to synth
if(!router)
{
fprintf(stderr, "Unable to create fluidsynth midi router - errno=%d\n", errno);
goto error_exit;
}
parser = new_fluid_midi_parser();
if(!parser)
{
fprintf(stderr, "Unable to create fluidsynth parser - errno=%d\n", errno);
goto error_exit;
}
#endif // USE_LIBFLUIDSYNTH_PARSER
#else // !USE_LIBFLUIDSYNTH
// now we need to run 'fluidsynth' with the appropriate parameters
// TODO: make sure I can find it in the path first and get the fullpath for it
strcpy(tbuf, "midi.oss.device=");
strcat(tbuf, szDevName);
pidFluidSynth = WBRunAsync("/usr/local/bin/fluidsynth", "--no-shell", "-a", DEFAULT_FREEBSD_OUT_DEVICE, "-g", "0.5",
"-v",
#ifdef __FreeBSD__
"-m", DEFAULT_FREEBSD_OUT_DEVICE,
#else // assume Linux
"-m", DEFAULT_LINUX_OUT_DEVICE,
#endif // __FreeBSD__ vs Linux
"-o", tbuf, szSoundFont, NULL);
close(iTemp);
#endif // USE_LIBFLUIDSYNTH
#ifndef USE_LIBFLUIDSYNTH
if(pidFluidSynth != -1)
{
#ifdef USE_CUSE
fprintf(stderr, "Opening FIFO \"%s\"\n", szDevName);
fflush(stderr);