switch to using boost::signals2 instead of sigc++, at least for libardour. not finish...
[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->edit_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->edit_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                           boost::bind (&DeltaCommand::unmarshal_note, this, _1));
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                           boost::bind (&DeltaCommand::unmarshal_note, this, _1));
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(), 
292                  boost::bind(
293                          boost::bind (&XMLNode::add_child_nocopy, *added_notes, _1),
294                          boost::bind (&DeltaCommand::marshal_note, this, _1)));
295
296         XMLNode* removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
297         for_each(_removed_notes.begin(), _removed_notes.end(), 
298                  boost::bind (
299                          boost::bind (&XMLNode::add_child_nocopy, *removed_notes, _1),
300                          boost::bind (&DeltaCommand::marshal_note, this, _1)));
301
302         return *delta_command;
303 }
304
305 /************** DIFF COMMAND ********************/
306
307 #define DIFF_NOTES_ELEMENT "ChangedNotes"
308 #define DIFF_COMMAND_ELEMENT "DiffCommand"
309
310 MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const std::string& name)
311         : Command(name)
312         , _model(m)
313         , _name(name)
314 {
315         assert(_model);
316 }
317
318 MidiModel::DiffCommand::DiffCommand(boost::shared_ptr<MidiModel> m, const XMLNode& node)
319         : _model(m)
320 {
321         assert(_model);
322         set_state(node, Stateful::loading_state_version);
323 }
324
325 void
326 MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
327                                uint8_t new_value)
328 {
329         NotePropertyChange change;
330
331         change.note = note;
332         change.property = prop;
333         change.new_value = new_value;
334
335         switch (prop) {
336         case NoteNumber:
337                 change.old_value = note->note();
338                 break;
339         case Velocity:
340                 change.old_value = note->velocity();
341                 break;
342         case StartTime:
343                 fatal << "MidiModel::DiffCommand::change() with integer argument called for start time" << endmsg;
344                 /*NOTREACHED*/
345                 break;
346         case Length:
347                 fatal << "MidiModel::DiffCommand::change() with integer argument called for length" << endmsg;
348                 /*NOTREACHED*/
349                 break;
350         case Channel:
351                 change.old_value = note->channel();
352                 break;
353         }
354
355         _changes.push_back (change);
356 }
357
358 void
359 MidiModel::DiffCommand::change(const boost::shared_ptr< Evoral::Note<TimeType> > note, Property prop,
360                                TimeType new_time)
361 {
362         NotePropertyChange change;
363
364         change.note = note;
365         change.property = prop;
366         change.new_time = new_time;
367
368         switch (prop) {
369         case NoteNumber:
370         case Channel:
371         case Velocity:
372                 fatal << "MidiModel::DiffCommand::change() with time argument called for note, channel or velocity" << endmsg;
373                 break;
374         case StartTime:
375                 change.old_time = note->time();
376                 break;
377         case Length:
378                 change.old_time = note->length();
379                 break;
380         }
381
382         _changes.push_back (change);
383 }
384
385 void
386 MidiModel::DiffCommand::operator()()
387 {
388         MidiModel::WriteLock lock(_model->edit_lock());
389
390         for (ChangeList::iterator i = _changes.begin(); i != _changes.end(); ++i) {
391                 Property prop = i->property;
392                 switch (prop) {
393                 case NoteNumber:
394                         i->note->set_note (i->new_value);
395                         break;
396                 case Velocity:
397                         i->note->set_velocity (i->new_value);
398                         break;
399                 case StartTime:
400                         i->note->set_time (i->new_time);
401                         break;
402                 case Length:
403                         i->note->set_length (i->new_time);
404                         break;
405                 case Channel:
406                         i->note->set_channel (i->new_value);
407                         break;
408                 }
409         }
410
411         lock.reset();
412         _model->ContentsChanged(); /* EMIT SIGNAL */
413 }
414
415 void
416 MidiModel::DiffCommand::undo()
417 {
418         MidiModel::WriteLock lock(_model->edit_lock());
419
420         for (ChangeList::iterator i = _changes.begin(); i != _changes.end(); ++i) {
421                 Property prop = i->property;
422                 switch (prop) {
423                 case NoteNumber:
424                         i->note->set_note (i->old_value);
425                         break;
426                 case Velocity:
427                         i->note->set_velocity (i->old_value);
428                         break;
429                 case StartTime:
430                         i->note->set_time (i->old_time);
431                         break;
432                 case Length:
433                         i->note->set_length (i->old_time);
434                         break;
435                 case Channel:
436                         i->note->set_channel (i->old_value);
437                         break;
438                 }
439         }
440
441         lock.reset();
442         _model->ContentsChanged(); /* EMIT SIGNAL */
443 }
444
445 XMLNode&
446 MidiModel::DiffCommand::marshal_change(const NotePropertyChange& change)
447 {
448         XMLNode* xml_change = new XMLNode("change");
449
450         /* first, the change itself */
451
452         xml_change->add_property ("property", enum_2_string (change.property));
453
454         {
455                 ostringstream old_value_str (ios::ate);
456                 if (change.property == StartTime || change.property == Length) {
457                         old_value_str << change.old_time;
458                 } else {
459                         old_value_str << (unsigned int) change.old_value;
460                 }
461                 xml_change->add_property ("old", old_value_str.str());
462         }
463
464         {
465                 ostringstream new_value_str (ios::ate);
466                 if (change.property == StartTime || change.property == Length) {
467                         new_value_str << change.new_time;
468                 } else {
469                         new_value_str << (unsigned int) change.new_value;
470                 }
471                 xml_change->add_property ("new", new_value_str.str());
472         }
473
474         /* now the rest of the note */
475
476         const SMFSource* smf = dynamic_cast<const SMFSource*> (_model->midi_source());
477
478         if (change.property != NoteNumber) {
479                 ostringstream note_str;
480                 note_str << int(change.note->note());
481                 xml_change->add_property("note", note_str.str());
482         }
483
484         if (change.property != Channel) {
485                 ostringstream channel_str;
486                 channel_str << int(change.note->channel());
487                 xml_change->add_property("channel", channel_str.str());
488         }
489
490         if (change.property != StartTime) {
491                 ostringstream time_str;
492                 if (smf) {
493                         time_str << smf->round_to_file_precision (change.note->time());
494                 } else {
495                         time_str << change.note->time();
496                 }
497                 xml_change->add_property("time", time_str.str());
498         }
499
500         if (change.property != Length) {
501                 ostringstream length_str;
502                 if (smf) {
503                         length_str << smf->round_to_file_precision (change.note->length());
504                 } else {
505                         length_str << change.note->length();
506                 }
507                 xml_change->add_property ("length", length_str.str());
508         }
509
510         if (change.property != Velocity) {
511                 ostringstream velocity_str;
512                 velocity_str << int (change.note->velocity());
513                 xml_change->add_property("velocity", velocity_str.str());
514         }
515
516         return *xml_change;
517 }
518
519 MidiModel::DiffCommand::NotePropertyChange
520 MidiModel::DiffCommand::unmarshal_change(XMLNode *xml_change)
521 {
522         XMLProperty* prop;
523         NotePropertyChange change;
524         unsigned int note;
525         unsigned int channel;
526         unsigned int velocity;
527         Evoral::MusicalTime time;
528         Evoral::MusicalTime length;
529
530         if ((prop = xml_change->property("property")) != 0) {
531                 change.property = (Property) string_2_enum (prop->value(), change.property);
532         } else {
533                 fatal << "!!!" << endmsg;
534                 /*NOTREACHED*/
535         }
536
537         if ((prop = xml_change->property ("old")) != 0) {
538                 istringstream old_str (prop->value());
539                 if (change.property == StartTime || change.property == Length) {
540                         old_str >> change.old_time;
541                 } else {
542                         int integer_value_so_that_istream_does_the_right_thing;
543                         old_str >> integer_value_so_that_istream_does_the_right_thing;
544                         change.old_value = integer_value_so_that_istream_does_the_right_thing;
545                 }
546         } else {
547                 fatal << "!!!" << endmsg;
548                 /*NOTREACHED*/
549         }
550
551         if ((prop = xml_change->property ("new")) != 0) {
552                 istringstream new_str (prop->value());
553                 if (change.property == StartTime || change.property == Length) {
554                         new_str >> change.new_time;
555                 } else {
556                         int integer_value_so_that_istream_does_the_right_thing;
557                         new_str >> integer_value_so_that_istream_does_the_right_thing;
558                         change.new_value = integer_value_so_that_istream_does_the_right_thing;
559                 }
560         } else {
561                 fatal << "!!!" << endmsg;
562                 /*NOTREACHED*/
563         }
564
565         if (change.property != NoteNumber) {
566                 if ((prop = xml_change->property("note")) != 0) {
567                         istringstream note_str(prop->value());
568                         note_str >> note;
569                 } else {
570                         warning << "note information missing note value" << endmsg;
571                         note = 127;
572                 }
573         } else {
574                 note = change.new_value;
575         }
576
577         if (change.property != Channel) {
578                 if ((prop = xml_change->property("channel")) != 0) {
579                         istringstream channel_str(prop->value());
580                         channel_str >> channel;
581                 } else {
582                         warning << "note information missing channel" << endmsg;
583                         channel = 0;
584                 }
585         } else {
586                 channel = change.new_value;
587         }
588
589         if (change.property != StartTime) {
590                 if ((prop = xml_change->property("time")) != 0) {
591                         istringstream time_str(prop->value());
592                         time_str >> time;
593                 } else {
594                         warning << "note information missing time" << endmsg;
595                         time = 0;
596                 }
597         } else {
598                 time = change.new_time;
599         }
600
601         if (change.property != Length) {
602                 if ((prop = xml_change->property("length")) != 0) {
603                         istringstream length_str(prop->value());
604                         length_str >> length;
605                 } else {
606                         warning << "note information missing length" << endmsg;
607                         length = 1;
608                 }
609         } else {
610                 length = change.new_time;
611         }
612
613         if (change.property != Velocity) {
614                 if ((prop = xml_change->property("velocity")) != 0) {
615                         istringstream velocity_str(prop->value());
616                         velocity_str >> velocity;
617                 } else {
618                         warning << "note information missing velocity" << endmsg;
619                         velocity = 127;
620                 }
621         } else {
622                 velocity = change.new_value;
623         }
624
625         /* we must point at the instance of the note that is actually in the model.
626            so go look for it ...
627         */
628
629         boost::shared_ptr<Evoral::Note<TimeType> > new_note (new Evoral::Note<TimeType> (channel, time, length, note, velocity));
630
631         change.note = _model->find_note (new_note);
632
633         if (!change.note) {
634                 warning << "MIDI note " << *new_note << " not found in model - programmers should investigate this" << endmsg;
635                 /* use the actual new note */
636                 change.note = new_note;
637         }
638
639         return change;
640 }
641
642 int
643 MidiModel::DiffCommand::set_state(const XMLNode& diff_command, int /*version*/)
644 {
645         if (diff_command.name() != string(DIFF_COMMAND_ELEMENT)) {
646                 return 1;
647         }
648
649         _changes.clear();
650
651         XMLNode* changed_notes = diff_command.child(DIFF_NOTES_ELEMENT);
652
653         if (changed_notes) {
654                 XMLNodeList notes = changed_notes->children();
655                 transform (notes.begin(), notes.end(), back_inserter(_changes),
656                            boost::bind (&DiffCommand::unmarshal_change, this, _1));
657
658         }
659
660         return 0;
661 }
662
663 XMLNode&
664 MidiModel::DiffCommand::get_state ()
665 {
666         XMLNode* diff_command = new XMLNode(DIFF_COMMAND_ELEMENT);
667         diff_command->add_property("midi-source", _model->midi_source()->id().to_s());
668
669         XMLNode* changes = diff_command->add_child(DIFF_NOTES_ELEMENT);
670         for_each(_changes.begin(), _changes.end(), 
671                  boost::bind (
672                          boost::bind (&XMLNode::add_child_nocopy, *changes, _1),
673                          boost::bind (&DiffCommand::marshal_change, this, _1)));
674
675         return *diff_command;
676 }
677
678 /** Write the model to a MidiSource (i.e. save the model).
679  * This is different from manually using read to write to a source in that
680  * note off events are written regardless of the track mode.  This is so the
681  * user can switch a recorded track (with note durations from some instrument)
682  * to percussive, save, reload, then switch it back to sustained without
683  * destroying the original note durations.
684  */
685 bool
686 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
687 {
688         ReadLock lock(read_lock());
689
690         const bool old_percussive = percussive();
691         set_percussive(false);
692
693         source->drop_model();
694         source->mark_streaming_midi_write_started(note_mode(), _midi_source->timeline_position());
695
696         for (Evoral::Sequence<TimeType>::const_iterator i = begin(); i != end(); ++i) {
697                 source->append_event_unlocked_beats(*i);
698         }
699
700         set_percussive(old_percussive);
701         source->mark_streaming_write_completed();
702
703         set_edited(false);
704
705         return true;
706 }
707
708 XMLNode&
709 MidiModel::get_state()
710 {
711         XMLNode *node = new XMLNode("MidiModel");
712         return *node;
713 }
714
715 boost::shared_ptr<Evoral::Note<MidiModel::TimeType> >
716 MidiModel::find_note (boost::shared_ptr<Evoral::Note<TimeType> > other)
717 {
718         Notes::iterator l = notes().lower_bound(other);
719
720         if (l != notes().end()) {
721                 for (; (*l)->time() == other->time(); ++l) {
722                         if (*l == other) {
723                                 return *l;
724                         }
725                 }
726         }
727
728         return boost::shared_ptr<Evoral::Note<TimeType> >();
729 }
730
731 /** Lock and invalidate the source.
732  * This should be used by commands and editing things
733  */
734 MidiModel::WriteLock
735 MidiModel::edit_lock()
736 {
737         Glib::Mutex::Lock* source_lock = new Glib::Mutex::Lock(_midi_source->mutex());
738         _midi_source->invalidate(); // Release cached iterator's read lock on model
739         return WriteLock(new WriteLockImpl(source_lock, _lock, _control_lock));
740 }
741
742 /** Lock just the model, the source lock must already be held.
743  * This should only be called from libardour/evoral places
744  */
745 MidiModel::WriteLock
746 MidiModel::write_lock()
747 {
748         assert(!_midi_source->mutex().trylock());
749         return WriteLock(new WriteLockImpl(NULL, _lock, _control_lock));
750 }