Factor out sequencing related things into an independant new library: "evoral".
[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 MidiModel::MidiModel(MidiSource *s, size_t size)
40         : ControlSet()
41         , Automatable(s->session(), "midi model")
42         , Sequence(size)
43         , _midi_source(s)
44 {
45 }
46
47 /** Start a new 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* MidiModel::new_delta_command(const string name)
54 {
55         DeltaCommand* cmd = new DeltaCommand(_midi_source->model(), name);
56         return cmd;
57 }
58
59 /** Apply a command.
60  *
61  * Ownership of cmd is taken, it must not be deleted by the caller.
62  * The command will constitute one item on the undo stack.
63  */
64 void
65 MidiModel::apply_command(Command* cmd)
66 {
67         _session.begin_reversible_command(cmd->name());
68         (*cmd)();
69         assert(is_sorted());
70         _session.commit_reversible_command(cmd);
71         _edited = true;
72 }
73
74
75 // DeltaCommand
76
77 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
78                 const std::string& name)
79         : Command(name)
80         , _model(m)
81         , _name(name)
82 {
83 }
84
85 MidiModel::DeltaCommand::DeltaCommand(boost::shared_ptr<MidiModel> m,
86                 const XMLNode& node)
87         : _model(m)
88 {
89         set_state(node);
90 }
91
92 void
93 MidiModel::DeltaCommand::add(const boost::shared_ptr<Evoral::Note> note)
94 {
95         //cerr << "MEC: apply" << endl;
96         _removed_notes.remove(note);
97         _added_notes.push_back(note);
98 }
99
100 void
101 MidiModel::DeltaCommand::remove(const boost::shared_ptr<Evoral::Note> note)
102 {
103         //cerr << "MEC: remove" << endl;
104         _added_notes.remove(note);
105         _removed_notes.push_back(note);
106 }
107
108 void
109 MidiModel::DeltaCommand::operator()()
110 {
111         // This could be made much faster by using a priority_queue for added and
112         // removed notes (or sort here), and doing a single iteration over _model
113
114         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
115         const bool reset_iter = (_model->_read_iter.locked());
116         double iter_time = -1.0;
117
118         if (reset_iter) {
119                 if (_model->_read_iter.get_event_pointer().get()) {
120                         iter_time = _model->_read_iter->time();
121                 } else {
122                         cerr << "MidiModel::DeltaCommand::operator(): WARNING: _read_iter points to no event" << endl;
123                 }
124                 _model->_read_iter = _model->end(); // drop read lock
125         }
126
127         assert( ! _model->_read_iter.locked());
128
129         _model->write_lock();
130
131         for (std::list< boost::shared_ptr<Evoral::Note> >::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
132                 _model->add_note_unlocked(*i);
133
134         for (std::list< boost::shared_ptr<Evoral::Note> >::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
135                 _model->remove_note_unlocked(*i);
136
137         _model->write_unlock();
138
139         if (reset_iter && iter_time != -1.0) {
140                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
141         }
142
143         _model->ContentsChanged(); /* EMIT SIGNAL */
144 }
145
146 void
147 MidiModel::DeltaCommand::undo()
148 {
149         // This could be made much faster by using a priority_queue for added and
150         // removed notes (or sort here), and doing a single iteration over _model
151
152         // Need to reset iterator to drop the read lock it holds, or we'll deadlock
153         const bool reset_iter = (_model->_read_iter.locked());
154         double iter_time = -1.0;
155
156         if (reset_iter) {
157                 if (_model->_read_iter.get_event_pointer().get()) {
158                         iter_time = _model->_read_iter->time();
159                 } else {
160                         cerr << "MidiModel::DeltaCommand::undo(): WARNING: _read_iter points to no event" << endl;
161                 }
162                 _model->_read_iter = _model->end(); // drop read lock
163         }
164
165         assert( ! _model->_read_iter.locked());
166
167         _model->write_lock();
168
169         for (std::list< boost::shared_ptr<Evoral::Note> >::iterator i = _added_notes.begin(); i
170                         != _added_notes.end(); ++i)
171                 _model->remove_note_unlocked(*i);
172
173         for (std::list< boost::shared_ptr<Evoral::Note> >::iterator i =
174                         _removed_notes.begin(); i != _removed_notes.end(); ++i)
175                 _model->add_note_unlocked(*i);
176
177         _model->write_unlock();
178
179         if (reset_iter && iter_time != -1.0) {
180                 _model->_read_iter = const_iterator(*_model.get(), iter_time);
181         }
182
183         _model->ContentsChanged(); /* EMIT SIGNAL */
184 }
185
186 XMLNode&
187 MidiModel::DeltaCommand::marshal_note(const boost::shared_ptr<Evoral::Note> note)
188 {
189         XMLNode *xml_note = new XMLNode("note");
190         ostringstream note_str(ios::ate);
191         note_str << int(note->note());
192         xml_note->add_property("note", note_str.str());
193
194         ostringstream channel_str(ios::ate);
195         channel_str << int(note->channel());
196         xml_note->add_property("channel", channel_str.str());
197
198         ostringstream time_str(ios::ate);
199         time_str << int(note->time());
200         xml_note->add_property("time", time_str.str());
201
202         ostringstream duration_str(ios::ate);
203         duration_str <<(unsigned int) note->duration();
204         xml_note->add_property("duration", duration_str.str());
205
206         ostringstream velocity_str(ios::ate);
207         velocity_str << (unsigned int) note->velocity();
208         xml_note->add_property("velocity", velocity_str.str());
209
210         return *xml_note;
211 }
212
213 boost::shared_ptr<Evoral::Note> MidiModel::DeltaCommand::unmarshal_note(XMLNode *xml_note)
214 {
215         unsigned int note;
216         istringstream note_str(xml_note->property("note")->value());
217         note_str >> note;
218
219         unsigned int channel;
220         istringstream channel_str(xml_note->property("channel")->value());
221         channel_str >> channel;
222
223         unsigned int time;
224         istringstream time_str(xml_note->property("time")->value());
225         time_str >> time;
226
227         unsigned int duration;
228         istringstream duration_str(xml_note->property("duration")->value());
229         duration_str >> duration;
230
231         unsigned int velocity;
232         istringstream velocity_str(xml_note->property("velocity")->value());
233         velocity_str >> velocity;
234
235         boost::shared_ptr<Evoral::Note> note_ptr(new Evoral::Note(channel, time, duration, note, velocity));
236         return note_ptr;
237 }
238
239 #define ADDED_NOTES_ELEMENT "added_notes"
240 #define REMOVED_NOTES_ELEMENT "removed_notes"
241 #define DELTA_COMMAND_ELEMENT "DeltaCommand"
242
243 int MidiModel::DeltaCommand::set_state(const XMLNode& delta_command)
244 {
245         if (delta_command.name() != string(DELTA_COMMAND_ELEMENT)) {
246                 return 1;
247         }
248
249         _added_notes.clear();
250         XMLNode *added_notes = delta_command.child(ADDED_NOTES_ELEMENT);
251         XMLNodeList notes = added_notes->children();
252         transform(notes.begin(), notes.end(), back_inserter(_added_notes),
253                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
254
255         _removed_notes.clear();
256         XMLNode *removed_notes = delta_command.child(REMOVED_NOTES_ELEMENT);
257         notes = removed_notes->children();
258         transform(notes.begin(), notes.end(), back_inserter(_removed_notes),
259                         sigc::mem_fun(*this, &DeltaCommand::unmarshal_note));
260
261         return 0;
262 }
263
264 XMLNode& MidiModel::DeltaCommand::get_state()
265 {
266         XMLNode *delta_command = new XMLNode(DELTA_COMMAND_ELEMENT);
267         delta_command->add_property("midi_source", _model->midi_source()->id().to_s());
268
269         XMLNode *added_notes = delta_command->add_child(ADDED_NOTES_ELEMENT);
270         for_each(_added_notes.begin(), _added_notes.end(), sigc::compose(
271                         sigc::mem_fun(*added_notes, &XMLNode::add_child_nocopy),
272                         sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
273
274         XMLNode *removed_notes = delta_command->add_child(REMOVED_NOTES_ELEMENT);
275         for_each(_removed_notes.begin(), _removed_notes.end(), sigc::compose(
276                         sigc::mem_fun(*removed_notes, &XMLNode::add_child_nocopy),
277                         sigc::mem_fun(*this, &DeltaCommand::marshal_note)));
278
279         return *delta_command;
280 }
281
282 struct EventTimeComparator {
283         typedef const Evoral::Event* value_type;
284         inline bool operator()(const Evoral::Event& a, const Evoral::Event& b) const {
285                 return a.time() >= b.time();
286         }
287 };
288
289 /** Write the model to a MidiSource (i.e. save the model).
290  * This is different from manually using read to write to a source in that
291  * note off events are written regardless of the track mode.  This is so the
292  * user can switch a recorded track (with note durations from some instrument)
293  * to percussive, save, reload, then switch it back to sustained without
294  * destroying the original note durations.
295  */
296 bool MidiModel::write_to(boost::shared_ptr<MidiSource> source)
297 {
298         read_lock();
299
300         const bool old_percussive = percussive();
301         set_percussive(false);
302         
303         for (const_iterator i = begin(); i != end(); ++i) {
304                 source->append_event_unlocked(Frames, *i);
305         }
306                 
307         set_percussive(old_percussive);
308         
309         read_unlock();
310         _edited = false;
311
312         return true;
313 }
314
315 XMLNode& MidiModel::get_state()
316 {
317         XMLNode *node = new XMLNode("MidiModel");
318         return *node;
319 }
320