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