Fix note separator lines adaptation to changing track height.
[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                 ++_note_iter;
97         }
98
99         if (earliest_control.first && earliest_control.second.first < _event.time())
100                 model.control_to_midi_event(_event, earliest_control);
101         else
102                 _control_iter = _control_iters.end();
103
104         if (_event.size() == 0) {
105                 //cerr << "Created MIDI iterator @ " << t << " is at end." << endl;
106                 _is_end = true;
107                 _model->read_unlock();
108                 _locked = false;
109         //} else {
110         //      printf("MIDI Iterator = %X @ %lf\n", _event.type(), _event.time());
111         }
112 }
113
114
115 MidiModel::const_iterator::~const_iterator()
116 {
117         if (_locked)
118                 _model->read_unlock();
119 }
120                 
121
122 const MidiModel::const_iterator&
123 MidiModel::const_iterator::operator++()
124 {
125         if (_is_end)
126                 throw std::logic_error("Attempt to iterate past end of MidiModel");
127
128         assert(_event.is_note() || _event.is_cc());
129
130         // Increment past current control event
131         if (_control_iter->first && _event.is_cc()) {
132                 double x, y;
133                 const bool ret = _control_iter->first->rt_safe_earliest_event_unlocked(
134                                 _control_iter->second.first, DBL_MAX, x, y, false);
135
136                 if (ret) {
137                         //cerr << "Incremented " << _control_iter->first->parameter().id() << " to " << x << endl;
138                         _control_iter->second.first = x;
139                         _control_iter->second.second = y;
140                 } else {
141                         //cerr << "Hit end of " << _control_iter->first->parameter().id() << endl;
142                         _control_iter->first.reset();
143                         _control_iter->second.first = DBL_MAX;
144                 }
145         }
146
147         // Now find and point at the earliest event
148
149         _control_iter = _control_iters.begin();
150
151         for (std::vector<MidiControlIterator>::iterator i = _control_iters.begin();
152                         i != _control_iters.end(); ++i) {
153                 if (i->second.first < _control_iter->second.first) {
154                         _control_iter = i;
155                 }
156         }
157         
158         enum Type { NIL, NOTE, CC };
159         Type type = NIL;
160
161         if (_note_iter != _model->notes().end())
162                 type = NOTE;
163         
164         if (_control_iter != _control_iters.end() && _control_iter->second.first != DBL_MAX)
165                 if (_note_iter == _model->notes().end() || _control_iter->second.first < _note_iter->time())
166                         type = CC;
167
168         if (type == NOTE) {
169                 //cerr << "MIDI Iterator = note" << endl;
170                 _event = MidiEvent(_note_iter->on_event(), false);
171                 ++_note_iter;
172         } else if (type == CC) {
173                 //cerr << "MIDI Iterator = CC" << endl;
174                 _model->control_to_midi_event(_event, *_control_iter);
175         } else {
176                 //cerr << "MIDI Iterator = NIL" << endl;
177                 _is_end = true;
178                 _model->read_unlock();
179                 _locked = false;
180         }
181
182         return *this;
183 }
184                 
185
186 bool
187 MidiModel::const_iterator::operator==(const const_iterator& other) const
188 {
189         if (_is_end)
190                 if (other._is_end)
191                         return true;
192                 else
193                         return false;
194         else
195                 return (_event == other._event);
196 }
197
198         
199 // MidiModel
200
201 MidiModel::MidiModel(Session& s, size_t size)
202         : Automatable(s, "midi model")
203         , _notes(size)
204         , _note_mode(Sustained)
205         , _writing(false)
206         , _edited(false)
207         //, _active_notes(LaterNoteEndComparator())
208         , _end_iter(*this, DBL_MAX)
209         , _next_read(UINT32_MAX)
210         , _read_iter(*this, DBL_MAX)
211 {
212 }
213
214
215 /** Read events in frame range \a start .. \a start+cnt into \a dst,
216  * adding \a stamp_offset to each event's timestamp.
217  * \return number of events written to \a dst
218  */
219 size_t
220 MidiModel::read(MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset) const
221 {
222         size_t read_events = 0;
223
224         if (start != _next_read) {
225                 _read_iter = const_iterator(*this, (double)start);
226         //      cerr << "Repositioning iterator from " << _next_read << " to " << start << endl;
227         //} else {
228         //      cerr << "Using cached iterator at " << _next_read << endl;
229         }
230
231         _next_read = start + nframes;
232
233         while (_read_iter != end() && _read_iter->time() < start + nframes) {
234                 dst.write(_read_iter->time() + stamp_offset, _read_iter->size(), _read_iter->buffer());
235                 ++_read_iter;
236                 ++read_events;
237         }
238
239 #if 0
240         /* FIXME: cache last lookup value to avoid O(n) search every time */
241
242         if (_note_mode == Sustained) {
243
244                 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
245
246                         while ( ! _active_notes.empty() ) {
247                                 const Note* const earliest_off = _active_notes.top();
248                                 const MidiEvent&  off_ev       = earliest_off->off_event();
249                                 if (off_ev.time() < start + nframes && off_ev.time() <= n->time()) {
250                                         dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
251                                         _active_notes.pop();
252                                         ++read_events;
253                                 } else {
254                                         break;
255                                 }
256                         }
257
258                         if (n->time() >= start + nframes)
259                                 break;
260
261                         // Note on
262                         if (n->time() >= start) {
263                                 const MidiEvent& on_ev = n->on_event();
264                                 dst.write(on_ev.time() + stamp_offset, on_ev.size(), on_ev.buffer());
265                                 _active_notes.push(&(*n));
266                                 ++read_events;
267                         }
268
269                 }
270                         
271                 // Write any trailing note offs
272                 while ( ! _active_notes.empty() ) {
273                         const Note* const earliest_off = _active_notes.top();
274                         const MidiEvent&  off_ev       = earliest_off->off_event();
275                         if (off_ev.time() < start + nframes) {
276                                 dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
277                                 _active_notes.pop();
278                                 ++read_events;
279                         } else {
280                                 break;
281                         }
282                 }
283
284         // Percussive
285         } else {
286                 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
287                         // Note on
288                         if (n->time() >= start) {
289                                 if (n->time() < start + nframes) {
290                                         const MidiEvent& ev = n->on_event();
291                                         dst.write(ev.time() + stamp_offset, ev.size(), ev.buffer());
292                                         ++read_events;
293                                 } else {
294                                         break;
295                                 }
296                         }
297                 }
298         }
299 #endif
300         return read_events;
301 }
302         
303
304 bool
305 MidiModel::control_to_midi_event(MidiEvent& ev, const MidiControlIterator& iter) const
306 {
307         if (iter.first->parameter().type() == MidiCCAutomation) {
308                 if (ev.size() < 3)
309                         ev.set_buffer((Byte*)malloc(3), true);
310
311                 assert(iter.first);
312                 assert(iter.first->parameter().id() <= INT8_MAX);
313                 assert(iter.second.second <= INT8_MAX);
314                 ev.buffer()[0] = MIDI_CMD_CONTROL;
315                 ev.buffer()[1] = (Byte)iter.first->parameter().id();
316                 ev.buffer()[2] = (Byte)iter.second.second;
317                 ev.time() = iter.second.first; // x
318                 ev.size() = 3;
319                 return true;
320         } else {
321                 return false;
322         }
323 }
324
325         
326 /** Return the earliest MIDI event in the given range.
327  *
328  * \return true if \a output has been set to the earliest event in the given range.
329  */
330 #if 0
331 bool
332 MidiModel::earliest_note_event(MidiEvent& output, nframes_t start, nframes_t nframes) const
333 {
334         /* FIXME: cache last lookup value to avoid O(n) search every time */
335                 
336         const Note*      const earliest_on  = NULL;
337         const Note*      const earliest_off = NULL;
338         const MidiEvent* const earliest_cc = NULL;
339
340         /* Notes */
341
342         if (_note_mode == Sustained) {
343                                 
344                 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
345
346                         if ( ! _active_notes.empty() ) {
347                                 const Note* const earliest_off = _active_notes.top();
348                                 const MidiEvent&  off_ev       = earliest_off->off_event();
349                                 if (off_ev.time() < start + nframes && off_ev.time() <= n->time()) {
350                                         output = off_ev;
351                                         //dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
352                                         _active_notes.pop();
353                                         return true;
354                                 }
355                         }
356
357                         if (n->time() >= start + nframes)
358                                 break;
359
360                         // Note on
361                         if (n->time() >= start) {
362                                 earliest_on = &n->on_event();
363                                 //dst.write(on_ev.time() + stamp_offset, on_ev.size(), on_ev.buffer());
364                                 _active_notes.push(&(*n));
365                                 return true;
366                         }
367
368                 }
369                         
370                 // Write any trailing note offs
371                 while ( ! _active_notes.empty() ) {
372                         const Note* const earliest_off = _active_notes.top();
373                         const MidiEvent&  off_ev       = earliest_off->off_event();
374                         if (off_ev.time() < start + nframes) {
375                                 dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
376                                 _active_notes.pop();
377                                 ++read_events;
378                         } else {
379                                 break;
380                         }
381                 }
382
383         // Percussive
384         } else {
385                 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
386                         // Note on
387                         if (n->time() >= start) {
388                                 if (n->time() < start + nframes) {
389                                         const MidiEvent& ev = n->on_event();
390                                         dst.write(ev.time() + stamp_offset, ev.size(), ev.buffer());
391                                         ++read_events;
392                                 } else {
393                                         break;
394                                 }
395                         }
396                 }
397         }
398
399         return read_events;
400 }
401 #endif
402
403 /** Begin a write of events to the model.
404  *
405  * If \a mode is Sustained, complete notes with duration are constructed as note
406  * on/off events are received.  Otherwise (Percussive), only note on events are
407  * stored; note off events are discarded entirely and all contained notes will
408  * have duration 0.
409  */
410 void
411 MidiModel::start_write()
412 {
413         //cerr << "MM " << this << " START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
414         write_lock();
415         _writing = true;
416         _write_notes.clear();
417         write_unlock();
418 }
419
420
421
422 /** Finish a write of events to the model.
423  *
424  * If \a delete_stuck is true and the current mode is Sustained, note on events
425  * that were never resolved with a corresonding note off will be deleted.
426  * Otherwise they will remain as notes with duration 0.
427  */
428 void
429 MidiModel::end_write(bool delete_stuck)
430 {
431         write_lock();
432         assert(_writing);
433         
434         //cerr << "MM " << this << " END WRITE: " << _notes.size() << " NOTES\n";
435
436         if (_note_mode == Sustained && delete_stuck) {
437                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
438                         if (n->duration() == 0) {
439                                 cerr << "WARNING: Stuck note lost: " << n->note() << endl;
440                                 n = _notes.erase(n);
441                         } else {
442                                 ++n;
443                         }
444                 }
445         }
446
447         _write_notes.clear();
448         _writing = false;
449         write_unlock();
450 }
451
452
453 /** Append contents of \a buf to model.  NOT realtime safe.
454  *
455  * Timestamps of events in \a buf are expected to be relative to
456  * the start of this model (t=0) and MUST be monotonically increasing
457  * and MUST be >= the latest event currently in the model.
458  *
459  * Events in buf are deep copied.
460  */
461 void
462 MidiModel::append(const MidiBuffer& buf)
463
464         write_lock();
465
466         assert(_writing);
467
468         for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
469                 assert(_notes.empty() || (*i).time() >= _notes.back().time());
470                 append(*i);
471         }
472         
473         write_unlock();
474 }
475
476
477 /** Append \a in_event to model.  NOT realtime safe.
478  *
479  * Timestamps of events in \a buf are expected to be relative to
480  * the start of this model (t=0) and MUST be monotonically increasing
481  * and MUST be >= the latest event currently in the model.
482  */
483 void
484 MidiModel::append(const MidiEvent& ev)
485 {
486         write_lock();
487
488         assert(_notes.empty() || ev.time() >= _notes.back().time());
489         assert(_writing);
490
491         if (ev.is_note_on())
492                 append_note_on_unlocked(ev.time(), ev.note(), ev.velocity());
493         else if (ev.is_note_off())
494                 append_note_off_unlocked(ev.time(), ev.note());
495         else if (ev.is_cc())
496                 append_cc_unlocked(ev.time(), ev.cc_number(), ev.cc_value());
497         else
498                 printf("MM Unknown event type %X\n", ev.type());
499         
500         write_unlock();
501 }
502
503
504 void
505 MidiModel::append_note_on_unlocked(double time, uint8_t note_num, uint8_t velocity)
506 {
507         //cerr << "MidiModel " << this << " note " << (int)note_num << " on @ " << time << endl;
508
509         assert(_writing);
510         _notes.push_back(Note(time, 0, note_num, velocity));
511         if (_note_mode == Sustained) {
512                 //cerr << "MM Sustained: Appending active note on " << (unsigned)(uint8_t)note_num << endl;
513                 _write_notes.push_back(_notes.size() - 1);
514         } else {
515                 //cerr << "MM Percussive: NOT appending active note on" << endl;
516         }
517 }
518
519
520 void
521 MidiModel::append_note_off_unlocked(double time, uint8_t note_num)
522 {
523         //cerr << "MidiModel " << this << " note " << (int)note_num << " off @ " << time << endl;
524
525         assert(_writing);
526         if (_note_mode == Percussive) {
527                 //cerr << "MM Ignoring note off (percussive mode)" << endl;
528                 return;
529         } else {
530                 //cerr << "MM Attempting to resolve note off " << (unsigned)(uint8_t)note_num << endl;
531         }
532
533         /* FIXME: make _write_notes fixed size (127 noted) for speed */
534         
535         /* FIXME: note off velocity for that one guy out there who actually has
536          * keys that send it */
537
538         for (WriteNotes::iterator n = _write_notes.begin(); n != _write_notes.end(); ++n) {
539                 Note& note = _notes[*n];
540                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
541                 if (note.note() == note_num) {
542                         assert(time > note.time());
543                         note.set_duration(time - note.time());
544                         _write_notes.erase(n);
545                         //cerr << "MM resolved note, duration: " << note.duration() << endl;
546                         break;
547                 }
548         }
549 }
550
551
552 void
553 MidiModel::append_cc_unlocked(double time, uint8_t number, uint8_t value)
554 {
555         Parameter param(MidiCCAutomation, number);
556         
557         boost::shared_ptr<AutomationControl> control = Automatable::control(param, true);
558         //cerr << "MidiModel " << this << "(" << control.get() << ") add CC " << (int)number << " = " << (int)value
559         //      << " @ " << time << endl;
560         control->list()->fast_simple_add(time, (double)value);
561 }
562
563
564 void
565 MidiModel::add_note_unlocked(const Note& note)
566 {
567         //cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
568         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
569         _notes.insert(i, note);
570 }
571
572
573 void
574 MidiModel::remove_note_unlocked(const Note& note)
575 {
576         //cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
577         Notes::iterator n = find(_notes.begin(), _notes.end(), note);
578         if (n != _notes.end())
579                 _notes.erase(n);
580 }
581
582 /** Slow!  for debugging only. */
583 #ifndef NDEBUG
584 bool
585 MidiModel::is_sorted() const
586 {
587         bool t = 0;
588         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
589                 if (n->time() < t)
590                         return false;
591                 else
592                         t = n->time();
593
594         return true;
595 }
596 #endif
597
598 /** Start a new command.
599  *
600  * This has no side-effects on the model or Session, the returned command
601  * can be held on to for as long as the caller wishes, or discarded without
602  * formality, until apply_command is called and ownership is taken.
603  */
604 MidiModel::DeltaCommand*
605 MidiModel::new_delta_command(const string name)
606 {
607         DeltaCommand* cmd =  new DeltaCommand(*this, name);
608         return cmd;
609 }
610
611
612 /** Apply a command.
613  *
614  * Ownership of cmd is taken, it must not be deleted by the caller.
615  * The command will constitute one item on the undo stack.
616  */
617 void
618 MidiModel::apply_command(Command* cmd)
619 {
620         _session.begin_reversible_command(cmd->name());
621         (*cmd)();
622         assert(is_sorted());
623         _session.commit_reversible_command(cmd);
624         _edited = true;
625 }
626
627
628 // MidiEditCommand
629
630
631 void
632 MidiModel::DeltaCommand::add(const Note& note)
633 {
634         //cerr << "MEC: apply" << endl;
635
636         _removed_notes.remove(note);
637         _added_notes.push_back(note);
638 }
639
640
641 void
642 MidiModel::DeltaCommand::remove(const Note& note)
643 {
644         //cerr << "MEC: remove" << endl;
645
646         _added_notes.remove(note);
647         _removed_notes.push_back(note);
648 }
649
650                 
651 void 
652 MidiModel::DeltaCommand::operator()()
653 {
654         // This could be made much faster by using a priority_queue for added and
655         // removed notes (or sort here), and doing a single iteration over _model
656         
657         _model.write_lock();
658         
659         for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
660                 _model.add_note_unlocked(*i);
661         
662         for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
663                 _model.remove_note_unlocked(*i);
664         
665         _model.write_unlock();
666         
667         _model.ContentsChanged(); /* EMIT SIGNAL */
668 }
669
670
671 void
672 MidiModel::DeltaCommand::undo()
673 {
674         // This could be made much faster by using a priority_queue for added and
675         // removed notes (or sort here), and doing a single iteration over _model
676         
677         _model.write_lock();
678
679         for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
680                 _model.remove_note_unlocked(*i);
681         
682         for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
683                 _model.add_note_unlocked(*i);
684         
685         _model.write_unlock();
686         
687         _model.ContentsChanged(); /* EMIT SIGNAL */
688 }
689
690
691 bool
692 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
693 {
694         //cerr << "Writing model to " << source->name() << endl;
695
696         /* This could be done using a temporary MidiRingBuffer and using
697          * MidiModel::read and MidiSource::write, but this is more efficient
698          * and doesn't require any buffer size assumptions (ie it's worth
699          * the code duplication).
700          *
701          * This is also different from read in that note off events are written
702          * regardless of the track mode.  This is so the user can switch a
703          * recorded track (with note durations from some instrument) to percussive,
704          * save, reload, then switch it back to sustained preserving the original
705          * note durations.
706          */
707
708         /* Percussive 
709         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
710                 const MidiEvent& ev = n->on_event();
711                 source->append_event_unlocked(ev);
712         }*/
713
714         read_lock();
715
716         LaterNoteEndComparator cmp;
717         ActiveNotes active_notes(cmp);
718                 
719         // Foreach note
720         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
721
722                 // Write any pending note offs earlier than this note on
723                 while ( ! active_notes.empty() ) {
724                         const Note* const earliest_off = active_notes.top();
725                         const MidiEvent&  off_ev       = earliest_off->off_event();
726                         if (off_ev.time() <= n->time()) {
727                                 source->append_event_unlocked(off_ev);
728                                 active_notes.pop();
729                         } else {
730                                 break;
731                         }
732                 }
733
734                 // Write this note on
735                 source->append_event_unlocked(n->on_event());
736                 if (n->duration() > 0)
737                         active_notes.push(&(*n));
738         }
739                 
740         // Write any trailing note offs
741         while ( ! active_notes.empty() ) {
742                 source->append_event_unlocked(active_notes.top()->off_event());
743                 active_notes.pop();
744         }
745
746         _edited = false;
747         
748         read_unlock();
749
750         return true;
751 }
752
753 XMLNode&
754 MidiModel::get_state()
755 {
756         XMLNode *node = new XMLNode("MidiModel");
757         return *node;
758 }
759