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