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