Support fancy controls for some AU units.
[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                 case Evoral::OverlapExternal:
133                         regs.push_back (*i);
134                         break;
135
136                 case Evoral::OverlapEnd:
137                         /* this region ends within the read range */
138                         regs.push_back (*i);
139                         ended.push_back (*i);
140                         break;
141                 default:
142                         /* we don't care */
143                         break;
144                 }
145         }
146
147         if (regs.size() == 1 && 
148             (ended.empty() || (ended.size() == 1 && ended.front() == regs.front()))) {
149
150                 /* just a single region - read directly into dst */
151
152                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Single region (%1) read, ended during this read %2\n", regs.front()->name(),
153                                                                     ended.size()));
154
155                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(regs.front());
156
157                 if (mr) {
158
159                         NoteTrackers::iterator t = _note_trackers.find (mr.get());
160                         MidiStateTracker* tracker;
161                         bool new_tracker = false;
162
163                         if (t == _note_trackers.end()) {
164                                 tracker = new MidiStateTracker;
165                                 new_tracker = true;
166                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tBEFORE: new tracker\n");
167                         } else {
168                                 tracker = t->second;
169                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tBEFORE: tracker says there are %1 on notes\n", tracker->on()));
170                         }
171
172                         mr->read_at (dst, start, dur, chan_n, _note_mode, tracker);
173                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tAFTER: tracker says there are %1 on notes\n", tracker->on()));
174
175                         if (!ended.empty()) {
176                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1 ended in this read, resolve notes and delete (%2) tracker\n",
177                                                                                     mr->name(), ((new_tracker) ? "new" : "old")));
178                                 tracker->resolve_notes (dst, mr->last_frame());
179                                 delete tracker;
180                                 if (!new_tracker) {
181                                         _note_trackers.erase (t);
182                                 }
183                         } else {
184                                 if (new_tracker) {
185                                         pair<Region*,MidiStateTracker*> newpair;
186                                         newpair.first = mr.get();
187                                         newpair.second = tracker;
188                                         _note_trackers.insert (newpair);
189                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
190                                 }
191                         }
192                 }
193
194         } else {
195
196                 /* multiple regions and/or note resolution: sort by layer, read into a temporary non-monotonically
197                    sorted EventSink, sort and then insert into dst.
198                 */
199
200                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("%1 regions to read, plus %2 trackers\n", regs.size(), tracker_info.size()));
201
202                 Evoral::EventList<framepos_t> evlist;
203
204                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("for %1 .. %2 we have %3 to consider\n", start, start+dur-1, regs.size()));
205
206                 for (vector<boost::shared_ptr<Region> >::iterator i = regs.begin(); i != regs.end(); ++i) {
207
208                         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*i);
209
210                         if (!mr) {
211                                 continue;
212                         }
213
214                         NoteTrackers::iterator t = _note_trackers.find (mr.get());
215                         MidiStateTracker* tracker;
216                         bool new_tracker = false;
217
218                         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()));
219
220                         if (t == _note_trackers.end()) {
221                                 tracker = new MidiStateTracker;
222                                 new_tracker = true;
223                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tBEFORE: new tracker\n");
224                         } else {
225                                 tracker = t->second;
226                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tBEFORE: tracker says there are %1 on notes\n", tracker->on()));
227                         }
228
229
230                         mr->read_at (evlist, start, dur, chan_n, _note_mode, tracker);
231
232 #ifndef NDEBUG
233                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("After %1 (%2 .. %3) we now have %4\n", mr->name(), mr->position(), mr->last_frame(), evlist.size()));
234                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
235                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
236                         }
237                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\tAFTER: tracker says there are %1 on notes\n", tracker->on()));
238 #endif
239                         if (find (ended.begin(), ended.end(), *i) != ended.end()) {
240
241                                 /* the region ended within the read range, so
242                                  * resolve any dangling notes (i.e. notes whose
243                                  * end is beyond the end of the region).
244                                  */
245                                 
246                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1 ended in this read, resolve notes and delete (%2) tracker\n",
247                                                                                     mr->name(), ((new_tracker) ? "new" : "old")));
248
249                                 tracker->resolve_notes (evlist, (*i)->last_frame());
250                                 delete tracker;
251                                 if (!new_tracker) {
252                                         _note_trackers.erase (t);
253                                 }
254
255                         } else {
256
257                                 if (new_tracker) {
258                                         _note_trackers.insert (make_pair (mr.get(), tracker));
259                                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "\tadded tracker to trackers\n");
260                                 }
261                         }
262                 }
263
264                 if (!evlist.empty()) {
265
266                         /* sort the event list */
267                         EventsSortByTimeAndType<framepos_t> cmp;
268                         evlist.sort (cmp);
269
270 #ifndef NDEBUG
271                         DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("Final we now have %1 events\n",  evlist.size()));
272                         for (Evoral::EventList<framepos_t>::iterator x = evlist.begin(); x != evlist.end(); ++x) {
273                                 DEBUG_TRACE (DEBUG::MidiPlaylistIO, string_compose ("\t%1\n", **x));
274                         }
275 #endif
276                         /* write into dst */
277                         for (Evoral::EventList<framepos_t>::iterator e = evlist.begin(); e != evlist.end(); ++e) {
278                                 Evoral::Event<framepos_t>* ev (*e);
279                                 dst.write (ev->time(), ev->event_type(), ev->size(), ev->buffer());
280                                 delete ev;
281                         }
282
283                 }
284         }
285
286         DEBUG_TRACE (DEBUG::MidiPlaylistIO, "-------------------------------------------------------------\n");
287         return dur;
288 }
289
290 void
291 MidiPlaylist::reset_note_trackers ()
292 {
293         Playlist::RegionWriteLock rl (this, false);
294
295         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
296                 delete n->second;
297         }
298         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 reset all note trackers\n", name()));
299         _note_trackers.clear ();
300 }
301
302 void
303 MidiPlaylist::resolve_note_trackers (Evoral::EventSink<framepos_t>& dst, framepos_t time)
304 {
305         Playlist::RegionWriteLock rl (this, false);
306
307         for (NoteTrackers::iterator n = _note_trackers.begin(); n != _note_trackers.end(); ++n) {
308                 n->second->resolve_notes(dst, time);
309                 delete n->second;
310         }
311         DEBUG_TRACE (DEBUG::MidiTrackers, string_compose ("%1 resolve all note trackers\n", name()));
312         _note_trackers.clear ();
313 }
314
315 void
316 MidiPlaylist::remove_dependents (boost::shared_ptr<Region> region)
317 {
318         /* MIDI regions have no dependents (crossfades) but we might be tracking notes */
319         NoteTrackers::iterator t = _note_trackers.find (region.get());
320
321         /* GACK! THREAD SAFETY! */
322
323         if (t != _note_trackers.end()) {
324                 delete t->second;
325                 _note_trackers.erase (t);
326         }
327 }
328
329 int
330 MidiPlaylist::set_state (const XMLNode& node, int version)
331 {
332         in_set_state++;
333         freeze ();
334
335         if (Playlist::set_state (node, version)) {
336                 return -1;
337         }
338
339         thaw();
340         in_set_state--;
341
342         return 0;
343 }
344
345 void
346 MidiPlaylist::dump () const
347 {
348         boost::shared_ptr<Region> r;
349
350         cerr << "Playlist \"" << _name << "\" " << endl
351         << regions.size() << " regions "
352         << endl;
353
354         for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
355                 r = *i;
356                 cerr << "  " << r->name() << " @ " << r << " ["
357                 << r->start() << "+" << r->length()
358                 << "] at "
359                 << r->position()
360                 << " on layer "
361                 << r->layer ()
362                 << endl;
363         }
364 }
365
366 bool
367 MidiPlaylist::destroy_region (boost::shared_ptr<Region> region)
368 {
369         boost::shared_ptr<MidiRegion> r = boost::dynamic_pointer_cast<MidiRegion> (region);
370
371         if (!r) {
372                 return false;
373         }
374
375         bool changed = false;
376
377         {
378                 RegionWriteLock rlock (this);
379                 RegionList::iterator i;
380                 RegionList::iterator tmp;
381
382                 for (i = regions.begin(); i != regions.end(); ) {
383
384                         tmp = i;
385                         ++tmp;
386
387                         if ((*i) == region) {
388                                 regions.erase (i);
389                                 changed = true;
390                         }
391
392                         i = tmp;
393                 }
394         }
395
396
397         if (changed) {
398                 /* overload this, it normally means "removed", not destroyed */
399                 notify_region_removed (region);
400         }
401
402         return changed;
403 }
404
405 set<Evoral::Parameter>
406 MidiPlaylist::contained_automation()
407 {
408         /* this function is never called from a realtime thread, so
409            its OK to block (for short intervals).
410         */
411
412         Playlist::RegionReadLock rl (this);
413         set<Evoral::Parameter> ret;
414
415         for (RegionList::const_iterator r = regions.begin(); r != regions.end(); ++r) {
416                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(*r);
417
418                 for (Automatable::Controls::iterator c = mr->model()->controls().begin();
419                                 c != mr->model()->controls().end(); ++c) {
420                         ret.insert(c->first);
421                 }
422         }
423
424         return ret;
425 }
426
427
428 bool
429 MidiPlaylist::region_changed (const PBD::PropertyChange& what_changed, boost::shared_ptr<Region> region)
430 {
431         if (in_flush || in_set_state) {
432                 return false;
433         }
434
435         PBD::PropertyChange our_interests;
436         our_interests.add (Properties::midi_data);
437
438         bool parent_wants_notify = Playlist::region_changed (what_changed, region);
439
440         if (parent_wants_notify || what_changed.contains (our_interests)) {
441                 notify_contents_changed ();
442         }
443
444         return true;
445 }
446