Include stripped down libsmf code internally.
[ardour.git] / libs / evoral / src / libsmf / smf.c
1 /*-
2  * Copyright (c) 2007, 2008 Edward Tomasz NapieraƂa <trasz@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * ALTHOUGH THIS SOFTWARE IS MADE OF WIN AND SCIENCE, IT IS PROVIDED BY THE
15  * AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
16  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
17  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
18  * THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
20  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
21  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  */
27
28 /**
29  * \file
30  *
31  * Various functions.
32  *
33  */
34
35 /* Reference: http://www.borg.com/~jglatt/tech/midifile.htm */
36
37 #include <stdlib.h>
38 #include <string.h>
39 #include <assert.h>
40 #include <math.h>
41 #include <errno.h>
42 #include <arpa/inet.h>
43 #include "smf.h"
44 #include "smf_private.h"
45
46 /**
47  * Allocates new smf_t structure.
48  * \return pointer to smf_t or NULL.
49  */
50 smf_t *
51 smf_new(void)
52 {
53         int cantfail;
54
55         smf_t *smf = malloc(sizeof(smf_t));
56         if (smf == NULL) {
57                 g_critical("Cannot allocate smf_t structure: %s", strerror(errno));
58                 return (NULL);
59         }
60
61         memset(smf, 0, sizeof(smf_t));
62
63         smf->tracks_array = g_ptr_array_new();
64         assert(smf->tracks_array);
65
66         smf->tempo_array = g_ptr_array_new();
67         assert(smf->tempo_array);
68
69         cantfail = smf_set_ppqn(smf, 120);
70         assert(!cantfail);
71
72         cantfail = smf_set_format(smf, 0);
73         assert(!cantfail);
74
75         smf_init_tempo(smf);
76
77         return (smf);
78 }
79
80 /**
81  * Frees smf and all it's descendant structures.
82  */
83 void
84 smf_delete(smf_t *smf)
85 {
86         /* Remove all the tracks, from last to first. */
87         while (smf->tracks_array->len > 0)
88                 smf_track_delete(g_ptr_array_index(smf->tracks_array, smf->tracks_array->len - 1));
89
90         smf_fini_tempo(smf);
91
92         assert(smf->tracks_array->len == 0);
93         assert(smf->number_of_tracks == 0);
94         g_ptr_array_free(smf->tracks_array, TRUE);
95         g_ptr_array_free(smf->tempo_array, TRUE);
96
97         memset(smf, 0, sizeof(smf_t));
98         free(smf);
99 }
100
101 /**
102  * Allocates new smf_track_t structure.
103  * \return pointer to smf_track_t or NULL.
104  */
105 smf_track_t *
106 smf_track_new(void)
107 {
108         smf_track_t *track = malloc(sizeof(smf_track_t));
109         if (track == NULL) {
110                 g_critical("Cannot allocate smf_track_t structure: %s", strerror(errno));
111                 return (NULL);
112         }
113
114         memset(track, 0, sizeof(smf_track_t));
115         track->next_event_number = -1;
116
117         track->events_array = g_ptr_array_new();
118         assert(track->events_array);
119
120         return (track);
121 }
122
123 /**
124  * Detaches track from its smf and frees it.
125  */
126 void
127 smf_track_delete(smf_track_t *track)
128 {
129         assert(track);
130         assert(track->events_array);
131
132         /* Remove all the events, from last to first. */
133         while (track->events_array->len > 0)
134                 smf_event_delete(g_ptr_array_index(track->events_array, track->events_array->len - 1));
135
136         if (track->smf)
137                 smf_track_remove_from_smf(track);
138
139         assert(track->events_array->len == 0);
140         assert(track->number_of_events == 0);
141         g_ptr_array_free(track->events_array, TRUE);
142
143         memset(track, 0, sizeof(smf_track_t));
144         free(track);
145 }
146
147
148 /**
149  * Appends smf_track_t to smf.
150  */
151 void
152 smf_add_track(smf_t *smf, smf_track_t *track)
153 {
154         int cantfail;
155
156         assert(track->smf == NULL);
157
158         track->smf = smf;
159         g_ptr_array_add(smf->tracks_array, track);
160
161         smf->number_of_tracks++;
162         track->track_number = smf->number_of_tracks;
163
164         if (smf->number_of_tracks > 1) {
165                 cantfail = smf_set_format(smf, 1);
166                 assert(!cantfail);
167         }
168 }
169
170 /**
171  * Detaches track from the smf.
172  */
173 void
174 smf_track_remove_from_smf(smf_track_t *track)
175 {
176         int i, j;
177         smf_track_t *tmp;
178         smf_event_t *ev;
179
180         assert(track->smf != NULL);
181
182         track->smf->number_of_tracks--;
183
184         assert(track->smf->tracks_array);
185         g_ptr_array_remove(track->smf->tracks_array, track);
186
187         /* Renumber the rest of the tracks, so they are consecutively numbered. */
188         for (i = track->track_number; i <= track->smf->number_of_tracks; i++) {
189                 tmp = smf_get_track_by_number(track->smf, i);
190                 tmp->track_number = i;
191
192                 /*
193                  * Events have track numbers too.  I guess this wasn't a wise
194                  * decision.  ;-/
195                  */
196                 for (j = 1; j <= tmp->number_of_events; j++) {
197                         ev = smf_track_get_event_by_number(tmp, j);
198                         ev->track_number = i;
199                 }
200         }
201
202         track->track_number = -1;
203         track->smf = NULL;
204 }
205
206 /**
207  * Allocates new smf_event_t structure.  The caller is responsible for allocating
208  * event->midi_buffer, filling it with MIDI data and setting event->midi_buffer_length properly.
209  * Note that event->midi_buffer will be freed by smf_event_delete.
210  * \return pointer to smf_event_t or NULL.
211  */
212 smf_event_t *
213 smf_event_new(void)
214 {
215         smf_event_t *event = malloc(sizeof(smf_event_t));
216         if (event == NULL) {
217                 g_critical("Cannot allocate smf_event_t structure: %s", strerror(errno));
218                 return (NULL);
219         }
220
221         memset(event, 0, sizeof(smf_event_t));
222
223         event->delta_time_pulses = -1;
224         event->time_pulses = -1;
225         event->time_seconds = -1.0;
226         event->track_number = -1;
227
228         return (event);
229 }
230
231 /**
232  * Allocates an smf_event_t structure and fills it with "len" bytes copied
233  * from "midi_data".
234  * \param midi_data Pointer to MIDI data.  It sill be copied to the newly allocated event->midi_buffer.
235  * \param len Length of the buffer.  It must be proper MIDI event length, e.g. 3 for Note On event.
236  * \return Event containing MIDI data or NULL.
237  */
238 smf_event_t *
239 smf_event_new_from_pointer(void *midi_data, int len)
240 {
241         smf_event_t *event;
242
243         event = smf_event_new();
244         if (event == NULL)
245                 return (NULL);
246
247         event->midi_buffer_length = len;
248         event->midi_buffer = malloc(event->midi_buffer_length);
249         if (event->midi_buffer == NULL) {
250                 g_critical("Cannot allocate MIDI buffer structure: %s", strerror(errno));
251                 smf_event_delete(event);
252
253                 return (NULL); 
254         }
255
256         memcpy(event->midi_buffer, midi_data, len);
257
258         return (event);
259 }
260
261 /**
262  * Allocates an smf_event_t structure and fills it with at most three bytes of data.
263  * For example, if you need to create Note On event, do something like this:
264  *
265  * smf_event_new_from_bytes(0x90, 0x3C, 0x7f);
266  *
267  * To create event for MIDI message that is shorter than three bytes, do something
268  * like this:
269  *
270  * smf_event_new_from_bytes(0xC0, 0x42, -1);
271  * 
272  * \param first_byte First byte of MIDI message.  Must be valid status byte.
273  * \param second_byte Second byte of MIDI message or -1, if message is one byte long.
274  * \param third_byte Third byte of MIDI message or -1, if message is two bytes long.
275  * \return Event containing MIDI data or NULL.
276  */
277 smf_event_t *
278 smf_event_new_from_bytes(int first_byte, int second_byte, int third_byte)
279 {
280         int len;
281
282         smf_event_t *event;
283
284         event = smf_event_new();
285         if (event == NULL)
286                 return (NULL);
287
288         if (first_byte < 0) {
289                 g_critical("First byte of MIDI message cannot be < 0");
290                 smf_event_delete(event);
291
292                 return (NULL);
293         }
294
295         if (first_byte > 255) {
296                 g_critical("smf_event_new_from_bytes: first byte is %d, which is larger than 255.", first_byte);
297                 return (NULL);
298         }
299
300         if (!is_status_byte(first_byte)) {
301                 g_critical("smf_event_new_from_bytes: first byte is not a valid status byte.");
302                 return (NULL);
303         }
304
305
306         if (second_byte < 0)
307                 len = 1;
308         else if (third_byte < 0)
309                 len = 2;
310         else
311                 len = 3;
312
313         if (len > 1) {
314                 if (second_byte > 255) {
315                         g_critical("smf_event_new_from_bytes: second byte is %d, which is larger than 255.", second_byte);
316                         return (NULL);
317                 }
318
319                 if (is_status_byte(second_byte)) {
320                         g_critical("smf_event_new_from_bytes: second byte cannot be a status byte.");
321                         return (NULL);
322                 }
323         }
324
325         if (len > 2) {
326                 if (third_byte > 255) {
327                         g_critical("smf_event_new_from_bytes: third byte is %d, which is larger than 255.", third_byte);
328                         return (NULL);
329                 }
330
331                 if (is_status_byte(third_byte)) {
332                         g_critical("smf_event_new_from_bytes: third byte cannot be a status byte.");
333                         return (NULL);
334                 }
335         }
336
337         event->midi_buffer_length = len;
338         event->midi_buffer = malloc(event->midi_buffer_length);
339         if (event->midi_buffer == NULL) {
340                 g_critical("Cannot allocate MIDI buffer structure: %s", strerror(errno));
341                 smf_event_delete(event);
342
343                 return (NULL); 
344         }
345
346         event->midi_buffer[0] = first_byte;
347         if (len > 1)
348                 event->midi_buffer[1] = second_byte;
349         if (len > 2)
350                 event->midi_buffer[2] = third_byte;
351
352         return (event);
353 }
354
355 /**
356  * Detaches event from its track and frees it.
357  */
358 void
359 smf_event_delete(smf_event_t *event)
360 {
361         if (event->track != NULL)
362                 smf_event_remove_from_track(event);
363
364         if (event->midi_buffer != NULL) {
365                 memset(event->midi_buffer, 0, event->midi_buffer_length);
366                 free(event->midi_buffer);
367         }
368
369         memset(event, 0, sizeof(smf_event_t));
370         free(event);
371 }
372
373 /**
374  * Used for sorting track->events_array.
375  */
376 static gint
377 events_array_compare_function(gconstpointer aa, gconstpointer bb)
378 {
379         smf_event_t *a, *b;
380         
381         /* "The comparison function for g_ptr_array_sort() doesn't take the pointers
382             from the array as arguments, it takes pointers to the pointers in the array." */
383         a = (smf_event_t *)*(gpointer *)aa;
384         b = (smf_event_t *)*(gpointer *)bb;
385
386         if (a->time_pulses < b->time_pulses)
387                 return (-1);
388
389         if (a->time_pulses > b->time_pulses)
390                 return (1);
391
392         /*
393          * We need to preserve original order, otherwise things will break
394          * when there are several events with the same ->time_pulses.
395          * XXX: This is an ugly hack; we should remove sorting altogether.
396          */
397
398         if (a->event_number < b->event_number)
399                 return (-1);
400
401         if (a->event_number > b->event_number)
402                 return (1);
403
404         return (0);
405 }
406
407 /*
408  * An assumption here is that if there is an EOT event, it will be at the end of the track.
409  */
410 static void
411 remove_eot_if_before_pulses(smf_track_t *track, int pulses)
412 {
413         smf_event_t *event;
414
415         event = smf_track_get_last_event(track);
416
417         if (event == NULL)
418                 return;
419
420         if (!smf_event_is_eot(event))
421                 return;
422
423         if (event->time_pulses > pulses)
424                 return;
425
426         smf_event_remove_from_track(event);
427 }
428
429 /**
430  * Adds the event to the track and computes ->delta_pulses.  Note that it is faster
431  * to append events to the end of the track than to insert them in the middle.
432  * Usually you want to use smf_track_add_event_seconds or smf_track_add_event_pulses
433  * instead of this one.  Event needs to have ->time_pulses and ->time_seconds already set.
434  * If you try to add event after an EOT, EOT event will be automatically deleted.
435  */
436 void
437 smf_track_add_event(smf_track_t *track, smf_event_t *event)
438 {
439         int i, last_pulses = 0;
440
441         assert(track->smf != NULL);
442         assert(event->track == NULL);
443         assert(event->delta_time_pulses == -1);
444         assert(event->time_pulses >= 0);
445         assert(event->time_seconds >= 0.0);
446
447         remove_eot_if_before_pulses(track, event->time_pulses);
448
449         event->track = track;
450         event->track_number = track->track_number;
451
452         if (track->number_of_events == 0) {
453                 assert(track->next_event_number == -1);
454                 track->next_event_number = 1;
455         }
456
457         if (track->number_of_events > 0)
458                 last_pulses = smf_track_get_last_event(track)->time_pulses;
459
460         track->number_of_events++;
461
462         /* Are we just appending element at the end of the track? */
463         if (last_pulses <= event->time_pulses) {
464                 event->delta_time_pulses = event->time_pulses - last_pulses;
465                 assert(event->delta_time_pulses >= 0);
466                 g_ptr_array_add(track->events_array, event);
467                 event->event_number = track->number_of_events;
468
469         /* We need to insert in the middle of the track.  XXX: This is slow. */
470         } else {
471                 /* Append, then sort according to ->time_pulses. */
472                 g_ptr_array_add(track->events_array, event);
473                 g_ptr_array_sort(track->events_array, events_array_compare_function);
474
475                 /* Renumber entries and fix their ->delta_pulses. */
476                 for (i = 1; i <= track->number_of_events; i++) {
477                         smf_event_t *tmp = smf_track_get_event_by_number(track, i);
478                         tmp->event_number = i;
479
480                         if (tmp->delta_time_pulses != -1)
481                                 continue;
482
483                         if (i == 1) {
484                                 tmp->delta_time_pulses = tmp->time_pulses;
485                         } else {
486                                 tmp->delta_time_pulses = tmp->time_pulses -
487                                         smf_track_get_event_by_number(track, i - 1)->time_pulses;
488                                 assert(tmp->delta_time_pulses >= 0);
489                         }
490                 }
491
492                 /* Adjust ->delta_time_pulses of the next event. */
493                 if (event->event_number < track->number_of_events) {
494                         smf_event_t *next_event = smf_track_get_event_by_number(track, event->event_number + 1);
495                         assert(next_event);
496                         assert(next_event->time_pulses >= event->time_pulses);
497                         next_event->delta_time_pulses -= event->delta_time_pulses;
498                         assert(next_event->delta_time_pulses >= 0);
499                 }
500         }
501
502         if (smf_event_is_tempo_change_or_time_signature(event)) {
503                 if (smf_event_is_last(event))
504                         maybe_add_to_tempo_map(event);
505                 else
506                         smf_create_tempo_map_and_compute_seconds(event->track->smf);
507         }
508 }
509
510 /**
511  * Add End Of Track metaevent.  Using it is optional, libsmf will automatically
512  * add EOT to the tracks during smf_save, with delta_pulses 0.  If you try to add EOT
513  * in the middle of the track, it will fail and nonzero value will be returned.
514  * If you try to add EOT after another EOT event, it will be added, but the existing
515  * EOT event will be removed.
516  *
517  * \return 0 if everything went ok, nonzero otherwise.
518  */
519 int
520 smf_track_add_eot_delta_pulses(smf_track_t *track, int delta)
521 {
522         smf_event_t *event;
523
524         event = smf_event_new_from_bytes(0xFF, 0x2F, 0x00);
525         if (event == NULL)
526                 return (-1);
527
528         smf_track_add_event_delta_pulses(track, event, delta);
529
530         return (0);
531 }
532
533 int
534 smf_track_add_eot_pulses(smf_track_t *track, int pulses)
535 {
536         smf_event_t *event, *last_event;
537
538         last_event = smf_track_get_last_event(track);
539         if (last_event != NULL) {
540                 if (last_event->time_pulses > pulses)
541                         return (-2);
542         }
543
544         event = smf_event_new_from_bytes(0xFF, 0x2F, 0x00);
545         if (event == NULL)
546                 return (-3);
547
548         smf_track_add_event_pulses(track, event, pulses);
549
550         return (0);
551 }
552
553 int
554 smf_track_add_eot_seconds(smf_track_t *track, double seconds)
555 {
556         smf_event_t *event, *last_event;
557
558         last_event = smf_track_get_last_event(track);
559         if (last_event != NULL) {
560                 if (last_event->time_seconds > seconds)
561                         return (-2);
562         }
563
564         event = smf_event_new_from_bytes(0xFF, 0x2F, 0x00);
565         if (event == NULL)
566                 return (-1);
567
568         smf_track_add_event_seconds(track, event, seconds);
569
570         return (0);
571 }
572
573 /**
574  * Detaches event from its track.
575  */
576 void
577 smf_event_remove_from_track(smf_event_t *event)
578 {
579         int i, was_last;
580         smf_event_t *tmp;
581         smf_track_t *track;
582
583         assert(event->track != NULL);
584         assert(event->track->smf != NULL);
585
586         track = event->track;
587         was_last = smf_event_is_last(event);
588
589         /* Adjust ->delta_time_pulses of the next event. */
590         if (event->event_number < track->number_of_events) {
591                 tmp = smf_track_get_event_by_number(track, event->event_number + 1);
592                 assert(tmp);
593                 tmp->delta_time_pulses += event->delta_time_pulses;
594         }
595
596         track->number_of_events--;
597         g_ptr_array_remove(track->events_array, event);
598
599         if (track->number_of_events == 0)
600                 track->next_event_number = -1;
601
602         /* Renumber the rest of the events, so they are consecutively numbered. */
603         for (i = event->event_number; i <= track->number_of_events; i++) {
604                 tmp = smf_track_get_event_by_number(track, i);
605                 tmp->event_number = i;
606         }
607
608         if (smf_event_is_tempo_change_or_time_signature(event)) {
609                 /* XXX: This will cause problems, when there is more than one Tempo Change event at a given time. */
610                 if (was_last)
611                         remove_last_tempo_with_pulses(event->track->smf, event->time_pulses);
612                 else
613                         smf_create_tempo_map_and_compute_seconds(track->smf);
614         }
615
616         event->track = NULL;
617         event->event_number = -1;
618         event->delta_time_pulses = -1;
619         event->time_pulses = -1;
620         event->time_seconds = -1.0;
621 }
622
623 /**
624   * \return Nonzero if event is Tempo Change or Time Signature metaevent.
625   */
626 int
627 smf_event_is_tempo_change_or_time_signature(const smf_event_t *event)
628 {
629         if (!smf_event_is_metadata(event))
630                 return (0);
631
632         assert(event->midi_buffer_length >= 2);
633
634         if (event->midi_buffer[1] == 0x51 || event->midi_buffer[1] == 0x58)
635                 return (1);
636
637         return (0);
638 }
639
640 /**
641   * Sets "Format" field of MThd header to the specified value.  Note that you
642   * don't really need to use this, as libsmf will automatically change format
643   * from 0 to 1 when you add the second track.
644   * \param smf SMF.
645   * \param format 0 for one track per file, 1 for several tracks per file.
646   */
647 int
648 smf_set_format(smf_t *smf, int format)
649 {
650         assert(format == 0 || format == 1);
651
652         if (smf->number_of_tracks > 1 && format == 0) {
653                 g_critical("There is more than one track, cannot set format to 0.");
654                 return (-1);
655         }
656
657         smf->format = format;
658
659         return (0);
660 }
661
662 /**
663   * Sets the PPQN ("Division") field of MThd header.  This is mandatory, you
664   * should call it right after smf_new.  Note that changing PPQN will change time_seconds
665   * of all the events.
666   * \param smf SMF.
667   * \param ppqn New PPQN.
668   */
669 int
670 smf_set_ppqn(smf_t *smf, int ppqn)
671 {
672         assert(ppqn > 0);
673
674         smf->ppqn = ppqn;
675
676         return (0);
677 }
678
679 /**
680   * Returns next event from the track given and advances next event counter.
681   * Do not depend on End Of Track event being the last event on the track - it
682   * is possible that the track will not end with EOT if you haven't added it
683   * yet.  EOTs are added automatically during smf_save().
684   *
685   * \return Event or NULL, if there are no more events left in this track.
686   */
687 smf_event_t *
688 smf_track_get_next_event(smf_track_t *track)
689 {
690         smf_event_t *event, *next_event;
691
692         /* End of track? */
693         if (track->next_event_number == -1)
694                 return (NULL);
695
696         assert(track->next_event_number >= 1);
697         assert(track->number_of_events > 0);
698
699         event = smf_track_get_event_by_number(track, track->next_event_number);
700
701         assert(event != NULL);
702
703         /* Is this the last event in the track? */
704         if (track->next_event_number < track->number_of_events) {
705                 next_event = smf_track_get_event_by_number(track, track->next_event_number + 1);
706                 assert(next_event);
707
708                 track->time_of_next_event = next_event->time_pulses;
709                 track->next_event_number++;
710         } else {
711                 track->next_event_number = -1;
712         }
713
714         return (event);
715 }
716
717 /**
718   * Returns next event from the track given.  Does not change next event counter,
719   * so repeatedly calling this routine will return the same event.
720   * \return Event or NULL, if there are no more events left in this track.
721   */
722 static smf_event_t *
723 smf_peek_next_event_from_track(smf_track_t *track)
724 {
725         smf_event_t *event;
726
727         /* End of track? */
728         if (track->next_event_number == -1)
729                 return (NULL);
730
731         assert(track->next_event_number >= 1);
732         assert(track->events_array->len != 0);
733
734         event = smf_track_get_event_by_number(track, track->next_event_number);
735
736         return (event);
737 }
738
739 /**
740  * \return Track with a given number or NULL, if there is no such track.
741  * Tracks are numbered consecutively starting from one.
742  */
743 smf_track_t *
744 smf_get_track_by_number(const smf_t *smf, int track_number)
745 {
746         smf_track_t *track;
747
748         assert(track_number >= 1);
749
750         if (track_number > smf->number_of_tracks)
751                 return (NULL);
752
753         track = (smf_track_t *)g_ptr_array_index(smf->tracks_array, track_number - 1);
754
755         assert(track);
756
757         return (track);
758 }
759
760 /**
761  * \return Event with a given number or NULL, if there is no such event.
762  * Events are numbered consecutively starting from one.
763  */
764 smf_event_t *
765 smf_track_get_event_by_number(const smf_track_t *track, int event_number)
766 {
767         smf_event_t *event;
768
769         assert(event_number >= 1);
770
771         if (event_number > track->number_of_events)
772                 return (NULL);
773
774         event = g_ptr_array_index(track->events_array, event_number - 1);
775
776         assert(event);
777
778         return (event);
779 }
780
781 /**
782  * \return Last event on the track or NULL, if track is empty.
783  */
784 smf_event_t *
785 smf_track_get_last_event(const smf_track_t *track)
786 {
787         smf_event_t *event;
788
789         if (track->number_of_events == 0)
790                 return (NULL);
791        
792         event = smf_track_get_event_by_number(track, track->number_of_events);
793
794         return (event);
795 }
796
797 /**
798  * Searches for track that contains next event, in time order.  In other words,
799  * returns the track that contains event that should be played next.
800  * \return Track with next event or NULL, if there are no events left.
801  */
802 smf_track_t *
803 smf_find_track_with_next_event(smf_t *smf)
804 {
805         int i, min_time = 0;
806         smf_track_t *track = NULL, *min_time_track = NULL;
807
808         /* Find track with event that should be played next. */
809         for (i = 1; i <= smf->number_of_tracks; i++) {
810                 track = smf_get_track_by_number(smf, i);
811
812                 assert(track);
813
814                 /* No more events in this track? */
815                 if (track->next_event_number == -1)
816                         continue;
817
818                 if (track->time_of_next_event < min_time || min_time_track == NULL) {
819                         min_time = track->time_of_next_event;
820                         min_time_track = track;
821                 }
822         }
823
824         return (min_time_track);
825 }
826
827 /**
828   * \return Next event, in time order, or NULL, if there are none left.
829   */
830 smf_event_t *
831 smf_get_next_event(smf_t *smf)
832 {
833         smf_event_t *event;
834         smf_track_t *track = smf_find_track_with_next_event(smf);
835
836         if (track == NULL) {
837 #if 0
838                 g_debug("End of the song.");
839 #endif
840
841                 return (NULL);
842         }
843
844         event = smf_track_get_next_event(track);
845         
846         assert(event != NULL);
847
848         event->track->smf->last_seek_position = -1.0;
849
850         return (event);
851 }
852
853 /**
854   * Advance the "next event counter".  This is functionally the same as calling
855   * smf_get_next_event and ignoring the return value.
856   */
857 void
858 smf_skip_next_event(smf_t *smf)
859 {
860         void *notused;
861
862         notused = smf_get_next_event(smf);
863 }
864
865 /**
866   * \return Next event, in time order, or NULL, if there are none left.  Does
867   * not advance position in song.
868   */
869 smf_event_t *
870 smf_peek_next_event(smf_t *smf)
871 {
872         smf_event_t *event;
873         smf_track_t *track = smf_find_track_with_next_event(smf);
874
875         if (track == NULL) {
876 #if 0
877                 g_debug("End of the song.");
878 #endif
879
880                 return (NULL);
881         }
882
883         event = smf_peek_next_event_from_track(track);
884         
885         assert(event != NULL);
886
887         return (event);
888 }
889
890 /**
891   * Rewinds the SMF.  What that means is, after calling this routine, smf_get_next_event
892   * will return first event in the song.
893   */
894 void
895 smf_rewind(smf_t *smf)
896 {
897         int i;
898         smf_track_t *track = NULL;
899         smf_event_t *event;
900
901         assert(smf);
902
903         smf->last_seek_position = 0.0;
904
905         for (i = 1; i <= smf->number_of_tracks; i++) {
906                 track = smf_get_track_by_number(smf, i);
907
908                 assert(track != NULL);
909
910                 if (track->number_of_events > 0) {
911                         track->next_event_number = 1;
912                         event = smf_peek_next_event_from_track(track);
913                         assert(event);
914                         track->time_of_next_event = event->time_pulses;
915                 } else {
916                         track->next_event_number = -1;
917                         track->time_of_next_event = 0;
918 #if 0
919                         g_warning("Warning: empty track.");
920 #endif
921                 }
922         }
923 }
924
925 /**
926   * Seeks the SMF to the given event.  After calling this routine, smf_get_next_event
927   * will return the event that was the second argument of this call.
928   */
929 int
930 smf_seek_to_event(smf_t *smf, const smf_event_t *target)
931 {
932         smf_event_t *event;
933
934         smf_rewind(smf);
935
936 #if 0
937         g_debug("Seeking to event %d, track %d.", target->event_number, target->track->track_number);
938 #endif
939
940         for (;;) {
941                 event = smf_peek_next_event(smf);
942
943                 /* There can't be NULL here, unless "target" is not in this smf. */
944                 assert(event);
945
946                 if (event != target)
947                         smf_skip_next_event(smf);
948                 else
949                         break;
950         }       
951
952         smf->last_seek_position = event->time_seconds;
953
954         return (0);
955 }
956
957 /**
958   * Seeks the SMF to the given position.  For example, after seeking to 1.0 seconds,
959   * smf_get_next_event will return first event that happens after the first second of song.
960   */
961 int
962 smf_seek_to_seconds(smf_t *smf, double seconds)
963 {
964         smf_event_t *event;
965
966         assert(seconds >= 0.0);
967
968         if (seconds == smf->last_seek_position) {
969 #if 0
970                 g_debug("Avoiding seek to %f seconds.", seconds);
971 #endif
972                 return (0);
973         }
974
975         smf_rewind(smf);
976
977 #if 0
978         g_debug("Seeking to %f seconds.", seconds);
979 #endif
980
981         for (;;) {
982                 event = smf_peek_next_event(smf);
983
984                 if (event == NULL) {
985                         g_critical("Trying to seek past the end of song.");
986                         return (-1);
987                 }
988
989                 if (event->time_seconds < seconds)
990                         smf_skip_next_event(smf);
991                 else
992                         break;
993         }
994
995         smf->last_seek_position = seconds;
996
997         return (0);
998 }
999
1000 /**
1001   * Seeks the SMF to the given position.  For example, after seeking to 10 pulses,
1002   * smf_get_next_event will return first event that happens after the first ten pulses.
1003   */
1004 int
1005 smf_seek_to_pulses(smf_t *smf, int pulses)
1006 {
1007         smf_event_t *event;
1008
1009         assert(pulses >= 0);
1010
1011         smf_rewind(smf);
1012
1013 #if 0
1014         g_debug("Seeking to %d pulses.", pulses);
1015 #endif
1016
1017         for (;;) {
1018                 event = smf_peek_next_event(smf);
1019
1020                 if (event == NULL) {
1021                         g_critical("Trying to seek past the end of song.");
1022                         return (-1);
1023                 }
1024
1025                 if (event->time_pulses < pulses)
1026                         smf_skip_next_event(smf);
1027                 else
1028                         break;
1029         }
1030
1031         smf->last_seek_position = event->time_seconds;
1032
1033         return (0);
1034 }
1035
1036 /**
1037   * \return Length of SMF, in pulses.
1038   */
1039 int
1040 smf_get_length_pulses(const smf_t *smf)
1041 {
1042         int pulses = 0, i;
1043
1044         for (i = 1; i <= smf->number_of_tracks; i++) {
1045                 smf_track_t *track;
1046                 smf_event_t *event;
1047
1048                 track = smf_get_track_by_number(smf, i);
1049                 assert(track);
1050
1051                 event = smf_track_get_last_event(track);
1052                 /* Empty track? */
1053                 if (event == NULL)
1054                         continue;
1055
1056                 if (event->time_pulses > pulses)
1057                         pulses = event->time_pulses;
1058         }
1059
1060         return (pulses);
1061 }
1062
1063 /**
1064   * \return Length of SMF, in seconds.
1065   */
1066 double
1067 smf_get_length_seconds(const smf_t *smf)
1068 {
1069         int i;
1070         double seconds = 0.0;
1071
1072         for (i = 1; i <= smf->number_of_tracks; i++) {
1073                 smf_track_t *track;
1074                 smf_event_t *event;
1075
1076                 track = smf_get_track_by_number(smf, i);
1077                 assert(track);
1078
1079                 event = smf_track_get_last_event(track);
1080                 /* Empty track? */
1081                 if (event == NULL)
1082                         continue;
1083
1084                 if (event->time_seconds > seconds)
1085                         seconds = event->time_seconds;
1086         }
1087
1088         return (seconds);
1089 }
1090
1091 /**
1092   * \return Nonzero, if there are no events in the SMF after this one.
1093   * Note that may be more than one "last event", if they occur at the same time.
1094   */
1095 int
1096 smf_event_is_last(const smf_event_t *event)
1097 {
1098         if (smf_get_length_pulses(event->track->smf) <= event->time_pulses)
1099                 return (1);
1100
1101         return (0);
1102 }
1103
1104 /**
1105   * \return Version of libsmf.
1106   */
1107 const char *
1108 smf_get_version(void)
1109 {
1110         return (SMF_VERSION);
1111 }
1112