Fix stuck notes in short MIDI regions.
[ardour.git] / libs / ardour / midi_playlist.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Author: David 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 #include <cassert>
21
22 #include <algorithm>
23 #include <iostream>
24 #include <utility>
25
26 #include <stdlib.h>
27
28 #include "evoral/EventList.hpp"
29
30 #include "ardour/debug.h"
31 #include "ardour/midi_model.h"
32 #include "ardour/midi_playlist.h"
33 #include "ardour/midi_region.h"
34 #include "ardour/midi_state_tracker.h"
35 #include "ardour/types.h"
36
37 #include "i18n.h"
38
39 using namespace ARDOUR;
40 using namespace PBD;
41 using namespace std;
42
43 MidiPlaylist::MidiPlaylist (Session& session, const XMLNode& node, bool hidden)
44         : Playlist (session, node, DataType::MIDI, hidden)
45         , _note_mode(Sustained)
46 {
47 #ifndef NDEBUG
48         const XMLProperty* prop = node.property("type");
49         assert(prop && DataType(prop->value()) == DataType::MIDI);
50 #endif
51
52         in_set_state++;
53         if (set_state (node, Stateful::loading_state_version)) {
54                 throw failed_constructor ();
55         }
56         in_set_state--;
57
58         relayer ();
59 }
60
61 MidiPlaylist::MidiPlaylist (Session& session, string name, bool hidden)
62         : Playlist (session, name, DataType::MIDI, hidden)
63         , _note_mode(Sustained)
64 {
65 }
66
67 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other, string name, bool hidden)
68         : Playlist (other, name, hidden)
69         , _note_mode(other->_note_mode)
70 {
71 }
72
73 MidiPlaylist::MidiPlaylist (boost::shared_ptr<const MidiPlaylist> other, framepos_t start, framecnt_t dur, string name, bool hidden)
74         : Playlist (other, start, dur, name, hidden)
75         , _note_mode(other->_note_mode)
76 {
77         /* this constructor does NOT notify others (session) */
78 }
79
80 MidiPlaylist::~MidiPlaylist ()
81 {
82 }
83
84 template<typename Time>
85 struct EventsSortByTimeAndType {
86     bool operator() (Evoral::Event<Time>* a, Evoral::Event<Time>* b) {
87             if (a->time() == b->time()) {
88                     if (parameter_is_midi ((AutomationType)a->event_type()) &&
89                         parameter_is_midi ((AutomationType)b->event_type())) {
90                             /* negate return value since we must return whether
91                              * or not a should sort before b, not b before a
92                              */
93                             return !MidiBuffer::second_simultaneous_midi_byte_is_first (a->buffer()[0], b->buffer()[0]);
94                     }
95             }
96             return a->time() < b->time();
97     }
98 };
99
100 /** Returns the number of frames in time duration read (eg could be large when 0 events are read) */
101 framecnt_t
102 MidiPlaylist::read (Evoral::EventSink<framepos_t>& dst, framepos_t start, framecnt_t dur, unsigned chan_n)
103 {
104         /* this function is never called from a realtime thread, so
105            its OK to block (for short intervals).
106         */
107
108         Playlist::RegionReadLock rl (this);
109
110         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("++++++ %1 .. %2  +++++++ %3 trackers +++++++++++++++++\n", 
111                                                             start, start + dur, _note_trackers.size()));
112
113         framepos_t end = start + dur - 1;
114
115         // relevent regions overlapping start <--> end
116         vector< boost::shared_ptr<Region> > regs;
117         vector< boost::shared_ptr<Region> > ended;
118         typedef pair<MidiStateTracker*,framepos_t> TrackerInfo;
119         vector<TrackerInfo> tracker_info;
120         NoteTrackers::iterator t;
121
122         for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
123
124                 /* in this call to coverage, the return value indicates the
125                  * overlap status of the read range (start...end) WRT to 
126                  * the region.
127                  */
128
129                 switch ((*i)->coverage (start, end)) {
130                 case Evoral::OverlapStart:
131                 case Evoral::OverlapInternal:
132                         regs.push_back (*i);
133                         break;
134
135                 case Evoral::OverlapExternal:
136                         /* this region is entirely contained in the read range */
137                         regs.push_back (*i);
138                         ended.push_back (*i);
139                         break;
140
141                 case Evoral::OverlapEnd:
142                         /* this region ends within the read range */
143                         regs.push_back (*i);
144                         ended.push_back (*i);
145                         break;
146                 default:
147                         /* we don't care */
148                         break;
149                 }
150         }
151
152         if (regs.size() == 1 && 
153             (ended.empty() || (ended.size() == 1 && ended.front() == regs.front()))) {
154
155                 /* just a single region - read directly into dst */
156
157                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Single region (%1) read, ended during this read %2\n", regs.front()->name(),
158                                                                     ended.size()));
159
160                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(regs.front());
161
162                 if (mr) {
163
164                         NoteTrackers::iterator t = _note_trackers.find (mr.get());
165                         MidiStateTracker* tracker;
166                         bool new_tracker = false;
167
168                         if (t == _note_trackers.end()) {
169                                 tracker = new MidiStateTracker;
170                                 new_tracker = true;
171                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tBEFORE: new tracker\n");
172                         } else {
173                                 tracker = t->second;
174                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tBEFORE: tracker says there are %1 on notes\n", tracker->on()));
175                         }
176
177                         mr->read_at (dst, start, dur, chan_n, _note_mode, tracker);
178                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tAFTER: tracker says there are %1 on notes\n", tracker->on()));
179
180                         if (!ended.empty()) {
181                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1 ended in this read, resolve notes and delete (%2) tracker\n",
182                                                                                     mr->name(), ((new_tracker) ? "new" : "old")));
183                                 tracker->resolve_notes (dst, mr->last_frame());
184                                 delete tracker;
185                                 if (!new_tracker) {
186                                         _note_trackers.erase (t);
187                                 }
188                         } else {
189                                 if (new_tracker) {
190                                         pair<Region*,MidiStateTracker*> newpair;
191                                         newpair.first = mr.get();
192                                         newpair.second = tracker;
193                                         _note_trackers.insert (newpair);
194                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
195                                 }
196                         }
197                 }
198
199         } else {
200
201                 /* multiple regions and/or note resolution: sort by layer, read into a temporary non-monotonically
202                    sorted EventSink, sort and then insert into dst.
203                 */
204
205                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("%1 regions to read, plus %2 trackers\n", regs.size(), tracker_info.size()));
206
207                 Evoral::EventList<framepos_t> evlist;
208
209                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("for %1 .. %2 we have %3 to consider\n", start, start+dur-1, regs.size()));
210
211                 for (vector<boost::shared_ptr<Region> >::iterator i = regs.begin(); i != regs.end(); ++i) {
212
213                         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*i);
214
215                         if (!mr) {
216                                 continue;
217                         }
218
219                         NoteTrackers::iterator t = _note_trackers.find (mr.get());
220                         MidiStateTracker* tracker;
221                         bool new_tracker = false;
222
223                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Before %1 (%2 .. %3) we now have %4 events\n", mr->name(), mr->position(), mr->last_frame(), evlist.size()));
224
225                         if (t == _note_trackers.end()) {
226                                 tracker = new MidiStateTracker;
227                                 new_tracker = true;
228                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tBEFORE: new tracker\n");
229                         } else {
230                                 tracker = t->second;
231                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tBEFORE: tracker says there are %1 on notes\n", tracker->on()));
232                         }
233
234
235                         mr->read_at (evlist, start, dur, chan_n, _note_mode, tracker);
236
237 #ifndef NDEBUG
238                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("After %1 (%2 .. %3) we now have %4\n", mr->name(), mr->position(), mr->last_frame(), evlist.size()));
239                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
240                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
241                         }
242                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tAFTER: tracker says there are %1 on notes\n", tracker->on()));
243 #endif
244                         if (find (ended.begin(), ended.end(), *i) != ended.end()) {
245
246                                 /* the region ended within the read range, so
247                                  * resolve any dangling notes (i.e. notes whose
248                                  * end is beyond the end of the region).
249                                  */
250                                 
251                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1 ended in this read, resolve notes and delete (%2) tracker\n",
252                                                                                     mr->name(), ((new_tracker) ? "new" : "old")));
253
254                                 tracker->resolve_notes (evlist, (*i)->last_frame());
255                                 delete tracker;
256                                 if (!new_tracker) {
257                                         _note_trackers.erase (t);
258                                 }
259
260                         } else {
261
262                                 if (new_tracker) {
263                                         _note_trackers.insert (make_pair (mr.get(), tracker));
264                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
265                                 }
266                         }
267                 }
268
269                 if (!evlist.empty()) {
270
271                         /* sort the event list */
272                         EventsSortByTimeAndType<framepos_t> cmp;
273                         evlist.sort (cmp);
274
275 #ifndef NDEBUG
276                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Final we now have %1 events\n",  evlist.size()));
277                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
278                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
279                         }
280 #endif
281                         /* write into dst */
282                         for (Evoral::EventList<framepos_t>::iterator e = evlist.begin(); e != evlist.end(); ++e) {
283                                 Evoral::Event<framepos_t>* ev (*e);
284                                 dst.write (ev->time(), ev->event_type(), ev->size(), ev->buffer());
285                                 delete ev;
286                         }
287
288                 }
289         }
290
291         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "-------------------------------------------------------------\n");
292         return dur;
293 }
294
295 void
296 MidiPlaylist::reset_note_trackers ()
297 {
298         Playlist::RegionWriteLock rl (this, false);
299
300         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
301                 delete n->second;
302         }
303         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 reset all note trackers\n", name()));
304         _note_trackers.clear ();
305 }
306
307 void
308 MidiPlaylist::resolve_note_trackers (Evoral::EventSink<framepos_t>& dst, framepos_t time)
309 {
310         Playlist::RegionWriteLock rl (this, false);
311
312         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
313                 n->second->resolve_notes(dst, time);
314                 delete n->second;
315         }
316         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 resolve all note trackers\n", name()));
317         _note_trackers.clear ();
318 }
319
320 void
321 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
322 {
323         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
324         NoteTrackers::iterator t = _note_trackers.find (region.get());
325
326         /* GACK! THREAD SAFETY! */
327
328         if (t != _note_trackers.end()) {
329                 delete t->second;
330                 _note_trackers.erase (t);
331         }
332 }
333
334 int
335 MidiPlaylist::set_state (const XMLNode& node, int version)
336 {
337         in_set_state++;
338         freeze ();
339
340         if (Playlist::set_state (node, version)) {
341                 return -1;
342         }
343
344         thaw();
345         in_set_state--;
346
347         return 0;
348 }
349
350 void
351 MidiPlaylist::dump () const
352 {
353         boost::shared_ptr<Region> r;
354
355         cerr << "Playlist \"" << _name << "\" " << endl
356         << regions.size() << " regions "
357         << endl;
358
359         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
360                 r = *i;
361                 cerr << "  " << r->name() << " @ " << r << " ["
362                 << r->start() << "+" << r->length()
363                 << "] at "
364                 << r->position()
365                 << " on layer "
366                 << r->layer ()
367                 << endl;
368         }
369 }
370
371 bool
372 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
373 {
374         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
375
376         if (!r) {
377                 return false;
378         }
379
380         bool changed = false;
381
382         {
383                 RegionWriteLock rlock (this);
384                 RegionList::iterator i;
385                 RegionList::iterator tmp;
386
387                 for (i = regions.begin(); i != regions.end(); ) {
388
389                         tmp = i;
390                         ++tmp;
391
392                         if ((*i) == region) {
393                                 regions.erase (i);
394                                 changed = true;
395                         }
396
397                         i = tmp;
398                 }
399         }
400
401
402         if (changed) {
403                 /* overload this, it normally means "removed", not destroyed */
404                 notify_region_removed (region);
405         }
406
407         return changed;
408 }
409
410 set<Evoral::Parameter>
411 MidiPlaylist::contained_automation()
412 {
413         /* this function is never called from a realtime thread, so
414            its OK to block (for short intervals).
415         */
416
417         Playlist::RegionReadLock rl (this);
418         set<Evoral::Parameter> ret;
419
420         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
421                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
422
423                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
424                                 c != mr->model()->controls().end(); ++c) {
425                         ret.insert(c->first);
426                 }
427         }
428
429         return ret;
430 }
431
432
433 bool
434 MidiPlaylist::region_changed (const PBD::PropertyChange& what_changed, boost::shared_ptr<Region> region)
435 {
436         if (in_flush || in_set_state) {
437                 return false;
438         }
439
440         PBD::PropertyChange our_interests;
441         our_interests.add (Properties::midi_data);
442
443         bool parent_wants_notify = Playlist::region_changed (what_changed, region);
444
445         if (parent_wants_notify || what_changed.contains (our_interests)) {
446                 notify_contents_changed ();
447         }
448
449         return true;
450 }
451