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