various minor MIDI fixes: prevent duplicate note entry with mouse, show note info...
[ardour.git] / libs / ardour / midi_model.cc
1 /*
2     Copyright (C) 2007 Paul Davis
3     Author: Dave Robillard
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/error.h"
28 #include "pbd/enumwriter.h"
29 #include "midi++/events.h"
30
31 #include "ardour/midi_model.h"
32 #include "ardour/midi_source.h"
33 #include "ardour/midi_state_tracker.h"
34 #include "ardour/smf_source.h"
35 #include "ardour/types.h"
36 #include "ardour/session.h"
37
38 using namespace std;
39 using namespace ARDOUR;
40 using namespace PBD;
41
42 MidiModel::MidiModel(MidiSource* s)
43         : AutomatableSequence<TimeType>(s->session())
44         , _midi_source(s)
45 {
46 }
47
48 /** Start a new Delta command.
49  *
50  * This has no side-effects on the model or Session, the returned command
51  * can be held on to for as long as the caller wishes, or discarded without
52  * formality, until apply_command is called and ownership is taken.
53  */
54 MidiModel::DeltaCommand*
55 MidiModel::new_delta_command(const string name)
56 {
57         DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
58         return cmd;
59 }
60
61 /** Start a new Diff command.
62  *
63  * This has no side-effects on the model or Session, the returned command
64  * can be held on to for as long as the caller wishes, or discarded without
65  * formality, until apply_command is called and ownership is taken.
66  */
67 MidiModel::DiffCommand*
68 MidiModel::new_diff_command(const string name)
69 {
70         DiffCommand* cmd = new DiffCommand(_midi_source->model(), name);
71         return cmd;
72 }
73
74 /** Apply a command.
75  *
76  * Ownership of cmd is taken, it must not be deleted by the caller.
77  * The command will constitute one item on the undo stack.
78  */
79 void
80 MidiModel::apply_command(Session& session, Command* cmd)
81 {
82         session.begin_reversible_command(cmd->name());
83         (*cmd)();
84         session.commit_reversible_command(cmd);
85         set_edited(true);
86 }
87
88 /** Apply a command as part of a larger reversible transaction
89  *
90  * Ownership of cmd is taken, it must not be deleted by the caller.
91  * The command will constitute one item on the undo stack.
92  */
93 void
94 MidiModel::apply_command_as_subcommand(Session& session, Command* cmd)
95 {
96         (*cmd)();
97         session.add_command(cmd);
98         set_edited(true);
99 }
100
101
102 // DeltaCommand
103
104 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
105         : Command(name)
106         , _model(m)
107         , _name(name)
108 {
109         assert(_model);
110 }
111
112 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
113         : _model(m)
114 {
115         assert(_model);
116         set_state(node, Stateful::loading_state_version);
117 }
118
119 void
120 MidiModel::DeltaCommand::add(const boost::shared_ptr< Evoral::Note<TimeType> > note)
121 {
122         _removed_notes.remove(note);
123         _added_notes.push_back(note);
124 }
125
126 void
127 MidiModel::DeltaCommand::remove(const boost::shared_ptr< Evoral::Note<TimeType> > note)
128 {
129         _added_notes.remove(note);
130         _removed_notes.push_back(note);
131 }
132
133 void
134 MidiModel::DeltaCommand::operator()()
135 {
136         // This could be made much faster by using a priority_queue for added and
137         // removed notes (or sort here), and doing a single iteration over _model
138
139         MidiModel::WriteLock lock(_model->edit_lock());
140
141         for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) {
142                 _model->add_note_unlocked(*i);
143         }
144
145         for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i) {
146                 _model->remove_note_unlocked(*i);
147         }
148
149         lock.reset();
150         _model->ContentsChanged(); /* EMIT SIGNAL */
151 }
152
153 void
154 MidiModel::DeltaCommand::undo()
155 {
156         // This could be made much faster by using a priority_queue for added and
157         // removed notes (or sort here), and doing a single iteration over _model
158
159         MidiModel::WriteLock lock(_model->edit_lock());;
160
161         for (NoteList::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i) {
162                 _model->remove_note_unlocked(*i);
163         }
164
165         for (NoteList::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i) {
166                 _model->add_note_unlocked(*i);
167         }
168
169         lock.reset();
170         _model->ContentsChanged(); /* EMIT SIGNAL */
171 }
172
173 XMLNode&
174 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr< Evoral::Note<TimeType> > note)
175 {
176         XMLNode* xml_note = new XMLNode("note");
177         ostringstream note_str(ios::ate);
178         note_str << int(note->note());
179         xml_note->add_property("note", note_str.str());
180
181         ostringstream channel_str(ios::ate);
182         channel_str << int(note->channel());
183         xml_note->add_property("channel", channel_str.str());
184
185         ostringstream time_str(ios::ate);
186         time_str << int(note->time());
187         xml_note->add_property("time", time_str.str());
188
189         ostringstream length_str(ios::ate);
190         length_str <<(unsigned int) note->length();
191         xml_note->add_property("length", length_str.str());
192
193         ostringstream velocity_str(ios::ate);
194         velocity_str << (unsigned int) note->velocity();
195         xml_note->add_property("velocity", velocity_str.str());
196
197         return *xml_note;
198 }
199
200 boost::shared_ptr< Evoral::Note<MidiModel::TimeType> >
201 MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
202 {
203         unsigned int note;
204         XMLProperty* prop;
205         unsigned int channel;
206         unsigned int time;
207         unsigned int length;
208         unsigned int velocity;
209
210         if ((prop = xml_note->property("note")) != 0) {
211                 istringstream note_str(prop->value());
212                 note_str >> note;
213         } else {
214                 warning << "note information missing note value" << endmsg;
215                 note = 127;
216         }
217
218         if ((prop = xml_note->property("channel")) != 0) {
219                 istringstream channel_str(prop->value());
220                 channel_str >> channel;
221         } else {
222                 warning << "note information missing channel" << endmsg;
223                 channel = 0;
224         }
225
226         if ((prop = xml_note->property("time")) != 0) {
227                 istringstream time_str(prop->value());
228                 time_str >> time;
229         } else {
230                 warning << "note information missing time" << endmsg;
231                 time = 0;
232         }
233
234         if ((prop = xml_note->property("length")) != 0) {
235                 istringstream length_str(prop->value());
236                 length_str >> length;
237         } else {
238                 warning << "note information missing length" << endmsg;
239                 length = 1;
240         }
241
242         if ((prop = xml_note->property("velocity")) != 0) {
243                 istringstream velocity_str(prop->value());
244                 velocity_str >> velocity;
245         } else {
246                 warning << "note information missing velocity" << endmsg;
247                 velocity = 127;
248         }
249
250         boost::shared_ptr< Evoral::Note<TimeType> > note_ptr(new Evoral::Note<TimeType>(
251                         channel, time, length, note, velocity));
252         return note_ptr;
253 }
254
255 #define ADDED_NOTES_ELEMENT "AddedNotes"
256 #define REMOVED_NOTES_ELEMENT "RemovedNotes"
257 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
258
259 int
260 MidiModel::DeltaCommand::set_state (const XMLNode& delta_command, int /*version*/)
261 {
262         if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
263                 return 1;
264         }
265
266         _added_notes.clear();
267         XMLNode* added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
268         if (added_notes) {
269                 XMLNodeList notes = added_notes->children();
270                 transform(notes.begin(), notes.end(), back_inserter(_added_notes),
271                           boost::bind (&DeltaCommand::unmarshal_note, this, _1));
272         }
273
274         _removed_notes.clear();
275         XMLNode* removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
276         if (removed_notes) {
277                 XMLNodeList notes = removed_notes->children();
278                 transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
279                           boost::bind (&DeltaCommand::unmarshal_note, this, _1));
280         }
281
282         return 0;
283 }
284
285 XMLNode&
286 MidiModel::DeltaCommand::get_state()
287 {
288         XMLNode* delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
289         delta_command->add_property("midi-source", _model->midi_source()->id().to_s());
290
291         XMLNode* added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
292         for_each(_added_notes.begin(), _added_notes.end(), 
293                  boost::bind(
294                          boost::bind (&XMLNode::add_child_nocopy, *added_notes, _1),
295                          boost::bind (&DeltaCommand::marshal_note, this, _1)));
296
297         XMLNode* removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
298         for_each(_removed_notes.begin(), _removed_notes.end(), 
299                  boost::bind (
300                          boost::bind (&XMLNode::add_child_nocopy, *removed_notes, _1),
301                          boost::bind (&DeltaCommand::marshal_note, this, _1)));
302
303         return *delta_command;
304 }
305
306 /************** DIFF COMMAND ********************/
307
308 #define DIFF_NOTES_ELEMENT "ChangedNotes"
309 #define DIFF_COMMAND_ELEMENT "DiffCommand"
310
311 MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
312         : Command(name)
313         , _model(m)
314         , _name(name)
315 {
316         assert(_model);
317 }
318
319 MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
320         : _model(m)
321 {
322         assert(_model);
323         set_state(node, Stateful::loading_state_version);
324 }
325
326 void
327 MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
328                                uint8_t new_value)
329 {
330         NoteChange change;
331
332         change.note = note;
333         change.property = prop;
334         change.new_value = new_value;
335
336         switch (prop) {
337         case NoteNumber:
338                 change.old_value = note->note();
339                 break;
340         case Velocity:
341                 change.old_value = note->velocity();
342                 break;
343         case StartTime:
344                 fatal << "MidiModel::DiffCommand::change() with integer argument called for start time" << endmsg;
345                 /*NOTREACHED*/
346                 break;
347         case Length:
348                 fatal << "MidiModel::DiffCommand::change() with integer argument called for length" << endmsg;
349                 /*NOTREACHED*/
350                 break;
351         case Channel:
352                 change.old_value = note->channel();
353                 break;
354         }
355
356         _changes.push_back (change);
357 }
358
359 void
360 MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
361                                TimeType new_time)
362 {
363         NoteChange change;
364
365         change.note = note;
366         change.property = prop;
367         change.new_time = new_time;
368
369         switch (prop) {
370         case NoteNumber:
371         case Channel:
372         case Velocity:
373                 fatal << "MidiModel::DiffCommand::change() with time argument called for note, channel or velocity" << endmsg;
374                 break;
375         case StartTime:
376                 change.old_time = note->time();
377                 break;
378         case Length:
379                 change.old_time = note->length();
380                 break;
381         }
382
383         _changes.push_back (change);
384 }
385
386 void
387 MidiModel::DiffCommand::operator()()
388 {
389         MidiModel::WriteLock lock(_model->edit_lock());
390
391         for (ChangeList::iterator i = _changes.begin(); i != _changes.end(); ++i) {
392                 Property prop = i->property;
393                 switch (prop) {
394                 case NoteNumber:
395                         i->note->set_note (i->new_value);
396                         break;
397                 case Velocity:
398                         i->note->set_velocity (i->new_value);
399                         break;
400                 case StartTime:
401                         i->note->set_time (i->new_time);
402                         break;
403                 case Length:
404                         i->note->set_length (i->new_time);
405                         break;
406                 case Channel:
407                         i->note->set_channel (i->new_value);
408                         break;
409                 }
410         }
411
412         lock.reset();
413         _model->ContentsChanged(); /* EMIT SIGNAL */
414 }
415
416 void
417 MidiModel::DiffCommand::undo()
418 {
419         MidiModel::WriteLock lock(_model->edit_lock());
420
421         for (ChangeList::iterator i = _changes.begin(); i != _changes.end(); ++i) {
422                 Property prop = i->property;
423                 switch (prop) {
424                 case NoteNumber:
425                         i->note->set_note (i->old_value);
426                         break;
427                 case Velocity:
428                         i->note->set_velocity (i->old_value);
429                         break;
430                 case StartTime:
431                         i->note->set_time (i->old_time);
432                         break;
433                 case Length:
434                         i->note->set_length (i->old_time);
435                         break;
436                 case Channel:
437                         i->note->set_channel (i->old_value);
438                         break;
439                 }
440         }
441
442         lock.reset();
443         _model->ContentsChanged(); /* EMIT SIGNAL */
444 }
445
446 XMLNode&
447 MidiModel::DiffCommand::marshal_change(const NoteChange& change)
448 {
449         XMLNode* xml_change = new XMLNode("change");
450
451         /* first, the change itself */
452
453         xml_change->add_property ("property", enum_2_string (change.property));
454
455         {
456                 ostringstream old_value_str (ios::ate);
457                 if (change.property == StartTime || change.property == Length) {
458                         old_value_str << change.old_time;
459                 } else {
460                         old_value_str << (unsigned int) change.old_value;
461                 }
462                 xml_change->add_property ("old", old_value_str.str());
463         }
464
465         {
466                 ostringstream new_value_str (ios::ate);
467                 if (change.property == StartTime || change.property == Length) {
468                         new_value_str << change.new_time;
469                 } else {
470                         new_value_str << (unsigned int) change.new_value;
471                 }
472                 xml_change->add_property ("new", new_value_str.str());
473         }
474
475         /* now the rest of the note */
476
477         const SMFSource* smf = dynamic_cast<const SMFSource*> (_model->midi_source());
478
479         if (change.property != NoteNumber) {
480                 ostringstream note_str;
481                 note_str << int(change.note->note());
482                 xml_change->add_property("note", note_str.str());
483         }
484
485         if (change.property != Channel) {
486                 ostringstream channel_str;
487                 channel_str << int(change.note->channel());
488                 xml_change->add_property("channel", channel_str.str());
489         }
490
491         if (change.property != StartTime) {
492                 ostringstream time_str;
493                 if (smf) {
494                         time_str << smf->round_to_file_precision (change.note->time());
495                 } else {
496                         time_str << change.note->time();
497                 }
498                 xml_change->add_property("time", time_str.str());
499         }
500
501         if (change.property != Length) {
502                 ostringstream length_str;
503                 if (smf) {
504                         length_str << smf->round_to_file_precision (change.note->length());
505                 } else {
506                         length_str << change.note->length();
507                 }
508                 xml_change->add_property ("length", length_str.str());
509         }
510
511         if (change.property != Velocity) {
512                 ostringstream velocity_str;
513                 velocity_str << int (change.note->velocity());
514                 xml_change->add_property("velocity", velocity_str.str());
515         }
516
517         return *xml_change;
518 }
519
520 MidiModel::DiffCommand::NoteChange
521 MidiModel::DiffCommand::unmarshal_change(XMLNode *xml_change)
522 {
523         XMLProperty* prop;
524         NoteChange change;
525         unsigned int note;
526         unsigned int channel;
527         unsigned int velocity;
528         Evoral::MusicalTime time;
529         Evoral::MusicalTime length;
530
531         if ((prop = xml_change->property("property")) != 0) {
532                 change.property = (Property) string_2_enum (prop->value(), change.property);
533         } else {
534                 fatal << "!!!" << endmsg;
535                 /*NOTREACHED*/
536         }
537
538         if ((prop = xml_change->property ("old")) != 0) {
539                 istringstream old_str (prop->value());
540                 if (change.property == StartTime || change.property == Length) {
541                         old_str >> change.old_time;
542                 } else {
543                         int integer_value_so_that_istream_does_the_right_thing;
544                         old_str >> integer_value_so_that_istream_does_the_right_thing;
545                         change.old_value = integer_value_so_that_istream_does_the_right_thing;
546                 }
547         } else {
548                 fatal << "!!!" << endmsg;
549                 /*NOTREACHED*/
550         }
551
552         if ((prop = xml_change->property ("new")) != 0) {
553                 istringstream new_str (prop->value());
554                 if (change.property == StartTime || change.property == Length) {
555                         new_str >> change.new_time;
556                 } else {
557                         int integer_value_so_that_istream_does_the_right_thing;
558                         new_str >> integer_value_so_that_istream_does_the_right_thing;
559                         change.new_value = integer_value_so_that_istream_does_the_right_thing;
560                 }
561         } else {
562                 fatal << "!!!" << endmsg;
563                 /*NOTREACHED*/
564         }
565
566         if (change.property != NoteNumber) {
567                 if ((prop = xml_change->property("note")) != 0) {
568                         istringstream note_str(prop->value());
569                         note_str >> note;
570                 } else {
571                         warning << "note information missing note value" << endmsg;
572                         note = 127;
573                 }
574         } else {
575                 note = change.new_value;
576         }
577
578         if (change.property != Channel) {
579                 if ((prop = xml_change->property("channel")) != 0) {
580                         istringstream channel_str(prop->value());
581                         channel_str >> channel;
582                 } else {
583                         warning << "note information missing channel" << endmsg;
584                         channel = 0;
585                 }
586         } else {
587                 channel = change.new_value;
588         }
589
590         if (change.property != StartTime) {
591                 if ((prop = xml_change->property("time")) != 0) {
592                         istringstream time_str(prop->value());
593                         time_str >> time;
594                 } else {
595                         warning << "note information missing time" << endmsg;
596                         time = 0;
597                 }
598         } else {
599                 time = change.new_time;
600         }
601
602         if (change.property != Length) {
603                 if ((prop = xml_change->property("length")) != 0) {
604                         istringstream length_str(prop->value());
605                         length_str >> length;
606                 } else {
607                         warning << "note information missing length" << endmsg;
608                         length = 1;
609                 }
610         } else {
611                 length = change.new_time;
612         }
613
614         if (change.property != Velocity) {
615                 if ((prop = xml_change->property("velocity")) != 0) {
616                         istringstream velocity_str(prop->value());
617                         velocity_str >> velocity;
618                 } else {
619                         warning << "note information missing velocity" << endmsg;
620                         velocity = 127;
621                 }
622         } else {
623                 velocity = change.new_value;
624         }
625
626         /* we must point at the instance of the note that is actually in the model.
627            so go look for it ...
628         */
629
630         boost::shared_ptr<Evoral::Note<TimeType> > new_note (new Evoral::Note<TimeType> (channel, time, length, note, velocity));
631
632         change.note = _model->find_note (new_note);
633
634         if (!change.note) {
635                 warning << "MIDI note " << *new_note << " not found in model - programmers should investigate this" << endmsg;
636                 /* use the actual new note */
637                 change.note = new_note;
638         }
639
640         return change;
641 }
642
643 int
644 MidiModel::DiffCommand::set_state(const XMLNode& diff_command, int /*version*/)
645 {
646         if (diff_command.name() != string(DIFF_COMMAND_ELEMENT)) {
647                 return 1;
648         }
649
650         _changes.clear();
651
652         XMLNode* changed_notes = diff_command.child(DIFF_NOTES_ELEMENT);
653
654         if (changed_notes) {
655                 XMLNodeList notes = changed_notes->children();
656                 transform (notes.begin(), notes.end(), back_inserter(_changes),
657                            boost::bind (&DiffCommand::unmarshal_change, this, _1));
658
659         }
660
661         return 0;
662 }
663
664 XMLNode&
665 MidiModel::DiffCommand::get_state ()
666 {
667         XMLNode* diff_command = new XMLNode(DIFF_COMMAND_ELEMENT);
668         diff_command->add_property("midi-source", _model->midi_source()->id().to_s());
669
670         XMLNode* changes = diff_command->add_child(DIFF_NOTES_ELEMENT);
671         for_each(_changes.begin(), _changes.end(), 
672                  boost::bind (
673                          boost::bind (&XMLNode::add_child_nocopy, *changes, _1),
674                          boost::bind (&DiffCommand::marshal_change, this, _1)));
675
676         return *diff_command;
677 }
678
679 /** Write all of the model to a MidiSource (i.e. save the model).
680  * This is different from manually using read to write to a source in that
681  * note off events are written regardless of the track mode.  This is so the
682  * user can switch a recorded track (with note durations from some instrument)
683  * to percussive, save, reload, then switch it back to sustained without
684  * destroying the original note durations.
685  */
686 bool
687 MidiModel::write_to (boost::shared_ptr<MidiSource> source)
688 {
689         ReadLock lock(read_lock());
690
691         const bool old_percussive = percussive();
692         set_percussive(false);
693
694         source->drop_model();
695         source->mark_streaming_midi_write_started(note_mode(), _midi_source->timeline_position());
696
697         for (Evoral::Sequence<TimeType>::const_iterator i = begin(); i != end(); ++i) {
698                 source->append_event_unlocked_beats(*i);
699         }
700
701         set_percussive(old_percussive);
702         source->mark_streaming_write_completed();
703
704         set_edited(false);
705
706         return true;
707 }
708
709 /** Write part or all of the model to a MidiSource (i.e. save the model).
710  * This is different from manually using read to write to a source in that
711  * note off events are written regardless of the track mode.  This is so the
712  * user can switch a recorded track (with note durations from some instrument)
713  * to percussive, save, reload, then switch it back to sustained without
714  * destroying the original note durations.
715  */
716 bool
717 MidiModel::write_section_to (boost::shared_ptr<MidiSource> source, Evoral::MusicalTime begin_time, Evoral::MusicalTime end_time)
718 {
719         ReadLock lock(read_lock());
720         MidiStateTracker mst;
721         Evoral::MusicalTime extra_note_on_time = end_time;
722
723         const bool old_percussive = percussive();
724         set_percussive(false);
725
726         source->drop_model();
727         source->mark_streaming_midi_write_started(note_mode(), _midi_source->timeline_position());
728
729         for (Evoral::Sequence<TimeType>::const_iterator i = begin(); i != end(); ++i) {
730                 const Evoral::Event<Evoral::MusicalTime>& ev (*i);
731                 
732                 if (ev.time() >= begin_time && ev.time() < end_time) {
733
734                         const Evoral::MIDIEvent<Evoral::MusicalTime>* mev = 
735                                 static_cast<const Evoral::MIDIEvent<Evoral::MusicalTime>* > (&ev);
736                         
737                         if (!mev) {
738                                 continue;
739                         }
740
741
742                         if (mev->is_note_off()) {
743                                 
744                                 if (!mst.active (mev->note(), mev->channel())) {
745                                         
746                                         /* add a note-on at the start of the range we're writing
747                                            to the file. velocity is just an arbitary reasonable value.
748                                         */
749                                         
750                                         Evoral::MIDIEvent<Evoral::MusicalTime> on (mev->event_type(), extra_note_on_time, 3, 0, true);
751                                         on.set_type (mev->type());
752                                         on.set_note (mev->note());
753                                         on.set_channel (mev->channel());
754                                         on.set_velocity (mev->velocity());
755                                         
756                                         cerr << "Add note on for odd note off, note = " << (int) on.note() << endl;
757                                         source->append_event_unlocked_beats (on);
758                                         mst.add (on.note(), on.channel());
759                                         mst.dump (cerr);
760                                         extra_note_on_time += 1.0/128.0;
761                                 }
762                                         
763                                 cerr << "MIDI Note off (note = " << (int) mev->note() << endl;
764                                 source->append_event_unlocked_beats (*i);
765                                 mst.remove (mev->note(), mev->channel());
766                                 mst.dump (cerr);
767                                         
768                         } else if (mev->is_note_on()) {
769                                 cerr << "MIDI Note on (note = " << (int) mev->note() << endl;
770                                 mst.add (mev->note(), mev->channel());
771                                 source->append_event_unlocked_beats(*i);
772                                 mst.dump (cerr);
773                         } else {
774                                 cerr << "MIDI other event type\n";
775                                 source->append_event_unlocked_beats(*i);
776                         }
777                 }
778         }
779
780         mst.resolve_notes (*source, end_time);
781
782         set_percussive(old_percussive);
783         source->mark_streaming_write_completed();
784
785         set_edited(false);
786
787         return true;
788 }
789
790 XMLNode&
791 MidiModel::get_state()
792 {
793         XMLNode *node = new XMLNode("MidiModel");
794         return *node;
795 }
796
797 boost::shared_ptr<Evoral::Note<MidiModel::TimeType> >
798 MidiModel::find_note (boost::shared_ptr<Evoral::Note<TimeType> > other)
799 {
800         Notes::iterator l = notes().lower_bound(other);
801
802         if (l != notes().end()) {
803                 for (; (*l)->time() == other->time(); ++l) {
804                         if (*l == other) {
805                                 return *l;
806                         }
807                 }
808         }
809
810         return boost::shared_ptr<Evoral::Note<TimeType> >();
811 }
812
813 /** Lock and invalidate the source.
814  * This should be used by commands and editing things
815  */
816 MidiModel::WriteLock
817 MidiModel::edit_lock()
818 {
819         Glib::Mutex::Lock* source_lock = new Glib::Mutex::Lock(_midi_source->mutex());
820         _midi_source->invalidate(); // Release cached iterator's read lock on model
821         return WriteLock(new WriteLockImpl(source_lock, _lock, _control_lock));
822 }
823
824 /** Lock just the model, the source lock must already be held.
825  * This should only be called from libardour/evoral places
826  */
827 MidiModel::WriteLock
828 MidiModel::write_lock()
829 {
830         assert(!_midi_source->mutex().trylock());
831         return WriteLock(new WriteLockImpl(NULL, _lock, _control_lock));
832 }