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