44416713f8d3b8f2322870aac09f2d89c0a7bb09
[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         _next_read = start + nframes;
280
281         while (_read_iter != end() && _read_iter->time() < start + nframes) {
282                 assert(_read_iter->size() > 0);
283                 dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
284                 //cerr << this << " MM::read event @ " << _read_iter->time() << endl;
285                 ++_read_iter;
286                 ++read_events;
287         }
288
289         return read_events;
290 }
291         
292
293 bool
294 MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
295 {
296         if (iter.first->parameter().type() == MidiCCAutomation) {
297                 if (ev.size() < 3)
298                         ev.set_buffer((Byte*)malloc(3), true);
299
300                 assert(iter.first);
301                 assert(iter.first->parameter().channel() < 16);
302                 assert(iter.first->parameter().id() <= INT8_MAX);
303                 assert(iter.second.second <= INT8_MAX);
304                 ev.buffer()[0] = MIDI_CMD_CONTROL + iter.first->parameter().channel();
305                 ev.buffer()[1] = (Byte)iter.first->parameter().id();
306                 ev.buffer()[2] = (Byte)iter.second.second;
307                 ev.time() = iter.second.first; // x
308                 ev.size() = 3;
309                 return true;
310         } else {
311                 return false;
312         }
313 }
314
315         
316 /** Begin a write of events to the model.
317  *
318  * If \a mode is Sustained, complete notes with duration are constructed as note
319  * on/off events are received.  Otherwise (Percussive), only note on events are
320  * stored; note off events are discarded entirely and all contained notes will
321  * have duration 0.
322  */
323 void
324 MidiModel::start_write()
325 {
326         //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
327         write_lock();
328         _writing = true;
329         for (int i = 0; i < 16; ++i)
330                 _write_notes[i].clear();
331         write_unlock();
332 }
333
334
335
336 /** Finish a write of events to the model.
337  *
338  * If \a delete_stuck is true and the current mode is Sustained, note on events
339  * that were never resolved with a corresonding note off will be deleted.
340  * Otherwise they will remain as notes with duration 0.
341  */
342 void
343 MidiModel::end_write(bool delete_stuck)
344 {
345         write_lock();
346         assert(_writing);
347         
348         //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
349
350         if (_note_mode == Sustained && delete_stuck) {
351                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
352                         if ((*n)->duration() == 0) {
353                                 cerr << "WARNING: Stuck note lost: " << (*n)->note() << endl;
354                                 n = _notes.erase(n);
355                         } else {
356                                 ++n;
357                         }
358                 }
359         }
360
361         for (int i = 0; i < 16; ++i) {
362                 if (!_write_notes[i].empty()) {
363                         cerr << "WARNING: MidiModel::end_write: Channel " << i << " has "
364                                         << _write_notes[i].size() << " stuck notes" << endl;
365                 }
366                 _write_notes[i].clear();
367         }
368         
369         _writing = false;
370         write_unlock();
371 }
372
373
374 /** Append \a in_event to model.  NOT realtime safe.
375  *
376  * Timestamps of events in \a buf are expected to be relative to
377  * the start of this model (t=0) and MUST be monotonically increasing
378  * and MUST be >= the latest event currently in the model.
379  */
380 void
381 MidiModel::append(const MidiEvent& ev)
382 {
383         write_lock();
384
385         assert(_notes.empty() || ev.time() >= _notes.back()->time());
386         assert(_writing);
387
388         if (ev.is_note_on())
389                 append_note_on_unlocked(ev.channel(), ev.time(), ev.note(), ev.velocity());
390         else if (ev.is_note_off())
391                 append_note_off_unlocked(ev.channel(), ev.time(), ev.note());
392         else if (ev.is_cc())
393                 append_cc_unlocked(ev.channel(), ev.time(), ev.cc_number(), ev.cc_value());
394         else
395                 printf("MM Unknown event type %X\n", ev.type());
396         
397         write_unlock();
398 }
399
400
401 void
402 MidiModel::append_note_on_unlocked(uint8_t chan, double time, uint8_t note_num, uint8_t velocity)
403 {
404         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
405                         " note " << (int)note_num << " on @ " << time << endl;*/
406
407         assert(chan < 16);
408         assert(_writing);
409
410         _notes.push_back(boost::shared_ptr<Note>(new Note(chan, time, 0, note_num, velocity)));
411         if (_note_mode == Sustained) {
412                 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
413                 _write_notes[chan].push_back(_notes.size() - 1);
414         }/* else {
415                 cerr << "MM Percussive: NOT appending active note on" << endl;
416         }*/
417 }
418
419
420 void
421 MidiModel::append_note_off_unlocked(uint8_t chan, double time, uint8_t note_num)
422 {
423         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
424                         " note " << (int)note_num << " off @ " << time << endl;*/
425
426         assert(chan < 16);
427         assert(_writing);
428
429         if (_note_mode == Percussive) {
430                 cerr << "MidiModel Ignoring note off (percussive mode)" << endl;
431                 return;
432         }
433
434         /* FIXME: make _write_notes fixed size (127 noted) for speed */
435         
436         /* FIXME: note off velocity for that one guy out there who actually has
437          * keys that send it */
438
439         bool resolved = false;
440
441         for (WriteNotes::iterator n = _write_notes[chan].begin(); n != _write_notes[chan].end(); ++n) {
442                 Note& note = *_notes[*n].get();
443                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
444                 if (note.note() == note_num) {
445                         assert(time >= note.time());
446                         note.set_duration(time - note.time());
447                         _write_notes[chan].erase(n);
448                         //cerr << "MM resolved note, duration: " << note.duration() << endl;
449                         resolved = true;
450                         break;
451                 }
452         }
453
454         if (!resolved)
455                 cerr << "MidiModel " << this << " spurious note off chan " << (int)chan
456                         << ", note " << (int)note_num << " @ " << time << endl;
457 }
458
459
460 void
461 MidiModel::append_cc_unlocked(uint8_t chan, double time, uint8_t number, uint8_t value)
462 {
463         /*cerr << "MidiModel " << this << " chan " << (int)chan <<
464                         " CC " << (int)number << " = " << (int)value << " @ " << time << endl;*/
465         
466         assert(chan < 16);
467         assert(_writing);
468         
469         Parameter param(MidiCCAutomation, number, chan);
470         
471         boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
472         control->list()->fast_simple_add(time, (double)value);
473 }
474
475
476 void
477 MidiModel::add_note_unlocked(const boost::shared_ptr<Note> note)
478 {
479         //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
480         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
481         _notes.insert(i, note);
482 }
483
484
485 void
486 MidiModel::remove_note_unlocked(const boost::shared_ptr<const Note> note)
487 {
488         //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
489         Notes::iterator n = find(_notes.begin(), _notes.end(), note);
490         if (n != _notes.end())
491                 _notes.erase(n);
492 }
493
494 /** Slow!  for debugging only. */
495 #ifndef NDEBUG
496 bool
497 MidiModel::is_sorted() const
498 {
499         bool t = 0;
500         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
501                 if ((*n)->time() < t)
502                         return false;
503                 else
504                         t = (*n)->time();
505
506         return true;
507 }
508 #endif
509
510 /** Start a new command.
511  *
512  * This has no side-effects on the model or Session, the returned command
513  * can be held on to for as long as the caller wishes, or discarded without
514  * formality, until apply_command is called and ownership is taken.
515  */
516 MidiModel::DeltaCommand*
517 MidiModel::new_delta_command(const string name)
518 {
519         DeltaCommand* cmd =  new DeltaCommand(*this, name);
520         return cmd;
521 }
522
523
524 /** Apply a command.
525  *
526  * Ownership of cmd is taken, it must not be deleted by the caller.
527  * The command will constitute one item on the undo stack.
528  */
529 void
530 MidiModel::apply_command(Command* cmd)
531 {
532         _session.begin_reversible_command(cmd->name());
533         (*cmd)();
534         assert(is_sorted());
535         _session.commit_reversible_command(cmd);
536         _edited = true;
537 }
538
539
540 // MidiEditCommand
541
542
543 void
544 MidiModel::DeltaCommand::add(const boost::shared_ptr<Note> note)
545 {
546         //cerr << "MEC: apply" << endl;
547
548         _removed_notes.remove(note);
549         _added_notes.push_back(note);
550 }
551
552
553 void
554 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Note> note)
555 {
556         //cerr << "MEC: remove" << endl;
557
558         _added_notes.remove(note);
559         _removed_notes.push_back(note);
560 }
561
562                 
563 void 
564 MidiModel::DeltaCommand::operator()()
565 {
566         // This could be made much faster by using a priority_queue for added and
567         // removed notes (or sort here), and doing a single iteration over _model
568         
569         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
570         const bool   reset_iter = (_model._read_iter.locked());
571         const double iter_time  = _model._read_iter->time();
572
573         if (reset_iter)
574                 _model._read_iter = _model.end(); // drop read lock
575
576         assert( ! _model._read_iter.locked());
577
578         _model.write_lock();
579         
580         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
581                 _model.add_note_unlocked(*i);
582         
583         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
584                 _model.remove_note_unlocked(*i);
585         
586         _model.write_unlock();
587
588         if (reset_iter)
589                 _model._read_iter = const_iterator(_model, iter_time);
590         
591         _model.ContentsChanged(); /* EMIT SIGNAL */
592 }
593
594
595 void
596 MidiModel::DeltaCommand::undo()
597 {
598         // This could be made much faster by using a priority_queue for added and
599         // removed notes (or sort here), and doing a single iteration over _model
600         
601         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
602         const bool   reset_iter = (_model._read_iter.locked());
603         const double iter_time  = _model._read_iter->time();
604
605         if (reset_iter)
606                 _model._read_iter = _model.end(); // drop read lock
607         
608         assert( ! _model._read_iter.locked());
609
610         _model.write_lock();
611
612         for (std::list< boost::shared_ptr<Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
613                 _model.remove_note_unlocked(*i);
614         
615         for (std::list< boost::shared_ptr<Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
616                 _model.add_note_unlocked(*i);
617         
618         _model.write_unlock();
619         
620         if (reset_iter)
621                 _model._read_iter = const_iterator(_model, iter_time);
622         
623         _model.ContentsChanged(); /* EMIT SIGNAL */
624 }
625
626
627 bool
628 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
629 {
630         //cerr << "Writing model to " << source->name() << endl;
631
632         /* This could be done using a temporary MidiRingBuffer and using
633          * MidiModel::read and MidiSource::write, but this is more efficient
634          * and doesn't require any buffer size assumptions (ie it's worth
635          * the code duplication).
636          *
637          * This is also different from read in that note off events are written
638          * regardless of the track mode.  This is so the user can switch a
639          * recorded track (with note durations from some instrument) to percussive,
640          * save, reload, then switch it back to sustained preserving the original
641          * note durations.
642          */
643
644         /* Percussive 
645         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
646                 const MidiEvent& ev = n->on_event();
647                 source->append_event_unlocked(ev);
648         }*/
649
650         read_lock();
651
652         LaterNoteEndComparator cmp;
653         ActiveNotes active_notes(cmp);
654                 
655         // Foreach note
656         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
657
658                 // Write any pending note offs earlier than this note on
659                 while ( ! active_notes.empty() ) {
660                         const boost::shared_ptr<const Note> earliest_off = active_notes.top();
661                         const MidiEvent& off_ev = earliest_off->off_event();
662                         if (off_ev.time() <= (*n)->time()) {
663                                 source->append_event_unlocked(off_ev);
664                                 active_notes.pop();
665                         } else {
666                                 break;
667                         }
668                 }
669
670                 // Write this note on
671                 source->append_event_unlocked((*n)->on_event());
672                 if ((*n)->duration() > 0)
673                         active_notes.push(*n);
674         }
675                 
676         // Write any trailing note offs
677         while ( ! active_notes.empty() ) {
678                 source->append_event_unlocked(active_notes.top()->off_event());
679                 active_notes.pop();
680         }
681
682         _edited = false;
683         
684         read_unlock();
685
686         return true;
687 }
688
689 XMLNode&
690 MidiModel::get_state()
691 {
692         XMLNode *node = new XMLNode("MidiModel");
693         return *node;
694 }
695