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