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