Update Fluidsynth to 2.0.1
[ardour.git] / libs / fluidsynth / src / fluid_midi.c
1 /* FluidSynth - A Software Synthesizer
2  *
3  * Copyright (C) 2003  Peter Hanappe and others.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public License
7  * as published by the Free Software Foundation; either version 2.1 of
8  * the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free
17  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18  * 02110-1301, USA
19  */
20
21 #include "fluid_midi.h"
22 #include "fluid_sys.h"
23 #include "fluid_synth.h"
24 #include "fluid_settings.h"
25
26
27 static int fluid_midi_event_length(unsigned char event);
28 static int fluid_isasciistring(char *s);
29 static long fluid_getlength(unsigned char *s);
30
31
32 /* Read the entire contents of a file into memory, allocating enough memory
33  * for the file, and returning the length and the buffer.
34  * Note: This rewinds the file to the start before reading.
35  * Returns NULL if there was an error reading or allocating memory.
36  */
37 static char *fluid_file_read_full(fluid_file fp, size_t *length);
38 static void fluid_midi_event_set_sysex_LOCAL(fluid_midi_event_t *evt, int type, void *data, int size, int dynamic);
39 #define READ_FULL_INITIAL_BUFLEN 1024
40
41 static fluid_track_t *new_fluid_track(int num);
42 static void delete_fluid_track(fluid_track_t *track);
43 static int fluid_track_set_name(fluid_track_t *track, char *name);
44 static int fluid_track_add_event(fluid_track_t *track, fluid_midi_event_t *evt);
45 static fluid_midi_event_t *fluid_track_next_event(fluid_track_t *track);
46 static int fluid_track_get_duration(fluid_track_t *track);
47 static int fluid_track_reset(fluid_track_t *track);
48
49 static int fluid_track_send_events(fluid_track_t *track,
50                                    fluid_synth_t *synth,
51                                    fluid_player_t *player,
52                                    unsigned int ticks);
53
54
55 static int fluid_player_add_track(fluid_player_t *player, fluid_track_t *track);
56 static int fluid_player_callback(void *data, unsigned int msec);
57 static int fluid_player_reset(fluid_player_t *player);
58 static int fluid_player_load(fluid_player_t *player, fluid_playlist_item *item);
59 static void fluid_player_advancefile(fluid_player_t *player);
60 static void fluid_player_playlist_load(fluid_player_t *player, unsigned int msec);
61
62 static fluid_midi_file *new_fluid_midi_file(const char *buffer, size_t length);
63 static void delete_fluid_midi_file(fluid_midi_file *mf);
64 static int fluid_midi_file_read_mthd(fluid_midi_file *midifile);
65 static int fluid_midi_file_load_tracks(fluid_midi_file *midifile, fluid_player_t *player);
66 static int fluid_midi_file_read_track(fluid_midi_file *mf, fluid_player_t *player, int num);
67 static int fluid_midi_file_read_event(fluid_midi_file *mf, fluid_track_t *track);
68 static int fluid_midi_file_read_varlen(fluid_midi_file *mf);
69 static int fluid_midi_file_getc(fluid_midi_file *mf);
70 static int fluid_midi_file_push(fluid_midi_file *mf, int c);
71 static int fluid_midi_file_read(fluid_midi_file *mf, void *buf, int len);
72 static int fluid_midi_file_skip(fluid_midi_file *mf, int len);
73 static int fluid_midi_file_eof(fluid_midi_file *mf);
74 static int fluid_midi_file_read_tracklen(fluid_midi_file *mf);
75 static int fluid_midi_file_eot(fluid_midi_file *mf);
76 static int fluid_midi_file_get_division(fluid_midi_file *midifile);
77
78 #if 0 // disable file I/O with Ardour
79 /***************************************************************
80  *
81  *                      MIDIFILE
82  */
83
84 /**
85  * Return a new MIDI file handle for parsing an already-loaded MIDI file.
86  * @internal
87  * @param buffer Pointer to full contents of MIDI file (borrows the pointer).
88  *  The caller must not free buffer until after the fluid_midi_file is deleted.
89  * @param length Size of the buffer in bytes.
90  * @return New MIDI file handle or NULL on error.
91  */
92 fluid_midi_file *
93 new_fluid_midi_file(const char *buffer, size_t length)
94 {
95     fluid_midi_file *mf;
96
97     mf = FLUID_NEW(fluid_midi_file);
98
99     if(mf == NULL)
100     {
101         FLUID_LOG(FLUID_ERR, "Out of memory");
102         return NULL;
103     }
104
105     FLUID_MEMSET(mf, 0, sizeof(fluid_midi_file));
106
107     mf->c = -1;
108     mf->running_status = -1;
109
110     mf->buffer = buffer;
111     mf->buf_len = length;
112     mf->buf_pos = 0;
113     mf->eof = FALSE;
114
115     if(fluid_midi_file_read_mthd(mf) != FLUID_OK)
116     {
117         FLUID_FREE(mf);
118         return NULL;
119     }
120
121     return mf;
122 }
123
124 static char *
125 fluid_file_read_full(fluid_file fp, size_t *length)
126 {
127     size_t buflen;
128     char *buffer;
129     size_t n;
130
131     /* Work out the length of the file in advance */
132     if(FLUID_FSEEK(fp, 0, SEEK_END) != 0)
133     {
134         FLUID_LOG(FLUID_ERR, "File load: Could not seek within file");
135         return NULL;
136     }
137
138     buflen = ftell(fp);
139
140     if(FLUID_FSEEK(fp, 0, SEEK_SET) != 0)
141     {
142         FLUID_LOG(FLUID_ERR, "File load: Could not seek within file");
143         return NULL;
144     }
145
146     FLUID_LOG(FLUID_DBG, "File load: Allocating %d bytes", buflen);
147     buffer = FLUID_MALLOC(buflen);
148
149     if(buffer == NULL)
150     {
151         FLUID_LOG(FLUID_PANIC, "Out of memory");
152         return NULL;
153     }
154
155     n = FLUID_FREAD(buffer, 1, buflen, fp);
156
157     if(n != buflen)
158     {
159         FLUID_LOG(FLUID_ERR, "Only read %d bytes; expected %d", n,
160                   buflen);
161         FLUID_FREE(buffer);
162         return NULL;
163     };
164
165     *length = n;
166
167     return buffer;
168 }
169
170 /**
171  * Delete a MIDI file handle.
172  * @internal
173  * @param mf MIDI file handle to close and free.
174  */
175 void
176 delete_fluid_midi_file(fluid_midi_file *mf)
177 {
178     fluid_return_if_fail(mf != NULL);
179
180     FLUID_FREE(mf);
181 }
182
183 /*
184  * Gets the next byte in a MIDI file, taking into account previous running status.
185  *
186  * returns -1 if EOF or read error
187  */
188 int
189 fluid_midi_file_getc(fluid_midi_file *mf)
190 {
191     unsigned char c;
192
193     if(mf->c >= 0)
194     {
195         c = mf->c;
196         mf->c = -1;
197     }
198     else
199     {
200         if(mf->buf_pos >= mf->buf_len)
201         {
202             mf->eof = TRUE;
203             return -1;
204         }
205
206         c = mf->buffer[mf->buf_pos++];
207         mf->trackpos++;
208     }
209
210     return (int) c;
211 }
212
213 /*
214  * Saves a byte to be returned the next time fluid_midi_file_getc() is called,
215  * when it is necessary according to running status.
216  */
217 int
218 fluid_midi_file_push(fluid_midi_file *mf, int c)
219 {
220     mf->c = c;
221     return FLUID_OK;
222 }
223
224 /*
225  * fluid_midi_file_read
226  */
227 int
228 fluid_midi_file_read(fluid_midi_file *mf, void *buf, int len)
229 {
230     int num = len < mf->buf_len - mf->buf_pos
231               ? len : mf->buf_len - mf->buf_pos;
232
233     if(num != len)
234     {
235         mf->eof = TRUE;
236     }
237
238     if(num < 0)
239     {
240         num = 0;
241     }
242
243     /* Note: Read bytes, even if there aren't enough, but only increment
244      * trackpos if successful (emulates old behaviour of fluid_midi_file_read)
245      */
246     FLUID_MEMCPY(buf, mf->buffer + mf->buf_pos, num);
247     mf->buf_pos += num;
248
249     if(num == len)
250     {
251         mf->trackpos += num;
252     }
253
254 #if DEBUG
255     else
256     {
257         FLUID_LOG(FLUID_DBG, "Could not read the requested number of bytes");
258     }
259
260 #endif
261     return (num != len) ? FLUID_FAILED : FLUID_OK;
262 }
263
264 /*
265  * fluid_midi_file_skip
266  */
267 int
268 fluid_midi_file_skip(fluid_midi_file *mf, int skip)
269 {
270     int new_pos = mf->buf_pos + skip;
271
272     /* Mimic the behaviour of fseek: Error to seek past the start of file, but
273      * OK to seek past end (this just puts it into the EOF state). */
274     if(new_pos < 0)
275     {
276         FLUID_LOG(FLUID_ERR, "Failed to seek position in file");
277         return FLUID_FAILED;
278     }
279
280     /* Clear the EOF flag, even if moved past the end of the file (this is
281      * consistent with the behaviour of fseek). */
282     mf->eof = FALSE;
283     mf->buf_pos = new_pos;
284     return FLUID_OK;
285 }
286
287 /*
288  * fluid_midi_file_eof
289  */
290 int fluid_midi_file_eof(fluid_midi_file *mf)
291 {
292     /* Note: This does not simply test whether the file read pointer is past
293      * the end of the file. It mimics the behaviour of feof by actually
294      * testing the stateful EOF condition, which is set to TRUE if getc or
295      * fread have attempted to read past the end (but not if they have
296      * precisely reached the end), but reset to FALSE upon a successful seek.
297      */
298     return mf->eof;
299 }
300
301 /*
302  * fluid_midi_file_read_mthd
303  */
304 int
305 fluid_midi_file_read_mthd(fluid_midi_file *mf)
306 {
307     char mthd[14];
308
309     if(fluid_midi_file_read(mf, mthd, sizeof(mthd)) != FLUID_OK)
310     {
311         return FLUID_FAILED;
312     }
313
314     if((FLUID_STRNCMP(mthd, "MThd", 4) != 0) || (mthd[7] != 6)
315             || (mthd[9] > 2))
316     {
317         FLUID_LOG(FLUID_ERR,
318                   "Doesn't look like a MIDI file: invalid MThd header");
319         return FLUID_FAILED;
320     }
321
322     mf->type = mthd[9];
323     mf->ntracks = (unsigned) mthd[11];
324     mf->ntracks += (unsigned int)(mthd[10]) << 16;
325
326     if((signed char)mthd[12] < 0)
327     {
328         mf->uses_smpte = 1;
329         mf->smpte_fps = -(signed char)mthd[12];
330         mf->smpte_res = (unsigned) mthd[13];
331         FLUID_LOG(FLUID_ERR, "File uses SMPTE timing -- Not implemented yet");
332         return FLUID_FAILED;
333     }
334     else
335     {
336         mf->uses_smpte = 0;
337         mf->division = ((unsigned)mthd[12] << 8) | ((unsigned)mthd[13] & 0xff);
338         FLUID_LOG(FLUID_DBG, "Division=%d", mf->division);
339     }
340
341     return FLUID_OK;
342 }
343
344 /*
345  * fluid_midi_file_load_tracks
346  */
347 int
348 fluid_midi_file_load_tracks(fluid_midi_file *mf, fluid_player_t *player)
349 {
350     int i;
351
352     for(i = 0; i < mf->ntracks; i++)
353     {
354         if(fluid_midi_file_read_track(mf, player, i) != FLUID_OK)
355         {
356             return FLUID_FAILED;
357         }
358     }
359
360     return FLUID_OK;
361 }
362
363 /*
364  * fluid_isasciistring
365  */
366 int
367 fluid_isasciistring(char *s)
368 {
369     /* From ctype.h */
370 #define fluid_isascii(c)    (((c) & ~0x7f) == 0)
371
372     int i;
373     int len = (int) FLUID_STRLEN(s);
374
375     for(i = 0; i < len; i++)
376     {
377         if(!fluid_isascii(s[i]))
378         {
379             return 0;
380         }
381     }
382
383     return 1;
384
385 #undef fluid_isascii
386 }
387
388 /*
389  * fluid_getlength
390  */
391 long
392 fluid_getlength(unsigned char *s)
393 {
394     long i = 0;
395     i = s[3] | (s[2] << 8) | (s[1] << 16) | (s[0] << 24);
396     return i;
397 }
398
399 /*
400  * fluid_midi_file_read_tracklen
401  */
402 int
403 fluid_midi_file_read_tracklen(fluid_midi_file *mf)
404 {
405     unsigned char length[5];
406
407     if(fluid_midi_file_read(mf, length, 4) != FLUID_OK)
408     {
409         return FLUID_FAILED;
410     }
411
412     mf->tracklen = fluid_getlength(length);
413     mf->trackpos = 0;
414     mf->eot = 0;
415     return FLUID_OK;
416 }
417
418 /*
419  * fluid_midi_file_eot
420  */
421 int
422 fluid_midi_file_eot(fluid_midi_file *mf)
423 {
424 #if DEBUG
425
426     if(mf->trackpos > mf->tracklen)
427     {
428         printf("track overrun: %d > %d\n", mf->trackpos, mf->tracklen);
429     }
430
431 #endif
432     return mf->eot || (mf->trackpos >= mf->tracklen);
433 }
434
435 /*
436  * fluid_midi_file_read_track
437  */
438 int
439 fluid_midi_file_read_track(fluid_midi_file *mf, fluid_player_t *player, int num)
440 {
441     fluid_track_t *track;
442     unsigned char id[5], length[5];
443     int found_track = 0;
444     int skip;
445
446     if(fluid_midi_file_read(mf, id, 4) != FLUID_OK)
447     {
448         return FLUID_FAILED;
449     }
450
451     id[4] = '\0';
452     mf->dtime = 0;
453
454     while(!found_track)
455     {
456
457         if(fluid_isasciistring((char *) id) == 0)
458         {
459             FLUID_LOG(FLUID_ERR,
460                       "An non-ascii track header found, corrupt file");
461             return FLUID_FAILED;
462
463         }
464         else if(FLUID_STRCMP((char *) id, "MTrk") == 0)
465         {
466
467             found_track = 1;
468
469             if(fluid_midi_file_read_tracklen(mf) != FLUID_OK)
470             {
471                 return FLUID_FAILED;
472             }
473
474             track = new_fluid_track(num);
475
476             if(track == NULL)
477             {
478                 FLUID_LOG(FLUID_ERR, "Out of memory");
479                 return FLUID_FAILED;
480             }
481
482             while(!fluid_midi_file_eot(mf))
483             {
484                 if(fluid_midi_file_read_event(mf, track) != FLUID_OK)
485                 {
486                     delete_fluid_track(track);
487                     return FLUID_FAILED;
488                 }
489             }
490
491             /* Skip remaining track data, if any */
492             if(mf->trackpos < mf->tracklen)
493             {
494                 if(fluid_midi_file_skip(mf, mf->tracklen - mf->trackpos) != FLUID_OK)
495                 {
496                     delete_fluid_track(track);
497                     return FLUID_FAILED;
498                 }
499             }
500
501             if(fluid_player_add_track(player, track) != FLUID_OK)
502             {
503                 delete_fluid_track(track);
504                 return FLUID_FAILED;
505             }
506
507         }
508         else
509         {
510             found_track = 0;
511
512             if(fluid_midi_file_read(mf, length, 4) != FLUID_OK)
513             {
514                 return FLUID_FAILED;
515             }
516
517             skip = fluid_getlength(length);
518
519             /* fseek(mf->fp, skip, SEEK_CUR); */
520             if(fluid_midi_file_skip(mf, skip) != FLUID_OK)
521             {
522                 return FLUID_FAILED;
523             }
524         }
525     }
526
527     if(fluid_midi_file_eof(mf))
528     {
529         FLUID_LOG(FLUID_ERR, "Unexpected end of file");
530         return FLUID_FAILED;
531     }
532
533     return FLUID_OK;
534 }
535
536 /*
537  * fluid_midi_file_read_varlen
538  */
539 int
540 fluid_midi_file_read_varlen(fluid_midi_file *mf)
541 {
542     int i;
543     int c;
544     mf->varlen = 0;
545
546     for(i = 0;; i++)
547     {
548         if(i == 4)
549         {
550             FLUID_LOG(FLUID_ERR, "Invalid variable length number");
551             return FLUID_FAILED;
552         }
553
554         c = fluid_midi_file_getc(mf);
555
556         if(c < 0)
557         {
558             FLUID_LOG(FLUID_ERR, "Unexpected end of file");
559             return FLUID_FAILED;
560         }
561
562         if(c & 0x80)
563         {
564             mf->varlen |= (int)(c & 0x7F);
565             mf->varlen <<= 7;
566         }
567         else
568         {
569             mf->varlen += c;
570             break;
571         }
572     }
573
574     return FLUID_OK;
575 }
576
577 /*
578  * fluid_midi_file_read_event
579  */
580 int
581 fluid_midi_file_read_event(fluid_midi_file *mf, fluid_track_t *track)
582 {
583     int status;
584     int type;
585     int tempo;
586     unsigned char *metadata = NULL;
587     unsigned char *dyn_buf = NULL;
588     unsigned char static_buf[256];
589     int nominator, denominator, clocks, notes;
590     fluid_midi_event_t *evt;
591     int channel = 0;
592     int param1 = 0;
593     int param2 = 0;
594     int size;
595
596     /* read the delta-time of the event */
597     if(fluid_midi_file_read_varlen(mf) != FLUID_OK)
598     {
599         return FLUID_FAILED;
600     }
601
602     mf->dtime += mf->varlen;
603
604     /* read the status byte */
605     status = fluid_midi_file_getc(mf);
606
607     if(status < 0)
608     {
609         FLUID_LOG(FLUID_ERR, "Unexpected end of file");
610         return FLUID_FAILED;
611     }
612
613     /* not a valid status byte: use the running status instead */
614     if((status & 0x80) == 0)
615     {
616         if((mf->running_status & 0x80) == 0)
617         {
618             FLUID_LOG(FLUID_ERR, "Undefined status and invalid running status");
619             return FLUID_FAILED;
620         }
621
622         fluid_midi_file_push(mf, status);
623         status = mf->running_status;
624     }
625
626     /* check what message we have */
627
628     mf->running_status = status;
629
630     if(status == MIDI_SYSEX)    /* system exclusif */
631     {
632         /* read the length of the message */
633         if(fluid_midi_file_read_varlen(mf) != FLUID_OK)
634         {
635             return FLUID_FAILED;
636         }
637
638         if(mf->varlen)
639         {
640             FLUID_LOG(FLUID_DBG, "%s: %d: alloc metadata, len = %d", __FILE__,
641                       __LINE__, mf->varlen);
642             metadata = FLUID_MALLOC(mf->varlen + 1);
643
644             if(metadata == NULL)
645             {
646                 FLUID_LOG(FLUID_PANIC, "Out of memory");
647                 return FLUID_FAILED;
648             }
649
650             /* read the data of the message */
651             if(fluid_midi_file_read(mf, metadata, mf->varlen) != FLUID_OK)
652             {
653                 FLUID_FREE(metadata);
654                 return FLUID_FAILED;
655             }
656
657             evt = new_fluid_midi_event();
658
659             if(evt == NULL)
660             {
661                 FLUID_LOG(FLUID_ERR, "Out of memory");
662                 FLUID_FREE(metadata);
663                 return FLUID_FAILED;
664             }
665
666             evt->dtime = mf->dtime;
667             size = mf->varlen;
668
669             if(metadata[mf->varlen - 1] == MIDI_EOX)
670             {
671                 size--;
672             }
673
674             /* Add SYSEX event and indicate that its dynamically allocated and should be freed with event */
675             fluid_midi_event_set_sysex(evt, metadata, size, TRUE);
676             fluid_track_add_event(track, evt);
677             mf->dtime = 0;
678         }
679
680         return FLUID_OK;
681
682     }
683     else if(status == MIDI_META_EVENT)      /* meta events */
684     {
685
686         int result = FLUID_OK;
687
688         /* get the type of the meta message */
689         type = fluid_midi_file_getc(mf);
690
691         if(type < 0)
692         {
693             FLUID_LOG(FLUID_ERR, "Unexpected end of file");
694             return FLUID_FAILED;
695         }
696
697         /* get the length of the data part */
698         if(fluid_midi_file_read_varlen(mf) != FLUID_OK)
699         {
700             return FLUID_FAILED;
701         }
702
703         if(mf->varlen < 255)
704         {
705             metadata = &static_buf[0];
706         }
707         else
708         {
709             FLUID_LOG(FLUID_DBG, "%s: %d: alloc metadata, len = %d", __FILE__,
710                       __LINE__, mf->varlen);
711             dyn_buf = FLUID_MALLOC(mf->varlen + 1);
712
713             if(dyn_buf == NULL)
714             {
715                 FLUID_LOG(FLUID_PANIC, "Out of memory");
716                 return FLUID_FAILED;
717             }
718
719             metadata = dyn_buf;
720         }
721
722         /* read the data */
723         if(mf->varlen)
724         {
725             if(fluid_midi_file_read(mf, metadata, mf->varlen) != FLUID_OK)
726             {
727                 if(dyn_buf)
728                 {
729                     FLUID_FREE(dyn_buf);
730                 }
731
732                 return FLUID_FAILED;
733             }
734         }
735
736         /* handle meta data */
737         switch(type)
738         {
739
740         case MIDI_COPYRIGHT:
741             metadata[mf->varlen] = 0;
742             break;
743
744         case MIDI_TRACK_NAME:
745             metadata[mf->varlen] = 0;
746             fluid_track_set_name(track, (char *) metadata);
747             break;
748
749         case MIDI_INST_NAME:
750             metadata[mf->varlen] = 0;
751             break;
752
753         case MIDI_LYRIC:
754         case MIDI_TEXT:
755         {
756             void *tmp;
757             int size = mf->varlen + 1;
758
759             /* NULL terminate strings for safety */
760             metadata[size - 1] = '\0';
761
762             evt = new_fluid_midi_event();
763
764             if(evt == NULL)
765             {
766                 FLUID_LOG(FLUID_ERR, "Out of memory");
767                 result = FLUID_FAILED;
768                 break;
769             }
770
771             evt->dtime = mf->dtime;
772
773             tmp = FLUID_MALLOC(size);
774
775             if(tmp == NULL)
776             {
777                 FLUID_LOG(FLUID_PANIC, "Out of memory");
778                 delete_fluid_midi_event(evt);
779                 evt = NULL;
780                 result = FLUID_FAILED;
781                 break;
782             }
783
784             FLUID_MEMCPY(tmp, metadata, size);
785
786             fluid_midi_event_set_sysex_LOCAL(evt, type, tmp, size, TRUE);
787             fluid_track_add_event(track, evt);
788             mf->dtime = 0;
789         }
790         break;
791
792         case MIDI_MARKER:
793             break;
794
795         case MIDI_CUE_POINT:
796             break; /* don't care much for text events */
797
798         case MIDI_EOT:
799             if(mf->varlen != 0)
800             {
801                 FLUID_LOG(FLUID_ERR, "Invalid length for EndOfTrack event");
802                 result = FLUID_FAILED;
803                 break;
804             }
805
806             mf->eot = 1;
807             evt = new_fluid_midi_event();
808
809             if(evt == NULL)
810             {
811                 FLUID_LOG(FLUID_ERR, "Out of memory");
812                 result = FLUID_FAILED;
813                 break;
814             }
815
816             evt->dtime = mf->dtime;
817             evt->type = MIDI_EOT;
818             fluid_track_add_event(track, evt);
819             mf->dtime = 0;
820             break;
821
822         case MIDI_SET_TEMPO:
823             if(mf->varlen != 3)
824             {
825                 FLUID_LOG(FLUID_ERR,
826                           "Invalid length for SetTempo meta event");
827                 result = FLUID_FAILED;
828                 break;
829             }
830
831             tempo = (metadata[0] << 16) + (metadata[1] << 8) + metadata[2];
832             evt = new_fluid_midi_event();
833
834             if(evt == NULL)
835             {
836                 FLUID_LOG(FLUID_ERR, "Out of memory");
837                 result = FLUID_FAILED;
838                 break;
839             }
840
841             evt->dtime = mf->dtime;
842             evt->type = MIDI_SET_TEMPO;
843             evt->channel = 0;
844             evt->param1 = tempo;
845             evt->param2 = 0;
846             fluid_track_add_event(track, evt);
847             mf->dtime = 0;
848             break;
849
850         case MIDI_SMPTE_OFFSET:
851             if(mf->varlen != 5)
852             {
853                 FLUID_LOG(FLUID_ERR,
854                           "Invalid length for SMPTE Offset meta event");
855                 result = FLUID_FAILED;
856                 break;
857             }
858
859             break; /* we don't use smtp */
860
861         case MIDI_TIME_SIGNATURE:
862             if(mf->varlen != 4)
863             {
864                 FLUID_LOG(FLUID_ERR,
865                           "Invalid length for TimeSignature meta event");
866                 result = FLUID_FAILED;
867                 break;
868             }
869
870             nominator = metadata[0];
871             denominator = pow(2.0, (double) metadata[1]);
872             clocks = metadata[2];
873             notes = metadata[3];
874
875             FLUID_LOG(FLUID_DBG,
876                       "signature=%d/%d, metronome=%d, 32nd-notes=%d",
877                       nominator, denominator, clocks, notes);
878
879             break;
880
881         case MIDI_KEY_SIGNATURE:
882             if(mf->varlen != 2)
883             {
884                 FLUID_LOG(FLUID_ERR,
885                           "Invalid length for KeySignature meta event");
886                 result = FLUID_FAILED;
887                 break;
888             }
889
890             /* We don't care about key signatures anyway */
891             /* sf = metadata[0];
892             mi = metadata[1]; */
893             break;
894
895         case MIDI_SEQUENCER_EVENT:
896             break;
897
898         default:
899             break;
900         }
901
902         if(dyn_buf)
903         {
904             FLUID_LOG(FLUID_DBG, "%s: %d: free metadata", __FILE__, __LINE__);
905             FLUID_FREE(dyn_buf);
906         }
907
908         return result;
909
910     }
911     else     /* channel messages */
912     {
913
914         type = status & 0xf0;
915         channel = status & 0x0f;
916
917         /* all channel message have at least 1 byte of associated data */
918         if((param1 = fluid_midi_file_getc(mf)) < 0)
919         {
920             FLUID_LOG(FLUID_ERR, "Unexpected end of file");
921             return FLUID_FAILED;
922         }
923
924         switch(type)
925         {
926
927         case NOTE_ON:
928             if((param2 = fluid_midi_file_getc(mf)) < 0)
929             {
930                 FLUID_LOG(FLUID_ERR, "Unexpected end of file");
931                 return FLUID_FAILED;
932             }
933
934             break;
935
936         case NOTE_OFF:
937             if((param2 = fluid_midi_file_getc(mf)) < 0)
938             {
939                 FLUID_LOG(FLUID_ERR, "Unexpected end of file");
940                 return FLUID_FAILED;
941             }
942
943             break;
944
945         case KEY_PRESSURE:
946             if((param2 = fluid_midi_file_getc(mf)) < 0)
947             {
948                 FLUID_LOG(FLUID_ERR, "Unexpected end of file");
949                 return FLUID_FAILED;
950             }
951
952             break;
953
954         case CONTROL_CHANGE:
955             if((param2 = fluid_midi_file_getc(mf)) < 0)
956             {
957                 FLUID_LOG(FLUID_ERR, "Unexpected end of file");
958                 return FLUID_FAILED;
959             }
960
961             break;
962
963         case PROGRAM_CHANGE:
964             break;
965
966         case CHANNEL_PRESSURE:
967             break;
968
969         case PITCH_BEND:
970             if((param2 = fluid_midi_file_getc(mf)) < 0)
971             {
972                 FLUID_LOG(FLUID_ERR, "Unexpected end of file");
973                 return FLUID_FAILED;
974             }
975
976             param1 = ((param2 & 0x7f) << 7) | (param1 & 0x7f);
977             param2 = 0;
978             break;
979
980         default:
981             /* Can't possibly happen !? */
982             FLUID_LOG(FLUID_ERR, "Unrecognized MIDI event");
983             return FLUID_FAILED;
984         }
985
986         evt = new_fluid_midi_event();
987
988         if(evt == NULL)
989         {
990             FLUID_LOG(FLUID_ERR, "Out of memory");
991             return FLUID_FAILED;
992         }
993
994         evt->dtime = mf->dtime;
995         evt->type = type;
996         evt->channel = channel;
997         evt->param1 = param1;
998         evt->param2 = param2;
999         fluid_track_add_event(track, evt);
1000         mf->dtime = 0;
1001     }
1002
1003     return FLUID_OK;
1004 }
1005
1006 /*
1007  * fluid_midi_file_get_division
1008  */
1009 int
1010 fluid_midi_file_get_division(fluid_midi_file *midifile)
1011 {
1012     return midifile->division;
1013 }
1014 #endif
1015
1016 /******************************************************
1017  *
1018  *     fluid_track_t
1019  */
1020
1021 /**
1022  * Create a MIDI event structure.
1023  * @return New MIDI event structure or NULL when out of memory.
1024  */
1025 fluid_midi_event_t *
1026 new_fluid_midi_event()
1027 {
1028     fluid_midi_event_t *evt;
1029     evt = FLUID_NEW(fluid_midi_event_t);
1030
1031     if(evt == NULL)
1032     {
1033         FLUID_LOG(FLUID_ERR, "Out of memory");
1034         return NULL;
1035     }
1036
1037     evt->dtime = 0;
1038     evt->type = 0;
1039     evt->channel = 0;
1040     evt->param1 = 0;
1041     evt->param2 = 0;
1042     evt->next = NULL;
1043     evt->paramptr = NULL;
1044     return evt;
1045 }
1046
1047 /**
1048  * Delete MIDI event structure.
1049  * @param evt MIDI event structure
1050  */
1051 void
1052 delete_fluid_midi_event(fluid_midi_event_t *evt)
1053 {
1054     fluid_midi_event_t *temp;
1055     fluid_return_if_fail(evt != NULL);
1056
1057     while(evt)
1058     {
1059         temp = evt->next;
1060
1061         /* Dynamic SYSEX event? - free (param2 indicates if dynamic) */
1062         if((evt->type == MIDI_SYSEX || (evt-> type == MIDI_TEXT) || (evt->type == MIDI_LYRIC)) &&
1063                 evt->paramptr && evt->param2)
1064         {
1065             FLUID_FREE(evt->paramptr);
1066         }
1067
1068         FLUID_FREE(evt);
1069         evt = temp;
1070     }
1071 }
1072
1073 /**
1074  * Get the event type field of a MIDI event structure.
1075  * @param evt MIDI event structure
1076  * @return Event type field (MIDI status byte without channel)
1077  */
1078 int
1079 fluid_midi_event_get_type(fluid_midi_event_t *evt)
1080 {
1081     return evt->type;
1082 }
1083
1084 /**
1085  * Set the event type field of a MIDI event structure.
1086  * @param evt MIDI event structure
1087  * @param type Event type field (MIDI status byte without channel)
1088  * @return Always returns #FLUID_OK
1089  */
1090 int
1091 fluid_midi_event_set_type(fluid_midi_event_t *evt, int type)
1092 {
1093     evt->type = type;
1094     return FLUID_OK;
1095 }
1096
1097 /**
1098  * Get the channel field of a MIDI event structure.
1099  * @param evt MIDI event structure
1100  * @return Channel field
1101  */
1102 int
1103 fluid_midi_event_get_channel(fluid_midi_event_t *evt)
1104 {
1105     return evt->channel;
1106 }
1107
1108 /**
1109  * Set the channel field of a MIDI event structure.
1110  * @param evt MIDI event structure
1111  * @param chan MIDI channel field
1112  * @return Always returns #FLUID_OK
1113  */
1114 int
1115 fluid_midi_event_set_channel(fluid_midi_event_t *evt, int chan)
1116 {
1117     evt->channel = chan;
1118     return FLUID_OK;
1119 }
1120
1121 /**
1122  * Get the key field of a MIDI event structure.
1123  * @param evt MIDI event structure
1124  * @return MIDI note number (0-127)
1125  */
1126 int
1127 fluid_midi_event_get_key(fluid_midi_event_t *evt)
1128 {
1129     return evt->param1;
1130 }
1131
1132 /**
1133  * Set the key field of a MIDI event structure.
1134  * @param evt MIDI event structure
1135  * @param v MIDI note number (0-127)
1136  * @return Always returns #FLUID_OK
1137  */
1138 int
1139 fluid_midi_event_set_key(fluid_midi_event_t *evt, int v)
1140 {
1141     evt->param1 = v;
1142     return FLUID_OK;
1143 }
1144
1145 /**
1146  * Get the velocity field of a MIDI event structure.
1147  * @param evt MIDI event structure
1148  * @return MIDI velocity number (0-127)
1149  */
1150 int
1151 fluid_midi_event_get_velocity(fluid_midi_event_t *evt)
1152 {
1153     return evt->param2;
1154 }
1155
1156 /**
1157  * Set the velocity field of a MIDI event structure.
1158  * @param evt MIDI event structure
1159  * @param v MIDI velocity value
1160  * @return Always returns #FLUID_OK
1161  */
1162 int
1163 fluid_midi_event_set_velocity(fluid_midi_event_t *evt, int v)
1164 {
1165     evt->param2 = v;
1166     return FLUID_OK;
1167 }
1168
1169 /**
1170  * Get the control number of a MIDI event structure.
1171  * @param evt MIDI event structure
1172  * @return MIDI control number
1173  */
1174 int
1175 fluid_midi_event_get_control(fluid_midi_event_t *evt)
1176 {
1177     return evt->param1;
1178 }
1179
1180 /**
1181  * Set the control field of a MIDI event structure.
1182  * @param evt MIDI event structure
1183  * @param v MIDI control number
1184  * @return Always returns #FLUID_OK
1185  */
1186 int
1187 fluid_midi_event_set_control(fluid_midi_event_t *evt, int v)
1188 {
1189     evt->param1 = v;
1190     return FLUID_OK;
1191 }
1192
1193 /**
1194  * Get the value field from a MIDI event structure.
1195  * @param evt MIDI event structure
1196  * @return Value field
1197  */
1198 int
1199 fluid_midi_event_get_value(fluid_midi_event_t *evt)
1200 {
1201     return evt->param2;
1202 }
1203
1204 /**
1205  * Set the value field of a MIDI event structure.
1206  * @param evt MIDI event structure
1207  * @param v Value to assign
1208  * @return Always returns #FLUID_OK
1209  */
1210 int
1211 fluid_midi_event_set_value(fluid_midi_event_t *evt, int v)
1212 {
1213     evt->param2 = v;
1214     return FLUID_OK;
1215 }
1216
1217 /**
1218  * Get the program field of a MIDI event structure.
1219  * @param evt MIDI event structure
1220  * @return MIDI program number (0-127)
1221  */
1222 int
1223 fluid_midi_event_get_program(fluid_midi_event_t *evt)
1224 {
1225     return evt->param1;
1226 }
1227
1228 /**
1229  * Set the program field of a MIDI event structure.
1230  * @param evt MIDI event structure
1231  * @param val MIDI program number (0-127)
1232  * @return Always returns #FLUID_OK
1233  */
1234 int
1235 fluid_midi_event_set_program(fluid_midi_event_t *evt, int val)
1236 {
1237     evt->param1 = val;
1238     return FLUID_OK;
1239 }
1240
1241 /**
1242  * Get the pitch field of a MIDI event structure.
1243  * @param evt MIDI event structure
1244  * @return Pitch value (14 bit value, 0-16383, 8192 is center)
1245  */
1246 int
1247 fluid_midi_event_get_pitch(fluid_midi_event_t *evt)
1248 {
1249     return evt->param1;
1250 }
1251
1252 /**
1253  * Set the pitch field of a MIDI event structure.
1254  * @param evt MIDI event structure
1255  * @param val Pitch value (14 bit value, 0-16383, 8192 is center)
1256  * @return Always returns FLUID_OK
1257  */
1258 int
1259 fluid_midi_event_set_pitch(fluid_midi_event_t *evt, int val)
1260 {
1261     evt->param1 = val;
1262     return FLUID_OK;
1263 }
1264
1265 /**
1266  * Assign sysex data to a MIDI event structure.
1267  * @param evt MIDI event structure
1268  * @param data Pointer to SYSEX data
1269  * @param size Size of SYSEX data in bytes
1270  * @param dynamic TRUE if the SYSEX data has been dynamically allocated and
1271  *   should be freed when the event is freed (only applies if event gets destroyed
1272  *   with delete_fluid_midi_event())
1273  * @return Always returns #FLUID_OK
1274  *
1275  * @note Unlike the other event assignment functions, this one sets evt->type.
1276  */
1277 int
1278 fluid_midi_event_set_sysex(fluid_midi_event_t *evt, void *data, int size, int dynamic)
1279 {
1280     fluid_midi_event_set_sysex_LOCAL(evt, MIDI_SYSEX, data, size, dynamic);
1281     return FLUID_OK;
1282 }
1283
1284 /**
1285  * Assign text data to a MIDI event structure.
1286  * @param evt MIDI event structure
1287  * @param data Pointer to text data
1288  * @param size Size of text data in bytes
1289  * @param dynamic TRUE if the data has been dynamically allocated and
1290  *   should be freed when the event is freed via delete_fluid_midi_event()
1291  * @return Always returns #FLUID_OK
1292  *
1293  * @since 2.0.0
1294  * @note Unlike the other event assignment functions, this one sets evt->type.
1295  */
1296 int
1297 fluid_midi_event_set_text(fluid_midi_event_t *evt, void *data, int size, int dynamic)
1298 {
1299     fluid_midi_event_set_sysex_LOCAL(evt, MIDI_TEXT, data, size, dynamic);
1300     return FLUID_OK;
1301 }
1302
1303 /**
1304  * Assign lyric data to a MIDI event structure.
1305  * @param evt MIDI event structure
1306  * @param data Pointer to lyric data
1307  * @param size Size of lyric data in bytes
1308  * @param dynamic TRUE if the data has been dynamically allocated and
1309  *   should be freed when the event is freed via delete_fluid_midi_event()
1310  * @return Always returns #FLUID_OK
1311  *
1312  * @since 2.0.0
1313  * @note Unlike the other event assignment functions, this one sets evt->type.
1314  */
1315 int
1316 fluid_midi_event_set_lyrics(fluid_midi_event_t *evt, void *data, int size, int dynamic)
1317 {
1318     fluid_midi_event_set_sysex_LOCAL(evt, MIDI_LYRIC, data, size, dynamic);
1319     return FLUID_OK;
1320 }
1321
1322 static void fluid_midi_event_set_sysex_LOCAL(fluid_midi_event_t *evt, int type, void *data, int size, int dynamic)
1323 {
1324     evt->type = type;
1325     evt->paramptr = data;
1326     evt->param1 = size;
1327     evt->param2 = dynamic;
1328 }
1329
1330 /******************************************************
1331  *
1332  *     fluid_track_t
1333  */
1334 #if 0 // disable fluid file player in Ardour
1335 /*
1336  * new_fluid_track
1337  */
1338 fluid_track_t *
1339 new_fluid_track(int num)
1340 {
1341     fluid_track_t *track;
1342     track = FLUID_NEW(fluid_track_t);
1343
1344     if(track == NULL)
1345     {
1346         return NULL;
1347     }
1348
1349     track->name = NULL;
1350     track->num = num;
1351     track->first = NULL;
1352     track->cur = NULL;
1353     track->last = NULL;
1354     track->ticks = 0;
1355     return track;
1356 }
1357
1358 /*
1359  * delete_fluid_track
1360  */
1361 void
1362 delete_fluid_track(fluid_track_t *track)
1363 {
1364     fluid_return_if_fail(track != NULL);
1365
1366     FLUID_FREE(track->name);
1367     delete_fluid_midi_event(track->first);
1368     FLUID_FREE(track);
1369 }
1370
1371 /*
1372  * fluid_track_set_name
1373  */
1374 int
1375 fluid_track_set_name(fluid_track_t *track, char *name)
1376 {
1377     int len;
1378
1379     if(track->name != NULL)
1380     {
1381         FLUID_FREE(track->name);
1382     }
1383
1384     if(name == NULL)
1385     {
1386         track->name = NULL;
1387         return FLUID_OK;
1388     }
1389
1390     len = FLUID_STRLEN(name);
1391     track->name = FLUID_MALLOC(len + 1);
1392
1393     if(track->name == NULL)
1394     {
1395         FLUID_LOG(FLUID_ERR, "Out of memory");
1396         return FLUID_FAILED;
1397     }
1398
1399     FLUID_STRCPY(track->name, name);
1400     return FLUID_OK;
1401 }
1402
1403 /*
1404  * fluid_track_get_duration
1405  */
1406 int
1407 fluid_track_get_duration(fluid_track_t *track)
1408 {
1409     int time = 0;
1410     fluid_midi_event_t *evt = track->first;
1411
1412     while(evt != NULL)
1413     {
1414         time += evt->dtime;
1415         evt = evt->next;
1416     }
1417
1418     return time;
1419 }
1420
1421 /*
1422  * fluid_track_add_event
1423  */
1424 int
1425 fluid_track_add_event(fluid_track_t *track, fluid_midi_event_t *evt)
1426 {
1427     evt->next = NULL;
1428
1429     if(track->first == NULL)
1430     {
1431         track->first = evt;
1432         track->cur = evt;
1433         track->last = evt;
1434     }
1435     else
1436     {
1437         track->last->next = evt;
1438         track->last = evt;
1439     }
1440
1441     return FLUID_OK;
1442 }
1443
1444 /*
1445  * fluid_track_next_event
1446  */
1447 fluid_midi_event_t *
1448 fluid_track_next_event(fluid_track_t *track)
1449 {
1450     if(track->cur != NULL)
1451     {
1452         track->cur = track->cur->next;
1453     }
1454
1455     return track->cur;
1456 }
1457
1458 /*
1459  * fluid_track_reset
1460  */
1461 int
1462 fluid_track_reset(fluid_track_t *track)
1463 {
1464     track->ticks = 0;
1465     track->cur = track->first;
1466     return FLUID_OK;
1467 }
1468
1469 /*
1470  * fluid_track_send_events
1471  */
1472 int
1473 fluid_track_send_events(fluid_track_t *track,
1474                         fluid_synth_t *synth,
1475                         fluid_player_t *player,
1476                         unsigned int ticks)
1477 {
1478     int status = FLUID_OK;
1479     fluid_midi_event_t *event;
1480     int seeking = player->seek_ticks >= 0;
1481
1482     if(seeking)
1483     {
1484         ticks = player->seek_ticks; /* update target ticks */
1485
1486         if(track->ticks > ticks)
1487         {
1488             fluid_track_reset(track);    /* reset track if seeking backwards */
1489         }
1490     }
1491
1492     while(1)
1493     {
1494
1495         event = track->cur;
1496
1497         if(event == NULL)
1498         {
1499             return status;
1500         }
1501
1502         /*              printf("track=%02d\tticks=%05u\ttrack=%05u\tdtime=%05u\tnext=%05u\n", */
1503         /*                     track->num, */
1504         /*                     ticks, */
1505         /*                     track->ticks, */
1506         /*                     event->dtime, */
1507         /*                     track->ticks + event->dtime); */
1508
1509         if(track->ticks + event->dtime > ticks)
1510         {
1511             return status;
1512         }
1513
1514         track->ticks += event->dtime;
1515
1516         if(!player || event->type == MIDI_EOT)
1517         {
1518         }
1519         else if(seeking && (event->type == NOTE_ON || event->type == NOTE_OFF))
1520         {
1521             /* skip on/off messages */
1522         }
1523         else
1524         {
1525             if(player->playback_callback)
1526             {
1527                 player->playback_callback(player->playback_userdata, event);
1528             }
1529         }
1530
1531         if(event->type == MIDI_SET_TEMPO)
1532         {
1533             fluid_player_set_midi_tempo(player, event->param1);
1534         }
1535
1536         fluid_track_next_event(track);
1537
1538     }
1539
1540     return status;
1541 }
1542
1543 /******************************************************
1544  *
1545  *     fluid_player
1546  */
1547 static void
1548 fluid_player_handle_reset_synth(void *data, const char *name, int value)
1549 {
1550     fluid_player_t *player = data;
1551     fluid_return_if_fail(player != NULL);
1552
1553     player->reset_synth_between_songs = value;
1554 }
1555
1556 /**
1557  * Create a new MIDI player.
1558  * @param synth Fluid synthesizer instance to create player for
1559  * @return New MIDI player instance or NULL on error (out of memory)
1560  */
1561 fluid_player_t *
1562 new_fluid_player(fluid_synth_t *synth)
1563 {
1564     int i;
1565     fluid_player_t *player;
1566     player = FLUID_NEW(fluid_player_t);
1567
1568     if(player == NULL)
1569     {
1570         FLUID_LOG(FLUID_ERR, "Out of memory");
1571         return NULL;
1572     }
1573
1574     player->status = FLUID_PLAYER_READY;
1575     player->loop = 1;
1576     player->ntracks = 0;
1577
1578     for(i = 0; i < MAX_NUMBER_OF_TRACKS; i++)
1579     {
1580         player->track[i] = NULL;
1581     }
1582
1583     player->synth = synth;
1584     player->system_timer = NULL;
1585     player->sample_timer = NULL;
1586     player->playlist = NULL;
1587     player->currentfile = NULL;
1588     player->division = 0;
1589     player->send_program_change = 1;
1590     player->miditempo = 480000;
1591     player->deltatime = 4.0;
1592     player->cur_msec = 0;
1593     player->cur_ticks = 0;
1594     player->seek_ticks = -1;
1595     fluid_player_set_playback_callback(player, fluid_synth_handle_midi_event, synth);
1596     player->use_system_timer = fluid_settings_str_equal(synth->settings,
1597                                "player.timing-source", "system");
1598
1599     fluid_settings_getint(synth->settings, "player.reset-synth", &i);
1600     fluid_player_handle_reset_synth(player, NULL, i);
1601     
1602     fluid_settings_callback_int(synth->settings, "player.reset-synth",
1603                                 fluid_player_handle_reset_synth, player);
1604
1605     return player;
1606 }
1607
1608 /**
1609  * Delete a MIDI player instance.
1610  * @param player MIDI player instance
1611  */
1612 void
1613 delete_fluid_player(fluid_player_t *player)
1614 {
1615     fluid_list_t *q;
1616     fluid_playlist_item *pi;
1617
1618     fluid_return_if_fail(player != NULL);
1619
1620     fluid_player_stop(player);
1621     fluid_player_reset(player);
1622
1623     while(player->playlist != NULL)
1624     {
1625         q = player->playlist->next;
1626         pi = (fluid_playlist_item *) player->playlist->data;
1627         FLUID_FREE(pi->filename);
1628         FLUID_FREE(pi->buffer);
1629         FLUID_FREE(pi);
1630         delete1_fluid_list(player->playlist);
1631         player->playlist = q;
1632     }
1633
1634     FLUID_FREE(player);
1635 }
1636
1637 /**
1638  * Registers settings related to the MIDI player
1639  */
1640 void
1641 fluid_player_settings(fluid_settings_t *settings)
1642 {
1643     /* player.timing-source can be either "system" (use system timer)
1644      or "sample" (use timer based on number of written samples) */
1645     fluid_settings_register_str(settings, "player.timing-source", "sample", 0);
1646     fluid_settings_add_option(settings, "player.timing-source", "sample");
1647     fluid_settings_add_option(settings, "player.timing-source", "system");
1648
1649     /* Selects whether the player should reset the synth between songs, or not. */
1650     fluid_settings_register_int(settings, "player.reset-synth", 1, 0, 1, FLUID_HINT_TOGGLED);
1651 }
1652
1653
1654 int
1655 fluid_player_reset(fluid_player_t *player)
1656 {
1657     int i;
1658
1659     for(i = 0; i < MAX_NUMBER_OF_TRACKS; i++)
1660     {
1661         if(player->track[i] != NULL)
1662         {
1663             delete_fluid_track(player->track[i]);
1664             player->track[i] = NULL;
1665         }
1666     }
1667
1668     /*  player->current_file = NULL; */
1669     /*  player->status = FLUID_PLAYER_READY; */
1670     /*  player->loop = 1; */
1671     player->ntracks = 0;
1672     player->division = 0;
1673     player->send_program_change = 1;
1674     player->miditempo = 480000;
1675     player->deltatime = 4.0;
1676     return 0;
1677 }
1678
1679 /*
1680  * fluid_player_add_track
1681  */
1682 int
1683 fluid_player_add_track(fluid_player_t *player, fluid_track_t *track)
1684 {
1685     if(player->ntracks < MAX_NUMBER_OF_TRACKS)
1686     {
1687         player->track[player->ntracks++] = track;
1688         return FLUID_OK;
1689     }
1690     else
1691     {
1692         return FLUID_FAILED;
1693     }
1694 }
1695
1696 /**
1697  * Change the MIDI callback function. This is usually set to
1698  * fluid_synth_handle_midi_event, but can optionally be changed
1699  * to a user-defined function instead, for intercepting all MIDI
1700  * messages sent to the synth. You can also use a midi router as
1701  * the callback function to modify the MIDI messages before sending
1702  * them to the synth.
1703  * @param player MIDI player instance
1704  * @param handler Pointer to callback function
1705  * @param handler_data Parameter sent to the callback function
1706  * @returns FLUID_OK
1707  * @since 1.1.4
1708  */
1709 int
1710 fluid_player_set_playback_callback(fluid_player_t *player,
1711                                    handle_midi_event_func_t handler, void *handler_data)
1712 {
1713     player->playback_callback = handler;
1714     player->playback_userdata = handler_data;
1715     return FLUID_OK;
1716 }
1717
1718 /**
1719  * Add a MIDI file to a player queue.
1720  * @param player MIDI player instance
1721  * @param midifile File name of the MIDI file to add
1722  * @return #FLUID_OK or #FLUID_FAILED
1723  */
1724 int
1725 fluid_player_add(fluid_player_t *player, const char *midifile)
1726 {
1727     fluid_playlist_item *pi = FLUID_MALLOC(sizeof(fluid_playlist_item));
1728     char *f = FLUID_STRDUP(midifile);
1729
1730     if(!pi || !f)
1731     {
1732         FLUID_FREE(pi);
1733         FLUID_FREE(f);
1734         FLUID_LOG(FLUID_PANIC, "Out of memory");
1735         return FLUID_FAILED;
1736     }
1737
1738     pi->filename = f;
1739     pi->buffer = NULL;
1740     pi->buffer_len = 0;
1741     player->playlist = fluid_list_append(player->playlist, pi);
1742     return FLUID_OK;
1743 }
1744
1745 /**
1746  * Add a MIDI file to a player queue, from a buffer in memory.
1747  * @param player MIDI player instance
1748  * @param buffer Pointer to memory containing the bytes of a complete MIDI
1749  *   file. The data is copied, so the caller may free or modify it immediately
1750  *   without affecting the playlist.
1751  * @param len Length of the buffer, in bytes.
1752  * @return #FLUID_OK or #FLUID_FAILED
1753  */
1754 int
1755 fluid_player_add_mem(fluid_player_t *player, const void *buffer, size_t len)
1756 {
1757     /* Take a copy of the buffer, so the caller can free immediately. */
1758     fluid_playlist_item *pi = FLUID_MALLOC(sizeof(fluid_playlist_item));
1759     void *buf_copy = FLUID_MALLOC(len);
1760
1761     if(!pi || !buf_copy)
1762     {
1763         FLUID_FREE(pi);
1764         FLUID_FREE(buf_copy);
1765         FLUID_LOG(FLUID_PANIC, "Out of memory");
1766         return FLUID_FAILED;
1767     }
1768
1769     FLUID_MEMCPY(buf_copy, buffer, len);
1770     pi->filename = NULL;
1771     pi->buffer = buf_copy;
1772     pi->buffer_len = len;
1773     player->playlist = fluid_list_append(player->playlist, pi);
1774     return FLUID_OK;
1775 }
1776
1777 /*
1778  * fluid_player_load
1779  */
1780 int
1781 fluid_player_load(fluid_player_t *player, fluid_playlist_item *item)
1782 {
1783     fluid_midi_file *midifile;
1784     char *buffer;
1785     size_t buffer_length;
1786     int buffer_owned;
1787
1788     if(item->filename != NULL)
1789     {
1790         fluid_file fp;
1791         /* This file is specified by filename; load the file from disk */
1792         FLUID_LOG(FLUID_DBG, "%s: %d: Loading midifile %s", __FILE__, __LINE__,
1793                   item->filename);
1794         /* Read the entire contents of the file into the buffer */
1795         fp = FLUID_FOPEN(item->filename, "rb");
1796
1797         if(fp == NULL)
1798         {
1799             FLUID_LOG(FLUID_ERR, "Couldn't open the MIDI file");
1800             return FLUID_FAILED;
1801         }
1802
1803         buffer = fluid_file_read_full(fp, &buffer_length);
1804
1805         if(buffer == NULL)
1806         {
1807             FLUID_FCLOSE(fp);
1808             return FLUID_FAILED;
1809         }
1810
1811         buffer_owned = 1;
1812         FLUID_FCLOSE(fp);
1813     }
1814     else
1815     {
1816         /* This file is specified by a pre-loaded buffer; load from memory */
1817         FLUID_LOG(FLUID_DBG, "%s: %d: Loading midifile from memory (%p)",
1818                   __FILE__, __LINE__, item->buffer);
1819         buffer = (char *) item->buffer;
1820         buffer_length = item->buffer_len;
1821         /* Do not free the buffer (it is owned by the playlist) */
1822         buffer_owned = 0;
1823     }
1824
1825     midifile = new_fluid_midi_file(buffer, buffer_length);
1826
1827     if(midifile == NULL)
1828     {
1829         if(buffer_owned)
1830         {
1831             FLUID_FREE(buffer);
1832         }
1833
1834         return FLUID_FAILED;
1835     }
1836
1837     player->division = fluid_midi_file_get_division(midifile);
1838     fluid_player_set_midi_tempo(player, player->miditempo); // Update deltatime
1839     /*FLUID_LOG(FLUID_DBG, "quarter note division=%d\n", player->division); */
1840
1841     if(fluid_midi_file_load_tracks(midifile, player) != FLUID_OK)
1842     {
1843         if(buffer_owned)
1844         {
1845             FLUID_FREE(buffer);
1846         }
1847
1848         delete_fluid_midi_file(midifile);
1849         return FLUID_FAILED;
1850     }
1851
1852     delete_fluid_midi_file(midifile);
1853
1854     if(buffer_owned)
1855     {
1856         FLUID_FREE(buffer);
1857     }
1858
1859     return FLUID_OK;
1860 }
1861
1862 void
1863 fluid_player_advancefile(fluid_player_t *player)
1864 {
1865     if(player->playlist == NULL)
1866     {
1867         return; /* No files to play */
1868     }
1869
1870     if(player->currentfile != NULL)
1871     {
1872         player->currentfile = fluid_list_next(player->currentfile);
1873     }
1874
1875     if(player->currentfile == NULL)
1876     {
1877         if(player->loop == 0)
1878         {
1879             return; /* We're done playing */
1880         }
1881
1882         if(player->loop > 0)
1883         {
1884             player->loop--;
1885         }
1886
1887         player->currentfile = player->playlist;
1888     }
1889 }
1890
1891 void
1892 fluid_player_playlist_load(fluid_player_t *player, unsigned int msec)
1893 {
1894     fluid_playlist_item *current_playitem;
1895     int i;
1896
1897     do
1898     {
1899         fluid_player_advancefile(player);
1900
1901         if(player->currentfile == NULL)
1902         {
1903             /* Failed to find next song, probably since we're finished */
1904             player->status = FLUID_PLAYER_DONE;
1905             return;
1906         }
1907
1908         fluid_player_reset(player);
1909         current_playitem = (fluid_playlist_item *) player->currentfile->data;
1910     }
1911     while(fluid_player_load(player, current_playitem) != FLUID_OK);
1912
1913     /* Successfully loaded midi file */
1914
1915     player->begin_msec = msec;
1916     player->start_msec = msec;
1917     player->start_ticks = 0;
1918     player->cur_ticks = 0;
1919
1920     if(player->reset_synth_between_songs)
1921     {
1922         fluid_synth_system_reset(player->synth);
1923     }
1924
1925     for(i = 0; i < player->ntracks; i++)
1926     {
1927         if(player->track[i] != NULL)
1928         {
1929             fluid_track_reset(player->track[i]);
1930         }
1931     }
1932 }
1933
1934 /*
1935  * fluid_player_callback
1936  */
1937 int
1938 fluid_player_callback(void *data, unsigned int msec)
1939 {
1940     int i;
1941     int loadnextfile;
1942     int status = FLUID_PLAYER_DONE;
1943     fluid_player_t *player;
1944     fluid_synth_t *synth;
1945     player = (fluid_player_t *) data;
1946     synth = player->synth;
1947
1948     loadnextfile = player->currentfile == NULL ? 1 : 0;
1949
1950     do
1951     {
1952         if(loadnextfile)
1953         {
1954             loadnextfile = 0;
1955             fluid_player_playlist_load(player, msec);
1956
1957             if(player->currentfile == NULL)
1958             {
1959                 return 0;
1960             }
1961         }
1962
1963         player->cur_msec = msec;
1964         player->cur_ticks = (player->start_ticks
1965                              + (int)((double)(player->cur_msec - player->start_msec)
1966                                      / player->deltatime + 0.5)); /* 0.5 to average overall error when casting */
1967
1968         if(player->seek_ticks >= 0)
1969         {
1970             fluid_synth_all_sounds_off(synth, -1); /* avoid hanging notes */
1971         }
1972
1973         for(i = 0; i < player->ntracks; i++)
1974         {
1975             if(!fluid_track_eot(player->track[i]))
1976             {
1977                 status = FLUID_PLAYER_PLAYING;
1978
1979                 if(fluid_track_send_events(player->track[i], synth, player,
1980                                            player->cur_ticks) != FLUID_OK)
1981                 {
1982                     /* */
1983                 }
1984             }
1985         }
1986
1987         if(player->seek_ticks >= 0)
1988         {
1989             player->start_ticks = player->seek_ticks;   /* tick position of last tempo value (which is now) */
1990             player->cur_ticks = player->seek_ticks;
1991             player->begin_msec = msec;      /* only used to calculate the duration of playing */
1992             player->start_msec = msec;      /* should be the (synth)-time of the last tempo change */
1993             player->seek_ticks = -1;        /* clear seek_ticks */
1994         }
1995
1996         if(status == FLUID_PLAYER_DONE)
1997         {
1998             FLUID_LOG(FLUID_DBG, "%s: %d: Duration=%.3f sec", __FILE__,
1999                       __LINE__, (msec - player->begin_msec) / 1000.0);
2000             loadnextfile = 1;
2001         }
2002     }
2003     while(loadnextfile);
2004
2005     player->status = status;
2006
2007     return 1;
2008 }
2009
2010 /**
2011  * Activates play mode for a MIDI player if not already playing.
2012  * @param player MIDI player instance
2013  * @return #FLUID_OK on success, #FLUID_FAILED otherwise
2014  */
2015 int
2016 fluid_player_play(fluid_player_t *player)
2017 {
2018     if(player->status == FLUID_PLAYER_PLAYING)
2019     {
2020         return FLUID_OK;
2021     }
2022
2023     if(player->playlist == NULL)
2024     {
2025         return FLUID_OK;
2026     }
2027
2028     player->status = FLUID_PLAYER_PLAYING;
2029
2030     if(player->use_system_timer)
2031     {
2032         player->system_timer = new_fluid_timer((int) player->deltatime,
2033                                                fluid_player_callback, (void *) player, TRUE, FALSE, TRUE);
2034
2035         if(player->system_timer == NULL)
2036         {
2037             return FLUID_FAILED;
2038         }
2039     }
2040     else
2041     {
2042         player->sample_timer = new_fluid_sample_timer(player->synth,
2043                                fluid_player_callback, (void *) player);
2044
2045         if(player->sample_timer == NULL)
2046         {
2047             return FLUID_FAILED;
2048         }
2049     }
2050
2051     return FLUID_OK;
2052 }
2053
2054 /**
2055  * Stops a MIDI player.
2056  * @param player MIDI player instance
2057  * @return Always returns #FLUID_OK
2058  */
2059 int
2060 fluid_player_stop(fluid_player_t *player)
2061 {
2062     if(player->system_timer != NULL)
2063     {
2064         delete_fluid_timer(player->system_timer);
2065     }
2066
2067     if(player->sample_timer != NULL)
2068     {
2069         delete_fluid_sample_timer(player->synth, player->sample_timer);
2070     }
2071
2072     player->status = FLUID_PLAYER_DONE;
2073     player->sample_timer = NULL;
2074     player->system_timer = NULL;
2075     return FLUID_OK;
2076 }
2077
2078 /**
2079  * Get MIDI player status.
2080  * @param player MIDI player instance
2081  * @return Player status (#fluid_player_status)
2082  * @since 1.1.0
2083  */
2084 int
2085 fluid_player_get_status(fluid_player_t *player)
2086 {
2087     return player->status;
2088 }
2089
2090 /**
2091  * Seek in the currently playing file.
2092  * @param player MIDI player instance
2093  * @param ticks the position to seek to in the current file
2094  * @return #FLUID_FAILED if ticks is negative or after the latest tick of the file,
2095  *   #FLUID_OK otherwise
2096  * @since 2.0.0
2097  *
2098  * The actual seek is performed during the player_callback.
2099  */
2100 int fluid_player_seek(fluid_player_t *player, int ticks)
2101 {
2102     if(ticks < 0 || ticks > fluid_player_get_total_ticks(player))
2103     {
2104         return FLUID_FAILED;
2105     }
2106
2107     player->seek_ticks = ticks;
2108     return FLUID_OK;
2109 }
2110
2111
2112 /**
2113  * Enable looping of a MIDI player
2114  * @param player MIDI player instance
2115  * @param loop Times left to loop the playlist. -1 means loop infinitely.
2116  * @return Always returns #FLUID_OK
2117  * @since 1.1.0
2118  *
2119  * For example, if you want to loop the playlist twice, set loop to 2
2120  * and call this function before you start the player.
2121  */
2122 int fluid_player_set_loop(fluid_player_t *player, int loop)
2123 {
2124     player->loop = loop;
2125     return FLUID_OK;
2126 }
2127
2128 /**
2129  * Set the tempo of a MIDI player.
2130  * @param player MIDI player instance
2131  * @param tempo Tempo to set playback speed to (in microseconds per quarter note, as per MIDI file spec)
2132  * @return Always returns #FLUID_OK
2133  */
2134 int fluid_player_set_midi_tempo(fluid_player_t *player, int tempo)
2135 {
2136     player->miditempo = tempo;
2137     player->deltatime = (double) tempo / player->division / 1000.0; /* in milliseconds */
2138     player->start_msec = player->cur_msec;
2139     player->start_ticks = player->cur_ticks;
2140
2141     FLUID_LOG(FLUID_DBG,
2142               "tempo=%d, tick time=%f msec, cur time=%d msec, cur tick=%d",
2143               tempo, player->deltatime, player->cur_msec, player->cur_ticks);
2144
2145     return FLUID_OK;
2146 }
2147
2148 /**
2149  * Set the tempo of a MIDI player in beats per minute.
2150  * @param player MIDI player instance
2151  * @param bpm Tempo in beats per minute
2152  * @return Always returns #FLUID_OK
2153  */
2154 int fluid_player_set_bpm(fluid_player_t *player, int bpm)
2155 {
2156     return fluid_player_set_midi_tempo(player, (int)((double) 60 * 1e6 / bpm));
2157 }
2158
2159 /**
2160  * Wait for a MIDI player to terminate (when done playing).
2161  * @param player MIDI player instance
2162  * @return #FLUID_OK on success, #FLUID_FAILED otherwise
2163  */
2164 int
2165 fluid_player_join(fluid_player_t *player)
2166 {
2167     if(player->system_timer)
2168     {
2169         return fluid_timer_join(player->system_timer);
2170     }
2171     else if(player->sample_timer)
2172     {
2173         /* Busy-wait loop, since there's no thread to wait for... */
2174         while(player->status != FLUID_PLAYER_DONE)
2175         {
2176             fluid_msleep(10);
2177         }
2178     }
2179
2180     return FLUID_OK;
2181 }
2182
2183 /**
2184  * Get the number of tempo ticks passed.
2185  * @param player MIDI player instance
2186  * @return The number of tempo ticks passed
2187  * @since 1.1.7
2188  */
2189 int fluid_player_get_current_tick(fluid_player_t *player)
2190 {
2191     return player->cur_ticks;
2192 }
2193
2194 /**
2195  * Looks through all available MIDI tracks and gets the absolute tick of the very last event to play.
2196  * @param player MIDI player instance
2197  * @return Total tick count of the sequence
2198  * @since 1.1.7
2199  */
2200 int fluid_player_get_total_ticks(fluid_player_t *player)
2201 {
2202     int i;
2203     int maxTicks = 0;
2204
2205     for(i = 0; i < player->ntracks; i++)
2206     {
2207         if(player->track[i] != NULL)
2208         {
2209             int ticks = fluid_track_get_duration(player->track[i]);
2210
2211             if(ticks > maxTicks)
2212             {
2213                 maxTicks = ticks;
2214             }
2215         }
2216     }
2217
2218     return maxTicks;
2219 }
2220
2221 /**
2222  * Get the tempo of a MIDI player in beats per minute.
2223  * @param player MIDI player instance
2224  * @return MIDI player tempo in BPM
2225  * @since 1.1.7
2226  */
2227 int fluid_player_get_bpm(fluid_player_t *player)
2228 {
2229     return (int)(60e6 / player->miditempo);
2230 }
2231
2232 /**
2233  * Get the tempo of a MIDI player.
2234  * @param player MIDI player instance
2235  * @return Tempo of the MIDI player (in microseconds per quarter note, as per MIDI file spec)
2236  * @since 1.1.7
2237  */
2238 int fluid_player_get_midi_tempo(fluid_player_t *player)
2239 {
2240     return player->miditempo;
2241 }
2242
2243 /************************************************************************
2244  *       MIDI PARSER
2245  *
2246  */
2247
2248 /*
2249  * new_fluid_midi_parser
2250  */
2251 fluid_midi_parser_t *
2252 new_fluid_midi_parser()
2253 {
2254     fluid_midi_parser_t *parser;
2255     parser = FLUID_NEW(fluid_midi_parser_t);
2256
2257     if(parser == NULL)
2258     {
2259         FLUID_LOG(FLUID_ERR, "Out of memory");
2260         return NULL;
2261     }
2262
2263     parser->status = 0; /* As long as the status is 0, the parser won't do anything -> no need to initialize all the fields. */
2264     return parser;
2265 }
2266
2267 /*
2268  * delete_fluid_midi_parser
2269  */
2270 void
2271 delete_fluid_midi_parser(fluid_midi_parser_t *parser)
2272 {
2273     fluid_return_if_fail(parser != NULL);
2274
2275     FLUID_FREE(parser);
2276 }
2277
2278 /**
2279  * Parse a MIDI stream one character at a time.
2280  * @param parser Parser instance
2281  * @param c Next character in MIDI stream
2282  * @return A parsed MIDI event or NULL if none.  Event is internal and should
2283  *   not be modified or freed and is only valid until next call to this function.
2284  * @internal Do not expose this function to the public API. It would allow downstream
2285  * apps to abuse fluidsynth as midi parser, e.g. feeding it with rawmidi and pull out
2286  * the needed midi information using the getter functions of fluid_midi_event_t.
2287  * This parser however is incomplete as it e.g. only provides a limited buffer to
2288  * store and process SYSEX data (i.e. doesnt allow arbitrary lengths)
2289  */
2290 fluid_midi_event_t *
2291 fluid_midi_parser_parse(fluid_midi_parser_t *parser, unsigned char c)
2292 {
2293     fluid_midi_event_t *event;
2294
2295     /* Real-time messages (0xF8-0xFF) can occur anywhere, even in the middle
2296      * of another message. */
2297     if(c >= 0xF8)
2298     {
2299         if(c == MIDI_SYSTEM_RESET)
2300         {
2301             parser->event.type = c;
2302             parser->status = 0; /* clear the status */
2303             return &parser->event;
2304         }
2305
2306         return NULL;
2307     }
2308
2309     /* Status byte? - If previous message not yet complete, it is discarded (re-sync). */
2310     if(c & 0x80)
2311     {
2312         /* Any status byte terminates SYSEX messages (not just 0xF7) */
2313         if(parser->status == MIDI_SYSEX && parser->nr_bytes > 0)
2314         {
2315             event = &parser->event;
2316             fluid_midi_event_set_sysex(event, parser->data, parser->nr_bytes,
2317                                        FALSE);
2318         }
2319         else
2320         {
2321             event = NULL;
2322         }
2323
2324         if(c < 0xF0)  /* Voice category message? */
2325         {
2326             parser->channel = c & 0x0F;
2327             parser->status = c & 0xF0;
2328
2329             /* The event consumes x bytes of data... (subtract 1 for the status byte) */
2330             parser->nr_bytes_total = fluid_midi_event_length(parser->status)
2331                                      - 1;
2332
2333             parser->nr_bytes = 0; /* 0  bytes read so far */
2334         }
2335         else if(c == MIDI_SYSEX)
2336         {
2337             parser->status = MIDI_SYSEX;
2338             parser->nr_bytes = 0;
2339         }
2340         else
2341         {
2342             parser->status = 0;    /* Discard other system messages (0xF1-0xF7) */
2343         }
2344
2345         return event; /* Return SYSEX event or NULL */
2346     }
2347
2348     /* Data/parameter byte */
2349
2350     /* Discard data bytes for events we don't care about */
2351     if(parser->status == 0)
2352     {
2353         return NULL;
2354     }
2355
2356     /* Max data size exceeded? (SYSEX messages only really) */
2357     if(parser->nr_bytes == FLUID_MIDI_PARSER_MAX_DATA_SIZE)
2358     {
2359         parser->status = 0; /* Discard the rest of the message */
2360         return NULL;
2361     }
2362
2363     /* Store next byte */
2364     parser->data[parser->nr_bytes++] = c;
2365
2366     /* Do we still need more data to get this event complete? */
2367     if(parser->status == MIDI_SYSEX || parser->nr_bytes < parser->nr_bytes_total)
2368     {
2369         return NULL;
2370     }
2371
2372     /* Event is complete, return it.
2373      * Running status byte MIDI feature is also handled here. */
2374     parser->event.type = parser->status;
2375     parser->event.channel = parser->channel;
2376     parser->nr_bytes = 0; /* Reset data size, in case there are additional running status messages */
2377
2378     switch(parser->status)
2379     {
2380     case NOTE_OFF:
2381     case NOTE_ON:
2382     case KEY_PRESSURE:
2383     case CONTROL_CHANGE:
2384     case PROGRAM_CHANGE:
2385     case CHANNEL_PRESSURE:
2386         parser->event.param1 = parser->data[0]; /* For example key number */
2387         parser->event.param2 = parser->data[1]; /* For example velocity */
2388         break;
2389
2390     case PITCH_BEND:
2391         /* Pitch-bend is transmitted with 14-bit precision. */
2392         parser->event.param1 = (parser->data[1] << 7) | parser->data[0];
2393         break;
2394
2395     default: /* Unlikely */
2396         return NULL;
2397     }
2398
2399     return &parser->event;
2400 }
2401
2402 /* Purpose:
2403  * Returns the length of a MIDI message. */
2404 static int
2405 fluid_midi_event_length(unsigned char event)
2406 {
2407     switch(event & 0xF0)
2408     {
2409     case NOTE_OFF:
2410     case NOTE_ON:
2411     case KEY_PRESSURE:
2412     case CONTROL_CHANGE:
2413     case PITCH_BEND:
2414         return 3;
2415
2416     case PROGRAM_CHANGE:
2417     case CHANNEL_PRESSURE:
2418         return 2;
2419     }
2420
2421     switch(event)
2422     {
2423     case MIDI_TIME_CODE:
2424     case MIDI_SONG_SELECT:
2425     case 0xF4:
2426     case 0xF5:
2427         return 2;
2428
2429     case MIDI_TUNE_REQUEST:
2430         return 1;
2431
2432     case MIDI_SONG_POSITION:
2433         return 3;
2434     }
2435
2436     return 1;
2437 }
2438 #endif