OSDN Git Service

9b025c9422b3c409d6924a86c3b9befd3d976cf9
[timidity41/timidity41.git] / interface / server_c.c
1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
4     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20     server_c.c - TiMidity server written by Masanao Izumo <mo@goice.co.jp>
21         Mon Apr 5 1999: Initial created.
22
23
24     Launch TiMidity server: (example)
25     % timidity -ir 7777
26
27     Protcol note:
28     The protocol is based on OSS interface.
29     TiMidity server has 2 TCP/IP connection.  They are control port and
30     data port.
31     Control port:
32         ASCII text protocol like FTP control port. See command_help for
33         control protocol in this source code.
34     Data port:
35         One way Binary stream data from client to server. The format of
36         stream is same as OSS sequencer stream.
37
38
39     TODO:
40         Protocol specification to be documented.
41     */
42
43 #ifdef HAVE_CONFIG_H
44 #include "config.h"
45 #endif /* HAVE_CONFIG_H */
46
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <stdarg.h>
50 #include <unistd.h>
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <sys/time.h>
54 #include <netinet/in.h>
55 #ifndef NO_STRING_H
56 #include <string.h>
57 #else
58 #include <strings.h>
59 #endif
60 #include <signal.h>
61
62 #ifdef HAVE_SYS_SOUNDCARD_H
63 #include <sys/soundcard.h>
64 #else
65 #include "server_defs.h"
66 #endif /* HAVE_SYS_SOUNDCARD_H */
67
68 #include "timidity.h"
69 #include "common.h"
70 #include "controls.h"
71 #include "instrum.h"
72 #include "playmidi.h"
73 #include "readmidi.h"
74 #include "recache.h"
75 #include "output.h"
76 #include "aq.h"
77 #include "timer.h"
78
79 /* #define DEBUG_DUMP_SEQ 1 */
80 #define MIDI_COMMAND_PER_SEC    100
81 #define DEFAULT_LOW_TIMEAT      0.4
82 #define DEFAULT_HIGH_TIMEAT     0.6
83 #define DONT_STOP_AUDIO 1
84 #define DEFAULT_TIMEBASE        100 /* HZ? */
85 #define MAXTICKDIFF             150
86 #define SIG_TIMEOUT_SEC         3
87
88
89 static int cmd_help(int argc, char **argv);
90 static int cmd_open(int argc, char **argv);
91 static int cmd_close(int argc, char **argv);
92 static int cmd_timebase(int argc, char **argv);
93 static int cmd_reset(int argc, char **argv);
94 static int cmd_patch(int argc, char **argv);
95 static int cmd_quit(int argc, char **argv);
96 static int cmd_queue(int argc, char **argv);
97 static int cmd_maxqueue(int argc, char **argv);
98 static int cmd_time(int argc, char **argv);
99 static int cmd_nop(int argc, char **argv);
100 static int cmd_autoreduce(int argc, char **argv);
101 static int cmd_setbuf(int argc, char **argv);
102
103 struct
104 {
105     char *cmd, *help;
106     int minarg, maxarg;
107     int (* proc)(int argc, char **argv);  /* argv[0] is command name
108                                            * argv[1..argc-1] is the arg.
109                                            * return: 0=success, -1=fatal-error,
110                                            *         1=connection-closed
111                                            */
112 } cmd_table[] =
113 {
114     {"HELP",
115         "HELP\tDisplay this message",
116         1, 1, cmd_help},
117     {"OPEN",
118         "OPEN {lsb|msb}\n"
119         "\tOpen data connection\n"
120         "\tlsb: The byte order of data stream is LSB\n"
121         "\tmsb: The byte order of data stream is MSB",
122         2, 2, cmd_open},
123     {"CLOSE",
124         "CLOSE\tShutdown current data connection",
125         1, 1, cmd_close},
126     {"TIMEBASE",
127         "TIMEBASE [timebase]\n\tSet time base",
128         1, 2, cmd_timebase},
129     {"RESET",
130         "RESET\tInitialize all of MIDI status",
131         1, 1, cmd_reset},
132     {"PATCH",
133         "PATCH {drumset|bank} <bank-no> <prog-no>\n\tLoad specified patch",
134         4, 4, cmd_patch},
135     {"QUIT",
136         "QUIT\tClose control connection",
137         1, 1, cmd_quit},
138     {"QUEUE",
139         "QUEUE\tTiMidity tells the time of audio buffer queue in second",
140         1, 1, cmd_queue},
141     {"MAXQUEUE",
142         "MAXQUEUE\n"
143         "\tTiMidity tells the maxmum time of audio buffer queue in second",
144         1, 1, cmd_maxqueue},
145     {"TIME",
146         "TIME\tTiMidity tells the current playing time in second",
147         1, 1, cmd_time},
148     {"NOP",
149         "NOP\tDo nothing",
150         1, 1, cmd_nop},
151     {"AUTOREDUCE",
152         "AUTOREDUCE {on|off} [msec]\n\tEnable/Disable auto voice reduction",
153         2, 3, cmd_autoreduce},
154     {"SETBUF",
155         "SETBUF low hi\n\tSpecify low/hi sec of buffer queue",
156         3, 3, cmd_setbuf},
157
158     {NULL, NULL, 0, 0, NULL} /* terminate */
159 };
160
161 /*
162 TEMPO [<tempo>]\n\
163         Change the tempo.  If the argument is omitted, TiMidity tells the\n\
164         current tempo.\n\
165 KEYSHIFT <{+|-}offs>\n\
166         Change the base key. (0 to reset)\n\
167 SPEED <{+|-}offs>\n\
168         Change the play speed. (0 to reset)\n\
169 MODE {gs|xg|gm}\n\
170         Specify default MIDI system mode\n\
171 SYNTH [gus|awe]\n\
172         Specify Synth type emulation. (no argument to default)\n\
173 */
174
175
176 static int ctl_open(int using_stdin, int using_stdout);
177 static void ctl_close(void);
178 static int ctl_read(int32 *valp);
179 static int cmsg(int type, int verbosity_level, char *fmt, ...);
180 static void ctl_event(CtlEvent *e);
181 static void ctl_pass_playing_list(int n, char *args[]);
182
183 /**********************************/
184 /* export the interface functions */
185
186 #define ctl server_control_mode
187
188 ControlMode ctl=
189 {
190     "remote interface", 'r',
191     1,0,0,
192     0,
193     ctl_open,
194     ctl_close,
195     ctl_pass_playing_list,
196     ctl_read,
197     cmsg,
198     ctl_event
199 };
200
201
202 struct fd_read_buffer
203 {
204     char buff[BUFSIZ];
205     /* count: beginning of read pointer
206      * size:  end of read pointer
207      * fd:    file descripter for input
208      */
209     int count, size, fd;
210 };
211 static int fdgets(char *buff, size_t buff_size, struct fd_read_buffer *p);
212 static int fdputs(char *s, int fd);
213 static uint32 data2long(uint8* data);
214 static uint16 data2short(uint8* data);
215 static int do_control_command_nonblock(void);
216
217 static struct fd_read_buffer control_fd_buffer;
218 static int data_fd = -1, control_fd = -1;
219 static int data_port, control_port;
220 static int is_lsb_data = 1;
221 static int curr_timebase = DEFAULT_TIMEBASE;
222 static int32 sample_correction;
223 static int32 sample_increment;
224 static int32 sample_correction;
225 static int32 sample_cum;
226 static int32 curr_event_samples, event_time_offset;
227 static int32 curr_tick, tick_offs;
228 static double start_time;
229 static int tmr_running;
230
231 static int is_system_prefix = 0;
232 static struct sockaddr_in control_client;
233 static double low_time_at = 0.3;
234 static double high_time_at = 0.5;
235 static FILE *outfp;
236
237 /*ARGSUSED*/
238 static int ctl_open(int using_stdin, int using_stdout)
239 {
240     ctl.opened = 1;
241     ctl.flags &= ~(CTLF_LIST_RANDOM|CTLF_LIST_SORT);
242     if(using_stdout)
243         outfp = stderr;
244     else
245         outfp = stdout;
246     return 0;
247 }
248
249 static void ctl_close(void)
250 {
251     if(!ctl.opened)
252         return;
253     if(data_fd != -1)
254     {
255         close(data_fd);
256         data_fd = -1;
257     }
258     if(control_fd != -1)
259     {
260         close(control_fd);
261         control_fd = -1;
262     }
263 }
264
265 /*ARGSUSED*/
266 static int ctl_read(int32 *valp)
267 {
268     if(data_fd != -1)
269         do_control_command_nonblock();
270     return RC_NONE;
271 }
272
273 static int cmsg(int type, int verbosity_level, char *fmt, ...)
274 {
275     va_list ap;
276
277     if((type==CMSG_TEXT || type==CMSG_INFO || type==CMSG_WARNING) &&
278        ctl.verbosity < verbosity_level)
279         return 0;
280
281     if(outfp == NULL)
282         outfp = stderr;
283
284     va_start(ap, fmt);
285     vfprintf(outfp, fmt, ap);
286     fputs(NLS, outfp);
287     fflush(outfp);
288     va_end(ap);
289
290     return 0;
291 }
292
293 static void ctl_event(CtlEvent *e)
294 {
295 }
296
297 static int pasv_open(int *port)
298 {
299     int sfd;
300     struct sockaddr_in server;
301
302     if((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
303     {
304         perror("socket");
305         return -1;
306     }
307
308     memset(&server, 0, sizeof(server));
309     server.sin_port        = htons(*port);
310     server.sin_family      = AF_INET;
311     server.sin_addr.s_addr = htonl(INADDR_ANY);
312
313 #ifdef SO_REUSEADDR
314     {
315         int on = 1;
316         setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (caddr_t)&on, sizeof(on));
317     }
318 #endif /* SO_REUSEADDR */
319
320     ctl.cmsg(CMSG_INFO, VERB_DEBUG, "Bind TCP/IP port=%d", *port);
321     if(bind(sfd, (struct sockaddr *)&server, sizeof(server)) < 0)
322     {
323         perror("bind");
324         close(sfd);
325         return -1;
326     }
327     if(*port == 0)
328     {
329         int len = sizeof(server);
330         if(getsockname(sfd, (struct sockaddr *)&server, &len) < 0)
331         {
332             perror("getsockname");
333             close(sfd);
334             return -1;
335         }
336         *port = ntohs(server.sin_port);
337     }
338
339     /* Set it up to wait for connections. */
340     if(listen(sfd, 1) < 0)
341     {
342         perror("listen");
343         close(sfd);
344         return -1;
345     }
346
347     return sfd;
348 }
349
350 static RETSIGTYPE sig_timeout(int sig)
351 {
352     signal(SIGALRM, sig_timeout); /* For SysV base */
353     /* Expect EINTR */
354 }
355
356 static void doit(void);
357 static int send_status(int status, char *message, ...);
358 static void compute_sample_increment(void);
359 static void server_reset(void);
360
361 static void ctl_pass_playing_list(int n, char *args[])
362 {
363     int sock;
364
365     if(n != 2 && n != 1)
366     {
367         fprintf(stderr, "Usage: timidity -ir control-port [data-port]\n");
368         return;
369     }
370
371 #ifdef SIGPIPE
372     signal(SIGPIPE, SIG_IGN);    /* Handle broken pipe */
373 #endif /* SIGPIPE */
374
375     control_port = atoi(args[0]);
376     if(n == 2)
377         data_port = atoi(args[1]);
378     else
379         data_port = 0;
380
381     if (control_port) {
382         sock = pasv_open(&control_port);
383         if(sock == -1)
384             return;
385     }
386     opt_realtime_playing = 1; /* Enable loading patch while playing */
387     allocate_cache_size = 0; /* Don't use pre-calclated samples */
388 /*  aq_set_soft_queue(-1.0, 0.0); */
389     alarm(0);
390     signal(SIGALRM, sig_timeout);
391
392     play_mode->close_output();
393     while(1)
394     {
395         int addrlen;
396
397         addrlen = sizeof(control_client);
398         memset(&control_client, 0, addrlen);
399
400         if (control_port) {
401             if((control_fd = accept(sock,
402                                 (struct sockaddr *)&control_client,
403                                 &addrlen)) < 0)
404             {
405                 if(errno == EINTR)
406                     continue;
407                 perror("accept");
408                 close(sock);
409                 return;
410             }
411         }
412         else control_fd = 0;
413
414         if(play_mode->open_output() < 0)
415         {
416             ctl.cmsg(CMSG_FATAL, VERB_NORMAL,
417                      "Couldn't open %s (`%c')",
418                      play_mode->id_name, play_mode->id_character);
419             send_status(510, "Couldn't open %s (`%c')",
420                         play_mode->id_name, play_mode->id_character);
421             if (control_port) {
422                 close(control_fd);
423                 control_fd = 1;
424             }
425             continue;
426         }
427
428         server_reset();
429
430         ctl.cmsg(CMSG_INFO, VERB_NOISY, "Connected");
431         doit();
432         ctl.cmsg(CMSG_INFO, VERB_NOISY, "Connection closed");
433
434         play_mode->close_output();
435
436         if(control_fd != -1 && control_port)
437         {
438             close(control_fd);
439             control_fd = -1;
440         }
441         if(data_fd != -1)
442         {
443             close(data_fd);
444             data_fd = -1;
445         }
446         free_instruments(0);
447         free_global_mblock();
448         if (!control_port)
449             break;
450     }
451 }
452
453 #define MAX_GETCMD_PARAMS 8
454 /* return:
455  * 0: success
456  * 1: error
457  *-1: fatal error (will be close the connection)
458  */
459 static int control_getcmd(char **params, int *nparams)
460 {
461     static char buff[BUFSIZ];
462     int n;
463
464     /* read line */
465     n = fdgets(buff, sizeof(buff), &control_fd_buffer);
466     if(n == -1)
467     {
468         perror("read");
469         return -1;
470     }
471     if(n == 0)
472         return 1;
473     if((params[0] = strtok(buff, " \t\r\n\240")) == NULL)
474         return 0;
475     *nparams = 0;
476     while(params[*nparams] && *nparams < MAX_GETCMD_PARAMS)
477         params[++(*nparams)] = strtok(NULL," \t\r\n\240");
478     return 0;
479 }
480
481 static int send_status(int status, char *message, ...)
482 {
483     va_list ap;
484     char buff[BUFSIZ];
485
486     va_start(ap, message);
487     sprintf(buff, "%03d ", status);
488     vsnprintf(buff + 4, sizeof(buff) - 5, message, ap);
489     va_end(ap);
490     strcat(buff, "\n");
491     if(write(control_fd, buff, strlen(buff)) == -1)
492         return -1;
493     return 0;
494 }
495
496 static void seq_play_event(MidiEvent *ev)
497 {
498     if(tmr_running)
499         ev->time = curr_event_samples;
500     else
501     {
502         if(IS_STREAM_TRACE)
503         {
504             event_time_offset += play_mode->rate / MIDI_COMMAND_PER_SEC;
505             ev->time = curr_event_samples;
506         }
507         else
508         {
509             double past_time = get_current_calender_time() - start_time;
510             if(play_mode->flag & PF_PCM_STREAM)
511                 past_time += high_time_at;
512             ev->time = (int32)(past_time * play_mode->rate);
513         }
514     }
515     ev->time += event_time_offset;
516     play_event(ev);
517 }
518
519 static void tmr_reset(void)
520 {
521     curr_event_samples =
522         event_time_offset =
523             sample_cum = 0;
524     playmidi_tmr_reset();
525     curr_timebase = DEFAULT_TIMEBASE;
526     curr_tick = tick_offs = 0;
527     start_time = get_current_calender_time();
528 }
529
530 static void compute_sample_increment(void)
531 {
532     double a;
533     a = (double)current_play_tempo * (double)play_mode->rate
534         * (65536.0/500000.0) / (double)curr_timebase,
535     sample_correction = (int32)(a) & 0xFFFF;
536     sample_increment = (int32)(a) >> 16;
537 }
538
539 static void add_tick(int tick)
540 {
541     int32 samples_to_do;
542     MidiEvent ev;
543
544     samples_to_do = sample_increment * tick;
545     sample_cum += sample_correction * tick;
546     if(sample_cum & 0xFFFF0000)
547     {
548         samples_to_do += ((sample_cum >> 16) & 0xFFFF);
549         sample_cum &= 0x0000FFFF;
550     }
551     curr_event_samples += samples_to_do;
552     curr_tick += tick;
553     ev.type = ME_NONE;
554     seq_play_event(&ev);
555 }
556
557 static int tick2sample(int tick)
558 {
559     int32 samples, cum;
560
561     samples = sample_increment * tick;
562     cum = sample_correction * tick;
563     if(cum & 0xFFFF0000)
564         samples += ((sample_cum >> 16) & 0xFFFF);
565     return samples;
566 }
567
568 int time2tick(double sec)
569 {
570     return (int)(sec * curr_timebase);
571 }
572
573
574 static void stop_playing(void)
575 {
576     if(upper_voices)
577     {
578         MidiEvent ev;
579         ev.type = ME_EOT;
580         ev.a = 0;
581         ev.b = 0;
582         seq_play_event(&ev);
583         aq_flush(0);
584     }
585 }
586
587 static int do_control_command(void);
588 static int do_control_command_nonblock(void);
589 static int do_sequencer(void);
590 static void do_chn_voice(uint8 *);
591 static void do_chn_common(uint8 *);
592 static void do_timing(uint8 *);
593 static void do_sysex(uint8 *, int len);
594 static void do_extended(uint8 *);
595 static void do_timeout(void);
596 static void server_seq_sync(double tm);
597
598 static uint8 data_buffer[BUFSIZ];
599 static int data_buffer_len;
600
601 static void doit(void)
602 {
603     memset(&control_fd_buffer, 0, sizeof(control_fd_buffer));
604     control_fd_buffer.fd = control_fd;
605
606     send_status(220, "TiMidity++ v%s ready", timidity_version);
607
608 /*    while(data_fd != -1 && control_fd != -1) */
609     while(control_fd != -1)
610     {
611         fd_set fds;
612         int n, maxfd;
613
614         if(data_fd == -1)
615         {
616             if(do_control_command())
617                 break;
618         }
619         else
620         {
621             long usec;
622
623             FD_ZERO(&fds);
624             FD_SET(control_fd, &fds);
625             FD_SET(data_fd, &fds);
626             if(control_fd > data_fd)
627                 maxfd = control_fd;
628             else
629                 maxfd = data_fd;
630
631             if(data_fd != -1)
632             {
633                     double wait_time;
634                     int32 filled;
635
636                     filled = aq_filled();
637                     if(!tmr_running && filled <= 0)
638                         usec = -1;
639                     else
640                     {
641                         wait_time = (double)filled / play_mode->rate
642                             - low_time_at;
643                         if(wait_time <= 0)
644                             usec = 0;
645                         else
646                             usec = (long)(wait_time * 1000000);
647                     }
648             }
649             else
650                 usec = -1;
651
652             if(usec >= 0)
653             {
654                 struct timeval timeout;
655                 timeout.tv_sec = usec / 1000000;
656                 timeout.tv_usec = usec % 1000000;
657                 n = select(maxfd + 1, &fds, NULL, NULL, &timeout);
658             }
659             else
660                 n = select(maxfd + 1, &fds, NULL, NULL, NULL);
661
662             if(n < 0)
663             {
664                 perror("select");
665                 break;
666             }
667
668             if(n == 0)
669             {
670                 if(ctl.verbosity >= VERB_DEBUG)
671                 {
672                     putchar(',');
673                     fflush(stdout);
674                 }
675                 do_timeout();
676                 continue;
677             }
678
679             if(control_fd != -1 && FD_ISSET(control_fd, &fds))
680             {
681                 if(do_control_command())
682                 {
683                     close(control_fd);
684                     control_fd = -1;
685                 }
686             }
687             else if(data_fd != -1 && FD_ISSET(data_fd, &fds))
688             {
689                 if(do_sequencer())
690                 {
691                     close(data_fd);
692                     data_fd = -1;
693                     send_status(403, "Data connection is closed");
694                 }
695             }
696         }
697     }
698
699     if(data_fd != -1)
700         stop_playing();
701 }
702
703 static void do_timeout(void)
704 {
705     double fill_time;
706
707     if(data_fd == -1 || !IS_STREAM_TRACE)
708         return;
709     aq_add(NULL, 0);
710     fill_time = high_time_at - (double)aq_filled() / play_mode->rate;
711     if(fill_time <= 0)
712         return;
713
714     if(tmr_running)
715         add_tick(time2tick(fill_time));
716     else
717     {
718         MidiEvent ev;
719         event_time_offset += (int32)(fill_time *
720                                      play_mode->rate);
721         ev.time = curr_event_samples + event_time_offset;
722         ev.type = ME_NONE;
723         play_event(&ev);
724     }
725 }
726
727 /* -1=error, 0=success, 1=connection-closed */
728 static int data_flush(int discard)
729 {
730     fd_set fds;
731     char buff[BUFSIZ];
732     struct timeval timeout;
733     int n;
734
735     while(1)
736     {
737         FD_ZERO(&fds);
738         FD_SET(data_fd, &fds);
739         timeout.tv_sec = 0;
740         if(discard)
741             timeout.tv_usec = 100000;
742         else
743             timeout.tv_usec = 0;
744         if((n = select(data_fd + 1, &fds, NULL, NULL, &timeout)) < 0)
745         {
746             perror("select");
747             return -1;
748         }
749         if(n == 0)
750             break;
751         if(discard)
752         {
753             if((n = read(data_fd, buff, sizeof(buff))) < 0)
754             {
755                 perror("read");
756                 return -1;
757             }
758             if(n == 0)
759                 return 1;
760         }
761         else
762         {
763             int status;
764             if((status = do_sequencer()) != 0)
765                 return status;
766         }
767     }
768     return 0;
769 }
770
771 static void server_seq_sync(double tm)
772 {
773     double t;
774     aq_soft_flush();
775     t = (double)aq_filled() / play_mode->rate;
776     if(t > tm)
777         usleep((unsigned long)((t - tm) * 1000000));
778 }
779
780 static void server_reset(void)
781 {
782     playmidi_stream_init();
783     if(free_instruments_afterwards)
784         free_instruments(0);
785     data_buffer_len = 0;
786     do_sysex(NULL, 0); /* Initialize SysEx buffer */
787     low_time_at = DEFAULT_LOW_TIMEAT;
788     high_time_at = DEFAULT_HIGH_TIMEAT;
789     reduce_voice_threshold = 0; /* Disable auto reduction voice */
790     compute_sample_increment();
791     tmr_reset();
792     tmr_running = 0;
793     start_time = get_current_calender_time();
794 }
795
796 /* -1=error, 0=success, 1=connection-closed */
797 static int do_control_command(void)
798 {
799     int status;
800     char *params[MAX_GETCMD_PARAMS];
801     int nparams;
802     int i;
803
804     if((status = control_getcmd(params, &nparams)) == -1)
805         return -1;
806     if(status == 1)
807     {
808         send_status(500, "Error");
809         return 1;
810     }
811
812     if(nparams == 0 ||  *params == NULL || **params == '\0')
813         return 0;
814
815     for(i = 0; cmd_table[i].cmd; i++)
816         if(strcasecmp(params[0], cmd_table[i].cmd) == 0)
817         {
818             if(nparams < cmd_table[i].minarg)
819                 return send_status(501, "'%s': Arguments is too few",
820                                    params[0]);
821             if(nparams > cmd_table[i].maxarg)
822                 return send_status(501, "'%s': Arguments is too many",
823                                    params[0]);
824             return cmd_table[i].proc(nparams, params);
825         }
826     return send_status(500, "'%s': command not understood.", params[0]);
827 }
828
829 static int cmd_help(int argc, char **argv)
830 {
831     int i;
832
833     if(send_status(200, "Help ok"))
834         return -1;
835
836     for(i = 0; cmd_table[i].cmd; i++)
837     {
838         if(fdputs(cmd_table[i].help, control_fd))
839             return -1;
840         if(fdputs("\n", control_fd))
841             return -1;
842     }
843     return fdputs(".\n", control_fd);
844 }
845
846 static int cmd_open(int argc, char **argv)
847 {
848     int sock;
849     struct sockaddr_in in;
850     int addrlen;
851     int port;
852
853     if(data_fd != -1)
854         return send_status(125, "Data connection is already opened");
855
856     if(strcasecmp(argv[1], "lsb") == 0)
857         is_lsb_data = 1;
858     else if(strcasecmp(argv[1], "msb") == 0)
859         is_lsb_data = 0;
860     else
861         return send_status(502, "OPEN: Invalid argument: %s", argv[1]);
862
863     port = data_port;
864     if((sock = pasv_open(&port)) == -1)
865         return send_status(511, "Can't open data connection");
866
867     addrlen = sizeof(in);
868     memset(&in, 0, addrlen);
869     send_status(200, "%d is ready acceptable", port);
870
871     alarm(SIG_TIMEOUT_SEC);
872     data_fd = accept(sock, (struct sockaddr *)&in, &addrlen);
873     alarm(0);
874
875     if(data_fd < 0)
876     {
877         send_status(512, "Accept error");
878         close(sock);
879         return 0;
880     }
881     close(sock);
882
883     if(control_client.sin_addr.s_addr != in.sin_addr.s_addr)
884         return send_status(513, "Security violation:  Address mismatch");
885
886     send_status(200, "Ready data connection");
887     data_buffer_len = 0;
888     do_sysex(NULL, 0); /* Initialize SysEx buffer */
889     tmr_reset();
890
891     return 0;
892 }
893
894 static int cmd_close(int argc, char **argv)
895 {
896     if(data_fd != -1)
897     {
898         close(data_fd);
899         data_fd = -1;
900         return send_status(302, "Data connection is closed");
901     }
902     return send_status(302, "Data connection is already closed");
903 }
904
905 static int cmd_queue(int argc, char **argv)
906 {
907     int32 qsamples;
908
909     aq_add(NULL, 0); /* Update software queue */
910     if(!aq_fill_buffer_flag)
911         qsamples = aq_soft_filled() + aq_filled();
912     else
913         qsamples = 0;
914     return send_status(200, "%f sec", (double)qsamples / play_mode->rate);
915 }
916
917 static int cmd_maxqueue(int argc, char **argv)
918 {
919     return send_status(200, "%f sec",
920                        (double)aq_get_dev_queuesize() / play_mode->rate);
921 }
922
923 static int cmd_time(int argc, char **argv)
924 {
925     return send_status(200, "%f sec", (double)aq_samples());
926 }
927
928 static int cmd_quit(int argc, char **argv)
929 {
930     send_status(200, "Bye");
931     return 1;
932 }
933
934 static int cmd_timebase(int argc, char **argv)
935 {
936     int i;
937
938     if(argc == 1)
939         return send_status(200, "%d OK", curr_timebase);
940     i = atoi(argv[1]);
941     if(i < 1)
942         i = 1;
943     else if(i > 1000)
944         i = 1000;
945     if(i != curr_timebase)
946     {
947         curr_timebase = i;
948         compute_sample_increment();
949         tick_offs = curr_tick;
950         start_time = get_current_calender_time();
951     }
952     return send_status(200, "OK");
953 }
954
955 static int cmd_patch(int argc, char **argv)
956 {
957     int dr, bank, prog;
958
959     if(strcasecmp(argv[1], "drumset") == 0)
960         dr = 1;
961     else if(strcasecmp(argv[1], "bank") == 0)
962         dr = 0;
963     else
964         return send_status(502, "PATCH: Invalid argument: %s", argv[1]); 
965
966     bank = atoi(argv[2]);
967     prog = atoi(argv[3]);
968     if(bank < 0 || bank > 127 || prog < 0 || prog > 127)
969         return send_status(502, "PATCH: Invalid argument"); 
970     if(play_midi_load_instrument(dr, bank, prog) == NULL)
971         return send_status(514, "PATCH: Can't load the patch");
972     return send_status(200, "OK");
973 }
974
975 static int cmd_reset(int argc, char **argv)
976 {
977     int status;
978
979     if(data_fd >= 0)
980     {
981         stop_playing();
982         if((status = data_flush(1)) != 0)
983             return status;
984     }
985     server_reset();
986     return send_status(200, "OK");
987 }
988
989 static int cmd_autoreduce(int argc, char **argv)
990 {
991     if(strcasecmp(argv[1], "on") == 0)
992     {
993         if(argc == 3)
994             reduce_voice_threshold = atoi(argv[2]);
995         else
996             reduce_voice_threshold = -1;
997     }
998     else if(strcasecmp(argv[1], "off") == 0)
999         reduce_voice_threshold = 0;
1000     else
1001         return send_status(502, "AUTOREDUCE: Invalid argument: %s",
1002                            argv[1]);
1003     return send_status(200, "OK");
1004 }
1005
1006 static int cmd_setbuf(int argc, char **argv)
1007 {
1008     low_time_at = atof(argv[1]);
1009     high_time_at = atof(argv[1]);
1010     return send_status(200, "OK");
1011 }
1012
1013 static int cmd_nop(int argc, char **argv)
1014 {
1015     return send_status(200, "NOP OK");
1016 }
1017
1018 static int do_control_command_nonblock(void)
1019 {
1020     struct timeval timeout;
1021     int n;
1022     fd_set fds;
1023
1024     if(control_fd == -1)
1025         return 1;
1026     FD_ZERO(&fds);
1027     FD_SET(control_fd, &fds);
1028     timeout.tv_sec = 0;
1029     timeout.tv_usec = 0;
1030     n = select(control_fd + 1, &fds, NULL, NULL, &timeout);
1031     if(n > 0 && FD_ISSET(control_fd, &fds))
1032         return do_control_command();
1033     return 0;
1034 }
1035
1036 static int fdgets(char *buff, size_t buff_size, struct fd_read_buffer *p)
1037 {
1038     int n, len, count, size, fd;
1039     char *buff_endp = buff + buff_size - 1, *pbuff, *beg;
1040
1041     fd = p->fd;
1042     if(buff_size == 0)
1043         return 0;
1044     else if(buff_size == 1) /* buff == buff_endp */
1045     {
1046         *buff = '\0';
1047         return 0;
1048     }
1049
1050     len = 0;
1051     count = p->count;
1052     size = p->size;
1053     pbuff = p->buff;
1054     beg = buff;
1055     do
1056     {
1057         if(count == size)
1058         {
1059             if((n = read(fd, pbuff, BUFSIZ)) <= 0)
1060             {
1061                 *buff = '\0';
1062                 if(n == 0)
1063                 {
1064                     p->count = p->size = 0;
1065                     return buff - beg;
1066                 }
1067                 return -1; /* < 0 error */
1068             }
1069             count = p->count = 0;
1070             size = p->size = n;
1071         }
1072         *buff++ = pbuff[count++];
1073     } while(*(buff - 1) != '\n' && buff != buff_endp);
1074     *buff = '\0';
1075     p->count = count;
1076     return buff - beg;
1077 }
1078
1079 static int fdputs(char *s, int fd)
1080 {
1081     if(write(fd, s, strlen(s)) == -1)
1082         return -1;
1083     return 0;
1084 }
1085
1086 #ifdef LITTLE_ENDIAN
1087 static uint32 data2long(uint8* data)
1088 {
1089     uint32 x;
1090     memcpy(&x, data, sizeof(x));
1091     if(!is_lsb_data)
1092         x = XCHG_LONG(x);
1093     return x;
1094 }
1095 static uint16 data2short(uint8* data)
1096 {
1097     uint16 x;
1098     memcpy(&x, data, sizeof(x));
1099     if(!is_lsb_data)
1100         x = XCHG_SHORT(x);
1101     return x;
1102 }
1103 #else
1104 static uint32 data2long(uint8* data)
1105 {
1106     uint32 x;
1107     memcpy(&x, data, sizeof(x));
1108     if(is_lsb_data)
1109         x = XCHG_LONG(x);
1110     return x;
1111 }
1112 static uint16 data2short(uint8* data)
1113 {
1114     uint16 x;
1115     memcpy(&x, data, sizeof(x));
1116     if(is_lsb_data)
1117         x = XCHG_SHORT(x);
1118     return x;
1119 }
1120 #endif
1121
1122 static int do_sequencer(void)
1123 {
1124     int n, offset;
1125     MidiEvent ev;
1126
1127     n = read(data_fd, data_buffer + data_buffer_len,
1128              sizeof(data_buffer) - data_buffer_len);
1129
1130     if(n <= 0)
1131     {
1132         stop_playing();
1133         return n;
1134     }
1135
1136 #ifdef DEBUG_DUMP_SEQ
1137     {
1138         int i;
1139         for(i = 0; i < n; i++)
1140             printf("%02x", data_buffer[data_buffer_len + i]);
1141         putchar('\n');
1142     }
1143 #endif /* DEBUG_DUMP_SEQ */
1144
1145     data_buffer_len += n;
1146     offset = 0;
1147     while(offset < data_buffer_len)
1148     {
1149         int cmd;
1150         cmd = data_buffer[offset];
1151
1152 #define READ_NEEDBUF(x) if(offset + x > data_buffer_len) goto done;
1153 #define READ_ADVBUF(x)  offset += x;
1154         switch(cmd)
1155         {
1156           case EV_CHN_VOICE:
1157             READ_NEEDBUF(8);
1158             do_chn_voice(data_buffer + offset);
1159             READ_ADVBUF(8);
1160             break;
1161           case EV_CHN_COMMON:
1162             READ_NEEDBUF(8);
1163             do_chn_common(data_buffer + offset);
1164             READ_ADVBUF(8);
1165             break;
1166           case EV_TIMING:
1167             READ_NEEDBUF(8);
1168             do_timing(data_buffer + offset);
1169             READ_ADVBUF(8);
1170             break;
1171           case EV_SYSEX:
1172             READ_NEEDBUF(8);
1173             do_sysex(data_buffer + offset + 2, 6);
1174             READ_ADVBUF(8);
1175             break;
1176           case SEQ_MIDIPUTC:
1177             if(is_system_prefix)
1178             {
1179                 READ_NEEDBUF(4);
1180                 do_sysex(data_buffer + offset + 1, 1);
1181                 if(data_buffer[offset + 1] == 0xf7)
1182                     is_system_prefix = 0;  /* End SysEX */
1183                 READ_ADVBUF(4);
1184                 break;
1185             }
1186             READ_NEEDBUF(2);
1187             switch(data_buffer[offset + 1] & 0xf0)
1188             {
1189               case MIDI_NOTEON:
1190                 READ_NEEDBUF(12);
1191                 ev.channel = data_buffer[offset + 1] & 0x0f;
1192                 ev.a       = data_buffer[offset + 5] & 0x7f;
1193                 ev.b       = data_buffer[offset + 9] & 0x7f;
1194                 if(ev.b != 0)
1195                     ev.type = ME_NOTEON;
1196                 else
1197                     ev.type = ME_NOTEOFF;
1198                 seq_play_event(&ev);
1199                 READ_ADVBUF(12);
1200                 break;
1201
1202               case MIDI_NOTEOFF:
1203                 READ_NEEDBUF(12);
1204                 ev.type    = ME_NOTEOFF;
1205                 ev.channel = data_buffer[offset + 1] & 0x0f;
1206                 ev.a       = data_buffer[offset + 5] & 0x7f;
1207                 ev.b       = data_buffer[offset + 9] & 0x7f;
1208                 seq_play_event(&ev);
1209                 READ_ADVBUF(12);
1210                 break;
1211
1212               case MIDI_KEY_PRESSURE:
1213                 READ_NEEDBUF(12);
1214                 ev.type    = ME_KEYPRESSURE;
1215                 ev.channel = data_buffer[offset + 1] & 0x0f;
1216                 ev.a       = data_buffer[offset + 5] & 0x7f;
1217                 ev.b       = data_buffer[offset + 9] & 0x7f;
1218                 seq_play_event(&ev);
1219                 READ_ADVBUF(12);
1220                 break;
1221
1222               case MIDI_CTL_CHANGE:
1223                 READ_NEEDBUF(12);
1224                 if(convert_midi_control_change(data_buffer[offset + 1] & 0x0f,
1225                                                data_buffer[offset + 5],
1226                                                data_buffer[offset + 9],
1227                                                &ev))
1228                     seq_play_event(&ev);
1229                 READ_ADVBUF(12);
1230                 break;
1231
1232               case MIDI_PGM_CHANGE:
1233                 READ_NEEDBUF(8);
1234                 ev.type    = ME_PROGRAM;
1235                 ev.channel = data_buffer[offset + 1] & 0x0f;
1236                 ev.a       = data_buffer[offset + 5] & 0x7f;
1237                 ev.b       = 0;
1238                 seq_play_event(&ev);
1239                 READ_ADVBUF(8);
1240                 break;
1241
1242               case MIDI_CHN_PRESSURE:
1243                 READ_NEEDBUF(8);
1244                 ev.type    = ME_CHANNEL_PRESSURE;
1245                 ev.channel = data_buffer[offset + 1] & 0x0f;
1246                 ev.a       = data_buffer[offset + 5] & 0x7f;
1247                 ev.b       = 0;
1248                 seq_play_event(&ev);
1249                 READ_ADVBUF(8);
1250                 break;
1251
1252               case MIDI_PITCH_BEND:
1253                 READ_NEEDBUF(12);
1254                 ev.type    = ME_PITCHWHEEL;
1255                 ev.channel = data_buffer[offset + 1] & 0x0f;
1256                 ev.a       = data_buffer[offset + 5] & 0x7f;
1257                 ev.b       = data_buffer[offset + 9] & 0x7f;
1258                 seq_play_event(&ev);
1259                 READ_ADVBUF(12);
1260                 break;
1261
1262               case MIDI_SYSTEM_PREFIX:
1263                 READ_NEEDBUF(4);
1264                 do_sysex(data_buffer + offset + 1, 1);
1265                 is_system_prefix = 1; /* Start SysEX */
1266                 READ_ADVBUF(4);
1267                 break;
1268
1269               default:
1270                 ctl.cmsg(CMSG_ERROR, VERB_NORMAL,
1271                          "Undefined SEQ_MIDIPUTC 0x%02x",
1272                          data_buffer[offset + 1]);
1273                 send_status(402, "Undefined SEQ_MIDIPUTC 0x%02x",
1274                             data_buffer[offset + 1]);
1275                 return 1;
1276             }
1277             break;
1278
1279           case SEQ_FULLSIZE:
1280             /* WARNING: This data may be devided into some socket fragments. */
1281             offset = data_buffer_len;
1282             ctl.cmsg(CMSG_WARNING, VERB_NORMAL,
1283                      "SEQ_FULLSIZE is received.  This command is not safety.");
1284             break;
1285
1286           case SEQ_EXTENDED:
1287             READ_NEEDBUF(8);
1288             do_extended(data_buffer + offset);
1289             READ_ADVBUF(8);
1290             break;
1291
1292           case EV_SEQ_LOCAL:
1293           case SEQ_PRIVATE:
1294             READ_NEEDBUF(8);
1295             /* Ignore */
1296             READ_ADVBUF(8);
1297             break;
1298
1299           default:
1300             ctl.cmsg(CMSG_ERROR, VERB_NORMAL,
1301                      "Undefined data 0x%02x", data_buffer[offset - 1]);
1302             send_status(401, "Wrong data is recieved (seqcmd=0x%02x)",
1303                         cmd);
1304             stop_playing();
1305             return 1;
1306         }
1307 #undef READ_NEEDBUF
1308 #undef READ_ADVBUF
1309     }
1310
1311   done:
1312     if(offset)
1313     {
1314         data_buffer_len -= offset;
1315         memmove(data_buffer, data_buffer + offset, data_buffer_len);
1316     }
1317     return 0;
1318 }
1319
1320
1321 static void do_chn_voice(uint8 *data)
1322 {
1323     int type, chn, note, parm;
1324     MidiEvent ev;
1325
1326     type = data[2];
1327     chn  = data[3] % MAX_CHANNELS;
1328     note = data[4] & 0x7f;
1329     parm = data[5] & 0x7f;
1330
1331     ev.channel = chn;
1332     ev.a       = note;
1333     ev.b       = parm;
1334     switch(type)
1335     {
1336       case MIDI_NOTEON:
1337         if(parm > 0)
1338         {
1339             ev.type = ME_NOTEON;
1340             seq_play_event(&ev);
1341             break;
1342         }
1343         /* FALLTHROUGH */
1344       case MIDI_NOTEOFF:
1345         ev.type = ME_NOTEOFF;
1346         seq_play_event(&ev);
1347         break;
1348       case MIDI_KEY_PRESSURE:
1349         ev.type = ME_KEYPRESSURE;
1350         seq_play_event(&ev);
1351         break;
1352     }
1353 }
1354
1355 static void do_chn_common(uint8 *data)
1356 {
1357     int type, chn, p1, p2, w14;
1358     MidiEvent ev;
1359
1360     type = data[2];
1361     chn  = data[3] % MAX_CHANNELS;
1362     p1 = data[4] & 0x7f;
1363     p2 = data[5] & 0x7f;
1364     w14 = data2short(data + 6) & 0x3fff;
1365
1366     if(type == 0xff) /* Meta event */
1367     {
1368         /* This event is special event for timidity.  (not OSS compatible) */
1369         switch(data[3])
1370         {
1371           case 0x2f: /* End of midi */
1372             stop_playing();
1373             tmr_reset();
1374             break;
1375
1376           case 0x7f: /* Sequencer-Specific Meta-Event */
1377             switch(data[4])
1378             {
1379               case 0x01: /* MIDI Reset */
1380                 ev.type = ME_RESET;
1381                 ev.a = DEFAULT_SYSTEM_MODE;
1382                 ev.b = 0;
1383                 seq_play_event(&ev);
1384                 break;
1385
1386               case 0x02:  { /* Used to sync. */
1387                     double target_time, queue_time, sleep_time;
1388                     if(w14 == 0)
1389                     {
1390                         aq_flush(0); /* wait until playout */
1391                         send_status(301, "0 Sync OK");
1392                         break;
1393                     }
1394
1395                     aq_soft_flush();
1396                     target_time = (double)w14 / curr_timebase;
1397                     queue_time = (double)aq_filled() / play_mode->rate;
1398                     sleep_time = queue_time - target_time;
1399                     if(sleep_time > 0)
1400                     {
1401                         send_status(301, "%g Sync OK", sleep_time);
1402                         usleep((unsigned long)(sleep_time * 1000000));
1403                     }
1404                     else
1405                         send_status(301, "0 Sync OK");
1406                 }
1407                 break;
1408             }
1409         }
1410         return;
1411     }
1412
1413     ev.channel = chn;
1414     switch(type)
1415     {
1416       case MIDI_CTL_CHANGE:
1417         if(convert_midi_control_change(chn, p1, w14, &ev))
1418             seq_play_event(&ev);
1419         break;
1420       case MIDI_PGM_CHANGE:
1421         ev.type = ME_PROGRAM;
1422         ev.a    = p1;
1423         ev.b    = 0;
1424         seq_play_event(&ev);
1425         break;
1426       case MIDI_CHN_PRESSURE:
1427         ev.type = ME_CHANNEL_PRESSURE;
1428         ev.a    = p1;
1429         ev.b    = p2;
1430         seq_play_event(&ev);
1431         break;
1432       case MIDI_PITCH_BEND:
1433         ev.type = ME_PITCHWHEEL;
1434         ev.a    = w14 & 0x7f;
1435         ev.b    = (w14>>7) & 0x7f;
1436         seq_play_event(&ev);
1437         break;
1438     }
1439 }
1440
1441
1442 static void do_timing(uint8 *data)
1443 {
1444     int32 val;
1445
1446     val = data2long(data + 4);
1447     switch(data[1])
1448     {
1449       case TMR_START:
1450         tmr_running = 1;
1451         tmr_reset();
1452         event_time_offset = (int32)(play_mode->rate * high_time_at);
1453         break;
1454
1455       case TMR_STOP:
1456         tmr_running = 0;
1457         break;
1458
1459       case TMR_CONTINUE:
1460         if(!tmr_running)
1461         {
1462             tmr_running = 1;
1463             tick_offs = curr_tick;
1464             start_time = get_current_calender_time();
1465         }
1466         break;
1467
1468       case TMR_TEMPO:
1469 #if 0 /* What should TMR_TEMPO work ? */
1470         if(val < 8)
1471             val = 8;
1472         else if(val > 250)
1473             val = 250;
1474         current_play_tempo = 60 * 1000000 / val;
1475         compute_sample_increment();
1476 #endif
1477         break;
1478
1479       case TMR_WAIT_ABS:
1480
1481 /*
1482    printf("## TMR_WAIT_ABS: %d %d %d %g\n",
1483        curr_tick,
1484        curr_tick - (time2tick(get_current_calender_time()
1485                               - start_time) + tick_offs),
1486        event_time_offset,
1487        (double)aq_filled() / play_mode->rate);
1488  */
1489
1490         val -= curr_tick;
1491         /*FALLTHROUGH*/
1492       case TMR_WAIT_REL:
1493         if(val <= 0)
1494             break;
1495         add_tick(val);
1496         break;
1497
1498 #if 0
1499       case TMR_ECHO:
1500       case TMR_SPP:
1501 #endif
1502       default:
1503 /* printf("## TMR=0x%02x is not supported\n", data[1]); */
1504         break;
1505     }
1506 }
1507
1508
1509 static void do_sysex(uint8 *data, int n)
1510 {
1511     static uint8 sysexbuf[BUFSIZ];
1512     static int buflen;
1513     static int fillflag;
1514     int i;
1515
1516     if(data == NULL)
1517     {
1518         buflen = fillflag = 0;
1519         is_system_prefix = 0;
1520         return;
1521     }
1522
1523     for(i = 0; i < n; i++)
1524     {
1525         /* SysEx := /\xf0([^\xf7]*\xf7)/ */
1526         if(!fillflag)
1527         {
1528             if(data[i] == 0xf0)
1529             {
1530                 fillflag = 1;
1531                 continue;
1532             }
1533         }
1534         if(fillflag)
1535         {
1536             if(buflen < sizeof(sysexbuf))
1537                 sysexbuf[buflen++] = data[i];
1538             if(data[i] == 0xf7)
1539             {
1540                 MidiEvent ev;
1541                 if(parse_sysex_event(sysexbuf, buflen, &ev))
1542                     seq_play_event(&ev);
1543                 buflen = 0;
1544                 fillflag = 0;
1545             }
1546         }
1547     }
1548 }
1549
1550 static void do_extended(uint8 *data)
1551 {
1552     int value;
1553     MidiEvent ev;
1554
1555     value = data[5] | data[6] * 256;
1556     switch(data[1])
1557     {
1558       case SEQ_CONTROLLER:
1559         switch(data[4])
1560         {
1561           case CTRL_PITCH_BENDER: /* ?? */
1562             break;
1563           case CTRL_PITCH_BENDER_RANGE: /* ?? */
1564             ev.channel = data[3] % MAX_CHANNELS;
1565             ev.b = 0;
1566             ev.a = 0;
1567
1568             /* LSB */
1569             ev.type = ME_NRPN_LSB;
1570             seq_play_event(&ev);
1571
1572             /* MSB */
1573             ev.type = ME_NRPN_MSB;
1574             seq_play_event(&ev);
1575
1576             /* Data entry */
1577             ev.type = ME_DATA_ENTRY_MSB;
1578             ev.a = value / 100; /* ?? */
1579             seq_play_event(&ev);
1580
1581             break;
1582           default:
1583             break;
1584         }
1585         break;
1586       default:
1587         break;
1588     }
1589 }
1590
1591
1592 /*
1593  * interface_<id>_loader();
1594  */
1595 ControlMode *interface_r_loader(void)
1596 {
1597     return &ctl;
1598 }