Fix some clang warnings (argument with 'nonnull' attribute passed null)
[ardour.git] / libs / evoral / src / SMF.cpp
1 /* This file is part of Evoral.
2  * Copyright (C) 2008 David Robillard <http://drobilla.net>
3  * Copyright (C) 2000-2008 Paul Davis
4  * Author: Hans Baier
5  *
6  * Evoral is free software; you can redistribute it and/or modify it under the
7  * terms of the GNU General Public License as published by the Free Software
8  * Foundation; either version 2 of the License, or (at your option) any later
9  * version.
10  *
11  * Evoral is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <iostream>
24 #include <stdint.h>
25
26 #include <glib/gstdio.h>
27
28 #include "libsmf/smf.h"
29
30 #include "evoral/Event.hpp"
31 #include "evoral/SMF.hpp"
32 #include "evoral/midi_util.h"
33
34 #ifdef COMPILER_MSVC
35 extern double round(double x);
36 #endif
37
38 using namespace std;
39
40 namespace Evoral {
41
42 SMF::SMF()
43         : _smf (0)
44         , _smf_track (0)
45         , _empty (true)
46         , _type0 (false)
47         {};
48
49 SMF::~SMF()
50 {
51         close ();
52 }
53
54 uint16_t
55 SMF::num_tracks() const
56 {
57         Glib::Threads::Mutex::Lock lm (_smf_lock);
58         return _smf ? _smf->number_of_tracks : 0;
59 }
60
61 uint16_t
62 SMF::ppqn() const
63 {
64         Glib::Threads::Mutex::Lock lm (_smf_lock);
65         return _smf->ppqn;
66 }
67
68 /** Seek to the specified track (1-based indexing)
69  * \return 0 on success
70  */
71 int
72 SMF::seek_to_track(int track)
73 {
74         Glib::Threads::Mutex::Lock lm (_smf_lock);
75         _smf_track = smf_get_track_by_number(_smf, track);
76         if (_smf_track != NULL) {
77                 _smf_track->next_event_number = (_smf_track->number_of_events == 0) ? 0 : 1;
78                 return 0;
79         } else {
80                 return -1;
81         }
82 }
83
84 /** Attempt to open the SMF file just to see if it is valid.
85  *
86  * \return  true on success
87  *          false on failure
88  */
89 bool
90 SMF::test(const std::string& path)
91 {
92         FILE* f = g_fopen(path.c_str(), "r");
93         if (f == 0) {
94                 return false;
95         }
96
97         smf_t* test_smf = smf_load(f);
98         fclose(f);
99
100         const bool success = (test_smf != NULL);
101         smf_delete(test_smf);
102
103         return success;
104 }
105
106 /** Attempt to open the SMF file for reading and/or writing.
107  *
108  * \return  0 on success
109  *         -1 if the file can not be opened or created
110  *         -2 if the file exists but specified track does not exist
111  */
112 int
113 SMF::open(const std::string& path, int track) THROW_FILE_ERROR
114 {
115         Glib::Threads::Mutex::Lock lm (_smf_lock);
116
117         _type0 = false;
118         _type0channels.clear ();
119
120         assert(track >= 1);
121         if (_smf) {
122                 smf_delete(_smf);
123         }
124
125         FILE* f = g_fopen(path.c_str(), "r");
126         if (f == 0) {
127                 return -1;
128         } else if ((_smf = smf_load(f)) == 0) {
129                 fclose(f);
130                 return -1;
131         } else if ((_smf_track = smf_get_track_by_number(_smf, track)) == 0) {
132                 fclose(f);
133                 return -2;
134         }
135
136         //cerr << "Track " << track << " # events: " << _smf_track->number_of_events << endl;
137         if (_smf_track->number_of_events == 0) {
138                 _smf_track->next_event_number = 0;
139                 _empty = true;
140         } else {
141                 _smf_track->next_event_number = 1;
142                 _empty = false;
143         }
144
145         fclose(f);
146
147         lm.release ();
148         if (_smf->format == 0 && _smf->number_of_tracks == 1 && !_empty) {
149                 // type-0 file: scan file for # of used channels.
150                 int ret;
151                 uint32_t delta_t = 0;
152                 uint32_t size    = 0;
153                 uint8_t* buf     = NULL;
154                 event_id_t event_id = 0;
155                 seek_to_start();
156                 while ((ret = read_event (&delta_t, &size, &buf, &event_id)) >= 0) {
157                         if (ret == 0) {
158                                 continue;
159                         }
160                         if (size == 0) {
161                                 break;
162                         }
163                         uint8_t type = buf[0] & 0xf0;
164                         uint8_t chan = buf[0] & 0x0f;
165                         if (type < 0x80 || type > 0xE0) {
166                                 continue;
167                         }
168                         _type0channels.insert(chan);
169                 }
170                 _type0 = true;
171                 seek_to_start();
172         }
173         return 0;
174 }
175
176
177 /** Attempt to create a new SMF file for reading and/or writing.
178  *
179  * \return  0 on success
180  *         -1 if the file can not be created
181  *         -2 if the track can not be created
182  */
183 int
184 SMF::create(const std::string& path, int track, uint16_t ppqn) THROW_FILE_ERROR
185 {
186         Glib::Threads::Mutex::Lock lm (_smf_lock);
187
188         assert(track >= 1);
189         if (_smf) {
190                 smf_delete(_smf);
191         }
192
193         _smf = smf_new();
194
195         if (_smf == NULL) {
196                 return -1;
197         }
198
199         if (smf_set_ppqn(_smf, ppqn) != 0) {
200                 return -1;
201         }
202
203         for (int i = 0; i < track; ++i) {
204                 _smf_track = smf_track_new();
205                 if (!_smf_track) {
206                         return -2;
207                 }
208                 smf_add_track(_smf, _smf_track);
209         }
210
211         _smf_track = smf_get_track_by_number(_smf, track);
212         if (!_smf_track)
213                 return -2;
214
215         _smf_track->next_event_number = 0;
216
217         {
218                 /* put a stub file on disk */
219
220                 FILE* f = g_fopen (path.c_str(), "w+");
221                 if (f == 0) {
222                         return -1;
223                 }
224
225                 if (smf_save (_smf, f)) {
226                         fclose (f);
227                         return -1;
228                 }
229                 fclose (f);
230         }
231
232         _empty = true;
233         _type0 = false;
234         _type0channels.clear ();
235
236         return 0;
237 }
238
239 void
240 SMF::close() THROW_FILE_ERROR
241 {
242         Glib::Threads::Mutex::Lock lm (_smf_lock);
243
244         if (_smf) {
245                 smf_delete(_smf);
246                 _smf = 0;
247                 _smf_track = 0;
248                 _type0 = false;
249                 _type0channels.clear ();
250         }
251 }
252
253 void
254 SMF::seek_to_start() const
255 {
256         Glib::Threads::Mutex::Lock lm (_smf_lock);
257         if (_smf_track) {
258                 _smf_track->next_event_number = std::min(_smf_track->number_of_events, (size_t)1);
259         } else {
260                 cerr << "WARNING: SMF seek_to_start() with no track" << endl;
261         }
262 }
263
264 /** Read an event from the current position in file.
265  *
266  * File position MUST be at the beginning of a delta time, or this will die very messily.
267  * ev.buffer must be of size ev.size, and large enough for the event.  The returned event
268  * will have it's time field set to it's delta time, in SMF tempo-based ticks, using the
269  * rate given by ppqn() (it is the caller's responsibility to calculate a real time).
270  *
271  * \a buf must be a pointer to a buffer allocated with malloc, or a pointer to NULL.
272  * \a size must be the capacity of \a buf.  If it is not large enough, \a buf will
273  * be reallocated and *size will be set to the new size of buf.
274  *
275  * if the event is a meta-event and is an Evoral Note ID, then \a note_id will be set
276  * to the value of the NoteID; otherwise, meta-events will set \a note_id to -1.
277  *
278  * \return event length (including status byte) on success, 0 if event was
279  * a meta event, or -1 on EOF (or end of track).
280  */
281 int
282 SMF::read_event(uint32_t* delta_t, uint32_t* size, uint8_t** buf, event_id_t* note_id) const
283 {
284         Glib::Threads::Mutex::Lock lm (_smf_lock);
285
286         smf_event_t* event;
287
288         assert(delta_t);
289         assert(size);
290         assert(buf);
291         assert(note_id);
292
293         if ((event = smf_track_get_next_event(_smf_track)) != NULL) {
294
295                 *delta_t = event->delta_time_pulses;
296
297                 if (smf_event_is_metadata(event)) {
298                         *note_id = -1; // "no note id in this meta-event */
299
300                         if (event->midi_buffer[1] == 0x7f) { // Sequencer-specific
301
302                                 uint32_t evsize;
303                                 uint32_t lenlen;
304
305                                 if (smf_extract_vlq (&event->midi_buffer[2], event->midi_buffer_length-2, &evsize, &lenlen) == 0) {
306
307                                         if (event->midi_buffer[2+lenlen] == 0x99 &&  // Evoral
308                                             event->midi_buffer[3+lenlen] == 0x1) { // Evoral Note ID
309
310                                                 uint32_t id;
311                                                 uint32_t idlen;
312
313                                                 if (smf_extract_vlq (&event->midi_buffer[4+lenlen], event->midi_buffer_length-(4+lenlen), &id, &idlen) == 0) {
314                                                         *note_id = id;
315                                                 }
316                                         }
317                                 }
318                         }
319                         return 0; /* this is a meta-event */
320                 }
321
322                 int event_size = event->midi_buffer_length;
323                 assert(event_size > 0);
324
325                 // Make sure we have enough scratch buffer
326                 if (*size < (unsigned)event_size) {
327                         *buf = (uint8_t*)realloc(*buf, event_size);
328                 }
329                 assert (*buf);
330                 memcpy(*buf, event->midi_buffer, size_t(event_size));
331                 *size = event_size;
332                 if (((*buf)[0] & 0xF0) == 0x90 && (*buf)[2] == 0) {
333                         /* normalize note on with velocity 0 to proper note off */
334                         (*buf)[0] = 0x80 | ((*buf)[0] & 0x0F);  /* note off */
335                         (*buf)[2] = 0x40;  /* default velocity */
336                 }
337
338                 if (!midi_event_is_valid(*buf, *size)) {
339                         cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
340                         *size = 0;
341                         return -1;
342                 }
343
344                 /* printf("SMF::read_event @ %u: ", *delta_t);
345                    for (size_t i = 0; i < *size; ++i) {
346                    printf("%X ", (*buf)[i]);
347                    } printf("\n") */
348
349                 return event_size;
350         } else {
351                 return -1;
352         }
353 }
354
355 void
356 SMF::append_event_delta(uint32_t delta_t, uint32_t size, const uint8_t* buf, event_id_t note_id)
357 {
358         Glib::Threads::Mutex::Lock lm (_smf_lock);
359
360         if (size == 0) {
361                 return;
362         }
363
364         /* printf("SMF::append_event_delta @ %u:", delta_t);
365            for (size_t i = 0; i < size; ++i) {
366            printf("%X ", buf[i]);
367            } printf("\n"); */
368
369         if (!midi_event_is_valid(buf, size)) {
370                 cerr << "WARNING: SMF ignoring illegal MIDI event" << endl;
371                 return;
372         }
373
374         smf_event_t* event;
375
376         /* XXX july 2010: currently only store event ID's for notes, program changes and bank changes
377          */
378
379         uint8_t const c = buf[0] & 0xf0;
380         bool const store_id = (
381                 c == MIDI_CMD_NOTE_ON ||
382                 c == MIDI_CMD_NOTE_OFF ||
383                 c == MIDI_CMD_NOTE_PRESSURE ||
384                 c == MIDI_CMD_PGM_CHANGE ||
385                 (c == MIDI_CMD_CONTROL && (buf[1] == MIDI_CTL_MSB_BANK || buf[1] == MIDI_CTL_LSB_BANK))
386                                );
387
388         if (store_id && note_id >= 0) {
389                 int idlen;
390                 int lenlen;
391                 uint8_t idbuf[16];
392                 uint8_t lenbuf[16];
393
394                 event = smf_event_new ();
395                 assert(event != NULL);
396
397                 /* generate VLQ representation of note ID */
398                 idlen = smf_format_vlq (idbuf, sizeof(idbuf), note_id);
399
400                 /* generate VLQ representation of meta event length,
401                    which is the idlen + 2 bytes (Evoral type ID plus Note ID type)
402                 */
403
404                 lenlen = smf_format_vlq (lenbuf, sizeof(lenbuf), idlen+2);
405
406                 event->midi_buffer_length = 2 + lenlen + 2 + idlen;
407                 /* this should be allocated by malloc(3) because libsmf will
408                    call free(3) on it
409                 */
410                 event->midi_buffer = (uint8_t*) malloc (sizeof(uint8_t) * event->midi_buffer_length);
411
412                 event->midi_buffer[0] = 0xff; // Meta-event
413                 event->midi_buffer[1] = 0x7f; // Sequencer-specific
414                 memcpy (&event->midi_buffer[2], lenbuf, lenlen);
415                 event->midi_buffer[2+lenlen] = 0x99; // Evoral type ID
416                 event->midi_buffer[3+lenlen] = 0x1;  // Evoral type Note ID
417                 memcpy (&event->midi_buffer[4+lenlen], idbuf, idlen);
418
419                 assert(_smf_track);
420                 smf_track_add_event_delta_pulses(_smf_track, event, 0);
421         }
422
423         event = smf_event_new_from_pointer(buf, size);
424         assert(event != NULL);
425
426         assert(_smf_track);
427         smf_track_add_event_delta_pulses(_smf_track, event, delta_t);
428         _empty = false;
429 }
430
431 void
432 SMF::begin_write()
433 {
434         Glib::Threads::Mutex::Lock lm (_smf_lock);
435
436         assert(_smf_track);
437         smf_track_delete(_smf_track);
438
439         _smf_track = smf_track_new();
440         assert(_smf_track);
441
442         smf_add_track(_smf, _smf_track);
443         assert(_smf->number_of_tracks == 1);
444 }
445
446 void
447 SMF::end_write(string const & path) THROW_FILE_ERROR
448 {
449         Glib::Threads::Mutex::Lock lm (_smf_lock);
450
451         if (!_smf) {
452                 return;
453         }
454
455         FILE* f = g_fopen (path.c_str(), "w+");
456         if (f == 0) {
457                 throw FileError (path);
458         }
459
460         if (smf_save(_smf, f) != 0) {
461                 fclose(f);
462                 throw FileError (path);
463         }
464
465         fclose(f);
466 }
467
468 double
469 SMF::round_to_file_precision (double val) const
470 {
471         double div = ppqn();
472
473         return round (val * div) / div;
474 }
475
476 void
477 SMF::track_names(vector<string>& names) const
478 {
479         if (!_smf) {
480                 return;
481         }
482
483         names.clear ();
484
485         Glib::Threads::Mutex::Lock lm (_smf_lock);
486
487         for (uint16_t n = 0; n < _smf->number_of_tracks; ++n) {
488                 smf_track_t* trk = smf_get_track_by_number (_smf, n+1);
489                 if (!trk) {
490                         names.push_back (string());
491                 } else {
492                         if (trk->name) {
493                                 names.push_back (trk->name);
494                         } else {
495                                 names.push_back (string());
496                         }
497                 }
498         }
499 }
500
501 void
502 SMF::instrument_names(vector<string>& names) const
503 {
504         if (!_smf) {
505                 return;
506         }
507
508         names.clear ();
509
510         Glib::Threads::Mutex::Lock lm (_smf_lock);
511
512         for (uint16_t n = 0; n < _smf->number_of_tracks; ++n) {
513                 smf_track_t* trk = smf_get_track_by_number (_smf, n+1);
514                 if (!trk) {
515                         names.push_back (string());
516                 } else {
517                         if (trk->instrument) {
518                                 names.push_back (trk->instrument);
519                         } else {
520                                 names.push_back (string());
521                         }
522                 }
523         }
524 }
525
526 SMF::Tempo::Tempo (smf_tempo_t* smft)
527         : time_pulses (smft->time_pulses)
528         , time_seconds (smft->time_seconds)
529         , microseconds_per_quarter_note (smft->microseconds_per_quarter_note)
530         , numerator (smft->numerator)
531         , denominator (smft->denominator)
532         , clocks_per_click (smft->clocks_per_click)
533         , notes_per_note (smft->notes_per_note)
534 {
535 }
536
537 int
538 SMF::num_tempos () const
539 {
540         assert (_smf);
541         return smf_get_tempo_count (_smf);
542 }
543
544 SMF::Tempo*
545 SMF::tempo_at_smf_pulse (size_t smf_pulse) const
546 {
547         smf_tempo_t* t = smf_get_tempo_by_seconds (_smf, smf_pulse);
548         if (!t) {
549                 return 0;
550         }
551         return new Tempo (t);
552 }
553
554 SMF::Tempo*
555 SMF::tempo_at_seconds (double seconds) const
556 {
557         smf_tempo_t* t = smf_get_tempo_by_seconds (_smf, seconds);
558         if (!t) {
559                 return 0;
560         }
561         return new Tempo (t);
562 }
563
564 SMF::Tempo*
565 SMF::nth_tempo (size_t n) const
566 {
567         assert (_smf);
568
569         smf_tempo_t* t = smf_get_tempo_by_number (_smf, n);
570         if (!t) {
571                 return 0;
572         }
573
574         return new Tempo (t);
575 }
576
577 } // namespace Evoral