Saving of edited MIDI data to disk (on session save).
[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 #include <iostream>
22 #include <algorithm>
23 #include <pbd/enumwriter.h>
24 #include <ardour/midi_model.h>
25 #include <ardour/midi_events.h>
26 #include <ardour/midi_source.h>
27 #include <ardour/types.h>
28 #include <ardour/session.h>
29
30 using namespace std;
31 using namespace ARDOUR;
32
33 // Note
34
35 MidiModel::Note::Note(double t, double d, uint8_t n, uint8_t v)
36         : _on_event(t, 3, NULL, true)
37         , _off_event(t + d, 3, NULL, true)
38 {
39         _on_event.buffer()[0] = MIDI_CMD_NOTE_ON;
40         _on_event.buffer()[1] = n;
41         _on_event.buffer()[2] = v;
42         
43         _off_event.buffer()[0] = MIDI_CMD_NOTE_OFF;
44         _off_event.buffer()[1] = n;
45         _off_event.buffer()[2] = 0x40;
46         
47         assert(time() == t);
48         assert(duration() == d);
49         assert(note() == n);
50         assert(velocity() == v);
51 }
52
53
54 MidiModel::Note::Note(const Note& copy)
55         : _on_event(copy._on_event, true)
56         , _off_event(copy._off_event, true)
57 {
58         /*
59         assert(copy._on_event.size == 3);
60         _on_event.buffer = _on_event_buffer;
61         memcpy(_on_event_buffer, copy._on_event_buffer, 3);
62         
63         assert(copy._off_event.size == 3);
64         _off_event.buffer = _off_event_buffer;
65         memcpy(_off_event_buffer, copy._off_event_buffer, 3);
66         */
67
68         assert(time() == copy.time());
69         assert(end_time() == copy.end_time());
70         assert(note() == copy.note());
71         assert(velocity() == copy.velocity());
72         assert(duration() == copy.duration());
73 }
74
75
76 const MidiModel::Note&
77 MidiModel::Note::operator=(const Note& copy)
78 {
79         _on_event = copy._on_event;
80         _off_event = copy._off_event;
81         /*_on_event.time = copy._on_event.time;
82         assert(copy._on_event.size == 3);
83         memcpy(_on_event_buffer, copy._on_event_buffer, 3);
84         
85         _off_event.time = copy._off_event.time;
86         assert(copy._off_event.size == 3);
87         memcpy(_off_event_buffer, copy._off_event_buffer, 3);
88         */
89         
90         assert(time() == copy.time());
91         assert(end_time() == copy.end_time());
92         assert(note() == copy.note());
93         assert(velocity() == copy.velocity());
94         assert(duration() == copy.duration());
95
96         return *this;
97 }
98
99 // MidiModel
100
101 MidiModel::MidiModel(Session& s, size_t size)
102         : _session(s)
103         , _notes(size)
104         , _note_mode(Sustained)
105         , _writing(false)
106         , _edited(false)
107         , _active_notes(LaterNoteEndComparator())
108 {
109 }
110
111
112 /** Read events in frame range \a start .. \a start+cnt into \a dst,
113  * adding \a stamp_offset to each event's timestamp.
114  * \return number of events written to \a dst
115  */
116 size_t
117 MidiModel::read (MidiRingBuffer& dst, nframes_t start, nframes_t nframes, nframes_t stamp_offset) const
118 {
119         size_t read_events = 0;
120
121         cerr << "MM READ @ " << start << " + " << nframes << endl;
122
123         /* FIXME: cache last lookup value to avoid the search */
124
125         if (_note_mode == Sustained) {
126
127                 /* FIXME: cache last lookup value to avoid the search */
128                 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
129
130                         cerr << "MM NOTE " << n->time() << endl;
131
132                         while ( ! _active_notes.empty() ) {
133                                 const Note* const earliest_off = _active_notes.top();
134                                 const MidiEvent&  off_ev       = earliest_off->off_event();
135                                 if (off_ev.time() < start + nframes && off_ev.time() <= n->time()) {
136                                         dst.write(off_ev.time() + stamp_offset, off_ev.size(), off_ev.buffer());
137                                         _active_notes.pop();
138                                         ++read_events;
139                                 } else {
140                                         break;
141                                 }
142                         }
143
144                         if (n->time() >= start + nframes)
145                                 break;
146
147                         // Note on
148                         if (n->time() >= start) {
149                                 const MidiEvent& on_ev = n->on_event();
150                                 dst.write(on_ev.time() + stamp_offset, on_ev.size(), on_ev.buffer());
151                                 _active_notes.push(&(*n));
152                                 ++read_events;
153                         }
154
155                 }
156
157         // Percussive
158         } else {
159                 for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
160                         // Note on
161                         if (n->time() >= start) {
162                                 if (n->time() < start + nframes) {
163                                         const MidiEvent& ev = n->on_event();
164                                         dst.write(ev.time() + stamp_offset, ev.size(), ev.buffer());
165                                         ++read_events;
166                                 } else {
167                                         break;
168                                 }
169                         }
170                 }
171         }
172
173         //if (read_events > 0)
174         //      cerr << "MM READ " << read_events << " EVENTS" << endl;
175
176         return read_events;
177 }
178
179
180 /** Begin a write of events to the model.
181  *
182  * If \a mode is Sustained, complete notes with duration are constructed as note
183  * on/off events are received.  Otherwise (Percussive), only note on events are
184  * stored; note off events are discarded entirely and all contained notes will
185  * have duration 0.
186  */
187 void
188 MidiModel::start_write()
189 {
190         //cerr << "MM START WRITE, MODE = " << enum_2_string(_note_mode) << endl;
191         _write_notes.clear();
192         _writing = true;
193 }
194
195
196
197 /** Finish a write of events to the model.
198  *
199  * If \a delete_stuck is true and the current mode is Sustained, note on events
200  * that were never resolved with a corresonding note off will be deleted.
201  * Otherwise they will remain as notes with duration 0.
202  */
203 void
204 MidiModel::end_write(bool delete_stuck)
205 {
206         assert(_writing);
207         
208         //cerr << "MM END WRITE\n";
209
210         if (_note_mode == Sustained && delete_stuck) {
211                 for (Notes::iterator n = _notes.begin(); n != _notes.end() ; ) {
212                         if (n->duration() == 0) {
213                                 cerr << "WARNING: Stuck note lost: " << n->note() << endl;
214                                 n = _notes.erase(n);
215                         } else {
216                                 ++n;
217                         }
218                 }
219         }
220
221         _write_notes.clear();
222         _writing = false;
223 }
224
225
226 /** Append contents of \a buf to model.  NOT realtime safe.
227  *
228  * Timestamps of events in \a buf are expected to be relative to
229  * the start of this model (t=0) and MUST be monotonically increasing
230  * and MUST be >= the latest event currently in the model.
231  *
232  * Events in buf are deep copied.
233  */
234 void
235 MidiModel::append(const MidiBuffer& buf)
236
237         assert(_writing);
238
239         _lock.writer_lock();
240
241         for (MidiBuffer::const_iterator i = buf.begin(); i != buf.end(); ++i) {
242                 const MidiEvent& ev = *i;
243                 
244                 assert(_notes.empty() || ev.time() >= _notes.back().time());
245
246                 if (ev.type() == MIDI_CMD_NOTE_ON)
247                         append_note_on(ev.time(), ev.note(), ev.velocity());
248                 else if (ev.type() == MIDI_CMD_NOTE_OFF)
249                         append_note_off(ev.time(), ev.note());
250         }
251         
252         _lock.writer_unlock();
253 }
254
255
256 /** Append \a in_event to model.  NOT realtime safe.
257  *
258  * Timestamps of events in \a buf are expected to be relative to
259  * the start of this model (t=0) and MUST be monotonically increasing
260  * and MUST be >= the latest event currently in the model.
261  */
262 void
263 MidiModel::append(double time, size_t size, const Byte* buf)
264 {
265         assert(_notes.empty() || time >= _notes.back().time());
266         assert(_writing);
267
268         if ((buf[0] & 0xF0) == MIDI_CMD_NOTE_ON)
269                 append_note_on(time, buf[1], buf[2]);
270         else if ((buf[0] & 0xF0) == MIDI_CMD_NOTE_OFF)
271                 append_note_off(time, buf[1]);
272 }
273
274
275 void
276 MidiModel::append_note_on(double time, uint8_t note_num, uint8_t velocity)
277 {
278         assert(_writing);
279         _notes.push_back(Note(time, 0, note_num, velocity));
280         if (_note_mode == Sustained) {
281                 //cerr << "MM Appending note on " << (unsigned)(uint8_t)note_num << endl;
282                 _write_notes.push_back(_notes.size() - 1);
283         } else {
284                 //cerr << "MM NOT appending note on" << endl;
285         }
286 }
287
288
289 void
290 MidiModel::append_note_off(double time, uint8_t note_num)
291 {
292         assert(_writing);
293         if (_note_mode == Percussive) {
294                 //cerr << "MM Ignoring note off (percussive mode)" << endl;
295                 return;
296         } else {
297                 //cerr << "MM Attempting to resolve note off " << (unsigned)(uint8_t)note_num << endl;
298         }
299
300         /* FIXME: make _write_notes fixed size (127 noted) for speed */
301         
302         /* FIXME: note off velocity for that one guy out there who actually has
303          * keys that send it */
304
305         for (WriteNotes::iterator n = _write_notes.begin(); n != _write_notes.end(); ++n) {
306                 Note& note = _notes[*n];
307                 //cerr << (unsigned)(uint8_t)note.note() << " ? " << (unsigned)note_num << endl;
308                 if (note.note() == note_num) {
309                         assert(time > note.time());
310                         note.set_duration(time - note.time());
311                         _write_notes.erase(n);
312                         //cerr << "MidiModel resolved note, duration: " << note.duration() << endl;
313                         break;
314                 }
315         }
316 }
317
318
319 void
320 MidiModel::add_note_unlocked(const Note& note)
321 {
322         cerr << "MidiModel " << this << " add note " << (int)note.note() << " @ " << note.time() << endl;
323         Notes::iterator i = upper_bound(_notes.begin(), _notes.end(), note, note_time_comparator);
324         _notes.insert(i, note);
325 }
326
327
328 void
329 MidiModel::remove_note_unlocked(const Note& note)
330 {
331         cerr << "MidiModel " << this << " remove note " << (int)note.note() << " @ " << note.time() << endl;
332         Notes::iterator n = find(_notes.begin(), _notes.end(), note);
333         if (n != _notes.end())
334                 _notes.erase(n);
335 }
336
337 /** Slow!  for debugging only. */
338 bool
339 MidiModel::is_sorted() const
340 {
341         bool t = 0;
342         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n)
343                 if (n->time() < t)
344                         return false;
345                 else
346                         t = n->time();
347
348         return true;
349 }
350
351
352 /** Start a new command.
353  *
354  * This has no side-effects on the model or Session, the returned command
355  * can be held on to for as long as the caller wishes, or discarded without
356  * formality, until apply_command is called and ownership is taken.
357  */
358 MidiModel::DeltaCommand*
359 MidiModel::new_delta_command(const string name)
360 {
361         DeltaCommand* cmd =  new DeltaCommand(*this, name);
362         return cmd;
363 }
364
365
366 /** Apply a command.
367  *
368  * Ownership of cmd is taken, it must not be deleted by the caller.
369  * The command will constitute one item on the undo stack.
370  */
371 void
372 MidiModel::apply_command(Command* cmd)
373 {
374         _session.begin_reversible_command(cmd->name());
375         (*cmd)();
376         assert(is_sorted());
377         _session.commit_reversible_command(cmd);
378         _edited = true;
379 }
380
381
382 // MidiEditCommand
383
384
385 void
386 MidiModel::DeltaCommand::add(const Note& note)
387 {
388         //cerr << "MEC: apply" << endl;
389
390         _removed_notes.remove(note);
391         _added_notes.push_back(note);
392 }
393
394
395 void
396 MidiModel::DeltaCommand::remove(const Note& note)
397 {
398         //cerr << "MEC: remove" << endl;
399
400         _added_notes.remove(note);
401         _removed_notes.push_back(note);
402 }
403
404                 
405 void 
406 MidiModel::DeltaCommand::operator()()
407 {
408         // This could be made much faster by using a priority_queue for added and
409         // removed notes (or sort here), and doing a single iteration over _model
410         
411         _model._lock.writer_lock();
412         
413         for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
414                 _model.add_note_unlocked(*i);
415         
416         for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
417                 _model.remove_note_unlocked(*i);
418         
419         _model._lock.writer_unlock();
420         
421         _model.ContentsChanged(); /* EMIT SIGNAL */
422 }
423
424
425 void
426 MidiModel::DeltaCommand::undo()
427 {
428         // This could be made much faster by using a priority_queue for added and
429         // removed notes (or sort here), and doing a single iteration over _model
430         
431         _model._lock.writer_lock();
432
433         for (std::list<Note>::iterator i = _added_notes.begin(); i != _added_notes.end(); ++i)
434                 _model.remove_note_unlocked(*i);
435         
436         for (std::list<Note>::iterator i = _removed_notes.begin(); i != _removed_notes.end(); ++i)
437                 _model.add_note_unlocked(*i);
438         
439         _model._lock.writer_unlock();
440         
441         _model.ContentsChanged(); /* EMIT SIGNAL */
442 }
443
444
445 bool
446 MidiModel::write_to(boost::shared_ptr<MidiSource> source)
447 {
448         cerr << "Writing model to " << source->name() << endl;
449
450         /* This could be done using a temporary MidiRingBuffer and using
451          * MidiModel::read and MidiSource::write, but this is more efficient
452          * and doesn't require any buffer size assumptions (ie it's worth
453          * the code duplication).
454          *
455          * This is also different from read in that note off events are written
456          * regardless of the track mode.  This is so the user can switch a
457          * recorded track (with note durations from some instrument) to percussive,
458          * save, reload, then switch it back to sustained preserving the original
459          * note durations.
460          */
461
462         /* Percussive 
463         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
464                 const MidiEvent& ev = n->on_event();
465                 source->append_event_unlocked(ev);
466         }*/
467
468         _lock.reader_lock();
469
470         LaterNoteEndComparator cmp;
471         ActiveNotes active_notes(cmp);
472                 
473         // Foreach note
474         for (Notes::const_iterator n = _notes.begin(); n != _notes.end(); ++n) {
475
476                 // Write any pending note offs earlier than this note on
477                 while ( ! active_notes.empty() ) {
478                         const Note* const earliest_off = active_notes.top();
479                         const MidiEvent&  off_ev       = earliest_off->off_event();
480                         if (off_ev.time() <= n->time()) {
481                                 source->append_event_unlocked(off_ev);
482                                 active_notes.pop();
483                         } else {
484                                 break;
485                         }
486                 }
487
488                 // Write this note on
489                 source->append_event_unlocked(n->on_event());
490                 if (n->duration() > 0)
491                         active_notes.push(&(*n));
492         }
493
494         _edited = false;
495         
496         _lock.reader_unlock();
497
498         return true;
499 }
500