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