new files added
[ardour.git] / libs / ardour / midi_model.cc
1 /*
2     Copyright (C) 2007 Paul Davis 
3         Written by Dave Robillard, 2007
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #define __STDC_LIMIT_MACROS 1
22
23 #include <iostream>
24 #include <algorithm>
25 #include <stdexcept>
26 #include <stdint.h>
27 #include <pbd/enumwriter.h>
28 #include <ardour/midi_model.h>
29 #include <ardour/midi_events.h>
30 #include <ardour/midi_source.h>
31 #include <ardour/types.h>
32 #include <ardour/session.h>
33
34 using namespace std;
35 using namespace ARDOUR;
36
37
38 // Read iterator (const_iterator)
39
40 MidiModel::const_iterator::const_iterator(const MidiModel& model, double t)
41         : _model(&model)
42         , _is_end( (t == DBL_MAX) || model.empty())
43         , _locked( ! _is_end)
44 {
45         //cerr << "Created MIDI iterator @ " << t << " (is end: " << _is_end << ")" << endl;
46         
47         if (_is_end)
48                 return;
49
50         model.read_lock();
51         
52         _note_iter = model.notes().end();
53
54         for (MidiModel::Notes::const_iterator i = model.notes().begin(); i != model.notes().end(); ++i) {
55                 if ((*i)->time() >= t) {
56                         _note_iter = i;
57                         break;
58                 }
59         }
60                         
61         MidiControlIterator earliest_control = make_pair(boost::shared_ptr<AutomationList>(),
62                         make_pair(DBL_MAX, 0.0));
63
64         _control_iters.reserve(model.controls().size());
65         for (Automatable::Controls::const_iterator i = model.controls().begin();
66                         i != model.controls().end(); ++i) {
67
68                 assert(i->first.type() == MidiCCAutomation);
69
70                 double x, y;
71                 bool ret = i->second->list()->rt_safe_earliest_event_unlocked(t, DBL_MAX, x, y);
72                 if (!ret) {
73                         /*cerr << "MIDI Iterator: CC " << i->first.id() << " (size " << i->second->list()->size()
74                                 << ") has no events past " << t << endl;*/
75                         continue;
76                 } 
77
78                 assert(x >= 0);
79                 assert(y >= 0);
80                 assert(y <= UINT8_MAX);
81                 
82                 const MidiControlIterator new_iter = make_pair(i->second->list(), make_pair(x, y));
83                 
84                 //cerr << "MIDI Iterator: CC " << i->first.id() << " added (" << x << ", " << y << ")" << endl;
85                 _control_iters.push_back(new_iter);
86
87                 if (x < earliest_control.second.first) {
88                         earliest_control = new_iter;
89                         _control_iter = _control_iters.end();
90                         --_control_iter;
91                 }
92         }
93
94         if (_note_iter != model.notes().end()) {
95                 _event = MidiEvent((*_note_iter)->on_event(), false);
96                 _active_notes.push(*_note_iter);
97                 ++_note_iter;
98         }
99
100         if (earliest_control.first && earliest_control.second.first < _event.time())
101                 model.control_to_midi_event(_event, earliest_control);
102         else
103                 _control_iter = _control_iters.end();
104
105         if (_event.size() == 0) {
106                 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
107                 _is_end = true;
108                 _model->read_unlock();
109                 _locked = false;
110         } /*else {
111                 printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
112         }*/
113 }
114
115
116 MidiModel::const_iterator::~const_iterator()
117 {
118         if (_locked)
119                 _model->read_unlock();
120 }
121                 
122
123 const MidiModel::const_iterator&
124 MidiModel::const_iterator::operator++()
125 {
126         if (_is_end)
127                 throw std::logic_error("Attempt to iterate past end of MidiModel");
128
129         assert(_event.is_note() || _event.is_cc());
130
131         // Increment past current control event
132         if (_control_iter != _control_iters.end() && _control_iter->first && _event.is_cc()) {
133                 double x, y;
134                 const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
135                                 _control_iter->second.first, DBL_MAX, x, y, false);
136
137                 if (ret) {
138                         //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
139                         _control_iter->second.first = x;
140                         _control_iter->second.second = y;
141                 } else {
142                         //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
143                         _control_iter->first.reset();
144                         _control_iter->second.first = DBL_MAX;
145                 }
146         }
147
148         // Now find and point at the earliest event
149
150         _control_iter = _control_iters.begin();
151
152         for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
153                         i != _control_iters.end(); ++i) {
154                 if (i->second.first < _control_iter->second.first) {
155                         _control_iter = i;
156                 }
157         }
158         
159         enum Type { NIL, NOTE_ON, NOTE_OFF, CC };
160         
161         Type   type = NIL;
162         double t    = 0;
163
164         // Next earliest note on
165         if (_note_iter != _model->notes().end()) {
166                 type = NOTE_ON;
167                 t = (*_note_iter)->time();
168         }
169         
170         // Use the next earliest note off iff it's earlier than the note on
171         if (_model->note_mode() == Sustained && (! _active_notes.empty())) {
172                 if (type == NIL || _active_notes.top()->end_time() <= (*_note_iter)->time()) {
173                         type = NOTE_OFF;
174                         t = _active_notes.top()->end_time();
175                 }
176         }
177         
178         // Use the next earliest controller iff it's earlier than the note event
179         if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
180                 if (type == NIL || _control_iter->second.first < t)
181                         type = CC;
182
183         if (type == NOTE_ON) {
184                 //cerr << "********** MIDI Iterator = note on" << endl;
185                 _event = MidiEvent((*_note_iter)->on_event(), false);
186                 _active_notes.push(*_note_iter);
187                 ++_note_iter;
188         } else if (type == NOTE_OFF) {
189                 //cerr << "********** MIDI Iterator = note off" << endl;
190                 _event = MidiEvent(_active_notes.top()->off_event(), false);
191                 _active_notes.pop();
192         } else if (type == CC) {
193                 //cerr << "********** MIDI Iterator = CC" << endl;
194                 _model->control_to_midi_event(_event, *_control_iter);
195         } else {
196                 //cerr << "********** MIDI Iterator = END" << endl;
197                 _is_end = true;
198                 _model->read_unlock();
199                 _locked = false;
200         }
201
202         assert(_is_end || _event.size() > 0);
203
204         return *this;
205 }
206                 
207
208 bool
209 MidiModel::const_iterator::operator==(const const_iterator& other) const
210 {
211         if (_is_end || other._is_end)
212                 return (_is_end == other._is_end);
213         else
214                 return (_event == other._event);
215 }
216                 
217
218 MidiModel::const_iterator&
219 MidiModel::const_iterator::operator=(const const_iterator& other)
220 {
221         if (_locked && _model != other._model)
222                 _model->read_unlock();
223
224         assert( ! other._event.owns_buffer());
225
226         _model = other._model;
227         _event = other._event;
228         _is_end = other._is_end;
229         _locked = other._locked;
230         _note_iter = other._note_iter;
231         _control_iters = other._control_iters;
232         _control_iter = other._control_iter;
233         
234         assert( ! _event.owns_buffer());
235         
236         if (_locked)
237                 _model->read_lock();
238
239         return *this;
240 }
241
242         
243 // MidiModel
244
245 MidiModel::MidiModel(Session& s, size_t size)
246         : Automatable(s, "midi model")
247         , _notes(size)
248         , _note_mode(Sustained)
249         , _writing(false)
250         , _edited(false)
251         , _end_iter(*this, DBL_MAX)
252         , _next_read(UINT32_MAX)
253         , _read_iter(*this, DBL_MAX)
254 {
255         assert(_end_iter._is_end);
256         assert( ! _end_iter._locked);
257 }
258
259
260 /** Read events in frame range \a start .. \a start+cnt into \a dst,
261  * adding \a stamp_offset to each event's timestamp.
262  * \return number of events written to \a dst
263  */
264 size_t
265 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset) const
266 {
267         //cerr << this << " MM::read @ " << start << " * " << nframes << " + " << stamp_offset << endl;
268         //cerr << this << " MM # notes: " << n_notes() << endl;
269
270         size_t read_events = 0;
271
272         if (start != _next_read) {
273                 _read_iter = const_iterator(*this, (double)start);
274                 //cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
275         } else {
276                 //cerr << "Using cached iterator at " << _next_read << endl;
277         }
278
279         if (_read_iter == end()) {
280                 //cerr << this << " MM::read: at end @ " << _read_iter->time() << endl;
281         } else {
282                 //cerr << this << " MM::read: at " << _read_iter->time() << endl;
283         }
284
285         _next_read = start + nframes;
286
287         while (_read_iter != end() && _read_iter->time() < start + nframes) {
288                 assert(_read_iter->size() > 0);
289                 dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
290                 //cerr << this << " MM::read event @ " << _read_iter->time() << endl;
291                 ++_read_iter;
292                 ++read_events;
293         }
294
295         return read_events;
296 }
297         
298
299 bool
300 MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
301 {
302         if (iter.first->parameter().type() == MidiCCAutomation) {
303                 if (ev.size() < 3)
304                         ev.set_buffer((Byte*)malloc(3), true);
305
306                 assert(iter.first);
307                 assert(iter.first->parameter().id() <= INT8_MAX);
308                 assert(iter.second.second <= INT8_MAX);
309                 ev.buffer()[0] = MIDI_CMD_CONTROL;
310                 ev.buffer()[1] = (Byte)iter.first->parameter().id();
311                 ev.buffer()[2] = (Byte)iter.second.second;
312                 ev.time() = iter.second.first; // x
313                 ev.size() = 3;
314                 return true;
315         } else {
316                 return false;
317         }
318 }
319
320         
321 /** Begin a write of events to the model.
322  *
323  * If \a mode is Sustained, complete notes with duration are constructed as note
324  * on/off events are received.  Otherwise (Percussive), only note on events are
325  * stored; note off events are discarded entirely and all contained notes will
326  * have duration 0.
327  */
328 void
329 MidiModel::start_write()
330 {
331         //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
332         write_lock();
333         _writing = true;
334         _write_notes.clear();
335         write_unlock();
336 }
337
338
339
340 /** Finish a write of events to the model.
341  *
342  * If \a delete_stuck is true and the current mode is Sustained, note on events
343  * that were never resolved with a corresonding note off will be deleted.
344  * Otherwise they will remain as notes with duration 0.
345  */
346 void
347 MidiModel::end_write(bool delete_stuck)
348 {
349         write_lock();
350         assert(_writing);
351         
352         //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
353
354         if (_note_mode == Sustained && delete_stuck) {
355                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
356                         if ((*n)->duration() == 0) {
357                                 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
358                                 n = _notes.erase(n);
359                         } else {
360                                 ++n;
361                         }
362                 }
363         }
364
365         _write_notes.clear();
366         _writing = false;
367         write_unlock();
368 }
369
370
371 /** Append \a in_event to model.  NOT realtime safe.
372  *
373  * Timestamps of events in \a buf are expected to be relative to
374  * the start of this model (t=0) and MUST be monotonically increasing
375  * and MUST be >= the latest event currently in the model.
376  */
377 void
378 MidiModel::append(const MidiEvent& ev)
379 {
380         write_lock();
381
382         assert(_notes.empty() || ev.time() >= _notes.back()->time());
383         assert(_writing);
384
385         if (ev.is_note_on())
386                 append_note_on_unlocked(ev.time(), ev.note(), ev.velocity());
387         else if (ev.is_note_off())
388                 append_note_off_unlocked(ev.time(), ev.note());
389         else if (ev.is_cc())
390                 append_cc_unlocked(ev.time(), ev.cc_number(), ev.cc_value());
391         else
392                 printf("MM Unknown event type %X\n", ev.type());
393         
394         write_unlock();
395 }
396
397
398 void
399 MidiModel::append_note_on_unlocked(double time, uint8_t note_num, uint8_t velocity)
400 {
401         //cerr << "MidiModel " << this << " note " << (int)note_num << " on @ " << time << endl;
402
403         assert(_writing);
404         _notes.push_back(boost::shared_ptr<Note>(new Note(time, 0, note_num, velocity)));
405         if (_note_mode == Sustained) {
406                 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
407                 _write_notes.push_back(_notes.size() - 1);
408         } else {
409                 //cerr << "MM Percussive: NOT appending active note on" << endl;
410         }
411 }
412
413
414 void
415 MidiModel::append_note_off_unlocked(double time, uint8_t note_num)
416 {
417         //cerr << "MidiModel " << this << " note " << (int)note_num << " off @ " << time << endl;
418
419         assert(_writing);
420         if (_note_mode == Percussive) {
421                 //cerr << "MM Ignoring note off (percussive mode)" << endl;
422                 return;
423         } else {
424                 //cerr << "MM Attempting to resolve note off " << (unsigned)(uint8_t)note_num << endl;
425         }
426
427         /* FIXME: make _write_notes fixed size (127 noted) for speed */
428         
429         /* FIXME: note off velocity for that one guy out there who actually has
430          * keys that send it */
431
432         for (WriteNotes::iterator n = _write_notes.begin(); n != _write_notes.end(); ++n) {
433                 Note& note = *_notes[*n].get();
434                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
435                 if (note.note() == note_num) {
436                         assert(time > note.time());
437                         note.set_duration(time - note.time());
438                         _write_notes.erase(n);
439                         //cerr << "MM resolved note, duration: " << note.duration() << endl;
440                         break;
441                 }
442         }
443 }
444
445
446 void
447 MidiModel::append_cc_unlocked(double time, uint8_t number, uint8_t value)
448 {
449         Parameter param(MidiCCAutomation, number);
450         
451         boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
452         //cerr << "MidiModel " << this << "(" << control.get() << ") add CC " << (int)number << " = " << (int)value
453         //      << " @ " << time << endl;
454         control->list()->fast_simple_add(time, (double)value);
455 }
456
457
458 void
459 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
460 {
461         //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
462         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
463         _notes.insert(i, note);
464 }
465
466
467 void
468 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
469 {
470         //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
471         Notes::iterator n = find(_notes.begin(), _notes.end(), note);
472         if (n != _notes.end())
473                 _notes.erase(n);
474 }
475
476 /** Slow!  for debugging only. */
477 #ifndef NDEBUG
478 bool
479 MidiModel::is_sorted() const
480 {
481         bool t = 0;
482         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
483                 if ((*n)->time() < t)
484                         return false;
485                 else
486                         t = (*n)->time();
487
488         return true;
489 }
490 #endif
491
492 /** Start a new command.
493  *
494  * This has no side-effects on the model or Session, the returned command
495  * can be held on to for as long as the caller wishes, or discarded without
496  * formality, until apply_command is called and ownership is taken.
497  */
498 MidiModel::DeltaCommand*
499 MidiModel::new_delta_command(const string name)
500 {
501         DeltaCommand* cmd =  new DeltaCommand(*this, name);
502         return cmd;
503 }
504
505
506 /** Apply a command.
507  *
508  * Ownership of cmd is taken, it must not be deleted by the caller.
509  * The command will constitute one item on the undo stack.
510  */
511 void
512 MidiModel::apply_command(Command* cmd)
513 {
514         _session.begin_reversible_command(cmd->name());
515         (*cmd)();
516         assert(is_sorted());
517         _session.commit_reversible_command(cmd);
518         _edited = true;
519 }
520
521
522 // MidiEditCommand
523
524
525 void
526 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
527 {
528         //cerr << "MEC: apply" << endl;
529
530         _removed_notes.remove(note);
531         _added_notes.push_back(note);
532 }
533
534
535 void
536 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
537 {
538         //cerr << "MEC: remove" << endl;
539
540         _added_notes.remove(note);
541         _removed_notes.push_back(note);
542 }
543
544                 
545 void 
546 MidiModel::DeltaCommand::operator()()
547 {
548         // This could be made much faster by using a priority_queue for added and
549         // removed notes (or sort here), and doing a single iteration over _model
550         
551         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
552         const bool   reset_iter = (_model._read_iter.locked());
553         const double iter_time  = _model._read_iter->time();
554
555         if (reset_iter)
556                 _model._read_iter = _model.end(); // drop read lock
557
558         assert( ! _model._read_iter.locked());
559
560         _model.write_lock();
561         
562         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
563                 _model.add_note_unlocked(*i);
564         
565         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
566                 _model.remove_note_unlocked(*i);
567         
568         _model.write_unlock();
569
570         if (reset_iter)
571                 _model._read_iter = const_iterator(_model, iter_time);
572         
573         _model.ContentsChanged(); /* EMIT SIGNAL */
574 }
575
576
577 void
578 MidiModel::DeltaCommand::undo()
579 {
580         // This could be made much faster by using a priority_queue for added and
581         // removed notes (or sort here), and doing a single iteration over _model
582         
583         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
584         const bool   reset_iter = (_model._read_iter.locked());
585         const double iter_time  = _model._read_iter->time();
586
587         if (reset_iter)
588                 _model._read_iter = _model.end(); // drop read lock
589         
590         assert( ! _model._read_iter.locked());
591
592         _model.write_lock();
593
594         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
595                 _model.remove_note_unlocked(*i);
596         
597         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
598                 _model.add_note_unlocked(*i);
599         
600         _model.write_unlock();
601         
602         if (reset_iter)
603                 _model._read_iter = const_iterator(_model, iter_time);
604         
605         _model.ContentsChanged(); /* EMIT SIGNAL */
606 }
607
608
609 bool
610 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
611 {
612         //cerr << "Writing model to " << source->name() << endl;
613
614         /* This could be done using a temporary MidiRingBuffer and using
615          * MidiModel::read and MidiSource::write, but this is more efficient
616          * and doesn't require any buffer size assumptions (ie it's worth
617          * the code duplication).
618          *
619          * This is also different from read in that note off events are written
620          * regardless of the track mode.  This is so the user can switch a
621          * recorded track (with note durations from some instrument) to percussive,
622          * save, reload, then switch it back to sustained preserving the original
623          * note durations.
624          */
625
626         /* Percussive 
627         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
628                 const MidiEvent& ev = n->on_event();
629                 source->append_event_unlocked(ev);
630         }*/
631
632         read_lock();
633
634         LaterNoteEndComparator cmp;
635         ActiveNotes active_notes(cmp);
636                 
637         // Foreach note
638         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
639
640                 // Write any pending note offs earlier than this note on
641                 while ( ! active_notes.empty() ) {
642                         const boost::shared_ptr<const Note> earliest_off = active_notes.top();
643                         const MidiEvent& off_ev = earliest_off->off_event();
644                         if (off_ev.time() <= (*n)->time()) {
645                                 source->append_event_unlocked(off_ev);
646                                 active_notes.pop();
647                         } else {
648                                 break;
649                         }
650                 }
651
652                 // Write this note on
653                 source->append_event_unlocked((*n)->on_event());
654                 if ((*n)->duration() > 0)
655                         active_notes.push(*n);
656         }
657                 
658         // Write any trailing note offs
659         while ( ! active_notes.empty() ) {
660                 source->append_event_unlocked(active_notes.top()->off_event());
661                 active_notes.pop();
662         }
663
664         _edited = false;
665         
666         read_unlock();
667
668         return true;
669 }
670
671 XMLNode&
672 MidiModel::get_state()
673 {
674         XMLNode *node = new XMLNode("MidiModel");
675         return *node;
676 }
677